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

simplify the composite provider slice: fold the harness-keyed effort ladder into the existing chain, drop unused exports and the event bus, single-flight the graph read, and build the catalog from one graph pass (#7564)

[._.]/ Adam Eivy94182043d3f1
diff --git a/server/lib/aiToolkit/internal/providerRef.js b/server/lib/aiToolkit/internal/providerRef.js
index 3099a04265..7677abef32 100644
--- a/server/lib/aiToolkit/internal/providerRef.js
+++ b/server/lib/aiToolkit/internal/providerRef.js
@@ -23,6 +23,9 @@ export const COMPOSITE_ID_RE = /^([a-z0-9-]+)\.(cli|tui|api)@([a-z0-9][a-z0-9-]*
/** Longest reference any selection field accepts. */
export const MAX_PROVIDER_REF_LENGTH = 200;
+/** The message a PRESET-ONLY field reports when handed a composite. */
+export const PRESET_ONLY_MESSAGE = 'must be a preset provider id (lowercase alphanumeric with hyphens); a composite harness.method@service selection is not accepted here';
+
/**
* @param {unknown} id
* @returns {{kind: 'preset', id: string}
diff --git a/server/lib/aiToolkit/validation.js b/server/lib/aiToolkit/validation.js
index fee3738961..d0912184e4 100644
--- a/server/lib/aiToolkit/validation.js
+++ b/server/lib/aiToolkit/validation.js
@@ -2,12 +2,7 @@ import { z } from 'zod';
import { MAX_MODEL_ACCESS_PATTERNS, MAX_MODEL_ACCESS_PATTERN_LENGTH, MODEL_ACCESS_MODES } from './internal/modelAccess.js';
import { basename, extname } from 'path';
import { MAX_TIMEOUT, MIN_TIMEOUT } from './constants.js';
-import { MAX_PROVIDER_REF_LENGTH, PRESET_ID_RE, parseProviderRef } from './internal/providerRef.js';
-
-// The preset-only rule, named once so every surface that refuses a composite
-// (`harness.method@service`, #7564) says the same thing: the active provider,
-// a record's fallback, and anything else keyed on `providers.json`.
-const PRESET_ONLY_MESSAGE = 'must be a preset provider id (lowercase alphanumeric with hyphens); a composite harness.method@service selection is not accepted here';
+import { MAX_PROVIDER_REF_LENGTH, PRESET_ID_RE, PRESET_ONLY_MESSAGE, parseProviderRef } from './internal/providerRef.js';
/**
* A run's provider selection: a preset record id or a composite reference the
diff --git a/server/lib/providerModels.js b/server/lib/providerModels.js
index 308187f76e..253091b80c 100644
--- a/server/lib/providerModels.js
+++ b/server/lib/providerModels.js
@@ -526,52 +526,29 @@ export function foldCursorEffortIntoModel(model, effort) {
*/
export function effortLevelsForProvider(provider, model = null) {
if (!provider) return null;
- // A record materialized from a composite id carries its harness by name
- // (#7564); read it before sniffing the command, which a bootstrap-wrapped
- // spawn or a path-configured binary can obscure.
- const byHarness = effortLevelsForHarness(provider.harnessId, provider, model);
- if (byHarness !== undefined) return byHarness;
- if (isOpencodeLocalProvider(provider)) return OPENCODE_LOCAL_EFFORT_LEVELS;
- if (isCodexProvider(provider)) return codexEffortLevelsForModel(model);
- if (isAntigravityProvider(provider)) {
+ // A record materialized from a composite id names its harness (#7564); each
+ // arm honors that before sniffing the command, so a path-configured binary or
+ // a bootstrap-wrapped spawn still offers its rungs.
+ const harness = provider.harnessId ?? null;
+ if (harness === 'opencode' || isOpencodeLocalProvider(provider)) {
+ return isOpencodeLocalProvider(provider) ? OPENCODE_LOCAL_EFFORT_LEVELS : null;
+ }
+ if (harness === 'codex' || isCodexProvider(provider)) return codexEffortLevelsForModel(model);
+ if (harness === 'antigravity' || isAntigravityProvider(provider)) {
const perModel = model ? antigravityModelEffortLevels(model, provider.models) : null;
if (perModel === null) return ANTIGRAVITY_EFFORT_LEVELS;
return perModel.length ? perModel : null;
}
- if (commandBasename(provider.command) === 'pi') return PI_EFFORT_LEVELS;
- if (isCursorProvider(provider)) return CURSOR_EFFORT_LEVELS;
- if (isGrokProvider(provider)) return GROK_EFFORT_LEVELS;
- if (isClaudeProvider(provider)) return CLAUDE_EFFORT_LEVELS;
+ if (harness === 'pi' || commandBasename(provider.command) === 'pi') return PI_EFFORT_LEVELS;
+ if (harness === 'cursor' || isCursorProvider(provider)) return CURSOR_EFFORT_LEVELS;
+ if (harness === 'grok' || isGrokProvider(provider)) return GROK_EFFORT_LEVELS;
+ if (harness === 'claude' || isClaudeProvider(provider)) return CLAUDE_EFFORT_LEVELS;
return null;
}
-/** Pi's reasoning ladder (`pi --effort`), shared by the harness table and command sniffing. */
+/** Pi's reasoning ladder (`pi --effort`). */
const PI_EFFORT_LEVELS = Object.freeze(['low', 'medium', 'high', 'xhigh', 'max']);
-/**
- * The effort ladder a HARNESS id names, or `undefined` when the id is absent
- * or names no harness this table knows — the signal for
- * {@link effortLevelsForProvider} to fall through to command sniffing.
- * `null` is a real answer ("this harness takes no effort flag").
- */
-function effortLevelsForHarness(harnessId, provider, model) {
- switch (harnessId) {
- case 'claude': return CLAUDE_EFFORT_LEVELS;
- case 'codex': return codexEffortLevelsForModel(model);
- case 'antigravity': {
- const perModel = model ? antigravityModelEffortLevels(model, provider?.models) : null;
- if (perModel === null) return ANTIGRAVITY_EFFORT_LEVELS;
- return perModel.length ? perModel : null;
- }
- case 'pi': return PI_EFFORT_LEVELS;
- case 'cursor': return CURSOR_EFFORT_LEVELS;
- case 'grok': return GROK_EFFORT_LEVELS;
- case 'opencode': return isOpencodeLocalProvider(provider) ? OPENCODE_LOCAL_EFFORT_LEVELS : null;
- case 'direct': case 'kimi': case 'kilo': case 'openchamber': return null;
- default: return undefined;
- }
-}
-
// Every effort value any CLI accepts, ordered weakest→strongest. The clamp
// below walks this so an effort saved against one provider survives a switch to
// a provider with a narrower ladder (agy tops out at `high`; claude has no
diff --git a/server/lib/providerRef.js b/server/lib/providerRef.js
index b935413a61..cdcc59a0fc 100644
--- a/server/lib/providerRef.js
+++ b/server/lib/providerRef.js
@@ -25,9 +25,6 @@
/** A preset record id — the slug `createProvider` assigns. */
export const PRESET_ID_RE = /^[a-z0-9][a-z0-9-]*$/;
-/** The execution methods a composite may name; mirrors a record's `type`. */
-export const COMPOSITE_METHODS = Object.freeze(['cli', 'tui', 'api']);
-
/**
* `<harness>.<method>@<service-slug>[+<bootstrap-slug>]`. Groups: harness id,
* method, service slug, optional bootstrap slug.
diff --git a/server/lib/providerRef.parity.test.js b/server/lib/providerRef.parity.test.js
index af43612c6a..e493e23cdb 100644
--- a/server/lib/providerRef.parity.test.js
+++ b/server/lib/providerRef.parity.test.js
@@ -19,6 +19,7 @@ describe('providerRef ↔ aiToolkit/internal/providerRef parity', () => {
expect(toolkit.PRESET_ID_RE.source).toBe(server.PRESET_ID_RE.source);
expect(toolkit.COMPOSITE_ID_RE.source).toBe(server.COMPOSITE_ID_RE.source);
expect(toolkit.MAX_PROVIDER_REF_LENGTH).toBe(server.MAX_PROVIDER_REF_LENGTH);
+ expect(toolkit.PRESET_ONLY_MESSAGE).toBe(server.PRESET_ONLY_MESSAGE);
});
it.each(SAMPLES)('parses %j identically', (id) => {
diff --git a/server/routes/providers.composite.test.js b/server/routes/providers.composite.test.js
index 8025af567a..9a7f3a7ec0 100644
--- a/server/routes/providers.composite.test.js
+++ b/server/routes/providers.composite.test.js
@@ -64,9 +64,10 @@ describe('PUT /api/providers/active', () => {
describe('GET /api/providers/catalog', () => {
it('hands the sanitized presets to the catalog builder and returns its answer', async () => {
- compositeService.buildProviderCatalog.mockImplementation(async ({ presets }) => ({ harnesses: [], services: [], bootstraps: [], compatibility: {}, effortLevels: {}, effortLevelsByModel: {}, presets }));
+ compositeService.buildProviderCatalog.mockResolvedValue({ harnesses: [], services: [], bootstraps: [], compatibility: {}, effortLevels: {}, effortLevelsByModel: {}, presets: [] });
const res = await request(app()).get('/api/providers/catalog');
expect(res.status).toBe(200);
+ expect(compositeService.buildProviderCatalog).toHaveBeenCalledWith();
expect(res.body.presets).toHaveLength(1);
expect(res.body.presets[0]).toMatchObject({ id: 'claude-code', hasApiKey: true });
expect(JSON.stringify(res.body)).not.toContain('preset-secret');
diff --git a/server/routes/providers.js b/server/routes/providers.js
index 816dbae9b6..2424305404 100644
--- a/server/routes/providers.js
+++ b/server/routes/providers.js
@@ -118,12 +118,12 @@ let runtimeSetupInFlight = false;
* distinguish "configured but blank" from an unknown redacted value when it
* paints provider readiness.
*/
-const sanitizeProvider = (provider, { hasApiKey = Boolean(provider?.apiKey) } = {}) => {
+const sanitizeProvider = (provider) => {
if (!provider) return provider;
const { apiKey, envVars, secretEnvVars, ...rest } = provider;
const sanitized = {
...rest,
- hasApiKey,
+ hasApiKey: Boolean(apiKey),
envVars: envVars ? { ...envVars } : {},
secretEnvVars: secretEnvVars || []
};
@@ -193,12 +193,13 @@ const presentProvider = (provider, capabilities = captureSystemCapabilities()) =
// untouched list rides along as `modelCatalog` — the editor seeds its
// "Available Models" box from it, so an ordinary Save on a scoped provider
// cannot persist the narrowed list over the real one.
- // `hasApiKey` is read off the RAW record: an inherited or materialized key
- // rides NON-enumerably (`withGatewayApiKey`, the composite resolver), and the
- // decorating spreads above have already dropped it by the time the sanitizer
- // looks — a composite with a key would otherwise read as keyless (#7564).
return sanitizeProvider({
...applyModelAccess(decorated),
+ // The RAW record's key: an inherited or materialized one rides
+ // NON-enumerably (`withGatewayApiKey`, the composite resolver), so the
+ // decorating spreads above dropped it — re-carried here so `hasApiKey`
+ // reports the key the run would actually use (#7564).
+ apiKey: provider?.apiKey,
// The UNION of the two refresh paths, because the button asks only
// whether SOME path can serve this record. Which one actually serves it is
// decided in `POST /:id/refresh-models`, and the two must stay in step or
@@ -208,7 +209,7 @@ const presentProvider = (provider, capabilities = captureSystemCapabilities()) =
publicReviewEnforcedPostures: enforcedPublicReviewPosturesForProvider(provider),
publicReviewSupported: publicReviewPostures.includes(PUBLIC_REVIEW_NO_TOOL_POSTURE),
publicReviewActionsSupported: publicReviewPostures.includes(PUBLIC_REVIEW_ACTIONS_POSTURE),
- }, { hasApiKey: Boolean(provider?.apiKey) });
+ });
};
/**
@@ -639,8 +640,8 @@ export function createPortOSProviderRoutes(aiToolkit) {
*/
router.get('/catalog', asyncHandler(async (_req, res) => {
const { buildProviderCatalog } = await import('../services/compositeProviders.js');
- const [data, capabilities] = await Promise.all([providerService.getAllProviders(), detectSystemCapabilities()]);
- res.json(await buildProviderCatalog({ presets: data.providers.map((provider) => presentProvider(provider, capabilities)) }));
+ const [catalog, data, capabilities] = await Promise.all([buildProviderCatalog(), providerService.getAllProviders(), detectSystemCapabilities()]);
+ res.json({ ...catalog, presets: data.providers.map((provider) => presentProvider(provider, capabilities)) });
}));
/** Per-harness enablement (#7564): the user's word, else PATH detection, `direct` always on. */
diff --git a/server/services/compositeProviders.js b/server/services/compositeProviders.js
index f169d6f477..18f2daee56 100644
--- a/server/services/compositeProviders.js
+++ b/server/services/compositeProviders.js
@@ -11,6 +11,7 @@ import { readGraph } from './providerGraphStore.js';
import { listServices } from './providerServices.js';
import { peekProviderRuntimeStatuses } from './providerRuntimeInstaller.js';
import { getSettings } from './settings.js';
+import { createSingleFlight } from '../lib/singleFlight.js';
/**
* COMPOSITE provider resolution (#7564, epic #7561): turning a
@@ -49,8 +50,15 @@ import { getSettings } from './settings.js';
const GRAPH_SNAPSHOT_TTL_MS = 1000;
let graphSnapshot = null;
let graphSnapshotAt = -Infinity;
+// One read per cold window even when N callers miss it together.
+const graphReads = createSingleFlight();
-/** id → { key, record } — one entry per composite, replaced when its inputs move. */
+/**
+ * id → { key, outcome } — one entry per composite, replaced when its inputs
+ * move. The key is the graph snapshot's timestamp plus the settings revision:
+ * a service edit lands on the next snapshot, a settings save bumps the
+ * revision, and a warm hit costs no I/O at all.
+ */
const materialized = new Map();
/** Drop every cached derivation. Exported for tests and for a caller that just changed a service row. */
@@ -60,11 +68,13 @@ export function invalidateCompositeCache() {
materialized.clear();
}
-async function graphWithinTtl(now = Date.now()) {
- if (graphSnapshot && now - graphSnapshotAt < GRAPH_SNAPSHOT_TTL_MS) return graphSnapshot;
- graphSnapshot = await readGraph();
- graphSnapshotAt = now;
- return graphSnapshot;
+async function graphWithinTtl() {
+ if (graphSnapshot && Date.now() - graphSnapshotAt < GRAPH_SNAPSHOT_TTL_MS) return graphSnapshot;
+ return graphReads.run('graph', async () => {
+ graphSnapshot = await readGraph();
+ graphSnapshotAt = Date.now();
+ return graphSnapshot;
+ });
}
/**
@@ -86,8 +96,6 @@ export function instanceForConnection(connection, env = process.env) {
});
}
-const refusal = (code, reason) => ({ record: null, code, reason });
-
/**
* Resolve, with the reason for a refusal. Pure over its inputs so the tests
* pin the policy without a store: the graph, the settings and the bootstrap
@@ -99,31 +107,29 @@ const refusal = (code, reason) => ({ record: null, code, reason });
*/
export function materializeComposite(id, { graph, settings, bootstraps, runtimes = undefined, env = process.env }) {
const ref = parseProviderRef(id);
- if (ref?.kind !== 'composite') return { ...refusal('not-composite', `"${id}" is not a composite provider id`), parts: null };
+ if (ref?.kind !== 'composite') return { record: null, code: 'not-composite', reason: `"${id}" is not a composite provider id`, parts: null };
const parts = { harnessId: ref.harnessId, method: ref.method, serviceSlug: ref.serviceSlug, bootstrapSlug: ref.bootstrapSlug };
- const withParts = (outcome) => ({ ...outcome, parts });
+ const refuse = (code, reason) => ({ record: null, code, reason, parts });
const harness = harnessById(ref.harnessId);
- if (!harness) return withParts(refusal('harness-unknown', `No harness "${ref.harnessId}"`));
+ if (!harness) return refuse('harness-unknown', `No harness "${ref.harnessId}"`);
const enablement = harnessEnablementFrom(ref.harnessId, { settings, runtimes });
if (!enablement?.enabled) {
- return withParts(refusal('harness-disabled', `${harness.label} is ${enablement?.source === 'setting' ? 'switched off' : 'not detected on this machine'}`));
+ return refuse('harness-disabled', `${harness.label} is ${enablement?.source === 'setting' ? 'switched off' : 'not detected on this machine'}`);
}
- if (!harness.modes.includes(ref.method)) return withParts(refusal('method-unsupported', `${harness.label} has no ${ref.method} mode`));
+ if (!harness.modes.includes(ref.method)) return refuse('method-unsupported', `${harness.label} has no ${ref.method} mode`);
const connection = findConnectionByRef(graph, ref.serviceSlug);
- if (!connection || connection.slug !== ref.serviceSlug) return withParts(refusal('service-unknown', `No service is addressed as "${ref.serviceSlug}"`));
- if (connection.enabled === false) return withParts(refusal('service-disabled', `Service "${ref.serviceSlug}" is switched off`));
+ if (!connection || connection.slug !== ref.serviceSlug) return refuse('service-unknown', `No service is addressed as "${ref.serviceSlug}"`);
+ if (connection.enabled === false) return refuse('service-disabled', `Service "${ref.serviceSlug}" is switched off`);
const instance = instanceForConnection(connection, env);
- if (!instance) return withParts(refusal('service-undefined', `Service "${ref.serviceSlug}" has no definition this build composes onto`));
- if (!isCompatible(harness, instance)) {
- return withParts(refusal('incompatible', `${harness.label} cannot be pointed at ${instance.definition.label}`));
- }
+ if (!instance) return refuse('service-undefined', `Service "${ref.serviceSlug}" has no definition this build composes onto`);
+ if (!isCompatible(harness, instance)) return refuse('incompatible', `${harness.label} cannot be pointed at ${instance.definition.label}`);
let bootstrap = null;
if (ref.bootstrapSlug) {
const app = bootstraps?.[ref.bootstrapSlug];
- if (!app) return withParts(refusal('bootstrap-unknown', `No credential bootstrap app is addressed as "${ref.bootstrapSlug}"`));
+ if (!app) return refuse('bootstrap-unknown', `No credential bootstrap app is addressed as "${ref.bootstrapSlug}"`);
bootstrap = bootstrapInputFor(ref.bootstrapSlug, app);
}
@@ -143,8 +149,8 @@ export function materializeComposite(id, { graph, settings, bootstraps, runtimes
});
// A refusal is a REASON on this composite, not a failure of the lookup: the
// caller asked "is this runnable?", and "no, because…" is the answer.
- if (error) return withParts(refusal(error.code, error.message));
- return withParts({ record: withHiddenCredential(record), code: null, reason: null });
+ if (error) return refuse(error.code, error.message);
+ return { record: withHiddenCredential(record), code: null, reason: null, parts };
}
/**
@@ -159,11 +165,6 @@ function withHiddenCredential(record) {
return rest;
}
-async function resolveInputs() {
- const [graph, settings, bootstraps] = await Promise.all([graphWithinTtl(), getSettings(), listCredentialBootstraps()]);
- return { graph, settings, bootstraps, runtimes: peekProviderRuntimeStatuses() };
-}
-
/**
* The full verdict for a composite id, from live inputs. `eligible: false`
* carries the code and reason a picker shows beside a saved selection.
@@ -179,12 +180,12 @@ export async function describeCompositeProvider(id) {
if (!providerGraphEnabled()) {
return { id, eligible: false, code: 'graph-unavailable', reason: 'Service instances are unavailable on this install', parts: null, record: null };
}
- const inputs = await resolveInputs();
- const connection = findConnectionByRef(inputs.graph, ref.serviceSlug);
- const key = `${connection?.revision ?? 'none'}|${harnessSettingsRevision()}`;
+ const graph = await graphWithinTtl();
+ const key = `${graphSnapshotAt}|${harnessSettingsRevision()}`;
const cached = materialized.get(id);
if (cached && cached.key === key) return { id, ...cached.outcome };
- const { record, code, reason, parts } = materializeComposite(id, inputs);
+ const [settings, bootstraps] = await Promise.all([getSettings(), listCredentialBootstraps()]);
+ const { record, code, reason, parts } = materializeComposite(id, { graph, settings, bootstraps, runtimes: peekProviderRuntimeStatuses() });
const outcome = { eligible: record !== null, code, reason, parts, record };
materialized.set(id, { key, outcome });
return { id, ...outcome };
@@ -238,31 +239,31 @@ const harnessEffortLevels = (harness, model = null) => effortLevelsForProvider(
* @param {{presets?: object[]}} [input]
*/
export async function buildProviderCatalog({ presets = [] } = {}) {
+ const graphEnabled = providerGraphEnabled();
+ const graph = graphEnabled ? await graphWithinTtl() : { connections: [] };
const [harnesses, bootstraps, services] = await Promise.all([
listHarnessEnablement(),
listCredentialBootstraps(),
- providerGraphEnabled() ? listServices().then((result) => result.services) : [],
+ graphEnabled ? listServices({ graph }).then((result) => result.services) : [],
]);
- const graph = providerGraphEnabled() ? await graphWithinTtl() : { connections: [] };
const instances = graph.connections.map((connection) => ({ connection, instance: instanceForConnection(connection) }))
.filter(({ instance }) => instance !== null);
- const compatibility = Object.fromEntries(PROVIDER_HARNESSES.map((harness) => [
- harness.id,
- instances.filter(({ instance }) => isCompatible(harness, instance)).map(({ instance }) => instance.slug),
- ]));
+ // One compatibility pass, read by both the slug map and the per-model ladders.
+ const compatible = new Map(PROVIDER_HARNESSES.map((harness) => [harness.id, instances.filter(({ instance }) => isCompatible(harness, instance))]));
+ const compatibility = Object.fromEntries([...compatible].map(([harnessId, rows]) => [harnessId, rows.map(({ instance }) => instance.slug)]));
const effortLevels = Object.fromEntries(PROVIDER_HARNESSES.map((harness) => [harness.id, harnessEffortLevels(harness)]));
+ const sameLadder = (a, b) => a === b || (Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((rung, i) => rung === b[i]));
// Per-model ladders, only where a model narrows or widens the harness's own
// (Codex's Ultra-capable models, Antigravity's per-model rungs): every
// catalog model of a compatible service, keyed under the harness.
const effortLevelsByModel = Object.fromEntries(PROVIDER_HARNESSES.map((harness) => {
- const base = JSON.stringify(effortLevels[harness.id]);
- const models = new Set(instances
- .filter(({ instance }) => isCompatible(harness, instance))
+ const base = effortLevels[harness.id];
+ const models = new Set(compatible.get(harness.id)
.flatMap(({ connection, instance }) => applyServicePlanFilter(instance.definition, instance.plan, connection.catalog?.models || [])));
const perModel = [...models]
.map((model) => [model, harnessEffortLevels(harness, model)])
- .filter(([, ladder]) => JSON.stringify(ladder) !== base);
+ .filter(([, ladder]) => !sameLadder(ladder, base));
return [harness.id, Object.fromEntries(perModel)];
}));
diff --git a/server/services/credentialBootstrapApps.js b/server/services/credentialBootstrapApps.js
index 28af3378d3..31f0fbc16d 100644
--- a/server/services/credentialBootstrapApps.js
+++ b/server/services/credentialBootstrapApps.js
@@ -24,12 +24,6 @@ export async function listCredentialBootstraps() {
return normalizeCredentialBootstraps(raw);
}
-/** One app by slug, or `null`. */
-export async function credentialBootstrapBySlug(slug) {
- const apps = await listCredentialBootstraps();
- return Object.hasOwn(apps, slug) ? apps[slug] : null;
-}
-
/**
* Replace the whole table. Validated against the settings-slice schema so a
* bad entry 400s here instead of surfacing as a spawn that cannot start.
diff --git a/server/services/harnessEnablement.js b/server/services/harnessEnablement.js
index 056d9345ef..cc54e48a4a 100644
--- a/server/services/harnessEnablement.js
+++ b/server/services/harnessEnablement.js
@@ -1,6 +1,6 @@
-import { EventEmitter } from 'node:events';
import { DIRECT_HARNESS_ID, PROVIDER_HARNESSES, harnessById } from '../lib/providerHarnesses.js';
import { isPlainObject } from '../lib/objects.js';
+import { harnessSettingsSchema } from '../lib/validation.js';
import { PROVIDER_RUNTIMES, peekProviderRuntimeStatuses } from './providerRuntimeInstaller.js';
import { getSettings, settingsEvents, updateSettingsWith } from './settings.js';
@@ -23,19 +23,10 @@ import { getSettings, settingsEvents, updateSettingsWith } from './settings.js';
* holds (AGENTS.md "No cold-bootstrap LLM calls").
*/
-/** Emits `changed` whenever the enablement inputs move (a settings save). */
-export const harnessEnablementEvents = new EventEmitter();
-
/** Bumped on every settings write; the composite resolver keys its cache on it. */
let settingsRevision = 0;
-settingsEvents.on('settings:updated', () => {
- settingsRevision += 1;
- harnessEnablementEvents.emit('changed');
-});
-settingsEvents.on('settings:invalidated', () => {
- settingsRevision += 1;
- harnessEnablementEvents.emit('changed');
-});
+settingsEvents.on('settings:updated', () => { settingsRevision += 1; });
+settingsEvents.on('settings:invalidated', () => { settingsRevision += 1; });
/** The revision the composite cache compares against. */
export const harnessSettingsRevision = () => settingsRevision;
@@ -84,11 +75,6 @@ export function harnessEnablementFrom(harnessId, { settings = {}, runtimes = und
return { enabled: detected, source: 'detected', detected, version };
}
-/** Whether `harnessId` may compose into a runnable composite right now. */
-export async function harnessEnabled(harnessId) {
- return harnessEnablementFrom(harnessId, { settings: await getSettings() })?.enabled === true;
-}
-
/**
* Every registry harness with its enablement verdict — the `harnesses` half
* of `GET /api/providers/catalog`. Cache-only detection; no probe is started.
@@ -124,14 +110,18 @@ export async function setHarnessEnabled(harnessId, enabled) {
}
/**
- * The slice with every entry that names no registry harness — or carries no
- * boolean — dropped. Pure; `reconcileHarnessEnablement` persists the result.
+ * The slice with every entry the settings schema rejects dropped — one
+ * definition of "a valid harnesses slice", the schema's. `direct` is dropped
+ * too: it cannot be disabled, so its entry would be a rule nothing reads.
+ * Pure; `reconcileHarnessEnablement` persists the result.
*/
export function normalizeHarnessSettings(raw) {
if (!isPlainObject(raw)) return {};
- return Object.fromEntries(Object.entries(raw)
- .filter(([id, entry]) => harnessById(id) && id !== DIRECT_HARNESS_ID && typeof entry?.enabled === 'boolean')
- .map(([id, entry]) => [id, { enabled: entry.enabled }]));
+ return Object.fromEntries(Object.entries(raw).flatMap(([id, entry]) => {
+ if (id === DIRECT_HARNESS_ID) return [];
+ const result = harnessSettingsSchema.safeParse({ [id]: entry });
+ return result.success ? [[id, result.data[id]]] : [];
+ }));
}
/**
diff --git a/server/services/harnessEnablement.test.js b/server/services/harnessEnablement.test.js
index 54b9c6a15b..a8971dd615 100644
--- a/server/services/harnessEnablement.test.js
+++ b/server/services/harnessEnablement.test.js
@@ -89,7 +89,8 @@ describe('listHarnessEnablement / setHarnessEnabled', () => {
describe('reconcileHarnessEnablement', () => {
it('drops entries nothing reads, keeps the rest, and is a no-op on the second pass', async () => {
- settingsState.current = { harnesses: { pi: { enabled: false, stray: 1 }, direct: { enabled: false }, bogus: { enabled: true }, codex: { enabled: 'yes' } } };
+ // A stray key rejects its entry (the slice is strict, as the PUT validator is), an unknown id and a non-boolean are dropped, `direct` is never stored.
+ settingsState.current = { harnesses: { pi: { enabled: false }, claude: { enabled: true, stray: 1 }, direct: { enabled: false }, bogus: { enabled: true }, codex: { enabled: 'yes' } } };
await expect(enablement.reconcileHarnessEnablement()).resolves.toEqual({ changed: true, harnesses: { pi: { enabled: false } } });
expect(settingsState.current.harnesses).toEqual({ pi: { enabled: false } });
settingsMock.updateSettingsWith.mockClear();
diff --git a/server/services/providerServices.js b/server/services/providerServices.js
index 54ba41d519..d731bd4e7e 100644
--- a/server/services/providerServices.js
+++ b/server/services/providerServices.js
@@ -134,10 +134,13 @@ function describe(connection, graph, envFile) {
});
}
-/** Every instance, sanitized: never a credential value, never a projection snapshot. */
-export async function listServices() {
+/**
+ * Every instance, sanitized: never a credential value, never a projection
+ * snapshot. A caller holding a fresh graph read passes it to skip a second.
+ */
+export async function listServices({ graph: preread = null } = {}) {
requireProviderGraph();
- const [graph, envFile] = await Promise.all([readGraph(), loadInstallEnvFile()]);
+ const [graph, envFile] = await Promise.all([preread ?? readGraph(), loadInstallEnvFile()]);
return { services: graph.connections.map((connection) => describe(connection, graph, envFile)) };
}