@dsh-cc/tools 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. package/LICENSE +201 -0
  2. package/README.i18n.yaml +6 -0
  3. package/README.md +209 -0
  4. package/README.zh.md +200 -0
  5. package/lib/abort-utils.d.ts +80 -0
  6. package/lib/abort-utils.d.ts.map +1 -0
  7. package/lib/abort-utils.js +186 -0
  8. package/lib/abort-utils.js.map +1 -0
  9. package/lib/cc-names.d.ts +100 -0
  10. package/lib/cc-names.d.ts.map +1 -0
  11. package/lib/cc-names.js +197 -0
  12. package/lib/cc-names.js.map +1 -0
  13. package/lib/code-mode.d.ts +46 -0
  14. package/lib/code-mode.d.ts.map +1 -0
  15. package/lib/code-mode.js +380 -0
  16. package/lib/code-mode.js.map +1 -0
  17. package/lib/define-tool.d.ts +103 -0
  18. package/lib/define-tool.d.ts.map +1 -0
  19. package/lib/define-tool.js +354 -0
  20. package/lib/define-tool.js.map +1 -0
  21. package/lib/index.d.ts +348 -0
  22. package/lib/index.d.ts.map +1 -0
  23. package/lib/index.js +289 -0
  24. package/lib/index.js.map +1 -0
  25. package/lib/invariant.d.ts +13 -0
  26. package/lib/invariant.d.ts.map +1 -0
  27. package/lib/invariant.js +123 -0
  28. package/lib/invariant.js.map +1 -0
  29. package/lib/json-render.d.ts +18 -0
  30. package/lib/json-render.d.ts.map +1 -0
  31. package/lib/json-render.js +111 -0
  32. package/lib/json-render.js.map +1 -0
  33. package/lib/json-schema-value.d.ts +18 -0
  34. package/lib/json-schema-value.d.ts.map +1 -0
  35. package/lib/json-schema-value.js +238 -0
  36. package/lib/json-schema-value.js.map +1 -0
  37. package/lib/json-schema.d.ts +101 -0
  38. package/lib/json-schema.d.ts.map +1 -0
  39. package/lib/json-schema.js +351 -0
  40. package/lib/json-schema.js.map +1 -0
  41. package/lib/presentation.d.ts +367 -0
  42. package/lib/presentation.d.ts.map +1 -0
  43. package/lib/presentation.js +8 -0
  44. package/lib/presentation.js.map +1 -0
  45. package/lib/py-names.d.ts +163 -0
  46. package/lib/py-names.d.ts.map +1 -0
  47. package/lib/py-names.js +236 -0
  48. package/lib/py-names.js.map +1 -0
  49. package/lib/py-render.d.ts +23 -0
  50. package/lib/py-render.d.ts.map +1 -0
  51. package/lib/py-render.js +434 -0
  52. package/lib/py-render.js.map +1 -0
  53. package/lib/py-sdk-doc.d.ts +29 -0
  54. package/lib/py-sdk-doc.d.ts.map +1 -0
  55. package/lib/py-sdk-doc.js +114 -0
  56. package/lib/py-sdk-doc.js.map +1 -0
  57. package/lib/py-types.d.ts +34 -0
  58. package/lib/py-types.d.ts.map +1 -0
  59. package/lib/py-types.js +40 -0
  60. package/lib/py-types.js.map +1 -0
  61. package/lib/run-code-defs.d.ts +77 -0
  62. package/lib/run-code-defs.d.ts.map +1 -0
  63. package/lib/run-code-defs.js +98 -0
  64. package/lib/run-code-defs.js.map +1 -0
  65. package/lib/runtime-code.d.ts +65 -0
  66. package/lib/runtime-code.d.ts.map +1 -0
  67. package/lib/runtime-code.js +129 -0
  68. package/lib/runtime-code.js.map +1 -0
  69. package/lib/runtime-core.d.ts +130 -0
  70. package/lib/runtime-core.d.ts.map +1 -0
  71. package/lib/runtime-core.js +33 -0
  72. package/lib/runtime-core.js.map +1 -0
  73. package/lib/runtime-execute.d.ts +82 -0
  74. package/lib/runtime-execute.d.ts.map +1 -0
  75. package/lib/runtime-execute.js +333 -0
  76. package/lib/runtime-execute.js.map +1 -0
  77. package/lib/runtime-registry.d.ts +131 -0
  78. package/lib/runtime-registry.d.ts.map +1 -0
  79. package/lib/runtime-registry.js +269 -0
  80. package/lib/runtime-registry.js.map +1 -0
  81. package/lib/runtime-results.d.ts +32 -0
  82. package/lib/runtime-results.d.ts.map +1 -0
  83. package/lib/runtime-results.js +163 -0
  84. package/lib/runtime-results.js.map +1 -0
  85. package/lib/runtime-schemas.d.ts +112 -0
  86. package/lib/runtime-schemas.d.ts.map +1 -0
  87. package/lib/runtime-schemas.js +222 -0
  88. package/lib/runtime-schemas.js.map +1 -0
  89. package/lib/scheduler.d.ts +22 -0
  90. package/lib/scheduler.d.ts.map +1 -0
  91. package/lib/scheduler.js +21 -0
  92. package/lib/scheduler.js.map +1 -0
  93. package/lib/schema-spec.d.ts +154 -0
  94. package/lib/schema-spec.d.ts.map +1 -0
  95. package/lib/schema-spec.js +9 -0
  96. package/lib/schema-spec.js.map +1 -0
  97. package/lib/schema.d.ts +5 -0
  98. package/lib/schema.d.ts.map +1 -0
  99. package/lib/schema.js +3 -0
  100. package/lib/schema.js.map +1 -0
  101. package/lib/testing.d.ts +25 -0
  102. package/lib/testing.d.ts.map +1 -0
  103. package/lib/testing.js +25 -0
  104. package/lib/testing.js.map +1 -0
  105. package/lib/tool-layer.d.ts +49 -0
  106. package/lib/tool-layer.d.ts.map +1 -0
  107. package/lib/tool-layer.js +57 -0
  108. package/lib/tool-layer.js.map +1 -0
  109. package/lib/tool-types.d.ts +385 -0
  110. package/lib/tool-types.d.ts.map +1 -0
  111. package/lib/tool-types.js +11 -0
  112. package/lib/tool-types.js.map +1 -0
  113. package/lib/ts-types.d.ts +37 -0
  114. package/lib/ts-types.d.ts.map +1 -0
  115. package/lib/ts-types.js +265 -0
  116. package/lib/ts-types.js.map +1 -0
  117. package/lib/types.d.ts +55 -0
  118. package/lib/types.d.ts.map +1 -0
  119. package/lib/types.js +7 -0
  120. package/lib/types.js.map +1 -0
  121. package/package.json +65 -0
package/lib/index.d.ts ADDED
@@ -0,0 +1,348 @@
1
+ /**
2
+ * Tool registry, model presentation modes, and pre/guard/around/post/result
3
+ * execution pipeline.
4
+ * @module @dsh-cc/tools
5
+ */
6
+ import { Context, Service } from '@deepseek-ai/cordis';
7
+ import z from '@deepseek-ai/schemastery';
8
+ import { ScopedLayers } from '@deepseek-ai/dsh-scope';
9
+ import type { ScopeKey, Scoped } from '@deepseek-ai/dsh-scope';
10
+ import type { ContentBlock, ToolSchema } from '@deepseek-ai/dsh-llm';
11
+ import type { UserMessage } from '@deepseek-ai/dsh-session';
12
+ import type { ToolProviderResult } from '@deepseek-ai/dsh-system-prompt';
13
+ import type { CodeRuntime } from '@deepseek-ai/dsh-code-runtime';
14
+ import { TOOL_RUNTIME_SCHEDULER } from './scheduler.ts';
15
+ import { ToolLayer } from './tool-layer.ts';
16
+ import type { ToolAskResolution, ToolCancellationState } from './tool-layer.ts';
17
+ import type { CodeDispatchLog, Config, MutableToolRunContext, PostToolDecision, PreToolDecision, ScheduledToolDispatch, ScheduledToolPreparation, ToolDefinition, ToolDispatchExecution, ToolExecution, ToolExecutionInput, ToolExecutionMode, ToolExecutionResult, ToolExecutionSuccess, ToolExecutionToken, ToolGuard, ToolPresentationMode, ToolRestriction, ToolRunContext, ToolRuntimeScheduler, ToolView } from './tool-types.ts';
18
+ import type { ToolSdkSchema } from './ts-types.ts';
19
+ import type { ToolRuntimeCore } from './runtime-core.ts';
20
+ export { defineTool, valueSchemaSpecToJsonSchema, parameterSchemaSpecToJsonSchema, validateArgs, ToolArgsError, type ValueSchemaAnnotations, type StringValueSchemaSpec, type NumberValueSchemaSpec, type IntegerValueSchemaSpec, type BooleanValueSchemaSpec, type NullValueSchemaSpec, type ArrayValueSchemaSpec, type ObjectValueSchemaSpec, type JsonValueSchemaSpec, type OneOfValueSchemaSpec, type ValueSchemaSpec, type ParameterPropertySpec, type ParameterSchemaSpec, type ParameterJsonSchema, type InferValue, type InferArgs, type DefineToolOptions, } from './schema.ts';
21
+ export { assertSupportedJsonSchema, assertObjectJsonSchema, validateJsonSchemaValue, JsonSchemaError, type JsonSchemaNode, type ObjectJsonSchema, type JsonSchemaType, type JsonSchemaScalar, } from './json-schema.ts';
22
+ export type { JsonValue } from '@deepseek-ai/dsh-session';
23
+ export type { CodeDispatchEventData, CodeDispatchStartEventData } from './types.ts';
24
+ export { CodeRunFailedError, RUN_CODE_NAME } from './code-mode.ts';
25
+ export { CC_TO_HARNESS_TOOLS, KNOWN_HARNESS_TOOLS, translateToolNames, ccToolAliases, ccCanonicalToolName, type ToolNameTranslationPolicy, } from './cc-names.ts';
26
+ export { jsonSchemaToTs, renderToolsSdk } from './ts-types.ts';
27
+ export { jsonSchemaToPy, renderToolsSdkPy } from './py-types.ts';
28
+ export { defineContentToolFixture, type ContentToolFixtureOptions } from './testing.ts';
29
+ export type { ToolCallKind, FileLocation, FileDiff, ReadFileLine, ToolCallView, GenericCallView, TerminalCallView, DiffCallView, ToolResultView, GenericResultView, TerminalResultView, DiffResultView, SearchResultView, SearchMatchesResultView, SearchPathsResultView, SearchFileMatches, SearchLineMatch, ReadResultView, WebResultView, WebSearchResultView, WebFetchResultView, WebSource, } from './presentation.ts';
30
+ declare module '@deepseek-ai/cordis' {
31
+ interface Context {
32
+ tools: ToolRuntime;
33
+ }
34
+ interface Events {
35
+ /**
36
+ * Allow, deny, or ask before dispatch. `next()` delegates to allow; missing
37
+ * approval support turns `ask` into denial. Async gates must observe
38
+ * `exec.signal`; the registry rechecks cancellation after they settle but
39
+ * never abandons their promise.
40
+ * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent's calls.
41
+ * @param exec - the pending call (name, parsed arguments, caller agent).
42
+ * @mode waterfall
43
+ */
44
+ 'tools/pre-execute'(this: Scoped<ToolRuntime | ToolRuntimeCore>, exec: ToolExecution, next: () => Promise<PreToolDecision>): Promise<PreToolDecision>;
45
+ /**
46
+ * Around-dispatch waterfall for timeout, retry, or metrics. `next()` returns
47
+ * a normalized result; wrappers may change only `exec.signal`, while call
48
+ * identity remains immutable. The registry re-fuses the original caller
49
+ * signal before the body, so replacement cannot detach caller cancellation;
50
+ * wrappers must still restore their signal and reach quiescence.
51
+ * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent's calls.
52
+ * @param exec - the allowed call about to dispatch (name, parsed arguments, caller agent, signal).
53
+ * @mode waterfall
54
+ */
55
+ 'tools/execute'(this: Scoped<ToolRuntime | ToolRuntimeCore>, exec: ToolDispatchExecution, next: () => Promise<ToolExecutionResult>): Promise<ToolExecutionResult>;
56
+ /**
57
+ * Accept, replace, enrich, or block a normalized dispatch result. `next()`
58
+ * accepts it unchanged; thrown tools still reach this waterfall as errors. Async
59
+ * listeners must observe `exec.signal`; after they settle, caller
60
+ * cancellation replaces only a successful accepted outcome with the code
61
+ * selected by whether the tool body was invoked.
62
+ * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent's calls.
63
+ * @param exec - the call that just ran (name, parsed arguments, caller agent).
64
+ * @param result - the dispatch outcome a listener may accept, replace, or block.
65
+ * @mode waterfall
66
+ */
67
+ 'tools/post-execute'(this: Scoped<ToolRuntime | ToolRuntimeCore>, exec: ToolExecution, result: Readonly<ToolExecutionResult>, next: () => Promise<PostToolDecision>): Promise<PostToolDecision>;
68
+ /**
69
+ * Allow a listener to replace content in the DURABLE LOG COPY of one
70
+ * `run_code` sub-dispatch outcome before the bridge appends its
71
+ * `tool/code-dispatch` event. `next()` keeps the
72
+ * content unchanged; a listener may return replacement blocks (e.g. the
73
+ * spill policy's preview + locator for an oversized text result). Only the
74
+ * logged copy is affected — the program already received the complete
75
+ * value, and the model sees neither. A throwing listener is contained:
76
+ * the bridge falls back to logging the original settled content.
77
+ * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent's dispatches.
78
+ * @param dispatch - the parent execution, sub-call identity, and the settled content to log.
79
+ * @mode waterfall
80
+ */
81
+ 'tools/code-dispatch-log'(this: Scoped<ToolRuntime | ToolRuntimeCore>, dispatch: CodeDispatchLog, next: () => Promise<ContentBlock[]>): Promise<ContentBlock[]>;
82
+ /**
83
+ * Observe the frozen, lossless-JSON final outcome. Listener failures are contained.
84
+ * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): keyed by `exec.agent`.
85
+ * @param exec - the execution object that traversed the pipeline.
86
+ * @param result - a deep-frozen snapshot of the final returned result.
87
+ * @mode emit
88
+ */
89
+ 'tools/result'(this: Scoped<ToolRuntime | ToolRuntimeCore>, exec: Readonly<ToolExecution>, result: Readonly<ToolExecutionResult>): undefined;
90
+ /**
91
+ * A tool was registered or unregistered, or a scoped restriction changed
92
+ * (the available tool set changed — possibly for one scope only). An
93
+ * UNFILTERED registry-subject notification, deliberately not scope-filtered
94
+ * dispatch: a global change concerns every agent's next assembly, so a
95
+ * scoped listener subscribing here sees every change, not just its own
96
+ * scope's.
97
+ * @mode emit
98
+ */
99
+ 'tools/change'(): void;
100
+ }
101
+ }
102
+ export type { CodeDispatchLog, Config, PostToolDecision, PreToolDecision, ScheduledToolDispatch, ScheduledToolPreparation, ToolDefinition, ToolDispatchExecution, ToolExecution, ToolExecutionFailure, ToolExecutionInput, ToolExecutionMode, ToolExecutionResult, ToolExecutionSuccess, ToolExecutionToken, ToolGuard, ToolOutputDefinition, ToolPresentationMode, ToolRestriction, ToolResult, ToolRunContext, ToolRuntimeScheduler, } from './tool-types.ts';
103
+ export type { ToolErrorInfo, ToolFailure } from './abort-utils.ts';
104
+ export { TOOL_ABORTED, TOOL_ABORTED_BEFORE_DISPATCH, ToolNotFoundError, ToolOutputError } from './abort-utils.ts';
105
+ /**
106
+ * Scheduler entry point omitted from the generated named service API.
107
+ * The value MUST be the upstream symbol instance: the in-box agent loop reads
108
+ * the staged scheduler off the registry through the symbol exported by
109
+ * `@deepseek-ai/dsh-tools`, and a `Symbol()` is identity-unique — minting a
110
+ * private one here leaves the loop reading `undefined` and crashing every
111
+ * turn's first tool call (`undefined.prepare`). The binding is a type-erased
112
+ * `createRequire` rather than a static import so upstream's declaration graph
113
+ * (its own `Context` augmentation, whose vendored copy this package also
114
+ * ships) never enters downstream type programs; the dependency stays
115
+ * runtime-only (peer-declared). Declared in the {@link ./scheduler.ts} leaf
116
+ * module; re-exported here to keep the public barrel surface unchanged.
117
+ * @internal
118
+ */
119
+ export { TOOL_RUNTIME_SCHEDULER };
120
+ /**
121
+ * Tool registry and execution pipeline. Scoped registrations shadow globals;
122
+ * one visibility resolver feeds presentation, lookup, and dispatch.
123
+ *
124
+ * The implementation lives in the `runtime-*.ts` collaborator modules behind
125
+ * the `ToolRuntimeCore` structural interface; this class is the constructed
126
+ * facade — configuration, state fields, scheduler staging, and one-line
127
+ * delegations.
128
+ */
129
+ export declare class ToolRuntime extends Service {
130
+ /** Cordis context; `Service` keeps it protected — declaration-only re-exposure for the `ToolRuntimeCore` interface. @internal */
131
+ readonly ctx: Context;
132
+ static inject: string[];
133
+ static Config: z<Config>;
134
+ /** Internal staged view consumed by `dsh-agent-loop`'s parallel scheduler. */
135
+ readonly [TOOL_RUNTIME_SCHEDULER]: ToolRuntimeScheduler;
136
+ /** @internal Context deferred by a running tool body, keyed by its scheduler-owned execution. */
137
+ readonly deferredContexts: WeakMap<ToolRunContext, UserMessage[]>;
138
+ /** @internal Executions whose tool body declared the current turn complete. */
139
+ readonly concludingExecutions: WeakSet<ToolExecution>;
140
+ /** @internal Original caller cancellation, kept outside the wrapper-mutable execution object. */
141
+ readonly cancellationStates: WeakMap<ToolRunContext, ToolCancellationState>;
142
+ /** @internal Definition-owned final content transform snapshotted before policy begins. */
143
+ readonly contentFinalizers: WeakMap<ToolRunContext, ((exec: Readonly<ToolExecution>, result: Readonly<ToolExecutionResult>) => ContentBlock[] | undefined) | undefined>;
144
+ /** @internal Visibility layers: registration, reservation, restriction, guards. */
145
+ readonly layers: ScopedLayers<ToolLayer>;
146
+ /** @internal Presentation for scopes that declare none; {@link modeFor} shadows it per scope. */
147
+ readonly defaultMode: ToolPresentationMode;
148
+ /** @internal */
149
+ readonly maxParallelSubCalls: number;
150
+ /**
151
+ * Reserved presentation transport, kept outside the filterable registration
152
+ * layers. Built on first need rather than at construction: which agents run
153
+ * a code mode is no longer known when the service is constructed, and the
154
+ * transport is stateless beyond its closures over the runtime.
155
+ * @internal
156
+ */
157
+ codeTransport: ToolDefinition | undefined;
158
+ /** @internal Registry-normalized results and the exact dispatch that validated each value. */
159
+ readonly canonicalResults: WeakMap<object, ToolExecutionToken>;
160
+ constructor(ctx: Context, config?: Config);
161
+ /**
162
+ * Present the calling scope's tools in `mode` instead of the deployment
163
+ * default. Nearest scope on the chain wins, so a preset's standing
164
+ * declaration covers every agent joined under it.
165
+ *
166
+ * Scoped only, and one declaration per scope: this is how an agent preset
167
+ * composes Code Mode agents beside native ones in the same process, and a
168
+ * process-global override would be the `mode` config field instead.
169
+ * @param mode - the presentation the covered agents' models see.
170
+ * @returns the exact disposer that restores the deployment default.
171
+ */
172
+ presentAs(mode: ToolPresentationMode): () => void;
173
+ /**
174
+ * Register globally or in the calling agent scope. Scoped tools shadow
175
+ * globals; duplicates within one layer and the reserved `run_code` name fail.
176
+ * @param definition - tool schema, execution, and optional finalization/presentation callbacks.
177
+ * @returns the exact disposer that unregisters the tool.
178
+ */
179
+ register(definition: ToolDefinition): () => void;
180
+ /**
181
+ * Reserve a capability NAME in the calling layer without registering a
182
+ * visible definition. A reserved name joins the known/restrictable universe
183
+ * — a scope may later `restrict()` it away, and `toolOrder` may list it — but
184
+ * it never reaches the model-facing schema until a real `register()` supplies
185
+ * the definition. This is how a deferred-tool registry seeds the names a
186
+ * composition may gate before their heavy definitions load.
187
+ *
188
+ * The name stays out of {@link ToolRuntime.get} and {@link ToolRuntime.schemas}
189
+ * (only registered definitions are visible). Duplicate reservations within one
190
+ * layer fail, matching the duplicate-name rule for {@link ToolRuntime.register}.
191
+ * @param name - the capability name to make known without presenting.
192
+ * @returns the exact disposer that clears the reservation.
193
+ */
194
+ reserve(name: string): () => void;
195
+ /**
196
+ * Whether a global tool name passes every scoped restriction on the viewing
197
+ * scope's chain. The answer ignores registration: a reserved or not-yet-loaded
198
+ * name is admitted if no `allow`/`deny` on the chain masks it, so a caller can
199
+ * gate whether a deferred capability may load for one agent. A name masked by
200
+ * an `allow` list it is absent from, or present in a `deny` list, is not
201
+ * admitted. When a name has multiple restrictions, they intersect (all must
202
+ * admit it), matching registration visibility.
203
+ * @param name - the capability name to test.
204
+ * @param scope - the viewing scope (the agent); omitted for the global view, which has no restrictions.
205
+ * @returns whether the name may load for that scope.
206
+ */
207
+ isAdmitted(name: string, scope?: ScopeKey): boolean;
208
+ /**
209
+ * Restrict global tools for the calling agent scope. Empty filters, unknown
210
+ * names, scope-local names, and reserved transport names fail. Restrictions
211
+ * intersect; scoped registrations remain visible.
212
+ * @param filter - global-tool mask: `allow` (keep only) and/or `deny` (remove).
213
+ * @returns the exact disposer that lifts this restriction.
214
+ */
215
+ restrict(filter: ToolRestriction): () => void;
216
+ /**
217
+ * Register a monotonic guard after the extensible `tools/pre-execute`
218
+ * waterfall. A plain-context guard applies globally; one registered through
219
+ * `agent.ctx` applies only to that agent. Any matching guard may deny by
220
+ * returning a reason, while no guard can force-allow a call another guard
221
+ * denied. The exact effect disposer is returned for ordered ownership and
222
+ * HMR cleanup.
223
+ * @param guard - synchronous check; a returned string denies the execution.
224
+ * @returns the exact disposer that unregisters the guard.
225
+ */
226
+ guard(guard: ToolGuard): () => void;
227
+ /**
228
+ * Look up a tool as one scope sees it (scoped
229
+ * shadows global; a restricted-away global reads as absent). Presenters pass
230
+ * the calling agent so the rendered card matches the definition that
231
+ * actually executed.
232
+ * @param name - the tool name as registered.
233
+ * @param scope - the viewing scope (the agent); omitted = the global view.
234
+ * @returns the definition the scope resolves, or undefined when none is visible.
235
+ */
236
+ get(name: string, scope?: ScopeKey): ToolDefinition | undefined;
237
+ /**
238
+ * Project visible definitions onto the allowlisted model-facing schema fields,
239
+ * excluding execution and presentation callbacks.
240
+ * @param scope - the viewing scope (the agent); omitted = the global view.
241
+ * @returns one deep-cloned schema per visible tool.
242
+ */
243
+ schemas(scope?: ScopeKey): ToolSchema[];
244
+ /**
245
+ * Classify a pending call through the caller's visible tool definition. Only
246
+ * an exact `true` is parallel; unknown, hidden, undeclared, invalid, or
247
+ * throwing classifiers are exclusive.
248
+ * @param exec - call name, parsed arguments, and optional agent scope.
249
+ * @returns the fail-closed scheduling mode.
250
+ */
251
+ executionMode(exec: ToolExecutionInput): ToolExecutionMode;
252
+ /**
253
+ * Execute through pre-policy, guards, around-dispatch, post-policy,
254
+ * definition-owned content finalization, and final notification. Tool and
255
+ * listener failures resolve as materialized error results; an invisible tool
256
+ * reports `UNKNOWN_TOOL`. The returned outcome is the same lossless, frozen
257
+ * snapshot final observers receive. Cancellation
258
+ * arriving after entry and before final result materialization skips a
259
+ * not-yet-started body with `ABORTED_BEFORE_DISPATCH` or replaces a
260
+ * successful started outcome with `ABORTED`; already-started work is still
261
+ * drained and may retain a tool-owned structured error.
262
+ * @param exec - the typed same-process call input. The registry assigns its
263
+ * correlation token before policy begins.
264
+ * @returns the materialized final result.
265
+ */
266
+ execute(exec: ToolExecutionInput): Promise<ToolExecutionResult>;
267
+ /** @internal */
268
+ guardReason(exec: ToolExecution): string | undefined;
269
+ /** @internal */
270
+ view(scope?: ScopeKey): ToolView;
271
+ /** @internal */
272
+ resolveExecution(name: string, scope: ScopeKey | undefined, nested: boolean): ToolDefinition | undefined;
273
+ /** @internal */
274
+ collapseSection(): {
275
+ name: string;
276
+ order: number;
277
+ text: (context: {
278
+ scope?: ScopeKey;
279
+ }) => string;
280
+ };
281
+ /** @internal */
282
+ sdkSection(): {
283
+ name: string;
284
+ order: number;
285
+ text: (context: {
286
+ scope?: ScopeKey;
287
+ }) => string;
288
+ };
289
+ /** @internal */
290
+ modeFor(scope?: ScopeKey): ToolPresentationMode;
291
+ /** @internal */
292
+ wireSchemas(scope?: ScopeKey): ToolProviderResult;
293
+ /** @internal */
294
+ sdkSchemas(scope?: ScopeKey): ToolSdkSchema[];
295
+ /** @internal */
296
+ schemaOf(definition: ToolDefinition, detachParameters: boolean): ToolSchema;
297
+ /** @internal */
298
+ collapses(name: string, scope: ScopeKey | undefined, nested: boolean): boolean;
299
+ /** @internal */
300
+ completeScheduledExecution(prepared: ScheduledToolPreparation): Promise<ToolExecutionResult>;
301
+ /** @internal */
302
+ createExecution(exec: ToolExecutionInput): ScheduledToolPreparation | {
303
+ kind: 'ready';
304
+ exec: MutableToolRunContext;
305
+ };
306
+ /** @internal */
307
+ prepareScheduledExecution(input: ToolExecutionInput): Promise<ScheduledToolPreparation>;
308
+ /** @internal */
309
+ prepareExecution<T>(input: ToolExecutionInput, next: (prepared: ScheduledToolPreparation) => T | PromiseLike<T>): Promise<T>;
310
+ /** @internal */
311
+ callerCancelled(exec: ToolRunContext): boolean;
312
+ /** @internal */
313
+ cancellationResult(exec: ToolRunContext, prior?: ToolExecutionResult): ToolExecutionResult;
314
+ /** @internal */
315
+ dispatchToolBody(exec: MutableToolRunContext): Promise<ToolExecutionResult>;
316
+ /** @internal */
317
+ dispatchScheduledExecution(exec: ToolRunContext): Promise<ScheduledToolDispatch>;
318
+ /** @internal */
319
+ finalizeScheduledExecution(exec: ToolRunContext, result: ToolExecutionResult): Promise<ToolExecutionResult>;
320
+ /** @internal */
321
+ finishScheduledExecution(exec: ToolRunContext, result: ToolExecutionResult): ToolExecutionResult;
322
+ /** @internal */
323
+ applyFinalContent(exec: ToolRunContext, result: ToolExecutionResult): ToolExecutionResult;
324
+ /** @internal */
325
+ notifyResult(exec: ToolExecution, result: ToolExecutionResult): void;
326
+ /** @internal */
327
+ postExecute(exec: ToolExecution, result: ToolExecutionResult): Promise<ToolExecutionResult>;
328
+ /** @internal */
329
+ markCanonical<T extends ToolExecutionResult>(exec: ToolExecution, result: T): T;
330
+ /** @internal */
331
+ createSuccessResult(exec: ToolExecution, tool: ToolDefinition, candidate: unknown): ToolExecutionSuccess;
332
+ /** @internal */
333
+ normalizeDispatchResult(exec: ToolExecution, result: ToolExecutionResult): ToolExecutionResult;
334
+ /** @internal */
335
+ materializeFinalResult(result: ToolExecutionResult): ToolExecutionResult;
336
+ /** @internal */
337
+ requireCodeTransport(): ToolDefinition;
338
+ /** @internal */
339
+ requireCodeRuntime(mode: ToolPresentationMode): CodeRuntime;
340
+ /** @internal */
341
+ shapeDispatchLog(dispatch: CodeDispatchLog): Promise<ContentBlock[]>;
342
+ /** @internal */
343
+ serviceAsk(exec: ToolExecution, ask: Extract<PreToolDecision, {
344
+ kind: 'ask';
345
+ }>): Promise<ToolAskResolution>;
346
+ }
347
+ export default ToolRuntime;
348
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAA;AACtD,OAAO,CAAC,MAAM,0BAA0B,CAAA;AACxC,OAAO,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAA;AACrD,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,wBAAwB,CAAA;AAC9D,OAAO,KAAK,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAA;AACpE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAA;AAC3D,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAA;AACxE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,+BAA+B,CAAA;AAChE,OAAO,EAAE,sBAAsB,EAAE,MAAM,gBAAgB,CAAA;AACvD,OAAO,EAAE,SAAS,EAA8B,MAAM,iBAAiB,CAAA;AACvE,OAAO,KAAK,EAAE,iBAAiB,EAAE,qBAAqB,EAAE,MAAM,iBAAiB,CAAA;AAC/E,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,EAAE,qBAAqB,EAAE,gBAAgB,EAAE,eAAe,EAAE,qBAAqB,EAAE,wBAAwB,EAAE,cAAc,EAAE,qBAAqB,EAAE,aAAa,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,mBAAmB,EAAE,oBAAoB,EAAE,kBAAkB,EAAE,SAAS,EAAE,oBAAoB,EAAE,eAAe,EAAE,cAAc,EAAE,oBAAoB,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAA;AACva,OAAO,KAAK,EAAE,aAAa,EAA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gBAAgB;IAChB,aAAa,CAAC,CAAC,SAAS,mBAAmB,EAAE,IAAI,EAAE,aAAa,EAAE,MAAM,EAAE,CAAC,GAAG,CAAC;IAC/E,gBAAgB;IAChB,mBAAmB,CAAC,IAAI,EAAE,aAAa,EAAE,IAAI,EAAE,cAAc,EAAE,SAAS,EAAE,OAAO,GAAG,oBAAoB;IACxG,gBAAgB;IAChB,uBAAuB,CAAC,IAAI,EAAE,aAAa,EAAE,MAAM,EAAE,mBAAmB,GAAG,mBAAmB;IAC9F,gBAAgB;IAChB,sBAAsB,CAAC,MAAM,EAAE,mBAAmB,GAAG,mBAAmB;IACxE,gBAAgB;IAChB,oBAAoB,IAAI,cAAc;IACtC,gBAAgB;IAChB,kBAAkB,CAAC,IAAI,EAAE,oBAAoB,GAAG,WAAW;IAC3D,gBAAgB;IAChB,gBAAgB,CAAC,QAAQ,EAAE,eAAe,GAAG,OAAO,CAAC,YAAY,EAAE,CAAC;IACpE,gBAAgB;IAChB,UAAU,CAAC,IAAI,EAAE,aAAa,EAAE,GAAG,EAAE,OAAO,CAAC,eAAe,EAAE;QAAE,IAAI,EAAE,KAAK,CAAA;KAAE,CAAC,GAAG,OAAO,CAAC,iBAAiB,CAAC;CAC5G;AAED,eAAe,WAAW,CAAA"}
package/lib/index.js ADDED
@@ -0,0 +1,289 @@
1
+ /**
2
+ * Tool registry, model presentation modes, and pre/guard/around/post/result
3
+ * execution pipeline.
4
+ * @module @dsh-cc/tools
5
+ */
6
+ import { Service } from '@deepseek-ai/cordis';
7
+ import z from '@deepseek-ai/schemastery';
8
+ import { ScopedLayers } from '@deepseek-ai/dsh-scope';
9
+ import { TOOL_RUNTIME_SCHEDULER } from "./scheduler.js";
10
+ import { ToolLayer, resolveMaxParallelSubCalls } from "./tool-layer.js";
11
+ import { executionMode, get, guard as registerGuard, guardReason, isAdmitted, register, reserve, resolveExecution, restrict, view } from "./runtime-registry.js";
12
+ import { collapses, collapseSection, modeFor, presentAs, schemaOf, schemas, sdkSchemas, sdkSection, wireSchemas } from "./runtime-schemas.js";
13
+ import { applyFinalContent, callerCancelled, cancellationResult, completeScheduledExecution, createExecution, dispatchScheduledExecution, dispatchToolBody, execute, finalizeScheduledExecution, finishScheduledExecution, prepareExecution, prepareScheduledExecution } from "./runtime-execute.js";
14
+ import { createSuccessResult, markCanonical, materializeFinalResult, normalizeDispatchResult, notifyResult, postExecute } from "./runtime-results.js";
15
+ import { requireCodeRuntime, requireCodeTransport, serviceAsk, shapeDispatchLog } from "./runtime-code.js";
16
+ export { defineTool, valueSchemaSpecToJsonSchema, parameterSchemaSpecToJsonSchema, validateArgs, ToolArgsError, } from "./schema.js";
17
+ export { assertSupportedJsonSchema, assertObjectJsonSchema, validateJsonSchemaValue, JsonSchemaError, } from "./json-schema.js";
18
+ export { CodeRunFailedError, RUN_CODE_NAME } from "./code-mode.js";
19
+ export { CC_TO_HARNESS_TOOLS, KNOWN_HARNESS_TOOLS, translateToolNames, ccToolAliases, ccCanonicalToolName, } from "./cc-names.js";
20
+ export { jsonSchemaToTs, renderToolsSdk } from "./ts-types.js";
21
+ export { jsonSchemaToPy, renderToolsSdkPy } from "./py-types.js";
22
+ export { defineContentToolFixture } from "./testing.js";
23
+ export { TOOL_ABORTED, TOOL_ABORTED_BEFORE_DISPATCH, ToolNotFoundError, ToolOutputError } from "./abort-utils.js";
24
+ /**
25
+ * Scheduler entry point omitted from the generated named service API.
26
+ * The value MUST be the upstream symbol instance: the in-box agent loop reads
27
+ * the staged scheduler off the registry through the symbol exported by
28
+ * `@deepseek-ai/dsh-tools`, and a `Symbol()` is identity-unique — minting a
29
+ * private one here leaves the loop reading `undefined` and crashing every
30
+ * turn's first tool call (`undefined.prepare`). The binding is a type-erased
31
+ * `createRequire` rather than a static import so upstream's declaration graph
32
+ * (its own `Context` augmentation, whose vendored copy this package also
33
+ * ships) never enters downstream type programs; the dependency stays
34
+ * runtime-only (peer-declared). Declared in the {@link ./scheduler.ts} leaf
35
+ * module; re-exported here to keep the public barrel surface unchanged.
36
+ * @internal
37
+ */
38
+ export { TOOL_RUNTIME_SCHEDULER };
39
+ /**
40
+ * Tool registry and execution pipeline. Scoped registrations shadow globals;
41
+ * one visibility resolver feeds presentation, lookup, and dispatch.
42
+ *
43
+ * The implementation lives in the `runtime-*.ts` collaborator modules behind
44
+ * the `ToolRuntimeCore` structural interface; this class is the constructed
45
+ * facade — configuration, state fields, scheduler staging, and one-line
46
+ * delegations.
47
+ */
48
+ export class ToolRuntime extends Service {
49
+ static inject = ['systemPrompt'];
50
+ static Config = z.object({
51
+ mode: z.union(['native', 'code', 'both']).default('native'),
52
+ maxParallelSubCalls: z.natural().min(1).default(10),
53
+ });
54
+ /** Internal staged view consumed by `dsh-agent-loop`'s parallel scheduler. */
55
+ [TOOL_RUNTIME_SCHEDULER] = {
56
+ prepare: exec => this.prepareScheduledExecution(exec),
57
+ dispatch: exec => this.dispatchScheduledExecution(exec),
58
+ finalize: (exec, result) => this.finalizeScheduledExecution(exec, result),
59
+ finish: (exec, result) => this.finishScheduledExecution(exec, result),
60
+ };
61
+ /** @internal Context deferred by a running tool body, keyed by its scheduler-owned execution. */
62
+ deferredContexts = new WeakMap();
63
+ /** @internal Executions whose tool body declared the current turn complete. */
64
+ concludingExecutions = new WeakSet();
65
+ /** @internal Original caller cancellation, kept outside the wrapper-mutable execution object. */
66
+ cancellationStates = new WeakMap();
67
+ /** @internal Definition-owned final content transform snapshotted before policy begins. */
68
+ contentFinalizers = new WeakMap();
69
+ /** @internal Visibility layers: registration, reservation, restriction, guards. */
70
+ layers = new ScopedLayers(scope => new ToolLayer(scope), () => { this.ctx.emit('tools/change'); });
71
+ /** @internal Presentation for scopes that declare none; {@link modeFor} shadows it per scope. */
72
+ defaultMode;
73
+ /** @internal */
74
+ maxParallelSubCalls;
75
+ /**
76
+ * Reserved presentation transport, kept outside the filterable registration
77
+ * layers. Built on first need rather than at construction: which agents run
78
+ * a code mode is no longer known when the service is constructed, and the
79
+ * transport is stateless beyond its closures over the runtime.
80
+ * @internal
81
+ */
82
+ codeTransport;
83
+ /** @internal Registry-normalized results and the exact dispatch that validated each value. */
84
+ canonicalResults = new WeakMap();
85
+ constructor(ctx, config = {}) {
86
+ super(ctx, 'tools');
87
+ // The schema already defaulted an omitted mode; the ?? narrows the
88
+ // optional-input type for direct (non-Loader) construction in tests.
89
+ this.defaultMode = config.mode ?? 'native';
90
+ this.maxParallelSubCalls = resolveMaxParallelSubCalls(config.maxParallelSubCalls);
91
+ ctx.systemPrompt.tools(context => this.wireSchemas(context.scope));
92
+ if (this.defaultMode !== 'native') {
93
+ ctx.systemPrompt.section(this.collapseSection());
94
+ ctx.systemPrompt.section(this.sdkSection());
95
+ }
96
+ }
97
+ /**
98
+ * Present the calling scope's tools in `mode` instead of the deployment
99
+ * default. Nearest scope on the chain wins, so a preset's standing
100
+ * declaration covers every agent joined under it.
101
+ *
102
+ * Scoped only, and one declaration per scope: this is how an agent preset
103
+ * composes Code Mode agents beside native ones in the same process, and a
104
+ * process-global override would be the `mode` config field instead.
105
+ * @param mode - the presentation the covered agents' models see.
106
+ * @returns the exact disposer that restores the deployment default.
107
+ */
108
+ presentAs(mode) {
109
+ return presentAs(this, mode);
110
+ }
111
+ /**
112
+ * Register globally or in the calling agent scope. Scoped tools shadow
113
+ * globals; duplicates within one layer and the reserved `run_code` name fail.
114
+ * @param definition - tool schema, execution, and optional finalization/presentation callbacks.
115
+ * @returns the exact disposer that unregisters the tool.
116
+ */
117
+ register(definition) {
118
+ return register(this, definition);
119
+ }
120
+ /**
121
+ * Reserve a capability NAME in the calling layer without registering a
122
+ * visible definition. A reserved name joins the known/restrictable universe
123
+ * — a scope may later `restrict()` it away, and `toolOrder` may list it — but
124
+ * it never reaches the model-facing schema until a real `register()` supplies
125
+ * the definition. This is how a deferred-tool registry seeds the names a
126
+ * composition may gate before their heavy definitions load.
127
+ *
128
+ * The name stays out of {@link ToolRuntime.get} and {@link ToolRuntime.schemas}
129
+ * (only registered definitions are visible). Duplicate reservations within one
130
+ * layer fail, matching the duplicate-name rule for {@link ToolRuntime.register}.
131
+ * @param name - the capability name to make known without presenting.
132
+ * @returns the exact disposer that clears the reservation.
133
+ */
134
+ reserve(name) {
135
+ return reserve(this, name);
136
+ }
137
+ /**
138
+ * Whether a global tool name passes every scoped restriction on the viewing
139
+ * scope's chain. The answer ignores registration: a reserved or not-yet-loaded
140
+ * name is admitted if no `allow`/`deny` on the chain masks it, so a caller can
141
+ * gate whether a deferred capability may load for one agent. A name masked by
142
+ * an `allow` list it is absent from, or present in a `deny` list, is not
143
+ * admitted. When a name has multiple restrictions, they intersect (all must
144
+ * admit it), matching registration visibility.
145
+ * @param name - the capability name to test.
146
+ * @param scope - the viewing scope (the agent); omitted for the global view, which has no restrictions.
147
+ * @returns whether the name may load for that scope.
148
+ */
149
+ isAdmitted(name, scope) {
150
+ return isAdmitted(this, name, scope);
151
+ }
152
+ /**
153
+ * Restrict global tools for the calling agent scope. Empty filters, unknown
154
+ * names, scope-local names, and reserved transport names fail. Restrictions
155
+ * intersect; scoped registrations remain visible.
156
+ * @param filter - global-tool mask: `allow` (keep only) and/or `deny` (remove).
157
+ * @returns the exact disposer that lifts this restriction.
158
+ */
159
+ restrict(filter) {
160
+ return restrict(this, filter);
161
+ }
162
+ /**
163
+ * Register a monotonic guard after the extensible `tools/pre-execute`
164
+ * waterfall. A plain-context guard applies globally; one registered through
165
+ * `agent.ctx` applies only to that agent. Any matching guard may deny by
166
+ * returning a reason, while no guard can force-allow a call another guard
167
+ * denied. The exact effect disposer is returned for ordered ownership and
168
+ * HMR cleanup.
169
+ * @param guard - synchronous check; a returned string denies the execution.
170
+ * @returns the exact disposer that unregisters the guard.
171
+ */
172
+ guard(guard) {
173
+ return registerGuard(this, guard);
174
+ }
175
+ /**
176
+ * Look up a tool as one scope sees it (scoped
177
+ * shadows global; a restricted-away global reads as absent). Presenters pass
178
+ * the calling agent so the rendered card matches the definition that
179
+ * actually executed.
180
+ * @param name - the tool name as registered.
181
+ * @param scope - the viewing scope (the agent); omitted = the global view.
182
+ * @returns the definition the scope resolves, or undefined when none is visible.
183
+ */
184
+ get(name, scope) {
185
+ return get(this, name, scope);
186
+ }
187
+ /**
188
+ * Project visible definitions onto the allowlisted model-facing schema fields,
189
+ * excluding execution and presentation callbacks.
190
+ * @param scope - the viewing scope (the agent); omitted = the global view.
191
+ * @returns one deep-cloned schema per visible tool.
192
+ */
193
+ schemas(scope) {
194
+ return schemas(this, scope);
195
+ }
196
+ /**
197
+ * Classify a pending call through the caller's visible tool definition. Only
198
+ * an exact `true` is parallel; unknown, hidden, undeclared, invalid, or
199
+ * throwing classifiers are exclusive.
200
+ * @param exec - call name, parsed arguments, and optional agent scope.
201
+ * @returns the fail-closed scheduling mode.
202
+ */
203
+ executionMode(exec) {
204
+ return executionMode(this, exec);
205
+ }
206
+ /**
207
+ * Execute through pre-policy, guards, around-dispatch, post-policy,
208
+ * definition-owned content finalization, and final notification. Tool and
209
+ * listener failures resolve as materialized error results; an invisible tool
210
+ * reports `UNKNOWN_TOOL`. The returned outcome is the same lossless, frozen
211
+ * snapshot final observers receive. Cancellation
212
+ * arriving after entry and before final result materialization skips a
213
+ * not-yet-started body with `ABORTED_BEFORE_DISPATCH` or replaces a
214
+ * successful started outcome with `ABORTED`; already-started work is still
215
+ * drained and may retain a tool-owned structured error.
216
+ * @param exec - the typed same-process call input. The registry assigns its
217
+ * correlation token before policy begins.
218
+ * @returns the materialized final result.
219
+ */
220
+ async execute(exec) {
221
+ return execute(this, exec);
222
+ }
223
+ /** @internal */
224
+ guardReason(exec) { return guardReason(this, exec); }
225
+ /** @internal */
226
+ view(scope) { return view(this, scope); }
227
+ /** @internal */
228
+ resolveExecution(name, scope, nested) { return resolveExecution(this, name, scope, nested); }
229
+ /** @internal */
230
+ collapseSection() { return collapseSection(this); }
231
+ /** @internal */
232
+ sdkSection() { return sdkSection(this); }
233
+ /** @internal */
234
+ modeFor(scope) { return modeFor(this, scope); }
235
+ /** @internal */
236
+ wireSchemas(scope) { return wireSchemas(this, scope); }
237
+ /** @internal */
238
+ sdkSchemas(scope) { return sdkSchemas(this, scope); }
239
+ /** @internal */
240
+ schemaOf(definition, detachParameters) { return schemaOf(this, definition, detachParameters); }
241
+ /** @internal */
242
+ collapses(name, scope, nested) { return collapses(this, name, scope, nested); }
243
+ /** @internal */
244
+ completeScheduledExecution(prepared) { return completeScheduledExecution(this, prepared); }
245
+ /** @internal */
246
+ createExecution(exec) { return createExecution(this, exec); }
247
+ /** @internal */
248
+ prepareScheduledExecution(input) { return prepareScheduledExecution(this, input); }
249
+ /** @internal */
250
+ prepareExecution(input, next) {
251
+ return prepareExecution(this, input, next);
252
+ }
253
+ /** @internal */
254
+ callerCancelled(exec) { return callerCancelled(this, exec); }
255
+ /** @internal */
256
+ cancellationResult(exec, prior) { return cancellationResult(this, exec, prior); }
257
+ /** @internal */
258
+ dispatchToolBody(exec) { return dispatchToolBody(this, exec); }
259
+ /** @internal */
260
+ dispatchScheduledExecution(exec) { return dispatchScheduledExecution(this, exec); }
261
+ /** @internal */
262
+ finalizeScheduledExecution(exec, result) { return finalizeScheduledExecution(this, exec, result); }
263
+ /** @internal */
264
+ finishScheduledExecution(exec, result) { return finishScheduledExecution(this, exec, result); }
265
+ /** @internal */
266
+ applyFinalContent(exec, result) { return applyFinalContent(this, exec, result); }
267
+ /** @internal */
268
+ notifyResult(exec, result) { return notifyResult(this, exec, result); }
269
+ /** @internal */
270
+ postExecute(exec, result) { return postExecute(this, exec, result); }
271
+ /** @internal */
272
+ markCanonical(exec, result) { return markCanonical(this, exec, result); }
273
+ /** @internal */
274
+ createSuccessResult(exec, tool, candidate) { return createSuccessResult(this, exec, tool, candidate); }
275
+ /** @internal */
276
+ normalizeDispatchResult(exec, result) { return normalizeDispatchResult(this, exec, result); }
277
+ /** @internal */
278
+ materializeFinalResult(result) { return materializeFinalResult(this, result); }
279
+ /** @internal */
280
+ requireCodeTransport() { return requireCodeTransport(this); }
281
+ /** @internal */
282
+ requireCodeRuntime(mode) { return requireCodeRuntime(this, mode); }
283
+ /** @internal */
284
+ shapeDispatchLog(dispatch) { return shapeDispatchLog(this, dispatch); }
285
+ /** @internal */
286
+ serviceAsk(exec, ask) { return serviceAsk(this, exec, ask); }
287
+ }
288
+ export default ToolRuntime;
289
+ //# sourceMappingURL=index.js.map