Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

Add AI assignment inventory settings

[._.]/ Adam Eivyfcc1184cc184
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index fb813ce856..24eb6cb617 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,7 @@
## Added
+- **[ai-assignment-inventory] Settings now has an AI Assignments admin page.** It inventories provider/model pins across the provider registry, embeddings, Voice, Messages, Brain, Universes, Story Builder, Pipeline series, CoS schedules, Loops, Feature Agents, and social agents, with per-row edits plus a bulk provider migration control.
- **[manuscript-multi-edit-fixes] Manuscript "Finish the draft" fixes can now propose and apply multiple anchored edits at once.** The manuscript-fix LLM contract moved from a single `{ find, replace }` to `{ edits: [{ issueNumber, find, replace, note }] }`, so a broad or unanchored editorial comment can generate several concrete insertions — across multiple issue sections when needed — instead of falling back to manual editing. The editor's comment card renders each suggestion as an inline diff with a per-edit checkbox and editable replacement, and accept applies the selected edits atomically through a new serialized batch write (`updateStagesWithLatest`) that snapshots prior text into runHistory and re-checks each anchor inside the per-series write lock. The prompt template embeds manuscript/premise/anchor content in distinct (non-backtick) fences with an explicit "treat as quoted source" guard; migration `060-manuscript-multi-edit-fix-prompt.js` auto-upgrades the prior single-edit prompt on existing installs. Backward compatible: legacy single-edit `{ find, replace }` accepts still resolve to one target.
## Changed
diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsx
index 6e419153cd..d3065165f6 100644
--- a/client/src/components/Layout.jsx
+++ b/client/src/components/Layout.jsx
@@ -283,6 +283,7 @@ const navItems = [
icon: Settings,
defaultTo: '/settings/general',
children: [
+ { to: '/settings/ai-assignments', label: 'AI Assignments', icon: Bot },
{ to: '/settings/backup', label: 'Backup', icon: Download },
{ to: '/settings/database', label: 'Database', icon: Database },
{ to: '/settings/general', label: 'General', icon: Settings },
diff --git a/client/src/components/settings/AiAssignmentsTab.jsx b/client/src/components/settings/AiAssignmentsTab.jsx
new file mode 100644
index 0000000000..11fce6efd2
--- /dev/null
+++ b/client/src/components/settings/AiAssignmentsTab.jsx
@@ -0,0 +1,329 @@
+import { useCallback, useEffect, useMemo, useState } from 'react';
+import { ArrowRight, Bot, RefreshCw, Save, Search } from 'lucide-react';
+import toast from '../ui/Toast';
+import { getAiAssignments, updateAiAssignment } from '../../services/api';
+
+const getDraft = (entry) => ({
+ providerId: entry.providerId || '',
+ model: entry.model || '',
+});
+
+const sameDraft = (entry, draft) =>
+ (entry.providerId || '') === (draft?.providerId || '') &&
+ (entry.model || '') === (draft?.model || '');
+
+const providerName = (providers, id) =>
+ providers.find((p) => p.id === id)?.name || id || 'Default';
+
+const modelOptionsFor = (entry, providers, draftProviderId) => {
+ if (Array.isArray(entry.modelOptions)) return entry.modelOptions;
+ const provider = providers.find((p) => p.id === draftProviderId);
+ return provider?.models || [];
+};
+
+const providerOptionsFor = (entry, providers) => {
+ if (Array.isArray(entry.providerOptions)) return entry.providerOptions;
+ const types = Array.isArray(entry.providerTypes) && entry.providerTypes.length
+ ? new Set(entry.providerTypes)
+ : null;
+ return providers
+ .filter((p) => !types || types.has(p.type))
+ .map((p) => ({ id: p.id, name: `${p.name}${p.enabled ? '' : ' (disabled)'}` }));
+};
+
+export default function AiAssignmentsTab() {
+ const [loading, setLoading] = useState(true);
+ const [saving, setSaving] = useState({});
+ const [data, setData] = useState({ providers: [], assignments: [] });
+ const [drafts, setDrafts] = useState({});
+ const [query, setQuery] = useState('');
+ const [area, setArea] = useState('all');
+ const [scope, setScope] = useState('all');
+ const [fromProvider, setFromProvider] = useState('');
+ const [toProvider, setToProvider] = useState('');
+ const [bulkSaving, setBulkSaving] = useState(false);
+
+ const load = useCallback(async () => {
+ setLoading(true);
+ const next = await getAiAssignments({ silent: true }).catch((err) => {
+ toast.error(`Failed to load AI assignments: ${err.message}`);
+ return null;
+ });
+ if (next) {
+ setData(next);
+ setDrafts(Object.fromEntries((next.assignments || []).map((entry) => [entry.id, getDraft(entry)])));
+ }
+ setLoading(false);
+ }, []);
+
+ useEffect(() => { load(); }, [load]);
+
+ const areas = useMemo(
+ () => ['all', ...Array.from(new Set((data.assignments || []).map((entry) => entry.area))).sort()],
+ [data.assignments]
+ );
+
+ const filtered = useMemo(() => {
+ const q = query.trim().toLowerCase();
+ return (data.assignments || []).filter((entry) => {
+ if (area !== 'all' && entry.area !== area) return false;
+ if (scope !== 'all' && entry.scope !== scope) return false;
+ if (!q) return true;
+ return [
+ entry.area,
+ entry.label,
+ entry.source,
+ entry.providerId,
+ entry.model,
+ entry.notes,
+ ].some((value) => String(value || '').toLowerCase().includes(q));
+ });
+ }, [area, data.assignments, query, scope]);
+
+ const providerCounts = useMemo(() => {
+ const counts = {};
+ for (const entry of data.assignments || []) {
+ if (!entry.providerId) continue;
+ const id = entry.providerId;
+ counts[id] = (counts[id] || 0) + 1;
+ }
+ return counts;
+ }, [data.assignments]);
+
+ const setDraft = (id, patch) => {
+ setDrafts((prev) => ({ ...prev, [id]: { ...(prev[id] || {}), ...patch } }));
+ };
+
+ const saveEntry = async (entry) => {
+ const draft = drafts[entry.id] || getDraft(entry);
+ setSaving((prev) => ({ ...prev, [entry.id]: true }));
+ const next = await updateAiAssignment(entry.id, {
+ providerId: draft.providerId || null,
+ model: draft.model || null,
+ }, { silent: true }).catch((err) => {
+ toast.error(`Save failed: ${err.message}`);
+ return null;
+ });
+ setSaving((prev) => ({ ...prev, [entry.id]: false }));
+ if (!next) return;
+ setData(next);
+ setDrafts(Object.fromEntries((next.assignments || []).map((item) => [item.id, getDraft(item)])));
+ toast.success('AI assignment saved');
+ };
+
+ const runBulkMigration = async () => {
+ if (!fromProvider || !toProvider || fromProvider === toProvider || bulkSaving) return;
+ const targets = (data.assignments || []).filter((entry) => (
+ entry.editable !== false &&
+ entry.providerEditable !== false &&
+ (drafts[entry.id]?.providerId || entry.providerId || '') === fromProvider &&
+ providerOptionsFor(entry, data.providers).some((option) => option.id === toProvider)
+ ));
+ if (targets.length === 0) {
+ toast.error('No editable assignments match that provider');
+ return;
+ }
+ setBulkSaving(true);
+ let latest = data;
+ const targetDefaultModel = data.providers.find((p) => p.id === toProvider)?.defaultModel || '';
+ for (const entry of targets) {
+ const nextModel = entry.modelEditable === false ? (drafts[entry.id]?.model || '') : targetDefaultModel;
+ const next = await updateAiAssignment(entry.id, {
+ providerId: toProvider,
+ model: nextModel || null,
+ }, { silent: true }).catch((err) => {
+ toast.error(`${entry.label}: ${err.message}`);
+ return null;
+ });
+ if (next) latest = next;
+ }
+ setData(latest);
+ setDrafts(Object.fromEntries((latest.assignments || []).map((item) => [item.id, getDraft(item)])));
+ setBulkSaving(false);
+ toast.success(`Migrated ${targets.length} assignment${targets.length === 1 ? '' : 's'}`);
+ };
+
+ if (loading) {
+ return <div className="text-sm text-gray-400">Loading AI assignments...</div>;
+ }
+
+ return (
+ <div className="space-y-5">
+ <div className="flex flex-col xl:flex-row xl:items-start xl:justify-between gap-4">
+ <div>
+ <div className="flex items-center gap-2 text-gray-200">
+ <Bot size={18} className="text-port-accent" />
+ <h2 className="text-lg font-semibold">AI Assignments</h2>
+ </div>
+ <div className="mt-2 flex flex-wrap gap-2 text-xs">
+ {Object.entries(providerCounts).sort((a, b) => b[1] - a[1]).map(([id, count]) => (
+ <span key={id} className="px-2 py-1 rounded bg-port-card border border-port-border text-gray-300">
+ {providerName(data.providers, id)}: {count}
+ </span>
+ ))}
+ </div>
+ </div>
+
+ <div className="bg-port-card border border-port-border rounded-lg p-3 space-y-2 min-w-full xl:min-w-[420px] xl:max-w-[520px]">
+ <div className="flex flex-col sm:flex-row gap-2">
+ <select
+ value={fromProvider}
+ onChange={(e) => setFromProvider(e.target.value)}
+ className="flex-1 bg-port-bg border border-port-border rounded px-2 py-2 text-sm text-white"
+ >
+ <option value="">From provider</option>
+ {data.providers.map((p) => <option key={p.id} value={p.id}>{p.name}</option>)}
+ </select>
+ <div className="hidden sm:flex items-center text-gray-500">
+ <ArrowRight size={16} />
+ </div>
+ <select
+ value={toProvider}
+ onChange={(e) => setToProvider(e.target.value)}
+ className="flex-1 bg-port-bg border border-port-border rounded px-2 py-2 text-sm text-white"
+ >
+ <option value="">To provider</option>
+ {data.providers.map((p) => <option key={p.id} value={p.id}>{p.name}</option>)}
+ </select>
+ <button
+ type="button"
+ onClick={runBulkMigration}
+ disabled={!fromProvider || !toProvider || fromProvider === toProvider || bulkSaving}
+ className="px-3 py-2 bg-port-accent hover:bg-port-accent/80 disabled:opacity-50 text-white rounded text-sm"
+ >
+ {bulkSaving ? 'Migrating...' : 'Migrate'}
+ </button>
+ </div>
+ <p className="text-xs text-gray-500">
+ Bulk migration updates editable rows that currently use the source provider and resets their model to the target default.
+ </p>
+ </div>
+ </div>
+
+ <div className="flex flex-col lg:flex-row gap-2">
+ <div className="relative flex-1">
+ <Search size={15} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500" />
+ <input
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ placeholder="Search assignments"
+ className="w-full bg-port-bg border border-port-border rounded pl-9 pr-3 py-2 text-sm text-white"
+ />
+ </div>
+ <select value={area} onChange={(e) => setArea(e.target.value)} className="bg-port-bg border border-port-border rounded px-3 py-2 text-sm text-white">
+ {areas.map((a) => <option key={a} value={a}>{a === 'all' ? 'All areas' : a}</option>)}
+ </select>
+ <select value={scope} onChange={(e) => setScope(e.target.value)} className="bg-port-bg border border-port-border rounded px-3 py-2 text-sm text-white">
+ <option value="all">All scopes</option>
+ <option value="global">Global</option>
+ <option value="record">Record pins</option>
+ <option value="runtime">Runtime call sites</option>
+ </select>
+ <button type="button" onClick={load} className="flex items-center justify-center gap-1.5 px-3 py-2 bg-port-border hover:bg-port-border/80 text-sm text-white rounded">
+ <RefreshCw size={14} />
+ Refresh
+ </button>
+ </div>
+
+ <div className="overflow-x-auto border border-port-border rounded-lg">
+ <table className="min-w-full divide-y divide-port-border">
+ <thead className="bg-port-card">
+ <tr className="text-left text-xs uppercase tracking-wide text-gray-500">
+ <th className="px-3 py-2 font-medium">Area</th>
+ <th className="px-3 py-2 font-medium min-w-[220px]">Assignment</th>
+ <th className="px-3 py-2 font-medium min-w-[210px]">Provider</th>
+ <th className="px-3 py-2 font-medium min-w-[220px]">Model</th>
+ <th className="px-3 py-2 font-medium min-w-[160px]">Source</th>
+ <th className="px-3 py-2 font-medium w-[90px]"></th>
+ </tr>
+ </thead>
+ <tbody className="divide-y divide-port-border bg-port-bg">
+ {filtered.map((entry) => {
+ const draft = drafts[entry.id] || getDraft(entry);
+ const providerOptions = providerOptionsFor(entry, data.providers);
+ const modelOptions = modelOptionsFor(entry, data.providers, draft.providerId);
+ const dirty = !sameDraft(entry, draft);
+ return (
+ <tr key={entry.id} className="align-top">
+ <td className="px-3 py-3 text-sm text-gray-300 whitespace-nowrap">
+ <div>{entry.area}</div>
+ <div className="mt-1 text-xs text-gray-600">{entry.scope}</div>
+ </td>
+ <td className="px-3 py-3">
+ <div className="text-sm text-white">{entry.label}</div>
+ {entry.notes && <div className="mt-1 text-xs text-gray-500">{entry.notes}</div>}
+ </td>
+ <td className="px-3 py-3">
+ {entry.providerEditable === false ? (
+ <div className="text-sm text-gray-300 py-2">{providerName(data.providers, draft.providerId)}</div>
+ ) : (
+ <select
+ value={draft.providerId}
+ onChange={(e) => {
+ const nextProviderId = e.target.value;
+ const nextDefault = data.providers.find((p) => p.id === nextProviderId)?.defaultModel || '';
+ setDraft(entry.id, { providerId: nextProviderId, model: entry.modelEditable === false ? draft.model : nextDefault });
+ }}
+ className="w-full bg-port-card border border-port-border rounded px-2 py-2 text-sm text-white"
+ >
+ <option value="">Default / unset</option>
+ {providerOptions.map((p) => <option key={p.id} value={p.id}>{p.name}</option>)}
+ </select>
+ )}
+ </td>
+ <td className="px-3 py-3">
+ {entry.modelEditable === false ? (
+ <div className="text-sm text-gray-300 py-2">{draft.model || 'Default'}</div>
+ ) : modelOptions.length > 0 ? (
+ <select
+ value={draft.model}
+ onChange={(e) => setDraft(entry.id, { model: e.target.value })}
+ className="w-full bg-port-card border border-port-border rounded px-2 py-2 text-sm text-white"
+ >
+ <option value="">Default / auto</option>
+ {modelOptions.map((m) => <option key={m} value={m}>{m}</option>)}
+ </select>
+ ) : (
+ <input
+ value={draft.model}
+ onChange={(e) => setDraft(entry.id, { model: e.target.value })}
+ placeholder="Default / auto"
+ className="w-full bg-port-card border border-port-border rounded px-2 py-2 text-sm text-white placeholder-gray-600"
+ />
+ )}
+ </td>
+ <td className="px-3 py-3 text-xs text-gray-500">
+ <div className="break-all">{entry.source}</div>
+ {entry.link && (
+ <a href={entry.link} className="inline-block mt-1 text-port-accent hover:underline">Open</a>
+ )}
+ </td>
+ <td className="px-3 py-3 text-right">
+ {entry.editable === false ? (
+ <span className="text-xs text-gray-600">Read only</span>
+ ) : (
+ <button
+ type="button"
+ onClick={() => saveEntry(entry)}
+ disabled={!dirty || saving[entry.id]}
+ className="inline-flex items-center gap-1.5 px-2.5 py-1.5 bg-port-accent hover:bg-port-accent/80 disabled:opacity-50 text-white rounded text-xs"
+ >
+ <Save size={12} />
+ {saving[entry.id] ? 'Saving' : 'Save'}
+ </button>
+ )}
+ </td>
+ </tr>
+ );
+ })}
+ {filtered.length === 0 && (
+ <tr>
+ <td colSpan="6" className="px-3 py-8 text-center text-sm text-gray-500">No assignments match the current filters.</td>
+ </tr>
+ )}
+ </tbody>
+ </table>
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/components/settings/SettingsTabsHeader.jsx b/client/src/components/settings/SettingsTabsHeader.jsx
index 0c2b57e086..675044614e 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: 'ai-assignments', label: 'AI Assignments', to: '/settings/ai-assignments' },
{ id: 'autofixer', label: 'Autofixer', to: '/settings/autofixer' },
{ id: 'backup', label: 'Backup', to: '/settings/backup' },
{ id: 'catalog', label: 'Catalog', to: '/settings/catalog' },
diff --git a/client/src/pages/Settings.jsx b/client/src/pages/Settings.jsx
index b1f4c7b047..4f9ee1564e 100644
--- a/client/src/pages/Settings.jsx
+++ b/client/src/pages/Settings.jsx
@@ -1,5 +1,6 @@
import { useParams, Navigate } from 'react-router-dom';
import { AutofixerTab } from '../components/settings/AutofixerTab';
+import AiAssignmentsTab from '../components/settings/AiAssignmentsTab';
import { BackupTab } from '../components/settings/BackupTab';
import { CatalogTypesTab } from '../components/settings/CatalogTypesTab';
import { DatabaseTab } from '../components/settings/DatabaseTab';
@@ -30,6 +31,7 @@ export default function Settings() {
const renderTabContent = () => {
switch (activeTab) {
case 'general': return <GeneralTab />;
+ case 'ai-assignments': return <AiAssignmentsTab />;
case 'autofixer': return <AutofixerTab />;
case 'backup': return <BackupTab />;
case 'catalog': return <CatalogTypesTab />;
diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.js
index aa499b7ed1..ff2b2f45eb 100644
--- a/client/src/services/apiSystem.js
+++ b/client/src/services/apiSystem.js
@@ -38,6 +38,12 @@ export const updateSettings = (data, options) => request('/settings', {
body: JSON.stringify(data),
...options
});
+export const getAiAssignments = (options) => request('/settings/ai-assignments', options);
+export const updateAiAssignment = (id, data, options) => request(`/settings/ai-assignments/${encodeURIComponent(id)}`, {
+ method: 'PUT',
+ body: JSON.stringify(data),
+ ...options
+});
const isPlainObject = (v) =>
v != null && typeof v === 'object' && !Array.isArray(v);
diff --git a/server/routes/settings.js b/server/routes/settings.js
index f7c88a29de..aad726d5a9 100644
--- a/server/routes/settings.js
+++ b/server/routes/settings.js
@@ -1,5 +1,7 @@
import { Router } from 'express';
+import { z } from 'zod';
import { getSettings, updateSettings } from '../services/settings.js';
+import { getAiAssignments, updateAiAssignment } from '../services/aiAssignments.js';
import {
setCodexParallelLimit,
CODEX_PARALLEL_MIN,
@@ -12,6 +14,11 @@ import { catalogUserTypesSettingsSchema } from '../lib/catalogValidation.js';
const router = Router();
+const aiAssignmentUpdateSchema = z.object({
+ providerId: z.string().trim().max(128).nullable().optional(),
+ model: z.string().trim().max(300).nullable().optional(),
+}).strict();
+
// Server-authoritative bounds the client UI can render directly so the form
// clamp never drifts away from what the queue actually enforces. Stitched
// under `imageGen.codex.parallelLimitBounds` since that's where the field
@@ -38,6 +45,17 @@ router.get('/', asyncHandler(async (req, res) => {
res.json(decorateBounds(safe));
}));
+// GET /api/settings/ai-assignments
+router.get('/ai-assignments', asyncHandler(async (_req, res) => {
+ res.json(await getAiAssignments());
+}));
+
+// PUT /api/settings/ai-assignments/:id
+router.put('/ai-assignments/:id', asyncHandler(async (req, res) => {
+ const payload = validateRequest(aiAssignmentUpdateSchema, req.body || {});
+ res.json(await updateAiAssignment(req.params.id, payload));
+}));
+
// PUT /api/settings
router.put('/', asyncHandler(async (req, res) => {
// Settings is a polymorphic store but the backup sub-object has a known
diff --git a/server/services/aiAssignments.js b/server/services/aiAssignments.js
new file mode 100644
index 0000000000..fa15da34ea
--- /dev/null
+++ b/server/services/aiAssignments.js
@@ -0,0 +1,566 @@
+import { getSettings, updateSettings } from './settings.js';
+import { getAllProviders, getProviderById, setActiveProvider, updateProvider } from './providers.js';
+import * as brainService from './brain.js';
+import * as universeService from './universeBuilder.js';
+import * as storyBuilderService from './storyBuilder.js';
+import * as pipelineSeriesService from './pipeline/series.js';
+import * as taskScheduleService from './taskSchedule.js';
+import * as loopsService from './loops.js';
+import * as featureAgentsService from './featureAgents.js';
+import * as agentPersonalitiesService from './agentPersonalities.js';
+import { getVoiceConfig, updateVoiceConfig } from './voice/config.js';
+import { isPlainObject } from '../lib/objects.js';
+
+const textProviderTypes = ['api', 'cli', 'tui'];
+const cliProviderTypes = ['cli', 'tui'];
+const apiProviderTypes = ['api'];
+const embeddingProviders = [
+ { id: 'none', name: 'Disabled' },
+ { id: 'ollama', name: 'Ollama' },
+ { id: 'lmstudio', name: 'LM Studio' },
+];
+
+const asNullable = (value) => {
+ if (value == null) return null;
+ const trimmed = String(value).trim();
+ return trimmed || null;
+};
+
+const pickModelOptions = (provider) => {
+ const raw = Array.isArray(provider?.models) ? provider.models : [];
+ const ids = raw.map((m) => (typeof m === 'string' ? m : m?.id)).filter(Boolean);
+ if (provider?.defaultModel && !ids.includes(provider.defaultModel)) ids.unshift(provider.defaultModel);
+ return ids;
+};
+
+const makeEntry = ({
+ id,
+ area,
+ label,
+ source,
+ providerId = null,
+ model = null,
+ scope = 'global',
+ editable = true,
+ providerEditable = true,
+ modelEditable = true,
+ providerTypes = textProviderTypes,
+ providerOptions = null,
+ modelOptions = null,
+ link = null,
+ notes = '',
+}) => ({
+ id,
+ area,
+ label,
+ source,
+ providerId: providerId || null,
+ model: model || null,
+ scope,
+ editable,
+ providerEditable,
+ modelEditable,
+ providerTypes,
+ providerOptions,
+ modelOptions,
+ link,
+ notes,
+});
+
+const patchSettingsPath = async (path, value) => {
+ const settings = await getSettings();
+ const segments = path.split('.');
+ const top = segments[0];
+ const root = isPlainObject(settings[top]) ? { ...settings[top] } : {};
+ let cur = root;
+ for (const segment of segments.slice(1, -1)) {
+ cur[segment] = isPlainObject(cur[segment]) ? { ...cur[segment] } : {};
+ cur = cur[segment];
+ }
+ cur[segments[segments.length - 1]] = value;
+ await updateSettings({ [top]: root });
+};
+
+const addProviderRegistryEntries = (entries, providersData) => {
+ const { activeProvider, providers = [] } = providersData;
+ entries.push(makeEntry({
+ id: 'provider.active',
+ area: 'Provider Registry',
+ label: 'System default provider',
+ source: 'data/providers.json activeProvider',
+ providerId: activeProvider,
+ modelEditable: false,
+ notes: 'Fallback for tools that do not pin their own provider.',
+ }));
+
+ for (const provider of providers) {
+ for (const field of ['defaultModel', 'lightModel', 'mediumModel', 'heavyModel']) {
+ entries.push(makeEntry({
+ id: `provider.model.${provider.id}.${field}`,
+ area: 'Provider Registry',
+ label: `${provider.name} ${field.replace('Model', '').toLowerCase() || 'default'} model`,
+ source: `provider ${provider.id}.${field}`,
+ providerId: provider.id,
+ model: provider[field] || null,
+ providerEditable: false,
+ modelOptions: pickModelOptions(provider),
+ notes: field === 'defaultModel' ? 'Used when an assignment leaves model blank.' : 'Used by task-tier model selection.',
+ link: '/ai',
+ }));
+ }
+ entries.push(makeEntry({
+ id: `provider.fallback.${provider.id}`,
+ area: 'Provider Registry',
+ label: `${provider.name} fallback provider`,
+ source: `provider ${provider.id}.fallbackProvider`,
+ providerId: provider.fallbackProvider || null,
+ modelEditable: false,
+ notes: 'Used when this provider is rate-limited or unavailable.',
+ link: '/ai',
+ }));
+ }
+};
+
+const addSettingsEntries = async (entries) => {
+ const settings = await getSettings();
+ const voice = await getVoiceConfig().catch(() => settings.voice || {});
+ const messages = settings.messages || {};
+
+ entries.push(makeEntry({
+ id: 'settings.embeddings',
+ area: 'Memory & Catalog',
+ label: 'Vector embeddings',
+ source: 'settings.embeddings',
+ providerId: settings.embeddings?.provider || 'none',
+ model: settings.embeddings?.model || null,
+ providerOptions: embeddingProviders,
+ providerTypes: [],
+ notes: 'Powers semantic search, including Chief of Staff memory retrieval.',
+ link: '/settings/embeddings',
+ }));
+
+ for (const [key, label] of [
+ ['autofixer', 'Autofixer'],
+ ['calendarSync', 'Calendar Sync'],
+ ]) {
+ entries.push(makeEntry({
+ id: `settings.${key}`,
+ area: 'Automation',
+ label,
+ source: `settings.${key}`,
+ providerId: settings[key]?.providerId || null,
+ model: settings[key]?.model || null,
+ providerTypes: cliProviderTypes,
+ notes: 'Requires a CLI/TUI provider because it runs agentic tool work.',
+ link: key === 'autofixer' ? '/settings/autofixer' : '/settings/general',
+ }));
+ }
+
+ entries.push(makeEntry({
+ id: 'settings.voice.llm',
+ area: 'Voice',
+ label: 'Conversational LLM',
+ source: 'settings.voice.llm',
+ providerId: voice.llm?.provider || null,
+ model: voice.llm?.model || null,
+ providerTypes: apiProviderTypes,
+ link: '/settings/voice',
+ }));
+ entries.push(makeEntry({
+ id: 'settings.voice.vision',
+ area: 'Voice',
+ label: 'Screen vision model',
+ source: 'settings.voice.llm.visionModel',
+ providerId: voice.llm?.provider || null,
+ model: voice.llm?.visionModel || null,
+ providerEditable: false,
+ providerTypes: apiProviderTypes,
+ link: '/settings/voice',
+ }));
+ entries.push(makeEntry({
+ id: 'settings.voice.codeAgent',
+ area: 'Voice',
+ label: 'Delegated coding agent',
+ source: 'settings.voice.llm.codeAgent',
+ providerId: voice.llm?.codeAgent?.provider || null,
+ model: voice.llm?.codeAgent?.model || null,
+ providerTypes: cliProviderTypes,
+ link: '/settings/voice',
+ }));
+
+ for (const action of ['triage', 'reply']) {
+ const cfg = messages[action] || {};
+ entries.push(makeEntry({
+ id: `settings.messages.${action}`,
+ area: 'Messages',
+ label: `${action[0].toUpperCase()}${action.slice(1)} assistant`,
+ source: `settings.messages.${action}`,
+ providerId: cfg.providerId || messages.providerId || null,
+ model: cfg.model || messages.model || null,
+ link: '/messages/config',
+ }));
+ }
+
+ for (const backend of ['lmstudio', 'ollama']) {
+ entries.push(makeEntry({
+ id: `settings.codeReview.${backend}`,
+ area: 'Review Loop',
+ label: `${backend === 'lmstudio' ? 'LM Studio' : 'Ollama'} reviewer model`,
+ source: `settings.codeReview.${backend}Model`,
+ providerId: backend,
+ model: settings.codeReview?.[`${backend}Model`] || null,
+ providerEditable: false,
+ providerTypes: [],
+ notes: 'Model used when the local reviewer is in the default review chain.',
+ link: '/ai',
+ }));
+ }
+};
+
+const addRecordEntries = async (entries) => {
+ const [
+ brainMeta,
+ universes,
+ storySessions,
+ series,
+ schedule,
+ loops,
+ featureAgents,
+ socialAgents,
+ ] = await Promise.all([
+ brainService.loadMeta().catch(() => null),
+ universeService.listUniverses().catch(() => []),
+ storyBuilderService.listStorySessions().catch(() => []),
+ pipelineSeriesService.listSeries().catch(() => []),
+ taskScheduleService.getScheduleStatus().catch(() => null),
+ loopsService.getLoops().catch(() => []),
+ featureAgentsService.getAllFeatureAgents().catch(() => []),
+ agentPersonalitiesService.getAllAgents().catch(() => []),
+ ]);
+
+ if (brainMeta) {
+ entries.push(makeEntry({
+ id: 'brain.default',
+ area: 'Brain',
+ label: 'Default classifier and digest model',
+ source: 'brain/meta.json',
+ providerId: brainMeta.defaultProvider || null,
+ model: brainMeta.defaultModel || null,
+ link: '/brain/config',
+ }));
+ }
+
+ for (const universe of universes) {
+ if (universe.llm?.provider || universe.llm?.model) {
+ entries.push(makeEntry({
+ id: `universe.${universe.id}`,
+ area: 'Universe Builder',
+ label: universe.name,
+ source: `universe ${universe.id}.llm`,
+ providerId: universe.llm?.provider || null,
+ model: universe.llm?.model || null,
+ scope: 'record',
+ link: `/universes/${universe.id}`,
+ }));
+ }
+ }
+
+ for (const session of storySessions) {
+ if (session.llm?.provider || session.llm?.model) {
+ entries.push(makeEntry({
+ id: `story.${session.id}`,
+ area: 'Story Builder',
+ label: session.title,
+ source: `story session ${session.id}.llm`,
+ providerId: session.llm?.provider || null,
+ model: session.llm?.model || null,
+ scope: 'record',
+ link: `/story-builder/${session.id}`,
+ }));
+ }
+ }
+
+ for (const s of series) {
+ if (s.llm?.provider || s.llm?.model) {
+ entries.push(makeEntry({
+ id: `pipeline.series.${s.id}`,
+ area: 'Pipeline',
+ label: s.name,
+ source: `pipeline series ${s.id}.llm`,
+ providerId: s.llm?.provider || null,
+ model: s.llm?.model || null,
+ scope: 'record',
+ link: `/pipeline/series/${s.id}`,
+ }));
+ }
+ }
+
+ for (const [taskType, task] of Object.entries(schedule?.tasks || {})) {
+ if (task.providerId || task.model) {
+ entries.push(makeEntry({
+ id: `cos.task.${taskType}`,
+ area: 'Chief of Staff',
+ label: `Scheduled task: ${taskType}`,
+ source: `cos task-schedule ${taskType}`,
+ providerId: task.providerId || null,
+ model: task.model || null,
+ scope: 'record',
+ providerTypes: cliProviderTypes,
+ link: '/cos/config',
+ }));
+ }
+ for (const [index, stage] of (task.taskMetadata?.pipeline?.stages || []).entries()) {
+ if (stage?.providerId || stage?.model) {
+ entries.push(makeEntry({
+ id: `cos.taskStage.${taskType}.${index}`,
+ area: 'Chief of Staff',
+ label: `${taskType} stage: ${stage.name || index + 1}`,
+ source: `cos task ${taskType}.taskMetadata.pipeline.stages[${index}]`,
+ providerId: stage.providerId || null,
+ model: stage.model || null,
+ scope: 'record',
+ providerTypes: cliProviderTypes,
+ link: '/cos/config',
+ }));
+ }
+ }
+ }
+
+ for (const loop of loops) {
+ if (loop.providerId) {
+ entries.push(makeEntry({
+ id: `loop.${loop.id}`,
+ area: 'Loops',
+ label: loop.name || loop.id,
+ source: `loop ${loop.id}.providerId`,
+ providerId: loop.providerId || null,
+ model: null,
+ scope: 'record',
+ modelEditable: false,
+ providerTypes: cliProviderTypes,
+ link: '/loops',
+ }));
+ }
+ }
+
+ for (const agent of featureAgents) {
+ if (agent.providerId || agent.model) {
+ entries.push(makeEntry({
+ id: `featureAgent.${agent.id}`,
+ area: 'Feature Agents',
+ label: agent.name,
+ source: `feature agent ${agent.id}`,
+ providerId: agent.providerId || null,
+ model: agent.model || null,
+ scope: 'record',
+ providerTypes: cliProviderTypes,
+ link: `/feature-agents/${agent.id}/config`,
+ }));
+ }
+ }
+
+ for (const agent of socialAgents) {
+ const configs = [];
+ if (agent.aiConfig?.providerId || agent.aiConfig?.model) configs.push(['default', agent.aiConfig]);
+ for (const key of ['content', 'engagement']) {
+ if (agent.aiConfig?.[key]?.providerId || agent.aiConfig?.[key]?.model) configs.push([key, agent.aiConfig[key]]);
+ }
+ for (const [key, cfg] of configs) {
+ entries.push(makeEntry({
+ id: `socialAgent.${agent.id}.${key}`,
+ area: 'Social Agents',
+ label: `${agent.name} ${key}`,
+ source: `agent personality ${agent.id}.aiConfig.${key}`,
+ providerId: cfg.providerId || null,
+ model: cfg.model || null,
+ scope: 'record',
+ link: `/agents/${agent.id}/overview`,
+ }));
+ }
+ }
+};
+
+const addRuntimeCallSiteEntries = (entries) => {
+ const callSites = [
+ ['Ask', 'Ask conversations', '/ask', 'Per-request provider/model override, otherwise the active provider resolves at run time.'],
+ ['Brain', 'Capture/retry/digest run buttons', '/brain/inbox', 'Uses Brain defaults unless a caller passes a one-off provider/model override.'],
+ ['Catalog', 'Catalog AI extraction', '/catalog', 'Accepts a one-off provider override for extraction jobs.'],
+ ['Digital Twin', 'Tests, enrichment, import, traits, taste summaries', '/digital-twin/overview', 'Most actions require a provider/model in the request and do not persist it as a default.'],
+ ['Insights', 'Theme and narrative refresh', '/insights/overview', 'Refresh endpoints accept provider/model per run.'],
+ ['Media', 'Prompt refinement', '/media/image', 'Prompt refine jobs carry their own provider/model in the request.'],
+ ['Meatspace POST', 'LLM drill generation and scoring', '/post/launcher', 'Drill runs accept provider/model per request and otherwise use active-provider fallback.'],
+ ['Standardizer', 'PM2 app standardization analysis', '/apps', 'Runs with an explicit provider when supplied, otherwise the active provider.'],
+ ['Social Agents', 'Generate post/comment actions', '/agents', 'Tool actions use the agent AI config when present, otherwise per-call values or defaults.'],
+ ['Universe Builder', 'Generate/refine/expand actions', '/universes', 'World actions use the universe pin when present and accept per-run overrides.'],
+ ['Pipeline', 'Stage generation, verification, canon extraction, editorial analysis', '/pipeline', 'Series pins are listed separately; individual action buttons may override provider/model for a single run.'],
+ ['Story Builder', 'Conductor steps and refinements', '/story-builder', 'Session pins are listed separately; step actions may override provider/model for a single run.'],
+ ['Voice', 'Screen description and image generation tools', '/settings/voice', 'Uses Voice LLM settings plus image-generation backend settings; per-tool calls may override image backend.'],
+ ];
+
+ for (const [area, label, link, notes] of callSites) {
+ entries.push(makeEntry({
+ id: `runtime.${area.toLowerCase().replace(/[^a-z0-9]+/g, '-')}`,
+ area,
+ label,
+ source: 'runtime call site',
+ scope: 'runtime',
+ editable: false,
+ providerEditable: false,
+ modelEditable: false,
+ link,
+ notes,
+ }));
+ }
+};
+
+export async function getAiAssignments() {
+ const providersData = await getAllProviders();
+ const entries = [];
+ addProviderRegistryEntries(entries, providersData);
+ await addSettingsEntries(entries);
+ await addRecordEntries(entries);
+ addRuntimeCallSiteEntries(entries);
+ return {
+ providers: providersData.providers.map((p) => ({
+ id: p.id,
+ name: p.name,
+ type: p.type,
+ enabled: p.enabled !== false,
+ defaultModel: p.defaultModel || null,
+ models: pickModelOptions(p),
+ })),
+ activeProvider: providersData.activeProvider || null,
+ assignments: entries,
+ };
+}
+
+export async function updateAiAssignment(id, { providerId, model } = {}) {
+ const nextProviderId = asNullable(providerId);
+ const nextModel = asNullable(model);
+
+ if (id === 'provider.active') {
+ if (!nextProviderId) throw new Error('System default provider is required');
+ await setActiveProvider(nextProviderId);
+ return getAiAssignments();
+ }
+
+ if (id.startsWith('provider.model.')) {
+ const [, , providerIdPart, field] = id.split('.');
+ const provider = await getProviderById(providerIdPart);
+ if (!provider) throw new Error(`Provider not found: ${providerIdPart}`);
+ await updateProvider(providerIdPart, { [field]: nextModel });
+ return getAiAssignments();
+ }
+
+ if (id.startsWith('provider.fallback.')) {
+ const providerIdPart = id.replace('provider.fallback.', '');
+ await updateProvider(providerIdPart, { fallbackProvider: nextProviderId });
+ return getAiAssignments();
+ }
+
+ if (id === 'settings.embeddings') {
+ await updateSettings({ embeddings: { provider: nextProviderId || 'none', model: nextModel } });
+ return getAiAssignments();
+ }
+
+ if (id === 'settings.autofixer' || id === 'settings.calendarSync') {
+ const key = id.split('.')[1];
+ await updateSettings({ [key]: { providerId: nextProviderId, model: nextModel } });
+ return getAiAssignments();
+ }
+
+ if (id === 'settings.voice.llm') {
+ await updateVoiceConfig({ llm: { provider: nextProviderId || '', model: nextModel || '' } });
+ return getAiAssignments();
+ }
+
+ if (id === 'settings.voice.vision') {
+ await updateVoiceConfig({ llm: { visionModel: nextModel || '' } });
+ return getAiAssignments();
+ }
+
+ if (id === 'settings.voice.codeAgent') {
+ await updateVoiceConfig({ llm: { codeAgent: { provider: nextProviderId || '', model: nextModel || '' } } });
+ return getAiAssignments();
+ }
+
+ if (id === 'settings.messages.triage' || id === 'settings.messages.reply') {
+ const action = id.split('.')[2];
+ const settings = await getSettings();
+ const messages = isPlainObject(settings.messages) ? { ...settings.messages } : {};
+ messages[action] = { ...(isPlainObject(messages[action]) ? messages[action] : {}), providerId: nextProviderId, model: nextModel };
+ await updateSettings({ messages });
+ return getAiAssignments();
+ }
+
+ if (id.startsWith('settings.codeReview.')) {
+ const backend = id.split('.')[2];
+ await patchSettingsPath(`codeReview.${backend}Model`, nextModel);
+ return getAiAssignments();
+ }
+
+ if (id === 'brain.default') {
+ await brainService.updateMeta({ defaultProvider: nextProviderId, defaultModel: nextModel });
+ return getAiAssignments();
+ }
+
+ if (id.startsWith('universe.')) {
+ await universeService.updateUniverse(id.replace('universe.', ''), { llm: { provider: nextProviderId, model: nextModel } });
+ return getAiAssignments();
+ }
+
+ if (id.startsWith('story.')) {
+ await storyBuilderService.updateStorySession(id.replace('story.', ''), { llm: { provider: nextProviderId, model: nextModel } });
+ return getAiAssignments();
+ }
+
+ if (id.startsWith('pipeline.series.')) {
+ await pipelineSeriesService.updateSeries(id.replace('pipeline.series.', ''), { llm: { provider: nextProviderId, model: nextModel } });
+ return getAiAssignments();
+ }
+
+ if (id.startsWith('cos.taskStage.')) {
+ const [, , taskType, indexRaw] = id.split('.');
+ const index = Number(indexRaw);
+ const task = await taskScheduleService.getTaskInterval(taskType);
+ const stages = [...(task.taskMetadata?.pipeline?.stages || [])];
+ if (!stages[index]) throw new Error(`Stage not found: ${id}`);
+ stages[index] = { ...stages[index], providerId: nextProviderId, model: nextModel };
+ await taskScheduleService.updateTaskInterval(taskType, {
+ taskMetadata: { ...(task.taskMetadata || {}), pipeline: { ...(task.taskMetadata?.pipeline || {}), stages } },
+ });
+ return getAiAssignments();
+ }
+
+ if (id.startsWith('cos.task.')) {
+ await taskScheduleService.updateTaskInterval(id.replace('cos.task.', ''), { providerId: nextProviderId, model: nextModel });
+ return getAiAssignments();
+ }
+
+ if (id.startsWith('loop.')) {
+ await loopsService.updateLoop(id.replace('loop.', ''), { providerId: nextProviderId });
+ return getAiAssignments();
+ }
+
+ if (id.startsWith('featureAgent.')) {
+ await featureAgentsService.updateFeatureAgent(id.replace('featureAgent.', ''), { providerId: nextProviderId, model: nextModel });
+ return getAiAssignments();
+ }
+
+ if (id.startsWith('socialAgent.')) {
+ const [, agentId, key] = id.split('.');
+ const agent = await agentPersonalitiesService.getAgentById(agentId);
+ if (!agent) throw new Error(`Agent not found: ${agentId}`);
+ const aiConfig = isPlainObject(agent.aiConfig) ? { ...agent.aiConfig } : {};
+ if (key === 'default') {
+ aiConfig.providerId = nextProviderId || undefined;
+ aiConfig.model = nextModel || undefined;
+ } else {
+ aiConfig[key] = { ...(isPlainObject(aiConfig[key]) ? aiConfig[key] : {}), providerId: nextProviderId || undefined, model: nextModel || undefined };
+ }
+ await agentPersonalitiesService.updateAgent(agentId, { aiConfig });
+ return getAiAssignments();
+ }
+
+ throw new Error(`Unknown AI assignment: ${id}`);
+}