switchback-core 2026.11.2 → 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.2",
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",
@@ -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
@@ -130,15 +133,33 @@ export function switchbackStateDir(): string {
130
133
  }
131
134
 
132
135
  /**
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`).
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()`.
137
139
  */
138
140
  export function configFilePath(): string {
139
141
  return join(switchbackConfigDir(), `${CONFIG_BASENAME}.yaml`);
140
142
  }
141
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
+
142
163
  function isRecord(value: unknown): value is Record<string, unknown> {
143
164
  return typeof value === "object" && value !== null && !Array.isArray(value);
144
165
  }
@@ -218,12 +239,7 @@ function splitAddress(address: DecisionModelId, where: string): { provider: stri
218
239
  * does exactly that). Whether that is a problem is a *host* question - pi has a
219
240
  * catalog, OpenCode does not - so it is answered where the host knows, not here.
220
241
  */
221
- function parseConnectionEntry(
222
- rawEntry: unknown,
223
- where: string,
224
- path: string,
225
- warnings: string[],
226
- ): DecisionModelEntry {
242
+ function parseConnectionEntry(rawEntry: unknown, where: string, path: string, warnings: string[]): DecisionModelEntry {
227
243
  if (!isRecord(rawEntry)) throw new ConfigError(`${where} must be an object with baseUrl and apiKey`, path);
228
244
  noteUnknownKeys(rawEntry, DECISION_MODEL_KEYS, where, warnings);
229
245
 
@@ -530,6 +546,93 @@ function parseFileConfig(value: unknown, path: string, warnings: string[]): Swit
530
546
  };
531
547
  }
532
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 } : {}),
569
+ ...(decisionModels !== undefined ? { decisionModels } : {}),
570
+ ...(rawDebug !== undefined ? { debug: rawDebug } : {}),
571
+ };
572
+ }
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
+
533
636
  function readAndParse(path: string, warnings: string[]): SwitchbackFileConfig {
534
637
  // The only .json file in this project's surface is the simulate fixture;
535
638
  // anything else ending in .json is a user config mistake.
@@ -553,14 +656,12 @@ function readAndParse(path: string, warnings: string[]): SwitchbackFileConfig {
553
656
  }
554
657
 
555
658
  /**
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>`.
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.
564
665
  */
565
666
 
566
667
  /** A store capable of resolving `secret:<name>` apiKey references. */
@@ -583,17 +684,30 @@ export interface SecretResolver {
583
684
  * and impossible on OpenCode, so that judgement belongs to the host
584
685
  * (`packages/opencode/src/decision-model-check.ts`).
585
686
  */
586
- export function loadConfig(secrets?: SecretResolver): {
687
+ export function loadConfig(
688
+ secrets?: SecretResolver,
689
+ host?: SwitchbackHost,
690
+ ): {
587
691
  config: ResolvedSwitchbackFileConfig;
588
692
  source: string;
589
693
  warnings: string[];
590
694
  } {
591
695
  const path = configFilePath();
592
- if (!existsSync(path)) return { config: DEFAULT_CONFIG, source: "<default>", warnings: [] };
593
-
696
+ const hasBase = existsSync(path);
594
697
  const warnings: string[] = [];
595
- const parsed = readAndParse(path, warnings);
596
- 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 };
597
711
  }
598
712
 
599
713
  /**
package/src/index.ts CHANGED
@@ -88,13 +88,21 @@ 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,
100
108
  DecisionProviderConfig,