code-mode.ts 27 KB

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