index.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  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. * TODO(permissions): commands run with the executor's full authority. The
  34. * permission/sandbox seam is the `tools/pre-execute` waterfall (deny/ask) plus
  35. * sandboxing `BashExecutor` implementations — see docs/architecture.md
  36. * § Extending The Harness.
  37. *
  38. * @module @deepseek-ai/dsh-tool-bash
  39. */
  40. import type { Context } from 'cordis'
  41. import { isAbsolute, resolve as resolvePath } from 'node:path'
  42. import { defineTool } from '@deepseek-ai/dsh-tools'
  43. import type { GenericCallView, TerminalCallView, ToolResult, ToolResultView } from '@deepseek-ai/dsh-tools'
  44. import type { Agent } from '@deepseek-ai/dsh-agent'
  45. import type {} from '@deepseek-ai/dsh-system-prompt'
  46. import { BashTaskId, OwnerToken } from '@deepseek-ai/dsh-bash'
  47. import type { BashRunResult, BashTask, CollectedOutput } from '@deepseek-ai/dsh-bash'
  48. export const name = 'tool-bash'
  49. export const inject = ['tools', 'bash', 'systemPrompt']
  50. /**
  51. * Validate the constraints the SchemaSpec can't express. `defineTool` now
  52. * validates parsed args against the SchemaSpec before `execute` runs (the
  53. * arg-validation RFC), so type/required/enum checks are already done and `args`
  54. * is the validated `InferArgs` shape here. What remains are value constraints
  55. * the DSL has no vocabulary for: non-empty strings and a positive, finite
  56. * timeout.
  57. */
  58. function validateBashArgs(args: {
  59. command: string
  60. description: string
  61. timeoutMs?: number
  62. workdir?: string
  63. run_in_background?: boolean
  64. }): void {
  65. if (args.command.trim().length === 0) {
  66. throw new Error('invalid command: expected a non-empty string')
  67. }
  68. if (args.description.trim().length === 0) {
  69. throw new Error('invalid description: expected a non-empty string')
  70. }
  71. if (args.timeoutMs !== undefined && (!Number.isFinite(args.timeoutMs) || args.timeoutMs <= 0)) {
  72. throw new Error(`invalid timeoutMs: expected a positive number, got ${JSON.stringify(args.timeoutMs)}`)
  73. }
  74. }
  75. /**
  76. * Reject an empty `task_id`. Type and presence are guaranteed by the
  77. * SchemaSpec validation (the arg-validation RFC); only the non-empty constraint, which the
  78. * DSL can't express, is left to check here.
  79. */
  80. function validateTaskId(value: string): BashTaskId {
  81. if (value.length === 0) {
  82. throw new Error(`invalid task_id: expected a string, got ${JSON.stringify(value)}`)
  83. }
  84. return BashTaskId(value)
  85. }
  86. /** Append the truncation notice (with the full-output spill path) to a stream's text. */
  87. function streamText(output: CollectedOutput): string {
  88. if (!output.truncated) return output.text
  89. return `${output.text}\n[output truncated; full output: ${output.spillPath ?? '(unavailable)'}]`
  90. }
  91. /**
  92. * Shape one finished run into the text the model sees: stdout, then a marked
  93. * stderr section, then exit-status markers. Non-zero exits are REPORTED, not
  94. * errored — the model decides how to react; only infrastructure failures
  95. * (spawn errors, aborts) surface as isError results.
  96. * @param result - the completed foreground run from the executor.
  97. * @returns the model-facing text: output body (or `(no output)`), then any timeout/signal/exit markers, each on its own line.
  98. */
  99. export function renderResult(result: BashRunResult): string {
  100. const out = streamText(result.stdout)
  101. const err = streamText(result.stderr)
  102. let body = out
  103. if (err.length > 0) {
  104. // Single newline between sections (stdout usually ends with one already).
  105. if (body.length > 0 && !body.endsWith('\n')) body += '\n'
  106. body += `[stderr]\n${err}`
  107. }
  108. if (body.length === 0) body = '(no output)'
  109. const markers: string[] = []
  110. // Timeout is reported independently of how the process actually ended: a
  111. // command can trap SIGTERM and exit 0 after our timer fired (e.g.
  112. // `trap "exit 0" TERM; sleep 60`), giving timedOut:true / exitCode:0 /
  113. // signal:null — the model must still see that the command was cut short.
  114. if (result.timedOut) markers.push(`[timed out after ${result.timeoutMs}ms]`)
  115. if (result.signal !== null) {
  116. markers.push(`[killed by signal: ${result.signal}]`)
  117. } else if (result.exitCode !== 0) {
  118. markers.push(`[exit code: ${result.exitCode}]`)
  119. }
  120. if (markers.length === 0) return body
  121. if (!body.endsWith('\n')) body += '\n'
  122. return body + markers.join('\n')
  123. }
  124. // ---------------------------------------------------------------------------
  125. // UI presentation (tool-owned). These shape how a UI (e.g. the ACP bridge)
  126. // renders a bash call's pending and completed states. They are display-only and
  127. // pure — a UI may call them during live streaming AND a session-log replay.
  128. // ---------------------------------------------------------------------------
  129. /**
  130. * Pending-state presentation for a `bash` call. The TITLE is the exact `command`
  131. * — a `kind: 'execute'` card is rendered as a terminal whose header label IS the
  132. * title, and an execute-kind card HIDES `rawInput` (Zed: `should_show_raw_input
  133. * = !is_terminal_tool`), so the command must BE the title to be seen. This
  134. * mirrors the reference ACP adapters (claude-agent-acp, codex-acp), which both
  135. * use the bare command as an execute tool's title. The model-written
  136. * `description` (a readable summary) rides as a `content` text block shown ABOVE
  137. * the card. (Note: claude-agent-acp DROPS the description in terminal mode and
  138. * shows only the card; surfacing it as a content block is a deliberate
  139. * divergence here — we keep the human summary visible alongside the card.)
  140. * `rawInput` still carries the bare command for non-execute UIs that DO render it.
  141. *
  142. * `terminal` marks the call so a capable UI renders a TERMINAL card — but ONLY a
  143. * FOREGROUND run is a terminal: a `run_in_background` call returns a task id
  144. * immediately (it never streams a terminal; its output is polled via
  145. * `bash_output`), so it is NOT marked terminal and renders as an ordinary
  146. * execute card. For a foreground run the `terminal.cwd` (header) is the model
  147. * `workdir` when given — ABSOLUTE as-is, RELATIVE for the UI bridge to resolve
  148. * against the session cwd; when omitted the bridge fills the session workspace
  149. * cwd (this PURE presenter, args only, can't see it).
  150. */
  151. type BashCallArgs = { command: string; description: string; workdir?: string; run_in_background?: boolean }
  152. function presentBashCall(args: BashCallArgs): GenericCallView | TerminalCallView {
  153. // A background start is not an interactive terminal — a generic execute card
  154. // with the command as rawInput and the description as a content block.
  155. if (args.run_in_background === true) {
  156. return {
  157. card: 'generic',
  158. title: args.command,
  159. kind: 'execute',
  160. rawInput: args.command,
  161. content: [{ type: 'text', text: args.description }],
  162. }
  163. }
  164. // A foreground run IS a terminal: the command titles the card, the description
  165. // renders above it, and the cwd (when the model gave a workdir) heads it.
  166. return {
  167. card: 'terminal',
  168. title: args.command,
  169. description: args.description,
  170. ...args.workdir !== undefined ? { cwd: args.workdir } : {},
  171. }
  172. }
  173. /**
  174. * Completed-state presentation for a `bash` call. Two parallel renderings of the
  175. * same output: `terminal.output` for a UI that shows a terminal card (the run's
  176. * stdout/stderr + status markers, exactly as the model sees them — the RAW text,
  177. * newlines preserved, since a terminal renderer relies on exact bytes), and a
  178. * fenced ```console `content` block as the fallback for a UI without terminal
  179. * support (the fences are a UI-only affordance, so they live here, not in the
  180. * model-facing result; the fenced body is trimmed of trailing blank lines for a
  181. * tidy block). A capable UI also gets an exit-status pill from `terminal.exitCode`
  182. * / `terminal.signal`, parsed from the status markers `renderResult` appended.
  183. *
  184. * Terminal output/exit is suppressed for results that are NOT a finished
  185. * foreground run: a `run_in_background` start (`isBackground` — the text is a
  186. * task-id ack, not a streamed run) and an `isError` result (a spawn failure or
  187. * abort — there is no real process exit to pill, and the body is an error
  188. * message, not `renderResult` output, so parsing it would be meaningless). Those
  189. * return a `generic` result whose content is the fenced ```console block. A
  190. * finished foreground run returns a `terminal` result carrying the RAW output
  191. * and the parsed exit status; the BRIDGE derives the fenced fallback from
  192. * `output` for a UI without terminal support, so the tool does not double-encode
  193. * it. A non-text result (unexpected for bash) falls through to `undefined`.
  194. */
  195. function presentBashResult(args: unknown, result: ToolResult): ToolResultView | undefined {
  196. const block = result.content.length === 1 ? result.content[0] : undefined
  197. if (block === undefined || block.type !== 'text') return undefined
  198. const raw = block.text
  199. const isBackground = typeof args === 'object' && args !== null && (args as { run_in_background?: unknown }).run_in_background === true
  200. // A background ack or an errored run is not a real terminal exit: render the
  201. // fenced ```console fallback as generic content (no exit pill).
  202. if (isBackground || result.isError) {
  203. return { card: 'generic', content: [{ type: 'text', text: `\`\`\`console\n${raw.replace(/\n+$/, '')}\n\`\`\`` }] }
  204. }
  205. // A finished foreground run: RAW output + parsed exit for the terminal card.
  206. // The bridge derives the no-capability fenced fallback from `output`.
  207. return { card: 'terminal', output: raw, ...parseExitStatus(raw) }
  208. }
  209. /**
  210. * Recover the structured exit status from a rendered `renderResult` string — the
  211. * inverse of the status markers it appends. A `[killed by signal: SIG]` marker
  212. * yields `{signal}`; otherwise an `[exit code: N]` marker yields `{exitCode:N}`;
  213. * absent both we report `{exitCode:0}` (a clean run appends no marker — and a
  214. * trapped-timeout run that exits 0 also has none and is accurately exit 0).
  215. *
  216. * Why parse rendered text at all: `presentResult` is replay-safe and on a
  217. * `session/load` the ONLY thing persisted is this content text — the structured
  218. * `BashRunResult` is long gone — so unless the exit were added to the persisted
  219. * event schema (deliberately NOT done; see the terminal-rendering RFC), parsing
  220. * is the only channel. The match is anchored to a LEADING newline + end-of-string
  221. * because `renderResult` always inserts a `\n` before the marker (line ~124) onto
  222. * a non-empty body: a real marker is therefore always its own final line. That
  223. * defeats the common spoof (program output that simply ENDS in `[exit code: 5]`
  224. * with no trailing newline — a clean exit 0 — no longer reads as a failure).
  225. *
  226. * KNOWN RESIDUAL (inherent to the replay-only-sees-text design): a clean exit 0
  227. * whose body's FINAL line is itself exactly the marker text — `[exit code: N]`
  228. * or `[killed by signal: SIG]`, printed by the program with nothing after — is
  229. * still indistinguishable from a real marker and would show a wrong pill. This is
  230. * display-only (execution and the model-facing text are unaffected) and narrow;
  231. * the complete fix is to persist a structured exit on the result event, which the
  232. * RFC names as the escape hatch.
  233. */
  234. function parseExitStatus(text: string): { exitCode: number } | { signal: string } {
  235. const signal = /\n\[killed by signal: ([^\]\n]+)\]$/.exec(text)
  236. if (signal?.[1] !== undefined) return { signal: signal[1] }
  237. const exit = /\n\[exit code: (\d+)\]$/.exec(text)
  238. if (exit?.[1] !== undefined) return { exitCode: Number(exit[1]) }
  239. return { exitCode: 0 }
  240. }
  241. /** Pending-state presentation for `bash_output`/`bash_kill` (background-task tools). */
  242. function presentTaskCall(verb: string, args: { task_id: string }): GenericCallView {
  243. return { card: 'generic', title: `${verb} background task ${args.task_id}`, kind: 'execute', rawInput: args.task_id }
  244. }
  245. /**
  246. * Resolve the working directory for a bash call. Precedence: an explicit model
  247. * `workdir` wins; otherwise default to the calling agent's session cwd
  248. * (`session.header.cwd`) so each ACP session's commands run in ITS workspace,
  249. * not the server's launch dir. A RELATIVE model `workdir` is resolved against
  250. * the session cwd (the tool tells the model to pass `workdir` instead of `cd`,
  251. * so a relative one should be relative to the session's root, not `process.cwd()`).
  252. * Returns `undefined` when neither is available (no agent / headerless session /
  253. * no session cwd) — the executor then applies its own config/`process.cwd()`
  254. * default, preserving today's non-ACP behavior.
  255. */
  256. function resolveWorkdir(modelWorkdir: string | undefined, exec: { agent?: Agent }): string | undefined {
  257. const sessionCwd = exec.agent?.session.header.cwd
  258. if (modelWorkdir === undefined) return sessionCwd
  259. if (sessionCwd !== undefined && !isAbsolute(modelWorkdir)) {
  260. return resolvePath(sessionCwd, modelWorkdir)
  261. }
  262. return modelWorkdir
  263. }
  264. /** Status line for background task reads. */
  265. function statusLine(task: BashTask): string {
  266. switch (task.status) {
  267. case 'running': return '[status: running]'
  268. case 'killed': return `[status: killed${task.signal !== null ? ` by ${task.signal}` : ''}]`
  269. case 'completed': return `[status: completed, exit code: ${task.exitCode ?? 0}]`
  270. }
  271. }
  272. export function apply(ctx: Context): void {
  273. // The bash tools' cross-call HABIT, which the per-tool descriptions cannot
  274. // carry (they describe one call each): the exit-code marker is only useful
  275. // if the model actually checks it every time.
  276. ctx.systemPrompt.section({
  277. name: 'tool:bash',
  278. order: 105,
  279. text: 'Check the [exit code: N] marker on every bash result; investigate failures before moving on.',
  280. })
  281. /**
  282. * The caller's owner TOKEN — the owning agent's `session.header.id`, or
  283. * `undefined` for a non-agent caller. Read `session.header.id` (NOT
  284. * `session.id`): every other subsystem keys off the header id (the ACP bridge,
  285. * both persistence backends), and the sibling `resolveWorkdir` already reads
  286. * `session.header.cwd`, so using `session.id` here would be the asymmetry smell
  287. * the conventions flag. The two are equal in production, but the header is the
  288. * canonical identity.
  289. */
  290. const callerToken = (exec: { agent?: Agent }): OwnerToken | undefined =>
  291. exec.agent ? OwnerToken(exec.agent.session.header.id) : undefined
  292. /**
  293. * Authorize a `bash_output`/`bash_kill` call against the task's stored owner
  294. * token. Rejects when the task HAS an owner and it differs from the caller's
  295. * token — using `!== undefined` semantics, NOT truthiness, so an empty-string
  296. * token is still a real owner (never treated as unowned). An unowned task
  297. * (`ownerOf` returns `undefined`) is allowed; a truly unknown id is also
  298. * `undefined` here and then fails loudly at the subsequent
  299. * `readOutput`/`kill` ("unknown bash task"). The conservative no-agent caller
  300. * (`callerToken` undefined) cannot match an owned task and is rejected.
  301. */
  302. const assertTaskAccess = (taskId: BashTaskId, exec: { agent?: Agent }): void => {
  303. const owner = ctx.bash.ownerOf(taskId)
  304. if (owner !== undefined && owner !== callerToken(exec)) {
  305. throw new Error(`task ${taskId} belongs to another session`)
  306. }
  307. }
  308. // Background completion → inject a notice into the owning agent's session.
  309. // Find the live agent by its session id token via the agent registry, read
  310. // opportunistically with `ctx.get('agents')` (NOT `ctx.agents`/static inject):
  311. // this listener runs from `task.done.then` on the bash fiber — a foreign
  312. // fiber — where the `ctx.agents` property proxy would throw through the
  313. // traceable shadow; `ctx.get(name)` is the topology-independent lookup. No
  314. // registry mounted (`undefined`) → drop the notice. Match on
  315. // `agent.session.header.id`, NOT the registry key: a config agent's id differs
  316. // from its session id, and the owner token IS the session id.
  317. ctx.bash.onTaskDone((task) => {
  318. const ownerToken = ctx.bash.ownerOf(task.id)
  319. if (ownerToken === undefined) return
  320. const agent = ctx.get('agents')?.list().find(a => OwnerToken(a.session.header.id) === ownerToken)
  321. if (!agent) return
  322. try {
  323. agent.inject(
  324. [{ type: 'text', text: `background bash task ${task.id} finished ${statusLine(task)}. Read its output with bash_output.` }],
  325. { source: { kind: 'plugin', plugin: 'tool-bash' } },
  326. )
  327. } catch (error: unknown) {
  328. // The ONE expected failure: the agent was disposed between task
  329. // completion and this injection (ReactLoopAgent.inject throws
  330. // `agent "<id>" is disposed`). That race is benign — drop the notice.
  331. // Anything else is a real bug and must surface, not be swallowed.
  332. if (error instanceof Error && error.message.includes('is disposed')) return
  333. throw error
  334. }
  335. })
  336. ctx.tools.register(defineTool({
  337. name: 'bash',
  338. description: 'Execute a bash command (`bash -c`) and return its stdout/stderr. '
  339. + 'Each call runs in a fresh shell: no state (cwd, variables, functions) persists between calls — '
  340. + 'pass `workdir` instead of using `cd`. Non-zero exits are reported as `[exit code: N]`. '
  341. + 'Long output is truncated to its tail; the full output is saved to a file whose path is reported when available. '
  342. + 'Set `run_in_background: true` for long-running commands: the call returns a task id immediately; '
  343. + 'poll it with `bash_output` and stop it with `bash_kill`.',
  344. parameters: {
  345. command: { type: 'string', required: true, description: 'The bash command to execute.' },
  346. description: {
  347. type: 'string',
  348. required: true,
  349. description: 'Clear, concise description of what this command does in active voice, '
  350. + '5-10 words (shown in the UI). Examples: "ls" → "List files in current directory"; '
  351. + '"git status" → "Show working tree status"; "npm install" → "Install package dependencies".',
  352. },
  353. timeoutMs: { type: 'number', description: 'Timeout in milliseconds. The executor applies its configured default and cap, and kills the command on expiry.' },
  354. workdir: { type: 'string', description: 'Working directory for this command. Defaults to the session workspace; a relative path is resolved against it.' },
  355. run_in_background: { type: 'boolean', description: 'Run in the background and return a task id immediately. No timeout applies.' },
  356. },
  357. async execute(args, exec) {
  358. validateBashArgs(args)
  359. // `description` is display/logging metadata only (surfaced to UIs via
  360. // the tool/call session event); it is intentionally NOT forwarded to
  361. // ctx.bash and has no effect on execution.
  362. // Default the workdir to the calling agent's session cwd so each ACP
  363. // session runs in its own workspace (see resolveWorkdir); an explicit
  364. // model workdir still wins.
  365. const workdir = resolveWorkdir(args.workdir, exec)
  366. const request = {
  367. command: args.command,
  368. ...workdir !== undefined ? { workdir } : {},
  369. ...args.timeoutMs !== undefined ? { timeoutMs: args.timeoutMs } : {},
  370. ...exec.signal ? { signal: exec.signal } : {},
  371. }
  372. if (args.run_in_background === true) {
  373. // Stamp the owner token (the agent's session id) onto the spec so the
  374. // executor stores it on the task — the isolation fence for bash_output/
  375. // bash_kill. Foreground runs pass no owner (they finish inline; nothing
  376. // to fence).
  377. const task = ctx.bash.start(ctx.bash.resolve({ ...request, owner: callerToken(exec) }))
  378. return [{ type: 'text', text: `started background task ${task.id}` }]
  379. }
  380. const result = await ctx.bash.run(ctx.bash.resolve(request))
  381. if (result.aborted) throw new Error('command aborted')
  382. return [{ type: 'text', text: renderResult(result) }]
  383. },
  384. presentCall: presentBashCall,
  385. presentResult: presentBashResult,
  386. }))
  387. ctx.tools.register(defineTool({
  388. name: 'bash_output',
  389. description: 'Read new output from a background bash task started with `bash` + `run_in_background`. '
  390. + 'Returns only output produced since the previous bash_output call, plus the task status. '
  391. + 'Tasks keep running while you do other work; poll again later for more output.',
  392. parameters: {
  393. task_id: { type: 'string', required: true, description: 'Task id returned by the bash tool.' },
  394. },
  395. // execute is synchronous (registry reads + string shaping) but the
  396. // ToolDefinition contract wants a Promise — hence resolve(), not async.
  397. execute(args, exec) {
  398. const id = validateTaskId(args.task_id)
  399. assertTaskAccess(id, exec)
  400. const read = ctx.bash.readOutput(id)
  401. let text = read.delta.length > 0 ? read.delta : '(no new output)'
  402. if (read.lossy) {
  403. const paths = [read.stdoutSpillPath, read.stderrSpillPath].filter((p): p is string => p !== undefined)
  404. const fullOutput = paths.length > 0 ? paths.join(', ') : '(unavailable)'
  405. text += `\n[some output was dropped from memory; full output: ${fullOutput}]`
  406. }
  407. text += `\n${statusLine(read.task)}`
  408. return Promise.resolve([{ type: 'text', text }])
  409. },
  410. presentCall: args => presentTaskCall('Read output from', args),
  411. }))
  412. ctx.tools.register(defineTool({
  413. name: 'bash_kill',
  414. description: 'Ask the executor to kill a running background bash task by task id.',
  415. parameters: {
  416. task_id: { type: 'string', required: true, description: 'Task id returned by the bash tool.' },
  417. },
  418. execute(args, exec) {
  419. const id = validateTaskId(args.task_id)
  420. assertTaskAccess(id, exec)
  421. const killed = ctx.bash.kill(id)
  422. return Promise.resolve([{
  423. type: 'text',
  424. text: killed ? `killed background task ${id}` : `task ${id} had already finished`,
  425. }])
  426. },
  427. presentCall: args => presentTaskCall('Kill', args),
  428. }))
  429. }