code-mode.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. /**
  2. * Code Mode `run_code` transport. Programs call the registry's agent-visible
  3. * tools through nested, sequential executions; each sub-dispatch is logged for
  4. * reconstruction, while only the outer curated result enters model history.
  5. * @module @deepseek-ai/dsh-tools/src/code-mode
  6. */
  7. import { parse } from 'node:path'
  8. import { CallId, HarnessError } from '@deepseek-ai/dsh-llm'
  9. import type { ContentBlock } from '@deepseek-ai/dsh-llm'
  10. import type { CodeBindingFunction, CodeRunResult, CodeRuntime } from '@deepseek-ai/dsh-code-runtime'
  11. import { snapshotJsonValue } from '@deepseek-ai/dsh-session'
  12. import type { JsonValue } from '@deepseek-ai/dsh-session'
  13. import { defineTool } from './schema.ts'
  14. import type { ToolDefinition, ToolRegistry } from './index.ts'
  15. declare module '@deepseek-ai/dsh-session' {
  16. interface SessionEventMap {
  17. /**
  18. * One bridged sub-dispatch from a `run_code` program: the parent
  19. * `run_code` call id, the deterministic sub-call id
  20. * (`<parent>:code:<n>`), the tool `name` with its JSON-normalized
  21. * `arguments` — the exact value dispatched, normalized BEFORE dispatch,
  22. * so this append can never fail on payload shape — whether the sub-call
  23. * errored, and a bounded `resultSummary` of its model-facing text. Before
  24. * bounding, occurrences of a non-root session workspace path are
  25. * normalized to `.` so host-specific absolute path lengths cannot change
  26. * the summary.
  27. * Log-only: `deriveMessages()` ignores it, so sub-calls never re-enter
  28. * model context; persistence and UIs get every call. Appended inside the
  29. * parent `run_code`'s execution (the bridge drains its queue before
  30. * returning), so the turn-enclosure invariant holds by construction.
  31. */
  32. 'tool/code-dispatch': { parentCallId: CallId; subCallId: CallId; name: string; arguments: unknown; isError: boolean; resultSummary: string }
  33. }
  34. }
  35. /** The model-facing name of the Code Mode tool. */
  36. export const RUN_CODE_NAME = 'run_code'
  37. /** The `tools:sdk` section order: inside the 100–199 tool-guidance band, after per-tool guidance sections. */
  38. export const SDK_SECTION_ORDER = 150
  39. /**
  40. * Thrown by `run_code` when the program run itself failed — a program
  41. * exception, a budget expiry, an abort, or substrate death. Extends
  42. * {@link HarnessError} (`code: 'CODE_RUN_FAILED'`); the registry's execution
  43. * pipeline converts it into a structured `isError` result whose text carries
  44. * the failure kind plus the captured logs, so the model can self-correct.
  45. */
  46. export class CodeRunFailedError extends HarnessError {
  47. constructor(message: string) {
  48. super(message, 'CODE_RUN_FAILED')
  49. this.name = 'CodeRunFailedError'
  50. }
  51. }
  52. /**
  53. * Cap for a `tool/code-dispatch` event's `resultSummary`. A log-ergonomics
  54. * constant, not config: the full result already flows to the program; the
  55. * summary exists so log readers see what a sub-call returned at a glance.
  56. */
  57. const SUMMARY_MAX_CHARS = 200
  58. /** Join Native content for the bounded durable sub-dispatch summary; non-text blocks become diagnostic placeholders. */
  59. function textOf(content: ContentBlock[]): string {
  60. return content
  61. .map((block) => {
  62. switch (block.type) {
  63. case 'text': return block.text
  64. // ContentBlockMap is merge-extensible — future block kinds land here
  65. // deliberately (no assertNever on merge-extensible unions).
  66. default: return `[${block.type} content]`
  67. }
  68. })
  69. .join('\n')
  70. }
  71. /** Normalize workspace paths, then bound a sub-call's model-facing text for its durable log summary. */
  72. function summarize(text: string, cwd: string | undefined): string {
  73. const stableText = cwd === undefined || cwd === parse(cwd).root
  74. ? text
  75. : text.replaceAll(cwd, '.')
  76. return stableText.length > SUMMARY_MAX_CHARS ? `${stableText.slice(0, SUMMARY_MAX_CHARS)}…` : stableText
  77. }
  78. /**
  79. * Snapshot one binding call's argument as lossless JSON, then clone it into
  80. * independent dispatch/log values so a tool mutation cannot desynchronize the
  81. * durable event from what was called.
  82. */
  83. function jsonNormalizeArgs(value: unknown): { dispatched: unknown; logged: unknown } {
  84. let snapshot: JsonValue | undefined
  85. try {
  86. snapshot = snapshotJsonValue(value) as JsonValue | undefined
  87. } catch (error: unknown) {
  88. throw new Error(`tool arguments must be lossless JSON: ${error instanceof Error ? error.message : String(error)}`)
  89. }
  90. if (snapshot === undefined) {
  91. throw new Error('tool arguments must be lossless JSON (call the tool with an arguments object, e.g. `{}`)')
  92. }
  93. return { dispatched: structuredClone(snapshot), logged: structuredClone(snapshot) }
  94. }
  95. /** Render one present program completion value for the model-facing result text. */
  96. function renderValue(value: JsonValue): string {
  97. return typeof value === 'string' ? value : JSON.stringify(value, null, 2)
  98. }
  99. /** Canonical value returned by the outer Code Mode transport. */
  100. type RunCodeOutput = { logs: string[]; result?: JsonValue }
  101. /**
  102. * Build the `run_code` {@link ToolDefinition}: one required `code` parameter,
  103. * executed through the dispatch bridge described above. The
  104. * registry reserves it as presentation infrastructure under non-native modes,
  105. * outside the filterable global/scoped capability layers.
  106. * @param registry - the owning registry (sub-calls go through its `execute`,
  107. * bindings cover its registered tools).
  108. * @param requireRuntime - resolves `ctx.codeRuntime` or throws the loud
  109. * misconfiguration error (shared with the registry's assembly-time checks).
  110. * @returns the registry-ready definition.
  111. */
  112. export function createRunCodeTool(registry: ToolRegistry, requireRuntime: () => CodeRuntime): ToolDefinition {
  113. return defineTool({
  114. name: RUN_CODE_NAME,
  115. description:
  116. 'Execute a TypeScript program against the available tools. Write the BODY of an '
  117. + 'async function (erasable syntax only; top-level `await` and `return` work) and '
  118. + 'call tools as `await tools.name(args)` per the declarations in the system prompt. '
  119. + 'Only what you print or return comes back — curate it.',
  120. parameters: {
  121. code: { type: 'string', required: true, description: 'The program: the body of an async TypeScript function.' },
  122. },
  123. output: {
  124. schema: {
  125. type: 'object',
  126. additionalProperties: false,
  127. properties: {
  128. logs: { type: 'array', required: true, items: { type: 'string' } },
  129. result: { type: 'json' },
  130. },
  131. },
  132. render: (_args, value) => {
  133. const rendered = value.result === undefined ? '' : renderValue(value.result)
  134. const parts = [value.logs.join('\n'), rendered].filter(part => part.length > 0)
  135. return [{ type: 'text', text: parts.length > 0 ? parts.join('\n') : '(run_code completed with no output)' }]
  136. },
  137. },
  138. async execute(args, exec): Promise<RunCodeOutput> {
  139. const runtime = requireRuntime()
  140. // The run-scoped abort: follows the outer signal in, and fires when the
  141. // run settles for ANY reason, so an in-flight sub-dispatch is aborted
  142. // (its executor kills on this signal) instead of orphaned, and
  143. // queued-unstarted dispatches are abandoned.
  144. const runController = new AbortController()
  145. const onOuterAbort = (): void => { runController.abort(exec.signal?.reason) }
  146. if (exec.signal?.aborted) onOuterAbort()
  147. exec.signal?.addEventListener('abort', onOuterAbort, { once: true })
  148. let dispatches = 0
  149. // The per-run serialization queue: every binding call chains onto the tail, so even
  150. // `Promise.all` executes the underlying tool calls one at a time in submission order (the
  151. // tool contract carries no concurrency-safety metadata yet).
  152. let queue: Promise<void> = Promise.resolve()
  153. const enqueue = <T>(task: () => Promise<T>): Promise<T> => {
  154. const turn = queue.then(() => {
  155. if (runController.signal.aborted) {
  156. throw new Error(`run_code run is over (${String(runController.signal.reason)}); tool call abandoned`)
  157. }
  158. return task()
  159. })
  160. queue = turn.then(() => undefined, () => undefined)
  161. return turn
  162. }
  163. // Read through a call, not a bare property: the abort state genuinely
  164. // changes across awaits, and a direct `.aborted` re-check after one
  165. // would be narrowed away by control flow analysis.
  166. const runOver = (): boolean => runController.signal.aborted
  167. const binding = (name: string): CodeBindingFunction => async (rawArgs: unknown): Promise<JsonValue> => {
  168. if (runOver()) {
  169. throw new Error(`run_code run is over (${String(runController.signal.reason)}); ${name} not dispatched`)
  170. }
  171. const normalized = jsonNormalizeArgs(rawArgs)
  172. const outcome = await enqueue(async () => {
  173. const n = ++dispatches
  174. const subCallId = CallId(`${String(exec.callId)}:code:${n}`)
  175. const result = await registry.execute({
  176. callId: subCallId,
  177. name,
  178. arguments: normalized.dispatched,
  179. ...exec.agent ? { agent: exec.agent } : {},
  180. parent: exec.token,
  181. signal: runController.signal,
  182. })
  183. for (const context of result.additionalContexts ?? []) {
  184. exec.deferContext(context)
  185. }
  186. const text = textOf(result.content)
  187. exec.agent?.session.append('tool/code-dispatch', {
  188. parentCallId: exec.callId,
  189. subCallId,
  190. name,
  191. // The SIBLING parse of the dispatched value: byte-identical JSON,
  192. // but a separate object — a tool mutating its args cannot desync
  193. // this record from what it actually received.
  194. arguments: normalized.logged,
  195. isError: result.isError,
  196. resultSummary: summarize(text, exec.agent.session.header.cwd),
  197. })
  198. return result.isError
  199. ? { isError: true as const, message: result.error.message }
  200. : { isError: false as const, value: result.value }
  201. })
  202. // A budget expiry or outer cancel that lands while this call was in
  203. // flight already aborted the dispatch; stop the program now rather
  204. // than hand it a result from a run that is over.
  205. if (runOver()) {
  206. throw new Error(`run_code run is over (${String(runController.signal.reason)}); ${name} result discarded`)
  207. }
  208. // The worker turns a binding rejection into ToolCallError and adds
  209. // only the binding name. Native content and internal error metadata
  210. // stay outside the program-facing failure contract.
  211. if (outcome.isError) throw new Error(outcome.message)
  212. return outcome.value
  213. }
  214. // Null-prototype + defineProperty, mirroring the worker-side namespace
  215. // build: a registered tool named `__proto__` must become an ordinary
  216. // own key (a plain-object assignment would hit the prototype setter,
  217. // silently dropping the binding), and the runtime host resolves
  218. // binding names as own properties only.
  219. const functions: Record<string, CodeBindingFunction> = Object.create(null) as Record<string, CodeBindingFunction>
  220. // Enumerate the CALLING AGENT's visible set (scoped tools join,
  221. // restricted globals vanish) — the same view the SDK section declared,
  222. // so a program can bind exactly what its prompt promised; sub-dispatch
  223. // re-resolves per call through the same view (exec.agent threads down).
  224. for (const schema of registry.schemas(exec.agent)) {
  225. if (schema.name === RUN_CODE_NAME) continue
  226. Object.defineProperty(functions, schema.name, { enumerable: true, value: binding(schema.name) })
  227. }
  228. try {
  229. let result: CodeRunResult
  230. try {
  231. result = await runtime.run({
  232. program: args.code,
  233. bindings: [{ global: 'tools', functions }],
  234. signal: runController.signal,
  235. })
  236. } finally {
  237. // Abort sub-dispatches and drain the folded queue before closing the turn.
  238. // Binding failures remain observable through their individual promises.
  239. runController.abort('run_code settled')
  240. await queue
  241. }
  242. if (result.error) {
  243. const logsText = result.logs.length > 0 ? `\nCaptured output:\n${result.logs.join('\n')}` : ''
  244. throw new CodeRunFailedError(`code run failed (${result.error.kind}): ${result.error.message}${logsText}`)
  245. }
  246. return {
  247. logs: result.logs,
  248. ...result.value !== undefined ? { result: result.value } : {},
  249. }
  250. } finally {
  251. exec.signal?.removeEventListener('abort', onOuterAbort)
  252. }
  253. },
  254. // ACP execute cards use the program as their visible title.
  255. presentCall: args => ({
  256. card: 'generic',
  257. title: args.code,
  258. kind: 'execute',
  259. rawInput: args.code,
  260. }),
  261. // Title omitted on the result: an update replaces only the fields it
  262. // carries, so the pending card's program title persists through
  263. // completion. The durable final content already includes logs plus the
  264. // return value, failure, or post-policy spill preview.
  265. presentResult: (_args, result) => ({ card: 'generic', content: result.content }),
  266. })
  267. }