switchback-core 2026.11.2 → 2026.11.4

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.2",
3
+ "version": "2026.11.4",
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",
@@ -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
@@ -424,11 +427,7 @@ export function addDecisionProvider(loaded: LoadedConfig, input: DecisionProvide
424
427
  }
425
428
 
426
429
  /** Patch one provider's connection details. */
427
- export function updateDecisionProvider(
428
- loaded: LoadedConfig,
429
- provider: string,
430
- patch: DecisionProviderPatch,
431
- ): void {
430
+ export function updateDecisionProvider(loaded: LoadedConfig, provider: string, patch: DecisionProviderPatch): void {
432
431
  const { map, node } = findDecisionProviderNode(loaded, provider);
433
432
  if (patch.baseUrl !== undefined) {
434
433
  if (patch.baseUrl === null) {
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
@@ -115,6 +118,36 @@ export const SWITCHBACK_CONFIG_DIR_ENV = "SWITCHBACK_CONFIG_DIR";
115
118
  /** Env override naming the shared switchback state directory outright. */
116
119
  export const SWITCHBACK_DIR_ENV = "SWITCHBACK_DIR";
117
120
 
121
+ /** Env override for the `debug:` flag: any value but 0/false/off/no enables it. */
122
+ export const SWITCHBACK_DEBUG_ENV = "SWITCHBACK_DEBUG";
123
+
124
+ /**
125
+ * Read an environment override for the config's `debug:` flag.
126
+ *
127
+ * An empty or absent value means "no override" (`undefined`) so the config
128
+ * decides; `0`/`false`/`off`/`no` (any case) disable, anything else enables.
129
+ * Shared by both hosts: the documented `SWITCHBACK_DEBUG=1` override is a
130
+ * property of the config surface, not of one adapter.
131
+ */
132
+ export function debugFlag(value: string | undefined): boolean | undefined {
133
+ const v = value?.trim().toLowerCase();
134
+ if (v === undefined || v === "") return undefined;
135
+ return !(v === "0" || v === "false" || v === "off" || v === "no");
136
+ }
137
+
138
+ /**
139
+ * The effective diagnostics switch: `SWITCHBACK_DEBUG` when it says anything,
140
+ * otherwise the config's `debug:`, otherwise off. Both hosts resolve it here so
141
+ * the env override cannot drift between them (pi shipped it, OpenCode silently
142
+ * ignored it while the docs promised both).
143
+ */
144
+ export function resolveDebug(
145
+ configured: boolean | undefined,
146
+ env: Record<string, string | undefined> = process.env,
147
+ ): boolean {
148
+ return debugFlag(env[SWITCHBACK_DEBUG_ENV]) ?? configured ?? false;
149
+ }
150
+
118
151
  /**
119
152
  * The shared switchback state directory: blocks.json, crashes.json,
120
153
  * pin.json, secrets.json. Runtime files live here so they are account-scoped,
@@ -130,15 +163,33 @@ export function switchbackStateDir(): string {
130
163
  }
131
164
 
132
165
  /**
133
- * Where the user config lives. One file, shared by every host:
134
- * `~/.config/switchback/switchback.yaml`. There are no host-specific or
135
- * project-local files - a host that reads switchback reads exactly this file
136
- * (`switchback-wix.12`).
166
+ * Where the user config lives. The shared base every host reads:
167
+ * `~/.config/switchback/switchback.yaml`. Per-host overlays
168
+ * (`configOverlayPath()`) layer on top of this file - see `loadConfig()`.
137
169
  */
138
170
  export function configFilePath(): string {
139
171
  return join(switchbackConfigDir(), `${CONFIG_BASENAME}.yaml`);
140
172
  }
141
173
 
174
+ /** Which host's overlay to apply in `loadConfig()`. */
175
+ export type SwitchbackHost = "pi" | "opencode";
176
+
177
+ /** Overlay filenames, per host. Optional partial files merged over the base. */
178
+ const OVERLAY_BASENAMES: Record<SwitchbackHost, string> = {
179
+ pi: `${CONFIG_BASENAME}.pi`,
180
+ opencode: `${CONFIG_BASENAME}.oc`,
181
+ };
182
+
183
+ /**
184
+ * Where a host's overlay lives, when it has one:
185
+ * `~/.config/switchback/switchback.pi.yaml` for pi,
186
+ * `~/.config/switchback/switchback.oc.yaml` for OpenCode.
187
+ * The file is optional - absence means "no overlay".
188
+ */
189
+ export function configOverlayPath(host: SwitchbackHost): string {
190
+ return join(switchbackConfigDir(), `${OVERLAY_BASENAMES[host]}.yaml`);
191
+ }
192
+
142
193
  function isRecord(value: unknown): value is Record<string, unknown> {
143
194
  return typeof value === "object" && value !== null && !Array.isArray(value);
144
195
  }
@@ -218,12 +269,7 @@ function splitAddress(address: DecisionModelId, where: string): { provider: stri
218
269
  * does exactly that). Whether that is a problem is a *host* question - pi has a
219
270
  * catalog, OpenCode does not - so it is answered where the host knows, not here.
220
271
  */
221
- function parseConnectionEntry(
222
- rawEntry: unknown,
223
- where: string,
224
- path: string,
225
- warnings: string[],
226
- ): DecisionModelEntry {
272
+ function parseConnectionEntry(rawEntry: unknown, where: string, path: string, warnings: string[]): DecisionModelEntry {
227
273
  if (!isRecord(rawEntry)) throw new ConfigError(`${where} must be an object with baseUrl and apiKey`, path);
228
274
  noteUnknownKeys(rawEntry, DECISION_MODEL_KEYS, where, warnings);
229
275
 
@@ -403,28 +449,40 @@ const SECRETS_PREFIX = "secret:";
403
449
  /**
404
450
  * Resolve a `secret:<ref>` apiKey value against a secret store. Anything else
405
451
  * (the literal string `ollama`, a real token, etc.) passes through unchanged.
406
- * A missing reference throws `SecretsError` (re-raised by the caller) - a secret
407
- * reference that does not resolve is a user error, not a silent default.
452
+ *
453
+ * An unresolvable reference never fails the load: it becomes a warning and the
454
+ * key is dropped (`apiKey` resolves to `undefined`), so the entry keeps its
455
+ * `baseUrl` and every other decision model stays usable. One unavailable
456
+ * credential must not disable classification for the whole config - a host
457
+ * may have no store at all (OpenCode resolves refs against the environment),
458
+ * and a single unset variable is a routine state, not a broken file. The host
459
+ * reports the warning through its own notify channel.
408
460
  */
409
461
  export function resolveSecretApiKey(
410
462
  apiKey: string | undefined,
411
463
  secrets: { get(name: string): string | undefined } | undefined,
464
+ warnings: string[] = [],
465
+ where = "<config>",
412
466
  ): string | undefined {
413
467
  if (apiKey === undefined) return undefined;
414
468
  if (!apiKey.startsWith(SECRETS_PREFIX)) return apiKey;
415
- if (secrets === undefined) {
416
- throw new ConfigError(
417
- `apiKey starts with "${SECRETS_PREFIX}" but no secret store was provided - pass one to loadConfig() or define the key in the secret store first.`,
418
- "<config>",
419
- );
420
- }
421
469
  const name = apiKey.slice(SECRETS_PREFIX.length);
422
470
  if (name.length === 0) {
423
- throw new ConfigError(`apiKey "${SECRETS_PREFIX}" is missing a name`, "<config>");
471
+ warnings.push(`${where}.apiKey "${SECRETS_PREFIX}" is missing a name - the key is ignored`);
472
+ return undefined;
473
+ }
474
+ if (secrets === undefined) {
475
+ warnings.push(
476
+ `${where}.apiKey "${apiKey}" cannot resolve (this host provides no secret store) - the key is ignored`,
477
+ );
478
+ return undefined;
424
479
  }
425
480
  const value = secrets.get(name);
426
481
  if (value === undefined) {
427
- throw new ConfigError(`apiKey "${apiKey}" does not resolve (secret "${name}" is not in the store)`, "<config>");
482
+ warnings.push(
483
+ `${where}.apiKey "${apiKey}" does not resolve (secret "${name}" is not in the store) - the key is ignored`,
484
+ );
485
+ return undefined;
428
486
  }
429
487
  return value;
430
488
  }
@@ -437,13 +495,19 @@ export function resolveSecretApiKey(
437
495
  function resolveFile(
438
496
  file: SwitchbackFileConfig,
439
497
  secrets: { get(name: string): string | undefined } | undefined = undefined,
498
+ warnings: string[] = [],
440
499
  ): ResolvedSwitchbackFileConfig {
441
500
  const resolvedDecisionProviders: Record<string, DecisionProviderConfig> | undefined =
442
501
  file.decisionProviders === undefined
443
502
  ? undefined
444
503
  : Object.fromEntries(
445
504
  Object.entries(file.decisionProviders).map(([provider, entry]) => {
446
- const apiKey = resolveSecretApiKey(entry.apiKey, secrets);
505
+ const apiKey = resolveSecretApiKey(
506
+ entry.apiKey,
507
+ secrets,
508
+ warnings,
509
+ `decisionProviders.${provider}`,
510
+ );
447
511
  const descriptor: DecisionProviderConfig = {
448
512
  ...(entry.baseUrl !== undefined ? { baseUrl: entry.baseUrl } : {}),
449
513
  ...(apiKey !== undefined ? { apiKey } : {}),
@@ -457,7 +521,7 @@ function resolveFile(
457
521
  : Object.fromEntries(
458
522
  Object.entries(file.decisionModels).map(([address, entry]) => {
459
523
  const { provider, id } = splitAddress(address, `decisionModels.${address}`);
460
- const apiKey = resolveSecretApiKey(entry.apiKey, secrets);
524
+ const apiKey = resolveSecretApiKey(entry.apiKey, secrets, warnings, `decisionModels.${address}`);
461
525
  const descriptor: DecisionModelConfig = {
462
526
  provider,
463
527
  id,
@@ -530,6 +594,93 @@ function parseFileConfig(value: unknown, path: string, warnings: string[]): Swit
530
594
  };
531
595
  }
532
596
 
597
+ /**
598
+ * Parse a per-host overlay file. Unlike the base, every section is optional:
599
+ * an overlay may carry only `decisionModels`, only extra `models`, or any
600
+ * combination. Model entries follow the same rules as the base file.
601
+ */
602
+ function parseOverlayFileConfig(value: unknown, path: string, warnings: string[]): SwitchbackFileConfig {
603
+ if (value === null || value === undefined) return { models: [] };
604
+ if (!isRecord(value)) throw new ConfigError("root must be an object", path);
605
+ noteUnknownKeys(value, FILE_KEYS, "config", warnings);
606
+ const models = value["models"];
607
+ const parsedAll = models === undefined ? [] : parseOverlayModels(models, path, warnings);
608
+ const rawDebug = value["debug"];
609
+ if (rawDebug !== undefined && typeof rawDebug !== "boolean") {
610
+ throw new ConfigError("debug must be a boolean", path);
611
+ }
612
+ const decisionProviders = parseDecisionProviders(value["decisionProviders"], path, warnings);
613
+ const decisionModels = parseDecisionModels(value["decisionModels"], path, warnings);
614
+ return {
615
+ models: parsedAll,
616
+ ...(decisionProviders !== undefined ? { decisionProviders } : {}),
617
+ ...(decisionModels !== undefined ? { decisionModels } : {}),
618
+ ...(rawDebug !== undefined ? { debug: rawDebug } : {}),
619
+ };
620
+ }
621
+
622
+ function parseOverlayModels(value: unknown, path: string, warnings: string[]): SwitchbackConfig[] {
623
+ if (!Array.isArray(value)) throw new ConfigError("models must be an array", path);
624
+ return value.map((entry, i) => parseSwitchbackModel(entry, i, warnings));
625
+ }
626
+
627
+ /**
628
+ * Merge a host overlay over the base config. Models match by id: an overlay
629
+ * entry with an id already in the base replaces it in place, a new id is
630
+ * appended. `decisionProviders`/`decisionModels` merge per key with the
631
+ * overlay winning; `debug` in the overlay wins when present.
632
+ */
633
+ export function mergeFileConfigs(base: SwitchbackFileConfig, overlay: SwitchbackFileConfig): SwitchbackFileConfig {
634
+ const merged = base.models.slice();
635
+ const indexById = new Map(merged.map((m, i) => [m.id, i]));
636
+ for (const model of overlay.models) {
637
+ const at = indexById.get(model.id);
638
+ if (at === undefined) {
639
+ indexById.set(model.id, merged.length);
640
+ merged.push(model);
641
+ } else {
642
+ merged[at] = model;
643
+ }
644
+ }
645
+ return {
646
+ models: merged,
647
+ ...(base.decisionProviders !== undefined || overlay.decisionProviders !== undefined
648
+ ? { decisionProviders: { ...base.decisionProviders, ...overlay.decisionProviders } }
649
+ : {}),
650
+ ...(base.decisionModels !== undefined || overlay.decisionModels !== undefined
651
+ ? { decisionModels: { ...base.decisionModels, ...overlay.decisionModels } }
652
+ : {}),
653
+ ...(overlay.debug !== undefined
654
+ ? { debug: overlay.debug }
655
+ : base.debug !== undefined
656
+ ? { debug: base.debug }
657
+ : {}),
658
+ };
659
+ }
660
+
661
+ function readAndParseOverlay(host: SwitchbackHost, warnings: string[]): SwitchbackFileConfig | undefined {
662
+ const path = configOverlayPath(host);
663
+ if (!existsSync(path)) return undefined;
664
+ return parseOverlay(path, warnings);
665
+ }
666
+
667
+ function parseOverlay(path: string, warnings: string[]): SwitchbackFileConfig {
668
+ if (path.endsWith(".json")) {
669
+ throw new ConfigError("switchback user config is YAML only; rename to switchback.oc.yaml", path);
670
+ }
671
+ const text = readFileSync(path, "utf8");
672
+ let raw: unknown;
673
+ try {
674
+ raw = parseYaml(text);
675
+ } catch (error) {
676
+ throw new ConfigError(
677
+ `switchback config is not valid YAML: ${error instanceof Error ? error.message.split("\n")[0] : String(error)}`,
678
+ path,
679
+ );
680
+ }
681
+ return parseOverlayFileConfig(raw, path, warnings);
682
+ }
683
+
533
684
  function readAndParse(path: string, warnings: string[]): SwitchbackFileConfig {
534
685
  // The only .json file in this project's surface is the simulate fixture;
535
686
  // anything else ending in .json is a user config mistake.
@@ -553,14 +704,12 @@ function readAndParse(path: string, warnings: string[]): SwitchbackFileConfig {
553
704
  }
554
705
 
555
706
  /**
556
- * Load the active switchback configuration from `configFilePath()`.
557
- *
558
- * Exactly one file is read. There is no aggregation and no precedence: a
559
- * host-specific overlay would let the two hosts disagree about the chain set,
560
- * and they do not share a model catalog, so an entry one host cannot resolve
561
- * would become a dead fallback on the other. A file that exists but fails to
562
- * parse or validate throws immediately. With no file present, DEFAULT_CONFIG
563
- * (empty fallbacks, fail-fast) applies and `source` is `<default>`.
707
+ * Load the active switchback configuration: the shared base
708
+ * (`configFilePath()`) plus, when `host` is given, that host's overlay
709
+ * (`configOverlayPath(host)`) merged on top. A missing overlay is skipped;
710
+ * a present-but-broken one throws, like the base. With no base file present
711
+ * (and no overlay), DEFAULT_CONFIG (empty fallbacks, fail-fast) applies and
712
+ * `source` is `<default>`; otherwise `source` names the files that were read.
564
713
  */
565
714
 
566
715
  /** A store capable of resolving `secret:<name>` apiKey references. */
@@ -583,17 +732,30 @@ export interface SecretResolver {
583
732
  * and impossible on OpenCode, so that judgement belongs to the host
584
733
  * (`packages/opencode/src/decision-model-check.ts`).
585
734
  */
586
- export function loadConfig(secrets?: SecretResolver): {
735
+ export function loadConfig(
736
+ secrets?: SecretResolver,
737
+ host?: SwitchbackHost,
738
+ ): {
587
739
  config: ResolvedSwitchbackFileConfig;
588
740
  source: string;
589
741
  warnings: string[];
590
742
  } {
591
743
  const path = configFilePath();
592
- if (!existsSync(path)) return { config: DEFAULT_CONFIG, source: "<default>", warnings: [] };
593
-
744
+ const hasBase = existsSync(path);
594
745
  const warnings: string[] = [];
595
- const parsed = readAndParse(path, warnings);
596
- return { config: resolveFile(parsed, secrets), source: resolve(path), warnings };
746
+ const base = hasBase ? readAndParse(path, warnings) : undefined;
747
+ const overlay = host === undefined ? undefined : readAndParseOverlay(host, warnings);
748
+ if (base === undefined && overlay === undefined)
749
+ return { config: DEFAULT_CONFIG, source: "<default>", warnings: [] };
750
+
751
+ const merged = base !== undefined && overlay !== undefined ? mergeFileConfigs(base, overlay) : (base ?? overlay)!;
752
+ const source =
753
+ base !== undefined && overlay !== undefined
754
+ ? `${resolve(path)}+${resolve(configOverlayPath(host!))}`
755
+ : base !== undefined
756
+ ? resolve(path)
757
+ : resolve(configOverlayPath(host!));
758
+ return { config: resolveFile(merged, secrets, warnings), source, warnings };
597
759
  }
598
760
 
599
761
  /**
package/src/index.ts CHANGED
@@ -88,13 +88,24 @@ export {
88
88
  piConfigDir,
89
89
  switchbackConfigDir,
90
90
  configFilePath,
91
+ configOverlayPath,
92
+ mergeFileConfigs,
91
93
  switchbackStateDir,
92
94
  resolveDecisionModel,
93
95
  resolveSecretApiKey,
96
+ resolveDebug,
97
+ debugFlag,
98
+ SWITCHBACK_DEBUG_ENV,
94
99
  validateFileConfig,
95
100
  createConfigWarningReporter,
96
101
  } from "./config.ts";
97
- export type { SwitchbackConfig, SwitchbackFileConfig, DecisionModelConfig, SecretResolver } from "./config.ts";
102
+ export type {
103
+ SwitchbackConfig,
104
+ SwitchbackFileConfig,
105
+ DecisionModelConfig,
106
+ SecretResolver,
107
+ SwitchbackHost,
108
+ } from "./config.ts";
98
109
  export type {
99
110
  DecisionModelEntry,
100
111
  DecisionProviderConfig,