@air-jam/devtools 0.0.0-stage → 1.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (256) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +112 -2
  3. package/dist/chunk-2O67AXCU.js +470 -0
  4. package/dist/chunk-2O67AXCU.js.map +1 -0
  5. package/dist/chunk-AO3ZDXF6.js +142 -0
  6. package/dist/chunk-AO3ZDXF6.js.map +1 -0
  7. package/dist/chunk-ART5TEYT.js +472 -0
  8. package/dist/chunk-ART5TEYT.js.map +1 -0
  9. package/dist/chunk-ASC2CK2R.js +77 -0
  10. package/dist/chunk-ASC2CK2R.js.map +1 -0
  11. package/dist/chunk-E3UZZGAV.js +50 -0
  12. package/dist/chunk-E3UZZGAV.js.map +1 -0
  13. package/dist/chunk-EJTE7UKX.js +64 -0
  14. package/dist/chunk-EJTE7UKX.js.map +1 -0
  15. package/dist/chunk-ESFKNN75.js +110 -0
  16. package/dist/chunk-ESFKNN75.js.map +1 -0
  17. package/dist/chunk-EU7A6PXW.js +1339 -0
  18. package/dist/chunk-EU7A6PXW.js.map +1 -0
  19. package/dist/chunk-FN7E6EA7.js +549 -0
  20. package/dist/chunk-FN7E6EA7.js.map +1 -0
  21. package/dist/chunk-GDFAWHGA.js +190 -0
  22. package/dist/chunk-GDFAWHGA.js.map +1 -0
  23. package/dist/chunk-HZUGBH4Y.js +347 -0
  24. package/dist/chunk-HZUGBH4Y.js.map +1 -0
  25. package/dist/chunk-ITKAOEGX.js +93 -0
  26. package/dist/chunk-ITKAOEGX.js.map +1 -0
  27. package/dist/chunk-JBCUTWRI.js +897 -0
  28. package/dist/chunk-JBCUTWRI.js.map +1 -0
  29. package/dist/chunk-JSI5S4WP.js +1174 -0
  30. package/dist/chunk-JSI5S4WP.js.map +1 -0
  31. package/dist/chunk-L4D675BG.js +97 -0
  32. package/dist/chunk-L4D675BG.js.map +1 -0
  33. package/dist/chunk-M6CJ7GQC.js +133 -0
  34. package/dist/chunk-M6CJ7GQC.js.map +1 -0
  35. package/dist/chunk-MEIMOSZC.js +749 -0
  36. package/dist/chunk-MEIMOSZC.js.map +1 -0
  37. package/dist/chunk-O3XG3FNL.js +1014 -0
  38. package/dist/chunk-O3XG3FNL.js.map +1 -0
  39. package/dist/chunk-OM6SCJ7H.js +18 -0
  40. package/dist/chunk-OM6SCJ7H.js.map +1 -0
  41. package/dist/chunk-PKD4WVX5.js +63 -0
  42. package/dist/chunk-PKD4WVX5.js.map +1 -0
  43. package/dist/chunk-PMBLXGFM.js +3384 -0
  44. package/dist/chunk-PMBLXGFM.js.map +1 -0
  45. package/dist/chunk-PMNE5GIN.js +279 -0
  46. package/dist/chunk-PMNE5GIN.js.map +1 -0
  47. package/dist/chunk-QAWI64VR.js +148 -0
  48. package/dist/chunk-QAWI64VR.js.map +1 -0
  49. package/dist/chunk-QGADSPHZ.js +449 -0
  50. package/dist/chunk-QGADSPHZ.js.map +1 -0
  51. package/dist/chunk-SPYN66UV.js +338 -0
  52. package/dist/chunk-SPYN66UV.js.map +1 -0
  53. package/dist/context.d.ts +19 -0
  54. package/dist/context.js +10 -0
  55. package/dist/context.js.map +1 -0
  56. package/dist/controller.d.ts +67 -0
  57. package/dist/controller.js +40 -0
  58. package/dist/controller.js.map +1 -0
  59. package/dist/dependencies.d.ts +44 -0
  60. package/dist/dependencies.js +10 -0
  61. package/dist/dependencies.js.map +1 -0
  62. package/dist/dev.d.ts +21 -0
  63. package/dist/dev.js +19 -0
  64. package/dist/dev.js.map +1 -0
  65. package/dist/game-builds.d.ts +200 -0
  66. package/dist/game-builds.js +16 -0
  67. package/dist/game-builds.js.map +1 -0
  68. package/dist/game-run-watch-CEd_SpAT.d.ts +84 -0
  69. package/dist/game-runs.d.ts +1452 -0
  70. package/dist/game-runs.js +76 -0
  71. package/dist/game-runs.js.map +1 -0
  72. package/dist/game-session-broker-CUvORfMd.d.ts +439 -0
  73. package/dist/game-session-broker.d.ts +4 -0
  74. package/dist/game-session-broker.js +40 -0
  75. package/dist/game-session-broker.js.map +1 -0
  76. package/dist/game-session.d.ts +3934 -0
  77. package/dist/game-session.js +195 -0
  78. package/dist/game-session.js.map +1 -0
  79. package/dist/game-settings.d.ts +16 -0
  80. package/dist/game-settings.js +237 -0
  81. package/dist/game-settings.js.map +1 -0
  82. package/dist/games.d.ts +28 -0
  83. package/dist/games.js +16 -0
  84. package/dist/games.js.map +1 -0
  85. package/dist/harness/visual.d.ts +204 -0
  86. package/dist/harness/visual.js +46 -0
  87. package/dist/harness/visual.js.map +1 -0
  88. package/dist/logs.d.ts +15 -0
  89. package/dist/logs.js +57 -0
  90. package/dist/logs.js.map +1 -0
  91. package/dist/managed-process-scope-BicYi_t9.d.ts +3 -0
  92. package/dist/mcp-config.d.ts +63 -0
  93. package/dist/mcp-config.js +191 -0
  94. package/dist/mcp-config.js.map +1 -0
  95. package/dist/platform-auth.d.ts +9 -0
  96. package/dist/platform-auth.js +45 -0
  97. package/dist/platform-auth.js.map +1 -0
  98. package/dist/platform-game-analytics.d.ts +51 -0
  99. package/dist/platform-game-analytics.js +49 -0
  100. package/dist/platform-game-analytics.js.map +1 -0
  101. package/dist/platform-game-app-id.d.ts +46 -0
  102. package/dist/platform-game-app-id.js +93 -0
  103. package/dist/platform-game-app-id.js.map +1 -0
  104. package/dist/platform-game-media.d.ts +347 -0
  105. package/dist/platform-game-media.js +168 -0
  106. package/dist/platform-game-media.js.map +1 -0
  107. package/dist/platform-games.d.ts +87 -0
  108. package/dist/platform-games.js +183 -0
  109. package/dist/platform-games.js.map +1 -0
  110. package/dist/quality.d.ts +16 -0
  111. package/dist/quality.js +62 -0
  112. package/dist/quality.js.map +1 -0
  113. package/dist/release.d.ts +1304 -0
  114. package/dist/release.js +34 -0
  115. package/dist/release.js.map +1 -0
  116. package/dist/rooms-check.d.ts +90 -0
  117. package/dist/rooms-check.js +717 -0
  118. package/dist/rooms-check.js.map +1 -0
  119. package/dist/source-tree-contract.d.ts +16 -0
  120. package/dist/source-tree-contract.js +13 -0
  121. package/dist/source-tree-contract.js.map +1 -0
  122. package/dist/testing.d.ts +464 -0
  123. package/dist/testing.js +27 -0
  124. package/dist/testing.js.map +1 -0
  125. package/dist/tooling/describe-game.d.ts +2 -0
  126. package/dist/tooling/describe-game.js +54 -0
  127. package/dist/tooling/describe-game.js.map +1 -0
  128. package/dist/tooling/game-session-broker.d.ts +2 -0
  129. package/dist/tooling/game-session-broker.js +28 -0
  130. package/dist/tooling/game-session-broker.js.map +1 -0
  131. package/dist/tooling/hold-runtime-host.d.ts +2 -0
  132. package/dist/tooling/hold-runtime-host.js +931 -0
  133. package/dist/tooling/hold-runtime-host.js.map +1 -0
  134. package/dist/tooling/list-visual-scenarios.d.ts +2 -0
  135. package/dist/tooling/list-visual-scenarios.js +25 -0
  136. package/dist/tooling/list-visual-scenarios.js.map +1 -0
  137. package/dist/tooling/managed-dev-supervisor.d.ts +2 -0
  138. package/dist/tooling/managed-dev-supervisor.js +51 -0
  139. package/dist/tooling/managed-dev-supervisor.js.map +1 -0
  140. package/dist/tooling/process-scope-bootstrap.mjs +24 -0
  141. package/dist/tooling/process-scope-guard.d.ts +2 -0
  142. package/dist/tooling/process-scope-guard.js +388 -0
  143. package/dist/tooling/process-scope-guard.js.map +1 -0
  144. package/dist/tooling/process-scope-windows.ps1 +148 -0
  145. package/dist/tooling/rooms-check-device.d.ts +2 -0
  146. package/dist/tooling/rooms-check-device.js +498 -0
  147. package/dist/tooling/rooms-check-device.js.map +1 -0
  148. package/dist/tooling/run-headless-room.d.ts +2 -0
  149. package/dist/tooling/run-headless-room.js +287 -0
  150. package/dist/tooling/run-headless-room.js.map +1 -0
  151. package/dist/tooling/run-test-profile.d.ts +2 -0
  152. package/dist/tooling/run-test-profile.js +181 -0
  153. package/dist/tooling/run-test-profile.js.map +1 -0
  154. package/dist/tooling/run-visual-capture.d.ts +2 -0
  155. package/dist/tooling/run-visual-capture.js +203 -0
  156. package/dist/tooling/run-visual-capture.js.map +1 -0
  157. package/dist/tooling/seal-game-build.d.ts +2 -0
  158. package/dist/tooling/seal-game-build.js +120 -0
  159. package/dist/tooling/seal-game-build.js.map +1 -0
  160. package/dist/types-CdYrgrG_.d.ts +1036 -0
  161. package/dist/types-DyRD-ym1.d.ts +141 -0
  162. package/dist/visual.d.ts +21 -0
  163. package/dist/visual.js +219 -0
  164. package/dist/visual.js.map +1 -0
  165. package/package.json +150 -3
  166. package/src/bounded-response.ts +28 -0
  167. package/src/built-game-runtime.ts +152 -0
  168. package/src/commands.ts +40 -0
  169. package/src/context.ts +218 -0
  170. package/src/controller-protocol.ts +22 -0
  171. package/src/controller.ts +1526 -0
  172. package/src/current-room-host.ts +166 -0
  173. package/src/decision-provider.ts +102 -0
  174. package/src/dependencies.ts +176 -0
  175. package/src/dependency-install-contract.ts +12 -0
  176. package/src/dev.ts +995 -0
  177. package/src/fs-utils.ts +93 -0
  178. package/src/game-action-observation.ts +106 -0
  179. package/src/game-build-protocol.ts +72 -0
  180. package/src/game-build.ts +483 -0
  181. package/src/game-run-owner.ts +2358 -0
  182. package/src/game-run-protocol.ts +448 -0
  183. package/src/game-run-record.ts +92 -0
  184. package/src/game-run-replay.ts +95 -0
  185. package/src/game-run-watch.ts +155 -0
  186. package/src/game-session-broker.ts +793 -0
  187. package/src/game-session-operations.ts +61 -0
  188. package/src/game-session-protocol.ts +180 -0
  189. package/src/game-session-runtime.ts +861 -0
  190. package/src/game-session.ts +206 -0
  191. package/src/game-settings.ts +295 -0
  192. package/src/games.ts +262 -0
  193. package/src/harness/visual/browser.ts +100 -0
  194. package/src/harness/visual/controller-observation.ts +181 -0
  195. package/src/harness/visual/prefab-contract.ts +29 -0
  196. package/src/harness/visual/prefab-runner.ts +178 -0
  197. package/src/harness/visual/runner.ts +549 -0
  198. package/src/harness/visual/runtime-controller-observations.ts +151 -0
  199. package/src/harness/visual/scenario-contract.ts +8 -0
  200. package/src/harness/visual/scenario-helpers.ts +67 -0
  201. package/src/harness/visual/screencast.ts +155 -0
  202. package/src/harness/visual/session.ts +400 -0
  203. package/src/harness/visual/types.ts +184 -0
  204. package/src/harness/visual.ts +7 -0
  205. package/src/headless-room-protocol.ts +112 -0
  206. package/src/headless-room.ts +222 -0
  207. package/src/helper-channel.ts +229 -0
  208. package/src/helper-scripts.ts +69 -0
  209. package/src/installed-dependencies.ts +74 -0
  210. package/src/logs.ts +67 -0
  211. package/src/managed-process-scope.ts +481 -0
  212. package/src/mcp-config.ts +262 -0
  213. package/src/node-process-environment.ts +10 -0
  214. package/src/platform-auth.ts +594 -0
  215. package/src/platform-game-analytics.ts +50 -0
  216. package/src/platform-game-app-id.ts +99 -0
  217. package/src/platform-game-media.ts +209 -0
  218. package/src/platform-games.ts +217 -0
  219. package/src/policy-artifact-contract.ts +52 -0
  220. package/src/policy-artifacts.ts +134 -0
  221. package/src/process-scope-admission.ts +50 -0
  222. package/src/process-scope-protocol.ts +66 -0
  223. package/src/process-scope.ts +327 -0
  224. package/src/quality.ts +82 -0
  225. package/src/release.ts +1683 -0
  226. package/src/rooms-check-fleet.ts +194 -0
  227. package/src/rooms-check-link.ts +138 -0
  228. package/src/rooms-check-protocol.ts +244 -0
  229. package/src/rooms-check.ts +797 -0
  230. package/src/runtime-owner-protocol.ts +218 -0
  231. package/src/source-tree-contract.ts +70 -0
  232. package/src/source-tree.ts +84 -0
  233. package/src/test-profile-process.ts +153 -0
  234. package/src/test-profile-protocol.ts +116 -0
  235. package/src/testing.ts +430 -0
  236. package/src/tooling/declaration-hook.ts +52 -0
  237. package/src/tooling/describe-game.ts +49 -0
  238. package/src/tooling/game-session-broker.ts +7 -0
  239. package/src/tooling/hold-runtime-host.ts +441 -0
  240. package/src/tooling/list-visual-scenarios.ts +21 -0
  241. package/src/tooling/load-game.ts +79 -0
  242. package/src/tooling/managed-dev-supervisor.ts +71 -0
  243. package/src/tooling/process-scope-bootstrap.mjs +24 -0
  244. package/src/tooling/process-scope-guard.ts +213 -0
  245. package/src/tooling/process-scope-windows.ps1 +148 -0
  246. package/src/tooling/rooms-check-device.ts +493 -0
  247. package/src/tooling/run-headless-room.ts +326 -0
  248. package/src/tooling/run-test-profile.ts +190 -0
  249. package/src/tooling/run-visual-capture.ts +231 -0
  250. package/src/tooling/runtime-owner-actions.ts +65 -0
  251. package/src/tooling/seal-game-build.ts +118 -0
  252. package/src/tooling/visual-pack.ts +11 -0
  253. package/src/types.ts +928 -0
  254. package/src/visual.ts +296 -0
  255. package/src/windows-process-scopes.ts +189 -0
  256. package/src/workspace-contract.ts +32 -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
+ });