@air-jam/devtools 0.0.0-stage → 0.9.3

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 (135) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +52 -2
  3. package/dist/agent.d.ts +15 -0
  4. package/dist/agent.js +19 -0
  5. package/dist/agent.js.map +1 -0
  6. package/dist/chunk-5YAARMW5.js +36 -0
  7. package/dist/chunk-5YAARMW5.js.map +1 -0
  8. package/dist/chunk-6WQODT37.js +1019 -0
  9. package/dist/chunk-6WQODT37.js.map +1 -0
  10. package/dist/chunk-CKFT2ZJE.js +801 -0
  11. package/dist/chunk-CKFT2ZJE.js.map +1 -0
  12. package/dist/chunk-ER3Q2C4G.js +358 -0
  13. package/dist/chunk-ER3Q2C4G.js.map +1 -0
  14. package/dist/chunk-GUEZP773.js +851 -0
  15. package/dist/chunk-GUEZP773.js.map +1 -0
  16. package/dist/chunk-HIDNI56E.js +33 -0
  17. package/dist/chunk-HIDNI56E.js.map +1 -0
  18. package/dist/chunk-QKXS5D35.js +43 -0
  19. package/dist/chunk-QKXS5D35.js.map +1 -0
  20. package/dist/chunk-S4LSCEVE.js +261 -0
  21. package/dist/chunk-S4LSCEVE.js.map +1 -0
  22. package/dist/chunk-VKMJO6VN.js +360 -0
  23. package/dist/chunk-VKMJO6VN.js.map +1 -0
  24. package/dist/chunk-WFUR3MXY.js +67 -0
  25. package/dist/chunk-WFUR3MXY.js.map +1 -0
  26. package/dist/chunk-XEMR7KUE.js +361 -0
  27. package/dist/chunk-XEMR7KUE.js.map +1 -0
  28. package/dist/chunk-ZLPD7FY5.js +191 -0
  29. package/dist/chunk-ZLPD7FY5.js.map +1 -0
  30. package/dist/context.d.ts +13 -0
  31. package/dist/context.js +9 -0
  32. package/dist/context.js.map +1 -0
  33. package/dist/controller.d.ts +41 -0
  34. package/dist/controller.js +30 -0
  35. package/dist/controller.js.map +1 -0
  36. package/dist/dev.d.ts +15 -0
  37. package/dist/dev.js +20 -0
  38. package/dist/dev.js.map +1 -0
  39. package/dist/game-session-broker.d.ts +57 -0
  40. package/dist/game-session-broker.js +235 -0
  41. package/dist/game-session-broker.js.map +1 -0
  42. package/dist/game-session.d.ts +13 -0
  43. package/dist/game-session.js +24 -0
  44. package/dist/game-session.js.map +1 -0
  45. package/dist/games.d.ts +21 -0
  46. package/dist/games.js +14 -0
  47. package/dist/games.js.map +1 -0
  48. package/dist/harness/visual.d.ts +321 -0
  49. package/dist/harness/visual.js +41 -0
  50. package/dist/harness/visual.js.map +1 -0
  51. package/dist/logs.d.ts +9 -0
  52. package/dist/logs.js +58 -0
  53. package/dist/logs.js.map +1 -0
  54. package/dist/mcp-config.d.ts +63 -0
  55. package/dist/mcp-config.js +190 -0
  56. package/dist/mcp-config.js.map +1 -0
  57. package/dist/platform-auth.d.ts +112 -0
  58. package/dist/platform-auth.js +37 -0
  59. package/dist/platform-auth.js.map +1 -0
  60. package/dist/platform-game-media.d.ts +309 -0
  61. package/dist/platform-game-media.js +168 -0
  62. package/dist/platform-game-media.js.map +1 -0
  63. package/dist/platform-games.d.ts +65 -0
  64. package/dist/platform-games.js +251 -0
  65. package/dist/platform-games.js.map +1 -0
  66. package/dist/quality.d.ts +10 -0
  67. package/dist/quality.js +63 -0
  68. package/dist/quality.js.map +1 -0
  69. package/dist/release.d.ts +1094 -0
  70. package/dist/release.js +1347 -0
  71. package/dist/release.js.map +1 -0
  72. package/dist/tooling/agent-contract.d.ts +2 -0
  73. package/dist/tooling/agent-contract.js +193 -0
  74. package/dist/tooling/agent-contract.js.map +1 -0
  75. package/dist/tooling/hold-runtime-host.d.ts +2 -0
  76. package/dist/tooling/hold-runtime-host.js +229 -0
  77. package/dist/tooling/hold-runtime-host.js.map +1 -0
  78. package/dist/tooling/inspect-airjam-agent.d.ts +2 -0
  79. package/dist/tooling/inspect-airjam-agent.js +37 -0
  80. package/dist/tooling/inspect-airjam-agent.js.map +1 -0
  81. package/dist/tooling/list-visual-scenarios.d.ts +2 -0
  82. package/dist/tooling/list-visual-scenarios.js +62 -0
  83. package/dist/tooling/list-visual-scenarios.js.map +1 -0
  84. package/dist/tooling/managed-dev-supervisor.d.ts +2 -0
  85. package/dist/tooling/managed-dev-supervisor.js +51 -0
  86. package/dist/tooling/managed-dev-supervisor.js.map +1 -0
  87. package/dist/tooling/run-visual-capture.d.ts +2 -0
  88. package/dist/tooling/run-visual-capture.js +167 -0
  89. package/dist/tooling/run-visual-capture.js.map +1 -0
  90. package/dist/types-C6NrHt88.d.ts +775 -0
  91. package/dist/visual.d.ts +15 -0
  92. package/dist/visual.js +263 -0
  93. package/dist/visual.js.map +1 -0
  94. package/package.json +113 -3
  95. package/src/agent.ts +380 -0
  96. package/src/commands.ts +40 -0
  97. package/src/context.ts +229 -0
  98. package/src/controller.ts +1376 -0
  99. package/src/dev.ts +999 -0
  100. package/src/fs-utils.ts +93 -0
  101. package/src/game-action-observation.ts +96 -0
  102. package/src/game-session-broker.ts +301 -0
  103. package/src/game-session.ts +459 -0
  104. package/src/games.ts +266 -0
  105. package/src/harness/visual/prefab-contract.ts +29 -0
  106. package/src/harness/visual/prefab-runner.ts +178 -0
  107. package/src/harness/visual/runner.ts +546 -0
  108. package/src/harness/visual/scenario-contract.ts +9 -0
  109. package/src/harness/visual/scenario-helpers.ts +63 -0
  110. package/src/harness/visual/session.ts +369 -0
  111. package/src/harness/visual/types.ts +181 -0
  112. package/src/harness/visual.ts +7 -0
  113. package/src/helper-scripts.ts +49 -0
  114. package/src/logs.ts +67 -0
  115. package/src/mcp-config.ts +262 -0
  116. package/src/platform-auth.ts +455 -0
  117. package/src/platform-game-media.ts +209 -0
  118. package/src/platform-games.ts +315 -0
  119. package/src/quality.ts +82 -0
  120. package/src/release.ts +1697 -0
  121. package/src/runtime-owner-protocol.ts +130 -0
  122. package/src/tooling/agent-contract.ts +232 -0
  123. package/src/tooling/agent-declaration.ts +36 -0
  124. package/src/tooling/airjam-agent-inspection.ts +45 -0
  125. package/src/tooling/airjam-agent.ts +118 -0
  126. package/src/tooling/hold-runtime-host.ts +224 -0
  127. package/src/tooling/inspect-airjam-agent.ts +20 -0
  128. package/src/tooling/list-visual-scenarios.ts +64 -0
  129. package/src/tooling/managed-dev-supervisor.ts +71 -0
  130. package/src/tooling/run-visual-capture.ts +217 -0
  131. package/src/tooling/runtime-owner-actions.ts +42 -0
  132. package/src/tooling/visual-pack.ts +46 -0
  133. package/src/types.ts +951 -0
  134. package/src/visual.ts +304 -0
  135. package/src/workspace-contract.ts +32 -0
package/src/dev.ts ADDED
@@ -0,0 +1,999 @@
1
+ import crossSpawn from "cross-spawn";
2
+ import { randomUUID } from "node:crypto";
3
+ import { closeSync, openSync } from "node:fs";
4
+ import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
5
+ import http from "node:http";
6
+ import https from "node:https";
7
+ import path from "node:path";
8
+ import { runCommandResult } from "./commands.js";
9
+ import { detectProjectContext } from "./context.js";
10
+ import { pathExists } from "./fs-utils.js";
11
+ import { inspectGame, listGames } from "./games.js";
12
+ import {
13
+ resolveDevtoolsHelperArgs,
14
+ resolveDevtoolsHelperScript,
15
+ } from "./helper-scripts.js";
16
+ import type {
17
+ AirJamDevMode,
18
+ AirJamDevStatus,
19
+ AirJamManagedDevProcess,
20
+ AirJamProjectContext,
21
+ AirJamRuntimeTopology,
22
+ AirJamSurfaceUrlSummary,
23
+ AirJamUnmanagedDevProcess,
24
+ GetDevStatusOptions,
25
+ GetTopologyOptions,
26
+ JsonObject,
27
+ ResetLocalDevOptions,
28
+ ResetLocalDevResult,
29
+ StartDevOptions,
30
+ StartDevResult,
31
+ StopDevOptions,
32
+ StopDevResult,
33
+ } from "./types.js";
34
+ import {
35
+ assertSupportedDevMode,
36
+ readWorkspaceContract,
37
+ } from "./workspace-contract.js";
38
+
39
+ export type {
40
+ AirJamDevMode,
41
+ AirJamDevStatus,
42
+ AirJamManagedDevProcess,
43
+ AirJamRuntimeTopology,
44
+ AirJamSurfaceUrlSummary,
45
+ GetDevStatusOptions,
46
+ GetTopologyOptions,
47
+ ResetLocalDevOptions,
48
+ ResetLocalDevResult,
49
+ StartDevOptions,
50
+ StartDevResult,
51
+ StopDevOptions,
52
+ StopDevResult,
53
+ } from "./types.js";
54
+
55
+ type ManagedRegistry = {
56
+ schemaVersion: 1;
57
+ processes: AirJamManagedDevProcess[];
58
+ };
59
+
60
+ type RawTopologyCommandResult = {
61
+ gameId?: unknown;
62
+ mode?: unknown;
63
+ secure?: unknown;
64
+ surfaces?: unknown;
65
+ };
66
+
67
+ const DEVTOOLS_SCHEMA_VERSION = 1 as const;
68
+ const START_TIMEOUT_MS = 120_000;
69
+ const KNOWN_LOCAL_DEV_PORTS = [4000, 5173] as const;
70
+ const KNOWN_PORTS_ENV = "AIRJAM_DEVTOOLS_KNOWN_PORTS";
71
+ const DEFAULT_CONTROLLER_PATH = "/controller";
72
+ const MANAGED_PROCESS_STOP_TIMEOUT_MS = 10_000;
73
+
74
+ const toTopologyMode = (
75
+ mode: AirJamDevMode,
76
+ ): "standalone-dev" | "arcade-live" | "arcade-built" => {
77
+ if (mode === "arcade-dev") {
78
+ return "arcade-live";
79
+ }
80
+ if (mode === "arcade-test") {
81
+ return "arcade-built";
82
+ }
83
+ return "standalone-dev";
84
+ };
85
+
86
+ const isKnownProjectMode = (
87
+ mode: AirJamProjectContext["mode"],
88
+ ): mode is "monorepo" | "standalone-game" =>
89
+ mode === "monorepo" || mode === "standalone-game";
90
+
91
+ const getDevtoolsRoot = (rootDir: string): string =>
92
+ path.join(rootDir, ".airjam", "devtools");
93
+
94
+ const getManagedRegistryPath = (rootDir: string): string =>
95
+ path.join(getDevtoolsRoot(rootDir), "managed-processes.json");
96
+
97
+ const getManagedProcessLogPath = (rootDir: string, processId: string): string =>
98
+ path.join(getDevtoolsRoot(rootDir), "processes", `${processId}.log`);
99
+
100
+ const isProcessAlive = (pid: number): boolean => {
101
+ if (!Number.isInteger(pid) || pid <= 0) {
102
+ return false;
103
+ }
104
+
105
+ try {
106
+ process.kill(pid, 0);
107
+ return true;
108
+ } catch {
109
+ return false;
110
+ }
111
+ };
112
+
113
+ const readCommandOutput = (command: string, args: string[]): string | null => {
114
+ try {
115
+ return runCommandResult({
116
+ command,
117
+ args,
118
+ cwd: process.cwd(),
119
+ }).stdout.trim();
120
+ } catch {
121
+ return null;
122
+ }
123
+ };
124
+
125
+ const readListeningPidsForPort = (port: number): number[] => {
126
+ const output = readCommandOutput("lsof", [
127
+ "-nP",
128
+ `-tiTCP:${port}`,
129
+ "-sTCP:LISTEN",
130
+ ]);
131
+ if (!output) {
132
+ return [];
133
+ }
134
+
135
+ return output
136
+ .split(/\r?\n/)
137
+ .map((value) => Number.parseInt(value.trim(), 10))
138
+ .filter((value) => Number.isInteger(value) && value > 0);
139
+ };
140
+
141
+ const readProcessCommand = (pid: number): string | null => {
142
+ const output = readCommandOutput("ps", ["-p", String(pid), "-o", "command="]);
143
+ return output && output.length > 0 ? output : null;
144
+ };
145
+
146
+ const readProcessAgeMs = (pid: number): number | null => {
147
+ const output = readCommandOutput("ps", ["-p", String(pid), "-o", "etimes="]);
148
+ const seconds = output ? Number.parseInt(output.trim(), 10) : Number.NaN;
149
+ return Number.isFinite(seconds) && seconds >= 0 ? seconds * 1000 : null;
150
+ };
151
+
152
+ const getKnownLocalDevPorts = (): number[] => {
153
+ const rawPorts = process.env[KNOWN_PORTS_ENV];
154
+ if (!rawPorts) {
155
+ return [...KNOWN_LOCAL_DEV_PORTS];
156
+ }
157
+
158
+ const ports = rawPorts
159
+ .split(",")
160
+ .map((value) => Number.parseInt(value.trim(), 10))
161
+ .filter((value) => Number.isInteger(value) && value > 0);
162
+ return ports.length > 0
163
+ ? Array.from(new Set(ports))
164
+ : [...KNOWN_LOCAL_DEV_PORTS];
165
+ };
166
+
167
+ const isLikelyAirJamLocalDevCommand = (command: string | null): boolean => {
168
+ if (!command) {
169
+ return false;
170
+ }
171
+
172
+ return /(^|\W)(@air-jam\/server|air-jam-server|airjam|vite|create-airjam)(\W|$)/.test(
173
+ command,
174
+ );
175
+ };
176
+
177
+ const listKnownPortListeners = (): AirJamUnmanagedDevProcess[] => {
178
+ const byPid = new Map<number, Set<number>>();
179
+
180
+ for (const port of getKnownLocalDevPorts()) {
181
+ for (const pid of readListeningPidsForPort(port)) {
182
+ const ports = byPid.get(pid) ?? new Set<number>();
183
+ ports.add(port);
184
+ byPid.set(pid, ports);
185
+ }
186
+ }
187
+
188
+ return Array.from(byPid.entries())
189
+ .map(([pid, ports]) => {
190
+ const ageMs = readProcessAgeMs(pid);
191
+ return {
192
+ pid,
193
+ ports: Array.from(ports).sort((left, right) => left - right),
194
+ command: readProcessCommand(pid),
195
+ startedAt:
196
+ ageMs !== null ? new Date(Date.now() - ageMs).toISOString() : null,
197
+ ageMs,
198
+ managed: false as const,
199
+ };
200
+ })
201
+ .sort((left, right) => left.pid - right.pid);
202
+ };
203
+
204
+ const waitForProcessExit = async (
205
+ pid: number,
206
+ timeoutMs = MANAGED_PROCESS_STOP_TIMEOUT_MS,
207
+ ): Promise<boolean> => {
208
+ const startedAt = Date.now();
209
+ while (Date.now() - startedAt < timeoutMs) {
210
+ if (!isProcessAlive(pid)) {
211
+ return true;
212
+ }
213
+ await new Promise((resolve) => setTimeout(resolve, 100));
214
+ }
215
+ return !isProcessAlive(pid);
216
+ };
217
+
218
+ const terminateManagedProcess = async (pid: number): Promise<void> => {
219
+ if (!Number.isInteger(pid) || pid <= 0) {
220
+ return;
221
+ }
222
+
223
+ if (!isProcessAlive(pid)) {
224
+ return;
225
+ }
226
+
227
+ if (process.platform === "win32") {
228
+ runCommandResult({
229
+ command: "taskkill",
230
+ args: ["/PID", String(pid), "/T", "/F"],
231
+ cwd: process.cwd(),
232
+ });
233
+ } else {
234
+ try {
235
+ process.kill(-pid, "SIGTERM");
236
+ } catch {
237
+ try {
238
+ process.kill(pid, "SIGTERM");
239
+ } catch {
240
+ // The process may have exited between inspection and signaling.
241
+ }
242
+ }
243
+ }
244
+
245
+ if (!(await waitForProcessExit(pid))) {
246
+ if (process.platform !== "win32") {
247
+ try {
248
+ process.kill(-pid, "SIGKILL");
249
+ } catch {
250
+ try {
251
+ process.kill(pid, "SIGKILL");
252
+ } catch {
253
+ // Report the authoritative terminal check below.
254
+ }
255
+ }
256
+ }
257
+ if (!(await waitForProcessExit(pid, 2_000))) {
258
+ throw new Error(`Managed Air Jam dev process ${pid} did not terminate.`);
259
+ }
260
+ }
261
+ };
262
+
263
+ const readRegistry = async (rootDir: string): Promise<ManagedRegistry> => {
264
+ const registryPath = getManagedRegistryPath(rootDir);
265
+ if (!(await pathExists(registryPath))) {
266
+ return {
267
+ schemaVersion: DEVTOOLS_SCHEMA_VERSION,
268
+ processes: [],
269
+ };
270
+ }
271
+
272
+ const parsed = JSON.parse(
273
+ await readFile(registryPath, "utf8"),
274
+ ) as Partial<ManagedRegistry>;
275
+
276
+ return {
277
+ schemaVersion: DEVTOOLS_SCHEMA_VERSION,
278
+ processes: Array.isArray(parsed.processes) ? parsed.processes : [],
279
+ };
280
+ };
281
+
282
+ const writeRegistry = async (
283
+ rootDir: string,
284
+ registry: ManagedRegistry,
285
+ ): Promise<void> => {
286
+ const registryPath = getManagedRegistryPath(rootDir);
287
+ await mkdir(path.dirname(registryPath), { recursive: true });
288
+ await writeFile(
289
+ registryPath,
290
+ `${JSON.stringify(registry, null, 2)}\n`,
291
+ "utf8",
292
+ );
293
+ };
294
+
295
+ const listManagedProcessesForRoot = async (
296
+ rootDir: string,
297
+ ): Promise<AirJamManagedDevProcess[]> => {
298
+ const registry = await readRegistry(rootDir);
299
+ const aliveProcesses = registry.processes.filter((processInfo) =>
300
+ isProcessAlive(processInfo.pid),
301
+ );
302
+
303
+ if (aliveProcesses.length !== registry.processes.length) {
304
+ await writeRegistry(rootDir, {
305
+ schemaVersion: DEVTOOLS_SCHEMA_VERSION,
306
+ processes: aliveProcesses,
307
+ });
308
+ }
309
+
310
+ return aliveProcesses.sort((left, right) =>
311
+ left.startedAt.localeCompare(right.startedAt),
312
+ );
313
+ };
314
+
315
+ const appendArg = (args: string[], flag: string, value?: string | boolean) => {
316
+ if (value === undefined || value === false || value === "") {
317
+ return;
318
+ }
319
+
320
+ if (value === true) {
321
+ args.push(flag);
322
+ return;
323
+ }
324
+
325
+ args.push(`${flag}=${value}`);
326
+ };
327
+
328
+ const resolveWorkspaceCliPath = (context: AirJamProjectContext): string => {
329
+ const workspace = readWorkspaceContract(context.packageJson);
330
+ if (!workspace)
331
+ throw new Error(
332
+ "Air Jam workspace must declare airjam.workspace in package.json.",
333
+ );
334
+ return path.resolve(context.rootDir, workspace.cli);
335
+ };
336
+
337
+ const resolveRequestedGameId = async ({
338
+ cwd,
339
+ context,
340
+ gameId,
341
+ }: {
342
+ cwd: string;
343
+ context: AirJamProjectContext;
344
+ gameId?: string;
345
+ }): Promise<string | null> => {
346
+ if (context.mode === "standalone-game") {
347
+ return (await inspectGame({ cwd, gameId })).id;
348
+ }
349
+
350
+ if (context.mode !== "monorepo") {
351
+ return null;
352
+ }
353
+
354
+ if (gameId) {
355
+ return gameId;
356
+ }
357
+
358
+ const games = await listGames({ cwd });
359
+ return games[0]?.id ?? null;
360
+ };
361
+
362
+ const resolveStartCommand = async ({
363
+ context,
364
+ cwd,
365
+ gameId,
366
+ mode,
367
+ secure,
368
+ }: {
369
+ context: AirJamProjectContext;
370
+ cwd: string;
371
+ gameId: string | null;
372
+ mode: AirJamDevMode;
373
+ secure: boolean;
374
+ }): Promise<{
375
+ command: string;
376
+ args: string[];
377
+ topologyMode: "standalone-dev" | "arcade-live" | "arcade-built";
378
+ expectedLogPath: string | null;
379
+ }> => {
380
+ if (context.mode === "monorepo") {
381
+ if (!gameId) {
382
+ throw new Error("Monorepo dev start requires a game id.");
383
+ }
384
+
385
+ const script =
386
+ mode === "arcade-dev"
387
+ ? "arcade:dev"
388
+ : mode === "arcade-test"
389
+ ? "arcade:test"
390
+ : "standalone:dev";
391
+
392
+ const args = [
393
+ resolveWorkspaceCliPath(context),
394
+ "workspace",
395
+ script,
396
+ `--game=${gameId}`,
397
+ ];
398
+ appendArg(args, "--secure", secure);
399
+
400
+ return {
401
+ command: process.execPath,
402
+ args,
403
+ topologyMode: toTopologyMode(mode),
404
+ expectedLogPath: path.join(cwd, ".airjam", "logs", "dev-latest.ndjson"),
405
+ };
406
+ }
407
+
408
+ if (context.mode !== "standalone-game") {
409
+ throw new Error(
410
+ "Air Jam dev start is only available in known project modes.",
411
+ );
412
+ }
413
+
414
+ const args =
415
+ context.packageJson?.scripts?.dev !== undefined
416
+ ? ["run", "dev"]
417
+ : ["exec", "airjam", "dev"];
418
+ if (secure) {
419
+ args.push("--", "--secure");
420
+ }
421
+
422
+ return {
423
+ command: "pnpm",
424
+ args,
425
+ topologyMode: "standalone-dev",
426
+ expectedLogPath: path.join(cwd, ".airjam", "logs", "dev-latest.ndjson"),
427
+ };
428
+ };
429
+
430
+ const parseJsonFromCommandOutput = <T>(output: string): T => {
431
+ const startIndex = output.indexOf("{");
432
+ const endIndex = output.lastIndexOf("}");
433
+ if (startIndex === -1 || endIndex === -1 || endIndex < startIndex) {
434
+ throw new Error(`Expected JSON output but received:\n${output}`);
435
+ }
436
+
437
+ return JSON.parse(output.slice(startIndex, endIndex + 1)) as T;
438
+ };
439
+
440
+ const resolveTopologyCommand = async ({
441
+ context,
442
+ gameId,
443
+ mode,
444
+ secure,
445
+ }: {
446
+ context: AirJamProjectContext;
447
+ gameId: string | null;
448
+ mode: AirJamDevMode;
449
+ secure: boolean;
450
+ }): Promise<{
451
+ command: string;
452
+ args: string[];
453
+ topologyMode: "standalone-dev" | "arcade-live" | "arcade-built";
454
+ }> => {
455
+ const topologyMode = toTopologyMode(mode);
456
+
457
+ if (context.mode === "monorepo") {
458
+ if (!gameId) {
459
+ throw new Error("Monorepo topology inspection requires a game id.");
460
+ }
461
+
462
+ const args = [
463
+ resolveWorkspaceCliPath(context),
464
+ "workspace",
465
+ "topology",
466
+ `--game=${gameId}`,
467
+ `--mode=${topologyMode}`,
468
+ ];
469
+ appendArg(args, "--secure", secure);
470
+
471
+ return {
472
+ command: process.execPath,
473
+ args,
474
+ topologyMode,
475
+ };
476
+ }
477
+
478
+ if (context.mode !== "standalone-game") {
479
+ throw new Error(
480
+ "Air Jam topology is only available in known project modes.",
481
+ );
482
+ }
483
+
484
+ const topologyScript = context.packageJson?.scripts?.topology?.trim();
485
+ const topologyScriptUsesAirJamCli =
486
+ typeof topologyScript === "string" &&
487
+ /\bairjam\s+topology\b/.test(topologyScript);
488
+ const args =
489
+ topologyScript && !topologyScriptUsesAirJamCli
490
+ ? ["run", "topology", "--", "--mode=standalone-dev"]
491
+ : ["exec", "airjam", "topology", "--mode=standalone-dev"];
492
+ appendArg(args, "--secure", secure);
493
+
494
+ return {
495
+ command: "pnpm",
496
+ args,
497
+ topologyMode,
498
+ };
499
+ };
500
+
501
+ const toObject = (value: unknown): JsonObject =>
502
+ value && typeof value === "object" && !Array.isArray(value)
503
+ ? (value as JsonObject)
504
+ : {};
505
+
506
+ const toStringOrNull = (value: unknown): string | null =>
507
+ typeof value === "string" && value.trim() !== "" ? value : null;
508
+
509
+ const joinUrl = (origin: string | null, pathname: string): string | null => {
510
+ if (!origin) {
511
+ return null;
512
+ }
513
+
514
+ return new URL(pathname, origin).toString();
515
+ };
516
+
517
+ const buildUrlSummary = ({
518
+ mode,
519
+ gameId,
520
+ surfaces,
521
+ controllerPath,
522
+ }: {
523
+ mode: AirJamDevMode;
524
+ gameId: string | null;
525
+ surfaces: Record<string, JsonObject>;
526
+ controllerPath: string;
527
+ }): AirJamSurfaceUrlSummary => {
528
+ if (mode === "standalone-dev") {
529
+ const hostSurface = toObject(surfaces.host);
530
+ const controllerSurface = toObject(surfaces.controller);
531
+ const hostOrigin = toStringOrNull(hostSurface.appOrigin);
532
+ const controllerOrigin =
533
+ toStringOrNull(controllerSurface.appOrigin) ?? hostOrigin;
534
+ const publicHost =
535
+ toStringOrNull(hostSurface.publicHost) ??
536
+ toStringOrNull(controllerSurface.publicHost) ??
537
+ hostOrigin;
538
+
539
+ return {
540
+ appOrigin: hostOrigin,
541
+ hostUrl: hostOrigin,
542
+ controllerBaseUrl: joinUrl(controllerOrigin, controllerPath),
543
+ publicHost,
544
+ localBuildUrl: null,
545
+ browserBuildUrl: null,
546
+ };
547
+ }
548
+
549
+ const platformHost = toObject(surfaces.platformHost);
550
+ const platformController = toObject(surfaces.platformController);
551
+ const embeddedHost = toObject(surfaces.embeddedHost);
552
+ const appOrigin = toStringOrNull(platformHost.appOrigin);
553
+ const controllerOrigin =
554
+ toStringOrNull(platformController.appOrigin) ??
555
+ toStringOrNull(platformHost.publicHost) ??
556
+ appOrigin;
557
+ const publicHost =
558
+ toStringOrNull(platformHost.publicHost) ??
559
+ toStringOrNull(platformController.publicHost) ??
560
+ controllerOrigin;
561
+ const assetBasePath = toStringOrNull(embeddedHost.assetBasePath);
562
+
563
+ return {
564
+ appOrigin,
565
+ hostUrl:
566
+ appOrigin && gameId
567
+ ? new URL(`/arcade/local-${gameId}`, appOrigin).toString()
568
+ : null,
569
+ controllerBaseUrl: joinUrl(controllerOrigin, DEFAULT_CONTROLLER_PATH),
570
+ publicHost,
571
+ localBuildUrl:
572
+ mode === "arcade-test" && publicHost && assetBasePath
573
+ ? new URL(assetBasePath, publicHost).toString()
574
+ : null,
575
+ browserBuildUrl:
576
+ mode === "arcade-test" && appOrigin && assetBasePath
577
+ ? new URL(assetBasePath, appOrigin).toString()
578
+ : null,
579
+ };
580
+ };
581
+
582
+ const wait = (ms: number): Promise<void> =>
583
+ new Promise((resolve) => setTimeout(resolve, ms));
584
+
585
+ const checkUrlReady = (targetUrl: string, secure: boolean): Promise<boolean> =>
586
+ new Promise((resolve) => {
587
+ const parsed = new URL(targetUrl);
588
+ const client = parsed.protocol === "https:" ? https : http;
589
+ const request = client.request(
590
+ parsed,
591
+ {
592
+ method: "GET",
593
+ rejectUnauthorized: secure ? false : undefined,
594
+ },
595
+ (response) => {
596
+ response.resume();
597
+ resolve(Boolean(response.statusCode && response.statusCode < 500));
598
+ },
599
+ );
600
+
601
+ request.setTimeout(2_500, () => {
602
+ request.destroy();
603
+ resolve(false);
604
+ });
605
+ request.on("error", () => resolve(false));
606
+ request.end();
607
+ });
608
+
609
+ const waitForTopologyReady = async ({
610
+ topology,
611
+ timeoutMs = START_TIMEOUT_MS,
612
+ }: {
613
+ topology: AirJamRuntimeTopology;
614
+ timeoutMs?: number;
615
+ }): Promise<void> => {
616
+ const urls = [topology.urls.hostUrl, topology.urls.controllerBaseUrl].filter(
617
+ (value): value is string => Boolean(value),
618
+ );
619
+ if (urls.length === 0) {
620
+ return;
621
+ }
622
+
623
+ const startedAt = Date.now();
624
+ while (Date.now() - startedAt < timeoutMs) {
625
+ const statuses = await Promise.all(
626
+ urls.map((targetUrl) => checkUrlReady(targetUrl, topology.secure)),
627
+ );
628
+ if (statuses.every(Boolean)) {
629
+ return;
630
+ }
631
+ await wait(500);
632
+ }
633
+
634
+ throw new Error(
635
+ `Timed out waiting for Air Jam dev endpoints: ${urls.join(", ")}`,
636
+ );
637
+ };
638
+
639
+ export const tryAttachToRunningDev = async ({
640
+ cwd = process.cwd(),
641
+ gameId,
642
+ mode = "standalone-dev",
643
+ secure = false,
644
+ timeoutMs = 2_500,
645
+ }: GetTopologyOptions & {
646
+ timeoutMs?: number;
647
+ } = {}): Promise<AirJamRuntimeTopology | null> => {
648
+ try {
649
+ const topology = await getTopology({
650
+ cwd,
651
+ gameId,
652
+ mode,
653
+ secure,
654
+ });
655
+ await waitForTopologyReady({
656
+ topology,
657
+ timeoutMs,
658
+ });
659
+ return topology;
660
+ } catch {
661
+ return null;
662
+ }
663
+ };
664
+
665
+ const readManagedProcessLogTail = async (
666
+ logPath: string,
667
+ maxLines = 60,
668
+ ): Promise<string> => {
669
+ if (!(await pathExists(logPath))) {
670
+ return "";
671
+ }
672
+
673
+ const contents = await readFile(logPath, "utf8");
674
+ return contents.split(/\r?\n/).filter(Boolean).slice(-maxLines).join("\n");
675
+ };
676
+
677
+ export const getDevStatus = async ({
678
+ cwd = process.cwd(),
679
+ }: GetDevStatusOptions = {}): Promise<AirJamDevStatus> => {
680
+ const context = await detectProjectContext({ cwd });
681
+ const managedProcesses = await listManagedProcessesForRoot(context.rootDir);
682
+ const managedPids = new Set(managedProcesses.map((entry) => entry.pid));
683
+ return {
684
+ processes: managedProcesses,
685
+ unmanagedProcesses: listKnownPortListeners().filter(
686
+ (entry) => !managedPids.has(entry.pid),
687
+ ),
688
+ knownPorts: getKnownLocalDevPorts(),
689
+ };
690
+ };
691
+
692
+ export const getTopology = async ({
693
+ cwd = process.cwd(),
694
+ gameId,
695
+ mode = "standalone-dev",
696
+ secure = false,
697
+ }: GetTopologyOptions = {}): Promise<AirJamRuntimeTopology> => {
698
+ const context = await detectProjectContext({ cwd });
699
+ assertSupportedDevMode(context.packageJson, mode);
700
+ if (!isKnownProjectMode(context.mode)) {
701
+ throw new Error(
702
+ "Air Jam topology is only available in recognized Air Jam projects.",
703
+ );
704
+ }
705
+
706
+ const resolvedGameId = await resolveRequestedGameId({
707
+ cwd,
708
+ context,
709
+ gameId,
710
+ });
711
+ const game =
712
+ resolvedGameId !== null
713
+ ? await inspectGame({ cwd, gameId: resolvedGameId })
714
+ : null;
715
+ const controllerPath = game?.controllerPathLikely ?? DEFAULT_CONTROLLER_PATH;
716
+ const topologyCommand = await resolveTopologyCommand({
717
+ context,
718
+ gameId: resolvedGameId,
719
+ mode,
720
+ secure,
721
+ });
722
+ const topologyResult = runCommandResult({
723
+ command: topologyCommand.command,
724
+ args: topologyCommand.args,
725
+ cwd: context.rootDir,
726
+ });
727
+
728
+ if (!topologyResult.ok) {
729
+ throw new Error(
730
+ `Failed to inspect Air Jam topology.\n\n${topologyResult.stderr || topologyResult.stdout}`,
731
+ );
732
+ }
733
+
734
+ const parsed = parseJsonFromCommandOutput<RawTopologyCommandResult>(
735
+ topologyResult.stdout,
736
+ );
737
+ const surfaces = toObject(parsed.surfaces) as Record<string, JsonObject>;
738
+ const processes = await listManagedProcessesForRoot(context.rootDir);
739
+ const matchingProcess =
740
+ processes.find(
741
+ (processInfo) =>
742
+ processInfo.mode === mode &&
743
+ processInfo.secure === secure &&
744
+ processInfo.gameId === resolvedGameId,
745
+ ) ?? null;
746
+
747
+ return {
748
+ projectMode: context.mode,
749
+ mode,
750
+ topologyMode: topologyCommand.topologyMode,
751
+ gameId: resolvedGameId,
752
+ secure,
753
+ surfaces,
754
+ urls: buildUrlSummary({
755
+ mode,
756
+ gameId: resolvedGameId,
757
+ surfaces,
758
+ controllerPath,
759
+ }),
760
+ process: matchingProcess,
761
+ };
762
+ };
763
+
764
+ export const startDev = async ({
765
+ cwd = process.cwd(),
766
+ gameId,
767
+ mode = "standalone-dev",
768
+ secure = false,
769
+ }: StartDevOptions = {}): Promise<StartDevResult> => {
770
+ const context = await detectProjectContext({ cwd });
771
+ assertSupportedDevMode(context.packageJson, mode);
772
+ if (!isKnownProjectMode(context.mode)) {
773
+ throw new Error(
774
+ "Air Jam dev start is only available in recognized Air Jam projects.",
775
+ );
776
+ }
777
+
778
+ const resolvedGameId = await resolveRequestedGameId({
779
+ cwd,
780
+ context,
781
+ gameId,
782
+ });
783
+ const existingProcesses = await listManagedProcessesForRoot(context.rootDir);
784
+ const exactMatch =
785
+ existingProcesses.find(
786
+ (processInfo) =>
787
+ processInfo.mode === mode &&
788
+ processInfo.secure === secure &&
789
+ processInfo.gameId === resolvedGameId,
790
+ ) ?? null;
791
+ if (exactMatch) {
792
+ return {
793
+ process: exactMatch,
794
+ reusedExistingProcess: true,
795
+ topology: await getTopology({
796
+ cwd: context.rootDir,
797
+ gameId: resolvedGameId ?? undefined,
798
+ mode,
799
+ secure,
800
+ }),
801
+ };
802
+ }
803
+
804
+ if (existingProcesses.length > 0) {
805
+ throw new Error(
806
+ `Air Jam devtools already manages ${existingProcesses.length} running dev process(es) in ${context.rootDir}. Stop them first with airjam.stop_dev.`,
807
+ );
808
+ }
809
+
810
+ const startCommand = await resolveStartCommand({
811
+ context,
812
+ cwd: context.rootDir,
813
+ gameId: resolvedGameId,
814
+ mode,
815
+ secure,
816
+ });
817
+ const processId = randomUUID();
818
+ const logPath = getManagedProcessLogPath(context.rootDir, processId);
819
+ await mkdir(path.dirname(logPath), { recursive: true });
820
+ const logFd = openSync(logPath, "a");
821
+ const supervisorPath = resolveDevtoolsHelperScript(
822
+ "managed-dev-supervisor.ts",
823
+ );
824
+ const supervisorDescriptor = Buffer.from(
825
+ JSON.stringify({
826
+ command: startCommand.command,
827
+ args: startCommand.args,
828
+ cwd: context.rootDir,
829
+ }),
830
+ "utf8",
831
+ ).toString("base64url");
832
+ const child = crossSpawn(
833
+ process.execPath,
834
+ [...resolveDevtoolsHelperArgs(supervisorPath), supervisorDescriptor],
835
+ {
836
+ cwd: context.rootDir,
837
+ detached: true,
838
+ stdio: ["ignore", logFd, logFd],
839
+ env: {
840
+ ...process.env,
841
+ CI: process.env.CI ?? "1",
842
+ NO_UPDATE_NOTIFIER: "1",
843
+ },
844
+ },
845
+ );
846
+ const childExited = new Promise<{
847
+ code: number | null;
848
+ signal: NodeJS.Signals | null;
849
+ }>((resolve) => {
850
+ child.once("exit", (code, signal) => {
851
+ resolve({ code, signal });
852
+ });
853
+ });
854
+ try {
855
+ await new Promise<void>((resolve, reject) => {
856
+ child.once("spawn", resolve);
857
+ child.once("error", reject);
858
+ });
859
+ } finally {
860
+ closeSync(logFd);
861
+ }
862
+ child.unref();
863
+
864
+ const managedProcess: AirJamManagedDevProcess = {
865
+ id: processId,
866
+ pid: child.pid ?? 0,
867
+ cwd: context.rootDir,
868
+ projectMode: context.mode,
869
+ mode,
870
+ topologyMode: startCommand.topologyMode,
871
+ secure,
872
+ gameId: resolvedGameId,
873
+ command: startCommand.command,
874
+ args: startCommand.args,
875
+ logPath,
876
+ expectedLogPath: startCommand.expectedLogPath,
877
+ startedAt: new Date().toISOString(),
878
+ };
879
+
880
+ await writeRegistry(context.rootDir, {
881
+ schemaVersion: DEVTOOLS_SCHEMA_VERSION,
882
+ processes: [managedProcess],
883
+ });
884
+
885
+ try {
886
+ const topology = await getTopology({
887
+ cwd: context.rootDir,
888
+ gameId: resolvedGameId ?? undefined,
889
+ mode,
890
+ secure,
891
+ });
892
+ await Promise.race([
893
+ waitForTopologyReady({ topology }),
894
+ childExited.then(({ code, signal }) => {
895
+ throw new Error(
896
+ signal
897
+ ? `Managed dev supervisor exited from signal ${signal}.`
898
+ : `Managed dev supervisor exited with code ${code ?? "unknown"}.`,
899
+ );
900
+ }),
901
+ ]);
902
+ return {
903
+ process: managedProcess,
904
+ reusedExistingProcess: false,
905
+ topology,
906
+ };
907
+ } catch (error) {
908
+ await terminateManagedProcess(managedProcess.pid);
909
+ await writeRegistry(context.rootDir, {
910
+ schemaVersion: DEVTOOLS_SCHEMA_VERSION,
911
+ processes: [],
912
+ });
913
+ const logTail = await readManagedProcessLogTail(logPath);
914
+ const message =
915
+ error instanceof Error ? error.message : String(error ?? "Unknown error");
916
+ throw new Error(
917
+ logTail ? `${message}\n\nManaged dev log tail:\n${logTail}` : message,
918
+ );
919
+ }
920
+ };
921
+
922
+ export const stopDev = async ({
923
+ cwd = process.cwd(),
924
+ processId,
925
+ mode,
926
+ }: StopDevOptions = {}): Promise<StopDevResult> => {
927
+ const context = await detectProjectContext({ cwd });
928
+ const processes = await listManagedProcessesForRoot(context.rootDir);
929
+ const selected = processes.filter((processInfo) => {
930
+ if (processId) {
931
+ return processInfo.id === processId;
932
+ }
933
+ if (mode) {
934
+ return processInfo.mode === mode;
935
+ }
936
+ return true;
937
+ });
938
+
939
+ for (const processInfo of selected) {
940
+ await terminateManagedProcess(processInfo.pid);
941
+ }
942
+
943
+ const remaining = processes.filter(
944
+ (processInfo) =>
945
+ !selected.some(
946
+ (selectedProcess) => selectedProcess.id === processInfo.id,
947
+ ),
948
+ );
949
+ await writeRegistry(context.rootDir, {
950
+ schemaVersion: DEVTOOLS_SCHEMA_VERSION,
951
+ processes: remaining,
952
+ });
953
+
954
+ return {
955
+ stopped: selected,
956
+ };
957
+ };
958
+
959
+ export const resetLocalDev = async ({
960
+ cwd = process.cwd(),
961
+ }: ResetLocalDevOptions = {}): Promise<ResetLocalDevResult> => {
962
+ const context = await detectProjectContext({ cwd });
963
+ const stoppedManaged = (await stopDev({ cwd: context.rootDir })).stopped;
964
+ const managedPids = new Set(stoppedManaged.map((entry) => entry.pid));
965
+ const unmanaged = listKnownPortListeners().filter(
966
+ (entry) => !managedPids.has(entry.pid),
967
+ );
968
+ const stoppedUnmanaged: AirJamUnmanagedDevProcess[] = [];
969
+
970
+ for (const processInfo of unmanaged) {
971
+ if (!isLikelyAirJamLocalDevCommand(processInfo.command)) {
972
+ continue;
973
+ }
974
+ await terminateManagedProcess(processInfo.pid);
975
+ stoppedUnmanaged.push(processInfo);
976
+ }
977
+
978
+ await rm(
979
+ path.join(context.rootDir, ".airjam", "preview-managed-server.json"),
980
+ {
981
+ force: true,
982
+ },
983
+ ).catch(() => undefined);
984
+
985
+ const stoppedPids = new Set([
986
+ ...stoppedManaged.map((entry) => entry.pid),
987
+ ...stoppedUnmanaged.map((entry) => entry.pid),
988
+ ]);
989
+ const remainingUnmanaged = listKnownPortListeners().filter(
990
+ (entry) => !stoppedPids.has(entry.pid),
991
+ );
992
+
993
+ return {
994
+ stoppedManaged,
995
+ stoppedUnmanaged,
996
+ remainingUnmanaged,
997
+ knownPorts: getKnownLocalDevPorts(),
998
+ };
999
+ };