@air-jam/cli 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 (127) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +273 -2
  3. package/bin/airjam.mjs +66 -0
  4. package/dist/ai-pack.d.ts +44 -0
  5. package/dist/ai-pack.js +15 -0
  6. package/dist/ai-pack.js.map +1 -0
  7. package/dist/auth-profile.d.ts +5 -0
  8. package/dist/auth-profile.js +7 -0
  9. package/dist/auth-profile.js.map +1 -0
  10. package/dist/auth-sessions.d.ts +5 -0
  11. package/dist/auth-sessions.js +7 -0
  12. package/dist/auth-sessions.js.map +1 -0
  13. package/dist/chunk-7D4AYBAV.js +64 -0
  14. package/dist/chunk-7D4AYBAV.js.map +1 -0
  15. package/dist/chunk-J5MAU4QZ.js +102 -0
  16. package/dist/chunk-J5MAU4QZ.js.map +1 -0
  17. package/dist/chunk-LH7UO57C.js +23 -0
  18. package/dist/chunk-LH7UO57C.js.map +1 -0
  19. package/dist/chunk-N7AI7HZK.js +529 -0
  20. package/dist/chunk-N7AI7HZK.js.map +1 -0
  21. package/dist/chunk-PKTLVQXZ.js +82 -0
  22. package/dist/chunk-PKTLVQXZ.js.map +1 -0
  23. package/dist/chunk-SQE4NPZP.js +31 -0
  24. package/dist/chunk-SQE4NPZP.js.map +1 -0
  25. package/dist/chunk-U6V3HEBB.js +939 -0
  26. package/dist/chunk-U6V3HEBB.js.map +1 -0
  27. package/dist/chunk-VEHNFPEO.js +224 -0
  28. package/dist/chunk-VEHNFPEO.js.map +1 -0
  29. package/dist/development.d.ts +102 -0
  30. package/dist/development.js +33 -0
  31. package/dist/development.js.map +1 -0
  32. package/dist/documentation.d.ts +27 -0
  33. package/dist/documentation.js +7 -0
  34. package/dist/documentation.js.map +1 -0
  35. package/dist/game-analytics.d.ts +5 -0
  36. package/dist/game-analytics.js +7 -0
  37. package/dist/game-analytics.js.map +1 -0
  38. package/dist/game-app-id.d.ts +5 -0
  39. package/dist/game-app-id.js +7 -0
  40. package/dist/game-app-id.js.map +1 -0
  41. package/dist/game-media.d.ts +5 -0
  42. package/dist/game-media.js +7 -0
  43. package/dist/game-media.js.map +1 -0
  44. package/dist/index.d.ts +1 -0
  45. package/dist/index.js +2468 -0
  46. package/dist/index.js.map +1 -0
  47. package/dist/scaffold.d.ts +6 -0
  48. package/dist/scaffold.js +20 -0
  49. package/dist/scaffold.js.map +1 -0
  50. package/package.json +82 -3
  51. package/runtime/local-network.d.mts +6 -0
  52. package/runtime/local-network.mjs +9 -0
  53. package/runtime/public-assets.mjs +62 -0
  54. package/runtime/source-fence.mjs +182 -0
  55. package/runtime/vite-config.d.mts +43 -0
  56. package/runtime/vite-config.mjs +134 -0
  57. package/runtime/vite-dev.mjs +18 -0
  58. package/runtime/vite-https.d.mts +11 -0
  59. package/runtime/vite-https.mjs +40 -0
  60. package/template-assets/bootstrap/.claude/launch.json +12 -0
  61. package/template-assets/bootstrap/AGENTS.md +290 -0
  62. package/template-assets/bootstrap/CLAUDE.md +55 -0
  63. package/template-assets/bootstrap/_gitignore +6 -0
  64. package/template-assets/bootstrap/skills/airjam-docs-workflow/SKILL.md +49 -0
  65. package/template-assets/bootstrap/skills/airjam-mcp/SKILL.md +100 -0
  66. package/template-assets/bootstrap/skills/canvas-2d-gameplay/SKILL.md +47 -0
  67. package/template-assets/bootstrap/skills/controller-ui/SKILL.md +71 -0
  68. package/template-assets/bootstrap/skills/debug-and-test/SKILL.md +72 -0
  69. package/template-assets/bootstrap/skills/game-architecture/SKILL.md +102 -0
  70. package/template-assets/bootstrap/skills/game-state-and-rendering/SKILL.md +44 -0
  71. package/template-assets/bootstrap/skills/host-surface/SKILL.md +52 -0
  72. package/template-assets/bootstrap/skills/index.md +36 -0
  73. package/template-assets/bootstrap/skills/prefab-authoring/SKILL.md +58 -0
  74. package/template-assets/bootstrap/skills/r3f-3d-scene/SKILL.md +61 -0
  75. package/template-assets/documentation/for-agents/controller-ui/page.mdx +99 -0
  76. package/template-assets/documentation/for-agents/page.mdx +120 -0
  77. package/template-assets/documentation/for-agents/project-structure/page.mdx +170 -0
  78. package/template-assets/documentation/for-agents/state-and-rendering/page.mdx +77 -0
  79. package/template-assets/documentation/for-agents/supported-agents/page.mdx +18 -0
  80. package/template-assets/documentation/getting-started/debugging/page.mdx +164 -0
  81. package/template-assets/documentation/getting-started/dev-logs/page.mdx +169 -0
  82. package/template-assets/documentation/getting-started/game-ideas/page.mdx +114 -0
  83. package/template-assets/documentation/getting-started/introduction/page.mdx +200 -0
  84. package/template-assets/documentation/getting-started/migrating-legacy-games/page.mdx +673 -0
  85. package/template-assets/documentation/getting-started/quick-start/page.mdx +310 -0
  86. package/template-assets/documentation/how-it-works/architecture/page.mdx +230 -0
  87. package/template-assets/documentation/how-it-works/host-system/page.mdx +270 -0
  88. package/template-assets/documentation/manifest.json +500 -0
  89. package/template-assets/documentation/sdk/assets-and-theme/page.mdx +185 -0
  90. package/template-assets/documentation/sdk/hooks/page.mdx +435 -0
  91. package/template-assets/documentation/sdk/input-system/page.mdx +240 -0
  92. package/template-assets/documentation/sdk/networked-state/page.mdx +295 -0
  93. package/template-assets/documentation/sdk/settings/page.mdx +155 -0
  94. package/template-assets/documentation/sdk/ui-components/page.mdx +268 -0
  95. package/template-assets/managed/.airjam/ai-pack.json +209 -0
  96. package/template-assets/managed/docs/airjam/agent-gold-path.md +115 -0
  97. package/template-assets/managed/docs/airjam/agent-mcp.md +179 -0
  98. package/template-assets/managed/docs/airjam/canvas-2d-gameplay.md +82 -0
  99. package/template-assets/managed/docs/airjam/composition-shell-contract.md +87 -0
  100. package/template-assets/managed/docs/airjam/debug-and-testing.md +104 -0
  101. package/template-assets/managed/docs/airjam/development-loop.md +51 -0
  102. package/template-assets/managed/docs/airjam/docs-index.md +64 -0
  103. package/template-assets/managed/docs/airjam/generated/architecture.md +223 -0
  104. package/template-assets/managed/docs/airjam/generated/assets-and-theme.md +188 -0
  105. package/template-assets/managed/docs/airjam/generated/controller-ui.md +102 -0
  106. package/template-assets/managed/docs/airjam/generated/debugging-and-logs.md +165 -0
  107. package/template-assets/managed/docs/airjam/generated/for-agents.md +123 -0
  108. package/template-assets/managed/docs/airjam/generated/game-ideas.md +107 -0
  109. package/template-assets/managed/docs/airjam/generated/host-system.md +261 -0
  110. package/template-assets/managed/docs/airjam/generated/input-system.md +241 -0
  111. package/template-assets/managed/docs/airjam/generated/introduction.md +195 -0
  112. package/template-assets/managed/docs/airjam/generated/migrating-legacy-games.md +674 -0
  113. package/template-assets/managed/docs/airjam/generated/networked-state.md +298 -0
  114. package/template-assets/managed/docs/airjam/generated/project-structure.md +171 -0
  115. package/template-assets/managed/docs/airjam/generated/quick-start.md +311 -0
  116. package/template-assets/managed/docs/airjam/generated/sdk-hooks.md +430 -0
  117. package/template-assets/managed/docs/airjam/generated/settings.md +158 -0
  118. package/template-assets/managed/docs/airjam/generated/state-and-rendering.md +80 -0
  119. package/template-assets/managed/docs/airjam/generated/supported-agents.md +21 -0
  120. package/template-assets/managed/docs/airjam/generated/ui-components.md +265 -0
  121. package/template-assets/managed/docs/airjam/generated/unified-dev-logs.md +170 -0
  122. package/template-assets/managed/docs/airjam/iconography.md +55 -0
  123. package/template-assets/managed/docs/airjam/prefab-authoring.md +212 -0
  124. package/template-assets/managed/docs/airjam/preview-controllers.md +129 -0
  125. package/template-assets/managed/docs/airjam/r3f-3d-scene.md +163 -0
  126. package/template-assets/managed/docs/airjam/state-lanes-cookbook.md +101 -0
  127. package/template-assets/managed/docs/airjam/visual-system.md +103 -0
package/dist/index.js ADDED
@@ -0,0 +1,2468 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ runAiPackDiff,
4
+ runAiPackRepair,
5
+ runAiPackStatus,
6
+ runAiPackUpdate
7
+ } from "./chunk-N7AI7HZK.js";
8
+ import {
9
+ registerAuthProfileCommand
10
+ } from "./chunk-LH7UO57C.js";
11
+ import {
12
+ registerAuthSessionsCommand
13
+ } from "./chunk-SQE4NPZP.js";
14
+ import {
15
+ DEFAULT_GAME_PORT,
16
+ SECURE_MODE_LOCAL,
17
+ SECURE_MODE_TUNNEL,
18
+ buildSecureGameEnv,
19
+ buildStandaloneGameTopology,
20
+ createProcessGroup,
21
+ detectLocalIpv4,
22
+ formatEnvValidationError,
23
+ getFlagValue,
24
+ hasFlag,
25
+ isEnvValidationError,
26
+ isPortOpen,
27
+ loadCreateAirJamRuntimeEnv,
28
+ loadEnvFile,
29
+ loadSecureDevState,
30
+ parseGameDevArgs,
31
+ resolveLocalBackendOrigin,
32
+ runSecureInitCli,
33
+ serializeResolvedTopology,
34
+ waitForPort
35
+ } from "./chunk-U6V3HEBB.js";
36
+ import {
37
+ readDocumentationSnapshot
38
+ } from "./chunk-J5MAU4QZ.js";
39
+ import {
40
+ registerGameAnalyticsCommand
41
+ } from "./chunk-7D4AYBAV.js";
42
+ import {
43
+ registerGameAppIdCommands
44
+ } from "./chunk-PKTLVQXZ.js";
45
+ import {
46
+ registerGameMediaCommands
47
+ } from "./chunk-VEHNFPEO.js";
48
+
49
+ // src/index.ts
50
+ import { gameSessionOperationSchemas as gameSessionOperationSchemas2 } from "@air-jam/devtools/game-session";
51
+ import { airJamSettingsValuesSchema } from "@air-jam/sdk/core";
52
+ import {
53
+ getDevStatus,
54
+ resetLocalDev,
55
+ startDev,
56
+ stopDev
57
+ } from "@air-jam/devtools/dev";
58
+ import {
59
+ GameRunWatchWriter,
60
+ currentRoomAttachmentSchema,
61
+ parseGameRunWatchSurface,
62
+ startGameRunSchema
63
+ } from "@air-jam/devtools/game-runs";
64
+ import {
65
+ cancelGameRun,
66
+ listGameRuns,
67
+ listGameTestProfiles,
68
+ readGameRun,
69
+ readGameSettings as readGameSettings2,
70
+ replayGameRun,
71
+ startGameRun,
72
+ steerGameRun,
73
+ stopAllGameRuns,
74
+ stopGameRun,
75
+ updateGameSettings as updateGameSettings2,
76
+ waitGameRun,
77
+ watchGameRun
78
+ } from "@air-jam/devtools/game-session";
79
+ import { AIRJAM_PROJECT_MCP_FILE as AIRJAM_PROJECT_MCP_FILE2 } from "@air-jam/devtools/mcp-config";
80
+ import {
81
+ AirJamPlatformApiError,
82
+ AirJamStoredPlatformSessionError,
83
+ clearStoredPlatformMachineSession,
84
+ getPlatformAuthStoragePath,
85
+ getPlatformMachineProfile,
86
+ loginPlatformWithDeviceFlow,
87
+ logoutPlatformMachineSession,
88
+ readStoredPlatformMachineSession
89
+ } from "@air-jam/devtools/platform-auth";
90
+ import {
91
+ createPlatformGame,
92
+ inspectPlatformGame,
93
+ listPlatformGames,
94
+ readLocalHostedGameDefaults,
95
+ updatePlatformGame
96
+ } from "@air-jam/devtools/platform-games";
97
+ import { runCompleteEvaluation } from "@air-jam/devtools/quality";
98
+ import {
99
+ archivePlatformRelease,
100
+ bundleLocalRelease,
101
+ exportPlatformReleaseGeneration,
102
+ finalizePlatformReleaseGeneration,
103
+ inspectLocalRelease,
104
+ inspectPlatformRelease,
105
+ listPlatformReleaseTargets,
106
+ listPlatformReleases,
107
+ publishPlatformRelease,
108
+ submitPlatformRelease,
109
+ uploadPlatformReleaseGeneration,
110
+ validateLocalRelease
111
+ } from "@air-jam/devtools/release";
112
+ import { Command } from "commander";
113
+ import kleur3 from "kleur";
114
+ import path3 from "path";
115
+
116
+ // runtime/game-dev.mjs
117
+ import crossSpawn from "cross-spawn";
118
+ import { execFileSync } from "child_process";
119
+ import fs from "fs";
120
+ import path from "path";
121
+ import { fileURLToPath } from "url";
122
+ var START_TIMEOUT_MS = 2e4;
123
+ var viteLauncher = fileURLToPath(
124
+ new URL("../runtime/vite-dev.mjs", import.meta.url)
125
+ );
126
+ var PREVIEW_MANAGED_SERVER_LOG_RELATIVE_PATH = path.join(
127
+ ".airjam",
128
+ "preview-managed-server.log"
129
+ );
130
+ var PREVIEW_MANAGED_SERVER_STATE_RELATIVE_PATH = path.join(
131
+ ".airjam",
132
+ "preview-managed-server.json"
133
+ );
134
+ var holdProcessOpen = async () => {
135
+ await new Promise(() => {
136
+ setInterval(() => {
137
+ }, 1 << 30);
138
+ });
139
+ };
140
+ var usage = () => {
141
+ console.log(
142
+ "Usage: airjam dev [--secure] [--secure-mode=local|tunnel] [--preview-managed] [--web-only] [--server-only] [--allow-existing-game]"
143
+ );
144
+ console.log("");
145
+ console.log("Modes:");
146
+ console.log(
147
+ " default Start local server + game (recommended)"
148
+ );
149
+ console.log(" --secure Start secure local game dev");
150
+ console.log(
151
+ " --secure-mode=tunnel Use Cloudflare tunnel fallback instead of local-only secure host"
152
+ );
153
+ console.log(
154
+ " --preview-managed Start background server + foreground Vite for preview/browser launch tools"
155
+ );
156
+ console.log(" --web-only Start only the game app");
157
+ console.log(" --server-only Start only the local Air Jam server");
158
+ console.log(
159
+ " --allow-existing-game Reuse an already-running Vite server on the game port"
160
+ );
161
+ console.log("");
162
+ console.log("Network isolation:");
163
+ console.log(" VITE_PORT Game app port (default: 5173)");
164
+ console.log(
165
+ " AIR_JAM_SERVER_PORT Local server port (default: 4000)"
166
+ );
167
+ console.log(
168
+ " AIR_JAM_BIND_HOST Bind address (default: all interfaces)"
169
+ );
170
+ console.log(" VITE_AIR_JAM_PUBLIC_HOST Explicit host/controller origin");
171
+ };
172
+ var getDefaultPublicHost = (env, gamePort) => {
173
+ const explicitPublicHost = env.VITE_AIR_JAM_PUBLIC_HOST;
174
+ if (explicitPublicHost) {
175
+ return explicitPublicHost;
176
+ }
177
+ const detectedIp = detectLocalIpv4();
178
+ if (!detectedIp) {
179
+ console.warn(
180
+ "[dev] Could not detect LAN IP. Falling back to localhost in QR links."
181
+ );
182
+ console.warn(
183
+ "[dev] Set VITE_AIR_JAM_PUBLIC_HOST manually for phone testing."
184
+ );
185
+ return `http://localhost:${gamePort}`;
186
+ }
187
+ return `http://${detectedIp}:${gamePort}`;
188
+ };
189
+ var readListeningPid = (port) => {
190
+ try {
191
+ const output = execFileSync(
192
+ "lsof",
193
+ ["-nP", `-tiTCP:${port}`, "-sTCP:LISTEN"],
194
+ {
195
+ encoding: "utf8",
196
+ stdio: ["ignore", "pipe", "ignore"]
197
+ }
198
+ ).trim().split("\n").find(Boolean);
199
+ const pid = Number.parseInt(output ?? "", 10);
200
+ return Number.isInteger(pid) && pid > 0 ? pid : null;
201
+ } catch {
202
+ return null;
203
+ }
204
+ };
205
+ var readProcessSummary = (pid) => {
206
+ if (!pid) {
207
+ return null;
208
+ }
209
+ try {
210
+ const command = execFileSync("ps", ["-p", String(pid), "-o", "command="], {
211
+ encoding: "utf8",
212
+ stdio: ["ignore", "pipe", "ignore"]
213
+ }).trim();
214
+ const etimesOutput = execFileSync(
215
+ "ps",
216
+ ["-p", String(pid), "-o", "etimes="],
217
+ {
218
+ encoding: "utf8",
219
+ stdio: ["ignore", "pipe", "ignore"]
220
+ }
221
+ ).trim();
222
+ const ageSeconds = Number.parseInt(etimesOutput, 10);
223
+ return {
224
+ pid,
225
+ command: command || null,
226
+ ageSeconds: Number.isFinite(ageSeconds) ? ageSeconds : null
227
+ };
228
+ } catch {
229
+ return { pid, command: null, ageSeconds: null };
230
+ }
231
+ };
232
+ var formatProcessSummary = (summary) => {
233
+ if (!summary) {
234
+ return "unknown process";
235
+ }
236
+ const age = typeof summary.ageSeconds === "number" ? `, age ${Math.floor(summary.ageSeconds / 60)}m${summary.ageSeconds % 60}s` : "";
237
+ const command = summary.command ? `, command: ${summary.command}` : "";
238
+ return `pid ${summary.pid}${age}${command}`;
239
+ };
240
+ var startServerIfNeeded = async (processGroup, serverPort, env) => {
241
+ const hasExistingServer = await isPortOpen(serverPort);
242
+ if (hasExistingServer) {
243
+ const summary = readProcessSummary(readListeningPid(serverPort));
244
+ console.warn(
245
+ `[dev] Reusing existing server on :${serverPort} (${formatProcessSummary(summary)}). If this looks stale, run "pnpm exec airjam reset local".`
246
+ );
247
+ return false;
248
+ }
249
+ processGroup.run("server", "pnpm", ["exec", "air-jam-server"], {
250
+ env: {
251
+ ...process.env,
252
+ ...env,
253
+ PORT: String(serverPort)
254
+ }
255
+ });
256
+ await waitForPort(serverPort, START_TIMEOUT_MS);
257
+ return true;
258
+ };
259
+ var startGameIfNeeded = async (processGroup, { gamePort, env, allowExistingGame }) => {
260
+ const hasExistingGame = await isPortOpen(gamePort);
261
+ if (hasExistingGame) {
262
+ if (allowExistingGame) {
263
+ console.log(`[dev] Reusing existing game on :${gamePort}`);
264
+ return false;
265
+ }
266
+ throw new Error(
267
+ `Port ${gamePort} is already in use. Stop the existing Vite dev server and retry.`
268
+ );
269
+ }
270
+ processGroup.run("game", process.execPath, [viteLauncher], {
271
+ env: {
272
+ ...process.env,
273
+ ...env
274
+ }
275
+ });
276
+ await waitForPort(gamePort, START_TIMEOUT_MS);
277
+ return true;
278
+ };
279
+ var ensurePreviewManagedServer = async ({ cwd, serverPort, env }) => {
280
+ const hasExistingServer = await isPortOpen(serverPort);
281
+ if (hasExistingServer) {
282
+ const summary = readProcessSummary(readListeningPid(serverPort));
283
+ console.warn(
284
+ `[dev] Reusing existing preview-managed server on :${serverPort} (${formatProcessSummary(summary)}). If this looks stale, run "pnpm exec airjam reset local".`
285
+ );
286
+ return false;
287
+ }
288
+ const airJamDir = path.join(cwd, ".airjam");
289
+ fs.mkdirSync(airJamDir, { recursive: true });
290
+ const logFile = path.join(cwd, PREVIEW_MANAGED_SERVER_LOG_RELATIVE_PATH);
291
+ const stateFile = path.join(cwd, PREVIEW_MANAGED_SERVER_STATE_RELATIVE_PATH);
292
+ const logFd = fs.openSync(logFile, "a");
293
+ const child = crossSpawn("pnpm", ["exec", "air-jam-server"], {
294
+ cwd,
295
+ env: {
296
+ ...process.env,
297
+ ...env,
298
+ PORT: String(serverPort)
299
+ },
300
+ detached: true,
301
+ stdio: ["ignore", logFd, logFd]
302
+ });
303
+ child.unref();
304
+ fs.closeSync(logFd);
305
+ fs.writeFileSync(
306
+ stateFile,
307
+ `${JSON.stringify(
308
+ {
309
+ pid: child.pid,
310
+ port: serverPort,
311
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
312
+ logFile
313
+ },
314
+ null,
315
+ 2
316
+ )}
317
+ `,
318
+ "utf8"
319
+ );
320
+ console.log(
321
+ `[dev] Started preview-managed background server on :${serverPort}`
322
+ );
323
+ console.log(`[dev] Background server log: ${logFile}`);
324
+ return true;
325
+ };
326
+ var runForegroundGame = ({ cwd, env }) => new Promise((resolve, reject) => {
327
+ const child = crossSpawn(process.execPath, [viteLauncher], {
328
+ cwd,
329
+ stdio: "inherit",
330
+ env: {
331
+ ...process.env,
332
+ ...env
333
+ }
334
+ });
335
+ child.on("error", reject);
336
+ child.on("exit", (code, signal) => {
337
+ if (signal) {
338
+ process.kill(process.pid, signal);
339
+ return;
340
+ }
341
+ resolve(code ?? 0);
342
+ });
343
+ process.on("SIGINT", () => child.kill("SIGINT"));
344
+ process.on("SIGTERM", () => child.kill("SIGTERM"));
345
+ });
346
+ var readPreviewProxyTargetPort = (publicPort) => {
347
+ try {
348
+ const lsofOutput = execFileSync(
349
+ "lsof",
350
+ ["-nP", `-iTCP:${publicPort}`, "-sTCP:LISTEN", "-Fp"],
351
+ {
352
+ encoding: "utf8",
353
+ stdio: ["ignore", "pipe", "ignore"]
354
+ }
355
+ );
356
+ const pidMatch = lsofOutput.match(/^p(\d+)$/m);
357
+ if (!pidMatch) {
358
+ return null;
359
+ }
360
+ const command = execFileSync("ps", ["-p", pidMatch[1], "-o", "command="], {
361
+ encoding: "utf8",
362
+ stdio: ["ignore", "pipe", "ignore"]
363
+ }).trim();
364
+ const proxyMatch = command.match(/preview-proxy\.mjs\s+(\d+)\s+(\d+)\b/);
365
+ if (!proxyMatch) {
366
+ return null;
367
+ }
368
+ const proxyPublicPort = Number(proxyMatch[1]);
369
+ const proxyTargetPort = Number(proxyMatch[2]);
370
+ if (!Number.isInteger(proxyPublicPort) || !Number.isInteger(proxyTargetPort) || proxyPublicPort !== publicPort) {
371
+ return null;
372
+ }
373
+ return proxyTargetPort;
374
+ } catch {
375
+ return null;
376
+ }
377
+ };
378
+ var resolvePreviewManagedPorts = async ({ port }) => {
379
+ const publicPort = port;
380
+ const publicPortInUse = await isPortOpen(publicPort);
381
+ if (!publicPortInUse) {
382
+ return {
383
+ publicPort,
384
+ vitePort: publicPort,
385
+ usesPreviewProxy: false
386
+ };
387
+ }
388
+ const proxyTargetPort = readPreviewProxyTargetPort(publicPort);
389
+ if (!proxyTargetPort) {
390
+ throw new Error(
391
+ `Port ${publicPort} is already in use. Close the existing process or choose a different VITE_PORT before running preview-managed dev.`
392
+ );
393
+ }
394
+ const targetPortInUse = await isPortOpen(proxyTargetPort);
395
+ if (targetPortInUse) {
396
+ throw new Error(
397
+ `Preview proxy port ${publicPort} is already forwarding to ${proxyTargetPort}, but that target port is also busy. Close the existing preview stack and retry.`
398
+ );
399
+ }
400
+ return {
401
+ publicPort,
402
+ vitePort: proxyTargetPort,
403
+ usesPreviewProxy: true
404
+ };
405
+ };
406
+ var validateGameDevMode = ({ args }) => {
407
+ if (args.webOnly && args.serverOnly) {
408
+ throw new Error("Cannot combine --web-only and --server-only.");
409
+ }
410
+ if (args.previewManaged && args.webOnly) {
411
+ throw new Error("Cannot combine --preview-managed and --web-only.");
412
+ }
413
+ if (args.previewManaged && args.serverOnly) {
414
+ throw new Error("Cannot combine --preview-managed and --server-only.");
415
+ }
416
+ if (args.previewManaged && args.allowExistingGame) {
417
+ throw new Error(
418
+ "Cannot combine --preview-managed and --allow-existing-game."
419
+ );
420
+ }
421
+ if (args.previewManaged && args.secure) {
422
+ throw new Error(
423
+ "Preview-managed mode does not support --secure. Use the normal `pnpm run dev` flow instead."
424
+ );
425
+ }
426
+ };
427
+ var runGameDevCli = async ({
428
+ cwd = process.cwd(),
429
+ argv = process.argv.slice(2),
430
+ env = process.env
431
+ } = {}) => {
432
+ loadEnvFile(path.join(cwd, ".env"), env);
433
+ loadEnvFile(path.join(cwd, ".env.local"), env);
434
+ const runtimeEnv = loadCreateAirJamRuntimeEnv({
435
+ env,
436
+ boundary: "create-airjam.dev"
437
+ });
438
+ const serverPort = runtimeEnv.AIR_JAM_SERVER_PORT;
439
+ const backendOrigin = resolveLocalBackendOrigin(runtimeEnv);
440
+ const secureRootDir = runtimeEnv.AIR_JAM_SECURE_ROOT ? path.resolve(cwd, runtimeEnv.AIR_JAM_SECURE_ROOT) : cwd;
441
+ const help = hasFlag(argv, "--help") || hasFlag(argv, "-h");
442
+ if (help) {
443
+ usage();
444
+ return;
445
+ }
446
+ const args = parseGameDevArgs(argv, runtimeEnv);
447
+ validateGameDevMode({ args });
448
+ const requestedGamePort = args.port || DEFAULT_GAME_PORT;
449
+ const previewManagedPorts = args.previewManaged ? await resolvePreviewManagedPorts({ port: requestedGamePort }) : null;
450
+ const publicGamePort = previewManagedPorts?.publicPort ?? requestedGamePort;
451
+ const viteGamePort = previewManagedPorts?.vitePort ?? requestedGamePort;
452
+ const processGroup = createProcessGroup();
453
+ processGroup.registerSignalHandlers();
454
+ try {
455
+ let secureState = null;
456
+ if (args.secure) {
457
+ secureState = loadSecureDevState({
458
+ cwd: secureRootDir,
459
+ mode: args.secureMode,
460
+ runtimeEnv,
461
+ gamePort: args.port
462
+ });
463
+ console.log(`[dev] Secure mode: ${secureState.mode}`);
464
+ console.log(`[dev] Public host: ${secureState.publicHost}`);
465
+ }
466
+ validateGameDevMode({ args });
467
+ const gameEnv = args.secure ? buildSecureGameEnv({
468
+ secureState,
469
+ webOnly: args.webOnly,
470
+ env: runtimeEnv,
471
+ backendOrigin
472
+ }) : {
473
+ VITE_AIR_JAM_RUNTIME_TOPOLOGY: serializeResolvedTopology(
474
+ buildStandaloneGameTopology({
475
+ surfaceRole: "host",
476
+ publicHost: getDefaultPublicHost(env, publicGamePort),
477
+ backendOrigin
478
+ })
479
+ ),
480
+ VITE_AIR_JAM_PUBLIC_HOST: getDefaultPublicHost(env, publicGamePort),
481
+ VITE_AIR_JAM_SERVER_URL: backendOrigin,
482
+ AIR_JAM_DEV_PROXY_BACKEND_URL: backendOrigin,
483
+ VITE_PORT: String(viteGamePort),
484
+ ...args.webOnly && runtimeEnv.VITE_AIR_JAM_SERVER_URL ? {
485
+ VITE_AIR_JAM_SERVER_URL: runtimeEnv.VITE_AIR_JAM_SERVER_URL
486
+ } : {}
487
+ };
488
+ gameEnv.AIR_JAM_BIND_HOST = runtimeEnv.AIR_JAM_BIND_HOST;
489
+ if (args.previewManaged) {
490
+ await ensurePreviewManagedServer({
491
+ cwd,
492
+ serverPort,
493
+ env: runtimeEnv
494
+ });
495
+ if (previewManagedPorts?.usesPreviewProxy) {
496
+ console.log(
497
+ `[dev] Detected browser preview proxy on :${publicGamePort}; binding Vite to :${viteGamePort} behind it.`
498
+ );
499
+ }
500
+ console.log(
501
+ "[dev] Preview-managed mode: foreground Vite is ready for browser/preview launch tools."
502
+ );
503
+ const exitCode = await runForegroundGame({
504
+ cwd,
505
+ env: gameEnv
506
+ });
507
+ process.exit(exitCode);
508
+ }
509
+ let startedServer = false;
510
+ if (!args.webOnly) {
511
+ startedServer = await startServerIfNeeded(
512
+ processGroup,
513
+ serverPort,
514
+ runtimeEnv
515
+ );
516
+ } else {
517
+ console.log(
518
+ "[dev] Web-only mode: skipping local Air Jam server startup."
519
+ );
520
+ }
521
+ let startedGame = false;
522
+ if (!args.serverOnly) {
523
+ startedGame = await startGameIfNeeded(processGroup, {
524
+ gamePort: viteGamePort,
525
+ env: gameEnv,
526
+ allowExistingGame: args.allowExistingGame
527
+ });
528
+ }
529
+ if (args.secure && secureState.mode === SECURE_MODE_TUNNEL) {
530
+ processGroup.run("cloudflared", "cloudflared", [
531
+ "tunnel",
532
+ "--config",
533
+ path.join(secureRootDir, ".cloudflared/config.yml"),
534
+ "run",
535
+ secureState.tunnelName
536
+ ]);
537
+ console.log(`Cloudflare tunnel: ${secureState.tunnelName}`);
538
+ }
539
+ if (!startedServer && !startedGame) {
540
+ await holdProcessOpen();
541
+ }
542
+ } catch (error) {
543
+ processGroup.shutdown(1);
544
+ throw error;
545
+ }
546
+ };
547
+
548
+ // runtime/topology.mjs
549
+ import { resolveProjectRuntimeTopology } from "@air-jam/sdk/runtime-topology";
550
+ import path2 from "path";
551
+ var SUPPORTED_MODES = /* @__PURE__ */ new Set([
552
+ "standalone-dev",
553
+ "self-hosted-production",
554
+ "hosted-release"
555
+ ]);
556
+ var getDefaultStandalonePublicHost = (env, gamePort) => {
557
+ const explicitPublicHost = env.VITE_AIR_JAM_PUBLIC_HOST;
558
+ if (explicitPublicHost) {
559
+ return explicitPublicHost;
560
+ }
561
+ const detectedIp = detectLocalIpv4();
562
+ if (!detectedIp) {
563
+ return `http://localhost:${gamePort}`;
564
+ }
565
+ return `http://${detectedIp}:${gamePort}`;
566
+ };
567
+ var requireConfiguredAppOrigin = (env, mode) => {
568
+ const appOrigin = env.VITE_AIR_JAM_PUBLIC_HOST || env.NEXT_PUBLIC_APP_URL;
569
+ if (appOrigin) {
570
+ return appOrigin;
571
+ }
572
+ throw new Error(
573
+ `Mode "${mode}" requires VITE_AIR_JAM_PUBLIC_HOST (or NEXT_PUBLIC_APP_URL) to be set.`
574
+ );
575
+ };
576
+ var resolveProjectSurfaceTopology = ({
577
+ runtimeMode,
578
+ secure,
579
+ env,
580
+ surfaceRole,
581
+ cwd
582
+ }) => {
583
+ if (runtimeMode === "standalone-dev") {
584
+ const gamePort = env.VITE_PORT ?? DEFAULT_GAME_PORT;
585
+ const secureState = secure ? loadSecureDevState({
586
+ cwd,
587
+ mode: SECURE_MODE_LOCAL,
588
+ runtimeEnv: env,
589
+ gamePort
590
+ }) : null;
591
+ const publicHost = secure ? secureState.publicHost : getDefaultStandalonePublicHost(env, gamePort);
592
+ return resolveProjectRuntimeTopology({
593
+ runtimeMode: secure ? "standalone-secure" : "standalone-dev",
594
+ surfaceRole,
595
+ appOrigin: publicHost,
596
+ backendOrigin: resolveLocalBackendOrigin(env),
597
+ publicHost,
598
+ secureTransport: secure
599
+ });
600
+ }
601
+ const appOrigin = requireConfiguredAppOrigin(env, runtimeMode);
602
+ return resolveProjectRuntimeTopology({
603
+ runtimeMode,
604
+ surfaceRole,
605
+ appOrigin,
606
+ backendOrigin: env.VITE_AIR_JAM_SERVER_URL || appOrigin,
607
+ publicHost: env.VITE_AIR_JAM_PUBLIC_HOST || appOrigin
608
+ });
609
+ };
610
+ var runProjectTopologyCli = async ({
611
+ cwd = process.cwd(),
612
+ argv = process.argv.slice(2),
613
+ env = process.env
614
+ } = {}) => {
615
+ if (hasFlag(argv, "--help") || hasFlag(argv, "-h")) {
616
+ console.log("Usage: airjam topology --mode=<mode> [--secure]");
617
+ console.log("");
618
+ console.log("Modes:");
619
+ console.log(
620
+ " standalone-dev Resolve standalone local game topology"
621
+ );
622
+ console.log(
623
+ " self-hosted-production Resolve self-hosted production topology"
624
+ );
625
+ console.log(
626
+ " hosted-release Resolve hosted Air Jam release topology"
627
+ );
628
+ return;
629
+ }
630
+ loadEnvFile(path2.join(cwd, ".env"), env);
631
+ loadEnvFile(path2.join(cwd, ".env.local"), env);
632
+ const runtimeEnv = loadCreateAirJamRuntimeEnv({
633
+ env,
634
+ boundary: "create-airjam.topology"
635
+ });
636
+ const mode = getFlagValue(argv, "--mode")?.trim();
637
+ if (!mode || !SUPPORTED_MODES.has(mode)) {
638
+ throw new Error(
639
+ "Missing or unsupported --mode. Use standalone-dev, self-hosted-production, or hosted-release."
640
+ );
641
+ }
642
+ const secure = hasFlag(argv, "--secure");
643
+ if (secure && mode !== "standalone-dev") {
644
+ throw new Error(
645
+ `--secure is only supported with --mode=standalone-dev. ${mode} should express transport through its configured URL values.`
646
+ );
647
+ }
648
+ const surfaces = Object.fromEntries(
649
+ ["host", "controller"].map((surfaceRole) => [
650
+ surfaceRole,
651
+ resolveProjectSurfaceTopology({
652
+ runtimeMode: mode,
653
+ secure,
654
+ env: runtimeEnv,
655
+ surfaceRole,
656
+ cwd
657
+ })
658
+ ])
659
+ );
660
+ process.stdout.write(
661
+ `${JSON.stringify(
662
+ {
663
+ mode,
664
+ secure,
665
+ surfaces
666
+ },
667
+ null,
668
+ 2
669
+ )}
670
+ `
671
+ );
672
+ };
673
+
674
+ // src/game-settings.ts
675
+ import { keepGameSettings } from "@air-jam/devtools/game-settings";
676
+ import { inspectGame } from "@air-jam/devtools/games";
677
+ function registerGameSettingsCommand(game) {
678
+ game.command("settings").description("Keep local game settings in source").command("keep").description("Rewrite declared default literals with chosen values").requiredOption(
679
+ "--set <name=value>",
680
+ "Setting to keep; repeat for multiple settings",
681
+ (value, previous = []) => [...previous, value]
682
+ ).option("--dir <path>", "Game project directory", process.cwd()).option("--json", "Print one machine-readable JSON document", false).action(async (input) => {
683
+ const { declaration } = await inspectGame({ cwd: input.dir });
684
+ const values = {};
685
+ for (const assignment of input.set) {
686
+ const split = assignment.indexOf("=");
687
+ if (split < 1)
688
+ throw new Error("AJ_SETTING_INVALID: Use --set name=value.");
689
+ const key = assignment.slice(0, split);
690
+ const raw = assignment.slice(split + 1);
691
+ if (Object.hasOwn(values, key))
692
+ throw new Error(
693
+ `AJ_SETTING_INVALID: ${key} was provided more than once.`
694
+ );
695
+ const setting = declaration.settings && Object.hasOwn(declaration.settings, key) ? declaration.settings[key] : void 0;
696
+ if (!setting)
697
+ throw new Error(
698
+ `AJ_SETTING_UNKNOWN: ${key} is not declared by this game.`
699
+ );
700
+ values[key] = setting.kind === "number" && raw.trim() !== "" ? Number(raw) : setting.kind === "boolean" && ["true", "false"].includes(raw) ? raw === "true" : raw;
701
+ }
702
+ const result = await keepGameSettings({ cwd: input.dir, values });
703
+ if (input.json) process.stdout.write(`${JSON.stringify(result)}
704
+ `);
705
+ else
706
+ for (const entry of result.kept)
707
+ console.log(
708
+ `${entry.key}: ${entry.from} -> ${entry.to}${entry.from === entry.to ? " (unchanged)" : ""} (${result.file})`
709
+ );
710
+ });
711
+ }
712
+
713
+ // src/mcp.ts
714
+ import { inspectProject } from "@air-jam/devtools/context";
715
+ import {
716
+ AIRJAM_PROJECT_MCP_FILE,
717
+ inspectMcpProjectSetup,
718
+ renderMcpClientProfile,
719
+ writeProjectLocalMcpConfig
720
+ } from "@air-jam/devtools/mcp-config";
721
+ import kleur from "kleur";
722
+ var printConfigSnippet = (value) => {
723
+ console.log(JSON.stringify(value, null, 2));
724
+ };
725
+ var runMcpDoctor = async ({
726
+ dir,
727
+ json = false
728
+ }) => {
729
+ const project = await inspectProject({ cwd: dir });
730
+ const setup = await inspectMcpProjectSetup({ cwd: dir });
731
+ if (json) {
732
+ process.stdout.write(
733
+ `${JSON.stringify({ projectMode: project.context.mode, ...setup }, null, 2)}
734
+ `
735
+ );
736
+ return;
737
+ }
738
+ console.log(kleur.cyan("Air Jam MCP doctor\n"));
739
+ console.log(`Project root: ${setup.projectDir}`);
740
+ console.log(`Project mode: ${project.context.mode}`);
741
+ console.log(
742
+ `MCP dependency: ${setup.package.dependencyPresent ? kleur.green("present") : kleur.yellow("missing")}`
743
+ );
744
+ console.log(
745
+ `MCP script: ${setup.package.scriptPresent ? kleur.green("present") : kleur.yellow("missing")}`
746
+ );
747
+ console.log(
748
+ `Portable declaration: ${setup.portableDeclaration.present ? kleur.green(setup.portableDeclaration.configPath) : kleur.yellow(`missing (${AIRJAM_PROJECT_MCP_FILE})`)}`
749
+ );
750
+ console.log(
751
+ `Codex registration: ${setup.clients.codex.registered ? kleur.green("present") : kleur.yellow("missing")}`
752
+ );
753
+ console.log(
754
+ `Claude Desktop registration: ${setup.clients.claudeDesktop.registered ? kleur.green("present") : kleur.yellow("missing")}`
755
+ );
756
+ console.log("");
757
+ console.log("Recommended project-local MCP config:\n");
758
+ printConfigSnippet(setup.recommendedConfig);
759
+ };
760
+ var runMcpInit = async ({
761
+ dir,
762
+ force,
763
+ json = false
764
+ }) => {
765
+ const inspection = await writeProjectLocalMcpConfig({
766
+ cwd: dir,
767
+ force: force === true
768
+ });
769
+ if (json) {
770
+ process.stdout.write(`${JSON.stringify(inspection, null, 2)}
771
+ `);
772
+ } else {
773
+ console.log(
774
+ kleur.green(
775
+ `Wrote portable MCP declaration to ${inspection.portableDeclaration.configPath}`
776
+ )
777
+ );
778
+ }
779
+ };
780
+ var runMcpConfig = async ({
781
+ dir,
782
+ profile = "portable",
783
+ json = false
784
+ }) => {
785
+ if (!["portable", "codex", "claude-desktop"].includes(profile)) {
786
+ throw new Error(
787
+ `Unknown MCP profile "${profile}". Use portable, codex, or claude-desktop.`
788
+ );
789
+ }
790
+ const setup = await inspectMcpProjectSetup({ cwd: dir });
791
+ const rendered = renderMcpClientProfile({
792
+ profile,
793
+ projectDir: setup.projectDir
794
+ });
795
+ process.stdout.write(
796
+ json ? `${JSON.stringify(rendered, null, 2)}
797
+ ` : rendered.content
798
+ );
799
+ };
800
+
801
+ // src/rooms.ts
802
+ import {
803
+ describeLinkProblem,
804
+ ROOMS_CHECK_SCENARIOS,
805
+ runRoomsCheck
806
+ } from "@air-jam/devtools/rooms-check";
807
+ import kleur2 from "kleur";
808
+ import { z } from "zod";
809
+ var positive = z.coerce.number().int().positive();
810
+ var optionsSchema = z.object({
811
+ scenario: z.array(z.enum(ROOMS_CHECK_SCENARIOS)).optional(),
812
+ json: z.boolean(),
813
+ origin: z.url().optional(),
814
+ hostCredentialCommand: z.string().min(1).optional(),
815
+ connectionsPerMinute: positive.optional(),
816
+ briefFreezeMs: positive.optional(),
817
+ stallMs: positive.optional(),
818
+ idleMs: positive.optional(),
819
+ crowdDurationMs: positive.optional(),
820
+ loadRooms: positive.optional(),
821
+ loadPhones: z.coerce.number().int().min(1).max(16).optional(),
822
+ loadDurationMs: positive.optional(),
823
+ loadWorkers: positive.optional()
824
+ });
825
+ var describeProblems = (result) => {
826
+ const byCause = /* @__PURE__ */ new Map();
827
+ for (const { device, problem } of result.connectionProblems) {
828
+ const cause = describeLinkProblem(problem);
829
+ const entry = byCause.get(cause) ?? { count: 0, devices: /* @__PURE__ */ new Set() };
830
+ entry.count += 1;
831
+ entry.devices.add(device);
832
+ byCause.set(cause, entry);
833
+ }
834
+ return [...byCause].map(
835
+ ([cause, { count, devices }]) => ` connection ${cause}: ${count} on ${[...devices].join(", ")}`
836
+ );
837
+ };
838
+ var describeResult = (result) => [
839
+ `${result.passed ? kleur2.green("pass") : kleur2.red("FAIL")} ${result.scenario} (${result.durationMs} ms)${result.failure ? `: ${result.failure}` : ""}`,
840
+ ...result.passed ? [` ${JSON.stringify(result.measurements)}`] : [],
841
+ ...describeProblems(result)
842
+ ].join("\n");
843
+ function registerRoomsCommand(program) {
844
+ program.command("rooms").description("Check room servers").command("check <url>").description(
845
+ "Run the room acceptance scenarios against a rooms origin, with the host and each phone as separate processes that are frozen, killed and replaced. Every scenario but load runs by default; load opens 100 rooms and 400 phones from this machine, so the target must allow that many connections from one address or the check must pace them (--connections-per-minute)."
846
+ ).option(
847
+ "--scenario <name>",
848
+ `Scenario to run; repeat for more (${ROOMS_CHECK_SCENARIOS.join(", ")})`,
849
+ (value, previous = []) => [...previous, value]
850
+ ).option("--json", "Print one machine-readable JSON document", false).option(
851
+ "--origin <origin>",
852
+ "The page origin every connection sends as its Origin header"
853
+ ).option(
854
+ "--host-credential-command <command>",
855
+ "A shell command printing one fresh host credential, run for every host that opens a room"
856
+ ).option(
857
+ "--connections-per-minute <count>",
858
+ "At most this many connection opens in any minute, across every device (default unpaced)"
859
+ ).option(
860
+ "--brief-freeze-ms <ms>",
861
+ "A phone lock shorter than the server's liveness window (default 5000)"
862
+ ).option(
863
+ "--stall-ms <ms>",
864
+ "How long a phone's network stalls while it keeps pressing (default 10000)"
865
+ ).option(
866
+ "--idle-ms <ms>",
867
+ "How long the background-host room idles (default 60000)"
868
+ ).option(
869
+ "--crowd-duration-ms <ms>",
870
+ "How long sixteen phones play (default 10000)"
871
+ ).option(
872
+ "--load-rooms <count>",
873
+ "Rooms the load scenario opens (default 100)"
874
+ ).option("--load-phones <count>", "Phones per load room (default 4)").option(
875
+ "--load-duration-ms <ms>",
876
+ "How long the load scenario measures (default 60000)"
877
+ ).option("--load-workers <count>", "Processes the load rooms run in").action(async (url, raw) => {
878
+ const parsed = optionsSchema.safeParse(raw);
879
+ if (!parsed.success) throw new Error(z.prettifyError(parsed.error));
880
+ const options = parsed.data;
881
+ const report = await runRoomsCheck({
882
+ url,
883
+ origin: options.origin,
884
+ hostCredentialCommand: options.hostCredentialCommand,
885
+ connectionsPerMinute: options.connectionsPerMinute,
886
+ scenarios: options.scenario,
887
+ briefFreezeMs: options.briefFreezeMs,
888
+ stallMs: options.stallMs,
889
+ idleMs: options.idleMs,
890
+ crowdDurationMs: options.crowdDurationMs,
891
+ load: {
892
+ rooms: options.loadRooms,
893
+ phonesPerRoom: options.loadPhones,
894
+ durationMs: options.loadDurationMs,
895
+ workers: options.loadWorkers
896
+ },
897
+ onResult: options.json ? void 0 : (result) => console.log(describeResult(result))
898
+ });
899
+ if (options.json) process.stdout.write(`${JSON.stringify(report)}
900
+ `);
901
+ if (!report.passed) process.exitCode = 1;
902
+ });
903
+ }
904
+
905
+ // src/session.ts
906
+ import { inspectProject as inspectProject2 } from "@air-jam/devtools/context";
907
+ import {
908
+ captureGameSessionVisuals,
909
+ closeGameSession,
910
+ controlGameSessionParticipant,
911
+ gameSessionOperationSchemas,
912
+ invokeGameSessionAction,
913
+ observeGameSession,
914
+ openGameSession,
915
+ readGameSession,
916
+ readGameSettings,
917
+ sendGameSessionInput,
918
+ updateGameSettings
919
+ } from "@air-jam/devtools/game-session";
920
+ import {
921
+ getGameSessionBrokerStatus,
922
+ stopGameSessionBroker
923
+ } from "@air-jam/devtools/game-session-broker";
924
+ var resolveProjectDir = async (dir) => (await inspectProject2({ cwd: dir })).context.rootDir;
925
+ var request = async ({
926
+ dir,
927
+ operation
928
+ }) => {
929
+ switch (operation.operation) {
930
+ case "open":
931
+ return openGameSession({ ...operation.input, cwd: dir });
932
+ case "read":
933
+ return readGameSession({ ...operation.input, cwd: dir });
934
+ case "observe":
935
+ return observeGameSession({ ...operation.input, cwd: dir });
936
+ case "settings-read":
937
+ return readGameSettings({ ...operation.input, cwd: dir });
938
+ case "settings-update":
939
+ return updateGameSettings({ ...operation.input, cwd: dir });
940
+ case "control":
941
+ return controlGameSessionParticipant({ ...operation.input, cwd: dir });
942
+ case "input":
943
+ return sendGameSessionInput({ ...operation.input, cwd: dir });
944
+ case "invoke":
945
+ return invokeGameSessionAction({ ...operation.input, cwd: dir });
946
+ case "capture":
947
+ return captureGameSessionVisuals({ ...operation.input, cwd: dir });
948
+ case "close":
949
+ return closeGameSession({ ...operation.input, cwd: dir });
950
+ default:
951
+ throw new Error("Unsupported session operation.");
952
+ }
953
+ };
954
+ var parseJsonValue = (value) => {
955
+ try {
956
+ return JSON.parse(value);
957
+ } catch {
958
+ return value;
959
+ }
960
+ };
961
+ var parseJsonObject = (value) => {
962
+ const parsed = JSON.parse(value);
963
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
964
+ throw new Error("Expected a JSON object.");
965
+ }
966
+ return parsed;
967
+ };
968
+ var runSessionBrokerStatus = async ({
969
+ dir
970
+ }) => {
971
+ return getGameSessionBrokerStatus(await resolveProjectDir(dir));
972
+ };
973
+ var runSessionBrokerStop = async ({
974
+ dir
975
+ }) => stopGameSessionBroker(await resolveProjectDir(dir));
976
+ var openSession = async ({
977
+ dir,
978
+ ...input
979
+ }) => request({ dir, operation: { operation: "open", input } });
980
+ var readSession = async ({
981
+ dir,
982
+ gameSessionId,
983
+ timeoutMs
984
+ }) => request({
985
+ dir,
986
+ operation: {
987
+ operation: "read",
988
+ input: { gameSessionId, timeoutMs }
989
+ }
990
+ });
991
+ var sendSessionInput = async ({
992
+ dir,
993
+ gameSessionId,
994
+ input
995
+ }) => request({
996
+ dir,
997
+ operation: {
998
+ operation: "input",
999
+ input: gameSessionOperationSchemas.input.parse({ gameSessionId, input })
1000
+ }
1001
+ });
1002
+ var invokeSessionAction = async ({
1003
+ dir,
1004
+ gameSessionId,
1005
+ actionId,
1006
+ payload,
1007
+ timeoutMs
1008
+ }) => request({
1009
+ dir,
1010
+ operation: {
1011
+ operation: "invoke",
1012
+ input: gameSessionOperationSchemas.invoke.parse({
1013
+ gameSessionId,
1014
+ actionId,
1015
+ payload,
1016
+ timeoutMs
1017
+ })
1018
+ }
1019
+ });
1020
+ var captureSessionVisuals = async ({
1021
+ dir,
1022
+ gameSessionId,
1023
+ timeoutMs
1024
+ }) => request({
1025
+ dir,
1026
+ operation: {
1027
+ operation: "capture",
1028
+ input: { gameSessionId, timeoutMs }
1029
+ }
1030
+ });
1031
+ var closeSession = async ({
1032
+ dir,
1033
+ gameSessionId
1034
+ }) => request({
1035
+ dir,
1036
+ operation: { operation: "close", input: { gameSessionId } }
1037
+ });
1038
+ var controlSessionParticipant = async ({
1039
+ dir,
1040
+ gameSessionId,
1041
+ command
1042
+ }) => request({
1043
+ dir,
1044
+ operation: {
1045
+ operation: "control",
1046
+ input: gameSessionOperationSchemas.control.parse({
1047
+ ...command,
1048
+ gameSessionId
1049
+ })
1050
+ }
1051
+ });
1052
+
1053
+ // src/version.ts
1054
+ import fs2 from "fs";
1055
+ var manifest = JSON.parse(
1056
+ fs2.readFileSync(new URL("../package.json", import.meta.url), "utf8")
1057
+ );
1058
+ if (typeof manifest.version !== "string" || manifest.version.length === 0) {
1059
+ throw new Error("@air-jam/cli package version is missing.");
1060
+ }
1061
+ var AIR_JAM_CLI_VERSION = manifest.version;
1062
+
1063
+ // src/index.ts
1064
+ var normalizeRuntimeCliArgv = (argv) => argv.filter((value) => value !== "--");
1065
+ var resolveActionOptions = (value) => {
1066
+ if (value && typeof value === "object" && "opts" in value && typeof value.opts === "function") {
1067
+ return value.opts();
1068
+ }
1069
+ return value;
1070
+ };
1071
+ var printReleaseIssues = (issues) => {
1072
+ for (const issue of issues) {
1073
+ const color = issue.severity === "error" ? kleur3.red : kleur3.yellow;
1074
+ const prefix = issue.severity === "error" ? "error" : "warning";
1075
+ console.log(color(`- ${prefix}: ${issue.message}`));
1076
+ if (issue.path) {
1077
+ console.log(kleur3.dim(` path: ${issue.path}`));
1078
+ }
1079
+ }
1080
+ };
1081
+ var printReleaseDoctor = async ({
1082
+ dir,
1083
+ distDir
1084
+ }) => {
1085
+ const doctor = await inspectLocalRelease({
1086
+ cwd: path3.resolve(dir || process.cwd()),
1087
+ distDir
1088
+ });
1089
+ console.log(
1090
+ doctor.canBundle ? kleur3.green("\n\u2713 Hosted release doctor passed\n") : kleur3.red("\n\u2717 Hosted release doctor failed\n")
1091
+ );
1092
+ console.log(`Project: ${kleur3.cyan(doctor.projectDir)}`);
1093
+ console.log(`Dist: ${kleur3.cyan(doctor.distDir)}`);
1094
+ console.log(
1095
+ `Build script: ${doctor.buildScript ? kleur3.cyan("present") : kleur3.red("missing")}`
1096
+ );
1097
+ console.log(
1098
+ `Metadata export: ${doctor.gameSlug ? kleur3.cyan("present") : kleur3.yellow("missing")}`
1099
+ );
1100
+ console.log(
1101
+ `Hosted contract: ${kleur3.dim(
1102
+ `${doctor.hostedContract.hostPath} (host), ${doctor.hostedContract.controllerPath} (controller), ${doctor.hostedContract.manifestPath} manifest`
1103
+ )}`
1104
+ );
1105
+ if (doctor.issues.length > 0) {
1106
+ console.log("");
1107
+ printReleaseIssues(doctor.issues);
1108
+ }
1109
+ if (!doctor.canBundle) {
1110
+ process.exitCode = 1;
1111
+ }
1112
+ };
1113
+ var runReleaseBundleCommand = async ({
1114
+ dir,
1115
+ distDir,
1116
+ out,
1117
+ skipBuild = false
1118
+ }) => {
1119
+ const result = await bundleLocalRelease({
1120
+ cwd: path3.resolve(dir || process.cwd()),
1121
+ distDir,
1122
+ out,
1123
+ skipBuild
1124
+ });
1125
+ if (result.buildResult?.stdout.trim()) {
1126
+ console.log(result.buildResult.stdout.trimEnd());
1127
+ }
1128
+ if (result.buildResult?.stderr.trim()) {
1129
+ console.error(result.buildResult.stderr.trimEnd());
1130
+ }
1131
+ console.log(kleur3.green("\n\u2713 Hosted release bundle created\n"));
1132
+ console.log(`Artifact: ${kleur3.cyan(result.outputFile)}`);
1133
+ console.log(
1134
+ kleur3.dim(
1135
+ `Hosted contract: / (host), /controller (controller), .airjam/release-manifest.json manifest`
1136
+ )
1137
+ );
1138
+ console.log(
1139
+ kleur3.dim(
1140
+ `Validated ${result.validation.fileCount} files (${result.validation.extractedSizeBytes} bytes extracted)`
1141
+ )
1142
+ );
1143
+ };
1144
+ var runReleaseValidateCommand = async ({
1145
+ dir,
1146
+ distDir,
1147
+ bundle,
1148
+ skipBuild = false
1149
+ }) => {
1150
+ const validation = await validateLocalRelease({
1151
+ cwd: path3.resolve(dir || process.cwd()),
1152
+ distDir,
1153
+ bundlePath: bundle,
1154
+ skipBuild
1155
+ });
1156
+ console.log(
1157
+ validation.ok ? kleur3.green("\n\u2713 Hosted release validation passed\n") : kleur3.red("\n\u2717 Hosted release validation failed\n")
1158
+ );
1159
+ if (validation.source.kind === "bundle") {
1160
+ console.log(`Bundle: ${kleur3.cyan(validation.source.bundlePath)}`);
1161
+ } else {
1162
+ console.log(`Project: ${kleur3.cyan(validation.source.projectDir)}`);
1163
+ console.log(`Dist: ${kleur3.cyan(validation.source.distDir)}`);
1164
+ }
1165
+ console.log(
1166
+ kleur3.dim(
1167
+ `Validated ${validation.fileCount} files (${validation.extractedSizeBytes} bytes extracted)`
1168
+ )
1169
+ );
1170
+ if (validation.issues.length > 0) {
1171
+ console.log("");
1172
+ printReleaseIssues(validation.issues);
1173
+ }
1174
+ if (!validation.ok) {
1175
+ process.exitCode = 1;
1176
+ }
1177
+ };
1178
+ var runReleaseListCommand = async ({
1179
+ platformUrl,
1180
+ game
1181
+ }) => {
1182
+ if (game?.trim()) {
1183
+ const result2 = await listPlatformReleases({
1184
+ platformUrl,
1185
+ slugOrId: game.trim()
1186
+ });
1187
+ console.log(
1188
+ kleur3.green(
1189
+ `
1190
+ \u2713 Hosted releases for ${result2.game.name}${result2.game.slug ? ` (${result2.game.slug})` : ""}
1191
+ `
1192
+ )
1193
+ );
1194
+ if (result2.releases.length === 0) {
1195
+ console.log(kleur3.dim("No hosted releases found."));
1196
+ return;
1197
+ }
1198
+ for (const release of result2.releases) {
1199
+ console.log(
1200
+ `${kleur3.cyan(release.id)} ${kleur3.yellow(release.status)} ${release.versionLabel ?? "(untitled)"} ${kleur3.dim(release.createdAt)} ${kleur3.cyan(release.playUrl)}`
1201
+ );
1202
+ }
1203
+ return;
1204
+ }
1205
+ const result = await listPlatformReleaseTargets({ platformUrl });
1206
+ console.log(kleur3.green("\n\u2713 Hosted release targets\n"));
1207
+ if (result.games.length === 0) {
1208
+ console.log(kleur3.dim("No owned hosted games found."));
1209
+ return;
1210
+ }
1211
+ for (const ownedGame of result.games) {
1212
+ console.log(
1213
+ `${kleur3.cyan(ownedGame.id)} ${ownedGame.slug ? kleur3.yellow(ownedGame.slug) : kleur3.dim("(no slug)")} ${ownedGame.name}`
1214
+ );
1215
+ }
1216
+ };
1217
+ var formatArcadeListing = ({
1218
+ status,
1219
+ reason
1220
+ }) => {
1221
+ const labels = {
1222
+ not_requested: "Not requested",
1223
+ awaiting_approval: "Waiting for approval",
1224
+ approved: "Listed in Arcade",
1225
+ rejected: "Not approved"
1226
+ };
1227
+ return status === "rejected" && reason ? `${labels[status]}: ${reason}` : labels[status];
1228
+ };
1229
+ var printHostedGame = ({
1230
+ game,
1231
+ heading
1232
+ }) => {
1233
+ console.log(kleur3.green(`
1234
+ \u2713 ${heading}
1235
+ `));
1236
+ console.log(`ID: ${kleur3.cyan(game.id)}`);
1237
+ console.log(`Name: ${kleur3.cyan(game.name)}`);
1238
+ console.log(`Slug: ${kleur3.cyan(game.slug ?? "(none)")}`);
1239
+ console.log(`Arcade visibility: ${kleur3.cyan(game.arcadeVisibility)}`);
1240
+ console.log(
1241
+ `Arcade listing: ${kleur3.cyan(formatArcadeListing(game.arcadeListing))}`
1242
+ );
1243
+ console.log(`Description: ${kleur3.cyan(game.description ?? "(none)")}`);
1244
+ console.log(`Preview URL: ${kleur3.cyan(game.url ?? "(none)")}`);
1245
+ console.log(`Source URL: ${kleur3.cyan(game.sourceUrl ?? "(none)")}`);
1246
+ console.log(`Template ID: ${kleur3.cyan(game.templateId ?? "(none)")}`);
1247
+ console.log(`Created: ${kleur3.cyan(game.createdAt)}`);
1248
+ console.log(`Updated: ${kleur3.cyan(game.updatedAt)}`);
1249
+ };
1250
+ var resolveCreateGameInput = async ({
1251
+ dir,
1252
+ name,
1253
+ slug,
1254
+ description,
1255
+ previewUrl,
1256
+ sourceUrl,
1257
+ templateId,
1258
+ arcadeVisibility
1259
+ }) => {
1260
+ const localDefaults = dir ? await readLocalHostedGameDefaults({
1261
+ cwd: path3.resolve(dir)
1262
+ }) : null;
1263
+ const resolvedName = name?.trim() || localDefaults?.metadata.name || localDefaults?.template.name || null;
1264
+ if (!resolvedName) {
1265
+ throw new Error(
1266
+ "Game name is required. Pass --name or point --dir at a game with declared metadata."
1267
+ );
1268
+ }
1269
+ const resolvedSlug = slug?.trim() || localDefaults?.metadata.slug;
1270
+ const resolvedDescription = description !== void 0 ? description.trim() || void 0 : localDefaults?.metadata.description || localDefaults?.template.description;
1271
+ const resolvedSourceUrl = sourceUrl?.trim() || localDefaults?.sourceUrl;
1272
+ const resolvedTemplateId = templateId?.trim() || localDefaults?.template.id;
1273
+ return {
1274
+ input: {
1275
+ name: resolvedName,
1276
+ ...resolvedSlug ? { slug: resolvedSlug } : {},
1277
+ ...resolvedDescription ? { description: resolvedDescription } : {},
1278
+ ...previewUrl?.trim() ? { url: previewUrl.trim() } : {},
1279
+ ...resolvedSourceUrl ? { sourceUrl: resolvedSourceUrl } : {},
1280
+ ...resolvedTemplateId ? { templateId: resolvedTemplateId } : {},
1281
+ ...arcadeVisibility ? { arcadeVisibility } : {}
1282
+ },
1283
+ localDefaults
1284
+ };
1285
+ };
1286
+ var runGameListCommand = async ({
1287
+ platformUrl,
1288
+ json
1289
+ }) => {
1290
+ const result = await listPlatformGames({ platformUrl });
1291
+ if (json) {
1292
+ process.stdout.write(`${JSON.stringify(result, null, 2)}
1293
+ `);
1294
+ return;
1295
+ }
1296
+ console.log(kleur3.green("\n\u2713 Hosted games\n"));
1297
+ if (result.games.length === 0) {
1298
+ console.log(kleur3.dim("No owned hosted games found."));
1299
+ return;
1300
+ }
1301
+ for (const game of result.games) {
1302
+ console.log(
1303
+ `${kleur3.cyan(game.id)} ${game.slug ? kleur3.yellow(game.slug) : kleur3.dim("(no slug)")} ${game.name} ${kleur3.dim(game.arcadeVisibility)} ${formatArcadeListing(game.arcadeListing)}`
1304
+ );
1305
+ }
1306
+ };
1307
+ var runGameInspectCommand = async ({
1308
+ platformUrl,
1309
+ game,
1310
+ json
1311
+ }) => {
1312
+ const result = await inspectPlatformGame({
1313
+ platformUrl,
1314
+ slugOrId: game
1315
+ });
1316
+ if (json) {
1317
+ process.stdout.write(`${JSON.stringify(result, null, 2)}
1318
+ `);
1319
+ return;
1320
+ }
1321
+ printHostedGame({
1322
+ game: result.game,
1323
+ heading: "Hosted game"
1324
+ });
1325
+ };
1326
+ var runGameCreateCommand = async ({
1327
+ platformUrl,
1328
+ dir,
1329
+ name,
1330
+ slug,
1331
+ description,
1332
+ previewUrl,
1333
+ sourceUrl,
1334
+ templateId,
1335
+ arcadeVisibility
1336
+ }) => {
1337
+ const { input } = await resolveCreateGameInput({
1338
+ dir,
1339
+ name,
1340
+ slug,
1341
+ description,
1342
+ previewUrl,
1343
+ sourceUrl,
1344
+ templateId,
1345
+ arcadeVisibility
1346
+ });
1347
+ const result = await createPlatformGame({
1348
+ platformUrl,
1349
+ input
1350
+ });
1351
+ printHostedGame({
1352
+ game: result.game,
1353
+ heading: "Hosted game created"
1354
+ });
1355
+ };
1356
+ var resolveUpdateGamePatch = ({
1357
+ name,
1358
+ slug,
1359
+ description,
1360
+ clearDescription = false,
1361
+ previewUrl,
1362
+ clearPreviewUrl = false,
1363
+ sourceUrl,
1364
+ clearSourceUrl = false,
1365
+ templateId,
1366
+ clearTemplateId = false,
1367
+ arcadeVisibility
1368
+ }) => {
1369
+ if (description !== void 0 && clearDescription) {
1370
+ throw new Error(
1371
+ "Use either --description or --clear-description, not both."
1372
+ );
1373
+ }
1374
+ if (previewUrl !== void 0 && clearPreviewUrl) {
1375
+ throw new Error(
1376
+ "Use either --preview-url or --clear-preview-url, not both."
1377
+ );
1378
+ }
1379
+ if (sourceUrl !== void 0 && clearSourceUrl) {
1380
+ throw new Error("Use either --source-url or --clear-source-url, not both.");
1381
+ }
1382
+ if (templateId !== void 0 && clearTemplateId) {
1383
+ throw new Error(
1384
+ "Use either --template-id or --clear-template-id, not both."
1385
+ );
1386
+ }
1387
+ const patch = {
1388
+ ...name?.trim() ? { name: name.trim() } : {},
1389
+ ...slug?.trim() ? { slug: slug.trim() } : {},
1390
+ ...description !== void 0 ? { description: description.trim() || null } : clearDescription ? { description: null } : {},
1391
+ ...previewUrl !== void 0 ? { url: previewUrl.trim() || null } : clearPreviewUrl ? { url: null } : {},
1392
+ ...sourceUrl !== void 0 ? { sourceUrl: sourceUrl.trim() || null } : clearSourceUrl ? { sourceUrl: null } : {},
1393
+ ...templateId !== void 0 ? { templateId: templateId.trim() || null } : clearTemplateId ? { templateId: null } : {},
1394
+ ...arcadeVisibility ? { arcadeVisibility } : {}
1395
+ };
1396
+ if (Object.keys(patch).length === 0) {
1397
+ throw new Error("No hosted game changes were provided.");
1398
+ }
1399
+ return patch;
1400
+ };
1401
+ var runGameUpdateCommand = async ({
1402
+ platformUrl,
1403
+ game,
1404
+ name,
1405
+ slug,
1406
+ description,
1407
+ clearDescription,
1408
+ previewUrl,
1409
+ clearPreviewUrl,
1410
+ sourceUrl,
1411
+ clearSourceUrl,
1412
+ templateId,
1413
+ clearTemplateId,
1414
+ arcadeVisibility
1415
+ }) => {
1416
+ const result = await updatePlatformGame({
1417
+ platformUrl,
1418
+ slugOrId: game,
1419
+ input: resolveUpdateGamePatch({
1420
+ name,
1421
+ slug,
1422
+ description,
1423
+ clearDescription,
1424
+ previewUrl,
1425
+ clearPreviewUrl,
1426
+ sourceUrl,
1427
+ clearSourceUrl,
1428
+ templateId,
1429
+ clearTemplateId,
1430
+ arcadeVisibility
1431
+ })
1432
+ });
1433
+ printHostedGame({
1434
+ game: result.game,
1435
+ heading: "Hosted game updated"
1436
+ });
1437
+ };
1438
+ var runReleaseInspectCommand = async ({
1439
+ platformUrl,
1440
+ releaseId
1441
+ }) => {
1442
+ const result = await inspectPlatformRelease({
1443
+ platformUrl,
1444
+ releaseId
1445
+ });
1446
+ const release = result.release;
1447
+ console.log(kleur3.green("\n\u2713 Hosted release\n"));
1448
+ console.log(`Release: ${kleur3.cyan(release.id)}`);
1449
+ console.log(`Game: ${kleur3.cyan(release.game.name)}`);
1450
+ console.log(`Status: ${kleur3.cyan(release.status)}`);
1451
+ console.log(`Version: ${kleur3.cyan(release.versionLabel ?? "(untitled)")}`);
1452
+ console.log(`Created: ${kleur3.cyan(release.createdAt)}`);
1453
+ console.log(`Play URL: ${kleur3.cyan(release.playUrl)}`);
1454
+ if (release.hostUrl) {
1455
+ console.log(`Host URL: ${kleur3.cyan(release.hostUrl)}`);
1456
+ }
1457
+ if (release.controllerUrl) {
1458
+ console.log(`Controller URL: ${kleur3.cyan(release.controllerUrl)}`);
1459
+ }
1460
+ const formatGeneration = (generation) => `${kleur3.cyan(generation.id)} (#${generation.sequence}, ${kleur3.yellow(generation.status)})`;
1461
+ console.log(
1462
+ `Candidate generation: ${release.candidateGeneration ? formatGeneration(release.candidateGeneration) : kleur3.dim("none")}`
1463
+ );
1464
+ console.log(
1465
+ `Promoted generation: ${release.promotedGeneration ? formatGeneration(release.promotedGeneration) : kleur3.dim("none")}`
1466
+ );
1467
+ if (release.generations.length > 0) {
1468
+ console.log("");
1469
+ console.log(kleur3.dim("Generation history:"));
1470
+ for (const generation of release.generations) {
1471
+ const observedSize = generation.observedSizeBytes ? `, ${generation.observedSizeBytes} bytes observed` : "";
1472
+ console.log(
1473
+ `- ${formatGeneration(generation)}: ${generation.originalFilename} (${generation.declaredSizeBytes} bytes declared${observedSize})`
1474
+ );
1475
+ }
1476
+ }
1477
+ if (release.checks.length > 0) {
1478
+ console.log("");
1479
+ console.log(kleur3.dim("Checks:"));
1480
+ for (const check of release.checks) {
1481
+ console.log(
1482
+ `- ${check.kind}: ${check.status} [generation ${check.generationId}]${check.summary ? ` (${check.summary})` : ""}`
1483
+ );
1484
+ }
1485
+ }
1486
+ };
1487
+ var runReleaseSubmitCommand = async ({
1488
+ platformUrl,
1489
+ game,
1490
+ versionLabel,
1491
+ dir,
1492
+ distDir,
1493
+ bundle,
1494
+ skipBuild = false,
1495
+ waitForProcessing = false,
1496
+ processingTimeoutSeconds,
1497
+ publish = false
1498
+ }) => {
1499
+ const resolvedCwd = path3.resolve(dir || process.cwd());
1500
+ if (processingTimeoutSeconds !== void 0 && (!Number.isSafeInteger(processingTimeoutSeconds) || processingTimeoutSeconds < 1)) {
1501
+ throw new Error("--processing-timeout must be a positive integer.");
1502
+ }
1503
+ let result;
1504
+ try {
1505
+ result = await submitPlatformRelease({
1506
+ platformUrl,
1507
+ slugOrId: game,
1508
+ versionLabel,
1509
+ cwd: resolvedCwd,
1510
+ distDir,
1511
+ bundlePath: bundle,
1512
+ skipBuild,
1513
+ waitForProcessing,
1514
+ ...processingTimeoutSeconds === void 0 ? {} : { processingTimeoutMs: processingTimeoutSeconds * 1e3 },
1515
+ publish
1516
+ });
1517
+ } catch (error) {
1518
+ if (error instanceof AirJamPlatformApiError && error.code === "not_found") {
1519
+ let createHint = 'Run `airjam game create --name "Your Game" --slug your-game` first.';
1520
+ try {
1521
+ const localDefaults = await readLocalHostedGameDefaults({
1522
+ cwd: resolvedCwd
1523
+ });
1524
+ const hintedSlug = localDefaults.metadata.slug ?? game;
1525
+ createHint = `Run \`airjam game create --dir ${resolvedCwd}${platformUrl ? ` --platform-url ${platformUrl}` : ""}\` to register this local game first, then retry with \`--game ${hintedSlug}\`.`;
1526
+ } catch {
1527
+ }
1528
+ throw new Error(`No owned hosted game matched "${game}". ${createHint}`);
1529
+ }
1530
+ throw error;
1531
+ }
1532
+ console.log(kleur3.green("\n\u2713 Hosted release submitted\n"));
1533
+ console.log(`Bundle: ${kleur3.cyan(result.bundlePath)}`);
1534
+ console.log(`Draft: ${kleur3.cyan(result.createdRelease.id)}`);
1535
+ console.log(
1536
+ `Created generation: ${kleur3.cyan(result.createdGeneration.id)} (#${result.createdGeneration.sequence})`
1537
+ );
1538
+ console.log(
1539
+ `Submitted generation: ${kleur3.cyan(result.submittedGeneration.id)} (${kleur3.yellow(result.submittedGeneration.status)})`
1540
+ );
1541
+ console.log(
1542
+ `Processing job: ${kleur3.cyan(result.processingJob.id)} (${kleur3.yellow(result.processingJob.status)})`
1543
+ );
1544
+ console.log(
1545
+ `Release status: ${kleur3.yellow(result.submittedRelease.status)}`
1546
+ );
1547
+ if (result.processedRelease) {
1548
+ console.log(
1549
+ `Processing complete: ${kleur3.cyan(result.processedRelease.id)} (${kleur3.yellow(result.processedRelease.status)})`
1550
+ );
1551
+ } else {
1552
+ console.log(
1553
+ kleur3.dim(
1554
+ `Inspect with: airjam release inspect --release ${result.submittedRelease.id}`
1555
+ )
1556
+ );
1557
+ }
1558
+ if (result.publishedRelease) {
1559
+ console.log(
1560
+ `Published: ${kleur3.cyan(result.publishedRelease.id)} (${kleur3.yellow(result.publishedRelease.status)})`
1561
+ );
1562
+ }
1563
+ };
1564
+ var runReleaseUploadCommand = async ({
1565
+ platformUrl,
1566
+ releaseId,
1567
+ dir,
1568
+ bundle
1569
+ }) => {
1570
+ const result = await uploadPlatformReleaseGeneration({
1571
+ platformUrl,
1572
+ releaseId,
1573
+ cwd: path3.resolve(dir || process.cwd()),
1574
+ bundlePath: bundle
1575
+ });
1576
+ console.log(kleur3.green("\n\u2713 Hosted release generation uploaded\n"));
1577
+ console.log(`Bundle: ${kleur3.cyan(result.bundlePath)}`);
1578
+ console.log(`Release: ${kleur3.cyan(result.release.id)}`);
1579
+ console.log(
1580
+ `Generation: ${kleur3.cyan(result.generation.id)} (#${result.generation.sequence}, ${kleur3.yellow(result.generation.status)})`
1581
+ );
1582
+ console.log(
1583
+ kleur3.dim(
1584
+ `Resume with: airjam release finalize --release ${result.release.id} --generation ${result.generation.id}`
1585
+ )
1586
+ );
1587
+ };
1588
+ var runReleaseFinalizeCommand = async ({
1589
+ platformUrl,
1590
+ releaseId,
1591
+ generationId
1592
+ }) => {
1593
+ const result = await finalizePlatformReleaseGeneration({
1594
+ platformUrl,
1595
+ releaseId,
1596
+ generationId
1597
+ });
1598
+ console.log(kleur3.green("\n\u2713 Hosted release processing queued\n"));
1599
+ console.log(`Release: ${kleur3.cyan(result.release.id)}`);
1600
+ console.log(`Release status: ${kleur3.yellow(result.release.status)}`);
1601
+ console.log(
1602
+ `Generation: ${kleur3.cyan(result.generation.id)} (${kleur3.yellow(result.generation.status)})`
1603
+ );
1604
+ console.log(
1605
+ `Processing job: ${kleur3.cyan(result.job.id)} (${kleur3.yellow(result.job.status)})`
1606
+ );
1607
+ console.log(
1608
+ kleur3.dim(
1609
+ `Inspect with: airjam release inspect --release ${result.release.id}`
1610
+ )
1611
+ );
1612
+ };
1613
+ var runReleaseExportCommand = async ({
1614
+ platformUrl,
1615
+ releaseId,
1616
+ generationId,
1617
+ dir,
1618
+ out
1619
+ }) => {
1620
+ const result = await exportPlatformReleaseGeneration({
1621
+ platformUrl,
1622
+ releaseId,
1623
+ generationId,
1624
+ cwd: path3.resolve(dir || process.cwd()),
1625
+ out
1626
+ });
1627
+ console.log(kleur3.green("\n\u2713 Hosted release generation exported\n"));
1628
+ console.log(`Release: ${kleur3.cyan(releaseId)}`);
1629
+ console.log(
1630
+ `Generation: ${kleur3.cyan(result.generation.id)} (#${result.generation.sequence})`
1631
+ );
1632
+ console.log(`Archive: ${kleur3.cyan(result.outputFile)}`);
1633
+ console.log(`Size: ${kleur3.cyan(`${result.sizeBytes} bytes`)}`);
1634
+ };
1635
+ var runReleasePublishCommand = async ({
1636
+ platformUrl,
1637
+ releaseId
1638
+ }) => {
1639
+ const result = await publishPlatformRelease({
1640
+ platformUrl,
1641
+ releaseId
1642
+ });
1643
+ console.log(kleur3.green("\n\u2713 Hosted release published\n"));
1644
+ console.log(`Release: ${kleur3.cyan(result.release.id)}`);
1645
+ console.log(`Status: ${kleur3.cyan(result.release.status)}`);
1646
+ console.log(`Play URL: ${kleur3.cyan(result.release.playUrl)}`);
1647
+ if (result.release.hostUrl) {
1648
+ console.log(`Host URL: ${kleur3.cyan(result.release.hostUrl)}`);
1649
+ }
1650
+ };
1651
+ var runAuthLoginCommand = async ({
1652
+ platformUrl,
1653
+ clientName
1654
+ }) => {
1655
+ console.log(kleur3.cyan("\nStarting Air Jam platform login...\n"));
1656
+ const result = await loginPlatformWithDeviceFlow({
1657
+ platformUrl,
1658
+ clientName,
1659
+ onPrompt: async (authorization) => {
1660
+ console.log(
1661
+ `Verification URL: ${kleur3.cyan(authorization.verificationUrl)}`
1662
+ );
1663
+ console.log(`Approval code: ${kleur3.cyan(authorization.userCode)}`);
1664
+ console.log(
1665
+ kleur3.dim(
1666
+ "Sign in on the dashboard, approve the CLI request, and this command will finish automatically.\n"
1667
+ )
1668
+ );
1669
+ }
1670
+ });
1671
+ console.log(kleur3.green("\n\u2713 Logged in to the Air Jam platform\n"));
1672
+ console.log(`Platform: ${kleur3.cyan(result.authenticated.platformBaseUrl)}`);
1673
+ console.log(`User: ${kleur3.cyan(result.authenticated.user.name)}`);
1674
+ console.log(`Email: ${kleur3.cyan(result.authenticated.user.email)}`);
1675
+ console.log(`Session file: ${kleur3.dim(getPlatformAuthStoragePath())}`);
1676
+ };
1677
+ var runAuthWhoAmICommand = async ({
1678
+ platformUrl
1679
+ }) => {
1680
+ const storedSession = await readStoredPlatformMachineSession();
1681
+ if (!storedSession) {
1682
+ console.log(kleur3.red("No stored Air Jam platform session was found."));
1683
+ console.log(kleur3.dim(`Expected at ${getPlatformAuthStoragePath()}`));
1684
+ process.exitCode = 1;
1685
+ return;
1686
+ }
1687
+ const profile = await getPlatformMachineProfile({ platformUrl });
1688
+ console.log(kleur3.green("\n\u2713 Air Jam platform session is valid\n"));
1689
+ console.log(`Platform: ${kleur3.cyan(profile.platformBaseUrl)}`);
1690
+ console.log(`User: ${kleur3.cyan(profile.user.name)}`);
1691
+ console.log(`Email: ${kleur3.cyan(profile.user.email)}`);
1692
+ console.log(`Role: ${kleur3.cyan(profile.user.role)}`);
1693
+ console.log(`Expires: ${kleur3.cyan(profile.session.expiresAt)}`);
1694
+ console.log(`Session file: ${kleur3.dim(getPlatformAuthStoragePath())}`);
1695
+ };
1696
+ var runAuthLogoutCommand = async ({
1697
+ platformUrl
1698
+ }) => {
1699
+ let storedSession;
1700
+ try {
1701
+ storedSession = await readStoredPlatformMachineSession();
1702
+ } catch (error) {
1703
+ if (!(error instanceof AirJamStoredPlatformSessionError)) throw error;
1704
+ await clearStoredPlatformMachineSession();
1705
+ console.log(
1706
+ kleur3.yellow(
1707
+ "Removed an unreadable local Air Jam session. Its remote token could not be revoked."
1708
+ )
1709
+ );
1710
+ return;
1711
+ }
1712
+ if (!storedSession) {
1713
+ console.log(kleur3.yellow("No stored Air Jam platform session was found."));
1714
+ return;
1715
+ }
1716
+ await logoutPlatformMachineSession({ platformUrl });
1717
+ console.log(kleur3.green("\n\u2713 Logged out of the Air Jam platform\n"));
1718
+ };
1719
+ var buildProgram = () => {
1720
+ const program = new Command();
1721
+ program.name("airjam").description("Operate Air Jam game projects").version(AIR_JAM_CLI_VERSION).action(() => {
1722
+ program.outputHelp();
1723
+ });
1724
+ const documentationCommand = program.command("docs").description("Read the installed public creator documentation");
1725
+ documentationCommand.command("list").option("--json", "Print one machine-readable JSON document", false).action(async (options) => {
1726
+ const snapshot = await readDocumentationSnapshot();
1727
+ const documents = snapshot.documents.map(
1728
+ ({ content: _content, ...document }) => document
1729
+ );
1730
+ if (options.json)
1731
+ process.stdout.write(
1732
+ `${JSON.stringify({ ...snapshot, documents }, null, 2)}
1733
+ `
1734
+ );
1735
+ else
1736
+ for (const document of documents)
1737
+ console.log(`${document.page.href}: ${document.page.title}`);
1738
+ });
1739
+ documentationCommand.command("read <slug>").option("--json", "Print one machine-readable JSON document", false).action(async (slug, options) => {
1740
+ const snapshot = await readDocumentationSnapshot();
1741
+ const document = snapshot.documents.find(
1742
+ (entry) => entry.page.href === `/docs/${slug}`
1743
+ );
1744
+ if (!document)
1745
+ throw new Error(
1746
+ `Unknown documentation page: ${slug}. Use "airjam docs list".`
1747
+ );
1748
+ process.stdout.write(
1749
+ options.json ? `${JSON.stringify({ packageVersion: snapshot.packageVersion, document }, null, 2)}
1750
+ ` : document.content
1751
+ );
1752
+ });
1753
+ const aiPackCommand = program.command("ai-pack").description("Inspect or update provenance-backed AI pack assets");
1754
+ aiPackCommand.command("status").description("Show AI pack status for a project").option("--dir <path>", "Project directory to inspect").option("--json", "Print one machine-readable JSON document", false).action(async (options) => {
1755
+ await runAiPackStatus(
1756
+ resolveActionOptions(options)
1757
+ );
1758
+ });
1759
+ aiPackCommand.command("diff").description("Show AI pack file differences for a project").option("--dir <path>", "Project directory to inspect").option("--json", "Print one machine-readable JSON document", false).action(async (options) => {
1760
+ await runAiPackDiff(
1761
+ resolveActionOptions(options)
1762
+ );
1763
+ });
1764
+ aiPackCommand.command("update").description("Update managed AI pack assets for a project").option("--dir <path>", "Project directory to inspect").option("--json", "Print one machine-readable JSON document", false).action(async (options) => {
1765
+ await runAiPackUpdate(
1766
+ resolveActionOptions(options)
1767
+ );
1768
+ });
1769
+ aiPackCommand.command("repair").description("Restore same-version managed files from the installed CLI").option("--dir <path>", "Project directory to repair").option("--json", "Print one machine-readable JSON document", false).action(async (options) => {
1770
+ await runAiPackRepair(
1771
+ resolveActionOptions(options)
1772
+ );
1773
+ });
1774
+ aiPackCommand.action(() => {
1775
+ aiPackCommand.outputHelp();
1776
+ });
1777
+ program.command("evaluate").description(
1778
+ "Run the complete game evaluation: typecheck, lint, tests, and production build"
1779
+ ).option("--dir <path>", "Project directory to evaluate").action(async (options) => {
1780
+ const input = resolveActionOptions(options);
1781
+ const result = await runCompleteEvaluation({ cwd: input.dir });
1782
+ process.stdout.write(`${JSON.stringify(result, null, 2)}
1783
+ `);
1784
+ if (result.status !== "passed") {
1785
+ process.exitCode = 1;
1786
+ }
1787
+ });
1788
+ const gameCommand = program.command("game").description("Manage hosted games and local game source");
1789
+ gameCommand.command("list").description("List owned hosted games").option("--json", "Print one machine-readable JSON document", false).option("--platform-url <url>", "Hosted Air Jam platform base URL").action(async (options) => {
1790
+ await runGameListCommand(
1791
+ resolveActionOptions(options)
1792
+ );
1793
+ });
1794
+ gameCommand.command("inspect").description("Inspect one owned hosted game").option("--json", "Print one machine-readable JSON document", false).requiredOption("--game <slug-or-id>", "Owned hosted game slug or ID").option("--platform-url <url>", "Hosted Air Jam platform base URL").action(async (options) => {
1795
+ const resolved = resolveActionOptions(options);
1796
+ await runGameInspectCommand({
1797
+ platformUrl: resolved.platformUrl,
1798
+ game: resolved.game,
1799
+ json: resolved.json
1800
+ });
1801
+ });
1802
+ gameCommand.command("create").description("Create a hosted game record for release publishing").option("--platform-url <url>", "Hosted Air Jam platform base URL").option(
1803
+ "--dir <path>",
1804
+ "Local game project directory for metadata defaults"
1805
+ ).option("--name <name>", "Hosted game display name").option("--slug <slug>", "Hosted game slug").option("--description <text>", "Catalog description/tagline").option("--preview-url <url>", "Private creator preview URL").option("--source-url <url>", "Source repository URL").option("--template-id <id>", "Template ID shown for developer actions").option(
1806
+ "--arcade-visibility <visibility>",
1807
+ "Initial arcade visibility (hidden or listed)"
1808
+ ).action(async (options) => {
1809
+ const resolved = resolveActionOptions(options);
1810
+ await runGameCreateCommand({
1811
+ platformUrl: resolved.platformUrl,
1812
+ dir: resolved.dir,
1813
+ name: resolved.name,
1814
+ slug: resolved.slug,
1815
+ description: resolved.description,
1816
+ previewUrl: resolved.previewUrl,
1817
+ sourceUrl: resolved.sourceUrl,
1818
+ templateId: resolved.templateId,
1819
+ arcadeVisibility: resolved.arcadeVisibility
1820
+ });
1821
+ });
1822
+ gameCommand.command("update").description("Update core hosted game metadata").requiredOption("--game <slug-or-id>", "Owned hosted game slug or ID").option("--platform-url <url>", "Hosted Air Jam platform base URL").option("--name <name>", "Hosted game display name").option("--slug <slug>", "Hosted game slug").option("--description <text>", "Catalog description/tagline").option("--clear-description", "Clear the catalog description", false).option("--preview-url <url>", "Private creator preview URL").option("--clear-preview-url", "Clear the private preview URL", false).option("--source-url <url>", "Source repository URL").option("--clear-source-url", "Clear the source repository URL", false).option("--template-id <id>", "Template ID shown for developer actions").option("--clear-template-id", "Clear the template ID", false).option(
1823
+ "--arcade-visibility <visibility>",
1824
+ "Arcade visibility (hidden or listed)"
1825
+ ).action(async (options) => {
1826
+ const resolved = resolveActionOptions(options);
1827
+ await runGameUpdateCommand({
1828
+ platformUrl: resolved.platformUrl,
1829
+ game: resolved.game,
1830
+ name: resolved.name,
1831
+ slug: resolved.slug,
1832
+ description: resolved.description,
1833
+ clearDescription: resolved.clearDescription,
1834
+ previewUrl: resolved.previewUrl,
1835
+ clearPreviewUrl: resolved.clearPreviewUrl,
1836
+ sourceUrl: resolved.sourceUrl,
1837
+ clearSourceUrl: resolved.clearSourceUrl,
1838
+ templateId: resolved.templateId,
1839
+ clearTemplateId: resolved.clearTemplateId,
1840
+ arcadeVisibility: resolved.arcadeVisibility
1841
+ });
1842
+ });
1843
+ registerGameSettingsCommand(gameCommand);
1844
+ registerGameAppIdCommands(gameCommand);
1845
+ registerGameAnalyticsCommand(gameCommand);
1846
+ registerGameMediaCommands(gameCommand);
1847
+ gameCommand.action(() => {
1848
+ gameCommand.outputHelp();
1849
+ });
1850
+ const releaseCommand = program.command("release").description("Work with hosted release bundles");
1851
+ releaseCommand.command("doctor").description(
1852
+ "Inspect whether a project is ready for hosted release bundling"
1853
+ ).option("--dir <path>", "Project directory to inspect").option("--dist-dir <path>", "Built static output directory").action(async (options) => {
1854
+ await printReleaseDoctor(
1855
+ resolveActionOptions(options)
1856
+ );
1857
+ });
1858
+ releaseCommand.command("bundle").description("Create a hosted release zip from a built game project").option("--dir <path>", "Project directory to bundle").option("--dist-dir <path>", "Built static output directory").option("--out <path>", "Output zip file path").option(
1859
+ "--skip-build",
1860
+ "Reuse the existing dist directory without building",
1861
+ false
1862
+ ).action(async (options) => {
1863
+ await runReleaseBundleCommand(
1864
+ resolveActionOptions(options)
1865
+ );
1866
+ });
1867
+ releaseCommand.command("validate").description(
1868
+ "Validate hosted release inputs or an existing hosted release zip"
1869
+ ).option("--dir <path>", "Project directory to inspect").option("--dist-dir <path>", "Built static output directory").option("--bundle <path>", "Existing hosted release zip to validate").option(
1870
+ "--skip-build",
1871
+ "Reuse the existing dist directory without building",
1872
+ false
1873
+ ).action(async (options) => {
1874
+ await runReleaseValidateCommand(
1875
+ resolveActionOptions(options)
1876
+ );
1877
+ });
1878
+ releaseCommand.command("list").description("List owned hosted games or releases for one hosted game").option("--platform-url <url>", "Hosted Air Jam platform base URL").option("--game <slug-or-id>", "List releases for one owned hosted game").action(async (options) => {
1879
+ await runReleaseListCommand(
1880
+ resolveActionOptions(options)
1881
+ );
1882
+ });
1883
+ releaseCommand.command("inspect").description("Inspect one hosted release from the Air Jam platform").requiredOption("--release <id>", "Hosted release ID to inspect").option("--platform-url <url>", "Hosted Air Jam platform base URL").action(async (options) => {
1884
+ const resolved = resolveActionOptions(options);
1885
+ await runReleaseInspectCommand({
1886
+ platformUrl: resolved.platformUrl,
1887
+ releaseId: resolved.release
1888
+ });
1889
+ });
1890
+ releaseCommand.command("submit").description("Bundle a game and submit it as a hosted release draft").requiredOption("--game <slug-or-id>", "Owned hosted game slug or ID").option("--platform-url <url>", "Hosted Air Jam platform base URL").option("--version-label <label>", "Optional hosted release version label").option("--dir <path>", "Project directory to bundle").option("--dist-dir <path>", "Built static output directory").option("--bundle <path>", "Existing hosted release zip to submit").option(
1891
+ "--skip-build",
1892
+ "Reuse the existing dist directory without building",
1893
+ false
1894
+ ).option(
1895
+ "--wait",
1896
+ "Wait for durable processing to reach a terminal generation state",
1897
+ false
1898
+ ).option(
1899
+ "--processing-timeout <seconds>",
1900
+ "Maximum processing wait; the durable job continues after a timeout",
1901
+ (value) => Number(value)
1902
+ ).option(
1903
+ "--publish",
1904
+ "Wait for successful processing and publish the ready release",
1905
+ false
1906
+ ).action(async (options) => {
1907
+ const resolved = resolveActionOptions(options);
1908
+ await runReleaseSubmitCommand({
1909
+ platformUrl: resolved.platformUrl,
1910
+ game: resolved.game,
1911
+ versionLabel: resolved.versionLabel,
1912
+ dir: resolved.dir,
1913
+ distDir: resolved.distDir,
1914
+ bundle: resolved.bundle,
1915
+ skipBuild: resolved.skipBuild,
1916
+ waitForProcessing: resolved.wait,
1917
+ processingTimeoutSeconds: resolved.processingTimeout,
1918
+ publish: resolved.publish
1919
+ });
1920
+ });
1921
+ releaseCommand.command("upload").description("Upload a bundle as a new immutable generation").requiredOption("--release <id>", "Hosted release ID").requiredOption("--bundle <path>", "Existing hosted release zip").option("--dir <path>", "Directory used to resolve the bundle path").option("--platform-url <url>", "Hosted Air Jam platform base URL").action(async (options) => {
1922
+ const resolved = resolveActionOptions(options);
1923
+ await runReleaseUploadCommand({
1924
+ platformUrl: resolved.platformUrl,
1925
+ releaseId: resolved.release,
1926
+ dir: resolved.dir,
1927
+ bundle: resolved.bundle
1928
+ });
1929
+ });
1930
+ releaseCommand.command("finalize").description("Finalize one exact immutable release generation").requiredOption("--release <id>", "Hosted release ID").requiredOption("--generation <id>", "Immutable generation ID").option("--platform-url <url>", "Hosted Air Jam platform base URL").action(async (options) => {
1931
+ const resolved = resolveActionOptions(options);
1932
+ await runReleaseFinalizeCommand({
1933
+ platformUrl: resolved.platformUrl,
1934
+ releaseId: resolved.release,
1935
+ generationId: resolved.generation
1936
+ });
1937
+ });
1938
+ releaseCommand.command("publish").description("Publish one ready hosted release").requiredOption("--release <id>", "Hosted release ID to publish").option("--platform-url <url>", "Hosted Air Jam platform base URL").action(async (options) => {
1939
+ const resolved = resolveActionOptions(options);
1940
+ await runReleasePublishCommand({
1941
+ platformUrl: resolved.platformUrl,
1942
+ releaseId: resolved.release
1943
+ });
1944
+ });
1945
+ releaseCommand.command("archive").description(
1946
+ "Retire one owned hosted release so it can no longer be played"
1947
+ ).requiredOption("--release <id>", "Exact hosted release ID to archive").option("--platform-url <url>", "Hosted Air Jam platform base URL").action(async (options) => {
1948
+ const resolved = resolveActionOptions(options);
1949
+ const result = await archivePlatformRelease({
1950
+ platformUrl: resolved.platformUrl,
1951
+ releaseId: resolved.release
1952
+ });
1953
+ process.stdout.write(`${JSON.stringify(result, null, 2)}
1954
+ `);
1955
+ });
1956
+ releaseCommand.command("export").description("Download one exact immutable hosted release generation").requiredOption("--release <id>", "Hosted release ID").requiredOption("--generation <id>", "Immutable generation ID").option("--dir <path>", "Directory used to resolve the output path").option("--out <path>", "Output archive path; refuses to overwrite").option("--platform-url <url>", "Hosted Air Jam platform base URL").action(async (options) => {
1957
+ const resolved = resolveActionOptions(options);
1958
+ await runReleaseExportCommand({
1959
+ platformUrl: resolved.platformUrl,
1960
+ releaseId: resolved.release,
1961
+ generationId: resolved.generation,
1962
+ dir: resolved.dir,
1963
+ out: resolved.out
1964
+ });
1965
+ });
1966
+ releaseCommand.action(() => {
1967
+ releaseCommand.outputHelp();
1968
+ });
1969
+ const authCommand = program.command("auth").description("Authenticate the local Air Jam CLI with the hosted platform");
1970
+ authCommand.command("login").description("Start browser-assisted Air Jam CLI login").option("--platform-url <url>", "Hosted Air Jam platform base URL").option("--client-name <name>", "Optional machine-readable client label").action(async (options) => {
1971
+ await runAuthLoginCommand(
1972
+ resolveActionOptions(options)
1973
+ );
1974
+ });
1975
+ authCommand.command("whoami").description("Inspect the current stored Air Jam platform session").option("--platform-url <url>", "Hosted Air Jam platform base URL").action(async (options) => {
1976
+ await runAuthWhoAmICommand(
1977
+ resolveActionOptions(options)
1978
+ );
1979
+ });
1980
+ authCommand.command("logout").description("Revoke the current stored Air Jam platform session").option("--platform-url <url>", "Hosted Air Jam platform base URL").action(async (options) => {
1981
+ await runAuthLogoutCommand(
1982
+ resolveActionOptions(options)
1983
+ );
1984
+ });
1985
+ registerAuthProfileCommand(authCommand);
1986
+ registerAuthSessionsCommand(authCommand);
1987
+ authCommand.action(() => {
1988
+ authCommand.outputHelp();
1989
+ });
1990
+ const mcpCommand = program.command("mcp").description("Inspect or initialize project-local Air Jam MCP setup");
1991
+ mcpCommand.command("doctor").description("Inspect the current project's Air Jam MCP setup").option("--dir <path>", "Project directory to inspect").option("--json", "Print one machine-readable JSON document", false).action(async (options) => {
1992
+ await runMcpDoctor(
1993
+ resolveActionOptions(options)
1994
+ );
1995
+ });
1996
+ mcpCommand.command("init").description(`Write ${AIRJAM_PROJECT_MCP_FILE2} for the current project`).option("--dir <path>", "Project directory to inspect").option("--force", "Overwrite an existing project-local MCP config", false).option("--json", "Print one machine-readable JSON document", false).action(async (options) => {
1997
+ await runMcpInit(
1998
+ resolveActionOptions(options)
1999
+ );
2000
+ });
2001
+ mcpCommand.command("config").description("Render a portable, Codex, or Claude Desktop MCP profile").option("--dir <path>", "Project directory to inspect").option(
2002
+ "--profile <profile>",
2003
+ "Profile to render (portable, codex, or claude-desktop); Codex supports CLI, IDE and app",
2004
+ "portable"
2005
+ ).option("--json", "Print the rendered profile metadata as JSON", false).action(async (options) => {
2006
+ const resolved = resolveActionOptions(options);
2007
+ await runMcpConfig(resolved);
2008
+ });
2009
+ mcpCommand.action(() => {
2010
+ mcpCommand.outputHelp();
2011
+ });
2012
+ const sessionCommand = program.command("session").description(
2013
+ "Operate persistent semantic game sessions through stable JSON contracts"
2014
+ );
2015
+ const runCommand = sessionCommand.command("run").description("Discover, start, inspect and stop bounded agent play runs");
2016
+ runCommand.command("profiles").option("--dir <path>", "Project directory").option("--game <id>", "Game ID in a monorepo").action(async (options) => {
2017
+ const input = resolveActionOptions(
2018
+ options
2019
+ );
2020
+ process.stdout.write(
2021
+ `${JSON.stringify(await listGameTestProfiles({ cwd: input.dir, gameId: input.game }), null, 2)}
2022
+ `
2023
+ );
2024
+ });
2025
+ runCommand.command("start").description(
2026
+ "Start an authored test or join the current room as a model player"
2027
+ ).requiredOption("--run-id <uuid>", "Stable caller-generated operation UUID").option("--kind <kind>", "test or play", "test").option("--profile <id>", "Authored scenario ID (test only)").option("--policy <id>", "Scenario policy ID (test only)").option(
2028
+ "--current",
2029
+ "Join the delegated current room; receive its private attachment through stdin"
2030
+ ).option(
2031
+ "--headless",
2032
+ "Play in a room with no page, on game time, as fast as the host runs"
2033
+ ).option("--dir <path>", "Project directory").option("--game <id>", "Game ID in a monorepo").option(
2034
+ "--duration-ms <ms>",
2035
+ "Maximum play time (game time when headless) and wall lifetime",
2036
+ Number
2037
+ ).option("--settings <json>", "Initial game settings JSON object").option("--steps <count>", "Maximum policy decisions (test only)", Number).option(
2038
+ "--seed <number>",
2039
+ "Policy random seed; a headless room also seeds the game with it",
2040
+ Number,
2041
+ 0
2042
+ ).option(
2043
+ "--intent <seat=text>",
2044
+ "Play intent text, or <seat=text> for each test seat",
2045
+ (value, previous = []) => [...previous, value]
2046
+ ).action(async (options) => {
2047
+ const input = resolveActionOptions(options);
2048
+ if (input.current && input.headless)
2049
+ throw new Error("Choose either --current or --headless.");
2050
+ if (input.kind !== "test" && input.kind !== "play")
2051
+ throw new Error("Choose --kind test or play.");
2052
+ if (input.kind === "play" && (!input.current || input.profile || input.policy || input.settings || input.durationMs !== void 0 || input.steps !== void 0 || (input.intent?.length ?? 0) > 1))
2053
+ throw new Error(
2054
+ "Play requires --current, at most one intent, and no test profile, policy, settings or budget."
2055
+ );
2056
+ const testPolicy = input.kind === "test" ? (() => {
2057
+ if (!input.profile || !input.policy)
2058
+ throw new Error("Tests require --profile and --policy.");
2059
+ return { profileId: input.profile, policyId: input.policy };
2060
+ })() : void 0;
2061
+ const intents = input.kind === "test" && input.intent?.length ? Object.fromEntries(
2062
+ input.intent.map((entry) => {
2063
+ const separator = entry.indexOf("=");
2064
+ if (separator < 1)
2065
+ throw new Error("Write each intent as <seat-id>=<text>.");
2066
+ return [entry.slice(0, separator), entry.slice(separator + 1)];
2067
+ })
2068
+ ) : void 0;
2069
+ let attachment;
2070
+ if (input.current) {
2071
+ if (process.stdin.isTTY)
2072
+ throw new Error(
2073
+ "Current-room play requires a private stdin attachment."
2074
+ );
2075
+ const chunks = [];
2076
+ let bytes = 0;
2077
+ for await (const chunk of process.stdin) {
2078
+ const buffer = Buffer.from(chunk);
2079
+ bytes += buffer.byteLength;
2080
+ if (bytes > 16384)
2081
+ throw new Error(
2082
+ "Current-room attachment exceeds its transfer allowance."
2083
+ );
2084
+ chunks.push(buffer);
2085
+ }
2086
+ try {
2087
+ attachment = currentRoomAttachmentSchema.parse(
2088
+ JSON.parse(Buffer.concat(chunks).toString("utf8"))
2089
+ );
2090
+ } catch {
2091
+ throw new Error("Current-room attachment failed validation.");
2092
+ }
2093
+ }
2094
+ const result = await startGameRun(
2095
+ startGameRunSchema.parse({
2096
+ cwd: input.dir,
2097
+ runId: input.runId,
2098
+ gameId: input.game,
2099
+ seed: input.seed,
2100
+ ...input.kind === "play" ? {
2101
+ kind: "play",
2102
+ target: { kind: "current" },
2103
+ ...input.intent?.[0] ? { intent: input.intent[0] } : {}
2104
+ } : {
2105
+ kind: "test",
2106
+ target: {
2107
+ kind: input.current ? "current" : input.headless ? "headless" : "owned"
2108
+ },
2109
+ ...testPolicy,
2110
+ ...input.settings ? {
2111
+ settings: airJamSettingsValuesSchema.parse(
2112
+ parseJsonObject(input.settings)
2113
+ )
2114
+ } : {},
2115
+ budget: {
2116
+ durationMs: input.durationMs ?? 3e4,
2117
+ steps: input.steps ?? 3e3
2118
+ },
2119
+ ...intents ? { intents } : {}
2120
+ }
2121
+ }),
2122
+ attachment
2123
+ );
2124
+ process.stdout.write(`${JSON.stringify(result, null, 2)}
2125
+ `);
2126
+ });
2127
+ for (const [name, operation] of [
2128
+ ["read", readGameRun],
2129
+ ["stop", stopGameRun],
2130
+ ["cancel", cancelGameRun]
2131
+ ]) {
2132
+ runCommand.command(`${name} <run-id>`).option("--dir <path>", "Project directory").action(async (runId, options) => {
2133
+ const input = resolveActionOptions(options);
2134
+ process.stdout.write(
2135
+ `${JSON.stringify(await operation({ cwd: input.dir, runId }), null, 2)}
2136
+ `
2137
+ );
2138
+ });
2139
+ }
2140
+ runCommand.command("replay <run-id>").description(
2141
+ "Replay an ended headless run from its input log and compare where it ends"
2142
+ ).option("--dir <path>", "Project directory").action(async (runId, options) => {
2143
+ const input = resolveActionOptions(options);
2144
+ process.stdout.write(
2145
+ `${JSON.stringify(await replayGameRun({ cwd: input.dir, runId }), null, 2)}
2146
+ `
2147
+ );
2148
+ });
2149
+ runCommand.command("steer <run-id>").description(
2150
+ "Change what one seat of an active run is trying to do; never sends a control"
2151
+ ).requiredOption("--seat <id>", "Seat to steer").option("--intent <text>", "The seat's new goal in plain words").option("--clear", "Remove the seat's goal").option("--source <source>", "creator, agent or operator", "operator").option("--dir <path>", "Project directory").action(async (runId, options) => {
2152
+ const input = resolveActionOptions(options);
2153
+ if (Boolean(input.clear) === (input.intent !== void 0))
2154
+ throw new Error("Give either --intent <text> or --clear.");
2155
+ process.stdout.write(
2156
+ `${JSON.stringify(
2157
+ await steerGameRun({
2158
+ cwd: input.dir,
2159
+ runId,
2160
+ seatId: input.seat,
2161
+ intent: input.clear ? null : input.intent ?? null,
2162
+ source: input.source
2163
+ }),
2164
+ null,
2165
+ 2
2166
+ )}
2167
+ `
2168
+ );
2169
+ });
2170
+ runCommand.command("watch <run-id>").description(
2171
+ "Stream live JPEG frames and producer heartbeats as NDJSON; disconnecting never stops the run"
2172
+ ).option("--dir <path>", "Project directory").option("--surface <surface>", "host or controller:<seat-id>", "host").action(async (runId, options) => {
2173
+ const input = resolveActionOptions(
2174
+ options
2175
+ );
2176
+ const surface = parseGameRunWatchSurface(input.surface);
2177
+ const cancellation = new AbortController();
2178
+ const writer = new GameRunWatchWriter(process.stdout);
2179
+ const stop = () => {
2180
+ writer.close();
2181
+ cancellation.abort();
2182
+ };
2183
+ process.once("SIGTERM", stop);
2184
+ process.once("SIGINT", stop);
2185
+ process.stdout.on("error", stop);
2186
+ try {
2187
+ await watchGameRun(
2188
+ { cwd: input.dir, runId, surface },
2189
+ (event) => writer.send(event),
2190
+ cancellation.signal
2191
+ );
2192
+ } catch (error) {
2193
+ if (!cancellation.signal.aborted) throw error;
2194
+ } finally {
2195
+ writer.close();
2196
+ process.off("SIGTERM", stop);
2197
+ process.off("SIGINT", stop);
2198
+ process.stdout.off("error", stop);
2199
+ }
2200
+ });
2201
+ runCommand.command("wait <run-id>").description(
2202
+ "Wait for completion or a bounded timeout; disconnecting never stops the run"
2203
+ ).option("--dir <path>", "Project directory").option("--timeout-ms <ms>", "Wait at most 30000 ms", Number, 25e3).action(async (runId, options) => {
2204
+ const input = resolveActionOptions(
2205
+ options
2206
+ );
2207
+ process.stdout.write(
2208
+ `${JSON.stringify(await waitGameRun({ cwd: input.dir, runId, timeoutMs: input.timeoutMs }), null, 2)}
2209
+ `
2210
+ );
2211
+ });
2212
+ runCommand.command("stop-all").description(
2213
+ "Stop every active run in this project without starting an owner"
2214
+ ).option("--dir <path>", "Project directory").action(async (options) => {
2215
+ const input = resolveActionOptions(options);
2216
+ process.stdout.write(
2217
+ `${JSON.stringify(await stopAllGameRuns({ cwd: input.dir }), null, 2)}
2218
+ `
2219
+ );
2220
+ });
2221
+ runCommand.command("list").option("--dir <path>", "Project directory").action(async (options) => {
2222
+ const input = resolveActionOptions(options);
2223
+ process.stdout.write(
2224
+ `${JSON.stringify(await listGameRuns({ cwd: input.dir }), null, 2)}
2225
+ `
2226
+ );
2227
+ });
2228
+ sessionCommand.command("open").description("Open a persistent semantic game session").option("--dir <path>", "Project directory").option("--game <id>", "Game ID in a monorepo").option(
2229
+ "--mode <mode>",
2230
+ "Dev mode (standalone-dev, arcade-dev, or arcade-test)"
2231
+ ).option("--secure", "Use secure local topology", false).option("--room <id>", "Existing room ID").option("--controller-url <url>", "Existing controller join URL").option("--timeout-ms <ms>", "Connection timeout in milliseconds", Number).action(async (options) => {
2232
+ const input = resolveActionOptions(options);
2233
+ const result = await openSession({
2234
+ dir: input.dir,
2235
+ gameId: input.game,
2236
+ mode: input.mode,
2237
+ secure: input.secure,
2238
+ roomId: input.room,
2239
+ controllerJoinUrl: input.controllerUrl,
2240
+ timeoutMs: input.timeoutMs
2241
+ });
2242
+ process.stdout.write(`${JSON.stringify(result, null, 2)}
2243
+ `);
2244
+ });
2245
+ sessionCommand.command("read").description("Read runtime and semantic state from a persistent session").argument("<session-id>", "Game session ID").option("--dir <path>", "Project directory").option("--timeout-ms <ms>", "Snapshot timeout in milliseconds", Number).action(async (sessionId, options) => {
2246
+ const input = resolveActionOptions(options);
2247
+ const result = await readSession({
2248
+ dir: input.dir,
2249
+ gameSessionId: sessionId,
2250
+ timeoutMs: input.timeoutMs
2251
+ });
2252
+ process.stdout.write(`${JSON.stringify(result, null, 2)}
2253
+ `);
2254
+ });
2255
+ sessionCommand.command("settings-read <session-id>").description("Read this host's settings values and revision").option("--dir <path>", "Project directory").action(async (gameSessionId, options) => {
2256
+ const { dir } = resolveActionOptions(options);
2257
+ process.stdout.write(
2258
+ `${JSON.stringify(await readGameSettings2({ gameSessionId, cwd: dir }), null, 2)}
2259
+ `
2260
+ );
2261
+ });
2262
+ sessionCommand.command("settings-update <session-id>").description("Change live settings at an expected revision").requiredOption("--patch <json>", "Settings patch JSON object").requiredOption(
2263
+ "--expected-revision <number>",
2264
+ "Revision from settings-read",
2265
+ Number
2266
+ ).option("--dir <path>", "Project directory").action(async (gameSessionId, options) => {
2267
+ const input = resolveActionOptions(options);
2268
+ const parsed = gameSessionOperationSchemas2["settings-update"].parse({
2269
+ gameSessionId,
2270
+ cwd: input.dir,
2271
+ patch: parseJsonObject(input.patch),
2272
+ expectedRevision: input.expectedRevision
2273
+ });
2274
+ process.stdout.write(
2275
+ `${JSON.stringify(await updateGameSettings2(parsed), null, 2)}
2276
+ `
2277
+ );
2278
+ });
2279
+ sessionCommand.command("control").description(
2280
+ "Send a fenced participant operation with an explicit lease and receipt"
2281
+ ).argument("<session-id>", "Game session ID").requiredOption(
2282
+ "--command <json>",
2283
+ "JSON containing expected identity, lease and operation (input/action/release)"
2284
+ ).option("--dir <path>", "Project directory").action(async (sessionId, options) => {
2285
+ const input = resolveActionOptions(
2286
+ options
2287
+ );
2288
+ const result = await controlSessionParticipant({
2289
+ dir: input.dir,
2290
+ gameSessionId: sessionId,
2291
+ command: parseJsonObject(input.command)
2292
+ });
2293
+ process.stdout.write(`${JSON.stringify(result, null, 2)}
2294
+ `);
2295
+ });
2296
+ sessionCommand.command("input").description("Send validated controller input through a persistent session").argument("<session-id>", "Game session ID").requiredOption("--input <json>", "Controller input JSON object").option("--dir <path>", "Project directory").action(async (sessionId, options) => {
2297
+ const input = resolveActionOptions(
2298
+ options
2299
+ );
2300
+ const result = await sendSessionInput({
2301
+ dir: input.dir,
2302
+ gameSessionId: sessionId,
2303
+ input: parseJsonObject(input.input)
2304
+ });
2305
+ process.stdout.write(`${JSON.stringify(result, null, 2)}
2306
+ `);
2307
+ });
2308
+ sessionCommand.command("invoke").description("Invoke one published semantic action").argument("<session-id>", "Game session ID").argument("<action-id>", "Published action ID, including its lane prefix").option("--payload <json>", "JSON payload or plain string payload").option("--dir <path>", "Project directory").option("--timeout-ms <ms>", "Action timeout in milliseconds", Number).action(async (sessionId, actionId, options) => {
2309
+ const input = resolveActionOptions(options);
2310
+ const result = await invokeSessionAction({
2311
+ dir: input.dir,
2312
+ gameSessionId: sessionId,
2313
+ actionId,
2314
+ ...input.payload !== void 0 ? { payload: parseJsonValue(input.payload) } : {},
2315
+ timeoutMs: input.timeoutMs
2316
+ });
2317
+ process.stdout.write(`${JSON.stringify(result, null, 2)}
2318
+ `);
2319
+ });
2320
+ sessionCommand.command("capture").description(
2321
+ "Capture canonical host and controller screenshots from a persistent session"
2322
+ ).argument("<session-id>", "Game session ID").option("--dir <path>", "Project directory").option("--timeout-ms <ms>", "Capture timeout in milliseconds", Number).action(async (sessionId, options) => {
2323
+ const input = resolveActionOptions(options);
2324
+ const result = await captureSessionVisuals({
2325
+ dir: input.dir,
2326
+ gameSessionId: sessionId,
2327
+ timeoutMs: input.timeoutMs
2328
+ });
2329
+ process.stdout.write(`${JSON.stringify(result, null, 2)}
2330
+ `);
2331
+ });
2332
+ sessionCommand.command("close").description("Close a persistent semantic game session").argument("<session-id>", "Game session ID").option("--dir <path>", "Project directory").action(async (sessionId, options) => {
2333
+ const input = resolveActionOptions(options);
2334
+ const result = await closeSession({
2335
+ dir: input.dir,
2336
+ gameSessionId: sessionId
2337
+ });
2338
+ process.stdout.write(`${JSON.stringify(result, null, 2)}
2339
+ `);
2340
+ });
2341
+ const sessionBrokerCommand = sessionCommand.command("broker").description("Inspect or stop the project-local semantic session broker");
2342
+ sessionBrokerCommand.command("status").description("Inspect broker health").option("--dir <path>", "Project directory").action(async (options) => {
2343
+ const result = await runSessionBrokerStatus(
2344
+ resolveActionOptions(options)
2345
+ );
2346
+ process.stdout.write(`${JSON.stringify(result, null, 2)}
2347
+ `);
2348
+ });
2349
+ sessionBrokerCommand.command("stop").description("Close active sessions and stop the broker").option("--dir <path>", "Project directory").action(async (options) => {
2350
+ const result = await runSessionBrokerStop(
2351
+ resolveActionOptions(options)
2352
+ );
2353
+ process.stdout.write(`${JSON.stringify(result, null, 2)}
2354
+ `);
2355
+ });
2356
+ sessionCommand.action(() => sessionCommand.outputHelp());
2357
+ registerRoomsCommand(program);
2358
+ program.command("status").description("Show local Air Jam dev process and known-port status").option("--dir <path>", "Project directory to inspect").action(async (options) => {
2359
+ const input = resolveActionOptions(options);
2360
+ const status = await getDevStatus({ cwd: input.dir });
2361
+ console.log(JSON.stringify(status, null, 2));
2362
+ });
2363
+ const resetCommand = program.command("reset").description("Reset local Air Jam development state");
2364
+ resetCommand.command("local").description(
2365
+ "Stop managed dev processes and stale known-port Air Jam local listeners"
2366
+ ).option("--dir <path>", "Project directory to reset").action(async (options) => {
2367
+ const input = resolveActionOptions(options);
2368
+ const result = await resetLocalDev({ cwd: input.dir });
2369
+ console.log(JSON.stringify(result, null, 2));
2370
+ });
2371
+ const devCommand = program.command("dev").description("Run project-local Air Jam game development").argument("[passthrough...]", "Additional runtime flags").allowExcessArguments(true).allowUnknownOption(false).option("--secure", "Start secure local game dev", false).option(
2372
+ "--secure-mode <mode>",
2373
+ "Secure mode to use when --secure is enabled (local or tunnel)"
2374
+ ).option(
2375
+ "--preview-managed",
2376
+ "Advanced/internal: start foreground Vite with a background server",
2377
+ false
2378
+ ).option("--web-only", "Start only the game app", false).option("--server-only", "Start only the local Air Jam server", false).option(
2379
+ "--allow-existing-game",
2380
+ "Reuse an already-running Vite server on the game port",
2381
+ false
2382
+ ).addHelpText(
2383
+ "after",
2384
+ [
2385
+ "",
2386
+ "Network isolation:",
2387
+ " VITE_PORT=<port> Game app port (default: 5173)",
2388
+ " AIR_JAM_SERVER_PORT=<port> Local server port (default: 4000)",
2389
+ " AIR_JAM_BIND_HOST=<address> Bind address (default: all interfaces)",
2390
+ " VITE_AIR_JAM_PUBLIC_HOST=<url> Explicit host/controller origin",
2391
+ "",
2392
+ "Set ports and the public origin when parallel agents or local projects need isolated dev stacks."
2393
+ ].join("\n")
2394
+ ).action(async () => {
2395
+ await runGameDevCli({
2396
+ argv: normalizeRuntimeCliArgv(process.argv.slice(3))
2397
+ });
2398
+ });
2399
+ devCommand.command("start").description("Start a managed Air Jam dev process and return JSON").option("--dir <path>", "Project directory to start").option("--game <id>", "Game ID in a monorepo").option(
2400
+ "--mode <mode>",
2401
+ "Dev mode (standalone-dev, arcade-dev, or arcade-test)",
2402
+ "standalone-dev"
2403
+ ).option("--secure", "Use secure local topology", false).action(async (options) => {
2404
+ const input = resolveActionOptions(options);
2405
+ const result = await startDev({
2406
+ cwd: input.dir,
2407
+ gameId: input.game,
2408
+ mode: input.mode,
2409
+ secure: input.secure
2410
+ });
2411
+ process.stdout.write(`${JSON.stringify(result, null, 2)}
2412
+ `);
2413
+ });
2414
+ devCommand.command("stop").description("Stop managed Air Jam dev processes and return JSON").option("--dir <path>", "Project directory to stop").option("--process <id>", "Managed process ID").option(
2415
+ "--mode <mode>",
2416
+ "Stop only one dev mode (standalone-dev, arcade-dev, or arcade-test)"
2417
+ ).action(async (options) => {
2418
+ const input = resolveActionOptions(options);
2419
+ const result = await stopDev({
2420
+ cwd: input.dir,
2421
+ processId: input.process,
2422
+ mode: input.mode
2423
+ });
2424
+ process.stdout.write(`${JSON.stringify(result, null, 2)}
2425
+ `);
2426
+ });
2427
+ program.command("secure:init").description("Initialize local secure Air Jam game development").argument("[passthrough...]", "Additional runtime flags").allowExcessArguments(true).allowUnknownOption(false).option("--mode <mode>", "Secure mode to configure (local or tunnel)").option("--hostname <hostname>", "Tunnel hostname for secure tunnel mode").option("--tunnel <name>", "Cloudflare tunnel name for secure tunnel mode").action(async () => {
2428
+ await runSecureInitCli({
2429
+ argv: normalizeRuntimeCliArgv(process.argv.slice(3))
2430
+ });
2431
+ });
2432
+ program.command("topology").description(
2433
+ "Print the resolved project runtime topology for the current game"
2434
+ ).allowUnknownOption(false).requiredOption(
2435
+ "--mode <mode>",
2436
+ "Topology mode to inspect (standalone-dev, self-hosted-production, hosted-release)"
2437
+ ).option(
2438
+ "--secure",
2439
+ "Resolve standalone local topology using trusted local HTTPS",
2440
+ false
2441
+ ).addHelpText(
2442
+ "after",
2443
+ "\nTopology honors VITE_PORT, AIR_JAM_SERVER_PORT, VITE_AIR_JAM_SERVER_URL, and VITE_AIR_JAM_PUBLIC_HOST.\n"
2444
+ ).action(async () => {
2445
+ await runProjectTopologyCli({
2446
+ argv: normalizeRuntimeCliArgv(process.argv.slice(3))
2447
+ });
2448
+ });
2449
+ return program;
2450
+ };
2451
+ async function main() {
2452
+ const program = buildProgram();
2453
+ await program.parseAsync(process.argv);
2454
+ }
2455
+ main().catch((err) => {
2456
+ if (isEnvValidationError(err)) {
2457
+ console.error(
2458
+ formatEnvValidationError(err, {
2459
+ docsHint: "Fix the listed env values in .env.local (or CI/deployment env) and retry."
2460
+ })
2461
+ );
2462
+ process.exit(1);
2463
+ return;
2464
+ }
2465
+ console.error(kleur3.red("Error:"), err);
2466
+ process.exit(1);
2467
+ });
2468
+ //# sourceMappingURL=index.js.map