@aiwayds/dsh-model-sync 0.12.1 → 0.13.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 (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 +122 -0
  10. package/lib/official-migrate.js +653 -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 +863 -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
@@ -0,0 +1,371 @@
1
+ /**
2
+ * Full-ownership Official Sync round engine.
3
+ *
4
+ * Once a profile has migrated a vendor's Builtin Provider into Managed Custom
5
+ * Providers, each sync round:
6
+ * 1. Confirms a profile-scoped OfficialMigrationRecord exists (otherwise no-op).
7
+ * 2. Resolves the API key via the stored `apiKeyEnv` (or adapter fallbacks).
8
+ * 3. Fetches & plans the latest official models via the UpstreamProviderAdapter.
9
+ * 4. On fetch failure or empty result: leaves all settings untouched (last-good).
10
+ * 5. Compares each active Managed Custom Provider structurally against
11
+ * `llm-pi-ai.user.providers`, writes changed providers, and unsets any
12
+ * managed Protocol Slot that became empty.
13
+ *
14
+ * @module dsh-model-sync/official-sync
15
+ */
16
+
17
+ import { diffEntries } from './diff.ts'
18
+ import type { SettingsModelProfile } from './translate.ts'
19
+ import type { Logger, SettingsDescriptor, SettingsMutationOp, SettingsService } from './writer.ts'
20
+ import type { GoFailureKind, GoFetchLike } from './opencode-go-source.ts'
21
+ import type {
22
+ CompatHintsByProtocol,
23
+ CustomProviderSpec,
24
+ OfficialAdapterConfig,
25
+ UpstreamProviderAdapter,
26
+ } from './official-adapter.ts'
27
+ import type { OfficialMigrationRecord, OfficialMigrationStore } from './official-store.ts'
28
+
29
+ export interface CredentialsLike {
30
+ resolve(ref: string): Promise<{ value: string } | undefined>
31
+ }
32
+
33
+ export interface LaunchEnvLike {
34
+ get(name: string): { value: string } | undefined
35
+ }
36
+
37
+ export interface OfficialCredentialContext {
38
+ get(name: 'credentials'): CredentialsLike | undefined
39
+ get(name: 'launchEnvironment'): LaunchEnvLike | undefined
40
+ get(name: string): unknown
41
+ }
42
+
43
+ export interface ResolvedCredential {
44
+ ref: string
45
+ value?: string
46
+ }
47
+
48
+ const REF_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/
49
+
50
+ /**
51
+ * Resolve a credential reference value across `ctx.credentials` and
52
+ * `ctx.launchEnvironment` (falling back to `process.env`).
53
+ */
54
+ export async function resolveCredentialByRefs(
55
+ ctx: OfficialCredentialContext,
56
+ refs: readonly string[],
57
+ ): Promise<ResolvedCredential> {
58
+ const uniqueRefs = [...new Set(refs.map((r) => r.trim()).filter((r) => r.length > 0))]
59
+ const credentials = ctx.get('credentials')
60
+ const launchEnv = ctx.get('launchEnvironment')
61
+
62
+ for (const ref of uniqueRefs) {
63
+ if (REF_PATTERN.test(ref) && credentials !== undefined) {
64
+ try {
65
+ const resolved = await credentials.resolve(ref)
66
+ if (resolved !== undefined && typeof resolved.value === 'string' && resolved.value.length > 0) {
67
+ return { ref, value: resolved.value }
68
+ }
69
+ } catch {
70
+ // Fall through to launchEnvironment / next ref
71
+ }
72
+ }
73
+ const envEntry = launchEnv !== undefined
74
+ ? launchEnv.get(ref)
75
+ : (process.env[ref] ? { value: process.env[ref]! } : undefined)
76
+ if (envEntry !== undefined && typeof envEntry.value === 'string' && envEntry.value.length > 0) {
77
+ return { ref, value: envEntry.value }
78
+ }
79
+ }
80
+
81
+ return { ref: uniqueRefs[0] ?? '' }
82
+ }
83
+
84
+ /** Materialize a CustomProviderSpec into the exact `llm-pi-ai` provider object. */
85
+ export function buildCustomProviderValue(spec: CustomProviderSpec): Record<string, unknown> {
86
+ const out: Record<string, unknown> = {
87
+ displayName: spec.displayName,
88
+ api: spec.api,
89
+ baseURL: spec.baseURL,
90
+ apiKeyEnv: spec.apiKeyEnv,
91
+ models: spec.models,
92
+ }
93
+ if (spec.compat !== undefined && Object.keys(spec.compat).length > 0) {
94
+ out.compat = spec.compat
95
+ }
96
+ if (spec.headers !== undefined && Object.keys(spec.headers).length > 0) {
97
+ out.headers = spec.headers
98
+ }
99
+ return out
100
+ }
101
+
102
+ function normalizeJsonValue(value: unknown): unknown {
103
+ if (Array.isArray(value)) return value.map(normalizeJsonValue)
104
+ if (value !== null && typeof value === 'object') {
105
+ const out: Record<string, unknown> = {}
106
+ for (const key of Object.keys(value as Record<string, unknown>).sort()) {
107
+ const child = (value as Record<string, unknown>)[key]
108
+ if (child !== undefined) out[key] = normalizeJsonValue(child)
109
+ }
110
+ return out
111
+ }
112
+ return value
113
+ }
114
+
115
+ export function canonicalDeepEqual(a: unknown, b: unknown): boolean {
116
+ return JSON.stringify(normalizeJsonValue(a)) === JSON.stringify(normalizeJsonValue(b))
117
+ }
118
+
119
+ export interface OfficialSyncDeps {
120
+ adapter: UpstreamProviderAdapter
121
+ config: OfficialAdapterConfig
122
+ settings: SettingsService | undefined
123
+ migrationStore: OfficialMigrationStore | undefined
124
+ credentialCtx: OfficialCredentialContext
125
+ logger: Logger
126
+ timeoutMs?: number
127
+ signal?: AbortSignal
128
+ fetchImpl?: GoFetchLike
129
+ detectHostSessionHeader?: () => boolean
130
+ loadPiAiCompatHints?: () => CompatHintsByProtocol
131
+ }
132
+
133
+ export interface OfficialSyncRoundResult {
134
+ ok: boolean
135
+ changed: boolean
136
+ reason:
137
+ | 'wrote'
138
+ | 'no-change'
139
+ | 'not-migrated'
140
+ | 'no-key'
141
+ | 'source-failed'
142
+ | 'settings-unavailable'
143
+ | 'mutate-rejected'
144
+ | 'conflict-retry-failed'
145
+ text: string
146
+ failureKind?: GoFailureKind
147
+ warnings?: string[]
148
+ }
149
+
150
+ const SETTINGS_CONFLICT = 'SETTINGS_CONFLICT'
151
+
152
+ function isConflictError(error: unknown): boolean {
153
+ return typeof error === 'object' && error !== null && (error as { code?: unknown }).code === SETTINGS_CONFLICT
154
+ }
155
+
156
+ function summarizeProviderDiff(
157
+ routeId: string,
158
+ prevSection: Record<string, unknown> | undefined,
159
+ nextModels: SettingsModelProfile[],
160
+ action: 'create' | 'update' | 'remove',
161
+ ): string {
162
+ if (action === 'remove') return `${routeId}: removed (protocol slot empty)`
163
+ if (action === 'create' || prevSection === undefined || !Array.isArray(prevSection.models)) {
164
+ return `${routeId}: created (${nextModels.length} models)`
165
+ }
166
+ const diff = diffEntries(prevSection.models as SettingsModelProfile[], nextModels)
167
+ const parts: string[] = []
168
+ if (diff.added.length > 0) parts.push(`+${diff.added.join(', +')}`)
169
+ if (diff.removed.length > 0) parts.push(`-${diff.removed.join(', -')}`)
170
+ if (diff.changed.length > 0) parts.push(`~${diff.changed.join(', ~')}`)
171
+ if (parts.length === 0) return `${routeId}: updated provider settings (${nextModels.length} models)`
172
+ return `${routeId}: ${parts.join('; ')} (${nextModels.length} models)`
173
+ }
174
+
175
+ function computeSyncOps(
176
+ llmDesc: SettingsDescriptor,
177
+ defaultModelDesc: SettingsDescriptor | undefined,
178
+ record: OfficialMigrationRecord,
179
+ adapter: UpstreamProviderAdapter,
180
+ config: OfficialAdapterConfig,
181
+ specs: readonly CustomProviderSpec[],
182
+ ): { ops: SettingsMutationOp[]; lines: string[]; warnings: string[]; nextManagedRoutes: string[] } {
183
+ const currentProviders = (llmDesc.user?.providers as Record<string, unknown> | undefined) ?? {}
184
+ const activeRouteIds = new Set(specs.map((s) => s.routeId))
185
+ const ops: SettingsMutationOp[] = []
186
+ const lines: string[] = []
187
+ const warnings: string[] = []
188
+
189
+ for (const spec of specs) {
190
+ const nextObj = buildCustomProviderValue(spec)
191
+ const prevObj = currentProviders[spec.routeId] as Record<string, unknown> | undefined
192
+ if (canonicalDeepEqual(prevObj, nextObj)) {
193
+ lines.push(`${spec.routeId}: up to date (${spec.models.length} models)`)
194
+ continue
195
+ }
196
+ ops.push({ op: 'set', path: ['providers', spec.routeId], value: nextObj })
197
+ lines.push(summarizeProviderDiff(
198
+ spec.routeId,
199
+ prevObj,
200
+ spec.models,
201
+ prevObj === undefined ? 'create' : 'update',
202
+ ))
203
+ }
204
+
205
+ const candidateCleanup = new Set<string>([
206
+ ...record.managedRoutes,
207
+ ...Object.values(config.routes),
208
+ ])
209
+ candidateCleanup.delete(adapter.builtinProviderId)
210
+
211
+ const defaultProvider = defaultModelDesc?.user?.provider as string | undefined
212
+ for (const routeId of candidateCleanup) {
213
+ if (activeRouteIds.has(routeId)) continue
214
+ if (currentProviders[routeId] === undefined) continue
215
+ ops.push({ op: 'unset', path: ['providers', routeId] })
216
+ lines.push(summarizeProviderDiff(routeId, undefined, [], 'remove'))
217
+ if (defaultProvider === routeId) {
218
+ warnings.push(`warning: agent-default-model points to removed empty slot "${routeId}"; please switch your default model.`)
219
+ }
220
+ }
221
+
222
+ const nextManagedRoutes = specs.map((s) => s.routeId)
223
+ return { ops, lines, warnings, nextManagedRoutes }
224
+ }
225
+
226
+ export async function runOfficialSyncRound(deps: OfficialSyncDeps): Promise<OfficialSyncRoundResult> {
227
+ const { adapter, config, settings, migrationStore, logger } = deps
228
+ const alias = adapter.aliases[0] ?? adapter.id
229
+
230
+ if (migrationStore === undefined) {
231
+ return {
232
+ ok: false,
233
+ changed: false,
234
+ reason: 'not-migrated',
235
+ text: `${adapter.id}: profile identity unavailable — run inside a dsh profile`,
236
+ }
237
+ }
238
+
239
+ const record = await migrationStore.read()
240
+ if (record === undefined) {
241
+ return {
242
+ ok: false,
243
+ changed: false,
244
+ reason: 'not-migrated',
245
+ text: `${adapter.id}: not migrated yet — run \`/model-sync migrate ${alias}\` first (zero writes).`,
246
+ }
247
+ }
248
+
249
+ const resolvedKey = await resolveCredentialByRefs(
250
+ deps.credentialCtx,
251
+ [record.apiKeyEnv, ...adapter.defaultKeyRefs],
252
+ )
253
+ if (resolvedKey.value === undefined) {
254
+ return {
255
+ ok: false,
256
+ changed: false,
257
+ reason: 'no-key',
258
+ failureKind: 'no-key',
259
+ text: `${adapter.id}: credential ${resolvedKey.ref} not configured — skipped (last-good preserved).`,
260
+ }
261
+ }
262
+
263
+ const fetched = await adapter.fetchAndPlan({
264
+ apiKey: resolvedKey.value,
265
+ apiKeyEnv: resolvedKey.ref,
266
+ config,
267
+ timeoutMs: deps.timeoutMs,
268
+ signal: deps.signal,
269
+ fetchImpl: deps.fetchImpl,
270
+ detectHostSessionHeader: deps.detectHostSessionHeader,
271
+ loadPiAiCompatHints: deps.loadPiAiCompatHints,
272
+ })
273
+
274
+ if (!fetched.ok || fetched.providers.length === 0) {
275
+ const errMsg = fetched.error?.message ?? 'official listing unavailable or empty'
276
+ return {
277
+ ok: false,
278
+ changed: false,
279
+ reason: 'source-failed',
280
+ failureKind: fetched.failureKind ?? 'transport',
281
+ text: `${adapter.id}: fetch failed (${errMsg}) — kept last-good models.`,
282
+ }
283
+ }
284
+
285
+ if (settings === undefined) {
286
+ return {
287
+ ok: false,
288
+ changed: false,
289
+ reason: 'settings-unavailable',
290
+ text: `${adapter.id}: settings service unavailable — skipped.`,
291
+ }
292
+ }
293
+
294
+ const applyWithDescriptor = async (): Promise<OfficialSyncRoundResult> => {
295
+ const descs = settings.describe()
296
+ const llmDesc = descs.find((d) => d.ns === 'llm-pi-ai')
297
+ if (llmDesc === undefined) {
298
+ return {
299
+ ok: false,
300
+ changed: false,
301
+ reason: 'settings-unavailable',
302
+ text: `${adapter.id}: llm-pi-ai namespace not registered — skipped.`,
303
+ }
304
+ }
305
+ const defaultModelDesc = descs.find((d) => d.ns === 'agent-default-model')
306
+ const plan = computeSyncOps(llmDesc, defaultModelDesc, record, adapter, config, fetched.providers)
307
+ const allWarnings = [...fetched.warnings, ...plan.warnings]
308
+ const sessionNote = fetched.sessionHeaderApplied
309
+ ? 'session-header: static fallback'
310
+ : 'session-header: host-native'
311
+
312
+ if (plan.ops.length === 0) {
313
+ if (!canonicalDeepEqual(record.managedRoutes, plan.nextManagedRoutes)) {
314
+ await migrationStore.write({ ...record, managedRoutes: plan.nextManagedRoutes })
315
+ }
316
+ return {
317
+ ok: true,
318
+ changed: false,
319
+ reason: 'no-change',
320
+ warnings: allWarnings,
321
+ text: [
322
+ `${adapter.id}: up to date (${fetched.totalModels} models across ${fetched.providers.length} custom providers; ${sessionNote})`,
323
+ ...plan.lines,
324
+ ...allWarnings,
325
+ ].join('\n'),
326
+ }
327
+ }
328
+
329
+ await settings.mutate('llm-pi-ai', plan.ops, llmDesc.revision)
330
+ if (!canonicalDeepEqual(record.managedRoutes, plan.nextManagedRoutes)) {
331
+ await migrationStore.write({ ...record, managedRoutes: plan.nextManagedRoutes })
332
+ }
333
+ return {
334
+ ok: true,
335
+ changed: true,
336
+ reason: 'wrote',
337
+ warnings: allWarnings,
338
+ text: [
339
+ `${adapter.id}: synced ${fetched.totalModels} models across ${fetched.providers.length} custom providers (${sessionNote})`,
340
+ ...plan.lines,
341
+ ...allWarnings,
342
+ ].join('\n'),
343
+ }
344
+ }
345
+
346
+ try {
347
+ return await applyWithDescriptor()
348
+ } catch (err) {
349
+ if (isConflictError(err)) {
350
+ logger.debug('model-sync: %s settings conflict, retrying once', adapter.id)
351
+ try {
352
+ return await applyWithDescriptor()
353
+ } catch (retryErr) {
354
+ const msg = retryErr instanceof Error ? retryErr.message : String(retryErr)
355
+ return {
356
+ ok: false,
357
+ changed: false,
358
+ reason: isConflictError(retryErr) ? 'conflict-retry-failed' : 'mutate-rejected',
359
+ text: `${adapter.id}: settings write failed after retry (${msg}).`,
360
+ }
361
+ }
362
+ }
363
+ const msg = err instanceof Error ? err.message : String(err)
364
+ return {
365
+ ok: false,
366
+ changed: false,
367
+ reason: 'mutate-rejected',
368
+ text: `${adapter.id}: settings validation rejected write (${msg}).`,
369
+ }
370
+ }
371
+ }