index.ts 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  1. /**
  2. * Model-facing `bash` tool over the `ctx.bash` executor seam. Background calls
  3. * register process handles with `ctx.tasks`; their work uses task cancellation
  4. * rather than the tool-call signal after an id is returned.
  5. *
  6. * TODO(permissions): deployment policy belongs in `tools/pre-execute` and
  7. * sandboxing executors; see docs/architecture.md § Extending The Harness.
  8. * @module @deepseek-ai/dsh-tool-bash
  9. */
  10. import { Service, type Context } from 'cordis'
  11. import z from 'schemastery'
  12. import { isAbsolute, resolve as resolvePath } from 'node:path'
  13. import { defineTool, TOOL_ABORTED } from '@deepseek-ai/dsh-tools'
  14. import type { GenericCallView, TerminalCallView, ToolExecution, ToolResult, ToolResultView } from '@deepseek-ai/dsh-tools'
  15. import { HarnessError } from '@deepseek-ai/dsh-llm'
  16. import type { Agent } from '@deepseek-ai/dsh-agent'
  17. import type {} from '@deepseek-ai/dsh-session-persistence'
  18. import type {} from '@deepseek-ai/dsh-system-prompt'
  19. import type {} from '@deepseek-ai/dsh-tasks'
  20. import type {} from '@deepseek-ai/dsh-user-approval'
  21. import type { SandboxExecutionPolicy, SandboxMode } from '@deepseek-ai/dsh-sandbox'
  22. import { ESCALATION_TARGETS, approveEscalation, canonicalPath, validateEscalationArgs } from '@deepseek-ai/dsh-sandbox'
  23. import type { SandboxPolicyService } from '@deepseek-ai/dsh-sandbox-policy'
  24. import { DSH_ENV_PREFIX } from '@deepseek-ai/dsh-bash'
  25. import type { BashRunResult, DshEnvironment, DshEnvironmentKey } from '@deepseek-ai/dsh-bash'
  26. import { DSH_HOME_ENV, resolveDshHome } from '@deepseek-ai/dsh-paths'
  27. import { processOutcome } from './background.ts'
  28. import { parseExitStatus, renderProcessRead, renderResult } from './render.ts'
  29. declare module 'cordis' {
  30. interface Context {
  31. bashEnv: BashEnvRegistry
  32. }
  33. }
  34. export const name = 'tool-bash'
  35. export const inject = ['tools', 'bash', 'systemPrompt']
  36. /** Configuration for the bash tool and its managed child environment. */
  37. export interface Config {
  38. /** Expose `run_in_background` (default true); disabled calls are also rejected. */
  39. enableRunInBackground?: boolean
  40. /** DeepSeek Harness home directory exposed as `DSH_HOME`; defaults to `$DSH_HOME` or `~/.dsh`. */
  41. dshHome?: string
  42. }
  43. /** Runtime configuration schema for the bash tool plugin. */
  44. export const Config: z<Config> = z.object({
  45. enableRunInBackground: z.boolean().default(true),
  46. dshHome: z.string(),
  47. })
  48. /** Model-visible metadata for one managed `DSH_*` environment variable. */
  49. export interface BashEnvVariable {
  50. /** Concise description of the environment fact represented by the variable. */
  51. description: string
  52. }
  53. /**
  54. * A plugin contribution to the managed environment of each model bash call.
  55. * Declared keys make ownership conflicts detectable before the first command;
  56. * `resolve` computes only the values available for the current execution.
  57. */
  58. export interface BashEnvContributor {
  59. /** Stable contributor name used in diagnostics and duplicate detection. */
  60. name: string
  61. /** Complete set of `DSH_*` keys this contributor may return. */
  62. variables: Readonly<Record<DshEnvironmentKey, BashEnvVariable>>
  63. /**
  64. * Resolve this contributor's available values for one tool execution.
  65. * @param execution - the bash tool execution and its optional calling agent.
  66. * @returns a partial map containing only keys declared in {@link variables}.
  67. */
  68. resolve(execution: ToolExecution): Readonly<Partial<Record<DshEnvironmentKey, string>>>
  69. }
  70. /** An enumerable declaration returned by {@link BashEnvRegistry.list}. */
  71. export interface BashEnvVariableInfo extends BashEnvVariable {
  72. /** Contributor that owns the variable. */
  73. contributor: string
  74. /** Declared `DSH_*` environment variable name. */
  75. key: DshEnvironmentKey
  76. }
  77. const DSH_SHELL_KEY = `${DSH_ENV_PREFIX}SHELL` as const
  78. const DSH_SESSION_ID_KEY = `${DSH_ENV_PREFIX}SESSION_ID` as const
  79. const DSH_SESSION_JSONL_KEY = `${DSH_ENV_PREFIX}SESSION_JSONL` as const
  80. const RESERVED_BASH_ENV_KEYS = new Set<DshEnvironmentKey>([
  81. DSH_HOME_ENV,
  82. DSH_SHELL_KEY,
  83. DSH_SESSION_ID_KEY,
  84. ])
  85. const BASH_ENV_KEY_SUFFIX = /^[A-Z][A-Z0-9_]*$/
  86. /**
  87. * Registry (`ctx.bashEnv`) for trusted, per-execution `DSH_*` variables.
  88. * The namespace is rebuilt for every model bash call: ambient `DSH_*` values
  89. * are discarded by the executor, then the registry's current snapshot is
  90. * injected. Built-in shell facts remain owned by the registry itself while
  91. * plugins can register additional, enumerable facts with effect-scoped
  92. * disposal.
  93. */
  94. export class BashEnvRegistry extends Service {
  95. private readonly contributors = new Map<string, BashEnvContributor>()
  96. private readonly keyOwners = new Map<DshEnvironmentKey, string>()
  97. private readonly dshHome: string
  98. /**
  99. * Create and install the `ctx.bashEnv` service.
  100. * @param ctx - Cordis context that owns the service and registrations.
  101. * @param config - home-directory configuration for the built-in variables.
  102. */
  103. constructor(ctx: Context, config: Config = {}) {
  104. super(ctx, 'bashEnv')
  105. this.dshHome = resolveDshHome(config.dshHome)
  106. }
  107. /**
  108. * Register one environment contributor. Names and keys are unique; built-in
  109. * keys are reserved. Registration is disposed with the calling plugin fiber.
  110. * @param contributor - declared key ownership and per-execution resolver.
  111. * @returns the disposer that unregisters the contribution.
  112. */
  113. register(contributor: BashEnvContributor): () => void {
  114. const dispose = this.ctx.effect(function* (this: BashEnvRegistry) {
  115. if (contributor.name.trim().length === 0) {
  116. throw new Error('bash env contributor name must be non-empty')
  117. }
  118. if (this.contributors.has(contributor.name)) {
  119. throw new Error(`bash env contributor "${contributor.name}" is already registered`)
  120. }
  121. const variables = Object.entries(contributor.variables) as [DshEnvironmentKey, BashEnvVariable][]
  122. for (const [key, variable] of variables) {
  123. if (!key.startsWith(DSH_ENV_PREFIX)
  124. || !BASH_ENV_KEY_SUFFIX.test(key.slice(DSH_ENV_PREFIX.length))) {
  125. throw new Error(`bash env contributor "${contributor.name}" declared invalid key "${key}"`)
  126. }
  127. if (RESERVED_BASH_ENV_KEYS.has(key)) {
  128. throw new Error(`bash env contributor "${contributor.name}" cannot own reserved key "${key}"`)
  129. }
  130. if (variable.description.trim().length === 0) {
  131. throw new Error(`bash env contributor "${contributor.name}" must describe "${key}"`)
  132. }
  133. const owner = this.keyOwners.get(key)
  134. if (owner !== undefined) {
  135. throw new Error(`bash env key "${key}" is already owned by contributor "${owner}"; contributor "${contributor.name}" cannot also own it`)
  136. }
  137. }
  138. this.contributors.set(contributor.name, contributor)
  139. for (const [key] of variables) this.keyOwners.set(key, contributor.name)
  140. yield () => {
  141. this.contributors.delete(contributor.name)
  142. for (const [key] of variables) this.keyOwners.delete(key)
  143. }
  144. }.bind(this), 'bashEnv.register()')
  145. return () => void dispose()
  146. }
  147. /**
  148. * Build the trusted `DSH_*` snapshot for one bash tool execution.
  149. * @param execution - the current tool execution.
  150. * @returns an immutable environment overlay containing built-ins and current contributions.
  151. */
  152. collect(execution: ToolExecution): DshEnvironment {
  153. const values: Record<DshEnvironmentKey, string> = {
  154. [DSH_HOME_ENV]: this.dshHome,
  155. [DSH_SHELL_KEY]: '1',
  156. }
  157. if (execution.agent !== undefined) {
  158. values[DSH_SESSION_ID_KEY] = execution.agent.session.header.id
  159. }
  160. for (const contributor of [...this.contributors.values()].sort((left, right) => left.name.localeCompare(right.name))) {
  161. const resolved = contributor.resolve(execution)
  162. for (const [rawKey, value] of Object.entries(resolved)) {
  163. const key = rawKey as DshEnvironmentKey
  164. if (!Object.hasOwn(contributor.variables, key)) {
  165. throw new Error(`bash env contributor "${contributor.name}" returned undeclared key "${key}"`)
  166. }
  167. if (typeof value !== 'string') {
  168. throw new Error(`bash env contributor "${contributor.name}" returned a non-string value for "${key}"`)
  169. }
  170. values[key] = value
  171. }
  172. }
  173. return Object.freeze(Object.fromEntries(Object.entries(values).sort(([left], [right]) => left.localeCompare(right))))
  174. }
  175. // TODO(bash-env-list-builtins): Include registry-owned built-ins before diagnostics,
  176. // prompt, or UI code treats list() as an exhaustive environment catalog.
  177. /**
  178. * Enumerate plugin-contributed variables without executing their resolvers.
  179. * @returns declarations sorted by environment variable name.
  180. */
  181. list(): BashEnvVariableInfo[] {
  182. return [...this.contributors.values()]
  183. .flatMap(contributor => Object.entries(contributor.variables).map(([key, variable]) => ({
  184. contributor: contributor.name,
  185. description: variable.description,
  186. key: key as DshEnvironmentKey,
  187. })))
  188. .sort((left, right) => left.key.localeCompare(right.key))
  189. }
  190. }
  191. /** Parsed tool args; execute validates value constraints absent from ParameterSchemaSpec. */
  192. interface BashToolArgs {
  193. command: string
  194. description: string
  195. timeoutMs?: number
  196. workdir?: string
  197. run_in_background?: boolean
  198. sandbox_permissions?: string
  199. justification?: string
  200. }
  201. function validateBashArgs(args: BashToolArgs): void {
  202. if (args.command.trim().length === 0) {
  203. throw new Error('invalid command: expected a non-empty string')
  204. }
  205. if (args.description.trim().length === 0) {
  206. throw new Error('invalid description: expected a non-empty string')
  207. }
  208. if (args.timeoutMs !== undefined && (!Number.isFinite(args.timeoutMs) || args.timeoutMs <= 0)) {
  209. throw new Error(`invalid timeoutMs: expected a positive number, got ${JSON.stringify(args.timeoutMs)}`)
  210. }
  211. // The escalation pairing (sandbox_permissions ⇔ justification, non-empty) is
  212. // the shared rule both enforcing families validate identically.
  213. validateEscalationArgs(args.sandbox_permissions, args.justification)
  214. }
  215. function bashDescription(backgroundEnabled: boolean, escalationModes: readonly SandboxMode[]): string {
  216. const background = backgroundEnabled
  217. ? '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`.'
  218. : 'Background execution is not available; long-running commands must finish within the timeout.'
  219. const base = 'Execute a bash command (`bash -c`) and return its stdout/stderr. '
  220. + 'Each call runs in a fresh shell: no state (cwd, variables, functions) persists between calls — '
  221. + 'pass `workdir` instead of using `cd`. Non-zero exits are reported as `[exit code: N]`. '
  222. + `Current harness environment facts are exposed through managed \`$${DSH_ENV_PREFIX}*\` variables; inspect them when needed. `
  223. + '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. '
  224. + 'Long output is truncated to its tail; the full output is saved to a file whose path is reported when available. '
  225. + background
  226. if (escalationModes.length === 0) return base
  227. return base + ' Attempting a command the sandbox may deny is safe and expected: run it and read the '
  228. + 'marker rather than assuming the denial. When a command is denied and a wider mode would let it '
  229. + 'succeed, escalate immediately in the same turn — the one sanctioned exception to a denial: retry '
  230. + 'the exact same command once with `sandbox_permissions` (the narrowest wider mode that suffices) '
  231. + 'plus a one-sentence `justification`. Do not detour through chat to ask permission first — the '
  232. + 'approval prompt raised by that retry is how the user consents. If the session states approval '
  233. + 'prompts are disabled, there is no exception: a denial is final — do not set `sandbox_permissions`. '
  234. + 'Never escalate speculatively: ground the request in a real denial — normally the one this command '
  235. + 'just hit; escalating up front is fine only when this session already denied the same access. '
  236. + 'A rejected escalation is final for that command — stop and explain, never work around '
  237. + 'it — but it does not forbid attempting or escalating other commands later.'
  238. }
  239. /**
  240. * Present foreground calls as terminals and background starts as generic cards.
  241. * The command remains the title on both paths; foreground cwd is passed through
  242. * for the bridge to resolve, while background descriptions remain card content.
  243. */
  244. type BashCallArgs = { command: string; description: string; workdir?: string; run_in_background?: boolean }
  245. function presentBashCall(args: BashCallArgs): GenericCallView | TerminalCallView {
  246. if (args.run_in_background === true) {
  247. return {
  248. card: 'generic',
  249. title: args.command,
  250. kind: 'execute',
  251. rawInput: args.command,
  252. content: [{ type: 'text', text: args.description }],
  253. }
  254. }
  255. return {
  256. card: 'terminal',
  257. title: args.command,
  258. description: args.description,
  259. ...args.workdir !== undefined ? { cwd: args.workdir } : {},
  260. }
  261. }
  262. /**
  263. * Present completed foreground output as a terminal; background acknowledgements
  264. * and execution errors use generic fenced output without an exit-status pill.
  265. */
  266. function presentBashResult(args: unknown, result: ToolResult): ToolResultView | undefined {
  267. const block = result.content.length === 1 ? result.content[0] : undefined
  268. if (block === undefined || block.type !== 'text') return undefined
  269. const raw = block.text
  270. const isBackground = typeof args === 'object' && args !== null && (args as { run_in_background?: unknown }).run_in_background === true
  271. // Background acknowledgements and errors have no terminal exit status.
  272. if (isBackground || result.isError) {
  273. return { card: 'generic', content: [{ type: 'text', text: `\`\`\`console\n${raw.replace(/\n+$/, '')}\n\`\`\`` }] }
  274. }
  275. // The exit marker becomes the card's exit pill, so it leaves the output body.
  276. const { body, ...exit } = parseExitStatus(raw)
  277. return { card: 'terminal', output: body, ...exit }
  278. }
  279. /**
  280. * Resolve an explicit workdir first, making a relative one session-workspace-relative;
  281. * otherwise use the filesystem identity of the session cwd and leave executor
  282. * defaulting as the fallback. A resolved sandbox-policy root wins so workdir
  283. * and confinement use the exact same per-call identity.
  284. */
  285. function resolveWorkdir(
  286. modelWorkdir: string | undefined,
  287. exec: { agent?: Agent },
  288. policyWorkspaceRoot?: string,
  289. ): string | undefined {
  290. const headerCwd = exec.agent?.session.header.cwd
  291. const sessionCwd = policyWorkspaceRoot ?? (headerCwd === undefined ? undefined : canonicalPath(headerCwd))
  292. if (modelWorkdir === undefined) return sessionCwd
  293. if (sessionCwd !== undefined && !isAbsolute(modelWorkdir)) {
  294. return resolvePath(sessionCwd, modelWorkdir)
  295. }
  296. return modelWorkdir
  297. }
  298. /** Detach the executor DTO from readonly seam interfaces into plain JSON data. */
  299. function canonicalBashResult(result: BashRunResult) {
  300. const output = (stream: BashRunResult['stdout']) => ({
  301. text: stream.text,
  302. truncated: stream.truncated,
  303. ...stream.spillPath !== undefined ? { spillPath: stream.spillPath } : {},
  304. })
  305. return {
  306. exitCode: result.exitCode,
  307. signal: result.signal,
  308. timedOut: result.timedOut,
  309. aborted: result.aborted,
  310. timeoutMs: result.timeoutMs,
  311. stdout: output(result.stdout),
  312. stderr: output(result.stderr),
  313. ...result.sandbox !== undefined ? {
  314. sandbox: {
  315. mode: result.sandbox.mode,
  316. denied: result.sandbox.denied,
  317. ...result.sandbox.enforcement !== undefined ? { enforcement: result.sandbox.enforcement } : {},
  318. ...result.sandbox.runnerFailed !== undefined ? { runnerFailed: result.sandbox.runnerFailed } : {},
  319. },
  320. } : {},
  321. }
  322. }
  323. /** Canonical background-handle properties shared by the bash output union. */
  324. const BACKGROUND_OUTPUT_PROPERTIES = {
  325. kind: { type: 'string', required: true, const: 'background' },
  326. taskId: { type: 'string', required: true },
  327. } as const
  328. export function apply(ctx: Context, config: Config = {}): void {
  329. const bashEnv = new BashEnvRegistry(ctx, config)
  330. bashEnv.register({
  331. name: 'session-persistence',
  332. variables: {
  333. [DSH_SESSION_JSONL_KEY]: {
  334. description: 'Absolute target path of the current session JSONL when the active persistence backend provides one.',
  335. },
  336. },
  337. resolve(execution) {
  338. const agent = execution.agent
  339. if (agent === undefined) return {}
  340. const location = ctx.get('sessionPersistence')?.locate(agent.session.header)
  341. return location?.kind === 'jsonl' ? { [DSH_SESSION_JSONL_KEY]: location.path } : {}
  342. },
  343. })
  344. const backgroundEnabled = config.enableRunInBackground ?? true
  345. const defaultMode = ctx.bash.sandboxMode
  346. const escalationModes: readonly SandboxMode[] = defaultMode === undefined ? [] : ESCALATION_TARGETS
  347. const sandboxPolicy: SandboxPolicyService | undefined = defaultMode === undefined ? undefined : ctx.get('sandboxPolicy')
  348. if (defaultMode !== undefined && sandboxPolicy === undefined) {
  349. throw new Error('tool-bash: the mounted bash executor confines but ctx.sandboxPolicy is missing')
  350. }
  351. /** Resolve the complete standing policy for this call when a confining executor is mounted. */
  352. const resolveSandboxPolicy = (exec: ToolExecution): SandboxExecutionPolicy | undefined =>
  353. sandboxPolicy?.resolve(exec.agent === undefined ? {} : { session: exec.agent.session })
  354. /**
  355. * Resolve a sandbox-escalation request through `ctx.approval` BEFORE
  356. * anything executes, delegating the shared fail-closed sequence (strict
  357. * widening, channel resolution, outcome mapping) to
  358. * {@link approveEscalation}. This tool contributes only the composition
  359. * guard (the fields are unadvertised without a sandboxing executor, yet
  360. * schema validation checks advertised keys only, so an unadvertised
  361. * `sandbox_permissions` still reaches execute) and the approval ingredients
  362. * The shared policy resolver is required whenever the executor advertises
  363. * confinement, so a split composition fails at tool-plugin load.
  364. */
  365. const approveBashEscalation = (
  366. mode: string,
  367. justification: string,
  368. exec: ToolExecution,
  369. standingPolicy: SandboxExecutionPolicy | undefined,
  370. ): Promise<SandboxMode> => {
  371. if (escalationModes.length === 0) {
  372. throw new Error('sandbox_permissions is not available in this composition (no sandboxing executor to escalate)')
  373. }
  374. const effectiveMode = (standingPolicy as SandboxExecutionPolicy).mode
  375. return approveEscalation(
  376. { requestedMode: mode, justification, effectiveMode, subject: 'command' },
  377. {
  378. approver: ctx.get('approval'),
  379. agent: exec.agent,
  380. callId: exec.callId,
  381. toolName: 'bash',
  382. signal: exec.signal,
  383. },
  384. )
  385. }
  386. // Cross-call guidance belongs in the prompt rather than one-call schema prose.
  387. ctx.systemPrompt.section({
  388. name: 'tool:bash',
  389. order: 105,
  390. text: 'Check the [exit code: N] marker on every bash result; investigate failures before moving on.',
  391. })
  392. ctx.tools.register(defineTool({
  393. name: 'bash',
  394. description: bashDescription(backgroundEnabled, escalationModes),
  395. parameters: {
  396. command: { type: 'string', required: true, description: 'The bash command to execute.' },
  397. description: {
  398. type: 'string',
  399. required: true,
  400. description: 'Clear, concise description of what this command does in active voice, '
  401. + '5-10 words (shown in the UI). Examples: "ls" → "List files in current directory"; '
  402. + '"git status" → "Show working tree status"; "npm install" → "Install package dependencies".',
  403. },
  404. timeoutMs: { type: 'number', description: 'Timeout in milliseconds. The executor applies its configured default and cap, and kills the command on expiry.' },
  405. workdir: { type: 'string', description: 'Working directory for this command. Defaults to the session workspace; a relative path is resolved against it.' },
  406. ...backgroundEnabled ? {
  407. 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.' },
  408. } : {},
  409. ...escalationModes.length > 0 ? {
  410. sandbox_permissions: {
  411. type: 'string' as const,
  412. enum: [...escalationModes],
  413. 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.',
  414. },
  415. justification: {
  416. type: 'string' as const,
  417. description: 'Required with sandbox_permissions: one sentence for the user explaining why this exact command needs the wider access.',
  418. },
  419. } : {},
  420. },
  421. output: {
  422. schema: {
  423. oneOf: [
  424. {
  425. type: 'object',
  426. additionalProperties: false,
  427. properties: BACKGROUND_OUTPUT_PROPERTIES,
  428. },
  429. {
  430. type: 'object',
  431. additionalProperties: false,
  432. properties: {
  433. kind: { type: 'string', required: true, const: 'foreground' },
  434. exitCode: { required: true, oneOf: [{ type: 'integer' }, { type: 'null' }] },
  435. signal: { required: true, oneOf: [{ type: 'string' }, { type: 'null' }] },
  436. timedOut: { type: 'boolean', required: true },
  437. aborted: { type: 'boolean', required: true },
  438. timeoutMs: { type: 'number', required: true },
  439. stdout: {
  440. type: 'object',
  441. additionalProperties: false,
  442. required: true,
  443. properties: {
  444. text: { type: 'string', required: true },
  445. truncated: { type: 'boolean', required: true },
  446. spillPath: { type: 'string' },
  447. },
  448. },
  449. stderr: {
  450. type: 'object',
  451. additionalProperties: false,
  452. required: true,
  453. properties: {
  454. text: { type: 'string', required: true },
  455. truncated: { type: 'boolean', required: true },
  456. spillPath: { type: 'string' },
  457. },
  458. },
  459. sandbox: {
  460. type: 'object',
  461. additionalProperties: false,
  462. properties: {
  463. mode: { type: 'string', required: true },
  464. denied: { type: 'boolean', required: true },
  465. enforcement: { type: 'string' },
  466. runnerFailed: { type: 'boolean' },
  467. },
  468. },
  469. },
  470. },
  471. ],
  472. },
  473. render: (_args, value) => [{
  474. type: 'text',
  475. text: value.kind === 'background'
  476. ? `started background task ${value.taskId}`
  477. : renderResult(value as { kind: 'foreground' } & BashRunResult, escalationModes),
  478. }],
  479. },
  480. async execute(args: BashToolArgs, exec) {
  481. validateBashArgs(args)
  482. // Description is display metadata; workdir defaults to the caller's session.
  483. const standingPolicy = resolveSandboxPolicy(exec)
  484. const approvedMode = args.sandbox_permissions !== undefined && args.justification !== undefined
  485. ? await approveBashEscalation(args.sandbox_permissions, args.justification, exec, standingPolicy)
  486. : undefined
  487. const policy = approvedMode === undefined
  488. ? standingPolicy
  489. : { ...(standingPolicy as SandboxExecutionPolicy), mode: approvedMode }
  490. const workdir = resolveWorkdir(args.workdir, exec, standingPolicy?.workspaceRoot)
  491. const dshEnv = bashEnv.collect(exec)
  492. const request = {
  493. command: args.command,
  494. ...workdir !== undefined ? { workdir } : {},
  495. ...args.timeoutMs !== undefined ? { timeoutMs: args.timeoutMs } : {},
  496. dshEnv,
  497. ...policy !== undefined ? { sandboxPolicy: policy } : {},
  498. }
  499. if (args.run_in_background === true) {
  500. // Undeclared keys are allowed, so schema omission also needs enforcement.
  501. if (!backgroundEnabled) {
  502. throw new Error('run_in_background is disabled for this deployment (enableRunInBackground: false)')
  503. }
  504. const tasks = ctx.get('tasks')
  505. if (tasks === undefined) {
  506. throw new Error('background tasks unavailable: load @deepseek-ai/dsh-tasks and @deepseek-ai/dsh-tool-tasks')
  507. }
  508. // The caller owns cancellation until ctx.tasks commits detached ownership.
  509. if (exec.signal.aborted) {
  510. const error = new HarnessError('tool call aborted', TOOL_ABORTED)
  511. error.name = 'AbortError'
  512. throw error
  513. }
  514. // Task preflight finishes before the starter can spawn a process.
  515. const id = tasks.start({
  516. kind: 'bash',
  517. label: args.command,
  518. ...exec.agent ? { owner: exec.agent } : {},
  519. run: () => {
  520. const proc = ctx.bash.start(ctx.bash.resolve(request))
  521. return {
  522. cancel: () => void proc.kill(),
  523. done: proc.done.then(() => processOutcome(proc)),
  524. readOutput: () => renderProcessRead(proc.readOutput(), proc.sandbox, escalationModes),
  525. }
  526. },
  527. })
  528. return { kind: 'background' as const, taskId: id }
  529. }
  530. const result = await ctx.bash.run(ctx.bash.resolve({
  531. ...request,
  532. signal: exec.signal,
  533. }))
  534. if (result.aborted) throw new Error('command aborted')
  535. return { kind: 'foreground' as const, ...canonicalBashResult(result) }
  536. },
  537. presentCall: presentBashCall,
  538. presentResult: presentBashResult,
  539. }))
  540. }