Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: route autofixer + calendar sync through configured AI provider
Adam Eivy6a05405e4351
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 8a6cde8bd2..f8ef79af23 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -19,6 +19,8 @@ TBD## Changed+- **Autofixer and Google Calendar sync now run through your configured AI provider.** Both previously hardcoded `claude -p`, ignoring whichever provider/model the rest of PortOS uses. They now resolve a configured CLI provider/model and route through a shared, dependency-light invocation path (`server/lib/cliProviderRun.js`) — the same per-CLI argv conventions (Codex `exec -`, Gemini stdin, Claude Code `-p -`) the main runner uses. New UI controls let you pick the provider/model per feature: a **Settings › Autofixer** tab, and a picker on the **Calendar › Config** tab (for Google MCP-sync accounts). Both default to Claude Code when unset, so existing installs are unchanged. The picker is restricted to enabled **CLI** providers — the autofixer must edit files and run pm2, and the calendar sync must call MCP tools, neither of which an API chat provider can do. *Migration note:* calendar MCP sync no longer honors the legacy `CLAUDE_PATH` env var — point the provider's command at your binary under **AI Providers** instead. The Claude-specific `--allowedTools` MCP flag is now passed only to Claude-family providers.+- **Importer source ceiling raised from 200K → 5M characters.** The Create › Importer page previously rejected pasted sources over 200,000 characters — far short of a real novel (a 250-page book runs ~400K chars; long novels reach several million). That cap was an over-conservative "v1" product limit, not a fundamental constraint: the schema layer already allowed 5MB, and modern large-context providers (Claude, Gemini) ingest a whole novel in a single call. The importer now matches the 5MB abuse-guard ceiling, so the only remaining limit is dynamic — the active provider's context window (the entire corpus still goes into one extraction call until chunked extraction lands). Sources that fit the ceiling but overflow the chosen model's window surface a provider error; pick a large-context provider or trim in the meantime. The pipeline's per-issue canon-extract truncation budget was decoupled (stays 200K) since a single issue's stage output is already hard-bounded at 400K and operates at a fundamentally smaller scale than whole-book ingest.- **Dashboard Quick Image widget** — now exposes **resolution** and **negative prompt** options (collapsible) alongside the prompt, and renders the result inline: async backends stream the diffusion loading animation (spinner / step counter / latent preview) and resolve to the final image, mirroring the Universe asset slots via the shared `MediaJobThumb`. Sync (external) backends show the completed image directly. The "Edit" hand-off now carries the chosen size + negative prompt into the full Image Gen page.diff --git a/autofixer/server.js b/autofixer/server.jsindex 8133ea4d71..7c7a3fdcb7 100644--- a/autofixer/server.js+++ b/autofixer/server.js@@ -3,6 +3,11 @@ import { readFile, writeFile, mkdir, access } from 'fs/promises';import { join, dirname } from 'path';import { fileURLToPath } from 'url';import { createRequire } from 'module';+// Dependency-light shared module (node builtins + pure arg builder only), so+// importing it from this standalone process doesn't pull in the AI toolkit.+// Lets the autofixer honor the user's configured CLI provider/model instead+// of hardcoding `claude -p`.+import { pickCliProvider, runCliProviderPrompt } from '../server/lib/cliProviderRun.js';const __filename = fileURLToPath(import.meta.url);const __dirname = dirname(__filename);@@ -30,6 +35,8 @@ function execPm2(pm2Args) {// Pathsconst DATA_DIR = join(__dirname, '../data');const APPS_FILE = join(DATA_DIR, 'apps.json');+const PROVIDERS_FILE = join(DATA_DIR, 'providers.json');+const SETTINGS_FILE = join(DATA_DIR, 'settings.json');const AUTOFIXER_DIR = join(DATA_DIR, 'autofixer');const SESSIONS_DIR = join(AUTOFIXER_DIR, 'sessions');const INDEX_FILE = join(AUTOFIXER_DIR, 'index.json');@@ -46,6 +53,35 @@ async function loadApps() {return Object.entries(parsed.apps || {}).map(([id, app]) => ({ id, ...app }));}+// Parse JSON, returning `fallback` on read OR parse failure. A corrupt config+// file (partial write, hand-edit) must not throw inside fixProcess — this runs+// in the autofixer's interval loop, outside any request lifecycle, where an+// uncaught throw would take the process down.+async function readJsonSafe(file, fallback) {+ const data = await readFile(file, 'utf8').catch(() => null);+ if (data == null) return fallback;+ try {+ return JSON.parse(data);+ } catch (err) {+ console.error(`❌ [Autofixer] Corrupt JSON in ${file}: ${err.message}`);+ return fallback;+ }+}++// Load PortOS's AI provider registry (shared data file) so the autofixer runs+// through whichever CLI provider the user configured rather than hardcoding+// claude. Returns the on-disk provider map keyed by id.+async function loadProviders() {+ const parsed = await readJsonSafe(PROVIDERS_FILE, { providers: {} });+ return parsed.providers || {};+}++// Load PortOS settings — `settings.autofixer = { providerId, model }` selects+// which CLI provider/model fixes crashed processes.+async function loadSettings() {+ return readJsonSafe(SETTINGS_FILE, {});+}+// Get all monitored process names from registered appsasync function getMonitoredProcesses() {const apps = await loadApps();@@ -187,84 +223,76 @@ Fix the issue and restart the process. Be systematic and thorough. Use the Bashconst outputBuffer = [];- return new Promise((resolve) => {- const child = spawn('claude', ['-p', prompt], {- cwd: app.repoPath,- stdio: ['ignore', 'pipe', 'pipe'],- shell: false,- windowsHide: true- });-- child.stdout.on('data', (data) => {- const output = data.toString();- outputBuffer.push(output);- process.stdout.write(output);- });+ // Resolve the configured CLI provider/model (settings.autofixer), falling+ // back to claude-code — the historical default — when unset. The autofixer+ // edits files and runs pm2, so it needs an agentic CLI provider; pickCliProvider+ // restricts to type 'cli' (API chat providers can't do file edits).+ const providers = await loadProviders();+ const settings = await loadSettings();+ const picked = pickCliProvider(providers, settings.autofixer || {});++ // Single completion path — write the session record + return the result.+ const finalize = async ({ success, exitCode, error }) => {+ const endTime = new Date().toISOString();+ const duration = new Date(endTime).getTime() - new Date(startTime).getTime();+ const output = outputBuffer.join('') + (error ? `\n[ERROR] ${error}` : '');++ console.log(`${success ? '✅ [Autofixer] Fix successful' : '❌ [Autofixer] Fix failed'} for ${processName} (exit code: ${exitCode})`);++ const metadata = {+ sessionId,+ startTime,+ endTime,+ duration,+ exitCode,+ success,+ processName,+ appName: app.name,+ appId: app.id,+ repoPath: app.repoPath,+ type: 'autofixer',+ provider: picked.provider?.id || null,+ model: picked.model || null,+ ...(error ? { error } : {}),+ };++ await saveSession(sessionId, prompt, output, metadata);+ console.log(`💾 [Autofixer] Saved session: ${sessionId}`);++ if (success) markAsFixed(processName);+ return { success, sessionId, output, ...(error ? { error } : {}) };+ };- child.stderr.on('data', (data) => {- const output = data.toString();- outputBuffer.push(`[STDERR] ${output}`);- process.stderr.write(output);- });+ if (picked.error) {+ outputBuffer.push(`[ERROR] ${picked.error}`);+ console.error(`❌ [Autofixer] ${picked.error}`);+ return finalize({ success: false, exitCode: -1, error: picked.error });+ }- child.on('close', async (code) => {- const endTime = new Date().toISOString();- const duration = new Date(endTime).getTime() - new Date(startTime).getTime();- const output = outputBuffer.join('');- const success = code === 0;-- console.log(`${success ? '✅ [Autofixer] Fix successful' : '❌ [Autofixer] Fix failed'} for ${processName} (exit code: ${code})`);-- const metadata = {- sessionId,- startTime,- endTime,- duration,- exitCode: code,- success,- processName,- appName: app.name,- appId: app.id,- repoPath: app.repoPath,- type: 'autofixer'- };-- await saveSession(sessionId, prompt, output, metadata);- console.log(`💾 [Autofixer] Saved session: ${sessionId}`);-- if (success) {- markAsFixed(processName);+ console.log(`🤖 [Autofixer] Fixing ${processName} via ${picked.provider.id}${picked.model ? ` (${picked.model})` : ''}`);++ const result = await runCliProviderPrompt({+ provider: picked.provider,+ model: picked.model,+ prompt,+ cwd: app.repoPath,+ timeoutMs: 600000, // 10 min — a fix may need several read/edit/restart cycles+ onData: (chunk, stream) => {+ if (stream === 'stderr') {+ outputBuffer.push(`[STDERR] ${chunk}`);+ process.stderr.write(chunk);+ } else {+ outputBuffer.push(chunk);+ process.stdout.write(chunk);}-- resolve({ success, sessionId, output });- });-- child.on('error', async (error) => {- const endTime = new Date().toISOString();- const duration = new Date(endTime).getTime() - new Date(startTime).getTime();- const output = outputBuffer.join('') + `\n[ERROR] ${error.message}`;-- console.error(`❌ [Autofixer] Error fixing ${processName}: ${error.message}`);-- const metadata = {- sessionId,- startTime,- endTime,- duration,- exitCode: -1,- success: false,- processName,- appName: app.name,- appId: app.id,- repoPath: app.repoPath,- type: 'autofixer',- error: error.message- };-- await saveSession(sessionId, prompt, output, metadata);- resolve({ success: false, sessionId, output, error: error.message });- });+ },});++ if (result.error) {+ console.error(`❌ [Autofixer] Error fixing ${processName}: ${result.error}`);+ return finalize({ success: false, exitCode: result.exitCode ?? -1, error: result.error });+ }+ return finalize({ success: result.exitCode === 0, exitCode: result.exitCode });}// Main check functiondiff --git a/client/src/components/FeatureProviderPicker.jsx b/client/src/components/FeatureProviderPicker.jsxnew file mode 100644index 0000000000..c71e688ad7--- /dev/null+++ b/client/src/components/FeatureProviderPicker.jsx@@ -0,0 +1,106 @@+import { useEffect, useMemo, useState } from 'react';+import toast from './ui/Toast';+import ProviderModelSelector from './ProviderModelSelector';+import { getProviders, getSettings, updateSettings } from '../services/api';+import { filterSelectableModels } from '../utils/providers';++/**+ * Reusable provider+model picker for per-feature AI assignment. Reads/writes+ * `settings[featureKey] = { providerId, model }` and restricts the provider+ * list to enabled CLI providers — the autofixer (file edits + pm2) and the+ * Google Calendar MCP sync both need an agentic CLI; API chat providers can't+ * edit files or call MCP tools. Falls back to `fallbackId` (default+ * `claude-code`, the historical hardcoded behavior) when nothing is saved.+ *+ * Persists on every change (optimistic, rolls back on failure) so there's no+ * separate Save button — matches the inline-picker pattern in+ * StagePromptModelPicker.+ */+export default function FeatureProviderPicker({ featureKey, fallbackId = 'claude-code', hint = null }) {+ const [providers, setProviders] = useState([]);+ const [providerId, setProviderId] = useState('');+ const [model, setModel] = useState('');+ const [loaded, setLoaded] = useState(false);+ const [saving, setSaving] = useState(false);++ useEffect(() => {+ let cancelled = false;+ Promise.all([+ getProviders().catch(() => ({ providers: [] })),+ getSettings({ silent: true }).catch(() => ({})),+ ]).then(([p, settings]) => {+ if (cancelled) return;+ // Match the server resolver's default-true semantics (pickCliProvider+ // uses `enabled !== false`) so the picker never hides a provider the+ // server would actually run, or vice versa.+ const cli = (p?.providers || []).filter((x) => x.type === 'cli' && x.enabled !== false);+ setProviders(cli);++ // Resolve the effective selection: saved providerId if it's still a+ // valid CLI provider, else fallbackId, else the first CLI provider.+ const cfg = settings?.[featureKey] || {};+ const resolved =+ cli.find((x) => x.id === cfg.providerId) ||+ cli.find((x) => x.id === fallbackId) ||+ cli[0] ||+ null;+ const offered = resolved ? filterSelectableModels(resolved.models || [resolved.defaultModel]) : [];+ setProviderId(resolved?.id || '');+ setModel(cfg.model && offered.includes(cfg.model) ? cfg.model : (resolved?.defaultModel || ''));+ setLoaded(true);+ });+ return () => { cancelled = true; };+ }, [featureKey, fallbackId]);++ const availableModels = useMemo(() => {+ const p = providers.find((pr) => pr.id === providerId);+ return p ? filterSelectableModels(p.models || [p.defaultModel]) : [];+ }, [providers, providerId]);++ const persist = async (nextProviderId, nextModel) => {+ const prev = { providerId, model };+ setProviderId(nextProviderId);+ setModel(nextModel);+ setSaving(true);+ // updateSettings toasts its own error; pass a custom catch that just rolls+ // back local state (no second toast).+ const merged = await updateSettings({ [featureKey]: { providerId: nextProviderId, model: nextModel } }).catch(() => null);+ setSaving(false);+ if (!merged) {+ setProviderId(prev.providerId);+ setModel(prev.model);+ return;+ }+ toast.success('Saved');+ };++ if (!loaded) return null;+ if (providers.length === 0) {+ return (+ <div className="text-sm text-port-warning">+ No enabled CLI providers configured. Add one under{' '}+ <a className="text-port-accent underline" href="/ai">AI Providers</a>.+ </div>+ );+ }++ return (+ <div className="space-y-2">+ <ProviderModelSelector+ providers={providers}+ selectedProviderId={providerId}+ selectedModel={model}+ availableModels={availableModels}+ onProviderChange={(id) => {+ const p = providers.find((pr) => pr.id === id);+ persist(id, p?.defaultModel || filterSelectableModels(p?.models)[0] || '');+ }}+ onModelChange={(m) => persist(providerId, m)}+ />+ <div className="flex items-center gap-2 min-h-[16px]">+ {saving && <span className="text-xs text-gray-500">saving…</span>}+ {hint && <p className="text-xs text-gray-500">{hint}</p>}+ </div>+ </div>+ );+}diff --git a/client/src/components/calendar/ConfigTab.jsx b/client/src/components/calendar/ConfigTab.jsxindex ee6efcddaa..f1ca0d594e 100644--- a/client/src/components/calendar/ConfigTab.jsx+++ b/client/src/components/calendar/ConfigTab.jsx@@ -2,6 +2,7 @@ import { useState, useEffect } from 'react';import { Plus, Trash2, RefreshCw, Globe, Calendar, Eye, EyeOff, ChevronDown, ChevronRight, Search, Key, ExternalLink, Wand2, Monitor } from 'lucide-react';import toast from '../ui/Toast';import * as api from '../../services/api';+import FeatureProviderPicker from '../FeatureProviderPicker';const TYPE_ICONS = { 'outlook-calendar': Globe, 'google-calendar': Calendar };const TYPE_LABELS = { 'outlook-calendar': 'Outlook Calendar (API)', 'google-calendar': 'Google Calendar' };@@ -164,8 +165,8 @@ export default function ConfigTab({ accounts, setAccounts }) {: await api.mcpDiscoverCalendars(account.id).catch(() => null);setDiscovering(null);if (!result || result.error) {- if (result?.error?.includes('spawn Claude')) {- return toast.error('Claude CLI not found. Ensure Claude Code is installed and in your PATH.');+ if (result?.error?.includes('Failed to spawn') || result?.error?.includes('No enabled CLI provider')) {+ return toast.error(`${result.error}. Check the provider configured for calendar sync above.`);}if (result?.error?.includes('OAuth')) {return toast.error('Google OAuth not configured. Set up credentials below.');@@ -334,9 +335,16 @@ export default function ConfigTab({ accounts, setAccounts }) {</div>{(account.syncMethod || 'claude-mcp') === 'claude-mcp' && (- <div className="text-xs text-gray-600 px-2 py-1.5 bg-port-bg/50 rounded">- Uses your Claude Code CLI with Google Calendar MCP integration.- Requires <span className="text-gray-400">claude</span> CLI installed and Google Calendar connected in Claude > Settings > Integrations.+ <div className="space-y-2">+ <div className="text-xs text-gray-600 px-2 py-1.5 bg-port-bg/50 rounded">+ Runs the selected agentic CLI provider with the Google Calendar MCP integration.+ Requires the chosen CLI installed and Google Calendar connected in its MCP settings+ (e.g. Claude > Settings > Integrations).+ </div>+ <FeatureProviderPicker+ featureKey="calendarSync"+ hint="Shared across all Google (MCP) calendar accounts. Defaults to Claude Code when unset."+ /></div>)}diff --git a/client/src/components/settings/AutofixerTab.jsx b/client/src/components/settings/AutofixerTab.jsxnew file mode 100644index 0000000000..a652600ee0--- /dev/null+++ b/client/src/components/settings/AutofixerTab.jsx@@ -0,0 +1,29 @@+import { Wrench } from 'lucide-react';+import FeatureProviderPicker from '../FeatureProviderPicker';++/**+ * Settings tab for the PortOS Autofixer — picks which configured CLI provider+ * + model runs when a monitored PM2 process crashes. The autofixer reads this+ * (`settings.autofixer`) from the shared data file in its own process.+ */+export function AutofixerTab() {+ return (+ <div className="space-y-6">+ <div className="bg-port-card border border-port-border rounded-lg p-4 sm:p-6">+ <div className="flex items-center gap-2 mb-2">+ <Wrench size={16} className="text-port-accent" />+ <h3 className="text-lg font-semibold text-white">Autofixer AI provider</h3>+ </div>+ <p className="text-sm text-gray-400 mb-4">+ When a monitored process crashes, the Autofixer runs this AI provider to read the logs,+ edit the offending files, and restart the process. Only agentic CLI providers are listed —+ the fixer needs file-edit and shell access, which API chat providers can't do.+ </p>+ <FeatureProviderPicker+ featureKey="autofixer"+ hint="Defaults to Claude Code when unset. Configure providers under AI Providers."+ />+ </div>+ </div>+ );+}diff --git a/client/src/components/settings/SettingsTabsHeader.jsx b/client/src/components/settings/SettingsTabsHeader.jsxindex c9e274182b..20bd2c2ecc 100644--- a/client/src/components/settings/SettingsTabsHeader.jsx+++ b/client/src/components/settings/SettingsTabsHeader.jsx@@ -10,6 +10,7 @@ import TabPills from '../ui/TabPills';// Pass `activeTab` matching one of the TABS ids below. Internal Settings// pages use the `<tab>` slug; the standalone pages use `providers` / `prompts`.const TABS = [+ { id: 'autofixer', label: 'Autofixer', to: '/settings/autofixer' },{ id: 'backup', label: 'Backup', to: '/settings/backup' },{ id: 'database', label: 'Database', to: '/settings/database' },{ id: 'general', label: 'General', to: '/settings/general' },diff --git a/client/src/pages/Settings.jsx b/client/src/pages/Settings.jsxindex d0964ad69b..a63cd4e944 100644--- a/client/src/pages/Settings.jsx+++ b/client/src/pages/Settings.jsx@@ -1,4 +1,5 @@import { useParams, Navigate } from 'react-router-dom';+import { AutofixerTab } from '../components/settings/AutofixerTab';import { BackupTab } from '../components/settings/BackupTab';import { DatabaseTab } from '../components/settings/DatabaseTab';import { LocalLlmTab } from '../components/settings/LocalLlmTab';@@ -27,6 +28,7 @@ export default function Settings() {const renderTabContent = () => {switch (activeTab) {case 'general': return <GeneralTab />;+ case 'autofixer': return <AutofixerTab />;case 'backup': return <BackupTab />;case 'database': return <DatabaseTab />;case 'local-llm': return <LocalLlmTab />;diff --git a/server/lib/README.md b/server/lib/README.mdindex 65d88b1382..bdd6618844 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -70,6 +70,8 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `promptPartials.js` | Mustache-style partial expansion. || `mediaModels.js` | Single source of truth for image/video model metadata. || `providerModels.js` | Provider model resolution sentinel + helpers. |+| `cliProviderArgs.js` | Per-CLI argv conventions (`buildCliArgs`) for stdin prompt delivery — dependency-light extraction from runner.js so out-of-process callers (autofixer) can import it. |+| `cliProviderRun.js` | One-shot CLI provider invocation (`pickCliProvider` + `runCliProviderPrompt`) — lightweight path for the autofixer + calendar MCP sync to honor the configured provider/model. || `runners.js` | Image-runner family constants. || `codexAssistantExtract.js` | Strip Codex CLI banner + echoed metadata from session transcript. || `codexCliOutput.js` | Network/system error patterns for `agentErrorAnalysis.js`. |diff --git a/server/lib/cliProviderArgs.js b/server/lib/cliProviderArgs.jsnew file mode 100644index 0000000000..5755a01ee9--- /dev/null+++ b/server/lib/cliProviderArgs.js@@ -0,0 +1,100 @@+/**+ * Per-CLI argv conventions for stdin-based prompt delivery.+ *+ * Extracted from `server/services/runner.js` (which still re-exports+ * `buildCliArgs` for its existing importers) so the conventions live in a+ * dependency-light module: it imports only the pure `providerModels.js`+ * helpers and node builtins. That keeps it importable from contexts that must+ * NOT pull in the AI toolkit / data layer — notably the standalone+ * `portos-autofixer` PM2 process, which runs from its own minimal package and+ * shells the user's configured CLI provider to fix crashed apps.+ *+ * Each CLI reads its prompt from stdin under a different convention:+ * - Codex: `codex exec -` (+ `--model` when not the sentinel)+ * - Gemini CLI: prompt piped to stdin (+ `-m <model>`)+ * - Claude Code: `-p -` (+ `--model <id>`)+ */++import { resolveCliModel, hasModelFlag } from './providerModels.js';++/**+ * Build CLI args based on provider type. Each CLI provider has different+ * conventions for stdin input and model selection. `provider.defaultModel`+ * is honored for all three (codex / claude-code / gemini-cli) so a per-call+ * clone with an overridden defaultModel actually picks that model instead of+ * falling back to whatever's baked into `provider.args`.+ *+ * Model-flag injection is GATED on `provider.args` not already containing a+ * model flag — users who hard-coded e.g. `--model gemini-2.5-pro` in their+ * saved provider config keep that override and don't get a duplicate flag.+ */+export function buildCliArgs(provider) {+ const providerId = provider?.id || '';+ // Sanitize: drop any broken/dangling `--model` / `-m` tokens before+ // appending. hasModelFlag treats those as "not a real pin" so the+ // injection path fires — but if we kept the bogus token in baseArgs the+ // CLI would still see two `--model` occurrences and reject the argv.+ const baseArgs = stripBrokenModelFlags(Array.isArray(provider?.args) ? provider.args : []);+ const effectiveDefaultModel = providerId === 'codex'+ ? resolveCliModel(provider.defaultModel)+ : provider.defaultModel;++ // Codex CLI: `codex exec -` reads prompt from stdin, --model for model.+ // Detect an existing leading `exec` in user/legacy args so we don't end up+ // running `codex exec --full-auto exec -` after migration of legacy+ // configs that already pinned an `exec` subcommand.+ if (providerId === 'codex') {+ const hasExec = baseArgs.includes('exec');+ const args = hasExec ? [...baseArgs] : [...baseArgs, 'exec'];+ if (effectiveDefaultModel) {+ args.push('--model', effectiveDefaultModel);+ }+ args.push('-'); // stdin marker+ return args;+ }++ // Gemini CLI: prompt is piped via stdin directly. `-m <model>` is gemini-+ // cli's documented short flag for model selection (long form: `--model`).+ // Skip injection when the user's saved args already pin a model (either+ // form) so we don't duplicate the flag.+ if (providerId === 'gemini-cli') {+ const args = [...baseArgs];+ if (effectiveDefaultModel && !hasModelFlag(baseArgs)) {+ args.push('-m', effectiveDefaultModel);+ }+ return args;+ }++ // Default (Claude Code CLI): `-p -` means "read prompt from stdin".+ // `--model <id>` is claude-code's model flag; it parses flags+ // positionally so appending after `-p -` is fine. Same gate as gemini-+ // cli — respect user-baked model flags.+ const args = [...baseArgs, '-p', '-'];+ if (effectiveDefaultModel && !hasModelFlag(baseArgs)) {+ args.push('--model', effectiveDefaultModel);+ }+ return args;+}++// Strip dangling/empty `--model` / `-m` tokens (no value follows, or the+// joined form has an empty value). Those would survive into the spawned+// argv unchanged and cause the CLI to reject the invocation — see the+// comment on hasModelFlag for the full reasoning. Pinned-with-value tokens+// are preserved untouched so user-baked model selections still win.+export function stripBrokenModelFlags(args) {+ if (!Array.isArray(args) || args.length === 0) return [];+ const out = [];+ for (let i = 0; i < args.length; i++) {+ const a = args[i];+ if (typeof a === 'string' && (a === '--model=' || a === '-m=')) {+ continue; // empty joined form+ }+ if (a === '--model' || a === '-m') {+ const next = args[i + 1];+ const hasValue = typeof next === 'string' && next.length > 0 && !next.startsWith('-');+ if (!hasValue) continue; // dangling separated form+ }+ out.push(a);+ }+ return out;+}diff --git a/server/lib/cliProviderRun.js b/server/lib/cliProviderRun.jsnew file mode 100644index 0000000000..a4b69597ed--- /dev/null+++ b/server/lib/cliProviderRun.js@@ -0,0 +1,153 @@+/**+ * One-shot invocation of a user-configured CLI AI provider.+ *+ * This is the single, dependency-light path for "run a prompt through whatever+ * CLI provider the user configured for this feature, get text back." It exists+ * so callers outside the main run machinery — the standalone `portos-autofixer`+ * process and the Google Calendar MCP sync — stop hardcoding `claude -p` and+ * instead honor the configured provider/model like every other AI call.+ *+ * Imports only node builtins + the pure arg builder, so the separate-process+ * autofixer (its own minimal package, only `express` installed) can import it+ * without dragging in the AI toolkit or data layer.+ *+ * For full-featured in-process runs (fallback chains, run records, SSE) use+ * `runPromptThroughProvider` in `promptRunner.js` instead. This helper is the+ * lightweight cousin for fire-and-collect prompts.+ */++import { spawn } from 'child_process';+import { buildCliArgs } from './cliProviderArgs.js';++/**+ * Resolve which CLI provider + model a feature should use from the providers+ * list and the feature's stored `{ providerId, model }` config.+ *+ * Only `type === 'cli'` providers are eligible: the autofixer must edit files+ * and run pm2, and the calendar sync must call MCP tools — neither works+ * through an API chat-completion provider. Resolution falls back from the+ * requested provider → `fallbackId` (default `claude-code`, the historical+ * behavior) → the first enabled CLI provider.+ *+ * @param {Array|Object} providers - array of providers OR the on-disk map keyed by id+ * @param {{ providerId?: string, model?: string, fallbackId?: string }} config+ * @returns {{ provider: object, model: string|null } | { error: string }}+ */+export function pickCliProvider(providers, config = {}) {+ const { providerId, model, fallbackId = 'claude-code' } = config || {};+ const list = Array.isArray(providers) ? providers : Object.values(providers || {});+ const cli = list.filter((p) => p && p.type === 'cli' && p.enabled !== false);+ if (cli.length === 0) {+ return { error: 'No enabled CLI provider is configured — add one under AI Providers.' };+ }++ const provider =+ (providerId && cli.find((p) => p.id === providerId)) ||+ cli.find((p) => p.id === fallbackId) ||+ cli[0];++ // Honor the requested model only when the provider actually offers it;+ // otherwise fall back to the provider's own default so a stale stored model+ // (e.g. left over from a different provider) can't pin a nonexistent id.+ const offered = Array.isArray(provider.models) ? provider.models : [];+ const resolvedModel = model && offered.includes(model) ? model : (provider.defaultModel || null);++ return { provider, model: resolvedModel };+}++/**+ * Spawn a CLI provider, deliver `prompt` via stdin (avoids OS argv limits),+ * and resolve with the collected stdout once the process exits.+ *+ * stdout and stderr are tracked separately: `text` is stdout only (the clean+ * response, safe to JSON-parse), while `onData(chunk, stream)` receives both+ * live for logging/progress. Mirrors the canonical `executeCliRun` settle+ * semantics — never rejects; failures come back as `{ error }`.+ *+ * @param {object} args+ * @param {object} args.provider - resolved CLI provider (must have `.command`)+ * @param {string|null} [args.model] - model override; applied as `defaultModel` so buildCliArgs injects it+ * @param {string} args.prompt - prompt text (sent via stdin)+ * @param {string} [args.cwd] - working directory for the child process+ * @param {string[]} [args.extraArgs] - extra argv appended after the built args (e.g. `--allowedTools …`)+ * @param {number} [args.timeoutMs] - SIGTERM after this many ms (default 300000)+ * @param {(chunk: string, stream: 'stdout'|'stderr') => void} [args.onData] - live output callback+ * @returns {Promise<{ text: string, exitCode: number, stderr: string } | { error: string, exitCode?: number, stderr?: string }>}+ */+export function runCliProviderPrompt(args = {}) {+ const { provider, model = null, prompt, cwd, extraArgs = [], timeoutMs = 300000, onData } = args;++ if (!provider?.command) {+ return Promise.resolve({ error: 'Provider has no command configured' });+ }+ if (typeof prompt !== 'string' || prompt.length === 0) {+ return Promise.resolve({ error: 'prompt must be a non-empty string' });+ }++ // Clone with the per-call model as defaultModel so buildCliArgs injects the+ // right --model/-m flag for this provider's CLI convention.+ const effectiveProvider = { ...provider, defaultModel: model ?? provider.defaultModel };+ const spawnArgs = [...buildCliArgs(effectiveProvider), ...(Array.isArray(extraArgs) ? extraArgs : [])];++ return new Promise((resolve) => {+ let stdout = '';+ let stderr = '';+ let settled = false;++ // CLAUDECODE is deleted from the child env so a nested invocation doesn't+ // think it's running inside the parent Claude Code session.+ const child = spawn(provider.command, spawnArgs, {+ cwd: cwd || process.cwd(),+ shell: false,+ stdio: ['pipe', 'pipe', 'pipe'],+ env: (() => { const e = { ...process.env, ...provider.envVars }; delete e.CLAUDECODE; return e; })(),+ windowsHide: true,+ });++ // Single settlement gate — the timer, spawn error, and close handler all+ // race. Without it a SIGKILL that doesn't kill synchronously lets the+ // timer fire later and settle an already-settled promise.+ const done = (result) => {+ if (settled) return;+ settled = true;+ clearTimeout(timer);+ resolve(result);+ };++ const timer = setTimeout(() => {+ if (!child.killed) child.kill('SIGTERM');+ done({ error: `Provider call timed out after ${timeoutMs}ms`, text: stdout.trim(), stderr });+ }, timeoutMs);++ // Register listeners BEFORE writing stdin so an immediate spawn failure or+ // a dead-stdin EPIPE is caught rather than thrown. A child that exits+ // before reading stdin would otherwise emit an unhandled 'error' on the+ // stdin stream — fatal in this non-request context (crashes the process).+ child.on('error', (err) => done({ error: `Failed to spawn ${provider.command}: ${err.message}` }));+ child.stdout?.on('data', (d) => { const t = d.toString(); stdout += t; onData?.(t, 'stdout'); });+ child.stderr?.on('data', (d) => { const t = d.toString(); stderr += t; onData?.(t, 'stderr'); });++ // Swallow EPIPE on stdin (child gone before/while we write) — the close/+ // error handler is the authoritative settle point; an unhandled stdin+ // 'error' would crash the process.+ child.stdin?.on('error', () => {});+ try {+ child.stdin.write(prompt);+ child.stdin.end();+ } catch {+ // Synchronous write failure (e.g. already-destroyed stdin) — let the+ // 'error'/'close' handler settle the promise with the real cause.+ }++ child.on('close', (code) => {+ const text = stdout.trim();+ // A non-zero exit with no stdout is a hard failure; surface stderr.+ // Match the historical calendar-sync rule: any stdout means partial+ // success worth returning to the parser.+ if (code !== 0 && !text) {+ return done({ error: (stderr.trim().slice(0, 500) || `${provider.command} exited with code ${code}`), exitCode: code, stderr });+ }+ done({ text, exitCode: code, stderr });+ });+ });+}diff --git a/server/lib/cliProviderRun.test.js b/server/lib/cliProviderRun.test.jsnew file mode 100644index 0000000000..6e69da2d3e--- /dev/null+++ b/server/lib/cliProviderRun.test.js@@ -0,0 +1,110 @@+import { describe, it, expect } from 'vitest';+import { pickCliProvider, runCliProviderPrompt } from './cliProviderRun.js';++const cli = (id, extra = {}) => ({ id, type: 'cli', command: id, enabled: true, models: [], ...extra });++describe('pickCliProvider', () => {+ const providers = {+ 'claude-code': cli('claude-code', { defaultModel: 'claude-opus-4-7', models: ['claude-opus-4-7', 'claude-haiku-4-5'] }),+ 'codex': cli('codex', { defaultModel: 'codex-configured-default', models: ['codex-configured-default'] }),+ 'gemini-cli': cli('gemini-cli', { defaultModel: 'gemini-2.5-pro', models: ['gemini-2.5-pro'] }),+ 'ollama': { id: 'ollama', type: 'api', enabled: true, defaultModel: 'llama3' },+ 'disabled-cli': cli('disabled-cli', { enabled: false }),+ };++ it('accepts the on-disk map shape (keyed by id)', () => {+ const { provider } = pickCliProvider(providers, { providerId: 'codex' });+ expect(provider.id).toBe('codex');+ });++ it('accepts an array shape', () => {+ const { provider } = pickCliProvider(Object.values(providers), { providerId: 'gemini-cli' });+ expect(provider.id).toBe('gemini-cli');+ });++ it('falls back to claude-code when providerId is unset', () => {+ const { provider, model } = pickCliProvider(providers, {});+ expect(provider.id).toBe('claude-code');+ expect(model).toBe('claude-opus-4-7');+ });++ it('falls back to claude-code when the requested provider does not exist', () => {+ const { provider } = pickCliProvider(providers, { providerId: 'nonexistent' });+ expect(provider.id).toBe('claude-code');+ });++ it('honors a custom fallbackId', () => {+ const { provider } = pickCliProvider(providers, { providerId: 'nope', fallbackId: 'codex' });+ expect(provider.id).toBe('codex');+ });++ it('never selects an API provider', () => {+ const { provider } = pickCliProvider(providers, { providerId: 'ollama' });+ expect(provider.id).not.toBe('ollama');+ expect(provider.type).toBe('cli');+ });++ it('never selects a disabled CLI provider', () => {+ const { provider } = pickCliProvider(providers, { providerId: 'disabled-cli' });+ expect(provider.id).not.toBe('disabled-cli');+ });++ it('honors a requested model when the provider offers it', () => {+ const { model } = pickCliProvider(providers, { providerId: 'claude-code', model: 'claude-haiku-4-5' });+ expect(model).toBe('claude-haiku-4-5');+ });++ it('drops a stale model the provider does not offer, falling back to its default', () => {+ const { model } = pickCliProvider(providers, { providerId: 'claude-code', model: 'gemini-2.5-pro' });+ expect(model).toBe('claude-opus-4-7');+ });++ it('errors when no CLI provider is configured', () => {+ const result = pickCliProvider({ ollama: providers.ollama }, {});+ expect(result.error).toMatch(/No enabled CLI provider/);+ });+});++describe('runCliProviderPrompt', () => {+ it('rejects a missing command without spawning', async () => {+ const result = await runCliProviderPrompt({ provider: { id: 'x' }, prompt: 'hi' });+ expect(result.error).toMatch(/no command/i);+ });++ it('rejects an empty prompt without spawning', async () => {+ const result = await runCliProviderPrompt({ provider: cli('gemini-cli'), prompt: '' });+ expect(result.error).toMatch(/non-empty/);+ });++ it('delivers the prompt via stdin and collects stdout', async () => {+ // gemini-cli with no model → buildCliArgs returns [] (no flags), so `cat`+ // simply echoes stdin back out — a clean end-to-end spawn test.+ const result = await runCliProviderPrompt({+ provider: { id: 'gemini-cli', type: 'cli', command: 'cat', args: [] },+ prompt: 'hello stdin world',+ });+ expect(result.error).toBeUndefined();+ expect(result.text).toBe('hello stdin world');+ expect(result.exitCode).toBe(0);+ });++ it('surfaces a spawn failure for a nonexistent binary', async () => {+ const result = await runCliProviderPrompt({+ provider: { id: 'gemini-cli', type: 'cli', command: 'this-binary-does-not-exist-xyz', args: [] },+ prompt: 'hi',+ });+ expect(result.error).toMatch(/Failed to spawn/);+ });++ it('settles cleanly when the child exits before reading stdin (no EPIPE crash)', async () => {+ // `true` exits 0 immediately and never drains stdin. Writing a large prompt+ // to its closed stdin would emit EPIPE — the helper must swallow that and+ // resolve via the close handler instead of throwing an unhandled error.+ const result = await runCliProviderPrompt({+ provider: { id: 'gemini-cli', type: 'cli', command: 'true', args: [] },+ prompt: 'x'.repeat(100000),+ });+ expect(result.error).toBeUndefined();+ expect(result.exitCode).toBe(0);+ });+});diff --git a/server/lib/index.js b/server/lib/index.jsindex a828ac90d6..e6ffe936a9 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -51,6 +51,8 @@ export * from './writersRoomStylePresets.js';export * from './aiProvider.js';export * from './aiToolkitState.js';export * from './ansiStrip.js';+export * from './cliProviderArgs.js';+export * from './cliProviderRun.js';export * from './codexAssistantExtract.js';export * from './codexCliOutput.js';export * from './hfToken.js';diff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex 382cf90182..6133f4f2c9 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -127,6 +127,7 @@ export const NAV_COMMANDS = [{ id: 'nav.post.morse', path: '/post/morse', label: 'Morse', section: 'POST', aliases: ['post-morse', 'morse', 'morse-code'], keywords: ['cw', 'ham', 'radio', 'koch', 'cognitive'] },{ id: 'nav.post.wordplay', path: '/post/wordplay', label: 'Wordplay', section: 'POST', aliases: ['post-wordplay'] },+ { id: 'nav.settings.autofixer', path: '/settings/autofixer', label: 'Autofixer', section: 'Settings', aliases: ['autofixer', 'settings-autofixer', 'auto-fixer'], keywords: ['crash', 'fix', 'pm2', 'repair', 'ai provider', 'restart'] },{ id: 'nav.settings.backup', path: '/settings/backup', label: 'Backup', section: 'Settings', aliases: ['backup', 'settings-backup'] },{ id: 'nav.settings.database', path: '/settings/database', label: 'Database', section: 'Settings', aliases: ['settings-database', 'database'] },{ id: 'nav.settings.general', path: '/settings/general', label: 'General', section: 'Settings', aliases: ['settings', 'settings-general', 'general'] },diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 739566bc17..0c5525c9ad 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -738,6 +738,18 @@ export const restoreRequestSchema = z.object({dryRun: z.boolean().optional().default(true)});+// Per-feature AI provider assignment: which configured CLI provider/model a+// feature runs through (e.g. `settings.autofixer`, `settings.calendarSync`).+// Empty string (UI "unset" sentinel) is coerced to undefined so it round-trips+// as "use the default" rather than a bogus id. Both the autofixer (file edits+// + pm2) and Google Calendar MCP sync require an agentic CLI provider; the+// picker resolution layer (`pickCliProvider`) enforces type 'cli'.+const emptyToUndefined = (v) => (v === '' ? undefined : v);+export const featureProviderConfigSchema = z.object({+ providerId: z.preprocess(emptyToUndefined, z.string().optional()),+ model: z.preprocess(emptyToUndefined, z.string().optional()),+});+// =============================================================================// WRITERS ROOM SCHEMAS// =============================================================================diff --git a/server/lib/validation.test.js b/server/lib/validation.test.jsindex f6868f3c68..b73bacf052 100644--- a/server/lib/validation.test.js+++ b/server/lib/validation.test.js@@ -12,10 +12,34 @@ import {stageConfigUpdateSchema,normalizeReviewers,buildReviewWithArgs,- createCosTaskSchema+ createCosTaskSchema,+ featureProviderConfigSchema} from './validation.js';describe('validation.js', () => {+ describe('featureProviderConfigSchema', () => {+ it('accepts a providerId + model', () => {+ const result = featureProviderConfigSchema.safeParse({ providerId: 'codex', model: 'gpt-5' });+ expect(result.success).toBe(true);+ expect(result.data).toEqual({ providerId: 'codex', model: 'gpt-5' });+ });++ it('coerces the empty-string "unset" sentinel to undefined', () => {+ const result = featureProviderConfigSchema.safeParse({ providerId: '', model: '' });+ expect(result.success).toBe(true);+ expect(result.data.providerId).toBeUndefined();+ expect(result.data.model).toBeUndefined();+ });++ it('accepts an empty object (use defaults)', () => {+ expect(featureProviderConfigSchema.safeParse({}).success).toBe(true);+ });++ it('rejects a non-string providerId', () => {+ expect(featureProviderConfigSchema.safeParse({ providerId: 42 }).success).toBe(false);+ });+ });+describe('processSchema', () => {it('should validate a complete process object', () => {const process = {diff --git a/server/routes/settings.js b/server/routes/settings.jsindex 105ea9dab6..220e520883 100644--- a/server/routes/settings.js+++ b/server/routes/settings.js@@ -7,7 +7,7 @@ import {CODEX_PARALLEL_DEFAULT,} from '../services/mediaJobQueue/index.js';import { asyncHandler } from '../lib/errorHandler.js';-import { backupConfigSchema, sharingSettingsPatchSchema, validateRequest } from '../lib/validation.js';+import { backupConfigSchema, sharingSettingsPatchSchema, featureProviderConfigSchema, validateRequest } from '../lib/validation.js';const router = Router();@@ -52,6 +52,14 @@ router.put('/', asyncHandler(async (req, res) => {sharingBio: req.body.sharingBio,});}+ // Per-feature AI provider assignments — validate each slice when present so+ // a malformed picker save can't write a non-string providerId/model to disk.+ if (req.body?.autofixer !== undefined) {+ validateRequest(featureProviderConfigSchema.partial(), req.body.autofixer);+ }+ if (req.body?.calendarSync !== undefined) {+ validateRequest(featureProviderConfigSchema.partial(), req.body.calendarSync);+ }const merged = await updateSettings(req.body);// The queue caches codex.parallelLimit in-process; sync it from the// merged value so a save takes effect without a restart and withoutdiff --git a/server/services/calendarGoogleSync.js b/server/services/calendarGoogleSync.jsindex 2a169aa4e2..9b24ed3597 100644--- a/server/services/calendarGoogleSync.js+++ b/server/services/calendarGoogleSync.js@@ -1,10 +1,19 @@import { v4 as uuidv4 } from '../lib/uuid.js';import { createHash } from 'crypto';-import { spawn } from 'child_process';import { getAccount, updateSyncStatus, updateSubcalendars, mergeDiscoveredSubcalendars } from './calendarAccounts.js';import { loadCache, saveCache } from './calendarSync.js';+import { getAllProviders } from './providers.js';+import { getSettings } from './settings.js';+import { pickCliProvider, runCliProviderPrompt } from '../lib/cliProviderRun.js';import { safeJSONParse } from '../lib/fileUtils.js';+// Google Calendar sync is driven through an MCP-capable CLI provider — the+// prompt asks the model to call the `mcp__claude_ai_Google_Calendar__*` tools.+// Only CLI providers wired to that MCP can satisfy it (API chat providers+// can't invoke MCP tools), so the picker is restricted to CLI providers and+// the allowedTools flag is passed through as a per-call extra arg.+const CALENDAR_MCP_ALLOWED_TOOLS = 'mcp__claude_ai_Google_Calendar__*';+function md5(str) {return createHash('md5').update(str).digest('hex').slice(0, 12);}@@ -139,14 +148,12 @@ After fetching ALL calendars, output ONLY a single JSON object (no markdown fencInclude the full events arrays as returned by gcal_list_events. Output NOTHING else — just the JSON.`;- const result = await runClaudeMcp(prompt, io, accountId).catch(err => {- console.error(`❌ MCP sync failed for ${account.name}: ${err.message}`);- return { error: err.message };- });+ const result = await runClaudeMcp(prompt, io, accountId);mcpSyncLock.delete(accountId);if (result.error) {+ console.error(`❌ MCP sync failed for ${account.name}: ${result.error}`);io?.emit('calendar:sync:failed', { accountId, error: result.error, method: 'mcp' });await updateSyncStatus(accountId, 'error');return { error: result.error, status: 502 };@@ -217,12 +224,10 @@ For each calendar, use:Output NOTHING else — just the JSON array.`;- const result = await runClaudeMcp(prompt, io, accountId).catch(err => {- console.error(`❌ Calendar discovery failed: ${err.message}`);- return { error: err.message };- });+ const result = await runClaudeMcp(prompt, io, accountId);if (result.error) {+ console.error(`❌ Calendar discovery failed: ${result.error}`);return { error: result.error, status: 502 };}@@ -242,50 +247,43 @@ Output NOTHING else — just the JSON array.`;return { calendars: merged, status: 'success' };}-function runClaudeMcp(prompt, io, accountId) {- return new Promise((resolve, reject) => {- const args = ['-p', '-', '--allowedTools', 'mcp__claude_ai_Google_Calendar__*'];- const claudeProcess = spawn(process.env.CLAUDE_PATH || 'claude', args, {- cwd: process.cwd(),- shell: false,- env: (() => { const e = { ...process.env }; delete e.CLAUDECODE; return e; })()- });-- let output = '';- let stderr = '';- const timeout = setTimeout(() => {- claudeProcess.kill('SIGTERM');- reject(new Error('MCP sync timed out after 5 minutes'));- }, 300000);-- claudeProcess.stdin.write(prompt);- claudeProcess.stdin.end();-- claudeProcess.stdout?.on('data', (data) => {- output += data.toString();- });-- claudeProcess.stderr?.on('data', (data) => {- const text = data.toString();- stderr += text;- // Emit progress for UI feedback- if (text.includes('gcal_list_events')) {+async function runClaudeMcp(prompt, io, accountId) {+ // Resolve the user's configured calendar-sync provider/model (falls back to+ // claude-code — the historical default — when unset). Restricted to CLI+ // providers since the sync relies on MCP tool calling.+ const all = await getAllProviders().catch(() => null);+ const settings = await getSettings().catch(() => ({}));+ const picked = pickCliProvider(all?.providers, settings?.calendarSync || {});+ if (picked.error) {+ return { error: picked.error };+ }++ // `--allowedTools mcp__…` is Claude-Code-specific argv. Other CLIs grant MCP+ // access through their own config (codex/gemini have no such flag), so pass+ // it only to Claude-family providers — appending it to another CLI would+ // make it reject the invocation on an unknown flag.+ const isClaudeFamily = /claude/i.test(picked.provider.command || '') || /claude/i.test(picked.provider.id || '');+ const extraArgs = isClaudeFamily ? ['--allowedTools', CALENDAR_MCP_ALLOWED_TOOLS] : [];++ console.log(`📅 Calendar MCP sync via ${picked.provider.id}${picked.model ? ` (${picked.model})` : ''}`);++ const result = await runCliProviderPrompt({+ provider: picked.provider,+ model: picked.model,+ prompt,+ cwd: process.cwd(),+ extraArgs,+ timeoutMs: 300000,+ onData: (chunk, stream) => {+ // Emit progress for UI feedback when the model starts listing events.+ if (stream === 'stderr' && chunk.includes('gcal_list_events')) {io?.emit('calendar:sync:progress', { accountId, message: 'Fetching calendar events...' });}- });-- claudeProcess.on('close', (code) => {- clearTimeout(timeout);- if (code !== 0 && !output) {- reject(new Error(stderr.slice(0, 500) || `Claude exited with code ${code}`));- } else {- resolve({ output: output.trim(), exitCode: code });- }- });-- claudeProcess.on('error', (err) => {- clearTimeout(timeout);- reject(new Error(`Failed to spawn Claude CLI: ${err.message}`));- });+ },});++ if (result.error) {+ return { error: result.error };+ }+ return { output: result.text, exitCode: result.exitCode };}diff --git a/server/services/runner.js b/server/services/runner.jsindex 45d95d2b21..cb4d7e9181 100644--- a/server/services/runner.js+++ b/server/services/runner.js@@ -6,7 +6,8 @@ import { spawn } from 'child_process';import { writeFile, readFile } from 'fs/promises';import { join } from 'path';import { ensureDir, tryReadFile } from '../lib/fileUtils.js';-import { resolveCliModel, hasModelFlag, extractBakedModel } from '../lib/providerModels.js';+import { hasModelFlag, extractBakedModel } from '../lib/providerModels.js';+import { buildCliArgs } from '../lib/cliProviderArgs.js';import {setAIToolkitInstance,getAIToolkitInstance,@@ -19,6 +20,12 @@ import {// imports from directly (lib→lib, no service layer violation).export { hasModelFlag, extractBakedModel };+// `buildCliArgs` was extracted to `server/lib/cliProviderArgs.js` (a+// dependency-light module the standalone autofixer + calendar MCP sync can+// import). Re-exported here so its existing importers — and runner.test.js —+// keep resolving it from runner.js unchanged.+export { buildCliArgs };+// Runner-only state. The toolkit singleton itself lives in// `lib/aiToolkitState.js` and is shared with providers / promptService;// `runnerConfig` (dataDir + hooks) is captured here because only the runner@@ -36,91 +43,6 @@ export async function createRun(options) {return requireToolkit().services.runner.createRun(options);}-/**- * Build CLI args based on provider type.- * Each CLI provider has different conventions for stdin input and model- * selection. `provider.defaultModel` is honored for all three (codex /- * claude-code / gemini-cli) so a per-call clone with an overridden- * defaultModel (e.g. modal-selected "thinking" tier in Refine Prompt)- * actually picks the modal-selected model instead of falling back to- * whatever's baked into `provider.args`.- *- * Model-flag injection is GATED on `provider.args` not already containing- * a model flag — users who hard-coded e.g. `--model gemini-2.5-pro` in- * their saved provider config keep that override and don't get a- * duplicate flag from us.- */-export function buildCliArgs(provider) {- const providerId = provider?.id || '';- // Sanitize: drop any broken/dangling `--model` / `-m` tokens before- // appending. hasModelFlag treats those as "not a real pin" so the- // injection path fires — but if we kept the bogus token in baseArgs the- // CLI would still see two `--model` occurrences and reject the argv.- const baseArgs = stripBrokenModelFlags(Array.isArray(provider?.args) ? provider.args : []);- const effectiveDefaultModel = providerId === 'codex'- ? resolveCliModel(provider.defaultModel)- : provider.defaultModel;-- // Codex CLI: `codex exec -` reads prompt from stdin, --model for model.- // Detect an existing leading `exec` in user/legacy args so we don't end up- // running `codex exec --full-auto exec -` after migration of legacy- // configs that already pinned an `exec` subcommand.- if (providerId === 'codex') {- const hasExec = baseArgs.includes('exec');- const args = hasExec ? [...baseArgs] : [...baseArgs, 'exec'];- if (effectiveDefaultModel) {- args.push('--model', effectiveDefaultModel);- }- args.push('-'); // stdin marker- return args;- }-- // Gemini CLI: prompt is piped via stdin directly. `-m <model>` is gemini-- // cli's documented short flag for model selection (long form: `--model`).- // Skip injection when the user's saved args already pin a model (either- // form) so we don't duplicate the flag.- if (providerId === 'gemini-cli') {- const args = [...baseArgs];- if (effectiveDefaultModel && !hasModelFlag(baseArgs)) {- args.push('-m', effectiveDefaultModel);- }- return args;- }-- // Default (Claude Code CLI): `-p -` means "read prompt from stdin".- // `--model <id>` is claude-code's model flag; it parses flags- // positionally so appending after `-p -` is fine. Same gate as gemini-- // cli — respect user-baked model flags.- const args = [...baseArgs, '-p', '-'];- if (effectiveDefaultModel && !hasModelFlag(baseArgs)) {- args.push('--model', effectiveDefaultModel);- }- return args;-}--// Strip dangling/empty `--model` / `-m` tokens (no value follows, or the-// joined form has an empty value). Those would survive into the spawned-// argv unchanged and cause the CLI to reject the invocation — see the-// comment on hasModelFlag for the full reasoning. Pinned-with-value tokens-// are preserved untouched so user-baked model selections still win.-function stripBrokenModelFlags(args) {- if (!Array.isArray(args) || args.length === 0) return [];- const out = [];- for (let i = 0; i < args.length; i++) {- const a = args[i];- if (typeof a === 'string' && (a === '--model=' || a === '-m=')) {- continue; // empty joined form- }- if (a === '--model' || a === '-m') {- const next = args[i + 1];- const hasValue = typeof next === 'string' && next.length > 0 && !next.startsWith('-');- if (!hasValue) continue; // dangling separated form- }- out.push(a);- }- return out;-}-/*** Returns the configured runs directory. Other execution paths* (`server/lib/tuiPromptRunner.js`) need this to write output + metadata