index.ts 18 KB

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