@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.
Files changed (263) hide show
  1. package/README.md +60 -0
  2. package/dist/{chunk-VKMJO6VN.js → chunk-2O67AXCU.js} +150 -40
  3. package/dist/chunk-2O67AXCU.js.map +1 -0
  4. package/dist/chunk-AO3ZDXF6.js +142 -0
  5. package/dist/chunk-AO3ZDXF6.js.map +1 -0
  6. package/dist/chunk-ART5TEYT.js +472 -0
  7. package/dist/chunk-ART5TEYT.js.map +1 -0
  8. package/dist/chunk-ASC2CK2R.js +77 -0
  9. package/dist/chunk-ASC2CK2R.js.map +1 -0
  10. package/dist/chunk-E3UZZGAV.js +50 -0
  11. package/dist/chunk-E3UZZGAV.js.map +1 -0
  12. package/dist/chunk-EJTE7UKX.js +64 -0
  13. package/dist/chunk-EJTE7UKX.js.map +1 -0
  14. package/dist/chunk-ESFKNN75.js +110 -0
  15. package/dist/chunk-ESFKNN75.js.map +1 -0
  16. package/dist/chunk-EU7A6PXW.js +1339 -0
  17. package/dist/chunk-EU7A6PXW.js.map +1 -0
  18. package/dist/chunk-FN7E6EA7.js +549 -0
  19. package/dist/chunk-FN7E6EA7.js.map +1 -0
  20. package/dist/chunk-GDFAWHGA.js +190 -0
  21. package/dist/chunk-GDFAWHGA.js.map +1 -0
  22. package/dist/chunk-HZUGBH4Y.js +347 -0
  23. package/dist/chunk-HZUGBH4Y.js.map +1 -0
  24. package/dist/chunk-ITKAOEGX.js +93 -0
  25. package/dist/chunk-ITKAOEGX.js.map +1 -0
  26. package/dist/chunk-JBCUTWRI.js +897 -0
  27. package/dist/chunk-JBCUTWRI.js.map +1 -0
  28. package/dist/chunk-JSI5S4WP.js +1174 -0
  29. package/dist/chunk-JSI5S4WP.js.map +1 -0
  30. package/dist/chunk-L4D675BG.js +97 -0
  31. package/dist/chunk-L4D675BG.js.map +1 -0
  32. package/dist/{chunk-GUEZP773.js → chunk-LB3Y64P5.js} +206 -60
  33. package/dist/chunk-LB3Y64P5.js.map +1 -0
  34. package/dist/chunk-M6CJ7GQC.js +133 -0
  35. package/dist/chunk-M6CJ7GQC.js.map +1 -0
  36. package/dist/{chunk-CKFT2ZJE.js → chunk-MEIMOSZC.js} +53 -105
  37. package/dist/chunk-MEIMOSZC.js.map +1 -0
  38. package/dist/chunk-OM6SCJ7H.js +18 -0
  39. package/dist/chunk-OM6SCJ7H.js.map +1 -0
  40. package/dist/chunk-PKD4WVX5.js +63 -0
  41. package/dist/chunk-PKD4WVX5.js.map +1 -0
  42. package/dist/chunk-PMBLXGFM.js +3384 -0
  43. package/dist/chunk-PMBLXGFM.js.map +1 -0
  44. package/dist/chunk-PMNE5GIN.js +279 -0
  45. package/dist/chunk-PMNE5GIN.js.map +1 -0
  46. package/dist/chunk-QAWI64VR.js +148 -0
  47. package/dist/chunk-QAWI64VR.js.map +1 -0
  48. package/dist/chunk-QGADSPHZ.js +449 -0
  49. package/dist/chunk-QGADSPHZ.js.map +1 -0
  50. package/dist/chunk-SPYN66UV.js +338 -0
  51. package/dist/chunk-SPYN66UV.js.map +1 -0
  52. package/dist/context.d.ts +9 -3
  53. package/dist/context.js +2 -1
  54. package/dist/controller.d.ts +33 -7
  55. package/dist/controller.js +18 -8
  56. package/dist/dependencies.d.ts +44 -0
  57. package/dist/dependencies.js +10 -0
  58. package/dist/dev.d.ts +9 -3
  59. package/dist/dev.js +3 -4
  60. package/dist/game-builds.d.ts +200 -0
  61. package/dist/game-builds.js +16 -0
  62. package/dist/game-builds.js.map +1 -0
  63. package/dist/game-run-watch-CEd_SpAT.d.ts +84 -0
  64. package/dist/game-runs.d.ts +1452 -0
  65. package/dist/game-runs.js +76 -0
  66. package/dist/game-runs.js.map +1 -0
  67. package/dist/game-session-broker-CUvORfMd.d.ts +439 -0
  68. package/dist/game-session-broker.d.ts +4 -57
  69. package/dist/game-session-broker.js +33 -228
  70. package/dist/game-session-broker.js.map +1 -1
  71. package/dist/game-session.d.ts +3931 -10
  72. package/dist/game-session.js +186 -15
  73. package/dist/game-session.js.map +1 -1
  74. package/dist/game-settings.d.ts +16 -0
  75. package/dist/game-settings.js +237 -0
  76. package/dist/game-settings.js.map +1 -0
  77. package/dist/games.d.ts +11 -4
  78. package/dist/games.js +4 -2
  79. package/dist/harness/visual.d.ts +34 -151
  80. package/dist/harness/visual.js +6 -1
  81. package/dist/logs.d.ts +8 -2
  82. package/dist/logs.js +3 -4
  83. package/dist/logs.js.map +1 -1
  84. package/dist/managed-process-scope-BicYi_t9.d.ts +3 -0
  85. package/dist/mcp-config.js +2 -1
  86. package/dist/mcp-config.js.map +1 -1
  87. package/dist/platform-auth.d.ts +8 -111
  88. package/dist/platform-auth.js +9 -1
  89. package/dist/platform-game-analytics.d.ts +51 -0
  90. package/dist/platform-game-analytics.js +49 -0
  91. package/dist/platform-game-analytics.js.map +1 -0
  92. package/dist/platform-game-app-id.d.ts +46 -0
  93. package/dist/platform-game-app-id.js +93 -0
  94. package/dist/platform-game-app-id.js.map +1 -0
  95. package/dist/platform-game-media.d.ts +40 -2
  96. package/dist/platform-game-media.js +1 -1
  97. package/dist/platform-games.d.ts +24 -2
  98. package/dist/platform-games.js +16 -84
  99. package/dist/platform-games.js.map +1 -1
  100. package/dist/quality.d.ts +9 -3
  101. package/dist/quality.js +3 -4
  102. package/dist/quality.js.map +1 -1
  103. package/dist/release.d.ts +226 -16
  104. package/dist/release.js +18 -1331
  105. package/dist/release.js.map +1 -1
  106. package/dist/rooms-check.d.ts +90 -0
  107. package/dist/rooms-check.js +717 -0
  108. package/dist/rooms-check.js.map +1 -0
  109. package/dist/source-tree-contract.d.ts +16 -0
  110. package/dist/source-tree-contract.js +13 -0
  111. package/dist/source-tree-contract.js.map +1 -0
  112. package/dist/testing.d.ts +464 -0
  113. package/dist/testing.js +27 -0
  114. package/dist/testing.js.map +1 -0
  115. package/dist/tooling/describe-game.js +54 -0
  116. package/dist/tooling/describe-game.js.map +1 -0
  117. package/dist/tooling/game-session-broker.js +28 -0
  118. package/dist/tooling/game-session-broker.js.map +1 -0
  119. package/dist/tooling/hold-runtime-host.js +770 -68
  120. package/dist/tooling/hold-runtime-host.js.map +1 -1
  121. package/dist/tooling/list-visual-scenarios.js +18 -55
  122. package/dist/tooling/list-visual-scenarios.js.map +1 -1
  123. package/dist/tooling/process-scope-bootstrap.mjs +24 -0
  124. package/dist/tooling/process-scope-guard.d.ts +2 -0
  125. package/dist/tooling/process-scope-guard.js +388 -0
  126. package/dist/tooling/process-scope-guard.js.map +1 -0
  127. package/dist/tooling/process-scope-windows.ps1 +148 -0
  128. package/dist/tooling/rooms-check-device.d.ts +2 -0
  129. package/dist/tooling/rooms-check-device.js +498 -0
  130. package/dist/tooling/rooms-check-device.js.map +1 -0
  131. package/dist/tooling/run-headless-room.d.ts +2 -0
  132. package/dist/tooling/run-headless-room.js +288 -0
  133. package/dist/tooling/run-headless-room.js.map +1 -0
  134. package/dist/tooling/run-test-profile.d.ts +2 -0
  135. package/dist/tooling/run-test-profile.js +181 -0
  136. package/dist/tooling/run-test-profile.js.map +1 -0
  137. package/dist/tooling/run-visual-capture.js +70 -34
  138. package/dist/tooling/run-visual-capture.js.map +1 -1
  139. package/dist/tooling/seal-game-build.d.ts +2 -0
  140. package/dist/tooling/seal-game-build.js +120 -0
  141. package/dist/tooling/seal-game-build.js.map +1 -0
  142. package/dist/{types-C6NrHt88.d.ts → types-CdYrgrG_.d.ts} +337 -76
  143. package/dist/types-DyRD-ym1.d.ts +141 -0
  144. package/dist/visual.d.ts +9 -3
  145. package/dist/visual.js +24 -68
  146. package/dist/visual.js.map +1 -1
  147. package/package.json +51 -14
  148. package/src/bounded-response.ts +28 -0
  149. package/src/built-game-runtime.ts +152 -0
  150. package/src/context.ts +2 -13
  151. package/src/controller-protocol.ts +22 -0
  152. package/src/controller.ts +747 -597
  153. package/src/current-room-host.ts +166 -0
  154. package/src/decision-provider.ts +102 -0
  155. package/src/dependencies.ts +176 -0
  156. package/src/dependency-install-contract.ts +12 -0
  157. package/src/dev.ts +46 -50
  158. package/src/game-action-observation.ts +11 -1
  159. package/src/game-build-protocol.ts +72 -0
  160. package/src/game-build.ts +483 -0
  161. package/src/game-run-owner.ts +2358 -0
  162. package/src/game-run-protocol.ts +448 -0
  163. package/src/game-run-record.ts +92 -0
  164. package/src/game-run-replay.ts +95 -0
  165. package/src/game-run-watch.ts +155 -0
  166. package/src/game-session-broker.ts +689 -197
  167. package/src/game-session-operations.ts +61 -0
  168. package/src/game-session-protocol.ts +180 -0
  169. package/src/game-session-runtime.ts +861 -0
  170. package/src/game-session.ts +164 -417
  171. package/src/game-settings.ts +295 -0
  172. package/src/games.ts +88 -92
  173. package/src/harness/visual/browser.ts +100 -0
  174. package/src/harness/visual/controller-observation.ts +181 -0
  175. package/src/harness/visual/runner.ts +24 -21
  176. package/src/harness/visual/runtime-controller-observations.ts +151 -0
  177. package/src/harness/visual/scenario-contract.ts +1 -2
  178. package/src/harness/visual/scenario-helpers.ts +5 -1
  179. package/src/harness/visual/screencast.ts +155 -0
  180. package/src/harness/visual/session.ts +74 -69
  181. package/src/harness/visual/types.ts +8 -5
  182. package/src/headless-room-protocol.ts +112 -0
  183. package/src/headless-room.ts +222 -0
  184. package/src/helper-channel.ts +229 -0
  185. package/src/helper-scripts.ts +25 -5
  186. package/src/installed-dependencies.ts +74 -0
  187. package/src/managed-process-scope.ts +481 -0
  188. package/src/node-process-environment.ts +10 -0
  189. package/src/platform-auth.ts +194 -55
  190. package/src/platform-game-analytics.ts +50 -0
  191. package/src/platform-game-app-id.ts +99 -0
  192. package/src/platform-games.ts +13 -111
  193. package/src/policy-artifact-contract.ts +52 -0
  194. package/src/policy-artifacts.ts +134 -0
  195. package/src/process-scope-admission.ts +50 -0
  196. package/src/process-scope-protocol.ts +66 -0
  197. package/src/process-scope.ts +327 -0
  198. package/src/release.ts +28 -42
  199. package/src/rooms-check-fleet.ts +194 -0
  200. package/src/rooms-check-link.ts +138 -0
  201. package/src/rooms-check-protocol.ts +244 -0
  202. package/src/rooms-check.ts +797 -0
  203. package/src/runtime-owner-protocol.ts +106 -18
  204. package/src/source-tree-contract.ts +70 -0
  205. package/src/source-tree.ts +84 -0
  206. package/src/test-profile-process.ts +153 -0
  207. package/src/test-profile-protocol.ts +116 -0
  208. package/src/testing.ts +430 -0
  209. package/src/tooling/declaration-hook.ts +52 -0
  210. package/src/tooling/describe-game.ts +49 -0
  211. package/src/tooling/game-session-broker.ts +7 -0
  212. package/src/tooling/hold-runtime-host.ts +254 -42
  213. package/src/tooling/list-visual-scenarios.ts +19 -62
  214. package/src/tooling/load-game.ts +79 -0
  215. package/src/tooling/process-scope-bootstrap.mjs +24 -0
  216. package/src/tooling/process-scope-guard.ts +213 -0
  217. package/src/tooling/process-scope-windows.ps1 +148 -0
  218. package/src/tooling/rooms-check-device.ts +493 -0
  219. package/src/tooling/run-headless-room.ts +329 -0
  220. package/src/tooling/run-test-profile.ts +190 -0
  221. package/src/tooling/run-visual-capture.ts +37 -23
  222. package/src/tooling/runtime-owner-actions.ts +23 -0
  223. package/src/tooling/seal-game-build.ts +118 -0
  224. package/src/tooling/visual-pack.ts +10 -45
  225. package/src/types.ts +54 -77
  226. package/src/visual.ts +14 -22
  227. package/src/windows-process-scopes.ts +189 -0
  228. package/dist/agent.d.ts +0 -15
  229. package/dist/agent.js +0 -19
  230. package/dist/chunk-5YAARMW5.js +0 -36
  231. package/dist/chunk-5YAARMW5.js.map +0 -1
  232. package/dist/chunk-6WQODT37.js +0 -1019
  233. package/dist/chunk-6WQODT37.js.map +0 -1
  234. package/dist/chunk-CKFT2ZJE.js.map +0 -1
  235. package/dist/chunk-ER3Q2C4G.js +0 -358
  236. package/dist/chunk-ER3Q2C4G.js.map +0 -1
  237. package/dist/chunk-GUEZP773.js.map +0 -1
  238. package/dist/chunk-HIDNI56E.js +0 -33
  239. package/dist/chunk-HIDNI56E.js.map +0 -1
  240. package/dist/chunk-QKXS5D35.js +0 -43
  241. package/dist/chunk-QKXS5D35.js.map +0 -1
  242. package/dist/chunk-S4LSCEVE.js +0 -261
  243. package/dist/chunk-S4LSCEVE.js.map +0 -1
  244. package/dist/chunk-VKMJO6VN.js.map +0 -1
  245. package/dist/chunk-WFUR3MXY.js +0 -67
  246. package/dist/chunk-WFUR3MXY.js.map +0 -1
  247. package/dist/chunk-XEMR7KUE.js +0 -361
  248. package/dist/chunk-XEMR7KUE.js.map +0 -1
  249. package/dist/chunk-ZLPD7FY5.js +0 -191
  250. package/dist/chunk-ZLPD7FY5.js.map +0 -1
  251. package/dist/tooling/agent-contract.js +0 -193
  252. package/dist/tooling/agent-contract.js.map +0 -1
  253. package/dist/tooling/inspect-airjam-agent.js +0 -37
  254. package/dist/tooling/inspect-airjam-agent.js.map +0 -1
  255. package/src/agent.ts +0 -380
  256. package/src/tooling/agent-contract.ts +0 -232
  257. package/src/tooling/agent-declaration.ts +0 -36
  258. package/src/tooling/airjam-agent-inspection.ts +0 -45
  259. package/src/tooling/airjam-agent.ts +0 -118
  260. package/src/tooling/inspect-airjam-agent.ts +0 -20
  261. /package/dist/{agent.js.map → dependencies.js.map} +0 -0
  262. /package/dist/tooling/{agent-contract.d.ts → describe-game.d.ts} +0 -0
  263. /package/dist/tooling/{inspect-airjam-agent.d.ts → game-session-broker.d.ts} +0 -0
@@ -0,0 +1,481 @@
1
+ import { spawn, type ChildProcess } from "node:child_process";
2
+ import { randomUUID } from "node:crypto";
3
+ import { readFile } from "node:fs/promises";
4
+ import path from "node:path";
5
+ import { debuglog } from "node:util";
6
+ import {
7
+ resolveDevtoolsHelperArgs,
8
+ resolveDevtoolsHelperScript,
9
+ } from "./helper-scripts.js";
10
+ import { nodeProcessEnvironment } from "./node-process-environment.js";
11
+ import {
12
+ processGuardResponseSchema,
13
+ processGuardStartupTimeoutMs,
14
+ processScopeAdmissionSchema,
15
+ type ProcessGuardRequest,
16
+ type ProcessGuardResponse,
17
+ } from "./process-scope-protocol.js";
18
+ import {
19
+ closeProcessScope,
20
+ processScopeJournalSchema,
21
+ processScopeMarker,
22
+ } from "./process-scope.js";
23
+
24
+ let processScopeFault: Error | undefined;
25
+ const debug = debuglog("airjam-process-scope");
26
+ function recordProcessScopeFault(error: unknown) {
27
+ processScopeFault ??=
28
+ error instanceof Error ? error : new Error(String(error));
29
+ }
30
+ export function assertProcessScopesConfirmed() {
31
+ if (processScopeFault) throw processScopeFault;
32
+ }
33
+
34
+ export function processGuardEnvironment() {
35
+ return nodeProcessEnvironment([
36
+ "PATH",
37
+ "SystemRoot",
38
+ "WINDIR",
39
+ "HOME",
40
+ "TMPDIR",
41
+ "TEMP",
42
+ "TMP",
43
+ "LANG",
44
+ "LC_ALL",
45
+ "NODE_DEBUG",
46
+ ]);
47
+ }
48
+
49
+ class ProcessGuard {
50
+ private readonly child: ChildProcess;
51
+ private failure: Error | null = null;
52
+ private readyConfirmed = false;
53
+ private readonly failureListeners = new Set<() => void>();
54
+ get processId() {
55
+ return this.child.pid;
56
+ }
57
+ watchFailure(listener: () => void) {
58
+ if (this.failure) listener();
59
+ else this.failureListeners.add(listener);
60
+ return () => this.failureListeners.delete(listener);
61
+ }
62
+ private readonly pending = new Map<
63
+ string,
64
+ {
65
+ resolve: (
66
+ value: Extract<ProcessGuardResponse, { kind: "result" }>,
67
+ ) => void;
68
+ reject: (error: Error) => void;
69
+ timer: ReturnType<typeof setTimeout>;
70
+ expired: boolean;
71
+ }
72
+ >();
73
+ readonly ready: Promise<void>;
74
+ constructor() {
75
+ const started = performance.now();
76
+ const startupDeadline =
77
+ process.hrtime.bigint() + BigInt(processGuardStartupTimeoutMs) * 1000000n;
78
+ this.child = spawn(
79
+ process.execPath,
80
+ [
81
+ ...resolveDevtoolsHelperArgs(
82
+ resolveDevtoolsHelperScript("process-scope-guard.ts"),
83
+ ),
84
+ startupDeadline.toString(),
85
+ ],
86
+ {
87
+ detached: true,
88
+ stdio: ["ignore", "ignore", "inherit", "ipc"],
89
+ env: processGuardEnvironment(),
90
+ },
91
+ );
92
+ this.child.unref();
93
+ this.ready = new Promise<void>((resolve, reject) => {
94
+ const timer = setTimeout(
95
+ () =>
96
+ abort(
97
+ new Error("process_scope_unavailable: Guardian startup timed out."),
98
+ ),
99
+ Math.max(
100
+ 1,
101
+ Number(startupDeadline - process.hrtime.bigint()) / 1000000,
102
+ ),
103
+ );
104
+ const abort = (error: Error) => {
105
+ clearTimeout(timer);
106
+ reject(error);
107
+ this.fail(error);
108
+ };
109
+ this.child.on("message", (value: unknown) => {
110
+ const message = processGuardResponseSchema.safeParse(value);
111
+ if (!message.success)
112
+ return abort(
113
+ new Error("process_scope_unavailable: Invalid guardian response."),
114
+ );
115
+ const result = message.data;
116
+ if (result.kind === "startup-error")
117
+ return abort(new Error(result.message));
118
+ if (result.kind === "ready") {
119
+ this.readyConfirmed = true;
120
+ clearTimeout(timer);
121
+ debug("%j", {
122
+ event: "process-scope-prepared",
123
+ durationMs: performance.now() - started,
124
+ });
125
+ this.child.channel?.unref();
126
+ resolve();
127
+ return;
128
+ }
129
+ const request = this.pending.get(result.id);
130
+ if (!request)
131
+ return abort(
132
+ new Error("process_scope_unavailable: Unknown guardian response."),
133
+ );
134
+ this.pending.delete(result.id);
135
+ clearTimeout(request.timer);
136
+ if (!request.expired) {
137
+ if (result.kind === "error") {
138
+ const error = new Error(result.message);
139
+ if (result.scopeUnconfirmed) recordProcessScopeFault(error);
140
+ request.reject(error);
141
+ } else request.resolve(result);
142
+ }
143
+ if (![...this.pending.values()].some((value) => !value.expired))
144
+ this.child.channel?.unref();
145
+ });
146
+ this.child.once("error", (error) => {
147
+ abort(error);
148
+ });
149
+ this.child.once("exit", () => {
150
+ const error = new Error("process_scope_unavailable: Guardian exited.");
151
+ abort(error);
152
+ });
153
+ });
154
+ }
155
+ private fail(error: Error) {
156
+ if (this.readyConfirmed) recordProcessScopeFault(error);
157
+ const first = this.failure === null;
158
+ this.failure ??= error;
159
+ for (const request of this.pending.values()) {
160
+ clearTimeout(request.timer);
161
+ request.reject(error);
162
+ }
163
+ this.pending.clear();
164
+ if (this.child.connected) this.child.disconnect();
165
+ this.child.channel?.unref();
166
+ if (first) for (const listener of this.failureListeners) listener();
167
+ }
168
+ async request(request: ProcessGuardRequest) {
169
+ await this.ready;
170
+ if (this.failure) throw this.failure;
171
+ if (this.pending.size >= 128)
172
+ throw new Error(
173
+ "process_scope_unavailable: Guardian request backlog exceeded.",
174
+ );
175
+ return new Promise<Extract<ProcessGuardResponse, { kind: "result" }>>(
176
+ (resolve, reject) => {
177
+ this.child.channel?.ref();
178
+ const timer = setTimeout(() => {
179
+ const pending = this.pending.get(request.id);
180
+ if (!pending) return;
181
+ pending.expired = true;
182
+ const error = new Error(
183
+ "process_scope_unavailable: Guardian request timed out.",
184
+ );
185
+ recordProcessScopeFault(error);
186
+ reject(error);
187
+ if (![...this.pending.values()].some((value) => !value.expired))
188
+ this.child.channel?.unref();
189
+ }, 10000);
190
+ this.pending.set(request.id, {
191
+ resolve,
192
+ reject,
193
+ timer,
194
+ expired: false,
195
+ });
196
+ this.child.send(request, (error) => {
197
+ if (error) this.fail(error);
198
+ });
199
+ },
200
+ );
201
+ }
202
+ }
203
+ let guard: ProcessGuard | undefined;
204
+ export async function prepareProcessScopes(startupSignal?: AbortSignal) {
205
+ assertProcessScopesConfirmed();
206
+ startupSignal?.throwIfAborted();
207
+ const manager = (guard ??= new ProcessGuard());
208
+ if (!startupSignal) await manager.ready;
209
+ else
210
+ await new Promise<void>((resolve, reject) => {
211
+ const aborted = () => {
212
+ startupSignal.removeEventListener("abort", aborted);
213
+ reject(startupSignal.reason);
214
+ };
215
+ startupSignal.addEventListener("abort", aborted, { once: true });
216
+ void manager.ready.then(
217
+ () => {
218
+ startupSignal.removeEventListener("abort", aborted);
219
+ resolve();
220
+ },
221
+ (error: unknown) => {
222
+ startupSignal.removeEventListener("abort", aborted);
223
+ reject(error);
224
+ },
225
+ );
226
+ });
227
+ return manager;
228
+ }
229
+ const processScopes = new WeakMap<ChildProcess, () => Promise<void>>();
230
+
231
+ async function stopUnadmittedRoot(child: ChildProcess) {
232
+ if (!child.pid || child.exitCode !== null || child.signalCode !== null)
233
+ return;
234
+ await new Promise<void>((resolve, reject) => {
235
+ const finish = (error?: Error) => {
236
+ clearTimeout(timer);
237
+ child.off("exit", exited);
238
+ child.off("error", failed);
239
+ if (error) reject(error);
240
+ else resolve();
241
+ };
242
+ const exited = () => finish();
243
+ const failed = (error: Error) => finish(error);
244
+ const timer = setTimeout(
245
+ () =>
246
+ finish(
247
+ new Error("process_tree_unconfirmed: Unadmitted root did not exit."),
248
+ ),
249
+ 2000,
250
+ );
251
+ child.once("exit", exited);
252
+ child.once("error", failed);
253
+ child.kill("SIGKILL");
254
+ });
255
+ }
256
+
257
+ export type ProcessScopeObserver = (close: () => Promise<void>) => void;
258
+
259
+ export async function closeAfterProcessFailure(
260
+ close: () => Promise<void>,
261
+ primary: unknown,
262
+ ): Promise<never> {
263
+ try {
264
+ await close();
265
+ } catch (cleanup) {
266
+ if (primary === cleanup) throw primary;
267
+ const message = (value: unknown) =>
268
+ value instanceof Error ? value.message : String(value);
269
+ throw new AggregateError(
270
+ [primary, cleanup],
271
+ `${message(primary)}; process cleanup could not be confirmed: ${message(cleanup)}`,
272
+ );
273
+ }
274
+ throw primary;
275
+ }
276
+
277
+ /** The bootstrap's gate opens only after kernel membership is recorded, before loading tsx or user code. */
278
+ export async function spawnScopedProcess(
279
+ args: string[],
280
+ options: {
281
+ cwd: string;
282
+ env?: NodeJS.ProcessEnv;
283
+ onScope?: ProcessScopeObserver;
284
+ startupSignal?: AbortSignal;
285
+ },
286
+ ) {
287
+ assertProcessScopesConfirmed();
288
+ const registerTypescript = args[0] === "--import";
289
+ const entry = registerTypescript ? args[2] : args[0];
290
+ if (!entry || entry.startsWith("-"))
291
+ throw new Error("A scoped process requires a helper module.");
292
+ const argumentsList = args.slice(registerTypescript ? 3 : 1);
293
+ const manager = await prepareProcessScopes(options.startupSignal);
294
+ options.startupSignal?.throwIfAborted();
295
+ const token = randomUUID();
296
+ await manager.request({
297
+ kind: "open",
298
+ id: randomUUID(),
299
+ token,
300
+ rootDir: options.cwd,
301
+ });
302
+ const { onScope, startupSignal, ...processOptions } = options;
303
+ const child = spawn(
304
+ process.execPath,
305
+ [
306
+ resolveDevtoolsHelperScript("process-scope-bootstrap.mjs"),
307
+ entry,
308
+ registerTypescript ? args[1] : "javascript",
309
+ ...argumentsList,
310
+ processScopeMarker(token),
311
+ ],
312
+ {
313
+ ...processOptions,
314
+ env: { ...(options.env ?? process.env), AIRJAM_PROCESS_SCOPE: token },
315
+ detached: true,
316
+ stdio: ["ignore", "pipe", "pipe", "ipc"],
317
+ },
318
+ );
319
+ const rootClosed = new Promise<void>((resolve) =>
320
+ child.once("close", () => resolve()),
321
+ );
322
+ let admitted = false;
323
+ let hello = false;
324
+ let gateOpened = false;
325
+ const openGate = () => {
326
+ if (
327
+ hello &&
328
+ admitted &&
329
+ !gateOpened &&
330
+ !closing &&
331
+ !startupSignal?.aborted &&
332
+ child.connected
333
+ ) {
334
+ gateOpened = true;
335
+ startupSignal?.removeEventListener("abort", abortAdmission);
336
+ child.send(1);
337
+ }
338
+ };
339
+ let closing: Promise<void> | undefined;
340
+ let unwatch = () => {};
341
+ const close = () =>
342
+ (closing ??= (async () => {
343
+ const result = await manager.request({
344
+ kind: "close",
345
+ id: randomUUID(),
346
+ token,
347
+ });
348
+ if (!admitted) await stopUnadmittedRoot(child);
349
+ if (result.receipt?.status !== "tree_clean")
350
+ throw new Error(
351
+ `process_tree_unconfirmed: ${JSON.stringify(result.receipt)}`,
352
+ );
353
+ await new Promise<void>((resolve, reject) => {
354
+ const timer = setTimeout(
355
+ () =>
356
+ reject(
357
+ new Error(
358
+ "process_tree_unconfirmed: Scoped root streams did not close.",
359
+ ),
360
+ ),
361
+ 2000,
362
+ );
363
+ void rootClosed.then(() => {
364
+ clearTimeout(timer);
365
+ resolve();
366
+ });
367
+ });
368
+ unwatch();
369
+ startupSignal?.removeEventListener("abort", abortAdmission);
370
+ })().catch((error) => {
371
+ recordProcessScopeFault(error);
372
+ throw error;
373
+ }));
374
+ const abortAdmission = () => {
375
+ void close().catch((error) => console.error(error));
376
+ };
377
+ startupSignal?.addEventListener("abort", abortAdmission, { once: true });
378
+ if (startupSignal?.aborted) abortAdmission();
379
+ unwatch = manager.watchFailure(() => {
380
+ void (async () => {
381
+ if (process.platform === "win32") {
382
+ await stopUnadmittedRoot(child);
383
+ return;
384
+ }
385
+ const filename = path.join(
386
+ options.cwd,
387
+ ".airjam/devtools/process-scopes",
388
+ `${token}.json`,
389
+ );
390
+ const journal = processScopeJournalSchema.parse(
391
+ JSON.parse(await readFile(filename, "utf8")),
392
+ );
393
+ if (
394
+ journal.scope.token !== token ||
395
+ journal.guardian.processId !== manager.processId
396
+ )
397
+ throw new Error(
398
+ "process_tree_unconfirmed: Guardian recovery identity mismatch.",
399
+ );
400
+ const receipt = await closeProcessScope(journal.scope);
401
+ if (receipt.status !== "tree_clean")
402
+ throw new Error(`process_tree_unconfirmed: ${JSON.stringify(receipt)}`);
403
+ })()
404
+ .catch((error) => console.error(error))
405
+ .finally(() => {
406
+ child.kill("SIGKILL");
407
+ });
408
+ });
409
+ processScopes.set(child, close);
410
+ try {
411
+ onScope?.(close);
412
+ } catch (error) {
413
+ return closeAfterProcessFailure(close, error);
414
+ }
415
+ child.on("message", (value: unknown) => {
416
+ if (value === 0) {
417
+ hello = true;
418
+ openGate();
419
+ return;
420
+ }
421
+ const request = processScopeAdmissionSchema.safeParse(value);
422
+ if (!request.success) return;
423
+ void (async () => {
424
+ let error: string | undefined;
425
+ try {
426
+ if (!admitted || request.data.token !== token || closing)
427
+ throw new Error(
428
+ "process_scope_unavailable: Scope admission is closed.",
429
+ );
430
+ await manager.request({
431
+ kind: "register",
432
+ id: randomUUID(),
433
+ token,
434
+ processId: request.data.processId,
435
+ root: false,
436
+ });
437
+ } catch (failure) {
438
+ error = failure instanceof Error ? failure.message : String(failure);
439
+ }
440
+ if (child.connected)
441
+ child.send({
442
+ type: "airjam-process-scope/admitted",
443
+ id: request.data.id,
444
+ ...(error ? { error } : {}),
445
+ });
446
+ })().catch((error) => console.error(error));
447
+ });
448
+ child.once("exit", () => {
449
+ void close().catch((error) => console.error(error));
450
+ });
451
+ child.once("error", () => {
452
+ void close().catch((error) => console.error(error));
453
+ });
454
+ void (async () => {
455
+ if (!child.pid) throw new Error("Process root identity unavailable.");
456
+ await manager.request({
457
+ kind: "register",
458
+ id: randomUUID(),
459
+ token,
460
+ processId: child.pid,
461
+ root: true,
462
+ });
463
+ if (closing) return;
464
+ admitted = true;
465
+ openGate();
466
+ })().catch((error) => {
467
+ console.error(error);
468
+ void close().catch((failure) => console.error(failure));
469
+ });
470
+ return child;
471
+ }
472
+
473
+ export async function closeScopedProcess(child: ChildProcess | null) {
474
+ if (!child) return;
475
+ const close = processScopes.get(child);
476
+ if (!close)
477
+ throw new Error(
478
+ "process_scope_unavailable: Process has no registered cleanup owner.",
479
+ );
480
+ await close();
481
+ }
@@ -0,0 +1,10 @@
1
+ export function nodeProcessEnvironment(
2
+ allowedKeys: readonly string[],
3
+ environment: NodeJS.ProcessEnv = process.env,
4
+ ) {
5
+ return Object.fromEntries(
6
+ ["ELECTRON_RUN_AS_NODE", ...allowedKeys].flatMap((key) =>
7
+ environment[key] === undefined ? [] : [[key, environment[key]]],
8
+ ),
9
+ );
10
+ }