pi-durable-subagents 1.5.0 → 1.6.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 +38 -0
- package/README.md +69 -14
- package/dist/agent/capabilities.js +5 -4
- package/dist/agent/child/live.js +2 -1
- package/dist/agent/exact/capture.js +3 -2
- package/dist/agent/main/snapshots.js +10 -9
- package/dist/agent/main.js +2 -1
- package/dist/cli/chaos/stack.js +53 -21
- package/dist/cli/control.js +4 -3
- package/dist/cli/doctor.js +3 -1
- package/dist/cli/drill/index.js +35 -17
- package/dist/cli/hold.js +221 -16
- package/dist/cli/restart.js +14 -2
- package/dist/cli/service.js +77 -2
- package/dist/cli/smoke.js +10 -6
- package/dist/compat/agents.js +46 -13
- package/dist/events/log.js +33 -11
- package/dist/kernel/cache.js +3 -2
- package/dist/kernel/fsx.js +203 -0
- package/dist/kernel/ids.js +11 -0
- package/dist/kernel/journal.js +42 -25
- package/dist/kernel/mailbox.js +7 -4
- package/dist/orchestrator/engine.js +49 -46
- package/dist/orchestrator/evaluator-client.js +11 -3
- package/dist/orchestrator/executor/command.js +21 -6
- package/dist/orchestrator/executor/effects/gate.js +291 -56
- package/dist/orchestrator/executor/effects/index.js +3 -4
- package/dist/orchestrator/executor/effects/output.js +9 -5
- package/dist/orchestrator/executor/effects/prepare.js +69 -35
- package/dist/orchestrator/executor/effects/worktree-path.js +102 -0
- package/dist/orchestrator/executor/ended.js +7 -3
- package/dist/orchestrator/executor/index.js +221 -63
- package/dist/orchestrator/executor/memory.js +15 -0
- package/dist/orchestrator/executor/session.js +4 -3
- package/dist/orchestrator/executor/sweep.js +34 -1
- package/dist/orchestrator/executor/worktree.js +7 -1
- package/dist/orchestrator/main.js +4 -2
- package/dist/orchestrator/reader-ledger.js +3 -2
- package/dist/orchestrator/settled.js +2 -1
- package/dist/orchestrator/snapshot.js +29 -22
- package/dist/orchestrator/stats.js +2 -1
- package/dist/orchestrator/store.js +3 -2
- package/dist/platform/cmdline.js +3 -0
- package/dist/platform/command.js +184 -20
- package/dist/platform/containment.js +204 -40
- package/dist/platform/job.js +1404 -0
- package/dist/platform/launch.js +157 -23
- package/dist/platform/lease.js +351 -32
- package/dist/platform/lock.js +464 -16
- package/dist/platform/proctable.js +31 -2
- package/dist/platform/windows.js +642 -0
- package/dist/requests.js +1 -1
- package/dist/ui/data.js +7 -6
- package/dist/ui/session.js +6 -5
- package/package.json +3 -3
package/dist/platform/lock.js
CHANGED
|
@@ -1,4 +1,10 @@
|
|
|
1
|
-
import { spawn } from "node:child_process";
|
|
1
|
+
import { execFile, spawn } from "node:child_process";
|
|
2
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
3
|
+
import { statSync } from "node:fs";
|
|
4
|
+
import { mkdir, rename, rm, writeFile } from "node:fs/promises";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import { frameworkCompiler } from "./job.js";
|
|
7
|
+
import { envValue, helperEnv, mergeEnv, powershellPath } from "./windows.js";
|
|
2
8
|
const perl = `use Fcntl qw(:flock); $|=1;
|
|
3
9
|
open(my $f, ">>", $ARGV[0]) or do { warn "open: $!"; exit 1; };
|
|
4
10
|
if (!flock($f, LOCK_EX|LOCK_NB)) { exit 2 if $!{EWOULDBLOCK} || $!{EAGAIN}; warn "flock: $!"; exit 1; }
|
|
@@ -12,28 +18,449 @@ except OSError as e:
|
|
|
12
18
|
print('locked',flush=True)
|
|
13
19
|
while sys.stdin.buffer.read(4096): pass
|
|
14
20
|
`;
|
|
21
|
+
/** Windows has no flock, Node's fs.open shares files on Win32, and foreign PID checks can race PID reuse or fail to
|
|
22
|
+
* prove handle ownership. PowerShell opens the lock file with .NET FileStream and FileShare.None (dwShareMode = 0), so
|
|
23
|
+
* the Windows kernel refuses every other open, rename or delete while the handle lives and releases it at once when
|
|
24
|
+
* the helper dies (C4). Only Win32 sharing/lock violations (0x80070020 / 0x80070021) exit 2 (held); access denied, an
|
|
25
|
+
* existing directory at the lock path or a missing parent directory exits 1 without deleting or renaming anything. */
|
|
26
|
+
const powershell = "$ErrorActionPreference = 'Stop'; " +
|
|
27
|
+
"$p = $env:DSA_LOCK_PATH; " +
|
|
28
|
+
"if ([string]::IsNullOrEmpty($p)) { [System.Console]::Error.WriteLine('open: empty lock path'); [System.Environment]::Exit(1) }; " +
|
|
29
|
+
"try { " +
|
|
30
|
+
"$fs = [System.IO.FileStream]::new($p, [System.IO.FileMode]::OpenOrCreate, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None) " +
|
|
31
|
+
"} catch { " +
|
|
32
|
+
"$e = $_.Exception; " +
|
|
33
|
+
"while ($e -and -not ($e -is [System.IO.IOException]) -and $e.InnerException) { $e = $e.InnerException }; " +
|
|
34
|
+
"$hr = if ($e) { [int]$e.HResult } else { 0 }; " +
|
|
35
|
+
"if ($e -is [System.IO.IOException] -and ($hr -eq -2147024864 -or $hr -eq -2147024863)) { [System.Environment]::Exit(2) }; " +
|
|
36
|
+
"try { " +
|
|
37
|
+
"if ([System.IO.Directory]::Exists($p)) { [System.Console]::Error.WriteLine(\"open: lock path is a directory: $p\"); [System.Environment]::Exit(1) }; " +
|
|
38
|
+
"$msg = if ($e) { \"$($e.GetType().Name) (0x$($hr.ToString('x8'))): $($e.Message)\" } else { \"$_\" }; " +
|
|
39
|
+
"[System.Console]::Error.WriteLine(\"open: $msg\") " +
|
|
40
|
+
"} catch {}; " +
|
|
41
|
+
"[System.Environment]::Exit(1) " +
|
|
42
|
+
"}; " +
|
|
43
|
+
"try { " +
|
|
44
|
+
"$out = [System.Console]::OpenStandardOutput(); " +
|
|
45
|
+
"$out.Write([byte[]](108,111,99,107,101,100,10), 0, 7); " +
|
|
46
|
+
"$out.Flush(); " +
|
|
47
|
+
"$in = [System.Console]::OpenStandardInput(); " +
|
|
48
|
+
"while ($in.ReadByte() -ge 0) {} " +
|
|
49
|
+
"} catch {}; " +
|
|
50
|
+
"try { $fs.Close() } catch {}; " +
|
|
51
|
+
"[System.GC]::KeepAlive($fs); " +
|
|
52
|
+
"[System.Environment]::Exit(0)";
|
|
53
|
+
/** Compiled .NET Framework helper for Windows: identical C4 FileShare.None handle semantics to the PowerShell fallback
|
|
54
|
+
* below, but avoids cold PowerShell startup on every lock acquisition (tens of ms instead of seconds). Pure ASCII so
|
|
55
|
+
* csc.exe parses identically under any code page; lock path arrives via UTF-16 environment variable DSA_LOCK_PATH. */
|
|
56
|
+
export const WIN_LOCK_HELPER_EXE = "DsaLock.exe";
|
|
57
|
+
export const WIN_LOCK_HELPER_SOURCE_FILE = "DsaLock.cs";
|
|
58
|
+
export const WIN_LOCK_HELPER_SOURCE = `using System;
|
|
59
|
+
using System.IO;
|
|
60
|
+
using System.Runtime.InteropServices;
|
|
61
|
+
using System.Text;
|
|
62
|
+
|
|
63
|
+
public static class DsaLock
|
|
64
|
+
{
|
|
65
|
+
static void WriteError(string message)
|
|
66
|
+
{
|
|
67
|
+
try
|
|
68
|
+
{
|
|
69
|
+
byte[] bytes = Encoding.UTF8.GetBytes(message + "\\n");
|
|
70
|
+
Stream stderr = Console.OpenStandardError();
|
|
71
|
+
stderr.Write(bytes, 0, bytes.Length);
|
|
72
|
+
stderr.Flush();
|
|
73
|
+
}
|
|
74
|
+
catch { }
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
public static int Main()
|
|
78
|
+
{
|
|
79
|
+
string p = Environment.GetEnvironmentVariable("DSA_LOCK_PATH");
|
|
80
|
+
if (string.IsNullOrEmpty(p))
|
|
81
|
+
{
|
|
82
|
+
WriteError("open: empty lock path");
|
|
83
|
+
return 1;
|
|
84
|
+
}
|
|
85
|
+
FileStream fs = null;
|
|
86
|
+
try
|
|
87
|
+
{
|
|
88
|
+
fs = new FileStream(p, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
|
|
89
|
+
}
|
|
90
|
+
catch (Exception ex)
|
|
91
|
+
{
|
|
92
|
+
Exception e = ex;
|
|
93
|
+
while (e != null && !(e is IOException) && e.InnerException != null) e = e.InnerException;
|
|
94
|
+
int hr = e != null ? Marshal.GetHRForException(e) : 0;
|
|
95
|
+
if (e is IOException && (hr == -2147024864 || hr == -2147024863)) return 2;
|
|
96
|
+
try
|
|
97
|
+
{
|
|
98
|
+
if (Directory.Exists(p))
|
|
99
|
+
{
|
|
100
|
+
WriteError("open: lock path is a directory: " + p);
|
|
101
|
+
return 1;
|
|
102
|
+
}
|
|
103
|
+
string msg = e != null
|
|
104
|
+
? e.GetType().Name + " (0x" + hr.ToString("x8") + "): " + e.Message
|
|
105
|
+
: ex.ToString();
|
|
106
|
+
WriteError("open: " + msg);
|
|
107
|
+
}
|
|
108
|
+
catch { }
|
|
109
|
+
return 1;
|
|
110
|
+
}
|
|
111
|
+
try
|
|
112
|
+
{
|
|
113
|
+
Stream stdout = Console.OpenStandardOutput();
|
|
114
|
+
byte[] locked = new byte[] { 108, 111, 99, 107, 101, 100, 10 };
|
|
115
|
+
stdout.Write(locked, 0, locked.Length);
|
|
116
|
+
stdout.Flush();
|
|
117
|
+
Stream stdin = Console.OpenStandardInput();
|
|
118
|
+
byte[] buf = new byte[64];
|
|
119
|
+
while (stdin.Read(buf, 0, buf.Length) > 0) { }
|
|
120
|
+
}
|
|
121
|
+
catch { }
|
|
122
|
+
finally
|
|
123
|
+
{
|
|
124
|
+
try { if (fs != null) fs.Close(); } catch { }
|
|
125
|
+
GC.KeepAlive(fs);
|
|
126
|
+
}
|
|
127
|
+
return 0;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
`;
|
|
131
|
+
function readyExecutable(exe) {
|
|
132
|
+
try {
|
|
133
|
+
const info = statSync(exe);
|
|
134
|
+
return info.isFile() && info.size > 0;
|
|
135
|
+
}
|
|
136
|
+
catch {
|
|
137
|
+
return false;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
/** Content-addressed user-private cache directories for the compiled Windows lock helper (`%LOCALAPPDATA%` first, then
|
|
141
|
+
* `DSA_HOME` when `LOCALAPPDATA` is absent in a stripped environment; never a shared temp directory). Returns empty when
|
|
142
|
+
* neither is set so callers fall back to PowerShell. */
|
|
143
|
+
export function winLockHelperCacheDirs(env = process.env, arch = process.arch) {
|
|
144
|
+
const hash = createHash("sha256").update(WIN_LOCK_HELPER_SOURCE).update("\0").update(arch).digest("hex").slice(0, 16);
|
|
145
|
+
const dirs = [];
|
|
146
|
+
const localAppData = envValue(env, "LOCALAPPDATA");
|
|
147
|
+
if (localAppData)
|
|
148
|
+
dirs.push(join(localAppData, "pi-durable-subagents", "lock-helper", `v1-${hash}`));
|
|
149
|
+
const dsaHome = envValue(env, "DSA_HOME");
|
|
150
|
+
if (dsaHome) {
|
|
151
|
+
const candidate = join(dsaHome, "cache", "lock-helper", `v1-${hash}`);
|
|
152
|
+
if (!dirs.includes(candidate))
|
|
153
|
+
dirs.push(candidate);
|
|
154
|
+
}
|
|
155
|
+
return dirs;
|
|
156
|
+
}
|
|
157
|
+
/** Sub-budget reserved for compiling the Windows lock helper so the PowerShell fallback always retains at least ~2/3 of
|
|
158
|
+
* the caller's `timeoutMs` budget. */
|
|
159
|
+
export function winLockHelperCompileBudget(budgetMs) {
|
|
160
|
+
if (!Number.isFinite(budgetMs) || budgetMs <= 0)
|
|
161
|
+
return 0;
|
|
162
|
+
return Math.min(5_000, Math.floor(budgetMs / 3));
|
|
163
|
+
}
|
|
164
|
+
/** Cooldown before retrying a failed Windows lock helper compile/spawn/crash (permanent disable is only for missing `csc.exe`). */
|
|
165
|
+
export const WIN_LOCK_HELPER_COOLDOWN_MS = 60_000;
|
|
166
|
+
function abortError() {
|
|
167
|
+
return Object.assign(new Error("lock helper compile aborted"), { code: "ABORT_ERR", name: "AbortError", killed: true });
|
|
168
|
+
}
|
|
169
|
+
function isMissingCompilerError(error) {
|
|
170
|
+
if (!error || typeof error !== "object")
|
|
171
|
+
return false;
|
|
172
|
+
const e = error;
|
|
173
|
+
return e.compilerMissing === true;
|
|
174
|
+
}
|
|
175
|
+
/** Compile and atomically publish `DsaLock.exe` into `cacheDir` (reusing an existing binary immediately). Safe under
|
|
176
|
+
* concurrent multi-process compilation: each builder compiles in a private staging dir and accepts an already-published
|
|
177
|
+
* binary if another process won the publish race. */
|
|
178
|
+
export async function compileWinLockHelper(cacheDir, options = {}) {
|
|
179
|
+
const exe = join(cacheDir, WIN_LOCK_HELPER_EXE);
|
|
180
|
+
if (readyExecutable(exe))
|
|
181
|
+
return exe;
|
|
182
|
+
if (options.signal?.aborted)
|
|
183
|
+
throw abortError();
|
|
184
|
+
await mkdir(cacheDir, { recursive: true });
|
|
185
|
+
if (readyExecutable(exe))
|
|
186
|
+
return exe;
|
|
187
|
+
const effectiveEnv = options.env ?? helperEnv();
|
|
188
|
+
let compiler;
|
|
189
|
+
try {
|
|
190
|
+
compiler = options.compiler ?? frameworkCompiler(effectiveEnv, options.arch ?? process.arch);
|
|
191
|
+
}
|
|
192
|
+
catch (error) {
|
|
193
|
+
throw Object.assign(error instanceof Error ? error : new Error(String(error)), { compilerMissing: true });
|
|
194
|
+
}
|
|
195
|
+
const stage = join(cacheDir, `build-${process.pid.toString(36)}-${randomBytes(8).toString("hex")}`);
|
|
196
|
+
const build = "DsaLock.build.exe";
|
|
197
|
+
await mkdir(stage, { recursive: true });
|
|
198
|
+
try {
|
|
199
|
+
if (options.signal?.aborted)
|
|
200
|
+
throw abortError();
|
|
201
|
+
await writeFile(join(stage, WIN_LOCK_HELPER_SOURCE_FILE), WIN_LOCK_HELPER_SOURCE, "utf8");
|
|
202
|
+
await new Promise((resolve, reject) => {
|
|
203
|
+
if (options.signal?.aborted) {
|
|
204
|
+
reject(abortError());
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
207
|
+
let settled = false;
|
|
208
|
+
const done = (fn) => {
|
|
209
|
+
if (settled)
|
|
210
|
+
return;
|
|
211
|
+
settled = true;
|
|
212
|
+
clearTimeout(killTimer);
|
|
213
|
+
options.signal?.removeEventListener("abort", onAbort);
|
|
214
|
+
fn();
|
|
215
|
+
};
|
|
216
|
+
const child = execFile(compiler, ["/nologo", "/optimize+", "/codepage:65001", "/target:exe", `/out:${build}`, WIN_LOCK_HELPER_SOURCE_FILE], {
|
|
217
|
+
cwd: stage,
|
|
218
|
+
windowsHide: true,
|
|
219
|
+
env: effectiveEnv,
|
|
220
|
+
maxBuffer: 1024 * 1024,
|
|
221
|
+
encoding: "utf8",
|
|
222
|
+
}, (error, stdout, stderr) => {
|
|
223
|
+
if (!error) {
|
|
224
|
+
done(resolve);
|
|
225
|
+
return;
|
|
226
|
+
}
|
|
227
|
+
const code = error.code;
|
|
228
|
+
const detail = String(stderr || stdout || "").trim().replace(/\s+/g, " ").slice(0, 200);
|
|
229
|
+
const wrapped = Object.assign(new Error(`lock helper compile failed: ${error.message}${detail ? `: ${detail}` : ""}`), {
|
|
230
|
+
killed: error.killed,
|
|
231
|
+
code,
|
|
232
|
+
compilerMissing: code === "ENOENT" && !stderr && !stdout,
|
|
233
|
+
});
|
|
234
|
+
done(() => reject(wrapped));
|
|
235
|
+
});
|
|
236
|
+
const terminateChild = () => {
|
|
237
|
+
try {
|
|
238
|
+
child.kill("SIGKILL");
|
|
239
|
+
}
|
|
240
|
+
catch { /* gone */ }
|
|
241
|
+
child.stdin?.destroy();
|
|
242
|
+
child.stdout?.destroy();
|
|
243
|
+
child.stderr?.destroy();
|
|
244
|
+
child.unref();
|
|
245
|
+
};
|
|
246
|
+
const onAbort = () => {
|
|
247
|
+
terminateChild();
|
|
248
|
+
done(() => reject(abortError()));
|
|
249
|
+
};
|
|
250
|
+
options.signal?.addEventListener("abort", onAbort, { once: true });
|
|
251
|
+
const timeout = options.timeoutMs ?? 30_000;
|
|
252
|
+
const killTimer = setTimeout(() => {
|
|
253
|
+
terminateChild();
|
|
254
|
+
done(() => reject(Object.assign(new Error(`lock helper compile timed out (${timeout} ms)`), { killed: true, code: "ETIMEDOUT" })));
|
|
255
|
+
}, Math.max(1, timeout));
|
|
256
|
+
killTimer.unref();
|
|
257
|
+
});
|
|
258
|
+
if (options.signal?.aborted)
|
|
259
|
+
throw abortError();
|
|
260
|
+
const built = join(stage, build);
|
|
261
|
+
const renameFile = options.renameFile ?? rename;
|
|
262
|
+
const deadline = Date.now() + (options.publishMs ?? 5_000);
|
|
263
|
+
const retryMs = options.retryMs ?? 50;
|
|
264
|
+
for (;;) {
|
|
265
|
+
if (options.signal?.aborted)
|
|
266
|
+
throw abortError();
|
|
267
|
+
if (readyExecutable(exe))
|
|
268
|
+
return exe;
|
|
269
|
+
try {
|
|
270
|
+
await renameFile(built, exe);
|
|
271
|
+
if (readyExecutable(exe))
|
|
272
|
+
return exe;
|
|
273
|
+
throw new Error(`lock helper executable missing after publish: ${exe}`);
|
|
274
|
+
}
|
|
275
|
+
catch (error) {
|
|
276
|
+
if (readyExecutable(exe))
|
|
277
|
+
return exe;
|
|
278
|
+
const code = error?.code ?? "";
|
|
279
|
+
if (!["EBUSY", "EPERM", "EACCES", "EAGAIN", "EEXIST"].includes(code) || Date.now() + retryMs >= deadline) {
|
|
280
|
+
throw error;
|
|
281
|
+
}
|
|
282
|
+
await new Promise(r => {
|
|
283
|
+
const onAbort = () => { clearTimeout(waitTimer); r(); };
|
|
284
|
+
const waitTimer = setTimeout(() => { options.signal?.removeEventListener("abort", onAbort); r(); }, retryMs);
|
|
285
|
+
options.signal?.addEventListener("abort", onAbort, { once: true });
|
|
286
|
+
});
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
finally {
|
|
291
|
+
await rm(stage, { recursive: true, force: true, maxRetries: 3, retryDelay: 50 }).catch(() => { });
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
let cachedWinHelper;
|
|
295
|
+
let winHelperDisabled = false;
|
|
296
|
+
let winHelperCooldownUntil = 0;
|
|
297
|
+
let winHelperInFlight;
|
|
298
|
+
/** Test seam: reset module-level cached Windows lock helper state. */
|
|
299
|
+
export function resetWinLockHelperState() {
|
|
300
|
+
cachedWinHelper = undefined;
|
|
301
|
+
winHelperDisabled = false;
|
|
302
|
+
winHelperCooldownUntil = 0;
|
|
303
|
+
if (winHelperInFlight) {
|
|
304
|
+
winHelperInFlight.controller.abort();
|
|
305
|
+
winHelperInFlight = undefined;
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
/** Resolve or compile the cached Windows lock helper within the reserved sub-budget so PowerShell fallback keeps the
|
|
309
|
+
* majority of `budgetMs`. Transient failures apply a cooldown; only a missing compiler disables permanently. */
|
|
310
|
+
export async function resolveWinLockHelper(budgetMs, options = {}) {
|
|
311
|
+
const now = options.now ?? Date.now;
|
|
312
|
+
const cooldownMs = options.cooldownMs ?? WIN_LOCK_HELPER_COOLDOWN_MS;
|
|
313
|
+
if (cachedWinHelper && readyExecutable(cachedWinHelper))
|
|
314
|
+
return cachedWinHelper;
|
|
315
|
+
cachedWinHelper = undefined;
|
|
316
|
+
if (winHelperDisabled)
|
|
317
|
+
return undefined;
|
|
318
|
+
if (now() < winHelperCooldownUntil)
|
|
319
|
+
return undefined;
|
|
320
|
+
const dirs = winLockHelperCacheDirs(options.env, options.arch);
|
|
321
|
+
if (!dirs.length)
|
|
322
|
+
return undefined;
|
|
323
|
+
for (const dir of dirs) {
|
|
324
|
+
const exe = join(dir, WIN_LOCK_HELPER_EXE);
|
|
325
|
+
if (readyExecutable(exe)) {
|
|
326
|
+
cachedWinHelper = exe;
|
|
327
|
+
return exe;
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
const compileBudget = winLockHelperCompileBudget(budgetMs);
|
|
331
|
+
if (compileBudget <= 0)
|
|
332
|
+
return undefined;
|
|
333
|
+
if (!winHelperInFlight) {
|
|
334
|
+
const controller = new AbortController();
|
|
335
|
+
const compileFn = options.compile ?? compileWinLockHelper;
|
|
336
|
+
const entry = {
|
|
337
|
+
controller,
|
|
338
|
+
waiters: 0,
|
|
339
|
+
promise: (async () => {
|
|
340
|
+
let missingCompiler = false;
|
|
341
|
+
let aborted = false;
|
|
342
|
+
for (const dir of dirs) {
|
|
343
|
+
if (controller.signal.aborted) {
|
|
344
|
+
aborted = true;
|
|
345
|
+
break;
|
|
346
|
+
}
|
|
347
|
+
try {
|
|
348
|
+
const exe = await compileFn(dir, {
|
|
349
|
+
...(options.compiler !== undefined ? { compiler: options.compiler } : {}),
|
|
350
|
+
timeoutMs: compileBudget,
|
|
351
|
+
signal: controller.signal,
|
|
352
|
+
...(options.env !== undefined ? { env: options.env } : {}),
|
|
353
|
+
...(options.arch !== undefined ? { arch: options.arch } : {}),
|
|
354
|
+
});
|
|
355
|
+
cachedWinHelper = exe;
|
|
356
|
+
return exe;
|
|
357
|
+
}
|
|
358
|
+
catch (error) {
|
|
359
|
+
if (isMissingCompilerError(error)) {
|
|
360
|
+
missingCompiler = true;
|
|
361
|
+
}
|
|
362
|
+
else if (controller.signal.aborted || error?.name === "AbortError" || error?.code === "ABORT_ERR") {
|
|
363
|
+
aborted = true;
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
if (missingCompiler) {
|
|
368
|
+
winHelperDisabled = true;
|
|
369
|
+
}
|
|
370
|
+
else if (!aborted) {
|
|
371
|
+
winHelperCooldownUntil = Math.max(winHelperCooldownUntil, now() + cooldownMs);
|
|
372
|
+
}
|
|
373
|
+
return undefined;
|
|
374
|
+
})().finally(() => {
|
|
375
|
+
if (winHelperInFlight === entry)
|
|
376
|
+
winHelperInFlight = undefined;
|
|
377
|
+
}),
|
|
378
|
+
};
|
|
379
|
+
winHelperInFlight = entry;
|
|
380
|
+
}
|
|
381
|
+
const active = winHelperInFlight;
|
|
382
|
+
active.waiters += 1;
|
|
383
|
+
let timer;
|
|
384
|
+
let timedOut = false;
|
|
385
|
+
try {
|
|
386
|
+
return await Promise.race([
|
|
387
|
+
active.promise,
|
|
388
|
+
new Promise(resolve => {
|
|
389
|
+
timer = setTimeout(() => { timedOut = true; resolve(undefined); }, compileBudget);
|
|
390
|
+
}),
|
|
391
|
+
]);
|
|
392
|
+
}
|
|
393
|
+
finally {
|
|
394
|
+
clearTimeout(timer);
|
|
395
|
+
active.waiters -= 1;
|
|
396
|
+
if (timedOut && active.waiters <= 0) {
|
|
397
|
+
// Kill and unref the timed-out compiler so short-lived CLI processes never hang after falling back to PowerShell.
|
|
398
|
+
active.controller.abort();
|
|
399
|
+
winHelperCooldownUntil = Math.max(winHelperCooldownUntil, now() + cooldownMs);
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
const powershellHelper = () => ({
|
|
404
|
+
command: powershellPath(),
|
|
405
|
+
args: ["-NoLogo", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", powershell],
|
|
406
|
+
pathInEnv: true,
|
|
407
|
+
});
|
|
408
|
+
const defaultHelpers = async (budgetMs) => {
|
|
409
|
+
if (process.platform === "win32") {
|
|
410
|
+
const exe = await resolveWinLockHelper(budgetMs);
|
|
411
|
+
const ps = powershellHelper();
|
|
412
|
+
return exe ? [{ command: exe, args: [], pathInEnv: true, fallbackOnSpawnError: true, selfHealOnCrash: true }, ps] : [ps];
|
|
413
|
+
}
|
|
414
|
+
return [{ command: "perl", args: ["-e", perl] }, { command: "python3", args: ["-c", python] }];
|
|
415
|
+
};
|
|
15
416
|
/** The error code of a helper that did not answer in time (a slow or suspended machine): transient, not a broken lock. */
|
|
16
417
|
export const LOCK_TIMEOUT = "DSA_LOCK_TIMEOUT";
|
|
17
418
|
export function isLockTimeout(error) { return error?.code === LOCK_TIMEOUT; }
|
|
18
|
-
/** C4: A kernel
|
|
419
|
+
/** C4: A kernel lock held by a helper whose stdin belongs only to the holder: `flock` through perl or python3 on
|
|
420
|
+
* Linux/macOS, a `FileShare.None` `FileStream` handle through a cached compiled .NET Framework helper (with Windows
|
|
421
|
+
* PowerShell fallback) on Windows. */
|
|
19
422
|
export class OsLock {
|
|
20
|
-
/** `timeoutMs` bounds how long the helper may take to answer (3 s
|
|
423
|
+
/** `timeoutMs` bounds how long the helper may take to answer (3 s on Unix, 15 s on Windows for cold helper compile or
|
|
424
|
+
* PowerShell fallback startup; background callers allow 15 s everywhere). */
|
|
21
425
|
timeoutMs;
|
|
22
|
-
|
|
426
|
+
candidates;
|
|
427
|
+
constructor(timeoutMs = process.platform === "win32" ? 15_000 : 3000, candidates) {
|
|
428
|
+
this.timeoutMs = timeoutMs;
|
|
429
|
+
this.candidates = candidates;
|
|
430
|
+
}
|
|
23
431
|
/** C4: Attempt non-blocking exclusion; holder death closes the helper's stdin. */
|
|
24
432
|
async tryAcquire(path) {
|
|
25
|
-
|
|
433
|
+
const win = process.platform === "win32";
|
|
434
|
+
if (!this.candidates && !win && process.platform !== "linux" && process.platform !== "darwin") {
|
|
26
435
|
throw new Error(`C4 capability unavailable: ${process.platform}`);
|
|
27
|
-
|
|
28
|
-
|
|
436
|
+
}
|
|
437
|
+
const deadline = performance.now() + this.timeoutMs;
|
|
438
|
+
const candidates = this.candidates ?? await defaultHelpers(this.timeoutMs);
|
|
439
|
+
for (const candidate of candidates) {
|
|
440
|
+
const remaining = Math.ceil(deadline - performance.now());
|
|
441
|
+
if (remaining <= 0) {
|
|
442
|
+
throw Object.assign(new Error(`C4 lock helper timeout (${this.timeoutMs} ms)`), { code: LOCK_TIMEOUT });
|
|
443
|
+
}
|
|
444
|
+
const args = candidate.pathInEnv ? [...candidate.args] : [...candidate.args, path];
|
|
445
|
+
const env = candidate.pathInEnv
|
|
446
|
+
? (win ? mergeEnv(helperEnv(), { DSA_LOCK_PATH: path }) : { ...process.env, DSA_LOCK_PATH: path })
|
|
447
|
+
: process.env;
|
|
448
|
+
const child = spawn(candidate.command, args, { stdio: "pipe", env, windowsHide: true });
|
|
29
449
|
let errorText = "";
|
|
450
|
+
let spawnFailed = false;
|
|
451
|
+
let exitCode;
|
|
30
452
|
child.stderr.on("data", chunk => { errorText = (errorText + chunk).slice(-4096); });
|
|
31
453
|
child.stdin.on("error", () => { });
|
|
32
|
-
const
|
|
33
|
-
child.once("error", reject);
|
|
454
|
+
const exited = new Promise((resolve, reject) => {
|
|
455
|
+
child.once("error", error => { spawnFailed = true; reject(error); });
|
|
34
456
|
child.once("exit", resolve);
|
|
35
457
|
});
|
|
36
|
-
|
|
458
|
+
const closed = new Promise((resolve, reject) => {
|
|
459
|
+
child.once("error", error => { spawnFailed = true; reject(error); });
|
|
460
|
+
child.once("close", resolve);
|
|
461
|
+
});
|
|
462
|
+
void exited.catch(() => { });
|
|
463
|
+
void closed.catch(() => { });
|
|
37
464
|
let timer;
|
|
38
465
|
try {
|
|
39
466
|
const acquired = await Promise.race([
|
|
@@ -47,12 +474,13 @@ export class OsLock {
|
|
|
47
474
|
reject(new Error("Invalid lock helper response"));
|
|
48
475
|
});
|
|
49
476
|
}),
|
|
50
|
-
|
|
477
|
+
closed.then(code => {
|
|
478
|
+
exitCode = code;
|
|
51
479
|
if (code === 2)
|
|
52
480
|
return false;
|
|
53
481
|
throw new Error(`C4 lock helper exited (${code}): ${errorText}`);
|
|
54
482
|
}),
|
|
55
|
-
new Promise((_, reject) => { timer = setTimeout(() => reject(Object.assign(new Error(`C4 lock helper timeout (${this.timeoutMs} ms)`), { code: LOCK_TIMEOUT })),
|
|
483
|
+
new Promise((_, reject) => { timer = setTimeout(() => reject(Object.assign(new Error(`C4 lock helper timeout (${this.timeoutMs} ms)`), { code: LOCK_TIMEOUT })), remaining); }),
|
|
56
484
|
]);
|
|
57
485
|
if (!acquired)
|
|
58
486
|
return null;
|
|
@@ -61,7 +489,7 @@ export class OsLock {
|
|
|
61
489
|
child.stdin.end();
|
|
62
490
|
const kill = setTimeout(() => child.kill("SIGKILL"), 1000);
|
|
63
491
|
try {
|
|
64
|
-
await
|
|
492
|
+
await exited;
|
|
65
493
|
}
|
|
66
494
|
finally {
|
|
67
495
|
clearTimeout(kill);
|
|
@@ -70,15 +498,35 @@ export class OsLock {
|
|
|
70
498
|
}
|
|
71
499
|
catch (error) {
|
|
72
500
|
child.kill("SIGKILL");
|
|
73
|
-
await
|
|
74
|
-
|
|
501
|
+
await exited.catch(() => { });
|
|
502
|
+
const code = error.code;
|
|
503
|
+
if (code === "ENOENT" || (spawnFailed && candidate.fallbackOnSpawnError)) {
|
|
504
|
+
if (candidate.command === cachedWinHelper)
|
|
505
|
+
cachedWinHelper = undefined;
|
|
506
|
+
if (candidate.selfHealOnCrash) {
|
|
507
|
+
if (code === "EACCES" || code === "EPERM" || code === "EBUSY") {
|
|
508
|
+
winHelperCooldownUntil = Math.max(winHelperCooldownUntil, Date.now() + WIN_LOCK_HELPER_COOLDOWN_MS);
|
|
509
|
+
}
|
|
510
|
+
else if (code !== "ENOENT") {
|
|
511
|
+
await rm(candidate.command, { force: true }).catch(() => { });
|
|
512
|
+
winHelperCooldownUntil = Math.max(winHelperCooldownUntil, Date.now() + WIN_LOCK_HELPER_COOLDOWN_MS);
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
continue;
|
|
516
|
+
}
|
|
517
|
+
if (candidate.selfHealOnCrash && !isLockTimeout(error) && typeof exitCode === "number" && exitCode !== 0 && exitCode !== 2 && !errorText.startsWith("open: ")) {
|
|
518
|
+
if (candidate.command === cachedWinHelper)
|
|
519
|
+
cachedWinHelper = undefined;
|
|
520
|
+
await rm(candidate.command, { force: true }).catch(() => { });
|
|
521
|
+
winHelperCooldownUntil = Math.max(winHelperCooldownUntil, Date.now() + WIN_LOCK_HELPER_COOLDOWN_MS);
|
|
75
522
|
continue;
|
|
523
|
+
}
|
|
76
524
|
throw error;
|
|
77
525
|
}
|
|
78
526
|
finally {
|
|
79
527
|
clearTimeout(timer);
|
|
80
528
|
}
|
|
81
529
|
}
|
|
82
|
-
throw new Error("C4 capability unavailable: install perl or python3 for flock");
|
|
530
|
+
throw new Error(win ? "C4 capability unavailable: PowerShell lock helper was not found" : "C4 capability unavailable: install perl or python3 for flock");
|
|
83
531
|
}
|
|
84
532
|
}
|
|
@@ -5,6 +5,7 @@ import { readFile, readdir } from "node:fs/promises";
|
|
|
5
5
|
import { closeSync, existsSync, openSync, readFileSync, readdirSync, readSync } from "node:fs";
|
|
6
6
|
import { execFile, execFileSync } from "node:child_process";
|
|
7
7
|
import { promisify } from "node:util";
|
|
8
|
+
import { attachScannedCommand, scannedCommand, winProcessRows, winSnapshotSync, winStart, winTag } from "./windows.js";
|
|
8
9
|
/** `ps` by its absolute path where it has one (macOS and Linux: /bin/ps), so a minimal PATH (a service unit, a test
|
|
9
10
|
* that hides `pi`) does not take the process table away. */
|
|
10
11
|
export const PS = existsSync("/bin/ps") ? "/bin/ps" : "ps";
|
|
@@ -50,6 +51,8 @@ export async function captureStart(pid) {
|
|
|
50
51
|
throw error;
|
|
51
52
|
}
|
|
52
53
|
}
|
|
54
|
+
if (process.platform === "win32")
|
|
55
|
+
return winStart(pid);
|
|
53
56
|
throw new Error(`C2 capability unavailable: ${process.platform}`);
|
|
54
57
|
}
|
|
55
58
|
/** C2: Observe live process identities, inherited tags and cumulative CPU time. */
|
|
@@ -61,6 +64,7 @@ export class ProcessTable {
|
|
|
61
64
|
ticks;
|
|
62
65
|
platform;
|
|
63
66
|
ps;
|
|
67
|
+
winRows;
|
|
64
68
|
tagName;
|
|
65
69
|
constructor(options = {}) {
|
|
66
70
|
this.tagName = options.tagName ?? "DSA_EXEC";
|
|
@@ -70,9 +74,21 @@ export class ProcessTable {
|
|
|
70
74
|
this.ps = options.ps ?? (async () => (await exec(PS, ["-axEww", "-o", "pid=,ppid=,lstart=,time=,stat=,command="],
|
|
71
75
|
// The whole table with environments is large; 2 s proved too short on loaded macOS machines.
|
|
72
76
|
{ env: { ...process.env, LC_ALL: "C" }, timeout: 10_000, maxBuffer: 32 * 1024 * 1024 })).stdout);
|
|
77
|
+
this.winRows = options.winRows ?? (() => winProcessRows());
|
|
73
78
|
}
|
|
74
|
-
/** Synchronous liveness for lease readers. Unlike execution tracking, hold tags are reread after each exec.
|
|
79
|
+
/** Synchronous liveness for lease readers. Unlike execution tracking, hold tags are reread after each exec. Windows
|
|
80
|
+
* cannot read another process's environment, so hold tags fall back to the ticket's process tree (tagged returns
|
|
81
|
+
* nothing there). */
|
|
75
82
|
tagged(tag) {
|
|
83
|
+
if (this.platform === "win32") {
|
|
84
|
+
try {
|
|
85
|
+
return [...winSnapshotSync().values()].filter(row => winTag(row.command, this.tagName) === tag)
|
|
86
|
+
.map(row => ({ pid: row.pid, start: row.start }));
|
|
87
|
+
}
|
|
88
|
+
catch {
|
|
89
|
+
return []; /* snapshot unavailable: group-only fallback */
|
|
90
|
+
}
|
|
91
|
+
}
|
|
76
92
|
if (this.platform === "darwin") {
|
|
77
93
|
try {
|
|
78
94
|
return this.mac(execFileSync(PS, ["-axEww", "-o", "pid=,ppid=,lstart=,time=,stat=,command="], { encoding: "utf8", env: { ...process.env, LC_ALL: "C" }, timeout: 1000, maxBuffer: 32 * 1024 * 1024 }), new Set([tag]))
|
|
@@ -108,7 +124,13 @@ export class ProcessTable {
|
|
|
108
124
|
/** C2, F1: Concurrent observations share a scan; fences wait out all pre-request work. */
|
|
109
125
|
async list(knownExecs = new Set(), options = {}) {
|
|
110
126
|
const value = await this.listRaw(options);
|
|
111
|
-
|
|
127
|
+
if (typeof value === "string")
|
|
128
|
+
return this.mac(value, knownExecs);
|
|
129
|
+
// A Windows tag comes from a command line, so a known-id filter keeps unrelated text from becoming an execution.
|
|
130
|
+
if (this.platform === "win32")
|
|
131
|
+
return value.map(p => p.tag !== undefined && !knownExecs.has(p.tag)
|
|
132
|
+
? attachScannedCommand({ ...p, tag: undefined }, scannedCommand(p)) : p);
|
|
133
|
+
return value;
|
|
112
134
|
}
|
|
113
135
|
async listRaw(options) {
|
|
114
136
|
if (options.fresh && this.pending)
|
|
@@ -130,6 +152,13 @@ export class ProcessTable {
|
|
|
130
152
|
}
|
|
131
153
|
}
|
|
132
154
|
async read() {
|
|
155
|
+
if (this.platform === "win32")
|
|
156
|
+
return (await this.winRows()).map(row => {
|
|
157
|
+
const tag = winTag(row.command, this.tagName);
|
|
158
|
+
return attachScannedCommand({ pid: row.pid, ppid: row.ppid, start: row.start,
|
|
159
|
+
...(row.cpuMs !== undefined ? { cpuMs: row.cpuMs } : {}),
|
|
160
|
+
...(tag ? { tag } : {}) }, row.command);
|
|
161
|
+
});
|
|
133
162
|
if (this.platform === "darwin")
|
|
134
163
|
return this.ps();
|
|
135
164
|
if (this.platform !== "linux")
|