2026-06-12 23:28:44 +08:00
/**
2026-07-15 21:08:58 +08:00
* Model-facing `bash` tool over the `ctx.bash` executor seam. Background calls
* register process handles with `ctx.tasks`; their work uses task cancellation
* rather than the tool-call signal after an id is returned.
2026-06-12 23:28:44 +08:00
*
2026-07-15 21:08:58 +08:00
* TODO(permissions): deployment policy belongs in `tools/pre-execute` and
* sandboxing executors; see docs/architecture.md § Extending The Harness.
2026-06-12 23:28:44 +08:00
* @module @deepseek-ai/dsh-tool-bash
*/
import type { Context } from 'cordis'
2026-07-09 21:22:54 +08:00
import z from 'schemastery'
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-05 01:54:46 +08:00
import type { } from '@deepseek-ai/dsh-system-prompt'
2026-07-09 21:22:54 +08:00
import type { } from '@deepseek-ai/dsh-tasks'
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-16 23:31:51 +08:00
import { ESCALATION_TARGETS , approveEscalation , validateEscalationArgs } from '@deepseek-ai/dsh-sandbox'
2026-07-14 20:05:57 +08:00
import { effectiveSandboxMode } from '@deepseek-ai/dsh-sandbox-policy'
2026-07-15 13:38:17 +08:00
import { processOutcome } from './background.ts'
import { parseExitStatus , renderProcessRead , renderResult } from './render.ts'
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-15 21:08:58 +08:00
/** Configures whether the model may background commands. */
2026-07-09 21:22:54 +08:00
export interface Config {
2026-07-15 21:08:58 +08:00
/** Expose `run_in_background` (default true); disabled calls are also rejected. */
2026-07-09 21:22:54 +08:00
enableRunInBackground? : boolean
}
export const Config : z < Config > = z . object ( {
enableRunInBackground : z.boolean ( ) . default ( true ) ,
} )
2026-07-15 21:08:58 +08:00
/** Parsed tool args; execute validates value constraints absent from SchemaSpec. */
2026-07-11 23:04:27 +08:00
interface BashToolArgs {
2026-06-12 23:28:44 +08:00
command : string
description : string
timeoutMs? : number
workdir? : string
run_in_background? : boolean
2026-07-11 23:04:27 +08:00
sandbox_permissions? : string
justification? : string
}
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-14 20:05:57 +08:00
// The escalation pairing (sandbox_permissions ⇔ justification, non-empty) is
// the shared rule both enforcing families validate identically.
validateEscalationArgs ( args . sandbox_permissions , args . justification )
2026-06-12 23:28:44 +08:00
}
2026-07-11 23:04:27 +08:00
function bashDescription ( backgroundEnabled : boolean , escalationModes : readonly SandboxMode [ ] ) : string {
const background = backgroundEnabled
? 'Set `run_in_background: true` for long-running commands: the call returns a task id immediately; read its output with `task_output` and stop it with `task_kill`.'
: 'Background execution is not available; long-running commands must finish within the timeout.'
2026-07-09 16:37:10 +08:00
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-11 23:04:27 +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. '
2026-07-09 16:37:10 +08:00
+ 'Long output is truncated to its tail; the full output is saved to a file whose path is reported when available. '
2026-07-11 23:04:27 +08:00
+ background
2026-07-09 16:37:10 +08:00
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-06-18 09:01:36 +08:00
/**
2026-07-15 21:08:58 +08:00
* Present foreground calls as terminals and background starts as generic cards.
* The command remains the title on both paths; foreground cwd is passed through
* for the bridge to resolve, while background descriptions remain card content.
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 {
if ( args . run_in_background === true ) {
return {
card : 'generic' ,
title : args.command ,
kind : 'execute' ,
rawInput : args.command ,
content : [ { type : 'text' , text : args.description } ] ,
}
}
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-15 21:08:58 +08:00
// Background acknowledgements and errors have no terminal exit status.
2026-07-03 02:04:03 +08:00
if ( isBackground || result . isError ) {
return { card : 'generic' , content : [ { type : 'text' , text : ` \` \` \` console \ n ${ raw . replace ( /\n+$/ , '' ) } \ n \` \` \` ` } ] }
}
return { card : 'terminal' , output : raw , . . . parseExitStatus ( raw ) }
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-07-09 21:22:54 +08:00
export function apply ( ctx : Context , config : Config ) : void {
const backgroundEnabled = config . enableRunInBackground ? ? true
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
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
2026-07-14 20:05:57 +08:00
* anything executes, delegating the shared fail-closed sequence (strict
* widening, channel resolution, outcome mapping) to
* {@link approveEscalation}. This tool contributes only the composition
* guard (the fields are unadvertised without a sandboxing executor, yet
* schema validation checks advertised keys only, so an unadvertised
2026-07-16 23:31:51 +08:00
* `sandbox_permissions` still reaches execute) and the approval ingredients
* — the seam is consumed opportunistically (`ctx.get`) so a deployment
* without it degrades per call.
2026-07-09 16:37:10 +08:00
*/
2026-07-14 20:05:57 +08:00
const approveBashEscalation = ( mode : string , justification : string , exec : ToolExecution ) : Promise < SandboxMode > = > {
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-09 16:41:03 +08:00
const effectiveMode = ( sessionOverride ( exec ) ? ? defaultMode ) as SandboxMode
2026-07-14 20:05:57 +08:00
return approveEscalation (
{ requestedMode : mode , justification , effectiveMode , subject : 'command' } ,
{
approver : ctx.get ( 'approval' ) ,
agent : exec.agent ,
callId : exec.callId ,
toolName : 'bash' ,
. . . exec . signal ? { signal : exec.signal } : { } ,
} ,
)
2026-07-09 16:37:10 +08:00
}
2026-07-15 21:08:58 +08:00
// Cross-call guidance belongs in the prompt rather than one-call schema prose.
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-12 23:28:44 +08:00
ctx . tools . register ( defineTool ( {
name : 'bash' ,
2026-07-11 23:04:27 +08:00
description : bashDescription ( backgroundEnabled , 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-07-09 21:22:54 +08:00
. . . backgroundEnabled ? {
run_in_background : { type : 'boolean' as const , description : 'Run in the background and return a task id immediately (collect with task_output, stop with task_kill). No timeout applies.' } ,
} : { } ,
2026-07-09 16:37:10 +08:00
. . . escalationModes . length > 0 ? {
sandbox_permissions : {
type : 'string' as const ,
enum : [ . . . escalationModes ] ,
2026-07-11 23:04:27 +08:00
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.' ,
2026-07-09 16:37:10 +08:00
} ,
justification : {
type : 'string' as const ,
2026-07-11 23:04:27 +08:00
description : 'Required with sandbox_permissions: one sentence for the user explaining why this exact command needs the wider access.' ,
2026-07-09 16:37:10 +08:00
} ,
} : { } ,
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-15 21:08:58 +08:00
// Description is display metadata; workdir defaults to the caller's session.
2026-07-09 16:37:10 +08:00
const sandboxMode = args . sandbox_permissions !== undefined && args . justification !== undefined
2026-07-14 20:05:57 +08:00
? await approveBashEscalation ( args . sandbox_permissions , args . justification , exec )
2026-07-09 16:41:03 +08:00
: sessionOverride ( exec )
2026-06-17 10:01:18 +08:00
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 } : { } ,
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-15 21:08:58 +08:00
// Undeclared keys are allowed, so schema omission also needs enforcement.
2026-07-09 23:37:51 +08:00
if ( ! backgroundEnabled ) {
throw new Error ( 'run_in_background is disabled for this deployment (enableRunInBackground: false)' )
}
2026-07-09 21:22:54 +08:00
const tasks = ctx . get ( 'tasks' )
if ( tasks === undefined ) {
throw new Error ( 'background tasks unavailable: load @deepseek-ai/dsh-tasks and @deepseek-ai/dsh-tool-tasks' )
}
2026-07-15 21:08:58 +08:00
// Reject pre-start cancellation; returned tasks use their own lifecycle.
2026-07-09 21:22:54 +08:00
if ( exec . signal ? . aborted ) throw new Error ( 'command aborted' )
2026-07-15 21:08:58 +08:00
// Task preflight finishes before the starter can spawn a process.
2026-07-09 21:53:48 +08:00
const id = tasks . start ( {
kind : 'bash' ,
label : args.command ,
. . . exec . agent ? { owner : exec.agent } : { } ,
run : ( ) = > {
const proc = ctx . bash . start ( ctx . bash . resolve ( request ) )
return {
cancel : ( ) = > void proc . kill ( ) ,
done : proc.done.then ( ( ) = > processOutcome ( proc ) ) ,
2026-07-11 23:04:27 +08:00
readOutput : ( ) = > renderProcessRead ( proc . readOutput ( ) , proc . sandbox , escalationModes ) ,
2026-07-09 21:53:48 +08:00
}
} ,
} )
2026-07-09 21:22:54 +08:00
return [ { type : 'text' , text : ` started background task ${ id } ` } ]
2026-06-12 23:28:44 +08:00
}
2026-07-09 21:22:54 +08:00
const result = await ctx . bash . run ( ctx . bash . resolve ( {
. . . request ,
. . . exec . signal ? { signal : exec.signal } : { } ,
} ) )
2026-06-12 23:28:44 +08:00
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
} ) )
}