@air-jam/devtools 0.9.3 → 1.0.0-beta.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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-GUEZP773.js → chunk-LB3Y64P5.js} +206 -60
  33. package/dist/chunk-LB3Y64P5.js.map +1 -0
  34. package/dist/chunk-M6CJ7GQC.js +133 -0
  35. package/dist/chunk-M6CJ7GQC.js.map +1 -0
  36. package/dist/{chunk-CKFT2ZJE.js → chunk-MEIMOSZC.js} +53 -105
  37. package/dist/chunk-MEIMOSZC.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 +770 -68
  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 +288 -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 +74 -69
  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 +254 -42
  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 +329 -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,166 @@
1
+ import {
2
+ hostAgentResultMessageSchema,
3
+ type HostAgentRequest,
4
+ type HostAgentResponse,
5
+ } from "@air-jam/sdk/runtime-control";
6
+ import { BodyLimitError, readBoundedText } from "./bounded-response.js";
7
+ import {
8
+ currentRoomHostRequestSchema,
9
+ currentRoomSeatClaimSchema,
10
+ type CurrentRoomAttachment,
11
+ type CurrentRoomSeatClaim,
12
+ } from "./game-run-protocol.js";
13
+
14
+ const MAXIMUM_RESPONSE_BYTES = 2 * 1024 * 1024;
15
+
16
+ export class CurrentRoomStopped extends Error {}
17
+
18
+ /**
19
+ * The creator's host, reached through the editor that granted the room. The
20
+ * endpoint is an ephemeral delegation, never part of a run record or trace.
21
+ */
22
+ export function currentRoomHost(
23
+ attachment: CurrentRoomAttachment,
24
+ ownerInstanceId: string,
25
+ ): (
26
+ request: HostAgentRequest,
27
+ timeoutMs: number,
28
+ signal?: AbortSignal,
29
+ ) => Promise<HostAgentResponse> {
30
+ return async (request, timeoutMs, signal) => {
31
+ const input = currentRoomHostRequestSchema.parse({
32
+ targetId: attachment.host.targetId,
33
+ ownerInstanceId,
34
+ request,
35
+ });
36
+ const deadline = AbortSignal.timeout(timeoutMs);
37
+ let response: Response;
38
+ try {
39
+ response = await fetch(attachment.host.endpoint, {
40
+ method: "POST",
41
+ headers: { "content-type": "application/json" },
42
+ body: JSON.stringify(input),
43
+ signal: signal ? AbortSignal.any([signal, deadline]) : deadline,
44
+ redirect: "error",
45
+ credentials: "omit",
46
+ });
47
+ } catch {
48
+ throw new Error(
49
+ "current_host_unavailable: The creator's editor could not be reached.",
50
+ );
51
+ }
52
+ if (!response.ok) {
53
+ if ([401, 403, 409, 410].includes(response.status)) {
54
+ let message = "The creator's room is no longer granted.";
55
+ try {
56
+ if (response.body) {
57
+ const body = JSON.parse(await readBoundedText(response.body, 4096));
58
+ if (typeof body?.error === "string" && body.error.trim())
59
+ message = body.error.trim().slice(0, 300);
60
+ }
61
+ } catch {
62
+ // Missing, invalid or oversized refusal bodies use the generic cause.
63
+ }
64
+ if (response.status === 410) throw new CurrentRoomStopped(message);
65
+ throw new Error(`runtime_replaced: ${message}`);
66
+ }
67
+ await response.body?.cancel();
68
+ throw new Error(
69
+ `current_host_unavailable: The editor returned HTTP ${response.status}.`,
70
+ );
71
+ }
72
+ if (!response.body)
73
+ throw new Error("current_host_invalid: Empty host response.");
74
+ let source: string;
75
+ try {
76
+ source = await readBoundedText(response.body, MAXIMUM_RESPONSE_BYTES);
77
+ } catch (error) {
78
+ throw new Error(
79
+ error instanceof BodyLimitError
80
+ ? "current_host_limit: The creator's host exceeded its transfer budget."
81
+ : "current_host_unavailable: Host response transfer failed.",
82
+ );
83
+ }
84
+ let result;
85
+ try {
86
+ result = hostAgentResultMessageSchema.shape.result.parse(
87
+ JSON.parse(source),
88
+ );
89
+ } catch {
90
+ throw new Error(
91
+ "current_host_invalid: The creator's host response failed validation.",
92
+ );
93
+ }
94
+ if (!result.ok) throw new Error(result.error);
95
+ const answer = result.response;
96
+ if (answer.operation !== request.operation)
97
+ throw new Error(
98
+ "current_host_invalid: The creator's host answered another request.",
99
+ );
100
+ if (
101
+ answer.operation === "observe" &&
102
+ request.operation === "observe" &&
103
+ (answer.observation.identity.roomId !== request.roomId ||
104
+ answer.observation.controllerId !== request.controllerId ||
105
+ answer.observation.scope !== request.scope ||
106
+ (request.expected &&
107
+ Object.entries(request.expected).some(
108
+ ([key, value]) =>
109
+ Reflect.get(answer.observation.identity, key) !== value,
110
+ )))
111
+ )
112
+ throw new Error(
113
+ "runtime_replaced: The observation belongs to another runtime or player.",
114
+ );
115
+ return answer;
116
+ };
117
+ }
118
+
119
+ /**
120
+ * Claims, through the editor that granted the room, a seat one of the run's
121
+ * players joined. The editor accepts it only for a seat its room shows as
122
+ * an agent's, unclaimed and within the run's count.
123
+ */
124
+ export function currentRoomSeatClaimer(
125
+ attachment: CurrentRoomAttachment,
126
+ ownerInstanceId: string,
127
+ ): (claim: CurrentRoomSeatClaim, timeoutMs: number) => Promise<void> {
128
+ return async (claim, timeoutMs) => {
129
+ const body = currentRoomSeatClaimSchema.parse({
130
+ targetId: attachment.host.targetId,
131
+ ownerInstanceId,
132
+ claim,
133
+ });
134
+ let response: Response;
135
+ try {
136
+ response = await fetch(attachment.host.endpoint, {
137
+ method: "POST",
138
+ headers: { "content-type": "application/json" },
139
+ body: JSON.stringify(body),
140
+ signal: AbortSignal.timeout(timeoutMs),
141
+ redirect: "error",
142
+ credentials: "omit",
143
+ });
144
+ } catch {
145
+ throw new Error(
146
+ "current_host_unavailable: The creator's editor could not be reached.",
147
+ );
148
+ }
149
+ if (response.ok) {
150
+ await response.body?.cancel();
151
+ return;
152
+ }
153
+ let message = `The editor refused the seat (HTTP ${response.status}).`;
154
+ try {
155
+ if (response.body) {
156
+ const refusal = JSON.parse(await readBoundedText(response.body, 4096));
157
+ if (typeof refusal?.error === "string" && refusal.error.trim())
158
+ message = refusal.error.trim().slice(0, 300);
159
+ }
160
+ } catch {
161
+ // Missing, invalid or oversized refusal bodies keep the generic cause.
162
+ }
163
+ if (response.status === 410) throw new CurrentRoomStopped(message);
164
+ throw new Error(`current_room_scope: ${message}`);
165
+ };
166
+ }
@@ -0,0 +1,102 @@
1
+ import { z } from "zod";
2
+ import { readBoundedText } from "./bounded-response.js";
3
+ import type { AirJamDecisionQuestion } from "./testing.js";
4
+
5
+ export type DecisionAnswer = { choice: string; confidence: number };
6
+ /** The run's decision model, named so every answer can be tied to it. */
7
+ export type DecisionProvider = {
8
+ model: string;
9
+ ask: (
10
+ question: AirJamDecisionQuestion,
11
+ signal: AbortSignal,
12
+ ) => Promise<DecisionAnswer>;
13
+ };
14
+
15
+ const MAX_RESPONSE_BYTES = 262_144;
16
+ const responseSchema = z.object({
17
+ answers: z.object({
18
+ decision: z.looseObject({
19
+ choice: z.string().min(1),
20
+ confidence: z.number().min(0).max(1),
21
+ }),
22
+ }),
23
+ });
24
+
25
+ const DECISION_VARIABLES = [
26
+ "AIRJAM_DECISIONS_ENDPOINT",
27
+ "AIRJAM_DECISIONS_MODEL",
28
+ "AIRJAM_DECISIONS_TOKEN",
29
+ ] as const;
30
+
31
+ /**
32
+ * A typed decision model reached through the Decisions API shape these models
33
+ * share (OpenRouter's, which Jev serves). The run owner takes its settings out
34
+ * of its own environment before starting anything, so no build, game or policy
35
+ * process it spawns can read the credential; Studio instead points the endpoint
36
+ * at a gateway that adds the credential itself.
37
+ */
38
+ export function takeDecisionProviderFromEnvironment(
39
+ environment: NodeJS.ProcessEnv = process.env,
40
+ ): DecisionProvider | undefined {
41
+ const [endpoint, model, token] = DECISION_VARIABLES.map((name) => {
42
+ const value = environment[name]?.trim();
43
+ delete environment[name];
44
+ return value;
45
+ });
46
+ if (!endpoint) return undefined;
47
+ if (!model)
48
+ throw new Error(
49
+ "Configure AIRJAM_DECISIONS_MODEL alongside AIRJAM_DECISIONS_ENDPOINT.",
50
+ );
51
+ const url = new URL(endpoint);
52
+ const ask: DecisionProvider["ask"] = async (question, signal) => {
53
+ const options = Object.entries(question.options);
54
+ const choices = new Map(
55
+ options.map(([name], index) => [`option_${index}`, name]),
56
+ );
57
+ const response = await fetch(url, {
58
+ method: "POST",
59
+ headers: {
60
+ "content-type": "application/json",
61
+ ...(token ? { authorization: `Bearer ${token}` } : {}),
62
+ },
63
+ body: JSON.stringify({
64
+ model,
65
+ state: question.state,
66
+ questions: {
67
+ decision: {
68
+ type: "choice",
69
+ instructions: question.question,
70
+ criteria: Object.fromEntries(
71
+ options.map(([, { when }], index) => [`option_${index}`, when]),
72
+ ),
73
+ },
74
+ },
75
+ }),
76
+ signal,
77
+ redirect: "error",
78
+ });
79
+ if (!response.ok) {
80
+ await response.body?.cancel();
81
+ throw new Error(`Decision model returned HTTP ${response.status}.`);
82
+ }
83
+ const parsed = responseSchema.safeParse(
84
+ JSON.parse(
85
+ response.body
86
+ ? await readBoundedText(response.body, MAX_RESPONSE_BYTES)
87
+ : "null",
88
+ ),
89
+ );
90
+ if (!parsed.success) throw new Error("Decision model returned no choice.");
91
+ const choice = choices.get(parsed.data.answers.decision.choice);
92
+ if (choice === undefined)
93
+ throw new Error(
94
+ `Decision model returned unknown choice ${JSON.stringify(parsed.data.answers.decision.choice)}.`,
95
+ );
96
+ return {
97
+ choice,
98
+ confidence: parsed.data.answers.decision.confidence,
99
+ };
100
+ };
101
+ return { model, ask };
102
+ }
@@ -0,0 +1,176 @@
1
+ import crossSpawn from "cross-spawn";
2
+ import { rm } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { createInterface } from "node:readline";
5
+ import { z } from "zod";
6
+ import { dependencyInstallObservationSchema } from "./dependency-install-contract.js";
7
+
8
+ const eventSchema = z.object({
9
+ name: z.string().optional(),
10
+ packageId: z.string().optional(),
11
+ status: z.string().optional(),
12
+ stage: z.string().optional(),
13
+ method: z.string().optional(),
14
+ added: z.number().int().optional(),
15
+ level: z.string().optional(),
16
+ });
17
+
18
+ export class DependencyInstallObservation {
19
+ private packages = new Map<string, Set<string>>();
20
+ private started = performance.now();
21
+ private stages: z.infer<typeof dependencyInstallObservationSchema>["stages"] =
22
+ [];
23
+ private added = 0;
24
+ private importMethods = new Set<string>();
25
+ private errors = "";
26
+ accept(line: string) {
27
+ let value: unknown;
28
+ try {
29
+ value = JSON.parse(line);
30
+ } catch {
31
+ this.errors = (this.errors + "\n" + line).slice(-16_384);
32
+ return;
33
+ }
34
+ const parsed = eventSchema.safeParse(value);
35
+ if (!parsed.success) return;
36
+ const event = parsed.data;
37
+ if (
38
+ event.method &&
39
+ (event.name === "pnpm:package-import-method" ||
40
+ (event.name === "pnpm:progress" && event.status === "imported"))
41
+ )
42
+ this.importMethods.add(event.method);
43
+ if (event.name === "pnpm:progress" && event.packageId && event.status) {
44
+ const states = this.packages.get(event.packageId) ?? new Set<string>();
45
+ states.add(event.status);
46
+ this.packages.set(event.packageId, states);
47
+ }
48
+ if (
49
+ event.name === "pnpm:stage" &&
50
+ event.stage &&
51
+ ["importing_started", "importing_done"].includes(event.stage)
52
+ )
53
+ this.stages.push({
54
+ stage: event.stage,
55
+ offsetMs: performance.now() - this.started,
56
+ });
57
+ if (
58
+ event.name === "pnpm:stats" &&
59
+ event.added !== undefined &&
60
+ Number.isSafeInteger(event.added)
61
+ )
62
+ this.added = event.added;
63
+ if (event.level === "error")
64
+ this.errors = (this.errors + "\n" + line).slice(-16_384);
65
+ }
66
+ failure(exitCode: number | null, signal: NodeJS.Signals | null = null) {
67
+ return new Error(
68
+ `Dependency installation failed (exit=${exitCode}, signal=${signal}): ${JSON.stringify(this.finish())}${this.errors}`,
69
+ );
70
+ }
71
+ finish() {
72
+ const count = (status: string) =>
73
+ [...this.packages.values()].filter((states) => states.has(status)).length;
74
+ return dependencyInstallObservationSchema.parse({
75
+ durationMs: performance.now() - this.started,
76
+ packageCount: this.packages.size,
77
+ reused: count("found_in_store"),
78
+ downloaded: count("fetched"),
79
+ added: this.added,
80
+ stages: this.stages,
81
+ importMethods: [...this.importMethods].sort(),
82
+ });
83
+ }
84
+ assertIndependentImports() {
85
+ if (this.added > 0 && this.importMethods.size === 0)
86
+ throw new Error(
87
+ "Dependency installation did not report its import method.",
88
+ );
89
+ if (
90
+ [...this.importMethods].some(
91
+ (method) => method !== "copy" && method !== "clone",
92
+ )
93
+ )
94
+ throw new Error(
95
+ `Dependency installation requires independent copies; pnpm reported ${[...this.importMethods].join(", ")}.`,
96
+ );
97
+ }
98
+ }
99
+
100
+ /** Workspace preparation, explicit upgrades and pinned tests share one installer. */
101
+ export async function installDependencies(
102
+ directory: string,
103
+ options: {
104
+ signal?: AbortSignal;
105
+ network?: "online" | "prefer-offline" | "offline";
106
+ lockfile?: "frozen" | "update";
107
+ scripts?: "run" | "ignore";
108
+ packageImportMethod?: "copy" | "clone-or-copy";
109
+ } = {},
110
+ ) {
111
+ options.signal?.throwIfAborted();
112
+ const observation = new DependencyInstallObservation();
113
+ const child = crossSpawn(
114
+ "pnpm",
115
+ [
116
+ "install",
117
+ options.lockfile === "update"
118
+ ? "--no-frozen-lockfile"
119
+ : "--frozen-lockfile",
120
+ "--reporter=ndjson",
121
+ `--package-import-method=${options.packageImportMethod ?? "copy"}`,
122
+ ...(options.scripts === "ignore" ? ["--ignore-scripts"] : []),
123
+ ...(options.network && options.network !== "online"
124
+ ? [`--${options.network}`]
125
+ : []),
126
+ ],
127
+ {
128
+ cwd: directory,
129
+ stdio: ["ignore", "pipe", "pipe"],
130
+ signal: options.signal,
131
+ killSignal: "SIGKILL",
132
+ },
133
+ );
134
+ if (!child.stderr || !child.stdout)
135
+ throw new Error("The dependency installer requires piped output.");
136
+ const output = [child.stdout, child.stderr].map((input) =>
137
+ createInterface({ input }),
138
+ );
139
+ const reading = Promise.all(
140
+ output.map(async (reader) => {
141
+ for await (const line of reader) observation.accept(line);
142
+ }),
143
+ );
144
+ const finished = new Promise<{
145
+ exitCode: number | null;
146
+ signal: NodeJS.Signals | null;
147
+ }>((resolve, reject) => {
148
+ child.once("error", reject);
149
+ child.once("close", (exitCode, signal) => resolve({ exitCode, signal }));
150
+ });
151
+ const closed = new Promise<void>((resolve) =>
152
+ child.once("close", () => resolve()),
153
+ );
154
+ try {
155
+ const [{ exitCode, signal }] = await Promise.all([finished, reading]);
156
+ if (exitCode !== 0) throw observation.failure(exitCode, signal);
157
+ observation.assertIndependentImports();
158
+ return observation.finish();
159
+ } catch (error) {
160
+ child.kill("SIGKILL");
161
+ await closed;
162
+ const failure = options.signal?.aborted
163
+ ? new Error(
164
+ observation.failure(child.exitCode, child.signalCode).message,
165
+ { cause: error },
166
+ )
167
+ : error;
168
+ await rm(path.join(directory, "node_modules"), {
169
+ recursive: true,
170
+ force: true,
171
+ });
172
+ throw failure;
173
+ } finally {
174
+ for (const reader of output) reader.close();
175
+ }
176
+ }
@@ -0,0 +1,12 @@
1
+ import { z } from "zod";
2
+ export const dependencyInstallObservationSchema = z.object({
3
+ durationMs: z.number().nonnegative(),
4
+ packageCount: z.number().int().nonnegative(),
5
+ reused: z.number().int().nonnegative(),
6
+ downloaded: z.number().int().nonnegative(),
7
+ added: z.number().int().nonnegative(),
8
+ importMethods: z.array(z.string()).optional(),
9
+ stages: z.array(
10
+ z.object({ stage: z.string(), offsetMs: z.number().nonnegative() }),
11
+ ),
12
+ });
package/src/dev.ts CHANGED
@@ -1,3 +1,7 @@
1
+ import {
2
+ parseRuntimeTopology,
3
+ runtimeTopologyToQueryParams,
4
+ } from "@air-jam/sdk/runtime-topology";
1
5
  import crossSpawn from "cross-spawn";
2
6
  import { randomUUID } from "node:crypto";
3
7
  import { closeSync, openSync } from "node:fs";
@@ -334,31 +338,6 @@ const resolveWorkspaceCliPath = (context: AirJamProjectContext): string => {
334
338
  return path.resolve(context.rootDir, workspace.cli);
335
339
  };
336
340
 
337
- const resolveRequestedGameId = async ({
338
- cwd,
339
- context,
340
- gameId,
341
- }: {
342
- cwd: string;
343
- context: AirJamProjectContext;
344
- gameId?: string;
345
- }): Promise<string | null> => {
346
- if (context.mode === "standalone-game") {
347
- return (await inspectGame({ cwd, gameId })).id;
348
- }
349
-
350
- if (context.mode !== "monorepo") {
351
- return null;
352
- }
353
-
354
- if (gameId) {
355
- return gameId;
356
- }
357
-
358
- const games = await listGames({ cwd });
359
- return games[0]?.id ?? null;
360
- };
361
-
362
341
  const resolveStartCommand = async ({
363
342
  context,
364
343
  cwd,
@@ -514,6 +493,20 @@ const joinUrl = (origin: string | null, pathname: string): string | null => {
514
493
  return new URL(pathname, origin).toString();
515
494
  };
516
495
 
496
+ const topologySurfaceUrl = (
497
+ origin: string,
498
+ pathname: string,
499
+ surface: JsonObject,
500
+ ): string => {
501
+ const url = new URL(pathname, origin);
502
+ const topology = parseRuntimeTopology(JSON.stringify(surface));
503
+ for (const [key, value] of Object.entries(
504
+ runtimeTopologyToQueryParams(topology),
505
+ ))
506
+ url.searchParams.set(key, value);
507
+ return url.toString();
508
+ };
509
+
517
510
  const buildUrlSummary = ({
518
511
  mode,
519
512
  gameId,
@@ -538,8 +531,16 @@ const buildUrlSummary = ({
538
531
 
539
532
  return {
540
533
  appOrigin: hostOrigin,
541
- hostUrl: hostOrigin,
542
- controllerBaseUrl: joinUrl(controllerOrigin, controllerPath),
534
+ hostUrl: hostOrigin
535
+ ? topologySurfaceUrl(hostOrigin, "/", hostSurface)
536
+ : null,
537
+ controllerBaseUrl: controllerOrigin
538
+ ? topologySurfaceUrl(
539
+ controllerOrigin,
540
+ controllerPath,
541
+ controllerSurface,
542
+ )
543
+ : null,
543
544
  publicHost,
544
545
  localBuildUrl: null,
545
546
  browserBuildUrl: null,
@@ -680,7 +681,10 @@ export const getDevStatus = async ({
680
681
  const context = await detectProjectContext({ cwd });
681
682
  const managedProcesses = await listManagedProcessesForRoot(context.rootDir);
682
683
  const managedPids = new Set(managedProcesses.map((entry) => entry.pid));
684
+ const { getGameSessionBrokerStatus } =
685
+ await import("./game-session-broker.js");
683
686
  return {
687
+ gameSessionBroker: await getGameSessionBrokerStatus(context.rootDir),
684
688
  processes: managedProcesses,
685
689
  unmanagedProcesses: listKnownPortListeners().filter(
686
690
  (entry) => !managedPids.has(entry.pid),
@@ -703,16 +707,13 @@ export const getTopology = async ({
703
707
  );
704
708
  }
705
709
 
706
- const resolvedGameId = await resolveRequestedGameId({
707
- cwd,
708
- context,
709
- gameId,
710
- });
711
710
  const game =
712
- resolvedGameId !== null
713
- ? await inspectGame({ cwd, gameId: resolvedGameId })
714
- : null;
715
- const controllerPath = game?.controllerPathLikely ?? DEFAULT_CONTROLLER_PATH;
711
+ context.mode === "standalone-game" || gameId
712
+ ? await inspectGame({ cwd, gameId })
713
+ : ((await listGames({ cwd }))[0] ?? null);
714
+ const resolvedGameId = game?.id ?? null;
715
+ const controllerPath =
716
+ game?.declaration.controllerPath ?? DEFAULT_CONTROLLER_PATH;
716
717
  const topologyCommand = await resolveTopologyCommand({
717
718
  context,
718
719
  gameId: resolvedGameId,
@@ -775,11 +776,13 @@ export const startDev = async ({
775
776
  );
776
777
  }
777
778
 
778
- const resolvedGameId = await resolveRequestedGameId({
779
+ const topology = await getTopology({
779
780
  cwd,
780
- context,
781
781
  gameId,
782
+ mode,
783
+ secure,
782
784
  });
785
+ const resolvedGameId = topology.gameId;
783
786
  const existingProcesses = await listManagedProcessesForRoot(context.rootDir);
784
787
  const exactMatch =
785
788
  existingProcesses.find(
@@ -792,12 +795,7 @@ export const startDev = async ({
792
795
  return {
793
796
  process: exactMatch,
794
797
  reusedExistingProcess: true,
795
- topology: await getTopology({
796
- cwd: context.rootDir,
797
- gameId: resolvedGameId ?? undefined,
798
- mode,
799
- secure,
800
- }),
798
+ topology,
801
799
  };
802
800
  }
803
801
 
@@ -883,12 +881,7 @@ export const startDev = async ({
883
881
  });
884
882
 
885
883
  try {
886
- const topology = await getTopology({
887
- cwd: context.rootDir,
888
- gameId: resolvedGameId ?? undefined,
889
- mode,
890
- secure,
891
- });
884
+ topology.process = managedProcess;
892
885
  await Promise.race([
893
886
  waitForTopologyReady({ topology }),
894
887
  childExited.then(({ code, signal }) => {
@@ -960,6 +953,8 @@ export const resetLocalDev = async ({
960
953
  cwd = process.cwd(),
961
954
  }: ResetLocalDevOptions = {}): Promise<ResetLocalDevResult> => {
962
955
  const context = await detectProjectContext({ cwd });
956
+ const { stopGameSessionBroker } = await import("./game-session-broker.js");
957
+ const gameSessionBroker = await stopGameSessionBroker(context.rootDir);
963
958
  const stoppedManaged = (await stopDev({ cwd: context.rootDir })).stopped;
964
959
  const managedPids = new Set(stoppedManaged.map((entry) => entry.pid));
965
960
  const unmanaged = listKnownPortListeners().filter(
@@ -991,6 +986,7 @@ export const resetLocalDev = async ({
991
986
  );
992
987
 
993
988
  return {
989
+ gameSessionBroker,
994
990
  stoppedManaged,
995
991
  stoppedUnmanaged,
996
992
  remainingUnmanaged,
@@ -41,9 +41,19 @@ export const computeGameSnapshotObservation = ({
41
41
  }): {
42
42
  snapshotAfterStatus:
43
43
  | "committed-update-observed"
44
- | "no-new-commit-before-timeout";
44
+ | "no-new-commit-before-timeout"
45
+ | "contract_changed"
46
+ | "runtime_replaced";
45
47
  observedStateChange: boolean;
46
48
  } => {
49
+ const replaced =
50
+ snapshotBefore.runtimeId !== snapshotAfter.runtimeId
51
+ ? "runtime_replaced"
52
+ : snapshotBefore.contractId !== snapshotAfter.contractId
53
+ ? "contract_changed"
54
+ : null;
55
+ if (replaced)
56
+ return { snapshotAfterStatus: replaced, observedStateChange: false };
47
57
  const fingerprintBefore = stableStoreSnapshotFingerprint(snapshotBefore);
48
58
  const fingerprintAfter = stableStoreSnapshotFingerprint(snapshotAfter);
49
59
  const dataFingerprintBefore =