index.ts 79 KB

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