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

stop rejecting a pr-reviewer stage's local model pin against the provider's cached catalog

[._.]/ Adam Eivy7f391fea3164
diff --git a/client/src/components/cos/tabs/schedule/PipelineStageConfig.jsx b/client/src/components/cos/tabs/schedule/PipelineStageConfig.jsx
index 378b38232e..5d55669e4f 100644
--- a/client/src/components/cos/tabs/schedule/PipelineStageConfig.jsx
+++ b/client/src/components/cos/tabs/schedule/PipelineStageConfig.jsx
@@ -57,8 +57,12 @@ const actionsStageNote = (eligibleProviders) => {
export default function PipelineStageConfig({ taskType, config, providers, providersLoaded = true, onUpdate, updating, setUpdating }) {
const stages = pipelineStages(config);
const needsSecurityModelPolicy = taskType === 'pr-reviewer';
+ // Every public-review stage — not just the tool-free gate — resolves a local
+ // provider's models from the daemon, so the fetch follows the postures rather
+ // than the task type.
+ const hasPublicReviewStage = stages.some((stage) => stagePublicReviewPosture(stage));
const { ollama, lmstudio, capabilitiesByBackend, loading: localModelsLoading } = useLocalModels({
- enabled: needsSecurityModelPolicy,
+ enabled: needsSecurityModelPolicy || hasPublicReviewStage,
});
// One policy per posture. The provider half is server-derived; the model half
// adds the authoritative no-tool capability check only for a local runtime,
@@ -160,10 +164,13 @@ export default function PipelineStageConfig({ taskType, config, providers, provi
const localBackend = localBackendForProvider(stageProvider);
const localModelIds = localBackend === 'ollama' ? ollama : localBackend === 'lmstudio' ? lmstudio : [];
// A LOCAL provider's installed-model list is the source of truth (its
- // stored catalog is stale, and only an installed model has a probeable
- // capability report). Every other provider uses its own catalog, so a
- // cloud CLI stage can pick any model that provider offers.
- const stageModels = isNoToolStage && localBackend
+ // stored catalog is a cached snapshot, and only an installed model has
+ // a probeable capability report). That holds for the sandboxed actions
+ // stage as much as the tool-free gate — offering the stale catalog
+ // there let a stage be pinned to a model the daemon no longer serves,
+ // and hid one that had just been pulled. Every other provider uses its
+ // own catalog, so a cloud CLI stage can pick any model it offers.
+ const stageModels = posture && localBackend
? localModelIds.map(id => ({
id,
name: id,
diff --git a/client/src/components/cos/tabs/schedule/PipelineStageConfig.test.jsx b/client/src/components/cos/tabs/schedule/PipelineStageConfig.test.jsx
index 8001d2612a..14d337aa53 100644
--- a/client/src/components/cos/tabs/schedule/PipelineStageConfig.test.jsx
+++ b/client/src/components/cos/tabs/schedule/PipelineStageConfig.test.jsx
@@ -223,4 +223,41 @@ describe('PipelineStageConfig — posture-driven eligibility', () => {
expect(note.textContent).toContain("OS-sandboxed by the vendor's own recipe: Codex TUI.");
expect(note.textContent).toContain('isolated by the disposable worktree only: OpenCode TUI.');
});
+
+ // A local runtime's daemon is the authority on what it serves; the provider
+ // record's `models` array is a cached snapshot. The tool-free gate already
+ // read the daemon, but the sandboxed actions stage read the snapshot — so a
+ // stage on a local provider could only be pinned to models that had since
+ // been removed, and never to one just pulled.
+ it('offers the installed local models for a local-backed ACTIONS stage', () => {
+ const localProvider = {
+ id: 'opencode-ollama-tui',
+ name: 'OpenCode Ollama TUI',
+ type: 'tui',
+ command: 'opencode',
+ models: ['stale-cached-model'],
+ publicReviewPostures: ['no-tool', 'sandboxed-actions'],
+ publicReviewEnforcedPostures: ['no-tool'],
+ };
+ render(
+ <MemoryRouter>
+ <PipelineStageConfig
+ taskType="pr-reviewer"
+ config={{ taskMetadata: { pipeline: { stages: [
+ profiledStages[0],
+ profiledStages[1],
+ { ...profiledStages[2], providerId: 'opencode-ollama-tui', model: 'tool-model' },
+ ] } } }}
+ providers={[localProvider]}
+ onUpdate={vi.fn().mockResolvedValue(undefined)}
+ updating={false}
+ setUpdating={() => {}}
+ />
+ </MemoryRouter>,
+ );
+
+ const modelSelects = screen.getAllByLabelText('Model');
+ // The daemon's installed models, NOT the record's `stale-cached-model`.
+ expect([...modelSelects[1].options].map((o) => o.value)).toEqual(['', 'safe-model', 'tool-model']);
+ });
});
diff --git a/client/src/utils/providers.js b/client/src/utils/providers.js
index ec966195cc..5c0caf1400 100644
--- a/client/src/utils/providers.js
+++ b/client/src/utils/providers.js
@@ -897,6 +897,13 @@ export const visionLocalModelFilter = (id, provider, visionIdsByProvider = null)
* claimed as local. This one only labels UI, so it stays a cheap regex; if it
* ever gates an action, take the server's rules with it.
*
+ * The pr-reviewer stage pickers (`PipelineStageConfig.jsx`) are downstream of
+ * this, the sandboxed actions stage included — but they only choose which model
+ * list to SHOW. The pin a stage saves is re-validated at spawn time by
+ * `modelPinIsOffered` (server/lib/localProviderRuntime.js), so a
+ * misclassification here degrades to a confusing dropdown, never to a model the
+ * provider was not allowed to run.
+ *
* @param {{id?:string,endpoint?:string,name?:string}} provider
* @returns {'ollama'|'lmstudio'|null}
*/
diff --git a/server/lib/README.md b/server/lib/README.md
index 14db2bdee9..313ac39bbc 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -180,7 +180,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `providerTranscriptUsage.js` | Parsers for the session files the coding CLIs write to disk (0 tokens to read) — `parseClaudeTranscript` (`~/.claude/projects/<cwd-slug>/*.jsonl`), `parseCodexRollout` (`~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl`), `parseGrokTurns`/`parseGrokChatHistory`/`decodeGrokSessionDir` (`~/.grok/sessions/<encodeURIComponent(cwd)>/<id>/`), `parseAgyTranscript`/`parseAgyHistory` (`~/.gemini/antigravity-cli/`), `claudeProjectSlug`, `totalTranscriptTokens`. Each de-duplicates a format hazard that otherwise inflates counts badly: Claude repeats one response across several lines sharing a `message.id`, Codex's `total_token_usage` is cumulative and repeated, grok's `turn_completed.usage` has shipped in both per-prompt and cumulative shapes (detected and delta'd, never summed raw) while its `_meta.totalTokens` is context occupancy and never billed. Antigravity writes no token fields at all, so its parser returns chars for the caller to estimate from. Each parser returns per-model buckets (`byModel`) plus the message keys it counted (`countedKeys`), and accepts an `exclude` set — that is what stops two overlapping PortOS runs from both billing the same messages. Tolerant of truncated (mid-write) files; consumed by `services/usageReconciler.js`. |
| `opencodeCatalogCache.js` | Primes the on-disk catalog `opencode models` prints from — `primeOpencodeCatalogCache()` fetches OpenCode's `api.json` with Node's fetch and atomically writes `$XDG_CACHE_HOME/opencode/models.json` (`~/.cache` when unset). OpenCode refreshes that file from a forked task whose failures it swallows (`opencode models --refresh` still prints `Models cache refreshed`) and its HTTP client has no Happy Eyeballs, so a host advertising an unreachable IPv6 default route freezes the catalog indefinitely while other machines on the same account list newer models. Refuses to fetch or write when `OPENCODE_MODELS_PATH` / a custom `OPENCODE_MODELS_URL` / `OPENCODE_DISABLE_MODELS_FETCH` means PortOS cannot be sure which file OpenCode reads, when the file is under five minutes old, or when the body did not parse as a catalog — a stale list beats an empty picker. Never throws; the caller probes either way. |
| `opencodeConfig.js` | OpenCode config builder — `buildOpencodeEnvVars(provider, model)` builds dynamic `OPENCODE_CONFIG_CONTENT` declaring model ids under the namespace the provider's marker selects: a local runtime (`ollama` / `mtplx` / `llama` / `vllm` / `sglang`, bare ids) or a hosted gateway from `providerGateways.js` (`vendor/model` ids kept whole). Fixes --model rejection. Also attaches the key for a key-bearing namespace, and pins `small_model` to the run model for a gateway so OpenCode's own side calls (titles, summarization) can't land on its built-in default — a billed model the operator never chose. Under a `no-tool` public-review profile it also applies `hardenOpencodeConfigForNoTool` — root `permission: deny`, an emptied tool map on every agent, `tool_call: false` on every declared model, and no MCP/plugins/share/autoupdate — which IS OpenCode's enforced tool-free recipe, since it ships no read-only argv flag (`providerVendors.js` pairs it with `run --agent` + `OPENCODE_PUBLIC_REVIEW_AGENT`). The harden step also copies `agent.build`'s generation settings onto that agent, so the stage's configured thinking effort reaches the model that actually runs. |
-| `localProviderRuntime.js` | Which LOCAL daemon a provider talks to, and where — `LOCAL_RUNTIMES` (llama.cpp / Ollama / LM Studio / MTPLX / vLLM: label, binary, canonical base URL read from `opencodeConfig.js` rather than re-typed, manage/docs links, model-download hint), `localBackendForProvider` + `localEndpointPort` + `isLocalInstanceHost` (moved here from `services/localModelHealing.js`, which re-exports them, so the healing path and the readiness checklist classify a provider identically — loopback/bind-all only, so a LAN/Tailscale peer on port 11434 is NOT claimed as a local daemon), `localRuntimeKind(provider)` (the `*Backed` markers first, then that classifier; `orcarouter` excluded as a remote API), `localRuntimeForProvider(provider)` → the row with the endpoint the provider ITSELF configures (`OPENCODE_CONFIG_CONTENT`'s `baseURL`, `ANTHROPIC_BASE_URL`, or `endpoint`), then the `OLLAMA_URL`/`OLLAMA_HOST`/`LM_STUDIO_URL` override the backend managers read, then the canonical default — and `null` when that resolved endpoint fails `isLocalInstanceEndpoint` (an API provider on another machine has no local daemon to check, whatever its name says) — plus `normalizeOpenAiBaseUrl`. Pure; the probing half is `services/providerReadiness.js`. Optional `setupStateDetail` overrides `providerReadiness`'s per-state prose for a runtime whose local setup is not a model cache (vLLM's is a compose project); `standbyWhenStopped` marks an installed runtime such as llama.cpp whose stopped state is intentional standby rather than incomplete setup. |
+| `localProviderRuntime.js` | Which LOCAL daemon a provider talks to, and where — `LOCAL_RUNTIMES` (llama.cpp / Ollama / LM Studio / MTPLX / vLLM: label, binary, canonical base URL read from `opencodeConfig.js` rather than re-typed, manage/docs links, model-download hint), `localBackendForProvider` + `localEndpointPort` + `isLocalInstanceHost` (moved here from `services/localModelHealing.js`, which re-exports them, so the healing path and the readiness checklist classify a provider identically — loopback/bind-all only, so a LAN/Tailscale peer on port 11434 is NOT claimed as a local daemon), `localRuntimeKind(provider)` (the `*Backed` markers first, then that classifier; `orcarouter` excluded as a remote API), `modelPinIsOffered(provider, model)` (the ONE rule for validating a stored model pin against a provider record: an empty `models` array and a local daemon's cached snapshot are both pass-throughs, so a freshly pulled Ollama model is never rejected as "not offered"), `localRuntimeForProvider(provider)` → the row with the endpoint the provider ITSELF configures (`OPENCODE_CONFIG_CONTENT`'s `baseURL`, `ANTHROPIC_BASE_URL`, or `endpoint`), then the `OLLAMA_URL`/`OLLAMA_HOST`/`LM_STUDIO_URL` override the backend managers read, then the canonical default — and `null` when that resolved endpoint fails `isLocalInstanceEndpoint` (an API provider on another machine has no local daemon to check, whatever its name says) — plus `normalizeOpenAiBaseUrl`. Pure; the probing half is `services/providerReadiness.js`. Optional `setupStateDetail` overrides `providerReadiness`'s per-state prose for a runtime whose local setup is not a model cache (vLLM's is a compose project); `standbyWhenStopped` marks an installed runtime such as llama.cpp whose stopped state is intentional standby rather than incomplete setup. |
| `managedDaemon.js` | Shared mechanism for the local daemons PortOS runs as optional PM2 processes (`services/llamaServerManager.js` → `portos-llama-server`, `services/mtplxServerManager.js` → `portos-mtplx`, `services/slotstreamServerManager.js` → `portos-slotstream`). Owns their PM2 process names — `LLAMA_APP`, `MTPLX_APP`, `SLOTSTREAM_APP`, and the `isModelServerProcess(name)` predicate over them — so a caller like the CoS health monitor can recognize a model server without importing a manager; the managers re-export those names. `createDaemonWatcher({...})` supplies the common PM2 launch-line re-adoption, endpoint probe, status skeleton, bounded log view, and port-release wait while managers retain daemon-specific parsing and lifecycle policy. `createDaemonLogBuffer({maxLines?})` is the bounded timestamped ring buffer of what PortOS logged around a launch, plus `withPm2Logs(output)` → that buffer followed by anything `pm2 logs` has which it doesn't already hold, deduped and re-capped (PM2's lines are a VIEW, never folded into the buffer — PM2 owns them and re-reads them every status call). `pm2ArgValue(args, flag)` reads one value back out of a PM2 process's recorded argv so a manager can recover a still-online daemon's launch config after a PortOS restart; `null` means the flag was absent, which a relaunch must leave off rather than defaulting. Also the shared **idle reaper**, for a daemon that cannot release its weights any other way: `registerIdleDaemon({name, getIdleMs, stop})` (seeds `lastUsedAt` to NOW, so a hand-started daemon gets a full window), `markDaemonUsed(name)` — call on real traffic, NEVER on a status poll — `daemonLastUsedAt(name)`, `idleWindowMs(minutes)` (minutes → ms; `0` = never, `null` = not configured, kept distinct), `reapIdleDaemons(now?)` → the names stopped, and `startIdleReaper({intervalMs?})` / `stopIdleReaper()` (ONE interval for all registrants, `unref`'d, idempotent). `mtplxServerManager` and `slotstreamServerManager` register: llama.cpp releases its checkpoint in place via `--sleep-idle-seconds` and must NOT be stopped for it. Deliberately mechanism only — what a launch line means and when a daemon may start is exactly what differs between the two. |
| `mtplxModels.js` | `listMtplxCachedModels({command?})` → `{models, error}` from `mtplx models --json` (walks local directories — pulls no weights, loads no model, but see `mtplxRuntime.js`: on an un-warmed Homebrew wrapper the spawn ITSELF is a several-hundred-megabyte runtime download, so poll callers must gate on `describeMtplxRuntime().ready` first) and `pickMtplxCachedModel(models)` → the repo id to hand `mtplx serve --model`. `models: null` means the cache could not be READ (no binary, command failed, unparseable) and is deliberately distinct from `[]` (read, and empty), because `services/localRuntimeSetup.js` starts MTPLX on its own default in the first case and refuses with the `mtplx pull` command in the second. Exists because `mtplx serve` defaults `--model` to one hard-coded checkpoint and exits 1 before binding when that repo is not cached — even on a host holding a different MTP model that serves fine. Picks only entries MTPLX itself calls complete (`validation.ok !== false`, so a half-finished pull is not served), preferring one with a recorded `mtplx_runtime.json` exactness contract. `describeMtplxCache(cache)` → `{state: 'unknown'\|'empty'\|'partial'\|'ready', model, count, error}` folds both into the one value `services/providerReadiness.js` puts on the checklist and `describeRuntimeSetup` picks a button from — so an empty cache is named up front instead of only inside the failure of a Start that could never work. |
| `mtplxRuntime.js` | `describeMtplxRuntime(binaryPath, {env?})` → `{ready, wrapper, venvPath}` — is MTPLX's own Python runtime on disk, decided by READING the binary rather than running it. Homebrew's `mtplx` is a shell wrapper that lazily bootstraps a version-keyed Python venv (a multi-hundred-megabyte pip install) on its first invocation, and `brew upgrade` re-arms it, so a status poll or an 8s-judged PM2 start is really a package download. This parses the wrapper's own `VENV=` assignment, honours `$MTPLX_BREW_VENV` the way `${MTPLX_BREW_VENV:-…}` does, and tests `<venv>/bin/mtplx` for executability — the wrapper's own `[ ! -x … ]` guard, so the two cannot disagree. Anything unrecognisable (a pip install, a compiled binary, an unparseable script) reports `ready: true, wrapper: false`, i.e. the status quo — never a block over a parse failure. |
diff --git a/server/lib/localProviderRuntime.js b/server/lib/localProviderRuntime.js
index 5aa734ec88..4151c879f5 100644
--- a/server/lib/localProviderRuntime.js
+++ b/server/lib/localProviderRuntime.js
@@ -296,6 +296,35 @@ export function localRuntimeKind(provider) {
return localBackendForProvider(provider);
}
+/**
+ * Whether a provider may be handed `model` — the one rule for validating a
+ * stored model pin against a provider record.
+ *
+ * Two providers are pass-throughs, for opposite reasons:
+ *
+ * - one that enumerates NO models has nothing to validate against, so any id
+ * is its caller's to choose;
+ * - one backed by a LOCAL daemon has a `models` array that is only a cached
+ * snapshot, while the daemon on this machine is the authority. Every model
+ * picker in PortOS deliberately offers what the daemon reports rather than
+ * what the record lists, so judging a local pin against the record rejects
+ * a model that is installed and serving — that is how a pr-reviewer stage
+ * pinned to a freshly pulled Ollama model got "not offered by provider" on
+ * every dispatch.
+ *
+ * Anything else enumerates its own catalog, and a pin outside it reaches the
+ * CLI as a model it cannot serve.
+ *
+ * @param {object|null|undefined} provider
+ * @param {string|null|undefined} model
+ * @returns {boolean}
+ */
+export function modelPinIsOffered(provider, model) {
+ const offered = Array.isArray(provider?.models) ? provider.models : [];
+ if (offered.length === 0 || localRuntimeKind(provider)) return true;
+ return offered.includes(model);
+}
+
/**
* The local runtime a provider needs, with the endpoint PortOS should probe.
*
diff --git a/server/services/agentProviderResolution.js b/server/services/agentProviderResolution.js
index deff86d377..9856ca1792 100644
--- a/server/services/agentProviderResolution.js
+++ b/server/services/agentProviderResolution.js
@@ -17,6 +17,7 @@ import { emitLog } from './cosEvents.js';
import { getActiveProvider, getAllProviders, getProviderById } from './providers.js';
import { isProviderAvailable, getFallbackProvider, getProviderStatus } from './providerStatus.js';
import { selectModelForRole, selectModelForTask } from './agentModelSelection.js';
+import { modelPinIsOffered } from '../lib/localProviderRuntime.js';
import { PRIMARY_ORCHESTRATION_ROLE, roleAssignment } from '../lib/orchestrationProfile.js';
import { publicReviewPostureForTask, resolvePublicReviewProvider } from './publicReviewProviderSelection.js';
@@ -71,22 +72,29 @@ async function resolvePublicReviewAgentProvider(task, posture) {
// and a retired id reaches the CLI as a model it cannot serve, so the stage
// spawns, produces no output, and is retried. The ordinary path guards this
// at its list check; `cliProviderRun.js#resolveCliProviderAndModel` does too.
- const modelSelection = await selectModelForTask(task, provider);
const pinnedModel = task.metadata?.model;
const pinnedForThisProvider = Boolean(pinnedModel) && task.metadata?.provider === provider.id;
- // A provider that enumerates NO models is a pass-through (any id is its
- // caller's to choose), so only a non-empty list can invalidate a pin.
- const offeredModels = Array.isArray(provider.models) ? provider.models : [];
- const pinIsOffered = offeredModels.length === 0 || offeredModels.includes(pinnedModel);
- if (pinnedForThisProvider && !pinIsOffered) {
+ // `modelPinIsOffered` owns which provider records may invalidate a pin at all
+ // — an empty catalog and a local daemon's cached snapshot are both
+ // pass-throughs (see its doc comment).
+ const pinRejected = pinnedForThisProvider && !modelPinIsOffered(provider, pinnedModel);
+ // Strip the rejected pin BEFORE model selection. `selectModelForTask` returns
+ // `metadata.model` verbatim as its highest-priority answer, so leaving it in
+ // place handed the CLI the very id just rejected and the warning below
+ // promised a default the run never used.
+ const modelSelection = await selectModelForTask(
+ pinRejected ? { ...task, metadata: { ...task.metadata, model: null } } : task,
+ provider,
+ );
+ if (pinRejected) {
emitLog('warn', `Public-review stage model "${pinnedModel}" is not offered by provider "${provider.id}" — using its default instead`, {
taskId: task.id,
requestedModel: pinnedModel,
providerId: provider.id,
- validModels: offeredModels,
+ validModels: provider.models,
});
}
- const selectedModel = pinnedForThisProvider && pinIsOffered
+ const selectedModel = pinnedForThisProvider && !pinRejected
? pinnedModel
: (modelSelection.model || provider.defaultModel || null);
emitLog('info', `Public-review stage (${posture}) resolved to provider ${provider.id}${selectedModel ? ` model ${selectedModel}` : ''}`, {
diff --git a/server/services/agentProviderResolution.test.js b/server/services/agentProviderResolution.test.js
index 67de32bf0c..cdb4b80a33 100644
--- a/server/services/agentProviderResolution.test.js
+++ b/server/services/agentProviderResolution.test.js
@@ -401,6 +401,40 @@ describe('resolveAgentProviderAndModel — public-review stages', () => {
.resolves.toMatchObject({ provider: { id: 'grok-cli' }, selectedModel: 'm-default' });
});
+ // The drop above has to survive model selection, which is where it used to
+ // be undone: `selectModelForTask` answers `metadata.model` verbatim as its
+ // highest-priority tier, so a resolution that left the rejected pin on the
+ // task got the same id back and spawned the CLI with it — while logging that
+ // it was "using its default instead". The mock is given the real precedence
+ // here on purpose; the flat `m-default` default cannot observe the bug.
+ it('does not let model selection hand the rejected pin back', async () => {
+ selectModelForTask.mockImplementation(async (task, provider) => (
+ task?.metadata?.model
+ ? { model: task.metadata.model, tier: 'user-specified', reason: 'user-preference' }
+ : { model: provider?.defaultModel || 'm-default', tier: 'medium', reason: 'default' }
+ ));
+ const CURATED = { id: 'grok-cli', type: 'cli', command: 'grok', models: ['grok-4'], defaultModel: 'grok-4' };
+ getAllProviders.mockResolvedValue({ providers: [CURATED], activeProvider: null });
+
+ const r = await resolveAgentProviderAndModel(gateTask({ provider: 'grok-cli', model: 'grok-3-retired' }));
+ expect(r.selectedModel).toBe('grok-4');
+ });
+
+ // A LOCAL runtime's `models` array is a cached snapshot of what the daemon
+ // had; the daemon itself is the authority, and the stage picker offers what
+ // it reports. Judging the pin against the snapshot rejected a model that was
+ // installed and serving — the live pr-reviewer gate logged "not offered by
+ // provider" for a freshly pulled Ollama model on every dispatch.
+ it('honors a model pin on a local-runtime provider whose cached list omits it', async () => {
+ const LOCAL = {
+ id: 'grok-ollama', type: 'cli', command: 'grok', ollamaBacked: true,
+ models: ['qwen3-coder:30b'], defaultModel: 'qwen3-coder:30b',
+ };
+ getAllProviders.mockResolvedValue({ providers: [LOCAL], activeProvider: null });
+ await expect(resolveAgentProviderAndModel(gateTask({ provider: 'grok-ollama', model: 'gemma3:27b' })))
+ .resolves.toMatchObject({ provider: { id: 'grok-ollama' }, selectedModel: 'gemma3:27b' });
+ });
+
// A provider that enumerates no models is a pass-through, so the pin stands.
it('honors a model pin on a provider that enumerates no models', async () => {
getAllProviders.mockResolvedValue({ providers: [GROK], activeProvider: null });