code-mode.ts 32 KB

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