@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
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Code Mode codegen — Python flavor. The pure projection from registered tool schemas to the
3
+ * Python SDK text the model programs against under `runtime.language === 'python'`. Sibling of
4
+ * {@link ./ts-types.ts | ts-types.ts}; the two files are two projections of the same registry
5
+ * store, keyed by the loaded {@link @deepseek-ai/dsh-code-runtime#CodeRuntime.language | code
6
+ * runtime's language}.
7
+ *
8
+ * Under `mode: 'code'` the native tool schemas are omitted from the request, so this generated
9
+ * SDK is the model's ONLY source for each tool's argument names, required fields, types,
10
+ * descriptions, and canonical output shapes; under `mode: 'both'` the native schemas ship
11
+ * alongside it and it is one of two. Object-shaped arguments and outputs therefore render as one
12
+ * named `TypedDict` per tool (and per nested object), not an opaque `dict[str, Any]`, so the
13
+ * shape survives into the program under the mode that has nothing else to carry it.
14
+ *
15
+ * Line-budget layout: `py-names.ts` holds the shared naming/state/text-escape machinery,
16
+ * `py-render.ts` the {@link renderType} walker, `py-sdk-doc.ts` the `renderToolsSdkPy`
17
+ * document renderer; this file stays the public barrel — both exports re-exported here.
18
+ * @module @dsh-cc/tools/src/py-types
19
+ */
20
+ export { renderToolsSdkPy } from './py-sdk-doc.ts';
21
+ /**
22
+ * Map one JSON-Schema node to a context-free Python type expression from the
23
+ * `typing` module. Handles every unified schema construct — `object` (degraded
24
+ * to `dict[str, Any]`: naming a `TypedDict` requires the render context that
25
+ * {@link renderToolsSdkPy} supplies), `const`/`enum` (→ `Literal[...]`),
26
+ * `oneOf` (→ union), `string`/`number`/`integer`/`boolean`/`null`, `array`
27
+ * (`items` → `list[T]`) — and returns `Any` for an unsupported or malformed
28
+ * schema, matching the TS flavor's `unknown` fallback. Type annotations in the
29
+ * emitted SDK are advisory: Python does not enforce them at runtime.
30
+ * @param schema - the JSON-Schema node.
31
+ * @returns the Python type text.
32
+ */
33
+ export declare function jsonSchemaToPy(schema: unknown): string;
34
+ //# sourceMappingURL=py-types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"py-types.d.ts","sourceRoot":"","sources":["../src/py-types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAIH,OAAO,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAA;AAElD;;;;;;;;;;;GAWG;AACH,wBAAgB,cAAc,CAAC,MAAM,EAAE,OAAO,GAAG,MAAM,CAKtD"}
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Code Mode codegen — Python flavor. The pure projection from registered tool schemas to the
3
+ * Python SDK text the model programs against under `runtime.language === 'python'`. Sibling of
4
+ * {@link ./ts-types.ts | ts-types.ts}; the two files are two projections of the same registry
5
+ * store, keyed by the loaded {@link @deepseek-ai/dsh-code-runtime#CodeRuntime.language | code
6
+ * runtime's language}.
7
+ *
8
+ * Under `mode: 'code'` the native tool schemas are omitted from the request, so this generated
9
+ * SDK is the model's ONLY source for each tool's argument names, required fields, types,
10
+ * descriptions, and canonical output shapes; under `mode: 'both'` the native schemas ship
11
+ * alongside it and it is one of two. Object-shaped arguments and outputs therefore render as one
12
+ * named `TypedDict` per tool (and per nested object), not an opaque `dict[str, Any]`, so the
13
+ * shape survives into the program under the mode that has nothing else to carry it.
14
+ *
15
+ * Line-budget layout: `py-names.ts` holds the shared naming/state/text-escape machinery,
16
+ * `py-render.ts` the {@link renderType} walker, `py-sdk-doc.ts` the `renderToolsSdkPy`
17
+ * document renderer; this file stays the public barrel — both exports re-exported here.
18
+ * @module @dsh-cc/tools/src/py-types
19
+ */
20
+ import { renderType } from "./py-render.js";
21
+ export { renderToolsSdkPy } from "./py-sdk-doc.js";
22
+ /**
23
+ * Map one JSON-Schema node to a context-free Python type expression from the
24
+ * `typing` module. Handles every unified schema construct — `object` (degraded
25
+ * to `dict[str, Any]`: naming a `TypedDict` requires the render context that
26
+ * {@link renderToolsSdkPy} supplies), `const`/`enum` (→ `Literal[...]`),
27
+ * `oneOf` (→ union), `string`/`number`/`integer`/`boolean`/`null`, `array`
28
+ * (`items` → `list[T]`) — and returns `Any` for an unsupported or malformed
29
+ * schema, matching the TS flavor's `unknown` fallback. Type annotations in the
30
+ * emitted SDK are advisory: Python does not enforce them at runtime.
31
+ * @param schema - the JSON-Schema node.
32
+ * @returns the Python type text.
33
+ */
34
+ export function jsonSchemaToPy(schema) {
35
+ // A throwaway state whose class collector never escapes: an object with
36
+ // properties has nowhere to declare its TypedDict and degrades to
37
+ // dict[str, Any]. renderToolsSdkPy drives the named-TypedDict path.
38
+ return renderType(schema, '', { classes: [], usedClassNames: new Set(), nextClassCounter: new Map(), typing: new Set() });
39
+ }
40
+ //# sourceMappingURL=py-types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"py-types.js","sourceRoot":"","sources":["../src/py-types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAA;AAE3C,OAAO,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAA;AAElD;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,cAAc,CAAC,MAAe;IAC5C,wEAAwE;IACxE,kEAAkE;IAClE,oEAAoE;IACpE,OAAO,UAAU,CAAC,MAAM,EAAE,EAAE,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE,cAAc,EAAE,IAAI,GAAG,EAAE,EAAE,gBAAgB,EAAE,IAAI,GAAG,EAAE,EAAE,MAAM,EAAE,IAAI,GAAG,EAAE,EAAE,CAAC,CAAA;AAC3H,CAAC"}
@@ -0,0 +1,77 @@
1
+ /**
2
+ * The model-facing `run_code` definition vocabulary: the tool name, its
3
+ * per-language schema flavors, and the failure error type shared by the
4
+ * Code Mode transport in {@link ./code-mode.ts}.
5
+ * @module dsh-tools/run-code-defs
6
+ */
7
+ import { HarnessError } from '@deepseek-ai/dsh-llm';
8
+ import type { CodeRuntime } from '@deepseek-ai/dsh-code-runtime';
9
+ /** The model-facing name of the Code Mode tool. */
10
+ export declare const RUN_CODE_NAME = "run_code";
11
+ /** The `tools:sdk` section order: inside the 100–199 tool-guidance band, after per-tool guidance sections. */
12
+ export declare const SDK_SECTION_ORDER = 150;
13
+ /**
14
+ * The language-specific `run_code` schema text: the tool `description` and its
15
+ * `code` parameter description, kept together so a language's two model-facing
16
+ * strings share one source of truth. Keyed by `CodeRuntime.language`, mirroring
17
+ * `SDK_RENDERERS` in {@link ./index.ts}. The emitted flavor MUST match the
18
+ * semantics the same language's SDK instructions promise, so the model never
19
+ * receives a TypeScript schema beside a Python SDK (or vice versa).
20
+ */
21
+ interface RunCodeFlavor {
22
+ /** The tool `description` the model sees for this language. */
23
+ readonly description: string;
24
+ /** The `code` parameter's description for this language. */
25
+ readonly codeDescription: string;
26
+ }
27
+ /**
28
+ * The TypeScript flavor: the fallback for a schema read with no runtime
29
+ * mounted ({@link resolveFlavor} owns which readers reach that). A real
30
+ * assembly always resolves a runtime first, so the model never sees this
31
+ * fallback outside its own language.
32
+ */
33
+ export declare const TYPESCRIPT_FLAVOR: RunCodeFlavor;
34
+ /**
35
+ * The languages Code Mode ships a presentation for. Both per-language tables —
36
+ * {@link RUN_CODE_FLAVORS} here and `SDK_RENDERERS` in {@link ./index.ts} — are
37
+ * checked against this union with `satisfies`, so a language added to one and
38
+ * not the other fails `typecheck` instead of waiting for a runtime that reports
39
+ * it. The tables stay declared `Record<string, …>` because `CodeRuntime.language`
40
+ * is an unconstrained `string`: this union pins what the harness ships, while the
41
+ * `Object.hasOwn` guards reject what a mounted runtime may report.
42
+ */
43
+ export type CodeSdkLanguage = 'typescript' | 'python';
44
+ /**
45
+ * The `description` parameter's model-facing description: language-independent
46
+ * (the UI label contract is the same for every runtime), shared between the
47
+ * static spec and the language-aware `parameters` getter so the two emissions
48
+ * can never drift.
49
+ */
50
+ export declare const RUN_CODE_DESCRIPTION_PARAM_DESCRIPTION: string;
51
+ /**
52
+ * Resolve the {@link RunCodeFlavor} for the loaded runtime's language, read at
53
+ * schema-emission time so the model-visible `run_code` schema always matches
54
+ * the SDK section's language. `peekRuntime` returns `undefined` only when no
55
+ * runtime is mounted, which reaches this function through definition readers
56
+ * and `schemas()` — the doc-catalog harvest is the only shipped one, and none
57
+ * of them feeds a model, because `wireSchemas` calls `requireCodeRuntime`
58
+ * before projecting — so that path degrades to {@link TYPESCRIPT_FLAVOR}. A
59
+ * mounted runtime whose language has no flavor entry fails loud, exactly as
60
+ * `requireCodeRuntime` rejects it at assembly. Keeping this table in step with
61
+ * `SDK_RENDERERS` is the compiler's job ({@link CodeSdkLanguage}); what this
62
+ * guard owns is the runtime-supplied language neither table knows, which never
63
+ * yields a wrong-language schema for a real runtime.
64
+ */
65
+ export declare function resolveFlavor(peekRuntime: () => CodeRuntime | undefined): RunCodeFlavor;
66
+ /**
67
+ * Thrown by `run_code` when the program run itself failed — a program
68
+ * exception, a budget expiry, an abort, or substrate death. Extends
69
+ * {@link HarnessError} (`code: 'CODE_RUN_FAILED'`); the registry's execution
70
+ * pipeline converts it into a structured `isError` result whose text carries
71
+ * the failure kind plus the captured logs, so the model can self-correct.
72
+ */
73
+ export declare class CodeRunFailedError extends HarnessError {
74
+ constructor(message: string);
75
+ }
76
+ export {};
77
+ //# sourceMappingURL=run-code-defs.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run-code-defs.d.ts","sourceRoot":"","sources":["../src/run-code-defs.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAA;AACnD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,+BAA+B,CAAA;AAEhE,mDAAmD;AACnD,eAAO,MAAM,aAAa,aAAa,CAAA;AAEvC,8GAA8G;AAC9G,eAAO,MAAM,iBAAiB,MAAM,CAAA;AAEpC;;;;;;;GAOG;AACH,UAAU,aAAa;IACrB,+DAA+D;IAC/D,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAA;IAC5B,4DAA4D;IAC5D,QAAQ,CAAC,eAAe,EAAE,MAAM,CAAA;CACjC;AAED;;;;;GAKG;AACH,eAAO,MAAM,iBAAiB,EAAE,aAQ/B,CAAA;AAiBD;;;;;;;;GAQG;AACH,MAAM,MAAM,eAAe,GAAG,YAAY,GAAG,QAAQ,CAAA;AAQrD;;;;;GAKG;AACH,eAAO,MAAM,sCAAsC,QAGkC,CAAA;AAErF;;;;;;;;;;;;;GAaG;AACH,wBAAgB,aAAa,CAAC,WAAW,EAAE,MAAM,WAAW,GAAG,SAAS,GAAG,aAAa,CAiBvF;AAED;;;;;;GAMG;AACH,qBAAa,kBAAmB,SAAQ,YAAY;gBACtC,OAAO,EAAE,MAAM;CAI5B"}
@@ -0,0 +1,98 @@
1
+ /**
2
+ * The model-facing `run_code` definition vocabulary: the tool name, its
3
+ * per-language schema flavors, and the failure error type shared by the
4
+ * Code Mode transport in {@link ./code-mode.ts}.
5
+ * @module dsh-tools/run-code-defs
6
+ */
7
+ import { HarnessError } from '@deepseek-ai/dsh-llm';
8
+ /** The model-facing name of the Code Mode tool. */
9
+ export const RUN_CODE_NAME = 'run_code';
10
+ /** The `tools:sdk` section order: inside the 100–199 tool-guidance band, after per-tool guidance sections. */
11
+ export const SDK_SECTION_ORDER = 150;
12
+ /**
13
+ * The TypeScript flavor: the fallback for a schema read with no runtime
14
+ * mounted ({@link resolveFlavor} owns which readers reach that). A real
15
+ * assembly always resolves a runtime first, so the model never sees this
16
+ * fallback outside its own language.
17
+ */
18
+ export const TYPESCRIPT_FLAVOR = {
19
+ description: 'Execute a TypeScript program against the available tools. Takes two required '
20
+ + 'arguments: `code`, the BODY of an async function (erasable syntax only; top-level '
21
+ + '`await` and `return` work), and `description`, a short summary of what the program '
22
+ + 'does. Call tools as `await tools.name(args)` per the declarations in the system '
23
+ + 'prompt. Only what you print or return comes back — curate it.',
24
+ codeDescription: 'The program: the body of an async TypeScript function.',
25
+ };
26
+ /**
27
+ * The Python flavor: the body of an async function, top-level `await` and
28
+ * `return`, answer via `print` and/or the returned value, matching
29
+ * {@link ./py-types.ts}'s SDK instructions.
30
+ */
31
+ const PYTHON_FLAVOR = {
32
+ description: 'Execute a Python program against the available tools. Takes two required '
33
+ + 'arguments: `code`, the BODY of an async function (top-level `await` and `return` '
34
+ + 'work), and `description`, a short summary of what the program does. Call tools as '
35
+ + '`await tools.name(args)` per the declarations in the system prompt. Answer '
36
+ + 'with `print(...)` and/or `return <value>` — only that comes back, so curate it.',
37
+ codeDescription: 'The program: the body of an async Python function.',
38
+ };
39
+ /** Per-language `run_code` schema flavors (see {@link RunCodeFlavor}); one entry per {@link CodeSdkLanguage}. */
40
+ const RUN_CODE_FLAVORS = {
41
+ typescript: TYPESCRIPT_FLAVOR,
42
+ python: PYTHON_FLAVOR,
43
+ };
44
+ /**
45
+ * The `description` parameter's model-facing description: language-independent
46
+ * (the UI label contract is the same for every runtime), shared between the
47
+ * static spec and the language-aware `parameters` getter so the two emissions
48
+ * can never drift.
49
+ */
50
+ export const RUN_CODE_DESCRIPTION_PARAM_DESCRIPTION = 'Clear, concise description of what this program does in active voice, '
51
+ + '5-10 words (shown in the UI). Examples: "Count TODO markers across packages"; '
52
+ + '"Read failing test and its fixture"; "Rename config key in every cordis.yml".';
53
+ /**
54
+ * Resolve the {@link RunCodeFlavor} for the loaded runtime's language, read at
55
+ * schema-emission time so the model-visible `run_code` schema always matches
56
+ * the SDK section's language. `peekRuntime` returns `undefined` only when no
57
+ * runtime is mounted, which reaches this function through definition readers
58
+ * and `schemas()` — the doc-catalog harvest is the only shipped one, and none
59
+ * of them feeds a model, because `wireSchemas` calls `requireCodeRuntime`
60
+ * before projecting — so that path degrades to {@link TYPESCRIPT_FLAVOR}. A
61
+ * mounted runtime whose language has no flavor entry fails loud, exactly as
62
+ * `requireCodeRuntime` rejects it at assembly. Keeping this table in step with
63
+ * `SDK_RENDERERS` is the compiler's job ({@link CodeSdkLanguage}); what this
64
+ * guard owns is the runtime-supplied language neither table knows, which never
65
+ * yields a wrong-language schema for a real runtime.
66
+ */
67
+ export function resolveFlavor(peekRuntime) {
68
+ const runtime = peekRuntime();
69
+ if (runtime === undefined) {
70
+ // No runtime mounted: reached by definition readers and `schemas()`, of
71
+ // which the doc-catalog harvest is the only shipped one. None feeds a
72
+ // model — `wireSchemas` calls `requireCodeRuntime` before projecting, so
73
+ // the assembly path never arrives here. Degrade to the TS default.
74
+ return TYPESCRIPT_FLAVOR;
75
+ }
76
+ // Own-property read: a language like `toString`/`constructor` would otherwise
77
+ // resolve an inherited Object.prototype member as a flavor.
78
+ const flavor = RUN_CODE_FLAVORS[runtime.language];
79
+ if (!Object.hasOwn(RUN_CODE_FLAVORS, runtime.language) || flavor === undefined) {
80
+ const known = Object.keys(RUN_CODE_FLAVORS).map(name => JSON.stringify(name)).join(', ');
81
+ throw new Error(`dsh-tools: no run_code schema flavor registered for runtime language ${JSON.stringify(runtime.language)} (known: ${known})`);
82
+ }
83
+ return flavor;
84
+ }
85
+ /**
86
+ * Thrown by `run_code` when the program run itself failed — a program
87
+ * exception, a budget expiry, an abort, or substrate death. Extends
88
+ * {@link HarnessError} (`code: 'CODE_RUN_FAILED'`); the registry's execution
89
+ * pipeline converts it into a structured `isError` result whose text carries
90
+ * the failure kind plus the captured logs, so the model can self-correct.
91
+ */
92
+ export class CodeRunFailedError extends HarnessError {
93
+ constructor(message) {
94
+ super(message, 'CODE_RUN_FAILED');
95
+ this.name = 'CodeRunFailedError';
96
+ }
97
+ }
98
+ //# sourceMappingURL=run-code-defs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run-code-defs.js","sourceRoot":"","sources":["../src/run-code-defs.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAA;AAGnD,mDAAmD;AACnD,MAAM,CAAC,MAAM,aAAa,GAAG,UAAU,CAAA;AAEvC,8GAA8G;AAC9G,MAAM,CAAC,MAAM,iBAAiB,GAAG,GAAG,CAAA;AAiBpC;;;;;GAKG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAkB;IAC9C,WAAW,EACT,+EAA+E;UAC7E,oFAAoF;UACpF,qFAAqF;UACrF,kFAAkF;UAClF,+DAA+D;IACnE,eAAe,EAAE,wDAAwD;CAC1E,CAAA;AAED;;;;GAIG;AACH,MAAM,aAAa,GAAkB;IACnC,WAAW,EACT,2EAA2E;UACzE,mFAAmF;UACnF,oFAAoF;UACpF,6EAA6E;UAC7E,iFAAiF;IACrF,eAAe,EAAE,oDAAoD;CACtE,CAAA;AAaD,iHAAiH;AACjH,MAAM,gBAAgB,GAAkC;IACtD,UAAU,EA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the code-runtime resolver, the code-dispatch log waterfall,
4
+ * and the approval-seam `ask` resolution. Bodies are verbatim moves from the
5
+ * former `ToolRuntime` methods with `this.` → `rt.`.
6
+ * @module
7
+ */
8
+ import type { ContentBlock } from '@deepseek-ai/dsh-llm';
9
+ import type { CodeRuntime } from '@deepseek-ai/dsh-code-runtime';
10
+ import type { CodeDispatchLog, PreToolDecision, ToolDefinition, ToolExecution, ToolPresentationMode } from './tool-types.ts';
11
+ import type { ToolAskResolution } from './tool-layer.ts';
12
+ import type { ToolRuntimeCore } from './runtime-core.ts';
13
+ /**
14
+ * The reserved `run_code` transport, built on first need.
15
+ *
16
+ * It never enters the global layer: per-agent restrictions must not remove
17
+ * it, and a scoped registration must not shadow it. The visibility resolver
18
+ * appends it after resolving the filterable global/scoped capability layers,
19
+ * and only for scopes whose mode actually presents it.
20
+ * @param rt - the owning runtime.
21
+ * @returns the shared transport definition.
22
+ */
23
+ export declare function requireCodeTransport(rt: ToolRuntimeCore): ToolDefinition;
24
+ /**
25
+ * Resolve the code runtime or throw the actionable misconfiguration error.
26
+ * Read at use time (assembly / run_code execution), NOT via static
27
+ * `inject`: an inject entry would hold `ctx.tools` — and every tool plugin
28
+ * behind it — hostage to a code runtime existing even under `mode:
29
+ * 'native'` (the loop's optional-backend idiom, same as
30
+ * `sessionPersistence`).
31
+ *
32
+ * Assembly and `run_code` execution read separately, so the language is not
33
+ * bound to a request. Harmless while one published backend exists — both
34
+ * reads return the same flavor — but a reload that swapped in a second
35
+ * language between them would hand a program written against one SDK to the
36
+ * other. Binding it is deferred until a second backend ships (the first
37
+ * point it is testable); rationale in the
38
+ * [language-dispatch note](../../../../.agents/notes/implemented/feature/2026-07-31-code-mode-language-dispatch.md).
39
+ */
40
+ export declare function requireCodeRuntime(rt: ToolRuntimeCore, mode: ToolPresentationMode): CodeRuntime;
41
+ /**
42
+ * Run the `tools/code-dispatch-log` waterfall over one settled sub-dispatch
43
+ * and return the content the bridge should log on `tool/code-dispatch`.
44
+ * Contained: when a listener throws, the method logs the original settled
45
+ * content; that failure must not fail the dispatch or omit the settle event. Private:
46
+ * the ONE consumer is the `run_code` bridge this registry constructs, which
47
+ * receives it as a capability parameter (the `requireRuntime` idiom) — the
48
+ * waterfall, not this invoker, is the public extension point.
49
+ */
50
+ export declare function shapeDispatchLog(rt: ToolRuntimeCore, dispatch: CodeDispatchLog): Promise<ContentBlock[]>;
51
+ /**
52
+ * Resolve an `ask` decision to allow/deny through the approval seam. The
53
+ * seam is consumed opportunistically with `ctx.get('approval')` — a
54
+ * deployment that composes no ApprovalService keeps the historical degrade
55
+ * to deny, and an unmount mid-session degrades the same way on the next ask.
56
+ * An agent-less execution also degrades: without an agent there is no
57
+ * session to audit to and no UI to route to. Otherwise the outcome maps
58
+ * one-to-one — `allowed-once` proceeds; the three non-grants deny with
59
+ * distinct reasons so the model can tell a human "no" from an absent
60
+ * approval channel.
61
+ */
62
+ export declare function serviceAsk(rt: ToolRuntimeCore, exec: ToolExecution, ask: Extract<PreToolDecision, {
63
+ kind: 'ask';
64
+ }>): Promise<ToolAskResolution>;
65
+ //# sourceMappingURL=runtime-code.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runtime-code.d.ts","sourceRoot":"","sources":["../src/runtime-code.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAGH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAA;AAExD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,+BAA+B,CAAA;AAMhE,OAAO,KAAK,EAAE,eAAe,EAAE,eAAe,EAAE,cAAc,EAAE,aAAa,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAA;AAC5H,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAA;AAExD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAA;AAExD;;;;;;;;;GASG;AACH,wBAAgB,oBAAoB,CAAC,EAAE,EAAE,eAAe,GAAG,cAAc,CAWxE;AAED;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,kBAAkB,CAAC,EAAE,EAAE,eAAe,EAAE,IAAI,EAAE,oBAAoB,GAAG,WAAW,CAU/F;AAED;;;;;;;;GAQG;AACH,wBAAsB,gBAAgB,CAAC,EAAE,EAAE,eAAe,EAAE,QAAQ,EAAE,eAAe,GAAG,OAAO,CAAC,YAAY,EAAE,CAAC,CAU9G;AAED;;;;;;;;;;GAUG;AACH,wBAAsB,UAAU,CAC9B,EAAE,EAAE,eAAe,EACnB,IAAI,EAAE,aAAa,EACnB,GAAG,EAAE,OAAO,CAAC,eAAe,EAAE;IAAE,IAAI,EAAE,KAAK,CAAA;CAAE,CAAC,GAC7C,OAAO,CAAC,iBAAiB,CAAC,CAqC5B"}
@@ -0,0 +1,129 @@
1
+ /**
2
+ * ToolRuntime Code Mode collaborators: the reserved `run_code` transport
3
+ * factory wiring, the code-runtime resolver, the code-dispatch log waterfall,
4
+ * and the approval-seam `ask` resolution. Bodies are verbatim moves from the
5
+ * former `ToolRuntime` methods with `this.` → `rt.`.
6
+ * @module
7
+ */
8
+ import { scopeTarget } from '@deepseek-ai/dsh-scope';
9
+ import { assertNever } from '@deepseek-ai/dsh-llm';
10
+ import { createRunCodeTool } from "./code-mode.js";
11
+ import { errorMessage } from "./abort-utils.js";
12
+ import { SDK_RENDERERS } from "./runtime-core.js";
13
+ /**
14
+ * The reserved `run_code` transport, built on first need.
15
+ *
16
+ * It never enters the global layer: per-agent restrictions must not remove
17
+ * it, and a scoped registration must not shadow it. The visibility resolver
18
+ * appends it after resolving the filterable global/scoped capability layers,
19
+ * and only for scopes whose mode actually presents it.
20
+ * @param rt - the owning runtime.
21
+ * @returns the shared transport definition.
22
+ */
23
+ export function requireCodeTransport(rt) {
24
+ rt.codeTransport ??= createRunCodeTool(rt, {
25
+ requireRuntime: () => rt.requireCodeRuntime(rt.defaultMode),
26
+ // The language-aware description/parameters getters read the runtime
27
+ // without demanding one, so a native-default process can still project
28
+ // the transport for an agent that chose code.
29
+ peekRuntime: () => rt.ctx.get('codeRuntime'),
30
+ maxParallel: rt.maxParallelSubCalls,
31
+ shapeDispatchLog: dispatch => rt.shapeDispatchLog(dispatch),
32
+ });
33
+ return rt.codeTransport;
34
+ }
35
+ /**
36
+ * Resolve the code runtime or throw the actionable misconfiguration error.
37
+ * Read at use time (assembly / run_code execution), NOT via static
38
+ * `inject`: an inject entry would hold `ctx.tools` — and every tool plugin
39
+ * behind it — hostage to a code runtime existing even under `mode:
40
+ * 'native'` (the loop's optional-backend idiom, same as
41
+ * `sessionPersistence`).
42
+ *
43
+ * Assembly and `run_code` execution read separately, so the language is not
44
+ * bound to a request. Harmless while one published backend exists — both
45
+ * reads return the same flavor — but a reload that swapped in a second
46
+ * language between them would hand a program written against one SDK to the
47
+ * other. Binding it is deferred until a second backend ships (the first
48
+ * point it is testable); rationale in the
49
+ * [language-dispatch note](../../../../.agents/notes/implemented/feature/2026-07-31-code-mode-language-dispatch.md).
50
+ */
51
+ export function requireCodeRuntime(rt, mode) {
52
+ const runtime = rt.ctx.get('codeRuntime');
53
+ if (!runtime) {
54
+ 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"`);
55
+ }
56
+ if (!Object.hasOwn(SDK_RENDERERS, runtime.language)) {
57
+ const known = Object.keys(SDK_RENDERERS).map(name => JSON.stringify(name)).join(', ');
58
+ throw new Error(`dsh-tools: no SDK renderer registered for runtime language ${JSON.stringify(runtime.language)} (known: ${known})`);
59
+ }
60
+ return runtime;
61
+ }
62
+ /**
63
+ * Run the `tools/code-dispatch-log` waterfall over one settled sub-dispatch
64
+ * and return the content the bridge should log on `tool/code-dispatch`.
65
+ * Contained: when a listener throws, the method logs the original settled
66
+ * content; that failure must not fail the dispatch or omit the settle event. Private:
67
+ * the ONE consumer is the `run_code` bridge this registry constructs, which
68
+ * receives it as a capability parameter (the `requireRuntime` idiom) — the
69
+ * waterfall, not this invoker, is the public extension point.
70
+ */
71
+ export async function shapeDispatchLog(rt, dispatch) {
72
+ try {
73
+ return await rt.ctx.waterfall(scopeTarget(rt, dispatch.agent), 'tools/code-dispatch-log', dispatch, () => Promise.resolve(dispatch.content));
74
+ }
75
+ catch (error) {
76
+ rt.ctx.logger.warn(`tools: code-dispatch-log listener failed for ${dispatch.name}: ${errorMessage(error)}; logging the original settled content`);
77
+ return dispatch.content;
78
+ }
79
+ }
80
+ /**
81
+ * Resolve an `ask` decision to allow/deny through the approval seam. The
82
+ * seam is consumed opportunistically with `ctx.get('approval')` — a
83
+ * deployment that composes no ApprovalService keeps the historical degrade
84
+ * to deny, and an unmount mid-session degrades the same way on the next ask.
85
+ * An agent-less execution also degrades: without an agent there is no
86
+ * session to audit to and no UI to route to. Otherwise the outcome maps
87
+ * one-to-one — `allowed-once` proceeds; the three non-grants deny with
88
+ * distinct reasons so the model can tell a human "no" from an absent
89
+ * approval channel.
90
+ */
91
+ export async function serviceAsk(rt, exec, ask) {
92
+ const approval = rt.ctx.get('approval');
93
+ if (approval === undefined) {
94
+ return {
95
+ decision: { kind: 'deny', reason: ask.reason ?? `tool "${exec.name}" requires approval (not yet supported)` },
96
+ approvalCancelled: false,
97
+ };
98
+ }
99
+ if (exec.agent === undefined) {
100
+ return {
101
+ decision: { kind: 'deny', reason: `tool "${exec.name}" requires approval, but the call has no agent to route it through` },
102
+ approvalCancelled: false,
103
+ };
104
+ }
105
+ const outcome = await approval.request({
106
+ agent: exec.agent,
107
+ toolName: exec.name,
108
+ callId: exec.callId,
109
+ ...ask.reason !== undefined ? { reason: ask.reason } : {},
110
+ signal: exec.signal,
111
+ });
112
+ switch (outcome) {
113
+ case 'allowed-once': return { decision: { kind: 'allow' }, approvalCancelled: false };
114
+ case 'rejected': return {
115
+ decision: { kind: 'deny', reason: `the user rejected tool "${exec.name}"` },
116
+ approvalCancelled: false,
117
+ };
118
+ case 'cancelled': return {
119
+ decision: { kind: 'deny', reason: `approval for tool "${exec.name}" was cancelled` },
120
+ approvalCancelled: true,
121
+ };
122
+ case 'unavailable': return {
123
+ decision: { kind: 'deny', reason: `tool "${exec.name}" requires approval, but no approval channel is available` },
124
+ approvalCancelled: false,
125
+ };
126
+ default: return assertNever(outcome, 'ApprovalOutcome');
127
+ }
128
+ }
129
+ //# sourceMappingURL=runtime-code.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runtime-code.js","sourceRoot":"","sources":["../src/runtime-code.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAA;AAEpD,OAAO,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAA;AAKlD,OAAO,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAA;AAClD,OAAO,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAA;AAG/C,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAA;AAGjD;;;;;;;;;GASG;AACH,MAAM,UAAU,oBAAoB,CAAC,EAAmB;IACtD,EAAE,CAAC,aAAa,KAAK,iBAAiB,CAAC,EAAE,EAAE;QACzC,cAAc,EAAE,GAAG,EAAE,CAAC,EAAE,CAAC,kBAAkB,CAAC,EAAE,CAAC,WAAW,CAAC;QAC3D,qEAAqE;QACrE,uEAAuE;QACvE,8CAA8C;QAC9C,WAAW,EAAE,GAAG,EAAE,CAAC,EAAE,CAAC,GAAG,CAAC,GAAG,CAAC,aAAa,CAAC;QAC5C,WAAW,EAAE,EAAE,CAAC,mBAAmB;QACnC,gBAAgB,EAAE,QAAQ,CAAC,EAAE,CAAC,EAAE,CAAC,gBAAgB,CAAC,QAAQ,CAAC;KAC5D,CAAC,CAAA;IACF,OAAO,EAAE,CAAC,aAAa,CAAA;AACzB,CAAC;AAED;;;;;;;;;;;;;;;GAeG;AACH,MAAM,UAAU,kBAAkB,CAAC,EAAmB,EAAE,IAA0B;IAChF,MAAM,OAAO,GAAG,EAAE,CAA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C,CAAC,OAAO;YACvB,QAAQ,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,sBAAsB,IAAI,CAAC,IAAI,iBAAiB,EAAE;YACpF,iBAAiB,EAAE,IAAI;SACxB,CAAA;QACD,KAAK,aAAa,CAAC,CAAC,OAAO;YACzB,QAAQ,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,IAAI,CAAC,IAAI,2DAA2D,EAAE;YACjH,iBAAiB,EAAE,KAAK;SACzB,CAAA;QACD,OAAO,CAAC,CAAC,OAAO,WAAW,CAAC,OAAO,EAAE,iBAAiB,CAAC,CAAA;IACzD,CAAC;AACH,CAAC"}
@@ -0,0 +1,130 @@
1
+ /**
2
+ * Structural core shared by the ToolRuntime facade and its free-function
3
+ * collaborator modules: the runtime's state fields plus every method
4
+ * signature the collaborators call through their `rt` parameter. The facade
5
+ * instance satisfies this interface structurally; collaborators stay acyclic
6
+ * at import time — this module imports NO value from `index.ts` (the only
7
+ * value edges here are the leaf SDK renderer table below).
8
+ * @module
9
+ */
10
+ import type { Context } from '@deepseek-ai/cordis';
11
+ import type { ScopeKey, ScopedLayers } from '@deepseek-ai/dsh-scope';
12
+ import type { ContentBlock, ToolSchema } from '@deepseek-ai/dsh-llm';
13
+ import type { UserMessage } from '@deepseek-ai/dsh-session';
14
+ import type { ToolProviderResult } from '@deepseek-ai/dsh-system-prompt';
15
+ import type { CodeRuntime } from '@deepseek-ai/dsh-code-runtime';
16
+ import type { ToolSdkSchema } from './ts-types.ts';
17
+ import { TOOL_RUNTIME_SCHEDULER } from './scheduler.ts';
18
+ import type { ToolLayer } from './tool-layer.ts';
19
+ import type { ToolAskResolution, ToolCancellationState } from './tool-layer.ts';
20
+ import type { CodeDispatchLog, MutableToolRunContext, PreToolDecision, ScheduledToolDispatch, ScheduledToolPreparation, ToolDefinition, ToolExecution, ToolExecutionInput, ToolExecutionMode, ToolExecutionResult, ToolExecutionSuccess, ToolExecutionToken, ToolGuard, ToolPresentationMode, ToolRestriction, ToolRunContext, ToolRuntimeScheduler, ToolView } from './tool-types.ts';
21
+ /**
22
+ * Language → SDK-section renderer. The registry looks up the loaded
23
+ * `ctx.codeRuntime.language` in this table when assembling the `tools:sdk`
24
+ * section under a non-native mode; a runtime whose language is not a key
25
+ * fails the assembly loudly (same idiom as `toolOrder` violations). Adding a
26
+ * new backend language is three parallel edits — a {@link CodeSdkLanguage}
27
+ * member, an entry here, and a `RUN_CODE_FLAVORS` entry in `code-mode.ts` for
28
+ * its `run_code` schema strings — plus the renderer function this table points
29
+ * at. The `satisfies` clause pins this table's key set to that union, which
30
+ * the flavor table is checked against too, so any of the three left out is a
31
+ * typecheck failure. What no check reaches is the prose that names the values
32
+ * instead of deriving them: the seam's `dsh-code-runtime` README pair, its
33
+ * `CodeRuntime.language` JSDoc, and `docs/subsystems/code-runtime.md`
34
+ * with its zh pair, plus this package's own README pair and the
35
+ * {@link Config.mode} JSDoc.
36
+ */
37
+ export declare const SDK_RENDERERS: Record<string, (schemas: ToolSdkSchema[]) => string>;
38
+ /**
39
+ * The ToolRuntime state and pipeline surface, as consumed by the
40
+ * `runtime-*.ts` free-function collaborators. Every member is public on the
41
+ * facade class (former `private` members carry an `@internal` tag); the class
42
+ * remains the only constructed form.
43
+ */
44
+ export interface ToolRuntimeCore {
45
+ /** Cordis context, inherited by the facade from `Service`. */
46
+ readonly ctx: Context;
47
+ /** Visibility layers: registration, reservation, restriction, guards. */
48
+ readonly layers: ScopedLayers<ToolLayer>;
49
+ /** Presentation for scopes that declare none; `modeFor` shadows it per scope. */
50
+ readonly defaultMode: ToolPresentationMode;
51
+ readonly maxParallelSubCalls: number;
52
+ /**
53
+ * Reserved presentation transport, kept outside the filterable registration
54
+ * layers. Built on first need rather than at construction: which agents run
55
+ * a code mode is no longer known when the service is constructed, and the
56
+ * transport is stateless beyond its closures over the runtime.
57
+ */
58
+ codeTransport: ToolDefinition | undefined;
59
+ /** Context deferred by a running tool body, keyed by its scheduler-owned execution. */
60
+ readonly deferredContexts: WeakMap<ToolRunContext, UserMessage[]>;
61
+ /** Executions whose tool body declared the current turn complete. */
62
+ readonly concludingExecutions: WeakSet<ToolExecution>;
63
+ /** Original caller cancellation, kept outside the wrapper-mutable execution object. */
64
+ readonly cancellationStates: WeakMap<ToolRunContext, ToolCancellationState>;
65
+ /** Definition-owned final content transform snapshotted before policy begins. */
66
+ readonly contentFinalizers: WeakMap<ToolRunContext, ToolDefinition['finalizeContent']>;
67
+ /** Registry-normalized results and the exact dispatch that validated each value. */
68
+ readonly canonicalResults: WeakMap<object, ToolExecutionToken>;
69
+ /** Internal staged view consumed by `dsh-agent-loop`'s parallel scheduler. */
70
+ readonly [TOOL_RUNTIME_SCHEDULER]: ToolRuntimeScheduler;
71
+ register(definition: ToolDefinition): () => void;
72
+ reserve(name: string): () => void;
73
+ isAdmitted(name: string, scope?: ScopeKey): boolean;
74
+ restrict(filter: ToolRestriction): () => void;
75
+ guard(guard: ToolGuard): () => void;
76
+ guardReason(exec: ToolExecution): string | undefined;
77
+ view(scope?: ScopeKey): ToolView;
78
+ get(name: string, scope?: ScopeKey): ToolDefinition | undefined;
79
+ resolveExecution(name: string, scope: ScopeKey | undefined, nested: boolean): ToolDefinition | undefined;
80
+ executionMode(exec: ToolExecutionInput): ToolExecutionMode;
81
+ collapseSection(): {
82
+ name: string;
83
+ order: number;
84
+ text: (context: {
85
+ scope?: ScopeKey;
86
+ }) => string;
87
+ };
88
+ sdkSection(): {
89
+ name: string;
90
+ order: number;
91
+ text: (context: {
92
+ scope?: ScopeKey;
93
+ }) => string;
94
+ };
95
+ modeFor(scope?: ScopeKey): ToolPresentationMode;
96
+ presentAs(mode: ToolPresentationMode): () => void;
97
+ wireSchemas(scope?: ScopeKey): ToolProviderResult;
98
+ schemas(scope?: ScopeKey): ToolSchema[];
99
+ sdkSchemas(scope?: ScopeKey): ToolSdkSchema[];
100
+ schemaOf(definition: ToolDefinition, detachParameters: boolean): ToolSchema;
101
+ collapses(name: string, scope: ScopeKey | undefined, nested: boolean): boolean;
102
+ execute(exec: ToolExecutionInput): Promise<ToolExecutionResult>;
103
+ completeScheduledExecution(prepared: ScheduledToolPreparation): Promise<ToolExecutionResult>;
104
+ createExecution(exec: ToolExecutionInput): ScheduledToolPreparation | {
105
+ kind: 'ready';
106
+ exec: MutableToolRunContext;
107
+ };
108
+ prepareScheduledExecution(input: ToolExecutionInput): Promise<ScheduledToolPreparation>;
109
+ prepareExecution<T>(input: ToolExecutionInput, next: (prepared: ScheduledToolPreparation) => T | PromiseLike<T>): Promise<T>;
110
+ callerCancelled(exec: ToolRunContext): boolean;
111
+ cancellationResult(exec: ToolRunContext, prior?: ToolExecutionResult): ToolExecutionResult;
112
+ dispatchToolBody(exec: MutableToolRunContext): Promise<ToolExecutionResult>;
113
+ dispatchScheduledExecution(exec: ToolRunContext): Promise<ScheduledToolDispatch>;
114
+ finalizeScheduledExecution(exec: ToolRunContext, result: ToolExecutionResult): Promise<ToolExecutionResult>;
115
+ finishScheduledExecution(exec: ToolRunContext, result: ToolExecutionResult): ToolExecutionResult;
116
+ applyFinalContent(exec: ToolRunContext, result: ToolExecutionResult): ToolExecutionResult;
117
+ notifyResult(exec: ToolExecution, result: ToolExecutionResult): void;
118
+ postExecute(exec: ToolExecution, result: ToolExecutionResult): Promise<ToolExecutionResult>;
119
+ markCanonical<T extends ToolExecutionResult>(exec: ToolExecution, result: T): T;
120
+ createSuccessResult(exec: ToolExecution, tool: ToolDefinition, candidate: unknown): ToolExecutionSuccess;
121
+ normalizeDispatchResult(exec: ToolExecution, result: ToolExecutionResult): ToolExecutionResult;
122
+ materializeFinalResult(result: ToolExecutionResult): ToolExecutionResult;
123
+ requireCodeTransport(): ToolDefinition;
124
+ requireCodeRuntime(mode: ToolPresentationMode): CodeRuntime;
125
+ shapeDispatchLog(dispatch: CodeDispatchLog): Promise<ContentBlock[]>;
126
+ serviceAsk(exec: ToolExecution, ask: Extract<PreToolDecision, {
127
+ kind: 'ask';
128
+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