code-mode.ts 32 KB

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