@aiwayds/dsh-model-sync 0.11.1 → 0.12.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 (45) hide show
  1. package/lib/index.d.ts +8 -0
  2. package/lib/index.js +90 -24
  3. package/lib/index.js.map +1 -1
  4. package/lib/opencode-go-diagnose.d.ts +43 -21
  5. package/lib/opencode-go-diagnose.js +87 -56
  6. package/lib/opencode-go-diagnose.js.map +1 -1
  7. package/lib/opencode-go-grouping.d.ts +4 -26
  8. package/lib/opencode-go-grouping.js +12 -68
  9. package/lib/opencode-go-grouping.js.map +1 -1
  10. package/lib/opencode-go-host-catalog.d.ts +42 -0
  11. package/lib/opencode-go-host-catalog.js +98 -0
  12. package/lib/opencode-go-host-catalog.js.map +1 -0
  13. package/lib/opencode-go-journal.d.ts +6 -2
  14. package/lib/opencode-go-journal.js +1 -1
  15. package/lib/opencode-go-journal.js.map +1 -1
  16. package/lib/opencode-go-migrate.d.ts +40 -5
  17. package/lib/opencode-go-migrate.js +313 -84
  18. package/lib/opencode-go-migrate.js.map +1 -1
  19. package/lib/opencode-go-migration.d.ts +43 -0
  20. package/lib/opencode-go-migration.js +91 -2
  21. package/lib/opencode-go-migration.js.map +1 -1
  22. package/lib/opencode-go-one-shot.d.ts +6 -0
  23. package/lib/opencode-go-one-shot.js +41 -4
  24. package/lib/opencode-go-one-shot.js.map +1 -1
  25. package/lib/opencode-go-planner.d.ts +39 -24
  26. package/lib/opencode-go-planner.js +275 -207
  27. package/lib/opencode-go-planner.js.map +1 -1
  28. package/lib/opencode-go-sync.d.ts +16 -3
  29. package/lib/opencode-go-sync.js +24 -0
  30. package/lib/opencode-go-sync.js.map +1 -1
  31. package/lib/opencode-go-writer.d.ts +17 -1
  32. package/lib/opencode-go-writer.js +111 -16
  33. package/lib/opencode-go-writer.js.map +1 -1
  34. package/package.json +2 -2
  35. package/src/index.ts +100 -25
  36. package/src/opencode-go-diagnose.ts +124 -70
  37. package/src/opencode-go-grouping.ts +14 -85
  38. package/src/opencode-go-host-catalog.ts +125 -0
  39. package/src/opencode-go-journal.ts +5 -3
  40. package/src/opencode-go-migrate.ts +352 -95
  41. package/src/opencode-go-migration.ts +116 -2
  42. package/src/opencode-go-one-shot.ts +49 -4
  43. package/src/opencode-go-planner.ts +293 -216
  44. package/src/opencode-go-sync.ts +40 -2
  45. package/src/opencode-go-writer.ts +127 -15
package/src/index.ts CHANGED
@@ -115,6 +115,13 @@ import {
115
115
  type UnclaimedMigrationRecord,
116
116
  } from './opencode-go-migration.ts'
117
117
  import { goOwnershipKey } from './opencode-go-planner.ts'
118
+ import {
119
+ ownWriteRecordUpdate,
120
+ } from './opencode-go-migration.ts'
121
+ import {
122
+ loadHostGoCatalogIds,
123
+ type HostCatalogLlmSeam,
124
+ } from './opencode-go-host-catalog.ts'
118
125
  import {
119
126
  applyMigration,
120
127
  buildMigrationPlanFromDeps,
@@ -149,6 +156,14 @@ export const GO_MIGRATION_REF_WRITER_SERVICE = 'goMigrationRefWriter'
149
156
  /** Public (unauthenticated) official catalog ids for id classification (design §14.2).
150
157
  * `undefined` ⇒ fail-closed `unclassified`. Tests inject an array/function. */
151
158
  export const GO_MIGRATION_PUBLIC_CATALOG_SERVICE = 'goMigrationPublicCatalog'
159
+ /**
160
+ * 0.12.1 seam: host runtime catalog ids for opencode-go (from the host llm
161
+ * adapter's in-memory catalog via `llm.discoverModels`). Tests inject an
162
+ * array, `null` (fail-closed shape) or an async function; production resolves
163
+ * through the llm seam at each call site so a host adapter swap is picked up
164
+ * live.
165
+ */
166
+ export const GO_HOST_CATALOG_SERVICE = 'goHostCatalog'
152
167
  /** Capability flag: when true, `--adopt` is refused and plan mode is adopt-disabled. */
153
168
  export const GO_MIGRATION_ADOPT_DISABLED_SERVICE = 'goMigrationAdoptDisabled'
154
169
  /** Optional override for the single-flight check (tests inject an in-flight mutex). */
@@ -319,10 +334,15 @@ interface ModelSyncConfigValue {
319
334
  }
320
335
  }
321
336
 
322
- /** The llm seam as this plugin needs it (overlay mode). */
337
+ /** The llm seam as this plugin needs it (overlay mode + 0.12.1 host catalog). */
323
338
  interface LlmSeam {
324
339
  listProviders?(): readonly { id: string }[]
325
340
  listModels?(provider: string): Promise<readonly { id: string }[]>
341
+ discoverModels?(
342
+ settingsNs: string,
343
+ request: { provider?: string; baseURL?: string; api?: string; apiKey?: string },
344
+ signal?: AbortSignal,
345
+ ): Promise<readonly { id: string }[]>
326
346
  }
327
347
 
328
348
  /** The catalog-refresh seam exposed by the patched dsh-llm-pi-ai adapter. */
@@ -563,7 +583,11 @@ export async function apply(ctx: Context, config: ModelSyncConfigValue): Promise
563
583
  }
564
584
  let record: MigrationRecord | undefined
565
585
  try {
566
- record = await store?.read()
586
+ // H4: strict status reads (the per-mutate second gate) use readStrict —
587
+ // a store error must reach the caller as a refusal, never as "no record".
588
+ record = opts.strict === true && store !== undefined && store.readStrict !== undefined
589
+ ? await store.readStrict()
590
+ : await store?.read()
567
591
  } catch (err) {
568
592
  if (opts.strict === true) throw err
569
593
  record = undefined // unreadable ⇒ conservative legacy detection
@@ -995,6 +1019,8 @@ export async function apply(ctx: Context, config: ModelSyncConfigValue): Promise
995
1019
  ownershipStore,
996
1020
  overrideStorer,
997
1021
  logger: ctx.logger as unknown as Logger,
1022
+ // 0.12.1: the host runtime catalog (fail-closed round when null).
1023
+ hostCatalogIds: await resolveHostCatalogIds(ctx),
998
1024
  // The explicit `adopt` command honours the master switch: disabled means
999
1025
  // zero writes (design §6.2.6). runGoSyncRound checks `enabled` first.
1000
1026
  config: options.adopt === true ? { ...value, adoptExisting: true } : value,
@@ -1012,32 +1038,32 @@ export async function apply(ctx: Context, config: ModelSyncConfigValue): Promise
1012
1038
  reloadMigration: () => loadMigrationStatus({ keyFingerprint, strict: true }),
1013
1039
  // §14.7.4: settings → ledger → fingerprint, all through the same
1014
1040
  // models-store queue; only successful own writes reach this callback.
1015
- onOwnWrite: async (route, managedIds) => {
1041
+ // H4: NO catch here. A strict read failure (or a read-only store) must
1042
+ // reach the writer's recordOwnWrite, which reports
1043
+ // settings-written-unaccounted and KEEPS the C2 write-ahead journal so
1044
+ // the next round's reconciliation re-commits the record — swallowing the
1045
+ // error here made recordOwnWrite report success and delete the journal,
1046
+ // leaving the gate drifted with no recovery (the old "self-heal" comment
1047
+ // was wrong: fingerprintHealed only fires on an identity MATCH, and this
1048
+ // write is exactly what changed the identity).
1049
+ onOwnWrite: async (route, managedIds, info) => {
1016
1050
  const store = migrationStore()
1017
- if (typeof store.write !== 'function') return // read-only injected store
1018
- let record: MigrationRecord | undefined
1019
- try {
1020
- record = await store.read()
1021
- } catch {
1022
- return // cannot merge safely; the next round's self-heal covers it
1051
+ if (typeof store.write !== 'function') {
1052
+ throw new Error('migration store is read-only; the migration record cannot be persisted')
1023
1053
  }
1024
- const goRoutes = Object.values(value.routes ?? {})
1054
+ const record = typeof store.readStrict === 'function'
1055
+ ? await store.readStrict()
1056
+ : await store.read()
1025
1057
  const liveDesc = rawSettings()?.describe().find((d) => d.ns === 'llm-pi-ai')
1026
- const sections = readGoProviderSections(liveDesc, goRoutes)
1027
- const appliedIdentityRoutes = record?.appliedIdentityRoutes ?? Object.keys(sections ?? {})
1028
- const appliedManagedIds = { ...(record?.appliedManagedIds ?? {}), [route]: [...managedIds].sort() }
1029
- // Same helper + route-set convention as loadMigrationStatus: a normal
1030
- // onboarding/own write must not look like a fingerprint drift next round.
1031
- const { identity, appliedFingerprint } = appliedFingerprintFieldsOf(
1032
- sections, record, appliedManagedIds,
1033
- )
1034
- await store.write({
1035
- ...(record ?? {}),
1036
- appliedIdentity: identity,
1037
- appliedIdentityRoutes,
1038
- appliedManagedIds,
1039
- appliedFingerprint,
1058
+ const next = ownWriteRecordUpdate({
1059
+ record,
1060
+ source: liveDesc,
1061
+ routes: Object.values(value.routes ?? {}),
1062
+ route,
1063
+ managedIds,
1064
+ unset: info?.unset === true,
1040
1065
  })
1066
+ await store.write(next)
1041
1067
  },
1042
1068
  })
1043
1069
  }
@@ -1095,6 +1121,29 @@ export async function apply(ctx: Context, config: ModelSyncConfigValue): Promise
1095
1121
  // -----------------------------------------------------------------------
1096
1122
  type MigrateEntries = readonly GoModelRecord[] | (() => Promise<readonly GoModelRecord[]> | readonly GoModelRecord[])
1097
1123
  type PublicCatalog = readonly string[] | (() => Promise<readonly string[]> | readonly string[])
1124
+ type HostCatalogSource = readonly string[] | null | (() => Promise<readonly string[] | null> | readonly string[] | null)
1125
+
1126
+ /**
1127
+ * 0.12.1: the host runtime catalog ids for opencode-go, read live from the
1128
+ * host llm adapter (`llm.discoverModels('llm-pi-ai', { provider })` — the
1129
+ * adapter answers from its in-memory installed catalog with no network and
1130
+ * no credential; that catalog is exactly what the host validates route
1131
+ * models against). `null` = unknown: every WRITE path fails closed on it,
1132
+ * the read-only diagnostic degrades. Test seam: GO_HOST_CATALOG_SERVICE.
1133
+ */
1134
+ const resolveHostCatalogIds = async (from: Context): Promise<readonly string[] | null> => {
1135
+ const injected = from.get(GO_HOST_CATALOG_SERVICE) as HostCatalogSource | undefined
1136
+ if (Array.isArray(injected)) return injected
1137
+ if (injected === null) return null
1138
+ if (typeof injected === 'function') return await injected()
1139
+ const llm = from.get('llm') as HostCatalogLlmSeam | undefined
1140
+ const result = await loadHostGoCatalogIds(llm)
1141
+ if (!result.ok) {
1142
+ from.logger.warn('model-sync: host-catalog-unavailable (%s): %s', result.reason, result.message)
1143
+ return null
1144
+ }
1145
+ return result.ids
1146
+ }
1098
1147
 
1099
1148
  /** Resolve the official listing through an injectable seam (tests: a fixture array). */
1100
1149
  const resolveMigrateEntries = async (
@@ -1166,6 +1215,19 @@ export async function apply(ctx: Context, config: ModelSyncConfigValue): Promise
1166
1215
  // status/rollback never need the official listing: no fetch, no extra I/O.
1167
1216
  const entries = needsEntries ? await resolveMigrateEntries(value, apiKey) : []
1168
1217
  const publicCatalogIds = needsEntries ? await resolvePublicCatalogIds(value, entries) : undefined
1218
+ // 0.12.1 (P0): plan/apply need the host runtime catalog (fail-closed
1219
+ // without it); status/rollback are read/restore-only and never resolve it.
1220
+ // `resolveHostCatalogIds` consults the GO_HOST_CATALOG_SERVICE test seam
1221
+ // and falls through to the REAL host llm adapter
1222
+ // (`llm.discoverModels('llm-pi-ai', { provider: 'opencode-go' })`) when no
1223
+ // seam is injected. There is NO fixture fallback onto the official
1224
+ // entries: a production ctx has no seam, and deriving the catalog from the
1225
+ // listing itself would silently re-open the 0.12.0 fault (writing ids the
1226
+ // running host does not know — incident migrate-go 20261129-114103).
1227
+ const hostCatalogIds = needsEntries ? await resolveHostCatalogIds(target) : undefined
1228
+ if (needsEntries && hostCatalogIds === null) {
1229
+ throw new Error('host runtime catalog unavailable (host-catalog-unavailable): 宿主 llm 目录不可读 — 为避免写入宿主不认识的模型 id,已拒绝规划/写入(fail-closed)')
1230
+ }
1169
1231
  const adoptDisabled = ctx.get(GO_MIGRATION_ADOPT_DISABLED_SERVICE) === true
1170
1232
  || settings === undefined || typeof settings.mutate !== 'function'
1171
1233
  return {
@@ -1175,6 +1237,7 @@ export async function apply(ctx: Context, config: ModelSyncConfigValue): Promise
1175
1237
  logger: target.logger as unknown as Logger,
1176
1238
  entries,
1177
1239
  publicCatalogIds,
1240
+ hostCatalogIds,
1178
1241
  routes: value.routes,
1179
1242
  ref: value.ref,
1180
1243
  keyFingerprint: fingerprintKey(typeof apiKey === 'string' ? apiKey.trim() : ''),
@@ -1382,6 +1445,9 @@ export async function apply(ctx: Context, config: ModelSyncConfigValue): Promise
1382
1445
  }),
1383
1446
  resolveEntries: (apiKey) => resolveMigrateEntries(value, apiKey),
1384
1447
  resolvePublicCatalogIds: (_apiKey, entries) => resolvePublicCatalogIds(value, entries),
1448
+ // 0.12.1: the one-shot aborts (zero writes) when the host runtime
1449
+ // catalog cannot be read — never fail open onto the full listing.
1450
+ resolveHostCatalogIds: () => resolveHostCatalogIds(target),
1385
1451
  resolveAsk: () => {
1386
1452
  try {
1387
1453
  return target.get('userQuestions') as AskServiceShape | undefined
@@ -1585,6 +1651,9 @@ export async function apply(ctx: Context, config: ModelSyncConfigValue): Promise
1585
1651
  // text carries the actionable "settings changed, next round
1586
1652
  // retries" guidance; no backoff is scheduled for it.
1587
1653
  || outcome.reason === 'settings-changed-during-sync'
1654
+ // 0.12.1: the host runtime catalog was unreadable — the round
1655
+ // failed closed (zero writes) and the user must see why.
1656
+ || outcome.reason === 'host-catalog-unavailable'
1588
1657
  // O1-minimal: failedRoutes (e.g. settings written but the ledger
1589
1658
  // failed) are a real failure even if other routes wrote. Callers
1590
1659
  // that only read `kind` must see `error`; the actionable reason
@@ -1636,7 +1705,13 @@ export async function apply(ctx: Context, config: ModelSyncConfigValue): Promise
1636
1705
  desc,
1637
1706
  'opencode-go',
1638
1707
  )
1639
- const report = await runGoDiagnostic({ apiKey, descriptor: desc })
1708
+ // 0.12.1: lag comparison uses the live host runtime catalog (null
1709
+ // tolerated — the diagnostic is read-only and degrades instead of
1710
+ // failing closed) and the RESOLVED go.routes (M2: custom chat
1711
+ // route names are diagnosed correctly).
1712
+ const { value: statusGoCfg } = readGoRuntimeConfig(config)
1713
+ const hostCatalogIds = await resolveHostCatalogIds(cmdCtx)
1714
+ const report = await runGoDiagnostic({ apiKey, descriptor: desc, routes: statusGoCfg.routes, hostCatalogIds })
1640
1715
  return { kind: 'success', text: `${ignored}${formatGoDiagnosticReport(report)}` } satisfies CommandResult
1641
1716
  } catch (error) {
1642
1717
  const message = error instanceof Error ? error.message : String(error)
@@ -1,6 +1,12 @@
1
1
  // P0 read-only diagnostic: compare the official opencode-go model set with
2
- // the current profile's opencode-go route configuration and produce a
3
- // structured report (added / missing / protocol ownership / entitlement).
2
+ // the current profile's single managed opencode-go route and produce a
3
+ // structured report (added / missing / superseded legacy routes).
4
+ //
5
+ // 0.12.0 single-route shape: the official listing is diffed against ONE
6
+ // managed route (the `chat` slot route); the three legacy protocol routes are
7
+ // listed separately with a superseded hint (sync unsets them when fully
8
+ // plugin-managed). There is no per-protocol grouping anymore — unknown
9
+ // protocols can no longer fail anything closed.
4
10
  //
5
11
  // Hard boundary: this module only READS a settings descriptor. It never calls
6
12
  // settings.mutate, never writes credentials, and never touches a profile file.
@@ -15,12 +21,7 @@ import {
15
21
  type GoAuthStatus,
16
22
  type GoSourceError,
17
23
  } from './opencode-go-source.ts'
18
- import {
19
- GO_SLOT_ROUTES,
20
- groupGoModelsByProtocol,
21
- type GoGroupingResult,
22
- type GoRouteSlot,
23
- } from './opencode-go-grouping.ts'
24
+ import { GO_SLOT_ROUTES } from './opencode-go-grouping.ts'
24
25
 
25
26
  /** Minimal settings-descriptor shape the diagnostic reads (no writer import). */
26
27
  export interface GoSettingsDescriptor {
@@ -29,23 +30,31 @@ export interface GoSettingsDescriptor {
29
30
 
30
31
  /** One route's currently configured model ids, read from the profile. */
31
32
  export interface GoRouteConfig {
32
- slot: GoRouteSlot
33
33
  route: string
34
34
  configuredIds: string[]
35
+ /** True for the single managed route (the official listing diffs against it). */
36
+ managed: boolean
35
37
  }
36
38
 
37
- /** The per-slot comparison in the report. */
38
- export interface GoSlotDiff {
39
- slot: GoRouteSlot
39
+ /** The comparison for one route in the report. */
40
+ export interface GoRouteDiff {
40
41
  route: string
41
- /** Ids the official entitled source places in this slot. */
42
+ /** Ids the official entitled source lists (managed route only; [] for legacy). */
42
43
  official: string[]
43
44
  /** Ids currently listed under this route in the profile. */
44
45
  configured: string[]
45
- /** Official ids absent from the profile. */
46
+ /** Official ids absent from the profile (managed route only). */
46
47
  added: string[]
47
- /** Profile ids absent from the official entitled set. */
48
+ /** Profile ids absent from the official entitled set (managed route only). */
48
49
  missing: string[]
50
+ /**
51
+ * 0.12.1: official ids the HOST runtime catalog does not know (managed route
52
+ * only). These are host-side lag, not a plugin problem — sync never writes
53
+ * them (needs-host-catalog) and they auto-join after a host upgrade.
54
+ */
55
+ hostCatalogLag: string[]
56
+ /** Legacy protocol route superseded by the single managed route. */
57
+ superseded?: boolean
49
58
  }
50
59
 
51
60
  /** Structured diagnostic report emitted by P0. */
@@ -56,15 +65,22 @@ export interface GoDiagnosticReport {
56
65
  keyFingerprint: string
57
66
  payloadHash?: string
58
67
  error?: GoSourceError
59
- routes: GoSlotDiff[]
60
- unassigned: GoGroupingResult['unassigned']
68
+ /** True when host runtime catalog ids were supplied (hostCatalogLag is meaningful). */
69
+ hostCatalogAvailable: boolean
70
+ /** First entry = the managed route diff; remaining = legacy routes found. */
71
+ routes: GoRouteDiff[]
61
72
  }
62
73
 
63
74
  /** Inputs to buildGoDiagnosticReport — all already-resolved (pure). */
64
75
  export interface BuildGoDiagnosticInput {
65
76
  source: GoSourceResult
66
- grouping: GoGroupingResult
67
77
  routes: readonly GoRouteConfig[]
78
+ /**
79
+ * Host runtime catalog ids for opencode-go. `undefined`/absent = unknown —
80
+ * no lag comparison is reported (the diagnostic is read-only, so unlike the
81
+ * write paths this degrades instead of failing closed).
82
+ */
83
+ hostCatalogIds?: readonly string[] | null
68
84
  generatedAt?: number
69
85
  }
70
86
 
@@ -76,15 +92,7 @@ function isRecord(value: unknown): value is Record<string, unknown> {
76
92
  return typeof value === 'object' && value !== null && !Array.isArray(value)
77
93
  }
78
94
 
79
- function slotFromRouteId(route: string): GoRouteSlot | undefined {
80
- if (route === GO_SLOT_ROUTES.chat) return 'chat'
81
- if (route === GO_SLOT_ROUTES.msg) return 'msg'
82
- if (route === GO_SLOT_ROUTES.resp) return 'resp'
83
- if (route === GO_SLOT_ROUTES.google) return 'google'
84
- return undefined
85
- }
86
-
87
- function toRouteConfig(slot: GoRouteSlot, route: string, providers: Record<string, unknown>): GoRouteConfig {
95
+ function toRouteConfig(route: string, managed: boolean, providers: Record<string, unknown>): GoRouteConfig {
88
96
  const routeData = providers[route]
89
97
  const models = isRecord(routeData) ? routeData.models : undefined
90
98
  const configuredIds = Array.isArray(models)
@@ -92,31 +100,31 @@ function toRouteConfig(slot: GoRouteSlot, route: string, providers: Record<strin
92
100
  .map((entry) => isRecord(entry) && typeof entry.id === 'string' ? entry.id : undefined)
93
101
  .filter((id): id is string => id !== undefined)
94
102
  : []
95
- return { slot, route, configuredIds }
103
+ return { route, configuredIds, managed }
96
104
  }
97
105
 
98
106
  /**
99
107
  * Read the profile's opencode-go route model ids from a settings descriptor.
100
- * The four default slots are always present (possibly empty); any additional
101
- * `opencode-go*` route carrying a recognizable slot suffix is included too.
102
- * This is a pure read — the descriptor is never modified.
108
+ * The single managed route (`chat` slot) is always present (possibly empty);
109
+ * the three legacy slot routes are listed only when they actually exist in
110
+ * the profile. This is a pure read — the descriptor is never modified.
111
+ *
112
+ * M2: `routes` accepts the resolved go.routes config so a custom chat route
113
+ * name is diagnosed correctly; defaults to the standard slot routes.
103
114
  */
104
- export function readGoRoutesFromDescriptor(desc: GoSettingsDescriptor | undefined): GoRouteConfig[] {
115
+ export function readGoRoutesFromDescriptor(
116
+ desc: GoSettingsDescriptor | undefined,
117
+ routes: Readonly<Record<string, string>> = GO_SLOT_ROUTES as unknown as Record<string, string>,
118
+ ): GoRouteConfig[] {
105
119
  const providers = desc?.user?.providers
106
120
  const table = isRecord(providers) ? providers : {}
107
- const configs: GoRouteConfig[] = []
108
- const seen = new Set<string>()
109
-
110
- for (const slot of ['chat', 'msg', 'resp', 'google'] as const) {
111
- const route = GO_SLOT_ROUTES[slot]
112
- configs.push(toRouteConfig(slot, route, table))
113
- seen.add(route)
114
- }
115
- for (const route of Object.keys(table)) {
116
- if (!route.startsWith('opencode-go') || seen.has(route)) continue
117
- const slot = slotFromRouteId(route)
118
- if (slot === undefined) continue
119
- configs.push(toRouteConfig(slot, route, table))
121
+ const chatRoute = routes.chat ?? GO_SLOT_ROUTES.chat
122
+ const configs: GoRouteConfig[] = [toRouteConfig(chatRoute, true, table)]
123
+ for (const slot of ['msg', 'resp', 'google'] as const) {
124
+ const route = routes[slot]
125
+ if (route === undefined || route === chatRoute) continue
126
+ if (!isRecord(table[route])) continue
127
+ configs.push(toRouteConfig(route, false, table))
120
128
  }
121
129
  return configs
122
130
  }
@@ -132,22 +140,45 @@ function missingFrom(left: readonly string[], right: readonly string[]): string[
132
140
 
133
141
  /**
134
142
  * Build the structured report. When the source read failed (no key, auth,
135
- entitlement, transport), the official side is empty and the diff is suppressed
136
- * — reporting every configured model as "missing" from a failed read would be
137
- * misleading. The failure is carried in authStatus / error instead.
143
+ * entitlement, transport), the official side is empty and the diff is
144
+ * suppressed — reporting every configured model as "missing" from a failed
145
+ * read would be misleading. The failure is carried in authStatus / error
146
+ * instead.
138
147
  */
139
148
  export function buildGoDiagnosticReport(input: BuildGoDiagnosticInput): GoDiagnosticReport {
140
149
  const available = input.source.ok
141
- const routes: GoSlotDiff[] = input.routes.map((config) => {
142
- const official = available ? (input.grouping.slots[config.slot] ?? []) : []
143
- const configured = config.configuredIds
150
+ const officialIds = available ? input.source.entries.map((entry) => entry.id) : []
151
+ // 0.12.1: official ids the host runtime catalog does not know (read-only
152
+ // comparison; when the catalog is unknown the lag list stays empty and the
153
+ // report says the comparison was skipped).
154
+ const hostCatalogIds = input.hostCatalogIds
155
+ const hostCatalogAvailable = Array.isArray(hostCatalogIds)
156
+ const hostSet = hostCatalogAvailable ? new Set(hostCatalogIds) : undefined
157
+ const hostCatalogLag = available && hostSet !== undefined
158
+ ? officialIds.filter((id) => !hostSet.has(id)).sort((a, b) => a.localeCompare(b))
159
+ : []
160
+ const routes: GoRouteDiff[] = input.routes.map((config) => {
161
+ if (config.managed) {
162
+ const configured = config.configuredIds
163
+ return {
164
+ route: config.route,
165
+ official: [...officialIds],
166
+ configured,
167
+ added: available ? missingFrom(officialIds, configured) : [],
168
+ missing: available ? missingFrom(configured, officialIds) : [],
169
+ hostCatalogLag,
170
+ }
171
+ }
172
+ // Legacy protocol route: no official placement anymore; listed for the
173
+ // superseded hint only.
144
174
  return {
145
- slot: config.slot,
146
175
  route: config.route,
147
- official,
148
- configured,
149
- added: available ? missingFrom(official, configured) : [],
150
- missing: available ? missingFrom(configured, official) : [],
176
+ official: [],
177
+ configured: config.configuredIds,
178
+ added: [],
179
+ missing: [],
180
+ hostCatalogLag: [],
181
+ superseded: true,
151
182
  }
152
183
  })
153
184
 
@@ -156,8 +187,8 @@ export function buildGoDiagnosticReport(input: BuildGoDiagnosticInput): GoDiagno
156
187
  generatedAt: input.generatedAt ?? Date.now(),
157
188
  authStatus: input.source.authStatus,
158
189
  keyFingerprint: input.source.keyFingerprint,
190
+ hostCatalogAvailable,
159
191
  routes,
160
- unassigned: available ? input.grouping.unassigned : [],
161
192
  }
162
193
  if (input.source.payloadHash !== undefined) report.payloadHash = input.source.payloadHash
163
194
  if (input.source.error !== undefined) report.error = input.source.error
@@ -170,21 +201,36 @@ export function formatGoDiagnosticReport(report: GoDiagnosticReport): string {
170
201
  'opencode-go official /v1/models diagnostic (read-only; no settings written)',
171
202
  ` authStatus: ${report.authStatus}`,
172
203
  ` keyFingerprint: ${report.keyFingerprint}`,
204
+ ` host catalog: ${report.hostCatalogAvailable ? 'available (lag comparison done)' : 'UNAVAILABLE — 宿主运行时目录未知,未做滞后对比'}`,
173
205
  ]
174
206
  if (report.payloadHash !== undefined) lines.push(` payloadHash: ${report.payloadHash}`)
175
207
  if (report.error !== undefined) {
176
208
  lines.push(` status: ${report.error.kind}${report.error.status !== undefined ? ` (HTTP ${report.error.status})` : ''}`)
177
209
  lines.push(` reason: ${report.error.message}`)
178
210
  }
179
- for (const slot of report.routes) {
211
+ for (const route of report.routes) {
212
+ if (route.superseded === true) {
213
+ lines.push(
214
+ ` ${route.route} [legacy/superseded]: configured ${route.configured.length}`
215
+ + ` (${route.configured.join(', ') || 'none'})`
216
+ + ' — superseded by the single managed route; sync unsets it when fully plugin-managed',
217
+ )
218
+ continue
219
+ }
180
220
  lines.push(
181
- ` ${slot.route} [${slot.slot}]: official ${slot.official.length}, configured ${slot.configured.length}`
182
- + `; +${slot.added.join(', +') || 'none'}`
183
- + `; -${slot.missing.join(', -') || 'none'}`,
221
+ ` ${route.route} [managed]: official ${route.official.length}, configured ${route.configured.length}`
222
+ + `; +${route.added.join(', +') || 'none'}`
223
+ + `; -${route.missing.join(', -') || 'none'}`,
184
224
  )
185
- }
186
- if (report.unassigned.length > 0) {
187
- lines.push(` unassigned: ${report.unassigned.map((u) => `${u.id} (${u.reason})`).join(', ')}`)
225
+ // 0.12.1: official-but-not-in-host-catalog is HOST-SIDE lag, deliberately
226
+ // listed apart from the configured diff — sync keeps these out of the
227
+ // route (needs-host-catalog) and they auto-join after a host upgrade.
228
+ if (route.hostCatalogLag.length > 0) {
229
+ lines.push(
230
+ ` host-catalog lag: ${route.hostCatalogLag.join(', ')}`
231
+ + ' — 官方 listing 有、宿主内置目录没有(宿主侧滞后,非本插件问题);sync 不会写入,宿主升级后自动纳入',
232
+ )
233
+ }
188
234
  }
189
235
  return lines.join('\n')
190
236
  }
@@ -197,16 +243,20 @@ export function formatGoDiagnosticReport(report: GoDiagnosticReport): string {
197
243
  export interface RunGoDiagnosticOptions {
198
244
  apiKey?: string
199
245
  descriptor?: GoSettingsDescriptor | undefined
246
+ /** M2: resolved go.routes config (custom chat route names diagnose correctly). */
247
+ routes?: Readonly<Record<string, string>>
200
248
  url?: string
201
249
  timeoutMs?: number
202
250
  fetchImpl?: GoFetchLike
251
+ /** Host runtime catalog ids; absent/null = unknown (lag comparison skipped). */
252
+ hostCatalogIds?: readonly string[] | null
203
253
  generatedAt?: number
204
254
  }
205
255
 
206
256
  /**
207
- * Run one read-only diagnostic: fetch official models, group by protocol,
208
- * read the profile's route config, and return the structured report.
209
- * Pass `fetchImpl` in tests so no network is ever touched.
257
+ * Run one read-only diagnostic: fetch official models, read the profile's
258
+ * route config, and return the structured report. Pass `fetchImpl` in tests
259
+ * so no network is ever touched.
210
260
  */
211
261
  export async function runGoDiagnostic(options: RunGoDiagnosticOptions = {}): Promise<GoDiagnosticReport> {
212
262
  const source = await fetchGoOfficialModels({
@@ -216,7 +266,11 @@ export async function runGoDiagnostic(options: RunGoDiagnosticOptions = {}): Pro
216
266
  fetchImpl: options.fetchImpl,
217
267
  observedAt: options.generatedAt,
218
268
  })
219
- const grouping = groupGoModelsByProtocol(source.entries)
220
- const routes = readGoRoutesFromDescriptor(options.descriptor)
221
- return buildGoDiagnosticReport({ source, grouping, routes, generatedAt: options.generatedAt })
269
+ const routes = readGoRoutesFromDescriptor(options.descriptor, options.routes)
270
+ return buildGoDiagnosticReport({
271
+ source,
272
+ routes,
273
+ hostCatalogIds: options.hostCatalogIds,
274
+ generatedAt: options.generatedAt,
275
+ })
222
276
  }
@@ -1,97 +1,26 @@
1
- // P0 protocol grouping: official api-dictionary keys → route slots.
1
+ // Route topology for the opencode-go single-route (catalog-reuse) write shape.
2
2
  //
3
- // Pure logic (07-design.md §6.2.3). P0 uses it for the diagnostic's protocol
4
- // ownership column; P1 will reuse it for route planning. No settings/IO here.
5
-
6
- import type { GoModelRecord } from './opencode-go-source.ts'
3
+ // 0.12.0 collapsed the four protocol routes into ONE managed route: the host
4
+ // (dsh-llm-pi-ai) only reuses pi-ai's builtin catalog provider when a route
5
+ // carries NO `api` field, and pi-ai 1.6.0's opencode-go catalog entries each
6
+ // carry their own per-protocol baseUrl — so any baseURL written on the single
7
+ // route would point at the wrong endpoint. The plugin therefore manages only
8
+ // the `chat` route and treats the three old protocol routes as legacy cleanup
9
+ // targets.
10
+ //
11
+ // Pure constants only (07-design.md §6.2.2 as revised). No settings/IO here.
7
12
 
8
- /** The four route slots of the go topology (design §6.2.2). */
13
+ /** The route slots of the go topology. `chat` is the only managed route; the
14
+ * other three are legacy cleanup targets kept for `go.routes` compat. */
9
15
  export type GoRouteSlot = 'chat' | 'msg' | 'resp' | 'google'
10
16
 
11
17
  export const GO_ROUTE_SLOTS: readonly GoRouteSlot[] = ['chat', 'msg', 'resp', 'google']
12
18
 
13
- /** Default route id per slot (design §6.2.6). */
19
+ /** Default route id per slot (design §6.2.6). The `chat` id names the single
20
+ * managed route; msg/resp/google name the legacy routes sync cleans up. */
14
21
  export const GO_SLOT_ROUTES: Readonly<Record<GoRouteSlot, string>> = {
15
22
  chat: 'opencode-go',
16
23
  msg: 'opencode-go-msg',
17
24
  resp: 'opencode-go-resp',
18
25
  google: 'opencode-go-google',
19
26
  }
20
-
21
- /** Official protocol names this plugin knows how to place. */
22
- export const GO_KNOWN_PROTOCOLS: ReadonlySet<string> = new Set([
23
- 'chat-completions',
24
- 'messages',
25
- 'responses',
26
- 'interactions',
27
- 'generate-content',
28
- ])
29
-
30
- export interface GoUnassignedModel {
31
- id: string
32
- protocols: string[]
33
- reason: 'unsupported-protocol' | 'unknown-protocol'
34
- }
35
-
36
- export interface GoGroupingResult {
37
- slots: Record<GoRouteSlot, string[]>
38
- /** Models that must not be written anywhere, with the reason why. */
39
- unassigned: GoUnassignedModel[]
40
- }
41
-
42
- /** Map an official protocol key to a route slot. */
43
- export function slotForProtocol(protocol: string): GoRouteSlot | undefined {
44
- switch (protocol) {
45
- case 'chat-completions': return 'chat'
46
- case 'messages': return 'msg'
47
- case 'responses': return 'resp'
48
- case 'interactions':
49
- case 'generate-content': return 'google'
50
- default: return undefined
51
- }
52
- }
53
-
54
- /**
55
- * Group official model ids by protocol (design §6.2.3):
56
- * - chat-completions present → chat (wins over any other protocol)
57
- * - exactly {messages} → msg; exactly {responses} → resp
58
- * - subset of {interactions, generate-content} → google
59
- * - multiple non-chat protocols → recommended_api breaks the tie
60
- * - empty / unknown / otherwise unsupported → unassigned (reported, never written)
61
- */
62
- export function groupGoModelsByProtocol(entries: readonly GoModelRecord[]): GoGroupingResult {
63
- const slots: Record<GoRouteSlot, string[]> = { chat: [], msg: [], resp: [], google: [] }
64
- const unassigned: GoUnassignedModel[] = []
65
-
66
- for (const entry of entries) {
67
- const protocols = entry.protocols
68
- const unknown = protocols.filter((protocol) => !GO_KNOWN_PROTOCOLS.has(protocol))
69
- if (unknown.length > 0) {
70
- unassigned.push({ id: entry.id, protocols: [...protocols], reason: 'unknown-protocol' })
71
- continue
72
- }
73
-
74
- let slot: GoRouteSlot | undefined
75
- if (protocols.length === 0) {
76
- // no placement
77
- } else if (protocols.includes('chat-completions')) {
78
- slot = 'chat'
79
- } else if (protocols.length === 1 && protocols[0] === 'messages') {
80
- slot = 'msg'
81
- } else if (protocols.length === 1 && protocols[0] === 'responses') {
82
- slot = 'resp'
83
- } else if (protocols.every((p) => p === 'interactions' || p === 'generate-content')) {
84
- slot = 'google'
85
- } else if (protocols.length > 1 && entry.recommendedProtocol !== undefined) {
86
- slot = slotForProtocol(entry.recommendedProtocol)
87
- }
88
-
89
- if (slot === undefined) {
90
- unassigned.push({ id: entry.id, protocols: [...protocols], reason: 'unsupported-protocol' })
91
- continue
92
- }
93
- slots[slot].push(entry.id)
94
- }
95
-
96
- return { slots, unassigned }
97
- }