index.ts 21 KB

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