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
package/lib/tools.mjs ADDED
@@ -0,0 +1,668 @@
1
+ // Every studio tool from a terminal: `nowhere tool <name> ...` and its short
2
+ // forms (view, play, eval, logs, status, screenshot, look, reference, compare,
3
+ // asset, blender, guide, image). The McpServer that `nowhere mcp` offers
4
+ // (mcp.mjs createServer) runs in this process, with an MCP client of its own
5
+ // over an in-memory transport, so a call goes through the same validation,
6
+ // the same words and the same gate on money as an agent's call does; the
7
+ // preview is headless Chrome (headlessPreview.mjs), started for the command
8
+ // and stopped after it, or the page `nowhere dev --headless` keeps open. The
9
+ // text a tool answers goes to stdout; every picture it returns is saved as a
10
+ // file and its path printed; the yes to a paid generation is typed at the
11
+ // terminal, or given with --yes (without a terminal, only where the creator
12
+ // set NOWHERE_ALLOW_PAID=1). Inside an agent's run (NOWHERE_AGENT_RUN=1, set
13
+ // by the studio's host) no paid generation starts from here at all.
14
+ //
15
+ // A paid generation across two commands: `asset generate --action estimate
16
+ // ...` prints the cost lines and the estimate id; the same command with
17
+ // `--confirm <id>` runs the estimate again in this process (which registers
18
+ // the offer with the server's ledger), checks the id is still the same, then
19
+ // submits, and the server asks for the yes.
20
+
21
+ import fs from 'node:fs'
22
+ import path from 'node:path'
23
+ import readline from 'node:readline'
24
+ import { Client } from '@modelcontextprotocol/sdk/client/index.js'
25
+ import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'
26
+ import { ElicitRequestSchema } from '@modelcontextprotocol/sdk/types.js'
27
+ import { connectHeadless } from './headlessPreview.mjs'
28
+ import { ALLOW_CODEX_VAR, ALLOW_PAID_VAR, createServer } from './mcp.mjs'
29
+ import { VERSION } from './resources.mjs'
30
+
31
+ /** The bin's commands this module answers. */
32
+ export const TOOL_COMMANDS = ['tools', 'tool', 'view', 'play', 'eval', 'logs', 'status', 'screenshot', 'look', 'reference', 'compare', 'asset', 'blender', 'guide', 'image']
33
+
34
+ /** How long one tool call may take: a Blender run or a playtest is minutes,
35
+ * and a person answering for a paid generation has ten. */
36
+ const CALL_TIMEOUT_MS = 60 * 60_000
37
+
38
+ /** The tools that spend money (mcp.mjs PAID): estimate, then confirm. */
39
+ const PAID = new Set(['asset_generate', 'image_generate', 'environment_generate'])
40
+
41
+ /** What stops a command: Ctrl+C, a kill, and a closed terminal. */
42
+ const SIGNALS = ['SIGINT', 'SIGTERM', 'SIGHUP']
43
+
44
+ /** The variable the studio's host sets for its agents' children (host.mjs connectorOptions). */
45
+ const AGENT_RUN_VAR = 'NOWHERE_AGENT_RUN'
46
+
47
+ const VIEWS = ['player', 'orbit', 'closeup', 'overview', 'free']
48
+ const EXT = { 'image/jpeg': 'jpg', 'image/png': 'png', 'image/webp': 'webp', 'image/gif': 'gif' }
49
+
50
+ export const TOOLS_HELP = `oda tools [--json] every tool, one line each (--json: the full schemas)
51
+ oda tool <name> [--json '{...}'] [--<field> <value>]... [--save <dir>] [--yes] [--raw]
52
+ oda tool <name> --help the tool's description and fields
53
+
54
+ Short forms (the same flags apply):
55
+ oda view [player|orbit|closeup|overview|free ...] [--target player] [--yaw 30] [--distance 12] ...
56
+ oda play --keys KeyW,ShiftLeft --seconds 3 or --steps '[{"keys":["KeyW"],"seconds":2}]'
57
+ oda eval <code...> the value, as JSON
58
+ oda logs [--level warn] [--since N] oda status oda screenshot
59
+ oda look apply --set '{"look":{"exposure":1.1}}' oda look compare <picture>
60
+ oda reference <picture> | --board oda compare <picture>
61
+ oda asset search <words...> [--kind model|material|hdri] asset fetch <id> asset import <from> --as assets/x.glb
62
+ oda asset generate --provider meshy --task text-to-3d --prompt "..." (then --confirm <id>) asset job <id> asset ledger [path]
63
+ oda blender <script.py> --out assets/x.glb
64
+ oda guide [name]
65
+ oda image --provider openai --prompt "..." --out blender/x/view.png (then --confirm <id>)
66
+
67
+ Arguments: --json '{...}' is the whole input; --<field> <value> sets one field (a value that
68
+ parses as JSON is used parsed, else as text; --<field> twice makes a list, so does a,b for a
69
+ list field; --<field> alone is true). --project <folder> names the project (default: here).
70
+ Pictures a tool answers are saved under <project>/.nowhere/shots/ (or --save <dir>) and
71
+ their paths printed. The preview runs in headless Chrome for the command, or in the page
72
+ \`oda dev --headless\` keeps open. A paid generation: the estimate prints its id; the same
73
+ command with --confirm <id> estimates again, then asks you for a yes at the terminal (--yes
74
+ answers it there; with no terminal, --yes counts only where NOWHERE_ALLOW_PAID=1 is set).`
75
+
76
+ /** yyyymmdd-hhmmss, in local time (make.mjs stamps its records the same way). */
77
+ function stampOf(date) {
78
+ const two = (n) => String(n).padStart(2, '0')
79
+ return `${date.getFullYear()}${two(date.getMonth() + 1)}${two(date.getDate())}-${two(date.getHours())}${two(date.getMinutes())}${two(date.getSeconds())}`
80
+ }
81
+
82
+ // ---------------------------------------------------------------- the server, in this process
83
+
84
+ /**
85
+ * The server `nowhere mcp` runs, with a client in the same process. `ask`
86
+ * answers the server's questions to the creator (a paid generation's cost):
87
+ * terminalAsk by default. `connect` reaches the preview (headless Chrome by
88
+ * default; a check passes a stand-in), `fetch` the network (a check's fake).
89
+ * @returns {Promise<{ root: () => string | null, listTools: () => Promise<object[]>,
90
+ * callTool: (name: string, args?: object) => Promise<object>, close: () => Promise<void> }>}
91
+ */
92
+ export async function openTools({ project, connect = connectHeadless, fetch, ask = terminalAsk(), timeoutMs = CALL_TIMEOUT_MS } = {}) {
93
+ const { server, root, close } = await createServer({ project, connect, ...(fetch ? { fetch } : {}) })
94
+ const [clientSide, serverSide] = InMemoryTransport.createLinkedPair()
95
+ await server.connect(serverSide)
96
+ const client = new Client({ name: 'nowhere-cli', version: VERSION }, { capabilities: { elicitation: { form: {} } } })
97
+ client.setRequestHandler(ElicitRequestSchema, async (req) => ask(req.params))
98
+ await client.connect(clientSide)
99
+ let closing = null
100
+ return {
101
+ root,
102
+ listTools: async () => (await client.listTools()).tools,
103
+ callTool: (name, args = {}) => client.callTool({ name, arguments: args }, undefined, { timeout: timeoutMs }),
104
+ // Once, however many times it is asked (a signal and the command's own
105
+ // end), and every caller waits for the whole of it: the server's preview
106
+ // and its Chrome first, then the client, so a call in flight ends only
107
+ // once nothing is left running.
108
+ close() {
109
+ closing ??= (async () => {
110
+ await close().catch(() => {})
111
+ await client.close().catch(() => {})
112
+ })()
113
+ return closing
114
+ },
115
+ }
116
+ }
117
+
118
+ /**
119
+ * The creator's answer at the terminal to the server's question (a paid
120
+ * generation's cost lines): the lines are printed, then a yes is asked for
121
+ * on the TTY, or given by --yes, or refused where there is no TTY to ask
122
+ * on. Every boolean the question asks for gets the same answer. Without a
123
+ * TTY, --yes may be any program's word rather than the person's, so it
124
+ * counts only where the creator set ALLOW_PAID_VAR, the rule an MCP client
125
+ * that cannot ask has too (mcp.mjs creatorAgrees); inside an agent's run
126
+ * nothing is agreed here at all. Ctrl+C at the question (readline closing
127
+ * with no answer) is a cancel, and `onCancel` stops the command.
128
+ */
129
+ export function terminalAsk({ yes = false, input = process.stdin, output = process.stderr, env = process.env, onCancel = () => {} } = {}) {
130
+ return async (params) => {
131
+ const message = String(params?.message ?? '').replace(/\n?Start it\?\s*$/, '')
132
+ const props = params?.requestedSchema?.properties ?? {}
133
+ const asked = Object.keys(props).filter((k) => props[k]?.type === 'boolean')
134
+ const answer = (agreed) => ({ action: 'accept', content: Object.fromEntries(asked.map((k) => [k, agreed])) })
135
+ if (message) output.write(`${message}\n`)
136
+ if (env?.[AGENT_RUN_VAR] === '1') {
137
+ output.write("Nothing is sent: this command runs inside an agent's run, and only the creator answers for a paid generation.\n")
138
+ return { action: 'decline' }
139
+ }
140
+ if (yes) {
141
+ if (input.isTTY || env?.[ALLOW_PAID_VAR] === '1') {
142
+ output.write('Agreed with --yes.\n')
143
+ return answer(true)
144
+ }
145
+ output.write(`Nothing is sent: --yes without a terminal counts only where ${ALLOW_PAID_VAR}=1 is set in this environment, the creator's own opt-in.\n`)
146
+ return { action: 'decline' }
147
+ }
148
+ if (!input.isTTY) {
149
+ output.write('Nothing is sent: there is no terminal here to ask you on. Run the command at a terminal to answer.\n')
150
+ return { action: 'decline' }
151
+ }
152
+ const rl = readline.createInterface({ input, output })
153
+ // In terminal mode Ctrl+C closes readline and raises no SIGINT, so the
154
+ // close is the answer when no line came first.
155
+ const typed = await new Promise((resolve) => {
156
+ rl.once('close', () => resolve(null))
157
+ rl.question('Start it? [y/N] ', resolve)
158
+ })
159
+ rl.close()
160
+ if (typed === null) {
161
+ output.write('\n')
162
+ onCancel()
163
+ return { action: 'cancel' }
164
+ }
165
+ return answer(/^y(es)?$/i.test(String(typed).trim()))
166
+ }
167
+ }
168
+
169
+ // ---------------------------------------------------------------- the arguments
170
+
171
+ /** The command's own options, taken out before the tool's fields. */
172
+ const OPTIONS = { json: 'value', save: 'value', project: 'value', yes: 'switch', raw: 'switch', help: 'switch' }
173
+
174
+ /**
175
+ * The words after the command: { positionals, fields: [{ name, value }] (value
176
+ * is the text given, or true for a bare flag, in order, repeats kept),
177
+ * options: { json, save, project, yes, raw, help }, wordAt }, or { error }.
178
+ * wordAt has one number per field: where among the positionals the word it
179
+ * took as its value stood, or -1 (an inline --name=value, or a bare flag),
180
+ * so a bare boolean flag can give its word back (giveBackWords).
181
+ */
182
+ export function parseToolArgv(argv) {
183
+ const positionals = []
184
+ const fields = []
185
+ const wordAt = []
186
+ const options = { json: undefined, save: undefined, project: undefined, yes: false, raw: false, help: false }
187
+ for (let i = 0; i < argv.length; i++) {
188
+ const arg = String(argv[i])
189
+ if (arg === '-h') {
190
+ options.help = true
191
+ continue
192
+ }
193
+ if (!arg.startsWith('--')) {
194
+ positionals.push(arg)
195
+ continue
196
+ }
197
+ const eq = arg.indexOf('=')
198
+ const name = eq >= 0 ? arg.slice(2, eq) : arg.slice(2)
199
+ if (!name) return { error: 'An empty option (--) means nothing here.' }
200
+ const inline = eq >= 0 ? arg.slice(eq + 1) : undefined
201
+ const next = () => {
202
+ if (inline !== undefined) return inline
203
+ const v = argv[i + 1]
204
+ if (v === undefined || String(v).startsWith('--')) return undefined
205
+ i++
206
+ return String(v)
207
+ }
208
+ if (OPTIONS[name] === 'switch') {
209
+ if (inline !== undefined) return { error: `--${name} takes no value.` }
210
+ options[name] = true
211
+ continue
212
+ }
213
+ if (OPTIONS[name] === 'value') {
214
+ const v = next()
215
+ // --json alone is `nowhere tools --json`, the full schemas.
216
+ if (v === undefined && name !== 'json') return { error: `--${name} needs a value.` }
217
+ options[name] = v ?? true
218
+ continue
219
+ }
220
+ const v = next()
221
+ fields.push({ name, value: v === undefined ? true : v })
222
+ wordAt.push(inline === undefined && v !== undefined ? positionals.length : -1)
223
+ }
224
+ return { positionals, fields, options, wordAt }
225
+ }
226
+
227
+ /**
228
+ * The words read again once the tool's fields are known: a bare boolean
229
+ * flag that took the next word as its value (--sheet ref.png, --fog player)
230
+ * is true, and the word goes back among the positionals where it stood. A
231
+ * value a boolean reads (true, false, yes, no, 1, 0) stays its value.
232
+ */
233
+ export function giveBackWords({ positionals, fields, wordAt = [] }, schema) {
234
+ const props = schema?.properties ?? {}
235
+ const words = [...positionals]
236
+ let given = 0
237
+ const read = fields.map((field, i) => {
238
+ const at = wordAt[i] ?? -1
239
+ if (at < 0 || props[field.name]?.type !== 'boolean' || typeof field.value !== 'string' || /^(true|false|yes|no|1|0)$/i.test(field.value)) return field
240
+ words.splice(at + given, 0, field.value)
241
+ given++
242
+ return { name: field.name, value: true }
243
+ })
244
+ return { positionals: words, fields: read }
245
+ }
246
+
247
+ /** The value as JSON, or undefined when it is not JSON. */
248
+ function asJson(value) {
249
+ try {
250
+ return JSON.parse(value)
251
+ } catch {
252
+ return undefined
253
+ }
254
+ }
255
+
256
+ /** One value as the field's JSON Schema reads it: text stays text for a
257
+ * string field, and for a field that may be text a JSON list or object is
258
+ * the only thing parsed (--target 3 names a placement "3"); a list field
259
+ * takes a JSON list or a,b; anything else that parses as JSON is used
260
+ * parsed, else it is text. */
261
+ function coerce(value, prop) {
262
+ if (value === true) return true
263
+ if (prop?.type === 'string') return value
264
+ if (Array.isArray(prop?.anyOf) && prop.anyOf.some((p) => p?.type === 'string')) {
265
+ const parsed = asJson(value)
266
+ return parsed !== null && typeof parsed === 'object' ? parsed : value
267
+ }
268
+ if (prop?.type === 'array') {
269
+ const list = asJson(value)
270
+ return Array.isArray(list) ? list : value.split(',').map((v) => coerce(v.trim(), prop.items))
271
+ }
272
+ if (prop?.type === 'boolean') {
273
+ if (/^(true|yes|1)$/i.test(value)) return true
274
+ if (/^(false|no|0)$/i.test(value)) return false
275
+ }
276
+ const parsed = asJson(value)
277
+ return parsed === undefined ? value : parsed
278
+ }
279
+
280
+ /**
281
+ * The tool's input from the command's fields: the short form's own
282
+ * `defaults` under everything, --json as the base, then `base` (what the
283
+ * short form read from its words), then each field. An unknown field is an
284
+ * error naming the tool's fields, and any field at all is one for a tool
285
+ * that takes no input.
286
+ */
287
+ export function toolInput({ fields = [], json, base = {}, defaults = {}, schema, tool = 'the tool' }) {
288
+ let input = {}
289
+ if (json !== undefined) {
290
+ try {
291
+ input = JSON.parse(json)
292
+ } catch (err) {
293
+ return { error: `--json is not JSON: ${err.message}` }
294
+ }
295
+ if (!input || typeof input !== 'object' || Array.isArray(input)) return { error: '--json takes an object: {"field": value, ...}' }
296
+ }
297
+ const props = schema?.properties ?? {}
298
+ const known = Object.keys(props)
299
+ if (fields.length && schema && !known.length) return { error: `${tool} takes no input (--${fields[0].name} means nothing to it).` }
300
+ const byName = new Map()
301
+ for (const { name, value } of fields) {
302
+ if (known.length && !(name in props)) return { error: `${tool} has no field "${name}". Its fields: ${known.join(', ')}.` }
303
+ if (!byName.has(name)) byName.set(name, [])
304
+ byName.get(name).push(value)
305
+ }
306
+ const args = { ...defaults, ...input, ...base }
307
+ for (const [name, values] of byName) {
308
+ const prop = props[name]
309
+ args[name] = values.length === 1 ? coerce(values[0], prop) : values.flatMap((v) => (prop?.type === 'array' ? coerce(v, prop) : [coerce(v, prop)]))
310
+ }
311
+ return { args }
312
+ }
313
+
314
+ // ---------------------------------------------------------------- the short forms
315
+
316
+ /** A reference picture as the reference tools take it (.nowhere/refs/<file>
317
+ * or refs/<file> in the project): a file anywhere else is copied into
318
+ * .nowhere/refs/ first, under its own name, or under a numbered one
319
+ * (ref-2.png) when a different picture already has that name there, which
320
+ * a brief may cite. `said` hears the path used. */
321
+ function referenceArg(given, root, cwd, said = () => {}) {
322
+ if (!given || !root) return given
323
+ const abs = path.resolve(cwd, given)
324
+ if (!fs.existsSync(abs) || !fs.statSync(abs).isFile()) return given
325
+ const rel = path.relative(root, abs).split(path.sep).join('/')
326
+ if (rel.startsWith('.nowhere/refs/') || rel.startsWith('refs/')) return rel
327
+ const dir = path.join(root, '.nowhere', 'refs')
328
+ fs.mkdirSync(dir, { recursive: true })
329
+ const bytes = fs.readFileSync(abs)
330
+ const ext = path.extname(abs)
331
+ const stem = path.basename(abs, ext)
332
+ for (let n = 1; ; n++) {
333
+ const name = n === 1 ? path.basename(abs) : `${stem}-${n}${ext}`
334
+ const at = path.join(dir, name)
335
+ if (fs.existsSync(at) && !fs.readFileSync(at).equals(bytes)) continue
336
+ if (!fs.existsSync(at)) fs.writeFileSync(at, bytes)
337
+ said(`.nowhere/refs/${name}`)
338
+ return `.nowhere/refs/${name}`
339
+ }
340
+ }
341
+
342
+ /**
343
+ * The tool a short form stands for and what its words say, before the
344
+ * fields: { tool, base, defaults? } or { error }. `tool` itself names the
345
+ * tool in its first word. defaults are the short form's own choices, which
346
+ * --json and the fields override (asset search looks for models unless
347
+ * told otherwise). `said` hears where a reference picture was put.
348
+ */
349
+ export function aliasCall(command, words, { root = null, cwd = process.cwd(), said = () => {} } = {}) {
350
+ const none = (what, rest = words) => (rest.length ? { error: `${what} takes no words, only flags (${rest.join(' ')}).` } : null)
351
+ switch (command) {
352
+ case 'tool':
353
+ if (!words[0]) return { error: 'Which tool? oda tool <name> (oda tools lists them).' }
354
+ if (words.length > 1) return { error: `oda tool ${words[0]} takes its input as flags (--<field> <value>) or --json, not words (${words.slice(1).join(' ')}).` }
355
+ return { tool: words[0], base: {} }
356
+ case 'view': {
357
+ const bad = words.find((w) => !VIEWS.includes(w))
358
+ if (bad) return { error: `"${bad}" is not a view: ${VIEWS.join(', ')}.` }
359
+ if (words.length <= 1) return { tool: 'nw_view', base: words[0] ? { view: words[0] } : {} }
360
+ return { tool: 'nw_view', base: {}, views: words }
361
+ }
362
+ case 'play':
363
+ return none('oda play') ?? { tool: 'nw_play', base: {} }
364
+ case 'eval':
365
+ return { tool: 'nw_eval', base: words.length ? { code: words.join(' ') } : {} }
366
+ case 'logs':
367
+ return none('oda logs') ?? { tool: 'nw_logs', base: {} }
368
+ case 'status':
369
+ return none('oda status') ?? { tool: 'nw_status', base: {} }
370
+ case 'screenshot':
371
+ return none('oda screenshot') ?? { tool: 'nw_screenshot', base: {} }
372
+ case 'look':
373
+ if (words[0] === 'apply') return { tool: 'look_apply', base: {} }
374
+ if (words[0] === 'compare') return { tool: 'look_compare', base: words[1] ? { reference: referenceArg(words[1], root, cwd, said) } : {} }
375
+ return { error: 'oda look apply --set \'{...}\', or oda look compare <picture>' }
376
+ case 'reference':
377
+ return { tool: 'nw_reference', base: words[0] ? { image: referenceArg(words[0], root, cwd, said) } : {} }
378
+ case 'compare':
379
+ return { tool: 'nw_compare', base: words[0] ? { reference: referenceArg(words[0], root, cwd, said) } : {} }
380
+ case 'asset':
381
+ switch (words[0]) {
382
+ case 'search':
383
+ return { tool: 'asset_search', base: words.length > 1 ? { query: words.slice(1).join(' ') } : {}, defaults: { kind: 'model' } }
384
+ case 'fetch':
385
+ return { tool: 'asset_fetch', base: words[1] ? { id: words[1] } : {} }
386
+ case 'import':
387
+ return { tool: 'asset_import', base: words[1] ? { from: words[1] } : {} }
388
+ case 'generate':
389
+ return none('oda asset generate', words.slice(1)) ?? { tool: 'asset_generate', base: {} }
390
+ case 'job':
391
+ return { tool: 'asset_job', base: words[1] ? { id: words[1] } : {} }
392
+ case 'ledger':
393
+ return { tool: 'asset_ledger', base: words[1] ? { path: words[1] } : {} }
394
+ default:
395
+ return { error: 'oda asset search|fetch|import|generate|job|ledger ...' }
396
+ }
397
+ case 'blender':
398
+ return { tool: 'nw_blender', base: words[0] ? { script: words[0] } : {} }
399
+ case 'guide':
400
+ return { tool: 'nw_guide', base: words[0] ? { name: words[0] } : {}, listNames: !words[0] }
401
+ case 'image':
402
+ return none('oda image') ?? { tool: 'image_generate', base: {} }
403
+ default:
404
+ return { error: `Unknown command "${command}".` }
405
+ }
406
+ }
407
+
408
+ // ---------------------------------------------------------------- what comes back
409
+
410
+ const textOf = (result) => (result?.content ?? []).filter((c) => c.type === 'text').map((c) => c.text).join('\n')
411
+ const imagesOf = (result) => (result?.content ?? []).filter((c) => c.type === 'image')
412
+
413
+ /**
414
+ * Writes every picture in a tool's result as a file of its own type under
415
+ * `dir`, named <tool>-<stamp>-<n>.<ext>, and answers the paths in order. A
416
+ * name another command took in the same second is never written over: n
417
+ * goes on to the next free one.
418
+ */
419
+ export function saveImages(result, { dir, tool, stamp = stampOf(new Date()) }) {
420
+ const images = imagesOf(result)
421
+ if (!images.length) return []
422
+ fs.mkdirSync(dir, { recursive: true })
423
+ let n = 0
424
+ return images.map((image) => {
425
+ const ext = EXT[image.mimeType] ?? 'bin'
426
+ const bytes = Buffer.from(image.data, 'base64')
427
+ for (;;) {
428
+ const file = path.join(dir, `${tool}-${stamp}-${++n}.${ext}`)
429
+ try {
430
+ fs.writeFileSync(file, bytes, { flag: 'wx' })
431
+ return file
432
+ } catch (err) {
433
+ if (err?.code !== 'EEXIST') throw err
434
+ }
435
+ }
436
+ })
437
+ }
438
+
439
+ const firstSentence = (text) => {
440
+ const s = String(text ?? '').split(/(?<=[.!?])\s+(?=[A-Z])/)[0].trim()
441
+ return s.length > 110 ? `${s.slice(0, 107).trimEnd()}...` : s
442
+ }
443
+
444
+ /** One line for a tool in the list. */
445
+ export const toolLine = (tool) => `${tool.name.padEnd(16)} ${firstSentence(tool.description)}${tool.annotations?.readOnlyHint ? ' (read-only)' : ''}`
446
+
447
+ const typeOf = (prop) => {
448
+ if (!prop || typeof prop !== 'object') return 'json'
449
+ if (Array.isArray(prop.enum)) return prop.enum.join('|')
450
+ if (prop.type === 'array') return `${typeOf(prop.items)},...`
451
+ if (prop.type) return Array.isArray(prop.type) ? prop.type.join('|') : prop.type
452
+ if (Array.isArray(prop.anyOf)) return prop.anyOf.map(typeOf).join('|')
453
+ return 'json'
454
+ }
455
+
456
+ /** A tool's description and its fields, for `nowhere tool <name> --help`. */
457
+ export function toolHelp(tool) {
458
+ const props = tool.inputSchema?.properties ?? {}
459
+ const required = new Set(tool.inputSchema?.required ?? [])
460
+ const lines = [`${tool.name}: ${tool.description}`, '']
461
+ if (!Object.keys(props).length) lines.push('It takes no input.')
462
+ else {
463
+ lines.push('Fields:')
464
+ for (const [name, prop] of Object.entries(props)) {
465
+ const bits = [prop?.description ? String(prop.description) : '', required.has(name) ? 'required' : '', prop?.default !== undefined ? `default ${JSON.stringify(prop.default)}` : ''].filter(Boolean)
466
+ lines.push(` --${name} <${typeOf(prop)}>${bits.length ? ` ${bits.join('; ')}` : ''}`)
467
+ }
468
+ }
469
+ return lines.join('\n')
470
+ }
471
+
472
+ // ---------------------------------------------------------------- the command
473
+
474
+ /** Thrown out of a call that a stop (Ctrl+C, a kill, a closed terminal) cut short. */
475
+ const STOPPED = Symbol('stopped')
476
+
477
+ /**
478
+ * Runs one of the bin's tool commands with the words after it. Resolves
479
+ * with the exit code: 0, 1 when the tool answered an error (or could not
480
+ * run), 2 for a usage error, 130 when it was stopped. deps, for the checks:
481
+ * out and err (the terminal), input (the TTY the yes is read from),
482
+ * connect, fetch, cwd, env, signals and exit.
483
+ */
484
+ export async function runTools(command, argv, deps = {}) {
485
+ const d = {
486
+ out: (line) => process.stdout.write(`${line}\n`),
487
+ err: (line) => process.stderr.write(`${line}\n`),
488
+ input: process.stdin,
489
+ output: process.stderr,
490
+ connect: undefined,
491
+ fetch: undefined,
492
+ cwd: process.cwd(),
493
+ env: process.env,
494
+ signals: process,
495
+ exit: (code) => process.exit(code),
496
+ now: () => new Date(),
497
+ ...deps,
498
+ }
499
+ const parsed = parseToolArgv(argv)
500
+ if (parsed.error) {
501
+ d.err(parsed.error)
502
+ return 2
503
+ }
504
+ const { positionals, fields, options } = parsed
505
+ if (options.help && (command === 'tools' || (command === 'tool' && !positionals[0]))) {
506
+ d.out(TOOLS_HELP)
507
+ return 0
508
+ }
509
+ const agentRun = d.env?.[AGENT_RUN_VAR] === '1'
510
+ if (options.yes && agentRun) {
511
+ d.err("Nothing was sent: --yes is the creator's own answer, and this command runs inside an agent's run.")
512
+ return 2
513
+ }
514
+
515
+ // A stop closes what the command started (the preview, its Chrome), then
516
+ // exits 130; a second one exits at once. The call it cut short ends in
517
+ // the catch below, which prints nothing of it.
518
+ let tools = null
519
+ let stopping = false
520
+ const stop = async () => {
521
+ if (stopping) return d.exit(130)
522
+ stopping = true
523
+ await tools?.close().catch(() => {})
524
+ d.exit(130)
525
+ }
526
+ for (const signal of SIGNALS) d.signals.on?.(signal, stop)
527
+ const call = async (name, args) => {
528
+ const result = await tools.callTool(name, args)
529
+ if (stopping) throw STOPPED
530
+ return result
531
+ }
532
+ try {
533
+ tools = await openTools({
534
+ project: options.project ? path.resolve(d.cwd, options.project) : d.cwd,
535
+ ...(d.connect ? { connect: d.connect } : {}),
536
+ ...(d.fetch ? { fetch: d.fetch } : {}),
537
+ ask: terminalAsk({ yes: options.yes, input: d.input, output: d.output, env: d.env, onCancel: () => void stop() }),
538
+ })
539
+ const offered = await tools.listTools()
540
+
541
+ if (command === 'tools') {
542
+ if (positionals.length || fields.length) {
543
+ d.err('oda tools [--json]')
544
+ return 2
545
+ }
546
+ d.out(options.json !== undefined ? JSON.stringify(offered.map(({ name, description, inputSchema, annotations }) => ({ name, description, inputSchema, ...(annotations ? { annotations } : {}) })), null, 2) : offered.map(toolLine).join('\n'))
547
+ return 0
548
+ }
549
+
550
+ // The tool first, from the words as they came (nothing is copied yet),
551
+ // then the words again with its fields known: a bare boolean flag gives
552
+ // back the word it took.
553
+ const first = aliasCall(command, positionals)
554
+ if (first.error) {
555
+ d.err(first.error)
556
+ return 2
557
+ }
558
+ const named = offered.find((t) => t.name === first.tool)
559
+ if (!named) {
560
+ d.err(`There is no tool "${first.tool}" here. oda tools lists them.`)
561
+ return 2
562
+ }
563
+ const words = giveBackWords(parsed, named.inputSchema)
564
+ const alias = aliasCall(command, words.positionals, { root: tools.root(), cwd: d.cwd, said: (rel) => d.err(`The picture is ${rel} in the project now.`) })
565
+ if (alias.error) {
566
+ d.err(alias.error)
567
+ return 2
568
+ }
569
+ const tool = offered.find((t) => t.name === alias.tool)
570
+ if (!tool) {
571
+ d.err(`There is no tool "${alias.tool}" here. oda tools lists them.`)
572
+ return 2
573
+ }
574
+ if (options.help) {
575
+ d.out(toolHelp(tool))
576
+ return 0
577
+ }
578
+ if (alias.listNames) {
579
+ d.out(`The guides: ${(tool.inputSchema?.properties?.name?.enum ?? []).join(', ')}\n\nnowhere guide <name>`)
580
+ return 0
581
+ }
582
+
583
+ if (options.json === true) {
584
+ d.err(`--json needs the input: --json '{"field": value, ...}'`)
585
+ return 2
586
+ }
587
+ const input = toolInput({ fields: words.fields, json: options.json, base: alias.base, defaults: alias.defaults, schema: tool.inputSchema, tool: tool.name })
588
+ if (input.error) {
589
+ d.err(input.error)
590
+ return 2
591
+ }
592
+ let args = input.args
593
+ // Several views in one call: the fields apply to each camera.
594
+ if (alias.views) {
595
+ const { views: _unused, view: _one, ...each } = args
596
+ args = { views: alias.views.map((view) => ({ view, ...each })) }
597
+ }
598
+
599
+ let result
600
+ if (PAID.has(tool.name)) {
601
+ const codex = tool.name === 'image_generate' && args.provider === 'codex'
602
+ const confirm = typeof args.confirm === 'string' && args.confirm ? args.confirm : null
603
+ if (!confirm) {
604
+ args.action ??= 'estimate'
605
+ if (args.action === 'submit') {
606
+ d.err(`Nothing was sent: submit needs --confirm <id>, the id an estimate printed. Run it with --action estimate first (Oda ${command} ... --action estimate).`)
607
+ return 2
608
+ }
609
+ result = await call(tool.name, args)
610
+ if (!result.isError && /^Estimate ([0-9a-f]{12}):/m.test(textOf(result))) {
611
+ const id = /^Estimate ([0-9a-f]{12}):/m.exec(textOf(result))[1]
612
+ const how = agentRun
613
+ ? "Inside an agent's run this command cannot start it: the run's own asset_generate, image_generate or environment_generate asks the creator."
614
+ : codex
615
+ ? `To start it, run the same command again with --confirm ${id} (and --action submit). Codex runs on your ChatGPT plan once ${ALLOW_CODEX_VAR}=1 is set; nothing is asked here.`
616
+ : `To start it, run the same command again with --confirm ${id} (and --action submit): the estimate runs again first, then you are asked for a yes at the terminal${d.input.isTTY ? ' (--yes agrees in the command)' : ', which needs one'}.`
617
+ d.out(`${textOf(result)}\n\n${how}`)
618
+ return 0
619
+ }
620
+ } else {
621
+ if (agentRun) {
622
+ d.err("Nothing was sent: inside an agent's run a generation starts only through the run's own asset_generate, image_generate or environment_generate, which ask the creator; an Oda command there cannot.")
623
+ return 2
624
+ }
625
+ args.action ??= 'submit'
626
+ // The estimate again, in this process: the offer the server's ledger
627
+ // takes a confirm for, and the proof the request did not change.
628
+ const again = { ...args, action: 'estimate' }
629
+ delete again.confirm
630
+ const estimate = await call(tool.name, again)
631
+ const id = /^Estimate ([0-9a-f]{12}):/m.exec(textOf(estimate))?.[1]
632
+ if (estimate.isError || !id) {
633
+ d.err(textOf(estimate) || 'The estimate did not answer, so nothing was sent.')
634
+ return 1
635
+ }
636
+ if (id !== confirm) {
637
+ d.err(`The request changed since estimate ${confirm} (it is now ${id}). Nothing was sent.`)
638
+ return 1
639
+ }
640
+ result = await call(tool.name, args)
641
+ }
642
+ } else result = await call(tool.name, args)
643
+
644
+ const root = tools.root()
645
+ const dir = options.save ? path.resolve(d.cwd, options.save) : path.join(root ?? d.cwd, '.nowhere', 'shots')
646
+ const files = saveImages(result, { dir, tool: tool.name, stamp: stampOf(d.now()) })
647
+ if (options.raw) {
648
+ let n = 0
649
+ const content = (result.content ?? []).map((c) => (c.type === 'image' ? { type: 'image', mimeType: c.mimeType, file: files[n++] } : c))
650
+ d.out(JSON.stringify({ ...result, content }, null, 2))
651
+ } else {
652
+ const text = textOf(result)
653
+ if (text) d.out(text)
654
+ for (const file of files) d.out(`saved ${file}`)
655
+ }
656
+ return result.isError ? 1 : 0
657
+ } catch (err) {
658
+ // What a stop closed is not an error to print: the command stopped.
659
+ if (stopping || err === STOPPED) {
660
+ await tools?.close().catch(() => {})
661
+ return 130
662
+ }
663
+ throw err
664
+ } finally {
665
+ for (const signal of SIGNALS) d.signals.off?.(signal, stop)
666
+ await tools?.close().catch(() => {})
667
+ }
668
+ }