@air-jam/devtools 0.0.0-stage → 1.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (256) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +112 -2
  3. package/dist/chunk-2O67AXCU.js +470 -0
  4. package/dist/chunk-2O67AXCU.js.map +1 -0
  5. package/dist/chunk-AO3ZDXF6.js +142 -0
  6. package/dist/chunk-AO3ZDXF6.js.map +1 -0
  7. package/dist/chunk-ART5TEYT.js +472 -0
  8. package/dist/chunk-ART5TEYT.js.map +1 -0
  9. package/dist/chunk-ASC2CK2R.js +77 -0
  10. package/dist/chunk-ASC2CK2R.js.map +1 -0
  11. package/dist/chunk-E3UZZGAV.js +50 -0
  12. package/dist/chunk-E3UZZGAV.js.map +1 -0
  13. package/dist/chunk-EJTE7UKX.js +64 -0
  14. package/dist/chunk-EJTE7UKX.js.map +1 -0
  15. package/dist/chunk-ESFKNN75.js +110 -0
  16. package/dist/chunk-ESFKNN75.js.map +1 -0
  17. package/dist/chunk-EU7A6PXW.js +1339 -0
  18. package/dist/chunk-EU7A6PXW.js.map +1 -0
  19. package/dist/chunk-FN7E6EA7.js +549 -0
  20. package/dist/chunk-FN7E6EA7.js.map +1 -0
  21. package/dist/chunk-GDFAWHGA.js +190 -0
  22. package/dist/chunk-GDFAWHGA.js.map +1 -0
  23. package/dist/chunk-HZUGBH4Y.js +347 -0
  24. package/dist/chunk-HZUGBH4Y.js.map +1 -0
  25. package/dist/chunk-ITKAOEGX.js +93 -0
  26. package/dist/chunk-ITKAOEGX.js.map +1 -0
  27. package/dist/chunk-JBCUTWRI.js +897 -0
  28. package/dist/chunk-JBCUTWRI.js.map +1 -0
  29. package/dist/chunk-JSI5S4WP.js +1174 -0
  30. package/dist/chunk-JSI5S4WP.js.map +1 -0
  31. package/dist/chunk-L4D675BG.js +97 -0
  32. package/dist/chunk-L4D675BG.js.map +1 -0
  33. package/dist/chunk-M6CJ7GQC.js +133 -0
  34. package/dist/chunk-M6CJ7GQC.js.map +1 -0
  35. package/dist/chunk-MEIMOSZC.js +749 -0
  36. package/dist/chunk-MEIMOSZC.js.map +1 -0
  37. package/dist/chunk-O3XG3FNL.js +1014 -0
  38. package/dist/chunk-O3XG3FNL.js.map +1 -0
  39. package/dist/chunk-OM6SCJ7H.js +18 -0
  40. package/dist/chunk-OM6SCJ7H.js.map +1 -0
  41. package/dist/chunk-PKD4WVX5.js +63 -0
  42. package/dist/chunk-PKD4WVX5.js.map +1 -0
  43. package/dist/chunk-PMBLXGFM.js +3384 -0
  44. package/dist/chunk-PMBLXGFM.js.map +1 -0
  45. package/dist/chunk-PMNE5GIN.js +279 -0
  46. package/dist/chunk-PMNE5GIN.js.map +1 -0
  47. package/dist/chunk-QAWI64VR.js +148 -0
  48. package/dist/chunk-QAWI64VR.js.map +1 -0
  49. package/dist/chunk-QGADSPHZ.js +449 -0
  50. package/dist/chunk-QGADSPHZ.js.map +1 -0
  51. package/dist/chunk-SPYN66UV.js +338 -0
  52. package/dist/chunk-SPYN66UV.js.map +1 -0
  53. package/dist/context.d.ts +19 -0
  54. package/dist/context.js +10 -0
  55. package/dist/context.js.map +1 -0
  56. package/dist/controller.d.ts +67 -0
  57. package/dist/controller.js +40 -0
  58. package/dist/controller.js.map +1 -0
  59. package/dist/dependencies.d.ts +44 -0
  60. package/dist/dependencies.js +10 -0
  61. package/dist/dependencies.js.map +1 -0
  62. package/dist/dev.d.ts +21 -0
  63. package/dist/dev.js +19 -0
  64. package/dist/dev.js.map +1 -0
  65. package/dist/game-builds.d.ts +200 -0
  66. package/dist/game-builds.js +16 -0
  67. package/dist/game-builds.js.map +1 -0
  68. package/dist/game-run-watch-CEd_SpAT.d.ts +84 -0
  69. package/dist/game-runs.d.ts +1452 -0
  70. package/dist/game-runs.js +76 -0
  71. package/dist/game-runs.js.map +1 -0
  72. package/dist/game-session-broker-CUvORfMd.d.ts +439 -0
  73. package/dist/game-session-broker.d.ts +4 -0
  74. package/dist/game-session-broker.js +40 -0
  75. package/dist/game-session-broker.js.map +1 -0
  76. package/dist/game-session.d.ts +3934 -0
  77. package/dist/game-session.js +195 -0
  78. package/dist/game-session.js.map +1 -0
  79. package/dist/game-settings.d.ts +16 -0
  80. package/dist/game-settings.js +237 -0
  81. package/dist/game-settings.js.map +1 -0
  82. package/dist/games.d.ts +28 -0
  83. package/dist/games.js +16 -0
  84. package/dist/games.js.map +1 -0
  85. package/dist/harness/visual.d.ts +204 -0
  86. package/dist/harness/visual.js +46 -0
  87. package/dist/harness/visual.js.map +1 -0
  88. package/dist/logs.d.ts +15 -0
  89. package/dist/logs.js +57 -0
  90. package/dist/logs.js.map +1 -0
  91. package/dist/managed-process-scope-BicYi_t9.d.ts +3 -0
  92. package/dist/mcp-config.d.ts +63 -0
  93. package/dist/mcp-config.js +191 -0
  94. package/dist/mcp-config.js.map +1 -0
  95. package/dist/platform-auth.d.ts +9 -0
  96. package/dist/platform-auth.js +45 -0
  97. package/dist/platform-auth.js.map +1 -0
  98. package/dist/platform-game-analytics.d.ts +51 -0
  99. package/dist/platform-game-analytics.js +49 -0
  100. package/dist/platform-game-analytics.js.map +1 -0
  101. package/dist/platform-game-app-id.d.ts +46 -0
  102. package/dist/platform-game-app-id.js +93 -0
  103. package/dist/platform-game-app-id.js.map +1 -0
  104. package/dist/platform-game-media.d.ts +347 -0
  105. package/dist/platform-game-media.js +168 -0
  106. package/dist/platform-game-media.js.map +1 -0
  107. package/dist/platform-games.d.ts +87 -0
  108. package/dist/platform-games.js +183 -0
  109. package/dist/platform-games.js.map +1 -0
  110. package/dist/quality.d.ts +16 -0
  111. package/dist/quality.js +62 -0
  112. package/dist/quality.js.map +1 -0
  113. package/dist/release.d.ts +1304 -0
  114. package/dist/release.js +34 -0
  115. package/dist/release.js.map +1 -0
  116. package/dist/rooms-check.d.ts +90 -0
  117. package/dist/rooms-check.js +717 -0
  118. package/dist/rooms-check.js.map +1 -0
  119. package/dist/source-tree-contract.d.ts +16 -0
  120. package/dist/source-tree-contract.js +13 -0
  121. package/dist/source-tree-contract.js.map +1 -0
  122. package/dist/testing.d.ts +464 -0
  123. package/dist/testing.js +27 -0
  124. package/dist/testing.js.map +1 -0
  125. package/dist/tooling/describe-game.d.ts +2 -0
  126. package/dist/tooling/describe-game.js +54 -0
  127. package/dist/tooling/describe-game.js.map +1 -0
  128. package/dist/tooling/game-session-broker.d.ts +2 -0
  129. package/dist/tooling/game-session-broker.js +28 -0
  130. package/dist/tooling/game-session-broker.js.map +1 -0
  131. package/dist/tooling/hold-runtime-host.d.ts +2 -0
  132. package/dist/tooling/hold-runtime-host.js +931 -0
  133. package/dist/tooling/hold-runtime-host.js.map +1 -0
  134. package/dist/tooling/list-visual-scenarios.d.ts +2 -0
  135. package/dist/tooling/list-visual-scenarios.js +25 -0
  136. package/dist/tooling/list-visual-scenarios.js.map +1 -0
  137. package/dist/tooling/managed-dev-supervisor.d.ts +2 -0
  138. package/dist/tooling/managed-dev-supervisor.js +51 -0
  139. package/dist/tooling/managed-dev-supervisor.js.map +1 -0
  140. package/dist/tooling/process-scope-bootstrap.mjs +24 -0
  141. package/dist/tooling/process-scope-guard.d.ts +2 -0
  142. package/dist/tooling/process-scope-guard.js +388 -0
  143. package/dist/tooling/process-scope-guard.js.map +1 -0
  144. package/dist/tooling/process-scope-windows.ps1 +148 -0
  145. package/dist/tooling/rooms-check-device.d.ts +2 -0
  146. package/dist/tooling/rooms-check-device.js +498 -0
  147. package/dist/tooling/rooms-check-device.js.map +1 -0
  148. package/dist/tooling/run-headless-room.d.ts +2 -0
  149. package/dist/tooling/run-headless-room.js +287 -0
  150. package/dist/tooling/run-headless-room.js.map +1 -0
  151. package/dist/tooling/run-test-profile.d.ts +2 -0
  152. package/dist/tooling/run-test-profile.js +181 -0
  153. package/dist/tooling/run-test-profile.js.map +1 -0
  154. package/dist/tooling/run-visual-capture.d.ts +2 -0
  155. package/dist/tooling/run-visual-capture.js +203 -0
  156. package/dist/tooling/run-visual-capture.js.map +1 -0
  157. package/dist/tooling/seal-game-build.d.ts +2 -0
  158. package/dist/tooling/seal-game-build.js +120 -0
  159. package/dist/tooling/seal-game-build.js.map +1 -0
  160. package/dist/types-CdYrgrG_.d.ts +1036 -0
  161. package/dist/types-DyRD-ym1.d.ts +141 -0
  162. package/dist/visual.d.ts +21 -0
  163. package/dist/visual.js +219 -0
  164. package/dist/visual.js.map +1 -0
  165. package/package.json +150 -3
  166. package/src/bounded-response.ts +28 -0
  167. package/src/built-game-runtime.ts +152 -0
  168. package/src/commands.ts +40 -0
  169. package/src/context.ts +218 -0
  170. package/src/controller-protocol.ts +22 -0
  171. package/src/controller.ts +1526 -0
  172. package/src/current-room-host.ts +166 -0
  173. package/src/decision-provider.ts +102 -0
  174. package/src/dependencies.ts +176 -0
  175. package/src/dependency-install-contract.ts +12 -0
  176. package/src/dev.ts +995 -0
  177. package/src/fs-utils.ts +93 -0
  178. package/src/game-action-observation.ts +106 -0
  179. package/src/game-build-protocol.ts +72 -0
  180. package/src/game-build.ts +483 -0
  181. package/src/game-run-owner.ts +2358 -0
  182. package/src/game-run-protocol.ts +448 -0
  183. package/src/game-run-record.ts +92 -0
  184. package/src/game-run-replay.ts +95 -0
  185. package/src/game-run-watch.ts +155 -0
  186. package/src/game-session-broker.ts +793 -0
  187. package/src/game-session-operations.ts +61 -0
  188. package/src/game-session-protocol.ts +180 -0
  189. package/src/game-session-runtime.ts +861 -0
  190. package/src/game-session.ts +206 -0
  191. package/src/game-settings.ts +295 -0
  192. package/src/games.ts +262 -0
  193. package/src/harness/visual/browser.ts +100 -0
  194. package/src/harness/visual/controller-observation.ts +181 -0
  195. package/src/harness/visual/prefab-contract.ts +29 -0
  196. package/src/harness/visual/prefab-runner.ts +178 -0
  197. package/src/harness/visual/runner.ts +549 -0
  198. package/src/harness/visual/runtime-controller-observations.ts +151 -0
  199. package/src/harness/visual/scenario-contract.ts +8 -0
  200. package/src/harness/visual/scenario-helpers.ts +67 -0
  201. package/src/harness/visual/screencast.ts +155 -0
  202. package/src/harness/visual/session.ts +400 -0
  203. package/src/harness/visual/types.ts +184 -0
  204. package/src/harness/visual.ts +7 -0
  205. package/src/headless-room-protocol.ts +112 -0
  206. package/src/headless-room.ts +222 -0
  207. package/src/helper-channel.ts +229 -0
  208. package/src/helper-scripts.ts +69 -0
  209. package/src/installed-dependencies.ts +74 -0
  210. package/src/logs.ts +67 -0
  211. package/src/managed-process-scope.ts +481 -0
  212. package/src/mcp-config.ts +262 -0
  213. package/src/node-process-environment.ts +10 -0
  214. package/src/platform-auth.ts +594 -0
  215. package/src/platform-game-analytics.ts +50 -0
  216. package/src/platform-game-app-id.ts +99 -0
  217. package/src/platform-game-media.ts +209 -0
  218. package/src/platform-games.ts +217 -0
  219. package/src/policy-artifact-contract.ts +52 -0
  220. package/src/policy-artifacts.ts +134 -0
  221. package/src/process-scope-admission.ts +50 -0
  222. package/src/process-scope-protocol.ts +66 -0
  223. package/src/process-scope.ts +327 -0
  224. package/src/quality.ts +82 -0
  225. package/src/release.ts +1683 -0
  226. package/src/rooms-check-fleet.ts +194 -0
  227. package/src/rooms-check-link.ts +138 -0
  228. package/src/rooms-check-protocol.ts +244 -0
  229. package/src/rooms-check.ts +797 -0
  230. package/src/runtime-owner-protocol.ts +218 -0
  231. package/src/source-tree-contract.ts +70 -0
  232. package/src/source-tree.ts +84 -0
  233. package/src/test-profile-process.ts +153 -0
  234. package/src/test-profile-protocol.ts +116 -0
  235. package/src/testing.ts +430 -0
  236. package/src/tooling/declaration-hook.ts +52 -0
  237. package/src/tooling/describe-game.ts +49 -0
  238. package/src/tooling/game-session-broker.ts +7 -0
  239. package/src/tooling/hold-runtime-host.ts +441 -0
  240. package/src/tooling/list-visual-scenarios.ts +21 -0
  241. package/src/tooling/load-game.ts +79 -0
  242. package/src/tooling/managed-dev-supervisor.ts +71 -0
  243. package/src/tooling/process-scope-bootstrap.mjs +24 -0
  244. package/src/tooling/process-scope-guard.ts +213 -0
  245. package/src/tooling/process-scope-windows.ps1 +148 -0
  246. package/src/tooling/rooms-check-device.ts +493 -0
  247. package/src/tooling/run-headless-room.ts +326 -0
  248. package/src/tooling/run-test-profile.ts +190 -0
  249. package/src/tooling/run-visual-capture.ts +231 -0
  250. package/src/tooling/runtime-owner-actions.ts +65 -0
  251. package/src/tooling/seal-game-build.ts +118 -0
  252. package/src/tooling/visual-pack.ts +11 -0
  253. package/src/types.ts +928 -0
  254. package/src/visual.ts +296 -0
  255. package/src/windows-process-scopes.ts +189 -0
  256. package/src/workspace-contract.ts +32 -0
@@ -0,0 +1,222 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import type { GameRunClock } from "./game-run-owner.js";
3
+ import type { HostRequester } from "./game-session-runtime.js";
4
+ import {
5
+ HEADLESS_ROOM_IPC_MAX_BYTES,
6
+ HEADLESS_ROOM_MAX_ADVANCE_MS,
7
+ headlessRoomRequestSchema,
8
+ headlessRoomResponseSchema,
9
+ type HeadlessRoomRequest,
10
+ type HeadlessRoomResponse,
11
+ } from "./headless-room-protocol.js";
12
+ import { startHelperChannel } from "./helper-channel.js";
13
+ import {
14
+ closeAfterProcessFailure,
15
+ type ProcessScopeObserver,
16
+ } from "./managed-process-scope.js";
17
+
18
+ const REQUEST_TIMEOUT_MS = 5_000;
19
+ /** A replay plays the whole recorded match before it answers. */
20
+ const REPLAY_TIMEOUT_MS = 120_000;
21
+
22
+ export type HeadlessRoom = {
23
+ gameId: string | null;
24
+ roomId: string;
25
+ controllerJoinUrl: string;
26
+ /** Reaches the room's host directly, as an owned host. */
27
+ requestHost: HostRequester;
28
+ /** Game time: waiting advances the game rather than the wall clock. */
29
+ clock: GameRunClock;
30
+ /**
31
+ * Writes everything that reached the game so far, by step, for replays;
32
+ * null when the game declares no simulation to replay.
33
+ */
34
+ saveInputLog:
35
+ | ((path: string) => Promise<{
36
+ sha256: string;
37
+ ticks: number;
38
+ stepMs: number;
39
+ entries: number;
40
+ full: boolean;
41
+ }>)
42
+ | null;
43
+ stop: () => Promise<void>;
44
+ };
45
+
46
+ /**
47
+ * Opens a game's room headless in its own process: no page, no drawing, and
48
+ * a clock that moves only when the run waits on it.
49
+ */
50
+ export async function startHeadlessRoom({
51
+ rootDir,
52
+ toolingRootDir,
53
+ configPath,
54
+ seed,
55
+ settings,
56
+ logPath,
57
+ onScope,
58
+ startupSignal,
59
+ }: {
60
+ rootDir: string;
61
+ toolingRootDir?: string;
62
+ configPath: string;
63
+ seed: number;
64
+ settings?: Record<string, string | number | boolean>;
65
+ logPath: string;
66
+ onScope?: ProcessScopeObserver;
67
+ startupSignal?: AbortSignal;
68
+ }): Promise<HeadlessRoom> {
69
+ const channel = await startHelperChannel({
70
+ name: "room",
71
+ helper: "run-headless-room.ts",
72
+ rootDir,
73
+ toolingRootDir,
74
+ onScope,
75
+ startupSignal,
76
+ logPath,
77
+ maxBytes: HEADLESS_ROOM_IPC_MAX_BYTES,
78
+ requestSchema: headlessRoomRequestSchema,
79
+ responseSchema: headlessRoomResponseSchema,
80
+ });
81
+ // One request at a time reaches the room, in the order the run sent them.
82
+ let queue: Promise<unknown> = Promise.resolve();
83
+ const request = <TKind extends HeadlessRoomResponse["kind"]>(
84
+ input: HeadlessRoomRequest,
85
+ expected: TKind,
86
+ timeoutMs = REQUEST_TIMEOUT_MS,
87
+ ) => {
88
+ const result = queue.then(async () => {
89
+ const response = await channel.request(input, timeoutMs);
90
+ if (response.kind === "error") throw new Error(response.message);
91
+ if (response.kind !== expected)
92
+ throw new Error(`room_protocol: Expected ${expected}.`);
93
+ return response as Extract<HeadlessRoomResponse, { kind: TKind }>;
94
+ });
95
+ queue = result.catch(() => undefined);
96
+ return result;
97
+ };
98
+ try {
99
+ const opened = await request(
100
+ { kind: "initialize", id: randomUUID(), configPath, seed, settings },
101
+ "initialized",
102
+ 10_000,
103
+ );
104
+ let nowMs = opened.nowMs;
105
+ return {
106
+ gameId: opened.gameId,
107
+ roomId: opened.roomId,
108
+ controllerJoinUrl: opened.controllerJoinUrl,
109
+ requestHost: async (hostRequest, timeoutMs, signal) => {
110
+ signal?.throwIfAborted();
111
+ const answered = await request(
112
+ { kind: "agent", id: randomUUID(), request: hostRequest },
113
+ "agent",
114
+ timeoutMs,
115
+ );
116
+ return answered.response;
117
+ },
118
+ clock: {
119
+ now: () => nowMs,
120
+ wait: async (ms, signal) => {
121
+ let remaining = ms;
122
+ while (remaining > 0) {
123
+ signal?.throwIfAborted();
124
+ const step = Math.min(remaining, HEADLESS_ROOM_MAX_ADVANCE_MS);
125
+ nowMs = (
126
+ await request(
127
+ { kind: "advance", id: randomUUID(), ms: step },
128
+ "advanced",
129
+ )
130
+ ).nowMs;
131
+ remaining -= step;
132
+ }
133
+ },
134
+ },
135
+ saveInputLog: opened.recordsInputLog
136
+ ? async (logPath) => {
137
+ const { sha256, ticks, stepMs, entries, full } = await request(
138
+ { kind: "saveInputLog", id: randomUUID(), path: logPath },
139
+ "savedInputLog",
140
+ );
141
+ return { sha256, ticks, stepMs, entries, full };
142
+ }
143
+ : null,
144
+ stop: channel.stop,
145
+ };
146
+ } catch (error) {
147
+ return closeAfterProcessFailure(channel.stop, error);
148
+ } finally {
149
+ channel.started();
150
+ }
151
+ }
152
+
153
+ /**
154
+ * Plays a recorded input log on a fresh copy of the game in its own process,
155
+ * with no server or page, and keeps the replayed host for questions such as
156
+ * a final observation.
157
+ */
158
+ export async function replayInputLog({
159
+ rootDir,
160
+ toolingRootDir,
161
+ configPath,
162
+ inputLogPath,
163
+ logPath,
164
+ }: {
165
+ rootDir: string;
166
+ toolingRootDir?: string;
167
+ configPath: string;
168
+ inputLogPath: string;
169
+ logPath: string;
170
+ }): Promise<{
171
+ gameId: string | null;
172
+ roomId: string;
173
+ ticks: number;
174
+ requestHost: HostRequester;
175
+ stop: () => Promise<void>;
176
+ }> {
177
+ const channel = await startHelperChannel({
178
+ name: "replay",
179
+ helper: "run-headless-room.ts",
180
+ rootDir,
181
+ toolingRootDir,
182
+ logPath,
183
+ maxBytes: HEADLESS_ROOM_IPC_MAX_BYTES,
184
+ requestSchema: headlessRoomRequestSchema,
185
+ responseSchema: headlessRoomResponseSchema,
186
+ });
187
+ try {
188
+ const replayed = await channel.request(
189
+ {
190
+ kind: "replay",
191
+ id: randomUUID(),
192
+ configPath,
193
+ logPath: inputLogPath,
194
+ },
195
+ REPLAY_TIMEOUT_MS,
196
+ );
197
+ if (replayed.kind === "error") throw new Error(replayed.message);
198
+ if (replayed.kind !== "replayed")
199
+ throw new Error("room_protocol: Expected replayed.");
200
+ return {
201
+ gameId: replayed.gameId,
202
+ roomId: replayed.roomId,
203
+ ticks: replayed.ticks,
204
+ requestHost: async (hostRequest, timeoutMs, signal) => {
205
+ signal?.throwIfAborted();
206
+ const answered = await channel.request(
207
+ { kind: "agent", id: randomUUID(), request: hostRequest },
208
+ timeoutMs,
209
+ );
210
+ if (answered.kind === "error") throw new Error(answered.message);
211
+ if (answered.kind !== "agent")
212
+ throw new Error("room_protocol: Expected agent.");
213
+ return answered.response;
214
+ },
215
+ stop: channel.stop,
216
+ };
217
+ } catch (error) {
218
+ return closeAfterProcessFailure(channel.stop, error);
219
+ } finally {
220
+ channel.started();
221
+ }
222
+ }
@@ -0,0 +1,229 @@
1
+ import { closeSync, openSync, writeSync } from "node:fs";
2
+ import type { z } from "zod";
3
+ import {
4
+ resolveDevtoolsHelperArgs,
5
+ resolveDevtoolsHelperScript,
6
+ resolveProjectDevtoolsHelperScript,
7
+ } from "./helper-scripts.js";
8
+ import {
9
+ closeAfterProcessFailure,
10
+ closeScopedProcess,
11
+ spawnScopedProcess,
12
+ type ProcessScopeObserver,
13
+ } from "./managed-process-scope.js";
14
+ import { nodeProcessEnvironment } from "./node-process-environment.js";
15
+ import { processScopeAdmissionSchema } from "./process-scope-protocol.js";
16
+
17
+ const environmentKeys = [
18
+ "PATH",
19
+ "HOME",
20
+ "TMPDIR",
21
+ "TEMP",
22
+ "TMP",
23
+ "NODE_EXTRA_CA_CERTS",
24
+ "HTTP_PROXY",
25
+ "HTTPS_PROXY",
26
+ "ALL_PROXY",
27
+ "NO_PROXY",
28
+ "http_proxy",
29
+ "https_proxy",
30
+ "all_proxy",
31
+ "no_proxy",
32
+ ];
33
+
34
+ const LOG_BYTES = 1_000_000;
35
+ const STARTUP_MS = 10_000;
36
+
37
+ /**
38
+ * One helper process that runs game code apart from the owner, answering one
39
+ * request at a time over IPC. Its errors start with `<name>_`, such as
40
+ * `policy_timeout`, so callers can tell them apart.
41
+ */
42
+ export async function startHelperChannel<
43
+ TRequest extends { id: string },
44
+ TResponse extends { kind: string; id?: string },
45
+ >({
46
+ name,
47
+ helper,
48
+ rootDir,
49
+ toolingRootDir,
50
+ onScope,
51
+ startupSignal,
52
+ logPath,
53
+ maxBytes,
54
+ requestSchema,
55
+ responseSchema,
56
+ }: {
57
+ name: string;
58
+ helper: string;
59
+ rootDir: string;
60
+ toolingRootDir?: string;
61
+ onScope?: ProcessScopeObserver;
62
+ startupSignal?: AbortSignal;
63
+ logPath: string;
64
+ maxBytes: number;
65
+ requestSchema: z.ZodType<TRequest>;
66
+ responseSchema: z.ZodType<TResponse>;
67
+ }): Promise<{
68
+ request: (input: TRequest, timeoutMs: number) => Promise<TResponse>;
69
+ busy: () => boolean;
70
+ /** Ends the startup signal's hold once the caller has initialized the helper. */
71
+ started: () => void;
72
+ stop: () => Promise<void>;
73
+ }> {
74
+ startupSignal?.throwIfAborted();
75
+ const script = toolingRootDir
76
+ ? resolveProjectDevtoolsHelperScript(toolingRootDir, helper)
77
+ : resolveDevtoolsHelperScript(helper);
78
+ const logDescriptor = openSync(logPath, "w", 0o600);
79
+ const child = await spawnScopedProcess(resolveDevtoolsHelperArgs(script), {
80
+ cwd: rootDir,
81
+ onScope,
82
+ startupSignal,
83
+ env: nodeProcessEnvironment(environmentKeys),
84
+ }).catch((error) => {
85
+ closeSync(logDescriptor);
86
+ if (startupSignal?.aborted)
87
+ throw new Error(`${name}_stopped`, { cause: error });
88
+ throw error;
89
+ });
90
+ let failure: Error | undefined;
91
+ let ready = false;
92
+ let pending:
93
+ | {
94
+ id: string;
95
+ resolve: (value: TResponse) => void;
96
+ reject: (error: Error) => void;
97
+ timer: ReturnType<typeof setTimeout>;
98
+ expired: boolean;
99
+ }
100
+ | undefined;
101
+ let stopping: Promise<void> | undefined;
102
+ let resolveReady: () => void;
103
+ let rejectReady: (error: Error) => void;
104
+ const boot = new Promise<void>((resolve, reject) => {
105
+ resolveReady = resolve;
106
+ rejectReady = reject;
107
+ });
108
+ const fail = (error: Error) => {
109
+ failure ??= error;
110
+ rejectReady(error);
111
+ if (pending) {
112
+ clearTimeout(pending.timer);
113
+ pending.reject(error);
114
+ pending = undefined;
115
+ }
116
+ };
117
+ child.on("error", fail);
118
+ child.once("exit", () => {
119
+ fail(new Error(`${name}_exited: The ${name} process is unavailable.`));
120
+ });
121
+ let logBytes = 0;
122
+ const log = (chunk: Buffer) => {
123
+ const remaining = LOG_BYTES - logBytes;
124
+ if (remaining > 0) {
125
+ const bounded = chunk.subarray(0, remaining);
126
+ try {
127
+ let offset = 0;
128
+ while (offset < bounded.length)
129
+ offset += writeSync(logDescriptor, bounded.subarray(offset));
130
+ } catch (error) {
131
+ fail(error instanceof Error ? error : new Error(String(error)));
132
+ child.kill("SIGKILL");
133
+ }
134
+ }
135
+ logBytes += chunk.length;
136
+ if (logBytes > LOG_BYTES) {
137
+ fail(
138
+ new Error(
139
+ `${name}_log_limit: The ${name} process exceeded its 1 MB diagnostic log budget.`,
140
+ ),
141
+ );
142
+ child.kill("SIGKILL");
143
+ }
144
+ };
145
+ child.stdout?.on("data", log);
146
+ child.stderr?.on("data", log);
147
+ child.on("message", (message: unknown) => {
148
+ if (message === 0) return;
149
+ if (processScopeAdmissionSchema.safeParse(message).success) return;
150
+ try {
151
+ if (Buffer.byteLength(JSON.stringify(message)) > maxBytes)
152
+ throw new Error(`${name}_protocol: Oversized response.`);
153
+ const result = responseSchema.parse(message);
154
+ if (result.kind === "ready") {
155
+ if (ready) throw new Error(`${name}_protocol: Duplicate startup.`);
156
+ ready = true;
157
+ resolveReady();
158
+ return;
159
+ }
160
+ if (!pending || result.id !== pending.id)
161
+ throw new Error(`${name}_protocol: Unexpected response ID.`);
162
+ const request = pending;
163
+ pending = undefined;
164
+ clearTimeout(request.timer);
165
+ if (!request.expired) request.resolve(result);
166
+ } catch (error) {
167
+ fail(error instanceof Error ? error : new Error(String(error)));
168
+ child.kill("SIGKILL");
169
+ }
170
+ });
171
+ const request = (input: TRequest, timeoutMs: number) => {
172
+ if (failure) return Promise.reject(failure);
173
+ if (pending)
174
+ return Promise.reject(
175
+ new Error(`${name}_busy: The previous request has not returned.`),
176
+ );
177
+ const parsed = requestSchema.parse(input);
178
+ if (Buffer.byteLength(JSON.stringify(parsed)) > maxBytes)
179
+ return Promise.reject(
180
+ new Error(`${name}_protocol: Request exceeds its byte budget.`),
181
+ );
182
+ return new Promise<TResponse>((resolve, reject) => {
183
+ const timer = setTimeout(() => {
184
+ if (pending?.id !== parsed.id) return;
185
+ pending.expired = true;
186
+ reject(new Error(`${name}_timeout: Request exceeded its deadline.`));
187
+ }, timeoutMs);
188
+ pending = { id: parsed.id, resolve, reject, timer, expired: false };
189
+ child.send(parsed, (error) => {
190
+ if (error) fail(error);
191
+ });
192
+ });
193
+ };
194
+ const stop = () =>
195
+ (stopping ??= (async () => {
196
+ startupSignal?.removeEventListener("abort", aborted);
197
+ fail(new Error(`${name}_stopped`));
198
+ try {
199
+ await closeScopedProcess(child);
200
+ } finally {
201
+ child.stdout?.destroy();
202
+ child.stderr?.destroy();
203
+ closeSync(logDescriptor);
204
+ }
205
+ })());
206
+ const aborted = () => {
207
+ void stop().catch(() => undefined);
208
+ };
209
+ startupSignal?.addEventListener("abort", aborted, { once: true });
210
+ const bootTimeout = setTimeout(
211
+ () => fail(new Error(`${name}_startup_timeout`)),
212
+ STARTUP_MS,
213
+ );
214
+ try {
215
+ if (startupSignal?.aborted) aborted();
216
+ await boot;
217
+ } catch (error) {
218
+ startupSignal?.removeEventListener("abort", aborted);
219
+ return closeAfterProcessFailure(stop, error);
220
+ } finally {
221
+ clearTimeout(bootTimeout);
222
+ }
223
+ return {
224
+ request,
225
+ busy: () => pending !== undefined,
226
+ started: () => startupSignal?.removeEventListener("abort", aborted),
227
+ stop,
228
+ };
229
+ }
@@ -0,0 +1,69 @@
1
+ import { existsSync } from "node:fs";
2
+ import { createRequire } from "node:module";
3
+ import path from "node:path";
4
+ import { fileURLToPath, pathToFileURL } from "node:url";
5
+
6
+ const moduleDir = path.dirname(fileURLToPath(import.meta.url));
7
+
8
+ export const resolveDevtoolsHelperScript = (fileName: string): string => {
9
+ const builtHelperPath = path.resolve(
10
+ moduleDir,
11
+ "tooling",
12
+ fileName.replace(/\.ts$/, ".js"),
13
+ );
14
+ if (existsSync(builtHelperPath)) {
15
+ return builtHelperPath;
16
+ }
17
+
18
+ const sourceHelperPath = path.resolve(
19
+ moduleDir,
20
+ "..",
21
+ "src",
22
+ "tooling",
23
+ fileName,
24
+ );
25
+ if (existsSync(sourceHelperPath)) {
26
+ return sourceHelperPath;
27
+ }
28
+
29
+ throw new Error(
30
+ `Air Jam helper script is missing from this installation: ${fileName}`,
31
+ );
32
+ };
33
+
34
+ const typescriptExtensions = new Set([".ts", ".tsx", ".mts", ".cts"]);
35
+ const projectTypescriptLoaderHelpers = new Set([
36
+ "list-visual-scenarios",
37
+ "run-visual-capture",
38
+ "run-headless-room",
39
+ ]);
40
+
41
+ export const resolveDevtoolsHelperArgs = (helperPath: string): string[] =>
42
+ typescriptExtensions.has(path.extname(helperPath)) ||
43
+ projectTypescriptLoaderHelpers.has(
44
+ path.basename(helperPath, path.extname(helperPath)),
45
+ )
46
+ ? [
47
+ "--import",
48
+ pathToFileURL(createRequire(helperPath).resolve("tsx")).href,
49
+ helperPath,
50
+ ]
51
+ : [helperPath];
52
+
53
+ export function resolveProjectDevtoolsHelperScript(
54
+ projectDir: string,
55
+ fileName: string,
56
+ ) {
57
+ const projectRequire = createRequire(path.join(projectDir, "package.json"));
58
+ const manifest = projectRequire.resolve("@air-jam/devtools/package.json");
59
+ const helper = path.join(
60
+ path.dirname(manifest),
61
+ "dist/tooling",
62
+ fileName.replace(/\.ts$/, ".js"),
63
+ );
64
+ if (!existsSync(helper))
65
+ throw new Error(
66
+ `The pinned dependency graph is missing its runtime helper: ${fileName}`,
67
+ );
68
+ return helper;
69
+ }
@@ -0,0 +1,74 @@
1
+ import { createHash } from "node:crypto";
2
+ import { lstat, readFile, readdir, readlink, realpath } from "node:fs/promises";
3
+ import path from "node:path";
4
+
5
+ /** Hash installed code, including postinstall output; mutable tool caches are not dependencies. */
6
+ export async function inspectInstalledDependencies(
7
+ rootDir: string,
8
+ liveRoot: string,
9
+ ) {
10
+ const directory = path.join(rootDir, "node_modules"),
11
+ hash = createHash("sha256");
12
+ const excluded = new Set([
13
+ ".cache",
14
+ ".vite",
15
+ ".vite-temp",
16
+ ".modules.yaml",
17
+ ".pnpm/lock.yaml",
18
+ ]);
19
+ const originalModules = path.join(liveRoot, "node_modules");
20
+ const inside = (filename: string) => {
21
+ const relative = path.relative(directory, filename);
22
+ return (
23
+ relative !== ".." &&
24
+ !relative.startsWith(`..${path.sep}`) &&
25
+ !path.isAbsolute(relative)
26
+ );
27
+ };
28
+ if (!inside(await realpath(directory)))
29
+ throw new Error(
30
+ "build_dependencies_external: Dependencies resolve outside the snapshot.",
31
+ );
32
+ async function walk(relative = "") {
33
+ for (const name of (await readdir(path.join(directory, relative))).sort()) {
34
+ const filename = relative ? `${relative}/${name}` : name;
35
+ if (excluded.has(filename)) continue;
36
+ const absolute = path.join(directory, filename),
37
+ stat = await lstat(absolute);
38
+ const kind = stat.isDirectory()
39
+ ? "directory"
40
+ : stat.isSymbolicLink()
41
+ ? "link"
42
+ : "file";
43
+ hash.update(JSON.stringify([filename, stat.mode & 511, kind]));
44
+ if (stat.isDirectory()) await walk(filename);
45
+ else if (stat.isSymbolicLink()) {
46
+ if (!inside(await realpath(absolute)))
47
+ throw new Error(
48
+ `build_dependencies_external: Dependency link escapes the snapshot: ${filename}`,
49
+ );
50
+ hash.update(await readlink(absolute));
51
+ } else if (stat.isFile()) {
52
+ const content = await readFile(absolute);
53
+ if (
54
+ relative === ".bin" &&
55
+ content.includes(Buffer.from(originalModules))
56
+ )
57
+ throw new Error(
58
+ `build_dependencies_external: A command shim points at the live checkout: ${filename}`,
59
+ );
60
+ hash.update(createHash("sha256").update(content).digest());
61
+ } else
62
+ throw new Error(
63
+ `build_dependencies_invalid: Unsupported installed entry: ${filename}`,
64
+ );
65
+ }
66
+ }
67
+ await walk();
68
+ return {
69
+ installedTreeHash: hash.digest("hex"),
70
+ installedLockfileHash: createHash("sha256")
71
+ .update(await readFile(path.join(directory, ".pnpm/lock.yaml")))
72
+ .digest("hex"),
73
+ };
74
+ }
package/src/logs.ts ADDED
@@ -0,0 +1,67 @@
1
+ import { runCommandResult } from "./commands.js";
2
+ import { detectProjectContext } from "./context.js";
3
+ import type { CommandResult, ReadDevLogsOptions } from "./types.js";
4
+
5
+ export type { CommandResult, ReadDevLogsOptions } from "./types.js";
6
+
7
+ const pushOption = (
8
+ args: string[],
9
+ name: string,
10
+ value: string | number | undefined,
11
+ ): void => {
12
+ if (value !== undefined && value !== "") {
13
+ args.push(`--${name}=${String(value)}`);
14
+ }
15
+ };
16
+
17
+ export const readDevLogs = async (
18
+ options: ReadDevLogsOptions = {},
19
+ ): Promise<CommandResult & { lines: string[] }> => {
20
+ const context = await detectProjectContext({ cwd: options.cwd });
21
+ const args = ["exec", "air-jam-server", "logs"];
22
+
23
+ pushOption(args, "view", options.view ?? "signal");
24
+ pushOption(args, "source", options.source);
25
+ pushOption(args, "trace", options.trace);
26
+ pushOption(args, "room", options.room);
27
+ pushOption(args, "controller", options.controller);
28
+ pushOption(args, "event", options.event);
29
+ pushOption(args, "process", options.process);
30
+ pushOption(args, "level", options.level);
31
+ pushOption(args, "runtime", options.runtime);
32
+ pushOption(args, "epoch", options.epoch);
33
+ pushOption(args, "console-category", options.consoleCategory);
34
+ pushOption(args, "file", options.file);
35
+
36
+ const result = runCommandResult({
37
+ command: "pnpm",
38
+ args,
39
+ cwd: context.rootDir,
40
+ });
41
+
42
+ const missingLogMessage = `${result.stderr}\n${result.stdout}`;
43
+ if (!result.ok && /Dev log file not found:/i.test(missingLogMessage)) {
44
+ const message =
45
+ "Air Jam dev logs are not ready yet. Start local dev with `pnpm run dev`, then retry logs after the server creates `.airjam/logs/dev-latest.ndjson`.";
46
+ return {
47
+ ...result,
48
+ exitCode: 0,
49
+ ok: true,
50
+ stdout: message,
51
+ stderr: "",
52
+ lines: [message],
53
+ };
54
+ }
55
+
56
+ const allLines = result.stdout.split(/\r?\n/).filter(Boolean);
57
+ const lines =
58
+ typeof options.tail === "number" && options.tail >= 0
59
+ ? allLines.slice(-options.tail)
60
+ : allLines;
61
+
62
+ return {
63
+ ...result,
64
+ stdout: lines.join("\n"),
65
+ lines,
66
+ };
67
+ };