@aiwayds/dsh-model-sync 0.11.1 → 0.12.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.
@@ -21,7 +21,6 @@
21
21
  import { createHash } from 'node:crypto'
22
22
  import {
23
23
  GO_SLOT_ROUTES,
24
- groupGoModelsByProtocol,
25
24
  type GoRouteSlot,
26
25
  } from './opencode-go-grouping.ts'
27
26
  import {
@@ -29,6 +28,7 @@ import {
29
28
  mapGoModelToProfile,
30
29
  planGoRouteFields,
31
30
  profileHash,
31
+ GO_LEGACY_ROUTE_FIELDS,
32
32
  type GoManagedModel,
33
33
  type GoOwnershipEntry,
34
34
  type GoPlannedRouteFields,
@@ -53,7 +53,11 @@ import type { GoOwnershipStore } from './opencode-go-writer.ts'
53
53
  import type { GoJournalStore } from './opencode-go-journal.ts'
54
54
  import type { Logger, SettingsDescriptor, SettingsMutationOp, SettingsService } from './writer.ts'
55
55
 
56
- const OWNED_FIELDS = ['api', 'baseURL', 'displayName', 'apiKeyEnv'] as const
56
+ // 0.12.0 catalog-reuse: the only route field migrate writes is `apiKeyEnv`.
57
+ // `api`/`baseURL` are stripped (they make the host leave pi-ai's builtin
58
+ // catalog provider — and its x-opencode-session wrapping — behind), and
59
+ // `displayName` is never rewritten so a user rename survives the migration.
60
+ const OWNED_FIELDS = ['apiKeyEnv'] as const
57
61
  const PLAN_VERSION = 1
58
62
 
59
63
  // ---------------------------------------------------------------------------
@@ -65,10 +69,8 @@ export type MigrationAction = 'create' | 'update' | 'keep' | 'unset'
65
69
 
66
70
  /** Classification of one id that exists in the current route (design §14.2). */
67
71
  export type MigrationIdKind =
68
- | 'desired-chat'
69
- | 'desired-msg'
70
- | 'desired-resp'
71
- | 'desired-google'
72
+ /** Official desired id — always targets the single managed route (0.12.0). */
73
+ | 'desired'
72
74
  | 'legacy-other-protocol'
73
75
  | 'unknown-retired'
74
76
  | 'user-extra'
@@ -327,6 +329,17 @@ export function verifyConsent(
327
329
  // Pure plan builder (V16: zero writes / zero external calls)
328
330
  // ---------------------------------------------------------------------------
329
331
 
332
+ /** Raw models array of one section from a readGoProviderSections result. */
333
+ function routeModels(
334
+ sections: Record<string, unknown> | undefined,
335
+ route: string,
336
+ ): SettingsModelProfile[] {
337
+ const section = sections?.[route]
338
+ return isRecord(section) && Array.isArray(section.models)
339
+ ? section.models as SettingsModelProfile[]
340
+ : []
341
+ }
342
+
330
343
  /** Per-route state, refined from the full-set state (§14.1). */
331
344
  function detectRouteStates(
332
345
  sections: Record<string, unknown> | undefined,
@@ -401,25 +414,20 @@ export function buildMigrationPlan(input: BuildPlanInput): MigrationPlan {
401
414
  const adopt = input.adopt === true && !adoptDisabled
402
415
  const rewriteRefs = input.rewriteRefs ?? 'none'
403
416
 
404
- const grouping = groupGoModelsByProtocol(input.entries)
405
- const entryById = new Map(input.entries.map((entry) => [entry.id, entry]))
406
-
407
- const desiredBySlot = new Map<GoRouteSlot, SettingsModelProfile[]>()
408
- for (const slot of ['chat', 'msg', 'resp', 'google'] as const) {
409
- desiredBySlot.set(slot, grouping.slots[slot]
410
- .map((id) => entryById.get(id))
411
- .filter((entry): entry is GoModelRecord => entry !== undefined)
412
- .map(mapGoModelToProfile)
413
- .sort((a, b) => a.id.localeCompare(b.id)))
414
- }
415
- const desiredIds = new Set([...desiredBySlot.values()].flat().map((profile) => profile.id))
416
-
417
- // The two ids that move out of chat into dedicated protocol routes (§14.4).
418
- const targets = grouping.slots.msg.concat(grouping.slots.resp)
419
- const references = input.references ?? defaultReferences(targets, rewriteRefs)
420
-
421
- // Routes actually in scope for this plan (a conditional, empty google slot
422
- // with no pre-existing section is skipped — §9.4).
417
+ // 0.12.0 desired collapse: EVERY official entry targets the single managed
418
+ // route (routes.chat). The three legacy protocol routes act only as move
419
+ // sources (adopt) / keep sources (conservative) for ids still sitting there.
420
+ const targetRoute = routes.chat
421
+ const targetSlot: GoRouteSlot = 'chat'
422
+ const fields = planGoRouteFields(input.entries, input.ref)
423
+ const desired = input.entries
424
+ .map(mapGoModelToProfile)
425
+ .sort((a, b) => a.id.localeCompare(b.id))
426
+ const desiredIds = new Set(desired.map((profile) => profile.id))
427
+
428
+ // Routes actually in scope for this plan: the managed route always; a legacy
429
+ // slot route only when its section exists (a never-created route has nothing
430
+ // to migrate).
423
431
  const scopedRoutes: {
424
432
  slot: GoRouteSlot
425
433
  route: string
@@ -427,27 +435,29 @@ export function buildMigrationPlan(input: BuildPlanInput): MigrationPlan {
427
435
  fields: GoPlannedRouteFields
428
436
  desired: SettingsModelProfile[]
429
437
  currentModels: SettingsModelProfile[]
430
- }[] = []
431
- for (const slot of ['chat', 'msg', 'resp', 'google'] as const) {
432
- if (slot === 'google' && desiredBySlot.get(slot)!.length === 0 && sections?.[routes[slot]] === undefined) continue
438
+ }[] = [{
439
+ slot: targetSlot,
440
+ route: targetRoute,
441
+ state: stateByRoute[targetRoute] ?? 'absent',
442
+ fields,
443
+ desired,
444
+ currentModels: routeModels(sections, targetRoute),
445
+ }]
446
+ for (const slot of ['msg', 'resp', 'google'] as const) {
433
447
  const route = routes[slot]
434
- const section = sections?.[route]
435
- const routeState = stateByRoute[route] ?? 'absent'
436
- const fields = planGoRouteFields(slot, input.entries.filter((entry) => grouping.slots[slot].includes(entry.id)), input.ref)
437
- const desired = desiredBySlot.get(slot) ?? []
438
- const currentModels: SettingsModelProfile[] = isRecord(section) && Array.isArray(section.models)
439
- ? section.models as SettingsModelProfile[]
440
- : []
441
- scopedRoutes.push({ slot, route, state: routeState, fields, desired, currentModels })
448
+ if (sections?.[route] === undefined) continue
449
+ scopedRoutes.push({
450
+ slot,
451
+ route,
452
+ state: stateByRoute[route] ?? 'absent',
453
+ fields,
454
+ desired: [],
455
+ currentModels: routeModels(sections, route),
456
+ })
442
457
  }
443
458
 
444
- // desired id → its official target route + exact profile.
445
- const desiredTarget = new Map<string, { slot: GoRouteSlot; route: string; profile: SettingsModelProfile }>()
446
- for (const scope of scopedRoutes) {
447
- for (const profile of scope.desired) {
448
- desiredTarget.set(profile.id, { slot: scope.slot, route: scope.route, profile })
449
- }
450
- }
459
+ // desired id → its official target (always the single managed route).
460
+ const desiredTarget = new Map(desired.map((profile) => [profile.id, { slot: targetSlot, route: targetRoute, profile }]))
451
461
 
452
462
  // Every id currently in settings, with all the routes it occupies.
453
463
  const currentLocations = new Map<string, { route: string; profile: SettingsModelProfile }[]>()
@@ -459,6 +469,13 @@ export function buildMigrationPlan(input: BuildPlanInput): MigrationPlan {
459
469
  }
460
470
  }
461
471
 
472
+ // Ids whose references change under this plan: desired ids still sitting on
473
+ // a legacy protocol route (they end up on the managed route after apply).
474
+ const targets = desired
475
+ .filter((profile) => (currentLocations.get(profile.id) ?? []).some((loc) => loc.route !== targetRoute))
476
+ .map((profile) => profile.id)
477
+ const references = input.references ?? defaultReferences(targets, rewriteRefs)
478
+
462
479
  const pinnedIds = new Set(input.pinnedModels ?? [])
463
480
  // `undefined` is materially different from an empty list: empty means the
464
481
  // catalog was fetched and truly has no such id (→ user-extra); undefined means
@@ -468,8 +485,7 @@ export function buildMigrationPlan(input: BuildPlanInput): MigrationPlan {
468
485
  const pruneUserExtra = input.pruneUserExtra === true
469
486
 
470
487
  const kindOf = (id: string): MigrationIdKind => {
471
- const target = desiredTarget.get(id)
472
- if (target !== undefined) return `desired-${target.slot}` as MigrationIdKind
488
+ if (desiredTarget.has(id)) return 'desired'
473
489
  // Fail-closed (§14.2): no public catalog → never guess "user-written".
474
490
  if (!publicCatalogAvailable) return 'unclassified'
475
491
  // Ids in the official public catalog but not in the current key's authorized
@@ -590,7 +606,7 @@ export function buildMigrationPlan(input: BuildPlanInput): MigrationPlan {
590
606
  reason: action.reason,
591
607
  }))
592
608
 
593
- const plannedRoutes: MigrationPlannedRoute[] = scopedRoutes.map((scope) => {
609
+ const plannedRoutesDraft: MigrationPlannedRoute[] = scopedRoutes.map((scope) => {
594
610
  const seen = new Set<string>()
595
611
  const existing: MigrationIdClass[] = []
596
612
  for (const profile of scope.currentModels) {
@@ -614,17 +630,35 @@ export function buildMigrationPlan(input: BuildPlanInput): MigrationPlan {
614
630
  return { slot: scope.slot, route: scope.route, state: scope.state, action, fields: scope.fields, desired: scope.desired, existing }
615
631
  })
616
632
 
633
+ // ONE plan-time simulation — the SAME function apply executes — decides both
634
+ // the informed-consent id set and which legacy routes end up emptied. A
635
+ // legacy protocol route whose post-apply models map is empty carries no
636
+ // user content anymore: apply will whole-section unset it (never a
637
+ // `models: []` write) and delete its ledger key.
638
+ const simulation = buildRouteWriteStates({ routes: plannedRoutesDraft, idActions }, input.descriptor)
639
+ const managedByRoute: Record<string, string[]> = {}
640
+ for (const [route, state] of simulation.byRoute) {
641
+ managedByRoute[route] = Object.keys(state.managed).sort((a, b) => a.localeCompare(b))
642
+ }
643
+ const plannedRoutes = plannedRoutesDraft.map((planned) => {
644
+ if (planned.slot === 'chat' || planned.state === 'absent') return planned
645
+ const postModels = simulation.byRoute.get(planned.route)?.models
646
+ if (postModels !== undefined && postModels.size === 0) {
647
+ return { ...planned, action: 'unset' as MigrationAction }
648
+ }
649
+ return planned
650
+ })
651
+
617
652
  const pinnedSuggestions = new Set<string>()
618
- const reversibleTargets = targets.filter((id) => !grouping.slots.chat.includes(id))
619
- for (const id of reversibleTargets) pinnedSuggestions.add(id)
653
+ // Reversible targets: desired ids still sitting on a legacy protocol route.
654
+ for (const id of targets) pinnedSuggestions.add(id)
620
655
  for (const id of pinnedIds) pinnedSuggestions.add(id)
621
656
 
622
657
  // B6 informed-consent text — part of the hashed body: any edit to this notice
623
658
  // changes planHash and invalidates the old confirmCode/ack. The id list comes
624
- // from `managedIdsAfterApply`, the SAME simulation apply uses for the ledger,
625
- // so a user-modified `update` row or a move onto a different-valued target is
626
- // never advertised as managed.
627
- const managedByRoute = managedIdsAfterApply({ routes: plannedRoutes, idActions }, input.descriptor)
659
+ // from the single `buildRouteWriteStates` simulation above — the SAME engine
660
+ // apply uses for the ledger — so a user-modified `update` row or a move onto
661
+ // a different-valued target is never advertised as managed.
628
662
  // N2: no row may claim management on paper if the simulation shows apply
629
663
  // will not actually write/adopt that id. Normalise the per-id `managed`
630
664
  // flags to the simulated set so even the printed `[managed]` marker cannot
@@ -673,10 +707,7 @@ export function buildMigrationPlan(input: BuildPlanInput): MigrationPlan {
673
707
 
674
708
  function describeId(kind: MigrationIdKind, adopt: boolean): string {
675
709
  switch (kind) {
676
- case 'desired-chat': return 'official chat-completions target'
677
- case 'desired-msg': return 'official messages target (dedicated -msg route)'
678
- case 'desired-resp': return 'official responses target (dedicated -resp route)'
679
- case 'desired-google': return 'official google target'
710
+ case 'desired': return 'official desired id (single managed route)'
680
711
  case 'legacy-other-protocol': return adopt ? 'legacy id on the wrong protocol route' : 'legacy id kept in conservative mode'
681
712
  case 'unknown-retired': return adopt ? 'unknown/retired id, delete only if confirmed in plan' : 'unknown/retired id kept as user-owned'
682
713
  case 'user-extra': return 'user-written id, never auto-deleted'
@@ -731,7 +762,7 @@ export function formatMigrationPlan(plan: MigrationPlan): string {
731
762
  for (const route of plan.routes) {
732
763
  const fields = route.fields
733
764
  lines.push(` ${route.route} [${route.slot}/${route.state}] ${route.action.toUpperCase()}`)
734
- lines.push(` api=${fields.api} baseURL=${fields.baseURL} displayName=${fields.displayName} apiKeyEnv=${fields.apiKeyEnv}`)
765
+ lines.push(` displayName=${fields.displayName} apiKeyEnv=${fields.apiKeyEnv}${route.action === 'unset' ? ' (whole-route unset; fields not written)' : ''}`)
735
766
  lines.push(` desired (${route.desired.length}): ${route.desired.map((profile) => profile.id).join(', ') || '(none)'}`)
736
767
  if (route.existing.length > 0) {
737
768
  lines.push(` existing: ${route.existing.map((entry) => `${entry.id}=${entry.kind}/${entry.action}`).join(', ')}`)
@@ -908,6 +939,14 @@ function routeOps(
908
939
  ops.push({ op: 'set', path: ['providers', route, field], value: fields[field] })
909
940
  }
910
941
  }
942
+ // Catalog-reuse: strip legacy `api`/`baseURL` so the host reuses pi-ai's
943
+ // builtin catalog provider for this route.
944
+ for (const field of GO_LEGACY_ROUTE_FIELDS) {
945
+ const value = data?.[field]
946
+ if (value !== undefined && value !== '') {
947
+ ops.push({ op: 'unset', path: ['providers', route, field] })
948
+ }
949
+ }
911
950
  const sorted = [...models].sort((a, b) => a.id.localeCompare(b.id))
912
951
  const current = [...rawModels(desc, route)].sort((a, b) => a.id.localeCompare(b.id))
913
952
  if (current.length !== sorted.length || current.some((profile, index) => profileHash(profile) !== profileHash(sorted[index]))) {
@@ -1214,6 +1253,37 @@ export async function applyMigration(
1214
1253
  continue
1215
1254
  }
1216
1255
  const current = rawModels(desc, planned.route)
1256
+ // Emptied legacy protocol route (plan action `unset`): whole-section
1257
+ // unset + ledger key delete. Never a `models: []` write (§9.4), and no
1258
+ // ledger entry survives it (no managedByRoute entry → appliedManagedIds
1259
+ // mirrors only routes that still have a ledger, N3).
1260
+ if (planned.action === 'unset') {
1261
+ const section = rawRoute(desc, planned.route)
1262
+ if (section !== undefined) {
1263
+ try {
1264
+ await mutateWithRetry(deps, [{ op: 'unset', path: ['providers', planned.route] }])
1265
+ writtenRoutes.push(planned.route)
1266
+ } catch (err) {
1267
+ failure = `${planned.route}: settings mutate failed (${errorText(err)})`
1268
+ routesResult.push({ route: planned.route, status: 'failed', reason: errorText(err) })
1269
+ break
1270
+ }
1271
+ }
1272
+ const legacyKey = goOwnershipKey(planned.route, deps.keyFingerprint)
1273
+ try {
1274
+ await deps.ownershipStore.delete(legacyKey)
1275
+ } catch (err) {
1276
+ failure = `${planned.route}: ledger delete failed (${errorText(err)})`
1277
+ routesResult.push({ route: planned.route, status: 'failed', reason: errorText(err) })
1278
+ break
1279
+ }
1280
+ routesResult.push({
1281
+ route: planned.route,
1282
+ status: section !== undefined ? 'wrote' : 'skipped',
1283
+ ...(section !== undefined ? {} : { reason: 'legacy route superseded; section already absent (no settings write)' }),
1284
+ })
1285
+ continue
1286
+ }
1217
1287
  // Write only ops that actually change fields/models. keep/update/delete-no
1218
1288
  // rows leave the section byte-identical, so no mutate happens for them.
1219
1289
  const ops = routeOps(desc, planned.route, planned.fields, [...state.models.values()])
@@ -650,14 +650,16 @@ const CONFIRM_PROCEED = '执行迁移'
650
650
  const CONFIRM_CANCEL = '取消'
651
651
 
652
652
  /**
653
- * Slot summary INCLUDING the route field values (api/baseURL, review M8) —
654
- * the user approves the exact endpoints, not just route names.
653
+ * Slot summary INCLUDING the route field values (review M8) — with the
654
+ * catalog-reuse shape the written fields are displayName/apiKeyEnv only (the
655
+ * endpoint lives in pi-ai's builtin catalog; api/baseURL are stripped), plus
656
+ * an explicit marker for legacy routes this run will whole-section unset.
655
657
  */
656
658
  function slotSummary(plan: MigrationPlan): string {
657
659
  const slots = (['chat', 'msg', 'resp', 'google'] as GoRouteSlot[])
658
660
  .map((slot) => ({ slot, route: plan.routes.find((candidate) => candidate.slot === slot) }))
659
661
  .filter((item): item is { slot: GoRouteSlot; route: MigrationPlan['routes'][number] } => item.route !== undefined)
660
- .map((item) => `${item.slot}→${item.route.route} (${item.route.fields.api}, ${item.route.fields.baseURL})`)
662
+ .map((item) => `${item.slot}→${item.route.route} (${item.route.fields.displayName}, ${item.route.fields.apiKeyEnv}${item.route.action === 'unset' ? ', 整段 unset' : ''})`)
661
663
  return slots.length > 0 ? slots.join('、') : '(no route changes)'
662
664
  }
663
665