Skip to content

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

fix: preserve Pi provider identity and stored model catalogs (#6350)

[._.]/ Adam Eivyce5c6b306d0f
diff --git a/server/lib/README.md b/server/lib/README.md
index fdad37329c..bf7143300c 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -171,6 +171,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `videoDurationProfiles.js` | Pure pinned duration/frame contracts shared by model-registry upgrades and migrations. LTX-2.5 A2V follows the full uploaded audio, rounds up to its 8n+1 temporal grid, and tops out at 1017 frames under the API's single-pass boundary. |
| `videoReferenceModes.js` | The i2v reference-mode contract (#4874) — what a supplied conditioning image PROMISES. `I2V_REFERENCE_MODES` (`anchor` \| `inspire`) + `I2V_REFERENCE_MODE_OPTIONS` (the label + the promise sentence the UI prints), `I2V_REFERENCE_MODE_RUNTIMES` (only `ltx25` can honor `inspire` — it needs per-image conditioning strength), `INSPIRE_DEFAULT_IMAGE_STRENGTH`, plus `normalizeI2vReferenceMode` / `isDefaultI2vReferenceMode` / `isKnownI2vReferenceMode` / `runtimeSupportsI2vReferenceMode` / `i2vReferenceModeLabel` / `resolveI2vReferenceStrength` and the one rule `i2vReferenceModeViolation({ model, mode, referenceMode, hasFirstImage })` → `{ code, message }` or null. Pure (no `ServerError`) because it is MIRRORED to `client/src/lib/videoReferenceModes.js`; `videoGen/modeContract.js#videoReferenceModeError` wraps it for the route + render boundaries. |
| `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 — `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. |
| `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. |
| `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. |
@@ -552,5 +553,3 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and
| `eidoverseCityLayout.js` | Native halls, rooftop landmark clearance and plinths, curated furniture, visitor chambers, and ordered signal bays for PortOS Commons. |
| `eidoverseCitySurface.js` | Deterministic GLB island scenery, pedestrian paths, gathering terraces, and physical district signs, stored through Eidoverse's content-addressed upload API. |
| `eidoverseIslandLandscape.js` | `appendEidoverseIslandLandscape` appends deterministic coastline, ocean, and distant mountain-island geometry to the Commons asset. |
-
-| `pi.js` | Pi command identity, headless/TUI arguments, and positional prompt delivery. |
diff --git a/server/lib/aiToolkit/internal/modelFetchers.js b/server/lib/aiToolkit/internal/modelFetchers.js
index eb09a93f3c..eed975380d 100644
--- a/server/lib/aiToolkit/internal/modelFetchers.js
+++ b/server/lib/aiToolkit/internal/modelFetchers.js
@@ -55,10 +55,6 @@ const displayName = (provider) => String(provider?.name || '').toLowerCase();
* gemini) exactly as the old chain did.
*/
export const MODEL_FETCHERS = [
- {
- key: 'pi', cliMatch: (p) => isPiCommand(p?.command),
- tuiMatch: (p) => isPiCommand(p?.command), fetch: '_fetchPiModels',
- },
{
key: 'ollama',
// Not a command test: the marker can be `ollamaBacked`, an id, or an
@@ -127,6 +123,10 @@ export const MODEL_FETCHERS = [
tuiMatch: isGatewayBackedProvider,
fetch: '_fetchGatewayModels',
},
+ {
+ key: 'pi', cliMatch: (p) => isPiCommand(p?.command),
+ tuiMatch: (p) => isPiCommand(p?.command), fetch: '_fetchPiModels',
+ },
{
key: 'cursor',
// No `cliNameMatch` on purpose — see the column notes above.
diff --git a/server/lib/aiToolkit/providers.js b/server/lib/aiToolkit/providers.js
index 861e01acbe..d05a567c2d 100644
--- a/server/lib/aiToolkit/providers.js
+++ b/server/lib/aiToolkit/providers.js
@@ -967,6 +967,14 @@ export function createProviderService(config = {}) {
// returning null so `null` keeps exactly ONE meaning out of this function:
// the provider does not exist. That is what lets the route's 404 say
// plainly "Provider not found" instead of guessing at a reason.
+ // Pi reports an unauthenticated install as an empty list. That is useful
+ // for first setup, but a lapsed login must not erase a populated catalog.
+ if (resolveModelFetcher(provider)?.key === 'pi' && Array.isArray(fetched)
+ && fetched.length === 0 && provider.models?.length) {
+ const error = new Error('Pi has no authenticated models. Use pi /login before refreshing the stored catalog.');
+ error.status = 502;
+ throw error;
+ }
const catalog = toModelCatalog(fetched);
if (catalog === null) {
const unsupported = new Error(`Model refresh returned nothing for provider '${provider.id}'`);
@@ -1345,12 +1353,12 @@ export function createProviderService(config = {}) {
const { stdout } = await pending.catch((err) => {
const output = `${err.stdout || ''}\n${err.stderr || ''}`;
if (!err.killed && isEmptyCatalog(output)) return { stdout: output };
- throw new Error(`'${bin} models' failed: ${err?.message || 'could not run the binary'}`);
+ throw new Error(`'${bin} ${listArgs.join(' ')}' failed: ${err?.message || 'could not run the binary'}`);
});
const listed = parse(stdout);
if (listed.length === 0 && !isEmptyCatalog(stdout)) {
- throw new Error(`'${bin} models' returned no model ids`);
+ throw new Error(`'${bin} ${listArgs.join(' ')}' returned no model ids`);
}
return listed;
},
diff --git a/server/lib/aiToolkit/providers.test.js b/server/lib/aiToolkit/providers.test.js
index 9f28001c7e..4338df8e3f 100644
--- a/server/lib/aiToolkit/providers.test.js
+++ b/server/lib/aiToolkit/providers.test.js
@@ -37,6 +37,8 @@ describe('Provider Service', () => {
await expect(providerService.refreshProviderModels(provider.id)).rejects.toThrow('failed');
expect((await providerService.getProviderById(provider.id)).models).toEqual(['example/model-a']);
await emit('No models available. Use /login to authenticate.');
+ await expect(providerService.refreshProviderModels(provider.id)).rejects.toThrow('no authenticated models');
+ expect((await providerService.getProviderById(provider.id)).models).toEqual(['example/model-a']);
expect(await providerService._fetchPiModels({ command })).toEqual([]);
await emit('No models available. Use /login to authenticate.', 1);
expect(await providerService._fetchPiModels({ command })).toEqual([]);
diff --git a/server/lib/pi.test.js b/server/lib/pi.test.js
index 02b2ccd821..e825827535 100644
--- a/server/lib/pi.test.js
+++ b/server/lib/pi.test.js
@@ -1,7 +1,7 @@
import { describe, it, expect } from 'vitest';
import { buildCliArgs, prepareCliPrompt } from './cliProviderArgs.js';
import { isPiCommand, ensurePiHeadlessArgs } from './pi.js';
-import { PROVIDER_VENDORS, publicReviewRecipe, PUBLIC_REVIEW_NO_TOOL_POSTURE, PUBLIC_REVIEW_ACTIONS_POSTURE } from './providerVendors.js';
+import { PROVIDER_VENDORS, inferTuiCommand, publicReviewRecipe, PUBLIC_REVIEW_NO_TOOL_POSTURE, PUBLIC_REVIEW_ACTIONS_POSTURE } from './providerVendors.js';
import { parseHarnessModels } from './harnessOutput.js';
import { reviewerEffortArgs } from './reviewerConfig.js';
@@ -21,6 +21,8 @@ describe('Pi provider boundaries', () => {
expect(ensurePiHeadlessArgs(args, 'example/other', 'high')).toEqual(args);
expect(isPiCommand('/opt/bin/pi.exe')).toBe(true);
expect(isPiCommand('pipeline')).toBe(false);
+ expect(inferTuiCommand('pi-tui')).toBe('pi');
+ expect(inferTuiCommand('example-api-tui')).toBe('claude');
expect(PROVIDER_VENDORS.slice(-2).map(v => v.id)).toEqual(['pi', 'claude']);
});
it('discards unsafe saved arguments in the no-tool posture and refuses action review', () => {
diff --git a/server/lib/providerModels.js b/server/lib/providerModels.js
index 218b4e639c..77eee37617 100644
--- a/server/lib/providerModels.js
+++ b/server/lib/providerModels.js
@@ -439,6 +439,8 @@ export const CODEX_EFFORT_KEY = 'model_reasoning_effort';
// provider args gets a SECOND, injected `--effort <level>` appended. Grok's
// parser accepts the duplicate and takes the last one, so their explicit pin
// would be silently overridden — the exact opposite of the contract below.
+// Pi's --thinking is also a value-taking effort pin; shared stripping keeps
+// per-run overrides consistent when switching providers.
const EFFORT_FLAG_NAMES = Object.freeze(['--effort', '--reasoning-effort', '--thinking']);
/**
diff --git a/server/lib/providerVendors.js b/server/lib/providerVendors.js
index b704936d9c..133a6a9034 100644
--- a/server/lib/providerVendors.js
+++ b/server/lib/providerVendors.js
@@ -554,6 +554,7 @@ const piCliArgs = (args, { model, effort }) => ensurePiHeadlessArgs(args, model,
const PI = {
id: 'pi',
idFragment: 'pi-',
+ matchId: (id) => /^pi(?:-|$)/.test(id),
inferredCommand: PI_COMMAND,
matchCommand: isPiCommand,
tuiArgs: ensurePiTuiArgs,
@@ -825,7 +826,7 @@ export function publicReviewRecipe(provider, posture) {
export function inferTuiCommand(id) {
if (!id) return CLAUDE.inferredCommand;
for (const vendor of PROVIDER_VENDORS) {
- if (vendor.idFragment && id.includes(vendor.idFragment)) return vendor.inferredCommand;
+ if (vendor.matchId ? vendor.matchId(id) : vendor.idFragment && id.includes(vendor.idFragment)) return vendor.inferredCommand;
}
return CLAUDE.inferredCommand;
}