Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
215 changes: 215 additions & 0 deletions ds-bot/src/host/card-gate.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,215 @@
// The card gate: decisions follow the job back to the Bot that sent it.
//
// A job a Bot sends another Bot runs in a hidden turn: the user does not watch it.
// A question card or a plan review raised there lands in the sub-agent's own chat,
// away from the conversation the user started the job in, so the gate refuses it
// and sends the decision back to the sender (the manager) instead. The manager
// cards the user and relays the answer; a plan approval relayed by a Main Bot with
// PLAN-APPROVED turns the sub-agent's plan mode off with no card.
//
// What stays open: a Main Bot's own cards, every turn the user typed, a request
// whose audience is the user, a card whose option is the production approval
// (the production guard only reads the transcript of the Bot that runs the
// command), and a job whose text carries CARD-IT-YOURSELF.
//
// DSH_CARD_GATE=off turns all of it off.

import { readFileSync } from 'node:fs'
import { appendFile, mkdir } from 'node:fs/promises'
import { dirname, join } from 'node:path'

export const CARD_IT_YOURSELF = 'CARD-IT-YOURSELF'
export const PLAN_APPROVED = 'PLAN-APPROVED'
export const EXIT_PLAN_MODE = 'exit_plan_mode'
const PRODUCTION_LABEL = /^deploy to production( \(Recommended\))?$/i
const TITLE_MAX = 200

export const gateOn = (env = process.env) => String(env.DSH_CARD_GATE ?? '').trim().toLowerCase() !== 'off'

export const isProductionLabel = label => PRODUCTION_LABEL.test(String(label ?? '').trim())

const clip = text => {
const value = String(text ?? '').replace(/\s+/g, ' ').trim()
return value.length > TITLE_MAX ? `${value.slice(0, TITLE_MAX - 3)}...` : value
}

/** The plan's first markdown heading, or its first line. */
export const planTitle = (plan) => {
for (const line of String(plan ?? '').split('\n')) {
const match = /^#{1,6}\s+(.+?)\s*$/.exec(line)
if (match) return clip(match[1])
}
return clip(String(plan ?? '').split('\n').find(line => line.trim() !== '') ?? '')
}

// Who sent the job a trigger carries: its Bot's name, else the name on the message.
const senderOf = (rt, info) => rt.botOf?.(info?.senderSessionId)?.name ?? info?.senderName ?? 'the Bot that sent this job'

/**
* The gate's view of the turn running in a Session: undefined when the turn is not
* one a Bot opened (no gate), else who runs it, who sent it, and whether it may card.
*/
export function gatedTurn(rt, sessionId) {
if (!gateOn()) return undefined
const { state } = rt
const entry = rt.live?.get(sessionId)
const turn = entry?.turn
if (turn === undefined || !(state.exchangeTurns?.[sessionId] ?? []).includes(turn)) return undefined
const botId = rt.chatOwners?.get(sessionId)
if (botId === undefined || rt.isMain?.(botId)) return undefined
const info = entry.info
// A request the user sees answered here is the user's turn as much as the Bot's.
if (info?.audience === 'user') return undefined
const triggers = [{ info, text: entry.infoText }, ...(entry.joined ?? [])]
const texts = triggers.flatMap(({ info: item, text }) => {
const record = (state.exchanges ?? []).find(other => other.id === item?.exchangeId)
return [text, record?.text].filter(value => typeof value === 'string')
Comment on lines +64 to +66

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve card-routing markers when messages become attachments

For jobs longer than MESSAGE_INLINE_MAX (20,000 characters), tools.js passes the result of attachLong to delivery: only the first 1,000 characters remain inline, and the rest becomes an attachment. Both strings inspected here then contain only that shortened representation, so a CARD-IT-YOURSELF instruction later in the job is silently ignored and the explicitly delegated question or plan review is refused. Preserve the routing flag from the original message before truncation, or inspect the complete attached job rather than only its preview.

Useful? React with 👍 / 👎.

})
return {
bot: rt.botOf?.(botId)?.name ?? botId,
manager: senderOf(rt, info),
cardItYourself: texts.some(text => text.includes(CARD_IT_YOURSELF)),
}
}

export const cardRefusal = manager => `This job came from ${manager}. Do not card Steve: end your turn with a DECISION block for ${manager} (question, 2 to 4 options, the recommended one marked with its reason, Hold). ${manager} cards Steve and relays his answer.`

export const planRefusal = manager => `This job came from ${manager}. Do not open a plan review for Steve here: send the full plan to ${manager} as a DECISION (Approve plan (Recommended) / Change it / Hold). When ${manager} relays approval with ${PLAN_APPROVED}, plan mode turns off for you.`

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Route plan approvals through a manager authorized to apply them

When a non-Main Bot delegates to another non-Main Bot, the recipient's plan review is blocked and this refusal promises that its manager can relay PLAN-APPROVED. However, relayPlanApproval explicitly ignores approvals from non-Main Bots. The unrestricted chat delegation path in tools.js permits this scenario, so following the refusal's instructions leaves the recipient in plan mode even after the manager obtains user approval. Route the decision through a Main Bot, or provide an authorized approval path for the actual manager.

Useful? React with 👍 / 👎.


/** Whether ask_user in this Session is refused; the refusal text, or undefined. */
export function refuseCard(rt, sessionId, options) {
const gated = gatedTurn(rt, sessionId)
if (gated === undefined || gated.cardItYourself) return undefined
if ((options ?? []).some(option => isProductionLabel(option?.label))) return undefined
return { ...gated, text: cardRefusal(gated.manager) }
}

/** Whether exit_plan_mode in this Session is refused; the refusal text, or undefined. */
export function refusePlan(rt, sessionId) {
const gated = gatedTurn(rt, sessionId)
if (gated === undefined || gated.cardItYourself) return undefined
return { ...gated, text: planRefusal(gated.manager) }
}

/** One JSON line in <home>/logs/card-gate.log. Only names, the tool and a title. */
export function logGate(rt, entry) {
if (typeof rt.home !== 'string') return Promise.resolve()
const path = join(rt.home, 'logs', 'card-gate.log')
const line = JSON.stringify({ time: new Date().toISOString(), ...entry, ...(entry.title !== undefined ? { title: clip(rt.redactSecrets?.(entry.title) ?? entry.title) } : {}) })
return mkdir(dirname(path), { recursive: true })
.then(() => appendFile(path, `${line}\n`, 'utf8'))
.catch(error => rt.warn?.('ds-bot: card gate log not written: %s', error?.code ?? error))
}

// A job a Main Bot hands out opens with this line; it carries the manager's
// approval to start, so the Bot it reaches is not left waiting in plan mode.
export const ORDER_PREFIX = /^ORDER from .+? · job /
export const orderReleaseOn = (env = process.env) => String(env.DSH_ORDER_RELEASE ?? '').trim().toLowerCase() !== 'off'

/** Which release a message carries: 'plan-approved', 'order', or undefined. */
export function releaseKind(text, env = process.env) {
const value = String(text ?? '')
if (value.includes(PLAN_APPROVED)) return 'plan-approved'
if (orderReleaseOn(env) && ORDER_PREFIX.test(value.trimStart())) return 'order'
return undefined
}

/**
* A Main Bot's message that relays a plan approval (PLAN-APPROVED), or hands out a
* job (an ORDER line), turns plan mode off in the Session it reaches, whether that
* Bot is a Main Bot or not: at once between turns, from the next step inside one.
* Every attempt is logged with its outcome, so a release that did nothing says why.
* Returns what planMode.set said, or undefined when nothing was done.
*/
export function relayPlanApproval(rt, { fromId, toId, agent, text }) {
if (!gateOn()) return undefined
const kind = releaseKind(text)
if (kind === undefined) return undefined
const log = (outcome) => {
void logGate(rt, { bot: rt.botOf?.(toId)?.name ?? toId, manager: rt.botOf?.(fromId)?.name ?? fromId ?? 'unknown', tool: kind, outcome })
}
if (fromId !== undefined && fromId === toId) { log('self'); return undefined }
if (fromId === undefined || !rt.isMain?.(fromId)) { log('sender-not-main'); return undefined }
const planMode = planModeFor(rt, agent)
if (planMode === undefined || agent === undefined) { log('no-plan-service'); return undefined }
let outcome
try {
const now = planMode.get(agent)
if (!(now.pending ?? now.active)) { log('not-in-plan-mode'); return undefined }
outcome = planMode.set(agent, false)
} catch (error) {
rt.warn?.('ds-bot: relayed plan approval not applied: %s', error)
log('error')
return undefined
}
log(outcome)
return outcome
}

/**
* The plan-mode service that serves this agent. Under an agent preset, plan mode
* lives in the preset's isolated group (`isolate: planMode: true`), so a Host-realm
* `ctx.get('planMode')` finds nothing: the preset composition is read first.
*/
export function planModeFor(rt, agent) {
if (agent === undefined) return undefined
return rt.ctx?.get?.('agentPresets')?.serviceFor?.(agent, 'planMode') ?? rt.ctx?.get?.('planMode')
}

/**
* Bots that keep plan mode on, by name: <home>/plan-mode-keep.json, a JSON array of
* names. Read on each call (it is tiny), so an edit needs no restart.
*/
export function keepsPlanMode(rt, name) {
if (typeof rt.home !== 'string' || typeof name !== 'string') return false
try {
const list = JSON.parse(readFileSync(join(rt.home, 'plan-mode-keep.json'), 'utf8'))
return Array.isArray(list) && list.some(item => String(item).trim().toLowerCase() === name.trim().toLowerCase())
} catch {
return false
}
}

export const planDefaultOffOn = (env = process.env) => String(env.DSH_PLAN_DEFAULT_OFF ?? '').trim().toLowerCase() !== 'off'

/**
* A Bot Session does not start in plan mode: DSH's shipped presets pin it on for
* every new Session (`defaultActive: true`), and Steve's rule is off by default.
* Each Session is switched off once, recorded in `state.planDefaultOff`, so a later
* /plan in that chat is the user's choice and stays on. A Bot with
* `planMode: 'on'` is left alone. Returns the outcome, or undefined.
*/
export function ensurePlanOff(rt, agent, why, { fresh = false } = {}) {
if (!planDefaultOffOn()) return undefined
const sessionId = agent?.session?.id ?? agent?.id
if (sessionId === undefined) return undefined
// A Session DS Bot has just made for a Bot is not yet in the owner tables.
const botId = rt.selfOf?.(sessionId)
if (botId === undefined && !fresh) return undefined
const done = rt.state?.planDefaultOff ?? (rt.state === undefined ? undefined : (rt.state.planDefaultOff = {}))
if (done === undefined || done[sessionId] !== undefined) return undefined
const bot = rt.botOf?.(botId)
const log = (outcome) => { void logGate(rt, { bot: bot?.name ?? botId ?? sessionId, tool: 'plan-default-off', why, outcome }) }
if (bot?.planMode === 'on' || keepsPlanMode(rt, bot?.name)) { done[sessionId] = 'kept'; log('kept-bot-opt-in'); void rt.save?.().catch?.(() => {}); return 'kept' }
const planMode = planModeFor(rt, agent)
if (planMode === undefined) { log('no-plan-service'); return undefined }
let outcome
try {
const now = planMode.get(agent)
outcome = (now.pending ?? now.active) ? planMode.set(agent, false) : 'already-off'
} catch (error) {
rt.warn?.('ds-bot: plan default-off not applied: %s', error)
log('error')
return undefined
}
done[sessionId] = outcome
void rt.save?.().catch?.(() => {})
log(outcome)
return outcome
}

/** One line at start-up, so the log proves this code is the code that is running. */
export function announceGate(rt) {
if (!gateOn()) return Promise.resolve()
return logGate(rt, { tool: 'gate-loaded', release: 'plan-approved+order', orderRelease: orderReleaseOn(), planDefaultOff: planDefaultOffOn(), lookup: 'agentPresets.serviceFor' })
}
7 changes: 7 additions & 0 deletions ds-bot/src/host/delivery.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
// Delivery: how one Bot, the user, or DS Bot itself puts a message into a Bot Session.
import { randomUUID } from 'node:crypto'
import { createUserMessage } from '@deepseek-ai/dsh-llm'
import { announceGate, ensurePlanOff, relayPlanApproval } from './card-gate.js'
import { HISTORY_TIMEOUT_MS, LONG_HEAD, MESSAGE_INLINE_MAX, READ_LINE_MAX, SOURCE_KIND, TEXT_KEPT, TEXT_SHOW_MAX } from './constants.js'
import { headOf, textOf } from './text.js'

export function install(rt) {
const { ctx, state } = rt
// The card gate says once that it is loaded, so its log proves which code runs.
void announceGate(rt)

const resolveAgent = async (sessionId) => {
const resolved = await ctx.sessionController.resolveAgent(sessionId)
Expand Down Expand Up @@ -96,6 +99,10 @@ export function install(rt) {
],
source,
})
// A Main Bot relaying a plan approval takes the Bot out of plan mode, before the
// message that carries it is read (card-gate.js).
ensurePlanOff(rt, agent, 'delivery')
relayPlanApproval(rt, { fromId, toId, agent, text })
if (steer) agent.steer(message)
else agent.followup(message)
Comment on lines +105 to 107

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Apply relayed approval when its message is consumed

If a Main Bot sends an approval with send_message(..., when: 'queue') while the recipient is working, this call changes plan mode before the approval message is queued with agent.followup. The current turn can therefore leave plan mode even though the approval belongs to work it will only read after that turn finishes; a pending mode change at the next step does not preserve the queue boundary either. Apply the approval when the corresponding message is consumed, so queued approvals cannot change the permissions of the currently running task.

Useful? React with 👍 / 👎.

await ctx.sessions.flush(agent.session)
Expand Down
7 changes: 6 additions & 1 deletion ds-bot/src/host/parts.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import { randomUUID } from 'node:crypto'
import { BlockAssembler, createUserMessage } from '@deepseek-ai/dsh-llm'
import { openTurnAt } from './btw.js'
import { ensurePlanOff } from './card-gate.js'
import { HANDOFF_ACK, HISTORY_TIMEOUT_MS, REPLY_KIND, SOURCE_KIND } from './constants.js'
import { parseReplies, stackReplies } from '../shared/group-replies.js'
import { CHECKPOINT_PROMPT, STEWARD_SYSTEM, checkpointCount, checkpointTail, checkpointTailNote, checkpointText, linesFor, parseDecision, stewardRequest } from './steward.js'
Expand Down Expand Up @@ -317,7 +318,11 @@ export function install(rt) {
}
adoptedEngines.clear()
}, 'ds-bot: Bot compaction')
ctx.on('agent/created', ({ agent }) => { adoptCompaction(agent) })
ctx.on('agent/created', ({ agent }) => {
adoptCompaction(agent)
// A Bot Session resumed after a restart leaves the plan mode DSH pinned on it, once.
ensurePlanOff(rt, agent, 'resumed')
})

// A Bot's own chat, or its Session in one group, or the group's own Session
// (`botId === undefined`), as numbered parts, oldest first; the last one is
Expand Down
3 changes: 3 additions & 0 deletions ds-bot/src/host/roster.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { mkdir } from 'node:fs/promises'
import { MAX_AVATAR_IMAGE, ROOM_MAX_MEMBERS, ROOM_MODES, ROOM_NAME_MAX, ROOM_NOTICE_MAX } from './constants.js'
import { currentColor, isColor, normalize, unquote } from './text.js'
import { nameProblem } from '../shared/mentions.js'
import { ensurePlanOff } from './card-gate.js'

const BROWSER_GRANT_KINDS = new Set(['post', 'upload', 'download', 'delete', '*'])
const HOSTNAME = /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)(?:\.(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?))*$/
Expand Down Expand Up @@ -89,6 +90,8 @@ export function install(rt) {
const { sessionId } = await ctx.sessionController.create({ ...place, ...await botPreset() })
const agent = await rt.resolveAgent(sessionId)
await ctx.sessionTitle.rename(agent.session, title)
// DSH's presets pin plan mode on for every new Session; a Bot's starts off (card-gate.js).
ensurePlanOff(rt, agent, 'new-session', { fresh: true })
return sessionId
}

Expand Down
14 changes: 14 additions & 0 deletions ds-bot/src/host/tools.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import { randomUUID } from 'node:crypto'
import { defineTool } from '@deepseek-ai/dsh-tools'
import { readAvatar } from './avatar.js'
import { EXIT_PLAN_MODE, logGate, planTitle, refuseCard, refusePlan } from './card-gate.js'
import { COLORS, EXTRA_COLORS, MESSAGE_INLINE_MAX, ROOM_MODES, SOURCE_KIND } from './constants.js'
import { within } from './folders.js'
import { absoluteLinks } from './links.js'
Expand Down Expand Up @@ -680,6 +681,12 @@ export function install(rt) {
.filter(option => option.label !== '')
.slice(0, 6)
if (options.length === 0) return 'Give at least one option.'
// A job another Bot sent is decided by that Bot, in its own chat (card-gate.js).
const refused = refuseCard(rt, id, options)
if (refused !== undefined) {
void logGate(rt, { bot: refused.bot, manager: refused.manager, tool: 'ask_user', title: String(args.question ?? '') })
return refused.text
}
// A hidden Bot-to-Bot turn shows none of its calls, so its card goes to the
// composer dock, which takes questions without a call.
const turn = rt.live.get(id)?.turn
Expand Down Expand Up @@ -927,6 +934,13 @@ Reason: ${why}` : ''}`
ctx.tools.guard((exec) => {
if (!rt.isBotSession(exec.agent?.id)) return undefined
if (exec.name === BLOCKING_QUESTION_TOOL) return `Bots cannot use ${BLOCKING_QUESTION_TOOL}. Ask with ask_user in your own chat, or ask in your reply.`
if (exec.name === EXIT_PLAN_MODE) {
// A plan for a job another Bot sent is approved through that Bot (card-gate.js).
const refused = refusePlan(rt, exec.agent?.id)
if (refused === undefined) return undefined
void logGate(rt, { bot: refused.bot, manager: refused.manager, tool: EXIT_PLAN_MODE, title: planTitle(exec.arguments?.plan) })
return refused.text
}
return DELEGATION_TOOLS.includes(exec.name) ? DELEGATION_REFUSAL : undefined
})
// Creation waits for this listener, so the Agent's first step already lacks the tool.
Expand Down
8 changes: 5 additions & 3 deletions ds-bot/src/host/turns.js
Original file line number Diff line number Diff line change
Expand Up @@ -369,8 +369,10 @@ export function install(rt) {

// A group Session is hidden as a whole, so its turns need no marking. A handoff
// package that only opens a part is acknowledged with a fixed line, also hidden.
const claimTrigger = (sessionId, entry, info) => {
const claimTrigger = (sessionId, entry, info, text) => {
entry.info = info
// The trigger's text without its header line, for the card gate (card-gate.js).
entry.infoText = typeof text === 'string' ? text : undefined
// A turn that was stopped for a part switch brings its joined requests along.
if (Array.isArray(info.joined) && info.joined.length > 0) {
entry.joined = info.joined.filter(item => item?.info !== undefined && item.info !== null)
Expand Down Expand Up @@ -599,7 +601,7 @@ export function install(rt) {
if (entry.pending !== undefined) {
claimedPending = entry.pending
claimedPendingText = entry.pendingText
claimTrigger(id, entry, claimedPending)
claimTrigger(id, entry, claimedPending, claimedPendingText)
entry.pending = undefined
entry.pendingText = undefined
}
Expand Down Expand Up @@ -696,7 +698,7 @@ export function install(rt) {
entry.pending = source
entry.pendingText = textOf(event.data.content).replace(/^\[(?:[^\r\n]*\]\r?\n|[^\]\r\n]*\])/, '')
}
else if (!opened) claimTrigger(id, entry, source)
else if (!opened) claimTrigger(id, entry, source, textOf(event.data.content).replace(/^\[(?:[^\r\n]*\]\r?\n|[^\]\r\n]*\])/, ''))
else if (source.work !== undefined && source.work !== rt.workOf?.(entry.info) && !expectsReply(source)) {
// A result for other work than this turn's informs it, and comes back in a
// turn of its own once this one ends, which goes on with that work.
Expand Down
Loading
Loading