@air-jam/devtools 0.9.3 → 1.0.0-beta.10
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-GUEZP773.js → chunk-LB3Y64P5.js} +206 -60
- package/dist/chunk-LB3Y64P5.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-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 +770 -68
- 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 +288 -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 +74 -69
- 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 +254 -42
- 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 +329 -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
|
@@ -0,0 +1,3384 @@
|
|
|
1
|
+
import {
|
|
2
|
+
sealGameBuild,
|
|
3
|
+
verifyPinnedGameBuild
|
|
4
|
+
} from "./chunk-FN7E6EA7.js";
|
|
5
|
+
import {
|
|
6
|
+
TEST_PROFILE_IPC_MAX_BYTES,
|
|
7
|
+
testProfileRequestSchema,
|
|
8
|
+
testProfileResponseSchema
|
|
9
|
+
} from "./chunk-L4D675BG.js";
|
|
10
|
+
import {
|
|
11
|
+
HEADLESS_ROOM_IPC_MAX_BYTES,
|
|
12
|
+
HEADLESS_ROOM_MAX_ADVANCE_MS,
|
|
13
|
+
headlessRoomRequestSchema,
|
|
14
|
+
headlessRoomResponseSchema
|
|
15
|
+
} from "./chunk-ITKAOEGX.js";
|
|
16
|
+
import {
|
|
17
|
+
MAXIMUM_GAME_RUN_MS,
|
|
18
|
+
MAXIMUM_GAME_RUN_STEERING_CHANGES,
|
|
19
|
+
MAXIMUM_GAME_RUN_TRACE_BYTES,
|
|
20
|
+
currentRoomAttachmentSchema,
|
|
21
|
+
currentRoomHostRequestSchema,
|
|
22
|
+
currentRoomSeatClaimSchema,
|
|
23
|
+
gameRunAddressSchema,
|
|
24
|
+
gameRunRecordSchema,
|
|
25
|
+
gameRunSessionIdentitySchema,
|
|
26
|
+
gameRunSteerSchema,
|
|
27
|
+
startGameRunSchema
|
|
28
|
+
} from "./chunk-HZUGBH4Y.js";
|
|
29
|
+
import {
|
|
30
|
+
PLAY_RUN_PLAYER,
|
|
31
|
+
policyArtifactManifestSchema,
|
|
32
|
+
policyArtifactReceiptSchema
|
|
33
|
+
} from "./chunk-PMNE5GIN.js";
|
|
34
|
+
import {
|
|
35
|
+
gameBuildIdentitySchema
|
|
36
|
+
} from "./chunk-ASC2CK2R.js";
|
|
37
|
+
import {
|
|
38
|
+
captureControllerSessionVisuals,
|
|
39
|
+
connectController,
|
|
40
|
+
controlControllerParticipant,
|
|
41
|
+
disconnectController,
|
|
42
|
+
forceDisconnectController,
|
|
43
|
+
invokeControllerAction,
|
|
44
|
+
ownsControllerSessionHost,
|
|
45
|
+
readRuntimeSnapshot,
|
|
46
|
+
requestControllerHostAgent,
|
|
47
|
+
resolveControllerSessionGameRuntime,
|
|
48
|
+
sendControllerInput,
|
|
49
|
+
watchControllerSessionVisuals
|
|
50
|
+
} from "./chunk-JSI5S4WP.js";
|
|
51
|
+
import {
|
|
52
|
+
assertProcessScopesConfirmed,
|
|
53
|
+
closeAfterProcessFailure,
|
|
54
|
+
closeScopedProcess,
|
|
55
|
+
nodeProcessEnvironment,
|
|
56
|
+
spawnScopedProcess
|
|
57
|
+
} from "./chunk-QGADSPHZ.js";
|
|
58
|
+
import {
|
|
59
|
+
gameRunWatchRequestSchema
|
|
60
|
+
} from "./chunk-AO3ZDXF6.js";
|
|
61
|
+
import {
|
|
62
|
+
processScopeAdmissionSchema
|
|
63
|
+
} from "./chunk-SPYN66UV.js";
|
|
64
|
+
import {
|
|
65
|
+
startDev,
|
|
66
|
+
stopDev
|
|
67
|
+
} from "./chunk-MEIMOSZC.js";
|
|
68
|
+
import {
|
|
69
|
+
inspectGame
|
|
70
|
+
} from "./chunk-ART5TEYT.js";
|
|
71
|
+
import {
|
|
72
|
+
resolveDevtoolsHelperArgs,
|
|
73
|
+
resolveDevtoolsHelperScript,
|
|
74
|
+
resolveProjectDevtoolsHelperScript
|
|
75
|
+
} from "./chunk-PKD4WVX5.js";
|
|
76
|
+
|
|
77
|
+
// src/current-room-host.ts
|
|
78
|
+
import {
|
|
79
|
+
hostAgentResultMessageSchema
|
|
80
|
+
} from "@air-jam/sdk/runtime-control";
|
|
81
|
+
|
|
82
|
+
// src/bounded-response.ts
|
|
83
|
+
var BodyLimitError = class extends Error {
|
|
84
|
+
};
|
|
85
|
+
async function readBoundedText(body, maxBytes) {
|
|
86
|
+
const reader = body.getReader();
|
|
87
|
+
const chunks = [];
|
|
88
|
+
let bytes = 0;
|
|
89
|
+
try {
|
|
90
|
+
while (true) {
|
|
91
|
+
const next = await reader.read();
|
|
92
|
+
if (next.done) break;
|
|
93
|
+
bytes += next.value.byteLength;
|
|
94
|
+
if (bytes > maxBytes)
|
|
95
|
+
throw new BodyLimitError(`Response exceeded ${maxBytes} bytes.`);
|
|
96
|
+
chunks.push(next.value);
|
|
97
|
+
}
|
|
98
|
+
} catch (error) {
|
|
99
|
+
await reader.cancel().catch(() => void 0);
|
|
100
|
+
throw error;
|
|
101
|
+
} finally {
|
|
102
|
+
reader.releaseLock();
|
|
103
|
+
}
|
|
104
|
+
return Buffer.concat(chunks, bytes).toString("utf8");
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// src/current-room-host.ts
|
|
108
|
+
var MAXIMUM_RESPONSE_BYTES = 2 * 1024 * 1024;
|
|
109
|
+
var CurrentRoomStopped = class extends Error {
|
|
110
|
+
};
|
|
111
|
+
function currentRoomHost(attachment, ownerInstanceId) {
|
|
112
|
+
return async (request, timeoutMs, signal) => {
|
|
113
|
+
const input = currentRoomHostRequestSchema.parse({
|
|
114
|
+
targetId: attachment.host.targetId,
|
|
115
|
+
ownerInstanceId,
|
|
116
|
+
request
|
|
117
|
+
});
|
|
118
|
+
const deadline = AbortSignal.timeout(timeoutMs);
|
|
119
|
+
let response;
|
|
120
|
+
try {
|
|
121
|
+
response = await fetch(attachment.host.endpoint, {
|
|
122
|
+
method: "POST",
|
|
123
|
+
headers: { "content-type": "application/json" },
|
|
124
|
+
body: JSON.stringify(input),
|
|
125
|
+
signal: signal ? AbortSignal.any([signal, deadline]) : deadline,
|
|
126
|
+
redirect: "error",
|
|
127
|
+
credentials: "omit"
|
|
128
|
+
});
|
|
129
|
+
} catch {
|
|
130
|
+
throw new Error(
|
|
131
|
+
"current_host_unavailable: The creator's editor could not be reached."
|
|
132
|
+
);
|
|
133
|
+
}
|
|
134
|
+
if (!response.ok) {
|
|
135
|
+
if ([401, 403, 409, 410].includes(response.status)) {
|
|
136
|
+
let message = "The creator's room is no longer granted.";
|
|
137
|
+
try {
|
|
138
|
+
if (response.body) {
|
|
139
|
+
const body = JSON.parse(await readBoundedText(response.body, 4096));
|
|
140
|
+
if (typeof body?.error === "string" && body.error.trim())
|
|
141
|
+
message = body.error.trim().slice(0, 300);
|
|
142
|
+
}
|
|
143
|
+
} catch {
|
|
144
|
+
}
|
|
145
|
+
if (response.status === 410) throw new CurrentRoomStopped(message);
|
|
146
|
+
throw new Error(`runtime_replaced: ${message}`);
|
|
147
|
+
}
|
|
148
|
+
await response.body?.cancel();
|
|
149
|
+
throw new Error(
|
|
150
|
+
`current_host_unavailable: The editor returned HTTP ${response.status}.`
|
|
151
|
+
);
|
|
152
|
+
}
|
|
153
|
+
if (!response.body)
|
|
154
|
+
throw new Error("current_host_invalid: Empty host response.");
|
|
155
|
+
let source;
|
|
156
|
+
try {
|
|
157
|
+
source = await readBoundedText(response.body, MAXIMUM_RESPONSE_BYTES);
|
|
158
|
+
} catch (error) {
|
|
159
|
+
throw new Error(
|
|
160
|
+
error instanceof BodyLimitError ? "current_host_limit: The creator's host exceeded its transfer budget." : "current_host_unavailable: Host response transfer failed."
|
|
161
|
+
);
|
|
162
|
+
}
|
|
163
|
+
let result;
|
|
164
|
+
try {
|
|
165
|
+
result = hostAgentResultMessageSchema.shape.result.parse(
|
|
166
|
+
JSON.parse(source)
|
|
167
|
+
);
|
|
168
|
+
} catch {
|
|
169
|
+
throw new Error(
|
|
170
|
+
"current_host_invalid: The creator's host response failed validation."
|
|
171
|
+
);
|
|
172
|
+
}
|
|
173
|
+
if (!result.ok) throw new Error(result.error);
|
|
174
|
+
const answer = result.response;
|
|
175
|
+
if (answer.operation !== request.operation)
|
|
176
|
+
throw new Error(
|
|
177
|
+
"current_host_invalid: The creator's host answered another request."
|
|
178
|
+
);
|
|
179
|
+
if (answer.operation === "observe" && request.operation === "observe" && (answer.observation.identity.roomId !== request.roomId || answer.observation.controllerId !== request.controllerId || answer.observation.scope !== request.scope || request.expected && Object.entries(request.expected).some(
|
|
180
|
+
([key, value]) => Reflect.get(answer.observation.identity, key) !== value
|
|
181
|
+
)))
|
|
182
|
+
throw new Error(
|
|
183
|
+
"runtime_replaced: The observation belongs to another runtime or player."
|
|
184
|
+
);
|
|
185
|
+
return answer;
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
function currentRoomSeatClaimer(attachment, ownerInstanceId) {
|
|
189
|
+
return async (claim, timeoutMs) => {
|
|
190
|
+
const body = currentRoomSeatClaimSchema.parse({
|
|
191
|
+
targetId: attachment.host.targetId,
|
|
192
|
+
ownerInstanceId,
|
|
193
|
+
claim
|
|
194
|
+
});
|
|
195
|
+
let response;
|
|
196
|
+
try {
|
|
197
|
+
response = await fetch(attachment.host.endpoint, {
|
|
198
|
+
method: "POST",
|
|
199
|
+
headers: { "content-type": "application/json" },
|
|
200
|
+
body: JSON.stringify(body),
|
|
201
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
202
|
+
redirect: "error",
|
|
203
|
+
credentials: "omit"
|
|
204
|
+
});
|
|
205
|
+
} catch {
|
|
206
|
+
throw new Error(
|
|
207
|
+
"current_host_unavailable: The creator's editor could not be reached."
|
|
208
|
+
);
|
|
209
|
+
}
|
|
210
|
+
if (response.ok) {
|
|
211
|
+
await response.body?.cancel();
|
|
212
|
+
return;
|
|
213
|
+
}
|
|
214
|
+
let message = `The editor refused the seat (HTTP ${response.status}).`;
|
|
215
|
+
try {
|
|
216
|
+
if (response.body) {
|
|
217
|
+
const refusal = JSON.parse(await readBoundedText(response.body, 4096));
|
|
218
|
+
if (typeof refusal?.error === "string" && refusal.error.trim())
|
|
219
|
+
message = refusal.error.trim().slice(0, 300);
|
|
220
|
+
}
|
|
221
|
+
} catch {
|
|
222
|
+
}
|
|
223
|
+
if (response.status === 410) throw new CurrentRoomStopped(message);
|
|
224
|
+
throw new Error(`current_room_scope: ${message}`);
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
// src/game-run-record.ts
|
|
229
|
+
import { constants } from "fs";
|
|
230
|
+
import { lstat, open, realpath } from "fs/promises";
|
|
231
|
+
import path from "path";
|
|
232
|
+
async function readGameRunArtifact(projectDir, runId, name, maximumBytes) {
|
|
233
|
+
gameRunAddressSchema.parse({ runId });
|
|
234
|
+
const filename = path.join(
|
|
235
|
+
await realpath(projectDir),
|
|
236
|
+
".airjam",
|
|
237
|
+
"artifacts",
|
|
238
|
+
"runs",
|
|
239
|
+
runId,
|
|
240
|
+
name
|
|
241
|
+
);
|
|
242
|
+
const file = await open(
|
|
243
|
+
filename,
|
|
244
|
+
constants.O_RDONLY | constants.O_NOFOLLOW
|
|
245
|
+
).catch((error) => {
|
|
246
|
+
if (error.code === "ENOENT") return null;
|
|
247
|
+
throw error;
|
|
248
|
+
});
|
|
249
|
+
if (!file) return null;
|
|
250
|
+
try {
|
|
251
|
+
const stat = await file.stat();
|
|
252
|
+
if (!stat.isFile() || stat.size > maximumBytes)
|
|
253
|
+
throw new Error(
|
|
254
|
+
"run_receipt_invalid: Retained record exceeds its limit."
|
|
255
|
+
);
|
|
256
|
+
const validatePath = async () => {
|
|
257
|
+
const current = await lstat(filename);
|
|
258
|
+
if (await realpath(filename) !== filename)
|
|
259
|
+
throw new Error("run_receipt_invalid: Retained record path changed.");
|
|
260
|
+
if (current.ino !== stat.ino || current.dev !== stat.dev) {
|
|
261
|
+
if (name === "record.json" && current.isFile()) return false;
|
|
262
|
+
throw new Error("run_receipt_invalid: Retained record path changed.");
|
|
263
|
+
}
|
|
264
|
+
return true;
|
|
265
|
+
};
|
|
266
|
+
if (!await validatePath()) return null;
|
|
267
|
+
const buffer = Buffer.alloc(stat.size + 1);
|
|
268
|
+
let size = 0;
|
|
269
|
+
while (size < buffer.length) {
|
|
270
|
+
const { bytesRead } = await file.read(buffer, size, buffer.length - size);
|
|
271
|
+
if (bytesRead === 0) break;
|
|
272
|
+
size += bytesRead;
|
|
273
|
+
}
|
|
274
|
+
if (!await validatePath()) return null;
|
|
275
|
+
if (size !== stat.size)
|
|
276
|
+
throw new Error(
|
|
277
|
+
"run_receipt_invalid: Retained record changed during read."
|
|
278
|
+
);
|
|
279
|
+
return buffer.subarray(0, size);
|
|
280
|
+
} finally {
|
|
281
|
+
await file.close();
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
async function readTerminalGameRun(projectDir, runId) {
|
|
285
|
+
const bytes = await readGameRunArtifact(
|
|
286
|
+
projectDir,
|
|
287
|
+
runId,
|
|
288
|
+
"record.json",
|
|
289
|
+
1048576
|
|
290
|
+
);
|
|
291
|
+
if (!bytes) return null;
|
|
292
|
+
const record = gameRunRecordSchema.parse(JSON.parse(bytes.toString("utf8")));
|
|
293
|
+
if (record.runId !== runId || record.request.runId !== runId || record.request.cwd !== projectDir)
|
|
294
|
+
throw new Error("run_receipt_invalid: Retained record identity differs.");
|
|
295
|
+
if (record.state !== "ended") return null;
|
|
296
|
+
if (!record.endedAt || !record.end)
|
|
297
|
+
throw new Error("run_receipt_invalid: Terminal receipt is incomplete.");
|
|
298
|
+
return record;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
// src/game-run-owner.ts
|
|
302
|
+
import { PARTICIPANT_CONTROL_DEADLINE_MS } from "@air-jam/sdk/protocol";
|
|
303
|
+
import {
|
|
304
|
+
clipFailureReason,
|
|
305
|
+
describeHostRuntimeFault,
|
|
306
|
+
readHostClip,
|
|
307
|
+
readHostInputLog,
|
|
308
|
+
sameHostRuntimeIdentity
|
|
309
|
+
} from "@air-jam/sdk/runtime-control";
|
|
310
|
+
import { createHash as createHash2, randomUUID as randomUUID3 } from "crypto";
|
|
311
|
+
import {
|
|
312
|
+
mkdir,
|
|
313
|
+
open as open2,
|
|
314
|
+
readFile as readFile2,
|
|
315
|
+
rename
|
|
316
|
+
} from "fs/promises";
|
|
317
|
+
import path3 from "path";
|
|
318
|
+
import { setTimeout as delay } from "timers/promises";
|
|
319
|
+
|
|
320
|
+
// src/headless-room.ts
|
|
321
|
+
import { randomUUID } from "crypto";
|
|
322
|
+
|
|
323
|
+
// src/helper-channel.ts
|
|
324
|
+
import { closeSync, openSync, writeSync } from "fs";
|
|
325
|
+
var environmentKeys = [
|
|
326
|
+
"PATH",
|
|
327
|
+
"HOME",
|
|
328
|
+
"TMPDIR",
|
|
329
|
+
"TEMP",
|
|
330
|
+
"TMP",
|
|
331
|
+
"NODE_EXTRA_CA_CERTS",
|
|
332
|
+
"HTTP_PROXY",
|
|
333
|
+
"HTTPS_PROXY",
|
|
334
|
+
"ALL_PROXY",
|
|
335
|
+
"NO_PROXY",
|
|
336
|
+
"http_proxy",
|
|
337
|
+
"https_proxy",
|
|
338
|
+
"all_proxy",
|
|
339
|
+
"no_proxy"
|
|
340
|
+
];
|
|
341
|
+
var LOG_BYTES = 1e6;
|
|
342
|
+
var STARTUP_MS = 1e4;
|
|
343
|
+
async function startHelperChannel({
|
|
344
|
+
name,
|
|
345
|
+
helper,
|
|
346
|
+
rootDir,
|
|
347
|
+
toolingRootDir,
|
|
348
|
+
onScope,
|
|
349
|
+
startupSignal,
|
|
350
|
+
logPath,
|
|
351
|
+
maxBytes,
|
|
352
|
+
requestSchema,
|
|
353
|
+
responseSchema
|
|
354
|
+
}) {
|
|
355
|
+
startupSignal?.throwIfAborted();
|
|
356
|
+
const script = toolingRootDir ? resolveProjectDevtoolsHelperScript(toolingRootDir, helper) : resolveDevtoolsHelperScript(helper);
|
|
357
|
+
const logDescriptor = openSync(logPath, "w", 384);
|
|
358
|
+
const child = await spawnScopedProcess(resolveDevtoolsHelperArgs(script), {
|
|
359
|
+
cwd: rootDir,
|
|
360
|
+
onScope,
|
|
361
|
+
startupSignal,
|
|
362
|
+
env: nodeProcessEnvironment(environmentKeys)
|
|
363
|
+
}).catch((error) => {
|
|
364
|
+
closeSync(logDescriptor);
|
|
365
|
+
if (startupSignal?.aborted)
|
|
366
|
+
throw new Error(`${name}_stopped`, { cause: error });
|
|
367
|
+
throw error;
|
|
368
|
+
});
|
|
369
|
+
let failure;
|
|
370
|
+
let ready = false;
|
|
371
|
+
let pending;
|
|
372
|
+
let stopping;
|
|
373
|
+
let resolveReady;
|
|
374
|
+
let rejectReady;
|
|
375
|
+
const boot = new Promise((resolve, reject) => {
|
|
376
|
+
resolveReady = resolve;
|
|
377
|
+
rejectReady = reject;
|
|
378
|
+
});
|
|
379
|
+
const fail = (error) => {
|
|
380
|
+
failure ??= error;
|
|
381
|
+
rejectReady(error);
|
|
382
|
+
if (pending) {
|
|
383
|
+
clearTimeout(pending.timer);
|
|
384
|
+
pending.reject(error);
|
|
385
|
+
pending = void 0;
|
|
386
|
+
}
|
|
387
|
+
};
|
|
388
|
+
child.on("error", fail);
|
|
389
|
+
child.once("exit", () => {
|
|
390
|
+
fail(new Error(`${name}_exited: The ${name} process is unavailable.`));
|
|
391
|
+
});
|
|
392
|
+
let logBytes = 0;
|
|
393
|
+
const log = (chunk) => {
|
|
394
|
+
const remaining = LOG_BYTES - logBytes;
|
|
395
|
+
if (remaining > 0) {
|
|
396
|
+
const bounded = chunk.subarray(0, remaining);
|
|
397
|
+
try {
|
|
398
|
+
let offset = 0;
|
|
399
|
+
while (offset < bounded.length)
|
|
400
|
+
offset += writeSync(logDescriptor, bounded.subarray(offset));
|
|
401
|
+
} catch (error) {
|
|
402
|
+
fail(error instanceof Error ? error : new Error(String(error)));
|
|
403
|
+
child.kill("SIGKILL");
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
logBytes += chunk.length;
|
|
407
|
+
if (logBytes > LOG_BYTES) {
|
|
408
|
+
fail(
|
|
409
|
+
new Error(
|
|
410
|
+
`${name}_log_limit: The ${name} process exceeded its 1 MB diagnostic log budget.`
|
|
411
|
+
)
|
|
412
|
+
);
|
|
413
|
+
child.kill("SIGKILL");
|
|
414
|
+
}
|
|
415
|
+
};
|
|
416
|
+
child.stdout?.on("data", log);
|
|
417
|
+
child.stderr?.on("data", log);
|
|
418
|
+
child.on("message", (message) => {
|
|
419
|
+
if (message === 0) return;
|
|
420
|
+
if (processScopeAdmissionSchema.safeParse(message).success) return;
|
|
421
|
+
try {
|
|
422
|
+
if (Buffer.byteLength(JSON.stringify(message)) > maxBytes)
|
|
423
|
+
throw new Error(`${name}_protocol: Oversized response.`);
|
|
424
|
+
const result = responseSchema.parse(message);
|
|
425
|
+
if (result.kind === "ready") {
|
|
426
|
+
if (ready) throw new Error(`${name}_protocol: Duplicate startup.`);
|
|
427
|
+
ready = true;
|
|
428
|
+
resolveReady();
|
|
429
|
+
return;
|
|
430
|
+
}
|
|
431
|
+
if (!pending || result.id !== pending.id)
|
|
432
|
+
throw new Error(`${name}_protocol: Unexpected response ID.`);
|
|
433
|
+
const request2 = pending;
|
|
434
|
+
pending = void 0;
|
|
435
|
+
clearTimeout(request2.timer);
|
|
436
|
+
if (!request2.expired) request2.resolve(result);
|
|
437
|
+
} catch (error) {
|
|
438
|
+
fail(error instanceof Error ? error : new Error(String(error)));
|
|
439
|
+
child.kill("SIGKILL");
|
|
440
|
+
}
|
|
441
|
+
});
|
|
442
|
+
const request = (input, timeoutMs) => {
|
|
443
|
+
if (failure) return Promise.reject(failure);
|
|
444
|
+
if (pending)
|
|
445
|
+
return Promise.reject(
|
|
446
|
+
new Error(`${name}_busy: The previous request has not returned.`)
|
|
447
|
+
);
|
|
448
|
+
const parsed = requestSchema.parse(input);
|
|
449
|
+
if (Buffer.byteLength(JSON.stringify(parsed)) > maxBytes)
|
|
450
|
+
return Promise.reject(
|
|
451
|
+
new Error(`${name}_protocol: Request exceeds its byte budget.`)
|
|
452
|
+
);
|
|
453
|
+
return new Promise((resolve, reject) => {
|
|
454
|
+
const timer = setTimeout(() => {
|
|
455
|
+
if (pending?.id !== parsed.id) return;
|
|
456
|
+
pending.expired = true;
|
|
457
|
+
reject(new Error(`${name}_timeout: Request exceeded its deadline.`));
|
|
458
|
+
}, timeoutMs);
|
|
459
|
+
pending = { id: parsed.id, resolve, reject, timer, expired: false };
|
|
460
|
+
child.send(parsed, (error) => {
|
|
461
|
+
if (error) fail(error);
|
|
462
|
+
});
|
|
463
|
+
});
|
|
464
|
+
};
|
|
465
|
+
const stop = () => stopping ??= (async () => {
|
|
466
|
+
startupSignal?.removeEventListener("abort", aborted);
|
|
467
|
+
fail(new Error(`${name}_stopped`));
|
|
468
|
+
try {
|
|
469
|
+
await closeScopedProcess(child);
|
|
470
|
+
} finally {
|
|
471
|
+
child.stdout?.destroy();
|
|
472
|
+
child.stderr?.destroy();
|
|
473
|
+
closeSync(logDescriptor);
|
|
474
|
+
}
|
|
475
|
+
})();
|
|
476
|
+
const aborted = () => {
|
|
477
|
+
void stop().catch(() => void 0);
|
|
478
|
+
};
|
|
479
|
+
startupSignal?.addEventListener("abort", aborted, { once: true });
|
|
480
|
+
const bootTimeout = setTimeout(
|
|
481
|
+
() => fail(new Error(`${name}_startup_timeout`)),
|
|
482
|
+
STARTUP_MS
|
|
483
|
+
);
|
|
484
|
+
try {
|
|
485
|
+
if (startupSignal?.aborted) aborted();
|
|
486
|
+
await boot;
|
|
487
|
+
} catch (error) {
|
|
488
|
+
startupSignal?.removeEventListener("abort", aborted);
|
|
489
|
+
return closeAfterProcessFailure(stop, error);
|
|
490
|
+
} finally {
|
|
491
|
+
clearTimeout(bootTimeout);
|
|
492
|
+
}
|
|
493
|
+
return {
|
|
494
|
+
request,
|
|
495
|
+
busy: () => pending !== void 0,
|
|
496
|
+
started: () => startupSignal?.removeEventListener("abort", aborted),
|
|
497
|
+
stop
|
|
498
|
+
};
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
// src/headless-room.ts
|
|
502
|
+
var REQUEST_TIMEOUT_MS = 5e3;
|
|
503
|
+
var REPLAY_TIMEOUT_MS = 12e4;
|
|
504
|
+
async function startHeadlessRoom({
|
|
505
|
+
rootDir,
|
|
506
|
+
toolingRootDir,
|
|
507
|
+
configPath,
|
|
508
|
+
seed,
|
|
509
|
+
settings,
|
|
510
|
+
logPath,
|
|
511
|
+
onScope,
|
|
512
|
+
startupSignal
|
|
513
|
+
}) {
|
|
514
|
+
const channel = await startHelperChannel({
|
|
515
|
+
name: "room",
|
|
516
|
+
helper: "run-headless-room.ts",
|
|
517
|
+
rootDir,
|
|
518
|
+
toolingRootDir,
|
|
519
|
+
onScope,
|
|
520
|
+
startupSignal,
|
|
521
|
+
logPath,
|
|
522
|
+
maxBytes: HEADLESS_ROOM_IPC_MAX_BYTES,
|
|
523
|
+
requestSchema: headlessRoomRequestSchema,
|
|
524
|
+
responseSchema: headlessRoomResponseSchema
|
|
525
|
+
});
|
|
526
|
+
let queue = Promise.resolve();
|
|
527
|
+
const request = (input, expected, timeoutMs = REQUEST_TIMEOUT_MS) => {
|
|
528
|
+
const result = queue.then(async () => {
|
|
529
|
+
const response = await channel.request(input, timeoutMs);
|
|
530
|
+
if (response.kind === "error") throw new Error(response.message);
|
|
531
|
+
if (response.kind !== expected)
|
|
532
|
+
throw new Error(`room_protocol: Expected ${expected}.`);
|
|
533
|
+
return response;
|
|
534
|
+
});
|
|
535
|
+
queue = result.catch(() => void 0);
|
|
536
|
+
return result;
|
|
537
|
+
};
|
|
538
|
+
try {
|
|
539
|
+
const opened = await request(
|
|
540
|
+
{ kind: "initialize", id: randomUUID(), configPath, seed, settings },
|
|
541
|
+
"initialized",
|
|
542
|
+
1e4
|
|
543
|
+
);
|
|
544
|
+
let nowMs = opened.nowMs;
|
|
545
|
+
return {
|
|
546
|
+
gameId: opened.gameId,
|
|
547
|
+
roomId: opened.roomId,
|
|
548
|
+
controllerJoinUrl: opened.controllerJoinUrl,
|
|
549
|
+
requestHost: async (hostRequest, timeoutMs, signal) => {
|
|
550
|
+
signal?.throwIfAborted();
|
|
551
|
+
const answered = await request(
|
|
552
|
+
{ kind: "agent", id: randomUUID(), request: hostRequest },
|
|
553
|
+
"agent",
|
|
554
|
+
timeoutMs
|
|
555
|
+
);
|
|
556
|
+
return answered.response;
|
|
557
|
+
},
|
|
558
|
+
clock: {
|
|
559
|
+
now: () => nowMs,
|
|
560
|
+
wait: async (ms, signal) => {
|
|
561
|
+
let remaining = ms;
|
|
562
|
+
while (remaining > 0) {
|
|
563
|
+
signal?.throwIfAborted();
|
|
564
|
+
const step = Math.min(remaining, HEADLESS_ROOM_MAX_ADVANCE_MS);
|
|
565
|
+
nowMs = (await request(
|
|
566
|
+
{ kind: "advance", id: randomUUID(), ms: step },
|
|
567
|
+
"advanced"
|
|
568
|
+
)).nowMs;
|
|
569
|
+
remaining -= step;
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
},
|
|
573
|
+
saveInputLog: opened.recordsInputLog ? async (logPath2) => {
|
|
574
|
+
const { sha256, ticks, stepMs, entries, full } = await request(
|
|
575
|
+
{ kind: "saveInputLog", id: randomUUID(), path: logPath2 },
|
|
576
|
+
"savedInputLog"
|
|
577
|
+
);
|
|
578
|
+
return { sha256, ticks, stepMs, entries, full };
|
|
579
|
+
} : null,
|
|
580
|
+
stop: channel.stop
|
|
581
|
+
};
|
|
582
|
+
} catch (error) {
|
|
583
|
+
return closeAfterProcessFailure(channel.stop, error);
|
|
584
|
+
} finally {
|
|
585
|
+
channel.started();
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
async function replayInputLog({
|
|
589
|
+
rootDir,
|
|
590
|
+
toolingRootDir,
|
|
591
|
+
configPath,
|
|
592
|
+
inputLogPath,
|
|
593
|
+
logPath
|
|
594
|
+
}) {
|
|
595
|
+
const channel = await startHelperChannel({
|
|
596
|
+
name: "replay",
|
|
597
|
+
helper: "run-headless-room.ts",
|
|
598
|
+
rootDir,
|
|
599
|
+
toolingRootDir,
|
|
600
|
+
logPath,
|
|
601
|
+
maxBytes: HEADLESS_ROOM_IPC_MAX_BYTES,
|
|
602
|
+
requestSchema: headlessRoomRequestSchema,
|
|
603
|
+
responseSchema: headlessRoomResponseSchema
|
|
604
|
+
});
|
|
605
|
+
try {
|
|
606
|
+
const replayed = await channel.request(
|
|
607
|
+
{
|
|
608
|
+
kind: "replay",
|
|
609
|
+
id: randomUUID(),
|
|
610
|
+
configPath,
|
|
611
|
+
logPath: inputLogPath
|
|
612
|
+
},
|
|
613
|
+
REPLAY_TIMEOUT_MS
|
|
614
|
+
);
|
|
615
|
+
if (replayed.kind === "error") throw new Error(replayed.message);
|
|
616
|
+
if (replayed.kind !== "replayed")
|
|
617
|
+
throw new Error("room_protocol: Expected replayed.");
|
|
618
|
+
return {
|
|
619
|
+
gameId: replayed.gameId,
|
|
620
|
+
roomId: replayed.roomId,
|
|
621
|
+
ticks: replayed.ticks,
|
|
622
|
+
requestHost: async (hostRequest, timeoutMs, signal) => {
|
|
623
|
+
signal?.throwIfAborted();
|
|
624
|
+
const answered = await channel.request(
|
|
625
|
+
{ kind: "agent", id: randomUUID(), request: hostRequest },
|
|
626
|
+
timeoutMs
|
|
627
|
+
);
|
|
628
|
+
if (answered.kind === "error") throw new Error(answered.message);
|
|
629
|
+
if (answered.kind !== "agent")
|
|
630
|
+
throw new Error("room_protocol: Expected agent.");
|
|
631
|
+
return answered.response;
|
|
632
|
+
},
|
|
633
|
+
stop: channel.stop
|
|
634
|
+
};
|
|
635
|
+
} catch (error) {
|
|
636
|
+
return closeAfterProcessFailure(channel.stop, error);
|
|
637
|
+
} finally {
|
|
638
|
+
channel.started();
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
// src/policy-artifacts.ts
|
|
643
|
+
import { createHash } from "crypto";
|
|
644
|
+
import { constants as constants2, createReadStream } from "fs";
|
|
645
|
+
import { access, lstat as lstat2, readFile, readdir, realpath as realpath2 } from "fs/promises";
|
|
646
|
+
import path2 from "path";
|
|
647
|
+
async function assertProtectedEntry(target, directory) {
|
|
648
|
+
const information = await lstat2(target);
|
|
649
|
+
if (directory ? !information.isDirectory() : !information.isFile())
|
|
650
|
+
throw new Error(
|
|
651
|
+
"policy_artifact_invalid: Expected a regular artifact entry, without symlinks."
|
|
652
|
+
);
|
|
653
|
+
if (!process.getuid || process.getuid() === 0 || information.uid === process.getuid())
|
|
654
|
+
throw new Error(
|
|
655
|
+
"policy_artifact_writable: Artifacts require an independent filesystem owner and a non-root policy."
|
|
656
|
+
);
|
|
657
|
+
try {
|
|
658
|
+
await access(target, constants2.W_OK);
|
|
659
|
+
} catch (error) {
|
|
660
|
+
if (error instanceof Error && "code" in error && error.code === "EACCES")
|
|
661
|
+
return;
|
|
662
|
+
throw error;
|
|
663
|
+
}
|
|
664
|
+
throw new Error(
|
|
665
|
+
"policy_artifact_writable: Policy artifacts must be read-only to the workload."
|
|
666
|
+
);
|
|
667
|
+
}
|
|
668
|
+
async function verifyPolicyArtifacts(options) {
|
|
669
|
+
const started = performance.now();
|
|
670
|
+
options.signal?.throwIfAborted();
|
|
671
|
+
if (!options.artifactRootDir || !path2.isAbsolute(options.artifactRootDir))
|
|
672
|
+
throw new Error(
|
|
673
|
+
"policy_artifacts_missing: Configure an absolute AIRJAM_TEST_ARTIFACTS_DIR for this policy."
|
|
674
|
+
);
|
|
675
|
+
const project = await realpath2(options.projectDir);
|
|
676
|
+
const manifestPath = await realpath2(options.manifestPath);
|
|
677
|
+
const relative = path2.relative(project, manifestPath);
|
|
678
|
+
if (!relative || relative === ".." || relative.startsWith(`..${path2.sep}`) || path2.isAbsolute(relative))
|
|
679
|
+
throw new Error(
|
|
680
|
+
"policy_artifact_invalid: The manifest must be pinned inside the project source."
|
|
681
|
+
);
|
|
682
|
+
if ((await lstat2(manifestPath)).size > 64 * 1024)
|
|
683
|
+
throw new Error("policy_artifact_invalid: Manifest exceeds 64 KiB.");
|
|
684
|
+
const content = await readFile(manifestPath, { signal: options.signal });
|
|
685
|
+
const manifest = policyArtifactManifestSchema.parse(
|
|
686
|
+
JSON.parse(content.toString("utf8"))
|
|
687
|
+
);
|
|
688
|
+
const manifestSha256 = createHash("sha256").update(content).digest("hex");
|
|
689
|
+
const directory = path2.join(options.artifactRootDir, manifestSha256);
|
|
690
|
+
const directories = /* @__PURE__ */ new Set();
|
|
691
|
+
let ancestor = directory;
|
|
692
|
+
while (true) {
|
|
693
|
+
directories.add(ancestor);
|
|
694
|
+
const parent = path2.dirname(ancestor);
|
|
695
|
+
if (parent === ancestor) break;
|
|
696
|
+
ancestor = parent;
|
|
697
|
+
}
|
|
698
|
+
for (const file of manifest.files) {
|
|
699
|
+
let parent = path2.dirname(path2.join(directory, file.path));
|
|
700
|
+
while (parent !== directory) {
|
|
701
|
+
directories.add(parent);
|
|
702
|
+
parent = path2.dirname(parent);
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
for (const parent of directories) await assertProtectedEntry(parent, true);
|
|
706
|
+
const expected = new Set(manifest.files.map((file) => file.path));
|
|
707
|
+
const pending = [""];
|
|
708
|
+
for (const relative2 of pending) {
|
|
709
|
+
options.signal?.throwIfAborted();
|
|
710
|
+
for (const entry of await readdir(path2.join(directory, relative2), {
|
|
711
|
+
withFileTypes: true
|
|
712
|
+
})) {
|
|
713
|
+
const name = relative2 ? `${relative2}/${entry.name}` : entry.name;
|
|
714
|
+
if (entry.isDirectory() && [...expected].some((file) => file.startsWith(name + "/")))
|
|
715
|
+
pending.push(name);
|
|
716
|
+
else if (!entry.isFile() || !expected.has(name))
|
|
717
|
+
throw new Error(
|
|
718
|
+
`policy_artifact_invalid: Unlisted artifact entry: ${name}.`
|
|
719
|
+
);
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
for (const file of manifest.files) {
|
|
723
|
+
options.signal?.throwIfAborted();
|
|
724
|
+
const target = path2.join(directory, file.path);
|
|
725
|
+
await assertProtectedEntry(target, false);
|
|
726
|
+
if ((await lstat2(target)).size !== file.bytes)
|
|
727
|
+
throw new Error(
|
|
728
|
+
`policy_artifact_invalid: Size differs for ${file.path}.`
|
|
729
|
+
);
|
|
730
|
+
const hash = createHash("sha256");
|
|
731
|
+
for await (const chunk of createReadStream(target, {
|
|
732
|
+
signal: options.signal
|
|
733
|
+
}))
|
|
734
|
+
hash.update(chunk);
|
|
735
|
+
if (hash.digest("hex") !== file.sha256)
|
|
736
|
+
throw new Error(
|
|
737
|
+
`policy_artifact_invalid: Digest differs for ${file.path}.`
|
|
738
|
+
);
|
|
739
|
+
}
|
|
740
|
+
return {
|
|
741
|
+
directory,
|
|
742
|
+
receipt: policyArtifactReceiptSchema.parse({
|
|
743
|
+
manifestSha256,
|
|
744
|
+
manifest,
|
|
745
|
+
verifyMs: performance.now() - started
|
|
746
|
+
})
|
|
747
|
+
};
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
// src/test-profile-process.ts
|
|
751
|
+
import { randomUUID as randomUUID2 } from "crypto";
|
|
752
|
+
async function startTestProfileProcess({
|
|
753
|
+
rootDir,
|
|
754
|
+
configPath,
|
|
755
|
+
profileId,
|
|
756
|
+
runKind = "test",
|
|
757
|
+
policyId,
|
|
758
|
+
seed,
|
|
759
|
+
logPath,
|
|
760
|
+
role,
|
|
761
|
+
toolingRootDir,
|
|
762
|
+
onScope,
|
|
763
|
+
startupSignal,
|
|
764
|
+
initializationDeadline,
|
|
765
|
+
artifacts
|
|
766
|
+
}) {
|
|
767
|
+
startupSignal?.throwIfAborted();
|
|
768
|
+
if (role !== "policy" && initializationDeadline !== void 0)
|
|
769
|
+
throw new Error("Only a policy can use the run's initialization deadline.");
|
|
770
|
+
if (role !== "policy" && artifacts !== void 0)
|
|
771
|
+
throw new Error("Only a policy can receive model artifacts.");
|
|
772
|
+
const channel = await startHelperChannel({
|
|
773
|
+
name: "policy",
|
|
774
|
+
helper: "run-test-profile.ts",
|
|
775
|
+
rootDir,
|
|
776
|
+
toolingRootDir,
|
|
777
|
+
onScope,
|
|
778
|
+
startupSignal,
|
|
779
|
+
logPath,
|
|
780
|
+
maxBytes: TEST_PROFILE_IPC_MAX_BYTES,
|
|
781
|
+
requestSchema: testProfileRequestSchema,
|
|
782
|
+
responseSchema: testProfileResponseSchema
|
|
783
|
+
});
|
|
784
|
+
const request = (input, timeoutMs) => channel.request(input, timeoutMs);
|
|
785
|
+
try {
|
|
786
|
+
const initialized = await request(
|
|
787
|
+
{
|
|
788
|
+
kind: "initialize",
|
|
789
|
+
id: randomUUID2(),
|
|
790
|
+
rootDir,
|
|
791
|
+
configPath,
|
|
792
|
+
profileId,
|
|
793
|
+
runKind,
|
|
794
|
+
policyId,
|
|
795
|
+
seed,
|
|
796
|
+
role,
|
|
797
|
+
...artifacts ? { artifacts } : {}
|
|
798
|
+
},
|
|
799
|
+
initializationDeadline === void 0 ? 1e4 : Math.max(1, initializationDeadline - performance.now())
|
|
800
|
+
);
|
|
801
|
+
if (initialized.kind !== "initialized")
|
|
802
|
+
throw new Error(
|
|
803
|
+
initialized.kind === "error" ? initialized.message : "Invalid policy initialization response."
|
|
804
|
+
);
|
|
805
|
+
return {
|
|
806
|
+
profiles: initialized.profiles,
|
|
807
|
+
preparation: initialized.preparation,
|
|
808
|
+
busy: channel.busy,
|
|
809
|
+
async decide(step, timeoutMs) {
|
|
810
|
+
if (role !== "policy")
|
|
811
|
+
throw new Error("Only a policy process can decide.");
|
|
812
|
+
const result = await request(
|
|
813
|
+
{ kind: "decide", id: randomUUID2(), step },
|
|
814
|
+
timeoutMs
|
|
815
|
+
);
|
|
816
|
+
if (result.kind !== "decision")
|
|
817
|
+
throw new Error(
|
|
818
|
+
result.kind === "error" ? result.message : "Invalid policy decision response."
|
|
819
|
+
);
|
|
820
|
+
return result.decision;
|
|
821
|
+
},
|
|
822
|
+
async evaluate(sample, timeoutMs) {
|
|
823
|
+
if (role !== "evaluator")
|
|
824
|
+
throw new Error("Only an evaluator process can judge.");
|
|
825
|
+
const result = await request(
|
|
826
|
+
{ kind: "evaluate", id: randomUUID2(), sample },
|
|
827
|
+
timeoutMs
|
|
828
|
+
);
|
|
829
|
+
if (result.kind !== "evaluation")
|
|
830
|
+
throw new Error(
|
|
831
|
+
result.kind === "error" ? result.message : "Invalid scenario evaluation response."
|
|
832
|
+
);
|
|
833
|
+
return result.verdict;
|
|
834
|
+
},
|
|
835
|
+
stop: channel.stop
|
|
836
|
+
};
|
|
837
|
+
} catch (error) {
|
|
838
|
+
return closeAfterProcessFailure(channel.stop, error);
|
|
839
|
+
} finally {
|
|
840
|
+
channel.started();
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
// src/game-run-owner.ts
|
|
845
|
+
var LOW_CONFIDENCE = 0.6;
|
|
846
|
+
var LOW_CONFIDENCE_STRETCH = 3;
|
|
847
|
+
function agentNickname(index) {
|
|
848
|
+
return `Agent ${index + 1}`;
|
|
849
|
+
}
|
|
850
|
+
function failureReason(message) {
|
|
851
|
+
return /trace_budget/.test(message) ? "trace_budget" : /runtime_replaced|observation_replaced|stale_identity/.test(message) ? "runtime_replaced" : /seat_replaced/.test(message) ? "seat_replaced" : "error";
|
|
852
|
+
}
|
|
853
|
+
var wallClock = {
|
|
854
|
+
now: () => performance.now(),
|
|
855
|
+
wait: (ms, signal) => delay(ms, void 0, { signal })
|
|
856
|
+
};
|
|
857
|
+
var GameRunOwner = class {
|
|
858
|
+
constructor(options) {
|
|
859
|
+
this.options = options;
|
|
860
|
+
this.directory = path3.join(
|
|
861
|
+
options.projectDir,
|
|
862
|
+
".airjam",
|
|
863
|
+
"artifacts",
|
|
864
|
+
"runs"
|
|
865
|
+
);
|
|
866
|
+
}
|
|
867
|
+
runs = /* @__PURE__ */ new Map();
|
|
868
|
+
admissions = /* @__PURE__ */ new Set();
|
|
869
|
+
draining = false;
|
|
870
|
+
stoppingAll;
|
|
871
|
+
directory;
|
|
872
|
+
persist(run) {
|
|
873
|
+
const source = `${JSON.stringify(gameRunRecordSchema.parse(run.record), null, 2)}
|
|
874
|
+
`;
|
|
875
|
+
const pending = run.persistence.then(async () => {
|
|
876
|
+
const temporary = path3.join(run.directory, "record.pending.json");
|
|
877
|
+
await open2(temporary, "w", 384).then(async (file) => {
|
|
878
|
+
try {
|
|
879
|
+
await file.writeFile(source);
|
|
880
|
+
} finally {
|
|
881
|
+
await file.close();
|
|
882
|
+
}
|
|
883
|
+
});
|
|
884
|
+
await rename(temporary, path3.join(run.directory, "record.json"));
|
|
885
|
+
});
|
|
886
|
+
run.persistence = pending.catch(() => void 0);
|
|
887
|
+
return pending;
|
|
888
|
+
}
|
|
889
|
+
trace(run, event, diagnostic = false) {
|
|
890
|
+
const bytes = Buffer.from(
|
|
891
|
+
`${JSON.stringify({ at: (/* @__PURE__ */ new Date()).toISOString(), ...event })}
|
|
892
|
+
`
|
|
893
|
+
);
|
|
894
|
+
const writing = run.tracing.then(async () => {
|
|
895
|
+
const limit = run.abort.signal.aborted ? MAXIMUM_GAME_RUN_TRACE_BYTES : MAXIMUM_GAME_RUN_TRACE_BYTES - 131072;
|
|
896
|
+
if (run.traceBytes + bytes.byteLength > limit) {
|
|
897
|
+
if (diagnostic) return;
|
|
898
|
+
run.traceTruncated = true;
|
|
899
|
+
if (run.abort.signal.aborted) return;
|
|
900
|
+
throw new Error("trace_budget: Run trace reached its byte allowance.");
|
|
901
|
+
}
|
|
902
|
+
if (run.traceFile === null)
|
|
903
|
+
throw new Error("trace_closed: The run trace is already sealed.");
|
|
904
|
+
run.traceFile ??= await open2(
|
|
905
|
+
path3.join(run.directory, "trace.ndjson"),
|
|
906
|
+
"a",
|
|
907
|
+
384
|
|
908
|
+
);
|
|
909
|
+
await run.traceFile.writeFile(bytes);
|
|
910
|
+
run.traceBytes += bytes.byteLength;
|
|
911
|
+
});
|
|
912
|
+
run.tracing = writing.catch(() => void 0);
|
|
913
|
+
return writing;
|
|
914
|
+
}
|
|
915
|
+
copy(record) {
|
|
916
|
+
return structuredClone(record);
|
|
917
|
+
}
|
|
918
|
+
quiescent(run) {
|
|
919
|
+
return run.record.state === "ended" && run.record.cleanup?.processesClosed === true && (!run.session || run.record.cleanup.close?.closed && run.record.cleanup.participantsClosed);
|
|
920
|
+
}
|
|
921
|
+
observeScopes(run) {
|
|
922
|
+
return (close) => {
|
|
923
|
+
run.scopes.push(close);
|
|
924
|
+
if (run.abort.signal.aborted)
|
|
925
|
+
void close().catch((error) => console.error(error));
|
|
926
|
+
};
|
|
927
|
+
}
|
|
928
|
+
prune() {
|
|
929
|
+
const ended = [...this.runs.values()].filter((run) => this.quiescent(run));
|
|
930
|
+
for (const expired of ended.slice(0, Math.max(0, ended.length - 32)))
|
|
931
|
+
this.runs.delete(expired.record.runId);
|
|
932
|
+
}
|
|
933
|
+
async discover(gameId) {
|
|
934
|
+
if (this.draining || this.stoppingAll)
|
|
935
|
+
throw new Error("owner_stopping: Profile discovery admission is closed.");
|
|
936
|
+
if ([...this.runs.values()].some((run) => !this.quiescent(run)))
|
|
937
|
+
throw new Error(
|
|
938
|
+
"run_busy: Wait for the current run to finish before inspecting profiles."
|
|
939
|
+
);
|
|
940
|
+
assertProcessScopesConfirmed();
|
|
941
|
+
const discovery = (async () => {
|
|
942
|
+
const game = await this.game(gameId);
|
|
943
|
+
await mkdir(this.directory, { recursive: true });
|
|
944
|
+
const policy = await startTestProfileProcess({
|
|
945
|
+
rootDir: game.rootDir,
|
|
946
|
+
configPath: game.configPath,
|
|
947
|
+
seed: 0,
|
|
948
|
+
role: "discover",
|
|
949
|
+
logPath: path3.join(this.directory, "discovery.log")
|
|
950
|
+
});
|
|
951
|
+
try {
|
|
952
|
+
return { gameId: game.id, profiles: policy.profiles };
|
|
953
|
+
} finally {
|
|
954
|
+
await policy.stop();
|
|
955
|
+
}
|
|
956
|
+
})();
|
|
957
|
+
this.admissions.add(discovery);
|
|
958
|
+
try {
|
|
959
|
+
return await discovery;
|
|
960
|
+
} finally {
|
|
961
|
+
this.admissions.delete(discovery);
|
|
962
|
+
}
|
|
963
|
+
}
|
|
964
|
+
async game(gameId) {
|
|
965
|
+
const game = await inspectGame({ cwd: this.options.projectDir, gameId });
|
|
966
|
+
if (!game?.configPath)
|
|
967
|
+
throw new Error("Choose a game that publishes an Air Jam config.");
|
|
968
|
+
return { ...game, configPath: game.configPath };
|
|
969
|
+
}
|
|
970
|
+
async start(input, attachment) {
|
|
971
|
+
if (this.draining || this.stoppingAll)
|
|
972
|
+
throw new Error("owner_stopping: Run admission is closed.");
|
|
973
|
+
const request = startGameRunSchema.parse({
|
|
974
|
+
...input,
|
|
975
|
+
cwd: this.options.projectDir
|
|
976
|
+
});
|
|
977
|
+
const existing = this.runs.get(request.runId);
|
|
978
|
+
if (existing) {
|
|
979
|
+
if (JSON.stringify(existing.record.request) !== JSON.stringify(request))
|
|
980
|
+
throw new Error(
|
|
981
|
+
"run_conflict: Run ID was admitted with a different request."
|
|
982
|
+
);
|
|
983
|
+
await existing.admission;
|
|
984
|
+
return this.copy(existing.record);
|
|
985
|
+
}
|
|
986
|
+
if (request.target.kind === "current" && !attachment)
|
|
987
|
+
throw new Error(
|
|
988
|
+
"current_attachment_required: Current-room play requires a delegated editor."
|
|
989
|
+
);
|
|
990
|
+
if (request.target.kind !== "current" && attachment)
|
|
991
|
+
throw new Error(
|
|
992
|
+
"unexpected_attachment: Owned and headless tests do not accept current-room access."
|
|
993
|
+
);
|
|
994
|
+
const current = attachment ? currentRoomAttachmentSchema.parse(attachment) : void 0;
|
|
995
|
+
if ([...this.runs.values()].some((run2) => !this.quiescent(run2)))
|
|
996
|
+
throw new Error(
|
|
997
|
+
"run_busy: This project already has an active or unclosed run."
|
|
998
|
+
);
|
|
999
|
+
assertProcessScopesConfirmed();
|
|
1000
|
+
const priorAdmissions = [...this.admissions];
|
|
1001
|
+
const run = {
|
|
1002
|
+
attachment: current,
|
|
1003
|
+
scopes: [],
|
|
1004
|
+
watches: /* @__PURE__ */ new Map(),
|
|
1005
|
+
record: {
|
|
1006
|
+
version: 1,
|
|
1007
|
+
runId: request.runId,
|
|
1008
|
+
ownerInstanceId: this.options.ownerInstanceId,
|
|
1009
|
+
request,
|
|
1010
|
+
state: "starting",
|
|
1011
|
+
startedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1012
|
+
seats: [],
|
|
1013
|
+
evidence: {
|
|
1014
|
+
observation: null,
|
|
1015
|
+
error: null,
|
|
1016
|
+
clip: {
|
|
1017
|
+
status: "not-captured",
|
|
1018
|
+
reason: request.target.kind === "headless" ? "headless" : "host-unavailable"
|
|
1019
|
+
}
|
|
1020
|
+
},
|
|
1021
|
+
counters: {
|
|
1022
|
+
steps: 0,
|
|
1023
|
+
applied: 0,
|
|
1024
|
+
rejected: 0,
|
|
1025
|
+
unconfirmed: 0,
|
|
1026
|
+
missed: 0
|
|
1027
|
+
}
|
|
1028
|
+
},
|
|
1029
|
+
directory: path3.join(this.directory, request.runId),
|
|
1030
|
+
abort: new AbortController(),
|
|
1031
|
+
seats: [],
|
|
1032
|
+
startupSteps: /* @__PURE__ */ new Set(["the game had not been resolved"]),
|
|
1033
|
+
evaluationCursor: 0,
|
|
1034
|
+
playEvaluationSent: false,
|
|
1035
|
+
receiptIndex: 0,
|
|
1036
|
+
effects: /* @__PURE__ */ new Set(),
|
|
1037
|
+
receipts: [],
|
|
1038
|
+
deadline: performance.now() + (request.kind === "play" ? MAXIMUM_GAME_RUN_MS : request.budget.durationMs),
|
|
1039
|
+
persistence: Promise.resolve(),
|
|
1040
|
+
tracing: Promise.resolve(),
|
|
1041
|
+
traceBytes: 0,
|
|
1042
|
+
traceTruncated: false,
|
|
1043
|
+
finished: new AbortController()
|
|
1044
|
+
};
|
|
1045
|
+
this.runs.set(request.runId, run);
|
|
1046
|
+
const admission = (async () => {
|
|
1047
|
+
await Promise.allSettled(priorAdmissions);
|
|
1048
|
+
assertProcessScopesConfirmed();
|
|
1049
|
+
await mkdir(this.directory, { recursive: true });
|
|
1050
|
+
try {
|
|
1051
|
+
await mkdir(run.directory, { mode: 448 });
|
|
1052
|
+
} catch (error) {
|
|
1053
|
+
if (!(error instanceof Error) || !("code" in error) || error.code !== "EEXIST")
|
|
1054
|
+
throw error;
|
|
1055
|
+
try {
|
|
1056
|
+
await readFile2(path3.join(run.directory, "cancelled.json"));
|
|
1057
|
+
throw new Error(
|
|
1058
|
+
"run_cancelled: This run ID was fenced before admission."
|
|
1059
|
+
);
|
|
1060
|
+
} catch (error2) {
|
|
1061
|
+
if (!(error2 instanceof Error) || !("code" in error2) || error2.code !== "ENOENT")
|
|
1062
|
+
throw error2;
|
|
1063
|
+
}
|
|
1064
|
+
const retained = gameRunRecordSchema.parse(
|
|
1065
|
+
JSON.parse(
|
|
1066
|
+
await readFile2(path3.join(run.directory, "record.json"), "utf8")
|
|
1067
|
+
)
|
|
1068
|
+
);
|
|
1069
|
+
if (retained.ownerInstanceId !== this.options.ownerInstanceId)
|
|
1070
|
+
throw new Error(
|
|
1071
|
+
"run_id_reused: A previous owner admitted this run ID."
|
|
1072
|
+
);
|
|
1073
|
+
if (JSON.stringify(retained.request) !== JSON.stringify(request))
|
|
1074
|
+
throw new Error(
|
|
1075
|
+
"run_conflict: Run ID was admitted with a different request."
|
|
1076
|
+
);
|
|
1077
|
+
if (retained.state !== "ended")
|
|
1078
|
+
throw new Error(
|
|
1079
|
+
"run_receipt_invalid: Retained run has no live activity or terminal receipt."
|
|
1080
|
+
);
|
|
1081
|
+
run.record = retained;
|
|
1082
|
+
return;
|
|
1083
|
+
}
|
|
1084
|
+
await this.persist(run);
|
|
1085
|
+
})();
|
|
1086
|
+
run.admission = admission;
|
|
1087
|
+
this.admissions.add(admission);
|
|
1088
|
+
try {
|
|
1089
|
+
await admission;
|
|
1090
|
+
} catch (error) {
|
|
1091
|
+
this.runs.delete(request.runId);
|
|
1092
|
+
throw error;
|
|
1093
|
+
} finally {
|
|
1094
|
+
this.admissions.delete(admission);
|
|
1095
|
+
}
|
|
1096
|
+
if (run.record.state === "ended") {
|
|
1097
|
+
this.prune();
|
|
1098
|
+
return this.copy(run.record);
|
|
1099
|
+
}
|
|
1100
|
+
if (run.abort.signal.aborted || this.draining) {
|
|
1101
|
+
await this.terminate(
|
|
1102
|
+
run,
|
|
1103
|
+
"owner_stopping",
|
|
1104
|
+
"Run admission stopped before startup."
|
|
1105
|
+
);
|
|
1106
|
+
return this.copy(run.record);
|
|
1107
|
+
}
|
|
1108
|
+
run.timer = setTimeout(
|
|
1109
|
+
() => {
|
|
1110
|
+
void this.terminate(
|
|
1111
|
+
run,
|
|
1112
|
+
run.record.request.kind === "play" ? "safety_deadline" : "budget",
|
|
1113
|
+
run.record.request.kind === "play" ? "Play reached its ten-minute safety deadline." : this.startupBudgetMessage(run)
|
|
1114
|
+
).catch((error) => console.error(error));
|
|
1115
|
+
},
|
|
1116
|
+
Math.max(0, run.deadline - performance.now())
|
|
1117
|
+
);
|
|
1118
|
+
run.startup = this.initialize(run);
|
|
1119
|
+
void run.startup.then(
|
|
1120
|
+
() => {
|
|
1121
|
+
if (!run.abort.signal.aborted)
|
|
1122
|
+
void this.play(run).catch((error) => this.failed(run, error));
|
|
1123
|
+
},
|
|
1124
|
+
(error) => this.failed(run, error)
|
|
1125
|
+
);
|
|
1126
|
+
return this.copy(run.record);
|
|
1127
|
+
}
|
|
1128
|
+
async read(runId) {
|
|
1129
|
+
const run = this.runs.get(runId);
|
|
1130
|
+
if (run) {
|
|
1131
|
+
if (run.record.state === "ended") await run.termination;
|
|
1132
|
+
return this.copy(run.record);
|
|
1133
|
+
}
|
|
1134
|
+
const source = await readFile2(
|
|
1135
|
+
path3.join(this.directory, runId, "record.json"),
|
|
1136
|
+
"utf8"
|
|
1137
|
+
);
|
|
1138
|
+
const record = gameRunRecordSchema.parse(JSON.parse(source));
|
|
1139
|
+
if (record.ownerInstanceId !== this.options.ownerInstanceId && record.state !== "ended")
|
|
1140
|
+
return {
|
|
1141
|
+
...record,
|
|
1142
|
+
state: "ended",
|
|
1143
|
+
end: {
|
|
1144
|
+
reason: "owner_lost",
|
|
1145
|
+
...record.request.kind === "test" ? { outcome: "inconclusive" } : {},
|
|
1146
|
+
message: "The session owner was replaced. This run cannot resume and has no confirmed teardown."
|
|
1147
|
+
}
|
|
1148
|
+
};
|
|
1149
|
+
return record;
|
|
1150
|
+
}
|
|
1151
|
+
list() {
|
|
1152
|
+
return [...this.runs.values()].map((run) => this.copy(run.record));
|
|
1153
|
+
}
|
|
1154
|
+
async wait(runId, timeoutMs, signal) {
|
|
1155
|
+
const run = this.runs.get(runId);
|
|
1156
|
+
if (!run || run.record.state === "ended") return this.read(runId);
|
|
1157
|
+
const cancellation = new AbortController();
|
|
1158
|
+
const combined = signal ? AbortSignal.any([signal, cancellation.signal]) : cancellation.signal;
|
|
1159
|
+
let completed = () => {
|
|
1160
|
+
};
|
|
1161
|
+
const finished = new Promise((resolve) => {
|
|
1162
|
+
completed = resolve;
|
|
1163
|
+
run.finished.signal.addEventListener("abort", completed, { once: true });
|
|
1164
|
+
});
|
|
1165
|
+
try {
|
|
1166
|
+
await Promise.race([
|
|
1167
|
+
finished,
|
|
1168
|
+
delay(timeoutMs, void 0, { signal: combined })
|
|
1169
|
+
]);
|
|
1170
|
+
return await this.read(runId);
|
|
1171
|
+
} finally {
|
|
1172
|
+
cancellation.abort();
|
|
1173
|
+
run.finished.signal.removeEventListener("abort", completed);
|
|
1174
|
+
}
|
|
1175
|
+
}
|
|
1176
|
+
async stop(runId, reason = "stopped") {
|
|
1177
|
+
const run = this.runs.get(runId);
|
|
1178
|
+
if (!run || run.record.state === "ended") return this.read(runId);
|
|
1179
|
+
run.record.stopRequestedAt ??= (/* @__PURE__ */ new Date()).toISOString();
|
|
1180
|
+
await this.terminate(
|
|
1181
|
+
run,
|
|
1182
|
+
reason,
|
|
1183
|
+
reason === "stopped" ? "Stopped by the caller." : reason
|
|
1184
|
+
);
|
|
1185
|
+
return this.copy(run.record);
|
|
1186
|
+
}
|
|
1187
|
+
/**
|
|
1188
|
+
* Change what one seat is trying to do while its run is active. Steering only
|
|
1189
|
+
* changes the intent its policy reads; controls still come from the policy.
|
|
1190
|
+
* Each change is recorded with its time and source.
|
|
1191
|
+
*/
|
|
1192
|
+
async steer(input) {
|
|
1193
|
+
const { runId, seatId, intent, source } = gameRunSteerSchema.parse(input);
|
|
1194
|
+
const run = this.runs.get(runId);
|
|
1195
|
+
if (!run || run.abort.signal.aborted || run.record.state === "ended" || run.record.state === "stopping")
|
|
1196
|
+
throw new Error("run_not_active: Only an active test can be steered.");
|
|
1197
|
+
if (!run.record.seats.length)
|
|
1198
|
+
throw new Error(
|
|
1199
|
+
"run_not_active: Seats are not ready yet; give starting goals as intents."
|
|
1200
|
+
);
|
|
1201
|
+
const seat = run.record.seats.find(
|
|
1202
|
+
(candidate) => candidate.seatId === seatId
|
|
1203
|
+
);
|
|
1204
|
+
if (!seat)
|
|
1205
|
+
throw new Error(`run_seat_unknown: Run ${runId} has no seat ${seatId}.`);
|
|
1206
|
+
const steering = run.record.steering ??= [];
|
|
1207
|
+
if (steering.length >= MAXIMUM_GAME_RUN_STEERING_CHANGES)
|
|
1208
|
+
throw new Error(
|
|
1209
|
+
`steering_limit: A run records at most ${MAXIMUM_GAME_RUN_STEERING_CHANGES} steering changes.`
|
|
1210
|
+
);
|
|
1211
|
+
seat.intent = intent;
|
|
1212
|
+
steering.push({ at: (/* @__PURE__ */ new Date()).toISOString(), seatId, intent, source });
|
|
1213
|
+
await this.trace(run, { kind: "steer", seatId, intent, source });
|
|
1214
|
+
await this.persist(run);
|
|
1215
|
+
return this.copy(run.record);
|
|
1216
|
+
}
|
|
1217
|
+
stopAll() {
|
|
1218
|
+
return this.stoppingAll ??= (async () => {
|
|
1219
|
+
await Promise.allSettled(this.admissions);
|
|
1220
|
+
const pending = [...this.runs.values()].filter(
|
|
1221
|
+
(run) => !this.quiescent(run)
|
|
1222
|
+
);
|
|
1223
|
+
const records = await Promise.all(
|
|
1224
|
+
pending.map((run) => this.stop(run.record.runId))
|
|
1225
|
+
);
|
|
1226
|
+
assertProcessScopesConfirmed();
|
|
1227
|
+
return records;
|
|
1228
|
+
})().finally(() => {
|
|
1229
|
+
this.stoppingAll = void 0;
|
|
1230
|
+
});
|
|
1231
|
+
}
|
|
1232
|
+
async cancel(runId) {
|
|
1233
|
+
gameRunAddressSchema.parse({ runId });
|
|
1234
|
+
const result = (record) => ({
|
|
1235
|
+
runId,
|
|
1236
|
+
ownerInstanceId: this.options.ownerInstanceId,
|
|
1237
|
+
fenced: true,
|
|
1238
|
+
record
|
|
1239
|
+
});
|
|
1240
|
+
if (this.runs.has(runId)) return result(await this.stop(runId));
|
|
1241
|
+
assertProcessScopesConfirmed();
|
|
1242
|
+
await mkdir(this.directory, { recursive: true });
|
|
1243
|
+
const directory = path3.join(this.directory, runId);
|
|
1244
|
+
try {
|
|
1245
|
+
await mkdir(directory, { mode: 448 });
|
|
1246
|
+
} catch (error) {
|
|
1247
|
+
if (!(error instanceof Error) || !("code" in error) || error.code !== "EEXIST")
|
|
1248
|
+
throw error;
|
|
1249
|
+
if (this.runs.has(runId)) return result(await this.stop(runId));
|
|
1250
|
+
try {
|
|
1251
|
+
return result(await this.read(runId));
|
|
1252
|
+
} catch (readError) {
|
|
1253
|
+
if (!(readError instanceof Error) || !("code" in readError) || readError.code !== "ENOENT")
|
|
1254
|
+
throw readError;
|
|
1255
|
+
}
|
|
1256
|
+
}
|
|
1257
|
+
const marker = await open2(
|
|
1258
|
+
path3.join(directory, "cancelled.json"),
|
|
1259
|
+
"wx",
|
|
1260
|
+
384
|
|
1261
|
+
).catch((error) => {
|
|
1262
|
+
if (error.code === "EEXIST") return null;
|
|
1263
|
+
throw error;
|
|
1264
|
+
});
|
|
1265
|
+
if (marker) {
|
|
1266
|
+
try {
|
|
1267
|
+
await marker.writeFile(
|
|
1268
|
+
JSON.stringify({ runId, cancelledAt: (/* @__PURE__ */ new Date()).toISOString() })
|
|
1269
|
+
);
|
|
1270
|
+
} finally {
|
|
1271
|
+
await marker.close();
|
|
1272
|
+
}
|
|
1273
|
+
}
|
|
1274
|
+
return result(null);
|
|
1275
|
+
}
|
|
1276
|
+
async closeSession(runId, reason) {
|
|
1277
|
+
const run = this.runs.get(runId);
|
|
1278
|
+
if (!run)
|
|
1279
|
+
throw new Error(
|
|
1280
|
+
"run_session_unavailable: No live activity owns this session."
|
|
1281
|
+
);
|
|
1282
|
+
await this.terminate(run, reason, reason);
|
|
1283
|
+
if (!this.quiescent(run) || !run.closed?.closed)
|
|
1284
|
+
throw new Error(
|
|
1285
|
+
"run_cleanup_unconfirmed: Local runtime teardown was not confirmed."
|
|
1286
|
+
);
|
|
1287
|
+
return run.closed;
|
|
1288
|
+
}
|
|
1289
|
+
async drain() {
|
|
1290
|
+
this.draining = true;
|
|
1291
|
+
await Promise.allSettled(this.admissions);
|
|
1292
|
+
const results = await Promise.allSettled(
|
|
1293
|
+
[...this.runs.values()].map(
|
|
1294
|
+
(run) => this.terminate(run, "owner_stopping", "Session owner is stopping.")
|
|
1295
|
+
)
|
|
1296
|
+
);
|
|
1297
|
+
const failures = results.flatMap(
|
|
1298
|
+
(result) => result.status === "rejected" ? [result.reason] : []
|
|
1299
|
+
);
|
|
1300
|
+
if (failures.length)
|
|
1301
|
+
throw new AggregateError(failures, "Run cleanup failed.");
|
|
1302
|
+
if ([...this.runs.values()].some((run) => !this.quiescent(run)))
|
|
1303
|
+
throw new Error(
|
|
1304
|
+
"run_cleanup_unconfirmed: An owned process scope did not close."
|
|
1305
|
+
);
|
|
1306
|
+
assertProcessScopesConfirmed();
|
|
1307
|
+
}
|
|
1308
|
+
startupBudgetMessage(run) {
|
|
1309
|
+
return run.startupSteps.size ? `Run reached its time budget during startup: ${[...run.startupSteps].join("; ")}.` : "Run reached its time budget.";
|
|
1310
|
+
}
|
|
1311
|
+
async initialize(run) {
|
|
1312
|
+
const game = await this.game(run.record.request.gameId);
|
|
1313
|
+
if (run.abort.signal.aborted) return;
|
|
1314
|
+
run.startupSteps.delete("the game had not been resolved");
|
|
1315
|
+
await this.trace(run, { kind: "game_resolved", gameId: game.id });
|
|
1316
|
+
if (run.record.request.target.kind === "owned") {
|
|
1317
|
+
run.startupSteps.add("the build had not been sealed or reused");
|
|
1318
|
+
run.build = await sealGameBuild({
|
|
1319
|
+
projectDir: game.rootDir,
|
|
1320
|
+
configRelative: path3.relative(game.rootDir, game.configPath),
|
|
1321
|
+
runDirectory: run.directory,
|
|
1322
|
+
signal: run.abort.signal,
|
|
1323
|
+
onScope: this.observeScopes(run),
|
|
1324
|
+
onBuildLog: (receipt) => {
|
|
1325
|
+
run.record.evidence ??= { observation: null, error: null };
|
|
1326
|
+
run.record.evidence.buildLog = {
|
|
1327
|
+
...receipt,
|
|
1328
|
+
path: `.airjam/artifacts/runs/${run.record.runId}/build.log`
|
|
1329
|
+
};
|
|
1330
|
+
}
|
|
1331
|
+
});
|
|
1332
|
+
run.record.build = {
|
|
1333
|
+
...gameBuildIdentitySchema.parse(run.build.manifest),
|
|
1334
|
+
integrity: "sealed"
|
|
1335
|
+
};
|
|
1336
|
+
run.startupSteps.delete("the build had not been sealed or reused");
|
|
1337
|
+
await this.trace(run, {
|
|
1338
|
+
kind: "build_sealed",
|
|
1339
|
+
build: run.record.build,
|
|
1340
|
+
reused: run.build.reused
|
|
1341
|
+
});
|
|
1342
|
+
await this.persist(run);
|
|
1343
|
+
}
|
|
1344
|
+
if (run.abort.signal.aborted) return;
|
|
1345
|
+
const common = {
|
|
1346
|
+
rootDir: run.build?.rootDir ?? game.rootDir,
|
|
1347
|
+
...run.build ? { toolingRootDir: run.build.rootDir } : {},
|
|
1348
|
+
configPath: run.build?.configPath ?? game.configPath,
|
|
1349
|
+
runKind: run.record.request.kind,
|
|
1350
|
+
...run.record.request.kind === "test" ? { profileId: run.record.request.profileId } : {},
|
|
1351
|
+
seed: run.record.request.seed,
|
|
1352
|
+
onScope: this.observeScopes(run),
|
|
1353
|
+
startupSignal: run.abort.signal
|
|
1354
|
+
};
|
|
1355
|
+
const room = run.record.request.target.kind === "headless" ? startHeadlessRoom({
|
|
1356
|
+
rootDir: common.rootDir,
|
|
1357
|
+
configPath: common.configPath,
|
|
1358
|
+
seed: run.record.request.seed,
|
|
1359
|
+
settings: run.record.request.kind === "test" ? run.record.request.settings : void 0,
|
|
1360
|
+
logPath: path3.join(run.directory, "room.log"),
|
|
1361
|
+
onScope: common.onScope,
|
|
1362
|
+
startupSignal: run.abort.signal
|
|
1363
|
+
}) : void 0;
|
|
1364
|
+
room?.catch(() => void 0);
|
|
1365
|
+
const request = run.record.request;
|
|
1366
|
+
let profile;
|
|
1367
|
+
if (request.kind === "test") {
|
|
1368
|
+
run.startupSteps.add("the evaluator had not started");
|
|
1369
|
+
run.evaluator = await startTestProfileProcess({
|
|
1370
|
+
...common,
|
|
1371
|
+
role: "evaluator",
|
|
1372
|
+
logPath: path3.join(run.directory, "evaluator.log")
|
|
1373
|
+
});
|
|
1374
|
+
if (run.abort.signal.aborted) return;
|
|
1375
|
+
run.startupSteps.delete("the evaluator had not started");
|
|
1376
|
+
await this.trace(run, { kind: "evaluator_started" });
|
|
1377
|
+
profile = run.evaluator.profiles.find(
|
|
1378
|
+
(candidate) => candidate.id === request.profileId
|
|
1379
|
+
);
|
|
1380
|
+
if (!profile) throw new Error("Unknown test profile.");
|
|
1381
|
+
const seats = profile.seats;
|
|
1382
|
+
const unknownIntent = Object.keys(request.intents ?? {}).find(
|
|
1383
|
+
(seatId) => !seats.some((seat) => seat.id === seatId)
|
|
1384
|
+
);
|
|
1385
|
+
if (unknownIntent)
|
|
1386
|
+
throw new Error(
|
|
1387
|
+
`run_intent_invalid: Profile ${profile.id} has no seat ${unknownIntent}.`
|
|
1388
|
+
);
|
|
1389
|
+
run.record.profile = profile;
|
|
1390
|
+
}
|
|
1391
|
+
const players = profile ?? PLAY_RUN_PLAYER;
|
|
1392
|
+
run.players = players;
|
|
1393
|
+
if (run.attachment && players.seats.length > run.attachment.seats)
|
|
1394
|
+
throw new Error(
|
|
1395
|
+
"current_profile_invalid: The creator's room issued too few seats."
|
|
1396
|
+
);
|
|
1397
|
+
const policy = request.kind === "test" ? profile?.policies.find(
|
|
1398
|
+
(candidate) => candidate.id === request.policyId
|
|
1399
|
+
) : { id: "model", label: "Decision model", artifacts: void 0 };
|
|
1400
|
+
if (!policy) throw new Error("Unknown test policy.");
|
|
1401
|
+
run.startupSteps.add("the policy had not been prepared");
|
|
1402
|
+
const artifacts = policy.artifacts === void 0 ? void 0 : await verifyPolicyArtifacts({
|
|
1403
|
+
projectDir: common.rootDir,
|
|
1404
|
+
manifestPath: path3.join(common.rootDir, policy.artifacts),
|
|
1405
|
+
artifactRootDir: process.env.AIRJAM_TEST_ARTIFACTS_DIR,
|
|
1406
|
+
signal: run.abort.signal
|
|
1407
|
+
});
|
|
1408
|
+
run.record.policyArtifacts = artifacts?.receipt;
|
|
1409
|
+
const preparing = (async () => {
|
|
1410
|
+
const initializing = performance.now();
|
|
1411
|
+
run.policy = await startTestProfileProcess({
|
|
1412
|
+
...common,
|
|
1413
|
+
role: "policy",
|
|
1414
|
+
initializationDeadline: run.deadline,
|
|
1415
|
+
...artifacts ? { artifacts } : {},
|
|
1416
|
+
policyId: policy.id,
|
|
1417
|
+
logPath: path3.join(run.directory, "policy.log")
|
|
1418
|
+
});
|
|
1419
|
+
if (run.abort.signal.aborted) return;
|
|
1420
|
+
run.record.policyInitializationMs = performance.now() - initializing;
|
|
1421
|
+
run.record.policyPreparation = run.policy.preparation;
|
|
1422
|
+
run.startupSteps.delete("the policy had not been prepared");
|
|
1423
|
+
await this.trace(run, {
|
|
1424
|
+
kind: "policy_prepared",
|
|
1425
|
+
initializationMs: run.record.policyInitializationMs,
|
|
1426
|
+
preparation: run.policy.preparation,
|
|
1427
|
+
...artifacts ? { artifacts: artifacts.receipt } : {}
|
|
1428
|
+
});
|
|
1429
|
+
})();
|
|
1430
|
+
run.startupSteps.add("the session had not opened");
|
|
1431
|
+
const attaching = (async () => {
|
|
1432
|
+
if (run.abort.signal.aborted) return;
|
|
1433
|
+
if (room) {
|
|
1434
|
+
run.room = await room;
|
|
1435
|
+
if (run.abort.signal.aborted) return;
|
|
1436
|
+
}
|
|
1437
|
+
run.session = await this.options.openSession({
|
|
1438
|
+
runId: run.record.runId,
|
|
1439
|
+
gameId: game.id,
|
|
1440
|
+
game,
|
|
1441
|
+
nickname: agentNickname(0),
|
|
1442
|
+
settings: run.record.request.kind === "test" ? run.record.request.settings : void 0,
|
|
1443
|
+
attachment: run.attachment,
|
|
1444
|
+
build: run.build,
|
|
1445
|
+
room: run.room,
|
|
1446
|
+
onScope: this.observeScopes(run)
|
|
1447
|
+
});
|
|
1448
|
+
if (run.abort.signal.aborted) return;
|
|
1449
|
+
run.startupSteps.delete("the session had not opened");
|
|
1450
|
+
await this.trace(run, {
|
|
1451
|
+
kind: "session_opened",
|
|
1452
|
+
gameSessionId: run.session.summary.gameSessionId
|
|
1453
|
+
});
|
|
1454
|
+
run.startupSteps.add("the participants had not become ready");
|
|
1455
|
+
run.record.session = gameRunSessionIdentitySchema.parse(
|
|
1456
|
+
run.session.summary
|
|
1457
|
+
);
|
|
1458
|
+
if (run.attachment && (run.session.summary.semanticAccess !== "delegated-host" || run.session.summary.roomId !== new URL(run.attachment.controllerJoinUrl).searchParams.get("room")))
|
|
1459
|
+
throw new Error(
|
|
1460
|
+
"current_room_scope: The delegated participant did not attach to its authorized room."
|
|
1461
|
+
);
|
|
1462
|
+
for (const [index, description] of players.seats.entries()) {
|
|
1463
|
+
if (index > 0 && run.abort.signal.aborted) return;
|
|
1464
|
+
const extra = index === 0 ? void 0 : await run.session.addParticipant(agentNickname(index));
|
|
1465
|
+
const controllerId = extra?.controllerId ?? run.session.summary.controllerId;
|
|
1466
|
+
run.seats.push({
|
|
1467
|
+
id: description.id,
|
|
1468
|
+
controllerId,
|
|
1469
|
+
participant: extra ?? run.session,
|
|
1470
|
+
extra,
|
|
1471
|
+
leaseId: randomUUID3(),
|
|
1472
|
+
sequence: 0,
|
|
1473
|
+
policyCursor: 0,
|
|
1474
|
+
misses: 0,
|
|
1475
|
+
staleDecisions: 0,
|
|
1476
|
+
lowConfidenceStreak: 0,
|
|
1477
|
+
lastAnswer: null
|
|
1478
|
+
});
|
|
1479
|
+
run.record.seats.push({
|
|
1480
|
+
seatId: description.id,
|
|
1481
|
+
controllerId,
|
|
1482
|
+
intent: request.kind === "play" ? request.intent ?? null : request.intents?.[description.id] ?? null,
|
|
1483
|
+
counters: {
|
|
1484
|
+
decisions: 0,
|
|
1485
|
+
applied: 0,
|
|
1486
|
+
rejected: 0,
|
|
1487
|
+
unconfirmed: 0,
|
|
1488
|
+
timeout: 0,
|
|
1489
|
+
blocked: 0,
|
|
1490
|
+
effects: 0
|
|
1491
|
+
}
|
|
1492
|
+
});
|
|
1493
|
+
}
|
|
1494
|
+
if (run.abort.signal.aborted) return;
|
|
1495
|
+
run.record.state = "setup";
|
|
1496
|
+
for (const seat of run.seats) {
|
|
1497
|
+
const first = await this.observe(run, seat, false);
|
|
1498
|
+
seat.expected = first.identity;
|
|
1499
|
+
this.seatRecord(run, seat).expected = first.identity;
|
|
1500
|
+
if (seat === run.seats[0]) {
|
|
1501
|
+
run.record.expected = first.identity;
|
|
1502
|
+
run.fromTick = first.ticks.after ?? 0;
|
|
1503
|
+
}
|
|
1504
|
+
if (run.abort.signal.aborted) return;
|
|
1505
|
+
if ((await this.control(run, seat, first, { kind: "release" }, "setup")).status !== "applied")
|
|
1506
|
+
throw new Error(
|
|
1507
|
+
"Participant control handshake was not acknowledged."
|
|
1508
|
+
);
|
|
1509
|
+
}
|
|
1510
|
+
const expectedParticipants = run.seats.map((seat) => seat.controllerId);
|
|
1511
|
+
const participantsDeadline = performance.now() + 5e3;
|
|
1512
|
+
let participants = await run.session.readParticipants();
|
|
1513
|
+
while (!expectedParticipants.every(
|
|
1514
|
+
(id) => participants.controllerIds.includes(id)
|
|
1515
|
+
)) {
|
|
1516
|
+
if (run.abort.signal.aborted) return;
|
|
1517
|
+
if (performance.now() >= participantsDeadline)
|
|
1518
|
+
throw new Error(
|
|
1519
|
+
"seat_replaced: The connected room roster did not include every run player."
|
|
1520
|
+
);
|
|
1521
|
+
await delay(25);
|
|
1522
|
+
participants = await run.session.readParticipants();
|
|
1523
|
+
}
|
|
1524
|
+
if (run.abort.signal.aborted) return;
|
|
1525
|
+
if (participants.roomId !== run.session.summary.roomId || run.record.request.target.kind !== "current" && participants.controllerIds.length !== expectedParticipants.length)
|
|
1526
|
+
throw new Error(
|
|
1527
|
+
"seat_replaced: Owned room membership does not match its controlled players."
|
|
1528
|
+
);
|
|
1529
|
+
run.startupSteps.delete("the participants had not become ready");
|
|
1530
|
+
run.record.rosterJoinedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
1531
|
+
await this.trace(run, {
|
|
1532
|
+
kind: "participants_ready",
|
|
1533
|
+
gameSessionId: run.session.summary.gameSessionId,
|
|
1534
|
+
expected: run.record.expected,
|
|
1535
|
+
...participants
|
|
1536
|
+
});
|
|
1537
|
+
})();
|
|
1538
|
+
const startup = await Promise.allSettled([preparing, attaching]);
|
|
1539
|
+
for (const result of startup)
|
|
1540
|
+
if (result.status === "rejected") throw result.reason;
|
|
1541
|
+
if (run.abort.signal.aborted) return;
|
|
1542
|
+
const session = run.session;
|
|
1543
|
+
if (!session)
|
|
1544
|
+
throw new Error("Run participant attachment did not complete.");
|
|
1545
|
+
run.startupSteps.add("the profile setup had not finished");
|
|
1546
|
+
if (!await this.runProfileSteps(run, session, profile?.setup ?? [], "setup"))
|
|
1547
|
+
return;
|
|
1548
|
+
await this.persist(run);
|
|
1549
|
+
run.startupSteps.delete("the profile setup had not finished");
|
|
1550
|
+
}
|
|
1551
|
+
/**
|
|
1552
|
+
* A profile's setup or hand-back steps, in order. Setup stops with the run
|
|
1553
|
+
* and its startup budget and retries a stale participant action until then;
|
|
1554
|
+
* hand-back runs after play has stopped and retries a stale action twice.
|
|
1555
|
+
* Returns false when setup stopped early.
|
|
1556
|
+
*/
|
|
1557
|
+
async runProfileSteps(run, session, steps, phase) {
|
|
1558
|
+
const name = phase === "setup" ? "Setup" : "Hand-back";
|
|
1559
|
+
for (const step of steps) {
|
|
1560
|
+
if (phase === "setup" && run.abort.signal.aborted) return false;
|
|
1561
|
+
if (step.lane === "host") {
|
|
1562
|
+
const result = await session.invokeHost(step.actionId, step.input);
|
|
1563
|
+
await this.trace(run, {
|
|
1564
|
+
kind: phase === "setup" ? "host_setup" : "host_hand_back",
|
|
1565
|
+
actionId: step.actionId,
|
|
1566
|
+
result
|
|
1567
|
+
});
|
|
1568
|
+
continue;
|
|
1569
|
+
}
|
|
1570
|
+
const seat = run.seats.find((candidate) => candidate.id === step.seatId);
|
|
1571
|
+
if (!seat) throw new Error(`${name} seat is not initialized.`);
|
|
1572
|
+
for (let attempt = 1; ; attempt++) {
|
|
1573
|
+
if (phase === "setup") {
|
|
1574
|
+
if (run.abort.signal.aborted) return false;
|
|
1575
|
+
if (performance.now() >= run.deadline) {
|
|
1576
|
+
void this.terminate(
|
|
1577
|
+
run,
|
|
1578
|
+
"budget",
|
|
1579
|
+
this.startupBudgetMessage(run)
|
|
1580
|
+
).catch((error) => console.error(error));
|
|
1581
|
+
return false;
|
|
1582
|
+
}
|
|
1583
|
+
}
|
|
1584
|
+
const observation = await this.observe(run, seat, false);
|
|
1585
|
+
const receipt = await this.control(
|
|
1586
|
+
run,
|
|
1587
|
+
seat,
|
|
1588
|
+
observation,
|
|
1589
|
+
{
|
|
1590
|
+
kind: "action",
|
|
1591
|
+
actionId: step.actionId,
|
|
1592
|
+
input: step.input,
|
|
1593
|
+
deadlineMs: this.deadline(observation)
|
|
1594
|
+
},
|
|
1595
|
+
phase
|
|
1596
|
+
);
|
|
1597
|
+
if (receipt.status === "rejected" && receipt.reason === "stale_decision" && (phase === "setup" || attempt < 3))
|
|
1598
|
+
continue;
|
|
1599
|
+
if (receipt.status !== "applied" || receipt.operation.kind !== "action" || !receipt.operation.result.ok)
|
|
1600
|
+
throw new Error(`${name} action ${step.actionId} was not accepted.`);
|
|
1601
|
+
break;
|
|
1602
|
+
}
|
|
1603
|
+
}
|
|
1604
|
+
return true;
|
|
1605
|
+
}
|
|
1606
|
+
async watch(input, onEvent, signal) {
|
|
1607
|
+
const request = gameRunWatchRequestSchema.parse(input);
|
|
1608
|
+
assertProcessScopesConfirmed();
|
|
1609
|
+
const run = this.runs.get(request.runId);
|
|
1610
|
+
if (!run || run.record.request.target.kind !== "owned" || !run.session || !["setup", "playing"].includes(run.record.state))
|
|
1611
|
+
throw new Error(
|
|
1612
|
+
"run_watch_unavailable: Only an active owned game can be watched."
|
|
1613
|
+
);
|
|
1614
|
+
const surfaceKey = JSON.stringify(request.surface);
|
|
1615
|
+
if (run.watches.has(surfaceKey))
|
|
1616
|
+
throw new Error(
|
|
1617
|
+
"run_watch_duplicate: This surface already has a producer."
|
|
1618
|
+
);
|
|
1619
|
+
if (run.watches.size >= 2)
|
|
1620
|
+
throw new Error("run_watch_limit: At most two surfaces can be produced.");
|
|
1621
|
+
const watcher = request.surface.kind === "host" ? run.session.watchHost : (() => {
|
|
1622
|
+
const seat = run.seats.find(
|
|
1623
|
+
(candidate) => request.surface.kind === "controller" && candidate.id === request.surface.seatId
|
|
1624
|
+
);
|
|
1625
|
+
if (!seat)
|
|
1626
|
+
throw new Error(
|
|
1627
|
+
"run_watch_seat: This player does not belong to the run."
|
|
1628
|
+
);
|
|
1629
|
+
return seat.participant.watch;
|
|
1630
|
+
})();
|
|
1631
|
+
const active = AbortSignal.any([signal, run.abort.signal]);
|
|
1632
|
+
active.throwIfAborted();
|
|
1633
|
+
run.record.watched = true;
|
|
1634
|
+
const operation = (async () => {
|
|
1635
|
+
await this.persist(run);
|
|
1636
|
+
await this.trace(
|
|
1637
|
+
run,
|
|
1638
|
+
{ kind: "watch_started", surface: request.surface },
|
|
1639
|
+
true
|
|
1640
|
+
);
|
|
1641
|
+
try {
|
|
1642
|
+
await watcher((event) => {
|
|
1643
|
+
if (active.aborted) return;
|
|
1644
|
+
onEvent(
|
|
1645
|
+
event.type === "ready" ? { ...event, runId: request.runId, surface: request.surface } : event
|
|
1646
|
+
);
|
|
1647
|
+
}, active);
|
|
1648
|
+
} catch (error) {
|
|
1649
|
+
await this.trace(
|
|
1650
|
+
run,
|
|
1651
|
+
{
|
|
1652
|
+
kind: "watch_failed",
|
|
1653
|
+
surface: request.surface,
|
|
1654
|
+
message: error instanceof Error ? error.message : String(error)
|
|
1655
|
+
},
|
|
1656
|
+
true
|
|
1657
|
+
);
|
|
1658
|
+
throw error;
|
|
1659
|
+
} finally {
|
|
1660
|
+
await this.trace(
|
|
1661
|
+
run,
|
|
1662
|
+
{ kind: "watch_stopped", surface: request.surface },
|
|
1663
|
+
true
|
|
1664
|
+
);
|
|
1665
|
+
}
|
|
1666
|
+
})();
|
|
1667
|
+
run.watches.set(surfaceKey, operation);
|
|
1668
|
+
try {
|
|
1669
|
+
await operation;
|
|
1670
|
+
} finally {
|
|
1671
|
+
run.watches.delete(surfaceKey);
|
|
1672
|
+
}
|
|
1673
|
+
}
|
|
1674
|
+
seatRecord(run, seat) {
|
|
1675
|
+
const record = run.record.seats.find(
|
|
1676
|
+
(candidate) => candidate.seatId === seat.id
|
|
1677
|
+
);
|
|
1678
|
+
if (!record) throw new Error("Run seat has no receipt record.");
|
|
1679
|
+
return record;
|
|
1680
|
+
}
|
|
1681
|
+
elapsed(run) {
|
|
1682
|
+
if (!run.session || run.playStartedAt === void 0)
|
|
1683
|
+
throw new Error("Run play has not started.");
|
|
1684
|
+
return run.session.clock.now() - run.playStartedAt;
|
|
1685
|
+
}
|
|
1686
|
+
/**
|
|
1687
|
+
* Answer a seat's question and keep that seat's running summary of how the
|
|
1688
|
+
* model played it: what it chose, what it missed, and stretches where it
|
|
1689
|
+
* stayed unsure, which often means the brief or the game was unclear.
|
|
1690
|
+
*/
|
|
1691
|
+
async answerFor(run, seat, question, deadline) {
|
|
1692
|
+
const record = this.seatRecord(run, seat);
|
|
1693
|
+
const answers = record.answers ??= {
|
|
1694
|
+
asked: 0,
|
|
1695
|
+
answered: 0,
|
|
1696
|
+
missed: 0,
|
|
1697
|
+
lowConfidence: 0,
|
|
1698
|
+
lowConfidenceStretches: 0,
|
|
1699
|
+
choices: {}
|
|
1700
|
+
};
|
|
1701
|
+
answers.asked++;
|
|
1702
|
+
let answer;
|
|
1703
|
+
try {
|
|
1704
|
+
answer = await this.answer(run, question, deadline);
|
|
1705
|
+
} catch (error) {
|
|
1706
|
+
answers.missed++;
|
|
1707
|
+
throw error;
|
|
1708
|
+
}
|
|
1709
|
+
answers.answered++;
|
|
1710
|
+
answers.choices[answer.choice] = (answers.choices[answer.choice] ?? 0) + 1;
|
|
1711
|
+
if (answer.note) {
|
|
1712
|
+
answers.automatic = (answers.automatic ?? 0) + 1;
|
|
1713
|
+
return answer;
|
|
1714
|
+
}
|
|
1715
|
+
if (answer.confidence < LOW_CONFIDENCE) {
|
|
1716
|
+
answers.lowConfidence++;
|
|
1717
|
+
if (++seat.lowConfidenceStreak === LOW_CONFIDENCE_STRETCH)
|
|
1718
|
+
answers.lowConfidenceStretches++;
|
|
1719
|
+
} else seat.lowConfidenceStreak = 0;
|
|
1720
|
+
return answer;
|
|
1721
|
+
}
|
|
1722
|
+
/**
|
|
1723
|
+
* Take the only option directly, or put the question to the run's decision
|
|
1724
|
+
* model and map its choice back to the option's own control.
|
|
1725
|
+
* It shares the policy's decision deadline, and
|
|
1726
|
+
* a late, failed or undeclared answer is a missed decision, never a fallback.
|
|
1727
|
+
*/
|
|
1728
|
+
async answer(run, question, deadline) {
|
|
1729
|
+
const options = Object.entries(question.options);
|
|
1730
|
+
if (options.length === 1) {
|
|
1731
|
+
const [choice, option2] = options[0];
|
|
1732
|
+
return {
|
|
1733
|
+
choice,
|
|
1734
|
+
confidence: 1,
|
|
1735
|
+
control: option2.control,
|
|
1736
|
+
durationMs: 0,
|
|
1737
|
+
note: "Only option; no model asked."
|
|
1738
|
+
};
|
|
1739
|
+
}
|
|
1740
|
+
const decisions = this.options.decisions;
|
|
1741
|
+
if (!decisions)
|
|
1742
|
+
throw new Error(
|
|
1743
|
+
"decision_provider_unavailable: This run's policy asks a decision model, but none is configured."
|
|
1744
|
+
);
|
|
1745
|
+
const remaining = deadline - performance.now();
|
|
1746
|
+
if (remaining <= 0)
|
|
1747
|
+
throw new Error("policy_timeout: Decision exceeded its deadline.");
|
|
1748
|
+
run.record.decisionModel ??= decisions.model;
|
|
1749
|
+
const started = performance.now();
|
|
1750
|
+
const timeout = AbortSignal.timeout(Math.ceil(remaining));
|
|
1751
|
+
let answered;
|
|
1752
|
+
try {
|
|
1753
|
+
answered = await decisions.ask(
|
|
1754
|
+
question,
|
|
1755
|
+
AbortSignal.any([run.abort.signal, timeout])
|
|
1756
|
+
);
|
|
1757
|
+
} catch (error) {
|
|
1758
|
+
if (timeout.aborted)
|
|
1759
|
+
throw new Error(
|
|
1760
|
+
"policy_timeout: Decision model exceeded its deadline."
|
|
1761
|
+
);
|
|
1762
|
+
throw new Error(
|
|
1763
|
+
`decision_failed: ${error instanceof Error ? error.message : String(error)}`
|
|
1764
|
+
);
|
|
1765
|
+
}
|
|
1766
|
+
const option = Object.hasOwn(question.options, answered.choice) ? question.options[answered.choice] : void 0;
|
|
1767
|
+
if (!option)
|
|
1768
|
+
throw new Error(
|
|
1769
|
+
"decision_failed: Decision model chose an option the policy did not offer."
|
|
1770
|
+
);
|
|
1771
|
+
return {
|
|
1772
|
+
...answered,
|
|
1773
|
+
control: option.control,
|
|
1774
|
+
durationMs: performance.now() - started
|
|
1775
|
+
};
|
|
1776
|
+
}
|
|
1777
|
+
async startClip(run) {
|
|
1778
|
+
run.record.evidence ??= { observation: null, error: null };
|
|
1779
|
+
if (run.room) {
|
|
1780
|
+
run.record.evidence.clip = { status: "not-captured", reason: "headless" };
|
|
1781
|
+
return;
|
|
1782
|
+
}
|
|
1783
|
+
const expected = run.record.expected;
|
|
1784
|
+
try {
|
|
1785
|
+
if (!run.session?.requestHost || !expected)
|
|
1786
|
+
throw new Error("No host-agent request path is available.");
|
|
1787
|
+
const response = await run.session.requestHost(
|
|
1788
|
+
{
|
|
1789
|
+
operation: "clip-start",
|
|
1790
|
+
roomId: expected.roomId,
|
|
1791
|
+
runtimeId: expected.runtimeId,
|
|
1792
|
+
clipId: run.record.runId
|
|
1793
|
+
},
|
|
1794
|
+
5e3
|
|
1795
|
+
);
|
|
1796
|
+
if (response.operation !== "clip-start" || response.clipId !== run.record.runId)
|
|
1797
|
+
throw new Error("Invalid clip start response.");
|
|
1798
|
+
run.clipStarted = true;
|
|
1799
|
+
await this.trace(
|
|
1800
|
+
run,
|
|
1801
|
+
{
|
|
1802
|
+
kind: "clip-start",
|
|
1803
|
+
clipId: run.record.runId
|
|
1804
|
+
},
|
|
1805
|
+
true
|
|
1806
|
+
).catch(() => {
|
|
1807
|
+
});
|
|
1808
|
+
} catch (error) {
|
|
1809
|
+
run.record.evidence.clip = {
|
|
1810
|
+
status: "not-captured",
|
|
1811
|
+
reason: clipFailureReason(error)
|
|
1812
|
+
};
|
|
1813
|
+
await this.trace(
|
|
1814
|
+
run,
|
|
1815
|
+
{
|
|
1816
|
+
kind: "clip-failure",
|
|
1817
|
+
reason: clipFailureReason(error),
|
|
1818
|
+
message: error instanceof Error ? error.message : String(error)
|
|
1819
|
+
},
|
|
1820
|
+
true
|
|
1821
|
+
).catch(() => {
|
|
1822
|
+
});
|
|
1823
|
+
}
|
|
1824
|
+
}
|
|
1825
|
+
async finishClip(run) {
|
|
1826
|
+
run.record.evidence ??= { observation: null, error: null };
|
|
1827
|
+
run.record.evidence.clip ??= {
|
|
1828
|
+
status: "not-captured",
|
|
1829
|
+
reason: run.room ? "headless" : "host-unavailable"
|
|
1830
|
+
};
|
|
1831
|
+
if (!run.clipStarted) return;
|
|
1832
|
+
try {
|
|
1833
|
+
const session = run.session;
|
|
1834
|
+
const expected = run.record.expected;
|
|
1835
|
+
if (!session?.requestHost || !expected)
|
|
1836
|
+
throw new Error("No recording host is available.");
|
|
1837
|
+
const result = await readHostClip(
|
|
1838
|
+
(request) => session.requestHost(request, 5e3),
|
|
1839
|
+
run.record.runId,
|
|
1840
|
+
expected
|
|
1841
|
+
);
|
|
1842
|
+
if (result.status === "not-captured") {
|
|
1843
|
+
run.record.evidence.clip = result;
|
|
1844
|
+
return;
|
|
1845
|
+
}
|
|
1846
|
+
const source = `${JSON.stringify(result.artifact)}
|
|
1847
|
+
`;
|
|
1848
|
+
const file = await open2(
|
|
1849
|
+
path3.join(run.directory, "clip.json"),
|
|
1850
|
+
"w",
|
|
1851
|
+
384
|
|
1852
|
+
);
|
|
1853
|
+
try {
|
|
1854
|
+
await file.writeFile(source);
|
|
1855
|
+
} finally {
|
|
1856
|
+
await file.close();
|
|
1857
|
+
}
|
|
1858
|
+
run.record.evidence.clip = {
|
|
1859
|
+
status: "captured",
|
|
1860
|
+
path: `.airjam/artifacts/runs/${run.record.runId}/clip.json`,
|
|
1861
|
+
sha256: createHash2("sha256").update(source).digest("hex"),
|
|
1862
|
+
bytes: Buffer.byteLength(source),
|
|
1863
|
+
frames: result.artifact.frames.length,
|
|
1864
|
+
durationMs: result.artifact.durationMs
|
|
1865
|
+
};
|
|
1866
|
+
} catch (error) {
|
|
1867
|
+
run.record.evidence.clip = {
|
|
1868
|
+
status: "not-captured",
|
|
1869
|
+
reason: clipFailureReason(error)
|
|
1870
|
+
};
|
|
1871
|
+
await this.trace(
|
|
1872
|
+
run,
|
|
1873
|
+
{
|
|
1874
|
+
kind: "clip-failure",
|
|
1875
|
+
reason: clipFailureReason(error),
|
|
1876
|
+
message: error instanceof Error ? error.message : String(error)
|
|
1877
|
+
},
|
|
1878
|
+
true
|
|
1879
|
+
).catch(() => {
|
|
1880
|
+
});
|
|
1881
|
+
}
|
|
1882
|
+
}
|
|
1883
|
+
deadline(observation) {
|
|
1884
|
+
if (!observation.clock)
|
|
1885
|
+
throw new Error("Host does not advertise command admission deadlines.");
|
|
1886
|
+
return observation.clock.startedAtMs + PARTICIPANT_CONTROL_DEADLINE_MS;
|
|
1887
|
+
}
|
|
1888
|
+
async observe(run, seat, includeImage, diagnostic = false) {
|
|
1889
|
+
if (!run.players) throw new Error("Run players are not initialized.");
|
|
1890
|
+
const observation = await seat.participant.observe({
|
|
1891
|
+
scope: diagnostic ? "diagnostic" : run.players.scope,
|
|
1892
|
+
includeImage,
|
|
1893
|
+
expected: seat.expected
|
|
1894
|
+
});
|
|
1895
|
+
if (seat.expected && !sameHostRuntimeIdentity(seat.expected, observation.identity))
|
|
1896
|
+
throw new Error(
|
|
1897
|
+
"runtime_replaced: Observed a different host generation."
|
|
1898
|
+
);
|
|
1899
|
+
if (observation.controllerId !== seat.controllerId)
|
|
1900
|
+
throw new Error(
|
|
1901
|
+
"seat_replaced: Observation belongs to a different player."
|
|
1902
|
+
);
|
|
1903
|
+
this.trackPace(run, observation);
|
|
1904
|
+
return observation;
|
|
1905
|
+
}
|
|
1906
|
+
/**
|
|
1907
|
+
* How fast the host's simulation ran during play, against real time. A
|
|
1908
|
+
* starved host plays in slow motion, which quietly makes tests easier, so
|
|
1909
|
+
* the record says so.
|
|
1910
|
+
*/
|
|
1911
|
+
trackPace(run, observation) {
|
|
1912
|
+
const pace = observation.pace;
|
|
1913
|
+
if (run.record.state !== "playing" || !pace) return;
|
|
1914
|
+
if (!run.paceStart || pace.wallMs < run.paceStart.wallMs) {
|
|
1915
|
+
run.paceStart = pace;
|
|
1916
|
+
return;
|
|
1917
|
+
}
|
|
1918
|
+
const wallMs = pace.wallMs - run.paceStart.wallMs;
|
|
1919
|
+
if (wallMs < 1e3) return;
|
|
1920
|
+
run.record.hostPace = {
|
|
1921
|
+
framesPerSecond: Math.round((pace.frames - run.paceStart.frames) / wallMs * 1e4) / 10,
|
|
1922
|
+
simulationSpeed: Math.round(
|
|
1923
|
+
(pace.simulatedMs - run.paceStart.simulatedMs) / wallMs * 100
|
|
1924
|
+
) / 100
|
|
1925
|
+
};
|
|
1926
|
+
}
|
|
1927
|
+
pruneReceipts(run) {
|
|
1928
|
+
run.receipts = run.receipts.filter(
|
|
1929
|
+
(receipt) => run.record.request.kind === "test" && receipt.index > run.evaluationCursor || receipt.sequence > (run.seats.find((seat) => seat.id === receipt.seatId)?.policyCursor ?? 0)
|
|
1930
|
+
);
|
|
1931
|
+
}
|
|
1932
|
+
async evaluationObservation(run, includeImage) {
|
|
1933
|
+
const primary = run.seats[0];
|
|
1934
|
+
if (!primary?.expected || run.seats.some((seat) => !seat.expected))
|
|
1935
|
+
throw new Error("Run has no fully initialized observation seats.");
|
|
1936
|
+
const checkSeats = () => Promise.all(run.seats.map((seat) => seat.participant.checkConnected()));
|
|
1937
|
+
await checkSeats();
|
|
1938
|
+
const observation = await this.observe(
|
|
1939
|
+
run,
|
|
1940
|
+
primary,
|
|
1941
|
+
includeImage,
|
|
1942
|
+
run.record.request.kind === "test"
|
|
1943
|
+
);
|
|
1944
|
+
await checkSeats();
|
|
1945
|
+
return observation;
|
|
1946
|
+
}
|
|
1947
|
+
control(run, seat, observation, operation, phase) {
|
|
1948
|
+
if (phase !== "cleanup" && run.abort.signal.aborted)
|
|
1949
|
+
return Promise.reject(
|
|
1950
|
+
new Error("run_stopped: No new effects after Stop.")
|
|
1951
|
+
);
|
|
1952
|
+
const pending = this.applyControl(run, seat, observation, operation, phase);
|
|
1953
|
+
run.effects.add(pending);
|
|
1954
|
+
void pending.finally(() => run.effects.delete(pending)).catch(() => void 0);
|
|
1955
|
+
return pending;
|
|
1956
|
+
}
|
|
1957
|
+
async applyControl(run, seat, observation, operation, phase) {
|
|
1958
|
+
const request = {
|
|
1959
|
+
expected: observation.identity,
|
|
1960
|
+
lease: { id: seat.leaseId, sequence: ++seat.sequence },
|
|
1961
|
+
operation
|
|
1962
|
+
};
|
|
1963
|
+
const send = () => {
|
|
1964
|
+
if (operation.kind !== "release")
|
|
1965
|
+
run.record.lastInputAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
1966
|
+
return seat.participant.control(request);
|
|
1967
|
+
};
|
|
1968
|
+
let attempts = 1;
|
|
1969
|
+
let acknowledgement = await send();
|
|
1970
|
+
if (acknowledgement.status === "unconfirmed") {
|
|
1971
|
+
await this.trace(run, {
|
|
1972
|
+
kind: "control_attempt",
|
|
1973
|
+
seatId: seat.id,
|
|
1974
|
+
phase,
|
|
1975
|
+
observationId: observation.id,
|
|
1976
|
+
sequence: seat.sequence,
|
|
1977
|
+
operation,
|
|
1978
|
+
receipt: acknowledgement
|
|
1979
|
+
});
|
|
1980
|
+
if (operation.kind === "release" || !run.abort.signal.aborted) {
|
|
1981
|
+
attempts = 2;
|
|
1982
|
+
acknowledgement = await send();
|
|
1983
|
+
}
|
|
1984
|
+
}
|
|
1985
|
+
if (phase === "cleanup" && operation.kind === "release" && acknowledgement.status === "applied")
|
|
1986
|
+
run.record.releaseAcknowledgedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
1987
|
+
run.record.counters[acknowledgement.status === "applied" ? "applied" : acknowledgement.status === "rejected" ? "rejected" : "unconfirmed"]++;
|
|
1988
|
+
this.seatRecord(run, seat).counters[acknowledgement.status === "applied" ? "applied" : acknowledgement.status === "rejected" ? "rejected" : "unconfirmed"]++;
|
|
1989
|
+
if (phase === "play" && acknowledgement.status === "applied" && operation.kind !== "release" && (acknowledgement.operation.kind !== "action" || acknowledgement.operation.result.ok))
|
|
1990
|
+
this.seatRecord(run, seat).counters.effects++;
|
|
1991
|
+
const receipt = {
|
|
1992
|
+
index: ++run.receiptIndex,
|
|
1993
|
+
seatId: seat.id,
|
|
1994
|
+
phase,
|
|
1995
|
+
sequence: seat.sequence,
|
|
1996
|
+
attempts,
|
|
1997
|
+
operation,
|
|
1998
|
+
acknowledgement
|
|
1999
|
+
};
|
|
2000
|
+
run.receipts.push(receipt);
|
|
2001
|
+
await this.trace(run, {
|
|
2002
|
+
kind: "control",
|
|
2003
|
+
observationId: observation.id,
|
|
2004
|
+
...receipt
|
|
2005
|
+
});
|
|
2006
|
+
return acknowledgement;
|
|
2007
|
+
}
|
|
2008
|
+
evaluate(run, phase, observation) {
|
|
2009
|
+
if (run.evaluation)
|
|
2010
|
+
throw new Error("evaluator_busy: A previous evaluation is pending.");
|
|
2011
|
+
const primary = run.seats[0];
|
|
2012
|
+
const evaluator = run.evaluator;
|
|
2013
|
+
if (!primary || !evaluator)
|
|
2014
|
+
throw new Error("Scenario evaluator is not initialized.");
|
|
2015
|
+
const through = run.receiptIndex;
|
|
2016
|
+
const receipts = run.receipts.filter(
|
|
2017
|
+
(receipt) => receipt.index > run.evaluationCursor && receipt.index <= through
|
|
2018
|
+
);
|
|
2019
|
+
const pending = (async () => {
|
|
2020
|
+
const sample = observation ?? await this.evaluationObservation(run, false);
|
|
2021
|
+
run.evaluationCursor = through;
|
|
2022
|
+
if (phase === "play") run.playEvaluationSent = true;
|
|
2023
|
+
const verdict = await evaluator.evaluate(
|
|
2024
|
+
{
|
|
2025
|
+
phase,
|
|
2026
|
+
observation: sample,
|
|
2027
|
+
seats: run.seats.map((seat) => ({
|
|
2028
|
+
seatId: seat.id,
|
|
2029
|
+
controllerId: seat.controllerId
|
|
2030
|
+
})),
|
|
2031
|
+
receipts,
|
|
2032
|
+
elapsedMs: this.elapsed(run)
|
|
2033
|
+
},
|
|
2034
|
+
1e3
|
|
2035
|
+
);
|
|
2036
|
+
run.record.evaluation ??= {};
|
|
2037
|
+
run.record.evaluation[phase] = verdict;
|
|
2038
|
+
await this.trace(run, {
|
|
2039
|
+
kind: "evaluation",
|
|
2040
|
+
phase,
|
|
2041
|
+
observationId: sample.id,
|
|
2042
|
+
through,
|
|
2043
|
+
verdict
|
|
2044
|
+
});
|
|
2045
|
+
this.pruneReceipts(run);
|
|
2046
|
+
return verdict;
|
|
2047
|
+
})();
|
|
2048
|
+
run.evaluation = pending;
|
|
2049
|
+
void pending.finally(() => {
|
|
2050
|
+
if (run.evaluation === pending) run.evaluation = void 0;
|
|
2051
|
+
}).catch(() => void 0);
|
|
2052
|
+
return pending;
|
|
2053
|
+
}
|
|
2054
|
+
async play(run) {
|
|
2055
|
+
const profile = run.players;
|
|
2056
|
+
const request = run.record.request;
|
|
2057
|
+
const policy = run.policy;
|
|
2058
|
+
const primary = run.seats[0];
|
|
2059
|
+
if (!profile || !policy || !primary)
|
|
2060
|
+
throw new Error("Run policy is not initialized.");
|
|
2061
|
+
const session = run.session;
|
|
2062
|
+
if (!session) throw new Error("Run session is not open.");
|
|
2063
|
+
const clock = session.clock;
|
|
2064
|
+
await this.startClip(run);
|
|
2065
|
+
if (run.abort.signal.aborted) return;
|
|
2066
|
+
run.record.state = "playing";
|
|
2067
|
+
await this.persist(run);
|
|
2068
|
+
if (run.abort.signal.aborted) return;
|
|
2069
|
+
run.playStartedAt = clock.now();
|
|
2070
|
+
run.record.playStartedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
2071
|
+
if (request.kind === "test") {
|
|
2072
|
+
clearTimeout(run.timer);
|
|
2073
|
+
run.deadline = performance.now() + request.budget.durationMs;
|
|
2074
|
+
run.timer = setTimeout(() => {
|
|
2075
|
+
void this.terminate(
|
|
2076
|
+
run,
|
|
2077
|
+
"budget",
|
|
2078
|
+
"Run reached its bounded play budget."
|
|
2079
|
+
).catch((error) => console.error(error));
|
|
2080
|
+
}, request.budget.durationMs);
|
|
2081
|
+
}
|
|
2082
|
+
const inFlight = /* @__PURE__ */ new Map();
|
|
2083
|
+
let lastTick = null;
|
|
2084
|
+
let progressedAt = clock.now();
|
|
2085
|
+
while (!run.abort.signal.aborted) {
|
|
2086
|
+
const roundStarted = clock.now();
|
|
2087
|
+
if (request.kind === "test" && (this.elapsed(run) >= request.budget.durationMs || run.record.counters.steps >= request.budget.steps && inFlight.size === 0))
|
|
2088
|
+
return this.terminate(
|
|
2089
|
+
run,
|
|
2090
|
+
"budget",
|
|
2091
|
+
"Run reached its bounded play budget."
|
|
2092
|
+
);
|
|
2093
|
+
if (request.kind === "test") {
|
|
2094
|
+
let verdict;
|
|
2095
|
+
try {
|
|
2096
|
+
verdict = await this.evaluate(run, "play");
|
|
2097
|
+
} catch (error) {
|
|
2098
|
+
if (run.abort.signal.aborted) return;
|
|
2099
|
+
if (!(error instanceof Error) || !/^policy_(timeout|busy):/.test(error.message))
|
|
2100
|
+
throw error;
|
|
2101
|
+
return this.terminate(
|
|
2102
|
+
run,
|
|
2103
|
+
"evaluator_unresponsive",
|
|
2104
|
+
error instanceof Error ? error.message : String(error)
|
|
2105
|
+
);
|
|
2106
|
+
}
|
|
2107
|
+
if (run.abort.signal.aborted) return;
|
|
2108
|
+
if (verdict.status === "failed")
|
|
2109
|
+
return this.terminate(
|
|
2110
|
+
run,
|
|
2111
|
+
"failed",
|
|
2112
|
+
verdict.message ?? "Scenario failed."
|
|
2113
|
+
);
|
|
2114
|
+
if (verdict.status === "passed") {
|
|
2115
|
+
const tested = run.record.seats.every(
|
|
2116
|
+
(seat) => seat.counters.effects > 0
|
|
2117
|
+
);
|
|
2118
|
+
return this.terminate(
|
|
2119
|
+
run,
|
|
2120
|
+
tested ? "completed" : "untested_seat",
|
|
2121
|
+
tested ? verdict.message ?? "Scenario passed." : "The scenario passed before every seat produced an applied play effect."
|
|
2122
|
+
);
|
|
2123
|
+
}
|
|
2124
|
+
}
|
|
2125
|
+
for (const seat of run.seats) {
|
|
2126
|
+
if (run.abort.signal.aborted) return;
|
|
2127
|
+
if (inFlight.has(seat.id)) continue;
|
|
2128
|
+
if (request.kind === "test" && run.record.counters.steps >= request.budget.steps)
|
|
2129
|
+
break;
|
|
2130
|
+
const started = performance.now();
|
|
2131
|
+
const observation = await this.observe(
|
|
2132
|
+
run,
|
|
2133
|
+
seat,
|
|
2134
|
+
run.record.request.target.kind === "owned" && profile.includeImage
|
|
2135
|
+
);
|
|
2136
|
+
if (run.abort.signal.aborted) return;
|
|
2137
|
+
const tick = observation.ticks.after;
|
|
2138
|
+
if (tick !== lastTick) {
|
|
2139
|
+
lastTick = tick;
|
|
2140
|
+
progressedAt = clock.now();
|
|
2141
|
+
}
|
|
2142
|
+
const fault = observation.host?.after?.fault;
|
|
2143
|
+
if (observation.host?.after?.connectionStatus !== "connected" || observation.host.after.runtimeState !== "playing" || tick !== null && clock.now() - progressedAt > 5e3)
|
|
2144
|
+
return this.terminate(
|
|
2145
|
+
run,
|
|
2146
|
+
"host_not_advancing",
|
|
2147
|
+
fault ? `The observed host stopped advancing: ${describeHostRuntimeFault(fault)}` : "The observed host stopped advancing.",
|
|
2148
|
+
fault ?? void 0
|
|
2149
|
+
);
|
|
2150
|
+
const step = ++run.record.counters.steps;
|
|
2151
|
+
const counters = this.seatRecord(run, seat).counters;
|
|
2152
|
+
const decisionStarted = performance.now();
|
|
2153
|
+
const decisionDeadline = decisionStarted + Math.min(
|
|
2154
|
+
profile.timing.decisionMs,
|
|
2155
|
+
Math.max(1, run.deadline - decisionStarted)
|
|
2156
|
+
);
|
|
2157
|
+
const decision = (async () => {
|
|
2158
|
+
if (policy.busy()) {
|
|
2159
|
+
counters.blocked++;
|
|
2160
|
+
throw new Error("policy_busy: Previous decision has not returned.");
|
|
2161
|
+
}
|
|
2162
|
+
const receipts = run.receipts.filter(
|
|
2163
|
+
(receipt) => receipt.seatId === seat.id && receipt.sequence > seat.policyCursor
|
|
2164
|
+
);
|
|
2165
|
+
seat.policyCursor = seat.sequence;
|
|
2166
|
+
counters.decisions++;
|
|
2167
|
+
return policy.decide(
|
|
2168
|
+
{
|
|
2169
|
+
observation,
|
|
2170
|
+
seatId: seat.id,
|
|
2171
|
+
intent: this.seatRecord(run, seat).intent,
|
|
2172
|
+
answer: seat.lastAnswer,
|
|
2173
|
+
step,
|
|
2174
|
+
elapsedMs: this.elapsed(run),
|
|
2175
|
+
receipts
|
|
2176
|
+
},
|
|
2177
|
+
decisionDeadline - decisionStarted
|
|
2178
|
+
);
|
|
2179
|
+
})();
|
|
2180
|
+
const pending = this.playDecision(run, seat, {
|
|
2181
|
+
observation,
|
|
2182
|
+
step,
|
|
2183
|
+
started,
|
|
2184
|
+
decisionStarted,
|
|
2185
|
+
decisionDeadline,
|
|
2186
|
+
decision
|
|
2187
|
+
}).catch((error) => this.failed(run, error)).finally(() => {
|
|
2188
|
+
inFlight.delete(seat.id);
|
|
2189
|
+
});
|
|
2190
|
+
inFlight.set(seat.id, pending);
|
|
2191
|
+
await decision.catch(() => void 0);
|
|
2192
|
+
}
|
|
2193
|
+
if (inFlight.size > 0 && (inFlight.size === run.seats.length || request.kind === "test" && run.record.counters.steps >= request.budget.steps))
|
|
2194
|
+
await Promise.race(inFlight.values());
|
|
2195
|
+
await clock.wait(
|
|
2196
|
+
Math.max(0, profile.timing.intervalMs - (clock.now() - roundStarted)),
|
|
2197
|
+
run.abort.signal
|
|
2198
|
+
).catch((error) => {
|
|
2199
|
+
if (!run.abort.signal.aborted) throw error;
|
|
2200
|
+
});
|
|
2201
|
+
}
|
|
2202
|
+
}
|
|
2203
|
+
async playDecision(run, seat, {
|
|
2204
|
+
observation,
|
|
2205
|
+
step,
|
|
2206
|
+
started,
|
|
2207
|
+
decisionStarted,
|
|
2208
|
+
decisionDeadline,
|
|
2209
|
+
decision: pendingDecision
|
|
2210
|
+
}) {
|
|
2211
|
+
const profile = run.players;
|
|
2212
|
+
if (!profile) throw new Error("Run players are not initialized.");
|
|
2213
|
+
const request = run.record.request;
|
|
2214
|
+
const tick = observation.ticks.after;
|
|
2215
|
+
const counters = this.seatRecord(run, seat).counters;
|
|
2216
|
+
let control;
|
|
2217
|
+
try {
|
|
2218
|
+
const decision = await pendingDecision;
|
|
2219
|
+
if (run.abort.signal.aborted) return;
|
|
2220
|
+
let answer;
|
|
2221
|
+
if ("ask" in decision) {
|
|
2222
|
+
seat.lastAnswer = null;
|
|
2223
|
+
answer = await this.answerFor(
|
|
2224
|
+
run,
|
|
2225
|
+
seat,
|
|
2226
|
+
decision.ask,
|
|
2227
|
+
decisionDeadline
|
|
2228
|
+
);
|
|
2229
|
+
if (run.abort.signal.aborted) return;
|
|
2230
|
+
control = answer.control;
|
|
2231
|
+
seat.lastAnswer = {
|
|
2232
|
+
choice: answer.choice,
|
|
2233
|
+
confidence: answer.confidence
|
|
2234
|
+
};
|
|
2235
|
+
} else control = decision.control;
|
|
2236
|
+
if (run.abort.signal.aborted) return;
|
|
2237
|
+
await this.trace(run, {
|
|
2238
|
+
kind: "policy_decision",
|
|
2239
|
+
seatId: seat.id,
|
|
2240
|
+
step,
|
|
2241
|
+
durationMs: performance.now() - decisionStarted,
|
|
2242
|
+
...decision.diagnostics ? { diagnostics: decision.diagnostics } : {},
|
|
2243
|
+
...answer ? {
|
|
2244
|
+
answer: {
|
|
2245
|
+
choice: answer.choice,
|
|
2246
|
+
confidence: answer.confidence,
|
|
2247
|
+
durationMs: answer.durationMs,
|
|
2248
|
+
control: answer.control,
|
|
2249
|
+
...answer.note ? { note: answer.note } : {}
|
|
2250
|
+
}
|
|
2251
|
+
} : {}
|
|
2252
|
+
});
|
|
2253
|
+
this.pruneReceipts(run);
|
|
2254
|
+
} catch (error) {
|
|
2255
|
+
if (run.abort.signal.aborted) return;
|
|
2256
|
+
if (!(error instanceof Error) || !/^(policy_(timeout|busy)|decision_failed):/.test(error.message))
|
|
2257
|
+
throw error;
|
|
2258
|
+
if (error.message.startsWith("policy_timeout:")) counters.timeout++;
|
|
2259
|
+
run.record.counters.missed++;
|
|
2260
|
+
const reason = error.message.slice(0, 300);
|
|
2261
|
+
await this.trace(run, {
|
|
2262
|
+
kind: "decision_missed",
|
|
2263
|
+
seatId: seat.id,
|
|
2264
|
+
step,
|
|
2265
|
+
reason
|
|
2266
|
+
});
|
|
2267
|
+
await this.control(run, seat, observation, { kind: "release" }, "play");
|
|
2268
|
+
if (++seat.misses >= 3)
|
|
2269
|
+
return this.terminate(
|
|
2270
|
+
run,
|
|
2271
|
+
"policy_unresponsive",
|
|
2272
|
+
`Seat ${seat.id} missed three consecutive decision opportunities. Last: ${reason}`
|
|
2273
|
+
);
|
|
2274
|
+
return;
|
|
2275
|
+
}
|
|
2276
|
+
if (run.abort.signal.aborted) return;
|
|
2277
|
+
seat.misses = 0;
|
|
2278
|
+
const operation = control.kind === "release" ? { kind: "release" } : control.kind === "input" ? {
|
|
2279
|
+
...control,
|
|
2280
|
+
ttlMs: profile.timing.inputTtlMs,
|
|
2281
|
+
deadlineMs: this.deadline(observation)
|
|
2282
|
+
} : { ...control, deadlineMs: this.deadline(observation) };
|
|
2283
|
+
if (operation.kind === "action" && request.kind === "test" && !run.record.profile?.actions.includes(operation.actionId))
|
|
2284
|
+
throw new Error(
|
|
2285
|
+
"policy_action_forbidden: Decision requested an action outside the profile."
|
|
2286
|
+
);
|
|
2287
|
+
const receipt = await this.control(
|
|
2288
|
+
run,
|
|
2289
|
+
seat,
|
|
2290
|
+
observation,
|
|
2291
|
+
operation,
|
|
2292
|
+
"play"
|
|
2293
|
+
);
|
|
2294
|
+
if (receipt.status === "unconfirmed")
|
|
2295
|
+
throw new Error(`control_unconfirmed: ${receipt.reason}`);
|
|
2296
|
+
if (receipt.status === "rejected") {
|
|
2297
|
+
if (receipt.reason === "stale_identity")
|
|
2298
|
+
return this.terminate(
|
|
2299
|
+
run,
|
|
2300
|
+
"runtime_replaced",
|
|
2301
|
+
"The game runtime was replaced."
|
|
2302
|
+
);
|
|
2303
|
+
if (receipt.reason !== "stale_decision")
|
|
2304
|
+
throw new Error(`control_rejected: ${receipt.reason}`);
|
|
2305
|
+
run.record.counters.missed++;
|
|
2306
|
+
await this.control(run, seat, observation, { kind: "release" }, "play");
|
|
2307
|
+
if (++seat.staleDecisions >= 3)
|
|
2308
|
+
return this.terminate(
|
|
2309
|
+
run,
|
|
2310
|
+
"decision_latency",
|
|
2311
|
+
`Seat ${seat.id} repeatedly arrived too late to apply.`
|
|
2312
|
+
);
|
|
2313
|
+
} else seat.staleDecisions = 0;
|
|
2314
|
+
await this.trace(run, {
|
|
2315
|
+
kind: "decision",
|
|
2316
|
+
seatId: seat.id,
|
|
2317
|
+
step,
|
|
2318
|
+
observationId: observation.id,
|
|
2319
|
+
tick,
|
|
2320
|
+
durationMs: performance.now() - started
|
|
2321
|
+
});
|
|
2322
|
+
}
|
|
2323
|
+
failed(run, error) {
|
|
2324
|
+
if (run.abort.signal.aborted) return;
|
|
2325
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
2326
|
+
const stopped = error instanceof CurrentRoomStopped;
|
|
2327
|
+
if (stopped) run.record.stopRequestedAt ??= (/* @__PURE__ */ new Date()).toISOString();
|
|
2328
|
+
void this.terminate(
|
|
2329
|
+
run,
|
|
2330
|
+
stopped ? "stopped" : failureReason(message),
|
|
2331
|
+
message
|
|
2332
|
+
).catch((failure) => console.error(failure));
|
|
2333
|
+
}
|
|
2334
|
+
terminate(run, reason, message, hostFault) {
|
|
2335
|
+
return run.termination ??= (async () => {
|
|
2336
|
+
run.record.abortedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
2337
|
+
run.abort.abort();
|
|
2338
|
+
clearTimeout(run.timer);
|
|
2339
|
+
run.record.state = "stopping";
|
|
2340
|
+
run.record.end = {
|
|
2341
|
+
reason,
|
|
2342
|
+
...run.record.request.kind === "test" ? { outcome: "inconclusive" } : {},
|
|
2343
|
+
message,
|
|
2344
|
+
...hostFault ? { hostFault } : {}
|
|
2345
|
+
};
|
|
2346
|
+
const cleanup = {
|
|
2347
|
+
seats: [],
|
|
2348
|
+
errors: [],
|
|
2349
|
+
participantsClosed: true
|
|
2350
|
+
};
|
|
2351
|
+
const attempt = async (operation) => {
|
|
2352
|
+
try {
|
|
2353
|
+
return await operation();
|
|
2354
|
+
} catch (error) {
|
|
2355
|
+
cleanup.errors.push(
|
|
2356
|
+
error instanceof Error ? error.message : String(error)
|
|
2357
|
+
);
|
|
2358
|
+
return void 0;
|
|
2359
|
+
}
|
|
2360
|
+
};
|
|
2361
|
+
await attempt(async () => {
|
|
2362
|
+
await run.admission;
|
|
2363
|
+
await run.startup;
|
|
2364
|
+
});
|
|
2365
|
+
await Promise.allSettled([...run.watches.values()]);
|
|
2366
|
+
const policy = run.policy;
|
|
2367
|
+
if (policy && run.record.request.kind === "test")
|
|
2368
|
+
await attempt(() => policy.stop());
|
|
2369
|
+
await Promise.allSettled([...run.effects]);
|
|
2370
|
+
const evaluationInFlight = run.evaluation;
|
|
2371
|
+
if (evaluationInFlight) await attempt(() => evaluationInFlight);
|
|
2372
|
+
if (run.session) {
|
|
2373
|
+
const session = run.session;
|
|
2374
|
+
for (const seat of run.seats) {
|
|
2375
|
+
const seatCleanup = { seatId: seat.id };
|
|
2376
|
+
cleanup.seats.push(seatCleanup);
|
|
2377
|
+
if (seat.expected) {
|
|
2378
|
+
const expected = seat.expected;
|
|
2379
|
+
seatCleanup.release = await attempt(
|
|
2380
|
+
() => this.control(
|
|
2381
|
+
run,
|
|
2382
|
+
seat,
|
|
2383
|
+
{ identity: expected, id: "cleanup" },
|
|
2384
|
+
{ kind: "release" },
|
|
2385
|
+
"cleanup"
|
|
2386
|
+
)
|
|
2387
|
+
);
|
|
2388
|
+
}
|
|
2389
|
+
seat.policyCursor = seat.sequence;
|
|
2390
|
+
}
|
|
2391
|
+
await this.finishClip(run);
|
|
2392
|
+
if (run.record.request.kind === "test") {
|
|
2393
|
+
const primary = run.seats[0];
|
|
2394
|
+
let finalObservation;
|
|
2395
|
+
try {
|
|
2396
|
+
if (!primary || !run.players)
|
|
2397
|
+
throw new Error("Run has no initialized observation seat.");
|
|
2398
|
+
const before = await this.evaluationObservation(run, false);
|
|
2399
|
+
const settleUntil = session.clock.now() + 2e3;
|
|
2400
|
+
let settled;
|
|
2401
|
+
do {
|
|
2402
|
+
await session.clock.wait(run.players.timing.intervalMs);
|
|
2403
|
+
settled = await this.evaluationObservation(run, false);
|
|
2404
|
+
} while (before.ticks.after !== null && settled.ticks.after === before.ticks.after && session.clock.now() < settleUntil);
|
|
2405
|
+
if (before.ticks.after !== null && settled.ticks.after === before.ticks.after) {
|
|
2406
|
+
const fault = settled.host?.after?.fault;
|
|
2407
|
+
if (fault) run.record.end.hostFault = fault;
|
|
2408
|
+
throw new Error(
|
|
2409
|
+
fault ? `The host did not advance after input release: ${describeHostRuntimeFault(fault)}` : "The host did not advance after input release."
|
|
2410
|
+
);
|
|
2411
|
+
}
|
|
2412
|
+
finalObservation = await this.evaluationObservation(run, true);
|
|
2413
|
+
if (!run.room && run.record.expected) {
|
|
2414
|
+
const result = await readHostInputLog(
|
|
2415
|
+
(request) => {
|
|
2416
|
+
if (!session.requestHost)
|
|
2417
|
+
throw new Error(
|
|
2418
|
+
"host_unavailable: Studio couldn't reach the game."
|
|
2419
|
+
);
|
|
2420
|
+
return session.requestHost(request, 5e3);
|
|
2421
|
+
},
|
|
2422
|
+
run.record.expected,
|
|
2423
|
+
{
|
|
2424
|
+
scope: finalObservation.scope,
|
|
2425
|
+
controllerId: finalObservation.controllerId
|
|
2426
|
+
}
|
|
2427
|
+
);
|
|
2428
|
+
run.record.evidence ??= { observation: null, error: null };
|
|
2429
|
+
if (result.status === "not-replayable")
|
|
2430
|
+
run.record.evidence.replay = {
|
|
2431
|
+
reason: result.reason,
|
|
2432
|
+
message: result.message
|
|
2433
|
+
};
|
|
2434
|
+
else {
|
|
2435
|
+
if (!result.observation)
|
|
2436
|
+
throw new Error(
|
|
2437
|
+
"The recording has no cut-bound observation."
|
|
2438
|
+
);
|
|
2439
|
+
finalObservation = {
|
|
2440
|
+
...result.observation,
|
|
2441
|
+
visual: finalObservation.visual
|
|
2442
|
+
};
|
|
2443
|
+
const inputSource = `${JSON.stringify(result.log)}
|
|
2444
|
+
`;
|
|
2445
|
+
const file2 = await open2(
|
|
2446
|
+
path3.join(run.directory, "input-log.json"),
|
|
2447
|
+
"w",
|
|
2448
|
+
384
|
|
2449
|
+
);
|
|
2450
|
+
try {
|
|
2451
|
+
await file2.writeFile(inputSource);
|
|
2452
|
+
} finally {
|
|
2453
|
+
await file2.close();
|
|
2454
|
+
}
|
|
2455
|
+
run.record.evidence.inputLog = {
|
|
2456
|
+
path: `.airjam/artifacts/runs/${run.record.runId}/input-log.json`,
|
|
2457
|
+
sha256: createHash2("sha256").update(inputSource).digest("hex"),
|
|
2458
|
+
ticks: result.log.ticks,
|
|
2459
|
+
stepMs: result.log.stepMs,
|
|
2460
|
+
entries: result.log.entries.length,
|
|
2461
|
+
fromTick: run.fromTick ?? 0,
|
|
2462
|
+
full: result.full
|
|
2463
|
+
};
|
|
2464
|
+
}
|
|
2465
|
+
}
|
|
2466
|
+
const source = `${JSON.stringify(finalObservation)}
|
|
2467
|
+
`;
|
|
2468
|
+
const file = await open2(
|
|
2469
|
+
path3.join(run.directory, "final-observation.json"),
|
|
2470
|
+
"w",
|
|
2471
|
+
384
|
|
2472
|
+
);
|
|
2473
|
+
try {
|
|
2474
|
+
await file.writeFile(source);
|
|
2475
|
+
} finally {
|
|
2476
|
+
await file.close();
|
|
2477
|
+
}
|
|
2478
|
+
run.record.evidence = {
|
|
2479
|
+
...run.record.evidence,
|
|
2480
|
+
observation: {
|
|
2481
|
+
path: `.airjam/artifacts/runs/${run.record.runId}/final-observation.json`,
|
|
2482
|
+
sha256: createHash2("sha256").update(source).digest("hex")
|
|
2483
|
+
},
|
|
2484
|
+
error: null
|
|
2485
|
+
};
|
|
2486
|
+
const saveInputLog = run.room?.saveInputLog;
|
|
2487
|
+
if (saveInputLog)
|
|
2488
|
+
run.record.evidence.inputLog = {
|
|
2489
|
+
path: `.airjam/artifacts/runs/${run.record.runId}/input-log.json`,
|
|
2490
|
+
fromTick: run.fromTick ?? 0,
|
|
2491
|
+
...await saveInputLog(
|
|
2492
|
+
path3.join(run.directory, "input-log.json")
|
|
2493
|
+
)
|
|
2494
|
+
};
|
|
2495
|
+
} catch (error) {
|
|
2496
|
+
const message2 = error instanceof Error ? error.message : String(error);
|
|
2497
|
+
run.record.evidence = {
|
|
2498
|
+
...run.record.evidence,
|
|
2499
|
+
observation: null,
|
|
2500
|
+
error: message2
|
|
2501
|
+
};
|
|
2502
|
+
if (run.record.end.reason === "completed")
|
|
2503
|
+
run.record.end = {
|
|
2504
|
+
reason: failureReason(message2),
|
|
2505
|
+
outcome: "inconclusive",
|
|
2506
|
+
message: message2,
|
|
2507
|
+
...run.record.end.hostFault ? { hostFault: run.record.end.hostFault } : {}
|
|
2508
|
+
};
|
|
2509
|
+
}
|
|
2510
|
+
if (finalObservation && run.evaluator && run.playEvaluationSent)
|
|
2511
|
+
await attempt(() => this.evaluate(run, "final", finalObservation));
|
|
2512
|
+
const evaluator2 = run.evaluator;
|
|
2513
|
+
if (evaluator2) await attempt(() => evaluator2.stop());
|
|
2514
|
+
}
|
|
2515
|
+
if (run.record.request.kind === "test" && run.record.request.target.kind === "current" && run.record.profile && run.seats.length > 0 && run.seats.every((seat) => seat.expected)) {
|
|
2516
|
+
const steps = run.record.profile.handBack;
|
|
2517
|
+
cleanup.handBack = steps ? await attempt(
|
|
2518
|
+
() => this.runProfileSteps(run, session, steps, "cleanup")
|
|
2519
|
+
) ? "returned" : "failed" : "undeclared";
|
|
2520
|
+
}
|
|
2521
|
+
for (const seat of run.seats.slice(1)) {
|
|
2522
|
+
const extra = seat.extra;
|
|
2523
|
+
if (!extra)
|
|
2524
|
+
throw new Error("Additional run seat has no owned participant.");
|
|
2525
|
+
let disconnected = await attempt(() => extra.close());
|
|
2526
|
+
if (!disconnected)
|
|
2527
|
+
disconnected = await attempt(() => extra.forceClose());
|
|
2528
|
+
if (!disconnected) cleanup.participantsClosed = false;
|
|
2529
|
+
const receipt = cleanup.seats.find(
|
|
2530
|
+
(candidate) => candidate.seatId === seat.id
|
|
2531
|
+
);
|
|
2532
|
+
if (!receipt) throw new Error("Run seat has no cleanup receipt.");
|
|
2533
|
+
receipt.disconnection = disconnected;
|
|
2534
|
+
await attempt(
|
|
2535
|
+
() => this.trace(run, {
|
|
2536
|
+
kind: "seat_left",
|
|
2537
|
+
seatId: seat.id,
|
|
2538
|
+
disconnection: disconnected
|
|
2539
|
+
})
|
|
2540
|
+
);
|
|
2541
|
+
}
|
|
2542
|
+
let closed = await attempt(() => session.close());
|
|
2543
|
+
if (!closed?.closed) {
|
|
2544
|
+
cleanup.forced = true;
|
|
2545
|
+
closed = await attempt(() => session.forceClose());
|
|
2546
|
+
}
|
|
2547
|
+
if (closed) {
|
|
2548
|
+
run.closed = closed;
|
|
2549
|
+
cleanup.close = {
|
|
2550
|
+
closed: closed.closed,
|
|
2551
|
+
disconnection: closed.disconnection
|
|
2552
|
+
};
|
|
2553
|
+
run.record.session = gameRunSessionIdentitySchema.parse(
|
|
2554
|
+
closed.session
|
|
2555
|
+
);
|
|
2556
|
+
}
|
|
2557
|
+
}
|
|
2558
|
+
if (policy && run.record.request.kind === "play")
|
|
2559
|
+
await attempt(() => policy.stop());
|
|
2560
|
+
const evaluator = run.evaluator;
|
|
2561
|
+
if (!run.session && evaluator) await attempt(() => evaluator.stop());
|
|
2562
|
+
const scopes = await Promise.allSettled(
|
|
2563
|
+
run.scopes.map((close) => close())
|
|
2564
|
+
);
|
|
2565
|
+
cleanup.processesClosed = scopes.every(
|
|
2566
|
+
(result) => result.status === "fulfilled"
|
|
2567
|
+
);
|
|
2568
|
+
try {
|
|
2569
|
+
assertProcessScopesConfirmed();
|
|
2570
|
+
} catch (error) {
|
|
2571
|
+
cleanup.processesClosed = false;
|
|
2572
|
+
cleanup.errors.push(
|
|
2573
|
+
error instanceof Error ? error.message : String(error)
|
|
2574
|
+
);
|
|
2575
|
+
}
|
|
2576
|
+
for (const result of scopes)
|
|
2577
|
+
if (result.status === "rejected")
|
|
2578
|
+
cleanup.errors.push(
|
|
2579
|
+
result.reason instanceof Error ? result.reason.message : String(result.reason)
|
|
2580
|
+
);
|
|
2581
|
+
const evaluation = run.record.evaluation;
|
|
2582
|
+
if (evaluation?.play?.status === "failed" || evaluation?.final?.status === "failed") {
|
|
2583
|
+
run.record.end = {
|
|
2584
|
+
reason: "failed",
|
|
2585
|
+
outcome: "failed",
|
|
2586
|
+
message: (evaluation.final?.status === "failed" ? evaluation.final : evaluation.play)?.message ?? "Scenario failed."
|
|
2587
|
+
};
|
|
2588
|
+
} else if (run.record.end.reason === "completed") {
|
|
2589
|
+
const released = cleanup.seats.length === run.record.seats.length && cleanup.seats.every((seat) => seat.release?.status === "applied");
|
|
2590
|
+
run.record.end.outcome = evaluation?.final?.status === "passed" && run.record.evidence?.observation && cleanup.errors.length === 0 && cleanup.close?.closed && released && cleanup.participantsClosed && cleanup.processesClosed ? "passed" : "inconclusive";
|
|
2591
|
+
if (run.record.end.outcome === "inconclusive")
|
|
2592
|
+
run.record.end.message = cleanup.errors[0] ?? (!released ? "Cleanup did not confirm every input release." : "The final evaluation did not confirm the earlier pass.");
|
|
2593
|
+
}
|
|
2594
|
+
if (run.build && run.record.build) {
|
|
2595
|
+
try {
|
|
2596
|
+
await verifyPinnedGameBuild(run.build);
|
|
2597
|
+
run.record.build.integrity = "verified";
|
|
2598
|
+
} catch (error) {
|
|
2599
|
+
run.record.build.integrity = "changed";
|
|
2600
|
+
run.record.end = {
|
|
2601
|
+
reason: "runtime_replaced",
|
|
2602
|
+
...run.record.request.kind === "test" ? { outcome: "inconclusive" } : {},
|
|
2603
|
+
message: error instanceof Error ? error.message : String(error)
|
|
2604
|
+
};
|
|
2605
|
+
}
|
|
2606
|
+
}
|
|
2607
|
+
run.record.cleanup = cleanup;
|
|
2608
|
+
run.record.endedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
2609
|
+
run.record.state = "ended";
|
|
2610
|
+
if (run.traceTruncated)
|
|
2611
|
+
run.record.end = {
|
|
2612
|
+
reason: "trace_budget",
|
|
2613
|
+
...run.record.request.kind === "test" ? { outcome: "inconclusive" } : {},
|
|
2614
|
+
message: "Trace byte allowance was exhausted; evidence is incomplete."
|
|
2615
|
+
};
|
|
2616
|
+
await attempt(
|
|
2617
|
+
() => this.trace(run, { kind: "ended", end: run.record.end, cleanup })
|
|
2618
|
+
);
|
|
2619
|
+
await attempt(async () => {
|
|
2620
|
+
await run.tracing;
|
|
2621
|
+
const file = run.traceFile;
|
|
2622
|
+
run.traceFile = null;
|
|
2623
|
+
await file?.close();
|
|
2624
|
+
});
|
|
2625
|
+
await attempt(async () => {
|
|
2626
|
+
const bytes = await readGameRunArtifact(
|
|
2627
|
+
this.options.projectDir,
|
|
2628
|
+
run.record.runId,
|
|
2629
|
+
"trace.ndjson",
|
|
2630
|
+
MAXIMUM_GAME_RUN_TRACE_BYTES
|
|
2631
|
+
);
|
|
2632
|
+
if (!bytes) throw new Error("Run trace is missing.");
|
|
2633
|
+
run.record.evidence ??= { observation: null, error: null };
|
|
2634
|
+
run.record.evidence.trace = {
|
|
2635
|
+
path: `.airjam/artifacts/runs/${run.record.runId}/trace.ndjson`,
|
|
2636
|
+
sha256: createHash2("sha256").update(bytes).digest("hex"),
|
|
2637
|
+
bytes: bytes.byteLength,
|
|
2638
|
+
truncated: run.traceTruncated
|
|
2639
|
+
};
|
|
2640
|
+
});
|
|
2641
|
+
if (run.record.end.outcome === "passed" && (cleanup.errors.length || run.traceTruncated))
|
|
2642
|
+
run.record.end = {
|
|
2643
|
+
reason: run.traceTruncated ? "trace_budget" : "error",
|
|
2644
|
+
outcome: "inconclusive",
|
|
2645
|
+
message: cleanup.errors[0] ?? "Trace byte allowance was exhausted."
|
|
2646
|
+
};
|
|
2647
|
+
await this.persist(run);
|
|
2648
|
+
if (run.session && cleanup.close?.closed && cleanup.participantsClosed)
|
|
2649
|
+
this.options.sessionClosed(run.session.summary.gameSessionId);
|
|
2650
|
+
this.prune();
|
|
2651
|
+
})().finally(() => run.finished.abort());
|
|
2652
|
+
}
|
|
2653
|
+
};
|
|
2654
|
+
|
|
2655
|
+
// src/game-session-runtime.ts
|
|
2656
|
+
import { seatViewSchema } from "@air-jam/sdk/room-protocol";
|
|
2657
|
+
import { randomUUID as randomUUID4 } from "crypto";
|
|
2658
|
+
import path4 from "path";
|
|
2659
|
+
|
|
2660
|
+
// src/game-action-observation.ts
|
|
2661
|
+
var isHostAcknowledgementObservationGap = (acknowledgement) => acknowledgement.status === "rejected" && (acknowledgement.reason === "host_ack_missing" || acknowledgement.reason === "host_ack_timeout");
|
|
2662
|
+
var stableStoreSnapshotFingerprint = (snapshot) => JSON.stringify(
|
|
2663
|
+
snapshot.rawStores.map((entry) => ({
|
|
2664
|
+
storeDomain: entry.storeDomain,
|
|
2665
|
+
revision: entry.revision
|
|
2666
|
+
})).sort((left, right) => left.storeDomain.localeCompare(right.storeDomain))
|
|
2667
|
+
);
|
|
2668
|
+
var stableStoreSnapshotDataFingerprint = (snapshot) => JSON.stringify(
|
|
2669
|
+
snapshot.rawStores.map((entry) => ({
|
|
2670
|
+
storeDomain: entry.storeDomain,
|
|
2671
|
+
data: entry.data
|
|
2672
|
+
})).sort((left, right) => left.storeDomain.localeCompare(right.storeDomain))
|
|
2673
|
+
);
|
|
2674
|
+
var computeGameSnapshotObservation = ({
|
|
2675
|
+
snapshotBefore,
|
|
2676
|
+
snapshotAfter
|
|
2677
|
+
}) => {
|
|
2678
|
+
const replaced = snapshotBefore.runtimeId !== snapshotAfter.runtimeId ? "runtime_replaced" : snapshotBefore.contractId !== snapshotAfter.contractId ? "contract_changed" : null;
|
|
2679
|
+
if (replaced)
|
|
2680
|
+
return { snapshotAfterStatus: replaced, observedStateChange: false };
|
|
2681
|
+
const fingerprintBefore = stableStoreSnapshotFingerprint(snapshotBefore);
|
|
2682
|
+
const fingerprintAfter = stableStoreSnapshotFingerprint(snapshotAfter);
|
|
2683
|
+
const dataFingerprintBefore = stableStoreSnapshotDataFingerprint(snapshotBefore);
|
|
2684
|
+
const dataFingerprintAfter = stableStoreSnapshotDataFingerprint(snapshotAfter);
|
|
2685
|
+
const projectedSnapshotBefore = JSON.stringify(snapshotBefore.snapshot);
|
|
2686
|
+
const projectedSnapshotAfter = JSON.stringify(snapshotAfter.snapshot);
|
|
2687
|
+
return {
|
|
2688
|
+
snapshotAfterStatus: fingerprintBefore === fingerprintAfter ? "no-new-commit-before-timeout" : "committed-update-observed",
|
|
2689
|
+
observedStateChange: dataFingerprintBefore !== dataFingerprintAfter || projectedSnapshotBefore !== projectedSnapshotAfter
|
|
2690
|
+
};
|
|
2691
|
+
};
|
|
2692
|
+
var classifyGameActionOutcome = ({
|
|
2693
|
+
acknowledgement,
|
|
2694
|
+
observedStateChange
|
|
2695
|
+
}) => {
|
|
2696
|
+
if (!isHostAcknowledgementObservationGap(acknowledgement)) {
|
|
2697
|
+
return {
|
|
2698
|
+
acknowledgementObservation: "host-acknowledged",
|
|
2699
|
+
outcome: acknowledgement.status === "accepted" ? "accepted" : "rejected"
|
|
2700
|
+
};
|
|
2701
|
+
}
|
|
2702
|
+
return {
|
|
2703
|
+
acknowledgementObservation: "host-acknowledgement-not-observed",
|
|
2704
|
+
outcome: observedStateChange ? "acknowledgement-not-observed-state-changed" : "acknowledgement-not-observed-no-state-change-observed"
|
|
2705
|
+
};
|
|
2706
|
+
};
|
|
2707
|
+
|
|
2708
|
+
// src/game-session-operations.ts
|
|
2709
|
+
var GameSessionOperations = class {
|
|
2710
|
+
tail = Promise.resolve();
|
|
2711
|
+
controller = new AbortController();
|
|
2712
|
+
failure = null;
|
|
2713
|
+
queued = 0;
|
|
2714
|
+
run(timeoutMs, operation) {
|
|
2715
|
+
if (this.failure) return Promise.reject(this.failure);
|
|
2716
|
+
if (this.queued >= 32)
|
|
2717
|
+
return Promise.reject(
|
|
2718
|
+
new Error("session_busy: Too many queued game operations.")
|
|
2719
|
+
);
|
|
2720
|
+
this.queued++;
|
|
2721
|
+
const result = this.tail.then(async () => {
|
|
2722
|
+
if (this.failure) throw this.failure;
|
|
2723
|
+
let timer;
|
|
2724
|
+
const aborted = new Promise((_, reject) => {
|
|
2725
|
+
const fail = () => reject(this.failure ?? new Error("session_closed"));
|
|
2726
|
+
this.controller.signal.addEventListener("abort", fail, { once: true });
|
|
2727
|
+
timer = setTimeout(() => {
|
|
2728
|
+
this.failure = new Error(
|
|
2729
|
+
"evaluation_timeout: Game operation exceeded its deadline; close this session before opening another."
|
|
2730
|
+
);
|
|
2731
|
+
this.controller.abort();
|
|
2732
|
+
}, timeoutMs);
|
|
2733
|
+
this.cancelCurrent = () => {
|
|
2734
|
+
clearTimeout(timer);
|
|
2735
|
+
this.controller.signal.removeEventListener("abort", fail);
|
|
2736
|
+
};
|
|
2737
|
+
});
|
|
2738
|
+
try {
|
|
2739
|
+
return await Promise.race([operation(this.controller.signal), aborted]);
|
|
2740
|
+
} catch (error) {
|
|
2741
|
+
if (error instanceof Error && /runtime_disconnected|evaluation_timeout|invalid_runtime_response/.test(
|
|
2742
|
+
error.message
|
|
2743
|
+
))
|
|
2744
|
+
this.failure = error;
|
|
2745
|
+
throw error;
|
|
2746
|
+
} finally {
|
|
2747
|
+
this.cancelCurrent();
|
|
2748
|
+
}
|
|
2749
|
+
});
|
|
2750
|
+
this.tail = result.catch(() => void 0).finally(() => {
|
|
2751
|
+
this.queued--;
|
|
2752
|
+
});
|
|
2753
|
+
return result;
|
|
2754
|
+
}
|
|
2755
|
+
cancelCurrent = () => {
|
|
2756
|
+
};
|
|
2757
|
+
close() {
|
|
2758
|
+
this.failure = new Error("session_closed: This game session is closed.");
|
|
2759
|
+
this.controller.abort();
|
|
2760
|
+
}
|
|
2761
|
+
};
|
|
2762
|
+
|
|
2763
|
+
// src/game-session-runtime.ts
|
|
2764
|
+
var claimOf = (controller) => {
|
|
2765
|
+
const instance = controller.welcome?.instance;
|
|
2766
|
+
if (typeof instance !== "string")
|
|
2767
|
+
throw new Error("current_room_scope: The room welcomed no seat to claim.");
|
|
2768
|
+
return { instance, seat: controller.controllerId };
|
|
2769
|
+
};
|
|
2770
|
+
function createGameSessionRuntime(ownerInstanceId = randomUUID4()) {
|
|
2771
|
+
const DEFAULT_TIMEOUT_MS = 5e3;
|
|
2772
|
+
const DEFAULT_SESSION_OPEN_TIMEOUT_MS = 3e4;
|
|
2773
|
+
const gameSessions = /* @__PURE__ */ new Map();
|
|
2774
|
+
const devProcessLeases = /* @__PURE__ */ new Map();
|
|
2775
|
+
const acquireDevProcessLease = async (options) => {
|
|
2776
|
+
if (options.controllerJoinUrl || options.roomId?.trim()) {
|
|
2777
|
+
return null;
|
|
2778
|
+
}
|
|
2779
|
+
const started = await startDev({
|
|
2780
|
+
cwd: options.cwd,
|
|
2781
|
+
gameId: options.gameId,
|
|
2782
|
+
mode: options.mode,
|
|
2783
|
+
secure: options.secure
|
|
2784
|
+
});
|
|
2785
|
+
const processId = started.process.id;
|
|
2786
|
+
const existing = devProcessLeases.get(processId);
|
|
2787
|
+
devProcessLeases.set(processId, {
|
|
2788
|
+
cwd: started.process.cwd,
|
|
2789
|
+
referenceCount: (existing?.referenceCount ?? 0) + 1,
|
|
2790
|
+
stopOnZero: existing?.stopOnZero ?? !started.reusedExistingProcess
|
|
2791
|
+
});
|
|
2792
|
+
return processId;
|
|
2793
|
+
};
|
|
2794
|
+
const releaseDevProcessLease = async (processId) => {
|
|
2795
|
+
const lease = devProcessLeases.get(processId);
|
|
2796
|
+
if (!lease) {
|
|
2797
|
+
return;
|
|
2798
|
+
}
|
|
2799
|
+
if (lease.referenceCount > 1) {
|
|
2800
|
+
devProcessLeases.set(processId, {
|
|
2801
|
+
...lease,
|
|
2802
|
+
referenceCount: lease.referenceCount - 1
|
|
2803
|
+
});
|
|
2804
|
+
return;
|
|
2805
|
+
}
|
|
2806
|
+
if (lease.stopOnZero) {
|
|
2807
|
+
await stopDev({ cwd: lease.cwd, processId });
|
|
2808
|
+
}
|
|
2809
|
+
devProcessLeases.delete(processId);
|
|
2810
|
+
};
|
|
2811
|
+
const toSessionActionId = (lane, actionId) => `${lane}:${actionId}`;
|
|
2812
|
+
const describeSessionActions = (actions, ownsHost) => actions.map((action) => ({
|
|
2813
|
+
actionId: toSessionActionId(
|
|
2814
|
+
action.target.kind === "host" ? "host" : "player",
|
|
2815
|
+
action.actionId
|
|
2816
|
+
),
|
|
2817
|
+
lane: action.target.kind === "host" ? "host" : "player",
|
|
2818
|
+
source: "semantic-game",
|
|
2819
|
+
description: action.description,
|
|
2820
|
+
availability: action.target.kind === "host" && !ownsHost ? "host_runtime_not_owned: Host actions require an owned host runtime." : action.availability,
|
|
2821
|
+
payload: {
|
|
2822
|
+
kind: action.payload.kind,
|
|
2823
|
+
description: action.payload.description,
|
|
2824
|
+
...action.payload.allowedValues ? { allowedValues: [...action.payload.allowedValues] } : {}
|
|
2825
|
+
},
|
|
2826
|
+
resultDescription: action.resultDescription
|
|
2827
|
+
}));
|
|
2828
|
+
const getRequiredGameSession = (gameSessionId) => {
|
|
2829
|
+
const session = gameSessions.get(gameSessionId);
|
|
2830
|
+
if (!session) {
|
|
2831
|
+
throw new Error(
|
|
2832
|
+
`Unknown Air Jam game session "${gameSessionId}". Open a game session first.`
|
|
2833
|
+
);
|
|
2834
|
+
}
|
|
2835
|
+
return session;
|
|
2836
|
+
};
|
|
2837
|
+
const updateSummary = (session, overrides) => {
|
|
2838
|
+
session.summary = { ...session.summary, ...overrides };
|
|
2839
|
+
};
|
|
2840
|
+
const openGameSession = async (options = {}, host, build, onScope, settings, game) => {
|
|
2841
|
+
const devProcessId = build ? null : await acquireDevProcessLease(options);
|
|
2842
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_SESSION_OPEN_TIMEOUT_MS;
|
|
2843
|
+
let controllerSession;
|
|
2844
|
+
try {
|
|
2845
|
+
controllerSession = await connectController(
|
|
2846
|
+
{ ...options, timeoutMs },
|
|
2847
|
+
{ build, onScope, settings }
|
|
2848
|
+
);
|
|
2849
|
+
} catch (error) {
|
|
2850
|
+
if (devProcessId) {
|
|
2851
|
+
await releaseDevProcessLease(devProcessId).catch(() => void 0);
|
|
2852
|
+
}
|
|
2853
|
+
throw error;
|
|
2854
|
+
}
|
|
2855
|
+
const operations = new GameSessionOperations();
|
|
2856
|
+
try {
|
|
2857
|
+
if (host?.claimSeat)
|
|
2858
|
+
await host.claimSeat(claimOf(controllerSession), timeoutMs);
|
|
2859
|
+
const runtime = await resolveControllerSessionGameRuntime({
|
|
2860
|
+
controllerSessionId: controllerSession.controllerSessionId,
|
|
2861
|
+
timeoutMs,
|
|
2862
|
+
game
|
|
2863
|
+
});
|
|
2864
|
+
const gameId = runtime.gameId ?? controllerSession.gameId ?? options.gameId ?? null;
|
|
2865
|
+
const ownsHost = !!host || ownsControllerSessionHost(controllerSession.controllerSessionId);
|
|
2866
|
+
const requestHost = host?.request ?? ((request, timeoutMs2, signal) => requestControllerHostAgent(
|
|
2867
|
+
controllerSession.controllerSessionId,
|
|
2868
|
+
request,
|
|
2869
|
+
timeoutMs2,
|
|
2870
|
+
signal
|
|
2871
|
+
));
|
|
2872
|
+
const live = ownsHost ? await operations.run(
|
|
2873
|
+
timeoutMs,
|
|
2874
|
+
(signal) => requestHost(
|
|
2875
|
+
{
|
|
2876
|
+
operation: "read",
|
|
2877
|
+
roomId: controllerSession.roomId,
|
|
2878
|
+
controllerId: controllerSession.controllerId
|
|
2879
|
+
},
|
|
2880
|
+
timeoutMs,
|
|
2881
|
+
signal
|
|
2882
|
+
)
|
|
2883
|
+
) : null;
|
|
2884
|
+
const contract = live?.operation === "read" ? live.snapshot : null;
|
|
2885
|
+
const gameActions = contract?.actions ?? [];
|
|
2886
|
+
const summary = {
|
|
2887
|
+
semanticAccess: host?.access ?? (ownsHost ? "owned-host" : "participant-only"),
|
|
2888
|
+
ownerInstanceId,
|
|
2889
|
+
gameSessionId: randomUUID4(),
|
|
2890
|
+
cwd: options.cwd ?? process.cwd(),
|
|
2891
|
+
gameId,
|
|
2892
|
+
controllerSessionId: controllerSession.controllerSessionId,
|
|
2893
|
+
projectMode: controllerSession.projectMode,
|
|
2894
|
+
mode: controllerSession.mode,
|
|
2895
|
+
topologyMode: controllerSession.topologyMode,
|
|
2896
|
+
secure: controllerSession.secure,
|
|
2897
|
+
process: controllerSession.process,
|
|
2898
|
+
roomId: controllerSession.roomId,
|
|
2899
|
+
controllerId: controllerSession.controllerId,
|
|
2900
|
+
controllerJoinUrl: controllerSession.controllerJoinUrl,
|
|
2901
|
+
socketOrigin: controllerSession.socketOrigin,
|
|
2902
|
+
connected: controllerSession.connected,
|
|
2903
|
+
connectedAt: controllerSession.connectedAt,
|
|
2904
|
+
disconnectedAt: controllerSession.disconnectedAt,
|
|
2905
|
+
disconnectReason: controllerSession.disconnectReason,
|
|
2906
|
+
hasAgentContract: Boolean(contract),
|
|
2907
|
+
actions: describeSessionActions(gameActions, ownsHost)
|
|
2908
|
+
};
|
|
2909
|
+
gameSessions.set(summary.gameSessionId, {
|
|
2910
|
+
summary,
|
|
2911
|
+
operations,
|
|
2912
|
+
requestHost,
|
|
2913
|
+
devProcessId
|
|
2914
|
+
});
|
|
2915
|
+
return summary;
|
|
2916
|
+
} catch (error) {
|
|
2917
|
+
operations.close();
|
|
2918
|
+
await disconnectController({
|
|
2919
|
+
controllerSessionId: controllerSession.controllerSessionId
|
|
2920
|
+
}).catch(() => void 0);
|
|
2921
|
+
if (devProcessId) {
|
|
2922
|
+
await releaseDevProcessLease(devProcessId).catch(() => void 0);
|
|
2923
|
+
}
|
|
2924
|
+
throw error;
|
|
2925
|
+
}
|
|
2926
|
+
};
|
|
2927
|
+
async function readLiveSnapshot(session, timeoutMs, signal) {
|
|
2928
|
+
const response = await session.requestHost(
|
|
2929
|
+
{
|
|
2930
|
+
operation: "read",
|
|
2931
|
+
roomId: session.summary.roomId,
|
|
2932
|
+
controllerId: session.summary.controllerId
|
|
2933
|
+
},
|
|
2934
|
+
timeoutMs,
|
|
2935
|
+
signal
|
|
2936
|
+
);
|
|
2937
|
+
if (response.operation !== "read")
|
|
2938
|
+
throw new Error("Invalid host read response.");
|
|
2939
|
+
const value = response.snapshot;
|
|
2940
|
+
updateSummary(session, {
|
|
2941
|
+
hasAgentContract: !!value,
|
|
2942
|
+
actions: describeSessionActions(value?.actions ?? [], true)
|
|
2943
|
+
});
|
|
2944
|
+
if (!value) return null;
|
|
2945
|
+
if (!session.summary.gameId)
|
|
2946
|
+
throw new Error("Owned game session has no game identity.");
|
|
2947
|
+
return {
|
|
2948
|
+
...value,
|
|
2949
|
+
controllerSessionId: session.summary.controllerSessionId,
|
|
2950
|
+
gameId: session.summary.gameId,
|
|
2951
|
+
runtimeStoreDomains: value.rawStores.map((store) => store.storeDomain)
|
|
2952
|
+
};
|
|
2953
|
+
}
|
|
2954
|
+
const readGameSession = async ({
|
|
2955
|
+
gameSessionId,
|
|
2956
|
+
timeoutMs = DEFAULT_TIMEOUT_MS
|
|
2957
|
+
}) => {
|
|
2958
|
+
const session = getRequiredGameSession(gameSessionId);
|
|
2959
|
+
return session.operations.run(timeoutMs, async (signal) => {
|
|
2960
|
+
const gameSnapshot = await readLiveSnapshot(session, timeoutMs, signal);
|
|
2961
|
+
const runtimeSnapshot = await readRuntimeSnapshot({
|
|
2962
|
+
controllerSessionId: session.summary.controllerSessionId,
|
|
2963
|
+
requestSync: false
|
|
2964
|
+
});
|
|
2965
|
+
updateSummary(session, {
|
|
2966
|
+
connected: runtimeSnapshot.connected,
|
|
2967
|
+
disconnectedAt: runtimeSnapshot.disconnectedAt,
|
|
2968
|
+
disconnectReason: runtimeSnapshot.disconnectReason,
|
|
2969
|
+
process: runtimeSnapshot.process
|
|
2970
|
+
});
|
|
2971
|
+
return { ...session.summary, runtimeSnapshot, gameSnapshot };
|
|
2972
|
+
});
|
|
2973
|
+
};
|
|
2974
|
+
const observeGameSession = async ({
|
|
2975
|
+
gameSessionId,
|
|
2976
|
+
timeoutMs = DEFAULT_TIMEOUT_MS,
|
|
2977
|
+
scope = "diagnostic",
|
|
2978
|
+
includeImage = true,
|
|
2979
|
+
expected
|
|
2980
|
+
}) => {
|
|
2981
|
+
const session = getRequiredGameSession(gameSessionId);
|
|
2982
|
+
if (session.summary.semanticAccess === "participant-only")
|
|
2983
|
+
throw new Error(
|
|
2984
|
+
"contract_runtime_not_owned: Observation requires an owned host or an explicit observation delegation."
|
|
2985
|
+
);
|
|
2986
|
+
return session.operations.run(timeoutMs, async (signal) => {
|
|
2987
|
+
const result = await session.requestHost(
|
|
2988
|
+
{
|
|
2989
|
+
operation: "observe",
|
|
2990
|
+
roomId: session.summary.roomId,
|
|
2991
|
+
controllerId: session.summary.controllerId,
|
|
2992
|
+
scope,
|
|
2993
|
+
includeImage,
|
|
2994
|
+
expected
|
|
2995
|
+
},
|
|
2996
|
+
timeoutMs,
|
|
2997
|
+
signal
|
|
2998
|
+
);
|
|
2999
|
+
if (result.operation !== "observe")
|
|
3000
|
+
throw new Error(
|
|
3001
|
+
"invalid_runtime_response: Expected a host observation."
|
|
3002
|
+
);
|
|
3003
|
+
return result.observation;
|
|
3004
|
+
});
|
|
3005
|
+
};
|
|
3006
|
+
const gameSettings = async (options) => {
|
|
3007
|
+
const session = getRequiredGameSession(options.gameSessionId);
|
|
3008
|
+
if (session.summary.semanticAccess === "participant-only")
|
|
3009
|
+
throw new Error(
|
|
3010
|
+
"contract_runtime_not_owned: Settings require an owned host."
|
|
3011
|
+
);
|
|
3012
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
3013
|
+
return session.operations.run(timeoutMs, async (signal) => {
|
|
3014
|
+
const snapshot = await readLiveSnapshot(session, timeoutMs, signal);
|
|
3015
|
+
if (!snapshot)
|
|
3016
|
+
throw new Error(
|
|
3017
|
+
"contract_runtime_unavailable: Game has no live semantic contract."
|
|
3018
|
+
);
|
|
3019
|
+
const request = {
|
|
3020
|
+
roomId: session.summary.roomId,
|
|
3021
|
+
runtimeId: snapshot.runtimeId
|
|
3022
|
+
};
|
|
3023
|
+
const response = await session.requestHost(
|
|
3024
|
+
"patch" in options ? {
|
|
3025
|
+
...request,
|
|
3026
|
+
operation: "settings-update",
|
|
3027
|
+
patch: options.patch,
|
|
3028
|
+
expectedRevision: options.expectedRevision
|
|
3029
|
+
} : { ...request, operation: "settings-read" },
|
|
3030
|
+
timeoutMs,
|
|
3031
|
+
signal
|
|
3032
|
+
);
|
|
3033
|
+
if (response.operation !== "settings-read" && response.operation !== "settings-update")
|
|
3034
|
+
throw new Error("invalid_runtime_response: Expected settings.");
|
|
3035
|
+
return { values: response.values, revision: response.revision };
|
|
3036
|
+
});
|
|
3037
|
+
};
|
|
3038
|
+
const readGameSettings = (options) => gameSettings(options);
|
|
3039
|
+
const updateGameSettings = (options) => gameSettings(options);
|
|
3040
|
+
const controlGameSessionParticipant = async (options) => {
|
|
3041
|
+
const session = getRequiredGameSession(options.gameSessionId);
|
|
3042
|
+
return session.operations.run(
|
|
3043
|
+
DEFAULT_TIMEOUT_MS,
|
|
3044
|
+
() => controlControllerParticipant({
|
|
3045
|
+
controllerSessionId: session.summary.controllerSessionId,
|
|
3046
|
+
expected: options.expected,
|
|
3047
|
+
lease: options.lease,
|
|
3048
|
+
operation: options.operation
|
|
3049
|
+
})
|
|
3050
|
+
);
|
|
3051
|
+
};
|
|
3052
|
+
const sendGameSessionInput = async ({
|
|
3053
|
+
gameSessionId,
|
|
3054
|
+
input
|
|
3055
|
+
}) => {
|
|
3056
|
+
const session = getRequiredGameSession(gameSessionId);
|
|
3057
|
+
return session.operations.run(DEFAULT_TIMEOUT_MS, async () => {
|
|
3058
|
+
const sent = await sendControllerInput({
|
|
3059
|
+
controllerSessionId: session.summary.controllerSessionId,
|
|
3060
|
+
input
|
|
3061
|
+
});
|
|
3062
|
+
updateSummary(session, {
|
|
3063
|
+
connected: sent.connected,
|
|
3064
|
+
disconnectedAt: sent.disconnectedAt,
|
|
3065
|
+
disconnectReason: sent.disconnectReason,
|
|
3066
|
+
process: sent.process
|
|
3067
|
+
});
|
|
3068
|
+
return { ...session.summary, input: sent.input, sentAt: sent.sentAt };
|
|
3069
|
+
});
|
|
3070
|
+
};
|
|
3071
|
+
const invokeGameSessionAction = async (options) => {
|
|
3072
|
+
const session = getRequiredGameSession(options.gameSessionId);
|
|
3073
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
3074
|
+
return session.operations.run(timeoutMs, async (signal) => {
|
|
3075
|
+
const before = await readLiveSnapshot(session, timeoutMs, signal);
|
|
3076
|
+
if (!before)
|
|
3077
|
+
throw new Error(
|
|
3078
|
+
"contract_runtime_unavailable: Game has no live semantic contract."
|
|
3079
|
+
);
|
|
3080
|
+
const action = before.actions.find(
|
|
3081
|
+
(action2) => toSessionActionId(
|
|
3082
|
+
action2.target.kind === "host" ? "host" : "player",
|
|
3083
|
+
action2.actionId
|
|
3084
|
+
) === options.actionId
|
|
3085
|
+
);
|
|
3086
|
+
if (!action)
|
|
3087
|
+
throw new Error(`Unknown game session action "${options.actionId}".`);
|
|
3088
|
+
const resolved = await session.requestHost(
|
|
3089
|
+
{
|
|
3090
|
+
operation: action.target.kind === "host" ? "invoke-host" : "resolve",
|
|
3091
|
+
roomId: session.summary.roomId,
|
|
3092
|
+
controllerId: session.summary.controllerId,
|
|
3093
|
+
contractId: before.contractId,
|
|
3094
|
+
runtimeId: before.runtimeId,
|
|
3095
|
+
actionId: action.actionId,
|
|
3096
|
+
payload: options.payload
|
|
3097
|
+
},
|
|
3098
|
+
timeoutMs,
|
|
3099
|
+
signal
|
|
3100
|
+
);
|
|
3101
|
+
if (resolved.operation !== "resolve" && resolved.operation !== "invoke-host")
|
|
3102
|
+
throw new Error("Invalid host resolve response.");
|
|
3103
|
+
const lane = resolved.target.kind === "host" ? "host" : "player";
|
|
3104
|
+
const sentAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
3105
|
+
const sent = lane === "player" ? await invokeControllerAction({
|
|
3106
|
+
controllerSessionId: session.summary.controllerSessionId,
|
|
3107
|
+
actionName: resolved.target.actionName,
|
|
3108
|
+
storeDomain: resolved.target.storeDomain,
|
|
3109
|
+
payload: resolved.payload,
|
|
3110
|
+
timeoutMs
|
|
3111
|
+
}) : null;
|
|
3112
|
+
const acknowledgement = sent?.acknowledgement ?? resolved.acknowledgement;
|
|
3113
|
+
if (!acknowledgement)
|
|
3114
|
+
throw new Error("Host action returned no acknowledgement.");
|
|
3115
|
+
const after = await readLiveSnapshot(session, timeoutMs, signal);
|
|
3116
|
+
if (!after)
|
|
3117
|
+
throw new Error(
|
|
3118
|
+
"contract_changed: Game contract unmounted after invocation; action may have executed."
|
|
3119
|
+
);
|
|
3120
|
+
const observation = computeGameSnapshotObservation({
|
|
3121
|
+
snapshotBefore: before,
|
|
3122
|
+
snapshotAfter: after
|
|
3123
|
+
});
|
|
3124
|
+
const classified = classifyGameActionOutcome({
|
|
3125
|
+
acknowledgement,
|
|
3126
|
+
observedStateChange: observation.observedStateChange
|
|
3127
|
+
});
|
|
3128
|
+
const outcome = observation.snapshotAfterStatus === "contract_changed" || observation.snapshotAfterStatus === "runtime_replaced" ? observation.snapshotAfterStatus : classified.outcome;
|
|
3129
|
+
return {
|
|
3130
|
+
...session.summary,
|
|
3131
|
+
actionId: options.actionId,
|
|
3132
|
+
lane,
|
|
3133
|
+
invocation: {
|
|
3134
|
+
...session.summary,
|
|
3135
|
+
actionId: action.actionId,
|
|
3136
|
+
lane,
|
|
3137
|
+
actionName: resolved.target.actionName,
|
|
3138
|
+
storeDomain: resolved.target.storeDomain,
|
|
3139
|
+
payload: resolved.payload,
|
|
3140
|
+
sentAt,
|
|
3141
|
+
acknowledgement,
|
|
3142
|
+
...classified,
|
|
3143
|
+
outcome,
|
|
3144
|
+
...observation,
|
|
3145
|
+
snapshotBefore: before,
|
|
3146
|
+
snapshotAfter: after
|
|
3147
|
+
}
|
|
3148
|
+
};
|
|
3149
|
+
});
|
|
3150
|
+
};
|
|
3151
|
+
const captureGameSessionVisuals = async ({
|
|
3152
|
+
gameSessionId,
|
|
3153
|
+
timeoutMs
|
|
3154
|
+
}) => {
|
|
3155
|
+
const session = getRequiredGameSession(gameSessionId);
|
|
3156
|
+
return session.operations.run(timeoutMs ?? 3e4, async () => {
|
|
3157
|
+
const captureId = `${(/* @__PURE__ */ new Date()).toISOString().replaceAll(/[^0-9A-Za-z]/gu, "-")}-${randomUUID4().slice(0, 8)}`;
|
|
3158
|
+
const relativeDir = path4.join(
|
|
3159
|
+
".airjam",
|
|
3160
|
+
"artifacts",
|
|
3161
|
+
"session-visuals",
|
|
3162
|
+
gameSessionId,
|
|
3163
|
+
captureId
|
|
3164
|
+
);
|
|
3165
|
+
const captured = await captureControllerSessionVisuals({
|
|
3166
|
+
controllerSessionId: session.summary.controllerSessionId,
|
|
3167
|
+
relativeDir,
|
|
3168
|
+
timeoutMs
|
|
3169
|
+
});
|
|
3170
|
+
return {
|
|
3171
|
+
...session.summary,
|
|
3172
|
+
contract: "air-jam-game-session-visual-capture/v1",
|
|
3173
|
+
capturedAt: captured.capturedAt,
|
|
3174
|
+
artifactDir: path4.join(session.summary.cwd, relativeDir),
|
|
3175
|
+
screenshots: captured.screenshots.map((screenshot) => ({
|
|
3176
|
+
...screenshot,
|
|
3177
|
+
filePath: path4.join(session.summary.cwd, screenshot.relativePath)
|
|
3178
|
+
}))
|
|
3179
|
+
};
|
|
3180
|
+
});
|
|
3181
|
+
};
|
|
3182
|
+
const disposeGameSession = async ({ gameSessionId }, disconnect) => {
|
|
3183
|
+
const session = getRequiredGameSession(gameSessionId);
|
|
3184
|
+
session.operations.close();
|
|
3185
|
+
const disconnected = session.disconnection ??= await disconnect({
|
|
3186
|
+
controllerSessionId: session.summary.controllerSessionId
|
|
3187
|
+
});
|
|
3188
|
+
updateSummary(session, {
|
|
3189
|
+
connected: disconnected.session.connected,
|
|
3190
|
+
disconnectedAt: disconnected.session.disconnectedAt,
|
|
3191
|
+
disconnectReason: disconnected.session.disconnectReason,
|
|
3192
|
+
process: disconnected.session.process
|
|
3193
|
+
});
|
|
3194
|
+
if (session.devProcessId) {
|
|
3195
|
+
await releaseDevProcessLease(session.devProcessId);
|
|
3196
|
+
session.devProcessId = null;
|
|
3197
|
+
}
|
|
3198
|
+
gameSessions.delete(gameSessionId);
|
|
3199
|
+
return {
|
|
3200
|
+
closed: true,
|
|
3201
|
+
session: session.summary,
|
|
3202
|
+
disconnection: {
|
|
3203
|
+
release: disconnected.release,
|
|
3204
|
+
leave: disconnected.leave
|
|
3205
|
+
}
|
|
3206
|
+
};
|
|
3207
|
+
};
|
|
3208
|
+
const closeGameSession = (input) => disposeGameSession(input, disconnectController);
|
|
3209
|
+
return {
|
|
3210
|
+
openGameSession,
|
|
3211
|
+
readGameSession,
|
|
3212
|
+
observeGameSession,
|
|
3213
|
+
readGameSettings,
|
|
3214
|
+
updateGameSettings,
|
|
3215
|
+
sendGameSessionInput,
|
|
3216
|
+
controlGameSessionParticipant,
|
|
3217
|
+
invokeGameSessionAction,
|
|
3218
|
+
captureGameSessionVisuals,
|
|
3219
|
+
closeGameSession,
|
|
3220
|
+
async openRunSession(options, {
|
|
3221
|
+
delegation,
|
|
3222
|
+
game,
|
|
3223
|
+
build,
|
|
3224
|
+
room,
|
|
3225
|
+
settings,
|
|
3226
|
+
onScope
|
|
3227
|
+
} = {}) {
|
|
3228
|
+
if (room && (delegation || build || options.controllerJoinUrl))
|
|
3229
|
+
throw new Error(
|
|
3230
|
+
"A headless room is its own target; it takes no build or other room."
|
|
3231
|
+
);
|
|
3232
|
+
const summary = await openGameSession(
|
|
3233
|
+
room ? { ...options, controllerJoinUrl: room.controllerJoinUrl } : options,
|
|
3234
|
+
room ? { access: "owned-host", request: room.requestHost } : delegation && {
|
|
3235
|
+
access: "delegated-host",
|
|
3236
|
+
request: delegation.host,
|
|
3237
|
+
claimSeat: delegation.claimSeat
|
|
3238
|
+
},
|
|
3239
|
+
build,
|
|
3240
|
+
onScope,
|
|
3241
|
+
room ? void 0 : settings,
|
|
3242
|
+
game
|
|
3243
|
+
);
|
|
3244
|
+
let seatsLeft = (delegation?.seats ?? 0) - 1;
|
|
3245
|
+
const gameSessionId = summary.gameSessionId;
|
|
3246
|
+
const session = getRequiredGameSession(gameSessionId);
|
|
3247
|
+
const checkParticipant = async (controllerSessionId, controllerId) => {
|
|
3248
|
+
const state = await readRuntimeSnapshot({
|
|
3249
|
+
controllerSessionId,
|
|
3250
|
+
requestSync: false
|
|
3251
|
+
});
|
|
3252
|
+
if (!state.connected || state.controllerId !== controllerId)
|
|
3253
|
+
throw new Error(
|
|
3254
|
+
"seat_replaced: Run participant is no longer connected."
|
|
3255
|
+
);
|
|
3256
|
+
};
|
|
3257
|
+
const observeParticipant = (controllerSessionId, controllerId) => (input) => session.operations.run(DEFAULT_TIMEOUT_MS, async (signal) => {
|
|
3258
|
+
await checkParticipant(controllerSessionId, controllerId);
|
|
3259
|
+
const result = await session.requestHost(
|
|
3260
|
+
{
|
|
3261
|
+
operation: "observe",
|
|
3262
|
+
roomId: summary.roomId,
|
|
3263
|
+
controllerId,
|
|
3264
|
+
...input
|
|
3265
|
+
},
|
|
3266
|
+
DEFAULT_TIMEOUT_MS,
|
|
3267
|
+
signal
|
|
3268
|
+
);
|
|
3269
|
+
if (result.operation !== "observe")
|
|
3270
|
+
throw new Error(
|
|
3271
|
+
"invalid_runtime_response: Expected a host observation."
|
|
3272
|
+
);
|
|
3273
|
+
await checkParticipant(controllerSessionId, controllerId);
|
|
3274
|
+
return result.observation;
|
|
3275
|
+
});
|
|
3276
|
+
const watchController = (controllerSessionId) => (onEvent, signal) => watchControllerSessionVisuals({
|
|
3277
|
+
ownerControllerSessionId: summary.controllerSessionId,
|
|
3278
|
+
controllerSessionId,
|
|
3279
|
+
onEvent,
|
|
3280
|
+
signal
|
|
3281
|
+
});
|
|
3282
|
+
return {
|
|
3283
|
+
summary,
|
|
3284
|
+
clock: room?.clock ?? wallClock,
|
|
3285
|
+
requestHost: session.requestHost,
|
|
3286
|
+
watch: watchController(summary.controllerSessionId),
|
|
3287
|
+
watchHost: (onEvent, signal) => watchControllerSessionVisuals({
|
|
3288
|
+
ownerControllerSessionId: summary.controllerSessionId,
|
|
3289
|
+
onEvent,
|
|
3290
|
+
signal
|
|
3291
|
+
}),
|
|
3292
|
+
async readParticipants() {
|
|
3293
|
+
const state = await readRuntimeSnapshot({
|
|
3294
|
+
controllerSessionId: summary.controllerSessionId,
|
|
3295
|
+
requestSync: false
|
|
3296
|
+
});
|
|
3297
|
+
if (!state.connected)
|
|
3298
|
+
throw new Error("seat_replaced: Primary player is disconnected.");
|
|
3299
|
+
return {
|
|
3300
|
+
roomId: state.roomId,
|
|
3301
|
+
controllerIds: seatViewSchema.array().parse(state.players).map((player) => player.id)
|
|
3302
|
+
};
|
|
3303
|
+
},
|
|
3304
|
+
checkConnected: () => checkParticipant(summary.controllerSessionId, summary.controllerId),
|
|
3305
|
+
observe: observeParticipant(
|
|
3306
|
+
summary.controllerSessionId,
|
|
3307
|
+
summary.controllerId
|
|
3308
|
+
),
|
|
3309
|
+
control: (input) => controlGameSessionParticipant({ ...input, gameSessionId }),
|
|
3310
|
+
async addParticipant(nickname) {
|
|
3311
|
+
if (delegation && seatsLeft <= 0)
|
|
3312
|
+
throw new Error(
|
|
3313
|
+
"current_room_scope: The creator's room granted no further seat."
|
|
3314
|
+
);
|
|
3315
|
+
seatsLeft -= 1;
|
|
3316
|
+
const controller = await connectController({
|
|
3317
|
+
cwd: summary.cwd,
|
|
3318
|
+
gameId: summary.gameId ?? void 0,
|
|
3319
|
+
controllerJoinUrl: summary.controllerJoinUrl,
|
|
3320
|
+
nickname
|
|
3321
|
+
});
|
|
3322
|
+
if (delegation)
|
|
3323
|
+
await delegation.claimSeat(claimOf(controller), DEFAULT_TIMEOUT_MS).catch(async (error) => {
|
|
3324
|
+
await disconnectController({
|
|
3325
|
+
controllerSessionId: controller.controllerSessionId
|
|
3326
|
+
});
|
|
3327
|
+
throw error;
|
|
3328
|
+
});
|
|
3329
|
+
let disconnected;
|
|
3330
|
+
const dispose = async (disconnect) => {
|
|
3331
|
+
const result = disconnected ??= await disconnect({
|
|
3332
|
+
controllerSessionId: controller.controllerSessionId
|
|
3333
|
+
});
|
|
3334
|
+
return { release: result.release, leave: result.leave };
|
|
3335
|
+
};
|
|
3336
|
+
return {
|
|
3337
|
+
controllerId: controller.controllerId,
|
|
3338
|
+
watch: watchController(controller.controllerSessionId),
|
|
3339
|
+
checkConnected: () => checkParticipant(
|
|
3340
|
+
controller.controllerSessionId,
|
|
3341
|
+
controller.controllerId
|
|
3342
|
+
),
|
|
3343
|
+
observe: observeParticipant(
|
|
3344
|
+
controller.controllerSessionId,
|
|
3345
|
+
controller.controllerId
|
|
3346
|
+
),
|
|
3347
|
+
control: (input) => session.operations.run(
|
|
3348
|
+
DEFAULT_TIMEOUT_MS,
|
|
3349
|
+
() => controlControllerParticipant({
|
|
3350
|
+
...input,
|
|
3351
|
+
controllerSessionId: controller.controllerSessionId
|
|
3352
|
+
})
|
|
3353
|
+
),
|
|
3354
|
+
close: () => dispose(disconnectController),
|
|
3355
|
+
forceClose: () => dispose(forceDisconnectController)
|
|
3356
|
+
};
|
|
3357
|
+
},
|
|
3358
|
+
invokeHost: async (actionId, payload) => {
|
|
3359
|
+
const result = await invokeGameSessionAction({
|
|
3360
|
+
gameSessionId,
|
|
3361
|
+
actionId: `host:${actionId}`,
|
|
3362
|
+
payload
|
|
3363
|
+
});
|
|
3364
|
+
if (!result.invocation.acknowledgement.ok)
|
|
3365
|
+
throw new Error("Host setup action was rejected.");
|
|
3366
|
+
return result;
|
|
3367
|
+
},
|
|
3368
|
+
close: () => closeGameSession({ gameSessionId }),
|
|
3369
|
+
forceClose: () => disposeGameSession({ gameSessionId }, forceDisconnectController)
|
|
3370
|
+
};
|
|
3371
|
+
}
|
|
3372
|
+
};
|
|
3373
|
+
}
|
|
3374
|
+
|
|
3375
|
+
export {
|
|
3376
|
+
readBoundedText,
|
|
3377
|
+
currentRoomHost,
|
|
3378
|
+
currentRoomSeatClaimer,
|
|
3379
|
+
readTerminalGameRun,
|
|
3380
|
+
replayInputLog,
|
|
3381
|
+
GameRunOwner,
|
|
3382
|
+
createGameSessionRuntime
|
|
3383
|
+
};
|
|
3384
|
+
//# sourceMappingURL=chunk-PMBLXGFM.js.map
|