@air-jam/devtools 0.9.3 → 1.0.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (263) hide show
  1. package/README.md +60 -0
  2. package/dist/{chunk-VKMJO6VN.js → chunk-2O67AXCU.js} +150 -40
  3. package/dist/chunk-2O67AXCU.js.map +1 -0
  4. package/dist/chunk-AO3ZDXF6.js +142 -0
  5. package/dist/chunk-AO3ZDXF6.js.map +1 -0
  6. package/dist/chunk-ART5TEYT.js +472 -0
  7. package/dist/chunk-ART5TEYT.js.map +1 -0
  8. package/dist/chunk-ASC2CK2R.js +77 -0
  9. package/dist/chunk-ASC2CK2R.js.map +1 -0
  10. package/dist/chunk-E3UZZGAV.js +50 -0
  11. package/dist/chunk-E3UZZGAV.js.map +1 -0
  12. package/dist/chunk-EJTE7UKX.js +64 -0
  13. package/dist/chunk-EJTE7UKX.js.map +1 -0
  14. package/dist/chunk-ESFKNN75.js +110 -0
  15. package/dist/chunk-ESFKNN75.js.map +1 -0
  16. package/dist/chunk-EU7A6PXW.js +1339 -0
  17. package/dist/chunk-EU7A6PXW.js.map +1 -0
  18. package/dist/chunk-FN7E6EA7.js +549 -0
  19. package/dist/chunk-FN7E6EA7.js.map +1 -0
  20. package/dist/chunk-GDFAWHGA.js +190 -0
  21. package/dist/chunk-GDFAWHGA.js.map +1 -0
  22. package/dist/chunk-HZUGBH4Y.js +347 -0
  23. package/dist/chunk-HZUGBH4Y.js.map +1 -0
  24. package/dist/chunk-ITKAOEGX.js +93 -0
  25. package/dist/chunk-ITKAOEGX.js.map +1 -0
  26. package/dist/chunk-JBCUTWRI.js +897 -0
  27. package/dist/chunk-JBCUTWRI.js.map +1 -0
  28. package/dist/chunk-JSI5S4WP.js +1174 -0
  29. package/dist/chunk-JSI5S4WP.js.map +1 -0
  30. package/dist/chunk-L4D675BG.js +97 -0
  31. package/dist/chunk-L4D675BG.js.map +1 -0
  32. package/dist/chunk-M6CJ7GQC.js +133 -0
  33. package/dist/chunk-M6CJ7GQC.js.map +1 -0
  34. package/dist/{chunk-CKFT2ZJE.js → chunk-MEIMOSZC.js} +53 -105
  35. package/dist/chunk-MEIMOSZC.js.map +1 -0
  36. package/dist/{chunk-GUEZP773.js → chunk-O3XG3FNL.js} +204 -41
  37. package/dist/chunk-O3XG3FNL.js.map +1 -0
  38. package/dist/chunk-OM6SCJ7H.js +18 -0
  39. package/dist/chunk-OM6SCJ7H.js.map +1 -0
  40. package/dist/chunk-PKD4WVX5.js +63 -0
  41. package/dist/chunk-PKD4WVX5.js.map +1 -0
  42. package/dist/chunk-PMBLXGFM.js +3384 -0
  43. package/dist/chunk-PMBLXGFM.js.map +1 -0
  44. package/dist/chunk-PMNE5GIN.js +279 -0
  45. package/dist/chunk-PMNE5GIN.js.map +1 -0
  46. package/dist/chunk-QAWI64VR.js +148 -0
  47. package/dist/chunk-QAWI64VR.js.map +1 -0
  48. package/dist/chunk-QGADSPHZ.js +449 -0
  49. package/dist/chunk-QGADSPHZ.js.map +1 -0
  50. package/dist/chunk-SPYN66UV.js +338 -0
  51. package/dist/chunk-SPYN66UV.js.map +1 -0
  52. package/dist/context.d.ts +9 -3
  53. package/dist/context.js +2 -1
  54. package/dist/controller.d.ts +33 -7
  55. package/dist/controller.js +18 -8
  56. package/dist/dependencies.d.ts +44 -0
  57. package/dist/dependencies.js +10 -0
  58. package/dist/dev.d.ts +9 -3
  59. package/dist/dev.js +3 -4
  60. package/dist/game-builds.d.ts +200 -0
  61. package/dist/game-builds.js +16 -0
  62. package/dist/game-builds.js.map +1 -0
  63. package/dist/game-run-watch-CEd_SpAT.d.ts +84 -0
  64. package/dist/game-runs.d.ts +1452 -0
  65. package/dist/game-runs.js +76 -0
  66. package/dist/game-runs.js.map +1 -0
  67. package/dist/game-session-broker-CUvORfMd.d.ts +439 -0
  68. package/dist/game-session-broker.d.ts +4 -57
  69. package/dist/game-session-broker.js +33 -228
  70. package/dist/game-session-broker.js.map +1 -1
  71. package/dist/game-session.d.ts +3931 -10
  72. package/dist/game-session.js +186 -15
  73. package/dist/game-session.js.map +1 -1
  74. package/dist/game-settings.d.ts +16 -0
  75. package/dist/game-settings.js +237 -0
  76. package/dist/game-settings.js.map +1 -0
  77. package/dist/games.d.ts +11 -4
  78. package/dist/games.js +4 -2
  79. package/dist/harness/visual.d.ts +34 -151
  80. package/dist/harness/visual.js +6 -1
  81. package/dist/logs.d.ts +8 -2
  82. package/dist/logs.js +3 -4
  83. package/dist/logs.js.map +1 -1
  84. package/dist/managed-process-scope-BicYi_t9.d.ts +3 -0
  85. package/dist/mcp-config.js +2 -1
  86. package/dist/mcp-config.js.map +1 -1
  87. package/dist/platform-auth.d.ts +8 -111
  88. package/dist/platform-auth.js +9 -1
  89. package/dist/platform-game-analytics.d.ts +51 -0
  90. package/dist/platform-game-analytics.js +49 -0
  91. package/dist/platform-game-analytics.js.map +1 -0
  92. package/dist/platform-game-app-id.d.ts +46 -0
  93. package/dist/platform-game-app-id.js +93 -0
  94. package/dist/platform-game-app-id.js.map +1 -0
  95. package/dist/platform-game-media.d.ts +40 -2
  96. package/dist/platform-game-media.js +1 -1
  97. package/dist/platform-games.d.ts +24 -2
  98. package/dist/platform-games.js +16 -84
  99. package/dist/platform-games.js.map +1 -1
  100. package/dist/quality.d.ts +9 -3
  101. package/dist/quality.js +3 -4
  102. package/dist/quality.js.map +1 -1
  103. package/dist/release.d.ts +226 -16
  104. package/dist/release.js +18 -1331
  105. package/dist/release.js.map +1 -1
  106. package/dist/rooms-check.d.ts +90 -0
  107. package/dist/rooms-check.js +717 -0
  108. package/dist/rooms-check.js.map +1 -0
  109. package/dist/source-tree-contract.d.ts +16 -0
  110. package/dist/source-tree-contract.js +13 -0
  111. package/dist/source-tree-contract.js.map +1 -0
  112. package/dist/testing.d.ts +464 -0
  113. package/dist/testing.js +27 -0
  114. package/dist/testing.js.map +1 -0
  115. package/dist/tooling/describe-game.js +54 -0
  116. package/dist/tooling/describe-game.js.map +1 -0
  117. package/dist/tooling/game-session-broker.js +28 -0
  118. package/dist/tooling/game-session-broker.js.map +1 -0
  119. package/dist/tooling/hold-runtime-host.js +769 -67
  120. package/dist/tooling/hold-runtime-host.js.map +1 -1
  121. package/dist/tooling/list-visual-scenarios.js +18 -55
  122. package/dist/tooling/list-visual-scenarios.js.map +1 -1
  123. package/dist/tooling/process-scope-bootstrap.mjs +24 -0
  124. package/dist/tooling/process-scope-guard.d.ts +2 -0
  125. package/dist/tooling/process-scope-guard.js +388 -0
  126. package/dist/tooling/process-scope-guard.js.map +1 -0
  127. package/dist/tooling/process-scope-windows.ps1 +148 -0
  128. package/dist/tooling/rooms-check-device.d.ts +2 -0
  129. package/dist/tooling/rooms-check-device.js +498 -0
  130. package/dist/tooling/rooms-check-device.js.map +1 -0
  131. package/dist/tooling/run-headless-room.d.ts +2 -0
  132. package/dist/tooling/run-headless-room.js +287 -0
  133. package/dist/tooling/run-headless-room.js.map +1 -0
  134. package/dist/tooling/run-test-profile.d.ts +2 -0
  135. package/dist/tooling/run-test-profile.js +181 -0
  136. package/dist/tooling/run-test-profile.js.map +1 -0
  137. package/dist/tooling/run-visual-capture.js +70 -34
  138. package/dist/tooling/run-visual-capture.js.map +1 -1
  139. package/dist/tooling/seal-game-build.d.ts +2 -0
  140. package/dist/tooling/seal-game-build.js +120 -0
  141. package/dist/tooling/seal-game-build.js.map +1 -0
  142. package/dist/{types-C6NrHt88.d.ts → types-CdYrgrG_.d.ts} +337 -76
  143. package/dist/types-DyRD-ym1.d.ts +141 -0
  144. package/dist/visual.d.ts +9 -3
  145. package/dist/visual.js +24 -68
  146. package/dist/visual.js.map +1 -1
  147. package/package.json +51 -14
  148. package/src/bounded-response.ts +28 -0
  149. package/src/built-game-runtime.ts +152 -0
  150. package/src/context.ts +2 -13
  151. package/src/controller-protocol.ts +22 -0
  152. package/src/controller.ts +747 -597
  153. package/src/current-room-host.ts +166 -0
  154. package/src/decision-provider.ts +102 -0
  155. package/src/dependencies.ts +176 -0
  156. package/src/dependency-install-contract.ts +12 -0
  157. package/src/dev.ts +46 -50
  158. package/src/game-action-observation.ts +11 -1
  159. package/src/game-build-protocol.ts +72 -0
  160. package/src/game-build.ts +483 -0
  161. package/src/game-run-owner.ts +2358 -0
  162. package/src/game-run-protocol.ts +448 -0
  163. package/src/game-run-record.ts +92 -0
  164. package/src/game-run-replay.ts +95 -0
  165. package/src/game-run-watch.ts +155 -0
  166. package/src/game-session-broker.ts +689 -197
  167. package/src/game-session-operations.ts +61 -0
  168. package/src/game-session-protocol.ts +180 -0
  169. package/src/game-session-runtime.ts +861 -0
  170. package/src/game-session.ts +164 -417
  171. package/src/game-settings.ts +295 -0
  172. package/src/games.ts +88 -92
  173. package/src/harness/visual/browser.ts +100 -0
  174. package/src/harness/visual/controller-observation.ts +181 -0
  175. package/src/harness/visual/runner.ts +24 -21
  176. package/src/harness/visual/runtime-controller-observations.ts +151 -0
  177. package/src/harness/visual/scenario-contract.ts +1 -2
  178. package/src/harness/visual/scenario-helpers.ts +5 -1
  179. package/src/harness/visual/screencast.ts +155 -0
  180. package/src/harness/visual/session.ts +72 -41
  181. package/src/harness/visual/types.ts +8 -5
  182. package/src/headless-room-protocol.ts +112 -0
  183. package/src/headless-room.ts +222 -0
  184. package/src/helper-channel.ts +229 -0
  185. package/src/helper-scripts.ts +25 -5
  186. package/src/installed-dependencies.ts +74 -0
  187. package/src/managed-process-scope.ts +481 -0
  188. package/src/node-process-environment.ts +10 -0
  189. package/src/platform-auth.ts +194 -55
  190. package/src/platform-game-analytics.ts +50 -0
  191. package/src/platform-game-app-id.ts +99 -0
  192. package/src/platform-games.ts +13 -111
  193. package/src/policy-artifact-contract.ts +52 -0
  194. package/src/policy-artifacts.ts +134 -0
  195. package/src/process-scope-admission.ts +50 -0
  196. package/src/process-scope-protocol.ts +66 -0
  197. package/src/process-scope.ts +327 -0
  198. package/src/release.ts +28 -42
  199. package/src/rooms-check-fleet.ts +194 -0
  200. package/src/rooms-check-link.ts +138 -0
  201. package/src/rooms-check-protocol.ts +244 -0
  202. package/src/rooms-check.ts +797 -0
  203. package/src/runtime-owner-protocol.ts +106 -18
  204. package/src/source-tree-contract.ts +70 -0
  205. package/src/source-tree.ts +84 -0
  206. package/src/test-profile-process.ts +153 -0
  207. package/src/test-profile-protocol.ts +116 -0
  208. package/src/testing.ts +430 -0
  209. package/src/tooling/declaration-hook.ts +52 -0
  210. package/src/tooling/describe-game.ts +49 -0
  211. package/src/tooling/game-session-broker.ts +7 -0
  212. package/src/tooling/hold-runtime-host.ts +255 -38
  213. package/src/tooling/list-visual-scenarios.ts +19 -62
  214. package/src/tooling/load-game.ts +79 -0
  215. package/src/tooling/process-scope-bootstrap.mjs +24 -0
  216. package/src/tooling/process-scope-guard.ts +213 -0
  217. package/src/tooling/process-scope-windows.ps1 +148 -0
  218. package/src/tooling/rooms-check-device.ts +493 -0
  219. package/src/tooling/run-headless-room.ts +326 -0
  220. package/src/tooling/run-test-profile.ts +190 -0
  221. package/src/tooling/run-visual-capture.ts +37 -23
  222. package/src/tooling/runtime-owner-actions.ts +23 -0
  223. package/src/tooling/seal-game-build.ts +118 -0
  224. package/src/tooling/visual-pack.ts +10 -45
  225. package/src/types.ts +54 -77
  226. package/src/visual.ts +14 -22
  227. package/src/windows-process-scopes.ts +189 -0
  228. package/dist/agent.d.ts +0 -15
  229. package/dist/agent.js +0 -19
  230. package/dist/chunk-5YAARMW5.js +0 -36
  231. package/dist/chunk-5YAARMW5.js.map +0 -1
  232. package/dist/chunk-6WQODT37.js +0 -1019
  233. package/dist/chunk-6WQODT37.js.map +0 -1
  234. package/dist/chunk-CKFT2ZJE.js.map +0 -1
  235. package/dist/chunk-ER3Q2C4G.js +0 -358
  236. package/dist/chunk-ER3Q2C4G.js.map +0 -1
  237. package/dist/chunk-GUEZP773.js.map +0 -1
  238. package/dist/chunk-HIDNI56E.js +0 -33
  239. package/dist/chunk-HIDNI56E.js.map +0 -1
  240. package/dist/chunk-QKXS5D35.js +0 -43
  241. package/dist/chunk-QKXS5D35.js.map +0 -1
  242. package/dist/chunk-S4LSCEVE.js +0 -261
  243. package/dist/chunk-S4LSCEVE.js.map +0 -1
  244. package/dist/chunk-VKMJO6VN.js.map +0 -1
  245. package/dist/chunk-WFUR3MXY.js +0 -67
  246. package/dist/chunk-WFUR3MXY.js.map +0 -1
  247. package/dist/chunk-XEMR7KUE.js +0 -361
  248. package/dist/chunk-XEMR7KUE.js.map +0 -1
  249. package/dist/chunk-ZLPD7FY5.js +0 -191
  250. package/dist/chunk-ZLPD7FY5.js.map +0 -1
  251. package/dist/tooling/agent-contract.js +0 -193
  252. package/dist/tooling/agent-contract.js.map +0 -1
  253. package/dist/tooling/inspect-airjam-agent.js +0 -37
  254. package/dist/tooling/inspect-airjam-agent.js.map +0 -1
  255. package/src/agent.ts +0 -380
  256. package/src/tooling/agent-contract.ts +0 -232
  257. package/src/tooling/agent-declaration.ts +0 -36
  258. package/src/tooling/airjam-agent-inspection.ts +0 -45
  259. package/src/tooling/airjam-agent.ts +0 -118
  260. package/src/tooling/inspect-airjam-agent.ts +0 -20
  261. /package/dist/{agent.js.map → dependencies.js.map} +0 -0
  262. /package/dist/tooling/{agent-contract.d.ts → describe-game.d.ts} +0 -0
  263. /package/dist/tooling/{inspect-airjam-agent.d.ts → game-session-broker.d.ts} +0 -0
@@ -1,48 +1,55 @@
1
+ import { spawn } from "node:child_process";
1
2
  import { randomBytes, randomUUID } from "node:crypto";
2
- import { chmod, mkdir, readFile, unlink, writeFile } from "node:fs/promises";
3
+ import { closeSync, existsSync, mkdirSync, openSync } from "node:fs";
4
+ import { mkdir, open, readFile, unlink } from "node:fs/promises";
3
5
  import {
4
6
  createServer,
5
7
  type IncomingMessage,
6
8
  type ServerResponse,
7
9
  } from "node:http";
8
10
  import path from "node:path";
11
+ import { z } from "zod";
9
12
  import {
10
- captureGameSessionVisuals,
11
- closeGameSession,
12
- invokeGameSessionAction,
13
- openGameSession,
14
- readGameSession,
15
- sendGameSessionInput,
16
- } from "./game-session.js";
17
- import type {
18
- CaptureGameSessionVisualsOptions,
19
- CloseGameSessionOptions,
20
- InvokeGameSessionActionOptions,
21
- OpenGameSessionOptions,
22
- ReadGameSessionOptions,
23
- SendGameSessionInputOptions,
24
- } from "./types.js";
25
-
26
- export type AirJamGameSessionBrokerState = {
27
- schemaVersion: 1;
28
- instanceId: string;
29
- pid: number;
30
- projectDir: string;
31
- origin: string;
32
- secret: string;
33
- startedAt: string;
34
- };
35
-
36
- export type AirJamGameSessionBrokerOperation =
37
- | { operation: "health"; input?: undefined }
38
- | { operation: "open"; input: OpenGameSessionOptions }
39
- | { operation: "read"; input: ReadGameSessionOptions }
40
- | { operation: "input"; input: SendGameSessionInputOptions }
41
- | { operation: "invoke"; input: InvokeGameSessionActionOptions }
42
- | { operation: "capture"; input: CaptureGameSessionVisualsOptions }
43
- | { operation: "close"; input: CloseGameSessionOptions }
44
- | { operation: "shutdown"; input?: undefined };
13
+ currentRoomHost,
14
+ currentRoomSeatClaimer,
15
+ } from "./current-room-host.js";
16
+ import { takeDecisionProviderFromEnvironment } from "./decision-provider.js";
17
+ import { GameRunOwner } from "./game-run-owner.js";
18
+ import {
19
+ GAME_RUN_PROTOCOL_VERSION,
20
+ GAME_SESSION_BROKER_STATE_FILE,
21
+ MAXIMUM_GAME_RUN_MS,
22
+ } from "./game-run-protocol.js";
23
+ import {
24
+ gameRunWatchRequestSchema,
25
+ GameRunWatchWriter,
26
+ readGameRunWatchStream,
27
+ type GameRunWatchEvent,
28
+ } from "./game-run-watch.js";
29
+ import {
30
+ gameSessionBrokerRequestSchema,
31
+ type GameSessionBrokerRequest,
32
+ } from "./game-session-protocol.js";
33
+ import { createGameSessionRuntime } from "./game-session-runtime.js";
34
+ import {
35
+ resolveDevtoolsHelperArgs,
36
+ resolveDevtoolsHelperScript,
37
+ } from "./helper-scripts.js";
38
+ import { assertProcessScopesConfirmed } from "./managed-process-scope.js";
45
39
 
40
+ const stateSchema = z
41
+ .object({
42
+ schemaVersion: z.literal(1),
43
+ instanceId: z.uuid(),
44
+ pid: z.number().int().positive(),
45
+ projectDir: z.string().min(1),
46
+ origin: z.string().regex(/^http:\/\/127\.0\.0\.1:\d+$/),
47
+ secret: z.string().min(40),
48
+ startedAt: z.iso.datetime(),
49
+ })
50
+ .strict();
51
+ export type AirJamGameSessionBrokerState = z.infer<typeof stateSchema>;
52
+ export type AirJamGameSessionBrokerOperation = GameSessionBrokerRequest;
46
53
  export type AirJamGameSessionBrokerHealth = {
47
54
  ok: true;
48
55
  instanceId: string;
@@ -50,90 +57,67 @@ export type AirJamGameSessionBrokerHealth = {
50
57
  projectDir: string;
51
58
  activeSessionCount: number;
52
59
  startedAt: string;
60
+ draining: boolean;
61
+ processScopeError: string | null;
62
+ gameRunProtocolVersion: number;
63
+ cleanupFailures: Array<{ gameSessionId: string; message: string }>;
53
64
  };
54
65
 
55
- const BROKER_STATE_RELATIVE_PATH = path.join(
56
- ".airjam",
57
- "devtools",
58
- "game-session-broker.json",
59
- );
60
- const REQUEST_BODY_LIMIT_BYTES = 1_048_576;
61
-
62
- export const resolveGameSessionBrokerStatePath = (projectDir: string): string =>
63
- path.join(projectDir, BROKER_STATE_RELATIVE_PATH);
66
+ const SESSION_IDLE_MS = 15 * 60_000;
67
+ const SESSION_MAXIMUM_MS = 60 * 60_000;
68
+ const EMPTY_OWNER_IDLE_MS = 5 * 60_000;
69
+ if (MAXIMUM_GAME_RUN_MS >= SESSION_IDLE_MS)
70
+ throw new Error(
71
+ "Run lifetime must remain below the session idle lease until activity renewal is introduced.",
72
+ );
73
+ export const resolveGameSessionBrokerStatePath = (projectDir: string) =>
74
+ path.join(projectDir, GAME_SESSION_BROKER_STATE_FILE);
64
75
 
65
- export const readGameSessionBrokerState = async (
66
- projectDir: string,
67
- ): Promise<AirJamGameSessionBrokerState | null> => {
76
+ export async function readGameSessionBrokerState(projectDir: string) {
77
+ let source: string;
68
78
  try {
69
- const value = JSON.parse(
70
- await readFile(resolveGameSessionBrokerStatePath(projectDir), "utf8"),
71
- ) as Partial<AirJamGameSessionBrokerState>;
72
- if (
73
- value.schemaVersion !== 1 ||
74
- typeof value.instanceId !== "string" ||
75
- typeof value.pid !== "number" ||
76
- typeof value.projectDir !== "string" ||
77
- typeof value.origin !== "string" ||
78
- typeof value.secret !== "string" ||
79
- typeof value.startedAt !== "string"
80
- ) {
81
- return null;
82
- }
83
- return value as AirJamGameSessionBrokerState;
79
+ source = await readFile(
80
+ resolveGameSessionBrokerStatePath(projectDir),
81
+ "utf8",
82
+ );
83
+ } catch (error) {
84
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return null;
85
+ throw error;
86
+ }
87
+ try {
88
+ return stateSchema.parse(JSON.parse(source));
84
89
  } catch {
85
90
  return null;
86
91
  }
87
- };
92
+ }
88
93
 
89
- const readJsonBody = async (request: IncomingMessage): Promise<unknown> => {
90
- const chunks: Buffer[] = [];
91
- let size = 0;
92
- for await (const chunk of request) {
93
- const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
94
- size += buffer.length;
95
- if (size > REQUEST_BODY_LIMIT_BYTES) {
96
- throw new Error("Game session broker request exceeds 1 MiB.");
97
- }
98
- chunks.push(buffer);
99
- }
100
- return JSON.parse(Buffer.concat(chunks).toString("utf8"));
101
- };
102
-
103
- const writeJson = (
104
- response: ServerResponse,
105
- statusCode: number,
106
- value: unknown,
107
- ): void => {
108
- response.writeHead(statusCode, {
109
- "content-type": "application/json; charset=utf-8",
110
- "cache-control": "no-store",
111
- });
112
- response.end(`${JSON.stringify(value)}\n`);
113
- };
114
-
115
- export const requestGameSessionBroker = async <TResult>({
94
+ export async function requestGameSessionBroker<TResult>({
116
95
  state,
117
96
  request,
118
97
  }: {
119
98
  state: AirJamGameSessionBrokerState;
120
99
  request: AirJamGameSessionBrokerOperation;
121
- }): Promise<TResult> => {
100
+ }): Promise<TResult> {
101
+ const operation = gameSessionBrokerRequestSchema.parse(request);
122
102
  const timeoutMs =
123
- request.operation === "open"
124
- ? Math.max(120_000, (request.input.timeoutMs ?? 0) + 60_000)
125
- : request.operation === "read" ||
126
- request.operation === "invoke" ||
127
- request.operation === "capture"
128
- ? Math.max(30_000, (request.input.timeoutMs ?? 0) + 10_000)
129
- : 30_000;
103
+ operation.operation === "health"
104
+ ? 1500
105
+ : operation.operation === "shutdown" ||
106
+ operation.operation === "run.stop" ||
107
+ operation.operation === "run.stop-all" ||
108
+ operation.operation === "run.cancel"
109
+ ? 150_000
110
+ : "input" in operation && "timeoutMs" in operation.input
111
+ ? Math.max(30_000, (operation.input.timeoutMs ?? 90_000) + 60_000)
112
+ : 30_000;
130
113
  const response = await fetch(`${state.origin}/v1/game-session`, {
131
114
  method: "POST",
132
115
  headers: {
133
116
  authorization: `Bearer ${state.secret}`,
117
+ "x-airjam-owner": state.instanceId,
134
118
  "content-type": "application/json",
135
119
  },
136
- body: JSON.stringify(request),
120
+ body: JSON.stringify(operation),
137
121
  signal: AbortSignal.timeout(timeoutMs),
138
122
  });
139
123
  const result = (await response.json()) as {
@@ -141,104 +125,537 @@ export const requestGameSessionBroker = async <TResult>({
141
125
  result?: TResult;
142
126
  error?: { message?: string };
143
127
  };
144
- if (!response.ok || result.ok !== true) {
128
+ if (!response.ok || result.ok !== true)
145
129
  throw new Error(
146
130
  result.error?.message ??
147
131
  `Game session broker request failed with HTTP ${response.status}.`,
148
132
  );
149
- }
150
133
  return result.result as TResult;
151
- };
134
+ }
135
+
136
+ export async function readGameSessionBrokerHealth(
137
+ state: AirJamGameSessionBrokerState,
138
+ ) {
139
+ try {
140
+ const health =
141
+ await requestGameSessionBroker<AirJamGameSessionBrokerHealth>({
142
+ state,
143
+ request: { operation: "health" },
144
+ });
145
+ if (
146
+ health.instanceId !== state.instanceId ||
147
+ health.projectDir !== state.projectDir ||
148
+ health.pid !== state.pid
149
+ )
150
+ throw new Error(
151
+ "Game session owner identity does not match its discovery record.",
152
+ );
153
+ return health;
154
+ } catch {
155
+ return null;
156
+ }
157
+ }
152
158
 
153
- export const runGameSessionBroker = async ({
159
+ function requireCurrentOwnerProtocol(health: AirJamGameSessionBrokerHealth) {
160
+ if (health.gameRunProtocolVersion !== GAME_RUN_PROTOCOL_VERSION)
161
+ throw new Error(
162
+ "owner_protocol_mismatch: Stop the existing game session owner before using the updated runtime.",
163
+ );
164
+ }
165
+ export async function ensureGameSessionBroker(projectDir: string) {
166
+ const state = await readGameSessionBrokerState(projectDir);
167
+ if (state) {
168
+ const health = await readGameSessionBrokerHealth(state);
169
+ if (health) {
170
+ requireCurrentOwnerProtocol(health);
171
+ return state;
172
+ }
173
+ throw new Error(
174
+ `broker_unresponsive: Owner ${state.instanceId} (pid ${state.pid}) is unavailable. Run airjam session stop --dir ${projectDir} before restarting it.`,
175
+ );
176
+ }
177
+ const statePath = resolveGameSessionBrokerStatePath(projectDir);
178
+ if (!existsSync(statePath)) {
179
+ const logDirectory = path.join(projectDir, ".airjam", "logs");
180
+ mkdirSync(logDirectory, { recursive: true });
181
+ const descriptor = openSync(
182
+ path.join(logDirectory, "game-session-broker.log"),
183
+ "a",
184
+ 0o600,
185
+ );
186
+ try {
187
+ const helper = resolveDevtoolsHelperScript("game-session-broker.ts");
188
+ const child = spawn(
189
+ process.execPath,
190
+ [...resolveDevtoolsHelperArgs(helper), projectDir],
191
+ {
192
+ cwd: projectDir,
193
+ detached: true,
194
+ stdio: ["ignore", descriptor, descriptor],
195
+ },
196
+ );
197
+ child.unref();
198
+ } finally {
199
+ closeSync(descriptor);
200
+ }
201
+ }
202
+ const deadline = Date.now() + 10_000;
203
+ while (Date.now() < deadline) {
204
+ const current = await readGameSessionBrokerState(projectDir);
205
+ if (current) {
206
+ const health = await readGameSessionBrokerHealth(current);
207
+ if (health) {
208
+ requireCurrentOwnerProtocol(health);
209
+ return current;
210
+ }
211
+ }
212
+ await new Promise((resolve) => setTimeout(resolve, 50));
213
+ }
214
+ throw new Error(
215
+ `broker_unavailable: Inspect ${path.join(projectDir, ".airjam", "logs", "game-session-broker.log")}; an existing discovery record requires explicit session stop.`,
216
+ );
217
+ }
218
+
219
+ export async function getGameSessionBrokerStatus(projectDir: string) {
220
+ const state = await readGameSessionBrokerState(projectDir);
221
+ const health = state ? await readGameSessionBrokerHealth(state) : null;
222
+ return health
223
+ ? { running: true as const, ...health }
224
+ : {
225
+ running: false as const,
226
+ projectDir,
227
+ ...(state
228
+ ? { staleState: true, pid: state.pid, instanceId: state.instanceId }
229
+ : {}),
230
+ };
231
+ }
232
+
233
+ export async function stopGameSessionBroker(projectDir: string) {
234
+ const statePath = resolveGameSessionBrokerStatePath(projectDir);
235
+ await mkdir(path.dirname(statePath), { recursive: true });
236
+ const repairPath = `${statePath}.repair`;
237
+ const repair = await open(repairPath, "wx", 0o600);
238
+ try {
239
+ const state = await readGameSessionBrokerState(projectDir);
240
+ if (!state) {
241
+ if (existsSync(statePath))
242
+ throw new Error(
243
+ "Invalid owner record; inspect it before repairing it.",
244
+ );
245
+ return { stopped: false, running: false, projectDir };
246
+ }
247
+ if (await readGameSessionBrokerHealth(state))
248
+ return await requestGameSessionBroker<{
249
+ stopped: true;
250
+ instanceId: string;
251
+ }>({
252
+ state,
253
+ request: { operation: "shutdown" },
254
+ });
255
+ try {
256
+ process.kill(state.pid, 0);
257
+ } catch (error) {
258
+ if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error;
259
+ const current = await readGameSessionBrokerState(projectDir);
260
+ if (current?.instanceId !== state.instanceId)
261
+ throw new Error("Owner changed during repair.");
262
+ await unlink(statePath);
263
+ return {
264
+ stopped: false,
265
+ running: false,
266
+ staleStateRemoved: true,
267
+ instanceId: state.instanceId,
268
+ projectDir,
269
+ };
270
+ }
271
+ throw new Error(
272
+ `broker_unresponsive: Owner pid ${state.pid} is still alive. Stop that owner before removing its discovery record.`,
273
+ );
274
+ } finally {
275
+ await repair.close();
276
+ await unlink(repairPath);
277
+ }
278
+ }
279
+
280
+ async function readBody(request: IncomingMessage) {
281
+ const chunks: Buffer[] = [];
282
+ let size = 0;
283
+ for await (const chunk of request) {
284
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
285
+ size += buffer.length;
286
+ if (size > 1_048_576)
287
+ throw new Error("Game session broker request exceeds 1 MiB.");
288
+ chunks.push(buffer);
289
+ }
290
+ return gameSessionBrokerRequestSchema.parse(
291
+ JSON.parse(Buffer.concat(chunks).toString("utf8")),
292
+ );
293
+ }
294
+ function writeJson(response: ServerResponse, status: number, value: unknown) {
295
+ response.writeHead(status, {
296
+ "content-type": "application/json; charset=utf-8",
297
+ "cache-control": "no-store",
298
+ });
299
+ response.end(`${JSON.stringify(value)}\n`);
300
+ }
301
+
302
+ export async function runGameSessionBroker({
154
303
  projectDir,
155
304
  }: {
156
305
  projectDir: string;
157
- }): Promise<void> => {
306
+ }) {
307
+ const decisions = takeDecisionProviderFromEnvironment();
158
308
  const resolvedProjectDir = path.resolve(projectDir);
159
309
  const statePath = resolveGameSessionBrokerStatePath(resolvedProjectDir);
160
310
  const instanceId = randomUUID();
161
311
  const secret = randomBytes(32).toString("base64url");
162
312
  const startedAt = new Date().toISOString();
163
- const activeSessionIds = new Set<string>();
164
- let shuttingDown = false;
165
- let shutdownCleanup: Promise<void> = Promise.resolve();
313
+ const runtime = createGameSessionRuntime(instanceId);
314
+ const sessions = new Map<
315
+ string,
316
+ {
317
+ expiresAt: number;
318
+ maximumAt: number;
319
+ runId?: string;
320
+ cleanupFailure?: string;
321
+ }
322
+ >();
323
+ const opening = new Set<Promise<unknown>>();
324
+ let draining = false;
325
+ let lastOperationAt = Date.now();
326
+ let drainPromise: Promise<void> | undefined;
327
+ let owned = false;
328
+ const runs = new GameRunOwner({
329
+ projectDir: resolvedProjectDir,
330
+ ownerInstanceId: instanceId,
331
+ decisions,
332
+ async openSession({
333
+ runId,
334
+ gameId,
335
+ game,
336
+ nickname,
337
+ attachment,
338
+ build,
339
+ room,
340
+ settings,
341
+ onScope,
342
+ }) {
343
+ const pending = (async () => {
344
+ const session = await runtime
345
+ .openRunSession(
346
+ {
347
+ cwd: build?.rootDir ?? resolvedProjectDir,
348
+ gameId,
349
+ nickname,
350
+ ...(attachment
351
+ ? { controllerJoinUrl: attachment.controllerJoinUrl }
352
+ : {}),
353
+ },
354
+ {
355
+ delegation: attachment
356
+ ? {
357
+ host: currentRoomHost(attachment, instanceId),
358
+ seats: attachment.seats,
359
+ claimSeat: currentRoomSeatClaimer(attachment, instanceId),
360
+ }
361
+ : undefined,
362
+ build,
363
+ game,
364
+ room,
365
+ settings,
366
+ onScope,
367
+ },
368
+ )
369
+ .catch((error: unknown) => {
370
+ if (!attachment) throw error;
371
+ throw new Error(
372
+ /room[_ ]full/i.test(String(error))
373
+ ? "room_full: There is no free player seat in the current room."
374
+ : "current_room_unavailable: The delegated player could not join the current room.",
375
+ );
376
+ });
377
+ sessions.set(session.summary.gameSessionId, {
378
+ runId,
379
+ expiresAt: Date.now() + SESSION_IDLE_MS,
380
+ maximumAt: Date.now() + SESSION_MAXIMUM_MS,
381
+ });
382
+ return session;
383
+ })();
384
+ opening.add(pending);
385
+ try {
386
+ return await pending;
387
+ } finally {
388
+ opening.delete(pending);
389
+ }
390
+ },
391
+ sessionClosed(gameSessionId) {
392
+ sessions.delete(gameSessionId);
393
+ },
394
+ });
166
395
 
167
- const closeActiveSessions = async (): Promise<void> => {
168
- await Promise.all(
169
- [...activeSessionIds].map((gameSessionId) =>
170
- closeGameSession({ gameSessionId }).catch(() => undefined),
171
- ),
172
- );
173
- activeSessionIds.clear();
396
+ const closeSession = async (
397
+ gameSessionId: string,
398
+ reason: "stopped" | "session_expired" = "stopped",
399
+ ) => {
400
+ const lease = sessions.get(gameSessionId);
401
+ if (lease?.runId) {
402
+ return runs.closeSession(lease.runId, reason);
403
+ }
404
+ const result = await runtime.closeGameSession({ gameSessionId });
405
+ sessions.delete(gameSessionId);
406
+ return result;
174
407
  };
408
+ const drain = () =>
409
+ (drainPromise ??= (async () => {
410
+ draining = true;
411
+ const runCleanup = await Promise.allSettled([runs.drain()]);
412
+ await Promise.allSettled(opening);
413
+ const results = await Promise.allSettled(
414
+ [...sessions.keys()].map((id) => closeSession(id)),
415
+ );
416
+ const failures = [...runCleanup, ...results].filter(
417
+ (result) => result.status === "rejected",
418
+ );
419
+ if (failures.length)
420
+ throw new AggregateError(
421
+ failures.map((result) => result.reason),
422
+ "Game session cleanup failed: " +
423
+ failures.map((result) => String(result.reason)).join("; "),
424
+ );
425
+ })());
175
426
 
176
427
  const server = createServer(async (request, response) => {
177
- if (request.method !== "POST" || request.url !== "/v1/game-session") {
178
- writeJson(response, 404, { ok: false, error: { message: "Not found." } });
179
- return;
180
- }
181
- if (request.headers.authorization !== `Bearer ${secret}`) {
182
- writeJson(response, 401, {
428
+ if (request.method !== "POST" || request.url !== "/v1/game-session")
429
+ return writeJson(response, 404, {
430
+ ok: false,
431
+ error: { message: "Not found." },
432
+ });
433
+ if (request.headers.authorization !== `Bearer ${secret}`)
434
+ return writeJson(response, 401, {
183
435
  ok: false,
184
436
  error: { message: "Invalid game session broker credentials." },
185
437
  });
186
- return;
187
- }
188
-
438
+ if (request.headers["x-airjam-owner"] !== instanceId)
439
+ return writeJson(response, 409, {
440
+ ok: false,
441
+ error: {
442
+ message:
443
+ "owner_replaced: Game session owner does not match this request.",
444
+ },
445
+ });
189
446
  try {
190
- const operation = (await readJsonBody(
191
- request,
192
- )) as AirJamGameSessionBrokerOperation;
193
- let result: unknown;
194
- switch (operation.operation) {
195
- case "health":
196
- result = {
447
+ const operation = await readBody(request);
448
+ if (operation.operation === "health") {
449
+ let processScopeError: string | null = null;
450
+ try {
451
+ assertProcessScopesConfirmed();
452
+ } catch (error) {
453
+ processScopeError =
454
+ error instanceof Error ? error.message : String(error);
455
+ }
456
+ return writeJson(response, 200, {
457
+ ok: true,
458
+ result: {
197
459
  ok: true,
198
460
  instanceId,
199
461
  pid: process.pid,
200
462
  projectDir: resolvedProjectDir,
201
- activeSessionCount: activeSessionIds.size,
463
+ activeSessionCount: sessions.size,
202
464
  startedAt,
203
- } satisfies AirJamGameSessionBrokerHealth;
204
- break;
205
- case "open": {
206
- const opened = await openGameSession({
465
+ draining,
466
+ processScopeError,
467
+ gameRunProtocolVersion: GAME_RUN_PROTOCOL_VERSION,
468
+ cleanupFailures: [...sessions].flatMap(([gameSessionId, lease]) =>
469
+ lease.cleanupFailure
470
+ ? [{ gameSessionId, message: lease.cleanupFailure }]
471
+ : [],
472
+ ),
473
+ } satisfies AirJamGameSessionBrokerHealth,
474
+ });
475
+ }
476
+ if (operation.operation === "shutdown") {
477
+ try {
478
+ await drain();
479
+ writeJson(response, 200, {
480
+ ok: true,
481
+ result: { stopped: true, instanceId },
482
+ });
483
+ } finally {
484
+ server.close();
485
+ }
486
+ return;
487
+ }
488
+ if (draining)
489
+ throw new Error("owner_stopping: No new operations are accepted.");
490
+ lastOperationAt = Date.now();
491
+ switch (operation.operation) {
492
+ case "run.watch": {
493
+ const cancellation = new AbortController();
494
+ const writer = new GameRunWatchWriter(response);
495
+ const disconnected = () => {
496
+ writer.close();
497
+ cancellation.abort();
498
+ };
499
+ response.once("close", disconnected);
500
+ try {
501
+ await runs.watch(
502
+ operation.input,
503
+ (event) => {
504
+ if (!response.headersSent)
505
+ response.writeHead(200, {
506
+ "content-type": "application/x-ndjson",
507
+ "cache-control": "no-store",
508
+ });
509
+ writer.send(event);
510
+ },
511
+ cancellation.signal,
512
+ );
513
+ } catch (error) {
514
+ if (!response.destroyed) {
515
+ const message =
516
+ error instanceof Error ? error.message : String(error);
517
+ if (!response.headersSent)
518
+ writeJson(response, 409, { ok: false, error: { message } });
519
+ else
520
+ writer.send({ type: "error", message: message.slice(0, 4000) });
521
+ }
522
+ } finally {
523
+ writer.close();
524
+ response.off("close", disconnected);
525
+ if (!response.writableEnded) response.end();
526
+ }
527
+ return;
528
+ }
529
+ case "run.start":
530
+ return writeJson(response, 200, {
531
+ ok: true,
532
+ result: await runs.start(operation.input, operation.attachment),
533
+ });
534
+ case "run.read":
535
+ return writeJson(response, 200, {
536
+ ok: true,
537
+ result: await runs.read(operation.input.runId),
538
+ });
539
+ case "run.wait": {
540
+ const cancellation = new AbortController();
541
+ const disconnected = () => cancellation.abort();
542
+ response.once("close", disconnected);
543
+ try {
544
+ return writeJson(response, 200, {
545
+ ok: true,
546
+ result: await runs.wait(
547
+ operation.input.runId,
548
+ operation.input.timeoutMs,
549
+ cancellation.signal,
550
+ ),
551
+ });
552
+ } finally {
553
+ response.off("close", disconnected);
554
+ }
555
+ }
556
+ case "run.stop":
557
+ return writeJson(response, 200, {
558
+ ok: true,
559
+ result: await runs.stop(operation.input.runId),
560
+ });
561
+ case "run.steer":
562
+ return writeJson(response, 200, {
563
+ ok: true,
564
+ result: await runs.steer(operation.input),
565
+ });
566
+ case "run.list":
567
+ return writeJson(response, 200, { ok: true, result: runs.list() });
568
+ case "run.stop-all":
569
+ return writeJson(response, 200, {
570
+ ok: true,
571
+ result: await runs.stopAll(),
572
+ });
573
+ case "run.cancel":
574
+ return writeJson(response, 200, {
575
+ ok: true,
576
+ result: await runs.cancel(operation.input.runId),
577
+ });
578
+ case "run.profiles":
579
+ return writeJson(response, 200, {
580
+ ok: true,
581
+ result: await runs.discover(operation.input.gameId),
582
+ });
583
+ }
584
+ if (operation.operation === "open") {
585
+ const pending = (async () => {
586
+ const opened = await runtime.openGameSession({
207
587
  ...operation.input,
208
588
  cwd: resolvedProjectDir,
209
589
  });
210
- activeSessionIds.add(opened.gameSessionId);
211
- result = opened;
212
- break;
590
+ if (draining) {
591
+ await runtime.closeGameSession({
592
+ gameSessionId: opened.gameSessionId,
593
+ });
594
+ throw new Error("owner_stopping: Session open cancelled.");
595
+ }
596
+ sessions.set(opened.gameSessionId, {
597
+ expiresAt: Date.now() + SESSION_IDLE_MS,
598
+ maximumAt: Date.now() + SESSION_MAXIMUM_MS,
599
+ });
600
+ return opened;
601
+ })();
602
+ opening.add(pending);
603
+ try {
604
+ return writeJson(response, 200, { ok: true, result: await pending });
605
+ } finally {
606
+ opening.delete(pending);
213
607
  }
608
+ }
609
+ const lease = sessions.get(operation.input.gameSessionId);
610
+ if (!lease)
611
+ throw new Error(
612
+ `unknown_session: Session does not belong to owner ${instanceId}, project ${resolvedProjectDir}, started ${startedAt}.`,
613
+ );
614
+ if (Date.now() >= lease.expiresAt || Date.now() >= lease.maximumAt) {
615
+ await closeSession(operation.input.gameSessionId, "session_expired");
616
+ throw new Error("session_expired: Its controller was disconnected.");
617
+ }
618
+ lease.expiresAt = Math.min(Date.now() + SESSION_IDLE_MS, lease.maximumAt);
619
+ if (
620
+ lease.runId &&
621
+ ["input", "invoke", "control", "close", "settings-update"].includes(
622
+ operation.operation,
623
+ )
624
+ )
625
+ throw new Error(
626
+ "session_owned_by_run: Interactive writes are refused; use run.stop to end this activity.",
627
+ );
628
+ let result: unknown;
629
+ switch (operation.operation) {
214
630
  case "read":
215
- result = await readGameSession(operation.input);
631
+ result = await runtime.readGameSession(operation.input);
632
+ break;
633
+ case "observe":
634
+ result = await runtime.observeGameSession(operation.input);
635
+ break;
636
+ case "settings-read":
637
+ result = await runtime.readGameSettings(operation.input);
638
+ break;
639
+ case "settings-update":
640
+ result = await runtime.updateGameSettings(operation.input);
641
+ break;
642
+ case "control":
643
+ result = await runtime.controlGameSessionParticipant(operation.input);
216
644
  break;
217
645
  case "input":
218
- result = await sendGameSessionInput(operation.input);
646
+ result = await runtime.sendGameSessionInput(operation.input);
219
647
  break;
220
648
  case "invoke":
221
- result = await invokeGameSessionAction(operation.input);
649
+ result = await runtime.invokeGameSessionAction(operation.input);
222
650
  break;
223
651
  case "capture":
224
- result = await captureGameSessionVisuals(operation.input);
652
+ result = await runtime.captureGameSessionVisuals(operation.input);
225
653
  break;
226
654
  case "close":
227
- result = await closeGameSession(operation.input);
228
- activeSessionIds.delete(operation.input.gameSessionId);
655
+ result = await closeSession(operation.input.gameSessionId);
229
656
  break;
230
- case "shutdown":
231
- await closeActiveSessions();
232
- result = { stopped: true, instanceId };
233
- shuttingDown = true;
234
- break;
235
- default:
236
- throw new Error("Unknown game session broker operation.");
237
657
  }
238
658
  writeJson(response, 200, { ok: true, result });
239
- if (shuttingDown) {
240
- server.close();
241
- }
242
659
  } catch (error) {
243
660
  writeJson(response, 400, {
244
661
  ok: false,
@@ -248,32 +665,66 @@ export const runGameSessionBroker = async ({
248
665
  });
249
666
  }
250
667
  });
251
-
252
- const cleanupState = async (): Promise<void> => {
253
- const current = await readGameSessionBrokerState(resolvedProjectDir);
254
- if (current?.instanceId === instanceId) {
255
- await unlink(statePath).catch(() => undefined);
256
- }
257
- };
258
- const stop = (): void => {
259
- if (!shuttingDown) {
260
- shuttingDown = true;
261
- server.close();
262
- shutdownCleanup = closeActiveSessions();
263
- }
264
- };
265
- process.once("SIGTERM", stop);
266
- process.once("SIGINT", stop);
267
-
268
- await new Promise<void>((resolve, reject) => {
269
- server.once("error", reject);
270
- server.listen(0, "127.0.0.1", async () => {
271
- try {
272
- const address = server.address();
273
- if (!address || typeof address === "string") {
274
- throw new Error("Game session broker did not bind a TCP port.");
668
+ let sweeping = false;
669
+ const sweep = setInterval(() => {
670
+ if (!owned || draining || sweeping) return;
671
+ sweeping = true;
672
+ const now = Date.now();
673
+ const expired = [...sessions].filter(
674
+ ([, lease]) =>
675
+ !lease.cleanupFailure &&
676
+ (now >= lease.expiresAt || now >= lease.maximumAt),
677
+ );
678
+ void Promise.allSettled(
679
+ expired.map(([id]) => closeSession(id, "session_expired")),
680
+ )
681
+ .then(async (results) => {
682
+ for (const [index, result] of results.entries()) {
683
+ if (result.status !== "rejected") continue;
684
+ const [id, lease] = expired[index];
685
+ lease.cleanupFailure =
686
+ result.reason instanceof Error
687
+ ? result.reason.message
688
+ : String(result.reason);
689
+ console.error(
690
+ `Session ${id} cleanup failed: ${lease.cleanupFailure}`,
691
+ );
692
+ }
693
+ if (
694
+ !sessions.size &&
695
+ !opening.size &&
696
+ now - lastOperationAt >= EMPTY_OWNER_IDLE_MS
697
+ ) {
698
+ await drain();
699
+ server.close();
275
700
  }
276
- const state: AirJamGameSessionBrokerState = {
701
+ })
702
+ .catch((error) => {
703
+ console.error(error);
704
+ })
705
+ .finally(() => {
706
+ sweeping = false;
707
+ });
708
+ }, 1000);
709
+ const stop = () => {
710
+ void drain()
711
+ .catch((error) => console.error(error))
712
+ .finally(() => server.close());
713
+ };
714
+ try {
715
+ await new Promise<void>((resolve, reject) => {
716
+ server.once("error", reject);
717
+ server.listen(0, "127.0.0.1", () => resolve());
718
+ });
719
+ const address = server.address();
720
+ if (!address || typeof address === "string")
721
+ throw new Error("Game session broker did not bind a TCP port.");
722
+ await mkdir(path.dirname(statePath), { recursive: true });
723
+ const descriptor = await open(statePath, "wx", 0o600);
724
+ owned = true;
725
+ try {
726
+ await descriptor.writeFile(
727
+ JSON.stringify({
277
728
  schemaVersion: 1,
278
729
  instanceId,
279
730
  pid: process.pid,
@@ -281,21 +732,62 @@ export const runGameSessionBroker = async ({
281
732
  origin: `http://127.0.0.1:${address.port}`,
282
733
  secret,
283
734
  startedAt,
284
- };
285
- await mkdir(path.dirname(statePath), { recursive: true });
286
- await writeFile(statePath, `${JSON.stringify(state, null, 2)}\n`, {
287
- encoding: "utf8",
288
- mode: 0o600,
289
- });
290
- await chmod(statePath, 0o600);
291
- } catch (error) {
292
- server.close();
293
- reject(error);
294
- }
295
- });
296
- server.once("close", resolve);
297
- });
735
+ } satisfies AirJamGameSessionBrokerState),
736
+ );
737
+ } finally {
738
+ await descriptor.close();
739
+ }
740
+ process.once("SIGTERM", stop);
741
+ process.once("SIGINT", stop);
742
+ await new Promise<void>((resolve) => server.once("close", resolve));
743
+ if (drainPromise) await drainPromise;
744
+ } finally {
745
+ clearInterval(sweep);
746
+ process.removeListener("SIGTERM", stop);
747
+ process.removeListener("SIGINT", stop);
748
+ if (server.listening) server.close();
749
+ if (
750
+ owned &&
751
+ (await readGameSessionBrokerState(resolvedProjectDir))?.instanceId ===
752
+ instanceId
753
+ )
754
+ await unlink(statePath);
755
+ }
756
+ }
298
757
 
299
- await shutdownCleanup;
300
- await cleanupState();
301
- };
758
+ export async function watchGameSessionBroker({
759
+ state,
760
+ input,
761
+ onEvent,
762
+ signal,
763
+ }: {
764
+ state: AirJamGameSessionBrokerState;
765
+ input: unknown;
766
+ onEvent: (event: GameRunWatchEvent) => void;
767
+ signal: AbortSignal;
768
+ }) {
769
+ const request = {
770
+ operation: "run.watch",
771
+ input: gameRunWatchRequestSchema.parse(input),
772
+ };
773
+ const response = await fetch(`${state.origin}/v1/game-session`, {
774
+ method: "POST",
775
+ headers: {
776
+ authorization: `Bearer ${state.secret}`,
777
+ "x-airjam-owner": state.instanceId,
778
+ "content-type": "application/json",
779
+ },
780
+ body: JSON.stringify(request),
781
+ signal,
782
+ });
783
+ if (!response.ok) {
784
+ const failure = (await response.json()) as { error?: { message?: string } };
785
+ throw new Error(
786
+ failure.error?.message ??
787
+ `Run watch failed with HTTP ${response.status}.`,
788
+ );
789
+ }
790
+ if (!response.body)
791
+ throw new Error("Run watch response has no event stream.");
792
+ await readGameRunWatchStream(response.body, onEvent);
793
+ }