@aiwayds/dsh-model-sync 0.12.0 → 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 (84) hide show
  1. package/README.md +18 -17
  2. package/README.zh-CN.md +18 -17
  3. package/lib/index.d.ts +54 -376
  4. package/lib/index.js +305 -1049
  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 +351 -1214
  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 -75
  42. package/lib/opencode-go-diagnose.js +0 -146
  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-journal.d.ts +0 -110
  48. package/lib/opencode-go-journal.js +0 -406
  49. package/lib/opencode-go-journal.js.map +0 -1
  50. package/lib/opencode-go-migrate.d.ts +0 -345
  51. package/lib/opencode-go-migrate.js +0 -1371
  52. package/lib/opencode-go-migrate.js.map +0 -1
  53. package/lib/opencode-go-migration.d.ts +0 -227
  54. package/lib/opencode-go-migration.js +0 -384
  55. package/lib/opencode-go-migration.js.map +0 -1
  56. package/lib/opencode-go-one-shot.d.ts +0 -276
  57. package/lib/opencode-go-one-shot.js +0 -1096
  58. package/lib/opencode-go-one-shot.js.map +0 -1
  59. package/lib/opencode-go-planner.d.ts +0 -154
  60. package/lib/opencode-go-planner.js +0 -305
  61. package/lib/opencode-go-planner.js.map +0 -1
  62. package/lib/opencode-go-scheduler.d.ts +0 -128
  63. package/lib/opencode-go-scheduler.js +0 -241
  64. package/lib/opencode-go-scheduler.js.map +0 -1
  65. package/lib/opencode-go-store.d.ts +0 -18
  66. package/lib/opencode-go-store.js +0 -68
  67. package/lib/opencode-go-store.js.map +0 -1
  68. package/lib/opencode-go-sync.d.ts +0 -94
  69. package/lib/opencode-go-sync.js +0 -364
  70. package/lib/opencode-go-sync.js.map +0 -1
  71. package/lib/opencode-go-writer.d.ts +0 -132
  72. package/lib/opencode-go-writer.js +0 -977
  73. package/lib/opencode-go-writer.js.map +0 -1
  74. package/src/opencode-go-diagnose.ts +0 -223
  75. package/src/opencode-go-grouping.ts +0 -26
  76. package/src/opencode-go-journal.ts +0 -458
  77. package/src/opencode-go-migrate.ts +0 -1764
  78. package/src/opencode-go-migration.ts +0 -552
  79. package/src/opencode-go-one-shot.ts +0 -1356
  80. package/src/opencode-go-planner.ts +0 -472
  81. package/src/opencode-go-scheduler.ts +0 -315
  82. package/src/opencode-go-store.ts +0 -73
  83. package/src/opencode-go-sync.ts +0 -503
  84. package/src/opencode-go-writer.ts +0 -1201
@@ -0,0 +1,494 @@
1
+ /**
2
+ * OpenCode Go Upstream Provider Adapter.
3
+ *
4
+ * Maps OpenCode Go's official `/v1/models` listing into up to four
5
+ * protocol-specific Managed Custom Providers (`opencode-go-chat`,
6
+ * `opencode-go-msg`, `opencode-go-resp`, `opencode-go-google`).
7
+ *
8
+ * Rules:
9
+ * - Official `/v1/models` is 100% the source of truth — never intersect with
10
+ * or filter against the host's bundled pi-ai catalog.
11
+ * - Multi-protocol models are assigned to a single Protocol Slot using
12
+ * `recommended_api` (with deterministic priority fallback) to avoid duplicate
13
+ * entries across providers.
14
+ * - Optional pi-ai compat hints are strictly filtered by dsh-llm-pi-ai's
15
+ * offered compat keys per wire protocol (withheld keys are never written).
16
+ * - `sessionHeader: 'auto'` probes the running host's `@earendil-works/pi-ai`
17
+ * for `getOpenCodeSessionHeaders` and injects a static `x-opencode-session`
18
+ * header only when the running host lacks native per-session injection.
19
+ *
20
+ * @module dsh-model-sync/opencode-go-adapter
21
+ */
22
+
23
+ import { existsSync, readFileSync, realpathSync } from 'node:fs'
24
+ import { createRequire } from 'node:module'
25
+ import { dirname, join } from 'node:path'
26
+ import type { SettingsModelProfile } from './translate.ts'
27
+ import {
28
+ OPENCODE_GO_DEFAULT_INTERVAL_MINUTES,
29
+ OPENCODE_GO_MODELS_URL,
30
+ fetchGoOfficialModels,
31
+ type GoModelRecord,
32
+ } from './opencode-go-source.ts'
33
+ import type {
34
+ CompatHintsByProtocol,
35
+ CustomProviderSpec,
36
+ OfficialFetchOptions,
37
+ OfficialFetchResult,
38
+ UpstreamProviderAdapter,
39
+ } from './official-adapter.ts'
40
+
41
+ export type OpenCodeGoSlot = 'chat' | 'msg' | 'resp' | 'google'
42
+
43
+ export const OPENCODE_GO_SLOTS: readonly OpenCodeGoSlot[] = ['chat', 'msg', 'resp', 'google']
44
+
45
+ export const OPENCODE_GO_SLOT_ROUTES: Readonly<Record<OpenCodeGoSlot, string>> = {
46
+ chat: 'opencode-go-chat',
47
+ msg: 'opencode-go-msg',
48
+ resp: 'opencode-go-resp',
49
+ google: 'opencode-go-google',
50
+ }
51
+
52
+ interface SlotDefinition {
53
+ slot: OpenCodeGoSlot
54
+ displayName: string
55
+ api: string
56
+ defaultBaseUrl: string
57
+ routeCompat?: Record<string, unknown>
58
+ }
59
+
60
+ const SLOT_DEFINITIONS: Readonly<Record<OpenCodeGoSlot, SlotDefinition>> = {
61
+ chat: {
62
+ slot: 'chat',
63
+ displayName: 'OpenCode Go (Chat)',
64
+ api: 'openai-completions',
65
+ defaultBaseUrl: 'https://opencode.ai/inference/go/openai/v1',
66
+ routeCompat: {
67
+ supportsStore: false,
68
+ maxTokensField: 'max_tokens',
69
+ },
70
+ },
71
+ msg: {
72
+ slot: 'msg',
73
+ displayName: 'OpenCode Go (Messages)',
74
+ api: 'anthropic-messages',
75
+ defaultBaseUrl: 'https://opencode.ai/inference/go/anthropic',
76
+ },
77
+ resp: {
78
+ slot: 'resp',
79
+ displayName: 'OpenCode Go (Responses)',
80
+ api: 'openai-responses',
81
+ defaultBaseUrl: 'https://opencode.ai/inference/go/openai/v1',
82
+ },
83
+ google: {
84
+ slot: 'google',
85
+ displayName: 'OpenCode Go (Google)',
86
+ api: 'google-generative-ai',
87
+ defaultBaseUrl: 'https://opencode.ai/inference/go/google/v1beta',
88
+ },
89
+ }
90
+
91
+ const PROTOCOL_TO_SLOT: Readonly<Record<string, OpenCodeGoSlot>> = {
92
+ 'chat-completions': 'chat',
93
+ messages: 'msg',
94
+ responses: 'resp',
95
+ 'generate-content': 'google',
96
+ interactions: 'google',
97
+ }
98
+
99
+ const PROTOCOL_PRIORITY: readonly string[] = [
100
+ 'chat-completions',
101
+ 'messages',
102
+ 'responses',
103
+ 'generate-content',
104
+ 'interactions',
105
+ ]
106
+
107
+ const THINKING_LEVELS = new Set(['off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'])
108
+
109
+ /**
110
+ * Exact set of compat fields offered by `dsh-llm-pi-ai` per protocol.
111
+ * Withheld pi-ai fields (e.g. `supportsMidConvoSystemMessages`,
112
+ * `sessionAffinityFormat`, `supportsAdditionalTools`) MUST NOT be written to
113
+ * Custom Providers or `dsh-llm-pi-ai` strict validation rejects the write.
114
+ */
115
+ const OFFERED_COMPAT_KEYS: Readonly<Record<string, ReadonlySet<string>>> = {
116
+ 'openai-completions': new Set([
117
+ 'supportsStore',
118
+ 'supportsDeveloperRole',
119
+ 'supportsReasoningEffort',
120
+ 'supportsUsageInStreaming',
121
+ 'supportsFinishReason',
122
+ 'maxTokensField',
123
+ 'requiresToolResultName',
124
+ 'requiresAssistantAfterToolResult',
125
+ 'requiresThinkingAsText',
126
+ 'requiresReasoningContentOnAssistantMessages',
127
+ 'thinkingFormat',
128
+ 'chatTemplateKwargs',
129
+ 'chatTemplateArgs',
130
+ 'supportsThinkingTokenBudget',
131
+ 'thinkingTokenBudgetField',
132
+ 'vllmPriority',
133
+ 'supportsStrictMode',
134
+ 'cacheControlFormat',
135
+ 'supportsLongCacheRetention',
136
+ ]),
137
+ 'openai-responses': new Set([
138
+ 'supportsDeveloperRole',
139
+ 'supportsMaxOutputTokens',
140
+ 'supportsStrictMode',
141
+ 'supportsLongCacheRetention',
142
+ ]),
143
+ 'anthropic-messages': new Set([
144
+ 'supportsEagerToolInputStreaming',
145
+ 'supportsLongCacheRetention',
146
+ 'supportsCacheControlOnTools',
147
+ 'supportsTemperature',
148
+ 'forceAdaptiveThinking',
149
+ 'allowEmptySignature',
150
+ 'supportsStrictTools',
151
+ ]),
152
+ 'google-generative-ai': new Set(),
153
+ }
154
+
155
+ export const OPENCODE_STATIC_SESSION_HEADERS: Readonly<Record<string, string>> = {
156
+ 'x-opencode-session': 'dsh-opencode-go',
157
+ }
158
+
159
+ /**
160
+ * Normalize an official `base_url` for the target wire protocol.
161
+ * `anthropic-messages` appends `/v1/messages` internally, so a trailing `/v1`
162
+ * from `/v1/models` must be stripped.
163
+ */
164
+ export function normalizeSlotBaseUrl(api: string, rawBaseUrl: string | undefined, fallback: string): string {
165
+ const candidate = typeof rawBaseUrl === 'string' && rawBaseUrl.trim().length > 0
166
+ ? rawBaseUrl.trim().replace(/\/+$/, '')
167
+ : fallback
168
+ if (api === 'anthropic-messages') {
169
+ return candidate.replace(/\/v1$/, '')
170
+ }
171
+ return candidate
172
+ }
173
+
174
+ /** Choose the single protocol + slot for an official model entry. */
175
+ export function pickOfficialProtocol(entry: GoModelRecord): { protocol: string; slot: OpenCodeGoSlot } | undefined {
176
+ if (entry.recommendedProtocol !== undefined && entry.protocols.includes(entry.recommendedProtocol)) {
177
+ const slot = PROTOCOL_TO_SLOT[entry.recommendedProtocol]
178
+ if (slot !== undefined) return { protocol: entry.recommendedProtocol, slot }
179
+ }
180
+ for (const candidate of PROTOCOL_PRIORITY) {
181
+ if (entry.protocols.includes(candidate)) {
182
+ const slot = PROTOCOL_TO_SLOT[candidate]
183
+ if (slot !== undefined) return { protocol: candidate, slot }
184
+ }
185
+ }
186
+ for (const candidate of entry.protocols) {
187
+ const slot = PROTOCOL_TO_SLOT[candidate]
188
+ if (slot !== undefined) return { protocol: candidate, slot }
189
+ }
190
+ return undefined
191
+ }
192
+
193
+ export function filterOfferedCompat(
194
+ api: string,
195
+ rawCompat: Readonly<Record<string, unknown>> | undefined,
196
+ ): Record<string, unknown> | undefined {
197
+ if (rawCompat === undefined) return undefined
198
+ const allowed = OFFERED_COMPAT_KEYS[api]
199
+ if (allowed === undefined || allowed.size === 0) return undefined
200
+ const out: Record<string, unknown> = {}
201
+ for (const [key, value] of Object.entries(rawCompat)) {
202
+ if (allowed.has(key) && value !== undefined) {
203
+ out[key] = value
204
+ }
205
+ }
206
+ return Object.keys(out).length > 0 ? out : undefined
207
+ }
208
+
209
+ /** Map one normalized official record to a Custom Provider model profile. */
210
+ export function mapGoRecordToCustomProfile(
211
+ entry: GoModelRecord,
212
+ api: string,
213
+ compatHint?: Readonly<Record<string, unknown>>,
214
+ ): SettingsModelProfile {
215
+ const profile: SettingsModelProfile = { id: entry.id }
216
+ if (entry.name.length > 0) profile.name = entry.name
217
+ if (entry.contextWindow !== undefined) profile.contextWindow = entry.contextWindow
218
+ const effectiveContext = entry.contextWindow ?? 1_000_000
219
+ if (entry.maxOutput !== undefined && entry.maxOutput < effectiveContext) {
220
+ profile.maxTokens = entry.maxOutput
221
+ }
222
+ if (entry.inputModalities.length > 0) {
223
+ profile.input = [...entry.inputModalities]
224
+ }
225
+ if (entry.reasoning?.supported === true && entry.reasoning.efforts.length > 0) {
226
+ const efforts: Record<string, string | null> = {}
227
+ let hasNonOffLevel = false
228
+ for (const rawEffort of entry.reasoning.efforts) {
229
+ if (!THINKING_LEVELS.has(rawEffort)) continue
230
+ if (rawEffort === 'off') {
231
+ efforts.off = null
232
+ } else {
233
+ efforts[rawEffort] = rawEffort
234
+ hasNonOffLevel = true
235
+ }
236
+ }
237
+ if (hasNonOffLevel) {
238
+ profile.reasoningEfforts = efforts
239
+ }
240
+ }
241
+ const compat = filterOfferedCompat(api, compatHint)
242
+ if (compat !== undefined) {
243
+ profile.compat = compat as SettingsModelProfile['compat']
244
+ }
245
+ return profile
246
+ }
247
+
248
+ /**
249
+ * Locate the running host's `@earendil-works/pi-ai` package root.
250
+ * Checks the running process (Electron `app.asar` / `process.argv[1]` /
251
+ * module resolution) BEFORE `DSH_CLOSURE_DIR`, so an older Electron Desktop
252
+ * runtime is never misidentified from a newer CLI `dsh` install.
253
+ */
254
+ function resolveHostPiAiRoots(): string[] {
255
+ const candidates: string[] = []
256
+ const tryResolveFromBase = (baseFile: string): void => {
257
+ try {
258
+ const req = createRequire(baseFile)
259
+ try {
260
+ const dshPiAiPkg = req.resolve('@deepseek-ai/dsh-llm-pi-ai/package.json')
261
+ const hostReq = createRequire(dshPiAiPkg)
262
+ candidates.push(dirname(hostReq.resolve('@earendil-works/pi-ai/package.json')))
263
+ } catch {
264
+ // Not found via dsh-llm-pi-ai; try direct pi-ai resolution
265
+ }
266
+ try {
267
+ candidates.push(dirname(req.resolve('@earendil-works/pi-ai/package.json')))
268
+ } catch {
269
+ // ignore
270
+ }
271
+ } catch {
272
+ // ignore invalid base path
273
+ }
274
+ }
275
+
276
+ const resPath = (process as { resourcesPath?: string }).resourcesPath
277
+ if (typeof resPath === 'string' && resPath.length > 0) {
278
+ const asarPkg = join(resPath, 'app.asar', 'package.json')
279
+ if (existsSync(asarPkg)) tryResolveFromBase(asarPkg)
280
+ }
281
+
282
+ if (typeof process.argv[1] === 'string' && process.argv[1].length > 0) {
283
+ try {
284
+ tryResolveFromBase(realpathSync(process.argv[1]))
285
+ } catch {
286
+ tryResolveFromBase(process.argv[1])
287
+ }
288
+ }
289
+
290
+ tryResolveFromBase(import.meta.url)
291
+
292
+ const closureDir = process.env.DSH_CLOSURE_DIR
293
+ if (typeof closureDir === 'string' && closureDir.length > 0) {
294
+ try {
295
+ const direct = join(dirname(realpathSync(closureDir)), '@earendil-works', 'pi-ai')
296
+ if (existsSync(join(direct, 'package.json'))) candidates.push(direct)
297
+ } catch {
298
+ // ignore
299
+ }
300
+ }
301
+
302
+ return [...new Set(candidates)]
303
+ }
304
+
305
+ /**
306
+ * Detect whether the running host's `@earendil-works/pi-ai` exports
307
+ * `getOpenCodeSessionHeaders` (added in pi-ai 1.6.0, which automatically
308
+ * injects `x-opencode-session` for Custom Providers targeting `opencode.ai`).
309
+ * Fail-safe: returns `false` if unsure, so older Desktop builds receive the
310
+ * static header fallback instead of hitting HTTP 400.
311
+ */
312
+ export function detectHostOpenCodeSessionSupport(): boolean {
313
+ for (const root of resolveHostPiAiRoots()) {
314
+ const identityPath = join(root, 'dist', 'utils', 'identity.js')
315
+ if (!existsSync(identityPath)) continue
316
+ try {
317
+ const content = readFileSync(identityPath, 'utf8')
318
+ if (content.includes('getOpenCodeSessionHeaders')) return true
319
+ return false
320
+ } catch {
321
+ return false
322
+ }
323
+ }
324
+ return false
325
+ }
326
+
327
+ /**
328
+ * Load optional per-model compat hints from the host's pi-ai
329
+ * `opencode-go.json` data file (never used to filter models).
330
+ */
331
+ export function loadDefaultPiAiCompatHints(): CompatHintsByProtocol {
332
+ for (const root of resolveHostPiAiRoots()) {
333
+ const dataPath = join(root, 'dist', 'providers', 'data', 'opencode-go.json')
334
+ if (!existsSync(dataPath)) continue
335
+ try {
336
+ const raw = JSON.parse(readFileSync(dataPath, 'utf8')) as Record<
337
+ string,
338
+ Record<string, { compat?: Record<string, unknown> } | null>
339
+ >
340
+ const out: Record<string, Record<string, Record<string, unknown>>> = {}
341
+ for (const [api, models] of Object.entries(raw)) {
342
+ if (typeof models !== 'object' || models === null) continue
343
+ const byId: Record<string, Record<string, unknown>> = {}
344
+ for (const [id, model] of Object.entries(models)) {
345
+ if (model !== null && typeof model === 'object' && model.compat !== undefined && typeof model.compat === 'object') {
346
+ const filtered = filterOfferedCompat(api, model.compat)
347
+ if (filtered !== undefined) byId[id] = filtered
348
+ }
349
+ }
350
+ if (Object.keys(byId).length > 0) out[api] = byId
351
+ }
352
+ return out
353
+ } catch {
354
+ return {}
355
+ }
356
+ }
357
+ return {}
358
+ }
359
+
360
+ export const opencodeGoAdapter: UpstreamProviderAdapter = {
361
+ id: 'opencode-go',
362
+ aliases: ['go', 'opencode-go'],
363
+ builtinProviderId: 'opencode-go',
364
+ displayName: 'OpenCode Go',
365
+ defaultIntervalMinutes: OPENCODE_GO_DEFAULT_INTERVAL_MINUTES,
366
+ defaultModelsUrl: OPENCODE_GO_MODELS_URL,
367
+ defaultKeyRefs: ['OPENCODE_GO_API_KEY', 'OPENCODE_API_KEY'],
368
+ slotOrder: OPENCODE_GO_SLOTS,
369
+ defaultSlotRoutes: OPENCODE_GO_SLOT_ROUTES,
370
+ legacyExtraRoutes: ['opencode-go-msg', 'opencode-go-resp', 'opencode-go-google'],
371
+ detectHostSessionHeader: detectHostOpenCodeSessionSupport,
372
+
373
+ async fetchAndPlan(options: OfficialFetchOptions): Promise<OfficialFetchResult> {
374
+ const source = await fetchGoOfficialModels({
375
+ url: options.config.modelsUrl || OPENCODE_GO_MODELS_URL,
376
+ apiKey: options.apiKey,
377
+ timeoutMs: options.timeoutMs,
378
+ fetchImpl: options.fetchImpl,
379
+ signal: options.signal,
380
+ })
381
+
382
+ const hostNativeSessionHeader = (options.detectHostSessionHeader ?? detectHostOpenCodeSessionSupport)()
383
+ const shouldAddStaticHeader = options.config.sessionHeader === 'static'
384
+ || (options.config.sessionHeader === 'auto' && !hostNativeSessionHeader)
385
+
386
+ if (!source.ok) {
387
+ return {
388
+ ok: false,
389
+ providers: [],
390
+ activeSlots: [],
391
+ emptySlots: [...OPENCODE_GO_SLOTS],
392
+ warnings: [],
393
+ authStatus: source.authStatus,
394
+ failureKind: source.error?.kind,
395
+ error: source.error,
396
+ observedAt: source.observedAt,
397
+ totalModels: 0,
398
+ sessionHeaderApplied: shouldAddStaticHeader,
399
+ hostNativeSessionHeader,
400
+ }
401
+ }
402
+
403
+ const compatHints = (options.loadPiAiCompatHints ?? loadDefaultPiAiCompatHints)()
404
+ const buckets: Record<OpenCodeGoSlot, { models: SettingsModelProfile[]; baseUrls: string[] }> = {
405
+ chat: { models: [], baseUrls: [] },
406
+ msg: { models: [], baseUrls: [] },
407
+ resp: { models: [], baseUrls: [] },
408
+ google: { models: [], baseUrls: [] },
409
+ }
410
+ const warnings: string[] = []
411
+
412
+ for (const entry of source.entries) {
413
+ const picked = pickOfficialProtocol(entry)
414
+ if (picked === undefined) {
415
+ warnings.push(`skipped ${entry.id}: no supported wire protocol in [${entry.protocols.join(', ')}]`)
416
+ continue
417
+ }
418
+ const def = SLOT_DEFINITIONS[picked.slot]
419
+ const hint = compatHints[def.api]?.[entry.id]
420
+ const profile = mapGoRecordToCustomProfile(entry, def.api, hint)
421
+ buckets[picked.slot].models.push(profile)
422
+ const rawUrl = entry.baseUrls[picked.protocol]
423
+ if (typeof rawUrl === 'string' && rawUrl.length > 0) {
424
+ buckets[picked.slot].baseUrls.push(rawUrl)
425
+ }
426
+ }
427
+
428
+ const providers: CustomProviderSpec[] = []
429
+ const activeSlots: string[] = []
430
+ const emptySlots: string[] = []
431
+
432
+ for (const slot of OPENCODE_GO_SLOTS) {
433
+ const bucket = buckets[slot]
434
+ if (bucket.models.length === 0) {
435
+ emptySlots.push(slot)
436
+ continue
437
+ }
438
+ activeSlots.push(slot)
439
+ const def = SLOT_DEFINITIONS[slot]
440
+ const routeId = options.config.routes[slot]?.trim() || OPENCODE_GO_SLOT_ROUTES[slot]
441
+ const sortedModels = [...bucket.models].sort((a, b) => a.id.localeCompare(b.id))
442
+ const baseURL = normalizeSlotBaseUrl(def.api, bucket.baseUrls[0], def.defaultBaseUrl)
443
+ const spec: CustomProviderSpec = {
444
+ slot,
445
+ routeId,
446
+ displayName: def.displayName,
447
+ api: def.api,
448
+ baseURL,
449
+ apiKeyEnv: options.apiKeyEnv,
450
+ models: sortedModels,
451
+ }
452
+ if (def.routeCompat !== undefined) {
453
+ spec.compat = { ...def.routeCompat }
454
+ }
455
+ if (shouldAddStaticHeader) {
456
+ spec.headers = { ...OPENCODE_STATIC_SESSION_HEADERS }
457
+ }
458
+ providers.push(spec)
459
+ }
460
+
461
+ if (providers.length === 0) {
462
+ return {
463
+ ok: false,
464
+ providers: [],
465
+ activeSlots: [],
466
+ emptySlots: [...OPENCODE_GO_SLOTS],
467
+ warnings,
468
+ authStatus: source.authStatus,
469
+ failureKind: 'parse',
470
+ error: {
471
+ kind: 'parse',
472
+ message: 'opencode-go listing contained no models matching supported wire protocols',
473
+ },
474
+ observedAt: source.observedAt,
475
+ totalModels: 0,
476
+ sessionHeaderApplied: shouldAddStaticHeader,
477
+ hostNativeSessionHeader,
478
+ }
479
+ }
480
+
481
+ return {
482
+ ok: true,
483
+ providers,
484
+ activeSlots,
485
+ emptySlots,
486
+ warnings,
487
+ authStatus: source.authStatus,
488
+ observedAt: source.observedAt,
489
+ totalModels: providers.reduce((sum, p) => sum + p.models.length, 0),
490
+ sessionHeaderApplied: shouldAddStaticHeader,
491
+ hostNativeSessionHeader,
492
+ }
493
+ },
494
+ }