toolsplice 0.0.0-stage → 0.0.2

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 (172) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +104 -2
  3. package/dist/abortable.d.ts +6 -0
  4. package/dist/abortable.js +50 -0
  5. package/dist/adaptive-read.d.ts +50 -0
  6. package/dist/adaptive-read.js +780 -0
  7. package/dist/answer-wait.d.ts +7 -0
  8. package/dist/answer-wait.js +45 -0
  9. package/dist/cache-reads.d.ts +18 -0
  10. package/dist/cache-reads.js +89 -0
  11. package/dist/calibration-ledger.d.ts +37 -0
  12. package/dist/calibration-ledger.js +148 -0
  13. package/dist/calibration-marker.d.ts +4 -0
  14. package/dist/calibration-marker.js +77 -0
  15. package/dist/catalog-setup.d.ts +33 -0
  16. package/dist/catalog-setup.js +89 -0
  17. package/dist/catalog.d.ts +10 -0
  18. package/dist/catalog.js +42 -0
  19. package/dist/checkpoint-files.d.ts +15 -0
  20. package/dist/checkpoint-files.js +99 -0
  21. package/dist/cli.d.ts +2 -0
  22. package/dist/cli.js +1454 -0
  23. package/dist/coalesce-reads.d.ts +6 -0
  24. package/dist/coalesce-reads.js +33 -0
  25. package/dist/codegen.d.ts +44 -0
  26. package/dist/codegen.js +479 -0
  27. package/dist/contract-caller.d.ts +23 -0
  28. package/dist/contract-caller.js +326 -0
  29. package/dist/contract-corrections.d.ts +35 -0
  30. package/dist/contract-corrections.js +159 -0
  31. package/dist/contract-schema.d.ts +7 -0
  32. package/dist/contract-schema.js +156 -0
  33. package/dist/contracts.d.ts +72 -0
  34. package/dist/contracts.js +370 -0
  35. package/dist/core.d.ts +44 -0
  36. package/dist/core.js +43 -0
  37. package/dist/db-final-answer.d.ts +9 -0
  38. package/dist/db-final-answer.js +62 -0
  39. package/dist/define.d.ts +78 -0
  40. package/dist/define.js +14 -0
  41. package/dist/doctor.d.ts +22 -0
  42. package/dist/doctor.js +91 -0
  43. package/dist/drift.d.ts +23 -0
  44. package/dist/drift.js +111 -0
  45. package/dist/execution.d.ts +38 -0
  46. package/dist/execution.js +66 -0
  47. package/dist/extract.d.ts +34 -0
  48. package/dist/extract.js +73 -0
  49. package/dist/final-answer-stores.d.ts +71 -0
  50. package/dist/final-answer-stores.js +72 -0
  51. package/dist/final-answer.d.ts +32 -0
  52. package/dist/final-answer.js +104 -0
  53. package/dist/impact.d.ts +48 -0
  54. package/dist/impact.js +71 -0
  55. package/dist/index.d.ts +51 -0
  56. package/dist/index.js +47 -0
  57. package/dist/local-tool.d.ts +18 -0
  58. package/dist/local-tool.js +32 -0
  59. package/dist/mcp-apps.d.ts +53 -0
  60. package/dist/mcp-apps.js +32 -0
  61. package/dist/mcp-event-delivery.d.ts +98 -0
  62. package/dist/mcp-event-delivery.js +211 -0
  63. package/dist/mcp-extensions.d.ts +46 -0
  64. package/dist/mcp-extensions.js +200 -0
  65. package/dist/mcp-peer.d.ts +45 -0
  66. package/dist/mcp-peer.js +207 -0
  67. package/dist/mcp-server-card.d.ts +21 -0
  68. package/dist/mcp-server-card.js +54 -0
  69. package/dist/ordered-transport.d.ts +12 -0
  70. package/dist/ordered-transport.js +106 -0
  71. package/dist/page-checkpoint.d.ts +71 -0
  72. package/dist/page-checkpoint.js +286 -0
  73. package/dist/page-read-gate.d.ts +15 -0
  74. package/dist/page-read-gate.js +48 -0
  75. package/dist/pattern.d.ts +3 -0
  76. package/dist/pattern.js +54 -0
  77. package/dist/postgres.d.ts +41 -0
  78. package/dist/postgres.js +264 -0
  79. package/dist/probe.d.ts +29 -0
  80. package/dist/probe.js +121 -0
  81. package/dist/proxy.d.ts +40 -0
  82. package/dist/proxy.js +436 -0
  83. package/dist/read-pages.d.ts +25 -0
  84. package/dist/read-pages.js +85 -0
  85. package/dist/read-policy.d.ts +6 -0
  86. package/dist/read-policy.js +16 -0
  87. package/dist/read-steps.d.ts +12 -0
  88. package/dist/read-steps.js +36 -0
  89. package/dist/result-session.d.ts +109 -0
  90. package/dist/result-session.js +620 -0
  91. package/dist/route-checkpoint.d.ts +3 -0
  92. package/dist/route-checkpoint.js +80 -0
  93. package/dist/route-driver-cli.d.ts +3 -0
  94. package/dist/route-driver-cli.js +43 -0
  95. package/dist/route-evaluation.d.ts +141 -0
  96. package/dist/route-evaluation.js +329 -0
  97. package/dist/row-groups.d.ts +17 -0
  98. package/dist/row-groups.js +79 -0
  99. package/dist/row-query.d.ts +62 -0
  100. package/dist/row-query.js +172 -0
  101. package/dist/rules.d.ts +30 -0
  102. package/dist/rules.js +72 -0
  103. package/dist/run-diagnostics.d.ts +75 -0
  104. package/dist/run-diagnostics.js +212 -0
  105. package/dist/runtime.d.ts +6 -0
  106. package/dist/runtime.js +26 -0
  107. package/dist/schema.d.ts +17 -0
  108. package/dist/schema.js +299 -0
  109. package/dist/search-fetch.d.ts +50 -0
  110. package/dist/search-fetch.js +264 -0
  111. package/dist/shape.d.ts +91 -0
  112. package/dist/shape.js +499 -0
  113. package/dist/skill-files.d.ts +9 -0
  114. package/dist/skill-files.js +49 -0
  115. package/dist/splice-diagnostics.d.ts +44 -0
  116. package/dist/splice-diagnostics.js +88 -0
  117. package/dist/splice-measure.d.ts +33 -0
  118. package/dist/splice-measure.js +55 -0
  119. package/dist/splice-project.d.ts +125 -0
  120. package/dist/splice-project.js +348 -0
  121. package/dist/splice-recording.d.ts +132 -0
  122. package/dist/splice-recording.js +481 -0
  123. package/dist/splice.d.ts +181 -0
  124. package/dist/splice.js +1263 -0
  125. package/dist/sqlite-checkpoint-store.d.ts +5 -0
  126. package/dist/sqlite-checkpoint-store.js +91 -0
  127. package/dist/sqlite-checkpoint-worker.d.ts +1 -0
  128. package/dist/sqlite-checkpoint-worker.js +115 -0
  129. package/dist/storage.d.ts +17 -0
  130. package/dist/storage.js +1 -0
  131. package/dist/store.d.ts +151 -0
  132. package/dist/store.js +735 -0
  133. package/dist/test-difference.d.ts +13 -0
  134. package/dist/test-difference.js +42 -0
  135. package/dist/testing.d.ts +122 -0
  136. package/dist/testing.js +261 -0
  137. package/dist/text-pages.d.ts +24 -0
  138. package/dist/text-pages.js +36 -0
  139. package/dist/tool-discovery.d.ts +59 -0
  140. package/dist/tool-discovery.js +136 -0
  141. package/dist/unevaluated.d.ts +7 -0
  142. package/dist/unevaluated.js +156 -0
  143. package/dist/v2.d.ts +49 -0
  144. package/dist/v2.js +413 -0
  145. package/dist/validate-output.d.ts +3 -0
  146. package/dist/validate-output.js +73 -0
  147. package/dist/version.d.ts +1 -0
  148. package/dist/version.js +1 -0
  149. package/dist/workflow-json.d.ts +8 -0
  150. package/dist/workflow-json.js +74 -0
  151. package/docs/AGENT-FRAMEWORKS.md +431 -0
  152. package/docs/BENCHMARKS.md +43 -0
  153. package/docs/INTEGRATION-QUICKSTART.md +859 -0
  154. package/docs/LEARNING-AND-STORAGE.md +393 -0
  155. package/docs/MCP.md +204 -0
  156. package/docs/PROJECTS-AND-UPGRADES.md +173 -0
  157. package/docs/PYTHON-REFERENCE.md +348 -0
  158. package/docs/PYTHON.md +120 -0
  159. package/docs/RECORDING-AND-CORRECTIONS.md +205 -0
  160. package/docs/TESTING.md +259 -0
  161. package/examples/mcp-app/build.mjs +11 -0
  162. package/examples/mcp-app/view.mjs +22 -0
  163. package/examples/quickstart.mjs +43 -0
  164. package/examples/route-driver.mjs +67 -0
  165. package/integrations/ai.d.mts +36 -0
  166. package/integrations/ai.mjs +178 -0
  167. package/integrations/call-options.mjs +9 -0
  168. package/integrations/langchain.d.mts +31 -0
  169. package/integrations/langchain.mjs +114 -0
  170. package/integrations/managed.mjs +154 -0
  171. package/integrations/types.d.mts +13 -0
  172. package/package.json +139 -4
@@ -0,0 +1,6 @@
1
+ import type { ToolCaller } from "./execution.js";
2
+ /** Share identical concurrent reads on one authorized caller for a single run. */
3
+ export declare function coalesceReads(caller: ToolCaller, { tools, maxPending }: {
4
+ tools: readonly string[];
5
+ maxPending?: number;
6
+ }): ToolCaller;
@@ -0,0 +1,33 @@
1
+ import { copyJson, jsonFingerprint } from "./workflow-json.js";
2
+ /** Share identical concurrent reads on one authorized caller for a single run. */
3
+ export function coalesceReads(caller, { tools, maxPending = 64 }) {
4
+ if (typeof caller !== "function" ||
5
+ !Array.isArray(tools) ||
6
+ !tools.length ||
7
+ tools.some((n) => typeof n !== "string" || !n))
8
+ throw new TypeError("Specify a connected caller and its read-only tool names.");
9
+ if (!Number.isSafeInteger(maxPending) || maxPending < 1)
10
+ throw new RangeError("maxPending must be a positive integer.");
11
+ const allowed = new Set(tools);
12
+ const pending = new Map();
13
+ return async (request, options) => {
14
+ if (!allowed.has(request.name) ||
15
+ (options && Object.values(options).some((v) => v !== undefined)) ||
16
+ Object.keys(request).some((k) => k !== "arguments" && k !== "name"))
17
+ return caller(request, options);
18
+ const snapshot = copyJson(request);
19
+ const key = jsonFingerprint(snapshot);
20
+ let flight = pending.get(key);
21
+ if (!flight) {
22
+ if (pending.size >= maxPending)
23
+ return caller(snapshot, options);
24
+ flight = Promise.resolve().then(() => caller(snapshot, options));
25
+ pending.set(key, flight);
26
+ const finished = () => {
27
+ pending.delete(key);
28
+ };
29
+ void flight.then(finished, finished);
30
+ }
31
+ return structuredClone(await flight);
32
+ };
33
+ }
@@ -0,0 +1,44 @@
1
+ import type { JsonSchema } from "./schema.js";
2
+ import { type ServerRecord, type ToolRecord } from "./store.js";
3
+ export interface TsOptions {
4
+ compact: boolean;
5
+ }
6
+ export declare const MAX_OUTPUT_DESCRIPTION_LENGTH = 2000;
7
+ export interface TsParts {
8
+ type: string;
9
+ /** Named definitions the main type refers to, as [name, body]. */
10
+ aliases: [string, string][];
11
+ }
12
+ export declare function schemaToTsParts(schema: JsonSchema, options?: TsOptions & {
13
+ aliasPrefix?: string;
14
+ usedNames?: Set<string>;
15
+ }): TsParts;
16
+ /** A self-contained rendering: named recursive types follow as `where Node = ...` (compact) or `type` lines. */
17
+ export declare function schemaToTs(schema: JsonSchema, options?: TsOptions): string;
18
+ /** True when `type` contains `|` or `&` outside any brackets, strings or comments. */
19
+ export declare function hasTopLevelOperator(type: string): boolean;
20
+ export declare function pascalCase(name: string): string;
21
+ /** One line describing what a tool returns, for appending to its description. */
22
+ export declare function describeOutput(tool: ToolRecord, options?: {
23
+ maxLength?: number;
24
+ }): string | undefined;
25
+ export interface ModuleOptions {
26
+ /** Name of the generated interface; defaults to the server name in PascalCase. */
27
+ interfaceName?: string;
28
+ /**
29
+ * learned: full output types. unknown: untyped (code mode without toolsplice).
30
+ * description: untyped, but each method's doc carries the one-line summary that
31
+ * `proxy --enrich description` appends to tool descriptions.
32
+ */
33
+ outputs?: "learned" | "unknown" | "description";
34
+ /** Replaces the comment explaining what a call returns. */
35
+ header?: string[];
36
+ }
37
+ export interface BindingModuleOptions extends Omit<ModuleOptions, "outputs"> {
38
+ /** Module specifier for Toolsplice's runtime. Default: toolsplice. */
39
+ runtimeImport?: string;
40
+ }
41
+ export declare const DEFAULT_HEADER: string[];
42
+ export declare function emitModule(server: ServerRecord, options?: ModuleOptions): string;
43
+ /** Emits a real .ts module containing types and a callable create<Interface> factory. */
44
+ export declare function emitBindings(server: ServerRecord, options?: BindingModuleOptions): string;
@@ -0,0 +1,479 @@
1
+ // Renders JSON Schema as TypeScript, either as a full .d.ts module with JSDoc
2
+ // or as a compact one-line signature cheap enough to append to a tool description.
3
+ import { toolOutput } from "./store.js";
4
+ const COMPACT_MAX_FIELDS = 25;
5
+ const MAX_COMMENT_LENGTH = 1000;
6
+ export const MAX_OUTPUT_DESCRIPTION_LENGTH = 2000;
7
+ const RESERVED_NAMES = new Set(["Array", "Record", "Promise", "String", "Number", "Boolean", "Object", "Function", "Symbol", "Date", "Map", "Set", "Unknown", "Any", "Never", "Null", "Undefined"]);
8
+ const RESERVED_BINDINGS = new Set("break case catch class const continue debugger default delete do else enum export extends false finally for function if import in instanceof new null return super switch this throw true try typeof var void while with implements interface let package private protected public static yield await any unknown never number string boolean undefined object intrinsic keyof unique readonly infer is asserts abstract declare namespace module require global".split(" "));
9
+ function allocateName(base, used) {
10
+ let name = base;
11
+ for (let i = 2; used.has(name) || RESERVED_NAMES.has(name); i++)
12
+ name = `${base}${i}`;
13
+ used.add(name);
14
+ return name;
15
+ }
16
+ /** Text is data even when a server supplies comment delimiters or line separators. */
17
+ function commentText(text, limit = MAX_COMMENT_LENGTH) {
18
+ return text.slice(0, limit).replace(/\*\//g, "*\\/").replace(/\/\*/g, "/ *").replace(/[\r\n\u2028\u2029\x00-\x1f\x7f]/g, " ");
19
+ }
20
+ export function schemaToTsParts(schema, options = { compact: false }) {
21
+ const ctx = { root: schema, compact: options.compact, depth: 0, seenRefs: new Set(), aliases: new Map(), aliasPrefix: options.aliasPrefix ? pascalCase(options.aliasPrefix) : "", refNames: new Map(), usedNames: options.usedNames ?? new Set(), budget: { remaining: options.compact ? 500 : 10000, characters: options.compact ? 20_000 : 1_000_000 }, renderDepth: 0, guardDepth: 0, activeRefs: new Map() };
22
+ const type = render(schema, ctx);
23
+ if (options.compact && type.length + [...ctx.aliases].reduce((n, [a, b]) => n + a.length + b.length + 5, 0) > 4000)
24
+ return { type: "unknown /* summary omitted: large schema */", aliases: [] };
25
+ return { type, aliases: [...ctx.aliases] };
26
+ }
27
+ /** A self-contained rendering: named recursive types follow as `where Node = ...` (compact) or `type` lines. */
28
+ export function schemaToTs(schema, options = { compact: false }) {
29
+ const { type, aliases } = schemaToTsParts(schema, options);
30
+ if (!aliases.length)
31
+ return type;
32
+ if (options.compact)
33
+ return `${type} where ${aliases.map(([n, b]) => `${n} = ${b}`).join("; ")}`;
34
+ return `${type}
35
+ ${aliases.map(([n, b]) => `type ${n} = ${b};`).join("\n")}`;
36
+ }
37
+ function render(schema, ctx) {
38
+ if (--ctx.budget.remaining < 0 || ctx.renderDepth >= 64)
39
+ return "unknown";
40
+ ctx = { ...ctx, renderDepth: ctx.renderDepth + 1 };
41
+ const result = renderBody(schema, ctx);
42
+ if (result.length > ctx.budget.characters)
43
+ return "unknown";
44
+ ctx.budget.characters -= result.length;
45
+ return result;
46
+ }
47
+ function renderBody(schema, ctx) {
48
+ if (schema === undefined || schema === true)
49
+ return "unknown";
50
+ if (schema === false)
51
+ return "never";
52
+ if (schema === null || typeof schema !== "object")
53
+ return "unknown";
54
+ if (typeof schema.$ref === "string")
55
+ return renderRef(schema.$ref, ctx);
56
+ if (Array.isArray(schema.enum) && schema.enum.length > ctx.budget.remaining)
57
+ return "unknown";
58
+ if (Array.isArray(schema.enum))
59
+ return schema.enum.map((v) => (boundedLiteral(v) ?? "unknown")).join(" | ") || "never";
60
+ if (Object.hasOwn(schema, "const"))
61
+ return boundedLiteral(schema.const) ?? "unknown";
62
+ const union = (schema.anyOf ?? schema.oneOf);
63
+ if (Array.isArray(union) && union.length > ctx.budget.remaining)
64
+ return "unknown";
65
+ if (Array.isArray(union))
66
+ return joinUnion(union.map((s) => render(s, ctx)));
67
+ if (Array.isArray(schema.allOf) && schema.allOf.length > ctx.budget.remaining)
68
+ return "unknown";
69
+ if (Array.isArray(schema.allOf))
70
+ return schema.allOf.map((s) => wrap(render(s, ctx))).join(" & ") || "unknown";
71
+ const type = schema.type;
72
+ if (Array.isArray(type))
73
+ return joinUnion(type.map((t) => render({ ...schema, type: t }, ctx)));
74
+ switch (type) {
75
+ case "string":
76
+ return withHint("string", stringHint(schema, ctx), ctx);
77
+ case "integer":
78
+ case "number":
79
+ return withHint("number", numberHint(schema), ctx);
80
+ case "boolean":
81
+ return "boolean";
82
+ case "null":
83
+ return "null";
84
+ case "array":
85
+ return renderArray(schema, ctx);
86
+ case "object":
87
+ return renderObject(schema, ctx);
88
+ default:
89
+ // Without an explicit type, properties/items only constrain instances of that type.
90
+ // Other JSON types remain valid; an object-only or array-only rendering would narrow it.
91
+ return withHint("unknown", typeof schema["x-hint"] === "string" ? schema["x-hint"] : undefined, ctx);
92
+ }
93
+ }
94
+ function renderRef(ref, ctx) {
95
+ if (ref !== "#" && !ref.startsWith("#/"))
96
+ return "unknown";
97
+ let target = ctx.root;
98
+ let segments;
99
+ try {
100
+ segments = ref === "#" ? [] : decodeURIComponent(ref.slice(2)).split("/").map((s) => s.replace(/~1/g, "/").replace(/~0/g, "~"));
101
+ }
102
+ catch {
103
+ return "unknown";
104
+ }
105
+ for (const key of segments) {
106
+ if (!target || typeof target !== "object" || !Object.hasOwn(target, key))
107
+ return "unknown";
108
+ target = target[key];
109
+ }
110
+ if (typeof target === "boolean")
111
+ return render(target, ctx);
112
+ if (!target || typeof target !== "object")
113
+ return "unknown";
114
+ // Reference-only cycles have no structural guard and cannot form valid TS aliases.
115
+ if (typeof target.$ref === "string") {
116
+ if (ctx.seenRefs.has(ref))
117
+ return "unknown";
118
+ ctx.seenRefs.add(ref);
119
+ try {
120
+ return render(target, ctx);
121
+ }
122
+ finally {
123
+ ctx.seenRefs.delete(ref);
124
+ }
125
+ }
126
+ const existing = ctx.refNames.get(ref);
127
+ if (existing)
128
+ return ctx.activeRefs.has(ref) && ctx.guardDepth <= ctx.activeRefs.get(ref) ? "unknown" : existing;
129
+ const name = allocateName(`${ctx.aliasPrefix}${pascalCase(segments.at(-1) ?? "Root")}`, ctx.usedNames);
130
+ ctx.refNames.set(ref, name);
131
+ ctx.aliases.set(name, "");
132
+ ctx.activeRefs.set(ref, ctx.guardDepth);
133
+ try {
134
+ ctx.aliases.set(name, render(target, { ...ctx, depth: 0 }));
135
+ }
136
+ finally {
137
+ ctx.activeRefs.delete(ref);
138
+ }
139
+ return name;
140
+ }
141
+ function renderArray(schema, ctx) {
142
+ ctx = { ...ctx, guardDepth: ctx.guardDepth + 1 };
143
+ if (Array.isArray(schema.prefixItems)) {
144
+ if (schema.prefixItems.length > ctx.budget.remaining)
145
+ return "unknown[]";
146
+ const min = typeof schema.minItems === "number" ? schema.minItems : 0;
147
+ const max = typeof schema.maxItems === "number" ? schema.maxItems : Infinity;
148
+ const members = schema.prefixItems.slice(0, max).map((item, i) => `${wrap(render(item, ctx))}${i >= min ? "?" : ""}`);
149
+ if (schema.items !== false && max > schema.prefixItems.length)
150
+ members.push(`...Array<${render(schema.items, ctx)}>`);
151
+ return `[${members.join(", ")}]`;
152
+ }
153
+ const items = schema.items;
154
+ const inner = render(items, ctx);
155
+ const array = hasTopLevelOperator(inner) ? `Array<${inner}>` : `${inner}[]`;
156
+ if (!ctx.suppressSampleHints && schema["x-sampled"] === true && schema["x-observed-items"] && typeof schema["x-observed-items"] === "object") {
157
+ const observed = annotationType(schema["x-observed-items"], { ...ctx, suppressSampleHints: true });
158
+ return `${array} /* ${commentText(`sampled item shape: ${observed}`)} */`;
159
+ }
160
+ return array;
161
+ }
162
+ function renderObject(schema, ctx) {
163
+ const props = (schema.properties ?? {});
164
+ const required = new Set((schema.required ?? []));
165
+ const keys = Object.keys(props);
166
+ if (keys.length > (ctx.compact ? 500 : 10000))
167
+ return "Record<string, unknown>";
168
+ if (keys.some((key) => key.length > 1000))
169
+ return "Record<string, unknown>";
170
+ const extra = schema.additionalProperties;
171
+ const mapHint = typeof schema["x-hint"] === "string" && ctx.compact ? ` /* ${commentText(schema["x-hint"])} */` : "";
172
+ if (keys.length === 0) {
173
+ if (extra === false)
174
+ return "Record<string, never>";
175
+ if (extra && typeof extra === "object") {
176
+ const value = render(extra, { ...ctx, guardDepth: ctx.guardDepth + 1 });
177
+ return ctx.activeRefs.size ? `{ [key: string]: ${value} }${mapHint}` : `Record<string, ${value}>${mapHint}`;
178
+ }
179
+ return "Record<string, unknown>";
180
+ }
181
+ const child = { ...ctx, depth: ctx.depth + 1, guardDepth: ctx.guardDepth + 1 };
182
+ const members = keys.map((key) => {
183
+ const prop = props[key];
184
+ const name = isIdentifier(key) ? key : JSON.stringify(key);
185
+ const optional = required.has(key) ? "" : "?";
186
+ const type = render(prop, child);
187
+ return { name, optional, type, doc: ctx.compact || !prop || typeof prop !== "object" ? "" : docComment(prop, ctx) };
188
+ });
189
+ if (extra && typeof extra === "object")
190
+ members.push({ name: "[key: string]", optional: "", type: joinUnion([render(extra, child), ...members.map((m) => m.type), ...(members.some((m) => m.optional) ? ["undefined"] : [])]), doc: "" });
191
+ if (ctx.compact) {
192
+ // Descriptions must stay short: summarize wide objects instead of listing every field.
193
+ if (members.length > COMPACT_MAX_FIELDS) {
194
+ const types = [...new Set(members.map((m) => m.type))];
195
+ if (types.length === 1 && !types[0].startsWith("{"))
196
+ return `Record<string, ${types[0]}> /* ${members.length} fields */`;
197
+ const shown = members.slice(0, COMPACT_MAX_FIELDS).map((m) => `${m.name}${m.optional}: ${m.type}`);
198
+ return `{ ${shown.join("; ")}; /* +${members.length - COMPACT_MAX_FIELDS} more fields */ }`;
199
+ }
200
+ return `{ ${members.map((m) => `${m.name}${m.optional}: ${m.type}`).join("; ")} }`;
201
+ }
202
+ const pad = " ".repeat(ctx.depth + 1);
203
+ const lines = members.map((m) => `${m.doc ? indentDoc(m.doc, pad) : ""}${pad}${m.name}${m.optional}: ${m.type};`);
204
+ return `{\n${lines.join("\n")}\n${" ".repeat(ctx.depth)}}`;
205
+ }
206
+ function stringHint(schema, ctx) {
207
+ const json = jsonContentType(schema, ctx);
208
+ if (json)
209
+ return `JSON string, parse to: ${json}`;
210
+ const observed = Array.isArray(schema["x-observed-values"]) ? schema["x-observed-values"].slice(0, 12) : undefined;
211
+ if (observed)
212
+ return observed.map((v) => boundedLiteral(v) ?? "[large value omitted]").join("|");
213
+ if (typeof schema.format === "string")
214
+ return schema.format;
215
+ return undefined;
216
+ }
217
+ /** For strings holding JSON: the parsed type, rendered compactly and safe to put inside a comment. */
218
+ function jsonContentType(schema, ctx) {
219
+ if (schema.contentMediaType !== "application/json" || !schema.contentSchema)
220
+ return undefined;
221
+ return annotationType(schema.contentSchema, ctx);
222
+ }
223
+ /** Render informational schemas in an isolated alias scope, sharing resource limits. */
224
+ function annotationType(schema, ctx) {
225
+ // Rendered against the same root so `$ref`s into the root's `$defs` resolve.
226
+ const inner = { ...ctx, compact: true, depth: 0, seenRefs: new Set(), aliases: new Map(), aliasPrefix: "", refNames: new Map(), usedNames: new Set(), activeRefs: new Map() };
227
+ const type = render(schema, inner);
228
+ const where = [...inner.aliases].map(([n, b]) => `${n} = ${b}`).join("; ");
229
+ return (where ? `${type} where ${where}` : type).replace(/\/\*\s*/g, "(").replace(/\s*\*\//g, ")");
230
+ }
231
+ /** Bound traversal before serializing untrusted enum/const/example JSON values. */
232
+ function boundedLiteral(value) {
233
+ let nodes = 512;
234
+ let characters = 4000;
235
+ const visit = (v, depth) => {
236
+ if (--nodes < 0 || depth > 32)
237
+ return undefined;
238
+ let result;
239
+ if (v === null || typeof v === "boolean" || (typeof v === "number" && Number.isFinite(v)))
240
+ result = JSON.stringify(v);
241
+ else if (typeof v === "string") {
242
+ if (v.length > characters)
243
+ return undefined;
244
+ result = JSON.stringify(v);
245
+ }
246
+ else if (Array.isArray(v)) {
247
+ if (v.length > nodes)
248
+ return undefined;
249
+ const parts = [];
250
+ for (const item of v) {
251
+ const part = visit(item, depth + 1);
252
+ if (part === undefined)
253
+ return undefined;
254
+ parts.push(part);
255
+ }
256
+ result = `[${parts.join(",")}]`;
257
+ }
258
+ else if (v && typeof v === "object") {
259
+ const parts = [];
260
+ for (const key in v) {
261
+ if (!Object.hasOwn(v, key))
262
+ continue;
263
+ if (key.length > characters)
264
+ return undefined;
265
+ const encodedKey = visit(key, depth + 1);
266
+ const part = visit(v[key], depth + 1);
267
+ if (encodedKey === undefined || part === undefined)
268
+ return undefined;
269
+ parts.push(`${encodedKey}:${part}`);
270
+ }
271
+ result = `{${parts.join(",")}}`;
272
+ }
273
+ if (result === undefined || result.length > characters)
274
+ return undefined;
275
+ characters -= result.length;
276
+ return result;
277
+ };
278
+ return visit(value, 0);
279
+ }
280
+ function numberHint(schema) {
281
+ if (schema["x-hint"] === "unix-seconds")
282
+ return "unix seconds";
283
+ if (schema["x-hint"] === "unix-millis")
284
+ return "unix millis";
285
+ return undefined;
286
+ }
287
+ /** Compact mode puts hints inline because there is no room for JSDoc. */
288
+ function withHint(type, hint, ctx) {
289
+ return ctx.compact && hint ? `${type} /* ${commentText(hint)} */` : type;
290
+ }
291
+ function docComment(schema, ctx, depth = 0) {
292
+ if (!schema || typeof schema !== "object" || depth >= 16 || --ctx.budget.remaining < 0)
293
+ return "";
294
+ const parts = [];
295
+ if (typeof schema.description === "string")
296
+ parts.push(schema.description.slice(0, MAX_COMMENT_LENGTH));
297
+ const observed = Array.isArray(schema["x-observed-values"]) ? schema["x-observed-values"].slice(0, 12) : undefined;
298
+ if (observed)
299
+ parts.push(`Observed values: ${observed.map((v) => boundedLiteral(v) ?? "[large value omitted]").join(", ")} (may not be exhaustive).`);
300
+ const json = jsonContentType(schema, ctx);
301
+ if (json)
302
+ parts.push(`Holds JSON; JSON.parse() it to get: ${json}`);
303
+ if (typeof schema.format === "string")
304
+ parts.push(`Format: ${schema.format}.`);
305
+ const hint = numberHint(schema);
306
+ if (hint)
307
+ parts.push(`Looks like a timestamp in ${hint}.`);
308
+ else if (typeof schema["x-hint"] === "string")
309
+ parts.push(`${capitalize(schema["x-hint"])}.`);
310
+ if (typeof schema["x-presence"] === "number")
311
+ parts.push(`Present in ${Math.round(schema["x-presence"] * 100)}% of observed objects.`);
312
+ if (schema["x-redacted"])
313
+ parts.push("Examples suppressed (key looks sensitive).");
314
+ const examples = Array.isArray(schema.examples) ? schema.examples : undefined;
315
+ if (examples?.length)
316
+ parts.push(`Example: ${examples.slice(0, 2).map((e) => boundedLiteral(e) ?? "[large value omitted]").join(", ")}`);
317
+ if (Array.isArray(schema.anyOf)) {
318
+ for (const v of schema.anyOf) {
319
+ const inner = docComment(v, ctx, depth + 1);
320
+ if (inner)
321
+ parts.push(inner);
322
+ }
323
+ }
324
+ return commentText(parts.join(" "));
325
+ }
326
+ function capitalize(text) {
327
+ return text.charAt(0).toUpperCase() + text.slice(1);
328
+ }
329
+ function indentDoc(doc, pad) {
330
+ return `${pad}/** ${commentText(doc)} */\n`;
331
+ }
332
+ function joinUnion(parts) {
333
+ return [...new Set(parts)].join(" | ") || "never";
334
+ }
335
+ function wrap(type) {
336
+ return hasTopLevelOperator(type) ? `(${type})` : type;
337
+ }
338
+ /** True when `type` contains `|` or `&` outside any brackets, strings or comments. */
339
+ export function hasTopLevelOperator(type) {
340
+ let depth = 0;
341
+ for (let i = 0; i < type.length; i++) {
342
+ const c = type[i];
343
+ if (c === "/" && type[i + 1] === "*") {
344
+ const end = type.indexOf("*/", i + 2);
345
+ i = end < 0 ? type.length : end + 1;
346
+ }
347
+ else if (c === '"') {
348
+ i++;
349
+ while (i < type.length && type[i] !== '"')
350
+ i += type[i] === "\\" ? 2 : 1;
351
+ }
352
+ else if (c === "{" || c === "(" || c === "<" || c === "[")
353
+ depth++;
354
+ else if (c === "}" || c === ")" || c === ">" || c === "]")
355
+ depth--;
356
+ else if (depth === 0 && (c === "|" || c === "&"))
357
+ return true;
358
+ }
359
+ return false;
360
+ }
361
+ function isIdentifier(key) {
362
+ return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key);
363
+ }
364
+ export function pascalCase(name) {
365
+ const cleaned = name.replace(/[^A-Za-z0-9]+/g, " ").trim();
366
+ const result = cleaned.replace(/(?:^|\s)(\w)/g, (_, c) => c.toUpperCase()).replace(/\s+/g, "");
367
+ return /^\d/.test(result) ? `T${result}` : result || "Tool";
368
+ }
369
+ // ---------------------------------------------------------------------------------------------
370
+ // Module and description rendering
371
+ /** One line describing what a tool returns, for appending to its description. */
372
+ export function describeOutput(tool, options = {}) {
373
+ const out = toolOutput(tool);
374
+ if (!out)
375
+ return undefined;
376
+ const type = outputTs(out, true);
377
+ const source = out.source === "declared" ? "declared by server" : `learned from ${out.samples} response${out.samples === 1 ? "" : "s"}`;
378
+ const encoding = out.encoding === "json-text" ? "JSON in the text content" : out.encoding === "structured" ? "structuredContent" : "plain text";
379
+ const limit = Math.max(0, Math.min(MAX_OUTPUT_DESCRIPTION_LENGTH, Math.floor(options.maxLength ?? MAX_OUTPUT_DESCRIPTION_LENGTH) || 0));
380
+ const summary = `Returns ${encoding} (${source}): ${type}`.replace(/[\r\n\u2028\u2029\x00-\x1f\x7f]/g, " ");
381
+ if (summary.length <= limit)
382
+ return summary;
383
+ const fallback = `Returns ${encoding} (${source}): unknown (schema summary omitted).`;
384
+ return fallback.length <= limit ? fallback : fallback.slice(0, limit);
385
+ }
386
+ function outputTs(out, compact) {
387
+ if (!out.schema)
388
+ return withText("string", out);
389
+ const { type, aliases } = schemaToTsParts(out.schema, { compact });
390
+ const result = withText(type, out);
391
+ if (!aliases.length)
392
+ return result;
393
+ return compact ? `${result} where ${aliases.map(([n, b]) => `${n} = ${b}`).join("; ")}` : `${result}\n${aliases.map(([n, b]) => `type ${n} = ${b};`).join("\n")}`;
394
+ }
395
+ function withText(type, out) {
396
+ const variants = [type, ...(out.alsoText ? ["string"] : []), ...(out.alsoEmpty ? ["null"] : [])];
397
+ return [...new Set(variants)].join(" | ");
398
+ }
399
+ /** `export type` lines for a schema plus the named recursive types it uses. */
400
+ function typeDeclarations(name, schema, fallback, prefix, out, usedNames) {
401
+ if (!schema)
402
+ return [`export type ${name} = ${out ? withText(fallback, out) : fallback};`];
403
+ const { type, aliases } = schemaToTsParts(schema, { compact: false, aliasPrefix: prefix, usedNames });
404
+ return [...aliases.map(([n, body]) => `export type ${n} = ${body};`), `export type ${name} = ${out ? withText(type, out) : type};`];
405
+ }
406
+ export const DEFAULT_HEADER = [
407
+ "// Output types are learned from real responses. A tool's result is its structuredContent,",
408
+ "// or its text content parsed as JSON, or the raw text when it isn't JSON.",
409
+ ];
410
+ export function emitModule(server, options = {}) {
411
+ return renderModule(server, options);
412
+ }
413
+ /** Emits a real .ts module containing types and a callable create<Interface> factory. */
414
+ export function emitBindings(server, options = {}) {
415
+ return renderModule(server, { ...options, outputs: "learned" }, options.runtimeImport ?? "toolsplice");
416
+ }
417
+ function renderModule(server, options, runtimeImport) {
418
+ const requestedIface = options.interfaceName ?? `${pascalCase(server.name)}Tools`;
419
+ const iface = isIdentifier(requestedIface) && !RESERVED_NAMES.has(requestedIface) && !RESERVED_BINDINGS.has(requestedIface) ? requestedIface : `${pascalCase(requestedIface)}Tools`;
420
+ const usedNames = new Set([iface]);
421
+ const runtime = runtimeImport === undefined ? undefined : allocateName("__toolsplice", usedNames);
422
+ const factory = runtime ? allocateName(`create${iface}`, usedNames) : undefined;
423
+ const tools = Object.values(server.tools).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
424
+ const names = tools.map((tool) => {
425
+ const base = pascalCase(tool.name);
426
+ return { input: allocateName(`${base}Input`, usedNames), output: allocateName(`${base}Output`, usedNames), base };
427
+ });
428
+ const learnedOutputs = (options.outputs ?? "learned") === "learned";
429
+ const out = [
430
+ `// Generated by toolsplice from "${commentText(server.name)}"${server.version ? ` v${commentText(server.version)}` : ""}.`,
431
+ ...(options.header ?? DEFAULT_HEADER),
432
+ "",
433
+ ...(runtime ? [`import * as ${runtime} from ${JSON.stringify(runtimeImport)};`, "// Observed return types are not runtime guarantees. Monitor drift before relying on them.", ""] : []),
434
+ ];
435
+ const methods = [];
436
+ const implementations = [];
437
+ for (const [index, tool] of tools.entries()) {
438
+ const { input, output: outputName, base } = names[index];
439
+ const output = learnedOutputs ? toolOutput(tool) : undefined;
440
+ out.push(...typeDeclarations(input, tool.inputSchema, "Record<string, unknown>", input, undefined, usedNames), "");
441
+ if (learnedOutputs)
442
+ out.push(`/** ${commentText(outputDoc(tool, output))} */`);
443
+ const outputFallback = output && !output.schema ? "string" : "unknown";
444
+ out.push(...typeDeclarations(outputName, output?.schema, outputFallback, base, output, usedNames), "");
445
+ const summary = options.outputs === "description" ? describeOutput(tool) : undefined;
446
+ const doc = [tool.description?.trim().slice(0, MAX_COMMENT_LENGTH), summary, annotationsDoc(tool)].filter(Boolean).join("\n");
447
+ const docBlock = doc ? ` /**\n${doc.split("\n").map((l) => ` * ${commentText(l)}`).join("\n")}\n */\n` : "";
448
+ const method = isIdentifier(tool.name) ? tool.name : JSON.stringify(tool.name);
449
+ methods.push(`${docBlock} ${method}(args: ${input}${runtime ? `, options?: ${runtime}.BindingCallOptions` : ""}): Promise<${outputName}>;`);
450
+ if (runtime)
451
+ implementations.push(` [${JSON.stringify(tool.name)}]: (args: ${input}, options?: ${runtime}.BindingCallOptions) => ${runtime}.invokeTool<${outputName}>(caller, ${JSON.stringify(tool.name)}, args, options),`);
452
+ }
453
+ out.push(`export interface ${iface} {`, methods.join("\n"), "}", "");
454
+ if (runtime)
455
+ out.push(`export function ${factory}(caller: ${runtime}.ToolCaller): ${iface} {`, " return {", ...implementations, " };", "}", "");
456
+ return out.join("\n");
457
+ }
458
+ function outputDoc(tool, out) {
459
+ if (!out)
460
+ return tool.calls ? `Not learned yet: ${tool.calls} call(s), none returned JSON.` : "Not learned yet: no calls recorded.";
461
+ const parts = [out.source === "declared" ? "Declared by the server." : `Learned from ${out.samples} response(s).`];
462
+ if (out.alsoText)
463
+ parts.push(out.textSample === undefined ? "Sometimes returns plain text instead." : "Sometimes returns plain text instead, e.g. " + (boundedLiteral(out.textSample) ?? "[large value omitted]") + ".");
464
+ if (out.prefix)
465
+ parts.push(`JSON follows a text prefix like ${(boundedLiteral(out.prefix) ?? "[large value omitted]")}.`);
466
+ if (out.warning)
467
+ parts.push(out.warning);
468
+ return parts.join(" ");
469
+ }
470
+ function annotationsDoc(tool) {
471
+ const a = tool.annotations;
472
+ if (!a)
473
+ return "";
474
+ if (a.readOnlyHint)
475
+ return "Read-only.";
476
+ if (a.destructiveHint)
477
+ return "Destructive: changes or deletes data.";
478
+ return "";
479
+ }
@@ -0,0 +1,23 @@
1
+ import { type ContractSnapshot, type ContractSchema } from "./contracts.js";
2
+ import { type ToolCaller } from "./execution.js";
3
+ export interface ContractIssue {
4
+ path: string;
5
+ keyword: string;
6
+ }
7
+ export declare class ContractValidationError extends Error {
8
+ readonly tool: string;
9
+ readonly stage: "input" | "output" | "contract";
10
+ readonly issues: ContractIssue[];
11
+ constructor(tool: string, stage: "input" | "output" | "contract", issues: ContractIssue[]);
12
+ }
13
+ export declare function createGuardCompiler(): (schema: ContractSchema | null, tool: string, stage: string) => import("ajv/dist/core.js").AnyValidateFunction<unknown>;
14
+ export interface ContractCallerOptions {
15
+ /** Both default true. Disabling one stage is explicit; unknown tools always fail before dispatch. */
16
+ inputs?: boolean;
17
+ outputs?: boolean;
18
+ }
19
+ /** Compile once, then enforce a detached snapshot before inputs and after decoded outputs.
20
+ * Raw successful results are returned unchanged for generated bindings or SDK consumers.
21
+ * MCP error and unfinished results pass through for normal SDK/binding error handling.
22
+ * Reviewed schemas are trusted configuration, not an arbitrary-schema execution sandbox. */
23
+ export declare function createContractCaller(caller: ToolCaller, source: ContractSnapshot, options?: ContractCallerOptions): ToolCaller;