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