index.ts 86 KB

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