oda-engine 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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 +131 -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-CptQkDVX.js +1 -0
  197. package/web-dist/assets/KTX2Loader-C53LJqss.js +2 -0
  198. package/web-dist/assets/SPZLoader-BQ3tjaTv.js +1 -0
  199. package/web-dist/assets/gaussianSplat-_9tcWegB.js +1 -0
  200. package/web-dist/assets/index-Baka-ZO7.js +693 -0
  201. package/web-dist/assets/index-CcjyyQco.css +1 -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,602 @@
1
+ // The build agent for every model that is not Claude.
2
+ //
3
+ // Claude runs in its own harness (the Agent SDK, agent/host.mjs). Any other
4
+ // vendor's model runs here: one loop that offers the same powers under plain
5
+ // names (read, write and edit files, list, search, run a command, and the
6
+ // studio's own tools from the registry in agent/tools, browser and computer
7
+ // included), speaks the vendor's API, and reports through the same events,
8
+ // so the chat cannot tell which loop is behind it. The host's guard, cost
9
+ // ledger and stop gate reach it through `hooks`. The API shapes come from
10
+ // each vendor's own reference (2026-10-13): the Responses API for OpenAI and
11
+ // xAI, Chat Completions for DeepSeek, generateContent for Gemini.
12
+
13
+ import { exec } from 'node:child_process'
14
+ import fsp from 'node:fs/promises'
15
+ import path from 'node:path'
16
+ import { runDef, toVendorSpec } from './agent/tools/index.mjs'
17
+
18
+ /** Files and folders the agent's listing and search pass over: dependencies,
19
+ * history and the studio's own scratch space are nobody's source. */
20
+ const SKIP_DIRS = new Set(['node_modules', '.git', '.nowhere', 'dist'])
21
+ const BINARY = /\.(glb|gltf|bin|png|jpe?g|webp|gif|ktx2|hdr|exr|fbx|obj|stl|ply|dae|3mf|splat|mp3|wav|ogg|mp4|zip|ico|woff2?)$/i
22
+ const MAX_READ_BYTES = 2_000_000
23
+ const MAX_TOOL_TEXT = 40_000
24
+ const COMMAND_TIMEOUT_MS = 120_000
25
+
26
+ // ---------------------------------------------------------------- tools
27
+
28
+ /** The tools, provider-neutral: name, description, JSON Schema. The plain
29
+ * file tools and the shell are this loop's own; everything else comes from
30
+ * the registry's defs. */
31
+ function toolSpecs({ shell, defs = [] }) {
32
+ const str = (description) => ({ type: 'string', description })
33
+ const specs = [
34
+ {
35
+ name: 'read_file',
36
+ description: 'Reads a text file in the project and returns it with line numbers. Use offset and limit for long files.',
37
+ parameters: {
38
+ type: 'object',
39
+ properties: {
40
+ path: str('Path relative to the project root, e.g. src/main.ts.'),
41
+ offset: { type: 'integer', description: 'First line to return, counting from 1.' },
42
+ limit: { type: 'integer', description: 'How many lines to return (default 2000).' },
43
+ },
44
+ required: ['path'],
45
+ },
46
+ },
47
+ {
48
+ name: 'write_file',
49
+ description: 'Writes a whole file in the project, creating folders as needed. Replaces the file if it exists; read it first.',
50
+ parameters: {
51
+ type: 'object',
52
+ properties: { path: str('Path relative to the project root.'), content: str('The complete new contents.') },
53
+ required: ['path', 'content'],
54
+ },
55
+ },
56
+ {
57
+ name: 'edit_file',
58
+ description:
59
+ 'Replaces one exact piece of text in a file. old_string must appear exactly once unless replace_all is true; include enough surrounding lines to make it unique.',
60
+ parameters: {
61
+ type: 'object',
62
+ properties: {
63
+ path: str('Path relative to the project root.'),
64
+ old_string: str('The exact text to replace, whitespace included.'),
65
+ new_string: str('The text to put in its place.'),
66
+ replace_all: { type: 'boolean', description: 'Replace every occurrence instead of exactly one.' },
67
+ },
68
+ required: ['path', 'old_string', 'new_string'],
69
+ },
70
+ },
71
+ {
72
+ name: 'list_files',
73
+ description: 'Lists project files matching a glob pattern such as src/**/*.ts (default: every file).',
74
+ parameters: { type: 'object', properties: { pattern: str('Glob pattern relative to the project root.') } },
75
+ },
76
+ {
77
+ name: 'search',
78
+ description: 'Searches the project\'s text files for a regular expression and returns matching lines as path:line: text.',
79
+ parameters: {
80
+ type: 'object',
81
+ properties: { pattern: str('JavaScript regular expression.'), glob: str('Only search files matching this glob.') },
82
+ required: ['pattern'],
83
+ },
84
+ },
85
+ ]
86
+ if (shell) {
87
+ specs.push({
88
+ name: 'run_command',
89
+ description: 'Runs a shell command in the project folder (two minute limit) and returns its output.',
90
+ parameters: { type: 'object', properties: { command: str('The command line.') }, required: ['command'] },
91
+ })
92
+ }
93
+ specs.push(...defs.map(toVendorSpec))
94
+ return specs
95
+ }
96
+
97
+ const trimText = (text) => (text.length > MAX_TOOL_TEXT ? `${text.slice(0, MAX_TOOL_TEXT)}\n… (cut at ${MAX_TOOL_TEXT} characters)` : text)
98
+
99
+ /** A glob as a regular expression over forward-slashed relative paths. */
100
+ function globRegex(glob) {
101
+ let out = ''
102
+ for (let i = 0; i < glob.length; i++) {
103
+ const c = glob[i]
104
+ if (c === '*' && glob[i + 1] === '*') {
105
+ out += '.*'
106
+ i++
107
+ if (glob[i + 1] === '/') i++
108
+ } else if (c === '*') out += '[^/]*'
109
+ else if (c === '?') out += '[^/]'
110
+ else out += c.replace(/[.+^${}()|[\]\\]/g, '\\$&')
111
+ }
112
+ return new RegExp(`^${out}$`)
113
+ }
114
+
115
+ async function walk(root, rel = '', out = []) {
116
+ let entries = []
117
+ try {
118
+ entries = await fsp.readdir(path.join(root, rel), { withFileTypes: true })
119
+ } catch {
120
+ return out
121
+ }
122
+ for (const e of entries) {
123
+ if (SKIP_DIRS.has(e.name) || e.name === '.DS_Store') continue
124
+ const child = rel ? `${rel}/${e.name}` : e.name
125
+ if (e.isDirectory()) await walk(root, child, out)
126
+ else if (e.isFile()) out.push(child)
127
+ if (out.length > 20_000) break
128
+ }
129
+ return out
130
+ }
131
+
132
+ /**
133
+ * Runs one tool call. Returns { text, images?, isError }, images being
134
+ * [{ data (base64), mime }]. Paths never leave the
135
+ * project (`inside` is the host's containment check), and .git is never
136
+ * written: the studio commits, not the agent. A registry tool runs through
137
+ * runDef with the host's ToolCtx (`toolCtx`).
138
+ */
139
+ async function runTool(name, args, ctx) {
140
+ const { projectRoot, inside, defs = [], toolCtx } = ctx
141
+ const fail = (text) => ({ text, isError: true })
142
+ const resolve = (p) => {
143
+ if (typeof p !== 'string' || !p.trim()) throw new Error('path is required')
144
+ const abs = path.resolve(projectRoot, p)
145
+ if (!inside(projectRoot, abs)) throw new Error(`${p} is outside the project. Only read and write inside the open project.`)
146
+ return abs
147
+ }
148
+ try {
149
+ switch (name) {
150
+ case 'read_file': {
151
+ const abs = resolve(args.path)
152
+ const stat = await fsp.stat(abs)
153
+ if (stat.size > MAX_READ_BYTES) return fail(`${args.path} is ${stat.size} bytes, too large to read.`)
154
+ if (BINARY.test(abs)) return fail(`${args.path} is a binary file.`)
155
+ const lines = (await fsp.readFile(abs, 'utf8')).split('\n')
156
+ const from = Math.max(1, Number(args.offset) || 1)
157
+ const count = Math.max(1, Number(args.limit) || 2000)
158
+ const slice = lines.slice(from - 1, from - 1 + count)
159
+ const body = slice.map((l, i) => `${from + i}\t${l.length > 2000 ? `${l.slice(0, 2000)}…` : l}`).join('\n')
160
+ const rest = lines.length > from - 1 + count ? `\n… ${lines.length - (from - 1 + count)} more lines` : ''
161
+ return { text: trimText(body + rest) }
162
+ }
163
+ case 'write_file': {
164
+ const abs = resolve(args.path)
165
+ if (abs.split(path.sep).includes('.git')) return fail('The project history is the studio\'s; .git is not written.')
166
+ if (typeof args.content !== 'string') return fail('content must be a string')
167
+ await fsp.mkdir(path.dirname(abs), { recursive: true })
168
+ await fsp.writeFile(abs, args.content, 'utf8')
169
+ return { text: `Wrote ${args.path} (${args.content.split('\n').length} lines).` }
170
+ }
171
+ case 'edit_file': {
172
+ const abs = resolve(args.path)
173
+ if (typeof args.old_string !== 'string' || typeof args.new_string !== 'string') return fail('old_string and new_string must be strings')
174
+ if (args.old_string === '') return fail('old_string must not be empty; use write_file to create a file.')
175
+ const text = await fsp.readFile(abs, 'utf8')
176
+ const count = text.split(args.old_string).length - 1
177
+ if (count === 0) return fail(`old_string was not found in ${args.path}. Read the file and copy the text exactly.`)
178
+ if (count > 1 && !args.replace_all) return fail(`old_string appears ${count} times in ${args.path}. Include more surrounding text, or set replace_all.`)
179
+ const next = args.replace_all ? text.split(args.old_string).join(args.new_string) : text.replace(args.old_string, () => args.new_string)
180
+ await fsp.writeFile(abs, next, 'utf8')
181
+ return { text: `Edited ${args.path} (${args.replace_all ? count : 1} replacement${count > 1 && args.replace_all ? 's' : ''}).` }
182
+ }
183
+ case 'list_files': {
184
+ const re = globRegex(typeof args.pattern === 'string' && args.pattern ? args.pattern : '**')
185
+ const files = (await walk(projectRoot)).filter((f) => re.test(f))
186
+ return { text: files.length ? trimText(files.slice(0, 1000).join('\n') + (files.length > 1000 ? `\n… ${files.length - 1000} more` : '')) : 'No files match.' }
187
+ }
188
+ case 'search': {
189
+ let re
190
+ try {
191
+ re = new RegExp(args.pattern)
192
+ } catch (err) {
193
+ return fail(`Not a valid regular expression: ${err.message}`)
194
+ }
195
+ const only = typeof args.glob === 'string' && args.glob ? globRegex(args.glob) : null
196
+ const hits = []
197
+ for (const f of await walk(projectRoot)) {
198
+ if (BINARY.test(f) || (only && !only.test(f))) continue
199
+ const abs = path.join(projectRoot, f)
200
+ let text
201
+ try {
202
+ if ((await fsp.stat(abs)).size > 1_000_000) continue
203
+ text = await fsp.readFile(abs, 'utf8')
204
+ } catch {
205
+ continue
206
+ }
207
+ text.split('\n').forEach((line, i) => {
208
+ if (hits.length < 300 && re.test(line)) hits.push(`${f}:${i + 1}: ${line.slice(0, 300)}`)
209
+ })
210
+ if (hits.length >= 300) break
211
+ }
212
+ return { text: hits.length ? hits.join('\n') : 'No matches.' }
213
+ }
214
+ case 'run_command': {
215
+ if (typeof args.command !== 'string' || !args.command.trim()) return fail('command is required')
216
+ const out = await new Promise((done) => {
217
+ exec(
218
+ args.command,
219
+ { cwd: projectRoot, timeout: COMMAND_TIMEOUT_MS, maxBuffer: 2_000_000, env: ctx.env },
220
+ (err, stdout, stderr) => done({ err, stdout, stderr }),
221
+ )
222
+ })
223
+ const text = [out.stdout, out.stderr].filter(Boolean).join('\n').trim() || '(no output)'
224
+ return out.err ? { text: trimText(`${text}\n(exit ${out.err.code ?? out.err.signal ?? 'error'})`), isError: true } : { text: trimText(text) }
225
+ }
226
+ default: {
227
+ const def = defs.find((d) => d.name === name)
228
+ if (!def) return fail(`No tool named ${name}.`)
229
+ const r = await runDef(def, args, toolCtx)
230
+ return { ...r, text: trimText(r.text) }
231
+ }
232
+ }
233
+ } catch (err) {
234
+ return fail(err?.message ?? String(err))
235
+ }
236
+ }
237
+
238
+ // ---------------------------------------------------------------- vendors
239
+
240
+ class VendorError extends Error {
241
+ constructor(status, message) {
242
+ super(message)
243
+ this.status = status
244
+ }
245
+ }
246
+
247
+ async function post(url, headers, body, signal, fetchImpl = fetch) {
248
+ let res
249
+ try {
250
+ res = await fetchImpl(url, { method: 'POST', headers: { 'content-type': 'application/json', ...headers }, body: JSON.stringify(body), signal })
251
+ } catch (err) {
252
+ if (err?.name === 'AbortError') throw err
253
+ throw new VendorError(0, `Could not reach the model's API (${err?.cause?.code ?? err?.message ?? 'network error'}).`)
254
+ }
255
+ const text = await res.text()
256
+ let json = null
257
+ try {
258
+ json = JSON.parse(text)
259
+ } catch {
260
+ // An error page, not JSON.
261
+ }
262
+ if (!res.ok) {
263
+ const detail = json?.error?.message ?? json?.message ?? (Array.isArray(json) ? json[0]?.error?.message : null) ?? text.slice(0, 300)
264
+ throw new VendorError(res.status, String(detail))
265
+ }
266
+ return json
267
+ }
268
+
269
+ /** Why a vendor refused, as one sentence the creator can act on. */
270
+ function readable(err, vendor, model) {
271
+ if (!(err instanceof VendorError)) return err?.message ?? String(err)
272
+ const m = err.message
273
+ if (err.status === 401 || err.status === 403 || /api key|unauthori[sz]ed|invalid.*key/i.test(m)) {
274
+ return `${vendor} refused the API key. Check it in Settings.`
275
+ }
276
+ if (err.status === 402 || /insufficient|quota|credit|balance|billing/i.test(m)) {
277
+ return `Your ${vendor} account is out of credit or over its limit. Top it up, or choose another model in Settings.`
278
+ }
279
+ if (err.status === 404 || /model.*(not found|does not exist|not supported)/i.test(m)) {
280
+ return `${vendor} does not offer ${model} to this key. Choose another model in Settings.`
281
+ }
282
+ if (err.status === 429 || err.status === 503 || err.status === 529) return `${vendor} is busy right now. Try again in a minute.`
283
+ return err.status ? `${vendor} answered ${err.status}: ${m}` : m
284
+ }
285
+
286
+ /** The kind of failure, as the host names them (shared.mjs failureKind), for
287
+ * the chat to say it in the screen language. */
288
+ function failureOf(err) {
289
+ if (!(err instanceof VendorError)) return 'other'
290
+ const m = err.message
291
+ if (err.status === 401 || err.status === 403 || /api key|unauthori[sz]ed|invalid.*key/i.test(m)) return 'key'
292
+ if (err.status === 402 || /insufficient|quota|credit|balance|billing/i.test(m)) return 'credit'
293
+ if (err.status === 429 || err.status === 503 || err.status === 529) return 'busy'
294
+ return 'other'
295
+ }
296
+
297
+ /** The Responses API's reasoning levels: the studio's two above high run as high. */
298
+ const RESPONSES_EFFORT = { low: 'low', medium: 'medium', high: 'high', xhigh: 'high', max: 'high' }
299
+ /** Who takes reasoning.effort on the Responses shape: xAI documents that its
300
+ * grok-4 reasoning models refuse the field. */
301
+ const TAKES_EFFORT = new Set(['openai'])
302
+
303
+ /**
304
+ * The Responses API (OpenAI, and xAI on the same shape). The conversation is
305
+ * kept server-side and continued by previous_response_id, so reasoning items
306
+ * never have to be carried by hand.
307
+ */
308
+ function responsesVendor({ baseUrl, apiKey, model, system, tools, images, effort, providerId }) {
309
+ const toolDefs = tools.map((t) => ({ type: 'function', name: t.name, description: t.description, parameters: t.parameters }))
310
+ const reasoning = TAKES_EFFORT.has(providerId) && RESPONSES_EFFORT[effort] ? { reasoning: { effort: RESPONSES_EFFORT[effort] } } : {}
311
+ let previous = null
312
+ let pending = null
313
+ return {
314
+ start(prompt, attached) {
315
+ const pictures = images ? attached : []
316
+ pending = [
317
+ { role: 'system', content: system },
318
+ {
319
+ role: 'user',
320
+ content: pictures.length
321
+ ? [{ type: 'input_text', text: prompt }, ...pictures.map((a) => ({ type: 'input_image', image_url: `data:${a.mime};base64,${a.data}` }))]
322
+ : prompt,
323
+ },
324
+ ]
325
+ },
326
+ async step(signal) {
327
+ const r = await post(
328
+ `${baseUrl}/responses`,
329
+ { authorization: `Bearer ${apiKey}` },
330
+ { model, input: pending, tools: toolDefs, ...reasoning, ...(previous ? { previous_response_id: previous } : {}) },
331
+ signal,
332
+ )
333
+ previous = r.id
334
+ const text = (r.output ?? [])
335
+ .filter((o) => o.type === 'message')
336
+ .flatMap((o) => o.content ?? [])
337
+ .filter((c) => c.type === 'output_text' && c.text)
338
+ .map((c) => c.text)
339
+ .join('')
340
+ const calls = (r.output ?? [])
341
+ .filter((o) => o.type === 'function_call')
342
+ .map((o) => ({ id: o.call_id, name: o.name, args: parseArgs(o.arguments) }))
343
+ return { text, calls, usage: { input: r.usage?.input_tokens ?? 0, output: r.usage?.output_tokens ?? 0 } }
344
+ },
345
+ answer(results, calls) {
346
+ pending = results.map((r, i) => ({ type: 'function_call_output', call_id: calls[i].id, output: r.text }))
347
+ const shots = images ? results.flatMap((r) => r.images ?? []) : []
348
+ if (shots.length) {
349
+ pending.push({ role: 'user', content: shots.map((s) => ({ type: 'input_image', image_url: `data:${s.mime};base64,${s.data}` })) })
350
+ }
351
+ },
352
+ nudge(text) {
353
+ pending = [{ role: 'user', content: text }]
354
+ },
355
+ }
356
+ }
357
+
358
+ /**
359
+ * One call on the Responses API with no tools and no conversation: the
360
+ * reference loop's second judge (agent/loop/judge.mjs) asks OpenAI for its
361
+ * score through the same request and the same refusals as the loop. Answers
362
+ * { text, usage: { input, output } }; throws a VendorError the way step()
363
+ * does. `fetchImpl` is the checks' stand-in for the network.
364
+ */
365
+ export async function respondOnce({ baseUrl, apiKey, model, system, text, images = [], signal, fetchImpl }) {
366
+ const content = [{ type: 'input_text', text }, ...images.map((a) => ({ type: 'input_image', image_url: `data:${a.mime};base64,${a.data}` }))]
367
+ const r = await post(`${baseUrl}/responses`, { authorization: `Bearer ${apiKey}` }, { model, input: [{ role: 'system', content: system }, { role: 'user', content }] }, signal, fetchImpl)
368
+ const out = (r?.output ?? [])
369
+ .filter((o) => o.type === 'message')
370
+ .flatMap((o) => o.content ?? [])
371
+ .filter((c) => c.type === 'output_text' && c.text)
372
+ .map((c) => c.text)
373
+ .join('')
374
+ return { text: out, usage: { input: r?.usage?.input_tokens ?? 0, output: r?.usage?.output_tokens ?? 0 } }
375
+ }
376
+
377
+ /** OpenAI-style Chat Completions (DeepSeek). The whole conversation is sent
378
+ * each step; DeepSeek runs without its thinking mode here, the mode its own
379
+ * reference documents tool calls for without extra rules. */
380
+ function chatVendor({ baseUrl, apiKey, model, system, tools, images, providerId }) {
381
+ const toolDefs = tools.map((t) => ({ type: 'function', function: { name: t.name, description: t.description, parameters: t.parameters } }))
382
+ const messages = [{ role: 'system', content: system }]
383
+ const extra = providerId === 'deepseek' ? { thinking: { type: 'disabled' } } : {}
384
+ return {
385
+ start(prompt, attached) {
386
+ const pictures = images ? attached : []
387
+ messages.push({
388
+ role: 'user',
389
+ content: pictures.length
390
+ ? [{ type: 'text', text: prompt }, ...pictures.map((a) => ({ type: 'image_url', image_url: { url: `data:${a.mime};base64,${a.data}` } }))]
391
+ : prompt,
392
+ })
393
+ },
394
+ async step(signal) {
395
+ const r = await post(`${baseUrl}/chat/completions`, { authorization: `Bearer ${apiKey}` }, { model, messages, tools: toolDefs, ...extra }, signal)
396
+ const msg = r.choices?.[0]?.message ?? {}
397
+ messages.push({ role: 'assistant', content: msg.content ?? '', ...(msg.tool_calls?.length ? { tool_calls: msg.tool_calls } : {}) })
398
+ const calls = (msg.tool_calls ?? []).map((c) => ({ id: c.id, name: c.function?.name, args: parseArgs(c.function?.arguments) }))
399
+ return { text: msg.content ?? '', calls, usage: { input: r.usage?.prompt_tokens ?? 0, output: r.usage?.completion_tokens ?? 0 } }
400
+ },
401
+ answer(results, calls) {
402
+ results.forEach((r, i) => messages.push({ role: 'tool', tool_call_id: calls[i].id, content: r.text }))
403
+ const shots = images ? results.flatMap((r) => r.images ?? []) : []
404
+ if (shots.length) {
405
+ messages.push({ role: 'user', content: shots.map((s) => ({ type: 'image_url', image_url: { url: `data:${s.mime};base64,${s.data}` } })) })
406
+ }
407
+ },
408
+ nudge(text) {
409
+ messages.push({ role: 'user', content: text })
410
+ },
411
+ }
412
+ }
413
+
414
+ /** Gemini's generateContent. The model's own turns go back exactly as they
415
+ * came, thought signatures and all, as the reference requires. */
416
+ function geminiVendor({ baseUrl, apiKey, model, system, tools, images }) {
417
+ const declarations = tools.map((t) => ({
418
+ name: t.name,
419
+ description: t.description,
420
+ ...(Object.keys(t.parameters.properties ?? {}).length ? { parameters: t.parameters } : {}),
421
+ }))
422
+ const contents = []
423
+ return {
424
+ start(prompt, attached) {
425
+ const pictures = images ? attached : []
426
+ contents.push({ role: 'user', parts: [{ text: prompt }, ...pictures.map((a) => ({ inlineData: { mimeType: a.mime, data: a.data } }))] })
427
+ },
428
+ async step(signal) {
429
+ const r = await post(
430
+ `${baseUrl}/models/${encodeURIComponent(model)}:generateContent`,
431
+ { 'x-goog-api-key': apiKey },
432
+ { systemInstruction: { parts: [{ text: system }] }, contents, tools: [{ functionDeclarations: declarations }] },
433
+ signal,
434
+ )
435
+ const content = r.candidates?.[0]?.content
436
+ if (!content) {
437
+ const why = r.promptFeedback?.blockReason ?? r.candidates?.[0]?.finishReason ?? 'no answer'
438
+ throw new VendorError(200, `Gemini returned nothing (${why}).`)
439
+ }
440
+ contents.push(content)
441
+ const parts = content.parts ?? []
442
+ const text = parts.filter((p) => typeof p.text === 'string' && !p.thought).map((p) => p.text).join('')
443
+ const calls = parts
444
+ .filter((p) => p.functionCall)
445
+ .map((p, i) => ({ id: p.functionCall.id ?? `call-${contents.length}-${i}`, callId: p.functionCall.id, name: p.functionCall.name, args: p.functionCall.args ?? {} }))
446
+ const u = r.usageMetadata ?? {}
447
+ return { text, calls, usage: { input: u.promptTokenCount ?? 0, output: (u.candidatesTokenCount ?? 0) + (u.thoughtsTokenCount ?? 0) } }
448
+ },
449
+ answer(results, calls) {
450
+ const parts = results.map((r, i) => ({
451
+ functionResponse: {
452
+ ...(calls[i].callId ? { id: calls[i].callId } : {}),
453
+ name: calls[i].name,
454
+ response: r.isError ? { error: r.text } : { result: r.text },
455
+ },
456
+ }))
457
+ if (images) for (const r of results) for (const s of r.images ?? []) parts.push({ inlineData: { mimeType: s.mime, data: s.data } })
458
+ contents.push({ role: 'user', parts })
459
+ },
460
+ nudge(text) {
461
+ contents.push({ role: 'user', parts: [{ text }] })
462
+ },
463
+ }
464
+ }
465
+
466
+ function parseArgs(raw) {
467
+ if (raw && typeof raw === 'object') return raw
468
+ try {
469
+ return JSON.parse(raw || '{}')
470
+ } catch {
471
+ return { __invalid: String(raw) }
472
+ }
473
+ }
474
+
475
+ // ---------------------------------------------------------------- loop
476
+
477
+ /** How often the stop gate may send the model back to work in one request. */
478
+ const MAX_NUDGES = 2
479
+
480
+ /**
481
+ * Runs one request to the end. `send` takes the host's events; `defs` are the
482
+ * registry's tools and `toolCtx` what their handlers get; `signal` cancels it.
483
+ * `hooks` is the host's harness, each part optional:
484
+ * beforeTool(name, args) -> { deny?: string, args? } the guard and the ledger (run_command is asked as Bash)
485
+ * afterTool(name, result, args) -> string | null a note appended to the result (the ledger's reminder)
486
+ * stopGate() -> Promise<string | null> a reason not to finish yet, sent back as a user turn
487
+ * usage({ input, output }) each step's tokens, for the ledger
488
+ * summary(how?) -> Promise<object> fields added to the done and error events;
489
+ * how.unfinished on the error ones
490
+ * There is no spending cap: the host's ledger asks the creator instead.
491
+ */
492
+ export async function runLoop({
493
+ id,
494
+ provider,
495
+ model,
496
+ apiKey,
497
+ system,
498
+ prompt,
499
+ images = [],
500
+ projectRoot,
501
+ inside,
502
+ defs = [],
503
+ toolCtx = {},
504
+ send,
505
+ signal,
506
+ env,
507
+ effort,
508
+ started = {},
509
+ hooks = {},
510
+ maxTurns = 400,
511
+ }) {
512
+ const shell = process.platform !== 'win32'
513
+ const tools = toolSpecs({ shell, defs })
514
+ const vendorName = provider.name
515
+ const make = provider.runtime === 'responses' ? responsesVendor : provider.runtime === 'chat' ? chatVendor : geminiVendor
516
+ const vendor = make({
517
+ baseUrl: provider.baseUrl,
518
+ apiKey,
519
+ model: model.id,
520
+ system,
521
+ tools,
522
+ images: model.images !== false,
523
+ providerId: provider.id,
524
+ effort,
525
+ })
526
+ const ctx = { projectRoot, inside, defs, toolCtx, env }
527
+ const price = Array.isArray(model.price) ? model.price : null
528
+ let cost = 0
529
+ let turns = 0
530
+ let nudges = 0
531
+ const summary = async (how = {}) => {
532
+ try {
533
+ return { costUsd: cost, ...((await hooks.summary?.(how)) ?? {}) }
534
+ } catch {
535
+ return { costUsd: cost }
536
+ }
537
+ }
538
+
539
+ send({ type: 'started', id, sessionId: null, model: model.id, ...started })
540
+ // A model that cannot see is told the pictures were there, so it can say so
541
+ // instead of answering as though the creator had sent none.
542
+ const blind = model.images === false && images.length > 0
543
+ vendor.start(blind ? `${prompt}\n\n(The creator attached ${images.length} image${images.length > 1 ? 's' : ''}, which this model cannot see.)` : prompt, images)
544
+ try {
545
+ for (;;) {
546
+ if (signal.aborted) throw Object.assign(new Error('cancelled'), { name: 'AbortError' })
547
+ turns++
548
+ const r = await vendor.step(signal)
549
+ if (price) cost += (r.usage.input * price[0] + r.usage.output * price[1]) / 1e6
550
+ hooks.usage?.(r.usage)
551
+ if (r.text) send({ type: 'text', id, delta: r.text + (r.calls.length ? '\n\n' : '') })
552
+ if (r.calls.length === 0) {
553
+ // Done only when the host's bar is met: a changed game was checked
554
+ // and looked at. Its reason goes back as the creator's next turn.
555
+ const reason = nudges < MAX_NUDGES && turns < maxTurns ? await hooks.stopGate?.() : null
556
+ if (reason) {
557
+ nudges++
558
+ vendor.nudge(reason)
559
+ continue
560
+ }
561
+ send({ type: 'done', id, subtype: 'success', turns, ...(await summary()) })
562
+ return
563
+ }
564
+ const results = []
565
+ for (const call of r.calls) {
566
+ send({ type: 'tool', id, toolId: call.id, name: call.name, input: call.args })
567
+ let result
568
+ if (call.args?.__invalid !== undefined) {
569
+ result = { text: 'The arguments were not valid JSON. Call the tool again with a JSON object.', isError: true }
570
+ } else {
571
+ const args = call.args ?? {}
572
+ // The shell is fenced like Claude's Bash.
573
+ const asked = call.name === 'run_command' ? ['Bash', { command: args.command }] : [call.name, args]
574
+ const verdict = (await hooks.beforeTool?.(...asked)) ?? {}
575
+ result = verdict.deny
576
+ ? { text: verdict.deny, isError: true }
577
+ : await runTool(call.name, call.name !== 'run_command' && verdict.args ? verdict.args : args, ctx)
578
+ const note = hooks.afterTool?.(call.name, result, args)
579
+ if (note) result = { ...result, text: `${result.text}\n\n${note}` }
580
+ }
581
+ send({ type: 'tool-result', id, toolId: call.id, name: call.name, isError: result.isError === true })
582
+ results.push(result)
583
+ }
584
+ vendor.answer(results, r.calls)
585
+ if (turns >= maxTurns) {
586
+ send({ type: 'error', id, message: 'The agent ran out of steps before it finished. Ask it to continue.', failure: 'turns', vendor: vendorName, turns, unfinished: true, cleanup: 'skipped', ...(await summary({ unfinished: true })) })
587
+ return
588
+ }
589
+ }
590
+ } catch (err) {
591
+ // A Stop is an unfinished request, as on Claude's path: its work is
592
+ // committed as unfinished and the chat offers to continue.
593
+ if (err?.name === 'AbortError') {
594
+ send({ type: 'error', id, message: 'Stopped before it finished.', failure: 'stopped', vendor: vendorName, turns, unfinished: true, cleanup: 'skipped', ...(await summary({ unfinished: true })) })
595
+ return
596
+ }
597
+ send({ type: 'error', id, message: readable(err, vendorName, model.name), failure: failureOf(err), vendor: vendorName, turns, unfinished: true, cleanup: 'skipped', ...(await summary({ unfinished: true })) })
598
+ }
599
+ }
600
+
601
+ /** For the safety check: the tools without a vendor. */
602
+ export const __test = { runTool, globRegex, toolSpecs }
@@ -0,0 +1,5 @@
1
+ {
2
+ "name": "nowhere",
3
+ "version": "1.5.0",
4
+ "description": "How to build Oda spaces whose every part is made for its own request: the TSL facts for three r186 (tsl-r185), the planet's look from the brief (look-dev), where assets come from (asset-sources), modelling in Blender with bpy (blender-modeling), art direction from references (art-direction), asset legality and the ledger (asset-legality), Web Audio synthesis from the brief (sound-design), playtest scripts with nw_play and nw_eval (playtesting), the loop a space runs against its target pictures, from the kickoff to the approval (reference-loop), and how a space is drawn, decided before any picture (style)."
5
+ }