switchback-core 2026.10.15 → 2026.10.19

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.10.15",
3
+ "version": "2026.10.19",
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",
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Comment-preserving read-modify-write editor for a switchback.yaml layer.
2
+ * Comment-preserving read-modify-write editor for switchback.yaml.
3
3
  *
4
4
  * Design: `src/config.ts` parses user config with `yaml.parse()`, which
5
5
  * keeps values but discards comments - fine for loading, lossy for editing.
@@ -9,7 +9,7 @@
9
9
  * their comments survive, and only newly created content is synthesized.
10
10
  *
11
11
  * Validation lives in exactly one place. Every mutation is structural only
12
- * (locate a node, set/splice/delete); `saveLayer()` re-validates the whole
12
+ * (locate a node, set/splice/delete); `saveConfigFile()` re-validates the whole
13
13
  * document through the exported `validateFileConfig()` - the same gate the
14
14
  * loader applies. The editor therefore carries no rule set of its own: a save
15
15
  * either produces exactly what `loadConfig()` would accept, or throws the
@@ -21,92 +21,53 @@
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
- * Layers: "project" is `<cwd>/.pi/switchback.yaml`, "global" is
25
- * `<piConfigDir>/switchback.yaml` (the loader's aggregation order). The
26
- * dialogue edits one layer file at a time; `defaultLayer()` picks project
27
- * when a project `.pi/` directory exists, else global.
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`).
28
27
  *
29
28
  * Writes are atomic - tmp file + rename, the `state.ts` pattern - and the
30
- * parent directory is created on demand, so a first save into a fresh
31
- * project layer works without ceremony.
29
+ * parent directory is created on demand, so a first save into a fresh install
30
+ * works without ceremony.
32
31
  */
33
32
 
34
33
  import { existsSync, readFileSync } from "node:fs";
35
- import { join } from "node:path";
36
34
  import { writeFileAtomic } from "./atomic-write.ts";
37
35
  import { isMap, isSeq, parseDocument, type Document, type YAMLMap, type YAMLSeq } from "yaml";
38
- import { ConfigError, piConfigDir, validateFileConfig } from "./config.ts";
39
- import type { ModelId, SwitchbackFileConfig } from "./types.ts";
36
+ import { ConfigError, configFilePath, validateFileConfig } from "./config.ts";
37
+ import type { IdleResetConfig, ModelId, SwitchbackFileConfig } from "./types.ts";
40
38
 
41
- /** Which switchback.yaml layer the editor has open. */
42
- export type ConfigLayer = "global" | "project";
43
-
44
- /** A layer loaded for editing: the parsed Document plus where it lives. */
45
- export interface LoadedLayer {
46
- layer: ConfigLayer;
47
- /** Absolute path of the layer file; shown in every dialogue screen title. */
39
+ /**
40
+ * A config file loaded for editing: the parsed Document plus where it lives.
41
+ *
42
+ * There is one file, `configFilePath()`, and therefore nothing to choose between.
43
+ */
44
+ export interface LoadedConfig {
45
+ /** Absolute path of the config file; shown in every dialogue screen title. */
48
46
  path: string;
49
47
  /** False when the file does not exist yet and the editor started fresh. */
50
48
  existed: boolean;
51
49
  doc: Document;
52
50
  }
53
51
 
54
- /** Header comment written when the editor creates a layer file from scratch. */
52
+ /** Header comment written when the editor creates the config file from scratch. */
55
53
  const NEW_FILE_HEADER = [
56
54
  "switchback configuration - see docs/configuration.md",
57
- "Layers: <cwd>/.pi/switchback.yaml overrides ~/.config/switchback/switchback.yaml per model id.",
55
+ "Read by every switchback host (pi and OpenCode) from this one file.",
58
56
  "API keys are secret-store references (`secret:<name>`), never literal values.",
59
57
  ].join("\n");
60
58
 
61
- /** The project layer's file path (`<cwd>/.pi/switchback.yaml`). */
62
- export function projectConfigPath(): string {
63
- return join(process.cwd(), ".pi", "switchback.yaml");
64
- }
65
-
66
- /** The global layer's file path (`<piConfigDir>/switchback.yaml`). */
67
- export function globalConfigPath(): string {
68
- return join(piConfigDir(), "switchback.yaml");
69
- }
70
-
71
59
  /**
72
- * The layer a dialogue offers first.
73
- *
74
- * Deliberately boring: the GLOBAL config is the base every project inherits, so
75
- * it is the natural default - unless the global file does not exist while a
76
- * project one does, in which case that project file is plainly what the user
77
- * works with. An earlier rule ("project when `<cwd>/.pi` exists") silently wrote
78
- * project overrides for users who only ever meant to edit their global config.
79
- *
80
- * This only orders the chooser; the dialogue asks explicitly and shows both
81
- * layers, so nothing is decided invisibly.
82
- */
83
- export function defaultLayer(): ConfigLayer {
84
- if (existsSync(globalConfigPath())) return "global";
85
- return existsSync(projectConfigPath()) ? "project" : "global";
86
- }
87
-
88
- /** File path for a layer. */
89
- export function layerPath(layer: ConfigLayer): string {
90
- return layer === "project" ? projectConfigPath() : globalConfigPath();
91
- }
92
-
93
- /** Whether a layer file exists on disk. */
94
- export function layerExists(layer: ConfigLayer): boolean {
95
- return existsSync(layerPath(layer));
96
- }
97
-
98
- /**
99
- * Parse a layer for editing. A missing file yields an empty Document that
100
- * carries the header comment; the first save creates it. A file that is not
60
+ * Parse the config file for editing. A missing file yields an empty Document
61
+ * that carries the header comment; the first save creates it. A file that is not
101
62
  * valid YAML throws ConfigError - the editor opens valid config only, and a
102
63
  * broken file is surfaced for a hand fix rather than silently rewritten.
103
64
  */
104
- export function loadLayer(layer: ConfigLayer): LoadedLayer {
105
- const path = layerPath(layer);
65
+ export function loadConfigFile(): LoadedConfig {
66
+ const path = configFilePath();
106
67
  if (!existsSync(path)) {
107
68
  const doc = parseDocument("");
108
69
  doc.commentBefore = NEW_FILE_HEADER;
109
- return { layer, path, existed: false, doc };
70
+ return { path, existed: false, doc };
110
71
  }
111
72
  let text: string;
112
73
  try {
@@ -119,16 +80,16 @@ export function loadLayer(layer: ConfigLayer): LoadedLayer {
119
80
  if (firstError !== undefined) {
120
81
  throw new ConfigError(`switchback config is not valid YAML: ${String(firstError.message)}`, path);
121
82
  }
122
- return { layer, path, existed: true, doc };
83
+ return { path, existed: true, doc };
123
84
  }
124
85
 
125
86
  /**
126
- * The layer's current config, validated by the loader's own gate. Throws
87
+ * The file's current config, validated by the loader's own gate. Throws
127
88
  * ConfigError when the on-disk document does not satisfy the config rules;
128
89
  * the dialogue surfaces that and declines to edit rather than round-tripping
129
90
  * an invalid state.
130
91
  */
131
- export function readLayerConfig(loaded: LoadedLayer): SwitchbackFileConfig {
92
+ export function readConfigFile(loaded: LoadedConfig): SwitchbackFileConfig {
132
93
  return validateFileConfig(loaded.doc.toJSON(), loaded.path).config;
133
94
  }
134
95
 
@@ -136,11 +97,11 @@ function errorMessage(error: unknown): string {
136
97
  return error instanceof Error ? error.message : String(error);
137
98
  }
138
99
 
139
- /** The `models:` sequence of a loaded layer; created on demand for a fresh layer file. */
140
- function requireModelsSeq(loaded: LoadedLayer): YAMLSeq {
100
+ /** The `models:` sequence; created on demand for a fresh config file. */
101
+ function requireModelsSeq(loaded: LoadedConfig): YAMLSeq {
141
102
  const models = loaded.doc.get("models");
142
103
  if (models === undefined || models === null) {
143
- // A fresh layer has no models key yet; the dialogue starts by adding one.
104
+ // A fresh file has no models key yet; the dialogue starts by adding one.
144
105
  const created = loaded.doc.createNode([]) as YAMLSeq;
145
106
  loaded.doc.set("models", created);
146
107
  return created;
@@ -150,7 +111,7 @@ function requireModelsSeq(loaded: LoadedLayer): YAMLSeq {
150
111
  }
151
112
 
152
113
  /** Find a model entry node by virtual-model id; both sides are normalized, so a file storing a bare `auto` is found by `switchback/auto` and vice versa. */
153
- function findModelNode(loaded: LoadedLayer, virtualId: string): { seq: YAMLSeq; index: number; node: YAMLMap } {
114
+ function findModelNode(loaded: LoadedConfig, virtualId: string): { seq: YAMLSeq; index: number; node: YAMLMap } {
154
115
  const seq = requireModelsSeq(loaded);
155
116
  const wanted = normalizeVirtualId(virtualId);
156
117
  for (const [index, item] of seq.items.entries()) {
@@ -169,7 +130,7 @@ function normalizeVirtualId(virtualId: string): string {
169
130
  }
170
131
 
171
132
  /** Structural duplicate check (normalized both sides) so the dialogue errors at the offending action, not only at save. */
172
- function assertModelIdAvailable(loaded: LoadedLayer, fullId: string): void {
133
+ function assertModelIdAvailable(loaded: LoadedConfig, fullId: string): void {
173
134
  const seq = requireModelsSeq(loaded);
174
135
  for (const item of seq.items) {
175
136
  if (item === null || !isMap(item)) continue;
@@ -186,7 +147,7 @@ function assertModelIdAvailable(loaded: LoadedLayer, fullId: string): void {
186
147
  * by `validateFileConfig`, so the user sees the loader's own message if a
187
148
  * fallback misses its `provider/id` form.
188
149
  */
189
- export function addVirtualModel(loaded: LoadedLayer, input: { id: string; name: string; fallbacks: ModelId[] }): void {
150
+ export function addVirtualModel(loaded: LoadedConfig, input: { id: string; name: string; fallbacks: ModelId[] }): void {
190
151
  const fullId = normalizeVirtualId(input.id);
191
152
  assertModelIdAvailable(loaded, fullId);
192
153
  const seq = requireModelsSeq(loaded);
@@ -194,13 +155,13 @@ export function addVirtualModel(loaded: LoadedLayer, input: { id: string; name:
194
155
  }
195
156
 
196
157
  /** Remove a virtual model entry by id (bare ids normalized). Confirm-gated by the dialogue. */
197
- export function removeVirtualModel(loaded: LoadedLayer, virtualId: string): void {
158
+ export function removeVirtualModel(loaded: LoadedConfig, virtualId: string): void {
198
159
  const { seq, index } = findModelNode(loaded, virtualId);
199
160
  seq.items.splice(index, 1);
200
161
  }
201
162
 
202
163
  /** Change a virtual model's id. The running pi keeps the old registration until restart. */
203
- export function renameVirtualModel(loaded: LoadedLayer, oldId: string, newId: string): void {
164
+ export function renameVirtualModel(loaded: LoadedConfig, oldId: string, newId: string): void {
204
165
  const fullNewId = normalizeVirtualId(newId);
205
166
  const old = normalizeVirtualId(oldId);
206
167
  if (fullNewId !== old) assertModelIdAvailable(loaded, fullNewId);
@@ -209,19 +170,19 @@ export function renameVirtualModel(loaded: LoadedLayer, oldId: string, newId: st
209
170
  }
210
171
 
211
172
  /** Change a virtual model's display name. */
212
- export function setVirtualModelName(loaded: LoadedLayer, virtualId: string, name: string): void {
173
+ export function setVirtualModelName(loaded: LoadedConfig, virtualId: string, name: string): void {
213
174
  const { node } = findModelNode(loaded, virtualId);
214
175
  node.set("name", name);
215
176
  }
216
177
 
217
178
  /** Replace a model's whole fallback list (ordered; first entry is preferred). */
218
- export function setFallbacks(loaded: LoadedLayer, virtualId: string, fallbacks: ModelId[]): void {
179
+ export function setFallbacks(loaded: LoadedConfig, virtualId: string, fallbacks: ModelId[]): void {
219
180
  const { node } = findModelNode(loaded, virtualId);
220
181
  node.set("fallbacks", loaded.doc.createNode([...fallbacks]));
221
182
  }
222
183
 
223
184
  /** Append one fallback at the end of the model's preference list. */
224
- export function addFallback(loaded: LoadedLayer, virtualId: string, fallback: ModelId): void {
185
+ export function addFallback(loaded: LoadedConfig, virtualId: string, fallback: ModelId): void {
225
186
  const { node } = findModelNode(loaded, virtualId);
226
187
  const seq = node.get("fallbacks");
227
188
  if (seq === undefined || seq === null || !isSeq(seq)) {
@@ -231,7 +192,7 @@ export function addFallback(loaded: LoadedLayer, virtualId: string, fallback: Mo
231
192
  }
232
193
 
233
194
  /** Remove the fallback at `index` (bounds-checked; the dialogue passes the picked position). */
234
- export function removeFallback(loaded: LoadedLayer, virtualId: string, index: number): void {
195
+ export function removeFallback(loaded: LoadedConfig, virtualId: string, index: number): void {
235
196
  const { node } = findModelNode(loaded, virtualId);
236
197
  const seq = node.get("fallbacks");
237
198
  if (seq === undefined || seq === null || !isSeq(seq) || index < 0 || index >= seq.items.length) {
@@ -241,7 +202,7 @@ export function removeFallback(loaded: LoadedLayer, virtualId: string, index: nu
241
202
  }
242
203
 
243
204
  /** Move a fallback from one position to another (the dialogue's up/down reordering). */
244
- export function moveFallback(loaded: LoadedLayer, virtualId: string, from: number, to: number): void {
205
+ export function moveFallback(loaded: LoadedConfig, virtualId: string, from: number, to: number): void {
245
206
  const { node } = findModelNode(loaded, virtualId);
246
207
  const seq = node.get("fallbacks");
247
208
  if (
@@ -267,7 +228,7 @@ export function moveFallback(loaded: LoadedLayer, virtualId: string, from: numbe
267
228
  * direct endpoint, live in the top-level `decisionModels:` map under the same
268
229
  * address.
269
230
  */
270
- export function setDecisionModel(loaded: LoadedLayer, virtualId: string, address: string | null): void {
231
+ export function setDecisionModel(loaded: LoadedConfig, virtualId: string, address: string | null): void {
271
232
  const { node } = findModelNode(loaded, virtualId);
272
233
  if (address === null) {
273
234
  node.delete("decisionModel");
@@ -313,7 +274,7 @@ function decisionModelToNode(doc: Document, input: DecisionModelInput): YAMLMap
313
274
  return doc.createNode(entry) as YAMLMap;
314
275
  }
315
276
 
316
- function requireDecisionModelsMap(loaded: LoadedLayer): YAMLMap {
277
+ function requireDecisionModelsMap(loaded: LoadedConfig): YAMLMap {
317
278
  const map = loaded.doc.get("decisionModels");
318
279
  if (map === undefined || map === null) {
319
280
  const created = loaded.doc.createNode({}) as YAMLMap;
@@ -327,7 +288,7 @@ function requireDecisionModelsMap(loaded: LoadedLayer): YAMLMap {
327
288
  }
328
289
 
329
290
  /** Find a decisionModels entry node by its address (the map key). */
330
- function findDecisionModelNode(loaded: LoadedLayer, address: string): { map: YAMLMap; node: YAMLMap } {
291
+ function findDecisionModelNode(loaded: LoadedConfig, address: string): { map: YAMLMap; node: YAMLMap } {
331
292
  const map = requireDecisionModelsMap(loaded);
332
293
  const node = map.get(address, true);
333
294
  if (node === undefined || node === null || !isMap(node)) {
@@ -337,7 +298,7 @@ function findDecisionModelNode(loaded: LoadedLayer, address: string): { map: YAM
337
298
  }
338
299
 
339
300
  /** Add a decision-model entry (duplicate addresses fail the save via `validateFileConfig`). */
340
- export function addDecisionModel(loaded: LoadedLayer, input: DecisionModelInput): void {
301
+ export function addDecisionModel(loaded: LoadedConfig, input: DecisionModelInput): void {
341
302
  const map = requireDecisionModelsMap(loaded);
342
303
  if (map.has(input.address)) {
343
304
  throw new ConfigError(`decisionModels already contains "${input.address}"`, loaded.path);
@@ -346,7 +307,7 @@ export function addDecisionModel(loaded: LoadedLayer, input: DecisionModelInput)
346
307
  }
347
308
 
348
309
  /** Patch one decision model's connection details. */
349
- export function updateDecisionModel(loaded: LoadedLayer, address: string, patch: DecisionModelPatch): void {
310
+ export function updateDecisionModel(loaded: LoadedConfig, address: string, patch: DecisionModelPatch): void {
350
311
  const { node } = findDecisionModelNode(loaded, address);
351
312
  if (patch.baseUrl !== undefined) {
352
313
  if (patch.baseUrl === null) {
@@ -367,7 +328,7 @@ export function updateDecisionModel(loaded: LoadedLayer, address: string, patch:
367
328
  * Rename a decision-model address and rewrite every `models[].decisionModel`
368
329
  * that names it in the same transaction, so a rename cannot dangle references.
369
330
  */
370
- export function renameDecisionModel(loaded: LoadedLayer, oldAddress: string, newAddress: string): void {
331
+ export function renameDecisionModel(loaded: LoadedConfig, oldAddress: string, newAddress: string): void {
371
332
  if (oldAddress !== newAddress) {
372
333
  const { map, node } = findDecisionModelNode(loaded, oldAddress);
373
334
  if (map.has(newAddress)) {
@@ -388,7 +349,7 @@ export function renameDecisionModel(loaded: LoadedLayer, oldAddress: string, new
388
349
  * and OpenCode cannot - the user decides what happens to the referencing model
389
350
  * instead of the editor silently clearing it.
390
351
  */
391
- export function removeDecisionModel(loaded: LoadedLayer, address: string): void {
352
+ export function removeDecisionModel(loaded: LoadedConfig, address: string): void {
392
353
  const { map } = findDecisionModelNode(loaded, address);
393
354
  map.delete(address);
394
355
  // An empty map is litter: drop the key so the file reads as if no entry was ever made.
@@ -396,7 +357,7 @@ export function removeDecisionModel(loaded: LoadedLayer, address: string): void
396
357
  }
397
358
 
398
359
  /** How many configured models name a decision model (the dialogue's confirm/warning text). */
399
- export function countDecisionModelReferences(loaded: LoadedLayer, address: string): number {
360
+ export function countDecisionModelReferences(loaded: LoadedConfig, address: string): number {
400
361
  let count = 0;
401
362
  for (const item of requireModelsSeq(loaded).items) {
402
363
  if (item === null || !isMap(item)) continue;
@@ -405,8 +366,24 @@ export function countDecisionModelReferences(loaded: LoadedLayer, address: strin
405
366
  return count;
406
367
  }
407
368
 
369
+ /**
370
+ * Set or clear a model's `idleReset:` option. A duration ("30m", "2h", ...)
371
+ * returns to the head of the fallback list after that much idle time;
372
+ * `classifier` asks the decision model; `null` deletes the key, which is the
373
+ * loader's default (`never`). Validation of the value itself is the loader's
374
+ * job at save time, so an unknown value surfaces with the loader's message.
375
+ */
376
+ export function setIdleReset(loaded: LoadedConfig, virtualId: string, option: IdleResetConfig | null): void {
377
+ const { node } = findModelNode(loaded, virtualId);
378
+ if (option === null) {
379
+ node.delete("idleReset");
380
+ return;
381
+ }
382
+ node.set("idleReset", option);
383
+ }
384
+
408
385
  /** Set the top-level `debug:` flag (per-switch diagnostics notifications). */
409
- export function setDebug(loaded: LoadedLayer, enabled: boolean): void {
386
+ export function setDebug(loaded: LoadedConfig, enabled: boolean): void {
410
387
  loaded.doc.set("debug", enabled);
411
388
  }
412
389
 
@@ -416,7 +393,7 @@ export function setDebug(loaded: LoadedLayer, enabled: boolean): void {
416
393
  * state is not a config `loadConfig()` would accept. On a throw the in-memory
417
394
  * document keeps the edit so the dialogue can re-enter the same editor for a fix.
418
395
  */
419
- export function saveLayer(loaded: LoadedLayer): void {
396
+ export function saveConfigFile(loaded: LoadedConfig): void {
420
397
  if (loaded.doc.contents === undefined || loaded.doc.contents === null) {
421
398
  loaded.doc.contents = loaded.doc.createNode({});
422
399
  }
package/src/config.ts CHANGED
@@ -1,33 +1,23 @@
1
1
  /**
2
2
  * User-facing switchback config loader.
3
3
  *
4
- * Config layers (all YAML, all optional):
5
- * 1. ~/.config/switchback/switchback.yaml (neutral basis, agent-agnostic)
6
- * 2. <piConfigDir>/switchback.yaml (provider-specific overlay; piConfigDir = ~/.pi/agent)
7
- * 3. <cwd>/.pi/switchback.yaml (per-project layer)
8
- * 4. built-in DEFAULT_CONFIG (only when no file exists)
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.
9
10
  *
10
- * The user layers are AGGREGATED, not first-match-wins: the merged model
11
- * list starts from the neutral basis, applies provider-specific overrides
12
- * in place, then applies project overrides. A layer that exists but fails to
13
- * parse or validate throws immediately - a broken layer is surfaced, never
14
- * silently dropped in favour of the others.
15
- *
16
- * The neutral basis (`~/.config/switchback/`) is the canonical, agent-agnostic
17
- * location so the same config serves both pi and opencode. Provider-specific
18
- * and project-local slots allow overlays without duplicating the full config.
19
- *
20
- * The project-local slot lives under `.pi/` deliberately: `.pi/` is ignored by
21
- * git (pi's own convention), so a per-project override can never be committed
22
- * into a repository the way a repo-root `switchback.yaml` would be. The repo
23
- * ships only `switchback.yaml.example` as the template.
11
+ * The location is `~/.config/switchback/` - not a host's private directory - so
12
+ * the same config serves pi and OpenCode. Override the directory with
13
+ * `SWITCHBACK_CONFIG_DIR` (tests, sandboxes).
24
14
  *
25
15
  * DEFAULT_CONFIG ships with `fallbacks: []` (no provider hardcoded) so a configless
26
16
  * user gets a clear, actionable error instead of a silently-broken router. The
27
17
  * fail-fast happens at extension load: `findModelConfig()` throws ConfigError
28
18
  * from index.ts (module top level) before route()/decide() ever runs. The
29
- * message names the known fix ("Configure fallbacks in ~/.config/switchback/switchback.yaml
30
- * or <cwd>/.pi/switchback.yaml and re-launch."). Until the user does
19
+ * message names the known fix ("Configure fallbacks in
20
+ * ~/.config/switchback/switchback.yaml and re-launch."). Until the user does
31
21
  * that, the extension is unavailable and `/switchback` diagnostics are not
32
22
  * registered; with `defaultModel=switchback/auto` in pi's settings.json, every
33
23
  * new session also starts with an invalid default. Trade-off accepted: prefer
@@ -108,16 +98,15 @@ export function piConfigDir(): string {
108
98
  /**
109
99
  * Resolve the neutral switchback config directory. This is the canonical,
110
100
  * agent-agnostic location for switchback user config: `~/.config/switchback`.
111
- * It serves as the basis layer that provider-specific configs (from
112
- * `~/.config/opencode` or `~/.pi/agent`) are superposed on top of.
101
+ * It is the only config location switchback reads.
113
102
  */
114
103
  export function switchbackConfigDir(): string {
115
104
  return process.env[SWITCHBACK_CONFIG_DIR_ENV] ?? join(homedir(), ".config", "switchback");
116
105
  }
117
106
 
118
107
  /**
119
- * Env override naming the neutral config directory outright. Lets a host or a
120
- * test pin the basis layer without touching the user's real `~/.config/switchback`.
108
+ * Env override naming the config directory outright. Lets tests and sandboxes pin
109
+ * the file without touching the user's real `~/.config/switchback`.
121
110
  */
122
111
  export const SWITCHBACK_CONFIG_DIR_ENV = "SWITCHBACK_CONFIG_DIR";
123
112
 
@@ -139,40 +128,13 @@ export function switchbackStateDir(): string {
139
128
  }
140
129
 
141
130
  /**
142
- * Where the layered config files live for one host invocation.
143
- *
144
- * The neutral basis (`~/.config/switchback`) and the local override
145
- * (`<cwd>/.pi`) are the same for every host; the agent overlay is the host's own
146
- * config directory, which pi defaults to and another host passes explicitly.
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`).
147
135
  */
148
- export interface ConfigLayerDirs {
149
- /** Agent-specific overlay directory. Defaults to pi's agent dir. */
150
- agent?: string;
151
- /** Project-local override directory. Defaults to `<cwd>/.pi`. */
152
- project?: string;
153
- }
154
-
155
- function candidatePaths(dirs: ConfigLayerDirs = {}): string[] {
156
- const cwd = process.cwd();
157
- const cfg = dirs.agent ?? piConfigDir();
158
- const project = dirs.project ?? join(cwd, ".pi");
159
- const neutral = switchbackConfigDir();
160
- // YAML-only: switchback.yaml is the human-facing config. The .json sibling is
161
- // dropped from the candidate list - the only JSON files that ship in this
162
- // project are machine-managed (`<state dir>/blocks.json` runtime state, the
163
- // simulate fixture `switchback.simulate.json`).
164
- // The project-local slot is `.pi/`, which git ignores, so a per-project
165
- // override never lands in a repository.
166
- //
167
- // Precedence (lowest → highest):
168
- // 1. ~/.config/switchback/switchback.yaml (neutral basis, agent-agnostic)
169
- // 2. <agent config dir>/switchback.yaml (host-specific overlay)
170
- // 3. <project dir>/switchback.yaml (local override)
171
- return [
172
- join(neutral, `${CONFIG_BASENAME}.yaml`),
173
- join(cfg, `${CONFIG_BASENAME}.yaml`),
174
- join(project, `${CONFIG_BASENAME}.yaml`),
175
- ];
136
+ export function configFilePath(): string {
137
+ return join(switchbackConfigDir(), `${CONFIG_BASENAME}.yaml`);
176
138
  }
177
139
 
178
140
  function isRecord(value: unknown): value is Record<string, unknown> {
@@ -444,19 +406,28 @@ function parseFileConfig(value: unknown, path: string, warnings: string[]): Swit
444
406
  if (!Array.isArray(models) || models.length === 0) {
445
407
  throw new ConfigError("models must be a non-empty array", path);
446
408
  }
447
- const parsed = models.map((entry, i) => parseSwitchbackModel(entry, i, warnings));
409
+ const parsedAll = models.map((entry, i) => parseSwitchbackModel(entry, i, warnings));
448
410
  // Any set of virtual model ids is valid - `switchback/auto` is the conventional
449
411
  // first entry, not a requirement. An unknown virtual id is already surfaced by
450
412
  // findModelConfig() at extension load, and index.ts registers one virtual model
451
- // per configured entry. A duplicated id WITHIN a file is rejected here: layers
452
- // may legitimately override each other, but one file must not contradict itself.
453
- const seen = new Set<string>();
454
- for (const entry of parsed) {
455
- if (seen.has(entry.id)) {
456
- throw new ConfigError(`models contains the id "${entry.id}" more than once`, path);
413
+ // per configured entry. A repeated id WITHIN the file keeps the FIRST entry and
414
+ // drops the later ones with a warning: a duplicated chain (a stale editor
415
+ // write, a hand merge) must not take the whole extension down. Each host shows
416
+ // the warning through its own channel (createConfigWarningReporter), and the
417
+ // message names both positions so the extra entry is easy to remove.
418
+ const parsed: SwitchbackConfig[] = [];
419
+ const firstIndex = new Map<string, number>();
420
+ parsedAll.forEach((entry, i) => {
421
+ const first = firstIndex.get(entry.id);
422
+ if (first === undefined) {
423
+ firstIndex.set(entry.id, i);
424
+ parsed.push(entry);
425
+ } else {
426
+ warnings.push(
427
+ `models[${i}] repeats the id "${entry.id}" (first defined at models[${first}]); the later entry was ignored`,
428
+ );
457
429
  }
458
- seen.add(entry.id);
459
- }
430
+ });
460
431
  const rawDebug = value["debug"];
461
432
  if (rawDebug !== undefined && typeof rawDebug !== "boolean") {
462
433
  throw new ConfigError("debug must be a boolean", path);
@@ -492,118 +463,77 @@ function readAndParse(path: string, warnings: string[]): SwitchbackFileConfig {
492
463
  try {
493
464
  raw = parseYaml(text);
494
465
  } catch (error) {
495
- // Surface a malformed layer as a typed, path-carrying error instead of the
496
- // parser's raw stack - a broken layer must stop startup loudly either way.
466
+ // Surface a malformed file as a typed, path-carrying error instead of the
467
+ // parser's raw stack - a broken config must stop startup loudly.
497
468
  throw new ConfigError(
498
469
  `switchback config is not valid YAML: ${error instanceof Error ? error.message.split("\n")[0] : String(error)}`,
499
470
  path,
500
471
  );
501
472
  }
502
- const layerWarnings: string[] = [];
503
- const parsed = parseFileConfig(raw, path, layerWarnings);
504
- for (const warning of layerWarnings) warnings.push(`${warning} (${path})`);
473
+ const parsed = parseFileConfig(raw, path, warnings);
505
474
  return parsed;
506
475
  }
507
476
 
508
477
  /**
509
- * Merge a per-project config on top of the agent-dir (global) config.
478
+ * Load the active switchback configuration from `configFilePath()`.
510
479
  *
511
- * Aggregation unit is the virtual-model entry: the merged list keeps the global
512
- * order as its base, a project entry with the same id replaces the global entry
513
- * in place (the project entry wins wholesale - fallbacks, name and classifier -
514
- * there is no field-level merging), and project-only models are appended after
515
- * the global ones in project order. With no global config the project config
516
- * stands alone, and vice versa.
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>`.
517
486
  */
518
- function aggregateConfigs(global: SwitchbackFileConfig, project: SwitchbackFileConfig): SwitchbackFileConfig {
519
- const merged = [...global.models];
520
- for (const projectEntry of project.models) {
521
- const index = merged.findIndex((m) => m.id === projectEntry.id);
522
- if (index === -1) merged.push(projectEntry);
523
- else merged[index] = projectEntry;
524
- }
525
- return {
526
- models: merged,
527
- // Decision models follow the same layering rule as debug: the project map
528
- // replaces the global map when present, so addresses resolve against one
529
- // predictable set. (A project layer without decisionModels keeps the global set.)
530
- ...(project.decisionModels !== undefined
531
- ? { decisionModels: project.decisionModels }
532
- : global.decisionModels !== undefined
533
- ? { decisionModels: global.decisionModels }
534
- : {}),
535
- ...(project.debug !== undefined
536
- ? { debug: project.debug }
537
- : global.debug !== undefined
538
- ? { debug: global.debug }
539
- : {}),
540
- };
541
- }
542
487
 
543
- /**
544
- * Load the active switchback configuration.
545
- *
546
- * The per-project file (`<cwd>/.pi/switchback.yaml`) and the agent-dir copy
547
- * (`<piConfigDir>/switchback.yaml`) are AGGREGATED, not first-match-wins: the
548
- * merged model list is the global list with project entries overriding
549
- * same-id entries in place and project-only entries appended. A file that
550
- * exists but fails to parse or validate throws immediately - a broken layer is
551
- * surfaced, never silently dropped. With neither file present, DEFAULT_CONFIG
552
- * (empty fallbacks, fail-fast) applies.
553
- */
554
488
  /** A store capable of resolving `secret:<name>` apiKey references. */
555
489
  export interface SecretResolver {
556
490
  get(name: string): string | undefined;
557
491
  }
558
492
 
559
493
  /**
560
- * Load, aggregate and resolve the user config.
494
+ * Load and resolve the user config.
561
495
  *
562
496
  * `secrets` resolves `apiKey: secret:<name>` references to plaintext. It is
563
497
  * injected rather than imported so this module stays free of the secrets store
564
498
  * (which itself reads `switchbackStateDir` from here) - production callers pass
565
499
  * `createSecretStore()`; tests pass a fake or leave it undefined.
566
500
  *
567
- * `dirs` overrides the layer locations; a host other than pi passes its own
568
- * agent config directory so its overlay participates.
569
- *
570
501
  * `warnings` carries recognised-but-suspicious findings (unknown keys, retired
571
502
  * keys, unreferenced decision models). They never fail the load: a host shows
572
503
  * them through its own notify channel.
573
504
  */
574
- export function loadConfig(
575
- secrets?: SecretResolver,
576
- dirs?: ConfigLayerDirs,
577
- ): { config: ResolvedSwitchbackFileConfig; source: string; warnings: string[] } {
578
- const [neutralPath, agentPath, projectPath] = candidatePaths(dirs) as [string, string, string];
579
- const neutralExists = existsSync(neutralPath);
580
- const agentExists = existsSync(agentPath);
581
- const projectExists = existsSync(projectPath);
582
-
583
- // Aggregate all existing layers, lowest precedence first.
584
- let merged: SwitchbackFileConfig | undefined;
585
- const sources: string[] = [];
586
- const warnings: string[] = [];
505
+ export function loadConfig(secrets?: SecretResolver): {
506
+ config: ResolvedSwitchbackFileConfig;
507
+ source: string;
508
+ warnings: string[];
509
+ } {
510
+ const path = configFilePath();
511
+ if (!existsSync(path)) return { config: DEFAULT_CONFIG, source: "<default>", warnings: [] };
587
512
 
588
- if (neutralExists) {
589
- merged = readAndParse(neutralPath, warnings);
590
- sources.push(resolve(neutralPath));
591
- }
592
- if (agentExists) {
593
- const agent = readAndParse(agentPath, warnings);
594
- sources.push(resolve(agentPath));
595
- merged = merged === undefined ? agent : aggregateConfigs(merged, agent);
596
- }
597
- if (projectExists) {
598
- const project = readAndParse(projectPath, warnings);
599
- sources.push(resolve(projectPath));
600
- merged = merged === undefined ? project : aggregateConfigs(merged, project);
601
- }
513
+ const warnings: string[] = [];
514
+ const parsed = readAndParse(path, warnings);
515
+ return { config: resolveFile(parsed, secrets), source: resolve(path), warnings };
516
+ }
602
517
 
603
- if (merged === undefined) {
604
- return { config: DEFAULT_CONFIG, source: "<default>", warnings };
605
- }
606
- return { config: resolveFile(merged, secrets), source: sources.join(" + "), warnings };
518
+ /**
519
+ * A deduplicating sink for the loader's `warnings`. Both hosts reload the config
520
+ * frequently (pi on every route, OpenCode on every provider transform), so a
521
+ * finding must not repeat per load: the reporter emits a warning set once and
522
+ * stays silent until the set changes. An empty set re-arms the reporter, so a
523
+ * warning that returns after a config fix is shown again.
524
+ */
525
+ export function createConfigWarningReporter(): (warnings: readonly string[], emit: (message: string) => void) => void {
526
+ let shown: string | undefined;
527
+ return (warnings, emit) => {
528
+ if (warnings.length === 0) {
529
+ shown = undefined;
530
+ return;
531
+ }
532
+ const key = warnings.join("\n");
533
+ if (key === shown) return;
534
+ shown = key;
535
+ emit(`switchback config: ${warnings.join("; ")}`);
536
+ };
607
537
  }
608
538
 
609
539
  /**
@@ -623,7 +553,7 @@ export function findModelConfig(config: ResolvedSwitchbackFileConfig, virtualId:
623
553
  if (!entry) throw new ConfigError(`no config entry for virtual model "${virtualId}"`, "<config>");
624
554
  if (entry.fallbacks.length === 0) {
625
555
  throw new ConfigError(
626
- `switchback has no fallbacks configured (source: ${entry.id}). Configure fallbacks in ~/.config/switchback/switchback.yaml or <cwd>/.pi/switchback.yaml and re-launch.`,
556
+ `switchback has no fallbacks configured (source: ${entry.id}). Configure fallbacks in ${configFilePath()} and re-launch.`,
627
557
  "<default>",
628
558
  );
629
559
  }
package/src/index.ts CHANGED
@@ -53,13 +53,18 @@ export {
53
53
  disableModel,
54
54
  disabledFilePath,
55
55
  enableModel,
56
+ getPinnedModel,
56
57
  isBlocked,
57
58
  isDisabled,
59
+ pinFilePath,
58
60
  readBlockedMap,
59
61
  readDisabledMap,
60
- unblockModel,
62
+ readPinMap,
63
+ setPinnedModel,
61
64
  stateFilePath,
65
+ unblockModel,
62
66
  } from "./state.ts";
67
+ export type { PinMap } from "./state.ts";
63
68
  export {
64
69
  readCrashMap,
65
70
  recordCrash,
@@ -81,10 +86,13 @@ export {
81
86
  SWITCHBACK_VIRTUAL_ID,
82
87
  ConfigError,
83
88
  piConfigDir,
89
+ switchbackConfigDir,
90
+ configFilePath,
84
91
  switchbackStateDir,
85
92
  resolveDecisionModel,
86
93
  resolveSecretApiKey,
87
94
  validateFileConfig,
95
+ createConfigWarningReporter,
88
96
  } from "./config.ts";
89
97
  export type { SwitchbackConfig, SwitchbackFileConfig, DecisionModelConfig, SecretResolver } from "./config.ts";
90
98
  export type {
@@ -98,27 +106,23 @@ export {
98
106
  addFallback,
99
107
  addVirtualModel,
100
108
  countDecisionModelReferences,
101
- defaultLayer,
102
- globalConfigPath,
103
- layerExists,
104
- layerPath,
105
- loadLayer,
109
+ loadConfigFile,
106
110
  moveFallback,
107
- projectConfigPath,
108
- readLayerConfig,
111
+ readConfigFile,
109
112
  removeDecisionModel,
110
113
  removeFallback,
111
114
  removeVirtualModel,
112
115
  renameDecisionModel,
113
116
  renameVirtualModel,
114
- saveLayer,
117
+ saveConfigFile,
115
118
  setDecisionModel,
116
119
  setDebug,
117
120
  setFallbacks,
121
+ setIdleReset,
118
122
  setVirtualModelName,
119
123
  updateDecisionModel,
120
124
  } from "./config-editor.ts";
121
- export type { ConfigLayer, DecisionModelInput, DecisionModelPatch, LoadedLayer } from "./config-editor.ts";
125
+ export type { DecisionModelInput, DecisionModelPatch, LoadedConfig } from "./config-editor.ts";
122
126
  export {
123
127
  buildClassifierProviders,
124
128
  classifierBaseUrlNote,