oda-engine 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (204) hide show
  1. package/README.md +151 -2
  2. package/bin/nowhere.mjs +352 -0
  3. package/lib/account.mjs +57 -0
  4. package/lib/agentModules.mjs +57 -0
  5. package/lib/devServer.mjs +351 -0
  6. package/lib/headless.mjs +231 -0
  7. package/lib/headlessPreview.mjs +212 -0
  8. package/lib/keys.mjs +517 -0
  9. package/lib/make.mjs +855 -0
  10. package/lib/mcp.mjs +537 -0
  11. package/lib/open.mjs +22 -0
  12. package/lib/preview.mjs +87 -0
  13. package/lib/previewRpc.mjs +134 -0
  14. package/lib/project.mjs +359 -0
  15. package/lib/publishFlow.mjs +90 -0
  16. package/lib/resources.mjs +50 -0
  17. package/lib/rules.mjs +60 -0
  18. package/lib/scaffold.mjs +42 -0
  19. package/lib/setup.mjs +59 -0
  20. package/lib/tools.mjs +668 -0
  21. package/package.json +51 -4
  22. package/template/game.config.json +9 -0
  23. package/template/scene.json +4 -0
  24. package/template/src/main.ts +11 -0
  25. package/vendor/DOCS.md +447 -0
  26. package/vendor/agent/appRun.mjs +520 -0
  27. package/vendor/agent/assets/brief.mjs +242 -0
  28. package/vendor/agent/assets/collider.mjs +531 -0
  29. package/vendor/agent/assets/environments/index.mjs +12 -0
  30. package/vendor/agent/assets/environments/worldlabs.mjs +161 -0
  31. package/vendor/agent/assets/fetch.mjs +168 -0
  32. package/vendor/agent/assets/footprint.mjs +13 -0
  33. package/vendor/agent/assets/gltf.mjs +547 -0
  34. package/vendor/agent/assets/hdr.mjs +269 -0
  35. package/vendor/agent/assets/imageOps.mjs +171 -0
  36. package/vendor/agent/assets/images/codex.mjs +307 -0
  37. package/vendor/agent/assets/images/fal.mjs +75 -0
  38. package/vendor/agent/assets/images/gemini.mjs +84 -0
  39. package/vendor/agent/assets/images/index.mjs +25 -0
  40. package/vendor/agent/assets/images/openai.mjs +75 -0
  41. package/vendor/agent/assets/images/stability.mjs +71 -0
  42. package/vendor/agent/assets/images/views.mjs +31 -0
  43. package/vendor/agent/assets/import.mjs +1352 -0
  44. package/vendor/agent/assets/inspect.mjs +465 -0
  45. package/vendor/agent/assets/jobs.mjs +196 -0
  46. package/vendor/agent/assets/ktx2.mjs +290 -0
  47. package/vendor/agent/assets/ledger.mjs +466 -0
  48. package/vendor/agent/assets/net.mjs +254 -0
  49. package/vendor/agent/assets/prices.json +39 -0
  50. package/vendor/agent/assets/providers/fal.mjs +115 -0
  51. package/vendor/agent/assets/providers/index.mjs +22 -0
  52. package/vendor/agent/assets/providers/meshy.mjs +119 -0
  53. package/vendor/agent/assets/providers/tripo.mjs +188 -0
  54. package/vendor/agent/assets/sources/ambientcg.mjs +129 -0
  55. package/vendor/agent/assets/sources/index.mjs +23 -0
  56. package/vendor/agent/assets/sources/polyhaven.mjs +237 -0
  57. package/vendor/agent/assets/sources/polypizza.mjs +121 -0
  58. package/vendor/agent/assets/splat.mjs +631 -0
  59. package/vendor/agent/assets/targets.mjs +122 -0
  60. package/vendor/agent/assets/tile.mjs +261 -0
  61. package/vendor/agent/assets/unzip.mjs +180 -0
  62. package/vendor/agent/blender/cleanup.py +360 -0
  63. package/vendor/agent/blender/convert.py +167 -0
  64. package/vendor/agent/blender/find.mjs +192 -0
  65. package/vendor/agent/blender/nw_export.py +104 -0
  66. package/vendor/agent/blender/nw_rubric.py +426 -0
  67. package/vendor/agent/blender/run.mjs +193 -0
  68. package/vendor/agent/blender/runner.py +252 -0
  69. package/vendor/agent/blender/sheet.py +743 -0
  70. package/vendor/agent/depth.mjs +134 -0
  71. package/vendor/agent/director/board.mjs +451 -0
  72. package/vendor/agent/director/contracts.mjs +663 -0
  73. package/vendor/agent/director/director.mjs +2365 -0
  74. package/vendor/agent/director/estimate.mjs +200 -0
  75. package/vendor/agent/director/gate.mjs +802 -0
  76. package/vendor/agent/director/limits.json +16 -0
  77. package/vendor/agent/director/methods.mjs +457 -0
  78. package/vendor/agent/director/policy.json +33 -0
  79. package/vendor/agent/director/prompts.mjs +244 -0
  80. package/vendor/agent/director/reading.mjs +341 -0
  81. package/vendor/agent/director/router.mjs +184 -0
  82. package/vendor/agent/director/seams.mjs +243 -0
  83. package/vendor/agent/director/session.mjs +643 -0
  84. package/vendor/agent/director/store.mjs +119 -0
  85. package/vendor/agent/director/taskGate.mjs +110 -0
  86. package/vendor/agent/director/teamLedger.mjs +118 -0
  87. package/vendor/agent/director/triage.mjs +63 -0
  88. package/vendor/agent/downloads.cjs +363 -0
  89. package/vendor/agent/flow.mjs +78 -0
  90. package/vendor/agent/guard.mjs +613 -0
  91. package/vendor/agent/host.mjs +1736 -0
  92. package/vendor/agent/language.mjs +58 -0
  93. package/vendor/agent/ledger.mjs +360 -0
  94. package/vendor/agent/locale.cjs +186 -0
  95. package/vendor/agent/loop/capacity.mjs +74 -0
  96. package/vendor/agent/loop/compose.mjs +127 -0
  97. package/vendor/agent/loop/gate.mjs +205 -0
  98. package/vendor/agent/loop/judge.mjs +189 -0
  99. package/vendor/agent/loop/levels.mjs +273 -0
  100. package/vendor/agent/loop/state.mjs +358 -0
  101. package/vendor/agent/notes.cjs +278 -0
  102. package/vendor/agent/pace.mjs +258 -0
  103. package/vendor/agent/panels.mjs +431 -0
  104. package/vendor/agent/prompt.mjs +342 -0
  105. package/vendor/agent/reference/board.mjs +410 -0
  106. package/vendor/agent/reference/compose.mjs +364 -0
  107. package/vendor/agent/reference/decode.mjs +56 -0
  108. package/vendor/agent/reference/facts.mjs +1874 -0
  109. package/vendor/agent/reference/png.mjs +107 -0
  110. package/vendor/agent/reference/records.mjs +63 -0
  111. package/vendor/agent/reference/web.mjs +252 -0
  112. package/vendor/agent/roles/artist.mjs +69 -0
  113. package/vendor/agent/roles/builder.mjs +79 -0
  114. package/vendor/agent/roles/checks.mjs +223 -0
  115. package/vendor/agent/roles/common.mjs +188 -0
  116. package/vendor/agent/roles/critic.mjs +171 -0
  117. package/vendor/agent/roles/index.mjs +39 -0
  118. package/vendor/agent/roles/modeller.mjs +142 -0
  119. package/vendor/agent/roles/qa.mjs +58 -0
  120. package/vendor/agent/roles/rubrics.mjs +79 -0
  121. package/vendor/agent/roles/sound.mjs +69 -0
  122. package/vendor/agent/rounds.cjs +333 -0
  123. package/vendor/agent/shared.mjs +284 -0
  124. package/vendor/agent/stopGate.mjs +574 -0
  125. package/vendor/agent/subagents.mjs +129 -0
  126. package/vendor/agent/tools/assets.mjs +499 -0
  127. package/vendor/agent/tools/blender.mjs +754 -0
  128. package/vendor/agent/tools/cards.mjs +479 -0
  129. package/vendor/agent/tools/choices.mjs +479 -0
  130. package/vendor/agent/tools/compose.mjs +74 -0
  131. package/vendor/agent/tools/environment.mjs +488 -0
  132. package/vendor/agent/tools/eyes.mjs +733 -0
  133. package/vendor/agent/tools/generate.mjs +338 -0
  134. package/vendor/agent/tools/guide.mjs +46 -0
  135. package/vendor/agent/tools/harness.mjs +193 -0
  136. package/vendor/agent/tools/image.mjs +643 -0
  137. package/vendor/agent/tools/index.mjs +162 -0
  138. package/vendor/agent/tools/look.mjs +578 -0
  139. package/vendor/agent/tools/loop.mjs +858 -0
  140. package/vendor/agent/tools/others.mjs +123 -0
  141. package/vendor/agent/tools/pictures.mjs +535 -0
  142. package/vendor/agent/tools/reference.mjs +366 -0
  143. package/vendor/agent/transcripts.mjs +118 -0
  144. package/vendor/agent-loop.mjs +602 -0
  145. package/vendor/agent-plugin/.claude-plugin/plugin.json +5 -0
  146. package/vendor/agent-plugin/skills/art-direction/SKILL.md +82 -0
  147. package/vendor/agent-plugin/skills/asset-legality/SKILL.md +101 -0
  148. package/vendor/agent-plugin/skills/asset-sources/SKILL.md +111 -0
  149. package/vendor/agent-plugin/skills/blender-modeling/SKILL.md +97 -0
  150. package/vendor/agent-plugin/skills/look-dev/SKILL.md +104 -0
  151. package/vendor/agent-plugin/skills/playtesting/SKILL.md +74 -0
  152. package/vendor/agent-plugin/skills/reference-loop/SKILL.md +102 -0
  153. package/vendor/agent-plugin/skills/sound-design/SKILL.md +60 -0
  154. package/vendor/agent-plugin/skills/style/SKILL.md +35 -0
  155. package/vendor/agent-plugin/skills/tsl-r185/SKILL.md +107 -0
  156. package/vendor/auth.cjs +570 -0
  157. package/vendor/build.cjs +953 -0
  158. package/vendor/catalog.json +455 -0
  159. package/vendor/connectors.cjs +688 -0
  160. package/vendor/eyes.mjs +733 -0
  161. package/vendor/gameExports.json +1390 -0
  162. package/vendor/git.cjs +222 -0
  163. package/vendor/models.json +57 -0
  164. package/vendor/publish.cjs +1018 -0
  165. package/vendor/refBoard.cjs +301 -0
  166. package/vendor/schema/dist/assets.d.ts +335 -0
  167. package/vendor/schema/dist/assets.js +439 -0
  168. package/vendor/schema/dist/brief.d.ts +357 -0
  169. package/vendor/schema/dist/brief.js +302 -0
  170. package/vendor/schema/dist/common.d.ts +9 -0
  171. package/vendor/schema/dist/common.js +13 -0
  172. package/vendor/schema/dist/config.d.ts +406 -0
  173. package/vendor/schema/dist/config.js +355 -0
  174. package/vendor/schema/dist/contract.d.ts +599 -0
  175. package/vendor/schema/dist/contract.js +1146 -0
  176. package/vendor/schema/dist/index.d.ts +14 -0
  177. package/vendor/schema/dist/index.js +21 -0
  178. package/vendor/schema/dist/look.d.ts +463 -0
  179. package/vendor/schema/dist/look.js +681 -0
  180. package/vendor/schema/dist/lookStats.d.ts +230 -0
  181. package/vendor/schema/dist/lookStats.js +768 -0
  182. package/vendor/schema/dist/pilot.d.ts +32 -0
  183. package/vendor/schema/dist/pilot.js +44 -0
  184. package/vendor/schema/dist/publish.d.ts +214 -0
  185. package/vendor/schema/dist/publish.js +291 -0
  186. package/vendor/schema/dist/scene.d.ts +75 -0
  187. package/vendor/schema/dist/scene.js +120 -0
  188. package/vendor/schema/dist/skyLight.d.ts +141 -0
  189. package/vendor/schema/dist/skyLight.js +436 -0
  190. package/vendor/schema/dist/style.d.ts +131 -0
  191. package/vendor/schema/dist/style.js +155 -0
  192. package/vendor/schema/package.json +1 -0
  193. package/vendor/selectionPrompt.mjs +51 -0
  194. package/vendor/useTools.mjs +195 -0
  195. package/vendor/userMessage.mjs +26 -0
  196. package/web-dist/assets/GaussianSplatUtils-CB77cP9U.js +1 -0
  197. package/web-dist/assets/KTX2Loader-6OIWUF7s.js +2 -0
  198. package/web-dist/assets/SPZLoader-zYj0Alfv.js +1 -0
  199. package/web-dist/assets/gaussianSplat-CJTI1sEh.js +1 -0
  200. package/web-dist/assets/index-CcjyyQco.css +1 -0
  201. package/web-dist/assets/index-DMyJcoZJ.js +693 -0
  202. package/web-dist/assets/meshopt_decoder.module-BvwdjiD3.js +1 -0
  203. package/web-dist/assets/zstddec.module-CfFeQW7d.js +1 -0
  204. package/web-dist/index.html +34 -0
package/lib/keys.mjs ADDED
@@ -0,0 +1,517 @@
1
+ // The services' API keys for the terminal: `nowhere tool` and its short forms,
2
+ // `nowhere make` and `nowhere mcp` find them here, so nobody has to export
3
+ // MESHY_API_KEY before every command. `nowhere keys set|list|test|remove|path`
4
+ // keeps them.
5
+ //
6
+ // macOS the login Keychain, one item per variable (service "nowhere",
7
+ // account the variable's name), written through `security -i`
8
+ // on its stdin as hex, so a key is never on a command line
9
+ // elsewhere ~/.config/nowhere/keys.json, created 0600 beside session.json
10
+ // (NOWHERE_CONFIG_DIR moves both). On a Mac the same file holds
11
+ // the names of the Keychain's items, which the Keychain cannot
12
+ // list cheaply, and any key the Keychain refused.
13
+ //
14
+ // The environment always wins: loadKeys() fills a stored key into process.env
15
+ // only where the variable is unset or blank. No value is ever printed or
16
+ // logged; a list shows the last four characters at most. The studio app keeps
17
+ // its own keys (Electron's safeStorage), so a key stored here is for the
18
+ // terminal. Inside an agent's run (NOWHERE_AGENT_RUN=1, set by the studio's
19
+ // host for its agents) the bin loads none of them, and set and remove refuse.
20
+
21
+ import { spawnSync } from 'node:child_process'
22
+ import fs from 'node:fs'
23
+ import path from 'node:path'
24
+ import { CONFIG_DIR } from './account.mjs'
25
+ import { vendor } from './resources.mjs'
26
+
27
+ export const KEYS_FILE = path.join(CONFIG_DIR, 'keys.json')
28
+
29
+ const SERVICE = 'nowhere'
30
+ const SECURITY = '/usr/bin/security'
31
+ /** security's exit code for an item that is not there (errSecItemNotFound). */
32
+ const NOT_FOUND = 44
33
+ const ENV_NAME = /^[A-Z][A-Z0-9_]*$/
34
+
35
+ /** The agent's own key, for a catalog that does not list it. */
36
+ const ANTHROPIC = Object.freeze({
37
+ id: 'anthropic',
38
+ name: 'Claude',
39
+ vendor: 'Anthropic',
40
+ category: 'agent',
41
+ auth: Object.freeze({ type: 'apiKey', envVar: 'ANTHROPIC_API_KEY', keyPrefix: 'sk-ant-', keyUrl: 'https://platform.claude.com/settings/keys' }),
42
+ })
43
+
44
+ let connectorsModule = null
45
+ const connectors = () => (connectorsModule ??= vendor('connectors.cjs'))
46
+
47
+ let entries = null
48
+ /** The catalog's keyed services (auth.type apiKey), the Anthropic key among them. */
49
+ export function keyEntries() {
50
+ if (!entries) {
51
+ const keyed = connectors()
52
+ .loadCatalog()
53
+ .filter((entry) => entry.auth?.type === 'apiKey' && ENV_NAME.test(String(entry.auth.envVar ?? '')))
54
+ entries = keyed.some((entry) => entry.id === ANTHROPIC.id || entry.auth.envVar === ANTHROPIC.auth.envVar) ? keyed : [ANTHROPIC, ...keyed]
55
+ }
56
+ return entries
57
+ }
58
+
59
+ /**
60
+ * What a key is called on the command line: a catalog id (meshy) or its
61
+ * variable (MESHY_API_KEY), either case, or any other variable written as one
62
+ * (UPPER_CASE). Null for anything else, and for a connector that has no key
63
+ * (blender).
64
+ */
65
+ export function resolveKey(arg) {
66
+ const word = String(arg ?? '').trim()
67
+ if (!word) return null
68
+ const lower = word.toLowerCase()
69
+ const upper = word.toUpperCase()
70
+ const entry = keyEntries().find((e) => e.id === lower) ?? keyEntries().find((e) => e.auth.envVar === upper)
71
+ if (entry) return { id: entry.id, name: entry.name, envVar: entry.auth.envVar, entry }
72
+ if (ENV_NAME.test(word)) return { id: null, name: word, envVar: word, entry: null }
73
+ return null
74
+ }
75
+
76
+ /** The last four characters, as the studio shows a key; never more. */
77
+ export const hintOf = (value) => (typeof value === 'string' && value.length >= 8 ? value.slice(-4) : '****')
78
+
79
+ const envHas = (env, name) => typeof env?.[name] === 'string' && env[name].trim() !== ''
80
+
81
+ // ---------------------------------------------------------------- the file
82
+
83
+ function readJson(file) {
84
+ try {
85
+ const value = JSON.parse(fs.readFileSync(file, 'utf8'))
86
+ return value && typeof value === 'object' ? value : {}
87
+ } catch {
88
+ return {}
89
+ }
90
+ }
91
+
92
+ /** As account.mjs writes session.json: a 0700 folder, a 0600 file, in one move. */
93
+ function writeJson(file, value) {
94
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 })
95
+ const tmp = `${file}.${process.pid}.tmp`
96
+ fs.writeFileSync(tmp, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 })
97
+ fs.renameSync(tmp, file)
98
+ fs.chmodSync(file, 0o600)
99
+ }
100
+
101
+ // ---------------------------------------------------------------- the Keychain
102
+
103
+ /** Runs `security <args>`, with the commands for -i on its stdin. */
104
+ function runSecurity(args, input) {
105
+ const r = spawnSync(SECURITY, args, { input, encoding: 'utf8', timeout: 30_000 })
106
+ if (r.error) throw r.error
107
+ return { status: r.status, stdout: r.stdout ?? '', stderr: r.stderr ?? '' }
108
+ }
109
+
110
+ const firstLine = (text) => String(text ?? '').split('\n').find((l) => l.trim())?.replace(/^security: /, '') ?? ''
111
+
112
+ function keychainBackend(security) {
113
+ const failure = (what, r) => new Error(`The macOS Keychain ${what}: ${firstLine(r.stderr) || `security exited ${r.status}`}`)
114
+ return {
115
+ get(name) {
116
+ const r = security(['find-generic-password', '-s', SERVICE, '-a', name, '-w'])
117
+ if (r.status === 0) return r.stdout.replace(/\r?\n$/, '')
118
+ if (r.status === NOT_FOUND) return null
119
+ throw failure(`did not give ${name}`, r)
120
+ },
121
+ set(name, value) {
122
+ // The key goes to security's own stdin, as hex: nothing in `ps` or a
123
+ // shell's history sees it, and no quoting applies to it.
124
+ const hex = Buffer.from(value, 'utf8').toString('hex')
125
+ const r = security(['-i'], `add-generic-password -U -s ${SERVICE} -a ${name} -X ${hex}\n`)
126
+ if (r.status !== 0) throw failure(`did not take ${name}`, r)
127
+ },
128
+ remove(name) {
129
+ const r = security(['delete-generic-password', '-s', SERVICE, '-a', name])
130
+ if (r.status === 0) return true
131
+ if (r.status === NOT_FOUND) return false
132
+ throw failure(`did not remove ${name}`, r)
133
+ },
134
+ }
135
+ }
136
+
137
+ // ---------------------------------------------------------------- the store
138
+
139
+ /**
140
+ * The store: the Keychain on a Mac (unless NOWHERE_KEYCHAIN=0), the file
141
+ * elsewhere, and the file on a Mac for a key the Keychain refused. A check
142
+ * hands in its own file and a stand-in for security.
143
+ */
144
+ export function keyStore({ platform = process.platform, env = process.env, file = KEYS_FILE, security = runSecurity } = {}) {
145
+ const keychain = platform === 'darwin' && env.NOWHERE_KEYCHAIN !== '0' ? keychainBackend(security) : null
146
+ const read = () => {
147
+ const doc = readJson(file)
148
+ return {
149
+ keychain: Array.isArray(doc.keychain) ? doc.keychain.filter((n) => typeof n === 'string') : [],
150
+ keys: doc.keys && typeof doc.keys === 'object' && !Array.isArray(doc.keys) ? doc.keys : {},
151
+ }
152
+ }
153
+ const write = (doc) => writeJson(file, { v: 1, ...(doc.keychain.length ? { keychain: doc.keychain } : {}), keys: doc.keys })
154
+
155
+ return {
156
+ kind: keychain ? 'keychain' : 'file',
157
+ file,
158
+ /** Where a key kept in `place` is, in words. */
159
+ placeName: (place) => (place === 'keychain' ? 'the macOS Keychain' : file),
160
+
161
+ /** The stored value and where it is: { value, where: 'keychain' | 'file' | null }.
162
+ * The file first: set() takes a key out of the file whenever the
163
+ * Keychain took it, so a key in the file is always the newest (one the
164
+ * Keychain refused to update, say). */
165
+ lookup(name) {
166
+ const doc = read()
167
+ if (typeof doc.keys[name] === 'string') return { value: doc.keys[name], where: 'file' }
168
+ if (keychain) {
169
+ const value = keychain.get(name)
170
+ if (value !== null) return { value, where: 'keychain' }
171
+ }
172
+ return { value: null, where: null }
173
+ },
174
+ get(name) {
175
+ return this.lookup(name).value
176
+ },
177
+
178
+ /** The names stored here (the Keychain's through the file's list). */
179
+ names() {
180
+ const doc = read()
181
+ return [...new Set([...doc.keychain, ...Object.keys(doc.keys)])]
182
+ },
183
+ /** Puts a Keychain item's name on the list when it is missing there. */
184
+ index(name) {
185
+ const doc = read()
186
+ if (doc.keychain.includes(name)) return
187
+ doc.keychain.push(name)
188
+ write(doc)
189
+ },
190
+
191
+ /** Stores a key: { where: 'keychain' | 'file', refusal } (the Keychain's words when it fell back to the file). */
192
+ set(name, value) {
193
+ const doc = read()
194
+ let refusal = null
195
+ if (keychain) {
196
+ try {
197
+ keychain.set(name, value)
198
+ if (!doc.keychain.includes(name)) doc.keychain.push(name)
199
+ delete doc.keys[name]
200
+ write(doc)
201
+ return { where: 'keychain', refusal: null }
202
+ } catch (err) {
203
+ refusal = err?.message ?? String(err)
204
+ }
205
+ // An older value the Keychain still holds goes, where it lets it.
206
+ try {
207
+ keychain.remove(name)
208
+ } catch {
209
+ // the file's value is read first anyway
210
+ }
211
+ }
212
+ doc.keys[name] = value
213
+ doc.keychain = doc.keychain.filter((n) => n !== name)
214
+ write(doc)
215
+ return { where: 'file', refusal }
216
+ },
217
+
218
+ /** Forgets a key wherever it is; false when nothing was stored. */
219
+ remove(name) {
220
+ const doc = read()
221
+ let removed = false
222
+ if (keychain) {
223
+ try {
224
+ removed = keychain.remove(name)
225
+ } catch (err) {
226
+ if (err?.code !== 'ENOENT') throw err
227
+ }
228
+ }
229
+ if (typeof doc.keys[name] === 'string') {
230
+ delete doc.keys[name]
231
+ removed = true
232
+ }
233
+ const listed = doc.keychain.includes(name)
234
+ doc.keychain = doc.keychain.filter((n) => n !== name)
235
+ if (removed || listed) write(doc)
236
+ return removed
237
+ },
238
+ }
239
+ }
240
+
241
+ let shared = null
242
+ const storeOf = (given) => given ?? (shared ??= keyStore())
243
+
244
+ /** The stored value of a variable, or null. */
245
+ export function getKey(envVar, store) {
246
+ return storeOf(store).get(envVar)
247
+ }
248
+
249
+ /** Stores a value; answers { where, refusal } as the store does. */
250
+ export function setKey(envVar, value, store) {
251
+ return storeOf(store).set(envVar, value)
252
+ }
253
+
254
+ /** Forgets a stored value; false when there was none. */
255
+ export function removeKey(envVar, store) {
256
+ return storeOf(store).remove(envVar)
257
+ }
258
+
259
+ /**
260
+ * Every key the catalog names, and every other one stored here, each as
261
+ * { id, name, envVar, status, where, hint, problem, line }: status is
262
+ * 'environment' (set in env, which wins), 'stored', 'unset', or 'problem'
263
+ * when the store did not answer. The line is what `nowhere keys list`
264
+ * prints; it never holds a value.
265
+ */
266
+ export function listKeys({ env = process.env, store, only = null } = {}) {
267
+ const s = storeOf(store)
268
+ const items = []
269
+ const seen = new Set()
270
+ const describe = (id, name, envVar) => {
271
+ seen.add(envVar)
272
+ let found = { value: null, where: null }
273
+ let problem = null
274
+ try {
275
+ found = s.lookup(envVar)
276
+ } catch (err) {
277
+ problem = err?.message ?? String(err)
278
+ }
279
+ // A Keychain item the list did not know of (the file was lost) is put
280
+ // back on it, so loadKeys() finds it too.
281
+ if (found.where === 'keychain') s.index(envVar)
282
+ const hint = found.value !== null ? hintOf(found.value) : null
283
+ const status = envHas(env, envVar) ? 'environment' : found.where ? 'stored' : problem ? 'problem' : 'unset'
284
+ const said =
285
+ status === 'environment'
286
+ ? `from the environment${found.where ? ` (a stored one, ending in ${hint}, is not used)` : ''}`
287
+ : status === 'stored'
288
+ ? `stored (${found.where}), ending in ${hint}`
289
+ : status === 'problem'
290
+ ? `not read: ${problem}`
291
+ : 'not set'
292
+ return { id, name, envVar, status, where: found.where, hint, problem, line: `${(id ?? '-').padEnd(12)} ${envVar.padEnd(20)} ${said}` }
293
+ }
294
+ for (const entry of keyEntries()) {
295
+ if (!only || only.envVar === entry.auth.envVar) items.push(describe(entry.id, entry.name, entry.auth.envVar))
296
+ }
297
+ for (const envVar of s.names()) {
298
+ if (!seen.has(envVar) && (!only || only.envVar === envVar)) items.push(describe(null, envVar, envVar))
299
+ }
300
+ if (only && !items.length) items.push(describe(only.id, only.name, only.envVar))
301
+ return items
302
+ }
303
+
304
+ /**
305
+ * Puts every stored key into `env` where the variable is unset or blank (the
306
+ * environment wins), and answers the names it filled, never the values. A
307
+ * key the store could not give is reported through `warn` and skipped.
308
+ * `only`, when given, says which names may be loaded (nowhere make takes
309
+ * the catalog's alone, the ones the agent's guard knows to keep secret).
310
+ */
311
+ export function loadKeys(env = process.env, { store, warn = () => {}, only = null } = {}) {
312
+ const s = storeOf(store)
313
+ const loaded = []
314
+ for (const name of s.names()) {
315
+ if (envHas(env, name) || (only && !only(name))) continue
316
+ try {
317
+ const value = s.get(name)
318
+ if (value === null) continue
319
+ env[name] = value
320
+ loaded.push(name)
321
+ } catch (err) {
322
+ warn(`${name} was not loaded: ${err?.message ?? err}`)
323
+ }
324
+ }
325
+ return loaded
326
+ }
327
+
328
+ // ---------------------------------------------------------------- the commands
329
+
330
+ export const KEYS_HELP = `oda keys set <id|ENV_VAR> [value] store a key: pasted at a prompt (not shown), piped on stdin, or given here
331
+ oda keys list [id|ENV_VAR] each key: stored (ending in its last four characters), from the environment, or not set
332
+ oda keys test <id> try the key that would be used against the service
333
+ oda keys remove <id|ENV_VAR> forget a stored key
334
+ oda keys path where the keys are kept
335
+
336
+ A key is named by its service (oda keys list has the ids) or by its variable (MESHY_API_KEY);
337
+ any other UPPER_CASE variable can be stored too. On a Mac they live in the login Keychain, one
338
+ item per variable (service "nowhere"); elsewhere, and for a key the Keychain refused, in
339
+ ~/.config/nowhere/keys.json, readable only by you (NOWHERE_CONFIG_DIR moves it, NOWHERE_KEYCHAIN=0
340
+ keeps everything in the file). The environment wins: a variable already set is used as it is.
341
+ oda tool, make and mcp read these (NOWHERE_STORED_KEYS=0 keeps them out of a command); the
342
+ studio app keeps its own keys. Any program running as you can read them, as it can the file.`
343
+
344
+ const ids = () => keyEntries().map((e) => e.id).join(', ')
345
+ const unknownKey = (word) => `There is no key "${word}". The ids: ${ids()}. Or name the variable itself, written as one (MESHY_API_KEY).`
346
+ const label = (key) => (key.id ? `${key.name} (${key.envVar})` : key.envVar)
347
+
348
+ /** A line typed with nothing shown: raw mode on a terminal, ended by Enter (Ctrl-C gives up). */
349
+ export function readHidden({ input, output, prompt }) {
350
+ return new Promise((resolve, reject) => {
351
+ output.write(prompt)
352
+ const raw = typeof input.setRawMode === 'function'
353
+ if (raw) input.setRawMode(true)
354
+ input.setEncoding?.('utf8')
355
+ let typed = ''
356
+ const finish = (err, value) => {
357
+ input.off('data', onData)
358
+ if (raw) input.setRawMode(false)
359
+ input.pause?.()
360
+ output.write('\n')
361
+ if (err) reject(err)
362
+ else resolve(value)
363
+ }
364
+ const onData = (chunk) => {
365
+ for (const ch of String(chunk)) {
366
+ if (ch === '\r' || ch === '\n' || ch === '\u0004') return finish(null, typed)
367
+ if (ch === '\u0003') return finish(new Error('Cancelled; nothing was stored.'))
368
+ if (ch === '\u007f' || ch === '\b') typed = typed.slice(0, -1)
369
+ else if (ch >= ' ') typed += ch
370
+ }
371
+ }
372
+ input.on('data', onData)
373
+ input.resume?.()
374
+ })
375
+ }
376
+
377
+ /** The first non-blank line of what was piped in (pbpaste | nowhere keys set meshy). */
378
+ async function readPiped(input) {
379
+ input.setEncoding?.('utf8')
380
+ let text = ''
381
+ for await (const chunk of input) text += chunk
382
+ return text.split(/\r?\n/).map((l) => l.trim()).find(Boolean) ?? ''
383
+ }
384
+
385
+ /**
386
+ * `nowhere keys <sub> ...`: the exit code, 0 or 1. A check hands in its own
387
+ * terminal and store; `nowhere keys test` reaches the service with the
388
+ * global fetch.
389
+ */
390
+ export async function runKeys(argv, deps = {}) {
391
+ const d = {
392
+ out: (line) => process.stdout.write(`${line}\n`),
393
+ err: (line) => process.stderr.write(`${line}\n`),
394
+ input: process.stdin,
395
+ output: process.stderr,
396
+ env: process.env,
397
+ store: undefined,
398
+ ...deps,
399
+ }
400
+ const [sub, ...words] = argv
401
+ // The creator's store is theirs to change: an agent's run (the studio's or
402
+ // nowhere make's, NOWHERE_AGENT_RUN) may read the list, not set or remove.
403
+ if ((sub === 'set' || sub === 'remove') && d.env?.NOWHERE_AGENT_RUN === '1') {
404
+ d.err(`Nothing was changed: oda keys ${sub} is the creator's own command, and this one runs inside an agent's run.`)
405
+ return 1
406
+ }
407
+ const store = storeOf(d.store)
408
+ const target = (what) => {
409
+ if (!words[0]) {
410
+ d.err(`Which key? oda keys ${what} <id|ENV_VAR>. The ids: ${ids()}.`)
411
+ return null
412
+ }
413
+ const key = resolveKey(words[0])
414
+ if (!key) d.err(unknownKey(words[0]))
415
+ return key
416
+ }
417
+
418
+ switch (sub) {
419
+ case undefined:
420
+ case 'help':
421
+ case '--help':
422
+ case '-h':
423
+ d.out(KEYS_HELP)
424
+ return 0
425
+
426
+ case 'path': {
427
+ d.out(
428
+ store.kind === 'keychain'
429
+ ? `The login Keychain, one item per key (service "nowhere", account the variable's name).\nThe names of those items, and any key the Keychain refused: ${store.file}`
430
+ : store.file,
431
+ )
432
+ return 0
433
+ }
434
+
435
+ case 'list': {
436
+ const only = words[0] ? resolveKey(words[0]) : null
437
+ if (words[0] && !only) {
438
+ d.err(unknownKey(words[0]))
439
+ return 1
440
+ }
441
+ for (const item of listKeys({ env: d.env, store, only })) d.out(item.line)
442
+ return 0
443
+ }
444
+
445
+ case 'set': {
446
+ const key = target('set')
447
+ if (!key) return 1
448
+ let value = words[1]
449
+ if (typeof value === 'string') {
450
+ d.err(`The key was given on the command line, so this shell's history has it now. Next time run \`oda keys set ${key.id ?? key.envVar}\` alone and paste it at the prompt.`)
451
+ } else if (d.input.isTTY) {
452
+ try {
453
+ value = await readHidden({ input: d.input, output: d.output, prompt: `Paste the ${label(key)} key; it is not shown: ` })
454
+ } catch (err) {
455
+ d.err(err?.message ?? String(err))
456
+ return 1
457
+ }
458
+ } else value = await readPiped(d.input)
459
+ value = String(value ?? '').trim()
460
+ const problem = connectors().keyProblem(key.entry, value)
461
+ if (problem) {
462
+ d.err(problem)
463
+ return 1
464
+ }
465
+ const put = store.set(key.envVar, value)
466
+ d.out(`Stored ${label(key)}, ending in ${hintOf(value)}, in ${store.placeName(put.where)}.`)
467
+ if (put.refusal) d.err(`The Keychain refused it (${put.refusal}), so it went to the file.`)
468
+ if (envHas(d.env, key.envVar)) d.err(`${key.envVar} is also set in this shell's environment, and that one wins until it is unset.`)
469
+ return 0
470
+ }
471
+
472
+ case 'remove': {
473
+ const key = target('remove')
474
+ if (!key) return 1
475
+ const removed = store.remove(key.envVar)
476
+ d.out(removed ? `Removed ${label(key)}.` : `${label(key)} was not stored.`)
477
+ if (envHas(d.env, key.envVar)) d.err(`${key.envVar} is still set in this shell's environment.`)
478
+ return removed ? 0 : 1
479
+ }
480
+
481
+ case 'test': {
482
+ const key = target('test')
483
+ if (!key) return 1
484
+ if (!key.entry) {
485
+ d.err(`${key.envVar} is not a service in the catalog, so there is nothing to test it against. The ids: ${ids()}.`)
486
+ return 1
487
+ }
488
+ let stored = { value: null, where: null }
489
+ let problem = null
490
+ try {
491
+ stored = store.lookup(key.envVar)
492
+ } catch (err) {
493
+ problem = err?.message ?? String(err)
494
+ }
495
+ const fromEnv = envHas(d.env, key.envVar) ? d.env[key.envVar].trim() : null
496
+ const source = fromEnv ? 'from the environment' : stored.where ? `stored in ${store.placeName(stored.where)}` : null
497
+ if (!source) {
498
+ d.err(`${key.id}: no key to test.${problem ? ` ${problem}.` : ''} oda keys set ${key.id}`)
499
+ return 1
500
+ }
501
+ // The same test the studio's Settings run, against the key that a
502
+ // command here would use: the environment's, else the stored one.
503
+ const ctx = {
504
+ userData: CONFIG_DIR,
505
+ env: d.env,
506
+ secrets: { getSecret: (id) => (id === key.id ? (fromEnv ?? stored.value) : null), listConnected: () => ({}) },
507
+ }
508
+ const result = await connectors().test(ctx, key.id)
509
+ d.out(`${key.id}: ${result.status}. ${result.detail} Tested the key ${source}.`)
510
+ return result.status === 'ok' ? 0 : 1
511
+ }
512
+
513
+ default:
514
+ d.err(`Unknown: oda keys ${sub}.\n\n${KEYS_HELP}`)
515
+ return 1
516
+ }
517
+ }