@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
@@ -7,106 +7,63 @@
7
7
  // here is a pure function of its inputs so it can be exercised with offline
8
8
  // fixtures only.
9
9
  //
10
- // Design refs: §2.1/§6.2.2 (route fields + msg baseURL normalization),
11
- // §6.2.3 (grouping), §6.2.4 (ownership-aware merge), §6.2.5 (route fields),
12
- // §9.2-9.4 (keep the name, conflicts, empty routes), ADR-004 (ledger keyed
13
- // by keyFingerprint), ADR-005 (deletion gates). F25 is intentionally absent:
14
- // report 19 proved the host injects x-opencode-session, so no special header
15
- // handling belongs in the plan.
10
+ // 0.12.0 single-route (catalog-reuse) shape: the host only reuses pi-ai's
11
+ // builtin catalog provider when a route carries no `api` field, and pi-ai
12
+ // 1.6.0's opencode-go catalog gives every model its own per-protocol baseUrl —
13
+ // so a managed route must never carry `api`/`baseURL`. The plan therefore
14
+ // writes ONE route (the `chat` slot route) holding ALL official entries, and
15
+ // plans cleanup for the three legacy protocol routes: unset when fully
16
+ // plugin-managed, keep+warn when they hold user content. Report 19's per-slot
17
+ // api/baseURL tables are gone with the topology they described.
16
18
 
17
19
  import { createHash } from 'node:crypto'
18
20
  import type { SettingsModelProfile } from './translate.ts'
19
21
  import type { GoModelRecord } from './opencode-go-source.ts'
20
22
  import { deriveKeyRef } from './route-credential.ts'
23
+ import { HOST_CATALOG_PROVIDER } from './opencode-go-host-catalog.ts'
21
24
  import {
22
25
  GO_SLOT_ROUTES,
23
- groupGoModelsByProtocol,
24
26
  type GoRouteSlot,
25
27
  } from './opencode-go-grouping.ts'
26
28
 
27
29
  // ---------------------------------------------------------------------------
28
- // Static route-field plan (design §2.1 / §6.2.2, confirmed by report 19)
30
+ // Static route-field plan (0.12.0 catalog-reuse shape)
29
31
  // ---------------------------------------------------------------------------
30
32
 
31
- /** Host `api` value per slot (llm-pi-ai PROTOCOLS, report 19 §1). */
32
- export const GO_API_BY_SLOT: Readonly<Record<GoRouteSlot, string>> = {
33
- chat: 'openai-completions',
34
- msg: 'anthropic-messages',
35
- resp: 'openai-responses',
36
- google: 'google-generative-ai',
37
- }
38
-
39
- /** The only display field the host uses to group providers (F22/13). */
40
- export const GO_DISPLAY_NAME_BY_SLOT: Readonly<Record<GoRouteSlot, string>> = {
41
- chat: 'OpenCode Go',
42
- msg: 'OpenCode Go · msg',
43
- resp: 'OpenCode Go · resp',
44
- google: 'OpenCode Go · google',
45
- }
46
-
47
33
  /**
48
- * Fallback host baseURLs — the values report 19 confirmed end-to-end. Normally
49
- * the baseURL comes from the official payload (§6.2.2); these are used only
50
- * when a record carries no per-protocol `base_url`.
34
+ * Route fields a managed route must carry. `api`/`baseURL` are deliberately
35
+ * ABSENT: writing them makes the host build the provider from the bare
36
+ * PROTOCOLS implementation (missing `x-opencode-session` header → HTTP 400)
37
+ * instead of the pi-ai builtin catalog provider.
51
38
  */
52
- export const GO_BASE_URL_BY_SLOT: Readonly<Record<GoRouteSlot, string>> = {
53
- chat: 'https://opencode.ai/inference/go/openai/v1',
54
- msg: 'https://opencode.ai/inference/go/anthropic',
55
- resp: 'https://opencode.ai/inference/go/openai/v1',
56
- google: 'https://opencode.ai/inference/go/google/v1beta',
39
+ export interface GoPlannedRouteFields {
40
+ displayName: string
41
+ apiKeyEnv: string
57
42
  }
58
43
 
59
- /** Official protocol keys that back each slot (§6.2.2 table). */
60
- export const GO_PROTOCOLS_BY_SLOT: Readonly<Record<GoRouteSlot, readonly string[]>> = {
61
- chat: ['chat-completions'],
62
- msg: ['messages'],
63
- resp: ['responses'],
64
- google: ['interactions', 'generate-content'],
65
- }
44
+ /** The display name planned for the single managed route (F22/13). */
45
+ export const GO_DISPLAY_NAME = 'OpenCode Go'
66
46
 
67
47
  /**
68
- * Normalize an official `base_url` for host use. Only `msg` changes: pi-ai
69
- * calls `beta.messages.create` and appends `/v1/messages?beta=true`, so the
70
- * trailing `/v1` must be stripped (ADR-003 / report 19 negative control).
48
+ * Legacy route fields the writer must strip from the managed route (and that
49
+ * old 0.11.x routes carry). They are never part of a written plan.
71
50
  */
72
- export function normalizeGoBaseUrl(raw: string, slot: GoRouteSlot): string {
73
- const trimmed = raw.replace(/\/+$/, '')
74
- if (slot === 'msg' && trimmed.endsWith('/v1')) return trimmed.slice(0, -3)
75
- return trimmed
76
- }
77
-
78
- export interface GoPlannedRouteFields {
79
- api: string
80
- baseURL: string
81
- displayName: string
82
- apiKeyEnv: string
83
- }
51
+ export const GO_LEGACY_ROUTE_FIELDS = ['api', 'baseURL'] as const
84
52
 
85
53
  /**
86
- * Build the route fields for a slot from the payload's per-protocol base_url.
54
+ * Build the planned route fields for the single managed route. `entries` is
55
+ * kept in the signature for symmetry with the migration caller (and future
56
+ * payload-driven fields); with the catalog-reuse shape the fields no longer
57
+ * depend on the payload — the endpoint lives in pi-ai's builtin catalog.
87
58
  * `ref` defaults to the P0-derived `OPENCODE_GO_API_KEY`.
88
59
  */
89
60
  export function planGoRouteFields(
90
- slot: GoRouteSlot,
91
61
  entries: readonly GoModelRecord[],
92
62
  ref: string = deriveKeyRef('opencode-go'),
93
63
  ): GoPlannedRouteFields {
94
- const protocols = GO_PROTOCOLS_BY_SLOT[slot]
95
- let raw: string | undefined
96
- for (const entry of entries) {
97
- for (const protocol of protocols) {
98
- const base = entry.baseUrls[protocol]
99
- if (base !== undefined && base.length > 0) {
100
- raw = base
101
- break
102
- }
103
- }
104
- if (raw !== undefined) break
105
- }
64
+ void entries
106
65
  return {
107
- api: GO_API_BY_SLOT[slot],
108
- baseURL: raw !== undefined ? normalizeGoBaseUrl(raw, slot) : GO_BASE_URL_BY_SLOT[slot],
109
- displayName: GO_DISPLAY_NAME_BY_SLOT[slot],
66
+ displayName: GO_DISPLAY_NAME,
110
67
  apiKeyEnv: ref,
111
68
  }
112
69
  }
@@ -196,6 +153,12 @@ export interface GoRouteState {
196
153
  models: readonly SettingsModelProfile[]
197
154
  /** Ids covered by a non-empty modelOverrides key on this route. */
198
155
  overrideIds?: readonly string[]
156
+ /**
157
+ * M1: section keys outside the plugin's known field set (headers, custom
158
+ * user fields, …). A legacy route carrying any of these holds user content
159
+ * the whole-route unset would destroy, so it is never "fully managed".
160
+ */
161
+ unknownKeys?: readonly string[]
199
162
  }
200
163
 
201
164
  // ---------------------------------------------------------------------------
@@ -205,7 +168,7 @@ export interface GoRouteState {
205
168
  export interface GoRouteConflict {
206
169
  slot: GoRouteSlot
207
170
  route: string
208
- field: 'api' | 'baseURL' | 'apiKeyEnv'
171
+ field: 'apiKeyEnv'
209
172
  expected: string
210
173
  actual: string
211
174
  reason: string
@@ -215,7 +178,7 @@ export type GoPlanReportLevel = 'info' | 'warn' | 'error'
215
178
 
216
179
  export interface GoPlanReportEntry {
217
180
  level: GoPlanReportLevel
218
- /** Stable machine code (e.g. route-conflict, kept-user-owned, unknown-protocol). */
181
+ /** Stable machine code (e.g. route-conflict, kept-user-owned, legacy-fields-strip). */
219
182
  code: string
220
183
  route?: string
221
184
  slot?: GoRouteSlot
@@ -229,9 +192,9 @@ export interface GoPlannedRoute {
229
192
  fields: GoPlannedRouteFields
230
193
  /** Complete merged models array, sorted by id (never an empty write — see unset/skip). */
231
194
  models: SettingsModelProfile[]
232
- /** Empty and fully plugin-managed: caller should unset providers.<route>. */
195
+ /** Empty and fully plugin-managed (or superseded legacy): caller should unset providers.<route>. */
233
196
  unset: boolean
234
- /** Conflict, empty main route, or empty route with user content: write nothing. */
197
+ /** Conflict, empty main route, or legacy route with user content: write nothing. */
235
198
  skip: boolean
236
199
  }
237
200
 
@@ -257,6 +220,14 @@ export interface GoPlannerOptions {
257
220
  /** sha256(key) first 16 hex from the source result; '-' when no key. */
258
221
  keyFingerprint: string
259
222
  entries: readonly GoModelRecord[]
223
+ /**
224
+ * Host runtime catalog ids for opencode-go (0.12.1). `undefined` keeps the
225
+ * 0.12.0 behavior (every official entry is desired); an array intersects the
226
+ * desired set with it — ids the host catalog does not know are NOT written
227
+ * (they would make the host reject the whole mutate, fail-closed) and are
228
+ * reported as a single `needs-host-catalog` info line instead.
229
+ */
230
+ hostCatalogIds?: readonly string[]
260
231
  /** Current state of the go routes, keyed by route id. */
261
232
  currentRoutes: Readonly<Record<string, GoRouteState>>
262
233
  ownership: GoOwnershipLedger
@@ -287,7 +258,7 @@ export function profileHash(profile: SettingsModelProfile): string {
287
258
  return createHash('sha256').update(JSON.stringify(canonicalize(profile))).digest('hex')
288
259
  }
289
260
 
290
- const OWNERSHIP_FIELDS = ['api', 'baseURL', 'apiKeyEnv'] as const
261
+ const OWNERSHIP_FIELDS = ['apiKeyEnv'] as const
291
262
 
292
263
  /** A current route conflicts only when a field is explicitly set to a different value. */
293
264
  function detectConflict(
@@ -328,12 +299,16 @@ function ownedFieldsMatch(
328
299
  /**
329
300
  * Build the write plan. Pure: identical inputs always produce an identical
330
301
  * plan (report/order included). No mutation of `options` or its nested values.
302
+ *
303
+ * Topology (0.12.0): ONE managed route (the `chat` slot route) receives ALL
304
+ * official entries; the three legacy protocol routes (msg/resp/google) are
305
+ * cleanup targets — unset when fully plugin-managed, kept with a warn when
306
+ * they hold user content.
331
307
  */
332
308
  export function planGoRoutes(options: GoPlannerOptions): GoPlanResult {
333
309
  const ref = options.ref ?? deriveKeyRef('opencode-go')
334
310
  const routes: Record<GoRouteSlot, string> = { ...GO_SLOT_ROUTES, ...(options.routes ?? {}) }
335
311
  const pinned = new Set(options.pinnedModels ?? [])
336
- const grouping = groupGoModelsByProtocol(options.entries)
337
312
  const report: GoPlanReportEntry[] = []
338
313
  const conflicts: GoRouteConflict[] = []
339
314
  const plannedRoutes: GoPlannedRoute[] = []
@@ -341,164 +316,266 @@ export function planGoRoutes(options: GoPlannerOptions): GoPlanResult {
341
316
  const nextOwnership: Record<string, GoOwnershipEntry> = { ...options.ownership }
342
317
  const desiredByRoute: Record<string, SettingsModelProfile[]> = {}
343
318
 
344
- // Unknown / otherwise unsupported protocols are fail-closed: reported, never
345
- // written (design §6.2.3, V1).
346
- for (const unassigned of grouping.unassigned) {
319
+ const entryById = new Map(options.entries.map((entry) => [entry.id, entry]))
320
+ // 0.12.1 catalog-intersection: ids the host runtime catalog does not know
321
+ // are NEVER desired — the host validates every route model id against its
322
+ // in-memory pi-ai catalog and rejects the whole mutate on one unknown id
323
+ // (fail-closed; incident migrate-go 20261129-114103: beam-free). The full
324
+ // official entry set stays in `entryById` for mapping/reports; the filtered
325
+ // ids are surfaced as one `needs-host-catalog` info line.
326
+ //
327
+ // P1-1 scope: that validation exists ONLY for the route that reuses the
328
+ // builtin catalog — the one NAMED after the catalog provider id
329
+ // (`go.routes.chat === 'opencode-go'`, the default). A custom go.routes.chat
330
+ // name keeps its own api/baseURL (it does not reuse any catalog), so the
331
+ // host never validates its ids against the runtime catalog: the whole
332
+ // restriction (filter, lag report, kept-host-unknown warnings) is off for it.
333
+ const hostSet = options.hostCatalogIds === undefined || routes.chat !== HOST_CATALOG_PROVIDER
334
+ ? undefined
335
+ : new Set(options.hostCatalogIds)
336
+ const lagIds = hostSet === undefined
337
+ ? []
338
+ : options.entries.map((entry) => entry.id).filter((id) => !hostSet.has(id)).sort((a, b) => a.localeCompare(b))
339
+ if (lagIds.length > 0) {
347
340
  report.push({
348
- level: 'warn',
349
- code: unassigned.reason,
350
- id: unassigned.id,
351
- message: `model ${unassigned.id} not assigned (${unassigned.protocols.join(',') || 'no protocols'})`,
341
+ level: 'info',
342
+ code: 'needs-host-catalog',
343
+ route: routes.chat,
344
+ slot: 'chat',
345
+ message: `host catalog lag: ${lagIds.join(', ')} not written — 官方 listing 有、宿主内置目录没有(宿主侧滞后,非本插件问题);宿主升级后 sync 自动纳入`,
352
346
  })
353
347
  }
354
-
355
- const entryById = new Map(options.entries.map((entry) => [entry.id, entry]))
356
-
357
- for (const slot of ['chat', 'msg', 'resp', 'google'] as const) {
358
- const desiredIds = grouping.slots[slot] ?? []
359
- const route = routes[slot]
360
- const current = options.currentRoutes[route]
361
- const ledgerKey = goOwnershipKey(route, options.keyFingerprint)
362
- const owned = options.ownership[ledgerKey]
363
- desiredByRoute[route] = []
364
-
365
- // Google slot is conditional and default-off (design §2.1): materialize it
366
- // only when it has members, or when there is a previous ledger to clean up.
367
- if (slot === 'google' && desiredIds.length === 0 && owned === undefined) continue
368
-
369
- const slotEntries = desiredIds
370
- .map((id) => entryById.get(id))
371
- .filter((entry): entry is GoModelRecord => entry !== undefined)
372
- const fields = planGoRouteFields(slot, slotEntries, ref)
373
-
374
- // Empty group: never produce a `models: []` write (§9.4 / A9). Unset a
375
- // fully plugin-managed route, otherwise skip (keeping the route as-is) and
376
- // report. A slot with no route at all is not planned at all.
377
- if (desiredIds.length === 0) {
378
- const currentModels = current?.models ?? []
379
- if (current === undefined || !current.exists) continue
380
- if (slot === 'chat') {
381
- // §9.4: an empty main route after a 200 is an upstream anomaly — keep
382
- // last-good, write nothing.
383
- plannedRoutes.push({ slot, route, fields, models: [...currentModels], unset: false, skip: true })
384
- report.push({ level: 'warn', code: 'upstream-empty', route, slot, message: 'main route has no members; kept last-good, no write' })
385
- continue
386
- }
387
- const managed = owned?.managed ?? {}
388
- const fullyManaged = owned !== undefined
389
- && currentModels.length > 0
390
- && currentModels.every((model) => {
391
- const record = managed[model.id]
392
- return record !== undefined && record.hash === profileHash(model)
393
- })
394
- && ownedFieldsMatch(owned, fields)
395
- if (fullyManaged) {
396
- plannedRoutes.push({ slot, route, fields, models: [], unset: true, skip: false })
397
- unsetRoutes.push(route)
398
- report.push({ level: 'info', code: 'unset-route', route, slot, message: `route ${route} is empty and fully plugin-managed; unset` })
399
- delete nextOwnership[ledgerKey]
400
- } else {
401
- plannedRoutes.push({ slot, route, fields, models: [...currentModels], unset: false, skip: true })
402
- if (currentModels.length > 0) {
403
- report.push({ level: 'warn', code: 'route-empty-has-user-content', route, slot, message: `route ${route} is empty but has user content; kept, no empty write` })
404
- }
405
- }
406
- continue
348
+ // Single-route desired set: every official entry the host catalog knows, in
349
+ // stable id order (0.12.0 behavior when no host catalog was supplied).
350
+ const desiredIds = [...entryById.keys()]
351
+ .filter((id) => hostSet === undefined || hostSet.has(id))
352
+ .sort((a, b) => a.localeCompare(b))
353
+
354
+ // --- The single managed route (chat slot) --------------------------------
355
+ const managedSlot: GoRouteSlot = 'chat'
356
+ const managedRoute = routes[managedSlot]
357
+ const current = options.currentRoutes[managedRoute]
358
+ const ledgerKey = goOwnershipKey(managedRoute, options.keyFingerprint)
359
+ const owned = options.ownership[ledgerKey]
360
+ const fields = planGoRouteFields(options.entries, ref)
361
+ desiredByRoute[managedRoute] = []
362
+ // H2: the main route's field conflict, hoisted so the legacy cleanup below
363
+ // can defer while the managed route is not writable.
364
+ let conflictOnMainRoute: GoRouteConflict | undefined
365
+
366
+ if (desiredIds.length === 0) {
367
+ const currentModels = current?.models ?? []
368
+ if (current !== undefined && current.exists) {
369
+ // §9.4: an empty main route after a 200 is an upstream anomaly — keep
370
+ // last-good, write nothing.
371
+ plannedRoutes.push({ slot: managedSlot, route: managedRoute, fields, models: [...currentModels], unset: false, skip: true })
372
+ report.push({ level: 'warn', code: 'upstream-empty', route: managedRoute, slot: managedSlot, message: 'main route has no members; kept last-good, no write' })
407
373
  }
408
-
409
- const conflict = detectConflict(slot, route, fields, current)
374
+ } else {
375
+ const conflict = detectConflict(managedSlot, managedRoute, fields, current)
410
376
  if (conflict !== undefined) {
411
377
  conflicts.push(conflict)
378
+ conflictOnMainRoute = conflict
412
379
  report.push({
413
380
  level: 'error',
414
381
  code: 'route-conflict',
415
- route,
416
- slot,
417
- message: `${route}.${conflict.field} is ${conflict.actual}, expected ${conflict.expected}`,
382
+ route: managedRoute,
383
+ slot: managedSlot,
384
+ message: `${managedRoute}.${conflict.field} is ${conflict.actual}, expected ${conflict.expected}`,
418
385
  })
419
- continue
420
- }
386
+ } else {
387
+ const desiredById = new Map<string, SettingsModelProfile>()
388
+ for (const id of desiredIds) {
389
+ const entry = entryById.get(id)
390
+ if (entry !== undefined) desiredById.set(id, mapGoModelToProfile(entry))
391
+ }
392
+ desiredByRoute[managedRoute] = [...desiredById.values()]
393
+
394
+ // Catalog-reuse strip notice: a route still carrying the old 0.11.x
395
+ // `api`/`baseURL` fields gets them unset this round (the writer emits
396
+ // the ops; this line explains why in the report). H3 scope: only the
397
+ // builtin catalog provider route may lose api/baseURL — catalog-reuse
398
+ // only exists for it. A custom go.routes.chat name (or a kept legacy
399
+ // custom route) NEEDS api/baseURL to be servable, so it is never
400
+ // stripped (empty-string fields are still garbage the host rejects and
401
+ // are stripped unconditionally by the writer).
402
+ if (managedRoute === HOST_CATALOG_PROVIDER && current !== undefined && current.exists
403
+ && GO_LEGACY_ROUTE_FIELDS.some((field) => current[field] !== undefined)) {
404
+ report.push({
405
+ level: 'info',
406
+ code: 'legacy-fields-strip',
407
+ route: managedRoute,
408
+ slot: managedSlot,
409
+ message: `route ${managedRoute} carries legacy api/baseURL fields; unsetting them so the host reuses the pi-ai builtin catalog provider (catalog-reuse fix)`,
410
+ })
411
+ }
421
412
 
422
- const desiredById = new Map<string, SettingsModelProfile>()
423
- for (const id of desiredIds) {
424
- const entry = entryById.get(id)
425
- if (entry !== undefined) desiredById.set(id, mapGoModelToProfile(entry))
426
- }
427
- desiredByRoute[route] = [...desiredById.values()]
413
+ const currentModels = current?.models ?? []
414
+ const managed = owned?.managed ?? {}
415
+ const nextManaged: Record<string, GoManagedModel> = {}
416
+ const kept: SettingsModelProfile[] = []
417
+ // H5: a KEPT id the host catalog does not know poisons every future
418
+ // mutate of this route (the host rejects the whole models array). The
419
+ // plan never removes user content on its own, so it warns instead — the
420
+ // actionable exits are a custom route (with api/baseURL) or the host
421
+ // upgrade.
422
+ const warnKeptHostUnknown = (id: string): void => {
423
+ if (hostSet === undefined || hostSet.has(id)) return
424
+ report.push({
425
+ level: 'warn',
426
+ code: 'kept-host-unknown',
427
+ route: managedRoute,
428
+ slot: managedSlot,
429
+ id,
430
+ message: `model ${id} kept but not in the host runtime catalog — 宿主可能拒绝本路由的全部写入;请迁移到带 api/baseURL 的自定义路由或等待宿主升级`,
431
+ })
432
+ }
428
433
 
429
- const currentModels = current?.models ?? []
430
- const managed = owned?.managed ?? {}
431
- const nextManaged: Record<string, GoManagedModel> = {}
432
- const kept: SettingsModelProfile[] = []
433
-
434
- for (const model of currentModels) {
435
- const id = model.id
436
- const desired = desiredById.get(id)
437
- const record = managed[id]
438
- const hashMatches = record !== undefined && record.hash === profileHash(model)
439
- const hasOverride = (current?.overrideIds ?? []).includes(id)
440
- const isPinned = pinned.has(id)
441
-
442
- if (desired !== undefined) {
443
- if (record !== undefined && hashMatches) {
444
- // Plugin-owned and untouched: overwrite with the freshly mapped value.
445
- const next = desired
446
- nextManaged[id] = { hash: profileHash(next) }
447
- kept.push(next)
448
- report.push({ level: 'info', code: 'overwrote-managed', route, slot, id, message: `refreshed plugin-managed model ${id}` })
449
- } else {
450
- // Not in ledger, or hash differs (user edited): keep as-is, never claim.
451
- kept.push(model)
452
- if (record !== undefined) nextManaged[id] = record
453
- report.push({
454
- level: 'info',
455
- code: 'kept-user-owned',
456
- route,
457
- slot,
458
- id,
459
- message: record !== undefined ? `model ${id} was modified; kept user value` : `model ${id} is user-owned; kept`,
460
- })
434
+ for (const model of currentModels) {
435
+ const id = model.id
436
+ const desired = desiredById.get(id)
437
+ const record = managed[id]
438
+ const hashMatches = record !== undefined && record.hash === profileHash(model)
439
+ const hasOverride = (current?.overrideIds ?? []).includes(id)
440
+ const isPinned = pinned.has(id)
441
+
442
+ if (desired !== undefined) {
443
+ if (record !== undefined && hashMatches) {
444
+ // Plugin-owned and untouched: overwrite with the freshly mapped value.
445
+ const next = desired
446
+ nextManaged[id] = { hash: profileHash(next) }
447
+ kept.push(next)
448
+ report.push({ level: 'info', code: 'overwrote-managed', route: managedRoute, slot: managedSlot, id, message: `refreshed plugin-managed model ${id}` })
449
+ } else {
450
+ // Not in ledger, or hash differs (user edited): keep as-is, never claim.
451
+ kept.push(model)
452
+ if (record !== undefined) nextManaged[id] = record
453
+ report.push({
454
+ level: 'info',
455
+ code: 'kept-user-owned',
456
+ route: managedRoute,
457
+ slot: managedSlot,
458
+ id,
459
+ message: record !== undefined ? `model ${id} was modified; kept user value` : `model ${id} is user-owned; kept`,
460
+ })
461
+ warnKeptHostUnknown(id)
462
+ }
463
+ continue
461
464
  }
462
- continue
465
+
466
+ // Not desired: the three deletion gates (ADR-005 / §6.2.4).
467
+ if (record !== undefined && hashMatches && !hasOverride && !isPinned) {
468
+ report.push({ level: 'info', code: 'deletion-candidate', route: managedRoute, slot: managedSlot, id, message: `model ${id} passed all three deletion gates` })
469
+ continue
470
+ }
471
+ kept.push(model)
472
+ if (record !== undefined) nextManaged[id] = record
473
+ const code = record === undefined
474
+ ? 'kept-user-owned'
475
+ : !hashMatches
476
+ ? 'kept-modified'
477
+ : hasOverride
478
+ ? 'kept-override'
479
+ : 'kept-pinned'
480
+ report.push({ level: 'info', code, route: managedRoute, slot: managedSlot, id, message: `model ${id} kept (${code}); not removed` })
481
+ warnKeptHostUnknown(id)
463
482
  }
464
483
 
465
- // Not desired: the three deletion gates (ADR-005 / §6.2.4).
466
- if (record !== undefined && hashMatches && !hasOverride && !isPinned) {
467
- report.push({ level: 'info', code: 'deletion-candidate', route, slot, id, message: `model ${id} passed all three deletion gates` })
468
- continue
484
+ // New desired ids (absent from settings) are added and claimed.
485
+ const currentIds = new Set(currentModels.map((model) => model.id))
486
+ for (const id of desiredIds) {
487
+ if (currentIds.has(id)) continue
488
+ const profile = desiredById.get(id)
489
+ if (profile === undefined) continue
490
+ nextManaged[id] = { hash: profileHash(profile) }
491
+ kept.push(profile)
492
+ report.push({ level: 'info', code: 'added', route: managedRoute, slot: managedSlot, id, message: `added model ${id}` })
469
493
  }
470
- kept.push(model)
471
- if (record !== undefined) nextManaged[id] = record
472
- const code = record === undefined
473
- ? 'kept-user-owned'
474
- : !hashMatches
475
- ? 'kept-modified'
476
- : hasOverride
477
- ? 'kept-override'
478
- : 'kept-pinned'
479
- report.push({ level: 'info', code, route, slot, id, message: `model ${id} kept (${code}); not removed` })
480
- }
481
494
 
482
- // New desired ids (absent from settings) are added and claimed.
483
- const currentIds = new Set(currentModels.map((model) => model.id))
484
- for (const id of desiredIds) {
485
- if (currentIds.has(id)) continue
486
- const profile = desiredById.get(id)
487
- if (profile === undefined) continue
488
- nextManaged[id] = { hash: profileHash(profile) }
489
- kept.push(profile)
490
- report.push({ level: 'info', code: 'added', route, slot, id, message: `added model ${id}` })
495
+ // `desiredIds` is non-empty here, so the merged array is never empty.
496
+ const merged = [...kept].sort((a, b) => a.id.localeCompare(b.id))
497
+ plannedRoutes.push({ slot: managedSlot, route: managedRoute, fields, models: merged, unset: false, skip: false })
498
+ // P1d-2 ownership: inherit the prior entry so migration-period fields
499
+ // (`preManagedSection` / `appliedAddedIds` and any future ones) survive the
500
+ // plan round-trip untouched. The planner never writes or clears these — it
501
+ // only refreshes the fields it owns (routeFields / managed). The go writer
502
+ // applies the same merge when it persists the ledger entry.
503
+ nextOwnership[ledgerKey] = { ...owned, routeFields: fields, managed: nextManaged }
491
504
  }
505
+ }
492
506
 
493
- // `desiredIds` is non-empty here, so the merged array is never empty.
494
- const merged = [...kept].sort((a, b) => a.id.localeCompare(b.id))
495
- plannedRoutes.push({ slot, route, fields, models: merged, unset: false, skip: false })
496
- // P1d-2 ownership: inherit the prior entry so migration-period fields
497
- // (`preManagedSection` / `appliedAddedIds` and any future ones) survive the
498
- // plan round-trip untouched. The planner never writes or clears these — it
499
- // only refreshes the fields it owns (routeFields / managed). The go writer
500
- // applies the same merge when it persists the ledger entry.
501
- nextOwnership[ledgerKey] = { ...owned, routeFields: fields, managed: nextManaged }
507
+ // --- Legacy protocol routes: cleanup plan ---------------------------------
508
+ // Only on a healthy payload: an anomalous empty listing must not trigger
509
+ // route teardown on top of the upstream anomaly.
510
+ // H2: also NOT while the main route has a field conflict — the writer
511
+ // executes routes independently, and a failed/skipped main-route write must
512
+ // never be followed by legacy unsets (the host validates route REMOVAL
513
+ // against no catalog, so the unsets would succeed and the user's
514
+ // non-chat-protocol models would be gone with the main route unwritten).
515
+ const conflictDeferred = conflictOnMainRoute !== undefined && desiredIds.length > 0
516
+ if (conflictDeferred) {
517
+ report.push({
518
+ level: 'warn',
519
+ code: 'legacy-cleanup-deferred',
520
+ route: managedRoute,
521
+ slot: managedSlot,
522
+ message: `main route ${managedRoute} has a field conflict; legacy route cleanup is deferred to the round that fixes it (H2: never unset legacy routes while the managed route write is not healthy)`,
523
+ })
524
+ }
525
+ if (desiredIds.length > 0 && conflictOnMainRoute === undefined) {
526
+ for (const slot of ['msg', 'resp', 'google'] as const) {
527
+ const route = routes[slot]
528
+ const routeCurrent = options.currentRoutes[route]
529
+ const legacyLedgerKey = goOwnershipKey(route, options.keyFingerprint)
530
+ const legacyOwned = options.ownership[legacyLedgerKey]
531
+ if ((routeCurrent === undefined || !routeCurrent.exists) && legacyOwned === undefined) continue
532
+
533
+ const legacyFields = planGoRouteFields(options.entries, ref)
534
+ const currentModels = routeCurrent?.models ?? []
535
+ const managed = legacyOwned?.managed ?? {}
536
+ // Fully managed = the plugin owns every model present (an empty route
537
+ // with a ledger entry counts: it was emptied by a previous round), the
538
+ // recorded ownership fields match this plan, AND the section carries no
539
+ // user content the whole-route unset would destroy (M1): no
540
+ // modelOverrides, no pinned ids, no renamed-away apiKeyEnv, no unknown
541
+ // fields (headers, custom keys).
542
+ const overrideIds = routeCurrent?.overrideIds ?? []
543
+ const unknownKeys = routeCurrent?.unknownKeys ?? []
544
+ const liveApiKeyEnv = routeCurrent?.apiKeyEnv
545
+ const apiKeyEnvUserTouched = liveApiKeyEnv !== undefined
546
+ && liveApiKeyEnv !== '' && liveApiKeyEnv !== legacyFields.apiKeyEnv
547
+ const fullyManaged = legacyOwned !== undefined
548
+ && currentModels.every((model) => {
549
+ const record = managed[model.id]
550
+ return record !== undefined && record.hash === profileHash(model)
551
+ })
552
+ && currentModels.every((model) => !pinned.has(model.id))
553
+ && overrideIds.length === 0
554
+ && unknownKeys.length === 0
555
+ && !apiKeyEnvUserTouched
556
+ && ownedFieldsMatch(legacyOwned, legacyFields)
557
+ if (fullyManaged) {
558
+ plannedRoutes.push({ slot, route, fields: legacyFields, models: [], unset: true, skip: false })
559
+ unsetRoutes.push(route)
560
+ report.push({ level: 'info', code: 'unset-legacy-route', route, slot, message: `legacy route ${route} is superseded by the single managed route and fully plugin-managed; unset` })
561
+ delete nextOwnership[legacyLedgerKey]
562
+ } else {
563
+ plannedRoutes.push({ slot, route, fields: legacyFields, models: [...currentModels], unset: false, skip: true })
564
+ const userContent: string[] = []
565
+ if (currentModels.length > 0) userContent.push(`${currentModels.length} model(s)`)
566
+ if (overrideIds.length > 0) userContent.push(`modelOverrides: ${overrideIds.join(', ')}`)
567
+ if (unknownKeys.length > 0) userContent.push(`custom fields: ${unknownKeys.join(', ')}`)
568
+ if (apiKeyEnvUserTouched) userContent.push(`apiKeyEnv: ${liveApiKeyEnv}`)
569
+ // P3: when pinned ids are the ONLY reason the route stays, say so —
570
+ // otherwise the keep looks unexplained (the fully-managed unset gates
571
+ // would have passed without them).
572
+ const pinnedKept = currentModels.filter((model) => pinned.has(model.id)).map((model) => model.id)
573
+ if (pinnedKept.length > 0) userContent.push(`pinned: ${pinnedKept.join(', ')}`)
574
+ if (userContent.length > 0) {
575
+ report.push({ level: 'warn', code: 'legacy-route-kept', route, slot, message: `legacy route ${route} holds user content (${userContent.join('; ')}); kept as-is (superseded by the single managed route)` })
576
+ }
577
+ }
578
+ }
502
579
  }
503
580
 
504
581
  return { routes: plannedRoutes, unsetRoutes, conflicts, report, nextOwnership, desiredByRoute }