@air-jam/devtools 0.9.3 → 1.0.0-beta.10
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 +60 -0
- package/dist/{chunk-VKMJO6VN.js → chunk-2O67AXCU.js} +150 -40
- package/dist/chunk-2O67AXCU.js.map +1 -0
- package/dist/chunk-AO3ZDXF6.js +142 -0
- package/dist/chunk-AO3ZDXF6.js.map +1 -0
- package/dist/chunk-ART5TEYT.js +472 -0
- package/dist/chunk-ART5TEYT.js.map +1 -0
- package/dist/chunk-ASC2CK2R.js +77 -0
- package/dist/chunk-ASC2CK2R.js.map +1 -0
- package/dist/chunk-E3UZZGAV.js +50 -0
- package/dist/chunk-E3UZZGAV.js.map +1 -0
- package/dist/chunk-EJTE7UKX.js +64 -0
- package/dist/chunk-EJTE7UKX.js.map +1 -0
- package/dist/chunk-ESFKNN75.js +110 -0
- package/dist/chunk-ESFKNN75.js.map +1 -0
- package/dist/chunk-EU7A6PXW.js +1339 -0
- package/dist/chunk-EU7A6PXW.js.map +1 -0
- package/dist/chunk-FN7E6EA7.js +549 -0
- package/dist/chunk-FN7E6EA7.js.map +1 -0
- package/dist/chunk-GDFAWHGA.js +190 -0
- package/dist/chunk-GDFAWHGA.js.map +1 -0
- package/dist/chunk-HZUGBH4Y.js +347 -0
- package/dist/chunk-HZUGBH4Y.js.map +1 -0
- package/dist/chunk-ITKAOEGX.js +93 -0
- package/dist/chunk-ITKAOEGX.js.map +1 -0
- package/dist/chunk-JBCUTWRI.js +897 -0
- package/dist/chunk-JBCUTWRI.js.map +1 -0
- package/dist/chunk-JSI5S4WP.js +1174 -0
- package/dist/chunk-JSI5S4WP.js.map +1 -0
- package/dist/chunk-L4D675BG.js +97 -0
- package/dist/chunk-L4D675BG.js.map +1 -0
- package/dist/{chunk-GUEZP773.js → chunk-LB3Y64P5.js} +206 -60
- package/dist/chunk-LB3Y64P5.js.map +1 -0
- package/dist/chunk-M6CJ7GQC.js +133 -0
- package/dist/chunk-M6CJ7GQC.js.map +1 -0
- package/dist/{chunk-CKFT2ZJE.js → chunk-MEIMOSZC.js} +53 -105
- package/dist/chunk-MEIMOSZC.js.map +1 -0
- package/dist/chunk-OM6SCJ7H.js +18 -0
- package/dist/chunk-OM6SCJ7H.js.map +1 -0
- package/dist/chunk-PKD4WVX5.js +63 -0
- package/dist/chunk-PKD4WVX5.js.map +1 -0
- package/dist/chunk-PMBLXGFM.js +3384 -0
- package/dist/chunk-PMBLXGFM.js.map +1 -0
- package/dist/chunk-PMNE5GIN.js +279 -0
- package/dist/chunk-PMNE5GIN.js.map +1 -0
- package/dist/chunk-QAWI64VR.js +148 -0
- package/dist/chunk-QAWI64VR.js.map +1 -0
- package/dist/chunk-QGADSPHZ.js +449 -0
- package/dist/chunk-QGADSPHZ.js.map +1 -0
- package/dist/chunk-SPYN66UV.js +338 -0
- package/dist/chunk-SPYN66UV.js.map +1 -0
- package/dist/context.d.ts +9 -3
- package/dist/context.js +2 -1
- package/dist/controller.d.ts +33 -7
- package/dist/controller.js +18 -8
- package/dist/dependencies.d.ts +44 -0
- package/dist/dependencies.js +10 -0
- package/dist/dev.d.ts +9 -3
- package/dist/dev.js +3 -4
- package/dist/game-builds.d.ts +200 -0
- package/dist/game-builds.js +16 -0
- package/dist/game-builds.js.map +1 -0
- package/dist/game-run-watch-CEd_SpAT.d.ts +84 -0
- package/dist/game-runs.d.ts +1452 -0
- package/dist/game-runs.js +76 -0
- package/dist/game-runs.js.map +1 -0
- package/dist/game-session-broker-CUvORfMd.d.ts +439 -0
- package/dist/game-session-broker.d.ts +4 -57
- package/dist/game-session-broker.js +33 -228
- package/dist/game-session-broker.js.map +1 -1
- package/dist/game-session.d.ts +3931 -10
- package/dist/game-session.js +186 -15
- package/dist/game-session.js.map +1 -1
- package/dist/game-settings.d.ts +16 -0
- package/dist/game-settings.js +237 -0
- package/dist/game-settings.js.map +1 -0
- package/dist/games.d.ts +11 -4
- package/dist/games.js +4 -2
- package/dist/harness/visual.d.ts +34 -151
- package/dist/harness/visual.js +6 -1
- package/dist/logs.d.ts +8 -2
- package/dist/logs.js +3 -4
- package/dist/logs.js.map +1 -1
- package/dist/managed-process-scope-BicYi_t9.d.ts +3 -0
- package/dist/mcp-config.js +2 -1
- package/dist/mcp-config.js.map +1 -1
- package/dist/platform-auth.d.ts +8 -111
- package/dist/platform-auth.js +9 -1
- package/dist/platform-game-analytics.d.ts +51 -0
- package/dist/platform-game-analytics.js +49 -0
- package/dist/platform-game-analytics.js.map +1 -0
- package/dist/platform-game-app-id.d.ts +46 -0
- package/dist/platform-game-app-id.js +93 -0
- package/dist/platform-game-app-id.js.map +1 -0
- package/dist/platform-game-media.d.ts +40 -2
- package/dist/platform-game-media.js +1 -1
- package/dist/platform-games.d.ts +24 -2
- package/dist/platform-games.js +16 -84
- package/dist/platform-games.js.map +1 -1
- package/dist/quality.d.ts +9 -3
- package/dist/quality.js +3 -4
- package/dist/quality.js.map +1 -1
- package/dist/release.d.ts +226 -16
- package/dist/release.js +18 -1331
- package/dist/release.js.map +1 -1
- package/dist/rooms-check.d.ts +90 -0
- package/dist/rooms-check.js +717 -0
- package/dist/rooms-check.js.map +1 -0
- package/dist/source-tree-contract.d.ts +16 -0
- package/dist/source-tree-contract.js +13 -0
- package/dist/source-tree-contract.js.map +1 -0
- package/dist/testing.d.ts +464 -0
- package/dist/testing.js +27 -0
- package/dist/testing.js.map +1 -0
- package/dist/tooling/describe-game.js +54 -0
- package/dist/tooling/describe-game.js.map +1 -0
- package/dist/tooling/game-session-broker.js +28 -0
- package/dist/tooling/game-session-broker.js.map +1 -0
- package/dist/tooling/hold-runtime-host.js +770 -68
- package/dist/tooling/hold-runtime-host.js.map +1 -1
- package/dist/tooling/list-visual-scenarios.js +18 -55
- package/dist/tooling/list-visual-scenarios.js.map +1 -1
- package/dist/tooling/process-scope-bootstrap.mjs +24 -0
- package/dist/tooling/process-scope-guard.d.ts +2 -0
- package/dist/tooling/process-scope-guard.js +388 -0
- package/dist/tooling/process-scope-guard.js.map +1 -0
- package/dist/tooling/process-scope-windows.ps1 +148 -0
- package/dist/tooling/rooms-check-device.d.ts +2 -0
- package/dist/tooling/rooms-check-device.js +498 -0
- package/dist/tooling/rooms-check-device.js.map +1 -0
- package/dist/tooling/run-headless-room.d.ts +2 -0
- package/dist/tooling/run-headless-room.js +288 -0
- package/dist/tooling/run-headless-room.js.map +1 -0
- package/dist/tooling/run-test-profile.d.ts +2 -0
- package/dist/tooling/run-test-profile.js +181 -0
- package/dist/tooling/run-test-profile.js.map +1 -0
- package/dist/tooling/run-visual-capture.js +70 -34
- package/dist/tooling/run-visual-capture.js.map +1 -1
- package/dist/tooling/seal-game-build.d.ts +2 -0
- package/dist/tooling/seal-game-build.js +120 -0
- package/dist/tooling/seal-game-build.js.map +1 -0
- package/dist/{types-C6NrHt88.d.ts → types-CdYrgrG_.d.ts} +337 -76
- package/dist/types-DyRD-ym1.d.ts +141 -0
- package/dist/visual.d.ts +9 -3
- package/dist/visual.js +24 -68
- package/dist/visual.js.map +1 -1
- package/package.json +51 -14
- package/src/bounded-response.ts +28 -0
- package/src/built-game-runtime.ts +152 -0
- package/src/context.ts +2 -13
- package/src/controller-protocol.ts +22 -0
- package/src/controller.ts +747 -597
- package/src/current-room-host.ts +166 -0
- package/src/decision-provider.ts +102 -0
- package/src/dependencies.ts +176 -0
- package/src/dependency-install-contract.ts +12 -0
- package/src/dev.ts +46 -50
- package/src/game-action-observation.ts +11 -1
- package/src/game-build-protocol.ts +72 -0
- package/src/game-build.ts +483 -0
- package/src/game-run-owner.ts +2358 -0
- package/src/game-run-protocol.ts +448 -0
- package/src/game-run-record.ts +92 -0
- package/src/game-run-replay.ts +95 -0
- package/src/game-run-watch.ts +155 -0
- package/src/game-session-broker.ts +689 -197
- package/src/game-session-operations.ts +61 -0
- package/src/game-session-protocol.ts +180 -0
- package/src/game-session-runtime.ts +861 -0
- package/src/game-session.ts +164 -417
- package/src/game-settings.ts +295 -0
- package/src/games.ts +88 -92
- package/src/harness/visual/browser.ts +100 -0
- package/src/harness/visual/controller-observation.ts +181 -0
- package/src/harness/visual/runner.ts +24 -21
- package/src/harness/visual/runtime-controller-observations.ts +151 -0
- package/src/harness/visual/scenario-contract.ts +1 -2
- package/src/harness/visual/scenario-helpers.ts +5 -1
- package/src/harness/visual/screencast.ts +155 -0
- package/src/harness/visual/session.ts +74 -69
- package/src/harness/visual/types.ts +8 -5
- package/src/headless-room-protocol.ts +112 -0
- package/src/headless-room.ts +222 -0
- package/src/helper-channel.ts +229 -0
- package/src/helper-scripts.ts +25 -5
- package/src/installed-dependencies.ts +74 -0
- package/src/managed-process-scope.ts +481 -0
- package/src/node-process-environment.ts +10 -0
- package/src/platform-auth.ts +194 -55
- package/src/platform-game-analytics.ts +50 -0
- package/src/platform-game-app-id.ts +99 -0
- package/src/platform-games.ts +13 -111
- package/src/policy-artifact-contract.ts +52 -0
- package/src/policy-artifacts.ts +134 -0
- package/src/process-scope-admission.ts +50 -0
- package/src/process-scope-protocol.ts +66 -0
- package/src/process-scope.ts +327 -0
- package/src/release.ts +28 -42
- package/src/rooms-check-fleet.ts +194 -0
- package/src/rooms-check-link.ts +138 -0
- package/src/rooms-check-protocol.ts +244 -0
- package/src/rooms-check.ts +797 -0
- package/src/runtime-owner-protocol.ts +106 -18
- package/src/source-tree-contract.ts +70 -0
- package/src/source-tree.ts +84 -0
- package/src/test-profile-process.ts +153 -0
- package/src/test-profile-protocol.ts +116 -0
- package/src/testing.ts +430 -0
- package/src/tooling/declaration-hook.ts +52 -0
- package/src/tooling/describe-game.ts +49 -0
- package/src/tooling/game-session-broker.ts +7 -0
- package/src/tooling/hold-runtime-host.ts +254 -42
- package/src/tooling/list-visual-scenarios.ts +19 -62
- package/src/tooling/load-game.ts +79 -0
- package/src/tooling/process-scope-bootstrap.mjs +24 -0
- package/src/tooling/process-scope-guard.ts +213 -0
- package/src/tooling/process-scope-windows.ps1 +148 -0
- package/src/tooling/rooms-check-device.ts +493 -0
- package/src/tooling/run-headless-room.ts +329 -0
- package/src/tooling/run-test-profile.ts +190 -0
- package/src/tooling/run-visual-capture.ts +37 -23
- package/src/tooling/runtime-owner-actions.ts +23 -0
- package/src/tooling/seal-game-build.ts +118 -0
- package/src/tooling/visual-pack.ts +10 -45
- package/src/types.ts +54 -77
- package/src/visual.ts +14 -22
- package/src/windows-process-scopes.ts +189 -0
- package/dist/agent.d.ts +0 -15
- package/dist/agent.js +0 -19
- package/dist/chunk-5YAARMW5.js +0 -36
- package/dist/chunk-5YAARMW5.js.map +0 -1
- package/dist/chunk-6WQODT37.js +0 -1019
- package/dist/chunk-6WQODT37.js.map +0 -1
- package/dist/chunk-CKFT2ZJE.js.map +0 -1
- package/dist/chunk-ER3Q2C4G.js +0 -358
- package/dist/chunk-ER3Q2C4G.js.map +0 -1
- package/dist/chunk-GUEZP773.js.map +0 -1
- package/dist/chunk-HIDNI56E.js +0 -33
- package/dist/chunk-HIDNI56E.js.map +0 -1
- package/dist/chunk-QKXS5D35.js +0 -43
- package/dist/chunk-QKXS5D35.js.map +0 -1
- package/dist/chunk-S4LSCEVE.js +0 -261
- package/dist/chunk-S4LSCEVE.js.map +0 -1
- package/dist/chunk-VKMJO6VN.js.map +0 -1
- package/dist/chunk-WFUR3MXY.js +0 -67
- package/dist/chunk-WFUR3MXY.js.map +0 -1
- package/dist/chunk-XEMR7KUE.js +0 -361
- package/dist/chunk-XEMR7KUE.js.map +0 -1
- package/dist/chunk-ZLPD7FY5.js +0 -191
- package/dist/chunk-ZLPD7FY5.js.map +0 -1
- package/dist/tooling/agent-contract.js +0 -193
- package/dist/tooling/agent-contract.js.map +0 -1
- package/dist/tooling/inspect-airjam-agent.js +0 -37
- package/dist/tooling/inspect-airjam-agent.js.map +0 -1
- package/src/agent.ts +0 -380
- package/src/tooling/agent-contract.ts +0 -232
- package/src/tooling/agent-declaration.ts +0 -36
- package/src/tooling/airjam-agent-inspection.ts +0 -45
- package/src/tooling/airjam-agent.ts +0 -118
- package/src/tooling/inspect-airjam-agent.ts +0 -20
- /package/dist/{agent.js.map → dependencies.js.map} +0 -0
- /package/dist/tooling/{agent-contract.d.ts → describe-game.d.ts} +0 -0
- /package/dist/tooling/{inspect-airjam-agent.d.ts → game-session-broker.d.ts} +0 -0
|
@@ -0,0 +1,388 @@
|
|
|
1
|
+
import {
|
|
2
|
+
closeProcessScope,
|
|
3
|
+
createProcessScope,
|
|
4
|
+
processGuardRequestSchema,
|
|
5
|
+
processGuardResponseSchema,
|
|
6
|
+
processGuardStartupDeadlineSchema,
|
|
7
|
+
processGuardStartupTimeoutMs,
|
|
8
|
+
processIdentity,
|
|
9
|
+
processScopeJournalSchema,
|
|
10
|
+
processScopeNamespace,
|
|
11
|
+
processScopeReceiptSchema,
|
|
12
|
+
registerProcessScope
|
|
13
|
+
} from "../chunk-SPYN66UV.js";
|
|
14
|
+
import {
|
|
15
|
+
resolveDevtoolsHelperScript
|
|
16
|
+
} from "../chunk-PKD4WVX5.js";
|
|
17
|
+
|
|
18
|
+
// src/tooling/process-scope-guard.ts
|
|
19
|
+
import {
|
|
20
|
+
mkdir,
|
|
21
|
+
readFile,
|
|
22
|
+
readdir,
|
|
23
|
+
rename,
|
|
24
|
+
unlink,
|
|
25
|
+
writeFile
|
|
26
|
+
} from "fs/promises";
|
|
27
|
+
import path from "path";
|
|
28
|
+
|
|
29
|
+
// src/windows-process-scopes.ts
|
|
30
|
+
import { spawn } from "child_process";
|
|
31
|
+
import { randomUUID } from "crypto";
|
|
32
|
+
import { createInterface } from "readline";
|
|
33
|
+
import { debuglog } from "util";
|
|
34
|
+
var debug = debuglog("airjam-process-scope");
|
|
35
|
+
var WindowsProcessScopes = class _WindowsProcessScopes {
|
|
36
|
+
child;
|
|
37
|
+
pending = /* @__PURE__ */ new Map();
|
|
38
|
+
failure = null;
|
|
39
|
+
ready;
|
|
40
|
+
constructor(startupTimeoutMs) {
|
|
41
|
+
const started = performance.now();
|
|
42
|
+
let firstOutput = Buffer.alloc(0);
|
|
43
|
+
let diagnosticTail = "";
|
|
44
|
+
const failure = (message) => new Error(
|
|
45
|
+
`${message} Elapsed ${Math.round(performance.now() - started)} ms; stdout prefix ${firstOutput.toString("hex") || "none"}; diagnostics: ${diagnosticTail || "none"}`
|
|
46
|
+
);
|
|
47
|
+
this.child = spawn(
|
|
48
|
+
"pwsh.exe",
|
|
49
|
+
[
|
|
50
|
+
"-NoProfile",
|
|
51
|
+
"-NonInteractive",
|
|
52
|
+
"-Command",
|
|
53
|
+
`& ([scriptblock]::Create([IO.File]::ReadAllText('${resolveDevtoolsHelperScript("process-scope-windows.ps1").replaceAll("'", "''")}')))`
|
|
54
|
+
],
|
|
55
|
+
{ stdio: ["pipe", "pipe", "pipe"], windowsHide: true }
|
|
56
|
+
);
|
|
57
|
+
this.child.once(
|
|
58
|
+
"spawn",
|
|
59
|
+
() => debug(
|
|
60
|
+
"PowerShell spawned in %d ms",
|
|
61
|
+
Math.round(performance.now() - started)
|
|
62
|
+
)
|
|
63
|
+
);
|
|
64
|
+
this.child.stderr?.on("data", (chunk) => {
|
|
65
|
+
diagnosticTail = (diagnosticTail + chunk.toString()).slice(-4096);
|
|
66
|
+
debug("%s", chunk.toString().trim());
|
|
67
|
+
});
|
|
68
|
+
this.ready = new Promise((resolve, reject) => {
|
|
69
|
+
const timer = setTimeout(() => {
|
|
70
|
+
const error = failure(
|
|
71
|
+
"process_scope_unavailable: Windows job guardian startup timed out."
|
|
72
|
+
);
|
|
73
|
+
abort(error);
|
|
74
|
+
}, startupTimeoutMs);
|
|
75
|
+
const abort = (error) => {
|
|
76
|
+
clearTimeout(timer);
|
|
77
|
+
reject(error);
|
|
78
|
+
this.fail(error);
|
|
79
|
+
};
|
|
80
|
+
const output = this.child.stdout;
|
|
81
|
+
if (!output) throw new Error("Windows guardian output is unavailable.");
|
|
82
|
+
output.on("error", abort);
|
|
83
|
+
this.child.stdin?.on("error", abort);
|
|
84
|
+
this.child.stderr?.on("error", abort);
|
|
85
|
+
output.on("data", (chunk) => {
|
|
86
|
+
if (firstOutput.length === 0)
|
|
87
|
+
debug(
|
|
88
|
+
"First PowerShell output at %d ms: %s",
|
|
89
|
+
Math.round(performance.now() - started),
|
|
90
|
+
chunk.subarray(0, 64).toString("hex")
|
|
91
|
+
);
|
|
92
|
+
if (firstOutput.length < 64)
|
|
93
|
+
firstOutput = Buffer.concat([
|
|
94
|
+
firstOutput,
|
|
95
|
+
chunk.subarray(0, 64 - firstOutput.length)
|
|
96
|
+
]);
|
|
97
|
+
});
|
|
98
|
+
const lines = createInterface({ input: output });
|
|
99
|
+
lines.on("line", (line) => {
|
|
100
|
+
try {
|
|
101
|
+
const result = processGuardResponseSchema.parse(JSON.parse(line));
|
|
102
|
+
if (result.kind === "ready") {
|
|
103
|
+
clearTimeout(timer);
|
|
104
|
+
resolve();
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
if (result.kind === "startup-error") throw new Error(result.message);
|
|
108
|
+
const request = this.pending.get(result.id);
|
|
109
|
+
if (!request) throw new Error("Unknown Windows job acknowledgement.");
|
|
110
|
+
this.pending.delete(result.id);
|
|
111
|
+
clearTimeout(request.timer);
|
|
112
|
+
if (result.kind === "error")
|
|
113
|
+
request.reject(new Error(result.message));
|
|
114
|
+
else request.resolve(result);
|
|
115
|
+
} catch (error) {
|
|
116
|
+
const invalid = failure(
|
|
117
|
+
`process_scope_unavailable: Invalid Windows guardian response ${JSON.stringify(line.slice(0, 256))}: ${error instanceof Error ? error.message : String(error)}`
|
|
118
|
+
);
|
|
119
|
+
abort(invalid);
|
|
120
|
+
}
|
|
121
|
+
});
|
|
122
|
+
this.child.once(
|
|
123
|
+
"error",
|
|
124
|
+
(error) => abort(
|
|
125
|
+
failure(
|
|
126
|
+
`process_scope_unavailable: Windows process scopes require PowerShell 7.4+ (pwsh). Install: winget install Microsoft.PowerShell. ${error.message}`
|
|
127
|
+
)
|
|
128
|
+
)
|
|
129
|
+
);
|
|
130
|
+
this.child.once("exit", (code, signal) => {
|
|
131
|
+
const error = failure(
|
|
132
|
+
`process_scope_unavailable: Windows job guardian exited (code ${code}, signal ${signal}).`
|
|
133
|
+
);
|
|
134
|
+
abort(error);
|
|
135
|
+
});
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
static async open(startupTimeoutMs = processGuardStartupTimeoutMs - 2500) {
|
|
139
|
+
const owner = new _WindowsProcessScopes(startupTimeoutMs);
|
|
140
|
+
await owner.ready;
|
|
141
|
+
return owner;
|
|
142
|
+
}
|
|
143
|
+
fail(error) {
|
|
144
|
+
const first = this.failure === null;
|
|
145
|
+
this.failure ??= error;
|
|
146
|
+
for (const request of this.pending.values()) {
|
|
147
|
+
clearTimeout(request.timer);
|
|
148
|
+
request.reject(error);
|
|
149
|
+
}
|
|
150
|
+
this.pending.clear();
|
|
151
|
+
if (first) this.child.kill();
|
|
152
|
+
}
|
|
153
|
+
async request(input) {
|
|
154
|
+
await this.ready;
|
|
155
|
+
if (this.failure) throw this.failure;
|
|
156
|
+
const id = randomUUID();
|
|
157
|
+
return new Promise(
|
|
158
|
+
(resolve, reject) => {
|
|
159
|
+
const timer = setTimeout(() => {
|
|
160
|
+
this.fail(
|
|
161
|
+
new Error(
|
|
162
|
+
"process_scope_unavailable: Windows job request timed out."
|
|
163
|
+
)
|
|
164
|
+
);
|
|
165
|
+
}, 5e3);
|
|
166
|
+
this.pending.set(id, { resolve, reject, timer });
|
|
167
|
+
this.child.stdin?.write(
|
|
168
|
+
`${JSON.stringify({ ...input, id })}
|
|
169
|
+
`,
|
|
170
|
+
(error) => {
|
|
171
|
+
if (error) this.fail(error);
|
|
172
|
+
}
|
|
173
|
+
);
|
|
174
|
+
}
|
|
175
|
+
);
|
|
176
|
+
}
|
|
177
|
+
async create(token) {
|
|
178
|
+
await this.request({ kind: "open", token });
|
|
179
|
+
}
|
|
180
|
+
async register(token, processId, root) {
|
|
181
|
+
await this.request({ kind: "register", token, processId, root });
|
|
182
|
+
}
|
|
183
|
+
async close(token) {
|
|
184
|
+
const result = await this.request({ kind: "close", token });
|
|
185
|
+
return processScopeReceiptSchema.parse(result.receipt);
|
|
186
|
+
}
|
|
187
|
+
async shutdown() {
|
|
188
|
+
this.child.stdin?.end();
|
|
189
|
+
await new Promise((resolve) => {
|
|
190
|
+
if (this.child.exitCode !== null) return resolve();
|
|
191
|
+
const timer = setTimeout(() => {
|
|
192
|
+
this.child.kill();
|
|
193
|
+
resolve();
|
|
194
|
+
}, 4e3);
|
|
195
|
+
this.child.once("exit", () => {
|
|
196
|
+
clearTimeout(timer);
|
|
197
|
+
resolve();
|
|
198
|
+
});
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
};
|
|
202
|
+
|
|
203
|
+
// src/tooling/process-scope-guard.ts
|
|
204
|
+
var scopes = /* @__PURE__ */ new Map();
|
|
205
|
+
var recovered = /* @__PURE__ */ new Set();
|
|
206
|
+
var poisoned = false;
|
|
207
|
+
var windows = null;
|
|
208
|
+
try {
|
|
209
|
+
const deadline = processGuardStartupDeadlineSchema.parse(process.argv[2]);
|
|
210
|
+
if (process.platform === "win32") {
|
|
211
|
+
const remainingMs = Number(deadline - process.hrtime.bigint()) / 1e6 - 250;
|
|
212
|
+
if (remainingMs <= 0)
|
|
213
|
+
throw new Error(
|
|
214
|
+
"process_scope_unavailable: Guardian preparation deadline elapsed before Windows startup."
|
|
215
|
+
);
|
|
216
|
+
windows = await WindowsProcessScopes.open(remainingMs);
|
|
217
|
+
}
|
|
218
|
+
} catch (error) {
|
|
219
|
+
if (process.send && process.connected) {
|
|
220
|
+
const transmit = process.send.bind(process);
|
|
221
|
+
await new Promise(
|
|
222
|
+
(resolve, reject) => transmit(
|
|
223
|
+
{
|
|
224
|
+
kind: "startup-error",
|
|
225
|
+
message: error instanceof Error ? error.message : String(error)
|
|
226
|
+
},
|
|
227
|
+
void 0,
|
|
228
|
+
void 0,
|
|
229
|
+
(failure) => failure ? reject(failure) : resolve()
|
|
230
|
+
)
|
|
231
|
+
);
|
|
232
|
+
}
|
|
233
|
+
throw error;
|
|
234
|
+
}
|
|
235
|
+
var guardian = windows ? null : processIdentity(process.pid);
|
|
236
|
+
if (!windows && !guardian)
|
|
237
|
+
throw new Error("process_scope_unavailable: Guardian identity unavailable.");
|
|
238
|
+
async function persist(entry) {
|
|
239
|
+
const temporary = `${entry.filename}.new`;
|
|
240
|
+
await writeFile(temporary, JSON.stringify({ guardian, scope: entry.scope }), {
|
|
241
|
+
mode: 384
|
|
242
|
+
});
|
|
243
|
+
await rename(temporary, entry.filename);
|
|
244
|
+
}
|
|
245
|
+
async function recover(rootDir) {
|
|
246
|
+
if (recovered.has(rootDir)) return;
|
|
247
|
+
const directory = path.join(rootDir, ".airjam/devtools/process-scopes");
|
|
248
|
+
await mkdir(directory, { recursive: true });
|
|
249
|
+
for (const name of await readdir(directory)) {
|
|
250
|
+
if (!name.endsWith(".json")) continue;
|
|
251
|
+
const filename = path.join(directory, name);
|
|
252
|
+
let record;
|
|
253
|
+
try {
|
|
254
|
+
record = processScopeJournalSchema.parse(
|
|
255
|
+
JSON.parse(await readFile(filename, "utf8"))
|
|
256
|
+
);
|
|
257
|
+
} catch (error) {
|
|
258
|
+
if (error.code === "ENOENT") continue;
|
|
259
|
+
throw error;
|
|
260
|
+
}
|
|
261
|
+
if (record.scope.namespace !== processScopeNamespace()) {
|
|
262
|
+
await unlink(filename).catch((error) => {
|
|
263
|
+
if (error.code !== "ENOENT") throw error;
|
|
264
|
+
});
|
|
265
|
+
continue;
|
|
266
|
+
}
|
|
267
|
+
const owner = processIdentity(record.guardian.processId);
|
|
268
|
+
if (owner?.started === record.guardian.started) continue;
|
|
269
|
+
const receipt = await closeProcessScope(record.scope);
|
|
270
|
+
if (receipt.status !== "tree_clean") {
|
|
271
|
+
poisoned = true;
|
|
272
|
+
await persist({ scope: record.scope, filename });
|
|
273
|
+
throw new Error(
|
|
274
|
+
`process_tree_unconfirmed: Recovery refused admission: ${JSON.stringify(receipt)}`
|
|
275
|
+
);
|
|
276
|
+
}
|
|
277
|
+
await unlink(filename).catch((error) => {
|
|
278
|
+
if (error.code !== "ENOENT") throw error;
|
|
279
|
+
});
|
|
280
|
+
}
|
|
281
|
+
recovered.add(rootDir);
|
|
282
|
+
}
|
|
283
|
+
async function close(token) {
|
|
284
|
+
if (windows) {
|
|
285
|
+
const receipt2 = await windows.close(token);
|
|
286
|
+
if (receipt2.status !== "tree_clean") poisoned = true;
|
|
287
|
+
return receipt2;
|
|
288
|
+
}
|
|
289
|
+
const entry = scopes.get(token);
|
|
290
|
+
if (!entry)
|
|
291
|
+
throw new Error("process_scope_unavailable: Unknown process scope.");
|
|
292
|
+
const receipt = await closeProcessScope(entry.scope);
|
|
293
|
+
if (receipt.status === "tree_clean") {
|
|
294
|
+
await unlink(entry.filename);
|
|
295
|
+
scopes.delete(token);
|
|
296
|
+
} else {
|
|
297
|
+
poisoned = true;
|
|
298
|
+
await persist(entry);
|
|
299
|
+
}
|
|
300
|
+
return receipt;
|
|
301
|
+
}
|
|
302
|
+
function send(value) {
|
|
303
|
+
if (process.connected) process.send?.(value);
|
|
304
|
+
}
|
|
305
|
+
var queue = Promise.resolve();
|
|
306
|
+
var stopping = false;
|
|
307
|
+
process.on("message", (value) => {
|
|
308
|
+
queue = queue.then(async () => {
|
|
309
|
+
const request = processGuardRequestSchema.parse(value);
|
|
310
|
+
try {
|
|
311
|
+
if (stopping)
|
|
312
|
+
throw new Error("process_scope_unavailable: Guardian is stopping.");
|
|
313
|
+
if (request.kind === "open") {
|
|
314
|
+
if (poisoned)
|
|
315
|
+
throw new Error(
|
|
316
|
+
"process_tree_unconfirmed: Guardian requires preserved-workspace recovery before new admission."
|
|
317
|
+
);
|
|
318
|
+
if (windows) await windows.create(request.token);
|
|
319
|
+
else {
|
|
320
|
+
await recover(request.rootDir);
|
|
321
|
+
if (scopes.has(request.token))
|
|
322
|
+
throw new Error("Duplicate process scope.");
|
|
323
|
+
const entry = {
|
|
324
|
+
scope: { ...createProcessScope(), token: request.token },
|
|
325
|
+
filename: path.join(
|
|
326
|
+
request.rootDir,
|
|
327
|
+
".airjam/devtools/process-scopes",
|
|
328
|
+
`${request.token}.json`
|
|
329
|
+
)
|
|
330
|
+
};
|
|
331
|
+
scopes.set(request.token, entry);
|
|
332
|
+
await persist(entry);
|
|
333
|
+
}
|
|
334
|
+
send({ kind: "result", id: request.id });
|
|
335
|
+
} else if (request.kind === "register") {
|
|
336
|
+
if (windows)
|
|
337
|
+
await windows.register(
|
|
338
|
+
request.token,
|
|
339
|
+
request.processId,
|
|
340
|
+
request.root
|
|
341
|
+
);
|
|
342
|
+
else {
|
|
343
|
+
const entry = scopes.get(request.token);
|
|
344
|
+
if (!entry) throw new Error("Unknown process scope.");
|
|
345
|
+
registerProcessScope(entry.scope, request.processId);
|
|
346
|
+
await persist(entry);
|
|
347
|
+
}
|
|
348
|
+
send({ kind: "result", id: request.id });
|
|
349
|
+
} else
|
|
350
|
+
send({
|
|
351
|
+
kind: "result",
|
|
352
|
+
id: request.id,
|
|
353
|
+
receipt: await close(request.token)
|
|
354
|
+
});
|
|
355
|
+
} catch (error) {
|
|
356
|
+
if (request.kind === "close") poisoned = true;
|
|
357
|
+
send({
|
|
358
|
+
kind: "error",
|
|
359
|
+
scopeUnconfirmed: poisoned,
|
|
360
|
+
id: request.id,
|
|
361
|
+
message: error instanceof Error ? error.message : String(error)
|
|
362
|
+
});
|
|
363
|
+
}
|
|
364
|
+
}).catch((error) => {
|
|
365
|
+
console.error(error);
|
|
366
|
+
void shutdown();
|
|
367
|
+
});
|
|
368
|
+
});
|
|
369
|
+
async function shutdown() {
|
|
370
|
+
if (stopping) return;
|
|
371
|
+
stopping = true;
|
|
372
|
+
await queue;
|
|
373
|
+
if (windows) await windows.shutdown();
|
|
374
|
+
else await Promise.allSettled([...scopes.keys()].map(close));
|
|
375
|
+
process.exit(0);
|
|
376
|
+
}
|
|
377
|
+
process.once("disconnect", () => {
|
|
378
|
+
void shutdown();
|
|
379
|
+
});
|
|
380
|
+
process.once("SIGTERM", () => {
|
|
381
|
+
void shutdown();
|
|
382
|
+
});
|
|
383
|
+
process.once("SIGINT", () => {
|
|
384
|
+
void shutdown();
|
|
385
|
+
});
|
|
386
|
+
if (process.connected) send({ kind: "ready" });
|
|
387
|
+
else await shutdown();
|
|
388
|
+
//# sourceMappingURL=process-scope-guard.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/tooling/process-scope-guard.ts","../../src/windows-process-scopes.ts"],"sourcesContent":["import {\n mkdir,\n readFile,\n readdir,\n rename,\n unlink,\n writeFile,\n} from \"node:fs/promises\";\nimport path from \"node:path\";\nimport {\n processGuardRequestSchema,\n processGuardStartupDeadlineSchema,\n type ProcessGuardResponse,\n} from \"../process-scope-protocol.js\";\nimport {\n closeProcessScope,\n createProcessScope,\n processIdentity,\n processScopeJournalSchema,\n processScopeNamespace,\n registerProcessScope,\n type ProcessScope,\n} from \"../process-scope.js\";\nimport { WindowsProcessScopes } from \"../windows-process-scopes.js\";\n\nconst scopes = new Map<string, { scope: ProcessScope; filename: string }>();\nconst recovered = new Set<string>();\nlet poisoned = false;\nlet windows: WindowsProcessScopes | null = null;\ntry {\n const deadline = processGuardStartupDeadlineSchema.parse(process.argv[2]);\n if (process.platform === \"win32\") {\n const remainingMs =\n Number(deadline - process.hrtime.bigint()) / 1000000 - 250;\n if (remainingMs <= 0)\n throw new Error(\n \"process_scope_unavailable: Guardian preparation deadline elapsed before Windows startup.\",\n );\n windows = await WindowsProcessScopes.open(remainingMs);\n }\n} catch (error) {\n if (process.send && process.connected) {\n const transmit = process.send.bind(process);\n await new Promise<void>((resolve, reject) =>\n transmit(\n {\n kind: \"startup-error\",\n message: error instanceof Error ? error.message : String(error),\n } satisfies ProcessGuardResponse,\n undefined,\n undefined,\n (failure) => (failure ? reject(failure) : resolve()),\n ),\n );\n }\n throw error;\n}\nconst guardian = windows ? null : processIdentity(process.pid);\nif (!windows && !guardian)\n throw new Error(\"process_scope_unavailable: Guardian identity unavailable.\");\n\nasync function persist(entry: { scope: ProcessScope; filename: string }) {\n const temporary = `${entry.filename}.new`;\n await writeFile(temporary, JSON.stringify({ guardian, scope: entry.scope }), {\n mode: 0o600,\n });\n await rename(temporary, entry.filename);\n}\nasync function recover(rootDir: string) {\n if (recovered.has(rootDir)) return;\n const directory = path.join(rootDir, \".airjam/devtools/process-scopes\");\n await mkdir(directory, { recursive: true });\n for (const name of await readdir(directory)) {\n if (!name.endsWith(\".json\")) continue;\n const filename = path.join(directory, name);\n let record;\n try {\n record = processScopeJournalSchema.parse(\n JSON.parse(await readFile(filename, \"utf8\")),\n );\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") continue;\n throw error;\n }\n if (record.scope.namespace !== processScopeNamespace()) {\n await unlink(filename).catch((error) => {\n if (error.code !== \"ENOENT\") throw error;\n });\n continue;\n }\n const owner = processIdentity(record.guardian.processId);\n if (owner?.started === record.guardian.started) continue;\n const receipt = await closeProcessScope(record.scope);\n if (receipt.status !== \"tree_clean\") {\n poisoned = true;\n await persist({ scope: record.scope, filename });\n throw new Error(\n `process_tree_unconfirmed: Recovery refused admission: ${JSON.stringify(receipt)}`,\n );\n }\n await unlink(filename).catch((error) => {\n if (error.code !== \"ENOENT\") throw error;\n });\n }\n recovered.add(rootDir);\n}\nasync function close(token: string) {\n if (windows) {\n const receipt = await windows.close(token);\n if (receipt.status !== \"tree_clean\") poisoned = true;\n return receipt;\n }\n const entry = scopes.get(token);\n if (!entry)\n throw new Error(\"process_scope_unavailable: Unknown process scope.\");\n const receipt = await closeProcessScope(entry.scope);\n if (receipt.status === \"tree_clean\") {\n await unlink(entry.filename);\n scopes.delete(token);\n } else {\n poisoned = true;\n await persist(entry);\n }\n return receipt;\n}\nfunction send(value: ProcessGuardResponse) {\n if (process.connected) process.send?.(value);\n}\nlet queue = Promise.resolve();\nlet stopping = false;\nprocess.on(\"message\", (value: unknown) => {\n queue = queue\n .then(async () => {\n const request = processGuardRequestSchema.parse(value);\n try {\n if (stopping)\n throw new Error(\"process_scope_unavailable: Guardian is stopping.\");\n if (request.kind === \"open\") {\n if (poisoned)\n throw new Error(\n \"process_tree_unconfirmed: Guardian requires preserved-workspace recovery before new admission.\",\n );\n if (windows) await windows.create(request.token);\n else {\n await recover(request.rootDir);\n if (scopes.has(request.token))\n throw new Error(\"Duplicate process scope.\");\n const entry = {\n scope: { ...createProcessScope(), token: request.token },\n filename: path.join(\n request.rootDir,\n \".airjam/devtools/process-scopes\",\n `${request.token}.json`,\n ),\n };\n scopes.set(request.token, entry);\n await persist(entry);\n }\n send({ kind: \"result\", id: request.id });\n } else if (request.kind === \"register\") {\n if (windows)\n await windows.register(\n request.token,\n request.processId,\n request.root,\n );\n else {\n const entry = scopes.get(request.token);\n if (!entry) throw new Error(\"Unknown process scope.\");\n registerProcessScope(entry.scope, request.processId);\n await persist(entry);\n }\n send({ kind: \"result\", id: request.id });\n } else\n send({\n kind: \"result\",\n id: request.id,\n receipt: await close(request.token),\n });\n } catch (error) {\n if (request.kind === \"close\") poisoned = true;\n send({\n kind: \"error\",\n scopeUnconfirmed: poisoned,\n id: request.id,\n message: error instanceof Error ? error.message : String(error),\n });\n }\n })\n .catch((error) => {\n console.error(error);\n void shutdown();\n });\n});\nasync function shutdown() {\n if (stopping) return;\n stopping = true;\n await queue;\n if (windows) await windows.shutdown();\n else await Promise.allSettled([...scopes.keys()].map(close));\n process.exit(0);\n}\nprocess.once(\"disconnect\", () => {\n void shutdown();\n});\nprocess.once(\"SIGTERM\", () => {\n void shutdown();\n});\nprocess.once(\"SIGINT\", () => {\n void shutdown();\n});\nif (process.connected) send({ kind: \"ready\" });\nelse await shutdown();\n","import { spawn, type ChildProcess } from \"node:child_process\";\nimport { randomUUID } from \"node:crypto\";\nimport { createInterface } from \"node:readline\";\nimport { debuglog } from \"node:util\";\nimport { resolveDevtoolsHelperScript } from \"./helper-scripts.js\";\nimport {\n processGuardResponseSchema,\n processGuardStartupTimeoutMs,\n type ProcessGuardResponse,\n} from \"./process-scope-protocol.js\";\nimport { processScopeReceiptSchema } from \"./process-scope.js\";\n\nconst debug = debuglog(\"airjam-process-scope\");\n\n/** Kernel job handles remain in this guardian; EOF or guardian death kills every member. */\nexport class WindowsProcessScopes {\n private readonly child: ChildProcess;\n private readonly pending = new Map<\n string,\n {\n resolve: (\n value: Extract<ProcessGuardResponse, { kind: \"result\" }>,\n ) => void;\n reject: (error: Error) => void;\n timer: ReturnType<typeof setTimeout>;\n }\n >();\n private failure: Error | null = null;\n private readonly ready: Promise<void>;\n private constructor(startupTimeoutMs: number) {\n const started = performance.now();\n let firstOutput = Buffer.alloc(0);\n let diagnosticTail = \"\";\n const failure = (message: string) =>\n new Error(\n `${message} Elapsed ${Math.round(performance.now() - started)} ms; stdout prefix ${firstOutput.toString(\"hex\") || \"none\"}; diagnostics: ${diagnosticTail || \"none\"}`,\n );\n this.child = spawn(\n \"pwsh.exe\",\n [\n \"-NoProfile\",\n \"-NonInteractive\",\n \"-Command\",\n `& ([scriptblock]::Create([IO.File]::ReadAllText('${resolveDevtoolsHelperScript(\"process-scope-windows.ps1\").replaceAll(\"'\", \"''\")}')))`,\n ],\n { stdio: [\"pipe\", \"pipe\", \"pipe\"], windowsHide: true },\n );\n this.child.once(\"spawn\", () =>\n debug(\n \"PowerShell spawned in %d ms\",\n Math.round(performance.now() - started),\n ),\n );\n this.child.stderr?.on(\"data\", (chunk: Buffer) => {\n diagnosticTail = (diagnosticTail + chunk.toString()).slice(-4096);\n debug(\"%s\", chunk.toString().trim());\n });\n this.ready = new Promise<void>((resolve, reject) => {\n const timer = setTimeout(() => {\n const error = failure(\n \"process_scope_unavailable: Windows job guardian startup timed out.\",\n );\n abort(error);\n }, startupTimeoutMs);\n const abort = (error: Error) => {\n clearTimeout(timer);\n reject(error);\n this.fail(error);\n };\n const output = this.child.stdout;\n if (!output) throw new Error(\"Windows guardian output is unavailable.\");\n output.on(\"error\", abort);\n this.child.stdin?.on(\"error\", abort);\n this.child.stderr?.on(\"error\", abort);\n output.on(\"data\", (chunk: Buffer) => {\n if (firstOutput.length === 0)\n debug(\n \"First PowerShell output at %d ms: %s\",\n Math.round(performance.now() - started),\n chunk.subarray(0, 64).toString(\"hex\"),\n );\n if (firstOutput.length < 64)\n firstOutput = Buffer.concat([\n firstOutput,\n chunk.subarray(0, 64 - firstOutput.length),\n ]);\n });\n const lines = createInterface({ input: output });\n lines.on(\"line\", (line) => {\n try {\n const result = processGuardResponseSchema.parse(JSON.parse(line));\n if (result.kind === \"ready\") {\n clearTimeout(timer);\n resolve();\n return;\n }\n if (result.kind === \"startup-error\") throw new Error(result.message);\n const request = this.pending.get(result.id);\n if (!request) throw new Error(\"Unknown Windows job acknowledgement.\");\n this.pending.delete(result.id);\n clearTimeout(request.timer);\n if (result.kind === \"error\")\n request.reject(new Error(result.message));\n else request.resolve(result);\n } catch (error) {\n const invalid = failure(\n `process_scope_unavailable: Invalid Windows guardian response ${JSON.stringify(line.slice(0, 256))}: ${error instanceof Error ? error.message : String(error)}`,\n );\n abort(invalid);\n }\n });\n this.child.once(\"error\", (error) =>\n abort(\n failure(\n `process_scope_unavailable: Windows process scopes require PowerShell 7.4+ (pwsh). Install: winget install Microsoft.PowerShell. ${error.message}`,\n ),\n ),\n );\n this.child.once(\"exit\", (code, signal) => {\n const error = failure(\n `process_scope_unavailable: Windows job guardian exited (code ${code}, signal ${signal}).`,\n );\n abort(error);\n });\n });\n }\n static async open(startupTimeoutMs = processGuardStartupTimeoutMs - 2500) {\n const owner = new WindowsProcessScopes(startupTimeoutMs);\n await owner.ready;\n return owner;\n }\n private fail(error: Error) {\n const first = this.failure === null;\n this.failure ??= error;\n for (const request of this.pending.values()) {\n clearTimeout(request.timer);\n request.reject(error);\n }\n this.pending.clear();\n if (first) this.child.kill();\n }\n private async request(input: Record<string, unknown>) {\n await this.ready;\n if (this.failure) throw this.failure;\n const id = randomUUID();\n return new Promise<Extract<ProcessGuardResponse, { kind: \"result\" }>>(\n (resolve, reject) => {\n const timer = setTimeout(() => {\n this.fail(\n new Error(\n \"process_scope_unavailable: Windows job request timed out.\",\n ),\n );\n }, 5000);\n this.pending.set(id, { resolve, reject, timer });\n this.child.stdin?.write(\n `${JSON.stringify({ ...input, id })}\\n`,\n (error) => {\n if (error) this.fail(error);\n },\n );\n },\n );\n }\n async create(token: string) {\n await this.request({ kind: \"open\", token });\n }\n async register(token: string, processId: number, root: boolean) {\n await this.request({ kind: \"register\", token, processId, root });\n }\n async close(token: string) {\n const result = await this.request({ kind: \"close\", token });\n return processScopeReceiptSchema.parse(result.receipt);\n }\n async shutdown() {\n this.child.stdin?.end();\n await new Promise<void>((resolve) => {\n if (this.child.exitCode !== null) return resolve();\n const timer = setTimeout(() => {\n this.child.kill();\n resolve();\n }, 4000);\n this.child.once(\"exit\", () => {\n clearTimeout(timer);\n resolve();\n });\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,OAAO,UAAU;;;ACRjB,SAAS,aAAgC;AACzC,SAAS,kBAAkB;AAC3B,SAAS,uBAAuB;AAChC,SAAS,gBAAgB;AASzB,IAAM,QAAQ,SAAS,sBAAsB;AAGtC,IAAM,uBAAN,MAAM,sBAAqB;AAAA,EACf;AAAA,EACA,UAAU,oBAAI,IAS7B;AAAA,EACM,UAAwB;AAAA,EACf;AAAA,EACT,YAAY,kBAA0B;AAC5C,UAAM,UAAU,YAAY,IAAI;AAChC,QAAI,cAAc,OAAO,MAAM,CAAC;AAChC,QAAI,iBAAiB;AACrB,UAAM,UAAU,CAAC,YACf,IAAI;AAAA,MACF,GAAG,OAAO,YAAY,KAAK,MAAM,YAAY,IAAI,IAAI,OAAO,CAAC,sBAAsB,YAAY,SAAS,KAAK,KAAK,MAAM,kBAAkB,kBAAkB,MAAM;AAAA,IACpK;AACF,SAAK,QAAQ;AAAA,MACX;AAAA,MACA;AAAA,QACE;AAAA,QACA;AAAA,QACA;AAAA,QACA,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AAW,MAAM;AAC5B,OAAK,SAAS;AAChB,CAAC;AACD,QAAQ,KAAK,UAAU,MAAM;AAC3B,OAAK,SAAS;AAChB,CAAC;AACD,IAAI,QAAQ,UAAW,MAAK,EAAE,MAAM,QAAQ,CAAC;AAAA,IACxC,OAAM,SAAS;","names":["receipt"]}
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
$ErrorActionPreference = 'Stop'
|
|
2
|
+
if ($PSVersionTable.PSVersion -lt [Version]'7.4') {
|
|
3
|
+
throw 'Windows process scopes require PowerShell 7.4+ (pwsh). Install: winget install Microsoft.PowerShell.'
|
|
4
|
+
}
|
|
5
|
+
$guardianClock = [Diagnostics.Stopwatch]::StartNew()
|
|
6
|
+
[Console]::Error.WriteLine("Air Jam job guardian starting: PowerShell $($PSVersionTable.PSVersion), input $([Console]::InputEncoding.CodePage), output $([Console]::OutputEncoding.CodePage)")
|
|
7
|
+
[Console]::Error.WriteLine("Air Jam job guardian compiling at $($guardianClock.ElapsedMilliseconds) ms")
|
|
8
|
+
Add-Type -TypeDefinition @'
|
|
9
|
+
using System;
|
|
10
|
+
using System.Collections.Generic;
|
|
11
|
+
using System.ComponentModel;
|
|
12
|
+
using System.Runtime.InteropServices;
|
|
13
|
+
using System.Threading;
|
|
14
|
+
|
|
15
|
+
public sealed class AirJamProcessJobs : IDisposable {
|
|
16
|
+
[StructLayout(LayoutKind.Sequential)] struct BasicLimits {
|
|
17
|
+
public long ProcessTime, JobTime; public uint Flags;
|
|
18
|
+
public UIntPtr MinimumWorkingSet, MaximumWorkingSet;
|
|
19
|
+
public uint ActiveProcessLimit; public UIntPtr Affinity;
|
|
20
|
+
public uint PriorityClass, SchedulingClass;
|
|
21
|
+
}
|
|
22
|
+
[StructLayout(LayoutKind.Sequential)] struct Counters {
|
|
23
|
+
public ulong ReadOperations, WriteOperations, OtherOperations, ReadBytes, WriteBytes, OtherBytes;
|
|
24
|
+
}
|
|
25
|
+
[StructLayout(LayoutKind.Sequential)] struct ExtendedLimits {
|
|
26
|
+
public BasicLimits Basic; public Counters IO;
|
|
27
|
+
public UIntPtr ProcessMemory, JobMemory, PeakProcessMemory, PeakJobMemory;
|
|
28
|
+
}
|
|
29
|
+
[StructLayout(LayoutKind.Sequential)] struct FileTime { public uint Low, High; }
|
|
30
|
+
[StructLayout(LayoutKind.Sequential)] struct Accounting {
|
|
31
|
+
public long UserTime, KernelTime, UserPeriod, KernelPeriod;
|
|
32
|
+
public uint PageFaults, TotalProcesses, ActiveProcesses, TerminatedProcesses;
|
|
33
|
+
}
|
|
34
|
+
[DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true)] static extern IntPtr CreateJobObject(IntPtr attributes, string name);
|
|
35
|
+
[DllImport("kernel32.dll", SetLastError=true)] static extern bool SetInformationJobObject(IntPtr job, int kind, ref ExtendedLimits limits, uint size);
|
|
36
|
+
[DllImport("kernel32.dll", SetLastError=true)] static extern IntPtr OpenProcess(uint access, bool inherit, uint processId);
|
|
37
|
+
[DllImport("kernel32.dll", SetLastError=true)] static extern bool GetProcessTimes(IntPtr process, out FileTime created, out FileTime exited, out FileTime kernel, out FileTime user);
|
|
38
|
+
[DllImport("kernel32.dll", SetLastError=true)] static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process);
|
|
39
|
+
[DllImport("kernel32.dll", SetLastError=true)] static extern bool IsProcessInJob(IntPtr process, IntPtr job, out bool member);
|
|
40
|
+
[DllImport("kernel32.dll", SetLastError=true)] static extern bool QueryInformationJobObject(IntPtr job, int kind, IntPtr buffer, uint length, IntPtr returned);
|
|
41
|
+
[DllImport("kernel32.dll", EntryPoint="QueryInformationJobObject", SetLastError=true)] static extern bool QueryAccounting(IntPtr job, int kind, ref Accounting accounting, uint length, IntPtr returned);
|
|
42
|
+
[DllImport("kernel32.dll", SetLastError=true)] static extern bool TerminateJobObject(IntPtr job, uint code);
|
|
43
|
+
[DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr handle);
|
|
44
|
+
sealed class Scope {
|
|
45
|
+
public IntPtr Job;
|
|
46
|
+
public readonly List<IntPtr> Roots = new List<IntPtr>();
|
|
47
|
+
}
|
|
48
|
+
readonly Dictionary<string,Scope> scopes = new Dictionary<string,Scope>();
|
|
49
|
+
static void Require(bool success) { if(!success) throw new Win32Exception(Marshal.GetLastWin32Error()); }
|
|
50
|
+
public void Create(string token) {
|
|
51
|
+
if(scopes.ContainsKey(token)) throw new InvalidOperationException("Duplicate process scope.");
|
|
52
|
+
if(scopes.Count >= 64) throw new InvalidOperationException("Process scope allowance exceeded.");
|
|
53
|
+
IntPtr job = CreateJobObject(IntPtr.Zero, null);
|
|
54
|
+
Require(job != IntPtr.Zero);
|
|
55
|
+
try {
|
|
56
|
+
var limits = new ExtendedLimits();
|
|
57
|
+
limits.Basic.Flags = 0x2000; // JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; no breakaway.
|
|
58
|
+
Require(SetInformationJobObject(job, 9, ref limits, (uint)Marshal.SizeOf(typeof(ExtendedLimits))));
|
|
59
|
+
scopes.Add(token, new Scope { Job = job });
|
|
60
|
+
} catch { CloseHandle(job); throw; }
|
|
61
|
+
}
|
|
62
|
+
public void Register(string token, uint processId, bool root) {
|
|
63
|
+
Scope scope = scopes[token];
|
|
64
|
+
IntPtr process = OpenProcess(0x1 | 0x100 | 0x1000 | 0x100000, false, processId);
|
|
65
|
+
Require(process != IntPtr.Zero);
|
|
66
|
+
bool retained = false;
|
|
67
|
+
try {
|
|
68
|
+
FileTime created, exited, kernel, user;
|
|
69
|
+
Require(GetProcessTimes(process, out created, out exited, out kernel, out user));
|
|
70
|
+
bool member;
|
|
71
|
+
Require(IsProcessInJob(process, scope.Job, out member));
|
|
72
|
+
if(root && !member) Require(AssignProcessToJobObject(scope.Job, process));
|
|
73
|
+
Require(IsProcessInJob(process, scope.Job, out member));
|
|
74
|
+
if(!member) throw new InvalidOperationException("Process is not contained in its scope's job.");
|
|
75
|
+
if(Array.IndexOf(Processes(scope.Job), processId) < 0) throw new InvalidOperationException("Process is absent from the job's process list.");
|
|
76
|
+
if(root) { scope.Roots.Add(process); retained = true; }
|
|
77
|
+
} finally { if(!retained) CloseHandle(process); }
|
|
78
|
+
}
|
|
79
|
+
static uint[] Processes(IntPtr job) {
|
|
80
|
+
const int maximum = 4096;
|
|
81
|
+
int size = 8 + IntPtr.Size * maximum;
|
|
82
|
+
IntPtr buffer = Marshal.AllocHGlobal(size);
|
|
83
|
+
try {
|
|
84
|
+
Require(QueryInformationJobObject(job, 3, buffer, (uint)size, IntPtr.Zero));
|
|
85
|
+
int count = Marshal.ReadInt32(buffer, 4);
|
|
86
|
+
if(count < 0 || count > maximum) throw new InvalidOperationException("Job process list exceeds its allowance.");
|
|
87
|
+
uint[] result = new uint[count];
|
|
88
|
+
for(int index=0; index<count; index++) result[index] = checked((uint)Marshal.ReadIntPtr(buffer, 8 + index*IntPtr.Size).ToInt64());
|
|
89
|
+
return result;
|
|
90
|
+
} finally { Marshal.FreeHGlobal(buffer); }
|
|
91
|
+
}
|
|
92
|
+
public uint[] Close(string token) {
|
|
93
|
+
Scope scope = scopes[token];
|
|
94
|
+
Require(TerminateJobObject(scope.Job, 1));
|
|
95
|
+
foreach(IntPtr root in scope.Roots) CloseHandle(root);
|
|
96
|
+
scope.Roots.Clear();
|
|
97
|
+
DateTime deadline = DateTime.UtcNow.AddSeconds(3);
|
|
98
|
+
var accounting = new Accounting();
|
|
99
|
+
do {
|
|
100
|
+
Require(QueryAccounting(scope.Job, 1, ref accounting, (uint)Marshal.SizeOf(typeof(Accounting)), IntPtr.Zero));
|
|
101
|
+
if(accounting.ActiveProcesses == 0) break;
|
|
102
|
+
Thread.Sleep(25);
|
|
103
|
+
} while(DateTime.UtcNow < deadline);
|
|
104
|
+
if(accounting.ActiveProcesses == 0) {
|
|
105
|
+
CloseHandle(scope.Job); scopes.Remove(token);
|
|
106
|
+
return new uint[0];
|
|
107
|
+
}
|
|
108
|
+
uint[] members = Processes(scope.Job);
|
|
109
|
+
if(members.Length == 0) throw new InvalidOperationException("Job cleanup accounting is unconfirmed.");
|
|
110
|
+
return members;
|
|
111
|
+
}
|
|
112
|
+
public void Dispose() {
|
|
113
|
+
foreach(Scope scope in scopes.Values) {
|
|
114
|
+
CloseHandle(scope.Job);
|
|
115
|
+
foreach(IntPtr root in scope.Roots) CloseHandle(root);
|
|
116
|
+
}
|
|
117
|
+
scopes.Clear();
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
'@
|
|
121
|
+
[Console]::Error.WriteLine("Air Jam job guardian compiled at $($guardianClock.ElapsedMilliseconds) ms")
|
|
122
|
+
$jobs = New-Object AirJamProcessJobs
|
|
123
|
+
try {
|
|
124
|
+
[Console]::Out.WriteLine('{"kind":"ready"}')
|
|
125
|
+
[Console]::Error.WriteLine("Air Jam job guardian ready at $($guardianClock.ElapsedMilliseconds) ms")
|
|
126
|
+
while ($null -ne ($line = [Console]::In.ReadLine())) {
|
|
127
|
+
$request = $line | ConvertFrom-Json
|
|
128
|
+
try {
|
|
129
|
+
$receipt = $null
|
|
130
|
+
switch ($request.kind) {
|
|
131
|
+
'open' { $jobs.Create([string]$request.token) }
|
|
132
|
+
'register' { $jobs.Register([string]$request.token, [uint32]$request.processId, [bool]$request.root) }
|
|
133
|
+
'close' {
|
|
134
|
+
$members = @($jobs.Close([string]$request.token))
|
|
135
|
+
$survivors = @($members | ForEach-Object { @{processId=$_;groupId=$_} })
|
|
136
|
+
$status = if($members.Count -eq 0) {'tree_clean'} else {'tree_unconfirmed'}
|
|
137
|
+
$receipt = @{status=$status;token=$request.token;survivors=$survivors;errors=@()}
|
|
138
|
+
}
|
|
139
|
+
default { throw 'Unknown process scope operation.' }
|
|
140
|
+
}
|
|
141
|
+
$result = @{kind='result';id=$request.id}
|
|
142
|
+
if($null -ne $receipt) { $result.receipt = $receipt }
|
|
143
|
+
[Console]::Out.WriteLine(($result | ConvertTo-Json -Compress -Depth 8))
|
|
144
|
+
} catch {
|
|
145
|
+
[Console]::Out.WriteLine((@{kind='error';id=$request.id;message=$_.Exception.Message;scopeUnconfirmed=($request.kind -eq 'close')} | ConvertTo-Json -Compress))
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
} finally { $jobs.Dispose() }
|