index.ts 22 KB

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