code-mode.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  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 { inspect } from 'node:util'
  9. import { CallId, HarnessError } from '@deepseek-ai/dsh-llm'
  10. import type { ContentBlock } from '@deepseek-ai/dsh-llm'
  11. import type { CodeBindingFunction, CodeRunResult, CodeRuntime } from '@deepseek-ai/dsh-code-runtime'
  12. import type {} 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. /** Bounded inspect for rendering a program's completion value into the model-facing text. */
  59. const INSPECT_OPTIONS = { depth: 4, maxArrayLength: 100, maxStringLength: 10_000 } as const
  60. /** Join a result's text blocks; a non-text block becomes a placeholder (an MVP limitation, stated in the SDK instructions). */
  61. function textOf(content: ContentBlock[]): string {
  62. return content
  63. .map((block) => {
  64. switch (block.type) {
  65. case 'text': return block.text
  66. // ContentBlockMap is merge-extensible — future block kinds land here
  67. // deliberately (no assertNever on merge-extensible unions).
  68. default: return `[${block.type} content]`
  69. }
  70. })
  71. .join('\n')
  72. }
  73. /** Normalize workspace paths, then bound a sub-call's model-facing text for its durable log summary. */
  74. function summarize(text: string, cwd: string | undefined): string {
  75. const stableText = cwd === undefined || cwd === parse(cwd).root
  76. ? text
  77. : text.replaceAll(cwd, '.')
  78. return stableText.length > SUMMARY_MAX_CHARS ? `${stableText.slice(0, SUMMARY_MAX_CHARS)}…` : stableText
  79. }
  80. /**
  81. * JSON-normalize one binding call's argument into TWO independent parses of the same canonical
  82. * text: `dispatched` goes to the tool, `logged` to the `tool/code-dispatch` event — identical
  83. * by construction (the runtime's structured-clone boundary is wider than JSON; the session log
  84. * accepts only JSON), and separate objects, so a tool mutating its args can neither desync the
  85. * log from what was dispatched nor re-poison the append.
  86. */
  87. function jsonNormalizeArgs(value: unknown): { dispatched: unknown; logged: unknown } {
  88. if (value === undefined) {
  89. throw new Error('tool arguments must be JSON-serializable (call the tool with an arguments object, e.g. `{}`)')
  90. }
  91. let text: string | undefined
  92. try {
  93. text = JSON.stringify(value)
  94. } catch (error: unknown) {
  95. throw new Error(`tool arguments must be JSON-serializable: ${error instanceof Error ? error.message : String(error)}`)
  96. }
  97. // JSON.stringify's lib type claims `string`, but a bare function or symbol
  98. // root really yields `undefined` at runtime — the guard is live.
  99. // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
  100. if (text === undefined) throw new Error('tool arguments must be JSON-serializable (got a value JSON cannot represent)')
  101. return { dispatched: JSON.parse(text) as unknown, logged: JSON.parse(text) as unknown }
  102. }
  103. /** Render the program's completion value for the model-facing result text (`''` when the program returned nothing). */
  104. function renderValue(value: unknown): string {
  105. if (value === undefined) return ''
  106. return typeof value === 'string' ? value : inspect(value, INSPECT_OPTIONS)
  107. }
  108. /** The run_code result's `meta` payload (JSON-serializable; `presentResult` narrows it back). */
  109. interface RunCodeMeta {
  110. logs: CodeRunResult['logs']
  111. }
  112. /** Soft-narrow a result `meta` back to {@link RunCodeMeta} (replay may carry older shapes; presentation must not throw). */
  113. function asRunCodeMeta(meta: unknown): RunCodeMeta | undefined {
  114. if (typeof meta !== 'object' || meta === null) return undefined
  115. const m = meta as Record<string, unknown>
  116. if (!Array.isArray(m.logs) || !m.logs.every(log => typeof log === 'string')) return undefined
  117. return m as unknown as RunCodeMeta
  118. }
  119. /**
  120. * Build the `run_code` {@link ToolDefinition}: one required `code` parameter,
  121. * executed through the dispatch bridge described above. The
  122. * registry reserves it as presentation infrastructure under non-native modes,
  123. * outside the filterable global/scoped capability layers.
  124. * @param registry - the owning registry (sub-calls go through its `execute`,
  125. * bindings cover its registered tools).
  126. * @param requireRuntime - resolves `ctx.codeRuntime` or throws the loud
  127. * misconfiguration error (shared with the registry's assembly-time checks).
  128. * @returns the registry-ready definition.
  129. */
  130. export function createRunCodeTool(registry: ToolRegistry, requireRuntime: () => CodeRuntime): ToolDefinition {
  131. return defineTool({
  132. name: RUN_CODE_NAME,
  133. description:
  134. 'Execute a TypeScript program against the available tools. Write the BODY of an '
  135. + 'async function (erasable syntax only; top-level `await` and `return` work) and '
  136. + 'call tools as `await tools.name(args)` per the declarations in the system prompt. '
  137. + 'Only what you print or return comes back — curate it.',
  138. parameters: {
  139. code: { type: 'string', required: true, description: 'The program: the body of an async TypeScript function.' },
  140. },
  141. async execute(args, exec) {
  142. const runtime = requireRuntime()
  143. // The run-scoped abort: follows the outer signal in, and fires when the
  144. // run settles for ANY reason, so an in-flight sub-dispatch is aborted
  145. // (its executor kills on this signal) instead of orphaned, and
  146. // queued-unstarted dispatches are abandoned.
  147. const runController = new AbortController()
  148. const onOuterAbort = (): void => { runController.abort(exec.signal?.reason) }
  149. if (exec.signal?.aborted) onOuterAbort()
  150. exec.signal?.addEventListener('abort', onOuterAbort, { once: true })
  151. let dispatches = 0
  152. // The per-run serialization queue: every binding call chains onto the tail, so even
  153. // `Promise.all` executes the underlying tool calls one at a time in submission order (the
  154. // tool contract carries no concurrency-safety metadata yet).
  155. let queue: Promise<void> = Promise.resolve()
  156. const enqueue = <T>(task: () => Promise<T>): Promise<T> => {
  157. const turn = queue.then(() => {
  158. if (runController.signal.aborted) {
  159. throw new Error(`run_code run is over (${String(runController.signal.reason)}); tool call abandoned`)
  160. }
  161. return task()
  162. })
  163. queue = turn.then(() => undefined, () => undefined)
  164. return turn
  165. }
  166. // Read through a call, not a bare property: the abort state genuinely
  167. // changes across awaits, and a direct `.aborted` re-check after one
  168. // would be narrowed away by control flow analysis.
  169. const runOver = (): boolean => runController.signal.aborted
  170. const binding = (name: string): CodeBindingFunction => async (rawArgs: unknown): Promise<unknown> => {
  171. if (runOver()) {
  172. throw new Error(`run_code run is over (${String(runController.signal.reason)}); ${name} not dispatched`)
  173. }
  174. const normalized = jsonNormalizeArgs(rawArgs)
  175. const outcome = await enqueue(async () => {
  176. const n = ++dispatches
  177. const subCallId = CallId(`${String(exec.callId)}:code:${n}`)
  178. const result = await registry.execute({
  179. callId: subCallId,
  180. name,
  181. arguments: normalized.dispatched,
  182. ...exec.agent ? { agent: exec.agent } : {},
  183. parent: exec.token,
  184. signal: runController.signal,
  185. })
  186. for (const context of result.additionalContexts ?? []) {
  187. exec.deferContext(context)
  188. }
  189. const text = textOf(result.content)
  190. exec.agent?.session.append('tool/code-dispatch', {
  191. parentCallId: exec.callId,
  192. subCallId,
  193. name,
  194. // The SIBLING parse of the dispatched value: byte-identical JSON,
  195. // but a separate object — a tool mutating its args cannot desync
  196. // this record from what it actually received.
  197. arguments: normalized.logged,
  198. isError: result.isError,
  199. resultSummary: summarize(text, exec.agent.session.header.cwd),
  200. })
  201. return { text, isError: result.isError }
  202. })
  203. // A budget expiry or outer cancel that lands while this call was in
  204. // flight already aborted the dispatch; stop the program now rather
  205. // than hand it a result from a run that is over.
  206. if (runOver()) {
  207. throw new Error(`run_code run is over (${String(runController.signal.reason)}); ${name} result discarded`)
  208. }
  209. // A failed tool call REJECTS — real code signals failure by throwing,
  210. // so try/catch and Promise.all short-circuiting behave as models
  211. // expect (the error text is the tool's model-facing result text).
  212. if (outcome.isError) throw new Error(outcome.text)
  213. return outcome.text
  214. }
  215. // Null-prototype + defineProperty, mirroring the worker-side namespace
  216. // build: a registered tool named `__proto__` must become an ordinary
  217. // own key (a plain-object assignment would hit the prototype setter,
  218. // silently dropping the binding), and the runtime host resolves
  219. // binding names as own properties only.
  220. const functions: Record<string, CodeBindingFunction> = Object.create(null) as Record<string, CodeBindingFunction>
  221. // Enumerate the CALLING AGENT's visible set (scoped tools join,
  222. // restricted globals vanish) — the same view the SDK section declared,
  223. // so a program can bind exactly what its prompt promised; sub-dispatch
  224. // re-resolves per call through the same view (exec.agent threads down).
  225. for (const schema of registry.schemas(exec.agent)) {
  226. if (schema.name === RUN_CODE_NAME) continue
  227. Object.defineProperty(functions, schema.name, { enumerable: true, value: binding(schema.name) })
  228. }
  229. try {
  230. let result: CodeRunResult
  231. try {
  232. result = await runtime.run({
  233. program: args.code,
  234. bindings: [{ global: 'tools', functions }],
  235. signal: runController.signal,
  236. })
  237. } finally {
  238. // Abort sub-dispatches and drain the folded queue before closing the turn.
  239. // Binding failures remain observable through their individual promises.
  240. runController.abort('run_code settled')
  241. await queue
  242. }
  243. if (result.error) {
  244. const logsText = result.logs.length > 0 ? `\nCaptured output:\n${result.logs.join('\n')}` : ''
  245. throw new CodeRunFailedError(`code run failed (${result.error.kind}): ${result.error.message}${logsText}`)
  246. }
  247. const rendered = renderValue(result.value)
  248. const parts = [result.logs.join('\n'), rendered].filter(part => part.length > 0)
  249. const meta: RunCodeMeta = { logs: result.logs }
  250. return {
  251. content: [{ type: 'text', text: parts.length > 0 ? parts.join('\n') : '(run_code completed with no output)' }],
  252. meta,
  253. }
  254. } finally {
  255. exec.signal?.removeEventListener('abort', onOuterAbort)
  256. }
  257. },
  258. // ACP execute cards use the program as their visible title.
  259. presentCall: args => ({
  260. card: 'generic',
  261. title: args.code,
  262. kind: 'execute',
  263. rawInput: args.code,
  264. }),
  265. // Title omitted on the result: an update replaces only the fields it
  266. // carries, so the pending card's program title persists through
  267. // completion; the captured output rides as body content.
  268. presentResult: (_args, result) => {
  269. const meta = asRunCodeMeta(result.meta)
  270. if (!meta) return undefined
  271. const output = meta.logs.join('\n')
  272. return {
  273. card: 'generic',
  274. ...output.length > 0 ? { content: [{ type: 'text' as const, text: output }] } : {},
  275. }
  276. },
  277. })
  278. }