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(ai): route every AI call through one central handler, add TUI support (#255)

[._.]/ Adam Eivy719bc4feb38e
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index b9b88affb6..45c7d853a4 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -11,6 +11,8 @@
## Changed
+- **TUI providers now work for every AI action.** Previously, picking a `type: "tui"` provider (Claude Code TUI, Codex TUI, Gemini TUI) for pipeline prose, refines, or any other staged-LLM call crashed with `Unsupported provider type: tui` because `runPromptThroughProvider` only handled `cli`/`api`. New `executeTuiRun` in `server/lib/tuiPromptRunner.js` spawns the TUI binary directly via `node-pty` (no shell wrapper, no shared-session cap), pastes the prompt via bracketed-paste, watches for the response to complete via output-idle (8s — vs the 180s `agentTuiSpawning.js` uses for long-running CoS agents, since one-shot prompts only have to wait for the model to stop talking), strips ANSI on the fly, and returns the cleaned text. Paste-handshake constants + helpers (`inferTuiCommand`, `applyCommandDefaults`, paste-marker watch, buffer caps) extracted to `server/lib/tuiHandshake.js` so the one-shot and long-running paths can't drift. The same change consolidated 11 ad-hoc call sites that each re-implemented `if (provider.type === 'cli') executeCliRun(...) else executeApiRun(...)` (`agentContentGenerator`, `taskEnhancer`, `universeBuilderRefine`, `agentPersonalityGenerator`, `agentPromptBuilder` JIRA-title, `loops`, `challengeSolver`, `pm2Standardizer`, `brain`, `meatspacePostLlm`) — all now route through the central handler and gain TUI support for free. `runPromptThroughProvider` grew `onData` + `timeout` options to absorb the streaming + per-call-timeout use cases. Net: −754 LOC of duplicated dispatch, one place to fix any future provider-type bug. Headless one-shots that need quieter session behavior (`brain`, `meatspacePostLlm`) still get `provider.headlessArgs` appended via a per-call clone so they don't pollute the user's Claude Code session list.
+
- **DONE.md condensed to feature-level summaries.** Dropped file paths, LOC counts, and test counts from the per-date entries; grouped by month with one-line bullets so an LLM can scan completed capabilities without drowning in implementation specifics. Per-release `.changelog/v*.md` files remain the source of truth for the rich details.
- **Universe-as-Canon — Phase B.4 schema teardown.** Series records no longer carry `characters` / `settings` / `objects` arrays — canon lives exclusively on the linked universe (Phase B.4 of the Universe-as-canon refactor). Sanitizer, Zod `seriesCreateSchema` / `seriesPatchSchema`, and the universe-canon resolver (`services/pipeline/seriesCanon.js`) all drop their series-side fallback paths; the legacy helpers `extractAndMergeIntoSeries`, `refineCharacterDescription` (and the `nounRefine.js` module), and `purgeImageRefFromAllSeries` are removed alongside the routes `POST /pipeline/series/:id/extract-bible` and `POST /pipeline/series/:id/characters/:entryId/refine`. Post-prose bible extraction (`textStages.js`) and storyboard scene extraction (`routes/pipeline.js`) now flow through `extractCanonFromProse` / `getSeriesCanon` against the linked universe, and the image-delete `purgeImageRefFromAll{Series→Universes}` scan was collapsed to the universe side only. Writers Room `promoteWorkToPipeline` mints a fresh universe per work and seeds it with the work's bibles instead of writing them onto the series; `POST /api/universe-builder` now accepts `characters` / `settings` / `objects` on the create-schema so promote + tests + the share-bucket importer can seed canon at creation. Voice-resolution + dialogue extraction in `audio.js` (`resolveVoiceForLine`, `extractDialogueLines`) now take canon-shaped objects (`{ characters }`) so the route can pass universe canon through `getSeriesCanon`. Stale clients sending the old canon fields on series PATCH/POST get a silent strip server-side rather than a 400. Test fixtures across `series.test.js`, `pipeline.test.js`, `promoteToPipeline.test.js`, and `sharing/integration.test.js` were updated to seed canon on a linked universe.
- **Pipeline series arc — inline theme editing.** Theme pills on the Series Arc card are now directly editable: click a pill to rename, hover for the × to remove, click the dashed "+ Add theme" chip to append (up to 20 themes, 100 chars each — matching `ARC_LIMITS` on the server). Writes are optimistic with a single-flight save gate so a blur-then-click sequence can't double-persist against stale state. The redundant comma-separated themes input was removed from the "Edit arc" form; logline / summary / protagonist arc / shape still live there.
diff --git a/server/integrations/moltbook/challengeSolver.js b/server/integrations/moltbook/challengeSolver.js
index 068eba6bf4..2a4d7ec7b4 100644
--- a/server/integrations/moltbook/challengeSolver.js
+++ b/server/integrations/moltbook/challengeSolver.js
@@ -12,7 +12,7 @@
* Uses AI for interpretation — supports both API and CLI providers.
*/
-import { executeApiRun, executeCliRun, createRun } from '../../services/runner.js';
+import { runPromptThroughProvider } from '../../lib/promptRunner.js';
import { getActiveProvider, getProviderById } from '../../services/providers.js';
/**
@@ -39,57 +39,17 @@ ${challengeText}
Answer:`;
- const { runId } = await createRun({
- providerId: provider.id,
- model,
- prompt,
- source: 'moltbook-challenge'
- });
-
- let responseText = '';
- const isCliProvider = provider.type === 'cli';
-
- await new Promise((resolve, reject) => {
- if (isCliProvider) {
- executeCliRun(
- runId,
- provider,
- prompt,
- process.cwd(),
- (text) => { responseText += text; },
- (result) => {
- if (result?.error || result?.success === false) {
- reject(new Error(result?.error || 'CLI execution failed'));
- } else {
- resolve(result);
- }
- },
- provider.timeout || 300000
- );
- } else {
- executeApiRun(
- runId,
- provider,
- model,
- prompt,
- process.cwd(),
- [],
- (data) => { responseText += typeof data === 'string' ? data : (data?.text || ''); },
- (result) => {
- if (result?.error) reject(new Error(result.error));
- else resolve(result);
- }
- );
- }
+ const { text } = await runPromptThroughProvider({
+ provider, prompt, source: 'moltbook-challenge', model,
});
// Extract number from response
- const numMatch = responseText.trim().match(/[\d]+\.?\d*/);
+ const numMatch = (text || '').trim().match(/[\d]+\.?\d*/);
if (numMatch) {
return parseFloat(numMatch[0]);
}
- console.log(`🔐 AI response didn't contain a number: "${responseText.substring(0, 100)}"`);
+ console.log(`🔐 AI response didn't contain a number: "${(text || '').substring(0, 100)}"`);
return null;
}
diff --git a/server/lib/ansiStrip.js b/server/lib/ansiStrip.js
new file mode 100644
index 0000000000..3b60b15e4c
--- /dev/null
+++ b/server/lib/ansiStrip.js
@@ -0,0 +1,52 @@
+/**
+ * Shared streaming ANSI / control-byte stripper.
+ *
+ * PTY output arrives in arbitrary chunks. A CSI/OSC escape sequence can split
+ * across two reads (e.g. `\x1B[` ends one chunk, `2J` starts the next) and a
+ * naive per-chunk strip would leak the body of unterminated sequences into
+ * the cleaned stream. This helper buffers a trailing fragment if it looks
+ * like an incomplete escape and prepends it to the next chunk before
+ * stripping, so split sequences resolve cleanly.
+ *
+ * Returns a stateful stripper function — instantiate one per stream.
+ */
+
+export const ANSI_PATTERN = /\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/g;
+
+const INCOMPLETE_CSI = /^\x1B\[[0-?]*[ -/]*$/;
+const INCOMPLETE_OSC = /^\x1B\][^\x07\x1B]*$/;
+const INCOMPLETE_ESC_2BYTE = /^\x1B$/;
+
+export function createStreamingAnsiStripper() {
+ let tail = '';
+ const strip = (s) => s.replace(ANSI_PATTERN, '').replace(/\x00/g, '');
+ return (text) => {
+ const combined = tail + text;
+ tail = '';
+ const lastEsc = combined.lastIndexOf('\x1B');
+ // Only consider the trailing fragment if it lives near the end — older
+ // unterminated bytes belong to a previous repaint and would never
+ // resolve. Bodies longer than 4096 bytes are treated as terminated; an
+ // unbounded OSC (e.g. very long hyperlink) would leak its body to
+ // display rather than buffer forever.
+ if (lastEsc !== -1 && combined.length - lastEsc <= 4096) {
+ const candidate = combined.slice(lastEsc);
+ if (INCOMPLETE_ESC_2BYTE.test(candidate)
+ || INCOMPLETE_CSI.test(candidate)
+ || INCOMPLETE_OSC.test(candidate)) {
+ tail = candidate;
+ return strip(combined.slice(0, lastEsc));
+ }
+ }
+ return strip(combined);
+ };
+}
+
+/**
+ * One-shot strip for buffered text (no streaming state). Use when you have
+ * the full PTY output in memory and just want a cleaned copy.
+ */
+export function stripAnsi(text) {
+ if (typeof text !== 'string') return '';
+ return text.replace(ANSI_PATTERN, '').replace(/\x00/g, '');
+}
diff --git a/server/lib/promptRunner.js b/server/lib/promptRunner.js
index 38c74d93c2..21ed4c4eb9 100644
--- a/server/lib/promptRunner.js
+++ b/server/lib/promptRunner.js
@@ -26,7 +26,8 @@
* stay honest about what the runner actually executed.
*/
-import { createRun, executeApiRun, executeCliRun, extractBakedModel, hasModelFlag } from '../services/runner.js';
+import { createRun, executeApiRun, executeCliRun, extractBakedModel, hasModelFlag, stopRun, patchRunMetadata } from '../services/runner.js';
+import { executeTuiRun, cleanTuiResponse } from './tuiPromptRunner.js';
const DEFAULT_TIMEOUT_MS = 300000;
const APPEND_CHUNK = (acc, chunk) => acc + (typeof chunk === 'string' ? chunk : (chunk?.text || ''));
@@ -34,17 +35,17 @@ const APPEND_CHUNK = (acc, chunk) => acc + (typeof chunk === 'string' ? chunk :
/**
* 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.
+ * first-class arg to `executeApiRun`. For CLI/TUI providers,
+ * `runner.js#buildCliArgs` / `tuiHandshake.js#buildTuiInvocation`
+ * translate the resolved `defaultModel` into a `--model`/`-m` flag — 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))
+ || ((provider?.type === 'cli' || provider?.type === 'tui') && !hasModelFlag(provider?.args))
);
/**
@@ -69,8 +70,8 @@ export function resolveEffectiveModel(provider, callerModel) {
if (providerHonorsModelOverride(provider)) {
return callerModel || provider?.defaultModel || provider?.models?.[0] || null;
}
- // Non-honoring CLI path: args-baked model id wins over defaultModel.
- const baked = provider?.type === 'cli' && hasModelFlag(provider?.args)
+ // Non-honoring CLI/TUI path: args-baked model id wins over defaultModel.
+ const baked = (provider?.type === 'cli' || provider?.type === 'tui') && hasModelFlag(provider?.args)
? extractBakedModel(provider.args)
: null;
return baked || provider?.defaultModel || provider?.models?.[0] || null;
@@ -88,7 +89,7 @@ export function resolveEffectiveModel(provider, callerModel) {
* make `/runs` and SSE status events lie about model usage.
*
* @param {object} args
- * @param {object} args.provider — { id, type: 'cli'|'api', timeout?, ... }
+ * @param {object} args.provider — { id, type: 'cli'|'api'|'tui', timeout?, ... }
* @param {string} args.prompt — full text to send to the LLM
* @param {string} args.source — run-record tag (`'universe-builder-expansion'`,
* `'media-prompt-refine'`, `'messages-triage'`, `'staged-llm'`, etc.)
@@ -96,11 +97,26 @@ export function resolveEffectiveModel(provider, callerModel) {
* 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)
+ * @param {(chunk: string) => void} [args.onData] — incremental stream
+ * callback; receives each output chunk as it arrives. Useful for live
+ * progress UI (loops, live transcripts). Does NOT change the resolved
+ * `text` value — callers receive the full buffered text either way.
+ * For TUI providers the stripped chunks are emitted; the final `text`
+ * is the cleaned response with the prompt-echo elided.
+ * @param {number} [args.timeout] — per-call timeout in ms; falls back to
+ * `provider.timeout`, then DEFAULT_TIMEOUT_MS. Callers like the loop
+ * runner expose a user-configurable timeout that isn't a provider attr.
+ * @param {string} [args.cwd] — working directory for the spawned process.
+ * Defaults to `process.cwd()`. Callers that run AI against external
+ * directories (loops with `loop.cwd`, pm2Standardizer with a repo path)
+ * must pass this — without it, the CLI/TUI spawn lands in PortOS's own
+ * cwd and the analysis runs against the wrong files. No-op for API
+ * providers (no spawn).
* @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 }) {
+export async function runPromptThroughProvider({ provider, prompt, source, model, runId: callerRunId, onData: onDataCallback, timeout: timeoutOverride, cwd: cwdOverride }) {
// 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
@@ -111,7 +127,7 @@ export async function runPromptThroughProvider({ provider, prompt, source, model
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') {
+ if (provider.type !== 'cli' && provider.type !== 'api' && provider.type !== 'tui') {
throw new Error(`Unsupported provider type: ${provider.type}`);
}
if (typeof prompt !== 'string' || !prompt.length) {
@@ -125,72 +141,119 @@ export async function runPromptThroughProvider({ provider, prompt, source, model
// so the record reflects reality. resolveEffectiveModel handles both
// the override-honored fallback chain AND the args-baked-CLI case
// (extract the args-pinned model id rather than logging defaultModel).
- const effectiveModel = resolveEffectiveModel(provider, model);
+ let effectiveProvider = provider;
+ let effectiveModel = resolveEffectiveModel(effectiveProvider, model);
+ const effectiveCwd = cwdOverride ?? process.cwd();
- // 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;
+ // Some call sites (stageRunner, loops) 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. Pass `workspacePath` so /runs metadata reflects the directory
+ // the spawn ran in.
+ //
+ // When we create the run ourselves, capture the FULL result — the
+ // toolkit's createRun may switch to a fallback provider when the
+ // requested one is unavailable (providerStatusService), and
+ // `runResult.provider` is the effective provider after that switch.
+ // Dispatch must use the fallback (otherwise we'd execute against the
+ // unavailable provider while the run record claims the fallback ran)
+ // and `effectiveModel` must be re-resolved against the fallback's
+ // defaults so the response value reflects what actually ran.
+ let runId = callerRunId;
+ if (!runId) {
+ const runResult = await createRun({
+ providerId: provider.id,
+ model: effectiveModel,
+ prompt,
+ source,
+ workspacePath: effectiveCwd,
+ });
+ runId = runResult.runId;
+ if (runResult.provider && runResult.provider.id !== provider.id) {
+ effectiveProvider = runResult.provider;
+ effectiveModel = resolveEffectiveModel(effectiveProvider, model);
+ // createRun persisted `metadata.model = effectiveModel || provider.defaultModel`
+ // using the ORIGINAL provider's resolved value — so /runs would
+ // attribute a model that doesn't belong to the fallback (e.g. an
+ // API model id recorded on a CLI fallback). Patch the record so
+ // attribution matches what actually executes.
+ patchRunMetadata(runId, {
+ model: effectiveModel,
+ providerId: effectiveProvider.id,
+ providerName: effectiveProvider.name,
+ }).catch(() => { /* best-effort; metadata patch is not load-bearing */ });
+ }
+ }
+
+ // Compute timeout AFTER the possible fallback switch so it reflects
+ // the provider that actually runs — providers can have wildly different
+ // `timeout` settings (a 5-min CLI vs a 30-s API), and using the
+ // original provider's timeout against a fallback would either time out
+ // a still-working run early or let a stuck one hang past its
+ // intended cap.
+ const effectiveTimeout = timeoutOverride ?? effectiveProvider?.timeout ?? DEFAULT_TIMEOUT_MS;
return new Promise((resolve, reject) => {
let text = '';
- const onData = (chunk) => { text = APPEND_CHUNK(text, chunk); };
+ let settled = false;
+ let apiTimeoutHandle = null;
+
+ const safeResolve = (value) => { if (!settled) { settled = true; if (apiTimeoutHandle) clearTimeout(apiTimeoutHandle); resolve(value); } };
+ const safeReject = (err) => { if (!settled) { settled = true; if (apiTimeoutHandle) clearTimeout(apiTimeoutHandle); reject(err); } };
+
+ const onData = (chunk) => {
+ text = APPEND_CHUNK(text, chunk);
+ if (onDataCallback) {
+ const chunkText = typeof chunk === 'string' ? chunk : (chunk?.text || '');
+ if (chunkText) onDataCallback(chunkText);
+ }
+ };
// Strictest discriminator: reject on either truthy `error` OR
// explicit `success === false`. Per-site drift was the bug.
+ const labelByType = { cli: 'CLI', api: 'API', tui: 'TUI' };
const onComplete = (result) => {
if (result?.error || result?.success === false) {
- reject(new Error(result?.error || `${provider.type === 'cli' ? 'CLI' : 'API'} execution failed`));
+ safeReject(new Error(result?.error || `${labelByType[effectiveProvider.type] || effectiveProvider.type} execution failed`));
} else {
- resolve({ text, runId, model: effectiveModel });
+ // TUI buffers contain the pasted prompt echo + UI chrome — clean
+ // before resolving so callers see roughly the same shape they
+ // get from a CLI run (model response text, possibly with noise).
+ const cleaned = effectiveProvider.type === 'tui' ? cleanTuiResponse(text, prompt) : text;
+ safeResolve({ text: cleaned, 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);
+ // executeCliRun / executeTuiRun both read `provider.defaultModel` for
+ // arg construction AND the run-started metadata hook. Hand them a
+ // clone with effectiveModel pinned so a per-call model override
+ // actually picks up (and the hook reports the right model). The
+ // guard skips the clone when effectiveModel already equals
+ // provider.defaultModel — typical for non-codex CLI providers where
+ // resolveEffectiveModel falls through to defaultModel anyway.
+ const providerForRun = effectiveModel && effectiveModel !== effectiveProvider.defaultModel
+ ? { ...effectiveProvider, defaultModel: effectiveModel }
+ : effectiveProvider;
+
+ if (effectiveProvider.type === 'cli') {
+ executeCliRun(runId, providerForRun, prompt, effectiveCwd, onData, onComplete, effectiveTimeout).catch(safeReject);
+ } else if (effectiveProvider.type === 'api') {
+ // API runs take model as a first-class arg — no clone needed. The
+ // toolkit's executeApiRun uses AbortController without a timer, so
+ // we enforce the per-call timeout here: if it fires before
+ // onComplete, reject with the same timeout shape CLI/TUI use and
+ // attempt to stop the run. Without this guard, API callers that
+ // used to enforce timeouts via fetchWithTimeout / AbortSignal.timeout
+ // (meatspacePostLlm, pm2Standardizer, brain) regress to hanging
+ // indefinitely on a stuck endpoint.
+ apiTimeoutHandle = setTimeout(() => {
+ stopRun(runId).catch(() => { /* best-effort cancel */ });
+ safeReject(new Error(`API execution timed out after ${effectiveTimeout}ms`));
+ }, effectiveTimeout);
+ executeApiRun(runId, effectiveProvider, effectiveModel, prompt, effectiveCwd, [], onData, onComplete).catch(safeReject);
+ } else if (effectiveProvider.type === 'tui') {
+ executeTuiRun(runId, providerForRun, prompt, effectiveCwd, onData, onComplete, effectiveTimeout).catch(safeReject);
} else {
- reject(new Error(`Unsupported provider type: ${provider.type}`));
+ safeReject(new Error(`Unsupported provider type: ${effectiveProvider.type}`));
}
});
}
diff --git a/server/lib/promptRunner.test.js b/server/lib/promptRunner.test.js
index 7330b2ad5e..497d08c605 100644
--- a/server/lib/promptRunner.test.js
+++ b/server/lib/promptRunner.test.js
@@ -6,9 +6,23 @@ vi.mock('../services/runner.js', () => ({
executeCliRun: vi.fn(),
hasModelFlag: vi.fn(() => false),
extractBakedModel: vi.fn(() => null),
+ // promptRunner.js imports stopRun for the API-timeout cancel path —
+ // without this mock, the timer firing would TypeError on `stopRun is
+ // not a function` and crash any test that triggers the API timeout.
+ stopRun: vi.fn().mockResolvedValue(undefined),
+}));
+
+// TUI runner is in lib (different module from services/runner.js) — mock it
+// here so the central handler's tui branch is testable without spawning a
+// real PTY. cleanTuiResponse is mocked to a passthrough so tests can assert
+// on the raw streamed text without worrying about the prompt-echo strip.
+vi.mock('./tuiPromptRunner.js', () => ({
+ executeTuiRun: vi.fn(),
+ cleanTuiResponse: vi.fn((text) => text),
}));
const runner = await import('../services/runner.js');
+const tuiRunner = await import('./tuiPromptRunner.js');
const { runPromptThroughProvider } = await import('./promptRunner.js');
const apiProvider = (extra = {}) => ({
@@ -17,10 +31,21 @@ const apiProvider = (extra = {}) => ({
const cliProvider = (extra = {}) => ({
id: 'codex', type: 'cli', defaultModel: 'm-default', timeout: 5000, ...extra,
});
+const tuiProvider = (extra = {}) => ({
+ id: 'claude-code-tui', type: 'tui', defaultModel: 'm-default', timeout: 5000, ...extra,
+});
beforeEach(() => {
vi.clearAllMocks();
runner.createRun.mockResolvedValue({ runId: 'run-xyz' });
+ // vi.clearAllMocks() clears calls but NOT mockReturnValue overrides,
+ // so the default implementations set in vi.mock() above don't auto-reset
+ // between tests. Re-apply the defaults that individual tests override
+ // (hasModelFlag, extractBakedModel, cleanTuiResponse) so a leak-over
+ // value can't poison the next test's resolveEffectiveModel run.
+ runner.hasModelFlag.mockReturnValue(false);
+ runner.extractBakedModel.mockReturnValue(null);
+ tuiRunner.cleanTuiResponse.mockImplementation((text) => text);
});
describe('promptRunner — happy paths', () => {
@@ -74,12 +99,34 @@ describe('promptRunner — happy paths', () => {
model: 'gpt-5',
});
- expect(runner.createRun).toHaveBeenCalledWith({
+ expect(runner.createRun).toHaveBeenCalledWith(expect.objectContaining({
providerId: 'openai',
model: 'gpt-5',
prompt: 'p',
source: 'media-prompt-refine',
+ }));
+ // workspacePath now also goes through (defaults to process.cwd() when
+ // the caller doesn't pass `cwd`) so /runs reflects the actual spawn dir.
+ expect(runner.createRun.mock.calls[0][0]).toHaveProperty('workspacePath');
+ });
+
+ it('forwards a per-call cwd through to createRun as workspacePath', async () => {
+ runner.executeCliRun.mockImplementation(async (id, _p, _pr, cwd, onData, onComplete, _t) => {
+ onData(cwd); // echo back the cwd so the assertion below can check it
+ onComplete({ success: true });
+ });
+
+ const out = await runPromptThroughProvider({
+ provider: cliProvider(),
+ prompt: 'p',
+ source: 't',
+ cwd: '/some/other/dir',
});
+
+ expect(out.text).toBe('/some/other/dir');
+ expect(runner.createRun).toHaveBeenCalledWith(
+ expect.objectContaining({ workspacePath: '/some/other/dir' })
+ );
});
it('reuses a caller-supplied runId (no createRun round-trip)', async () => {
@@ -185,12 +232,12 @@ describe('promptRunner — happy paths', () => {
// args-baked model id so the recorded run reflects what actually
// executed (not the caller's silently-dropped override or the
// provider.defaultModel fallback).
- expect(runner.createRun).toHaveBeenCalledWith({
+ expect(runner.createRun).toHaveBeenCalledWith(expect.objectContaining({
providerId: 'claude-code',
model: 'baked-in',
prompt: 'p',
source: 't',
- });
+ }));
});
});
@@ -346,3 +393,138 @@ describe('promptRunner — multi-chunk text accumulation', () => {
expect(out.text).toBe('hello world');
});
});
+
+// =============================================================================
+// TUI routing — the third dispatch branch added alongside cli/api. Mirrors
+// the cli/api coverage above so the central handler's tui path can't quietly
+// regress (was the entry point for the Pipeline-prose crash bug).
+// =============================================================================
+
+describe('promptRunner — TUI provider routing', () => {
+ it('routes TUI providers through executeTuiRun, accumulates stripped text, resolves { text, runId, model }', async () => {
+ tuiRunner.executeTuiRun.mockImplementation(async (id, _p, _pr, _cwd, onData, onComplete, _t) => {
+ onData('once ');
+ onData('upon ');
+ onData('a time');
+ onComplete({ success: true, exitCode: 0 });
+ });
+
+ const out = await runPromptThroughProvider({
+ provider: tuiProvider(),
+ prompt: 'tell me a story',
+ source: 'pipeline-text-stage',
+ });
+
+ expect(out).toEqual({ text: 'once upon a time', runId: 'run-xyz', model: 'm-default' });
+ expect(tuiRunner.executeTuiRun).toHaveBeenCalledTimes(1);
+ expect(runner.executeCliRun).not.toHaveBeenCalled();
+ expect(runner.executeApiRun).not.toHaveBeenCalled();
+ });
+
+ it('passes cwd + timeout overrides through to executeTuiRun', async () => {
+ tuiRunner.executeTuiRun.mockImplementation(async (id, _p, _pr, _cwd, onData, onComplete, _t) => {
+ onData('ok');
+ onComplete({ success: true });
+ });
+
+ await runPromptThroughProvider({
+ provider: tuiProvider(),
+ prompt: 'p', source: 't',
+ cwd: '/tmp/some-other-repo',
+ timeout: 60000,
+ });
+
+ const args = tuiRunner.executeTuiRun.mock.calls[0];
+ expect(args[3]).toBe('/tmp/some-other-repo'); // cwd positional arg
+ expect(args[6]).toBe(60000); // timeout positional arg
+ });
+
+ it('runs cleanTuiResponse on the accumulated text before resolving', async () => {
+ tuiRunner.executeTuiRun.mockImplementation(async (id, _p, _pr, _cwd, onData, onComplete, _t) => {
+ onData('raw with chrome');
+ onComplete({ success: true });
+ });
+ tuiRunner.cleanTuiResponse.mockReturnValueOnce('cleaned');
+
+ const out = await runPromptThroughProvider({
+ provider: tuiProvider(),
+ prompt: 'p', source: 't',
+ });
+
+ expect(tuiRunner.cleanTuiResponse).toHaveBeenCalledWith('raw with chrome', 'p');
+ expect(out.text).toBe('cleaned');
+ });
+
+ it('rejects with TUI-labeled error when executeTuiRun fires onComplete with success: false', async () => {
+ tuiRunner.executeTuiRun.mockImplementation(async (id, _p, _pr, _cwd, _od, onComplete, _t) => {
+ onComplete({ success: false, exitCode: 124 });
+ });
+
+ await expect(runPromptThroughProvider({
+ provider: tuiProvider(),
+ prompt: 'p', source: 't',
+ })).rejects.toThrow(/TUI execution failed/);
+ });
+
+ it('rejects when executeTuiRun rejects (spawn failure path)', async () => {
+ tuiRunner.executeTuiRun.mockRejectedValue(new Error("Failed to spawn TUI 'claude'"));
+ await expect(runPromptThroughProvider({
+ provider: tuiProvider(),
+ prompt: 'p', source: 't',
+ })).rejects.toThrow(/Failed to spawn TUI/);
+ });
+});
+
+// =============================================================================
+// API timeout enforcement — the toolkit's executeApiRun has no internal
+// timer, so the central handler races a setTimeout against onComplete.
+// Verify that a stuck API run rejects with the timeout error AND that
+// stopRun is invoked for best-effort cancellation. Regression guard for
+// the round-2 review finding that API callers were hanging indefinitely.
+// =============================================================================
+
+describe('promptRunner — API timeout enforcement', () => {
+ it('rejects with timeout error when executeApiRun never completes and calls stopRun', async () => {
+ vi.useFakeTimers();
+ // executeApiRun hangs — never invokes onComplete or onData.
+ runner.executeApiRun.mockImplementation(() => new Promise(() => {}));
+
+ // Kick off the call and attach the rejection assertion BEFORE advancing
+ // timers — otherwise the timer-driven reject lands without a handler
+ // attached and vitest flags an unhandled rejection.
+ const promise = runPromptThroughProvider({
+ provider: apiProvider(),
+ prompt: 'p', source: 't',
+ timeout: 5000,
+ });
+ const assertion = expect(promise).rejects.toThrow(/API execution timed out after 5000ms/);
+
+ await vi.advanceTimersByTimeAsync(6000);
+ await assertion;
+
+ expect(runner.stopRun).toHaveBeenCalledWith('run-xyz');
+ vi.useRealTimers();
+ });
+
+ it('does not call stopRun when API completes within the timeout', async () => {
+ vi.useFakeTimers();
+ runner.executeApiRun.mockImplementation(async (id, _p, _m, _pr, _cwd, _ctx, onData, onComplete) => {
+ onData('quick');
+ onComplete({ success: true });
+ });
+
+ const promise = runPromptThroughProvider({
+ provider: apiProvider(),
+ prompt: 'p', source: 't',
+ timeout: 5000,
+ });
+
+ const out = await promise;
+ expect(out.text).toBe('quick');
+ // Advance time past what would have been the timeout — should not fire
+ // because settle-once guards cleared the handle.
+ await vi.advanceTimersByTimeAsync(10000);
+ expect(runner.stopRun).not.toHaveBeenCalled();
+ vi.useRealTimers();
+ });
+});
diff --git a/server/lib/providerModels.js b/server/lib/providerModels.js
index 41c4ab8145..40ae864a4f 100644
--- a/server/lib/providerModels.js
+++ b/server/lib/providerModels.js
@@ -23,3 +23,53 @@ export const resolveCliModel = (model) => isCodexConfiguredDefault(model) ? null
*/
export const filterSelectableModels = (models) =>
(models || []).filter(m => m !== CODEX_CONFIGURED_DEFAULT);
+
+/**
+ * Detects whether the provider's stored argv already pins a model with a
+ * usable value. Checks both flag forms (`--model` / `-m`) and both styles
+ * (separated `--model x` and joined `--model=x`). A separated flag with no
+ * value following (`['--model']` at end of argv, or `['--model', '--other']`)
+ * is treated as NOT a baked-in pin — the CLI would reject the argv at
+ * runtime anyway, and pretending it's a pin would also make refiners report
+ * `null` (from extractBakedModel) and skip injecting our own model.
+ *
+ * Used to gate runner-injected `--model` flags: when the user has hard-coded
+ * a model in args, the runner-injected one is suppressed and the args-baked
+ * model wins.
+ */
+export function hasModelFlag(args) {
+ if (!Array.isArray(args)) return false;
+ for (let i = 0; i < args.length; i++) {
+ const a = args[i];
+ if (typeof a !== 'string') continue;
+ if (a.startsWith('--model=') && a.length > '--model='.length) return true;
+ if (a.startsWith('-m=') && a.length > '-m='.length) return true;
+ if (a === '--model' || a === '-m') {
+ const next = args[i + 1];
+ if (typeof next === 'string' && next.length > 0 && !next.startsWith('-')) return true;
+ }
+ }
+ return false;
+}
+
+/**
+ * Extract the pinned model id from provider.args when a model flag is baked
+ * in. Supports separated form (`--model X` / `-m X`) and joined form
+ * (`--model=X` / `-m=X`). Returns null when no model flag is present or the
+ * separated form has no value following the flag.
+ */
+export function extractBakedModel(args) {
+ if (!Array.isArray(args)) return null;
+ for (let i = 0; i < args.length; i++) {
+ const a = args[i];
+ if (typeof a !== 'string') continue;
+ if (a === '--model' || a === '-m') {
+ const next = args[i + 1];
+ if (typeof next === 'string' && next.length > 0 && !next.startsWith('-')) return next;
+ return null;
+ }
+ if (a.startsWith('--model=')) return a.slice('--model='.length) || null;
+ if (a.startsWith('-m=')) return a.slice('-m='.length) || null;
+ }
+ return null;
+}
diff --git a/server/lib/tuiHandshake.js b/server/lib/tuiHandshake.js
new file mode 100644
index 0000000000..34a497c28d
--- /dev/null
+++ b/server/lib/tuiHandshake.js
@@ -0,0 +1,88 @@
+/**
+ * Shared TUI invocation + paste-handshake constants.
+ *
+ * Two execution paths need these: `server/lib/tuiPromptRunner.js` (one-shot
+ * prompts from the central handler) and `server/services/agentTuiSpawning.js`
+ * (long-running CoS agents). Both shell into the same set of TUI binaries
+ * (Claude Code, Codex, Gemini) and use identical PTY-paste choreography to
+ * deliver the prompt — banner repaint wait, bracketed-paste, Enter handshake.
+ * Without this shared module they had verbatim copies that would silently
+ * drift the first time anyone tweaked one side's paste timing.
+ *
+ * No cycle risk: this module imports nothing from either consumer.
+ */
+
+import { resolveCliModel, hasModelFlag } from './providerModels.js';
+
+// ─── Paste handshake constants ────────────────────────────────────────────
+
+// PTY readiness — wait for the TUI banner to finish repainting (output-idle
+// for READY_IDLE_THRESHOLD_MS) before pasting. A fixed delay loses to slow
+// banners and burns time on fast ones; idle-detect adapts.
+export const READY_POLL_INTERVAL_MS = 300;
+export const READY_IDLE_THRESHOLD_MS = 1200;
+export const PASTE_DEADLINE_MS = 10000;
+
+// Claude Code emits `[Pasted text #N +M lines]` after committing a paste.
+// Watch for the marker (or fall back after PASTE_TO_ENTER_FALLBACK_MS)
+// before sending `\r` so Enter doesn't get swallowed mid-paste-commit.
+export const PASTE_MARKER_POLL_MS = 150;
+export const PASTE_MARKER_PATTERN = /\[Pasted text #\d+/;
+export const PASTE_TO_ENTER_MIN_DELAY_MS = 200;
+export const PASTE_TO_ENTER_FALLBACK_MS = 3500;
+
+// Defaults the consumer applies when the provider config doesn't pin
+// per-provider values (provider.tuiPromptDelayMs / .tuiIdleTimeoutMs).
+export const DEFAULT_TUI_PROMPT_DELAY_MS = 2500;
+export const DEFAULT_TUI_IDLE_TIMEOUT_MS = 180000;
+
+// ─── Buffer caps (defensive, not load-bearing) ────────────────────────────
+
+export const RAW_BUFFER_CAP = 512 * 1024;
+export const RAW_BUFFER_HEADROOM = 640 * 1024;
+export const OUTPUT_BUFFER_CAP = 1024 * 1024;
+export const OUTPUT_BUFFER_HEADROOM = 1280 * 1024;
+
+// ─── Command + args helpers ───────────────────────────────────────────────
+
+export function inferTuiCommand(id) {
+ if (!id) return 'claude';
+ if (id.includes('codex')) return 'codex';
+ if (id.includes('gemini')) return 'gemini';
+ return 'claude';
+}
+
+// Codex TUI blocks on every tool approval without `--ask-for-approval never`.
+// No human-at-keyboard for headless calls (one-shot OR agent), so inject it.
+export function applyCommandDefaults(command, args) {
+ if (command === 'codex' && !args.includes('--ask-for-approval')) {
+ return ['--ask-for-approval', 'never', ...args];
+ }
+ return args;
+}
+
+/**
+ * Build the spawn args for a TUI invocation. When `provider.args` already
+ * has a `--model X` (or `-m X`) pin, the args-baked flag wins and we skip
+ * the per-call --model append — otherwise the CLI would see two flags and
+ * either error or take the last one (provider-specific). Matches the same
+ * gate `runner.js#buildCliArgs` uses for CLI providers.
+ */
+export function buildTuiInvocation(provider, model) {
+ const command = provider?.command || inferTuiCommand(provider?.id);
+ const baseArgs = applyCommandDefaults(command, [...(provider?.args || [])]);
+ const effectiveModel = resolveCliModel(model);
+ const shouldInject = effectiveModel && !hasModelFlag(baseArgs);
+ const args = shouldInject ? [...baseArgs, '--model', effectiveModel] : baseArgs;
+ return { command, args };
+}
+
+/**
+ * Returns true when the stripped chunk looks like a `command not found`
+ * error for our spawned TUI binary. Used as an early-fail probe so a typo'd
+ * provider.command surfaces in seconds instead of after the idle timeout.
+ */
+export function detectMissingTuiBinary(strippedText, commandName) {
+ const lower = strippedText.toLowerCase();
+ return lower.includes('command not found') && lower.includes(commandName.toLowerCase());
+}
diff --git a/server/lib/tuiPromptRunner.js b/server/lib/tuiPromptRunner.js
new file mode 100644
index 0000000000..05f712585f
--- /dev/null
+++ b/server/lib/tuiPromptRunner.js
@@ -0,0 +1,352 @@
+/**
+ * One-shot TUI prompt runner.
+ *
+ * Spawns a TUI binary (Claude Code, Codex, Gemini, etc.) in a PTY, waits for
+ * the prompt cursor to become input-ready, bracketed-pastes the prompt + Enter,
+ * watches for the model response to complete via sustained output-idle, then
+ * strips ANSI and returns the captured text. Persists a run record under
+ * `data/runs/<runId>/` so /runs can replay TUI invocations alongside CLI/API.
+ *
+ * Distinct from `server/services/agentTuiSpawning.js` — that path wraps
+ * long-running CoS agents (worktree, /simplify, /do:pr, .agent-done sentinel).
+ * This is the synchronous "send prompt, get text back" variant the central
+ * promptRunner needs when `provider.type === 'tui'`.
+ *
+ * Spawning bypasses `services/shell.js` deliberately:
+ * - shellService caps total sessions at 5, which the central handler can
+ * exceed easily (arc planner fans out parallel calls).
+ * - shellService wraps a login shell around the TUI; pasting `${cmd}\n`
+ * into a zsh prompt is slower and noisier than spawning the TUI directly.
+ *
+ * Completion detection is intentionally minimal: idle-after-response, with a
+ * hard timeout fallback. Per-binary input-prompt regexes were considered but
+ * are fragile across versions and screen sizes; the idle threshold (~8s)
+ * works universally and matches how a human knows the TUI finished — output
+ * stopped scrolling.
+ */
+
+import { spawn as ptySpawn } from 'node-pty';
+import { join } from 'path';
+import { ensureDir, PATHS } from './fileUtils.js';
+import { createStreamingAnsiStripper } from './ansiStrip.js';
+import { getRunsPath, finalizeRunRecord, emitRunStarted } from '../services/runner.js';
+import {
+ DEFAULT_TUI_PROMPT_DELAY_MS,
+ PASTE_MARKER_POLL_MS,
+ PASTE_MARKER_PATTERN,
+ PASTE_TO_ENTER_MIN_DELAY_MS,
+ PASTE_TO_ENTER_FALLBACK_MS,
+ PASTE_DEADLINE_MS,
+ READY_POLL_INTERVAL_MS,
+ READY_IDLE_THRESHOLD_MS,
+ OUTPUT_BUFFER_CAP,
+ OUTPUT_BUFFER_HEADROOM,
+ RAW_BUFFER_CAP,
+ RAW_BUFFER_HEADROOM,
+ buildTuiInvocation,
+ detectMissingTuiBinary,
+} from './tuiHandshake.js';
+
+// One-shot defaults that don't apply to the long-running agent path:
+// - hard run cap (5 min vs unbounded for agents)
+// - response-complete idle threshold (8s vs 180s for agents — agents wait
+// out tool calls + /simplify + /do:pr, we're just waiting for the model
+// to stop talking)
+const DEFAULT_TIMEOUT_MS = 300000;
+const DEFAULT_ONE_SHOT_IDLE_MS = 8000;
+
+// Wide PTY so TUI doesn't wrap responses at narrow widths, which makes
+// downstream parsing harder.
+const PTY_COLS = 200;
+const PTY_ROWS = 50;
+
+/**
+ * Run a single prompt through a TUI provider. Mirrors the signature of
+ * `executeCliRun` / `executeApiRun` so the central handler treats all three
+ * branches uniformly (positional, NOT an options object).
+ *
+ * Caller (typically `runPromptThroughProvider`) owns the run record:
+ * - `createRun` (toolkit) writes the initial metadata.json + prompt.txt
+ * - this function writes output.txt and finalizes metadata.json on exit
+ * via `runner.js#finalizeRunRecord`, so /runs shows TUI runs with the
+ * same success/exitCode/duration shape as CLI runs.
+ *
+ * @param {string} runId — pre-created run id (from createRun).
+ * @param {object} provider — { id, type: 'tui', command, args, envVars,
+ * tuiPromptDelayMs?, tuiOneShotIdleMs?, timeout?, defaultModel? }. The
+ * model passed to `--model` is taken from `provider.defaultModel`; per-
+ * call overrides are applied by the central handler via a provider clone
+ * before this function is reached.
+ * @param {string} prompt — full text to paste into the TUI.
+ * @param {string} cwd — working directory for the spawned TUI.
+ * @param {(chunk: string) => void} [onData] — incremental ANSI-stripped
+ * output stream.
+ * @param {(meta: object) => void} [onComplete] — fired after exit with
+ * `{ exitCode, duration, success, error?, model? }`. Promise resolves
+ * AFTER this fires.
+ * @param {number} [timeout] — hard cap on a single run (ms). Falls back to
+ * `provider.timeout`, then `DEFAULT_TIMEOUT_MS`.
+ * @returns {Promise<void>}
+ */
+export async function executeTuiRun(runId, provider, prompt, cwd, onData, onComplete, timeout) {
+ if (!provider || typeof provider !== 'object') {
+ throw new Error('executeTuiRun: provider is required');
+ }
+ if (typeof prompt !== 'string' || !prompt) {
+ throw new Error('executeTuiRun: prompt must be a non-empty string');
+ }
+
+ const { command, args } = buildTuiInvocation(provider, provider.defaultModel);
+ const promptDelayMs = provider.tuiPromptDelayMs ?? DEFAULT_TUI_PROMPT_DELAY_MS;
+ const idleThresholdMs = provider.tuiOneShotIdleMs ?? DEFAULT_ONE_SHOT_IDLE_MS;
+ const totalTimeoutMs = timeout ?? provider.timeout ?? DEFAULT_TIMEOUT_MS;
+ const workingDir = (typeof cwd === 'string' && cwd) ? cwd : PATHS.root;
+
+ // Mirror runner.js#executeCliRun's runs-path resolution so TUI runs land
+ // under the runner-config dataDir (not always PATHS.runs) — otherwise a
+ // non-default dataDir would split metadata + output across two trees.
+ const runDir = join(getRunsPath(), runId);
+ await ensureDir(runDir);
+
+ console.log(`📟 Executing TUI: ${command} ${args.join(' ')} (${prompt.length} chars via paste)`);
+
+ // CLAUDECODE is set when PortOS itself runs inside Claude Code; passing it
+ // through to a spawned Claude Code TUI would make the child think it's
+ // nested. Other AI spawn paths (runner.js, agentCliSpawning.js) strip it
+ // for the same reason.
+ const childEnv = { ...process.env, ...(provider.envVars || {}), TERM: 'xterm-256color', COLORTERM: 'truecolor' };
+ delete childEnv.CLAUDECODE;
+
+ let ptyProcess;
+ try {
+ ptyProcess = ptySpawn(command, args, {
+ name: 'xterm-256color',
+ cols: PTY_COLS,
+ rows: PTY_ROWS,
+ cwd: workingDir,
+ env: childEnv,
+ });
+ } catch (err) {
+ throw new Error(`Failed to spawn TUI '${command}': ${err.message}`);
+ }
+
+ // Fire the toolkit's `onRunStarted` hook now that the PTY is alive — the
+ // CLI/API paths fire it inside the toolkit's executeCliRun/executeApiRun,
+ // but the TUI path doesn't go through those. Without this hook, /runs and
+ // any SSE-based "active run" UI never see TUI runs as in-flight.
+ emitRunStarted({ runId, provider, model: provider.defaultModel });
+
+ const startTime = Date.now();
+ let outputBuffer = '';
+ let rawBuffer = '';
+ let promptSentAt = null;
+ let firstOutputAt = null;
+ let lastOutputAt = startTime;
+ let firstResponseAt = null;
+ let finalized = false;
+
+ const streamingStrip = createStreamingAnsiStripper();
+ let readyTimer = null;
+ let pasteEnterTimer = null;
+ let idleWatchTimer = null;
+ let hardTimeoutTimer = null;
+
+ const cleanupTimers = () => {
+ if (readyTimer) { clearInterval(readyTimer); readyTimer = null; }
+ if (pasteEnterTimer) { clearInterval(pasteEnterTimer); pasteEnterTimer = null; }
+ if (idleWatchTimer) { clearInterval(idleWatchTimer); idleWatchTimer = null; }
+ if (hardTimeoutTimer) { clearTimeout(hardTimeoutTimer); hardTimeoutTimer = null; }
+ };
+
+ return new Promise((resolve) => {
+ const finish = async ({ success, exitCode = 0, error = null, reason = 'completed' }) => {
+ if (finalized) return;
+ finalized = true;
+ cleanupTimers();
+
+ // Kill the PTY if still alive — one-shot runs don't leave a session
+ // behind for the user to interact with.
+ try { if (ptyProcess && !ptyProcess.killed) ptyProcess.kill(); } catch { /* already gone */ }
+
+ // Delegate run-record finalization (output.txt + metadata.json merge
+ // + onRunCompleted/onRunFailed hooks + toolkit error analysis) to the
+ // shared runner helper. `completionReason` lands in `extras` so it
+ // gets persisted to metadata.json BEFORE the write (was previously
+ // set post-write and never made it to disk → /runs replay missed it).
+ const metadata = await finalizeRunRecord({
+ runId, output: outputBuffer, exitCode, success, error, startTime,
+ extras: { completionReason: reason },
+ }).catch((err) => {
+ console.error(`❌ TUI run ${runId} finalize failed: ${err.message}`);
+ return {
+ exitCode, success, error: error || err.message,
+ duration: Date.now() - startTime, completionReason: reason,
+ };
+ });
+ onComplete?.(metadata);
+ resolve();
+ };
+
+ ptyProcess.onData((data) => {
+ const text = data.toString();
+ rawBuffer += text;
+ if (rawBuffer.length > RAW_BUFFER_HEADROOM) rawBuffer = rawBuffer.slice(-RAW_BUFFER_CAP);
+
+ const stripped = streamingStrip(text);
+ if (stripped) {
+ outputBuffer += stripped;
+ if (outputBuffer.length > OUTPUT_BUFFER_HEADROOM) {
+ outputBuffer = outputBuffer.slice(-OUTPUT_BUFFER_CAP);
+ }
+ onData?.(stripped);
+ }
+
+ const now = Date.now();
+ lastOutputAt = now;
+ if (firstOutputAt === null) firstOutputAt = now;
+ if (promptSentAt && firstResponseAt === null && now > promptSentAt) {
+ firstResponseAt = now;
+ // Defer the idle-watch timer until the first response chunk so we
+ // don't run a 1Hz no-op throughout the 5-30s spawn + paste window.
+ // Significant on parallel fan-out paths (arc planner).
+ idleWatchTimer = setInterval(() => {
+ if (finalized) return;
+ const idle = Date.now() - lastOutputAt;
+ if (idle >= idleThresholdMs) {
+ finish({ success: true, exitCode: 0, reason: 'idle-complete' });
+ }
+ }, 1000);
+ }
+
+ // Early-fail probe — without this guard a typo'd provider.command
+ // would idle until the hard timeout (5 min default).
+ if (!promptSentAt && detectMissingTuiBinary(stripped, command)) {
+ finish({
+ success: false,
+ exitCode: 127,
+ error: `TUI command not found: ${command}`,
+ reason: 'command-not-found'
+ });
+ }
+ });
+
+ ptyProcess.onExit(({ exitCode, signal }) => {
+ const killed = !!signal;
+ const finalExitCode = typeof exitCode === 'number' ? exitCode : (killed ? 130 : 0);
+ const success = !killed && finalExitCode === 0;
+ // Always set an explicit error string when finishing as failure. The
+ // toolkit's errorDetection (if enabled) will fill in `error` inside
+ // finalizeRunRecord, but if it's absent we'd persist `success: false`
+ // with no error and the central handler would reject with a generic
+ // "TUI execution failed". Include the exit code + a tail of the
+ // captured output so failures are actionable from /runs without
+ // re-running.
+ let error = null;
+ if (killed) {
+ error = `TUI killed (signal ${signal})`;
+ } else if (!success) {
+ const tail = outputBuffer.slice(-200).trim();
+ error = tail
+ ? `TUI exited with code ${finalExitCode}: ${tail}`
+ : `TUI exited with code ${finalExitCode}`;
+ }
+ finish({
+ success,
+ exitCode: finalExitCode,
+ error,
+ reason: killed ? 'killed' : 'exit'
+ });
+ });
+
+ const sendPrompt = (reason) => {
+ if (finalized || promptSentAt) return;
+ promptSentAt = Date.now();
+ const rawLenBeforePaste = rawBuffer.length;
+ try {
+ ptyProcess.write(`\x1b[200~${prompt}\x1b[201~`);
+ } catch (err) {
+ finish({ success: false, exitCode: 1, error: `Failed to write prompt: ${err.message}`, reason: 'write-failed' });
+ return;
+ }
+ console.log(`📟 Pasted prompt into TUI ${command} (${reason})`);
+
+ const pasteSentAt = Date.now();
+ pasteEnterTimer = setInterval(() => {
+ if (finalized) { clearInterval(pasteEnterTimer); pasteEnterTimer = null; return; }
+ const elapsed = Date.now() - pasteSentAt;
+ const postPaste = rawBuffer.slice(rawLenBeforePaste);
+ const markerSeen = PASTE_MARKER_PATTERN.test(postPaste);
+ if ((markerSeen && elapsed >= PASTE_TO_ENTER_MIN_DELAY_MS)
+ || elapsed >= PASTE_TO_ENTER_FALLBACK_MS) {
+ clearInterval(pasteEnterTimer);
+ pasteEnterTimer = null;
+ try { ptyProcess.write('\r'); } catch { /* PTY may have already exited */ }
+ }
+ }, PASTE_MARKER_POLL_MS);
+ };
+
+ // Ready watch — paste only once the TUI banner finishes repainting AND
+ // we've had at least promptDelayMs of runtime. Falls back to forcing
+ // the paste after PASTE_DEADLINE_MS so a silent provider still gets
+ // the prompt.
+ readyTimer = setInterval(() => {
+ if (finalized || promptSentAt) {
+ clearInterval(readyTimer);
+ readyTimer = null;
+ return;
+ }
+ const now = Date.now();
+ const elapsed = now - startTime;
+ if (elapsed >= PASTE_DEADLINE_MS) {
+ sendPrompt('fallback');
+ return;
+ }
+ if (elapsed < promptDelayMs) return;
+ if (firstOutputAt === null) return;
+ if (now - lastOutputAt < READY_IDLE_THRESHOLD_MS) return;
+ sendPrompt('ready');
+ }, READY_POLL_INTERVAL_MS);
+
+ // (idleWatchTimer is created inside onData once firstResponseAt is set.)
+
+ // Hard timeout — covers stuck-banner, no-response, and runaway-response
+ // cases. Provider-configurable via `timeout`; defaults to 5 min.
+ hardTimeoutTimer = setTimeout(() => {
+ if (finalized) return;
+ finish({
+ success: false,
+ exitCode: 124,
+ error: `TUI run timed out after ${totalTimeoutMs}ms`,
+ reason: 'timeout'
+ });
+ }, totalTimeoutMs);
+ });
+}
+
+/**
+ * Best-effort response cleanup for an already-ANSI-stripped TUI buffer.
+ *
+ * The TUI buffer is a screen, not a log — it contains banner art, the
+ * pasted prompt echoed back, status lines ("thinking...", token counters),
+ * box-drawing characters around the input prompt, and the model's response
+ * interleaved with all of it. Reliable carve-out would need per-binary
+ * scrapers; this helper just drops the obvious bits (paste marker + echoed
+ * prompt) and leaves downstream consumers (`extractJson`,
+ * `extractCodexAssistant`) to find structured content in the rest.
+ *
+ * Input is assumed pre-stripped of ANSI codes (the central handler streams
+ * each chunk through `createStreamingAnsiStripper` during accumulation, so
+ * `outputBuffer` is already clean). Don't strip again — it's a wasted scan
+ * over up to 1MB of text.
+ */
+export function cleanTuiResponse(strippedText, prompt) {
+ if (typeof strippedText !== 'string' || !strippedText) return '';
+ let text = strippedText.replace(/\[Pasted text #\d+[^\]]*\]/g, '');
+ // split-join over the prompt is safe because the prompt is fixed text —
+ // no regex escaping needed. Guard on length>16 so a degenerate empty/
+ // tiny prompt doesn't accidentally erase model output.
+ if (typeof prompt === 'string' && prompt.length > 16) {
+ text = text.split(prompt).join('');
+ }
+ return text.trim();
+}
diff --git a/server/lib/tuiPromptRunner.test.js b/server/lib/tuiPromptRunner.test.js
new file mode 100644
index 0000000000..3183f915d3
--- /dev/null
+++ b/server/lib/tuiPromptRunner.test.js
@@ -0,0 +1,90 @@
+import { describe, it, expect } from 'vitest';
+import { cleanTuiResponse } from './tuiPromptRunner.js';
+
+// Targeted coverage for the cleanTuiResponse helper — it shapes what every
+// TUI-provider caller sees as the model response (paste-marker removal,
+// prompt-echo strip). Bugs here would silently corrupt prose generation
+// and JSON parsing downstream.
+
+describe('cleanTuiResponse', () => {
+ describe('empty / non-string inputs', () => {
+ it('returns empty string for empty input', () => {
+ expect(cleanTuiResponse('', 'anything')).toBe('');
+ });
+ it('returns empty string for non-string raw', () => {
+ expect(cleanTuiResponse(null, 'anything')).toBe('');
+ expect(cleanTuiResponse(undefined, 'anything')).toBe('');
+ expect(cleanTuiResponse(42, 'anything')).toBe('');
+ });
+ });
+
+ describe('paste-marker removal', () => {
+ it('drops the Claude Code [Pasted text #N +M lines] marker', () => {
+ const raw = 'before\n[Pasted text #1 +42 lines]\nresponse body';
+ expect(cleanTuiResponse(raw, '')).toBe('before\n\nresponse body');
+ });
+
+ it('drops multiple paste markers from the same buffer', () => {
+ const raw = '[Pasted text #1 +3 lines] reply A [Pasted text #2 +5 lines] reply B';
+ expect(cleanTuiResponse(raw, '')).toBe('reply A reply B');
+ });
+
+ it('leaves text that resembles but does not match the marker pattern alone', () => {
+ const raw = 'Look at [Pasted text without number] and continue';
+ expect(cleanTuiResponse(raw, '')).toBe('Look at [Pasted text without number] and continue');
+ });
+ });
+
+ describe('prompt echo elision', () => {
+ it('strips a verbatim prompt that the TUI echoes back', () => {
+ const prompt = 'Write a sonnet about an ocelot wearing a crown of starlight';
+ const raw = `${prompt}\n\nShall I compare thee to a summer's ocelot?`;
+ expect(cleanTuiResponse(raw, prompt)).toBe(`Shall I compare thee to a summer's ocelot?`);
+ });
+
+ it('strips every echoed occurrence (some TUIs render the prompt twice)', () => {
+ const prompt = 'Generate a six-word science fiction story about regret';
+ const raw = `${prompt}\nresponse 1\n${prompt}\nresponse 2`;
+ const out = cleanTuiResponse(raw, prompt);
+ expect(out).not.toContain(prompt);
+ expect(out).toContain('response 1');
+ expect(out).toContain('response 2');
+ });
+
+ it('skips prompt-echo elision when the prompt is shorter than the 16-char guard', () => {
+ // Short prompts could appear naturally inside the model's response
+ // (e.g. prompt="ok" appearing in "okay, here is..."). The guard
+ // keeps the response intact instead of mass-deleting bigrams.
+ const prompt = 'Write?';
+ const raw = `Write? Sure, here is my best Writeful Writeup`;
+ expect(cleanTuiResponse(raw, prompt)).toBe(raw);
+ });
+
+ it('does NOT strip prompt-substring matches inside the response — only exact full-prompt matches', () => {
+ // split-join uses the full prompt as the splitter, so a substring
+ // of the prompt that appears in the model's reply survives. This
+ // is the right behavior: a model often refers back to phrases
+ // from the prompt without echoing the whole thing.
+ const prompt = 'Continue the story: The cat sat on the mat';
+ const raw = `${prompt}\nThe cat sat on the mat for many hours.`;
+ const out = cleanTuiResponse(raw, prompt);
+ // First occurrence (the full prompt echo) elided; the substring
+ // reference in the reply is preserved.
+ expect(out).toBe('The cat sat on the mat for many hours.');
+ });
+
+ it('handles undefined/non-string prompt without throwing', () => {
+ expect(cleanTuiResponse('plain response', undefined)).toBe('plain response');
+ expect(cleanTuiResponse('plain response', null)).toBe('plain response');
+ expect(cleanTuiResponse('plain response', 12345)).toBe('plain response');
+ });
+ });
+
+ describe('integration — marker + prompt + trim together', () => {
+ it('removes paste marker AND prompt echo AND trims surrounding whitespace', () => {
+ const prompt = 'Summarize the plot of Aster of Pan in a single sentence';
+ const raw = `\n\n[Pasted text #7 +1 lines]\n${prompt}\n\nA child rebuilds wonder in a green ruin.\n\n`;
+ expect(cleanTuiResponse(raw, prompt)).toBe('A child rebuilds wonder in a green ruin.');
+ });
+ });
+});
diff --git a/server/services/agentContentGenerator.js b/server/services/agentContentGenerator.js
index c7f809ac2c..915d5deb19 100644
--- a/server/services/agentContentGenerator.js
+++ b/server/services/agentContentGenerator.js
@@ -5,10 +5,10 @@
* Includes recent activity context to avoid repetition.
*/
-import { executeApiRun, executeCliRun, createRun } from './runner.js';
import { getActiveProvider, getProviderById } from './providers.js';
import * as agentActivity from './agentActivity.js';
import { safeJSONParse } from '../lib/fileUtils.js';
+import { runPromptThroughProvider } from '../lib/promptRunner.js';
/**
* Parse JSON from AI response text (handles markdown blocks, extra text)
@@ -89,55 +89,9 @@ async function runAIGeneration(prompt, providerId, model, source) {
throw new Error('No AI provider available for content generation');
}
- const selectedModel = model || provider.defaultModel || provider.models?.[0];
-
- const { runId } = await createRun({
- providerId: provider.id,
- model: selectedModel,
- prompt,
- source
+ const { text: responseText, model: selectedModel } = await runPromptThroughProvider({
+ provider, prompt, source, model,
});
-
- let responseText = '';
- const isCliProvider = provider.type === 'cli';
-
- await new Promise((resolve, reject) => {
- if (isCliProvider) {
- executeCliRun(
- runId,
- provider,
- prompt,
- process.cwd(),
- (text) => { responseText += text; },
- (result) => {
- if (result?.error || result?.success === false) {
- reject(new Error(result?.error || 'CLI execution failed'));
- } else {
- resolve(result);
- }
- },
- provider.timeout || 300000
- );
- } else {
- executeApiRun(
- runId,
- provider,
- selectedModel,
- prompt,
- process.cwd(),
- [],
- (data) => { responseText += typeof data === 'string' ? data : (data?.text || ''); },
- (result) => {
- if (result?.error) {
- reject(new Error(result.error));
- } else {
- resolve(result);
- }
- }
- );
- }
- });
-
return { responseText, provider, selectedModel };
}
diff --git a/server/services/agentPersonalityGenerator.js b/server/services/agentPersonalityGenerator.js
index deb9a53fe0..2f0d10b7b5 100644
--- a/server/services/agentPersonalityGenerator.js
+++ b/server/services/agentPersonalityGenerator.js
@@ -5,7 +5,7 @@
* Generates style, tone, topics, quirks, and prompt prefix for social platform agents.
*/
-import { executeApiRun, executeCliRun, createRun } from './runner.js';
+import { runPromptThroughProvider } from '../lib/promptRunner.js';
import { getActiveProvider, getProviderById } from './providers.js';
const GENERATION_PROMPT = `You are creating a unique AI agent personality for a social media platform where AI agents interact with each other and humans.
@@ -78,8 +78,10 @@ export async function generateAgentPersonality(seed = {}, providerId = null, mod
throw new Error('No AI provider available for personality generation');
}
- // Determine model
- const selectedModel = model || provider.defaultModel || provider.models?.[0];
+ // Caller's requested model — passed to the central handler as a hint.
+ // The handler returns the model that actually executed, which is what
+ // we record on the personality below.
+ const requestedModel = model || provider.defaultModel || provider.models?.[0];
// Build the input section based on what's provided as seed content
const seedLines = [];
@@ -129,65 +131,13 @@ export async function generateAgentPersonality(seed = {}, providerId = null, mod
// Build the prompt
const fullPrompt = GENERATION_PROMPT.replace('{inputSection}', inputSection);
- // Create a run for this generation
- const { runId } = await createRun({
- providerId: provider.id,
- model: selectedModel,
- prompt: fullPrompt,
- source: 'agent-personality-generation'
- });
-
- // Collect the response
- let responseText = '';
-
- // Use appropriate execution method based on provider type
- const isCliProvider = provider.type === 'cli';
-
- await new Promise((resolve, reject) => {
- if (isCliProvider) {
- // CLI providers use executeCliRun
- executeCliRun(
- runId,
- provider,
- fullPrompt,
- process.cwd(),
- (text) => {
- responseText += text;
- },
- (result) => {
- if (result?.error || result?.success === false) {
- reject(new Error(result?.error || 'CLI execution failed'));
- } else {
- resolve(result);
- }
- },
- provider.timeout || 300000
- );
- } else {
- // API providers use executeApiRun
- executeApiRun(
- runId,
- provider,
- selectedModel,
- fullPrompt,
- process.cwd(),
- [],
- (data) => {
- responseText += typeof data === 'string' ? data : (data?.text || '');
- },
- (result) => {
- if (result?.error) {
- reject(new Error(result.error));
- } else {
- resolve(result);
- }
- }
- );
- }
+ const { text, model: effectiveModel } = await runPromptThroughProvider({
+ provider, prompt: fullPrompt, source: 'agent-personality-generation', model: requestedModel,
});
+ const selectedModel = effectiveModel || requestedModel;
// Parse the JSON response
- responseText = responseText.trim();
+ let responseText = text.trim();
// Check for empty response
if (!responseText) {
diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.js
index 601832195c..da3a9d3cef 100644
--- a/server/services/agentPromptBuilder.js
+++ b/server/services/agentPromptBuilder.js
@@ -14,7 +14,7 @@ import { getDigitalTwinForPrompt } from './digital-twin.js';
import { buildPrompt } from './promptService.js';
import { getToolsSummaryForPrompt } from './tools.js';
import { getActiveProvider } from './providers.js';
-import { executeApiRun, executeCliRun, createRun } from './runner.js';
+import { runPromptThroughProvider } from '../lib/promptRunner.js';
import { readJSONFile, loadSlashdoFile, PATHS } from '../lib/fileUtils.js';
import * as jiraService from './jira.js';
import { emitLog } from './cosEvents.js';
@@ -780,23 +780,18 @@ export async function generateJiraTitle(description) {
const prompt = `Generate a concise JIRA ticket title (max 80 chars) for this task. Output ONLY the title text, nothing else.\n\nTask: ${description}`;
- const { runId } = await createRun({ providerId: provider.id, model, prompt, source: 'jira-title' }).catch(() => ({}));
- if (!runId) return fallback;
-
- let title = '';
-
- await new Promise((resolve) => {
- const onData = (data) => { title += typeof data === 'string' ? data : (data?.text || ''); };
- const onDone = () => resolve();
-
- if (provider.type === 'cli') {
- executeCliRun(runId, provider, prompt, process.cwd(), onData, onDone, 30000);
- } else {
- executeApiRun(runId, provider, model, prompt, process.cwd(), [], onData, onDone);
- }
- }).catch(err => console.warn(`⚠️ JIRA title generation failed: ${err.message}`));
+ // Best-effort title — failures are non-fatal (the task still gets the
+ // truncated-description fallback). 30s is the legacy cap; titles should
+ // be near-instant, and a slow model shouldn't block task creation.
+ const result = await runPromptThroughProvider({
+ provider, prompt, source: 'jira-title', model, timeout: 30000,
+ }).catch(err => {
+ console.warn(`⚠️ JIRA title generation failed: ${err.message}`);
+ return null;
+ });
+ if (!result) return fallback;
- title = title.trim().replace(/^["']|["']$/g, '');
+ const title = (result.text || '').trim().replace(/^["']|["']$/g, '');
return title || fallback;
}
diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.js
index a0b3d7b56a..fe3d989b70 100644
--- a/server/services/agentTuiSpawning.js
+++ b/server/services/agentTuiSpawning.js
@@ -24,38 +24,34 @@ import { persistSimplifySummaries } from './agentLifecycle.js';
import { activeAgents, userTerminatedAgents } from './agentState.js';
import { PATHS } from '../lib/fileUtils.js';
import { resolveCliModel } from '../lib/providerModels.js';
-
-const DEFAULT_TUI_PROMPT_DELAY_MS = 2500;
-const DEFAULT_TUI_IDLE_TIMEOUT_MS = 180000;
+import { createStreamingAnsiStripper } from '../lib/ansiStrip.js';
+import {
+ DEFAULT_TUI_PROMPT_DELAY_MS,
+ DEFAULT_TUI_IDLE_TIMEOUT_MS,
+ READY_POLL_INTERVAL_MS,
+ READY_IDLE_THRESHOLD_MS,
+ PASTE_MARKER_POLL_MS,
+ PASTE_MARKER_PATTERN,
+ PASTE_TO_ENTER_MIN_DELAY_MS,
+ PASTE_TO_ENTER_FALLBACK_MS,
+ PASTE_DEADLINE_MS,
+ RAW_BUFFER_CAP,
+ RAW_BUFFER_HEADROOM,
+ OUTPUT_BUFFER_CAP,
+ OUTPUT_BUFFER_HEADROOM,
+ inferTuiCommand,
+ applyCommandDefaults,
+} from '../lib/tuiHandshake.js';
+
+// Agent-specific timing/lifecycle constants (not shared with the one-shot
+// runner — agents stay alive much longer and write a sentinel file when done).
const DEFAULT_TUI_MIN_RUNTIME_MS = 15000;
-const RAW_BUFFER_CAP = 512 * 1024;
-const RAW_BUFFER_HEADROOM = 640 * 1024;
-const OUTPUT_BUFFER_CAP = 1024 * 1024;
-const OUTPUT_BUFFER_HEADROOM = 1280 * 1024;
// Debounce window for batching parsed output to disk + state. A chatty TUI can
// emit hundreds of lines/sec; without batching, each line triggers a full
// state load+save (see appendAgentOutput) and a small appendFile, which slows
// the PTY event loop and thrashes the filesystem. 250ms is invisible to the
// live tail but cuts I/O by 1-2 orders of magnitude.
const OUTPUT_FLUSH_INTERVAL_MS = 250;
-
-// Paste readiness gating. The TUI process needs time to render its welcome
-// banner and become input-ready before bracketed paste lands; sending the paste
-// during boot loses the entire prompt. We poll for output-idle (TUI has stopped
-// repainting) instead of guessing a fixed delay, with a hard upper bound so a
-// silent provider still gets the prompt eventually.
-const READY_POLL_INTERVAL_MS = 300;
-const READY_IDLE_THRESHOLD_MS = 1200;
-// Wait for Claude Code's `[Pasted text #N +M lines]` marker to appear before
-// sending `\r`. A fixed 400 ms timer was too short for large prompts (87+
-// line pastes) — Claude Code was still committing the paste buffer when the
-// Enter arrived, so the Enter got swallowed. The marker is emitted as soon
-// as the paste is committed and the input cursor is ready for submit.
-const PASTE_MARKER_POLL_MS = 150;
-const PASTE_MARKER_PATTERN = /\[Pasted text #\d+/;
-const PASTE_TO_ENTER_MIN_DELAY_MS = 200;
-const PASTE_TO_ENTER_FALLBACK_MS = 3500;
-const PASTE_DEADLINE_MS = 10000;
// Sentinel-file polling. TUI agents write `.agent-done` in their workspace
// when they've finished /simplify + /do:pr (or /do:push) — we poll for it
// here so the agent gets cleanly finalized as soon as the work is done,
@@ -63,41 +59,6 @@ const PASTE_DEADLINE_MS = 10000;
const DONE_SENTINEL_NAME = '.agent-done';
const DONE_POLL_INTERVAL_MS = 2000;
-const ANSI_PATTERN = /\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/g;
-
-// Heuristics for a trailing chunk that *might* be an unterminated escape
-// sequence. We hold the tail back from the strip pass and prepend it to the
-// next chunk, so a CSI/OSC split across two PTY reads still strips cleanly
-// instead of leaking the body (e.g. `0;Claude Code…`) into displayed output.
-const INCOMPLETE_CSI = /^\x1B\[[0-?]*[ -/]*$/;
-const INCOMPLETE_OSC = /^\x1B\][^\x07\x1B]*$/;
-const INCOMPLETE_ESC_2BYTE = /^\x1B$/;
-
-function createStreamingAnsiStripper() {
- let tail = '';
- const strip = (s) => s.replace(ANSI_PATTERN, '').replace(/\x00/g, '');
- return (text) => {
- const combined = tail + text;
- tail = '';
- const lastEsc = combined.lastIndexOf('\x1B');
- // Only consider the trailing fragment if it lives near the end — older
- // unterminated bytes belong to a previous repaint and would never resolve.
- // Bodies longer than 4096 bytes are treated as terminated; an unbounded
- // OSC (e.g. very long hyperlink) would leak its body to display rather
- // than buffer forever.
- if (lastEsc !== -1 && combined.length - lastEsc <= 4096) {
- const candidate = combined.slice(lastEsc);
- if (INCOMPLETE_ESC_2BYTE.test(candidate)
- || INCOMPLETE_CSI.test(candidate)
- || INCOMPLETE_OSC.test(candidate)) {
- tail = candidate;
- return strip(combined.slice(0, lastEsc));
- }
- }
- return strip(combined);
- };
-}
-
function shellQuote(value) {
const text = String(value ?? '');
if (/^[A-Za-z0-9_./:=+-]+$/.test(text)) return text;
@@ -109,24 +70,6 @@ function appendModelArgs(args, model) {
return effectiveModel ? [...args, '--model', effectiveModel] : args;
}
-function inferTuiCommand(id) {
- if (!id) return 'claude';
- if (id.includes('codex')) return 'codex';
- if (id.includes('gemini')) return 'gemini';
- return 'claude';
-}
-
-// Without `--ask-for-approval never`, codex TUI blocks on the user to approve
-// every tool call — there's no human at the keyboard for sub-agent runs, so
-// the session hangs until idle-timeout. Injected here (vs. requiring it in
-// every saved provider config) so existing installs upgrade automatically.
-function applyCommandDefaults(command, args) {
- if (command === 'codex' && !args.includes('--ask-for-approval')) {
- return ['--ask-for-approval', 'never', ...args];
- }
- return args;
-}
-
export function buildTuiSpawnConfig(provider, model) {
const command = provider?.command || inferTuiCommand(provider?.id);
const baseArgs = applyCommandDefaults(command, [...(provider?.args || [])]);
diff --git a/server/services/brain.js b/server/services/brain.js
index d4917fbdb7..16f681d4b6 100644
--- a/server/services/brain.js
+++ b/server/services/brain.js
@@ -8,14 +8,13 @@
* - Handle corrections and fixes
*/
-import { spawn } from 'child_process';
import * as storage from './brainStorage.js';
import { brainEvents } from './brainStorage.js';
import { getActiveProvider, getProviderById } from './providers.js';
import { buildPrompt } from './promptService.js';
import { validate } from '../lib/validation.js';
import { safeJSONParse } from '../lib/fileUtils.js';
-import { resolveCliModel } from '../lib/providerModels.js';
+import { runPromptThroughProvider } from '../lib/promptRunner.js';
import {
classifierOutputSchema,
digestOutputSchema,
@@ -60,101 +59,18 @@ async function callAI(promptStageName, variables, providerOverride, modelOverrid
console.log(`🧠 Calling AI: ${provider.id} / ${model} / ${promptStageName}`);
- if (provider.type === 'cli') {
+ // brain runs are headless classification — append the provider's
+ // headlessArgs (e.g. claude-code's --no-session-persistence) so the
+ // user's session list doesn't fill up with classifier transcripts.
+ // The clone leaves the saved provider config untouched.
+ const providerForCall = provider.headlessArgs?.length
+ ? { ...provider, args: [...(provider.args || []), ...provider.headlessArgs] }
+ : provider;
- return new Promise((resolve, reject) => {
- const args = [...(provider.args || [])];
- if (provider.headlessArgs?.length) {
- args.push(...provider.headlessArgs);
- }
- // gemini-cli prompt delivery differs here from runner.js and agentCliSpawning.js:
- // those pipe the prompt via stdin for streaming runs, while this path uses
- // stdio: ['ignore', ...] for one-shot headless classification. With stdin ignored,
- // gemini-cli flips to interactive mode and hangs — so the prompt must go via
- // --prompt, and --output-format text skips interactive-mode detection overhead.
- const isGeminiCli = provider.id === 'gemini-cli';
- if (isGeminiCli && !args.includes('--output-format') && !args.includes('-o')) {
- args.push('--output-format', 'text');
- }
- const cliModel = resolveCliModel(model);
- if (cliModel) {
- args.push('--model', cliModel);
- }
- if (isGeminiCli) {
- args.push('--prompt', prompt);
- } else {
- args.push(prompt);
- }
- let output = '';
-
- const child = spawn(provider.command, args, {
- env: (() => { const e = { ...process.env, ...provider.envVars }; delete e.CLAUDECODE; return e; })(),
- stdio: ['ignore', 'pipe', 'pipe'],
- shell: false,
- windowsHide: true
- });
-
- child.stdout.on('data', (data) => {
- output += data.toString();
- });
-
- child.stderr.on('data', (data) => {
- output += data.toString();
- });
-
- const timeoutMs = provider.timeout || 300000;
- const killTimer = setTimeout(() => {
- child.kill('SIGKILL');
- reject(new Error(`CLI AI call timed out after ${timeoutMs}ms`));
- }, timeoutMs);
-
- child.on('close', (code) => {
- clearTimeout(killTimer);
- if (code === 0) {
- resolve({ content: output, model, providerId: provider.id });
- } else {
- reject(new Error(`CLI exited with code ${code}${output ? ': ' + output.substring(0, 500) : ''}`));
- }
- });
-
- child.on('error', (err) => {
- clearTimeout(killTimer);
- reject(err);
- });
- });
- }
-
- if (provider.type === 'api') {
- const headers = { 'Content-Type': 'application/json' };
- if (provider.apiKey) {
- headers['Authorization'] = `Bearer ${provider.apiKey}`;
- }
-
- const response = await fetch(`${provider.endpoint}/chat/completions`, {
- method: 'POST',
- headers,
- body: JSON.stringify({
- model,
- messages: [{ role: 'user', content: prompt }],
- temperature: 0.1
- }),
- signal: AbortSignal.timeout(provider.timeout || 300000)
- });
-
- if (!response.ok) {
- const errorText = await response.text();
- throw new Error(`AI API error: ${response.status} - ${errorText}`);
- }
-
- const data = await response.json();
- return {
- content: data.choices?.[0]?.message?.content || '',
- model,
- providerId: provider.id
- };
- }
-
- throw new Error(`Unsupported provider type: ${provider.type}`);
+ const { text, model: effectiveModel } = await runPromptThroughProvider({
+ provider: providerForCall, prompt, source: `brain-${promptStageName}`, model,
+ });
+ return { content: text, model: effectiveModel || model, providerId: provider.id };
}
/**
diff --git a/server/services/brain.test.js b/server/services/brain.test.js
index fda276b29a..3fc4ff0fb3 100644
--- a/server/services/brain.test.js
+++ b/server/services/brain.test.js
@@ -78,12 +78,16 @@ vi.mock('../lib/fileUtils.js', () => ({
})
}));
-// Mock child_process
-vi.mock('child_process', () => ({
- spawn: vi.fn()
+// Mock the central LLM handler — brain.js used to spawn child_process
+// directly, but now delegates to runPromptThroughProvider. Tests stub it to
+// return canned responses; the runner-internal mechanics (spawn args, --model
+// flag injection, stdio shape, gemini-cli --output-format) are covered by
+// runner.test.js, not here.
+vi.mock('../lib/promptRunner.js', () => ({
+ runPromptThroughProvider: vi.fn()
}));
-import { spawn } from 'child_process';
+import { runPromptThroughProvider } from '../lib/promptRunner.js';
import * as storage from './brainStorage.js';
import { getProviderById } from './providers.js';
import {
@@ -625,12 +629,7 @@ describe('brain service', () => {
};
// Mock fetch for API provider
- globalThis.fetch = vi.fn().mockResolvedValue({
- ok: true,
- json: () => Promise.resolve({
- choices: [{ message: { content: JSON.stringify(digestResponse) } }]
- })
- });
+ runPromptThroughProvider.mockResolvedValue({ text: JSON.stringify(digestResponse), runId: "test-run", model: "test-model" });
storage.createDigest.mockResolvedValue({ id: 'digest-001', ...digestResponse });
@@ -663,12 +662,7 @@ describe('brain service', () => {
smallWin: 'Yes'
};
- globalThis.fetch = vi.fn().mockResolvedValue({
- ok: true,
- json: () => Promise.resolve({
- choices: [{ message: { content: JSON.stringify(digestResponse) } }]
- })
- });
+ runPromptThroughProvider.mockResolvedValue({ text: JSON.stringify(digestResponse), runId: "test-run", model: "test-model" });
storage.createDigest.mockImplementation(async (data) => ({ id: 'digest-001', ...data }));
@@ -700,24 +694,16 @@ describe('brain service', () => {
smallWin: 'Win'
};
- globalThis.fetch = vi.fn().mockResolvedValue({
- ok: true,
- json: () => Promise.resolve({
- choices: [{ message: { content: JSON.stringify(digestResponse) } }]
- })
- });
+ runPromptThroughProvider.mockResolvedValue({ text: JSON.stringify(digestResponse), runId: "test-run", model: "test-model" });
storage.createDigest.mockImplementation(async (data) => ({ id: 'd1', ...data }));
await runDailyDigest();
- // Verify fetch was called with body containing only Alice (has followUps)
- const fetchCall = globalThis.fetch.mock.calls[0];
- const body = JSON.parse(fetchCall[1].body);
- const promptContent = body.messages[0].content;
- // The prompt should contain the stringified peopleWithFollowUps
- // We can't easily check the prompt content without knowing the template,
- // but we can verify the storage calls
+ // After the central-handler migration we no longer inspect the raw
+ // request body — the storage-call assertion is what proves the filter
+ // ran. The prompt content is built inside the central handler from
+ // the variables we passed in.
expect(storage.getPeople).toHaveBeenCalled();
});
@@ -731,12 +717,7 @@ describe('brain service', () => {
getProviderById.mockResolvedValue(mockProvider);
// Return invalid format (missing required fields)
- globalThis.fetch = vi.fn().mockResolvedValue({
- ok: true,
- json: () => Promise.resolve({
- choices: [{ message: { content: JSON.stringify({ wrong: 'format' }) } }]
- })
- });
+ runPromptThroughProvider.mockResolvedValue({ text: JSON.stringify({ wrong: 'format' }), runId: 'test-run', model: 'test-model' });
await expect(runDailyDigest()).rejects.toThrow('Invalid digest output');
});
@@ -773,12 +754,7 @@ describe('brain service', () => {
recurringTheme: 'Productivity'
};
- globalThis.fetch = vi.fn().mockResolvedValue({
- ok: true,
- json: () => Promise.resolve({
- choices: [{ message: { content: JSON.stringify(reviewResponse) } }]
- })
- });
+ runPromptThroughProvider.mockResolvedValue({ text: JSON.stringify(reviewResponse), runId: "test-run", model: "test-model" });
storage.createReview.mockResolvedValue({ id: 'review-001', ...reviewResponse });
@@ -809,12 +785,7 @@ describe('brain service', () => {
recurringTheme: 'Theme'
};
- globalThis.fetch = vi.fn().mockResolvedValue({
- ok: true,
- json: () => Promise.resolve({
- choices: [{ message: { content: JSON.stringify(reviewResponse) } }]
- })
- });
+ runPromptThroughProvider.mockResolvedValue({ text: JSON.stringify(reviewResponse), runId: "test-run", model: "test-model" });
storage.createReview.mockImplementation(async (data) => ({ id: 'r1', ...data }));
@@ -832,12 +803,7 @@ describe('brain service', () => {
const mockProvider = { id: 'lmstudio', enabled: true, type: 'api', endpoint: 'http://localhost:1234/v1', defaultModel: 'test' };
getProviderById.mockResolvedValue(mockProvider);
- globalThis.fetch = vi.fn().mockResolvedValue({
- ok: true,
- json: () => Promise.resolve({
- choices: [{ message: { content: JSON.stringify({ bad: 'data' }) } }]
- })
- });
+ runPromptThroughProvider.mockResolvedValue({ text: JSON.stringify({ bad: 'data' }), runId: 'test-run', model: 'test-model' });
await expect(runWeeklyReview()).rejects.toThrow('Invalid review output');
});
@@ -867,12 +833,7 @@ describe('brain service', () => {
// Wrap in markdown code block
const wrappedResponse = '```json\n' + JSON.stringify(digestResponse) + '\n```';
- globalThis.fetch = vi.fn().mockResolvedValue({
- ok: true,
- json: () => Promise.resolve({
- choices: [{ message: { content: wrappedResponse } }]
- })
- });
+ runPromptThroughProvider.mockResolvedValue({ text: wrappedResponse, runId: "test-run", model: "test-model" });
storage.createDigest.mockImplementation(async (data) => ({ id: 'd1', ...data }));
@@ -889,12 +850,7 @@ describe('brain service', () => {
const mockProvider = { id: 'lmstudio', enabled: true, type: 'api', endpoint: 'http://localhost:1234/v1', defaultModel: 'test' };
getProviderById.mockResolvedValue(mockProvider);
- globalThis.fetch = vi.fn().mockResolvedValue({
- ok: true,
- json: () => Promise.resolve({
- choices: [{ message: { content: '' } }]
- })
- });
+ runPromptThroughProvider.mockResolvedValue({ text: '', runId: "test-run", model: "test-model" });
await expect(runDailyDigest()).rejects.toThrow('Empty or invalid AI response');
});
@@ -936,24 +892,87 @@ describe('brain service', () => {
const mockProvider = { id: 'lmstudio', enabled: true, type: 'api', endpoint: 'http://localhost:1234/v1', defaultModel: 'test' };
getProviderById.mockResolvedValue(mockProvider);
- globalThis.fetch = vi.fn().mockResolvedValue({
- ok: false,
- status: 500,
- text: () => Promise.resolve('Internal Server Error')
- });
+ // Central handler rejects on upstream API failure; the message format
+ // changed from "AI API error: 500" (old direct-fetch) to whatever the
+ // toolkit's executeApiRun surfaces. Test just asserts a rejection now.
+ runPromptThroughProvider.mockRejectedValue(new Error('AI API error: 500'));
await expect(runDailyDigest()).rejects.toThrow('AI API error: 500');
});
- it('should throw for unsupported provider type', async () => {
+ // Removed: "should throw for unsupported provider type" — that
+ // validation moved to runPromptThroughProvider (lib/promptRunner.js),
+ // which is covered by promptRunner.test.js. brain.js no longer
+ // dispatches on provider.type directly.
+ });
+
+ // ===========================================================================
+ // headlessArgs — brain runs are classifier-style and must not pollute the
+ // user's Claude Code session list. brain.js appends provider.headlessArgs
+ // to a per-call provider clone before calling the central handler.
+ // Regression coverage for the migration from spawn() to runPromptThroughProvider.
+ // ===========================================================================
+
+ describe('headlessArgs preservation', () => {
+ it('appends provider.headlessArgs to the provider passed to the central handler', async () => {
storage.getProjects.mockResolvedValue([{ id: 'p1', name: 'Proj', status: 'active' }]);
storage.getAdminItems.mockResolvedValue([]);
storage.getPeople.mockResolvedValue([]);
storage.getInboxLog.mockResolvedValue([]);
+ storage.createDigest.mockImplementation(async (data) => ({ id: 'd1', ...data }));
- getProviderById.mockResolvedValue({ id: 'weird', enabled: true, type: 'smoke_signal', defaultModel: 'test' });
+ getProviderById.mockResolvedValue({
+ id: 'claude-code',
+ enabled: true,
+ type: 'cli',
+ command: 'claude',
+ args: ['--print'],
+ headlessArgs: ['--no-session-persistence', '--disable-slash-commands'],
+ defaultModel: 'claude-opus-4-7'
+ });
+
+ runPromptThroughProvider.mockResolvedValue({
+ text: JSON.stringify({
+ digestText: 'd', topActions: ['a'], stuckThing: 's', smallWin: 'w'
+ }),
+ runId: 'r', model: 'claude-opus-4-7'
+ });
- await expect(runDailyDigest()).rejects.toThrow('Unsupported provider type: smoke_signal');
+ await runDailyDigest('claude-code');
+
+ const passedProvider = runPromptThroughProvider.mock.calls[0][0].provider;
+ expect(passedProvider.args).toEqual([
+ '--print', '--no-session-persistence', '--disable-slash-commands'
+ ]);
+ });
+
+ it('does not clone the provider when headlessArgs is empty/absent', async () => {
+ storage.getProjects.mockResolvedValue([{ id: 'p1', name: 'Proj', status: 'active' }]);
+ storage.getAdminItems.mockResolvedValue([]);
+ storage.getPeople.mockResolvedValue([]);
+ storage.getInboxLog.mockResolvedValue([]);
+ storage.createDigest.mockImplementation(async (data) => ({ id: 'd1', ...data }));
+
+ const provider = {
+ id: 'lmstudio',
+ enabled: true,
+ type: 'api',
+ endpoint: 'http://localhost:1234/v1',
+ defaultModel: 'test'
+ };
+ getProviderById.mockResolvedValue(provider);
+
+ runPromptThroughProvider.mockResolvedValue({
+ text: JSON.stringify({
+ digestText: 'd', topActions: ['a'], stuckThing: 's', smallWin: 'w'
+ }),
+ runId: 'r', model: 'test'
+ });
+
+ await runDailyDigest('lmstudio');
+
+ const passedProvider = runPromptThroughProvider.mock.calls[0][0].provider;
+ expect(passedProvider).toBe(provider);
});
});
@@ -1006,206 +1025,4 @@ describe('brain service', () => {
expect(getSummary).toBe(storage.getSummary);
});
});
-
- // ===========================================================================
- // callAI CLI path — gemini-cli argv construction
- // Guards against regressions like reintroducing interactive-mode detection,
- // dropping --prompt, or losing the thinking-model fallback.
- // ===========================================================================
-
- describe('callAI CLI path (gemini-cli argv)', () => {
- function createMockChild(stdoutPayload) {
- const child = new EventEmitter();
- child.stdout = new EventEmitter();
- child.stderr = new EventEmitter();
- child.kill = vi.fn();
- // Emit payload and close on next tick so listeners attach first
- setImmediate(() => {
- child.stdout.emit('data', Buffer.from(stdoutPayload));
- child.emit('close', 0);
- });
- return child;
- }
-
- const validDigestJson = JSON.stringify({
- digestText: 'tiny digest',
- topActions: ['a'],
- stuckThing: 's',
- smallWin: 'w'
- });
-
- beforeEach(() => {
- // Override outer beforeEach's defaultModel so the callAI fallback path is reachable
- storage.loadMeta.mockResolvedValue({
- confidenceThreshold: 0.6,
- defaultProvider: 'gemini-cli',
- defaultModel: null
- });
- storage.getProjects.mockResolvedValue([{ id: 'p1', name: 'Proj', status: 'active' }]);
- storage.getAdminItems.mockResolvedValue([]);
- storage.getPeople.mockResolvedValue([]);
- storage.getInboxLog.mockResolvedValue([]);
- storage.createDigest.mockResolvedValue({ id: 'd1' });
- storage.updateMeta.mockResolvedValue();
- });
-
- it('passes prompt via --prompt, forces --output-format text, and falls back to flash-lite when model unset', async () => {
- getProviderById.mockResolvedValue({
- id: 'gemini-cli',
- enabled: true,
- type: 'cli',
- command: 'gemini',
- args: [],
- timeout: 50
- // defaultModel deliberately unset — exercises the flash fallback
- });
- spawn.mockReturnValue(createMockChild(validDigestJson));
-
- await runDailyDigest('gemini-cli');
-
- expect(spawn).toHaveBeenCalledTimes(1);
- const [command, args, opts] = spawn.mock.calls[0];
- expect(command).toBe('gemini');
- expect(opts.stdio).toEqual(['ignore', 'pipe', 'pipe']);
-
- // Non-interactive output format pinned
- const outputFmtIdx = args.indexOf('--output-format');
- expect(outputFmtIdx).toBeGreaterThanOrEqual(0);
- expect(args[outputFmtIdx + 1]).toBe('text');
-
- // Thinking-model fallback
- const modelIdx = args.indexOf('--model');
- expect(modelIdx).toBeGreaterThanOrEqual(0);
- expect(args[modelIdx + 1]).toBe('gemini-2.5-flash');
-
- // Prompt delivered via flag (not positional) so gemini-cli stays non-interactive
- const promptIdx = args.indexOf('--prompt');
- expect(promptIdx).toBeGreaterThanOrEqual(0);
- expect(args[promptIdx + 1]).toBe('test prompt');
- });
-
- it('honors an explicit model override instead of the flash fallback', async () => {
- getProviderById.mockResolvedValue({
- id: 'gemini-cli',
- enabled: true,
- type: 'cli',
- command: 'gemini',
- args: [],
- defaultModel: 'gemini-2.5-pro',
- timeout: 50
- });
- spawn.mockReturnValue(createMockChild(validDigestJson));
-
- await runDailyDigest('gemini-cli');
-
- const args = spawn.mock.calls[0][1];
- const modelIdx = args.indexOf('--model');
- expect(args[modelIdx + 1]).toBe('gemini-2.5-pro');
- });
-
- 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: [],
- // 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
- });
- spawn.mockReturnValue(createMockChild(validDigestJson));
-
- await runDailyDigest('gemini-cli');
-
- const args = spawn.mock.calls[0][1];
- const modelIdx = args.indexOf('--model');
- expect(args[modelIdx + 1]).toBe('gemini-3-flash');
- });
-
- it('does not duplicate --output-format when provider args already specify it', async () => {
- getProviderById.mockResolvedValue({
- id: 'gemini-cli',
- enabled: true,
- type: 'cli',
- command: 'gemini',
- args: ['--output-format', 'json'],
- defaultModel: 'gemini-2.5-flash',
- timeout: 50
- });
- spawn.mockReturnValue(createMockChild(validDigestJson));
-
- await runDailyDigest('gemini-cli');
-
- const args = spawn.mock.calls[0][1];
- const occurrences = args.filter(a => a === '--output-format').length;
- expect(occurrences).toBe(1);
- expect(args[args.indexOf('--output-format') + 1]).toBe('json');
- });
-
- it('persists the resolved model in digest ai.modelId so attribution survives the fallback', async () => {
- getProviderById.mockResolvedValue({
- id: 'gemini-cli',
- enabled: true,
- type: 'cli',
- command: 'gemini',
- args: [],
- timeout: 50
- // defaultModel and lightModel unset — forces the hard-coded fallback
- });
- spawn.mockReturnValue(createMockChild(validDigestJson));
- // Capture the digest record so we can assert its ai metadata
- let storedDigest = null;
- storage.createDigest.mockImplementation(async (data) => {
- storedDigest = data;
- return { id: 'd-attr', ...data };
- });
-
- await runDailyDigest('gemini-cli');
-
- expect(storedDigest).toBeTruthy();
- expect(storedDigest.ai.providerId).toBe('gemini-cli');
- expect(storedDigest.ai.modelId).toBe('gemini-2.5-flash');
- });
-
- it('uses positional prompt (not --prompt) for non-gemini CLI providers', async () => {
- getProviderById.mockResolvedValue({
- id: 'claude-code',
- enabled: true,
- type: 'cli',
- command: 'claude',
- args: ['-p'],
- defaultModel: 'sonnet',
- timeout: 50
- });
- spawn.mockReturnValue(createMockChild(validDigestJson));
-
- await runDailyDigest('claude-code');
-
- const args = spawn.mock.calls[0][1];
- expect(args).not.toContain('--prompt');
- expect(args).not.toContain('--output-format');
- expect(args[args.length - 1]).toBe('test prompt');
- });
-
- it('omits --model entirely when defaultModel is the codex sentinel', async () => {
- getProviderById.mockResolvedValue({
- id: 'codex',
- enabled: true,
- type: 'cli',
- command: 'codex',
- args: [],
- defaultModel: 'codex-configured-default',
- timeout: 50
- });
- spawn.mockReturnValue(createMockChild(validDigestJson));
-
- await runDailyDigest('codex');
-
- const args = spawn.mock.calls[0][1];
- expect(args).not.toContain('--model');
- });
- });
});
diff --git a/server/services/loops.js b/server/services/loops.js
index 3fb7d53677..751e91b8ea 100644
--- a/server/services/loops.js
+++ b/server/services/loops.js
@@ -12,7 +12,8 @@ import { readFile, writeFile } from 'fs/promises';
import { join } from 'path';
import { PATHS, ensureDir } from '../lib/fileUtils.js';
import { randomUUID } from 'crypto';
-import { createRun, executeCliRun } from './runner.js';
+import { createRun } from './runner.js';
+import { runPromptThroughProvider } from '../lib/promptRunner.js';
import { getProviderById, getAllProviders, getActiveProvider } from './providers.js';
export const loopEvents = new EventEmitter();
@@ -95,7 +96,10 @@ async function executeIteration(loop) {
lineCount: outputLines.length,
duration: metadata.duration,
provider: provider.name,
- model: provider.defaultModel,
+ // The model the central handler actually ran (set by the .then below
+ // when the run resolved), with provider.defaultModel as the fallback
+ // for the failure path where executedModel is still null.
+ model: metadata.model || provider.defaultModel,
timestamp: Date.now()
};
@@ -128,6 +132,9 @@ async function executeIteration(loop) {
console.log(`🔄 Loop ${id} iteration ${iterationNum} complete (${provider.name}, exit ${metadata.exitCode}, ${outputLines.length} lines)`);
};
+ // Pre-create the run so `active.runId` can be set before generation
+ // starts (cancellation needs the id). The central handler reuses our
+ // runId when provided rather than creating a second one.
const runResult = await createRun({
providerId: provider.id,
prompt: loop.prompt,
@@ -146,19 +153,50 @@ async function executeIteration(loop) {
active.runId = runResult.metadata.id;
- executeCliRun(
- runResult.metadata.id,
- runResult.provider,
- loop.prompt,
- loop.cwd || PATHS.root,
- onData,
- onComplete,
- loop.timeout || DEFAULT_TIMEOUT_MS
- ).catch(err => {
- active.running = false;
- active.runId = null;
+ // The toolkit's createRun may switch to a fallback provider when the
+ // requested one is marked unavailable (providerStatusService). Reassign
+ // `provider` to the effective one so dispatch, onComplete's
+ // history/persistence side, and the `iteration:complete` event all see
+ // the provider that actually ran. Without this, fallback would only
+ // update the run record while the spawn still hit the dead provider.
+ if (runResult.provider && runResult.provider.id !== provider.id) {
+ provider = runResult.provider;
+ }
+
+ // Adapt the central handler's resolve/reject to the legacy onComplete
+ // metadata shape. We can't get the runner's full metadata back from
+ // runPromptThroughProvider today — it only resolves `{ text, runId,
+ // model }`. Reconstruct the bits onComplete inspects (exitCode + success
+ // + duration) from the promise resolution; pass through `model` so
+ // iterResult records what actually ran (not just the saved default).
+ const startedAt = Date.now();
+ runPromptThroughProvider({
+ provider, prompt: loop.prompt, source: 'loop', runId: runResult.metadata.id,
+ onData, timeout: loop.timeout || DEFAULT_TIMEOUT_MS,
+ // loop.cwd is a user-facing setting on each loop record — without this
+ // pass-through, every loop runs against PortOS's own cwd instead of
+ // the directory the user picked.
+ cwd: loop.cwd || PATHS.root,
+ }).then(({ model: executedModel }) => {
+ onComplete({ exitCode: 0, success: true, duration: Date.now() - startedAt, model: executedModel });
+ }).catch(err => {
+ // Pre-migration `executeCliRun` always invoked `onComplete` — even on
+ // non-zero exit — so loop history / persistence / `iteration:complete`
+ // observers saw failed runs too. The .then/.catch split here would
+ // skip onComplete on failure and only emit `iteration:error`, breaking
+ // anything that subscribed to completes (history.push, lastExitCode
+ // persistence). Fire onComplete with a failure shape before the error
+ // event so the history + persistence side stays consistent.
+ const failureMetadata = {
+ exitCode: 1,
+ success: false,
+ duration: Date.now() - startedAt,
+ error: err.message,
+ model: provider.defaultModel,
+ };
+ onComplete(failureMetadata).catch(() => { /* history write is best-effort */ });
loopEvents.emit('iteration:error', { id, iteration: iterationNum, error: err.message, timestamp: Date.now() });
- console.error(`❌ Loop ${id} executeCliRun failed: ${err.message}`);
+ console.error(`❌ Loop ${id} run failed: ${err.message}`);
});
}
diff --git a/server/services/loops.test.js b/server/services/loops.test.js
index d14f22c015..bb122c5d17 100644
--- a/server/services/loops.test.js
+++ b/server/services/loops.test.js
@@ -19,8 +19,11 @@ vi.mock('../lib/fileUtils.js', () => ({
}));
vi.mock('./runner.js', () => ({
- createRun: vi.fn(),
- executeCliRun: vi.fn()
+ createRun: vi.fn()
+}));
+
+vi.mock('../lib/promptRunner.js', () => ({
+ runPromptThroughProvider: vi.fn()
}));
vi.mock('./providers.js', () => ({
@@ -30,7 +33,8 @@ vi.mock('./providers.js', () => ({
}));
import { readFile, writeFile } from 'fs/promises';
-import { createRun, executeCliRun } from './runner.js';
+import { createRun } from './runner.js';
+import { runPromptThroughProvider } from '../lib/promptRunner.js';
import { getProviderById, getActiveProvider } from './providers.js';
import {
createLoop,
@@ -42,7 +46,7 @@ import {
// Convenience aliases after import
const mockCreateRun = createRun;
-const mockExecuteCliRun = executeCliRun;
+const mockRunPrompt = runPromptThroughProvider;
const mockGetProviderById = getProviderById;
const mockGetActiveProvider = getActiveProvider;
@@ -62,8 +66,9 @@ function setupProviderMocks() {
mockGetProviderById.mockResolvedValue(MOCK_PROVIDER);
mockGetActiveProvider.mockResolvedValue(MOCK_PROVIDER);
mockCreateRun.mockResolvedValue(MOCK_RUN_RESULT);
- // executeCliRun is fire-and-forget in loops.js; mock to resolve immediately
- mockExecuteCliRun.mockResolvedValue(undefined);
+ // runPromptThroughProvider is fire-and-forget in loops.js (started, then
+ // .then chains onComplete). Resolve quickly so the iteration completes.
+ mockRunPrompt.mockResolvedValue({ text: '', runId: 'run-123', model: 'test' });
}
describe('loops.js', () => {
@@ -242,7 +247,7 @@ describe('loops.js', () => {
// executeIteration error logging via triggerLoop
// ===========================================================================
describe('error handling in executeIteration', () => {
- it('logs console.error when executeCliRun rejects', async () => {
+ it('logs console.error when the central prompt runner rejects', async () => {
const loop = await createLoop({
prompt: 'error test',
interval: '30s',
@@ -252,15 +257,15 @@ describe('loops.js', () => {
const savedBefore = JSON.parse(writeFile.mock.calls[0][1]);
readFile.mockResolvedValue(JSON.stringify(savedBefore));
- // Make executeCliRun reject
- mockExecuteCliRun.mockRejectedValue(new Error('CLI execution failed'));
+ // Make runPromptThroughProvider reject (replaces the old executeCliRun
+ // rejection path — same failure surface, new dispatcher).
+ mockRunPrompt.mockRejectedValue(new Error('CLI execution failed'));
const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
await triggerLoop(loop.id);
- // Allow microtasks to settle (the .catch on executeCliRun is async)
- // Flush promise microtask queue
+ // Allow microtasks to settle (the .catch on the runner is async)
for (let i = 0; i < 5; i++) await Promise.resolve();
expect(consoleSpy).toHaveBeenCalledWith(
diff --git a/server/services/meatspacePostLlm.js b/server/services/meatspacePostLlm.js
index 8568ab20a5..718e92366c 100644
--- a/server/services/meatspacePostLlm.js
+++ b/server/services/meatspacePostLlm.js
@@ -9,9 +9,8 @@
* - pun-wordplay: creative wordplay and pun generation
*/
-import { spawn } from 'child_process';
import { getActiveProvider, getProviderById } from './providers.js';
-import { resolveCliModel } from '../lib/providerModels.js';
+import { runPromptThroughProvider } from '../lib/promptRunner.js';
export const LLM_DRILL_TYPES = [
'word-association',
@@ -46,71 +45,19 @@ async function callAI(prompt, providerId, model) {
const selectedModel = model || provider.defaultModel;
console.log(`🧪 POST LLM drill: ${provider.id} / ${selectedModel}`);
- if (provider.type === 'cli') {
- return new Promise((resolve, reject) => {
- const args = [...(provider.args || [])];
- if (provider.headlessArgs?.length) args.push(...provider.headlessArgs);
- const cliModel = resolveCliModel(selectedModel);
- if (cliModel) args.push('--model', cliModel);
- args.push(prompt);
- let output = '';
- let settled = false;
-
- const child = spawn(provider.command, args, {
- env: (() => { const e = { ...process.env, ...(provider.envVars || {}) }; delete e.CLAUDECODE; return e; })(),
- shell: false,
- windowsHide: true
- });
-
- const timeoutHandle = setTimeout(() => {
- if (settled) return;
- settled = true;
- child.kill();
- reject(new Error('POST AI request timed out'));
- }, provider.timeout || 120000);
-
- child.stdout.on('data', d => { output += d.toString(); });
- child.stderr.on('data', d => { output += d.toString(); });
- child.on('close', code => {
- if (settled) return;
- settled = true;
- clearTimeout(timeoutHandle);
- code === 0 ? resolve(output) : reject(new Error(`CLI exited with code ${code}`));
- });
- child.on('error', err => {
- if (settled) return;
- settled = true;
- clearTimeout(timeoutHandle);
- reject(err);
- });
- });
- }
-
- if (provider.type === 'api') {
- const headers = { 'Content-Type': 'application/json' };
- if (provider.apiKey) headers['Authorization'] = `Bearer ${provider.apiKey}`;
-
- const response = await fetch(`${provider.endpoint}/chat/completions`, {
- method: 'POST',
- headers,
- body: JSON.stringify({
- model: selectedModel,
- messages: [{ role: 'user', content: prompt }],
- temperature: 0.7
- }),
- signal: AbortSignal.timeout(provider.timeout || 120000)
- });
-
- if (!response.ok) {
- const errorText = await response.text();
- throw new Error(`AI API error: ${response.status} - ${errorText}`);
- }
-
- const data = await response.json();
- return data.choices?.[0]?.message?.content || '';
- }
-
- throw new Error(`Unsupported provider type: ${provider.type}`);
+ // Append headlessArgs so claude-code's POST drills don't pollute the
+ // user's session list. The clone leaves the saved provider config
+ // untouched. Default timeout for POST drills is shorter than the
+ // central handler's default (2 min vs 5) since drills should be snappy.
+ const providerForCall = provider.headlessArgs?.length
+ ? { ...provider, args: [...(provider.args || []), ...provider.headlessArgs] }
+ : provider;
+
+ const { text } = await runPromptThroughProvider({
+ provider: providerForCall, prompt, source: 'meatspace-post-llm', model: selectedModel,
+ timeout: provider.timeout || 120000,
+ });
+ return text;
}
function parseJsonFromAI(content) {
diff --git a/server/services/meatspacePostLlm.test.js b/server/services/meatspacePostLlm.test.js
index 58446442d3..d7b926728c 100644
--- a/server/services/meatspacePostLlm.test.js
+++ b/server/services/meatspacePostLlm.test.js
@@ -1,5 +1,4 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
-import EventEmitter from 'events';
// Mock providers before importing the module
vi.mock('./providers.js', () => ({
@@ -7,13 +6,15 @@ vi.mock('./providers.js', () => ({
getProviderById: vi.fn()
}));
-vi.mock('child_process', async (importOriginal) => {
- const actual = await importOriginal();
- return { ...actual, spawn: vi.fn() };
-});
+// Mock the central LLM handler — meatspacePostLlm used to spawn child_process
+// + fetch directly, but now delegates to runPromptThroughProvider. Runner
+// internals (spawn args, --model flag injection) are covered by runner.test.js.
+vi.mock('../lib/promptRunner.js', () => ({
+ runPromptThroughProvider: vi.fn()
+}));
import { getActiveProvider, getProviderById } from './providers.js';
-import { spawn } from 'child_process';
+import { runPromptThroughProvider } from '../lib/promptRunner.js';
import {
LLM_DRILL_TYPES,
generateLlmDrill,
@@ -25,7 +26,9 @@ import {
scoreLlmDrill
} from './meatspacePostLlm.js';
-// Helper: mock an API provider that returns a given JSON string
+// Helper: mock an API provider that returns a given JSON string. Sets the
+// central handler to resolve with the stringified response — drills then
+// parse it the same way they used to with a fetch-mocked API response.
function mockApiProvider(responseJson) {
const provider = {
id: 'test-provider',
@@ -38,11 +41,10 @@ function mockApiProvider(responseJson) {
getActiveProvider.mockResolvedValue(provider);
getProviderById.mockResolvedValue(provider);
- global.fetch = vi.fn().mockResolvedValue({
- ok: true,
- json: () => Promise.resolve({
- choices: [{ message: { content: JSON.stringify(responseJson) } }]
- })
+ runPromptThroughProvider.mockResolvedValue({
+ text: JSON.stringify(responseJson),
+ runId: 'test-run',
+ model: 'test-model'
});
return provider;
@@ -468,11 +470,9 @@ describe('AI response parsing', () => {
endpoint: 'http://localhost:9999', defaultModel: 'test'
};
getActiveProvider.mockResolvedValue(provider);
- global.fetch = vi.fn().mockResolvedValue({
- ok: true,
- json: () => Promise.resolve({
- choices: [{ message: { content: '```json\n{"questions":[{"prompt":"hello"}]}\n```' } }]
- })
+ runPromptThroughProvider.mockResolvedValue({
+ text: '```json\n{"questions":[{"prompt":"hello"}]}\n```',
+ runId: 'test-run', model: 'test-model'
});
const result = await generateWordAssociation({ count: 1 });
@@ -485,11 +485,9 @@ describe('AI response parsing', () => {
endpoint: 'http://localhost:9999', defaultModel: 'test'
};
getActiveProvider.mockResolvedValue(provider);
- global.fetch = vi.fn().mockResolvedValue({
- ok: true,
- json: () => Promise.resolve({
- choices: [{ message: { content: 'Here is the result:\n{"questions":[{"prompt":"world"}]}\nHope this helps!' } }]
- })
+ runPromptThroughProvider.mockResolvedValue({
+ text: 'Here is the result:\n{"questions":[{"prompt":"world"}]}\nHope this helps!',
+ runId: 'test-run', model: 'test-model'
});
const result = await generateWordAssociation({ count: 1 });
@@ -502,73 +500,11 @@ describe('AI response parsing', () => {
endpoint: 'http://localhost:9999', defaultModel: 'test'
};
getActiveProvider.mockResolvedValue(provider);
- global.fetch = vi.fn().mockResolvedValue({
- ok: true,
- json: () => Promise.resolve({
- choices: [{ message: { content: '' } }]
- })
+ runPromptThroughProvider.mockResolvedValue({
+ text: '', runId: 'test-run', model: 'test-model'
});
await expect(generateWordAssociation({ count: 1 })).rejects.toThrow();
});
});
-// =============================================================================
-// CODEX SENTINEL — CLI spawn path
-// =============================================================================
-
-describe('CLI provider — codex sentinel model', () => {
- function createMockChild(stdoutPayload) {
- const child = new EventEmitter();
- child.stdout = new EventEmitter();
- child.stderr = new EventEmitter();
- child.kill = vi.fn();
- setImmediate(() => {
- child.stdout.emit('data', Buffer.from(stdoutPayload));
- child.emit('close', 0);
- });
- return child;
- }
-
- it('omits --model flag when defaultModel is the codex sentinel', async () => {
- getActiveProvider.mockResolvedValue({
- id: 'codex',
- enabled: true,
- type: 'cli',
- command: 'codex',
- args: [],
- defaultModel: 'codex-configured-default',
- timeout: 5000
- });
- spawn.mockReturnValue(createMockChild(JSON.stringify({
- questions: [{ prompt: 'river', hints: '' }]
- })));
-
- await generateWordAssociation({ count: 1 });
-
- const [, args] = spawn.mock.calls.at(-1);
- expect(args).not.toContain('--model');
- });
-
- it('passes --model normally for non-sentinel CLI models', async () => {
- getActiveProvider.mockResolvedValue({
- id: 'codex',
- enabled: true,
- type: 'cli',
- command: 'codex',
- args: [],
- defaultModel: 'o4-mini',
- timeout: 5000
- });
- spawn.mockReturnValue(createMockChild(JSON.stringify({
- questions: [{ prompt: 'river', hints: '' }]
- })));
-
- await generateWordAssociation({ count: 1 });
-
- const [, args] = spawn.mock.calls.at(-1);
- const modelIdx = args.indexOf('--model');
- expect(modelIdx).toBeGreaterThanOrEqual(0);
- expect(args[modelIdx + 1]).toBe('o4-mini');
- });
-});
diff --git a/server/services/pm2Standardizer.js b/server/services/pm2Standardizer.js
index e0f93ff0ba..b77ca8d9e3 100644
--- a/server/services/pm2Standardizer.js
+++ b/server/services/pm2Standardizer.js
@@ -6,7 +6,7 @@ import { promisify } from 'util';
import { getActiveProvider, getProviderById } from './providers.js';
import { spawn } from 'child_process';
import { safeJSONParse } from '../lib/fileUtils.js';
-import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';
+import { runPromptThroughProvider } from '../lib/promptRunner.js';
const execAsync = promisify(exec);
const DEFAULT_PM2_AI_TIMEOUT_MS = 180000;
@@ -165,83 +165,18 @@ Rules:
}
/**
- * Execute LLM analysis using CLI provider
+ * Execute LLM analysis through the central handler — works for cli, api,
+ * and tui providers without per-type branching. `cwd` is the analyzed
+ * repo path, NOT PortOS's cwd; without it the CLI/TUI spawn lands in
+ * PortOS's directory and the analysis reads the wrong files.
*/
-async function executeCliAnalysis(provider, prompt, cwd) {
- return new Promise((resolve, reject) => {
- const args = [...(provider.args || []), prompt];
- let output = '';
- let settled = false;
- let timer = null;
-
- const settle = (fn, value) => {
- if (settled) return;
- settled = true;
- if (timer) clearTimeout(timer);
- fn(value);
- };
-
- const child = spawn(provider.command, args, {
- cwd,
- env: process.env,
- shell: false,
- windowsHide: true
- });
-
- child.stdout.on('data', (data) => {
- output += data.toString();
- });
-
- child.stderr.on('data', (data) => {
- output += data.toString();
- });
-
- child.on('close', (code) => {
- if (code === 0) {
- settle(resolve, output);
- } else {
- settle(reject, new Error(`CLI exited with code ${code}`));
- }
- });
-
- child.on('error', (err) => settle(reject, err));
-
- const timeoutMs = provider.timeout || 180000;
- timer = setTimeout(() => {
- console.log(`⏰ CLI analysis timed out after ${timeoutMs / 1000}s for: ${provider.command}`);
- child.kill();
- settle(reject, new Error(`Standardization analysis timed out after ${timeoutMs / 1000}s`));
- }, timeoutMs);
+async function executeAnalysis(provider, prompt, cwd) {
+ const { text } = await runPromptThroughProvider({
+ provider, prompt, source: 'pm2-standardize',
+ timeout: provider.timeout || DEFAULT_PM2_AI_TIMEOUT_MS,
+ cwd,
});
-}
-
-/**
- * Execute LLM analysis using API provider
- */
-async function executeApiAnalysis(provider, prompt) {
- const headers = { 'Content-Type': 'application/json' };
- if (provider.apiKey) {
- headers['Authorization'] = `Bearer ${provider.apiKey}`;
- }
-
- const timeoutMs = provider.timeout || DEFAULT_PM2_AI_TIMEOUT_MS;
-
- const response = await fetchWithTimeout(`${provider.endpoint}/chat/completions`, {
- method: 'POST',
- headers,
- body: JSON.stringify({
- model: provider.defaultModel,
- messages: [{ role: 'user', content: prompt }],
- temperature: 0.1
- })
- }, timeoutMs);
-
- if (!response.ok) {
- throw new Error(`API error: ${response.status}`);
- }
-
- const data = await response.json();
- return data.choices?.[0]?.message?.content || '';
+ return text;
}
/**
@@ -368,14 +303,7 @@ export async function analyzeApp(repoPath, providerId = null) {
const startTime = Date.now();
console.log(`🤖 Running ${provider.type} analysis via ${provider.name} (timeout: ${(provider.timeout || 180000) / 1000}s)`);
- let response;
- if (provider.type === 'cli') {
- response = await executeCliAnalysis(provider, prompt, repoPath);
- } else if (provider.type === 'api') {
- response = await executeApiAnalysis(provider, prompt);
- } else {
- return { success: false, error: 'Unknown provider type' };
- }
+ const response = await executeAnalysis(provider, prompt, repoPath);
console.log(`✅ Analysis response received in ${((Date.now() - startTime) / 1000).toFixed(1)}s`);
diff --git a/server/services/runner.js b/server/services/runner.js
index 6c97dbada1..897cbf106b 100644
--- a/server/services/runner.js
+++ b/server/services/runner.js
@@ -6,7 +6,13 @@ import { spawn } from 'child_process';
import { writeFile, readFile } from 'fs/promises';
import { join } from 'path';
import { ensureDir } from '../lib/fileUtils.js';
-import { resolveCliModel } from '../lib/providerModels.js';
+import { resolveCliModel, hasModelFlag, extractBakedModel } from '../lib/providerModels.js';
+
+// Re-exported so `server/lib/promptRunner.js` can import via the runner
+// (its existing dependency boundary). The canonical home is now
+// `server/lib/providerModels.js` — that's where `server/lib/tuiHandshake.js`
+// imports from directly (lib→lib, no service layer violation).
+export { hasModelFlag, extractBakedModel };
// This will be initialized by server/index.js and set via setAIToolkit()
let aiToolkitInstance = null;
@@ -109,61 +115,99 @@ function stripBrokenModelFlags(args) {
return out;
}
-// Detects whether the provider's stored argv already pins a model with a
-// usable value. We check both flag forms (`--model` / `-m`) and both styles
-// (separated `--model x` and joined `--model=x`). gemini-cli is the only
-// one that uses `-m` short form; checking it on claude-code too is harmless
-// (claude-code doesn't define a `-m` short flag).
-//
-// A separated flag with no value following (`['--model']` at end of argv,
-// or `['--model', '--other']`) is treated as NOT a baked-in pin — the CLI
-// would reject the argv at runtime anyway, and pretending it's a pin would
-// also make refiners report `null` (from extractBakedModel) and skip
-// injecting our own model. Better to leave injection on and let
-// buildCliArgs fix the broken argv by appending a valid `--model X`.
-export function hasModelFlag(args) {
- if (!Array.isArray(args)) return false;
- for (let i = 0; i < args.length; i++) {
- const a = args[i];
- if (typeof a !== 'string') continue;
- if (a.startsWith('--model=') && a.length > '--model='.length) return true;
- if (a.startsWith('-m=') && a.length > '-m='.length) return true;
- if (a === '--model' || a === '-m') {
- const next = args[i + 1];
- if (typeof next === 'string' && next.length > 0 && !next.startsWith('-')) return true;
- }
- }
- return false;
+/**
+ * Returns the configured runs directory. Other execution paths
+ * (`server/lib/tuiPromptRunner.js`) need this to write output + metadata
+ * under the same tree as `createRun` — without it, runs configured with a
+ * non-default `dataDir` end up split across two trees and `/runs` replay
+ * breaks.
+ */
+export function getRunsPath() {
+ return join(runnerConfig.dataDir, 'runs');
}
/**
- * Extract the pinned model id from provider.args when a model flag is baked
- * in. Supports separated form (`--model X` / `-m X`) and joined form
- * (`--model=X` / `-m=X`). Returns null when no model flag is present or the
- * separated form has no value following the flag.
+ * Read existing metadata.json (written by toolkit createRun), merge in
+ * completion fields, optionally run error analysis, write back, fire
+ * onRunCompleted / onRunFailed hooks, and write the output buffer. Mirror
+ * of the close-handler block in executeCliRun below — extracted so
+ * `tuiPromptRunner.js` can produce the same run-record shape (otherwise
+ * /runs shows TUI runs stuck with `success: null` forever).
*
- * Used by refiners (mediaPromptRefiner, universeBuilderRefine) so the model
- * reported back to the caller / persisted on the run record matches what
- * the CLI will actually run when the user has hard-coded a model in args.
+ * `extras` (optional object) is merged into the persisted metadata BEFORE
+ * the file is written, so caller-specific fields like `completionReason`
+ * (TUI) survive to disk and show up on /runs replay.
+ *
+ * @returns the merged metadata object (also written to disk).
*/
-export function extractBakedModel(args) {
- if (!Array.isArray(args)) return null;
- for (let i = 0; i < args.length; i++) {
- const a = args[i];
- if (typeof a !== 'string') continue;
- if (a === '--model' || a === '-m') {
- const next = args[i + 1];
- // Match hasModelFlag exactly: a value that starts with '-' is the next
- // flag, not the model id. Without this guard, `['--model', '--other']`
- // would extract `'--other'` even though hasModelFlag said "no baked
- // model" — the two would disagree and refiners could mis-report.
- if (typeof next === 'string' && next.length > 0 && !next.startsWith('-')) return next;
- return null;
- }
- if (a.startsWith('--model=')) return a.slice('--model='.length) || null;
- if (a.startsWith('-m=')) return a.slice('-m='.length) || null;
+export async function finalizeRunRecord({ runId, output, exitCode, success, error, startTime, extras }) {
+ if (!aiToolkitInstance) throw new Error('AI Toolkit not initialized');
+ const runDir = join(getRunsPath(), runId);
+ const outputPath = join(runDir, 'output.txt');
+ const metadataPath = join(runDir, 'metadata.json');
+
+ await writeFile(outputPath, output).catch(() => {});
+
+ const metadataStr = await readFile(metadataPath, 'utf-8').catch(() => '{}');
+ let metadata = {};
+ try { metadata = JSON.parse(metadataStr); } catch { console.log('⚠️ Corrupted metadata for run, using fresh'); }
+ metadata.endTime = new Date().toISOString();
+ metadata.duration = Date.now() - startTime;
+ metadata.exitCode = exitCode;
+ metadata.success = success;
+ metadata.outputSize = Buffer.byteLength(output);
+ if (error) metadata.error = error;
+ if (extras && typeof extras === 'object') Object.assign(metadata, extras);
+
+ if (!success && aiToolkitInstance.services.errorDetection) {
+ const errorAnalysis = aiToolkitInstance.services.errorDetection.analyzeError(output, exitCode);
+ metadata.error = metadata.error || errorAnalysis.message || `Process exited with code ${exitCode}`;
+ metadata.errorCategory = errorAnalysis.category;
+ metadata.errorAnalysis = errorAnalysis;
+ }
+
+ await writeFile(metadataPath, JSON.stringify(metadata, null, 2)).catch(() => {});
+
+ if (success) {
+ runnerConfig.hooks?.onRunCompleted?.(metadata, output);
+ } else {
+ runnerConfig.hooks?.onRunFailed?.(metadata, metadata.error, output);
}
- return null;
+
+ return metadata;
+}
+
+/**
+ * Fire the `onRunStarted` lifecycle hook — used by execution paths that
+ * don't go through the toolkit's executeCliRun/executeApiRun (which fire
+ * it internally). `tuiPromptRunner.js` calls this on PTY spawn so UI/SSE
+ * run tracking sees TUI runs as active.
+ */
+export function emitRunStarted({ runId, provider, model }) {
+ runnerConfig.hooks?.onRunStarted?.({
+ runId,
+ provider: provider?.name || provider?.id,
+ model: model ?? provider?.defaultModel,
+ });
+}
+
+/**
+ * Best-effort merge of `patch` into an existing run's metadata.json.
+ * Used by `promptRunner.js` when the toolkit's createRun falls back to a
+ * different provider — the original `metadata.model` then claims a model
+ * that doesn't belong to the fallback. Patch it post-hoc so /runs
+ * attribution matches what actually ran. Silent on read/write failures
+ * because the run record is best-effort tracking, not load-bearing.
+ */
+export async function patchRunMetadata(runId, patch) {
+ if (!patch || typeof patch !== 'object') return;
+ const metadataPath = join(getRunsPath(), runId, 'metadata.json');
+ const metadataStr = await readFile(metadataPath, 'utf-8').catch(() => null);
+ if (!metadataStr) return;
+ let metadata;
+ try { metadata = JSON.parse(metadataStr); } catch { return; }
+ Object.assign(metadata, patch);
+ await writeFile(metadataPath, JSON.stringify(metadata, null, 2)).catch(() => {});
}
/**
diff --git a/server/services/taskEnhancer.js b/server/services/taskEnhancer.js
index 8cc7433c3d..6fb059e36d 100644
--- a/server/services/taskEnhancer.js
+++ b/server/services/taskEnhancer.js
@@ -7,9 +7,9 @@
* Uses the 'cos-task-enhance' prompt stage for provider/model configuration.
*/
-import { executeApiRun, executeCliRun, createRun } from './runner.js';
import { getActiveProvider, getProviderById } from './providers.js';
import { getStage, buildPrompt } from './promptService.js';
+import { runPromptThroughProvider } from '../lib/promptRunner.js';
const STAGE_NAME = 'cos-task-enhance';
@@ -104,65 +104,13 @@ export async function enhanceTaskPrompt(description, context = '') {
.replace('{contextSection}', contextSection);
}
- // Create a run for this enhancement
- const { runId } = await createRun({
- providerId: provider.id,
- model,
- prompt: fullPrompt,
- source: 'task-enhancement'
- });
-
- // Collect the response
- let enhancedDescription = '';
-
- // Use appropriate execution method based on provider type
- const isCliProvider = provider.type === 'cli';
-
- await new Promise((resolve, reject) => {
- if (isCliProvider) {
- // CLI providers use executeCliRun
- executeCliRun(
- runId,
- provider,
- fullPrompt,
- process.cwd(),
- (text) => {
- enhancedDescription += text;
- },
- (result) => {
- if (result?.error || result?.success === false) {
- reject(new Error(result?.error || 'CLI execution failed'));
- } else {
- resolve(result);
- }
- },
- provider.timeout || 300000
- );
- } else {
- // API providers use executeApiRun
- executeApiRun(
- runId,
- provider,
- model,
- fullPrompt,
- process.cwd(),
- [], // No screenshots needed
- (data) => {
- enhancedDescription += typeof data === 'string' ? data : (data?.text || '');
- },
- (result) => {
- if (result?.error) {
- reject(new Error(result.error));
- } else {
- resolve(result);
- }
- }
- );
- }
+ const { text, model: effectiveModel } = await runPromptThroughProvider({
+ provider, prompt: fullPrompt, source: 'task-enhancement', model,
});
+ model = effectiveModel;
// Clean up the response - remove any leading/trailing whitespace and common prefixes
- enhancedDescription = enhancedDescription.trim();
+ let enhancedDescription = text.trim();
// Remove common AI response prefixes
const prefixesToRemove = [
diff --git a/server/services/universeBuilderRefine.js b/server/services/universeBuilderRefine.js
index a41f37c0d0..a4291ab5e0 100644
--- a/server/services/universeBuilderRefine.js
+++ b/server/services/universeBuilderRefine.js
@@ -13,7 +13,7 @@
import { ServerError } from "../lib/errorHandler.js";
import { getActiveProvider, getProviderById } from "./providers.js";
-import { createRun, executeApiRun, executeCliRun } from "./runner.js";
+import { runPromptThroughProvider } from "../lib/promptRunner.js";
import { resolveEffectiveModel } from "../lib/promptRunner.js";
import {
renderCategoriesForPrompt as renderCategoriesShared,
@@ -329,65 +329,18 @@ const mergeCompositesWithLocks = (originalSheets, llmSheets) => {
return sanitizeCompositeSheets(merged);
};
-// CLI providers (codex/claude-code/gemini-cli) need provider-specific arg
-// 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.
+// Routes through the central handler so cli/api/tui providers all work; the
+// per-CLI argv quirks (codex `exec -`, gemini stdin pipe, claude `-p -`) live
+// inside runner.js#buildCliArgs and the TUI paste/idle handshake lives in
+// tuiPromptRunner.js — both reached via runPromptThroughProvider.
async function runRefine(provider, model, prompt) {
- const { runId } = await createRun({
- providerId: provider.id,
- model,
- prompt,
- source: "universe-builder-refine",
- });
-
- let text = "";
- return 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 || "Universe refinement failed", {
- status: 502,
- code: "WORLD_REFINE_FAILED",
- }),
- );
- } else {
- resolve({ text, runId });
- }
- };
- if (provider.type === "cli") {
- // Mirror the media refiner: `buildCliArgs` now honors a per-call model
- // override (via `provider.defaultModel`) for codex / claude-code /
- // gemini-cli. Clone the provider with the overridden defaultModel
- // whenever the caller picked something other than the saved default.
- 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);
- }
+ return runPromptThroughProvider({
+ provider, prompt, source: "universe-builder-refine", model,
+ }).catch((err) => {
+ throw new ServerError(err?.message || "Universe refinement failed", {
+ status: 502,
+ code: "WORLD_REFINE_FAILED",
+ });
});
}