ptc.ts 32 KB

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