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-07-13 23:44:44 +08:00
* Notices do not wake idle agents. Ownership is stored with the executor task so
* it survives this plugin's reload; per-call authority is escalation grant,
* session override, then executor default. See the package README for the tool contract.
2026-06-12 23:28:44 +08:00
* @module @deepseek-ai/dsh-tool-bash
*/
2026-07-12 15:41:42 +08:00
import { Service , type Context } from 'cordis'
import z from 'schemastery'
2026-07-12 16:30:01 +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-10 20:52:27 +08:00
import type { } from '@deepseek-ai/dsh-session-persistence'
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-12 16:14:13 +08:00
import { BashTaskId , DSH_ENV_PREFIX , OwnerToken , effectiveSandboxMode } from '@deepseek-ai/dsh-bash'
2026-07-15 13:32:29 +08:00
import type { BashTask , DshEnvironment , DshEnvironmentKey } from '@deepseek-ai/dsh-bash'
2026-07-12 16:30:01 +08:00
import { DSH_HOME_ENV , resolveDshHome } from '@deepseek-ai/dsh-home'
2026-07-14 03:45:22 +08:00
import { parseExitStatus , renderResult } from './render.ts'
2026-07-12 15:41:42 +08:00
declare module 'cordis' {
interface Context {
bashEnv : BashEnvRegistry
}
}
2026-06-12 23:28:44 +08:00
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-12 15:41:42 +08:00
/** Configuration for the bash tool and its managed child environment. */
export interface Config {
/** DeepSeek Harness home directory exposed as `DSH_HOME`; defaults to `$DSH_HOME` or `~/.dsh`. */
dshHome? : string
}
/** Runtime configuration schema for the bash tool plugin. */
export const Config : z < Config > = z . object ( {
dshHome : z.string ( ) ,
} )
/** Model-visible metadata for one managed `DSH_*` environment variable. */
export interface BashEnvVariable {
/** Concise description of the environment fact represented by the variable. */
description : string
}
/**
* A plugin contribution to the managed environment of each model bash call.
* Declared keys make ownership conflicts detectable before the first command;
* `resolve` computes only the values available for the current execution.
*/
export interface BashEnvContributor {
/** Stable contributor name used in diagnostics and duplicate detection. */
name : string
/** Complete set of `DSH_*` keys this contributor may return. */
2026-07-12 16:14:13 +08:00
variables : Readonly < Record < DshEnvironmentKey , BashEnvVariable > >
2026-07-12 15:41:42 +08:00
/**
* Resolve this contributor's available values for one tool execution.
* @param execution - the bash tool execution and its optional calling agent.
* @returns a partial map containing only keys declared in {@link variables}.
*/
2026-07-12 16:14:13 +08:00
resolve ( execution : ToolExecution ) : Readonly < Partial < Record < DshEnvironmentKey , string > > >
2026-07-12 15:41:42 +08:00
}
/** An enumerable declaration returned by {@link BashEnvRegistry.list}. */
export interface BashEnvVariableInfo extends BashEnvVariable {
/** Contributor that owns the variable. */
contributor : string
/** Declared `DSH_*` environment variable name. */
2026-07-12 16:14:13 +08:00
key : DshEnvironmentKey
2026-07-12 15:41:42 +08:00
}
2026-07-12 16:14:13 +08:00
const DSH_SHELL_KEY = ` ${ DSH_ENV_PREFIX } SHELL ` as const
const DSH_SESSION_ID_KEY = ` ${ DSH_ENV_PREFIX } SESSION_ID ` as const
const DSH_SESSION_JSONL_KEY = ` ${ DSH_ENV_PREFIX } SESSION_JSONL ` as const
const RESERVED_BASH_ENV_KEYS = new Set < DshEnvironmentKey > ( [
2026-07-12 16:30:01 +08:00
DSH_HOME_ENV ,
2026-07-12 16:14:13 +08:00
DSH_SHELL_KEY ,
DSH_SESSION_ID_KEY ,
2026-07-12 15:41:42 +08:00
] )
2026-07-12 16:14:13 +08:00
const BASH_ENV_KEY_SUFFIX = /^[A-Z][A-Z0-9_]*$/
2026-07-12 15:41:42 +08:00
/**
* Registry (`ctx.bashEnv`) for trusted, per-execution `DSH_*` variables.
* The namespace is rebuilt for every model bash call: ambient `DSH_*` values
* are discarded by the executor, then the registry's current snapshot is
* injected. Built-in shell facts remain owned by the registry itself while
* plugins can register additional, enumerable facts with effect-scoped
* disposal.
*/
export class BashEnvRegistry extends Service {
private readonly contributors = new Map < string , BashEnvContributor > ( )
2026-07-12 16:14:13 +08:00
private readonly keyOwners = new Map < DshEnvironmentKey , string > ( )
2026-07-12 15:41:42 +08:00
private readonly dshHome : string
/**
* Create and install the `ctx.bashEnv` service.
* @param ctx - Cordis context that owns the service and registrations.
* @param config - home-directory configuration for the built-in variables.
*/
constructor ( ctx : Context , config : Config = { } ) {
super ( ctx , 'bashEnv' )
2026-07-12 16:30:01 +08:00
this . dshHome = resolveDshHome ( config . dshHome )
2026-07-12 15:41:42 +08:00
}
/**
* Register one environment contributor. Names and keys are unique; built-in
* keys are reserved. Registration is disposed with the calling plugin fiber.
* @param contributor - declared key ownership and per-execution resolver.
* @returns the disposer that unregisters the contribution.
*/
register ( contributor : BashEnvContributor ) : ( ) = > void {
const dispose = this . ctx . effect ( function * ( this : BashEnvRegistry ) {
if ( contributor . name . trim ( ) . length === 0 ) {
throw new Error ( 'bash env contributor name must be non-empty' )
}
if ( this . contributors . has ( contributor . name ) ) {
throw new Error ( ` bash env contributor " ${ contributor . name } " is already registered ` )
}
2026-07-12 16:14:13 +08:00
const variables = Object . entries ( contributor . variables ) as [ DshEnvironmentKey , BashEnvVariable ] [ ]
2026-07-12 15:41:42 +08:00
for ( const [ key , variable ] of variables ) {
2026-07-12 16:14:13 +08:00
if ( ! key . startsWith ( DSH_ENV_PREFIX )
|| ! BASH_ENV_KEY_SUFFIX . test ( key . slice ( DSH_ENV_PREFIX . length ) ) ) {
2026-07-12 15:41:42 +08:00
throw new Error ( ` bash env contributor " ${ contributor . name } " declared invalid key " ${ key } " ` )
}
if ( RESERVED_BASH_ENV_KEYS . has ( key ) ) {
throw new Error ( ` bash env contributor " ${ contributor . name } " cannot own reserved key " ${ key } " ` )
}
if ( variable . description . trim ( ) . length === 0 ) {
throw new Error ( ` bash env contributor " ${ contributor . name } " must describe " ${ key } " ` )
}
const owner = this . keyOwners . get ( key )
if ( owner !== undefined ) {
throw new Error ( ` bash env key " ${ key } " is already owned by contributor " ${ owner } "; contributor " ${ contributor . name } " cannot also own it ` )
}
}
this . contributors . set ( contributor . name , contributor )
for ( const [ key ] of variables ) this . keyOwners . set ( key , contributor . name )
yield ( ) = > {
this . contributors . delete ( contributor . name )
for ( const [ key ] of variables ) this . keyOwners . delete ( key )
}
} . bind ( this ) , 'bashEnv.register()' )
return ( ) = > void dispose ( )
}
/**
* Build the trusted `DSH_*` snapshot for one bash tool execution.
* @param execution - the current tool execution.
* @returns an immutable environment overlay containing built-ins and current contributions.
*/
collect ( execution : ToolExecution ) : DshEnvironment {
2026-07-12 16:14:13 +08:00
const values : Record < DshEnvironmentKey , string > = {
2026-07-12 16:30:01 +08:00
[ DSH_HOME_ENV ] : this . dshHome ,
2026-07-12 16:14:13 +08:00
[ DSH_SHELL_KEY ] : '1' ,
2026-07-12 15:41:42 +08:00
}
if ( execution . agent !== undefined ) {
2026-07-12 16:14:13 +08:00
values [ DSH_SESSION_ID_KEY ] = execution . agent . session . header . id
2026-07-12 15:41:42 +08:00
}
for ( const contributor of [ . . . this . contributors . values ( ) ] . sort ( ( left , right ) = > left . name . localeCompare ( right . name ) ) ) {
const resolved = contributor . resolve ( execution )
for ( const [ rawKey , value ] of Object . entries ( resolved ) ) {
2026-07-12 16:14:13 +08:00
const key = rawKey as DshEnvironmentKey
2026-07-12 15:41:42 +08:00
if ( ! Object . hasOwn ( contributor . variables , key ) ) {
throw new Error ( ` bash env contributor " ${ contributor . name } " returned undeclared key " ${ key } " ` )
}
if ( typeof value !== 'string' ) {
throw new Error ( ` bash env contributor " ${ contributor . name } " returned a non-string value for " ${ key } " ` )
}
values [ key ] = value
}
}
return Object . freeze ( Object . fromEntries ( Object . entries ( values ) . sort ( ( [ left ] , [ right ] ) = > left . localeCompare ( right ) ) ) )
}
2026-07-15 00:04:00 +08:00
// TODO(bash-env-list-builtins): Include registry-owned built-ins before diagnostics,
// prompt, or UI code treats list() as an exhaustive environment catalog.
2026-07-12 15:41:42 +08:00
/**
* Enumerate plugin-contributed variables without executing their resolvers.
* @returns declarations sorted by environment variable name.
*/
list ( ) : BashEnvVariableInfo [ ] {
return [ . . . this . contributors . values ( ) ]
. flatMap ( contributor = > Object . entries ( contributor . variables ) . map ( ( [ key , variable ] ) = > ( {
contributor : contributor.name ,
description : variable.description ,
2026-07-12 16:14:13 +08:00
key : key as DshEnvironmentKey ,
2026-07-12 15:41:42 +08:00
} ) ) )
. sort ( ( left , right ) = > left . key . localeCompare ( right . key ) )
}
}
2026-06-12 23:28:44 +08:00
/**
2026-07-14 14:37:16 +08:00
* Validate value constraints absent from SchemaSpec: non-empty strings, a
* positive finite timeout, and paired escalation mode and justification.
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
/**
2026-07-14 14:37:16 +08:00
* Reject an empty `task_id`; SchemaSpec already validates type and presence.
2026-06-13 23:00:42 +08:00
*/
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
/**
2026-07-14 14:37:16 +08:00
* Validated bash arguments. Escalation fields are advertised only when the
* mounted executor reports a confining mode.
2026-07-09 16:37:10 +08:00
*/
interface BashToolArgs {
command : string
description : string
timeoutMs? : number
workdir? : string
run_in_background? : boolean
sandbox_permissions? : string
justification? : string
}
/**
2026-07-14 14:37:16 +08:00
* Strictly wider modes for each effective mode. Execution checks this table
* because the schema is global while the effective mode is per call.
2026-07-09 16:37:10 +08:00
*/
const WIDER_MODES : Record < string , readonly SandboxMode [ ] > = {
'read-only' : [ 'workspace-write' , 'danger-full-access' ] ,
'workspace-write' : [ 'danger-full-access' ] ,
}
/**
2026-07-14 14:37:16 +08:00
* All possible escalation targets. Advertise the global set because a session
* override may be narrower than the executor default; execution rejects a
* target that is not wider for that call.
2026-07-09 16:37:10 +08:00
*/
const ESCALATION_TARGETS : readonly SandboxMode [ ] = [ 'workspace-write' , 'danger-full-access' ]
/**
2026-07-13 23:44:44 +08:00
* The bash tool's byte-stable base description. Escalation guidance is added
* only when the mounted executor can honor it, as the one exception to the
* ordinary no-retry guidance.
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]`. '
2026-07-12 16:14:13 +08:00
+ ` Current harness environment facts are exposed through managed \` $ ${ DSH_ENV_PREFIX } * \` variables; inspect them when needed. `
2026-07-09 16:37:10 +08:00
+ '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 '
2026-07-14 14:37:16 +08:00
+ '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 '
2026-07-09 16:37:10 +08:00
+ '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 '
2026-07-14 14:37:16 +08:00
+ 'approval prompt raised by that retry is how the user consents. If the session states approval '
2026-07-09 16:37:10 +08:00
+ 'prompts are disabled, there is no exception: a denial is final — do not set `sandbox_permissions`. '
2026-07-14 14:37:16 +08:00
+ 'Never escalate speculatively: ground the request in a real denial — normally the one this command '
2026-07-09 16:37:10 +08:00
+ 'just hit; escalating up front is fine only when this session already denied the same access. '
2026-07-14 14:37:16 +08:00
+ 'A rejected escalation is final for that command — stop and explain, never work around '
2026-07-09 16:37:10 +08:00
+ 'it — but it does not forbid attempting or escalating other commands later.'
}
2026-07-13 23:44:44 +08:00
// Pure tool-owned presentation used for both live events and replay.
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 } ] ,
}
}
2026-07-14 14:37:16 +08:00
// A foreground run is a terminal; an explicit workdir supplies its cwd.
2026-07-03 02:04:03 +08:00
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 \` \` \` ` } ] }
}
2026-07-14 14:37:16 +08:00
// A finished foreground run supplies raw output and parsed exit status.
2026-07-03 02:04:03 +08:00
// 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
}
/** 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 } ] `
}
}
2026-07-12 15:41:42 +08:00
export function apply ( ctx : Context , config : Config = { } ) : void {
const bashEnv = new BashEnvRegistry ( ctx , config )
bashEnv . register ( {
name : 'session-persistence' ,
variables : {
2026-07-12 16:14:13 +08:00
[ DSH_SESSION_JSONL_KEY ] : {
2026-07-12 15:41:42 +08:00
description : 'Absolute target path of the current session JSONL when the active persistence backend provides one.' ,
} ,
} ,
resolve ( execution ) {
const agent = execution . agent
if ( agent === undefined ) return { }
const location = ctx . get ( 'sessionPersistence' ) ? . locate ( agent . session . header )
2026-07-12 16:14:13 +08:00
return location ? . kind === 'jsonl' ? { [ DSH_SESSION_JSONL_KEY ] : location . path } : { }
2026-07-12 15:41:42 +08:00
} ,
} )
2026-07-14 14:37:16 +08:00
// Cross-call guidance belongs in the prompt rather than one tool description.
2026-07-05 01:54:46 +08:00
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
/**
2026-07-14 14:37:16 +08:00
* Return the canonical session-header id used by ACP and persistence as the
* task owner, or undefined for a non-agent caller.
2026-06-20 08:14:27 +08:00
*/
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-07-14 14:37:16 +08:00
* Reject access when a task has a different session owner. Unowned tasks are
* allowed; unknown ids still fail in the subsequent read or kill.
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-13 23:44:44 +08:00
// Advertise the closed target vocabulary globally, then enforce strict
// widening against each call's effective session mode.
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
/**
2026-07-14 14:37:16 +08:00
* Return the calling session's folded standing mode. Approval outranks this
* value and the executor default applies when it is absent; non-sandboxing
* and agent-less calls have no override.
2026-07-09 16:41:03 +08:00
*/
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
/**
2026-07-14 14:37:16 +08:00
* Request one-shot escalation before execution. Missing approval context,
* rejection, cancellation, and unavailable answers throw without running the
* command; the optional seam is resolved per call through `ctx.get`.
2026-07-09 16:37:10 +08:00
*/
const approveEscalation = async ( mode : string , justification : string , exec : ToolExecution ) : Promise < SandboxMode > = > {
2026-07-14 14:37:16 +08:00
// Reject an unadvertised escalation before prompting for a nonexistent sandbox.
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-14 14:37:16 +08:00
// Schema validation pins the vocabulary; the per-call check proves widening.
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-13 23:44:44 +08:00
// `description` is display/logging metadata only. Escalation approval
// completes before execution; grant > session override > executor default.
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-07-12 15:41:42 +08:00
const dshEnv = bashEnv . collect ( 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-12 15:41:42 +08:00
dshEnv ,
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-14 14:37:16 +08:00
// Store the session owner on the task for bash_output/bash_kill isolation.
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 ) {
2026-07-14 14:37:16 +08:00
// Background settlement carries the runner-failure fact that a
// foreground call exposes as SANDBOX_UNAVAILABLE.
2026-07-09 16:05:44 +08:00
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
} ) )
}