index.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. /**
  2. * Model-facing `bash`, `bash_output`, and `bash_kill` tools over the executor
  3. * seam. Background tasks are fenced by owning session, completion injects a
  4. * durable notice, and confining executors add one-shot approval-based escalation.
  5. * Notices do not wake idle agents. Ownership is stored with the executor task so
  6. * it survives this plugin's reload; per-call authority is escalation grant,
  7. * session override, then executor default. See the package README for the tool contract.
  8. * @module @deepseek-ai/dsh-tool-bash
  9. */
  10. import type { Context } from 'cordis'
  11. import { isAbsolute, resolve as resolvePath } from 'node:path'
  12. import { defineTool } from '@deepseek-ai/dsh-tools'
  13. import type { GenericCallView, TerminalCallView, ToolExecution, ToolResult, ToolResultView } from '@deepseek-ai/dsh-tools'
  14. import type { Agent } from '@deepseek-ai/dsh-agent'
  15. import { assertNever } from '@deepseek-ai/dsh-llm'
  16. import type {} from '@deepseek-ai/dsh-system-prompt'
  17. // Side-effect type import: declaration-merges `ctx.approval`, consumed
  18. // opportunistically by the escalation gate (`ctx.get('approval')` — the seam
  19. // stays optional at runtime, same pattern as dsh-tools' ask routing).
  20. import type {} from '@deepseek-ai/dsh-user-approval'
  21. import type { SandboxMode } from '@deepseek-ai/dsh-sandbox'
  22. import { BashTaskId, OwnerToken, effectiveSandboxMode } from '@deepseek-ai/dsh-bash'
  23. import type { BashTask } from '@deepseek-ai/dsh-bash'
  24. import { parseExitStatus, renderResult } from './render.ts'
  25. export const name = 'tool-bash'
  26. export const inject = ['tools', 'bash', 'systemPrompt']
  27. /**
  28. * Validate value constraints absent from SchemaSpec: non-empty strings, a
  29. * positive finite timeout, and paired escalation mode and justification.
  30. */
  31. function validateBashArgs(args: BashToolArgs): void {
  32. if (args.command.trim().length === 0) {
  33. throw new Error('invalid command: expected a non-empty string')
  34. }
  35. if (args.description.trim().length === 0) {
  36. throw new Error('invalid description: expected a non-empty string')
  37. }
  38. if (args.timeoutMs !== undefined && (!Number.isFinite(args.timeoutMs) || args.timeoutMs <= 0)) {
  39. throw new Error(`invalid timeoutMs: expected a positive number, got ${JSON.stringify(args.timeoutMs)}`)
  40. }
  41. if (args.sandbox_permissions !== undefined && args.justification === undefined) {
  42. throw new Error('invalid escalation: sandbox_permissions requires a justification')
  43. }
  44. if (args.justification !== undefined && args.sandbox_permissions === undefined) {
  45. throw new Error('invalid escalation: justification is only valid together with sandbox_permissions')
  46. }
  47. if (args.justification !== undefined && args.justification.trim().length === 0) {
  48. throw new Error('invalid justification: expected a non-empty sentence')
  49. }
  50. }
  51. /**
  52. * Reject an empty `task_id`; SchemaSpec already validates type and presence.
  53. */
  54. function validateTaskId(value: string): BashTaskId {
  55. if (value.length === 0) {
  56. throw new Error(`invalid task_id: expected a string, got ${JSON.stringify(value)}`)
  57. }
  58. return BashTaskId(value)
  59. }
  60. /**
  61. * Validated bash arguments. Escalation fields are advertised only when the
  62. * mounted executor reports a confining mode.
  63. */
  64. interface BashToolArgs {
  65. command: string
  66. description: string
  67. timeoutMs?: number
  68. workdir?: string
  69. run_in_background?: boolean
  70. sandbox_permissions?: string
  71. justification?: string
  72. }
  73. /**
  74. * Strictly wider modes for each effective mode. Execution checks this table
  75. * because the schema is global while the effective mode is per call.
  76. */
  77. const WIDER_MODES: Record<string, readonly SandboxMode[]> = {
  78. 'read-only': ['workspace-write', 'danger-full-access'],
  79. 'workspace-write': ['danger-full-access'],
  80. }
  81. /**
  82. * All possible escalation targets. Advertise the global set because a session
  83. * override may be narrower than the executor default; execution rejects a
  84. * target that is not wider for that call.
  85. */
  86. const ESCALATION_TARGETS: readonly SandboxMode[] = ['workspace-write', 'danger-full-access']
  87. /**
  88. * The bash tool's byte-stable base description. Escalation guidance is added
  89. * only when the mounted executor can honor it, as the one exception to the
  90. * ordinary no-retry guidance.
  91. */
  92. function bashDescription(escalationModes: readonly SandboxMode[]): string {
  93. const base = 'Execute a bash command (`bash -c`) and return its stdout/stderr. '
  94. + 'Each call runs in a fresh shell: no state (cwd, variables, functions) persists between calls — '
  95. + 'pass `workdir` instead of using `cd`. Non-zero exits are reported as `[exit code: N]`. '
  96. + '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). '
  97. + 'Long output is truncated to its tail; the full output is saved to a file whose path is reported when available. '
  98. + 'Set `run_in_background: true` for long-running commands: the call returns a task id immediately; '
  99. + 'poll it with `bash_output` and stop it with `bash_kill`.'
  100. if (escalationModes.length === 0) return base
  101. return base + ' Attempting a command the sandbox may deny is safe and expected: run it and read the '
  102. + 'marker rather than assuming the denial. When a command is denied and a wider mode would let it '
  103. + 'succeed, escalate immediately in the same turn — the one sanctioned exception to a denial: retry '
  104. + 'the exact same command once with `sandbox_permissions` (the narrowest wider mode that suffices) '
  105. + 'plus a one-sentence `justification`. Do not detour through chat to ask permission first — the '
  106. + 'approval prompt raised by that retry is how the user consents. If the session states approval '
  107. + 'prompts are disabled, there is no exception: a denial is final — do not set `sandbox_permissions`. '
  108. + 'Never escalate speculatively: ground the request in a real denial — normally the one this command '
  109. + 'just hit; escalating up front is fine only when this session already denied the same access. '
  110. + 'A rejected escalation is final for that command — stop and explain, never work around '
  111. + 'it — but it does not forbid attempting or escalating other commands later.'
  112. }
  113. // Pure tool-owned presentation used for both live events and replay.
  114. /**
  115. * Present foreground calls as terminals and background starts as generic cards.
  116. */
  117. type BashCallArgs = { command: string; description: string; workdir?: string; run_in_background?: boolean }
  118. function presentBashCall(args: BashCallArgs): GenericCallView | TerminalCallView {
  119. // A background start is not an interactive terminal — a generic execute card
  120. // with the command as rawInput and the description as a content block.
  121. if (args.run_in_background === true) {
  122. return {
  123. card: 'generic',
  124. title: args.command,
  125. kind: 'execute',
  126. rawInput: args.command,
  127. content: [{ type: 'text', text: args.description }],
  128. }
  129. }
  130. // A foreground run is a terminal; an explicit workdir supplies its cwd.
  131. return {
  132. card: 'terminal',
  133. title: args.command,
  134. description: args.description,
  135. ...args.workdir !== undefined ? { cwd: args.workdir } : {},
  136. }
  137. }
  138. /**
  139. * Present completed foreground output as a terminal; background acknowledgements
  140. * and execution errors use generic fenced output without an exit-status pill.
  141. */
  142. function presentBashResult(args: unknown, result: ToolResult): ToolResultView | undefined {
  143. const block = result.content.length === 1 ? result.content[0] : undefined
  144. if (block === undefined || block.type !== 'text') return undefined
  145. const raw = block.text
  146. const isBackground = typeof args === 'object' && args !== null && (args as { run_in_background?: unknown }).run_in_background === true
  147. // A background ack or an errored run is not a real terminal exit: render the
  148. // fenced ```console fallback as generic content (no exit pill).
  149. if (isBackground || result.isError) {
  150. return { card: 'generic', content: [{ type: 'text', text: `\`\`\`console\n${raw.replace(/\n+$/, '')}\n\`\`\`` }] }
  151. }
  152. // A finished foreground run supplies raw output and parsed exit status.
  153. // The bridge derives the no-capability fenced fallback from `output`.
  154. return { card: 'terminal', output: raw, ...parseExitStatus(raw) }
  155. }
  156. /** Pending-state presentation for `bash_output`/`bash_kill` (background-task tools). */
  157. function presentTaskCall(verb: string, args: { task_id: string }): GenericCallView {
  158. return { card: 'generic', title: `${verb} background task ${args.task_id}`, kind: 'execute', rawInput: args.task_id }
  159. }
  160. /**
  161. * Resolve an explicit workdir first, making a relative one session-cwd-relative;
  162. * otherwise use the session cwd and leave executor defaulting as the fallback.
  163. */
  164. function resolveWorkdir(modelWorkdir: string | undefined, exec: { agent?: Agent }): string | undefined {
  165. const sessionCwd = exec.agent?.session.header.cwd
  166. if (modelWorkdir === undefined) return sessionCwd
  167. if (sessionCwd !== undefined && !isAbsolute(modelWorkdir)) {
  168. return resolvePath(sessionCwd, modelWorkdir)
  169. }
  170. return modelWorkdir
  171. }
  172. /** Status line for background task reads. */
  173. function statusLine(task: BashTask): string {
  174. switch (task.status) {
  175. case 'running': return '[status: running]'
  176. case 'killed': return `[status: killed${task.signal !== null ? ` by ${task.signal}` : ''}]`
  177. case 'completed': return `[status: completed, exit code: ${task.exitCode ?? 0}]`
  178. }
  179. }
  180. export function apply(ctx: Context): void {
  181. // Cross-call guidance belongs in the prompt rather than one tool description.
  182. ctx.systemPrompt.section({
  183. name: 'tool:bash',
  184. order: 105,
  185. text: 'Check the [exit code: N] marker on every bash result; investigate failures before moving on.',
  186. })
  187. /**
  188. * Return the canonical session-header id used by ACP and persistence as the
  189. * task owner, or undefined for a non-agent caller.
  190. */
  191. const callerToken = (exec: { agent?: Agent }): OwnerToken | undefined =>
  192. exec.agent ? OwnerToken(exec.agent.session.header.id) : undefined
  193. /**
  194. * Reject access when a task has a different session owner. Unowned tasks are
  195. * allowed; unknown ids still fail in the subsequent read or kill.
  196. */
  197. const assertTaskAccess = (taskId: BashTaskId, exec: { agent?: Agent }): void => {
  198. const owner = ctx.bash.ownerOf(taskId)
  199. if (owner !== undefined && owner !== callerToken(exec)) {
  200. throw new Error(`task ${taskId} belongs to another session`)
  201. }
  202. }
  203. // Completion runs on the bash fiber, so use topology-independent lookup and
  204. // match the executor's stored session-owner token to a live agent.
  205. ctx.bash.onTaskDone((task) => {
  206. const ownerToken = ctx.bash.ownerOf(task.id)
  207. if (ownerToken === undefined) return
  208. const agent = ctx.get('agents')?.list().find(a => OwnerToken(a.session.header.id) === ownerToken)
  209. if (!agent) return
  210. try {
  211. agent.inject(
  212. [{ type: 'text', text: `background bash task ${task.id} finished ${statusLine(task)}. Read its output with bash_output.` }],
  213. { source: { kind: 'plugin', plugin: 'tool-bash' } },
  214. )
  215. } catch (error: unknown) {
  216. // The one expected failure: the agent was disposed between task completion and this
  217. // injection (ReactLoopAgent.inject throws `agent "<id>" is disposed`).
  218. if (error instanceof Error && error.message.includes('is disposed')) return
  219. throw error
  220. }
  221. })
  222. // The escalation surface exists whenever the mounted executor confines.
  223. // Advertise the closed target vocabulary globally, then enforce strict
  224. // widening against each call's effective session mode.
  225. const defaultMode = ctx.bash.sandboxMode
  226. const escalationModes: readonly SandboxMode[] = defaultMode === undefined ? [] : ESCALATION_TARGETS
  227. /**
  228. * Return the calling session's folded standing mode. Approval outranks this
  229. * value and the executor default applies when it is absent; non-sandboxing
  230. * and agent-less calls have no override.
  231. */
  232. const sessionOverride = (exec: ToolExecution): SandboxMode | undefined =>
  233. defaultMode === undefined || exec.agent === undefined ? undefined : effectiveSandboxMode(exec.agent.session.events)
  234. /**
  235. * Request one-shot escalation before execution. Missing approval context,
  236. * rejection, cancellation, and unavailable answers throw without running the
  237. * command; the optional seam is resolved per call through `ctx.get`.
  238. */
  239. const approveEscalation = async (mode: string, justification: string, exec: ToolExecution): Promise<SandboxMode> => {
  240. // Reject an unadvertised escalation before prompting for a nonexistent sandbox.
  241. if (escalationModes.length === 0) {
  242. throw new Error('sandbox_permissions is not available in this composition (no sandboxing executor to escalate)')
  243. }
  244. // Reject sandbox widening against the call's effective mode before requesting approval.
  245. const effectiveMode = (sessionOverride(exec) ?? defaultMode) as SandboxMode
  246. if (!(WIDER_MODES[effectiveMode] ?? []).includes(mode as SandboxMode)) {
  247. throw new Error(`sandbox escalation to "${mode}" is not strictly wider than this call's current "${effectiveMode}" mode`)
  248. }
  249. const approval = ctx.get('approval')
  250. if (approval === undefined) {
  251. throw new Error(`sandbox escalation to "${mode}" requires approval, but no approval service is composed`)
  252. }
  253. if (exec.agent === undefined) {
  254. throw new Error(`sandbox escalation to "${mode}" requires approval, but the call has no agent to route it through`)
  255. }
  256. const outcome = await approval.request({
  257. agent: exec.agent,
  258. toolName: 'bash',
  259. callId: exec.callId,
  260. // Self-contained for the audit trail: approval/asked stores this
  261. // reason, and the target mode is part of the grant's identity.
  262. reason: `escalate sandbox to ${mode}: ${justification}`,
  263. ...exec.signal ? { signal: exec.signal } : {},
  264. })
  265. switch (outcome) {
  266. // Schema validation pins the vocabulary; the per-call check proves widening.
  267. case 'allowed-once': return mode as SandboxMode
  268. case 'rejected': throw new Error(`the user rejected escalating this command to "${mode}"`)
  269. case 'cancelled': throw new Error(`approval for escalating to "${mode}" was cancelled`)
  270. case 'unavailable': throw new Error(`sandbox escalation to "${mode}" requires approval, but no approval channel is available`)
  271. default: return assertNever(outcome, 'ApprovalOutcome')
  272. }
  273. }
  274. ctx.tools.register(defineTool({
  275. name: 'bash',
  276. description: bashDescription(escalationModes),
  277. parameters: {
  278. command: { type: 'string', required: true, description: 'The bash command to execute.' },
  279. description: {
  280. type: 'string',
  281. required: true,
  282. description: 'Clear, concise description of what this command does in active voice, '
  283. + '5-10 words (shown in the UI). Examples: "ls" → "List files in current directory"; '
  284. + '"git status" → "Show working tree status"; "npm install" → "Install package dependencies".',
  285. },
  286. timeoutMs: { type: 'number', description: 'Timeout in milliseconds. The executor applies its configured default and cap, and kills the command on expiry.' },
  287. workdir: { type: 'string', description: 'Working directory for this command. Defaults to the session workspace; a relative path is resolved against it.' },
  288. run_in_background: { type: 'boolean', description: 'Run in the background and return a task id immediately. No timeout applies.' },
  289. ...escalationModes.length > 0 ? {
  290. sandbox_permissions: {
  291. type: 'string' as const,
  292. enum: [...escalationModes],
  293. description: 'The wider sandbox mode this command needs. Only valid as a one-shot retry '
  294. + 'of a command the sandbox just denied; requires justification and user approval.',
  295. },
  296. justification: {
  297. type: 'string' as const,
  298. description: 'Required with sandbox_permissions: one sentence for the user explaining '
  299. + 'why this exact command needs the wider access.',
  300. },
  301. } : {},
  302. },
  303. async execute(args: BashToolArgs, exec) {
  304. validateBashArgs(args)
  305. // `description` is display/logging metadata only. Escalation approval
  306. // completes before execution; grant > session override > executor default.
  307. const sandboxMode = args.sandbox_permissions !== undefined && args.justification !== undefined
  308. ? await approveEscalation(args.sandbox_permissions, args.justification, exec)
  309. : sessionOverride(exec)
  310. // Default the workdir to the calling agent's session cwd so each ACP
  311. // session runs in its own workspace (see resolveWorkdir); an explicit
  312. // model workdir still wins.
  313. const workdir = resolveWorkdir(args.workdir, exec)
  314. const request = {
  315. command: args.command,
  316. ...workdir !== undefined ? { workdir } : {},
  317. ...args.timeoutMs !== undefined ? { timeoutMs: args.timeoutMs } : {},
  318. ...exec.signal ? { signal: exec.signal } : {},
  319. ...sandboxMode !== undefined ? { sandboxMode } : {},
  320. }
  321. if (args.run_in_background === true) {
  322. // Store the session owner on the task for bash_output/bash_kill isolation.
  323. const task = ctx.bash.start(ctx.bash.resolve({ ...request, owner: callerToken(exec) }))
  324. return [{ type: 'text', text: `started background task ${task.id}` }]
  325. }
  326. const result = await ctx.bash.run(ctx.bash.resolve(request))
  327. if (result.aborted) throw new Error('command aborted')
  328. return [{ type: 'text', text: renderResult(result, escalationModes) }]
  329. },
  330. presentCall: presentBashCall,
  331. presentResult: presentBashResult,
  332. }))
  333. ctx.tools.register(defineTool({
  334. name: 'bash_output',
  335. description: 'Read new output from a background bash task started with `bash` + `run_in_background`. '
  336. + 'Returns only output produced since the previous bash_output call, plus the task status. '
  337. + 'Tasks keep running while you do other work; poll again later for more output.',
  338. parameters: {
  339. task_id: { type: 'string', required: true, description: 'Task id returned by the bash tool.' },
  340. },
  341. // execute is synchronous (registry reads + string shaping) but the
  342. // ToolDefinition contract wants a Promise — hence resolve(), not async.
  343. execute(args, exec) {
  344. const id = validateTaskId(args.task_id)
  345. assertTaskAccess(id, exec)
  346. const read = ctx.bash.readOutput(id)
  347. let text = read.delta.length > 0 ? read.delta : '(no new output)'
  348. if (read.lossy) {
  349. const paths = [read.stdoutSpillPath, read.stderrSpillPath].filter((p): p is string => p !== undefined)
  350. const fullOutput = paths.length > 0 ? paths.join(', ') : '(unavailable)'
  351. text += `\n[some output was dropped from memory; full output: ${fullOutput}]`
  352. }
  353. text += `\n${statusLine(read.task)}`
  354. if (read.task.sandbox?.runnerFailed) {
  355. // Background settlement carries the runner-failure fact that a
  356. // foreground call exposes as SANDBOX_UNAVAILABLE.
  357. 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]`
  358. } else if (read.task.sandbox?.denied) {
  359. // Mirrors the foreground result marker (and its same-turn escalation hint).
  360. text += `\n[sandbox: file access denied under ${read.task.sandbox.mode} mode]`
  361. if (escalationModes.length > 0) {
  362. 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]'
  363. }
  364. }
  365. return Promise.resolve([{ type: 'text', text }])
  366. },
  367. presentCall: args => presentTaskCall('Read output from', args),
  368. }))
  369. ctx.tools.register(defineTool({
  370. name: 'bash_kill',
  371. description: 'Ask the executor to kill a running background bash task by task id.',
  372. parameters: {
  373. task_id: { type: 'string', required: true, description: 'Task id returned by the bash tool.' },
  374. },
  375. execute(args, exec) {
  376. const id = validateTaskId(args.task_id)
  377. assertTaskAccess(id, exec)
  378. const killed = ctx.bash.kill(id)
  379. return Promise.resolve([{
  380. type: 'text',
  381. text: killed ? `killed background task ${id}` : `task ${id} had already finished`,
  382. }])
  383. },
  384. presentCall: args => presentTaskCall('Kill', args),
  385. }))
  386. }