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
@@ -0,0 +1,520 @@
1
+ import { spawn as nodeSpawn } from 'node:child_process'
2
+ import fs from 'node:fs'
3
+ import os from 'node:os'
4
+ import path from 'node:path'
5
+ import { fileURLToPath } from 'node:url'
6
+
7
+ // A request run through the creator's own agent app (agentApps.cjs) rather
8
+ // than through a model the studio calls itself: Codex, Gemini CLI, Hermes
9
+ // Agent or Cursor's agent, started without a window in the project's folder,
10
+ // on whatever account the app is signed in to. The app's own agent does the
11
+ // work, with its own tools for files and commands; what it knows of Oda comes
12
+ // from the Oda MCP server (packages/cli), whose instructions and tools it
13
+ // reads. The studio shows what the app says and does, and nothing more: no
14
+ // cost (the app's account pays), no cards, none of the studio's own guard.
15
+ //
16
+ // The app must act without asking, since nobody can answer it here: Codex in
17
+ // its workspace sandbox, the others with their accept-everything switch.
18
+ //
19
+ // `node appRun.mjs --self-test` runs the commands and the parsers on
20
+ // stand-ins.
21
+
22
+ /** What the app is told before the creator's words. */
23
+ export function appNote(app, projectRoot) {
24
+ return [
25
+ `You are building an Oda space for its creator, who wrote the request below in Oda Studio. The project is the folder you are in: ${projectRoot}`,
26
+ 'Use the tools of the MCP server named oda for everything about Oda: read its instructions, start with nw_docs, check your work with nw_check and look at it with nw_view before you say it is done.',
27
+ 'Work only inside this folder. Do not publish and do not sign in unless the creator asks for it in so many words.',
28
+ "Answer in the language the creator wrote in, in a few plain sentences: what you made and where, and anything that is not working yet.",
29
+ '',
30
+ '',
31
+ ].join('\n')
32
+ }
33
+
34
+ const toml = (s) => JSON.stringify(String(s))
35
+
36
+ /**
37
+ * The command for one request: { args, env, stdin, format }. `server` is the
38
+ * Oda server as agentApps.cjs gives it ({ command, args, env: ['K=V'] }),
39
+ * which Codex is handed for this run alone, with its tools allowed; the
40
+ * others use the server Connect put in their own settings.
41
+ */
42
+ export function appCommand(app, { prompt, images = [], projectRoot }) {
43
+ const server = app.server
44
+ switch (app.id) {
45
+ case 'codex':
46
+ return {
47
+ args: [
48
+ 'exec',
49
+ '--json',
50
+ '--skip-git-repo-check',
51
+ '--sandbox',
52
+ 'workspace-write',
53
+ '-C',
54
+ projectRoot,
55
+ ...(server
56
+ ? [
57
+ '-c',
58
+ `mcp_servers.oda.command=${toml(server.command)}`,
59
+ '-c',
60
+ `mcp_servers.oda.args=[${[...server.args, '--headless'].map(toml).join(', ')}]`,
61
+ ...(server.env?.length ? ['-c', `mcp_servers.oda.env={ ${server.env.map((e) => `${e.split('=')[0]} = ${toml(e.split('=').slice(1).join('='))}`).join(', ')} }`] : []),
62
+ '-c',
63
+ 'mcp_servers.oda.default_tools_approval_mode="approve"',
64
+ ]
65
+ : []),
66
+ ...images.flatMap((file) => ['-i', file]),
67
+ // The model and reasoning step picked in the studio; none, Codex's own.
68
+ ...(app.model ? ['-m', app.model] : []),
69
+ ...(app.effort ? ['-c', `model_reasoning_effort=${toml(app.effort)}`] : []),
70
+ ],
71
+ // The request on stdin: an image list would otherwise take it for a file.
72
+ stdin: prompt,
73
+ env: {},
74
+ format: 'codex',
75
+ }
76
+ case 'gemini':
77
+ // NO_BROWSER: an ended sign-in prints its address rather than opening
78
+ // a browser window over the creator's work.
79
+ return { args: ['-y', ...(app.model ? ['-m', app.model] : []), '-p', withPictures(prompt, images)], stdin: '', env: { NO_BROWSER: 'true' }, format: 'text' }
80
+ case 'hermes':
81
+ return { args: ['chat', '-Q', '--yolo', '--source', 'tool', ...(app.model ? ['-m', app.model] : []), ...(images[0] ? ['--image', images[0]] : []), '-q', withPictures(prompt, images.slice(1))], stdin: '', env: {}, format: 'text' }
82
+ case 'cursor':
83
+ return { args: ['-p', '--output-format', 'stream-json', '--force', ...(app.model ? ['--model', app.model] : []), withPictures(prompt, images)], stdin: '', env: {}, format: 'cursor' }
84
+ default:
85
+ return null
86
+ }
87
+ }
88
+
89
+ /** An app that takes no picture is told where the creator's pictures are. */
90
+ function withPictures(prompt, images) {
91
+ if (!images.length) return prompt
92
+ return `${prompt}\n\n(The creator attached ${images.length === 1 ? 'a picture' : `${images.length} pictures`}: ${images.join(', ')}. Look at ${images.length === 1 ? 'it' : 'them'} before you start.)`
93
+ }
94
+
95
+ const ANSI = /\x1b\[[0-9;?]*[ -/]*[@-~]|\x1b\][^\x07]*\x07|\r/g
96
+ const clean = (s) => String(s).replace(ANSI, '')
97
+
98
+ /** Why a run stopped, when the app says it in words the studio knows: a
99
+ * sentence for the creator, or null. */
100
+ export function knownFailure(app, text) {
101
+ const t = clean(text)
102
+ if (/login required|Please (log|sign) in|not logged in|authenticat(e|ion) (page|required)|Waiting for auth/i.test(t)) {
103
+ return `${app.name} is not signed in on this Mac. Sign in there (run ${path.basename(app.command)} in a terminal), then send the request again.`
104
+ }
105
+ if (/Incorrect API key|invalid api key|HTTP 401|401 Unauthorized/i.test(t)) return `${app.name} has no working model account. Set it up in ${app.name} itself, then send the request again.`
106
+ if (/usage limit|quota|rate limit|out of credits|credit balance|HTTP 429/i.test(t)) return `${app.name} is out of usage for now. Wait for its limit to reset, or choose another way to build in Settings.`
107
+ return null
108
+ }
109
+
110
+ /**
111
+ * Reads what the app prints and tells it as the studio's own events (without
112
+ * the run's id, which the host adds): text, tool, tool-result. Returns
113
+ * { push(chunk), end() -> { turns, error, said } }.
114
+ */
115
+ export function createParser(format, emit) {
116
+ let rest = ''
117
+ let turns = 0
118
+ let error = null
119
+ let said = false
120
+ let seq = 0
121
+ const text = (delta) => {
122
+ if (!delta) return
123
+ said = true
124
+ emit({ type: 'text', delta })
125
+ }
126
+ const lineOf = {
127
+ // codex exec --json: one event a line.
128
+ codex(line) {
129
+ let event
130
+ try {
131
+ event = JSON.parse(line)
132
+ } catch {
133
+ return
134
+ }
135
+ const item = event?.item
136
+ if (event?.type === 'turn.completed') turns++
137
+ else if (event?.type === 'error' || event?.type === 'turn.failed') error = String(event?.message ?? event?.error?.message ?? 'Codex stopped with an error.')
138
+ else if (item?.type === 'agent_message' && event.type === 'item.completed') text(`${String(item.text ?? '').trim()}\n\n`)
139
+ else if (item?.type === 'mcp_tool_call' || item?.type === 'command_execution' || item?.type === 'file_change' || item?.type === 'web_search') {
140
+ const toolId = String(item.id ?? `app-${seq++}`)
141
+ const name = item.type === 'mcp_tool_call' ? String(item.tool ?? 'tool') : item.type === 'command_execution' ? 'Bash' : item.type === 'file_change' ? 'Write' : 'WebSearch'
142
+ if (event.type === 'item.started') {
143
+ const input = item.type === 'mcp_tool_call' ? parsed(item.arguments) : item.type === 'command_execution' ? { command: String(item.command ?? '') } : item.type === 'file_change' ? { file_path: String(item.changes?.[0]?.path ?? '') } : { query: String(item.query ?? '') }
144
+ emit({ type: 'tool', toolId, name, input })
145
+ } else if (event.type === 'item.completed') {
146
+ emit({ type: 'tool-result', toolId, name, isError: item.status === 'failed' || (typeof item.exit_code === 'number' && item.exit_code !== 0) })
147
+ }
148
+ }
149
+ },
150
+ // cursor-agent --output-format stream-json: one event a line.
151
+ cursor(line) {
152
+ let event
153
+ try {
154
+ event = JSON.parse(line)
155
+ } catch {
156
+ return
157
+ }
158
+ if (event?.type === 'assistant') {
159
+ for (const part of event.message?.content ?? []) if (part?.type === 'text') text(String(part.text ?? ''))
160
+ } else if (event?.type === 'tool_call') {
161
+ const toolId = String(event.call_id ?? `app-${seq++}`)
162
+ const kind = Object.keys(event.tool_call ?? {})[0] ?? 'tool'
163
+ const call = event.tool_call?.[kind] ?? {}
164
+ const name = /shell/i.test(kind) ? 'Bash' : /write|edit/i.test(kind) ? 'Write' : /read/i.test(kind) ? 'Read' : String(call.args?.toolName ?? call.args?.name ?? kind)
165
+ if (event.subtype === 'started') emit({ type: 'tool', toolId, name, input: call.args && typeof call.args === 'object' ? call.args : {} })
166
+ else if (event.subtype === 'completed') emit({ type: 'tool-result', toolId, name, isError: !!call.result?.error })
167
+ } else if (event?.type === 'result') {
168
+ turns++
169
+ if (event.is_error) error = String(event.result ?? 'Cursor stopped with an error.')
170
+ else if (!said) text(String(event.result ?? ''))
171
+ }
172
+ },
173
+ // Plain words (Gemini CLI, Hermes): each line as it comes. Hermes ends
174
+ // with its session's id, which is not the creator's to read.
175
+ text(line) {
176
+ const t = clean(line)
177
+ if (/^\s*session_id:\s*\S+\s*$/.test(t)) return
178
+ text(`${t}\n`)
179
+ },
180
+ }
181
+ const each = lineOf[format] ?? lineOf.text
182
+ return {
183
+ push(chunk) {
184
+ rest += String(chunk)
185
+ let at
186
+ while ((at = rest.indexOf('\n')) >= 0) {
187
+ const line = rest.slice(0, at)
188
+ rest = rest.slice(at + 1)
189
+ if (line.trim() || format === 'text') each(line)
190
+ }
191
+ },
192
+ end() {
193
+ if (rest.trim()) each(rest)
194
+ rest = ''
195
+ if (format === 'text' && said) turns = Math.max(turns, 1)
196
+ return { turns, error, said }
197
+ },
198
+ }
199
+ }
200
+
201
+ function parsed(json) {
202
+ if (json && typeof json === 'object') return json
203
+ try {
204
+ const value = JSON.parse(String(json ?? '{}'))
205
+ return value && typeof value === 'object' ? value : {}
206
+ } catch {
207
+ return {}
208
+ }
209
+ }
210
+
211
+ /** The environment an app runs in: the studio's, without any vendor's key
212
+ * (the app is to use its own sign-in, not a key the studio happens to
213
+ * hold), with the usual places on PATH that a Finder launch lacks, and told
214
+ * that the Oda server it starts is to keep its preview without a window. */
215
+ export function appEnv(base, extra = {}) {
216
+ const env = {}
217
+ for (const [name, value] of Object.entries(base ?? {})) {
218
+ if (/^(ANTHROPIC|OPENAI|GEMINI|GOOGLE|XAI|DEEPSEEK|CODEX|CURSOR)_.*(KEY|TOKEN|BASE_URL)$/.test(name)) continue
219
+ if (typeof value === 'string') env[name] = value
220
+ }
221
+ const home = env.HOME || os.homedir()
222
+ env.PATH = [path.join(home, '.local', 'bin'), '/opt/homebrew/bin', '/usr/local/bin', '/usr/bin', '/bin', env.PATH ?? ''].filter(Boolean).join(':')
223
+ return { ...env, ODA_MCP_HEADLESS: '1', ...extra }
224
+ }
225
+
226
+ /** Takes this process's own mark away (the host, when the studio quits
227
+ * mid-run and no run's finally gets to). */
228
+ export function clearRunMarker(env = process.env) {
229
+ try {
230
+ const file = runMarkerFile(env)
231
+ if (JSON.parse(fs.readFileSync(file, 'utf8')).pid === process.pid) fs.rmSync(file, { force: true })
232
+ } catch {
233
+ // None, or another studio's.
234
+ }
235
+ }
236
+
237
+ /** Where the studio says a run through an app is going on in a project, so
238
+ * the Oda server that app starts keeps its preview in headless Chrome and
239
+ * opens no browser window over the creator's work (packages/cli reads it:
240
+ * not every app hands its environment on to the servers it starts). */
241
+ export function runMarkerFile(env = process.env) {
242
+ return path.join(env.NOWHERE_CONFIG_DIR || path.join(env.HOME || os.homedir(), '.config', 'nowhere'), 'studio-run.json')
243
+ }
244
+
245
+ /**
246
+ * Runs one request through the app. emit(event) gets text, tool and
247
+ * tool-result events; onChild(stop) gets a way to stop it. Resolves to
248
+ * { ok, turns } or { ok: false, turns, error, stopped }.
249
+ */
250
+ export async function runAgentApp({ app, prompt, images = [], projectRoot, env = process.env, emit, onChild, spawn = nodeSpawn, marker = runMarkerFile(env) }) {
251
+ const command = appCommand(app, { prompt, images, projectRoot })
252
+ if (!command) return { ok: false, turns: 0, error: `The studio does not know how to build through ${app?.name ?? 'this app'}.` }
253
+ const mark = JSON.stringify({ project: projectRoot, at: Date.now(), pid: process.pid })
254
+ try {
255
+ fs.mkdirSync(path.dirname(marker), { recursive: true })
256
+ fs.writeFileSync(marker, mark)
257
+ } catch {
258
+ // Without it an app that drops the environment gets a browser preview.
259
+ }
260
+ const parser = createParser(command.format, emit)
261
+ // The end of what it printed: errTail from its error stream alone, tail
262
+ // from both (an app that prints plain words says its errors among them).
263
+ let tail = ''
264
+ let errTail = ''
265
+ let stopped = false
266
+ let failure = null
267
+ try {
268
+ const code = await new Promise((resolve) => {
269
+ let child
270
+ try {
271
+ // Its own process group: stopping it takes the servers it started too.
272
+ child = spawn(app.command, command.args, { cwd: projectRoot, env: appEnv(env, command.env), stdio: ['pipe', 'pipe', 'pipe'], detached: true })
273
+ } catch (err) {
274
+ failure = `${app.name} could not be started (${err?.message ?? err}).`
275
+ return resolve(1)
276
+ }
277
+ const signal = (name) => {
278
+ try {
279
+ process.kill(-child.pid, name)
280
+ } catch {
281
+ try {
282
+ child.kill(name)
283
+ } catch {
284
+ // Already gone.
285
+ }
286
+ }
287
+ }
288
+ let hard = null
289
+ const stop = () => {
290
+ signal('SIGTERM')
291
+ // An app that does not go when asked is made to.
292
+ hard ??= setTimeout(() => signal('SIGKILL'), 5000)
293
+ hard.unref?.()
294
+ }
295
+ onChild?.(() => {
296
+ stopped = true
297
+ stop()
298
+ })
299
+ // Whole characters, never half of one at the end of a chunk.
300
+ child.stdout.setEncoding?.('utf8')
301
+ child.stderr.setEncoding?.('utf8')
302
+ child.stdout.on('data', (chunk) => {
303
+ tail = (tail + String(chunk)).slice(-4000)
304
+ parser.push(chunk)
305
+ })
306
+ child.stderr.on('data', (chunk) => {
307
+ tail = (tail + String(chunk)).slice(-4000)
308
+ errTail = (errTail + String(chunk)).slice(-4000)
309
+ // Nobody is there to sign in: said at once, rather than waited out.
310
+ // Only on its error stream: its answer may well say these words.
311
+ if (!failure && /login required|Waiting for auth/i.test(String(chunk))) {
312
+ failure = knownFailure(app, String(chunk))
313
+ stop()
314
+ }
315
+ })
316
+ child.on('error', (err) => {
317
+ failure ??= `${app.name} could not be started (${err?.message ?? err}).`
318
+ resolve(1)
319
+ })
320
+ child.on('close', (c) => {
321
+ clearTimeout(hard)
322
+ // Whatever it started and left behind (its servers, their Chrome) goes with it.
323
+ signal('SIGTERM')
324
+ resolve(c ?? 1)
325
+ })
326
+ child.stdin.on('error', () => {})
327
+ child.stdin.end(command.stdin ?? '')
328
+ })
329
+ const read = parser.end()
330
+ if (stopped) return { ok: false, turns: read.turns, stopped: true, error: 'Stopped before it finished.' }
331
+ if (code === 0 && !read.error && !failure) return { ok: true, turns: Math.max(1, read.turns) }
332
+ const lastLine = clean(tail).split('\n').map((l) => l.trim()).filter(Boolean).pop() ?? ''
333
+ // Why, from what the app itself said of the failure: its error event and
334
+ // its error stream, and for an app that prints plain words, those too.
335
+ // Never from the words of its answer in a stream of events.
336
+ const said = command.format === 'text' ? tail : errTail
337
+ const error = failure ?? knownFailure(app, `${read.error ?? ''}\n${said}`) ?? `${app.name} stopped before it finished${read.error || lastLine ? `: ${(read.error ?? lastLine).slice(0, 300)}` : '.'}`
338
+ return { ok: false, turns: read.turns, error }
339
+ } finally {
340
+ try {
341
+ if (fs.readFileSync(marker, 'utf8') === mark) fs.rmSync(marker, { force: true })
342
+ } catch {
343
+ // Already gone.
344
+ }
345
+ }
346
+ }
347
+
348
+ // ---------------------------------------------------------------- self-test
349
+
350
+ async function selfTest() {
351
+ const { EventEmitter } = await import('node:events')
352
+ let failures = 0
353
+ const check = (label, pass, detail) => {
354
+ console.log(`${pass ? 'PASS' : 'FAIL'} ${label}`)
355
+ if (!pass) {
356
+ failures++
357
+ if (detail !== undefined) console.log(' ', JSON.stringify(detail))
358
+ }
359
+ }
360
+ const server = { command: '/opt/homebrew/bin/node', args: ['/repo/cli.mjs', 'mcp'], env: [] }
361
+ const codex = { id: 'codex', name: 'Codex', command: '/x/codex', server }
362
+
363
+ let c = appCommand(codex, { prompt: 'make a sea', images: ['/tmp/a.png'], projectRoot: '/p' })
364
+ check('1. Codex: exec as JSON lines in the workspace sandbox, the request on stdin, the picture attached', c.args.slice(0, 7).join(' ') === 'exec --json --skip-git-repo-check --sandbox workspace-write -C /p' && c.stdin === 'make a sea' && c.args.slice(-2).join(' ') === '-i /tmp/a.png' && c.format === 'codex', c.args)
365
+ check('2. ...with the Oda server for this run alone, headless, its tools allowed', c.args.includes('mcp_servers.oda.command="/opt/homebrew/bin/node"') && c.args.includes('mcp_servers.oda.args=["/repo/cli.mjs", "mcp", "--headless"]') && c.args.includes('mcp_servers.oda.default_tools_approval_mode="approve"'), c.args)
366
+ c = appCommand({ ...codex, server: { ...server, env: ['ELECTRON_RUN_AS_NODE=1'] } }, { prompt: 'x', projectRoot: '/p' })
367
+ check('3. ...and its environment when it runs on Electron', c.args.includes('mcp_servers.oda.env={ ELECTRON_RUN_AS_NODE = "1" }'), c.args)
368
+ c = appCommand({ id: 'gemini', name: 'Gemini', command: 'gemini' }, { prompt: 'make a sea', images: ['/tmp/a.png'], projectRoot: '/p' })
369
+ check('4. Gemini: accepts every action, opens no browser, and is told where the picture is', c.args[0] === '-y' && c.args[1] === '-p' && /attached a picture: \/tmp\/a\.png/.test(c.args[2]) && c.env.NO_BROWSER === 'true' && c.format === 'text', c)
370
+ c = appCommand({ id: 'hermes', name: 'Hermes', command: 'hermes' }, { prompt: 'make a sea', images: ['/tmp/a.png', '/tmp/b.png'], projectRoot: '/p' })
371
+ check('5. Hermes: quiet, one picture attached and the rest named', c.args.slice(0, 7).join(' ') === 'chat -Q --yolo --source tool --image /tmp/a.png' && c.args[7] === '-q' && /attached a picture: \/tmp\/b\.png/.test(c.args[8]), c.args)
372
+ c = appCommand({ id: 'cursor', name: 'Cursor', command: 'cursor-agent' }, { prompt: 'make a sea', projectRoot: '/p' })
373
+ check('6. Cursor: printed as JSON lines, commands allowed', c.args.join(' ') === '-p --output-format stream-json --force make a sea' && c.format === 'cursor')
374
+ check('7. an app the studio does not know has no command', appCommand({ id: 'other' }, { prompt: 'x', projectRoot: '/p' }) === null)
375
+
376
+ const seen = []
377
+ let p = createParser('codex', (e) => seen.push(e))
378
+ const lines = [
379
+ { type: 'thread.started', thread_id: 't' },
380
+ { type: 'item.completed', item: { id: 'i0', type: 'agent_message', text: 'Looking first.\n' } },
381
+ { type: 'item.started', item: { id: 'i1', type: 'mcp_tool_call', server: 'oda', tool: 'nw_view', arguments: '{"view":"player"}', status: 'in_progress' } },
382
+ { type: 'item.completed', item: { id: 'i1', type: 'mcp_tool_call', server: 'oda', tool: 'nw_view', status: 'completed' } },
383
+ { type: 'item.started', item: { id: 'i2', type: 'command_execution', command: 'ls', status: 'in_progress' } },
384
+ { type: 'item.completed', item: { id: 'i2', type: 'command_execution', command: 'ls', exit_code: 2, status: 'completed' } },
385
+ { type: 'item.started', item: { id: 'i3', type: 'file_change', changes: [{ path: '/p/src/game.ts', kind: 'update' }], status: 'in_progress' } },
386
+ { type: 'item.completed', item: { id: 'i3', type: 'file_change', status: 'completed' } },
387
+ { type: 'item.completed', item: { id: 'i4', type: 'agent_message', text: 'Done.' } },
388
+ { type: 'turn.completed', usage: {} },
389
+ ]
390
+ const whole = lines.map((l) => JSON.stringify(l)).join('\n') + '\n'
391
+ p.push(whole.slice(0, 137))
392
+ p.push(whole.slice(137))
393
+ let end = p.end()
394
+ check('8. Codex events, split anywhere: its words, then each tool by the name the chat knows', JSON.stringify(seen.map((e) => (e.type === 'text' ? e.delta : `${e.type}:${e.name}${e.isError ? '!' : ''}`))) === JSON.stringify(['Looking first.\n\n', 'tool:nw_view', 'tool-result:nw_view', 'tool:Bash', 'tool-result:Bash!', 'tool:Write', 'tool-result:Write', 'Done.\n\n']), seen)
395
+ check('9. ...a tool\'s arguments read, the edited file named, one turn counted', seen[1].input.view === 'player' && seen[5].input.file_path === '/p/src/game.ts' && end.turns === 1 && end.error === null && end.said === true, end)
396
+ p = createParser('codex', () => {})
397
+ p.push('{"type":"turn.failed","error":{"message":"usage limit reached"}}\n')
398
+ check('10. a turn that failed keeps its reason', p.end().error === 'usage limit reached')
399
+
400
+ const words = []
401
+ p = createParser('text', (e) => words.push(e.delta))
402
+ p.push('\x1b[32mI made a sea.\x1b[0m\nIt is lit from the west.\n\nsession_id: 20261115_004429_856cc1\n')
403
+ end = p.end()
404
+ check('11. plain words: colour codes off, the session line left out', words.join('') === 'I made a sea.\nIt is lit from the west.\n\n' && end.turns === 1, words)
405
+
406
+ const cur = []
407
+ p = createParser('cursor', (e) => cur.push(e))
408
+ p.push([{ type: 'system', subtype: 'init' }, { type: 'assistant', message: { content: [{ type: 'text', text: 'On it.' }] } }, { type: 'tool_call', subtype: 'started', call_id: 'c1', tool_call: { shellToolCall: { args: { command: 'ls' } } } }, { type: 'tool_call', subtype: 'completed', call_id: 'c1', tool_call: { shellToolCall: { result: { success: {} } } } }, { type: 'result', subtype: 'success', is_error: false, result: 'On it.' }].map((l) => JSON.stringify(l)).join('\n') + '\n')
409
+ end = p.end()
410
+ check('12. Cursor events: words once, the shell as Bash, the result not said twice', JSON.stringify(cur.map((e) => (e.type === 'text' ? e.delta : `${e.type}:${e.name}`))) === JSON.stringify(['On it.', 'tool:Bash', 'tool-result:Bash']) && end.turns === 1, cur)
411
+
412
+ const env = appEnv({ HOME: '/h', PATH: '/usr/bin', OPENAI_API_KEY: 'k', ANTHROPIC_API_KEY: 'k', GEMINI_API_KEY: 'k', MESHY_API_KEY: 'm', OPENAI_BASE_URL: 'u' }, { NO_BROWSER: 'true' })
413
+ check('13. the app gets no vendor key of the studio\'s, a PATH with the usual places, and the headless word', !('OPENAI_API_KEY' in env) && !('ANTHROPIC_API_KEY' in env) && !('GEMINI_API_KEY' in env) && !('OPENAI_BASE_URL' in env) && env.MESHY_API_KEY === 'm' && env.PATH.startsWith('/h/.local/bin:/opt/homebrew/bin') && env.ODA_MCP_HEADLESS === '1' && env.NO_BROWSER === 'true', env)
414
+
415
+ // The runner, on a stand-in for the app's process.
416
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'apprun-'))
417
+ const marker = path.join(dir, 'studio-run.json')
418
+ const fake = (script) => (file, args, opts) => {
419
+ const child = new EventEmitter()
420
+ child.pid = 999999
421
+ child.stdout = new EventEmitter()
422
+ child.stderr = new EventEmitter()
423
+ child.stdin = Object.assign(new EventEmitter(), { end: (text) => (child.typed = text) })
424
+ child.kill = () => setImmediate(() => child.emit('close', 143))
425
+ child.spawned = { file, args, opts }
426
+ setImmediate(() => script(child))
427
+ fake.last = child
428
+ return child
429
+ }
430
+ const out = []
431
+ let r = await runAgentApp({
432
+ app: codex,
433
+ prompt: 'make a sea',
434
+ projectRoot: dir,
435
+ env: { HOME: dir, PATH: '/usr/bin' },
436
+ marker,
437
+ emit: (e) => out.push(e),
438
+ spawn: fake((child) => {
439
+ fake.markDuring = fs.existsSync(marker) ? JSON.parse(fs.readFileSync(marker, 'utf8')).project : null
440
+ child.stdout.emit('data', whole)
441
+ child.emit('close', 0)
442
+ }),
443
+ })
444
+ check('14. a run that ends well: ok, its events passed on, the request typed, in the project and its own group', r.ok === true && r.turns === 1 && out.length === 8 && fake.last.typed === 'make a sea' && fake.last.spawned.opts.cwd === dir && fake.last.spawned.opts.detached === true, { r, n: out.length })
445
+ check('15. ...the run was marked for the server while it went on, and the mark is gone after', fake.markDuring === dir && !fs.existsSync(marker))
446
+ r = await runAgentApp({
447
+ app: { id: 'gemini', name: 'Gemini', command: '/x/gemini' },
448
+ prompt: 'x',
449
+ projectRoot: dir,
450
+ env: { HOME: dir },
451
+ marker,
452
+ emit: () => {},
453
+ spawn: fake((child) => child.stderr.emit('data', 'Code Assist login required.\nAttempting to open authentication page in your browser.\n')),
454
+ })
455
+ check('16. an app that wants a sign-in is stopped at once and said', r.ok === false && /Gemini is not signed in on this Mac/.test(r.error), r)
456
+ const kept = []
457
+ r = await runAgentApp({
458
+ app: codex,
459
+ prompt: 'x',
460
+ projectRoot: dir,
461
+ env: { HOME: dir },
462
+ marker,
463
+ emit: (e) => kept.push(e),
464
+ spawn: fake((child) => {
465
+ child.stdout.emit('data', `${JSON.stringify({ type: 'item.completed', item: { id: 'i0', type: 'agent_message', text: 'The page says login required, and its quota is shown.' } })}\n${JSON.stringify({ type: 'turn.completed' })}\n`)
466
+ child.emit('close', 0)
467
+ }),
468
+ })
469
+ check('16b. the same words in the app\'s answer stop nothing', r.ok === true && kept.length === 1, r)
470
+ r = await runAgentApp({
471
+ app: { id: 'hermes', name: 'Hermes', command: '/x/hermes' },
472
+ prompt: 'x',
473
+ projectRoot: dir,
474
+ env: { HOME: dir },
475
+ marker,
476
+ emit: () => {},
477
+ spawn: fake((child) => {
478
+ child.stdout.emit('data', 'Error: HTTP 401: Incorrect API key provided: no-key-r***ired.\n\nsession_id: 1\n')
479
+ child.emit('close', 1)
480
+ }),
481
+ })
482
+ check('17. an app with no working model account says so, not its raw error', r.ok === false && /Hermes has no working model account/.test(r.error), r)
483
+ let stop = null
484
+ const stopping = runAgentApp({ app: codex, prompt: 'x', projectRoot: dir, env: { HOME: dir }, marker, emit: () => {}, onChild: (s) => (stop = s), spawn: fake(() => {}) })
485
+ await new Promise((resolve) => setImmediate(resolve))
486
+ const kill = process.kill
487
+ process.kill = () => {
488
+ throw new Error('no such group')
489
+ }
490
+ stop()
491
+ process.kill = kill
492
+ r = await stopping
493
+ check('18. Stop ends the app and is told as a stop', r.ok === false && r.stopped === true, r)
494
+ r = await runAgentApp({ app: codex, prompt: 'x', projectRoot: dir, env: { HOME: dir }, marker, emit: () => {}, spawn: fake((child) => {
495
+ child.stderr.emit('data', 'thread panicked at main.rs\n')
496
+ child.emit('close', 101)
497
+ }) })
498
+ check('19. any other end says the app\'s last line', r.ok === false && /Codex stopped before it finished: thread panicked at main\.rs/.test(r.error), r)
499
+
500
+ fs.rmSync(dir, { recursive: true, force: true })
501
+ // The model and effort picked in the studio go with each app's own flags.
502
+ c = appCommand({ ...codex, model: 'gpt-a', effort: 'high' }, { prompt: 'x', projectRoot: '/p' })
503
+ check('20. Codex is given the picked model and reasoning step', c.args.join(' ').includes('-m gpt-a') && c.args.includes('model_reasoning_effort="high"'), c.args)
504
+ const plain = appCommand(codex, { prompt: 'x', projectRoot: '/p' })
505
+ check('21. ...and nothing of either with no pick (its own setting)', !plain.args.includes('-m') && !plain.args.some((a) => /model_reasoning_effort/.test(a)), plain.args)
506
+ const g = appCommand({ id: 'gemini', name: 'Gemini', command: 'gemini', model: 'gemini-2.5-flash' }, { prompt: 'x', projectRoot: '/p' })
507
+ const h = appCommand({ id: 'hermes', name: 'Hermes', command: 'hermes', model: 'm1' }, { prompt: 'x', projectRoot: '/p' })
508
+ const cu = appCommand({ id: 'cursor', name: 'Cursor', command: 'cursor-agent', model: 'm2' }, { prompt: 'x', projectRoot: '/p' })
509
+ check('22. Gemini, Hermes and Cursor are given the picked model their own way', g.args.join(' ').includes('-m gemini-2.5-flash') && h.args.join(' ').includes('-m m1') && cu.args.join(' ').includes('--model m2'), { g: g.args, h: h.args, cu: cu.args })
510
+
511
+ console.log(failures === 0 ? '\nall checks passed' : `\n${failures} check(s) failed`)
512
+ process.exit(failures === 0 ? 0 : 1)
513
+ }
514
+
515
+ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url) && process.argv.includes('--self-test')) {
516
+ selfTest().catch((err) => {
517
+ console.error(err)
518
+ process.exit(1)
519
+ })
520
+ }