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
refactor([med-ai-dispatch-server-services-digital-twin]): migrate callProviderAI to runPromptThroughProvider
[._.]/ Adam Eivy409a87b6c0de
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex bc35ea57e3..20ff8b9090 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,8 @@## Changed+- **[med-ai-dispatch-server-services-digital-twin] `callProviderAI` migrated to `runPromptThroughProvider` — TUI providers now work for Digital Twin AI calls.** `server/services/digital-twin-helpers.js#callProviderAI` previously had a hand-rolled `if (provider.type === 'api') fetch(...) else spawn(provider.command, ...)` split that silently routed TUI providers (claude-code, etc.) into the CLI spawn branch. That branch piped the prompt into stdin against a process expecting a PTY — depending on the binary either it hung until the per-call timeout or scraped its interactive banner chrome into the returned text, so every Digital Twin AI feature was unusable when the user's active provider was a TUI. Migrated to the shared `runPromptThroughProvider` from `server/lib/promptRunner.js` (`source: 'digital-twin'`) so dispatch goes through `executeCliRun` / `executeApiRun` / `executeTuiRun` per `provider.type`, with the same TUI-chrome stripping the rest of the codebase relies on. Return shape (`{ text }` / `{ error }`) is preserved so the 12 call sites across `digital-twin-testing.js`, `digital-twin-import.js`, `digital-twin-enrichment.js`, and `digital-twin-analysis.js` don't change behavior on the parse-and-fallback paths. The legacy `temperature` / `max_tokens` named options were dropped from both the function signature and all 12 call sites — the toolkit's `executeApiRun` doesn't forward them, matching every other unified-runner caller in the repo, so keeping them at call sites would have been cargo-culted. `server/services/digital-twin.test.js` switched from mocking `global.fetch` to mocking `../lib/promptRunner.js` for the goodreads-CSV provider-call test. 87/87 digital-twin tests pass; 6150/6150 server tests pass.+- **[extract-cover-render-handler-factory] Four cover-render route handlers collapsed into one config-driven factory.** The volume front/back + comic-issue front/back cover-render routes in `server/routes/pipeline.js` were 95% identical — differing only in { Zod schema, slot field (`cover` vs `backCover`), script body field (`coverScript` vs `backCoverScript`), optional precheck (issue routes ran `getIssue` for an early 404), enqueue fn (`enqueueVolumeCover` / `enqueueVolumeBackCover` / `enqueueComicCover` / `enqueueComicBackCover`), write fn (`seriesSvc.updateSeasonOnSeries` vs `issuesSvc.updateStageWithLatest`), and response shape (`{ season, series }` vs `{ cover|backCover, issue, stage }`) }. Extracted `makeCoverRenderHandler({ schema, slotField, scriptField, prepare, enqueue, applyWrite, buildResponse })` factory + a pure `buildCoverPatchFn` helper that owns the shared `compute` closure — same `typeof body[scriptField] === 'string'` script-gate semantics (absent preserves, empty-string clears) on all four routes, just defined once. Two named helpers (`updateVolumeSeason`, `updateComicPagesStage`) capture the per-record write signature so the route definitions only declare what's actually different. Net ~80 LOC → ~25 LOC across the four routes; 85/85 pipeline route tests pass (preserves the script-gate invariants pinned by `[med-pipeline-server-routes-pipeline-js-1416-1452]`); 6150/6150 server tests pass.- **[med-sharing-server-services-sharing-version-js] Sharing importer salvages pre-B.4 series-side canon instead of dropping it.** Cross-peer share-bucket imports from a pre-B.4 install previously lost any `series.{characters, settings|places, objects}` arrays silently — `sanitizeSeries` (post-B.4) strips those fields on insert, and the importer fed records straight into `insertSeriesWithId`. The B.4 schema teardown intentionally moved canon onto the linked universe, so the recovery shape was the existing `migrateSeriesCanon` CLI helper; the gap was that nothing ran it for peer-authored records. `server/services/pipeline/migrateSeriesCanon.js` now exposes a per-record helper `applyLegacySeriesCanonToUniverse(series, { dryRun, log })` (extracted from the CLI batch's loop body) that folds legacy canon into the linked or freshly-created universe with the same `SERIES_EXTRACT` + `autoLock` + `sourceSeriesId` provenance the live extract path uses. `server/services/sharing/importer.js` calls this helper for every incoming series record carrying a non-empty `characters / settings / places / objects` array — between the universes merge loop and the series merge loop, so the universe (existing or newly minted for orphan series) holds the canon by the time `sanitizeSeries` runs. The pre-022 `settings[]` wire name is coalesced onto `places[]` inside the helper so peers shipping either rename-era survive. Two new integration tests in `services/sharing/integration.test.js` lock in the linked-universe and orphan-universe paths; 5904 server tests pass. `SHARING_SCHEMA_VERSION` is intentionally NOT bumped — the version bump would only help if paired with a hard refusal, and salvaging the data is the kinder outcome.diff --git a/PLAN.md b/PLAN.mdindex 9d09896882..5393f532bf 100644--- a/PLAN.md+++ b/PLAN.md@@ -18,7 +18,6 @@ _Nothing currently parked — pick the next item from the Backlog._### v2.1.0 pre-release review residue (deferred from main→release multi-agent review, 2026-05-16)-- [ ] [med-ai-dispatch-server-services-digital-twin] **[MED][AI-DISPATCH]** `server/services/digital-twin-helpers.js:56-130` — `callProviderAI` still has ad-hoc CLI/API split with TUI falling into the CLI branch (will hang or render banner into pipe). Migrate to `runPromptThroughProvider`.- [ ] [med-ai-dispatch-server-lib-tuipromptrunner-js-198] **[MED][AI-DISPATCH]** `server/lib/tuiPromptRunner.js:198-200` — `OUTPUT_BUFFER_CAP = 1MB` silently truncates the _head_ of TUI responses >1.25MB mid-token. Persists to disk AND returns truncated. Either stream incrementally to `output.txt` (like agentTuiSpawning does) or raise the cap + log a warning.- [ ] [med-tests-no-direct-tests-for-executetuirun-pty] **[MED][TESTS]** No direct tests for `executeTuiRun` PTY mechanics — idle-complete, hard-timeout, missing-binary early-fail, `emitRunStarted` shape, CLAUDECODE env stripping. The new `tuiPromptRunner.test.js` only covers `cleanTuiResponse`.- [ ] [med-importer-server-routes-importer-test-js-no] **[MED][IMPORTER]** `server/routes/importer.test.js` — no test pins `ERR_PARTIAL_COMMIT_ISSUES → 207` status mapping. Future refactor that drops the entry from `SERVICE_ERROR_STATUS` would 500 on partial commits and trigger pager alerts (the in-code comment's stated regression).diff --git a/server/services/digital-twin-analysis.js b/server/services/digital-twin-analysis.jsindex 0c2fb74b87..d59a88eb12 100644--- a/server/services/digital-twin-analysis.js+++ b/server/services/digital-twin-analysis.js@@ -145,7 +145,7 @@ export async function detectContradictions(providerId, model) {return { issues: [], error: 'Provider not found or disabled' };}- const result = await callProviderAI(provider, model, prompt, { temperature: 0.3, max_tokens: 2000 });+ const result = await callProviderAI(provider, model, prompt);if (!result.error && result.text) {return parseContradictionResponse(result.text);}@@ -190,7 +190,7 @@ export async function generateDynamicTests(providerId, model) {return { tests: [], error: 'Provider not found or disabled' };}- const result = await callProviderAI(provider, model, prompt, { temperature: 0.7, max_tokens: 3000 });+ const result = await callProviderAI(provider, model, prompt);if (!result.error && result.text) {return parseGeneratedTests(result.text);}@@ -235,7 +235,7 @@ export async function analyzeWritingSamples(samples, providerId, model) {return { error: 'Provider not found or disabled' };}- const result = await callProviderAI(provider, model, prompt, { temperature: 0.5, max_tokens: 2000 });+ const result = await callProviderAI(provider, model, prompt);if (!result.error && result.text) {return parseWritingAnalysis(result.text);}@@ -368,7 +368,7 @@ export async function analyzeTraits(providerId, model, forceReanalyze = false) {return { error: 'Provider not found or disabled' };}- const result = await callProviderAI(provider, model, prompt, { temperature: 0.3, max_tokens: 3000 });+ const result = await callProviderAI(provider, model, prompt);if (result.error) {return { error: result.error };}@@ -449,7 +449,7 @@ export async function calculateConfidence(providerId, model) {return calculateLocalConfidence(twinContent, currentTraits, meta);}- const result = await callProviderAI(provider, model, prompt, { temperature: 0.3, max_tokens: 2000 });+ const result = await callProviderAI(provider, model, prompt);if (!result.error && result.text) {const parsed = parseConfidenceResponse(result.text);diff --git a/server/services/digital-twin-enrichment.js b/server/services/digital-twin-enrichment.jsindex c58df2785f..29663c3575 100644--- a/server/services/digital-twin-enrichment.js+++ b/server/services/digital-twin-enrichment.js@@ -119,7 +119,7 @@ export async function generateEnrichmentQuestion(category, providerOverride, modconst fallbackText = `What else should your digital twin know about your ${config.label.toLowerCase()}?`;let question = null;- const result = await callProviderAI(provider, model, prompt, { temperature: 0.8, max_tokens: 200 });+ const result = await callProviderAI(provider, model, prompt);if (!result.error && result.text) {question = result.text.trim() || null;}@@ -269,7 +269,7 @@ export async function processEnrichmentAnswer(data) {}).catch(() => null);if (prompt) {- const result = await callProviderAI(provider, modelOverride || provider.defaultModel, prompt, { temperature: 0.3, max_tokens: 500 });+ const result = await callProviderAI(provider, modelOverride || provider.defaultModel, prompt);if (!result.error && result.text) {formattedContent = result.text.trim() || formattedContent;}@@ -451,7 +451,7 @@ Respond in JSON format:}\`\`\``;- const result = await callProviderAI(provider, model, prompt, { temperature: 0.7, max_tokens: 3000 });+ const result = await callProviderAI(provider, model, prompt);if (result.error) {throw new Error(result.error);}diff --git a/server/services/digital-twin-helpers.js b/server/services/digital-twin-helpers.jsindex df0f0bb6c8..20f208a2fc 100644--- a/server/services/digital-twin-helpers.js+++ b/server/services/digital-twin-helpers.js@@ -1,9 +1,7 @@import { v4 as uuidv4 } from '../lib/uuid.js';import { existsSync } from 'fs';import { ensureDir, PATHS, safeJSONParse } from '../lib/fileUtils.js';-import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';--const DEFAULT_AI_TIMEOUT_MS = 300000;+import { runPromptThroughProvider } from '../lib/promptRunner.js';export const DIGITAL_TWIN_DIR = PATHS.digitalTwin;@@ -51,80 +49,24 @@ export async function ensureSoulDir() {}/**- * Call any AI provider (API or CLI) with a prompt and return the response text.+ * Call any AI provider (CLI / API / TUI) with a prompt and return the response text.+ *+ * Dispatches through the shared `runPromptThroughProvider` so TUI providers+ * (claude-code, etc.) no longer fall into the legacy CLI spawn branch — that+ * branch piped raw stdin into a process that wanted an interactive PTY and+ * either hung or echoed banner chrome into the captured output. The shared+ * runner picks the right transport per provider type and strips TUI chrome+ * before returning the cleaned response.+ *+ * Returns `{ text }` on success, `{ error }` on failure — preserved from the+ * legacy shape so the parse-and-fallback patterns in callers keep working.*/-export async function callProviderAI(provider, model, prompt, { temperature = 0.3, max_tokens = 4000 } = {}) {- const timeout = provider.timeout || DEFAULT_AI_TIMEOUT_MS;-- if (provider.type === 'api') {- const headers = { 'Content-Type': 'application/json' };- if (provider.apiKey) headers['Authorization'] = `Bearer ${provider.apiKey}`;-- const response = await fetchWithTimeout(`${provider.endpoint}/chat/completions`, {- method: 'POST',- headers,- body: JSON.stringify({- model,- messages: [{ role: 'user', content: prompt }],- temperature,- max_tokens- })- }, timeout).catch((err) => ({ ok: false, _fetchError: err.name === 'AbortError' ? 'AI request timed out' : err.message }));-- if (response._fetchError) {- return { error: response._fetchError };- }-- if (!response.ok) {- return { error: `Provider API error: ${response.status}` };- }-- const data = await response.json();- return { text: data.choices?.[0]?.message?.content || '' };- }-- // CLI provider — pipe prompt via stdin to avoid arg length limits on large prompts- const { spawn } = await import('child_process');- return new Promise((resolve) => {- const args = [...(provider.args || [])];- let output = '';- let resolved = false;-- const child = spawn(provider.command, args, {- env: (() => { const e = { ...process.env, ...provider.envVars }; delete e.CLAUDECODE; return e; })(),- shell: false,- stdio: ['pipe', 'pipe', 'pipe'],- windowsHide: true- });-- // Pipe prompt via stdin- child.stdin.write(prompt);- child.stdin.end();-- child.stdout.on('data', (data) => { output += data.toString(); });- child.stderr.on('data', (data) => { output += data.toString(); });- const timeoutHandle = setTimeout(() => {- if (resolved) return;- resolved = true;- child.kill();- resolve({ error: 'AI request timed out' });- }, timeout);-- child.on('close', (code) => {- clearTimeout(timeoutHandle);- if (resolved) return;- resolved = true;- if (code === 0) {- resolve({ text: output });- } else {- resolve({ error: `CLI exited with code ${code}: ${output.substring(0, 500)}` });- }- });- child.on('error', (err) => {- clearTimeout(timeoutHandle);- if (resolved) return;- resolved = true;- resolve({ error: err.message });- });- });+export async function callProviderAI(provider, model, prompt) {+ return runPromptThroughProvider({+ provider,+ prompt,+ model,+ source: 'digital-twin',+ }).then(({ text }) => ({ text: text || '' }))+ .catch((err) => ({ error: err?.message || 'AI request failed' }));}diff --git a/server/services/digital-twin-import.js b/server/services/digital-twin-import.jsindex c10c59e2a5..5279a3f4c6 100644--- a/server/services/digital-twin-import.js+++ b/server/services/digital-twin-import.js@@ -286,7 +286,7 @@ async function analyzeWithPrompt(prompt, providerId, model, source, parsedData)return { error: 'Provider not found or disabled' };}- const result = await callProviderAI(provider, model, prompt, { temperature: 0.4, max_tokens: 3000 });+ const result = await callProviderAI(provider, model, prompt);if (!result.error && result.text) {return parseImportAnalysisResponse(result.text, source, parsedData);}@@ -514,7 +514,7 @@ export async function analyzeAssessment(content, providerId, model) {// 3. Call AI for analysisconsole.log(`🧪 [${now()}] Calling ${provider.name} (${model}), prompt=${analysisPrompt.length} chars`);- const aiResponse = await callProviderAI(provider, model, analysisPrompt, { temperature: 0.3, max_tokens: 4000 });+ const aiResponse = await callProviderAI(provider, model, analysisPrompt);if (aiResponse.error) {return { error: aiResponse.error };diff --git a/server/services/digital-twin-testing.js b/server/services/digital-twin-testing.jsindex 7e8e66fb9f..3a5940c075 100644--- a/server/services/digital-twin-testing.js+++ b/server/services/digital-twin-testing.js@@ -98,7 +98,7 @@ async function runSingleTest(test, soulContext, providerId, model) {// Combine system prompt with user prompt for callProviderAI (single-message interface)const combinedPrompt = `You are embodying the following identity. Respond as this person would, based on the soul document below:\n\n${soulContext}\n\nUser: ${test.prompt}`;- const result = await callProviderAI(provider, model, combinedPrompt, { temperature: 0.7, max_tokens: 1000 });+ const result = await callProviderAI(provider, model, combinedPrompt);if (result.error) {throw new Error(result.error);}@@ -142,7 +142,7 @@ async function scoreTestResponse(test, response, providerId, model) {}const provider = await getProviderById(providerId);- const result = await callProviderAI(provider, model, prompt, { temperature: 0.1, max_tokens: 500 });+ const result = await callProviderAI(provider, model, prompt);if (!result.error && result.text) {return parseScoreResponse(result.text);diff --git a/server/services/digital-twin.test.js b/server/services/digital-twin.test.jsindex aab7aea55d..65e78288fd 100644--- a/server/services/digital-twin.test.js+++ b/server/services/digital-twin.test.js@@ -73,6 +73,10 @@ vi.mock('./socialAccounts.js', () => ({getAllAccounts: vi.fn(() => [])}));+vi.mock('../lib/promptRunner.js', () => ({+ runPromptThroughProvider: vi.fn()+}));+// ============================================================================// Imports// ============================================================================@@ -82,6 +86,7 @@ import { existsSync } from 'fs';import { getProviderById, getActiveProvider } from './providers.js';import { buildPrompt } from './promptService.js';import { safeJSONParse } from '../lib/fileUtils.js';+import { runPromptThroughProvider } from '../lib/promptRunner.js';import {digitalTwinEvents,@@ -1249,13 +1254,10 @@ Should mention core values.getProviderById.mockResolvedValue(mockProvider);buildPrompt.mockResolvedValue(null); // Force fallback prompt- // Mock fetch for callProviderAI- const originalFetch = global.fetch;- global.fetch = vi.fn().mockResolvedValue({- ok: true,- json: async () => ({- choices: [{ message: { content: '```json\n{"insights": {"patterns": ["voracious reader"]}, "rawSummary": "test"}\n```' } }]- })+ runPromptThroughProvider.mockResolvedValue({+ text: '```json\n{"insights": {"patterns": ["voracious reader"]}, "rawSummary": "test"}\n```',+ runId: 'run-1',+ model: 'model-1'});safeJSONParse.mockImplementation((str, defaultValue) => {@@ -1266,8 +1268,6 @@ Should mention core values.const result = await analyzeImportedData('goodreads', csv, 'p1', 'model-1');expect(result.source).toBe('goodreads');expect(result.itemCount).toBe(2);-- global.fetch = originalFetch;});});