Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix agy image gen failing on a retired shipped model id
[._.]/ Adam Eivye031d61f914c
diff --git a/server/lib/README.md b/server/lib/README.mdindex 8198a52d92..558e5681d1 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -202,7 +202,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `videoStreamingMode.js` | Block-streaming request vocabulary for LTX-2/2.5 MLX local video renders (#6499) — `VIDEO_STREAMING_MODES` (`auto` \| `resident` \| `stream`), `DEFAULT_VIDEO_STREAMING_MODE` (`'auto'`), `VIDEO_STREAMING_MODE_OPTIONS` (label + description for the picker), `isDefaultVideoStreamingMode` / `isKnownVideoStreamingMode` / `videoStreamingModeLabel` / `videoStreamingModeFromRecord`. This module carries only the REQUEST-side enum — `scripts/generate_ltx2.py#resolve_streaming_policy()` inspects the pinned pipeline's actual constructor and this machine's physical RAM to decide whether `auto` streams, and an explicit `stream` request the pinned pipeline cannot honor (Extend) is a refusal there, not a downgrade here. Pure, mirrored to `client/src/lib/videoStreamingMode.js`. || `videoTextEncoders.js` | Swappable prompt conditioners for local video runtimes. MiniMax H3 reads the *unnormalized* hidden state after Qwen3-VL language layer 49 (layers 50-63, the final norm and `lm_head` are never evaluated), so any checkpoint carrying the same embedding + layers 0-49 + vision tower is a drop-in conditioner — swapping it changes how the model reads a prompt without touching the diffusion weights. `TEXT_ENCODERS_BY_RUNTIME` declares the shipped options per runtime (pinned repo/revision plus an explicit `files` LIST — one repackaged safetensors, or just the shards of an upstream checkpoint that carry parameters the loader actually builds; in code rather than the media-models registry so a stale `data/media-models.json` can't name a file the runner can't map); `videoTextEncoderOptions(model)` returns the TRUE list stock-first (it deliberately does NOT collapse a one-entry runtime to `[]` — that is a presentation rule, and folding it in here would change what the server believes a model supports and empty the "offers …" list in the error; `TextEncoderPicker` owns the hide-when-there-is-no-real-choice check), `isStockTextEncoder(id)` makes absence and the `stock` sentinel the same request, `resolveVideoTextEncoder(model, id)` returns `null` for the stock choice or throws `VIDEO_TEXT_ENCODER_UNSUPPORTED` (with the non-throwing `supportsVideoTextEncoder` + `videoTextEncoderUnsupportedError` split out so the request path can reject before staging uploads), and `downloadableVideoTextEncoders()` (deduped by id — the table is keyed by RUNTIME, so one conditioner can be offered by two) / `downloadableVideoTextEncoder(id)` feed the `/api/video-gen/text-encoders/:id/(download\|repair)` lane. Two loader-mechanics fields exist because a ComfyUI-packaged conditioner is namespaced differently from the HF checkpoint the MLX port matches: `keyPrefixMap` (`model.` → `model.language_model.`, `visual.` → `model.visual.`) is applied to every checkpoint key by `scripts/generate_minimax_h3.py` BEFORE the pinned loader sees it — no fork of the pinned runtime — and `finalNormKey` names where the runner synthesizes a ones-filled `norm.weight` for a checkpoint published without one (correct upstream, since H3 reads the state *before* the norm, but the pinned loader refuses to load with any parameter missing). Both are absent for an UPSTREAM Qwen3-VL-32B checkpoint, which already uses the loader namespace and ships its own norm. A candidate must BE Qwen3-VL-32B (the shim reuses upstream's config/tokenizer/processor) — a different Qwen generation is not a substitute however close its conditioning width looks; see docs/features/video-text-encoders.md. `publicTextEncoderOption(entry)` is the client projection and deliberately drops both, so the UI can't reimplement the remap. The `ltx25` table (#4320) uses a third mechanic, `configOverrides`, because an LTX-2.5 pack's OWN Gemma 4 tower wins over `--gemma` inside the pinned fork: the substitution is a standalone shim directory whose generated `config.json` is the substitute's own with these keys merged over it (only ever the `model_type` label a unified checkpoint gets wrong — never `text_config`/`quantization`), and a candidate must BE Gemma 4 12B at 48 layers / hidden 3840 / vocab 262144 / `k_eq_v`. `verified` gates a substitute out of BOTH lanes (picker AND download) until it has been A/B-rendered against its runtime's stock conditioner — required on every non-built-in entry and fail-closed on absence, so a new entry is unreachable until someone states a verdict; both ltx25 substitutes are `verified: false` today. `declaredVideoTextEncoders()` is the UNFILTERED table for shape/invariant checks only — never the render or download path, and `videoTextEncoderRuntimes()` enumerates the table's runtime keys so parity/shape tests cover every runtime rather than the one that happened to exist when they were written. || `pi.js` | Pi command identity, headless/TUI arguments, and positional prompt delivery. |-| `providerModels.js` | Provider model resolution sentinels + helpers (`CODEX_CONFIGURED_DEFAULT` / `ANTIGRAVITY_CONFIGURED_DEFAULT` / `GROK_CONFIGURED_DEFAULT` / `KIMI_CONFIGURED_DEFAULT`, `resolveCliModel`, `filterSelectableModels`, Bedrock/OpenCode model mappers, `localRuntimeNamespace(provider)` — the OpenCode namespace only when it names a LOCAL daemon, i.e. the composed "namespace and not a hosted gateway" test that `cliChildEnv.js`, `localProviderRuntime.js` and `providerVendors.js` all key on, `CODEX_OSS_LOCAL_PROVIDERS` / `CODEX_OSS_MIN_VERSION` / `codexOssLocalProvider` / `codexUnsupportedLocalRuntime` — the codex half of that same axis: which local runtimes Codex's `--local-provider` can serve, and which marked runtime it cannot, kept here beside the namespace they wrap so `providerPrerequisites.js` classifies a codex record without importing `codex.js` (the argv emitter, `buildCodexOssArgs`, stays there), `OPENCODE_PUBLIC_REVIEW_AGENT` — the read-only OpenCode agent a no-tool public-review stage runs as, kept in this leaf because `providerVendors.js` must not import `opencodeConfig.js`, `parseOpencodeConfigContent` — the shared "is this stored OPENCODE_CONFIG_CONTENT usable?" read — plus `opencodeConfigIsLocalOnly` / `opencodeProviderIsLocalOnly`, the ONE locality rule `providerVendors.js` (gate eligibility) and `cliChildEnv.js` (public-review env allowlist) must not disagree about: if eligibility says yes where the allowlist strips the config, the stage spawns against the user's own ~/.config/opencode with tools intact while still reporting an enforced tool-free gate, `normalizeClaudeModelId` / `resolveClaudeCliModel` — the Claude-argv chokepoint that rewrites a dotted first-party version (`claude-fable-5.1`) to the dashed id Claude Code actually serves before the Bedrock mapping runs, model-flag scan helpers incl. `stripBrokenModelFlags`, `isCodexProvider`, `isKimiProvider`, `isAntigravityProvider`, `isCursorProvider`) plus reasoning-effort helpers for the claude/codex/agy/cursor CLIs (`CLAUDE_EFFORT_LEVELS` / `CODEX_EFFORT_LEVELS` / `ANTIGRAVITY_EFFORT_LEVELS` / `CURSOR_EFFORT_LEVELS` / `EFFORT_LEVELS`, `effortLevelsForProvider`, `resolveCliEffort` — clamps an out-of-range effort to the nearest level the target CLI accepts rather than dropping it, so a value saved against a wider ladder survives a provider switch — `clampEffortToLadder` (that clamp over an explicit ladder; the client's own `resolveCliEffort` runs its published-field ladder through it), `hasEffortFlag`, `buildEffortArgs` — the one emitter of `--effort <level>` / `-c model_reasoning_effort=<level>`, and deliberately silent for cursor — and `foldCursorEffortIntoModel`, which carries a cursor level inside `--model` as Cursor’s own variant syntax (`gpt-5[effort=max]`) because `cursor-agent` has no `--effort` flag) plus codex startup-arg helpers (`CODEX_EFFORT_KEY`, `CODEX_UPDATE_CHECK_KEY`, `hasCodexUpdateCheckConfig`, `buildCodexStartupArgs` — the one emitter of `-c check_for_update_on_startup=false`, spread by every codex spawn builder to disable the blocking startup update modal) plus `PORTOS_CLI_CONFIG_KEYS` / `isPortosSuppliedConfigKey` — the exhaustive list of `-c <key>=<value>` config keys PortOS injects, read by the `cli-config-invalid` error analyzer to tell a rejected PortOS override apart from a bad line in the user's own CLI config file.; `isOpencodeLocalProvider` (the OpenCode-on-a-local-backend-or-gateway gate behind the OpenCode effort ladder) and `isCodexSubscriptionProvider` (the ChatGPT-subscription readiness key, housed here so the browser re-export skips `codexAccount.js`'s protocol tables) |+| `providerModels.js` | Provider model resolution sentinels + helpers (`CODEX_CONFIGURED_DEFAULT` / `ANTIGRAVITY_CONFIGURED_DEFAULT` / `GROK_CONFIGURED_DEFAULT` / `KIMI_CONFIGURED_DEFAULT`, `resolveCliModel`, `filterSelectableModels`, Bedrock/OpenCode model mappers, `localRuntimeNamespace(provider)` — the OpenCode namespace only when it names a LOCAL daemon, i.e. the composed "namespace and not a hosted gateway" test that `cliChildEnv.js`, `localProviderRuntime.js` and `providerVendors.js` all key on, `CODEX_OSS_LOCAL_PROVIDERS` / `CODEX_OSS_MIN_VERSION` / `codexOssLocalProvider` / `codexUnsupportedLocalRuntime` — the codex half of that same axis: which local runtimes Codex's `--local-provider` can serve, and which marked runtime it cannot, kept here beside the namespace they wrap so `providerPrerequisites.js` classifies a codex record without importing `codex.js` (the argv emitter, `buildCodexOssArgs`, stays there), `OPENCODE_PUBLIC_REVIEW_AGENT` — the read-only OpenCode agent a no-tool public-review stage runs as, kept in this leaf because `providerVendors.js` must not import `opencodeConfig.js`, `parseOpencodeConfigContent` — the shared "is this stored OPENCODE_CONFIG_CONTENT usable?" read — plus `opencodeConfigIsLocalOnly` / `opencodeProviderIsLocalOnly`, the ONE locality rule `providerVendors.js` (gate eligibility) and `cliChildEnv.js` (public-review env allowlist) must not disagree about: if eligibility says yes where the allowlist strips the config, the stage spawns against the user's own ~/.config/opencode with tools intact while still reporting an enforced tool-free gate, `normalizeClaudeModelId` / `resolveClaudeCliModel` — the Claude-argv chokepoint that rewrites a dotted first-party version (`claude-fable-5.1`) to the dashed id Claude Code actually serves before the Bedrock mapping runs, model-flag scan helpers incl. `stripBrokenModelFlags`, `isCodexProvider`, `isKimiProvider`, `isAntigravityProvider`, `isCursorProvider`) plus the agy catalog family, which reads an `agy models` list as base ids paired with effort tiers (`splitAntigravityModel`, `antigravityBaseModels`, `antigravityModelEffortLevels`, `antigravityCatalogListsModel` — is a stored pin still served? — and `pickAntigravityRelayModel` — the cheapest tier to relay one tool call on when a vendor retires the pin PortOS shipped) plus reasoning-effort helpers for the claude/codex/agy/cursor CLIs (`CLAUDE_EFFORT_LEVELS` / `CODEX_EFFORT_LEVELS` / `ANTIGRAVITY_EFFORT_LEVELS` / `CURSOR_EFFORT_LEVELS` / `EFFORT_LEVELS`, `effortLevelsForProvider`, `resolveCliEffort` — clamps an out-of-range effort to the nearest level the target CLI accepts rather than dropping it, so a value saved against a wider ladder survives a provider switch — `clampEffortToLadder` (that clamp over an explicit ladder; the client's own `resolveCliEffort` runs its published-field ladder through it), `hasEffortFlag`, `buildEffortArgs` — the one emitter of `--effort <level>` / `-c model_reasoning_effort=<level>`, and deliberately silent for cursor — and `foldCursorEffortIntoModel`, which carries a cursor level inside `--model` as Cursor’s own variant syntax (`gpt-5[effort=max]`) because `cursor-agent` has no `--effort` flag) plus codex startup-arg helpers (`CODEX_EFFORT_KEY`, `CODEX_UPDATE_CHECK_KEY`, `hasCodexUpdateCheckConfig`, `buildCodexStartupArgs` — the one emitter of `-c check_for_update_on_startup=false`, spread by every codex spawn builder to disable the blocking startup update modal) plus `PORTOS_CLI_CONFIG_KEYS` / `isPortosSuppliedConfigKey` — the exhaustive list of `-c <key>=<value>` config keys PortOS injects, read by the `cli-config-invalid` error analyzer to tell a rejected PortOS override apart from a bad line in the user's own CLI config file.; `isOpencodeLocalProvider` (the OpenCode-on-a-local-backend-or-gateway gate behind the OpenCode effort ladder) and `isCodexSubscriptionProvider` (the ChatGPT-subscription readiness key, housed here so the browser re-export skips `codexAccount.js`'s protocol tables) || `providerVendors.js` | `PROVIDER_VENDORS` — one row per coding-agent CLI/TUI vendor (claude/codex/antigravity/opencode/grok/kimi/cursor, plus a deliberately-incomplete legacy `gemini-cli` row), consumed by every dispatch site that used to hand-roll its own vendor if-chain across ~8 branches in 5 files (#3618): `applyCommandDefaults`/`prepareCliPrompt` (re-exported from `tuiHandshake.js`/`cliProviderArgs.js`), `buildVendorCliArgs`/`buildVendorSpawnConfig` (consumed by `cliProviderArgs.js#buildCliArgs` / `agentCliSpawning.js#buildCliSpawnConfig`), `inferTuiCommand` (re-exported from `tuiHandshake.js`), and `injectTuiModelAndEffort` — the shared antigravity-validates-the-pair-vs-everyone-else `--model`/`--effort` injection used by both `tuiHandshake.js#buildTuiInvocation` and `agentTuiSpawning.js#buildTuiSpawnConfig`, replacing a second copy of that split that had already drifted once before this file existed. Doesn't rewrite any vendor's argv-building logic — that stays in `antigravity.js`/`grok.js`/`kimi.js`/`cursor.js`/`codex.js`. Dependency-light on purpose, mirroring those files. || `publicReviewSpawnGate.js` | The ordered spawn-time preconditions a public-content review stage must clear before `runAgentSpawn` starts an agent for it — `checkPublicReviewSpawnPreconditions` returns the FIRST failing gate as `{ reason, category, emit }` (or null), running them in the order that is the contract: `publicReviewScanBlock` (the model-abuse scan cleared at least one PR), `publicReviewEligibilityBlock` (a complete eligibility verdict COVERING every PR the issue watcher saw — a partial gate is not a pass), `publicReviewProviderBlock` from `providerVendors.js` (the vendor row declares a maintained recipe for the requested posture; it owns the ordinary-task `null` posture, the re-derivation #5866 got wrong), then the model itself. `emit` tells the caller how to announce it: `warn-log` for the two fail-closed CONTENT gates, whose block must not raise an investigator that could retry the same unvalidated input, `agent:error` for a provider/model misconfiguration that should. `validateModel` is injected rather than imported — it is the one gate that probes a live runtime, so taking it as a parameter keeps this leaf out of the local-LLM graph and makes the gate ORDER testable with a stub. || `modelCapabilityTests.js` | Catalog + scoring for the CAPABILITY tests on `/models/performance` (run by `services/modelCapabilityTests.js`): `CAPABILITY_TESTS` (sandbox repair / image analysis / story outline / fiction scene / rhetoric evaluator, each gated on the capability badges the install catalog already shows), `applicabilityFor` + `applicableTests` (`applicable` / `not-applicable` / `unknown` — an UNCLAIMED capability is never a failure, and `null` capabilities mean the runtime reported none, which is distinct from `[]`), `scoreKeywords` + `VISION_FIXTURE_KEYWORDS` (required vs bonus terms, word-boundary matched with a negation guard so "no dog" doesn't score a dog), `scoreStoryBeats` + `HEROS_JOURNEY_BEATS` (coverage AND ordering, judged only over the beats present), `scoreSandboxRepair` (verdict from observed disk facts — editing the test instead of the module fails outright), `formatAgentEvent` (one agent stream frame → a transcript line), `rollUpVerdict`, and the verbatim `CAPABILITY_TEST_PROMPTS` / `SANDBOX_TASK_PROMPT` the consent gate shows. Pure, so any stored transcript can be re-scored with no provider call. |diff --git a/server/lib/imageGenCapabilities.js b/server/lib/imageGenCapabilities.jsindex 6126bb4c27..ce27bde424 100644--- a/server/lib/imageGenCapabilities.js+++ b/server/lib/imageGenCapabilities.js@@ -69,8 +69,33 @@ export const CODEX_IMAGEGEN_DEFAULT_EFFORT = 'low';// code-level-default rationale as Codex: reaches every install and peer with no// migration; an explicit `imageGen.agy.model` in Settings still wins. If this// tier ever proves flaky at issuing generate_image, escalate exactly one rung-// (gemini-3.5-flash-medium) and record why here.-export const AGY_IMAGEGEN_DEFAULT_MODEL = 'gemini-3.5-flash-low';+// (gemini-3.8-flash-medium) and record why here.+//+// THE INCIDENT BOTH PINS BELOW ARE GUARDED AGAINST — the canonical telling; the+// helpers and tests that defend it point back here rather than restating it.+// Vendors retire model ids between builds, and no migration carries a+// code-level default along. Migration 335 dropped the whole gemini-3.5 tier+// from the shipped Antigravity catalog while this constant still read+// `gemini-3.5-flash-low`, so every unpinned agy render failed with `--effort is+// not supported for model "gemini-3.5-flash"` — silently, until someone tried+// to generate an image. Two defenses, layered:+//+// - `imageGenCapabilities.test.js` pins BOTH constants to the ids+// `data.reference/providers.json` still seeds, so a catalog migration that+// forgets its pin fails in CI instead of on a user's render;+// - agy additionally self-heals at render time+// (`imageGen/agy.js#resolveAgyDriverModel`), because an install can outrun+// its PortOS version: the catalog refreshes from the live CLI on its own+// schedule. That covers only this PortOS-chosen pin — a model the user typed+// is theirs. Codex has no such heal: its pin is passed through verbatim by+// `imageGen/codex.js` with no model/effort pairing to validate, so a retired+// id surfaces as codex's own error rather than a confusing one, and the CI+// guard above is the defense. Give it one if that ever stops being true.+//+// So this constant is a shipped STARTING POINT — but keep it current: it is+// what the Settings/ImageGen pickers display as "the default", and what an+// install with no catalog falls back to.+export const AGY_IMAGEGEN_DEFAULT_MODEL = 'gemini-3.8-flash-low';// The image model behind agy's generate_image tool — fixed server-side by// Antigravity and NOT selectable by PortOS. Re-probed 2026-07-30 against agydiff --git a/server/lib/imageGenCapabilities.test.js b/server/lib/imageGenCapabilities.test.jsnew file mode 100644index 0000000000..e1d56ee619--- /dev/null+++ b/server/lib/imageGenCapabilities.test.js@@ -0,0 +1,46 @@+import { describe, it, expect } from 'vitest';+import { readFileSync } from 'fs';+import { dirname, resolve } from 'path';+import { fileURLToPath } from 'url';+import { AGY_IMAGEGEN_DEFAULT_MODEL, CODEX_IMAGEGEN_DEFAULT_MODEL } from './imageGenCapabilities.js';+import { pickAntigravityRelayModel } from './providerModels.js';++// The cheap-tier pins here are code-level defaults: no migration carries them,+// so nothing forces them to move when a vendor retires a model id, and they+// went out of sync exactly that way — see AGY_IMAGEGEN_DEFAULT_MODEL for the+// incident this guard exists to make impossible to ship again.+//+// Derived from `data.reference/providers.json` rather than a hand-transcribed+// list: that seed is what a fresh install starts with, and every catalog+// migration is written to keep it in lockstep, so it is the one place that+// already knows which ids a vendor still serves.+//+// Read as JSON instead of importing the toolkit's own catalog module — that+// module pulls the whole provider subtree, and this is a two-value check (see+// the server suite import budget in `importScoping.test.js`).+describe('shipped image-gen model pins stay in the seeded provider catalog', () => {+ const SEED_PATH = resolve(dirname(fileURLToPath(import.meta.url)), '../../data.reference/providers.json');+ const seeded = JSON.parse(readFileSync(SEED_PATH, 'utf8')).providers || {};+ const modelsFor = (id) => (Array.isArray(seeded[id]?.models) ? seeded[id].models : []);++ it.each([+ ['antigravity-cli', AGY_IMAGEGEN_DEFAULT_MODEL],+ ['codex', CODEX_IMAGEGEN_DEFAULT_MODEL],+ ])('%s still serves the pin %s', (providerId, pin) => {+ const models = modelsFor(providerId);+ // Guards the lookup itself: a renamed provider id would otherwise make+ // every assertion below pass against an empty list.+ expect(models.length, `no seeded models for ${providerId}`).toBeGreaterThan(0);+ expect(+ models,+ `${pin} is no longer in the shipped ${providerId} catalog — re-point the pin in imageGenCapabilities.js to a tier the vendor still serves.`,+ ).toContain(pin);+ });++ // Stronger than "the pin exists": the agy pin is the id the render-time heal+ // would choose anyway, so the constant is a cached answer to the rule rather+ // than a second, hand-maintained opinion that can quietly disagree with it.+ it('agy pin is the relay tier the runtime heal would pick from the same catalog', () => {+ expect(pickAntigravityRelayModel(modelsFor('antigravity-cli'))).toBe(AGY_IMAGEGEN_DEFAULT_MODEL);+ });+});diff --git a/server/lib/importScoping.test.js b/server/lib/importScoping.test.jsindex d4f6dc2aa0..9fb64f8dfa 100644--- a/server/lib/importScoping.test.js+++ b/server/lib/importScoping.test.js@@ -480,7 +480,16 @@ describe('deferred imports stay deferred (#6156)', () => {// db.js, the hook suite reaches the media queue, the prompt/render suites reach// the modules they mock — plus the two pure leaves the lib barrel gains and the// schema composer's decks.js, counted by the suites that load those barrels.-const MAX_STATIC_INSTANTIATIONS = 103918;+// Pinning the shipped image-gen model defaults to the seeded provider catalog+// measures +7, all of it ONE new test file's own closure: imageGenCapabilities.js+// and the generationModes.js leaf behind it, plus providerModels.js and its+// three leaves, reached so the guard can assert the agy pin is the tier+// pickAntigravityRelayModel would choose rather than a second hand-maintained+// opinion. It reads data.reference/providers.json as JSON rather than importing+// the toolkit's own catalog module precisely to avoid dragging that subtree in,+// and no production module gained an edge — so raise by exactly that delta and+// keep the headroom.+const MAX_STATIC_INSTANTIATIONS = 103925;const SKIP_DIRS = new Set(['node_modules', 'coverage', 'dist', 'data']);diff --git a/server/lib/providerModels.js b/server/lib/providerModels.jsindex 919dadb149..25b6952812 100644--- a/server/lib/providerModels.js+++ b/server/lib/providerModels.js@@ -247,6 +247,65 @@ export function antigravityModelEffortLevels(model, models) {return Object.freeze(ANTIGRAVITY_EFFORT_LEVELS.filter(level => list.includes(`${base}-${level}`)));}+/**+ * Is `id` a model the install's agy catalog still lists?+ *+ * Compared on BASE ids: once `--effort` carries the tier, `gemini-3.6-flash`+ * and `gemini-3.6-flash-low` are the same `--model` value, and a tier the base+ * does not offer is clamped by `antigravityModelEffortLevels` rather than being+ * a different model.+ *+ * An EMPTY catalog answers `true`. "We have no catalog" must never read as "the+ * model is gone" — the list is empty on a fresh install, when the provider+ * service isn't initialized, and whenever the `agy models` probe failed — and a+ * false negative there would swap out a model that works.+ *+ * @param {string} id - base or suffixed model id (a blank one reads as unlisted;+ * callers ask this about a pin they already hold)+ * @param {unknown[]|null|undefined} models - the provider's model catalog+ * @returns {boolean}+ */+export function antigravityCatalogListsModel(id, models) {+ const bases = antigravityBaseModels((Array.isArray(models) ? models : []).filter(m => typeof m === 'string'));+ return !bases.length || bases.includes(splitAntigravityModel(id).base);+}++/**+ * The cheapest catalog entry that can drive an unattended agy relay — the tier+ * to pick on the user's behalf when an agent is needed only to issue one tool+ * call and does no creative work of its own. Today's caller is image gen's+ * shipped pin, `AGY_IMAGEGEN_DEFAULT_MODEL`, whose comment carries the whole+ * rationale and the incident that made a frozen id untenable.+ *+ * Re-derives that choice from whatever the catalog currently holds, in agy's+ * own listed order (newest first):+ *+ * 1. a flash model at the weakest effort tier — cheapest, and empirically+ * enough to relay a tool call;+ * 2. any model at that tier, when no flash model is listed at all;+ * 3. any flash model, when the catalog exposes no effort suffixes;+ * 4. `null` — nothing cheap is listed, so the caller keeps what it had rather+ * than escalating onto a reasoning-heavy tier (`claude-opus-4-6-thinking`)+ * behind the user's back.+ *+ * The tier is read off `ANTIGRAVITY_EFFORT_LEVELS` rather than spelled `low`,+ * so a renamed ladder moves this with it. "flash" stays a literal: it is+ * Google's own family name, not something PortOS derives.+ *+ * @param {unknown[]|null|undefined} models - the provider's model catalog+ * @returns {string|null}+ */+export function pickAntigravityRelayModel(models) {+ const cheapest = ANTIGRAVITY_EFFORT_LEVELS[0];+ const tiers = filterSelectableModels((Array.isArray(models) ? models : []).filter(m => typeof m === 'string'))+ .map(id => ({ id, ...splitAntigravityModel(id) }));+ const pick = (match) => tiers.find(match)?.id;+ return pick(m => m.effort === cheapest && m.base.includes('flash'))+ || pick(m => m.effort === cheapest)+ || pick(m => m.base.includes('flash'))+ || null;+}+/*** True when a provider is codex-flavored — the shipped `codex`/`codex-tui`* provider ids or any provider whose launch command basename is `codex`diff --git a/server/lib/providerModels.test.js b/server/lib/providerModels.test.jsindex 71da27f0f1..9988792fb1 100644--- a/server/lib/providerModels.test.js+++ b/server/lib/providerModels.test.js@@ -49,7 +49,9 @@ import {isKimiProvider,splitAntigravityModel,antigravityBaseModels,+ antigravityCatalogListsModel,antigravityModelEffortLevels,+ pickAntigravityRelayModel,resolveInjectedTuiModel} from './providerModels.js';import { readFileSync } from 'fs';@@ -389,6 +391,59 @@ describe('providerModels', () => {});});+ // The catalog moves under the pins: migration 335 dropped the whole+ // gemini-3.5 tier, and every unpinned agy image render then failed with+ // "--effort is not supported for model gemini-3.5-flash". These two answer+ // "is this pin still served?" and "what do we fall back to?".+ describe('antigravityCatalogListsModel', () => {+ it('accepts a listed id, and a base whose suffixed variants are listed', () => {+ expect(antigravityCatalogListsModel('gemini-3.6-flash-low', AGY_CATALOG)).toBe(true);+ expect(antigravityCatalogListsModel('claude-sonnet-4-6', AGY_CATALOG)).toBe(true);+ // --model takes the base; the suffix only decides --effort.+ expect(antigravityCatalogListsModel('gemini-3.6-flash', AGY_CATALOG)).toBe(true);+ // A tier the base lacks is still the same MODEL — antigravityModelEffortLevels+ // clamps it downstream, so this is not the "retired id" case.+ expect(antigravityCatalogListsModel('gemini-3.1-pro-medium', AGY_CATALOG)).toBe(true);+ });++ it('reports a retired id as unlisted', () => {+ expect(antigravityCatalogListsModel('gemini-3.5-flash-low', AGY_CATALOG)).toBe(false);+ });++ // "No catalog" must never read as "the model is gone": the list is empty on+ // a fresh install, before the first refresh, and when the probe failed.+ it('treats an absent or empty catalog as knowing everything', () => {+ expect(antigravityCatalogListsModel('gemini-3.5-flash-low', [])).toBe(true);+ expect(antigravityCatalogListsModel('gemini-3.5-flash-low', null)).toBe(true);+ });+ });++ describe('pickAntigravityRelayModel', () => {+ it('prefers a flash model at the weakest tier, in the order agy listed them', () => {+ expect(pickAntigravityRelayModel(AGY_CATALOG)).toBe('gemini-3.6-flash-low');+ expect(pickAntigravityRelayModel([+ ANTIGRAVITY_CONFIGURED_DEFAULT,+ 'gemini-3.8-flash-high',+ 'gemini-3.8-flash-low',+ 'gemini-3.6-flash-low',+ ])).toBe('gemini-3.8-flash-low');+ });++ it('falls back to any weakest tier, then to any flash model', () => {+ expect(pickAntigravityRelayModel(['gemini-3.1-pro-high', 'gemini-3.1-pro-low'])).toBe('gemini-3.1-pro-low');+ expect(pickAntigravityRelayModel(['claude-sonnet-4-6', 'gemini-flash-experimental'])).toBe('gemini-flash-experimental');+ });++ // Nothing cheap listed → keep what the caller had rather than escalating+ // onto a reasoning-heavy tier behind the user's back. The sentinel is never+ // a relay candidate: it means "send no --model at all".+ it('returns null rather than escalating onto a reasoning tier', () => {+ expect(pickAntigravityRelayModel(['claude-opus-4-6-thinking', 'claude-sonnet-4-6'])).toBe(null);+ expect(pickAntigravityRelayModel([ANTIGRAVITY_CONFIGURED_DEFAULT])).toBe(null);+ expect(pickAntigravityRelayModel(null)).toBe(null);+ });+ });+describe('isCodexProvider', () => {it('matches shipped ids and codex command basenames', () => {expect(isCodexProvider({ id: 'codex' })).toBe(true);diff --git a/server/routes/imageGen.test.js b/server/routes/imageGen.test.jsindex 38e91c7038..63bf8676ce 100644--- a/server/routes/imageGen.test.js+++ b/server/routes/imageGen.test.js@@ -200,6 +200,10 @@ import * as imageGen from '../services/imageGen/index.js';import * as characterService from '../services/character.js';import * as mediaJobQueue from '../services/mediaJobQueue/index.js';import { getSettings } from '../services/settings.js';+// Asserted against the CONSTANT, never a literal copy of it: the shipped agy+// pin has to be re-pointed whenever Google retires an id, and a hard-coded+// expectation here turns that routine bump into a false failure.+import { AGY_IMAGEGEN_DEFAULT_MODEL } from '../lib/imageGenCapabilities.js';import { findOrCreateUniverseCollection } from '../services/mediaCollections.js';import { prepareRemoteMediaJob } from '../services/federatedMedia/remoteSubmission.js';@@ -902,8 +906,8 @@ describe('Image Gen Routes', () => {.send({ prompt: 'a lighthouse' });expect(response.status).toBe(200);- expect(response.body.model).toBe('gemini-3.5-flash-low');- expect(mediaJobQueue.enqueueJob.mock.calls.at(-1)[0].params.model).toBe('gemini-3.5-flash-low');+ expect(response.body.model).toBe(AGY_IMAGEGEN_DEFAULT_MODEL);+ expect(mediaJobQueue.enqueueJob.mock.calls.at(-1)[0].params.model).toBe(AGY_IMAGEGEN_DEFAULT_MODEL);});// No getSettings mock here on purpose: Zod rejects before the route everdiff --git a/server/services/imageGen/agy.js b/server/services/imageGen/agy.jsindex 6d1f426ecf..478140b6fc 100644--- a/server/services/imageGen/agy.js+++ b/server/services/imageGen/agy.js@@ -18,11 +18,17 @@ import { isAbsolute, join, resolve as pathResolve, sep } from 'path';import { tmpdir } from 'os';import sharp from 'sharp';import {+ ANTIGRAVITY_CLI_ID,ensureAntigravityPrintArgs,isAntigravityModelId,parseAntigravityModelList,prepareAntigravityPrompt,} from '../../lib/antigravity.js';+import {+ antigravityCatalogListsModel,+ pickAntigravityRelayModel,+ splitAntigravityModel,+} from '../../lib/providerModels.js';import { bufferedSpawn, killProcessTree, prepareCliSpawn } from '../../lib/bufferedSpawn.js';import { atomicWrite, copyFileGuarded, detectImageFormat, ensureDir, PATHS, rmGuarded, unlinkGuarded } from '../../lib/fileUtils.js';import { ServerError } from '../../lib/errorHandler.js';@@ -204,9 +210,57 @@ ${noFabricationClause(AGY_TOOL)}Do not create any other files, do not modify any code or workspace content, and do not run unrelated tools. When the file is written, you are done.`;}+/**+ * The agy session model + catalog this render should drive.+ *+ * Two things want the catalog, and only a model carrying a baked effort tier+ * can need either — so an id with no tier (and a render with no pin at all)+ * skips the read. The shipped default does carry one, so a default-config+ * render always pays it; that is one cached provider-record read against a+ * multi-second CLI spawn.+ *+ * - agy validates the (model, effort) PAIR and rejects a tier the base does+ * not offer ("gemini-3.1-pro has no 'medium' effort"), so+ * `ensureAntigravityPrintArgs` has to see `models` to clamp the ladder down+ * to the tiers that base really has. Without it every suffixed id resolves+ * against the full low/medium/high ladder and can emit an unsupported pair.+ * Image gen was the last agy spawn site not passing the catalog through.+ * - a SHIPPED default the vendor has retired is ours to re-point — see+ * `AGY_IMAGEGEN_DEFAULT_MODEL` for the incident. `shippedDefault` is the+ * provenance flag `cloudProviderConfig` sets, NOT a comparison against the+ * constant: a user who types today's shipped id into Settings still owns+ * that pin, and substituting it would hide agy's own "unknown model" error+ * behind a silently different render. The re-point lands on the job's+ * sidecar and returned record, which is what regen and provenance read.+ *+ * The catalog comes from the install's provider record (cache-fronted by the+ * provider service), NOT from an `agy models` spawn: the render path must not+ * pay a second child process, and a probe failure would stall it behind a+ * timeout. The deferred import keeps `services/providers.js` and the toolkit+ * subtree behind it out of every image-gen suite closure (server suite import+ * budget, `lib/importScoping.test.js`); `.catch` covers the uninitialized+ * toolkit, and no catalog means "leave the caller's model alone".+ */+async function resolveAgyDriverModel(model, shippedDefault) {+ if (!model || !splitAntigravityModel(model).effort) return { model: model || null, models: null };+ const models = await import('../providers.js')+ .then(({ getProviderById }) => getProviderById(ANTIGRAVITY_CLI_ID))+ .then((provider) => provider?.models)+ .catch(() => null);+ if (shippedDefault && !antigravityCatalogListsModel(model, models)) {+ const replacement = pickAntigravityRelayModel(models);+ if (replacement) {+ console.log(`🔀 agy default model ${model} is no longer listed — driving with ${replacement}`);+ return { model: replacement, models };+ }+ }+ return { model, models };+}+export async function generateImage({agyPath,model,+ modelIsShippedDefault = false,prompt = '',width,height,@@ -248,7 +302,11 @@ export async function generateImage({const fullPrompt = buildAgyPrompt({prompt, negativePrompt, width, height, stagingPath, inputImages, initImageStrength,});- const baseArgs = ensureAntigravityPrintArgs([], { model });+ // `driverModel` is what agy actually runs on — a retired shipped default is+ // re-pointed here, so every record below reports the model that rendered+ // rather than the one the caller asked for. See resolveAgyDriverModel.+ const { model: driverModel, models } = await resolveAgyDriverModel(model, modelIsShippedDefault);+ const baseArgs = ensureAntigravityPrintArgs([], { model: driverModel, models });const { args } = prepareAntigravityPrompt(baseArgs, fullPrompt);const bin = agyPath || DEFAULT_BIN;const meta = {@@ -259,7 +317,7 @@ export async function generateImage({height: height ? Number(height) : null,filename,mode: IMAGE_GEN_MODE.AGY,- model: model || null,+ model: driverModel,// The agent/session model above drives the CLI; the image itself always// renders on Antigravity's fixed server-side backend — record it so// provenance names the model that actually produced the pixels (#3231).@@ -299,7 +357,7 @@ export async function generateImage({path: `/data/images/${filename}`,generationId: jobId,mode: IMAGE_GEN_MODE.AGY,- model: model || null,+ model: driverModel,status: 'running',};}diff --git a/server/services/imageGen/agy.test.js b/server/services/imageGen/agy.test.jsindex e116dd841d..885817999c 100644--- a/server/services/imageGen/agy.test.js+++ b/server/services/imageGen/agy.test.js@@ -30,6 +30,15 @@ vi.mock('../../lib/childProcess.js', async (importOriginal) => {};});+// The install's agy model catalog, which generateImage reads (through a+// deferred import of services/providers.js) to clamp the effort ladder and to+// re-point a rotated-out shipped default. Empty = "no catalog", the shape a+// fresh install / uninitialized toolkit produces.+const catalog = vi.hoisted(() => ({ models: [] }));+vi.mock('../providers.js', () => ({+ getProviderById: async (id) => (id === 'antigravity-cli' ? { id, models: catalog.models } : null),+}));+const TEST_ROOT = join(tmpdir(), `portos-agy-test-${process.pid}-${Date.now()}`);const FAKE_IMAGES_DIR = join(TEST_ROOT, 'data-images');vi.mock('../../lib/fileUtils.js', async () => {@@ -42,6 +51,7 @@ vi.mock('../../lib/fileUtils.js', async () => {});const agy = await import('./agy.js');+const { AGY_IMAGEGEN_DEFAULT_MODEL } = await import('../../lib/imageGenCapabilities.js');const { imageGenEvents } = await import('../imageGenEvents.js');const flush = () => new Promise((resolve) => setImmediate(resolve));const stagingPathFor = (jobId) => join(tmpdir(), `portos-agy-${jobId}`, 'output.png');@@ -53,6 +63,7 @@ const closeChild = async (index = 0, code = 1) => {};beforeEach(async () => {+ catalog.models = [];spawnCalls.length = 0;imageGenEvents.removeAllListeners();agy._internals.setHarvestTimeoutForTests(10);@@ -176,6 +187,67 @@ describe('agy image provider', () => {expect(spawnCalls).toHaveLength(0);});+ // A catalog can outrun the install's PortOS version, retiring the shipped pin+ // under it (see AGY_IMAGEGEN_DEFAULT_MODEL for the incident). The default is+ // PortOS's own choice, so it re-points to the cheapest tier still listed.+ it('re-points the shipped default when the catalog no longer lists it', async () => {+ catalog.models = ['gemini-4.2-flash-high', 'gemini-4.2-flash-low', 'claude-sonnet-4-6'];+ const job = await agy.generateImage({+ prompt: 'a fox',+ model: AGY_IMAGEGEN_DEFAULT_MODEL,+ modelIsShippedDefault: true,+ });++ expect(job.model).toBe('gemini-4.2-flash-low');+ const { args } = spawnCalls[0];+ expect(args).toEqual(expect.arrayContaining(['--model', 'gemini-4.2-flash', '--effort', 'low']));+ expect(args).not.toContain(AGY_IMAGEGEN_DEFAULT_MODEL);+ await closeChild();+ });++ // A pin the USER typed is a deliberate choice: substituting it would render+ // something else under agy's name and bury agy's own "unknown model" error.+ // It rides through verbatim — with no --effort, since the catalog knows no+ // tiers for it and agy validates the PAIR.+ it('never substitutes a user-pinned model the catalog does not list', async () => {+ catalog.models = ['gemini-4.2-flash-low', 'claude-sonnet-4-6'];+ const job = await agy.generateImage({ prompt: 'a fox', model: 'private-build-low' });++ expect(job.model).toBe('private-build-low');+ const { args } = spawnCalls[0];+ expect(args).toEqual(expect.arrayContaining(['--model', 'private-build-low']));+ expect(args).not.toContain('--effort');+ await closeChild();+ });++ // The gate is PROVENANCE, not string equality: the same id is PortOS's to+ // re-point when it inherited it, and the user's to keep when they typed it.+ // resolveCloudProviderConfig is the only layer that still knows which.+ it('leaves the shipped id alone when the user pinned it themselves', async () => {+ catalog.models = ['gemini-4.2-flash-low'];+ const job = await agy.generateImage({+ prompt: 'a fox',+ model: AGY_IMAGEGEN_DEFAULT_MODEL,+ modelIsShippedDefault: false,+ });++ expect(job.model).toBe(AGY_IMAGEGEN_DEFAULT_MODEL);+ expect(spawnCalls[0].args).not.toContain('gemini-4.2-flash');+ await closeChild();+ });++ // agy rejects the PAIR, not the model: "gemini-3.1-pro has no 'medium'+ // effort (available: low, high)". The catalog is what narrows the ladder.+ it('clamps a baked effort tier the chosen base does not offer', async () => {+ catalog.models = ['gemini-3.1-pro-high', 'gemini-3.1-pro-low'];+ await agy.generateImage({ prompt: 'a fox', model: 'gemini-3.1-pro-medium' });++ const { args } = spawnCalls[0];+ expect(args).toEqual(expect.arrayContaining(['--model', 'gemini-3.1-pro', '--effort', 'low']));+ expect(args).not.toContain('medium');+ await closeChild();+ });+it('rejects invalid custom model ids', async () => {await expect(agy.generateImage({prompt: 'a fox',diff --git a/server/services/imageGen/cloudProviderConfig.js b/server/services/imageGen/cloudProviderConfig.jsindex 6020e825b1..44f4cd994c 100644--- a/server/services/imageGen/cloudProviderConfig.js+++ b/server/services/imageGen/cloudProviderConfig.js@@ -96,6 +96,13 @@ export const CLOUD_PROVIDER_SPECS = Object.freeze({params: (a, override) => ({agyPath: a.agyPath,model: override || a.model || AGY_IMAGEGEN_DEFAULT_MODEL,+ // Provenance, which the resolved `model` above erases: this is the only+ // place that still knows whether the id is PortOS's own shipped pin or+ // something a human chose. The agy provider re-points a shipped pin that+ // the vendor has retired from its catalog, and must never do that to a+ // user's — an id typed into Settings (or sent as a per-render override)+ // is a deliberate choice, even when it happens to equal the shipped one.+ modelIsShippedDefault: !override && !a.model,}),}),});diff --git a/server/services/imageGen/cloudProviderConfig.test.js b/server/services/imageGen/cloudProviderConfig.test.jsindex 3ddfc92668..1944b62e66 100644--- a/server/services/imageGen/cloudProviderConfig.test.js+++ b/server/services/imageGen/cloudProviderConfig.test.js@@ -71,6 +71,7 @@ describe('resolveCloudProviderConfig', () => {mode: IMAGE_GEN_MODE.AGY,agyPath: '/bin/agy',model: 'gemini-image',+ modelIsShippedDefault: false,});const fallback = resolveCloudProviderConfig(@@ -82,6 +83,9 @@ describe('resolveCloudProviderConfig', () => {// a single generate_image relay (#3231).expect(fallback.modelId).toBe(AGY_IMAGEGEN_DEFAULT_MODEL);expect(fallback.providerParams.model).toBe(AGY_IMAGEGEN_DEFAULT_MODEL);+ // Provenance for the agy provider's retired-pin re-point: only an id+ // PortOS chose may be swapped out from under the render.+ expect(fallback.providerParams.modelIsShippedDefault).toBe(true);});it('lets a per-render model override win over the saved default', () => {@@ -96,6 +100,7 @@ describe('resolveCloudProviderConfig', () => {mode: IMAGE_GEN_MODE.AGY,agyPath: '/bin/agy',model: 'gemini-3.6-flash-high',+ modelIsShippedDefault: false,});const codex = resolveCloudProviderConfig(