code-mode.ts 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682
  1. /**
  2. * Code Mode `run_code` transport. Programs call the registry's agent-visible
  3. * tools through nested executions scheduled under the native concurrency
  4. * contract; each sub-dispatch is logged for reconstruction, while only the
  5. * outer curated result enters model history.
  6. * @module @deepseek-ai/dsh-tools/src/code-mode
  7. */
  8. import { CallId, createUserMessage, 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 { FIRST_PARTY_SECTION_ORDER } from '@deepseek-ai/dsh-system-prompt'
  14. import { defineTool, parameterSchemaSpecToJsonSchema } from './schema.ts'
  15. import { TOOL_RUNTIME_SCHEDULER } from './index.ts'
  16. import type { CodeDispatchLog, ToolDefinition, ToolExecutionResult, ToolRuntime, ToolRunContext } from './index.ts'
  17. import type {} from './types.ts'
  18. /** The model-facing name of the Code Mode tool. */
  19. export const RUN_CODE_NAME = 'run_code'
  20. /** The `tools:sdk` section order, after per-tool guidance sections. */
  21. export const SDK_SECTION_ORDER = FIRST_PARTY_SECTION_ORDER.TOOLS_SDK
  22. /**
  23. * The language-specific `run_code` schema text: the tool `description` and its
  24. * `code` parameter description, kept together so a language's two model-facing
  25. * strings share one source of truth. Keyed by `CodeRuntime.language`, mirroring
  26. * `SDK_RENDERERS` in {@link ./index.ts}. The emitted flavor MUST match the
  27. * semantics the same language's SDK instructions promise, so the model never
  28. * receives a TypeScript schema beside a Python SDK (or vice versa).
  29. */
  30. interface RunCodeFlavor {
  31. /** The tool `description` the model sees for this language. */
  32. readonly description: string
  33. /** The `code` parameter's description for this language. */
  34. readonly codeDescription: string
  35. }
  36. /**
  37. * The TypeScript flavor: the fallback for a schema read with no runtime
  38. * mounted ({@link resolveFlavor} owns which readers reach that). A real
  39. * assembly always resolves a runtime first, so the model never sees this
  40. * fallback outside its own language.
  41. */
  42. const TYPESCRIPT_FLAVOR: RunCodeFlavor = {
  43. description:
  44. 'Execute a TypeScript program against the available tools. Takes two required '
  45. + 'arguments: `code`, the BODY of an async function (erasable syntax only; top-level '
  46. + '`await` and `return` work), and `description`, a short summary of what the program '
  47. + 'does. Call tools as `await tools.name(args)` per the declarations in the system '
  48. + 'prompt. Only what you print or return is program output — curate it. Image-bearing '
  49. + 'subtool results are attached after the run.',
  50. codeDescription: 'The program: the body of an async TypeScript function.',
  51. }
  52. /**
  53. * The Python flavor: the body of an async function, top-level `await` and
  54. * `return`, answer via `print` and/or the returned value, matching
  55. * {@link ./py-types.ts}'s SDK instructions.
  56. */
  57. const PYTHON_FLAVOR: RunCodeFlavor = {
  58. description:
  59. 'Execute a Python program against the available tools. Takes two required '
  60. + 'arguments: `code`, the BODY of an async function (top-level `await` and `return` '
  61. + 'work), and `description`, a short summary of what the program does. Call tools as '
  62. + '`await tools.name(args)` per the declarations in the system prompt. Use '
  63. + '`print(...)` and/or `return <value>` for program output — curate it. Image-bearing '
  64. + 'subtool results are attached after the run.',
  65. codeDescription: 'The program: the body of an async Python function.',
  66. }
  67. /**
  68. * The languages Code Mode ships a presentation for. Both per-language tables —
  69. * {@link RUN_CODE_FLAVORS} here and `SDK_RENDERERS` in {@link ./index.ts} — are
  70. * checked against this union with `satisfies`, so a language added to one and
  71. * not the other fails `typecheck` instead of waiting for a runtime that reports
  72. * it. The tables stay declared `Record<string, …>` because `CodeRuntime.language`
  73. * is an unconstrained `string`: this union pins what the harness ships, while the
  74. * `Object.hasOwn` guards reject what a mounted runtime may report.
  75. */
  76. export type CodeSdkLanguage = 'typescript' | 'python'
  77. /** Per-language `run_code` schema flavors (see {@link RunCodeFlavor}); one entry per {@link CodeSdkLanguage}. */
  78. const RUN_CODE_FLAVORS: Record<string, RunCodeFlavor> = {
  79. typescript: TYPESCRIPT_FLAVOR,
  80. python: PYTHON_FLAVOR,
  81. } satisfies Record<CodeSdkLanguage, RunCodeFlavor>
  82. /**
  83. * The `description` parameter's model-facing description: language-independent
  84. * (the UI label contract is the same for every runtime), shared between the
  85. * static spec and the language-aware `parameters` getter so the two emissions
  86. * can never drift.
  87. */
  88. const RUN_CODE_DESCRIPTION_PARAM_DESCRIPTION
  89. = 'Clear, concise description of what this program does in active voice, '
  90. + '5-10 words (shown in the UI). Examples: "Count TODO markers across packages"; '
  91. + '"Read failing test and its fixture"; "Rename config key in every cordis.yml".'
  92. /**
  93. * Resolve the {@link RunCodeFlavor} for the loaded runtime's language, read at
  94. * schema-emission time so the model-visible `run_code` schema always matches
  95. * the SDK section's language. `peekRuntime` returns `undefined` only when no
  96. * runtime is mounted, which reaches this function through definition readers
  97. * and `schemas()` — the doc-catalog harvest is the only shipped one, and none
  98. * of them feeds a model, because `wireSchemas` calls `requireCodeRuntime`
  99. * before projecting — so that path degrades to {@link TYPESCRIPT_FLAVOR}. A
  100. * mounted runtime whose language has no flavor entry fails loud, exactly as
  101. * `requireCodeRuntime` rejects it at assembly. Keeping this table in step with
  102. * `SDK_RENDERERS` is the compiler's job ({@link CodeSdkLanguage}); what this
  103. * guard owns is the runtime-supplied language neither table knows, which never
  104. * yields a wrong-language schema for a real runtime.
  105. */
  106. function resolveFlavor(peekRuntime: () => CodeRuntime | undefined): RunCodeFlavor {
  107. const runtime = peekRuntime()
  108. if (runtime === undefined) {
  109. // No runtime mounted: reached by definition readers and `schemas()`, of
  110. // which the doc-catalog harvest is the only shipped one. None feeds a
  111. // model — `wireSchemas` calls `requireCodeRuntime` before projecting, so
  112. // the assembly path never arrives here. Degrade to the TS default.
  113. return TYPESCRIPT_FLAVOR
  114. }
  115. // Own-property read: a language like `toString`/`constructor` would otherwise
  116. // resolve an inherited Object.prototype member as a flavor.
  117. const flavor = RUN_CODE_FLAVORS[runtime.language]
  118. if (!Object.hasOwn(RUN_CODE_FLAVORS, runtime.language) || flavor === undefined) {
  119. const known = Object.keys(RUN_CODE_FLAVORS).map(name => JSON.stringify(name)).join(', ')
  120. throw new Error(`dsh-tools: no run_code schema flavor registered for runtime language ${JSON.stringify(runtime.language)} (known: ${known})`)
  121. }
  122. return flavor
  123. }
  124. /**
  125. * Thrown by `run_code` when the program run itself failed — a program
  126. * exception, a budget expiry, an abort, or substrate death. Extends
  127. * {@link HarnessError} (`code: 'CODE_RUN_FAILED'`); the registry's execution
  128. * pipeline converts it into a structured `isError` result whose text carries
  129. * the failure kind plus the captured logs, so the model can self-correct.
  130. */
  131. export class CodeRunFailedError extends HarnessError {
  132. constructor(message: string) {
  133. super(message, 'CODE_RUN_FAILED')
  134. this.name = 'CodeRunFailedError'
  135. }
  136. }
  137. /**
  138. * Snapshot one binding call's argument as lossless JSON, then snapshot that
  139. * detached value again so dispatch and logging stay independent without
  140. * reintroducing structured-clone's platform-specific nesting limit.
  141. */
  142. function jsonNormalizeArgs(value: unknown): { dispatched: unknown; logged: unknown } {
  143. let snapshot: JsonValue | undefined
  144. try {
  145. snapshot = snapshotJsonValue(value) as JsonValue | undefined
  146. } catch (error: unknown) {
  147. throw new Error(`tool arguments must be lossless JSON: ${error instanceof Error ? error.message : String(error)}`)
  148. }
  149. if (snapshot === undefined) {
  150. throw new Error('tool arguments must be lossless JSON (call the tool with an arguments object, e.g. `{}`)')
  151. }
  152. const logged = snapshotJsonValue(snapshot)
  153. /* v8 ignore next -- snapshot is already a detached lossless JSON value. */
  154. if (logged === undefined) {
  155. throw new Error('tool arguments could not be detached for durable logging')
  156. }
  157. return { dispatched: snapshot, logged }
  158. }
  159. /** Two-space JSON presentation, matching the existing shallow `run_code` text contract. */
  160. const JSON_INDENT = ' '
  161. /**
  162. * ECMAScript caps `JSON.stringify`'s `space` string at ten characters. The
  163. * renderer also caps TOTAL indentation there, compacting deeper subtrees, so
  164. * formatted output remains linear in the canonical JSON size.
  165. */
  166. const MAX_JSON_INDENT_CHARS = 10
  167. /** A pending fragment in the iterative JSON presentation traversal. */
  168. type JsonRenderTask =
  169. | { kind: 'text'; text: string }
  170. | { kind: 'value'; value: JsonValue; depth: number; compact: boolean }
  171. /** Render one non-string JSON root without recursive traversal or unbounded indentation growth. */
  172. function renderJsonValue(value: Exclude<JsonValue, string>): string {
  173. const chunks: string[] = []
  174. const tasks: JsonRenderTask[] = [{ kind: 'value', value, depth: 0, compact: false }]
  175. for (let task = tasks.pop(); task !== undefined; task = tasks.pop()) {
  176. if (task.kind === 'text') {
  177. chunks.push(task.text)
  178. continue
  179. }
  180. const current = task.value
  181. if (current === null || typeof current === 'boolean' || typeof current === 'number') {
  182. chunks.push(String(current))
  183. continue
  184. }
  185. if (typeof current === 'string') {
  186. chunks.push(JSON.stringify(current))
  187. continue
  188. }
  189. const compact = task.compact || (task.depth + 1) * JSON_INDENT.length > MAX_JSON_INDENT_CHARS
  190. const childDepth = task.depth + 1
  191. if (Array.isArray(current)) {
  192. chunks.push('[')
  193. if (current.length === 0) {
  194. chunks.push(']')
  195. continue
  196. }
  197. tasks.push({ kind: 'text', text: compact ? ']' : `\n${JSON_INDENT.repeat(task.depth)}]` })
  198. for (let index = current.length - 1; index >= 0; index--) {
  199. const item = current[index]
  200. /* v8 ignore next -- canonical JsonValue arrays are dense. */
  201. if (item === undefined) throw new Error('cannot render a sparse JSON array')
  202. tasks.push({ kind: 'value', value: item, depth: childDepth, compact })
  203. tasks.push({
  204. kind: 'text',
  205. text: compact
  206. ? index === 0 ? '' : ','
  207. : `${index === 0 ? '\n' : ',\n'}${JSON_INDENT.repeat(childDepth)}`,
  208. })
  209. }
  210. continue
  211. }
  212. const keys = Object.keys(current)
  213. chunks.push('{')
  214. if (keys.length === 0) {
  215. chunks.push('}')
  216. continue
  217. }
  218. tasks.push({ kind: 'text', text: compact ? '}' : `\n${JSON_INDENT.repeat(task.depth)}}` })
  219. for (let index = keys.length - 1; index >= 0; index--) {
  220. const key = keys[index]
  221. /* v8 ignore next -- the loop is bounded by the captured key count. */
  222. if (key === undefined) throw new Error('cannot render a missing JSON object key')
  223. const item = current[key]
  224. /* v8 ignore next -- canonical JsonValue records contain no undefined properties. */
  225. if (item === undefined) throw new Error('cannot render an undefined JSON object property')
  226. tasks.push({ kind: 'value', value: item, depth: childDepth, compact })
  227. tasks.push({
  228. kind: 'text',
  229. text: compact
  230. ? `${index === 0 ? '' : ','}${JSON.stringify(key)}:`
  231. : `${index === 0 ? '\n' : ',\n'}${JSON_INDENT.repeat(childDepth)}${JSON.stringify(key)}: `,
  232. })
  233. }
  234. }
  235. return chunks.join('')
  236. }
  237. /** Render one present program completion value for the model-facing result text. */
  238. function renderValue(value: JsonValue): string {
  239. return typeof value === 'string' ? value : renderJsonValue(value)
  240. }
  241. /** Canonical value returned by the outer Code Mode transport. */
  242. type RunCodeOutput = { logs: string[]; result?: JsonValue }
  243. /**
  244. * Registry-private capabilities the bridge receives at construction — the
  245. * `requireRuntime` idiom: operations only the owning registry can mint stay
  246. * off its public service API and flow here as closures instead.
  247. */
  248. export interface RunCodeBridgeOptions {
  249. /** Resolves `ctx.codeRuntime` or throws the loud misconfiguration error (shared with the registry's assembly-time checks). */
  250. requireRuntime: () => CodeRuntime
  251. /**
  252. * Reads `ctx.codeRuntime` without throwing: `undefined` when none is mounted.
  253. * Lets schema emission tell "no runtime" (degrade to TS; the readers that
  254. * reach it are {@link resolveFlavor}'s) apart from "unknown language" (fail
  255. * loud).
  256. */
  257. peekRuntime: () => CodeRuntime | undefined
  258. /** The run's overlap cap for parallel-classified sub-calls (the registry passes its validated `maxParallelSubCalls`). */
  259. maxParallel: number
  260. /** Runs the contained `tools/code-dispatch-log` waterfall over one settled sub-dispatch (the registry's private invoker). */
  261. shapeDispatchLog: (dispatch: CodeDispatchLog) => Promise<ContentBlock[]>
  262. }
  263. /**
  264. * Build the `run_code` {@link ToolDefinition}: required `code` and
  265. * `description` parameters, executed through the dispatch bridge described
  266. * above. The
  267. * registry reserves it as presentation infrastructure under non-native modes,
  268. * outside the filterable global/scoped capability layers.
  269. * @param registry - the owning registry (sub-calls go through its `execute`,
  270. * bindings cover its registered tools).
  271. * @param options - the registry-private capabilities described above.
  272. * @returns the registry-ready definition.
  273. */
  274. export function createRunCodeTool(registry: ToolRuntime, options: RunCodeBridgeOptions): ToolDefinition {
  275. const { requireRuntime, peekRuntime, maxParallel, shapeDispatchLog } = options
  276. const definition = defineTool({
  277. name: RUN_CODE_NAME,
  278. // The description and `code` parameter description are placeholders here:
  279. // the language-aware getters installed below replace both, resolving the
  280. // loaded runtime's flavor at schema-emission time so the schema the MODEL
  281. // sees matches the SDK section's language. Argument VALIDATION still keys
  282. // off this static spec (defineTool closes over it), which is language-
  283. // independent (one required string `code`).
  284. description: TYPESCRIPT_FLAVOR.description,
  285. parameters: {
  286. code: { type: 'string', required: true, description: TYPESCRIPT_FLAVOR.codeDescription },
  287. description: {
  288. type: 'string',
  289. required: true,
  290. description: RUN_CODE_DESCRIPTION_PARAM_DESCRIPTION,
  291. },
  292. },
  293. output: {
  294. schema: {
  295. type: 'object',
  296. additionalProperties: false,
  297. properties: {
  298. logs: { type: 'array', required: true, items: { type: 'string' } },
  299. result: { type: 'json' },
  300. },
  301. },
  302. render: (_args, value) => {
  303. const rendered = value.result === undefined ? '' : renderValue(value.result)
  304. const parts = [value.logs.join('\n'), rendered].filter(part => part.length > 0)
  305. return [{ type: 'text', text: parts.length > 0 ? parts.join('\n') : '(run_code completed with no output)' }]
  306. },
  307. },
  308. async execute(args, exec): Promise<RunCodeOutput> {
  309. if (args.description.trim().length === 0) {
  310. throw new Error('invalid description: expected a non-empty string')
  311. }
  312. const runtime = requireRuntime()
  313. // The run-scoped abort: follows the outer signal in, and fires when the
  314. // run settles for ANY reason, so an in-flight sub-dispatch is aborted
  315. // (its executor kills on this signal) instead of orphaned, and
  316. // queued-unstarted dispatches are abandoned.
  317. const runController = new AbortController()
  318. const onOuterAbort = (): void => { runController.abort(exec.signal.reason) }
  319. exec.signal.addEventListener('abort', onOuterAbort, { once: true })
  320. let dispatches = 0
  321. // The per-run scheduler uses the registry's staged interface and follows
  322. // the same concurrency rules as the native loop. It also follows the
  323. // native loop's SEQUENCING: every ordered stage (the dispatch-start
  324. // append, prepare = pre-execute/guards, finalize/finish = post-execute,
  325. // context deferral, the settle append) runs inside ONE driver lane, so
  326. // ordered policy stages never overlap each other and only the
  327. // around-dispatch/body stage runs concurrently. Starts are strictly
  328. // submission-ordered; results commit in submission order through the
  329. // head-of-line cursor. Consecutive parallel-classified calls overlap up
  330. // to maxParallel; an exclusive call waits for the pool to drain, runs
  331. // alone, and holds its barrier until its COMMIT (post-execute included)
  332. // completes, exactly like a native exclusive group. Classification is
  333. // re-read via executionMode() immediately before each start (a registry
  334. // mutation while queued can flip a call exclusive), matching the native
  335. // scheduler's lazy reclassification.
  336. interface PendingDispatch {
  337. /** Ordered stage: append the start event, await prepare (pre-execute/guards), launch the body into `flight`. */
  338. start(): Promise<void>
  339. classify(): 'parallel' | 'exclusive'
  340. abandon(): void
  341. /** Ordered stage: post-execute + context deferral + settle event, in submission order. */
  342. commit(): Promise<void>
  343. /** The launched around-dispatch/body stage; resolved until start() replaces it. */
  344. flight: Promise<void>
  345. /** True once the dispatch stage parked its outcome; the commit cursor waits on it. */
  346. settled: boolean
  347. /** The classification this entry started under; an exclusive holds its barrier through commit(). */
  348. mode?: 'parallel' | 'exclusive'
  349. }
  350. const pendingQueue: PendingDispatch[] = []
  351. const inFlight = new Set<Promise<void>>()
  352. /** Tracked settle-event side work (log-content listener + append), drained at run settlement. */
  353. const logWork = new Set<Promise<void>>()
  354. const commitQueue: PendingDispatch[] = []
  355. let exclusiveActive = false
  356. let driving = false
  357. let driverRun: Promise<void> = Promise.resolve()
  358. let wake: (() => void) | undefined
  359. const wakeup = (): void => {
  360. const release = wake
  361. wake = undefined
  362. release?.()
  363. }
  364. /**
  365. * The single ordered lane. Each pass commits the head-of-line settled
  366. * dispatch (ordered post-execute), then starts the next queued entry if
  367. * its slot is free (ordered pre-execute), and otherwise sleeps until a
  368. * body settles or a new submission arrives. One run reaching the
  369. * empty-queues/empty-pool state is quiescence.
  370. */
  371. const drive = (): Promise<void> => {
  372. if (driving) return driverRun
  373. driving = true
  374. driverRun = (async () => {
  375. try {
  376. for (;;) {
  377. // Create the wakeup promise before inspecting state so a settle or submission arriving
  378. // between the checks and the await below cannot be lost.
  379. const signal = new Promise<void>((resolve) => { wake = resolve })
  380. const commitHead = commitQueue[0]
  381. if (commitHead !== undefined && commitHead.settled) {
  382. commitQueue.shift()
  383. await commitHead.commit()
  384. // The barrier covers post-execute: later starts wait for the
  385. // exclusive call's full pipeline, as under the native loop.
  386. if (commitHead.mode === 'exclusive') exclusiveActive = false
  387. continue
  388. }
  389. const head = pendingQueue[0]
  390. if (head !== undefined) {
  391. if (runController.signal.aborted) {
  392. pendingQueue.shift()
  393. head.abandon()
  394. continue
  395. }
  396. // Reclassify at start time (fail-closed on registry changes).
  397. const mode = head.classify()
  398. const capacity = !exclusiveActive
  399. && (mode === 'exclusive' ? inFlight.size === 0 : inFlight.size < maxParallel)
  400. if (capacity) {
  401. if (mode === 'exclusive') exclusiveActive = true
  402. head.mode = mode
  403. pendingQueue.shift()
  404. // Joined before start() so the commit cursor sees submission
  405. // order; nothing commits it until `settled` flips.
  406. commitQueue.push(head)
  407. await head.start()
  408. const flight: Promise<void> = head.flight.finally(() => {
  409. inFlight.delete(flight)
  410. wakeup()
  411. })
  412. inFlight.add(flight)
  413. continue
  414. }
  415. }
  416. if (pendingQueue.length === 0 && commitQueue.length === 0 && inFlight.size === 0) return
  417. await signal
  418. }
  419. } finally {
  420. driving = false
  421. wake = undefined
  422. }
  423. })()
  424. return driverRun
  425. }
  426. /** Every dispatch settled AND committed; nothing can start (the run is aborted at call time). */
  427. const drainDispatches = async (): Promise<void> => {
  428. // The abort already fired: the driver abandons queued-unstarted
  429. // entries, awaits the live pool, and drains the ordered commit lane —
  430. // including a commit already in progress when the program returned.
  431. await drive()
  432. // Every settle event is appended inside the open run_code turn
  433. // (tasks self-remove on settlement).
  434. while (logWork.size > 0) await Promise.allSettled([...logWork])
  435. }
  436. // Read through a call, not a bare property: the abort state genuinely
  437. // changes across awaits, and a direct `.aborted` re-check after one
  438. // would be narrowed away by control flow analysis.
  439. const runOver = (): boolean => runController.signal.aborted
  440. const binding = (name: string): CodeBindingFunction => async (rawArgs: unknown): Promise<JsonValue> => {
  441. if (runOver()) {
  442. throw new Error(`run_code run is over (${String(runController.signal.reason)}); ${name} not dispatched`)
  443. }
  444. const normalized = jsonNormalizeArgs(rawArgs)
  445. const n = ++dispatches
  446. const subCallId = CallId(`${String(exec.callId)}:code:${n}`)
  447. const input = {
  448. callId: subCallId,
  449. rootCallId: exec.rootCallId,
  450. name,
  451. arguments: normalized.dispatched,
  452. ...exec.agent ? { agent: exec.agent } : {},
  453. parent: exec.token,
  454. signal: runController.signal,
  455. }
  456. type DispatchOutcome = { isError: true; message: string } | { isError: false; value: JsonValue }
  457. const scheduler = registry[TOOL_RUNTIME_SCHEDULER]
  458. const outcome = await new Promise<DispatchOutcome>((resolve, reject) => {
  459. // Set by the dispatch stage (or start() for a pre-settled result): what commit() finalizes in submission order.
  460. let parked:
  461. | { kind: 'post-result' | 'final-result'; exec: ToolRunContext; result: ToolExecutionResult }
  462. | undefined
  463. const settle = (result: ToolExecutionResult): void => {
  464. // The program gets its value NOW: the log-content listener (for
  465. // example, a spill backend) must never delay the binding or occupy
  466. // a dispatch slot. The event append is tracked side work; the run's
  467. // settlement drains logWork so every settle event is still appended
  468. // inside the open turn (shapeDispatchLog is contained, so this
  469. // chain cannot reject).
  470. resolve(result.isError
  471. ? { isError: true, message: result.error.message }
  472. : { isError: false, value: result.value })
  473. const agent = exec.agent
  474. if (agent === undefined) return
  475. const task: Promise<void> = (async () => {
  476. // The listener may replace the durable copy with a preview and
  477. // locator; the program's value and model-visible result are
  478. // untouched.
  479. const logged = await shapeDispatchLog({
  480. exec, agent, subCallId, name, isError: result.isError,
  481. // The registry deep-froze this projection at result
  482. // finalization; append snapshots the final copy again, so
  483. // the log stays detached.
  484. content: result.content,
  485. })
  486. agent.session.append('tool/code-dispatch', {
  487. rootCallId: exec.rootCallId,
  488. parentCallId: exec.callId,
  489. subCallId,
  490. name,
  491. // The SIBLING parse of the dispatched value: byte-identical JSON,
  492. // but a separate object — a tool mutating its args cannot desync
  493. // this record from what it actually received.
  494. arguments: normalized.logged,
  495. isError: result.isError,
  496. content: logged,
  497. })
  498. })().finally(() => { logWork.delete(task) })
  499. logWork.add(task)
  500. }
  501. pendingQueue.push({
  502. flight: Promise.resolve(),
  503. settled: false,
  504. // Re-read per driver pass against the same agent view the SDK
  505. // declared; fail-closed exclusive when undeclared/invalid.
  506. classify: () => registry.executionMode(input).kind,
  507. abandon: () => {
  508. reject(new Error(`run_code run is over (${String(runController.signal.reason)}); ${name} tool call abandoned`))
  509. },
  510. async start(): Promise<void> {
  511. exec.agent?.session.append('tool/code-dispatch-start', {
  512. rootCallId: exec.rootCallId,
  513. parentCallId: exec.callId,
  514. subCallId,
  515. name,
  516. arguments: normalized.logged,
  517. })
  518. // Ordered prepare runs INSIDE the driver lane: the next entry's
  519. // pre-execute waits for this resolution, as under the native
  520. // scheduler. Only the launched body below overlaps.
  521. const prepared = await scheduler.prepare(input)
  522. if (prepared.kind === 'dispatch') {
  523. this.flight = scheduler.dispatch(prepared.exec).then((dispatchOutcome) => {
  524. parked = { kind: dispatchOutcome.kind, exec: prepared.exec, result: dispatchOutcome.result }
  525. this.settled = true
  526. })
  527. return
  528. }
  529. parked = { kind: prepared.kind, exec: prepared.exec, result: prepared.result }
  530. this.settled = true
  531. },
  532. async commit(): Promise<void> {
  533. /* v8 ignore next -- commit() runs only after `settled` flipped, which set parked. */
  534. if (parked === undefined) return
  535. const result = parked.kind === 'post-result'
  536. ? await scheduler.finalize(parked.exec, parked.result)
  537. : scheduler.finish(parked.exec, parked.result)
  538. if (!result.isError && result.content.some(block => block.type === 'image')) {
  539. exec.deferContext(createUserMessage({
  540. content: result.content,
  541. source: { kind: 'plugin', plugin: 'tools-code-mode' },
  542. }))
  543. }
  544. for (const context of result.additionalContexts ?? []) {
  545. exec.deferContext(context)
  546. }
  547. // The composite forwards `additionalContexts` above and
  548. // `concludesTurn` here from the nested result. Only a successful
  549. // nested result can carry the terminal marker
  550. // (ToolExecutionFailure types it never), so a policy-converted
  551. // failure cannot stop the turn through a recovering program.
  552. if (result.concludesTurn) exec.concludeTurn()
  553. settle(result)
  554. // Backpressure on pending event-append tasks: each task retains
  555. // a full result while a slow backend stores it, so the pool cap
  556. // bounds their count. Beyond the cap, the
  557. // ordered lane waits, so later sub-calls cannot start and
  558. // pending I/O/memory cannot grow without bound.
  559. while (logWork.size > maxParallel) await Promise.race(logWork)
  560. },
  561. })
  562. wakeup()
  563. void drive()
  564. })
  565. // A budget expiry or outer cancel that occurs while this call was in
  566. // flight already aborted the dispatch; stop the program now rather
  567. // than hand it a result from a run that is over.
  568. if (runOver()) {
  569. throw new Error(`run_code run is over (${String(runController.signal.reason)}); ${name} result discarded`)
  570. }
  571. // The worker turns a binding rejection into ToolCallError and adds
  572. // only the binding name. Native content and internal error metadata
  573. // stay outside the program-facing failure contract.
  574. if (outcome.isError) throw new Error(outcome.message)
  575. return outcome.value
  576. }
  577. // Null-prototype + defineProperty, mirroring the worker-side namespace
  578. // build: a registered tool named `__proto__` must become an ordinary
  579. // own key (a plain-object assignment would hit the prototype setter,
  580. // silently dropping the binding), and the runtime host resolves
  581. // binding names as own properties only.
  582. const functions: Record<string, CodeBindingFunction> = Object.create(null) as Record<string, CodeBindingFunction>
  583. // Enumerate the CALLING AGENT's visible set (scoped tools join,
  584. // restricted globals vanish) — the same view the SDK section declared,
  585. // so a program can bind exactly what its prompt promised; sub-dispatch
  586. // re-resolves per call through the same view (exec.agent threads down).
  587. for (const schema of registry.schemas(exec.agent)) {
  588. if (schema.name === RUN_CODE_NAME) continue
  589. Object.defineProperty(functions, schema.name, { enumerable: true, value: binding(schema.name) })
  590. }
  591. try {
  592. let result: CodeRunResult
  593. try {
  594. result = await runtime.run({
  595. program: args.code,
  596. bindings: [{
  597. global: 'tools',
  598. functions,
  599. errorClass: { name: 'ToolCallError', memberNameProperty: 'toolName' },
  600. }],
  601. signal: runController.signal,
  602. })
  603. } finally {
  604. // Abort sub-dispatches and drain every in-flight dispatch before
  605. // closing the turn (queued-unstarted ones are abandoned unlogged).
  606. // Binding failures remain observable through their individual promises.
  607. runController.abort('run_code settled')
  608. await drainDispatches()
  609. }
  610. if (result.error) {
  611. const logsText = result.logs.length > 0 ? `\nCaptured output:\n${result.logs.join('\n')}` : ''
  612. throw new CodeRunFailedError(`code run failed (${result.error.kind}): ${result.error.message}${logsText}`)
  613. }
  614. return {
  615. logs: result.logs,
  616. ...result.value !== undefined ? { result: result.value } : {},
  617. }
  618. } finally {
  619. exec.signal.removeEventListener('abort', onOuterAbort)
  620. }
  621. },
  622. // The model-authored description is the call's always-visible UI label
  623. // (the bash `description` precedent); the program itself rides rawInput.
  624. presentCall: args => ({
  625. card: 'generic',
  626. title: args.description,
  627. kind: 'execute',
  628. rawInput: args.code,
  629. }),
  630. // Deliberately no presentResult: the generic card fallback keeps this
  631. // title and reads durable result content without duplicating a large raw
  632. // result into the host view payload.
  633. })
  634. // Resolve the language flavor lazily, at the moment the registry projects the
  635. // schema (`schemaOf` destructures `description`/`parameters`). The definition
  636. // is minted once at registration, before a runtime is known; deferring here
  637. // is the least invasive point that still emits the loaded runtime's language.
  638. Object.defineProperty(definition, 'description', {
  639. enumerable: true,
  640. get: () => resolveFlavor(peekRuntime).description,
  641. })
  642. Object.defineProperty(definition, 'parameters', {
  643. enumerable: true,
  644. // Recompile through the same spec→schema projection defineTool used, so
  645. // the emitted schema always matches the validated specification.
  646. get: () => parameterSchemaSpecToJsonSchema({
  647. code: { type: 'string', required: true, description: resolveFlavor(peekRuntime).codeDescription },
  648. description: { type: 'string', required: true, description: RUN_CODE_DESCRIPTION_PARAM_DESCRIPTION },
  649. }) as unknown as Record<string, unknown>,
  650. })
  651. return definition
  652. }