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

refactor(server): unify promptRunner + jsonExtract — collapse 4 LLM-runner sites + 3 JSON extractors (#221)

[._.]/ Adam Eivy31ad71b17afd
diff --git a/DONE.md b/DONE.md
index dbc31c2e13..6db90acc74 100644
--- a/DONE.md
+++ b/DONE.md
@@ -14,6 +14,8 @@ Archive of completed work. For active roadmap, see [PLAN.md](./PLAN.md). For pro
- **`mediaModels.js` drift warning** — `loadMediaModels()` now logs a loud `⚠️ media-models drift` warning at boot for any id present in BOTH `_shippedDefaults` AND `DEFAULT_REGISTRY` but missing from the user's live list. Catches the 2026-05-09 silent-drift class. No auto-recover — surfaces the bug, lets a human decide. Warning is honest that intentional deletions are indistinguishable from drift and will keep firing each boot. Covers `image` plus `video.macos` and `video.windows`. 4 new tests.
- **CLI `defaultModel` for all CLI providers** — `services/runner.js#buildCliArgs` now appends `--model <id>` to claude-code (after `-p -`; claude-code parses flags positionally) and `-m <id>` to gemini-cli, gated on the provider's stored `args` not already containing `--model`/`-m` (both space- and `=`-joined forms; rejects dangling/empty flag forms). Codex behavior unchanged. New `hasModelFlag`/`extractBakedModel`/`stripBrokenModelFlags` helpers exported for reuse. Stage runner / message evaluator / media prompt refiner / world builder refiner per-call model overrides now actually take effect for all three CLIs instead of silently no-op'ing for claude-code and gemini-cli; refiners report the args-baked model id (not defaultModel) when a model is pinned in args. 15+ new tests + 2 regression tests; surfaced from Copilot review on PR #217 and #222.
- **Extract `scripts/_runner_common.py`** — Pulled the byte-for-byte-duplicated `pick_device` / `make_generator` / `apply_memory_optimizations` / `write_sidecar` / `make_stepwise_callback` / `_emit_user_error` / `_repo_from_hf_error` / HF cause-chain walker (~200 LOC) out of `scripts/flux2_macos.py` + `scripts/z_image_turbo.py` into a shared module. `make_stepwise_callback` now takes an optional `unpack_latents` callable so the flux2 packed-transformer-latent path stays runner-specific while the rest of the decode is shared. `install_hf_error_handler` is a `@decorator` over `main()` that owns the gated/notfound/401 dispatch — `if __name__ == "__main__": main()` collapses to one line in both runners. Mirrors the `lora_utils.py` extraction pattern. Server tests 4012/4012 green; both runners' `--help` resolves cleanly.
+- **Shared `runPromptThroughProvider` runner-wrapper** — Four near-identical "create run → branch on provider.type → executeCliRun/executeApiRun → accumulate text → reject on error" implementations (`worldBuilderExpand#callLLM`, `stageRunner#awaitRunnerCall`, `mediaPromptRefiner#runRefinePrompt`, `messageEvaluator#runPrompt`) collapse onto `server/lib/promptRunner.js`. The unified runner picks the strictest discriminator: rejects on `success === false` OR truthy `error` for BOTH CLI and API. Per-site drift used to let API "soft failures" flow through as empty text — now they reject loudly. Returns `{ text, runId, model }` where `model` is the post-gate effective model that actually executed (per-call model is dropped for providers that don't honor it — see `providerHonorsModelOverride`). 19 unit tests in `promptRunner.test.js` covering happy paths, strictest-discriminator rejection, executeCliRun/executeApiRun pre-onComplete rejection forwarding, and multi-chunk text accumulation.
+- **Shared `findBalancedBlocks` + `tryParseWithRepair` + `extractJson` in `server/lib/jsonExtract.js`** — Three near-identical extractors (`worldBuilderExpand.js`, `mediaPromptRefiner.js#extractRefinementJson`, `stageRunner.js#extractJson`) all solved the same "extract JSON from CLI-banner-prefixed LLM output" problem. Promoted the richest implementation (string-aware brace walker + string-aware trailing-comma + Codex `}}]` orphan-brace repair + `[...]` placeholder cleanup) into the shared lib with optional `shapePredicate` for caller-specific block selection. All three callers re-import from the lib; mediaPromptRefiner keeps its tri-state placeholder-vs-real walker via `findBalancedBlocks` + `tryParseWithRepair` directly so the "schema placeholder" error message stays intact. 33 unit tests in `jsonExtract.test.js`.
## 2026-05-10
diff --git a/PLAN.md b/PLAN.md
index 7d3fc69b77..12179bcce8 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -60,10 +60,6 @@ _All items in this section have shipped — see DONE.md → 2026-05-12 for the
`scripts/_runner_common.py` extraction entry._
- [ ] **Project-wide `<Modal>` component** — every modal in the app (`Flux2InstallModal`, `EditAppModal`, `MemoryEditModal`, `ResumeAgentModal`, `MediaLightbox`, `LayoutEditor`, `KeyboardHelp`, `RapidReader`, `DeployPanel`'s confirm, the new `CivitaiAuthModal` in `Loras.jsx`) rolls its own `fixed inset-0 z-50 bg-black/70 flex items-center justify-center p-4` backdrop + click-outside + close-button + ESC handler. Extract `client/src/components/ui/Modal.jsx` with backdrop + dialog props and a slot for the body, then convert all call sites. ~300 LOC of duplicated chrome across the codebase.
-- [ ] **Extract shared `runPromptThroughProvider` runner-wrapper** — four near-identical "create run → branch on provider.type → executeCliRun/executeApiRun → accumulate text → reject on error" implementations now exist: `server/services/mediaPromptRefiner.js#runRefinePrompt`, `server/services/messageEvaluator.js#runPrompt`, `server/lib/stageRunner.js#awaitRunnerCall`, `server/services/worldBuilderExpand.js#callLLM`. Promote into `server/lib/promptRunner.js` returning `{ text, runId }`, then collapse the four sites. Failure-handling drift is already visible (some reject on `success === false`, some only on `error`) — the unified version should pick the stricter discriminator. Surfaced from the Refine Prompt /simplify pass.
-
-- [ ] **Promote `findBalancedBlocks` + `tryParseWithRepair` to `server/lib/jsonExtract.js`** — `server/services/worldBuilderExpand.js:132-235` (with trailing-comma + Codex `}}]` repair + `[...]` placeholder cleanup), `server/services/mediaPromptRefiner.js#extractRefinementJson` (string-aware brace walker), and `server/lib/stageRunner.js#extractJson` (greedy regex) all solve the same "extract JSON from CLI-banner-prefixed LLM output" problem. The richest implementation is in worldBuilderExpand; lift it out and have all three callers import it (with caller-specific shape predicates). Surfaced from the Refine Prompt /simplify pass.
-
- [ ] **Extend `normalize.js` to expose render-config fields** — `client/src/components/media/PromptRefineModal.jsx#getRenderConfig` reaches into `item.raw?.{cfgScale,loraFilenames,loraScales,steps (video),guidanceScale,seed,tiling,disableAudio}` because `normalizeImage`/`normalizeVideo` don't surface those fields. Either lift the snake_case/camelCase fallback chain into normalize.js so the modal reads from `item.*` only, or add `getRenderConfigForItem(item)` co-located with normalize so the sidecar field-naming knowledge lives in one file. Surfaced from the Refine Prompt /simplify pass.
### Better Audit follow-ups
diff --git a/server/lib/jsonExtract.js b/server/lib/jsonExtract.js
new file mode 100644
index 0000000000..a7bd7376b5
--- /dev/null
+++ b/server/lib/jsonExtract.js
@@ -0,0 +1,251 @@
+/**
+ * Shared JSON extraction utilities for LLM responses.
+ *
+ * LLM output is messy — CLI providers (notably Codex) prepend banner text
+ * and echo the user prompt back to stdout before the model response. The
+ * prompt itself often contains a JSON-shaped schema example whose braces
+ * balance but whose contents are not valid JSON. Models also routinely
+ * emit trailing commas, `[...]` placeholder elisions, and the Codex
+ * `}}]` orphan-brace corruption pattern.
+ *
+ * This module collapses three near-identical extractors that all solved
+ * the same problem:
+ * - worldBuilderExpand.js — string-aware brace walker + repair passes
+ * - mediaPromptRefiner.js#extractRefinementJson — brace walker without repairs
+ * - stageRunner.js#extractJson — greedy regex
+ *
+ * The richest implementation (worldBuilderExpand) is promoted here and
+ * the three callers import from this file with optional shape predicates.
+ */
+
+import { stripCodeFences } from './aiProvider.js';
+
+/**
+ * Walk the string and return every top-level brace-balanced block, in
+ * order. String-aware so braces/brackets inside JSON string values don't
+ * throw off the depth counter. Returning every block lets the caller try
+ * each in turn — preferring the one whose shape matches the expected
+ * response over an in-prompt schema example.
+ *
+ * @param {string} s — input text
+ * @param {object} [options]
+ * @param {string} [options.startChar='{'] — opening delimiter ('{' or '[')
+ * @param {string} [options.endChar='}'] — matching closing delimiter
+ * @returns {string[]} — every balanced block found, in source order
+ */
+export function findBalancedBlocks(s, { startChar = '{', endChar = '}' } = {}) {
+ if (typeof s !== 'string' || !s) return [];
+ const blocks = [];
+ let i = 0;
+ while (i < s.length) {
+ const start = s.indexOf(startChar, i);
+ if (start === -1) break;
+ let depth = 0;
+ let inString = false;
+ let escaped = false;
+ let end = -1;
+ for (let j = start; j < s.length; j += 1) {
+ const ch = s[j];
+ if (inString) {
+ if (escaped) escaped = false;
+ else if (ch === '\\') escaped = true;
+ else if (ch === '"') inString = false;
+ continue;
+ }
+ if (ch === '"') { inString = true; continue; }
+ if (ch === startChar) depth += 1;
+ else if (ch === endChar) {
+ depth -= 1;
+ if (depth === 0) { end = j; break; }
+ }
+ }
+ // Intentional bail on the first unbalanced segment. A well-formed
+ // block COULD exist further along (e.g. an LLM that dumped partial
+ // JSON, then prose, then a complete second JSON object), but for
+ // PortOS's LLM-output use case the more common shape is "model
+ // emitted one JSON and then trailed off" — surfacing the candidates
+ // we have so far and letting the caller decide is safer than gluing
+ // together fragments that span an unbalanced gap. If a future use
+ // case needs scan-past-unbalanced behavior, add an opt-in option.
+ if (end === -1) break;
+ blocks.push(s.slice(start, end + 1));
+ i = end + 1;
+ }
+ return blocks;
+}
+
+/**
+ * Apply a regex `replace()` to the input ONLY OUTSIDE quoted JSON
+ * string regions. Walks the input with the same string/escape awareness
+ * as `findBalancedBlocks`, splits into alternating "code" and "string"
+ * segments, runs the replace on each code segment, then reassembles.
+ * Strings are passed through verbatim, so a JSON string containing
+ * `,}` or `}}]` as content is preserved.
+ */
+function replaceOutsideStrings(input, pattern, replacement) {
+ if (typeof input !== 'string' || !input) return input;
+ const segments = [];
+ let cursor = 0;
+ let inString = false;
+ let escaped = false;
+ for (let i = 0; i < input.length; i += 1) {
+ const ch = input[i];
+ if (inString) {
+ if (escaped) escaped = false;
+ else if (ch === '\\') escaped = true;
+ else if (ch === '"') {
+ // String just closed at index `i`. The open-quote → close-quote
+ // range (inclusive) is a 'string' segment the replace can't touch.
+ segments.push({ kind: 'string', text: input.slice(cursor, i + 1) });
+ cursor = i + 1;
+ inString = false;
+ }
+ continue;
+ }
+ if (ch === '"') {
+ // About to enter a string at index `i`. Flush the preceding code
+ // region so the replace can fire on it.
+ if (i > cursor) segments.push({ kind: 'code', text: input.slice(cursor, i) });
+ cursor = i;
+ inString = true;
+ }
+ }
+ // Flush trailing region. If the input ended mid-string (malformed JSON),
+ // treat the unterminated tail as a string so the repair doesn't touch
+ // it — the parse will fail anyway and the caller falls through.
+ if (cursor < input.length) {
+ segments.push({ kind: inString ? 'string' : 'code', text: input.slice(cursor) });
+ }
+ return segments.map((seg) => (
+ seg.kind === 'code' ? seg.text.replace(pattern, replacement) : seg.text
+ )).join('');
+}
+
+/**
+ * Try JSON.parse on a candidate block. If it fails, apply cheap repairs
+ * for observed LLM corruption patterns and try again:
+ * - Trailing commas before `}` or `]` (common LLM mistake).
+ * - `[...]` literal placeholder elisions echoed from prompt examples.
+ * - Codex CLI `}}]` orphan-brace corruption — an extra `}` snuck in
+ * between a variation's close-brace and the array's `]`. Swapping
+ * `}}]` → `}]}` (not dropping the brace) keeps the brace count
+ * correct so the outer container still closes.
+ *
+ * All repairs are STRING-AWARE: the regexes only touch characters
+ * outside quoted JSON string values, so a string containing `,}` or
+ * `}}]` as ordinary content is preserved.
+ *
+ * Returns `{ value }` on success (where `value` may be a valid JSON
+ * `null`); returns `{ error }` if all repairs fail. The wrapper lets a
+ * top-level `null` response flow through as a real parsed value rather
+ * than colliding with a "did not parse" sentinel.
+ *
+ * @param {string} jsonText — candidate JSON text
+ * @returns {{ value: unknown } | { error: Error }}
+ */
+export function tryParseWithRepair(jsonText) {
+ if (typeof jsonText !== 'string') return { error: new Error('Non-string input') };
+ // `[...]` placeholder cleanup runs before the first parse so a block
+ // containing only that token (no other JSON errors) succeeds on the
+ // first try instead of falling into the trailing-comma branch.
+ const initial = replaceOutsideStrings(jsonText, /\[\s*\.\.\.\s*\]/g, '[]');
+ const initialResult = safeParse(initial);
+ if (!initialResult.error) return initialResult;
+
+ const noTrailing = replaceOutsideStrings(initial, /,(\s*[}\]])/g, '$1');
+ if (noTrailing !== initial) {
+ const trailingResult = safeParse(noTrailing);
+ if (!trailingResult.error) return trailingResult;
+ }
+
+ const fixedOrphan = replaceOutsideStrings(noTrailing, /}\s*}\s*]/g, '}]}');
+ const orphanResult = safeParse(fixedOrphan);
+ if (!orphanResult.error) return orphanResult;
+
+ // Surface the last attempt's parse error so the caller can include the
+ // concrete reason ("Unexpected token } in JSON at position 47") in its
+ // error message rather than a generic "no JSON block found".
+ return { error: orphanResult.error };
+}
+
+// Returns `{ value }` on success or `{ error }` on failure. The discriminated
+// shape lets a JSON `null` literal flow through as a valid parsed value
+// (some LLMs legitimately return `null`); a single-value-with-sentinel
+// API can't distinguish "parsed `null`" from "did not parse."
+function safeParse(text) {
+ try { return { value: JSON.parse(text) }; } catch (error) { return { error }; }
+}
+
+/**
+ * Extract the first matching JSON block from CLI-banner-prefixed LLM
+ * output. Strips ```json / ``` fences, walks balanced blocks, applies
+ * repairs, and returns the first block matching the optional shape
+ * predicate (or the first block that parses at all when no predicate
+ * is supplied).
+ *
+ * Returns `{ value: undefined, lastError, lastPreview }` if no block
+ * parses — callers decide whether to throw a typed error (ServerError)
+ * or attempt a different fallback.
+ *
+ * @param {string} text — raw LLM output
+ * @param {object} [options]
+ * @param {(parsed:unknown)=>boolean} [options.shapePredicate] — return true
+ * for blocks whose shape matches the caller's expected response. Used to
+ * skip in-prompt schema examples that parse cleanly but aren't the answer.
+ * @param {'object'|'array'} [options.blockType='object'] — top-level shape
+ * to walk for (`{...}` vs `[...]`).
+ * @returns {{ value:unknown, lastError?:Error, lastPreview?:string }}
+ * — `value` is the parsed block, or `undefined` when no block matches.
+ * On no-match, `lastError` + `lastPreview` (200-char excerpt of the last
+ * candidate text) are populated for use in caller error messages.
+ */
+export function extractJson(text, { shapePredicate, blockType = 'object' } = {}) {
+ if (typeof text !== 'string' || !text.trim()) {
+ return { value: undefined, lastError: new Error('Empty LLM response'), lastPreview: '' };
+ }
+
+ let s = stripCodeFences(text.trim());
+ // stripCodeFences only catches leading/trailing fences. CLI banners
+ // sometimes wrap the response in fences mid-stream — fall back to
+ // a non-greedy match for the FIRST inner ```…``` block so we still
+ // extract the inner JSON. NOTE: callers that may see fenced
+ // prompt-echo content BEFORE the real response should skip this
+ // helper and walk the full text directly (see stageRunner.extractJson)
+ // — the first-fence heuristic locks onto the echoed schema and never
+ // reaches the actual model output.
+ const fence = s.match(/```(?:json)?\s*([\s\S]*?)```/);
+ if (fence) s = fence[1].trim();
+
+ const { startChar, endChar } = blockType === 'array'
+ ? { startChar: '[', endChar: ']' }
+ : { startChar: '{', endChar: '}' };
+
+ const candidates = findBalancedBlocks(s, { startChar, endChar });
+ if (!candidates.length) candidates.push(s);
+
+ // `parsedHolder` carries the first parseable block as `{ value }` even
+ // when it doesn't match shapePredicate, so a top-level `null` literal
+ // can still flow through as a real parsed value on fallback.
+ let parsedHolder;
+ let lastError;
+ let lastPreview = s.slice(0, 200);
+ for (const block of candidates) {
+ const result = tryParseWithRepair(block);
+ if (result.error) {
+ lastError = result.error;
+ lastPreview = block.slice(0, 200);
+ continue;
+ }
+ if (!shapePredicate || shapePredicate(result.value)) {
+ return { value: result.value };
+ }
+ if (parsedHolder === undefined) parsedHolder = result;
+ }
+
+ if (parsedHolder !== undefined) return parsedHolder;
+ return {
+ value: undefined,
+ lastError: lastError || new Error('No matching JSON block found'),
+ lastPreview,
+ };
+}
diff --git a/server/lib/jsonExtract.test.js b/server/lib/jsonExtract.test.js
new file mode 100644
index 0000000000..20eea3dc08
--- /dev/null
+++ b/server/lib/jsonExtract.test.js
@@ -0,0 +1,222 @@
+import { describe, it, expect } from 'vitest';
+import { findBalancedBlocks, tryParseWithRepair, extractJson } from './jsonExtract.js';
+
+describe('jsonExtract.findBalancedBlocks', () => {
+ it('returns the single top-level brace-balanced block', () => {
+ expect(findBalancedBlocks('{"a":1}')).toEqual(['{"a":1}']);
+ });
+
+ it('returns multiple sibling blocks in source order', () => {
+ expect(findBalancedBlocks('{"a":1} prose {"b":2}')).toEqual(['{"a":1}', '{"b":2}']);
+ });
+
+ it('respects quoted strings — braces inside JSON string values do not affect depth', () => {
+ expect(findBalancedBlocks('{"a":"}"}')).toEqual(['{"a":"}"}']);
+ expect(findBalancedBlocks('{"a":"{ nested }"}')).toEqual(['{"a":"{ nested }"}']);
+ });
+
+ it('honors escaped quotes inside JSON string values', () => {
+ expect(findBalancedBlocks('{"a":"\\"}"}')).toEqual(['{"a":"\\"}"}']);
+ });
+
+ it('bails on unbalanced input — no fake completion of dangling braces', () => {
+ expect(findBalancedBlocks('{"a":1')).toEqual([]);
+ });
+
+ it('returns an empty array for empty / non-string input', () => {
+ expect(findBalancedBlocks('')).toEqual([]);
+ expect(findBalancedBlocks(null)).toEqual([]);
+ expect(findBalancedBlocks(undefined)).toEqual([]);
+ });
+
+ it('supports array-mode block walking', () => {
+ expect(findBalancedBlocks('prose [1,2,3] more', { startChar: '[', endChar: ']' })).toEqual(['[1,2,3]']);
+ });
+});
+
+describe('jsonExtract.tryParseWithRepair', () => {
+ it('parses clean JSON in the happy path', () => {
+ expect(tryParseWithRepair('{"a":1}')).toEqual({ value: { a: 1 } });
+ });
+
+ it('repairs trailing commas before `}` and `]`', () => {
+ expect(tryParseWithRepair('{"a":[1,2,],"b":1,}')).toEqual({ value: { a: [1, 2], b: 1 } });
+ });
+
+ it('preserves trailing-comma-like patterns INSIDE string values (string-aware repair)', () => {
+ // Without string-aware repair, `,}` inside a string value would be
+ // rewritten to `}`, corrupting the content. The repair only runs
+ // outside quoted string regions.
+ const input = '{"label":"hello ,}","b":1,}'; // trailing `,}` outside, `,}` inside string
+ expect(tryParseWithRepair(input)).toEqual({ value: { label: 'hello ,}', b: 1 } });
+ });
+
+ it('preserves `}}]` INSIDE string values (string-aware orphan-brace repair)', () => {
+ // The Codex orphan-brace repair `}}]` → `}]}` must not touch
+ // string contents — a model writing about JSON syntax in a label
+ // would otherwise be silently rewritten.
+ const input = '{"note":"the pattern }}] is a code smell","ok":true}';
+ expect(tryParseWithRepair(input)).toEqual({
+ value: { note: 'the pattern }}] is a code smell', ok: true },
+ });
+ });
+
+ it('preserves `[...]` placeholder-looking content INSIDE string values', () => {
+ // A string containing the literal text `[...]` (e.g. a translation
+ // note or instruction text) must not be replaced with `[]`.
+ const input = '{"hint":"insert [...] here"}';
+ expect(tryParseWithRepair(input)).toEqual({ value: { hint: 'insert [...] here' } });
+ });
+
+ it('repairs Codex `}}]` orphan-brace corruption on a brace-balanced slice', () => {
+ // In production this repair runs AFTER findBalancedBlocks has carved
+ // out the outer-balanced slice. The slice contains `}}]` mid-content
+ // (the variation object closed, an orphan `}` snuck in, then `]`
+ // closes the array). Swapping `}}]` → `}]}` is brace-count-neutral
+ // so the outer container still closes. The slice itself MUST be
+ // brace-balanced (4 `{`, 4 `}`) — that's the post-findBalancedBlocks
+ // shape, lifted from worldBuilderExpand's real production failure.
+ const bad = '{"stylePrompt":"x","categories":{"vehicles":{"variations":[{"label":"a","prompt":"…blister"}}]}}';
+ expect(tryParseWithRepair(bad)).toEqual({
+ value: {
+ stylePrompt: 'x',
+ categories: { vehicles: { variations: [{ label: 'a', prompt: '…blister' }] } },
+ },
+ });
+ });
+
+ it('replaces literal `[...]` placeholder elisions with empty arrays', () => {
+ expect(tryParseWithRepair('{"vars":[...]}')).toEqual({ value: { vars: [] } });
+ });
+
+ it('returns the concrete parse error when no repair can recover the input', () => {
+ const r1 = tryParseWithRepair('{ this is not valid json');
+ expect(r1.value).toBeUndefined();
+ expect(r1.error).toBeInstanceOf(Error);
+ expect(r1.error.message).toMatch(/JSON/i);
+ const r2 = tryParseWithRepair('garbage');
+ expect(r2.error).toBeInstanceOf(Error);
+ });
+
+ it('returns an error for non-string input', () => {
+ expect(tryParseWithRepair(null).error).toBeInstanceOf(Error);
+ expect(tryParseWithRepair(42).error).toBeInstanceOf(Error);
+ });
+
+ it('preserves JSON `null` as a valid parsed value distinguishable from parse failure', () => {
+ // A top-level JSON `null` literal is a valid parsed value — the
+ // `{ value }` wrapper lets callers distinguish it from a parse
+ // failure (which returns `{ error }`).
+ expect(tryParseWithRepair('null')).toEqual({ value: null });
+ });
+});
+
+describe('jsonExtract.extractJson', () => {
+ it('parses raw JSON object', () => {
+ expect(extractJson('{"a":1}').value).toEqual({ a: 1 });
+ });
+
+ it('strips ```json fences', () => {
+ expect(extractJson('```json\n{"a":1}\n```').value).toEqual({ a: 1 });
+ });
+
+ it('strips bare ``` fences', () => {
+ expect(extractJson('```\n{"a":1}\n```').value).toEqual({ a: 1 });
+ });
+
+ it('skips a preamble before the first { … } block (CLI banner)', () => {
+ const raw = 'OpenAI Codex CLI v2.1.0\n[workdir, /tmp]\n\n{"a":1,"b":2}\n[finished]';
+ expect(extractJson(raw).value).toEqual({ a: 1, b: 2 });
+ });
+
+ it('returns the first matching block when no shape predicate is supplied', () => {
+ expect(extractJson('{"a":1} {"b":2}').value).toEqual({ a: 1 });
+ });
+
+ it('skips a pseudo-JSON schema example and picks the real response via shapePredicate', () => {
+ // Codex echoes the prompt's schema-shaped example back to stdout
+ // before the model response. extractJson must skip it and find the
+ // real expansion-shaped block.
+ const raw = [
+ '{ "label": "Crystalline canyon basin", "prompt": "vast crystalline canyon" }',
+ '{"stylePrompt":"painterly","categories":{"landscapes":{"variations":[]}}}',
+ ].join('\n');
+ const isExpansion = (o) => o && typeof o === 'object'
+ && (typeof o.stylePrompt === 'string' || typeof o.negativePrompt === 'string');
+ const { value } = extractJson(raw, { shapePredicate: isExpansion });
+ expect(value.stylePrompt).toBe('painterly');
+ });
+
+ it('falls back to the first parseable block when shapePredicate matches nothing', () => {
+ // If the predicate is too strict to match anything, the first valid
+ // block is still returned so callers can decide whether to accept
+ // the looser shape or fail with a typed error.
+ const raw = '{"a":1} {"b":2}';
+ const { value } = extractJson(raw, { shapePredicate: () => false });
+ expect(value).toEqual({ a: 1 });
+ });
+
+ it('replaces literal [...] placeholders with empty arrays so the rest parses', () => {
+ const raw = '{"stylePrompt":"x","categories":{"vehicles":{"variations":[...]}}}';
+ const { value } = extractJson(raw);
+ expect(value.stylePrompt).toBe('x');
+ expect(value.categories.vehicles.variations).toEqual([]);
+ });
+
+ it('strips trailing comma before `]`', () => {
+ const raw = '{"variations":[{"label":"a","prompt":"b"},]}';
+ const { value } = extractJson(raw);
+ expect(value.variations).toEqual([{ label: 'a', prompt: 'b' }]);
+ });
+
+ it('repairs Codex CLI orphan-brace corruption (`}}]` → `}]}`) inside the response', () => {
+ const bad = '{"stylePrompt":"x","categories":{"vehicles":{"variations":[{"label":"a","prompt":"…blister"}}]}}}';
+ const { value } = extractJson(bad);
+ expect(value.stylePrompt).toBe('x');
+ expect(value.categories.vehicles.variations).toEqual([{ label: 'a', prompt: '…blister' }]);
+ });
+
+ it('returns lastError + lastPreview when no block parses', () => {
+ const { value, lastError, lastPreview } = extractJson('{ "broken');
+ expect(value).toBeUndefined();
+ expect(lastError).toBeInstanceOf(Error);
+ expect(lastPreview).toContain('broken');
+ });
+
+ it('surfaces the concrete JSON.parse error message (not a generic "no JSON block found")', () => {
+ // Regression: when every candidate block fails parsing, `lastError`
+ // must carry the actual JSON.parse exception so downstream error
+ // context (e.g. ServerError reason) is informative.
+ const { value, lastError } = extractJson('{ "invalid": }');
+ expect(value).toBeUndefined();
+ // V8 / SpiderMonkey error messages differ but both reference JSON
+ // and contain a position marker. The important thing is that it's
+ // NOT the generic fallback message.
+ expect(lastError.message).not.toMatch(/No matching JSON block found/);
+ expect(lastError.message).toMatch(/JSON|Unexpected|token/i);
+ });
+
+ it('successfully extracts a top-level JSON `null` literal', () => {
+ // A bare `null` response is a valid JSON value — extractJson must
+ // not collapse it into a "did not parse" sentinel. Bracket-aware
+ // findBalancedBlocks won't find a block for `null` (no `{`/`[`),
+ // so the fallback `candidates.push(s)` path handles it.
+ expect(extractJson('null')).toEqual({ value: null });
+ });
+
+ it('returns an Empty-LLM-response sentinel for empty input', () => {
+ const { value, lastError } = extractJson('');
+ expect(value).toBeUndefined();
+ expect(lastError.message).toMatch(/Empty LLM response/);
+ });
+
+ it('walks arrays when blockType is array', () => {
+ const raw = 'preamble [1,2,3] postamble';
+ expect(extractJson(raw, { blockType: 'array' }).value).toEqual([1, 2, 3]);
+ });
+
+ it('does not misparse `}` inside string values (string-aware brace walker)', () => {
+ const raw = 'banner {"a":"close-brace-} inside"}';
+ expect(extractJson(raw).value).toEqual({ a: 'close-brace-} inside' });
+ });
+});
diff --git a/server/lib/promptRunner.js b/server/lib/promptRunner.js
new file mode 100644
index 0000000000..116867567d
--- /dev/null
+++ b/server/lib/promptRunner.js
@@ -0,0 +1,168 @@
+/**
+ * Shared LLM runner wrapper.
+ *
+ * Four near-identical implementations of "create run → branch on
+ * provider.type → executeCliRun/executeApiRun → accumulate streamed text
+ * → reject on error" had drifted in failure-handling:
+ *
+ * - worldBuilderExpand#callLLM — CLI: `error || success === false`, API: `error` only
+ * - stageRunner#awaitRunnerCall — CLI: `error || success === false`, API: `error` only
+ * - mediaPromptRefiner#runRefinePrompt — both: `error || success === false`
+ * - messageEvaluator#runPrompt — CLI: `error || success === false`, API: `error` only
+ *
+ * This unified runner picks the strictest discriminator: reject on
+ * `success === false` OR truthy `error` for BOTH CLI and API. The
+ * per-site drift was the bug — silent API "soft failures" (e.g. an
+ * empty completion that doesn't set `error` but does set
+ * `success: false`) used to flow through as a successful empty string.
+ *
+ * Returns `{ text, runId, model }`. `text` is the full streamed body;
+ * `runId` is the persisted run id so callers can log it and surface
+ * data/runs/<runId>/output.txt for offline debugging; `model` is the
+ * effective model that actually executed after the per-provider
+ * override gate (null when neither the caller's model nor
+ * provider.defaultModel applies). Callers should log/return THIS
+ * `model`, not the value they passed in, so logs and run records
+ * stay honest about what the runner actually executed.
+ */
+
+import { createRun, executeApiRun, executeCliRun, hasModelFlag } from '../services/runner.js';
+
+const DEFAULT_TIMEOUT_MS = 300000;
+const APPEND_CHUNK = (acc, chunk) => acc + (typeof chunk === 'string' ? chunk : (chunk?.text || ''));
+
+/**
+ * Returns true when the runner+provider pair will actually honor a
+ * per-call `model` override. For API providers the model is a
+ * first-class arg to `executeApiRun`. For CLI providers,
+ * `runner.js#buildCliArgs` now translates the resolved `defaultModel`
+ * into a `--model`/`-m` flag for codex, claude-code, AND gemini-cli —
+ * BUT only when the user hasn't already baked a model flag into
+ * `provider.args`. If a flag is baked in, the runner-injected one is
+ * suppressed and the args-baked model wins; so claim "doesn't honor"
+ * for that case to keep the run-record honest.
+ */
+export const providerHonorsModelOverride = (provider) => (
+ provider?.type === 'api'
+ || (provider?.type === 'cli' && !hasModelFlag(provider?.args))
+);
+
+/**
+ * Run a prompt through a provider and resolve with the streamed text +
+ * run id. Rejects (via the strictest discriminator) on any runner-
+ * reported failure.
+ *
+ * Per-call `model` overrides are silently dropped for providers that
+ * don't honor them (see `providerHonorsModelOverride`). This keeps the
+ * persisted run record honest about which model actually ran — passing
+ * the user's selection downstream when the runner can't apply it would
+ * make `/runs` and SSE status events lie about model usage.
+ *
+ * @param {object} args
+ * @param {object} args.provider — { id, type: 'cli'|'api', timeout?, ... }
+ * @param {string} args.prompt — full text to send to the LLM
+ * @param {string} args.source — run-record tag (`'world-builder-expansion'`,
+ * `'media-prompt-refine'`, `'messages-triage'`, `'staged-llm'`, etc.)
+ * @param {string} [args.model] — model id hint; ignored when the
+ * provider doesn't honor it (claude-code, gemini-cli today).
+ * @param {string} [args.runId] — caller-supplied run id (skip createRun
+ * round-trip when the caller has already created the run)
+ * @returns {Promise<{ text: string, runId: string, model: string|null }>}
+ * — `model` is the resolved model that actually executed (null when
+ * neither override nor provider.defaultModel applies).
+ */
+export async function runPromptThroughProvider({ provider, prompt, source, model, runId: callerRunId }) {
+ // Validate inputs up front so an accidentally-null `provider` (or one
+ // missing `id`/`type`) surfaces a clear error here instead of throwing
+ // a downstream TypeError on `provider.id` inside createRun or on the
+ // provider.type dispatch below.
+ if (!provider || typeof provider !== 'object') {
+ throw new Error('runPromptThroughProvider: provider is required');
+ }
+ if (typeof provider.id !== 'string' || !provider.id) {
+ throw new Error('runPromptThroughProvider: provider.id must be a non-empty string');
+ }
+ if (provider.type !== 'cli' && provider.type !== 'api') {
+ throw new Error(`Unsupported provider type: ${provider.type}`);
+ }
+ if (typeof prompt !== 'string' || !prompt.length) {
+ throw new Error('runPromptThroughProvider: prompt must be a non-empty string');
+ }
+ if (typeof source !== 'string' || !source.length) {
+ throw new Error('runPromptThroughProvider: source must be a non-empty string');
+ }
+
+ // Resolve the model that'll actually run BEFORE creating the run record
+ // so the record reflects reality. For providers that don't honor the
+ // override, fall back to provider.defaultModel / models[0].
+ const effectiveModel = providerHonorsModelOverride(provider)
+ ? (model || provider.defaultModel || provider.models?.[0] || null)
+ : (provider.defaultModel || provider.models?.[0] || null);
+
+ // Some call sites (stageRunner) create the run themselves so they can
+ // log the runId before the LLM call starts. When provided, reuse it.
+ // Otherwise create one here so callers always get a runId back.
+ const runId = callerRunId || (await createRun({
+ providerId: provider.id,
+ model: effectiveModel,
+ prompt,
+ source,
+ })).runId;
+
+ return new Promise((resolve, reject) => {
+ let text = '';
+ const onData = (chunk) => { text = APPEND_CHUNK(text, chunk); };
+ // Strictest discriminator: reject on either truthy `error` OR
+ // explicit `success === false`. Per-site drift was the bug.
+ const onComplete = (result) => {
+ if (result?.error || result?.success === false) {
+ reject(new Error(result?.error || `${provider.type === 'cli' ? 'CLI' : 'API'} execution failed`));
+ } else {
+ resolve({ text, runId, model: effectiveModel });
+ }
+ };
+
+ if (provider.type === 'cli') {
+ // executeCliRun reads `provider.defaultModel` for both the CLI
+ // args and the run-started metadata hook. Hand it a clone with
+ // effectiveModel in defaultModel so codex's --model flag picks
+ // up the override AND the hook reports the right model. The
+ // guard below skips the clone only when effectiveModel already
+ // equals provider.defaultModel exactly — so:
+ // - codex with a user-picked override that differs from the
+ // baked default → clone, set new defaultModel.
+ // - non-codex CLI whose defaultModel is already set: gate
+ // above forces effectiveModel = provider.defaultModel,
+ // guard skips the clone.
+ // - non-codex CLI with defaultModel unset but models[0] set:
+ // effectiveModel falls back to models[0], differs from the
+ // missing defaultModel, so we DO clone and the hook can log
+ // a real value instead of `undefined`.
+ const providerForCli = effectiveModel && effectiveModel !== provider.defaultModel
+ ? { ...provider, defaultModel: effectiveModel }
+ : provider;
+ executeCliRun(
+ runId,
+ providerForCli,
+ prompt,
+ process.cwd(),
+ onData,
+ onComplete,
+ providerForCli.timeout ?? DEFAULT_TIMEOUT_MS,
+ ).catch(reject);
+ } else if (provider.type === 'api') {
+ executeApiRun(
+ runId,
+ provider,
+ effectiveModel,
+ prompt,
+ process.cwd(),
+ [],
+ onData,
+ onComplete,
+ ).catch(reject);
+ } else {
+ reject(new Error(`Unsupported provider type: ${provider.type}`));
+ }
+ });
+}
diff --git a/server/lib/promptRunner.test.js b/server/lib/promptRunner.test.js
new file mode 100644
index 0000000000..7141ca9d5f
--- /dev/null
+++ b/server/lib/promptRunner.test.js
@@ -0,0 +1,311 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+vi.mock('../services/runner.js', () => ({
+ createRun: vi.fn(),
+ executeApiRun: vi.fn(),
+ executeCliRun: vi.fn(),
+ hasModelFlag: vi.fn(() => false),
+}));
+
+const runner = await import('../services/runner.js');
+const { runPromptThroughProvider } = await import('./promptRunner.js');
+
+const apiProvider = (extra = {}) => ({
+ id: 'mock-api', type: 'api', defaultModel: 'm-default', ...extra,
+});
+const cliProvider = (extra = {}) => ({
+ id: 'codex', type: 'cli', defaultModel: 'm-default', timeout: 5000, ...extra,
+});
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ runner.createRun.mockResolvedValue({ runId: 'run-xyz' });
+});
+
+describe('promptRunner — happy paths', () => {
+ it('routes CLI providers through executeCliRun, accumulates text, resolves { text, runId, model }', async () => {
+ runner.executeCliRun.mockImplementation(async (id, _p, _pr, _cwd, onData, onComplete, _t) => {
+ onData('hello ');
+ onData('world');
+ onComplete({ success: true });
+ });
+
+ const out = await runPromptThroughProvider({
+ provider: cliProvider(),
+ prompt: 'p',
+ source: 'test',
+ });
+
+ expect(out).toEqual({ text: 'hello world', runId: 'run-xyz', model: 'm-default' });
+ expect(runner.executeCliRun).toHaveBeenCalledTimes(1);
+ expect(runner.executeApiRun).not.toHaveBeenCalled();
+ });
+
+ it('routes API providers through executeApiRun, accumulates text, resolves { text, runId, model }', async () => {
+ runner.executeApiRun.mockImplementation(async (id, _p, _m, _pr, _cwd, _ctx, onData, onComplete) => {
+ onData('foo');
+ onData({ text: 'bar' }); // API streams sometimes ship {text} chunks
+ onComplete({ success: true });
+ });
+
+ const out = await runPromptThroughProvider({
+ provider: apiProvider(),
+ prompt: 'p',
+ source: 'test',
+ model: 'gpt-test',
+ });
+
+ expect(out).toEqual({ text: 'foobar', runId: 'run-xyz', model: 'gpt-test' });
+ expect(runner.executeApiRun).toHaveBeenCalledTimes(1);
+ expect(runner.executeCliRun).not.toHaveBeenCalled();
+ });
+
+ it('forwards the provider id + model + source to createRun', async () => {
+ runner.executeApiRun.mockImplementation(async (id, _p, _m, _pr, _cwd, _ctx, onData, onComplete) => {
+ onData('ok');
+ onComplete({ success: true });
+ });
+
+ await runPromptThroughProvider({
+ provider: apiProvider({ id: 'openai' }),
+ prompt: 'p',
+ source: 'media-prompt-refine',
+ model: 'gpt-5',
+ });
+
+ expect(runner.createRun).toHaveBeenCalledWith({
+ providerId: 'openai',
+ model: 'gpt-5',
+ prompt: 'p',
+ source: 'media-prompt-refine',
+ });
+ });
+
+ it('reuses a caller-supplied runId (no createRun round-trip)', async () => {
+ runner.executeApiRun.mockImplementation(async (id, _p, _m, _pr, _cwd, _ctx, onData, onComplete) => {
+ onData('ok');
+ onComplete({ success: true });
+ });
+
+ const out = await runPromptThroughProvider({
+ provider: apiProvider(),
+ prompt: 'p',
+ source: 't',
+ runId: 'caller-supplied-run',
+ });
+
+ expect(out.runId).toBe('caller-supplied-run');
+ expect(runner.createRun).not.toHaveBeenCalled();
+ });
+
+ it('passes a CLI provider clone with overridden defaultModel for codex (which honors --model)', async () => {
+ runner.executeCliRun.mockImplementation(async (id, providerArg, _p, _cwd, onData, onComplete, _t) => {
+ onData(`ran with model=${providerArg.defaultModel}`);
+ onComplete({ success: true });
+ });
+
+ const out = await runPromptThroughProvider({
+ provider: cliProvider({ defaultModel: 'old' }), // id: 'codex'
+ prompt: 'p',
+ source: 't',
+ model: 'new',
+ });
+
+ expect(out.text).toBe('ran with model=new');
+ });
+
+ it('clones non-codex CLI providers with the model override when args have no baked-in model flag', async () => {
+ // Post-#222: runner.js#buildCliArgs honors `provider.defaultModel`
+ // for codex / claude-code / gemini-cli when the user hasn't already
+ // baked a model flag into provider.args. So the clone is safe and
+ // the run record correctly reflects the user's selection.
+ runner.hasModelFlag.mockReturnValue(false);
+ runner.executeCliRun.mockImplementation(async (id, providerArg, _p, _cwd, onData, onComplete, _t) => {
+ onData(`ran with defaultModel=${providerArg.defaultModel}`);
+ onComplete({ success: true });
+ });
+
+ const out = await runPromptThroughProvider({
+ provider: { id: 'claude-code', type: 'cli', defaultModel: 'old', timeout: 5000, args: [] },
+ prompt: 'p',
+ source: 't',
+ model: 'user-picked-this',
+ });
+
+ expect(out.text).toBe('ran with defaultModel=user-picked-this');
+ });
+
+ it('does NOT clone CLI providers when args have a baked-in --model flag (args win)', async () => {
+ // When the user has pinned a model in provider.args, runner.js
+ // suppresses its own --model injection. Per-call override is
+ // silently dropped and the args-baked model wins — keep the run
+ // record honest by not pretending the override applied.
+ runner.hasModelFlag.mockReturnValue(true);
+ runner.executeCliRun.mockImplementation(async (id, providerArg, _p, _cwd, onData, onComplete, _t) => {
+ onData(`ran with defaultModel=${providerArg.defaultModel}`);
+ onComplete({ success: true });
+ });
+
+ const out = await runPromptThroughProvider({
+ provider: { id: 'claude-code', type: 'cli', defaultModel: 'fallback', timeout: 5000, args: ['--model', 'baked-in'] },
+ prompt: 'p',
+ source: 't',
+ model: 'user-picked-this',
+ });
+
+ expect(out.text).toBe('ran with defaultModel=fallback');
+ });
+});
+
+describe('promptRunner — strictest-discriminator rejection', () => {
+ it('rejects when CLI onComplete reports success: false (even with no error string)', async () => {
+ runner.executeCliRun.mockImplementation(async (id, _p, _pr, _cwd, _onData, onComplete, _t) => {
+ onComplete({ success: false });
+ });
+
+ await expect(runPromptThroughProvider({
+ provider: cliProvider(),
+ prompt: 'p',
+ source: 't',
+ })).rejects.toThrow(/CLI execution failed/);
+ });
+
+ it('rejects when CLI onComplete reports a non-zero error', async () => {
+ runner.executeCliRun.mockImplementation(async (id, _p, _pr, _cwd, _onData, onComplete, _t) => {
+ onComplete({ error: 'codex timeout' });
+ });
+
+ await expect(runPromptThroughProvider({
+ provider: cliProvider(),
+ prompt: 'p',
+ source: 't',
+ })).rejects.toThrow(/codex timeout/);
+ });
+
+ it('rejects when API onComplete reports success: false (this is the discriminator drift fix)', async () => {
+ // Before the unification, API sites only checked `error` and would
+ // resolve with empty text on success: false — silently swallowing
+ // soft failures. The unified runner rejects on success: false too.
+ runner.executeApiRun.mockImplementation(async (id, _p, _m, _pr, _cwd, _ctx, _onData, onComplete) => {
+ onComplete({ success: false });
+ });
+
+ await expect(runPromptThroughProvider({
+ provider: apiProvider(),
+ prompt: 'p',
+ source: 't',
+ })).rejects.toThrow(/API execution failed/);
+ });
+
+ it('rejects when API onComplete reports a non-zero error', async () => {
+ runner.executeApiRun.mockImplementation(async (id, _p, _m, _pr, _cwd, _ctx, _onData, onComplete) => {
+ onComplete({ error: 'upstream 500' });
+ });
+
+ await expect(runPromptThroughProvider({
+ provider: apiProvider(),
+ prompt: 'p',
+ source: 't',
+ })).rejects.toThrow(/upstream 500/);
+ });
+
+ it('forwards executeCliRun rejection (e.g. ensureDir/spawn failure pre-onComplete)', async () => {
+ runner.executeCliRun.mockRejectedValue(new Error('ensureDir failed'));
+ await expect(runPromptThroughProvider({
+ provider: cliProvider(),
+ prompt: 'p',
+ source: 't',
+ })).rejects.toThrow(/ensureDir failed/);
+ });
+
+ it('forwards executeApiRun rejection (toolkit not initialized, etc.)', async () => {
+ runner.executeApiRun.mockRejectedValue(new Error('AI Toolkit not initialized'));
+ await expect(runPromptThroughProvider({
+ provider: apiProvider(),
+ prompt: 'p',
+ source: 't',
+ })).rejects.toThrow(/AI Toolkit not initialized/);
+ });
+
+ it('rejects unsupported provider types up-front', async () => {
+ await expect(runPromptThroughProvider({
+ provider: { id: 'bogus', type: 'rpc' },
+ prompt: 'p',
+ source: 't',
+ })).rejects.toThrow(/Unsupported provider type: rpc/);
+ });
+
+ it('rejects when provider is null or missing entirely', async () => {
+ await expect(runPromptThroughProvider({
+ provider: null, prompt: 'p', source: 't',
+ })).rejects.toThrow(/provider is required/);
+ await expect(runPromptThroughProvider({
+ prompt: 'p', source: 't',
+ })).rejects.toThrow(/provider is required/);
+ });
+
+ it('rejects when provider.id is missing or non-string', async () => {
+ await expect(runPromptThroughProvider({
+ provider: { type: 'api' }, prompt: 'p', source: 't',
+ })).rejects.toThrow(/provider.id must be a non-empty string/);
+ await expect(runPromptThroughProvider({
+ provider: { id: '', type: 'api' }, prompt: 'p', source: 't',
+ })).rejects.toThrow(/provider.id must be a non-empty string/);
+ });
+
+ it('rejects when prompt or source is missing/empty', async () => {
+ await expect(runPromptThroughProvider({
+ provider: apiProvider(), prompt: '', source: 't',
+ })).rejects.toThrow(/prompt must be a non-empty string/);
+ await expect(runPromptThroughProvider({
+ provider: apiProvider(), prompt: 'p', source: '',
+ })).rejects.toThrow(/source must be a non-empty string/);
+ });
+});
+
+describe('promptRunner — multi-chunk text accumulation', () => {
+ it('accumulates many CLI string chunks in order', async () => {
+ runner.executeCliRun.mockImplementation(async (id, _p, _pr, _cwd, onData, onComplete, _t) => {
+ for (const c of ['a', 'b', 'c', 'd', 'e']) onData(c);
+ onComplete({ success: true });
+ });
+ const out = await runPromptThroughProvider({
+ provider: cliProvider(),
+ prompt: 'p',
+ source: 't',
+ });
+ expect(out.text).toBe('abcde');
+ });
+
+ it('accumulates mixed string + {text} API chunks in order', async () => {
+ runner.executeApiRun.mockImplementation(async (id, _p, _m, _pr, _cwd, _ctx, onData, onComplete) => {
+ onData('A');
+ onData({ text: 'B' });
+ onData({ text: 'C' });
+ onData('D');
+ onComplete({ success: true });
+ });
+ const out = await runPromptThroughProvider({
+ provider: apiProvider(),
+ prompt: 'p',
+ source: 't',
+ });
+ expect(out.text).toBe('ABCD');
+ });
+
+ it('ignores non-string non-{text} chunks (e.g. heartbeat events)', async () => {
+ runner.executeApiRun.mockImplementation(async (id, _p, _m, _pr, _cwd, _ctx, onData, onComplete) => {
+ onData('hello');
+ onData({ heartbeat: true }); // chunk with no text — ignored
+ onData(null); // ignored
+ onData(' world');
+ onComplete({ success: true });
+ });
+ const out = await runPromptThroughProvider({
+ provider: apiProvider(),
+ prompt: 'p',
+ source: 't',
+ });
+ expect(out.text).toBe('hello world');
+ });
+});
diff --git a/server/lib/stageRunner.js b/server/lib/stageRunner.js
index b0a2a50d78..9c5c3954cb 100644
--- a/server/lib/stageRunner.js
+++ b/server/lib/stageRunner.js
@@ -15,10 +15,12 @@
*/
import { ServerError } from './errorHandler.js';
+import { findBalancedBlocks, tryParseWithRepair } from './jsonExtract.js';
+import { providerHonorsModelOverride, runPromptThroughProvider } from './promptRunner.js';
import { stripCodeFences } from './aiProvider.js';
import { getActiveProvider, getProviderById } from '../services/providers.js';
import { buildPrompt, getStage } from '../services/promptService.js';
-import { createRun, executeApiRun, executeCliRun } from '../services/runner.js';
+import { createRun } from '../services/runner.js';
// Stage configs name a model by tier (PromptManager UI). Map each tier name
// to the provider's per-tier model field; an unset tier falls through to
@@ -75,73 +77,94 @@ async function resolveProviderForStage(stage, { providerOverride } = {}) {
throw new ServerError('No AI provider available', { status: 503, code: 'NO_PROVIDER' });
}
-// Wraps executeApiRun / executeCliRun as a Promise so callers can await one
-// completion. Mirrors the pattern in worldBuilderExpand.js#callLLM — both
-// runner entry points are async and can reject before onComplete fires, so
-// we forward those rejections through the outer Promise instead of letting
-// them surface as unhandledRejection (Node ≥15 process-killer).
-function awaitRunnerCall({ provider, model, prompt, runId, source }) {
- return new Promise((resolve, reject) => {
- let text = '';
- if (provider.type === 'cli') {
- // executeCliRun reads `provider.defaultModel` for both the CLI args
- // (`buildCliArgs(provider)`) and the run-started metadata hook. The
- // toolkit's CLI entry doesn't accept a separate model param, so to
- // honor a stage-level model override (or a tier-name resolution like
- // `model: 'heavy'`) we hand it a shallow clone with the resolved
- // model in `defaultModel`. Without this, `runStagedLLM(..., { modelOverride: 'codex-mini' })`
- // would silently fall back to the provider's stock default AND the
- // run record would log the wrong model.
- const providerForCli = model && model !== provider.defaultModel
- ? { ...provider, defaultModel: model }
- : provider;
- executeCliRun(
- runId,
- providerForCli,
- prompt,
- process.cwd(),
- (chunk) => { text += chunk; },
- (result) => {
- if (result?.error || result?.success === false) {
- reject(new Error(result?.error || 'CLI execution failed'));
- } else {
- resolve(text);
- }
- },
- providerForCli.timeout ?? 300000,
- ).catch(reject);
- } else if (provider.type === 'api') {
- executeApiRun(
- runId,
- provider,
- model,
- prompt,
- process.cwd(),
- [],
- (data) => { text += typeof data === 'string' ? data : (data?.text || ''); },
- (result) => {
- if (result?.error) reject(new Error(result.error));
- else resolve(text);
- },
- ).catch(reject);
- } else {
- reject(new Error(`Unsupported provider type: ${provider.type}`));
- }
- });
-}
-
/**
* Extract the first balanced object/array from an LLM response. Some
* providers prepend explanation prose; the prompt asks for JSON only but
- * we have to be defensive. Lifted from the writers-room evaluator so the
- * pipeline gets the same lenient parser when it eventually requests JSON.
+ * we have to be defensive. Walks the same fence-stripped text as
+ * `lib/jsonExtract` so stages benefit from string-aware brace walking +
+ * Codex `}}]` and trailing-comma repairs.
+ *
+ * Picks the earliest *parseable* top-level block, regardless of whether
+ * it's an object or array. This is the only safe heuristic given:
+ * - Banner lines like `[workdir, /tmp]` precede the real JSON, so
+ * `indexOf('[')` is a lying delimiter peek.
+ * - An object response may legitimately contain an inner array field
+ * (e.g. `{"a":[1,2]}`), and a raw walker run with `blockType: 'array'`
+ * would happily return that `[1,2]` if asked.
+ * By gathering balanced candidates for BOTH shapes, parsing each in
+ * source order, and returning the first that parses, banners get
+ * skipped (their contents don't parse as JSON) and the wrapper shape
+ * is preserved (`[{"a":1}]` parses as the array; `{"a":[1,2]}` parses
+ * as the object because the `{` opener comes before the inner `[`).
+ *
+ * When `promptToStrip` is supplied, any verbatim occurrence of that
+ * string is removed from `text` BEFORE walking. This handles CLI
+ * runners (notably Codex) that echo the input prompt to stdout — the
+ * prompt itself frequently contains fenced JSON schema examples that
+ * would otherwise parse and win on source-order ranking. Stripping
+ * the echo leaves only the model's actual response in the text the
+ * walker sees.
*/
-export function extractJson(text) {
+export function extractJson(text, { promptToStrip } = {}) {
if (!text || typeof text !== 'string') throw new Error('Empty AI response');
- let str = stripCodeFences(text);
- const objMatch = str.match(/[{[][\s\S]*[\]}]/);
- if (objMatch) str = objMatch[0];
- return JSON.parse(str);
+ if (typeof promptToStrip === 'string' && promptToStrip) {
+ // Remove every verbatim occurrence so we don't have to guess where
+ // a CLI runner inserted line wrapping or trim. The prompt is fixed
+ // text we built ourselves a few lines up — split-join is safer
+ // than building a regex (which would need escaping).
+ text = text.split(promptToStrip).join('');
+ }
+
+ // Trim leading + trailing fences via stripCodeFences (note: it strips
+ // each side independently, so a response that only has a leading
+ // ```json with no closing fence will still get its opener removed —
+ // that's intentional and matches every other JSON-from-LLM helper in
+ // the codebase). What we DELIBERATELY do NOT do here is grab the
+ // first inner ```…``` fenced block: on Codex CLI runs the prompt
+ // itself can echo to stdout before the model response, and many
+ // stage prompts contain fenced JSON schema examples that would
+ // precede the real answer. Walking the whole text with
+ // findBalancedBlocks is safer — an echoed schema either parses
+ // (and gets ranked by source order) or fails parse-with-repair and
+ // is silently skipped in favor of the real response.
+ const s = stripCodeFences(text.trim());
+
+ // Collect candidates of BOTH shapes with their source-text positions.
+ // findBalancedBlocks returns block substrings in order; indexOf gives
+ // us the start so we can interleave the two shape lists.
+ const candidates = [];
+ let cursor = 0;
+ for (const block of findBalancedBlocks(s, { startChar: '{', endChar: '}' })) {
+ const idx = s.indexOf(block, cursor);
+ candidates.push({ block, start: idx });
+ cursor = idx + block.length;
+ }
+ cursor = 0;
+ for (const block of findBalancedBlocks(s, { startChar: '[', endChar: ']' })) {
+ const idx = s.indexOf(block, cursor);
+ candidates.push({ block, start: idx });
+ cursor = idx + block.length;
+ }
+ candidates.sort((a, b) => a.start - b.start);
+
+ // Fall back to the raw text if neither shape walker found anything —
+ // the response might still be parseable JSON (e.g. a bare number or
+ // string literal). tryParseWithRepair handles those too.
+ if (!candidates.length) candidates.push({ block: s, start: 0 });
+
+ let lastError;
+ for (const { block } of candidates) {
+ const parsed = tryParseWithRepair(block);
+ if (!parsed.error) return parsed.value;
+ lastError = parsed.error;
+ }
+
+ // No fallback to jsonExtract.extractJson here: that helper grabs the
+ // first inner ```…``` fenced block, which is exactly the prompt-echo
+ // failure mode this implementation was rewritten to avoid. Surface
+ // the last parse error from the candidate loop so callers see the
+ // concrete reason instead of a generic "no JSON block found".
+ throw new Error(`Invalid JSON in AI response: ${lastError?.message || 'no JSON block found'}`);
}
/**
@@ -159,22 +182,36 @@ export async function runStagedLLM(stageName, variables, options = {}) {
const stage = getStage(stageName);
const provider = await resolveProviderForStage(stage, options);
const prompt = await buildPrompt(stageName, variables);
- let model = resolveModel(provider, options.modelOverride || stage?.model);
- // Special case: gemini-cli requires an explicit model — toolkit defaults
- // to `auto` which can resolve to a slow reasoning model (LM Studio gotcha).
- if (provider.id === 'gemini-cli' && !model) {
- model = provider.lightModel || 'gemini-2.5-flash';
- }
+ const resolvedModel = resolveModel(provider, options.modelOverride || stage?.model);
+ // Non-codex CLI providers ignore per-call model overrides at the
+ // runner.js#buildCliArgs layer, so recording the resolved model in
+ // createRun would lie about what actually ran. Drop the override at
+ // the record + log boundary for those providers — promptRunner does
+ // the same internally. PLAN.md tracks extending buildCliArgs to honor
+ // per-call model for all CLI providers; once that lands the gate goes
+ // away (and the gemini-cli fast-model fallback can be reintroduced
+ // here, since today it would be silently dropped anyway).
+ const effectiveModel = providerHonorsModelOverride(provider)
+ ? resolvedModel
+ : (provider.defaultModel || provider.models?.[0] || null);
const { runId } = await createRun({
providerId: provider.id,
- model,
+ model: effectiveModel,
prompt,
source: options.source || 'staged-llm',
});
- console.log(`📝 stage: ${provider.id} / ${model || '(default)'} / ${stageName} → ${runId.slice(0, 8)}`);
+ console.log(`📝 stage: ${provider.id} / ${effectiveModel || '(default)'} / ${stageName} → ${runId.slice(0, 8)}`);
- const text = await awaitRunnerCall({ provider, model, prompt, runId, source: options.source });
- const content = options.returnsJson ? extractJson(text) : text;
- return { content, model: model || null, providerId: provider.id, runId };
+ // Stage runs pre-create the run record (so the runId can be logged BEFORE
+ // the LLM call starts), then thread that id through the shared runner.
+ const { text } = await runPromptThroughProvider({
+ provider, model: effectiveModel, prompt, source: options.source || 'staged-llm', runId,
+ });
+ // Pass the prompt down so extractJson can strip any echoed copy of
+ // it before walking — Codex CLI echoes stdin to stdout, and stage
+ // prompts often contain fenced JSON schema examples that would
+ // otherwise parse-and-win over the model's actual response.
+ const content = options.returnsJson ? extractJson(text, { promptToStrip: prompt }) : text;
+ return { content, model: effectiveModel || null, providerId: provider.id, runId };
}
diff --git a/server/lib/stageRunner.test.js b/server/lib/stageRunner.test.js
index 1270181094..d98a357548 100644
--- a/server/lib/stageRunner.test.js
+++ b/server/lib/stageRunner.test.js
@@ -14,6 +14,7 @@ vi.mock('../services/runner.js', () => ({
createRun: vi.fn(async () => ({ runId: 'run-abc12345' })),
executeApiRun: vi.fn(),
executeCliRun: vi.fn(),
+ hasModelFlag: vi.fn(() => false),
}));
const providers = await import('../services/providers.js');
@@ -77,6 +78,52 @@ describe('stageRunner — extractJson', () => {
it('parses an array', () => {
expect(extractJson('[1,2,3]')).toEqual([1, 2, 3]);
});
+ it('preserves an array-of-objects wrapper instead of grabbing the inner object', () => {
+ // Regression: an "object-first then array-fallback" strategy used to
+ // return `{"a":1}` from `[{"a":1},{"a":2}]`, silently dropping the
+ // array wrapper. The current strategy walks balanced candidates for
+ // BOTH shapes, sorts by source-text start position, and returns the
+ // first that parses — so the array opener at position 0 wins over
+ // the inner object opener at position 1.
+ expect(extractJson('[{"a":1},{"a":2}]')).toEqual([{ a: 1 }, { a: 2 }]);
+ });
+ it('preserves an array-of-objects wrapper inside a fenced response', () => {
+ expect(extractJson('```json\n[{"id":"x"}]\n```')).toEqual([{ id: 'x' }]);
+ });
+ it('still extracts a leading object when an array appears later in prose', () => {
+ expect(extractJson('Sure! {"a":1} (example array later: [1,2])')).toEqual({ a: 1 });
+ });
+ it('skips a Codex CLI banner `[workdir, /tmp]` and returns the actual object', () => {
+ // Regression: a raw `indexOf('[') < indexOf('{')` peek would prefer
+ // array-mode and (in the worst case) return an inner array field
+ // instead of the wrapping object. Earliest-parseable-block ordering
+ // skips the banner because its contents don't parse as JSON.
+ const raw = 'OpenAI Codex CLI v2.1.0\n[workdir, /tmp]\n\n{"a":1,"b":[2,3]}\n[finished]';
+ expect(extractJson(raw)).toEqual({ a: 1, b: [2, 3] });
+ });
+ it('returns the wrapping object — not its inner array field — when both walks succeed', () => {
+ // Object opener comes before the inner array opener, so the object
+ // wins on earliest-start ordering.
+ expect(extractJson('{"items":[1,2,3]}')).toEqual({ items: [1, 2, 3] });
+ });
+ it('strips a known echoed prompt before walking so the real response wins', () => {
+ // Regression: Codex CLI echoes stdin to stdout, so when a stage
+ // prompt contains a fenced JSON schema example, both that schema
+ // AND the model's actual response are present in the captured
+ // text. Picking by source order returns the schema (placeholder
+ // data). Passing the prompt verbatim lets extractJson strip the
+ // echo first, so the response wins.
+ const prompt = 'Prompt echo:\n```json\n{"_schema":"example"}\n```';
+ const raw = `${prompt}\n\nResponse:\n{"answer":42}`;
+ expect(extractJson(raw, { promptToStrip: prompt })).toEqual({ answer: 42 });
+ });
+ it('without promptToStrip, an echoed schema block still wins on source order (documents the failure mode)', () => {
+ // This is the failure mode that runStagedLLM avoids by ALWAYS
+ // passing the prompt down. Kept here so future contributors who
+ // bypass the stripping path know they have to provide it.
+ const raw = 'Prompt echo:\n```json\n{"_schema":"example"}\n```\n\nResponse:\n{"answer":42}';
+ expect(extractJson(raw)).toEqual({ _schema: 'example' });
+ });
it('throws on empty or non-string input', () => {
expect(() => extractJson('')).toThrow(/Empty AI response/);
expect(() => extractJson(null)).toThrow(/Empty AI response/);
diff --git a/server/services/mediaPromptRefiner.js b/server/services/mediaPromptRefiner.js
index 899270ccae..b132d400d1 100644
--- a/server/services/mediaPromptRefiner.js
+++ b/server/services/mediaPromptRefiner.js
@@ -1,6 +1,8 @@
import { ServerError } from '../lib/errorHandler.js';
+import { findBalancedBlocks, tryParseWithRepair } from '../lib/jsonExtract.js';
+import { runPromptThroughProvider } from '../lib/promptRunner.js';
import { getProviderById } from './providers.js';
-import { createRun, executeApiRun, executeCliRun, hasModelFlag, extractBakedModel } from './runner.js';
+import { hasModelFlag, extractBakedModel } from './runner.js';
const MAX_PROMPT_LEN = 8000;
const MAX_REASON_LEN = 1200;
@@ -24,49 +26,36 @@ const isPlaceholderPrompt = (s) => typeof s === 'string' && /^\s*<.+>\s*$/.test(
// Codex CLI prepends a banner like `OpenAI Codex CLI...` and `[workdir, /…]`
// metadata before the model's JSON output, AND echoes the input prompt to
// stdout (which contains the schema example {…}). Walk braces with string-
-// awareness, skip any block whose `prompt` is a placeholder, and return the
-// first remaining block that parses as an object with a `prompt` field.
+// awareness via the shared lib, skip any block whose `prompt` is a
+// placeholder, and return the first remaining block that parses as an
+// object with a `prompt` field.
function extractRefinementJson(raw) {
if (typeof raw !== 'string' || !raw.trim()) throw new Error('Empty AI response');
let s = raw.trim();
const fence = s.match(/```(?:json)?\s*([\s\S]*?)```/);
if (fence) s = fence[1].trim();
- let i = 0;
- let lastErr;
+ const candidates = findBalancedBlocks(s);
+ if (!candidates.length) candidates.push(s);
+
+ // Walk every balanced block ourselves rather than calling the shared
+ // extractJson — we need a tri-state outcome (real refinement, placeholder
+ // echo, or parse error) to surface the "schema placeholder" error message
+ // that helps users pick a stronger model. extractJson's shape predicate
+ // collapses placeholder-vs-real into a single fallback path.
let placeholderSeen = false;
- while (i < s.length) {
- const start = s.indexOf('{', i);
- if (start === -1) break;
- let depth = 0;
- let inString = false;
- let escaped = false;
- let end = -1;
- for (let j = start; j < s.length; j++) {
- const ch = s[j];
- if (inString) {
- if (escaped) escaped = false;
- else if (ch === '\\') escaped = true;
- else if (ch === '"') inString = false;
- continue;
- }
- if (ch === '"') { inString = true; continue; }
- if (ch === '{') depth++;
- else if (ch === '}') {
- depth--;
- if (depth === 0) { end = j; break; }
- }
+ let lastErr;
+ for (const block of candidates) {
+ const result = tryParseWithRepair(block);
+ if (result.error) {
+ lastErr = result.error;
+ continue;
+ }
+ const { value } = result;
+ if (value && typeof value === 'object' && typeof value.prompt === 'string') {
+ if (isPlaceholderPrompt(value.prompt)) { placeholderSeen = true; }
+ else return value;
}
- if (end === -1) break;
- const block = s.slice(start, end + 1);
- try {
- const value = JSON.parse(block);
- if (value && typeof value === 'object' && typeof value.prompt === 'string') {
- if (isPlaceholderPrompt(value.prompt)) { placeholderSeen = true; }
- else return value;
- }
- } catch (e) { lastErr = e; }
- i = end + 1;
}
if (placeholderSeen) {
throw new Error('AI returned the schema placeholder instead of a real refinement — try a stronger model or rerun');
@@ -115,37 +104,19 @@ ${feedback}`;
// shapes that the toolkit runner already knows about — going through the
// runner avoids the "stdin is not a terminal" failure mode that hits when
// you spawn `codex` directly without the `exec -` invocation.
-async function runRefinePrompt(provider, model, prompt) {
- const { runId } = await createRun({
- providerId: provider.id,
+//
+// promptRunner already drops the per-call model for providers that don't
+// honor it (see providerHonorsModelOverride), so we pass `model` through
+// unconditionally and let the shared layer decide. Wrap runner failures
+// in a typed ServerError so the route returns 502 PROMPT_REFINE_FAILED.
+function runRefinePrompt(provider, model, prompt) {
+ return runPromptThroughProvider({
+ provider,
model,
prompt,
source: 'media-prompt-refine',
- });
-
- let text = '';
- return await new Promise((resolve, reject) => {
- const onData = (chunk) => { text += typeof chunk === 'string' ? chunk : (chunk?.text || ''); };
- const onComplete = (result) => {
- if (result?.error || result?.success === false) {
- reject(new ServerError(result?.error || 'Prompt refinement failed', { status: 502, code: 'PROMPT_REFINE_FAILED' }));
- } else {
- resolve({ text, runId });
- }
- };
- if (provider.type === 'cli') {
- // `runner.js#buildCliArgs` honors `provider.defaultModel` for every
- // supported CLI provider (codex / claude-code / gemini-cli) — it
- // injects `--model` / `-m` whenever the user hasn't already baked a
- // model flag into provider.args. So cloning with an overridden
- // defaultModel is safe for all CLI types.
- const providerForCli = model && model !== provider.defaultModel
- ? { ...provider, defaultModel: model }
- : provider;
- executeCliRun(runId, providerForCli, prompt, process.cwd(), onData, onComplete, provider.timeout ?? 300000).catch(reject);
- } else {
- executeApiRun(runId, provider, model, prompt, process.cwd(), [], onData, onComplete).catch(reject);
- }
+ }).catch((err) => {
+ throw new ServerError(err?.message || 'Prompt refinement failed', { status: 502, code: 'PROMPT_REFINE_FAILED' });
});
}
diff --git a/server/services/messageEvaluator.js b/server/services/messageEvaluator.js
index f70b1b73f3..34cc8677fa 100644
--- a/server/services/messageEvaluator.js
+++ b/server/services/messageEvaluator.js
@@ -2,9 +2,9 @@ import { readFile } from 'fs/promises';
import { join } from 'path';
import { getSettings } from './settings.js';
import { getProviderById, getAllProviders } from './providers.js';
-import { createRun, executeApiRun, executeCliRun } from './runner.js';
import { buildRulesPromptSection } from './messageTriageRules.js';
import { PATHS } from '../lib/fileUtils.js';
+import { runPromptThroughProvider } from '../lib/promptRunner.js';
const EVAL_PROMPT = `You are an email triage assistant. For each email below, recommend ONE action and a brief reason.
@@ -70,27 +70,12 @@ async function resolveProviderConfig(actionType) {
}
async function runPrompt(provider, model, prompt, source) {
- const selectedModel = model || provider.defaultModel || provider.models?.[0];
- const { runId } = await createRun({ providerId: provider.id, model: selectedModel, prompt, source });
-
- let responseText = '';
- await new Promise((resolve, reject) => {
- if (provider.type === 'cli') {
- executeCliRun(
- runId, provider, prompt, process.cwd(),
- (text) => { responseText += text; },
- (result) => { result?.error || result?.success === false ? reject(new Error(result?.error || 'CLI execution failed')) : resolve(result); },
- provider.timeout || 300000
- );
- } else {
- executeApiRun(
- runId, provider, selectedModel, prompt, process.cwd(), [],
- (data) => { responseText += typeof data === 'string' ? data : (data?.text || ''); },
- (result) => { result?.error ? reject(new Error(result.error)) : resolve(result); }
- );
- }
- });
- return responseText;
+ // promptRunner internally gates per-call model overrides for providers
+ // that don't honor them (non-codex CLI). Surface the effective model
+ // it actually used so callers can log it accurately instead of echoing
+ // back the (possibly-dropped) input model.
+ const { text, model: effectiveModel } = await runPromptThroughProvider({ provider, model, prompt, source });
+ return { text, model: effectiveModel };
}
function parseEvalResponse(text, messageIds) {
@@ -130,8 +115,9 @@ export async function evaluateMessages(messages) {
const rulesSection = await buildRulesPromptSection();
const prompt = EVAL_PROMPT + rulesSection + JSON.stringify(payload, null, 2) + '\n' + EVAL_PROMPT_SUFFIX;
- console.log(`📧 Evaluating ${messages.length} messages with ${provider.name}/${model || provider.defaultModel}`);
- const response = await runPrompt(provider, model, prompt, 'messages-triage');
+ console.log(`📧 Evaluating ${messages.length} messages with ${provider.name}`);
+ const { text: response, model: effectiveModel } = await runPrompt(provider, model, prompt, 'messages-triage');
+ console.log(`📧 Triage ran on ${provider.name}/${effectiveModel || '(default)'}`);
const messageIds = new Set(messages.map(m => m.id));
const evaluations = parseEvalResponse(response, messageIds);
@@ -230,7 +216,8 @@ export async function generateReplyBody(message, instructions = '', options = {}
if (threadContext) template += threadContext;
const voiceLabel = shouldUseVoice ? ' with voice' : '';
- console.log(`📧 Generating AI reply${voiceLabel} with ${provider.name}/${model || provider.defaultModel}`);
- const response = await runPrompt(provider, model, template, 'messages-reply');
+ console.log(`📧 Generating AI reply${voiceLabel} with ${provider.name}`);
+ const { text: response, model: effectiveModel } = await runPrompt(provider, model, template, 'messages-reply');
+ console.log(`📧 Reply ran on ${provider.name}/${effectiveModel || '(default)'}`);
return { body: response.trim() };
}
diff --git a/server/services/worldBuilderExpand.js b/server/services/worldBuilderExpand.js
index 391f9c4c41..b55d88f60f 100644
--- a/server/services/worldBuilderExpand.js
+++ b/server/services/worldBuilderExpand.js
@@ -11,7 +11,6 @@
* model so the UI still works for users who haven't configured a stage.
*/
-import { executeApiRun, executeCliRun, createRun } from './runner.js';
import { getActiveProvider, getProviderById } from './providers.js';
import {
WORLD_CATEGORIES,
@@ -22,6 +21,8 @@ import {
sanitizeCompositeSheets,
} from './worldBuilder.js';
import { ServerError } from '../lib/errorHandler.js';
+import { extractJson as extractJsonShared } from '../lib/jsonExtract.js';
+import { providerHonorsModelOverride, runPromptThroughProvider } from '../lib/promptRunner.js';
const LABEL_MAX = 80;
@@ -67,169 +68,34 @@ Concrete compositeSheets examples:
- If the world needs pitch posters, do not put "text" in the negativePrompt. Prefer "watermark, logo, unreadable tiny text, text artifacts" so title/section typography remains possible.
- Output JUST the JSON object. No prose before or after.`;
-const isCliProvider = (provider) => provider?.type === 'cli';
-
-// Awaiting createRun separately keeps the Promise executor synchronous —
-// an `async` executor body silently swallows rejected awaits, leaving the
-// caller's Promise hanging forever if createRun throws.
-// Returns { text, runId } — runId is logged so a user debugging an empty
-// expansion can find the raw stdout at data/runs/<runId>/output.txt.
-async function callLLM(provider, model, prompt) {
- const { runId } = await createRun({
- providerId: provider.id,
- model,
- prompt,
- source: 'world-builder-expansion',
- });
- return new Promise((resolve, reject) => {
- let text = '';
- // Both executeCliRun / executeApiRun are async — they can reject before
- // onComplete ever fires (ensureDir/read/write failures, toolkit not
- // initialized, provider errors). Without a rejection handler the awaiter
- // would hang forever and Node would log an unhandledRejection. Forward
- // the rejection through `reject` so callLLM() always settles.
- if (isCliProvider(provider)) {
- executeCliRun(
- runId,
- provider,
- prompt,
- process.cwd(),
- (chunk) => { text += chunk; },
- (result) => {
- if (result?.error || result?.success === false) {
- reject(new Error(result?.error || 'CLI execution failed'));
- } else {
- resolve({ text, runId });
- }
- },
- provider.timeout ?? 300000,
- ).catch(reject);
- } else {
- executeApiRun(
- runId,
- provider,
- model,
- prompt,
- process.cwd(),
- [],
- (data) => { text += typeof data === 'string' ? data : (data?.text || ''); },
- (result) => {
- if (result?.error) reject(new Error(result.error));
- else resolve({ text, runId });
- },
- ).catch(reject);
- }
- });
-}
-
-// Walk the string and return every top-level brace-balanced { … } block, in
-// order. String-aware so braces inside JSON string values don't throw off the
-// depth counter. Used by extractJson — Codex CLI echoes the user prompt back
-// to stdout before the model response, and the prompt itself contains a
-// JSON-shaped *schema example* (e.g. `{ "label": string (max 80 chars), … }`)
-// whose braces balance but whose contents are not valid JSON. Returning every
-// block lets the caller try each in turn instead of giving up on the first.
-const findBalancedBlocks = (s) => {
- const blocks = [];
- let i = 0;
- while (i < s.length) {
- const start = s.indexOf('{', i);
- if (start === -1) break;
- let depth = 0;
- let inString = false;
- let escaped = false;
- let end = -1;
- for (let j = start; j < s.length; j += 1) {
- const ch = s[j];
- if (inString) {
- if (escaped) escaped = false;
- else if (ch === '\\') escaped = true;
- else if (ch === '"') inString = false;
- continue;
- }
- if (ch === '"') { inString = true; continue; }
- if (ch === '{') depth += 1;
- else if (ch === '}') {
- depth -= 1;
- if (depth === 0) { end = j; break; }
- }
- }
- if (end === -1) break; // unbalanced — no later block can balance either
- blocks.push(s.slice(start, end + 1));
- i = end + 1;
- }
- return blocks;
-};
-
-// Try JSON.parse on a candidate block; if it fails, attempt a few cheap
-// repairs that handle observed LLM corruption patterns:
-// - Codex CLI sometimes emits an EXTRA `}` between a variation's close-brace
-// and its enclosing array's `]` (`}}]}}}` instead of `}]}}}`). Brace
-// balance still works because the extra `{` was hallucinated upstream.
-// - Trailing comma before `]` or `}`.
-// We try removing/normalizing one suspicious char at a time, capped at a few
-// attempts so a genuinely broken block still bubbles a parse error.
-const tryParseWithRepair = (block) => {
- try { return { value: JSON.parse(block) }; } catch (initialErr) {
- // Remove trailing commas before `}` or `]` (common LLM mistake).
- let candidate = block.replace(/,(\s*[}\]])/g, '$1');
- if (candidate !== block) {
- try { return { value: JSON.parse(candidate) }; } catch { /* keep trying */ }
- }
- // Fix Codex's `}}]` → `}]}` pattern: the variation object closes
- // correctly, then an orphan `}` lands BEFORE the array's `]` instead of
- // after it. Swapping (not dropping) keeps the brace count correct so the
- // outer container still closes — dropping the brace would leave a
- // dangling object open further out.
- candidate = candidate.replace(/}\s*}\s*]/g, '}]}');
- try { return { value: JSON.parse(candidate) }; } catch (err) {
- return { error: err };
- }
- }
-};
+// Prefer a block that *looks like* a world-expansion response (has any of
+// stylePrompt / negativePrompt / categories / compositeSheets at the top
+// level). The expansion prompt includes literal JSON examples like
+// { "label": "Crystalline canyon basin", "prompt": "…" }
+// which parse cleanly but aren't the response. Without the shape preference
+// we'd return that first valid-but-wrong object and end up with 0 variations.
+const isExpansionShape = (o) => o && typeof o === 'object'
+ && (typeof o.stylePrompt === 'string'
+ || typeof o.negativePrompt === 'string'
+ || (o.categories && typeof o.categories === 'object')
+ || Array.isArray(o.compositeSheets));
const extractJson = (raw) => {
+ // Empty input is a "client-side" oversight (no LLM output at all) — keep
+ // the original raw Error so callers / tests that key on the message
+ // continue to match. Down-stream JSON parse failures are wrapped in a
+ // typed 502 ServerError so the route layer surfaces a useful HTTP code.
if (!raw || typeof raw !== 'string') throw new Error('Empty LLM response');
- let s = raw.trim();
- // Strip ```json fences if present.
- const fence = s.match(/```(?:json)?\s*([\s\S]*?)```/);
- if (fence) s = fence[1].trim();
- // Try each brace-balanced block in order. This skips preamble ("Here is…"),
- // prompt echoes (Codex CLI), and pseudo-JSON schema examples in the prompt.
- // We prefer a block that *looks like* a world-expansion response (has any of
- // stylePrompt / negativePrompt / categories at the top level) — the prompt
- // template includes small JSON examples like
- // { "label": "Crystalline canyon basin", "prompt": "…" }
- // which parse cleanly but aren't the response. Without the shape preference
- // we'd return that first valid-but-wrong object and end up with 0 variations.
- const candidates = findBalancedBlocks(s);
- if (!candidates.length) candidates.push(s);
- const isExpansionShape = (o) => o && typeof o === 'object'
- && (typeof o.stylePrompt === 'string' || typeof o.negativePrompt === 'string' || (o.categories && typeof o.categories === 'object') || Array.isArray(o.compositeSheets));
- let firstParsed;
- let lastErr;
- let lastPreview = s;
- for (const block of candidates) {
- // Recovery: some LLMs (notably Codex CLI) echo the prompt's `[...]`
- // schema-notation back as a literal value. Replace such empty-placeholder
- // arrays with `[]` so the rest of the parse can succeed.
- const cleaned = block.replace(/\[\s*\.\.\.\s*\]/g, '[]');
- const { value: parsed, error } = tryParseWithRepair(cleaned);
- if (parsed !== undefined) {
- if (isExpansionShape(parsed)) return parsed;
- if (firstParsed === undefined) firstParsed = parsed;
- } else {
- lastErr = error;
- lastPreview = cleaned;
- }
- }
- if (firstParsed !== undefined) return firstParsed;
+ const { value, lastError, lastPreview } = extractJsonShared(raw, {
+ shapePredicate: isExpansionShape,
+ });
+ if (value !== undefined) return value;
throw new ServerError(
'LLM returned invalid JSON for world expansion. Try a different model or rerun.',
{
status: 502,
code: 'LLM_INVALID_JSON',
- context: { details: { reason: lastErr?.message || 'no JSON object found', preview: lastPreview.slice(0, 200) } },
+ context: { details: { reason: lastError?.message || 'no JSON object found', preview: lastPreview || '' } },
},
);
};
@@ -295,12 +161,24 @@ export async function expandWorldTemplate({ starterPrompt, providerId, model } =
let provider = providerId ? await getProviderById(providerId).catch(() => null) : null;
if (!provider) provider = await getActiveProvider();
if (!provider) throw new Error('No AI provider available for world expansion');
- const selectedModel = model || provider.defaultModel || provider.models?.[0];
+ // Mirror the gate that promptRunner applies internally so the log line
+ // and the returned `llm.model` field reflect what'll actually execute.
+ // Non-codex CLI providers ignore the per-call model.
+ const selectedModel = providerHonorsModelOverride(provider)
+ ? (model || provider.defaultModel || provider.models?.[0])
+ : (provider.defaultModel || provider.models?.[0]);
const fullPrompt = EXPANSION_PROMPT.replace('{starterPrompt}', starterPrompt.trim());
console.log(`🌍 World Builder expanding via ${provider.name}/${selectedModel || 'default'}`);
- const { text: raw, runId } = await callLLM(provider, selectedModel, fullPrompt);
+ // runId is logged so a user debugging an empty expansion can find the
+ // raw stdout at data/runs/<runId>/output.txt.
+ const { text: raw, runId } = await runPromptThroughProvider({
+ provider,
+ model: selectedModel,
+ prompt: fullPrompt,
+ source: 'world-builder-expansion',
+ });
// Log raw response shape so a "0 variations" outcome is debuggable from
// the server console alone — the runId points at data/runs/<id>/output.txt
// for the full transcript.