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
feat(writers-room): per-stage LLM picker, surfaced Adapt failures, Codex/Claude-Code CLI support
Adam Eivyd66926233610
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 0476b1129e..9a6f7252b3 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,10 @@## Added+- **Writers Room — Codex / Claude Code CLI support for AI passes, and tail-truncated CLI errors so failures are actually readable.** `callCliProvider` previously branched on `gemini-cli` and treated everything else as "spawn the binary, pipe prompt to stdin" — which Codex and Claude Code reject because they need a subcommand to run non-interactively. Picking Codex as the Adapt LLM exited code 1 with `Error: stdin is not a terminal` because `codex` defaulted to its REPL; Claude Code would have the same gap. Replaced the binary `isGeminiCli` switch with a `buildCliInvocation(provider, model)` dispatcher mirroring `runner.js` / `agentCliSpawning.js`: `codex` → `exec [--model <m>] -`, `claude-code` / `claude-code-bedrock` → `-p - [--model <m>]`, `gemini-cli` → unchanged (`--prompt` arg + `stdio[0] = 'ignore'`), default → spawn binary and pipe prompt to stdin. Also flipped CLI error truncation from `slice(0, 500)` → `slice(-2000)` since the actual failure (e.g. `"The 'gpt-5' model is not supported when using Codex with a ChatGPT account"`) lives at the end of stderr — the head-truncation was clipping the banner and hiding the real cause. Touched: `server/services/writersRoom/evaluator.js`.++- **Writers Room — per-stage provider/model picker in Storyboard settings, and surfaced Adapt failures.** The storyboard's gear-icon settings drawer now exposes an **Adapt LLM** picker with the same Tier-vs-Specific toggle the global Prompt Manager uses (`Tier: default/quick/coding/heavy` or `Specific: <provider> + <model>`). Picking a value PUTs `/api/prompts/writers-room-script` so the same selector works from `/prompts` or any panel that runs the stage. The evaluator's `callAI` now reads `stage.provider` + `stage.model` first (falling back to active provider only when no override is set) and resolves tier names through the provider's `defaultModel`/`lightModel`/`mediumModel`/`heavyModel`, fixing a case where every Writers Room AI pass silently routed through `getActiveProvider()` regardless of stage config. The Storyboard panel also now surfaces failed runs: instead of silently falling back to "No storyboard yet" when the latest Adapt snapshot is `failed`, it shows an error banner with the actual error message, an `Adjust LLM` shortcut into the settings drawer, and a `Re-run Adapt` button. (The 5-minute Gemini-CLI timeout that prompted this — `CLI AI call timed out after 300000ms` on a 4,800-word draft — was the original symptom: the call had been failing on disk for hours but the UI just looked empty.) New file: `client/src/components/writers-room/StagePromptModelPicker.jsx`. Touched: `server/services/writersRoom/evaluator.js`, `client/src/components/writers-room/StoryboardPanel.jsx`.+- **Writers Room — auto-queue every missing scene image when Adapt completes.** After **Run Adapt** finishes, the storyboard automatically dispatches a render for every scene that doesn't already have an image. Toasts `Queued N scene renders`. Scenes that already have an image (e.g. unchanged scene IDs from a prior pass) are skipped — re-Adapting only queues NEW scenes, not re-renders. The local FLUX image-gen queue serializes the requests server-side so the GPU isn't slammed; cards sit in queued state until the worker picks them up, and each card's existing socket subscription handles its own progress + completion + scene-image attachment. Implementation: `SceneCard` is now `forwardRef` + `useImperativeHandle` exposing `{ generate, canGenerate }`; `StoryboardPanel` collects refs and dispatches via `requestAnimationFrame` on the post-Adapt `latestScript` update. Touched: `client/src/components/writers-room/{SceneCard,StoryboardPanel}.jsx`.- **Writers Room — Steps + Seed inputs in the storyboard image-gen settings.** The storyboard's settings popover now exposes per-Writers-Room Steps and Seed alongside Image Model + Resolution (organized as two 2-column grids — `[model | resolution]` and `[steps | seed]`). Seed has a Dice5 randomize button matching the Image Gen page. Empty steps = use model default; empty seed = random per render. Both persist in `settings.json` and flow through `generateImage`. Touched: `client/src/components/writers-room/{StoryboardPanel,SceneCard,sceneCardHelpers}.jsx`.@@ -16,6 +20,8 @@## Changed+- **Gemini-CLI provider model list updated to current Google releases.** Replaced the deprecated `gemini-2.5-flash-lite` with the current set: `gemini-3.1-pro` (heavy), `gemini-3-flash` (medium), `gemini-2.5-pro`, `gemini-2.5-flash` (light + default). Tier mappings remap: `defaultModel`/`lightModel` → `gemini-2.5-flash`, `mediumModel` → `gemini-3-flash`, `heavyModel` → `gemini-3.1-pro`. The hardcoded gemini-cli fallback in `brain.js` and `writersRoom/evaluator.js` (used when both `defaultModel` and `lightModel` are unset on the provider) now points to `gemini-2.5-flash` instead of `gemini-2.5-flash-lite`. Mirror change applied to the upstream `portos-ai-toolkit` `providers.sample.json` so fresh installs pick up the new defaults. Touched: `data{,sample}/providers.json`, `server/services/{brain.js,brain.test.js,writersRoom/evaluator.js}`, `../portos-ai-toolkit/src/defaults/providers.sample.json`.+- **Writers Room — Adapt prompt rewritten for paragraph-grain output.** The Adapt stage was producing 8 scenes for a 4,800-word piece because the prompt told the LLM "A scene = one continuous unit of action in one location" + "Don't pad. If the natural arc is 3 scenes, return 3." That's a screenplay rule; wrong for a storyboard companion where dense beat-level cards are the whole point. Reframed "scene" as "one storyboard panel," set an explicit count anchor ("a 4,000-word piece with ~80 paragraphs should yield ~50–80 scenes, not 8"), listed when to SPLIT (default — every substantive paragraph; new visual framing; back-and-forth dialogue) vs MERGE (rare — one-sentence paragraphs depicting the same instant; pure dialogue tags), removed the "don't pad" anti-pattern, and tightened action/visualPrompt budgets since each work now has many more cards. Sluglines may repeat across consecutive same-location scenes. Touched: `data{,sample}/prompts/stages/writers-room-script.md`.- **Writers Room — analysis storage collapsed from history-of-runs to latest-per-kind.** The Adapt / Evaluate / Format / Characters analyses were each accumulating a fresh `wr-analysis-<uuid>.json` file per run, growing forever. The user only ever cares about the latest of each kind. Analysis id is now just the kind (`script`, `format`, `evaluate`, `characters`); files are `<kind>.json`; re-running a kind atomicWrite-overwrites its previous snapshot. Boot-time `recoverStuckAnalyses` gained a one-time migration that scans for legacy UUID-named files, groups by kind, keeps the latest per kind (by `completedAt|createdAt`), rewrites as `<kind>.json`, and deletes the legacy files. Idempotent. Touched: `server/services/writersRoom/evaluator.js`.diff --git a/client/src/components/writers-room/StagePromptModelPicker.jsx b/client/src/components/writers-room/StagePromptModelPicker.jsxnew file mode 100644index 0000000000..6fdaecfef1--- /dev/null+++ b/client/src/components/writers-room/StagePromptModelPicker.jsx@@ -0,0 +1,127 @@+import { useEffect, useMemo, useState } from 'react';+import toast from '../ui/Toast';+import ProviderModelSelector from '../ProviderModelSelector';++/**+ * Inline picker for a prompt stage's provider+model. Mirrors the Tier/Specific+ * toggle in PromptManager so any panel that runs an LLM stage (Adapt, Evaluate,+ * Format, Characters) can configure it locally without sending the user to+ * /prompts. Persists via PUT /api/prompts/<stageName>.+ */+export default function StagePromptModelPicker({ stageName, label = 'Stage LLM', icon = null, hint = null }) {+ const [stage, setStage] = useState(null);+ const [providers, setProviders] = useState([]);+ const [saving, setSaving] = useState(false);+ const [loaded, setLoaded] = useState(false);++ useEffect(() => {+ let cancelled = false;+ Promise.all([+ fetch(`/api/prompts/${encodeURIComponent(stageName)}`).then((r) => (r.ok ? r.json() : null)).catch(() => null),+ fetch('/api/providers').then((r) => (r.ok ? r.json() : null)).catch(() => null),+ ]).then(([s, p]) => {+ if (cancelled) return;+ setStage(s || null);+ setProviders((p?.providers || []).filter((x) => x.enabled));+ setLoaded(true);+ });+ return () => { cancelled = true; };+ }, [stageName]);++ const persist = async (next) => {+ setSaving(true);+ setStage((prev) => ({ ...prev, ...next }));+ const res = await fetch(`/api/prompts/${encodeURIComponent(stageName)}`, {+ method: 'PUT',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ provider: next.provider ?? null,+ model: next.model,+ }),+ });+ setSaving(false);+ if (!res.ok) toast.error(`Failed to save ${label}: ${await res.text().catch(() => res.statusText)}`);+ };++ if (!loaded) return null;+ if (!stage) {+ return (+ <div className="text-[11px] text-port-error">+ Stage <code>{stageName}</code> not found — open Prompts to create it.+ </div>+ );+ }++ const isSpecific = !!stage.provider;+ const modelsForProvider = useMemo(() => {+ const p = providers.find((pr) => pr.id === stage.provider);+ return p ? (p.models || [p.defaultModel]).filter(Boolean) : [];+ }, [providers, stage.provider]);++ const switchToTier = () => {+ if (!isSpecific) return;+ persist({ provider: null, model: 'default' });+ };+ const switchToSpecific = () => {+ if (isSpecific) return;+ const first = providers[0];+ if (!first) return;+ persist({ provider: first.id, model: first.defaultModel || (first.models || [])[0] || '' });+ };++ return (+ <div className="space-y-1.5">+ <div className="flex items-center justify-between">+ <span className="text-[9px] uppercase tracking-wider text-gray-500 flex items-center gap-1">+ {icon}{label}+ {saving && <span className="text-gray-600 normal-case">· saving…</span>}+ </span>+ <div className="flex gap-1">+ <button+ type="button"+ onClick={switchToTier}+ className={`px-1.5 py-0.5 text-[9px] rounded ${!isSpecific ? 'bg-port-accent text-white' : 'bg-port-border text-gray-400 hover:text-white'}`}+ >+ Tier+ </button>+ <button+ type="button"+ onClick={switchToSpecific}+ disabled={providers.length === 0}+ className={`px-1.5 py-0.5 text-[9px] rounded ${isSpecific ? 'bg-port-accent text-white' : 'bg-port-border text-gray-400 hover:text-white'} disabled:opacity-50`}+ >+ Specific+ </button>+ </div>+ </div>++ {!isSpecific ? (+ <select+ value={stage.model || 'default'}+ onChange={(e) => persist({ provider: null, model: e.target.value })}+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1 text-[11px] text-gray-200"+ >+ <option value="default">Default — use the active provider's default model</option>+ <option value="quick">Quick — provider's light/fast model</option>+ <option value="coding">Coding — provider's medium model</option>+ <option value="heavy">Heavy — provider's heavy model</option>+ </select>+ ) : (+ <ProviderModelSelector+ providers={providers}+ selectedProviderId={stage.provider}+ selectedModel={stage.model || ''}+ availableModels={modelsForProvider}+ onProviderChange={(id) => {+ const p = providers.find((pr) => pr.id === id);+ persist({ provider: id, model: p?.defaultModel || (p?.models || [])[0] || '' });+ }}+ onModelChange={(model) => persist({ provider: stage.provider, model })}+ compact+ />+ )}++ {hint && <div className="text-[10px] text-gray-500">{hint}</div>}+ </div>+ );+}diff --git a/client/src/components/writers-room/StoryboardPanel.jsx b/client/src/components/writers-room/StoryboardPanel.jsxindex 1129485a5c..c2e6e7c258 100644--- a/client/src/components/writers-room/StoryboardPanel.jsx+++ b/client/src/components/writers-room/StoryboardPanel.jsx@@ -1,5 +1,5 @@import { useCallback, useEffect, useMemo, useRef, useState } from 'react';-import { Clapperboard, Loader2, RefreshCcw, Settings as SettingsIcon, AlertTriangle, Palette, Check, Dice5 } from 'lucide-react';+import { Clapperboard, Loader2, RefreshCcw, Settings as SettingsIcon, AlertTriangle, Palette, Check, Dice5, Cpu } from 'lucide-react';import { randomSeed } from '../../lib/genUtils';import toast from '../ui/Toast';import {@@ -12,6 +12,7 @@ import { listImageModels } from '../../services/apiImageVideo';import { timeAgo } from '../../utils/formatters';import useMounted from '../../hooks/useMounted';import SceneCard from './SceneCard';+import StagePromptModelPicker from './StagePromptModelPicker';import {WR_IMAGE_DEFAULTS,buildCharByKey,@@ -20,6 +21,8 @@ import {EMPTY_IMAGE_STYLE,} from './sceneCardHelpers';+const SCRIPT_STAGE = 'writers-room-script';+export default function StoryboardPanel({work,characters = [],@@ -32,6 +35,7 @@ export default function StoryboardPanel({onStyleChange,}) {const [latestScript, setLatestScript] = useState(null);+ const [latestFailure, setLatestFailure] = useState(null);const [loading, setLoading] = useState(false);const [imageCfg, setImageCfg] = useState(WR_IMAGE_DEFAULTS);const [models, setModels] = useState([]);@@ -60,14 +64,22 @@ export default function StoryboardPanel({setLoading(true);const list = await listWritersRoomAnalyses(work.id).catch(() => []);if (!mountedRef.current) return;- const latest = list.find((a) => a.kind === 'script' && a.status === 'succeeded');- if (!latest) {+ // listAnalyses is sorted createdAt desc, so the first match per status is+ // also the most-recent one. Track failures only when newer than the latest+ // success — a stale failure under a newer success is just history.+ const scripts = list.filter((a) => a.kind === 'script');+ const latestRun = scripts[0] || null;+ const latestSucceeded = scripts.find((a) => a.status === 'succeeded') || null;+ const failureIsNewer = latestRun?.status === 'failed'+ && (!latestSucceeded || (latestRun.createdAt || '') > (latestSucceeded.createdAt || ''));+ setLatestFailure(failureIsNewer ? latestRun : null);+ if (!latestSucceeded) {setLatestScript(null);setLoading(false);return;}// listAnalyses returns metadata only — fetch the full snapshot for scenes + sceneImages.- const full = await getWritersRoomAnalysis(work.id, latest.id).catch(() => null);+ const full = await getWritersRoomAnalysis(work.id, latestSucceeded.id).catch(() => null);if (!mountedRef.current) return;setLatestScript(full);setLoading(false);@@ -75,6 +87,7 @@ export default function StoryboardPanel({useEffect(() => {setLatestScript(null);+ setLatestFailure(null);loadLatestScript();}, [loadLatestScript]);@@ -163,7 +176,13 @@ export default function StoryboardPanel({</div>{showSettings && (- <div className="px-3 py-2 border-b border-port-border bg-port-card/30 shrink-0 space-y-3">+ <div className="px-3 py-2 border-b border-port-border bg-port-card/30 shrink-0 space-y-3 max-h-[60vh] overflow-y-auto">+ <StagePromptModelPicker+ stageName={SCRIPT_STAGE}+ label="Adapt LLM"+ icon={<Cpu size={10} />}+ hint="Used when you click Run Adapt to break prose into scenes."+ /><WorldStyleRowvalue={imageStyle}presets={stylePresets}@@ -180,11 +199,21 @@ export default function StoryboardPanel({</div>)}- {!loading && !latestScript && (+ {!loading && latestFailure && (+ <FailedAdaptBanner+ failure={latestFailure}+ onRunAdapt={onRunAdapt}+ runningAdapt={runningAdapt}+ onOpenSettings={() => setShowSettings(true)}+ hasPriorScript={!!latestScript}+ />+ )}++ {!loading && !latestScript && !latestFailure && (<EmptyAdaptCTA onRunAdapt={onRunAdapt} runningAdapt={runningAdapt} />)}- {!loading && latestScript && isStale && (+ {!loading && latestScript && isStale && !latestFailure && (<StaleBanner onRunAdapt={onRunAdapt} runningAdapt={runningAdapt} />)}@@ -243,6 +272,49 @@ function EmptyAdaptCTA({ onRunAdapt, runningAdapt }) {);}+function FailedAdaptBanner({ failure, onRunAdapt, runningAdapt, onOpenSettings, hasPriorScript }) {+ const error = failure?.error || 'Adapt failed for an unknown reason';+ const isTimeout = /timed out/i.test(error);+ return (+ <div className="p-3 mb-2 border border-port-error/40 bg-port-error/5 rounded text-[11px] space-y-2">+ <div className="flex items-start gap-2">+ <AlertTriangle size={14} className="text-port-error mt-0.5 shrink-0" />+ <div className="flex-1 min-w-0">+ <div className="text-port-error font-medium">Adapt failed</div>+ <div className="text-gray-300 break-words">{error}</div>+ {isTimeout && (+ <div className="text-gray-500 mt-1">+ Long drafts are heavy for small/light models — try a faster model+ (e.g. an API provider) via the gear icon.+ </div>+ )}+ {!hasPriorScript && (+ <div className="text-gray-500 mt-1">+ No prior storyboard to fall back to — re-running will create the first one.+ </div>+ )}+ </div>+ </div>+ <div className="flex gap-2 justify-end">+ <button+ onClick={onOpenSettings}+ className="flex items-center gap-1 px-2 py-1 border border-port-border text-gray-300 rounded text-[10px] hover:bg-port-border/40"+ >+ <SettingsIcon size={10} /> Adjust LLM+ </button>+ <button+ onClick={onRunAdapt}+ disabled={runningAdapt || !onRunAdapt}+ className="flex items-center gap-1 px-2 py-1 bg-port-error/20 border border-port-error/40 text-port-error rounded text-[10px] hover:bg-port-error/30 disabled:opacity-50"+ >+ {runningAdapt ? <Loader2 size={10} className="animate-spin" /> : <RefreshCcw size={10} />}+ Re-run Adapt+ </button>+ </div>+ </div>+ );+}+function StaleBanner({ onRunAdapt, runningAdapt }) {return (<div className="flex items-start gap-2 p-2 mb-1 border border-port-warning/40 bg-port-warning/5 rounded text-[11px]">diff --git a/data.sample/providers.json b/data.sample/providers.jsonindex b4173fcd66..6c5e20f6e6 100644--- a/data.sample/providers.json+++ b/data.sample/providers.json@@ -55,11 +55,11 @@"type": "cli","command": "gemini","args": [],- "models": ["gemini-2.5-flash-lite", "gemini-2.5-flash", "gemini-2.5-pro"],- "defaultModel": "gemini-2.5-flash-lite",- "lightModel": "gemini-2.5-flash-lite",- "mediumModel": "gemini-2.5-flash",- "heavyModel": "gemini-2.5-pro",+ "models": ["gemini-3.1-pro", "gemini-3-flash", "gemini-2.5-pro", "gemini-2.5-flash"],+ "defaultModel": "gemini-2.5-flash",+ "lightModel": "gemini-2.5-flash",+ "mediumModel": "gemini-3-flash",+ "heavyModel": "gemini-3.1-pro","timeout": 300000,"enabled": true,"envVars": {}diff --git a/server/services/brain.js b/server/services/brain.jsindex e234e1baf2..8c35cb9fff 100644--- a/server/services/brain.js+++ b/server/services/brain.js@@ -50,11 +50,11 @@ async function callAI(promptStageName, variables, providerOverride, modelOverridconst prompt = await buildPrompt(promptStageName, variables);let model = modelOverride || provider.defaultModel;- // gemini-cli default is a thinking model (2.5-pro); prefer the provider's configured+ // gemini-cli default is a thinking model (3.1-pro); prefer the provider's configured// light tier (populated from data.sample/providers.json on new installs) and only fall- // back to the hard-coded flash-lite if nothing is configured at all.+ // back to the hard-coded flash if nothing is configured at all.if (provider.id === 'gemini-cli' && !model) {- model = provider.lightModel || 'gemini-2.5-flash-lite';+ model = provider.lightModel || 'gemini-2.5-flash';}console.log(`🧠 Calling AI: ${provider.id} / ${model} / ${promptStageName}`);@@ -566,7 +566,7 @@ export async function runDailyDigest(providerOverride, modelOverride) {}// Store digest — ai.modelId reflects the resolved model so attribution stays- // accurate even when callAI falls back (e.g., gemini-cli → gemini-2.5-flash-lite).+ // accurate even when callAI falls back (e.g., gemini-cli → gemini-2.5-flash).const digest = await storage.createDigest({...digestData,ai: {@@ -628,7 +628,7 @@ export async function runWeeklyReview(providerOverride, modelOverride) {}// Store review — ai.modelId reflects the resolved model so attribution stays- // accurate even when callAI falls back (e.g., gemini-cli → gemini-2.5-flash-lite).+ // accurate even when callAI falls back (e.g., gemini-cli → gemini-2.5-flash).const review = await storage.createReview({...reviewData,ai: {diff --git a/server/services/brain.test.js b/server/services/brain.test.jsindex 97f566dce3..f5692cc91c 100644--- a/server/services/brain.test.js+++ b/server/services/brain.test.js@@ -1057,7 +1057,7 @@ describe('brain service', () => {command: 'gemini',args: [],timeout: 50- // defaultModel deliberately unset — exercises the flash-lite fallback+ // defaultModel deliberately unset — exercises the flash fallback});spawn.mockReturnValue(createMockChild(validDigestJson));@@ -1076,7 +1076,7 @@ describe('brain service', () => {// Thinking-model fallbackconst modelIdx = args.indexOf('--model');expect(modelIdx).toBeGreaterThanOrEqual(0);- expect(args[modelIdx + 1]).toBe('gemini-2.5-flash-lite');+ expect(args[modelIdx + 1]).toBe('gemini-2.5-flash');// Prompt delivered via flag (not positional) so gemini-cli stays non-interactiveconst promptIdx = args.indexOf('--prompt');@@ -1084,7 +1084,7 @@ describe('brain service', () => {expect(args[promptIdx + 1]).toBe('test prompt');});- it('honors an explicit model override instead of the flash-lite fallback', async () => {+ it('honors an explicit model override instead of the flash fallback', async () => {getProviderById.mockResolvedValue({id: 'gemini-cli',enabled: true,@@ -1103,14 +1103,16 @@ describe('brain service', () => {expect(args[modelIdx + 1]).toBe('gemini-2.5-pro');});- it('prefers provider.lightModel over the hard-coded flash-lite fallback when defaultModel is unset', async () => {+ it('prefers provider.lightModel over the hard-coded flash fallback when defaultModel is unset', async () => {getProviderById.mockResolvedValue({id: 'gemini-cli',enabled: true,type: 'cli',command: 'gemini',args: [],- lightModel: 'gemini-2.5-flash',+ // Use a different model from the hard-coded fallback so the test+ // proves lightModel wins, not that both happened to be the same string.+ lightModel: 'gemini-3-flash',timeout: 50// defaultModel deliberately unset — lightModel should win over the hard-coded default});@@ -1120,7 +1122,7 @@ describe('brain service', () => {const args = spawn.mock.calls[0][1];const modelIdx = args.indexOf('--model');- expect(args[modelIdx + 1]).toBe('gemini-2.5-flash');+ expect(args[modelIdx + 1]).toBe('gemini-3-flash');});it('does not duplicate --output-format when provider args already specify it', async () => {@@ -1130,7 +1132,7 @@ describe('brain service', () => {type: 'cli',command: 'gemini',args: ['--output-format', 'json'],- defaultModel: 'gemini-2.5-flash-lite',+ defaultModel: 'gemini-2.5-flash',timeout: 50});spawn.mockReturnValue(createMockChild(validDigestJson));@@ -1165,7 +1167,7 @@ describe('brain service', () => {expect(storedDigest).toBeTruthy();expect(storedDigest.ai.providerId).toBe('gemini-cli');- expect(storedDigest.ai.modelId).toBe('gemini-2.5-flash-lite');+ expect(storedDigest.ai.modelId).toBe('gemini-2.5-flash');});it('uses positional prompt (not --prompt) for non-gemini CLI providers', async () => {diff --git a/server/services/writersRoom/evaluator.js b/server/services/writersRoom/evaluator.jsindex 3aac7c0ce2..7f7f2b540f 100644--- a/server/services/writersRoom/evaluator.js+++ b/server/services/writersRoom/evaluator.js@@ -10,8 +10,8 @@ import { readFile, readdir, rm } from 'fs/promises';import { PATHS, atomicWrite, ensureDir, safeJSONParse } from '../../lib/fileUtils.js';import { ServerError } from '../../lib/errorHandler.js';import { stripCodeFences } from '../../lib/aiProvider.js';-import { getActiveProvider } from '../providers.js';-import { buildPrompt } from '../promptService.js';+import { getActiveProvider, getProviderById } from '../providers.js';+import { buildPrompt, getStage } from '../promptService.js';import { ANALYSIS_KINDS } from '../../lib/writersRoomPresets.js';import { getWorkWithBody } from './local.js';import { listCharacters, mergeExtractedCharacters } from './characters.js';@@ -37,7 +37,41 @@ const analysisPath = (workId, id) => join(analysisDir(workId), `${id}.json`);// ---------- LLM invocation -----------async function resolveProvider() {+// Tier names used in stage configs (PromptManager UI). Map to the provider's+// configured per-tier model id; an unset tier falls back to defaultModel so+// stages with `model: 'heavy'` still run on providers that don't break out tiers.+const TIER_TO_MODEL_KEY = {+ default: 'defaultModel',+ quick: 'lightModel',+ coding: 'mediumModel',+ heavy: 'heavyModel',+};++function isTierName(model) {+ return typeof model === 'string' && model in TIER_TO_MODEL_KEY;+}++function resolveModel(provider, stageModel) {+ if (!stageModel) return provider.defaultModel || null;+ if (isTierName(stageModel)) {+ return provider[TIER_TO_MODEL_KEY[stageModel]] || provider.defaultModel || null;+ }+ return stageModel;+}++// Stage config can pin a specific provider via `stage.provider`. When set we+// must use that provider (or fail) — falling back to the active provider would+// silently route the call through whatever's currently selected, defeating the+// whole point of the per-stage override.+async function resolveProviderForStage(stage) {+ if (stage?.provider) {+ const pinned = await getProviderById(stage.provider).catch(() => null);+ if (pinned?.enabled) return pinned;+ throw new ServerError(+ `Stage provider "${stage.provider}" is not available — re-pick a provider in Prompts or the Storyboard settings`,+ { status: 503, code: 'STAGE_PROVIDER_UNAVAILABLE' }+ );+ }const active = await getActiveProvider().catch(() => null);if (active?.enabled) return active;throw new ServerError('No AI provider available', { status: 503, code: 'NO_PROVIDER' });@@ -64,23 +98,56 @@ async function callApiProvider(provider, model, prompt, temperature) {return data.choices?.[0]?.message?.content || '';}+// Each CLI needs a different incantation to run non-interactively from a+// server process. Get it wrong and the CLI either hangs waiting for a TTY or+// exits with "Error: stdin is not a terminal". Mirrors `runner.js` /+// `agentCliSpawning.js` so the writers-room path agrees with how PortOS+// already spawns these CLIs everywhere else.+function buildCliInvocation(provider, model) {+ const baseArgs = [...(provider.args || [])];+ if (provider.headlessArgs?.length) baseArgs.push(...provider.headlessArgs);++ switch (provider.id) {+ case 'gemini-cli': {+ const args = [...baseArgs];+ if (!args.includes('--output-format') && !args.includes('-o')) {+ args.push('--output-format', 'text');+ }+ if (model) args.push('--model', model);+ return { args, promptViaStdin: false };+ }+ case 'codex': {+ // `codex exec -` reads the prompt from stdin. Without `exec` codex+ // launches its REPL and bails with "Error: stdin is not a terminal".+ const args = [...baseArgs, 'exec'];+ if (model) args.push('--model', model);+ args.push('-');+ return { args, promptViaStdin: true };+ }+ case 'claude-code':+ case 'claude-code-bedrock': {+ const args = [...baseArgs, '-p', '-'];+ if (model) args.push('--model', model);+ return { args, promptViaStdin: true };+ }+ default: {+ const args = [...baseArgs];+ if (model) args.push('--model', model);+ return { args, promptViaStdin: true };+ }+ }+}+function callCliProvider(provider, model, prompt) {return new Promise((resolve, reject) => {- const args = [...(provider.args || [])];- if (provider.headlessArgs?.length) args.push(...provider.headlessArgs);- const isGeminiCli = provider.id === 'gemini-cli';- if (isGeminiCli && !args.includes('--output-format') && !args.includes('-o')) {- args.push('--output-format', 'text');- }- if (model) args.push('--model', model);- // Send the prose via stdin for non-gemini CLIs — adapted-screenplay drafts- // can run tens of thousands of characters once headings and dialogue are- // inlined, well past argv ceilings on macOS/Linux.- const usingStdin = !isGeminiCli;- if (isGeminiCli) args.push('--prompt', prompt);+ const { args, promptViaStdin } = buildCliInvocation(provider, model);+ // gemini-cli takes the prompt as a flag because its non-interactive mode+ // requires `--prompt` plus stdio: ['ignore', ...]. Every other CLI accepts+ // the prompt on stdin, which dodges argv ceilings on long drafts.+ if (!promptViaStdin) args.push('--prompt', prompt);const child = spawn(provider.command, args, {env: (() => { const e = { ...process.env, ...provider.envVars }; delete e.CLAUDECODE; return e; })(),- stdio: [usingStdin ? 'pipe' : 'ignore', 'pipe', 'pipe'],+ stdio: [promptViaStdin ? 'pipe' : 'ignore', 'pipe', 'pipe'],shell: false,windowsHide: true,});@@ -95,19 +162,23 @@ function callCliProvider(provider, model, prompt) {child.on('close', (code) => {clearTimeout(killer);if (code === 0) resolve(output);- else reject(new Error(`CLI exited with code ${code}${output ? ': ' + output.slice(0, 500) : ''}`));+ // Tail the output rather than head — CLI banners/transcripts come first+ // and the actual error/stack lives at the end. 500 chars of header was+ // hiding real failures (e.g. provider auth errors) under a Codex banner.+ else reject(new Error(`CLI exited with code ${code}${output ? ': ' + output.slice(-2000) : ''}`));});child.on('error', (err) => { clearTimeout(killer); reject(err); });- if (usingStdin) child.stdin.end(prompt);+ if (promptViaStdin) child.stdin.end(prompt);});}async function callAI(stageName, variables, temperature) {- const provider = await resolveProvider();+ const stage = getStage(stageName);+ const provider = await resolveProviderForStage(stage);const prompt = await buildPrompt(stageName, variables);- let model = provider.defaultModel;+ let model = resolveModel(provider, stage?.model);if (provider.id === 'gemini-cli' && !model) {- model = provider.lightModel || 'gemini-2.5-flash-lite';+ model = provider.lightModel || 'gemini-2.5-flash';}console.log(`📝 wr eval: ${provider.id} / ${model || '(default)'} / ${stageName}`);if (provider.type === 'api') {