@air-jam/devtools 0.0.0-stage → 1.0.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +112 -2
- package/dist/chunk-2O67AXCU.js +470 -0
- 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-MEIMOSZC.js +749 -0
- package/dist/chunk-MEIMOSZC.js.map +1 -0
- package/dist/chunk-O3XG3FNL.js +1014 -0
- 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 +19 -0
- package/dist/context.js +10 -0
- package/dist/context.js.map +1 -0
- package/dist/controller.d.ts +67 -0
- package/dist/controller.js +40 -0
- package/dist/controller.js.map +1 -0
- package/dist/dependencies.d.ts +44 -0
- package/dist/dependencies.js +10 -0
- package/dist/dependencies.js.map +1 -0
- package/dist/dev.d.ts +21 -0
- package/dist/dev.js +19 -0
- package/dist/dev.js.map +1 -0
- 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 -0
- package/dist/game-session-broker.js +40 -0
- package/dist/game-session-broker.js.map +1 -0
- package/dist/game-session.d.ts +3934 -0
- package/dist/game-session.js +195 -0
- package/dist/game-session.js.map +1 -0
- 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 +28 -0
- package/dist/games.js +16 -0
- package/dist/games.js.map +1 -0
- package/dist/harness/visual.d.ts +204 -0
- package/dist/harness/visual.js +46 -0
- package/dist/harness/visual.js.map +1 -0
- package/dist/logs.d.ts +15 -0
- package/dist/logs.js +57 -0
- package/dist/logs.js.map +1 -0
- package/dist/managed-process-scope-BicYi_t9.d.ts +3 -0
- package/dist/mcp-config.d.ts +63 -0
- package/dist/mcp-config.js +191 -0
- package/dist/mcp-config.js.map +1 -0
- package/dist/platform-auth.d.ts +9 -0
- package/dist/platform-auth.js +45 -0
- package/dist/platform-auth.js.map +1 -0
- 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 +347 -0
- package/dist/platform-game-media.js +168 -0
- package/dist/platform-game-media.js.map +1 -0
- package/dist/platform-games.d.ts +87 -0
- package/dist/platform-games.js +183 -0
- package/dist/platform-games.js.map +1 -0
- package/dist/quality.d.ts +16 -0
- package/dist/quality.js +62 -0
- package/dist/quality.js.map +1 -0
- package/dist/release.d.ts +1304 -0
- package/dist/release.js +34 -0
- package/dist/release.js.map +1 -0
- 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.d.ts +2 -0
- package/dist/tooling/describe-game.js +54 -0
- package/dist/tooling/describe-game.js.map +1 -0
- package/dist/tooling/game-session-broker.d.ts +2 -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.d.ts +2 -0
- package/dist/tooling/hold-runtime-host.js +931 -0
- package/dist/tooling/hold-runtime-host.js.map +1 -0
- package/dist/tooling/list-visual-scenarios.d.ts +2 -0
- package/dist/tooling/list-visual-scenarios.js +25 -0
- package/dist/tooling/list-visual-scenarios.js.map +1 -0
- package/dist/tooling/managed-dev-supervisor.d.ts +2 -0
- package/dist/tooling/managed-dev-supervisor.js +51 -0
- package/dist/tooling/managed-dev-supervisor.js.map +1 -0
- 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.d.ts +2 -0
- package/dist/tooling/run-visual-capture.js +203 -0
- package/dist/tooling/run-visual-capture.js.map +1 -0
- 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-CdYrgrG_.d.ts +1036 -0
- package/dist/types-DyRD-ym1.d.ts +141 -0
- package/dist/visual.d.ts +21 -0
- package/dist/visual.js +219 -0
- package/dist/visual.js.map +1 -0
- package/package.json +150 -3
- package/src/bounded-response.ts +28 -0
- package/src/built-game-runtime.ts +152 -0
- package/src/commands.ts +40 -0
- package/src/context.ts +218 -0
- package/src/controller-protocol.ts +22 -0
- package/src/controller.ts +1526 -0
- 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 +995 -0
- package/src/fs-utils.ts +93 -0
- package/src/game-action-observation.ts +106 -0
- 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 +793 -0
- 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 +206 -0
- package/src/game-settings.ts +295 -0
- package/src/games.ts +262 -0
- package/src/harness/visual/browser.ts +100 -0
- package/src/harness/visual/controller-observation.ts +181 -0
- package/src/harness/visual/prefab-contract.ts +29 -0
- package/src/harness/visual/prefab-runner.ts +178 -0
- package/src/harness/visual/runner.ts +549 -0
- package/src/harness/visual/runtime-controller-observations.ts +151 -0
- package/src/harness/visual/scenario-contract.ts +8 -0
- package/src/harness/visual/scenario-helpers.ts +67 -0
- package/src/harness/visual/screencast.ts +155 -0
- package/src/harness/visual/session.ts +400 -0
- package/src/harness/visual/types.ts +184 -0
- package/src/harness/visual.ts +7 -0
- 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 +69 -0
- package/src/installed-dependencies.ts +74 -0
- package/src/logs.ts +67 -0
- package/src/managed-process-scope.ts +481 -0
- package/src/mcp-config.ts +262 -0
- package/src/node-process-environment.ts +10 -0
- package/src/platform-auth.ts +594 -0
- package/src/platform-game-analytics.ts +50 -0
- package/src/platform-game-app-id.ts +99 -0
- package/src/platform-game-media.ts +209 -0
- package/src/platform-games.ts +217 -0
- 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/quality.ts +82 -0
- package/src/release.ts +1683 -0
- 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 +218 -0
- 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 +441 -0
- package/src/tooling/list-visual-scenarios.ts +21 -0
- package/src/tooling/load-game.ts +79 -0
- package/src/tooling/managed-dev-supervisor.ts +71 -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 +231 -0
- package/src/tooling/runtime-owner-actions.ts +65 -0
- package/src/tooling/seal-game-build.ts +118 -0
- package/src/tooling/visual-pack.ts +11 -0
- package/src/types.ts +928 -0
- package/src/visual.ts +296 -0
- package/src/windows-process-scopes.ts +189 -0
- package/src/workspace-contract.ts +32 -0
|
@@ -0,0 +1,1526 @@
|
|
|
1
|
+
import type { AirJamActionInvocationResult } from "@air-jam/sdk";
|
|
2
|
+
import {
|
|
3
|
+
AIR_JAM_ARCADE_SURFACE_STORE_DOMAIN,
|
|
4
|
+
arcadeSurfaceRuntimeIdentitySchema,
|
|
5
|
+
embeddedReplicatedStoreDomainFromArcadeIdentity,
|
|
6
|
+
localReferenceSourceGameId,
|
|
7
|
+
} from "@air-jam/sdk/arcade/surface";
|
|
8
|
+
import {
|
|
9
|
+
agentValuesToInputState,
|
|
10
|
+
airJamActionResultOf,
|
|
11
|
+
type AirJamInput,
|
|
12
|
+
type AirJamInputState,
|
|
13
|
+
} from "@air-jam/sdk/core";
|
|
14
|
+
import {
|
|
15
|
+
controllerLeasedControlAckSchema,
|
|
16
|
+
leasedControlRequestSchema,
|
|
17
|
+
type ControllerLeasedControlAck,
|
|
18
|
+
type LeasedControlRequest,
|
|
19
|
+
} from "@air-jam/sdk/protocol";
|
|
20
|
+
import {
|
|
21
|
+
AIRJAM_CONTROL_CHANNEL,
|
|
22
|
+
AIRJAM_LEASED_CONTROL_REQUEST,
|
|
23
|
+
AIRJAM_PRESENTATION_CHANNEL,
|
|
24
|
+
encodeInputPayload,
|
|
25
|
+
encodePhoneInputFrame,
|
|
26
|
+
type RoomLink,
|
|
27
|
+
type StateDocument,
|
|
28
|
+
} from "@air-jam/sdk/room-protocol";
|
|
29
|
+
import {
|
|
30
|
+
createRoomKey,
|
|
31
|
+
createScopedPhoneConnector,
|
|
32
|
+
createWebSocketConnector,
|
|
33
|
+
PhoneRoomSession,
|
|
34
|
+
serveRoomPort,
|
|
35
|
+
type RoomSessionStatus,
|
|
36
|
+
} from "@air-jam/sdk/room-session";
|
|
37
|
+
import type {
|
|
38
|
+
HostAgentRequest,
|
|
39
|
+
HostAgentResponse,
|
|
40
|
+
HostRuntimeActionRequest,
|
|
41
|
+
} from "@air-jam/sdk/runtime-control";
|
|
42
|
+
import {
|
|
43
|
+
AIR_JAM_RUNTIME_INSPECTION_KEY,
|
|
44
|
+
readRuntimeInspectionContract,
|
|
45
|
+
type HostRuntimeInspectionContract,
|
|
46
|
+
} from "@air-jam/sdk/runtime-inspection";
|
|
47
|
+
import { parseRuntimeTopologyFromSearchParams } from "@air-jam/sdk/runtime-topology";
|
|
48
|
+
import type { ChildProcess } from "node:child_process";
|
|
49
|
+
import { randomUUID } from "node:crypto";
|
|
50
|
+
import { z } from "zod";
|
|
51
|
+
import { detectProjectContext } from "./context.js";
|
|
52
|
+
import { getTopology } from "./dev.js";
|
|
53
|
+
import type { PinnedGameBuild } from "./game-build-protocol.js";
|
|
54
|
+
import type { GameSurfaceWatchEvent } from "./game-run-watch.js";
|
|
55
|
+
import { inspectGame } from "./games.js";
|
|
56
|
+
import {
|
|
57
|
+
resolveDevtoolsHelperArgs,
|
|
58
|
+
resolveDevtoolsHelperScript,
|
|
59
|
+
resolveProjectDevtoolsHelperScript,
|
|
60
|
+
} from "./helper-scripts.js";
|
|
61
|
+
import {
|
|
62
|
+
closeScopedProcess,
|
|
63
|
+
spawnScopedProcess,
|
|
64
|
+
type ProcessScopeObserver,
|
|
65
|
+
} from "./managed-process-scope.js";
|
|
66
|
+
import {
|
|
67
|
+
AIR_JAM_RUNTIME_OWNER_ACTION_REQUEST,
|
|
68
|
+
AIR_JAM_RUNTIME_OWNER_CAPTURE_PORT,
|
|
69
|
+
AIR_JAM_RUNTIME_OWNER_CAPTURE_REQUEST,
|
|
70
|
+
isRuntimeOwnerActionResult,
|
|
71
|
+
isRuntimeOwnerCaptureResult,
|
|
72
|
+
runtimeOwnerAgentResultSchema,
|
|
73
|
+
runtimeOwnerCaptureFrameSchema,
|
|
74
|
+
runtimeOwnerWatchEventSchema,
|
|
75
|
+
type AirJamRuntimeOwnerCaptureResult,
|
|
76
|
+
} from "./runtime-owner-protocol.js";
|
|
77
|
+
import type {
|
|
78
|
+
AirJamGameInspection,
|
|
79
|
+
AirJamProjectMode,
|
|
80
|
+
AirJamRuntimeSnapshotInspection,
|
|
81
|
+
AirJamVirtualControllerSession,
|
|
82
|
+
AirJamVirtualControllerSessionSummary,
|
|
83
|
+
ConnectControllerOptions,
|
|
84
|
+
DisconnectControllerOptions,
|
|
85
|
+
DisconnectControllerResult,
|
|
86
|
+
GetTopologyOptions,
|
|
87
|
+
InvokeControllerActionOptions,
|
|
88
|
+
InvokeControllerActionResult,
|
|
89
|
+
JsonObject,
|
|
90
|
+
ReadRuntimeSnapshotOptions,
|
|
91
|
+
SendControllerInputOptions,
|
|
92
|
+
SendControllerInputResult,
|
|
93
|
+
} from "./types.js";
|
|
94
|
+
|
|
95
|
+
export type {
|
|
96
|
+
AirJamRuntimeSnapshotInspection,
|
|
97
|
+
AirJamRuntimeStoreSnapshot,
|
|
98
|
+
AirJamVirtualControllerSession,
|
|
99
|
+
AirJamVirtualControllerSessionSummary,
|
|
100
|
+
ConnectControllerOptions,
|
|
101
|
+
DisconnectControllerOptions,
|
|
102
|
+
DisconnectControllerResult,
|
|
103
|
+
InvokeControllerActionOptions,
|
|
104
|
+
InvokeControllerActionResult,
|
|
105
|
+
ReadRuntimeSnapshotOptions,
|
|
106
|
+
SendControllerInputOptions,
|
|
107
|
+
SendControllerInputResult,
|
|
108
|
+
} from "./types.js";
|
|
109
|
+
|
|
110
|
+
type InternalControllerSession = {
|
|
111
|
+
cwd: string;
|
|
112
|
+
summary: AirJamVirtualControllerSessionSummary;
|
|
113
|
+
room: PhoneRoomSession;
|
|
114
|
+
projectMode: AirJamProjectMode;
|
|
115
|
+
/** When each channel this phone mirrors last changed, and how many times. */
|
|
116
|
+
storeUpdates: Map<string, { revision: number; updatedAt: string }>;
|
|
117
|
+
lastSignal: JsonObject | null;
|
|
118
|
+
lastError: JsonObject | null;
|
|
119
|
+
isolatedRuntimeOwner: ChildProcess | null;
|
|
120
|
+
participantLeaseId: string | null;
|
|
121
|
+
participantLastCommand: LeasedControlRequest | null;
|
|
122
|
+
/** The controls this session last sent, so buttons count presses. */
|
|
123
|
+
inputState: AirJamInputState | null;
|
|
124
|
+
/** The game's declared controls, read once the first input is sent; null when the game declares none. */
|
|
125
|
+
inputLayout: AirJamInput | null | undefined;
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
const DEFAULT_TIMEOUT_MS = 5_000;
|
|
129
|
+
const DEFAULT_VISUAL_CAPTURE_TIMEOUT_MS = 15_000;
|
|
130
|
+
const WAIT_INTERVAL_MS = 25;
|
|
131
|
+
const virtualControllerSessions = new Map<string, InternalControllerSession>();
|
|
132
|
+
|
|
133
|
+
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
|
134
|
+
typeof value === "object" && value !== null && !Array.isArray(value);
|
|
135
|
+
|
|
136
|
+
const toJsonObject = (value: unknown): JsonObject | null => {
|
|
137
|
+
if (!isRecord(value)) {
|
|
138
|
+
return null;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
return { ...value };
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
const nowIso = (): string => new Date().toISOString();
|
|
145
|
+
|
|
146
|
+
const waitForCondition = async ({
|
|
147
|
+
timeoutMs,
|
|
148
|
+
predicate,
|
|
149
|
+
}: {
|
|
150
|
+
timeoutMs: number;
|
|
151
|
+
predicate: () => boolean;
|
|
152
|
+
}): Promise<void> => {
|
|
153
|
+
const startedAt = Date.now();
|
|
154
|
+
while (!predicate()) {
|
|
155
|
+
if (Date.now() - startedAt >= timeoutMs) {
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
await new Promise((resolve) => setTimeout(resolve, WAIT_INTERVAL_MS));
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
|
|
162
|
+
/** Waits until the phone's room welcomes it, or ends with why it could not join. */
|
|
163
|
+
const waitForWelcome = (room: PhoneRoomSession, timeoutMs: number) =>
|
|
164
|
+
new Promise<void>((resolve, reject) => {
|
|
165
|
+
const settle = (status: RoomSessionStatus) => {
|
|
166
|
+
if (status.phase === "open") finish();
|
|
167
|
+
else if (status.phase === "closed")
|
|
168
|
+
finish(new Error(`Controller join was refused (${status.reason}).`));
|
|
169
|
+
};
|
|
170
|
+
const finish = (error?: Error) => {
|
|
171
|
+
clearTimeout(timer);
|
|
172
|
+
stop();
|
|
173
|
+
if (error) reject(error);
|
|
174
|
+
else resolve();
|
|
175
|
+
};
|
|
176
|
+
const timer = setTimeout(
|
|
177
|
+
() =>
|
|
178
|
+
finish(
|
|
179
|
+
new Error(
|
|
180
|
+
"Timed out waiting for the room to welcome the controller.",
|
|
181
|
+
),
|
|
182
|
+
),
|
|
183
|
+
timeoutMs,
|
|
184
|
+
);
|
|
185
|
+
const stop = room.on("status", settle);
|
|
186
|
+
settle(room.status);
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
/** A channel's copy as this phone mirrors it, waiting up to `timeoutMs` for its first. */
|
|
190
|
+
const waitForChannel = async (
|
|
191
|
+
room: PhoneRoomSession,
|
|
192
|
+
channel: string,
|
|
193
|
+
timeoutMs: number,
|
|
194
|
+
): Promise<StateDocument | null> => {
|
|
195
|
+
await waitForCondition({
|
|
196
|
+
timeoutMs,
|
|
197
|
+
predicate: () => room.channel(channel) !== undefined,
|
|
198
|
+
});
|
|
199
|
+
return room.channel(channel) ?? null;
|
|
200
|
+
};
|
|
201
|
+
|
|
202
|
+
const requestOwnedHostAction = async ({
|
|
203
|
+
owner,
|
|
204
|
+
payload,
|
|
205
|
+
timeoutMs,
|
|
206
|
+
}: {
|
|
207
|
+
owner: ChildProcess;
|
|
208
|
+
payload: HostRuntimeActionRequest;
|
|
209
|
+
timeoutMs: number;
|
|
210
|
+
}): Promise<AirJamActionInvocationResult> =>
|
|
211
|
+
await new Promise((resolve) => {
|
|
212
|
+
const requestId = randomUUID();
|
|
213
|
+
const finish = (ack: AirJamActionInvocationResult) => {
|
|
214
|
+
clearTimeout(timeout);
|
|
215
|
+
owner.off("message", onMessage);
|
|
216
|
+
owner.off("exit", onExit);
|
|
217
|
+
owner.off("disconnect", onExit);
|
|
218
|
+
owner.off("error", onError);
|
|
219
|
+
resolve(ack);
|
|
220
|
+
};
|
|
221
|
+
const onError = () =>
|
|
222
|
+
finish({
|
|
223
|
+
ok: false,
|
|
224
|
+
status: "rejected",
|
|
225
|
+
source: "client",
|
|
226
|
+
reason: "host_ack_missing",
|
|
227
|
+
message:
|
|
228
|
+
"The owned host runtime disconnected before its acknowledgement was observed.",
|
|
229
|
+
});
|
|
230
|
+
const onExit = () => onError();
|
|
231
|
+
const onMessage = (message: unknown) => {
|
|
232
|
+
if (
|
|
233
|
+
isRuntimeOwnerActionResult(message) &&
|
|
234
|
+
message.requestId === requestId
|
|
235
|
+
)
|
|
236
|
+
finish(message.acknowledgement);
|
|
237
|
+
};
|
|
238
|
+
const timeout = setTimeout(() => {
|
|
239
|
+
finish({
|
|
240
|
+
ok: false,
|
|
241
|
+
status: "rejected",
|
|
242
|
+
source: "client",
|
|
243
|
+
reason: "host_ack_timeout",
|
|
244
|
+
message: "Timed out waiting for the owned host action acknowledgement.",
|
|
245
|
+
});
|
|
246
|
+
}, timeoutMs);
|
|
247
|
+
owner.on("message", onMessage);
|
|
248
|
+
owner.once("exit", onExit);
|
|
249
|
+
owner.once("disconnect", onExit);
|
|
250
|
+
owner.once("error", onError);
|
|
251
|
+
try {
|
|
252
|
+
owner.send(
|
|
253
|
+
{
|
|
254
|
+
type: AIR_JAM_RUNTIME_OWNER_ACTION_REQUEST,
|
|
255
|
+
requestId,
|
|
256
|
+
action: payload,
|
|
257
|
+
},
|
|
258
|
+
(error) => {
|
|
259
|
+
if (error) onError();
|
|
260
|
+
},
|
|
261
|
+
);
|
|
262
|
+
} catch {
|
|
263
|
+
onError();
|
|
264
|
+
}
|
|
265
|
+
});
|
|
266
|
+
|
|
267
|
+
const parseJoinRoomId = (joinUrl: URL): string | null => {
|
|
268
|
+
const roomId =
|
|
269
|
+
joinUrl.searchParams.get("room") ?? joinUrl.searchParams.get("aj_room");
|
|
270
|
+
return roomId?.trim().toUpperCase() || null;
|
|
271
|
+
};
|
|
272
|
+
|
|
273
|
+
const terminateIsolatedRuntimeOwner = closeScopedProcess;
|
|
274
|
+
|
|
275
|
+
const resolveSocketOriginFromTopology = async (
|
|
276
|
+
options: GetTopologyOptions,
|
|
277
|
+
): Promise<string | null> => {
|
|
278
|
+
try {
|
|
279
|
+
const topology = await getTopology(options);
|
|
280
|
+
const preferredSurfaces = [
|
|
281
|
+
topology.surfaces.controller,
|
|
282
|
+
topology.surfaces.embeddedController,
|
|
283
|
+
topology.surfaces.platformController,
|
|
284
|
+
];
|
|
285
|
+
|
|
286
|
+
for (const surface of preferredSurfaces) {
|
|
287
|
+
const objectSurface = toJsonObject(surface);
|
|
288
|
+
const socketOrigin =
|
|
289
|
+
(typeof objectSurface?.socketOrigin === "string"
|
|
290
|
+
? objectSurface.socketOrigin
|
|
291
|
+
: null) ??
|
|
292
|
+
(typeof objectSurface?.backendOrigin === "string"
|
|
293
|
+
? objectSurface.backendOrigin
|
|
294
|
+
: null) ??
|
|
295
|
+
(typeof objectSurface?.appOrigin === "string"
|
|
296
|
+
? objectSurface.appOrigin
|
|
297
|
+
: null);
|
|
298
|
+
if (socketOrigin) {
|
|
299
|
+
return socketOrigin;
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
} catch {
|
|
303
|
+
// Fall back to the join URL origin below.
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
return null;
|
|
307
|
+
};
|
|
308
|
+
|
|
309
|
+
const resolveControllerJoinUrlFromTopology = async ({
|
|
310
|
+
cwd,
|
|
311
|
+
gameId,
|
|
312
|
+
mode,
|
|
313
|
+
secure,
|
|
314
|
+
roomId,
|
|
315
|
+
}: {
|
|
316
|
+
cwd: string;
|
|
317
|
+
gameId?: string;
|
|
318
|
+
mode: NonNullable<ConnectControllerOptions["mode"]>;
|
|
319
|
+
secure: boolean;
|
|
320
|
+
roomId?: string;
|
|
321
|
+
}): Promise<string | null> => {
|
|
322
|
+
if (!roomId) {
|
|
323
|
+
return null;
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
const topology = await getTopology({
|
|
327
|
+
cwd,
|
|
328
|
+
gameId,
|
|
329
|
+
mode,
|
|
330
|
+
secure,
|
|
331
|
+
});
|
|
332
|
+
if (!topology.urls.controllerBaseUrl) {
|
|
333
|
+
return null;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
const joinUrl = new URL(topology.urls.controllerBaseUrl);
|
|
337
|
+
joinUrl.searchParams.set("room", roomId);
|
|
338
|
+
return joinUrl.toString();
|
|
339
|
+
};
|
|
340
|
+
|
|
341
|
+
const startIsolatedRuntimeOwner = async ({
|
|
342
|
+
cwd,
|
|
343
|
+
gameId,
|
|
344
|
+
mode,
|
|
345
|
+
secure,
|
|
346
|
+
timeoutMs,
|
|
347
|
+
build,
|
|
348
|
+
settings,
|
|
349
|
+
onScope,
|
|
350
|
+
}: {
|
|
351
|
+
settings?: Record<string, number | boolean | string>;
|
|
352
|
+
cwd: string;
|
|
353
|
+
onScope?: ProcessScopeObserver;
|
|
354
|
+
build?: PinnedGameBuild;
|
|
355
|
+
gameId?: string;
|
|
356
|
+
mode: NonNullable<ConnectControllerOptions["mode"]>;
|
|
357
|
+
secure: boolean;
|
|
358
|
+
timeoutMs: number;
|
|
359
|
+
}): Promise<{
|
|
360
|
+
process: ChildProcess;
|
|
361
|
+
roomId: string | null;
|
|
362
|
+
controllerJoinUrl: string | null;
|
|
363
|
+
inspection: HostRuntimeInspectionContract | null;
|
|
364
|
+
}> => {
|
|
365
|
+
const topology = build
|
|
366
|
+
? null
|
|
367
|
+
: await getTopology({
|
|
368
|
+
cwd,
|
|
369
|
+
gameId,
|
|
370
|
+
mode,
|
|
371
|
+
secure,
|
|
372
|
+
});
|
|
373
|
+
|
|
374
|
+
const appOrigin = topology?.urls.appOrigin;
|
|
375
|
+
const hostUrl = topology?.urls.hostUrl;
|
|
376
|
+
const controllerBaseUrl = topology?.urls.controllerBaseUrl;
|
|
377
|
+
const publicHost = topology?.urls.publicHost;
|
|
378
|
+
if (!build && (!appOrigin || !hostUrl || !controllerBaseUrl || !publicHost)) {
|
|
379
|
+
throw new Error(
|
|
380
|
+
"Unable to start an isolated runtime owner because the resolved topology is incomplete.",
|
|
381
|
+
);
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
const helperFile = build
|
|
385
|
+
? resolveProjectDevtoolsHelperScript(build.rootDir, "hold-runtime-host.ts")
|
|
386
|
+
: resolveDevtoolsHelperScript("hold-runtime-host.ts");
|
|
387
|
+
const args = [
|
|
388
|
+
...resolveDevtoolsHelperArgs(helperFile),
|
|
389
|
+
"--mode",
|
|
390
|
+
mode,
|
|
391
|
+
"--timeout-ms",
|
|
392
|
+
String(timeoutMs),
|
|
393
|
+
];
|
|
394
|
+
if (settings) args.push("--settings", JSON.stringify(settings));
|
|
395
|
+
if (build) args.push("--pinned-build", build.manifestPath);
|
|
396
|
+
else {
|
|
397
|
+
for (const [flag, value] of [
|
|
398
|
+
["--app-origin", appOrigin],
|
|
399
|
+
["--host-url", hostUrl],
|
|
400
|
+
["--controller-base-url", controllerBaseUrl],
|
|
401
|
+
["--public-host", publicHost],
|
|
402
|
+
["--local-build-url", topology?.urls.localBuildUrl],
|
|
403
|
+
["--browser-build-url", topology?.urls.browserBuildUrl],
|
|
404
|
+
] as const)
|
|
405
|
+
if (value) args.push(flag, value);
|
|
406
|
+
}
|
|
407
|
+
const helperProcess = await spawnScopedProcess(args, {
|
|
408
|
+
cwd,
|
|
409
|
+
onScope,
|
|
410
|
+
});
|
|
411
|
+
|
|
412
|
+
return await new Promise((resolve, reject) => {
|
|
413
|
+
let stderrBuffer = "";
|
|
414
|
+
let settled = false;
|
|
415
|
+
const timeout = setTimeout(() => {
|
|
416
|
+
cleanup();
|
|
417
|
+
void terminateIsolatedRuntimeOwner(helperProcess).finally(() => {
|
|
418
|
+
const stderrSummary = stderrBuffer.trim();
|
|
419
|
+
const stderrSuffix = stderrSummary
|
|
420
|
+
? ` Helper stderr: ${stderrSummary}`
|
|
421
|
+
: "";
|
|
422
|
+
reject(
|
|
423
|
+
new Error(
|
|
424
|
+
"Timed out waiting for isolated runtime ownership. Another local game session may still own the isolated runtime lease, or no host page may be available to create a room. Run `pnpm exec airjam status` to inspect local dev processes; if the state looks stale, run `pnpm exec airjam reset local` and then reopen the host page." +
|
|
425
|
+
stderrSuffix,
|
|
426
|
+
),
|
|
427
|
+
);
|
|
428
|
+
});
|
|
429
|
+
}, timeoutMs);
|
|
430
|
+
|
|
431
|
+
const cleanup = () => {
|
|
432
|
+
clearTimeout(timeout);
|
|
433
|
+
helperProcess.off("message", onReady);
|
|
434
|
+
helperProcess.stderr?.off("data", onStderr);
|
|
435
|
+
helperProcess.off("exit", onExit);
|
|
436
|
+
helperProcess.off("error", onError);
|
|
437
|
+
};
|
|
438
|
+
|
|
439
|
+
const onReady = (message: unknown) => {
|
|
440
|
+
const result = z
|
|
441
|
+
.object({
|
|
442
|
+
type: z.literal("air-jam-runtime-owner.ready/v1"),
|
|
443
|
+
roomId: z.string().nullable(),
|
|
444
|
+
controllerJoinUrl: z.string().nullable(),
|
|
445
|
+
inspection: z.unknown(),
|
|
446
|
+
})
|
|
447
|
+
.safeParse(message);
|
|
448
|
+
if (!result.success) return;
|
|
449
|
+
const inspection = readRuntimeInspectionContract({
|
|
450
|
+
[AIR_JAM_RUNTIME_INSPECTION_KEY]: result.data.inspection,
|
|
451
|
+
});
|
|
452
|
+
if (inspection?.role !== "host") {
|
|
453
|
+
cleanup();
|
|
454
|
+
void terminateIsolatedRuntimeOwner(helperProcess).then(
|
|
455
|
+
() =>
|
|
456
|
+
reject(
|
|
457
|
+
new Error(
|
|
458
|
+
"Isolated runtime owner returned an invalid host inspection.",
|
|
459
|
+
),
|
|
460
|
+
),
|
|
461
|
+
reject,
|
|
462
|
+
);
|
|
463
|
+
return;
|
|
464
|
+
}
|
|
465
|
+
settled = true;
|
|
466
|
+
cleanup();
|
|
467
|
+
resolve({
|
|
468
|
+
process: helperProcess,
|
|
469
|
+
roomId: result.data.roomId,
|
|
470
|
+
controllerJoinUrl: result.data.controllerJoinUrl,
|
|
471
|
+
inspection,
|
|
472
|
+
});
|
|
473
|
+
};
|
|
474
|
+
|
|
475
|
+
const onStderr = (chunk: Buffer | string) => {
|
|
476
|
+
stderrBuffer = (stderrBuffer + chunk.toString()).slice(-262144);
|
|
477
|
+
};
|
|
478
|
+
|
|
479
|
+
const onError = (error: Error) => {
|
|
480
|
+
if (settled) {
|
|
481
|
+
return;
|
|
482
|
+
}
|
|
483
|
+
cleanup();
|
|
484
|
+
reject(error);
|
|
485
|
+
};
|
|
486
|
+
|
|
487
|
+
const onExit = (code: number | null, signal: NodeJS.Signals | null) => {
|
|
488
|
+
if (settled) {
|
|
489
|
+
return;
|
|
490
|
+
}
|
|
491
|
+
cleanup();
|
|
492
|
+
reject(
|
|
493
|
+
new Error(
|
|
494
|
+
[
|
|
495
|
+
"Isolated runtime owner exited before producing a join URL.",
|
|
496
|
+
stderrBuffer.trim(),
|
|
497
|
+
`exit=${code ?? "null"} signal=${signal ?? "null"}`,
|
|
498
|
+
]
|
|
499
|
+
.filter(Boolean)
|
|
500
|
+
.join("\n"),
|
|
501
|
+
),
|
|
502
|
+
);
|
|
503
|
+
};
|
|
504
|
+
|
|
505
|
+
helperProcess.stdout?.resume();
|
|
506
|
+
helperProcess.on("message", onReady);
|
|
507
|
+
helperProcess.stderr?.on("data", onStderr);
|
|
508
|
+
helperProcess.once("error", onError);
|
|
509
|
+
helperProcess.once("exit", onExit);
|
|
510
|
+
});
|
|
511
|
+
};
|
|
512
|
+
|
|
513
|
+
/**
|
|
514
|
+
* Serves the observed controller page the acting phone's room, read-only:
|
|
515
|
+
* the owner relays the page's room port here over IPC, and this side serves
|
|
516
|
+
* it as a view of the acting phone's session. The page sees what the phone
|
|
517
|
+
* sees; nothing it sends reaches the room.
|
|
518
|
+
*/
|
|
519
|
+
function relayControllerObservation(
|
|
520
|
+
session: InternalControllerSession,
|
|
521
|
+
owner: ChildProcess,
|
|
522
|
+
requestId: string,
|
|
523
|
+
onError: (error: Error) => void,
|
|
524
|
+
) {
|
|
525
|
+
const listeners = new Set<(event: MessageEvent) => void>();
|
|
526
|
+
const fromOwner = (message: unknown) => {
|
|
527
|
+
const frame = runtimeOwnerCaptureFrameSchema.safeParse(message);
|
|
528
|
+
if (!frame.success || frame.data.requestId !== requestId) return;
|
|
529
|
+
for (const listener of listeners)
|
|
530
|
+
listener({ data: frame.data.message } as MessageEvent);
|
|
531
|
+
};
|
|
532
|
+
const port = {
|
|
533
|
+
addEventListener: (_: "message", listener: (event: MessageEvent) => void) =>
|
|
534
|
+
listeners.add(listener),
|
|
535
|
+
removeEventListener: (
|
|
536
|
+
_: "message",
|
|
537
|
+
listener: (event: MessageEvent) => void,
|
|
538
|
+
) => listeners.delete(listener),
|
|
539
|
+
start: () => {},
|
|
540
|
+
postMessage: (message: unknown) =>
|
|
541
|
+
owner.send(
|
|
542
|
+
{ type: AIR_JAM_RUNTIME_OWNER_CAPTURE_PORT, requestId, message },
|
|
543
|
+
(error) => {
|
|
544
|
+
if (error) onError(error);
|
|
545
|
+
},
|
|
546
|
+
),
|
|
547
|
+
} as unknown as MessagePort;
|
|
548
|
+
const scoped = createScopedPhoneConnector(session.room, () => true);
|
|
549
|
+
const stopServing = serveRoomPort(port, (address, handlers) => {
|
|
550
|
+
const link = scoped.connector(address, handlers);
|
|
551
|
+
let greeted = false;
|
|
552
|
+
const readOnly: RoomLink = {
|
|
553
|
+
...link,
|
|
554
|
+
send: (data) => {
|
|
555
|
+
if (!greeted || data === "ping") link.send(data);
|
|
556
|
+
greeted = true;
|
|
557
|
+
},
|
|
558
|
+
};
|
|
559
|
+
return readOnly;
|
|
560
|
+
});
|
|
561
|
+
owner.on("message", fromOwner);
|
|
562
|
+
return {
|
|
563
|
+
close() {
|
|
564
|
+
stopServing();
|
|
565
|
+
scoped.close();
|
|
566
|
+
owner.off("message", fromOwner);
|
|
567
|
+
},
|
|
568
|
+
};
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
export const captureControllerSessionVisuals = async ({
|
|
572
|
+
controllerSessionId,
|
|
573
|
+
relativeDir,
|
|
574
|
+
timeoutMs = DEFAULT_VISUAL_CAPTURE_TIMEOUT_MS,
|
|
575
|
+
}: {
|
|
576
|
+
controllerSessionId: string;
|
|
577
|
+
relativeDir: string;
|
|
578
|
+
timeoutMs?: number;
|
|
579
|
+
}) => {
|
|
580
|
+
const session = getRequiredSession(controllerSessionId);
|
|
581
|
+
const owner = session.isolatedRuntimeOwner;
|
|
582
|
+
if (!session.summary.connected)
|
|
583
|
+
throw new Error(
|
|
584
|
+
"The acting controller must be connected for visual capture.",
|
|
585
|
+
);
|
|
586
|
+
if (!owner?.connected) {
|
|
587
|
+
throw new Error(
|
|
588
|
+
`Air Jam controller session "${controllerSessionId}" does not own a capturable host runtime. Capture from the first game session opened for the room.`,
|
|
589
|
+
);
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
const requestId = randomUUID();
|
|
593
|
+
const result = await new Promise<AirJamRuntimeOwnerCaptureResult>(
|
|
594
|
+
(resolve, reject) => {
|
|
595
|
+
const timeout = setTimeout(() => {
|
|
596
|
+
cleanup();
|
|
597
|
+
reject(new Error("Timed out waiting for runtime visual capture."));
|
|
598
|
+
}, timeoutMs);
|
|
599
|
+
const cleanup = () => {
|
|
600
|
+
clearTimeout(timeout);
|
|
601
|
+
relay.close();
|
|
602
|
+
stopFollowing();
|
|
603
|
+
owner.off("message", onMessage);
|
|
604
|
+
owner.off("error", onError);
|
|
605
|
+
owner.off("exit", onExit);
|
|
606
|
+
};
|
|
607
|
+
const onMessage = (message: unknown) => {
|
|
608
|
+
if (
|
|
609
|
+
!isRuntimeOwnerCaptureResult(message) ||
|
|
610
|
+
message.requestId !== requestId
|
|
611
|
+
) {
|
|
612
|
+
return;
|
|
613
|
+
}
|
|
614
|
+
cleanup();
|
|
615
|
+
if (!message.ok) {
|
|
616
|
+
reject(new Error(message.error ?? "Runtime visual capture failed."));
|
|
617
|
+
return;
|
|
618
|
+
}
|
|
619
|
+
resolve(message);
|
|
620
|
+
};
|
|
621
|
+
const onError = (error: Error) => {
|
|
622
|
+
cleanup();
|
|
623
|
+
reject(error);
|
|
624
|
+
};
|
|
625
|
+
const stopFollowing = session.room.on("status", (status) => {
|
|
626
|
+
if (status.phase === "open") return;
|
|
627
|
+
cleanup();
|
|
628
|
+
reject(
|
|
629
|
+
new Error(
|
|
630
|
+
"Acting controller disconnected before visual capture completed.",
|
|
631
|
+
),
|
|
632
|
+
);
|
|
633
|
+
});
|
|
634
|
+
const onExit = (code: number | null) => {
|
|
635
|
+
cleanup();
|
|
636
|
+
reject(
|
|
637
|
+
new Error(
|
|
638
|
+
`Runtime owner exited before visual capture completed (code ${code ?? "unknown"}).`,
|
|
639
|
+
),
|
|
640
|
+
);
|
|
641
|
+
};
|
|
642
|
+
|
|
643
|
+
const relay = relayControllerObservation(
|
|
644
|
+
session,
|
|
645
|
+
owner,
|
|
646
|
+
requestId,
|
|
647
|
+
onError,
|
|
648
|
+
);
|
|
649
|
+
owner.on("message", onMessage);
|
|
650
|
+
owner.once("error", onError);
|
|
651
|
+
owner.once("exit", onExit);
|
|
652
|
+
owner.send(
|
|
653
|
+
{
|
|
654
|
+
type: AIR_JAM_RUNTIME_OWNER_CAPTURE_REQUEST,
|
|
655
|
+
requestId,
|
|
656
|
+
relativeDir,
|
|
657
|
+
harnessSessionId: session.summary.controllerSessionId,
|
|
658
|
+
roomId: session.summary.roomId,
|
|
659
|
+
},
|
|
660
|
+
(error) => {
|
|
661
|
+
if (error) onError(error);
|
|
662
|
+
},
|
|
663
|
+
);
|
|
664
|
+
},
|
|
665
|
+
);
|
|
666
|
+
|
|
667
|
+
return {
|
|
668
|
+
capturedAt: result.capturedAt,
|
|
669
|
+
screenshots: result.screenshots,
|
|
670
|
+
};
|
|
671
|
+
};
|
|
672
|
+
|
|
673
|
+
const buildRuntimeSnapshot = ({
|
|
674
|
+
session,
|
|
675
|
+
requestedStoreDomains = [],
|
|
676
|
+
missingStoreDomains = [],
|
|
677
|
+
}: {
|
|
678
|
+
session: InternalControllerSession;
|
|
679
|
+
requestedStoreDomains?: string[];
|
|
680
|
+
missingStoreDomains?: string[];
|
|
681
|
+
}): AirJamRuntimeSnapshotInspection => {
|
|
682
|
+
const room = session.room;
|
|
683
|
+
return {
|
|
684
|
+
...session.summary,
|
|
685
|
+
welcome: room.instance
|
|
686
|
+
? {
|
|
687
|
+
roomId: room.code,
|
|
688
|
+
instance: room.instance,
|
|
689
|
+
controllerId: room.seat,
|
|
690
|
+
}
|
|
691
|
+
: null,
|
|
692
|
+
controllerState: (room.channel(AIRJAM_PRESENTATION_CHANNEL) ??
|
|
693
|
+
null) as JsonObject | null,
|
|
694
|
+
players: room.seats.map((seat) => ({ ...seat })),
|
|
695
|
+
storeSnapshots: [...room.documents()]
|
|
696
|
+
.map(([storeDomain, data]) => ({
|
|
697
|
+
storeDomain,
|
|
698
|
+
data: data as JsonObject,
|
|
699
|
+
revision: session.storeUpdates.get(storeDomain)?.revision ?? 0,
|
|
700
|
+
updatedAt:
|
|
701
|
+
session.storeUpdates.get(storeDomain)?.updatedAt ??
|
|
702
|
+
session.summary.connectedAt,
|
|
703
|
+
}))
|
|
704
|
+
.sort((left, right) => left.storeDomain.localeCompare(right.storeDomain)),
|
|
705
|
+
lastSignal: session.lastSignal,
|
|
706
|
+
lastError: session.lastError,
|
|
707
|
+
requestedStoreDomains: [...requestedStoreDomains],
|
|
708
|
+
missingStoreDomains: [...missingStoreDomains],
|
|
709
|
+
};
|
|
710
|
+
};
|
|
711
|
+
|
|
712
|
+
const buildSessionSummary = (
|
|
713
|
+
session: InternalControllerSession,
|
|
714
|
+
): AirJamVirtualControllerSessionSummary => ({
|
|
715
|
+
...session.summary,
|
|
716
|
+
});
|
|
717
|
+
|
|
718
|
+
export const ownsControllerSessionHost = (
|
|
719
|
+
controllerSessionId: string,
|
|
720
|
+
): boolean => {
|
|
721
|
+
const owner = getRequiredSession(controllerSessionId).isolatedRuntimeOwner;
|
|
722
|
+
return Boolean(owner?.connected && !owner.killed && owner.exitCode === null);
|
|
723
|
+
};
|
|
724
|
+
|
|
725
|
+
const getRequiredSession = (
|
|
726
|
+
controllerSessionId: string,
|
|
727
|
+
): InternalControllerSession => {
|
|
728
|
+
const session = virtualControllerSessions.get(controllerSessionId);
|
|
729
|
+
if (!session) {
|
|
730
|
+
throw new Error(
|
|
731
|
+
`Unknown Air Jam controller session "${controllerSessionId}". Connect a controller first.`,
|
|
732
|
+
);
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
return session;
|
|
736
|
+
};
|
|
737
|
+
|
|
738
|
+
export const inspectControllerSessionContext = (
|
|
739
|
+
controllerSessionId: string,
|
|
740
|
+
): {
|
|
741
|
+
cwd: string;
|
|
742
|
+
gameId: string | null;
|
|
743
|
+
controllerId: string;
|
|
744
|
+
session: AirJamVirtualControllerSessionSummary;
|
|
745
|
+
} => {
|
|
746
|
+
const session = getRequiredSession(controllerSessionId);
|
|
747
|
+
return {
|
|
748
|
+
cwd: session.cwd,
|
|
749
|
+
gameId: session.summary.gameId,
|
|
750
|
+
controllerId: session.summary.controllerId,
|
|
751
|
+
session: buildSessionSummary(session),
|
|
752
|
+
};
|
|
753
|
+
};
|
|
754
|
+
|
|
755
|
+
export const resolveControllerSessionGameRuntime = async ({
|
|
756
|
+
controllerSessionId,
|
|
757
|
+
game,
|
|
758
|
+
timeoutMs = DEFAULT_TIMEOUT_MS,
|
|
759
|
+
}: {
|
|
760
|
+
controllerSessionId: string;
|
|
761
|
+
timeoutMs?: number;
|
|
762
|
+
game?: AirJamGameInspection;
|
|
763
|
+
}): Promise<{
|
|
764
|
+
gameId: string | null;
|
|
765
|
+
defaultStoreDomain: string;
|
|
766
|
+
}> => {
|
|
767
|
+
const session = getRequiredSession(controllerSessionId);
|
|
768
|
+
const usesArcadeRuntime =
|
|
769
|
+
session.summary.mode === "arcade-dev" ||
|
|
770
|
+
session.summary.mode === "arcade-test" ||
|
|
771
|
+
session.summary.topologyMode === "arcade-live" ||
|
|
772
|
+
session.summary.topologyMode === "arcade-built";
|
|
773
|
+
|
|
774
|
+
if (!usesArcadeRuntime) {
|
|
775
|
+
return {
|
|
776
|
+
gameId: session.summary.gameId,
|
|
777
|
+
defaultStoreDomain: "default",
|
|
778
|
+
};
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
const surfaceData = (await waitForChannel(
|
|
782
|
+
session.room,
|
|
783
|
+
AIR_JAM_ARCADE_SURFACE_STORE_DOMAIN,
|
|
784
|
+
timeoutMs,
|
|
785
|
+
)) as Record<string, unknown> | null;
|
|
786
|
+
// Replicated surface state also contains presentation fields. Validate its
|
|
787
|
+
// identity projection without weakening the strict bridge identity contract.
|
|
788
|
+
const parsedSurface = arcadeSurfaceRuntimeIdentitySchema.safeParse({
|
|
789
|
+
epoch: surfaceData?.epoch,
|
|
790
|
+
kind: surfaceData?.kind,
|
|
791
|
+
gameId: surfaceData?.gameId,
|
|
792
|
+
});
|
|
793
|
+
|
|
794
|
+
if (!parsedSurface.success) {
|
|
795
|
+
throw new Error(
|
|
796
|
+
`Arcade controller session "${controllerSessionId}" did not expose a valid "${AIR_JAM_ARCADE_SURFACE_STORE_DOMAIN}" snapshot.`,
|
|
797
|
+
);
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
if (parsedSurface.data.kind !== "game" || !parsedSurface.data.gameId) {
|
|
801
|
+
session.summary.gameId = null;
|
|
802
|
+
throw new Error(
|
|
803
|
+
`Arcade controller session "${controllerSessionId}" does not currently have an active embedded game.`,
|
|
804
|
+
);
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
const sourceGameId =
|
|
808
|
+
session.projectMode === "standalone-game"
|
|
809
|
+
? (game ?? (await inspectGame({ cwd: session.cwd }))).id
|
|
810
|
+
: (localReferenceSourceGameId(parsedSurface.data.gameId) ??
|
|
811
|
+
parsedSurface.data.gameId);
|
|
812
|
+
session.summary.gameId = sourceGameId;
|
|
813
|
+
|
|
814
|
+
return {
|
|
815
|
+
gameId: sourceGameId,
|
|
816
|
+
defaultStoreDomain: embeddedReplicatedStoreDomainFromArcadeIdentity(
|
|
817
|
+
parsedSurface.data,
|
|
818
|
+
),
|
|
819
|
+
};
|
|
820
|
+
};
|
|
821
|
+
|
|
822
|
+
/** Follows the phone's room: its status, its channels' changes and its signals. */
|
|
823
|
+
const followRoom = (session: InternalControllerSession): void => {
|
|
824
|
+
const room = session.room;
|
|
825
|
+
room.on("status", (status) => {
|
|
826
|
+
// Connected means the room link is open now; a reconnecting phone is not.
|
|
827
|
+
session.summary.connected = status.phase === "open";
|
|
828
|
+
if (status.phase === "open") {
|
|
829
|
+
session.summary.controllerId = room.seat ?? session.summary.controllerId;
|
|
830
|
+
return;
|
|
831
|
+
}
|
|
832
|
+
if (status.phase !== "closed") return;
|
|
833
|
+
session.summary.disconnectedAt = nowIso();
|
|
834
|
+
session.summary.disconnectReason = status.reason;
|
|
835
|
+
if (status.reason !== "owner" && status.reason !== "left")
|
|
836
|
+
session.lastError = { reason: status.reason };
|
|
837
|
+
void terminateIsolatedRuntimeOwner(session.isolatedRuntimeOwner).then(
|
|
838
|
+
() => {
|
|
839
|
+
session.isolatedRuntimeOwner = null;
|
|
840
|
+
},
|
|
841
|
+
(error) => console.error(error),
|
|
842
|
+
);
|
|
843
|
+
});
|
|
844
|
+
room.on("state", ({ channel }) => {
|
|
845
|
+
const previous = session.storeUpdates.get(channel)?.revision ?? 0;
|
|
846
|
+
session.storeUpdates.set(channel, {
|
|
847
|
+
revision: previous + 1,
|
|
848
|
+
updatedAt: nowIso(),
|
|
849
|
+
});
|
|
850
|
+
});
|
|
851
|
+
room.on("signal", (signal) => {
|
|
852
|
+
session.lastSignal = {
|
|
853
|
+
kind: signal.kind,
|
|
854
|
+
payload: signal.payload,
|
|
855
|
+
} as JsonObject;
|
|
856
|
+
});
|
|
857
|
+
};
|
|
858
|
+
|
|
859
|
+
export const connectController = async (
|
|
860
|
+
{
|
|
861
|
+
cwd = process.cwd(),
|
|
862
|
+
gameId,
|
|
863
|
+
mode = "standalone-dev",
|
|
864
|
+
secure = false,
|
|
865
|
+
roomId,
|
|
866
|
+
controllerJoinUrl,
|
|
867
|
+
nickname,
|
|
868
|
+
avatarId,
|
|
869
|
+
timeoutMs = DEFAULT_TIMEOUT_MS,
|
|
870
|
+
}: ConnectControllerOptions = {},
|
|
871
|
+
{
|
|
872
|
+
build,
|
|
873
|
+
onScope,
|
|
874
|
+
settings,
|
|
875
|
+
}: {
|
|
876
|
+
build?: PinnedGameBuild;
|
|
877
|
+
onScope?: ProcessScopeObserver;
|
|
878
|
+
settings?: Record<string, number | boolean | string>;
|
|
879
|
+
} = {},
|
|
880
|
+
): Promise<AirJamVirtualControllerSession> => {
|
|
881
|
+
const context = await detectProjectContext({ cwd });
|
|
882
|
+
const normalizedRequestedRoomId = roomId?.trim().toUpperCase() || undefined;
|
|
883
|
+
const canUseIsolatedOwner =
|
|
884
|
+
!normalizedRequestedRoomId &&
|
|
885
|
+
!controllerJoinUrl &&
|
|
886
|
+
(Boolean(gameId) || context.mode === "standalone-game");
|
|
887
|
+
|
|
888
|
+
const connectWithJoinUrl = async ({
|
|
889
|
+
joinUrlString,
|
|
890
|
+
ownedRuntimeProcess,
|
|
891
|
+
}: {
|
|
892
|
+
joinUrlString: string;
|
|
893
|
+
ownedRuntimeProcess: ChildProcess | null;
|
|
894
|
+
}): Promise<AirJamVirtualControllerSession> => {
|
|
895
|
+
const joinUrl = new URL(joinUrlString);
|
|
896
|
+
const resolvedRoomId =
|
|
897
|
+
normalizedRequestedRoomId ?? parseJoinRoomId(joinUrl);
|
|
898
|
+
if (!resolvedRoomId) {
|
|
899
|
+
throw new Error(
|
|
900
|
+
`Controller join URL "${joinUrlString}" does not include a room code.`,
|
|
901
|
+
);
|
|
902
|
+
}
|
|
903
|
+
|
|
904
|
+
const topology = controllerJoinUrl
|
|
905
|
+
? null
|
|
906
|
+
: await getTopology({ cwd, gameId, mode, secure }).catch(() => null);
|
|
907
|
+
const resolvedGameId = gameId ?? topology?.gameId ?? null;
|
|
908
|
+
const resolvedSocketOrigin =
|
|
909
|
+
parseRuntimeTopologyFromSearchParams(joinUrl.searchParams)
|
|
910
|
+
?.socketOrigin ??
|
|
911
|
+
(controllerJoinUrl
|
|
912
|
+
? joinUrl.origin
|
|
913
|
+
: ((await resolveSocketOriginFromTopology({
|
|
914
|
+
cwd,
|
|
915
|
+
gameId: resolvedGameId ?? undefined,
|
|
916
|
+
mode,
|
|
917
|
+
secure,
|
|
918
|
+
})) ?? joinUrl.origin));
|
|
919
|
+
const controllerSessionId = randomUUID();
|
|
920
|
+
const label = nickname?.trim().slice(0, 24);
|
|
921
|
+
const avatar = avatarId?.trim();
|
|
922
|
+
|
|
923
|
+
const room = new PhoneRoomSession({
|
|
924
|
+
connector: createWebSocketConnector(resolvedSocketOrigin),
|
|
925
|
+
key: createRoomKey(),
|
|
926
|
+
code: resolvedRoomId,
|
|
927
|
+
kind: "agent",
|
|
928
|
+
deviceWakeEvents: null,
|
|
929
|
+
...(label || avatar
|
|
930
|
+
? {
|
|
931
|
+
profile: {
|
|
932
|
+
...(label ? { label } : {}),
|
|
933
|
+
...(avatar ? { avatarId: avatar } : {}),
|
|
934
|
+
},
|
|
935
|
+
}
|
|
936
|
+
: {}),
|
|
937
|
+
});
|
|
938
|
+
|
|
939
|
+
const internalSession: InternalControllerSession = {
|
|
940
|
+
cwd,
|
|
941
|
+
summary: {
|
|
942
|
+
controllerSessionId,
|
|
943
|
+
gameId: resolvedGameId,
|
|
944
|
+
projectMode: context.mode,
|
|
945
|
+
mode,
|
|
946
|
+
topologyMode: build
|
|
947
|
+
? "self-hosted-production"
|
|
948
|
+
: (topology?.topologyMode ?? null),
|
|
949
|
+
secure,
|
|
950
|
+
process: topology?.process ?? null,
|
|
951
|
+
roomId: resolvedRoomId,
|
|
952
|
+
controllerId: "",
|
|
953
|
+
controllerJoinUrl: joinUrlString,
|
|
954
|
+
socketOrigin: resolvedSocketOrigin,
|
|
955
|
+
connected: false,
|
|
956
|
+
connectedAt: nowIso(),
|
|
957
|
+
disconnectedAt: null,
|
|
958
|
+
disconnectReason: null,
|
|
959
|
+
},
|
|
960
|
+
room,
|
|
961
|
+
projectMode: context.mode,
|
|
962
|
+
storeUpdates: new Map(),
|
|
963
|
+
lastSignal: null,
|
|
964
|
+
lastError: null,
|
|
965
|
+
isolatedRuntimeOwner: ownedRuntimeProcess,
|
|
966
|
+
participantLeaseId: null,
|
|
967
|
+
participantLastCommand: null,
|
|
968
|
+
inputState: null,
|
|
969
|
+
inputLayout: undefined,
|
|
970
|
+
};
|
|
971
|
+
|
|
972
|
+
followRoom(internalSession);
|
|
973
|
+
|
|
974
|
+
try {
|
|
975
|
+
await waitForWelcome(room, timeoutMs);
|
|
976
|
+
// A host in the room publishes its presentation at once; a summary
|
|
977
|
+
// without it reads as a room whose host is away.
|
|
978
|
+
await waitForChannel(
|
|
979
|
+
room,
|
|
980
|
+
AIRJAM_PRESENTATION_CHANNEL,
|
|
981
|
+
Math.min(timeoutMs, 500),
|
|
982
|
+
);
|
|
983
|
+
virtualControllerSessions.set(controllerSessionId, internalSession);
|
|
984
|
+
return buildRuntimeSnapshot({ session: internalSession });
|
|
985
|
+
} catch (error) {
|
|
986
|
+
room.close();
|
|
987
|
+
await terminateIsolatedRuntimeOwner(ownedRuntimeProcess);
|
|
988
|
+
throw error;
|
|
989
|
+
}
|
|
990
|
+
};
|
|
991
|
+
|
|
992
|
+
const resolvedJoinUrl = build
|
|
993
|
+
? null
|
|
994
|
+
: (controllerJoinUrl ??
|
|
995
|
+
(await resolveControllerJoinUrlFromTopology({
|
|
996
|
+
cwd,
|
|
997
|
+
gameId,
|
|
998
|
+
mode,
|
|
999
|
+
secure,
|
|
1000
|
+
roomId: normalizedRequestedRoomId,
|
|
1001
|
+
})));
|
|
1002
|
+
if (!resolvedJoinUrl) {
|
|
1003
|
+
if (!canUseIsolatedOwner) {
|
|
1004
|
+
throw new Error(
|
|
1005
|
+
"Unable to resolve a controller join URL. Open the host page first so a room exists, or provide roomId/controllerJoinUrl explicitly. If a stale dev process may be holding the local runtime, run `pnpm exec airjam status` and then `pnpm exec airjam reset local`.",
|
|
1006
|
+
);
|
|
1007
|
+
}
|
|
1008
|
+
|
|
1009
|
+
const owner = await startIsolatedRuntimeOwner({
|
|
1010
|
+
cwd,
|
|
1011
|
+
gameId,
|
|
1012
|
+
mode,
|
|
1013
|
+
secure,
|
|
1014
|
+
timeoutMs,
|
|
1015
|
+
build,
|
|
1016
|
+
settings,
|
|
1017
|
+
onScope,
|
|
1018
|
+
});
|
|
1019
|
+
if (!owner.controllerJoinUrl) {
|
|
1020
|
+
await terminateIsolatedRuntimeOwner(owner.process);
|
|
1021
|
+
throw new Error(
|
|
1022
|
+
"Isolated runtime owner did not produce a controller join URL.",
|
|
1023
|
+
);
|
|
1024
|
+
}
|
|
1025
|
+
|
|
1026
|
+
return connectWithJoinUrl({
|
|
1027
|
+
joinUrlString: owner.controllerJoinUrl,
|
|
1028
|
+
ownedRuntimeProcess: owner.process,
|
|
1029
|
+
});
|
|
1030
|
+
}
|
|
1031
|
+
|
|
1032
|
+
return connectWithJoinUrl({
|
|
1033
|
+
joinUrlString: resolvedJoinUrl,
|
|
1034
|
+
ownedRuntimeProcess: null,
|
|
1035
|
+
});
|
|
1036
|
+
};
|
|
1037
|
+
|
|
1038
|
+
export const sendControllerInput = async ({
|
|
1039
|
+
controllerSessionId,
|
|
1040
|
+
input,
|
|
1041
|
+
}: SendControllerInputOptions): Promise<SendControllerInputResult> => {
|
|
1042
|
+
const session = getRequiredSession(controllerSessionId);
|
|
1043
|
+
if (!session.summary.connected) {
|
|
1044
|
+
throw new Error(
|
|
1045
|
+
`Air Jam controller session "${controllerSessionId}" is not connected.`,
|
|
1046
|
+
);
|
|
1047
|
+
}
|
|
1048
|
+
|
|
1049
|
+
if (session.participantLeaseId)
|
|
1050
|
+
throw new Error(
|
|
1051
|
+
"participant_control_leased: Use the leased control path for this player.",
|
|
1052
|
+
);
|
|
1053
|
+
session.inputLayout ??=
|
|
1054
|
+
(await inspectGame({
|
|
1055
|
+
cwd: session.cwd,
|
|
1056
|
+
...(session.summary.gameId ? { gameId: session.summary.gameId } : {}),
|
|
1057
|
+
}).then(
|
|
1058
|
+
(game) => game.declaration.input,
|
|
1059
|
+
() => null,
|
|
1060
|
+
)) ?? null;
|
|
1061
|
+
const layout = session.inputLayout;
|
|
1062
|
+
if (!layout)
|
|
1063
|
+
throw new Error(
|
|
1064
|
+
"input_unavailable: This controller's game declares no controls it can read.",
|
|
1065
|
+
);
|
|
1066
|
+
// An agent sends values; a button turns into a press each time it goes down.
|
|
1067
|
+
const payload = {
|
|
1068
|
+
...session.inputState,
|
|
1069
|
+
...agentValuesToInputState(session.inputState, input),
|
|
1070
|
+
};
|
|
1071
|
+
session.inputState = payload;
|
|
1072
|
+
session.room.sendInputFrame(
|
|
1073
|
+
encodePhoneInputFrame(encodeInputPayload(layout, payload)),
|
|
1074
|
+
);
|
|
1075
|
+
|
|
1076
|
+
return {
|
|
1077
|
+
...buildSessionSummary(session),
|
|
1078
|
+
input: payload,
|
|
1079
|
+
sentAt: nowIso(),
|
|
1080
|
+
};
|
|
1081
|
+
};
|
|
1082
|
+
|
|
1083
|
+
export async function controlControllerParticipant({
|
|
1084
|
+
controllerSessionId,
|
|
1085
|
+
...input
|
|
1086
|
+
}: {
|
|
1087
|
+
controllerSessionId: string;
|
|
1088
|
+
} & LeasedControlRequest): Promise<ControllerLeasedControlAck> {
|
|
1089
|
+
const session = getRequiredSession(controllerSessionId);
|
|
1090
|
+
const request = leasedControlRequestSchema.parse(input);
|
|
1091
|
+
if (!session.summary.connected)
|
|
1092
|
+
return { status: "rejected", reason: "unauthorized" };
|
|
1093
|
+
if (
|
|
1094
|
+
session.participantLeaseId &&
|
|
1095
|
+
session.participantLeaseId !== request.lease.id
|
|
1096
|
+
)
|
|
1097
|
+
return { status: "rejected", reason: "lease_conflict" };
|
|
1098
|
+
session.participantLeaseId = request.lease.id;
|
|
1099
|
+
if (
|
|
1100
|
+
!session.participantLastCommand ||
|
|
1101
|
+
request.lease.sequence > session.participantLastCommand.lease.sequence
|
|
1102
|
+
)
|
|
1103
|
+
session.participantLastCommand = request;
|
|
1104
|
+
const outcome = await session.room.request(
|
|
1105
|
+
AIRJAM_CONTROL_CHANNEL,
|
|
1106
|
+
AIRJAM_LEASED_CONTROL_REQUEST,
|
|
1107
|
+
request,
|
|
1108
|
+
{ exclusive: true, timeoutMs: 2000 },
|
|
1109
|
+
);
|
|
1110
|
+
if (outcome.status === "busy") return { status: "rejected", reason: "busy" };
|
|
1111
|
+
if (outcome.status === "refused")
|
|
1112
|
+
return { status: "rejected", reason: "active_host_missing" };
|
|
1113
|
+
if (outcome.status === "unconfirmed")
|
|
1114
|
+
return { status: "unconfirmed", reason: "transport_ack_unavailable" };
|
|
1115
|
+
const parsed = controllerLeasedControlAckSchema.safeParse(outcome.result);
|
|
1116
|
+
if (
|
|
1117
|
+
!parsed.success ||
|
|
1118
|
+
(parsed.data.status === "applied" &&
|
|
1119
|
+
(parsed.data.leaseId !== request.lease.id ||
|
|
1120
|
+
parsed.data.sequence !== request.lease.sequence ||
|
|
1121
|
+
parsed.data.operation.kind !== request.operation.kind))
|
|
1122
|
+
)
|
|
1123
|
+
return { status: "unconfirmed", reason: "invalid_acknowledgement" };
|
|
1124
|
+
return parsed.data;
|
|
1125
|
+
}
|
|
1126
|
+
|
|
1127
|
+
export const invokeControllerAction = async ({
|
|
1128
|
+
controllerSessionId,
|
|
1129
|
+
actionName,
|
|
1130
|
+
storeDomain,
|
|
1131
|
+
payload,
|
|
1132
|
+
timeoutMs = DEFAULT_TIMEOUT_MS,
|
|
1133
|
+
}: InvokeControllerActionOptions): Promise<InvokeControllerActionResult> => {
|
|
1134
|
+
const session = getRequiredSession(controllerSessionId);
|
|
1135
|
+
if (!session.summary.connected) {
|
|
1136
|
+
throw new Error(
|
|
1137
|
+
`Air Jam controller session "${controllerSessionId}" is not connected.`,
|
|
1138
|
+
);
|
|
1139
|
+
}
|
|
1140
|
+
|
|
1141
|
+
if (session.participantLeaseId)
|
|
1142
|
+
throw new Error(
|
|
1143
|
+
"participant_control_leased: Use the leased control path for this player.",
|
|
1144
|
+
);
|
|
1145
|
+
const normalizedPayload = payload ? { ...payload } : undefined;
|
|
1146
|
+
const acknowledgement = airJamActionResultOf(
|
|
1147
|
+
await session.room.request(storeDomain, actionName, normalizedPayload, {
|
|
1148
|
+
timeoutMs,
|
|
1149
|
+
}),
|
|
1150
|
+
);
|
|
1151
|
+
|
|
1152
|
+
return {
|
|
1153
|
+
...buildSessionSummary(session),
|
|
1154
|
+
actionName,
|
|
1155
|
+
storeDomain,
|
|
1156
|
+
...(normalizedPayload ? { payload: normalizedPayload } : {}),
|
|
1157
|
+
sentAt: nowIso(),
|
|
1158
|
+
acknowledgement,
|
|
1159
|
+
};
|
|
1160
|
+
};
|
|
1161
|
+
|
|
1162
|
+
export const invokeHostAction = async ({
|
|
1163
|
+
controllerSessionId,
|
|
1164
|
+
actionName,
|
|
1165
|
+
storeDomain,
|
|
1166
|
+
payload,
|
|
1167
|
+
timeoutMs = DEFAULT_TIMEOUT_MS,
|
|
1168
|
+
}: {
|
|
1169
|
+
controllerSessionId: string;
|
|
1170
|
+
actionName: string;
|
|
1171
|
+
storeDomain: string;
|
|
1172
|
+
payload?: Record<string, unknown>;
|
|
1173
|
+
timeoutMs?: number;
|
|
1174
|
+
}): Promise<InvokeControllerActionResult> => {
|
|
1175
|
+
const session = getRequiredSession(controllerSessionId);
|
|
1176
|
+
if (!session.summary.connected) {
|
|
1177
|
+
throw new Error(
|
|
1178
|
+
`Air Jam controller session "${controllerSessionId}" is not connected.`,
|
|
1179
|
+
);
|
|
1180
|
+
}
|
|
1181
|
+
|
|
1182
|
+
const normalizedPayload = payload ? { ...payload } : undefined;
|
|
1183
|
+
const owner = session.isolatedRuntimeOwner;
|
|
1184
|
+
const acknowledgement: AirJamActionInvocationResult =
|
|
1185
|
+
owner && ownsControllerSessionHost(controllerSessionId)
|
|
1186
|
+
? await requestOwnedHostAction({
|
|
1187
|
+
owner,
|
|
1188
|
+
payload: {
|
|
1189
|
+
roomId: session.summary.roomId,
|
|
1190
|
+
actionName,
|
|
1191
|
+
payload: normalizedPayload,
|
|
1192
|
+
storeDomain,
|
|
1193
|
+
},
|
|
1194
|
+
timeoutMs,
|
|
1195
|
+
})
|
|
1196
|
+
: {
|
|
1197
|
+
ok: false,
|
|
1198
|
+
status: "rejected",
|
|
1199
|
+
source: "client",
|
|
1200
|
+
reason: "host_runtime_not_owned",
|
|
1201
|
+
message:
|
|
1202
|
+
"Host actions require an owned host runtime; room attachments provide player participation only.",
|
|
1203
|
+
};
|
|
1204
|
+
|
|
1205
|
+
return {
|
|
1206
|
+
...buildSessionSummary(session),
|
|
1207
|
+
actionName,
|
|
1208
|
+
storeDomain,
|
|
1209
|
+
...(normalizedPayload ? { payload: normalizedPayload } : {}),
|
|
1210
|
+
sentAt: nowIso(),
|
|
1211
|
+
acknowledgement,
|
|
1212
|
+
};
|
|
1213
|
+
};
|
|
1214
|
+
|
|
1215
|
+
export const readRuntimeSnapshot = async ({
|
|
1216
|
+
controllerSessionId,
|
|
1217
|
+
storeDomains = [],
|
|
1218
|
+
requestSync = storeDomains.length > 0,
|
|
1219
|
+
timeoutMs = DEFAULT_TIMEOUT_MS,
|
|
1220
|
+
}: ReadRuntimeSnapshotOptions): Promise<AirJamRuntimeSnapshotInspection> => {
|
|
1221
|
+
const session = getRequiredSession(controllerSessionId);
|
|
1222
|
+
const normalizedStoreDomains = Array.from(
|
|
1223
|
+
new Set(
|
|
1224
|
+
storeDomains
|
|
1225
|
+
.map((entry) => entry.trim())
|
|
1226
|
+
.filter((entry) => entry.length > 0),
|
|
1227
|
+
),
|
|
1228
|
+
);
|
|
1229
|
+
|
|
1230
|
+
const missingStoreDomains: string[] = [];
|
|
1231
|
+
if (requestSync && normalizedStoreDomains.length > 0) {
|
|
1232
|
+
const syncResults = await Promise.all(
|
|
1233
|
+
normalizedStoreDomains.map(async (storeDomain) => ({
|
|
1234
|
+
storeDomain,
|
|
1235
|
+
ok:
|
|
1236
|
+
(await waitForChannel(session.room, storeDomain, timeoutMs)) !== null,
|
|
1237
|
+
})),
|
|
1238
|
+
);
|
|
1239
|
+
|
|
1240
|
+
for (const result of syncResults) {
|
|
1241
|
+
if (!result.ok) {
|
|
1242
|
+
missingStoreDomains.push(result.storeDomain);
|
|
1243
|
+
}
|
|
1244
|
+
}
|
|
1245
|
+
}
|
|
1246
|
+
|
|
1247
|
+
return buildRuntimeSnapshot({
|
|
1248
|
+
session,
|
|
1249
|
+
requestedStoreDomains: normalizedStoreDomains,
|
|
1250
|
+
missingStoreDomains,
|
|
1251
|
+
});
|
|
1252
|
+
};
|
|
1253
|
+
|
|
1254
|
+
async function disposeControllerSession(session: InternalControllerSession) {
|
|
1255
|
+
const owner = session.isolatedRuntimeOwner;
|
|
1256
|
+
session.room.close();
|
|
1257
|
+
session.summary.connected = false;
|
|
1258
|
+
session.summary.disconnectedAt ??= nowIso();
|
|
1259
|
+
session.summary.disconnectReason ??= "manual_disconnect";
|
|
1260
|
+
await terminateIsolatedRuntimeOwner(owner);
|
|
1261
|
+
session.isolatedRuntimeOwner = null;
|
|
1262
|
+
virtualControllerSessions.delete(session.summary.controllerSessionId);
|
|
1263
|
+
}
|
|
1264
|
+
|
|
1265
|
+
export async function forceDisconnectController({
|
|
1266
|
+
controllerSessionId,
|
|
1267
|
+
}: DisconnectControllerOptions): Promise<DisconnectControllerResult> {
|
|
1268
|
+
const session = getRequiredSession(controllerSessionId);
|
|
1269
|
+
await disposeControllerSession(session);
|
|
1270
|
+
return {
|
|
1271
|
+
disconnected: true,
|
|
1272
|
+
release: { status: "unconfirmed", reason: "runtime_unavailable" },
|
|
1273
|
+
leave: {
|
|
1274
|
+
status: "unconfirmed",
|
|
1275
|
+
message:
|
|
1276
|
+
"Forced local transport/runtime teardown; server leave was not confirmed.",
|
|
1277
|
+
},
|
|
1278
|
+
session: buildSessionSummary(session),
|
|
1279
|
+
};
|
|
1280
|
+
}
|
|
1281
|
+
|
|
1282
|
+
export const disconnectController = async ({
|
|
1283
|
+
controllerSessionId,
|
|
1284
|
+
}: DisconnectControllerOptions): Promise<DisconnectControllerResult> => {
|
|
1285
|
+
const session = getRequiredSession(controllerSessionId);
|
|
1286
|
+
const last = session.participantLastCommand;
|
|
1287
|
+
const release: DisconnectControllerResult["release"] = last
|
|
1288
|
+
? last.lease.sequence === Number.MAX_SAFE_INTEGER
|
|
1289
|
+
? { status: "rejected", reason: "invalid_request" }
|
|
1290
|
+
: await controlControllerParticipant({
|
|
1291
|
+
controllerSessionId,
|
|
1292
|
+
expected: last.expected,
|
|
1293
|
+
lease: { id: last.lease.id, sequence: last.lease.sequence + 1 },
|
|
1294
|
+
operation: { kind: "release" },
|
|
1295
|
+
})
|
|
1296
|
+
: { status: "not-leased" };
|
|
1297
|
+
let leave: DisconnectControllerResult["leave"] = { status: "not-connected" };
|
|
1298
|
+
if (session.summary.connected) {
|
|
1299
|
+
session.room.leave();
|
|
1300
|
+
await waitForCondition({
|
|
1301
|
+
timeoutMs: DEFAULT_TIMEOUT_MS,
|
|
1302
|
+
predicate: () => session.room.status.phase === "closed",
|
|
1303
|
+
});
|
|
1304
|
+
const status = session.room.status;
|
|
1305
|
+
leave =
|
|
1306
|
+
status.phase === "closed" && status.reason === "left"
|
|
1307
|
+
? { status: "acknowledged" }
|
|
1308
|
+
: {
|
|
1309
|
+
status: "unconfirmed",
|
|
1310
|
+
message: "The room did not confirm the seat was given up.",
|
|
1311
|
+
};
|
|
1312
|
+
}
|
|
1313
|
+
await disposeControllerSession(session);
|
|
1314
|
+
|
|
1315
|
+
return {
|
|
1316
|
+
disconnected: true,
|
|
1317
|
+
leave,
|
|
1318
|
+
release,
|
|
1319
|
+
session: buildSessionSummary(session),
|
|
1320
|
+
};
|
|
1321
|
+
};
|
|
1322
|
+
|
|
1323
|
+
export async function requestControllerHostAgent(
|
|
1324
|
+
controllerSessionId: string,
|
|
1325
|
+
request: HostAgentRequest,
|
|
1326
|
+
timeoutMs: number,
|
|
1327
|
+
signal?: AbortSignal,
|
|
1328
|
+
): Promise<HostAgentResponse> {
|
|
1329
|
+
const owner = getRequiredSession(controllerSessionId).isolatedRuntimeOwner;
|
|
1330
|
+
if (!owner || !ownsControllerSessionHost(controllerSessionId))
|
|
1331
|
+
throw new Error(
|
|
1332
|
+
"contract_runtime_not_owned: Semantic testing requires an owned host. Open a game session without an explicit room or join URL.",
|
|
1333
|
+
);
|
|
1334
|
+
return new Promise((resolve, reject) => {
|
|
1335
|
+
const requestId = randomUUID();
|
|
1336
|
+
let settled = false;
|
|
1337
|
+
const finish = (error?: Error, result?: HostAgentResponse) => {
|
|
1338
|
+
if (settled) return;
|
|
1339
|
+
settled = true;
|
|
1340
|
+
clearTimeout(timer);
|
|
1341
|
+
owner.off("message", onMessage);
|
|
1342
|
+
owner.off("error", onError);
|
|
1343
|
+
owner.off("exit", onExit);
|
|
1344
|
+
owner.off("disconnect", onExit);
|
|
1345
|
+
signal?.removeEventListener("abort", onAbort);
|
|
1346
|
+
if (error) reject(error);
|
|
1347
|
+
else if (result) resolve(result);
|
|
1348
|
+
};
|
|
1349
|
+
const onMessage = (message: unknown) => {
|
|
1350
|
+
if (
|
|
1351
|
+
!message ||
|
|
1352
|
+
typeof message !== "object" ||
|
|
1353
|
+
!("type" in message) ||
|
|
1354
|
+
message.type !== "air-jam-runtime-owner.agent-result/v1" ||
|
|
1355
|
+
!("requestId" in message) ||
|
|
1356
|
+
message.requestId !== requestId
|
|
1357
|
+
)
|
|
1358
|
+
return;
|
|
1359
|
+
const parsed = runtimeOwnerAgentResultSchema.safeParse(message);
|
|
1360
|
+
if (!parsed.success) {
|
|
1361
|
+
finish(
|
|
1362
|
+
new Error(
|
|
1363
|
+
"invalid_runtime_response: Owned host returned an invalid agent response.",
|
|
1364
|
+
),
|
|
1365
|
+
);
|
|
1366
|
+
return;
|
|
1367
|
+
}
|
|
1368
|
+
if (parsed.data.ok) finish(undefined, parsed.data.result);
|
|
1369
|
+
else finish(new Error(parsed.data.error));
|
|
1370
|
+
};
|
|
1371
|
+
const onError = (error: Error) => finish(error);
|
|
1372
|
+
const onExit = () =>
|
|
1373
|
+
finish(
|
|
1374
|
+
new Error("runtime_disconnected: Owned host exited during evaluation."),
|
|
1375
|
+
);
|
|
1376
|
+
const onAbort = () =>
|
|
1377
|
+
finish(new Error("session_closed: Evaluation was cancelled."));
|
|
1378
|
+
const timer = setTimeout(
|
|
1379
|
+
() =>
|
|
1380
|
+
finish(
|
|
1381
|
+
new Error("evaluation_timeout: Owned game evaluation timed out."),
|
|
1382
|
+
),
|
|
1383
|
+
timeoutMs,
|
|
1384
|
+
);
|
|
1385
|
+
owner.on("message", onMessage);
|
|
1386
|
+
owner.once("error", onError);
|
|
1387
|
+
owner.once("exit", onExit);
|
|
1388
|
+
owner.once("disconnect", onExit);
|
|
1389
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
1390
|
+
if (signal?.aborted) {
|
|
1391
|
+
onAbort();
|
|
1392
|
+
return;
|
|
1393
|
+
}
|
|
1394
|
+
try {
|
|
1395
|
+
owner.send(
|
|
1396
|
+
{ type: "air-jam-runtime-owner.agent/v1", requestId, request },
|
|
1397
|
+
(error) => {
|
|
1398
|
+
if (error) onError(error);
|
|
1399
|
+
},
|
|
1400
|
+
);
|
|
1401
|
+
} catch (error) {
|
|
1402
|
+
onError(error instanceof Error ? error : new Error(String(error)));
|
|
1403
|
+
}
|
|
1404
|
+
});
|
|
1405
|
+
}
|
|
1406
|
+
|
|
1407
|
+
export async function watchControllerSessionVisuals({
|
|
1408
|
+
ownerControllerSessionId,
|
|
1409
|
+
controllerSessionId,
|
|
1410
|
+
onEvent,
|
|
1411
|
+
signal,
|
|
1412
|
+
}: {
|
|
1413
|
+
ownerControllerSessionId: string;
|
|
1414
|
+
controllerSessionId?: string;
|
|
1415
|
+
onEvent: (event: GameSurfaceWatchEvent) => void;
|
|
1416
|
+
signal: AbortSignal;
|
|
1417
|
+
}): Promise<void> {
|
|
1418
|
+
signal.throwIfAborted();
|
|
1419
|
+
const session = getRequiredSession(ownerControllerSessionId);
|
|
1420
|
+
const owner = session.isolatedRuntimeOwner;
|
|
1421
|
+
if (!owner?.connected)
|
|
1422
|
+
throw new Error("Run watch requires its owned host runtime.");
|
|
1423
|
+
const target = controllerSessionId
|
|
1424
|
+
? getRequiredSession(controllerSessionId)
|
|
1425
|
+
: undefined;
|
|
1426
|
+
if (
|
|
1427
|
+
target &&
|
|
1428
|
+
(!target.summary.connected ||
|
|
1429
|
+
target.summary.roomId !== session.summary.roomId)
|
|
1430
|
+
)
|
|
1431
|
+
throw new Error("Run watch controller is not connected to the owned room.");
|
|
1432
|
+
const watchId = randomUUID();
|
|
1433
|
+
await new Promise<void>((resolve, reject) => {
|
|
1434
|
+
let stopping = false;
|
|
1435
|
+
let failed: Error | undefined;
|
|
1436
|
+
const cleanup = () => {
|
|
1437
|
+
clearTimeout(timeout);
|
|
1438
|
+
owner.off("message", message);
|
|
1439
|
+
owner.off("error", error);
|
|
1440
|
+
owner.off("exit", exit);
|
|
1441
|
+
signal.removeEventListener("abort", stop);
|
|
1442
|
+
relay?.close();
|
|
1443
|
+
};
|
|
1444
|
+
const settle = (failure?: Error) => {
|
|
1445
|
+
cleanup();
|
|
1446
|
+
if (failure) reject(failure);
|
|
1447
|
+
else resolve();
|
|
1448
|
+
};
|
|
1449
|
+
let timeout = setTimeout(
|
|
1450
|
+
() => error(new Error("Timed out starting the game watch.")),
|
|
1451
|
+
DEFAULT_VISUAL_CAPTURE_TIMEOUT_MS,
|
|
1452
|
+
);
|
|
1453
|
+
const stop = () => {
|
|
1454
|
+
if (stopping) return;
|
|
1455
|
+
stopping = true;
|
|
1456
|
+
clearTimeout(timeout);
|
|
1457
|
+
timeout = setTimeout(
|
|
1458
|
+
() => settle(new Error("Timed out closing the game watch.")),
|
|
1459
|
+
DEFAULT_VISUAL_CAPTURE_TIMEOUT_MS,
|
|
1460
|
+
);
|
|
1461
|
+
owner.send(
|
|
1462
|
+
{ type: "air-jam-runtime-owner.watch-stop/v1", watchId },
|
|
1463
|
+
(failure) => {
|
|
1464
|
+
if (failure) settle(failure);
|
|
1465
|
+
},
|
|
1466
|
+
);
|
|
1467
|
+
};
|
|
1468
|
+
const error = (failure: Error) => {
|
|
1469
|
+
failed ??= failure;
|
|
1470
|
+
stop();
|
|
1471
|
+
};
|
|
1472
|
+
const exit = () =>
|
|
1473
|
+
settle(new Error("Game watch owner exited before its stream closed."));
|
|
1474
|
+
const message = (value: unknown) => {
|
|
1475
|
+
const parsed = runtimeOwnerWatchEventSchema.safeParse(value);
|
|
1476
|
+
if (!parsed.success || parsed.data.watchId !== watchId) return;
|
|
1477
|
+
const event = parsed.data.event;
|
|
1478
|
+
if (event.type === "closed") {
|
|
1479
|
+
settle(failed);
|
|
1480
|
+
return;
|
|
1481
|
+
}
|
|
1482
|
+
if (event.type === "error") {
|
|
1483
|
+
if (stopping) {
|
|
1484
|
+
settle(new Error(event.message));
|
|
1485
|
+
return;
|
|
1486
|
+
}
|
|
1487
|
+
error(new Error(event.message));
|
|
1488
|
+
return;
|
|
1489
|
+
}
|
|
1490
|
+
if (stopping) return;
|
|
1491
|
+
if (event.type === "ready") clearTimeout(timeout);
|
|
1492
|
+
try {
|
|
1493
|
+
onEvent(event);
|
|
1494
|
+
} catch (failure) {
|
|
1495
|
+
error(failure instanceof Error ? failure : new Error(String(failure)));
|
|
1496
|
+
}
|
|
1497
|
+
};
|
|
1498
|
+
const relay = target
|
|
1499
|
+
? relayControllerObservation(target, owner, watchId, error)
|
|
1500
|
+
: undefined;
|
|
1501
|
+
owner.on("message", message);
|
|
1502
|
+
owner.once("error", error);
|
|
1503
|
+
owner.once("exit", exit);
|
|
1504
|
+
signal.addEventListener("abort", stop, { once: true });
|
|
1505
|
+
if (signal.aborted) {
|
|
1506
|
+
stop();
|
|
1507
|
+
return;
|
|
1508
|
+
}
|
|
1509
|
+
owner.send(
|
|
1510
|
+
{
|
|
1511
|
+
type: "air-jam-runtime-owner.watch/v1",
|
|
1512
|
+
watchId,
|
|
1513
|
+
surface: target ? "controller" : "host",
|
|
1514
|
+
...(target
|
|
1515
|
+
? {
|
|
1516
|
+
harnessSessionId: target.summary.controllerSessionId,
|
|
1517
|
+
roomId: target.summary.roomId,
|
|
1518
|
+
}
|
|
1519
|
+
: {}),
|
|
1520
|
+
},
|
|
1521
|
+
(failure) => {
|
|
1522
|
+
if (failure) error(failure);
|
|
1523
|
+
},
|
|
1524
|
+
);
|
|
1525
|
+
});
|
|
1526
|
+
}
|