index.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. /**
  2. * Model-facing Consumer of the `ctx.shell` capability seam. Background calls
  3. * register process handles with `ctx.jobs`; their work uses job 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 § Where new behavior goes.
  8. * @module @deepseek-ai/dsh-tool-bash
  9. */
  10. import type { Context } from '@deepseek-ai/cordis'
  11. import z from '@deepseek-ai/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-jobs'
  18. import type {} from '@deepseek-ai/dsh-user-approval'
  19. import type {} from '@deepseek-ai/dsh-shell-env'
  20. import type { SandboxExecutionPolicy, SandboxMode } from '@deepseek-ai/dsh-sandbox'
  21. import { ESCALATION_TARGETS, approveEscalation, canonicalPath, validateEscalationArgs } from '@deepseek-ai/dsh-sandbox'
  22. import type { SandboxPolicyService } from '@deepseek-ai/dsh-sandbox-policy'
  23. import { DSH_ENV_PREFIX } from '@deepseek-ai/dsh-shell'
  24. import type { ShellRunResult } from '@deepseek-ai/dsh-shell'
  25. import { processOutcome } from './background.ts'
  26. import { parseExitStatus, renderProcessRead, renderResult } from './render.ts'
  27. export const name = 'tool-bash'
  28. export const inject = ['tools', 'shell', 'systemPrompt', 'shellEnv']
  29. /** Configuration for the bash tool. */
  30. export interface Config {
  31. /** Expose `run_in_background` (default true); disabled calls are also rejected. */
  32. enableRunInBackground?: boolean
  33. }
  34. /** Runtime configuration schema for the bash tool plugin. */
  35. export const Config: z<Config> = z.object({
  36. enableRunInBackground: z.boolean().default(true),
  37. })
  38. /** Parsed tool args; execute validates value constraints absent from ParameterSchemaSpec. */
  39. interface BashToolArgs {
  40. command: string
  41. description: string
  42. timeoutMs?: number
  43. workdir?: string
  44. run_in_background?: boolean
  45. sandbox_permissions?: string
  46. justification?: string
  47. }
  48. function validateBashArgs(args: BashToolArgs): void {
  49. if (args.command.trim().length === 0) {
  50. throw new Error('invalid command: expected a non-empty string')
  51. }
  52. if (args.description.trim().length === 0) {
  53. throw new Error('invalid description: expected a non-empty string')
  54. }
  55. if (args.timeoutMs !== undefined && (!Number.isFinite(args.timeoutMs) || args.timeoutMs <= 0)) {
  56. throw new Error(`invalid timeoutMs: expected a positive number, got ${JSON.stringify(args.timeoutMs)}`)
  57. }
  58. // The escalation pairing (sandbox_permissions ⇔ justification, non-empty) is
  59. // the shared rule both enforcing families validate identically.
  60. validateEscalationArgs(args.sandbox_permissions, args.justification)
  61. }
  62. function bashDescription(backgroundEnabled: boolean, escalationModes: readonly SandboxMode[]): string {
  63. const background = backgroundEnabled
  64. ? 'Set `run_in_background: true` for long-running commands: the call returns a job id immediately; read its output with `job_output` and stop it with `job_kill`.'
  65. : 'Background execution is not available; long-running commands must finish within the timeout.'
  66. const base = 'Execute a bash command (`bash -c`) and return its stdout/stderr. '
  67. + 'Each call runs in a fresh shell: no state (cwd, variables, functions) persists between calls — '
  68. + 'pass `workdir` instead of using `cd`. Non-zero exits are reported as `[exit code: N]`. '
  69. + `Current harness environment facts are exposed through managed \`$${DSH_ENV_PREFIX}*\` variables; inspect them when needed. `
  70. + '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. '
  71. + 'Long output is truncated to its tail; the full output is saved to a file whose path is reported when available. '
  72. + background
  73. if (escalationModes.length === 0) return base
  74. return base + ' Attempting a command the sandbox may deny is safe and expected: run it and read the '
  75. + 'marker rather than assuming the denial. When a command is denied and a wider mode would let it '
  76. + 'succeed, escalate immediately in the same turn — the one sanctioned exception to a denial: retry '
  77. + 'the exact same command once with `sandbox_permissions` (the narrowest wider mode that suffices) '
  78. + 'plus a one-sentence `justification`. Do not detour through chat to ask permission first — the '
  79. + 'approval prompt raised by that retry is how the user consents. If the session states approval '
  80. + 'prompts are disabled, there is no exception: a denial is final — do not set `sandbox_permissions`. '
  81. + 'Never escalate speculatively: ground the request in a real denial — normally the one this command '
  82. + 'just hit; escalating up front is fine only when this session already denied the same access. '
  83. + 'A rejected escalation is final for that command — stop and explain, never work around '
  84. + 'it — but it does not forbid attempting or escalating other commands later.'
  85. }
  86. /**
  87. * Present foreground calls as terminals and background starts as generic cards.
  88. * The command remains the title on both paths; foreground cwd is passed through
  89. * for the bridge to resolve, while background descriptions remain card content.
  90. */
  91. type BashCallArgs = { command: string; description: string; workdir?: string; run_in_background?: boolean }
  92. function presentBashCall(args: BashCallArgs): GenericCallView | TerminalCallView {
  93. if (args.run_in_background === true) {
  94. return {
  95. card: 'generic',
  96. title: args.command,
  97. kind: 'execute',
  98. rawInput: args.command,
  99. content: [{ type: 'text', text: args.description }],
  100. }
  101. }
  102. return {
  103. card: 'terminal',
  104. title: args.command,
  105. description: args.description,
  106. ...args.workdir !== undefined ? { cwd: args.workdir } : {},
  107. }
  108. }
  109. /**
  110. * Present completed foreground output as a terminal; background acknowledgements
  111. * and execution errors use generic fenced output without an exit-status pill.
  112. */
  113. function presentBashResult(args: unknown, result: ToolResult): ToolResultView | undefined {
  114. const block = result.content.length === 1 ? result.content[0] : undefined
  115. if (block === undefined || block.type !== 'text') return undefined
  116. const raw = block.text
  117. const isBackground = typeof args === 'object' && args !== null && (args as { run_in_background?: unknown }).run_in_background === true
  118. // Background acknowledgements and errors have no terminal exit status.
  119. if (isBackground || result.isError) {
  120. return { card: 'generic', content: [{ type: 'text', text: `\`\`\`console\n${raw.replace(/\n+$/, '')}\n\`\`\`` }] }
  121. }
  122. // The exit marker becomes the card's exit pill, so it leaves the output body.
  123. const { body, ...exit } = parseExitStatus(raw)
  124. return { card: 'terminal', output: body, ...exit }
  125. }
  126. /**
  127. * Resolve an explicit workdir first, making a relative one session-workspace-relative;
  128. * otherwise use the filesystem identity of the session cwd and leave executor
  129. * defaulting as the fallback. A resolved sandbox-policy root wins so workdir
  130. * and confinement use the exact same per-call identity.
  131. */
  132. function resolveWorkdir(
  133. modelWorkdir: string | undefined,
  134. exec: { agent?: Agent },
  135. policyWorkspaceRoot?: string,
  136. ): string | undefined {
  137. const headerCwd = exec.agent?.session.header.cwd
  138. const sessionCwd = policyWorkspaceRoot ?? (headerCwd === undefined ? undefined : canonicalPath(headerCwd))
  139. if (modelWorkdir === undefined) return sessionCwd
  140. if (sessionCwd !== undefined && !isAbsolute(modelWorkdir)) {
  141. return resolvePath(sessionCwd, modelWorkdir)
  142. }
  143. return modelWorkdir
  144. }
  145. /** Detach the executor DTO from readonly Service Definition types into plain JSON data. */
  146. function canonicalBashResult(result: ShellRunResult) {
  147. const output = (stream: ShellRunResult['stdout']) => ({
  148. text: stream.text,
  149. truncated: stream.truncated,
  150. ...stream.spillPath !== undefined ? { spillPath: stream.spillPath } : {},
  151. })
  152. return {
  153. exitCode: result.exitCode,
  154. signal: result.signal,
  155. timedOut: result.timedOut,
  156. aborted: result.aborted,
  157. timeoutMs: result.timeoutMs,
  158. stdout: output(result.stdout),
  159. stderr: output(result.stderr),
  160. ...result.sandbox !== undefined ? {
  161. sandbox: {
  162. mode: result.sandbox.mode,
  163. denied: result.sandbox.denied,
  164. ...result.sandbox.enforcement !== undefined ? { enforcement: result.sandbox.enforcement } : {},
  165. ...result.sandbox.runnerFailed !== undefined ? { runnerFailed: result.sandbox.runnerFailed } : {},
  166. },
  167. } : {},
  168. }
  169. }
  170. /** Canonical background-handle properties shared by the bash output union. */
  171. const BACKGROUND_OUTPUT_PROPERTIES = {
  172. kind: { type: 'string', required: true, const: 'background' },
  173. jobId: { type: 'string', required: true },
  174. } as const
  175. export function apply(ctx: Context, config: Config = {}): void {
  176. const backgroundEnabled = config.enableRunInBackground ?? true
  177. const defaultMode = ctx.shell.sandboxMode
  178. const escalationModes: readonly SandboxMode[] = defaultMode === undefined ? [] : ESCALATION_TARGETS
  179. const sandboxPolicy: SandboxPolicyService | undefined = defaultMode === undefined ? undefined : ctx.get('sandboxPolicy')
  180. if (defaultMode !== undefined && sandboxPolicy === undefined) {
  181. throw new Error('tool-bash: the mounted bash executor confines but ctx.sandboxPolicy is missing')
  182. }
  183. /** Resolve the complete standing policy for this call when a confining executor is mounted. */
  184. const resolveSandboxPolicy = (exec: ToolExecution): SandboxExecutionPolicy | undefined =>
  185. sandboxPolicy?.resolve(exec.agent === undefined ? {} : { session: exec.agent.session })
  186. /**
  187. * Resolve a sandbox-escalation request through `ctx.approval` BEFORE
  188. * anything executes, delegating the shared fail-closed sequence (strict
  189. * widening, channel resolution, outcome mapping) to
  190. * {@link approveEscalation}. This tool contributes only the composition
  191. * guard (the fields are unadvertised without a sandboxing executor, yet
  192. * schema validation checks advertised keys only, so an unadvertised
  193. * `sandbox_permissions` still reaches execute) and the approval
  194. * ingredients. The shared policy resolver is required whenever the executor
  195. * advertises confinement, so a split composition fails at tool-plugin load.
  196. */
  197. const approveBashEscalation = (
  198. mode: string,
  199. justification: string,
  200. exec: ToolExecution,
  201. standingPolicy: SandboxExecutionPolicy | undefined,
  202. ): Promise<SandboxMode> => {
  203. if (escalationModes.length === 0) {
  204. throw new Error('sandbox_permissions is not available in this composition (no sandboxing executor to escalate)')
  205. }
  206. const effectiveMode = (standingPolicy as SandboxExecutionPolicy).mode
  207. return approveEscalation(
  208. { requestedMode: mode, justification, effectiveMode, subject: 'command' },
  209. {
  210. approver: ctx.get('approval'),
  211. agent: exec.agent,
  212. callId: exec.callId,
  213. toolName: 'bash',
  214. signal: exec.signal,
  215. },
  216. )
  217. }
  218. // Cross-call guidance belongs in the prompt rather than one-call schema prose.
  219. ctx.systemPrompt.section({
  220. name: 'tool:bash',
  221. order: ctx.systemPrompt.getSectionOrder('TOOL_BASH'),
  222. text: 'Check the [exit code: N] marker on every bash result; investigate failures before moving on.',
  223. })
  224. ctx.tools.register(defineTool({
  225. name: 'bash',
  226. description: bashDescription(backgroundEnabled, escalationModes),
  227. parameters: {
  228. command: { type: 'string', required: true, description: 'The bash command to execute.' },
  229. description: {
  230. type: 'string',
  231. required: true,
  232. description: 'Clear, concise description of what this command does in active voice, '
  233. + '5-10 words (shown in the UI). Examples: "ls" → "List files in current directory"; '
  234. + '"git status" → "Show working tree status"; "npm install" → "Install package dependencies".',
  235. },
  236. timeoutMs: { type: 'number', description: 'Timeout in milliseconds. The executor applies its configured default and cap, and kills the command on expiry.' },
  237. workdir: { type: 'string', description: 'Working directory for this command. Defaults to the session workspace; a relative path is resolved against it.' },
  238. ...backgroundEnabled ? {
  239. run_in_background: { type: 'boolean' as const, description: 'Run in the background and return a job id immediately (collect with job_output, stop with job_kill). No timeout applies.' },
  240. } : {},
  241. ...escalationModes.length > 0 ? {
  242. sandbox_permissions: {
  243. type: 'string' as const,
  244. enum: [...escalationModes],
  245. 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.',
  246. },
  247. justification: {
  248. type: 'string' as const,
  249. description: 'Required with sandbox_permissions: one sentence for the user explaining why this exact command needs the wider access.',
  250. },
  251. } : {},
  252. },
  253. output: {
  254. schema: {
  255. oneOf: [
  256. {
  257. type: 'object',
  258. additionalProperties: false,
  259. properties: BACKGROUND_OUTPUT_PROPERTIES,
  260. },
  261. {
  262. type: 'object',
  263. additionalProperties: false,
  264. properties: {
  265. kind: { type: 'string', required: true, const: 'foreground' },
  266. exitCode: { required: true, oneOf: [{ type: 'integer' }, { type: 'null' }] },
  267. signal: { required: true, oneOf: [{ type: 'string' }, { type: 'null' }] },
  268. timedOut: { type: 'boolean', required: true },
  269. aborted: { type: 'boolean', required: true },
  270. timeoutMs: { type: 'number', required: true },
  271. stdout: {
  272. type: 'object',
  273. additionalProperties: false,
  274. required: true,
  275. properties: {
  276. text: { type: 'string', required: true },
  277. truncated: { type: 'boolean', required: true },
  278. spillPath: { type: 'string' },
  279. },
  280. },
  281. stderr: {
  282. type: 'object',
  283. additionalProperties: false,
  284. required: true,
  285. properties: {
  286. text: { type: 'string', required: true },
  287. truncated: { type: 'boolean', required: true },
  288. spillPath: { type: 'string' },
  289. },
  290. },
  291. sandbox: {
  292. type: 'object',
  293. additionalProperties: false,
  294. properties: {
  295. mode: { type: 'string', required: true },
  296. denied: { type: 'boolean', required: true },
  297. enforcement: { type: 'string' },
  298. runnerFailed: { type: 'boolean' },
  299. },
  300. },
  301. },
  302. },
  303. ],
  304. },
  305. render: (_args, value) => [{
  306. type: 'text',
  307. text: value.kind === 'background'
  308. ? `started background job ${value.jobId}`
  309. : renderResult(value as { kind: 'foreground' } & ShellRunResult, escalationModes),
  310. }],
  311. },
  312. async execute(args: BashToolArgs, exec) {
  313. validateBashArgs(args)
  314. // Description is display metadata; workdir defaults to the caller's session.
  315. const standingPolicy = resolveSandboxPolicy(exec)
  316. const approvedMode = args.sandbox_permissions !== undefined && args.justification !== undefined
  317. ? await approveBashEscalation(args.sandbox_permissions, args.justification, exec, standingPolicy)
  318. : undefined
  319. const policy = approvedMode === undefined
  320. ? standingPolicy
  321. : { ...(standingPolicy as SandboxExecutionPolicy), mode: approvedMode }
  322. const workdir = resolveWorkdir(args.workdir, exec, standingPolicy?.workspaceRoot)
  323. const dshEnv = ctx.shellEnv.collect(exec)
  324. const request = {
  325. command: args.command,
  326. ...workdir !== undefined ? { workdir } : {},
  327. ...args.timeoutMs !== undefined ? { timeoutMs: args.timeoutMs } : {},
  328. dshEnv,
  329. ...policy !== undefined ? { sandboxPolicy: policy } : {},
  330. }
  331. if (args.run_in_background === true) {
  332. // Undeclared keys are allowed, so schema omission also needs enforcement.
  333. if (!backgroundEnabled) {
  334. throw new Error('run_in_background is disabled for this deployment (enableRunInBackground: false)')
  335. }
  336. const jobs = ctx.get('jobs')
  337. if (jobs === undefined) {
  338. throw new Error('background jobs unavailable: load @deepseek-ai/dsh-jobs and @deepseek-ai/dsh-tool-jobs')
  339. }
  340. // The caller owns cancellation until ctx.jobs commits detached ownership.
  341. if (exec.signal.aborted) {
  342. const error = new HarnessError('tool call aborted', TOOL_ABORTED)
  343. error.name = 'AbortError'
  344. throw error
  345. }
  346. // Task preflight finishes before the starter can spawn a process.
  347. const id = jobs.start({
  348. kind: 'bash',
  349. label: args.command,
  350. ...exec.agent ? { owner: exec.agent } : {},
  351. run: () => {
  352. const proc = ctx.shell.start(ctx.shell.resolve(request))
  353. return {
  354. cancel: () => void proc.kill(),
  355. done: proc.done.then(() => processOutcome(proc)),
  356. readOutput: () => renderProcessRead(proc.readOutput(), proc.sandbox, escalationModes),
  357. }
  358. },
  359. })
  360. return { kind: 'background' as const, jobId: id }
  361. }
  362. const result = await ctx.shell.run(ctx.shell.resolve({
  363. ...request,
  364. signal: exec.signal,
  365. }))
  366. if (result.aborted) {
  367. const error = new HarnessError('tool call aborted', TOOL_ABORTED)
  368. error.name = 'AbortError'
  369. throw error
  370. }
  371. return { kind: 'foreground' as const, ...canonicalBashResult(result) }
  372. },
  373. presentCall: presentBashCall,
  374. presentResult: presentBashResult,
  375. }))
  376. }