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