oda-engine 0.0.0-stage → 0.1.0

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 (204) hide show
  1. package/README.md +151 -2
  2. package/bin/nowhere.mjs +352 -0
  3. package/lib/account.mjs +57 -0
  4. package/lib/agentModules.mjs +57 -0
  5. package/lib/devServer.mjs +351 -0
  6. package/lib/headless.mjs +231 -0
  7. package/lib/headlessPreview.mjs +212 -0
  8. package/lib/keys.mjs +517 -0
  9. package/lib/make.mjs +855 -0
  10. package/lib/mcp.mjs +537 -0
  11. package/lib/open.mjs +22 -0
  12. package/lib/preview.mjs +87 -0
  13. package/lib/previewRpc.mjs +134 -0
  14. package/lib/project.mjs +359 -0
  15. package/lib/publishFlow.mjs +90 -0
  16. package/lib/resources.mjs +50 -0
  17. package/lib/rules.mjs +60 -0
  18. package/lib/scaffold.mjs +42 -0
  19. package/lib/setup.mjs +59 -0
  20. package/lib/tools.mjs +668 -0
  21. package/package.json +51 -4
  22. package/template/game.config.json +9 -0
  23. package/template/scene.json +4 -0
  24. package/template/src/main.ts +11 -0
  25. package/vendor/DOCS.md +447 -0
  26. package/vendor/agent/appRun.mjs +520 -0
  27. package/vendor/agent/assets/brief.mjs +242 -0
  28. package/vendor/agent/assets/collider.mjs +531 -0
  29. package/vendor/agent/assets/environments/index.mjs +12 -0
  30. package/vendor/agent/assets/environments/worldlabs.mjs +161 -0
  31. package/vendor/agent/assets/fetch.mjs +168 -0
  32. package/vendor/agent/assets/footprint.mjs +13 -0
  33. package/vendor/agent/assets/gltf.mjs +547 -0
  34. package/vendor/agent/assets/hdr.mjs +269 -0
  35. package/vendor/agent/assets/imageOps.mjs +171 -0
  36. package/vendor/agent/assets/images/codex.mjs +307 -0
  37. package/vendor/agent/assets/images/fal.mjs +75 -0
  38. package/vendor/agent/assets/images/gemini.mjs +84 -0
  39. package/vendor/agent/assets/images/index.mjs +25 -0
  40. package/vendor/agent/assets/images/openai.mjs +75 -0
  41. package/vendor/agent/assets/images/stability.mjs +71 -0
  42. package/vendor/agent/assets/images/views.mjs +31 -0
  43. package/vendor/agent/assets/import.mjs +1352 -0
  44. package/vendor/agent/assets/inspect.mjs +465 -0
  45. package/vendor/agent/assets/jobs.mjs +196 -0
  46. package/vendor/agent/assets/ktx2.mjs +290 -0
  47. package/vendor/agent/assets/ledger.mjs +466 -0
  48. package/vendor/agent/assets/net.mjs +254 -0
  49. package/vendor/agent/assets/prices.json +39 -0
  50. package/vendor/agent/assets/providers/fal.mjs +115 -0
  51. package/vendor/agent/assets/providers/index.mjs +22 -0
  52. package/vendor/agent/assets/providers/meshy.mjs +119 -0
  53. package/vendor/agent/assets/providers/tripo.mjs +188 -0
  54. package/vendor/agent/assets/sources/ambientcg.mjs +129 -0
  55. package/vendor/agent/assets/sources/index.mjs +23 -0
  56. package/vendor/agent/assets/sources/polyhaven.mjs +237 -0
  57. package/vendor/agent/assets/sources/polypizza.mjs +121 -0
  58. package/vendor/agent/assets/splat.mjs +631 -0
  59. package/vendor/agent/assets/targets.mjs +122 -0
  60. package/vendor/agent/assets/tile.mjs +261 -0
  61. package/vendor/agent/assets/unzip.mjs +180 -0
  62. package/vendor/agent/blender/cleanup.py +360 -0
  63. package/vendor/agent/blender/convert.py +167 -0
  64. package/vendor/agent/blender/find.mjs +192 -0
  65. package/vendor/agent/blender/nw_export.py +104 -0
  66. package/vendor/agent/blender/nw_rubric.py +426 -0
  67. package/vendor/agent/blender/run.mjs +193 -0
  68. package/vendor/agent/blender/runner.py +252 -0
  69. package/vendor/agent/blender/sheet.py +743 -0
  70. package/vendor/agent/depth.mjs +134 -0
  71. package/vendor/agent/director/board.mjs +451 -0
  72. package/vendor/agent/director/contracts.mjs +663 -0
  73. package/vendor/agent/director/director.mjs +2365 -0
  74. package/vendor/agent/director/estimate.mjs +200 -0
  75. package/vendor/agent/director/gate.mjs +802 -0
  76. package/vendor/agent/director/limits.json +16 -0
  77. package/vendor/agent/director/methods.mjs +457 -0
  78. package/vendor/agent/director/policy.json +33 -0
  79. package/vendor/agent/director/prompts.mjs +244 -0
  80. package/vendor/agent/director/reading.mjs +341 -0
  81. package/vendor/agent/director/router.mjs +184 -0
  82. package/vendor/agent/director/seams.mjs +243 -0
  83. package/vendor/agent/director/session.mjs +643 -0
  84. package/vendor/agent/director/store.mjs +119 -0
  85. package/vendor/agent/director/taskGate.mjs +110 -0
  86. package/vendor/agent/director/teamLedger.mjs +118 -0
  87. package/vendor/agent/director/triage.mjs +63 -0
  88. package/vendor/agent/downloads.cjs +363 -0
  89. package/vendor/agent/flow.mjs +78 -0
  90. package/vendor/agent/guard.mjs +613 -0
  91. package/vendor/agent/host.mjs +1736 -0
  92. package/vendor/agent/language.mjs +58 -0
  93. package/vendor/agent/ledger.mjs +360 -0
  94. package/vendor/agent/locale.cjs +186 -0
  95. package/vendor/agent/loop/capacity.mjs +74 -0
  96. package/vendor/agent/loop/compose.mjs +127 -0
  97. package/vendor/agent/loop/gate.mjs +205 -0
  98. package/vendor/agent/loop/judge.mjs +189 -0
  99. package/vendor/agent/loop/levels.mjs +273 -0
  100. package/vendor/agent/loop/state.mjs +358 -0
  101. package/vendor/agent/notes.cjs +278 -0
  102. package/vendor/agent/pace.mjs +258 -0
  103. package/vendor/agent/panels.mjs +431 -0
  104. package/vendor/agent/prompt.mjs +342 -0
  105. package/vendor/agent/reference/board.mjs +410 -0
  106. package/vendor/agent/reference/compose.mjs +364 -0
  107. package/vendor/agent/reference/decode.mjs +56 -0
  108. package/vendor/agent/reference/facts.mjs +1874 -0
  109. package/vendor/agent/reference/png.mjs +107 -0
  110. package/vendor/agent/reference/records.mjs +63 -0
  111. package/vendor/agent/reference/web.mjs +252 -0
  112. package/vendor/agent/roles/artist.mjs +69 -0
  113. package/vendor/agent/roles/builder.mjs +79 -0
  114. package/vendor/agent/roles/checks.mjs +223 -0
  115. package/vendor/agent/roles/common.mjs +188 -0
  116. package/vendor/agent/roles/critic.mjs +171 -0
  117. package/vendor/agent/roles/index.mjs +39 -0
  118. package/vendor/agent/roles/modeller.mjs +142 -0
  119. package/vendor/agent/roles/qa.mjs +58 -0
  120. package/vendor/agent/roles/rubrics.mjs +79 -0
  121. package/vendor/agent/roles/sound.mjs +69 -0
  122. package/vendor/agent/rounds.cjs +333 -0
  123. package/vendor/agent/shared.mjs +284 -0
  124. package/vendor/agent/stopGate.mjs +574 -0
  125. package/vendor/agent/subagents.mjs +129 -0
  126. package/vendor/agent/tools/assets.mjs +499 -0
  127. package/vendor/agent/tools/blender.mjs +754 -0
  128. package/vendor/agent/tools/cards.mjs +479 -0
  129. package/vendor/agent/tools/choices.mjs +479 -0
  130. package/vendor/agent/tools/compose.mjs +74 -0
  131. package/vendor/agent/tools/environment.mjs +488 -0
  132. package/vendor/agent/tools/eyes.mjs +733 -0
  133. package/vendor/agent/tools/generate.mjs +338 -0
  134. package/vendor/agent/tools/guide.mjs +46 -0
  135. package/vendor/agent/tools/harness.mjs +193 -0
  136. package/vendor/agent/tools/image.mjs +643 -0
  137. package/vendor/agent/tools/index.mjs +162 -0
  138. package/vendor/agent/tools/look.mjs +578 -0
  139. package/vendor/agent/tools/loop.mjs +858 -0
  140. package/vendor/agent/tools/others.mjs +123 -0
  141. package/vendor/agent/tools/pictures.mjs +535 -0
  142. package/vendor/agent/tools/reference.mjs +366 -0
  143. package/vendor/agent/transcripts.mjs +118 -0
  144. package/vendor/agent-loop.mjs +602 -0
  145. package/vendor/agent-plugin/.claude-plugin/plugin.json +5 -0
  146. package/vendor/agent-plugin/skills/art-direction/SKILL.md +82 -0
  147. package/vendor/agent-plugin/skills/asset-legality/SKILL.md +101 -0
  148. package/vendor/agent-plugin/skills/asset-sources/SKILL.md +111 -0
  149. package/vendor/agent-plugin/skills/blender-modeling/SKILL.md +97 -0
  150. package/vendor/agent-plugin/skills/look-dev/SKILL.md +104 -0
  151. package/vendor/agent-plugin/skills/playtesting/SKILL.md +74 -0
  152. package/vendor/agent-plugin/skills/reference-loop/SKILL.md +102 -0
  153. package/vendor/agent-plugin/skills/sound-design/SKILL.md +60 -0
  154. package/vendor/agent-plugin/skills/style/SKILL.md +35 -0
  155. package/vendor/agent-plugin/skills/tsl-r185/SKILL.md +107 -0
  156. package/vendor/auth.cjs +570 -0
  157. package/vendor/build.cjs +953 -0
  158. package/vendor/catalog.json +455 -0
  159. package/vendor/connectors.cjs +688 -0
  160. package/vendor/eyes.mjs +733 -0
  161. package/vendor/gameExports.json +1390 -0
  162. package/vendor/git.cjs +222 -0
  163. package/vendor/models.json +57 -0
  164. package/vendor/publish.cjs +1018 -0
  165. package/vendor/refBoard.cjs +301 -0
  166. package/vendor/schema/dist/assets.d.ts +335 -0
  167. package/vendor/schema/dist/assets.js +439 -0
  168. package/vendor/schema/dist/brief.d.ts +357 -0
  169. package/vendor/schema/dist/brief.js +302 -0
  170. package/vendor/schema/dist/common.d.ts +9 -0
  171. package/vendor/schema/dist/common.js +13 -0
  172. package/vendor/schema/dist/config.d.ts +406 -0
  173. package/vendor/schema/dist/config.js +355 -0
  174. package/vendor/schema/dist/contract.d.ts +599 -0
  175. package/vendor/schema/dist/contract.js +1146 -0
  176. package/vendor/schema/dist/index.d.ts +14 -0
  177. package/vendor/schema/dist/index.js +21 -0
  178. package/vendor/schema/dist/look.d.ts +463 -0
  179. package/vendor/schema/dist/look.js +681 -0
  180. package/vendor/schema/dist/lookStats.d.ts +230 -0
  181. package/vendor/schema/dist/lookStats.js +768 -0
  182. package/vendor/schema/dist/pilot.d.ts +32 -0
  183. package/vendor/schema/dist/pilot.js +44 -0
  184. package/vendor/schema/dist/publish.d.ts +214 -0
  185. package/vendor/schema/dist/publish.js +291 -0
  186. package/vendor/schema/dist/scene.d.ts +75 -0
  187. package/vendor/schema/dist/scene.js +120 -0
  188. package/vendor/schema/dist/skyLight.d.ts +141 -0
  189. package/vendor/schema/dist/skyLight.js +436 -0
  190. package/vendor/schema/dist/style.d.ts +131 -0
  191. package/vendor/schema/dist/style.js +155 -0
  192. package/vendor/schema/package.json +1 -0
  193. package/vendor/selectionPrompt.mjs +51 -0
  194. package/vendor/useTools.mjs +195 -0
  195. package/vendor/userMessage.mjs +26 -0
  196. package/web-dist/assets/GaussianSplatUtils-CB77cP9U.js +1 -0
  197. package/web-dist/assets/KTX2Loader-6OIWUF7s.js +2 -0
  198. package/web-dist/assets/SPZLoader-zYj0Alfv.js +1 -0
  199. package/web-dist/assets/gaussianSplat-CJTI1sEh.js +1 -0
  200. package/web-dist/assets/index-CcjyyQco.css +1 -0
  201. package/web-dist/assets/index-DMyJcoZJ.js +693 -0
  202. package/web-dist/assets/meshopt_decoder.module-BvwdjiD3.js +1 -0
  203. package/web-dist/assets/zstddec.module-CfFeQW7d.js +1 -0
  204. package/web-dist/index.html +34 -0
package/lib/make.mjs ADDED
@@ -0,0 +1,855 @@
1
+ // `nowhere make`: a game from one request, with no window. The studio's own
2
+ // agent host runs it (with the director and the roles of a production, or
3
+ // the single agent for a quick request), found by agentModules.mjs; its eyes
4
+ // are a preview page this command starts and opens in headless Chrome
5
+ // (headless.mjs), answered through previewRpc.mjs as the MCP server answers
6
+ // them; and the cards the studio would show the creator are answered by the
7
+ // command's flags (askPolicy). Nothing opens on the screen.
8
+ //
9
+ // What happened is recorded in the project, beside the director's own
10
+ // .nowhere/production/<id>/: .nowhere/make/<stamp>/ holds run.json (the
11
+ // versions, the flags without any key, the GPU, the times, the outcome and
12
+ // the cost by model), events.jsonl (every event the host sent), cards.jsonl
13
+ // (every card and the answer it got), host.log and page-console.log. The
14
+ // project is committed at the end, so each run is one commit to compare.
15
+ //
16
+ // The real-model experiments run through this: the same request on the fast
17
+ // route and as a production, under a ceiling or not, read back from run.json.
18
+ // A production runs only when asked for: --route production or auto, or
19
+ // NOWHERE_TEAM_PRODUCTION=1, the CLI's side of the studio's Settings switch
20
+ // (agent.teamProduction, off by default). Otherwise the one agent makes it.
21
+
22
+ import fs from 'node:fs'
23
+ import path from 'node:path'
24
+ import { agentModule, agentRequire, agentTree, missingSdk, NO_SDK } from './agentModules.mjs'
25
+ import { startDevServer as startPreviewServer } from './devServer.mjs'
26
+ import { chromeEnv, findChrome as findChromeFile, launch as launchChrome, NO_CHROME } from './headless.mjs'
27
+ import { PREVIEW_METHODS, createPreviewRpc } from './previewRpc.mjs'
28
+ import { isProject } from './project.mjs'
29
+ import { PKG, VERSION, WEB, vendor } from './resources.mjs'
30
+ import { createProject } from './scaffold.mjs'
31
+
32
+ export const MAKE_USAGE = `oda make <project> --request <text> [--image <file>]... [--approve-cost <usd>] [--allow-web] [--allow-codex] [--decline-paid]
33
+ [--vision approve|skip] [--quality <1-5> | --best] [--ceiling <model id>] [--route auto|production|fast] [--max-sessions <n>]`
34
+
35
+ export const MAKE_HELP = `${MAKE_USAGE}
36
+
37
+ Makes a space in <project> (a new or empty folder becomes a project) from one
38
+ request, with no window: the studio's agent, with headless Chrome as its eyes.
39
+ Needs ANTHROPIC_API_KEY.
40
+
41
+ --request <text> what to make, in any language
42
+ --image <file> a reference picture (PNG, JPEG, WebP or GIF), up to 24
43
+ --approve-cost <usd> approve cost cards up to this in all (default 0: none); a card that does not
44
+ fit what is left is approved for what is left, and cancelled once nothing is.
45
+ What is left is this amount less what was approved or, when that is more, what
46
+ the run has spent; the run is stopped by 1.5 times this amount plus $1
47
+ --allow-web allow the web (otherwise denied)
48
+ --allow-codex allow Codex to make pictures on this computer's ChatGPT plan (otherwise denied)
49
+ --decline-paid no paid generation; the paid services' keys stay out of the agent's environment
50
+ --vision approve|skip how the vision card is answered (default approve)
51
+ --quality <1-5> the quality gauge, as in the studio's composer: the model, the effort a build
52
+ runs at, the rounds and the bar (1 Quick, 2 Standard, 3 Careful, 4 High, 5 Max);
53
+ it approves no cost, so it needs --approve-cost (without it the step's upper
54
+ estimate is printed and nothing starts)
55
+ --best the most the model can do: the top quality step under --ceiling, the web and
56
+ Codex allowed, choices left to the agent, and the step's upper estimate approved
57
+ (printed at the start) unless --approve-cost gives another amount
58
+ --ceiling <model id> never use a model priced above this one (it caps --quality's model too)
59
+ --route auto|production|fast the director's choice, a production, or one agent (default fast;
60
+ auto when NOWHERE_TEAM_PRODUCTION=1, team production being experimental)
61
+ --max-sessions <n> sessions at once in a production
62
+
63
+ Recorded in <project>/.nowhere/make/<stamp>/ and committed. Exit 0 done, 1 not finished, 2 could not start.`
64
+
65
+ export const NO_KEY = 'oda make needs ANTHROPIC_API_KEY in the environment: the key of the Anthropic account the space is made on.'
66
+
67
+ /** The environment variable that turns team production on for nowhere make,
68
+ * as the studio's Settings switch does for the studio. */
69
+ export const TEAM_PRODUCTION_VAR = 'NOWHERE_TEAM_PRODUCTION'
70
+
71
+ /** The route when --route is not given: one agent, unless team production
72
+ * is turned on, when the director chooses (auto). */
73
+ export function defaultRoute(env = process.env) {
74
+ return String(env?.[TEAM_PRODUCTION_VAR] ?? '').trim() === '1' ? 'auto' : 'fast'
75
+ }
76
+
77
+ const VALUE_FLAGS = new Set(['request', 'image', 'approve-cost', 'vision', 'quality', 'ceiling', 'route', 'max-sessions'])
78
+ const SWITCHES = new Set(['allow-web', 'allow-codex', 'decline-paid', 'best'])
79
+ const SWITCH_OPTIONS = { 'allow-web': 'allowWeb', 'allow-codex': 'allowCodex', 'decline-paid': 'declinePaid', best: 'best' }
80
+ const IMAGE_TYPES = { png: 'image/png', jpeg: 'image/jpeg', webp: 'image/webp', gif: 'image/gif' }
81
+ // The studio's own limits for attached pictures (main.cjs checkImages).
82
+ /** As the studio takes them in one message (agent/reference/board.mjs
83
+ * REFERENCE_LIMITS.perMessage): every one goes on the reference board and is
84
+ * measured, and the first few go in the message itself. */
85
+ const MAX_IMAGES = 24
86
+ const MAX_IMAGE_BYTES = 4.5 * 1024 * 1024
87
+ /** How long a request to the page may take before the tool hears it timed
88
+ * out (agent-host.mjs RPC_TIMEOUT; the tool's own timeoutMs wins). */
89
+ const RPC_TIMEOUT = { build: 60_000, status: 10_000, view: 33_000, play: 105_000, eval: 12_000, logs: 8_000, pixels: 12_000 }
90
+ /** What the studio's window does and this command cannot. */
91
+ const WINDOW_ONLY = new Set(['screenshot', 'capture-screen', 'browser', 'computer', 'computer-apps'])
92
+ /** The GPU adapter the page draws with, as WebGPU names it. */
93
+ const ADAPTER_CODE =
94
+ '(() => { const i = renderer?.backend?.device?.adapterInfo; return i ? { vendor: i.vendor, architecture: i.architecture, description: i.description, isFallbackAdapter: i.isFallbackAdapter ?? null } : null })()'
95
+
96
+ /**
97
+ * The command's arguments (everything after `make`): { help } for --help,
98
+ * { options } when they make sense, else { error } with the sentence.
99
+ */
100
+ export function parseMakeArgs(argv) {
101
+ // route null: not given, so runMake takes defaultRoute's.
102
+ // approveCostSet: --approve-cost was given (0 included), apart from its default.
103
+ const options = { project: null, request: null, images: [], approveCost: 0, approveCostSet: false, allowWeb: false, allowCodex: false, declinePaid: false, vision: 'approve', quality: null, best: false, ceiling: null, route: null, maxSessions: null }
104
+ for (let i = 0; i < argv.length; i++) {
105
+ const arg = String(argv[i])
106
+ if (arg === '--help' || arg === '-h') return { help: true }
107
+ if (!arg.startsWith('--')) {
108
+ if (options.project !== null) return { error: `One project folder at a time: "${options.project}" and "${arg}".` }
109
+ options.project = arg
110
+ continue
111
+ }
112
+ const eq = arg.indexOf('=')
113
+ const name = eq >= 0 ? arg.slice(2, eq) : arg.slice(2)
114
+ if (SWITCHES.has(name)) {
115
+ if (eq >= 0) return { error: `--${name} takes no value.` }
116
+ options[SWITCH_OPTIONS[name]] = true
117
+ continue
118
+ }
119
+ if (!VALUE_FLAGS.has(name)) return { error: `Unknown option --${name}.` }
120
+ let value = eq >= 0 ? arg.slice(eq + 1) : argv[++i]
121
+ if (value === undefined) return { error: `--${name} needs a value.` }
122
+ value = String(value)
123
+ if (name === 'request') options.request = value
124
+ else if (name === 'image') options.images.push(value)
125
+ else if (name === 'approve-cost') {
126
+ const usd = Number(value)
127
+ if (!Number.isFinite(usd) || usd < 0 || value.trim() === '') return { error: `--approve-cost takes an amount in US dollars, such as 5 (not "${value}").` }
128
+ options.approveCost = usd
129
+ options.approveCostSet = true
130
+ } else if (name === 'vision') {
131
+ if (value !== 'approve' && value !== 'skip') return { error: '--vision is approve or skip.' }
132
+ options.vision = value
133
+ } else if (name === 'route') {
134
+ if (!['auto', 'production', 'fast'].includes(value)) return { error: '--route is auto, production or fast.' }
135
+ options.route = value
136
+ } else if (name === 'quality') {
137
+ const n = Number(value)
138
+ if (!Number.isInteger(n) || n < 1 || n > 5 || value.trim() === '') return { error: `--quality is a whole step from 1 to 5 (not "${value}").` }
139
+ options.quality = n
140
+ } else if (name === 'max-sessions') {
141
+ const n = Number(value)
142
+ if (!Number.isInteger(n) || n < 1 || n > 8) return { error: '--max-sessions is a whole number from 1 to 8.' }
143
+ options.maxSessions = n
144
+ } else options.ceiling = value
145
+ }
146
+ if (!options.project) return { error: `Which project? ${MAKE_USAGE}` }
147
+ if (!options.request || !options.request.trim()) return { error: 'What should it make? Give the request with --request "..."' }
148
+ if (options.images.length > MAX_IMAGES) return { error: `Up to ${MAX_IMAGES} reference pictures (--image), as in the studio.` }
149
+ if (options.best && options.quality !== null) return { error: '--best picks the quality step itself (the top one under --ceiling): give --best or --quality, not both.' }
150
+ // --best: the web and Codex allowed; the step and its approval are set in
151
+ // runMake, once the models are read.
152
+ if (options.best) Object.assign(options, { allowWeb: true, allowCodex: true })
153
+ return { options }
154
+ }
155
+
156
+ /** A picture's type from its first bytes, or null for anything else. */
157
+ export function sniffImage(bytes) {
158
+ const b = Buffer.from(bytes ?? [])
159
+ if (b.length >= 8 && b.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) return IMAGE_TYPES.png
160
+ if (b.length >= 3 && b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff) return IMAGE_TYPES.jpeg
161
+ if (b.length >= 6 && /^GIF8[79]a$/.test(b.subarray(0, 6).toString('latin1'))) return IMAGE_TYPES.gif
162
+ if (b.length >= 12 && b.subarray(0, 4).toString('latin1') === 'RIFF' && b.subarray(8, 12).toString('latin1') === 'WEBP') return IMAGE_TYPES.webp
163
+ return null
164
+ }
165
+
166
+ /** The reference pictures as the host takes them ({ mime, data } in base64),
167
+ * or the sentence for the first that will not do. */
168
+ export function readImages(files, cwd = process.cwd()) {
169
+ const images = []
170
+ for (const file of files) {
171
+ const at = path.resolve(cwd, file)
172
+ let bytes
173
+ try {
174
+ bytes = fs.readFileSync(at)
175
+ } catch (err) {
176
+ return { error: `The picture ${file} cannot be read (${err.code ?? err.message}).` }
177
+ }
178
+ const mime = sniffImage(bytes)
179
+ if (!mime) return { error: `${file} is not a PNG, JPEG, WebP or GIF picture.` }
180
+ if (bytes.length > MAX_IMAGE_BYTES) return { error: `${file} is over 4.5 MB, the most one picture can be, as in the studio.` }
181
+ images.push({ mime, data: bytes.toString('base64') })
182
+ }
183
+ return { images }
184
+ }
185
+
186
+ const roundUsd = (n) => Math.round(n * 1e6) / 1e6
187
+
188
+ /** The top quality step whose model costs no more (by output price) than
189
+ * the ceiling, a Claude model id; 5 with no ceiling. */
190
+ export function bestStep(levels, claude, ceiling = null) {
191
+ const out = (id) => Number(claude?.models?.find((m) => m.id === id)?.price?.[1] ?? Infinity)
192
+ if (!ceiling || !claude?.models?.some((m) => m.id === ceiling)) return 5
193
+ const fits = levels.QUALITY_STEPS.filter((n) => out(levels.QUALITY[n].model) <= out(ceiling))
194
+ return fits.length ? Math.max(...fits) : 1
195
+ }
196
+
197
+ /** A quality step's upper estimate in US dollars, as the host prices the
198
+ * composer's approval (loop/levels.mjs estimateQuality): the step's model
199
+ * under the ceiling, the judge, a second judge on OpenAI when its key is
200
+ * passed on, and the target pictures. Null with no price. */
201
+ export function qualityEstimate(levels, shared, options, env = {}) {
202
+ const model = levels.qualityModel(options.quality, options.ceiling ?? null)
203
+ const openai = typeof env?.OPENAI_API_KEY === 'string' && env.OPENAI_API_KEY.trim() !== '' && !options.declinePaid
204
+ const judge = openai ? (shared.MODELS.providers.find((p) => p.id === 'openai')?.models.find((m) => m.images) ?? null) : null
205
+ const est = levels.estimateQuality(options.quality, { pricing: shared.PRICING[model] ?? null, judge: judge ? shared.pricingFor(judge) : null, targetUsd: levels.targetPrice() })
206
+ return Number.isFinite(est?.usd?.hi) ? est.usd.hi : null
207
+ }
208
+ const usd = (n) => `$${(Number(n) || 0).toFixed(2)}`
209
+
210
+ /**
211
+ * The answers the studio's creator would give, from the flags: a cost card
212
+ * is approved while what was approved so far, with it, stays within
213
+ * --approve-cost; one that does not fit is approved for what is left of it,
214
+ * and cancelled once nothing is left, a card that asks for $0 included.
215
+ * What is left is counted from the larger of what was approved and what the
216
+ * run has spent (the card comes with it): each approval lets the ledger
217
+ * spend half as much again and $1 past it from where the spend then stands,
218
+ * so approvals counted alone would add up to more than --approve-cost
219
+ * promises. Counted this way a run stops by 1.5 times --approve-cost plus $1.
220
+ * The web is allowed with
221
+ * --allow-web and denied without, Codex with --allow-codex; a key is skipped (the keys this run has
222
+ * are the environment's); a choice is unavailable, so the agent chooses for
223
+ * itself; the vision card is answered by --vision; anything else is
224
+ * unavailable, as a card no one could see. `record` hears every card with its answer, `say` a line for
225
+ * the terminal.
226
+ */
227
+ export function askPolicy(flags, { record = () => {}, say = () => {} } = {}) {
228
+ const limit = Number.isFinite(Number(flags?.approveCost)) ? Number(flags.approveCost) : 0
229
+ let approved = 0
230
+
231
+ function decide(card, spentUsd) {
232
+ switch (card?.kind) {
233
+ case 'cost': {
234
+ const items = Array.isArray(card.estimate?.items) ? card.estimate.items : null
235
+ const fits = items && items.length >= 1 && items.length <= 12 && items.every((i) => i && typeof i.label === 'string' && Number.isFinite(i.usd) && i.usd >= 0)
236
+ // The same refusal as the studio's cards.cjs: a card it cannot read is no approval.
237
+ if (!fits) return { result: { ok: false, error: 'A cost card needs an estimate: 1 to 12 lines, each a label of up to 80 characters and a cost in US dollars from 0 to 10000.' }, line: 'a cost card without a readable estimate was refused' }
238
+ const total = roundUsd(items.reduce((sum, i) => sum + i.usd, 0))
239
+ // What is left of --approve-cost: less what was approved or, when
240
+ // the run has spent more than that, what it has spent.
241
+ const spent = Number.isFinite(spentUsd) && spentUsd > 0 ? spentUsd : 0
242
+ const rest = roundUsd(limit - Math.max(approved, spent))
243
+ // Nothing left: no card is approved, one that asks for $0 neither
244
+ // (any approval moves the ledger on from where the spend stands).
245
+ if (rest <= 1e-9) {
246
+ const why = spent > approved + 1e-9 ? `the run has spent ${usd(spent)} of --approve-cost ${usd(limit)}` : `all of --approve-cost ${usd(limit)} is approved already`
247
+ return { result: { answer: 'cancel' }, line: `cost ${usd(total)} asked, cancelled: ${why}` }
248
+ }
249
+ if (total <= rest + 1e-9) {
250
+ approved = roundUsd(approved + total)
251
+ return { result: { answer: 'approve', approvedUsd: total }, line: `cost ${usd(total)} approved (${usd(approved)} of --approve-cost ${usd(limit)} so far)` }
252
+ }
253
+ // The agent hears the smaller amount and keeps its work within it.
254
+ approved = roundUsd(approved + rest)
255
+ return { result: { answer: 'approve', approvedUsd: rest }, line: `cost ${usd(total)} asked, ${usd(rest)} approved: the rest of --approve-cost ${usd(limit)}` }
256
+ }
257
+ case 'consent':
258
+ if (card.topic === 'web') {
259
+ const answer = flags?.allowWeb ? 'allow' : 'deny'
260
+ return { result: { answer, saved: false }, line: `the web: ${answer === 'allow' ? 'allowed (--allow-web)' : 'denied (no --allow-web)'}` }
261
+ }
262
+ if (card.topic === 'codex') {
263
+ const answer = flags?.allowCodex ? 'allow' : 'deny'
264
+ return { result: { answer, saved: false }, line: `Codex: ${answer === 'allow' ? 'allowed (--allow-codex)' : 'denied (no --allow-codex)'}` }
265
+ }
266
+ return { result: { answer: 'unavailable' }, line: `consent for ${card.topic ?? 'something'}: no one to ask here` }
267
+ case 'key':
268
+ return { result: { answer: 'skipped', connector: String(card.connector ?? '') }, line: `a key for ${card.connector ?? 'a service'}: skipped (set its variable before the run to use it)` }
269
+ case 'choice':
270
+ // No one is here to choose: the agent picks and says which.
271
+ return { result: { answer: 'unavailable' }, line: `choice "${card.title ?? ''}": left to the agent` }
272
+ case 'vision':
273
+ return flags?.vision === 'skip' ? { result: { answer: 'skip' }, line: 'the vision: skipped (--vision skip)' } : { result: { answer: 'approve' }, line: 'the vision: approved' }
274
+ default:
275
+ return { result: { answer: 'unavailable' }, line: `a ${card?.kind ?? 'card'} card: no one to answer it here` }
276
+ }
277
+ }
278
+
279
+ return {
280
+ async ask(params) {
281
+ const card = params?.card ?? null
282
+ const { result, line } = decide(card, Number(params?.spentUsd))
283
+ record({ card, answer: result })
284
+ say(line)
285
+ return result
286
+ },
287
+ approvedUsd: () => approved,
288
+ }
289
+ }
290
+
291
+ /**
292
+ * The connectors part of the host's message: the keyed services whose
293
+ * variable is set in `env` (its value handed over, and the service named to
294
+ * the agent as the studio names a connected one), except, with declinePaid,
295
+ * the paid ones: theirs are kept out of the agent's environment.
296
+ */
297
+ export function connectorsFor(env, { declinePaid = false } = {}, { catalog = [], paidCategories = new Set() } = {}) {
298
+ const out = { env: {}, envRemove: [], mcpServers: {}, services: [], available: [] }
299
+ for (const entry of catalog) {
300
+ // Claude runs the agent; its key travels as the message's apiKey.
301
+ if (entry?.auth?.type !== 'apiKey' || entry.id === 'anthropic') continue
302
+ const name = entry.auth.envVar
303
+ if (!/^[A-Z_][A-Z0-9_]*$/.test(String(name ?? ''))) continue
304
+ const value = typeof env?.[name] === 'string' ? env[name].trim() : ''
305
+ if (!value) continue
306
+ if (declinePaid && paidCategories.has(entry.category)) {
307
+ out.envRemove.push(name)
308
+ continue
309
+ }
310
+ out.env[name] = value
311
+ const header = entry.auth.header ? ` (header ${entry.auth.header.name}: ${entry.auth.header.prefix ?? ''}<key>)` : ''
312
+ out.services.push(`${entry.name}: ${entry.blurb ?? ''} Key in ${name}${header}.${entry.auth.docsUrl ? ` Docs ${entry.auth.docsUrl}` : ''}`)
313
+ }
314
+ return out
315
+ }
316
+
317
+ /** The computer's language, as main.cjs reads the OS's: it sets the screen
318
+ * language every card and the brief are in (agent/locale.cjs screenLocale:
319
+ * English where the studio has no labels for it), while the agent replies
320
+ * in the language the request is written in. Intl's locale, which Node
321
+ * takes from the environment; LANG when Intl has none. */
322
+ export function osLocale(env = process.env) {
323
+ let tag = ''
324
+ try {
325
+ tag = Intl.DateTimeFormat().resolvedOptions().locale ?? ''
326
+ } catch {
327
+ tag = ''
328
+ }
329
+ return tag && tag !== 'und' ? tag : String(env.LC_ALL || env.LC_MESSAGES || env.LANG || 'en')
330
+ }
331
+
332
+ /** The message the host runs, as main.cjs sends a prompt (agent-host.mjs). */
333
+ export function makeMessage({ options, id, text, images, projectRoot, apiKey, model, connectors, osLocale }) {
334
+ return {
335
+ id,
336
+ text,
337
+ images,
338
+ projectRoot,
339
+ apiKey,
340
+ model,
341
+ // The quality step, with no approval of its own (the studio's composer
342
+ // sends qualityApproval; here --approve-cost is the only one).
343
+ ...(options.quality ? { quality: options.quality } : {}),
344
+ // A team only when a production may run (auto lets the director choose).
345
+ team: options.route === 'auto' || options.route === 'production',
346
+ ...(options.route && options.route !== 'auto' ? { route: options.route } : {}),
347
+ settings: {
348
+ consents: { web: options.allowWeb ? 'allow' : 'deny', codex: options.allowCodex ? 'allow' : 'deny' },
349
+ declinePaid: options.declinePaid,
350
+ ceiling: options.ceiling,
351
+ vision: options.vision,
352
+ maxSessions: options.maxSessions,
353
+ },
354
+ connectors,
355
+ history: [],
356
+ osLocale,
357
+ studio: { userData: null, devtoolsPorts: [9222, 9229] },
358
+ }
359
+ }
360
+
361
+ /** yyyymmdd-hhmmss, in local time. */
362
+ export function stampOf(date) {
363
+ const two = (n) => String(n).padStart(2, '0')
364
+ return `${date.getFullYear()}${two(date.getMonth() + 1)}${two(date.getDate())}-${two(date.getHours())}${two(date.getMinutes())}${two(date.getSeconds())}`
365
+ }
366
+
367
+ /** The engine checkout's commit, when this package runs from one. */
368
+ function engineCommit() {
369
+ const gitDir = path.resolve(PKG, '..', '..', '.git')
370
+ try {
371
+ const head = fs.readFileSync(path.join(gitDir, 'HEAD'), 'utf8').trim()
372
+ if (!head.startsWith('ref: ')) return /^[0-9a-f]{40}$/.test(head) ? head : null
373
+ const ref = head.slice(5)
374
+ const loose = path.join(gitDir, ref)
375
+ if (fs.existsSync(loose)) return fs.readFileSync(loose, 'utf8').trim()
376
+ const packed = fs.readFileSync(path.join(gitDir, 'packed-refs'), 'utf8')
377
+ return new RegExp(`^([0-9a-f]{40}) ${ref.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}$`, 'm').exec(packed)?.[1] ?? null
378
+ } catch {
379
+ return null
380
+ }
381
+ }
382
+
383
+ /** A URL with the preview's session token taken out, for the record. */
384
+ const withoutToken = (s) => String(s).replace(/([?&]t=)[^&\s]+/g, '$1<token>')
385
+
386
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
387
+ /** A wait that can be called off, so a run that ended leaves no timer behind
388
+ * (a check runs many in one process). */
389
+ function deadline(ms) {
390
+ let timer
391
+ const promise = new Promise((resolve) => (timer = setTimeout(resolve, ms)))
392
+ return { promise, clear: () => clearTimeout(timer) }
393
+ }
394
+
395
+ /** One line per task whose status, model or round changed, and the phase. */
396
+ function boardLines(board, seen) {
397
+ const lines = []
398
+ if (board?.phase && seen.get('phase') !== board.phase) {
399
+ seen.set('phase', board.phase)
400
+ lines.push(`phase: ${board.phase}`)
401
+ }
402
+ for (const t of Array.isArray(board?.tasks) ? board.tasks : []) {
403
+ const key = [t.status, t.model?.id, t.effort, t.round, t.pass].join('|')
404
+ if (seen.get(t.id) === key) continue
405
+ seen.set(t.id, key)
406
+ const model = t.model ? `${t.model.name ?? t.model.id}${t.effort ? ` ${t.effort}` : ''}` : 'no model yet'
407
+ const scores = t.scores ? `, overall ${t.scores.overall}` : ''
408
+ lines.push(` ${t.id} ${t.role} (${t.label ?? ''}): ${t.status}, ${model}, round ${t.round ?? 0}/${t.roundLimit ?? '?'}${t.escalated ? ', moved up' : ''}${scores}, ${usd(t.usd)}`)
409
+ }
410
+ return lines
411
+ }
412
+
413
+ /** The page's console, every entry the probe kept, as nw_logs prints them. */
414
+ async function pageConsole(request) {
415
+ const lines = []
416
+ let since = 0
417
+ for (let page = 0; page < 50; page++) {
418
+ let reply
419
+ try {
420
+ reply = await request('probe:logs', { since, limit: 200 }, 5000)
421
+ } catch (err) {
422
+ lines.push(`(the page's console could not be read: ${err?.message ?? err})`)
423
+ break
424
+ }
425
+ const entries = Array.isArray(reply?.entries) ? reply.entries : []
426
+ for (const e of entries) lines.push(`[${e.seq}] +${((Number(e.t) || 0) / 1000).toFixed(1)}s ${e.level} ${e.source}: ${e.text}`)
427
+ if (entries.length < 200 || !Number.isFinite(reply?.next) || reply.next <= since) break
428
+ since = reply.next
429
+ }
430
+ return lines
431
+ }
432
+
433
+ /**
434
+ * Runs one request, start to end. Resolves with { exit, outcome,
435
+ * productionId, recordDir, report, error }: exit 0 when the game was made
436
+ * (the host's done), 1 when it was kept below the critic's bar, not
437
+ * finished, stopped or failed, 2 when it could not start (the sentence in
438
+ * error).
439
+ *
440
+ * deps, for the checks: env (the key and the services' keys are read from
441
+ * it), createHost and hostTest (the host, and its test hooks: a scripted
442
+ * model), startDevServer, findChrome, launch, signals (where SIGINT,
443
+ * SIGTERM and SIGHUP come from), exit (a second Ctrl+C), out and err (the terminal),
444
+ * now, and the waits (pageWaitMs, probeWaitMs, cancelWaitMs).
445
+ */
446
+ export async function runMake(options, deps = {}) {
447
+ const d = {
448
+ env: process.env,
449
+ createHost: null,
450
+ hostTest: undefined,
451
+ startDevServer: startPreviewServer,
452
+ findChrome: () => findChromeFile({ env: deps.env ?? process.env }),
453
+ launch: launchChrome,
454
+ signals: process,
455
+ exit: (code) => process.exit(code),
456
+ out: (line) => process.stdout.write(`${line}\n`),
457
+ err: (line) => process.stderr.write(`${line}\n`),
458
+ now: () => new Date(),
459
+ pageWaitMs: 30_000,
460
+ probeWaitMs: 30_000,
461
+ cancelWaitMs: 60_000,
462
+ cwd: process.cwd(),
463
+ ...deps,
464
+ }
465
+ options = { ...options, route: options.route ?? defaultRoute(d.env) }
466
+ const startedAt = d.now()
467
+ const cantStart = (error, extra = {}) => {
468
+ d.err(error)
469
+ return { exit: 2, outcome: 'could not start', productionId: null, recordDir: null, report: '', error, ...extra }
470
+ }
471
+
472
+ // ---------------------------------------------------------- before anything starts
473
+ const apiKey = typeof d.env.ANTHROPIC_API_KEY === 'string' ? d.env.ANTHROPIC_API_KEY.trim() : ''
474
+ if (!apiKey) return cantStart(NO_KEY)
475
+ const text = String(options.request ?? '').trim()
476
+ if (!text) return cantStart('What should it make? Give the request with --request "..."')
477
+ const read = readImages(options.images ?? [], d.cwd)
478
+ if (read.error) return cantStart(read.error)
479
+ if (!fs.existsSync(path.join(WEB, 'index.html'))) return cantStart('This copy of oda-engine has no preview page (web-dist/). Reinstall it, or run its build in a checkout.')
480
+
481
+ const tree = agentTree()
482
+ if (!tree) return cantStart('This copy of oda-engine does not carry the studio agent that oda make runs (vendor/agent/host.mjs). Reinstall it, or run its build in a checkout.')
483
+ let shared
484
+ let levels
485
+ let createHost = d.createHost
486
+ try {
487
+ shared = await agentModule('shared.mjs', tree)
488
+ levels = await agentModule('loop/levels.mjs', tree)
489
+ if (!createHost) createHost = (await agentModule('host.mjs', tree)).createHost
490
+ } catch (err) {
491
+ return cantStart(missingSdk(err) ? NO_SDK : `The studio agent did not load: ${err?.message ?? err}`)
492
+ }
493
+ const claude = shared.MODELS.providers.find((p) => p.runtime === 'claude-agent-sdk')
494
+ if (options.ceiling && !claude?.models.some((m) => m.id === options.ceiling)) {
495
+ return cantStart(`--ceiling takes a Claude model id: ${(claude?.models ?? []).map((m) => m.id).join(', ')}.`)
496
+ }
497
+
498
+ // --best: the top quality step whose model is not dearer than --ceiling.
499
+ if (options.best) options = { ...options, quality: bestStep(levels, claude, options.ceiling) }
500
+ // A quality step's upper estimate (as the studio's composer approves it on
501
+ // sending): --best approves it unless --approve-cost says otherwise, and
502
+ // --quality with no --approve-cost stops here, before anything starts.
503
+ if (options.quality) {
504
+ const hi = qualityEstimate(levels, shared, options, d.env)
505
+ const step = levels.QUALITY[options.quality]
506
+ const priced = Number.isFinite(hi) ? `up to ${usd(hi)}` : 'at no known price'
507
+ d.out(`Quality step ${step.step} (${step.name}) on ${levels.qualityModel(step.step, options.ceiling)}: ${priced} for a new space, by the studio's estimate.`)
508
+ const given = options.approveCostSet === true || (Number(options.approveCost) || 0) > 0
509
+ if (options.best && !given && Number.isFinite(hi)) {
510
+ options = { ...options, approveCost: hi, approveCostSet: true }
511
+ d.out(`--best approves ${usd(hi)}.`)
512
+ } else if (!given) {
513
+ return cantStart(`--quality ${step.step} approves no cost, so the agent would plan and build nothing: add --approve-cost ${Number.isFinite(hi) ? hi.toFixed(2) : '<usd>'} (the step's upper estimate${Number.isFinite(hi) ? `, ${usd(hi)}` : ''}) to build.`)
514
+ }
515
+ }
516
+ // What this run will do without, said before it starts.
517
+ if (!options.allowWeb) d.out('No web: no CC0 libraries, HDRIs, style research or reference pictures; add --allow-web')
518
+ const openaiKey = typeof d.env.OPENAI_API_KEY === 'string' && d.env.OPENAI_API_KEY.trim() !== '' && !options.declinePaid
519
+ if (!options.allowCodex && !openaiKey) d.out('No picture generator: the space will have no target pictures to be judged against. Add --allow-codex or set OPENAI_API_KEY.')
520
+
521
+ // The project: a new or empty folder becomes one; anything else must be one.
522
+ let projectRoot = path.resolve(d.cwd, String(options.project))
523
+ const empty = !fs.existsSync(projectRoot) || (fs.statSync(projectRoot).isDirectory() && fs.readdirSync(projectRoot).length === 0)
524
+ if (empty) {
525
+ try {
526
+ await createProject(projectRoot)
527
+ } catch (err) {
528
+ return cantStart(`The project could not be made: ${err?.message ?? err}`)
529
+ }
530
+ } else if (!isProject(projectRoot)) {
531
+ return cantStart(`${projectRoot} is not an Oda project (no game.config.json and src/main.ts) and is not empty. Give a project, an empty folder or a new one.`)
532
+ }
533
+ projectRoot = fs.realpathSync(projectRoot)
534
+
535
+ // ---------------------------------------------------------- the record
536
+ let stamp = stampOf(startedAt)
537
+ let recordDir = path.join(projectRoot, '.nowhere', 'make', stamp)
538
+ for (let n = 2; fs.existsSync(recordDir); n++) recordDir = path.join(projectRoot, '.nowhere', 'make', `${stamp}-${n}`)
539
+ stamp = path.basename(recordDir)
540
+ fs.mkdirSync(recordDir, { recursive: true })
541
+ const appendLine = (name, value) => {
542
+ try {
543
+ fs.appendFileSync(path.join(recordDir, name), `${typeof value === 'string' ? value : JSON.stringify(value)}\n`)
544
+ } catch {
545
+ // a full disk loses the record, not the run
546
+ }
547
+ }
548
+ const log = (line) => appendLine('host.log', String(line))
549
+ const say = (line) => d.out(line)
550
+
551
+ const git = vendor('git.cjs')
552
+ // Anything the creator changed and had not committed is its own commit, so
553
+ // the run's commit holds only what the run made.
554
+ await git.ensureRepo(projectRoot, path.basename(projectRoot))
555
+ const before = await git.autoCommit(projectRoot, `before make: ${text.split('\n')[0].slice(0, 100)}`)
556
+
557
+ // ---------------------------------------------------------- Ctrl+C, a hangup, an exit
558
+ let stopping = false
559
+ let signalled = 0
560
+ let host = null
561
+ let chrome = null
562
+ let dev = null
563
+ let wakeStop = () => {}
564
+ const stopped = new Promise((resolve) => (wakeStop = resolve))
565
+ const onSignal = () => {
566
+ signalled++
567
+ if (signalled === 1) {
568
+ stopping = true
569
+ say('Stopping (Ctrl+C again quits at once).')
570
+ host?.cancel()
571
+ wakeStop()
572
+ return
573
+ }
574
+ // At once, but never leaving a headless browser behind.
575
+ void Promise.resolve(chrome?.kill())
576
+ .catch(() => {})
577
+ .finally(() => d.exit(1))
578
+ }
579
+ // A closed terminal or a dropped ssh session is a Stop too: Chrome and
580
+ // Blender run in process groups of their own, so they never get the hangup.
581
+ d.signals.on('SIGINT', onSignal)
582
+ d.signals.on('SIGTERM', onSignal)
583
+ d.signals.on('SIGHUP', onSignal)
584
+ // However this process ends (an uncaught throw, an exit at once), the
585
+ // headless browser goes with it; a kill is synchronous, so it works here.
586
+ const killChrome = () => {
587
+ try {
588
+ if (chrome?.pid) process.kill(process.platform === 'win32' ? chrome.pid : -chrome.pid, 'SIGKILL')
589
+ } catch {
590
+ // already gone
591
+ }
592
+ }
593
+ process.once('exit', killChrome)
594
+
595
+ let exit = 1
596
+ let outcome = 'failed'
597
+ let error = null
598
+ let productionId = null
599
+ let reply = ''
600
+ let lastCost = null
601
+ let backend = null
602
+ let adapter = null
603
+ let commit = null
604
+ let hostEnded = null
605
+ let finalUsd = null
606
+ let msg = null
607
+ const counts = { events: 0, cards: 0 }
608
+
609
+ try {
610
+ // -------------------------------------------------------- the preview and its eyes
611
+ say(`oda make: ${path.basename(projectRoot)}`)
612
+ const cannot = (message) => Object.assign(new Error(message), { cantStart: true })
613
+ try {
614
+ dev = await d.startDevServer({ root: projectRoot, port: 0, log: (line) => log(`[preview] ${line}`) })
615
+ } catch (err) {
616
+ throw cannot(`The preview could not start: ${err?.message ?? err}`)
617
+ }
618
+ const chromeFile = d.findChrome()
619
+ if (!chromeFile) throw cannot(NO_CHROME)
620
+ try {
621
+ chrome = await d.launch({ url: dev.url, chrome: chromeFile, env: chromeEnv(d.env) })
622
+ } catch (err) {
623
+ throw cannot(err?.message ?? String(err))
624
+ }
625
+ log(`[make] chrome ${chrome.version ?? '(version unknown)'} pid ${chrome.pid}`)
626
+ const tail = () => (chrome?.tail?.(12) ?? []).map((l) => ` ${l}`).join('\n')
627
+
628
+ if (!(await dev.waitForPage(d.pageWaitMs))) {
629
+ throw cannot(`Headless Chrome did not open the preview page within ${Math.round(d.pageWaitMs / 1000)} s. Chrome's last words:\n${tail()}`)
630
+ }
631
+ // The page's probe says which GPU backend the view drew with.
632
+ const until = Date.now() + d.probeWaitMs
633
+ let status = null
634
+ while (!stopping && Date.now() < until) {
635
+ status = await dev.request('probe:status', {}, 4000).catch(() => null)
636
+ if (status?.frame?.backend) break
637
+ await sleep(500)
638
+ }
639
+ backend = status?.frame?.backend ?? null
640
+ if (!stopping && backend !== 'WebGPU') {
641
+ throw cannot(`The preview runs ${backend ? `on ${backend}` : 'with no GPU backend'}, not WebGPU, so what the agent sees would not be what a planet shows. Chrome's last words:\n${tail()}`)
642
+ }
643
+ const found = await dev.request('probe:eval', { code: ADAPTER_CODE, timeoutMs: 3000 }, 5000).catch(() => null)
644
+ adapter = found?.ok ? (found.value ?? null) : null
645
+ if (backend) say(` the eyes: headless ${chrome.version ?? 'Chrome'}, ${backend}${adapter?.description ? ` on ${adapter.description}` : adapter?.architecture ? ` on ${adapter.vendor} ${adapter.architecture}` : ''}`)
646
+
647
+ // -------------------------------------------------------- the rpc
648
+ const eyes = createPreviewRpc({
649
+ root: projectRoot,
650
+ preview: { url: dev.url, request: dev.request, ensurePage: (ms) => dev.waitForPage(ms) },
651
+ pageWaitMs: 10_000,
652
+ noPage: () => 'The headless preview page is not connected.',
653
+ })
654
+ const policy = askPolicy(options, {
655
+ record: (entry) => {
656
+ counts.cards++
657
+ appendLine('cards.jsonl', { at: new Date().toISOString(), ...entry })
658
+ },
659
+ say: (line) => say(` card: ${line}`),
660
+ })
661
+ const rpc = async (method, params, timeoutMs) => {
662
+ if (method === 'ask') return policy.ask(params)
663
+ if (WINDOW_ONLY.has(method)) return { ok: false, error: 'Not in the runner.' }
664
+ if (!PREVIEW_METHODS.includes(method) && method !== 'image-resize') return { ok: false, error: `Unknown rpc: ${method}` }
665
+ // The page's own timeouts answer first; this only keeps a lost page
666
+ // from holding a tool forever.
667
+ const wait = (Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : (RPC_TIMEOUT[method] ?? 30_000)) + 5000
668
+ const late = deadline(wait)
669
+ try {
670
+ return await Promise.race([eyes.rpc(method, params, timeoutMs), late.promise.then(() => ({ ok: false, error: `rpc ${method} timed out` }))])
671
+ } finally {
672
+ late.clear()
673
+ }
674
+ }
675
+
676
+ // -------------------------------------------------------- the host
677
+ const ended = new Promise((resolve) => (hostEnded = resolve))
678
+ const seen = new Map()
679
+ const send = (event) => {
680
+ counts.events++
681
+ appendLine('events.jsonl', { at: Date.now(), ...event })
682
+ switch (event?.type) {
683
+ case 'started':
684
+ productionId ??= event.team?.productionId ?? null
685
+ say(` started: ${event.team ? `a production${productionId ? ` (${productionId})` : ''}` : `one agent on ${event.model}`}`)
686
+ break
687
+ case 'board':
688
+ productionId ??= event.board?.productionId ?? null
689
+ for (const line of boardLines(event.board, seen)) say(line)
690
+ break
691
+ case 'tool':
692
+ reply = ''
693
+ break
694
+ case 'text':
695
+ reply += String(event.delta ?? '')
696
+ break
697
+ case 'cost':
698
+ lastCost = event
699
+ break
700
+ case 'done':
701
+ productionId ??= event.team?.productionId ?? null
702
+ hostEnded({ ok: true, event })
703
+ break
704
+ case 'error':
705
+ hostEnded({ ok: false, event })
706
+ break
707
+ }
708
+ }
709
+ let connectors = { env: {}, envRemove: [], mcpServers: {}, services: [], available: [] }
710
+ try {
711
+ connectors = connectorsFor(d.env, options, { catalog: agentRequire('../connectors.cjs', tree).loadCatalog(), paidCategories: shared.PAID_CATEGORIES })
712
+ } catch (err) {
713
+ log(`[make] the connector catalog could not be read, so no service keys are passed on: ${err?.message ?? err}`)
714
+ }
715
+ msg = makeMessage({
716
+ options,
717
+ id: `make-${stamp}`,
718
+ text,
719
+ images: read.images,
720
+ projectRoot,
721
+ apiKey,
722
+ // --quality's step's model, held under --ceiling (loop/levels.mjs qualityModel).
723
+ model: options.quality ? levels.qualityModel(options.quality, options.ceiling) : (options.ceiling ?? shared.MODELS.default),
724
+ connectors,
725
+ osLocale: osLocale(),
726
+ })
727
+ if (stopping) throw Object.assign(new Error('Stopped before it started.'), { stopped: true })
728
+ host = createHost({ send, rpc, log, ...(d.hostTest ? { test: d.hostTest } : {}) })
729
+ const running = Promise.resolve()
730
+ .then(() => host.run(msg))
731
+ .catch((err) => log(`[make] the host threw: ${err?.stack ?? err}`))
732
+ // A Stop waits for the host to say it ended, at most cancelWaitMs.
733
+ let wait = null
734
+ await Promise.race([
735
+ running,
736
+ stopped.then(() => {
737
+ wait = deadline(d.cancelWaitMs)
738
+ return Promise.race([running, ended, wait.promise])
739
+ }),
740
+ ])
741
+ wait?.clear()
742
+ const end = await Promise.race([ended, sleep(0).then(() => null)])
743
+ if (Number.isFinite(end?.event?.costUsd)) finalUsd = end.event.costUsd
744
+ if (end?.ok) {
745
+ outcome = 'done'
746
+ exit = 0
747
+ } else if (end?.event?.failure === 'stopped' || stopping) {
748
+ outcome = 'stopped'
749
+ error = end?.event?.message ?? 'Stopped before it finished.'
750
+ } else if (end?.event) {
751
+ // A production whose game runs with every task's work in it, some of
752
+ // it below the critic's bar, is kept: made, but not done.
753
+ outcome = end.event.failure === 'kept' ? 'kept' : end.event.unfinished === false ? 'failed' : 'unfinished'
754
+ error = end.event.message ?? null
755
+ } else {
756
+ outcome = 'failed'
757
+ error = 'The host ended without saying how.'
758
+ }
759
+ } catch (err) {
760
+ if (err?.cantStart) {
761
+ d.err(err.message)
762
+ exit = 2
763
+ outcome = 'could not start'
764
+ } else if (err?.stopped) outcome = 'stopped'
765
+ else {
766
+ d.err(`oda make failed: ${err?.message ?? err}`)
767
+ outcome = 'failed'
768
+ }
769
+ error = err?.message ?? String(err)
770
+ } finally {
771
+ // The page's console, while the page is still there.
772
+ if (dev && chrome) {
773
+ const lines = await pageConsole(dev.request).catch(() => [])
774
+ try {
775
+ fs.writeFileSync(path.join(recordDir, 'page-console.log'), `${lines.join('\n')}${lines.length ? '\n' : ''}`)
776
+ } catch {
777
+ // no console then
778
+ }
779
+ }
780
+ // Everything the run changed, as one commit (.nowhere/ is not in git).
781
+ if (exit !== 2) {
782
+ const subject = `${outcome === 'done' ? 'make' : outcome === 'kept' ? 'make (kept below the bar)' : 'make (unfinished)'}: ${text.split('\n')[0].slice(0, 100)}`
783
+ const message = text.length > 100 || text.includes('\n') ? `${subject}\n\n${text}\n` : subject
784
+ commit = await git.autoCommit(projectRoot, message)
785
+ commit = { committed: commit.committed, sha: commit.sha ?? null, files: commit.changed?.length ?? 0, subject }
786
+ }
787
+ const chromeGone = chrome ? await chrome.kill().catch(() => null) : null
788
+ await dev?.close?.()
789
+ // Only now: a Ctrl+C before this still kills Chrome first.
790
+ d.signals.off?.('SIGINT', onSignal)
791
+ d.signals.off?.('SIGTERM', onSignal)
792
+ d.signals.off?.('SIGHUP', onSignal)
793
+ process.off('exit', killChrome)
794
+ const endedAt = d.now()
795
+ const run = {
796
+ cli: VERSION,
797
+ engine: { version: VERSION, commit: engineCommit(), agent: tree.from },
798
+ flags: {
799
+ project: options.project,
800
+ request: text,
801
+ images: options.images ?? [],
802
+ approveCost: options.approveCost ?? 0,
803
+ allowWeb: !!options.allowWeb,
804
+ allowCodex: !!options.allowCodex,
805
+ declinePaid: !!options.declinePaid,
806
+ vision: options.vision ?? 'approve',
807
+ quality: options.quality ?? null,
808
+ best: !!options.best,
809
+ ceiling: options.ceiling ?? null,
810
+ route: options.route,
811
+ maxSessions: options.maxSessions ?? null,
812
+ },
813
+ chrome: chrome ? { path: chrome.path ?? null, version: chrome.version ?? null, args: (chrome.args ?? []).map(withoutToken), exited: chromeGone } : null,
814
+ gpu: { backend, adapter },
815
+ start: startedAt.toISOString(),
816
+ end: endedAt.toISOString(),
817
+ wallSeconds: Math.round((endedAt - startedAt) / 100) / 10,
818
+ exit,
819
+ outcome,
820
+ ...(error ? { error } : {}),
821
+ productionId,
822
+ model: msg?.model ?? null,
823
+ // The host's own last figure (done or error), else its last cost event.
824
+ // A production's is by model and by role; the fast route's is one
825
+ // agent's, with what its helpers and paid generation took apart.
826
+ cost:
827
+ lastCost || finalUsd !== null
828
+ ? {
829
+ usd: finalUsd ?? lastCost?.usd ?? null,
830
+ approvedUsd: lastCost?.approvedUsd ?? null,
831
+ byModel: lastCost?.byModel ?? null,
832
+ byRole: lastCost?.byRole ?? null,
833
+ helperUsd: lastCost?.helperUsd ?? null,
834
+ generationUsd: lastCost?.generationUsd ?? null,
835
+ }
836
+ : null,
837
+ commit: { before: before?.committed ? before.sha : null, ...(commit ?? {}) },
838
+ recorded: { events: counts.events, cards: counts.cards },
839
+ }
840
+ try {
841
+ fs.writeFileSync(path.join(recordDir, 'run.json'), `${JSON.stringify(run, null, 2)}\n`)
842
+ } catch (err) {
843
+ d.err(`run.json could not be written: ${err?.message ?? err}`)
844
+ }
845
+ }
846
+
847
+ const where = path.relative(d.cwd, recordDir) || recordDir
848
+ if (reply.trim()) say(`\n${reply.trim()}\n`)
849
+ const spent = finalUsd ?? lastCost?.usd
850
+ say(`${outcome === 'done' ? 'Done' : outcome === 'could not start' ? 'Could not start' : outcome === 'kept' ? "Made, but below the critic's bar (kept)" : `Not finished (${outcome})`}${productionId ? `, production ${productionId}` : ''}${Number.isFinite(spent) ? `, ${usd(spent)} spent` : ''}. Recorded in ${where}.`)
851
+ return { exit, outcome, productionId, recordDir, report: reply.trim(), error }
852
+ }
853
+
854
+ /** Only for the checks: the pieces runMake is made of. */
855
+ export const __test = { boardLines, pageConsole, withoutToken, engineCommit, chromeEnv }