@air-jam/devtools 0.0.0-stage → 0.9.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +52 -2
  3. package/dist/agent.d.ts +15 -0
  4. package/dist/agent.js +19 -0
  5. package/dist/agent.js.map +1 -0
  6. package/dist/chunk-5YAARMW5.js +36 -0
  7. package/dist/chunk-5YAARMW5.js.map +1 -0
  8. package/dist/chunk-6WQODT37.js +1019 -0
  9. package/dist/chunk-6WQODT37.js.map +1 -0
  10. package/dist/chunk-CKFT2ZJE.js +801 -0
  11. package/dist/chunk-CKFT2ZJE.js.map +1 -0
  12. package/dist/chunk-ER3Q2C4G.js +358 -0
  13. package/dist/chunk-ER3Q2C4G.js.map +1 -0
  14. package/dist/chunk-GUEZP773.js +851 -0
  15. package/dist/chunk-GUEZP773.js.map +1 -0
  16. package/dist/chunk-HIDNI56E.js +33 -0
  17. package/dist/chunk-HIDNI56E.js.map +1 -0
  18. package/dist/chunk-QKXS5D35.js +43 -0
  19. package/dist/chunk-QKXS5D35.js.map +1 -0
  20. package/dist/chunk-S4LSCEVE.js +261 -0
  21. package/dist/chunk-S4LSCEVE.js.map +1 -0
  22. package/dist/chunk-VKMJO6VN.js +360 -0
  23. package/dist/chunk-VKMJO6VN.js.map +1 -0
  24. package/dist/chunk-WFUR3MXY.js +67 -0
  25. package/dist/chunk-WFUR3MXY.js.map +1 -0
  26. package/dist/chunk-XEMR7KUE.js +361 -0
  27. package/dist/chunk-XEMR7KUE.js.map +1 -0
  28. package/dist/chunk-ZLPD7FY5.js +191 -0
  29. package/dist/chunk-ZLPD7FY5.js.map +1 -0
  30. package/dist/context.d.ts +13 -0
  31. package/dist/context.js +9 -0
  32. package/dist/context.js.map +1 -0
  33. package/dist/controller.d.ts +41 -0
  34. package/dist/controller.js +30 -0
  35. package/dist/controller.js.map +1 -0
  36. package/dist/dev.d.ts +15 -0
  37. package/dist/dev.js +20 -0
  38. package/dist/dev.js.map +1 -0
  39. package/dist/game-session-broker.d.ts +57 -0
  40. package/dist/game-session-broker.js +235 -0
  41. package/dist/game-session-broker.js.map +1 -0
  42. package/dist/game-session.d.ts +13 -0
  43. package/dist/game-session.js +24 -0
  44. package/dist/game-session.js.map +1 -0
  45. package/dist/games.d.ts +21 -0
  46. package/dist/games.js +14 -0
  47. package/dist/games.js.map +1 -0
  48. package/dist/harness/visual.d.ts +321 -0
  49. package/dist/harness/visual.js +41 -0
  50. package/dist/harness/visual.js.map +1 -0
  51. package/dist/logs.d.ts +9 -0
  52. package/dist/logs.js +58 -0
  53. package/dist/logs.js.map +1 -0
  54. package/dist/mcp-config.d.ts +63 -0
  55. package/dist/mcp-config.js +190 -0
  56. package/dist/mcp-config.js.map +1 -0
  57. package/dist/platform-auth.d.ts +112 -0
  58. package/dist/platform-auth.js +37 -0
  59. package/dist/platform-auth.js.map +1 -0
  60. package/dist/platform-game-media.d.ts +309 -0
  61. package/dist/platform-game-media.js +168 -0
  62. package/dist/platform-game-media.js.map +1 -0
  63. package/dist/platform-games.d.ts +65 -0
  64. package/dist/platform-games.js +251 -0
  65. package/dist/platform-games.js.map +1 -0
  66. package/dist/quality.d.ts +10 -0
  67. package/dist/quality.js +63 -0
  68. package/dist/quality.js.map +1 -0
  69. package/dist/release.d.ts +1094 -0
  70. package/dist/release.js +1347 -0
  71. package/dist/release.js.map +1 -0
  72. package/dist/tooling/agent-contract.d.ts +2 -0
  73. package/dist/tooling/agent-contract.js +193 -0
  74. package/dist/tooling/agent-contract.js.map +1 -0
  75. package/dist/tooling/hold-runtime-host.d.ts +2 -0
  76. package/dist/tooling/hold-runtime-host.js +229 -0
  77. package/dist/tooling/hold-runtime-host.js.map +1 -0
  78. package/dist/tooling/inspect-airjam-agent.d.ts +2 -0
  79. package/dist/tooling/inspect-airjam-agent.js +37 -0
  80. package/dist/tooling/inspect-airjam-agent.js.map +1 -0
  81. package/dist/tooling/list-visual-scenarios.d.ts +2 -0
  82. package/dist/tooling/list-visual-scenarios.js +62 -0
  83. package/dist/tooling/list-visual-scenarios.js.map +1 -0
  84. package/dist/tooling/managed-dev-supervisor.d.ts +2 -0
  85. package/dist/tooling/managed-dev-supervisor.js +51 -0
  86. package/dist/tooling/managed-dev-supervisor.js.map +1 -0
  87. package/dist/tooling/run-visual-capture.d.ts +2 -0
  88. package/dist/tooling/run-visual-capture.js +167 -0
  89. package/dist/tooling/run-visual-capture.js.map +1 -0
  90. package/dist/types-C6NrHt88.d.ts +775 -0
  91. package/dist/visual.d.ts +15 -0
  92. package/dist/visual.js +263 -0
  93. package/dist/visual.js.map +1 -0
  94. package/package.json +113 -3
  95. package/src/agent.ts +380 -0
  96. package/src/commands.ts +40 -0
  97. package/src/context.ts +229 -0
  98. package/src/controller.ts +1376 -0
  99. package/src/dev.ts +999 -0
  100. package/src/fs-utils.ts +93 -0
  101. package/src/game-action-observation.ts +96 -0
  102. package/src/game-session-broker.ts +301 -0
  103. package/src/game-session.ts +459 -0
  104. package/src/games.ts +266 -0
  105. package/src/harness/visual/prefab-contract.ts +29 -0
  106. package/src/harness/visual/prefab-runner.ts +178 -0
  107. package/src/harness/visual/runner.ts +546 -0
  108. package/src/harness/visual/scenario-contract.ts +9 -0
  109. package/src/harness/visual/scenario-helpers.ts +63 -0
  110. package/src/harness/visual/session.ts +369 -0
  111. package/src/harness/visual/types.ts +181 -0
  112. package/src/harness/visual.ts +7 -0
  113. package/src/helper-scripts.ts +49 -0
  114. package/src/logs.ts +67 -0
  115. package/src/mcp-config.ts +262 -0
  116. package/src/platform-auth.ts +455 -0
  117. package/src/platform-game-media.ts +209 -0
  118. package/src/platform-games.ts +315 -0
  119. package/src/quality.ts +82 -0
  120. package/src/release.ts +1697 -0
  121. package/src/runtime-owner-protocol.ts +130 -0
  122. package/src/tooling/agent-contract.ts +232 -0
  123. package/src/tooling/agent-declaration.ts +36 -0
  124. package/src/tooling/airjam-agent-inspection.ts +45 -0
  125. package/src/tooling/airjam-agent.ts +118 -0
  126. package/src/tooling/hold-runtime-host.ts +224 -0
  127. package/src/tooling/inspect-airjam-agent.ts +20 -0
  128. package/src/tooling/list-visual-scenarios.ts +64 -0
  129. package/src/tooling/managed-dev-supervisor.ts +71 -0
  130. package/src/tooling/run-visual-capture.ts +217 -0
  131. package/src/tooling/runtime-owner-actions.ts +42 -0
  132. package/src/tooling/visual-pack.ts +46 -0
  133. package/src/types.ts +951 -0
  134. package/src/visual.ts +304 -0
  135. package/src/workspace-contract.ts +32 -0
@@ -0,0 +1,93 @@
1
+ import { access, readdir, readFile, realpath, stat } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import type { PackageJson } from "./types.js";
4
+
5
+ export const pathExists = async (targetPath: string): Promise<boolean> => {
6
+ try {
7
+ await access(targetPath);
8
+ return true;
9
+ } catch {
10
+ return false;
11
+ }
12
+ };
13
+
14
+ export const resolveCanonicalPath = async (
15
+ targetPath: string,
16
+ ): Promise<string> => {
17
+ const absolutePath = path.resolve(targetPath);
18
+ return realpath(absolutePath).catch(() => absolutePath);
19
+ };
20
+
21
+ export const readJsonFile = async <T = unknown>(filePath: string): Promise<T> =>
22
+ JSON.parse(await readFile(filePath, "utf8")) as T;
23
+
24
+ export const readPackageJson = async (
25
+ rootDir: string,
26
+ ): Promise<{ path: string; value: PackageJson } | null> => {
27
+ const packageJsonPath = path.join(rootDir, "package.json");
28
+ if (!(await pathExists(packageJsonPath))) {
29
+ return null;
30
+ }
31
+
32
+ return {
33
+ path: packageJsonPath,
34
+ value: await readJsonFile<PackageJson>(packageJsonPath),
35
+ };
36
+ };
37
+
38
+ export const findUp = async (
39
+ startDir: string,
40
+ fileName: string,
41
+ ): Promise<string | null> => {
42
+ let currentDir = path.resolve(startDir);
43
+
44
+ while (true) {
45
+ const candidate = path.join(currentDir, fileName);
46
+ if (await pathExists(candidate)) {
47
+ return candidate;
48
+ }
49
+
50
+ const parent = path.dirname(currentDir);
51
+ if (parent === currentDir) {
52
+ return null;
53
+ }
54
+ currentDir = parent;
55
+ }
56
+ };
57
+
58
+ export const listDirectories = async (rootDir: string): Promise<string[]> => {
59
+ if (!(await pathExists(rootDir))) {
60
+ return [];
61
+ }
62
+
63
+ const entries = await readdir(rootDir);
64
+ const dirs = await Promise.all(
65
+ entries.map(async (entry) => {
66
+ const entryPath = path.join(rootDir, entry);
67
+ const entryStat = await stat(entryPath).catch(() => null);
68
+ return entryStat?.isDirectory() ? entryPath : null;
69
+ }),
70
+ );
71
+
72
+ return dirs.filter((dir): dir is string => Boolean(dir));
73
+ };
74
+
75
+ export const firstExistingPath = async (
76
+ candidates: string[],
77
+ ): Promise<string | null> => {
78
+ for (const candidate of candidates) {
79
+ if (await pathExists(candidate)) {
80
+ return candidate;
81
+ }
82
+ }
83
+
84
+ return null;
85
+ };
86
+
87
+ export const resolveCandidatePath = (
88
+ rootDir: string,
89
+ relativePaths: string[],
90
+ ): Promise<string | null> =>
91
+ firstExistingPath(
92
+ relativePaths.map((relativePath) => path.join(rootDir, relativePath)),
93
+ );
@@ -0,0 +1,96 @@
1
+ import type { AirJamActionInvocationResult } from "@air-jam/sdk/protocol";
2
+ import type { AirJamGameSnapshotInspection } from "./types.js";
3
+
4
+ export const isHostAcknowledgementObservationGap = (
5
+ acknowledgement: AirJamActionInvocationResult,
6
+ ): boolean =>
7
+ acknowledgement.status === "rejected" &&
8
+ (acknowledgement.reason === "host_ack_missing" ||
9
+ acknowledgement.reason === "host_ack_timeout");
10
+
11
+ const stableStoreSnapshotFingerprint = (
12
+ snapshot: AirJamGameSnapshotInspection,
13
+ ): string =>
14
+ JSON.stringify(
15
+ snapshot.rawStores
16
+ .map((entry) => ({
17
+ storeDomain: entry.storeDomain,
18
+ revision: entry.revision,
19
+ }))
20
+ .sort((left, right) => left.storeDomain.localeCompare(right.storeDomain)),
21
+ );
22
+
23
+ const stableStoreSnapshotDataFingerprint = (
24
+ snapshot: AirJamGameSnapshotInspection,
25
+ ): string =>
26
+ JSON.stringify(
27
+ snapshot.rawStores
28
+ .map((entry) => ({
29
+ storeDomain: entry.storeDomain,
30
+ data: entry.data,
31
+ }))
32
+ .sort((left, right) => left.storeDomain.localeCompare(right.storeDomain)),
33
+ );
34
+
35
+ export const computeGameSnapshotObservation = ({
36
+ snapshotBefore,
37
+ snapshotAfter,
38
+ }: {
39
+ snapshotBefore: AirJamGameSnapshotInspection;
40
+ snapshotAfter: AirJamGameSnapshotInspection;
41
+ }): {
42
+ snapshotAfterStatus:
43
+ | "committed-update-observed"
44
+ | "no-new-commit-before-timeout";
45
+ observedStateChange: boolean;
46
+ } => {
47
+ const fingerprintBefore = stableStoreSnapshotFingerprint(snapshotBefore);
48
+ const fingerprintAfter = stableStoreSnapshotFingerprint(snapshotAfter);
49
+ const dataFingerprintBefore =
50
+ stableStoreSnapshotDataFingerprint(snapshotBefore);
51
+ const dataFingerprintAfter =
52
+ stableStoreSnapshotDataFingerprint(snapshotAfter);
53
+ const projectedSnapshotBefore = JSON.stringify(snapshotBefore.snapshot);
54
+ const projectedSnapshotAfter = JSON.stringify(snapshotAfter.snapshot);
55
+
56
+ return {
57
+ snapshotAfterStatus:
58
+ fingerprintBefore === fingerprintAfter
59
+ ? "no-new-commit-before-timeout"
60
+ : "committed-update-observed",
61
+ observedStateChange:
62
+ dataFingerprintBefore !== dataFingerprintAfter ||
63
+ projectedSnapshotBefore !== projectedSnapshotAfter,
64
+ };
65
+ };
66
+
67
+ export const classifyGameActionOutcome = ({
68
+ acknowledgement,
69
+ observedStateChange,
70
+ }: {
71
+ acknowledgement: AirJamActionInvocationResult;
72
+ observedStateChange: boolean;
73
+ }): {
74
+ acknowledgementObservation:
75
+ | "host-acknowledged"
76
+ | "host-acknowledgement-not-observed";
77
+ outcome:
78
+ | "accepted"
79
+ | "rejected"
80
+ | "acknowledgement-not-observed-state-changed"
81
+ | "acknowledgement-not-observed-no-state-change-observed";
82
+ } => {
83
+ if (!isHostAcknowledgementObservationGap(acknowledgement)) {
84
+ return {
85
+ acknowledgementObservation: "host-acknowledged",
86
+ outcome: acknowledgement.status === "accepted" ? "accepted" : "rejected",
87
+ };
88
+ }
89
+
90
+ return {
91
+ acknowledgementObservation: "host-acknowledgement-not-observed",
92
+ outcome: observedStateChange
93
+ ? "acknowledgement-not-observed-state-changed"
94
+ : "acknowledgement-not-observed-no-state-change-observed",
95
+ };
96
+ };
@@ -0,0 +1,301 @@
1
+ import { randomBytes, randomUUID } from "node:crypto";
2
+ import { chmod, mkdir, readFile, unlink, writeFile } from "node:fs/promises";
3
+ import {
4
+ createServer,
5
+ type IncomingMessage,
6
+ type ServerResponse,
7
+ } from "node:http";
8
+ import path from "node:path";
9
+ 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 };
45
+
46
+ export type AirJamGameSessionBrokerHealth = {
47
+ ok: true;
48
+ instanceId: string;
49
+ pid: number;
50
+ projectDir: string;
51
+ activeSessionCount: number;
52
+ startedAt: string;
53
+ };
54
+
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);
64
+
65
+ export const readGameSessionBrokerState = async (
66
+ projectDir: string,
67
+ ): Promise<AirJamGameSessionBrokerState | null> => {
68
+ 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;
84
+ } catch {
85
+ return null;
86
+ }
87
+ };
88
+
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>({
116
+ state,
117
+ request,
118
+ }: {
119
+ state: AirJamGameSessionBrokerState;
120
+ request: AirJamGameSessionBrokerOperation;
121
+ }): Promise<TResult> => {
122
+ 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;
130
+ const response = await fetch(`${state.origin}/v1/game-session`, {
131
+ method: "POST",
132
+ headers: {
133
+ authorization: `Bearer ${state.secret}`,
134
+ "content-type": "application/json",
135
+ },
136
+ body: JSON.stringify(request),
137
+ signal: AbortSignal.timeout(timeoutMs),
138
+ });
139
+ const result = (await response.json()) as {
140
+ ok?: boolean;
141
+ result?: TResult;
142
+ error?: { message?: string };
143
+ };
144
+ if (!response.ok || result.ok !== true) {
145
+ throw new Error(
146
+ result.error?.message ??
147
+ `Game session broker request failed with HTTP ${response.status}.`,
148
+ );
149
+ }
150
+ return result.result as TResult;
151
+ };
152
+
153
+ export const runGameSessionBroker = async ({
154
+ projectDir,
155
+ }: {
156
+ projectDir: string;
157
+ }): Promise<void> => {
158
+ const resolvedProjectDir = path.resolve(projectDir);
159
+ const statePath = resolveGameSessionBrokerStatePath(resolvedProjectDir);
160
+ const instanceId = randomUUID();
161
+ const secret = randomBytes(32).toString("base64url");
162
+ const startedAt = new Date().toISOString();
163
+ const activeSessionIds = new Set<string>();
164
+ let shuttingDown = false;
165
+ let shutdownCleanup: Promise<void> = Promise.resolve();
166
+
167
+ const closeActiveSessions = async (): Promise<void> => {
168
+ await Promise.all(
169
+ [...activeSessionIds].map((gameSessionId) =>
170
+ closeGameSession({ gameSessionId }).catch(() => undefined),
171
+ ),
172
+ );
173
+ activeSessionIds.clear();
174
+ };
175
+
176
+ 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, {
183
+ ok: false,
184
+ error: { message: "Invalid game session broker credentials." },
185
+ });
186
+ return;
187
+ }
188
+
189
+ try {
190
+ const operation = (await readJsonBody(
191
+ request,
192
+ )) as AirJamGameSessionBrokerOperation;
193
+ let result: unknown;
194
+ switch (operation.operation) {
195
+ case "health":
196
+ result = {
197
+ ok: true,
198
+ instanceId,
199
+ pid: process.pid,
200
+ projectDir: resolvedProjectDir,
201
+ activeSessionCount: activeSessionIds.size,
202
+ startedAt,
203
+ } satisfies AirJamGameSessionBrokerHealth;
204
+ break;
205
+ case "open": {
206
+ const opened = await openGameSession({
207
+ ...operation.input,
208
+ cwd: resolvedProjectDir,
209
+ });
210
+ activeSessionIds.add(opened.gameSessionId);
211
+ result = opened;
212
+ break;
213
+ }
214
+ case "read":
215
+ result = await readGameSession(operation.input);
216
+ break;
217
+ case "input":
218
+ result = await sendGameSessionInput(operation.input);
219
+ break;
220
+ case "invoke":
221
+ result = await invokeGameSessionAction(operation.input);
222
+ break;
223
+ case "capture":
224
+ result = await captureGameSessionVisuals(operation.input);
225
+ break;
226
+ case "close":
227
+ result = await closeGameSession(operation.input);
228
+ activeSessionIds.delete(operation.input.gameSessionId);
229
+ 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
+ }
238
+ writeJson(response, 200, { ok: true, result });
239
+ if (shuttingDown) {
240
+ server.close();
241
+ }
242
+ } catch (error) {
243
+ writeJson(response, 400, {
244
+ ok: false,
245
+ error: {
246
+ message: error instanceof Error ? error.message : String(error),
247
+ },
248
+ });
249
+ }
250
+ });
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.");
275
+ }
276
+ const state: AirJamGameSessionBrokerState = {
277
+ schemaVersion: 1,
278
+ instanceId,
279
+ pid: process.pid,
280
+ projectDir: resolvedProjectDir,
281
+ origin: `http://127.0.0.1:${address.port}`,
282
+ secret,
283
+ 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
+ });
298
+
299
+ await shutdownCleanup;
300
+ await cleanupState();
301
+ };