@air-jam/devtools 0.9.3 → 1.0.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +60 -0
- package/dist/{chunk-VKMJO6VN.js → chunk-2O67AXCU.js} +150 -40
- package/dist/chunk-2O67AXCU.js.map +1 -0
- package/dist/chunk-AO3ZDXF6.js +142 -0
- package/dist/chunk-AO3ZDXF6.js.map +1 -0
- package/dist/chunk-ART5TEYT.js +472 -0
- package/dist/chunk-ART5TEYT.js.map +1 -0
- package/dist/chunk-ASC2CK2R.js +77 -0
- package/dist/chunk-ASC2CK2R.js.map +1 -0
- package/dist/chunk-E3UZZGAV.js +50 -0
- package/dist/chunk-E3UZZGAV.js.map +1 -0
- package/dist/chunk-EJTE7UKX.js +64 -0
- package/dist/chunk-EJTE7UKX.js.map +1 -0
- package/dist/chunk-ESFKNN75.js +110 -0
- package/dist/chunk-ESFKNN75.js.map +1 -0
- package/dist/chunk-EU7A6PXW.js +1339 -0
- package/dist/chunk-EU7A6PXW.js.map +1 -0
- package/dist/chunk-FN7E6EA7.js +549 -0
- package/dist/chunk-FN7E6EA7.js.map +1 -0
- package/dist/chunk-GDFAWHGA.js +190 -0
- package/dist/chunk-GDFAWHGA.js.map +1 -0
- package/dist/chunk-HZUGBH4Y.js +347 -0
- package/dist/chunk-HZUGBH4Y.js.map +1 -0
- package/dist/chunk-ITKAOEGX.js +93 -0
- package/dist/chunk-ITKAOEGX.js.map +1 -0
- package/dist/chunk-JBCUTWRI.js +897 -0
- package/dist/chunk-JBCUTWRI.js.map +1 -0
- package/dist/chunk-JSI5S4WP.js +1174 -0
- package/dist/chunk-JSI5S4WP.js.map +1 -0
- package/dist/chunk-L4D675BG.js +97 -0
- package/dist/chunk-L4D675BG.js.map +1 -0
- package/dist/chunk-M6CJ7GQC.js +133 -0
- package/dist/chunk-M6CJ7GQC.js.map +1 -0
- package/dist/{chunk-CKFT2ZJE.js → chunk-MEIMOSZC.js} +53 -105
- package/dist/chunk-MEIMOSZC.js.map +1 -0
- package/dist/{chunk-GUEZP773.js → chunk-O3XG3FNL.js} +204 -41
- package/dist/chunk-O3XG3FNL.js.map +1 -0
- package/dist/chunk-OM6SCJ7H.js +18 -0
- package/dist/chunk-OM6SCJ7H.js.map +1 -0
- package/dist/chunk-PKD4WVX5.js +63 -0
- package/dist/chunk-PKD4WVX5.js.map +1 -0
- package/dist/chunk-PMBLXGFM.js +3384 -0
- package/dist/chunk-PMBLXGFM.js.map +1 -0
- package/dist/chunk-PMNE5GIN.js +279 -0
- package/dist/chunk-PMNE5GIN.js.map +1 -0
- package/dist/chunk-QAWI64VR.js +148 -0
- package/dist/chunk-QAWI64VR.js.map +1 -0
- package/dist/chunk-QGADSPHZ.js +449 -0
- package/dist/chunk-QGADSPHZ.js.map +1 -0
- package/dist/chunk-SPYN66UV.js +338 -0
- package/dist/chunk-SPYN66UV.js.map +1 -0
- package/dist/context.d.ts +9 -3
- package/dist/context.js +2 -1
- package/dist/controller.d.ts +33 -7
- package/dist/controller.js +18 -8
- package/dist/dependencies.d.ts +44 -0
- package/dist/dependencies.js +10 -0
- package/dist/dev.d.ts +9 -3
- package/dist/dev.js +3 -4
- package/dist/game-builds.d.ts +200 -0
- package/dist/game-builds.js +16 -0
- package/dist/game-builds.js.map +1 -0
- package/dist/game-run-watch-CEd_SpAT.d.ts +84 -0
- package/dist/game-runs.d.ts +1452 -0
- package/dist/game-runs.js +76 -0
- package/dist/game-runs.js.map +1 -0
- package/dist/game-session-broker-CUvORfMd.d.ts +439 -0
- package/dist/game-session-broker.d.ts +4 -57
- package/dist/game-session-broker.js +33 -228
- package/dist/game-session-broker.js.map +1 -1
- package/dist/game-session.d.ts +3931 -10
- package/dist/game-session.js +186 -15
- package/dist/game-session.js.map +1 -1
- package/dist/game-settings.d.ts +16 -0
- package/dist/game-settings.js +237 -0
- package/dist/game-settings.js.map +1 -0
- package/dist/games.d.ts +11 -4
- package/dist/games.js +4 -2
- package/dist/harness/visual.d.ts +34 -151
- package/dist/harness/visual.js +6 -1
- package/dist/logs.d.ts +8 -2
- package/dist/logs.js +3 -4
- package/dist/logs.js.map +1 -1
- package/dist/managed-process-scope-BicYi_t9.d.ts +3 -0
- package/dist/mcp-config.js +2 -1
- package/dist/mcp-config.js.map +1 -1
- package/dist/platform-auth.d.ts +8 -111
- package/dist/platform-auth.js +9 -1
- package/dist/platform-game-analytics.d.ts +51 -0
- package/dist/platform-game-analytics.js +49 -0
- package/dist/platform-game-analytics.js.map +1 -0
- package/dist/platform-game-app-id.d.ts +46 -0
- package/dist/platform-game-app-id.js +93 -0
- package/dist/platform-game-app-id.js.map +1 -0
- package/dist/platform-game-media.d.ts +40 -2
- package/dist/platform-game-media.js +1 -1
- package/dist/platform-games.d.ts +24 -2
- package/dist/platform-games.js +16 -84
- package/dist/platform-games.js.map +1 -1
- package/dist/quality.d.ts +9 -3
- package/dist/quality.js +3 -4
- package/dist/quality.js.map +1 -1
- package/dist/release.d.ts +226 -16
- package/dist/release.js +18 -1331
- package/dist/release.js.map +1 -1
- package/dist/rooms-check.d.ts +90 -0
- package/dist/rooms-check.js +717 -0
- package/dist/rooms-check.js.map +1 -0
- package/dist/source-tree-contract.d.ts +16 -0
- package/dist/source-tree-contract.js +13 -0
- package/dist/source-tree-contract.js.map +1 -0
- package/dist/testing.d.ts +464 -0
- package/dist/testing.js +27 -0
- package/dist/testing.js.map +1 -0
- package/dist/tooling/describe-game.js +54 -0
- package/dist/tooling/describe-game.js.map +1 -0
- package/dist/tooling/game-session-broker.js +28 -0
- package/dist/tooling/game-session-broker.js.map +1 -0
- package/dist/tooling/hold-runtime-host.js +769 -67
- package/dist/tooling/hold-runtime-host.js.map +1 -1
- package/dist/tooling/list-visual-scenarios.js +18 -55
- package/dist/tooling/list-visual-scenarios.js.map +1 -1
- package/dist/tooling/process-scope-bootstrap.mjs +24 -0
- package/dist/tooling/process-scope-guard.d.ts +2 -0
- package/dist/tooling/process-scope-guard.js +388 -0
- package/dist/tooling/process-scope-guard.js.map +1 -0
- package/dist/tooling/process-scope-windows.ps1 +148 -0
- package/dist/tooling/rooms-check-device.d.ts +2 -0
- package/dist/tooling/rooms-check-device.js +498 -0
- package/dist/tooling/rooms-check-device.js.map +1 -0
- package/dist/tooling/run-headless-room.d.ts +2 -0
- package/dist/tooling/run-headless-room.js +287 -0
- package/dist/tooling/run-headless-room.js.map +1 -0
- package/dist/tooling/run-test-profile.d.ts +2 -0
- package/dist/tooling/run-test-profile.js +181 -0
- package/dist/tooling/run-test-profile.js.map +1 -0
- package/dist/tooling/run-visual-capture.js +70 -34
- package/dist/tooling/run-visual-capture.js.map +1 -1
- package/dist/tooling/seal-game-build.d.ts +2 -0
- package/dist/tooling/seal-game-build.js +120 -0
- package/dist/tooling/seal-game-build.js.map +1 -0
- package/dist/{types-C6NrHt88.d.ts → types-CdYrgrG_.d.ts} +337 -76
- package/dist/types-DyRD-ym1.d.ts +141 -0
- package/dist/visual.d.ts +9 -3
- package/dist/visual.js +24 -68
- package/dist/visual.js.map +1 -1
- package/package.json +51 -14
- package/src/bounded-response.ts +28 -0
- package/src/built-game-runtime.ts +152 -0
- package/src/context.ts +2 -13
- package/src/controller-protocol.ts +22 -0
- package/src/controller.ts +747 -597
- package/src/current-room-host.ts +166 -0
- package/src/decision-provider.ts +102 -0
- package/src/dependencies.ts +176 -0
- package/src/dependency-install-contract.ts +12 -0
- package/src/dev.ts +46 -50
- package/src/game-action-observation.ts +11 -1
- package/src/game-build-protocol.ts +72 -0
- package/src/game-build.ts +483 -0
- package/src/game-run-owner.ts +2358 -0
- package/src/game-run-protocol.ts +448 -0
- package/src/game-run-record.ts +92 -0
- package/src/game-run-replay.ts +95 -0
- package/src/game-run-watch.ts +155 -0
- package/src/game-session-broker.ts +689 -197
- package/src/game-session-operations.ts +61 -0
- package/src/game-session-protocol.ts +180 -0
- package/src/game-session-runtime.ts +861 -0
- package/src/game-session.ts +164 -417
- package/src/game-settings.ts +295 -0
- package/src/games.ts +88 -92
- package/src/harness/visual/browser.ts +100 -0
- package/src/harness/visual/controller-observation.ts +181 -0
- package/src/harness/visual/runner.ts +24 -21
- package/src/harness/visual/runtime-controller-observations.ts +151 -0
- package/src/harness/visual/scenario-contract.ts +1 -2
- package/src/harness/visual/scenario-helpers.ts +5 -1
- package/src/harness/visual/screencast.ts +155 -0
- package/src/harness/visual/session.ts +72 -41
- package/src/harness/visual/types.ts +8 -5
- package/src/headless-room-protocol.ts +112 -0
- package/src/headless-room.ts +222 -0
- package/src/helper-channel.ts +229 -0
- package/src/helper-scripts.ts +25 -5
- package/src/installed-dependencies.ts +74 -0
- package/src/managed-process-scope.ts +481 -0
- package/src/node-process-environment.ts +10 -0
- package/src/platform-auth.ts +194 -55
- package/src/platform-game-analytics.ts +50 -0
- package/src/platform-game-app-id.ts +99 -0
- package/src/platform-games.ts +13 -111
- package/src/policy-artifact-contract.ts +52 -0
- package/src/policy-artifacts.ts +134 -0
- package/src/process-scope-admission.ts +50 -0
- package/src/process-scope-protocol.ts +66 -0
- package/src/process-scope.ts +327 -0
- package/src/release.ts +28 -42
- package/src/rooms-check-fleet.ts +194 -0
- package/src/rooms-check-link.ts +138 -0
- package/src/rooms-check-protocol.ts +244 -0
- package/src/rooms-check.ts +797 -0
- package/src/runtime-owner-protocol.ts +106 -18
- package/src/source-tree-contract.ts +70 -0
- package/src/source-tree.ts +84 -0
- package/src/test-profile-process.ts +153 -0
- package/src/test-profile-protocol.ts +116 -0
- package/src/testing.ts +430 -0
- package/src/tooling/declaration-hook.ts +52 -0
- package/src/tooling/describe-game.ts +49 -0
- package/src/tooling/game-session-broker.ts +7 -0
- package/src/tooling/hold-runtime-host.ts +255 -38
- package/src/tooling/list-visual-scenarios.ts +19 -62
- package/src/tooling/load-game.ts +79 -0
- package/src/tooling/process-scope-bootstrap.mjs +24 -0
- package/src/tooling/process-scope-guard.ts +213 -0
- package/src/tooling/process-scope-windows.ps1 +148 -0
- package/src/tooling/rooms-check-device.ts +493 -0
- package/src/tooling/run-headless-room.ts +326 -0
- package/src/tooling/run-test-profile.ts +190 -0
- package/src/tooling/run-visual-capture.ts +37 -23
- package/src/tooling/runtime-owner-actions.ts +23 -0
- package/src/tooling/seal-game-build.ts +118 -0
- package/src/tooling/visual-pack.ts +10 -45
- package/src/types.ts +54 -77
- package/src/visual.ts +14 -22
- package/src/windows-process-scopes.ts +189 -0
- package/dist/agent.d.ts +0 -15
- package/dist/agent.js +0 -19
- package/dist/chunk-5YAARMW5.js +0 -36
- package/dist/chunk-5YAARMW5.js.map +0 -1
- package/dist/chunk-6WQODT37.js +0 -1019
- package/dist/chunk-6WQODT37.js.map +0 -1
- package/dist/chunk-CKFT2ZJE.js.map +0 -1
- package/dist/chunk-ER3Q2C4G.js +0 -358
- package/dist/chunk-ER3Q2C4G.js.map +0 -1
- package/dist/chunk-GUEZP773.js.map +0 -1
- package/dist/chunk-HIDNI56E.js +0 -33
- package/dist/chunk-HIDNI56E.js.map +0 -1
- package/dist/chunk-QKXS5D35.js +0 -43
- package/dist/chunk-QKXS5D35.js.map +0 -1
- package/dist/chunk-S4LSCEVE.js +0 -261
- package/dist/chunk-S4LSCEVE.js.map +0 -1
- package/dist/chunk-VKMJO6VN.js.map +0 -1
- package/dist/chunk-WFUR3MXY.js +0 -67
- package/dist/chunk-WFUR3MXY.js.map +0 -1
- package/dist/chunk-XEMR7KUE.js +0 -361
- package/dist/chunk-XEMR7KUE.js.map +0 -1
- package/dist/chunk-ZLPD7FY5.js +0 -191
- package/dist/chunk-ZLPD7FY5.js.map +0 -1
- package/dist/tooling/agent-contract.js +0 -193
- package/dist/tooling/agent-contract.js.map +0 -1
- package/dist/tooling/inspect-airjam-agent.js +0 -37
- package/dist/tooling/inspect-airjam-agent.js.map +0 -1
- package/src/agent.ts +0 -380
- package/src/tooling/agent-contract.ts +0 -232
- package/src/tooling/agent-declaration.ts +0 -36
- package/src/tooling/airjam-agent-inspection.ts +0 -45
- package/src/tooling/airjam-agent.ts +0 -118
- package/src/tooling/inspect-airjam-agent.ts +0 -20
- /package/dist/{agent.js.map → dependencies.js.map} +0 -0
- /package/dist/tooling/{agent-contract.d.ts → describe-game.d.ts} +0 -0
- /package/dist/tooling/{inspect-airjam-agent.d.ts → game-session-broker.d.ts} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/current-room-host.ts","../src/bounded-response.ts","../src/game-run-record.ts","../src/game-run-owner.ts","../src/headless-room.ts","../src/helper-channel.ts","../src/policy-artifacts.ts","../src/test-profile-process.ts","../src/game-session-runtime.ts","../src/game-action-observation.ts","../src/game-session-operations.ts"],"sourcesContent":["import {\n hostAgentResultMessageSchema,\n type HostAgentRequest,\n type HostAgentResponse,\n} from \"@air-jam/sdk/runtime-control\";\nimport { BodyLimitError, readBoundedText } from \"./bounded-response.js\";\nimport {\n currentRoomHostRequestSchema,\n currentRoomSeatClaimSchema,\n type CurrentRoomAttachment,\n type CurrentRoomSeatClaim,\n} from \"./game-run-protocol.js\";\n\nconst MAXIMUM_RESPONSE_BYTES = 2 * 1024 * 1024;\n\nexport class CurrentRoomStopped extends Error {}\n\n/**\n * The creator's host, reached through the editor that granted the room. The\n * endpoint is an ephemeral delegation, never part of a run record or trace.\n */\nexport function currentRoomHost(\n attachment: CurrentRoomAttachment,\n ownerInstanceId: string,\n): (\n request: HostAgentRequest,\n timeoutMs: number,\n signal?: AbortSignal,\n) => Promise<HostAgentResponse> {\n return async (request, timeoutMs, signal) => {\n const input = currentRoomHostRequestSchema.parse({\n targetId: attachment.host.targetId,\n ownerInstanceId,\n request,\n });\n const deadline = AbortSignal.timeout(timeoutMs);\n let response: Response;\n try {\n response = await fetch(attachment.host.endpoint, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(input),\n signal: signal ? AbortSignal.any([signal, deadline]) : deadline,\n redirect: \"error\",\n credentials: \"omit\",\n });\n } catch {\n throw new Error(\n \"current_host_unavailable: The creator's editor could not be reached.\",\n );\n }\n if (!response.ok) {\n if ([401, 403, 409, 410].includes(response.status)) {\n let message = \"The creator's room is no longer granted.\";\n try {\n if (response.body) {\n const body = JSON.parse(await readBoundedText(response.body, 4096));\n if (typeof body?.error === \"string\" && body.error.trim())\n message = body.error.trim().slice(0, 300);\n }\n } catch {\n // Missing, invalid or oversized refusal bodies use the generic cause.\n }\n if (response.status === 410) throw new CurrentRoomStopped(message);\n throw new Error(`runtime_replaced: ${message}`);\n }\n await response.body?.cancel();\n throw new Error(\n `current_host_unavailable: The editor returned HTTP ${response.status}.`,\n );\n }\n if (!response.body)\n throw new Error(\"current_host_invalid: Empty host response.\");\n let source: string;\n try {\n source = await readBoundedText(response.body, MAXIMUM_RESPONSE_BYTES);\n } catch (error) {\n throw new Error(\n error instanceof BodyLimitError\n ? \"current_host_limit: The creator's host exceeded its transfer budget.\"\n : \"current_host_unavailable: Host response transfer failed.\",\n );\n }\n let result;\n try {\n result = hostAgentResultMessageSchema.shape.result.parse(\n JSON.parse(source),\n );\n } catch {\n throw new Error(\n \"current_host_invalid: The creator's host response failed validation.\",\n );\n }\n if (!result.ok) throw new Error(result.error);\n const answer = result.response;\n if (answer.operation !== request.operation)\n throw new Error(\n \"current_host_invalid: The creator's host answered another request.\",\n );\n if (\n answer.operation === \"observe\" &&\n request.operation === \"observe\" &&\n (answer.observation.identity.roomId !== request.roomId ||\n answer.observation.controllerId !== request.controllerId ||\n answer.observation.scope !== request.scope ||\n (request.expected &&\n Object.entries(request.expected).some(\n ([key, value]) =>\n Reflect.get(answer.observation.identity, key) !== value,\n )))\n )\n throw new Error(\n \"runtime_replaced: The observation belongs to another runtime or player.\",\n );\n return answer;\n };\n}\n\n/**\n * Claims, through the editor that granted the room, a seat one of the run's\n * players joined. The editor accepts it only for a seat its room shows as\n * an agent's, unclaimed and within the run's count.\n */\nexport function currentRoomSeatClaimer(\n attachment: CurrentRoomAttachment,\n ownerInstanceId: string,\n): (claim: CurrentRoomSeatClaim, timeoutMs: number) => Promise<void> {\n return async (claim, timeoutMs) => {\n const body = currentRoomSeatClaimSchema.parse({\n targetId: attachment.host.targetId,\n ownerInstanceId,\n claim,\n });\n let response: Response;\n try {\n response = await fetch(attachment.host.endpoint, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(body),\n signal: AbortSignal.timeout(timeoutMs),\n redirect: \"error\",\n credentials: \"omit\",\n });\n } catch {\n throw new Error(\n \"current_host_unavailable: The creator's editor could not be reached.\",\n );\n }\n if (response.ok) {\n await response.body?.cancel();\n return;\n }\n let message = `The editor refused the seat (HTTP ${response.status}).`;\n try {\n if (response.body) {\n const refusal = JSON.parse(await readBoundedText(response.body, 4096));\n if (typeof refusal?.error === \"string\" && refusal.error.trim())\n message = refusal.error.trim().slice(0, 300);\n }\n } catch {\n // Missing, invalid or oversized refusal bodies keep the generic cause.\n }\n if (response.status === 410) throw new CurrentRoomStopped(message);\n throw new Error(`current_room_scope: ${message}`);\n };\n}\n","/** A response body exceeded its caller's transfer budget and was cancelled. */\nexport class BodyLimitError extends Error {}\n\n/** Read a body as UTF-8 text, cancelling it on failure or beyond `maxBytes`. */\nexport async function readBoundedText(\n body: ReadableStream<Uint8Array>,\n maxBytes: number,\n) {\n const reader = body.getReader();\n const chunks: Uint8Array[] = [];\n let bytes = 0;\n try {\n while (true) {\n const next = await reader.read();\n if (next.done) break;\n bytes += next.value.byteLength;\n if (bytes > maxBytes)\n throw new BodyLimitError(`Response exceeded ${maxBytes} bytes.`);\n chunks.push(next.value);\n }\n } catch (error) {\n await reader.cancel().catch(() => undefined);\n throw error;\n } finally {\n reader.releaseLock();\n }\n return Buffer.concat(chunks, bytes).toString(\"utf8\");\n}\n","import { constants } from \"node:fs\";\nimport { lstat, open, realpath } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport {\n gameRunAddressSchema,\n gameRunRecordSchema,\n type AirJamGameRunRecord,\n} from \"./game-run-protocol.js\";\n\nexport async function readGameRunArtifact(\n projectDir: string,\n runId: string,\n name: \"record.json\" | \"trace.ndjson\",\n maximumBytes: number,\n) {\n gameRunAddressSchema.parse({ runId });\n const filename = path.join(\n await realpath(projectDir),\n \".airjam\",\n \"artifacts\",\n \"runs\",\n runId,\n name,\n );\n const file = await open(\n filename,\n constants.O_RDONLY | constants.O_NOFOLLOW,\n ).catch((error: NodeJS.ErrnoException) => {\n if (error.code === \"ENOENT\") return null;\n throw error;\n });\n if (!file) return null;\n try {\n const stat = await file.stat();\n if (!stat.isFile() || stat.size > maximumBytes)\n throw new Error(\n \"run_receipt_invalid: Retained record exceeds its limit.\",\n );\n const validatePath = async () => {\n const current = await lstat(filename);\n if ((await realpath(filename)) !== filename)\n throw new Error(\"run_receipt_invalid: Retained record path changed.\");\n if (current.ino !== stat.ino || current.dev !== stat.dev) {\n // Live records are replaced atomically; a changing record is not an offline terminal receipt.\n if (name === \"record.json\" && current.isFile()) return false;\n throw new Error(\"run_receipt_invalid: Retained record path changed.\");\n }\n return true;\n };\n if (!(await validatePath())) return null;\n const buffer = Buffer.alloc(stat.size + 1);\n let size = 0;\n while (size < buffer.length) {\n const { bytesRead } = await file.read(buffer, size, buffer.length - size);\n if (bytesRead === 0) break;\n size += bytesRead;\n }\n if (!(await validatePath())) return null;\n if (size !== stat.size)\n throw new Error(\n \"run_receipt_invalid: Retained record changed during read.\",\n );\n return buffer.subarray(0, size);\n } finally {\n await file.close();\n }\n}\n\n/** Completed evidence remains readable without reviving a session owner. */\nexport async function readTerminalGameRun(\n projectDir: string,\n runId: string,\n): Promise<AirJamGameRunRecord | null> {\n const bytes = await readGameRunArtifact(\n projectDir,\n runId,\n \"record.json\",\n 1_048_576,\n );\n if (!bytes) return null;\n const record = gameRunRecordSchema.parse(JSON.parse(bytes.toString(\"utf8\")));\n if (\n record.runId !== runId ||\n record.request.runId !== runId ||\n record.request.cwd !== projectDir\n )\n throw new Error(\"run_receipt_invalid: Retained record identity differs.\");\n if (record.state !== \"ended\") return null;\n if (!record.endedAt || !record.end)\n throw new Error(\"run_receipt_invalid: Terminal receipt is incomplete.\");\n return record;\n}\n","import type {\n ControllerLeasedControl,\n ControllerLeasedControlAck,\n} from \"@air-jam/sdk/protocol\";\nimport { PARTICIPANT_CONTROL_DEADLINE_MS } from \"@air-jam/sdk/protocol\";\nimport {\n clipFailureReason,\n describeHostRuntimeFault,\n readHostClip,\n readHostInputLog,\n sameHostRuntimeIdentity,\n type HostAgentRequest,\n type HostAgentResponse,\n type HostObservation,\n} from \"@air-jam/sdk/runtime-control\";\nimport { createHash, randomUUID } from \"node:crypto\";\nimport {\n mkdir,\n open,\n readFile,\n rename,\n type FileHandle,\n} from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { setTimeout as delay } from \"node:timers/promises\";\nimport type { ControllerDisconnection } from \"./controller-protocol.js\";\nimport { CurrentRoomStopped } from \"./current-room-host.js\";\nimport type { DecisionAnswer, DecisionProvider } from \"./decision-provider.js\";\nimport {\n gameBuildIdentitySchema,\n type PinnedGameBuild,\n} from \"./game-build-protocol.js\";\nimport { sealGameBuild, verifyPinnedGameBuild } from \"./game-build.js\";\nimport {\n currentRoomAttachmentSchema,\n gameRunAddressSchema,\n gameRunRecordSchema,\n gameRunSessionIdentitySchema,\n gameRunSteerSchema,\n MAXIMUM_GAME_RUN_MS,\n MAXIMUM_GAME_RUN_STEERING_CHANGES,\n MAXIMUM_GAME_RUN_TRACE_BYTES,\n startGameRunSchema,\n type AirJamGameRunCancellation,\n type AirJamGameRunRecord,\n type CurrentRoomAttachment,\n type GameRunSteerOptions,\n type StartGameRunOptions,\n} from \"./game-run-protocol.js\";\nimport { readGameRunArtifact } from \"./game-run-record.js\";\nimport {\n gameRunWatchRequestSchema,\n type GameRunWatchEvent,\n type GameSurfaceWatcher,\n} from \"./game-run-watch.js\";\nimport { inspectGame } from \"./games.js\";\nimport { startHeadlessRoom, type HeadlessRoom } from \"./headless-room.js\";\nimport {\n assertProcessScopesConfirmed,\n type ProcessScopeObserver,\n} from \"./managed-process-scope.js\";\nimport { verifyPolicyArtifacts } from \"./policy-artifacts.js\";\nimport { startTestProfileProcess } from \"./test-profile-process.js\";\nimport type {\n AirJamDecisionQuestion,\n AirJamPlayControl,\n AirJamPolicyDecision,\n AirJamRunPlayers,\n AirJamRunReceipt,\n AirJamScenarioVerdict,\n AirJamTestProfileDescription,\n} from \"./testing.js\";\nimport { PLAY_RUN_PLAYER } from \"./testing.js\";\nimport type {\n AirJamGameInspection,\n AirJamGameSessionSummary,\n CloseGameSessionResult,\n} from \"./types.js\";\n\ntype HostObservationIdentity = HostObservation[\"identity\"];\ntype AnsweredDecision = DecisionAnswer & {\n control: AirJamPlayControl;\n durationMs: number;\n note?: \"Only option; no model asked.\";\n};\n\ntype EndReason = NonNullable<AirJamGameRunRecord[\"end\"]>[\"reason\"];\n/** Answers below this confidence count as unsure; this many in a row is a stretch. */\nconst LOW_CONFIDENCE = 0.6;\nconst LOW_CONFIDENCE_STRETCH = 3;\nfunction agentNickname(index: number) {\n return `Agent ${index + 1}`;\n}\nfunction failureReason(message: string): EndReason {\n return /trace_budget/.test(message)\n ? \"trace_budget\"\n : /runtime_replaced|observation_replaced|stale_identity/.test(message)\n ? \"runtime_replaced\"\n : /seat_replaced/.test(message)\n ? \"seat_replaced\"\n : \"error\";\n}\nexport type { AirJamGameRunRecord } from \"./game-run-protocol.js\";\n\nexport type GameRunParticipant = {\n watch: GameSurfaceWatcher;\n controllerId: string;\n checkConnected: () => Promise<void>;\n observe: (options: {\n scope: \"player\" | \"diagnostic\";\n includeImage: boolean;\n expected?: HostObservationIdentity;\n }) => Promise<HostObservation>;\n control: (\n request: Pick<ControllerLeasedControl, \"expected\" | \"lease\" | \"operation\">,\n ) => Promise<ControllerLeasedControlAck>;\n close: () => Promise<ControllerDisconnection>;\n forceClose: () => Promise<ControllerDisconnection>;\n};\n/**\n * The time a run plays on. A live room plays on the wall clock; a headless\n * room's clock is game time, which moves only while the run waits on it.\n */\nexport type GameRunClock = {\n now: () => number;\n wait: (ms: number, signal?: AbortSignal) => Promise<void>;\n};\nexport const wallClock: GameRunClock = {\n now: () => performance.now(),\n wait: (ms, signal) => delay(ms, undefined, { signal }),\n};\nexport type GameRunSession = Omit<\n GameRunParticipant,\n \"controllerId\" | \"close\" | \"forceClose\"\n> & {\n summary: AirJamGameSessionSummary;\n clock: GameRunClock;\n watchHost: GameSurfaceWatcher;\n requestHost?: (\n request: HostAgentRequest,\n timeoutMs: number,\n ) => Promise<HostAgentResponse>;\n readParticipants: () => Promise<{ roomId: string; controllerIds: string[] }>;\n addParticipant: (nickname: string) => Promise<GameRunParticipant>;\n invokeHost: (actionId: string, input: unknown) => Promise<unknown>;\n close: () => Promise<CloseGameSessionResult>;\n forceClose: () => Promise<CloseGameSessionResult>;\n};\ntype RunSeat = {\n id: string;\n controllerId: string;\n participant: Pick<\n GameRunParticipant,\n \"observe\" | \"control\" | \"checkConnected\" | \"watch\"\n >;\n extra?: GameRunParticipant;\n expected?: HostObservationIdentity;\n leaseId: string;\n sequence: number;\n policyCursor: number;\n misses: number;\n staleDecisions: number;\n lowConfidenceStreak: number;\n /** The model's answer to this seat's latest question, for its policy. */\n lastAnswer: { choice: string; confidence: number } | null;\n};\ntype Run = {\n record: AirJamGameRunRecord;\n players?: AirJamRunPlayers;\n /** The host's simulation pace when play began, to measure play against. */\n paceStart?: NonNullable<HostObservation[\"pace\"]>;\n attachment?: CurrentRoomAttachment;\n /** The room a headless run plays in, owned by this run. */\n room?: HeadlessRoom;\n /** The session clock's reading when play began. */\n playStartedAt?: number;\n clipStarted?: boolean;\n fromTick?: number;\n directory: string;\n abort: AbortController;\n session?: GameRunSession;\n build?: PinnedGameBuild;\n scopes: Array<() => Promise<void>>;\n watches: Map<string, Promise<void>>;\n policy?: Awaited<ReturnType<typeof startTestProfileProcess>>;\n evaluator?: Awaited<ReturnType<typeof startTestProfileProcess>>;\n evaluation?: Promise<AirJamScenarioVerdict>;\n evaluationCursor: number;\n playEvaluationSent: boolean;\n receiptIndex: number;\n effects: Set<Promise<ControllerLeasedControlAck>>;\n seats: RunSeat[];\n receipts: AirJamRunReceipt[];\n startup?: Promise<void>;\n startupSteps: Set<string>;\n admission?: Promise<void>;\n persistence: Promise<void>;\n tracing: Promise<void>;\n /** Open while the run writes its trace; null once the trace is sealed. */\n traceFile?: FileHandle | null;\n traceBytes: number;\n traceTruncated: boolean;\n termination?: Promise<void>;\n finished: AbortController;\n closed?: CloseGameSessionResult;\n deadline: number;\n timer?: ReturnType<typeof setTimeout>;\n};\n\nexport class GameRunOwner {\n private runs = new Map<string, Run>();\n private admissions = new Set<Promise<unknown>>();\n private draining = false;\n private stoppingAll: Promise<AirJamGameRunRecord[]> | undefined;\n private directory: string;\n constructor(\n private readonly options: {\n projectDir: string;\n ownerInstanceId: string;\n openSession: (options: {\n runId: string;\n gameId?: string;\n game?: AirJamGameInspection;\n nickname: string;\n settings?: Record<string, number | boolean | string>;\n attachment?: CurrentRoomAttachment;\n build?: PinnedGameBuild;\n room?: HeadlessRoom;\n onScope: ProcessScopeObserver;\n }) => Promise<GameRunSession>;\n sessionClosed: (gameSessionId: string) => void;\n decisions?: DecisionProvider;\n },\n ) {\n this.directory = path.join(\n options.projectDir,\n \".airjam\",\n \"artifacts\",\n \"runs\",\n );\n }\n\n private persist(run: Run) {\n const source = `${JSON.stringify(gameRunRecordSchema.parse(run.record), null, 2)}\\n`;\n const pending = run.persistence.then(async () => {\n const temporary = path.join(run.directory, \"record.pending.json\");\n await open(temporary, \"w\", 0o600).then(async (file) => {\n try {\n await file.writeFile(source);\n } finally {\n await file.close();\n }\n });\n await rename(temporary, path.join(run.directory, \"record.json\"));\n });\n run.persistence = pending.catch(() => undefined);\n return pending;\n }\n private trace(run: Run, event: Record<string, unknown>, diagnostic = false) {\n const bytes = Buffer.from(\n `${JSON.stringify({ at: new Date().toISOString(), ...event })}\\n`,\n );\n const writing = run.tracing.then(async () => {\n const limit = run.abort.signal.aborted\n ? MAXIMUM_GAME_RUN_TRACE_BYTES\n : MAXIMUM_GAME_RUN_TRACE_BYTES - 131_072;\n if (run.traceBytes + bytes.byteLength > limit) {\n if (diagnostic) return;\n run.traceTruncated = true;\n if (run.abort.signal.aborted) return;\n throw new Error(\"trace_budget: Run trace reached its byte allowance.\");\n }\n if (run.traceFile === null)\n throw new Error(\"trace_closed: The run trace is already sealed.\");\n run.traceFile ??= await open(\n path.join(run.directory, \"trace.ndjson\"),\n \"a\",\n 0o600,\n );\n await run.traceFile.writeFile(bytes);\n run.traceBytes += bytes.byteLength;\n });\n // The caller receives failures; the journal must still accept teardown events.\n run.tracing = writing.catch(() => undefined);\n return writing;\n }\n private copy(record: AirJamGameRunRecord): AirJamGameRunRecord {\n return structuredClone(record);\n }\n private quiescent(run: Run) {\n return (\n run.record.state === \"ended\" &&\n run.record.cleanup?.processesClosed === true &&\n (!run.session ||\n (run.record.cleanup.close?.closed &&\n run.record.cleanup.participantsClosed))\n );\n }\n private observeScopes(run: Run): ProcessScopeObserver {\n return (close) => {\n run.scopes.push(close);\n if (run.abort.signal.aborted)\n void close().catch((error) => console.error(error));\n };\n }\n private prune() {\n const ended = [...this.runs.values()].filter((run) => this.quiescent(run));\n for (const expired of ended.slice(0, Math.max(0, ended.length - 32)))\n this.runs.delete(expired.record.runId);\n }\n\n async discover(\n gameId?: string,\n ): Promise<{ gameId: string; profiles: AirJamTestProfileDescription[] }> {\n if (this.draining || this.stoppingAll)\n throw new Error(\"owner_stopping: Profile discovery admission is closed.\");\n if ([...this.runs.values()].some((run) => !this.quiescent(run)))\n throw new Error(\n \"run_busy: Wait for the current run to finish before inspecting profiles.\",\n );\n assertProcessScopesConfirmed();\n const discovery = (async () => {\n const game = await this.game(gameId);\n await mkdir(this.directory, { recursive: true });\n const policy = await startTestProfileProcess({\n rootDir: game.rootDir,\n configPath: game.configPath,\n seed: 0,\n role: \"discover\",\n logPath: path.join(this.directory, \"discovery.log\"),\n });\n try {\n return { gameId: game.id, profiles: policy.profiles };\n } finally {\n await policy.stop();\n }\n })();\n this.admissions.add(discovery);\n try {\n return await discovery;\n } finally {\n this.admissions.delete(discovery);\n }\n }\n private async game(gameId?: string) {\n const game = await inspectGame({ cwd: this.options.projectDir, gameId });\n if (!game?.configPath)\n throw new Error(\"Choose a game that publishes an Air Jam config.\");\n return { ...game, configPath: game.configPath };\n }\n\n async start(\n input: StartGameRunOptions,\n attachment?: CurrentRoomAttachment,\n ): Promise<AirJamGameRunRecord> {\n if (this.draining || this.stoppingAll)\n throw new Error(\"owner_stopping: Run admission is closed.\");\n const request = startGameRunSchema.parse({\n ...input,\n cwd: this.options.projectDir,\n });\n const existing = this.runs.get(request.runId);\n if (existing) {\n if (JSON.stringify(existing.record.request) !== JSON.stringify(request))\n throw new Error(\n \"run_conflict: Run ID was admitted with a different request.\",\n );\n await existing.admission;\n return this.copy(existing.record);\n }\n if (request.target.kind === \"current\" && !attachment)\n throw new Error(\n \"current_attachment_required: Current-room play requires a delegated editor.\",\n );\n if (request.target.kind !== \"current\" && attachment)\n throw new Error(\n \"unexpected_attachment: Owned and headless tests do not accept current-room access.\",\n );\n const current = attachment\n ? currentRoomAttachmentSchema.parse(attachment)\n : undefined;\n if ([...this.runs.values()].some((run) => !this.quiescent(run)))\n throw new Error(\n \"run_busy: This project already has an active or unclosed run.\",\n );\n assertProcessScopesConfirmed();\n const priorAdmissions = [...this.admissions];\n const run: Run = {\n attachment: current,\n scopes: [],\n watches: new Map(),\n record: {\n version: 1,\n runId: request.runId,\n ownerInstanceId: this.options.ownerInstanceId,\n request,\n state: \"starting\",\n startedAt: new Date().toISOString(),\n seats: [],\n evidence: {\n observation: null,\n error: null,\n clip: {\n status: \"not-captured\",\n reason:\n request.target.kind === \"headless\"\n ? \"headless\"\n : \"host-unavailable\",\n },\n },\n counters: {\n steps: 0,\n applied: 0,\n rejected: 0,\n unconfirmed: 0,\n missed: 0,\n },\n },\n directory: path.join(this.directory, request.runId),\n abort: new AbortController(),\n seats: [],\n startupSteps: new Set([\"the game had not been resolved\"]),\n evaluationCursor: 0,\n playEvaluationSent: false,\n receiptIndex: 0,\n effects: new Set(),\n receipts: [],\n deadline:\n performance.now() +\n (request.kind === \"play\"\n ? MAXIMUM_GAME_RUN_MS\n : request.budget.durationMs),\n persistence: Promise.resolve(),\n tracing: Promise.resolve(),\n traceBytes: 0,\n traceTruncated: false,\n finished: new AbortController(),\n };\n this.runs.set(request.runId, run);\n const admission = (async () => {\n await Promise.allSettled(priorAdmissions);\n assertProcessScopesConfirmed();\n await mkdir(this.directory, { recursive: true });\n try {\n await mkdir(run.directory, { mode: 0o700 });\n } catch (error) {\n if (\n !(error instanceof Error) ||\n !(\"code\" in error) ||\n error.code !== \"EEXIST\"\n )\n throw error;\n try {\n await readFile(path.join(run.directory, \"cancelled.json\"));\n throw new Error(\n \"run_cancelled: This run ID was fenced before admission.\",\n );\n } catch (error) {\n if (\n !(error instanceof Error) ||\n !(\"code\" in error) ||\n error.code !== \"ENOENT\"\n )\n throw error;\n }\n const retained = gameRunRecordSchema.parse(\n JSON.parse(\n await readFile(path.join(run.directory, \"record.json\"), \"utf8\"),\n ),\n );\n if (retained.ownerInstanceId !== this.options.ownerInstanceId)\n throw new Error(\n \"run_id_reused: A previous owner admitted this run ID.\",\n );\n if (JSON.stringify(retained.request) !== JSON.stringify(request))\n throw new Error(\n \"run_conflict: Run ID was admitted with a different request.\",\n );\n if (retained.state !== \"ended\")\n throw new Error(\n \"run_receipt_invalid: Retained run has no live activity or terminal receipt.\",\n );\n run.record = retained;\n return;\n }\n await this.persist(run);\n })();\n run.admission = admission;\n this.admissions.add(admission);\n try {\n await admission;\n } catch (error) {\n this.runs.delete(request.runId);\n throw error;\n } finally {\n this.admissions.delete(admission);\n }\n if (run.record.state === \"ended\") {\n this.prune();\n return this.copy(run.record);\n }\n if (run.abort.signal.aborted || this.draining) {\n await this.terminate(\n run,\n \"owner_stopping\",\n \"Run admission stopped before startup.\",\n );\n return this.copy(run.record);\n }\n run.timer = setTimeout(\n () => {\n void this.terminate(\n run,\n run.record.request.kind === \"play\" ? \"safety_deadline\" : \"budget\",\n run.record.request.kind === \"play\"\n ? \"Play reached its ten-minute safety deadline.\"\n : this.startupBudgetMessage(run),\n ).catch((error) => console.error(error));\n },\n Math.max(0, run.deadline - performance.now()),\n );\n run.startup = this.initialize(run);\n void run.startup.then(\n () => {\n if (!run.abort.signal.aborted)\n void this.play(run).catch((error) => this.failed(run, error));\n },\n (error) => this.failed(run, error),\n );\n return this.copy(run.record);\n }\n\n async read(runId: string): Promise<AirJamGameRunRecord> {\n const run = this.runs.get(runId);\n if (run) {\n if (run.record.state === \"ended\") await run.termination;\n return this.copy(run.record);\n }\n const source = await readFile(\n path.join(this.directory, runId, \"record.json\"),\n \"utf8\",\n );\n const record = gameRunRecordSchema.parse(JSON.parse(source));\n if (\n record.ownerInstanceId !== this.options.ownerInstanceId &&\n record.state !== \"ended\"\n )\n return {\n ...record,\n state: \"ended\" as const,\n end: {\n reason: \"owner_lost\" as const,\n ...(record.request.kind === \"test\"\n ? { outcome: \"inconclusive\" as const }\n : {}),\n message:\n \"The session owner was replaced. This run cannot resume and has no confirmed teardown.\",\n },\n };\n return record;\n }\n list(): AirJamGameRunRecord[] {\n return [...this.runs.values()].map((run) => this.copy(run.record));\n }\n async wait(\n runId: string,\n timeoutMs: number,\n signal?: AbortSignal,\n ): Promise<AirJamGameRunRecord> {\n const run = this.runs.get(runId);\n if (!run || run.record.state === \"ended\") return this.read(runId);\n const cancellation = new AbortController();\n const combined = signal\n ? AbortSignal.any([signal, cancellation.signal])\n : cancellation.signal;\n let completed = () => {};\n const finished = new Promise<void>((resolve) => {\n completed = resolve;\n run.finished.signal.addEventListener(\"abort\", completed, { once: true });\n });\n try {\n await Promise.race([\n finished,\n delay(timeoutMs, undefined, { signal: combined }),\n ]);\n return await this.read(runId);\n } finally {\n cancellation.abort();\n run.finished.signal.removeEventListener(\"abort\", completed);\n }\n }\n async stop(\n runId: string,\n reason: EndReason = \"stopped\",\n ): Promise<AirJamGameRunRecord> {\n const run = this.runs.get(runId);\n if (!run || run.record.state === \"ended\") return this.read(runId);\n run.record.stopRequestedAt ??= new Date().toISOString();\n await this.terminate(\n run,\n reason,\n reason === \"stopped\" ? \"Stopped by the caller.\" : reason,\n );\n return this.copy(run.record);\n }\n /**\n * Change what one seat is trying to do while its run is active. Steering only\n * changes the intent its policy reads; controls still come from the policy.\n * Each change is recorded with its time and source.\n */\n async steer(input: GameRunSteerOptions): Promise<AirJamGameRunRecord> {\n const { runId, seatId, intent, source } = gameRunSteerSchema.parse(input);\n const run = this.runs.get(runId);\n if (\n !run ||\n run.abort.signal.aborted ||\n run.record.state === \"ended\" ||\n run.record.state === \"stopping\"\n )\n throw new Error(\"run_not_active: Only an active test can be steered.\");\n if (!run.record.seats.length)\n throw new Error(\n \"run_not_active: Seats are not ready yet; give starting goals as intents.\",\n );\n const seat = run.record.seats.find(\n (candidate) => candidate.seatId === seatId,\n );\n if (!seat)\n throw new Error(`run_seat_unknown: Run ${runId} has no seat ${seatId}.`);\n const steering = (run.record.steering ??= []);\n if (steering.length >= MAXIMUM_GAME_RUN_STEERING_CHANGES)\n throw new Error(\n `steering_limit: A run records at most ${MAXIMUM_GAME_RUN_STEERING_CHANGES} steering changes.`,\n );\n seat.intent = intent;\n steering.push({ at: new Date().toISOString(), seatId, intent, source });\n await this.trace(run, { kind: \"steer\", seatId, intent, source });\n await this.persist(run);\n return this.copy(run.record);\n }\n stopAll(): Promise<AirJamGameRunRecord[]> {\n return (this.stoppingAll ??= (async () => {\n await Promise.allSettled(this.admissions);\n const pending = [...this.runs.values()].filter(\n (run) => !this.quiescent(run),\n );\n const records = await Promise.all(\n pending.map((run) => this.stop(run.record.runId)),\n );\n assertProcessScopesConfirmed();\n return records;\n })().finally(() => {\n this.stoppingAll = undefined;\n }));\n }\n async cancel(runId: string): Promise<AirJamGameRunCancellation> {\n gameRunAddressSchema.parse({ runId });\n const result = (record: AirJamGameRunRecord | null) => ({\n runId,\n ownerInstanceId: this.options.ownerInstanceId,\n fenced: true as const,\n record,\n });\n if (this.runs.has(runId)) return result(await this.stop(runId));\n assertProcessScopesConfirmed();\n await mkdir(this.directory, { recursive: true });\n const directory = path.join(this.directory, runId);\n try {\n await mkdir(directory, { mode: 0o700 });\n } catch (error) {\n if (\n !(error instanceof Error) ||\n !(\"code\" in error) ||\n error.code !== \"EEXIST\"\n )\n throw error;\n if (this.runs.has(runId)) return result(await this.stop(runId));\n try {\n return result(await this.read(runId));\n } catch (readError) {\n if (\n !(readError instanceof Error) ||\n !(\"code\" in readError) ||\n readError.code !== \"ENOENT\"\n )\n throw readError;\n }\n }\n const marker = await open(\n path.join(directory, \"cancelled.json\"),\n \"wx\",\n 0o600,\n ).catch((error: NodeJS.ErrnoException) => {\n if (error.code === \"EEXIST\") return null;\n throw error;\n });\n if (marker) {\n try {\n await marker.writeFile(\n JSON.stringify({ runId, cancelledAt: new Date().toISOString() }),\n );\n } finally {\n await marker.close();\n }\n }\n return result(null);\n }\n async closeSession(runId: string, reason: EndReason) {\n const run = this.runs.get(runId);\n if (!run)\n throw new Error(\n \"run_session_unavailable: No live activity owns this session.\",\n );\n await this.terminate(run, reason, reason);\n if (!this.quiescent(run) || !run.closed?.closed)\n throw new Error(\n \"run_cleanup_unconfirmed: Local runtime teardown was not confirmed.\",\n );\n return run.closed;\n }\n async drain() {\n this.draining = true;\n await Promise.allSettled(this.admissions);\n const results = await Promise.allSettled(\n [...this.runs.values()].map((run) =>\n this.terminate(run, \"owner_stopping\", \"Session owner is stopping.\"),\n ),\n );\n const failures = results.flatMap((result) =>\n result.status === \"rejected\" ? [result.reason] : [],\n );\n if (failures.length)\n throw new AggregateError(failures, \"Run cleanup failed.\");\n if ([...this.runs.values()].some((run) => !this.quiescent(run)))\n throw new Error(\n \"run_cleanup_unconfirmed: An owned process scope did not close.\",\n );\n assertProcessScopesConfirmed();\n }\n\n private startupBudgetMessage(run: Run) {\n return run.startupSteps.size\n ? `Run reached its time budget during startup: ${[...run.startupSteps].join(\"; \")}.`\n : \"Run reached its time budget.\";\n }\n\n private async initialize(run: Run) {\n const game = await this.game(run.record.request.gameId);\n if (run.abort.signal.aborted) return;\n run.startupSteps.delete(\"the game had not been resolved\");\n await this.trace(run, { kind: \"game_resolved\", gameId: game.id });\n if (run.record.request.target.kind === \"owned\") {\n run.startupSteps.add(\"the build had not been sealed or reused\");\n run.build = await sealGameBuild({\n projectDir: game.rootDir,\n configRelative: path.relative(game.rootDir, game.configPath),\n runDirectory: run.directory,\n signal: run.abort.signal,\n onScope: this.observeScopes(run),\n onBuildLog: (receipt) => {\n run.record.evidence ??= { observation: null, error: null };\n run.record.evidence.buildLog = {\n ...receipt,\n path: `.airjam/artifacts/runs/${run.record.runId}/build.log`,\n };\n },\n });\n run.record.build = {\n ...gameBuildIdentitySchema.parse(run.build.manifest),\n integrity: \"sealed\",\n };\n run.startupSteps.delete(\"the build had not been sealed or reused\");\n await this.trace(run, {\n kind: \"build_sealed\",\n build: run.record.build,\n reused: run.build.reused,\n });\n await this.persist(run);\n }\n if (run.abort.signal.aborted) return;\n const common = {\n rootDir: run.build?.rootDir ?? game.rootDir,\n ...(run.build ? { toolingRootDir: run.build.rootDir } : {}),\n configPath: run.build?.configPath ?? game.configPath,\n runKind: run.record.request.kind,\n ...(run.record.request.kind === \"test\"\n ? { profileId: run.record.request.profileId }\n : {}),\n seed: run.record.request.seed,\n onScope: this.observeScopes(run),\n startupSignal: run.abort.signal,\n };\n // The room starts alongside the profile processes; it needs only the game.\n const room =\n run.record.request.target.kind === \"headless\"\n ? startHeadlessRoom({\n rootDir: common.rootDir,\n configPath: common.configPath,\n seed: run.record.request.seed,\n settings:\n run.record.request.kind === \"test\"\n ? run.record.request.settings\n : undefined,\n logPath: path.join(run.directory, \"room.log\"),\n onScope: common.onScope,\n startupSignal: run.abort.signal,\n })\n : undefined;\n room?.catch(() => undefined);\n const request = run.record.request;\n let profile: AirJamTestProfileDescription | undefined;\n if (request.kind === \"test\") {\n run.startupSteps.add(\"the evaluator had not started\");\n run.evaluator = await startTestProfileProcess({\n ...common,\n role: \"evaluator\",\n logPath: path.join(run.directory, \"evaluator.log\"),\n });\n if (run.abort.signal.aborted) return;\n run.startupSteps.delete(\"the evaluator had not started\");\n await this.trace(run, { kind: \"evaluator_started\" });\n profile = run.evaluator.profiles.find(\n (candidate) => candidate.id === request.profileId,\n );\n if (!profile) throw new Error(\"Unknown test profile.\");\n const seats = profile.seats;\n const unknownIntent = Object.keys(request.intents ?? {}).find(\n (seatId) => !seats.some((seat) => seat.id === seatId),\n );\n if (unknownIntent)\n throw new Error(\n `run_intent_invalid: Profile ${profile.id} has no seat ${unknownIntent}.`,\n );\n run.record.profile = profile;\n }\n const players = profile ?? PLAY_RUN_PLAYER;\n run.players = players;\n if (run.attachment && players.seats.length > run.attachment.seats)\n throw new Error(\n \"current_profile_invalid: The creator's room issued too few seats.\",\n );\n const policy =\n request.kind === \"test\"\n ? profile?.policies.find(\n (candidate) => candidate.id === request.policyId,\n )\n : { id: \"model\", label: \"Decision model\", artifacts: undefined };\n if (!policy) throw new Error(\"Unknown test policy.\");\n run.startupSteps.add(\"the policy had not been prepared\");\n const artifacts =\n policy.artifacts === undefined\n ? undefined\n : await verifyPolicyArtifacts({\n projectDir: common.rootDir,\n manifestPath: path.join(common.rootDir, policy.artifacts),\n artifactRootDir: process.env.AIRJAM_TEST_ARTIFACTS_DIR,\n signal: run.abort.signal,\n });\n run.record.policyArtifacts = artifacts?.receipt;\n const preparing = (async () => {\n const initializing = performance.now();\n run.policy = await startTestProfileProcess({\n ...common,\n role: \"policy\",\n initializationDeadline: run.deadline,\n ...(artifacts ? { artifacts } : {}),\n policyId: policy.id,\n logPath: path.join(run.directory, \"policy.log\"),\n });\n if (run.abort.signal.aborted) return;\n run.record.policyInitializationMs = performance.now() - initializing;\n run.record.policyPreparation = run.policy.preparation;\n run.startupSteps.delete(\"the policy had not been prepared\");\n await this.trace(run, {\n kind: \"policy_prepared\",\n initializationMs: run.record.policyInitializationMs,\n preparation: run.policy.preparation,\n ...(artifacts ? { artifacts: artifacts.receipt } : {}),\n });\n })();\n run.startupSteps.add(\"the session had not opened\");\n const attaching = (async () => {\n if (run.abort.signal.aborted) return;\n if (room) {\n run.room = await room;\n if (run.abort.signal.aborted) return;\n }\n run.session = await this.options.openSession({\n runId: run.record.runId,\n gameId: game.id,\n game,\n nickname: agentNickname(0),\n settings:\n run.record.request.kind === \"test\"\n ? run.record.request.settings\n : undefined,\n attachment: run.attachment,\n build: run.build,\n room: run.room,\n onScope: this.observeScopes(run),\n });\n if (run.abort.signal.aborted) return;\n run.startupSteps.delete(\"the session had not opened\");\n await this.trace(run, {\n kind: \"session_opened\",\n gameSessionId: run.session.summary.gameSessionId,\n });\n run.startupSteps.add(\"the participants had not become ready\");\n run.record.session = gameRunSessionIdentitySchema.parse(\n run.session.summary,\n );\n if (\n run.attachment &&\n (run.session.summary.semanticAccess !== \"delegated-host\" ||\n run.session.summary.roomId !==\n new URL(run.attachment.controllerJoinUrl).searchParams.get(\"room\"))\n )\n throw new Error(\n \"current_room_scope: The delegated participant did not attach to its authorized room.\",\n );\n for (const [index, description] of players.seats.entries()) {\n if (index > 0 && run.abort.signal.aborted) return;\n const extra =\n index === 0\n ? undefined\n : await run.session.addParticipant(agentNickname(index));\n const controllerId =\n extra?.controllerId ?? run.session.summary.controllerId;\n run.seats.push({\n id: description.id,\n controllerId,\n participant: extra ?? run.session,\n extra,\n leaseId: randomUUID(),\n sequence: 0,\n policyCursor: 0,\n misses: 0,\n staleDecisions: 0,\n lowConfidenceStreak: 0,\n lastAnswer: null,\n });\n run.record.seats.push({\n seatId: description.id,\n controllerId,\n intent:\n request.kind === \"play\"\n ? (request.intent ?? null)\n : (request.intents?.[description.id] ?? null),\n counters: {\n decisions: 0,\n applied: 0,\n rejected: 0,\n unconfirmed: 0,\n timeout: 0,\n blocked: 0,\n effects: 0,\n },\n });\n }\n if (run.abort.signal.aborted) return;\n run.record.state = \"setup\";\n for (const seat of run.seats) {\n const first = await this.observe(run, seat, false);\n seat.expected = first.identity;\n this.seatRecord(run, seat).expected = first.identity;\n if (seat === run.seats[0]) {\n run.record.expected = first.identity;\n run.fromTick = first.ticks.after ?? 0;\n }\n if (run.abort.signal.aborted) return;\n if (\n (await this.control(run, seat, first, { kind: \"release\" }, \"setup\"))\n .status !== \"applied\"\n )\n throw new Error(\n \"Participant control handshake was not acknowledged.\",\n );\n }\n const expectedParticipants = run.seats.map((seat) => seat.controllerId);\n const participantsDeadline = performance.now() + 5000;\n let participants = await run.session.readParticipants();\n while (\n !expectedParticipants.every((id) =>\n participants.controllerIds.includes(id),\n )\n ) {\n if (run.abort.signal.aborted) return;\n if (performance.now() >= participantsDeadline)\n throw new Error(\n \"seat_replaced: The connected room roster did not include every run player.\",\n );\n await delay(25);\n participants = await run.session.readParticipants();\n }\n if (run.abort.signal.aborted) return;\n if (\n participants.roomId !== run.session.summary.roomId ||\n (run.record.request.target.kind !== \"current\" &&\n participants.controllerIds.length !== expectedParticipants.length)\n )\n throw new Error(\n \"seat_replaced: Owned room membership does not match its controlled players.\",\n );\n run.startupSteps.delete(\"the participants had not become ready\");\n run.record.rosterJoinedAt = new Date().toISOString();\n await this.trace(run, {\n kind: \"participants_ready\",\n gameSessionId: run.session.summary.gameSessionId,\n expected: run.record.expected,\n ...participants,\n });\n })();\n const startup = await Promise.allSettled([preparing, attaching]);\n for (const result of startup)\n if (result.status === \"rejected\") throw result.reason;\n if (run.abort.signal.aborted) return;\n const session = run.session;\n if (!session)\n throw new Error(\"Run participant attachment did not complete.\");\n run.startupSteps.add(\"the profile setup had not finished\");\n if (\n !(await this.runProfileSteps(run, session, profile?.setup ?? [], \"setup\"))\n )\n return;\n await this.persist(run);\n run.startupSteps.delete(\"the profile setup had not finished\");\n }\n /**\n * A profile's setup or hand-back steps, in order. Setup stops with the run\n * and its startup budget and retries a stale participant action until then;\n * hand-back runs after play has stopped and retries a stale action twice.\n * Returns false when setup stopped early.\n */\n private async runProfileSteps(\n run: Run,\n session: GameRunSession,\n steps: AirJamTestProfileDescription[\"setup\"],\n phase: \"setup\" | \"cleanup\",\n ) {\n const name = phase === \"setup\" ? \"Setup\" : \"Hand-back\";\n for (const step of steps) {\n if (phase === \"setup\" && run.abort.signal.aborted) return false;\n if (step.lane === \"host\") {\n const result = await session.invokeHost(step.actionId, step.input);\n await this.trace(run, {\n kind: phase === \"setup\" ? \"host_setup\" : \"host_hand_back\",\n actionId: step.actionId,\n result,\n });\n continue;\n }\n const seat = run.seats.find((candidate) => candidate.id === step.seatId);\n if (!seat) throw new Error(`${name} seat is not initialized.`);\n for (let attempt = 1; ; attempt++) {\n if (phase === \"setup\") {\n if (run.abort.signal.aborted) return false;\n if (performance.now() >= run.deadline) {\n // Teardown waits for startup, so it cannot be awaited here.\n void this.terminate(\n run,\n \"budget\",\n this.startupBudgetMessage(run),\n ).catch((error) => console.error(error));\n return false;\n }\n }\n const observation = await this.observe(run, seat, false);\n const receipt = await this.control(\n run,\n seat,\n observation,\n {\n kind: \"action\",\n actionId: step.actionId,\n input: step.input,\n deadlineMs: this.deadline(observation),\n },\n phase,\n );\n if (\n receipt.status === \"rejected\" &&\n receipt.reason === \"stale_decision\" &&\n (phase === \"setup\" || attempt < 3)\n )\n continue;\n if (\n receipt.status !== \"applied\" ||\n receipt.operation.kind !== \"action\" ||\n !receipt.operation.result.ok\n )\n throw new Error(`${name} action ${step.actionId} was not accepted.`);\n break;\n }\n }\n return true;\n }\n async watch(\n input: unknown,\n onEvent: (event: GameRunWatchEvent) => void,\n signal: AbortSignal,\n ) {\n const request = gameRunWatchRequestSchema.parse(input);\n assertProcessScopesConfirmed();\n const run = this.runs.get(request.runId);\n if (\n !run ||\n run.record.request.target.kind !== \"owned\" ||\n !run.session ||\n ![\"setup\", \"playing\"].includes(run.record.state)\n )\n throw new Error(\n \"run_watch_unavailable: Only an active owned game can be watched.\",\n );\n const surfaceKey = JSON.stringify(request.surface);\n if (run.watches.has(surfaceKey))\n throw new Error(\n \"run_watch_duplicate: This surface already has a producer.\",\n );\n if (run.watches.size >= 2)\n throw new Error(\"run_watch_limit: At most two surfaces can be produced.\");\n const watcher =\n request.surface.kind === \"host\"\n ? run.session.watchHost\n : (() => {\n const seat = run.seats.find(\n (candidate) =>\n request.surface.kind === \"controller\" &&\n candidate.id === request.surface.seatId,\n );\n if (!seat)\n throw new Error(\n \"run_watch_seat: This player does not belong to the run.\",\n );\n return seat.participant.watch;\n })();\n const active = AbortSignal.any([signal, run.abort.signal]);\n active.throwIfAborted();\n run.record.watched = true;\n const operation = (async () => {\n await this.persist(run);\n await this.trace(\n run,\n { kind: \"watch_started\", surface: request.surface },\n true,\n );\n try {\n await watcher((event) => {\n if (active.aborted) return;\n onEvent(\n event.type === \"ready\"\n ? { ...event, runId: request.runId, surface: request.surface }\n : event,\n );\n }, active);\n } catch (error) {\n await this.trace(\n run,\n {\n kind: \"watch_failed\",\n surface: request.surface,\n message: error instanceof Error ? error.message : String(error),\n },\n true,\n );\n throw error;\n } finally {\n await this.trace(\n run,\n { kind: \"watch_stopped\", surface: request.surface },\n true,\n );\n }\n })();\n run.watches.set(surfaceKey, operation);\n try {\n await operation;\n } finally {\n run.watches.delete(surfaceKey);\n }\n }\n private seatRecord(run: Run, seat: RunSeat) {\n const record = run.record.seats.find(\n (candidate) => candidate.seatId === seat.id,\n );\n if (!record) throw new Error(\"Run seat has no receipt record.\");\n return record;\n }\n private elapsed(run: Run) {\n if (!run.session || run.playStartedAt === undefined)\n throw new Error(\"Run play has not started.\");\n return run.session.clock.now() - run.playStartedAt;\n }\n /**\n * Answer a seat's question and keep that seat's running summary of how the\n * model played it: what it chose, what it missed, and stretches where it\n * stayed unsure, which often means the brief or the game was unclear.\n */\n private async answerFor(\n run: Run,\n seat: RunSeat,\n question: AirJamDecisionQuestion,\n deadline: number,\n ) {\n const record = this.seatRecord(run, seat);\n const answers = (record.answers ??= {\n asked: 0,\n answered: 0,\n missed: 0,\n lowConfidence: 0,\n lowConfidenceStretches: 0,\n choices: {},\n });\n answers.asked++;\n let answer: AnsweredDecision;\n try {\n answer = await this.answer(run, question, deadline);\n } catch (error) {\n answers.missed++;\n throw error;\n }\n answers.answered++;\n answers.choices[answer.choice] = (answers.choices[answer.choice] ?? 0) + 1;\n if (answer.note) {\n answers.automatic = (answers.automatic ?? 0) + 1;\n return answer;\n }\n if (answer.confidence < LOW_CONFIDENCE) {\n answers.lowConfidence++;\n if (++seat.lowConfidenceStreak === LOW_CONFIDENCE_STRETCH)\n answers.lowConfidenceStretches++;\n } else seat.lowConfidenceStreak = 0;\n return answer;\n }\n /**\n * Take the only option directly, or put the question to the run's decision\n * model and map its choice back to the option's own control.\n * It shares the policy's decision deadline, and\n * a late, failed or undeclared answer is a missed decision, never a fallback.\n */\n private async answer(\n run: Run,\n question: AirJamDecisionQuestion,\n deadline: number,\n ): Promise<AnsweredDecision> {\n const options = Object.entries(question.options);\n if (options.length === 1) {\n const [choice, option] = options[0];\n return {\n choice,\n confidence: 1,\n control: option.control,\n durationMs: 0,\n note: \"Only option; no model asked.\",\n };\n }\n const decisions = this.options.decisions;\n if (!decisions)\n throw new Error(\n \"decision_provider_unavailable: This run's policy asks a decision model, but none is configured.\",\n );\n const remaining = deadline - performance.now();\n if (remaining <= 0)\n throw new Error(\"policy_timeout: Decision exceeded its deadline.\");\n run.record.decisionModel ??= decisions.model;\n const started = performance.now();\n const timeout = AbortSignal.timeout(Math.ceil(remaining));\n let answered: DecisionAnswer;\n try {\n answered = await decisions.ask(\n question,\n AbortSignal.any([run.abort.signal, timeout]),\n );\n } catch (error) {\n if (timeout.aborted)\n throw new Error(\n \"policy_timeout: Decision model exceeded its deadline.\",\n );\n throw new Error(\n `decision_failed: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n const option = Object.hasOwn(question.options, answered.choice)\n ? question.options[answered.choice]\n : undefined;\n if (!option)\n throw new Error(\n \"decision_failed: Decision model chose an option the policy did not offer.\",\n );\n return {\n ...answered,\n control: option.control,\n durationMs: performance.now() - started,\n };\n }\n private async startClip(run: Run) {\n run.record.evidence ??= { observation: null, error: null };\n if (run.room) {\n run.record.evidence.clip = { status: \"not-captured\", reason: \"headless\" };\n return;\n }\n const expected = run.record.expected;\n try {\n if (!run.session?.requestHost || !expected)\n throw new Error(\"No host-agent request path is available.\");\n const response = await run.session.requestHost(\n {\n operation: \"clip-start\",\n roomId: expected.roomId,\n runtimeId: expected.runtimeId,\n clipId: run.record.runId,\n },\n 5000,\n );\n if (\n response.operation !== \"clip-start\" ||\n response.clipId !== run.record.runId\n )\n throw new Error(\"Invalid clip start response.\");\n run.clipStarted = true;\n await this.trace(\n run,\n {\n kind: \"clip-start\",\n clipId: run.record.runId,\n },\n true,\n ).catch(() => {});\n } catch (error) {\n run.record.evidence.clip = {\n status: \"not-captured\",\n reason: clipFailureReason(error),\n };\n await this.trace(\n run,\n {\n kind: \"clip-failure\",\n reason: clipFailureReason(error),\n message: error instanceof Error ? error.message : String(error),\n },\n true,\n ).catch(() => {});\n }\n }\n\n private async finishClip(run: Run) {\n run.record.evidence ??= { observation: null, error: null };\n run.record.evidence.clip ??= {\n status: \"not-captured\",\n reason: run.room ? \"headless\" : \"host-unavailable\",\n };\n if (!run.clipStarted) return;\n try {\n const session = run.session;\n const expected = run.record.expected;\n if (!session?.requestHost || !expected)\n throw new Error(\"No recording host is available.\");\n const result = await readHostClip(\n (request) => session.requestHost!(request, 5000),\n run.record.runId,\n expected,\n );\n if (result.status === \"not-captured\") {\n run.record.evidence.clip = result;\n return;\n }\n const source = `${JSON.stringify(result.artifact)}\\n`;\n const file = await open(\n path.join(run.directory, \"clip.json\"),\n \"w\",\n 0o600,\n );\n try {\n await file.writeFile(source);\n } finally {\n await file.close();\n }\n run.record.evidence.clip = {\n status: \"captured\",\n path: `.airjam/artifacts/runs/${run.record.runId}/clip.json`,\n sha256: createHash(\"sha256\").update(source).digest(\"hex\"),\n bytes: Buffer.byteLength(source),\n frames: result.artifact.frames.length,\n durationMs: result.artifact.durationMs,\n };\n } catch (error) {\n run.record.evidence.clip = {\n status: \"not-captured\",\n reason: clipFailureReason(error),\n };\n await this.trace(\n run,\n {\n kind: \"clip-failure\",\n reason: clipFailureReason(error),\n message: error instanceof Error ? error.message : String(error),\n },\n true,\n ).catch(() => {});\n }\n }\n\n private deadline(observation: HostObservation) {\n if (!observation.clock)\n throw new Error(\"Host does not advertise command admission deadlines.\");\n return observation.clock.startedAtMs + PARTICIPANT_CONTROL_DEADLINE_MS;\n }\n private async observe(\n run: Run,\n seat: RunSeat,\n includeImage: boolean,\n diagnostic = false,\n ) {\n if (!run.players) throw new Error(\"Run players are not initialized.\");\n const observation = await seat.participant.observe({\n scope: diagnostic ? \"diagnostic\" : run.players.scope,\n includeImage,\n expected: seat.expected,\n });\n if (\n seat.expected &&\n !sameHostRuntimeIdentity(seat.expected, observation.identity)\n )\n throw new Error(\n \"runtime_replaced: Observed a different host generation.\",\n );\n if (observation.controllerId !== seat.controllerId)\n throw new Error(\n \"seat_replaced: Observation belongs to a different player.\",\n );\n this.trackPace(run, observation);\n return observation;\n }\n /**\n * How fast the host's simulation ran during play, against real time. A\n * starved host plays in slow motion, which quietly makes tests easier, so\n * the record says so.\n */\n private trackPace(run: Run, observation: HostObservation) {\n const pace = observation.pace;\n if (run.record.state !== \"playing\" || !pace) return;\n if (!run.paceStart || pace.wallMs < run.paceStart.wallMs) {\n run.paceStart = pace;\n return;\n }\n const wallMs = pace.wallMs - run.paceStart.wallMs;\n if (wallMs < 1000) return;\n run.record.hostPace = {\n framesPerSecond:\n Math.round(((pace.frames - run.paceStart.frames) / wallMs) * 10_000) /\n 10,\n simulationSpeed:\n Math.round(\n ((pace.simulatedMs - run.paceStart.simulatedMs) / wallMs) * 100,\n ) / 100,\n };\n }\n private pruneReceipts(run: Run) {\n run.receipts = run.receipts.filter(\n (receipt) =>\n (run.record.request.kind === \"test\" &&\n receipt.index > run.evaluationCursor) ||\n receipt.sequence >\n (run.seats.find((seat) => seat.id === receipt.seatId)?.policyCursor ??\n 0),\n );\n }\n private async evaluationObservation(run: Run, includeImage: boolean) {\n const primary = run.seats[0];\n if (!primary?.expected || run.seats.some((seat) => !seat.expected))\n throw new Error(\"Run has no fully initialized observation seats.\");\n const checkSeats = () =>\n Promise.all(run.seats.map((seat) => seat.participant.checkConnected()));\n await checkSeats();\n const observation = await this.observe(\n run,\n primary,\n includeImage,\n run.record.request.kind === \"test\",\n );\n await checkSeats();\n return observation;\n }\n private control(\n run: Run,\n seat: RunSeat,\n observation: Pick<HostObservation, \"id\" | \"identity\">,\n operation: ControllerLeasedControl[\"operation\"],\n phase: \"setup\" | \"play\" | \"cleanup\",\n ) {\n if (phase !== \"cleanup\" && run.abort.signal.aborted)\n return Promise.reject(\n new Error(\"run_stopped: No new effects after Stop.\"),\n );\n const pending = this.applyControl(run, seat, observation, operation, phase);\n run.effects.add(pending);\n void pending\n .finally(() => run.effects.delete(pending))\n .catch(() => undefined);\n return pending;\n }\n private async applyControl(\n run: Run,\n seat: RunSeat,\n observation: Pick<HostObservation, \"id\" | \"identity\">,\n operation: ControllerLeasedControl[\"operation\"],\n phase: \"setup\" | \"play\" | \"cleanup\",\n ) {\n const request = {\n expected: observation.identity,\n lease: { id: seat.leaseId, sequence: ++seat.sequence },\n operation,\n };\n const send = () => {\n if (operation.kind !== \"release\")\n run.record.lastInputAt = new Date().toISOString();\n return seat.participant.control(request);\n };\n let attempts: 1 | 2 = 1;\n let acknowledgement = await send();\n if (acknowledgement.status === \"unconfirmed\") {\n await this.trace(run, {\n kind: \"control_attempt\",\n seatId: seat.id,\n phase,\n observationId: observation.id,\n sequence: seat.sequence,\n operation,\n receipt: acknowledgement,\n });\n if (operation.kind === \"release\" || !run.abort.signal.aborted) {\n attempts = 2;\n acknowledgement = await send();\n }\n }\n if (\n phase === \"cleanup\" &&\n operation.kind === \"release\" &&\n acknowledgement.status === \"applied\"\n )\n run.record.releaseAcknowledgedAt = new Date().toISOString();\n run.record.counters[\n acknowledgement.status === \"applied\"\n ? \"applied\"\n : acknowledgement.status === \"rejected\"\n ? \"rejected\"\n : \"unconfirmed\"\n ]++;\n this.seatRecord(run, seat).counters[\n acknowledgement.status === \"applied\"\n ? \"applied\"\n : acknowledgement.status === \"rejected\"\n ? \"rejected\"\n : \"unconfirmed\"\n ]++;\n if (\n phase === \"play\" &&\n acknowledgement.status === \"applied\" &&\n operation.kind !== \"release\" &&\n (acknowledgement.operation.kind !== \"action\" ||\n acknowledgement.operation.result.ok)\n )\n this.seatRecord(run, seat).counters.effects++;\n const receipt: AirJamRunReceipt = {\n index: ++run.receiptIndex,\n seatId: seat.id,\n phase,\n sequence: seat.sequence,\n attempts,\n operation,\n acknowledgement,\n };\n run.receipts.push(receipt);\n await this.trace(run, {\n kind: \"control\",\n observationId: observation.id,\n ...receipt,\n });\n return acknowledgement;\n }\n private evaluate(\n run: Run,\n phase: \"play\" | \"final\",\n observation?: HostObservation,\n ) {\n if (run.evaluation)\n throw new Error(\"evaluator_busy: A previous evaluation is pending.\");\n const primary = run.seats[0];\n const evaluator = run.evaluator;\n if (!primary || !evaluator)\n throw new Error(\"Scenario evaluator is not initialized.\");\n const through = run.receiptIndex;\n const receipts = run.receipts.filter(\n (receipt) =>\n receipt.index > run.evaluationCursor && receipt.index <= through,\n );\n const pending = (async () => {\n const sample =\n observation ?? (await this.evaluationObservation(run, false));\n run.evaluationCursor = through;\n if (phase === \"play\") run.playEvaluationSent = true;\n const verdict = await evaluator.evaluate(\n {\n phase,\n observation: sample,\n seats: run.seats.map((seat) => ({\n seatId: seat.id,\n controllerId: seat.controllerId,\n })),\n receipts,\n elapsedMs: this.elapsed(run),\n },\n 1000,\n );\n run.record.evaluation ??= {};\n run.record.evaluation[phase] = verdict;\n await this.trace(run, {\n kind: \"evaluation\",\n phase,\n observationId: sample.id,\n through,\n verdict,\n });\n this.pruneReceipts(run);\n return verdict;\n })();\n run.evaluation = pending;\n void pending\n .finally(() => {\n if (run.evaluation === pending) run.evaluation = undefined;\n })\n .catch(() => undefined);\n return pending;\n }\n private async play(run: Run) {\n const profile = run.players;\n const request = run.record.request;\n const policy = run.policy;\n const primary = run.seats[0];\n if (!profile || !policy || !primary)\n throw new Error(\"Run policy is not initialized.\");\n const session = run.session;\n if (!session) throw new Error(\"Run session is not open.\");\n const clock = session.clock;\n await this.startClip(run);\n if (run.abort.signal.aborted) return;\n run.record.state = \"playing\";\n await this.persist(run);\n if (run.abort.signal.aborted) return;\n run.playStartedAt = clock.now();\n run.record.playStartedAt = new Date().toISOString();\n if (request.kind === \"test\") {\n clearTimeout(run.timer);\n run.deadline = performance.now() + request.budget.durationMs;\n run.timer = setTimeout(() => {\n void this.terminate(\n run,\n \"budget\",\n \"Run reached its bounded play budget.\",\n ).catch((error) => console.error(error));\n }, request.budget.durationMs);\n }\n const inFlight = new Map<string, Promise<void>>();\n let lastTick: number | null = null;\n let progressedAt = clock.now();\n while (!run.abort.signal.aborted) {\n const roundStarted = clock.now();\n if (\n request.kind === \"test\" &&\n (this.elapsed(run) >= request.budget.durationMs ||\n (run.record.counters.steps >= request.budget.steps &&\n inFlight.size === 0))\n )\n return this.terminate(\n run,\n \"budget\",\n \"Run reached its bounded play budget.\",\n );\n if (request.kind === \"test\") {\n let verdict: AirJamScenarioVerdict;\n try {\n verdict = await this.evaluate(run, \"play\");\n } catch (error) {\n if (run.abort.signal.aborted) return;\n if (\n !(error instanceof Error) ||\n !/^policy_(timeout|busy):/.test(error.message)\n )\n throw error;\n return this.terminate(\n run,\n \"evaluator_unresponsive\",\n error instanceof Error ? error.message : String(error),\n );\n }\n if (run.abort.signal.aborted) return;\n if (verdict.status === \"failed\")\n return this.terminate(\n run,\n \"failed\",\n verdict.message ?? \"Scenario failed.\",\n );\n if (verdict.status === \"passed\") {\n const tested = run.record.seats.every(\n (seat) => seat.counters.effects > 0,\n );\n return this.terminate(\n run,\n tested ? \"completed\" : \"untested_seat\",\n tested\n ? (verdict.message ?? \"Scenario passed.\")\n : \"The scenario passed before every seat produced an applied play effect.\",\n );\n }\n }\n for (const seat of run.seats) {\n if (run.abort.signal.aborted) return;\n if (inFlight.has(seat.id)) continue;\n if (\n request.kind === \"test\" &&\n run.record.counters.steps >= request.budget.steps\n )\n break;\n const started = performance.now();\n const observation = await this.observe(\n run,\n seat,\n run.record.request.target.kind === \"owned\" && profile.includeImage,\n );\n if (run.abort.signal.aborted) return;\n const tick = observation.ticks.after;\n if (tick !== lastTick) {\n lastTick = tick;\n progressedAt = clock.now();\n }\n const fault = observation.host?.after?.fault;\n if (\n observation.host?.after?.connectionStatus !== \"connected\" ||\n observation.host.after.runtimeState !== \"playing\" ||\n (tick !== null && clock.now() - progressedAt > 5000)\n )\n return this.terminate(\n run,\n \"host_not_advancing\",\n fault\n ? `The observed host stopped advancing: ${describeHostRuntimeFault(fault)}`\n : \"The observed host stopped advancing.\",\n fault ?? undefined,\n );\n const step = ++run.record.counters.steps;\n const counters = this.seatRecord(run, seat).counters;\n const decisionStarted = performance.now();\n const decisionDeadline =\n decisionStarted +\n Math.min(\n profile.timing.decisionMs,\n Math.max(1, run.deadline - decisionStarted),\n );\n const decision = (async () => {\n if (policy.busy()) {\n counters.blocked++;\n throw new Error(\"policy_busy: Previous decision has not returned.\");\n }\n const receipts = run.receipts.filter(\n (receipt) =>\n receipt.seatId === seat.id &&\n receipt.sequence > seat.policyCursor,\n );\n seat.policyCursor = seat.sequence;\n counters.decisions++;\n return policy.decide(\n {\n observation,\n seatId: seat.id,\n intent: this.seatRecord(run, seat).intent,\n answer: seat.lastAnswer,\n step,\n elapsedMs: this.elapsed(run),\n receipts,\n },\n decisionDeadline - decisionStarted,\n );\n })();\n const pending = this.playDecision(run, seat, {\n observation,\n step,\n started,\n decisionStarted,\n decisionDeadline,\n decision,\n })\n .catch((error) => this.failed(run, error))\n .finally(() => {\n inFlight.delete(seat.id);\n });\n inFlight.set(seat.id, pending);\n // The policy helper has one IPC channel; model answers run outside it.\n await decision.catch(() => undefined);\n }\n if (\n inFlight.size > 0 &&\n (inFlight.size === run.seats.length ||\n (request.kind === \"test\" &&\n run.record.counters.steps >= request.budget.steps))\n )\n await Promise.race(inFlight.values());\n await clock\n .wait(\n Math.max(0, profile.timing.intervalMs - (clock.now() - roundStarted)),\n run.abort.signal,\n )\n .catch((error) => {\n if (!run.abort.signal.aborted) throw error;\n });\n }\n }\n private async playDecision(\n run: Run,\n seat: RunSeat,\n {\n observation,\n step,\n started,\n decisionStarted,\n decisionDeadline,\n decision: pendingDecision,\n }: {\n observation: HostObservation;\n step: number;\n started: number;\n decisionStarted: number;\n decisionDeadline: number;\n decision: Promise<AirJamPolicyDecision>;\n },\n ) {\n const profile = run.players;\n if (!profile) throw new Error(\"Run players are not initialized.\");\n const request = run.record.request;\n const tick = observation.ticks.after;\n const counters = this.seatRecord(run, seat).counters;\n let control: AirJamPlayControl;\n try {\n const decision = await pendingDecision;\n if (run.abort.signal.aborted) return;\n let answer: AnsweredDecision | undefined;\n if (\"ask\" in decision) {\n // A missed answer must not leave the previous choice to act on.\n seat.lastAnswer = null;\n answer = await this.answerFor(\n run,\n seat,\n decision.ask,\n decisionDeadline,\n );\n if (run.abort.signal.aborted) return;\n control = answer.control;\n seat.lastAnswer = {\n choice: answer.choice,\n confidence: answer.confidence,\n };\n } else control = decision.control;\n if (run.abort.signal.aborted) return;\n await this.trace(run, {\n kind: \"policy_decision\",\n seatId: seat.id,\n step,\n durationMs: performance.now() - decisionStarted,\n ...(decision.diagnostics ? { diagnostics: decision.diagnostics } : {}),\n ...(answer\n ? {\n answer: {\n choice: answer.choice,\n confidence: answer.confidence,\n durationMs: answer.durationMs,\n control: answer.control,\n ...(answer.note ? { note: answer.note } : {}),\n },\n }\n : {}),\n });\n this.pruneReceipts(run);\n } catch (error) {\n if (run.abort.signal.aborted) return;\n if (\n !(error instanceof Error) ||\n !/^(policy_(timeout|busy)|decision_failed):/.test(error.message)\n )\n throw error;\n if (error.message.startsWith(\"policy_timeout:\")) counters.timeout++;\n run.record.counters.missed++;\n const reason = error.message.slice(0, 300);\n await this.trace(run, {\n kind: \"decision_missed\",\n seatId: seat.id,\n step,\n reason,\n });\n await this.control(run, seat, observation, { kind: \"release\" }, \"play\");\n if (++seat.misses >= 3)\n return this.terminate(\n run,\n \"policy_unresponsive\",\n `Seat ${seat.id} missed three consecutive decision opportunities. Last: ${reason}`,\n );\n return;\n }\n if (run.abort.signal.aborted) return;\n seat.misses = 0;\n const operation: ControllerLeasedControl[\"operation\"] =\n control.kind === \"release\"\n ? { kind: \"release\" }\n : control.kind === \"input\"\n ? {\n ...control,\n ttlMs: profile.timing.inputTtlMs,\n deadlineMs: this.deadline(observation),\n }\n : { ...control, deadlineMs: this.deadline(observation) };\n if (\n operation.kind === \"action\" &&\n request.kind === \"test\" &&\n !run.record.profile?.actions.includes(operation.actionId)\n )\n throw new Error(\n \"policy_action_forbidden: Decision requested an action outside the profile.\",\n );\n const receipt = await this.control(\n run,\n seat,\n observation,\n operation,\n \"play\",\n );\n if (receipt.status === \"unconfirmed\")\n throw new Error(`control_unconfirmed: ${receipt.reason}`);\n if (receipt.status === \"rejected\") {\n if (receipt.reason === \"stale_identity\")\n return this.terminate(\n run,\n \"runtime_replaced\",\n \"The game runtime was replaced.\",\n );\n if (receipt.reason !== \"stale_decision\")\n throw new Error(`control_rejected: ${receipt.reason}`);\n run.record.counters.missed++;\n await this.control(run, seat, observation, { kind: \"release\" }, \"play\");\n if (++seat.staleDecisions >= 3)\n return this.terminate(\n run,\n \"decision_latency\",\n `Seat ${seat.id} repeatedly arrived too late to apply.`,\n );\n } else seat.staleDecisions = 0;\n await this.trace(run, {\n kind: \"decision\",\n seatId: seat.id,\n step,\n observationId: observation.id,\n tick,\n durationMs: performance.now() - started,\n });\n }\n private failed(run: Run, error: unknown) {\n if (run.abort.signal.aborted) return;\n const message = error instanceof Error ? error.message : String(error);\n const stopped = error instanceof CurrentRoomStopped;\n if (stopped) run.record.stopRequestedAt ??= new Date().toISOString();\n void this.terminate(\n run,\n stopped ? \"stopped\" : failureReason(message),\n message,\n ).catch((failure) => console.error(failure));\n }\n private terminate(\n run: Run,\n reason: EndReason,\n message: string,\n hostFault?: NonNullable<AirJamGameRunRecord[\"end\"]>[\"hostFault\"],\n ) {\n return (run.termination ??= (async () => {\n run.record.abortedAt = new Date().toISOString();\n run.abort.abort();\n clearTimeout(run.timer);\n run.record.state = \"stopping\";\n run.record.end = {\n reason,\n ...(run.record.request.kind === \"test\"\n ? { outcome: \"inconclusive\" as const }\n : {}),\n message,\n ...(hostFault ? { hostFault } : {}),\n };\n const cleanup: NonNullable<AirJamGameRunRecord[\"cleanup\"]> = {\n seats: [],\n errors: [],\n participantsClosed: true,\n };\n const attempt = async <T>(operation: () => Promise<T>) => {\n try {\n return await operation();\n } catch (error) {\n cleanup.errors.push(\n error instanceof Error ? error.message : String(error),\n );\n return undefined;\n }\n };\n await attempt(async () => {\n await run.admission;\n await run.startup;\n });\n await Promise.allSettled([...run.watches.values()]);\n const policy = run.policy;\n if (policy && run.record.request.kind === \"test\")\n await attempt(() => policy.stop());\n await Promise.allSettled([...run.effects]);\n const evaluationInFlight = run.evaluation;\n if (evaluationInFlight) await attempt(() => evaluationInFlight);\n if (run.session) {\n const session = run.session;\n for (const seat of run.seats) {\n const seatCleanup: NonNullable<\n AirJamGameRunRecord[\"cleanup\"]\n >[\"seats\"][number] = { seatId: seat.id };\n cleanup.seats.push(seatCleanup);\n if (seat.expected) {\n const expected = seat.expected;\n seatCleanup.release = await attempt(() =>\n this.control(\n run,\n seat,\n { identity: expected, id: \"cleanup\" },\n { kind: \"release\" },\n \"cleanup\",\n ),\n );\n }\n seat.policyCursor = seat.sequence;\n }\n await this.finishClip(run);\n if (run.record.request.kind === \"test\") {\n const primary = run.seats[0];\n let finalObservation: HostObservation | undefined;\n try {\n if (!primary || !run.players)\n throw new Error(\"Run has no initialized observation seat.\");\n const before = await this.evaluationObservation(run, false);\n const settleUntil = session.clock.now() + 2000;\n let settled: HostObservation;\n do {\n await session.clock.wait(run.players.timing.intervalMs);\n settled = await this.evaluationObservation(run, false);\n } while (\n before.ticks.after !== null &&\n settled.ticks.after === before.ticks.after &&\n session.clock.now() < settleUntil\n );\n if (\n before.ticks.after !== null &&\n settled.ticks.after === before.ticks.after\n ) {\n const fault = settled.host?.after?.fault;\n if (fault) run.record.end.hostFault = fault;\n throw new Error(\n fault\n ? `The host did not advance after input release: ${describeHostRuntimeFault(fault)}`\n : \"The host did not advance after input release.\",\n );\n }\n finalObservation = await this.evaluationObservation(run, true);\n if (!run.room && run.record.expected) {\n const result = await readHostInputLog(\n (request) => {\n if (!session.requestHost)\n throw new Error(\n \"host_unavailable: Studio couldn't reach the game.\",\n );\n return session.requestHost(request, 5000);\n },\n run.record.expected,\n {\n scope: finalObservation.scope,\n controllerId: finalObservation.controllerId,\n },\n );\n run.record.evidence ??= { observation: null, error: null };\n if (result.status === \"not-replayable\")\n run.record.evidence.replay = {\n reason: result.reason,\n message: result.message,\n };\n else {\n if (!result.observation)\n throw new Error(\n \"The recording has no cut-bound observation.\",\n );\n // Keep the screen capture, with state sampled at the log cut.\n finalObservation = {\n ...result.observation,\n visual: finalObservation.visual,\n };\n const inputSource = `${JSON.stringify(result.log)}\\n`;\n const file = await open(\n path.join(run.directory, \"input-log.json\"),\n \"w\",\n 0o600,\n );\n try {\n await file.writeFile(inputSource);\n } finally {\n await file.close();\n }\n run.record.evidence.inputLog = {\n path: `.airjam/artifacts/runs/${run.record.runId}/input-log.json`,\n sha256: createHash(\"sha256\")\n .update(inputSource)\n .digest(\"hex\"),\n ticks: result.log.ticks,\n stepMs: result.log.stepMs,\n entries: result.log.entries.length,\n fromTick: run.fromTick ?? 0,\n full: result.full,\n };\n }\n }\n const source = `${JSON.stringify(finalObservation)}\\n`;\n const file = await open(\n path.join(run.directory, \"final-observation.json\"),\n \"w\",\n 0o600,\n );\n try {\n await file.writeFile(source);\n } finally {\n await file.close();\n }\n run.record.evidence = {\n ...run.record.evidence,\n observation: {\n path: `.airjam/artifacts/runs/${run.record.runId}/final-observation.json`,\n sha256: createHash(\"sha256\").update(source).digest(\"hex\"),\n },\n error: null,\n };\n const saveInputLog = run.room?.saveInputLog;\n if (saveInputLog)\n run.record.evidence.inputLog = {\n path: `.airjam/artifacts/runs/${run.record.runId}/input-log.json`,\n fromTick: run.fromTick ?? 0,\n ...(await saveInputLog(\n path.join(run.directory, \"input-log.json\"),\n )),\n };\n } catch (error) {\n const message =\n error instanceof Error ? error.message : String(error);\n run.record.evidence = {\n ...run.record.evidence,\n observation: null,\n error: message,\n };\n if (run.record.end.reason === \"completed\")\n run.record.end = {\n reason: failureReason(message),\n outcome: \"inconclusive\",\n message,\n ...(run.record.end.hostFault\n ? { hostFault: run.record.end.hostFault }\n : {}),\n };\n }\n if (finalObservation && run.evaluator && run.playEvaluationSent)\n await attempt(() => this.evaluate(run, \"final\", finalObservation));\n const evaluator = run.evaluator;\n if (evaluator) await attempt(() => evaluator.stop());\n }\n // A test in the creator's room hands it back before its players leave,\n // so the room no longer plays on without them.\n if (\n run.record.request.kind === \"test\" &&\n run.record.request.target.kind === \"current\" &&\n run.record.profile &&\n run.seats.length > 0 &&\n run.seats.every((seat) => seat.expected)\n ) {\n const steps = run.record.profile.handBack;\n cleanup.handBack = steps\n ? (await attempt(() =>\n this.runProfileSteps(run, session, steps, \"cleanup\"),\n ))\n ? \"returned\"\n : \"failed\"\n : \"undeclared\";\n }\n for (const seat of run.seats.slice(1)) {\n const extra = seat.extra;\n if (!extra)\n throw new Error(\"Additional run seat has no owned participant.\");\n let disconnected = await attempt(() => extra.close());\n if (!disconnected)\n disconnected = await attempt(() => extra.forceClose());\n if (!disconnected) cleanup.participantsClosed = false;\n const receipt = cleanup.seats.find(\n (candidate) => candidate.seatId === seat.id,\n );\n if (!receipt) throw new Error(\"Run seat has no cleanup receipt.\");\n receipt.disconnection = disconnected;\n await attempt(() =>\n this.trace(run, {\n kind: \"seat_left\",\n seatId: seat.id,\n disconnection: disconnected,\n }),\n );\n }\n let closed = await attempt(() => session.close());\n if (!closed?.closed) {\n cleanup.forced = true;\n closed = await attempt(() => session.forceClose());\n }\n if (closed) {\n run.closed = closed;\n cleanup.close = {\n closed: closed.closed,\n disconnection: closed.disconnection,\n };\n run.record.session = gameRunSessionIdentitySchema.parse(\n closed.session,\n );\n }\n }\n if (policy && run.record.request.kind === \"play\")\n await attempt(() => policy.stop());\n const evaluator = run.evaluator;\n if (!run.session && evaluator) await attempt(() => evaluator.stop());\n const scopes = await Promise.allSettled(\n run.scopes.map((close) => close()),\n );\n cleanup.processesClosed = scopes.every(\n (result) => result.status === \"fulfilled\",\n );\n try {\n assertProcessScopesConfirmed();\n } catch (error) {\n cleanup.processesClosed = false;\n cleanup.errors.push(\n error instanceof Error ? error.message : String(error),\n );\n }\n for (const result of scopes)\n if (result.status === \"rejected\")\n cleanup.errors.push(\n result.reason instanceof Error\n ? result.reason.message\n : String(result.reason),\n );\n const evaluation = run.record.evaluation;\n if (\n evaluation?.play?.status === \"failed\" ||\n evaluation?.final?.status === \"failed\"\n ) {\n run.record.end = {\n reason: \"failed\",\n outcome: \"failed\",\n message:\n (evaluation.final?.status === \"failed\"\n ? evaluation.final\n : evaluation.play\n )?.message ?? \"Scenario failed.\",\n };\n } else if (run.record.end.reason === \"completed\") {\n const released =\n cleanup.seats.length === run.record.seats.length &&\n cleanup.seats.every((seat) => seat.release?.status === \"applied\");\n run.record.end.outcome =\n evaluation?.final?.status === \"passed\" &&\n run.record.evidence?.observation &&\n cleanup.errors.length === 0 &&\n cleanup.close?.closed &&\n released &&\n cleanup.participantsClosed &&\n cleanup.processesClosed\n ? \"passed\"\n : \"inconclusive\";\n if (run.record.end.outcome === \"inconclusive\")\n run.record.end.message =\n cleanup.errors[0] ??\n (!released\n ? \"Cleanup did not confirm every input release.\"\n : \"The final evaluation did not confirm the earlier pass.\");\n }\n if (run.build && run.record.build) {\n try {\n await verifyPinnedGameBuild(run.build);\n run.record.build.integrity = \"verified\";\n } catch (error) {\n run.record.build.integrity = \"changed\";\n run.record.end = {\n reason: \"runtime_replaced\",\n ...(run.record.request.kind === \"test\"\n ? { outcome: \"inconclusive\" as const }\n : {}),\n message: error instanceof Error ? error.message : String(error),\n };\n }\n }\n run.record.cleanup = cleanup;\n run.record.endedAt = new Date().toISOString();\n run.record.state = \"ended\";\n if (run.traceTruncated)\n run.record.end = {\n reason: \"trace_budget\",\n ...(run.record.request.kind === \"test\"\n ? { outcome: \"inconclusive\" as const }\n : {}),\n message:\n \"Trace byte allowance was exhausted; evidence is incomplete.\",\n };\n await attempt(() =>\n this.trace(run, { kind: \"ended\", end: run.record.end, cleanup }),\n );\n await attempt(async () => {\n await run.tracing;\n const file = run.traceFile;\n run.traceFile = null;\n await file?.close();\n });\n await attempt(async () => {\n const bytes = await readGameRunArtifact(\n this.options.projectDir,\n run.record.runId,\n \"trace.ndjson\",\n MAXIMUM_GAME_RUN_TRACE_BYTES,\n );\n if (!bytes) throw new Error(\"Run trace is missing.\");\n run.record.evidence ??= { observation: null, error: null };\n run.record.evidence.trace = {\n path: `.airjam/artifacts/runs/${run.record.runId}/trace.ndjson`,\n sha256: createHash(\"sha256\").update(bytes).digest(\"hex\"),\n bytes: bytes.byteLength,\n truncated: run.traceTruncated,\n };\n });\n if (\n run.record.end.outcome === \"passed\" &&\n (cleanup.errors.length || run.traceTruncated)\n )\n run.record.end = {\n reason: run.traceTruncated ? \"trace_budget\" : \"error\",\n outcome: \"inconclusive\",\n message: cleanup.errors[0] ?? \"Trace byte allowance was exhausted.\",\n };\n await this.persist(run);\n if (run.session && cleanup.close?.closed && cleanup.participantsClosed)\n this.options.sessionClosed(run.session.summary.gameSessionId);\n this.prune();\n })().finally(() => run.finished.abort()));\n }\n}\n","import { randomUUID } from \"node:crypto\";\nimport type { GameRunClock } from \"./game-run-owner.js\";\nimport type { HostRequester } from \"./game-session-runtime.js\";\nimport {\n HEADLESS_ROOM_IPC_MAX_BYTES,\n HEADLESS_ROOM_MAX_ADVANCE_MS,\n headlessRoomRequestSchema,\n headlessRoomResponseSchema,\n type HeadlessRoomRequest,\n type HeadlessRoomResponse,\n} from \"./headless-room-protocol.js\";\nimport { startHelperChannel } from \"./helper-channel.js\";\nimport {\n closeAfterProcessFailure,\n type ProcessScopeObserver,\n} from \"./managed-process-scope.js\";\n\nconst REQUEST_TIMEOUT_MS = 5_000;\n/** A replay plays the whole recorded match before it answers. */\nconst REPLAY_TIMEOUT_MS = 120_000;\n\nexport type HeadlessRoom = {\n gameId: string | null;\n roomId: string;\n controllerJoinUrl: string;\n /** Reaches the room's host directly, as an owned host. */\n requestHost: HostRequester;\n /** Game time: waiting advances the game rather than the wall clock. */\n clock: GameRunClock;\n /**\n * Writes everything that reached the game so far, by step, for replays;\n * null when the game declares no simulation to replay.\n */\n saveInputLog:\n | ((path: string) => Promise<{\n sha256: string;\n ticks: number;\n stepMs: number;\n entries: number;\n full: boolean;\n }>)\n | null;\n stop: () => Promise<void>;\n};\n\n/**\n * Opens a game's room headless in its own process: no page, no drawing, and\n * a clock that moves only when the run waits on it.\n */\nexport async function startHeadlessRoom({\n rootDir,\n toolingRootDir,\n configPath,\n seed,\n settings,\n logPath,\n onScope,\n startupSignal,\n}: {\n rootDir: string;\n toolingRootDir?: string;\n configPath: string;\n seed: number;\n settings?: Record<string, string | number | boolean>;\n logPath: string;\n onScope?: ProcessScopeObserver;\n startupSignal?: AbortSignal;\n}): Promise<HeadlessRoom> {\n const channel = await startHelperChannel({\n name: \"room\",\n helper: \"run-headless-room.ts\",\n rootDir,\n toolingRootDir,\n onScope,\n startupSignal,\n logPath,\n maxBytes: HEADLESS_ROOM_IPC_MAX_BYTES,\n requestSchema: headlessRoomRequestSchema,\n responseSchema: headlessRoomResponseSchema,\n });\n // One request at a time reaches the room, in the order the run sent them.\n let queue: Promise<unknown> = Promise.resolve();\n const request = <TKind extends HeadlessRoomResponse[\"kind\"]>(\n input: HeadlessRoomRequest,\n expected: TKind,\n timeoutMs = REQUEST_TIMEOUT_MS,\n ) => {\n const result = queue.then(async () => {\n const response = await channel.request(input, timeoutMs);\n if (response.kind === \"error\") throw new Error(response.message);\n if (response.kind !== expected)\n throw new Error(`room_protocol: Expected ${expected}.`);\n return response as Extract<HeadlessRoomResponse, { kind: TKind }>;\n });\n queue = result.catch(() => undefined);\n return result;\n };\n try {\n const opened = await request(\n { kind: \"initialize\", id: randomUUID(), configPath, seed, settings },\n \"initialized\",\n 10_000,\n );\n let nowMs = opened.nowMs;\n return {\n gameId: opened.gameId,\n roomId: opened.roomId,\n controllerJoinUrl: opened.controllerJoinUrl,\n requestHost: async (hostRequest, timeoutMs, signal) => {\n signal?.throwIfAborted();\n const answered = await request(\n { kind: \"agent\", id: randomUUID(), request: hostRequest },\n \"agent\",\n timeoutMs,\n );\n return answered.response;\n },\n clock: {\n now: () => nowMs,\n wait: async (ms, signal) => {\n let remaining = ms;\n while (remaining > 0) {\n signal?.throwIfAborted();\n const step = Math.min(remaining, HEADLESS_ROOM_MAX_ADVANCE_MS);\n nowMs = (\n await request(\n { kind: \"advance\", id: randomUUID(), ms: step },\n \"advanced\",\n )\n ).nowMs;\n remaining -= step;\n }\n },\n },\n saveInputLog: opened.recordsInputLog\n ? async (logPath) => {\n const { sha256, ticks, stepMs, entries, full } = await request(\n { kind: \"saveInputLog\", id: randomUUID(), path: logPath },\n \"savedInputLog\",\n );\n return { sha256, ticks, stepMs, entries, full };\n }\n : null,\n stop: channel.stop,\n };\n } catch (error) {\n return closeAfterProcessFailure(channel.stop, error);\n } finally {\n channel.started();\n }\n}\n\n/**\n * Plays a recorded input log on a fresh copy of the game in its own process,\n * with no server or page, and keeps the replayed host for questions such as\n * a final observation.\n */\nexport async function replayInputLog({\n rootDir,\n toolingRootDir,\n configPath,\n inputLogPath,\n logPath,\n}: {\n rootDir: string;\n toolingRootDir?: string;\n configPath: string;\n inputLogPath: string;\n logPath: string;\n}): Promise<{\n gameId: string | null;\n roomId: string;\n ticks: number;\n requestHost: HostRequester;\n stop: () => Promise<void>;\n}> {\n const channel = await startHelperChannel({\n name: \"replay\",\n helper: \"run-headless-room.ts\",\n rootDir,\n toolingRootDir,\n logPath,\n maxBytes: HEADLESS_ROOM_IPC_MAX_BYTES,\n requestSchema: headlessRoomRequestSchema,\n responseSchema: headlessRoomResponseSchema,\n });\n try {\n const replayed = await channel.request(\n {\n kind: \"replay\",\n id: randomUUID(),\n configPath,\n logPath: inputLogPath,\n },\n REPLAY_TIMEOUT_MS,\n );\n if (replayed.kind === \"error\") throw new Error(replayed.message);\n if (replayed.kind !== \"replayed\")\n throw new Error(\"room_protocol: Expected replayed.\");\n return {\n gameId: replayed.gameId,\n roomId: replayed.roomId,\n ticks: replayed.ticks,\n requestHost: async (hostRequest, timeoutMs, signal) => {\n signal?.throwIfAborted();\n const answered = await channel.request(\n { kind: \"agent\", id: randomUUID(), request: hostRequest },\n timeoutMs,\n );\n if (answered.kind === \"error\") throw new Error(answered.message);\n if (answered.kind !== \"agent\")\n throw new Error(\"room_protocol: Expected agent.\");\n return answered.response;\n },\n stop: channel.stop,\n };\n } catch (error) {\n return closeAfterProcessFailure(channel.stop, error);\n } finally {\n channel.started();\n }\n}\n","import { closeSync, openSync, writeSync } from \"node:fs\";\nimport type { z } from \"zod\";\nimport {\n resolveDevtoolsHelperArgs,\n resolveDevtoolsHelperScript,\n resolveProjectDevtoolsHelperScript,\n} from \"./helper-scripts.js\";\nimport {\n closeAfterProcessFailure,\n closeScopedProcess,\n spawnScopedProcess,\n type ProcessScopeObserver,\n} from \"./managed-process-scope.js\";\nimport { nodeProcessEnvironment } from \"./node-process-environment.js\";\nimport { processScopeAdmissionSchema } from \"./process-scope-protocol.js\";\n\nconst environmentKeys = [\n \"PATH\",\n \"HOME\",\n \"TMPDIR\",\n \"TEMP\",\n \"TMP\",\n \"NODE_EXTRA_CA_CERTS\",\n \"HTTP_PROXY\",\n \"HTTPS_PROXY\",\n \"ALL_PROXY\",\n \"NO_PROXY\",\n \"http_proxy\",\n \"https_proxy\",\n \"all_proxy\",\n \"no_proxy\",\n];\n\nconst LOG_BYTES = 1_000_000;\nconst STARTUP_MS = 10_000;\n\n/**\n * One helper process that runs game code apart from the owner, answering one\n * request at a time over IPC. Its errors start with `<name>_`, such as\n * `policy_timeout`, so callers can tell them apart.\n */\nexport async function startHelperChannel<\n TRequest extends { id: string },\n TResponse extends { kind: string; id?: string },\n>({\n name,\n helper,\n rootDir,\n toolingRootDir,\n onScope,\n startupSignal,\n logPath,\n maxBytes,\n requestSchema,\n responseSchema,\n}: {\n name: string;\n helper: string;\n rootDir: string;\n toolingRootDir?: string;\n onScope?: ProcessScopeObserver;\n startupSignal?: AbortSignal;\n logPath: string;\n maxBytes: number;\n requestSchema: z.ZodType<TRequest>;\n responseSchema: z.ZodType<TResponse>;\n}): Promise<{\n request: (input: TRequest, timeoutMs: number) => Promise<TResponse>;\n busy: () => boolean;\n /** Ends the startup signal's hold once the caller has initialized the helper. */\n started: () => void;\n stop: () => Promise<void>;\n}> {\n startupSignal?.throwIfAborted();\n const script = toolingRootDir\n ? resolveProjectDevtoolsHelperScript(toolingRootDir, helper)\n : resolveDevtoolsHelperScript(helper);\n const logDescriptor = openSync(logPath, \"w\", 0o600);\n const child = await spawnScopedProcess(resolveDevtoolsHelperArgs(script), {\n cwd: rootDir,\n onScope,\n startupSignal,\n env: nodeProcessEnvironment(environmentKeys),\n }).catch((error) => {\n closeSync(logDescriptor);\n if (startupSignal?.aborted)\n throw new Error(`${name}_stopped`, { cause: error });\n throw error;\n });\n let failure: Error | undefined;\n let ready = false;\n let pending:\n | {\n id: string;\n resolve: (value: TResponse) => void;\n reject: (error: Error) => void;\n timer: ReturnType<typeof setTimeout>;\n expired: boolean;\n }\n | undefined;\n let stopping: Promise<void> | undefined;\n let resolveReady: () => void;\n let rejectReady: (error: Error) => void;\n const boot = new Promise<void>((resolve, reject) => {\n resolveReady = resolve;\n rejectReady = reject;\n });\n const fail = (error: Error) => {\n failure ??= error;\n rejectReady(error);\n if (pending) {\n clearTimeout(pending.timer);\n pending.reject(error);\n pending = undefined;\n }\n };\n child.on(\"error\", fail);\n child.once(\"exit\", () => {\n fail(new Error(`${name}_exited: The ${name} process is unavailable.`));\n });\n let logBytes = 0;\n const log = (chunk: Buffer) => {\n const remaining = LOG_BYTES - logBytes;\n if (remaining > 0) {\n const bounded = chunk.subarray(0, remaining);\n try {\n let offset = 0;\n while (offset < bounded.length)\n offset += writeSync(logDescriptor, bounded.subarray(offset));\n } catch (error) {\n fail(error instanceof Error ? error : new Error(String(error)));\n child.kill(\"SIGKILL\");\n }\n }\n logBytes += chunk.length;\n if (logBytes > LOG_BYTES) {\n fail(\n new Error(\n `${name}_log_limit: The ${name} process exceeded its 1 MB diagnostic log budget.`,\n ),\n );\n child.kill(\"SIGKILL\");\n }\n };\n child.stdout?.on(\"data\", log);\n child.stderr?.on(\"data\", log);\n child.on(\"message\", (message: unknown) => {\n if (message === 0) return;\n if (processScopeAdmissionSchema.safeParse(message).success) return;\n try {\n if (Buffer.byteLength(JSON.stringify(message)) > maxBytes)\n throw new Error(`${name}_protocol: Oversized response.`);\n const result = responseSchema.parse(message);\n if (result.kind === \"ready\") {\n if (ready) throw new Error(`${name}_protocol: Duplicate startup.`);\n ready = true;\n resolveReady();\n return;\n }\n if (!pending || result.id !== pending.id)\n throw new Error(`${name}_protocol: Unexpected response ID.`);\n const request = pending;\n pending = undefined;\n clearTimeout(request.timer);\n if (!request.expired) request.resolve(result);\n } catch (error) {\n fail(error instanceof Error ? error : new Error(String(error)));\n child.kill(\"SIGKILL\");\n }\n });\n const request = (input: TRequest, timeoutMs: number) => {\n if (failure) return Promise.reject(failure);\n if (pending)\n return Promise.reject(\n new Error(`${name}_busy: The previous request has not returned.`),\n );\n const parsed = requestSchema.parse(input);\n if (Buffer.byteLength(JSON.stringify(parsed)) > maxBytes)\n return Promise.reject(\n new Error(`${name}_protocol: Request exceeds its byte budget.`),\n );\n return new Promise<TResponse>((resolve, reject) => {\n const timer = setTimeout(() => {\n if (pending?.id !== parsed.id) return;\n pending.expired = true;\n reject(new Error(`${name}_timeout: Request exceeded its deadline.`));\n }, timeoutMs);\n pending = { id: parsed.id, resolve, reject, timer, expired: false };\n child.send(parsed, (error) => {\n if (error) fail(error);\n });\n });\n };\n const stop = () =>\n (stopping ??= (async () => {\n startupSignal?.removeEventListener(\"abort\", aborted);\n fail(new Error(`${name}_stopped`));\n try {\n await closeScopedProcess(child);\n } finally {\n child.stdout?.destroy();\n child.stderr?.destroy();\n closeSync(logDescriptor);\n }\n })());\n const aborted = () => {\n void stop().catch(() => undefined);\n };\n startupSignal?.addEventListener(\"abort\", aborted, { once: true });\n const bootTimeout = setTimeout(\n () => fail(new Error(`${name}_startup_timeout`)),\n STARTUP_MS,\n );\n try {\n if (startupSignal?.aborted) aborted();\n await boot;\n } catch (error) {\n startupSignal?.removeEventListener(\"abort\", aborted);\n return closeAfterProcessFailure(stop, error);\n } finally {\n clearTimeout(bootTimeout);\n }\n return {\n request,\n busy: () => pending !== undefined,\n started: () => startupSignal?.removeEventListener(\"abort\", aborted),\n stop,\n };\n}\n","import { createHash } from \"node:crypto\";\nimport { constants, createReadStream } from \"node:fs\";\nimport { access, lstat, readFile, readdir, realpath } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport type { z } from \"zod\";\nimport {\n policyArtifactManifestSchema,\n policyArtifactReceiptSchema,\n} from \"./policy-artifact-contract.js\";\n\nasync function assertProtectedEntry(target: string, directory: boolean) {\n const information = await lstat(target);\n if (directory ? !information.isDirectory() : !information.isFile())\n throw new Error(\n \"policy_artifact_invalid: Expected a regular artifact entry, without symlinks.\",\n );\n if (\n !process.getuid ||\n process.getuid() === 0 ||\n information.uid === process.getuid()\n )\n throw new Error(\n \"policy_artifact_writable: Artifacts require an independent filesystem owner and a non-root policy.\",\n );\n try {\n await access(target, constants.W_OK);\n } catch (error) {\n if (error instanceof Error && \"code\" in error && error.code === \"EACCES\")\n return;\n throw error;\n }\n throw new Error(\n \"policy_artifact_writable: Policy artifacts must be read-only to the workload.\",\n );\n}\n\n/** This validates public, independently provisioned files; it does not download or run models. */\nexport async function verifyPolicyArtifacts(options: {\n projectDir: string;\n manifestPath: string;\n artifactRootDir?: string;\n signal?: AbortSignal;\n}): Promise<{\n directory: string;\n receipt: z.infer<typeof policyArtifactReceiptSchema>;\n}> {\n const started = performance.now();\n options.signal?.throwIfAborted();\n if (!options.artifactRootDir || !path.isAbsolute(options.artifactRootDir))\n throw new Error(\n \"policy_artifacts_missing: Configure an absolute AIRJAM_TEST_ARTIFACTS_DIR for this policy.\",\n );\n const project = await realpath(options.projectDir);\n const manifestPath = await realpath(options.manifestPath);\n const relative = path.relative(project, manifestPath);\n if (\n !relative ||\n relative === \"..\" ||\n relative.startsWith(`..${path.sep}`) ||\n path.isAbsolute(relative)\n )\n throw new Error(\n \"policy_artifact_invalid: The manifest must be pinned inside the project source.\",\n );\n if ((await lstat(manifestPath)).size > 64 * 1024)\n throw new Error(\"policy_artifact_invalid: Manifest exceeds 64 KiB.\");\n const content = await readFile(manifestPath, { signal: options.signal });\n const manifest = policyArtifactManifestSchema.parse(\n JSON.parse(content.toString(\"utf8\")),\n );\n const manifestSha256 = createHash(\"sha256\").update(content).digest(\"hex\");\n const directory = path.join(options.artifactRootDir, manifestSha256);\n const directories = new Set<string>();\n let ancestor = directory;\n while (true) {\n directories.add(ancestor);\n const parent = path.dirname(ancestor);\n if (parent === ancestor) break;\n ancestor = parent;\n }\n for (const file of manifest.files) {\n let parent = path.dirname(path.join(directory, file.path));\n while (parent !== directory) {\n directories.add(parent);\n parent = path.dirname(parent);\n }\n }\n for (const parent of directories) await assertProtectedEntry(parent, true);\n const expected = new Set(manifest.files.map((file) => file.path));\n const pending = [\"\"];\n for (const relative of pending) {\n options.signal?.throwIfAborted();\n for (const entry of await readdir(path.join(directory, relative), {\n withFileTypes: true,\n })) {\n const name = relative ? `${relative}/${entry.name}` : entry.name;\n if (\n entry.isDirectory() &&\n [...expected].some((file) => file.startsWith(name + \"/\"))\n )\n pending.push(name);\n else if (!entry.isFile() || !expected.has(name))\n throw new Error(\n `policy_artifact_invalid: Unlisted artifact entry: ${name}.`,\n );\n }\n }\n for (const file of manifest.files) {\n options.signal?.throwIfAborted();\n const target = path.join(directory, file.path);\n await assertProtectedEntry(target, false);\n if ((await lstat(target)).size !== file.bytes)\n throw new Error(\n `policy_artifact_invalid: Size differs for ${file.path}.`,\n );\n const hash = createHash(\"sha256\");\n for await (const chunk of createReadStream(target, {\n signal: options.signal,\n }))\n hash.update(chunk);\n if (hash.digest(\"hex\") !== file.sha256)\n throw new Error(\n `policy_artifact_invalid: Digest differs for ${file.path}.`,\n );\n }\n return {\n directory,\n receipt: policyArtifactReceiptSchema.parse({\n manifestSha256,\n manifest,\n verifyMs: performance.now() - started,\n }),\n };\n}\n","import { randomUUID } from \"node:crypto\";\nimport type { z } from \"zod\";\nimport { startHelperChannel } from \"./helper-channel.js\";\nimport {\n closeAfterProcessFailure,\n type ProcessScopeObserver,\n} from \"./managed-process-scope.js\";\nimport type { policyArtifactReceiptSchema } from \"./policy-artifact-contract.js\";\nimport {\n TEST_PROFILE_IPC_MAX_BYTES,\n testProfileRequestSchema,\n testProfileResponseSchema,\n type TestProfileRequest,\n} from \"./test-profile-protocol.js\";\nimport type {\n AirJamPolicyDecision,\n AirJamPolicyStep,\n AirJamScenarioSample,\n AirJamScenarioVerdict,\n AirJamTestProfileDescription,\n policyPreparationSchema,\n} from \"./testing.js\";\n\nexport async function startTestProfileProcess({\n rootDir,\n configPath,\n profileId,\n runKind = \"test\",\n policyId,\n seed,\n logPath,\n role,\n toolingRootDir,\n onScope,\n startupSignal,\n initializationDeadline,\n artifacts,\n}: {\n rootDir: string;\n toolingRootDir?: string;\n onScope?: ProcessScopeObserver;\n startupSignal?: AbortSignal;\n initializationDeadline?: number;\n artifacts?: {\n directory: string;\n receipt: z.infer<typeof policyArtifactReceiptSchema>;\n };\n configPath: string;\n runKind?: \"test\" | \"play\";\n profileId?: string;\n policyId?: string;\n seed: number;\n logPath: string;\n role: \"discover\" | \"policy\" | \"evaluator\";\n}): Promise<{\n profiles: AirJamTestProfileDescription[];\n preparation: z.infer<typeof policyPreparationSchema>;\n decide: (\n step: AirJamPolicyStep,\n timeoutMs: number,\n ) => Promise<AirJamPolicyDecision>;\n evaluate: (\n sample: AirJamScenarioSample,\n timeoutMs: number,\n ) => Promise<AirJamScenarioVerdict>;\n busy: () => boolean;\n stop: () => Promise<void>;\n}> {\n startupSignal?.throwIfAborted();\n if (role !== \"policy\" && initializationDeadline !== undefined)\n throw new Error(\"Only a policy can use the run's initialization deadline.\");\n if (role !== \"policy\" && artifacts !== undefined)\n throw new Error(\"Only a policy can receive model artifacts.\");\n const channel = await startHelperChannel({\n name: \"policy\",\n helper: \"run-test-profile.ts\",\n rootDir,\n toolingRootDir,\n onScope,\n startupSignal,\n logPath,\n maxBytes: TEST_PROFILE_IPC_MAX_BYTES,\n requestSchema: testProfileRequestSchema,\n responseSchema: testProfileResponseSchema,\n });\n const request = (input: TestProfileRequest, timeoutMs: number) =>\n channel.request(input, timeoutMs);\n try {\n const initialized = await request(\n {\n kind: \"initialize\",\n id: randomUUID(),\n rootDir,\n configPath,\n profileId,\n runKind,\n policyId,\n seed,\n role,\n ...(artifacts ? { artifacts } : {}),\n },\n initializationDeadline === undefined\n ? 10_000\n : Math.max(1, initializationDeadline - performance.now()),\n );\n if (initialized.kind !== \"initialized\")\n throw new Error(\n initialized.kind === \"error\"\n ? initialized.message\n : \"Invalid policy initialization response.\",\n );\n return {\n profiles: initialized.profiles,\n preparation: initialized.preparation,\n busy: channel.busy,\n async decide(step: AirJamPolicyStep, timeoutMs: number) {\n if (role !== \"policy\")\n throw new Error(\"Only a policy process can decide.\");\n const result = await request(\n { kind: \"decide\", id: randomUUID(), step },\n timeoutMs,\n );\n if (result.kind !== \"decision\")\n throw new Error(\n result.kind === \"error\"\n ? result.message\n : \"Invalid policy decision response.\",\n );\n return result.decision;\n },\n async evaluate(sample: AirJamScenarioSample, timeoutMs: number) {\n if (role !== \"evaluator\")\n throw new Error(\"Only an evaluator process can judge.\");\n const result = await request(\n { kind: \"evaluate\", id: randomUUID(), sample },\n timeoutMs,\n );\n if (result.kind !== \"evaluation\")\n throw new Error(\n result.kind === \"error\"\n ? result.message\n : \"Invalid scenario evaluation response.\",\n );\n return result.verdict;\n },\n stop: channel.stop,\n };\n } catch (error) {\n return closeAfterProcessFailure(channel.stop, error);\n } finally {\n channel.started();\n }\n}\n","import { seatViewSchema } from \"@air-jam/sdk/room-protocol\";\nimport type {\n HostAgentRequest,\n HostAgentResponse,\n HostObservationRequest,\n} from \"@air-jam/sdk/runtime-control\";\nimport { randomUUID } from \"node:crypto\";\nimport path from \"node:path\";\nimport type { z } from \"zod\";\nimport {\n captureControllerSessionVisuals,\n connectController,\n controlControllerParticipant,\n disconnectController,\n forceDisconnectController,\n invokeControllerAction,\n ownsControllerSessionHost,\n readRuntimeSnapshot,\n requestControllerHostAgent,\n resolveControllerSessionGameRuntime,\n sendControllerInput,\n watchControllerSessionVisuals,\n} from \"./controller.js\";\nimport { startDev, stopDev } from \"./dev.js\";\nimport {\n classifyGameActionOutcome,\n computeGameSnapshotObservation,\n} from \"./game-action-observation.js\";\nimport type { PinnedGameBuild } from \"./game-build-protocol.js\";\nimport {\n wallClock,\n type GameRunParticipant,\n type GameRunSession,\n} from \"./game-run-owner.js\";\nimport type { CurrentRoomSeatClaim } from \"./game-run-protocol.js\";\nimport { GameSessionOperations } from \"./game-session-operations.js\";\nimport { gameSessionOperationSchemas } from \"./game-session-protocol.js\";\nimport type { HeadlessRoom } from \"./headless-room.js\";\nimport type { ProcessScopeObserver } from \"./managed-process-scope.js\";\nimport type {\n AirJamGameAgentActionDescriptor,\n AirJamGameInspection,\n AirJamGameSessionActionDescriptor,\n AirJamGameSessionInspection,\n AirJamGameSessionSummary,\n AirJamGameSessionVisualCaptureResult,\n CaptureGameSessionVisualsOptions,\n CloseGameSessionOptions,\n CloseGameSessionResult,\n InvokeGameSessionActionOptions,\n InvokeGameSessionActionResult,\n JsonObject,\n OpenGameSessionOptions,\n ReadGameSessionOptions,\n SendGameSessionInputOptions,\n SendGameSessionInputResult,\n} from \"./types.js\";\n\nexport type {\n AirJamGameSessionActionDescriptor,\n AirJamGameSessionInspection,\n AirJamGameSessionSummary,\n AirJamGameSessionVisualCaptureResult,\n CaptureGameSessionVisualsOptions,\n CloseGameSessionOptions,\n CloseGameSessionResult,\n InvokeGameSessionActionOptions,\n InvokeGameSessionActionResult,\n OpenGameSessionOptions,\n ReadGameSessionOptions,\n SendGameSessionInputOptions,\n SendGameSessionInputResult,\n} from \"./types.js\";\n\n/** Sends one semantic request to the game's host realm. */\n/** Claims a seat a run's player holds in a room it was granted. */\nexport type SeatClaimer = (\n claim: CurrentRoomSeatClaim,\n timeoutMs: number,\n) => Promise<void>;\n\n/** The seat a connected controller holds, named by its room's instance. */\nconst claimOf = (controller: {\n controllerId: string;\n welcome: JsonObject | null;\n}): CurrentRoomSeatClaim => {\n const instance = controller.welcome?.instance;\n if (typeof instance !== \"string\")\n throw new Error(\"current_room_scope: The room welcomed no seat to claim.\");\n return { instance, seat: controller.controllerId };\n};\n\nexport type HostRequester = (\n request: HostAgentRequest,\n timeoutMs: number,\n signal?: AbortSignal,\n) => Promise<HostAgentResponse>;\n\ntype InternalGameSession = {\n summary: AirJamGameSessionSummary;\n operations: GameSessionOperations;\n devProcessId: string | null;\n disconnection?: Awaited<ReturnType<typeof disconnectController>>;\n requestHost: HostRequester;\n};\n\nexport function createGameSessionRuntime(ownerInstanceId = randomUUID()) {\n const DEFAULT_TIMEOUT_MS = 5_000;\n const DEFAULT_SESSION_OPEN_TIMEOUT_MS = 30_000;\n const gameSessions = new Map<string, InternalGameSession>();\n const devProcessLeases = new Map<\n string,\n { cwd: string; referenceCount: number; stopOnZero: boolean }\n >();\n\n const acquireDevProcessLease = async (\n options: OpenGameSessionOptions,\n ): Promise<string | null> => {\n // Explicit targets belong to an already running host. Attaching must never\n // start, replace, or later stop that host's development processes.\n if (options.controllerJoinUrl || options.roomId?.trim()) {\n return null;\n }\n const started = await startDev({\n cwd: options.cwd,\n gameId: options.gameId,\n mode: options.mode,\n secure: options.secure,\n });\n const processId = started.process.id;\n const existing = devProcessLeases.get(processId);\n devProcessLeases.set(processId, {\n cwd: started.process.cwd,\n referenceCount: (existing?.referenceCount ?? 0) + 1,\n stopOnZero: existing?.stopOnZero ?? !started.reusedExistingProcess,\n });\n return processId;\n };\n\n const releaseDevProcessLease = async (processId: string): Promise<void> => {\n const lease = devProcessLeases.get(processId);\n if (!lease) {\n return;\n }\n if (lease.referenceCount > 1) {\n devProcessLeases.set(processId, {\n ...lease,\n referenceCount: lease.referenceCount - 1,\n });\n return;\n }\n\n if (lease.stopOnZero) {\n await stopDev({ cwd: lease.cwd, processId });\n }\n devProcessLeases.delete(processId);\n };\n\n const toSessionActionId = (\n lane: \"player\" | \"host\",\n actionId: string,\n ): string => `${lane}:${actionId}`;\n\n const describeSessionActions = (\n actions: AirJamGameAgentActionDescriptor[],\n ownsHost: boolean,\n ): AirJamGameSessionActionDescriptor[] =>\n actions.map((action) => ({\n actionId: toSessionActionId(\n action.target.kind === \"host\" ? \"host\" : \"player\",\n action.actionId,\n ),\n lane: action.target.kind === \"host\" ? \"host\" : \"player\",\n source: \"semantic-game\",\n description: action.description,\n availability:\n action.target.kind === \"host\" && !ownsHost\n ? \"host_runtime_not_owned: Host actions require an owned host runtime.\"\n : action.availability,\n payload: {\n kind: action.payload.kind,\n description: action.payload.description,\n ...(action.payload.allowedValues\n ? { allowedValues: [...action.payload.allowedValues] }\n : {}),\n },\n resultDescription: action.resultDescription,\n }));\n\n const getRequiredGameSession = (\n gameSessionId: string,\n ): InternalGameSession => {\n const session = gameSessions.get(gameSessionId);\n if (!session) {\n throw new Error(\n `Unknown Air Jam game session \"${gameSessionId}\". Open a game session first.`,\n );\n }\n return session;\n };\n\n const updateSummary = (\n session: InternalGameSession,\n overrides: Partial<AirJamGameSessionSummary>,\n ): void => {\n session.summary = { ...session.summary, ...overrides };\n };\n\n const openGameSession = async (\n options: OpenGameSessionOptions = {},\n /**\n * A host realm this session reaches directly rather than through its\n * controller. A delegated host's seats are claimed before it is asked\n * anything about them.\n */\n host?: {\n access: \"owned-host\" | \"delegated-host\";\n request: HostRequester;\n claimSeat?: SeatClaimer;\n },\n build?: PinnedGameBuild,\n onScope?: ProcessScopeObserver,\n settings?: Record<string, number | boolean | string>,\n game?: AirJamGameInspection,\n ): Promise<AirJamGameSessionSummary> => {\n const devProcessId = build ? null : await acquireDevProcessLease(options);\n const timeoutMs = options.timeoutMs ?? DEFAULT_SESSION_OPEN_TIMEOUT_MS;\n let controllerSession: Awaited<ReturnType<typeof connectController>>;\n try {\n controllerSession = await connectController(\n { ...options, timeoutMs },\n { build, onScope, settings },\n );\n } catch (error) {\n if (devProcessId) {\n await releaseDevProcessLease(devProcessId).catch(() => undefined);\n }\n throw error;\n }\n const operations = new GameSessionOperations();\n try {\n if (host?.claimSeat)\n await host.claimSeat(claimOf(controllerSession), timeoutMs);\n const runtime = await resolveControllerSessionGameRuntime({\n controllerSessionId: controllerSession.controllerSessionId,\n timeoutMs,\n game,\n });\n const gameId =\n runtime.gameId ?? controllerSession.gameId ?? options.gameId ?? null;\n const ownsHost =\n !!host ||\n ownsControllerSessionHost(controllerSession.controllerSessionId);\n const requestHost: HostRequester =\n host?.request ??\n ((request, timeoutMs, signal) =>\n requestControllerHostAgent(\n controllerSession.controllerSessionId,\n request,\n timeoutMs,\n signal,\n ));\n const live = ownsHost\n ? await operations.run(timeoutMs, (signal) =>\n requestHost(\n {\n operation: \"read\",\n roomId: controllerSession.roomId,\n controllerId: controllerSession.controllerId,\n },\n timeoutMs,\n signal,\n ),\n )\n : null;\n const contract = live?.operation === \"read\" ? live.snapshot : null;\n const gameActions = contract?.actions ?? [];\n const summary: AirJamGameSessionSummary = {\n semanticAccess:\n host?.access ?? (ownsHost ? \"owned-host\" : \"participant-only\"),\n ownerInstanceId,\n gameSessionId: randomUUID(),\n cwd: options.cwd ?? process.cwd(),\n gameId,\n controllerSessionId: controllerSession.controllerSessionId,\n projectMode: controllerSession.projectMode,\n mode: controllerSession.mode,\n topologyMode: controllerSession.topologyMode,\n secure: controllerSession.secure,\n process: controllerSession.process,\n roomId: controllerSession.roomId,\n controllerId: controllerSession.controllerId,\n controllerJoinUrl: controllerSession.controllerJoinUrl,\n socketOrigin: controllerSession.socketOrigin,\n connected: controllerSession.connected,\n connectedAt: controllerSession.connectedAt,\n disconnectedAt: controllerSession.disconnectedAt,\n disconnectReason: controllerSession.disconnectReason,\n hasAgentContract: Boolean(contract),\n actions: describeSessionActions(gameActions, ownsHost),\n };\n\n gameSessions.set(summary.gameSessionId, {\n summary,\n operations,\n requestHost,\n devProcessId,\n });\n return summary;\n } catch (error) {\n operations.close();\n await disconnectController({\n controllerSessionId: controllerSession.controllerSessionId,\n }).catch(() => undefined);\n if (devProcessId) {\n await releaseDevProcessLease(devProcessId).catch(() => undefined);\n }\n throw error;\n }\n };\n\n async function readLiveSnapshot(\n session: InternalGameSession,\n timeoutMs: number,\n signal?: AbortSignal,\n ): Promise<import(\"./types.js\").AirJamGameSnapshotInspection | null> {\n const response = await session.requestHost(\n {\n operation: \"read\",\n roomId: session.summary.roomId,\n controllerId: session.summary.controllerId,\n },\n timeoutMs,\n signal,\n );\n if (response.operation !== \"read\")\n throw new Error(\"Invalid host read response.\");\n const value = response.snapshot;\n updateSummary(session, {\n hasAgentContract: !!value,\n actions: describeSessionActions(value?.actions ?? [], true),\n });\n if (!value) return null;\n if (!session.summary.gameId)\n throw new Error(\"Owned game session has no game identity.\");\n return {\n ...value,\n controllerSessionId: session.summary.controllerSessionId,\n gameId: session.summary.gameId,\n runtimeStoreDomains: value.rawStores.map((store) => store.storeDomain),\n };\n }\n\n const readGameSession = async ({\n gameSessionId,\n timeoutMs = DEFAULT_TIMEOUT_MS,\n }: ReadGameSessionOptions): Promise<AirJamGameSessionInspection> => {\n const session = getRequiredGameSession(gameSessionId);\n return session.operations.run(timeoutMs, async (signal) => {\n const gameSnapshot = await readLiveSnapshot(session, timeoutMs, signal);\n const runtimeSnapshot = await readRuntimeSnapshot({\n controllerSessionId: session.summary.controllerSessionId,\n requestSync: false,\n });\n updateSummary(session, {\n connected: runtimeSnapshot.connected,\n disconnectedAt: runtimeSnapshot.disconnectedAt,\n disconnectReason: runtimeSnapshot.disconnectReason,\n process: runtimeSnapshot.process,\n });\n return { ...session.summary, runtimeSnapshot, gameSnapshot };\n });\n };\n\n const observeGameSession = async ({\n gameSessionId,\n timeoutMs = DEFAULT_TIMEOUT_MS,\n scope = \"diagnostic\",\n includeImage = true,\n expected,\n }: ReadGameSessionOptions &\n Partial<\n Pick<HostObservationRequest, \"scope\" | \"includeImage\" | \"expected\">\n >) => {\n const session = getRequiredGameSession(gameSessionId);\n if (session.summary.semanticAccess === \"participant-only\")\n throw new Error(\n \"contract_runtime_not_owned: Observation requires an owned host or an explicit observation delegation.\",\n );\n return session.operations.run(timeoutMs, async (signal) => {\n const result = await session.requestHost(\n {\n operation: \"observe\",\n roomId: session.summary.roomId,\n controllerId: session.summary.controllerId,\n scope,\n includeImage,\n expected,\n },\n timeoutMs,\n signal,\n );\n if (result.operation !== \"observe\")\n throw new Error(\n \"invalid_runtime_response: Expected a host observation.\",\n );\n return result.observation;\n });\n };\n\n const gameSettings = async (\n options:\n | z.infer<(typeof gameSessionOperationSchemas)[\"settings-read\"]>\n | z.infer<(typeof gameSessionOperationSchemas)[\"settings-update\"]>,\n ) => {\n const session = getRequiredGameSession(options.gameSessionId);\n if (session.summary.semanticAccess === \"participant-only\")\n throw new Error(\n \"contract_runtime_not_owned: Settings require an owned host.\",\n );\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n return session.operations.run(timeoutMs, async (signal) => {\n const snapshot = await readLiveSnapshot(session, timeoutMs, signal);\n if (!snapshot)\n throw new Error(\n \"contract_runtime_unavailable: Game has no live semantic contract.\",\n );\n const request = {\n roomId: session.summary.roomId,\n runtimeId: snapshot.runtimeId,\n };\n const response = await session.requestHost(\n \"patch\" in options\n ? {\n ...request,\n operation: \"settings-update\",\n patch: options.patch,\n expectedRevision: options.expectedRevision,\n }\n : { ...request, operation: \"settings-read\" },\n timeoutMs,\n signal,\n );\n if (\n response.operation !== \"settings-read\" &&\n response.operation !== \"settings-update\"\n )\n throw new Error(\"invalid_runtime_response: Expected settings.\");\n return { values: response.values, revision: response.revision };\n });\n };\n const readGameSettings = (\n options: z.infer<(typeof gameSessionOperationSchemas)[\"settings-read\"]>,\n ) => gameSettings(options);\n const updateGameSettings = (\n options: z.infer<(typeof gameSessionOperationSchemas)[\"settings-update\"]>,\n ) => gameSettings(options);\n\n const controlGameSessionParticipant = async (\n options: z.infer<typeof gameSessionOperationSchemas.control>,\n ) => {\n const session = getRequiredGameSession(options.gameSessionId);\n return session.operations.run(DEFAULT_TIMEOUT_MS, () =>\n controlControllerParticipant({\n controllerSessionId: session.summary.controllerSessionId,\n expected: options.expected,\n lease: options.lease,\n operation: options.operation,\n }),\n );\n };\n\n const sendGameSessionInput = async ({\n gameSessionId,\n input,\n }: SendGameSessionInputOptions): Promise<SendGameSessionInputResult> => {\n const session = getRequiredGameSession(gameSessionId);\n return session.operations.run(DEFAULT_TIMEOUT_MS, async () => {\n const sent = await sendControllerInput({\n controllerSessionId: session.summary.controllerSessionId,\n input,\n });\n updateSummary(session, {\n connected: sent.connected,\n disconnectedAt: sent.disconnectedAt,\n disconnectReason: sent.disconnectReason,\n process: sent.process,\n });\n return { ...session.summary, input: sent.input, sentAt: sent.sentAt };\n });\n };\n\n const invokeGameSessionAction = async (\n options: InvokeGameSessionActionOptions,\n ): Promise<InvokeGameSessionActionResult> => {\n const session = getRequiredGameSession(options.gameSessionId);\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n return session.operations.run(timeoutMs, async (signal) => {\n const before = await readLiveSnapshot(session, timeoutMs, signal);\n if (!before)\n throw new Error(\n \"contract_runtime_unavailable: Game has no live semantic contract.\",\n );\n const action = before.actions.find(\n (action) =>\n toSessionActionId(\n action.target.kind === \"host\" ? \"host\" : \"player\",\n action.actionId,\n ) === options.actionId,\n );\n if (!action)\n throw new Error(`Unknown game session action \"${options.actionId}\".`);\n const resolved = await session.requestHost(\n {\n operation: action.target.kind === \"host\" ? \"invoke-host\" : \"resolve\",\n roomId: session.summary.roomId,\n controllerId: session.summary.controllerId,\n contractId: before.contractId,\n runtimeId: before.runtimeId,\n actionId: action.actionId,\n payload: options.payload,\n },\n timeoutMs,\n signal,\n );\n if (\n resolved.operation !== \"resolve\" &&\n resolved.operation !== \"invoke-host\"\n )\n throw new Error(\"Invalid host resolve response.\");\n const lane = resolved.target.kind === \"host\" ? \"host\" : \"player\";\n const sentAt = new Date().toISOString();\n const sent =\n lane === \"player\"\n ? await invokeControllerAction({\n controllerSessionId: session.summary.controllerSessionId,\n actionName: resolved.target.actionName,\n storeDomain: resolved.target.storeDomain,\n payload: resolved.payload,\n timeoutMs,\n })\n : null;\n const acknowledgement = sent?.acknowledgement ?? resolved.acknowledgement;\n if (!acknowledgement)\n throw new Error(\"Host action returned no acknowledgement.\");\n const after = await readLiveSnapshot(session, timeoutMs, signal);\n if (!after)\n throw new Error(\n \"contract_changed: Game contract unmounted after invocation; action may have executed.\",\n );\n const observation = computeGameSnapshotObservation({\n snapshotBefore: before,\n snapshotAfter: after,\n });\n const classified = classifyGameActionOutcome({\n acknowledgement,\n observedStateChange: observation.observedStateChange,\n });\n const outcome =\n observation.snapshotAfterStatus === \"contract_changed\" ||\n observation.snapshotAfterStatus === \"runtime_replaced\"\n ? observation.snapshotAfterStatus\n : classified.outcome;\n return {\n ...session.summary,\n actionId: options.actionId,\n lane,\n invocation: {\n ...session.summary,\n actionId: action.actionId,\n lane,\n actionName: resolved.target.actionName,\n storeDomain: resolved.target.storeDomain,\n payload: resolved.payload,\n sentAt,\n acknowledgement,\n ...classified,\n outcome,\n ...observation,\n snapshotBefore: before,\n snapshotAfter: after,\n },\n };\n });\n };\n\n const captureGameSessionVisuals = async ({\n gameSessionId,\n timeoutMs,\n }: CaptureGameSessionVisualsOptions): Promise<AirJamGameSessionVisualCaptureResult> => {\n const session = getRequiredGameSession(gameSessionId);\n return session.operations.run(timeoutMs ?? 30000, async () => {\n const captureId = `${new Date()\n .toISOString()\n .replaceAll(/[^0-9A-Za-z]/gu, \"-\")}-${randomUUID().slice(0, 8)}`;\n const relativeDir = path.join(\n \".airjam\",\n \"artifacts\",\n \"session-visuals\",\n gameSessionId,\n captureId,\n );\n const captured = await captureControllerSessionVisuals({\n controllerSessionId: session.summary.controllerSessionId,\n relativeDir,\n timeoutMs,\n });\n return {\n ...session.summary,\n contract: \"air-jam-game-session-visual-capture/v1\",\n capturedAt: captured.capturedAt,\n artifactDir: path.join(session.summary.cwd, relativeDir),\n screenshots: captured.screenshots.map((screenshot) => ({\n ...screenshot,\n filePath: path.join(session.summary.cwd, screenshot.relativePath),\n })),\n };\n });\n };\n\n const disposeGameSession = async (\n { gameSessionId }: CloseGameSessionOptions,\n disconnect: typeof disconnectController,\n ): Promise<CloseGameSessionResult> => {\n const session = getRequiredGameSession(gameSessionId);\n session.operations.close();\n const disconnected = (session.disconnection ??= await disconnect({\n controllerSessionId: session.summary.controllerSessionId,\n }));\n updateSummary(session, {\n connected: disconnected.session.connected,\n disconnectedAt: disconnected.session.disconnectedAt,\n disconnectReason: disconnected.session.disconnectReason,\n process: disconnected.session.process,\n });\n if (session.devProcessId) {\n await releaseDevProcessLease(session.devProcessId);\n session.devProcessId = null;\n }\n gameSessions.delete(gameSessionId);\n return {\n closed: true,\n session: session.summary,\n disconnection: {\n release: disconnected.release,\n leave: disconnected.leave,\n },\n };\n };\n const closeGameSession = (input: CloseGameSessionOptions) =>\n disposeGameSession(input, disconnectController);\n\n return {\n openGameSession,\n readGameSession,\n observeGameSession,\n readGameSettings,\n updateGameSettings,\n sendGameSessionInput,\n controlGameSessionParticipant,\n invokeGameSessionAction,\n captureGameSessionVisuals,\n closeGameSession,\n async openRunSession(\n options: OpenGameSessionOptions,\n {\n delegation,\n game,\n build,\n room,\n settings,\n onScope,\n }: {\n /** The creator's host, how many seats the run may hold there, and how it claims each. */\n delegation?: {\n host: HostRequester;\n seats: number;\n claimSeat: SeatClaimer;\n };\n game?: AirJamGameInspection;\n build?: PinnedGameBuild;\n /** A headless room this run owns; its players join it on game time. */\n room?: HeadlessRoom;\n settings?: Record<string, number | boolean | string>;\n onScope?: ProcessScopeObserver;\n } = {},\n ): Promise<GameRunSession> {\n if (room && (delegation || build || options.controllerJoinUrl))\n throw new Error(\n \"A headless room is its own target; it takes no build or other room.\",\n );\n const summary = await openGameSession(\n room\n ? { ...options, controllerJoinUrl: room.controllerJoinUrl }\n : options,\n room\n ? { access: \"owned-host\", request: room.requestHost }\n : delegation && {\n access: \"delegated-host\",\n request: delegation.host,\n claimSeat: delegation.claimSeat,\n },\n build,\n onScope,\n room ? undefined : settings,\n game,\n );\n let seatsLeft = (delegation?.seats ?? 0) - 1;\n const gameSessionId = summary.gameSessionId;\n const session = getRequiredGameSession(gameSessionId);\n const checkParticipant = async (\n controllerSessionId: string,\n controllerId: string,\n ) => {\n const state = await readRuntimeSnapshot({\n controllerSessionId,\n requestSync: false,\n });\n if (!state.connected || state.controllerId !== controllerId)\n throw new Error(\n \"seat_replaced: Run participant is no longer connected.\",\n );\n };\n const observeParticipant =\n (\n controllerSessionId: string,\n controllerId: string,\n ): GameRunParticipant[\"observe\"] =>\n (input) =>\n session.operations.run(DEFAULT_TIMEOUT_MS, async (signal) => {\n await checkParticipant(controllerSessionId, controllerId);\n const result = await session.requestHost(\n {\n operation: \"observe\",\n roomId: summary.roomId,\n controllerId,\n ...input,\n },\n DEFAULT_TIMEOUT_MS,\n signal,\n );\n if (result.operation !== \"observe\")\n throw new Error(\n \"invalid_runtime_response: Expected a host observation.\",\n );\n await checkParticipant(controllerSessionId, controllerId);\n return result.observation;\n });\n const watchController =\n (controllerSessionId: string): GameRunParticipant[\"watch\"] =>\n (onEvent, signal) =>\n watchControllerSessionVisuals({\n ownerControllerSessionId: summary.controllerSessionId,\n controllerSessionId,\n onEvent,\n signal,\n });\n return {\n summary,\n clock: room?.clock ?? wallClock,\n requestHost: session.requestHost,\n watch: watchController(summary.controllerSessionId),\n watchHost: (onEvent, signal) =>\n watchControllerSessionVisuals({\n ownerControllerSessionId: summary.controllerSessionId,\n onEvent,\n signal,\n }),\n async readParticipants() {\n const state = await readRuntimeSnapshot({\n controllerSessionId: summary.controllerSessionId,\n requestSync: false,\n });\n if (!state.connected)\n throw new Error(\"seat_replaced: Primary player is disconnected.\");\n return {\n roomId: state.roomId,\n controllerIds: seatViewSchema\n .array()\n .parse(state.players)\n .map((player) => player.id),\n };\n },\n checkConnected: () =>\n checkParticipant(summary.controllerSessionId, summary.controllerId),\n observe: observeParticipant(\n summary.controllerSessionId,\n summary.controllerId,\n ),\n control: (input) =>\n controlGameSessionParticipant({ ...input, gameSessionId }),\n async addParticipant(nickname) {\n if (delegation && seatsLeft <= 0)\n throw new Error(\n \"current_room_scope: The creator's room granted no further seat.\",\n );\n seatsLeft -= 1;\n const controller = await connectController({\n cwd: summary.cwd,\n gameId: summary.gameId ?? undefined,\n controllerJoinUrl: summary.controllerJoinUrl,\n nickname,\n });\n if (delegation)\n await delegation\n .claimSeat(claimOf(controller), DEFAULT_TIMEOUT_MS)\n .catch(async (error: unknown) => {\n await disconnectController({\n controllerSessionId: controller.controllerSessionId,\n });\n throw error;\n });\n let disconnected:\n | Awaited<ReturnType<typeof disconnectController>>\n | undefined;\n const dispose = async (disconnect: typeof disconnectController) => {\n const result = (disconnected ??= await disconnect({\n controllerSessionId: controller.controllerSessionId,\n }));\n return { release: result.release, leave: result.leave };\n };\n return {\n controllerId: controller.controllerId,\n watch: watchController(controller.controllerSessionId),\n checkConnected: () =>\n checkParticipant(\n controller.controllerSessionId,\n controller.controllerId,\n ),\n observe: observeParticipant(\n controller.controllerSessionId,\n controller.controllerId,\n ),\n control: (input) =>\n session.operations.run(DEFAULT_TIMEOUT_MS, () =>\n controlControllerParticipant({\n ...input,\n controllerSessionId: controller.controllerSessionId,\n }),\n ),\n close: () => dispose(disconnectController),\n forceClose: () => dispose(forceDisconnectController),\n } satisfies GameRunParticipant;\n },\n invokeHost: async (actionId, payload) => {\n const result = await invokeGameSessionAction({\n gameSessionId,\n actionId: `host:${actionId}`,\n payload,\n });\n if (!result.invocation.acknowledgement.ok)\n throw new Error(\"Host setup action was rejected.\");\n return result;\n },\n close: () => closeGameSession({ gameSessionId }),\n forceClose: () =>\n disposeGameSession({ gameSessionId }, forceDisconnectController),\n };\n },\n };\n}\n","import type { AirJamActionInvocationResult } from \"@air-jam/sdk/protocol\";\nimport type { AirJamGameSnapshotInspection } from \"./types.js\";\n\nexport const isHostAcknowledgementObservationGap = (\n acknowledgement: AirJamActionInvocationResult,\n): boolean =>\n acknowledgement.status === \"rejected\" &&\n (acknowledgement.reason === \"host_ack_missing\" ||\n acknowledgement.reason === \"host_ack_timeout\");\n\nconst stableStoreSnapshotFingerprint = (\n snapshot: AirJamGameSnapshotInspection,\n): string =>\n JSON.stringify(\n snapshot.rawStores\n .map((entry) => ({\n storeDomain: entry.storeDomain,\n revision: entry.revision,\n }))\n .sort((left, right) => left.storeDomain.localeCompare(right.storeDomain)),\n );\n\nconst stableStoreSnapshotDataFingerprint = (\n snapshot: AirJamGameSnapshotInspection,\n): string =>\n JSON.stringify(\n snapshot.rawStores\n .map((entry) => ({\n storeDomain: entry.storeDomain,\n data: entry.data,\n }))\n .sort((left, right) => left.storeDomain.localeCompare(right.storeDomain)),\n );\n\nexport const computeGameSnapshotObservation = ({\n snapshotBefore,\n snapshotAfter,\n}: {\n snapshotBefore: AirJamGameSnapshotInspection;\n snapshotAfter: AirJamGameSnapshotInspection;\n}): {\n snapshotAfterStatus:\n | \"committed-update-observed\"\n | \"no-new-commit-before-timeout\"\n | \"contract_changed\"\n | \"runtime_replaced\";\n observedStateChange: boolean;\n} => {\n const replaced =\n snapshotBefore.runtimeId !== snapshotAfter.runtimeId\n ? \"runtime_replaced\"\n : snapshotBefore.contractId !== snapshotAfter.contractId\n ? \"contract_changed\"\n : null;\n if (replaced)\n return { snapshotAfterStatus: replaced, observedStateChange: false };\n const fingerprintBefore = stableStoreSnapshotFingerprint(snapshotBefore);\n const fingerprintAfter = stableStoreSnapshotFingerprint(snapshotAfter);\n const dataFingerprintBefore =\n stableStoreSnapshotDataFingerprint(snapshotBefore);\n const dataFingerprintAfter =\n stableStoreSnapshotDataFingerprint(snapshotAfter);\n const projectedSnapshotBefore = JSON.stringify(snapshotBefore.snapshot);\n const projectedSnapshotAfter = JSON.stringify(snapshotAfter.snapshot);\n\n return {\n snapshotAfterStatus:\n fingerprintBefore === fingerprintAfter\n ? \"no-new-commit-before-timeout\"\n : \"committed-update-observed\",\n observedStateChange:\n dataFingerprintBefore !== dataFingerprintAfter ||\n projectedSnapshotBefore !== projectedSnapshotAfter,\n };\n};\n\nexport const classifyGameActionOutcome = ({\n acknowledgement,\n observedStateChange,\n}: {\n acknowledgement: AirJamActionInvocationResult;\n observedStateChange: boolean;\n}): {\n acknowledgementObservation:\n | \"host-acknowledged\"\n | \"host-acknowledgement-not-observed\";\n outcome:\n | \"accepted\"\n | \"rejected\"\n | \"acknowledgement-not-observed-state-changed\"\n | \"acknowledgement-not-observed-no-state-change-observed\";\n} => {\n if (!isHostAcknowledgementObservationGap(acknowledgement)) {\n return {\n acknowledgementObservation: \"host-acknowledged\",\n outcome: acknowledgement.status === \"accepted\" ? \"accepted\" : \"rejected\",\n };\n }\n\n return {\n acknowledgementObservation: \"host-acknowledgement-not-observed\",\n outcome: observedStateChange\n ? \"acknowledgement-not-observed-state-changed\"\n : \"acknowledgement-not-observed-no-state-change-observed\",\n };\n};\n","export class GameSessionOperations {\n private tail: Promise<unknown> = Promise.resolve();\n private controller = new AbortController();\n private failure: Error | null = null;\n private queued = 0;\n\n run<T>(\n timeoutMs: number,\n operation: (signal: AbortSignal) => Promise<T>,\n ): Promise<T> {\n if (this.failure) return Promise.reject(this.failure);\n if (this.queued >= 32)\n return Promise.reject(\n new Error(\"session_busy: Too many queued game operations.\"),\n );\n this.queued++;\n const result = this.tail.then(async () => {\n if (this.failure) throw this.failure;\n let timer: ReturnType<typeof setTimeout>;\n const aborted = new Promise<never>((_, reject) => {\n const fail = () => reject(this.failure ?? new Error(\"session_closed\"));\n this.controller.signal.addEventListener(\"abort\", fail, { once: true });\n timer = setTimeout(() => {\n this.failure = new Error(\n \"evaluation_timeout: Game operation exceeded its deadline; close this session before opening another.\",\n );\n this.controller.abort();\n }, timeoutMs);\n this.cancelCurrent = () => {\n clearTimeout(timer);\n this.controller.signal.removeEventListener(\"abort\", fail);\n };\n });\n try {\n return await Promise.race([operation(this.controller.signal), aborted]);\n } catch (error) {\n if (\n error instanceof Error &&\n /runtime_disconnected|evaluation_timeout|invalid_runtime_response/.test(\n error.message,\n )\n )\n this.failure = error;\n throw error;\n } finally {\n this.cancelCurrent();\n }\n });\n this.tail = result\n .catch(() => undefined)\n .finally(() => {\n this.queued--;\n });\n return result;\n }\n private cancelCurrent = () => {};\n close() {\n this.failure = new Error(\"session_closed: This game session is closed.\");\n this.controller.abort();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,EACE;AAAA,OAGK;;;ACHA,IAAM,iBAAN,cAA6B,MAAM;AAAC;AAG3C,eAAsB,gBACpB,MACA,UACA;AACA,QAAM,SAAS,KAAK,UAAU;AAC9B,QAAM,SAAuB,CAAC;AAC9B,MAAI,QAAQ;AACZ,MAAI;AACF,WAAO,MAAM;AACX,YAAM,OAAO,MAAM,OAAO,KAAK;AAC/B,UAAI,KAAK,KAAM;AACf,eAAS,KAAK,MAAM;AACpB,UAAI,QAAQ;AACV,cAAM,IAAI,eAAe,qBAAqB,QAAQ,SAAS;AACjE,aAAO,KAAK,KAAK,KAAK;AAAA,IACxB;AAAA,EACF,SAAS,OAAO;AACd,UAAM,OAAO,OAAO,EAAE,MAAM,MAAM,MAAS;AAC3C,UAAM;AAAA,EACR,UAAE;AACA,WAAO,YAAY;AAAA,EACrB;AACA,SAAO,OAAO,OAAO,QAAQ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B,MACzC,6BAA6B;AAAA,gBAC3B,GAAG;AAAA,gBACH,qBAAqB,WAAW;AAAA,cAClC,CAAC;AAAA,YACH;AAAA,YACF,OAAO,MAAM,QAAQ,oBAAoB;AAAA,YACzC,YAAY,MAAM,QAAQ,yBAAyB;AAAA,UACrD;AAAA,QACF;AAAA,QACA,YAAY,OAAO,UAAU,YAAY;AACvC,gBAAM,SAAS,MAAM,wBAAwB;AAAA,YAC3C;AAAA,YACA,UAAU,QAAQ,QAAQ;AAAA,YAC1B;AAAA,UACF,CAAC;AACD,cAAI,CAAC,OAAO,WAAW,gBAAgB;AACrC,kBAAM,IAAI,MAAM,iCAAiC;AACnD,iBAAO;AAAA,QACT;AAAA,QACA,OAAO,MAAM,iBAAiB,EAAE,cAAc,CAAC;AAAA,QAC/C,YAAY,MACV,mBAAmB,EAAE,cAAc,GAAG,yBAAyB;AAAA,MACnE;AAAA,IACF;AAAA,EACF;AACF;","names":["createHash","randomUUID","open","readFile","path","request","logPath","constants","lstat","realpath","path","lstat","constants","path","realpath","relative","randomUUID","randomUUID","path","open","run","readFile","error","randomUUID","option","createHash","file","message","evaluator","randomUUID","path","randomUUID","timeoutMs","action","path"]}
|