@aiwayds/dsh-model-sync 0.12.1 → 0.13.1

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 (88) hide show
  1. package/README.md +18 -17
  2. package/README.zh-CN.md +18 -17
  3. package/lib/index.d.ts +54 -384
  4. package/lib/index.js +306 -1107
  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 +122 -0
  10. package/lib/official-migrate.js +653 -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 +352 -1281
  33. package/src/official-adapter.ts +111 -0
  34. package/src/official-migrate.ts +863 -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 -96
  42. package/lib/opencode-go-diagnose.js +0 -177
  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-host-catalog.d.ts +0 -42
  48. package/lib/opencode-go-host-catalog.js +0 -98
  49. package/lib/opencode-go-host-catalog.js.map +0 -1
  50. package/lib/opencode-go-journal.d.ts +0 -114
  51. package/lib/opencode-go-journal.js +0 -406
  52. package/lib/opencode-go-journal.js.map +0 -1
  53. package/lib/opencode-go-migrate.d.ts +0 -378
  54. package/lib/opencode-go-migrate.js +0 -1529
  55. package/lib/opencode-go-migrate.js.map +0 -1
  56. package/lib/opencode-go-migration.d.ts +0 -270
  57. package/lib/opencode-go-migration.js +0 -473
  58. package/lib/opencode-go-migration.js.map +0 -1
  59. package/lib/opencode-go-one-shot.d.ts +0 -282
  60. package/lib/opencode-go-one-shot.js +0 -1131
  61. package/lib/opencode-go-one-shot.js.map +0 -1
  62. package/lib/opencode-go-planner.d.ts +0 -168
  63. package/lib/opencode-go-planner.js +0 -407
  64. package/lib/opencode-go-planner.js.map +0 -1
  65. package/lib/opencode-go-scheduler.d.ts +0 -128
  66. package/lib/opencode-go-scheduler.js +0 -241
  67. package/lib/opencode-go-scheduler.js.map +0 -1
  68. package/lib/opencode-go-store.d.ts +0 -18
  69. package/lib/opencode-go-store.js +0 -68
  70. package/lib/opencode-go-store.js.map +0 -1
  71. package/lib/opencode-go-sync.d.ts +0 -107
  72. package/lib/opencode-go-sync.js +0 -388
  73. package/lib/opencode-go-sync.js.map +0 -1
  74. package/lib/opencode-go-writer.d.ts +0 -148
  75. package/lib/opencode-go-writer.js +0 -1061
  76. package/lib/opencode-go-writer.js.map +0 -1
  77. package/src/opencode-go-diagnose.ts +0 -276
  78. package/src/opencode-go-grouping.ts +0 -26
  79. package/src/opencode-go-host-catalog.ts +0 -125
  80. package/src/opencode-go-journal.ts +0 -460
  81. package/src/opencode-go-migrate.ts +0 -1951
  82. package/src/opencode-go-migration.ts +0 -666
  83. package/src/opencode-go-one-shot.ts +0 -1399
  84. package/src/opencode-go-planner.ts +0 -582
  85. package/src/opencode-go-scheduler.ts +0 -315
  86. package/src/opencode-go-store.ts +0 -73
  87. package/src/opencode-go-sync.ts +0 -541
  88. package/src/opencode-go-writer.ts +0 -1301
@@ -0,0 +1,863 @@
1
+ /**
2
+ * Official Sync migration, rollback, and read-only status diagnostic.
3
+ *
4
+ * Design:
5
+ * - Strict precondition: target profile MUST already declare the legacy
6
+ * `providers.<builtinProviderId>` section (e.g. `providers.opencode-go`).
7
+ * Blank profiles cannot initialize via `migrate`.
8
+ * - Single confirmation gate via `userQuestions` (or `--confirm` when
9
+ * non-interactive; fail-closed otherwise).
10
+ * - File backups (`cordis.patch.yml.bak.<stamp>` and
11
+ * `models-store.json.bak.<stamp>`, keeping 3 newest per category) are
12
+ * created before confirmation/writes, with byte-restore on mid-apply failure.
13
+ * - Rewrites `agent-default-model` when it points at the deleted builtin
14
+ * provider, and reports advisory warnings for any other references in
15
+ * `cordis.patch.yml`.
16
+ * - Rollback restores the previous builtin provider, restores
17
+ * `agent-default-model`, removes the Managed Custom Providers, and deletes
18
+ * the profile's OfficialMigrationRecord.
19
+ *
20
+ * @module dsh-model-sync/official-migrate
21
+ */
22
+
23
+ import { mkdir, open, readFile, readdir, rename, stat as statFd, unlink, writeFile } from 'node:fs/promises'
24
+ import { readFileSync, statSync, writeFileSync } from 'node:fs'
25
+ import { basename, dirname, join } from 'node:path'
26
+ import type { GoFetchLike } from './opencode-go-source.ts'
27
+ import { resolveDshHome } from './legacy-import.ts'
28
+ import { MODELS_STORE_PATH, loadModelsStore, type ModelsStoreAccessor } from './remote-catalog.ts'
29
+ import {
30
+ createFilePatchSettingsService,
31
+ scanPatchReferences,
32
+ type PatchFileIo,
33
+ type PatchReferenceHit,
34
+ } from './opencode-go-patch-file.ts'
35
+ import type { Logger, SettingsMutationOp, SettingsService } from './writer.ts'
36
+ import type {
37
+ CompatHintsByProtocol,
38
+ CustomProviderSpec,
39
+ OfficialAdapterConfig,
40
+ UpstreamProviderAdapter,
41
+ } from './official-adapter.ts'
42
+ import {
43
+ cleanupLegacyGoStoreKeys,
44
+ createOfficialMigrationStore,
45
+ type OfficialMigrationRecord,
46
+ type OfficialMigrationStore,
47
+ } from './official-store.ts'
48
+ import {
49
+ buildCustomProviderValue,
50
+ resolveCredentialByRefs,
51
+ type OfficialCredentialContext,
52
+ } from './official-sync.ts'
53
+
54
+ export interface AskQuestionOption {
55
+ label: string
56
+ description?: string
57
+ }
58
+
59
+ export interface AskQuestionItem {
60
+ id: string
61
+ question: string
62
+ detail?: string
63
+ header?: string
64
+ options?: AskQuestionOption[]
65
+ multiSelect?: boolean
66
+ }
67
+
68
+ export interface AskAnswerItem {
69
+ id: string
70
+ selected?: string[]
71
+ custom?: string
72
+ }
73
+
74
+ export interface AskServiceShape {
75
+ ask(request: {
76
+ questions: AskQuestionItem[]
77
+ agent?: unknown
78
+ signal?: AbortSignal
79
+ }): Promise<{
80
+ answers?: AskAnswerItem[]
81
+ }>
82
+ }
83
+
84
+ export interface MigrateFs {
85
+ readFile(path: string): Promise<string>
86
+ writeFile(path: string, data: string, mode?: number): Promise<void>
87
+ rename(from: string, to: string): Promise<void>
88
+ unlink(path: string): Promise<void>
89
+ mkdir(path: string, options: { recursive: boolean }): Promise<void>
90
+ stat(path: string): Promise<{ mode: number } | undefined>
91
+ readdir(path: string): Promise<string[]>
92
+ writeFileExclusive(path: string, data: string, mode?: number): Promise<boolean>
93
+ }
94
+
95
+ export interface MigrateTargetProfile {
96
+ profileKey: string
97
+ profileDir?: string
98
+ isCurrent: boolean
99
+ settings: SettingsService | undefined
100
+ patchText?: string
101
+ patchPath?: string
102
+ }
103
+
104
+ export interface OfficialMigrateDeps {
105
+ adapter: UpstreamProviderAdapter
106
+ config: OfficialAdapterConfig
107
+ home: string
108
+ modelsStorePath: string
109
+ profilesDir?: string
110
+ currentProfile: {
111
+ key: string | undefined
112
+ dir: string | undefined
113
+ }
114
+ currentSettings: SettingsService | undefined
115
+ credentialCtx: OfficialCredentialContext
116
+ logger: Logger
117
+ timeoutMs?: number
118
+ fetchImpl?: GoFetchLike
119
+ detectHostSessionHeader?: () => boolean
120
+ loadPiAiCompatHints?: () => CompatHintsByProtocol
121
+ resolveAsk?: () => AskServiceShape | undefined
122
+ /** Test seam: override migration store creation. */
123
+ storeFor?: (profileKey: string) => OfficialMigrationStore
124
+ /** Test seam: override legacy store cleanup. */
125
+ storeAccessor?: ModelsStoreAccessor
126
+ fs?: MigrateFs
127
+ patchIoFor?: (path: string) => PatchFileIo
128
+ now?: () => number
129
+ onCurrentProfileMigrated?: () => Promise<void> | void
130
+ onCurrentProfileRolledBack?: () => Promise<void> | void
131
+ }
132
+
133
+ export interface MigrateCommandResult {
134
+ kind: 'success' | 'error'
135
+ text: string
136
+ }
137
+
138
+ const BACKUP_KEEP_COUNT = 3
139
+ const LABEL_MIGRATE = '执行迁移'
140
+ const LABEL_ROLLBACK = '确认回退'
141
+ const LABEL_CANCEL = '取消'
142
+
143
+ function formatStamp(ms: number): string {
144
+ const d = new Date(ms)
145
+ const p = (n: number, w = 2) => String(n).padStart(w, '0')
146
+ return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}-${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}`
147
+ }
148
+
149
+ let exclusiveSeq = 0
150
+ export function createDefaultMigrateFs(): MigrateFs {
151
+ return {
152
+ readFile: (path) => readFile(path, 'utf8'),
153
+ writeFile: (path, data, mode) => (mode === undefined ? writeFile(path, data) : writeFile(path, data, { mode })),
154
+ rename: (from, to) => rename(from, to),
155
+ unlink: async (path) => { await unlink(path) },
156
+ mkdir: async (path, options) => { await mkdir(path, options) },
157
+ stat: async (path) => {
158
+ const info = await statFd(path).catch(() => undefined)
159
+ return info === undefined ? undefined : { mode: info.mode }
160
+ },
161
+ readdir: async (path) => readdir(path),
162
+ writeFileExclusive: async (path, data, mode) => {
163
+ let handle
164
+ try {
165
+ handle = await open(path, 'wx', mode)
166
+ } catch (err) {
167
+ if ((err as NodeJS.ErrnoException).code === 'EEXIST') return false
168
+ throw err
169
+ }
170
+ try {
171
+ await handle.writeFile('dsh-model-sync: backup claim in progress\n')
172
+ } finally {
173
+ await handle.close().catch(() => {})
174
+ }
175
+ const tmp = `${path}.tmp-${process.pid}-${exclusiveSeq++}`
176
+ try {
177
+ await writeFile(tmp, data, mode === undefined ? undefined : { mode })
178
+ await rename(tmp, path)
179
+ return true
180
+ } catch (err) {
181
+ await unlink(tmp).catch(() => {})
182
+ await unlink(path).catch(() => {})
183
+ throw err
184
+ }
185
+ },
186
+ }
187
+ }
188
+
189
+ export function createDefaultPatchIo(path: string): PatchFileIo {
190
+ let seq = 0
191
+ return {
192
+ readText: () => readFileSync(path, 'utf8'),
193
+ writeAtomic: async (text) => {
194
+ seq += 1
195
+ const tmp = `${path}.tmp-${process.pid}-${seq}`
196
+ const mode = statSync(path).mode
197
+ try {
198
+ writeFileSync(tmp, text, mode !== undefined ? { mode } : undefined)
199
+ await rename(tmp, path)
200
+ } catch (err) {
201
+ await unlink(tmp).catch(() => {})
202
+ throw err
203
+ }
204
+ },
205
+ }
206
+ }
207
+
208
+ async function createExclusiveBackup(
209
+ fs: MigrateFs,
210
+ sourcePath: string,
211
+ stamp: string,
212
+ ): Promise<{ backupPath: string; sourceText: string; mode?: number } | undefined> {
213
+ const info = await fs.stat(sourcePath).catch(() => undefined)
214
+ if (info === undefined) return undefined
215
+ const sourceText = await fs.readFile(sourcePath)
216
+ const dir = dirname(sourcePath)
217
+ const base = basename(sourcePath)
218
+ await fs.mkdir(dir, { recursive: true })
219
+ const mode = info.mode & 0o777
220
+ for (let attempt = 0; attempt < 100; attempt++) {
221
+ const suffix = attempt === 0 ? stamp : `${stamp}-${attempt}`
222
+ const candidate = join(dir, `${base}.bak.${suffix}`)
223
+ const ok = await fs.writeFileExclusive(candidate, sourceText, mode)
224
+ if (ok) {
225
+ await pruneOldBackups(fs, dir, `${base}.bak.`, BACKUP_KEEP_COUNT)
226
+ return { backupPath: candidate, sourceText, mode }
227
+ }
228
+ }
229
+ throw new Error(`failed to claim unique backup path for ${sourcePath}`)
230
+ }
231
+
232
+ async function pruneOldBackups(
233
+ fs: MigrateFs,
234
+ dir: string,
235
+ prefix: string,
236
+ keepCount: number,
237
+ ): Promise<void> {
238
+ const entries = await fs.readdir(dir).catch(() => [] as string[])
239
+ const matching = entries
240
+ .filter((name) => name.startsWith(prefix) && /^\d{8}-\d{6}/.test(name.slice(prefix.length)))
241
+ .sort((a, b) => b.localeCompare(a))
242
+ for (const stale of matching.slice(keepCount)) {
243
+ await fs.unlink(join(dir, stale)).catch(() => {})
244
+ }
245
+ }
246
+
247
+ function storeForProfile(deps: OfficialMigrateDeps, profileKey: string): OfficialMigrationStore {
248
+ if (deps.storeFor !== undefined) return deps.storeFor(profileKey)
249
+ const accessor = deps.storeAccessor ?? loadModelsStore(deps.modelsStorePath)
250
+ return createOfficialMigrationStore(accessor, profileKey, deps.adapter.id)
251
+ }
252
+
253
+ interface DefaultModelRewritePlan {
254
+ currentProvider: string
255
+ currentModel: string
256
+ nextProvider: string
257
+ nextModel: string
258
+ previousConfig: Record<string, unknown>
259
+ }
260
+
261
+ function planDefaultModelRewrite(
262
+ defaultModelUser: Record<string, unknown> | undefined,
263
+ builtinProviderId: string,
264
+ providers: readonly CustomProviderSpec[],
265
+ ): DefaultModelRewritePlan | undefined {
266
+ if (defaultModelUser === undefined) return undefined
267
+ const currentProvider = defaultModelUser.provider
268
+ const currentModel = defaultModelUser.model
269
+ if (currentProvider !== builtinProviderId || typeof currentModel !== 'string' || currentModel.length === 0) {
270
+ return undefined
271
+ }
272
+ const matchingProvider = providers.find((p) => p.models.some((m) => m.id === currentModel))
273
+ const targetProvider = matchingProvider ?? providers[0]
274
+ if (targetProvider === undefined || targetProvider.models.length === 0) return undefined
275
+ const nextModel = matchingProvider !== undefined ? currentModel : targetProvider.models[0]!.id
276
+ return {
277
+ currentProvider: builtinProviderId,
278
+ currentModel,
279
+ nextProvider: targetProvider.routeId,
280
+ nextModel,
281
+ previousConfig: structuredClone(defaultModelUser),
282
+ }
283
+ }
284
+
285
+ async function askSingleConfirmation(
286
+ ask: AskServiceShape | undefined,
287
+ questionId: string,
288
+ question: string,
289
+ header: string,
290
+ confirmLabel: string,
291
+ confirmFlag: boolean,
292
+ invocation?: { agent?: unknown; signal?: AbortSignal },
293
+ ): Promise<{ confirmed: true } | { confirmed: false; error: string }> {
294
+ if (ask === undefined) {
295
+ if (confirmFlag) return { confirmed: true }
296
+ return {
297
+ confirmed: false,
298
+ error: 'Interactive confirmation channel is unavailable in this host. Run from an interactive UI, or pass `--confirm` explicitly after reviewing the status/preview.',
299
+ }
300
+ }
301
+ let response
302
+ try {
303
+ response = await ask.ask({
304
+ questions: [{
305
+ id: questionId,
306
+ question,
307
+ header,
308
+ options: [
309
+ { label: confirmLabel },
310
+ { label: LABEL_CANCEL },
311
+ ],
312
+ multiSelect: false,
313
+ }],
314
+ ...(invocation?.agent === undefined ? {} : { agent: invocation.agent }),
315
+ ...(invocation?.signal === undefined ? {} : { signal: invocation.signal }),
316
+ })
317
+ } catch (err) {
318
+ const msg = err instanceof Error ? err.message : String(err)
319
+ return { confirmed: false, error: `Confirmation failed (${msg}); no settings were changed.` }
320
+ }
321
+ if (invocation?.signal?.aborted === true) {
322
+ return { confirmed: false, error: 'Cancelled (signal aborted); no settings were changed.' }
323
+ }
324
+ const answer = (response?.answers ?? []).find((item) => item.id === questionId)
325
+ const selected = answer?.selected ?? []
326
+ const choseConfirm = selected.includes(confirmLabel)
327
+ const choseCancel = selected.includes(LABEL_CANCEL)
328
+ if (choseConfirm && !choseCancel) {
329
+ return { confirmed: true }
330
+ }
331
+ if (choseConfirm && choseCancel) {
332
+ return { confirmed: false, error: 'Confirmation answer was ambiguous; no settings were changed.' }
333
+ }
334
+ return { confirmed: false, error: 'Cancelled by user; no settings were changed.' }
335
+ }
336
+
337
+ interface PreparedTargetPlan {
338
+ target: MigrateTargetProfile
339
+ store: OfficialMigrationStore
340
+ apiKeyEnv: string
341
+ previousBuiltinSection: Record<string, unknown>
342
+ previousManagedSections: Record<string, Record<string, unknown> | null>
343
+ specs: CustomProviderSpec[]
344
+ totalModels: number
345
+ sessionHeaderApplied: boolean
346
+ hostNativeSessionHeader: boolean
347
+ warnings: string[]
348
+ defaultModelRewrite?: DefaultModelRewritePlan
349
+ otherRefs: PatchReferenceHit[]
350
+ staleRoutesToUnset: string[]
351
+ }
352
+
353
+ async function resolveTargetProfiles(
354
+ deps: OfficialMigrateDeps,
355
+ allProfiles: boolean,
356
+ ): Promise<{ ok: true; targets: MigrateTargetProfile[] } | { ok: false; error: string }> {
357
+ const fs = deps.fs ?? createDefaultMigrateFs()
358
+ const patchIoFor = deps.patchIoFor ?? createDefaultPatchIo
359
+ const currentKey = deps.currentProfile.key
360
+ if (currentKey === undefined) {
361
+ return {
362
+ ok: false,
363
+ error: 'Cannot resolve current dsh profile identity. Launch inside a dsh profile before migrating.',
364
+ }
365
+ }
366
+
367
+ const currentDir = deps.currentProfile.dir
368
+ const currentPatchPath = currentDir !== undefined ? join(currentDir, 'cordis.patch.yml') : undefined
369
+ const currentPatchText = currentPatchPath !== undefined
370
+ ? await fs.readFile(currentPatchPath).catch(() => undefined)
371
+ : undefined
372
+
373
+ const currentTarget: MigrateTargetProfile = {
374
+ profileKey: currentKey,
375
+ profileDir: currentDir,
376
+ isCurrent: true,
377
+ settings: deps.currentSettings,
378
+ patchPath: currentPatchPath,
379
+ patchText: currentPatchText,
380
+ }
381
+
382
+ if (!allProfiles) return { ok: true, targets: [currentTarget] }
383
+
384
+ const targets: MigrateTargetProfile[] = []
385
+ const currentLlmDesc = deps.currentSettings?.describe().find((d) => d.ns === 'llm-pi-ai')
386
+ const currentProviders = (currentLlmDesc?.user?.providers as Record<string, unknown> | undefined) ?? {}
387
+ const currentAlreadyMigrated = (await storeForProfile(deps, currentKey).read()) !== undefined
388
+ if (!currentAlreadyMigrated && currentProviders[deps.adapter.builtinProviderId] !== undefined) {
389
+ targets.push(currentTarget)
390
+ }
391
+
392
+ const profilesRoot = deps.profilesDir ?? join(deps.home || resolveDshHome(), 'profiles')
393
+ const dirs = await fs.readdir(profilesRoot).catch(() => [] as string[])
394
+ for (const name of dirs.sort()) {
395
+ const dir = join(profilesRoot, name)
396
+ if (name === currentKey || (currentDir !== undefined && dir === currentDir)) continue
397
+ const patchPath = join(dir, 'cordis.patch.yml')
398
+ const info = await fs.stat(patchPath).catch(() => undefined)
399
+ if (info === undefined) continue
400
+ const patchText = await fs.readFile(patchPath).catch(() => undefined)
401
+ if (patchText === undefined) continue
402
+ const fileSettings = createFilePatchSettingsService(patchIoFor(patchPath))
403
+ const llmDesc = fileSettings.describe().find((d) => d.ns === 'llm-pi-ai')
404
+ const providers = (llmDesc?.user?.providers as Record<string, unknown> | undefined) ?? {}
405
+ if (providers[deps.adapter.builtinProviderId] === undefined) continue
406
+ const existingRecord = await storeForProfile(deps, name).read()
407
+ if (existingRecord !== undefined) continue
408
+ targets.push({
409
+ profileKey: name,
410
+ profileDir: dir,
411
+ isCurrent: false,
412
+ settings: fileSettings,
413
+ patchPath,
414
+ patchText,
415
+ })
416
+ }
417
+
418
+ if (targets.length === 0) {
419
+ return {
420
+ ok: false,
421
+ error: `No unmigrated profiles with \`providers.${deps.adapter.builtinProviderId}\` found.`,
422
+ }
423
+ }
424
+ return { ok: true, targets }
425
+ }
426
+
427
+ async function prepareProfilePlan(
428
+ deps: OfficialMigrateDeps,
429
+ target: MigrateTargetProfile,
430
+ ): Promise<{ ok: true; plan: PreparedTargetPlan } | { ok: false; error: string }> {
431
+ const { adapter, config } = deps
432
+ const store = storeForProfile(deps, target.profileKey)
433
+ const existing = await store.read()
434
+ if (existing !== undefined) {
435
+ const alias = adapter.aliases[0] ?? adapter.id
436
+ return {
437
+ ok: false,
438
+ error: `[${target.profileKey}] ${adapter.id} is already migrated. Use \`/model-sync ${alias}\` to update or \`/model-sync rollback ${alias}\` to revert.`,
439
+ }
440
+ }
441
+
442
+ if (target.settings === undefined) {
443
+ return { ok: false, error: `[${target.profileKey}] settings service unavailable.` }
444
+ }
445
+ const descs = target.settings.describe()
446
+ const llmDesc = descs.find((d) => d.ns === 'llm-pi-ai')
447
+ const providers = (llmDesc?.user?.providers as Record<string, unknown> | undefined) ?? {}
448
+ const rawBuiltin = providers[adapter.builtinProviderId]
449
+ if (rawBuiltin === undefined || rawBuiltin === null || typeof rawBuiltin !== 'object' || Array.isArray(rawBuiltin)) {
450
+ return {
451
+ ok: false,
452
+ error: `[${target.profileKey}] No existing Builtin Provider \`providers.${adapter.builtinProviderId}\` found. Please configure \`${adapter.builtinProviderId}\` and its API key first; blank profiles cannot initialize via migrate.`,
453
+ }
454
+ }
455
+ const previousBuiltinSection = structuredClone(rawBuiltin as Record<string, unknown>)
456
+ const declaredKeyEnv = typeof previousBuiltinSection.apiKeyEnv === 'string' && previousBuiltinSection.apiKeyEnv.trim().length > 0
457
+ ? previousBuiltinSection.apiKeyEnv.trim()
458
+ : undefined
459
+
460
+ const candidateRefs = declaredKeyEnv !== undefined
461
+ ? [declaredKeyEnv, ...adapter.defaultKeyRefs]
462
+ : adapter.defaultKeyRefs
463
+ const resolved = await resolveCredentialByRefs(deps.credentialCtx, candidateRefs)
464
+ if (resolved.value === undefined) {
465
+ return {
466
+ ok: false,
467
+ error: `[${target.profileKey}] API key for \`${resolved.ref}\` is not configured. Please set the credential before running migrate.`,
468
+ }
469
+ }
470
+
471
+ const fetched = await adapter.fetchAndPlan({
472
+ apiKey: resolved.value,
473
+ apiKeyEnv: resolved.ref,
474
+ config,
475
+ timeoutMs: deps.timeoutMs,
476
+ fetchImpl: deps.fetchImpl,
477
+ detectHostSessionHeader: deps.detectHostSessionHeader,
478
+ loadPiAiCompatHints: deps.loadPiAiCompatHints,
479
+ })
480
+ if (!fetched.ok || fetched.providers.length === 0) {
481
+ return {
482
+ ok: false,
483
+ error: `[${target.profileKey}] Failed to fetch official ${adapter.displayName} models (${fetched.error?.message ?? 'empty listing'}); zero writes performed.`,
484
+ }
485
+ }
486
+
487
+ const defaultModelDesc = descs.find((d) => d.ns === 'agent-default-model')
488
+ const defaultModelRewrite = planDefaultModelRewrite(
489
+ defaultModelDesc?.user as Record<string, unknown> | undefined,
490
+ adapter.builtinProviderId,
491
+ fetched.providers,
492
+ )
493
+
494
+ const otherRefs = target.patchText !== undefined
495
+ ? scanPatchReferences(target.patchText, adapter.builtinProviderId)
496
+ : []
497
+
498
+ const previousManagedSections: Record<string, Record<string, unknown> | null> = {}
499
+ for (const spec of fetched.providers) {
500
+ const cur = providers[spec.routeId]
501
+ previousManagedSections[spec.routeId] = cur !== undefined && cur !== null && typeof cur === 'object' && !Array.isArray(cur)
502
+ ? structuredClone(cur as Record<string, unknown>)
503
+ : null
504
+ }
505
+
506
+ const activeRouteIds = new Set(fetched.providers.map((p) => p.routeId))
507
+ const staleRoutesToUnset: string[] = []
508
+ for (const legacyRoute of [...adapter.legacyExtraRoutes, ...Object.values(config.routes)]) {
509
+ if (legacyRoute === adapter.builtinProviderId || activeRouteIds.has(legacyRoute)) continue
510
+ if (providers[legacyRoute] !== undefined) {
511
+ staleRoutesToUnset.push(legacyRoute)
512
+ previousManagedSections[legacyRoute] = providers[legacyRoute] !== null && typeof providers[legacyRoute] === 'object' && !Array.isArray(providers[legacyRoute])
513
+ ? structuredClone(providers[legacyRoute] as Record<string, unknown>)
514
+ : null
515
+ }
516
+ }
517
+
518
+ return {
519
+ ok: true,
520
+ plan: {
521
+ target,
522
+ store,
523
+ apiKeyEnv: resolved.ref,
524
+ previousBuiltinSection,
525
+ previousManagedSections,
526
+ specs: fetched.providers,
527
+ totalModels: fetched.totalModels,
528
+ sessionHeaderApplied: fetched.sessionHeaderApplied,
529
+ hostNativeSessionHeader: fetched.hostNativeSessionHeader,
530
+ warnings: fetched.warnings,
531
+ defaultModelRewrite,
532
+ otherRefs,
533
+ staleRoutesToUnset,
534
+ },
535
+ }
536
+ }
537
+
538
+ export async function runOfficialMigrate(
539
+ deps: OfficialMigrateDeps,
540
+ options: { allProfiles?: boolean; confirm?: boolean; agent?: unknown; signal?: AbortSignal } = {},
541
+ ): Promise<MigrateCommandResult> {
542
+ const fs = deps.fs ?? createDefaultMigrateFs()
543
+ const targetsRes = await resolveTargetProfiles(deps, options.allProfiles === true)
544
+ if (!targetsRes.ok) return { kind: 'error', text: targetsRes.error }
545
+
546
+ const plans: PreparedTargetPlan[] = []
547
+ for (const target of targetsRes.targets) {
548
+ const res = await prepareProfilePlan(deps, target)
549
+ if (!res.ok) return { kind: 'error', text: res.error }
550
+ plans.push(res.plan)
551
+ }
552
+
553
+ // Build backups BEFORE asking confirmation (matching safe backup pattern)
554
+ const stamp = formatStamp((deps.now ?? Date.now)())
555
+ const backups: Array<{ originalPath: string; backupPath: string; sourceText: string; mode?: number }> = []
556
+ for (const plan of plans) {
557
+ if (plan.target.patchPath !== undefined) {
558
+ const bak = await createExclusiveBackup(fs, plan.target.patchPath, stamp)
559
+ if (bak !== undefined) backups.push({ originalPath: plan.target.patchPath, ...bak })
560
+ }
561
+ }
562
+ const storeBak = await createExclusiveBackup(fs, deps.modelsStorePath, stamp)
563
+
564
+ // Single confirmation gate
565
+ const previewLines: string[] = [
566
+ `迁移 ${deps.adapter.displayName} (${deps.adapter.builtinProviderId}) 到独立 Custom Providers:`,
567
+ ]
568
+ for (const plan of plans) {
569
+ const slots = plan.specs.map((s) => `${s.routeId} (${s.api}, ${s.models.length} models)`).join(', ')
570
+ previewLines.push(`• Profile "${plan.target.profileKey}":`)
571
+ previewLines.push(` - 提取 Key 引用: ${plan.apiKeyEnv}`)
572
+ previewLines.push(` - 删除 Builtin Provider: ${deps.adapter.builtinProviderId}`)
573
+ previewLines.push(` - 创建 Custom Providers: ${slots}`)
574
+ if (plan.defaultModelRewrite !== undefined) {
575
+ previewLines.push(
576
+ ` - 改写默认模型: ${plan.defaultModelRewrite.currentProvider}/${plan.defaultModelRewrite.currentModel} → ${plan.defaultModelRewrite.nextProvider}/${plan.defaultModelRewrite.nextModel}`,
577
+ )
578
+ }
579
+ if (plan.otherRefs.length > 0) {
580
+ previewLines.push(` - 提示其他配置引用 (${plan.otherRefs.length} 处需按需手工调整): ${plan.otherRefs.map((h) => `${h.entryId}:${h.value}`).join(', ')}`)
581
+ }
582
+ }
583
+ if (backups.length > 0 || storeBak !== undefined) {
584
+ const bakPaths = [...backups.map((b) => b.backupPath), ...(storeBak ? [storeBak.backupPath] : [])]
585
+ previewLines.push(`• 备份文件: ${bakPaths.join(', ')}`)
586
+ }
587
+ previewLines.push(`• 迁移后将自动开启每 ${deps.config.intervalMinutes} 分钟同步一次官方最新模型(可通过 /model-sync rollback ${deps.adapter.aliases[0] ?? deps.adapter.id} 回退)。`)
588
+
589
+ const ask = deps.resolveAsk?.()
590
+ const consent = await askSingleConfirmation(
591
+ ask,
592
+ 'official-migrate-confirm',
593
+ previewLines.join('\n'),
594
+ `迁移 ${deps.adapter.displayName}`,
595
+ LABEL_MIGRATE,
596
+ options.confirm === true,
597
+ { agent: options.agent, signal: options.signal },
598
+ )
599
+ if (!consent.confirmed) {
600
+ return { kind: 'error', text: consent.error }
601
+ }
602
+
603
+ // Apply writes; on failure, byte-restore backed up patch files & store
604
+ const modifiedPatches: Array<{ originalPath: string; sourceText: string; mode?: number }> = []
605
+ try {
606
+ const accessor = deps.storeAccessor ?? loadModelsStore(deps.modelsStorePath)
607
+ for (const plan of plans) {
608
+ const settings = plan.target.settings!
609
+ const descs = settings.describe()
610
+ const llmDesc = descs.find((d) => d.ns === 'llm-pi-ai')
611
+ if (llmDesc === undefined) throw new Error(`[${plan.target.profileKey}] llm-pi-ai namespace missing`)
612
+
613
+ const ops: SettingsMutationOp[] = []
614
+ for (const spec of plan.specs) {
615
+ ops.push({ op: 'set', path: ['providers', spec.routeId], value: buildCustomProviderValue(spec) })
616
+ }
617
+ ops.push({ op: 'unset', path: ['providers', deps.adapter.builtinProviderId] })
618
+ for (const stale of plan.staleRoutesToUnset) {
619
+ ops.push({ op: 'unset', path: ['providers', stale] })
620
+ }
621
+
622
+ const patchBak = backups.find((b) => b.originalPath === plan.target.patchPath)
623
+ if (patchBak !== undefined) modifiedPatches.push(patchBak)
624
+
625
+ await settings.mutate('llm-pi-ai', ops, llmDesc.revision)
626
+
627
+ if (plan.defaultModelRewrite !== undefined) {
628
+ const dmDesc = settings.describe().find((d) => d.ns === 'agent-default-model')
629
+ if (dmDesc !== undefined) {
630
+ const dmOps: SettingsMutationOp[] = [
631
+ { op: 'set', path: ['provider'], value: plan.defaultModelRewrite.nextProvider },
632
+ ]
633
+ if (plan.defaultModelRewrite.nextModel !== plan.defaultModelRewrite.currentModel) {
634
+ dmOps.push({ op: 'set', path: ['model'], value: plan.defaultModelRewrite.nextModel })
635
+ }
636
+ await settings.mutate('agent-default-model', dmOps, dmDesc.revision)
637
+ }
638
+ }
639
+
640
+ const record: OfficialMigrationRecord = {
641
+ version: 2,
642
+ adapterId: deps.adapter.id,
643
+ profileKey: plan.target.profileKey,
644
+ migratedAt: (deps.now ?? Date.now)(),
645
+ apiKeyEnv: plan.apiKeyEnv,
646
+ builtinProviderId: deps.adapter.builtinProviderId,
647
+ managedRoutes: plan.specs.map((s) => s.routeId),
648
+ previousBuiltinSection: plan.previousBuiltinSection,
649
+ previousManagedSections: plan.previousManagedSections,
650
+ ...(plan.defaultModelRewrite !== undefined
651
+ ? { previousDefaultModel: plan.defaultModelRewrite.previousConfig, rewroteDefaultModel: true }
652
+ : {}),
653
+ }
654
+ await plan.store.write(record)
655
+ await cleanupLegacyGoStoreKeys(accessor, plan.target.profileKey, Object.values(deps.config.routes))
656
+ }
657
+
658
+ if (plans.some((p) => p.target.isCurrent)) {
659
+ await deps.onCurrentProfileMigrated?.()
660
+ }
661
+ } catch (err) {
662
+ const msg = err instanceof Error ? err.message : String(err)
663
+ for (const bak of modifiedPatches) {
664
+ await fs.writeFile(bak.originalPath, bak.sourceText, bak.mode).catch(() => {})
665
+ }
666
+ if (storeBak !== undefined) {
667
+ await fs.writeFile(deps.modelsStorePath, storeBak.sourceText, storeBak.mode).catch(() => {})
668
+ }
669
+ return {
670
+ kind: 'error',
671
+ text: `Migration failed (${msg}); modified files were restored from backup.`,
672
+ }
673
+ }
674
+
675
+ const summaryLines = [
676
+ `Migration succeeded for ${plans.length} profile(s):`,
677
+ ...plans.map((p) => {
678
+ const slots = p.specs.map((s) => `${s.routeId}(${s.models.length})`).join(', ')
679
+ const dm = p.defaultModelRewrite !== undefined
680
+ ? `; default-model -> ${p.defaultModelRewrite.nextProvider}/${p.defaultModelRewrite.nextModel}`
681
+ : ''
682
+ const refs = p.otherRefs.length > 0
683
+ ? `; advisory refs remaining in other entries: ${p.otherRefs.map((h) => `${h.entryId}:${h.value}`).join(', ')}`
684
+ : ''
685
+ return `- ${p.target.profileKey}: deleted ${deps.adapter.builtinProviderId}, created [${slots}]${dm}${refs}`
686
+ }),
687
+ ]
688
+ return { kind: 'success', text: summaryLines.join('\n') }
689
+ }
690
+
691
+ export async function runOfficialRollback(
692
+ deps: OfficialMigrateDeps,
693
+ options: { confirm?: boolean; agent?: unknown; signal?: AbortSignal } = {},
694
+ ): Promise<MigrateCommandResult> {
695
+ const fs = deps.fs ?? createDefaultMigrateFs()
696
+ const profileKey = deps.currentProfile.key
697
+ if (profileKey === undefined) {
698
+ return { kind: 'error', text: 'Cannot resolve current dsh profile identity.' }
699
+ }
700
+
701
+ const store = storeForProfile(deps, profileKey)
702
+ const record = await store.read()
703
+ if (record === undefined) {
704
+ return { kind: 'error', text: `[${profileKey}] No migration record found for ${deps.adapter.id}; nothing to roll back.` }
705
+ }
706
+
707
+ const settings = deps.currentSettings
708
+ if (settings === undefined) {
709
+ return { kind: 'error', text: `[${profileKey}] settings service unavailable.` }
710
+ }
711
+
712
+ const stamp = formatStamp((deps.now ?? Date.now)())
713
+ const patchPath = deps.currentProfile.dir !== undefined ? join(deps.currentProfile.dir, 'cordis.patch.yml') : undefined
714
+ const patchBak = patchPath !== undefined ? await createExclusiveBackup(fs, patchPath, stamp) : undefined
715
+ const storeBak = await createExclusiveBackup(fs, deps.modelsStorePath, stamp)
716
+
717
+ const previewLines = [
718
+ `回退 ${deps.adapter.displayName} 迁移 (profile "${profileKey}"):`,
719
+ `- 还原 Builtin Provider: ${record.builtinProviderId}`,
720
+ `- 移除 Managed Custom Providers: ${record.managedRoutes.join(', ')}`,
721
+ ...(record.rewroteDefaultModel && record.previousDefaultModel
722
+ ? [`- 还原默认模型: ${String(record.previousDefaultModel.provider ?? '')}/${String(record.previousDefaultModel.model ?? '')}`]
723
+ : []),
724
+ ...(patchBak || storeBak
725
+ ? [`- 备份路径: ${[patchBak?.backupPath, storeBak?.backupPath].filter(Boolean).join(', ')}`]
726
+ : []),
727
+ ]
728
+
729
+ const consent = await askSingleConfirmation(
730
+ deps.resolveAsk?.(),
731
+ 'official-rollback-confirm',
732
+ previewLines.join('\n'),
733
+ `回退 ${deps.adapter.displayName}`,
734
+ LABEL_ROLLBACK,
735
+ options.confirm === true,
736
+ { agent: options.agent, signal: options.signal },
737
+ )
738
+ if (!consent.confirmed) return { kind: 'error', text: consent.error }
739
+
740
+ try {
741
+ const descs = settings.describe()
742
+ const llmDesc = descs.find((d) => d.ns === 'llm-pi-ai')
743
+ if (llmDesc === undefined) throw new Error('llm-pi-ai namespace missing')
744
+
745
+ const ops: SettingsMutationOp[] = [
746
+ { op: 'set', path: ['providers', record.builtinProviderId], value: record.previousBuiltinSection },
747
+ ]
748
+ const routesToClear = new Set([
749
+ ...record.managedRoutes,
750
+ ...Object.keys(record.previousManagedSections ?? {}),
751
+ ])
752
+ routesToClear.delete(record.builtinProviderId)
753
+ for (const routeId of routesToClear) {
754
+ const prev = record.previousManagedSections?.[routeId]
755
+ if (prev !== undefined && prev !== null) {
756
+ ops.push({ op: 'set', path: ['providers', routeId], value: prev })
757
+ } else {
758
+ ops.push({ op: 'unset', path: ['providers', routeId] })
759
+ }
760
+ }
761
+ await settings.mutate('llm-pi-ai', ops, llmDesc.revision)
762
+
763
+ if (record.rewroteDefaultModel && record.previousDefaultModel !== undefined) {
764
+ const dmDesc = settings.describe().find((d) => d.ns === 'agent-default-model')
765
+ if (dmDesc !== undefined) {
766
+ const dmOps: SettingsMutationOp[] = []
767
+ for (const [k, v] of Object.entries(record.previousDefaultModel)) {
768
+ dmOps.push({ op: 'set', path: [k], value: v })
769
+ }
770
+ if (dmOps.length > 0) await settings.mutate('agent-default-model', dmOps, dmDesc.revision)
771
+ }
772
+ }
773
+
774
+ await store.delete()
775
+ await deps.onCurrentProfileRolledBack?.()
776
+ } catch (err) {
777
+ const msg = err instanceof Error ? err.message : String(err)
778
+ if (patchBak !== undefined && patchPath !== undefined) {
779
+ await fs.writeFile(patchPath, patchBak.sourceText, patchBak.mode).catch(() => {})
780
+ }
781
+ if (storeBak !== undefined) {
782
+ await fs.writeFile(deps.modelsStorePath, storeBak.sourceText, storeBak.mode).catch(() => {})
783
+ }
784
+ return { kind: 'error', text: `Rollback failed (${msg}); files restored from backup.` }
785
+ }
786
+
787
+ return {
788
+ kind: 'success',
789
+ text: `[${profileKey}] Rolled back ${deps.adapter.id}: restored ${record.builtinProviderId}, removed [${record.managedRoutes.join(', ')}], stopped auto-sync.`,
790
+ }
791
+ }
792
+
793
+ export async function runOfficialStatus(
794
+ deps: OfficialMigrateDeps,
795
+ ): Promise<MigrateCommandResult> {
796
+ const { adapter, config } = deps
797
+ const alias = adapter.aliases[0] ?? adapter.id
798
+ const profileKey = deps.currentProfile.key
799
+ const descs = deps.currentSettings?.describe() ?? []
800
+ const llmDesc = descs.find((d) => d.ns === 'llm-pi-ai')
801
+ const providers = (llmDesc?.user?.providers as Record<string, unknown> | undefined) ?? {}
802
+ const record = profileKey !== undefined ? await storeForProfile(deps, profileKey).read() : undefined
803
+
804
+ const hostNative = (deps.detectHostSessionHeader ?? adapter.detectHostSessionHeader ?? (() => false))()
805
+ const lines: string[] = [
806
+ `${adapter.displayName} (${adapter.id}) status:`,
807
+ `- profile: ${profileKey ?? '(unknown)'}`,
808
+ `- migration: ${record !== undefined ? `migrated (at ${new Date(record.migratedAt).toISOString()}, keyRef=${record.apiKeyEnv})` : 'not migrated'}`,
809
+ `- auto-sync interval: ${config.intervalMinutes} min (0 = manual only)`,
810
+ `- sessionHeader: mode=${config.sessionHeader}, host-native=${hostNative ? 'yes' : 'no'}`,
811
+ ]
812
+
813
+ const hasLegacyBuiltin = providers[adapter.builtinProviderId] !== undefined
814
+ if (hasLegacyBuiltin) {
815
+ const builtinModels = (providers[adapter.builtinProviderId] as { models?: unknown[] } | undefined)?.models
816
+ lines.push(`- builtin ${adapter.builtinProviderId}: present (${Array.isArray(builtinModels) ? builtinModels.length : 'catalog'} models)`)
817
+ } else {
818
+ lines.push(`- builtin ${adapter.builtinProviderId}: absent`)
819
+ }
820
+
821
+ const slotRoutes = new Set([
822
+ ...(record?.managedRoutes ?? []),
823
+ ...Object.values(config.routes),
824
+ ])
825
+ for (const routeId of slotRoutes) {
826
+ if (routeId === adapter.builtinProviderId) continue
827
+ const section = providers[routeId] as { api?: string; models?: unknown[]; headers?: Record<string, string> } | undefined
828
+ if (section !== undefined) {
829
+ const count = Array.isArray(section.models) ? section.models.length : 0
830
+ lines.push(`- custom ${routeId}: active (api=${section.api ?? '?'}, models=${count}, static-headers=${section.headers ? 'yes' : 'no'})`)
831
+ }
832
+ }
833
+
834
+ const keyRefs = record !== undefined ? [record.apiKeyEnv, ...adapter.defaultKeyRefs] : adapter.defaultKeyRefs
835
+ const resolved = await resolveCredentialByRefs(deps.credentialCtx, keyRefs)
836
+ if (resolved.value === undefined) {
837
+ lines.push(`- official API: skipped (${resolved.ref} not configured)`)
838
+ } else {
839
+ const fetched = await adapter.fetchAndPlan({
840
+ apiKey: resolved.value,
841
+ apiKeyEnv: resolved.ref,
842
+ config,
843
+ timeoutMs: deps.timeoutMs,
844
+ fetchImpl: deps.fetchImpl,
845
+ detectHostSessionHeader: deps.detectHostSessionHeader,
846
+ loadPiAiCompatHints: deps.loadPiAiCompatHints,
847
+ })
848
+ if (!fetched.ok) {
849
+ lines.push(`- official API: error (${fetched.error?.message ?? 'unknown'})`)
850
+ } else {
851
+ const slotSummary = fetched.providers.map((p) => `${p.routeId}=${p.models.length}`).join(', ')
852
+ lines.push(`- official API: ok (${fetched.totalModels} models → ${slotSummary})`)
853
+ }
854
+ }
855
+
856
+ if (record === undefined) {
857
+ lines.push(hasLegacyBuiltin
858
+ ? `Hint: run \`/model-sync migrate ${alias}\` to detach into Managed Custom Providers.`
859
+ : `Hint: configure \`${adapter.builtinProviderId}\` in settings first, then run \`/model-sync migrate ${alias}\`.`)
860
+ }
861
+
862
+ return { kind: 'success', text: lines.join('\n') }
863
+ }