index.ts 68 KB

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