index.ts 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608
  1. /**
  2. * Tool registry, model presentation modes, and pre/guard/around/post/result
  3. * execution pipeline.
  4. * @module @deepseek-ai/dsh-tools
  5. */
  6. import { Context, Service } from 'cordis'
  7. import z from 'schemastery'
  8. import { AnonymousEntries, NamedEntries, ScopedLayers, scopeOf, scopeTarget } from '@deepseek-ai/dsh-scope'
  9. import type { ScopeKey, ScopeLayer, Scoped } from '@deepseek-ai/dsh-scope'
  10. import type { CallId, ContentBlock, ToolSchema } from '@deepseek-ai/dsh-llm'
  11. import { assertNever, deepFreeze, HarnessError } from '@deepseek-ai/dsh-llm'
  12. import type { Agent } from '@deepseek-ai/dsh-agent'
  13. import { snapshotJsonValue } from '@deepseek-ai/dsh-session'
  14. import type { JsonValue, UserMessage } from '@deepseek-ai/dsh-session'
  15. import type { ToolProviderResult } from '@deepseek-ai/dsh-system-prompt'
  16. import type { CodeRuntime } from '@deepseek-ai/dsh-code-runtime'
  17. // Type-only: makes `ctx.get('approval')` resolve to the ApprovalService
  18. // augmentation. The seam stays optional at runtime — see `serviceAsk`.
  19. import type {} from '@deepseek-ai/dsh-user-approval'
  20. import type { ToolCallView, ToolResultView } from './presentation.ts'
  21. import { assertSupportedJsonSchema, validateJsonSchemaValue } from './json-schema.ts'
  22. import type { JsonSchemaNode } from './json-schema.ts'
  23. import { createRunCodeTool, RUN_CODE_NAME, SDK_SECTION_ORDER } from './code-mode.ts'
  24. import { renderToolsSdk } from './ts-types.ts'
  25. import type { ToolSdkSchema } from './ts-types.ts'
  26. export {
  27. defineTool,
  28. valueSchemaSpecToJsonSchema,
  29. parameterSchemaSpecToJsonSchema,
  30. validateArgs,
  31. ToolArgsError,
  32. type ValueSchemaAnnotations,
  33. type StringValueSchemaSpec,
  34. type NumberValueSchemaSpec,
  35. type IntegerValueSchemaSpec,
  36. type BooleanValueSchemaSpec,
  37. type NullValueSchemaSpec,
  38. type ArrayValueSchemaSpec,
  39. type ObjectValueSchemaSpec,
  40. type JsonValueSchemaSpec,
  41. type OneOfValueSchemaSpec,
  42. type ValueSchemaSpec,
  43. type ParameterPropertySpec,
  44. type ParameterSchemaSpec,
  45. type ParameterJsonSchema,
  46. type InferValue,
  47. type InferArgs,
  48. type DefineToolOptions,
  49. } from './schema.ts'
  50. export {
  51. assertSupportedJsonSchema,
  52. assertObjectJsonSchema,
  53. validateJsonSchemaValue,
  54. JsonSchemaError,
  55. type JsonSchemaNode,
  56. type ObjectJsonSchema,
  57. type JsonSchemaType,
  58. type JsonSchemaScalar,
  59. } from './json-schema.ts'
  60. export type { JsonValue } from '@deepseek-ai/dsh-session'
  61. export { CodeRunFailedError, RUN_CODE_NAME } from './code-mode.ts'
  62. export { jsonSchemaToTs, renderToolsSdk } from './ts-types.ts'
  63. export { defineContentToolFixture, type ContentToolFixtureOptions } from './testing.ts'
  64. // The render-intent vocabulary a tool declares via `presentCall`/`presentResult`
  65. // lives in its own UI-facing module; re-export it so `@deepseek-ai/dsh-tools`
  66. // stays the single public surface for tool producers and UI adapters.
  67. export type {
  68. ToolCallKind,
  69. FileLocation,
  70. FileDiff,
  71. ReadFileLine,
  72. ToolCallView,
  73. GenericCallView,
  74. TerminalCallView,
  75. DiffCallView,
  76. ToolResultView,
  77. GenericResultView,
  78. TerminalResultView,
  79. DiffResultView,
  80. SearchResultView,
  81. SearchMatchesResultView,
  82. SearchPathsResultView,
  83. SearchFileMatches,
  84. SearchLineMatch,
  85. ReadResultView,
  86. WebResultView,
  87. WebSearchResultView,
  88. WebFetchResultView,
  89. WebSource,
  90. } from './presentation.ts'
  91. declare module 'cordis' {
  92. interface Context {
  93. tools: ToolRegistry
  94. }
  95. interface Events {
  96. /**
  97. * Allow, deny, or ask before dispatch. `next()` delegates to allow; missing
  98. * approval support turns `ask` into denial. Async gates must observe
  99. * `exec.signal`; the registry rechecks cancellation after they settle but
  100. * never abandons their promise.
  101. * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent's calls.
  102. * @param exec - the pending call (name, parsed arguments, caller agent).
  103. * @mode waterfall
  104. */
  105. 'tools/pre-execute'(this: Scoped<ToolRegistry>, exec: ToolExecution, next: () => Promise<PreToolDecision>): Promise<PreToolDecision>
  106. /**
  107. * Around-dispatch waterfall for timeout, retry, or metrics. `next()` returns
  108. * a normalized result; wrappers may change only `exec.signal`, while call
  109. * identity remains immutable. The registry re-fuses the original caller
  110. * signal before the body, so replacement cannot detach caller cancellation;
  111. * wrappers must still restore their signal and reach quiescence.
  112. * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent's calls.
  113. * @param exec - the allowed call about to dispatch (name, parsed arguments, caller agent, signal).
  114. * @mode waterfall
  115. */
  116. 'tools/execute'(this: Scoped<ToolRegistry>, exec: ToolDispatchExecution, next: () => Promise<ToolExecutionResult>): Promise<ToolExecutionResult>
  117. /**
  118. * Accept, replace, enrich, or block a normalized dispatch result. `next()`
  119. * accepts it unchanged; thrown tools still reach this seam as errors. Async
  120. * listeners must observe `exec.signal`; after they settle, caller
  121. * cancellation replaces only a successful accepted outcome with the code
  122. * selected by whether the tool body was invoked.
  123. * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent's calls.
  124. * @param exec - the call that just ran (name, parsed arguments, caller agent).
  125. * @param result - the dispatch outcome a listener may accept, replace, or block.
  126. * @mode waterfall
  127. */
  128. 'tools/post-execute'(this: Scoped<ToolRegistry>, exec: ToolExecution, result: Readonly<ToolExecutionResult>, next: () => Promise<PostToolDecision>): Promise<PostToolDecision>
  129. /**
  130. * Shape the DURABLE LOG COPY of one `run_code` sub-dispatch outcome before
  131. * the bridge appends its `tool/code-dispatch` event. `next()` keeps the
  132. * content unchanged; a listener may return replacement blocks (e.g. the
  133. * spill policy's preview + locator for an oversized text result). Only the
  134. * logged copy is affected — the program already received the complete
  135. * value, and the model sees neither. A throwing listener is contained:
  136. * the bridge falls back to logging the unshaped content.
  137. * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent's dispatches.
  138. * @param dispatch - the parent execution, sub-call identity, and the settled content to log.
  139. * @mode waterfall
  140. */
  141. 'tools/code-dispatch-log'(this: Scoped<ToolRegistry>, dispatch: CodeDispatchLog, next: () => Promise<ContentBlock[]>): Promise<ContentBlock[]>
  142. /**
  143. * Observe the frozen, lossless-JSON final outcome. Listener failures are contained.
  144. * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): keyed by `exec.agent`.
  145. * @param exec - the execution object that traversed the pipeline.
  146. * @param result - a deep-frozen snapshot of the final returned result.
  147. * @mode emit
  148. */
  149. 'tools/result'(this: Scoped<ToolRegistry>, exec: Readonly<ToolExecution>, result: Readonly<ToolExecutionResult>): undefined
  150. /**
  151. * A tool was registered or unregistered, or a scoped restriction changed
  152. * (the available tool set changed — possibly for one scope only). An
  153. * UNFILTERED registry-subject notification, deliberately not scope-filtered
  154. * dispatch: a global change concerns every agent's next assembly, so a
  155. * scoped listener subscribing here sees every change, not just its own
  156. * scope's.
  157. * @mode emit
  158. */
  159. 'tools/change'(): void
  160. }
  161. }
  162. /** Tool-owned canonical output contract used after the body returns a JSON value. */
  163. export interface ToolOutputDefinition {
  164. /** Raw supported JSON Schema enforced against every successful canonical value. */
  165. readonly schema: JsonSchemaNode
  166. /** Pure projection from validated arguments and value to Native/model content. */
  167. render(args: unknown, value: JsonValue): ContentBlock[]
  168. /** Pure replayable presentation projection, computed only for surface calls. */
  169. presentationMeta?(args: unknown, value: JsonValue): JsonValue
  170. }
  171. /** A registered tool: its schema plus the execution function. */
  172. export interface ToolDefinition extends ToolSchema {
  173. /** Mandatory canonical output declaration. */
  174. readonly output: ToolOutputDefinition
  175. /**
  176. * Run one accepted call and return only its canonical lossless-JSON value.
  177. * Async work must observe or forward `exec.signal` and settle only after its
  178. * owned work reaches quiescence. The registry preserves caller cancellation
  179. * through around-dispatch signal replacement and does not abandon this
  180. * promise, but it cannot hard-kill same-process code.
  181. * @param args - losslessly snapshotted, frozen model arguments.
  182. * @param exec - execution identity, cancellation signal, and context deferral.
  183. * @returns the canonical value declared by `output.schema`.
  184. */
  185. execute(args: unknown, exec: ToolRunContext): Promise<unknown>
  186. /**
  187. * Synchronous last-mile transform for model-facing content. The registry
  188. * snapshots this callback when execution starts and invokes it exactly once
  189. * for every normalized outcome, including pipeline failures that bypass
  190. * `tools/post-execute`, immediately before lossless materialization.
  191. * Returning `undefined` preserves the content; every other result field
  192. * remains registry-owned. The callback must be total and must not throw.
  193. * @param exec - immutable execution identity and arguments.
  194. * @param result - complete normalized outcome before materialization.
  195. * @returns replacement content, or `undefined` to preserve it.
  196. */
  197. finalizeContent?(exec: Readonly<ToolExecution>, result: Readonly<ToolExecutionResult>): ContentBlock[] | undefined
  198. /**
  199. * Cooperative tool-call timeout budget in milliseconds. Omit for no deadline.
  200. * Enforced by `@deepseek-ai/dsh-timeout-policy` (a `tools/execute` wrapper); it
  201. * is NEVER sent to the model — `schemas()` whitelists only name/description/
  202. * parameters. Declaring it asserts this tool forwards `exec.signal` to a
  203. * cooperative implementation that can reach quiescence when the signal aborts.
  204. */
  205. timeoutMs?: number
  206. /**
  207. * Pure synchronous classifier for overlap with sibling tool calls. Only
  208. * `true` opts in; omission, exceptions, non-`true` returns, and invalid
  209. * `defineTool` arguments are exclusive. This metadata is never model-visible.
  210. *
  211. * Opted-in executions must not mutate parent-owned state. Shared state must
  212. * tolerate concurrent dispatch; recorder races are permitted only when they
  213. * commute or fail closed. See the
  214. * [parallel-tool-call Agent Note](../../../../.agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.md)
  215. * for the full contract.
  216. * @param args - parsed arguments; `defineTool` validates before calling.
  217. * @returns Whether this call may join a parallel group.
  218. */
  219. isConcurrencySafe?(args: unknown): boolean
  220. /**
  221. * Optional: how to present the PENDING state of one call in a UI, derived from
  222. * the call's `args` (parsed arguments, `unknown` — the tool validates/narrows
  223. * its own input). Returns a {@link ToolCallView} (a `card`-tagged render intent),
  224. * or `undefined` (or omit the method) to fall back to a generic presentation
  225. * (title = tool name, raw args as input). Pure and side-effect-free: a UI may
  226. * call it during live streaming AND a session-log replay, so it must depend
  227. * only on `args`.
  228. */
  229. presentCall?(args: unknown): ToolCallView | undefined
  230. /**
  231. * Optional: how to present the COMPLETED state, given the same `args` and the
  232. * durable result projection (`content`, failure state, and optional `meta`). Returns a
  233. * {@link ToolResultView}, or `undefined` (or omit the method) to keep the
  234. * pending title and render the raw result content. Pure and side-effect-free
  235. * for the same replay reason.
  236. */
  237. presentResult?(args: unknown, result: ToolResult): ToolResultView | undefined
  238. }
  239. /** The completed outcome handed to {@link ToolDefinition.presentResult}. */
  240. export interface ToolResult {
  241. /** The final model-facing content (or the rendered error text on failure). */
  242. content: ContentBlock[]
  243. /** Whether the call failed. */
  244. isError: boolean
  245. /**
  246. * The tool-private presentation payload projected by its output declaration
  247. * and threaded verbatim from the `tool/result` event. Absent when the tool
  248. * declared no projector or the call was nested under a composite transport.
  249. */
  250. meta?: JsonValue
  251. }
  252. declare const toolExecutionTokenBrand: unique symbol
  253. /** Opaque call identity that permits correlation without exposing mutable execution state. */
  254. export type ToolExecutionToken = symbol & { readonly [toolExecutionTokenBrand]: true }
  255. /**
  256. * Caller-supplied description of one tool call. {@link ToolRegistry.execute}
  257. * adds the registry-owned token to form a pipeline {@link ToolExecution};
  258. * callers do not choose that token.
  259. */
  260. export interface ToolExecutionInput {
  261. readonly callId: CallId
  262. readonly name: string
  263. /** Losslessly JSON-serializable parsed arguments (tools validate their own schema). */
  264. readonly arguments: unknown
  265. /** The agent on whose behalf the call runs (set by the agent loop). */
  266. readonly agent?: Agent
  267. /**
  268. * Opaque token of the enclosing transport execution, when one exists. Code
  269. * Mode sets this on SDK sub-dispatches so commit-style observers can wait for
  270. * the outer `run_code` outcome without receiving its live mutable execution.
  271. */
  272. readonly parent?: ToolExecutionToken
  273. /** Required caller-owned cancellation for this invocation. */
  274. readonly signal: AbortSignal
  275. }
  276. /**
  277. * Scheduling mode for one pending call. `parallel` may overlap with siblings;
  278. * `exclusive` runs alone and forms an ordering barrier.
  279. */
  280. export type ToolExecutionMode =
  281. | { kind: 'parallel' }
  282. | { kind: 'exclusive' }
  283. /**
  284. * One settled `run_code` sub-dispatch about to be logged, as seen by the
  285. * `tools/code-dispatch-log` waterfall: the parent execution (session owner,
  286. * outer call identity), the sub-call identity, and the outcome whose durable
  287. * copy a listener may reshape. `content` is the RENDERED result projection
  288. * (what a native `tool/result` would carry) — the program itself received
  289. * the structured `value` (or just the error message on failure); only the
  290. * `tool/code-dispatch` event's copy changes.
  291. */
  292. export interface CodeDispatchLog {
  293. /** The outer `run_code` execution. */
  294. readonly exec: ToolExecution
  295. /** The calling agent (the scope routing key and the spill owner), when the outer call has one. */
  296. readonly agent?: Agent
  297. /** Deterministic sub-call id (`<parent>:code:<n>`). */
  298. readonly subCallId: CallId
  299. /** The dispatched sub-tool name. */
  300. readonly name: string
  301. /** Whether the sub-call settled as an error. */
  302. readonly isError: boolean
  303. /** The sub-call's complete model-facing content (the settle event's default payload). */
  304. readonly content: ContentBlock[]
  305. }
  306. /**
  307. * One pending tool call inside the registry pipeline. Parsed arguments cross
  308. * one lossless-JSON materialization boundary before policy and are deep-frozen;
  309. * call identity, the caller signal, and the registry-assigned {@link token} are
  310. * readonly. The registry freezes the complete object before `tools/result`
  311. * observers run.
  312. */
  313. export interface ToolExecution extends ToolExecutionInput {
  314. /** Registry-assigned identity shared with nested calls only as their opaque `parent` token. */
  315. readonly token: ToolExecutionToken
  316. }
  317. /**
  318. * Around-dispatch view of a {@link ToolExecution}. A `tools/execute` wrapper
  319. * may replace the signal for its delegated lifetime, but it cannot remove it.
  320. * The registry fuses every replacement with the captured caller signal.
  321. */
  322. export interface ToolDispatchExecution extends Omit<ToolExecution, 'signal'> {
  323. /** Cancellation signal visible to the next wrapper or tool body. */
  324. signal: AbortSignal
  325. }
  326. /**
  327. * Runtime context handed to a tool implementation after the registry has
  328. * accepted a {@link ToolExecution}. {@link deferContext} attaches context to
  329. * this execution's own result — a composite tool ferries nested-dispatch
  330. * context back to the outer result, and a leaf tool may mint a fresh
  331. * plugin-sourced instruction; the loop appends it only after the
  332. * `tool/result`.
  333. */
  334. export interface ToolRunContext extends ToolExecution {
  335. /**
  336. * Defer one context — typically a nested-dispatch context ferried by a
  337. * composite tool, or a fresh plugin-sourced instruction — until this tool's
  338. * final result reaches the agent loop. Contexts retain their individual
  339. * source and metadata and are emitted in call order.
  340. */
  341. deferContext(context: UserMessage): void
  342. /**
  343. * Mark a successful final result as terminal for the current agent turn.
  344. * The marker rides this execution's own result (`concludesTurn` exists only
  345. * on {@link ToolExecutionSuccess}); a composite that dispatches nested
  346. * calls forwards it from the nested result, exactly like
  347. * `additionalContexts`, so only an authoritative nested success can
  348. * conclude the enclosing run.
  349. */
  350. concludeTurn(): void
  351. }
  352. /** Registry-owned live execution object; public pipeline views stay readonly. */
  353. type MutableToolRunContext = Omit<ToolRunContext, 'signal'> & { signal: AbortSignal }
  354. /**
  355. * Scheduler-only result after ordered pre-execute and guards. A `post-result`
  356. * still receives post-execute; a `final-result` bypasses it.
  357. * @internal
  358. */
  359. export type ScheduledToolPreparation =
  360. | { kind: 'dispatch'; exec: ToolRunContext }
  361. | { kind: 'post-result'; exec: ToolRunContext; result: ToolExecutionResult }
  362. | { kind: 'final-result'; exec: ToolRunContext; result: ToolExecutionResult }
  363. /**
  364. * Scheduler-only dispatch result. A `post-result` still receives post-execute;
  365. * a `final-result` already matches {@link ToolRegistry.execute} failure semantics.
  366. * @internal
  367. */
  368. export type ScheduledToolDispatch =
  369. | { kind: 'post-result'; result: ToolExecutionResult }
  370. | { kind: 'final-result'; result: ToolExecutionResult }
  371. /**
  372. * Symbol-keyed scheduler view that keeps pre/post policy ordered while
  373. * overlapping dispatch. Ordinary callers use {@link ToolRegistry.execute};
  374. * this is not a plugin seam.
  375. * @internal
  376. */
  377. export interface ToolRegistryScheduler {
  378. /** Materialize input, run the ordered pre-execute/guard gate, and decide what stage follows. */
  379. prepare(exec: ToolExecutionInput): Promise<ScheduledToolPreparation>
  380. /** Run only the around-dispatch/body stage. */
  381. dispatch(exec: ToolRunContext): Promise<ScheduledToolDispatch>
  382. /** Run post-execute and definition-owned content finalization, then materialize and notify. */
  383. finalize(exec: ToolRunContext, result: ToolExecutionResult): Promise<ToolExecutionResult>
  384. /** Run definition-owned content finalization, then materialize and notify without post-execute. */
  385. finish(exec: ToolRunContext, result: ToolExecutionResult): ToolExecutionResult
  386. }
  387. /**
  388. * Scheduler entry point omitted from the generated named service API.
  389. * @internal
  390. */
  391. export const TOOL_REGISTRY_SCHEDULER: unique symbol = Symbol('@deepseek-ai/dsh-tools.scheduler')
  392. /** Canonical error code for cancellation after a tool body was invoked. */
  393. export const TOOL_ABORTED = 'ABORTED'
  394. /** Canonical error code for cancellation before a tool body was invoked. */
  395. export const TOOL_ABORTED_BEFORE_DISPATCH = 'ABORTED_BEFORE_DISPATCH'
  396. /** Structured error metadata for a failed tool call (alongside the model-facing text). */
  397. export interface ToolErrorInfo {
  398. name: string
  399. code: string
  400. }
  401. /** Canonical failure detail; internal routing information remains optional. */
  402. export interface ToolFailure {
  403. /** Human-readable failure message without the Native `Error: ` envelope. */
  404. message: string
  405. /** Internal error class/code used by policy and durable diagnostics. */
  406. info?: ToolErrorInfo
  407. }
  408. /**
  409. * Thrown (internally) when the model requests a tool that isn't registered.
  410. * Extends {@link HarnessError} (`code: 'UNKNOWN_TOOL'`) so an unknown-tool
  411. * failure is as routable as a tool-thrown one — retry/sandbox/replay code can
  412. * distinguish it from a tool body's own error.
  413. */
  414. export class ToolNotFoundError extends HarnessError {
  415. constructor(toolName: string) {
  416. super(`unknown tool "${toolName}"`, 'UNKNOWN_TOOL')
  417. this.name = 'ToolNotFoundError'
  418. }
  419. }
  420. /** Thrown when a tool body or post-policy value violates its declared output. */
  421. export class ToolOutputError extends HarnessError {
  422. /** Schema/value violations in validation order. */
  423. readonly violations: string[]
  424. constructor(toolName: string, violations: string[]) {
  425. super(`tool "${toolName}" returned invalid output: ${violations.join('; ')}`, 'INVALID_TOOL_OUTPUT')
  426. this.name = 'ToolOutputError'
  427. this.violations = violations
  428. }
  429. }
  430. /** Convert one projector exception into the canonical invalid-output failure. */
  431. function projectionError(toolName: string, projector: 'render' | 'presentationMeta', error: unknown): ToolOutputError {
  432. return new ToolOutputError(toolName, [`output.${projector} failed: ${errorMessage(error)}`])
  433. }
  434. /** Snapshot one projector result before later durable-result materialization. */
  435. function snapshotProjection<T>(toolName: string, projector: 'render' | 'presentationMeta', candidate: T): T {
  436. try {
  437. const detached = snapshotJsonValue(candidate)
  438. if (detached === undefined) {
  439. throw new ToolOutputError(toolName, [`output.${projector} returned non-lossless JSON`])
  440. }
  441. return detached
  442. } catch (error: unknown) {
  443. if (error instanceof ToolOutputError) throw error
  444. throw projectionError(toolName, projector, error)
  445. }
  446. }
  447. /** Snapshot one body or policy value into the canonical invalid-output failure class. */
  448. function snapshotToolValue(toolName: string, candidate: unknown): JsonValue {
  449. try {
  450. const detached = snapshotJsonValue(candidate)
  451. if (detached === undefined) throw new ToolOutputError(toolName, ['value is not lossless JSON'])
  452. return detached as JsonValue
  453. } catch (error: unknown) {
  454. if (error instanceof ToolOutputError) throw error
  455. throw new ToolOutputError(toolName, [`value snapshot failed: ${errorMessage(error)}`])
  456. }
  457. }
  458. /** Successful canonical tool execution, including its Native/model projection. */
  459. export interface ToolExecutionSuccess {
  460. readonly isError: false
  461. /** Execution-local canonical value; deliberately omitted from durable events. */
  462. readonly value: JsonValue
  463. readonly content: ContentBlock[]
  464. readonly error?: never
  465. readonly meta?: JsonValue
  466. readonly additionalContexts?: UserMessage[]
  467. /** The agent loop stops after committing this successful result batch. */
  468. readonly concludesTurn?: true
  469. }
  470. /** Failed canonical tool execution; failures never carry a successful value. */
  471. export interface ToolExecutionFailure {
  472. readonly isError: true
  473. readonly error: ToolFailure
  474. readonly value?: never
  475. readonly content: ContentBlock[]
  476. readonly meta?: JsonValue
  477. readonly additionalContexts?: UserMessage[]
  478. readonly concludesTurn?: never
  479. }
  480. /** The discriminated, execution-local outcome of one tool call. */
  481. export type ToolExecutionResult = ToolExecutionSuccess | ToolExecutionFailure
  482. /**
  483. * Pre-dispatch decision. `allow` runs the call; `deny` materializes an error;
  484. * `ask` runs only after an approval service returns `allowed-once` and otherwise
  485. * denies. Input rewriting is excluded because arguments are already logged and
  486. * presented.
  487. */
  488. export type PreToolDecision =
  489. | { kind: 'allow' }
  490. | { kind: 'deny'; reason: string }
  491. | { kind: 'ask'; reason?: string }
  492. /**
  493. * Post-dispatch decision: accept, replace one projection, attach context for the
  494. * next request, or block by turning corrective feedback into an error result.
  495. */
  496. export type PostToolDecision =
  497. | { kind: 'accept'; content?: ContentBlock[]; value?: never; additionalContexts?: UserMessage[] }
  498. | { kind: 'accept'; value: JsonValue; content?: never; additionalContexts?: UserMessage[] }
  499. | { kind: 'block'; feedback: ContentBlock[]; additionalContexts?: UserMessage[] }
  500. /**
  501. * Best-effort human-readable message from an arbitrary thrown value: Error
  502. * instances use `.message`; non-Error objects with a string `message`
  503. * property (e.g. `throw { message: 'denied' }`) use it too; everything else
  504. * is stringified.
  505. */
  506. function errorMessage(error: unknown): string {
  507. try {
  508. if (error instanceof Error) return error.message
  509. if (typeof error === 'object' && error !== null
  510. && 'message' in error && typeof error.message === 'string') {
  511. return error.message
  512. }
  513. return String(error)
  514. } catch {
  515. // A hostile thrown value can trap `instanceof`, property access, or string
  516. // coercion. Error normalization is the outermost safety boundary, so its
  517. // fallback must itself be total.
  518. return '<unprintable thrown value>'
  519. }
  520. }
  521. /** Derive one failure message from policy feedback without changing its rendered blocks. */
  522. function failureMessageFromContent(content: ContentBlock[]): string {
  523. const text = content
  524. .map(block => block.type === 'text' ? block.text : `[${block.type} content]`)
  525. .join('\n')
  526. return text.length > 0 ? text : 'tool result blocked by post-execute policy'
  527. }
  528. /** Snapshot and freeze one durable tool-result projection or reject lossy data. */
  529. function materializePresentation<T>(candidate: T): T {
  530. const detached = snapshotJsonValue(candidate)
  531. if (detached === undefined) {
  532. throw new TypeError('tool result must be losslessly JSON-serializable')
  533. }
  534. return deepFreeze(detached)
  535. }
  536. /** Structured `{ name, code }` for a thrown HarnessError, else undefined. */
  537. function errorInfo(error: unknown): ToolErrorInfo | undefined {
  538. try {
  539. return error instanceof HarnessError ? { name: error.name, code: error.code } : undefined
  540. } catch {
  541. return undefined
  542. }
  543. }
  544. /** How the registry presents its tools to the model (see {@link Config.mode}). */
  545. export type ToolPresentationMode = 'native' | 'code' | 'both'
  546. /** Plugin config: how the registered tools are presented to the model. */
  547. export interface Config {
  548. /**
  549. * Model presentation. `native` (default) sends every visible schema; `code`
  550. * sends only `run_code` plus a generated SDK prompt; `both` sends both forms.
  551. * Code modes require a TypeScript runtime and fail prompt assembly when it is
  552. * absent or mismatched. Under `code`, native names in `toolOrder` are invalid.
  553. */
  554. mode?: ToolPresentationMode
  555. /**
  556. * Concurrency cap for a `run_code` program's overlapping sub-calls
  557. * (default 10, the loop scheduler's own default). Sub-calls follow the
  558. * native scheduling contract — only calls whose tools classify
  559. * concurrency-safe overlap; exclusive calls form barriers — so `1`
  560. * restores strictly serial dispatch. Must be a positive integer.
  561. */
  562. maxParallelSubCalls?: number
  563. }
  564. /**
  565. * Per-scope filter over global tools. Restrictions intersect and do not affect
  566. * scoped registrations or the reserved Code Mode transport.
  567. */
  568. export interface ToolRestriction {
  569. /** Global tool names that stay visible; everything else is removed. */
  570. readonly allow?: readonly string[]
  571. /** Global tool names removed from visibility. */
  572. readonly deny?: readonly string[]
  573. }
  574. /** One restriction compiled at registration for repeated live-global lookup. */
  575. interface CompiledToolRestriction {
  576. readonly allow?: ReadonlySet<string>
  577. readonly deny?: ReadonlySet<string>
  578. }
  579. /** One scope's complete registry view, derived in a single layer traversal. */
  580. interface ToolView {
  581. /** Visible definitions after restrictions, scoped shadowing, and transport insertion. */
  582. readonly visible: ReadonlyMap<string, ToolDefinition>
  583. /** Pre-restriction capability names used by prompt-order validation. */
  584. readonly knownNames: ReadonlySet<string>
  585. /** Current global names that a scoped restriction may name. */
  586. readonly restrictableNames: ReadonlySet<string>
  587. }
  588. /**
  589. * A monotonic execution guard evaluated after every `tools/pre-execute`
  590. * listener and before the tool body. Returning a reason denies the call;
  591. * returning `undefined` leaves it unchanged. Because guards have no allow
  592. * result, listener ordering cannot turn a denial back into permission.
  593. * @param execution - the identity-protected call after extensible pre-execute policy completed.
  594. * @returns a final denial reason, or `undefined` to leave the call allowed.
  595. */
  596. export type ToolGuard = (execution: Readonly<ToolExecution>) => string | undefined
  597. /** One scope's complete tool-registry contribution. */
  598. class ToolLayer implements ScopeLayer {
  599. readonly tools: NamedEntries<ToolDefinition>
  600. readonly restrictions = new AnonymousEntries<CompiledToolRestriction>()
  601. readonly guards = new AnonymousEntries<ToolGuard>()
  602. constructor(scope: ScopeKey | undefined) {
  603. this.tools = new NamedEntries(name => new Error(scope === undefined
  604. ? `tool "${name}" is already registered (for a per-agent variant, register through that agent's \`agent.ctx\` instead)`
  605. : `tool "${name}" is already registered in this scope`))
  606. }
  607. /** Whether every contribution table in this aggregate layer is empty. */
  608. isEmpty(): boolean {
  609. return this.tools.isEmpty() && this.restrictions.isEmpty() && this.guards.isEmpty()
  610. }
  611. /** Whether every compiled restriction in this layer admits a global tool name. */
  612. admits(name: string): boolean {
  613. for (const filter of this.restrictions.values()) {
  614. if ((filter.allow !== undefined && !filter.allow.has(name))
  615. || (filter.deny !== undefined && filter.deny.has(name))) return false
  616. }
  617. return true
  618. }
  619. /** First monotonic denial from this layer's live guard registrations. */
  620. guardReason(exec: ToolExecution): string | undefined {
  621. for (const guard of this.guards.values()) {
  622. const reason = guard(exec)
  623. if (reason !== undefined) return reason
  624. }
  625. return undefined
  626. }
  627. }
  628. /** Approval decision plus whether the approval channel reported cancellation. */
  629. interface ToolAskResolution {
  630. readonly decision: Extract<PreToolDecision, { kind: 'allow' | 'deny' }>
  631. readonly approvalCancelled: boolean
  632. }
  633. /** Caller cancellation and dispatch state kept outside the around-wrapper view. */
  634. interface ToolCancellationState {
  635. readonly callerSignal: AbortSignal
  636. bodyInvoked: boolean
  637. }
  638. /** One dispatch-scoped fused signal plus listener cleanup after the body settles. */
  639. interface FusedToolSignal {
  640. readonly signal: AbortSignal
  641. dispose(): void
  642. }
  643. /** Resolve the run_code overlap cap at the owning config boundary (direct construction bypasses the Loader schema). */
  644. function resolveMaxParallelSubCalls(value: number | undefined): number {
  645. const maxParallelSubCalls = value ?? 10
  646. if (!Number.isInteger(maxParallelSubCalls) || maxParallelSubCalls < 1) {
  647. throw new Error('maxParallelSubCalls must be a positive integer')
  648. }
  649. return maxParallelSubCalls
  650. }
  651. /**
  652. * Tool registry and execution pipeline. Scoped registrations shadow globals;
  653. * one visibility resolver feeds presentation, lookup, and dispatch.
  654. */
  655. export class ToolRegistry extends Service {
  656. static inject = ['systemPrompt']
  657. static Config: z<Config> = z.object({
  658. mode: z.union(['native', 'code', 'both'] as const).default('native'),
  659. maxParallelSubCalls: z.natural().min(1).default(10),
  660. })
  661. /** Internal staged view consumed by `dsh-agent-loop`'s parallel scheduler. */
  662. readonly [TOOL_REGISTRY_SCHEDULER]: ToolRegistryScheduler = {
  663. prepare: exec => this.prepareScheduledExecution(exec),
  664. dispatch: exec => this.dispatchScheduledExecution(exec),
  665. finalize: (exec, result) => this.finalizeScheduledExecution(exec, result),
  666. finish: (exec, result) => this.finishScheduledExecution(exec, result),
  667. }
  668. /** Context deferred by a running tool body, keyed by its scheduler-owned execution. */
  669. private deferredContexts = new WeakMap<ToolRunContext, UserMessage[]>()
  670. /** Executions whose tool body declared the current turn complete. */
  671. private concludingExecutions = new WeakSet<ToolExecution>()
  672. /** Original caller cancellation, kept outside the wrapper-mutable execution object. */
  673. private cancellationStates = new WeakMap<ToolRunContext, ToolCancellationState>()
  674. /** Definition-owned final content transform snapshotted before policy begins. */
  675. private contentFinalizers = new WeakMap<ToolRunContext, ToolDefinition['finalizeContent']>()
  676. private readonly layers = new ScopedLayers(
  677. scope => new ToolLayer(scope),
  678. () => { this.ctx.emit('tools/change') },
  679. )
  680. private readonly mode: ToolPresentationMode
  681. /** Reserved presentation transport, kept outside the filterable registration layers. */
  682. private readonly codeTransport: ToolDefinition | undefined
  683. constructor(ctx: Context, config: Config = {}) {
  684. super(ctx, 'tools')
  685. // The schema already defaulted an omitted mode; the ?? narrows the
  686. // optional-input type for direct (non-Loader) construction in tests.
  687. this.mode = config.mode ?? 'native'
  688. // `run_code` is presentation infrastructure, not an end capability. It
  689. // therefore does not enter the global layer: per-agent restrictions must
  690. // not remove it, and a scoped registration must not shadow it. The
  691. // visibility resolver appends this reserved definition after resolving
  692. // the filterable global/scoped capability layers.
  693. this.codeTransport = this.mode === 'native'
  694. ? undefined
  695. : createRunCodeTool(this, {
  696. requireRuntime: () => this.requireCodeRuntime(),
  697. maxParallel: resolveMaxParallelSubCalls(config.maxParallelSubCalls),
  698. shapeDispatchLog: dispatch => this.shapeDispatchLog(dispatch),
  699. })
  700. ctx.systemPrompt.tools(context => this.wireSchemas(context.scope))
  701. if (this.mode !== 'native') {
  702. ctx.systemPrompt.section({
  703. name: 'tools:sdk',
  704. order: SDK_SECTION_ORDER,
  705. // Regenerate from the calling scope's visible tools in stable order.
  706. text: (context) => {
  707. this.requireCodeRuntime()
  708. return renderToolsSdk(this.sdkSchemas(context.scope))
  709. },
  710. })
  711. }
  712. }
  713. /**
  714. * Build one scope's wire schemas and names for prompt-order validation.
  715. * Restrictions do not make known tools invalid, but a mode collapse does.
  716. */
  717. private wireSchemas(scope?: ScopeKey): ToolProviderResult {
  718. const view = this.view(scope)
  719. const schemas = [...view.visible.values()].map(definition => this.schemaOf(definition, false))
  720. if (this.mode === 'native') {
  721. return { schemas, knownNames: [...view.knownNames] }
  722. }
  723. this.requireCodeRuntime()
  724. if (this.mode === 'code') {
  725. return {
  726. schemas: schemas.filter(schema => schema.name === RUN_CODE_NAME),
  727. knownNames: [RUN_CODE_NAME],
  728. }
  729. }
  730. return { schemas, knownNames: [...view.knownNames, RUN_CODE_NAME] }
  731. }
  732. /**
  733. * Resolve the code runtime or throw the actionable misconfiguration error.
  734. * Read at use time (assembly / run_code execution), NOT via static
  735. * `inject`: an inject entry would hold `ctx.tools` — and every tool plugin
  736. * behind it — hostage to a code runtime existing even under `mode:
  737. * 'native'` (the loop's optional-backend idiom, same as
  738. * `sessionPersistence`).
  739. */
  740. private requireCodeRuntime(): CodeRuntime {
  741. const runtime = this.ctx.get('codeRuntime')
  742. if (!runtime) {
  743. throw new Error(`dsh-tools: mode "${this.mode}" requires a code runtime — load a ctx.codeRuntime implementation (e.g. @deepseek-ai/dsh-code-runtime-worker) or set tools mode to "native"`)
  744. }
  745. if (runtime.language !== 'typescript') {
  746. throw new Error(`dsh-tools: mode "${this.mode}" generates a TypeScript SDK, but the loaded code runtime's language is "${runtime.language}"`)
  747. }
  748. return runtime
  749. }
  750. /**
  751. * Register globally or in the calling agent scope. Scoped tools shadow
  752. * globals; duplicates within one layer and the reserved `run_code` name fail.
  753. * @param definition - tool schema, execution, and optional finalization/presentation callbacks.
  754. * @returns the exact disposer that unregisters the tool.
  755. */
  756. register(definition: ToolDefinition): () => void {
  757. const name = definition.name
  758. const output = (definition as Partial<ToolDefinition>).output
  759. if (output === undefined || typeof output !== 'object'
  760. || typeof output.render !== 'function'
  761. || (output.presentationMeta !== undefined && typeof output.presentationMeta !== 'function')) {
  762. throw new TypeError(`tool "${name}" must declare output { schema, render, presentationMeta? }`)
  763. }
  764. assertSupportedJsonSchema(output.schema)
  765. const timeoutMs = definition.timeoutMs
  766. if (timeoutMs !== undefined
  767. && (!Number.isFinite(timeoutMs) || timeoutMs <= 0)) {
  768. throw new TypeError(`tool "${name}" timeoutMs must be a positive finite number`)
  769. }
  770. if (this.codeTransport !== undefined && name === RUN_CODE_NAME) {
  771. throw new Error(`tool name "${RUN_CODE_NAME}" is reserved for the Code Mode presentation transport and cannot be registered or shadowed`)
  772. }
  773. return this.layers.effect(
  774. this.ctx,
  775. layer => layer.tools.insert(name, definition),
  776. { label: 'tools.register()' },
  777. )
  778. }
  779. /**
  780. * Restrict global tools for the calling agent scope. Empty filters, unknown
  781. * names, scope-local names, and reserved transport names fail. Restrictions
  782. * intersect; scoped registrations remain visible.
  783. * @param filter - global-surface mask: `allow` (keep only) and/or `deny` (remove).
  784. * @returns the exact disposer that lifts this restriction.
  785. */
  786. restrict(filter: ToolRestriction): () => void {
  787. const scope = scopeOf(this.ctx)
  788. if (scope === undefined) {
  789. throw new Error('tools.restrict() requires a scoped context (agent.ctx): a context-global restriction would mask every agent — deny the tool for the intended agent instead')
  790. }
  791. const allow = filter.allow
  792. const deny = filter.deny
  793. if (allow === undefined && deny === undefined) {
  794. throw new Error('tools.restrict({}) is a no-op: pass `allow` and/or `deny` (an empty filter is almost always a materialized-empty-config bug)')
  795. }
  796. const compiled: CompiledToolRestriction = {
  797. ...allow !== undefined ? { allow: new Set(allow) } : {},
  798. ...deny !== undefined ? { deny: new Set(deny) } : {},
  799. }
  800. if (this.codeTransport !== undefined
  801. && [...allow ?? [], ...deny ?? []].includes(RUN_CODE_NAME)) {
  802. throw new Error(`tools.restrict() cannot name reserved Code Mode presentation transport "${RUN_CODE_NAME}"; restrict end-capability tools instead`)
  803. }
  804. const known = this.view(scope).restrictableNames
  805. const unknown = [...allow ?? [], ...deny ?? []].filter(name => !known.has(name))
  806. if (unknown.length > 0) {
  807. throw new Error(`tools.restrict() names unknown global tool${unknown.length > 1 ? 's' : ''} ${unknown.map(n => `"${n}"`).join(', ')}; known global tools: ${[...known].sort().join(', ') || '(none)'}`)
  808. }
  809. return this.layers.effect(
  810. this.ctx,
  811. layer => layer.restrictions.append(compiled),
  812. { label: 'tools.restrict()' },
  813. )
  814. }
  815. /**
  816. * Register a monotonic guard after the extensible `tools/pre-execute`
  817. * waterfall. A plain-context guard applies globally; one registered through
  818. * `agent.ctx` applies only to that agent. Any matching guard may deny by
  819. * returning a reason, while no guard can force-allow a call another guard
  820. * denied. The exact effect disposer is returned for ordered ownership and
  821. * HMR cleanup.
  822. * @param guard - synchronous check; a returned string denies the execution.
  823. * @returns the exact disposer that unregisters the guard.
  824. */
  825. guard(guard: ToolGuard): () => void {
  826. return this.layers.effect(
  827. this.ctx,
  828. layer => layer.guards.append(guard),
  829. { label: 'tools.guard()', notify: false },
  830. )
  831. }
  832. /** First monotonic denial from the global then matching scoped guard layers. */
  833. private guardReason(exec: ToolExecution): string | undefined {
  834. const globalReason = this.layers.global.guardReason(exec)
  835. if (globalReason !== undefined) return globalReason
  836. return exec.agent === undefined ? undefined : this.layers.peek(exec.agent)?.guardReason(exec)
  837. }
  838. /**
  839. * Resolve every registry fact one scope needs in one layer traversal. The
  840. * visible map applies global restrictions, scoped shadowing, and the reserved
  841. * presentation transport; the other sets retain the pre-restriction facts
  842. * needed by restriction and prompt-order validation.
  843. * @param scope - the viewing scope (the agent), or undefined for the global view.
  844. * @returns the complete derived view for that scope.
  845. */
  846. private view(scope?: ScopeKey): ToolView {
  847. const layer = this.layers.peek(scope)
  848. const visible = new Map<string, ToolDefinition>()
  849. const knownNames = new Set<string>()
  850. const restrictableNames = new Set<string>()
  851. for (const [name, definition] of this.layers.global.tools.entries()) {
  852. knownNames.add(name)
  853. restrictableNames.add(name)
  854. if (layer?.admits(name) ?? true) visible.set(name, definition)
  855. }
  856. // Scoped layer second: same-name entries REPLACE (shadow) the global ones,
  857. // and scope-local registrations are never part of the global filter above.
  858. for (const [name, definition] of layer?.tools.entries() ?? []) {
  859. knownNames.add(name)
  860. visible.set(name, definition)
  861. }
  862. // Presentation infrastructure is resolved last and outside capability
  863. // filtering. Registration rejects this reserved name, so the insertion is
  864. // an invariant assertion as well as protection against future layer changes.
  865. if (this.codeTransport !== undefined) {
  866. visible.set(RUN_CODE_NAME, this.codeTransport)
  867. }
  868. return { visible, knownNames, restrictableNames }
  869. }
  870. /**
  871. * Look up a tool as one scope sees it (scoped
  872. * shadows global; a restricted-away global reads as absent). Presenters pass
  873. * the calling agent so the rendered card matches the definition that
  874. * actually executed.
  875. * @param name - the tool name as registered.
  876. * @param scope - the viewing scope (the agent); omitted = the global view.
  877. * @returns the definition the scope resolves, or undefined when none is visible.
  878. */
  879. get(name: string, scope?: ScopeKey): ToolDefinition | undefined {
  880. return this.view(scope).visible.get(name)
  881. }
  882. /**
  883. * Project visible definitions onto the allowlisted model-facing schema fields,
  884. * excluding execution and presentation callbacks.
  885. * @param scope - the viewing scope (the agent); omitted = the global view.
  886. * @returns one deep-cloned schema per visible tool.
  887. */
  888. schemas(scope?: ScopeKey): ToolSchema[] {
  889. return [...this.view(scope).visible.values()].map(definition => this.schemaOf(definition, true))
  890. }
  891. /** Project visible callable tools onto the generated Code Mode SDK contract. */
  892. private sdkSchemas(scope?: ScopeKey): ToolSdkSchema[] {
  893. return [...this.view(scope).visible.values()]
  894. .filter(definition => definition.name !== RUN_CODE_NAME)
  895. .map((definition): ToolSdkSchema => {
  896. const output = snapshotJsonValue(definition.output.schema)
  897. /* v8 ignore next -- registration already validated and retained this schema as lossless JSON. */
  898. if (output === undefined) {
  899. throw new Error(`tool "${definition.name}" output schema must be lossless JSON before SDK projection`)
  900. }
  901. return {
  902. ...this.schemaOf(definition, true),
  903. output,
  904. }
  905. })
  906. }
  907. /** Project one definition onto the model-facing schema fields. */
  908. private schemaOf(definition: ToolDefinition, detachParameters: boolean): ToolSchema {
  909. const { name, description, parameters } = definition
  910. const detached = detachParameters ? snapshotJsonValue(parameters) : parameters
  911. if (detached === undefined) {
  912. throw new Error(`tool "${name}" parameters must be lossless JSON before schema projection`)
  913. }
  914. return {
  915. name,
  916. description,
  917. parameters: detached,
  918. }
  919. }
  920. /**
  921. * Classify a pending call through the caller's visible tool definition. Only
  922. * an exact `true` is parallel; unknown, hidden, undeclared, invalid, or
  923. * throwing classifiers are exclusive.
  924. * @param exec - call name, parsed arguments, and optional agent scope.
  925. * @returns the fail-closed scheduling mode.
  926. */
  927. executionMode(exec: ToolExecutionInput): ToolExecutionMode {
  928. const tool = this.get(exec.name, exec.agent)
  929. if (!tool?.isConcurrencySafe) return { kind: 'exclusive' }
  930. try {
  931. const concurrencySafe: unknown = tool.isConcurrencySafe(exec.arguments)
  932. return concurrencySafe === true ? { kind: 'parallel' } : { kind: 'exclusive' }
  933. } catch {
  934. return { kind: 'exclusive' }
  935. }
  936. }
  937. /**
  938. * Run the `tools/code-dispatch-log` waterfall over one settled sub-dispatch
  939. * and return the content the bridge should log on `tool/code-dispatch`.
  940. * Contained: a throwing listener falls back to the unshaped content — log
  941. * shaping must never fail the dispatch or lose the settle event. Private:
  942. * the ONE consumer is the `run_code` bridge this registry constructs, which
  943. * receives it as a capability parameter (the `requireRuntime` idiom) — the
  944. * waterfall, not this invoker, is the public extension seam.
  945. */
  946. private async shapeDispatchLog(dispatch: CodeDispatchLog): Promise<ContentBlock[]> {
  947. try {
  948. return await this.ctx.waterfall(
  949. scopeTarget(this, dispatch.agent), 'tools/code-dispatch-log', dispatch,
  950. () => Promise.resolve(dispatch.content),
  951. )
  952. } catch (error: unknown) {
  953. this.ctx.logger.warn(`tools: code-dispatch-log listener failed for ${dispatch.name}: ${errorMessage(error)}; logging the unshaped content`)
  954. return dispatch.content
  955. }
  956. }
  957. /**
  958. * Execute through pre-policy, guards, around-dispatch, post-policy,
  959. * definition-owned content finalization, and final notification. Tool and
  960. * listener failures resolve as materialized error results; an invisible tool
  961. * reports `UNKNOWN_TOOL`. The returned outcome is the same lossless, frozen
  962. * snapshot final observers receive. Cancellation
  963. * arriving after entry and before final result materialization skips a
  964. * not-yet-started body with `ABORTED_BEFORE_DISPATCH` or replaces a
  965. * successful started outcome with `ABORTED`; already-started work is still
  966. * drained and may retain a tool-owned structured error.
  967. * @param exec - the typed same-process call input. The registry assigns its
  968. * correlation token before policy begins.
  969. * @returns the materialized final result.
  970. */
  971. async execute(exec: ToolExecutionInput): Promise<ToolExecutionResult> {
  972. return this.prepareExecution(exec, prepared => this.completeScheduledExecution(prepared))
  973. }
  974. private async completeScheduledExecution(prepared: ScheduledToolPreparation): Promise<ToolExecutionResult> {
  975. switch (prepared.kind) {
  976. case 'dispatch': {
  977. const dispatched = await this.dispatchScheduledExecution(prepared.exec)
  978. return dispatched.kind === 'post-result'
  979. ? await this.finalizeScheduledExecution(prepared.exec, dispatched.result)
  980. : this.finishScheduledExecution(prepared.exec, dispatched.result)
  981. }
  982. case 'post-result':
  983. return await this.finalizeScheduledExecution(prepared.exec, prepared.result)
  984. case 'final-result':
  985. return this.finishScheduledExecution(prepared.exec, prepared.result)
  986. /* v8 ignore next -- closed-union exhaustiveness guard */
  987. default:
  988. return assertNever(prepared, 'scheduled tool preparation')
  989. }
  990. }
  991. private createExecution(exec: ToolExecutionInput): ScheduledToolPreparation | { kind: 'ready'; exec: MutableToolRunContext } {
  992. const deferredContexts: UserMessage[] = []
  993. const token = createExecutionToken()
  994. const callId = exec.callId
  995. const name = exec.name
  996. const agent = exec.agent
  997. const parent = exec.parent
  998. const signal = exec.signal
  999. const definition = this.get(name, agent)
  1000. const finalizeContent = definition?.finalizeContent?.bind(definition)
  1001. const concludingExecutions = this.concludingExecutions
  1002. const base = {
  1003. token,
  1004. callId,
  1005. name,
  1006. signal,
  1007. ...agent !== undefined ? { agent } : {},
  1008. ...parent !== undefined ? { parent } : {},
  1009. deferContext(context: UserMessage): void {
  1010. deferredContexts.push(context)
  1011. },
  1012. concludeTurn(): void {
  1013. concludingExecutions.add(this as unknown as ToolExecution)
  1014. },
  1015. }
  1016. try {
  1017. const detached = snapshotJsonValue(exec.arguments)
  1018. if (detached === undefined) {
  1019. throw new TypeError('tool execution arguments must be losslessly JSON-serializable')
  1020. }
  1021. const execution: MutableToolRunContext = { ...base, arguments: deepFreeze(detached) }
  1022. this.deferredContexts.set(execution, deferredContexts)
  1023. this.contentFinalizers.set(execution, finalizeContent)
  1024. this.cancellationStates.set(execution, {
  1025. callerSignal: signal,
  1026. bodyInvoked: false,
  1027. })
  1028. return { kind: 'ready', exec: execution }
  1029. } catch (error: unknown) {
  1030. const execution: MutableToolRunContext = { ...base, arguments: undefined }
  1031. this.contentFinalizers.set(execution, finalizeContent)
  1032. return { kind: 'final-result', exec: execution, result: toolErrorResult(error) }
  1033. }
  1034. }
  1035. /**
  1036. * Run the ordered pre-execute and monotonic guard stages for the scheduler.
  1037. * @param input - the caller-supplied execution input.
  1038. * @returns the prepared execution plus the next scheduler stage.
  1039. * @internal
  1040. */
  1041. private async prepareScheduledExecution(input: ToolExecutionInput): Promise<ScheduledToolPreparation> {
  1042. return this.prepareExecution(input, prepared => prepared)
  1043. }
  1044. private async prepareExecution<T>(
  1045. input: ToolExecutionInput,
  1046. next: (prepared: ScheduledToolPreparation) => T | PromiseLike<T>,
  1047. ): Promise<T> {
  1048. const created = this.createExecution(input)
  1049. if (created.kind !== 'ready') return next(created)
  1050. const exec = created.exec
  1051. if (this.callerCancelled(exec)) {
  1052. return next({ kind: 'final-result', exec, result: toolAbortedBeforeDispatchResult() })
  1053. }
  1054. try {
  1055. const carrier = scopeTarget(this, exec.agent)
  1056. const gate = await this.ctx.waterfall(
  1057. carrier, 'tools/pre-execute', exec,
  1058. () => Promise.resolve<PreToolDecision>({ kind: 'allow' }),
  1059. )
  1060. const askResolution: ToolAskResolution = gate.kind === 'ask'
  1061. ? await this.serviceAsk(exec, gate)
  1062. : { decision: gate, approvalCancelled: false }
  1063. const { decision } = askResolution
  1064. if (this.callerCancelled(exec) && askResolution.approvalCancelled) {
  1065. return await next({ kind: 'post-result', exec, result: toolAbortedBeforeDispatchResult() })
  1066. }
  1067. const denialReason = decision.kind === 'allow'
  1068. ? this.guardReason(exec)
  1069. : decision.reason
  1070. if (denialReason !== undefined) {
  1071. return await next({
  1072. kind: 'post-result',
  1073. exec,
  1074. result: this.materializeFinalResult({
  1075. content: [{ type: 'text', text: `Error: ${denialReason}` }],
  1076. isError: true,
  1077. error: { message: denialReason },
  1078. }),
  1079. })
  1080. }
  1081. if (this.callerCancelled(exec)) {
  1082. return await next({ kind: 'post-result', exec, result: toolAbortedBeforeDispatchResult() })
  1083. }
  1084. return await next({ kind: 'dispatch', exec })
  1085. } catch (error: unknown) {
  1086. return next({ kind: 'final-result', exec, result: toolErrorResult(error) })
  1087. }
  1088. }
  1089. /** Whether the original caller signal is currently aborted. */
  1090. private callerCancelled(exec: ToolRunContext): boolean {
  1091. const state = this.cancellationStates.get(exec)
  1092. /* v8 ignore next -- only registry-minted executions reach the staged scheduler methods */
  1093. if (state === undefined) throw new Error('tool registry scheduler invariant violated: missing cancellation state')
  1094. return state.callerSignal.aborted
  1095. }
  1096. /** Canonical cancellation outcome selected by whether the tool body started. */
  1097. private cancellationResult(exec: ToolRunContext, prior?: ToolExecutionResult): ToolExecutionResult {
  1098. const state = this.cancellationStates.get(exec)
  1099. /* v8 ignore next -- only registry-minted executions reach the staged scheduler methods */
  1100. if (state === undefined) throw new Error('tool registry scheduler invariant violated: missing cancellation state')
  1101. return state.bodyInvoked
  1102. ? toolAbortedResult(prior)
  1103. : toolAbortedBeforeDispatchResult(prior)
  1104. }
  1105. /**
  1106. * Dispatch the registered body with the original caller signal fused back
  1107. * into any around-wrapper replacement. Cancellation never abandons the body:
  1108. * a started promise reaches quiescence before its outcome becomes `ABORTED`.
  1109. */
  1110. private async dispatchToolBody(exec: MutableToolRunContext): Promise<ToolExecutionResult> {
  1111. const state = this.cancellationStates.get(exec)
  1112. /* v8 ignore next -- only registry-minted executions reach the staged scheduler methods */
  1113. if (state === undefined) throw new Error('tool registry scheduler invariant violated: missing cancellation state')
  1114. const wrapperSignal = exec.signal
  1115. const fused = fuseToolSignals(state.callerSignal, wrapperSignal)
  1116. const signal = fused.signal
  1117. if (isAborted(signal)) {
  1118. fused.dispose()
  1119. return toolAbortedBeforeDispatchResult()
  1120. }
  1121. exec.signal = signal
  1122. try {
  1123. const tool = this.get(exec.name, exec.agent)
  1124. if (!tool) throw new ToolNotFoundError(exec.name)
  1125. state.bodyInvoked = true
  1126. const returned = await tool.execute(exec.arguments, exec)
  1127. const result = this.createSuccessResult(exec, tool, returned)
  1128. return isAborted(signal)
  1129. ? toolAbortedResult(result)
  1130. : result
  1131. } catch (error: unknown) {
  1132. return toolErrorResult(error)
  1133. } finally {
  1134. fused.dispose()
  1135. exec.signal = wrapperSignal
  1136. }
  1137. }
  1138. /**
  1139. * Run around-dispatch and the tool body. Tool and unknown-tool failures still
  1140. * receive post-execute; pipeline failures are already final.
  1141. * @param exec - the prepared execution.
  1142. * @returns whether the result still needs post-execute.
  1143. * @internal
  1144. */
  1145. private async dispatchScheduledExecution(exec: ToolRunContext): Promise<ScheduledToolDispatch> {
  1146. try {
  1147. const mutableExec = exec as MutableToolRunContext
  1148. const carrier = scopeTarget(this, exec.agent)
  1149. const result = await this.ctx.waterfall(
  1150. carrier, 'tools/execute', mutableExec,
  1151. () => this.dispatchToolBody(mutableExec),
  1152. )
  1153. const normalized = this.normalizeDispatchResult(exec, result)
  1154. const deferredContexts = this.deferredContexts.get(exec)
  1155. /* v8 ignore next -- dispatch only receives executions minted by this registry's prepare stage */
  1156. if (deferredContexts === undefined) throw new Error('tool registry scheduler invariant violated: unprepared execution')
  1157. const resultWithDeferredContexts: ToolExecutionResult = deferredContexts.length === 0
  1158. ? normalized
  1159. : this.markCanonical(exec, {
  1160. ...normalized,
  1161. additionalContexts: [
  1162. ...deferredContexts,
  1163. ...normalized.additionalContexts ?? [],
  1164. ],
  1165. })
  1166. return {
  1167. kind: 'post-result',
  1168. result: this.callerCancelled(exec) && !resultWithDeferredContexts.isError
  1169. ? this.cancellationResult(exec, resultWithDeferredContexts)
  1170. : resultWithDeferredContexts,
  1171. }
  1172. } catch (error: unknown) {
  1173. return { kind: 'final-result', result: toolErrorResult(error) }
  1174. }
  1175. }
  1176. /**
  1177. * Run ordered post-execute, then apply definition-owned content finalization,
  1178. * materialize, and notify the final outcome.
  1179. * @param exec - the prepared execution.
  1180. * @param result - dispatch/pre result that still needs post-execute.
  1181. * @returns the materialized final result.
  1182. * @internal
  1183. */
  1184. private async finalizeScheduledExecution(exec: ToolRunContext, result: ToolExecutionResult): Promise<ToolExecutionResult> {
  1185. try {
  1186. const postResult = await this.postExecute(exec, result)
  1187. return this.finishScheduledExecution(
  1188. exec,
  1189. this.callerCancelled(exec) && !postResult.isError
  1190. ? this.cancellationResult(exec, postResult)
  1191. : postResult,
  1192. )
  1193. } catch (error: unknown) {
  1194. return this.finishScheduledExecution(exec, toolErrorResult(error))
  1195. }
  1196. }
  1197. /**
  1198. * Materialize the candidate, apply definition-owned content finalization,
  1199. * then materialize and notify the authoritative result.
  1200. * @param exec - the prepared execution.
  1201. * @param result - final result.
  1202. * @returns the materialized final result.
  1203. * @internal
  1204. */
  1205. private finishScheduledExecution(exec: ToolRunContext, result: ToolExecutionResult): ToolExecutionResult {
  1206. let materializedResult: ToolExecutionResult
  1207. try {
  1208. materializedResult = this.materializeFinalResult(result)
  1209. } catch (error: unknown) {
  1210. materializedResult = this.materializeFinalResult(toolErrorResult(error))
  1211. }
  1212. let finalResult: ToolExecutionResult
  1213. try {
  1214. finalResult = this.materializeFinalResult(this.applyFinalContent(exec, materializedResult))
  1215. } catch (error: unknown) {
  1216. finalResult = this.materializeFinalResult(toolErrorResult(error))
  1217. }
  1218. this.notifyResult(exec, finalResult)
  1219. return finalResult
  1220. }
  1221. /** Apply the snapshotted tool-owned content transform without exposing other result fields. */
  1222. private applyFinalContent(exec: ToolRunContext, result: ToolExecutionResult): ToolExecutionResult {
  1223. const finalizeContent = this.contentFinalizers.get(exec)
  1224. if (finalizeContent === undefined) return result
  1225. const content = finalizeContent(exec, result)
  1226. return content === undefined ? result : { ...result, content }
  1227. }
  1228. /** Notify observers without exposing a mutation or error channel into the outcome. */
  1229. private notifyResult(exec: ToolExecution, result: ToolExecutionResult): void {
  1230. // Freeze the registry's live object before observers receive its readonly
  1231. // WeakMap-keyable view.
  1232. Object.freeze(exec)
  1233. const { name: toolName, callId } = exec
  1234. const reportFailure = (error: unknown): void => {
  1235. this.ctx.logger.warn(`tool "${toolName}" (${callId}): tools/result observer failed: ${errorMessage(error)}`)
  1236. }
  1237. const callbacks = this.ctx.events.dispatch('emit', [
  1238. scopeTarget(this, exec.agent), 'tools/result', exec, result,
  1239. ])
  1240. for (const callback of callbacks) {
  1241. try {
  1242. const returned: unknown = callback(exec, result)
  1243. void Promise.resolve(returned).catch(reportFailure)
  1244. } catch (error: unknown) {
  1245. reportFailure(error)
  1246. }
  1247. }
  1248. }
  1249. /**
  1250. * Resolve an `ask` decision to allow/deny through the approval seam. The
  1251. * seam is consumed opportunistically with `ctx.get('approval')` — a
  1252. * deployment that composes no ApprovalService keeps the historical degrade
  1253. * to deny, and an unmount mid-session degrades the same way on the next ask.
  1254. * An agent-less execution also degrades: without an agent there is no
  1255. * session to audit to and no UI to route to. Otherwise the outcome maps
  1256. * one-to-one — `allowed-once` proceeds; the three non-grants deny with
  1257. * distinct reasons so the model can tell a human "no" from an absent
  1258. * approval channel.
  1259. */
  1260. private async serviceAsk(
  1261. exec: ToolExecution,
  1262. ask: Extract<PreToolDecision, { kind: 'ask' }>,
  1263. ): Promise<ToolAskResolution> {
  1264. const approval = this.ctx.get('approval')
  1265. if (approval === undefined) {
  1266. return {
  1267. decision: { kind: 'deny', reason: ask.reason ?? `tool "${exec.name}" requires approval (not yet supported)` },
  1268. approvalCancelled: false,
  1269. }
  1270. }
  1271. if (exec.agent === undefined) {
  1272. return {
  1273. decision: { kind: 'deny', reason: `tool "${exec.name}" requires approval, but the call has no agent to route it through` },
  1274. approvalCancelled: false,
  1275. }
  1276. }
  1277. const outcome = await approval.request({
  1278. agent: exec.agent,
  1279. toolName: exec.name,
  1280. callId: exec.callId,
  1281. ...ask.reason !== undefined ? { reason: ask.reason } : {},
  1282. signal: exec.signal,
  1283. })
  1284. switch (outcome) {
  1285. case 'allowed-once': return { decision: { kind: 'allow' }, approvalCancelled: false }
  1286. case 'rejected': return {
  1287. decision: { kind: 'deny', reason: `the user rejected tool "${exec.name}"` },
  1288. approvalCancelled: false,
  1289. }
  1290. case 'cancelled': return {
  1291. decision: { kind: 'deny', reason: `approval for tool "${exec.name}" was cancelled` },
  1292. approvalCancelled: true,
  1293. }
  1294. case 'unavailable': return {
  1295. decision: { kind: 'deny', reason: `tool "${exec.name}" requires approval, but no approval channel is available` },
  1296. approvalCancelled: false,
  1297. }
  1298. default: return assertNever(outcome, 'ApprovalOutcome')
  1299. }
  1300. }
  1301. /**
  1302. * Run the `tools/post-execute` waterfall over a dispatched `result` and apply
  1303. * its {@link PostToolDecision}: `accept` keeps the call successful (replacing
  1304. * `content` when given), `block` turns it into an `isError` whose content is
  1305. * the corrective `feedback`. Either decision may attach `additionalContexts`,
  1306. * which are ferried on the returned result for the loop's active-batch FIFO.
  1307. * Context deferred by the tool body survives an accepted result but is
  1308. * discarded when the outer call is blocked; a block exposes only context the
  1309. * blocking decision explicitly supplied.
  1310. * Runs inside `execute`'s outer try/catch (a throwing listener → isError).
  1311. */
  1312. private async postExecute(exec: ToolExecution, result: ToolExecutionResult): Promise<ToolExecutionResult> {
  1313. const decision = await this.ctx.waterfall(
  1314. scopeTarget(this, exec.agent), 'tools/post-execute', exec, result,
  1315. () => Promise.resolve<PostToolDecision>({ kind: 'accept' }),
  1316. )
  1317. const decisionContexts = decision.additionalContexts ?? []
  1318. if (decision.kind === 'block') {
  1319. const message = failureMessageFromContent(decision.feedback)
  1320. return this.markCanonical(exec, {
  1321. content: decision.feedback,
  1322. isError: true,
  1323. error: { message },
  1324. ...decisionContexts.length > 0 ? { additionalContexts: decisionContexts } : {},
  1325. })
  1326. }
  1327. if (Object.hasOwn(decision, 'content') && Object.hasOwn(decision, 'value')) {
  1328. throw new TypeError('tools/post-execute accept decision cannot replace both value and content')
  1329. }
  1330. const additionalContexts = [
  1331. ...result.additionalContexts ?? [],
  1332. ...decisionContexts,
  1333. ]
  1334. if (Object.hasOwn(decision, 'value')) {
  1335. if (result.isError) {
  1336. throw new TypeError('tools/post-execute cannot replace the value of a failed result')
  1337. }
  1338. const tool = this.get(exec.name, exec.agent)
  1339. if (tool === undefined) throw new ToolNotFoundError(exec.name)
  1340. const replaced = this.createSuccessResult(exec, tool, decision.value)
  1341. return this.markCanonical(exec, {
  1342. ...replaced,
  1343. ...additionalContexts.length > 0 ? { additionalContexts } : {},
  1344. })
  1345. }
  1346. return this.markCanonical(exec, {
  1347. ...result,
  1348. ...decision.content !== undefined ? { content: decision.content } : {},
  1349. ...additionalContexts.length > 0 ? { additionalContexts } : {},
  1350. })
  1351. }
  1352. /** Registry-normalized results and the exact dispatch that validated each value. */
  1353. private readonly canonicalResults = new WeakMap<object, ToolExecutionToken>()
  1354. /** Mark one registry-normalized result as canonical only for its owning dispatch. */
  1355. private markCanonical<T extends ToolExecutionResult>(exec: ToolExecution, result: T): T {
  1356. this.canonicalResults.set(result, exec.token)
  1357. return result
  1358. }
  1359. /** Snapshot, validate, render, and optionally project one successful body value. */
  1360. private createSuccessResult(exec: ToolExecution, tool: ToolDefinition, candidate: unknown): ToolExecutionSuccess {
  1361. const detached = snapshotToolValue(tool.name, candidate)
  1362. const violations = validateJsonSchemaValue(tool.output.schema, detached, 'value')
  1363. if (violations.length > 0) throw new ToolOutputError(tool.name, violations)
  1364. const value = deepFreeze(detached)
  1365. let rendered: ContentBlock[]
  1366. try {
  1367. rendered = tool.output.render(exec.arguments, value)
  1368. } catch (error: unknown) {
  1369. throw projectionError(tool.name, 'render', error)
  1370. }
  1371. const content = snapshotProjection(tool.name, 'render', rendered)
  1372. let meta: JsonValue | undefined
  1373. if (exec.parent === undefined && tool.output.presentationMeta !== undefined) {
  1374. let projected: JsonValue
  1375. try {
  1376. projected = tool.output.presentationMeta(exec.arguments, value)
  1377. } catch (error: unknown) {
  1378. throw projectionError(tool.name, 'presentationMeta', error)
  1379. }
  1380. meta = snapshotProjection(tool.name, 'presentationMeta', projected)
  1381. }
  1382. const concludesTurn = this.concludingExecutions.has(exec)
  1383. return this.markCanonical(exec, this.materializeFinalResult({
  1384. isError: false,
  1385. value,
  1386. content,
  1387. ...meta !== undefined ? { meta } : {},
  1388. ...concludesTurn ? { concludesTurn: true as const } : {},
  1389. }) as ToolExecutionSuccess)
  1390. }
  1391. /** Normalize an around-dispatch wrapper's authored result through the owning output contract. */
  1392. private normalizeDispatchResult(exec: ToolExecution, result: ToolExecutionResult): ToolExecutionResult {
  1393. if (this.canonicalResults.get(result) === exec.token) return result
  1394. if (result.isError) {
  1395. return this.markCanonical(exec, {
  1396. isError: true,
  1397. error: result.error,
  1398. content: result.content,
  1399. ...result.meta !== undefined ? { meta: result.meta } : {},
  1400. ...result.additionalContexts !== undefined ? { additionalContexts: result.additionalContexts } : {},
  1401. })
  1402. }
  1403. const tool = this.get(exec.name, exec.agent)
  1404. if (tool === undefined) throw new ToolNotFoundError(exec.name)
  1405. const normalized = this.createSuccessResult(exec, tool, result.value)
  1406. return this.markCanonical(exec, {
  1407. ...normalized,
  1408. ...result.additionalContexts !== undefined ? { additionalContexts: result.additionalContexts } : {},
  1409. })
  1410. }
  1411. /** Materialize the authoritative commit outcome once, immediately before `tools/result`. */
  1412. private materializeFinalResult(result: ToolExecutionResult): ToolExecutionResult {
  1413. const presentation = {
  1414. content: result.content,
  1415. ...result.meta !== undefined ? { meta: result.meta } : {},
  1416. ...result.additionalContexts !== undefined ? { additionalContexts: result.additionalContexts } : {},
  1417. }
  1418. if (result.isError) {
  1419. return materializePresentation({ isError: true as const, error: result.error, ...presentation })
  1420. }
  1421. const detached = materializePresentation({
  1422. isError: false as const,
  1423. ...presentation,
  1424. ...result.concludesTurn === true ? { concludesTurn: true as const } : {},
  1425. })
  1426. return deepFreeze({ ...detached, value: result.value })
  1427. }
  1428. }
  1429. /** Mint a same-process correlation token whose identity is its value. */
  1430. function createExecutionToken(): ToolExecutionToken {
  1431. return Symbol('dsh.tool.execution') as ToolExecutionToken
  1432. }
  1433. function toolErrorResult(error: unknown): ToolExecutionResult {
  1434. const info = errorInfo(error)
  1435. const message = errorMessage(error)
  1436. return {
  1437. content: [{ type: 'text', text: `Error: ${message}` }],
  1438. isError: true,
  1439. error: { message, ...info ? { info } : {} },
  1440. }
  1441. }
  1442. /** Read live abort state across an await without treating it as synchronously immutable. */
  1443. function isAborted(signal: AbortSignal): boolean {
  1444. return signal.aborted
  1445. }
  1446. /**
  1447. * Fuse caller and wrapper cancellation without nesting `AbortSignal.any`.
  1448. * Keeping the relay dispatch-scoped also removes listeners when work settles.
  1449. */
  1450. function fuseToolSignals(caller: AbortSignal, wrapper: AbortSignal): FusedToolSignal {
  1451. if (caller === wrapper) return { signal: caller, dispose() {} }
  1452. const controller = new AbortController()
  1453. let listening = false
  1454. const dispose = (): void => {
  1455. if (!listening) return
  1456. listening = false
  1457. caller.removeEventListener('abort', abortFromCaller)
  1458. wrapper.removeEventListener('abort', abortFromWrapper)
  1459. }
  1460. const abortFrom = (source: AbortSignal): void => {
  1461. const reason: unknown = source.reason
  1462. controller.abort(reason)
  1463. dispose()
  1464. }
  1465. const abortFromCaller = (): void => { abortFrom(caller) }
  1466. const abortFromWrapper = (): void => { abortFrom(wrapper) }
  1467. if (wrapper.aborted) abortFromWrapper()
  1468. else if (caller.aborted) abortFromCaller()
  1469. else {
  1470. listening = true
  1471. caller.addEventListener('abort', abortFromCaller, { once: true })
  1472. wrapper.addEventListener('abort', abortFromWrapper, { once: true })
  1473. }
  1474. return { signal: controller.signal, dispose }
  1475. }
  1476. /** Canonical result when cancellation supersedes success after body invocation. */
  1477. function toolAbortedResult(prior?: ToolExecutionResult): ToolExecutionResult {
  1478. const additionalContexts = prior?.additionalContexts ?? []
  1479. return {
  1480. content: [{ type: 'text', text: 'Error: tool call aborted' }],
  1481. isError: true,
  1482. error: {
  1483. message: 'tool call aborted',
  1484. info: { name: 'AbortError', code: TOOL_ABORTED },
  1485. },
  1486. ...additionalContexts.length > 0 ? { additionalContexts } : {},
  1487. }
  1488. }
  1489. /** Canonical result when cancellation prevents tool body invocation. */
  1490. function toolAbortedBeforeDispatchResult(prior?: ToolExecutionResult): ToolExecutionResult {
  1491. const additionalContexts = prior?.additionalContexts ?? []
  1492. return {
  1493. content: [{ type: 'text', text: 'Error: tool call aborted before dispatch' }],
  1494. isError: true,
  1495. error: {
  1496. message: 'tool call aborted before dispatch',
  1497. info: { name: 'AbortError', code: TOOL_ABORTED_BEFORE_DISPATCH },
  1498. },
  1499. ...additionalContexts.length > 0 ? { additionalContexts } : {},
  1500. }
  1501. }
  1502. export default ToolRegistry