@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
@@ -1,582 +0,0 @@
1
- // P1a pure planner: official opencode-go records + current route state +
2
- // ownership ledger → a settings-independent write plan.
3
- //
4
- // Hard boundary (design 07 §6.2.1): this module does no I/O, never calls
5
- // settings.mutate, never touches credentials, and never schedules timers. The
6
- // caller in P1b turns the returned plan into settings operations. Everything
7
- // here is a pure function of its inputs so it can be exercised with offline
8
- // fixtures only.
9
- //
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.
18
-
19
- import { createHash } from 'node:crypto'
20
- import type { SettingsModelProfile } from './translate.ts'
21
- import type { GoModelRecord } from './opencode-go-source.ts'
22
- import { deriveKeyRef } from './route-credential.ts'
23
- import { HOST_CATALOG_PROVIDER } from './opencode-go-host-catalog.ts'
24
- import {
25
- GO_SLOT_ROUTES,
26
- type GoRouteSlot,
27
- } from './opencode-go-grouping.ts'
28
-
29
- // ---------------------------------------------------------------------------
30
- // Static route-field plan (0.12.0 catalog-reuse shape)
31
- // ---------------------------------------------------------------------------
32
-
33
- /**
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.
38
- */
39
- export interface GoPlannedRouteFields {
40
- displayName: string
41
- apiKeyEnv: string
42
- }
43
-
44
- /** The display name planned for the single managed route (F22/13). */
45
- export const GO_DISPLAY_NAME = 'OpenCode Go'
46
-
47
- /**
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.
50
- */
51
- export const GO_LEGACY_ROUTE_FIELDS = ['api', 'baseURL'] as const
52
-
53
- /**
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.
58
- * `ref` defaults to the P0-derived `OPENCODE_GO_API_KEY`.
59
- */
60
- export function planGoRouteFields(
61
- entries: readonly GoModelRecord[],
62
- ref: string = deriveKeyRef('opencode-go'),
63
- ): GoPlannedRouteFields {
64
- void entries
65
- return {
66
- displayName: GO_DISPLAY_NAME,
67
- apiKeyEnv: ref,
68
- }
69
- }
70
-
71
- // ---------------------------------------------------------------------------
72
- // Model mapping (design §6.1 field mapping)
73
- // ---------------------------------------------------------------------------
74
-
75
- /** Effort keys the host schema accepts (mirrors translate.ts THINKING_LEVELS). */
76
- const THINKING_LEVELS = new Set(['off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'])
77
-
78
- /** Official GoModelRecord → host SettingsModelProfile. `created` never enters. */
79
- export function mapGoModelToProfile(entry: GoModelRecord): SettingsModelProfile {
80
- const profile: SettingsModelProfile = { id: entry.id }
81
- if (entry.name.length > 0) profile.name = entry.name
82
- if (entry.contextWindow !== undefined) profile.contextWindow = entry.contextWindow
83
- if (entry.maxOutput !== undefined) profile.maxTokens = entry.maxOutput
84
- if (entry.inputModalities.length > 0) profile.input = [...entry.inputModalities]
85
- if (entry.reasoning !== undefined && entry.reasoning.efforts.length > 0) {
86
- const efforts: Record<string, string | null> = {}
87
- for (const effort of entry.reasoning.efforts) {
88
- if (THINKING_LEVELS.has(effort)) efforts[effort] = effort
89
- }
90
- if (Object.keys(efforts).length > 0) profile.reasoningEfforts = efforts
91
- }
92
- return profile
93
- }
94
-
95
- // ---------------------------------------------------------------------------
96
- // Ownership ledger (ADR-004: keyed by <route>#<keyFingerprint>)
97
- // ---------------------------------------------------------------------------
98
-
99
- export interface GoManagedModel {
100
- /** Hash of the profile the plugin last wrote for this id. */
101
- hash: string
102
- }
103
-
104
- export interface GoOwnershipEntry {
105
- /** Route fields the plugin last wrote (used to recognize a fully-owned route). */
106
- routeFields?: Partial<GoPlannedRouteFields>
107
- /** Plugin-managed model ids and the hash of their last written profile. */
108
- managed: Record<string, GoManagedModel>
109
- /**
110
- * Raw models present in the route before the plugin first claimed it (design
111
- * §6.1 / ADR-004). Audit-only: never used as a whole-route write-back.
112
- * Rollback restores from `preManagedSection` (§14.3), not from this field.
113
- */
114
- preManagedSnapshot?: SettingsModelProfile[]
115
- /**
116
- * P1d-2: the COMPLETE raw provider section captured before `migrate apply`
117
- * (all fields — api/baseURL/displayName/apiKeyEnv/models — exactly as found).
118
- * `null` means the route did not exist before the migration. This is the
119
- * authoritative rollback target (design §14.3 whole-section snapshot) and is
120
- * persisted on the same models-store queue as the rest of the ledger entry;
121
- * unlike the in-progress backup it is NOT released when apply succeeds.
122
- */
123
- preManagedSection?: Record<string, unknown> | null
124
- /**
125
- * P1d-2: ids `migrate apply` newly introduced on this route (merged desired
126
- * ids absent from the pre-apply section). Rollback removes these, while ids
127
- * the user adds after apply are left untouched.
128
- */
129
- appliedAddedIds?: string[]
130
- /**
131
- * Consecutive successful rounds an id has been absent from the desired set.
132
- * The planner only flags a deletion-candidate; the writer owns this counter
133
- * and deletes only once it reaches `confirmRemovals` (design §6.2.4 / V5).
134
- */
135
- missing?: Record<string, number>
136
- }
137
-
138
- export type GoOwnershipLedger = Readonly<Record<string, GoOwnershipEntry>>
139
-
140
- /** Ledger key: one route's ownership is invisible under a different key. */
141
- export function goOwnershipKey(route: string, keyFingerprint: string): string {
142
- return `${route}#${keyFingerprint}`
143
- }
144
-
145
- /** The raw current state of one provider route in settings. */
146
- export interface GoRouteState {
147
- exists: boolean
148
- api?: string
149
- baseURL?: string
150
- displayName?: string
151
- apiKeyEnv?: string
152
- /** Raw models array (no schema defaults applied). */
153
- models: readonly SettingsModelProfile[]
154
- /** Ids covered by a non-empty modelOverrides key on this route. */
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[]
162
- }
163
-
164
- // ---------------------------------------------------------------------------
165
- // Plan output
166
- // ---------------------------------------------------------------------------
167
-
168
- export interface GoRouteConflict {
169
- slot: GoRouteSlot
170
- route: string
171
- field: 'apiKeyEnv'
172
- expected: string
173
- actual: string
174
- reason: string
175
- }
176
-
177
- export type GoPlanReportLevel = 'info' | 'warn' | 'error'
178
-
179
- export interface GoPlanReportEntry {
180
- level: GoPlanReportLevel
181
- /** Stable machine code (e.g. route-conflict, kept-user-owned, legacy-fields-strip). */
182
- code: string
183
- route?: string
184
- slot?: GoRouteSlot
185
- id?: string
186
- message: string
187
- }
188
-
189
- export interface GoPlannedRoute {
190
- slot: GoRouteSlot
191
- route: string
192
- fields: GoPlannedRouteFields
193
- /** Complete merged models array, sorted by id (never an empty write — see unset/skip). */
194
- models: SettingsModelProfile[]
195
- /** Empty and fully plugin-managed (or superseded legacy): caller should unset providers.<route>. */
196
- unset: boolean
197
- /** Conflict, empty main route, or legacy route with user content: write nothing. */
198
- skip: boolean
199
- }
200
-
201
- export interface GoPlanResult {
202
- routes: GoPlannedRoute[]
203
- /** Routes the caller should unset (never paired with `models: []`). */
204
- unsetRoutes: string[]
205
- conflicts: GoRouteConflict[]
206
- report: GoPlanReportEntry[]
207
- /** Shallow copy of the ledger updated only for this key's routes. */
208
- nextOwnership: Record<string, GoOwnershipEntry>
209
- /**
210
- * The mapped desired profiles per route BEFORE the merge with current
211
- * settings. The writer needs this to do a first-round conservative claim
212
- * (official desired ∩ current, never ids outside the desired set) — the
213
- * merged `routes[].models` already contains kept user entries and cannot be
214
- * used for that distinction.
215
- */
216
- desiredByRoute: Record<string, SettingsModelProfile[]>
217
- }
218
-
219
- export interface GoPlannerOptions {
220
- /** sha256(key) first 16 hex from the source result; '-' when no key. */
221
- keyFingerprint: string
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[]
231
- /** Current state of the go routes, keyed by route id. */
232
- currentRoutes: Readonly<Record<string, GoRouteState>>
233
- ownership: GoOwnershipLedger
234
- /** go.ref; defaults to P0's deriveKeyRef('opencode-go'). */
235
- ref?: string
236
- /** go.routes overrides (default GO_SLOT_ROUTES). */
237
- routes?: Partial<Record<GoRouteSlot, string>>
238
- /** go.pinnedModels — protected from deletion (design A4). */
239
- pinnedModels?: readonly string[]
240
- }
241
-
242
- // ---------------------------------------------------------------------------
243
- // Helpers
244
- // ---------------------------------------------------------------------------
245
-
246
- function canonicalize(value: unknown): unknown {
247
- if (Array.isArray(value)) return value.map(canonicalize)
248
- if (typeof value !== 'object' || value === null) return value
249
- const out: Record<string, unknown> = {}
250
- for (const key of Object.keys(value as Record<string, unknown>).sort()) {
251
- out[key] = canonicalize((value as Record<string, unknown>)[key])
252
- }
253
- return out
254
- }
255
-
256
- /** Stable hash of a settings profile — the "现值哈希" of the deletion gates. */
257
- export function profileHash(profile: SettingsModelProfile): string {
258
- return createHash('sha256').update(JSON.stringify(canonicalize(profile))).digest('hex')
259
- }
260
-
261
- const OWNERSHIP_FIELDS = ['apiKeyEnv'] as const
262
-
263
- /** A current route conflicts only when a field is explicitly set to a different value. */
264
- function detectConflict(
265
- slot: GoRouteSlot,
266
- route: string,
267
- fields: GoPlannedRouteFields,
268
- current: GoRouteState | undefined,
269
- ): GoRouteConflict | undefined {
270
- if (current === undefined || !current.exists) return undefined
271
- for (const field of OWNERSHIP_FIELDS) {
272
- const actual = current[field]
273
- if (actual !== undefined && actual !== '' && actual !== fields[field]) {
274
- return {
275
- slot,
276
- route,
277
- field,
278
- expected: fields[field],
279
- actual,
280
- reason: 'existing route field differs from plan; keep name, skip write (design §9.3)',
281
- }
282
- }
283
- }
284
- return undefined
285
- }
286
-
287
- function ownedFieldsMatch(
288
- owned: GoOwnershipEntry | undefined,
289
- fields: GoPlannedRouteFields,
290
- ): boolean {
291
- if (owned === undefined || owned.routeFields === undefined) return false
292
- return OWNERSHIP_FIELDS.every((field) => owned.routeFields![field] === fields[field])
293
- }
294
-
295
- // ---------------------------------------------------------------------------
296
- // Planner
297
- // ---------------------------------------------------------------------------
298
-
299
- /**
300
- * Build the write plan. Pure: identical inputs always produce an identical
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.
307
- */
308
- export function planGoRoutes(options: GoPlannerOptions): GoPlanResult {
309
- const ref = options.ref ?? deriveKeyRef('opencode-go')
310
- const routes: Record<GoRouteSlot, string> = { ...GO_SLOT_ROUTES, ...(options.routes ?? {}) }
311
- const pinned = new Set(options.pinnedModels ?? [])
312
- const report: GoPlanReportEntry[] = []
313
- const conflicts: GoRouteConflict[] = []
314
- const plannedRoutes: GoPlannedRoute[] = []
315
- const unsetRoutes: string[] = []
316
- const nextOwnership: Record<string, GoOwnershipEntry> = { ...options.ownership }
317
- const desiredByRoute: Record<string, SettingsModelProfile[]> = {}
318
-
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) {
340
- report.push({
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 自动纳入`,
346
- })
347
- }
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' })
373
- }
374
- } else {
375
- const conflict = detectConflict(managedSlot, managedRoute, fields, current)
376
- if (conflict !== undefined) {
377
- conflicts.push(conflict)
378
- conflictOnMainRoute = conflict
379
- report.push({
380
- level: 'error',
381
- code: 'route-conflict',
382
- route: managedRoute,
383
- slot: managedSlot,
384
- message: `${managedRoute}.${conflict.field} is ${conflict.actual}, expected ${conflict.expected}`,
385
- })
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
- }
412
-
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
- }
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: 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
464
- }
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)
482
- }
483
-
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}` })
493
- }
494
-
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 }
504
- }
505
- }
506
-
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
- }
579
- }
580
-
581
- return { routes: plannedRoutes, unsetRoutes, conflicts, report, nextOwnership, desiredByRoute }
582
- }