@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
@@ -59,6 +59,16 @@ export interface GoRoundDeps {
59
59
  overrideStorer?: GoOverrideStorer
60
60
  logger: Logger
61
61
  config: GoSyncRuntimeConfig
62
+ /**
63
+ * Host runtime catalog ids for opencode-go (0.12.1). An ARRAY intersects the
64
+ * desired set with it (ids the host catalog does not know are reported as
65
+ * `needs-host-catalog`, never written). `null` FAILS THE ROUND CLOSED —
66
+ * zero writes — because writing the unverified full listing is exactly how
67
+ * 0.12.0 got the whole mutate rejected by the host. `undefined` (pure unit
68
+ * callers only; production always supplies one of the two) keeps the 0.12.0
69
+ * behavior.
70
+ */
71
+ hostCatalogIds?: readonly string[] | null
62
72
  /** Resolved credential VALUE; undefined/empty means no request and no write (V4). */
63
73
  apiKey?: string
64
74
  /** Injectable network; production falls back to the global fetch in the source. */
@@ -81,8 +91,9 @@ export interface GoRoundDeps {
81
91
  * `canWrite-unavailable` and skips the route (fail closed).
82
92
  */
83
93
  reloadMigration?: () => Promise<MigrationStatus>
84
- /** §14.7.4: forward the post-own-write managed ids to the record persister. */
85
- onOwnWrite?: (route: string, managedIds: string[]) => Promise<void>
94
+ /** §14.7.4: forward the post-own-write managed ids to the record persister.
95
+ * The third argument marks a whole-section unset (ledger key deleted). */
96
+ onOwnWrite?: (route: string, managedIds: string[], info?: { unset: boolean }) => Promise<void>
86
97
  /**
87
98
  * O1/C2: file-backed write-ahead journal store. With `profileKey` and
88
99
  * `keyFingerprint`, the round reconciles surviving journals BEFORE the
@@ -110,6 +121,9 @@ export type GoRoundReason =
110
121
  | 'aborted'
111
122
  | 'migration-gate'
112
123
  | 'settings-changed-during-sync'
124
+ // 0.12.1: the host runtime catalog could not be read — fail closed, zero
125
+ // writes (never write an unverified listing the host may reject wholesale).
126
+ | 'host-catalog-unavailable'
113
127
  // O1-minimal: one or more routes had failedRoutes (including the truthful
114
128
  // "settings written but not recorded" case). The command surface reports
115
129
  // kind:'error' for it, not a clean success.
@@ -154,6 +168,12 @@ function readRouteState(desc: SettingsDescriptor | undefined, route: string): Go
154
168
  const value = data[field]
155
169
  if (typeof value === 'string') state[field] = value
156
170
  }
171
+ // M1: keys outside the plugin's known field set are user content (headers,
172
+ // custom config) — a whole-route unset would destroy them, so the planner's
173
+ // fully-managed verdict never fires while any exist.
174
+ const knownFields = new Set(['api', 'baseURL', 'displayName', 'apiKeyEnv', 'models', 'modelOverrides'])
175
+ const unknownKeys = Object.keys(data).filter((key) => !knownFields.has(key))
176
+ if (unknownKeys.length > 0) state.unknownKeys = unknownKeys
157
177
  return state
158
178
  }
159
179
 
@@ -327,6 +347,22 @@ export async function runGoSyncRound(deps: GoRoundDeps): Promise<GoSyncRoundResu
327
347
  })
328
348
  }
329
349
 
350
+ // 0.12.1: fail-closed BEFORE the source fetch (zero side effects, same spirit
351
+ // as the migration gate short-circuit above). Without the host runtime
352
+ // catalog there is no servable write: the 0.12.0 full-listing write is what
353
+ // got rejected by the host in the first place.
354
+ if (deps.hostCatalogIds === null) {
355
+ return withJournal({
356
+ ok: false,
357
+ reason: 'host-catalog-unavailable',
358
+ text: [
359
+ 'opencode-go: host runtime catalog unavailable — 本轮 fail-closed 中止,零写入、零请求。',
360
+ ' 宿主 llm 服务的 discoverModels 未返回目录(服务缺失/未注册/无 opencode-go catalog)。',
361
+ ' 为避免再次写入宿主不认识的模型 id(宿主对整条 mutate fail-closed 拒绝),未做任何写入;目录可用后自动恢复。',
362
+ ].join('\n'),
363
+ })
364
+ }
365
+
330
366
  // B4 (31, design §14.7.5): snapshot the host settings document revision
331
367
  // BEFORE the network wait. This is only a baseline for the post-fetch
332
368
  // freshness check below — never a source for the write plan itself.
@@ -389,6 +425,7 @@ export async function runGoSyncRound(deps: GoRoundDeps): Promise<GoSyncRoundResu
389
425
  const plan = planGoRoutes({
390
426
  keyFingerprint: source.keyFingerprint,
391
427
  entries: source.entries,
428
+ hostCatalogIds: deps.hostCatalogIds,
392
429
  currentRoutes,
393
430
  ownership,
394
431
  ref: config.ref,
@@ -431,6 +468,7 @@ export async function runGoSyncRound(deps: GoRoundDeps): Promise<GoSyncRoundResu
431
468
  overrideStorer: deps.overrideStorer,
432
469
  logger,
433
470
  keyFingerprint: source.keyFingerprint,
471
+ hostCatalogIds: deps.hostCatalogIds,
434
472
  confirmRemovals: config.confirmRemovals,
435
473
  adoptExisting: config.adoptExisting,
436
474
  // B4/N1: the revision this round validated (post-fetch == pre-fetch).
@@ -20,12 +20,14 @@ 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,
26
27
  type GoPlanResult,
27
28
  type GoPlannedRoute,
28
29
  } from './opencode-go-planner.ts'
30
+ import { HOST_CATALOG_PROVIDER } from './opencode-go-host-catalog.ts'
29
31
  import {
30
32
  profilesEqual,
31
33
  type Logger,
@@ -42,11 +44,12 @@ import {
42
44
  import { fingerprintSection } from './opencode-go-migration.ts'
43
45
 
44
46
  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
47
+ // 0.12.0 catalog-reuse: the ONLY route field the writer sets is `apiKeyEnv`.
48
+ // `api`/`baseURL` must stay UNSET (they make the host build the provider from
49
+ // the bare PROTOCOLS implementation — missing `x-opencode-session` → HTTP 400
50
+ // — instead of pi-ai's builtin catalog provider), and `displayName` is a
51
+ // display field deliberately never rewritten so a user rename survives.
52
+ const OWNED_FIELDS = ['apiKeyEnv'] as const
50
53
 
51
54
  // O1-minimal: a settings.mutate can land while the ledger/record write after it
52
55
  // fails. That route is NOT a clean success (no ledger => next round keeps it as
@@ -90,6 +93,16 @@ export interface GoWriterDeps {
90
93
  logger: Logger
91
94
  /** sha256(key) prefix from the source result; `-` when no key. */
92
95
  keyFingerprint: string
96
+ /**
97
+ * Host runtime catalog ids for opencode-go (0.12.1). `undefined` keeps the
98
+ * 0.12.0 writer behavior. With an array the writer (H5): removes
99
+ * deletion-candidates the host catalog does not know IMMEDIATELY (the
100
+ * double-round confirmation deadlocks when round 1's write-back is rejected
101
+ * wholesale and the counter can never persist), and refuses to write any
102
+ * route whose final models array still carries ids outside the catalog
103
+ * (fail-closed with an actionable message instead of a raw host rejection).
104
+ */
105
+ hostCatalogIds?: readonly string[]
93
106
  /** go.confirmRemovals; default 2 (schema min 2, design §6.2.6). */
94
107
  confirmRemovals?: number
95
108
  /**
@@ -128,8 +141,12 @@ export interface GoWriterDeps {
128
141
  * both succeeded, with the ledger-managed ids just committed. The callback
129
142
  * re-persists `appliedFingerprint` through the same store queue. Never called
130
143
  * for a failed write, a no-change round, or another writer's no-op success.
144
+ * H4/M2: the third argument marks a whole-section unset (the ledger key was
145
+ * deleted, not written) so the record update can DROP the route's
146
+ * `appliedManagedIds` key instead of persisting a phantom `[]` entry no
147
+ * ledger backs.
131
148
  */
132
- onOwnWrite?: (route: string, managedIds: string[]) => Promise<void> | void
149
+ onOwnWrite?: (route: string, managedIds: string[], info?: { unset: boolean }) => Promise<void> | void
133
150
  /**
134
151
  * O1/C2: write-ahead journal store. When present together with `profileKey`,
135
152
  * each settings mutate is preceded by a journal slot recording the intended
@@ -398,10 +415,11 @@ async function recordOwnWrite(
398
415
  route: string,
399
416
  managedIds: string[],
400
417
  report: GoPlanReportEntry[],
418
+ unset = false,
401
419
  ): Promise<boolean> {
402
420
  if (deps.onOwnWrite === undefined) return true
403
421
  try {
404
- await deps.onOwnWrite(route, managedIds)
422
+ await deps.onOwnWrite(route, managedIds, { unset })
405
423
  return true
406
424
  } catch (err) {
407
425
  if (isStoreLockTimeout(err)) {
@@ -416,9 +434,13 @@ async function recordOwnWrite(
416
434
  })
417
435
  return false
418
436
  }
419
- // Settings + ledger already landed; a failed fingerprint write is healed at
420
- // the next round (§14.7.4 fingerprint-healed), never a failed route. O1:
421
- // still report it truthfully instead of leaving the record gap silent.
437
+ // Settings + ledger already landed; a failed fingerprint write is NOT a
438
+ // failed route. H4: this failure must reach recordOwnWrite (report +
439
+ // `false`) so the C2 write-ahead journal is KEPT and the next round's
440
+ // reconciliation re-commits the record — "fingerprint-healed" cannot cover
441
+ // it (it only fires on an identity match, and this write changed the
442
+ // identity). O1: still report it truthfully instead of leaving the record
443
+ // gap silent.
422
444
  deps.logger.warn('appliedFingerprint update failed for %s: %s', route, errorText(err))
423
445
  report.push({
424
446
  level: 'warn',
@@ -543,10 +565,11 @@ interface RouteOps {
543
565
  }
544
566
 
545
567
  /**
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).
568
+ * Build one route's ops. Set `apiKeyEnv` + unset any legacy `api`/`baseURL`
569
+ * (or a whole-route `unset`) + set `models`, all in ONE mutate, so a route
570
+ * never ends up with fields from one round and models from another
571
+ * (§6.2.4 atomicity). Returns `undefined` when nothing would change
572
+ * (`profilesEqual` gate).
550
573
  */
551
574
  async function buildRouteOps(
552
575
  planned: GoPlannedRoute,
@@ -555,6 +578,12 @@ async function buildRouteOps(
555
578
  overrideStorer: GoOverrideStorer | undefined,
556
579
  ): Promise<RouteOps | undefined> {
557
580
  const data = rawRoute(desc, planned.route)
581
+ // M3: a planned whole-route unset with NO live section needs only the LEDGER
582
+ // delete — a settings unset of an absent section is a pointless mutate (and
583
+ // a revision bump). Return no ops; the caller's no-change path still deletes
584
+ // the ledger key via persistLedger's unset branch. Checked before any
585
+ // override-store read so the cleanup does zero pointless I/O.
586
+ if (planned.unset && data === undefined) return undefined
558
587
  const settingsOverrides = rawOverrides(desc, planned.route)
559
588
 
560
589
  // Settings key wins; store replay is the fallback (§6.2.4 store-first).
@@ -582,6 +611,21 @@ async function buildRouteOps(
582
611
  ops.push({ op: 'set', path: ['providers', planned.route, field], value: planned.fields[field] })
583
612
  }
584
613
  }
614
+ // Catalog-reuse (H3 scope): only the BUILTIN catalog provider route
615
+ // ('opencode-go') may lose non-empty `api`/`baseURL` — the host reuses
616
+ // pi-ai's builtin catalog provider (and its x-opencode-session wrapping)
617
+ // for that id alone. A custom go.routes.chat name or any other route
618
+ // NEEDS api/baseURL to be servable, so they are preserved. Empty-string
619
+ // fields are broken values the host rejects outright and are stripped
620
+ // everywhere.
621
+ const stripCatalogReuse = planned.route === HOST_CATALOG_PROVIDER
622
+ for (const field of GO_LEGACY_ROUTE_FIELDS) {
623
+ const value = data?.[field]
624
+ if (value === undefined) continue
625
+ if (value === '' || stripCatalogReuse) {
626
+ ops.push({ op: 'unset', path: ['providers', planned.route, field] })
627
+ }
628
+ }
585
629
  const currentRaw = sortedModels(rawModels(desc, planned.route))
586
630
  const mergedSorted = sortedModels(mergedModels)
587
631
  postWriteModels = mergedSorted
@@ -637,6 +681,17 @@ export async function writeGoPlan(plan: GoPlanResult, deps: GoWriterDeps): Promi
637
681
  })
638
682
  }
639
683
 
684
+ // H2: whether the main (chat-slot) route's write landed healthy this round.
685
+ // Legacy route unsets are gated on it — the writer executes routes
686
+ // independently and the host validates route REMOVAL against no catalog, so
687
+ // a failed/conflicted main-route write followed by successful legacy unsets
688
+ // would silently lose the user's non-chat-protocol models.
689
+ const mainRouteReady = (): boolean => {
690
+ const rows = result.routes.filter((row) => row.slot === 'chat')
691
+ return rows.some((row) => row.status === 'wrote' || row.status === 'no-change')
692
+ && !rows.some((row) => row.status === 'failed' || row.status === 'conflict')
693
+ }
694
+
640
695
  const desc = settings === undefined ? undefined : findLlmDescriptor(settings)
641
696
  if (settings === undefined || desc === undefined) {
642
697
  for (const planned of plan.routes) {
@@ -662,6 +717,20 @@ export async function writeGoPlan(plan: GoPlanResult, deps: GoWriterDeps): Promi
662
717
  continue
663
718
  }
664
719
 
720
+ // H2: legacy teardown is gated on a healthy main-route write this round
721
+ // (see mainRouteReady above). No settings write, no ledger touch.
722
+ if (planned.unset && planned.slot !== 'chat' && !mainRouteReady()) {
723
+ result.routes.push({ route: planned.route, slot: planned.slot, status: 'skipped', reason: 'main-route-not-ready' })
724
+ report.push({
725
+ level: 'warn',
726
+ code: 'main-route-not-ready',
727
+ route: planned.route,
728
+ slot: planned.slot,
729
+ message: `legacy route ${planned.route} unset deferred: the main route write did not land this round; no teardown while the managed route is not healthy`,
730
+ })
731
+ continue
732
+ }
733
+
665
734
  // Single-writer second gate (§14.7.5): re-read the persisted status here,
666
735
  // never reuse the round-level snapshot. A route whose authority was revoked
667
736
  // between the round gate and this point is skipped with a report line —
@@ -704,10 +773,32 @@ export async function writeGoPlan(plan: GoPlanResult, deps: GoWriterDeps): Promi
704
773
  // --- Double-round deletion confirmation (V5) ---------------------------
705
774
  // The planner flags a candidate after its three gates pass; only the
706
775
  // writer knows how many consecutive successful rounds have flagged it.
776
+ // H5: a candidate the HOST RUNTIME CATALOG does not know skips the counter
777
+ // entirely — the host rejects the whole models array on such an id, so
778
+ // round 1's write-back fails and the counter can never persist (a
779
+ // permanent write-failed loop). Removing it immediately is what restores
780
+ // writability; the id auto-returns when the host upgrades.
781
+ //
782
+ // P1-1 scope: that rejection exists only for the route reusing the builtin
783
+ // catalog (chat slot + the builtin provider id). A custom go.routes.chat
784
+ // name keeps its own api/baseURL and is never validated against the
785
+ // runtime catalog, so its deletions follow the normal two-round path.
786
+ const enforcesHostCatalog = planned.slot === 'chat' && planned.route === HOST_CATALOG_PROVIDER
787
+ const hostSet = enforcesHostCatalog && deps.hostCatalogIds !== undefined
788
+ ? new Set(deps.hostCatalogIds)
789
+ : undefined
707
790
  const missing: Record<string, number> = { ...(prior?.missing ?? {}) }
708
791
  const finalModels = [...planned.models]
709
792
  for (const candidate of candidates) {
710
793
  const id = candidate.id!
794
+ const hostUnknown = hostSet !== undefined && !hostSet.has(id)
795
+ if (hostUnknown) {
796
+ // Confirmed immediately: let the planner's exclusion stand — delete.
797
+ delete missing[id]
798
+ candidate.code = 'deleted'
799
+ candidate.message = `model ${id} removed immediately: the host runtime catalog does not know it (its presence would make the host reject every mutate); it auto-returns after the host upgrades`
800
+ continue
801
+ }
711
802
  const seen = missing[id] ?? 0
712
803
  if (seen + 1 < confirmRemovals) {
713
804
  // Round 1 of 2 (or earlier for a larger threshold): keep the model.
@@ -734,6 +825,27 @@ export async function writeGoPlan(plan: GoPlanResult, deps: GoWriterDeps): Promi
734
825
  }
735
826
  const sortedFinal = sortedModels(finalModels)
736
827
 
828
+ // H5 (fail-closed): refuse the route write when the FINAL models array
829
+ // would still carry ids the host runtime catalog does not know — the host
830
+ // rejects the whole mutate, so writing is guaranteed to fail while
831
+ // pretending otherwise. Zero writes for this route; the report names the
832
+ // ids and both actionable exits.
833
+ if (hostSet !== undefined && !planned.unset) {
834
+ const unknownIds = sortedFinal.filter((model) => !hostSet.has(model.id)).map((model) => model.id)
835
+ if (unknownIds.length > 0) {
836
+ result.routes.push({ route: planned.route, slot: planned.slot, status: 'failed', reason: 'host-catalog-unknown-models' })
837
+ result.failedRoutes.push({ route: planned.route, reason: 'host-catalog-unknown-models' })
838
+ report.push({
839
+ level: 'error',
840
+ code: 'host-catalog-unknown-models',
841
+ route: planned.route,
842
+ slot: planned.slot,
843
+ message: `route ${planned.route} not written: ${unknownIds.join(', ')} are not in the host runtime catalog and the host would reject the whole mutate — keep them on a custom route (with api/baseURL) or wait for the host upgrade; zero settings writes for this route`,
844
+ })
845
+ continue
846
+ }
847
+ }
848
+
737
849
  // --- Ledger to persist if this route's write succeeds ------------------
738
850
  const nextManaged: Record<string, GoManagedModel> = { ...(plan.nextOwnership[key]?.managed ?? {}) }
739
851
  // A pending candidate is still plugin-managed: keep it in the ledger so a
@@ -1064,7 +1176,7 @@ export async function writeGoPlan(plan: GoPlanResult, deps: GoWriterDeps): Promi
1064
1176
  }
1065
1177
  if (commit.committed) {
1066
1178
  const recordPersisted = await recordOwnWrite(
1067
- deps, planned.route, planned.unset ? [] : Object.keys(nextEntry.managed).sort(), report,
1179
+ deps, planned.route, planned.unset ? [] : Object.keys(nextEntry.managed).sort(), report, planned.unset,
1068
1180
  )
1069
1181
  // C2: only a fully accounted write (settings + ledger + record) closes the
1070
1182
  // journal. A failed record persist (S1b) keeps it so the next round's