index.ts 86 KB

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