2026-06-12 23:28:44 +08:00
/**
2026-07-13 23:27:00 +08:00
* Model-facing `bash`, `bash_output`, and `bash_kill` tools over the executor
* seam. Background tasks are fenced by owning session, completion injects a
* durable notice, and confining executors add one-shot approval-based escalation.
2026-06-12 23:28:44 +08:00
* @module @deepseek-ai/dsh-tool-bash
*/
import type { Context } from 'cordis'
2026-06-17 10:01:18 +08:00
import { isAbsolute , resolve as resolvePath } from 'node:path'
2026-06-12 23:28:44 +08:00
import { defineTool } from '@deepseek-ai/dsh-tools'
2026-07-09 16:37:10 +08:00
import type { GenericCallView , TerminalCallView , ToolExecution , ToolResult , ToolResultView } from '@deepseek-ai/dsh-tools'
2026-06-12 23:28:44 +08:00
import type { Agent } from '@deepseek-ai/dsh-agent'
2026-07-09 16:37:10 +08:00
import { assertNever } from '@deepseek-ai/dsh-llm'
2026-07-05 01:54:46 +08:00
import type { } from '@deepseek-ai/dsh-system-prompt'
2026-07-09 16:37:10 +08:00
// Side-effect type import: declaration-merges `ctx.approval`, consumed
// opportunistically by the escalation gate (`ctx.get('approval')` — the seam
// stays optional at runtime, same pattern as dsh-tools' ask routing).
2026-07-11 21:37:38 +08:00
import type { } from '@deepseek-ai/dsh-user-approval'
2026-07-09 16:37:10 +08:00
import type { SandboxMode } from '@deepseek-ai/dsh-sandbox'
2026-07-09 16:41:03 +08:00
import { BashTaskId , OwnerToken , effectiveSandboxMode } from '@deepseek-ai/dsh-bash'
2026-06-12 23:28:44 +08:00
import type { BashRunResult , BashTask , CollectedOutput } from '@deepseek-ai/dsh-bash'
export const name = 'tool-bash'
2026-07-05 01:54:46 +08:00
export const inject = [ 'tools' , 'bash' , 'systemPrompt' ]
2026-06-12 23:28:44 +08:00
/**
2026-07-13 23:27:00 +08:00
* Validate the constraints the SchemaSpec can't express. `defineTool`
2026-06-18 02:18:24 +08:00
* validates parsed args against the SchemaSpec before `execute` runs (the
* arg-validation RFC), so type/required/enum checks are already done and `args`
* is the validated `InferArgs` shape here. What remains are value constraints
2026-07-09 16:37:10 +08:00
* the DSL has no vocabulary for: non-empty strings, a positive finite timeout,
* and the escalation pairing (`sandbox_permissions` and `justification` travel
* together — an approval prompt without a reason, or a reason driving nothing,
* is a malformed ask).
2026-06-12 23:28:44 +08:00
*/
2026-07-09 16:37:10 +08:00
function validateBashArgs ( args : BashToolArgs ) : void {
2026-06-13 23:00:42 +08:00
if ( args . command . trim ( ) . length === 0 ) {
2026-06-12 23:28:44 +08:00
throw new Error ( 'invalid command: expected a non-empty string' )
}
2026-06-13 23:00:42 +08:00
if ( args . description . trim ( ) . length === 0 ) {
2026-06-12 23:28:44 +08:00
throw new Error ( 'invalid description: expected a non-empty string' )
}
2026-06-13 23:00:42 +08:00
if ( args . timeoutMs !== undefined && ( ! Number . isFinite ( args . timeoutMs ) || args . timeoutMs <= 0 ) ) {
2026-06-12 23:28:44 +08:00
throw new Error ( ` invalid timeoutMs: expected a positive number, got ${ JSON . stringify ( args . timeoutMs ) } ` )
}
2026-07-09 16:37:10 +08:00
if ( args . sandbox_permissions !== undefined && args . justification === undefined ) {
throw new Error ( 'invalid escalation: sandbox_permissions requires a justification' )
}
if ( args . justification !== undefined && args . sandbox_permissions === undefined ) {
throw new Error ( 'invalid escalation: justification is only valid together with sandbox_permissions' )
}
if ( args . justification !== undefined && args . justification . trim ( ) . length === 0 ) {
throw new Error ( 'invalid justification: expected a non-empty sentence' )
}
2026-06-12 23:28:44 +08:00
}
2026-06-13 23:00:42 +08:00
/**
* Reject an empty `task_id`. Type and presence are guaranteed by the
2026-06-18 02:18:24 +08:00
* SchemaSpec validation (the arg-validation RFC); only the non-empty constraint, which the
2026-06-13 23:00:42 +08:00
* DSL can't express, is left to check here.
*/
2026-06-21 07:17:25 +08:00
function validateTaskId ( value : string ) : BashTaskId {
2026-06-13 23:00:42 +08:00
if ( value . length === 0 ) {
2026-06-12 23:28:44 +08:00
throw new Error ( ` invalid task_id: expected a string, got ${ JSON . stringify ( value ) } ` )
}
2026-06-21 07:17:25 +08:00
return BashTaskId ( value )
2026-06-12 23:28:44 +08:00
}
2026-07-09 16:37:10 +08:00
/**
* The bash tool's validated argument shape — the base parameters plus the two
* escalation fields, which are ADVERTISED only when the mounted executor
* reports a confining default mode (absent from the schema otherwise, so the
* SchemaSpec validator rejects them before `execute` ever sees one).
*/
interface BashToolArgs {
command : string
description : string
timeoutMs? : number
workdir? : string
run_in_background? : boolean
sandbox_permissions? : string
justification? : string
}
/**
* The strictly-wider table: what a call whose effective mode is the key may
* escalate TO. Checked at EXECUTION, never baked into the schema — the
* schema's enum is {@link ESCALATION_TARGETS}, because schemas are
* registry-global while the effective mode is per-call truth.
*/
const WIDER_MODES : Record < string , readonly SandboxMode [ ] > = {
'read-only' : [ 'workspace-write' , 'danger-full-access' ] ,
'workspace-write' : [ 'danger-full-access' ] ,
}
/**
* The closed escalation-target vocabulary — every mode a call could ever
* escalate TO (`read-only` is the floor; nothing escalates to it). Advertised
* whenever the mounted executor confines: cutting the enum down to the modes
* wider than the executor's DEFAULT would strand a session whose effective
* mode sits below it (a `danger-full-access` default would advertise nothing
* while a narrower-switched session stays confined with no lever).
*/
const ESCALATION_TARGETS : readonly SandboxMode [ ] = [ 'workspace-write' , 'danger-full-access' ]
/**
2026-07-12 03:36:43 +08:00
* The bash tool's static description.
2026-07-09 16:37:10 +08:00
*/
function bashDescription ( escalationModes : readonly SandboxMode [ ] ) : string {
const base = 'Execute a bash command (`bash -c`) and return its stdout/stderr. '
+ 'Each call runs in a fresh shell: no state (cwd, variables, functions) persists between calls — '
+ 'pass `workdir` instead of using `cd`. Non-zero exits are reported as `[exit code: N]`. '
+ '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). '
+ 'Long output is truncated to its tail; the full output is saved to a file whose path is reported when available. '
+ 'Set `run_in_background: true` for long-running commands: the call returns a task id immediately; '
+ 'poll it with `bash_output` and stop it with `bash_kill`.'
if ( escalationModes . length === 0 ) return base
return base + ' Attempting a command the sandbox may deny is safe and expected: run it and read the '
+ 'marker rather than assuming the denial. When a command IS denied and a wider mode would let it '
+ 'succeed, escalate immediately in the SAME turn — the ONE sanctioned exception to a denial: retry '
+ 'the exact same command once with `sandbox_permissions` (the narrowest wider mode that suffices) '
+ 'plus a one-sentence `justification`. Do not detour through chat to ask permission first — the '
+ 'approval prompt raised by that retry IS how the user consents. If the session states approval '
+ 'prompts are disabled, there is no exception: a denial is final — do not set `sandbox_permissions`. '
+ 'Never escalate speculatively: ground the request in a real denial — normally the one THIS command '
+ 'just hit; escalating up front is fine only when this session already denied the same access. '
+ 'A rejected escalation is final for THAT command — stop and explain, never work around '
+ 'it — but it does not forbid attempting or escalating other commands later.'
}
2026-06-12 23:28:44 +08:00
/** Append the truncation notice (with the full-output spill path) to a stream's text. */
function streamText ( output : CollectedOutput ) : string {
if ( ! output . truncated ) return output . text
return ` ${ output . text } \ n[output truncated; full output: ${ output . spillPath ? ? '(unavailable)' } ] `
}
/**
2026-07-13 23:27:00 +08:00
* Shape one finished run into model-visible stdout, marked stderr, and status
* facts. Non-zero exits and sandbox denials remain ordinary results; only
* infrastructure failure or abort makes the tool call itself fail.
2026-07-12 03:36:43 +08:00
*
2026-07-06 22:09:30 +08:00
* @param result - the completed foreground run from the executor.
2026-07-12 03:36:43 +08:00
* @param escalationModes - the escalation targets this composition advertises; non-empty
* adds the same-turn escalation hint after a denial marker (default `[]`: no hint).
* @returns the model-facing text: output body (or `(no output)`), then any
* timeout/signal/exit markers, each on its own line.
2026-06-12 23:28:44 +08:00
*/
2026-07-09 16:37:10 +08:00
export function renderResult (
result : BashRunResult ,
escalationModes : readonly SandboxMode [ ] = [ ] ,
) : string {
2026-06-12 23:28:44 +08:00
const out = streamText ( result . stdout )
const err = streamText ( result . stderr )
let body = out
if ( err . length > 0 ) {
// Single newline between sections (stdout usually ends with one already).
if ( body . length > 0 && ! body . endsWith ( '\n' ) ) body += '\n'
body += ` [stderr] \ n ${ err } `
}
if ( body . length === 0 ) body = '(no output)'
const markers : string [ ] = [ ]
2026-07-09 16:05:44 +08:00
// The sandbox marker precedes the exit-status markers so `[exit code: N]`
// stays the LAST line (exitStatus() anchors its parse there). Denial is a
// reported fact like timeout: the model decides how to react.
if ( result . sandbox ? . denied ) {
markers . push ( ` [sandbox: file access denied under ${ result . sandbox . mode } mode] ` )
2026-07-09 16:37:10 +08:00
// The same-turn nudge lives at the decision point: only when this
// composition advertises the fields (a lever is never hinted that the
// schema does not offer), and inside the sandbox marker family so the
// exit-code marker stays the last line.
if ( escalationModes . length > 0 ) {
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]' )
}
2026-07-09 16:05:44 +08:00
}
2026-06-12 23:28:44 +08:00
// Timeout is reported independently of how the process actually ended: a
// command can trap SIGTERM and exit 0 after our timer fired (e.g.
// `trap "exit 0" TERM; sleep 60`), giving timedOut:true / exitCode:0 /
// signal:null — the model must still see that the command was cut short.
if ( result . timedOut ) markers . push ( ` [timed out after ${ result . timeoutMs } ms] ` )
if ( result . signal !== null ) {
markers . push ( ` [killed by signal: ${ result . signal } ] ` )
} else if ( result . exitCode !== 0 ) {
markers . push ( ` [exit code: ${ result . exitCode } ] ` )
}
if ( markers . length === 0 ) return body
if ( ! body . endsWith ( '\n' ) ) body += '\n'
return body + markers . join ( '\n' )
}
2026-07-12 03:36:43 +08:00
// UI presentation (tool-owned).
2026-06-18 09:01:36 +08:00
/**
2026-07-13 23:27:00 +08:00
* Present foreground calls as terminals and background starts as generic cards.
2026-06-18 09:01:36 +08:00
*/
2026-06-18 19:35:15 +08:00
type BashCallArgs = { command : string ; description : string ; workdir? : string ; run_in_background? : boolean }
2026-07-03 02:04:03 +08:00
function presentBashCall ( args : BashCallArgs ) : GenericCallView | TerminalCallView {
// A background start is not an interactive terminal — a generic execute card
// with the command as rawInput and the description as a content block.
if ( args . run_in_background === true ) {
return {
card : 'generic' ,
title : args.command ,
kind : 'execute' ,
rawInput : args.command ,
content : [ { type : 'text' , text : args.description } ] ,
}
}
// A foreground run IS a terminal: the command titles the card, the description
// renders above it, and the cwd (when the model gave a workdir) heads it.
return {
card : 'terminal' ,
2026-06-18 18:54:32 +08:00
title : args.command ,
2026-07-03 02:04:03 +08:00
description : args.description ,
. . . args . workdir !== undefined ? { cwd : args.workdir } : { } ,
2026-06-18 17:25:09 +08:00
}
2026-06-18 09:01:36 +08:00
}
/**
2026-07-13 23:27:00 +08:00
* Present completed foreground output as a terminal; background acknowledgements
* and execution errors use generic fenced output without an exit-status pill.
2026-06-18 09:01:36 +08:00
*/
2026-07-03 02:04:03 +08:00
function presentBashResult ( args : unknown , result : ToolResult ) : ToolResultView | undefined {
2026-06-18 09:01:36 +08:00
const block = result . content . length === 1 ? result . content [ 0 ] : undefined
if ( block === undefined || block . type !== 'text' ) return undefined
2026-06-18 18:54:32 +08:00
const raw = block . text
2026-06-18 19:35:15 +08:00
const isBackground = typeof args === 'object' && args !== null && ( args as { run_in_background? : unknown } ) . run_in_background === true
2026-07-03 02:04:03 +08:00
// A background ack or an errored run is not a real terminal exit: render the
// fenced ```console fallback as generic content (no exit pill).
if ( isBackground || result . isError ) {
return { card : 'generic' , content : [ { type : 'text' , text : ` \` \` \` console \ n ${ raw . replace ( /\n+$/ , '' ) } \ n \` \` \` ` } ] }
}
// A finished foreground run: RAW output + parsed exit for the terminal card.
// The bridge derives the no-capability fenced fallback from `output`.
return { card : 'terminal' , output : raw , . . . parseExitStatus ( raw ) }
2026-06-18 09:01:36 +08:00
}
2026-06-18 18:54:32 +08:00
/**
2026-07-13 23:27:00 +08:00
* Recover exit status from the final marked line emitted by {@link renderResult}.
* A program whose own final line exactly mimics a marker remains ambiguous for UI display.
2026-06-18 18:54:32 +08:00
*/
function parseExitStatus ( text : string ) : { exitCode : number } | { signal : string } {
2026-06-18 19:35:15 +08:00
const signal = /\n\[killed by signal: ([^\]\n]+)\]$/ . exec ( text )
2026-06-18 18:54:32 +08:00
if ( signal ? . [ 1 ] !== undefined ) return { signal : signal [ 1 ] }
2026-06-18 19:35:15 +08:00
const exit = /\n\[exit code: (\d+)\]$/ . exec ( text )
2026-06-18 18:54:32 +08:00
if ( exit ? . [ 1 ] !== undefined ) return { exitCode : Number ( exit [ 1 ] ) }
return { exitCode : 0 }
}
2026-06-18 09:01:36 +08:00
/** Pending-state presentation for `bash_output`/`bash_kill` (background-task tools). */
2026-07-03 02:04:03 +08:00
function presentTaskCall ( verb : string , args : { task_id : string } ) : GenericCallView {
return { card : 'generic' , title : ` ${ verb } background task ${ args . task_id } ` , kind : 'execute' , rawInput : args.task_id }
2026-06-18 09:01:36 +08:00
}
2026-06-17 10:01:18 +08:00
/**
2026-07-13 23:27:00 +08:00
* Resolve an explicit workdir first, making a relative one session-cwd-relative;
* otherwise use the session cwd and leave executor defaulting as the fallback.
2026-06-17 10:01:18 +08:00
*/
function resolveWorkdir ( modelWorkdir : string | undefined , exec : { agent? : Agent } ) : string | undefined {
const sessionCwd = exec . agent ? . session . header . cwd
if ( modelWorkdir === undefined ) return sessionCwd
if ( sessionCwd !== undefined && ! isAbsolute ( modelWorkdir ) ) {
return resolvePath ( sessionCwd , modelWorkdir )
}
return modelWorkdir
}
2026-06-12 23:28:44 +08:00
/** Status line for background task reads. */
function statusLine ( task : BashTask ) : string {
switch ( task . status ) {
case 'running' : return '[status: running]'
case 'killed' : return ` [status: killed ${ task . signal !== null ? ` by ${ task . signal } ` : '' } ] `
case 'completed' : return ` [status: completed, exit code: ${ task . exitCode ? ? 0 } ] `
}
}
export function apply ( ctx : Context ) : void {
2026-07-05 01:54:46 +08:00
// The bash tools' cross-call HABIT, which the per-tool descriptions cannot
// carry (they describe one call each): the exit-code marker is only useful
// if the model actually checks it every time.
ctx . systemPrompt . section ( {
name : 'tool:bash' ,
order : 105 ,
text : 'Check the [exit code: N] marker on every bash result; investigate failures before moving on.' ,
} )
2026-06-20 08:14:27 +08:00
/**
* The caller's owner TOKEN — the owning agent's `session.header.id`, or
* `undefined` for a non-agent caller. Read `session.header.id` (NOT
* `session.id`): every other subsystem keys off the header id (the ACP bridge,
* both persistence backends), and the sibling `resolveWorkdir` already reads
* `session.header.cwd`, so using `session.id` here would be the asymmetry smell
* the conventions flag. The two are equal in production, but the header is the
* canonical identity.
*/
2026-06-21 07:17:25 +08:00
const callerToken = ( exec : { agent? : Agent } ) : OwnerToken | undefined = >
exec . agent ? OwnerToken ( exec . agent . session . header . id ) : undefined
2026-06-16 19:23:21 +08:00
/**
2026-06-20 08:14:27 +08:00
* Authorize a `bash_output`/`bash_kill` call against the task's stored owner
* token. Rejects when the task HAS an owner and it differs from the caller's
* token — using `!== undefined` semantics, NOT truthiness, so an empty-string
* token is still a real owner (never treated as unowned). An unowned task
* (`ownerOf` returns `undefined`) is allowed; a truly unknown id is also
* `undefined` here and then fails loudly at the subsequent
* `readOutput`/`kill` ("unknown bash task"). The conservative no-agent caller
* (`callerToken` undefined) cannot match an owned task and is rejected.
2026-06-16 19:23:21 +08:00
*/
2026-06-21 07:17:25 +08:00
const assertTaskAccess = ( taskId : BashTaskId , exec : { agent? : Agent } ) : void = > {
2026-06-20 08:14:27 +08:00
const owner = ctx . bash . ownerOf ( taskId )
if ( owner !== undefined && owner !== callerToken ( exec ) ) {
2026-06-16 19:23:21 +08:00
throw new Error ( ` task ${ taskId } belongs to another session ` )
}
}
2026-07-13 23:27:00 +08:00
// Completion runs on the bash fiber, so use topology-independent lookup and
// match the executor's stored session-owner token to a live agent.
2026-06-12 23:28:44 +08:00
ctx . bash . onTaskDone ( ( task ) = > {
2026-06-20 08:14:27 +08:00
const ownerToken = ctx . bash . ownerOf ( task . id )
if ( ownerToken === undefined ) return
2026-06-21 07:17:25 +08:00
const agent = ctx . get ( 'agents' ) ? . list ( ) . find ( a = > OwnerToken ( a . session . header . id ) === ownerToken )
2026-06-12 23:28:44 +08:00
if ( ! agent ) return
try {
agent . inject (
[ { type : 'text' , text : ` background bash task ${ task . id } finished ${ statusLine ( task ) } . Read its output with bash_output. ` } ] ,
{ source : { kind : 'plugin' , plugin : 'tool-bash' } } ,
)
} catch ( error : unknown ) {
2026-07-12 03:36:43 +08:00
// The one expected failure: the agent was disposed between task completion and this
// injection (ReactLoopAgent.inject throws `agent "<id>" is disposed`).
2026-06-12 23:28:44 +08:00
if ( error instanceof Error && error . message . includes ( 'is disposed' ) ) return
throw error
}
} )
2026-07-11 21:37:38 +08:00
// The escalation surface exists whenever the mounted executor confines.
2026-07-09 16:37:10 +08:00
const defaultMode = ctx . bash . sandboxMode
const escalationModes : readonly SandboxMode [ ] = defaultMode === undefined ? [ ] : ESCALATION_TARGETS
2026-07-09 16:41:03 +08:00
/**
* The session's standing mode override for an ordinary (non-escalating)
* call: the `bash/sandbox-mode` fold of the calling agent's log, stamped
* onto the request so EXECUTION follows the same effective mode the prompt
* section states. Weakest precedence — an escalation grant (freshly
* approved for exactly this call) outranks it, and without either the
* executor's `resolve()` applies its configured default. Undefined for a
* non-sandboxing executor (nothing honors it) and for agent-less callers
* (no session to fold).
*/
const sessionOverride = ( exec : ToolExecution ) : SandboxMode | undefined = >
defaultMode === undefined || exec . agent === undefined ? undefined : effectiveSandboxMode ( exec . agent . session . events )
2026-07-09 16:37:10 +08:00
/**
* Resolve a sandbox-escalation request through `ctx.approval` BEFORE
* anything executes. Returns the granted mode to stamp onto the bash
* request; throws the distinct fail-closed text for every other path (no
* service composed, an agent-less execution, a rejection, a cancellation,
* an unanswerable ask) — the registry turns the throw into this call's
* isError result, and nothing has run. The seam is consumed
* opportunistically (`ctx.get`, the dsh-tools ask-routing pattern), so a
* deployment without it degrades per call, never at registration.
*/
const approveEscalation = async ( mode : string , justification : string , exec : ToolExecution ) : Promise < SandboxMode > = > {
2026-07-12 03:36:43 +08:00
// Schema validation only checks ADVERTISED keys, so an unadvertised `sandbox_permissions`
// (no sandboxing executor) still reaches execute — reject it here so a human is never
// prompted to "escalate" a sandbox that is not there.
2026-07-09 16:37:10 +08:00
if ( escalationModes . length === 0 ) {
throw new Error ( 'sandbox_permissions is not available in this composition (no sandboxing executor to escalate)' )
}
2026-07-12 03:36:43 +08:00
// Reject sandbox widening against the call's effective mode before requesting approval.
2026-07-09 16:41:03 +08:00
const effectiveMode = ( sessionOverride ( exec ) ? ? defaultMode ) as SandboxMode
2026-07-09 16:37:10 +08:00
if ( ! ( WIDER_MODES [ effectiveMode ] ? ? [ ] ) . includes ( mode as SandboxMode ) ) {
throw new Error ( ` sandbox escalation to " ${ mode } " is not strictly wider than this call's current " ${ effectiveMode } " mode ` )
}
const approval = ctx . get ( 'approval' )
if ( approval === undefined ) {
throw new Error ( ` sandbox escalation to " ${ mode } " requires approval, but no approval service is composed ` )
}
if ( exec . agent === undefined ) {
throw new Error ( ` sandbox escalation to " ${ mode } " requires approval, but the call has no agent to route it through ` )
}
const outcome = await approval . request ( {
agent : exec.agent ,
toolName : 'bash' ,
callId : exec.callId ,
// Self-contained for the audit trail: approval/asked stores this
// reason, and the target mode is part of the grant's identity.
reason : ` escalate sandbox to ${ mode } : ${ justification } ` ,
. . . exec . signal ? { signal : exec.signal } : { } ,
} )
switch ( outcome ) {
2026-07-11 21:37:38 +08:00
// The SchemaSpec enum already pinned `mode` to the closed target
// vocabulary; the per-call check above proved it is strictly wider.
2026-07-09 16:37:10 +08:00
case 'allowed-once' : return mode as SandboxMode
case 'rejected' : throw new Error ( ` the user rejected escalating this command to " ${ mode } " ` )
case 'cancelled' : throw new Error ( ` approval for escalating to " ${ mode } " was cancelled ` )
case 'unavailable' : throw new Error ( ` sandbox escalation to " ${ mode } " requires approval, but no approval channel is available ` )
default : return assertNever ( outcome , 'ApprovalOutcome' )
}
}
2026-06-12 23:28:44 +08:00
ctx . tools . register ( defineTool ( {
name : 'bash' ,
2026-07-09 16:37:10 +08:00
description : bashDescription ( escalationModes ) ,
2026-06-12 23:28:44 +08:00
parameters : {
command : { type : 'string' , required : true , description : 'The bash command to execute.' } ,
description : {
type : 'string' ,
required : true ,
description : 'Clear, concise description of what this command does in active voice, '
+ '5-10 words (shown in the UI). Examples: "ls" → "List files in current directory"; '
+ '"git status" → "Show working tree status"; "npm install" → "Install package dependencies".' ,
} ,
2026-06-17 21:26:44 +08:00
timeoutMs : { type : 'number' , description : 'Timeout in milliseconds. The executor applies its configured default and cap, and kills the command on expiry.' } ,
2026-06-17 10:01:18 +08:00
workdir : { type : 'string' , description : 'Working directory for this command. Defaults to the session workspace; a relative path is resolved against it.' } ,
2026-06-12 23:28:44 +08:00
run_in_background : { type : 'boolean' , description : 'Run in the background and return a task id immediately. No timeout applies.' } ,
2026-07-09 16:37:10 +08:00
. . . escalationModes . length > 0 ? {
sandbox_permissions : {
type : 'string' as const ,
enum : [ . . . escalationModes ] ,
description : 'The wider sandbox mode this command needs. Only valid as a one-shot retry '
+ 'of a command the sandbox just denied; requires justification and user approval.' ,
} ,
justification : {
type : 'string' as const ,
description : 'Required with sandbox_permissions: one sentence for the user explaining '
+ 'why this exact command needs the wider access.' ,
} ,
} : { } ,
2026-06-12 23:28:44 +08:00
} ,
2026-07-09 16:37:10 +08:00
async execute ( args : BashToolArgs , exec ) {
2026-06-12 23:28:44 +08:00
validateBashArgs ( args )
2026-07-12 03:36:43 +08:00
// `description` is display/logging metadata only (surfaced to UIs via the tool/call
// session event); it is intentionally not forwarded to ctx.bash and has no effect on
// execution.
2026-07-09 16:37:10 +08:00
const sandboxMode = args . sandbox_permissions !== undefined && args . justification !== undefined
? await approveEscalation ( args . sandbox_permissions , args . justification , exec )
2026-07-09 16:41:03 +08:00
: sessionOverride ( exec )
2026-06-17 10:01:18 +08:00
// Default the workdir to the calling agent's session cwd so each ACP
// session runs in its own workspace (see resolveWorkdir); an explicit
// model workdir still wins.
const workdir = resolveWorkdir ( args . workdir , exec )
2026-06-12 23:28:44 +08:00
const request = {
command : args.command ,
2026-06-17 10:01:18 +08:00
. . . workdir !== undefined ? { workdir } : { } ,
2026-06-12 23:28:44 +08:00
. . . args . timeoutMs !== undefined ? { timeoutMs : args.timeoutMs } : { } ,
. . . exec . signal ? { signal : exec.signal } : { } ,
2026-07-09 16:37:10 +08:00
. . . sandboxMode !== undefined ? { sandboxMode } : { } ,
2026-06-12 23:28:44 +08:00
}
if ( args . run_in_background === true ) {
2026-07-12 03:36:43 +08:00
// Stamp the owner token (the agent's session id) onto the spec so the executor stores
// it on the task — the isolation fence for bash_output/ bash_kill.
2026-06-20 08:14:27 +08:00
const task = ctx . bash . start ( ctx . bash . resolve ( { . . . request , owner : callerToken ( exec ) } ) )
2026-06-12 23:28:44 +08:00
return [ { type : 'text' , text : ` started background task ${ task . id } ` } ]
}
const result = await ctx . bash . run ( ctx . bash . resolve ( request ) )
if ( result . aborted ) throw new Error ( 'command aborted' )
2026-07-09 16:37:10 +08:00
return [ { type : 'text' , text : renderResult ( result , escalationModes ) } ]
2026-06-12 23:28:44 +08:00
} ,
2026-06-18 09:01:36 +08:00
presentCall : presentBashCall ,
presentResult : presentBashResult ,
2026-06-12 23:28:44 +08:00
} ) )
ctx . tools . register ( defineTool ( {
name : 'bash_output' ,
description : 'Read new output from a background bash task started with `bash` + `run_in_background`. '
+ 'Returns only output produced since the previous bash_output call, plus the task status. '
+ 'Tasks keep running while you do other work; poll again later for more output.' ,
parameters : {
task_id : { type : 'string' , required : true , description : 'Task id returned by the bash tool.' } ,
} ,
// execute is synchronous (registry reads + string shaping) but the
// ToolDefinition contract wants a Promise — hence resolve(), not async.
2026-06-16 19:23:21 +08:00
execute ( args , exec ) {
const id = validateTaskId ( args . task_id )
assertTaskAccess ( id , exec )
const read = ctx . bash . readOutput ( id )
2026-06-12 23:28:44 +08:00
let text = read . delta . length > 0 ? read . delta : '(no new output)'
if ( read . lossy ) {
const paths = [ read . stdoutSpillPath , read . stderrSpillPath ] . filter ( ( p ) : p is string = > p !== undefined )
2026-06-19 01:54:57 +08:00
const fullOutput = paths . length > 0 ? paths . join ( ', ' ) : '(unavailable)'
text += ` \ n[some output was dropped from memory; full output: ${ fullOutput } ] `
2026-06-12 23:28:44 +08:00
}
text += ` \ n ${ statusLine ( read . task ) } `
2026-07-09 16:05:44 +08:00
if ( read . task . sandbox ? . runnerFailed ) {
// The sandbox RUNNER itself failed — the command never ran. The
// foreground path surfaces this as the structured SANDBOX_UNAVAILABLE
// error; a settled task's read carries the marker instead.
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] `
} else if ( read . task . sandbox ? . denied ) {
2026-07-12 03:36:43 +08:00
// Mirrors the foreground result marker (and its same-turn escalation hint).
2026-07-09 16:05:44 +08:00
text += ` \ n[sandbox: file access denied under ${ read . task . sandbox . mode } mode] `
2026-07-09 16:37:10 +08:00
if ( escalationModes . length > 0 ) {
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]'
}
2026-07-09 16:05:44 +08:00
}
2026-06-12 23:28:44 +08:00
return Promise . resolve ( [ { type : 'text' , text } ] )
} ,
2026-06-18 09:01:36 +08:00
presentCall : args = > presentTaskCall ( 'Read output from' , args ) ,
2026-06-12 23:28:44 +08:00
} ) )
ctx . tools . register ( defineTool ( {
name : 'bash_kill' ,
2026-06-17 21:26:44 +08:00
description : 'Ask the executor to kill a running background bash task by task id.' ,
2026-06-12 23:28:44 +08:00
parameters : {
task_id : { type : 'string' , required : true , description : 'Task id returned by the bash tool.' } ,
} ,
2026-06-16 19:23:21 +08:00
execute ( args , exec ) {
2026-06-12 23:28:44 +08:00
const id = validateTaskId ( args . task_id )
2026-06-16 19:23:21 +08:00
assertTaskAccess ( id , exec )
2026-06-12 23:28:44 +08:00
const killed = ctx . bash . kill ( id )
return Promise . resolve ( [ {
type : 'text' ,
text : killed ? ` killed background task ${ id } ` : ` task ${ id } had already finished ` ,
} ] )
} ,
2026-06-18 09:01:36 +08:00
presentCall : args = > presentTaskCall ( 'Kill' , args ) ,
2026-06-12 23:28:44 +08:00
} ) )
}