@aiwayds/dsh-model-sync 0.5.0 → 0.6.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.
@@ -0,0 +1,284 @@
1
+ // Plan C (settings-seam): one-time legacy settings import for the 0.1.5 → 0.1.7 upgrade.
2
+
3
+ /**
4
+ * The dsh 0.1.7 host renames the old `~/.dsh/settings.yaml` to
5
+ * `settings.yaml.imported` and imports its sections into the active profile
6
+ * keyed by "section name = entry id". This plugin's old section was named
7
+ * `model-sync` — which HAPPENS to equal the entry id (`OWN_ENTRY_ID` in
8
+ * index.ts), so the host's one-shot import usually already carried the values
9
+ * over. But installs where the import never fired (host skipped the rename,
10
+ * a manually restored settings.yaml, plugin installed after the host
11
+ * upgrade) still hold their config in the legacy section. This module
12
+ * recovers it once:
13
+ *
14
+ * 1. read `<home>/settings.yaml.imported` (preferred) →
15
+ * `<home>/settings.yaml` (fallback);
16
+ * 2. flat-parse the `model-sync:` section (scalars only, conservative);
17
+ * 3. keep keys whose legacy value differs from the current effective value;
18
+ * 4. `settings.update('dsh-model-sync', patch)` → on success write the
19
+ * audit marker `<home>/storages/dsh-model-sync/legacy-import.json`;
20
+ * on failure warn and write nothing (the next boot retries);
21
+ * 5. marker present → the whole migration is skipped (idempotent — a
22
+ * later manual edit of the imported file must not resurrect old values).
23
+ *
24
+ * A marker is written for EVERY settled outcome (imported / no-op /
25
+ * no-legacy / no-section) so this runs at most once per home. Never throws
26
+ * into the caller beyond what the apply()-side catch contains: plugin
27
+ * activation must not depend on this.
28
+ *
29
+ * Deliberately a standalone copy of the same contract dsh-topics-memory
30
+ * implements: the two plugins share no runtime, only the convention.
31
+ *
32
+ * @module dsh-model-sync/legacy-import
33
+ */
34
+
35
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
36
+ import { homedir } from 'node:os'
37
+ import { join } from 'node:path'
38
+
39
+ /** Profile entry id the recovered values are written to (index.ts OWN_ENTRY_ID). */
40
+ export const ENTRY_ID = 'dsh-model-sync'
41
+
42
+ /** Legacy top-level section name in the old settings.yaml. */
43
+ export const LEGACY_SECTION = 'model-sync'
44
+
45
+ /** Storage dir name for the audit marker (repo dir name, host convention). */
46
+ export const STORAGE_DIR_NAME = 'dsh-model-sync'
47
+
48
+ /** Legacy keys worth recovering, mapped 1:1 onto Config keys of the same name. */
49
+ export const LEGACY_KEYS = ['writeMode', 'intervalMinutes'] as const
50
+
51
+ export type LegacyKey = (typeof LEGACY_KEYS)[number]
52
+
53
+ /** The settings seam the import writes through (`ctx.settings.update`). */
54
+ export interface SettingsUpdateSeam {
55
+ update(ns: string, patch: object): Promise<void>
56
+ }
57
+
58
+ /** Minimal logger surface (both sinks optional — bare harnesses have none). */
59
+ export interface LegacyImportLogger {
60
+ info?(message: string): void
61
+ warn?(message: string): void
62
+ }
63
+
64
+ export interface LegacyImportInput {
65
+ /** Resolved dsh home (`resolveDshHome()` at the call site). */
66
+ home: string
67
+ /** `ctx.settings` — absent/unusable seams skip the import without a marker. */
68
+ settings?: SettingsUpdateSeam | undefined
69
+ /** Host logger (optional). */
70
+ logger?: LegacyImportLogger | undefined
71
+ /** Current effective value for one legacy key (Volatile ref `.get()` at the call site). */
72
+ getCurrent(key: LegacyKey): unknown
73
+ }
74
+
75
+ export type LegacyImportOutcome =
76
+ | 'imported' // ≥1 key written through settings.update, marker written
77
+ | 'no-op' // section found but every key equal/unknown, marker written
78
+ | 'no-legacy' // neither legacy file exists, marker written
79
+ | 'no-section' // legacy file exists without a `model-sync:` section, marker written
80
+ | 'marker-exists' // already migrated before — nothing touched
81
+ | 'no-settings' // settings seam unusable — no marker, retried next boot
82
+ | 'update-failed' // settings.update rejected — no marker, retried next boot
83
+
84
+ export interface LegacyImportResult {
85
+ outcome: LegacyImportOutcome
86
+ /** Keys written through settings.update (also in the marker). */
87
+ imported: Record<string, unknown>
88
+ /** Keys not imported, with the reason (audit trail). */
89
+ skipped: Record<string, string>
90
+ }
91
+
92
+ /** Dsh home resolution: `$DSH_HOME` when set, `~/.dsh` otherwise (the same
93
+ * shape remote-catalog.ts bakes in for the models-store path). */
94
+ export function resolveDshHome(): string {
95
+ const env = process.env.DSH_HOME?.trim()
96
+ if (env !== undefined && env !== '') return env
97
+ return join(homedir(), '.dsh')
98
+ }
99
+
100
+ /** Candidates in priority order: the host's renamed document first. */
101
+ export function legacySettingsCandidates(home: string): string[] {
102
+ return [join(home, 'settings.yaml.imported'), join(home, 'settings.yaml')]
103
+ }
104
+
105
+ /** Audit marker path: `<home>/storages/<dir>/legacy-import.json`. */
106
+ export function legacyMarkerPath(home: string): string {
107
+ return join(home, 'storages', STORAGE_DIR_NAME, 'legacy-import.json')
108
+ }
109
+
110
+ function escapeRegExp(s: string): string {
111
+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
112
+ }
113
+
114
+ /** A fully quoted scalar: balanced matching quote pair. */
115
+ function isQuoted(s: string): boolean {
116
+ return s.length >= 2 && ((s.startsWith('"') && s.endsWith('"')) || (s.startsWith("'") && s.endsWith("'")))
117
+ }
118
+
119
+ function unquote(s: string): string {
120
+ const inner = s.slice(1, -1)
121
+ // Double quotes: unescape \" and \\; single quotes: '' is a literal '.
122
+ if (s.startsWith('"')) return inner.replaceAll('\\"', '"').replaceAll('\\\\', '\\')
123
+ return inner.replaceAll("''", "'")
124
+ }
125
+
126
+ /**
127
+ * Scalar inference for one flat `key: value` value. Quoted values are
128
+ * unquoted; a single-line quoted flow-JSON value (`'["a","b"]'`) is
129
+ * JSON-parsed after unquoting — a malformed one stays a string. Unquoted
130
+ * flow collections are kept as strings (conservative: this is not a full
131
+ * YAML parser). Empty never reaches here (the line parser skips value-less
132
+ * keys — they open a nested block).
133
+ */
134
+ export function inferScalar(raw: string): unknown {
135
+ const s = raw.trim()
136
+ if (isQuoted(s)) {
137
+ const inner = unquote(s)
138
+ const t = inner.trim()
139
+ if (t.startsWith('[') || t.startsWith('{')) {
140
+ try {
141
+ return JSON.parse(t)
142
+ } catch {
143
+ // not JSON after all — keep the unquoted string
144
+ }
145
+ }
146
+ return inner
147
+ }
148
+ if (s === 'true' || s === 'True' || s === 'TRUE') return true
149
+ if (s === 'false' || s === 'False' || s === 'FALSE') return false
150
+ if (/^-?\d+$/.test(s) || /^-?\d+\.\d+$/.test(s)) return Number(s)
151
+ return s
152
+ }
153
+
154
+ /**
155
+ * Flat section parser: locate the top-level `section:` line and collect its
156
+ * DIRECT children (`key: value` at one common indent) until the next
157
+ * top-level key. Deliberately conservative — NOT a YAML parser:
158
+ * - `key:` with an empty value (opens a nested map/sequence) is skipped, and
159
+ * the deeper lines under it never match the child indent, so folded values
160
+ * are skipped whole;
161
+ * - lines at any other indent are ignored;
162
+ * - an inline value on the header line itself (`section: x`) is not a flat
163
+ * map → `{}`.
164
+ * Pure function — tests run it against literal strings.
165
+ */
166
+ export function parseFlatSection(raw: string, section: string): Record<string, unknown> {
167
+ const lines = raw.split('\n').map((l) => l.replace(/\r$/, ''))
168
+ const header = new RegExp(`^${escapeRegExp(section)}:(.*)$`)
169
+ const start = lines.findIndex((l) => header.test(l))
170
+ if (start < 0) return {}
171
+ // An inline header value means the section is not a block map of children.
172
+ if (lines[start].replace(header, '$1').trim() !== '') return {}
173
+ const out: Record<string, unknown> = {}
174
+ let childIndent: number | undefined
175
+ for (let i = start + 1; i < lines.length; i++) {
176
+ const line = lines[i]
177
+ if (line.trim() === '' || line.trimStart().startsWith('#')) continue
178
+ const indent = line.length - line.trimStart().length
179
+ if (indent === 0) break // next top-level key — section over
180
+ if (childIndent === undefined) childIndent = indent
181
+ if (indent !== childIndent) continue // nested block content — skipped
182
+ const match = /^([^\s:][^:]*):(?:[ \t]+(.*))?$/.exec(line.trim())
183
+ if (match === null) continue // not a `key: value` line — skipped
184
+ if (match[2] === undefined || match[2].trim() === '') continue // opens a nested block
185
+ out[match[1].trim()] = inferScalar(match[2])
186
+ }
187
+ return out
188
+ }
189
+
190
+ /**
191
+ * Run the one-time import. Resolves with the outcome; only throws on truly
192
+ * unexpected I/O errors (the apply()-side catch contains those). The marker
193
+ * is written for every settled outcome EXCEPT the retry-worthy failures
194
+ * (`no-settings`, `update-failed`) — those must re-run at the next boot.
195
+ */
196
+ export async function runLegacySettingsImport(input: LegacyImportInput): Promise<LegacyImportResult> {
197
+ const skipped: Record<string, string> = {}
198
+ const imported: Record<string, unknown> = {}
199
+ const warn = (message: string): void => {
200
+ try {
201
+ input.logger?.warn?.(message)
202
+ } catch {
203
+ // contained — a broken logger must not break the import
204
+ }
205
+ }
206
+ const info = (message: string): void => {
207
+ try {
208
+ input.logger?.info?.(message)
209
+ } catch {
210
+ // contained
211
+ }
212
+ }
213
+
214
+ const markerPath = legacyMarkerPath(input.home)
215
+ if (existsSync(markerPath)) return { outcome: 'marker-exists', imported, skipped }
216
+
217
+ // A settings seam that cannot accept the patch is a retry-worthy state:
218
+ // return WITHOUT reading/marking, so a host that mounts the service later
219
+ // (and a test harness pointing at a real home) neither imports nor writes.
220
+ const settings = input.settings
221
+ if (settings === undefined || typeof settings.update !== 'function') {
222
+ return { outcome: 'no-settings', imported, skipped }
223
+ }
224
+
225
+ // Locate the legacy document.
226
+ const source = legacySettingsCandidates(input.home).find((p) => existsSync(p))
227
+ if (source === undefined) {
228
+ writeMarker(markerPath, { at: new Date().toISOString(), outcome: 'no-legacy', source: undefined, imported, skipped })
229
+ return { outcome: 'no-legacy', imported, skipped }
230
+ }
231
+
232
+ const section = parseFlatSection(readFileSync(source, 'utf8'), LEGACY_SECTION)
233
+ // The marker records the source BASENAME: the marker lives inside the same
234
+ // home, so the directory part is implied.
235
+ const sourceName = source.slice(source.lastIndexOf('/') + 1)
236
+ const present = Object.keys(section)
237
+ if (present.length === 0) {
238
+ writeMarker(markerPath, { at: new Date().toISOString(), outcome: 'no-section', source: sourceName, imported, skipped })
239
+ return { outcome: 'no-section', imported, skipped }
240
+ }
241
+
242
+ // Key-level rule: import only when the legacy value differs from the
243
+ // current effective value; keys this plugin does not know are recorded and
244
+ // left alone (an unknown key would be rejected by the host's schema).
245
+ for (const key of present) {
246
+ if (!(LEGACY_KEYS as readonly string[]).includes(key)) {
247
+ skipped[key] = 'unknown-key'
248
+ continue
249
+ }
250
+ const legacyValue = section[key]
251
+ if (legacyValue === input.getCurrent(key as LegacyKey)) skipped[key] = 'equal'
252
+ else imported[key] = legacyValue
253
+ }
254
+
255
+ if (Object.keys(imported).length === 0) {
256
+ writeMarker(markerPath, { at: new Date().toISOString(), outcome: 'no-op', source: sourceName, imported, skipped })
257
+ info(`${ENTRY_ID}: legacy settings import (${LEGACY_SECTION} → ${ENTRY_ID}): nothing to import (all values equal or unknown)`)
258
+ return { outcome: 'no-op', imported, skipped }
259
+ }
260
+
261
+ try {
262
+ await settings.update(ENTRY_ID, imported)
263
+ } catch (error) {
264
+ // No marker: the next boot retries the import.
265
+ warn(`${ENTRY_ID}: legacy settings import failed (will retry next boot): ${error instanceof Error ? error.message : String(error)}`)
266
+ return { outcome: 'update-failed', imported, skipped }
267
+ }
268
+
269
+ writeMarker(markerPath, { at: new Date().toISOString(), outcome: 'imported', source: sourceName, imported, skipped })
270
+ info(`${ENTRY_ID}: legacy settings import (${LEGACY_SECTION} → ${ENTRY_ID}): ${Object.keys(imported).join(', ')}`)
271
+ return { outcome: 'imported', imported, skipped }
272
+ }
273
+
274
+ /** Persist the audit marker; a failed write leaves no marker (harmless — the
275
+ * next boot re-runs and converges, every step after the marker check is
276
+ * idempotent). */
277
+ function writeMarker(path: string, marker: Record<string, unknown>): void {
278
+ try {
279
+ mkdirSync(join(path, '..'), { recursive: true })
280
+ writeFileSync(path, `${JSON.stringify(marker, null, 2)}\n`)
281
+ } catch {
282
+ // contained — see above
283
+ }
284
+ }
@@ -0,0 +1,293 @@
1
+ // Provider-native model-list fetch: union the pi.dev catalog with each
2
+ // provider's own /models endpoint — the fresher source.
3
+ //
4
+ // Why this exists: pi.dev (and the pi-ai builtin snapshot behind it) lags
5
+ // behind the providers. Measured 2026-09-22 against the native endpoints:
6
+ // DeepSeek's listing had already renamed deepseek-v4-flash → deepseek-flash
7
+ // while pi-ai still carried the retired id; Zhipu served glm-5.3-flashx that
8
+ // pi-ai did not know; Xiaomi's platform announced the V2.6 series while pi-ai
9
+ // stopped at v2.5. Every provider above exposes an OpenAI-shaped
10
+ // `GET /models` listing that answers "which ids exist" straight from the
11
+ // horse's mouth.
12
+ //
13
+ // Merge policy (user-mandated 2026-09-22): the listing may only ADD ids —
14
+ // never remove. A pi.dev entry keeps its richer metadata untouched; a
15
+ // native-only id is synthesized as a minimal entry. Capacities follow the
16
+ // same "don't guess" rule: contextWindow is written only when the listing
17
+ // itself states one (Moonshot's `context_length`), maxTokens never — omitting
18
+ // both lets dsh-llm-pi-ai fall back to the route's defaultContextWindow /
19
+ // defaultMaxTokens (its resolve chain `entry.x ?? base?.x ?? request.default`
20
+ // is exactly this policy made native).
21
+ //
22
+ // Failure policy: a failed native fetch must never lose models. It degrades
23
+ // to the pi.dev result unchanged and surfaces one report line; the round
24
+ // proceeds either way.
25
+
26
+ import type { RemoteCatalogEntry } from './remote-catalog.ts'
27
+ import { deriveKeyRef, getRawUserApiKeyEnv, type RouteCredentialSettingsDescriptor } from './route-credential.ts'
28
+
29
+ // ---------------------------------------------------------------------------
30
+ // Endpoint table
31
+ // ---------------------------------------------------------------------------
32
+
33
+ /** How the /models request authenticates. */
34
+ export type ProviderNativeAuth = 'bearer' | 'api-key-header'
35
+
36
+ /** One provider route's native model-listing endpoint. */
37
+ export interface ProviderNativeEndpoint {
38
+ /** Full URL of the OpenAI-shaped `GET` listing. */
39
+ url: string
40
+ /** Authentication style (Xiaomi accepts either; its docs lead with the header). */
41
+ auth: ProviderNativeAuth
42
+ }
43
+
44
+ /**
45
+ * Provider routes with a known first-party model-listing API. Routes absent
46
+ * from this table (gateways like `opencode-go`, unverified providers) simply
47
+ * keep the pi.dev-only behavior.
48
+ *
49
+ * All endpoints verified 2026-09-22: DeepSeek/Zhipu with a live key, the rest
50
+ * probe-confirmed (401 vs 404 — the endpoint exists, the key was not ours to
51
+ * spend) plus official docs for Xiaomi (mimo.mi.com list-models) and
52
+ * Moonshot (platform.kimi.com OpenAPI, whose response uniquely adds
53
+ * `context_length` and capability flags we can lift).
54
+ */
55
+ export const PROVIDER_NATIVE_ENDPOINTS: Readonly<Record<string, ProviderNativeEndpoint>> = {
56
+ deepseek: { url: 'https://api.deepseek.com/models', auth: 'bearer' },
57
+ 'moonshotai-cn': { url: 'https://api.moonshot.cn/v1/models', auth: 'bearer' },
58
+ moonshotai: { url: 'https://api.moonshot.ai/v1/models', auth: 'bearer' },
59
+ 'kimi-coding': { url: 'https://api.kimi.com/coding/v1/models', auth: 'bearer' },
60
+ zai: { url: 'https://api.z.ai/api/paas/v4/models', auth: 'bearer' },
61
+ 'zai-coding-cn': { url: 'https://open.bigmodel.cn/api/coding/paas/v4/models', auth: 'bearer' },
62
+ xiaomi: { url: 'https://api.xiaomimimo.com/v1/models', auth: 'api-key-header' },
63
+ 'xiaomi-token-plan-cn': { url: 'https://token-plan-cn.xiaomimimo.com/v1/models', auth: 'api-key-header' },
64
+ 'xiaomi-token-plan-ams': { url: 'https://token-plan-ams.xiaomimimo.com/v1/models', auth: 'api-key-header' },
65
+ 'xiaomi-token-plan-sgp': { url: 'https://token-plan-sgp.xiaomimimo.com/v1/models', auth: 'api-key-header' },
66
+ }
67
+
68
+ // ---------------------------------------------------------------------------
69
+ // Credential value resolution
70
+ // ---------------------------------------------------------------------------
71
+
72
+ /**
73
+ * The credentials seam surface this module needs beyond the gate's
74
+ * `describe`: `resolve` returns the value itself (the gate only asks whether
75
+ * it is configured). Optional peer — callers tolerate its absence via the
76
+ * launch-environment fallback.
77
+ */
78
+ export interface CredentialsResolveSeam {
79
+ resolve(ref: string): Promise<{ value: string } | undefined>
80
+ }
81
+
82
+ /** The launch-environment snapshot surface (same as route-credential.ts). */
83
+ export interface LaunchEnvironmentSnapshotLike {
84
+ get(name: string): { value: string } | undefined
85
+ }
86
+
87
+ /** The subset of `Context` the credential-value resolver reads. */
88
+ export interface NativeCredentialContext {
89
+ get(name: 'credentials'): CredentialsResolveSeam | undefined
90
+ get(name: 'launchEnvironment'): LaunchEnvironmentSnapshotLike | undefined
91
+ get(name: string): unknown
92
+ }
93
+
94
+ /**
95
+ * Resolve one route's credential reference to its current VALUE — the same
96
+ * two layers `checkRouteCredential` gates on, but reading through instead of
97
+ * asking whether:
98
+ * 1. the credentials seam's `resolve(ref)` (the same per-operation read the
99
+ * harness itself uses before a request);
100
+ * 2. the launch-environment snapshot (process env fallback when the service
101
+ * is absent).
102
+ *
103
+ * Returns undefined when neither layer has a value; callers skip the native
104
+ * fetch (the pi.dev result stands) rather than fail the round.
105
+ */
106
+ export async function resolveRouteCredentialValue(
107
+ ctx: NativeCredentialContext,
108
+ desc: RouteCredentialSettingsDescriptor | undefined,
109
+ route: string,
110
+ ): Promise<string | undefined> {
111
+ const declared = getRawUserApiKeyEnv(desc, route)
112
+ const ref = declared ?? deriveKeyRef(route)
113
+ const REF_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/
114
+
115
+ if (REF_PATTERN.test(ref)) {
116
+ const credentials = ctx.get('credentials')
117
+ if (credentials !== undefined) {
118
+ try {
119
+ const resolved = await credentials.resolve(ref)
120
+ if (resolved !== undefined && typeof resolved.value === 'string' && resolved.value.length > 0) {
121
+ return resolved.value
122
+ }
123
+ } catch {
124
+ // Same tolerance as the gate: a half-broken seam reads as "no value
125
+ // here" and falls through to the environment.
126
+ }
127
+ }
128
+ }
129
+
130
+ const snapshot = ctx.get('launchEnvironment') ?? {
131
+ get(name: string) {
132
+ const value = process.env[name]
133
+ return value !== undefined && value !== '' ? { value, source: 'process' } : undefined
134
+ },
135
+ }
136
+ const entry = snapshot.get(ref)
137
+ if (entry !== undefined && typeof entry.value === 'string' && entry.value.length > 0) {
138
+ return entry.value
139
+ }
140
+ return undefined
141
+ }
142
+
143
+ // ---------------------------------------------------------------------------
144
+ // Fetch + parse
145
+ // ---------------------------------------------------------------------------
146
+
147
+ /** One provider's native listing outcome: the fresh truth, or why not. */
148
+ export type ProviderNativeResult =
149
+ | {
150
+ ok: true
151
+ /** Model ids exactly as the provider lists them. */
152
+ ids: string[]
153
+ /** contextWindow values the listing itself states (Moonshot `context_length`). */
154
+ contextById: Map<string, number>
155
+ }
156
+ | { ok: false; error: string }
157
+
158
+ /** A minimal fetch compatible enough for tests to stub. */
159
+ export type FetchLike = (url: string, init: { headers: Record<string, string>; signal: AbortSignal }) => Promise<{
160
+ ok: boolean
161
+ status: number
162
+ json(): Promise<unknown>
163
+ }>
164
+
165
+ function isPositiveInt(value: unknown): value is number {
166
+ return typeof value === 'number' && Number.isInteger(value) && value > 0
167
+ }
168
+
169
+ /**
170
+ * Parse a native listing body. Accepts the OpenAI list shape
171
+ * `{"object":"list","data":[{"id":...}]}` and tolerates the per-provider
172
+ * extras (Moonshot's `context_length`; Zhipu's `created`/`owned_by`) — only
173
+ * string `id`s count, and only a positive-integer `context_length` is kept.
174
+ */
175
+ export function parseProviderNativeBody(value: unknown): { ids: string[]; contextById: Map<string, number> } {
176
+ const ids: string[] = []
177
+ const contextById = new Map<string, number>()
178
+ if (typeof value !== 'object' || value === null) throw new Error('body is not an object')
179
+ const data = (value as Record<string, unknown>).data
180
+ if (!Array.isArray(data)) throw new Error('body has no data array')
181
+ for (const item of data) {
182
+ if (typeof item !== 'object' || item === null) continue
183
+ const id = (item as Record<string, unknown>).id
184
+ if (typeof id !== 'string' || id.length === 0) continue
185
+ ids.push(id)
186
+ const context = (item as Record<string, unknown>).context_length
187
+ if (isPositiveInt(context)) contextById.set(id, context)
188
+ }
189
+ if (ids.length === 0) throw new Error('data array lists no usable model ids')
190
+ return { ids, contextById }
191
+ }
192
+
193
+ /**
194
+ * Fetch one route's native model listing. Any failure (non-200, network,
195
+ * unparseable body) resolves to `{ ok: false, error }` — never throws, so the
196
+ * caller's pi.dev result is untouchable.
197
+ *
198
+ * @param route Provider route id; must have an entry in the endpoint table.
199
+ * @param apiKey The credential value (Bearer token / api-key header value).
200
+ * @param timeoutMs Abort budget.
201
+ * @param fetchImpl Injectable fetch (tests); defaults to the global fetch.
202
+ */
203
+ export async function fetchProviderNativeModels(
204
+ route: string,
205
+ apiKey: string,
206
+ timeoutMs: number,
207
+ fetchImpl: FetchLike = fetch as unknown as FetchLike,
208
+ ): Promise<ProviderNativeResult> {
209
+ const endpoint = PROVIDER_NATIVE_ENDPOINTS[route]
210
+ if (endpoint === undefined) {
211
+ return { ok: false, error: `no native endpoint mapped for route "${route}"` }
212
+ }
213
+ const headers: Record<string, string> = { accept: 'application/json' }
214
+ if (endpoint.auth === 'bearer') headers.authorization = `Bearer ${apiKey}`
215
+ else headers['api-key'] = apiKey
216
+
217
+ const controller = new AbortController()
218
+ const timer = setTimeout(() => controller.abort(), timeoutMs)
219
+ try {
220
+ const response = await fetchImpl(endpoint.url, { headers, signal: controller.signal })
221
+ if (!response.ok) {
222
+ return { ok: false, error: `HTTP ${response.status} from ${new URL(endpoint.url).host}` }
223
+ }
224
+ const parsed = parseProviderNativeBody(await response.json())
225
+ return { ok: true, ...parsed }
226
+ } catch (err: unknown) {
227
+ const message = err instanceof Error ? err.message : String(err)
228
+ return { ok: false, error: `native listing fetch failed: ${message}` }
229
+ } finally {
230
+ clearTimeout(timer)
231
+ }
232
+ }
233
+
234
+ // ---------------------------------------------------------------------------
235
+ // Union merge
236
+ // ---------------------------------------------------------------------------
237
+
238
+ /** Outcome of merging a native listing into a route's pi.dev entries. */
239
+ export interface MergedNativeResult {
240
+ /** pi.dev entries plus one synthesized entry per native-only id. */
241
+ entries: RemoteCatalogEntry[]
242
+ /** Native ids that were not already present and got synthesized. */
243
+ addedIds: string[]
244
+ /** Why some or all native ids could not be synthesized (routeApi unknown). */
245
+ skippedReason?: string
246
+ }
247
+
248
+ /**
249
+ * Union a native listing into the pi.dev entries — additions only.
250
+ *
251
+ * A native id the pi.dev list already carries is ignored (pi.dev's richer
252
+ * metadata wins). A native-only id becomes a minimal entry: no maxTokens ever
253
+ * (no source states one), contextWindow only when the listing itself did
254
+ * (`contextById`). `routeApi` is the route's single builtin api — required so
255
+ * the entry can survive translate's base-less gate; routes with no resolvable
256
+ * api (unknown route, mixed-protocol gateway) skip synthesis wholesale with a
257
+ * `skippedReason` instead of emitting entries the runtime would reject.
258
+ */
259
+ export function mergeProviderNativeEntries(
260
+ piDevEntries: readonly RemoteCatalogEntry[],
261
+ native: { ids: readonly string[]; contextById: ReadonlyMap<string, number> },
262
+ route: string,
263
+ routeApi: string | undefined,
264
+ ): MergedNativeResult {
265
+ const known = new Set(piDevEntries.map((e) => e.id))
266
+ const addedIds: string[] = []
267
+ const entries: RemoteCatalogEntry[] = [...piDevEntries]
268
+
269
+ for (const id of native.ids) {
270
+ if (known.has(id)) continue
271
+ if (routeApi === undefined) {
272
+ return {
273
+ entries,
274
+ addedIds,
275
+ skippedReason: `cannot place ${native.ids.length - addedIds.length} new id(s) — route has no single builtin api to address them`,
276
+ }
277
+ }
278
+ const context = native.contextById.get(id)
279
+ entries.push({
280
+ id,
281
+ name: id,
282
+ api: routeApi,
283
+ provider: route,
284
+ baseUrl: '',
285
+ reasoning: false,
286
+ input: ['text'],
287
+ ...(context !== undefined ? { contextWindow: context } : {}),
288
+ })
289
+ addedIds.push(id)
290
+ }
291
+
292
+ return { entries, addedIds }
293
+ }
@@ -62,7 +62,8 @@ export interface RouteCredentialContext {
62
62
  /**
63
63
  * The settings descriptor shape this module needs (matches writer.ts's
64
64
  * `SettingsDescriptor`). Only `user.providers.<route>.apiKeyEnv` is read —
65
- * the value the user explicitly declared in settings.yaml.
65
+ * the value the user explicitly declared in the llm-pi-ai provider profile
66
+ * (settings.yaml up to dsh 0.1.6, the profile patch on 0.1.7+).
66
67
  */
67
68
  export interface RouteCredentialSettingsDescriptor {
68
69
  user?: Record<string, unknown>
package/src/translate.ts CHANGED
@@ -108,6 +108,14 @@ export interface BuiltinModelData {
108
108
  id: string
109
109
  api: string
110
110
  maxTokens?: number
111
+ /**
112
+ * The id left the official default model list (dsh 0.1.7 removed
113
+ * deepseek-v4-flash / deepseek-v4-flash-vision-exp) but the data is kept
114
+ * for historical user configurations. Deprecated entries still serve
115
+ * base-matching classification, but the keepBuiltinOnly emission skips
116
+ * them unless explicitly opted back in (see index.ts getBuiltinOnlyEntries).
117
+ */
118
+ deprecated?: boolean
111
119
  }
112
120
 
113
121
  // ---------------------------------------------------------------------------
package/src/writer.ts CHANGED
@@ -31,7 +31,8 @@
31
31
  * stored ones (a re-added key is the user's latest intent).
32
32
  * - Revision conflict retry: catch SETTINGS_CONFLICT, re-read, re-translate,
33
33
  * re-write once
34
- * - Never touches ~/.dsh/settings.yaml directly — only through settings.mutate
34
+ * - Never touches the settings document directly (settings.yaml up to
35
+ * dsh 0.1.6, the profile patch on 0.1.7+) — only through settings.mutate
35
36
  * - Store read failure: when the models-store read fails (corrupt JSON,
36
37
  * EACCES, …) AND settings carries no overrides key, skip the round with
37
38
  * reason 'store-unavailable' and leave settings.models untouched — the