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.
- package/LICENSE +21 -0
- package/README.md +104 -2
- package/dist/abortable.d.ts +6 -0
- package/dist/abortable.js +50 -0
- package/dist/adaptive-read.d.ts +50 -0
- package/dist/adaptive-read.js +780 -0
- package/dist/answer-wait.d.ts +7 -0
- package/dist/answer-wait.js +45 -0
- package/dist/cache-reads.d.ts +18 -0
- package/dist/cache-reads.js +89 -0
- package/dist/calibration-ledger.d.ts +37 -0
- package/dist/calibration-ledger.js +148 -0
- package/dist/calibration-marker.d.ts +4 -0
- package/dist/calibration-marker.js +77 -0
- package/dist/catalog-setup.d.ts +33 -0
- package/dist/catalog-setup.js +89 -0
- package/dist/catalog.d.ts +10 -0
- package/dist/catalog.js +42 -0
- package/dist/checkpoint-files.d.ts +15 -0
- package/dist/checkpoint-files.js +99 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +1454 -0
- package/dist/coalesce-reads.d.ts +6 -0
- package/dist/coalesce-reads.js +33 -0
- package/dist/codegen.d.ts +44 -0
- package/dist/codegen.js +479 -0
- package/dist/contract-caller.d.ts +23 -0
- package/dist/contract-caller.js +326 -0
- package/dist/contract-corrections.d.ts +35 -0
- package/dist/contract-corrections.js +159 -0
- package/dist/contract-schema.d.ts +7 -0
- package/dist/contract-schema.js +156 -0
- package/dist/contracts.d.ts +72 -0
- package/dist/contracts.js +370 -0
- package/dist/core.d.ts +44 -0
- package/dist/core.js +43 -0
- package/dist/db-final-answer.d.ts +9 -0
- package/dist/db-final-answer.js +62 -0
- package/dist/define.d.ts +78 -0
- package/dist/define.js +14 -0
- package/dist/doctor.d.ts +22 -0
- package/dist/doctor.js +91 -0
- package/dist/drift.d.ts +23 -0
- package/dist/drift.js +111 -0
- package/dist/execution.d.ts +38 -0
- package/dist/execution.js +66 -0
- package/dist/extract.d.ts +34 -0
- package/dist/extract.js +73 -0
- package/dist/final-answer-stores.d.ts +71 -0
- package/dist/final-answer-stores.js +72 -0
- package/dist/final-answer.d.ts +32 -0
- package/dist/final-answer.js +104 -0
- package/dist/impact.d.ts +48 -0
- package/dist/impact.js +71 -0
- package/dist/index.d.ts +51 -0
- package/dist/index.js +47 -0
- package/dist/local-tool.d.ts +18 -0
- package/dist/local-tool.js +32 -0
- package/dist/mcp-apps.d.ts +53 -0
- package/dist/mcp-apps.js +32 -0
- package/dist/mcp-event-delivery.d.ts +98 -0
- package/dist/mcp-event-delivery.js +211 -0
- package/dist/mcp-extensions.d.ts +46 -0
- package/dist/mcp-extensions.js +200 -0
- package/dist/mcp-peer.d.ts +45 -0
- package/dist/mcp-peer.js +207 -0
- package/dist/mcp-server-card.d.ts +21 -0
- package/dist/mcp-server-card.js +54 -0
- package/dist/ordered-transport.d.ts +12 -0
- package/dist/ordered-transport.js +106 -0
- package/dist/page-checkpoint.d.ts +71 -0
- package/dist/page-checkpoint.js +286 -0
- package/dist/page-read-gate.d.ts +15 -0
- package/dist/page-read-gate.js +48 -0
- package/dist/pattern.d.ts +3 -0
- package/dist/pattern.js +54 -0
- package/dist/postgres.d.ts +41 -0
- package/dist/postgres.js +264 -0
- package/dist/probe.d.ts +29 -0
- package/dist/probe.js +121 -0
- package/dist/proxy.d.ts +40 -0
- package/dist/proxy.js +436 -0
- package/dist/read-pages.d.ts +25 -0
- package/dist/read-pages.js +85 -0
- package/dist/read-policy.d.ts +6 -0
- package/dist/read-policy.js +16 -0
- package/dist/read-steps.d.ts +12 -0
- package/dist/read-steps.js +36 -0
- package/dist/result-session.d.ts +109 -0
- package/dist/result-session.js +620 -0
- package/dist/route-checkpoint.d.ts +3 -0
- package/dist/route-checkpoint.js +80 -0
- package/dist/route-driver-cli.d.ts +3 -0
- package/dist/route-driver-cli.js +43 -0
- package/dist/route-evaluation.d.ts +141 -0
- package/dist/route-evaluation.js +329 -0
- package/dist/row-groups.d.ts +17 -0
- package/dist/row-groups.js +79 -0
- package/dist/row-query.d.ts +62 -0
- package/dist/row-query.js +172 -0
- package/dist/rules.d.ts +30 -0
- package/dist/rules.js +72 -0
- package/dist/run-diagnostics.d.ts +75 -0
- package/dist/run-diagnostics.js +212 -0
- package/dist/runtime.d.ts +6 -0
- package/dist/runtime.js +26 -0
- package/dist/schema.d.ts +17 -0
- package/dist/schema.js +299 -0
- package/dist/search-fetch.d.ts +50 -0
- package/dist/search-fetch.js +264 -0
- package/dist/shape.d.ts +91 -0
- package/dist/shape.js +499 -0
- package/dist/skill-files.d.ts +9 -0
- package/dist/skill-files.js +49 -0
- package/dist/splice-diagnostics.d.ts +44 -0
- package/dist/splice-diagnostics.js +88 -0
- package/dist/splice-measure.d.ts +33 -0
- package/dist/splice-measure.js +55 -0
- package/dist/splice-project.d.ts +125 -0
- package/dist/splice-project.js +348 -0
- package/dist/splice-recording.d.ts +132 -0
- package/dist/splice-recording.js +481 -0
- package/dist/splice.d.ts +181 -0
- package/dist/splice.js +1263 -0
- package/dist/sqlite-checkpoint-store.d.ts +5 -0
- package/dist/sqlite-checkpoint-store.js +91 -0
- package/dist/sqlite-checkpoint-worker.d.ts +1 -0
- package/dist/sqlite-checkpoint-worker.js +115 -0
- package/dist/storage.d.ts +17 -0
- package/dist/storage.js +1 -0
- package/dist/store.d.ts +151 -0
- package/dist/store.js +735 -0
- package/dist/test-difference.d.ts +13 -0
- package/dist/test-difference.js +42 -0
- package/dist/testing.d.ts +122 -0
- package/dist/testing.js +261 -0
- package/dist/text-pages.d.ts +24 -0
- package/dist/text-pages.js +36 -0
- package/dist/tool-discovery.d.ts +59 -0
- package/dist/tool-discovery.js +136 -0
- package/dist/unevaluated.d.ts +7 -0
- package/dist/unevaluated.js +156 -0
- package/dist/v2.d.ts +49 -0
- package/dist/v2.js +413 -0
- package/dist/validate-output.d.ts +3 -0
- package/dist/validate-output.js +73 -0
- package/dist/version.d.ts +1 -0
- package/dist/version.js +1 -0
- package/dist/workflow-json.d.ts +8 -0
- package/dist/workflow-json.js +74 -0
- package/docs/AGENT-FRAMEWORKS.md +431 -0
- package/docs/BENCHMARKS.md +43 -0
- package/docs/INTEGRATION-QUICKSTART.md +859 -0
- package/docs/LEARNING-AND-STORAGE.md +393 -0
- package/docs/MCP.md +204 -0
- package/docs/PROJECTS-AND-UPGRADES.md +173 -0
- package/docs/PYTHON-REFERENCE.md +348 -0
- package/docs/PYTHON.md +120 -0
- package/docs/RECORDING-AND-CORRECTIONS.md +205 -0
- package/docs/TESTING.md +259 -0
- package/examples/mcp-app/build.mjs +11 -0
- package/examples/mcp-app/view.mjs +22 -0
- package/examples/quickstart.mjs +43 -0
- package/examples/route-driver.mjs +67 -0
- package/integrations/ai.d.mts +36 -0
- package/integrations/ai.mjs +178 -0
- package/integrations/call-options.mjs +9 -0
- package/integrations/langchain.d.mts +31 -0
- package/integrations/langchain.mjs +114 -0
- package/integrations/managed.mjs +154 -0
- package/integrations/types.d.mts +13 -0
- package/package.json +139 -4
|
@@ -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,43 @@
|
|
|
1
|
+
/** The CLI keeps application and framework logging off its report stream. */
|
|
2
|
+
import { fork } from "node:child_process";
|
|
3
|
+
import { realpathSync } from "node:fs";
|
|
4
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
5
|
+
import { collectRouteTrials, planRouteEvaluation } from "./route-evaluation.js";
|
|
6
|
+
import { CheckpointError, checkpointMessages } from "./route-checkpoint.js";
|
|
7
|
+
const filename = fileURLToPath(import.meta.url);
|
|
8
|
+
const failure = "Evaluation stopped. Check the driver's imports, run, measured usage and grade callbacks.";
|
|
9
|
+
export async function executeRouteDriver(driver, mode, checkpoint, retry = false) {
|
|
10
|
+
const path = realpathSync(driver);
|
|
11
|
+
return new Promise((resolve, reject) => {
|
|
12
|
+
const child = fork(filename, ["route-driver", path, mode, checkpoint ?? "", retry ? "yes" : "no"], {
|
|
13
|
+
stdio: ["inherit", 2, 2, "ipc"],
|
|
14
|
+
});
|
|
15
|
+
let report;
|
|
16
|
+
child.once("message", (value) => {
|
|
17
|
+
report = value;
|
|
18
|
+
});
|
|
19
|
+
child.once("error", () => reject(new Error(failure)));
|
|
20
|
+
child.once("close", (code) => {
|
|
21
|
+
if (code === 0 && report !== undefined)
|
|
22
|
+
resolve(report);
|
|
23
|
+
else
|
|
24
|
+
reject(new Error(checkpointMessages[code] ?? failure));
|
|
25
|
+
});
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
if (process.send &&
|
|
29
|
+
process.argv[1] === filename &&
|
|
30
|
+
process.argv[2] === "route-driver") {
|
|
31
|
+
// The parent going away must also stop any active driver.
|
|
32
|
+
process.once("disconnect", () => process.exit(1));
|
|
33
|
+
try {
|
|
34
|
+
const { default: suite } = await import(pathToFileURL(process.argv[3]).href);
|
|
35
|
+
const result = process.argv[4] === "plan"
|
|
36
|
+
? planRouteEvaluation(suite)
|
|
37
|
+
: await collectRouteTrials(suite, { checkpoint: process.argv[5] || undefined, retryIncomplete: process.argv[6] === "yes" });
|
|
38
|
+
process.send(result, (error) => process.exit(error ? 1 : 0));
|
|
39
|
+
}
|
|
40
|
+
catch (error) {
|
|
41
|
+
process.exit(error instanceof CheckpointError ? error.code : 1);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
@@ -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 {};
|