somora 2026.930.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 (404) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +364 -0
  3. package/bin/node-version.d.mts +3 -0
  4. package/bin/node-version.mjs +45 -0
  5. package/bin/somora.mjs +77 -0
  6. package/config.example.yaml +896 -0
  7. package/docs/agents.md +677 -0
  8. package/docs/api.md +3194 -0
  9. package/docs/browser.md +317 -0
  10. package/docs/builder.md +331 -0
  11. package/docs/cache-strategy.md +373 -0
  12. package/docs/compaction.md +253 -0
  13. package/docs/display.md +154 -0
  14. package/docs/dream-phases.md +891 -0
  15. package/docs/files.md +387 -0
  16. package/docs/imagegen.md +366 -0
  17. package/docs/images/somora-hero.png +0 -0
  18. package/docs/images/somora-mobile-2026-05-23.png +0 -0
  19. package/docs/images/somora-tui-2026-05-23.png +0 -0
  20. package/docs/images/somora-web-2026-05-23.png +0 -0
  21. package/docs/index.md +178 -0
  22. package/docs/lsp.md +93 -0
  23. package/docs/mcp.md +332 -0
  24. package/docs/memory.md +407 -0
  25. package/docs/mobile.md +310 -0
  26. package/docs/models.md +379 -0
  27. package/docs/projects.md +425 -0
  28. package/docs/realtime-voice.md +293 -0
  29. package/docs/resources.md +230 -0
  30. package/docs/sampling.md +128 -0
  31. package/docs/security.md +189 -0
  32. package/docs/sentinel.md +295 -0
  33. package/docs/setup.md +1217 -0
  34. package/docs/skills.md +501 -0
  35. package/docs/team.md +189 -0
  36. package/docs/thinking.md +463 -0
  37. package/docs/tmux.md +399 -0
  38. package/docs/tools.md +117 -0
  39. package/docs/videogen.md +191 -0
  40. package/docs/voice.md +288 -0
  41. package/docs/web.md +893 -0
  42. package/docs/wiki.md +583 -0
  43. package/npm-shrinkwrap.json +5670 -0
  44. package/package.json +116 -0
  45. package/src/attachments/store.ts +196 -0
  46. package/src/browser/change-stream.ts +31 -0
  47. package/src/browser/display.ts +108 -0
  48. package/src/browser/policy.ts +121 -0
  49. package/src/browser/screencast.ts +374 -0
  50. package/src/browser/service.ts +1337 -0
  51. package/src/browser/session.ts +15 -0
  52. package/src/browser/snapshot.ts +40 -0
  53. package/src/cli/auth.ts +117 -0
  54. package/src/cli/codex.ts +41 -0
  55. package/src/cli/lsp.ts +71 -0
  56. package/src/cli/resolvers/clawhub.ts +400 -0
  57. package/src/cli/setup.ts +835 -0
  58. package/src/cli/skill.ts +619 -0
  59. package/src/cli/somora.ts +548 -0
  60. package/src/cli/systemd-unit.ts +72 -0
  61. package/src/cli/team.ts +148 -0
  62. package/src/cli/tui/activity-stream.ts +121 -0
  63. package/src/cli/tui/api.ts +479 -0
  64. package/src/cli/tui/app.tsx +1169 -0
  65. package/src/cli/tui/autocomplete.tsx +55 -0
  66. package/src/cli/tui/commands.ts +913 -0
  67. package/src/cli/tui/dream-glyphs.ts +22 -0
  68. package/src/cli/tui/footer.tsx +15 -0
  69. package/src/cli/tui/format.ts +28 -0
  70. package/src/cli/tui/header.tsx +279 -0
  71. package/src/cli/tui/index.tsx +120 -0
  72. package/src/cli/tui/markdown.tsx +63 -0
  73. package/src/cli/tui/sampling.ts +162 -0
  74. package/src/cli/tui/separator.tsx +13 -0
  75. package/src/cli/tui/state.ts +42 -0
  76. package/src/cli/tui/stream.ts +330 -0
  77. package/src/cli/tui/thinking-text.ts +54 -0
  78. package/src/cli/tui/turn-views.tsx +499 -0
  79. package/src/cli/tui/types.ts +410 -0
  80. package/src/cli/tui/work-queue.ts +161 -0
  81. package/src/cli/update-args.ts +55 -0
  82. package/src/cli/wiki.ts +406 -0
  83. package/src/compaction/index.ts +28 -0
  84. package/src/compaction/midturn.ts +210 -0
  85. package/src/compaction/policy.ts +154 -0
  86. package/src/compaction/summarize.ts +691 -0
  87. package/src/compaction/template.ts +90 -0
  88. package/src/compaction/types.ts +148 -0
  89. package/src/config/loader.ts +276 -0
  90. package/src/config/reload.ts +43 -0
  91. package/src/config/types.ts +2292 -0
  92. package/src/dream/deep-actions.ts +324 -0
  93. package/src/dream/deep-dispatcher.ts +237 -0
  94. package/src/dream/deep-llm.ts +388 -0
  95. package/src/dream/deep-prompts.ts +106 -0
  96. package/src/dream/deep-runner.ts +757 -0
  97. package/src/dream/deep-skip-cache.ts +199 -0
  98. package/src/dream/deep-worker.ts +229 -0
  99. package/src/dream/json-salvage.ts +34 -0
  100. package/src/dream/judge.ts +188 -0
  101. package/src/dream/loop-state.ts +286 -0
  102. package/src/dream/lucid-actions.ts +303 -0
  103. package/src/dream/lucid-batches.ts +94 -0
  104. package/src/dream/lucid-prompt.ts +82 -0
  105. package/src/dream/lucid-runner.ts +744 -0
  106. package/src/dream/lucid-storage.ts +277 -0
  107. package/src/dream/lucid-structure.ts +102 -0
  108. package/src/dream/lucid-types.ts +137 -0
  109. package/src/dream/lucid-worker.ts +224 -0
  110. package/src/dream/rem-dedup.ts +502 -0
  111. package/src/dream/rem-extract.ts +782 -0
  112. package/src/dream/rem-reset-run.ts +67 -0
  113. package/src/dream/rem-runner.ts +696 -0
  114. package/src/dream/rem-worker.ts +527 -0
  115. package/src/dream/review-window.ts +71 -0
  116. package/src/dream/scheduler-state.ts +129 -0
  117. package/src/dream/storage.ts +497 -0
  118. package/src/dream/types.ts +133 -0
  119. package/src/dream/wiki-context.ts +133 -0
  120. package/src/engine/a2a.ts +33 -0
  121. package/src/engine/availability.ts +63 -0
  122. package/src/engine/claude-cli.ts +969 -0
  123. package/src/engine/codex-app-server-client.ts +294 -0
  124. package/src/engine/codex-bin.ts +49 -0
  125. package/src/engine/codex-cli.ts +1014 -0
  126. package/src/engine/codex-dynamic-tools.ts +239 -0
  127. package/src/engine/codex-home.ts +63 -0
  128. package/src/engine/codex-thread-config.ts +74 -0
  129. package/src/engine/context-budget.ts +257 -0
  130. package/src/engine/engine-meta-labels.ts +211 -0
  131. package/src/engine/grok-cli.ts +941 -0
  132. package/src/engine/inline-think.ts +59 -0
  133. package/src/engine/model-availability.ts +105 -0
  134. package/src/engine/openai-compatible.ts +2464 -0
  135. package/src/engine/reasoning-retry.ts +83 -0
  136. package/src/engine/registry.ts +13 -0
  137. package/src/engine/replay.ts +195 -0
  138. package/src/engine/sampling.ts +90 -0
  139. package/src/engine/thinking-params.ts +264 -0
  140. package/src/engine/types.ts +269 -0
  141. package/src/engine/user-tag.ts +24 -0
  142. package/src/imagegen/aspect.ts +128 -0
  143. package/src/imagegen/generate.ts +642 -0
  144. package/src/imagegen/references.ts +75 -0
  145. package/src/imagegen/types.ts +154 -0
  146. package/src/lsp/client.ts +183 -0
  147. package/src/lsp/fake-server.helper.mjs +42 -0
  148. package/src/lsp/format.ts +29 -0
  149. package/src/lsp/index.ts +21 -0
  150. package/src/lsp/manager.ts +238 -0
  151. package/src/lsp/registry.ts +151 -0
  152. package/src/mcp/config.ts +117 -0
  153. package/src/mcp/hub/audit.ts +55 -0
  154. package/src/mcp/hub/bridge.ts +115 -0
  155. package/src/mcp/hub/catalog.ts +69 -0
  156. package/src/mcp/hub/credentials.ts +406 -0
  157. package/src/mcp/hub/env-expand.ts +14 -0
  158. package/src/mcp/hub/manager.ts +770 -0
  159. package/src/mcp/hub/normalize.ts +213 -0
  160. package/src/mcp/server.ts +368 -0
  161. package/src/mcp/tool-schema.ts +20 -0
  162. package/src/media/capabilities.ts +392 -0
  163. package/src/media/records.ts +175 -0
  164. package/src/media/store.ts +217 -0
  165. package/src/media/types.ts +69 -0
  166. package/src/memory/chunking.ts +168 -0
  167. package/src/memory/embeddings.ts +262 -0
  168. package/src/memory/index.ts +15 -0
  169. package/src/memory/inject.ts +197 -0
  170. package/src/memory/manager.ts +996 -0
  171. package/src/memory/registry.ts +176 -0
  172. package/src/memory/rescan.ts +101 -0
  173. package/src/memory/retrieval.ts +586 -0
  174. package/src/memory/shared-index.ts +372 -0
  175. package/src/memory/slug.ts +39 -0
  176. package/src/memory/storage.ts +385 -0
  177. package/src/memory/watcher.ts +134 -0
  178. package/src/multimodal/blocks.ts +101 -0
  179. package/src/multimodal/dimensions.ts +214 -0
  180. package/src/multimodal/load.ts +86 -0
  181. package/src/multimodal/mime.ts +135 -0
  182. package/src/multimodal/pdf-render.ts +80 -0
  183. package/src/multimodal/user-content.ts +266 -0
  184. package/src/persona/files.ts +144 -0
  185. package/src/persona/loader.ts +598 -0
  186. package/src/persona/skill-gating-store.ts +59 -0
  187. package/src/persona/tool-gating-store.ts +113 -0
  188. package/src/projects/focus.ts +186 -0
  189. package/src/projects/prompt-block.ts +106 -0
  190. package/src/projects/scheme.ts +107 -0
  191. package/src/projects/store.ts +144 -0
  192. package/src/projects/types.ts +73 -0
  193. package/src/sentinel/dispatcher.ts +97 -0
  194. package/src/sentinel/schedule.ts +271 -0
  195. package/src/sentinel/scheduler.ts +840 -0
  196. package/src/sentinel/store.ts +259 -0
  197. package/src/sentinel/types.ts +221 -0
  198. package/src/server/activity-stream.ts +160 -0
  199. package/src/server/ask-calls.ts +137 -0
  200. package/src/server/ask-wait-graph.ts +171 -0
  201. package/src/server/async-tasks.ts +199 -0
  202. package/src/server/builder-busy.ts +86 -0
  203. package/src/server/builder-prompt.ts +204 -0
  204. package/src/server/builder-questions.ts +117 -0
  205. package/src/server/builder-session.ts +249 -0
  206. package/src/server/chat-aborts.ts +83 -0
  207. package/src/server/claude-config-dir.ts +71 -0
  208. package/src/server/claude-credential-sync.ts +454 -0
  209. package/src/server/env-file.ts +100 -0
  210. package/src/server/env.ts +115 -0
  211. package/src/server/heal-session.ts +151 -0
  212. package/src/server/history-page.ts +46 -0
  213. package/src/server/index.ts +7244 -0
  214. package/src/server/lockfile.ts +89 -0
  215. package/src/server/logger.ts +67 -0
  216. package/src/server/logs.ts +187 -0
  217. package/src/server/loopback-fetch.ts +130 -0
  218. package/src/server/openai-client.ts +89 -0
  219. package/src/server/prompt-assembly.ts +334 -0
  220. package/src/server/restart-reconcile.ts +139 -0
  221. package/src/server/run-turn-fallback.ts +275 -0
  222. package/src/server/run-turn-types.ts +91 -0
  223. package/src/server/run-turn.ts +1474 -0
  224. package/src/server/sanitize-assistant-text.ts +112 -0
  225. package/src/server/session-export.ts +220 -0
  226. package/src/server/session-queue.ts +376 -0
  227. package/src/server/session-workdir.ts +49 -0
  228. package/src/server/sse-h2-safe.ts +61 -0
  229. package/src/server/sse-liveness.ts +162 -0
  230. package/src/server/sse-serializer.ts +161 -0
  231. package/src/server/start-turn.ts +249 -0
  232. package/src/server/steer-inbox.ts +107 -0
  233. package/src/server/tls-keeper.ts +153 -0
  234. package/src/server/tool-format.ts +167 -0
  235. package/src/server/turn-framing.ts +52 -0
  236. package/src/server/turn-origin-kind.ts +74 -0
  237. package/src/server/turn-origin.ts +40 -0
  238. package/src/server/work-ledger.ts +975 -0
  239. package/src/server/workspace.ts +114 -0
  240. package/src/setup/config-edit.ts +201 -0
  241. package/src/setup/presets.ts +71 -0
  242. package/src/setup/prompt.ts +163 -0
  243. package/src/setup/tailscale.ts +44 -0
  244. package/src/skills/bin-checks.ts +227 -0
  245. package/src/skills/bootstrap.ts +347 -0
  246. package/src/skills/env-scope.ts +175 -0
  247. package/src/skills/gating.ts +71 -0
  248. package/src/skills/lint.ts +202 -0
  249. package/src/skills/load.ts +368 -0
  250. package/src/skills/path-helpers.ts +102 -0
  251. package/src/skills/registry.ts +178 -0
  252. package/src/ssh/exec.ts +142 -0
  253. package/src/ssh/index.ts +12 -0
  254. package/src/ssh/known-hosts.ts +109 -0
  255. package/src/ssh/pool.ts +307 -0
  256. package/src/storage/sessions.ts +602 -0
  257. package/src/team/render.ts +149 -0
  258. package/src/team/resolve.ts +122 -0
  259. package/src/team/store.ts +124 -0
  260. package/src/team/types.ts +111 -0
  261. package/src/team/write.ts +95 -0
  262. package/src/testing/isolated-home.mts +46 -0
  263. package/src/tmux/attention-watcher.ts +272 -0
  264. package/src/tmux/attention.ts +336 -0
  265. package/src/tmux/list.ts +91 -0
  266. package/src/tmux/origin-store.ts +102 -0
  267. package/src/tmux/tui-markers.ts +267 -0
  268. package/src/tools/agents/ask-cancel.ts +94 -0
  269. package/src/tools/agents/ask-result.ts +235 -0
  270. package/src/tools/agents/ask.ts +704 -0
  271. package/src/tools/agents/builder-dispatch.ts +217 -0
  272. package/src/tools/agents/images.ts +104 -0
  273. package/src/tools/agents/index.ts +42 -0
  274. package/src/tools/agents/long-task-timeouts.ts +39 -0
  275. package/src/tools/agents/session-list.ts +136 -0
  276. package/src/tools/agents/session-model.ts +106 -0
  277. package/src/tools/agents/spawn.ts +845 -0
  278. package/src/tools/agents/status.ts +589 -0
  279. package/src/tools/browser/index.ts +6 -0
  280. package/src/tools/browser/ops.ts +145 -0
  281. package/src/tools/browser/tools.ts +184 -0
  282. package/src/tools/builder/short-descriptions.ts +80 -0
  283. package/src/tools/builder/tools.ts +222 -0
  284. package/src/tools/docs/index.ts +1 -0
  285. package/src/tools/docs/tools.ts +228 -0
  286. package/src/tools/dream/index.ts +11 -0
  287. package/src/tools/dream/tools.ts +1002 -0
  288. package/src/tools/exec/allowlist.ts +233 -0
  289. package/src/tools/exec/background-detach.helper.mts +27 -0
  290. package/src/tools/exec/blacklist.ts +336 -0
  291. package/src/tools/exec/concurrency.ts +150 -0
  292. package/src/tools/exec/fit-output.ts +82 -0
  293. package/src/tools/exec/index.ts +7 -0
  294. package/src/tools/exec/internal-env.ts +89 -0
  295. package/src/tools/exec/job-store.ts +403 -0
  296. package/src/tools/exec/local.ts +649 -0
  297. package/src/tools/exec/remote.ts +399 -0
  298. package/src/tools/exec/tools.ts +934 -0
  299. package/src/tools/file/analyze.ts +378 -0
  300. package/src/tools/file/index.ts +2 -0
  301. package/src/tools/file/local.ts +707 -0
  302. package/src/tools/file/lsp-hook.ts +72 -0
  303. package/src/tools/file/persona-guard.ts +61 -0
  304. package/src/tools/file/policy.ts +292 -0
  305. package/src/tools/file/read-format.ts +129 -0
  306. package/src/tools/file/remote.ts +680 -0
  307. package/src/tools/file/replace.ts +507 -0
  308. package/src/tools/file/search-window.ts +224 -0
  309. package/src/tools/file/tools.ts +658 -0
  310. package/src/tools/file/write-scope.ts +182 -0
  311. package/src/tools/gating.ts +106 -0
  312. package/src/tools/image/budget.ts +82 -0
  313. package/src/tools/image/index.ts +7 -0
  314. package/src/tools/image/tools.ts +601 -0
  315. package/src/tools/index.ts +99 -0
  316. package/src/tools/memory/index.ts +12 -0
  317. package/src/tools/memory/tools.ts +399 -0
  318. package/src/tools/projects/index.ts +1 -0
  319. package/src/tools/projects/tools.ts +643 -0
  320. package/src/tools/registry.ts +427 -0
  321. package/src/tools/resources/index.ts +8 -0
  322. package/src/tools/resources/tools.ts +176 -0
  323. package/src/tools/resources/visibility.ts +60 -0
  324. package/src/tools/sentinel/index.ts +1 -0
  325. package/src/tools/sentinel/tools.ts +592 -0
  326. package/src/tools/skill/index.ts +4 -0
  327. package/src/tools/skill/tools.ts +285 -0
  328. package/src/tools/time/index.ts +5 -0
  329. package/src/tools/time/tools.ts +123 -0
  330. package/src/tools/tmux/index.ts +1 -0
  331. package/src/tools/tmux/local.ts +277 -0
  332. package/src/tools/tmux/remote.ts +168 -0
  333. package/src/tools/tmux/tools.ts +1064 -0
  334. package/src/tools/tool-output.ts +97 -0
  335. package/src/tools/types.ts +227 -0
  336. package/src/tools/video/index.ts +1 -0
  337. package/src/tools/video/tools.ts +425 -0
  338. package/src/tools/web/fetch.ts +337 -0
  339. package/src/tools/web/index.ts +4 -0
  340. package/src/tools/web/tools.ts +186 -0
  341. package/src/tools/wiki/index.ts +1 -0
  342. package/src/tools/wiki/tools.ts +445 -0
  343. package/src/tts/cache-gc.ts +128 -0
  344. package/src/tts/prepare-for-tts.ts +114 -0
  345. package/src/tts/service.ts +332 -0
  346. package/src/types/events.ts +695 -0
  347. package/src/types/turn-origin.ts +53 -0
  348. package/src/version.ts +21 -0
  349. package/src/videogen/dialects.ts +222 -0
  350. package/src/videogen/generate.ts +484 -0
  351. package/src/videogen/jobs.ts +178 -0
  352. package/src/videogen/runner.ts +125 -0
  353. package/src/videogen/wake.ts +119 -0
  354. package/src/voice/realtime/call.ts +948 -0
  355. package/src/voice/realtime/consult.ts +293 -0
  356. package/src/voice/realtime/fake-provider.ts +134 -0
  357. package/src/voice/realtime/manager.ts +384 -0
  358. package/src/voice/realtime/openai-provider.ts +471 -0
  359. package/src/voice/realtime/persona.ts +227 -0
  360. package/src/voice/realtime/session-match.ts +116 -0
  361. package/src/voice/realtime/types.ts +182 -0
  362. package/src/wiki/conflict.ts +113 -0
  363. package/src/wiki/explorer.ts +578 -0
  364. package/src/wiki/index-builder.ts +172 -0
  365. package/src/wiki/language.ts +134 -0
  366. package/src/wiki/log-builder.ts +150 -0
  367. package/src/wiki/map.ts +258 -0
  368. package/src/wiki/migration/analyze.ts +304 -0
  369. package/src/wiki/migration/execute.ts +689 -0
  370. package/src/wiki/migration/refine.ts +402 -0
  371. package/src/wiki/migration/store.ts +100 -0
  372. package/src/wiki/move-page.ts +57 -0
  373. package/src/wiki/structure-file.ts +192 -0
  374. package/src/wiki/taxonomy.ts +140 -0
  375. package/src/wiki/templates.ts +163 -0
  376. package/src/wiki/types.ts +133 -0
  377. package/templates/skills/README.md +24 -0
  378. package/templates/skills/_templates/api-wrapper/SKILL.md +26 -0
  379. package/templates/skills/_templates/cli-wrapper/BOOTSTRAP.md +32 -0
  380. package/templates/skills/_templates/cli-wrapper/SKILL.md +24 -0
  381. package/templates/skills/_templates/default/SKILL.md +25 -0
  382. package/templates/skills/builder-handover/SKILL.md +96 -0
  383. package/templates/skills/builder-handover/assets/ORDER.md +12 -0
  384. package/templates/skills/skill-author/SKILL.md +110 -0
  385. package/tsconfig.json +22 -0
  386. package/web/dist/assets/index-BaVv6pB2.js +631 -0
  387. package/web/dist/assets/index-BaVv6pB2.js.map +1 -0
  388. package/web/dist/assets/index-V3FV3Z25.css +32 -0
  389. package/web/dist/favicon.svg +8 -0
  390. package/web/dist/index.html +20 -0
  391. package/web/package.json +36 -0
  392. package/web/tsconfig.json +25 -0
  393. package/web-mobile/dist/apple-touch-icon.png +0 -0
  394. package/web-mobile/dist/assets/index-BqKt7IMx.css +1 -0
  395. package/web-mobile/dist/assets/index-X_vRr6cd.js +88 -0
  396. package/web-mobile/dist/assets/index-X_vRr6cd.js.map +1 -0
  397. package/web-mobile/dist/favicon.svg +8 -0
  398. package/web-mobile/dist/icon-192.png +0 -0
  399. package/web-mobile/dist/icon-512.png +0 -0
  400. package/web-mobile/dist/index.html +27 -0
  401. package/web-mobile/dist/manifest.webmanifest +32 -0
  402. package/web-mobile/dist/service-worker.js +90 -0
  403. package/web-mobile/package.json +28 -0
  404. package/web-mobile/tsconfig.json +25 -0
@@ -0,0 +1,642 @@
1
+ // The single code path both entrances use: the web app's Images window
2
+ // (POST /images/generate) and the agents' `image_generate` tool. Two
3
+ // implementations would drift, and then the UI can do something the
4
+ // agent can't.
5
+ //
6
+ // Wire target is the OpenAI-shaped image endpoint. OpenRouter answers
7
+ // with base64 in `data[].b64_json`; OpenAI direct answers with a URL
8
+ // unless asked otherwise. Both are handled — a URL is fetched and the
9
+ // bytes stored, so the caller always ends up with a local file.
10
+ //
11
+ // The prompt is passed through VERBATIM. Specs travel as sibling fields
12
+ // in the request body, never appended to the prompt text — that's the
13
+ // whole reason this uses the image endpoint instead of chat completions
14
+ // with image modalities.
15
+
16
+ import { Buffer } from 'node:buffer';
17
+ import type { Config, ImageModel, Provider } from '../config/types.ts';
18
+ import { resolveImageModel } from '../config/types.ts';
19
+ import { logger } from '../server/logger.ts';
20
+ import { ratioMismatch, requestedRatio, translateAspectForOpenAiWire } from './aspect.ts';
21
+ import { applyDefaults, resolveCapabilities, validateSpecs } from '../media/capabilities.ts';
22
+ import { linkMedia, storeMedia } from '../media/store.ts';
23
+ import { parseSizeSpec, readDimensions } from '../multimodal/dimensions.ts';
24
+ import { newMediaId, writeRecord } from '../media/records.ts';
25
+ import type { ImageSpecs } from './types.ts';
26
+ import type { MediaRecord } from '../media/types.ts';
27
+
28
+ /** One reference image, as handed to the generator. */
29
+ export interface ReferenceImage {
30
+ bytes: Buffer;
31
+ /** Concrete MIME, sniffed from the bytes by the caller. */
32
+ mime: string;
33
+ /** Filename sent in the multipart part — some backends key format
34
+ * detection off the extension. */
35
+ filename: string;
36
+ }
37
+
38
+ export interface GenerateInput {
39
+ prompt: string;
40
+ /** Config handle. Omitted → first configured model. */
41
+ model?: string;
42
+ specs?: ImageSpecs;
43
+ /** Extra destination for the finished file(s). Hardlinked. */
44
+ saveTo?: string;
45
+ /** Reference images for image-to-image, already read from disk by
46
+ * the caller. Bytes rather than paths: the read policy that decides
47
+ * WHICH files an agent may open belongs in the tool layer, where the
48
+ * agent identity is known — this module only knows how to talk to an
49
+ * endpoint. */
50
+ references?: ReferenceImage[];
51
+ /** Provider-specific fields passed through untouched. */
52
+ extra?: Record<string, unknown>;
53
+ agent?: string;
54
+ session?: string;
55
+ }
56
+
57
+ export interface GenerateOutput {
58
+ images: MediaRecord[];
59
+ /** Sum over the batch, when the upstream reported it. */
60
+ costUsd?: number;
61
+ /**
62
+ * Things the caller should know that did not stop the generation:
63
+ * a parameter the endpoint ignored, a size it substituted. Empty on a
64
+ * clean run. Surfaced rather than logged, because the caller is
65
+ * usually a model and it cannot fix what it is not told.
66
+ */
67
+ warnings?: string[];
68
+ /** Models that were tried and were unavailable, in order, when a
69
+ * `fallback:` chain had to be walked. Absent on a first-try success.
70
+ * Surfaced to the caller because a chain that has quietly settled on
71
+ * its last resort is a cost and quality change nobody would notice
72
+ * otherwise. */
73
+ fellBackFrom?: string[];
74
+ }
75
+
76
+ /** Thrown for anything the caller can fix by changing its input. The
77
+ * tool layer relays `message` to the model verbatim; it is written to
78
+ * be actionable. */
79
+ export class ImageGenError extends Error {
80
+ constructor(
81
+ message: string,
82
+ /**
83
+ * `unavailable` is deliberately separate from `upstream`: an image
84
+ * backend commonly shares a GPU box that runs one profile at a
85
+ * time and answers 503 when its own isn't active. That is a
86
+ * temporary state of the world, not a broken endpoint and not the
87
+ * caller's mistake — it deserves a message that says "come back
88
+ * later", and an HTTP status that says the same to the web app.
89
+ */
90
+ readonly kind: 'config' | 'input' | 'upstream' | 'unavailable' = 'input',
91
+ ) {
92
+ super(message);
93
+ this.name = 'ImageGenError';
94
+ }
95
+ }
96
+
97
+ function ensureEnabled(config: Config): void {
98
+ if (!config.imageGen?.enabled) {
99
+ throw new ImageGenError(
100
+ 'Image generation is not enabled. Set imageGen.enabled: true in config.yaml and configure at least one model.',
101
+ 'config',
102
+ );
103
+ }
104
+ }
105
+
106
+ function resolveOrThrow(
107
+ config: Config,
108
+ name?: string,
109
+ ): { entry: ImageModel; provider: Provider; providerName: string } {
110
+ const resolved = resolveImageModel(config, name);
111
+ if (resolved) return resolved;
112
+
113
+ const configured = (config.imageGen?.models ?? []).map((m) => m.name);
114
+ if (name && configured.length > 0) {
115
+ throw new ImageGenError(
116
+ `Unknown image model '${name}'. Configured: ${configured.join(', ')}`,
117
+ 'input',
118
+ );
119
+ }
120
+ if (configured.length === 0) {
121
+ throw new ImageGenError('No image models configured under imageGen.models.', 'config');
122
+ }
123
+ // Handle resolved but its provider entry is missing.
124
+ const entry = config.imageGen?.models.find((m) => m.name === (name ?? configured[0]));
125
+ throw new ImageGenError(
126
+ `Image model '${entry?.name}' points at provider '${entry?.provider}', which is not defined under providers.`,
127
+ 'config',
128
+ );
129
+ }
130
+
131
+ /** Strip a `data:image/png;base64,` prefix if present — callers hand us
132
+ * either form and both are common. */
133
+ function bareBase64(v: string): string {
134
+ const comma = v.indexOf(',');
135
+ return v.startsWith('data:') && comma > 0 ? v.slice(comma + 1) : v;
136
+ }
137
+
138
+ interface UpstreamImage {
139
+ bytes: Buffer;
140
+ mime?: string;
141
+ }
142
+
143
+ interface RawImageRow {
144
+ b64_json?: string;
145
+ /** Some routers return the field explicitly nulled (LiteLLM does this
146
+ * when it has already inlined the bytes as b64_json). Typed as
147
+ * nullable so that shape is handled rather than tripped over. */
148
+ url?: string | null;
149
+ image_url?: { url?: string | null };
150
+ media_type?: string;
151
+ mime_type?: string;
152
+ }
153
+
154
+ /**
155
+ * Turn one response row into bytes, following a URL if that's what we
156
+ * got. Providers differ here and the difference is not worth exposing
157
+ * to callers — every path ends in a local file either way.
158
+ *
159
+ * Three shapes are in the wild and all three occur against endpoints we
160
+ * target:
161
+ * - `b64_json` — what a public endpoint hands out when it does not
162
+ * want to serve files itself. Nothing to fetch.
163
+ * - an absolute URL — OpenAI direct does this, on a different host
164
+ * with the credentials baked into the link.
165
+ * - a RELATIVE path — an image server addressed directly tends to
166
+ * answer with a path into its own output tree ("/output/x.png"),
167
+ * because from its point of view the client already knows the host.
168
+ *
169
+ * The relative case is why `baseUrl` is a parameter: without it such a
170
+ * row is undecodable and the whole generation is thrown away after it
171
+ * was already paid for.
172
+ */
173
+ async function rowToBytes(
174
+ row: RawImageRow,
175
+ timeoutMs: number,
176
+ baseUrl: string,
177
+ apiKey?: string,
178
+ ): Promise<UpstreamImage | null> {
179
+ const mime = row.media_type ?? row.mime_type;
180
+ if (typeof row.b64_json === 'string' && row.b64_json.length > 0) {
181
+ return { bytes: Buffer.from(bareBase64(row.b64_json), 'base64'), mime };
182
+ }
183
+ const url = row.url ?? row.image_url?.url;
184
+ if (typeof url !== 'string' || url.length === 0) return null;
185
+ if (url.startsWith('data:')) {
186
+ return { bytes: Buffer.from(bareBase64(url), 'base64'), mime };
187
+ }
188
+
189
+ // Absolute stays absolute; anything else is resolved against the
190
+ // endpoint we just talked to.
191
+ let resolved: URL;
192
+ try {
193
+ resolved = new URL(url, baseUrl.endsWith('/') ? baseUrl : `${baseUrl}/`);
194
+ } catch {
195
+ return null;
196
+ }
197
+ if (resolved.protocol !== 'http:' && resolved.protocol !== 'https:') return null;
198
+
199
+ // The key travels ONLY back to the host we already authenticated
200
+ // against. A provider that answers with a pre-signed link on someone
201
+ // else's host does not need it, and sending it there would hand our
202
+ // credential to a third party.
203
+ const headers: Record<string, string> = {};
204
+ if (apiKey && resolved.origin === new URL(baseUrl).origin) {
205
+ headers.authorization = `Bearer ${apiKey}`;
206
+ }
207
+
208
+ const res = await fetch(resolved, { headers, signal: AbortSignal.timeout(timeoutMs) });
209
+ if (!res.ok) {
210
+ // 401/403 on the follow-up fetch has one likely cause, and guessing
211
+ // it here saves an hour of confusion: the key is only sent back to
212
+ // the origin we authenticated against, so a link served from a
213
+ // DIFFERENT internal host arrives unauthenticated.
214
+ const authHint =
215
+ res.status === 401 || res.status === 403
216
+ ? ` The image link is on a different origin than the provider's baseUrl, so no API key was` +
217
+ ` sent with it (by design — a key is never handed to another host). Configure the model's` +
218
+ ` provider baseUrl to match the host that serves the images, or have the endpoint return` +
219
+ ` b64_json instead of a link.`
220
+ : '';
221
+ throw new ImageGenError(
222
+ `Upstream returned an image URL that could not be fetched (${res.status}): ${resolved.href}.${authHint}`,
223
+ 'upstream',
224
+ );
225
+ }
226
+ const buf = Buffer.from(await res.arrayBuffer());
227
+ return { bytes: buf, mime: res.headers.get('content-type') ?? mime };
228
+ }
229
+
230
+ /**
231
+ * Build the ordered list of model handles to try, following each
232
+ * entry's `fallback:`. A cycle in the config (a → b → a) would
233
+ * otherwise spin forever, so a handle already in the chain ends it.
234
+ */
235
+ function fallbackChain(config: Config, first: string): string[] {
236
+ const chain: string[] = [];
237
+ const seen = new Set<string>();
238
+ let name: string | undefined = first;
239
+ while (name && !seen.has(name)) {
240
+ seen.add(name);
241
+ chain.push(name);
242
+ name = config.imageGen?.models.find((m) => m.name === name)?.fallback;
243
+ }
244
+ return chain;
245
+ }
246
+
247
+ /**
248
+ * Generate, walking the `fallback:` chain when a model turns out to be
249
+ * unavailable. Everything except availability is fatal on the first
250
+ * attempt: a bad spec value or an unknown handle is the caller's to
251
+ * fix, and trying the next model would only bury the real message.
252
+ */
253
+ export async function generateImage(
254
+ input: GenerateInput,
255
+ config: Config,
256
+ ): Promise<GenerateOutput> {
257
+ ensureEnabled(config);
258
+ const first = input.model ?? config.imageGen?.models[0]?.name;
259
+ if (!first) {
260
+ throw new ImageGenError('No image models configured under imageGen.models.', 'config');
261
+ }
262
+ const chain = fallbackChain(config, first);
263
+ const fellBackFrom: string[] = [];
264
+
265
+ for (const [i, name] of chain.entries()) {
266
+ const last = i === chain.length - 1;
267
+ try {
268
+ const out = await generateOnce({ ...input, model: name }, config);
269
+ if (fellBackFrom.length > 0) {
270
+ logger.warn({
271
+ msg: 'imagegen.fell_back',
272
+ requested: first,
273
+ used: name,
274
+ skipped: fellBackFrom,
275
+ agent: input.agent,
276
+ });
277
+ return { ...out, fellBackFrom };
278
+ }
279
+ return out;
280
+ } catch (err) {
281
+ const unavailable =
282
+ err instanceof ImageGenError && (err.kind === 'upstream' || err.kind === 'unavailable');
283
+ if (!unavailable || last) throw err;
284
+ fellBackFrom.push(`${name}: ${(err as Error).message}`);
285
+ logger.warn({
286
+ msg: 'imagegen.model_unavailable',
287
+ model: name,
288
+ next: chain[i + 1],
289
+ err: (err as Error).message,
290
+ });
291
+ }
292
+ }
293
+ // Unreachable: the loop either returns or throws on the last entry.
294
+ throw new ImageGenError(`No image model in the chain from '${first}' produced an image.`, 'upstream');
295
+ }
296
+
297
+ async function generateOnce(
298
+ input: GenerateInput,
299
+ config: Config,
300
+ ): Promise<GenerateOutput> {
301
+ ensureEnabled(config);
302
+
303
+ const prompt = input.prompt?.trim();
304
+ if (!prompt) throw new ImageGenError('prompt must not be empty.', 'input');
305
+
306
+ const { entry, provider, providerName } = resolveOrThrow(config, input.model);
307
+ const label = entry.label ?? entry.name;
308
+
309
+ if (provider.engine !== 'openai-compatible') {
310
+ throw new ImageGenError(
311
+ `Image model '${entry.name}' uses provider '${providerName}' with engine '${provider.engine}'; image generation needs an openai-compatible provider.`,
312
+ 'config',
313
+ );
314
+ }
315
+
316
+ const caps = await resolveCapabilities(providerName, provider, entry);
317
+ const specs = applyDefaults(input.specs ?? {}, entry, caps);
318
+ const problems = validateSpecs(specs, caps, label);
319
+
320
+ const references = input.references ?? [];
321
+ if (caps.maxReferences !== undefined && references.length > caps.maxReferences) {
322
+ problems.push(
323
+ caps.maxReferences === 0
324
+ ? `${label} does not work from reference images — drop reference_images, or pick a model that does.`
325
+ : `${references.length} reference images passed, but ${label} accepts at most ${caps.maxReferences}.`,
326
+ );
327
+ }
328
+ if (problems.length > 0) throw new ImageGenError(problems.join('\n'), 'input');
329
+
330
+ // What the caller asked for stays `specs` (validation, warnings, the
331
+ // ratio check on the result); `wireSpecs` is what actually goes out.
332
+ // On the OpenAI wire `aspect_ratio` becomes `size` — the wire has no
333
+ // ratio field and routers drop it on /images/edits (aspect.ts).
334
+ const warnings: string[] = [];
335
+ let wireSpecs: ImageSpecs = specs;
336
+ if (entry.wire === 'openai') {
337
+ const t = translateAspectForOpenAiWire(specs, caps, references.length > 0 ? 'multipart' : 'json');
338
+ wireSpecs = t.specs;
339
+ if (t.translated) {
340
+ logger.info({
341
+ msg: 'imagegen.aspect_ratio_translated',
342
+ model: entry.name,
343
+ from: t.translated.from,
344
+ to: t.translated.to,
345
+ via: t.translated.via,
346
+ exact: t.translated.exact,
347
+ });
348
+ if (!t.translated.exact) {
349
+ warnings.push(
350
+ `${label} takes no aspect_ratio on this wire; ${t.translated.from} was sent as size ${t.translated.to}, ` +
351
+ `the closest shape available — not an exact ${t.translated.from}.`,
352
+ );
353
+ }
354
+ } else if (t.dropped) {
355
+ logger.warn({ msg: 'imagegen.aspect_ratio_dropped', model: entry.name, from: t.dropped.from, reason: t.dropped.reason });
356
+ warnings.push(`aspect_ratio '${t.dropped.from}' could not be expressed for ${label} and was not sent (${t.dropped.reason}).`);
357
+ }
358
+ }
359
+
360
+ const timeoutMs = config.imageGen?.timeoutMs ?? 300_000;
361
+ const base = provider.baseUrl.replace(/\/+$/, '');
362
+ const headers: Record<string, string> = {};
363
+ if (provider.apiKey) headers.authorization = `Bearer ${provider.apiKey}`;
364
+
365
+ // The two dialects differ ONLY once reference images are involved;
366
+ // plain generation is the same JSON POST everywhere. See
367
+ // ImageModelSchema.wire for why this is configured, not sniffed.
368
+ const useMultipart = references.length > 0 && entry.wire === 'openai';
369
+ const url = base + (useMultipart ? entry.editEndpoint : entry.endpoint);
370
+
371
+ let requestBody: BodyInit;
372
+ if (useMultipart) {
373
+ // OpenAI's edit endpoint (and LiteLLM's passthrough to a local
374
+ // backend) takes files, not base64: one `image[]` part per
375
+ // reference. Sending several is the entire point of multi-reference
376
+ // work, so the array form is used even for a single image.
377
+ const form = new FormData();
378
+ form.append('model', entry.model);
379
+ form.append('prompt', prompt);
380
+ for (const [key, value] of Object.entries(wireSpecs)) {
381
+ if (value !== undefined) form.append(key, String(value));
382
+ }
383
+ for (const [key, value] of Object.entries(input.extra ?? {})) {
384
+ if (value !== undefined) {
385
+ form.append(key, typeof value === 'string' ? value : JSON.stringify(value));
386
+ }
387
+ }
388
+ for (const ref of references) {
389
+ form.append('image[]', new Blob([new Uint8Array(ref.bytes)], { type: ref.mime }), ref.filename);
390
+ }
391
+ // No content-type header on purpose — fetch has to set it itself so
392
+ // the multipart boundary matches the body it generates.
393
+ requestBody = form;
394
+ } else {
395
+ headers['content-type'] = 'application/json';
396
+ const body: Record<string, unknown> = {
397
+ ...(input.extra ?? {}),
398
+ model: entry.model,
399
+ prompt,
400
+ };
401
+ for (const [key, value] of Object.entries(wireSpecs)) {
402
+ if (value !== undefined) body[key] = value;
403
+ }
404
+ if (references.length > 0) {
405
+ // OpenRouter's Image API (`POST /api/v1/images`) rejects bare base64
406
+ // strings with a ZodError ("expected object, received string") —
407
+ // verified live 2026-09-01. It wants chat-completions-style objects
408
+ // carrying a data URL. Bound to the openrouter dialect on purpose:
409
+ // a future JSON dialect that wants bare strings must not inherit
410
+ // the object form silently. `wire: openai` never reaches this branch
411
+ // with references (multipart above).
412
+ // https://openrouter.ai/docs/guides/overview/multimodal/image-generation
413
+ body.input_references =
414
+ entry.wire === 'openrouter'
415
+ ? references.map((r) => ({
416
+ type: 'image_url',
417
+ image_url: { url: `data:${r.mime};base64,${r.bytes.toString('base64')}` },
418
+ }))
419
+ : references.map((r) => r.bytes.toString('base64'));
420
+ }
421
+ requestBody = JSON.stringify(body);
422
+ }
423
+
424
+ // The fields as sent (no bytes) — the arbiter when a shape comes back
425
+ // wrong. The 2026-09-06 case took a day to pin on the router because
426
+ // nothing recorded what left somora.
427
+ logger.info({
428
+ msg: 'imagegen.request',
429
+ model: entry.name,
430
+ wire: entry.wire,
431
+ endpoint: useMultipart ? entry.editEndpoint : entry.endpoint,
432
+ multipart: useMultipart,
433
+ references: references.length,
434
+ specs: Object.fromEntries(Object.entries(wireSpecs).filter(([, v]) => v !== undefined)),
435
+ ...(input.extra && Object.keys(input.extra).length > 0 ? { extra: Object.keys(input.extra) } : {}),
436
+ });
437
+
438
+ const startedAt = Date.now();
439
+ let res: Response;
440
+ try {
441
+ res = await fetch(url, {
442
+ method: 'POST',
443
+ headers,
444
+ body: requestBody,
445
+ signal: AbortSignal.timeout(timeoutMs),
446
+ });
447
+ } catch (err) {
448
+ const msg = (err as Error).message;
449
+ const timedOut = (err as Error).name === 'TimeoutError';
450
+ logger.warn({ msg: 'imagegen.upstream_unreachable', url, err: msg });
451
+ throw new ImageGenError(
452
+ timedOut
453
+ ? `Image request timed out after ${Math.round(timeoutMs / 1000)}s. Large resolutions take longer — raise imageGen.timeoutMs if this repeats.`
454
+ : `Image upstream unreachable: ${msg}`,
455
+ 'upstream',
456
+ );
457
+ }
458
+
459
+ if (!res.ok) {
460
+ const text = await res.text().catch(() => '');
461
+ logger.warn({ msg: 'imagegen.upstream_error', status: res.status, body: text.slice(0, 500) });
462
+ // 503/504 means "not right now". The upstream body typically names
463
+ // WHY — the active GPU profile, for instance — so it is relayed
464
+ // verbatim rather than summarised away.
465
+ if (res.status === 503 || res.status === 504) {
466
+ throw new ImageGenError(
467
+ `Image model '${entry.name}' is not available right now (upstream ${res.status}). ` +
468
+ `This is usually temporary. Upstream says: ${text.slice(0, 300)}`,
469
+ 'unavailable',
470
+ );
471
+ }
472
+ throw new ImageGenError(
473
+ `Image upstream returned ${res.status}: ${text.slice(0, 300)}`,
474
+ 'upstream',
475
+ );
476
+ }
477
+
478
+ const payload = (await res.json()) as {
479
+ data?: RawImageRow[];
480
+ images?: RawImageRow[];
481
+ usage?: { cost?: number };
482
+ /** Non-standard, and worth reading where a provider offers it: the
483
+ * parameters it accepted but did not use, and free-text notes
484
+ * about anything it adjusted. Absent almost everywhere — a strict
485
+ * OpenAI-shaped proxy in front of a backend will drop them, which
486
+ * is exactly why the size check below does not depend on them. */
487
+ ignored_params?: unknown;
488
+ warnings?: unknown;
489
+ };
490
+ const rows = payload.data ?? payload.images ?? [];
491
+ if (!Array.isArray(rows) || rows.length === 0) {
492
+ throw new ImageGenError(
493
+ 'Image upstream returned no image data. The model may not support this endpoint.',
494
+ 'upstream',
495
+ );
496
+ }
497
+
498
+ const decoded: UpstreamImage[] = [];
499
+ for (const row of rows) {
500
+ const img = await rowToBytes(row, timeoutMs, provider.baseUrl, provider.apiKey);
501
+ if (img && img.bytes.length > 0) decoded.push(img);
502
+ }
503
+ if (decoded.length === 0) {
504
+ throw new ImageGenError(
505
+ 'Image upstream returned rows without usable image data (no b64_json and no fetchable url).',
506
+ 'upstream',
507
+ );
508
+ }
509
+
510
+ const costUsd = typeof payload.usage?.cost === 'number' ? payload.usage.cost : undefined;
511
+
512
+ // Whatever the endpoint volunteered, relayed as-is.
513
+ if (Array.isArray(payload.ignored_params)) {
514
+ const names = payload.ignored_params.filter((x): x is string => typeof x === 'string');
515
+ if (names.length > 0) {
516
+ warnings.push(
517
+ `The endpoint ignored these parameters — they had no effect: ${names.join(', ')}.`,
518
+ );
519
+ }
520
+ }
521
+ if (Array.isArray(payload.warnings)) {
522
+ for (const w of payload.warnings) if (typeof w === 'string' && w) warnings.push(w);
523
+ }
524
+
525
+ // And the check that needs no cooperation: did we get the size we
526
+ // asked for? A cap, a rounding to a supported step, or a model that
527
+ // only renders squares all answer 200 with a perfectly good image of
528
+ // the wrong shape. Only comparable when the request named pixels —
529
+ // a tier like "2K" is a different vocabulary.
530
+ const requested = parseSizeSpec(wireSpecs.size);
531
+ const firstDims = readDimensions(decoded[0]!.bytes);
532
+ if (requested && firstDims &&
533
+ (requested.width !== firstDims.width || requested.height !== firstDims.height)) {
534
+ warnings.push(
535
+ `Requested ${requested.width}x${requested.height} but the image came back ` +
536
+ `${firstDims.width}x${firstDims.height}. The endpoint substituted a size — ` +
537
+ `it may cap dimensions or round to sizes it supports.`,
538
+ );
539
+ logger.info({
540
+ msg: 'imagegen.size_substituted',
541
+ model: entry.name,
542
+ requested: wireSpecs.size,
543
+ actual: `${firstDims.width}x${firstDims.height}`,
544
+ });
545
+ }
546
+ // Same check for a SHAPE: a ratio was asked for (as aspect_ratio, or
547
+ // as a named size) and the pixels say otherwise. This is what would
548
+ // have stopped a whole series of "16:9" squares after the first one.
549
+ const wantedRatio = requestedRatio(specs) ?? requestedRatio(wireSpecs);
550
+ if (!requested && wantedRatio !== null && firstDims && ratioMismatch(wantedRatio, firstDims.width, firstDims.height)) {
551
+ const asked = specs.aspect_ratio ?? wireSpecs.size ?? specs.size;
552
+ warnings.push(
553
+ `Requested aspect ratio ${asked} but the image came back ${firstDims.width}x${firstDims.height} ` +
554
+ `(${(firstDims.width / firstDims.height).toFixed(2)}:1). The endpoint or a router in front of it ` +
555
+ `ignored the ratio — check the model's catalog and prefer an explicit size if this repeats.`,
556
+ );
557
+ logger.warn({
558
+ msg: 'imagegen.aspect_ratio_substituted',
559
+ model: entry.name,
560
+ requested: asked,
561
+ sent: Object.fromEntries(Object.entries(wireSpecs).filter(([, v]) => v !== undefined)),
562
+ actual: `${firstDims.width}x${firstDims.height}`,
563
+ });
564
+ }
565
+
566
+ const batchId = newMediaId();
567
+ const now = new Date();
568
+ const records: MediaRecord[] = [];
569
+
570
+ for (const [i, img] of decoded.entries()) {
571
+ const stored = await storeMedia({
572
+ bytes: img.bytes,
573
+ kind: 'image',
574
+ prompt,
575
+ config,
576
+ declaredMime: img.mime,
577
+ outputFormat: wireSpecs.output_format,
578
+ now,
579
+ });
580
+
581
+ const linkedTo: string[] = [];
582
+ if (input.saveTo) {
583
+ try {
584
+ linkedTo.push(await linkMedia(stored.path, input.saveTo));
585
+ } catch (err) {
586
+ // The image exists and is safe in its canonical home; failing
587
+ // the whole call over a second name would throw away a paid
588
+ // generation. Report it as a warning instead.
589
+ logger.warn({
590
+ msg: 'imagegen.link_failed',
591
+ dest: input.saveTo,
592
+ err: (err as Error).message,
593
+ });
594
+ }
595
+ }
596
+
597
+ const dims = readDimensions(img.bytes);
598
+ const record: MediaRecord = {
599
+ id: newMediaId(),
600
+ kind: 'image',
601
+ createdAt: now.toISOString(),
602
+ prompt,
603
+ modelName: entry.name,
604
+ modelId: entry.model,
605
+ provider: providerName,
606
+ // As SENT — the gallery must never show a spec the endpoint never
607
+ // saw as if it were the image's shape (width/height carry the truth).
608
+ specs: { ...wireSpecs },
609
+ path: stored.path,
610
+ filename: stored.filename,
611
+ mime: stored.mime,
612
+ bytes: stored.bytes,
613
+ ...(dims ? { width: dims.width, height: dims.height } : {}),
614
+ linkedTo,
615
+ // Upstreams bill per request, not per image; splitting evenly
616
+ // keeps the gallery's per-image figure honest for n > 1.
617
+ ...(costUsd !== undefined ? { costUsd: costUsd / decoded.length } : {}),
618
+ ...(input.agent ? { agent: input.agent } : {}),
619
+ ...(input.session ? { session: input.session } : {}),
620
+ ...(references.length > 0 ? { references: references.length } : {}),
621
+ batchId,
622
+ batchIndex: i,
623
+ };
624
+ await writeRecord(record);
625
+ records.push(record);
626
+ }
627
+
628
+ logger.info({
629
+ msg: 'imagegen.generated',
630
+ model: entry.model,
631
+ count: records.length,
632
+ ms: Date.now() - startedAt,
633
+ costUsd,
634
+ agent: input.agent,
635
+ });
636
+
637
+ return {
638
+ images: records,
639
+ ...(costUsd !== undefined ? { costUsd } : {}),
640
+ ...(warnings.length > 0 ? { warnings } : {}),
641
+ };
642
+ }