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.
- package/LICENSE +21 -0
- package/README.md +364 -0
- package/bin/node-version.d.mts +3 -0
- package/bin/node-version.mjs +45 -0
- package/bin/somora.mjs +77 -0
- package/config.example.yaml +896 -0
- package/docs/agents.md +677 -0
- package/docs/api.md +3194 -0
- package/docs/browser.md +317 -0
- package/docs/builder.md +331 -0
- package/docs/cache-strategy.md +373 -0
- package/docs/compaction.md +253 -0
- package/docs/display.md +154 -0
- package/docs/dream-phases.md +891 -0
- package/docs/files.md +387 -0
- package/docs/imagegen.md +366 -0
- package/docs/images/somora-hero.png +0 -0
- package/docs/images/somora-mobile-2026-05-23.png +0 -0
- package/docs/images/somora-tui-2026-05-23.png +0 -0
- package/docs/images/somora-web-2026-05-23.png +0 -0
- package/docs/index.md +178 -0
- package/docs/lsp.md +93 -0
- package/docs/mcp.md +332 -0
- package/docs/memory.md +407 -0
- package/docs/mobile.md +310 -0
- package/docs/models.md +379 -0
- package/docs/projects.md +425 -0
- package/docs/realtime-voice.md +293 -0
- package/docs/resources.md +230 -0
- package/docs/sampling.md +128 -0
- package/docs/security.md +189 -0
- package/docs/sentinel.md +295 -0
- package/docs/setup.md +1217 -0
- package/docs/skills.md +501 -0
- package/docs/team.md +189 -0
- package/docs/thinking.md +463 -0
- package/docs/tmux.md +399 -0
- package/docs/tools.md +117 -0
- package/docs/videogen.md +191 -0
- package/docs/voice.md +288 -0
- package/docs/web.md +893 -0
- package/docs/wiki.md +583 -0
- package/npm-shrinkwrap.json +5670 -0
- package/package.json +116 -0
- package/src/attachments/store.ts +196 -0
- package/src/browser/change-stream.ts +31 -0
- package/src/browser/display.ts +108 -0
- package/src/browser/policy.ts +121 -0
- package/src/browser/screencast.ts +374 -0
- package/src/browser/service.ts +1337 -0
- package/src/browser/session.ts +15 -0
- package/src/browser/snapshot.ts +40 -0
- package/src/cli/auth.ts +117 -0
- package/src/cli/codex.ts +41 -0
- package/src/cli/lsp.ts +71 -0
- package/src/cli/resolvers/clawhub.ts +400 -0
- package/src/cli/setup.ts +835 -0
- package/src/cli/skill.ts +619 -0
- package/src/cli/somora.ts +548 -0
- package/src/cli/systemd-unit.ts +72 -0
- package/src/cli/team.ts +148 -0
- package/src/cli/tui/activity-stream.ts +121 -0
- package/src/cli/tui/api.ts +479 -0
- package/src/cli/tui/app.tsx +1169 -0
- package/src/cli/tui/autocomplete.tsx +55 -0
- package/src/cli/tui/commands.ts +913 -0
- package/src/cli/tui/dream-glyphs.ts +22 -0
- package/src/cli/tui/footer.tsx +15 -0
- package/src/cli/tui/format.ts +28 -0
- package/src/cli/tui/header.tsx +279 -0
- package/src/cli/tui/index.tsx +120 -0
- package/src/cli/tui/markdown.tsx +63 -0
- package/src/cli/tui/sampling.ts +162 -0
- package/src/cli/tui/separator.tsx +13 -0
- package/src/cli/tui/state.ts +42 -0
- package/src/cli/tui/stream.ts +330 -0
- package/src/cli/tui/thinking-text.ts +54 -0
- package/src/cli/tui/turn-views.tsx +499 -0
- package/src/cli/tui/types.ts +410 -0
- package/src/cli/tui/work-queue.ts +161 -0
- package/src/cli/update-args.ts +55 -0
- package/src/cli/wiki.ts +406 -0
- package/src/compaction/index.ts +28 -0
- package/src/compaction/midturn.ts +210 -0
- package/src/compaction/policy.ts +154 -0
- package/src/compaction/summarize.ts +691 -0
- package/src/compaction/template.ts +90 -0
- package/src/compaction/types.ts +148 -0
- package/src/config/loader.ts +276 -0
- package/src/config/reload.ts +43 -0
- package/src/config/types.ts +2292 -0
- package/src/dream/deep-actions.ts +324 -0
- package/src/dream/deep-dispatcher.ts +237 -0
- package/src/dream/deep-llm.ts +388 -0
- package/src/dream/deep-prompts.ts +106 -0
- package/src/dream/deep-runner.ts +757 -0
- package/src/dream/deep-skip-cache.ts +199 -0
- package/src/dream/deep-worker.ts +229 -0
- package/src/dream/json-salvage.ts +34 -0
- package/src/dream/judge.ts +188 -0
- package/src/dream/loop-state.ts +286 -0
- package/src/dream/lucid-actions.ts +303 -0
- package/src/dream/lucid-batches.ts +94 -0
- package/src/dream/lucid-prompt.ts +82 -0
- package/src/dream/lucid-runner.ts +744 -0
- package/src/dream/lucid-storage.ts +277 -0
- package/src/dream/lucid-structure.ts +102 -0
- package/src/dream/lucid-types.ts +137 -0
- package/src/dream/lucid-worker.ts +224 -0
- package/src/dream/rem-dedup.ts +502 -0
- package/src/dream/rem-extract.ts +782 -0
- package/src/dream/rem-reset-run.ts +67 -0
- package/src/dream/rem-runner.ts +696 -0
- package/src/dream/rem-worker.ts +527 -0
- package/src/dream/review-window.ts +71 -0
- package/src/dream/scheduler-state.ts +129 -0
- package/src/dream/storage.ts +497 -0
- package/src/dream/types.ts +133 -0
- package/src/dream/wiki-context.ts +133 -0
- package/src/engine/a2a.ts +33 -0
- package/src/engine/availability.ts +63 -0
- package/src/engine/claude-cli.ts +969 -0
- package/src/engine/codex-app-server-client.ts +294 -0
- package/src/engine/codex-bin.ts +49 -0
- package/src/engine/codex-cli.ts +1014 -0
- package/src/engine/codex-dynamic-tools.ts +239 -0
- package/src/engine/codex-home.ts +63 -0
- package/src/engine/codex-thread-config.ts +74 -0
- package/src/engine/context-budget.ts +257 -0
- package/src/engine/engine-meta-labels.ts +211 -0
- package/src/engine/grok-cli.ts +941 -0
- package/src/engine/inline-think.ts +59 -0
- package/src/engine/model-availability.ts +105 -0
- package/src/engine/openai-compatible.ts +2464 -0
- package/src/engine/reasoning-retry.ts +83 -0
- package/src/engine/registry.ts +13 -0
- package/src/engine/replay.ts +195 -0
- package/src/engine/sampling.ts +90 -0
- package/src/engine/thinking-params.ts +264 -0
- package/src/engine/types.ts +269 -0
- package/src/engine/user-tag.ts +24 -0
- package/src/imagegen/aspect.ts +128 -0
- package/src/imagegen/generate.ts +642 -0
- package/src/imagegen/references.ts +75 -0
- package/src/imagegen/types.ts +154 -0
- package/src/lsp/client.ts +183 -0
- package/src/lsp/fake-server.helper.mjs +42 -0
- package/src/lsp/format.ts +29 -0
- package/src/lsp/index.ts +21 -0
- package/src/lsp/manager.ts +238 -0
- package/src/lsp/registry.ts +151 -0
- package/src/mcp/config.ts +117 -0
- package/src/mcp/hub/audit.ts +55 -0
- package/src/mcp/hub/bridge.ts +115 -0
- package/src/mcp/hub/catalog.ts +69 -0
- package/src/mcp/hub/credentials.ts +406 -0
- package/src/mcp/hub/env-expand.ts +14 -0
- package/src/mcp/hub/manager.ts +770 -0
- package/src/mcp/hub/normalize.ts +213 -0
- package/src/mcp/server.ts +368 -0
- package/src/mcp/tool-schema.ts +20 -0
- package/src/media/capabilities.ts +392 -0
- package/src/media/records.ts +175 -0
- package/src/media/store.ts +217 -0
- package/src/media/types.ts +69 -0
- package/src/memory/chunking.ts +168 -0
- package/src/memory/embeddings.ts +262 -0
- package/src/memory/index.ts +15 -0
- package/src/memory/inject.ts +197 -0
- package/src/memory/manager.ts +996 -0
- package/src/memory/registry.ts +176 -0
- package/src/memory/rescan.ts +101 -0
- package/src/memory/retrieval.ts +586 -0
- package/src/memory/shared-index.ts +372 -0
- package/src/memory/slug.ts +39 -0
- package/src/memory/storage.ts +385 -0
- package/src/memory/watcher.ts +134 -0
- package/src/multimodal/blocks.ts +101 -0
- package/src/multimodal/dimensions.ts +214 -0
- package/src/multimodal/load.ts +86 -0
- package/src/multimodal/mime.ts +135 -0
- package/src/multimodal/pdf-render.ts +80 -0
- package/src/multimodal/user-content.ts +266 -0
- package/src/persona/files.ts +144 -0
- package/src/persona/loader.ts +598 -0
- package/src/persona/skill-gating-store.ts +59 -0
- package/src/persona/tool-gating-store.ts +113 -0
- package/src/projects/focus.ts +186 -0
- package/src/projects/prompt-block.ts +106 -0
- package/src/projects/scheme.ts +107 -0
- package/src/projects/store.ts +144 -0
- package/src/projects/types.ts +73 -0
- package/src/sentinel/dispatcher.ts +97 -0
- package/src/sentinel/schedule.ts +271 -0
- package/src/sentinel/scheduler.ts +840 -0
- package/src/sentinel/store.ts +259 -0
- package/src/sentinel/types.ts +221 -0
- package/src/server/activity-stream.ts +160 -0
- package/src/server/ask-calls.ts +137 -0
- package/src/server/ask-wait-graph.ts +171 -0
- package/src/server/async-tasks.ts +199 -0
- package/src/server/builder-busy.ts +86 -0
- package/src/server/builder-prompt.ts +204 -0
- package/src/server/builder-questions.ts +117 -0
- package/src/server/builder-session.ts +249 -0
- package/src/server/chat-aborts.ts +83 -0
- package/src/server/claude-config-dir.ts +71 -0
- package/src/server/claude-credential-sync.ts +454 -0
- package/src/server/env-file.ts +100 -0
- package/src/server/env.ts +115 -0
- package/src/server/heal-session.ts +151 -0
- package/src/server/history-page.ts +46 -0
- package/src/server/index.ts +7244 -0
- package/src/server/lockfile.ts +89 -0
- package/src/server/logger.ts +67 -0
- package/src/server/logs.ts +187 -0
- package/src/server/loopback-fetch.ts +130 -0
- package/src/server/openai-client.ts +89 -0
- package/src/server/prompt-assembly.ts +334 -0
- package/src/server/restart-reconcile.ts +139 -0
- package/src/server/run-turn-fallback.ts +275 -0
- package/src/server/run-turn-types.ts +91 -0
- package/src/server/run-turn.ts +1474 -0
- package/src/server/sanitize-assistant-text.ts +112 -0
- package/src/server/session-export.ts +220 -0
- package/src/server/session-queue.ts +376 -0
- package/src/server/session-workdir.ts +49 -0
- package/src/server/sse-h2-safe.ts +61 -0
- package/src/server/sse-liveness.ts +162 -0
- package/src/server/sse-serializer.ts +161 -0
- package/src/server/start-turn.ts +249 -0
- package/src/server/steer-inbox.ts +107 -0
- package/src/server/tls-keeper.ts +153 -0
- package/src/server/tool-format.ts +167 -0
- package/src/server/turn-framing.ts +52 -0
- package/src/server/turn-origin-kind.ts +74 -0
- package/src/server/turn-origin.ts +40 -0
- package/src/server/work-ledger.ts +975 -0
- package/src/server/workspace.ts +114 -0
- package/src/setup/config-edit.ts +201 -0
- package/src/setup/presets.ts +71 -0
- package/src/setup/prompt.ts +163 -0
- package/src/setup/tailscale.ts +44 -0
- package/src/skills/bin-checks.ts +227 -0
- package/src/skills/bootstrap.ts +347 -0
- package/src/skills/env-scope.ts +175 -0
- package/src/skills/gating.ts +71 -0
- package/src/skills/lint.ts +202 -0
- package/src/skills/load.ts +368 -0
- package/src/skills/path-helpers.ts +102 -0
- package/src/skills/registry.ts +178 -0
- package/src/ssh/exec.ts +142 -0
- package/src/ssh/index.ts +12 -0
- package/src/ssh/known-hosts.ts +109 -0
- package/src/ssh/pool.ts +307 -0
- package/src/storage/sessions.ts +602 -0
- package/src/team/render.ts +149 -0
- package/src/team/resolve.ts +122 -0
- package/src/team/store.ts +124 -0
- package/src/team/types.ts +111 -0
- package/src/team/write.ts +95 -0
- package/src/testing/isolated-home.mts +46 -0
- package/src/tmux/attention-watcher.ts +272 -0
- package/src/tmux/attention.ts +336 -0
- package/src/tmux/list.ts +91 -0
- package/src/tmux/origin-store.ts +102 -0
- package/src/tmux/tui-markers.ts +267 -0
- package/src/tools/agents/ask-cancel.ts +94 -0
- package/src/tools/agents/ask-result.ts +235 -0
- package/src/tools/agents/ask.ts +704 -0
- package/src/tools/agents/builder-dispatch.ts +217 -0
- package/src/tools/agents/images.ts +104 -0
- package/src/tools/agents/index.ts +42 -0
- package/src/tools/agents/long-task-timeouts.ts +39 -0
- package/src/tools/agents/session-list.ts +136 -0
- package/src/tools/agents/session-model.ts +106 -0
- package/src/tools/agents/spawn.ts +845 -0
- package/src/tools/agents/status.ts +589 -0
- package/src/tools/browser/index.ts +6 -0
- package/src/tools/browser/ops.ts +145 -0
- package/src/tools/browser/tools.ts +184 -0
- package/src/tools/builder/short-descriptions.ts +80 -0
- package/src/tools/builder/tools.ts +222 -0
- package/src/tools/docs/index.ts +1 -0
- package/src/tools/docs/tools.ts +228 -0
- package/src/tools/dream/index.ts +11 -0
- package/src/tools/dream/tools.ts +1002 -0
- package/src/tools/exec/allowlist.ts +233 -0
- package/src/tools/exec/background-detach.helper.mts +27 -0
- package/src/tools/exec/blacklist.ts +336 -0
- package/src/tools/exec/concurrency.ts +150 -0
- package/src/tools/exec/fit-output.ts +82 -0
- package/src/tools/exec/index.ts +7 -0
- package/src/tools/exec/internal-env.ts +89 -0
- package/src/tools/exec/job-store.ts +403 -0
- package/src/tools/exec/local.ts +649 -0
- package/src/tools/exec/remote.ts +399 -0
- package/src/tools/exec/tools.ts +934 -0
- package/src/tools/file/analyze.ts +378 -0
- package/src/tools/file/index.ts +2 -0
- package/src/tools/file/local.ts +707 -0
- package/src/tools/file/lsp-hook.ts +72 -0
- package/src/tools/file/persona-guard.ts +61 -0
- package/src/tools/file/policy.ts +292 -0
- package/src/tools/file/read-format.ts +129 -0
- package/src/tools/file/remote.ts +680 -0
- package/src/tools/file/replace.ts +507 -0
- package/src/tools/file/search-window.ts +224 -0
- package/src/tools/file/tools.ts +658 -0
- package/src/tools/file/write-scope.ts +182 -0
- package/src/tools/gating.ts +106 -0
- package/src/tools/image/budget.ts +82 -0
- package/src/tools/image/index.ts +7 -0
- package/src/tools/image/tools.ts +601 -0
- package/src/tools/index.ts +99 -0
- package/src/tools/memory/index.ts +12 -0
- package/src/tools/memory/tools.ts +399 -0
- package/src/tools/projects/index.ts +1 -0
- package/src/tools/projects/tools.ts +643 -0
- package/src/tools/registry.ts +427 -0
- package/src/tools/resources/index.ts +8 -0
- package/src/tools/resources/tools.ts +176 -0
- package/src/tools/resources/visibility.ts +60 -0
- package/src/tools/sentinel/index.ts +1 -0
- package/src/tools/sentinel/tools.ts +592 -0
- package/src/tools/skill/index.ts +4 -0
- package/src/tools/skill/tools.ts +285 -0
- package/src/tools/time/index.ts +5 -0
- package/src/tools/time/tools.ts +123 -0
- package/src/tools/tmux/index.ts +1 -0
- package/src/tools/tmux/local.ts +277 -0
- package/src/tools/tmux/remote.ts +168 -0
- package/src/tools/tmux/tools.ts +1064 -0
- package/src/tools/tool-output.ts +97 -0
- package/src/tools/types.ts +227 -0
- package/src/tools/video/index.ts +1 -0
- package/src/tools/video/tools.ts +425 -0
- package/src/tools/web/fetch.ts +337 -0
- package/src/tools/web/index.ts +4 -0
- package/src/tools/web/tools.ts +186 -0
- package/src/tools/wiki/index.ts +1 -0
- package/src/tools/wiki/tools.ts +445 -0
- package/src/tts/cache-gc.ts +128 -0
- package/src/tts/prepare-for-tts.ts +114 -0
- package/src/tts/service.ts +332 -0
- package/src/types/events.ts +695 -0
- package/src/types/turn-origin.ts +53 -0
- package/src/version.ts +21 -0
- package/src/videogen/dialects.ts +222 -0
- package/src/videogen/generate.ts +484 -0
- package/src/videogen/jobs.ts +178 -0
- package/src/videogen/runner.ts +125 -0
- package/src/videogen/wake.ts +119 -0
- package/src/voice/realtime/call.ts +948 -0
- package/src/voice/realtime/consult.ts +293 -0
- package/src/voice/realtime/fake-provider.ts +134 -0
- package/src/voice/realtime/manager.ts +384 -0
- package/src/voice/realtime/openai-provider.ts +471 -0
- package/src/voice/realtime/persona.ts +227 -0
- package/src/voice/realtime/session-match.ts +116 -0
- package/src/voice/realtime/types.ts +182 -0
- package/src/wiki/conflict.ts +113 -0
- package/src/wiki/explorer.ts +578 -0
- package/src/wiki/index-builder.ts +172 -0
- package/src/wiki/language.ts +134 -0
- package/src/wiki/log-builder.ts +150 -0
- package/src/wiki/map.ts +258 -0
- package/src/wiki/migration/analyze.ts +304 -0
- package/src/wiki/migration/execute.ts +689 -0
- package/src/wiki/migration/refine.ts +402 -0
- package/src/wiki/migration/store.ts +100 -0
- package/src/wiki/move-page.ts +57 -0
- package/src/wiki/structure-file.ts +192 -0
- package/src/wiki/taxonomy.ts +140 -0
- package/src/wiki/templates.ts +163 -0
- package/src/wiki/types.ts +133 -0
- package/templates/skills/README.md +24 -0
- package/templates/skills/_templates/api-wrapper/SKILL.md +26 -0
- package/templates/skills/_templates/cli-wrapper/BOOTSTRAP.md +32 -0
- package/templates/skills/_templates/cli-wrapper/SKILL.md +24 -0
- package/templates/skills/_templates/default/SKILL.md +25 -0
- package/templates/skills/builder-handover/SKILL.md +96 -0
- package/templates/skills/builder-handover/assets/ORDER.md +12 -0
- package/templates/skills/skill-author/SKILL.md +110 -0
- package/tsconfig.json +22 -0
- package/web/dist/assets/index-BaVv6pB2.js +631 -0
- package/web/dist/assets/index-BaVv6pB2.js.map +1 -0
- package/web/dist/assets/index-V3FV3Z25.css +32 -0
- package/web/dist/favicon.svg +8 -0
- package/web/dist/index.html +20 -0
- package/web/package.json +36 -0
- package/web/tsconfig.json +25 -0
- package/web-mobile/dist/apple-touch-icon.png +0 -0
- package/web-mobile/dist/assets/index-BqKt7IMx.css +1 -0
- package/web-mobile/dist/assets/index-X_vRr6cd.js +88 -0
- package/web-mobile/dist/assets/index-X_vRr6cd.js.map +1 -0
- package/web-mobile/dist/favicon.svg +8 -0
- package/web-mobile/dist/icon-192.png +0 -0
- package/web-mobile/dist/icon-512.png +0 -0
- package/web-mobile/dist/index.html +27 -0
- package/web-mobile/dist/manifest.webmanifest +32 -0
- package/web-mobile/dist/service-worker.js +90 -0
- package/web-mobile/package.json +28 -0
- 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
|
+
}
|