toolsplice-core 0.0.1 → 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 (111) hide show
  1. package/README.md +26 -17
  2. package/dist/abortable.d.ts +6 -0
  3. package/dist/abortable.js +50 -0
  4. package/dist/adaptive-read.d.ts +50 -0
  5. package/dist/adaptive-read.js +780 -0
  6. package/dist/answer-wait.d.ts +7 -0
  7. package/dist/answer-wait.js +45 -0
  8. package/dist/cache-reads.d.ts +18 -0
  9. package/dist/cache-reads.js +89 -0
  10. package/dist/calibration-ledger.d.ts +37 -0
  11. package/dist/calibration-ledger.js +148 -0
  12. package/dist/calibration-marker.d.ts +4 -0
  13. package/dist/calibration-marker.js +77 -0
  14. package/dist/catalog-setup.d.ts +33 -0
  15. package/dist/catalog-setup.js +89 -0
  16. package/dist/catalog.d.ts +10 -0
  17. package/dist/catalog.js +42 -0
  18. package/dist/checkpoint-files.d.ts +15 -0
  19. package/dist/checkpoint-files.js +99 -0
  20. package/dist/coalesce-reads.d.ts +6 -0
  21. package/dist/coalesce-reads.js +33 -0
  22. package/dist/contract-caller.d.ts +2 -1
  23. package/dist/contract-caller.js +35 -16
  24. package/dist/contract-schema.d.ts +3 -1
  25. package/dist/contract-schema.js +34 -4
  26. package/dist/contracts.d.ts +1 -0
  27. package/dist/contracts.js +5 -1
  28. package/dist/core.d.ts +31 -1
  29. package/dist/core.js +27 -0
  30. package/dist/db-final-answer.d.ts +9 -0
  31. package/dist/db-final-answer.js +62 -0
  32. package/dist/define.d.ts +78 -0
  33. package/dist/define.js +14 -0
  34. package/dist/final-answer-stores.d.ts +71 -0
  35. package/dist/final-answer-stores.js +72 -0
  36. package/dist/final-answer.d.ts +32 -0
  37. package/dist/final-answer.js +104 -0
  38. package/dist/impact.d.ts +48 -0
  39. package/dist/impact.js +71 -0
  40. package/dist/local-tool.d.ts +18 -0
  41. package/dist/local-tool.js +32 -0
  42. package/dist/mcp-apps.d.ts +53 -0
  43. package/dist/mcp-apps.js +32 -0
  44. package/dist/mcp-event-delivery.d.ts +98 -0
  45. package/dist/mcp-event-delivery.js +211 -0
  46. package/dist/mcp-extensions.d.ts +46 -0
  47. package/dist/mcp-extensions.js +200 -0
  48. package/dist/mcp-peer.d.ts +45 -0
  49. package/dist/mcp-peer.js +207 -0
  50. package/dist/mcp-server-card.d.ts +21 -0
  51. package/dist/mcp-server-card.js +54 -0
  52. package/dist/page-checkpoint.d.ts +71 -0
  53. package/dist/page-checkpoint.js +286 -0
  54. package/dist/page-read-gate.d.ts +15 -0
  55. package/dist/page-read-gate.js +48 -0
  56. package/dist/pattern.d.ts +1 -0
  57. package/dist/pattern.js +27 -5
  58. package/dist/read-pages.d.ts +25 -0
  59. package/dist/read-pages.js +85 -0
  60. package/dist/read-policy.d.ts +6 -0
  61. package/dist/read-policy.js +16 -0
  62. package/dist/read-steps.d.ts +12 -0
  63. package/dist/read-steps.js +36 -0
  64. package/dist/result-session.d.ts +109 -0
  65. package/dist/result-session.js +620 -0
  66. package/dist/route-checkpoint.d.ts +3 -0
  67. package/dist/route-checkpoint.js +80 -0
  68. package/dist/route-evaluation.d.ts +141 -0
  69. package/dist/route-evaluation.js +329 -0
  70. package/dist/row-groups.d.ts +17 -0
  71. package/dist/row-groups.js +79 -0
  72. package/dist/row-query.d.ts +62 -0
  73. package/dist/row-query.js +172 -0
  74. package/dist/rules.d.ts +30 -0
  75. package/dist/rules.js +72 -0
  76. package/dist/run-diagnostics.d.ts +75 -0
  77. package/dist/run-diagnostics.js +212 -0
  78. package/dist/search-fetch.d.ts +50 -0
  79. package/dist/search-fetch.js +264 -0
  80. package/dist/skill-files.d.ts +9 -0
  81. package/dist/skill-files.js +49 -0
  82. package/dist/splice-diagnostics.d.ts +4 -0
  83. package/dist/splice-diagnostics.js +24 -16
  84. package/dist/splice-recording.d.ts +29 -2
  85. package/dist/splice-recording.js +22 -5
  86. package/dist/splice.d.ts +98 -1
  87. package/dist/splice.js +225 -27
  88. package/dist/sqlite-checkpoint-store.d.ts +5 -0
  89. package/dist/sqlite-checkpoint-store.js +91 -0
  90. package/dist/sqlite-checkpoint-worker.js +115 -0
  91. package/dist/test-difference.d.ts +13 -0
  92. package/dist/test-difference.js +42 -0
  93. package/dist/testing.d.ts +122 -0
  94. package/dist/testing.js +261 -0
  95. package/dist/text-pages.d.ts +24 -0
  96. package/dist/text-pages.js +36 -0
  97. package/dist/tool-discovery.d.ts +59 -0
  98. package/dist/tool-discovery.js +136 -0
  99. package/dist/unevaluated.d.ts +7 -0
  100. package/dist/unevaluated.js +156 -0
  101. package/dist/version.d.ts +1 -1
  102. package/dist/version.js +1 -1
  103. package/dist/workflow-json.js +1 -1
  104. package/integrations/ai.d.mts +36 -0
  105. package/integrations/ai.mjs +178 -0
  106. package/integrations/call-options.mjs +9 -0
  107. package/integrations/langchain.d.mts +31 -0
  108. package/integrations/langchain.mjs +114 -0
  109. package/integrations/managed.mjs +154 -0
  110. package/integrations/types.d.mts +13 -0
  111. package/package.json +30 -1
@@ -0,0 +1,80 @@
1
+ import { createHash } from "node:crypto";
2
+ import { mkdirSync } from "node:fs";
3
+ import { hostname } from "node:os";
4
+ import { join, resolve } from "node:path";
5
+ import { jsonFingerprint } from "./workflow-json.js";
6
+ import { CheckpointError, active, publish, read } from "./checkpoint-files.js";
7
+ export { CheckpointError, checkpointMessages } from "./checkpoint-files.js";
8
+ import { runWithLedger } from "./calibration-ledger.js";
9
+ export function openRouteCheckpoint(directory, descriptor, cases, retry) {
10
+ const dir = resolve(directory);
11
+ const hash = createHash("sha256").update(jsonFingerprint(descriptor));
12
+ for (const item of cases)
13
+ hash.update(jsonFingerprint(item));
14
+ const suite = hash.digest("hex");
15
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
16
+ const manifest = join(dir, "manifest.json");
17
+ const header = { format: "toolsplice-calibration", version: 1, suite };
18
+ if (!read(manifest))
19
+ publish(manifest, header);
20
+ const saved = read(manifest);
21
+ if (saved?.format !== header.format || saved.version !== 1)
22
+ throw new CheckpointError(44);
23
+ if (saved.suite !== suite)
24
+ throw new CheckpointError(41);
25
+ return async function checkpointTrial(index, run, validate) {
26
+ for (let attempt = 0;; attempt++) {
27
+ const slot = index + "-" + attempt;
28
+ const path = join(dir, slot + ".json");
29
+ const key = suite + "/" + slot;
30
+ const resultPath = join(dir, slot + ".result.json");
31
+ let record = read(path);
32
+ if (!record && publish(path, { key, state: "active", host: hostname(), pid: process.pid })) {
33
+ try {
34
+ const trial = await runWithLedger(dir, slot, key, run);
35
+ if (!publish(resultPath, { key, state: "graded", trial }))
36
+ throw new CheckpointError(44);
37
+ publish(path, { key, state: "done", trial }, true);
38
+ return trial;
39
+ }
40
+ catch (error) {
41
+ // A directory flush may fail after the completed record became visible.
42
+ if (read(path)?.state === "active")
43
+ publish(path, { key, state: "uncertain" }, true);
44
+ throw error;
45
+ }
46
+ }
47
+ record ??= read(path);
48
+ if (record?.key !== key)
49
+ throw new CheckpointError(44);
50
+ if (record.state === "done") {
51
+ if (!validate(record.trial))
52
+ throw new CheckpointError(44);
53
+ return record.trial;
54
+ }
55
+ if (record.state !== "active" && record.state !== "uncertain")
56
+ throw new CheckpointError(44);
57
+ const staged = read(resultPath);
58
+ if (staged) {
59
+ if (staged.key !== key || staged.state !== "graded" || !validate(staged.trial))
60
+ throw new CheckpointError(44);
61
+ publish(path, { key, state: "done", trial: staged.trial }, true);
62
+ return staged.trial;
63
+ }
64
+ // Another attempt may already have committed this trial after an explicit retry.
65
+ if (read(join(dir, index + "-" + (attempt + 1) + ".json")))
66
+ continue;
67
+ if (record.state === "active") {
68
+ if (active(record))
69
+ throw new CheckpointError(42);
70
+ // It may have committed between the first read and the process exit.
71
+ if (read(path)?.state !== "active" || read(resultPath)) {
72
+ attempt--;
73
+ continue;
74
+ }
75
+ }
76
+ if (!retry)
77
+ throw new CheckpointError(43);
78
+ }
79
+ };
80
+ }
@@ -0,0 +1,141 @@
1
+ export { readCalibrationLedger, startCalibrationCall, type CalibrationUsage } from "./calibration-ledger.js";
2
+ import type { RunDiagnostics } from "./run-diagnostics.js";
3
+ /** Derive a portable stamp from the model, prompts, tool catalog and settings supplied by the host. */
4
+ export declare function routeContext(identity: Record<string, unknown>): string;
5
+ export declare const toolRoutes: readonly ["native", "adaptive", "configured"];
6
+ export type ToolRoute = (typeof toolRoutes)[number];
7
+ export type RouteSplit = "fit" | "holdout";
8
+ export interface RouteTrial {
9
+ workload: string;
10
+ case: string;
11
+ repeat: number;
12
+ split: RouteSplit;
13
+ route: ToolRoute;
14
+ exact: boolean;
15
+ elapsedMs: number;
16
+ costUsd: number;
17
+ modelCalls: number;
18
+ }
19
+ export interface RouteLimits {
20
+ minPairs?: number;
21
+ minCases?: number;
22
+ minAccuracy?: number;
23
+ maxP95Ms?: number;
24
+ maxMeanCostUsd?: number;
25
+ minGain?: number;
26
+ }
27
+ export interface RouteEvidence {
28
+ format: "toolsplice-route-trials";
29
+ version: 1;
30
+ context: string;
31
+ trials: readonly RouteTrial[];
32
+ limits?: RouteLimits;
33
+ }
34
+ export interface RoutePolicy {
35
+ format: "toolsplice-route-policy";
36
+ version: 1;
37
+ context: string;
38
+ routes: {
39
+ workload: string;
40
+ route: ToolRoute;
41
+ }[];
42
+ }
43
+ export declare function evaluateRoutes(evidence: unknown): {
44
+ policy: RoutePolicy;
45
+ workloads: {
46
+ workload: string;
47
+ selected: "adaptive" | "configured" | "native";
48
+ fit: {
49
+ route: "adaptive" | "configured" | "native";
50
+ reasons: string[];
51
+ native: {
52
+ trials: number;
53
+ exact: number;
54
+ modelCalls: number;
55
+ meanCostUsd: number;
56
+ p95Ms: number;
57
+ };
58
+ measured: {
59
+ trials: number;
60
+ exact: number;
61
+ modelCalls: number;
62
+ meanCostUsd: number;
63
+ p95Ms: number;
64
+ };
65
+ }[];
66
+ holdout: {
67
+ route: "adaptive" | "configured" | "native";
68
+ reasons: string[];
69
+ native: {
70
+ trials: number;
71
+ exact: number;
72
+ modelCalls: number;
73
+ meanCostUsd: number;
74
+ p95Ms: number;
75
+ };
76
+ measured: {
77
+ trials: number;
78
+ exact: number;
79
+ modelCalls: number;
80
+ meanCostUsd: number;
81
+ p95Ms: number;
82
+ };
83
+ } | null;
84
+ }[];
85
+ };
86
+ /** Compile once at startup. Unknown workloads, stale contexts and invalid policies use native. */
87
+ export declare function prepareRoutePolicy(policy: unknown, context: string): (workload: string) => ToolRoute;
88
+ export declare function routeFor(policy: unknown, workload: string, context: string): ToolRoute;
89
+ /** Dispatch exactly one application callback. An unavailable route uses native. */
90
+ export declare function runRouted<T>(choose: (workload: string) => ToolRoute, workload: string, handlers: {
91
+ native: () => T | PromiseLike<T>;
92
+ adaptive?: () => T | PromiseLike<T>;
93
+ configured?: () => T | PromiseLike<T>;
94
+ }, diagnostics?: RunDiagnostics): Promise<Awaited<T>>;
95
+ export interface EvaluationCase<Input = unknown> {
96
+ id: string;
97
+ workload: string;
98
+ split: RouteSplit;
99
+ input: Input;
100
+ expected?: unknown;
101
+ }
102
+ export type EvaluationOutcome<Answer> = {
103
+ costUsd: number;
104
+ modelCalls: number;
105
+ } & ({
106
+ answer: Answer;
107
+ failed?: boolean;
108
+ } | {
109
+ failed: true;
110
+ answer?: never;
111
+ });
112
+ export interface EvaluationSuite<Input, Answer> {
113
+ context: string;
114
+ cases: readonly EvaluationCase<Input>[];
115
+ repeats?: number;
116
+ routes?: readonly ToolRoute[];
117
+ limits?: RouteLimits;
118
+ run(route: ToolRoute, item: Pick<EvaluationCase<Input>, "id" | "workload" | "input">, repeat: number): EvaluationOutcome<Answer> | PromiseLike<EvaluationOutcome<Answer>>;
119
+ grade(item: EvaluationCase<Input>, answer: Answer): boolean | PromiseLike<boolean>;
120
+ }
121
+ /** Count work and report under-sampled groups without invoking the driver or grader. */
122
+ export declare function planRouteEvaluation<Input, Answer>(suite: EvaluationSuite<Input, Answer>): {
123
+ context: string;
124
+ routes: any[];
125
+ repeats: number;
126
+ plannedTrials: number;
127
+ workloads: {
128
+ workload: string;
129
+ fitCases: number;
130
+ holdoutCases: number;
131
+ sharedInputsAcrossSplits: number;
132
+ fitPairs: number;
133
+ holdoutPairs: number;
134
+ meetsSampleMinimum: boolean;
135
+ }[];
136
+ };
137
+ /** Only route/case IDs, grades, timings and usage enter the portable receipt. */
138
+ export declare function collectRouteTrials<Input, Answer>(suite: EvaluationSuite<Input, Answer>, options?: {
139
+ checkpoint?: string;
140
+ retryIncomplete?: boolean;
141
+ }): Promise<RouteEvidence>;
@@ -0,0 +1,329 @@
1
+ /** Compare read-only tool routes on paired trials and independently held-out cases. */
2
+ import { copyJson, jsonFingerprint } from "./workflow-json.js";
3
+ export { readCalibrationLedger, startCalibrationCall } from "./calibration-ledger.js";
4
+ import { openRouteCheckpoint } from "./route-checkpoint.js";
5
+ /** Derive a portable stamp from the model, prompts, tool catalog and settings supplied by the host. */
6
+ export function routeContext(identity) {
7
+ if (identity === null ||
8
+ typeof identity !== "object" ||
9
+ Array.isArray(identity) ||
10
+ !Object.keys(identity).length)
11
+ throw new TypeError("A nonempty route context object is required.");
12
+ return "sha256:" + jsonFingerprint(identity);
13
+ }
14
+ export const toolRoutes = ["native", "adaptive", "configured"];
15
+ const isRecord = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
16
+ const isRoute = (v) => toolRoutes.some((r) => r === v);
17
+ const id = (v) => typeof v === "string" &&
18
+ /^[A-Za-z0-9][A-Za-z0-9._:/@+-]{0,191}$/.test(v) &&
19
+ !v.endsWith("\n");
20
+ const nonnegative = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0;
21
+ const uint = (v) => nonnegative(v) && Number.isSafeInteger(v);
22
+ function limits(value = {}) {
23
+ if (!isRecord(value) ||
24
+ Object.keys(value).some((k) => ![
25
+ "minPairs",
26
+ "minCases",
27
+ "minAccuracy",
28
+ "maxP95Ms",
29
+ "maxMeanCostUsd",
30
+ "minGain",
31
+ ].includes(k)))
32
+ throw new Error("Invalid route limits.");
33
+ const { minPairs = 5, minCases = 2, minAccuracy = 1, maxP95Ms = Number.MAX_VALUE, maxMeanCostUsd = Number.MAX_VALUE, minGain = 0.01, } = value;
34
+ if (!uint(minPairs) ||
35
+ minPairs < 1 ||
36
+ !uint(minCases) ||
37
+ minCases < 1 ||
38
+ !nonnegative(minAccuracy) ||
39
+ minAccuracy > 1 ||
40
+ !nonnegative(minGain) ||
41
+ minGain > 1 ||
42
+ !nonnegative(maxP95Ms) ||
43
+ !nonnegative(maxMeanCostUsd))
44
+ throw new Error("Invalid route limits.");
45
+ return { minPairs, minCases, minAccuracy, minGain, maxP95Ms, maxMeanCostUsd };
46
+ }
47
+ function validTrial(v) {
48
+ return (isRecord(v) &&
49
+ id(v.workload) &&
50
+ id(v.case) &&
51
+ uint(v.repeat) &&
52
+ (v.split === "fit" || v.split === "holdout") &&
53
+ isRoute(v.route) &&
54
+ typeof v.exact === "boolean" &&
55
+ nonnegative(v.elapsedMs) &&
56
+ nonnegative(v.costUsd) &&
57
+ uint(v.modelCalls));
58
+ }
59
+ function metrics(rows) {
60
+ const n = rows.length;
61
+ const times = rows.map((r) => r.elapsedMs).sort((a, b) => a - b);
62
+ const exact = rows.reduce((s, r) => s + Number(r.exact), 0);
63
+ const ordered = [...rows].sort((a, b) => a.case < b.case ? -1 : a.case > b.case ? 1 : a.repeat - b.repeat);
64
+ const cost = ordered.reduce((s, r) => s + r.costUsd, 0);
65
+ const modelCalls = rows.reduce((s, r) => s + r.modelCalls, 0);
66
+ if (!Number.isFinite(cost) || !Number.isSafeInteger(modelCalls))
67
+ throw new Error("Route measurement total is out of range.");
68
+ return {
69
+ trials: n,
70
+ exact,
71
+ modelCalls,
72
+ meanCostUsd: n ? cost / n : 0,
73
+ p95Ms: n ? times[Math.ceil(0.95 * n) - 1] : 0,
74
+ };
75
+ }
76
+ const key = (r) => JSON.stringify([r.case, r.repeat]);
77
+ function compare(rows, route, split, bounds) {
78
+ const baseline = rows.filter((r) => r.split === split && r.route === "native");
79
+ const candidate = rows.filter((r) => r.split === split && r.route === route);
80
+ const pairs = new Map(candidate.map((r) => [key(r), r]));
81
+ const reasons = [];
82
+ const expectedPairs = new Set(rows.filter((r) => r.split === split).map(key))
83
+ .size;
84
+ if (baseline.length !== expectedPairs ||
85
+ baseline.length !== candidate.length ||
86
+ baseline.some((r) => !pairs.has(key(r))))
87
+ reasons.push("unmatched-trials");
88
+ if (baseline.length < bounds.minPairs ||
89
+ new Set(baseline.map((r) => r.case)).size < bounds.minCases)
90
+ reasons.push("insufficient-evidence");
91
+ if (baseline.some((r) => r.exact && pairs.get(key(r))?.exact === false))
92
+ reasons.push("lost-correct-answer");
93
+ const native = metrics(baseline), measured = metrics(candidate);
94
+ if (!measured.exact || measured.exact / candidate.length < bounds.minAccuracy)
95
+ reasons.push("accuracy-floor");
96
+ if (measured.p95Ms > Math.min(native.p95Ms, bounds.maxP95Ms))
97
+ reasons.push("p95-latency");
98
+ // Relative tolerance only covers rounding when summing the same measured USD values.
99
+ const costCap = Math.min(native.meanCostUsd, bounds.maxMeanCostUsd);
100
+ if (measured.meanCostUsd >
101
+ costCap + Number.EPSILON * Math.abs(costCap) * Math.max(1, candidate.length))
102
+ reasons.push("cost");
103
+ const improves = (after, before) => after < before &&
104
+ before > 0 &&
105
+ (before - after) / before + Number.EPSILON >= bounds.minGain;
106
+ if (!(measured.exact > native.exact ||
107
+ improves(measured.p95Ms, native.p95Ms) ||
108
+ improves(measured.meanCostUsd, native.meanCostUsd)))
109
+ reasons.push("no-measured-gain");
110
+ return { route, reasons, native, measured };
111
+ }
112
+ export function evaluateRoutes(evidence) {
113
+ if (!isRecord(evidence) ||
114
+ evidence.format !== "toolsplice-route-trials" ||
115
+ evidence.version !== 1 ||
116
+ !id(evidence.context) ||
117
+ !Array.isArray(evidence.trials) ||
118
+ !evidence.trials.length ||
119
+ evidence.trials.length > 100000)
120
+ throw new Error("Expected a version 1 Toolsplice route-trial receipt with 1 to 100000 trials.");
121
+ const bounds = limits(evidence.limits);
122
+ const groups = new Map(), seen = new Set(), partitions = new Map();
123
+ for (const r of evidence.trials) {
124
+ if (!validTrial(r))
125
+ throw new Error("Invalid route trial.");
126
+ const item = JSON.stringify([r.workload, r.case]);
127
+ if (partitions.has(item) && partitions.get(item) !== r.split)
128
+ throw new Error("Fit and holdout cases must be disjoint within a workload.");
129
+ partitions.set(item, r.split);
130
+ const k = JSON.stringify([r.workload, r.case, r.repeat, r.route]);
131
+ if (seen.has(k))
132
+ throw new Error("Duplicate route trial.");
133
+ seen.add(k);
134
+ if (!groups.has(r.workload))
135
+ groups.set(r.workload, []);
136
+ groups.get(r.workload).push(r);
137
+ }
138
+ const policy = {
139
+ format: "toolsplice-route-policy",
140
+ version: 1,
141
+ context: evidence.context,
142
+ routes: [],
143
+ };
144
+ const workloads = [...groups.keys()].sort().map((workload) => {
145
+ const rows = groups.get(workload);
146
+ const fit = toolRoutes
147
+ .filter((r) => r !== "native" && rows.some((t) => t.route === r))
148
+ .map((r) => compare(rows, r, "fit", bounds));
149
+ // Select using fit only. A rejected winner cannot be replaced using holdout scores.
150
+ const winner = fit
151
+ .filter((r) => !r.reasons.length)
152
+ .sort((a, b) => b.measured.exact - a.measured.exact ||
153
+ a.measured.meanCostUsd - b.measured.meanCostUsd ||
154
+ a.measured.p95Ms - b.measured.p95Ms ||
155
+ a.measured.modelCalls - b.measured.modelCalls)[0];
156
+ const holdout = winner
157
+ ? compare(rows, winner.route, "holdout", bounds)
158
+ : null;
159
+ const selected = holdout && !holdout.reasons.length ? holdout.route : "native";
160
+ policy.routes.push({ workload, route: selected });
161
+ return { workload, selected, fit, holdout };
162
+ });
163
+ return { policy, workloads };
164
+ }
165
+ /** Compile once at startup. Unknown workloads, stale contexts and invalid policies use native. */
166
+ export function prepareRoutePolicy(policy, context) {
167
+ const fallback = () => "native";
168
+ if (!id(context) ||
169
+ !isRecord(policy) ||
170
+ policy.format !== "toolsplice-route-policy" ||
171
+ policy.version !== 1 ||
172
+ policy.context !== context ||
173
+ !Array.isArray(policy.routes) ||
174
+ policy.routes.length > 100000)
175
+ return fallback;
176
+ const routes = new Map();
177
+ for (const row of policy.routes) {
178
+ if (!isRecord(row) ||
179
+ !id(row.workload) ||
180
+ !isRoute(row.route) ||
181
+ routes.has(row.workload))
182
+ return fallback;
183
+ routes.set(row.workload, row.route);
184
+ }
185
+ return (workload) => routes.get(workload) ?? "native";
186
+ }
187
+ export function routeFor(policy, workload, context) {
188
+ return prepareRoutePolicy(policy, context)(workload);
189
+ }
190
+ /** Dispatch exactly one application callback. An unavailable route uses native. */
191
+ export async function runRouted(choose, workload, handlers, diagnostics) {
192
+ if (typeof handlers.native !== "function")
193
+ throw new TypeError("A native route handler is required.");
194
+ const candidate = choose(workload);
195
+ const selected = isRoute(candidate) &&
196
+ Object.hasOwn(handlers, candidate) &&
197
+ typeof handlers[candidate] === "function"
198
+ ? candidate
199
+ : "native";
200
+ const run = handlers[selected];
201
+ return diagnostics ? diagnostics.run(selected, run) : await run();
202
+ }
203
+ function prepareSuite(suite) {
204
+ const { context, cases, run, grade, repeats = 3, routes: provided = toolRoutes, } = suite;
205
+ const routes = Array.isArray(provided) ? [...provided] : provided;
206
+ const configuredLimits = suite.limits === undefined ? undefined : { ...suite.limits };
207
+ limits(suite.limits);
208
+ if (!id(context) ||
209
+ !Array.isArray(cases) ||
210
+ !cases.length ||
211
+ !uint(repeats) ||
212
+ repeats < 1 ||
213
+ !Array.isArray(routes) ||
214
+ !routes.includes("native") ||
215
+ routes.length < 2 ||
216
+ routes.some((r) => !isRoute(r)) ||
217
+ new Set(routes).size !== routes.length ||
218
+ cases.length * repeats * routes.length > 100000 ||
219
+ typeof run !== "function" ||
220
+ typeof grade !== "function")
221
+ throw new Error("Invalid evaluation suite.");
222
+ const seen = new Set();
223
+ const snapshots = cases.map((c) => copyJson(c));
224
+ for (const c of snapshots) {
225
+ if (!isRecord(c) ||
226
+ !id(c.id) ||
227
+ !id(c.workload) ||
228
+ !Object.hasOwn(c, "input") ||
229
+ (c.split !== "fit" && c.split !== "holdout") ||
230
+ seen.has(JSON.stringify([c.workload, c.id])))
231
+ throw new Error("Invalid or repeated evaluation case.");
232
+ seen.add(JSON.stringify([c.workload, c.id]));
233
+ }
234
+ return { context, snapshots, run, grade, repeats, routes, configuredLimits };
235
+ }
236
+ /** Count work and report under-sampled groups without invoking the driver or grader. */
237
+ export function planRouteEvaluation(suite) {
238
+ const { context, snapshots, repeats, routes, configuredLimits } = prepareSuite(suite);
239
+ const bounds = limits(configuredLimits);
240
+ const counts = new Map();
241
+ for (const item of snapshots) {
242
+ const group = counts.get(item.workload) ?? {
243
+ fit: 0,
244
+ holdout: 0,
245
+ fitInputs: new Set(),
246
+ holdoutInputs: new Set(),
247
+ };
248
+ group[item.split]++;
249
+ const inputs = item.split === "fit" ? group.fitInputs : group.holdoutInputs;
250
+ inputs.add(jsonFingerprint(item.input));
251
+ counts.set(item.workload, group);
252
+ }
253
+ const workloads = [...counts.keys()].sort().map((workload) => {
254
+ const { fit, holdout, fitInputs, holdoutInputs } = counts.get(workload);
255
+ return {
256
+ workload,
257
+ fitCases: fit,
258
+ holdoutCases: holdout,
259
+ sharedInputsAcrossSplits: [...holdoutInputs].filter((x) => fitInputs.has(x)).length,
260
+ fitPairs: fit * repeats,
261
+ holdoutPairs: holdout * repeats,
262
+ meetsSampleMinimum: Math.min(fit, holdout) >= bounds.minCases &&
263
+ Math.min(fit, holdout) * repeats >= bounds.minPairs,
264
+ };
265
+ });
266
+ return {
267
+ context,
268
+ routes,
269
+ repeats,
270
+ plannedTrials: snapshots.length * repeats * routes.length,
271
+ workloads,
272
+ };
273
+ }
274
+ /** Only route/case IDs, grades, timings and usage enter the portable receipt. */
275
+ export async function collectRouteTrials(suite, options = {}) {
276
+ const { context, snapshots, run, grade, repeats, routes, configuredLimits } = prepareSuite(suite);
277
+ if ((options.checkpoint !== undefined && (!options.checkpoint || typeof options.checkpoint !== "string")) ||
278
+ (options.retryIncomplete !== undefined && typeof options.retryIncomplete !== "boolean") ||
279
+ (options.retryIncomplete && !options.checkpoint))
280
+ throw new TypeError("Invalid checkpoint options.");
281
+ const checkpoint = options.checkpoint && openRouteCheckpoint(options.checkpoint, { context, repeats, routes, limits: configuredLimits ?? {} }, snapshots, options.retryIncomplete === true);
282
+ const trials = [];
283
+ for (let repeat = 0; repeat < repeats; repeat++)
284
+ for (const [i, c] of snapshots.entries()) {
285
+ for (let j = 0; j < routes.length; j++) {
286
+ const route = routes[(repeat + i + j) % routes.length];
287
+ const identity = { workload: c.workload, case: c.id, repeat, split: c.split, route };
288
+ const measure = async () => {
289
+ const submitted = {
290
+ id: c.id,
291
+ workload: c.workload,
292
+ input: structuredClone(c.input),
293
+ };
294
+ const start = performance.now();
295
+ const outcome = await run(route, submitted, repeat);
296
+ const elapsedMs = performance.now() - start;
297
+ if (!outcome ||
298
+ (!Object.hasOwn(outcome, "answer") && !outcome.failed) ||
299
+ !nonnegative(outcome.costUsd) ||
300
+ !uint(outcome.modelCalls) ||
301
+ (outcome.failed !== undefined && typeof outcome.failed !== "boolean"))
302
+ throw new Error("The driver must report measured cost and model calls for each trial.");
303
+ const exact = outcome.failed
304
+ ? false
305
+ : await grade(structuredClone(c), outcome.answer);
306
+ if (typeof exact !== "boolean")
307
+ throw new Error("The grader must return a boolean.");
308
+ return {
309
+ ...identity,
310
+ exact,
311
+ elapsedMs,
312
+ costUsd: outcome.costUsd,
313
+ modelCalls: outcome.modelCalls,
314
+ };
315
+ };
316
+ const matches = (row) => validTrial(row) &&
317
+ Object.keys(row).length === 9 && row.workload === identity.workload && row.case === identity.case &&
318
+ row.split === identity.split && row.repeat === repeat && row.route === route;
319
+ trials.push(checkpoint ? await checkpoint(trials.length, measure, matches) : await measure());
320
+ }
321
+ }
322
+ return {
323
+ format: "toolsplice-route-trials",
324
+ version: 1,
325
+ context,
326
+ ...(configuredLimits ? { limits: configuredLimits } : {}),
327
+ trials,
328
+ };
329
+ }
@@ -0,0 +1,17 @@
1
+ type Scalar = string | number | boolean | null;
2
+ export interface RowGrouping {
3
+ field: string;
4
+ bucket?: "utcDay";
5
+ top?: number;
6
+ ties?: "include" | "truncate";
7
+ }
8
+ export interface RowGroup {
9
+ key: Scalar;
10
+ count: number;
11
+ }
12
+ export declare function rowGroups(spec: RowGrouping): {
13
+ merge(key: Scalar, count: number): void;
14
+ append(row: Record<string, unknown>): void;
15
+ finish(): RowGroup[];
16
+ };
17
+ export {};
@@ -0,0 +1,79 @@
1
+ import { jsonObject } from "./workflow-json.js";
2
+ const timestamp = /^(\d{4}-\d{2}-\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d{1,9})?(Z|[+-]\d{2}:\d{2})$/;
3
+ function utcDay(value) {
4
+ let ms;
5
+ if (typeof value === "number" && Number.isSafeInteger(value))
6
+ ms = value;
7
+ else {
8
+ const parts = typeof value === "string" && timestamp.exec(value);
9
+ if (!parts ||
10
+ parts[0] !== value ||
11
+ parts[1].startsWith("0000") ||
12
+ +parts[2] > 23 ||
13
+ +parts[3] > 59 ||
14
+ +parts[4] > 59)
15
+ throw new TypeError("Expected an offset-qualified timestamp or integer Unix milliseconds.");
16
+ const date = new Date(parts[1] + "T00:00:00Z");
17
+ if (!Number.isFinite(date.getTime()) ||
18
+ date.toISOString().slice(0, 10) !== parts[1])
19
+ throw new TypeError("Invalid calendar date.");
20
+ ms = Date.parse(value);
21
+ }
22
+ if (!Number.isFinite(ms) || ms < -62135596800000 || ms > 253402300799999)
23
+ throw new RangeError("UTC year must be between 0001 and 9999.");
24
+ return new Date(ms).toISOString().slice(0, 10);
25
+ }
26
+ function rank(key) {
27
+ return key === null
28
+ ? 0
29
+ : typeof key === "boolean"
30
+ ? 1
31
+ : typeof key === "number"
32
+ ? 2
33
+ : 3;
34
+ }
35
+ function keyOrder(a, b) {
36
+ return (rank(a) - rank(b) ||
37
+ (a === b || a === null || b === null ? 0 : a < b ? -1 : 1));
38
+ }
39
+ export function rowGroups(spec) {
40
+ if (!jsonObject(spec) ||
41
+ typeof spec.field !== "string" ||
42
+ !spec.field.length ||
43
+ spec.field.length > 2048 ||
44
+ Object.keys(spec).some((k) => !["field", "bucket", "top", "ties"].includes(k)) ||
45
+ (spec.bucket !== undefined && spec.bucket !== "utcDay") ||
46
+ (spec.top !== undefined &&
47
+ (!Number.isSafeInteger(spec.top) || spec.top < 1)) ||
48
+ (spec.ties !== undefined &&
49
+ (spec.top === undefined || !["include", "truncate"].includes(spec.ties))))
50
+ throw new TypeError("Invalid groupBy specification.");
51
+ const counts = new Map();
52
+ return {
53
+ merge(key, count) {
54
+ counts.set(key, (counts.get(key) ?? 0) + count);
55
+ },
56
+ append(row) {
57
+ if (!Object.hasOwn(row, spec.field))
58
+ throw new TypeError("Grouping field missing from a source row.");
59
+ const key = spec.bucket ? utcDay(row[spec.field]) : row[spec.field];
60
+ if (!(key === null ||
61
+ typeof key === "boolean" ||
62
+ typeof key === "string" ||
63
+ (typeof key === "number" &&
64
+ Number.isFinite(key) &&
65
+ (!Number.isInteger(key) || Number.isSafeInteger(key)))))
66
+ throw new TypeError("Expected a precise JSON scalar group key.");
67
+ counts.set(key, (counts.get(key) ?? 0) + 1);
68
+ },
69
+ finish() {
70
+ const rows = Array.from(counts, ([key, count]) => ({ key, count })).sort((a, b) => b.count - a.count || keyOrder(a.key, b.key));
71
+ if (spec.top === undefined || spec.top >= rows.length)
72
+ return rows;
73
+ const boundary = rows[spec.top - 1].count;
74
+ return spec.ties === "truncate"
75
+ ? rows.slice(0, spec.top)
76
+ : rows.filter((r) => r.count >= boundary);
77
+ },
78
+ };
79
+ }