toolsplice 0.0.0-stage → 0.0.1

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 (65) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +372 -2
  3. package/dist/cli.d.ts +2 -0
  4. package/dist/cli.js +923 -0
  5. package/dist/codegen.d.ts +44 -0
  6. package/dist/codegen.js +479 -0
  7. package/dist/contract-caller.d.ts +22 -0
  8. package/dist/contract-caller.js +307 -0
  9. package/dist/contract-corrections.d.ts +35 -0
  10. package/dist/contract-corrections.js +159 -0
  11. package/dist/contract-schema.d.ts +5 -0
  12. package/dist/contract-schema.js +126 -0
  13. package/dist/contracts.d.ts +71 -0
  14. package/dist/contracts.js +366 -0
  15. package/dist/core.d.ts +14 -0
  16. package/dist/core.js +16 -0
  17. package/dist/doctor.d.ts +22 -0
  18. package/dist/doctor.js +91 -0
  19. package/dist/drift.d.ts +23 -0
  20. package/dist/drift.js +111 -0
  21. package/dist/execution.d.ts +38 -0
  22. package/dist/execution.js +66 -0
  23. package/dist/extract.d.ts +34 -0
  24. package/dist/extract.js +73 -0
  25. package/dist/index.d.ts +20 -0
  26. package/dist/index.js +19 -0
  27. package/dist/ordered-transport.d.ts +12 -0
  28. package/dist/ordered-transport.js +106 -0
  29. package/dist/pattern.d.ts +2 -0
  30. package/dist/pattern.js +32 -0
  31. package/dist/postgres.d.ts +41 -0
  32. package/dist/postgres.js +264 -0
  33. package/dist/probe.d.ts +29 -0
  34. package/dist/probe.js +134 -0
  35. package/dist/proxy.d.ts +40 -0
  36. package/dist/proxy.js +436 -0
  37. package/dist/runtime.d.ts +6 -0
  38. package/dist/runtime.js +26 -0
  39. package/dist/schema.d.ts +17 -0
  40. package/dist/schema.js +299 -0
  41. package/dist/shape.d.ts +91 -0
  42. package/dist/shape.js +499 -0
  43. package/dist/splice-diagnostics.d.ts +40 -0
  44. package/dist/splice-diagnostics.js +80 -0
  45. package/dist/splice-project.d.ts +119 -0
  46. package/dist/splice-project.js +296 -0
  47. package/dist/splice-recording.d.ts +105 -0
  48. package/dist/splice-recording.js +464 -0
  49. package/dist/splice.d.ts +84 -0
  50. package/dist/splice.js +1065 -0
  51. package/dist/storage.d.ts +17 -0
  52. package/dist/storage.js +1 -0
  53. package/dist/store.d.ts +151 -0
  54. package/dist/store.js +735 -0
  55. package/dist/v2.d.ts +49 -0
  56. package/dist/v2.js +396 -0
  57. package/dist/validate-output.d.ts +3 -0
  58. package/dist/validate-output.js +73 -0
  59. package/dist/version.d.ts +1 -0
  60. package/dist/version.js +1 -0
  61. package/dist/workflow-json.d.ts +8 -0
  62. package/dist/workflow-json.js +74 -0
  63. package/docs/PROJECTS-AND-UPGRADES.md +115 -0
  64. package/docs/RECORDING-AND-CORRECTIONS.md +176 -0
  65. package/package.json +95 -4
package/dist/drift.js ADDED
@@ -0,0 +1,111 @@
1
+ // Structural changes are observations, not proof of a breaking upstream change. No result values
2
+ // are retained here. This also gives exports a fingerprint that doesn't change on every call.
3
+ import { definitionContract } from "./contract-schema.js";
4
+ import { createHash } from "node:crypto";
5
+ import { emptyShape } from "./shape.js";
6
+ import { toJsonSchema } from "./schema.js";
7
+ const CONTRACT_KEYS = new Set([
8
+ "type", "properties", "required", "items", "prefixItems", "additionalProperties", "anyOf", "oneOf", "allOf",
9
+ "$ref", "$defs", "definitions", "format", "enum", "const", "contentMediaType", "contentSchema", "x-hint",
10
+ "minItems", "maxItems",
11
+ "x-observed-items", "x-sampled",
12
+ ]);
13
+ /** Strip examples, occurrence counts and other annotations. Stable across key order and traffic volume. */
14
+ export function contract(schema) {
15
+ if (schema === null || typeof schema !== "object")
16
+ return schema;
17
+ if (Array.isArray(schema))
18
+ return schema.map(contract);
19
+ const s = schema;
20
+ return Object.fromEntries(Object.keys(s).filter((k) => CONTRACT_KEYS.has(k)).sort().map((k) => {
21
+ const value = s[k];
22
+ if (k === "const" || k === "enum")
23
+ return [k, literal(value)];
24
+ if (["properties", "$defs", "definitions"].includes(k) && value && typeof value === "object") {
25
+ return [k, Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([n, v]) => [n, contract(v)]))];
26
+ }
27
+ if (k === "required" && Array.isArray(value))
28
+ return [k, [...value].sort()];
29
+ return [k, contract(value)];
30
+ }));
31
+ }
32
+ /** Literal JSON objects inside const/enum are data: do not filter their property names. */
33
+ function literal(value) {
34
+ if (Array.isArray(value))
35
+ return value.map(literal);
36
+ if (!value || typeof value !== "object")
37
+ return value;
38
+ return Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => [k, literal(v)]));
39
+ }
40
+ export function stableHash(value) {
41
+ return createHash("sha256").update(JSON.stringify(value)).digest("hex");
42
+ }
43
+ export function learnedContract(tool) {
44
+ return {
45
+ schema: contract(toJsonSchema(tool.shape)),
46
+ encodings: ["structured", "json-text", "text", "empty"].filter((k) => tool.kinds[k] > 0),
47
+ };
48
+ }
49
+ export function exportFingerprint(server) {
50
+ return stableHash(Object.values(server.tools).sort((a, b) => a.name.localeCompare(b.name)).map((t) => ({
51
+ name: t.name, input: t.inputSchema === undefined ? undefined : definitionContract(t.inputSchema), declared: t.outputSchema === undefined ? undefined : definitionContract(t.outputSchema), learned: learnedContract(t),
52
+ })));
53
+ }
54
+ /** Run after recordCall, using a snapshot taken before it. Only changes after the first result count. */
55
+ export function recordDrift(tool, before, priorObservations, kind) {
56
+ if (kind === "error" || !priorObservations)
57
+ return undefined;
58
+ const after = learnedContract(tool);
59
+ if (stableHash(before) === stableHash(after))
60
+ return undefined;
61
+ return addEvent(tool, { at: new Date().toISOString(), changes: differences(before, after), reason: "observed-shape" });
62
+ }
63
+ function addEvent(tool, event) {
64
+ const drift = (tool.drift ??= { revision: 0, events: [] });
65
+ drift.revision++;
66
+ drift.events.push(event);
67
+ if (drift.events.length > 20)
68
+ drift.events.splice(0, drift.events.length - 20);
69
+ return event;
70
+ }
71
+ export function resetLearning(tool, reason) {
72
+ if (!tool.calls)
73
+ return;
74
+ tool.calls = 0;
75
+ tool.kinds = { structured: 0, "json-text": 0, text: 0, error: 0, empty: 0 };
76
+ tool.shape = emptyShape();
77
+ tool.textSamples = [];
78
+ tool.errorSamples = [];
79
+ tool.prefixes = [];
80
+ delete tool.schemaValidation;
81
+ addEvent(tool, { at: new Date().toISOString(), changes: ["Learned output reset; observe this version again."], reason });
82
+ }
83
+ export function definitionFingerprint(tool) {
84
+ return stableHash({ input: tool.inputSchema === undefined ? undefined : definitionContract(tool.inputSchema), output: tool.outputSchema === undefined ? undefined : definitionContract(tool.outputSchema) });
85
+ }
86
+ /** Short, value-free JSON-pointer paths; field names are data, not prose instructions. */
87
+ function differences(before, after) {
88
+ const changes = [];
89
+ const walk = (a, b, path, depth) => {
90
+ if (changes.length >= 12 || depth > 28 || JSON.stringify(a) === JSON.stringify(b))
91
+ return;
92
+ if (a && b && !Array.isArray(a) && !Array.isArray(b) && typeof a === "object" && typeof b === "object") {
93
+ const aa = a, bb = b;
94
+ for (const k of [...new Set([...Object.keys(aa), ...Object.keys(bb)])].sort()) {
95
+ const p = `${path}/${k.replace(/~/g, "~0").replace(/\//g, "~1")}`;
96
+ if (!Object.hasOwn(aa, k))
97
+ changes.push(`Added ${p}`);
98
+ else if (!Object.hasOwn(bb, k))
99
+ changes.push(`Changed ${p}`);
100
+ else
101
+ walk(aa[k], bb[k], p, depth + 1);
102
+ if (changes.length >= 12)
103
+ break;
104
+ }
105
+ }
106
+ else
107
+ changes.push(`Changed ${path || "/"}`);
108
+ };
109
+ walk(before, after, "", 0);
110
+ return changes.length ? changes : ["Observed output shape changed."];
111
+ }
@@ -0,0 +1,38 @@
1
+ import { type ToolResultLike } from "./extract.js";
2
+ export type ToolFunction = (args?: Record<string, unknown>) => Promise<unknown>;
3
+ export interface BindingCallOptions {
4
+ signal?: AbortSignal;
5
+ timeoutMs?: number;
6
+ onProgress?: (progress: {
7
+ progress: number;
8
+ total?: number;
9
+ message?: string;
10
+ }) => void;
11
+ }
12
+ /** Supply a raw MCP result; generated bindings perform the matching decode. */
13
+ export type ToolCaller = (request: {
14
+ name: string;
15
+ arguments: Record<string, unknown>;
16
+ }, options?: BindingCallOptions) => Promise<ToolResultLike>;
17
+ export declare function bindingOptions(options?: BindingCallOptions, defaults?: BindingCallOptions): {
18
+ timeout: number;
19
+ signal: AbortSignal | undefined;
20
+ onprogress: ((progress: {
21
+ progress: number;
22
+ total?: number;
23
+ message?: string;
24
+ }) => void) | undefined;
25
+ };
26
+ /** Used by generated factories. Output is observationally typed, not runtime validated.
27
+ * Transport/abort errors propagate unchanged; an MCP isError result throws ToolError. */
28
+ export declare function invokeTool<Output>(caller: ToolCaller, name: string, args: unknown, options?: BindingCallOptions): Promise<Output>;
29
+ /**
30
+ * decoded: structuredContent, else text parsed as JSON (a short prose prefix is stripped), else the text.
31
+ * raw: structuredContent, else the text as-is — what most code-mode runtimes hand the model today.
32
+ */
33
+ export type DecodeMode = "decoded" | "raw";
34
+ export declare class ToolError extends Error {
35
+ readonly tool: string;
36
+ constructor(tool: string, message: string);
37
+ }
38
+ export declare function decode(result: ToolResultLike, mode?: DecodeMode): unknown;
@@ -0,0 +1,66 @@
1
+ // SDK-free call options, decoding and execution used by both package variants.
2
+ import { extract } from "./extract.js";
3
+ export function bindingOptions(options, defaults) {
4
+ const timeout = options?.timeoutMs ?? defaults?.timeoutMs ?? 120_000;
5
+ if (!Number.isSafeInteger(timeout) || timeout < 1 || timeout > 2_147_483_647)
6
+ throw new RangeError("timeoutMs must be an integer between 1 and 2147483647.");
7
+ const signal = options?.signal ?? defaults?.signal;
8
+ signal?.throwIfAborted();
9
+ return {
10
+ timeout,
11
+ signal,
12
+ onprogress: options?.onProgress ?? defaults?.onProgress,
13
+ };
14
+ }
15
+ /** Used by generated factories. Output is observationally typed, not runtime validated.
16
+ * Transport/abort errors propagate unchanged; an MCP isError result throws ToolError. */
17
+ export async function invokeTool(caller, name, args, options) {
18
+ bindingOptions(options);
19
+ if (!args || typeof args !== "object" || Array.isArray(args))
20
+ throw new TypeError("Tool arguments must be an object.");
21
+ const result = await caller({ name, arguments: args }, options);
22
+ options?.signal?.throwIfAborted();
23
+ if (result &&
24
+ typeof result === "object" &&
25
+ "resultType" in result &&
26
+ result.resultType !== undefined &&
27
+ result.resultType !== "complete") {
28
+ throw new ToolError(name, "Tool did not complete; handle its interactive or deferred result through the SDK.");
29
+ }
30
+ try {
31
+ return decode(result);
32
+ }
33
+ catch (error) {
34
+ throw new ToolError(name, error instanceof Error ? error.message : String(error));
35
+ }
36
+ }
37
+ export class ToolError extends Error {
38
+ tool;
39
+ constructor(tool, message) {
40
+ super(`${tool}: ${message}`);
41
+ this.tool = tool;
42
+ this.name = "ToolError";
43
+ }
44
+ }
45
+ export function decode(result, mode = "decoded") {
46
+ const extracted = extract(result);
47
+ if (extracted.kind === "error")
48
+ throw new Error(extracted.text || "tool returned an error");
49
+ if (mode === "raw") {
50
+ if (result.structuredContent !== undefined)
51
+ return result.structuredContent;
52
+ const texts = (result.content ?? [])
53
+ .filter((c) => c.type === "text")
54
+ .map((c) => c.text ?? "");
55
+ return texts.length === 1 ? texts[0] : texts;
56
+ }
57
+ switch (extracted.kind) {
58
+ case "structured":
59
+ case "json-text":
60
+ return extracted.value;
61
+ case "text":
62
+ return extracted.text;
63
+ case "empty":
64
+ return null;
65
+ }
66
+ }
@@ -0,0 +1,34 @@
1
+ export type OutputKind = "structured" | "json-text" | "text" | "error" | "empty";
2
+ export type Extracted = {
3
+ kind: "structured";
4
+ value: unknown;
5
+ } | {
6
+ kind: "json-text";
7
+ value: unknown;
8
+ multi: boolean;
9
+ prefix?: string;
10
+ } | {
11
+ kind: "text";
12
+ text: string;
13
+ } | {
14
+ kind: "error";
15
+ text: string;
16
+ } | {
17
+ kind: "empty";
18
+ };
19
+ interface ContentItem {
20
+ type: string;
21
+ text?: string;
22
+ }
23
+ export interface ToolResultLike {
24
+ content?: ContentItem[];
25
+ structuredContent?: unknown;
26
+ isError?: boolean;
27
+ }
28
+ /** Parses a string as JSON, tolerating code fences and a short leading sentence. */
29
+ export declare function parseJsonText(raw: string): {
30
+ value: unknown;
31
+ prefix?: string;
32
+ } | undefined;
33
+ export declare function extract(result: ToolResultLike): Extracted;
34
+ export {};
@@ -0,0 +1,73 @@
1
+ // Pulls a machine-readable value out of an MCP tool result.
2
+ // Most servers don't send structuredContent, so we also look for JSON inside text content.
3
+ const FENCE = /^```(?:json|JSON)?\s*\n([\s\S]*?)\n?```$/;
4
+ /** Parses a string as JSON, tolerating code fences and a short leading sentence. */
5
+ export function parseJsonText(raw) {
6
+ const text = raw.trim();
7
+ if (!text)
8
+ return undefined;
9
+ const fenced = FENCE.exec(text);
10
+ const body = fenced ? fenced[1].trim() : text;
11
+ const direct = tryParse(body);
12
+ if (direct.ok)
13
+ return { value: direct.value };
14
+ // "Found 3 issues:\n[...]" — accept a short prefix followed by a JSON object or array.
15
+ const start = firstJsonStart(body);
16
+ if (start > 0 && start <= 200) {
17
+ const rest = body.slice(start);
18
+ const parsed = tryParse(rest);
19
+ if (parsed.ok && typeof parsed.value === "object" && parsed.value !== null) {
20
+ return { value: parsed.value, prefix: body.slice(0, start).trim() };
21
+ }
22
+ }
23
+ return undefined;
24
+ }
25
+ export function extract(result) {
26
+ const textItems = (result.content ?? []).filter((c) => c.type === "text" && typeof c.text === "string");
27
+ const allText = textItems.map((c) => c.text).join("\n");
28
+ if (result.isError)
29
+ return { kind: "error", text: allText };
30
+ // Modern MCP permits any JSON value here, including null; absence is undefined.
31
+ if (result.structuredContent !== undefined) {
32
+ return { kind: "structured", value: result.structuredContent };
33
+ }
34
+ if (textItems.length === 0)
35
+ return { kind: "empty" };
36
+ if (textItems.length === 1) {
37
+ const parsed = parseJsonText(textItems[0].text);
38
+ if (parsed)
39
+ return { kind: "json-text", value: parsed.value, multi: false, prefix: parsed.prefix };
40
+ return { kind: "text", text: allText };
41
+ }
42
+ // Some servers send one text item per record. Treat it as an array only if every item is JSON.
43
+ const values = [];
44
+ for (const item of textItems) {
45
+ const parsed = parseJsonText(item.text);
46
+ if (!parsed || parsed.prefix)
47
+ return { kind: "text", text: allText };
48
+ values.push(parsed.value);
49
+ }
50
+ return { kind: "json-text", value: values, multi: true };
51
+ }
52
+ function tryParse(text) {
53
+ const first = text[0];
54
+ // Only structured JSON counts; a bare word like `true` or `12` in prose is too ambiguous.
55
+ if (first !== "{" && first !== "[" && first !== '"' && !/^-?\d/.test(text) && text !== "true" && text !== "false" && text !== "null") {
56
+ return { ok: false };
57
+ }
58
+ try {
59
+ return { ok: true, value: JSON.parse(text) };
60
+ }
61
+ catch {
62
+ return { ok: false };
63
+ }
64
+ }
65
+ function firstJsonStart(text) {
66
+ const brace = text.indexOf("{");
67
+ const bracket = text.indexOf("[");
68
+ if (brace < 0)
69
+ return bracket;
70
+ if (bracket < 0)
71
+ return brace;
72
+ return Math.min(brace, bracket);
73
+ }
@@ -0,0 +1,20 @@
1
+ export { extract, parseJsonText, type Extracted, type OutputKind, type ToolResultLike } from "./extract.js";
2
+ export { emptyShape, mergeInto, observe, shapeFromValues, hasEmbeddedJson, isSafeValue, type Shape, type ObserveOptions, type ExamplePolicy } from "./shape.js";
3
+ export { toJsonSchema, observedValues, looksLikeMap, type JsonSchema, type SchemaOptions } from "./schema.js";
4
+ export { schemaToTs, schemaToTsParts, emitModule, emitBindings, describeOutput, pascalCase, DEFAULT_HEADER, type ModuleOptions, type BindingModuleOptions } from "./codegen.js";
5
+ export { ShapeStore, ShapeStoreError, type ShapeStoreDiagnostic, applyExamplePolicy, scrub, recordCall, recordToolList, toolOutput, newServer, type ServerRecord, type ToolRecord, type ToolOutput } from "./store.js";
6
+ export { createProxy, type ProxyOptions, type EnrichMode, type Proxy } from "./proxy.js";
7
+ export { probe, synthesizeArgs, type ProbeOptions, type ProbeReport } from "./probe.js";
8
+ export { decode, toolFunctions, createToolCaller, invokeTool, ToolError, type BindingCallOptions, type ToolCaller, type DecodeMode, type ToolFunction } from "./runtime.js";
9
+ export { diagnose, diagnoseTool, formatDoctor, type DoctorReport, type ToolDiagnostic, type ToolHealth } from "./doctor.js";
10
+ export { exportFingerprint, learnedContract, recordDrift, type DriftState, type DriftEvent } from "./drift.js";
11
+ export { orderedTransport } from "./ordered-transport.js";
12
+ export type { LearningStore, Awaitable } from "./storage.js";
13
+ export { createContractFromCatalog, createContractSnapshot, parseContractSnapshot, compareContractSnapshots, contractCheckFailed, definitionContract, type ContractSnapshot, type ContractTool, type ContractSchema, type ContractComparison, type ContractChange, type ChangeSeverity } from "./contracts.js";
14
+ export { createContractCaller, ContractValidationError, type ContractIssue, type ContractCallerOptions } from "./contract-caller.js";
15
+ export { selectContractTools } from "./contracts.js";
16
+ export { initializeSpliceProject, createSpliceProjectFiles, checkSpliceProject, checkSpliceProjectFiles, type SpliceProjectOptions } from "./splice-project.js";
17
+ export { explainSpliceError, type SpliceExplanation, type SpliceFieldOrigin } from "./splice-diagnostics.js";
18
+ export { createSpliceRecorder, parseSpliceRecording, replaySpliceRecording, type SpliceRecording, type SpliceRecordingOptions, type SpliceReplayOptions } from "./splice-recording.js";
19
+ export { parseContractCorrection, applyContractCorrection, type ContractCorrection, type CorrectionFixtureResult } from "./contract-corrections.js";
20
+ export { parseSpliceSpec, preflightSplice, prepareSplice, emitSpliceModule, SpliceError, type SpliceSpec, type SpliceEndpoint, type SpliceBinding, type SpliceReport, type SpliceIssue, type SpliceRunOptions, type SpliceMappingOptions } from "./splice.js";
package/dist/index.js ADDED
@@ -0,0 +1,19 @@
1
+ export { extract, parseJsonText } from "./extract.js";
2
+ export { emptyShape, mergeInto, observe, shapeFromValues, hasEmbeddedJson, isSafeValue } from "./shape.js";
3
+ export { toJsonSchema, observedValues, looksLikeMap } from "./schema.js";
4
+ export { schemaToTs, schemaToTsParts, emitModule, emitBindings, describeOutput, pascalCase, DEFAULT_HEADER } from "./codegen.js";
5
+ export { ShapeStore, ShapeStoreError, applyExamplePolicy, scrub, recordCall, recordToolList, toolOutput, newServer } from "./store.js";
6
+ export { createProxy } from "./proxy.js";
7
+ export { probe, synthesizeArgs } from "./probe.js";
8
+ export { decode, toolFunctions, createToolCaller, invokeTool, ToolError } from "./runtime.js";
9
+ export { diagnose, diagnoseTool, formatDoctor } from "./doctor.js";
10
+ export { exportFingerprint, learnedContract, recordDrift } from "./drift.js";
11
+ export { orderedTransport } from "./ordered-transport.js";
12
+ export { createContractFromCatalog, createContractSnapshot, parseContractSnapshot, compareContractSnapshots, contractCheckFailed, definitionContract } from "./contracts.js";
13
+ export { createContractCaller, ContractValidationError } from "./contract-caller.js";
14
+ export { selectContractTools } from "./contracts.js";
15
+ export { initializeSpliceProject, createSpliceProjectFiles, checkSpliceProject, checkSpliceProjectFiles } from "./splice-project.js";
16
+ export { explainSpliceError } from "./splice-diagnostics.js";
17
+ export { createSpliceRecorder, parseSpliceRecording, replaySpliceRecording } from "./splice-recording.js";
18
+ export { parseContractCorrection, applyContractCorrection } from "./contract-corrections.js";
19
+ export { parseSpliceSpec, preflightSplice, prepareSplice, emitSpliceModule, SpliceError } from "./splice.js";
@@ -0,0 +1,12 @@
1
+ import type { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
2
+ /**
3
+ * Wrap BEFORE connecting a client/server. Delivers inbound events in order,
4
+ * one per microtask, so SDK notification callbacks can run before a following
5
+ * response removes their progress handlers. No timers, pings or wire changes.
6
+ *
7
+ * Owns the underlying transport callbacks, just as Protocol.connect does.
8
+ * Methods/getters (including transport-specific extensions such as pid, stderr
9
+ * and terminateSession) retain their original receiver. Use a fresh wrapper for
10
+ * each connection; closing is idempotent and drains prior events before onclose.
11
+ */
12
+ export declare function orderedTransport<T extends Transport>(transport: T): T;
@@ -0,0 +1,106 @@
1
+ /**
2
+ * Wrap BEFORE connecting a client/server. Delivers inbound events in order,
3
+ * one per microtask, so SDK notification callbacks can run before a following
4
+ * response removes their progress handlers. No timers, pings or wire changes.
5
+ *
6
+ * Owns the underlying transport callbacks, just as Protocol.connect does.
7
+ * Methods/getters (including transport-specific extensions such as pid, stderr
8
+ * and terminateSession) retain their original receiver. Use a fresh wrapper for
9
+ * each connection; closing is idempotent and drains prior events before onclose.
10
+ */
11
+ export function orderedTransport(transport) {
12
+ const callbacks = {
13
+ onmessage: transport.onmessage, onerror: transport.onerror, onclose: transport.onclose,
14
+ };
15
+ const queue = [];
16
+ const idle = [];
17
+ let scheduled = false, closed = false, closeQueued = false, started = false;
18
+ let closing;
19
+ function schedule() {
20
+ if (scheduled || !queue.length)
21
+ return;
22
+ scheduled = true;
23
+ queueMicrotask(() => {
24
+ scheduled = false;
25
+ const delivery = queue.shift();
26
+ try {
27
+ if (delivery.kind === "close") {
28
+ closed = true;
29
+ callbacks.onclose?.();
30
+ }
31
+ else if (!closed && delivery.kind === "message")
32
+ callbacks.onmessage?.(delivery.message, delivery.extra);
33
+ else if (!closed && delivery.kind === "error")
34
+ callbacks.onerror?.(delivery.error);
35
+ }
36
+ catch (error) {
37
+ // Callback failure must not strand later responses or close waiters.
38
+ try {
39
+ callbacks.onerror?.(error instanceof Error ? error : new Error("Ordered transport callback failed."));
40
+ }
41
+ catch { }
42
+ }
43
+ finally {
44
+ schedule();
45
+ if (!queue.length && !scheduled)
46
+ for (const resolve of idle.splice(0))
47
+ resolve();
48
+ }
49
+ });
50
+ }
51
+ function enqueue(delivery) {
52
+ if (closed || closeQueued)
53
+ return;
54
+ if (delivery.kind === "close")
55
+ closeQueued = true;
56
+ queue.push(delivery);
57
+ schedule();
58
+ }
59
+ const start = async () => {
60
+ if (started)
61
+ throw new Error("Ordered transport already started; use a fresh wrapper per connection.");
62
+ if (closed || closeQueued)
63
+ throw new Error("Ordered transport is closed.");
64
+ started = true;
65
+ await transport.start();
66
+ };
67
+ const close = () => {
68
+ closing ??= (async () => {
69
+ await transport.close();
70
+ enqueue({ kind: "close" });
71
+ if (queue.length || scheduled)
72
+ await new Promise((resolve) => idle.push(resolve));
73
+ })();
74
+ return closing;
75
+ };
76
+ transport.onmessage = (message, extra) => enqueue({ kind: "message", message, extra });
77
+ transport.onerror = (error) => enqueue({ kind: "error", error });
78
+ transport.onclose = () => enqueue({ kind: "close" });
79
+ const bound = new Map();
80
+ return new Proxy(transport, {
81
+ get(target, key) {
82
+ if (key === "onmessage" || key === "onerror" || key === "onclose")
83
+ return callbacks[key];
84
+ if (key === "start")
85
+ return start;
86
+ if (key === "close")
87
+ return close;
88
+ const value = Reflect.get(target, key, target);
89
+ if (typeof value !== "function" || key === "constructor")
90
+ return value;
91
+ const existing = bound.get(key);
92
+ if (existing?.original === value)
93
+ return existing.value;
94
+ const fn = value.bind(target);
95
+ bound.set(key, { original: value, value: fn });
96
+ return fn;
97
+ },
98
+ set(target, key, value) {
99
+ if (key === "onmessage" || key === "onerror" || key === "onclose") {
100
+ Reflect.set(callbacks, key, value);
101
+ return true;
102
+ }
103
+ return Reflect.set(target, key, value, target);
104
+ },
105
+ });
106
+ }
@@ -0,0 +1,2 @@
1
+ import { RE2JS } from "re2js";
2
+ export declare function compilePattern(pattern: string): RE2JS;
@@ -0,0 +1,32 @@
1
+ // JSON Schema patterns use an intentionally small ASCII subset shared with ECMA-262.
2
+ // RE2JS supplies non-backtracking execution. Reject constructs with differing engine
3
+ // semantics (dot, negated/Unicode classes, shorthand whitespace, lookaround, backrefs).
4
+ import { RE2JS } from "re2js";
5
+ export function compilePattern(pattern) {
6
+ if (pattern.length > 1024)
7
+ throw new Error("pattern limit");
8
+ let inClass = false;
9
+ for (let i = 0; i < pattern.length; i++) {
10
+ const c = pattern[i];
11
+ if (c.charCodeAt(0) > 127)
12
+ throw new Error("non-ASCII pattern");
13
+ if (c === "\\") {
14
+ const n = pattern[++i];
15
+ if (!n || !"dwnrtf\\^$.*+?()[]{}|/-".includes(n))
16
+ throw new Error("unsupported escape");
17
+ continue;
18
+ }
19
+ if (c === "[") {
20
+ if (inClass || pattern[i + 1] === "^")
21
+ throw new Error("unsupported character class");
22
+ inClass = true;
23
+ }
24
+ else if (c === "]")
25
+ inClass = false;
26
+ else if (c === "." && !inClass)
27
+ throw new Error("unsupported wildcard");
28
+ }
29
+ // Syntax only: native regexes are never executed for contract validation.
30
+ new RegExp(pattern, "u");
31
+ return RE2JS.compile(pattern);
32
+ }
@@ -0,0 +1,41 @@
1
+ import type { LearningStore } from "./storage.js";
2
+ import { type ServerRecord } from "./store.js";
3
+ export interface PostgresStoreOptions {
4
+ connectionString: string;
5
+ /** Separate projects/tenants in one database. This is not a database authorization boundary. */
6
+ namespace?: string;
7
+ /** Auto-create schema v1 on first use. Set false for a pre-migrated restricted runtime role. */
8
+ migrate?: boolean;
9
+ timeoutMs?: number;
10
+ maxConnections?: number;
11
+ pollIntervalMs?: number;
12
+ }
13
+ /** PostgreSQL 14+. Owns its connection pool; call close() after all users stop.
14
+ * All updates and deletes acquire the same transaction-scoped advisory lock,
15
+ * including absent rows. A crashed connection releases its locks automatically.
16
+ * No callback retry after entry, and no file/cache fallback after an outage. */
17
+ export declare class PostgresShapeStore implements LearningStore {
18
+ #private;
19
+ readonly namespace: string;
20
+ private readyPromise?;
21
+ private closed;
22
+ private watchers;
23
+ private revisions;
24
+ private readonly timeout;
25
+ private readonly max;
26
+ private readonly pollInterval;
27
+ constructor(options: PostgresStoreOptions);
28
+ private failure;
29
+ private pool;
30
+ initialize(): Promise<void>;
31
+ private initializeSchema;
32
+ refresh(name: string): Promise<ServerRecord | undefined>;
33
+ load(name: string, version?: string): Promise<ServerRecord>;
34
+ has(name: string): Promise<boolean>;
35
+ list(): Promise<string[]>;
36
+ private transaction;
37
+ transact<T>(name: string, mutate: (record: ServerRecord) => T): Promise<T>;
38
+ remove(name: string): Promise<void>;
39
+ watch(name: string, onChange: () => void, onError?: () => void): () => void;
40
+ close(): Promise<void>;
41
+ }