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,688 @@
1
+ // Connector logic for the main process: which services are on, what the agent
2
+ // gets for them, and the connection test. Electron-free on purpose: main hands
3
+ // in a context { userData, secrets, env } and the test suite hands in fakes.
4
+ //
5
+ // Secrets never leave this module in any form but a stored value handed to the
6
+ // agent host: ConnectorStatus.hint and TestResult.detail are built from the
7
+ // four-character hint and HTTP status codes only.
8
+
9
+ const fs = require('node:fs')
10
+ const net = require('node:net')
11
+ const os = require('node:os')
12
+ const path = require('node:path')
13
+
14
+ // The catalog is data, so main reads the same file the renderer bundles. A
15
+ // packaged app has no src/ tree, and the build emits a copy next to the
16
+ // renderer bundle; the source tree wins while it exists, so a dev edit is never
17
+ // shadowed by a stale build.
18
+ const CATALOG_FILES = [
19
+ path.join(__dirname, '..', 'src', 'connectors', 'catalog.json'),
20
+ path.join(__dirname, '..', 'dist', 'catalog.json'),
21
+ path.join(__dirname, 'catalog.json'),
22
+ ]
23
+ const SETTINGS_FILE = 'connectors.json'
24
+ const ID_SHAPE = /^[a-z][a-z0-9]*$/
25
+ // Claude runs the agent instead of being a service the agent calls, so its key
26
+ // is the one an inherited environment variable may enable on its own.
27
+ const AGENT_ID = 'anthropic'
28
+ // Anthropic keys are `sk-ant-` followed by a long opaque tail. Like every check
29
+ // in keyProblem this only catches a mispaste (a truncated copy, a shell prompt
30
+ // dragged along); whether a key works is the vendor's answer to give.
31
+ const ANTHROPIC_SHAPE = /^sk-ant-[A-Za-z0-9_-]{24,300}$/
32
+ const ENCRYPTION_UNAVAILABLE =
33
+ 'This system has no OS-level encryption available, so the key cannot be stored here.'
34
+
35
+ // ---------------------------------------------------------------- catalog
36
+
37
+ // The renderer validates the same file with zod (catalog.ts). Main cannot load
38
+ // that module, so this only checks what the functions below lean on.
39
+ function loadCatalog(files = CATALOG_FILES) {
40
+ const file = files.find((candidate) => fs.existsSync(candidate))
41
+ if (!file) throw new Error(`connector catalog not found (looked in ${files.join(', ')})`)
42
+ const raw = JSON.parse(fs.readFileSync(file, 'utf8'))
43
+ if (!Array.isArray(raw)) throw new Error('connector catalog is not an array')
44
+ for (const entry of raw) {
45
+ if (typeof entry?.id !== 'string' || !ID_SHAPE.test(entry.id)) {
46
+ throw new Error(`connector catalog: bad id ${JSON.stringify(entry?.id)}`)
47
+ }
48
+ if (entry.auth?.type !== 'apiKey' && entry.auth?.type !== 'mcp') {
49
+ throw new Error(`connector ${entry.id}: unknown auth type`)
50
+ }
51
+ }
52
+ return Object.freeze(raw.map((entry) => Object.freeze(entry)))
53
+ }
54
+
55
+ // This module is required before `app.whenReady()`, so a catalog that will not
56
+ // parse must not take the studio down before a window exists: the app comes up
57
+ // with no connectors and main reports the problem once it can show a dialog.
58
+ let CATALOG = []
59
+ let catalogError = null
60
+ try {
61
+ CATALOG = loadCatalog()
62
+ } catch (err) {
63
+ catalogError = err?.message ?? String(err)
64
+ }
65
+
66
+ /** The message for the load failure, or null when the catalog is good. */
67
+ function catalogProblem() {
68
+ return catalogError
69
+ }
70
+
71
+ const EXTERNAL_URLS = new Set(
72
+ CATALOG.flatMap((c) => (c.auth.type === 'apiKey' ? [c.auth.docsUrl, c.auth.keyUrl] : [c.auth.docsUrl])),
73
+ )
74
+
75
+ function isKnownId(id) {
76
+ return typeof id === 'string' && CATALOG.some((c) => c.id === id)
77
+ }
78
+
79
+ function entryFor(id) {
80
+ return CATALOG.find((c) => c.id === id) ?? null
81
+ }
82
+
83
+ /** Only a catalog docsUrl or keyUrl may be handed to the system browser. */
84
+ function allowedExternal(url) {
85
+ return typeof url === 'string' && EXTERNAL_URLS.has(url)
86
+ }
87
+
88
+ // ---------------------------------------------------------------- keys
89
+
90
+ /** What is wrong with a pasted key, as { text, code, vars }: the English
91
+ * sentence, and the code and values a chat card shows it by in the
92
+ * screen language (src/cards/labels.ts, error.*). Null when it looks fine. */
93
+ function keyProblemOf(entry, value) {
94
+ const format = (text) => ({ text, code: 'keyFormat' })
95
+ if (typeof value !== 'string' || value.trim() === '') return { text: 'Paste your API key first.', code: 'keyEmpty' }
96
+ const key = value.trim()
97
+ if (/\s/.test(key)) return format('The key contains a space or line break. Copy the whole value, with nothing around it.')
98
+ const prefix = entry?.auth?.keyPrefix
99
+ if (prefix && !key.startsWith(prefix)) return { text: `${entry.vendor} keys start with "${prefix}".`, code: 'keyPrefix', vars: { vendor: entry.vendor, prefix } }
100
+ if (prefix === 'sk-ant-') {
101
+ if (!ANTHROPIC_SHAPE.test(key)) {
102
+ return format('That does not look like a complete Anthropic API key. Copy the whole value, with nothing after it.')
103
+ }
104
+ return null
105
+ }
106
+ if (key.length < 8) return format('That is too short to be an API key.')
107
+ if (key.length > 512) return format('That is too long to be an API key. Copy just the key.')
108
+ return null
109
+ }
110
+
111
+ function keyProblem(entry, value) {
112
+ return keyProblemOf(entry, value)?.text ?? null
113
+ }
114
+
115
+ function envValue(env, name) {
116
+ const value = env?.[name]
117
+ return typeof value === 'string' && value.trim() !== '' ? value.trim() : null
118
+ }
119
+
120
+ // ---------------------------------------------------------------- settings (connectors.json)
121
+
122
+ function emptySettings() {
123
+ return { v: 1, connectors: {} }
124
+ }
125
+
126
+ /** A missing or corrupt file reads as empty; the next write replaces it. */
127
+ function readSettings(userData) {
128
+ try {
129
+ const raw = JSON.parse(fs.readFileSync(path.join(userData, SETTINGS_FILE), 'utf8'))
130
+ if (!raw || typeof raw !== 'object' || raw.v !== 1) return emptySettings()
131
+ const connectors = raw.connectors
132
+ if (!connectors || typeof connectors !== 'object' || Array.isArray(connectors)) return emptySettings()
133
+ return { v: 1, connectors }
134
+ } catch {
135
+ return emptySettings()
136
+ }
137
+ }
138
+
139
+ const singleLine = (s) => typeof s === 'string' && !/[\r\n]/.test(s)
140
+
141
+ function cleanArgs(args) {
142
+ if (!Array.isArray(args) || !args.every(singleLine)) return null
143
+ return args.map((a) => a.trim()).filter((a) => a !== '')
144
+ }
145
+
146
+ /** Only the entry's declared settings survive; values are plain single lines. */
147
+ function cleanSettings(entry, settings) {
148
+ const declared = new Set((entry.auth.settings ?? []).map((s) => s.env))
149
+ const out = {}
150
+ if (!settings || typeof settings !== 'object') return out
151
+ for (const [name, value] of Object.entries(settings)) {
152
+ if (!declared.has(name) || !singleLine(value)) continue
153
+ const trimmed = value.trim()
154
+ if (trimmed !== '' && trimmed.length <= 1000) out[name] = trimmed
155
+ }
156
+ return out
157
+ }
158
+
159
+ function cleanRecord(entry, record) {
160
+ if (!record || typeof record !== 'object') return null
161
+ const out = { enabled: record.enabled === true }
162
+ // An apiKey entry stores one thing: whether a key inherited from the shell
163
+ // may be used. Command lines belong to mcp entries only.
164
+ if (entry.auth.type !== 'mcp') return out
165
+ if (singleLine(record.command) && record.command.trim() !== '') out.command = record.command.trim()
166
+ const args = cleanArgs(record.args)
167
+ if (args) out.args = args
168
+ const settings = cleanSettings(entry, record.settings)
169
+ if (Object.keys(settings).length > 0) out.settings = settings
170
+ return out
171
+ }
172
+
173
+ function writeSettings(userData, doc) {
174
+ const connectors = {}
175
+ for (const [id, record] of Object.entries(doc?.connectors ?? {})) {
176
+ const entry = entryFor(id)
177
+ if (!entry) continue
178
+ const clean = cleanRecord(entry, record)
179
+ if (!clean) continue
180
+ // An apiKey record only ever says "use the environment": once that is off
181
+ // the record has nothing left to say, so it leaves the file.
182
+ if (entry.auth.type !== 'mcp' && !clean.enabled) continue
183
+ connectors[id] = clean
184
+ }
185
+ const target = path.join(userData, SETTINGS_FILE)
186
+ const tmp = `${target}.tmp`
187
+ fs.mkdirSync(userData, { recursive: true })
188
+ fs.writeFileSync(tmp, `${JSON.stringify({ v: 1, connectors }, null, 2)}\n`)
189
+ fs.renameSync(tmp, target)
190
+ }
191
+
192
+ // ---------------------------------------------------------------- status
193
+
194
+ /**
195
+ * Whether a key the studio merely inherited from the shell may be used. The
196
+ * agent's own key is the one exception: the studio cannot start without it, and
197
+ * it is spent on the creator's own session rather than on a vendor's meter.
198
+ * Every other service has to be switched on in Settings, so a variable that
199
+ * happens to be exported for unrelated work never enrolls an account.
200
+ */
201
+ function envAllowed(entry, settingsDoc) {
202
+ if (entry.id === AGENT_ID) return true
203
+ return settingsDoc?.connectors?.[entry.id]?.enabled === true
204
+ }
205
+
206
+ /** Pure: the ConnectorStatus for one entry given what is stored and configured. */
207
+ function statusFor(entry, { stored, env, settingsDoc }) {
208
+ if (entry.auth.type === 'apiKey') {
209
+ const inherited = envValue(env, entry.auth.envVar) !== null
210
+ if (typeof stored === 'string') {
211
+ return {
212
+ id: entry.id,
213
+ status: 'connected',
214
+ source: 'stored',
215
+ hint: stored ? `Key ending in ${stored}` : 'Key stored',
216
+ envAvailable: inherited,
217
+ }
218
+ }
219
+ if (inherited && envAllowed(entry, settingsDoc)) {
220
+ return {
221
+ id: entry.id,
222
+ status: 'connected',
223
+ source: 'env',
224
+ hint: `${entry.auth.envVar} from the environment`,
225
+ envAvailable: true,
226
+ }
227
+ }
228
+ if (inherited) {
229
+ return {
230
+ id: entry.id,
231
+ status: 'needs-key',
232
+ hint: `${entry.auth.envVar} is set in this shell but is not in use.`,
233
+ envAvailable: true,
234
+ }
235
+ }
236
+ return { id: entry.id, status: 'needs-key', hint: '', envAvailable: false }
237
+ }
238
+
239
+ const record = settingsDoc?.connectors?.[entry.id] ?? {}
240
+ const command =
241
+ singleLine(record.command) && record.command.trim() !== '' ? record.command.trim() : entry.auth.command
242
+ const args = cleanArgs(record.args) ?? [...entry.auth.args]
243
+ const settings = cleanSettings(entry, record.settings)
244
+ return {
245
+ id: entry.id,
246
+ status: record.enabled === true ? 'connected' : 'not-connected',
247
+ hint: [command, ...args].join(' '),
248
+ command,
249
+ args,
250
+ settings,
251
+ }
252
+ }
253
+
254
+ function statusOf(ctx, entry) {
255
+ const connected = ctx.secrets.listConnected()
256
+ return statusFor(entry, {
257
+ stored: Object.hasOwn(connected, entry.id) ? connected[entry.id] : null,
258
+ env: ctx.env,
259
+ settingsDoc: readSettings(ctx.userData),
260
+ })
261
+ }
262
+
263
+ function listStatuses(ctx) {
264
+ const connected = ctx.secrets.listConnected()
265
+ const settingsDoc = readSettings(ctx.userData)
266
+ return CATALOG.map((entry) =>
267
+ statusFor(entry, {
268
+ stored: Object.hasOwn(connected, entry.id) ? connected[entry.id] : null,
269
+ env: ctx.env,
270
+ settingsDoc,
271
+ }),
272
+ )
273
+ }
274
+
275
+ // ---------------------------------------------------------------- connect / disconnect
276
+
277
+ function connect(ctx, id, fields) {
278
+ const entry = entryFor(id)
279
+ if (!entry) return { ok: false, error: 'Unknown connector.' }
280
+ const f = fields && typeof fields === 'object' ? fields : {}
281
+
282
+ if (entry.auth.type === 'apiKey') {
283
+ // "Use this key": the creator opting the inherited variable in or out. No
284
+ // key travels with it, and a stored key is left where it is.
285
+ if (f.useEnv !== undefined) {
286
+ if (!envValue(ctx.env, entry.auth.envVar)) {
287
+ return { ok: false, error: `${entry.auth.envVar} is not set in this session.` }
288
+ }
289
+ const doc = readSettings(ctx.userData)
290
+ const previous = doc.connectors[id] && typeof doc.connectors[id] === 'object' ? doc.connectors[id] : {}
291
+ doc.connectors[id] = { ...previous, enabled: f.useEnv === true }
292
+ try {
293
+ writeSettings(ctx.userData, doc)
294
+ } catch (err) {
295
+ return { ok: false, error: `The setting could not be saved (${err.code ?? 'unknown error'}).` }
296
+ }
297
+ return { ok: true, status: statusOf(ctx, entry) }
298
+ }
299
+
300
+ const problem = keyProblemOf(entry, f.key)
301
+ if (problem) return { ok: false, error: problem.text, code: problem.code, ...(problem.vars ? { vars: problem.vars } : {}) }
302
+ if (!ctx.secrets.encryptionAvailable()) return { ok: false, error: ENCRYPTION_UNAVAILABLE, code: 'noEncryption' }
303
+ try {
304
+ ctx.secrets.setSecret(id, f.key.trim())
305
+ } catch (err) {
306
+ // Reported straight to the user, so it carries the failure code only:
307
+ // anything derived from the key itself must never reach a message or a log.
308
+ return { ok: false, error: `The key could not be saved (${err.code ?? 'unknown error'}).`, code: 'notSaved' }
309
+ }
310
+ return { ok: true, status: statusOf(ctx, entry) }
311
+ }
312
+
313
+ // MCP: a field left undefined keeps whatever override is already stored, a
314
+ // value equal to the catalog's removes the override so a catalog update
315
+ // flows through.
316
+ const doc = readSettings(ctx.userData)
317
+ const previous = doc.connectors[id] && typeof doc.connectors[id] === 'object' ? doc.connectors[id] : {}
318
+ const record = { ...previous, enabled: true }
319
+
320
+ if (f.command !== undefined) {
321
+ if (!singleLine(f.command)) return { ok: false, error: 'The command must be a single line.' }
322
+ const command = f.command.trim()
323
+ if (command === '' || command === entry.auth.command) delete record.command
324
+ else record.command = command
325
+ }
326
+ if (f.args !== undefined) {
327
+ const args = cleanArgs(f.args)
328
+ if (!args) return { ok: false, error: 'Arguments must be a list of single-line strings.' }
329
+ if (JSON.stringify(args) === JSON.stringify(entry.auth.args)) delete record.args
330
+ else record.args = args
331
+ }
332
+ if (f.settings !== undefined) {
333
+ if (!f.settings || typeof f.settings !== 'object') return { ok: false, error: 'Settings must be an object.' }
334
+ record.settings = cleanSettings(entry, f.settings)
335
+ }
336
+
337
+ doc.connectors[id] = record
338
+ try {
339
+ writeSettings(ctx.userData, doc)
340
+ } catch (err) {
341
+ return { ok: false, error: `The settings could not be saved (${err.code ?? 'unknown error'}).` }
342
+ }
343
+ return { ok: true, status: statusOf(ctx, entry) }
344
+ }
345
+
346
+ /**
347
+ * apiKey: forgets the stored key and stops using an inherited one, so one
348
+ * button ends every way the service could be reached. mcp: turns the server
349
+ * off, overrides kept.
350
+ */
351
+ function disconnect(ctx, id) {
352
+ const entry = entryFor(id)
353
+ if (!entry) return { ok: false, error: 'Unknown connector.' }
354
+
355
+ if (entry.auth.type === 'apiKey') {
356
+ try {
357
+ ctx.secrets.clearSecret(id)
358
+ } catch (err) {
359
+ return { ok: false, error: `The key could not be removed (${err.code ?? 'unknown error'}).` }
360
+ }
361
+ const keyDoc = readSettings(ctx.userData)
362
+ if (keyDoc.connectors[id]?.enabled === true) {
363
+ keyDoc.connectors[id] = { ...keyDoc.connectors[id], enabled: false }
364
+ try {
365
+ writeSettings(ctx.userData, keyDoc)
366
+ } catch (err) {
367
+ return { ok: false, error: `The key was removed, but the setting could not be saved (${err.code ?? 'unknown error'}).` }
368
+ }
369
+ }
370
+ return { ok: true, status: statusOf(ctx, entry) }
371
+ }
372
+
373
+ const doc = readSettings(ctx.userData)
374
+ const previous = doc.connectors[id]
375
+ if (previous && typeof previous === 'object' && previous.enabled === true) {
376
+ doc.connectors[id] = { ...previous, enabled: false }
377
+ try {
378
+ writeSettings(ctx.userData, doc)
379
+ } catch (err) {
380
+ return { ok: false, error: `The settings could not be saved (${err.code ?? 'unknown error'}).` }
381
+ }
382
+ }
383
+ return { ok: true, status: statusOf(ctx, entry) }
384
+ }
385
+
386
+ // ---------------------------------------------------------------- test
387
+
388
+ const DEFAULT_REJECT = [401, 403]
389
+
390
+ /**
391
+ * 2xx and 429 mean the key was recognised; 401 and 403 mean it was not. Not
392
+ * every vendor answers a bad key with either: Gemini returns 400
393
+ * INVALID_ARGUMENT, so an entry may name the codes that mean rejection for it.
394
+ */
395
+ function interpretResponse(status, rejectStatuses) {
396
+ if ((status >= 200 && status < 300) || status === 429) return 'ok'
397
+ const rejects = Array.isArray(rejectStatuses) && rejectStatuses.length > 0 ? rejectStatuses : DEFAULT_REJECT
398
+ if (rejects.includes(status)) return 'rejected'
399
+ return 'error'
400
+ }
401
+
402
+ // A Finder-launched app gets the login shell's minimal PATH, without the
403
+ // directories the usual installers use. Searched after PATH itself.
404
+ function extraBinDirs(env) {
405
+ const home = env?.HOME ?? os.homedir()
406
+ return [
407
+ path.join(home, '.local', 'bin'),
408
+ '/opt/homebrew/bin',
409
+ '/usr/local/bin',
410
+ path.join(home, '.cargo', 'bin'),
411
+ path.join(home, '.bun', 'bin'),
412
+ ]
413
+ }
414
+
415
+ // An MCP stdio server is spawned with the env we hand it and nothing else, so
416
+ // the few variables a command line tool cannot run without have to be carried
417
+ // over by name. uvx in particular writes its cache under HOME.
418
+ const INHERITED_ENV = ['HOME', 'USER', 'LOGNAME', 'SHELL', 'TMPDIR', 'LANG', 'LC_ALL', 'SYSTEMROOT', 'APPDATA']
419
+
420
+ function baseServerEnv(env) {
421
+ const out = { PATH: searchPath(env) }
422
+ for (const name of INHERITED_ENV) {
423
+ const value = env?.[name]
424
+ if (typeof value === 'string' && value !== '') out[name] = value
425
+ }
426
+ return out
427
+ }
428
+
429
+ /** PATH plus the extra directories, deduplicated, for a spawned server. */
430
+ function searchPath(env) {
431
+ const seen = new Set()
432
+ const out = []
433
+ for (const dir of [...(env?.PATH ?? '').split(path.delimiter), ...extraBinDirs(env)]) {
434
+ if (dir === '' || seen.has(dir)) continue
435
+ seen.add(dir)
436
+ out.push(dir)
437
+ }
438
+ return out.join(path.delimiter)
439
+ }
440
+
441
+ function isExecutable(candidate) {
442
+ try {
443
+ fs.accessSync(candidate, fs.constants.X_OK)
444
+ return fs.statSync(candidate).isFile()
445
+ } catch {
446
+ return false
447
+ }
448
+ }
449
+
450
+ /** Absolute path of `command`, or null when nothing on the search path runs it. */
451
+ function resolveCommand(command, env) {
452
+ if (typeof command !== 'string' || command.trim() === '') return null
453
+ const extensions = process.platform === 'win32' ? ['', ...(env?.PATHEXT ?? '.EXE;.CMD;.BAT').split(';')] : ['']
454
+ if (command.includes('/') || command.includes('\\')) {
455
+ const abs = path.resolve(command)
456
+ for (const ext of extensions) if (isExecutable(abs + ext)) return abs + ext
457
+ return null
458
+ }
459
+ for (const dir of searchPath(env).split(path.delimiter)) {
460
+ for (const ext of extensions) {
461
+ const candidate = path.join(dir, command + ext)
462
+ if (isExecutable(candidate)) return candidate
463
+ }
464
+ }
465
+ return null
466
+ }
467
+
468
+ function probeTcp(host, port, timeoutMs) {
469
+ return new Promise((resolve) => {
470
+ let settled = false
471
+ const socket = net.connect({ host, port })
472
+ const done = (ok) => {
473
+ if (settled) return
474
+ settled = true
475
+ socket.destroy()
476
+ resolve(ok)
477
+ }
478
+ socket.setTimeout(timeoutMs, () => done(false))
479
+ socket.once('connect', () => done(true))
480
+ socket.once('error', () => done(false))
481
+ })
482
+ }
483
+
484
+ function installHint(command) {
485
+ const name = path.basename(command)
486
+ if (name === 'uvx' || name === 'uv') return 'Install uv and reopen the studio.'
487
+ if (name === 'npx' || name === 'node') return 'Install Node.js and reopen the studio.'
488
+ return 'Install it and reopen the studio.'
489
+ }
490
+
491
+ async function testApiKey(ctx, entry) {
492
+ const key = ctx.secrets.getSecret(entry.id) ?? envValue(ctx.env, entry.auth.envVar)
493
+ if (!key) return { status: 'untested', detail: 'No key to test.' }
494
+ const endpoint = entry.testEndpoint
495
+ if (!endpoint) return { status: 'untested', detail: 'Saved. This service has no test endpoint.' }
496
+
497
+ let response
498
+ try {
499
+ response = await fetch(endpoint.url, {
500
+ method: endpoint.method,
501
+ headers: { ...(endpoint.headers ?? {}), [entry.auth.header.name]: entry.auth.header.prefix + key },
502
+ body: endpoint.method === 'POST' ? endpoint.body : undefined,
503
+ // A redirect would carry the key header to whatever host the vendor
504
+ // points at; a 3xx is reported as an unexpected reply instead.
505
+ redirect: 'manual',
506
+ signal: AbortSignal.timeout(8000),
507
+ })
508
+ } catch {
509
+ return { status: 'offline', detail: 'Saved, not tested: the service could not be reached.' }
510
+ }
511
+ // The body is never read; releasing it frees the connection.
512
+ response.body?.cancel().catch(() => {})
513
+
514
+ const verdict = interpretResponse(response.status, endpoint.rejectStatuses)
515
+ if (verdict === 'ok') return { status: 'ok', detail: `Key accepted (HTTP ${response.status}).` }
516
+ if (verdict === 'rejected') {
517
+ return { status: 'rejected', detail: `The key was rejected (HTTP ${response.status}). Check it and save again.` }
518
+ }
519
+ return { status: 'error', detail: `Reachable, unexpected reply (HTTP ${response.status}).` }
520
+ }
521
+
522
+ async function testMcp(ctx, entry) {
523
+ const status = statusOf(ctx, entry)
524
+ const resolved = resolveCommand(status.command, ctx.env)
525
+ const name = path.basename(status.command)
526
+ if (!resolved) {
527
+ return { status: 'error', detail: `${name} was not found on this machine. ${installHint(status.command)}` }
528
+ }
529
+
530
+ // blender-mcp is only half of the bridge: the server talks to the addon over
531
+ // a TCP socket, so the probe tells the creator which half is missing.
532
+ if (entry.id === 'blender') {
533
+ const host = status.settings.BLENDER_HOST ?? 'localhost'
534
+ const port = Number.parseInt(status.settings.BLENDER_PORT ?? '9876', 10)
535
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
536
+ return { status: 'error', detail: 'Blender port must be a number between 1 and 65535.' }
537
+ }
538
+ const listening = await probeTcp(host, port, 1500)
539
+ if (listening) return { status: 'ok', detail: `${name} found; Blender is listening on ${port}.` }
540
+ return {
541
+ status: 'error',
542
+ detail: `${name} found, but Blender is not listening on ${port}. Start the addon from the Blender sidebar.`,
543
+ }
544
+ }
545
+
546
+ return { status: 'ok', detail: `Command found: ${resolved}` }
547
+ }
548
+
549
+ async function test(ctx, id) {
550
+ const entry = entryFor(id)
551
+ if (!entry) return { status: 'error', detail: 'Unknown connector.' }
552
+ return entry.auth.type === 'apiKey' ? testApiKey(ctx, entry) : testMcp(ctx, entry)
553
+ }
554
+
555
+ // ---------------------------------------------------------------- agent
556
+
557
+ const POLY_HAVEN =
558
+ 'Poly Haven: free CC0 HDRIs, textures and models at https://api.polyhaven.com, no key needed.'
559
+
560
+ // The paid services the agent may offer to use before they are connected: it
561
+ // asks with a key card in the chat (agent/cards.cjs) when one is needed, so
562
+ // nothing has to be set up on a settings screen first. Generation and asset
563
+ // services, plus the two model vendors whose APIs also make images.
564
+ const OFFERED_CATEGORIES = new Set(['3d', 'world', 'image', 'audio', 'assets'])
565
+ const OFFERED_EXTRA = new Set(['openai', 'gemini'])
566
+
567
+ const offered = (entry) =>
568
+ entry.auth.type === 'apiKey' && entry.id !== AGENT_ID && (OFFERED_CATEGORIES.has(entry.category) || OFFERED_EXTRA.has(entry.id))
569
+
570
+ /**
571
+ * What the agent host gets with each prompt: environment for stored keys,
572
+ * MCP server configs, one plain line per service for the system prompt, the
573
+ * inherited keys to strip from the child's environment, and the services it
574
+ * could ask the creator to connect (`available`, names only, never a secret).
575
+ * The agent's own key is not a service; main hands it over separately.
576
+ */
577
+ function resolveForAgent(ctx) {
578
+ const settingsDoc = readSettings(ctx.userData)
579
+ const env = {}
580
+ const envRemove = []
581
+ const mcpServers = {}
582
+ const services = []
583
+ const available = []
584
+ let wantsPolyHaven = false
585
+
586
+ // A stored key is an explicit choice; an inherited one counts only once the
587
+ // creator has switched it on in Settings. Only stored keys need exporting,
588
+ // since the agent host starts from the studio's own environment.
589
+ const keyFor = (entry) => {
590
+ const stored = ctx.secrets.getSecret(entry.id)
591
+ if (stored) return stored
592
+ const inherited = envValue(ctx.env, entry.auth.envVar)
593
+ return inherited && envAllowed(entry, settingsDoc) ? inherited : null
594
+ }
595
+
596
+ for (const entry of CATALOG) {
597
+ // Claude runs the agent rather than being something the agent calls, so its
598
+ // key is handled by the credentials store and never announced as a service.
599
+ // The other models under the same category are ordinary callable APIs.
600
+ if (entry.id === AGENT_ID) continue
601
+
602
+ if (entry.auth.type === 'apiKey') {
603
+ const stored = ctx.secrets.getSecret(entry.id)
604
+ const usable = stored ?? keyFor(entry)
605
+ if (!usable) {
606
+ // The variable is in this shell for other work. It is not announced,
607
+ // and it does not travel to the agent either.
608
+ if (envValue(ctx.env, entry.auth.envVar)) envRemove.push(entry.auth.envVar)
609
+ if (offered(entry)) {
610
+ available.push({ id: entry.id, name: entry.name, category: entry.category, blurb: entry.blurb, envVar: entry.auth.envVar })
611
+ }
612
+ continue
613
+ }
614
+ if (stored) env[entry.auth.envVar] = stored
615
+ const { header } = entry.auth
616
+ services.push(
617
+ `${entry.name}: ${entry.blurb} Key in ${entry.auth.envVar} (header ${header.name}: ${header.prefix}<key>). Docs ${entry.auth.docsUrl}`,
618
+ )
619
+ if (entry.category === '3d' || entry.category === 'assets') wantsPolyHaven = true
620
+ continue
621
+ }
622
+
623
+ if (settingsDoc.connectors[entry.id]?.enabled !== true) continue
624
+ const status = statusFor(entry, { stored: null, env: ctx.env, settingsDoc })
625
+ // The server inherits an augmented PATH: `npx` has to find `node`, and a
626
+ // Finder-launched app does not have ~/.local/bin on its own PATH.
627
+ const serverEnv = { ...baseServerEnv(ctx.env), ...status.settings }
628
+ for (const [name, sourceId] of Object.entries(entry.auth.secretEnv ?? {})) {
629
+ const source = entryFor(sourceId)
630
+ const value = source && source.auth.type === 'apiKey' ? keyFor(source) : null
631
+ if (value) serverEnv[name] = value
632
+ }
633
+ mcpServers[entry.id] = {
634
+ type: 'stdio',
635
+ // The bare command when unresolved, so the CLI's own error surfaces.
636
+ command: resolveCommand(status.command, ctx.env) ?? status.command,
637
+ args: status.args,
638
+ env: serverEnv,
639
+ }
640
+ const requires = entry.auth.requires ? ` Requires ${entry.auth.requires}` : ''
641
+ services.push(`${entry.name}: ${entry.blurb} MCP tools mcp__${entry.id}__*.${requires}`)
642
+ wantsPolyHaven = true
643
+ }
644
+
645
+ if (wantsPolyHaven) services.push(POLY_HAVEN)
646
+ return { env, envRemove, mcpServers, services, available }
647
+ }
648
+
649
+ /**
650
+ * What a key card shows and needs about one service, or null for anything
651
+ * that is not an API-key service. The agent's own key is left out: it runs
652
+ * the request already, and a key typed into a card mid-run would replace it.
653
+ * hasKey is true when a key is usable now (stored, or inherited and switched on).
654
+ */
655
+ function connectorInfo(ctx, id) {
656
+ const entry = entryFor(id)
657
+ if (!entry || entry.auth.type !== 'apiKey' || entry.id === AGENT_ID) return null
658
+ return {
659
+ id: entry.id,
660
+ name: entry.name,
661
+ category: entry.category,
662
+ keyUrl: entry.auth.keyUrl,
663
+ docsUrl: entry.auth.docsUrl,
664
+ envVar: entry.auth.envVar,
665
+ hasKey: statusOf(ctx, entry).status === 'connected',
666
+ }
667
+ }
668
+
669
+ module.exports = {
670
+ loadCatalog,
671
+ catalogProblem,
672
+ isKnownId,
673
+ entryFor,
674
+ allowedExternal,
675
+ keyProblem,
676
+ readSettings,
677
+ writeSettings,
678
+ statusFor,
679
+ listStatuses,
680
+ connect,
681
+ disconnect,
682
+ test,
683
+ interpretResponse,
684
+ resolveCommand,
685
+ searchPath,
686
+ resolveForAgent,
687
+ connectorInfo,
688
+ }