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