@loucompanion/forge-bridge 0.1.4-dev.4677bbd22f17 → 0.1.4-dev.60e18c3cfec6
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/README.md +33 -0
- package/dist/bridge/bridge.base.d.ts +9 -0
- package/dist/bridge/bridge.service.d.ts +72 -1
- package/dist/bridge/bridge.service.js +308 -9
- package/dist/bridge/bridge.types.d.ts +16 -0
- package/dist/bridge/local-yield-flag.d.ts +6 -0
- package/dist/bridge/local-yield-flag.js +34 -0
- package/dist/bridge/runner-host-capabilities.d.ts +2 -0
- package/dist/bridge/runner-host-capabilities.js +4 -0
- package/dist/bridge/test-postgres-capability.d.ts +14 -0
- package/dist/bridge/test-postgres-capability.js +120 -0
- package/dist/cleanup/cleanup.service.d.ts +9 -0
- package/dist/cleanup/cleanup.service.js +72 -109
- package/dist/cleanup/cleanup.types.d.ts +4 -0
- package/dist/cleanup/forge-owned-paths.d.ts +9 -0
- package/dist/cleanup/forge-owned-paths.js +53 -0
- package/dist/cleanup/host-runtime-ledger.d.ts +5 -0
- package/dist/cleanup/host-runtime-ledger.js +109 -0
- package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
- package/dist/cleanup/managed-branch-sweep.js +111 -0
- package/dist/cli/cli.help.js +18 -0
- package/dist/cli/cli.service.d.ts +16 -0
- package/dist/cli/cli.service.js +142 -16
- package/dist/cli/local-config.d.ts +4 -0
- package/dist/cli/local-config.js +26 -4
- package/dist/runtime/aspnet-runtime-prebuild.js +94 -6
- package/dist/runtime/host-load-admission.d.ts +60 -0
- package/dist/runtime/host-load-admission.js +99 -0
- package/dist/runtime/host-load-child-environment.d.ts +22 -0
- package/dist/runtime/host-load-child-environment.js +67 -0
- package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
- package/dist/runtime/host-load-forge-cgroups.js +140 -0
- package/dist/runtime/host-load-governor-config.d.ts +43 -0
- package/dist/runtime/host-load-governor-config.js +76 -0
- package/dist/runtime/host-load-governor.d.ts +174 -0
- package/dist/runtime/host-load-governor.js +541 -0
- package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
- package/dist/runtime/host-load-ledger-lock.js +185 -0
- package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
- package/dist/runtime/host-load-runtime-settings.js +78 -0
- package/dist/runtime/host-load-sampler.d.ts +43 -0
- package/dist/runtime/host-load-sampler.js +74 -6
- package/dist/runtime/host-load-step-class.d.ts +68 -0
- package/dist/runtime/host-load-step-class.js +106 -0
- package/dist/runtime/host-load-step-reaper.d.ts +27 -0
- package/dist/runtime/host-load-step-reaper.js +95 -0
- package/dist/runtime/host-load-step-run.d.ts +73 -0
- package/dist/runtime/host-load-step-run.js +102 -0
- package/dist/runtime/host-load-token-ledger.d.ts +174 -0
- package/dist/runtime/host-load-token-ledger.js +421 -0
- package/dist/runtime/host-pressure-stall.d.ts +21 -1
- package/dist/runtime/host-pressure-stall.js +48 -1
- package/dist/runtime/host-runtime-contract.d.ts +3 -0
- package/dist/runtime/host-runtime-contract.js +4 -1
- package/dist/runtime/host-runtime-lease.d.ts +74 -4
- package/dist/runtime/host-runtime-lease.js +279 -10
- package/dist/runtime/host-runtime-promotion.js +12 -0
- package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
- package/dist/runtime/host-runtime-requirements-check.js +29 -0
- package/dist/runtime/host-runtime-requirements.d.ts +36 -0
- package/dist/runtime/host-runtime-requirements.js +117 -0
- package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
- package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
- package/dist/runtime/runner-settings.d.ts +100 -0
- package/dist/runtime/runner-settings.js +214 -0
- package/dist/sandbox/host-capacity-broker.d.ts +107 -0
- package/dist/sandbox/host-capacity-broker.js +315 -0
- package/dist/sandbox/runtime.d.ts +10 -1
- package/dist/sandbox/runtime.js +45 -2
- package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
- package/dist/sandbox/sandbox-cgroups.js +42 -0
- package/dist/session/managed-attempt-tools.d.ts +2 -0
- package/dist/session/managed-attempt-tools.js +156 -37
- package/dist/session/managed-command-host-load.d.ts +45 -0
- package/dist/session/managed-command-host-load.js +82 -0
- package/dist/session/mcp-argument-coercion.d.ts +23 -0
- package/dist/session/mcp-argument-coercion.js +121 -0
- package/dist/session/phase-completion.artifacts.d.ts +7 -0
- package/dist/session/phase-completion.artifacts.js +94 -25
- package/dist/session/phase-completion.command-validation.d.ts +7 -0
- package/dist/session/phase-completion.command-validation.js +77 -0
- package/dist/session/phase-completion.d.ts +4 -0
- package/dist/session/phase-completion.helpers.js +13 -12
- package/dist/session/phase-completion.js +4 -0
- package/dist/session/phase-completion.prompts.js +6 -1
- package/dist/session/phase-completion.runtime.d.ts +5 -3
- package/dist/session/phase-completion.runtime.js +49 -19
- package/dist/session/phase-completion.schema-parts.d.ts +19 -0
- package/dist/session/phase-completion.schema-parts.js +188 -0
- package/dist/session/phase-completion.schemas.d.ts +3 -3
- package/dist/session/phase-completion.schemas.js +184 -209
- package/dist/session/phase-completion.validation.d.ts +2 -3
- package/dist/session/phase-completion.validation.js +46 -92
- package/dist/session/pre-publication-host-load.d.ts +27 -0
- package/dist/session/pre-publication-host-load.js +111 -0
- package/dist/session/pre-publication-process.d.ts +3 -0
- package/dist/session/pre-publication-process.js +23 -11
- package/dist/session/pre-publication-step-execution.d.ts +11 -0
- package/dist/session/pre-publication-step-execution.js +49 -0
- package/dist/session/pre-publication-validation.d.ts +9 -9
- package/dist/session/pre-publication-validation.js +21 -55
- package/dist/session/provider-cli/provider-cli.process.js +2 -2
- package/dist/session/provider-cli/provider-cli.prompts.js +5 -2
- package/dist/session/provider-cli/provider-cli.service.d.ts +6 -0
- package/dist/session/provider-cli/provider-cli.service.js +132 -14
- package/dist/session/provider-cli/provider-cli.types.d.ts +30 -0
- package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
- package/dist/session/sandbox-host-capacity-gate.js +229 -0
- package/dist/session/session.base.d.ts +9 -1
- package/dist/session/session.service.d.ts +9 -2
- package/dist/session/session.service.js +120 -5
- package/dist/session/session.types.d.ts +3 -0
- package/dist/session/session.types.js +3 -3
- package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
- package/dist/session/workspace-runtime-fingerprint.js +138 -0
- package/dist/shared/process/host-process-supervisor.d.ts +1 -0
- package/dist/shared/process/host-process-supervisor.js +1 -1
- package/dist/shared/process/process-tree.d.ts +52 -0
- package/dist/shared/process/process-tree.js +144 -0
- package/dist/shared/process/process.d.ts +67 -0
- package/dist/shared/process/process.js +213 -11
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/worktree/dependency-warmer.d.ts +25 -0
- package/dist/worktree/dependency-warmer.js +46 -10
- package/dist/worktree/worktree.service.d.ts +10 -1
- package/dist/worktree/worktree.service.js +42 -2
- package/dist/worktree/worktree.types.d.ts +7 -0
- package/package.json +1 -1
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import fs from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { GitClient } from "../shared/git/git.js";
|
|
5
|
+
import { loadHostRuntimeContract } from "../runtime/host-runtime-contract.js";
|
|
6
|
+
import { hostRuntimeContractFingerprint } from "../runtime/host-runtime-promotion.js";
|
|
7
|
+
import { isRuntimeOnlyPath } from "./publishable-worktree-changes.js";
|
|
8
|
+
/** Untracked files up to this size are hashed by content; larger ones by size and mtime. */
|
|
9
|
+
const untrackedContentHashLimitBytes = 1024 * 1024;
|
|
10
|
+
/**
|
|
11
|
+
* Forge's own runtime output never changes what the application runs, and Forge
|
|
12
|
+
* rewrites some of it (readiness manifests, completion artifacts) between passes.
|
|
13
|
+
*/
|
|
14
|
+
const runtimeOnlyPathspecs = [
|
|
15
|
+
":(exclude).local",
|
|
16
|
+
":(exclude).forge/work-items",
|
|
17
|
+
":(exclude).forge/stories",
|
|
18
|
+
];
|
|
19
|
+
export async function readWorkspaceRuntimeFingerprint(worktreePath, git = new GitClient()) {
|
|
20
|
+
const headSha = (await git.run(worktreePath, ["rev-parse", "--verify", "HEAD^{commit}"])).trim().toLowerCase();
|
|
21
|
+
const mergeHead = await readMergeHead(git, worktreePath);
|
|
22
|
+
// A mode change (chmod +x on a launch script) changes what runs. The repository may set
|
|
23
|
+
// core.fileMode=false, which would drop it from the diff, so this read always records modes.
|
|
24
|
+
const diff = await git.run(worktreePath, ["-c", "core.fileMode=true", "diff", "HEAD", "--binary", "--no-ext-diff", "--no-textconv", "--", ".", ...runtimeOnlyPathspecs]);
|
|
25
|
+
const diffDigest = sha256(diff);
|
|
26
|
+
const untracked = (await git.run(worktreePath, [
|
|
27
|
+
"ls-files", "--others", "--exclude-standard", "-z", "--", ".", ...runtimeOnlyPathspecs,
|
|
28
|
+
]))
|
|
29
|
+
.split("\0")
|
|
30
|
+
.filter(entry => entry.length > 0 && !isRuntimeOnlyPath(entry))
|
|
31
|
+
.sort((left, right) => left.localeCompare(right));
|
|
32
|
+
const untrackedHash = createHash("sha256");
|
|
33
|
+
for (const relative of untracked) {
|
|
34
|
+
untrackedHash.update(relative).update("\0");
|
|
35
|
+
const absolute = path.join(worktreePath, relative);
|
|
36
|
+
const stat = await fs.lstat(absolute).catch(() => null);
|
|
37
|
+
if (!stat) {
|
|
38
|
+
untrackedHash.update("missing\0");
|
|
39
|
+
continue;
|
|
40
|
+
}
|
|
41
|
+
// Like git, record the executable bit: chmod changes what runs without touching content or mtime.
|
|
42
|
+
untrackedHash.update(stat.isFile() && (stat.mode & 0o111) !== 0 ? "exec\0" : "plain\0");
|
|
43
|
+
if (stat.isFile() && stat.size <= untrackedContentHashLimitBytes) {
|
|
44
|
+
const content = await fs.readFile(absolute).catch(() => null);
|
|
45
|
+
untrackedHash.update(content ? `content:${sha256(content)}\0` : `unreadable:${stat.size}:${stat.mtimeMs}\0`);
|
|
46
|
+
}
|
|
47
|
+
else {
|
|
48
|
+
untrackedHash.update(`stat:${stat.size}:${stat.mtimeMs}\0`);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
const untrackedDigest = `sha256:${untrackedHash.digest("hex")}`;
|
|
52
|
+
const runtimeInputsDigest = await readRuntimeInputsDigest(worktreePath);
|
|
53
|
+
const digest = sha256(JSON.stringify({ headSha, mergeHead, diffDigest, untrackedDigest, runtimeInputsDigest }));
|
|
54
|
+
return { headSha, mergeHead, diffDigest, untrackedDigest, runtimeInputsDigest, digest };
|
|
55
|
+
}
|
|
56
|
+
export function sameWorkspaceRuntimeFingerprint(left, right) {
|
|
57
|
+
return left !== null && right !== null && left.digest === right.digest;
|
|
58
|
+
}
|
|
59
|
+
/** Names what changed between two fingerprints, for the restart checkpoint. */
|
|
60
|
+
export function workspaceRuntimeFingerprintChanges(previous, current) {
|
|
61
|
+
if (!previous)
|
|
62
|
+
return ["unrecorded"];
|
|
63
|
+
const changes = [];
|
|
64
|
+
if (previous.headSha !== current.headSha)
|
|
65
|
+
changes.push("head");
|
|
66
|
+
if (previous.mergeHead !== current.mergeHead)
|
|
67
|
+
changes.push("merge_head");
|
|
68
|
+
if (previous.diffDigest !== current.diffDigest)
|
|
69
|
+
changes.push("tracked_changes");
|
|
70
|
+
if (previous.untrackedDigest !== current.untrackedDigest)
|
|
71
|
+
changes.push("untracked_files");
|
|
72
|
+
if (previous.runtimeInputsDigest !== current.runtimeInputsDigest)
|
|
73
|
+
changes.push("runtime_inputs");
|
|
74
|
+
return changes;
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* The loaded runtime contract (project file or derived) and each regular file inside the worktree
|
|
78
|
+
* that a configured launch names as its command or an argument, by executable bit and content.
|
|
79
|
+
* Ignored or not: these are exactly what the stack was launched from. Nothing else ignored is read.
|
|
80
|
+
*/
|
|
81
|
+
async function readRuntimeInputsDigest(worktreePath) {
|
|
82
|
+
const hash = createHash("sha256");
|
|
83
|
+
let contract;
|
|
84
|
+
try {
|
|
85
|
+
contract = await loadHostRuntimeContract(worktreePath);
|
|
86
|
+
}
|
|
87
|
+
catch (error) {
|
|
88
|
+
// An unloadable contract is a state of its own; the restart reports why it cannot load.
|
|
89
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
90
|
+
return sha256(`unloadable:${message.split(":", 1)[0]}`);
|
|
91
|
+
}
|
|
92
|
+
hash.update(`contract:${hostRuntimeContractFingerprint(contract)}\0`);
|
|
93
|
+
const root = await fs.realpath(worktreePath);
|
|
94
|
+
const named = new Set();
|
|
95
|
+
for (const port of contract.contract.runtime.ports) {
|
|
96
|
+
if (!port.launch)
|
|
97
|
+
continue;
|
|
98
|
+
const workingDirectory = path.resolve(root, port.launch.workingDirectory);
|
|
99
|
+
for (const candidate of [port.launch.command, ...port.launch.args]) {
|
|
100
|
+
if (!candidate || candidate.startsWith("-"))
|
|
101
|
+
continue;
|
|
102
|
+
const absolute = path.resolve(workingDirectory, candidate);
|
|
103
|
+
const relative = path.relative(root, absolute);
|
|
104
|
+
if (relative === "" || relative.startsWith("..") || path.isAbsolute(relative))
|
|
105
|
+
continue;
|
|
106
|
+
named.add(relative);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
for (const relative of [...named].sort((left, right) => left.localeCompare(right))) {
|
|
110
|
+
const stat = await fs.stat(path.join(root, relative)).catch(() => null);
|
|
111
|
+
if (!stat?.isFile())
|
|
112
|
+
continue;
|
|
113
|
+
hash.update(relative).update("\0").update((stat.mode & 0o111) !== 0 ? "exec\0" : "plain\0");
|
|
114
|
+
if (stat.size <= untrackedContentHashLimitBytes) {
|
|
115
|
+
const content = await fs.readFile(path.join(root, relative)).catch(() => null);
|
|
116
|
+
hash.update(content ? `content:${sha256(content)}\0` : `unreadable:${stat.size}:${stat.mtimeMs}\0`);
|
|
117
|
+
}
|
|
118
|
+
else {
|
|
119
|
+
hash.update(`stat:${stat.size}:${stat.mtimeMs}\0`);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
return `sha256:${hash.digest("hex")}`;
|
|
123
|
+
}
|
|
124
|
+
async function readMergeHead(git, worktreePath) {
|
|
125
|
+
const relative = (await git.run(worktreePath, ["rev-parse", "--git-path", "MERGE_HEAD"])).trim();
|
|
126
|
+
if (!relative)
|
|
127
|
+
return null;
|
|
128
|
+
const mergeHeadPath = path.resolve(worktreePath, relative);
|
|
129
|
+
const content = await fs.readFile(mergeHeadPath, "utf8").catch((error) => {
|
|
130
|
+
if (error.code === "ENOENT")
|
|
131
|
+
return null;
|
|
132
|
+
throw error;
|
|
133
|
+
});
|
|
134
|
+
return content === null ? null : content.trim().toLowerCase();
|
|
135
|
+
}
|
|
136
|
+
function sha256(value) {
|
|
137
|
+
return `sha256:${createHash("sha256").update(value).digest("hex")}`;
|
|
138
|
+
}
|
|
@@ -57,3 +57,4 @@ export declare function persistHostProcessSupervisorMetadata(launch: HostProcess
|
|
|
57
57
|
*/
|
|
58
58
|
export declare function captureHostProcessIdentity(pid: number, platform?: NodeJS.Platform): string | null;
|
|
59
59
|
export declare function terminateHostProcessTree(child: ChildProcess, launch: HostProcessSupervisedLaunch | null, graceMs?: number): Promise<void>;
|
|
60
|
+
export declare function windowsPowerShellPath(): string;
|
|
@@ -250,7 +250,7 @@ function assertMetadataPath(logDirectory, metadataPath) {
|
|
|
250
250
|
throw new Error("host_process_supervisor_invalid: metadata path must be inside FORGE_LOG_DIR.");
|
|
251
251
|
}
|
|
252
252
|
}
|
|
253
|
-
function windowsPowerShellPath() {
|
|
253
|
+
export function windowsPowerShellPath() {
|
|
254
254
|
const systemRoot = process.env.SystemRoot?.trim() || "C:\\Windows";
|
|
255
255
|
const candidate = path.win32.join(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
|
|
256
256
|
return fs.existsSync(candidate) ? candidate : "powershell.exe";
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
export interface WindowsProcessEntry {
|
|
2
|
+
readonly pid: number;
|
|
3
|
+
readonly parentPid: number;
|
|
4
|
+
/** Creation time; a pid with a different one is a different process. */
|
|
5
|
+
readonly createdAt: string;
|
|
6
|
+
}
|
|
7
|
+
/** The process table and termination primitive, injectable for tests. */
|
|
8
|
+
export interface WindowsProcessTable {
|
|
9
|
+
list(): Promise<readonly WindowsProcessEntry[]>;
|
|
10
|
+
/** `taskkill /PID <pid> /T /F`: the process and the descendants Windows still links to it. */
|
|
11
|
+
killTree(pid: number): Promise<void>;
|
|
12
|
+
}
|
|
13
|
+
export declare const systemWindowsProcessTable: WindowsProcessTable;
|
|
14
|
+
/** What is known about the root's creation before it has been seen in the table. */
|
|
15
|
+
export type WindowsRootMarker =
|
|
16
|
+
/** Its recorded birth marker (Get-Process ticks): matched within a millisecond. */
|
|
17
|
+
{
|
|
18
|
+
readonly exactCreatedAt: string;
|
|
19
|
+
}
|
|
20
|
+
/** It was spawned no earlier than this (ticks): set synchronously at spawn. */
|
|
21
|
+
| {
|
|
22
|
+
readonly notBefore: string;
|
|
23
|
+
};
|
|
24
|
+
/** .NET ticks (100 ns since 0001-01-01 UTC), the unit Win32_Process creation times are read in. */
|
|
25
|
+
export declare function windowsTicksFromEpochMs(epochMs: number): string;
|
|
26
|
+
/** A Windows command's tracked tree; see the module comment. */
|
|
27
|
+
export declare class WindowsProcessTree {
|
|
28
|
+
private readonly rootPid;
|
|
29
|
+
private readonly table;
|
|
30
|
+
private readonly marker;
|
|
31
|
+
private readonly known;
|
|
32
|
+
/** The root's creation time as the process table reports it, once seen. */
|
|
33
|
+
private observedRoot;
|
|
34
|
+
private rootExited;
|
|
35
|
+
/**
|
|
36
|
+
* The root marker anchors the tree even if the root exits before the first
|
|
37
|
+
* snapshot (or, for a reaped token, before the reaper runs): descendants
|
|
38
|
+
* created after it whose parent was the root are still found. A tree with
|
|
39
|
+
* no marker that never saw its root cannot be proven gone.
|
|
40
|
+
*/
|
|
41
|
+
constructor(rootPid: number, table: WindowsProcessTable, marker?: WindowsRootMarker | null);
|
|
42
|
+
/** The root has exited: from now on its pid only names it if its exact creation was seen. */
|
|
43
|
+
markRootExited(): void;
|
|
44
|
+
/** Records the root's current descendants; call while the command runs. */
|
|
45
|
+
track(): Promise<void>;
|
|
46
|
+
/** Stops every tracked member and proves none is left; false when one survives or nothing anchors the tree. */
|
|
47
|
+
stop(deadlineMs: number): Promise<boolean>;
|
|
48
|
+
private rootAnchor;
|
|
49
|
+
private isRoot;
|
|
50
|
+
private absorb;
|
|
51
|
+
private alive;
|
|
52
|
+
}
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { promisify } from "node:util";
|
|
3
|
+
import { windowsPowerShellPath } from "./host-process-supervisor.js";
|
|
4
|
+
const execFileAsync = promisify(execFile);
|
|
5
|
+
export const systemWindowsProcessTable = {
|
|
6
|
+
async list() {
|
|
7
|
+
const { stdout } = await execFileAsync(windowsPowerShellPath(), [
|
|
8
|
+
"-NoLogo", "-NoProfile", "-NonInteractive", "-Command",
|
|
9
|
+
"Get-CimInstance Win32_Process | ForEach-Object { \"$($_.ProcessId) $($_.ParentProcessId) $($_.CreationDate.ToUniversalTime().Ticks)\" }",
|
|
10
|
+
], { encoding: "utf8", windowsHide: true, maxBuffer: 8 * 1024 * 1024, timeout: 30_000 });
|
|
11
|
+
return stdout.split(/\r?\n/u).flatMap(line => {
|
|
12
|
+
const [pid, parentPid, createdAt] = line.trim().split(" ");
|
|
13
|
+
return pid && parentPid && createdAt ? [{ pid: Number(pid), parentPid: Number(parentPid), createdAt }] : [];
|
|
14
|
+
});
|
|
15
|
+
},
|
|
16
|
+
async killTree(pid) {
|
|
17
|
+
await execFileAsync("taskkill", ["/PID", String(pid), "/T", "/F"], { windowsHide: true, timeout: 30_000 })
|
|
18
|
+
.catch(() => undefined);
|
|
19
|
+
},
|
|
20
|
+
};
|
|
21
|
+
/** .NET ticks (100 ns since 0001-01-01 UTC), the unit Win32_Process creation times are read in. */
|
|
22
|
+
export function windowsTicksFromEpochMs(epochMs) {
|
|
23
|
+
return ((BigInt(Math.floor(epochMs)) + 62135596800000n) * 10000n).toString();
|
|
24
|
+
}
|
|
25
|
+
/** A Windows command's tracked tree; see the module comment. */
|
|
26
|
+
export class WindowsProcessTree {
|
|
27
|
+
rootPid;
|
|
28
|
+
table;
|
|
29
|
+
marker;
|
|
30
|
+
known = new Map();
|
|
31
|
+
/** The root's creation time as the process table reports it, once seen. */
|
|
32
|
+
observedRoot = null;
|
|
33
|
+
rootExited = false;
|
|
34
|
+
/**
|
|
35
|
+
* The root marker anchors the tree even if the root exits before the first
|
|
36
|
+
* snapshot (or, for a reaped token, before the reaper runs): descendants
|
|
37
|
+
* created after it whose parent was the root are still found. A tree with
|
|
38
|
+
* no marker that never saw its root cannot be proven gone.
|
|
39
|
+
*/
|
|
40
|
+
constructor(rootPid, table, marker = null) {
|
|
41
|
+
this.rootPid = rootPid;
|
|
42
|
+
this.table = table;
|
|
43
|
+
this.marker = marker;
|
|
44
|
+
const anchor = this.rootAnchor();
|
|
45
|
+
if (anchor !== null)
|
|
46
|
+
this.known.set(rootPid, anchor);
|
|
47
|
+
}
|
|
48
|
+
/** The root has exited: from now on its pid only names it if its exact creation was seen. */
|
|
49
|
+
markRootExited() {
|
|
50
|
+
this.rootExited = true;
|
|
51
|
+
}
|
|
52
|
+
/** Records the root's current descendants; call while the command runs. */
|
|
53
|
+
async track() {
|
|
54
|
+
const entries = await this.table.list().catch(() => null);
|
|
55
|
+
if (entries)
|
|
56
|
+
this.absorb(entries);
|
|
57
|
+
}
|
|
58
|
+
/** Stops every tracked member and proves none is left; false when one survives or nothing anchors the tree. */
|
|
59
|
+
async stop(deadlineMs) {
|
|
60
|
+
for (;;) {
|
|
61
|
+
const entries = await this.table.list().catch(() => null);
|
|
62
|
+
if (!entries) {
|
|
63
|
+
if (Date.now() >= deadlineMs)
|
|
64
|
+
return false;
|
|
65
|
+
await delay(200);
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
this.absorb(entries);
|
|
69
|
+
// Without any anchor nothing proves which processes were the root's: fail closed.
|
|
70
|
+
if (!this.known.has(this.rootPid))
|
|
71
|
+
return false;
|
|
72
|
+
const alive = this.alive(entries);
|
|
73
|
+
if (alive.length === 0)
|
|
74
|
+
return true;
|
|
75
|
+
if (Date.now() >= deadlineMs)
|
|
76
|
+
return false;
|
|
77
|
+
for (const pid of alive)
|
|
78
|
+
await this.table.killTree(pid);
|
|
79
|
+
await delay(100);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
rootAnchor() {
|
|
83
|
+
if (this.observedRoot !== null)
|
|
84
|
+
return this.observedRoot;
|
|
85
|
+
if (this.marker === null)
|
|
86
|
+
return null;
|
|
87
|
+
return "exactCreatedAt" in this.marker ? this.marker.exactCreatedAt : this.marker.notBefore;
|
|
88
|
+
}
|
|
89
|
+
isRoot(entry) {
|
|
90
|
+
if (entry.pid !== this.rootPid)
|
|
91
|
+
return false;
|
|
92
|
+
if (this.observedRoot !== null)
|
|
93
|
+
return entry.createdAt === this.observedRoot;
|
|
94
|
+
if (this.marker !== null && "exactCreatedAt" in this.marker)
|
|
95
|
+
return ticksClose(entry.createdAt, this.marker.exactCreatedAt);
|
|
96
|
+
// Before it exits, the root's pid cannot name anyone else.
|
|
97
|
+
if (this.rootExited)
|
|
98
|
+
return false;
|
|
99
|
+
return this.marker === null || compareTicks(entry.createdAt, this.marker.notBefore) >= 0;
|
|
100
|
+
}
|
|
101
|
+
absorb(entries) {
|
|
102
|
+
const root = entries.find(entry => this.isRoot(entry));
|
|
103
|
+
if (root && this.observedRoot === null)
|
|
104
|
+
this.observedRoot = root.createdAt;
|
|
105
|
+
const anchor = this.rootAnchor();
|
|
106
|
+
if (anchor !== null)
|
|
107
|
+
this.known.set(this.rootPid, anchor);
|
|
108
|
+
// Parents first: repeat until no new descendant of a known member appears.
|
|
109
|
+
let added = true;
|
|
110
|
+
while (added) {
|
|
111
|
+
added = false;
|
|
112
|
+
for (const entry of entries) {
|
|
113
|
+
if (this.known.has(entry.pid) || entry.pid === entry.parentPid)
|
|
114
|
+
continue;
|
|
115
|
+
const parentCreatedAt = this.known.get(entry.parentPid);
|
|
116
|
+
// A child is never older than its parent; an older one only reuses the parent's pid as its parent id.
|
|
117
|
+
if (parentCreatedAt === undefined || compareTicks(entry.createdAt, parentCreatedAt) < 0)
|
|
118
|
+
continue;
|
|
119
|
+
this.known.set(entry.pid, entry.createdAt);
|
|
120
|
+
added = true;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
alive(entries) {
|
|
125
|
+
return entries
|
|
126
|
+
.filter(entry => entry.pid === this.rootPid ? this.isRoot(entry) : this.known.get(entry.pid) === entry.createdAt)
|
|
127
|
+
.map(entry => entry.pid);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
function ticksClose(left, right) {
|
|
131
|
+
if (!/^\d+$/u.test(left) || !/^\d+$/u.test(right))
|
|
132
|
+
return left === right;
|
|
133
|
+
const difference = BigInt(left) - BigInt(right);
|
|
134
|
+
return (difference < 0n ? -difference : difference) <= 10000n;
|
|
135
|
+
}
|
|
136
|
+
function compareTicks(left, right) {
|
|
137
|
+
if (/^\d+$/u.test(left) && /^\d+$/u.test(right)) {
|
|
138
|
+
return left.length === right.length ? left.localeCompare(right) : left.length - right.length;
|
|
139
|
+
}
|
|
140
|
+
return left.localeCompare(right);
|
|
141
|
+
}
|
|
142
|
+
async function delay(ms) {
|
|
143
|
+
await new Promise(resolve => setTimeout(resolve, ms));
|
|
144
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type WindowsProcessTable } from "./process-tree.js";
|
|
1
2
|
export interface ProcessRunRequest {
|
|
2
3
|
readonly command: string;
|
|
3
4
|
readonly args: readonly string[];
|
|
@@ -5,15 +6,81 @@ export interface ProcessRunRequest {
|
|
|
5
6
|
readonly env?: NodeJS.ProcessEnv;
|
|
6
7
|
readonly rawOutput?: boolean;
|
|
7
8
|
readonly windowsVerbatimArguments?: boolean;
|
|
9
|
+
/**
|
|
10
|
+
* Stops the child (SIGTERM, then SIGKILL after a grace period) and rejects
|
|
11
|
+
* with an AbortError, but only once the child has exited, and with
|
|
12
|
+
* `processGroup` once its whole tree is proven gone: a caller that returns
|
|
13
|
+
* capacity on rejection never does so while the command still runs.
|
|
14
|
+
*/
|
|
15
|
+
readonly signal?: AbortSignal;
|
|
16
|
+
/**
|
|
17
|
+
* Treat the command's whole process tree as the step: it is stopped as a
|
|
18
|
+
* whole (on abort, and whatever outlives the command when it exits) and the
|
|
19
|
+
* run settles only once no member is left. Unix: the command leads its own
|
|
20
|
+
* process group. Windows (no process groups): the tree is tracked while the
|
|
21
|
+
* command runs and stopped with `taskkill /T /F`; see process-tree.ts. If the
|
|
22
|
+
* tree cannot be proven gone the run rejects with ProcessTreeTerminationError.
|
|
23
|
+
*/
|
|
24
|
+
readonly processGroup?: boolean;
|
|
25
|
+
/**
|
|
26
|
+
* Keeps at most this many characters of each stream: the tail, after a
|
|
27
|
+
* truncation notice. Unbounded when omitted.
|
|
28
|
+
*/
|
|
29
|
+
readonly maxOutputChars?: number;
|
|
30
|
+
/** Called with the child's pid once it has spawned. */
|
|
31
|
+
readonly onSpawn?: (pid: number) => void;
|
|
8
32
|
}
|
|
9
33
|
export interface ProcessRunResult {
|
|
10
34
|
readonly exitCode: number;
|
|
11
35
|
readonly stdout: string;
|
|
12
36
|
readonly stderr: string;
|
|
37
|
+
/** True when maxOutputChars dropped the head of either stream. */
|
|
38
|
+
readonly outputTruncated?: boolean;
|
|
13
39
|
}
|
|
14
40
|
export interface ProcessRunner {
|
|
15
41
|
run(request: ProcessRunRequest): Promise<ProcessRunResult>;
|
|
16
42
|
}
|
|
43
|
+
/**
|
|
44
|
+
* A command's process tree could not be proven gone after it was stopped.
|
|
45
|
+
* Whatever reserved capacity for it must keep that reservation.
|
|
46
|
+
*/
|
|
47
|
+
export declare class ProcessTreeTerminationError extends Error {
|
|
48
|
+
readonly rootPid: number;
|
|
49
|
+
readonly command: string;
|
|
50
|
+
readonly stillGone: () => Promise<boolean>;
|
|
51
|
+
readonly code = "process_tree_termination_unconfirmed";
|
|
52
|
+
/**
|
|
53
|
+
* `stillGone` resolves true once the tree is proven gone (Unix: an existence
|
|
54
|
+
* check only, since its members were already SIGKILLed; Windows: another
|
|
55
|
+
* tracked stop), for callers that hold the reservation until then.
|
|
56
|
+
*/
|
|
57
|
+
constructor(rootPid: number, command: string, stillGone: () => Promise<boolean>);
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* True when `error`, or anything it wraps (an AggregateError's errors, a cause
|
|
61
|
+
* chain, a sanitized copy that kept only the message), says a process tree
|
|
62
|
+
* could not be proven gone. Whoever holds capacity for that tree must keep it.
|
|
63
|
+
*/
|
|
64
|
+
export declare function isProcessTreeTerminationUnproven(error: unknown, depth?: number): boolean;
|
|
65
|
+
export interface NodeProcessRunnerOptions {
|
|
66
|
+
/** How long a stopped command gets after SIGTERM before SIGKILL. */
|
|
67
|
+
readonly terminationGraceMs?: number;
|
|
68
|
+
/** How long to wait for a SIGKILLed tree to disappear before giving up. */
|
|
69
|
+
readonly killWaitMs?: number;
|
|
70
|
+
/** Test seams for the Windows tree path. */
|
|
71
|
+
readonly platform?: NodeJS.Platform;
|
|
72
|
+
readonly windowsProcesses?: WindowsProcessTable;
|
|
73
|
+
readonly windowsTrackIntervalMs?: number;
|
|
74
|
+
/** Test seam: whether a Unix process group still has members. */
|
|
75
|
+
readonly groupAlive?: (groupId: number) => boolean;
|
|
76
|
+
}
|
|
17
77
|
export declare class NodeProcessRunner implements ProcessRunner {
|
|
78
|
+
private readonly graceMs;
|
|
79
|
+
private readonly killWaitMs;
|
|
80
|
+
private readonly platform;
|
|
81
|
+
private readonly windowsProcesses;
|
|
82
|
+
private readonly windowsTrackIntervalMs;
|
|
83
|
+
private readonly groupAlive;
|
|
84
|
+
constructor(options?: NodeProcessRunnerOptions);
|
|
18
85
|
run(request: ProcessRunRequest): Promise<ProcessRunResult>;
|
|
19
86
|
}
|