opencode-model-router 2.8.0 → 2.9.0
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 +364 -0
- package/README.md +20 -0
- 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
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
import { observeV2, type ObservationValue, type ServiceIdentity, type ServiceSpanKind, type V2Observations } from "../compat/v2-observations";
|
|
2
|
+
import { pathsOverlap } from "./schedule";
|
|
3
|
+
import type { Clock, LedgerV1, LedgerWriter } from "./types";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Service family (v2 opt-in only), amended G8 intrinsic-time oracle:
|
|
7
|
+
* {family:"service",spanKind:"service"|"service-prep"|"service-wait"|"service-unattributed",action:"start"|"end",
|
|
8
|
+
* planId,taskId,attempt,phaseId,entryId,taskIds,component,candidate,operationId,stage,clockMs,durationMs,result}.
|
|
9
|
+
* Task verification identifies taskId+attempt; integration identifies phaseId+entryId and copies ALL entry.taskIds
|
|
10
|
+
* (also for a batch probe/subset). candidate is the checked commit/snapshot identity, null when not yet known.
|
|
11
|
+
* Pre-entry queue/lane/repo-lock waits have entryId=null (no journal entry exists yet), retaining taskId+attempt
|
|
12
|
+
* or phaseId and the queued taskIds. Never fabricate a future entry ID or attribute these waits as execution.
|
|
13
|
+
* operationId is unique within the sink/stream, shared by exactly one start/end pair, including failed attempts.
|
|
14
|
+
* stage distinguishes command/recheck/grading, rebase, merge and CAS, and named preparation/resource waits.
|
|
15
|
+
* clockMs uses the process monotonic performance clock (NOT epoch `at` or journal duration); durationMs is zero
|
|
16
|
+
* on start and end-start on end. result is null on start, a bounded outcome label on end, never output/error text.
|
|
17
|
+
* Results describe that operation (pass/fail/error/timed-out/interrupted, completed for grading/preparation,
|
|
18
|
+
* acquired/busy for a slot, dequeued/dropped/disposed/aborted for a queue wait), NOT the published task verdict.
|
|
19
|
+
* Sum ONLY service intervals: mandatory verification execution/grading, actual rebase, mandatory integration
|
|
20
|
+
* command execution, checked merge/CAS, and phase-suite command execution. No enclosing journal/gate durations.
|
|
21
|
+
* Preparation (capture, snapshot/environment, checkout reset/provisioning, planning, grader startup) and resource
|
|
22
|
+
* waits (leases, repo/verification slots, lanes) are separate, possibly nested, non-service spans. Publication,
|
|
23
|
+
* release/cleanup and retry backoff are never service. No execution (memo/no-checks/aborted-before-run) means no
|
|
24
|
+
* service pair. Repeated executions/retries have distinct IDs; do not deduplicate by candidate or taskIds.
|
|
25
|
+
* End precedes result publication/cleanup. Exceptions still close pairs. Missing pairs/faulted streams are UNKNOWN,
|
|
26
|
+
* not zero service. Unattributed spans (native grading without provider attempt events) are also UNKNOWN, never
|
|
27
|
+
* zero or intrinsic service. Observations neither query for identity nor change admission, scheduling or verification.
|
|
28
|
+
*/
|
|
29
|
+
export interface ServiceObservation {
|
|
30
|
+
start(kind: ServiceSpanKind, stage: string, candidate?: string | null): { end(result: string): void } | undefined;
|
|
31
|
+
execution(stage: string, candidate?: string | null): ServiceExecution | undefined;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Per-call, diagnostic-only process hook. Methods are idempotent and contain observer failures. */
|
|
35
|
+
export interface ServiceExecution {
|
|
36
|
+
/** A process adapter claims the call BEFORE preparing its executable/environment or refusing a spawn. */
|
|
37
|
+
prepare(): void;
|
|
38
|
+
/** Immediately before the actual spawn, after all preparation. */
|
|
39
|
+
start(): void;
|
|
40
|
+
/** At process settlement, before result conversion/publication/cleanup; also closes a refused preparation. */
|
|
41
|
+
end(result: string): void;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const serviceSequences = new WeakMap<V2Observations, number>();
|
|
45
|
+
|
|
46
|
+
/** Lazy identity and clock; every diagnostic failure is contained, including injected observers/identity thunks. */
|
|
47
|
+
export function serviceObservation(sink: V2Observations | undefined, identity: () => ServiceIdentity,
|
|
48
|
+
now: () => number = () => performance.now()): ServiceObservation | undefined {
|
|
49
|
+
if (sink === undefined) return undefined;
|
|
50
|
+
const open = (spanKind: ServiceSpanKind, stage: string, candidate?: string | null,
|
|
51
|
+
project = identity, clock = now): ReturnType<ServiceObservation["start"]> => {
|
|
52
|
+
let captured: ServiceIdentity | undefined;
|
|
53
|
+
let operationId = "";
|
|
54
|
+
let started = 0;
|
|
55
|
+
observeV2(sink, () => {
|
|
56
|
+
captured = { ...project(), ...(candidate === undefined ? {} : { candidate }) };
|
|
57
|
+
captured = { ...captured, taskIds: [...captured.taskIds] };
|
|
58
|
+
const n = (serviceSequences.get(sink) ?? 0) + 1;
|
|
59
|
+
serviceSequences.set(sink, n);
|
|
60
|
+
operationId = `service-${n}`;
|
|
61
|
+
started = clock();
|
|
62
|
+
return { ...captured, family: "service", spanKind, stage, operationId, action: "start", clockMs: started, durationMs: 0, result: null };
|
|
63
|
+
});
|
|
64
|
+
if (captured === undefined || operationId === "") return undefined;
|
|
65
|
+
const fields = captured;
|
|
66
|
+
let ended = false;
|
|
67
|
+
return { end(result) {
|
|
68
|
+
if (ended) return;
|
|
69
|
+
ended = true;
|
|
70
|
+
observeV2(sink, () => {
|
|
71
|
+
const clockMs = now();
|
|
72
|
+
return { ...fields, family: "service", spanKind, stage, operationId, action: "end", clockMs, durationMs: clockMs - started, result };
|
|
73
|
+
});
|
|
74
|
+
} };
|
|
75
|
+
};
|
|
76
|
+
return {
|
|
77
|
+
start: open,
|
|
78
|
+
execution(stage, candidate) {
|
|
79
|
+
// Defer classification, not the clock/identity. An injected execution-only seam is itself the boundary;
|
|
80
|
+
// production adapters call prepare/start/end to split preparation from the actual child lifetime.
|
|
81
|
+
let captured: ServiceIdentity, started: number;
|
|
82
|
+
try {
|
|
83
|
+
captured = { ...identity(), ...(candidate === undefined ? {} : { candidate }) };
|
|
84
|
+
captured = { ...captured, taskIds: [...captured.taskIds] };
|
|
85
|
+
started = now();
|
|
86
|
+
} catch (error) {
|
|
87
|
+
observeV2(sink, () => { throw error; });
|
|
88
|
+
return undefined;
|
|
89
|
+
}
|
|
90
|
+
let phase: "pending" | "preparation" | "execution" | "ended" = "pending";
|
|
91
|
+
let span: ReturnType<ServiceObservation["start"]>;
|
|
92
|
+
const begin = (kind: ServiceSpanKind, name: string, clock = now) => open(kind, name, undefined, () => captured, clock);
|
|
93
|
+
return {
|
|
94
|
+
prepare() {
|
|
95
|
+
if (phase !== "pending") return;
|
|
96
|
+
phase = "preparation";
|
|
97
|
+
span = begin("service-prep", "process-preparation", () => started);
|
|
98
|
+
},
|
|
99
|
+
start() {
|
|
100
|
+
if (phase === "execution" || phase === "ended") return;
|
|
101
|
+
span?.end("completed");
|
|
102
|
+
phase = "execution";
|
|
103
|
+
span = begin("service", stage);
|
|
104
|
+
},
|
|
105
|
+
end(result) {
|
|
106
|
+
if (phase === "ended") return;
|
|
107
|
+
if (phase === "pending") span = begin("service", stage, () => started);
|
|
108
|
+
phase = "ended";
|
|
109
|
+
span?.end(result);
|
|
110
|
+
},
|
|
111
|
+
};
|
|
112
|
+
},
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Same plan-scoped v2 port as physical slots; queue/checks need no runtime or scheduling hook. */
|
|
117
|
+
export function executorServiceObservation(clock: Clock, planId: string, identity: () => ServiceIdentity): ServiceObservation | undefined {
|
|
118
|
+
return serviceObservation(slotObservers.get(clock)?.get(planId)?.sink, identity);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Physical-slot schema (scheduler family; separate from provider tokens and write leases):
|
|
123
|
+
* Ledger/attach tasks include `slot: string|null`. Clearing it does NOT assert a successful pool release.
|
|
124
|
+
* Pool rows have {planId,parentSessionID,action,state}, where state is
|
|
125
|
+
* {clockMs,maxParallel,opened,closed,slots:[{slot,kind,state,taskId}],corrupt:[slot],detail}.
|
|
126
|
+
* `slot` is the pool-local name, never a path; identity is (planId,slot). `taskId` is null for special slots
|
|
127
|
+
* and unrecognised owners. Slot states are creating/provisioning/ready/leased/resetting/broken/retired.
|
|
128
|
+
* A ledger slot outside the pool's name grammar invalidates the observation, never emits arbitrary text/paths.
|
|
129
|
+
* Every row copies the current in-memory records, never calls get/list or performs diagnostic I/O.
|
|
130
|
+
* Actions/detail:
|
|
131
|
+
* - slot-pool-open, slot-pool-close: null.
|
|
132
|
+
* - slot-state: {slot}, immediately AFTER a committed in-memory record swap/removal (including recovery/GC).
|
|
133
|
+
* This observes creating, reset/provisioning, leased-to-task, broken and ready/available transitions.
|
|
134
|
+
* - slot-acquire-start: {kind,taskId} (before the existing pool-lock wait).
|
|
135
|
+
* - slot-claim: {slot,kind,taskId,mode}, after claim under the pool mutex, before work under the slot mutex.
|
|
136
|
+
* - slot-acquire-result: {slot,kind,taskId,mode,result}; mode=same/reset/create/recreate, or null when claim failed;
|
|
137
|
+
* result=created/reused/unavailable/failed. A failed claim has slot=null; work failures retain the claimed slot.
|
|
138
|
+
* - slot-provision-start, slot-reset-start: {slot}.
|
|
139
|
+
* - slot-provision-end, slot-reset-end: {slot,result}, result=completed/failed. Completion is NOT availability:
|
|
140
|
+
* the slot can still be provisioning/resetting/leased; consult the accompanying records.
|
|
141
|
+
* - slot-release-start, slot-release-failed: {slot}, under the slot mutex. Failure leaves the actual record unchanged.
|
|
142
|
+
* - slot-release-complete: {slot,result}, result=released/unchanged. `released` follows the awaited marker write
|
|
143
|
+
* AND memory swap to ready/owner=null. `unchanged` is the existing no-op (missing or non-leased record), not availability.
|
|
144
|
+
* A provider release, task.slot=null, lease-release or release-start is NOT evidence of physical availability.
|
|
145
|
+
* ready records can be reused; live task records count against maxParallel (integration/ci do not).
|
|
146
|
+
* Unused capacity/broken replacement still requires a successful claim; corrupt/unmarked directories can refuse it.
|
|
147
|
+
* Missing pool facts are UNKNOWN. No scheduler decisions are inferred or changed by this stream.
|
|
148
|
+
*/
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Runtime idle-close schema (scheduler family, separate from physical-slot actions):
|
|
152
|
+
* {family:"scheduler",planId,parentSessionID,action:"idle-close",state:{clockMs,ledgerSeq,...,detail:{fromMs,toMs,ms,
|
|
153
|
+
* metric:{name:"idle-with-ready",fromAt,toAt,ms,readyTaskIds,free}}}}.
|
|
154
|
+
* Emitted inside closeIdle at the actual closing continuation, before the asynchronous metric append can run.
|
|
155
|
+
* clockMs=toMs uses the metric endpoint's single Clock.now() sample; ms=max(0,toMs-fromMs). No extra clock read.
|
|
156
|
+
* metric is a defensive copy of the full, unchanged ledger payload: correlate by planId, payload and occurrence
|
|
157
|
+
* order, not by the later journal timestamp. ledgerSeq is the committed watermark at closure, NOT the metric's seq.
|
|
158
|
+
* A row observes metric creation, not successful journal persistence or scheduling eligibility. Capture is lazy,
|
|
159
|
+
* exception-contained and inert without the v2 observation sink; it neither queries nor changes scheduler state.
|
|
160
|
+
*/
|
|
161
|
+
|
|
162
|
+
// Runtime and its lazily-created plan pools already share the injected clock object. Scope the diagnostic port
|
|
163
|
+
// by that identity AND plan, so queue-owned operations are covered too, without wrapping pool methods or adding
|
|
164
|
+
// queries/awaits to assembly. No entry exists off/v1; detach drops the writer/sink, and the clock key is weak.
|
|
165
|
+
const slotObservers = new WeakMap<Clock, Map<string, { sink: V2Observations; writer: LedgerWriter }>>();
|
|
166
|
+
|
|
167
|
+
export function attachSlotObservations(sink: V2Observations | undefined, clock: Clock, writer: LedgerWriter): void {
|
|
168
|
+
if (sink === undefined) return;
|
|
169
|
+
try {
|
|
170
|
+
let plans = slotObservers.get(clock);
|
|
171
|
+
if (plans === undefined) { plans = new Map(); slotObservers.set(clock, plans); }
|
|
172
|
+
plans.set(writer.planId, { sink, writer });
|
|
173
|
+
} catch { /* Diagnostics must not affect attachment. */ }
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
export function detachSlotObservations(clock: Clock, writer: LedgerWriter): void {
|
|
177
|
+
try {
|
|
178
|
+
const plans = slotObservers.get(clock);
|
|
179
|
+
if (plans?.get(writer.planId)?.writer === writer) plans.delete(writer.planId);
|
|
180
|
+
if (plans?.size === 0) slotObservers.delete(clock);
|
|
181
|
+
} catch { /* Diagnostics must not affect detachment. */ }
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
export function observeSlotPool(clock: Clock, planId: string, action: string, state: () => ObservationValue): void {
|
|
185
|
+
const port = slotObservers.get(clock)?.get(planId);
|
|
186
|
+
if (port === undefined) return;
|
|
187
|
+
observeV2(port.sink, () => ({ family: "scheduler", planId,
|
|
188
|
+
parentSessionID: port.writer.ledger.orchestrator.sessionID, action, state: state() }));
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** Raw committed scheduler inputs, not readySet/updateIdle output. No plan text, evidence, paths or commands. */
|
|
192
|
+
export function observeSchedulerLedger(sink: V2Observations | undefined, ledger: Readonly<LedgerV1>, action: "ledger" | "attach"): void {
|
|
193
|
+
observeV2(sink, () => {
|
|
194
|
+
const tasks = Object.values(ledger.tasks);
|
|
195
|
+
if (tasks.length > 256) throw new Error("scheduler observation task bound");
|
|
196
|
+
// The ledger accepts arbitrary strings here; unlike pool markers, it does not enforce the slot-name grammar.
|
|
197
|
+
if (tasks.some(t => t.slot !== null && !/^(?:slot-[1-9][0-9]{0,2}|integration|ci)$/.test(t.slot))) {
|
|
198
|
+
throw new Error("scheduler observation slot identity");
|
|
199
|
+
}
|
|
200
|
+
return { family: "scheduler", planId: ledger.planId, parentSessionID: ledger.orchestrator.sessionID, action,
|
|
201
|
+
state: {
|
|
202
|
+
ledgerSeq: ledger.seq, status: ledger.status, maxParallel: ledger.config.maxParallel,
|
|
203
|
+
tasks: tasks.map((t) => ({ id: t.id, state: t.state, kind: t.kind, phase: t.phase, p50: t.estimate.p50, slot: t.slot,
|
|
204
|
+
attempts: t.attempts.map((a) => ({ n: a.n, callID: a.callID, childSessionID: a.childSessionID, outcome: a.outcome })) })),
|
|
205
|
+
edges: ledger.edges.map((e) => ({ from: e.from, to: e.to })),
|
|
206
|
+
phases: ledger.phases.map((p) => ({ id: p.id, gate: p.gate, paused: p.paused })),
|
|
207
|
+
// Pairwise conflict facts preserve the scheduler's prefix-overlap rule without disclosing paths.
|
|
208
|
+
writeConflicts: tasks.flatMap((t, i) => tasks.slice(i + 1).filter((other) =>
|
|
209
|
+
t.footprint.writes.some((a) => other.footprint.writes.some((b) => pathsOverlap(a, b)))).map((other) => [t.id, other.id])),
|
|
210
|
+
} };
|
|
211
|
+
});
|
|
212
|
+
}
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { realpath as fsRealpath } from "node:fs/promises";
|
|
3
|
+
import { join, resolve } from "node:path";
|
|
4
|
+
import {
|
|
5
|
+
gitEnvironment,
|
|
6
|
+
gitExecutable,
|
|
7
|
+
hardeningArgs,
|
|
8
|
+
inheritedSafeDirectoryArgs,
|
|
9
|
+
isNetworkOrDevicePath,
|
|
10
|
+
spawnBounded,
|
|
11
|
+
workRootGuards,
|
|
12
|
+
} from "../router/git-tools.js";
|
|
13
|
+
import { PLAN_ID_PATTERN, type IsoTime, type PlanId } from "./types.js";
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Where the executor keeps its state (2.2.1). Nothing here touches the filesystem or runs git at module load; every
|
|
17
|
+
* function that does takes its seams through {@link ExecutorPathsDeps}, so unit tests need no real repository.
|
|
18
|
+
*
|
|
19
|
+
* The executor home lives in the repository's git **common** directory, never in a worktree's private git directory
|
|
20
|
+
* (`<common>\worktrees\<id>`): the main checkout and every linked worktree of one repository therefore resolve to the
|
|
21
|
+
* same home, and removing a worktree never removes a plan's ledger.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
/** Name of the executor directory inside the git common directory (2.2.1.a). */
|
|
25
|
+
export const EXECUTOR_HOME_DIRNAME = "omr-executor";
|
|
26
|
+
|
|
27
|
+
/** Name of the directory under the executor home that holds the slot markers (2.2.1.b). */
|
|
28
|
+
export const SLOT_MARKERS_DIRNAME = "slots";
|
|
29
|
+
|
|
30
|
+
/** Result of one git run: the exit code (null when killed) and both streams as text. */
|
|
31
|
+
export interface GitRunResult {
|
|
32
|
+
code: number | null;
|
|
33
|
+
stdout: string;
|
|
34
|
+
stderr: string;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Runs git with `args` in `cwd`. The default is hardened, has no shell and bounds time and output. */
|
|
38
|
+
export type GitRunner = (args: readonly string[], cwd: string) => Promise<GitRunResult>;
|
|
39
|
+
|
|
40
|
+
/** Test seams for {@link resolveExecutorHome}; every field is optional and defaults to the real thing. */
|
|
41
|
+
export interface ExecutorPathsDeps {
|
|
42
|
+
/** Replaces the whole git invocation (executable choice, hardening, spawning). */
|
|
43
|
+
git?: GitRunner;
|
|
44
|
+
/** Replaces `fs.promises.realpath`. */
|
|
45
|
+
realpath?: (path: string) => Promise<string>;
|
|
46
|
+
/** Aborts the default git runner. */
|
|
47
|
+
signal?: AbortSignal;
|
|
48
|
+
/** Time bound for the default git runner (ms). */
|
|
49
|
+
timeoutMs?: number;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Bound on a `rev-parse --git-common-dir` answer: one path line. */
|
|
53
|
+
const GIT_OUTPUT_LIMIT = 64 * 1024;
|
|
54
|
+
/** Default time bound for the git call (ms). */
|
|
55
|
+
const GIT_TIMEOUT_MS = 15_000;
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* The default {@link GitRunner}: the git executable is chosen outside `dir`'s work root (`workRootGuards`), run with the
|
|
59
|
+
* router's hardening arguments, a scrubbed `GIT_*` environment and the user's `safe.directory` values, never through a shell.
|
|
60
|
+
*/
|
|
61
|
+
function defaultGitRunner(deps: ExecutorPathsDeps): GitRunner {
|
|
62
|
+
return async (args, cwd) => {
|
|
63
|
+
const executable = gitExecutable(workRootGuards(cwd));
|
|
64
|
+
const trusted = await inheritedSafeDirectoryArgs(executable);
|
|
65
|
+
const result = await spawnBounded(executable, [...hardeningArgs(), ...trusted, ...args], cwd, {
|
|
66
|
+
env: gitEnvironment(),
|
|
67
|
+
signal: deps.signal,
|
|
68
|
+
timeoutMs: deps.timeoutMs ?? GIT_TIMEOUT_MS,
|
|
69
|
+
maxBytes: GIT_OUTPUT_LIMIT,
|
|
70
|
+
});
|
|
71
|
+
if (result.truncated) throw new Error("git output exceeds its size bound");
|
|
72
|
+
return { code: result.code, stdout: result.output.toString("utf8"), stderr: result.stderr.toString("utf8") };
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* `<realpath of git rev-parse --git-common-dir>\omr-executor` (2.2.1.a), resolved from `dir`.
|
|
78
|
+
*
|
|
79
|
+
* `--git-common-dir` is relative to `dir` in a main checkout (`.git`) and absolute in a linked worktree, so it is resolved
|
|
80
|
+
* against `dir` first and then through `realpath` (symlinks, junctions, case on Windows), which makes both give one home.
|
|
81
|
+
* Throws when `dir` is not in a git repository, when git reports a network or device path, or when the directory does not
|
|
82
|
+
* exist. Creates nothing: the ledger store creates the directory when it opens a plan.
|
|
83
|
+
*/
|
|
84
|
+
export async function resolveExecutorHome(dir: string, deps: ExecutorPathsDeps = {}): Promise<string> {
|
|
85
|
+
const git = deps.git ?? defaultGitRunner(deps);
|
|
86
|
+
const real = deps.realpath ?? fsRealpath;
|
|
87
|
+
const run = await git(["rev-parse", "--git-common-dir"], dir);
|
|
88
|
+
if (run.code !== 0) {
|
|
89
|
+
throw new Error(`Cannot resolve the git common directory of ${dir} (${run.code}): ${run.stderr.trim()}`);
|
|
90
|
+
}
|
|
91
|
+
const reported = run.stdout.replace(/\r?\n$/, "");
|
|
92
|
+
if (reported.trim() === "") throw new Error(`git reported no common directory for ${dir}`);
|
|
93
|
+
if (isNetworkOrDevicePath(reported)) throw new Error("Refusing executor home: git reports a network or device path");
|
|
94
|
+
// A relative answer resolved against `dir`, or a realpath that crosses a junction or symlink, can land on a network or device path
|
|
95
|
+
// that the reported text did not show: check both results as well.
|
|
96
|
+
const resolved = resolve(dir, reported);
|
|
97
|
+
if (isNetworkOrDevicePath(resolved)) throw new Error("Refusing executor home: the git common directory resolves to a network or device path");
|
|
98
|
+
const common = await real(resolved);
|
|
99
|
+
if (isNetworkOrDevicePath(common)) throw new Error("Refusing executor home: the git common directory resolves to a network or device path");
|
|
100
|
+
return join(common, EXECUTOR_HOME_DIRNAME);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* True when `id` is a well-formed plan id (`PLAN_ID_PATTERN`, 2.2.1.c). The slot markers directory name (`slots`) is reserved, compared
|
|
105
|
+
* case-insensitively because the home lives on a case-insensitive filesystem on Windows: a plan of that name would collide with it.
|
|
106
|
+
*/
|
|
107
|
+
export function isPlanId(id: unknown): id is PlanId {
|
|
108
|
+
return (
|
|
109
|
+
typeof id === "string" &&
|
|
110
|
+
PLAN_ID_PATTERN.test(id) &&
|
|
111
|
+
id.toLowerCase() !== SLOT_MARKERS_DIRNAME &&
|
|
112
|
+
!WINDOWS_DEVICE_NAME.test(id)
|
|
113
|
+
);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Windows reserved device names (any case): a directory of that name cannot be created or addressed reliably on Windows. */
|
|
117
|
+
const WINDOWS_DEVICE_NAME = /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])$/i;
|
|
118
|
+
|
|
119
|
+
/** Returns `id` or throws unless it matches `PLAN_ID_PATTERN`: the id becomes a path segment, so it is never trusted unchecked. */
|
|
120
|
+
export function assertPlanId(id: string): PlanId {
|
|
121
|
+
if (!isPlanId(id)) throw new Error(`Invalid plan id: ${JSON.stringify(id)}`);
|
|
122
|
+
return id;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** `<home>\<planId>\` (2.2.1.b); throws on a plan id that is not a valid path segment. */
|
|
126
|
+
export function planDir(home: string, planId: PlanId): string {
|
|
127
|
+
return join(home, assertPlanId(planId));
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** `<home>\slots\` (2.2.1.b). */
|
|
131
|
+
export function slotMarkersDir(home: string): string {
|
|
132
|
+
return join(home, SLOT_MARKERS_DIRNAME);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** Object keys sorted at every depth, so equal options always serialise to the same text. */
|
|
136
|
+
function canonicalJson(value: unknown): string {
|
|
137
|
+
return JSON.stringify(value, (_key, v: unknown) => {
|
|
138
|
+
if (v === null || typeof v !== "object" || Array.isArray(v)) return v;
|
|
139
|
+
const sorted: Record<string, unknown> = {};
|
|
140
|
+
for (const key of Object.keys(v).sort()) sorted[key] = (v as Record<string, unknown>)[key];
|
|
141
|
+
return sorted;
|
|
142
|
+
}) ?? "";
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* A new plan id, `p-<yyyymmdd>-<6 hex of sha256(path + digest + options)>` (2.2.1.c).
|
|
147
|
+
*
|
|
148
|
+
* `path + digest + options` is the plain concatenation of the three: `planPath` as the caller passes it (canonicalise it
|
|
149
|
+
* first), the plan file's digest, and the compile options (a string is used verbatim; anything else as key-sorted JSON).
|
|
150
|
+
* The date is the UTC day of `now` (a `Date` or an ISO time). The result always satisfies `PLAN_ID_PATTERN`.
|
|
151
|
+
*/
|
|
152
|
+
export function newPlanId(planPath: string, digest: string, options: unknown, now: Date | IsoTime): PlanId {
|
|
153
|
+
const when = typeof now === "string" ? new Date(now) : now;
|
|
154
|
+
if (Number.isNaN(when.getTime())) throw new Error("newPlanId needs a valid time");
|
|
155
|
+
const day = when.toISOString().slice(0, 10).replace(/-/g, "");
|
|
156
|
+
const optionsText = typeof options === "string" ? options : canonicalJson(options);
|
|
157
|
+
const hex = createHash("sha256").update(planPath + digest + optionsText).digest("hex").slice(0, 6);
|
|
158
|
+
return assertPlanId(`p-${day}-${hex}`);
|
|
159
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* G-16: the plan executor is Windows-only in this release. Its slots live under a drive-letter path
|
|
3
|
+
* (`routing.executor.slotsDir`, default `<drive>:\.omr-slots\<planId>`), so on any other platform the executor is not
|
|
4
|
+
* assembled on OpenCode v2: `router_plan` and `/plan` are not registered, `/router` does not list `/plan`, role
|
|
5
|
+
* registration does no executor-home lookup and grants no slots root, and start-up executor discovery does nothing.
|
|
6
|
+
*
|
|
7
|
+
* This module is the one platform seam: every caller asks {@link executorPlatformSupported}, whose `platform` defaults to
|
|
8
|
+
* `process.platform`, so a test drives both platforms by spying on it.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
/** The one notice per process on a platform without the executor, logged only when the config asks for it. */
|
|
12
|
+
export const EXECUTOR_PLATFORM_NOTICE = "plan executor requires Windows; router_plan and /plan are not registered";
|
|
13
|
+
|
|
14
|
+
/** The executor access's unavailable reason on such a platform (start-up discovery is skipped with it). */
|
|
15
|
+
export const EXECUTOR_PLATFORM_REASON = "the plan executor requires Windows";
|
|
16
|
+
|
|
17
|
+
/** Whether the plan executor can be assembled on `platform` (default: this process's). */
|
|
18
|
+
export function executorPlatformSupported(platform: NodeJS.Platform = process.platform): boolean {
|
|
19
|
+
return platform === "win32";
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* QA-62C-3: the "notice logged" flag lives on `globalThis` under a registry symbol, so every loaded copy of this module
|
|
24
|
+
* (a hot reload, a second bundle) shares it and the process still logs one notice.
|
|
25
|
+
*/
|
|
26
|
+
const platformNoticeKey = Symbol.for("omr.executor.platformNotice.v1");
|
|
27
|
+
const platformNotice = globalThis as typeof globalThis & { [platformNoticeKey]?: boolean };
|
|
28
|
+
|
|
29
|
+
/** Logs {@link EXECUTOR_PLATFORM_NOTICE} once per process (AGENTS.md: at most one notice per process for an inert feature). */
|
|
30
|
+
export function warnExecutorPlatformOnce(logger: { warn(message: string): void }): void {
|
|
31
|
+
if (platformNotice[platformNoticeKey] === true) return;
|
|
32
|
+
platformNotice[platformNoticeKey] = true;
|
|
33
|
+
logger.warn(`[router] ${EXECUTOR_PLATFORM_NOTICE}`);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Tests only: forget that the notice was logged. */
|
|
37
|
+
export function resetExecutorPlatformNotice(): void {
|
|
38
|
+
delete platformNotice[platformNoticeKey];
|
|
39
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { hostname } from "node:os";
|
|
2
|
+
|
|
3
|
+
export interface ProcessIdentity { pid: number; hostname: string; token: string }
|
|
4
|
+
|
|
5
|
+
/** QA-DF1-21: one journal token for every module copy in this process. Keep the existing global slot and token format. */
|
|
6
|
+
const PROCESS_TOKEN_SLOT = Symbol.for("opencode-model-router.v2.process-token");
|
|
7
|
+
|
|
8
|
+
export function processToken(): string {
|
|
9
|
+
const known: unknown = Reflect.get(globalThis, PROCESS_TOKEN_SLOT);
|
|
10
|
+
if (typeof known === "string") return known;
|
|
11
|
+
const token = `${process.pid.toString(16)}-${Date.now().toString(16)}-${Math.random().toString(16).slice(2, 10)}`;
|
|
12
|
+
Reflect.set(globalThis, PROCESS_TOKEN_SLOT, token);
|
|
13
|
+
return token;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** A later process may reuse the pid, never the token. */
|
|
17
|
+
export function processIdentity(): ProcessIdentity {
|
|
18
|
+
return { pid: process.pid, hostname: hostname(), token: processToken() };
|
|
19
|
+
}
|