switchback-core 2026.10.16 → 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 +1 -1
- package/src/config-editor.ts +49 -88
- package/src/config.ts +80 -150
- package/src/index.ts +7 -9
package/package.json
CHANGED
package/src/config-editor.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Comment-preserving read-modify-write editor for
|
|
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); `
|
|
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
|
-
*
|
|
25
|
-
*
|
|
26
|
-
*
|
|
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
|
-
*
|
|
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,
|
|
36
|
+
import { ConfigError, configFilePath, validateFileConfig } from "./config.ts";
|
|
39
37
|
import type { IdleResetConfig, ModelId, SwitchbackFileConfig } from "./types.ts";
|
|
40
38
|
|
|
41
|
-
/**
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
/** Absolute path of the
|
|
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
|
|
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
|
-
"
|
|
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
|
-
/**
|
|
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
59
|
/**
|
|
99
|
-
* Parse
|
|
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
|
|
105
|
-
const path =
|
|
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 {
|
|
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 {
|
|
83
|
+
return { path, existed: true, doc };
|
|
123
84
|
}
|
|
124
85
|
|
|
125
86
|
/**
|
|
126
|
-
* The
|
|
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
|
|
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
|
|
140
|
-
function requireModelsSeq(loaded:
|
|
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
|
|
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:
|
|
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:
|
|
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:
|
|
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:
|
|
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:
|
|
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:
|
|
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:
|
|
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:
|
|
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:
|
|
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:
|
|
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:
|
|
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:
|
|
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:
|
|
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:
|
|
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:
|
|
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:
|
|
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:
|
|
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:
|
|
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;
|
|
@@ -412,7 +373,7 @@ export function countDecisionModelReferences(loaded: LoadedLayer, address: strin
|
|
|
412
373
|
* loader's default (`never`). Validation of the value itself is the loader's
|
|
413
374
|
* job at save time, so an unknown value surfaces with the loader's message.
|
|
414
375
|
*/
|
|
415
|
-
export function setIdleReset(loaded:
|
|
376
|
+
export function setIdleReset(loaded: LoadedConfig, virtualId: string, option: IdleResetConfig | null): void {
|
|
416
377
|
const { node } = findModelNode(loaded, virtualId);
|
|
417
378
|
if (option === null) {
|
|
418
379
|
node.delete("idleReset");
|
|
@@ -422,7 +383,7 @@ export function setIdleReset(loaded: LoadedLayer, virtualId: string, option: Idl
|
|
|
422
383
|
}
|
|
423
384
|
|
|
424
385
|
/** Set the top-level `debug:` flag (per-switch diagnostics notifications). */
|
|
425
|
-
export function setDebug(loaded:
|
|
386
|
+
export function setDebug(loaded: LoadedConfig, enabled: boolean): void {
|
|
426
387
|
loaded.doc.set("debug", enabled);
|
|
427
388
|
}
|
|
428
389
|
|
|
@@ -432,7 +393,7 @@ export function setDebug(loaded: LoadedLayer, enabled: boolean): void {
|
|
|
432
393
|
* state is not a config `loadConfig()` would accept. On a throw the in-memory
|
|
433
394
|
* document keeps the edit so the dialogue can re-enter the same editor for a fix.
|
|
434
395
|
*/
|
|
435
|
-
export function
|
|
396
|
+
export function saveConfigFile(loaded: LoadedConfig): void {
|
|
436
397
|
if (loaded.doc.contents === undefined || loaded.doc.contents === null) {
|
|
437
398
|
loaded.doc.contents = loaded.doc.createNode({});
|
|
438
399
|
}
|
package/src/config.ts
CHANGED
|
@@ -1,33 +1,23 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* User-facing switchback config loader.
|
|
3
3
|
*
|
|
4
|
-
* Config
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
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
|
|
11
|
-
*
|
|
12
|
-
*
|
|
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
|
|
30
|
-
*
|
|
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
|
|
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
|
|
120
|
-
*
|
|
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
|
|
143
|
-
*
|
|
144
|
-
*
|
|
145
|
-
* (
|
|
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
|
|
149
|
-
|
|
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
|
|
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
|
|
452
|
-
//
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
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
|
-
|
|
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
|
|
496
|
-
// parser's raw stack - a broken
|
|
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
|
|
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
|
-
*
|
|
478
|
+
* Load the active switchback configuration from `configFilePath()`.
|
|
510
479
|
*
|
|
511
|
-
*
|
|
512
|
-
*
|
|
513
|
-
*
|
|
514
|
-
*
|
|
515
|
-
*
|
|
516
|
-
*
|
|
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
|
|
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
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
const
|
|
580
|
-
|
|
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
|
-
|
|
589
|
-
|
|
590
|
-
|
|
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
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
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
|
|
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
|
@@ -86,10 +86,13 @@ export {
|
|
|
86
86
|
SWITCHBACK_VIRTUAL_ID,
|
|
87
87
|
ConfigError,
|
|
88
88
|
piConfigDir,
|
|
89
|
+
switchbackConfigDir,
|
|
90
|
+
configFilePath,
|
|
89
91
|
switchbackStateDir,
|
|
90
92
|
resolveDecisionModel,
|
|
91
93
|
resolveSecretApiKey,
|
|
92
94
|
validateFileConfig,
|
|
95
|
+
createConfigWarningReporter,
|
|
93
96
|
} from "./config.ts";
|
|
94
97
|
export type { SwitchbackConfig, SwitchbackFileConfig, DecisionModelConfig, SecretResolver } from "./config.ts";
|
|
95
98
|
export type {
|
|
@@ -103,20 +106,15 @@ export {
|
|
|
103
106
|
addFallback,
|
|
104
107
|
addVirtualModel,
|
|
105
108
|
countDecisionModelReferences,
|
|
106
|
-
|
|
107
|
-
globalConfigPath,
|
|
108
|
-
layerExists,
|
|
109
|
-
layerPath,
|
|
110
|
-
loadLayer,
|
|
109
|
+
loadConfigFile,
|
|
111
110
|
moveFallback,
|
|
112
|
-
|
|
113
|
-
readLayerConfig,
|
|
111
|
+
readConfigFile,
|
|
114
112
|
removeDecisionModel,
|
|
115
113
|
removeFallback,
|
|
116
114
|
removeVirtualModel,
|
|
117
115
|
renameDecisionModel,
|
|
118
116
|
renameVirtualModel,
|
|
119
|
-
|
|
117
|
+
saveConfigFile,
|
|
120
118
|
setDecisionModel,
|
|
121
119
|
setDebug,
|
|
122
120
|
setFallbacks,
|
|
@@ -124,7 +122,7 @@ export {
|
|
|
124
122
|
setVirtualModelName,
|
|
125
123
|
updateDecisionModel,
|
|
126
124
|
} from "./config-editor.ts";
|
|
127
|
-
export type {
|
|
125
|
+
export type { DecisionModelInput, DecisionModelPatch, LoadedConfig } from "./config-editor.ts";
|
|
128
126
|
export {
|
|
129
127
|
buildClassifierProviders,
|
|
130
128
|
classifierBaseUrlNote,
|