opencode-model-router 2.8.0 → 2.9.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.
- package/CHANGELOG.md +372 -0
- package/README.md +22 -2
- package/package.json +5 -1
- package/src/commands/output.ts +23 -1
- package/src/compat/background.ts +2439 -0
- package/src/compat/child-session.ts +6 -0
- package/src/compat/turn-state.ts +215 -0
- package/src/compat/v2-client.ts +136 -17
- package/src/compat/v2-hooks.ts +2656 -114
- package/src/compat/v2-observations.ts +328 -0
- package/src/executor/capacity.ts +362 -0
- package/src/executor/child-guards.ts +40 -0
- package/src/executor/command.ts +265 -0
- package/src/executor/compile/edges.ts +809 -0
- package/src/executor/compile/estimate.ts +158 -0
- package/src/executor/compile/footprint.ts +829 -0
- package/src/executor/compile/index.ts +1080 -0
- package/src/executor/compile/parse.ts +1492 -0
- package/src/executor/compile/residue.ts +706 -0
- package/src/executor/compile/validate.ts +280 -0
- package/src/executor/create.ts +672 -0
- package/src/executor/expand.ts +551 -0
- package/src/executor/git.ts +1214 -0
- package/src/executor/host-preamble.ts +17 -0
- package/src/executor/instructions.ts +35 -0
- package/src/executor/integrate/bisect.ts +73 -0
- package/src/executor/integrate/checks.ts +1086 -0
- package/src/executor/integrate/land.ts +177 -0
- package/src/executor/integrate/phase-suite.ts +407 -0
- package/src/executor/integrate/queue.ts +3083 -0
- package/src/executor/integrate/run-resolver.ts +19 -0
- package/src/executor/launch.ts +652 -0
- package/src/executor/ledger.ts +2208 -0
- package/src/executor/observations.ts +212 -0
- package/src/executor/paths.ts +159 -0
- package/src/executor/platform.ts +39 -0
- package/src/executor/process-identity.ts +19 -0
- package/src/executor/qa-loop.ts +470 -0
- package/src/executor/recovery.ts +403 -0
- package/src/executor/runtime.ts +6233 -0
- package/src/executor/schedule.ts +246 -0
- package/src/executor/slots/env.ts +145 -0
- package/src/executor/slots/pool.ts +1564 -0
- package/src/executor/slots/provision.ts +853 -0
- package/src/executor/tool.ts +534 -0
- package/src/executor/types.ts +2064 -0
- package/src/executor/unattended.ts +488 -0
- package/src/guard/store.ts +3 -1
- package/src/index.ts +1498 -288
- package/src/router/config.ts +776 -25
- package/src/router/git-tools.ts +106 -15
- package/src/router/leases.ts +1469 -0
- package/src/router/logger.ts +44 -32
- package/src/router/protocol.ts +40 -10
- package/src/router/role-agents.ts +224 -17
- package/src/router/roles-config.ts +10 -1
- package/src/router/roles.ts +1 -1
- package/src/router/run-tools.ts +56 -4
- package/src/router/tool-paths.ts +308 -0
- package/src/router/work-roots.ts +86 -0
- package/src/routing/advisor/findings.ts +25 -5
- package/src/routing/classify/index.ts +7 -1
- package/src/routing/classify/rules.ts +11 -0
- package/src/routing/commands/stats.ts +2 -2
- package/src/routing/outcomes/durations.ts +225 -0
- package/src/routing/outcomes/index.ts +59 -2
- package/src/routing/outcomes/persist.ts +409 -0
- package/src/routing/outcomes/stats.ts +170 -11
- package/src/routing/outcomes/timings.ts +836 -0
- package/src/routing/outcomes/types.ts +98 -0
- package/src/routing/roles/approvals.ts +86 -5
- package/src/routing/roles/binding.ts +99 -9
- package/src/routing/roles/orphans.ts +68 -0
- package/src/routing/roles/policy.ts +21 -3
- package/src/routing/roles/work-root.ts +3 -1
- package/src/routing/wire/dispatch.ts +86 -12
- package/src/routing/wire/hint.ts +56 -8
- package/src/v2.ts +94 -49
- package/src/verify/branch.ts +8 -2
- package/src/verify/canonical-path.ts +35 -0
- package/src/verify/deterministic.ts +38 -9
- package/src/verify/dispatch.ts +64 -28
- package/src/verify/exec.ts +52 -9
- package/src/verify/pending.ts +1691 -10
- package/src/verify/perimeter.ts +12 -6
- package/src/verify/plan-task.ts +729 -0
- package/src/verify/reference.ts +216 -3
- package/src/verify/tree.ts +30 -13
- package/src/verify/types.ts +9 -2
- package/src/verify/wiring.ts +290 -31
- package/tiers.json +5 -5
|
@@ -0,0 +1,328 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Read-only v2 diagnostics. No global instance, config key, host call or v1 activation.
|
|
3
|
+
* The only production creator is v2.ts. Writers receive detached JSON, never live router objects.
|
|
4
|
+
* Recording only snapshots/enqueues; bounded batches drain on setImmediate, never in a microtask.
|
|
5
|
+
* Explicit flush/close are synchronous lifecycle barriers, not hot-path operations.
|
|
6
|
+
*
|
|
7
|
+
* Wire format v1: {v, stream, seq, at, family, ...payload}. Families are native-args,
|
|
8
|
+
* completion-effect, scheduler and service. A final {v, stream, seq, at, kind:"end", ...counts}
|
|
9
|
+
* seals the stream. Consumers MUST require contiguous seq from 1, an end record, and
|
|
10
|
+
* dropped=failed=0; absence, overflow, serialization faults and writer faults are not evidence.
|
|
11
|
+
*
|
|
12
|
+
* Native arguments are own-property fingerprints, not text: {type, digest} per field,
|
|
13
|
+
* with background {present, type, value?} separately (value is ONLY a boolean).
|
|
14
|
+
* Digests are stream-local HMAC-SHA256 of canonical, type-tagged values. Thus prompt,
|
|
15
|
+
* description, paths, arbitrary extension values and credentials never leave the process,
|
|
16
|
+
* but equality and key presence (including own undefined) remain testable. Unknown keys
|
|
17
|
+
* are HMAC'd too. No HMAC key is persisted. Unsupported/accessor/overlarge values drop
|
|
18
|
+
* the event, never inspect a getter or change the operation.
|
|
19
|
+
*
|
|
20
|
+
* Smoke: set MODEL_ROUTER_V2_OBSERVATIONS to an existing diagnostic directory before
|
|
21
|
+
* v2 setup. Collect <pid>-<file-id>.jsonl after adapter disposal. Each setup has its own
|
|
22
|
+
* stream (do not combine seq across streams). No directory creation and no writes off.
|
|
23
|
+
* `checkV2ObservationStream` implements that collection check. Shared timing recorders
|
|
24
|
+
* write each invocation to ONE live holder's stream; collect ALL files for the run.
|
|
25
|
+
*
|
|
26
|
+
* Completion payload: {effect, source, parentSessionID, callID, childSessionID,
|
|
27
|
+
* handle?, outcome?}. The attempt key is the three identity fields, NOT child alone.
|
|
28
|
+
* Count rows per effect AND source: background-delta, deferred-change, required-change
|
|
29
|
+
* and plan-task-change are distinct capture invocations. Plan-task captures (including
|
|
30
|
+
* restart fallback) use the attempt's parent, retained callID (or plan verification id
|
|
31
|
+
* when absent) and childSessionID. Delivery sources distinguish foreground-result, completed-provider,
|
|
32
|
+
* held-synthetic and unheld-synthetic (every retry counts). Rows precede invocations,
|
|
33
|
+
* including failed ones; they do not assert successful persistence/delivery.
|
|
34
|
+
*
|
|
35
|
+
* Scheduler payload: {planId,parentSessionID,action,state}. Ledger/attach state is
|
|
36
|
+
* {ledgerSeq,status,maxParallel,tasks:[{id,state,kind,phase,p50,slot,attempts:[{n,callID,
|
|
37
|
+
* childSessionID,outcome}]}],edges:[{from,to}],phases:[{id,gate,paused}],
|
|
38
|
+
* writeConflicts:[[taskId,taskId]]}. A graph >256 tasks invalidates the stream, not a
|
|
39
|
+
* silently truncated snapshot. A ledger graph row follows every nonempty committed batch,
|
|
40
|
+
* including metric-only and collaborators' batches, at the actual committed swap before
|
|
41
|
+
* any subsequent await. Empty appends emit no graph row.
|
|
42
|
+
* Runtime state is {clockMs,ledgerSeq,orchIdle,passive,recovering,disposed,latch,
|
|
43
|
+
* inFlight:[taskId],tokens:["task#attempt"],detail}. Actions/detail:
|
|
44
|
+
* - route {taskId,provider,heavy}; route-unavailable {taskId}
|
|
45
|
+
* - capacity-free {provider,heavy,free}; capacity-reserve {taskId,attempt,provider,
|
|
46
|
+
* heavy,token,force}; capacity-release {taskId,attempt,token,result}
|
|
47
|
+
* - lease-eligibility {writers:[taskId],holder:null|{planId,taskId}}
|
|
48
|
+
* - launch-gate {ok,ready:[taskId]} or {taskId,attempt,ok}
|
|
49
|
+
* - launch-prepare {taskId,attempt}; launch {taskId,attempt,callID,provider,heavy}
|
|
50
|
+
* - launch-step-end {taskId,attempt,result}; orchestrator {event}
|
|
51
|
+
* - runtime-attach, activation, activation-end, promote, schedule, abort, dispose,
|
|
52
|
+
* detach, lease-released-notification: detail=null.
|
|
53
|
+
* Other raw states: capacity-init {maxParallel,providers:[{provider,limit,holdUntilMs,
|
|
54
|
+
* lastSignalAtMs,pausedUntilMs}]}; provider {provider,change,from,to,until};
|
|
55
|
+
* lease-acquire {taskRef,ok}; lease-release {taskRef}.
|
|
56
|
+
* Service execution/preparation/wait pairs are specified in src/executor/observations.ts.
|
|
57
|
+
* Physical-slot events are specified in src/executor/observations.ts. Neither
|
|
58
|
+
* task.slot=null nor provider/write-lease release implies physical pool availability.
|
|
59
|
+
* Provider labels are stream-local keyed tokens, never configuration text. These
|
|
60
|
+
* observations never call updateIdle or query a controller/host just for diagnostics.
|
|
61
|
+
* Unqueried route/lease/gate facts are UNKNOWN, not eligible. Reconstruct from the raw
|
|
62
|
+
* graph + control transitions + original query results; do not use the ready list as
|
|
63
|
+
* the oracle. `at` is epoch ms at observation entry; scheduler clockMs is the runtime clock.
|
|
64
|
+
*/
|
|
65
|
+
import { createHmac, randomBytes, randomUUID } from "node:crypto";
|
|
66
|
+
import { closeSync, openSync, writeSync } from "node:fs";
|
|
67
|
+
import { join } from "node:path";
|
|
68
|
+
|
|
69
|
+
export const OBSERVATION_MAX_EVENTS = 50_000;
|
|
70
|
+
export const OBSERVATION_MAX_BYTES = 16 * 1024 * 1024;
|
|
71
|
+
export const OBSERVATION_MAX_ROW_BYTES = 64 * 1024;
|
|
72
|
+
// Room for a UUID, all numeric counters/timestamp (even at their longest JSON spelling), and framing.
|
|
73
|
+
const SEAL_RESERVE_BYTES = 512;
|
|
74
|
+
const DRAIN_MAX_ROWS = 64;
|
|
75
|
+
|
|
76
|
+
export interface ArgumentFingerprint { type: string; digest: string }
|
|
77
|
+
export interface ArgumentObservation {
|
|
78
|
+
fields: Record<string, ArgumentFingerprint>;
|
|
79
|
+
background: { present: boolean; type: string; value?: boolean };
|
|
80
|
+
}
|
|
81
|
+
export interface CompletionIdentity {
|
|
82
|
+
parentSessionID: string;
|
|
83
|
+
callID: string;
|
|
84
|
+
childSessionID: string | null;
|
|
85
|
+
}
|
|
86
|
+
export type CompletionEffect = "change-set-capture" | "finish-dispatch" | "deferred-register"
|
|
87
|
+
| "verification-enqueue" | "verification-settle" | "annotation-delivery" | "timing-row-write";
|
|
88
|
+
type Scalar = string | number | boolean | null;
|
|
89
|
+
export type ObservationValue = Scalar | readonly ObservationValue[] | { readonly [key: string]: ObservationValue };
|
|
90
|
+
export interface ServiceIdentity {
|
|
91
|
+
planId: string;
|
|
92
|
+
taskId: string | null;
|
|
93
|
+
attempt: number | null;
|
|
94
|
+
phaseId: string | null;
|
|
95
|
+
entryId: string | null;
|
|
96
|
+
taskIds: readonly string[];
|
|
97
|
+
component: "verify" | "rebase" | "checks" | "fast-forward" | "phase-suite";
|
|
98
|
+
candidate: string | null;
|
|
99
|
+
}
|
|
100
|
+
export type ServiceSpanKind = "service" | "service-prep" | "service-wait" | "service-unattributed";
|
|
101
|
+
export type ServiceObservationData = ServiceIdentity & {
|
|
102
|
+
family: "service"; spanKind: ServiceSpanKind; operationId: string; stage: string;
|
|
103
|
+
action: "start" | "end"; clockMs: number; durationMs: number; result: string | null;
|
|
104
|
+
};
|
|
105
|
+
export type ObservationData =
|
|
106
|
+
| { family: "native-args"; callID: string; sessionID: string; before: ArgumentObservation; after: ArgumentObservation;
|
|
107
|
+
backgroundDecision: boolean | null }
|
|
108
|
+
| ({ family: "completion-effect"; effect: CompletionEffect; source: string; handle?: string; outcome?: string } & CompletionIdentity)
|
|
109
|
+
| { family: "scheduler"; planId: string; parentSessionID: string; action: string; state: ObservationValue }
|
|
110
|
+
| ServiceObservationData;
|
|
111
|
+
export type ObservationRecord = ObservationData & { v: 1; stream: string; seq: number; at: number };
|
|
112
|
+
export interface ObservationCounts { attempted: number; written: number; dropped: number; failed: number }
|
|
113
|
+
export interface V2Observations {
|
|
114
|
+
record(make: (args: (value: unknown) => ArgumentObservation) => ObservationData): void;
|
|
115
|
+
counts(): Readonly<ObservationCounts>;
|
|
116
|
+
/** Synchronously drain without sealing. For explicit lifecycle/test barriers only, never routing. */
|
|
117
|
+
flush(): void;
|
|
118
|
+
close(): void;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
interface PendingRow { line: string; next?: PendingRow }
|
|
122
|
+
|
|
123
|
+
const ARG_KEYS = new Set(["prompt", "description", "agent", "subagent_type", "sessionID", "task_id", "model", "background",
|
|
124
|
+
"cwd", "workdir", "workRoot", "variant", "temperature", "maxTokens"]);
|
|
125
|
+
|
|
126
|
+
/** No getters/toJSON, bounded traversal, and explicit type tags (undefined is not absence). */
|
|
127
|
+
function canonical(value: unknown): string {
|
|
128
|
+
let nodes = 0;
|
|
129
|
+
let bytes = 0;
|
|
130
|
+
const walk = (v: unknown, depth: number): unknown => {
|
|
131
|
+
if (++nodes > 8192 || depth > 24) throw new Error("observation value bound");
|
|
132
|
+
if (v === null) return ["null"];
|
|
133
|
+
if (typeof v === "string") {
|
|
134
|
+
bytes += Buffer.byteLength(v);
|
|
135
|
+
if (bytes > 2 * 1024 * 1024) throw new Error("observation text bound");
|
|
136
|
+
return ["string", v];
|
|
137
|
+
}
|
|
138
|
+
if (typeof v === "undefined") return ["undefined"];
|
|
139
|
+
if (typeof v === "boolean") return ["boolean", v];
|
|
140
|
+
if (typeof v === "number") return ["number", Object.is(v, -0) ? "-0" : String(v)];
|
|
141
|
+
if (typeof v !== "object" || Object.getOwnPropertySymbols(v).length > 0) throw new Error("unsupported observation value");
|
|
142
|
+
const proto: unknown = Object.getPrototypeOf(v);
|
|
143
|
+
if (!Array.isArray(v) && proto !== Object.prototype && proto !== null) throw new Error("unsupported observation object");
|
|
144
|
+
const entries = Object.entries(Object.getOwnPropertyDescriptors(v)).sort(([a], [b]) => a.localeCompare(b));
|
|
145
|
+
return [Array.isArray(v) ? "array" : "object", entries.map(([k, d]) => {
|
|
146
|
+
bytes += Buffer.byteLength(k);
|
|
147
|
+
if (bytes > 2 * 1024 * 1024) throw new Error("observation key bound");
|
|
148
|
+
if (!("value" in d)) throw new Error("observation accessor");
|
|
149
|
+
return [k, walk(d.value, depth + 1)];
|
|
150
|
+
})];
|
|
151
|
+
};
|
|
152
|
+
return JSON.stringify(walk(value, 0));
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export function createV2Observations(options: {
|
|
156
|
+
/** Detached JSONL only; called by the deferred drain or explicit flush/close, never record. Faults are counted. */
|
|
157
|
+
write(line: string): void;
|
|
158
|
+
now?: () => number;
|
|
159
|
+
maxEvents?: number;
|
|
160
|
+
/** Includes the seal; data rows reserve seal space. A cap too small for the seal leaves a failed, incomplete stream. */
|
|
161
|
+
maxBytes?: number;
|
|
162
|
+
}): V2Observations {
|
|
163
|
+
const stream = randomUUID();
|
|
164
|
+
const key = randomBytes(32);
|
|
165
|
+
const digest = (v: unknown): string => createHmac("sha256", key).update(canonical(v)).digest("hex");
|
|
166
|
+
const args = (value: unknown): ArgumentObservation => {
|
|
167
|
+
if (value === null || typeof value !== "object") throw new Error("non-object arguments");
|
|
168
|
+
canonical(value); // Bound the ENTIRE argument bag, not each field separately.
|
|
169
|
+
const fields: Record<string, ArgumentFingerprint> = Object.create(null);
|
|
170
|
+
const descriptors = Object.getOwnPropertyDescriptors(value);
|
|
171
|
+
for (const [name, d] of Object.entries(descriptors)) {
|
|
172
|
+
if (!("value" in d)) throw new Error("argument accessor");
|
|
173
|
+
fields[ARG_KEYS.has(name) ? name : `key:${digest(name)}`] = { type: d.value === null ? "null" : typeof d.value, digest: digest(d.value) };
|
|
174
|
+
}
|
|
175
|
+
const bg = descriptors.background;
|
|
176
|
+
return { fields, background: { present: bg !== undefined, type: bg === undefined ? "absent" : typeof bg.value,
|
|
177
|
+
...(typeof bg?.value === "boolean" ? { value: bg.value } : {}) } };
|
|
178
|
+
};
|
|
179
|
+
const counts: ObservationCounts = { attempted: 0, written: 0, dropped: 0, failed: 0 };
|
|
180
|
+
const bound = (n: number | undefined, max: number): number => n !== undefined && Number.isFinite(n) ? Math.max(0, Math.min(max, Math.floor(n))) : max;
|
|
181
|
+
const maxEvents = bound(options.maxEvents, OBSERVATION_MAX_EVENTS);
|
|
182
|
+
const maxBytes = bound(options.maxBytes, OBSERVATION_MAX_BYTES);
|
|
183
|
+
const dataBytes = Math.max(0, maxBytes - SEAL_RESERVE_BYTES);
|
|
184
|
+
let bytes = 0;
|
|
185
|
+
let closed = false;
|
|
186
|
+
let recording = false;
|
|
187
|
+
let head: PendingRow | undefined;
|
|
188
|
+
let tail: PendingRow | undefined;
|
|
189
|
+
let scheduled: ReturnType<typeof setImmediate> | undefined;
|
|
190
|
+
const stamp = (): number => options.now?.() ?? Date.now();
|
|
191
|
+
const drain = (limit: number): void => {
|
|
192
|
+
for (let n = 0; head !== undefined && n < limit; n++) {
|
|
193
|
+
const row = head;
|
|
194
|
+
head = row.next;
|
|
195
|
+
if (head === undefined) tail = undefined;
|
|
196
|
+
try { options.write(row.line); counts.written++; }
|
|
197
|
+
catch { counts.failed++; }
|
|
198
|
+
}
|
|
199
|
+
};
|
|
200
|
+
const schedule = (): void => {
|
|
201
|
+
if (scheduled !== undefined || closed || head === undefined) return;
|
|
202
|
+
scheduled = setImmediate(() => {
|
|
203
|
+
scheduled = undefined;
|
|
204
|
+
drain(DRAIN_MAX_ROWS);
|
|
205
|
+
schedule();
|
|
206
|
+
});
|
|
207
|
+
scheduled.unref();
|
|
208
|
+
};
|
|
209
|
+
const flush = (): void => {
|
|
210
|
+
if (scheduled !== undefined) clearImmediate(scheduled);
|
|
211
|
+
scheduled = undefined;
|
|
212
|
+
drain(Infinity);
|
|
213
|
+
};
|
|
214
|
+
return {
|
|
215
|
+
record(make) {
|
|
216
|
+
if (closed) return;
|
|
217
|
+
const seq = ++counts.attempted;
|
|
218
|
+
if (recording || seq > maxEvents || bytes >= dataBytes) { counts.dropped++; return; }
|
|
219
|
+
recording = true;
|
|
220
|
+
try {
|
|
221
|
+
const at = stamp();
|
|
222
|
+
const line = JSON.stringify({ ...make(args), v: 1, stream, seq, at }, (name, value: unknown) =>
|
|
223
|
+
name === "provider" && typeof value === "string" ? `provider:${digest(value)}` : value) + "\n";
|
|
224
|
+
const size = Buffer.byteLength(line);
|
|
225
|
+
if (size > OBSERVATION_MAX_ROW_BYTES || bytes + size > dataBytes) { counts.dropped++; return; }
|
|
226
|
+
// Charge failed writes too: even a writer that writes then throws cannot exceed the byte bound.
|
|
227
|
+
bytes += size;
|
|
228
|
+
// Only detached strings enter this event/byte-bounded queue. Link/unlink are O(1), with no array shifts.
|
|
229
|
+
const row: PendingRow = { line };
|
|
230
|
+
if (tail === undefined) head = row;
|
|
231
|
+
else tail.next = row;
|
|
232
|
+
tail = row;
|
|
233
|
+
schedule();
|
|
234
|
+
} catch { counts.failed++; }
|
|
235
|
+
finally { recording = false; }
|
|
236
|
+
},
|
|
237
|
+
counts: () => ({ ...counts }),
|
|
238
|
+
flush,
|
|
239
|
+
close() {
|
|
240
|
+
if (closed) return;
|
|
241
|
+
closed = true;
|
|
242
|
+
flush(); // Every accepted row (including failed writes) is accounted for before sealing.
|
|
243
|
+
try {
|
|
244
|
+
const line = JSON.stringify({ v: 1, stream, seq: counts.attempted + 1, at: stamp(), kind: "end", ...counts }) + "\n";
|
|
245
|
+
const size = Buffer.byteLength(line);
|
|
246
|
+
// Tiny caps may not fit even an empty seal: leave the stream incomplete rather than exceed the cap.
|
|
247
|
+
if (bytes + size > maxBytes) { counts.failed++; return; }
|
|
248
|
+
bytes += size;
|
|
249
|
+
options.write(line);
|
|
250
|
+
}
|
|
251
|
+
catch { counts.failed++; }
|
|
252
|
+
},
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/** One defensive seam for every call site, including an injected/broken observer. Off never evaluates make. */
|
|
257
|
+
export function observeV2(sink: V2Observations | undefined, make: Parameters<V2Observations["record"]>[0]): void {
|
|
258
|
+
if (sink === undefined) return;
|
|
259
|
+
try { sink.record(make); } catch { /* Diagnostics must not affect the operation. */ }
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/** Adapter-injected callback: the timing recorder knows only its detached write identity, not this diagnostic layer. */
|
|
263
|
+
export function timingWriteObserver(sink: V2Observations | undefined): ((row: Readonly<CompletionIdentity & { outcome: string }>) => void) | undefined {
|
|
264
|
+
if (sink === undefined) return undefined;
|
|
265
|
+
return (row) => observeV2(sink, () => ({ family: "completion-effect", effect: "timing-row-write", source: "append-timings",
|
|
266
|
+
parentSessionID: row.parentSessionID, callID: row.callID, childSessionID: row.childSessionID, outcome: row.outcome }));
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/** The caller must be v2; v1 never reads this environment variable. Failure leaves diagnostics off. */
|
|
270
|
+
export function openV2Observations(env: NodeJS.ProcessEnv = process.env): V2Observations | undefined {
|
|
271
|
+
const dir = env.MODEL_ROUTER_V2_OBSERVATIONS;
|
|
272
|
+
if (!dir) return undefined;
|
|
273
|
+
let fd: number | undefined;
|
|
274
|
+
try {
|
|
275
|
+
fd = openSync(join(dir, `${process.pid}-${randomUUID()}.jsonl`), "wx", 0o600);
|
|
276
|
+
const file = fd;
|
|
277
|
+
const sink = createV2Observations({ write: (line) => {
|
|
278
|
+
const data = Buffer.from(line);
|
|
279
|
+
let offset = 0;
|
|
280
|
+
while (offset < data.length) {
|
|
281
|
+
const n = writeSync(file, data, offset, data.length - offset);
|
|
282
|
+
if (n <= 0) throw new Error("observation write stalled");
|
|
283
|
+
offset += n;
|
|
284
|
+
}
|
|
285
|
+
} });
|
|
286
|
+
let closed = false;
|
|
287
|
+
return { record: sink.record, counts: sink.counts, flush: sink.flush, close() {
|
|
288
|
+
if (closed) return;
|
|
289
|
+
closed = true;
|
|
290
|
+
sink.close();
|
|
291
|
+
try { closeSync(file); } catch { /* Best effort. */ }
|
|
292
|
+
} };
|
|
293
|
+
} catch {
|
|
294
|
+
if (fd !== undefined) { try { closeSync(fd); } catch { /* Best effort. */ } }
|
|
295
|
+
return undefined;
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/** task:<parent>:<callID> is the dispatch store's key. No inference when it is not that namespace. */
|
|
300
|
+
export function completionIdentity(parentSessionID: string, dispatchID: string, childSessionID: string | null): CompletionIdentity {
|
|
301
|
+
const prefix = `task:${parentSessionID}:`;
|
|
302
|
+
return { parentSessionID, callID: dispatchID.startsWith(prefix) ? dispatchID.slice(prefix.length) : dispatchID, childSessionID };
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/** Collector-side completeness check. Never called by routing; missing seals/gaps/faults are hard errors, not success. */
|
|
306
|
+
export function checkV2ObservationStream(lines: readonly string[]): ObservationRecord[] {
|
|
307
|
+
if (lines.length === 0 || lines.length > OBSERVATION_MAX_EVENTS + 1) throw new Error("missing or oversized observation stream");
|
|
308
|
+
const records: ObservationRecord[] = [];
|
|
309
|
+
let stream: string | undefined;
|
|
310
|
+
for (const [i, line] of lines.entries()) {
|
|
311
|
+
if (Buffer.byteLength(line) > OBSERVATION_MAX_ROW_BYTES) throw new Error("oversized observation row");
|
|
312
|
+
const row: unknown = JSON.parse(line);
|
|
313
|
+
if (row === null || typeof row !== "object") throw new Error("invalid observation row");
|
|
314
|
+
const r = row as Record<string, unknown>;
|
|
315
|
+
if (typeof r.stream !== "string" || r.stream === "" || r.v !== 1 || r.seq !== i + 1 || typeof r.at !== "number" || !Number.isFinite(r.at)) {
|
|
316
|
+
throw new Error("observation version/sequence gap");
|
|
317
|
+
}
|
|
318
|
+
stream ??= r.stream;
|
|
319
|
+
if (r.stream !== stream) throw new Error("mixed observation streams");
|
|
320
|
+
if (i === lines.length - 1) {
|
|
321
|
+
if (r.kind !== "end" || r.attempted !== i || r.written !== i || r.dropped !== 0 || r.failed !== 0) throw new Error("incomplete observation stream");
|
|
322
|
+
} else {
|
|
323
|
+
if (r.kind !== undefined || !["native-args", "completion-effect", "scheduler", "service"].includes(String(r.family))) throw new Error("invalid observation family");
|
|
324
|
+
records.push(row as ObservationRecord);
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
return records;
|
|
328
|
+
}
|