index.ts 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673
  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 shared `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 shared registry/session id,
  395. * or `undefined` for a non-agent caller. Agent and Session deliberately have
  396. * one live identity; workdir remains separate session metadata.
  397. */
  398. const callerToken = (exec: { agent?: Agent }): OwnerToken | undefined =>
  399. exec.agent ? OwnerToken(exec.agent.id) : undefined
  400. /**
  401. * Authorize a `bash_output`/`bash_kill` call against the task's stored owner
  402. * token. Rejects when the task HAS an owner and it differs from the caller's
  403. * token — using `!== undefined` semantics, NOT truthiness, so an empty-string
  404. * token is still a real owner (never treated as unowned). An unowned task
  405. * (`ownerOf` returns `undefined`) is allowed; a truly unknown id is also
  406. * `undefined` here and then fails loudly at the subsequent
  407. * `readOutput`/`kill` ("unknown bash task"). The conservative no-agent caller
  408. * (`callerToken` undefined) cannot match an owned task and is rejected.
  409. */
  410. const assertTaskAccess = (taskId: BashTaskId, exec: { agent?: Agent }): void => {
  411. const owner = ctx.bash.ownerOf(taskId)
  412. if (owner !== undefined && owner !== callerToken(exec)) {
  413. throw new Error(`task ${taskId} belongs to another session`)
  414. }
  415. }
  416. // Background completion → inject a notice into the owning agent's session.
  417. // Find the live agent by its shared registry/session token, read
  418. // opportunistically with `ctx.get('agents')` (NOT `ctx.agents`/static inject):
  419. // this listener runs from `task.done.then` on the bash fiber — a foreign
  420. // fiber — where the `ctx.agents` property proxy would throw through the
  421. // traceable shadow; `ctx.get(name)` is the topology-independent lookup. No
  422. // registry mounted (`undefined`) → drop the notice.
  423. ctx.bash.onTaskDone((task) => {
  424. const ownerToken = ctx.bash.ownerOf(task.id)
  425. if (ownerToken === undefined) return
  426. const agent = ctx.get('agents')?.list().find(a => OwnerToken(a.id) === ownerToken)
  427. if (!agent) return
  428. try {
  429. agent.inject(
  430. [{ type: 'text', text: `background bash task ${task.id} finished ${statusLine(task)}. Read its output with bash_output.` }],
  431. { source: { kind: 'plugin', plugin: 'tool-bash' } },
  432. )
  433. } catch (error: unknown) {
  434. // The ONE expected failure: the agent was disposed between task
  435. // completion and this injection (Agent.inject throws
  436. // `agent "<id>" is disposed`). That race is benign — drop the notice.
  437. // Anything else is a real bug and must surface, not be swallowed.
  438. if (error instanceof Error && error.message.includes('is disposed')) return
  439. throw error
  440. }
  441. })
  442. // The escalation surface exists whenever the mounted executor confines.
  443. // Its enum is the closed target vocabulary, deliberately NOT cut down by
  444. // the configured default: a session may switch to a narrower effective mode
  445. // while sharing this globally registered schema. Strict widening therefore
  446. // belongs to the per-call check below. An executor swap restarts this fiber
  447. // (static inject) and re-registers the schema.
  448. const defaultMode = ctx.bash.sandboxMode
  449. const escalationModes: readonly SandboxMode[] = defaultMode === undefined ? [] : ESCALATION_TARGETS
  450. /**
  451. * The session's standing mode override for an ordinary (non-escalating)
  452. * call: the `bash/sandbox-mode` fold of the calling agent's log, stamped
  453. * onto the request so EXECUTION follows the same effective mode the prompt
  454. * section states. Weakest precedence — an escalation grant (freshly
  455. * approved for exactly this call) outranks it, and without either the
  456. * executor's `resolve()` applies its configured default. Undefined for a
  457. * non-sandboxing executor (nothing honors it) and for agent-less callers
  458. * (no session to fold).
  459. */
  460. const sessionOverride = (exec: ToolExecution): SandboxMode | undefined =>
  461. defaultMode === undefined || exec.agent === undefined ? undefined : effectiveSandboxMode(exec.agent.session.events)
  462. /**
  463. * Resolve a sandbox-escalation request through `ctx.approval` BEFORE
  464. * anything executes. Returns the granted mode to stamp onto the bash
  465. * request; throws the distinct fail-closed text for every other path (no
  466. * service composed, an agent-less execution, a rejection, a cancellation,
  467. * an unanswerable ask) — the registry turns the throw into this call's
  468. * isError result, and nothing has run. The seam is consumed
  469. * opportunistically (`ctx.get`, the dsh-tools ask-routing pattern), so a
  470. * deployment without it degrades per call, never at registration.
  471. */
  472. const approveEscalation = async (mode: string, justification: string, exec: ToolExecution): Promise<SandboxMode> => {
  473. // Schema validation only checks ADVERTISED keys, so an unadvertised
  474. // `sandbox_permissions` (no sandboxing executor) still reaches execute — reject it here so a
  475. // human is never prompted to "escalate" a sandbox that is not there. When
  476. // the fields ARE advertised, the registry's SchemaSpec enum has already
  477. // pinned `mode` to this ladder for every caller.
  478. if (escalationModes.length === 0) {
  479. throw new Error('sandbox_permissions is not available in this composition (no sandboxing executor to escalate)')
  480. }
  481. // Strict widening is an EXECUTION check against the call's effective
  482. // mode — session override ?? executor default, the same fold ordinary
  483. // calls are stamped with — deliberately not a schema constraint (the
  484. // enum is the closed target vocabulary; the effective mode is per-call
  485. // truth). A non-widening request fails closed here and never prompts a
  486. // human.
  487. const effectiveMode = (sessionOverride(exec) ?? defaultMode) as SandboxMode
  488. if (!(WIDER_MODES[effectiveMode] ?? []).includes(mode as SandboxMode)) {
  489. throw new Error(`sandbox escalation to "${mode}" is not strictly wider than this call's current "${effectiveMode}" mode`)
  490. }
  491. const approval = ctx.get('approval')
  492. if (approval === undefined) {
  493. throw new Error(`sandbox escalation to "${mode}" requires approval, but no approval service is composed`)
  494. }
  495. if (exec.agent === undefined) {
  496. throw new Error(`sandbox escalation to "${mode}" requires approval, but the call has no agent to route it through`)
  497. }
  498. const outcome = await approval.request({
  499. agent: exec.agent,
  500. toolName: 'bash',
  501. callId: exec.callId,
  502. // Self-contained for the audit trail: approval/asked stores this
  503. // reason, and the target mode is part of the grant's identity.
  504. reason: `escalate sandbox to ${mode}: ${justification}`,
  505. ...exec.signal ? { signal: exec.signal } : {},
  506. })
  507. switch (outcome) {
  508. // The SchemaSpec enum already pinned `mode` to the closed target
  509. // vocabulary; the per-call check above proved it is strictly wider.
  510. case 'allowed-once': return mode as SandboxMode
  511. case 'rejected': throw new Error(`the user rejected escalating this command to "${mode}"`)
  512. case 'cancelled': throw new Error(`approval for escalating to "${mode}" was cancelled`)
  513. case 'unavailable': throw new Error(`sandbox escalation to "${mode}" requires approval, but no approval channel is available`)
  514. default: return assertNever(outcome, 'ApprovalOutcome')
  515. }
  516. }
  517. ctx.tools.register(defineTool({
  518. name: 'bash',
  519. description: bashDescription(escalationModes),
  520. parameters: {
  521. command: { type: 'string', required: true, description: 'The bash command to execute.' },
  522. description: {
  523. type: 'string',
  524. required: true,
  525. description: 'Clear, concise description of what this command does in active voice, '
  526. + '5-10 words (shown in the UI). Examples: "ls" → "List files in current directory"; '
  527. + '"git status" → "Show working tree status"; "npm install" → "Install package dependencies".',
  528. },
  529. timeoutMs: { type: 'number', description: 'Timeout in milliseconds. The executor applies its configured default and cap, and kills the command on expiry.' },
  530. workdir: { type: 'string', description: 'Working directory for this command. Defaults to the session workspace; a relative path is resolved against it.' },
  531. run_in_background: { type: 'boolean', description: 'Run in the background and return a task id immediately. No timeout applies.' },
  532. ...escalationModes.length > 0 ? {
  533. sandbox_permissions: {
  534. type: 'string' as const,
  535. enum: [...escalationModes],
  536. description: 'The wider sandbox mode this command needs. Only valid as a one-shot retry '
  537. + 'of a command the sandbox just denied; requires justification and user approval.',
  538. },
  539. justification: {
  540. type: 'string' as const,
  541. description: 'Required with sandbox_permissions: one sentence for the user explaining '
  542. + 'why this exact command needs the wider access.',
  543. },
  544. } : {},
  545. },
  546. async execute(args: BashToolArgs, exec) {
  547. validateBashArgs(args)
  548. // `description` is display/logging metadata only (surfaced to UIs via
  549. // the tool/call session event); it is intentionally NOT forwarded to
  550. // ctx.bash and has no effect on execution.
  551. // An escalating call resolves approval BEFORE anything executes; every
  552. // non-grant outcome throws its distinct error text and runs nothing.
  553. // (validateBashArgs pinned the pairing, so the double narrow is exact.)
  554. // An ordinary call carries the session's standing override instead —
  555. // grant > session override > executor default (see sessionOverride).
  556. const sandboxMode = args.sandbox_permissions !== undefined && args.justification !== undefined
  557. ? await approveEscalation(args.sandbox_permissions, args.justification, exec)
  558. : sessionOverride(exec)
  559. // Default the workdir to the calling agent's session cwd so each ACP
  560. // session runs in its own workspace (see resolveWorkdir); an explicit
  561. // model workdir still wins.
  562. const workdir = resolveWorkdir(args.workdir, exec)
  563. const request = {
  564. command: args.command,
  565. ...workdir !== undefined ? { workdir } : {},
  566. ...args.timeoutMs !== undefined ? { timeoutMs: args.timeoutMs } : {},
  567. ...exec.signal ? { signal: exec.signal } : {},
  568. ...sandboxMode !== undefined ? { sandboxMode } : {},
  569. }
  570. if (args.run_in_background === true) {
  571. // Stamp the owner token (the agent's session id) onto the spec so the
  572. // executor stores it on the task — the isolation fence for bash_output/
  573. // bash_kill. Foreground runs pass no owner (they finish inline; nothing
  574. // to fence).
  575. const task = ctx.bash.start(ctx.bash.resolve({ ...request, owner: callerToken(exec) }))
  576. return [{ type: 'text', text: `started background task ${task.id}` }]
  577. }
  578. const result = await ctx.bash.run(ctx.bash.resolve(request))
  579. if (result.aborted) throw new Error('command aborted')
  580. return [{ type: 'text', text: renderResult(result, escalationModes) }]
  581. },
  582. presentCall: presentBashCall,
  583. presentResult: presentBashResult,
  584. }))
  585. ctx.tools.register(defineTool({
  586. name: 'bash_output',
  587. description: 'Read new output from a background bash task started with `bash` + `run_in_background`. '
  588. + 'Returns only output produced since the previous bash_output call, plus the task status. '
  589. + 'Tasks keep running while you do other work; poll again later for more output.',
  590. parameters: {
  591. task_id: { type: 'string', required: true, description: 'Task id returned by the bash tool.' },
  592. },
  593. // execute is synchronous (registry reads + string shaping) but the
  594. // ToolDefinition contract wants a Promise — hence resolve(), not async.
  595. execute(args, exec) {
  596. const id = validateTaskId(args.task_id)
  597. assertTaskAccess(id, exec)
  598. const read = ctx.bash.readOutput(id)
  599. let text = read.delta.length > 0 ? read.delta : '(no new output)'
  600. if (read.lossy) {
  601. const paths = [read.stdoutSpillPath, read.stderrSpillPath].filter((p): p is string => p !== undefined)
  602. const fullOutput = paths.length > 0 ? paths.join(', ') : '(unavailable)'
  603. text += `\n[some output was dropped from memory; full output: ${fullOutput}]`
  604. }
  605. text += `\n${statusLine(read.task)}`
  606. if (read.task.sandbox?.runnerFailed) {
  607. // The sandbox RUNNER itself failed — the command never ran. The
  608. // foreground path surfaces this as the structured SANDBOX_UNAVAILABLE
  609. // error; a settled task's read carries the marker instead.
  610. 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]`
  611. } else if (read.task.sandbox?.denied) {
  612. // Mirrors the foreground result marker (and its same-turn escalation
  613. // hint). Background denials are only classifiable once the task
  614. // settles (the classifier needs the whole stderr), so the marker
  615. // rides every read that sees the settled task.
  616. text += `\n[sandbox: file access denied under ${read.task.sandbox.mode} mode]`
  617. if (escalationModes.length > 0) {
  618. 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]'
  619. }
  620. }
  621. return Promise.resolve([{ type: 'text', text }])
  622. },
  623. presentCall: args => presentTaskCall('Read output from', args),
  624. }))
  625. ctx.tools.register(defineTool({
  626. name: 'bash_kill',
  627. description: 'Ask the executor to kill a running background bash task by task id.',
  628. parameters: {
  629. task_id: { type: 'string', required: true, description: 'Task id returned by the bash tool.' },
  630. },
  631. execute(args, exec) {
  632. const id = validateTaskId(args.task_id)
  633. assertTaskAccess(id, exec)
  634. const killed = ctx.bash.kill(id)
  635. return Promise.resolve([{
  636. type: 'text',
  637. text: killed ? `killed background task ${id}` : `task ${id} had already finished`,
  638. }])
  639. },
  640. presentCall: args => presentTaskCall('Kill', args),
  641. }))
  642. }