index.ts 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679
  1. /**
  2. * The model-facing bash tools: `bash`, `bash_output`, `bash_kill`. Pure
  3. * schema + text shaping — every process concern lives behind the `ctx.bash`
  4. * executor seam (`@deepseek-ai/dsh-bash`), so sandbox/permission/remote
  5. * executor implementations swap in without touching what the model sees.
  6. *
  7. * Background notifications: when a background task completes, a short notice
  8. * is injected into the owning agent's session (`agent.inject()` — the
  9. * documented context seam). Injection is durable context for the NEXT model
  10. * request, not a wake-up: an idle agent stays idle until something sends a
  11. * message, which is why the tool descriptions tell the model to poll with
  12. * `bash_output`.
  13. *
  14. * Task ownership: a background task's OWNER is an opaque token — the owning
  15. * agent's `session.header.id` — passed to the executor at spawn
  16. * (`resolve({ …, owner })`) and stored ON THE TASK inside the executor
  17. * (`@deepseek-ai/dsh-bash`'s `ownerOf(id)` seam), NOT in a plugin-local map.
  18. * `bash_output`/`bash_kill` compare `ctx.bash.ownerOf(id)` to the caller's token
  19. * and reject a task owned by a DIFFERENT session (`owner !== undefined && owner
  20. * !== caller`); an unowned task (no token — started by a non-agent caller) is
  21. * open to anyone. Task ids are global and predictable (`bash-1`, …); under
  22. * multi-session ACP (RFC 011) this token check is the fence that stops one
  23. * session's agent from reading or killing another session's background task.
  24. *
  25. * Storing the token on the task in the EXECUTOR (disposed with the `dsh-bash`
  26. * fiber), rather than in this plugin, is what makes ownership survive a
  27. * `tool-bash` HMR reload — a reload that reset a plugin-local map would orphan
  28. * a task spawned before it. (The `onTaskDone` listener is still effect-scoped
  29. * to this plugin's `apply`, so a
  30. * completion landing during the reload gap still drops its one notice — the
  31. * pre-existing reload-gap drop — but the ownership fence itself is HMR-proof.)
  32. *
  33. * Commands run with the executor's full authority unless a sandboxing
  34. * executor (`@deepseek-ai/dsh-bash-sandbox`) confines them; per-call
  35. * allow/deny/ask policy is the `tools/pre-execute` waterfall — see
  36. * docs/architecture.md § Extension And Composition. Under a sandboxing
  37. * executor this plugin also advertises the ESCALATION surface
  38. * (`sandbox_permissions`/`justification` — the sandbox RFC § Escalation,
  39. * docs/rfc/implemented/feature/2026-07-06-sandbox.md): a command the
  40. * sandbox denied may be retried once under a strictly wider mode, resolved
  41. * through `ctx.approval` BEFORE anything executes and failing closed on every
  42. * unanswerable path. The fields exist only when the mounted executor reports
  43. * a confining default (`ctx.bash.sandboxMode`) — a lever is never advertised
  44. * that the composition cannot honor.
  45. *
  46. * Per-session mode switching (the sandbox RFC § Per-session mode switching): a session may carry a
  47. * standing sandbox-mode override — the `bash/sandbox-mode` event fold from
  48. * `@deepseek-ai/dsh-bash` — which this plugin makes real at EXECUTION: each
  49. * call is stamped `escalation grant > session override > executor default`.
  50. * The prompt deliberately does NOT state the mode and no switch is narrated:
  51. * the model learns the boundary from the denial marker (which names the mode
  52. * it ran under) exactly when it matters, instead of preemptively refusing
  53. * work a standing declaration would discourage.
  54. *
  55. * @module @deepseek-ai/dsh-tool-bash
  56. */
  57. import type { Context } from 'cordis'
  58. import { isAbsolute, resolve as resolvePath } from 'node:path'
  59. import { defineTool } from '@deepseek-ai/dsh-tools'
  60. import type { GenericCallView, TerminalCallView, ToolExecution, ToolResult, ToolResultView } from '@deepseek-ai/dsh-tools'
  61. import type { Agent } from '@deepseek-ai/dsh-agent'
  62. import { assertNever } from '@deepseek-ai/dsh-llm'
  63. import type {} from '@deepseek-ai/dsh-system-prompt'
  64. // Side-effect type import: declaration-merges `ctx.approval`, consumed
  65. // opportunistically by the escalation gate (`ctx.get('approval')` — the seam
  66. // stays optional at runtime, same pattern as dsh-tools' ask routing).
  67. import type {} from '@deepseek-ai/dsh-user-approval'
  68. import type { SandboxMode } from '@deepseek-ai/dsh-sandbox'
  69. import { BashTaskId, OwnerToken, effectiveSandboxMode } from '@deepseek-ai/dsh-bash'
  70. import type { BashRunResult, BashTask, CollectedOutput } from '@deepseek-ai/dsh-bash'
  71. export const name = 'tool-bash'
  72. export const inject = ['tools', 'bash', 'systemPrompt']
  73. /**
  74. * Validate the constraints the SchemaSpec can't express. `defineTool` now
  75. * validates parsed args against the SchemaSpec before `execute` runs (the
  76. * arg-validation RFC), so type/required/enum checks are already done and `args`
  77. * is the validated `InferArgs` shape here. What remains are value constraints
  78. * the DSL has no vocabulary for: non-empty strings, a positive finite timeout,
  79. * and the escalation pairing (`sandbox_permissions` and `justification` travel
  80. * together — an approval prompt without a reason, or a reason driving nothing,
  81. * is a malformed ask).
  82. */
  83. function validateBashArgs(args: BashToolArgs): void {
  84. if (args.command.trim().length === 0) {
  85. throw new Error('invalid command: expected a non-empty string')
  86. }
  87. if (args.description.trim().length === 0) {
  88. throw new Error('invalid description: expected a non-empty string')
  89. }
  90. if (args.timeoutMs !== undefined && (!Number.isFinite(args.timeoutMs) || args.timeoutMs <= 0)) {
  91. throw new Error(`invalid timeoutMs: expected a positive number, got ${JSON.stringify(args.timeoutMs)}`)
  92. }
  93. if (args.sandbox_permissions !== undefined && args.justification === undefined) {
  94. throw new Error('invalid escalation: sandbox_permissions requires a justification')
  95. }
  96. if (args.justification !== undefined && args.sandbox_permissions === undefined) {
  97. throw new Error('invalid escalation: justification is only valid together with sandbox_permissions')
  98. }
  99. if (args.justification !== undefined && args.justification.trim().length === 0) {
  100. throw new Error('invalid justification: expected a non-empty sentence')
  101. }
  102. }
  103. /**
  104. * Reject an empty `task_id`. Type and presence are guaranteed by the
  105. * SchemaSpec validation (the arg-validation RFC); only the non-empty constraint, which the
  106. * DSL can't express, is left to check here.
  107. */
  108. function validateTaskId(value: string): BashTaskId {
  109. if (value.length === 0) {
  110. throw new Error(`invalid task_id: expected a string, got ${JSON.stringify(value)}`)
  111. }
  112. return BashTaskId(value)
  113. }
  114. /**
  115. * The bash tool's validated argument shape — the base parameters plus the two
  116. * escalation fields, which are ADVERTISED only when the mounted executor
  117. * reports a confining default mode (absent from the schema otherwise, so the
  118. * SchemaSpec validator rejects them before `execute` ever sees one).
  119. */
  120. interface BashToolArgs {
  121. command: string
  122. description: string
  123. timeoutMs?: number
  124. workdir?: string
  125. run_in_background?: boolean
  126. sandbox_permissions?: string
  127. justification?: string
  128. }
  129. /**
  130. * The strictly-wider table: what a call whose effective mode is the key may
  131. * escalate TO. Checked at EXECUTION, never baked into the schema — the
  132. * schema's enum is {@link ESCALATION_TARGETS}, because schemas are
  133. * registry-global while the effective mode is per-call truth.
  134. */
  135. const WIDER_MODES: Record<string, readonly SandboxMode[]> = {
  136. 'read-only': ['workspace-write', 'danger-full-access'],
  137. 'workspace-write': ['danger-full-access'],
  138. }
  139. /**
  140. * The closed escalation-target vocabulary — every mode a call could ever
  141. * escalate TO (`read-only` is the floor; nothing escalates to it). Advertised
  142. * whenever the mounted executor confines: cutting the enum down to the modes
  143. * wider than the executor's DEFAULT would strand a session whose effective
  144. * mode sits below it (a `danger-full-access` default would advertise nothing
  145. * while a narrower-switched session stays confined with no lever).
  146. */
  147. const ESCALATION_TARGETS: readonly SandboxMode[] = ['workspace-write', 'danger-full-access']
  148. /**
  149. * The bash tool's static description. The base text is byte-stable regardless
  150. * of composition (it is part of the pinned snapshot header); the escalation
  151. * teaching rides only when the mounted executor actually honors the fields —
  152. * it names the ONE sanctioned exception to the base text's "do not retry
  153. * another way" rule. Its deference clause ("If the session states approval
  154. * prompts are disabled…") points at the approval plugin's never-policy prompt
  155. * sentence by meaning, not by parsed wording — a rendezvous kept working by
  156. * that sentence continuing to open with the approvals-disabled claim.
  157. */
  158. function bashDescription(escalationModes: readonly SandboxMode[]): string {
  159. const base = 'Execute a bash command (`bash -c`) and return its stdout/stderr. '
  160. + 'Each call runs in a fresh shell: no state (cwd, variables, functions) persists between calls — '
  161. + 'pass `workdir` instead of using `cd`. Non-zero exits are reported as `[exit code: N]`. '
  162. + 'Commands may run under a file sandbox; a blocked file operation is reported as `[sandbox: file access denied under <mode> mode]` — a policy denial, not a bug in the command; do not retry another way (a background task reports the same marker via bash_output once it has finished). '
  163. + 'Long output is truncated to its tail; the full output is saved to a file whose path is reported when available. '
  164. + 'Set `run_in_background: true` for long-running commands: the call returns a task id immediately; '
  165. + 'poll it with `bash_output` and stop it with `bash_kill`.'
  166. if (escalationModes.length === 0) return base
  167. return base + ' Attempting a command the sandbox may deny is safe and expected: run it and read the '
  168. + 'marker rather than assuming the denial. When a command IS denied and a wider mode would let it '
  169. + 'succeed, escalate immediately in the SAME turn — the ONE sanctioned exception to a denial: retry '
  170. + 'the exact same command once with `sandbox_permissions` (the narrowest wider mode that suffices) '
  171. + 'plus a one-sentence `justification`. Do not detour through chat to ask permission first — the '
  172. + 'approval prompt raised by that retry IS how the user consents. If the session states approval '
  173. + 'prompts are disabled, there is no exception: a denial is final — do not set `sandbox_permissions`. '
  174. + 'Never escalate speculatively: ground the request in a real denial — normally the one THIS command '
  175. + 'just hit; escalating up front is fine only when this session already denied the same access. '
  176. + 'A rejected escalation is final for THAT command — stop and explain, never work around '
  177. + 'it — but it does not forbid attempting or escalating other commands later.'
  178. }
  179. /** Append the truncation notice (with the full-output spill path) to a stream's text. */
  180. function streamText(output: CollectedOutput): string {
  181. if (!output.truncated) return output.text
  182. return `${output.text}\n[output truncated; full output: ${output.spillPath ?? '(unavailable)'}]`
  183. }
  184. /**
  185. * Shape one finished run into the text the model sees: stdout, then a marked
  186. * stderr section, then exit-status markers. Non-zero exits are REPORTED, not
  187. * errored — the model decides how to react; only infrastructure failures
  188. * (spawn errors, aborts) surface as isError results.
  189. * @param result - the completed foreground run from the executor.
  190. * @param escalationModes - the escalation targets this composition advertises;
  191. * non-empty adds the same-turn escalation hint after a denial marker
  192. * (default `[]`: no hint).
  193. * @returns the model-facing text: output body (or `(no output)`), then any timeout/signal/exit markers, each on its own line.
  194. */
  195. export function renderResult(
  196. result: BashRunResult,
  197. escalationModes: readonly SandboxMode[] = [],
  198. ): string {
  199. const out = streamText(result.stdout)
  200. const err = streamText(result.stderr)
  201. let body = out
  202. if (err.length > 0) {
  203. // Single newline between sections (stdout usually ends with one already).
  204. if (body.length > 0 && !body.endsWith('\n')) body += '\n'
  205. body += `[stderr]\n${err}`
  206. }
  207. if (body.length === 0) body = '(no output)'
  208. const markers: string[] = []
  209. // The sandbox marker precedes the exit-status markers so `[exit code: N]`
  210. // stays the LAST line (exitStatus() anchors its parse there). Denial is a
  211. // reported fact like timeout: the model decides how to react.
  212. if (result.sandbox?.denied) {
  213. markers.push(`[sandbox: file access denied under ${result.sandbox.mode} mode]`)
  214. // The same-turn nudge lives at the decision point: only when this
  215. // composition advertises the fields (a lever is never hinted that the
  216. // schema does not offer), and inside the sandbox marker family so the
  217. // exit-code marker stays the last line.
  218. if (escalationModes.length > 0) {
  219. markers.push('[sandbox: escalation available — retry this exact command once with sandbox_permissions (the narrowest wider mode that suffices) + justification; the approval prompt asks the user]')
  220. }
  221. }
  222. // Timeout is reported independently of how the process actually ended: a
  223. // command can trap SIGTERM and exit 0 after our timer fired (e.g.
  224. // `trap "exit 0" TERM; sleep 60`), giving timedOut:true / exitCode:0 /
  225. // signal:null — the model must still see that the command was cut short.
  226. if (result.timedOut) markers.push(`[timed out after ${result.timeoutMs}ms]`)
  227. if (result.signal !== null) {
  228. markers.push(`[killed by signal: ${result.signal}]`)
  229. } else if (result.exitCode !== 0) {
  230. markers.push(`[exit code: ${result.exitCode}]`)
  231. }
  232. if (markers.length === 0) return body
  233. if (!body.endsWith('\n')) body += '\n'
  234. return body + markers.join('\n')
  235. }
  236. // ---------------------------------------------------------------------------
  237. // UI presentation (tool-owned). These shape how a UI (e.g. the ACP bridge)
  238. // renders a bash call's pending and completed states. They are display-only and
  239. // pure — a UI may call them during live streaming AND a session-log replay.
  240. // ---------------------------------------------------------------------------
  241. /**
  242. * Pending-state presentation for a `bash` call. The TITLE is the exact `command`
  243. * — a `kind: 'execute'` card is rendered as a terminal whose header label IS the
  244. * title, and an execute-kind card HIDES `rawInput` (Zed: `should_show_raw_input
  245. * = !is_terminal_tool`), so the command must BE the title to be seen. This
  246. * mirrors the reference ACP adapters (claude-agent-acp, codex-acp), which both
  247. * use the bare command as an execute tool's title. The model-written
  248. * `description` (a readable summary) rides as a `content` text block shown ABOVE
  249. * the card. (Note: claude-agent-acp DROPS the description in terminal mode and
  250. * shows only the card; surfacing it as a content block is a deliberate
  251. * divergence here — we keep the human summary visible alongside the card.)
  252. * `rawInput` still carries the bare command for non-execute UIs that DO render it.
  253. *
  254. * `terminal` marks the call so a capable UI renders a TERMINAL card — but ONLY a
  255. * FOREGROUND run is a terminal: a `run_in_background` call returns a task id
  256. * immediately (it never streams a terminal; its output is polled via
  257. * `bash_output`), so it is NOT marked terminal and renders as an ordinary
  258. * execute card. For a foreground run the `terminal.cwd` (header) is the model
  259. * `workdir` when given — ABSOLUTE as-is, RELATIVE for the UI bridge to resolve
  260. * against the session cwd; when omitted the bridge fills the session workspace
  261. * cwd (this PURE presenter, args only, can't see it).
  262. */
  263. type BashCallArgs = { command: string; description: string; workdir?: string; run_in_background?: boolean }
  264. function presentBashCall(args: BashCallArgs): GenericCallView | TerminalCallView {
  265. // A background start is not an interactive terminal — a generic execute card
  266. // with the command as rawInput and the description as a content block.
  267. if (args.run_in_background === true) {
  268. return {
  269. card: 'generic',
  270. title: args.command,
  271. kind: 'execute',
  272. rawInput: args.command,
  273. content: [{ type: 'text', text: args.description }],
  274. }
  275. }
  276. // A foreground run IS a terminal: the command titles the card, the description
  277. // renders above it, and the cwd (when the model gave a workdir) heads it.
  278. return {
  279. card: 'terminal',
  280. title: args.command,
  281. description: args.description,
  282. ...args.workdir !== undefined ? { cwd: args.workdir } : {},
  283. }
  284. }
  285. /**
  286. * Completed-state presentation for a `bash` call. Two parallel renderings of the
  287. * same output: `terminal.output` for a UI that shows a terminal card (the run's
  288. * stdout/stderr + status markers, exactly as the model sees them — the RAW text,
  289. * newlines preserved, since a terminal renderer relies on exact bytes), and a
  290. * fenced ```console `content` block as the fallback for a UI without terminal
  291. * support (the fences are a UI-only affordance, so they live here, not in the
  292. * model-facing result; the fenced body is trimmed of trailing blank lines for a
  293. * tidy block). A capable UI also gets an exit-status pill from `terminal.exitCode`
  294. * / `terminal.signal`, parsed from the status markers `renderResult` appended.
  295. *
  296. * Terminal output/exit is suppressed for results that are NOT a finished
  297. * foreground run: a `run_in_background` start (`isBackground` — the text is a
  298. * task-id ack, not a streamed run) and an `isError` result (a spawn failure or
  299. * abort — there is no real process exit to pill, and the body is an error
  300. * message, not `renderResult` output, so parsing it would be meaningless). Those
  301. * return a `generic` result whose content is the fenced ```console block. A
  302. * finished foreground run returns a `terminal` result carrying the RAW output
  303. * and the parsed exit status; the BRIDGE derives the fenced fallback from
  304. * `output` for a UI without terminal support, so the tool does not double-encode
  305. * it. A non-text result (unexpected for bash) falls through to `undefined`.
  306. */
  307. function presentBashResult(args: unknown, result: ToolResult): ToolResultView | undefined {
  308. const block = result.content.length === 1 ? result.content[0] : undefined
  309. if (block === undefined || block.type !== 'text') return undefined
  310. const raw = block.text
  311. const isBackground = typeof args === 'object' && args !== null && (args as { run_in_background?: unknown }).run_in_background === true
  312. // A background ack or an errored run is not a real terminal exit: render the
  313. // fenced ```console fallback as generic content (no exit pill).
  314. if (isBackground || result.isError) {
  315. return { card: 'generic', content: [{ type: 'text', text: `\`\`\`console\n${raw.replace(/\n+$/, '')}\n\`\`\`` }] }
  316. }
  317. // A finished foreground run: RAW output + parsed exit for the terminal card.
  318. // The bridge derives the no-capability fenced fallback from `output`.
  319. return { card: 'terminal', output: raw, ...parseExitStatus(raw) }
  320. }
  321. /**
  322. * Recover the structured exit status from a rendered `renderResult` string — the
  323. * inverse of the status markers it appends. A `[killed by signal: SIG]` marker
  324. * yields `{signal}`; otherwise an `[exit code: N]` marker yields `{exitCode:N}`;
  325. * absent both we report `{exitCode:0}` (a clean run appends no marker — and a
  326. * trapped-timeout run that exits 0 also has none and is accurately exit 0).
  327. *
  328. * Why parse rendered text at all: `presentResult` is replay-safe and on a
  329. * `session/load` the ONLY thing persisted is this content text — the structured
  330. * `BashRunResult` is long gone — so unless the exit were added to the persisted
  331. * event schema (deliberately NOT done; see the terminal-rendering RFC), parsing
  332. * is the only channel. The match is anchored to a LEADING newline + end-of-string
  333. * because `renderResult` always inserts a `\n` before the marker (line ~124) onto
  334. * a non-empty body: a real marker is therefore always its own final line. That
  335. * defeats the common spoof (program output that simply ENDS in `[exit code: 5]`
  336. * with no trailing newline — a clean exit 0 — no longer reads as a failure).
  337. *
  338. * KNOWN RESIDUAL (inherent to the replay-only-sees-text design): a clean exit 0
  339. * whose body's FINAL line is itself exactly the marker text — `[exit code: N]`
  340. * or `[killed by signal: SIG]`, printed by the program with nothing after — is
  341. * still indistinguishable from a real marker and would show a wrong pill. This is
  342. * display-only (execution and the model-facing text are unaffected) and narrow;
  343. * the complete fix is to persist a structured exit on the result event, which the
  344. * RFC names as the escape hatch.
  345. */
  346. function parseExitStatus(text: string): { exitCode: number } | { signal: string } {
  347. const signal = /\n\[killed by signal: ([^\]\n]+)\]$/.exec(text)
  348. if (signal?.[1] !== undefined) return { signal: signal[1] }
  349. const exit = /\n\[exit code: (\d+)\]$/.exec(text)
  350. if (exit?.[1] !== undefined) return { exitCode: Number(exit[1]) }
  351. return { exitCode: 0 }
  352. }
  353. /** Pending-state presentation for `bash_output`/`bash_kill` (background-task tools). */
  354. function presentTaskCall(verb: string, args: { task_id: string }): GenericCallView {
  355. return { card: 'generic', title: `${verb} background task ${args.task_id}`, kind: 'execute', rawInput: args.task_id }
  356. }
  357. /**
  358. * Resolve the working directory for a bash call. Precedence: an explicit model
  359. * `workdir` wins; otherwise default to the calling agent's session cwd
  360. * (`session.header.cwd`) so each ACP session's commands run in ITS workspace,
  361. * not the server's launch dir. A RELATIVE model `workdir` is resolved against
  362. * the session cwd (the tool tells the model to pass `workdir` instead of `cd`,
  363. * so a relative one should be relative to the session's root, not `process.cwd()`).
  364. * Returns `undefined` when neither is available (no agent / headerless session /
  365. * no session cwd) — the executor then applies its own config/`process.cwd()`
  366. * default, preserving today's non-ACP behavior.
  367. */
  368. function resolveWorkdir(modelWorkdir: string | undefined, exec: { agent?: Agent }): string | undefined {
  369. const sessionCwd = exec.agent?.session.header.cwd
  370. if (modelWorkdir === undefined) return sessionCwd
  371. if (sessionCwd !== undefined && !isAbsolute(modelWorkdir)) {
  372. return resolvePath(sessionCwd, modelWorkdir)
  373. }
  374. return modelWorkdir
  375. }
  376. /** Status line for background task reads. */
  377. function statusLine(task: BashTask): string {
  378. switch (task.status) {
  379. case 'running': return '[status: running]'
  380. case 'killed': return `[status: killed${task.signal !== null ? ` by ${task.signal}` : ''}]`
  381. case 'completed': return `[status: completed, exit code: ${task.exitCode ?? 0}]`
  382. }
  383. }
  384. export function apply(ctx: Context): void {
  385. // The bash tools' cross-call HABIT, which the per-tool descriptions cannot
  386. // carry (they describe one call each): the exit-code marker is only useful
  387. // if the model actually checks it every time.
  388. ctx.systemPrompt.section({
  389. name: 'tool:bash',
  390. order: 105,
  391. text: 'Check the [exit code: N] marker on every bash result; investigate failures before moving on.',
  392. })
  393. /**
  394. * The caller's owner TOKEN — the owning agent's `session.header.id`, or
  395. * `undefined` for a non-agent caller. Read `session.header.id` (NOT
  396. * `session.id`): every other subsystem keys off the header id (the ACP bridge,
  397. * both persistence backends), and the sibling `resolveWorkdir` already reads
  398. * `session.header.cwd`, so using `session.id` here would be the asymmetry smell
  399. * the conventions flag. The two are equal in production, but the header is the
  400. * canonical identity.
  401. */
  402. const callerToken = (exec: { agent?: Agent }): OwnerToken | undefined =>
  403. exec.agent ? OwnerToken(exec.agent.session.header.id) : undefined
  404. /**
  405. * Authorize a `bash_output`/`bash_kill` call against the task's stored owner
  406. * token. Rejects when the task HAS an owner and it differs from the caller's
  407. * token — using `!== undefined` semantics, NOT truthiness, so an empty-string
  408. * token is still a real owner (never treated as unowned). An unowned task
  409. * (`ownerOf` returns `undefined`) is allowed; a truly unknown id is also
  410. * `undefined` here and then fails loudly at the subsequent
  411. * `readOutput`/`kill` ("unknown bash task"). The conservative no-agent caller
  412. * (`callerToken` undefined) cannot match an owned task and is rejected.
  413. */
  414. const assertTaskAccess = (taskId: BashTaskId, exec: { agent?: Agent }): void => {
  415. const owner = ctx.bash.ownerOf(taskId)
  416. if (owner !== undefined && owner !== callerToken(exec)) {
  417. throw new Error(`task ${taskId} belongs to another session`)
  418. }
  419. }
  420. // Background completion → inject a notice into the owning agent's session.
  421. // Find the live agent by its session id token via the agent registry, read
  422. // opportunistically with `ctx.get('agents')` (NOT `ctx.agents`/static inject):
  423. // this listener runs from `task.done.then` on the bash fiber — a foreign
  424. // fiber — where the `ctx.agents` property proxy would throw through the
  425. // traceable shadow; `ctx.get(name)` is the topology-independent lookup. No
  426. // registry mounted (`undefined`) → drop the notice. Match on
  427. // `agent.session.header.id`, NOT the registry key: a config agent's id differs
  428. // from its session id, and the owner token IS the session id.
  429. ctx.bash.onTaskDone((task) => {
  430. const ownerToken = ctx.bash.ownerOf(task.id)
  431. if (ownerToken === undefined) return
  432. const agent = ctx.get('agents')?.list().find(a => OwnerToken(a.session.header.id) === ownerToken)
  433. if (!agent) return
  434. try {
  435. agent.inject(
  436. [{ type: 'text', text: `background bash task ${task.id} finished ${statusLine(task)}. Read its output with bash_output.` }],
  437. { source: { kind: 'plugin', plugin: 'tool-bash' } },
  438. )
  439. } catch (error: unknown) {
  440. // The ONE expected failure: the agent was disposed between task
  441. // completion and this injection (ReactLoopAgent.inject throws
  442. // `agent "<id>" is disposed`). That race is benign — drop the notice.
  443. // Anything else is a real bug and must surface, not be swallowed.
  444. if (error instanceof Error && error.message.includes('is disposed')) return
  445. throw error
  446. }
  447. })
  448. // The escalation surface exists whenever the mounted executor confines.
  449. // Its enum is the closed target vocabulary, deliberately NOT cut down by
  450. // the configured default: a session may switch to a narrower effective mode
  451. // while sharing this globally registered schema. Strict widening therefore
  452. // belongs to the per-call check below. An executor swap restarts this fiber
  453. // (static inject) and re-registers the schema.
  454. const defaultMode = ctx.bash.sandboxMode
  455. const escalationModes: readonly SandboxMode[] = defaultMode === undefined ? [] : ESCALATION_TARGETS
  456. /**
  457. * The session's standing mode override for an ordinary (non-escalating)
  458. * call: the `bash/sandbox-mode` fold of the calling agent's log, stamped
  459. * onto the request so EXECUTION follows the same effective mode the prompt
  460. * section states. Weakest precedence — an escalation grant (freshly
  461. * approved for exactly this call) outranks it, and without either the
  462. * executor's `resolve()` applies its configured default. Undefined for a
  463. * non-sandboxing executor (nothing honors it) and for agent-less callers
  464. * (no session to fold).
  465. */
  466. const sessionOverride = (exec: ToolExecution): SandboxMode | undefined =>
  467. defaultMode === undefined || exec.agent === undefined ? undefined : effectiveSandboxMode(exec.agent.session.events)
  468. /**
  469. * Resolve a sandbox-escalation request through `ctx.approval` BEFORE
  470. * anything executes. Returns the granted mode to stamp onto the bash
  471. * request; throws the distinct fail-closed text for every other path (no
  472. * service composed, an agent-less execution, a rejection, a cancellation,
  473. * an unanswerable ask) — the registry turns the throw into this call's
  474. * isError result, and nothing has run. The seam is consumed
  475. * opportunistically (`ctx.get`, the dsh-tools ask-routing pattern), so a
  476. * deployment without it degrades per call, never at registration.
  477. */
  478. const approveEscalation = async (mode: string, justification: string, exec: ToolExecution): Promise<SandboxMode> => {
  479. // Schema validation only checks ADVERTISED keys, so an unadvertised
  480. // `sandbox_permissions` (no sandboxing executor) still reaches execute — reject it here so a
  481. // human is never prompted to "escalate" a sandbox that is not there. When
  482. // the fields ARE advertised, the registry's SchemaSpec enum has already
  483. // pinned `mode` to this ladder for every caller.
  484. if (escalationModes.length === 0) {
  485. throw new Error('sandbox_permissions is not available in this composition (no sandboxing executor to escalate)')
  486. }
  487. // Strict widening is an EXECUTION check against the call's effective
  488. // mode — session override ?? executor default, the same fold ordinary
  489. // calls are stamped with — deliberately not a schema constraint (the
  490. // enum is the closed target vocabulary; the effective mode is per-call
  491. // truth). A non-widening request fails closed here and never prompts a
  492. // human.
  493. const effectiveMode = (sessionOverride(exec) ?? defaultMode) as SandboxMode
  494. if (!(WIDER_MODES[effectiveMode] ?? []).includes(mode as SandboxMode)) {
  495. throw new Error(`sandbox escalation to "${mode}" is not strictly wider than this call's current "${effectiveMode}" mode`)
  496. }
  497. const approval = ctx.get('approval')
  498. if (approval === undefined) {
  499. throw new Error(`sandbox escalation to "${mode}" requires approval, but no approval service is composed`)
  500. }
  501. if (exec.agent === undefined) {
  502. throw new Error(`sandbox escalation to "${mode}" requires approval, but the call has no agent to route it through`)
  503. }
  504. const outcome = await approval.request({
  505. agent: exec.agent,
  506. toolName: 'bash',
  507. callId: exec.callId,
  508. // Self-contained for the audit trail: approval/asked stores this
  509. // reason, and the target mode is part of the grant's identity.
  510. reason: `escalate sandbox to ${mode}: ${justification}`,
  511. ...exec.signal ? { signal: exec.signal } : {},
  512. })
  513. switch (outcome) {
  514. // The SchemaSpec enum already pinned `mode` to the closed target
  515. // vocabulary; the per-call check above proved it is strictly wider.
  516. case 'allowed-once': return mode as SandboxMode
  517. case 'rejected': throw new Error(`the user rejected escalating this command to "${mode}"`)
  518. case 'cancelled': throw new Error(`approval for escalating to "${mode}" was cancelled`)
  519. case 'unavailable': throw new Error(`sandbox escalation to "${mode}" requires approval, but no approval channel is available`)
  520. default: return assertNever(outcome, 'ApprovalOutcome')
  521. }
  522. }
  523. ctx.tools.register(defineTool({
  524. name: 'bash',
  525. description: bashDescription(escalationModes),
  526. parameters: {
  527. command: { type: 'string', required: true, description: 'The bash command to execute.' },
  528. description: {
  529. type: 'string',
  530. required: true,
  531. description: 'Clear, concise description of what this command does in active voice, '
  532. + '5-10 words (shown in the UI). Examples: "ls" → "List files in current directory"; '
  533. + '"git status" → "Show working tree status"; "npm install" → "Install package dependencies".',
  534. },
  535. timeoutMs: { type: 'number', description: 'Timeout in milliseconds. The executor applies its configured default and cap, and kills the command on expiry.' },
  536. workdir: { type: 'string', description: 'Working directory for this command. Defaults to the session workspace; a relative path is resolved against it.' },
  537. run_in_background: { type: 'boolean', description: 'Run in the background and return a task id immediately. No timeout applies.' },
  538. ...escalationModes.length > 0 ? {
  539. sandbox_permissions: {
  540. type: 'string' as const,
  541. enum: [...escalationModes],
  542. description: 'The wider sandbox mode this command needs. Only valid as a one-shot retry '
  543. + 'of a command the sandbox just denied; requires justification and user approval.',
  544. },
  545. justification: {
  546. type: 'string' as const,
  547. description: 'Required with sandbox_permissions: one sentence for the user explaining '
  548. + 'why this exact command needs the wider access.',
  549. },
  550. } : {},
  551. },
  552. async execute(args: BashToolArgs, exec) {
  553. validateBashArgs(args)
  554. // `description` is display/logging metadata only (surfaced to UIs via
  555. // the tool/call session event); it is intentionally NOT forwarded to
  556. // ctx.bash and has no effect on execution.
  557. // An escalating call resolves approval BEFORE anything executes; every
  558. // non-grant outcome throws its distinct error text and runs nothing.
  559. // (validateBashArgs pinned the pairing, so the double narrow is exact.)
  560. // An ordinary call carries the session's standing override instead —
  561. // grant > session override > executor default (see sessionOverride).
  562. const sandboxMode = args.sandbox_permissions !== undefined && args.justification !== undefined
  563. ? await approveEscalation(args.sandbox_permissions, args.justification, exec)
  564. : sessionOverride(exec)
  565. // Default the workdir to the calling agent's session cwd so each ACP
  566. // session runs in its own workspace (see resolveWorkdir); an explicit
  567. // model workdir still wins.
  568. const workdir = resolveWorkdir(args.workdir, exec)
  569. const request = {
  570. command: args.command,
  571. ...workdir !== undefined ? { workdir } : {},
  572. ...args.timeoutMs !== undefined ? { timeoutMs: args.timeoutMs } : {},
  573. ...exec.signal ? { signal: exec.signal } : {},
  574. ...sandboxMode !== undefined ? { sandboxMode } : {},
  575. }
  576. if (args.run_in_background === true) {
  577. // Stamp the owner token (the agent's session id) onto the spec so the
  578. // executor stores it on the task — the isolation fence for bash_output/
  579. // bash_kill. Foreground runs pass no owner (they finish inline; nothing
  580. // to fence).
  581. const task = ctx.bash.start(ctx.bash.resolve({ ...request, owner: callerToken(exec) }))
  582. return [{ type: 'text', text: `started background task ${task.id}` }]
  583. }
  584. const result = await ctx.bash.run(ctx.bash.resolve(request))
  585. if (result.aborted) throw new Error('command aborted')
  586. return [{ type: 'text', text: renderResult(result, escalationModes) }]
  587. },
  588. presentCall: presentBashCall,
  589. presentResult: presentBashResult,
  590. }))
  591. ctx.tools.register(defineTool({
  592. name: 'bash_output',
  593. description: 'Read new output from a background bash task started with `bash` + `run_in_background`. '
  594. + 'Returns only output produced since the previous bash_output call, plus the task status. '
  595. + 'Tasks keep running while you do other work; poll again later for more output.',
  596. parameters: {
  597. task_id: { type: 'string', required: true, description: 'Task id returned by the bash tool.' },
  598. },
  599. // execute is synchronous (registry reads + string shaping) but the
  600. // ToolDefinition contract wants a Promise — hence resolve(), not async.
  601. execute(args, exec) {
  602. const id = validateTaskId(args.task_id)
  603. assertTaskAccess(id, exec)
  604. const read = ctx.bash.readOutput(id)
  605. let text = read.delta.length > 0 ? read.delta : '(no new output)'
  606. if (read.lossy) {
  607. const paths = [read.stdoutSpillPath, read.stderrSpillPath].filter((p): p is string => p !== undefined)
  608. const fullOutput = paths.length > 0 ? paths.join(', ') : '(unavailable)'
  609. text += `\n[some output was dropped from memory; full output: ${fullOutput}]`
  610. }
  611. text += `\n${statusLine(read.task)}`
  612. if (read.task.sandbox?.runnerFailed) {
  613. // The sandbox RUNNER itself failed — the command never ran. The
  614. // foreground path surfaces this as the structured SANDBOX_UNAVAILABLE
  615. // error; a settled task's read carries the marker instead.
  616. text += `\n[sandbox: the sandbox runner itself failed under ${read.task.sandbox.mode} mode — the command did not run; this is a sandbox problem, not a command failure]`
  617. } else if (read.task.sandbox?.denied) {
  618. // Mirrors the foreground result marker (and its same-turn escalation
  619. // hint). Background denials are only classifiable once the task
  620. // settles (the classifier needs the whole stderr), so the marker
  621. // rides every read that sees the settled task.
  622. text += `\n[sandbox: file access denied under ${read.task.sandbox.mode} mode]`
  623. if (escalationModes.length > 0) {
  624. text += '\n[sandbox: escalation available — retry this exact command once with sandbox_permissions (the narrowest wider mode that suffices) + justification; the approval prompt asks the user]'
  625. }
  626. }
  627. return Promise.resolve([{ type: 'text', text }])
  628. },
  629. presentCall: args => presentTaskCall('Read output from', args),
  630. }))
  631. ctx.tools.register(defineTool({
  632. name: 'bash_kill',
  633. description: 'Ask the executor to kill a running background bash task by task id.',
  634. parameters: {
  635. task_id: { type: 'string', required: true, description: 'Task id returned by the bash tool.' },
  636. },
  637. execute(args, exec) {
  638. const id = validateTaskId(args.task_id)
  639. assertTaskAccess(id, exec)
  640. const killed = ctx.bash.kill(id)
  641. return Promise.resolve([{
  642. type: 'text',
  643. text: killed ? `killed background task ${id}` : `task ${id} had already finished`,
  644. }])
  645. },
  646. presentCall: args => presentTaskCall('Kill', args),
  647. }))
  648. }