@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.
- package/README.md +60 -0
- package/dist/{chunk-VKMJO6VN.js → chunk-2O67AXCU.js} +150 -40
- package/dist/chunk-2O67AXCU.js.map +1 -0
- package/dist/chunk-AO3ZDXF6.js +142 -0
- package/dist/chunk-AO3ZDXF6.js.map +1 -0
- package/dist/chunk-ART5TEYT.js +472 -0
- package/dist/chunk-ART5TEYT.js.map +1 -0
- package/dist/chunk-ASC2CK2R.js +77 -0
- package/dist/chunk-ASC2CK2R.js.map +1 -0
- package/dist/chunk-E3UZZGAV.js +50 -0
- package/dist/chunk-E3UZZGAV.js.map +1 -0
- package/dist/chunk-EJTE7UKX.js +64 -0
- package/dist/chunk-EJTE7UKX.js.map +1 -0
- package/dist/chunk-ESFKNN75.js +110 -0
- package/dist/chunk-ESFKNN75.js.map +1 -0
- package/dist/chunk-EU7A6PXW.js +1339 -0
- package/dist/chunk-EU7A6PXW.js.map +1 -0
- package/dist/chunk-FN7E6EA7.js +549 -0
- package/dist/chunk-FN7E6EA7.js.map +1 -0
- package/dist/chunk-GDFAWHGA.js +190 -0
- package/dist/chunk-GDFAWHGA.js.map +1 -0
- package/dist/chunk-HZUGBH4Y.js +347 -0
- package/dist/chunk-HZUGBH4Y.js.map +1 -0
- package/dist/chunk-ITKAOEGX.js +93 -0
- package/dist/chunk-ITKAOEGX.js.map +1 -0
- package/dist/chunk-JBCUTWRI.js +897 -0
- package/dist/chunk-JBCUTWRI.js.map +1 -0
- package/dist/chunk-JSI5S4WP.js +1174 -0
- package/dist/chunk-JSI5S4WP.js.map +1 -0
- package/dist/chunk-L4D675BG.js +97 -0
- package/dist/chunk-L4D675BG.js.map +1 -0
- package/dist/chunk-M6CJ7GQC.js +133 -0
- package/dist/chunk-M6CJ7GQC.js.map +1 -0
- package/dist/{chunk-CKFT2ZJE.js → chunk-MEIMOSZC.js} +53 -105
- package/dist/chunk-MEIMOSZC.js.map +1 -0
- package/dist/{chunk-GUEZP773.js → chunk-O3XG3FNL.js} +204 -41
- package/dist/chunk-O3XG3FNL.js.map +1 -0
- package/dist/chunk-OM6SCJ7H.js +18 -0
- package/dist/chunk-OM6SCJ7H.js.map +1 -0
- package/dist/chunk-PKD4WVX5.js +63 -0
- package/dist/chunk-PKD4WVX5.js.map +1 -0
- package/dist/chunk-PMBLXGFM.js +3384 -0
- package/dist/chunk-PMBLXGFM.js.map +1 -0
- package/dist/chunk-PMNE5GIN.js +279 -0
- package/dist/chunk-PMNE5GIN.js.map +1 -0
- package/dist/chunk-QAWI64VR.js +148 -0
- package/dist/chunk-QAWI64VR.js.map +1 -0
- package/dist/chunk-QGADSPHZ.js +449 -0
- package/dist/chunk-QGADSPHZ.js.map +1 -0
- package/dist/chunk-SPYN66UV.js +338 -0
- package/dist/chunk-SPYN66UV.js.map +1 -0
- package/dist/context.d.ts +9 -3
- package/dist/context.js +2 -1
- package/dist/controller.d.ts +33 -7
- package/dist/controller.js +18 -8
- package/dist/dependencies.d.ts +44 -0
- package/dist/dependencies.js +10 -0
- package/dist/dev.d.ts +9 -3
- package/dist/dev.js +3 -4
- package/dist/game-builds.d.ts +200 -0
- package/dist/game-builds.js +16 -0
- package/dist/game-builds.js.map +1 -0
- package/dist/game-run-watch-CEd_SpAT.d.ts +84 -0
- package/dist/game-runs.d.ts +1452 -0
- package/dist/game-runs.js +76 -0
- package/dist/game-runs.js.map +1 -0
- package/dist/game-session-broker-CUvORfMd.d.ts +439 -0
- package/dist/game-session-broker.d.ts +4 -57
- package/dist/game-session-broker.js +33 -228
- package/dist/game-session-broker.js.map +1 -1
- package/dist/game-session.d.ts +3931 -10
- package/dist/game-session.js +186 -15
- package/dist/game-session.js.map +1 -1
- package/dist/game-settings.d.ts +16 -0
- package/dist/game-settings.js +237 -0
- package/dist/game-settings.js.map +1 -0
- package/dist/games.d.ts +11 -4
- package/dist/games.js +4 -2
- package/dist/harness/visual.d.ts +34 -151
- package/dist/harness/visual.js +6 -1
- package/dist/logs.d.ts +8 -2
- package/dist/logs.js +3 -4
- package/dist/logs.js.map +1 -1
- package/dist/managed-process-scope-BicYi_t9.d.ts +3 -0
- package/dist/mcp-config.js +2 -1
- package/dist/mcp-config.js.map +1 -1
- package/dist/platform-auth.d.ts +8 -111
- package/dist/platform-auth.js +9 -1
- package/dist/platform-game-analytics.d.ts +51 -0
- package/dist/platform-game-analytics.js +49 -0
- package/dist/platform-game-analytics.js.map +1 -0
- package/dist/platform-game-app-id.d.ts +46 -0
- package/dist/platform-game-app-id.js +93 -0
- package/dist/platform-game-app-id.js.map +1 -0
- package/dist/platform-game-media.d.ts +40 -2
- package/dist/platform-game-media.js +1 -1
- package/dist/platform-games.d.ts +24 -2
- package/dist/platform-games.js +16 -84
- package/dist/platform-games.js.map +1 -1
- package/dist/quality.d.ts +9 -3
- package/dist/quality.js +3 -4
- package/dist/quality.js.map +1 -1
- package/dist/release.d.ts +226 -16
- package/dist/release.js +18 -1331
- package/dist/release.js.map +1 -1
- package/dist/rooms-check.d.ts +90 -0
- package/dist/rooms-check.js +717 -0
- package/dist/rooms-check.js.map +1 -0
- package/dist/source-tree-contract.d.ts +16 -0
- package/dist/source-tree-contract.js +13 -0
- package/dist/source-tree-contract.js.map +1 -0
- package/dist/testing.d.ts +464 -0
- package/dist/testing.js +27 -0
- package/dist/testing.js.map +1 -0
- package/dist/tooling/describe-game.js +54 -0
- package/dist/tooling/describe-game.js.map +1 -0
- package/dist/tooling/game-session-broker.js +28 -0
- package/dist/tooling/game-session-broker.js.map +1 -0
- package/dist/tooling/hold-runtime-host.js +769 -67
- package/dist/tooling/hold-runtime-host.js.map +1 -1
- package/dist/tooling/list-visual-scenarios.js +18 -55
- package/dist/tooling/list-visual-scenarios.js.map +1 -1
- package/dist/tooling/process-scope-bootstrap.mjs +24 -0
- package/dist/tooling/process-scope-guard.d.ts +2 -0
- package/dist/tooling/process-scope-guard.js +388 -0
- package/dist/tooling/process-scope-guard.js.map +1 -0
- package/dist/tooling/process-scope-windows.ps1 +148 -0
- package/dist/tooling/rooms-check-device.d.ts +2 -0
- package/dist/tooling/rooms-check-device.js +498 -0
- package/dist/tooling/rooms-check-device.js.map +1 -0
- package/dist/tooling/run-headless-room.d.ts +2 -0
- package/dist/tooling/run-headless-room.js +287 -0
- package/dist/tooling/run-headless-room.js.map +1 -0
- package/dist/tooling/run-test-profile.d.ts +2 -0
- package/dist/tooling/run-test-profile.js +181 -0
- package/dist/tooling/run-test-profile.js.map +1 -0
- package/dist/tooling/run-visual-capture.js +70 -34
- package/dist/tooling/run-visual-capture.js.map +1 -1
- package/dist/tooling/seal-game-build.d.ts +2 -0
- package/dist/tooling/seal-game-build.js +120 -0
- package/dist/tooling/seal-game-build.js.map +1 -0
- package/dist/{types-C6NrHt88.d.ts → types-CdYrgrG_.d.ts} +337 -76
- package/dist/types-DyRD-ym1.d.ts +141 -0
- package/dist/visual.d.ts +9 -3
- package/dist/visual.js +24 -68
- package/dist/visual.js.map +1 -1
- package/package.json +51 -14
- package/src/bounded-response.ts +28 -0
- package/src/built-game-runtime.ts +152 -0
- package/src/context.ts +2 -13
- package/src/controller-protocol.ts +22 -0
- package/src/controller.ts +747 -597
- package/src/current-room-host.ts +166 -0
- package/src/decision-provider.ts +102 -0
- package/src/dependencies.ts +176 -0
- package/src/dependency-install-contract.ts +12 -0
- package/src/dev.ts +46 -50
- package/src/game-action-observation.ts +11 -1
- package/src/game-build-protocol.ts +72 -0
- package/src/game-build.ts +483 -0
- package/src/game-run-owner.ts +2358 -0
- package/src/game-run-protocol.ts +448 -0
- package/src/game-run-record.ts +92 -0
- package/src/game-run-replay.ts +95 -0
- package/src/game-run-watch.ts +155 -0
- package/src/game-session-broker.ts +689 -197
- package/src/game-session-operations.ts +61 -0
- package/src/game-session-protocol.ts +180 -0
- package/src/game-session-runtime.ts +861 -0
- package/src/game-session.ts +164 -417
- package/src/game-settings.ts +295 -0
- package/src/games.ts +88 -92
- package/src/harness/visual/browser.ts +100 -0
- package/src/harness/visual/controller-observation.ts +181 -0
- package/src/harness/visual/runner.ts +24 -21
- package/src/harness/visual/runtime-controller-observations.ts +151 -0
- package/src/harness/visual/scenario-contract.ts +1 -2
- package/src/harness/visual/scenario-helpers.ts +5 -1
- package/src/harness/visual/screencast.ts +155 -0
- package/src/harness/visual/session.ts +72 -41
- package/src/harness/visual/types.ts +8 -5
- package/src/headless-room-protocol.ts +112 -0
- package/src/headless-room.ts +222 -0
- package/src/helper-channel.ts +229 -0
- package/src/helper-scripts.ts +25 -5
- package/src/installed-dependencies.ts +74 -0
- package/src/managed-process-scope.ts +481 -0
- package/src/node-process-environment.ts +10 -0
- package/src/platform-auth.ts +194 -55
- package/src/platform-game-analytics.ts +50 -0
- package/src/platform-game-app-id.ts +99 -0
- package/src/platform-games.ts +13 -111
- package/src/policy-artifact-contract.ts +52 -0
- package/src/policy-artifacts.ts +134 -0
- package/src/process-scope-admission.ts +50 -0
- package/src/process-scope-protocol.ts +66 -0
- package/src/process-scope.ts +327 -0
- package/src/release.ts +28 -42
- package/src/rooms-check-fleet.ts +194 -0
- package/src/rooms-check-link.ts +138 -0
- package/src/rooms-check-protocol.ts +244 -0
- package/src/rooms-check.ts +797 -0
- package/src/runtime-owner-protocol.ts +106 -18
- package/src/source-tree-contract.ts +70 -0
- package/src/source-tree.ts +84 -0
- package/src/test-profile-process.ts +153 -0
- package/src/test-profile-protocol.ts +116 -0
- package/src/testing.ts +430 -0
- package/src/tooling/declaration-hook.ts +52 -0
- package/src/tooling/describe-game.ts +49 -0
- package/src/tooling/game-session-broker.ts +7 -0
- package/src/tooling/hold-runtime-host.ts +255 -38
- package/src/tooling/list-visual-scenarios.ts +19 -62
- package/src/tooling/load-game.ts +79 -0
- package/src/tooling/process-scope-bootstrap.mjs +24 -0
- package/src/tooling/process-scope-guard.ts +213 -0
- package/src/tooling/process-scope-windows.ps1 +148 -0
- package/src/tooling/rooms-check-device.ts +493 -0
- package/src/tooling/run-headless-room.ts +326 -0
- package/src/tooling/run-test-profile.ts +190 -0
- package/src/tooling/run-visual-capture.ts +37 -23
- package/src/tooling/runtime-owner-actions.ts +23 -0
- package/src/tooling/seal-game-build.ts +118 -0
- package/src/tooling/visual-pack.ts +10 -45
- package/src/types.ts +54 -77
- package/src/visual.ts +14 -22
- package/src/windows-process-scopes.ts +189 -0
- package/dist/agent.d.ts +0 -15
- package/dist/agent.js +0 -19
- package/dist/chunk-5YAARMW5.js +0 -36
- package/dist/chunk-5YAARMW5.js.map +0 -1
- package/dist/chunk-6WQODT37.js +0 -1019
- package/dist/chunk-6WQODT37.js.map +0 -1
- package/dist/chunk-CKFT2ZJE.js.map +0 -1
- package/dist/chunk-ER3Q2C4G.js +0 -358
- package/dist/chunk-ER3Q2C4G.js.map +0 -1
- package/dist/chunk-GUEZP773.js.map +0 -1
- package/dist/chunk-HIDNI56E.js +0 -33
- package/dist/chunk-HIDNI56E.js.map +0 -1
- package/dist/chunk-QKXS5D35.js +0 -43
- package/dist/chunk-QKXS5D35.js.map +0 -1
- package/dist/chunk-S4LSCEVE.js +0 -261
- package/dist/chunk-S4LSCEVE.js.map +0 -1
- package/dist/chunk-VKMJO6VN.js.map +0 -1
- package/dist/chunk-WFUR3MXY.js +0 -67
- package/dist/chunk-WFUR3MXY.js.map +0 -1
- package/dist/chunk-XEMR7KUE.js +0 -361
- package/dist/chunk-XEMR7KUE.js.map +0 -1
- package/dist/chunk-ZLPD7FY5.js +0 -191
- package/dist/chunk-ZLPD7FY5.js.map +0 -1
- package/dist/tooling/agent-contract.js +0 -193
- package/dist/tooling/agent-contract.js.map +0 -1
- package/dist/tooling/inspect-airjam-agent.js +0 -37
- package/dist/tooling/inspect-airjam-agent.js.map +0 -1
- package/src/agent.ts +0 -380
- package/src/tooling/agent-contract.ts +0 -232
- package/src/tooling/agent-declaration.ts +0 -36
- package/src/tooling/airjam-agent-inspection.ts +0 -45
- package/src/tooling/airjam-agent.ts +0 -118
- package/src/tooling/inspect-airjam-agent.ts +0 -20
- /package/dist/{agent.js.map → dependencies.js.map} +0 -0
- /package/dist/tooling/{agent-contract.d.ts → describe-game.d.ts} +0 -0
- /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 {
|
|
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
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
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
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
export const resolveGameSessionBrokerStatePath = (projectDir: string)
|
|
63
|
-
path.join(projectDir,
|
|
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
|
|
66
|
-
|
|
67
|
-
): Promise<AirJamGameSessionBrokerState | null> => {
|
|
76
|
+
export async function readGameSessionBrokerState(projectDir: string) {
|
|
77
|
+
let source: string;
|
|
68
78
|
try {
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
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
|
-
|
|
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
|
-
|
|
124
|
-
?
|
|
125
|
-
:
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
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(
|
|
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
|
-
|
|
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
|
-
})
|
|
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
|
|
164
|
-
|
|
165
|
-
|
|
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
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
)
|
|
173
|
-
|
|
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, {
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
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
|
-
|
|
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 =
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
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:
|
|
463
|
+
activeSessionCount: sessions.size,
|
|
202
464
|
startedAt,
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
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
|
-
|
|
211
|
-
|
|
212
|
-
|
|
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
|
|
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
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
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
|
-
|
|
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
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
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
|
-
|
|
300
|
-
|
|
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
|
+
}
|