index.ts 63 KB

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