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
promote aiProvider into services, keeping its pure text helpers in lib
[._.]/ Adam Eivyd0a8ebf40a02
diff --git a/client/public/flows.json b/client/public/flows.jsonindex 0bd3495053..c2c4adb373 100644--- a/client/public/flows.json+++ b/client/public/flows.json@@ -71,7 +71,7 @@{ "id": "svc.cosJobScheduler", "label": "cosJobScheduler", "group": "server-services", "file": "server/services/cosJobScheduler.js", "desc": "Fires due scheduled jobs: inline script/shell or task:ready for AI agents." },{ "id": "lib.promptRunner", "label": "promptRunner", "group": "server-lib", "file": "server/lib/promptRunner.js", "desc": "Assembles prompts from templates + context and runs them through a provider." },- { "id": "lib.aiProvider", "label": "aiProvider + aiToolkit", "group": "server-lib", "file": "server/lib/aiProvider.js", "desc": "Provider registry/resolution: CLI providers, local backends, model selection." },+ { "id": "lib.aiProvider", "label": "aiProvider + aiToolkit", "group": "server-lib", "file": "server/services/aiProvider.js", "desc": "Provider registry/resolution: CLI providers, local backends, model selection." },{ "id": "lib.peerHttpClient", "label": "peerHttpClient", "group": "server-lib", "file": "server/lib/peerHttpClient.js", "desc": "peerFetch: authenticated HTTP to federated peer instances." },{ "id": "lib.navManifest", "label": "navManifest", "group": "server-lib", "file": "server/lib/navManifest.js", "desc": "NAV_COMMANDS + resolveNavCommand — shared by ⌘K palette and voice nav." },diff --git a/server/lib/README.md b/server/lib/README.mdindex 84f6248c9e..cf260c9ff6 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -117,7 +117,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `aiToolkit/` | Vendored toolkit (providers + runner + prompts + status). See `aiToolkit/index.js`. || `aiToolkitState.js` | Module-level singleton for the toolkit instance shared by the `providers`/`runner`/`promptService` shims — `setAIToolkitInstance` / `requireToolkit` (throws `AI_TOOLKIT_NOT_INITIALIZED`) / `getAIToolkitInstance` (no-throw for cleanup paths). || `antigravity.js` | Antigravity (`agy`) CLI provider helpers — id/sentinel constants (`ANTIGRAVITY_CLI_ID`, `ANTIGRAVITY_CONFIGURED_DEFAULT`, `LEGACY_GEMINI_*`), `isAntigravityCommand`/`isAntigravityCliProvider` predicates, and `ensureAntigravityPrintArgs(args, {model, effort})`/`ensureAntigravityTuiArgs(args, {model, effort})`/`stripAntigravityUnsupportedArgs` argv normalizers. `parseAntigravityModelList(stdout)` parses `agy models` rows — accepts both the modern `<id>\t<Label>` shape and the older bare-id-per-line one, deduped, sentinel dropped (mirrored in the vendored toolkit's `internal/antigravity.js`; used by both the provider-catalog refresh and Image Gen's agy model picker). `isAntigravityModelId(id)` is the same id shape as a bare predicate, for spawn sites building an `agy --model` argv from a value no route schema bounded. The strip drops legacy Gemini `--yolo`/`-m`/`--output-format` but PRESERVES the long `--model` (agy accepts it as a per-session flag, so a user-baked pin is a real selection and suppresses the injected one); the two builders inject `--model`/`--effort` from the per-run overrides, always ahead of the trailing `--print` marker whose value is the prompt. |-| `aiProvider.js` | Shared AI provider utilities for LLM calls. |+| `llmText.js` | Pure LLM-output text helpers — `stripCodeFences` (unfence a model reply) and `parseLLMJSON` (unfence then JSON.parse with a descriptive throw). Below the provider layer, so lib can clean model output without importing provider orchestration. || `promptRunner.js` | Shared LLM runner wrapper. || `providerCooldown.js` | Provider bench policy — `resolveProviderBench(analysis)` → `null` (don't bench) / a `usage-limit` marker / an `unavailable` marker with the per-category cooldown from `COOLDOWN_MS_BY_CATEGORY`. Declines to bench request/response-specific categories (`isRequestSpecificCategory` / `isSchemaTypeCategory`) so one bad model id or off-shape response can't take a healthy provider offline. Shared by `promptRunner.js` (prompt cascade) and `services/agentFinalization.js` (finished CoS agent run) so both bench a category for the same window. Pure. || `providerPrerequisites.js` | Can a provider run on this host AT ALL — `providerPrerequisites(provider, { runtime, gatewayKeySet })` → `{ met, missing: [{ code, label }] }` (CLI binary on PATH, API key stored for a public endpoint, the sibling key a gateway-backed wrapper inherits from the API record of its own gateway id unless it carries its own), plus `providerRuntimeKey` (`null` for an API provider, for a command carrying an explicit path, and for a provider with its own `PATH` in `envVars` — the runtime table only answers "does the BARE binary resolve on PortOS's PATH?", which is not those providers' question), `isPrivateNetworkEndpoint` (mirror of the client copy: loopback/RFC1918/tailnet CGNAT + ULA/`.ts.net`/single-label hosts need no key) and `describeMissingPrerequisites`. `runtime: null` = NOT PROBED and never counts as missing. Feeds BOTH `GET /api/providers` and the fallback chain in `aiToolkit/providerStatus.js` (via `services/providerPrerequisites.js`), so a `NEEDS SETUP` card and the router read one computation (#4611). `ROUTING_BLOCKING_CODES`/`blocksRouting(missing)` narrow what ROUTING may act on to the missing binary. Stored, inherited, and environment-backed credential findings stay presentation-only here because the server cannot assume the eventual process environment; the client card classifies sanitized env metadata through tri-state lookups (#4612). Pure. |diff --git a/server/lib/aiToolkit/internal/endpointGuard.js b/server/lib/aiToolkit/internal/endpointGuard.jsindex d6504fe9c1..5650a5a588 100644--- a/server/lib/aiToolkit/internal/endpointGuard.js+++ b/server/lib/aiToolkit/internal/endpointGuard.js@@ -25,7 +25,7 @@* credential-theft target.** Kept in `aiToolkit/internal/` (pure, no imports) so the toolkit stays- * self-contained; `server/lib/aiProvider.js` imports it from here too.+ * self-contained; `server/services/aiProvider.js` imports it from here too.** NOTE: checks are performed on the URL's literal host. We do not resolve DNS,* so a user-supplied hostname that resolves to a private/metadata IP is treateddiff --git a/server/lib/index.js b/server/lib/index.jsindex c08d91f83f..8adb1f20f1 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -104,7 +104,7 @@ export * from './writersRoomPresets.js';export * from './writersRoomStylePresets.js';// === Prompt & AI (toolkit lives in aiToolkit/ — see its own index.js) ===-export * from './aiProvider.js';+export * from './llmText.js';export * from './aiToolkitState.js';export * from './ansiStrip.js';// Namespaced: antigravity.js and providerModels.js both exportdiff --git a/server/lib/jsonExtract.js b/server/lib/jsonExtract.jsindex 12f82add1f..e34ef4707b 100644--- a/server/lib/jsonExtract.js+++ b/server/lib/jsonExtract.js@@ -18,7 +18,7 @@* the three callers import from this file with optional shape predicates.*/-import { stripCodeFences } from './aiProvider.js';+import { stripCodeFences } from './llmText.js';/*** Walk the string and return every top-level brace-balanced block, indiff --git a/server/lib/layering.test.js b/server/lib/layering.test.jsindex 24a99928a9..1b6e2acd2a 100644--- a/server/lib/layering.test.js+++ b/server/lib/layering.test.js@@ -24,7 +24,6 @@ const LIB_ROOT = dirname(fileURLToPath(import.meta.url));// inversion awaiting its slice of #4901 — NOT a permanent exemption. Fix the// module, delete the row. Never add a row for new code.const PREEXISTING_LIB_TO_SERVICES_ALLOWLIST = new Set([- 'aiProvider.js','assetMounts.js','createSettingsGatedSyncScheduler.js','creativeDirectorPrompts.js',diff --git a/server/lib/llmText.js b/server/lib/llmText.jsnew file mode 100644index 0000000000..4867a5cb07--- /dev/null+++ b/server/lib/llmText.js@@ -0,0 +1,34 @@+/**+ * Pure text helpers for LLM responses.+ *+ * These sit below the provider layer so a lib module can clean up model output+ * without importing the provider orchestration that produced it (issue #4901).+ * They were exported from `aiProvider.js` while it lived in lib; that module+ * calls providers and moved to services, but nothing about unfencing a string+ * needs a provider. `services/aiProvider.js` re-exports both, so existing+ * imports keep working.+ */++/**+ * Strip markdown code fences from LLM output before JSON.parse.+ *+ * Trims surrounding whitespace BEFORE the fence regex so common LLM shapes+ * with trailing newlines/spaces around the closing fence (e.g. "```json\n{}\n```\n")+ * still get the closing ``` stripped — the regex anchors on end-of-string.+ */+export function stripCodeFences(raw) {+ return raw.trim().replace(/^```(?:json)?\n?/, '').replace(/\n?```$/, '').trim();+}++/**+ * Parse JSON from LLM output, stripping code fences first.+ * Throws a descriptive error on parse failure.+ */+export function parseLLMJSON(raw) {+ const cleaned = stripCodeFences(raw);+ try {+ return JSON.parse(cleaned);+ } catch (e) {+ throw new Error(`Invalid JSON from AI: ${e.message}`);+ }+}diff --git a/server/lib/stageRunner.js b/server/lib/stageRunner.jsindex 21d080a82b..c16a6fbecc 100644--- a/server/lib/stageRunner.js+++ b/server/lib/stageRunner.js@@ -17,7 +17,7 @@import { ServerError } from './errorHandler.js';import { findBalancedBlocks, tryParseWithRepair } from './jsonExtract.js';import { resolveEffectiveModel, runPromptThroughProvider, DEFAULT_TIMEOUT_MS, isLocalEndpoint } from './promptRunner.js';-import { stripCodeFences } from './aiProvider.js';+import { stripCodeFences } from './llmText.js';import { extractCodexAssistant } from './codexAssistantExtract.js';import { getActiveProvider, getProviderById } from '../services/providers.js';import { commandBasename, isCodexProvider } from './providerModels.js';diff --git a/server/lib/aiProvider.js b/server/services/aiProvider.jssimilarity index 92%rename from server/lib/aiProvider.jsrename to server/services/aiProvider.jsindex d44ab7cbba..8dc14c4e01 100644--- a/server/lib/aiProvider.js+++ b/server/services/aiProvider.js@@ -3,17 +3,17 @@* Used by insightsService, identity, goalCheckIn, taste-questionnaire, etc.*/-import { getAllProviders } from '../services/providers.js';-import { startAIOp } from '../services/aiStatusEvents.js';-import { ensureProviderReady as ensureOllamaProviderReady, isOllamaProvider } from '../services/ollamaManager.js';-import { ensureMtplxProviderReady, isMtplxProvider } from '../services/mtplxServerManager.js';+import { getAllProviders } from './providers.js';+import { startAIOp } from './aiStatusEvents.js';+import { ensureProviderReady as ensureOllamaProviderReady, isOllamaProvider } from './ollamaManager.js';+import { ensureMtplxProviderReady, isMtplxProvider } from './mtplxServerManager.js';// localModelHealing is lazy-imported at its (rare, error-recovery) call site// below — a static import here pulls its notifications/providers deps (which// eagerly import fileUtils `PATHS`) into every aiProvider consumer's module// graph, breaking suites that partial-mock fileUtils without PATHS.-import { readResponseJson } from './readResponseJson.js';-import { evaluateSecretEndpoint } from './aiToolkit/internal/endpointGuard.js';-import { withCreativeLatitude } from './creativeLatitude.js';+import { readResponseJson } from '../lib/readResponseJson.js';+import { evaluateSecretEndpoint } from '../lib/aiToolkit/internal/endpointGuard.js';+import { withCreativeLatitude } from '../lib/creativeLatitude.js';const isAPI = (p) => p && p.type === 'api' && p.enabled !== false;@@ -335,26 +335,7 @@ export async function callProviderAISimple(provider, model, prompt, options = {}return { error: first.error };}-/**- * Strip markdown code fences from LLM output before JSON.parse.- *- * Trims surrounding whitespace BEFORE the fence regex so common LLM shapes- * with trailing newlines/spaces around the closing fence (e.g. "```json\n{}\n```\n")- * still get the closing ``` stripped — the regex anchors on end-of-string.- */-export function stripCodeFences(raw) {- return raw.trim().replace(/^```(?:json)?\n?/, '').replace(/\n?```$/, '').trim();-}--/**- * Parse JSON from LLM output, stripping code fences first.- * Throws a descriptive error on parse failure.- */-export function parseLLMJSON(raw) {- const cleaned = stripCodeFences(raw);- try {- return JSON.parse(cleaned);- } catch (e) {- throw new Error(`Invalid JSON from AI: ${e.message}`);- }-}+// Extracted to lib/llmText.js in #4901 — unfencing a string needs no provider,+// and lib modules must be able to do it without importing this one. Re-exported+// here so the callers that have always imported them from aiProvider keep working.+export { stripCodeFences, parseLLMJSON } from '../lib/llmText.js';diff --git a/server/lib/aiProvider.test.js b/server/services/aiProvider.test.jssimilarity index 98%rename from server/lib/aiProvider.test.jsrename to server/services/aiProvider.test.jsindex 51809739d0..7cf4a2acd0 100644--- a/server/lib/aiProvider.test.js+++ b/server/services/aiProvider.test.js@@ -1,6 +1,6 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';import { stripCodeFences, parseLLMJSON, callProviderAISimple } from './aiProvider.js';-import { CREATIVE_LATITUDE_HEADING } from './creativeLatitude.js';+import { CREATIVE_LATITUDE_HEADING } from '../lib/creativeLatitude.js';// `statusOp` is hoisted with the mock factories so the ai:status spy is in scope// when vitest lifts vi.mock above the imports.diff --git a/server/services/autobiography.js b/server/services/autobiography.jsindex 5f96e3d50d..df0ecd0bdb 100644--- a/server/services/autobiography.js+++ b/server/services/autobiography.js@@ -13,7 +13,7 @@ import { atomicWrite, ensureDir, PATHS, readJSONFile } from '../lib/fileUtils.jsimport { recordTombstone } from '../lib/tombstones.js';import { addNotification, NOTIFICATION_TYPES, exists as notificationExists } from './notifications.js';import { getActiveProvider, getProviderById } from './providers.js';-import { callProviderAISimple, parseLLMJSON } from '../lib/aiProvider.js';+import { callProviderAISimple, parseLLMJSON } from './aiProvider.js';const DATA_DIR = join(PATHS.digitalTwin, 'autobiography');const STORIES_FILE = join(DATA_DIR, 'stories.json');diff --git a/server/services/autobiography.test.js b/server/services/autobiography.test.jsindex 5fb5c737fa..c9eb1db503 100644--- a/server/services/autobiography.test.js+++ b/server/services/autobiography.test.js@@ -36,7 +36,7 @@ vi.mock('./providers.js', () => ({}));const mockCallProviderAISimple = vi.fn();-vi.mock('../lib/aiProvider.js', () => ({+vi.mock('./aiProvider.js', () => ({callProviderAISimple: (...args) => mockCallProviderAISimple(...args),// Real-ish JSON extractor good enough for testsparseLLMJSON: (raw) => JSON.parse(raw)diff --git a/server/services/creativeDirector/sceneEvaluator.test.js b/server/services/creativeDirector/sceneEvaluator.test.jsindex 69a7553253..f0a3c22766 100644--- a/server/services/creativeDirector/sceneEvaluator.test.js+++ b/server/services/creativeDirector/sceneEvaluator.test.js@@ -27,7 +27,7 @@ const mocks = vi.hoisted(() => ({vi.mock('fs', () => ({ existsSync: mocks.existsSync }));vi.mock('../../lib/fileUtils.js', () => ({ PATHS: { videoThumbnails: '/data/video-thumbnails' } }));-vi.mock('../../lib/aiProvider.js', () => ({ stripCodeFences: (s) => String(s).replace(/```[a-z]*\n?/gi, '').replace(/```/g, '') }));+vi.mock('../aiProvider.js', () => ({ stripCodeFences: (s) => String(s).replace(/```[a-z]*\n?/gi, '').replace(/```/g, '') }));vi.mock('../../lib/promptRunner.js', () => ({runPromptThroughProvider: mocks.runPromptThroughProvider,assertVisionRunUsedImages: mocks.assertVisionRunUsedImages,diff --git a/server/services/goalCheckIn.js b/server/services/goalCheckIn.jsindex 9fab6a9acd..25f5def60a 100644--- a/server/services/goalCheckIn.js+++ b/server/services/goalCheckIn.js@@ -1,7 +1,7 @@import { join } from 'path';import { v4 as uuidv4 } from '../lib/uuid.js';import { atomicWrite, PATHS, readJSONFile, ensureDir } from '../lib/fileUtils.js';-import { callProviderAISimple, parseLLMJSON } from '../lib/aiProvider.js';+import { callProviderAISimple, parseLLMJSON } from './aiProvider.js';import { addNotification, NOTIFICATION_TYPES } from './notifications.js';const GOALS_FILE = join(PATHS.digitalTwin, 'goals.json');diff --git a/server/services/goalCheckIn.test.js b/server/services/goalCheckIn.test.jsindex c4ba2c4e65..13dd55fdb0 100644--- a/server/services/goalCheckIn.test.js+++ b/server/services/goalCheckIn.test.js@@ -33,7 +33,7 @@ vi.mock('../lib/fileUtils.js', async (importOriginal) =>const provider = { id: 'p1', defaultModel: 'test-model' };vi.mock('./providers.js', () => ({ getActiveProvider: vi.fn(async () => provider) }));-vi.mock('../lib/aiProvider.js', () => ({+vi.mock('./aiProvider.js', () => ({callProviderAISimple: vi.fn(async () => ({ text: '{"assessment":"ok","recommendations":["keep going"]}' })),parseLLMJSON: (text) => JSON.parse(text),}));diff --git a/server/services/identity.test.js b/server/services/identity.test.jsindex 9136c9f6a6..a3d5fb2c1a 100644--- a/server/services/identity.test.js+++ b/server/services/identity.test.js@@ -1437,7 +1437,7 @@ describe('Integration: organizeGoals', () => {}));// callProviderAISimple mock set per-test to use actual goal IDs- vi.doMock('../lib/aiProvider.js', () => ({+ vi.doMock('./aiProvider.js', () => ({callProviderAISimple: vi.fn(async () => ({ text: '{}' })),parseLLMJSON: vi.fn((text) => JSON.parse(text))}));@@ -1452,7 +1452,7 @@ describe('Integration: organizeGoals', () => {const goal2 = await createGoal({ title: 'Learn Spanish' });// Re-mock with actual goal IDs- const { callProviderAISimple, parseLLMJSON } = await import('../lib/aiProvider.js');+ const { callProviderAISimple, parseLLMJSON } = await import('./aiProvider.js');callProviderAISimple.mockResolvedValue({text: JSON.stringify({apexGoal: { existingId: null, suggestedTitle: 'Live fully', suggestedDescription: 'The ultimate purpose' },@@ -1504,7 +1504,7 @@ describe('Integration: organizeGoals', () => {getProviderById: vi.fn(async () => null)}));- vi.doMock('../lib/aiProvider.js', () => ({+ vi.doMock('./aiProvider.js', () => ({callProviderAISimple: vi.fn(),parseLLMJSON: vi.fn()}));diff --git a/server/services/identity/goals.js b/server/services/identity/goals.jsindex 3e0aa83f4f..32d58bfd86 100644--- a/server/services/identity/goals.js+++ b/server/services/identity/goals.js@@ -1,7 +1,7 @@import { v4 as uuidv4 } from '../../lib/uuid.js';import { ServerError } from '../../lib/errorHandler.js';import { getActivities } from '../meatspaceCalendar.js';-import { callProviderAISimple, parseLLMJSON } from '../../lib/aiProvider.js';+import { callProviderAISimple, parseLLMJSON } from '../aiProvider.js';import {goalTypeEnum,goalPhasesProposalSchema,diff --git a/server/services/identity/goals.test.js b/server/services/identity/goals.test.jsindex d0d3c946ea..561b4b62f2 100644--- a/server/services/identity/goals.test.js+++ b/server/services/identity/goals.test.js@@ -18,7 +18,7 @@ vi.mock('../providers.js', () => ({getProviderById: vi.fn(async () => ({ id: 'p1', apiType: 'openai', defaultModel: 'm1' }))}));-vi.mock('../../lib/aiProvider.js', async (importOriginal) => {+vi.mock('../aiProvider.js', async (importOriginal) => {const actual = await importOriginal();return { ...actual, callProviderAISimple: vi.fn(async () => ({ text: h.aiText })) };});diff --git a/server/services/insightsService.js b/server/services/insightsService.jsindex b479e420a4..01c43b409f 100644--- a/server/services/insightsService.js+++ b/server/services/insightsService.js@@ -19,7 +19,7 @@ import { MARKER_CATEGORIES, CURATED_MARKERS } from '../lib/curatedGenomeMarkers.import { getTasteProfile } from './taste-questionnaire.js';import { getActiveProvider, getProviderById } from './providers.js';import { getCorrelationData } from './appleHealthQuery.js';-import { stripCodeFences, parseLLMJSON } from '../lib/aiProvider.js';+import { stripCodeFences, parseLLMJSON } from './aiProvider.js';import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';import { readResponseJson } from '../lib/readResponseJson.js';import { ensureProviderReady as ensureOllamaProviderReady } from './ollamaManager.js';diff --git a/server/services/jiraReports.js b/server/services/jiraReports.jsindex e4f1b02da8..19456433b6 100644--- a/server/services/jiraReports.js+++ b/server/services/jiraReports.js@@ -8,7 +8,7 @@ import { join } from 'path';import { atomicWrite, ensureDir, PATHS, readJSONFile } from '../lib/fileUtils.js';import { getInstances, createJiraClient } from './jira.js';import { getActiveApps } from './apps.js';-import { callProviderAISimple } from '../lib/aiProvider.js';+import { callProviderAISimple } from './aiProvider.js';import { getActiveProvider, getAllProviders } from './providers.js';const REPORTS_DIR = join(PATHS.data, 'jira-reports');diff --git a/server/services/llamaServerManager.js b/server/services/llamaServerManager.jsindex 6ec8a1782f..682aa423ba 100644--- a/server/services/llamaServerManager.js+++ b/server/services/llamaServerManager.js@@ -24,7 +24,7 @@ import { execPm2, getAppStatusStrict, clearJlistCache, getSavedProcessNames } fr// `settings.js` is lazy-imported at its call sites below, never statically: it// eagerly resolves `fileUtils.PATHS` at module load, which drags PATHS into the// module graph of every consumer of this manager and breaks the many suites that-// partial-mock fileUtils without it. Same reason `lib/aiProvider.js` defers+// partial-mock fileUtils without it. Same reason `services/aiProvider.js` defers// `localModelHealing`.diff --git a/server/services/moodBoardStyleSynthesis.js b/server/services/moodBoardStyleSynthesis.jsindex 2b060ee046..d24f51bab8 100644--- a/server/services/moodBoardStyleSynthesis.js+++ b/server/services/moodBoardStyleSynthesis.js@@ -10,7 +10,7 @@* through the universe's queued-write adopt endpoint.*/-import { parseLLMJSON, resolveAPIProvider } from '../lib/aiProvider.js';+import { parseLLMJSON, resolveAPIProvider } from './aiProvider.js';import { ServerError } from '../lib/errorHandler.js';import { assertProvider, runPromptThroughProvider } from '../lib/promptRunner.js';import { trimTo } from '../lib/storyBible.js';diff --git a/server/services/moodBoardStyleSynthesis.test.js b/server/services/moodBoardStyleSynthesis.test.jsindex fa66e6b55b..6d30698ffd 100644--- a/server/services/moodBoardStyleSynthesis.test.js+++ b/server/services/moodBoardStyleSynthesis.test.js@@ -1,6 +1,6 @@import { beforeEach, describe, expect, it, vi } from 'vitest';-vi.mock('../lib/aiProvider.js', async (importActual) => {+vi.mock('./aiProvider.js', async (importActual) => {const actual = await importActual();return { ...actual, resolveAPIProvider: vi.fn() };});@@ -9,7 +9,7 @@ vi.mock('../lib/promptRunner.js', async (importActual) => {return { ...actual, runPromptThroughProvider: vi.fn() };});-const aiProvider = await import('../lib/aiProvider.js');+const aiProvider = await import('./aiProvider.js');const promptRunner = await import('../lib/promptRunner.js');const {collectBoardStyleContext,diff --git a/server/services/mtplxServerManager.js b/server/services/mtplxServerManager.jsindex 69cc835b02..6468f8055c 100644--- a/server/services/mtplxServerManager.js+++ b/server/services/mtplxServerManager.js@@ -33,7 +33,7 @@ import { createDaemonWatcher, pm2ArgValue, idleWindowMs, markDaemonUsed, registe// `settings.js` is lazy-imported at its call sites below, never statically: it// eagerly resolves `fileUtils.PATHS` at module load, which drags PATHS into the// module graph of every consumer of this manager and breaks the many suites that-// partial-mock fileUtils without it. Same reason `lib/aiProvider.js` defers+// partial-mock fileUtils without it. Same reason `services/aiProvider.js` defers// `localModelHealing`.import { isAppleSilicon, isPortInUse } from '../lib/platform.js';@@ -835,7 +835,7 @@ export async function ensureMtplxRunning() {/*** Is this provider served by the MTPLX daemon PortOS manages?*- * Mirrors `ollamaManager.isOllamaProvider` so `lib/aiProvider.js` gates both+ * Mirrors `ollamaManager.isOllamaProvider` so `services/aiProvider.js` gates both* local daemons the same way. Only a LOCAL endpoint counts: an MTPLX on a* tailnet peer is someone else's process, and neither starting nor idle-stopping* it is this install's business.@@ -857,7 +857,7 @@ export function isMtplxProvider(provider) {}/**- * The `ensureProviderReady` shape `lib/aiProvider.js` expects, for MTPLX.+ * The `ensureProviderReady` shape `services/aiProvider.js` expects, for MTPLX.** This is the one call site that both refreshes the idle clock and lazily* restarts — deliberately on the INFERENCE path rather than indiff --git a/server/services/taste-questionnaire.js b/server/services/taste-questionnaire.jsindex 5b1f7a448a..1cd0fc0513 100644--- a/server/services/taste-questionnaire.js+++ b/server/services/taste-questionnaire.js@@ -11,7 +11,7 @@ import { existsSync } from 'fs';import { join } from 'path';import { v4 as uuidv4 } from '../lib/uuid.js';import { atomicWrite, ensureDir, safeJSONParse, PATHS } from '../lib/fileUtils.js';-import { resolveAPIProvider, callProviderAISimple } from '../lib/aiProvider.js';+import { resolveAPIProvider, callProviderAISimple } from './aiProvider.js';import { ServerError } from '../lib/errorHandler.js';import { buildPrompt } from './promptService.js';import { digitalTwinEvents } from './digital-twin.js';diff --git a/server/services/taste-questionnaire.test.js b/server/services/taste-questionnaire.test.jsindex b2dd9e85a1..dc8a4e829a 100644--- a/server/services/taste-questionnaire.test.js+++ b/server/services/taste-questionnaire.test.js@@ -19,7 +19,7 @@ vi.mock('./digital-twin.js', () => ({// Drive the provider boundary directly so each "Go deeper" outcome is reachable// without a live LLM. Re-imported per test because beforeEach resets the module// registry, which mints fresh spies for each generation.-vi.mock('../lib/aiProvider.js', () => ({+vi.mock('./aiProvider.js', () => ({resolveAPIProvider: vi.fn(),callProviderAISimple: vi.fn(),}));@@ -140,7 +140,7 @@ describe('generatePersonalizedTasteQuestion outcomes', () => {});it('reports no-provider rather than blaming the user documents that do exist', async () => {- const { resolveAPIProvider } = await import('../lib/aiProvider.js');+ const { resolveAPIProvider } = await import('./aiProvider.js');resolveAPIProvider.mockResolvedValue(null);const taste = await import('./taste-questionnaire.js');await seedIdentityContext(taste);@@ -152,7 +152,7 @@ describe('generatePersonalizedTasteQuestion outcomes', () => {});it('throws AI_PROVIDER_ERROR instead of collapsing a provider failure into "nothing to ask"', async () => {- const { resolveAPIProvider, callProviderAISimple } = await import('../lib/aiProvider.js');+ const { resolveAPIProvider, callProviderAISimple } = await import('./aiProvider.js');resolveAPIProvider.mockResolvedValue(PROVIDER);callProviderAISimple.mockResolvedValue({ error: 'Provider returned 401: invalid key' });const taste = await import('./taste-questionnaire.js');@@ -173,7 +173,7 @@ describe('generatePersonalizedTasteQuestion outcomes', () => {});it('returns the question with reason null on success', async () => {- const { resolveAPIProvider, callProviderAISimple } = await import('../lib/aiProvider.js');+ const { resolveAPIProvider, callProviderAISimple } = await import('./aiProvider.js');resolveAPIProvider.mockResolvedValue(PROVIDER);callProviderAISimple.mockResolvedValue({ text: ' Which film would you rewatch forever? ' });const taste = await import('./taste-questionnaire.js');diff --git a/server/services/universeBuilderRefine.image.test.js b/server/services/universeBuilderRefine.image.test.jsindex 9124a19185..945b6e46f0 100644--- a/server/services/universeBuilderRefine.image.test.js+++ b/server/services/universeBuilderRefine.image.test.js@@ -2,7 +2,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';// Style-reference-image refine path: forces a vision API provider, passes the// resolved image path as a screenshot, and rejects a non-API fallback.-vi.mock('../lib/aiProvider.js', async (importActual) => {+vi.mock('./aiProvider.js', async (importActual) => {const actual = await importActual();return { ...actual, resolveAPIProvider: vi.fn() };});@@ -15,7 +15,7 @@ vi.mock('../lib/promptRunner.js', async (importActual) => {};});-const aiProvider = await import('../lib/aiProvider.js');+const aiProvider = await import('./aiProvider.js');const promptRunner = await import('../lib/promptRunner.js');const { refineWorldPrompts } = await import('./universeBuilderRefine.js');diff --git a/server/services/universeBuilderRefine.js b/server/services/universeBuilderRefine.jsindex 4ab8d4ab0c..7f18c5171c 100644--- a/server/services/universeBuilderRefine.js+++ b/server/services/universeBuilderRefine.js@@ -14,7 +14,7 @@import { ServerError } from "../lib/errorHandler.js";import { findBalancedBlocks, tryParseWithRepair } from "../lib/jsonExtract.js";import { assertProvider, resolveProviderAndModel, resolveEffectiveModel, runPromptThroughProvider, assertVisionRunUsedImages } from "../lib/promptRunner.js";-import { resolveAPIProvider } from "../lib/aiProvider.js";+import { resolveAPIProvider } from './aiProvider.js';import {renderCategoriesForPrompt as renderCategoriesShared,renderCompositesForPrompt as renderCompositesShared,diff --git a/server/services/universeStyleReference.js b/server/services/universeStyleReference.jsindex 1b92384e8f..5d159c1fd9 100644--- a/server/services/universeStyleReference.js+++ b/server/services/universeStyleReference.js@@ -7,7 +7,7 @@*/import { randomUUID } from 'crypto';-import { parseLLMJSON, resolveAPIProvider } from '../lib/aiProvider.js';+import { parseLLMJSON, resolveAPIProvider } from './aiProvider.js';import { ServerError } from '../lib/errorHandler.js';import { assertProvider, assertVisionRunUsedImages, runPromptThroughProvider } from '../lib/promptRunner.js';import { trimTo } from '../lib/storyBible.js';diff --git a/server/services/universeStyleReference.test.js b/server/services/universeStyleReference.test.jsindex 470679c210..bfd7f900cf 100644--- a/server/services/universeStyleReference.test.js+++ b/server/services/universeStyleReference.test.js@@ -1,6 +1,6 @@import { beforeEach, describe, expect, it, vi } from 'vitest';-vi.mock('../lib/aiProvider.js', async (importActual) => {+vi.mock('./aiProvider.js', async (importActual) => {const actual = await importActual();return { ...actual, resolveAPIProvider: vi.fn() };});@@ -9,7 +9,7 @@ vi.mock('../lib/promptRunner.js', async (importActual) => {return { ...actual, runPromptThroughProvider: vi.fn() };});-const aiProvider = await import('../lib/aiProvider.js');+const aiProvider = await import('./aiProvider.js');const promptRunner = await import('../lib/promptRunner.js');const {analyzeUniverseStyleReference,diff --git a/server/services/universeVisionDescribe.js b/server/services/universeVisionDescribe.jsindex f2141ee279..a73d22b1f0 100644--- a/server/services/universeVisionDescribe.js+++ b/server/services/universeVisionDescribe.js@@ -18,7 +18,7 @@* description from nothing.*/-import { resolveAPIProvider, stripCodeFences } from '../lib/aiProvider.js';+import { resolveAPIProvider, stripCodeFences } from './aiProvider.js';import { runPromptThroughProvider, assertProvider, assertVisionRunUsedImages } from '../lib/promptRunner.js';import { ServerError } from '../lib/errorHandler.js';import { getUniverse } from './universeBuilder.js';diff --git a/server/services/universeVisionDescribe.test.js b/server/services/universeVisionDescribe.test.jsindex a3e7019f6b..1c49eecad7 100644--- a/server/services/universeVisionDescribe.test.js+++ b/server/services/universeVisionDescribe.test.js@@ -2,7 +2,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';// resolveAPIProvider drives provider selection; stripCodeFences is real (re-// exported through the partial mock so the cleanup of the runner's text works).-vi.mock('../lib/aiProvider.js', async (importActual) => {+vi.mock('./aiProvider.js', async (importActual) => {const actual = await importActual();return { ...actual, resolveAPIProvider: vi.fn() };});@@ -21,7 +21,7 @@ vi.mock('./universeBuilder.js', async (importActual) => {return { ...actual, getUniverse: vi.fn() };});-const aiProvider = await import('../lib/aiProvider.js');+const aiProvider = await import('./aiProvider.js');const promptRunner = await import('../lib/promptRunner.js');const universeBuilder = await import('./universeBuilder.js');const {diff --git a/server/services/universeVisionExpand.js b/server/services/universeVisionExpand.jsindex e4ba138c79..e10ee6b30d 100644--- a/server/services/universeVisionExpand.js+++ b/server/services/universeVisionExpand.js@@ -30,7 +30,7 @@import { getUniverse } from './universeBuilder.js';import { applyExpansion, STRING_FIELDS, LIST_FIELDS } from './universeCharacterExpand.js';import { bibleFieldIsBlank } from '../lib/universeBibleCompleteness.js';-import { resolveAPIProvider, parseLLMJSON } from '../lib/aiProvider.js';+import { resolveAPIProvider, parseLLMJSON } from './aiProvider.js';import { runPromptThroughProvider, assertProvider, assertVisionRunUsedImages } from '../lib/promptRunner.js';import { ServerError } from '../lib/errorHandler.js';import { shortId } from '../lib/fileUtils.js';diff --git a/server/services/universeVisionExpand.test.js b/server/services/universeVisionExpand.test.jsindex c20daae1af..b0550d2297 100644--- a/server/services/universeVisionExpand.test.js+++ b/server/services/universeVisionExpand.test.js@@ -2,7 +2,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';// resolveAPIProvider drives provider selection; parseLLMJSON stays real so the// JSON-parse + fence-strip path is exercised end to end.-vi.mock('../lib/aiProvider.js', async (importActual) => {+vi.mock('./aiProvider.js', async (importActual) => {const actual = await importActual();return { ...actual, resolveAPIProvider: vi.fn() };});@@ -21,7 +21,7 @@ vi.mock('./universeBuilder.js', async (importActual) => {return { ...actual, getUniverse: vi.fn() };});-const aiProvider = await import('../lib/aiProvider.js');+const aiProvider = await import('./aiProvider.js');const promptRunner = await import('../lib/promptRunner.js');const universeBuilder = await import('./universeBuilder.js');const {diff --git a/server/services/writersRoom/evaluator.js b/server/services/writersRoom/evaluator.jsindex cfbb32b53a..9280640a1d 100644--- a/server/services/writersRoom/evaluator.js+++ b/server/services/writersRoom/evaluator.js@@ -8,7 +8,7 @@ import { join } from 'path';import { readFile, readdir, rm } from 'fs/promises';import { PATHS, atomicWrite, ensureDir, safeJSONParse, tryReadFile } from '../../lib/fileUtils.js';import { ServerError } from '../../lib/errorHandler.js';-import { stripCodeFences } from '../../lib/aiProvider.js';+import { stripCodeFences } from '../aiProvider.js';import { runStagedLLM } from '../../lib/stageRunner.js';import { extractBible } from '../../lib/bibleExtractor.js';import { extractScenes, SOURCE_KIND } from '../../lib/sceneExtractor.js';diff --git a/server/services/writersRoom/evaluator.test.js b/server/services/writersRoom/evaluator.test.jsindex 8e27814852..e4e0feb86a 100644--- a/server/services/writersRoom/evaluator.test.js+++ b/server/services/writersRoom/evaluator.test.js@@ -4,7 +4,7 @@ import { describe, it, expect, vi } from 'vitest';// heavy siblings so this unit test can import it cheaply — it only exercises the// pure KIND_META map + the `cuts`/`revise` SHAPERS, which depend on nothing but// stripCodeFences (aiProvider) and CUT_TYPES (cutApplier, real).-vi.mock('../../lib/aiProvider.js', () => ({ stripCodeFences: (s) => String(s ?? '') }));+vi.mock('../aiProvider.js', () => ({ stripCodeFences: (s) => String(s ?? '') }));vi.mock('../../lib/stageRunner.js', () => ({ runStagedLLM: vi.fn() }));vi.mock('../../lib/bibleExtractor.js', () => ({ extractBible: vi.fn() }));vi.mock('../../lib/sceneExtractor.js', () => ({ extractScenes: vi.fn(), SOURCE_KIND: { PROSE: 'prose' } }));