switchback-core 2026.11.1 → 2026.11.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "switchback-core",
3
- "version": "2026.11.1",
3
+ "version": "2026.11.3",
4
4
  "type": "module",
5
5
  "description": "Host-agnostic core for switchback: fallback routing, error classification ports, block state and configuration.",
6
6
  "license": "MIT",
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Which decision models carry their own connection details, and which depend on
3
+ * a host's classifier catalog.
4
+ *
5
+ * This is the one question the config loader deliberately does *not* answer: an
6
+ * address without a `baseUrl` is perfectly valid on a host that has a catalog
7
+ * (pi resolves `typesafe/jev-latest` straight from its model registry), and it
8
+ * is unusable on a host that does not (OpenCode has no catalog, so the address
9
+ * needs `decisionProviders.<provider>` or a `decisionModels.<address>` entry).
10
+ *
11
+ * Both answers are computed here from the resolved config, so the pi check and
12
+ * the OpenCode notice agree on what "has a connection" means and no host repeats
13
+ * the precedence rule (address override wins over the provider entry).
14
+ */
15
+
16
+ import type { ResolvedSwitchbackFileConfig } from "./types.ts";
17
+
18
+ /**
19
+ * The minimum shape a connection lookup needs. Both the file config and the
20
+ * resolved config satisfy it, so the dialogue (which re-reads the file) and the
21
+ * host checks (which pass the resolved config) share one rule.
22
+ */
23
+ interface ConnectionSource {
24
+ readonly decisionModels?: Readonly<Record<string, { readonly baseUrl?: string }>>;
25
+ readonly decisionProviders?: Readonly<Record<string, { readonly baseUrl?: string }>>;
26
+ }
27
+
28
+ /** Split a `provider/id` decision-model address; undefined parts mean a malformed one. */
29
+ export function splitDecisionModelAddress(address: string): { provider: string; id: string } | undefined {
30
+ const slash = address.indexOf("/");
31
+ if (slash <= 0 || slash === address.length - 1) return undefined;
32
+ return { provider: address.slice(0, slash), id: address.slice(slash + 1) };
33
+ }
34
+
35
+ /** The connection details an address resolves to: its own entry first, then its provider's. */
36
+ export function decisionModelConnection(config: ConnectionSource, address: string): { baseUrl?: string } | undefined {
37
+ const parts = splitDecisionModelAddress(address);
38
+ return config.decisionModels?.[address] ?? (parts === undefined ? undefined : config.decisionProviders?.[parts.provider]);
39
+ }
40
+
41
+ /** Every decision-model address the config references, de-duplicated, in model order. */
42
+ export function referencedDecisionModelAddresses(config: ResolvedSwitchbackFileConfig): string[] {
43
+ const addresses = new Set<string>();
44
+ for (const model of config.models) {
45
+ if (model.decisionModel !== undefined) addresses.add(`${model.decisionModel.provider}/${model.decisionModel.id}`);
46
+ }
47
+ return [...addresses];
48
+ }
49
+
50
+ /**
51
+ * Referenced addresses that carry no `baseUrl` and therefore need a classifier
52
+ * catalog. On pi these resolve from the registry; on OpenCode they are the exact
53
+ * set that silently cannot classify, which is the only case worth a notice.
54
+ */
55
+ export function decisionModelsWithoutConnection(config: ResolvedSwitchbackFileConfig): string[] {
56
+ return referencedDecisionModelAddresses(config).filter(
57
+ (address) => decisionModelConnection(config, address)?.baseUrl === undefined,
58
+ );
59
+ }
@@ -21,9 +21,12 @@
21
21
  * job via the encrypted store (`packages/pi/src/secrets.ts`). The type shape makes a
22
22
  * literal key unrepresentable at this boundary.
23
23
  *
24
- * One file: `configFilePath()` (`~/.config/switchback/switchback.yaml`), the same
25
- * config both hosts read. There are no host-specific or per-project layers to
26
- * choose between (`switchback-wix.12`).
24
+ * One base file, optional per-host overlays: `configFilePath()`
25
+ * (`~/.config/switchback/switchback.yaml`) is the shared base both hosts read,
26
+ * and `configOverlayPath(host)` (`switchback.pi.yaml` / `switchback.oc.yaml`)
27
+ * layers host-only entries on top at load time (`switchback-wix.12` as amended).
28
+ * The dialogue edits the base file; overlays are hand-edited partial files.
29
+ * There are no per-project layers to choose between.
27
30
  *
28
31
  * Writes are atomic - tmp file + rename, the `state.ts` pattern - and the
29
32
  * parent directory is created on demand, so a first save into a fresh install
@@ -224,9 +227,9 @@ export function moveFallback(loaded: LoadedConfig, virtualId: string, from: numb
224
227
  /**
225
228
  * Set or clear a model's decision model. `null` clears the key (the model then
226
229
  * reports and blind-cycles without classifying). The value is a decision-model
227
- * address ("provider/model-id"); connection details, when the address needs a
228
- * direct endpoint, live in the top-level `decisionModels:` map under the same
229
- * address.
230
+ * address ("provider/model-id"); the connection details it inherits live in
231
+ * `decisionProviders:` under the provider, or in a `decisionModels:` entry at
232
+ * the same address when that one model needs its own endpoint.
230
233
  */
231
234
  export function setDecisionModel(loaded: LoadedConfig, virtualId: string, address: string | null): void {
232
235
  const { node } = findModelNode(loaded, virtualId);
@@ -366,6 +369,110 @@ export function countDecisionModelReferences(loaded: LoadedConfig, address: stri
366
369
  return count;
367
370
  }
368
371
 
372
+ /** A `decisionProviders:` map value as the editor accepts it. */
373
+ export interface DecisionProviderInput {
374
+ /** Provider id - the map key, and the first half of a decision-model address. */
375
+ provider: string;
376
+ /** Direct SystemOne endpoint; omit for catalog resolution. */
377
+ baseUrl?: string;
378
+ /**
379
+ * Secret-store name, written as `secret:<name>`. Omit for an endpoint that
380
+ * ignores the bearer token; the entry then carries `apiKey: local`.
381
+ */
382
+ apiKeySecretName?: string;
383
+ }
384
+
385
+ /** Field-level patch for an existing provider; `null` clears the field. */
386
+ export type DecisionProviderPatch = DecisionModelPatch;
387
+
388
+ function requireDecisionProvidersMap(loaded: LoadedConfig): YAMLMap {
389
+ const map = loaded.doc.get("decisionProviders");
390
+ if (map === undefined || map === null) {
391
+ const created = loaded.doc.createNode({}) as YAMLMap;
392
+ loaded.doc.set("decisionProviders", created);
393
+ return created;
394
+ }
395
+ if (!isMap(map)) throw new ConfigError("decisionProviders must be a map keyed by provider id", loaded.path);
396
+ return map;
397
+ }
398
+
399
+ /** Find a decisionProviders entry node by provider id (the map key). */
400
+ function findDecisionProviderNode(loaded: LoadedConfig, provider: string): { map: YAMLMap; node: YAMLMap } {
401
+ const map = requireDecisionProvidersMap(loaded);
402
+ const node = map.get(provider, true);
403
+ if (node === undefined || node === null || !isMap(node)) {
404
+ throw new ConfigError(`decisionProviders.${provider} not found`, loaded.path);
405
+ }
406
+ return { map, node };
407
+ }
408
+
409
+ /**
410
+ * Add a provider's connection details. One entry serves every decision model of
411
+ * that provider, so this is what a new decision model normally needs - not a
412
+ * `decisionModels` entry per model.
413
+ */
414
+ export function addDecisionProvider(loaded: LoadedConfig, input: DecisionProviderInput): void {
415
+ const map = requireDecisionProvidersMap(loaded);
416
+ if (map.has(input.provider)) {
417
+ throw new ConfigError(`decisionProviders already contains "${input.provider}"`, loaded.path);
418
+ }
419
+ map.set(
420
+ input.provider,
421
+ decisionModelToNode(loaded.doc, {
422
+ address: input.provider,
423
+ ...(input.baseUrl !== undefined ? { baseUrl: input.baseUrl } : {}),
424
+ ...(input.apiKeySecretName !== undefined ? { apiKeySecretName: input.apiKeySecretName } : {}),
425
+ }),
426
+ );
427
+ }
428
+
429
+ /** Patch one provider's connection details. */
430
+ export function updateDecisionProvider(loaded: LoadedConfig, provider: string, patch: DecisionProviderPatch): void {
431
+ const { map, node } = findDecisionProviderNode(loaded, provider);
432
+ if (patch.baseUrl !== undefined) {
433
+ if (patch.baseUrl === null) {
434
+ node.delete("baseUrl");
435
+ // apiKey is only valid alongside baseUrl; clearing baseUrl clears it.
436
+ node.delete("apiKey");
437
+ } else {
438
+ node.set("baseUrl", patch.baseUrl);
439
+ if (!node.has("apiKey")) node.set("apiKey", "local");
440
+ }
441
+ }
442
+ if (patch.apiKeySecretName !== undefined) {
443
+ node.set("apiKey", patch.apiKeySecretName === null ? "local" : `secret:${patch.apiKeySecretName}`);
444
+ }
445
+ // An update that clears the whole connection would leave an empty `{}`
446
+ // behind; drop the key instead, like removeDecisionProvider does.
447
+ if (node.get("baseUrl") === undefined && node.get("apiKey") === undefined) {
448
+ map.delete(provider);
449
+ if (map.items.length === 0) loaded.doc.delete("decisionProviders");
450
+ }
451
+ }
452
+
453
+ /**
454
+ * Remove a provider's connection details. Per-address `decisionModels` entries
455
+ * are left alone (they may carry their own endpoint), and chains are not
456
+ * rewritten: their addresses simply fall back to catalog resolution.
457
+ */
458
+ export function removeDecisionProvider(loaded: LoadedConfig, provider: string): void {
459
+ const { map } = findDecisionProviderNode(loaded, provider);
460
+ map.delete(provider);
461
+ // An empty map is litter: drop the key so the file reads as if no entry was ever made.
462
+ if (map.items.length === 0) loaded.doc.delete("decisionProviders");
463
+ }
464
+
465
+ /** How many configured models use a decision model from this provider. */
466
+ export function countDecisionProviderReferences(loaded: LoadedConfig, provider: string): number {
467
+ let count = 0;
468
+ for (const item of requireModelsSeq(loaded).items) {
469
+ if (item === null || !isMap(item)) continue;
470
+ const address = item.get("decisionModel");
471
+ if (typeof address === "string" && address.slice(0, address.indexOf("/")) === provider) count += 1;
472
+ }
473
+ return count;
474
+ }
475
+
369
476
  /**
370
477
  * Set or clear a model's `idleReset:` option. A duration ("30m", "2h", ...)
371
478
  * returns to the head of the fallback list after that much idle time;
package/src/config.ts CHANGED
@@ -1,12 +1,15 @@
1
1
  /**
2
2
  * User-facing switchback config loader.
3
3
  *
4
- * Config file (YAML, optional): `~/.config/switchback/switchback.yaml`, one file
5
- * shared by every host. There are no host-specific or per-project layers: a
6
- * host-specific overlay would let the two hosts disagree about the chain set,
7
- * and they do not share a model catalog, so an entry one host cannot resolve
8
- * would become a dead fallback on the other (`switchback-wix.12`). When the file
9
- * is absent, the built-in DEFAULT_CONFIG applies.
4
+ * Config files (YAML): `~/.config/switchback/switchback.yaml` is the shared
5
+ * base read by every host, with optional per-host overlays applied on top:
6
+ * `switchback.pi.yaml` for pi, `switchback.oc.yaml` for OpenCode. A host that
7
+ * passes its overlay to `loadConfig()` reads base + its own overlay merged;
8
+ * a host that passes nothing reads the base alone. Overlays are partial files
9
+ * (every section optional): models with an id already in the base replace
10
+ * that entry, new ids are appended; `decisionProviders`/`decisionModels`
11
+ * merge per key with the overlay winning; `debug` in the overlay wins when
12
+ * present. Overlay files are optional and missing files are simply skipped.
10
13
  *
11
14
  * The location is `~/.config/switchback/` - not a host's private directory - so
12
15
  * the same config serves pi and OpenCode. Override the directory with
@@ -40,6 +43,8 @@ import type {
40
43
  DecisionModelConfig,
41
44
  DecisionModelEntry,
42
45
  DecisionModelId,
46
+ DecisionProviderConfig,
47
+ DecisionProviderEntry,
43
48
  ModelId,
44
49
  ResolvedSwitchbackConfig,
45
50
  ResolvedSwitchbackFileConfig,
@@ -53,7 +58,7 @@ const VIRTUAL_ID = "auto";
53
58
  const CONFIG_BASENAME = "switchback";
54
59
 
55
60
  /** Recognised keys, per level. Anything else is reported as a warning, not an error. */
56
- const FILE_KEYS = ["models", "decisionModels", "debug"] as const;
61
+ const FILE_KEYS = ["models", "decisionProviders", "decisionModels", "debug"] as const;
57
62
  const MODEL_KEYS = ["id", "name", "fallbacks", "decisionModel", "idleReset"] as const;
58
63
  const DECISION_MODEL_KEYS = ["baseUrl", "apiKey"] as const;
59
64
 
@@ -128,19 +133,54 @@ export function switchbackStateDir(): string {
128
133
  }
129
134
 
130
135
  /**
131
- * Where the user config lives. One file, shared by every host:
132
- * `~/.config/switchback/switchback.yaml`. There are no host-specific or
133
- * project-local files - a host that reads switchback reads exactly this file
134
- * (`switchback-wix.12`).
136
+ * Where the user config lives. The shared base every host reads:
137
+ * `~/.config/switchback/switchback.yaml`. Per-host overlays
138
+ * (`configOverlayPath()`) layer on top of this file - see `loadConfig()`.
135
139
  */
136
140
  export function configFilePath(): string {
137
141
  return join(switchbackConfigDir(), `${CONFIG_BASENAME}.yaml`);
138
142
  }
139
143
 
144
+ /** Which host's overlay to apply in `loadConfig()`. */
145
+ export type SwitchbackHost = "pi" | "opencode";
146
+
147
+ /** Overlay filenames, per host. Optional partial files merged over the base. */
148
+ const OVERLAY_BASENAMES: Record<SwitchbackHost, string> = {
149
+ pi: `${CONFIG_BASENAME}.pi`,
150
+ opencode: `${CONFIG_BASENAME}.oc`,
151
+ };
152
+
153
+ /**
154
+ * Where a host's overlay lives, when it has one:
155
+ * `~/.config/switchback/switchback.pi.yaml` for pi,
156
+ * `~/.config/switchback/switchback.oc.yaml` for OpenCode.
157
+ * The file is optional - absence means "no overlay".
158
+ */
159
+ export function configOverlayPath(host: SwitchbackHost): string {
160
+ return join(switchbackConfigDir(), `${OVERLAY_BASENAMES[host]}.yaml`);
161
+ }
162
+
140
163
  function isRecord(value: unknown): value is Record<string, unknown> {
141
164
  return typeof value === "object" && value !== null && !Array.isArray(value);
142
165
  }
143
166
 
167
+ /**
168
+ * Validate a provider id: a single YAML map key that names a provider, without
169
+ * the "/" a decision-model address has (the model id is the second half of the
170
+ * address and never part of the provider key).
171
+ */
172
+ function parseProviderId(value: string, where: string): string {
173
+ if (value.length === 0) throw new ConfigError(`${where} must be a non-empty provider id`, where);
174
+ if (value.includes("/")) {
175
+ throw new ConfigError(
176
+ `${where} must be a provider id (e.g. "ollama"), not a "provider/model" address - the model id belongs in models[].decisionModel`,
177
+ where,
178
+ );
179
+ }
180
+ if (/\s/u.test(value)) throw new ConfigError(`${where} must not contain whitespace`, where);
181
+ return value;
182
+ }
183
+
144
184
  function parseModelId(value: unknown, where: string): ModelId {
145
185
  if (typeof value !== "string") throw new ConfigError(`${where} must be a string (e.g. "provider/id")`, where);
146
186
  if (value.indexOf("/") <= 0) throw new ConfigError(`${where} must be of the form "provider/id"`, where);
@@ -190,8 +230,92 @@ function splitAddress(address: DecisionModelId, where: string): { provider: stri
190
230
  }
191
231
 
192
232
  /**
193
- * Parse the `decisionModels:` map. Each key is a decision-model address; the
194
- * value carries the connection details for a direct SystemOne endpoint.
233
+ * Validate one connection-details map value. `baseUrl` and `apiKey` come as a
234
+ * pair: a direct endpoint needs a bearer token even when the endpoint ignores it
235
+ * (`apiKey: local`), and a token without an endpoint would be dead weight.
236
+ *
237
+ * No warning is emitted when both are absent: the address then resolves through
238
+ * the host's classifier catalog, which is a perfectly valid configuration (pi
239
+ * does exactly that). Whether that is a problem is a *host* question - pi has a
240
+ * catalog, OpenCode does not - so it is answered where the host knows, not here.
241
+ */
242
+ function parseConnectionEntry(rawEntry: unknown, where: string, path: string, warnings: string[]): DecisionModelEntry {
243
+ if (!isRecord(rawEntry)) throw new ConfigError(`${where} must be an object with baseUrl and apiKey`, path);
244
+ noteUnknownKeys(rawEntry, DECISION_MODEL_KEYS, where, warnings);
245
+
246
+ const rawBaseUrl = rawEntry["baseUrl"];
247
+ let baseUrl: string | undefined;
248
+ if (rawBaseUrl !== undefined) {
249
+ if (typeof rawBaseUrl !== "string" || rawBaseUrl.length === 0) {
250
+ throw new ConfigError(`${where}.baseUrl must be a non-empty URL string`, path);
251
+ }
252
+ let parsed: URL;
253
+ try {
254
+ parsed = new URL(rawBaseUrl);
255
+ } catch {
256
+ throw new ConfigError(`${where}.baseUrl is not a valid URL: ${rawBaseUrl}`, path);
257
+ }
258
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
259
+ throw new ConfigError(`${where}.baseUrl must be http(s), got ${parsed.protocol}`, path);
260
+ }
261
+ baseUrl = rawBaseUrl;
262
+ }
263
+
264
+ const rawApiKey = rawEntry["apiKey"];
265
+ let apiKey: string | undefined;
266
+ if (rawApiKey !== undefined) {
267
+ if (typeof rawApiKey !== "string" || rawApiKey.length === 0) {
268
+ throw new ConfigError(`${where}.apiKey must be a non-empty string`, path);
269
+ }
270
+ apiKey = rawApiKey;
271
+ }
272
+ if (baseUrl !== undefined && apiKey === undefined) {
273
+ throw new ConfigError(
274
+ `${where}.apiKey is required with baseUrl - use "local" for endpoints that ignore the bearer token`,
275
+ path,
276
+ );
277
+ }
278
+ if (apiKey !== undefined && baseUrl === undefined) {
279
+ throw new ConfigError(`${where}.apiKey requires ${where}.baseUrl`, path);
280
+ }
281
+ return {
282
+ ...(baseUrl !== undefined ? { baseUrl } : {}),
283
+ ...(apiKey !== undefined ? { apiKey } : {}),
284
+ };
285
+ }
286
+
287
+ /**
288
+ * Parse the `decisionProviders:` map: connection details keyed by provider id,
289
+ * shared by every decision model of that provider.
290
+ */
291
+ function parseDecisionProviders(
292
+ value: unknown,
293
+ path: string,
294
+ warnings: string[],
295
+ ): Record<string, DecisionProviderEntry> | undefined {
296
+ if (value === undefined) return undefined;
297
+ if (Array.isArray(value)) {
298
+ warnings.push(
299
+ `decisionProviders is a map keyed by provider id (e.g. ollama: { baseUrl, apiKey }); the list form was ignored (${path})`,
300
+ );
301
+ return undefined;
302
+ }
303
+ if (!isRecord(value)) throw new ConfigError("decisionProviders must be an object keyed by provider id", path);
304
+ const entries: Record<string, DecisionProviderEntry> = {};
305
+ for (const [provider, rawEntry] of Object.entries(value)) {
306
+ const where = `decisionProviders.${provider}`;
307
+ parseProviderId(provider, where);
308
+ entries[provider] = parseConnectionEntry(rawEntry, where, path, warnings);
309
+ }
310
+ return entries;
311
+ }
312
+
313
+ /**
314
+ * Parse the `decisionModels:` map: per-address connection overrides. Each key is
315
+ * a decision-model address; the value carries the connection details for a
316
+ * direct SystemOne endpoint. Normally the same details live once in
317
+ * `decisionProviders:` instead; this map exists for the one-model-of-a-provider
318
+ * case and for files written before the provider section existed.
195
319
  */
196
320
  function parseDecisionModels(
197
321
  value: unknown,
@@ -210,64 +334,17 @@ function parseDecisionModels(
210
334
  for (const [address, rawEntry] of Object.entries(value)) {
211
335
  const where = `decisionModels.${address}`;
212
336
  parseModelId(address, where);
213
- if (!isRecord(rawEntry)) throw new ConfigError(`${where} must be an object with baseUrl and apiKey`, path);
214
- noteUnknownKeys(rawEntry, DECISION_MODEL_KEYS, where, warnings);
215
-
216
- const rawBaseUrl = rawEntry["baseUrl"];
217
- let baseUrl: string | undefined;
218
- if (rawBaseUrl !== undefined) {
219
- if (typeof rawBaseUrl !== "string" || rawBaseUrl.length === 0) {
220
- throw new ConfigError(`${where}.baseUrl must be a non-empty URL string`, path);
221
- }
222
- let parsed: URL;
223
- try {
224
- parsed = new URL(rawBaseUrl);
225
- } catch {
226
- throw new ConfigError(`${where}.baseUrl is not a valid URL: ${rawBaseUrl}`, path);
227
- }
228
- if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
229
- throw new ConfigError(`${where}.baseUrl must be http(s), got ${parsed.protocol}`, path);
230
- }
231
- baseUrl = rawBaseUrl;
232
- }
233
-
234
- const rawApiKey = rawEntry["apiKey"];
235
- let apiKey: string | undefined;
236
- if (rawApiKey !== undefined) {
237
- if (typeof rawApiKey !== "string" || rawApiKey.length === 0) {
238
- throw new ConfigError(`${where}.apiKey must be a non-empty string`, path);
239
- }
240
- apiKey = rawApiKey;
241
- }
242
- if (baseUrl !== undefined && apiKey === undefined) {
243
- // A direct endpoint needs a bearer token to send. Local servers ignore
244
- // it, but the token is still the thing that makes "direct endpoint"
245
- // explicit rather than a silent default.
246
- throw new ConfigError(
247
- `${where}.apiKey is required with baseUrl - use "local" for endpoints that ignore the bearer token`,
248
- path,
249
- );
250
- }
251
- if (apiKey !== undefined && baseUrl === undefined) {
252
- throw new ConfigError(`${where}.apiKey requires ${where}.baseUrl`, path);
253
- }
254
- if (baseUrl === undefined) {
255
- warnings.push(
256
- `${where} has no connection details; it can only resolve through a classifier catalog (pi has one, OpenCode does not)`,
257
- );
258
- }
259
- entries[address] = {
260
- ...(baseUrl !== undefined ? { baseUrl } : {}),
261
- ...(apiKey !== undefined ? { apiKey } : {}),
262
- };
337
+ entries[address] = parseConnectionEntry(rawEntry, where, path, warnings);
263
338
  }
264
339
  return entries;
265
340
  }
266
341
 
267
342
  /**
268
- * Resolve a chain's `decisionModel:` address against the `decisionModels:` map.
343
+ * Resolve a chain's `decisionModel:` address against the config's connection
344
+ * details.
269
345
  *
270
- * A map entry with a `baseUrl` pins the endpoint. Without one the address stays
346
+ * Precedence: a `decisionModels:` entry at the exact address wins, otherwise the
347
+ * provider's `decisionProviders:` entry applies. With neither the address stays
271
348
  * catalog-resolved, which pi can do and OpenCode cannot - that stays a visible
272
349
  * "no classifier" cycle there instead of a load error, because the same file is
273
350
  * valid on pi.
@@ -275,10 +352,11 @@ function parseDecisionModels(
275
352
  export function resolveDecisionModel(
276
353
  decisionModels: Record<DecisionModelId, DecisionModelConfig> | undefined,
277
354
  address: DecisionModelId | undefined,
355
+ decisionProviders?: Record<string, DecisionProviderConfig>,
278
356
  ): DecisionModelConfig | undefined {
279
357
  if (address === undefined) return undefined;
280
358
  const { provider, id } = splitAddress(address, "decisionModel");
281
- const entry = decisionModels?.[address];
359
+ const entry = decisionModels?.[address] ?? decisionProviders?.[provider];
282
360
  return {
283
361
  provider,
284
362
  id,
@@ -292,6 +370,8 @@ export type {
292
370
  SwitchbackFileConfig,
293
371
  DecisionModelConfig,
294
372
  DecisionModelEntry,
373
+ DecisionProviderEntry,
374
+ DecisionProviderConfig,
295
375
  DecisionModelId,
296
376
  } from "./types.ts";
297
377
 
@@ -365,11 +445,28 @@ export function resolveSecretApiKey(
365
445
  return value;
366
446
  }
367
447
 
368
- /** Resolve every chain's `decisionModel:` address against the map, and the map's secret refs. */
448
+ /**
449
+ * Resolve the config into what the router consumes: provider/address connection
450
+ * details with their secret refs resolved, and every chain's address merged with
451
+ * the connection details it inherits (address override first, then provider).
452
+ */
369
453
  function resolveFile(
370
454
  file: SwitchbackFileConfig,
371
455
  secrets: { get(name: string): string | undefined } | undefined = undefined,
372
456
  ): ResolvedSwitchbackFileConfig {
457
+ const resolvedDecisionProviders: Record<string, DecisionProviderConfig> | undefined =
458
+ file.decisionProviders === undefined
459
+ ? undefined
460
+ : Object.fromEntries(
461
+ Object.entries(file.decisionProviders).map(([provider, entry]) => {
462
+ const apiKey = resolveSecretApiKey(entry.apiKey, secrets);
463
+ const descriptor: DecisionProviderConfig = {
464
+ ...(entry.baseUrl !== undefined ? { baseUrl: entry.baseUrl } : {}),
465
+ ...(apiKey !== undefined ? { apiKey } : {}),
466
+ };
467
+ return [provider, descriptor];
468
+ }),
469
+ );
373
470
  const resolvedDecisionModels: Record<DecisionModelId, DecisionModelConfig> | undefined =
374
471
  file.decisionModels === undefined
375
472
  ? undefined
@@ -389,9 +486,12 @@ function resolveFile(
389
486
  return {
390
487
  models: file.models.map((model) => {
391
488
  const { decisionModel, ...rest } = model;
392
- const resolved = resolveDecisionModel(resolvedDecisionModels, decisionModel);
489
+ const resolved = resolveDecisionModel(resolvedDecisionModels, decisionModel, resolvedDecisionProviders);
393
490
  return resolved === undefined ? rest : { ...rest, decisionModel: resolved };
394
491
  }),
492
+ ...(resolvedDecisionProviders !== undefined && Object.keys(resolvedDecisionProviders).length > 0
493
+ ? { decisionProviders: resolvedDecisionProviders }
494
+ : {}),
395
495
  ...(resolvedDecisionModels !== undefined && Object.keys(resolvedDecisionModels).length > 0
396
496
  ? { decisionModels: resolvedDecisionModels }
397
497
  : {}),
@@ -432,26 +532,107 @@ function parseFileConfig(value: unknown, path: string, warnings: string[]): Swit
432
532
  if (rawDebug !== undefined && typeof rawDebug !== "boolean") {
433
533
  throw new ConfigError("debug must be a boolean", path);
434
534
  }
535
+ const decisionProviders = parseDecisionProviders(value["decisionProviders"], path, warnings);
435
536
  const decisionModels = parseDecisionModels(value["decisionModels"], path, warnings);
436
- // A `decisionModels` entry no chain references is harmless but almost always a
437
- // leftover: warn (do not fail) so the block does not quietly rot.
438
- if (decisionModels !== undefined) {
439
- const referenced = new Set(parsed.map((model) => model.decisionModel).filter((id) => id !== undefined));
440
- for (const address of Object.keys(decisionModels)) {
441
- if (!referenced.has(address)) {
442
- warnings.push(
443
- `decisionModels.${address} is not referenced by any models[].decisionModel and was ignored`,
444
- );
445
- }
446
- }
447
- }
537
+ // Unreferenced connection details are not a problem: a provider entry is shared
538
+ // by every model of that provider (and may be prepared before a chain names
539
+ // one), so nothing is "ignored" and nothing can rot. The earlier warning here
540
+ // read like a failure report for a perfectly valid config.
448
541
  return {
449
542
  models: parsed,
543
+ ...(decisionProviders !== undefined ? { decisionProviders } : {}),
544
+ ...(decisionModels !== undefined ? { decisionModels } : {}),
545
+ ...(rawDebug !== undefined ? { debug: rawDebug } : {}),
546
+ };
547
+ }
548
+
549
+ /**
550
+ * Parse a per-host overlay file. Unlike the base, every section is optional:
551
+ * an overlay may carry only `decisionModels`, only extra `models`, or any
552
+ * combination. Model entries follow the same rules as the base file.
553
+ */
554
+ function parseOverlayFileConfig(value: unknown, path: string, warnings: string[]): SwitchbackFileConfig {
555
+ if (value === null || value === undefined) return { models: [] };
556
+ if (!isRecord(value)) throw new ConfigError("root must be an object", path);
557
+ noteUnknownKeys(value, FILE_KEYS, "config", warnings);
558
+ const models = value["models"];
559
+ const parsedAll = models === undefined ? [] : parseOverlayModels(models, path, warnings);
560
+ const rawDebug = value["debug"];
561
+ if (rawDebug !== undefined && typeof rawDebug !== "boolean") {
562
+ throw new ConfigError("debug must be a boolean", path);
563
+ }
564
+ const decisionProviders = parseDecisionProviders(value["decisionProviders"], path, warnings);
565
+ const decisionModels = parseDecisionModels(value["decisionModels"], path, warnings);
566
+ return {
567
+ models: parsedAll,
568
+ ...(decisionProviders !== undefined ? { decisionProviders } : {}),
450
569
  ...(decisionModels !== undefined ? { decisionModels } : {}),
451
570
  ...(rawDebug !== undefined ? { debug: rawDebug } : {}),
452
571
  };
453
572
  }
454
573
 
574
+ function parseOverlayModels(value: unknown, path: string, warnings: string[]): SwitchbackConfig[] {
575
+ if (!Array.isArray(value)) throw new ConfigError("models must be an array", path);
576
+ return value.map((entry, i) => parseSwitchbackModel(entry, i, warnings));
577
+ }
578
+
579
+ /**
580
+ * Merge a host overlay over the base config. Models match by id: an overlay
581
+ * entry with an id already in the base replaces it in place, a new id is
582
+ * appended. `decisionProviders`/`decisionModels` merge per key with the
583
+ * overlay winning; `debug` in the overlay wins when present.
584
+ */
585
+ export function mergeFileConfigs(base: SwitchbackFileConfig, overlay: SwitchbackFileConfig): SwitchbackFileConfig {
586
+ const merged = base.models.slice();
587
+ const indexById = new Map(merged.map((m, i) => [m.id, i]));
588
+ for (const model of overlay.models) {
589
+ const at = indexById.get(model.id);
590
+ if (at === undefined) {
591
+ indexById.set(model.id, merged.length);
592
+ merged.push(model);
593
+ } else {
594
+ merged[at] = model;
595
+ }
596
+ }
597
+ return {
598
+ models: merged,
599
+ ...(base.decisionProviders !== undefined || overlay.decisionProviders !== undefined
600
+ ? { decisionProviders: { ...base.decisionProviders, ...overlay.decisionProviders } }
601
+ : {}),
602
+ ...(base.decisionModels !== undefined || overlay.decisionModels !== undefined
603
+ ? { decisionModels: { ...base.decisionModels, ...overlay.decisionModels } }
604
+ : {}),
605
+ ...(overlay.debug !== undefined
606
+ ? { debug: overlay.debug }
607
+ : base.debug !== undefined
608
+ ? { debug: base.debug }
609
+ : {}),
610
+ };
611
+ }
612
+
613
+ function readAndParseOverlay(host: SwitchbackHost, warnings: string[]): SwitchbackFileConfig | undefined {
614
+ const path = configOverlayPath(host);
615
+ if (!existsSync(path)) return undefined;
616
+ return parseOverlay(path, warnings);
617
+ }
618
+
619
+ function parseOverlay(path: string, warnings: string[]): SwitchbackFileConfig {
620
+ if (path.endsWith(".json")) {
621
+ throw new ConfigError("switchback user config is YAML only; rename to switchback.oc.yaml", path);
622
+ }
623
+ const text = readFileSync(path, "utf8");
624
+ let raw: unknown;
625
+ try {
626
+ raw = parseYaml(text);
627
+ } catch (error) {
628
+ throw new ConfigError(
629
+ `switchback config is not valid YAML: ${error instanceof Error ? error.message.split("\n")[0] : String(error)}`,
630
+ path,
631
+ );
632
+ }
633
+ return parseOverlayFileConfig(raw, path, warnings);
634
+ }
635
+
455
636
  function readAndParse(path: string, warnings: string[]): SwitchbackFileConfig {
456
637
  // The only .json file in this project's surface is the simulate fixture;
457
638
  // anything else ending in .json is a user config mistake.
@@ -475,14 +656,12 @@ function readAndParse(path: string, warnings: string[]): SwitchbackFileConfig {
475
656
  }
476
657
 
477
658
  /**
478
- * Load the active switchback configuration from `configFilePath()`.
479
- *
480
- * Exactly one file is read. There is no aggregation and no precedence: a
481
- * host-specific overlay would let the two hosts disagree about the chain set,
482
- * and they do not share a model catalog, so an entry one host cannot resolve
483
- * would become a dead fallback on the other. A file that exists but fails to
484
- * parse or validate throws immediately. With no file present, DEFAULT_CONFIG
485
- * (empty fallbacks, fail-fast) applies and `source` is `<default>`.
659
+ * Load the active switchback configuration: the shared base
660
+ * (`configFilePath()`) plus, when `host` is given, that host's overlay
661
+ * (`configOverlayPath(host)`) merged on top. A missing overlay is skipped;
662
+ * a present-but-broken one throws, like the base. With no base file present
663
+ * (and no overlay), DEFAULT_CONFIG (empty fallbacks, fail-fast) applies and
664
+ * `source` is `<default>`; otherwise `source` names the files that were read.
486
665
  */
487
666
 
488
667
  /** A store capable of resolving `secret:<name>` apiKey references. */
@@ -499,20 +678,36 @@ export interface SecretResolver {
499
678
  * `createSecretStore()`; tests pass a fake or leave it undefined.
500
679
  *
501
680
  * `warnings` carries recognised-but-suspicious findings (unknown keys, retired
502
- * keys, unreferenced decision models). They never fail the load: a host shows
503
- * them through its own notify channel.
681
+ * keys, malformed optional values). They never fail the load: a host shows them
682
+ * through its own notify channel. Host *capability* findings are deliberately
683
+ * not here - a decision model that relies on a classifier catalog is fine on pi
684
+ * and impossible on OpenCode, so that judgement belongs to the host
685
+ * (`packages/opencode/src/decision-model-check.ts`).
504
686
  */
505
- export function loadConfig(secrets?: SecretResolver): {
687
+ export function loadConfig(
688
+ secrets?: SecretResolver,
689
+ host?: SwitchbackHost,
690
+ ): {
506
691
  config: ResolvedSwitchbackFileConfig;
507
692
  source: string;
508
693
  warnings: string[];
509
694
  } {
510
695
  const path = configFilePath();
511
- if (!existsSync(path)) return { config: DEFAULT_CONFIG, source: "<default>", warnings: [] };
512
-
696
+ const hasBase = existsSync(path);
513
697
  const warnings: string[] = [];
514
- const parsed = readAndParse(path, warnings);
515
- return { config: resolveFile(parsed, secrets), source: resolve(path), warnings };
698
+ const base = hasBase ? readAndParse(path, warnings) : undefined;
699
+ const overlay = host === undefined ? undefined : readAndParseOverlay(host, warnings);
700
+ if (base === undefined && overlay === undefined)
701
+ return { config: DEFAULT_CONFIG, source: "<default>", warnings: [] };
702
+
703
+ const merged = base !== undefined && overlay !== undefined ? mergeFileConfigs(base, overlay) : (base ?? overlay)!;
704
+ const source =
705
+ base !== undefined && overlay !== undefined
706
+ ? `${resolve(path)}+${resolve(configOverlayPath(host!))}`
707
+ : base !== undefined
708
+ ? resolve(path)
709
+ : resolve(configOverlayPath(host!));
710
+ return { config: resolveFile(merged, secrets), source, warnings };
516
711
  }
517
712
 
518
713
  /**
package/src/index.ts CHANGED
@@ -88,28 +88,41 @@ export {
88
88
  piConfigDir,
89
89
  switchbackConfigDir,
90
90
  configFilePath,
91
+ configOverlayPath,
92
+ mergeFileConfigs,
91
93
  switchbackStateDir,
92
94
  resolveDecisionModel,
93
95
  resolveSecretApiKey,
94
96
  validateFileConfig,
95
97
  createConfigWarningReporter,
96
98
  } from "./config.ts";
97
- export type { SwitchbackConfig, SwitchbackFileConfig, DecisionModelConfig, SecretResolver } from "./config.ts";
99
+ export type {
100
+ SwitchbackConfig,
101
+ SwitchbackFileConfig,
102
+ DecisionModelConfig,
103
+ SecretResolver,
104
+ SwitchbackHost,
105
+ } from "./config.ts";
98
106
  export type {
99
107
  DecisionModelEntry,
108
+ DecisionProviderConfig,
109
+ DecisionProviderEntry,
100
110
  DecisionModelId,
101
111
  ResolvedSwitchbackConfig,
102
112
  ResolvedSwitchbackFileConfig,
103
113
  } from "./types.ts";
104
114
  export {
105
115
  addDecisionModel,
116
+ addDecisionProvider,
106
117
  addFallback,
107
118
  addVirtualModel,
108
119
  countDecisionModelReferences,
120
+ countDecisionProviderReferences,
109
121
  loadConfigFile,
110
122
  moveFallback,
111
123
  readConfigFile,
112
124
  removeDecisionModel,
125
+ removeDecisionProvider,
113
126
  removeFallback,
114
127
  removeVirtualModel,
115
128
  renameDecisionModel,
@@ -121,14 +134,27 @@ export {
121
134
  setIdleReset,
122
135
  setVirtualModelName,
123
136
  updateDecisionModel,
137
+ updateDecisionProvider,
138
+ } from "./config-editor.ts";
139
+ export type {
140
+ DecisionModelInput,
141
+ DecisionModelPatch,
142
+ DecisionProviderInput,
143
+ DecisionProviderPatch,
144
+ LoadedConfig,
124
145
  } from "./config-editor.ts";
125
- export type { DecisionModelInput, DecisionModelPatch, LoadedConfig } from "./config-editor.ts";
126
146
  export {
127
147
  buildClassifierProviders,
128
148
  classifierBaseUrlNote,
129
149
  defaultDecisionModelName,
130
150
  directEndpointWouldClobber,
131
151
  } from "./classifier-catalog.ts";
152
+ export {
153
+ decisionModelConnection,
154
+ decisionModelsWithoutConnection,
155
+ referencedDecisionModelAddresses,
156
+ splitDecisionModelAddress,
157
+ } from "./classifier-connection.ts";
132
158
  export type {
133
159
  ClassifierModelSummary,
134
160
  ClassifierProviderOption,
package/src/types.ts CHANGED
@@ -31,17 +31,30 @@ export interface DecisionModelConfig {
31
31
  }
32
32
 
33
33
  /**
34
- * Connection details for one decision-model address - a `decisionModels:` map
35
- * value. `baseUrl` and `apiKey` come as a pair: a direct endpoint needs a bearer
36
- * token even when the endpoint ignores it (`apiKey: local`).
34
+ * Connection details for one classifier provider - a `decisionProviders:` map
35
+ * value, and also the shape of a per-address `decisionModels:` override.
36
+ * `baseUrl` and `apiKey` come as a pair: a direct endpoint needs a bearer token
37
+ * even when the endpoint ignores it (`apiKey: local`).
38
+ *
39
+ * The provider map is the normal place to put these: one entry serves every
40
+ * decision model of that provider (`ollama/tev1`, `ollama/tev1:0.8b`, ...), so a
41
+ * chain only names `provider/model` and no longer repeats endpoint details per
42
+ * model.
37
43
  */
38
- export interface DecisionModelEntry {
44
+ export interface DecisionProviderEntry {
39
45
  /** Direct SystemOne endpoint (http/https). */
40
46
  baseUrl?: string;
41
47
  /** Bearer token, or `secret:<name>`. Required with `baseUrl`. */
42
48
  apiKey?: string;
43
49
  }
44
50
 
51
+ /**
52
+ * Connection details for one decision-model address - a `decisionModels:` map
53
+ * value, and the per-address override that wins over `decisionProviders:`.
54
+ * Same shape as a provider entry; see `DecisionProviderEntry`.
55
+ */
56
+ export type DecisionModelEntry = DecisionProviderEntry;
57
+
45
58
  /**
46
59
  * A config entry after address resolution: `decisionModel` is always the
47
60
  * provider/id descriptor. This is what the router and the extension consume; the
@@ -51,11 +64,20 @@ export type ResolvedSwitchbackConfig = Omit<SwitchbackConfig, "decisionModel"> &
51
64
  decisionModel?: DecisionModelConfig;
52
65
  };
53
66
 
67
+ /** A classifier provider's connection details after secret resolution. */
68
+ export type DecisionProviderConfig = DecisionProviderEntry;
69
+
54
70
  /** A config file after aggregation and address resolution. */
55
71
  export interface ResolvedSwitchbackFileConfig {
56
72
  models: ResolvedSwitchbackConfig[];
57
73
  /** Resolved `decisionModels:` entries, keyed by their address. */
58
74
  decisionModels?: Record<DecisionModelId, DecisionModelConfig>;
75
+ /**
76
+ * Resolved `decisionProviders:` entries, keyed by provider id. Copied into
77
+ * every `models[].decisionModel` of that provider during resolution, so the
78
+ * router only ever reads a fully connected descriptor.
79
+ */
80
+ decisionProviders?: Record<string, DecisionProviderConfig>;
59
81
  debug?: boolean;
60
82
  }
61
83
 
@@ -75,9 +97,9 @@ export interface SwitchbackConfig {
75
97
  /** Ordered preference of physical models ("provider/id"). First entry is the preferred model. */
76
98
  fallbacks: ModelId[];
77
99
  /**
78
- * Decision model as "provider/model-id". Connection details for direct
79
- * endpoints live in the top-level `decisionModels:` map under the same
80
- * address. Absent: report and blind-cycle.
100
+ * Decision model as "provider/model-id". Connection details for a direct
101
+ * endpoint come from `decisionProviders:` (or a `decisionModels:` entry at
102
+ * this exact address, which wins). Absent: report and blind-cycle.
81
103
  */
82
104
  decisionModel?: DecisionModelId;
83
105
  /** Return to the head of the list after this much idle time (default `never`). */
@@ -88,9 +110,16 @@ export interface SwitchbackConfig {
88
110
  export interface SwitchbackFileConfig {
89
111
  models: SwitchbackConfig[];
90
112
  /**
91
- * Connection details for decision-model addresses that need a direct
92
- * SystemOne endpoint, keyed by the same "provider/model-id" address a chain
93
- * names in `decisionModel:`.
113
+ * Connection details for classifier providers that need a direct SystemOne
114
+ * endpoint, keyed by provider id. One entry covers every decision model of
115
+ * that provider, so `decisionModel: ollama/tev1` inherits
116
+ * `decisionProviders.ollama`. This is the normal place for endpoint + token.
117
+ */
118
+ decisionProviders?: Record<string, DecisionProviderEntry>;
119
+ /**
120
+ * Per-address connection overrides, keyed by "provider/model-id". Only needed
121
+ * when one model of a provider talks to a different endpoint than its
122
+ * provider entry; it wins over `decisionProviders:` for that address.
94
123
  */
95
124
  decisionModels?: Record<DecisionModelId, DecisionModelEntry>;
96
125
  /**