@aiwayds/dsh-model-sync 0.11.1 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -7,12 +7,14 @@
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'
@@ -20,93 +22,47 @@ import type { GoModelRecord } from './opencode-go-source.ts'
20
22
  import { deriveKeyRef } from './route-credential.ts'
21
23
  import {
22
24
  GO_SLOT_ROUTES,
23
- groupGoModelsByProtocol,
24
25
  type GoRouteSlot,
25
26
  } from './opencode-go-grouping.ts'
26
27
 
27
28
  // ---------------------------------------------------------------------------
28
- // Static route-field plan (design §2.1 / §6.2.2, confirmed by report 19)
29
+ // Static route-field plan (0.12.0 catalog-reuse shape)
29
30
  // ---------------------------------------------------------------------------
30
31
 
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
32
  /**
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`.
33
+ * Route fields a managed route must carry. `api`/`baseURL` are deliberately
34
+ * ABSENT: writing them makes the host build the provider from the bare
35
+ * PROTOCOLS implementation (missing `x-opencode-session` header → HTTP 400)
36
+ * instead of the pi-ai builtin catalog provider.
51
37
  */
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',
38
+ export interface GoPlannedRouteFields {
39
+ displayName: string
40
+ apiKeyEnv: string
57
41
  }
58
42
 
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
- }
43
+ /** The display name planned for the single managed route (F22/13). */
44
+ export const GO_DISPLAY_NAME = 'OpenCode Go'
66
45
 
67
46
  /**
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).
47
+ * Legacy route fields the writer must strip from the managed route (and that
48
+ * old 0.11.x routes carry). They are never part of a written plan.
71
49
  */
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
- }
50
+ export const GO_LEGACY_ROUTE_FIELDS = ['api', 'baseURL'] as const
84
51
 
85
52
  /**
86
- * Build the route fields for a slot from the payload's per-protocol base_url.
53
+ * Build the planned route fields for the single managed route. `entries` is
54
+ * kept in the signature for symmetry with the migration caller (and future
55
+ * payload-driven fields); with the catalog-reuse shape the fields no longer
56
+ * depend on the payload — the endpoint lives in pi-ai's builtin catalog.
87
57
  * `ref` defaults to the P0-derived `OPENCODE_GO_API_KEY`.
88
58
  */
89
59
  export function planGoRouteFields(
90
- slot: GoRouteSlot,
91
60
  entries: readonly GoModelRecord[],
92
61
  ref: string = deriveKeyRef('opencode-go'),
93
62
  ): 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
- }
63
+ void entries
106
64
  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],
65
+ displayName: GO_DISPLAY_NAME,
110
66
  apiKeyEnv: ref,
111
67
  }
112
68
  }
@@ -205,7 +161,7 @@ export interface GoRouteState {
205
161
  export interface GoRouteConflict {
206
162
  slot: GoRouteSlot
207
163
  route: string
208
- field: 'api' | 'baseURL' | 'apiKeyEnv'
164
+ field: 'apiKeyEnv'
209
165
  expected: string
210
166
  actual: string
211
167
  reason: string
@@ -215,7 +171,7 @@ export type GoPlanReportLevel = 'info' | 'warn' | 'error'
215
171
 
216
172
  export interface GoPlanReportEntry {
217
173
  level: GoPlanReportLevel
218
- /** Stable machine code (e.g. route-conflict, kept-user-owned, unknown-protocol). */
174
+ /** Stable machine code (e.g. route-conflict, kept-user-owned, legacy-fields-strip). */
219
175
  code: string
220
176
  route?: string
221
177
  slot?: GoRouteSlot
@@ -229,9 +185,9 @@ export interface GoPlannedRoute {
229
185
  fields: GoPlannedRouteFields
230
186
  /** Complete merged models array, sorted by id (never an empty write — see unset/skip). */
231
187
  models: SettingsModelProfile[]
232
- /** Empty and fully plugin-managed: caller should unset providers.<route>. */
188
+ /** Empty and fully plugin-managed (or superseded legacy): caller should unset providers.<route>. */
233
189
  unset: boolean
234
- /** Conflict, empty main route, or empty route with user content: write nothing. */
190
+ /** Conflict, empty main route, or legacy route with user content: write nothing. */
235
191
  skip: boolean
236
192
  }
237
193
 
@@ -287,7 +243,7 @@ export function profileHash(profile: SettingsModelProfile): string {
287
243
  return createHash('sha256').update(JSON.stringify(canonicalize(profile))).digest('hex')
288
244
  }
289
245
 
290
- const OWNERSHIP_FIELDS = ['api', 'baseURL', 'apiKeyEnv'] as const
246
+ const OWNERSHIP_FIELDS = ['apiKeyEnv'] as const
291
247
 
292
248
  /** A current route conflicts only when a field is explicitly set to a different value. */
293
249
  function detectConflict(
@@ -328,12 +284,16 @@ function ownedFieldsMatch(
328
284
  /**
329
285
  * Build the write plan. Pure: identical inputs always produce an identical
330
286
  * plan (report/order included). No mutation of `options` or its nested values.
287
+ *
288
+ * Topology (0.12.0): ONE managed route (the `chat` slot route) receives ALL
289
+ * official entries; the three legacy protocol routes (msg/resp/google) are
290
+ * cleanup targets — unset when fully plugin-managed, kept with a warn when
291
+ * they hold user content.
331
292
  */
332
293
  export function planGoRoutes(options: GoPlannerOptions): GoPlanResult {
333
294
  const ref = options.ref ?? deriveKeyRef('opencode-go')
334
295
  const routes: Record<GoRouteSlot, string> = { ...GO_SLOT_ROUTES, ...(options.routes ?? {}) }
335
296
  const pinned = new Set(options.pinnedModels ?? [])
336
- const grouping = groupGoModelsByProtocol(options.entries)
337
297
  const report: GoPlanReportEntry[] = []
338
298
  const conflicts: GoRouteConflict[] = []
339
299
  const plannedRoutes: GoPlannedRoute[] = []
@@ -341,164 +301,171 @@ export function planGoRoutes(options: GoPlannerOptions): GoPlanResult {
341
301
  const nextOwnership: Record<string, GoOwnershipEntry> = { ...options.ownership }
342
302
  const desiredByRoute: Record<string, SettingsModelProfile[]> = {}
343
303
 
344
- // Unknown / otherwise unsupported protocols are fail-closed: reported, never
345
- // written (design §6.2.3, V1).
346
- for (const unassigned of grouping.unassigned) {
347
- 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'})`,
352
- })
353
- }
354
-
355
304
  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
305
+ // Single-route desired set: every official entry, in stable id order.
306
+ const desiredIds = [...entryById.keys()].sort((a, b) => a.localeCompare(b))
307
+
308
+ // --- The single managed route (chat slot) --------------------------------
309
+ const managedSlot: GoRouteSlot = 'chat'
310
+ const managedRoute = routes[managedSlot]
311
+ const current = options.currentRoutes[managedRoute]
312
+ const ledgerKey = goOwnershipKey(managedRoute, options.keyFingerprint)
313
+ const owned = options.ownership[ledgerKey]
314
+ const fields = planGoRouteFields(options.entries, ref)
315
+ desiredByRoute[managedRoute] = []
316
+
317
+ if (desiredIds.length === 0) {
318
+ const currentModels = current?.models ?? []
319
+ if (current !== undefined && current.exists) {
320
+ // §9.4: an empty main route after a 200 is an upstream anomaly — keep
321
+ // last-good, write nothing.
322
+ plannedRoutes.push({ slot: managedSlot, route: managedRoute, fields, models: [...currentModels], unset: false, skip: true })
323
+ report.push({ level: 'warn', code: 'upstream-empty', route: managedRoute, slot: managedSlot, message: 'main route has no members; kept last-good, no write' })
407
324
  }
408
-
409
- const conflict = detectConflict(slot, route, fields, current)
325
+ } else {
326
+ const conflict = detectConflict(managedSlot, managedRoute, fields, current)
410
327
  if (conflict !== undefined) {
411
328
  conflicts.push(conflict)
412
329
  report.push({
413
330
  level: 'error',
414
331
  code: 'route-conflict',
415
- route,
416
- slot,
417
- message: `${route}.${conflict.field} is ${conflict.actual}, expected ${conflict.expected}`,
332
+ route: managedRoute,
333
+ slot: managedSlot,
334
+ message: `${managedRoute}.${conflict.field} is ${conflict.actual}, expected ${conflict.expected}`,
418
335
  })
419
- continue
420
- }
336
+ } else {
337
+ const desiredById = new Map<string, SettingsModelProfile>()
338
+ for (const id of desiredIds) {
339
+ const entry = entryById.get(id)
340
+ if (entry !== undefined) desiredById.set(id, mapGoModelToProfile(entry))
341
+ }
342
+ desiredByRoute[managedRoute] = [...desiredById.values()]
343
+
344
+ // Catalog-reuse strip notice: a route still carrying the old 0.11.x
345
+ // `api`/`baseURL` fields gets them unset this round (the writer emits
346
+ // the ops; this line explains why in the report).
347
+ if (current !== undefined && current.exists
348
+ && GO_LEGACY_ROUTE_FIELDS.some((field) => current[field] !== undefined && current[field] !== '')) {
349
+ report.push({
350
+ level: 'info',
351
+ code: 'legacy-fields-strip',
352
+ route: managedRoute,
353
+ slot: managedSlot,
354
+ message: `route ${managedRoute} carries legacy api/baseURL fields; unsetting them so the host reuses the pi-ai builtin catalog provider (catalog-reuse fix)`,
355
+ })
356
+ }
421
357
 
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()]
358
+ const currentModels = current?.models ?? []
359
+ const managed = owned?.managed ?? {}
360
+ const nextManaged: Record<string, GoManagedModel> = {}
361
+ const kept: SettingsModelProfile[] = []
362
+
363
+ for (const model of currentModels) {
364
+ const id = model.id
365
+ const desired = desiredById.get(id)
366
+ const record = managed[id]
367
+ const hashMatches = record !== undefined && record.hash === profileHash(model)
368
+ const hasOverride = (current?.overrideIds ?? []).includes(id)
369
+ const isPinned = pinned.has(id)
370
+
371
+ if (desired !== undefined) {
372
+ if (record !== undefined && hashMatches) {
373
+ // Plugin-owned and untouched: overwrite with the freshly mapped value.
374
+ const next = desired
375
+ nextManaged[id] = { hash: profileHash(next) }
376
+ kept.push(next)
377
+ report.push({ level: 'info', code: 'overwrote-managed', route: managedRoute, slot: managedSlot, id, message: `refreshed plugin-managed model ${id}` })
378
+ } else {
379
+ // Not in ledger, or hash differs (user edited): keep as-is, never claim.
380
+ kept.push(model)
381
+ if (record !== undefined) nextManaged[id] = record
382
+ report.push({
383
+ level: 'info',
384
+ code: 'kept-user-owned',
385
+ route: managedRoute,
386
+ slot: managedSlot,
387
+ id,
388
+ message: record !== undefined ? `model ${id} was modified; kept user value` : `model ${id} is user-owned; kept`,
389
+ })
390
+ }
391
+ continue
392
+ }
428
393
 
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
- })
394
+ // Not desired: the three deletion gates (ADR-005 / §6.2.4).
395
+ if (record !== undefined && hashMatches && !hasOverride && !isPinned) {
396
+ report.push({ level: 'info', code: 'deletion-candidate', route: managedRoute, slot: managedSlot, id, message: `model ${id} passed all three deletion gates` })
397
+ continue
461
398
  }
462
- continue
399
+ kept.push(model)
400
+ if (record !== undefined) nextManaged[id] = record
401
+ const code = record === undefined
402
+ ? 'kept-user-owned'
403
+ : !hashMatches
404
+ ? 'kept-modified'
405
+ : hasOverride
406
+ ? 'kept-override'
407
+ : 'kept-pinned'
408
+ report.push({ level: 'info', code, route: managedRoute, slot: managedSlot, id, message: `model ${id} kept (${code}); not removed` })
463
409
  }
464
410
 
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
411
+ // New desired ids (absent from settings) are added and claimed.
412
+ const currentIds = new Set(currentModels.map((model) => model.id))
413
+ for (const id of desiredIds) {
414
+ if (currentIds.has(id)) continue
415
+ const profile = desiredById.get(id)
416
+ if (profile === undefined) continue
417
+ nextManaged[id] = { hash: profileHash(profile) }
418
+ kept.push(profile)
419
+ report.push({ level: 'info', code: 'added', route: managedRoute, slot: managedSlot, id, message: `added model ${id}` })
469
420
  }
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
421
 
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}` })
422
+ // `desiredIds` is non-empty here, so the merged array is never empty.
423
+ const merged = [...kept].sort((a, b) => a.id.localeCompare(b.id))
424
+ plannedRoutes.push({ slot: managedSlot, route: managedRoute, fields, models: merged, unset: false, skip: false })
425
+ // P1d-2 ownership: inherit the prior entry so migration-period fields
426
+ // (`preManagedSection` / `appliedAddedIds` and any future ones) survive the
427
+ // plan round-trip untouched. The planner never writes or clears these — it
428
+ // only refreshes the fields it owns (routeFields / managed). The go writer
429
+ // applies the same merge when it persists the ledger entry.
430
+ nextOwnership[ledgerKey] = { ...owned, routeFields: fields, managed: nextManaged }
491
431
  }
432
+ }
492
433
 
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 }
434
+ // --- Legacy protocol routes: cleanup plan ---------------------------------
435
+ // Only on a healthy payload: an anomalous empty listing must not trigger
436
+ // route teardown on top of the upstream anomaly.
437
+ if (desiredIds.length > 0) {
438
+ for (const slot of ['msg', 'resp', 'google'] as const) {
439
+ const route = routes[slot]
440
+ const routeCurrent = options.currentRoutes[route]
441
+ const legacyLedgerKey = goOwnershipKey(route, options.keyFingerprint)
442
+ const legacyOwned = options.ownership[legacyLedgerKey]
443
+ if ((routeCurrent === undefined || !routeCurrent.exists) && legacyOwned === undefined) continue
444
+
445
+ const legacyFields = planGoRouteFields(options.entries, ref)
446
+ const currentModels = routeCurrent?.models ?? []
447
+ const managed = legacyOwned?.managed ?? {}
448
+ // Fully managed = the plugin owns every model present (an empty route
449
+ // with a ledger entry counts: it was emptied by a previous round) and
450
+ // the recorded ownership fields match this plan.
451
+ const fullyManaged = legacyOwned !== undefined
452
+ && currentModels.every((model) => {
453
+ const record = managed[model.id]
454
+ return record !== undefined && record.hash === profileHash(model)
455
+ })
456
+ && ownedFieldsMatch(legacyOwned, legacyFields)
457
+ if (fullyManaged) {
458
+ plannedRoutes.push({ slot, route, fields: legacyFields, models: [], unset: true, skip: false })
459
+ unsetRoutes.push(route)
460
+ 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` })
461
+ delete nextOwnership[legacyLedgerKey]
462
+ } else {
463
+ plannedRoutes.push({ slot, route, fields: legacyFields, models: [...currentModels], unset: false, skip: true })
464
+ if (currentModels.length > 0) {
465
+ report.push({ level: 'warn', code: 'legacy-route-kept', route, slot, message: `legacy route ${route} holds user content; kept as-is (superseded by the single managed route)` })
466
+ }
467
+ }
468
+ }
502
469
  }
503
470
 
504
471
  return { routes: plannedRoutes, unsetRoutes, conflicts, report, nextOwnership, desiredByRoute }
@@ -20,6 +20,7 @@ import type { GoRouteSlot } from './opencode-go-grouping.ts'
20
20
  import {
21
21
  goOwnershipKey,
22
22
  profileHash,
23
+ GO_LEGACY_ROUTE_FIELDS,
23
24
  type GoManagedModel,
24
25
  type GoOwnershipEntry,
25
26
  type GoPlanReportEntry,
@@ -42,11 +43,12 @@ import {
42
43
  import { fingerprintSection } from './opencode-go-migration.ts'
43
44
 
44
45
  const SETTINGS_CONFLICT = 'SETTINGS_CONFLICT'
45
- // O1-minimal: `displayName` is a display field, NOT an identity/ownership field.
46
- // It is deliberately kept out of this set so it matches the planner's
47
- // OWNERSHIP_FIELDS (detectConflict), which never checks it. A display-name-only
48
- // upstream change must not make the writer rewrite the route's identity fields.
49
- const OWNED_FIELDS = ['api', 'baseURL', 'apiKeyEnv'] as const
46
+ // 0.12.0 catalog-reuse: the ONLY route field the writer sets is `apiKeyEnv`.
47
+ // `api`/`baseURL` must stay UNSET (they make the host build the provider from
48
+ // the bare PROTOCOLS implementation — missing `x-opencode-session` → HTTP 400
49
+ // — instead of pi-ai's builtin catalog provider), and `displayName` is a
50
+ // display field deliberately never rewritten so a user rename survives.
51
+ const OWNED_FIELDS = ['apiKeyEnv'] as const
50
52
 
51
53
  // O1-minimal: a settings.mutate can land while the ledger/record write after it
52
54
  // fails. That route is NOT a clean success (no ledger => next round keeps it as
@@ -543,10 +545,11 @@ interface RouteOps {
543
545
  }
544
546
 
545
547
  /**
546
- * Build one route's ops. `set api/baseURL/displayName/apiKeyEnv/models` (or a
547
- * whole-route `unset`) all go into ONE mutate, so a route never ends up with
548
- * fields from one round and models from another (§6.2.4 atomicity).
549
- * Returns `undefined` when nothing would change (`profilesEqual` gate).
548
+ * Build one route's ops. Set `apiKeyEnv` + unset any legacy `api`/`baseURL`
549
+ * (or a whole-route `unset`) + set `models`, all in ONE mutate, so a route
550
+ * never ends up with fields from one round and models from another
551
+ * (§6.2.4 atomicity). Returns `undefined` when nothing would change
552
+ * (`profilesEqual` gate).
550
553
  */
551
554
  async function buildRouteOps(
552
555
  planned: GoPlannedRoute,
@@ -582,6 +585,15 @@ async function buildRouteOps(
582
585
  ops.push({ op: 'set', path: ['providers', planned.route, field], value: planned.fields[field] })
583
586
  }
584
587
  }
588
+ // Catalog-reuse: a route still carrying the 0.11.x `api`/`baseURL` fields
589
+ // gets them unset — with any `api` present the host leaves pi-ai's builtin
590
+ // catalog provider (and its x-opencode-session wrapping) behind.
591
+ for (const field of GO_LEGACY_ROUTE_FIELDS) {
592
+ const value = data?.[field]
593
+ if (value !== undefined && value !== '') {
594
+ ops.push({ op: 'unset', path: ['providers', planned.route, field] })
595
+ }
596
+ }
585
597
  const currentRaw = sortedModels(rawModels(desc, planned.route))
586
598
  const mergedSorted = sortedModels(mergedModels)
587
599
  postWriteModels = mergedSorted