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,672 @@
|
|
|
1
|
+
// Executor assembly is synchronous; repository/home discovery is prepared separately.
|
|
2
|
+
import { realpathSync } from "node:fs";
|
|
3
|
+
import { realpath } from "node:fs/promises";
|
|
4
|
+
import { hostname } from "node:os";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import type { V2Executor, V2ExecutorHost } from "../compat/v2-hooks";
|
|
7
|
+
import { loadConfig, parseModelRef, resolveActiveTiers, resolveRolesRouting, resolveRouting, validateSlotsDir, type RouterHost } from "../router/config";
|
|
8
|
+
import { resolveRoles } from "../router/roles";
|
|
9
|
+
import { annotateSteps } from "../routing/engine/plan";
|
|
10
|
+
import { classifyMany } from "../routing/classify";
|
|
11
|
+
import { CLASS_STATIC_TIER } from "../routing/classify/types";
|
|
12
|
+
import { createDurationModel, DURATION_PRIOR_MS, type DurationModel } from "../routing/outcomes/durations";
|
|
13
|
+
import { CLASS_ROLE_KIND } from "../routing/engine/roles-taxonomy";
|
|
14
|
+
import { runArgv } from "../verify/exec";
|
|
15
|
+
import { hardeningArgs, spawnBounded, workRootGuards } from "../router/git-tools";
|
|
16
|
+
import { createCapacityController } from "./capacity";
|
|
17
|
+
import { createPlanCompiler, type CompilerDeps } from "./compile";
|
|
18
|
+
import { createGitOps, createGitRunner } from "./git";
|
|
19
|
+
import { BackgroundRuns, createIntegrateGit, createIntegrationChecks, createWriteGuard } from "./integrate/checks";
|
|
20
|
+
import { createLander } from "./integrate/land";
|
|
21
|
+
import { createPhaseSuiteRunner } from "./integrate/phase-suite";
|
|
22
|
+
import { createRunResolver } from "./integrate/run-resolver";
|
|
23
|
+
import { createIntegrationQueue, createRepoLockFactory, type IntegrationStepEvent } from "./integrate/queue";
|
|
24
|
+
import { createTaskLauncher } from "./launch";
|
|
25
|
+
import { createLedgerStore, createNodeClock, createNodeFileSystem } from "./ledger";
|
|
26
|
+
import { resolveExecutorHome } from "./paths";
|
|
27
|
+
import { processIdentity } from "./process-identity";
|
|
28
|
+
import { createRecoveryService, sameToplevel } from "./recovery";
|
|
29
|
+
import { createExecutorRuntime, realCollaborators, type ExecutorRuntimeHandle, type RuntimeDeps } from "./runtime";
|
|
30
|
+
import type { V2Observations } from "../compat/v2-observations";
|
|
31
|
+
import { createScheduler } from "./schedule";
|
|
32
|
+
import { countPlanMarkers, createSlotPool, defaultSlotsDir, type SlotPoolOpenOptions } from "./slots/pool";
|
|
33
|
+
import { createProvisioner } from "./slots/provision";
|
|
34
|
+
import { ExecutorError, type ExecutorRuntime, type LedgerStore, type LedgerV1, type PlanId, type SlotPool, type Spawner } from "./types";
|
|
35
|
+
|
|
36
|
+
/** Process adapter over the router's bounded, no-shell runner. */
|
|
37
|
+
function nodeSpawner(): Spawner {
|
|
38
|
+
return {
|
|
39
|
+
pid: process.pid, hostname: hostname(),
|
|
40
|
+
isAlive(pid) { try { process.kill(pid, 0); return true; } catch (error) { return (error as NodeJS.ErrnoException).code === "EPERM"; } },
|
|
41
|
+
async run(command, args, options) {
|
|
42
|
+
const start = Date.now();
|
|
43
|
+
const result = await spawnBounded(command, args, options.cwd, {
|
|
44
|
+
env: { ...options.env }, timeoutMs: options.timeoutMs, signal: options.signal,
|
|
45
|
+
maxBytes: options.maxOutputBytes, settleOnFailure: true, killGroupOnSettle: true,
|
|
46
|
+
});
|
|
47
|
+
if (result.failure !== undefined) throw new Error(result.failure);
|
|
48
|
+
return { code: result.code, signal: null, stdout: result.output.toString("utf8"), stderr: result.stderr.toString("utf8"),
|
|
49
|
+
truncated: result.truncated, durationMs: Date.now() - start };
|
|
50
|
+
},
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
type OpenPool = SlotPool & { open(opts?: SlotPoolOpenOptions): Promise<void>; close(): void; removeEmptyDir?(): Promise<boolean> };
|
|
55
|
+
|
|
56
|
+
/** Collection fences slot operations; a closed facade may still open a gc-only handle for purge. */
|
|
57
|
+
export class PlanSlotPools {
|
|
58
|
+
private readonly entries = new Map<PlanId, { view: SlotPool; pool: Promise<OpenPool> | null; closed: boolean }>();
|
|
59
|
+
constructor(private readonly deps: {
|
|
60
|
+
store: LedgerStore; toplevel: string; makePool(ledger: Readonly<LedgerV1>): OpenPool; log?: RuntimeDeps["log"];
|
|
61
|
+
/** QA-5.1-22: how many slot markers the plan still has (read only); a purge asks it when the plan's slotsDir is invalid. */
|
|
62
|
+
markers?(planId: PlanId): Promise<number>;
|
|
63
|
+
}) {}
|
|
64
|
+
|
|
65
|
+
readonly facade: SlotPool = {
|
|
66
|
+
acquire: (id, ...args) => this.of(id).acquire(id, ...args),
|
|
67
|
+
acquireSpecial: (id, ...args) => this.of(id).acquireSpecial(id, ...args),
|
|
68
|
+
reset: async () => { throw new ExecutorError("E_PLAN_STATE", "a slot operation requires a plan"); },
|
|
69
|
+
noteCommit: async () => { throw new ExecutorError("E_PLAN_STATE", "a slot operation requires a plan"); },
|
|
70
|
+
cleanForChecks: async () => { throw new ExecutorError("E_PLAN_STATE", "a slot operation requires a plan"); },
|
|
71
|
+
release: async () => { throw new ExecutorError("E_PLAN_STATE", "a slot operation requires a plan"); },
|
|
72
|
+
get: async () => null,
|
|
73
|
+
list: async (id) => id === undefined ? (await Promise.all([...this.entries.keys()].map((plan) => this.of(plan).list()))).flat() : this.of(id).list(),
|
|
74
|
+
gc: (finished, opts) => this.gc(finished, opts),
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
of(planId: PlanId): SlotPool {
|
|
78
|
+
const have = this.entries.get(planId);
|
|
79
|
+
if (have !== undefined) return have.view;
|
|
80
|
+
const entry = { view: null as SlotPool | null, pool: null as Promise<OpenPool> | null, closed: false };
|
|
81
|
+
const releaseListeners = new Set<() => void>();
|
|
82
|
+
const get = (): Promise<OpenPool> => {
|
|
83
|
+
if (entry.closed) return Promise.reject(new ExecutorError("E_PLAN_STATE", `slots of plan ${planId} are closed`));
|
|
84
|
+
entry.pool ??= this.deps.store.read(planId).then(async (ledger) => {
|
|
85
|
+
const pool = this.deps.makePool(ledger);
|
|
86
|
+
try {
|
|
87
|
+
if (ledger.status === "completed" || ledger.status === "aborted") await pool.open({ create: false });
|
|
88
|
+
else await pool.open();
|
|
89
|
+
}
|
|
90
|
+
catch (error) { pool.close(); throw error; }
|
|
91
|
+
if (entry.closed) { pool.close(); throw new ExecutorError("E_PLAN_STATE", `slots of plan ${planId} are closed`); }
|
|
92
|
+
pool.onTaskSlotReleased?.(() => {
|
|
93
|
+
if (entry.closed) return;
|
|
94
|
+
for (const listener of releaseListeners) {
|
|
95
|
+
try { listener(); } catch { /* Notification failures must not fail release. */ }
|
|
96
|
+
}
|
|
97
|
+
});
|
|
98
|
+
return pool;
|
|
99
|
+
});
|
|
100
|
+
return entry.pool;
|
|
101
|
+
};
|
|
102
|
+
// An invalid slotsDir with no markers has nothing to save (the purge has the same exception).
|
|
103
|
+
const inspect = async <T>(read: (pool: OpenPool) => Promise<T>, empty: T): Promise<T> => {
|
|
104
|
+
if (entry.closed) return empty;
|
|
105
|
+
try {
|
|
106
|
+
return await read(await get());
|
|
107
|
+
} catch (error) {
|
|
108
|
+
if (error instanceof ExecutorError && error.code === "E_INVALID_INPUT" && await this.deps.markers?.(planId) === 0) return empty;
|
|
109
|
+
throw error;
|
|
110
|
+
}
|
|
111
|
+
};
|
|
112
|
+
const view: SlotPool = {
|
|
113
|
+
acquire: async (...args) => (await get()).acquire(...args),
|
|
114
|
+
acquireSpecial: async (...args) => (await get()).acquireSpecial(...args),
|
|
115
|
+
reset: async (...args) => (await get()).reset(...args),
|
|
116
|
+
noteCommit: async (...args) => (await get()).noteCommit(...args),
|
|
117
|
+
cleanForChecks: async (...args) => (await get()).cleanForChecks(...args),
|
|
118
|
+
release: async (...args) => { if (!entry.closed) await (await get()).release(...args); },
|
|
119
|
+
onTaskSlotReleased(listener) {
|
|
120
|
+
releaseListeners.add(listener);
|
|
121
|
+
return () => { releaseListeners.delete(listener); };
|
|
122
|
+
},
|
|
123
|
+
get: (...args) => inspect((pool) => pool.get(...args), null),
|
|
124
|
+
list: (...args) => inspect((pool) => pool.list(...args), []),
|
|
125
|
+
gc: async (finished, opts) => {
|
|
126
|
+
if (entry.closed) {
|
|
127
|
+
// QA-5.1-22: the gc-only handle creates no directory.
|
|
128
|
+
const pool = this.deps.makePool(await this.deps.store.read(planId));
|
|
129
|
+
try { await pool.open({ create: false }); return await pool.gc(finished, opts); }
|
|
130
|
+
finally { pool.close(); }
|
|
131
|
+
}
|
|
132
|
+
const pool = await get();
|
|
133
|
+
const result = await pool.gc(finished, opts);
|
|
134
|
+
// A partial collection must keep its markers readable for the next save preflight, even though the pool
|
|
135
|
+
// itself already fences writes. A successful collection has nothing left to inspect.
|
|
136
|
+
if (await finished(planId) && result.reported.length === 0) { entry.closed = true; pool.close(); }
|
|
137
|
+
return result;
|
|
138
|
+
},
|
|
139
|
+
};
|
|
140
|
+
entry.view = view;
|
|
141
|
+
// Keep the memoized promise and closed flag in the same cell as the facade.
|
|
142
|
+
this.entries.set(planId, Object.assign(entry, { view }));
|
|
143
|
+
return view;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
async gc(finished: Parameters<SlotPool["gc"]>[0], opts?: Parameters<SlotPool["gc"]>[1]): ReturnType<SlotPool["gc"]> {
|
|
147
|
+
const removed: string[] = [], reported: string[] = [];
|
|
148
|
+
for (const plan of await this.deps.store.list()) {
|
|
149
|
+
if (!sameToplevel(plan.toplevel, this.deps.toplevel)) continue;
|
|
150
|
+
if (plan.status !== "completed" && plan.status !== "aborted" && this.entries.get(plan.planId)?.pool == null) continue;
|
|
151
|
+
try {
|
|
152
|
+
const result = await this.of(plan.planId).gc(finished, opts);
|
|
153
|
+
removed.push(...result.removed); reported.push(...result.reported);
|
|
154
|
+
} catch (error) {
|
|
155
|
+
this.deps.log?.("warn", "slot gc failed", { planId: plan.planId, error: error instanceof Error ? error.message : String(error) });
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
return { removed, reported };
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* QA-5.1-22: the purge's full gc of a finished plan. The live pool (if any) is closed first; the gc runs through a gc-only
|
|
163
|
+
* handle, which creates no directory, and a complete gc (no slot of the plan left) removes `<root>\<planId>` if it is
|
|
164
|
+
* empty. An invalid slotsDir with no slot marker of the plan skips the gc (nothing to collect); with markers it refuses.
|
|
165
|
+
*/
|
|
166
|
+
async purge(planId: PlanId, finished: Parameters<SlotPool["gc"]>[0]): ReturnType<SlotPool["gc"]> {
|
|
167
|
+
const entry = this.entries.get(planId);
|
|
168
|
+
if (entry !== undefined && !entry.closed) {
|
|
169
|
+
entry.closed = true;
|
|
170
|
+
try { (await entry.pool)?.close(); } catch { /* A failed open owns no live pool. */ }
|
|
171
|
+
}
|
|
172
|
+
const ledger = await this.deps.store.read(planId);
|
|
173
|
+
let pool: OpenPool | null = null;
|
|
174
|
+
try {
|
|
175
|
+
pool = this.deps.makePool(ledger);
|
|
176
|
+
await pool.open({ create: false });
|
|
177
|
+
} catch (error) {
|
|
178
|
+
pool?.close();
|
|
179
|
+
if (!(error instanceof ExecutorError) || error.code !== "E_INVALID_INPUT") throw error;
|
|
180
|
+
const markers = this.deps.markers === undefined ? 1 : await this.deps.markers(planId);
|
|
181
|
+
if (markers > 0) {
|
|
182
|
+
throw new ExecutorError("E_PLAN_STATE", `plan ${planId} still has ${markers} slot marker(s) but its slotsDir is invalid (${error.message}); `
|
|
183
|
+
+ "fix the slotsDir or remove those slots by hand, then purge again", { planId });
|
|
184
|
+
}
|
|
185
|
+
this.deps.log?.("warn", "purge: invalid slotsDir and no slot marker; nothing to collect", { planId, error: error.message });
|
|
186
|
+
return { removed: [], reported: [] };
|
|
187
|
+
}
|
|
188
|
+
try {
|
|
189
|
+
const result = await pool.gc(finished);
|
|
190
|
+
await pool.removeEmptyDir?.();
|
|
191
|
+
return result;
|
|
192
|
+
} finally { pool.close(); }
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
async markerOf(slotName: string): Promise<{ planId: PlanId; taskId: string } | null> {
|
|
196
|
+
const owners: Array<{ planId: PlanId; taskId: string }> = [];
|
|
197
|
+
for (const plan of await this.deps.store.list()) {
|
|
198
|
+
if (!sameToplevel(plan.toplevel, this.deps.toplevel) || (plan.status !== "running" && plan.status !== "paused")) continue;
|
|
199
|
+
for (const record of await this.of(plan.planId).list()) {
|
|
200
|
+
if (record.slot !== slotName && !sameToplevel(record.path, slotName)) continue;
|
|
201
|
+
const owner = record.state === "leased" && record.owner !== null ? /^plan:([^:]+):(.+)$/.exec(record.owner) : null;
|
|
202
|
+
if (owner?.[1] === plan.planId && owner[2] !== undefined) owners.push({ planId: plan.planId, taskId: owner[2] });
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
return owners.length === 1 ? owners[0] ?? null : null;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
async closeAll(): Promise<void> {
|
|
209
|
+
for (const entry of this.entries.values()) {
|
|
210
|
+
entry.closed = true;
|
|
211
|
+
try { (await entry.pool)?.close(); } catch { /* A failed open owns no live pool. */ }
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** A configured slotsDir is a root, not a shared plan directory (A-5.1-6). */
|
|
217
|
+
export function slotsDirOf(planId: PlanId, toplevel: string, root: string | null = null): string {
|
|
218
|
+
return root === null ? defaultSlotsDir(toplevel, planId) : join(root, planId);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
function checkSlotsDir(slotsDir: string, toplevel: string): void {
|
|
222
|
+
const result = validateSlotsDir(slotsDir, toplevel);
|
|
223
|
+
if (!result.ok) throw new ExecutorError("E_INVALID_INPUT", result.reason);
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** Approval must still target the branch tip captured by compile, before any integration worktree is created. */
|
|
227
|
+
async function checkBase(git: RuntimeDeps["git"], repo: LedgerV1["repo"]): Promise<void> {
|
|
228
|
+
const result = await git.run(["rev-parse", "--verify", `refs/heads/${repo.baseBranch}^{commit}`], { cwd: repo.toplevel, timeoutMs: 5_000 });
|
|
229
|
+
if (result.code !== 0) throw new ExecutorError("E_GIT", `could not read base branch ${repo.baseBranch}`);
|
|
230
|
+
const head = result.stdout.trim();
|
|
231
|
+
if (head !== repo.baseCommit) {
|
|
232
|
+
throw new ExecutorError("E_STALE_BASE", `base branch ${repo.baseBranch} moved ${repo.baseCommit}→${head} since compile; recompile`,
|
|
233
|
+
{ baseBranch: repo.baseBranch, old: repo.baseCommit, new: head });
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
const processClaimKey = Symbol.for("omr.executor.claim.v1");
|
|
238
|
+
/**
|
|
239
|
+
* QA-5.1-20: the retry callbacks of copies refused by the claim (a hot reload starts the new copy before the old one has
|
|
240
|
+
* disposed). Kept beside the claim on the same global record, under its own key, so the claim's shape stays what every
|
|
241
|
+
* loaded copy reads; a release calls each waiter once, and the waiters race for the claim through the same token check.
|
|
242
|
+
*/
|
|
243
|
+
const processClaimWaitersKey = Symbol.for("omr.executor.claim.waiters.v1");
|
|
244
|
+
const processClaims = globalThis as typeof globalThis & {
|
|
245
|
+
[processClaimKey]?: { token: symbol; toplevel: string };
|
|
246
|
+
[processClaimWaitersKey]?: Set<() => void>;
|
|
247
|
+
};
|
|
248
|
+
|
|
249
|
+
function claimWaiters(): Set<() => void> {
|
|
250
|
+
return processClaims[processClaimWaitersKey] ??= new Set();
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/** Frees the claim `token` holds (no-op for another holder's), then tells every refused copy that it may retry. */
|
|
254
|
+
function releaseClaim(token: symbol): void {
|
|
255
|
+
if (processClaims[processClaimKey]?.token !== token) return;
|
|
256
|
+
delete processClaims[processClaimKey];
|
|
257
|
+
for (const retry of [...claimWaiters()]) {
|
|
258
|
+
try { retry(); } catch { /* A waiter's failure is its own (it logs and clears its access). */ }
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/** No telemetry port: fixed tier priors, with the existing eight-minute prior as the middle tier. */
|
|
263
|
+
function staticTierDurations(cfg: Parameters<typeof resolveRoles>[0]): DurationModel {
|
|
264
|
+
const priors = { fast: DURATION_PRIOR_MS / 2, medium: DURATION_PRIOR_MS, heavy: DURATION_PRIOR_MS * 2 };
|
|
265
|
+
const models: Readonly<Record<string, DurationModel>> = Object.fromEntries(Object.entries(priors).map(([tier, priorMs]) =>
|
|
266
|
+
[tier, createDurationModel({ readTimings: () => [], now: () => 0 }, { priorMs })]));
|
|
267
|
+
const roles = resolveRoles(cfg, "v2"), names = Object.keys(priors);
|
|
268
|
+
const staticTiers: Readonly<Record<string, string | null>> = CLASS_STATIC_TIER;
|
|
269
|
+
return {
|
|
270
|
+
estimate(query) {
|
|
271
|
+
const requested = models[query.role] === undefined ? staticTiers[query.class] ?? cfg.defaultTier : query.role;
|
|
272
|
+
const role = roles.get(query.role);
|
|
273
|
+
const floor = role === undefined ? 0 : Math.max(0, names.indexOf(role.tierRange.floor));
|
|
274
|
+
const ceiling = role === undefined ? names.length - 1 : names.indexOf(role.tierRange.ceiling);
|
|
275
|
+
const index = Math.max(floor, Math.min(ceiling < 0 ? names.length - 1 : ceiling, Math.max(0, names.indexOf(requested))));
|
|
276
|
+
return (models[names[index] ?? "medium"] ?? models.medium!).estimate(query);
|
|
277
|
+
},
|
|
278
|
+
observe() {},
|
|
279
|
+
async load() {},
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
export interface CreateExecutorOptions {
|
|
284
|
+
observations?: V2Observations;
|
|
285
|
+
host: V2ExecutorHost;
|
|
286
|
+
prepared: PreparedExecutor;
|
|
287
|
+
access: ExecutorAccess;
|
|
288
|
+
annotate?: CompilerDeps["annotate"];
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/** The adapter starts the returned runtime; assembling it never starts recovery or opens a plan. */
|
|
292
|
+
export function createExecutor(
|
|
293
|
+
context: { routerHost: RouterHost; directory: string },
|
|
294
|
+
options: CreateExecutorOptions,
|
|
295
|
+
): V2Executor | null | undefined {
|
|
296
|
+
if (context.routerHost === "v1") return undefined;
|
|
297
|
+
return assembleExecutor(context, options);
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/**
|
|
301
|
+
* QA-5.1-20: a copy refused only by the process claim keeps its inputs and retries the assembly once the claim is free: at
|
|
302
|
+
* the release (the holder's dispose calls every waiter) or, failing that, the first time its `lateRuntime` is used. The
|
|
303
|
+
* waiters race for the claim through the same token check, so one wins; the others stay waiters.
|
|
304
|
+
* QA-5.1-26: the winner is handed to its adapter (`host.onExecutor`), which adopts it through the same path as an executor
|
|
305
|
+
* built at start: it registers the executor's providers and hooks, starts it once (its recovery runs once) and disposes it in
|
|
306
|
+
* the W7 order. A winner its adapter does not adopt (the adapter is already disposing) gets the safety dispose here.
|
|
307
|
+
*/
|
|
308
|
+
function waitForClaim(context: { directory: string }, options: CreateExecutorOptions): void {
|
|
309
|
+
const { access, host } = options;
|
|
310
|
+
const lifetime = host.lifetime;
|
|
311
|
+
if (access.deferRetry === undefined || lifetime.aborted) return;
|
|
312
|
+
const waiters = claimWaiters();
|
|
313
|
+
let spent = false;
|
|
314
|
+
// A copy that ends while it waits stops waiting: no executor is ever assembled for a disposed copy.
|
|
315
|
+
function forget(): void {
|
|
316
|
+
spent = true;
|
|
317
|
+
waiters.delete(retry);
|
|
318
|
+
access.deferRetry?.(null);
|
|
319
|
+
}
|
|
320
|
+
function retry(): void {
|
|
321
|
+
if (spent || lifetime.aborted || processClaims[processClaimKey] !== undefined) return;
|
|
322
|
+
lifetime.removeEventListener("abort", forget);
|
|
323
|
+
forget();
|
|
324
|
+
const built = assembleExecutor(context, options);
|
|
325
|
+
if (built === null) return;
|
|
326
|
+
let adopted = false;
|
|
327
|
+
try {
|
|
328
|
+
adopted = host.onExecutor(built);
|
|
329
|
+
} catch (error) {
|
|
330
|
+
console.warn("[model-router] executor: the adapter could not adopt it", String(error));
|
|
331
|
+
}
|
|
332
|
+
if (!adopted) void disposeUnadopted(built);
|
|
333
|
+
}
|
|
334
|
+
lifetime.addEventListener("abort", forget, { once: true });
|
|
335
|
+
waiters.add(retry);
|
|
336
|
+
access.deferRetry(retry);
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/**
|
|
340
|
+
* QA-5.1-26: the safety dispose of a handed-over executor its adapter did not adopt (it assembled after the adapter began to
|
|
341
|
+
* dispose): the runtime, then its launcher, as W7 orders them. The runtime's dispose releases the claim, whatever fails.
|
|
342
|
+
*/
|
|
343
|
+
async function disposeUnadopted(built: V2Executor): Promise<void> {
|
|
344
|
+
for (const [what, run] of [["runtime", () => built.runtime.dispose()], ["launcher", () => built.launcher.dispose()]] as const) {
|
|
345
|
+
try {
|
|
346
|
+
await run();
|
|
347
|
+
} catch (error) {
|
|
348
|
+
console.warn(`[model-router] executor: the ${what} could not be disposed`, String(error));
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
function assembleExecutor(context: { directory: string }, options: CreateExecutorOptions): V2Executor | null {
|
|
354
|
+
const { directory } = context;
|
|
355
|
+
const { host, prepared, access } = options;
|
|
356
|
+
const absent = (reason: string): null => { access.clear(reason); return null; };
|
|
357
|
+
const cfg = loadConfig(directory);
|
|
358
|
+
if (resolveRolesRouting(cfg, "v2").delegation !== "roles") return absent("routing.delegation must be roles at start");
|
|
359
|
+
if (resolveRouting(cfg, "v2").leases.mode !== "enforce") return absent("routing.leases.mode must be enforce");
|
|
360
|
+
if (host.verifier === null) return absent("no plan-task verifier");
|
|
361
|
+
if (cfg.enforcement?.verify?.require === "never") return absent("enforcement.verify.require is never");
|
|
362
|
+
if (!prepared.ok) return absent(prepared.reason);
|
|
363
|
+
if (host.leases === null) return absent("the lease registry is not available");
|
|
364
|
+
if (host.runner === null) return absent("the child runner is not available");
|
|
365
|
+
if (processClaims[processClaimKey] !== undefined) {
|
|
366
|
+
// QA-5.1-20: refused only by the claim (a hot reload's new copy, while the old one disposes): wait for its release.
|
|
367
|
+
waitForClaim(context, options);
|
|
368
|
+
return absent("another plan executor already owns this process");
|
|
369
|
+
}
|
|
370
|
+
const claim = Symbol("plan executor");
|
|
371
|
+
const { toplevel, home } = prepared;
|
|
372
|
+
processClaims[processClaimKey] = { token: claim, toplevel };
|
|
373
|
+
const clock = createNodeClock();
|
|
374
|
+
const fs = createNodeFileSystem();
|
|
375
|
+
const spawner = nodeSpawner();
|
|
376
|
+
const log: RuntimeDeps["log"] = (level, message, detail) => {
|
|
377
|
+
const write = level === "info" ? console.info : level === "warn" ? console.warn : console.error;
|
|
378
|
+
write(`[model-router] executor: ${message}`, ...(detail === undefined ? [] : [detail]));
|
|
379
|
+
};
|
|
380
|
+
const timers = new Set<{ readonly id: number }>();
|
|
381
|
+
let pools: PlanSlotPools | null = null;
|
|
382
|
+
let launcher: ReturnType<typeof createTaskLauncher> | null = null;
|
|
383
|
+
try {
|
|
384
|
+
const rawGit = createGitRunner({ mode: "hardened", toplevel });
|
|
385
|
+
const git: RuntimeDeps["git"] = { run: (args, opts) => rawGit.run([...hardeningArgs(), ...args], opts) };
|
|
386
|
+
const userGit = createGitRunner({ mode: "user", toplevel });
|
|
387
|
+
const store = createLedgerStore({ home, observations: options.observations });
|
|
388
|
+
const opsOf = (planId: PlanId) => createGitOps({ git, userGit, fs, planId, toplevel, executorHome: home });
|
|
389
|
+
pools = new PlanSlotPools({
|
|
390
|
+
store, toplevel, log,
|
|
391
|
+
markers: (planId) => countPlanMarkers({ fs, markersDir: join(home, "slots") }, planId),
|
|
392
|
+
makePool(ledger) {
|
|
393
|
+
const slotsDir = ledger.config.slotsDir ?? slotsDirOf(ledger.planId, toplevel);
|
|
394
|
+
checkSlotsDir(slotsDir, toplevel);
|
|
395
|
+
return createSlotPool({ planId: ledger.planId, repoKey: ledger.repo.key, toplevel, slotsDir,
|
|
396
|
+
markersDir: join(home, "slots"), executorHome: home, maxParallel: ledger.config.maxParallel,
|
|
397
|
+
git: opsOf(ledger.planId), fs, clock,
|
|
398
|
+
integrationHead: async () => (await store.read(ledger.planId)).integration.head,
|
|
399
|
+
provisioner: createProvisioner({ spawner, fs, clock, config: ledger.config,
|
|
400
|
+
host: { platform: process.platform, env: process.env, guards: workRootGuards(slotsDir) } }),
|
|
401
|
+
logger: { warn: (message) => log("warn", message) },
|
|
402
|
+
});
|
|
403
|
+
},
|
|
404
|
+
});
|
|
405
|
+
const planPools = pools;
|
|
406
|
+
const routes: RuntimeDeps["routes"] = {
|
|
407
|
+
route(task) {
|
|
408
|
+
const current = loadConfig(directory);
|
|
409
|
+
const roles = resolveRoles(current, "v2");
|
|
410
|
+
const role = roles.get(task.route.role);
|
|
411
|
+
if (role === undefined || !role.enabled) throw new ExecutorError("E_INVALID_INPUT", `unknown role ${task.route.role}`);
|
|
412
|
+
const tiers = resolveActiveTiers(current);
|
|
413
|
+
const names = Object.keys(tiers);
|
|
414
|
+
const floor = names.indexOf(role.tierRange.floor), ceiling = names.indexOf(role.tierRange.ceiling);
|
|
415
|
+
const requested = names.indexOf(task.route.tier ?? current.defaultTier);
|
|
416
|
+
if (floor < 0 || ceiling < floor || requested < 0) throw new ExecutorError("E_INVALID_INPUT", "role tier range is unavailable");
|
|
417
|
+
const tier = names[Math.max(floor, Math.min(ceiling, requested))];
|
|
418
|
+
const config = tier === undefined ? undefined : tiers[tier];
|
|
419
|
+
const model = config === undefined ? undefined : parseModelRef(config.model);
|
|
420
|
+
if (model === undefined || tier === undefined) throw new ExecutorError("E_INVALID_INPUT", "the task model is unavailable");
|
|
421
|
+
return { agent: role.agent, tier, model: { providerID: model.providerId, modelID: model.modelId, variant: config?.variant ?? null },
|
|
422
|
+
provider: model.providerId, heavy: tier === "heavy" };
|
|
423
|
+
},
|
|
424
|
+
};
|
|
425
|
+
const roleOf: CompilerDeps["roleOf"] = (route, tier) => {
|
|
426
|
+
const roles = resolveRoles(loadConfig(directory), "v2");
|
|
427
|
+
const kind = tier === "heavy" && route?.class === undefined ? "review" : CLASS_ROLE_KIND[route?.class ?? "other"];
|
|
428
|
+
const candidates = [...roles.values()].filter((role) => role.enabled).sort((a, b) => a.agent.localeCompare(b.agent));
|
|
429
|
+
const chosen = candidates.find((role) => role.kind === kind) ?? candidates.find((role) => role.kind === "general");
|
|
430
|
+
if (chosen === undefined) throw new ExecutorError("E_INVALID_INPUT", `no enabled role for ${kind}`);
|
|
431
|
+
return chosen;
|
|
432
|
+
};
|
|
433
|
+
const innerCompiler = createPlanCompiler({
|
|
434
|
+
fs,
|
|
435
|
+
git: { async run(args, cwd) { const r = await git.run(args, { cwd, timeoutMs: 5_000 }); return { code: r.code ?? -1, stdout: r.stdout }; } },
|
|
436
|
+
durations: host.durations ?? staticTierDurations(cfg),
|
|
437
|
+
annotate: options.annotate ?? (async (steps) => {
|
|
438
|
+
const current = loadConfig(directory), routing = resolveRouting(current, "v2");
|
|
439
|
+
return annotateSteps(steps, { cfg: current, routing, agents: null, store: null,
|
|
440
|
+
classifyMany: (inputs) => classifyMany(inputs, { cfg: current, settings: { ...routing.classifier, backend: "rules" },
|
|
441
|
+
minClassConfidence: routing.minClassConfidence, backend: null, logger: { warn: (message) => log("warn", message) }, routeLinePositions: "any" }),
|
|
442
|
+
});
|
|
443
|
+
}),
|
|
444
|
+
roleOf,
|
|
445
|
+
integrationWorktree: (id) => join(slotsDirOf(id, toplevel, resolveRouting(loadConfig(directory), "v2").executor.slotsDir), "integration"),
|
|
446
|
+
});
|
|
447
|
+
const compiler: RuntimeDeps["compiler"] = {
|
|
448
|
+
...innerCompiler,
|
|
449
|
+
async compile(path, opts) {
|
|
450
|
+
const result = await innerCompiler.compile(path, opts);
|
|
451
|
+
if (!sameToplevel(result.draft.repo.toplevel, toplevel)) throw new ExecutorError("E_INVALID_INPUT", "the plan belongs to another repository");
|
|
452
|
+
const slotsDir = slotsDirOf(result.draft.planId, toplevel, resolveRouting(loadConfig(directory), "v2").executor.slotsDir);
|
|
453
|
+
result.draft.config.slotsDir = slotsDir;
|
|
454
|
+
if (!sameToplevel(result.draft.integration.worktree, join(slotsDir, "integration"))) {
|
|
455
|
+
throw new ExecutorError("E_INVALID_INPUT", "the integration worktree does not match the plan slots directory");
|
|
456
|
+
}
|
|
457
|
+
checkSlotsDir(slotsDir, toplevel);
|
|
458
|
+
return result;
|
|
459
|
+
},
|
|
460
|
+
};
|
|
461
|
+
let runtime: ExecutorRuntimeHandle | null = null;
|
|
462
|
+
const innerLauncher = createTaskLauncher({ runner: host.runner, hosts: host.hosts, bindings: host.bindings,
|
|
463
|
+
bookkeeping: host.bookkeeping, clock, lifetime: host.lifetime, knownAgent: host.knownAgent,
|
|
464
|
+
onMetric: (id, metric) => host.onLauncherMetric(id, metric),
|
|
465
|
+
});
|
|
466
|
+
let launcherDisposal: Promise<void> | null = null;
|
|
467
|
+
launcher = { ...innerLauncher, dispose: () => launcherDisposal ??= innerLauncher.dispose() };
|
|
468
|
+
const taskLauncher = launcher;
|
|
469
|
+
const resolver = createRunResolver(() => resolveRolesRouting(loadConfig(directory), "v2").run);
|
|
470
|
+
const buildQueue: Parameters<typeof realCollaborators>[0]["queue"] = (input) => {
|
|
471
|
+
const planId = input.writer.planId;
|
|
472
|
+
const pool = planPools.of(planId), ops = opsOf(planId);
|
|
473
|
+
const guard = createWriteGuard({ ledger: () => input.writer.ledger, pool, realpath, platform: process.platform });
|
|
474
|
+
const igit = createIntegrateGit(git, guard), background = new BackgroundRuns();
|
|
475
|
+
const logger = { warn: (message: string) => log("warn", `queue: ${message}`) };
|
|
476
|
+
const checks = createIntegrationChecks({ ledger: () => input.writer.ledger, pool, git: ops, igit, resolver, guard, background, clock, logger,
|
|
477
|
+
spawn: async (command, opts) => {
|
|
478
|
+
const start = clock.now();
|
|
479
|
+
const result = await runArgv(command.file, command.args, { cwd: command.cwd ?? opts.cwd, env: command.env,
|
|
480
|
+
...(command.envMode === undefined ? {} : { envMode: command.envMode }),
|
|
481
|
+
...(opts.service === undefined ? {} : { service: opts.service }),
|
|
482
|
+
signal: opts.signal, lowPriority: opts.lowPriority, timeoutMs: resolveRolesRouting(loadConfig(directory), "v2").run.timeoutMs });
|
|
483
|
+
return { exitCode: result.code, timedOut: result.timedOut, stdout: result.stdout, stderr: result.stderr, durationMs: clock.now() - start };
|
|
484
|
+
},
|
|
485
|
+
});
|
|
486
|
+
const suite = createPhaseSuiteRunner({ checks, igit, git: ops, pool, resolver, background, clock, logger });
|
|
487
|
+
const lander = createLander({ git: ops, igit, guard, run: git, realpath, platform: process.platform });
|
|
488
|
+
const queue = createIntegrationQueue({ planId, writer: input.writer,
|
|
489
|
+
history: { steps: async () => (await store.exportPlan(planId)).events.filter((event): event is IntegrationStepEvent => event.type === "integration-step") },
|
|
490
|
+
git: ops, igit, pool, leases: input.leases, checks, suite, lander, listener: input.listener,
|
|
491
|
+
settle: (taskId, release) => {
|
|
492
|
+
const poll = (): void => {
|
|
493
|
+
// G-1: a child recovery adopted after a restart is in no launcher flight; the runtime still reports it live
|
|
494
|
+
// until it is stopped (or its slot held).
|
|
495
|
+
if (!taskLauncher.inFlight().some((flight) => flight.taskId === taskId) && runtime?.childLive?.(planId, taskId) !== true) {
|
|
496
|
+
void release().catch((error: unknown) => log("warn", "settled release failed", String(error)));
|
|
497
|
+
return;
|
|
498
|
+
}
|
|
499
|
+
const timer = clock.setTimer(100, () => { timers.delete(timer); poll(); });
|
|
500
|
+
timers.add(timer);
|
|
501
|
+
};
|
|
502
|
+
poll();
|
|
503
|
+
},
|
|
504
|
+
// M1: the runtime saves a blocked dependent's slot before its release (it always supplies the hook).
|
|
505
|
+
releaseSlot: input.releaseSlot ?? ((_taskId, slot) => pool.release(slot)),
|
|
506
|
+
locks: createRepoLockFactory({ stateRoot: join(home, "locks"), clock, pid: spawner.pid, hostname: spawner.hostname, isPidAlive: spawner.isAlive, logger }),
|
|
507
|
+
guard, clock, logger,
|
|
508
|
+
});
|
|
509
|
+
return {
|
|
510
|
+
enqueue: (ids) => queue.enqueue(ids), checkPhase: (id) => queue.checkPhase(id), land: () => queue.land(),
|
|
511
|
+
abort: () => queue.abort(), queued: () => queue.queued(), dispose: () => queue.dispose(),
|
|
512
|
+
async resume() {
|
|
513
|
+
const ledger = input.writer.ledger, ref = `refs/heads/${ledger.integration.branch}`;
|
|
514
|
+
if (await igit.readRef(toplevel, ref) === null) {
|
|
515
|
+
const result = await git.run(["update-ref", ref, ledger.integration.head, "0".repeat(ledger.integration.head.length)], { cwd: toplevel, timeoutMs: 5_000 });
|
|
516
|
+
if (result.code !== 0 && await igit.readRef(toplevel, ref) === null) throw new ExecutorError("E_GIT", "could not create the integration branch");
|
|
517
|
+
}
|
|
518
|
+
await pool.acquireSpecial(planId, "integration");
|
|
519
|
+
return queue.resume();
|
|
520
|
+
},
|
|
521
|
+
};
|
|
522
|
+
};
|
|
523
|
+
const leases = host.leases;
|
|
524
|
+
const holder: RuntimeDeps["holder"] = (sessionID) => {
|
|
525
|
+
const now = clock.iso();
|
|
526
|
+
return { sessionID, pid: spawner.pid, hostname: spawner.hostname, startedAt: now, heartbeatAt: now };
|
|
527
|
+
};
|
|
528
|
+
const self = processIdentity();
|
|
529
|
+
runtime = createExecutorRuntime({ store, compiler, self, executorHome: home,
|
|
530
|
+
observations: options.observations,
|
|
531
|
+
slots: planPools.facade, slotsFor: (id) => planPools.of(id), purgeSlots: (id, finished) => planPools.purge(id, finished),
|
|
532
|
+
scheduler: createScheduler(), launcher: taskLauncher, routes, verifier: host.verifier, git, hosts: host.hosts, bindings: host.bindings, clock,
|
|
533
|
+
leaseRegistry: { acquireWrite: (owner, writes) => {
|
|
534
|
+
const result = leases.registry.acquireWrite(owner, writes);
|
|
535
|
+
if (result.ok) return { ok: true };
|
|
536
|
+
if (result.reason === "held" || result.reason === "unknown-target") {
|
|
537
|
+
return { ok: false, reason: result.reason, holders: result.holders.map((holder) => ({ holderID: holder.holderID, taskRef: holder.taskRef ?? null })) };
|
|
538
|
+
}
|
|
539
|
+
if (result.reason === "cap") return { ok: false, reason: "cap", message: `lease registry capacity reached (${result.held}/${result.limit})` };
|
|
540
|
+
return { ok: false, reason: "invalid", message: result.message };
|
|
541
|
+
},
|
|
542
|
+
holderOf: (path) => {
|
|
543
|
+
const holder = leases.registry.planHolderOf(toplevel, path);
|
|
544
|
+
return holder === null ? null : { holderID: holder.holderID, taskRef: holder.taskRef ?? null };
|
|
545
|
+
},
|
|
546
|
+
releaseTask: (ref) => { leases.registry.releaseTask(ref); leases.notifyReleased(); } },
|
|
547
|
+
recovery: createRecoveryService({ store, host: host.hosts, toplevel, holder, slotMarker: (slot) => planPools.markerOf(slot), clock, log,
|
|
548
|
+
launcherLiveness: { self, isAlive: spawner.isAlive } }),
|
|
549
|
+
holder, capacity: createCapacityController, collaborators: realCollaborators({ queue: buildQueue, clock, log }),
|
|
550
|
+
pinOrchestrator: host.pinOrchestrator, log,
|
|
551
|
+
config: () => ({ ...resolveRouting(loadConfig(directory), "v2").executor, slotsDir: null }), toplevel,
|
|
552
|
+
async checkSlotsDir(slotsDir, repoToplevel, planId?: PlanId) {
|
|
553
|
+
checkSlotsDir(slotsDir, repoToplevel);
|
|
554
|
+
if (planId === undefined) throw new ExecutorError("E_PLAN_STATE", "approval validation requires the plan id");
|
|
555
|
+
const ledger = await store.read(planId);
|
|
556
|
+
await checkBase(git, ledger.repo);
|
|
557
|
+
},
|
|
558
|
+
});
|
|
559
|
+
const innerRuntime = runtime;
|
|
560
|
+
let disposal: Promise<void> | null = null;
|
|
561
|
+
let starting: Promise<void> | null = null;
|
|
562
|
+
const wrapped: ExecutorRuntimeHandle = { ...innerRuntime,
|
|
563
|
+
// QA-5.1-20: recovery runs once per runtime, whoever starts it (the adapter, a claim retry or a late port).
|
|
564
|
+
start() {
|
|
565
|
+
starting ??= innerRuntime.start();
|
|
566
|
+
return starting;
|
|
567
|
+
},
|
|
568
|
+
dispose() {
|
|
569
|
+
disposal ??= (async () => {
|
|
570
|
+
access.clear("disposed");
|
|
571
|
+
try { await innerRuntime.dispose(); }
|
|
572
|
+
finally {
|
|
573
|
+
try { await planPools.closeAll(); }
|
|
574
|
+
finally { for (const timer of timers) clock.clearTimer(timer); timers.clear(); releaseClaim(claim); }
|
|
575
|
+
}
|
|
576
|
+
})();
|
|
577
|
+
return disposal;
|
|
578
|
+
} };
|
|
579
|
+
access.set(wrapped);
|
|
580
|
+
return { runtime: wrapped, launcher: taskLauncher };
|
|
581
|
+
} catch (error) {
|
|
582
|
+
void launcher?.dispose();
|
|
583
|
+
void pools?.closeAll();
|
|
584
|
+
for (const timer of timers) clock.clearTimer(timer);
|
|
585
|
+
const failed = absent(`assembly failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
586
|
+
releaseClaim(claim);
|
|
587
|
+
return failed;
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
export type PreparedExecutor = { ok: true; toplevel: string; home: string } | { ok: false; reason: string };
|
|
592
|
+
|
|
593
|
+
/** Discovery only: no ledger, worktree, marker or executor directory is created. */
|
|
594
|
+
export async function prepareExecutor(directory: string): Promise<PreparedExecutor> {
|
|
595
|
+
try {
|
|
596
|
+
const git = createGitRunner({ mode: "hardened", toplevel: directory });
|
|
597
|
+
const run = (args: readonly string[], cwd: string) => git.run([...hardeningArgs(), ...args], { cwd, timeoutMs: 5_000 });
|
|
598
|
+
const result = await run(["rev-parse", "--show-toplevel"], directory);
|
|
599
|
+
if (result.code !== 0 || result.stdout.trim() === "") return { ok: false, reason: "not a git repository" };
|
|
600
|
+
const toplevel = realpathSync.native(result.stdout.trim());
|
|
601
|
+
const home = await resolveExecutorHome(toplevel, { git: run, realpath: async (path) => realpathSync.native(path) });
|
|
602
|
+
return { ok: true, toplevel, home };
|
|
603
|
+
} catch (error) {
|
|
604
|
+
return { ok: false, reason: `repository discovery failed: ${error instanceof Error ? error.message : String(error)}` };
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
export interface ExecutorAccess {
|
|
609
|
+
runtime(): ExecutorRuntime | null;
|
|
610
|
+
unavailable(): string;
|
|
611
|
+
set(runtime: ExecutorRuntime): void;
|
|
612
|
+
clear(reason: string): void;
|
|
613
|
+
/**
|
|
614
|
+
* QA-5.1-20: the assembly retry of a copy refused only by the process claim (null: none). `runtime()` runs it, at most
|
|
615
|
+
* once per claim release, when it finds no runtime; `createExecutor` sets it.
|
|
616
|
+
*/
|
|
617
|
+
deferRetry?(retry: (() => void) | null): void;
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
/** Tool/command ports resolve the current executor at call time, not plugin initialization. */
|
|
621
|
+
export function lateRuntime(access: ExecutorAccess): ExecutorRuntime {
|
|
622
|
+
const get = (): ExecutorRuntime => {
|
|
623
|
+
const runtime = access.runtime();
|
|
624
|
+
if (runtime === null) throw new ExecutorError("E_PLAN_STATE", access.unavailable());
|
|
625
|
+
return runtime;
|
|
626
|
+
};
|
|
627
|
+
return {
|
|
628
|
+
compile: (...args) => get().compile(...args),
|
|
629
|
+
residue: (...args) => get().residue(...args),
|
|
630
|
+
approve: (...args) => get().approve(...args),
|
|
631
|
+
status: (...args) => get().status(...args),
|
|
632
|
+
ready: (...args) => get().ready(...args),
|
|
633
|
+
addTasks: (...args) => get().addTasks(...args),
|
|
634
|
+
answer: (...args) => get().answer(...args),
|
|
635
|
+
done: (...args) => get().done(...args),
|
|
636
|
+
pause: (...args) => get().pause(...args),
|
|
637
|
+
resume: (...args) => get().resume(...args),
|
|
638
|
+
abort: (...args) => get().abort(...args),
|
|
639
|
+
land: (...args) => get().land(...args),
|
|
640
|
+
adopt: (...args) => get().adopt(...args),
|
|
641
|
+
gc: () => get().gc(),
|
|
642
|
+
exportPlan: (...args) => get().exportPlan(...args),
|
|
643
|
+
purge: (...args) => get().purge(...args),
|
|
644
|
+
onRouterToolCall: (...args) => get().onRouterToolCall(...args),
|
|
645
|
+
onHostEvent: (...args) => get().onHostEvent(...args),
|
|
646
|
+
onRetryHook: (...args) => get().onRetryHook(...args),
|
|
647
|
+
onChildEnd: (...args) => get().onChildEnd(...args),
|
|
648
|
+
planLine: (sessionID) => access.runtime()?.planLine(sessionID) ?? null,
|
|
649
|
+
start: async () => { await access.runtime()?.start(); },
|
|
650
|
+
dispose: async () => { await access.runtime()?.dispose(); },
|
|
651
|
+
};
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
export function createExecutorAccess(): ExecutorAccess {
|
|
655
|
+
let current: ExecutorRuntime | null = null;
|
|
656
|
+
let reason = "the plan executor is not available: not initialized";
|
|
657
|
+
let retry: (() => void) | null = null;
|
|
658
|
+
return {
|
|
659
|
+
runtime: () => {
|
|
660
|
+
// QA-5.1-20: no runtime yet, and refused by the claim: retry the assembly now if the claim is free (else it waits).
|
|
661
|
+
if (current === null && retry !== null) retry();
|
|
662
|
+
return current;
|
|
663
|
+
},
|
|
664
|
+
unavailable: () => reason,
|
|
665
|
+
set(runtime) { current = runtime; },
|
|
666
|
+
clear(why) {
|
|
667
|
+
current = null;
|
|
668
|
+
reason = `the plan executor is not available: ${why}`;
|
|
669
|
+
},
|
|
670
|
+
deferRetry(next) { retry = next; },
|
|
671
|
+
};
|
|
672
|
+
}
|