code-mode.ts 32 KB

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