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,392 @@
|
|
|
1
|
+
// What a given image model actually accepts.
|
|
2
|
+
//
|
|
3
|
+
// Allowed spec values are NOT a property of somora — they belong to the
|
|
4
|
+
// model. grok-imagine renders 1K and 2K; another model does 512 and 4K;
|
|
5
|
+
// next month there's one that does neither. Hardcoding the lists would
|
|
6
|
+
// mean a somora release per model, so the truth is fetched from the
|
|
7
|
+
// provider's image-model catalog at runtime.
|
|
8
|
+
//
|
|
9
|
+
// Three sources, in precedence order:
|
|
10
|
+
// 1. `imageGen.models[].allow` — operator override, always wins.
|
|
11
|
+
// For providers without a catalog (a local image server) or one
|
|
12
|
+
// that's wrong.
|
|
13
|
+
// 2. The provider catalog, cached per process.
|
|
14
|
+
// 3. Nothing — and then everything is allowed. A tool that refuses
|
|
15
|
+
// valid input because it couldn't reach a catalog is worse than
|
|
16
|
+
// one that forwards the request and relays the upstream's own
|
|
17
|
+
// complaint.
|
|
18
|
+
//
|
|
19
|
+
// The catalog payload is provider-specific and not standardized. We
|
|
20
|
+
// read the shapes we can identify with confidence and ignore the rest;
|
|
21
|
+
// an unrecognized payload degrades to source 3 rather than to an empty
|
|
22
|
+
// allow-list. The full entry is logged once at debug level so a real
|
|
23
|
+
// payload can be inspected and this parser tightened against it.
|
|
24
|
+
|
|
25
|
+
import type { ImageModel, OpenAiCompatibleProvider } from '../config/types.ts';
|
|
26
|
+
import { logger } from '../server/logger.ts';
|
|
27
|
+
import {
|
|
28
|
+
ENUMERABLE_SPEC_FIELDS,
|
|
29
|
+
type EnumerableSpecField,
|
|
30
|
+
type ImageSpecs,
|
|
31
|
+
type ModelCapabilities,
|
|
32
|
+
supportsField,
|
|
33
|
+
} from '../imagegen/types.ts';
|
|
34
|
+
|
|
35
|
+
/** Catalog responses are cached for the process lifetime, keyed by
|
|
36
|
+
* provider+endpoint. Restart to re-read — same posture as the rest of
|
|
37
|
+
* config.yaml, and a model's parameter list does not change hourly. */
|
|
38
|
+
const catalogCache = new Map<string, Promise<CatalogEntry[] | null>>();
|
|
39
|
+
|
|
40
|
+
interface CatalogEntry {
|
|
41
|
+
id: string;
|
|
42
|
+
raw: Record<string, unknown>;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* The shape OpenRouter's image-model catalog actually uses, verified
|
|
47
|
+
* against `GET /api/v1/images/models` on 2026-08-26:
|
|
48
|
+
*
|
|
49
|
+
* supported_parameters: {
|
|
50
|
+
* resolution: { type: 'enum', values: ['1K', '2K'] },
|
|
51
|
+
* aspect_ratio: { type: 'enum', values: ['1:1', '16:9', …] },
|
|
52
|
+
* n: { type: 'range', min: 1, max: 1 },
|
|
53
|
+
* input_references: { type: 'range', min: 0, max: 3 },
|
|
54
|
+
* }
|
|
55
|
+
*
|
|
56
|
+
* Read first, because it's the one shape we've seen from a real
|
|
57
|
+
* provider. The looser key-guessing below stays as a fallback for
|
|
58
|
+
* catalogs that publish something else.
|
|
59
|
+
*/
|
|
60
|
+
interface ParamSpec {
|
|
61
|
+
type?: string;
|
|
62
|
+
values?: unknown;
|
|
63
|
+
/** Suggestions, not a restriction — see ModelCapabilities.recommended. */
|
|
64
|
+
recommended?: unknown;
|
|
65
|
+
/** Extra vocabulary the field takes besides its type — for `size`,
|
|
66
|
+
* named ratios (cerebro visual-adapter, 2026-09-07). */
|
|
67
|
+
also_accepts?: unknown;
|
|
68
|
+
min?: unknown;
|
|
69
|
+
max?: unknown;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function supportedParameters(raw: Record<string, unknown>): Record<string, ParamSpec> | null {
|
|
73
|
+
const sp = raw.supported_parameters;
|
|
74
|
+
if (!sp || typeof sp !== 'object' || Array.isArray(sp)) return null;
|
|
75
|
+
return sp as Record<string, ParamSpec>;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function enumValues(params: Record<string, ParamSpec> | null, field: string): string[] | undefined {
|
|
79
|
+
const spec = params?.[field];
|
|
80
|
+
if (!spec || spec.type !== 'enum') return undefined;
|
|
81
|
+
return asStringArray(spec.values);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* `allowZero` matters more than it looks. For `n`, a maximum of zero is
|
|
86
|
+
* meaningless and reads as a catalog glitch. For `input_references` it
|
|
87
|
+
* is a real statement — "this model takes no reference images at all" —
|
|
88
|
+
* and dropping it as "unknown" would let a caller send references to a
|
|
89
|
+
* model that cannot use them, which then fails at the endpoint or,
|
|
90
|
+
* worse, silently ignores them.
|
|
91
|
+
*/
|
|
92
|
+
function rangeMax(
|
|
93
|
+
params: Record<string, ParamSpec> | null,
|
|
94
|
+
field: string,
|
|
95
|
+
allowZero = false,
|
|
96
|
+
): number | undefined {
|
|
97
|
+
const spec = params?.[field];
|
|
98
|
+
if (!spec || spec.type !== 'range') return undefined;
|
|
99
|
+
const max = spec.max;
|
|
100
|
+
if (typeof max !== 'number' || !Number.isFinite(max)) return undefined;
|
|
101
|
+
return max > 0 || (allowZero && max === 0) ? max : undefined;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Field names a catalog might use for each spec, most specific first.
|
|
105
|
+
* Fallback for providers that don't publish `supported_parameters`. */
|
|
106
|
+
const CATALOG_KEYS: Record<EnumerableSpecField, string[]> = {
|
|
107
|
+
resolution: ['resolutions', 'supported_resolutions', 'resolution'],
|
|
108
|
+
aspect_ratio: ['aspect_ratios', 'supported_aspect_ratios', 'aspect_ratio'],
|
|
109
|
+
size: ['sizes', 'supported_sizes', 'size'],
|
|
110
|
+
quality: ['qualities', 'supported_qualities', 'quality'],
|
|
111
|
+
output_format: ['output_formats', 'supported_output_formats', 'output_format'],
|
|
112
|
+
background: ['backgrounds', 'supported_backgrounds', 'background'],
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
function asStringArray(v: unknown): string[] | undefined {
|
|
116
|
+
if (!Array.isArray(v)) return undefined;
|
|
117
|
+
const out = v.filter((x): x is string => typeof x === 'string' && x.length > 0);
|
|
118
|
+
return out.length > 0 ? out : undefined;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Pull a spec's allowed values out of a catalog entry, looking at the
|
|
122
|
+
* top level and one nesting level down (catalogs commonly group these
|
|
123
|
+
* under `parameters` / `capabilities` / `image`). */
|
|
124
|
+
function readValues(raw: Record<string, unknown>, field: EnumerableSpecField): string[] | undefined {
|
|
125
|
+
const containers: Record<string, unknown>[] = [raw];
|
|
126
|
+
for (const key of ['parameters', 'capabilities', 'image', 'image_generation']) {
|
|
127
|
+
const nested = raw[key];
|
|
128
|
+
if (nested && typeof nested === 'object' && !Array.isArray(nested)) {
|
|
129
|
+
containers.push(nested as Record<string, unknown>);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
for (const container of containers) {
|
|
133
|
+
for (const key of CATALOG_KEYS[field]) {
|
|
134
|
+
const hit = asStringArray(container[key]);
|
|
135
|
+
if (hit) return hit;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
return undefined;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function readNumber(
|
|
142
|
+
raw: Record<string, unknown>,
|
|
143
|
+
keys: string[],
|
|
144
|
+
allowZero = false,
|
|
145
|
+
): number | undefined {
|
|
146
|
+
for (const key of keys) {
|
|
147
|
+
const v = raw[key];
|
|
148
|
+
if (typeof v !== 'number' || !Number.isFinite(v)) continue;
|
|
149
|
+
if (v > 0 || (allowZero && v === 0)) return v;
|
|
150
|
+
}
|
|
151
|
+
return undefined;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
async function fetchCatalog(
|
|
155
|
+
provider: OpenAiCompatibleProvider,
|
|
156
|
+
endpoint: string,
|
|
157
|
+
timeoutMs: number,
|
|
158
|
+
): Promise<CatalogEntry[] | null> {
|
|
159
|
+
const url = provider.baseUrl.replace(/\/+$/, '') + endpoint;
|
|
160
|
+
const headers: Record<string, string> = { accept: 'application/json' };
|
|
161
|
+
if (provider.apiKey) headers.authorization = `Bearer ${provider.apiKey}`;
|
|
162
|
+
|
|
163
|
+
try {
|
|
164
|
+
const res = await fetch(url, {
|
|
165
|
+
method: 'GET',
|
|
166
|
+
headers,
|
|
167
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
168
|
+
});
|
|
169
|
+
if (!res.ok) {
|
|
170
|
+
logger.debug({ msg: 'imagegen.catalog_http_error', url, status: res.status });
|
|
171
|
+
return null;
|
|
172
|
+
}
|
|
173
|
+
const body = (await res.json()) as unknown;
|
|
174
|
+
const rows = Array.isArray(body)
|
|
175
|
+
? body
|
|
176
|
+
: ((body as { data?: unknown[] })?.data ?? (body as { models?: unknown[] })?.models);
|
|
177
|
+
if (!Array.isArray(rows)) {
|
|
178
|
+
logger.debug({ msg: 'imagegen.catalog_unexpected_shape', url });
|
|
179
|
+
return null;
|
|
180
|
+
}
|
|
181
|
+
const entries: CatalogEntry[] = [];
|
|
182
|
+
for (const row of rows) {
|
|
183
|
+
if (!row || typeof row !== 'object' || Array.isArray(row)) continue;
|
|
184
|
+
const raw = row as Record<string, unknown>;
|
|
185
|
+
const id = typeof raw.id === 'string' ? raw.id : typeof raw.slug === 'string' ? raw.slug : '';
|
|
186
|
+
if (id) entries.push({ id, raw });
|
|
187
|
+
}
|
|
188
|
+
logger.info({ msg: 'imagegen.catalog_loaded', url, models: entries.length });
|
|
189
|
+
return entries;
|
|
190
|
+
} catch (err) {
|
|
191
|
+
logger.debug({ msg: 'imagegen.catalog_unreachable', url, err: (err as Error).message });
|
|
192
|
+
return null;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** Catalog rows for one provider endpoint, cached. */
|
|
197
|
+
export async function loadCatalog(
|
|
198
|
+
providerName: string,
|
|
199
|
+
provider: OpenAiCompatibleProvider,
|
|
200
|
+
endpoint: string | null,
|
|
201
|
+
timeoutMs = 15_000,
|
|
202
|
+
): Promise<CatalogEntry[] | null> {
|
|
203
|
+
if (!endpoint) return null;
|
|
204
|
+
const key = `${providerName}${endpoint}`;
|
|
205
|
+
let pending = catalogCache.get(key);
|
|
206
|
+
if (!pending) {
|
|
207
|
+
pending = fetchCatalog(provider, endpoint, timeoutMs);
|
|
208
|
+
catalogCache.set(key, pending);
|
|
209
|
+
}
|
|
210
|
+
return pending;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** Test seam — the cache is process-wide and would leak between cases. */
|
|
214
|
+
export function clearCatalogCache(): void {
|
|
215
|
+
catalogCache.clear();
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** Every image model the provider offers, for the UI's "what can I
|
|
219
|
+
* configure?" list. Empty array when no catalog is reachable. */
|
|
220
|
+
export async function listCatalogModels(
|
|
221
|
+
providerName: string,
|
|
222
|
+
provider: OpenAiCompatibleProvider,
|
|
223
|
+
endpoint: string | null,
|
|
224
|
+
): Promise<Array<{ id: string; name?: string }>> {
|
|
225
|
+
const entries = await loadCatalog(providerName, provider, endpoint);
|
|
226
|
+
if (!entries) return [];
|
|
227
|
+
return entries.map((e) => ({
|
|
228
|
+
id: e.id,
|
|
229
|
+
name: typeof e.raw.name === 'string' ? e.raw.name : undefined,
|
|
230
|
+
}));
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
export async function resolveCapabilities(
|
|
234
|
+
providerName: string,
|
|
235
|
+
provider: OpenAiCompatibleProvider,
|
|
236
|
+
entry: ImageModel,
|
|
237
|
+
): Promise<ModelCapabilities> {
|
|
238
|
+
// 1. Operator override wins outright.
|
|
239
|
+
if (entry.allow) {
|
|
240
|
+
const values: Partial<Record<EnumerableSpecField, string[]>> = {};
|
|
241
|
+
for (const field of ENUMERABLE_SPEC_FIELDS) {
|
|
242
|
+
const configured = entry.allow[field as keyof typeof entry.allow];
|
|
243
|
+
if (Array.isArray(configured)) values[field] = configured as string[];
|
|
244
|
+
}
|
|
245
|
+
return {
|
|
246
|
+
known: true,
|
|
247
|
+
source: 'config',
|
|
248
|
+
values,
|
|
249
|
+
// Only when the operator actually declared one. Same rule as the
|
|
250
|
+
// catalog path: a list that exists is exhaustive, no list means
|
|
251
|
+
// we don't know and everything passes.
|
|
252
|
+
...(entry.allow.supported ? { supported: entry.allow.supported } : {}),
|
|
253
|
+
maxN: entry.allow.maxN,
|
|
254
|
+
maxReferences: entry.allow.maxReferences,
|
|
255
|
+
};
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
// 2. Provider catalog.
|
|
259
|
+
const entries = await loadCatalog(providerName, provider, entry.capabilitiesEndpoint);
|
|
260
|
+
const row = entries?.find((e) => e.id === entry.model);
|
|
261
|
+
if (!row) {
|
|
262
|
+
if (entries) {
|
|
263
|
+
// Catalog answered but doesn't list this model. Not fatal — a
|
|
264
|
+
// brand-new model can be callable before it's indexed, and
|
|
265
|
+
// refusing here would be somora overruling the provider.
|
|
266
|
+
logger.warn({
|
|
267
|
+
msg: 'imagegen.model_not_in_catalog',
|
|
268
|
+
model: entry.model,
|
|
269
|
+
provider: providerName,
|
|
270
|
+
});
|
|
271
|
+
}
|
|
272
|
+
return { known: false, source: 'unknown', values: {} };
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
logger.debug({ msg: 'imagegen.catalog_entry', model: entry.model, raw: row.raw });
|
|
276
|
+
|
|
277
|
+
const params = supportedParameters(row.raw);
|
|
278
|
+
const values: Partial<Record<EnumerableSpecField, string[]>> = {};
|
|
279
|
+
const recommended: Partial<Record<EnumerableSpecField, string[]>> = {};
|
|
280
|
+
for (const field of ENUMERABLE_SPEC_FIELDS) {
|
|
281
|
+
const hit = enumValues(params, field) ?? readValues(row.raw, field);
|
|
282
|
+
if (hit) values[field] = hit;
|
|
283
|
+
const hint = asStringArray(params?.[field]?.recommended);
|
|
284
|
+
if (hint) recommended[field] = hint;
|
|
285
|
+
}
|
|
286
|
+
const sizeAlsoAccepts = asStringArray(params?.size?.also_accepts);
|
|
287
|
+
return {
|
|
288
|
+
known: true,
|
|
289
|
+
source: 'catalog',
|
|
290
|
+
values,
|
|
291
|
+
...(Object.keys(recommended).length > 0 ? { recommended } : {}),
|
|
292
|
+
...(sizeAlsoAccepts ? { sizeAlsoAccepts } : {}),
|
|
293
|
+
// Only when the catalog published a parameter list. A catalog entry
|
|
294
|
+
// without one tells us the model exists, not what it takes.
|
|
295
|
+
...(params ? { supported: Object.keys(params) } : {}),
|
|
296
|
+
maxN: rangeMax(params, 'n') ?? readNumber(row.raw, ['max_images', 'maxN', 'max_n']),
|
|
297
|
+
maxReferences:
|
|
298
|
+
rangeMax(params, 'input_references', true) ??
|
|
299
|
+
readNumber(row.raw, ['max_input_references', 'max_references'], true),
|
|
300
|
+
// Not a request parameter, so it lives beside supported_parameters
|
|
301
|
+
// rather than inside it: variants are options on the CONTENT call.
|
|
302
|
+
...(asStringArray(row.raw.supported_variants)
|
|
303
|
+
? { variants: asStringArray(row.raw.supported_variants) }
|
|
304
|
+
: {}),
|
|
305
|
+
};
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/**
|
|
309
|
+
* Validate specs against what the model accepts.
|
|
310
|
+
*
|
|
311
|
+
* Rejections name the valid values, because the caller is often a
|
|
312
|
+
* language model: "resolution '4K' is not supported by this model —
|
|
313
|
+
* allowed: 1K, 2K" gets corrected on the next attempt, whereas
|
|
314
|
+
* "invalid resolution" gets retried verbatim three times.
|
|
315
|
+
*
|
|
316
|
+
* Unknown constraints are not constraints. Only a field we positively
|
|
317
|
+
* know the allowed values for can fail here.
|
|
318
|
+
*/
|
|
319
|
+
export function validateSpecs(
|
|
320
|
+
specs: ImageSpecs,
|
|
321
|
+
caps: ModelCapabilities,
|
|
322
|
+
modelLabel: string,
|
|
323
|
+
): string[] {
|
|
324
|
+
const errors: string[] = [];
|
|
325
|
+
|
|
326
|
+
// A field the model doesn't take at all. Forwarding it would look
|
|
327
|
+
// like it worked — the provider ignores the parameter and returns an
|
|
328
|
+
// image that quietly disregards what was asked for, which is how you
|
|
329
|
+
// end up wondering why "transparent background" did nothing.
|
|
330
|
+
for (const [field, value] of Object.entries(specs)) {
|
|
331
|
+
if (value === undefined) continue;
|
|
332
|
+
if (!supportsField(caps, field)) {
|
|
333
|
+
errors.push(
|
|
334
|
+
`${modelLabel} does not accept '${field}'` +
|
|
335
|
+
(caps.supported ? ` — it takes: ${caps.supported.join(', ')}` : ''),
|
|
336
|
+
);
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
for (const field of ENUMERABLE_SPEC_FIELDS) {
|
|
341
|
+
const value = specs[field];
|
|
342
|
+
const allowed = caps.values[field];
|
|
343
|
+
if (value === undefined || !allowed || allowed.length === 0) continue;
|
|
344
|
+
// Tier names are case-insensitive in practice ("2k" vs "2K").
|
|
345
|
+
const ok = allowed.some((a) => a.toLowerCase() === String(value).toLowerCase());
|
|
346
|
+
if (!ok) {
|
|
347
|
+
errors.push(
|
|
348
|
+
`${field} '${value}' is not supported by ${modelLabel} — allowed: ${allowed.join(', ')}`,
|
|
349
|
+
);
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
if (specs.n !== undefined) {
|
|
354
|
+
if (!Number.isInteger(specs.n) || specs.n < 1) {
|
|
355
|
+
errors.push(`n must be a positive integer, got '${specs.n}'`);
|
|
356
|
+
} else if (caps.maxN !== undefined && specs.n > caps.maxN) {
|
|
357
|
+
errors.push(`n '${specs.n}' exceeds what ${modelLabel} allows (max ${caps.maxN})`);
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
if (specs.output_compression !== undefined) {
|
|
362
|
+
const c = specs.output_compression;
|
|
363
|
+
if (!Number.isInteger(c) || c < 0 || c > 100) {
|
|
364
|
+
errors.push(`output_compression must be an integer 0-100, got '${c}'`);
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
return errors;
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
/** Merge configured defaults under caller-supplied specs. Caller wins
|
|
372
|
+
* field by field, so a default aspect ratio survives a call that only
|
|
373
|
+
* overrides the resolution. */
|
|
374
|
+
export function applyDefaults(
|
|
375
|
+
specs: ImageSpecs,
|
|
376
|
+
entry: ImageModel,
|
|
377
|
+
caps?: ModelCapabilities,
|
|
378
|
+
): ImageSpecs {
|
|
379
|
+
const merged: ImageSpecs = { ...specs };
|
|
380
|
+
for (const [key, value] of Object.entries(entry.defaults)) {
|
|
381
|
+
if (value === undefined) continue;
|
|
382
|
+
// Silently skipped rather than applied-and-rejected: defaults are
|
|
383
|
+
// operator convenience, not intent for this particular call. One
|
|
384
|
+
// shared default block across several models shouldn't make every
|
|
385
|
+
// request to the odd one out fail.
|
|
386
|
+
if (caps && !supportsField(caps, key)) continue;
|
|
387
|
+
if (merged[key as keyof ImageSpecs] === undefined) {
|
|
388
|
+
(merged as Record<string, unknown>)[key] = value;
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
return merged;
|
|
392
|
+
}
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
// Metadata for generated media — one JSON file per item under
|
|
2
|
+
// ~/.somora/media/.
|
|
3
|
+
//
|
|
4
|
+
// Records written before video existed lived under ~/.somora/images/;
|
|
5
|
+
// those are moved across on first use. The directory is ours and
|
|
6
|
+
// invisible to clients, so renaming it costs one migration and spares
|
|
7
|
+
// everyone a name that stops being true the day a video lands in it.
|
|
8
|
+
//
|
|
9
|
+
// Separate from the image files themselves on purpose: the canonical
|
|
10
|
+
// image directory is a place a human browses, drags into other apps and
|
|
11
|
+
// occasionally cleans out. Sidecar .json files next to the images would
|
|
12
|
+
// be noise there, and a deleted image would silently take its
|
|
13
|
+
// provenance with it.
|
|
14
|
+
//
|
|
15
|
+
// Write is tmp-then-rename (same as src/tools/exec/job-store.ts) so a
|
|
16
|
+
// crash mid-write can't leave a half-parsed record behind.
|
|
17
|
+
|
|
18
|
+
import { mkdir, readdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';
|
|
19
|
+
import { randomUUID } from 'node:crypto';
|
|
20
|
+
import { join } from 'node:path';
|
|
21
|
+
import { logger, SOMORA_HOME_DIR } from '../server/logger.ts';
|
|
22
|
+
import type { MediaKind, MediaRecord } from './types.ts';
|
|
23
|
+
import { mediaKind } from './types.ts';
|
|
24
|
+
|
|
25
|
+
const RECORDS_DIR = join(SOMORA_HOME_DIR, 'media');
|
|
26
|
+
const LEGACY_RECORDS_DIR = join(SOMORA_HOME_DIR, 'images');
|
|
27
|
+
|
|
28
|
+
/** Short, URL-safe, collision-resistant enough for a personal archive. */
|
|
29
|
+
export function newMediaId(): string {
|
|
30
|
+
return randomUUID().replace(/-/g, '').slice(0, 12);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
let migrated = false;
|
|
34
|
+
|
|
35
|
+
/** Move pre-video records into the new directory, once per process.
|
|
36
|
+
* Best-effort: a file that won't move is left where it is and logged
|
|
37
|
+
* rather than failing the call that happened to trigger the sweep. */
|
|
38
|
+
async function migrateLegacy(): Promise<void> {
|
|
39
|
+
if (migrated) return;
|
|
40
|
+
migrated = true;
|
|
41
|
+
let files: string[];
|
|
42
|
+
try {
|
|
43
|
+
files = await readdir(LEGACY_RECORDS_DIR);
|
|
44
|
+
} catch {
|
|
45
|
+
return; // never existed, or already gone
|
|
46
|
+
}
|
|
47
|
+
let moved = 0;
|
|
48
|
+
for (const file of files) {
|
|
49
|
+
if (!file.endsWith('.json')) continue;
|
|
50
|
+
try {
|
|
51
|
+
await rename(join(LEGACY_RECORDS_DIR, file), join(RECORDS_DIR, file));
|
|
52
|
+
moved += 1;
|
|
53
|
+
} catch (err) {
|
|
54
|
+
logger.warn({ msg: 'media.record_migrate_failed', file, err: (err as Error).message });
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
if (moved > 0) logger.info({ msg: 'media.records_migrated', from: LEGACY_RECORDS_DIR, moved });
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
async function ensureDir(): Promise<void> {
|
|
61
|
+
await mkdir(RECORDS_DIR, { recursive: true });
|
|
62
|
+
await migrateLegacy();
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function recordPath(id: string): string {
|
|
66
|
+
return join(RECORDS_DIR, `${id}.json`);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export async function writeRecord(record: MediaRecord): Promise<void> {
|
|
70
|
+
await ensureDir();
|
|
71
|
+
const target = recordPath(record.id);
|
|
72
|
+
const tmp = `${target}.tmp`;
|
|
73
|
+
await writeFile(tmp, JSON.stringify(record, null, 2), 'utf8');
|
|
74
|
+
await rename(tmp, target);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export async function readRecord(id: string): Promise<MediaRecord | null> {
|
|
78
|
+
// Ids come from HTTP paths and tool arguments — refuse anything that
|
|
79
|
+
// could climb out of the records dir before it reaches join().
|
|
80
|
+
if (!/^[A-Za-z0-9_-]{1,64}$/.test(id)) return null;
|
|
81
|
+
try {
|
|
82
|
+
const raw = await readFile(recordPath(id), 'utf8');
|
|
83
|
+
return JSON.parse(raw) as MediaRecord;
|
|
84
|
+
} catch (err) {
|
|
85
|
+
if ((err as NodeJS.ErrnoException).code !== 'ENOENT') {
|
|
86
|
+
logger.warn({ msg: 'imagegen.record_read_failed', id, err: (err as Error).message });
|
|
87
|
+
}
|
|
88
|
+
return null;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export async function deleteRecord(id: string): Promise<boolean> {
|
|
93
|
+
if (!/^[A-Za-z0-9_-]{1,64}$/.test(id)) return false;
|
|
94
|
+
try {
|
|
95
|
+
await unlink(recordPath(id));
|
|
96
|
+
return true;
|
|
97
|
+
} catch {
|
|
98
|
+
return false;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export interface ListFilter {
|
|
103
|
+
/** Restrict to one medium. Omitted ⇒ both. */
|
|
104
|
+
kind?: MediaKind;
|
|
105
|
+
/** Case-insensitive substring over the prompt. */
|
|
106
|
+
query?: string;
|
|
107
|
+
/** Config handle, e.g. `grok-imagine`. */
|
|
108
|
+
model?: string;
|
|
109
|
+
agent?: string;
|
|
110
|
+
session?: string;
|
|
111
|
+
/** ISO date (YYYY-MM-DD) — inclusive bounds on createdAt. */
|
|
112
|
+
since?: string;
|
|
113
|
+
until?: string;
|
|
114
|
+
limit?: number;
|
|
115
|
+
offset?: number;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export interface ListResult {
|
|
119
|
+
total: number;
|
|
120
|
+
items: MediaRecord[];
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Newest first. Reads every record — fine for a personal archive in the
|
|
125
|
+
* thousands, and it keeps the store a plain directory of JSON files
|
|
126
|
+
* that stays readable and repairable by hand. If this ever gets slow,
|
|
127
|
+
* the fix is an index, not a database.
|
|
128
|
+
*/
|
|
129
|
+
export async function listRecords(filter: ListFilter = {}): Promise<ListResult> {
|
|
130
|
+
await ensureDir();
|
|
131
|
+
let files: string[];
|
|
132
|
+
try {
|
|
133
|
+
files = await readdir(RECORDS_DIR);
|
|
134
|
+
} catch {
|
|
135
|
+
return { total: 0, items: [] };
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const records: MediaRecord[] = [];
|
|
139
|
+
for (const file of files) {
|
|
140
|
+
if (!file.endsWith('.json')) continue;
|
|
141
|
+
try {
|
|
142
|
+
const raw = await readFile(join(RECORDS_DIR, file), 'utf8');
|
|
143
|
+
records.push(JSON.parse(raw) as MediaRecord);
|
|
144
|
+
} catch (err) {
|
|
145
|
+
logger.warn({ msg: 'media.record_skipped', file, err: (err as Error).message });
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
const q = filter.query?.toLowerCase();
|
|
150
|
+
const matched = records.filter((r) => {
|
|
151
|
+
if (q && !r.prompt.toLowerCase().includes(q)) return false;
|
|
152
|
+
if (filter.kind && mediaKind(r) !== filter.kind) return false;
|
|
153
|
+
if (filter.model && r.modelName !== filter.model) return false;
|
|
154
|
+
if (filter.agent && r.agent !== filter.agent) return false;
|
|
155
|
+
if (filter.session && r.session !== filter.session) return false;
|
|
156
|
+
if (filter.since && r.createdAt < filter.since) return false;
|
|
157
|
+
// `until` is a date; compare against the day's end so an inclusive
|
|
158
|
+
// bound doesn't exclude everything generated that afternoon.
|
|
159
|
+
if (filter.until && r.createdAt > `${filter.until}T23:59:59.999Z`) return false;
|
|
160
|
+
return true;
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
matched.sort((a, b) => (a.createdAt < b.createdAt ? 1 : a.createdAt > b.createdAt ? -1 : 0));
|
|
164
|
+
|
|
165
|
+
const offset = filter.offset ?? 0;
|
|
166
|
+
const limit = filter.limit ?? 100;
|
|
167
|
+
return { total: matched.length, items: matched.slice(offset, offset + limit) };
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** Total bytes across all records — shown in the gallery so the
|
|
171
|
+
* archive's growth is visible without a shell. */
|
|
172
|
+
export async function totalBytes(): Promise<number> {
|
|
173
|
+
const { items } = await listRecords({ limit: Number.MAX_SAFE_INTEGER });
|
|
174
|
+
return items.reduce((sum, r) => sum + (r.bytes || 0), 0);
|
|
175
|
+
}
|