@aiwayds/dsh-model-sync 0.1.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.
- package/cordis.patch.yml +9 -0
- package/lib/builtin-catalog-snapshot.d.ts +18 -0
- package/lib/builtin-catalog-snapshot.js +41 -0
- package/lib/builtin-catalog-snapshot.js.map +1 -0
- package/lib/diff.d.ts +40 -0
- package/lib/diff.js +101 -0
- package/lib/diff.js.map +1 -0
- package/lib/index.d.ts +9 -0
- package/lib/index.js +319 -0
- package/lib/index.js.map +1 -0
- package/lib/remote-catalog.d.ts +92 -0
- package/lib/remote-catalog.js +217 -0
- package/lib/remote-catalog.js.map +1 -0
- package/lib/translate.d.ts +88 -0
- package/lib/translate.js +173 -0
- package/lib/translate.js.map +1 -0
- package/lib/writer.d.ts +64 -0
- package/lib/writer.js +137 -0
- package/lib/writer.js.map +1 -0
- package/package.json +65 -0
- package/src/builtin-catalog-snapshot.ts +60 -0
- package/src/diff.ts +139 -0
- package/src/index.ts +405 -0
- package/src/remote-catalog.ts +313 -0
- package/src/translate.ts +282 -0
- package/src/writer.ts +219 -0
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
// Plan C (settings-seam): pi.dev remote-catalog fetch and persistent cache.
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* pi.dev remote-catalog fetch and persistent cache.
|
|
5
|
+
*
|
|
6
|
+
* Ported from the dsh-llm-pi-ai patch (hunk 1: withRemoteCatalog / modelsStore /
|
|
7
|
+
* parseRemoteCatalog / remoteModels). The original patch overlays pi.dev's model
|
|
8
|
+
* listing on top of the static catalog in memory; Plan C instead fetches and
|
|
9
|
+
* caches so translate.ts can produce the settings write target.
|
|
10
|
+
*
|
|
11
|
+
* @module dsh-model-sync/remote-catalog
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { homedir } from 'node:os'
|
|
15
|
+
import { dirname, join } from 'node:path'
|
|
16
|
+
import { mkdir, readFile, writeFile } from 'node:fs/promises'
|
|
17
|
+
|
|
18
|
+
// ---------------------------------------------------------------------------
|
|
19
|
+
// Constants (ported from docs-dsh-llm-pi-ai.patch:35-36)
|
|
20
|
+
// ---------------------------------------------------------------------------
|
|
21
|
+
|
|
22
|
+
/** Base URL for pi.dev model catalog API. */
|
|
23
|
+
export const REMOTE_CATALOG_BASE_URL = 'https://pi.dev'
|
|
24
|
+
|
|
25
|
+
/** Minimum interval between revalidation requests per provider. */
|
|
26
|
+
export const REMOTE_CATALOG_REFRESH_INTERVAL_MS = 4 * 60 * 60 * 1000
|
|
27
|
+
|
|
28
|
+
/** Path to the persistent per-provider cache. */
|
|
29
|
+
export const MODELS_STORE_PATH = join(homedir(), '.dsh', 'models-store.json')
|
|
30
|
+
|
|
31
|
+
// ---------------------------------------------------------------------------
|
|
32
|
+
// Types
|
|
33
|
+
// ---------------------------------------------------------------------------
|
|
34
|
+
|
|
35
|
+
/** Shape of a single model entry from pi.dev's /api/models/providers/<route>. */
|
|
36
|
+
export interface RemoteCatalogEntry {
|
|
37
|
+
id: string
|
|
38
|
+
name: string
|
|
39
|
+
api: string
|
|
40
|
+
provider: string
|
|
41
|
+
baseUrl: string
|
|
42
|
+
reasoning: boolean
|
|
43
|
+
input: string[]
|
|
44
|
+
cost?: Record<string, number>
|
|
45
|
+
contextWindow?: number
|
|
46
|
+
maxTokens?: number
|
|
47
|
+
compat?: {
|
|
48
|
+
supportsStore?: boolean
|
|
49
|
+
supportsDeveloperRole?: boolean
|
|
50
|
+
maxTokensField?: string
|
|
51
|
+
thinkingFormat?: string
|
|
52
|
+
supportsReasoningEffort?: boolean
|
|
53
|
+
zaiToolStream?: boolean
|
|
54
|
+
requiresReasoningContentOnAssistantMessages?: boolean
|
|
55
|
+
sessionAffinityFormat?: string
|
|
56
|
+
supportsLongCacheRetention?: boolean
|
|
57
|
+
}
|
|
58
|
+
thinkingLevelMap?: Record<string, string | null>
|
|
59
|
+
[key: string]: unknown
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Per-provider cache entry persisted to ~/.dsh/models-store.json. */
|
|
63
|
+
export interface ModelsStoreEntry {
|
|
64
|
+
models: RemoteCatalogEntry[]
|
|
65
|
+
checkedAt: number
|
|
66
|
+
lastModified: number
|
|
67
|
+
etag?: string
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Top-level shape of ~/.dsh/models-store.json. */
|
|
71
|
+
export interface ModelsStore {
|
|
72
|
+
[route: string]: ModelsStoreEntry
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// ---------------------------------------------------------------------------
|
|
76
|
+
// Fetch result
|
|
77
|
+
// ---------------------------------------------------------------------------
|
|
78
|
+
|
|
79
|
+
export interface FetchRemoteCatalogResult {
|
|
80
|
+
/** Filtered entries from pi.dev (only entries whose api is in the route). */
|
|
81
|
+
entries: RemoteCatalogEntry[]
|
|
82
|
+
/** Whether the ETag/304 path was used (body unchanged). */
|
|
83
|
+
fromCache: boolean
|
|
84
|
+
/** Error message if the fetch failed; entries will be from last-good cache. */
|
|
85
|
+
error?: string
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// ---------------------------------------------------------------------------
|
|
89
|
+
// parseRemoteCatalog (ported from docs-dsh-llm-pi-ai.patch:48-59)
|
|
90
|
+
// ---------------------------------------------------------------------------
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Normalize pi.dev's response shape into a flat entry array.
|
|
94
|
+
* pi.dev may return: a plain array, `{ models: [...] }`, or an object of arrays.
|
|
95
|
+
*/
|
|
96
|
+
export function parseRemoteCatalog(
|
|
97
|
+
providerId: string,
|
|
98
|
+
value: unknown,
|
|
99
|
+
): RemoteCatalogEntry[] {
|
|
100
|
+
const entries: unknown[] = Array.isArray(value)
|
|
101
|
+
? value
|
|
102
|
+
: typeof value === 'object' && value !== null && 'models' in value && Array.isArray((value as Record<string, unknown>).models)
|
|
103
|
+
? ((value as Record<string, unknown>).models as unknown[])
|
|
104
|
+
: typeof value === 'object' && value !== null
|
|
105
|
+
? Object.values(value as Record<string, unknown>)
|
|
106
|
+
: []
|
|
107
|
+
if (entries.length === 0) {
|
|
108
|
+
throw new Error(`Invalid model catalog for provider "${providerId}"`)
|
|
109
|
+
}
|
|
110
|
+
return entries
|
|
111
|
+
.filter((entry): entry is Record<string, unknown> => {
|
|
112
|
+
if (typeof entry !== 'object' || entry === null || !('id' in entry)) return false
|
|
113
|
+
// I-11: validate typeof id and api are strings (not just present)
|
|
114
|
+
if (typeof (entry as Record<string, unknown>).id !== 'string') return false
|
|
115
|
+
if (!('api' in entry) || typeof (entry as Record<string, unknown>).api !== 'string') return false
|
|
116
|
+
return true
|
|
117
|
+
})
|
|
118
|
+
.map((model) => ({ ...model, provider: providerId }) as unknown as RemoteCatalogEntry)
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// ---------------------------------------------------------------------------
|
|
122
|
+
// Models store persistence (ported from docs-dsh-llm-pi-ai.patch:67-96)
|
|
123
|
+
// ---------------------------------------------------------------------------
|
|
124
|
+
|
|
125
|
+
let modelsStoreCache: ModelsStoreAccessor | undefined
|
|
126
|
+
|
|
127
|
+
/** Serialized read/write accessor for ~/.dsh/models-store.json. */
|
|
128
|
+
export interface ModelsStoreAccessor {
|
|
129
|
+
read(providerId?: string): Promise<ModelsStoreEntry | undefined>
|
|
130
|
+
write(providerId: string, entry: ModelsStoreEntry): Promise<void>
|
|
131
|
+
delete(providerId: string): Promise<void>
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Get (or create) the singleton models-store accessor.
|
|
136
|
+
* Each read parses the file fresh; writes are serialized through a promise queue
|
|
137
|
+
* to avoid clobbering concurrent writes.
|
|
138
|
+
*
|
|
139
|
+
* @param storePath Optional override for the store file path (defaults to ~/.dsh/models-store.json).
|
|
140
|
+
*/
|
|
141
|
+
export function loadModelsStore(storePath?: string): ModelsStoreAccessor {
|
|
142
|
+
const effectivePath = storePath ?? MODELS_STORE_PATH
|
|
143
|
+
|
|
144
|
+
// Only cache when using the default path (singleton); custom paths always create fresh accessors
|
|
145
|
+
if (storePath === undefined && modelsStoreCache !== undefined) return modelsStoreCache
|
|
146
|
+
|
|
147
|
+
const readDoc = async (): Promise<ModelsStore> => {
|
|
148
|
+
try {
|
|
149
|
+
return JSON.parse(await readFile(effectivePath, 'utf8')) as ModelsStore
|
|
150
|
+
} catch {
|
|
151
|
+
return {}
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
const writeDoc = async (doc: ModelsStore): Promise<void> => {
|
|
156
|
+
await mkdir(dirname(effectivePath), { recursive: true })
|
|
157
|
+
await writeFile(effectivePath, JSON.stringify(doc))
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
let queue: Promise<void> = Promise.resolve()
|
|
161
|
+
const enqueue = (task: () => Promise<void>): Promise<void> => {
|
|
162
|
+
const next = queue.then(task, task)
|
|
163
|
+
queue = next.catch(() => {})
|
|
164
|
+
return next
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
const accessor: ModelsStoreAccessor = {
|
|
168
|
+
read: async (providerId?: string): Promise<ModelsStoreEntry | undefined> => {
|
|
169
|
+
const doc = await readDoc()
|
|
170
|
+
return providerId === undefined ? undefined : doc[providerId]
|
|
171
|
+
},
|
|
172
|
+
write: (providerId: string, entry: ModelsStoreEntry): Promise<void> =>
|
|
173
|
+
enqueue(async () => {
|
|
174
|
+
const doc = await readDoc()
|
|
175
|
+
doc[providerId] = entry
|
|
176
|
+
await writeDoc(doc)
|
|
177
|
+
}),
|
|
178
|
+
delete: (providerId: string): Promise<void> =>
|
|
179
|
+
enqueue(async () => {
|
|
180
|
+
const doc = await readDoc()
|
|
181
|
+
delete doc[providerId]
|
|
182
|
+
await writeDoc(doc)
|
|
183
|
+
}),
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// Only cache the default-path accessor (singleton)
|
|
187
|
+
if (storePath === undefined) {
|
|
188
|
+
modelsStoreCache = accessor
|
|
189
|
+
}
|
|
190
|
+
return accessor
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* Reset the singleton accessor (for testing).
|
|
195
|
+
*/
|
|
196
|
+
export function resetModelsStoreCache(): void {
|
|
197
|
+
modelsStoreCache = undefined
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
// ---------------------------------------------------------------------------
|
|
201
|
+
// fetchRemoteCatalog (adapted from docs-dsh-llm-pi-ai.patch:104-151)
|
|
202
|
+
// ---------------------------------------------------------------------------
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* Fetch one route's model list from pi.dev with ETag/304 revalidation.
|
|
206
|
+
*
|
|
207
|
+
* Behavior mirrors the original withRemoteCatalog.refreshModels:
|
|
208
|
+
* - 304 → update checkedAt, return cached entries
|
|
209
|
+
* - 404/501 → store empty overlay, return empty
|
|
210
|
+
* - transient failure → keep cached entries, return error message
|
|
211
|
+
* - success → parse + store + return entries
|
|
212
|
+
*
|
|
213
|
+
* @param route The provider route id (e.g. 'opencode-go')
|
|
214
|
+
* @param timeout Abort budget in ms (default 30s)
|
|
215
|
+
* @param store Optional override for the models-store accessor (testing)
|
|
216
|
+
* @param options Additional options (storePath, force)
|
|
217
|
+
*/
|
|
218
|
+
export async function fetchRemoteCatalog(
|
|
219
|
+
route: string,
|
|
220
|
+
timeout?: number,
|
|
221
|
+
store?: ModelsStoreAccessor,
|
|
222
|
+
options?: { storePath?: string; force?: boolean },
|
|
223
|
+
): Promise<FetchRemoteCatalogResult> {
|
|
224
|
+
const effectiveStore = store ?? loadModelsStore(options?.storePath)
|
|
225
|
+
const stored = await effectiveStore.read(route)
|
|
226
|
+
|
|
227
|
+
// I-5: throttle — return cached entries if checkedAt is within revalidation interval
|
|
228
|
+
if (!options?.force && stored !== undefined && stored.models.length > 0) {
|
|
229
|
+
const elapsed = Date.now() - stored.checkedAt
|
|
230
|
+
if (elapsed >= 0 && elapsed < REMOTE_CATALOG_REFRESH_INTERVAL_MS) {
|
|
231
|
+
return { entries: stored.models, fromCache: true }
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
const url = new URL(`/api/models/providers/${encodeURIComponent(route)}`, REMOTE_CATALOG_BASE_URL)
|
|
236
|
+
const headers: Record<string, string> = { accept: 'application/json' }
|
|
237
|
+
if (stored?.models?.length && stored.etag) {
|
|
238
|
+
headers['if-none-match'] = stored.etag
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
const controller = new AbortController()
|
|
242
|
+
const timer = timeout !== undefined
|
|
243
|
+
? setTimeout(() => controller.abort(), timeout)
|
|
244
|
+
: undefined
|
|
245
|
+
|
|
246
|
+
try {
|
|
247
|
+
const response = await fetch(url, {
|
|
248
|
+
headers,
|
|
249
|
+
signal: controller.signal,
|
|
250
|
+
})
|
|
251
|
+
|
|
252
|
+
const checkedAt = Date.now()
|
|
253
|
+
|
|
254
|
+
// 304: body unchanged, just refresh checkedAt
|
|
255
|
+
if (response.status === 304 && stored) {
|
|
256
|
+
await effectiveStore.write(route, { ...stored, checkedAt })
|
|
257
|
+
return { entries: stored.models, fromCache: true }
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
// 404/501: provider not found on pi.dev; store empty overlay
|
|
261
|
+
if (response.status === 404 || response.status === 501) {
|
|
262
|
+
const entry: ModelsStoreEntry = {
|
|
263
|
+
models: stored?.models ?? [],
|
|
264
|
+
checkedAt,
|
|
265
|
+
lastModified: 0,
|
|
266
|
+
etag: undefined,
|
|
267
|
+
}
|
|
268
|
+
await effectiveStore.write(route, entry)
|
|
269
|
+
return { entries: [], fromCache: false }
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
// Transient failure: keep cached entries, report error
|
|
273
|
+
if (!response.ok) {
|
|
274
|
+
const entry: ModelsStoreEntry = {
|
|
275
|
+
models: stored?.models ?? [],
|
|
276
|
+
checkedAt,
|
|
277
|
+
lastModified: stored?.lastModified ?? 0,
|
|
278
|
+
etag: stored?.etag,
|
|
279
|
+
}
|
|
280
|
+
await effectiveStore.write(route, entry)
|
|
281
|
+
return {
|
|
282
|
+
entries: stored?.models ?? [],
|
|
283
|
+
fromCache: false,
|
|
284
|
+
error: `Model catalog request failed for ${route}: ${response.status}`,
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
// Success: parse and store
|
|
289
|
+
const refreshed = parseRemoteCatalog(route, await response.json())
|
|
290
|
+
const lastModified = Date.parse(response.headers.get('last-modified') ?? '')
|
|
291
|
+
const etag = response.headers.get('etag') ?? undefined
|
|
292
|
+
|
|
293
|
+
const storeEntry: ModelsStoreEntry = {
|
|
294
|
+
models: refreshed,
|
|
295
|
+
checkedAt,
|
|
296
|
+
lastModified: Number.isNaN(lastModified) ? 0 : lastModified,
|
|
297
|
+
etag,
|
|
298
|
+
}
|
|
299
|
+
await effectiveStore.write(route, storeEntry)
|
|
300
|
+
|
|
301
|
+
return { entries: refreshed, fromCache: false }
|
|
302
|
+
} catch (err: unknown) {
|
|
303
|
+
const message = err instanceof Error ? err.message : String(err)
|
|
304
|
+
// On abort or network error, return cached entries
|
|
305
|
+
return {
|
|
306
|
+
entries: stored?.models ?? [],
|
|
307
|
+
fromCache: false,
|
|
308
|
+
error: `Fetch failed for ${route}: ${message}`,
|
|
309
|
+
}
|
|
310
|
+
} finally {
|
|
311
|
+
if (timer !== undefined) clearTimeout(timer)
|
|
312
|
+
}
|
|
313
|
+
}
|
package/src/translate.ts
ADDED
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
// Plan C (settings-seam): translate pi.dev entries into settings-writable profiles.
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Translate pi.dev remote catalog entries into settings-writable model profiles.
|
|
5
|
+
*
|
|
6
|
+
* Implements the 14 translation rules from the design doc §3.3, including:
|
|
7
|
+
* - base-matching vs base-less classification (§3.4)
|
|
8
|
+
* - reasoningEfforts derivation with S2 gate (§3.5)
|
|
9
|
+
* - compat api gate for S5 (§3.3 rules 8/9)
|
|
10
|
+
* - maxTokens classification (§3.3 rule 5)
|
|
11
|
+
* - drop logic for mixed-protocol routes (§3.3 rule 13)
|
|
12
|
+
* - keepBuiltinOnly behavior (§5.2)
|
|
13
|
+
*
|
|
14
|
+
* @module dsh-model-sync/translate
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import type { RemoteCatalogEntry } from './remote-catalog.ts'
|
|
18
|
+
|
|
19
|
+
// ---------------------------------------------------------------------------
|
|
20
|
+
// Types
|
|
21
|
+
// ---------------------------------------------------------------------------
|
|
22
|
+
|
|
23
|
+
/** A model profile as written to settings.models (the narrow writable shape). */
|
|
24
|
+
export interface SettingsModelProfile {
|
|
25
|
+
id: string
|
|
26
|
+
name?: string
|
|
27
|
+
contextWindow?: number
|
|
28
|
+
input?: string[]
|
|
29
|
+
maxTokens?: number
|
|
30
|
+
reasoningEfforts?: Record<string, string | null>
|
|
31
|
+
compat?: {
|
|
32
|
+
thinkingFormat?: string
|
|
33
|
+
supportsReasoningEffort?: boolean
|
|
34
|
+
}
|
|
35
|
+
[key: string]: unknown
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Options for the translation pass. */
|
|
39
|
+
export interface TranslateOptions {
|
|
40
|
+
/**
|
|
41
|
+
* true = target list = pi.dev ∪ builtin-only ids (smooth migration, don't
|
|
42
|
+
* delete existing models). false = strict mirror of pi.dev only.
|
|
43
|
+
*/
|
|
44
|
+
keepBuiltinOnly: boolean
|
|
45
|
+
/**
|
|
46
|
+
* true = drop unserviceable entries and continue; false = if any entry is
|
|
47
|
+
* dropped, abort the entire route (don't write).
|
|
48
|
+
*/
|
|
49
|
+
dropUnserviceable: boolean
|
|
50
|
+
/** Specific drop warnings to filter (currently unused, reserved). */
|
|
51
|
+
dropWarnings: DropWarning[]
|
|
52
|
+
/**
|
|
53
|
+
* true = force all models with non-empty thinkingFormat to have max
|
|
54
|
+
* reasoning effort. Skips S2 gate SRE check, ensures reasoningEfforts
|
|
55
|
+
* contains low/high/max, and forces compat.supportsReasoningEffort=true
|
|
56
|
+
* (S5 gate, openai-completions only). 400 risk is on the user.
|
|
57
|
+
*/
|
|
58
|
+
forceMaxReasoningEffort: boolean
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** A warning about a dropped or degraded entry. */
|
|
62
|
+
export interface DropWarning {
|
|
63
|
+
id: string
|
|
64
|
+
route: string
|
|
65
|
+
reason: string
|
|
66
|
+
severity: 'drop' | 'degrade'
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Result of the translation pass for one route. */
|
|
70
|
+
export interface TranslateResult {
|
|
71
|
+
/** Settings-writable entries, sorted by id. Empty when aborted. */
|
|
72
|
+
entries: SettingsModelProfile[]
|
|
73
|
+
/** Ids that were dropped (with reason). */
|
|
74
|
+
dropped: DropWarning[]
|
|
75
|
+
/** Ids that are degraded but still written (with reason). */
|
|
76
|
+
warnings: DropWarning[]
|
|
77
|
+
/** true when dropUnserviceable=false and drops exist — entries must not be written. */
|
|
78
|
+
aborted: boolean
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// ---------------------------------------------------------------------------
|
|
82
|
+
// THINKING_LEVELS whitelist (§3.5)
|
|
83
|
+
// ---------------------------------------------------------------------------
|
|
84
|
+
|
|
85
|
+
/** Allowed thinking level keys and their valid wire-spelling constraints. */
|
|
86
|
+
const THINKING_LEVELS = new Set([
|
|
87
|
+
'off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max',
|
|
88
|
+
])
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Builtin catalog data per route: needed for base-matching classification,
|
|
92
|
+
* maxTokens stripping, and api-gate resolution.
|
|
93
|
+
*/
|
|
94
|
+
export interface BuiltinModelData {
|
|
95
|
+
id: string
|
|
96
|
+
api: string
|
|
97
|
+
maxTokens?: number
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// ---------------------------------------------------------------------------
|
|
101
|
+
// Core translation
|
|
102
|
+
// ---------------------------------------------------------------------------
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Translate a route's pi.dev entries into settings-writable profiles.
|
|
106
|
+
*
|
|
107
|
+
* @param entries Raw entries from pi.dev for this route
|
|
108
|
+
* @param builtinIds Set of model ids present in the installed builtin catalog for this route
|
|
109
|
+
* @param builtinData Array of builtin catalog data (id, api, maxTokens) for this route
|
|
110
|
+
* @param route The route id (e.g. 'opencode-go')
|
|
111
|
+
* @param options Translation options
|
|
112
|
+
* @param builtinOnlyEntries Entries from builtin catalog that are not in pi.dev (for keepBuiltinOnly)
|
|
113
|
+
*/
|
|
114
|
+
export function translateEntries(
|
|
115
|
+
entries: RemoteCatalogEntry[],
|
|
116
|
+
builtinIds: Set<string>,
|
|
117
|
+
builtinData: BuiltinModelData[],
|
|
118
|
+
route: string,
|
|
119
|
+
options: TranslateOptions,
|
|
120
|
+
builtinOnlyEntries?: RemoteCatalogEntry[],
|
|
121
|
+
): TranslateResult {
|
|
122
|
+
const dropped: DropWarning[] = []
|
|
123
|
+
const warnings: DropWarning[] = []
|
|
124
|
+
const result: SettingsModelProfile[] = []
|
|
125
|
+
|
|
126
|
+
for (const entry of entries) {
|
|
127
|
+
const isBaseMatching = builtinIds.has(entry.id)
|
|
128
|
+
const builtin = builtinData.find((b) => b.id === entry.id)
|
|
129
|
+
|
|
130
|
+
// Determine resolved api for compat gate (rules 8/9):
|
|
131
|
+
// Use builtin api if base-matching, otherwise the entry's own api
|
|
132
|
+
const resolvedApi = isBaseMatching && builtin ? builtin.api : entry.api
|
|
133
|
+
|
|
134
|
+
// Rule 13: drop base-less entries only when they truly have no api
|
|
135
|
+
if (!isBaseMatching && (!entry.api || entry.api === '')) {
|
|
136
|
+
dropped.push({
|
|
137
|
+
id: entry.id,
|
|
138
|
+
route,
|
|
139
|
+
reason: `base-less entry "${entry.id}" has no api — cannot resolve`,
|
|
140
|
+
severity: 'drop',
|
|
141
|
+
})
|
|
142
|
+
continue
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// Rule 1: id (always written)
|
|
146
|
+
const profile: SettingsModelProfile = { id: entry.id }
|
|
147
|
+
|
|
148
|
+
// Rule 2: name
|
|
149
|
+
if (entry.name !== undefined) profile.name = entry.name
|
|
150
|
+
|
|
151
|
+
// Rule 3: contextWindow
|
|
152
|
+
if (entry.contextWindow !== undefined) profile.contextWindow = entry.contextWindow
|
|
153
|
+
|
|
154
|
+
// Rule 4: input (modalities)
|
|
155
|
+
if (entry.input !== undefined && entry.input.length > 0) {
|
|
156
|
+
profile.input = [...entry.input]
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// Rule 5: maxTokens — base-matching: strip; base-less: keep
|
|
160
|
+
if (!isBaseMatching && entry.maxTokens !== undefined) {
|
|
161
|
+
profile.maxTokens = entry.maxTokens
|
|
162
|
+
}
|
|
163
|
+
// base-matching: don't write maxTokens (pi-ai falls back to catalog value)
|
|
164
|
+
|
|
165
|
+
// Rule 6: reasoning (boolean) — never write
|
|
166
|
+
// Rule 7: reasoningEfforts — derive with S2 gate
|
|
167
|
+
const thinkingFormat = entry.compat?.thinkingFormat
|
|
168
|
+
const supportsRE = entry.compat?.supportsReasoningEffort
|
|
169
|
+
// S2 gate: thinkingFormat non-empty AND (forceMaxReasoningEffort OR supportsReasoningEffort !== false)
|
|
170
|
+
if (thinkingFormat !== undefined && thinkingFormat !== '' && (options.forceMaxReasoningEffort || supportsRE !== false)) {
|
|
171
|
+
// Derive reasoningEfforts as dict (§3.5)
|
|
172
|
+
profile.reasoningEfforts = deriveReasoningEfforts(entry, options.forceMaxReasoningEffort)
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// Rules 8/9: compat.thinkingFormat / compat.supportsReasoningEffort
|
|
176
|
+
// S5 gate: only write when resolved api === 'openai-completions'
|
|
177
|
+
if (resolvedApi === 'openai-completions') {
|
|
178
|
+
const compat: Record<string, unknown> = {}
|
|
179
|
+
if (entry.compat?.thinkingFormat !== undefined) {
|
|
180
|
+
compat.thinkingFormat = entry.compat.thinkingFormat
|
|
181
|
+
}
|
|
182
|
+
if (entry.compat?.supportsReasoningEffort !== undefined) {
|
|
183
|
+
compat.supportsReasoningEffort = entry.compat.supportsReasoningEffort
|
|
184
|
+
}
|
|
185
|
+
// force mode: override supportsReasoningEffort to true (only when thinkingFormat is present)
|
|
186
|
+
if (options.forceMaxReasoningEffort && entry.compat?.thinkingFormat) {
|
|
187
|
+
compat.supportsReasoningEffort = true
|
|
188
|
+
}
|
|
189
|
+
if (Object.keys(compat).length > 0) {
|
|
190
|
+
profile.compat = compat as SettingsModelProfile['compat']
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
// else: drop the compat keys (don't drop the entry itself)
|
|
194
|
+
|
|
195
|
+
// Rules 10-12: other compat keys, api/baseUrl/provider per entry, cost/etc — never write
|
|
196
|
+
|
|
197
|
+
// Rule 14: api-divergent entries must be written (accept protocol override)
|
|
198
|
+
if (isBaseMatching && builtin && entry.api !== builtin.api) {
|
|
199
|
+
warnings.push({
|
|
200
|
+
id: entry.id,
|
|
201
|
+
route,
|
|
202
|
+
reason: `api divergence: pi.dev=${entry.api} vs installed=${builtin.api} — written, protocol will use installed`,
|
|
203
|
+
severity: 'degrade',
|
|
204
|
+
})
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
result.push(profile)
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// keepBuiltinOnly: merge in builtin-only entries (§5.2)
|
|
211
|
+
// Emit minimal {id} only — the adapter's ...base spread restores all fields.
|
|
212
|
+
if (options.keepBuiltinOnly && builtinOnlyEntries !== undefined) {
|
|
213
|
+
for (const entry of builtinOnlyEntries) {
|
|
214
|
+
// Already present in pi.dev list? Skip (shouldn't happen, but guard)
|
|
215
|
+
if (result.some((r) => r.id === entry.id)) continue
|
|
216
|
+
|
|
217
|
+
// Minimal profile: only id. All other fields come from ...base at runtime.
|
|
218
|
+
result.push({ id: entry.id })
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// Sort by id for stable output (§4.4)
|
|
223
|
+
result.sort((a, b) => a.id.localeCompare(b.id))
|
|
224
|
+
|
|
225
|
+
// If dropUnserviceable is false and there are drops, return empty (don't write)
|
|
226
|
+
if (!options.dropUnserviceable && dropped.length > 0) {
|
|
227
|
+
return { entries: [], dropped, warnings, aborted: true }
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
return { entries: result, dropped, warnings, aborted: false }
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
// ---------------------------------------------------------------------------
|
|
234
|
+
// Derive reasoningEfforts (§3.5)
|
|
235
|
+
// ---------------------------------------------------------------------------
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* Derive reasoningEfforts dict from a pi.dev entry.
|
|
239
|
+
*
|
|
240
|
+
* Schema requires dict: z.dict(z.union([z.string(), z.null()]), z.union(THINKING_LEVELS)).
|
|
241
|
+
* Key = effort level, value = wire spelling (string|null).
|
|
242
|
+
*
|
|
243
|
+
* We derive from thinkingLevelMap when available, otherwise produce a minimal
|
|
244
|
+
* two-level dict with low/high using the effort name as wire spelling.
|
|
245
|
+
*
|
|
246
|
+
* Design doc §3.5: "dict { low: '<wire>', high: '<wire>' } — value is wire
|
|
247
|
+
* spelling, not level name; may include off: null"
|
|
248
|
+
*
|
|
249
|
+
* @param entry The pi.dev entry
|
|
250
|
+
* @param force When true, ensure low/high/max are all present in the result
|
|
251
|
+
*/
|
|
252
|
+
function deriveReasoningEfforts(entry: RemoteCatalogEntry, force: boolean): Record<string, string | null> {
|
|
253
|
+
const tlm = entry.thinkingLevelMap
|
|
254
|
+
if (tlm !== undefined && Object.keys(tlm).length > 0) {
|
|
255
|
+
// Filter: only keep keys in THINKING_LEVELS whitelist with non-empty string values
|
|
256
|
+
const filtered: Record<string, string | null> = {}
|
|
257
|
+
for (const [k, v] of Object.entries(tlm)) {
|
|
258
|
+
if (!THINKING_LEVELS.has(k)) continue
|
|
259
|
+
if (typeof v === 'string' && v.length > 0) {
|
|
260
|
+
filtered[k] = v
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
// If filtering left only 'off' (or empty), supplement with low/high defaults
|
|
264
|
+
const nonOffKeys = Object.keys(filtered).filter((k) => k !== 'off')
|
|
265
|
+
if (nonOffKeys.length === 0) {
|
|
266
|
+
const base: Record<string, string | null> = { low: 'low', high: 'high' }
|
|
267
|
+
if (force) base.max = 'max'
|
|
268
|
+
return base
|
|
269
|
+
}
|
|
270
|
+
// force mode: ensure low/high/max are present
|
|
271
|
+
if (force) {
|
|
272
|
+
if (!filtered.low) filtered.low = 'low'
|
|
273
|
+
if (!filtered.high) filtered.high = 'high'
|
|
274
|
+
if (!filtered.max) filtered.max = 'max'
|
|
275
|
+
}
|
|
276
|
+
return filtered
|
|
277
|
+
}
|
|
278
|
+
// Fallback: minimal two-level dict (low/high)
|
|
279
|
+
const base: Record<string, string | null> = { low: 'low', high: 'high' }
|
|
280
|
+
if (force) base.max = 'max'
|
|
281
|
+
return base
|
|
282
|
+
}
|