index.ts 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  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. return { card: 'terminal', output: raw, ...parseExitStatus(raw) }
  276. }
  277. /**
  278. * Resolve an explicit workdir first, making a relative one session-workspace-relative;
  279. * otherwise use the filesystem identity of the session cwd and leave executor
  280. * defaulting as the fallback. A resolved sandbox-policy root wins so workdir
  281. * and confinement use the exact same per-call identity.
  282. */
  283. function resolveWorkdir(
  284. modelWorkdir: string | undefined,
  285. exec: { agent?: Agent },
  286. policyWorkspaceRoot?: string,
  287. ): string | undefined {
  288. const headerCwd = exec.agent?.session.header.cwd
  289. const sessionCwd = policyWorkspaceRoot ?? (headerCwd === undefined ? undefined : canonicalPath(headerCwd))
  290. if (modelWorkdir === undefined) return sessionCwd
  291. if (sessionCwd !== undefined && !isAbsolute(modelWorkdir)) {
  292. return resolvePath(sessionCwd, modelWorkdir)
  293. }
  294. return modelWorkdir
  295. }
  296. /** Detach the executor DTO from readonly seam interfaces into plain JSON data. */
  297. function canonicalBashResult(result: BashRunResult) {
  298. const output = (stream: BashRunResult['stdout']) => ({
  299. text: stream.text,
  300. truncated: stream.truncated,
  301. ...stream.spillPath !== undefined ? { spillPath: stream.spillPath } : {},
  302. })
  303. return {
  304. exitCode: result.exitCode,
  305. signal: result.signal,
  306. timedOut: result.timedOut,
  307. aborted: result.aborted,
  308. timeoutMs: result.timeoutMs,
  309. stdout: output(result.stdout),
  310. stderr: output(result.stderr),
  311. ...result.sandbox !== undefined ? {
  312. sandbox: {
  313. mode: result.sandbox.mode,
  314. denied: result.sandbox.denied,
  315. ...result.sandbox.enforcement !== undefined ? { enforcement: result.sandbox.enforcement } : {},
  316. ...result.sandbox.runnerFailed !== undefined ? { runnerFailed: result.sandbox.runnerFailed } : {},
  317. },
  318. } : {},
  319. }
  320. }
  321. /** Canonical background-handle properties shared by the bash output union. */
  322. const BACKGROUND_OUTPUT_PROPERTIES = {
  323. kind: { type: 'string', required: true, const: 'background' },
  324. taskId: { type: 'string', required: true },
  325. } as const
  326. export function apply(ctx: Context, config: Config = {}): void {
  327. const bashEnv = new BashEnvRegistry(ctx, config)
  328. bashEnv.register({
  329. name: 'session-persistence',
  330. variables: {
  331. [DSH_SESSION_JSONL_KEY]: {
  332. description: 'Absolute target path of the current session JSONL when the active persistence backend provides one.',
  333. },
  334. },
  335. resolve(execution) {
  336. const agent = execution.agent
  337. if (agent === undefined) return {}
  338. const location = ctx.get('sessionPersistence')?.locate(agent.session.header)
  339. return location?.kind === 'jsonl' ? { [DSH_SESSION_JSONL_KEY]: location.path } : {}
  340. },
  341. })
  342. const backgroundEnabled = config.enableRunInBackground ?? true
  343. const defaultMode = ctx.bash.sandboxMode
  344. const escalationModes: readonly SandboxMode[] = defaultMode === undefined ? [] : ESCALATION_TARGETS
  345. const sandboxPolicy: SandboxPolicyService | undefined = defaultMode === undefined ? undefined : ctx.get('sandboxPolicy')
  346. if (defaultMode !== undefined && sandboxPolicy === undefined) {
  347. throw new Error('tool-bash: the mounted bash executor confines but ctx.sandboxPolicy is missing')
  348. }
  349. /** Resolve the complete standing policy for this call when a confining executor is mounted. */
  350. const resolveSandboxPolicy = (exec: ToolExecution): SandboxExecutionPolicy | undefined =>
  351. sandboxPolicy?.resolve(exec.agent === undefined ? {} : { session: exec.agent.session })
  352. /**
  353. * Resolve a sandbox-escalation request through `ctx.approval` BEFORE
  354. * anything executes, delegating the shared fail-closed sequence (strict
  355. * widening, channel resolution, outcome mapping) to
  356. * {@link approveEscalation}. This tool contributes only the composition
  357. * guard (the fields are unadvertised without a sandboxing executor, yet
  358. * schema validation checks advertised keys only, so an unadvertised
  359. * `sandbox_permissions` still reaches execute) and the approval ingredients
  360. * The shared policy resolver is required whenever the executor advertises
  361. * confinement, so a split composition fails at tool-plugin load.
  362. */
  363. const approveBashEscalation = (
  364. mode: string,
  365. justification: string,
  366. exec: ToolExecution,
  367. standingPolicy: SandboxExecutionPolicy | undefined,
  368. ): Promise<SandboxMode> => {
  369. if (escalationModes.length === 0) {
  370. throw new Error('sandbox_permissions is not available in this composition (no sandboxing executor to escalate)')
  371. }
  372. const effectiveMode = (standingPolicy as SandboxExecutionPolicy).mode
  373. return approveEscalation(
  374. { requestedMode: mode, justification, effectiveMode, subject: 'command' },
  375. {
  376. approver: ctx.get('approval'),
  377. agent: exec.agent,
  378. callId: exec.callId,
  379. toolName: 'bash',
  380. signal: exec.signal,
  381. },
  382. )
  383. }
  384. // Cross-call guidance belongs in the prompt rather than one-call schema prose.
  385. ctx.systemPrompt.section({
  386. name: 'tool:bash',
  387. order: 105,
  388. text: 'Check the [exit code: N] marker on every bash result; investigate failures before moving on.',
  389. })
  390. ctx.tools.register(defineTool({
  391. name: 'bash',
  392. description: bashDescription(backgroundEnabled, escalationModes),
  393. parameters: {
  394. command: { type: 'string', required: true, description: 'The bash command to execute.' },
  395. description: {
  396. type: 'string',
  397. required: true,
  398. description: 'Clear, concise description of what this command does in active voice, '
  399. + '5-10 words (shown in the UI). Examples: "ls" → "List files in current directory"; '
  400. + '"git status" → "Show working tree status"; "npm install" → "Install package dependencies".',
  401. },
  402. timeoutMs: { type: 'number', description: 'Timeout in milliseconds. The executor applies its configured default and cap, and kills the command on expiry.' },
  403. workdir: { type: 'string', description: 'Working directory for this command. Defaults to the session workspace; a relative path is resolved against it.' },
  404. ...backgroundEnabled ? {
  405. 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.' },
  406. } : {},
  407. ...escalationModes.length > 0 ? {
  408. sandbox_permissions: {
  409. type: 'string' as const,
  410. enum: [...escalationModes],
  411. 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.',
  412. },
  413. justification: {
  414. type: 'string' as const,
  415. description: 'Required with sandbox_permissions: one sentence for the user explaining why this exact command needs the wider access.',
  416. },
  417. } : {},
  418. },
  419. output: {
  420. schema: {
  421. oneOf: [
  422. {
  423. type: 'object',
  424. additionalProperties: false,
  425. properties: BACKGROUND_OUTPUT_PROPERTIES,
  426. },
  427. {
  428. type: 'object',
  429. additionalProperties: false,
  430. properties: {
  431. kind: { type: 'string', required: true, const: 'foreground' },
  432. exitCode: { required: true, oneOf: [{ type: 'integer' }, { type: 'null' }] },
  433. signal: { required: true, oneOf: [{ type: 'string' }, { type: 'null' }] },
  434. timedOut: { type: 'boolean', required: true },
  435. aborted: { type: 'boolean', required: true },
  436. timeoutMs: { type: 'number', required: true },
  437. stdout: {
  438. type: 'object',
  439. additionalProperties: false,
  440. required: true,
  441. properties: {
  442. text: { type: 'string', required: true },
  443. truncated: { type: 'boolean', required: true },
  444. spillPath: { type: 'string' },
  445. },
  446. },
  447. stderr: {
  448. type: 'object',
  449. additionalProperties: false,
  450. required: true,
  451. properties: {
  452. text: { type: 'string', required: true },
  453. truncated: { type: 'boolean', required: true },
  454. spillPath: { type: 'string' },
  455. },
  456. },
  457. sandbox: {
  458. type: 'object',
  459. additionalProperties: false,
  460. properties: {
  461. mode: { type: 'string', required: true },
  462. denied: { type: 'boolean', required: true },
  463. enforcement: { type: 'string' },
  464. runnerFailed: { type: 'boolean' },
  465. },
  466. },
  467. },
  468. },
  469. ],
  470. },
  471. render: (_args, value) => [{
  472. type: 'text',
  473. text: value.kind === 'background'
  474. ? `started background task ${value.taskId}`
  475. : renderResult(value as { kind: 'foreground' } & BashRunResult, escalationModes),
  476. }],
  477. },
  478. async execute(args: BashToolArgs, exec) {
  479. validateBashArgs(args)
  480. // Description is display metadata; workdir defaults to the caller's session.
  481. const standingPolicy = resolveSandboxPolicy(exec)
  482. const approvedMode = args.sandbox_permissions !== undefined && args.justification !== undefined
  483. ? await approveBashEscalation(args.sandbox_permissions, args.justification, exec, standingPolicy)
  484. : undefined
  485. const policy = approvedMode === undefined
  486. ? standingPolicy
  487. : { ...(standingPolicy as SandboxExecutionPolicy), mode: approvedMode }
  488. const workdir = resolveWorkdir(args.workdir, exec, standingPolicy?.workspaceRoot)
  489. const dshEnv = bashEnv.collect(exec)
  490. const request = {
  491. command: args.command,
  492. ...workdir !== undefined ? { workdir } : {},
  493. ...args.timeoutMs !== undefined ? { timeoutMs: args.timeoutMs } : {},
  494. dshEnv,
  495. ...policy !== undefined ? { sandboxPolicy: policy } : {},
  496. }
  497. if (args.run_in_background === true) {
  498. // Undeclared keys are allowed, so schema omission also needs enforcement.
  499. if (!backgroundEnabled) {
  500. throw new Error('run_in_background is disabled for this deployment (enableRunInBackground: false)')
  501. }
  502. const tasks = ctx.get('tasks')
  503. if (tasks === undefined) {
  504. throw new Error('background tasks unavailable: load @deepseek-ai/dsh-tasks and @deepseek-ai/dsh-tool-tasks')
  505. }
  506. // The caller owns cancellation until ctx.tasks commits detached ownership.
  507. if (exec.signal.aborted) {
  508. const error = new HarnessError('tool call aborted', TOOL_ABORTED)
  509. error.name = 'AbortError'
  510. throw error
  511. }
  512. // Task preflight finishes before the starter can spawn a process.
  513. const id = tasks.start({
  514. kind: 'bash',
  515. label: args.command,
  516. ...exec.agent ? { owner: exec.agent } : {},
  517. run: () => {
  518. const proc = ctx.bash.start(ctx.bash.resolve(request))
  519. return {
  520. cancel: () => void proc.kill(),
  521. done: proc.done.then(() => processOutcome(proc)),
  522. readOutput: () => renderProcessRead(proc.readOutput(), proc.sandbox, escalationModes),
  523. }
  524. },
  525. })
  526. return { kind: 'background' as const, taskId: id }
  527. }
  528. const result = await ctx.bash.run(ctx.bash.resolve({
  529. ...request,
  530. signal: exec.signal,
  531. }))
  532. if (result.aborted) throw new Error('command aborted')
  533. return { kind: 'foreground' as const, ...canonicalBashResult(result) }
  534. },
  535. presentCall: presentBashCall,
  536. presentResult: presentBashResult,
  537. }))
  538. }