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,853 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Slot provisioning (Phase 2.4.4, memo section 5): detects the package managers of a slot's
|
|
3
|
+
* checkout, plans their install commands (argv arrays, never a shell) and runs them under a
|
|
4
|
+
* machine-wide lock per manager, with bounded output and a timeout per step.
|
|
5
|
+
*/
|
|
6
|
+
import { createHash } from "node:crypto";
|
|
7
|
+
import { homedir } from "node:os";
|
|
8
|
+
import { posix, win32 } from "node:path";
|
|
9
|
+
import { envLookup, firstOutside, isFullPath, isInside, realFileOrUndefined, stripUrlUserinfo } from "../../router/git-tools";
|
|
10
|
+
import {
|
|
11
|
+
isCredentialEnv, npmConfigPins, npmHardeningFlags, resolveNodeExecutable, resolveNpmCli, resolveSystemShell, runEnvironment,
|
|
12
|
+
type RunHost,
|
|
13
|
+
} from "../../router/run-tools";
|
|
14
|
+
import { CLEANUP_RETRIES, CLEANUP_RETRY_BASE_MS, DEPENDENCY_FILES, TRANSIENT_FS_CODES } from "../../verify/reference";
|
|
15
|
+
import {
|
|
16
|
+
ExecutorError, type Clock, type ExecutorConfig, type FileSystem, type ProcessResult, type SlotRecord, type Spawner,
|
|
17
|
+
} from "../types";
|
|
18
|
+
|
|
19
|
+
export type Manager = "pnpm" | "npm" | "yarn" | "uv" | "poetry" | "pip";
|
|
20
|
+
|
|
21
|
+
const NODE_MANAGERS: readonly Manager[] = ["npm", "pnpm", "yarn"];
|
|
22
|
+
const PYTHON_MANAGERS: readonly Manager[] = ["pip", "poetry", "uv"];
|
|
23
|
+
const ALL_MANAGERS: readonly Manager[] = ["npm", "pip", "pnpm", "poetry", "uv", "yarn"];
|
|
24
|
+
|
|
25
|
+
function isManager(name: string): name is Manager {
|
|
26
|
+
return (ALL_MANAGERS as readonly string[]).includes(name);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function baseName(repoPath: string): string {
|
|
30
|
+
return repoPath.split("/").at(-1) ?? "";
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Tracked paths under a dependency directory are never manifests. */
|
|
34
|
+
function underDependencyDir(repoPath: string): boolean {
|
|
35
|
+
return repoPath.split("/").slice(0, -1).some((segment) => segment === "node_modules" || segment === ".venv");
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Node: DEPENDENCY_FILES basenames at any depth; pip: requirements*.txt, pyproject.toml, setup.py, setup.cfg;
|
|
40
|
+
* uv: uv.lock, pyproject.toml; poetry: poetry.lock, pyproject.toml. Matched against the slot's tracked paths
|
|
41
|
+
* (`git ls-files -z`), never under node_modules/ or .venv/.
|
|
42
|
+
*/
|
|
43
|
+
export const PROVISION_MANIFESTS: Readonly<Record<Manager, (repoPath: string) => boolean>> = {
|
|
44
|
+
npm: (p) => !underDependencyDir(p) && DEPENDENCY_FILES.has(baseName(p)),
|
|
45
|
+
pnpm: (p) => !underDependencyDir(p) && (DEPENDENCY_FILES.has(baseName(p)) || p === "pnpm-workspace.yaml"),
|
|
46
|
+
yarn: (p) => !underDependencyDir(p) && DEPENDENCY_FILES.has(baseName(p)),
|
|
47
|
+
pip: (p) => !underDependencyDir(p)
|
|
48
|
+
&& (/^requirements.*\.txt$/.test(baseName(p)) || ["pyproject.toml", "setup.py", "setup.cfg"].includes(baseName(p))),
|
|
49
|
+
uv: (p) => !underDependencyDir(p) && ["uv.lock", "pyproject.toml"].includes(baseName(p)),
|
|
50
|
+
poetry: (p) => !underDependencyDir(p) && ["poetry.lock", "pyproject.toml"].includes(baseName(p)),
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
/** The directory each manager installs into, relative to the slot root. */
|
|
54
|
+
export const DEPENDENCY_DIRS: Readonly<Record<Manager, readonly string[]>> = {
|
|
55
|
+
npm: ["node_modules"], pnpm: ["node_modules"], yarn: ["node_modules"],
|
|
56
|
+
pip: [".venv"], uv: [".venv"], poetry: [".venv"],
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
/** Managers whose install does not prune: `fresh` deletes these directories first. */
|
|
60
|
+
const FRESH_REMOVES: Readonly<Partial<Record<Manager, string>>> = { pip: ".venv", poetry: ".venv" };
|
|
61
|
+
|
|
62
|
+
export const PROVISION_STEP_TIMEOUT_MS = 1_200_000;
|
|
63
|
+
/** Output kept per step: head and tail. */
|
|
64
|
+
export const PROVISION_OUTPUT_KEEP_BYTES = 16 * 1024;
|
|
65
|
+
const PROBE_TIMEOUT_MS = 60_000;
|
|
66
|
+
const TAIL_LINES = 12;
|
|
67
|
+
/** Entries one recursive slot sweep may visit before it refuses (provisioning and the pool share it). */
|
|
68
|
+
export const SLOT_SWEEP_MAX_ENTRIES = 2_000_000;
|
|
69
|
+
const LOCK_HEARTBEAT_MS = 10_000;
|
|
70
|
+
const LOCK_STALE_MS = 60_000;
|
|
71
|
+
const LOCK_STALE_RECHECK_MS = 1_000;
|
|
72
|
+
const LOCK_POLL_MIN_MS = 500;
|
|
73
|
+
const LOCK_POLL_MAX_MS = 5_000;
|
|
74
|
+
|
|
75
|
+
export interface Detection {
|
|
76
|
+
managers: Manager[];
|
|
77
|
+
yarnBerry: boolean;
|
|
78
|
+
editable: boolean;
|
|
79
|
+
/** Repo-relative manifest path -> sha256 of the on-disk bytes. */
|
|
80
|
+
manifests: Record<string, string>;
|
|
81
|
+
python: string | null;
|
|
82
|
+
/** Yarn berry: the `yarnPath` of `.yarnrc.yml` (slot-relative), when it names one. */
|
|
83
|
+
yarnPath?: string;
|
|
84
|
+
/** The slot tracks a root `pnpm-workspace.yaml`: pnpm then keeps its workspace instead of ignoring it. */
|
|
85
|
+
pnpmWorkspace?: boolean;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function fail(message: string, detail: Record<string, string | number> = {}): ExecutorError {
|
|
89
|
+
return new ExecutorError("E_PROVISION", message, detail);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function overrideKeys(config: Pick<ExecutorConfig, "provision">): Manager[] {
|
|
93
|
+
return config.provision === "auto" ? [] : Object.keys(config.provision).filter(isManager);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
async function readOptional(fs: FileSystem, path: string): Promise<string | null> {
|
|
97
|
+
const st = await fs.lstat(path);
|
|
98
|
+
if (st === null || st.kind !== "file") return null;
|
|
99
|
+
return fs.readText(path);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function hasDependencies(pkg: unknown): boolean {
|
|
103
|
+
if (typeof pkg !== "object" || pkg === null) return false;
|
|
104
|
+
for (const field of ["dependencies", "devDependencies", "optionalDependencies", "peerDependencies"]) {
|
|
105
|
+
const value: unknown = Reflect.get(pkg, field);
|
|
106
|
+
if (typeof value === "object" && value !== null && Object.keys(value).length > 0) return true;
|
|
107
|
+
}
|
|
108
|
+
return false;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
async function detectNode(slot: string, tracked: ReadonlySet<string>, fs: FileSystem, forced: readonly Manager[]): Promise<Manager[]> {
|
|
112
|
+
const fromOverride = forced.filter((m) => NODE_MANAGERS.includes(m));
|
|
113
|
+
if (fromOverride.length > 0) return fromOverride;
|
|
114
|
+
let pkg: unknown = null;
|
|
115
|
+
if (tracked.has("package.json")) {
|
|
116
|
+
const text = await readOptional(fs, joinPath(slot, "package.json"));
|
|
117
|
+
if (text !== null) {
|
|
118
|
+
try {
|
|
119
|
+
pkg = JSON.parse(text);
|
|
120
|
+
} catch (error) {
|
|
121
|
+
throw fail(`package.json in ${slot} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
const declared: unknown = typeof pkg === "object" && pkg !== null ? Reflect.get(pkg, "packageManager") : undefined;
|
|
126
|
+
if (typeof declared === "string") {
|
|
127
|
+
const name = declared.split("@")[0] ?? "";
|
|
128
|
+
if (name === "pnpm" || name === "npm" || name === "yarn") return [name];
|
|
129
|
+
}
|
|
130
|
+
const lockfiles: Array<[string, Manager]> = [["pnpm-lock.yaml", "pnpm"], ["package-lock.json", "npm"], ["yarn.lock", "yarn"]];
|
|
131
|
+
const present = lockfiles.filter(([file]) => tracked.has(file));
|
|
132
|
+
// A Node manager looks for its project upward from the slot: without a root package.json it could adopt one outside.
|
|
133
|
+
if (present.length > 0 && pkg === null) {
|
|
134
|
+
throw fail(`lockfile without package.json at ${slot} (${present.map(([file]) => file).join(", ")}); commit a package.json at the repository root or set executor.provision`);
|
|
135
|
+
}
|
|
136
|
+
if (present.length === 1) return [present[0]![1]];
|
|
137
|
+
if (present.length > 1) {
|
|
138
|
+
throw fail(`ambiguous lockfiles in ${slot} (${present.map(([file]) => file).join(", ")}); set packageManager or executor.provision`);
|
|
139
|
+
}
|
|
140
|
+
if (pkg !== null && hasDependencies(pkg)) {
|
|
141
|
+
throw fail(`package.json in ${slot} declares dependencies but no lockfile is committed; commit a lockfile (pnpm-lock.yaml, package-lock.json or yarn.lock)`);
|
|
142
|
+
}
|
|
143
|
+
return [];
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
interface PythonProject { managers: Manager[]; editable: boolean }
|
|
147
|
+
|
|
148
|
+
async function detectPython(slot: string, tracked: ReadonlySet<string>, fs: FileSystem, forced: readonly Manager[]): Promise<PythonProject> {
|
|
149
|
+
const pyproject = tracked.has("pyproject.toml") ? await readOptional(fs, joinPath(slot, "pyproject.toml")) : null;
|
|
150
|
+
const buildSystem = pyproject !== null && /^\s*\[build-system\]/m.test(pyproject);
|
|
151
|
+
const backend = pyproject === null ? null : /^\s*build-backend\s*=\s*["']([^"']+)["']/m.exec(pyproject)?.[1] ?? null;
|
|
152
|
+
const editable = backend === "setuptools.build_meta" || (backend === null && tracked.has("setup.py"));
|
|
153
|
+
// uv and poetry look for their project upward from the slot: without a root pyproject.toml they could adopt one outside.
|
|
154
|
+
const needRoot = (managers: readonly Manager[]): void => {
|
|
155
|
+
const rooted = managers.filter((m) => m === "uv" || m === "poetry");
|
|
156
|
+
if (rooted.length > 0 && pyproject === null) {
|
|
157
|
+
throw fail(`${rooted.join(", ")} needs a pyproject.toml at the repository root of ${slot}; commit one or set executor.provision`, { manager: rooted[0]! });
|
|
158
|
+
}
|
|
159
|
+
};
|
|
160
|
+
const fromOverride = forced.filter((m) => PYTHON_MANAGERS.includes(m));
|
|
161
|
+
// An override carries its own argv, so it is not held to the root pyproject.toml.
|
|
162
|
+
if (fromOverride.length > 0) return { managers: fromOverride, editable: fromOverride.includes("pip") && editable };
|
|
163
|
+
if (tracked.has("uv.lock")) {
|
|
164
|
+
needRoot(["uv"]);
|
|
165
|
+
return { managers: ["uv"], editable: false };
|
|
166
|
+
}
|
|
167
|
+
if (tracked.has("poetry.lock")) {
|
|
168
|
+
needRoot(["poetry"]);
|
|
169
|
+
return { managers: ["poetry"], editable: false };
|
|
170
|
+
}
|
|
171
|
+
if (tracked.has("requirements.txt") || buildSystem) return { managers: ["pip"], editable };
|
|
172
|
+
return { managers: [], editable: false };
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function sha256(text: string): string {
|
|
176
|
+
return createHash("sha256").update(text, "utf8").digest("hex");
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function joinPath(root: string, rel: string): string {
|
|
180
|
+
const api = /^[A-Za-z]:[\\/]|^[\\/]{2}/.test(root) ? win32 : posix;
|
|
181
|
+
return api.join(root, ...rel.split("/"));
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** Which managers a slot needs, and the manifests whose change triggers re-provisioning. */
|
|
185
|
+
export async function detectManagers(slot: string, tracked: readonly string[], fs: FileSystem,
|
|
186
|
+
config: Pick<ExecutorConfig, "provision" | "python">): Promise<Detection> {
|
|
187
|
+
const usable = tracked.filter((p) => !underDependencyDir(p));
|
|
188
|
+
const set = new Set(usable);
|
|
189
|
+
const forced = overrideKeys(config);
|
|
190
|
+
const node = await detectNode(slot, set, fs, forced);
|
|
191
|
+
const python = await detectPython(slot, set, fs, forced);
|
|
192
|
+
const managers = [...node, ...python.managers].sort();
|
|
193
|
+
const yarnrc = managers.includes("yarn") ? await readOptional(fs, joinPath(slot, ".yarnrc.yml")) : null;
|
|
194
|
+
const yarnBerry = yarnrc !== null;
|
|
195
|
+
const yarnPath = yarnrc === null ? undefined : /^\s*yarnPath:\s*["']?([^"'\r\n#]+?)["']?\s*(?:#.*)?$/m.exec(yarnrc)?.[1];
|
|
196
|
+
const manifests: Record<string, string> = {};
|
|
197
|
+
for (const manager of managers) {
|
|
198
|
+
for (const rel of usable) {
|
|
199
|
+
if (!PROVISION_MANIFESTS[manager](rel) || rel in manifests) continue;
|
|
200
|
+
const text = await readOptional(fs, joinPath(slot, rel));
|
|
201
|
+
if (text !== null) manifests[rel] = sha256(text);
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
return {
|
|
205
|
+
managers, yarnBerry, editable: python.editable, manifests,
|
|
206
|
+
python: config.python === "auto" ? null : config.python,
|
|
207
|
+
...(yarnPath === undefined ? {} : { yarnPath }),
|
|
208
|
+
...(managers.includes("pnpm") && set.has("pnpm-workspace.yaml") ? { pnpmWorkspace: true } : {}),
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/** True when the slot's recorded managers or manifests differ from what is detected now. */
|
|
213
|
+
export function needsProvision(rec: Pick<SlotRecord, "managers" | "manifests">, d: Detection): boolean {
|
|
214
|
+
const recorded = [...rec.managers].sort();
|
|
215
|
+
if (recorded.length !== d.managers.length || recorded.some((m, i) => m !== d.managers[i])) return true;
|
|
216
|
+
const have = Object.keys(rec.manifests);
|
|
217
|
+
const want = Object.keys(d.manifests);
|
|
218
|
+
if (have.length !== want.length) return true;
|
|
219
|
+
return want.some((path) => rec.manifests[path] !== d.manifests[path]);
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
export interface ProvisionStep {
|
|
223
|
+
manager: Manager;
|
|
224
|
+
command: string;
|
|
225
|
+
args: string[];
|
|
226
|
+
env: Record<string, string>;
|
|
227
|
+
cwd: string;
|
|
228
|
+
timeoutMs: number;
|
|
229
|
+
label: string;
|
|
230
|
+
/** Run the step only when `command <condition>` (same env and cwd) exits 0. */
|
|
231
|
+
condition?: string[];
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
export interface ProvisionHost {
|
|
235
|
+
env: NodeJS.ProcessEnv;
|
|
236
|
+
platform: NodeJS.Platform;
|
|
237
|
+
nodeExecPath?: string;
|
|
238
|
+
/** workRootGuards(slot): no tool binary may live inside these (G4). */
|
|
239
|
+
guards: readonly string[];
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
type Provision = Pick<ExecutorConfig, "provision" | "python">;
|
|
243
|
+
|
|
244
|
+
function api(platform: NodeJS.Platform) {
|
|
245
|
+
return platform === "win32" ? win32 : posix;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/** run-tools throws plain refusals; surface them as E_PROVISION with the same text. */
|
|
249
|
+
function resolving<T>(what: string, fn: () => T): T {
|
|
250
|
+
try {
|
|
251
|
+
return fn();
|
|
252
|
+
} catch (error) {
|
|
253
|
+
throw fail(`${what}: ${error instanceof Error ? error.message : String(error)}`);
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
function pathDirs(host: ProvisionHost): string[] {
|
|
258
|
+
const raw = envLookup(host.env, "PATH") ?? "";
|
|
259
|
+
return raw.split(host.platform === "win32" ? ";" : ":").map((entry) => entry.replace(/^"|"$/g, ""))
|
|
260
|
+
.filter((entry) => entry !== "" && isFullPath(entry, host.platform));
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/** An existing regular file, as found, with the found path and its real path both outside the guards. */
|
|
264
|
+
function locate(path: string, host: ProvisionHost): string | undefined {
|
|
265
|
+
if (!isFullPath(path, host.platform)) return undefined;
|
|
266
|
+
const real = realFileOrUndefined(path);
|
|
267
|
+
if (real === undefined) return undefined;
|
|
268
|
+
const found = api(host.platform).normalize(path);
|
|
269
|
+
if (firstOutside([found], host.guards) === undefined || firstOutside([real], host.guards) === undefined) return undefined;
|
|
270
|
+
return found;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
const STORE_STUB_RE = /[\\/]Microsoft[\\/]WindowsApps[\\/]/i;
|
|
274
|
+
|
|
275
|
+
/** A bare name as `.exe` (win32) on an absolute PATH entry outside the guards. */
|
|
276
|
+
function findExecutable(name: string, host: ProvisionHost): string | undefined {
|
|
277
|
+
const file = host.platform === "win32" && !/\.(exe|com)$/i.test(name) ? `${name}.exe` : name;
|
|
278
|
+
for (const dir of pathDirs(host)) {
|
|
279
|
+
const found = locate(api(host.platform).join(dir, file), host);
|
|
280
|
+
if (found !== undefined) return found;
|
|
281
|
+
}
|
|
282
|
+
return undefined;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
function requireTool(manager: Manager, host: ProvisionHost, hint: string): string {
|
|
286
|
+
const found = findExecutable(manager, host);
|
|
287
|
+
if (found !== undefined) return found;
|
|
288
|
+
throw fail(`${manager} was not found on PATH (an absolute PATH entry outside the work root); ${hint} or set executor.provision`,
|
|
289
|
+
{ manager });
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/** A node entry script beside a package manager's launcher, run as `node <entry>`. */
|
|
293
|
+
function entryBesideLauncher(launcher: string, entries: readonly string[], host: ProvisionHost): string | undefined {
|
|
294
|
+
const p = api(host.platform);
|
|
295
|
+
for (const dir of pathDirs(host)) {
|
|
296
|
+
const launchers = host.platform === "win32" ? [`${launcher}.cmd`, `${launcher}.exe`] : [launcher];
|
|
297
|
+
if (!launchers.some((name) => realFileOrUndefined(p.join(dir, name)) !== undefined)) continue;
|
|
298
|
+
for (const entry of entries) {
|
|
299
|
+
const found = locate(p.join(dir, entry), host);
|
|
300
|
+
if (found !== undefined) return found;
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
return undefined;
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
interface NodeTools { node: string; runHost: RunHost }
|
|
307
|
+
|
|
308
|
+
function nodeTools(host: ProvisionHost): NodeTools {
|
|
309
|
+
const runHost: RunHost = { platform: host.platform, env: host.env, nodeExecPath: host.nodeExecPath };
|
|
310
|
+
return { node: resolving("node executable", () => resolveNodeExecutable(runHost, host.guards)), runHost };
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
function corepackEntry(name: string, node: string, host: ProvisionHost): string | undefined {
|
|
314
|
+
const p = api(host.platform);
|
|
315
|
+
return locate(p.join(p.dirname(node), "node_modules", "corepack", "dist", name), host);
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
interface Resolved { command: string; prefix: string[] }
|
|
319
|
+
|
|
320
|
+
function resolvePython(d: Detection, config: Provision, host: ProvisionHost): Resolved {
|
|
321
|
+
const wanted = d.python ?? (config.python === "auto" ? null : config.python);
|
|
322
|
+
let resolved: Resolved;
|
|
323
|
+
if (wanted !== null) {
|
|
324
|
+
const found = isFullPath(wanted, host.platform) ? locate(wanted, host) : findExecutable(wanted, host);
|
|
325
|
+
if (found === undefined) throw fail(`executor.python "${wanted}" was not found as an absolute file or an executable on PATH outside the work root`, { python: wanted });
|
|
326
|
+
resolved = { command: found, prefix: [] };
|
|
327
|
+
} else if (host.platform === "win32") {
|
|
328
|
+
const launcher = findExecutable("py", host);
|
|
329
|
+
if (launcher === undefined) throw fail("Python was not found (py.exe on PATH); install Python 3 or set executor.python", { manager: "pip" });
|
|
330
|
+
resolved = { command: launcher, prefix: ["-3"] };
|
|
331
|
+
} else {
|
|
332
|
+
const found = findExecutable("python3", host);
|
|
333
|
+
if (found === undefined) throw fail("python3 was not found on PATH; install Python 3 or set executor.python", { manager: "pip" });
|
|
334
|
+
resolved = { command: found, prefix: [] };
|
|
335
|
+
}
|
|
336
|
+
if (STORE_STUB_RE.test(resolved.command) || STORE_STUB_RE.test(realFileOrUndefined(resolved.command) ?? "")) {
|
|
337
|
+
throw fail(`${resolved.command} is the Microsoft Store Python stub; install Python 3 or set executor.python`, { python: resolved.command });
|
|
338
|
+
}
|
|
339
|
+
return resolved;
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
/** The user's Python environment must not leak into an install step: it would install into the user's venv or site. */
|
|
343
|
+
const FOREIGN_PYTHON_ENV: readonly string[] = [
|
|
344
|
+
"VIRTUAL_ENV", "CONDA_PREFIX", "CONDA_DEFAULT_ENV", "PYTHONHOME", "PYTHONPATH", "PIP_TARGET", "PIP_PREFIX", "PIP_USER",
|
|
345
|
+
"POETRY_VIRTUALENVS_PATH",
|
|
346
|
+
];
|
|
347
|
+
|
|
348
|
+
function stepEnv(host: ProvisionHost, shell: string, slot: string, extra: Record<string, string>): Record<string, string> {
|
|
349
|
+
const base = runEnvironment(host.env, host.platform, shell, { guards: host.guards });
|
|
350
|
+
const env: Record<string, string> = {};
|
|
351
|
+
const foreign = new Set(FOREIGN_PYTHON_ENV.map((name) => (host.platform === "win32" ? name.toUpperCase() : name)));
|
|
352
|
+
for (const [key, value] of Object.entries(base)) {
|
|
353
|
+
if (value === undefined || isCredentialEnv(key)) continue;
|
|
354
|
+
if (foreign.has(host.platform === "win32" ? key.toUpperCase() : key)) continue;
|
|
355
|
+
env[key] = value;
|
|
356
|
+
}
|
|
357
|
+
const fixed: Record<string, string> = {
|
|
358
|
+
CI: "1", COREPACK_ENABLE_DOWNLOAD_PROMPT: "0", PIP_NO_INPUT: "1", UV_PYTHON_DOWNLOADS: "never",
|
|
359
|
+
UV_PROJECT_ENVIRONMENT: api(host.platform).join(slot, ".venv"), ...extra,
|
|
360
|
+
};
|
|
361
|
+
for (const [name, value] of Object.entries(fixed)) {
|
|
362
|
+
if (host.platform === "win32") {
|
|
363
|
+
for (const existing of Object.keys(env)) if (existing.toUpperCase() === name.toUpperCase()) delete env[existing];
|
|
364
|
+
}
|
|
365
|
+
env[name] = value;
|
|
366
|
+
}
|
|
367
|
+
return env;
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
function venvPython(slot: string, platform: NodeJS.Platform): string {
|
|
371
|
+
const p = api(platform);
|
|
372
|
+
return platform === "win32" ? p.join(slot, ".venv", "Scripts", "python.exe") : p.join(slot, ".venv", "bin", "python");
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
const BARE_NAME_RE = /^[A-Za-z0-9_][A-Za-z0-9_.+-]{0,99}$/;
|
|
376
|
+
|
|
377
|
+
/** Plans the install commands of the detected managers (E_PROVISION on a missing binary). */
|
|
378
|
+
export function planProvision(slot: string, d: Detection, host: ProvisionHost, config: Provision): ProvisionStep[] {
|
|
379
|
+
const p = api(host.platform);
|
|
380
|
+
let tools: NodeTools | undefined;
|
|
381
|
+
const node = (): NodeTools => (tools ??= nodeTools(host));
|
|
382
|
+
const shell = resolving("system shell", () => resolveSystemShell(
|
|
383
|
+
{ platform: host.platform, env: host.env, nodeExecPath: host.nodeExecPath }, host.guards));
|
|
384
|
+
const overrides: Record<string, string[][]> = config.provision === "auto" ? {} : config.provision;
|
|
385
|
+
|
|
386
|
+
const step = (manager: Manager, command: string, args: string[], label: string,
|
|
387
|
+
extra: Record<string, string> = {}, condition?: string[]): ProvisionStep => ({
|
|
388
|
+
manager, command, args, env: stepEnv(host, shell, slot, extra), cwd: slot, timeoutMs: PROVISION_STEP_TIMEOUT_MS, label,
|
|
389
|
+
...(condition === undefined ? {} : { condition }),
|
|
390
|
+
});
|
|
391
|
+
|
|
392
|
+
const npmFlags = (): string[] => {
|
|
393
|
+
const { node: nodePath, runHost } = node();
|
|
394
|
+
const cli = resolving("npm-cli.js", () => resolveNpmCli(nodePath, host.platform, host.guards));
|
|
395
|
+
const pins = resolving("npm configuration", () => npmConfigPins(nodePath, cli, runHost.env, host.platform, host.guards));
|
|
396
|
+
return [cli, ...npmHardeningFlags(shell, pins).filter((flag) => flag !== "--workspaces=false")];
|
|
397
|
+
};
|
|
398
|
+
|
|
399
|
+
const overrideStep = (manager: Manager, argv: readonly string[], index: number): ProvisionStep => {
|
|
400
|
+
const [program, ...rest] = argv;
|
|
401
|
+
const label = `${manager} override ${index + 1}`;
|
|
402
|
+
if (program === undefined || program === "") throw fail(`executor.provision.${manager}[${index}] is an empty argv`, { manager });
|
|
403
|
+
if (program === "node") return step(manager, node().node, rest, label);
|
|
404
|
+
if (program === "npm") return step(manager, node().node, [...npmFlags(), ...rest], label);
|
|
405
|
+
if (program === "python") {
|
|
406
|
+
const python = resolvePython(d, config, host);
|
|
407
|
+
return step(manager, python.command, [...python.prefix, ...rest], label);
|
|
408
|
+
}
|
|
409
|
+
if (/\.(cmd|bat|ps1)$/i.test(program)) {
|
|
410
|
+
throw fail(`executor.provision.${manager}[${index}]: ${program} needs a shell; use "node <entry.js>" or an .exe instead`, { manager });
|
|
411
|
+
}
|
|
412
|
+
let command: string | undefined;
|
|
413
|
+
if (isFullPath(program, host.platform)) {
|
|
414
|
+
if (/(^|[\\/])\.\.([\\/]|$)/.test(program)) throw fail(`executor.provision.${manager}[${index}]: ${program} must not contain a ".." segment`, { manager });
|
|
415
|
+
if (host.platform === "win32" && !/\.(exe|com)$/i.test(program)) {
|
|
416
|
+
throw fail(`executor.provision.${manager}[${index}]: ${program} must be an .exe or .com on Windows`, { manager });
|
|
417
|
+
}
|
|
418
|
+
command = locate(program, host);
|
|
419
|
+
} else if (BARE_NAME_RE.test(program)) {
|
|
420
|
+
command = findExecutable(program, host);
|
|
421
|
+
} else {
|
|
422
|
+
throw fail(`executor.provision.${manager}[${index}]: ${program} must be absolute or a bare name`, { manager });
|
|
423
|
+
}
|
|
424
|
+
if (command === undefined) {
|
|
425
|
+
throw fail(`executor.provision.${manager}[${index}]: ${program} was not found as an executable outside the work root; install it or fix the path`, { manager });
|
|
426
|
+
}
|
|
427
|
+
return step(manager, command, rest, label);
|
|
428
|
+
};
|
|
429
|
+
|
|
430
|
+
const steps: ProvisionStep[] = [];
|
|
431
|
+
for (const manager of d.managers) {
|
|
432
|
+
const override = overrides[manager];
|
|
433
|
+
if (override !== undefined) {
|
|
434
|
+
override.forEach((argv, index) => steps.push(overrideStep(manager, argv, index)));
|
|
435
|
+
continue;
|
|
436
|
+
}
|
|
437
|
+
switch (manager) {
|
|
438
|
+
case "npm":
|
|
439
|
+
steps.push(step("npm", node().node, [...npmFlags(), "--prefix", slot, "ci", "--prefer-offline", "--no-audit", "--no-fund"], "npm ci"));
|
|
440
|
+
break;
|
|
441
|
+
case "pnpm": {
|
|
442
|
+
// --dir pins the project to the slot. Without a tracked root pnpm-workspace.yaml, --ignore-workspace stops pnpm
|
|
443
|
+
// adopting one above the slot; with one, pnpm stops at the slot's own file, so the workspace installs whole.
|
|
444
|
+
const args = ["--dir", slot, "install", ...(d.pnpmWorkspace === true ? [] : ["--ignore-workspace"]),
|
|
445
|
+
"--frozen-lockfile", "--prefer-offline", "--config.confirm-modules-purge=false"];
|
|
446
|
+
const exe = findExecutable("pnpm", host);
|
|
447
|
+
if (exe !== undefined) {
|
|
448
|
+
steps.push(step("pnpm", exe, args, "pnpm install"));
|
|
449
|
+
break;
|
|
450
|
+
}
|
|
451
|
+
const entry = entryBesideLauncher("pnpm", [p.join("node_modules", "pnpm", "bin", "pnpm.cjs")], host)
|
|
452
|
+
?? corepackEntry("pnpm.js", node().node, host);
|
|
453
|
+
if (entry === undefined) {
|
|
454
|
+
throw fail("pnpm was not found (pnpm.exe on PATH, pnpm.cmd beside node_modules\\pnpm, or corepack in the node install); install pnpm or enable corepack, or set executor.provision", { manager });
|
|
455
|
+
}
|
|
456
|
+
steps.push(step("pnpm", node().node, [entry, ...args], "pnpm install"));
|
|
457
|
+
break;
|
|
458
|
+
}
|
|
459
|
+
case "yarn": {
|
|
460
|
+
// Classic takes --cwd. Berry has no such flag: it runs with cwd=slot and finds its project by the slot's own
|
|
461
|
+
// yarn.lock (detection requires a lockfile and a package.json there), so it stays inside the slot.
|
|
462
|
+
const args = d.yarnBerry ? ["install", "--immutable"] : ["--cwd", slot, "install", "--frozen-lockfile", "--non-interactive"];
|
|
463
|
+
let entry: string | undefined;
|
|
464
|
+
if (d.yarnBerry && d.yarnPath !== undefined) {
|
|
465
|
+
const wanted = p.resolve(slot, d.yarnPath);
|
|
466
|
+
if (!isInside(p.resolve(slot), wanted) || realFileOrUndefined(wanted) === undefined) {
|
|
467
|
+
throw fail(`yarnPath ${d.yarnPath} in .yarnrc.yml is missing or outside ${slot}; commit the release file or set executor.provision`, { manager });
|
|
468
|
+
}
|
|
469
|
+
entry = wanted;
|
|
470
|
+
} else if (!d.yarnBerry) {
|
|
471
|
+
entry = entryBesideLauncher("yarn", ["yarn.js", p.join("node_modules", "yarn", "bin", "yarn.js")], host);
|
|
472
|
+
}
|
|
473
|
+
entry ??= corepackEntry("yarn.js", node().node, host);
|
|
474
|
+
if (entry === undefined) {
|
|
475
|
+
throw fail("yarn was not found (yarn.cmd on PATH with its yarn.js, or corepack in the node install); install yarn or enable corepack, or set executor.provision", { manager });
|
|
476
|
+
}
|
|
477
|
+
steps.push(step("yarn", node().node, [entry, ...args], "yarn install"));
|
|
478
|
+
break;
|
|
479
|
+
}
|
|
480
|
+
case "uv": {
|
|
481
|
+
const exe = requireTool("uv", host, "install uv (https://docs.astral.sh/uv/)");
|
|
482
|
+
const python = d.python ?? (config.python === "auto" ? null : config.python);
|
|
483
|
+
steps.push(step("uv", exe, ["--project", slot, "sync", "--frozen", ...(python === null ? [] : ["--python", python])], "uv sync"));
|
|
484
|
+
break;
|
|
485
|
+
}
|
|
486
|
+
case "poetry": {
|
|
487
|
+
const exe = requireTool("poetry", host, "install poetry");
|
|
488
|
+
steps.push(step("poetry", exe, ["--directory", slot, "install", "--no-interaction"], "poetry install", { POETRY_VIRTUALENVS_IN_PROJECT: "true" }));
|
|
489
|
+
break;
|
|
490
|
+
}
|
|
491
|
+
case "pip": {
|
|
492
|
+
const python = resolvePython(d, config, host);
|
|
493
|
+
const venv = venvPython(slot, host.platform);
|
|
494
|
+
steps.push(step("pip", python.command, [...python.prefix, "-m", "venv", ".venv"], "pip venv"));
|
|
495
|
+
const requirements = ["requirements.txt", "requirements-dev.txt"].filter((file) => file in d.manifests);
|
|
496
|
+
if (requirements.length > 0) {
|
|
497
|
+
steps.push(step("pip", venv, ["-m", "pip", "install", "--disable-pip-version-check", "--no-input",
|
|
498
|
+
...requirements.flatMap((file) => ["-r", file])], "pip install"));
|
|
499
|
+
}
|
|
500
|
+
if (d.editable) {
|
|
501
|
+
steps.push(step("pip", venv, ["-m", "pip", "install", "--disable-pip-version-check", "--no-input",
|
|
502
|
+
"--no-build-isolation", "-e", "."], "pip install -e .", {}, ["-c", "import setuptools"]));
|
|
503
|
+
}
|
|
504
|
+
break;
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
return steps;
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
/** `%LOCALAPPDATA%\omr-executor\locks\<manager>.lock` (POSIX: `$HOME/.cache/omr-executor/locks/<manager>.lock`). */
|
|
512
|
+
export function managerLockPath(m: Manager, env: NodeJS.ProcessEnv, platform: NodeJS.Platform): string {
|
|
513
|
+
if (platform === "win32") {
|
|
514
|
+
const base = envLookup(env, "LOCALAPPDATA") ?? win32.join(envLookup(env, "USERPROFILE") ?? homedir(), "AppData", "Local");
|
|
515
|
+
return win32.join(base, "omr-executor", "locks", `${m}.lock`);
|
|
516
|
+
}
|
|
517
|
+
return posix.join(envLookup(env, "HOME") ?? homedir(), ".cache", "omr-executor", "locks", `${m}.lock`);
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
export interface Provisioner {
|
|
521
|
+
/** `detectManagers` with this provisioner's own config: detection and provisioning never disagree. */
|
|
522
|
+
detect(slot: string, tracked: readonly string[]): Promise<Detection>;
|
|
523
|
+
provision(slot: string, d: Detection, o: { fresh: boolean; signal?: AbortSignal }): Promise<void>;
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
interface LockBody { pid: number; hostname: string; startedAt: number; heartbeatAt: number }
|
|
527
|
+
|
|
528
|
+
function parseLock(text: string): LockBody | null {
|
|
529
|
+
try {
|
|
530
|
+
const value: unknown = JSON.parse(text);
|
|
531
|
+
if (typeof value !== "object" || value === null) return null;
|
|
532
|
+
const pid: unknown = Reflect.get(value, "pid");
|
|
533
|
+
const host: unknown = Reflect.get(value, "hostname");
|
|
534
|
+
const startedAt: unknown = Reflect.get(value, "startedAt");
|
|
535
|
+
const heartbeatAt: unknown = Reflect.get(value, "heartbeatAt");
|
|
536
|
+
if (typeof pid !== "number" || typeof host !== "string" || typeof startedAt !== "number" || typeof heartbeatAt !== "number") return null;
|
|
537
|
+
return { pid, hostname: host, startedAt, heartbeatAt };
|
|
538
|
+
} catch {
|
|
539
|
+
// An unreadable lock body is a damaged lock: the caller treats null as stale.
|
|
540
|
+
return null;
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
function errorCode(error: unknown): string | undefined {
|
|
545
|
+
if (typeof error === "object" && error !== null && "code" in error) {
|
|
546
|
+
const code: unknown = Reflect.get(error, "code");
|
|
547
|
+
return typeof code === "string" ? code : undefined;
|
|
548
|
+
}
|
|
549
|
+
return undefined;
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
const HINTS: Readonly<Record<Manager, string>> = {
|
|
553
|
+
npm: "package-lock.json may be out of sync with package.json; run npm install and commit the lockfile",
|
|
554
|
+
pnpm: "pnpm-lock.yaml may be out of date; run pnpm install and commit the lockfile",
|
|
555
|
+
yarn: "yarn.lock may be out of date; run yarn install and commit the lockfile",
|
|
556
|
+
uv: "uv.lock may be out of date; run uv lock and commit it",
|
|
557
|
+
poetry: "poetry.lock may be out of date; run poetry lock and commit it",
|
|
558
|
+
pip: "check requirements*.txt and the Python version, or set executor.python or executor.provision",
|
|
559
|
+
};
|
|
560
|
+
|
|
561
|
+
/** In-process chain per lock path: waiters in this process queue here, so they never poll the file against each other. */
|
|
562
|
+
const CHAINS = new Map<string, Promise<void>>();
|
|
563
|
+
|
|
564
|
+
export function createProvisioner(deps: {
|
|
565
|
+
spawner: Spawner; fs: FileSystem; clock: Clock; host: ProvisionHost; config: Provision;
|
|
566
|
+
}): Provisioner {
|
|
567
|
+
const { spawner, fs, clock, host, config } = deps;
|
|
568
|
+
const p = api(host.platform);
|
|
569
|
+
const uvCache = new Map<string, Promise<string | null>>();
|
|
570
|
+
|
|
571
|
+
const sleep = (ms: number, signal?: AbortSignal): Promise<void> => new Promise((resolve) => {
|
|
572
|
+
const handle = clock.setTimer(ms, () => { signal?.removeEventListener("abort", onAbort); resolve(); });
|
|
573
|
+
const onAbort = (): void => { clock.clearTimer(handle); resolve(); };
|
|
574
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
575
|
+
});
|
|
576
|
+
|
|
577
|
+
const aborted = (slot: string, signal?: AbortSignal): void => {
|
|
578
|
+
if (signal?.aborted) throw fail(`provisioning of ${slot} was aborted`, { slot });
|
|
579
|
+
};
|
|
580
|
+
|
|
581
|
+
/** Creates `path` and every missing parent (the FileSystem port's mkdir is not recursive). */
|
|
582
|
+
async function ensureDir(path: string): Promise<void> {
|
|
583
|
+
const missing: string[] = [];
|
|
584
|
+
let cur = path;
|
|
585
|
+
for (;;) {
|
|
586
|
+
if (await fs.lstat(cur) !== null) break;
|
|
587
|
+
missing.push(cur);
|
|
588
|
+
const up = p.dirname(cur);
|
|
589
|
+
if (up === cur) break;
|
|
590
|
+
cur = up;
|
|
591
|
+
}
|
|
592
|
+
for (const dir of missing.reverse()) {
|
|
593
|
+
try {
|
|
594
|
+
await fs.mkdir(dir);
|
|
595
|
+
} catch (error) {
|
|
596
|
+
if (errorCode(error) !== "EEXIST") throw error;
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
async function removeRetrying(path: string, recursive: boolean): Promise<void> {
|
|
602
|
+
for (let attempt = 0; ; attempt += 1) {
|
|
603
|
+
try {
|
|
604
|
+
await fs.rm(path, { recursive });
|
|
605
|
+
return;
|
|
606
|
+
} catch (error) {
|
|
607
|
+
const code = errorCode(error);
|
|
608
|
+
if (code === "ENOENT") return;
|
|
609
|
+
if (code === undefined || !TRANSIENT_FS_CODES.has(code) || attempt >= CLEANUP_RETRIES) throw error;
|
|
610
|
+
await sleep(CLEANUP_RETRY_BASE_MS * 2 ** attempt);
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
/**
|
|
616
|
+
* Removes every symlink/junction below `root` (non-recursively, never descending into one), so the recursive
|
|
617
|
+
* removal that follows cannot reach what a link points to. Real directories are descended iteratively.
|
|
618
|
+
*/
|
|
619
|
+
async function sweepLinks(root: string): Promise<void> {
|
|
620
|
+
const pending = [root];
|
|
621
|
+
let seen = 0;
|
|
622
|
+
for (let dir = pending.pop(); dir !== undefined; dir = pending.pop()) {
|
|
623
|
+
let names: string[];
|
|
624
|
+
try {
|
|
625
|
+
names = await fs.readdir(dir);
|
|
626
|
+
} catch (error) {
|
|
627
|
+
if (errorCode(error) === "ENOENT") continue;
|
|
628
|
+
throw error;
|
|
629
|
+
}
|
|
630
|
+
for (const name of names) {
|
|
631
|
+
seen += 1;
|
|
632
|
+
if (seen > SLOT_SWEEP_MAX_ENTRIES) {
|
|
633
|
+
throw fail(`more than ${SLOT_SWEEP_MAX_ENTRIES} entries below ${root}; refusing to remove it recursively`, { path: root });
|
|
634
|
+
}
|
|
635
|
+
const child = p.join(dir, name);
|
|
636
|
+
const st = await fs.lstat(child);
|
|
637
|
+
if (st === null) continue;
|
|
638
|
+
if (st.kind === "symlink" || st.kind === "junction") await removeRetrying(child, false);
|
|
639
|
+
else if (st.kind === "dir") pending.push(child);
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
/** lstat gate: a real directory is swept of links, then removed recursively; a link or a file only itself. */
|
|
645
|
+
async function removeDependencyDir(slot: string, rel: string): Promise<void> {
|
|
646
|
+
const target = p.join(slot, rel);
|
|
647
|
+
const st = await fs.lstat(target);
|
|
648
|
+
if (st === null) return;
|
|
649
|
+
if (st.kind === "dir") await sweepLinks(target);
|
|
650
|
+
await removeRetrying(target, st.kind === "dir");
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
async function freshen(slot: string, d: Detection): Promise<void> {
|
|
654
|
+
for (const manager of d.managers) {
|
|
655
|
+
const rel = FRESH_REMOVES[manager] ?? (manager === "yarn" && !d.yarnBerry ? "node_modules" : undefined);
|
|
656
|
+
if (rel !== undefined) await removeDependencyDir(slot, rel);
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
/** Heartbeat write: tmp + rename, but only while `held()` is true, so a release can never be undone by a late beat. */
|
|
661
|
+
async function writeLock(path: string, body: LockBody, held: () => boolean): Promise<void> {
|
|
662
|
+
const tmp = `${path}.${clock.randomHex(8)}.tmp`;
|
|
663
|
+
await fs.writeText(tmp, JSON.stringify(body), { fsync: true });
|
|
664
|
+
if (!held()) {
|
|
665
|
+
await removeRetrying(tmp, false);
|
|
666
|
+
return;
|
|
667
|
+
}
|
|
668
|
+
await fs.rename(tmp, path);
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
/** Holds the machine-wide lock of `manager` while `work` runs. */
|
|
672
|
+
async function withManagerLock<T>(manager: Manager, slot: string, signal: AbortSignal | undefined, work: () => Promise<T>): Promise<T> {
|
|
673
|
+
const lockPath = managerLockPath(manager, host.env, host.platform);
|
|
674
|
+
const previous = CHAINS.get(lockPath) ?? Promise.resolve();
|
|
675
|
+
let release: () => void = () => undefined;
|
|
676
|
+
const mine = new Promise<void>((resolve) => { release = resolve; });
|
|
677
|
+
const tail = previous.then(() => mine);
|
|
678
|
+
CHAINS.set(lockPath, tail);
|
|
679
|
+
try {
|
|
680
|
+
await previous;
|
|
681
|
+
const deadline = clock.now() + PROVISION_STEP_TIMEOUT_MS;
|
|
682
|
+
await ensureDir(p.dirname(lockPath));
|
|
683
|
+
const body = await acquireFileLock(manager, slot, lockPath, deadline, signal);
|
|
684
|
+
let beat: { readonly id: number } | undefined;
|
|
685
|
+
let stopped = false;
|
|
686
|
+
let inFlight: Promise<void> | undefined;
|
|
687
|
+
const schedule = (): void => {
|
|
688
|
+
if (stopped) return;
|
|
689
|
+
beat = clock.setTimer(LOCK_HEARTBEAT_MS, () => {
|
|
690
|
+
if (stopped) return;
|
|
691
|
+
body.heartbeatAt = clock.now();
|
|
692
|
+
// A failed beat is retried on the next one; the lock only goes stale after LOCK_STALE_MS.
|
|
693
|
+
const write = writeLock(lockPath, body, () => !stopped).then(schedule, schedule);
|
|
694
|
+
inFlight = write;
|
|
695
|
+
});
|
|
696
|
+
};
|
|
697
|
+
schedule();
|
|
698
|
+
let outcome: { ok: true; value: T } | { ok: false; error: unknown };
|
|
699
|
+
try {
|
|
700
|
+
outcome = { ok: true, value: await work() };
|
|
701
|
+
} catch (error) {
|
|
702
|
+
outcome = { ok: false, error };
|
|
703
|
+
}
|
|
704
|
+
stopped = true;
|
|
705
|
+
if (beat !== undefined) clock.clearTimer(beat);
|
|
706
|
+
// A beat still writing must finish (and see `stopped`) before the lock is removed, or its rename would recreate it.
|
|
707
|
+
if (inFlight !== undefined) await inFlight;
|
|
708
|
+
let releaseError: unknown;
|
|
709
|
+
try {
|
|
710
|
+
await removeRetrying(lockPath, false);
|
|
711
|
+
} catch (error) {
|
|
712
|
+
releaseError = error;
|
|
713
|
+
}
|
|
714
|
+
if (!outcome.ok) throw outcome.error;
|
|
715
|
+
if (releaseError !== undefined) {
|
|
716
|
+
throw fail(`could not release the ${manager} install lock ${lockPath}: ${releaseError instanceof Error ? releaseError.message : String(releaseError)}`, { manager, slot });
|
|
717
|
+
}
|
|
718
|
+
return outcome.value;
|
|
719
|
+
} finally {
|
|
720
|
+
release();
|
|
721
|
+
if (CHAINS.get(lockPath) === tail) CHAINS.delete(lockPath);
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
async function acquireFileLock(manager: Manager, slot: string, lockPath: string, deadline: number,
|
|
726
|
+
signal: AbortSignal | undefined): Promise<LockBody> {
|
|
727
|
+
let delay = LOCK_POLL_MIN_MS;
|
|
728
|
+
for (;;) {
|
|
729
|
+
aborted(slot, signal);
|
|
730
|
+
const now = clock.now();
|
|
731
|
+
const body: LockBody = { pid: spawner.pid, hostname: spawner.hostname, startedAt: now, heartbeatAt: now };
|
|
732
|
+
try {
|
|
733
|
+
await fs.writeText(lockPath, JSON.stringify(body), { exclusive: true, fsync: true });
|
|
734
|
+
return body;
|
|
735
|
+
} catch (error) {
|
|
736
|
+
if (errorCode(error) !== "EEXIST") throw error;
|
|
737
|
+
}
|
|
738
|
+
const taken = await takeOverIfStale(lockPath, signal);
|
|
739
|
+
if (taken) continue;
|
|
740
|
+
if (clock.now() + delay > deadline) {
|
|
741
|
+
throw fail(`timed out waiting for the ${manager} install lock ${lockPath} while provisioning ${slot}; another install is running, or remove a stale lock`, { manager, slot });
|
|
742
|
+
}
|
|
743
|
+
await sleep(delay, signal);
|
|
744
|
+
delay = Math.min(delay * 2, LOCK_POLL_MAX_MS);
|
|
745
|
+
}
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
const isStale = (text: string | null): boolean => {
|
|
749
|
+
if (text === null) return false;
|
|
750
|
+
const body = parseLock(text);
|
|
751
|
+
if (body === null) return true;
|
|
752
|
+
if (body.hostname === spawner.hostname && !spawner.isAlive(body.pid)) return true;
|
|
753
|
+
return clock.now() - body.heartbeatAt > LOCK_STALE_MS;
|
|
754
|
+
};
|
|
755
|
+
|
|
756
|
+
async function readLock(lockPath: string): Promise<string | null> {
|
|
757
|
+
try {
|
|
758
|
+
return await fs.readText(lockPath);
|
|
759
|
+
} catch (error) {
|
|
760
|
+
if (errorCode(error) === "ENOENT") return null;
|
|
761
|
+
throw error;
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
/** True when the lock is gone (removed or taken over) and the caller should retry creating it at once. */
|
|
766
|
+
async function takeOverIfStale(lockPath: string, signal: AbortSignal | undefined): Promise<boolean> {
|
|
767
|
+
const first = await readLock(lockPath);
|
|
768
|
+
if (first === null) return true;
|
|
769
|
+
if (!isStale(first)) return false;
|
|
770
|
+
await sleep(LOCK_STALE_RECHECK_MS, signal);
|
|
771
|
+
const second = await readLock(lockPath);
|
|
772
|
+
if (second === null) return true;
|
|
773
|
+
if (second !== first || !isStale(second)) return false;
|
|
774
|
+
const stale = `${lockPath}.${clock.randomHex(8)}.stale`;
|
|
775
|
+
try {
|
|
776
|
+
await fs.rename(lockPath, stale);
|
|
777
|
+
} catch (error) {
|
|
778
|
+
if (errorCode(error) === "ENOENT") return true;
|
|
779
|
+
throw error;
|
|
780
|
+
}
|
|
781
|
+
const moved = await readLock(stale);
|
|
782
|
+
if (moved !== null && moved !== second && !isStale(moved)) {
|
|
783
|
+
// Someone refreshed the lock between the read and the rename: put it back unless a new one exists.
|
|
784
|
+
try {
|
|
785
|
+
await fs.writeText(lockPath, moved, { exclusive: true, fsync: true });
|
|
786
|
+
} catch (error) {
|
|
787
|
+
if (errorCode(error) !== "EEXIST") throw error;
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
await removeRetrying(stale, false);
|
|
791
|
+
return true;
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
const tailOf = (r: ProcessResult): string => {
|
|
795
|
+
const lines = `${r.stderr}\n${r.stdout}`.split(/\r?\n/).map((line) => line.trimEnd()).filter((line) => line !== "");
|
|
796
|
+
return stripUrlUserinfo(lines.slice(-TAIL_LINES).join("\n"));
|
|
797
|
+
};
|
|
798
|
+
|
|
799
|
+
/** UV_CACHE_DIR on the slot's drive when `uv cache dir` is on another one (win32 only). */
|
|
800
|
+
async function uvCacheOverride(step: ProvisionStep, slot: string, signal?: AbortSignal): Promise<Record<string, string>> {
|
|
801
|
+
if (host.platform !== "win32" || step.manager !== "uv" || "UV_CACHE_DIR" in step.env) return {};
|
|
802
|
+
let pending = uvCache.get(step.command);
|
|
803
|
+
if (pending === undefined) {
|
|
804
|
+
pending = spawner.run(step.command, ["cache", "dir"], {
|
|
805
|
+
cwd: slot, timeoutMs: PROBE_TIMEOUT_MS, env: step.env, maxOutputBytes: PROVISION_OUTPUT_KEEP_BYTES, signal,
|
|
806
|
+
}).then((r) => (r.code === 0 ? r.stdout.trim().split(/\r?\n/)[0] ?? null : null), () => null);
|
|
807
|
+
uvCache.set(step.command, pending);
|
|
808
|
+
}
|
|
809
|
+
const cacheDir = await pending;
|
|
810
|
+
const slotDrive = /^[A-Za-z]:/.exec(slot)?.[0];
|
|
811
|
+
const cacheDrive = cacheDir === null ? undefined : /^[A-Za-z]:/.exec(cacheDir)?.[0];
|
|
812
|
+
if (slotDrive === undefined || cacheDrive === undefined || slotDrive.toLowerCase() === cacheDrive.toLowerCase()) return {};
|
|
813
|
+
return { UV_CACHE_DIR: win32.join(`${slotDrive}\\`, ".omr-cache", "uv") };
|
|
814
|
+
}
|
|
815
|
+
|
|
816
|
+
async function runStep(step: ProvisionStep, slot: string, signal?: AbortSignal): Promise<void> {
|
|
817
|
+
aborted(slot, signal);
|
|
818
|
+
const env = { ...step.env, ...(await uvCacheOverride(step, slot, signal)) };
|
|
819
|
+
const common = { cwd: step.cwd, env, maxOutputBytes: 2 * PROVISION_OUTPUT_KEEP_BYTES, signal };
|
|
820
|
+
try {
|
|
821
|
+
if (step.condition !== undefined) {
|
|
822
|
+
const probe = await spawner.run(step.command, step.condition, { ...common, timeoutMs: PROBE_TIMEOUT_MS });
|
|
823
|
+
if (probe.code !== 0) return;
|
|
824
|
+
}
|
|
825
|
+
const result = await spawner.run(step.command, step.args, { ...common, timeoutMs: step.timeoutMs });
|
|
826
|
+
if (result.code === 0 && result.signal === null) return;
|
|
827
|
+
const how = result.code === null ? `signal ${result.signal ?? "unknown"}` : `exit ${result.code}`;
|
|
828
|
+
throw fail(`${step.label} failed in ${slot} (${how}): ${tailOf(result)} — ${HINTS[step.manager]}`,
|
|
829
|
+
{ manager: step.manager, slot, label: step.label });
|
|
830
|
+
} catch (error) {
|
|
831
|
+
if (error instanceof ExecutorError) throw error;
|
|
832
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
833
|
+
throw fail(`${step.label} could not run in ${slot}: ${stripUrlUserinfo(message)} — ${HINTS[step.manager]}`,
|
|
834
|
+
{ manager: step.manager, slot, label: step.label });
|
|
835
|
+
}
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
return {
|
|
839
|
+
detect: (slot, tracked) => detectManagers(slot, tracked, fs, config),
|
|
840
|
+
async provision(slot, d, o) {
|
|
841
|
+
const steps = planProvision(slot, d, host, config);
|
|
842
|
+
aborted(slot, o.signal);
|
|
843
|
+
if (o.fresh) await freshen(slot, d);
|
|
844
|
+
for (const manager of d.managers) {
|
|
845
|
+
const own = steps.filter((s) => s.manager === manager);
|
|
846
|
+
if (own.length === 0) continue;
|
|
847
|
+
await withManagerLock(manager, slot, o.signal, async () => {
|
|
848
|
+
for (const step of own) await runStep(step, slot, o.signal);
|
|
849
|
+
});
|
|
850
|
+
}
|
|
851
|
+
},
|
|
852
|
+
};
|
|
853
|
+
}
|