@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.
Files changed (263) hide show
  1. package/README.md +60 -0
  2. package/dist/{chunk-VKMJO6VN.js → chunk-2O67AXCU.js} +150 -40
  3. package/dist/chunk-2O67AXCU.js.map +1 -0
  4. package/dist/chunk-AO3ZDXF6.js +142 -0
  5. package/dist/chunk-AO3ZDXF6.js.map +1 -0
  6. package/dist/chunk-ART5TEYT.js +472 -0
  7. package/dist/chunk-ART5TEYT.js.map +1 -0
  8. package/dist/chunk-ASC2CK2R.js +77 -0
  9. package/dist/chunk-ASC2CK2R.js.map +1 -0
  10. package/dist/chunk-E3UZZGAV.js +50 -0
  11. package/dist/chunk-E3UZZGAV.js.map +1 -0
  12. package/dist/chunk-EJTE7UKX.js +64 -0
  13. package/dist/chunk-EJTE7UKX.js.map +1 -0
  14. package/dist/chunk-ESFKNN75.js +110 -0
  15. package/dist/chunk-ESFKNN75.js.map +1 -0
  16. package/dist/chunk-EU7A6PXW.js +1339 -0
  17. package/dist/chunk-EU7A6PXW.js.map +1 -0
  18. package/dist/chunk-FN7E6EA7.js +549 -0
  19. package/dist/chunk-FN7E6EA7.js.map +1 -0
  20. package/dist/chunk-GDFAWHGA.js +190 -0
  21. package/dist/chunk-GDFAWHGA.js.map +1 -0
  22. package/dist/chunk-HZUGBH4Y.js +347 -0
  23. package/dist/chunk-HZUGBH4Y.js.map +1 -0
  24. package/dist/chunk-ITKAOEGX.js +93 -0
  25. package/dist/chunk-ITKAOEGX.js.map +1 -0
  26. package/dist/chunk-JBCUTWRI.js +897 -0
  27. package/dist/chunk-JBCUTWRI.js.map +1 -0
  28. package/dist/chunk-JSI5S4WP.js +1174 -0
  29. package/dist/chunk-JSI5S4WP.js.map +1 -0
  30. package/dist/chunk-L4D675BG.js +97 -0
  31. package/dist/chunk-L4D675BG.js.map +1 -0
  32. package/dist/chunk-M6CJ7GQC.js +133 -0
  33. package/dist/chunk-M6CJ7GQC.js.map +1 -0
  34. package/dist/{chunk-CKFT2ZJE.js → chunk-MEIMOSZC.js} +53 -105
  35. package/dist/chunk-MEIMOSZC.js.map +1 -0
  36. package/dist/{chunk-GUEZP773.js → chunk-O3XG3FNL.js} +204 -41
  37. package/dist/chunk-O3XG3FNL.js.map +1 -0
  38. package/dist/chunk-OM6SCJ7H.js +18 -0
  39. package/dist/chunk-OM6SCJ7H.js.map +1 -0
  40. package/dist/chunk-PKD4WVX5.js +63 -0
  41. package/dist/chunk-PKD4WVX5.js.map +1 -0
  42. package/dist/chunk-PMBLXGFM.js +3384 -0
  43. package/dist/chunk-PMBLXGFM.js.map +1 -0
  44. package/dist/chunk-PMNE5GIN.js +279 -0
  45. package/dist/chunk-PMNE5GIN.js.map +1 -0
  46. package/dist/chunk-QAWI64VR.js +148 -0
  47. package/dist/chunk-QAWI64VR.js.map +1 -0
  48. package/dist/chunk-QGADSPHZ.js +449 -0
  49. package/dist/chunk-QGADSPHZ.js.map +1 -0
  50. package/dist/chunk-SPYN66UV.js +338 -0
  51. package/dist/chunk-SPYN66UV.js.map +1 -0
  52. package/dist/context.d.ts +9 -3
  53. package/dist/context.js +2 -1
  54. package/dist/controller.d.ts +33 -7
  55. package/dist/controller.js +18 -8
  56. package/dist/dependencies.d.ts +44 -0
  57. package/dist/dependencies.js +10 -0
  58. package/dist/dev.d.ts +9 -3
  59. package/dist/dev.js +3 -4
  60. package/dist/game-builds.d.ts +200 -0
  61. package/dist/game-builds.js +16 -0
  62. package/dist/game-builds.js.map +1 -0
  63. package/dist/game-run-watch-CEd_SpAT.d.ts +84 -0
  64. package/dist/game-runs.d.ts +1452 -0
  65. package/dist/game-runs.js +76 -0
  66. package/dist/game-runs.js.map +1 -0
  67. package/dist/game-session-broker-CUvORfMd.d.ts +439 -0
  68. package/dist/game-session-broker.d.ts +4 -57
  69. package/dist/game-session-broker.js +33 -228
  70. package/dist/game-session-broker.js.map +1 -1
  71. package/dist/game-session.d.ts +3931 -10
  72. package/dist/game-session.js +186 -15
  73. package/dist/game-session.js.map +1 -1
  74. package/dist/game-settings.d.ts +16 -0
  75. package/dist/game-settings.js +237 -0
  76. package/dist/game-settings.js.map +1 -0
  77. package/dist/games.d.ts +11 -4
  78. package/dist/games.js +4 -2
  79. package/dist/harness/visual.d.ts +34 -151
  80. package/dist/harness/visual.js +6 -1
  81. package/dist/logs.d.ts +8 -2
  82. package/dist/logs.js +3 -4
  83. package/dist/logs.js.map +1 -1
  84. package/dist/managed-process-scope-BicYi_t9.d.ts +3 -0
  85. package/dist/mcp-config.js +2 -1
  86. package/dist/mcp-config.js.map +1 -1
  87. package/dist/platform-auth.d.ts +8 -111
  88. package/dist/platform-auth.js +9 -1
  89. package/dist/platform-game-analytics.d.ts +51 -0
  90. package/dist/platform-game-analytics.js +49 -0
  91. package/dist/platform-game-analytics.js.map +1 -0
  92. package/dist/platform-game-app-id.d.ts +46 -0
  93. package/dist/platform-game-app-id.js +93 -0
  94. package/dist/platform-game-app-id.js.map +1 -0
  95. package/dist/platform-game-media.d.ts +40 -2
  96. package/dist/platform-game-media.js +1 -1
  97. package/dist/platform-games.d.ts +24 -2
  98. package/dist/platform-games.js +16 -84
  99. package/dist/platform-games.js.map +1 -1
  100. package/dist/quality.d.ts +9 -3
  101. package/dist/quality.js +3 -4
  102. package/dist/quality.js.map +1 -1
  103. package/dist/release.d.ts +226 -16
  104. package/dist/release.js +18 -1331
  105. package/dist/release.js.map +1 -1
  106. package/dist/rooms-check.d.ts +90 -0
  107. package/dist/rooms-check.js +717 -0
  108. package/dist/rooms-check.js.map +1 -0
  109. package/dist/source-tree-contract.d.ts +16 -0
  110. package/dist/source-tree-contract.js +13 -0
  111. package/dist/source-tree-contract.js.map +1 -0
  112. package/dist/testing.d.ts +464 -0
  113. package/dist/testing.js +27 -0
  114. package/dist/testing.js.map +1 -0
  115. package/dist/tooling/describe-game.js +54 -0
  116. package/dist/tooling/describe-game.js.map +1 -0
  117. package/dist/tooling/game-session-broker.js +28 -0
  118. package/dist/tooling/game-session-broker.js.map +1 -0
  119. package/dist/tooling/hold-runtime-host.js +769 -67
  120. package/dist/tooling/hold-runtime-host.js.map +1 -1
  121. package/dist/tooling/list-visual-scenarios.js +18 -55
  122. package/dist/tooling/list-visual-scenarios.js.map +1 -1
  123. package/dist/tooling/process-scope-bootstrap.mjs +24 -0
  124. package/dist/tooling/process-scope-guard.d.ts +2 -0
  125. package/dist/tooling/process-scope-guard.js +388 -0
  126. package/dist/tooling/process-scope-guard.js.map +1 -0
  127. package/dist/tooling/process-scope-windows.ps1 +148 -0
  128. package/dist/tooling/rooms-check-device.d.ts +2 -0
  129. package/dist/tooling/rooms-check-device.js +498 -0
  130. package/dist/tooling/rooms-check-device.js.map +1 -0
  131. package/dist/tooling/run-headless-room.d.ts +2 -0
  132. package/dist/tooling/run-headless-room.js +287 -0
  133. package/dist/tooling/run-headless-room.js.map +1 -0
  134. package/dist/tooling/run-test-profile.d.ts +2 -0
  135. package/dist/tooling/run-test-profile.js +181 -0
  136. package/dist/tooling/run-test-profile.js.map +1 -0
  137. package/dist/tooling/run-visual-capture.js +70 -34
  138. package/dist/tooling/run-visual-capture.js.map +1 -1
  139. package/dist/tooling/seal-game-build.d.ts +2 -0
  140. package/dist/tooling/seal-game-build.js +120 -0
  141. package/dist/tooling/seal-game-build.js.map +1 -0
  142. package/dist/{types-C6NrHt88.d.ts → types-CdYrgrG_.d.ts} +337 -76
  143. package/dist/types-DyRD-ym1.d.ts +141 -0
  144. package/dist/visual.d.ts +9 -3
  145. package/dist/visual.js +24 -68
  146. package/dist/visual.js.map +1 -1
  147. package/package.json +51 -14
  148. package/src/bounded-response.ts +28 -0
  149. package/src/built-game-runtime.ts +152 -0
  150. package/src/context.ts +2 -13
  151. package/src/controller-protocol.ts +22 -0
  152. package/src/controller.ts +747 -597
  153. package/src/current-room-host.ts +166 -0
  154. package/src/decision-provider.ts +102 -0
  155. package/src/dependencies.ts +176 -0
  156. package/src/dependency-install-contract.ts +12 -0
  157. package/src/dev.ts +46 -50
  158. package/src/game-action-observation.ts +11 -1
  159. package/src/game-build-protocol.ts +72 -0
  160. package/src/game-build.ts +483 -0
  161. package/src/game-run-owner.ts +2358 -0
  162. package/src/game-run-protocol.ts +448 -0
  163. package/src/game-run-record.ts +92 -0
  164. package/src/game-run-replay.ts +95 -0
  165. package/src/game-run-watch.ts +155 -0
  166. package/src/game-session-broker.ts +689 -197
  167. package/src/game-session-operations.ts +61 -0
  168. package/src/game-session-protocol.ts +180 -0
  169. package/src/game-session-runtime.ts +861 -0
  170. package/src/game-session.ts +164 -417
  171. package/src/game-settings.ts +295 -0
  172. package/src/games.ts +88 -92
  173. package/src/harness/visual/browser.ts +100 -0
  174. package/src/harness/visual/controller-observation.ts +181 -0
  175. package/src/harness/visual/runner.ts +24 -21
  176. package/src/harness/visual/runtime-controller-observations.ts +151 -0
  177. package/src/harness/visual/scenario-contract.ts +1 -2
  178. package/src/harness/visual/scenario-helpers.ts +5 -1
  179. package/src/harness/visual/screencast.ts +155 -0
  180. package/src/harness/visual/session.ts +72 -41
  181. package/src/harness/visual/types.ts +8 -5
  182. package/src/headless-room-protocol.ts +112 -0
  183. package/src/headless-room.ts +222 -0
  184. package/src/helper-channel.ts +229 -0
  185. package/src/helper-scripts.ts +25 -5
  186. package/src/installed-dependencies.ts +74 -0
  187. package/src/managed-process-scope.ts +481 -0
  188. package/src/node-process-environment.ts +10 -0
  189. package/src/platform-auth.ts +194 -55
  190. package/src/platform-game-analytics.ts +50 -0
  191. package/src/platform-game-app-id.ts +99 -0
  192. package/src/platform-games.ts +13 -111
  193. package/src/policy-artifact-contract.ts +52 -0
  194. package/src/policy-artifacts.ts +134 -0
  195. package/src/process-scope-admission.ts +50 -0
  196. package/src/process-scope-protocol.ts +66 -0
  197. package/src/process-scope.ts +327 -0
  198. package/src/release.ts +28 -42
  199. package/src/rooms-check-fleet.ts +194 -0
  200. package/src/rooms-check-link.ts +138 -0
  201. package/src/rooms-check-protocol.ts +244 -0
  202. package/src/rooms-check.ts +797 -0
  203. package/src/runtime-owner-protocol.ts +106 -18
  204. package/src/source-tree-contract.ts +70 -0
  205. package/src/source-tree.ts +84 -0
  206. package/src/test-profile-process.ts +153 -0
  207. package/src/test-profile-protocol.ts +116 -0
  208. package/src/testing.ts +430 -0
  209. package/src/tooling/declaration-hook.ts +52 -0
  210. package/src/tooling/describe-game.ts +49 -0
  211. package/src/tooling/game-session-broker.ts +7 -0
  212. package/src/tooling/hold-runtime-host.ts +255 -38
  213. package/src/tooling/list-visual-scenarios.ts +19 -62
  214. package/src/tooling/load-game.ts +79 -0
  215. package/src/tooling/process-scope-bootstrap.mjs +24 -0
  216. package/src/tooling/process-scope-guard.ts +213 -0
  217. package/src/tooling/process-scope-windows.ps1 +148 -0
  218. package/src/tooling/rooms-check-device.ts +493 -0
  219. package/src/tooling/run-headless-room.ts +326 -0
  220. package/src/tooling/run-test-profile.ts +190 -0
  221. package/src/tooling/run-visual-capture.ts +37 -23
  222. package/src/tooling/runtime-owner-actions.ts +23 -0
  223. package/src/tooling/seal-game-build.ts +118 -0
  224. package/src/tooling/visual-pack.ts +10 -45
  225. package/src/types.ts +54 -77
  226. package/src/visual.ts +14 -22
  227. package/src/windows-process-scopes.ts +189 -0
  228. package/dist/agent.d.ts +0 -15
  229. package/dist/agent.js +0 -19
  230. package/dist/chunk-5YAARMW5.js +0 -36
  231. package/dist/chunk-5YAARMW5.js.map +0 -1
  232. package/dist/chunk-6WQODT37.js +0 -1019
  233. package/dist/chunk-6WQODT37.js.map +0 -1
  234. package/dist/chunk-CKFT2ZJE.js.map +0 -1
  235. package/dist/chunk-ER3Q2C4G.js +0 -358
  236. package/dist/chunk-ER3Q2C4G.js.map +0 -1
  237. package/dist/chunk-GUEZP773.js.map +0 -1
  238. package/dist/chunk-HIDNI56E.js +0 -33
  239. package/dist/chunk-HIDNI56E.js.map +0 -1
  240. package/dist/chunk-QKXS5D35.js +0 -43
  241. package/dist/chunk-QKXS5D35.js.map +0 -1
  242. package/dist/chunk-S4LSCEVE.js +0 -261
  243. package/dist/chunk-S4LSCEVE.js.map +0 -1
  244. package/dist/chunk-VKMJO6VN.js.map +0 -1
  245. package/dist/chunk-WFUR3MXY.js +0 -67
  246. package/dist/chunk-WFUR3MXY.js.map +0 -1
  247. package/dist/chunk-XEMR7KUE.js +0 -361
  248. package/dist/chunk-XEMR7KUE.js.map +0 -1
  249. package/dist/chunk-ZLPD7FY5.js +0 -191
  250. package/dist/chunk-ZLPD7FY5.js.map +0 -1
  251. package/dist/tooling/agent-contract.js +0 -193
  252. package/dist/tooling/agent-contract.js.map +0 -1
  253. package/dist/tooling/inspect-airjam-agent.js +0 -37
  254. package/dist/tooling/inspect-airjam-agent.js.map +0 -1
  255. package/src/agent.ts +0 -380
  256. package/src/tooling/agent-contract.ts +0 -232
  257. package/src/tooling/agent-declaration.ts +0 -36
  258. package/src/tooling/airjam-agent-inspection.ts +0 -45
  259. package/src/tooling/airjam-agent.ts +0 -118
  260. package/src/tooling/inspect-airjam-agent.ts +0 -20
  261. /package/dist/{agent.js.map → dependencies.js.map} +0 -0
  262. /package/dist/tooling/{agent-contract.d.ts → describe-game.d.ts} +0 -0
  263. /package/dist/tooling/{inspect-airjam-agent.d.ts → game-session-broker.d.ts} +0 -0
@@ -0,0 +1,181 @@
1
+ import { AIR_JAM_RUNTIME_INSPECTION_KEY } from "@air-jam/sdk/runtime-inspection";
2
+ import {
3
+ parseRuntimeTopologyFromSearchParams,
4
+ resolveRuntimeTopology,
5
+ runtimeTopologyToQueryParams,
6
+ } from "@air-jam/sdk/runtime-topology";
7
+ import type { Browser } from "playwright-core";
8
+ import { installHarnessRuntimeTopology } from "./browser.js";
9
+ import { DEFAULT_CONTROLLER_VIEWPORT } from "./session.js";
10
+
11
+ /**
12
+ * Shows the acting phone's controller in a browser page for capture. The
13
+ * page frames the game's controller as an embedded harness controller and
14
+ * relays the room port it asks for to `onPortMessage`; the room's answers
15
+ * come back through `deliver`. Whoever holds the acting phone serves that
16
+ * port, read-only, as a view of its session.
17
+ */
18
+ export async function openControllerObservation({
19
+ browser,
20
+ controllerJoinUrl,
21
+ harnessSessionId,
22
+ roomId,
23
+ onPortMessage,
24
+ signal,
25
+ }: {
26
+ browser: Browser;
27
+ controllerJoinUrl: string;
28
+ harnessSessionId: string;
29
+ roomId: string;
30
+ onPortMessage: (message: unknown) => void;
31
+ signal?: AbortSignal;
32
+ }) {
33
+ const context = await browser.newContext({
34
+ viewport: DEFAULT_CONTROLLER_VIEWPORT,
35
+ });
36
+ let closing: Promise<void> | undefined;
37
+ const close = () => {
38
+ signal?.removeEventListener("abort", aborted);
39
+ return (closing ??= context.close());
40
+ };
41
+ const aborted = () => {
42
+ // The lifecycle awaits this same close promise, including its failure.
43
+ void close().catch(() => undefined);
44
+ };
45
+ signal?.addEventListener("abort", aborted, { once: true });
46
+ try {
47
+ signal?.throwIfAborted();
48
+ const controllerUrl = new URL(controllerJoinUrl);
49
+ const parentUrl = new URL(
50
+ `/__airjam/controller-observation/${harnessSessionId}`,
51
+ "http://airjam-controller-observation.localhost",
52
+ );
53
+ // Fulfilled documents have no network address space. Give only this
54
+ // trusted capture shell permission to load the local game controller.
55
+ await context.grantPermissions(["local-network-access"], {
56
+ origin: parentUrl.origin,
57
+ });
58
+ const topology = parseRuntimeTopologyFromSearchParams(
59
+ controllerUrl.searchParams,
60
+ );
61
+ if (!topology)
62
+ throw new Error(
63
+ "Controller observation requires complete runtime topology.",
64
+ );
65
+ const observationTopology = resolveRuntimeTopology({
66
+ ...topology,
67
+ embedded: true,
68
+ embedParentOrigin: parentUrl.origin,
69
+ });
70
+ await installHarnessRuntimeTopology(context, observationTopology);
71
+ for (const [name, value] of Object.entries(
72
+ runtimeTopologyToQueryParams(observationTopology),
73
+ ))
74
+ controllerUrl.searchParams.set(name, value);
75
+ controllerUrl.searchParams.set("aj_room", roomId);
76
+ controllerUrl.searchParams.set("aj_harness_session", harnessSessionId);
77
+ const page = await context.newPage();
78
+ await page.route(parentUrl.href, (route) =>
79
+ route.fulfill({
80
+ contentType: "text/html",
81
+ body: "<!doctype html><html><head><style>html,body,iframe{width:100%;height:100%;margin:0;border:0;display:block;overflow:hidden}</style></head><body></body></html>",
82
+ }),
83
+ );
84
+ await page.exposeBinding(
85
+ "airJamObservationMessage",
86
+ (_, message: unknown) => onPortMessage(message),
87
+ );
88
+ await page.goto(parentUrl.href, { waitUntil: "domcontentloaded" });
89
+ await page.evaluate(
90
+ ({ controllerUrl, harnessSessionId }) => {
91
+ const frame = document.createElement("iframe");
92
+ let port: MessagePort | null = null;
93
+ const pending: unknown[] = [];
94
+ Object.assign(window, {
95
+ airJamObservationDeliver: (message: unknown) => {
96
+ if (port) port.postMessage(message);
97
+ else pending.push(message);
98
+ },
99
+ });
100
+ window.addEventListener("message", (event: MessageEvent<unknown>) => {
101
+ if (
102
+ event.source !== frame.contentWindow ||
103
+ event.origin !== new URL(controllerUrl).origin
104
+ )
105
+ return;
106
+ const request = event.data as {
107
+ type?: string;
108
+ payload?: { role?: string; harnessSessionId?: string };
109
+ };
110
+ if (
111
+ request.type !== "AIRJAM_ROOM_BRIDGE_REQUEST" ||
112
+ !event.ports[0] ||
113
+ request.payload?.role !== "controller" ||
114
+ request.payload.harnessSessionId !== harnessSessionId
115
+ )
116
+ return;
117
+ port?.close();
118
+ port = event.ports[0];
119
+ port.onmessage = (message: MessageEvent<unknown>) => {
120
+ const binding = Reflect.get(window, "airJamObservationMessage") as (
121
+ value: unknown,
122
+ ) => Promise<void>;
123
+ void binding(message.data);
124
+ };
125
+ port.start();
126
+ for (const message of pending.splice(0)) port.postMessage(message);
127
+ });
128
+ frame.src = controllerUrl;
129
+ frame.title = "Acting controller observation";
130
+ document.body.append(frame);
131
+ },
132
+ { controllerUrl: controllerUrl.href, harnessSessionId },
133
+ );
134
+ const frameElement = await page.locator("iframe").elementHandle();
135
+ if (!frameElement)
136
+ throw new Error("Controller observation frame is missing.");
137
+ const controllerFrame = await frameElement.contentFrame();
138
+ if (!controllerFrame)
139
+ throw new Error("Controller observation document is unavailable.");
140
+ // Connecting needs the room's answers delivered, so the caller gets the
141
+ // delivery handle now and awaits `ready` after draining what it holds.
142
+ const ready = (async () => {
143
+ await controllerFrame.waitForFunction(
144
+ ({ key, roomId }) => {
145
+ const inspection = Reflect.get(window, key) as
146
+ | { roomId?: string; connectionStatus?: string }
147
+ | undefined;
148
+ return (
149
+ inspection?.roomId === roomId &&
150
+ inspection.connectionStatus === "connected"
151
+ );
152
+ },
153
+ { key: AIR_JAM_RUNTIME_INSPECTION_KEY, roomId },
154
+ );
155
+ // Inspection updates in an effect; allow its rendered controller state to reach the compositor.
156
+ await controllerFrame.evaluate(
157
+ () =>
158
+ new Promise<void>((resolve) =>
159
+ requestAnimationFrame(() => requestAnimationFrame(() => resolve())),
160
+ ),
161
+ );
162
+ signal?.throwIfAborted();
163
+ })();
164
+ return {
165
+ page,
166
+ ready,
167
+ async deliver(message: unknown) {
168
+ await page.evaluate((message) => {
169
+ const deliver = Reflect.get(window, "airJamObservationDeliver") as (
170
+ value: unknown,
171
+ ) => void;
172
+ deliver(message);
173
+ }, message);
174
+ },
175
+ close,
176
+ };
177
+ } catch (error) {
178
+ await close();
179
+ throw error;
180
+ }
181
+ }
@@ -1,6 +1,7 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import type { Browser, Page } from "playwright-core";
4
+ import { inspectGame } from "../../games.js";
4
5
  import {
5
6
  DEFAULT_HOST_VIEWPORT,
6
7
  dismissHarnessControllerFullscreenPrompt,
@@ -13,6 +14,7 @@ import type {
13
14
  VisualCaptureScenarioMetadata,
14
15
  VisualCaptureSummary,
15
16
  VisualHarnessMode,
17
+ VisualHarnessPageSurface,
16
18
  VisualHarnessUrls,
17
19
  VisualScenario,
18
20
  VisualScenarioAgent,
@@ -22,6 +24,15 @@ import type {
22
24
  VisualViewport,
23
25
  } from "./types.js";
24
26
 
27
+ type VisualAgentSessionOptions = {
28
+ gameId: string;
29
+ scenarioId: string;
30
+ host: VisualHarnessPageSurface;
31
+ urls: VisualHarnessUrls;
32
+ mode: VisualHarnessMode;
33
+ secure: boolean;
34
+ };
35
+
25
36
  const ensureDir = (dir: string): void => {
26
37
  fs.mkdirSync(dir, { recursive: true });
27
38
  };
@@ -161,15 +172,13 @@ const createScenarioRunContext = async <TAgent extends AnyAirJamAgentContract>({
161
172
  urls: Omit<VisualHarnessUrls, "controllerJoinUrl">;
162
173
  mode: VisualHarnessMode;
163
174
  secure: boolean;
164
- createAgentSession?: (options: {
165
- gameId: string;
166
- scenarioId: string;
167
- urls: VisualHarnessUrls;
168
- mode: VisualHarnessMode;
169
- secure: boolean;
170
- }) => Promise<VisualScenarioAgent<InferVisualScenarioSnapshot<TAgent>>>;
175
+ createAgentSession?: (
176
+ options: VisualAgentSessionOptions,
177
+ ) => Promise<VisualScenarioAgent<InferVisualScenarioSnapshot<TAgent>>>;
171
178
  }): Promise<VisualScenarioContext<TAgent>> => {
179
+ const { declaration } = await inspectGame({ gameId });
172
180
  const session = await openVisualHarnessSession({
181
+ inputModalities: declaration.metadata.inputModalities,
173
182
  browser,
174
183
  urls,
175
184
  mode,
@@ -224,6 +233,7 @@ const createScenarioRunContext = async <TAgent extends AnyAirJamAgentContract>({
224
233
  createAgentSession({
225
234
  gameId,
226
235
  scenarioId: scenario.id,
236
+ host: session.host,
227
237
  urls: session.urls,
228
238
  mode,
229
239
  secure,
@@ -250,6 +260,7 @@ const createScenarioRunContext = async <TAgent extends AnyAirJamAgentContract>({
250
260
  captureSurface({ surface: "host", viewportName, ...viewport }),
251
261
  captureController: async (viewportName: string, viewport: VisualViewport) =>
252
262
  captureSurface({ surface: "controller", viewportName, ...viewport }),
263
+ inputModalities: declaration.metadata.inputModalities,
253
264
  screenshotRecords,
254
265
  notes,
255
266
  close: async () => {
@@ -321,13 +332,9 @@ const runScenarioCapture = async <TAgent extends AnyAirJamAgentContract>({
321
332
  urls: Omit<VisualHarnessUrls, "controllerJoinUrl">;
322
333
  mode: VisualHarnessMode;
323
334
  secure: boolean;
324
- createAgentSession?: (options: {
325
- gameId: string;
326
- scenarioId: string;
327
- urls: VisualHarnessUrls;
328
- mode: VisualHarnessMode;
329
- secure: boolean;
330
- }) => Promise<VisualScenarioAgent<InferVisualScenarioSnapshot<TAgent>>>;
335
+ createAgentSession?: (
336
+ options: VisualAgentSessionOptions,
337
+ ) => Promise<VisualScenarioAgent<InferVisualScenarioSnapshot<TAgent>>>;
331
338
  }): Promise<VisualCaptureScenarioMetadata> => {
332
339
  const scenarioDir = path.join(artifactRoot, gameId, scenario.id);
333
340
  resetDir(scenarioDir);
@@ -432,13 +439,9 @@ export type RunVisualHarnessOptions = {
432
439
  mode: VisualHarnessMode;
433
440
  secure: boolean;
434
441
  }) => Promise<VisualHarnessStackHandle>;
435
- createAgentSession?: (options: {
436
- gameId: string;
437
- scenarioId: string;
438
- urls: VisualHarnessUrls;
439
- mode: VisualHarnessMode;
440
- secure: boolean;
441
- }) => Promise<VisualScenarioAgent<Record<string, unknown>>>;
442
+ createAgentSession?: (
443
+ options: VisualAgentSessionOptions,
444
+ ) => Promise<VisualScenarioAgent<Record<string, unknown>>>;
442
445
  onScenarioStart?: (scenario: VisualScenario<AnyAirJamAgentContract>) => void;
443
446
  onCaptureStart?: (info: {
444
447
  gameId: string;
@@ -0,0 +1,151 @@
1
+ import type { RuntimeInspectionContract } from "@air-jam/sdk/runtime-inspection";
2
+ import type { Browser } from "playwright-core";
3
+ import type { z } from "zod";
4
+ import {
5
+ AIR_JAM_RUNTIME_OWNER_CAPTURE_FRAME,
6
+ type runtimeOwnerCapturePortSchema,
7
+ type runtimeOwnerObservedControllerSchema,
8
+ } from "../../runtime-owner-protocol.js";
9
+ import { openControllerObservation } from "./controller-observation.js";
10
+
11
+ type ControllerObservation = Awaited<
12
+ ReturnType<typeof openControllerObservation>
13
+ >;
14
+ type Entry = {
15
+ opening?: Promise<ControllerObservation>;
16
+ observation?: ControllerObservation;
17
+ queued: number;
18
+ abort: AbortController;
19
+ pending: z.infer<typeof runtimeOwnerCapturePortSchema>[];
20
+ delivery: Promise<void>;
21
+ error?: unknown;
22
+ closing?: Promise<void>;
23
+ onError: (error: Error) => void;
24
+ };
25
+
26
+ /** How many room messages may wait for the page before the observation fails. */
27
+ const PENDING_DELIVERIES = 256;
28
+
29
+ // Both one-shot captures and live watching mirror existing players through this owner.
30
+ export class RuntimeControllerObservations {
31
+ private entries = new Map<string, Entry>();
32
+ constructor(
33
+ private readonly options: {
34
+ browser: Browser;
35
+ readInspection: () => Promise<RuntimeInspectionContract | null>;
36
+ send: (message: unknown) => void;
37
+ },
38
+ ) {}
39
+ async open(
40
+ requestId: string,
41
+ context: z.infer<typeof runtimeOwnerObservedControllerSchema>,
42
+ onError: Entry["onError"],
43
+ ) {
44
+ if (this.entries.has(requestId))
45
+ throw new Error("Controller observation already exists.");
46
+ const entry: Entry = {
47
+ queued: 0,
48
+ abort: new AbortController(),
49
+ pending: [],
50
+ delivery: Promise.resolve(),
51
+ onError,
52
+ };
53
+ this.entries.set(requestId, entry);
54
+ entry.opening = (async () => {
55
+ const inspection = await this.options.readInspection();
56
+ if (inspection?.role !== "host" || inspection.roomId !== context.roomId)
57
+ throw new Error("Observation belongs to another host room.");
58
+ const observation = await openControllerObservation({
59
+ browser: this.options.browser,
60
+ signal: entry.abort.signal,
61
+ controllerJoinUrl: inspection.joinUrl,
62
+ harnessSessionId: context.harnessSessionId,
63
+ roomId: context.roomId,
64
+ onPortMessage: (message) =>
65
+ this.options.send({
66
+ type: AIR_JAM_RUNTIME_OWNER_CAPTURE_FRAME,
67
+ requestId,
68
+ message,
69
+ }),
70
+ });
71
+ entry.observation = observation;
72
+ for (const event of entry.pending.splice(0)) this.deliver(event);
73
+ await observation.ready;
74
+ await entry.delivery;
75
+ if (entry.error) throw entry.error;
76
+ return observation;
77
+ })();
78
+ try {
79
+ return await entry.opening;
80
+ } catch (error) {
81
+ try {
82
+ await this.close(requestId);
83
+ } catch (cleanupError) {
84
+ throw new AggregateError(
85
+ [error, cleanupError],
86
+ "Controller observation failed and cleanup was not confirmed.",
87
+ );
88
+ }
89
+ throw error;
90
+ }
91
+ }
92
+ private fail(entry: Entry, error: unknown) {
93
+ if (entry.error) return;
94
+ entry.error = error;
95
+ entry.onError(error instanceof Error ? error : new Error(String(error)));
96
+ }
97
+ deliver(event: z.infer<typeof runtimeOwnerCapturePortSchema>) {
98
+ const entry = this.entries.get(event.requestId);
99
+ if (!entry || entry.error || entry.closing) return;
100
+ if (entry.pending.length + entry.queued >= PENDING_DELIVERIES) {
101
+ this.fail(
102
+ entry,
103
+ new Error("Controller observation event allowance exceeded."),
104
+ );
105
+ return;
106
+ }
107
+ if (!entry.observation) {
108
+ entry.pending.push(event);
109
+ return;
110
+ }
111
+ const observation = entry.observation;
112
+ entry.queued++;
113
+ entry.delivery = entry.delivery
114
+ .then(() => {
115
+ if (!entry.closing && !entry.error)
116
+ return observation.deliver(event.message);
117
+ })
118
+ .catch((error: unknown) => {
119
+ if (!entry.closing) this.fail(entry, error);
120
+ })
121
+ .finally(() => {
122
+ entry.queued--;
123
+ });
124
+ }
125
+ async close(requestId: string) {
126
+ const entry = this.entries.get(requestId);
127
+ if (!entry) return;
128
+ entry.abort.abort();
129
+ return (entry.closing ??= (async () => {
130
+ try {
131
+ await entry.opening?.catch(() => undefined);
132
+ await entry.observation?.close();
133
+ await entry.delivery;
134
+ } finally {
135
+ this.entries.delete(requestId);
136
+ }
137
+ })());
138
+ }
139
+
140
+ async closeAll() {
141
+ const results = await Promise.allSettled(
142
+ [...this.entries.keys()].map((id) => this.close(id)),
143
+ );
144
+ const failed = results.filter((result) => result.status === "rejected");
145
+ if (failed.length)
146
+ throw new AggregateError(
147
+ failed.map((result) => result.reason),
148
+ "Controller observation cleanup failed.",
149
+ );
150
+ }
151
+ }
@@ -1,9 +1,8 @@
1
- import type { AnyAirJamAgentContract } from "@air-jam/sdk";
1
+ import type { AnyAirJamAgentContract } from "@air-jam/sdk/core";
2
2
  import type { VisualScenario, VisualScenarioPack } from "./types.js";
3
3
 
4
4
  export const defineVisualScenarios = <
5
5
  TAgent extends AnyAirJamAgentContract,
6
6
  >(pack: {
7
- agent: TAgent;
8
7
  scenarios: ReadonlyArray<VisualScenario<TAgent>>;
9
8
  }): VisualScenarioPack<TAgent> => pack;
@@ -1,3 +1,4 @@
1
+ import { fixedControllerOrientation } from "@air-jam/sdk/metadata";
1
2
  import type { VisualScenarioContext, VisualViewport } from "./types.js";
2
3
 
3
4
  export const STANDARD_HOST_VIEWPORTS = [
@@ -27,7 +28,10 @@ export const captureStandardSurfaces = async (
27
28
  }
28
29
 
29
30
  await context.ensureControllerInteractive();
30
- const controllerOrientation = options?.controllerOrientation ?? "portrait";
31
+ const controllerOrientation =
32
+ fixedControllerOrientation(context.inputModalities ?? []) ??
33
+ options?.controllerOrientation ??
34
+ "portrait";
31
35
  const controllerViewports =
32
36
  controllerOrientation === "landscape"
33
37
  ? STANDARD_CONTROLLER_LANDSCAPE_VIEWPORTS
@@ -0,0 +1,155 @@
1
+ import type { Page } from "playwright-core";
2
+ import {
3
+ GAME_WATCH_HEARTBEAT_MS,
4
+ MAXIMUM_GAME_WATCH_FRAME_BASE64,
5
+ type GameRunWatchEvent,
6
+ } from "../../game-run-watch.js";
7
+
8
+ export function jpegDimensions(data: string) {
9
+ const bytes = Buffer.from(data, "base64");
10
+ if (bytes[0] !== 0xff || bytes[1] !== 0xd8)
11
+ throw new Error("Run watch received a non-JPEG frame.");
12
+ let offset = 2;
13
+ while (offset + 4 <= bytes.length) {
14
+ if (bytes[offset] !== 0xff) throw new Error("Invalid JPEG marker.");
15
+ const marker = bytes[offset + 1];
16
+ const length = bytes.readUInt16BE(offset + 2);
17
+ if (length < 2 || offset + 2 + length > bytes.length) break;
18
+ if ([0xc0, 0xc1, 0xc2].includes(marker)) {
19
+ if (length < 8) break;
20
+ return {
21
+ width: bytes.readUInt16BE(offset + 7),
22
+ height: bytes.readUInt16BE(offset + 5),
23
+ };
24
+ }
25
+ offset += length + 2;
26
+ }
27
+ throw new Error("Run watch JPEG dimensions are unavailable.");
28
+ }
29
+
30
+ export async function startGameScreencast({
31
+ page,
32
+ send,
33
+ onError,
34
+ onReady,
35
+ }: {
36
+ page: Page;
37
+ send: (event: GameRunWatchEvent, sent: (error: Error | null) => void) => void;
38
+ onError: (error: Error) => void;
39
+ onReady: (dimensions: { width: number; height: number }) => void;
40
+ }) {
41
+ const viewport = page.viewportSize();
42
+ if (!viewport)
43
+ throw new Error("Run watch requires an explicit capture viewport.");
44
+ const scale = Math.min(1, 1280 / Math.max(viewport.width, viewport.height));
45
+ const connection = await page.context().newCDPSession(page);
46
+ let closed = false;
47
+ let sending = false;
48
+ let pending: GameRunWatchEvent | undefined;
49
+ let heartbeat: GameRunWatchEvent | undefined;
50
+ let sequence = 0;
51
+ let lastFrameSeq: number | null = null;
52
+ const acknowledgements: number[] = [];
53
+ let acknowledgementTimer: ReturnType<typeof setTimeout> | undefined;
54
+ let heartbeatTimer: ReturnType<typeof setInterval> | undefined;
55
+ let nextAcknowledgementAt = 0;
56
+ const acknowledge = () => {
57
+ if (closed || acknowledgementTimer || !acknowledgements.length) return;
58
+ acknowledgementTimer = setTimeout(
59
+ () => {
60
+ acknowledgementTimer = undefined;
61
+ if (closed) return;
62
+ const sessionId = acknowledgements.shift();
63
+ if (sessionId === undefined) return;
64
+ nextAcknowledgementAt = performance.now() + 1000 / 15;
65
+ void connection
66
+ .send("Page.screencastFrameAck", { sessionId })
67
+ .then(acknowledge, (error: Error) => {
68
+ if (!closed) onError(error);
69
+ });
70
+ },
71
+ Math.max(0, nextAcknowledgementAt - performance.now()),
72
+ );
73
+ };
74
+ const flush = () => {
75
+ if (closed || sending) return;
76
+ const event = heartbeat ?? pending;
77
+ if (!event) return;
78
+ if (event.type === "frame") pending = undefined;
79
+ else heartbeat = undefined;
80
+ sending = true;
81
+ send(event, (error) => {
82
+ sending = false;
83
+ if (closed) return;
84
+ if (error) {
85
+ onError(error);
86
+ return;
87
+ }
88
+ flush();
89
+ });
90
+ };
91
+ const pageClosed = () => {
92
+ if (!closed) onError(new Error("Watched game surface closed."));
93
+ };
94
+ page.once("close", pageClosed);
95
+ connection.on("Page.screencastFrame", (frame) => {
96
+ if (closed) return;
97
+ if (acknowledgements.length >= 4) {
98
+ onError(new Error("Run watch capture flow control exceeded."));
99
+ return;
100
+ }
101
+ acknowledgements.push(frame.sessionId);
102
+ acknowledge();
103
+ try {
104
+ if (frame.data.length > MAXIMUM_GAME_WATCH_FRAME_BASE64)
105
+ throw new Error("Run watch frame exceeds its transfer allowance.");
106
+ if (frame.metadata.timestamp === undefined)
107
+ throw new Error("Run watch frame is missing its capture timestamp.");
108
+ if (sequence === 0) {
109
+ onReady(jpegDimensions(frame.data));
110
+ heartbeatTimer = setInterval(() => {
111
+ heartbeat = { type: "heartbeat", at: Date.now(), lastFrameSeq };
112
+ flush();
113
+ }, GAME_WATCH_HEARTBEAT_MS);
114
+ }
115
+ lastFrameSeq = sequence++;
116
+ pending = {
117
+ type: "frame",
118
+ seq: lastFrameSeq,
119
+ capturedAt: frame.metadata.timestamp * 1000,
120
+ data: frame.data,
121
+ };
122
+ flush();
123
+ } catch (error) {
124
+ onError(error instanceof Error ? error : new Error(String(error)));
125
+ }
126
+ });
127
+ const close = async () => {
128
+ if (closed) return;
129
+ closed = true;
130
+ clearInterval(heartbeatTimer);
131
+ clearTimeout(acknowledgementTimer);
132
+ acknowledgements.length = 0;
133
+ pending = undefined;
134
+ heartbeat = undefined;
135
+ page.off("close", pageClosed);
136
+ try {
137
+ await connection.detach();
138
+ } catch (error) {
139
+ if (!page.isClosed()) throw error;
140
+ }
141
+ };
142
+ try {
143
+ await connection.send("Page.startScreencast", {
144
+ format: "jpeg",
145
+ quality: 75,
146
+ maxWidth: Math.floor(viewport.width * scale),
147
+ maxHeight: Math.floor(viewport.height * scale),
148
+ everyNthFrame: 1,
149
+ });
150
+ return { close };
151
+ } catch (error) {
152
+ await close();
153
+ throw error;
154
+ }
155
+ }