@aiwayds/dsh-model-sync 0.12.0 → 0.13.0

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.
Files changed (84) hide show
  1. package/README.md +18 -17
  2. package/README.zh-CN.md +18 -17
  3. package/lib/index.d.ts +54 -376
  4. package/lib/index.js +305 -1049
  5. package/lib/index.js.map +1 -1
  6. package/lib/official-adapter.d.ts +80 -0
  7. package/lib/official-adapter.js +34 -0
  8. package/lib/official-adapter.js.map +1 -0
  9. package/lib/official-migrate.d.ts +116 -0
  10. package/lib/official-migrate.js +643 -0
  11. package/lib/official-migrate.js.map +1 -0
  12. package/lib/official-scheduler.d.ts +72 -0
  13. package/lib/official-scheduler.js +195 -0
  14. package/lib/official-scheduler.js.map +1 -0
  15. package/lib/official-store.d.ts +41 -0
  16. package/lib/official-store.js +84 -0
  17. package/lib/official-store.js.map +1 -0
  18. package/lib/official-sync.d.ts +68 -0
  19. package/lib/official-sync.js +274 -0
  20. package/lib/official-sync.js.map +1 -0
  21. package/lib/opencode-go-adapter.d.ts +56 -0
  22. package/lib/opencode-go-adapter.js +455 -0
  23. package/lib/opencode-go-adapter.js.map +1 -0
  24. package/lib/opencode-go-patch-file.d.ts +11 -0
  25. package/lib/opencode-go-patch-file.js +175 -11
  26. package/lib/opencode-go-patch-file.js.map +1 -1
  27. package/lib/opencode-go-source.d.ts +1 -1
  28. package/lib/opencode-go-source.js +1 -1
  29. package/locale/en.json +1 -1
  30. package/locale/zh.json +1 -1
  31. package/package.json +3 -3
  32. package/src/index.ts +351 -1214
  33. package/src/official-adapter.ts +111 -0
  34. package/src/official-migrate.ts +840 -0
  35. package/src/official-scheduler.ts +235 -0
  36. package/src/official-store.ts +122 -0
  37. package/src/official-sync.ts +371 -0
  38. package/src/opencode-go-adapter.ts +494 -0
  39. package/src/opencode-go-patch-file.ts +175 -9
  40. package/src/opencode-go-source.ts +1 -1
  41. package/lib/opencode-go-diagnose.d.ts +0 -75
  42. package/lib/opencode-go-diagnose.js +0 -146
  43. package/lib/opencode-go-diagnose.js.map +0 -1
  44. package/lib/opencode-go-grouping.d.ts +0 -7
  45. package/lib/opencode-go-grouping.js +0 -21
  46. package/lib/opencode-go-grouping.js.map +0 -1
  47. package/lib/opencode-go-journal.d.ts +0 -110
  48. package/lib/opencode-go-journal.js +0 -406
  49. package/lib/opencode-go-journal.js.map +0 -1
  50. package/lib/opencode-go-migrate.d.ts +0 -345
  51. package/lib/opencode-go-migrate.js +0 -1371
  52. package/lib/opencode-go-migrate.js.map +0 -1
  53. package/lib/opencode-go-migration.d.ts +0 -227
  54. package/lib/opencode-go-migration.js +0 -384
  55. package/lib/opencode-go-migration.js.map +0 -1
  56. package/lib/opencode-go-one-shot.d.ts +0 -276
  57. package/lib/opencode-go-one-shot.js +0 -1096
  58. package/lib/opencode-go-one-shot.js.map +0 -1
  59. package/lib/opencode-go-planner.d.ts +0 -154
  60. package/lib/opencode-go-planner.js +0 -305
  61. package/lib/opencode-go-planner.js.map +0 -1
  62. package/lib/opencode-go-scheduler.d.ts +0 -128
  63. package/lib/opencode-go-scheduler.js +0 -241
  64. package/lib/opencode-go-scheduler.js.map +0 -1
  65. package/lib/opencode-go-store.d.ts +0 -18
  66. package/lib/opencode-go-store.js +0 -68
  67. package/lib/opencode-go-store.js.map +0 -1
  68. package/lib/opencode-go-sync.d.ts +0 -94
  69. package/lib/opencode-go-sync.js +0 -364
  70. package/lib/opencode-go-sync.js.map +0 -1
  71. package/lib/opencode-go-writer.d.ts +0 -132
  72. package/lib/opencode-go-writer.js +0 -977
  73. package/lib/opencode-go-writer.js.map +0 -1
  74. package/src/opencode-go-diagnose.ts +0 -223
  75. package/src/opencode-go-grouping.ts +0 -26
  76. package/src/opencode-go-journal.ts +0 -458
  77. package/src/opencode-go-migrate.ts +0 -1764
  78. package/src/opencode-go-migration.ts +0 -552
  79. package/src/opencode-go-one-shot.ts +0 -1356
  80. package/src/opencode-go-planner.ts +0 -472
  81. package/src/opencode-go-scheduler.ts +0 -315
  82. package/src/opencode-go-store.ts +0 -73
  83. package/src/opencode-go-sync.ts +0 -503
  84. package/src/opencode-go-writer.ts +0 -1201
package/lib/index.js CHANGED
@@ -1,190 +1,70 @@
1
- // Plan C (settings-seam): orchestrator with overlay and settings modes.
2
1
  /**
3
- * dsh-model-sync — drive the llm adapter's pi.dev catalog refresh and report
4
- * what changed.
5
- *
6
- * Supports two write modes:
7
- * - 'settings' (default): self-contained fetch → translate → settings.mutate
8
- * pipeline that writes through the host settings service (zero patch
9
- * required; settings.yaml up to dsh 0.1.6, the profile patch on 0.1.7+)
10
- * - 'overlay' (legacy, deprecated): delegates to the patched dsh-llm-pi-ai's
11
- * piAiCatalog.refresh() to overlay pi.dev entries in memory. dsh 0.2.1
12
- * removed the piAiCatalog seam entirely (the pi-ai 0.87.1 → 1.3.0
13
- * ModelsStore rework), so this mode can never refresh there and every
14
- * round degrades to a notice; use the settings mode.
2
+ * dsh-model-sync — keep Builtin Providers synchronized with pi.dev and
3
+ * detach supported Official Sync vendors (starting with OpenCode Go) into
4
+ * per-protocol Managed Custom Providers backed by their official models API.
15
5
  *
16
6
  * @module dsh-model-sync
17
7
  */
18
8
  import z from '@deepseek-ai/schemastery';
19
- import { diffModelIds, diffEntries } from "./diff.js";
20
- import { fetchRemoteCatalog, loadModelsStore, } from "./remote-catalog.js";
9
+ import { diffEntries, diffModelIds } from "./diff.js";
10
+ import { MODELS_STORE_PATH, fetchRemoteCatalog, loadModelsStore, } from "./remote-catalog.js";
21
11
  import { translateEntries, } from "./translate.js";
22
12
  import { syncToSettings, } from "./writer.js";
23
13
  import { BUILTIN_CATALOG_SNAPSHOT } from "./builtin-catalog-snapshot.js";
24
- import { refreshLiveCatalog, getLiveBuiltinCatalogForRoute } from "./live-catalog.js";
25
- import { checkRouteCredential, deriveKeyRef } from "./route-credential.js";
26
- import { OPENCODE_GO_MODELS_URL, OPENCODE_GO_DEFAULT_INTERVAL_MINUTES, fetchGoOfficialModels, fetchGoPublicCatalogIds, fingerprintKey } from "./opencode-go-source.js";
27
- import { GO_SLOT_ROUTES } from "./opencode-go-grouping.js";
28
- import { createModelsStoreOwnershipStore } from "./opencode-go-store.js";
29
- import { createModelsStoreJournalStore, } from "./opencode-go-journal.js";
30
- import { GO_FETCH_SERVICE, GO_OWNERSHIP_STORE_SERVICE, GO_OVERRIDE_STORER_SERVICE, runGoSyncRound, } from "./opencode-go-sync.js";
31
- import { GO_SCHEDULER_RANDOM_SERVICE, GO_SCHEDULER_TIMERS_SERVICE, GoScheduler, } from "./opencode-go-scheduler.js";
14
+ import { getLiveBuiltinCatalogForRoute, refreshLiveCatalog } from "./live-catalog.js";
15
+ import { checkRouteCredential } from "./route-credential.js";
32
16
  import { PROVIDER_NATIVE_ENDPOINTS, fetchProviderNativeModels, mergeProviderNativeEntries, resolveRouteCredentialValue, } from "./provider-native.js";
33
- import { runLegacySettingsImport, resolveDshHome, } from "./legacy-import.js";
34
- import { runGoDiagnostic, formatGoDiagnosticReport } from "./opencode-go-diagnose.js";
35
- import { PROFILE_IDENTITY_REQUIRED_MESSAGE, PROFILE_IDENTITY_STATUS_HINT, resolveProfileKey, } from "./opencode-go-profile.js";
36
- import { GO_MIGRATION_STORE_SERVICE, appliedFingerprintFieldsOf, createModelsStoreMigrationStateStore, goLedgerManagedIds, isGoRoute, MIGRATION_GATE_HINT, migrationStatusOf, readGoProviderSections, routeWriter, unclaimedRecordState, } from "./opencode-go-migration.js";
37
- import { goOwnershipKey } from "./opencode-go-planner.js";
38
- import { applyMigration, buildMigrationPlanFromDeps, formatMigrationPlan, migrationStatusReport, rollbackMigration, } from "./opencode-go-migrate.js";
39
- import { runMigrateGoOneShot, parseMigrateGoFlags, } from "./opencode-go-one-shot.js";
40
- import { MODELS_STORE_PATH } from "./remote-catalog.js";
41
- import { mkdir, open, readFile, readdir, rename, stat as statFd, unlink, writeFile } from 'node:fs/promises';
42
- import { readFileSync, statSync, writeFileSync } from 'node:fs';
17
+ import { resolveDshHome, runLegacySettingsImport, } from "./legacy-import.js";
18
+ import { OPENCODE_GO_DEFAULT_INTERVAL_MINUTES, OPENCODE_GO_MODELS_URL } from "./opencode-go-source.js";
19
+ import { resolveProfileKey } from "./opencode-go-profile.js";
20
+ import { formatUnsupportedProviderError, listOfficialAdapters, resolveOfficialAdapter, } from "./official-adapter.js";
21
+ import { createDefaultOfficialMigrationStore, createOfficialMigrationStore, } from "./official-store.js";
22
+ import { runOfficialSyncRound, } from "./official-sync.js";
23
+ import { OfficialSyncScheduler, } from "./official-scheduler.js";
24
+ import { runOfficialMigrate, runOfficialRollback, runOfficialStatus, } from "./official-migrate.js";
43
25
  export const name = 'dsh-model-sync';
44
- /** The settings seam this plugin consumes (its own config namespace). */
45
26
  export const inject = ['settings'];
46
- /** P1d-2 seams: injected official entries (plan/apply) and optional reference writer. */
47
- export const GO_MIGRATION_ENTRIES_SERVICE = 'goMigrationEntries';
48
- export const GO_MIGRATION_REF_WRITER_SERVICE = 'goMigrationRefWriter';
49
- /** Public (unauthenticated) official catalog ids for id classification (design §14.2).
50
- * `undefined` ⇒ fail-closed `unclassified`. Tests inject an array/function. */
51
- export const GO_MIGRATION_PUBLIC_CATALOG_SERVICE = 'goMigrationPublicCatalog';
52
- /** Capability flag: when true, `--adopt` is refused and plan mode is adopt-disabled. */
53
- export const GO_MIGRATION_ADOPT_DISABLED_SERVICE = 'goMigrationAdoptDisabled';
54
- /** Optional override for the single-flight check (tests inject an in-flight mutex). */
55
- export const GO_MIGRATION_MUTEX_SERVICE = 'goMigrationMutex';
56
- /** O1/C2 seam: injected write-ahead journal store (tests use a temp-dir store). */
57
- export const GO_JOURNAL_STORE_SERVICE = 'goJournalStore';
58
- /**
59
- * One-shot migrate-go path overrides (tests point everything at a temp dir;
60
- * a host may pin non-default locations). Plain `undefined` fields fall back
61
- * to resolveDshHome() / MODELS_STORE_PATH / `<home>/profiles`.
62
- */
63
- export const GO_ONESHOT_PATHS_SERVICE = 'goOneShotPaths';
64
- // dsh-settings 0.1.7 rewrote the seam: the runtime register(ns, schema) call
65
- // is gone, and a plugin's settings form is projected from its exported
66
- // `Config` schema — the namespace IS the profile entry id. The bundle patch
67
- // mounts this plugin under the stable id below, so `dsh-model-sync` is the
68
- // namespace the settings UI (and the legacy settings.yaml import) address.
27
+ /** Optional test/host service seams for Official Sync. */
28
+ export const OFFICIAL_FETCH_SERVICE = 'officialFetch';
29
+ export const OFFICIAL_SCHEDULER_TIMERS_SERVICE = 'officialSchedulerTimers';
30
+ export const OFFICIAL_SCHEDULER_RANDOM_SERVICE = 'officialSchedulerRandom';
31
+ export const OFFICIAL_SESSION_HEADER_DETECT_SERVICE = 'officialSessionHeaderDetect';
32
+ export const OFFICIAL_COMPAT_HINTS_SERVICE = 'officialCompatHints';
33
+ export const OFFICIAL_MIGRATION_PATHS_SERVICE = 'officialMigrationPaths';
69
34
  const OWN_ENTRY_ID = 'dsh-model-sync';
70
- /**
71
- * The plugin's `Config` schema: the settings form the 0.1.7 host projects from
72
- * the `dsh-model-sync` entry. Every field is user-adjustable and therefore
73
- * `.volatile()` — volatile fields are the only ones the settings page can edit
74
- * (and the only ones the legacy settings.yaml import accepts), and they hot-
75
- * reload without remounting the plugin. Requires schemastery >= 3.18.4 (the
76
- * version the dsh 0.1.7 wave ships), which provides `.volatile()`.
77
- */
78
35
  export const Config = z.object({
79
- /**
80
- * Write mode: 'settings' (default, zero-patch settings.mutate pipeline) or
81
- * 'overlay'. DEPRECATED: 'overlay' delegates to the patched adapter's
82
- * piAiCatalog.refresh, a seam dsh 0.2.1 removed outright (pi-ai 1.3.0
83
- * ModelsStore rework) — every overlay round now degrades to a notice.
84
- * Use the settings mode.
85
- */
86
36
  writeMode: z.union(['settings', 'overlay']).default('settings').volatile(),
87
- /** Minutes between auto refreshes (default 240 = 4 hours); 0 = startup-only. */
88
37
  intervalMinutes: z.number().step(1).min(0).default(240).volatile(),
89
- /** Delay before the first auto refresh, so the llm adapter is ready. */
90
38
  startupDelaySeconds: z.number().step(1).min(0).default(5).volatile(),
91
- /** Abort budget for one forced refresh's network round. */
92
39
  refreshTimeoutMs: z.number().step(1).min(1000).default(120000).volatile(),
93
- /** Routes to manage (empty = all pi.dev routes). */
94
40
  managedRoutes: z.array(z.string()).default([]).volatile(),
95
- /** Keep builtin-only models not in pi.dev (smooth migration). */
96
41
  keepBuiltinOnly: z.boolean().default(true).volatile(),
97
- /** Drop unserviceable entries (true) or abort the entire route (false). */
98
42
  dropUnserviceable: z.boolean().default(true).volatile(),
99
- /**
100
- * Union each mapped route's first-party /models listing into the pi.dev
101
- * result (additions only — see provider-native.ts). Default on: the native
102
- * listing is the fresher source; pi.dev lags (measured 2026-09-22).
103
- */
104
43
  providerNativeFetch: z.boolean().default(true).volatile(),
105
- /** Notify on changes (logger + /model-sync report). */
106
44
  syncNotify: z.boolean().default(false).volatile(),
107
- /**
108
- * Force all models with a non-empty thinkingFormat to have max reasoning
109
- * effort. Skips S2 gate's SRE check, ensures reasoningEfforts contains
110
- * max, and forces compat.supportsReasoningEffort=true (S5 gate, openai-
111
- * completions only). 400 risk is on the user.
112
- */
113
45
  forceMaxReasoningEffort: z.boolean().default(false).volatile(),
114
- /**
115
- * keepBuiltinOnly may re-emit builtin ids the official default model list
116
- * dropped (dsh 0.1.7 removed deepseek-v4-flash / deepseek-v4-flash-vision-
117
- * exp). Those stay in the snapshot for historical user configurations but
118
- * are excluded from the synced list unless this flag opts them back in —
119
- * a re-emitted retired id is a model the 0.1.7 host no longer resolves.
120
- */
121
46
  keepDeprecatedBuiltin: z.boolean().default(false).volatile(),
122
- /**
123
- * OpenCode Go / Zen configuration contract (design §6.2.6). Published in one
124
- * Config schema in P1: read-only subset (go.enabled/ref/modelsUrl/
125
- * intervalMinutes, zen.enabled/ref/mode/modelsUrl) plus the write-side subset
126
- * (go.routes/adoptExisting/pinnedModels/confirmRemovals,
127
- * zen.routes/seedFromBuiltin). Defaults are byte-for-byte the P0 constants —
128
- * `modelsUrl` and `ref` are imported from the P0 modules so a P0→P1 drift is
129
- * impossible. Zen stays login-only with no modelsUrl by default (design A5).
130
- * Nested leaves are `.volatile()` (host settings can edit them); the parent
131
- * objects are not, because schemastery forbids a volatile field under an
132
- * enclosing volatile field.
133
- */
134
- opencode: z.object({
135
- go: z.object({
136
- enabled: z.boolean().default(false).volatile(),
137
- ref: z.string().default(deriveKeyRef('opencode-go')).volatile(),
47
+ officialSync: z.object({
48
+ 'opencode-go': z.object({
49
+ intervalMinutes: z.number().step(1).min(0).default(OPENCODE_GO_DEFAULT_INTERVAL_MINUTES).volatile(),
138
50
  modelsUrl: z.string().default(OPENCODE_GO_MODELS_URL).volatile(),
139
- intervalMinutes: z.number().step(1).min(15).default(OPENCODE_GO_DEFAULT_INTERVAL_MINUTES).volatile(),
140
- adoptExisting: z.boolean().default(false).volatile(),
141
- pinnedModels: z.array(z.string()).default([]).volatile(),
51
+ sessionHeader: z.union(['auto', 'static', 'none']).default('auto').volatile(),
142
52
  routes: z.object({
143
- chat: z.string().default('opencode-go').volatile(),
53
+ chat: z.string().default('opencode-go-chat').volatile(),
144
54
  msg: z.string().default('opencode-go-msg').volatile(),
145
55
  resp: z.string().default('opencode-go-resp').volatile(),
146
56
  google: z.string().default('opencode-go-google').volatile(),
147
57
  }).default({}),
148
- confirmRemovals: z.number().step(1).min(2).default(2).volatile(),
149
- }).default({}),
150
- zen: z.object({
151
- enabled: z.boolean().default(true).volatile(),
152
- ref: z.string().default('OPENCODE_API_KEY').volatile(),
153
- mode: z.union(['login-only', 'routes']).default('login-only').volatile(),
154
- /** No proven listing endpoint; without it routes mode is unsupported. */
155
- modelsUrl: z.string().volatile(),
156
- seedFromBuiltin: z.boolean().default(false).volatile(),
157
- routes: z.object({
158
- chat: z.string().default('opencode-zen').volatile(),
159
- msg: z.string().default('opencode-zen-msg').volatile(),
160
- resp: z.string().default('opencode-zen-resp').volatile(),
161
- }).default({}),
162
58
  }).default({}),
163
59
  }).default({}),
164
60
  });
165
- /**
166
- * Default routes to manage when managedRoutes is empty.
167
- *
168
- * NOTE (intentional deviation from design doc §5.5): the design suggests
169
- * dynamically enumerating routes from the llm adapter's provider list, but
170
- * that requires pi.dev to have been fetched first — unavailable during
171
- * bootstrap. A static list is the pragmatic fallback; update manually when
172
- * new routes appear on pi.dev.
173
- */
174
61
  const DEFAULT_ROUTES = [
175
62
  'opencode-go',
176
63
  'zai-coding-cn',
177
64
  'minimax-cn',
178
65
  'xiaomi-token-plan-cn',
179
66
  ];
180
- /** Default route list — exported for tests that need to iterate the same set
181
- * the plugin syncs when `managedRoutes` is empty. Not part of the public
182
- * runtime surface; subject to change without notice. */
183
67
  export const DEFAULT_ROUTES_LIST = DEFAULT_ROUTES;
184
- // ---------------------------------------------------------------------------
185
- // P1c go config / dependency helpers (design §6.2.6)
186
- // ---------------------------------------------------------------------------
187
- /** Read a volatile Config leaf, tolerating hosts/tests that hand a plain value. */
188
68
  function readVolatile(slot, fallback) {
189
69
  if (slot === undefined)
190
70
  return fallback;
@@ -193,68 +73,29 @@ function readVolatile(slot, fallback) {
193
73
  }
194
74
  return slot;
195
75
  }
196
- /**
197
- * Project the go Config subset for one round. Reads the live volatile refs, so
198
- * a settings edit takes effect on the next round without a remount. The
199
- * defensive shape also keeps older/partial fake configs (no `opencode` block)
200
- * on the default zero-behavior path instead of throwing during apply().
201
- */
202
- function readGoRuntimeConfig(config) {
203
- const raw = config;
204
- const opencode = raw.opencode;
205
- const go = opencode?.go;
206
- const rawRoutes = go?.routes;
207
- const routes = Object.fromEntries(Object.keys(GO_SLOT_ROUTES).map((slot) => [
208
- slot,
209
- readVolatile(rawRoutes?.[slot], GO_SLOT_ROUTES[slot]),
210
- ]));
211
- return {
212
- enabled: readVolatile(go?.enabled, false),
213
- value: {
214
- enabled: readVolatile(go?.enabled, false),
215
- ref: readVolatile(go?.ref, deriveKeyRef('opencode-go')),
216
- modelsUrl: readVolatile(go?.modelsUrl, OPENCODE_GO_MODELS_URL),
217
- routes,
218
- pinnedModels: readVolatile(go?.pinnedModels, []),
219
- confirmRemovals: readVolatile(go?.confirmRemovals, 2),
220
- adoptExisting: readVolatile(go?.adoptExisting, false),
221
- },
222
- };
223
- }
224
- /**
225
- * Project the go scheduling subset (design §6.3). `intervalMinutes` is the go
226
- * field (default 60, floor 15, enforced by the scheduler); the startup delay is
227
- * the shared top-level field the design names for startup jitter.
228
- *
229
- * `enabled` defaults to false — the design §6.2.6 value, unchanged by P1d-1.
230
- * Migration zero-write is now enforced independently by routeWriter (§14.6 /
231
- * §14.7) on every write path, so this default is a product choice, not the
232
- * only protection. All scheduler paths are still gated by this value.
233
- */
234
- function readGoSchedulerConfig(config) {
76
+ function readOfficialAdapterConfig(config, adapter) {
235
77
  const raw = config;
236
- const opencode = raw.opencode;
237
- const go = opencode?.go;
78
+ const officialRoot = raw.officialSync;
79
+ const block = officialRoot?.[adapter.id];
80
+ const rawRoutes = block?.routes;
81
+ const routes = {};
82
+ for (const slot of adapter.slotOrder) {
83
+ routes[slot] = readVolatile(rawRoutes?.[slot], adapter.defaultSlotRoutes[slot]);
84
+ }
238
85
  return {
239
- enabled: readVolatile(go?.enabled, false),
240
- intervalMinutes: readVolatile(go?.intervalMinutes, OPENCODE_GO_DEFAULT_INTERVAL_MINUTES),
241
- startupDelaySeconds: readVolatile(raw.startupDelaySeconds, 5),
86
+ intervalMinutes: readVolatile(block?.intervalMinutes, adapter.defaultIntervalMinutes),
87
+ modelsUrl: readVolatile(block?.modelsUrl, adapter.defaultModelsUrl),
88
+ sessionHeader: readVolatile(block?.sessionHeader, 'auto'),
89
+ routes,
242
90
  };
243
91
  }
244
- /**
245
- * Revision-keyed (not time-window-keyed) reentry marker. `readRevision` reads
246
- * the live descriptor after a mutate, so the marker always holds the revision
247
- * the host stamped on OUR write; a later event for the same ns+revision can
248
- * only be that write's echo (§14.7.2 items 1/5). `now` is injected so tests
249
- * never depend on a wall clock.
250
- */
251
- function createOwnWriteTracker(readRevision, now) {
92
+ function createOwnWriteTracker(readRevision) {
252
93
  let last;
253
- const tracker = {
94
+ return {
254
95
  record(ns) {
255
96
  const revision = readRevision(ns);
256
97
  if (revision !== undefined)
257
- last = { ns, revision, at: now() };
98
+ last = { ns, revision };
258
99
  },
259
100
  matches(ns, eventRevision) {
260
101
  if (last === undefined || last.ns !== ns)
@@ -265,24 +106,13 @@ function createOwnWriteTracker(readRevision, now) {
265
106
  return current !== undefined && current === last.revision;
266
107
  },
267
108
  };
268
- return tracker;
269
109
  }
270
110
  function settingsRevision(settings, ns) {
271
111
  return settings?.describe().find((desc) => desc.ns === ns)?.revision;
272
112
  }
273
113
  export async function apply(ctx, config) {
274
- // On dsh 0.1.7 the resolved Config arrives as apply()'s second argument:
275
- // every volatile field is a stable reference (see VolatileRef), so the
276
- // reads below are live views — no scope.get() and no scope.watch() (both
277
- // removed from dsh-settings; the hot-reload notification moved to the
278
- // settings/document-updated event, subscribed at the bottom of apply()).
279
- // P1d-1: one reentry marker shared by every write path. `rawSettings()` is
280
- // resolved per call so a host that mounts the settings service after this
281
- // plugin still works; the thin wrapper records the post-mutate revision for
282
- // the document-updated reentry check (§14.7.2). Every settings-writing path
283
- // below goes through `settingsForWrite*` — never a bare ctx.get('settings').
284
114
  const rawSettings = () => ctx.get('settings');
285
- const ownWrite = createOwnWriteTracker((ns) => settingsRevision(rawSettings(), ns), () => Date.now());
115
+ const ownWrite = createOwnWriteTracker((ns) => settingsRevision(rawSettings(), ns));
286
116
  const settingsForWriteFrom = (context) => {
287
117
  const raw = context.get('settings');
288
118
  if (raw === undefined)
@@ -296,153 +126,24 @@ export async function apply(ctx, config) {
296
126
  };
297
127
  };
298
128
  const settingsForWrite = () => settingsForWriteFrom(ctx);
299
- // B1/H9: one stable profile identity per plugin instance, resolved from the
300
- // host (profileContext / DSH_PROFILE). Both file-backed stores below scope
301
- // every shared models-store key with it so two profiles cannot share a
302
- // migration record or ownership ledger entry. When no identity can be
303
- // resolved there is NO 'default' collapse: every file-backed ledger path
304
- // fails closed with an actionable error instead of silently sharing a key.
305
129
  const profileKey = resolveProfileKey(ctx);
306
- const requireScopedProfileKey = () => {
307
- if (profileKey === undefined)
308
- throw new Error(PROFILE_IDENTITY_REQUIRED_MESSAGE);
309
- return profileKey;
310
- };
311
- // The injection seam is an explicit opt-in (tests / hosts that supply their
312
- // own scoped store); only the file-backed fallback requires host identity.
313
- const migrationStore = () => ctx.get(GO_MIGRATION_STORE_SERVICE)
314
- ?? createModelsStoreMigrationStateStore(undefined, requireScopedProfileKey());
315
- const ownershipStoreForRound = () => ctx.get(GO_OWNERSHIP_STORE_SERVICE)
316
- ?? createModelsStoreOwnershipStore(undefined, requireScopedProfileKey());
317
- // O1/C2: the journal lives in the same models-store.json. An injected seam
318
- // wins (tests use a temp-dir accessor); without a resolved profile identity
319
- // there is NO journal — never fall back to the real default ~/.dsh from a
320
- // host/test that supplied no identity (the ledger path fails closed too).
321
- const journalStoreForRound = () => ctx.get(GO_JOURNAL_STORE_SERVICE)
322
- ?? (profileKey === undefined ? undefined : createModelsStoreJournalStore());
323
- /**
324
- * Read current migration status from the persisted record + live settings +
325
- * (when a key fingerprint is available) the live ownership ledger.
326
- * `strict` rethrows a record read failure so the §14.7.5 second gate can fail
327
- * closed with `canWrite-unavailable`; the normal path degrades to "no record"
328
- * (conservative legacy detection) as before.
329
- */
330
- const loadMigrationStatus = async (opts = {}) => {
331
- const desc = rawSettings()?.describe().find((d) => d.ns === 'llm-pi-ai');
332
- // H9 fail-closed: with no resolvable profile identity the file-backed store
333
- // factory throws. A non-strict READ degrades to "no record" (gate closed,
334
- // zero writes) so boot-time status refreshes / isApplying cannot produce an
335
- // unhandled rejection; strict reads (the per-mutate second gate) rethrow.
336
- // Every WRITE path still fails closed when it builds its file-backed store.
337
- // N2: remember an identity-refused file-backed store so the (non-strict)
338
- // status read can surface it instead of looking like a normal legacy state.
339
- // The check is on the thrown identity error, not on `profileKey === undefined`
340
- // alone: an injected-store host has a usable ledger even with no host
341
- // identity and must NOT get a false "identity unavailable" report.
342
- let identityUnavailable = false;
343
- let store;
344
- try {
345
- store = migrationStore();
346
- }
347
- catch (err) {
348
- if (opts.strict === true)
349
- throw err;
350
- if (err instanceof Error && err.message === PROFILE_IDENTITY_REQUIRED_MESSAGE)
351
- identityUnavailable = true;
352
- }
353
- let record;
354
- try {
355
- record = await store?.read();
356
- }
357
- catch (err) {
358
- if (opts.strict === true)
359
- throw err;
360
- record = undefined; // unreadable ⇒ conservative legacy detection
361
- }
362
- const goRoutes = Object.values(readGoRuntimeConfig(config).value.routes ?? {});
363
- let managedIds;
364
- const fp = opts.keyFingerprint;
365
- if (fp !== undefined) {
366
- let ownership;
367
- try {
368
- ownership = ownershipStoreForRound();
369
- }
370
- catch (err) {
371
- if (opts.strict === true)
372
- throw err;
373
- if (err instanceof Error && err.message === PROFILE_IDENTITY_REQUIRED_MESSAGE)
374
- identityUnavailable = true;
375
- }
376
- // Only routes with a REAL ledger entry join the fingerprint set. The old
377
- // `<route>: []` filler for configured-but-absent routes disagreed with
378
- // migrate/onOwnWrite and produced a phantom `fingerprint-healed` on the
379
- // first healthy round after onboarding.
380
- managedIds = await goLedgerManagedIds(goRoutes, (route) => ownership === undefined
381
- ? Promise.resolve(undefined)
382
- : ownership.read(goOwnershipKey(route, fp)));
383
- }
384
- const status = migrationStatusOf(desc, record, goRoutes, managedIds);
385
- // W1/D6: the go report and `migrate status` must agree on the label for a
386
- // record this profile cannot claim. Use the SAME helper as migrate status;
387
- // only when our own scoped read() found no record (B1 isolation). This is
388
- // label-only: both states already keep the gate closed / write authority
389
- // none / zero writes, and nothing is claimed or deleted.
390
- if (record === undefined && store?.unclaimedRecords !== undefined) {
391
- let unclaimed;
392
- try {
393
- unclaimed = await store.unclaimedRecords();
394
- }
395
- catch (err) {
396
- if (opts.strict === true)
397
- throw err;
398
- unclaimed = []; // advisory provenance scan never changes the gate
399
- }
400
- const recordState = unclaimedRecordState(unclaimed);
401
- if (recordState !== undefined)
402
- status.state = recordState;
403
- }
404
- // N2: a non-strict refresh that degraded because no identity was available
405
- // must be VISIBLE — log the actionable error (covers boot / document-updated
406
- // refresh where there is no report line) and tag the status so sync reports
407
- // do not show the normal legacy hint. This changes NO write/fail-closed
408
- // behavior: the gate is already closed and no store/settings write occurs.
409
- if (identityUnavailable) {
410
- status.identityUnavailable = true;
411
- ctx.logger.warn('model-sync: non-strict status refresh degraded — %s', PROFILE_IDENTITY_REQUIRED_MESSAGE);
412
- }
413
- // §14.7.4 self-heal: identity matches but the stored full fingerprint is
414
- // stale because the fingerprint persist failed after settings+ledger landed.
415
- // Rewrite it in the same queue instead of closing the gate forever.
416
- if (status.fingerprintHealed && typeof store?.write === 'function') {
417
- try {
418
- ctx.logger.info('model-sync: fingerprint-healed (identity matched; stale appliedFingerprint)');
419
- await store.write({
420
- ...(record ?? {}),
421
- appliedManagedIds: managedIds ?? record?.appliedManagedIds,
422
- appliedFingerprint: status.expectedFingerprint,
423
- });
424
- status.appliedFingerprint = status.expectedFingerprint;
425
- status.fingerprintHealed = false;
426
- }
427
- catch (err) {
428
- ctx.logger.warn('model-sync: fingerprint-healed write failed: %s', err instanceof Error ? err.message : String(err));
429
- }
130
+ const pathOverrides = () => ctx.get(OFFICIAL_MIGRATION_PATHS_SERVICE);
131
+ const migrationStoreFor = (adapterId, keyOverride) => {
132
+ const effectiveKey = keyOverride ?? profileKey;
133
+ if (effectiveKey === undefined)
134
+ return undefined;
135
+ const overrides = pathOverrides();
136
+ if (overrides?.storeAccessor !== undefined) {
137
+ return createOfficialMigrationStore(overrides.storeAccessor, effectiveKey, adapterId);
430
138
  }
431
- return status;
139
+ return createDefaultOfficialMigrationStore(effectiveKey, adapterId, overrides?.modelsStorePath);
432
140
  };
433
141
  // -----------------------------------------------------------------------
434
- // Overlay mode sync (existing behavior)
142
+ // Legacy pi.dev sync (Builtin Provider track)
435
143
  // -----------------------------------------------------------------------
436
- const syncOverlay = async (config, llm, force) => {
144
+ const syncOverlay = async (cfg, llm, force) => {
437
145
  const catalog = ctx.get('piAiCatalog');
438
146
  if (catalog?.refresh === undefined) {
439
- // Degradation path (never throws): the overlay needs a hand-patched
440
- // dsh-llm-pi-ai exposing piAiCatalog.refresh(). Since dsh 0.1.2-alpha.3
441
- // the patch cannot even apply (it shims settingsNamespace and
442
- // installSettingsSection, both removed from dsh-settings), and dsh
443
- // 0.2.1 removed the piAiCatalog seam outright (pi-ai 1.3.0 ModelsStore
444
- // rework) — so every host now lands here unless it runs the settings
445
- // mode, which is the supported path.
446
147
  return 'catalog refresh is unavailable — the dsh-llm-pi-ai remote-catalog patch is not applied (deprecated: dsh 0.2.1 removed the piAiCatalog seam, pi-ai 1.3.0 ModelsStore rework); the model list is the static catalog only. Switch writeMode to the supported settings mode.';
447
148
  }
448
149
  let providers;
@@ -469,7 +170,7 @@ export async function apply(ctx, config) {
469
170
  const before = await list();
470
171
  const errors = await catalog.refresh({
471
172
  force,
472
- signal: AbortSignal.timeout(config.refreshTimeoutMs.get()),
173
+ signal: AbortSignal.timeout(cfg.refreshTimeoutMs.get()),
473
174
  });
474
175
  const after = await list();
475
176
  const lines = [];
@@ -495,62 +196,42 @@ export async function apply(ctx, config) {
495
196
  }
496
197
  return lines.join('\n');
497
198
  };
498
- // -----------------------------------------------------------------------
499
- // Settings mode sync (Plan C: fetch → translate → write)
500
- // -----------------------------------------------------------------------
501
- const syncSettings = async (config, force) => {
199
+ const loadMigratedSkipMap = async () => {
200
+ const skipped = new Map();
201
+ for (const adapter of listOfficialAdapters()) {
202
+ const store = migrationStoreFor(adapter.id);
203
+ const record = await store?.read().catch(() => undefined);
204
+ if (record !== undefined) {
205
+ skipped.set(adapter.builtinProviderId, adapter);
206
+ for (const r of record.managedRoutes)
207
+ skipped.set(r, adapter);
208
+ }
209
+ }
210
+ return skipped;
211
+ };
212
+ const syncSettings = async (cfg, force) => {
502
213
  const settings = settingsForWrite();
503
214
  const logger = ctx.logger;
504
- const store = loadModelsStore();
215
+ const store = loadModelsStore(pathOverrides()?.modelsStorePath);
505
216
  const lines = [];
506
- // Determine routes to sync
507
- const managedRoutes = config.managedRoutes.get();
508
- const routes = managedRoutes.length > 0
509
- ? [...managedRoutes]
510
- : DEFAULT_ROUTES;
511
- // P1d-1 single writer: while opencode.go.enabled=true the legacy pi.dev
512
- // path must NEVER write an `opencode-go*` route — not even in `absent` /
513
- // `applied` state (that belongs to go sync), and especially not when the
514
- // migration gate is closed. Login-triggered/manual/auto all funnel through
515
- // this one loop (design §14.7.1, ADR-008).
516
- const { value: goCfg } = readGoRuntimeConfig(config);
517
- const goRouteIds = Object.values(goCfg.routes ?? {});
518
- const piDevAuthority = { caller: 'pi.dev', goEnabled: goCfg.enabled, goRoutes: goRouteIds };
519
- let piDevMigration;
217
+ const managedRoutes = cfg.managedRoutes.get();
218
+ const routes = managedRoutes.length > 0 ? [...managedRoutes] : DEFAULT_ROUTES;
219
+ const migratedSkip = await loadMigratedSkipMap();
520
220
  const gateDesc = settings?.describe().find((d) => d.ns === 'llm-pi-ai');
521
221
  const gateCtx = ctx;
522
222
  for (const route of routes) {
523
- // Single-writer gate before ANY fetch/translate/mutate for go routes.
524
- // A skip always produces a report line (never silent, §14.7.1).
525
- if (goCfg.enabled && isGoRoute(route, goRouteIds)) {
526
- piDevMigration ??= await loadMigrationStatus();
527
- const decision = routeWriter(route, piDevAuthority, piDevMigration);
528
- if (decision.decision === 'skip') {
529
- // N2: an identity-refused ledger is NOT a normal legacy state. Surface
530
- // the actionable identity hint instead of the generic migration hint.
531
- const hint = piDevMigration.identityUnavailable === true
532
- ? `; ${PROFILE_IDENTITY_STATUS_HINT}`
533
- : (piDevMigration.state === 'absent' || piDevMigration.state === 'applied'
534
- ? ''
535
- : `; ${MIGRATION_GATE_HINT}`);
536
- lines.push(`${route}: skipped — ${decision.reason}${hint}`);
537
- continue;
538
- }
223
+ const ownerAdapter = migratedSkip.get(route);
224
+ if (ownerAdapter !== undefined) {
225
+ const alias = ownerAdapter.aliases[0] ?? ownerAdapter.id;
226
+ lines.push(`${route}: skipped — migrated to official custom providers (use /model-sync ${alias})`);
227
+ continue;
539
228
  }
540
- // Layer 1 follows llm-pi-ai's resolveApiKey: prefer the credentials seam.
541
- // Layer 2 follows its authContextFrom(ctx).env(): launch environment,
542
- // or process.env when the service is absent. Both miss → skip fetch,
543
- // translate and settings.mutate, naming the missing ref in the report.
544
- // deriveKeyRef replicates the web UI's conventional reference name.
545
- // Known gap: after credential removal, a same-name shell export allows
546
- // writes, but requests with the seam present still get MISSING_CREDENTIAL.
547
229
  const gate = await checkRouteCredential(gateCtx, gateDesc, route);
548
230
  if (!gate.ok) {
549
231
  lines.push(`${route}: skipped — credential ${gate.ref} not configured`);
550
232
  continue;
551
233
  }
552
- // Fetch from pi.dev — pass force to bypass revalidation throttle (I-5)
553
- const result = await fetchRemoteCatalog(route, config.refreshTimeoutMs.get(), store, { force });
234
+ const result = await fetchRemoteCatalog(route, cfg.refreshTimeoutMs.get(), store, { force });
554
235
  if (result.error !== undefined && result.entries.length === 0) {
555
236
  lines.push(`${route}: fetch failed (${result.error}); keeping last-good`);
556
237
  continue;
@@ -559,34 +240,22 @@ export async function apply(ctx, config) {
559
240
  lines.push(`${route}: no models from pi.dev; skipped`);
560
241
  continue;
561
242
  }
562
- // Translate
563
243
  const translateOpts = {
564
- keepBuiltinOnly: config.keepBuiltinOnly.get(),
565
- dropUnserviceable: config.dropUnserviceable.get(),
244
+ keepBuiltinOnly: cfg.keepBuiltinOnly.get(),
245
+ dropUnserviceable: cfg.dropUnserviceable.get(),
566
246
  dropWarnings: [],
567
- forceMaxReasoningEffort: config.forceMaxReasoningEffort.get(),
247
+ forceMaxReasoningEffort: cfg.forceMaxReasoningEffort.get(),
568
248
  };
569
- // For builtin catalog snapshot: we use a mock for now since we can't
570
- // import pi-ai at runtime. The builtin catalog data is needed for
571
- // base-matching classification. In a real deployment, this would come
572
- // from the built-in snapshot file.
573
249
  const builtinData = getBuiltinCatalogForRoute(route);
574
- // Provider-native union: fold the route's first-party /models listing
575
- // (the fresher source — pi.dev lags; measured 2026-09-22) into the
576
- // pi.dev result. Additions only, capacities only where the listing
577
- // states them; any failure degrades to the pi.dev list unchanged so a
578
- // native hiccup can never lose models.
579
250
  let entries = result.entries;
580
- if (config.providerNativeFetch.get() && PROVIDER_NATIVE_ENDPOINTS[route] !== undefined) {
251
+ if (cfg.providerNativeFetch.get() && PROVIDER_NATIVE_ENDPOINTS[route] !== undefined) {
581
252
  const apiKey = await resolveRouteCredentialValue(ctx, gateDesc, route);
582
253
  if (apiKey === undefined) {
583
254
  lines.push(`${route}: provider-native skipped — credential value unavailable`);
584
255
  }
585
256
  else {
586
- const native = await fetchProviderNativeModels(route, apiKey, config.refreshTimeoutMs.get());
257
+ const native = await fetchProviderNativeModels(route, apiKey, cfg.refreshTimeoutMs.get());
587
258
  if (native.ok) {
588
- // Base-less synthesis needs the route's one addressable api;
589
- // unknown or mixed-protocol routes skip synthesis wholesale.
590
259
  const routeApis = [...new Set(builtinData.map((b) => b.api))];
591
260
  const merged = mergeProviderNativeEntries(entries, native, route, routeApis.length === 1 ? routeApis[0] : undefined);
592
261
  entries = merged.entries;
@@ -604,26 +273,17 @@ export async function apply(ctx, config) {
604
273
  }
605
274
  const builtinIds = new Set(builtinData.map((b) => b.id));
606
275
  const builtinOnlyEntries = translateOpts.keepBuiltinOnly
607
- ? getBuiltinOnlyEntries(route, entries, builtinData, config.keepDeprecatedBuiltin.get())
276
+ ? getBuiltinOnlyEntries(route, entries, builtinData, cfg.keepDeprecatedBuiltin.get())
608
277
  : undefined;
609
278
  const translated = translateEntries(entries, builtinIds, builtinData, route, translateOpts, builtinOnlyEntries);
610
- // Report drops and warnings
611
- if (translated.dropped.length > 0) {
612
- for (const w of translated.dropped) {
613
- lines.push(`${route}: DROPPED ${w.id} — ${w.reason}`);
614
- }
615
- }
616
- if (translated.warnings.length > 0) {
617
- for (const w of translated.warnings) {
618
- lines.push(`${route}: DEGRADED ${w.id} — ${w.reason}`);
619
- }
620
- }
621
- // B1: abort detected — skip writer, only warn
279
+ for (const w of translated.dropped)
280
+ lines.push(`${route}: DROPPED ${w.id} — ${w.reason}`);
281
+ for (const w of translated.warnings)
282
+ lines.push(`${route}: DEGRADED ${w.id} — ${w.reason}`);
622
283
  if (translated.aborted) {
623
284
  lines.push(`${route}: ABORTED — dropUnserviceable=false and ${translated.dropped.length} entries dropped; settings not written`);
624
285
  continue;
625
286
  }
626
- // I-6: generate added/removed diff report from current raw models
627
287
  if (settings !== undefined) {
628
288
  const descs = settings.describe();
629
289
  const llmDesc = descs.find((d) => d.ns === 'llm-pi-ai');
@@ -636,19 +296,8 @@ export async function apply(ctx, config) {
636
296
  lines.push(`${route}: removed ${entryDiff.removed.join(', ')}`);
637
297
  }
638
298
  }
639
- // Write to settings (change-only, with conflict retry); the store
640
- // carries the modelOverrides replay/persist (mutual-exclusion fix)
641
- const syncResult = await syncToSettings(settings, route, translated.entries, logger,
642
- // retranslate callback for conflict retry
643
- async (newRevision) => {
644
- // Re-translate with same data (the remote data hasn't changed;
645
- // only the settings revision changed)
646
- void newRevision; // revision is used by the caller
647
- return translated.entries;
648
- }, store);
299
+ const syncResult = await syncToSettings(settings, route, translated.entries, logger, async () => translated.entries, store);
649
300
  if (syncResult.wrote) {
650
- // Detail suffix for the override flows; routes without overrides keep
651
- // the classic "(wrote)" line byte-for-byte.
652
301
  const reason = syncResult.reason === 'wrote' ? '' : `${syncResult.reason}; `;
653
302
  let detail;
654
303
  if (syncResult.overridesSource === 'settings') {
@@ -674,9 +323,6 @@ export async function apply(ctx, config) {
674
323
  lines.push(`${route}: rejected by settings validation (see log)`);
675
324
  }
676
325
  else if (syncResult.reason === 'store-unavailable') {
677
- // The store failed (corrupt/permission on read, or filesystem on
678
- // write); settings.models was the authoritative source and stays
679
- // untouched either way — the user's folded values are preserved.
680
326
  lines.push(`${route}: skipped (models-store unavailable; settings untouched)`);
681
327
  }
682
328
  else {
@@ -685,31 +331,18 @@ export async function apply(ctx, config) {
685
331
  }
686
332
  return lines.join('\n');
687
333
  };
688
- // -----------------------------------------------------------------------
689
- // Unified syncNow
690
- // -----------------------------------------------------------------------
691
- /** One-shot guard for the overlay-mode deprecation warning. */
692
334
  let overlayDeprecationWarned = false;
693
335
  const syncNow = async (force) => {
694
- // Read the live refs up front; the volatile snapshots are fresh per call.
695
336
  const writeMode = config.writeMode.get();
696
337
  const managedRoutes = config.managedRoutes.get();
697
338
  const routes = managedRoutes.length > 0 ? [...managedRoutes] : DEFAULT_ROUTES;
698
- // Prefer the host's live pi-ai catalog for this round; the frozen
699
- // snapshot is only the no-host fallback. Without this, keepBuiltinOnly
700
- // re-emits ids the host's catalog has already dropped. Awaiting keeps the
701
- // `which`/`npm` probes off the host's event loop (they used to block every
702
- // surface for ~0.2s per round).
703
339
  await refreshLiveCatalog(routes);
704
340
  if (writeMode === 'settings') {
705
341
  return syncSettings(config, force);
706
342
  }
707
- // Overlay mode (legacy). dsh 0.2.1 removed the piAiCatalog seam (pi-ai
708
- // 1.3.0 ModelsStore rework), so this mode can no longer refresh anywhere;
709
- // warn once per process and let the round degrade with its notice.
710
343
  if (!overlayDeprecationWarned) {
711
344
  overlayDeprecationWarned = true;
712
- ctx.logger.warn("model-sync: writeMode 'overlay' is deprecated — dsh 0.2.1 removed the piAiCatalog seam (pi-ai 1.3.0 ModelsStore rework); switch to the default 'settings' mode");
345
+ ctx.logger.warn("model-sync: writeMode 'overlay' is deprecated — dsh 0.2.1 removed the piAiCatalog seam; switch to 'settings' mode");
713
346
  }
714
347
  const llm = ctx.get('llm');
715
348
  if (llm === undefined || llm.listProviders === undefined || llm.listModels === undefined) {
@@ -718,435 +351,111 @@ export async function apply(ctx, config) {
718
351
  return syncOverlay(config, llm, force);
719
352
  };
720
353
  // -----------------------------------------------------------------------
721
- // P1c go round: source → planner → writer, all deps from cordis seams.
722
- // P1c-2 wraps this in the scheduler below; the round itself still owns no
723
- // timer and no command registration.
354
+ // Official Sync Schedulers (one per registered UpstreamProviderAdapter)
724
355
  // -----------------------------------------------------------------------
725
- const runGoRound = async (options = {}) => {
726
- const { value } = readGoRuntimeConfig(config);
727
- const settings = settingsForWrite();
728
- const desc = settings?.describe().find((d) => d.ns === 'llm-pi-ai');
729
- const apiKey = await resolveRouteCredentialValue(ctx, desc, 'opencode-go', value.ref);
730
- // The ledger is keyed by the same credential fingerprint the source uses;
731
- // deriving it here lets the status read include the live managed-id set.
732
- const keyFingerprint = fingerprintKey(typeof apiKey === 'string' ? apiKey.trim() : '');
733
- const migration = await loadMigrationStatus({ keyFingerprint });
734
- const ownershipStore = ownershipStoreForRound();
735
- // The existing models-store accessor already satisfies GoOverrideStorer
736
- // (read(route).overrides + updateOverrides); the service seam lets tests
737
- // point both stores at a temp dir instead of the real ~/.dsh.
738
- const overrideStorer = ctx.get(GO_OVERRIDE_STORER_SERVICE)
739
- ?? loadModelsStore();
740
- return runGoSyncRound({
741
- settings,
742
- ownershipStore,
743
- overrideStorer,
744
- logger: ctx.logger,
745
- // The explicit `adopt` command honours the master switch: disabled means
746
- // zero writes (design §6.2.6). runGoSyncRound checks `enabled` first.
747
- config: options.adopt === true ? { ...value, adoptExisting: true } : value,
748
- apiKey,
749
- fetchImpl: ctx.get(GO_FETCH_SERVICE),
750
- signal: options.signal,
751
- migration,
752
- // O1/C2: journal + reconciliation use the same profile/fingerprint as the
753
- // ledger. Reconciliation runs before the gate inside runGoSyncRound.
754
- journalStore: journalStoreForRound(),
755
- profileKey,
756
- keyFingerprint,
757
- // §14.7.5: the second gate re-reads the persisted record on each mutate
758
- // (strict: a failed read skips the route with canWrite-unavailable).
759
- reloadMigration: () => loadMigrationStatus({ keyFingerprint, strict: true }),
760
- // §14.7.4: settings → ledger → fingerprint, all through the same
761
- // models-store queue; only successful own writes reach this callback.
762
- onOwnWrite: async (route, managedIds) => {
763
- const store = migrationStore();
764
- if (typeof store.write !== 'function')
765
- return; // read-only injected store
766
- let record;
356
+ const schedulers = new Map();
357
+ const timers = ctx.get(OFFICIAL_SCHEDULER_TIMERS_SERVICE);
358
+ const random = ctx.get(OFFICIAL_SCHEDULER_RANDOM_SERVICE);
359
+ const buildMigrateDeps = (targetCtx, adapter) => {
360
+ const overrides = pathOverrides();
361
+ const profileCtx = targetCtx.get('profileContext');
362
+ const launchEnv = targetCtx.get('launchEnvironment');
363
+ return {
364
+ adapter,
365
+ config: readOfficialAdapterConfig(config, adapter),
366
+ home: overrides?.home ?? resolveDshHome(),
367
+ modelsStorePath: overrides?.modelsStorePath ?? MODELS_STORE_PATH,
368
+ profilesDir: overrides?.profilesDir,
369
+ currentProfile: {
370
+ key: resolveProfileKey(targetCtx) ?? profileKey,
371
+ dir: profileCtx?.dir ?? launchEnv?.get('DSH_PROFILE_DIR')?.value,
372
+ },
373
+ currentSettings: settingsForWriteFrom(targetCtx),
374
+ credentialCtx: targetCtx,
375
+ logger: targetCtx.logger,
376
+ timeoutMs: readVolatile(config.refreshTimeoutMs, 120000),
377
+ fetchImpl: targetCtx.get(OFFICIAL_FETCH_SERVICE),
378
+ detectHostSessionHeader: targetCtx.get(OFFICIAL_SESSION_HEADER_DETECT_SERVICE),
379
+ loadPiAiCompatHints: targetCtx.get(OFFICIAL_COMPAT_HINTS_SERVICE),
380
+ resolveAsk: () => {
767
381
  try {
768
- record = await store.read();
382
+ return targetCtx.get('userQuestions');
769
383
  }
770
384
  catch {
771
- return; // cannot merge safely; the next round's self-heal covers it
385
+ return undefined;
772
386
  }
773
- const goRoutes = Object.values(value.routes ?? {});
774
- const liveDesc = rawSettings()?.describe().find((d) => d.ns === 'llm-pi-ai');
775
- const sections = readGoProviderSections(liveDesc, goRoutes);
776
- // Catalog-reuse (0.12.0): legacy protocol routes disappear from
777
- // settings once sync unsets them. Keeping their names in
778
- // appliedIdentityRoutes would make `fingerprintGoIdentity` fill them
779
- // with `{}` — a route set the persisted identity was never computed
780
- // over — and the gate would read `drifted` forever. Shrink the route
781
- // set to the sections that still exist so the identity, the stored
782
- // route set, and the next round's status read all agree.
783
- const presentRoutes = Object.keys(sections ?? {});
784
- const appliedIdentityRoutes = (record?.appliedIdentityRoutes ?? presentRoutes)
785
- .filter((route) => presentRoutes.includes(route));
786
- const appliedManagedIds = { ...(record?.appliedManagedIds ?? {}), [route]: [...managedIds].sort() };
787
- // Same helper + route-set convention as loadMigrationStatus: a normal
788
- // onboarding/own write must not look like a fingerprint drift next round.
789
- const { identity, appliedFingerprint } = appliedFingerprintFieldsOf(sections, { ...(record ?? {}), appliedIdentityRoutes }, appliedManagedIds);
790
- await store.write({
791
- ...(record ?? {}),
792
- appliedIdentity: identity,
793
- appliedIdentityRoutes,
794
- appliedManagedIds,
795
- appliedFingerprint,
796
- });
797
387
  },
798
- });
799
- };
800
- // -----------------------------------------------------------------------
801
- // P1c-2: async timer + scheduling for the go round (design §6.3 / §14.6).
802
- // One GoScheduler instance serves BOTH the timer and the manual /model-sync
803
- // go command, so they share the single-flight lock. Clock and jitter inputs
804
- // are optional cordis services so tests never arm a real timer.
805
- // -----------------------------------------------------------------------
806
- const goTimers = ctx.get(GO_SCHEDULER_TIMERS_SERVICE) ?? {
807
- setTimeout: (fn, ms) => setTimeout(fn, ms),
808
- clearTimeout: (handle) => clearTimeout(handle),
388
+ storeFor: (k) => migrationStoreFor(adapter.id, k),
389
+ storeAccessor: overrides?.storeAccessor,
390
+ fs: overrides?.fs,
391
+ patchIoFor: overrides?.patchIoFor,
392
+ now: overrides?.now,
393
+ onCurrentProfileMigrated: async () => {
394
+ await schedulers.get(adapter.id)?.rearm();
395
+ },
396
+ onCurrentProfileRolledBack: async () => {
397
+ await schedulers.get(adapter.id)?.rearm();
398
+ },
399
+ };
809
400
  };
810
- const goRandom = ctx.get(GO_SCHEDULER_RANDOM_SERVICE)
811
- ?? { next: () => Math.random() };
812
- const goScheduler = new GoScheduler({
813
- config: () => readGoSchedulerConfig(config),
814
- timers: goTimers,
815
- random: goRandom,
816
- runRound: async ({ adopt, signal }) => {
817
- const round = await runGoRound({ adopt, signal });
818
- return {
819
- ok: round.ok,
820
- reason: round.reason,
821
- text: round.text,
822
- failureKind: round.reason === 'source-failed' && round.source?.error !== undefined
823
- ? round.source.error.kind
824
- : undefined,
825
- };
826
- },
827
- report: (text) => {
828
- for (const line of text.split('\n'))
829
- ctx.logger.info('model-sync: %s', line);
830
- },
831
- // M-5: drop (never queue) any round while a migration apply holds the routes.
832
- isApplying: async () => (await loadMigrationStatus()).applying,
833
- });
834
- ctx.effect(() => () => goScheduler.dispose(), 'dsh-model-sync: go scheduler dispose');
835
- // A changed credential invalidates any accumulated backoff: a fixed key must
836
- // retry on the normal schedule instead of waiting out a capped 6h backoff
837
- // (design §6.3). The effect scopes the listener to this plugin's lifetime —
838
- // unload removes it together with the scheduler.
401
+ for (const adapter of listOfficialAdapters()) {
402
+ const scheduler = new OfficialSyncScheduler({
403
+ adapterId: adapter.id,
404
+ timers,
405
+ random,
406
+ getIntervalMinutes: () => readOfficialAdapterConfig(config, adapter).intervalMinutes,
407
+ getStartupDelaySeconds: () => readVolatile(config.startupDelaySeconds, 5),
408
+ isMigrated: async () => (await migrationStoreFor(adapter.id)?.read()) !== undefined,
409
+ runRound: ({ signal }) => runOfficialSyncRound({
410
+ adapter,
411
+ config: readOfficialAdapterConfig(config, adapter),
412
+ settings: settingsForWrite(),
413
+ migrationStore: migrationStoreFor(adapter.id),
414
+ credentialCtx: ctx,
415
+ logger: ctx.logger,
416
+ timeoutMs: readVolatile(config.refreshTimeoutMs, 120000),
417
+ signal,
418
+ fetchImpl: ctx.get(OFFICIAL_FETCH_SERVICE),
419
+ detectHostSessionHeader: ctx.get(OFFICIAL_SESSION_HEADER_DETECT_SERVICE),
420
+ loadPiAiCompatHints: ctx.get(OFFICIAL_COMPAT_HINTS_SERVICE),
421
+ }),
422
+ onReport: (trigger, result) => {
423
+ if (trigger === 'manual')
424
+ return;
425
+ if (!result.ok) {
426
+ ctx.logger.warn('model-sync: %s (%s) %s', adapter.id, trigger, result.text);
427
+ }
428
+ else if (result.changed && readVolatile(config.syncNotify, false)) {
429
+ for (const line of result.text.split('\n'))
430
+ ctx.logger.info('model-sync: %s', line);
431
+ }
432
+ else if (result.changed) {
433
+ ctx.logger.info('model-sync: %s (%s) updated models', adapter.id, trigger);
434
+ }
435
+ },
436
+ });
437
+ schedulers.set(adapter.id, scheduler);
438
+ ctx.effect(() => () => scheduler.dispose(), `dsh-model-sync: official scheduler dispose (${adapter.id})`);
439
+ void scheduler.start();
440
+ }
839
441
  ctx.effect(() => ctx.on('credentials/reference-updated', (ref) => {
840
442
  if (typeof ref !== 'string')
841
443
  return;
842
- const { value } = readGoRuntimeConfig(config);
843
- if (ref !== value.ref)
844
- return;
845
- goScheduler.resetBackoff();
846
- }), 'dsh-model-sync: credentials/reference-updated → go backoff reset');
847
- goScheduler.start();
848
- /** Resolve the official listing through an injectable seam (tests: a fixture array). */
849
- const resolveMigrateEntries = async (value, apiKey) => {
850
- const injected = ctx.get(GO_MIGRATION_ENTRIES_SERVICE);
851
- if (Array.isArray(injected))
852
- return injected;
853
- if (typeof injected === 'function')
854
- return await injected();
855
- const source = await fetchGoOfficialModels({
856
- url: value.modelsUrl,
857
- apiKey,
858
- fetchImpl: ctx.get(GO_FETCH_SERVICE),
859
- timeoutMs: config.refreshTimeoutMs.get(),
860
- });
861
- if (!source.ok) {
862
- throw new Error(`official opencode-go listing unavailable (${source.error?.kind ?? 'unknown'}); no plan generated`);
863
- }
864
- return source.entries;
865
- };
866
- /**
867
- * Public-catalog producer for id classification (§14.2): ids the current key
868
- * cannot serve but that are still official are `unknown-retired`, everything
869
- * else is `user-extra`. When the public list cannot be fetched the result is
870
- * `undefined`, which makes the plan mark such ids `unclassified` (never
871
- * deleted) instead of defaulting them to deletable `user-extra`.
872
- */
873
- const resolvePublicCatalogIds = async (value, entries) => {
874
- const injected = ctx.get(GO_MIGRATION_PUBLIC_CATALOG_SERVICE);
875
- if (Array.isArray(injected))
876
- return injected;
877
- if (typeof injected === 'function')
878
- return await injected();
879
- // Offline fixture mode: the injected authorized entries are the only catalog
880
- // available; deriving ids from them keeps `migrate plan` zero-fetch (V16).
881
- if (ctx.get(GO_MIGRATION_ENTRIES_SERVICE) !== undefined)
882
- return entries.map((entry) => entry.id);
883
- const result = await fetchGoPublicCatalogIds({
884
- url: value.modelsUrl,
885
- fetchImpl: ctx.get(GO_FETCH_SERVICE),
886
- timeoutMs: config.refreshTimeoutMs.get(),
887
- });
888
- return result.ok ? result.ids : undefined;
889
- };
890
- const migrateDeps = async (target, opts = {}, needsEntries = true) => {
891
- const { value } = readGoRuntimeConfig(config);
892
- const settings = settingsForWriteFrom(target);
893
- const desc = settings?.describe().find((d) => d.ns === 'llm-pi-ai');
894
- const apiKey = await resolveRouteCredentialValue(target, desc, 'opencode-go', value.ref);
895
- const refWriter = target.get(GO_MIGRATION_REF_WRITER_SERVICE);
896
- // Keep the pre-action-table evaluation order: the file-backed stores fail
897
- // closed without a profile identity, and must do so BEFORE any source
898
- // fetch (D4: no identity ⇒ zero outbound requests, zero writes).
899
- const ownershipStore = target.get(GO_OWNERSHIP_STORE_SERVICE)
900
- ?? ownershipStoreForRound();
901
- const store = migrationStore();
902
- // status/rollback never need the official listing: no fetch, no extra I/O.
903
- const entries = needsEntries ? await resolveMigrateEntries(value, apiKey) : [];
904
- const publicCatalogIds = needsEntries ? await resolvePublicCatalogIds(value, entries) : undefined;
905
- const adoptDisabled = ctx.get(GO_MIGRATION_ADOPT_DISABLED_SERVICE) === true
906
- || settings === undefined || typeof settings.mutate !== 'function';
907
- return {
908
- settings,
909
- ownershipStore,
910
- migrationStore: store,
911
- logger: target.logger,
912
- entries,
913
- publicCatalogIds,
914
- routes: value.routes,
915
- ref: value.ref,
916
- keyFingerprint: fingerprintKey(typeof apiKey === 'string' ? apiKey.trim() : ''),
917
- adopt: opts.adopt,
918
- adoptDisabled,
919
- rewriteRefs: opts.rewriteRefs,
920
- // Config path: go.pinnedModels (readGoRuntimeConfig:361) now reaches plan.
921
- pinnedModels: value.pinnedModels,
922
- pruneUserExtra: opts.pruneUserExtra,
923
- now: Date.now(),
924
- isSyncInFlight: ctx.get(GO_MIGRATION_MUTEX_SERVICE)
925
- ?? (() => goScheduler.isInFlight),
926
- applyReferenceRewrite: refWriter,
927
- // O1/C2: apply/rollback clear this profile's journals so a stale slot
928
- // cannot re-account settings that the migration just rewrote or undid.
929
- journalStore: journalStoreForRound(),
930
- profileKey,
931
- };
932
- };
933
- /** Shared by the slash command and the `modelSync` host service (§14.5). */
934
- const runMigrate = async (args, target) => {
935
- const usage = [
936
- 'usage: /model-sync migrate plan [--adopt] [--prune-user-extra] [--rewrite-refs=default-model|config]',
937
- ' /model-sync migrate apply --plan <planHash> --confirm <6-digit-code> --ack-managed',
938
- ' /model-sync migrate rollback --plan <planHash>',
939
- ' /model-sync migrate status',
940
- ].join('\n');
941
- const action = args[0] ?? 'plan';
942
- const rest = args.slice(1);
943
- if (!['plan', 'apply', 'rollback', 'status'].includes(action)) {
944
- return { kind: 'error', text: `migrate: unknown action '${action}'\n${usage}` };
945
- }
946
- // Consent has no bypass: these flags are recognised and rejected explicitly.
947
- if (rest.some((flag) => flag === '--yes' || flag === '--auto' || flag.startsWith('--yes=') || flag.startsWith('--auto='))) {
948
- return { kind: 'error', text: 'migrate: --yes/--auto are not supported; apply requires --plan <hash> and --confirm <code>' };
949
- }
950
- const flagValue = (name) => {
951
- const index = rest.indexOf(name);
952
- if (index >= 0)
953
- return rest[index + 1];
954
- const inline = rest.find((token) => token.startsWith(`${name}=`));
955
- return inline?.slice(name.length + 1);
956
- };
957
- const planHash = flagValue('--plan');
958
- const confirmCode = flagValue('--confirm');
959
- const adopt = rest.includes('--adopt');
960
- const ackManaged = rest.includes('--ack-managed');
961
- const pruneUserExtra = rest.includes('--prune-user-extra');
962
- const rewriteRefsRaw = rest.find((token) => token.startsWith('--rewrite-refs='))?.slice('--rewrite-refs='.length);
963
- const rewriteRefs = rewriteRefsRaw === 'default-model' || rewriteRefsRaw === 'config'
964
- ? rewriteRefsRaw
965
- : undefined;
966
- try {
967
- if (action === 'status') {
968
- const deps = await migrateDeps(target, {}, false);
969
- const report = await migrationStatusReport(deps, { caller: 'go', goEnabled: readGoRuntimeConfig(config).value.enabled });
970
- return { kind: 'success', text: report.text };
971
- }
972
- if (action === 'plan') {
973
- const deps = await migrateDeps(target, { adopt, rewriteRefs, pruneUserExtra });
974
- const record = await deps.migrationStore.read().catch(() => undefined);
975
- // Same pure builder apply uses — the printed table IS the consented one.
976
- // When adopt is disabled the mode is reported as adopt-disabled and the
977
- // rows stay conservative; no adopt action can be printed as executable.
978
- const plan = buildMigrationPlanFromDeps(deps, record);
979
- return { kind: 'success', text: formatMigrationPlan(plan) };
980
- }
981
- if (action === 'apply') {
982
- const deps = await migrateDeps(target, { adopt, rewriteRefs, pruneUserExtra });
983
- // Fail-closed fallback (§14.2): reject at the command layer before any
984
- // write when the per-id action table cannot be executed verbatim.
985
- if (adopt && deps.adoptDisabled === true) {
986
- return {
987
- kind: 'error',
988
- text: 'migrate apply refused (adopt-disabled): --adopt cannot execute the per-id action table verbatim; use conservative mode; zero writes',
989
- };
444
+ for (const adapter of listOfficialAdapters()) {
445
+ const scheduler = schedulers.get(adapter.id);
446
+ if (scheduler === undefined)
447
+ continue;
448
+ void migrationStoreFor(adapter.id)?.read().then((record) => {
449
+ if (adapter.defaultKeyRefs.includes(ref) || record?.apiKeyEnv === ref) {
450
+ void scheduler.resetPause();
990
451
  }
991
- const result = await applyMigration({ planHash, confirmCode, ackManaged }, deps);
992
- return { kind: result.ok ? 'success' : 'error', text: result.text };
993
- }
994
- // rollback
995
- const deps = await migrateDeps(target, {}, false);
996
- const result = await rollbackMigration({ planHash }, deps);
997
- return { kind: result.ok ? 'success' : 'error', text: result.text };
998
- }
999
- catch (error) {
1000
- const message = error instanceof Error ? error.message : String(error);
1001
- return { kind: 'error', text: `migrate ${action} failed: ${message}` };
452
+ }).catch(() => { });
1002
453
  }
1003
- };
454
+ }), 'dsh-model-sync: credentials/reference-updated → official pause reset');
1004
455
  // -----------------------------------------------------------------------
1005
- // One-shot migrate-go deps (design: one command = plan + backup + confirm
1006
- // + apply). Assembled from the same seams migrateDeps reads; the fs subset
1007
- // and the clock are the only new external surfaces, both plain adapters
1008
- // over node:fs/promises and Date here so tests inject their own.
456
+ // Legacy pi.dev auto-refresh timers
1009
457
  // -----------------------------------------------------------------------
1010
- const oneShotFs = {
1011
- readFile: (path) => readFile(path, 'utf8'),
1012
- writeFile: (path, data, mode) => (mode === undefined ? writeFile(path, data) : writeFile(path, data, { mode })),
1013
- rename: (from, to) => rename(from, to),
1014
- unlink: async (path) => { await unlink(path); },
1015
- mkdir: async (path, options) => { await mkdir(path, options); },
1016
- stat: async (path) => {
1017
- const info = await statFd(path).catch(() => undefined);
1018
- return info === undefined ? undefined : { mode: info.mode };
1019
- },
1020
- readdir: async (path) => readdir(path),
1021
- // Backup creation: claim the final name exclusively (O_EXCL `wx` — false
1022
- // when taken, so the caller retries the next sequence suffix), stamp the
1023
- // claim with a recognizable placeholder line, then replace the claimed
1024
- // file atomically via tmp + rename. A crash between claim and rename
1025
- // leaves a self-describing placeholder (review M7) instead of a silent
1026
- // 0-byte file that looks like a real backup; the tmp+rename guarantees the
1027
- // backup content itself is never torn. A failure of the tmp write or the
1028
- // rename releases the claim AND removes the tmp residue.
1029
- writeFileExclusive: async (path, data, mode) => {
1030
- let handle;
1031
- try {
1032
- handle = await open(path, 'wx', mode);
1033
- }
1034
- catch (err) {
1035
- if (err.code === 'EEXIST')
1036
- return false;
1037
- throw err;
1038
- }
1039
- try {
1040
- // The file was created with `mode` by open(wx); the placeholder write
1041
- // keeps that mode — no explicit mode needed here.
1042
- await handle.writeFile('dsh-model-sync: backup claim in progress — crash residue, NOT a backup (safe to delete)\n');
1043
- }
1044
- finally {
1045
- await handle.close().catch(() => { });
1046
- }
1047
- const tmp = `${path}.tmp-${process.pid}-${exclusiveWriteSeq++}`;
1048
- try {
1049
- await writeFile(tmp, data, mode === undefined ? undefined : { mode });
1050
- await rename(tmp, path);
1051
- return true;
1052
- }
1053
- catch (err) {
1054
- await unlink(tmp).catch(() => { }); // remove the tmp residue (review M7)
1055
- await unlink(path).catch(() => { }); // release the claim; nothing was replaced
1056
- throw err;
1057
- }
1058
- },
1059
- };
1060
- let exclusiveWriteSeq = 0;
1061
- /** Sync-read + atomic-write io for one patch file (describe() is sync). */
1062
- const patchIoFor = (path) => {
1063
- let writeSeq = 0;
1064
- return {
1065
- readText: () => readFileSync(path, 'utf8'),
1066
- writeAtomic: async (text) => {
1067
- writeSeq += 1;
1068
- const tmp = `${path}.tmp-${process.pid}-${writeSeq}`;
1069
- const mode = statSync(path).mode;
1070
- try {
1071
- writeFileSync(tmp, text, mode !== undefined ? { mode } : undefined);
1072
- await rename(tmp, path);
1073
- }
1074
- catch (err) {
1075
- await unlink(tmp).catch(() => { }); // no tmp residue on a failed write (review M7)
1076
- throw err;
1077
- }
1078
- },
1079
- };
1080
- };
1081
- const buildOneShotDeps = (target) => {
1082
- const { value } = readGoRuntimeConfig(config);
1083
- const settings = settingsForWriteFrom(target);
1084
- const desc = settings?.describe().find((item) => item.ns === 'llm-pi-ai');
1085
- const ref = value.ref;
1086
- const profile = target.get('profileContext');
1087
- const launchEnv = target.get('launchEnvironment');
1088
- const injectedMutex = target.get(GO_MIGRATION_MUTEX_SERVICE);
1089
- const injectedRefWriter = target.get(GO_MIGRATION_REF_WRITER_SERVICE);
1090
- const pathOverrides = target.get(GO_ONESHOT_PATHS_SERVICE);
1091
- return {
1092
- home: pathOverrides?.home ?? resolveDshHome(),
1093
- modelsStorePath: pathOverrides?.modelsStorePath ?? MODELS_STORE_PATH,
1094
- profilesDir: pathOverrides?.profilesDir,
1095
- fs: oneShotFs,
1096
- patchIoFor,
1097
- currentProfile: {
1098
- key: resolveProfileKey(target),
1099
- dir: profile?.dir ?? launchEnv?.get('DSH_PROFILE_DIR')?.value,
1100
- },
1101
- currentSettings: settings,
1102
- hostSettings: rawSettings(),
1103
- goConfig: {
1104
- routes: value.routes,
1105
- ref,
1106
- pinnedModels: value.pinnedModels,
1107
- adoptDisabled: target.get(GO_MIGRATION_ADOPT_DISABLED_SERVICE) === true
1108
- || settings === undefined || typeof settings.mutate !== 'function',
1109
- },
1110
- resolveCredential: async () => ({
1111
- value: await resolveRouteCredentialValue(target, desc, 'opencode-go', ref),
1112
- ref,
1113
- }),
1114
- resolveEntries: (apiKey) => resolveMigrateEntries(value, apiKey),
1115
- resolvePublicCatalogIds: (_apiKey, entries) => resolvePublicCatalogIds(value, entries),
1116
- resolveAsk: () => {
1117
- try {
1118
- return target.get('userQuestions');
1119
- }
1120
- catch {
1121
- return undefined;
1122
- }
1123
- },
1124
- // File-backed stores scoped per profile in the SAME models-store.json
1125
- // the backup step snapshots. The GO_MIGRATION_STORE_SERVICE /
1126
- // GO_OWNERSHIP_STORE_SERVICE seams are deliberately NOT consulted
1127
- // here: the one-shot needs per-profile scoping, which the injected
1128
- // single-store seams cannot express — the path override below is the
1129
- // test seam instead (tests point it at a temp dir).
1130
- storesFor: (profileKey) => ({
1131
- ownership: createModelsStoreOwnershipStore(pathOverrides?.modelsStorePath, profileKey),
1132
- migration: createModelsStoreMigrationStateStore(pathOverrides?.modelsStorePath, profileKey),
1133
- }),
1134
- journalStore: profileKey === undefined ? undefined : createModelsStoreJournalStore(pathOverrides?.modelsStorePath),
1135
- isSyncInFlight: injectedMutex ?? (() => goScheduler.isInFlight),
1136
- applyReferenceRewrite: injectedRefWriter,
1137
- ...(pathOverrides?.testOnlyOwnershipWriteFaultPrefix !== undefined
1138
- ? { faultOwnershipWriteOnKeyPrefix: pathOverrides.testOnlyOwnershipWriteFaultPrefix }
1139
- : {}),
1140
- logger: target.logger,
1141
- now: Date.now,
1142
- };
1143
- };
1144
- /** Auto rounds log the same report the /model-sync command shows. */
1145
458
  const runAuto = () => {
1146
- // A rejected round (service lookups mid-dispose, a refused mutate) must
1147
- // settle here: an unhandled rejection from a timer-driven round would
1148
- // terminate the whole host process, and the auto path has no caller to
1149
- // hand the error to.
1150
459
  void syncNow(false).then((report) => {
1151
460
  for (const line of report.split('\n'))
1152
461
  ctx.logger.info('model-sync: %s', line);
@@ -1154,7 +463,8 @@ export async function apply(ctx, config) {
1154
463
  ctx.logger.warn('model-sync: auto refresh failed: %o', error);
1155
464
  });
1156
465
  };
1157
- /** (Re)arm the auto-refresh interval; 0 disarms. */
466
+ let stopInterval;
467
+ let startupTimer;
1158
468
  const armInterval = (minutes) => {
1159
469
  if (stopInterval !== undefined)
1160
470
  clearInterval(stopInterval);
@@ -1162,64 +472,59 @@ export async function apply(ctx, config) {
1162
472
  if (minutes > 0)
1163
473
  stopInterval = setInterval(runAuto, minutes * 60_000);
1164
474
  };
1165
- let stopInterval;
1166
- let startupTimer;
1167
- // One effect releases whatever timers are live at dispose.
1168
475
  ctx.effect(() => () => {
1169
476
  if (stopInterval !== undefined)
1170
477
  clearInterval(stopInterval);
1171
478
  if (startupTimer !== undefined)
1172
479
  clearTimeout(startupTimer);
1173
480
  });
1174
- // Volatile fields are stable references, so the initial arms read them once
1175
- // and the interval keeps working; the hot-reload notification arrives as a
1176
- // settings/document-updated event (the 0.1.7 replacement for scope.watch).
1177
481
  startupTimer = setTimeout(runAuto, Math.max(0, config.startupDelaySeconds.get() ?? 5) * 1000);
1178
482
  armInterval(config.intervalMinutes.get() ?? 240);
1179
483
  ctx.effect(() => ctx.on('settings/document-updated', (ns, revision) => {
1180
- // P1d-1 §14.7.2: if this event is the echo of a settings.mutate we just
1181
- // performed, only refresh status — schedule NO round (the V23 race was a
1182
- // go write echo triggering the legacy pi.dev auto round ~1s later).
1183
- if (ownWrite.matches(ns, typeof revision === 'number' ? revision : undefined)) {
1184
- ctx.logger.info('model-sync: reentry-ignored (ns=%s revision=%s); no round scheduled', ns, revision);
1185
- void loadMigrationStatus(); // refresh state only; no timer, no runAuto
484
+ if (ownWrite.matches(ns, typeof revision === 'number' ? revision : undefined))
1186
485
  return;
1187
- }
1188
- // Only this plugin's own config entry (the bundle-patch id) re-arms timers;
1189
- // the handler is idempotent — the refs already carry the new values, so the
1190
- // next round reads them fresh. A foreign ns (including llm-pi-ai writes by
1191
- // other actors) never schedules a round here.
1192
486
  if (ns !== OWN_ENTRY_ID)
1193
487
  return;
1194
488
  armInterval(config.intervalMinutes.get() ?? 0);
1195
- // §14.7.2 item 2: remove the old "immediate +1s runAuto". Config edits now
1196
- // only re-arm the normal interval; an immediate round needs an explicit
1197
- // /model-sync. (P1c-2 go scheduler still re-arms idempotently.)
1198
- goScheduler.rearm();
1199
- void loadMigrationStatus();
489
+ for (const scheduler of schedulers.values()) {
490
+ void scheduler.rearm();
491
+ }
1200
492
  }), 'dsh-model-sync: settings/document-updated');
1201
- // The modelSync service stays exposed for UIs that want direct access. The
1202
- // /model-sync command itself is registered by this plugin (below) through
1203
- // the shared command registry, which interactive UIs discover on their own.
493
+ // -----------------------------------------------------------------------
494
+ // Public service & slash command registration
495
+ // -----------------------------------------------------------------------
1204
496
  ctx.provide('modelSync', {
1205
497
  syncNow: () => syncNow(true),
1206
- migratePlan: (options) => runMigrate(['plan', ...(options?.adopt === true ? ['--adopt'] : []),
1207
- ...(options?.pruneUserExtra === true ? ['--prune-user-extra'] : []),
1208
- ...(options?.rewriteRefs !== undefined ? [`--rewrite-refs=${options.rewriteRefs}`] : [])], ctx).then((result) => result.text),
1209
- migrateApply: (args) => runMigrate(['apply', ...(args.planHash !== undefined ? ['--plan', args.planHash] : []),
1210
- ...(args.confirmCode !== undefined ? ['--confirm', args.confirmCode] : []),
1211
- ...(args.ackManaged === true ? ['--ack-managed'] : [])], ctx).then((result) => result.text),
1212
- migrateRollback: (args) => runMigrate(['rollback', ...(args.planHash !== undefined ? ['--plan', args.planHash] : [])], ctx).then((result) => result.text),
1213
- migrateStatus: () => runMigrate(['status'], ctx).then((result) => result.text),
498
+ syncOfficial: async (provider) => {
499
+ const adapter = resolveOfficialAdapter(provider);
500
+ if (adapter === undefined)
501
+ return formatUnsupportedProviderError(provider);
502
+ const scheduler = schedulers.get(adapter.id);
503
+ const res = await scheduler.triggerManual();
504
+ return res.text;
505
+ },
506
+ migrate: async (provider, opts) => {
507
+ const adapter = resolveOfficialAdapter(provider);
508
+ if (adapter === undefined)
509
+ return formatUnsupportedProviderError(provider);
510
+ const res = await runOfficialMigrate(buildMigrateDeps(ctx, adapter), opts);
511
+ return res.text;
512
+ },
513
+ rollback: async (provider, opts) => {
514
+ const adapter = resolveOfficialAdapter(provider);
515
+ if (adapter === undefined)
516
+ return formatUnsupportedProviderError(provider);
517
+ const res = await runOfficialRollback(buildMigrateDeps(ctx, adapter), opts);
518
+ return res.text;
519
+ },
520
+ status: async (provider = 'opencode-go') => {
521
+ const adapter = resolveOfficialAdapter(provider);
522
+ if (adapter === undefined)
523
+ return formatUnsupportedProviderError(provider);
524
+ const res = await runOfficialStatus(buildMigrateDeps(ctx, adapter));
525
+ return res.text;
526
+ },
1214
527
  });
1215
- // Register the /model-sync slash command from the plugin itself. The
1216
- // registry is @deepseek-ai/dsh-commands' CommandRuntime ("Plugin-owned
1217
- // human-command registry shared by interactive UI adapters") — registration
1218
- // is global, so every interactive UI lists the command without any UI-side
1219
- // wiring. The registry is an optional peer: the `ctx.inject` sub-fiber stays
1220
- // dormant until the host provides the `commands` service, so hosts without
1221
- // the registry keep every other feature working. A bare `ctx.commands` read
1222
- // without a declared inject throws in cordis 4.
1223
528
  ctx.inject(['commands'], (cmdCtx) => {
1224
529
  const commands = cmdCtx.commands;
1225
530
  if (commands?.register === undefined)
@@ -1227,163 +532,138 @@ export async function apply(ctx, config) {
1227
532
  cmdCtx.effect(() => {
1228
533
  const definition = {
1229
534
  name: 'model-sync',
1230
- description: 'Force one model-list sync round from the pi.dev gateway into settings; go subcommands: go|status (one full opencode-go round), adopt go; migrate plan|apply|rollback|status (explicit consent only); migrate-go (one-shot full migration with file backups + one confirmation)',
1231
- // GUI clients (@deepseek-ai/dsh-client-ui-commands) only claim the
1232
- // text after `/model-sync ` as command arguments when the definition
1233
- // declares `input`; without it matchEnter treats the whole line as a
1234
- // chat message and the `/` menu can only run the bare command. The
1235
- // host's parseCommand already hands the raw tail to the handler below
1236
- // as rawInput, so declaring the hint is all the plugin side needs.
1237
- // Attachments stay refused (no `attachments: true`) — the handler
1238
- // has no attachment semantics.
535
+ description: 'Sync pi.dev Builtin Providers (bare), or sync/migrate/rollback/status official custom providers (e.g. /model-sync go, /model-sync migrate go, /model-sync rollback go)',
1239
536
  input: {
1240
- hint: 'migrate plan|apply|rollback|status · migrate-go · go|status',
537
+ hint: 'go | migrate <provider> [--all-profiles] [--confirm] | rollback <provider> | status [provider]',
1241
538
  },
1242
539
  handler: async (invocation) => {
1243
- const args = invocation.rawInput.trim().split(/\s+/).filter((part) => part.length > 0);
1244
- const [sub, scope] = args;
1245
- // P1d-2: migration is the ONLY explicit-consent config writer. It is
1246
- // never auto-triggered and never folded into the pi.dev sync path.
1247
- if (sub === 'migrate') {
1248
- return runMigrate(args.slice(1), cmdCtx);
540
+ const tokens = invocation.rawInput.trim().split(/\s+/).filter((t) => t.length > 0);
541
+ if (tokens.length === 0) {
542
+ try {
543
+ const report = await syncNow(true);
544
+ return { kind: 'success', text: report };
545
+ }
546
+ catch (error) {
547
+ const message = error instanceof Error ? error.message : String(error);
548
+ return { kind: 'error', text: `model-sync failed: ${message}` };
549
+ }
1249
550
  }
1250
- // One-shot migrate-go: the full plan → backup → confirm → apply
1251
- // pipeline for the current profile (or --all-profiles). Its consent
1252
- // is the interactive confirmation; apply still passes through the
1253
- // unchanged verifyConsent gate with the computed hash/code.
1254
- if (sub === 'migrate-go') {
1255
- const parsed = parseMigrateGoFlags(args.slice(1));
1256
- if (!parsed.ok) {
1257
- return { kind: 'error', text: parsed.error };
551
+ const [sub, ...rest] = tokens;
552
+ const lowerSub = sub.toLowerCase();
553
+ const flags = new Set(rest.filter((t) => t.startsWith('--')));
554
+ const positional = rest.filter((t) => !t.startsWith('--'));
555
+ if (lowerSub === 'migrate-go' || lowerSub === 'migrate') {
556
+ const targetName = lowerSub === 'migrate-go' ? 'opencode-go' : positional[0];
557
+ if (targetName === undefined) {
558
+ return {
559
+ kind: 'error',
560
+ text: 'usage: /model-sync migrate <provider> [--all-profiles] [--confirm] (e.g. /model-sync migrate go)',
561
+ };
562
+ }
563
+ const adapter = resolveOfficialAdapter(targetName);
564
+ if (adapter === undefined) {
565
+ return { kind: 'error', text: formatUnsupportedProviderError(targetName) };
1258
566
  }
1259
- const flags = parsed.flags;
1260
567
  try {
1261
- return await runMigrateGoOneShot(buildOneShotDeps(cmdCtx), flags, { agent: invocation.agent, signal: invocation.signal });
568
+ return await runOfficialMigrate(buildMigrateDeps(cmdCtx, adapter), {
569
+ allProfiles: flags.has('--all-profiles'),
570
+ confirm: flags.has('--confirm'),
571
+ agent: invocation.agent,
572
+ signal: invocation.signal,
573
+ });
1262
574
  }
1263
575
  catch (error) {
1264
576
  const message = error instanceof Error ? error.message : String(error);
1265
- return { kind: 'error', text: `migrate-go failed: ${message}` };
577
+ return { kind: 'error', text: `migrate ${targetName} failed: ${message}` };
1266
578
  }
1267
579
  }
1268
- // B3 (31 R-4): `eject` is retired — `migrate rollback` is the only
1269
- // rollback entry. Reject the old invocation explicitly so it never
1270
- // falls through to a bare sync (which would write to go routes under
1271
- // a command name the user believed was read-only).
1272
- if (sub === 'eject') {
1273
- return { kind: 'error', text: 'model-sync eject go: retired; use /model-sync migrate rollback --plan <hash>' };
1274
- }
1275
- // Design §7.1 keeps bare `/model-sync` (pi.dev settings sync) exactly
1276
- // as it was. The go subcommands are additive: `go`/`status` run one
1277
- // full go round, `adopt go` runs it with adoption. Status stays the
1278
- // read-only `/opencode-status` command — it is never a write trigger.
1279
- if ((sub === 'go' || sub === 'status' || sub === 'adopt')
1280
- && (scope === undefined || scope === 'go')) {
1281
- try {
1282
- // Route manual rounds through the scheduler so they share the
1283
- // single-flight lock with timer-driven rounds. A second trigger
1284
- // while a round is in flight is skipped and reported (design
1285
- // §14.6), never queued. The report text is the round's own text,
1286
- // unchanged, for real rounds.
1287
- const outcome = await goScheduler.triggerManual({ adopt: sub === 'adopt' });
1288
- // N1: a round that threw (e.g. the file-backed ledger refusing to
1289
- // build without a profile identity) is reported as a scheduler
1290
- // error. It is a real failure — the command must return
1291
- // `kind:'error'` so callers that only read `kind` can detect it;
1292
- // the actionable reason is carried in `text`. Skips (disabled,
1293
- // already-in-flight, migration-applying, disposed) stay success,
1294
- // byte-identical to before.
1295
- const failed = outcome.reason === 'source-failed'
1296
- // oldfox #3: a writer exception is a real failure at the
1297
- // command surface, but a distinct reason from source failure.
1298
- || outcome.reason === 'writer-error'
1299
- || outcome.reason === 'scheduler-error'
1300
- // B4: an abandoned round must be visible as a failure at the
1301
- // command surface too (it is not a successful sync). The reason
1302
- // text carries the actionable "settings changed, next round
1303
- // retries" guidance; no backoff is scheduled for it.
1304
- || outcome.reason === 'settings-changed-during-sync'
1305
- // O1-minimal: failedRoutes (e.g. settings written but the ledger
1306
- // failed) are a real failure even if other routes wrote. Callers
1307
- // that only read `kind` must see `error`; the actionable reason
1308
- // and the new report code are carried in `text`.
1309
- || outcome.reason === 'write-failed';
580
+ if (lowerSub === 'rollback') {
581
+ const targetName = positional[0];
582
+ if (targetName === undefined) {
1310
583
  return {
1311
- kind: failed ? 'error' : 'success',
1312
- text: outcome.text,
584
+ kind: 'error',
585
+ text: 'usage: /model-sync rollback <provider> [--confirm] (e.g. /model-sync rollback go)',
1313
586
  };
1314
587
  }
588
+ const adapter = resolveOfficialAdapter(targetName);
589
+ if (adapter === undefined) {
590
+ return { kind: 'error', text: formatUnsupportedProviderError(targetName) };
591
+ }
592
+ try {
593
+ return await runOfficialRollback(buildMigrateDeps(cmdCtx, adapter), {
594
+ confirm: flags.has('--confirm'),
595
+ agent: invocation.agent,
596
+ signal: invocation.signal,
597
+ });
598
+ }
599
+ catch (error) {
600
+ const message = error instanceof Error ? error.message : String(error);
601
+ return { kind: 'error', text: `rollback ${targetName} failed: ${message}` };
602
+ }
603
+ }
604
+ if (lowerSub === 'status') {
605
+ const targetName = positional[0] ?? 'opencode-go';
606
+ const adapter = resolveOfficialAdapter(targetName);
607
+ if (adapter === undefined) {
608
+ return { kind: 'error', text: formatUnsupportedProviderError(targetName) };
609
+ }
610
+ try {
611
+ return await runOfficialStatus(buildMigrateDeps(cmdCtx, adapter));
612
+ }
1315
613
  catch (error) {
1316
614
  const message = error instanceof Error ? error.message : String(error);
1317
- return { kind: 'error', text: `model-sync ${sub} failed: ${message}` };
615
+ return { kind: 'error', text: `status ${targetName} failed: ${message}` };
1318
616
  }
1319
617
  }
1320
- const ignored = invocation.rawInput.trim().length > 0
1321
- ? 'The sync scope is decided by the model-sync managedRoutes config; the argument is ignored.\n'
1322
- : '';
618
+ const adapter = resolveOfficialAdapter(sub);
619
+ if (adapter === undefined) {
620
+ return { kind: 'error', text: formatUnsupportedProviderError(sub) };
621
+ }
1323
622
  try {
1324
- const report = await syncNow(true);
1325
- return { kind: 'success', text: `${ignored}${report}` };
623
+ const scheduler = schedulers.get(adapter.id);
624
+ const res = await scheduler.triggerManual();
625
+ return {
626
+ kind: res.ok ? 'success' : 'error',
627
+ text: res.text,
628
+ };
1326
629
  }
1327
630
  catch (error) {
1328
631
  const message = error instanceof Error ? error.message : String(error);
1329
- return { kind: 'error', text: `${ignored}model-sync failed: ${message}` };
632
+ return { kind: 'error', text: `model-sync ${sub} failed: ${message}` };
1330
633
  }
1331
634
  },
1332
635
  };
1333
636
  return commands.register(definition);
1334
637
  }, 'dsh-model-sync: /model-sync');
1335
- // P0 read-only diagnostic. Parallel to /model-sync (whose behavior is
1336
- // unchanged): fetch the official go listing, compare it with the current
1337
- // profile's opencode-go routes, and print a structured report. This path
1338
- // never calls settings.mutate, never writes credentials, and never edits
1339
- // a profile file — it only reads describe()/credentials.resolve().
1340
638
  cmdCtx.effect(() => {
1341
639
  const definition = {
1342
640
  name: 'opencode-status',
1343
- description: 'Read-only diagnostic: compare opencode-go official /v1/models with the current profile routes (no writes)',
641
+ description: 'Read-only diagnostic for OpenCode Go Official Sync status (alias for /model-sync status go)',
1344
642
  handler: async (invocation) => {
1345
643
  const token = invocation.rawInput.trim();
1346
- const ignored = token !== '' && token !== 'go'
1347
- ? 'opencode-status: P0 diagnoses opencode-go only; the argument is ignored.\n'
1348
- : '';
644
+ const targetName = token === '' ? 'opencode-go' : token;
645
+ const adapter = resolveOfficialAdapter(targetName);
646
+ if (adapter === undefined) {
647
+ return { kind: 'error', text: formatUnsupportedProviderError(targetName) };
648
+ }
1349
649
  try {
1350
- const desc = cmdCtx.get('settings')?.describe()
1351
- .find((d) => d.ns === 'llm-pi-ai');
1352
- const apiKey = await resolveRouteCredentialValue(cmdCtx, desc, 'opencode-go');
1353
- const report = await runGoDiagnostic({ apiKey, descriptor: desc });
1354
- return { kind: 'success', text: `${ignored}${formatGoDiagnosticReport(report)}` };
650
+ return await runOfficialStatus(buildMigrateDeps(cmdCtx, adapter));
1355
651
  }
1356
652
  catch (error) {
1357
653
  const message = error instanceof Error ? error.message : String(error);
1358
- return { kind: 'error', text: `${ignored}opencode-status failed: ${message}` };
654
+ return { kind: 'error', text: `opencode-status failed: ${message}` };
1359
655
  }
1360
656
  },
1361
657
  };
1362
658
  return commands.register(definition);
1363
659
  }, 'dsh-model-sync: /opencode-status');
1364
660
  });
1365
- // One-time legacy settings import (0.1.5 → 0.1.7 upgrade path, see
1366
- // legacy-import.ts): recover the old `model-sync:` section for hosts where
1367
- // the 0.1.7 one-shot settings.yaml import never carried it over. Wired
1368
- // through ctx.inject(['settings'], …) instead of a direct `ctx.settings`
1369
- // read: a real boot can run apply() before the settings service mounts,
1370
- // and the direct read then silently no-settings'd the import away every
1371
- // boot. The inject callback fires the moment the service exists
1372
- // (immediately when it already does — fake-ctx tests stay synchronous),
1373
- // fire-and-forget so activation never waits on it. Fully contained: any
1374
- // failure only warns and leaves the audit marker unwritten, so the next
1375
- // boot retries; activation never depends on this. The volatile refs read
1376
- // fresh, and the update itself fires settings/document-updated for this
1377
- // entry — the timers armed above with the pre-import value re-arm to it
1378
- // without a restart.
661
+ // One-time legacy settings.yaml import
1379
662
  ctx.inject(['settings'], (sctx) => {
1380
663
  void runLegacySettingsImport({
1381
664
  home: resolveDshHome(),
1382
665
  settings: sctx.settings,
1383
666
  logger: ctx.logger,
1384
- // The volatile refs read fresh, and the update itself fires
1385
- // settings/document-updated for this entry — the timers armed above
1386
- // with the pre-import value re-arm to it without a restart.
1387
667
  getCurrent: (key) => {
1388
668
  const slot = config[key];
1389
669
  return typeof slot?.get === 'function' ? slot.get() : slot;
@@ -1394,32 +674,11 @@ export async function apply(ctx, config) {
1394
674
  });
1395
675
  }
1396
676
  // ---------------------------------------------------------------------------
1397
- // Builtin catalog helpers (uses shared snapshot)
677
+ // Builtin catalog helpers (pi.dev track)
1398
678
  // ---------------------------------------------------------------------------
1399
- /**
1400
- * Get builtin catalog data for a route: the host's live pi-ai catalog when it
1401
- * can be located, the frozen build-time snapshot otherwise. Live-first is the
1402
- * point — the snapshot rots when the host's bundled pi-ai drops models
1403
- * (grok-4.5 was removed in pi-ai 0.84.4), and a stale keepBuiltinOnly entry
1404
- * gets the whole llm-pi-ai namespace rejected by the alpha line's strict
1405
- * registration.
1406
- */
1407
679
  function getBuiltinCatalogForRoute(route) {
1408
680
  return getLiveBuiltinCatalogForRoute(route) ?? BUILTIN_CATALOG_SNAPSHOT[route] ?? [];
1409
681
  }
1410
- /**
1411
- * Get entries from builtin catalog that are not in pi.dev (for keepBuiltinOnly).
1412
- * Returns minimal RemoteCatalogEntry-shaped objects — translateEntries only
1413
- * reads entry.id from these, emitting {id} profiles (I-3).
1414
- *
1415
- * Deprecated snapshot entries (the official default model list dropped them —
1416
- * dsh 0.1.7 removed deepseek-v4-flash / deepseek-v4-flash-vision-exp) are
1417
- * excluded unless `includeDeprecated` opts them back in: a re-emitted retired
1418
- * id is a model the 0.1.7 host no longer resolves. The data itself stays in
1419
- * the snapshot for historical user configurations.
1420
- *
1421
- * Exported for the test suite; not part of the public runtime surface.
1422
- */
1423
682
  export function getBuiltinOnlyEntries(route, piDevEntries, builtinData, includeDeprecated = false) {
1424
683
  const piDevIds = new Set(piDevEntries.map((e) => e.id));
1425
684
  return builtinData
@@ -1435,9 +694,6 @@ export function getBuiltinOnlyEntries(route, piDevEntries, builtinData, includeD
1435
694
  input: ['text'],
1436
695
  }));
1437
696
  }
1438
- /**
1439
- * Extract raw user-segment models for a route from a settings descriptor (I-6).
1440
- */
1441
697
  function getRawUserModelsFromDesc(desc, route) {
1442
698
  if (desc === undefined)
1443
699
  return undefined;