@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.
@@ -0,0 +1,92 @@
1
+ /** Base URL for pi.dev model catalog API. */
2
+ export declare const REMOTE_CATALOG_BASE_URL = "https://pi.dev";
3
+ /** Minimum interval between revalidation requests per provider. */
4
+ export declare const REMOTE_CATALOG_REFRESH_INTERVAL_MS: number;
5
+ /** Path to the persistent per-provider cache. */
6
+ export declare const MODELS_STORE_PATH: string;
7
+ /** Shape of a single model entry from pi.dev's /api/models/providers/<route>. */
8
+ export interface RemoteCatalogEntry {
9
+ id: string;
10
+ name: string;
11
+ api: string;
12
+ provider: string;
13
+ baseUrl: string;
14
+ reasoning: boolean;
15
+ input: string[];
16
+ cost?: Record<string, number>;
17
+ contextWindow?: number;
18
+ maxTokens?: number;
19
+ compat?: {
20
+ supportsStore?: boolean;
21
+ supportsDeveloperRole?: boolean;
22
+ maxTokensField?: string;
23
+ thinkingFormat?: string;
24
+ supportsReasoningEffort?: boolean;
25
+ zaiToolStream?: boolean;
26
+ requiresReasoningContentOnAssistantMessages?: boolean;
27
+ sessionAffinityFormat?: string;
28
+ supportsLongCacheRetention?: boolean;
29
+ };
30
+ thinkingLevelMap?: Record<string, string | null>;
31
+ [key: string]: unknown;
32
+ }
33
+ /** Per-provider cache entry persisted to ~/.dsh/models-store.json. */
34
+ export interface ModelsStoreEntry {
35
+ models: RemoteCatalogEntry[];
36
+ checkedAt: number;
37
+ lastModified: number;
38
+ etag?: string;
39
+ }
40
+ /** Top-level shape of ~/.dsh/models-store.json. */
41
+ export interface ModelsStore {
42
+ [route: string]: ModelsStoreEntry;
43
+ }
44
+ export interface FetchRemoteCatalogResult {
45
+ /** Filtered entries from pi.dev (only entries whose api is in the route). */
46
+ entries: RemoteCatalogEntry[];
47
+ /** Whether the ETag/304 path was used (body unchanged). */
48
+ fromCache: boolean;
49
+ /** Error message if the fetch failed; entries will be from last-good cache. */
50
+ error?: string;
51
+ }
52
+ /**
53
+ * Normalize pi.dev's response shape into a flat entry array.
54
+ * pi.dev may return: a plain array, `{ models: [...] }`, or an object of arrays.
55
+ */
56
+ export declare function parseRemoteCatalog(providerId: string, value: unknown): RemoteCatalogEntry[];
57
+ /** Serialized read/write accessor for ~/.dsh/models-store.json. */
58
+ export interface ModelsStoreAccessor {
59
+ read(providerId?: string): Promise<ModelsStoreEntry | undefined>;
60
+ write(providerId: string, entry: ModelsStoreEntry): Promise<void>;
61
+ delete(providerId: string): Promise<void>;
62
+ }
63
+ /**
64
+ * Get (or create) the singleton models-store accessor.
65
+ * Each read parses the file fresh; writes are serialized through a promise queue
66
+ * to avoid clobbering concurrent writes.
67
+ *
68
+ * @param storePath Optional override for the store file path (defaults to ~/.dsh/models-store.json).
69
+ */
70
+ export declare function loadModelsStore(storePath?: string): ModelsStoreAccessor;
71
+ /**
72
+ * Reset the singleton accessor (for testing).
73
+ */
74
+ export declare function resetModelsStoreCache(): void;
75
+ /**
76
+ * Fetch one route's model list from pi.dev with ETag/304 revalidation.
77
+ *
78
+ * Behavior mirrors the original withRemoteCatalog.refreshModels:
79
+ * - 304 → update checkedAt, return cached entries
80
+ * - 404/501 → store empty overlay, return empty
81
+ * - transient failure → keep cached entries, return error message
82
+ * - success → parse + store + return entries
83
+ *
84
+ * @param route The provider route id (e.g. 'opencode-go')
85
+ * @param timeout Abort budget in ms (default 30s)
86
+ * @param store Optional override for the models-store accessor (testing)
87
+ * @param options Additional options (storePath, force)
88
+ */
89
+ export declare function fetchRemoteCatalog(route: string, timeout?: number, store?: ModelsStoreAccessor, options?: {
90
+ storePath?: string;
91
+ force?: boolean;
92
+ }): Promise<FetchRemoteCatalogResult>;
@@ -0,0 +1,217 @@
1
+ // Plan C (settings-seam): pi.dev remote-catalog fetch and persistent cache.
2
+ /**
3
+ * pi.dev remote-catalog fetch and persistent cache.
4
+ *
5
+ * Ported from the dsh-llm-pi-ai patch (hunk 1: withRemoteCatalog / modelsStore /
6
+ * parseRemoteCatalog / remoteModels). The original patch overlays pi.dev's model
7
+ * listing on top of the static catalog in memory; Plan C instead fetches and
8
+ * caches so translate.ts can produce the settings write target.
9
+ *
10
+ * @module dsh-model-sync/remote-catalog
11
+ */
12
+ import { homedir } from 'node:os';
13
+ import { dirname, join } from 'node:path';
14
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
15
+ // ---------------------------------------------------------------------------
16
+ // Constants (ported from docs-dsh-llm-pi-ai.patch:35-36)
17
+ // ---------------------------------------------------------------------------
18
+ /** Base URL for pi.dev model catalog API. */
19
+ export const REMOTE_CATALOG_BASE_URL = 'https://pi.dev';
20
+ /** Minimum interval between revalidation requests per provider. */
21
+ export const REMOTE_CATALOG_REFRESH_INTERVAL_MS = 4 * 60 * 60 * 1000;
22
+ /** Path to the persistent per-provider cache. */
23
+ export const MODELS_STORE_PATH = join(homedir(), '.dsh', 'models-store.json');
24
+ // ---------------------------------------------------------------------------
25
+ // parseRemoteCatalog (ported from docs-dsh-llm-pi-ai.patch:48-59)
26
+ // ---------------------------------------------------------------------------
27
+ /**
28
+ * Normalize pi.dev's response shape into a flat entry array.
29
+ * pi.dev may return: a plain array, `{ models: [...] }`, or an object of arrays.
30
+ */
31
+ export function parseRemoteCatalog(providerId, value) {
32
+ const entries = Array.isArray(value)
33
+ ? value
34
+ : typeof value === 'object' && value !== null && 'models' in value && Array.isArray(value.models)
35
+ ? value.models
36
+ : typeof value === 'object' && value !== null
37
+ ? Object.values(value)
38
+ : [];
39
+ if (entries.length === 0) {
40
+ throw new Error(`Invalid model catalog for provider "${providerId}"`);
41
+ }
42
+ return entries
43
+ .filter((entry) => {
44
+ if (typeof entry !== 'object' || entry === null || !('id' in entry))
45
+ return false;
46
+ // I-11: validate typeof id and api are strings (not just present)
47
+ if (typeof entry.id !== 'string')
48
+ return false;
49
+ if (!('api' in entry) || typeof entry.api !== 'string')
50
+ return false;
51
+ return true;
52
+ })
53
+ .map((model) => ({ ...model, provider: providerId }));
54
+ }
55
+ // ---------------------------------------------------------------------------
56
+ // Models store persistence (ported from docs-dsh-llm-pi-ai.patch:67-96)
57
+ // ---------------------------------------------------------------------------
58
+ let modelsStoreCache;
59
+ /**
60
+ * Get (or create) the singleton models-store accessor.
61
+ * Each read parses the file fresh; writes are serialized through a promise queue
62
+ * to avoid clobbering concurrent writes.
63
+ *
64
+ * @param storePath Optional override for the store file path (defaults to ~/.dsh/models-store.json).
65
+ */
66
+ export function loadModelsStore(storePath) {
67
+ const effectivePath = storePath ?? MODELS_STORE_PATH;
68
+ // Only cache when using the default path (singleton); custom paths always create fresh accessors
69
+ if (storePath === undefined && modelsStoreCache !== undefined)
70
+ return modelsStoreCache;
71
+ const readDoc = async () => {
72
+ try {
73
+ return JSON.parse(await readFile(effectivePath, 'utf8'));
74
+ }
75
+ catch {
76
+ return {};
77
+ }
78
+ };
79
+ const writeDoc = async (doc) => {
80
+ await mkdir(dirname(effectivePath), { recursive: true });
81
+ await writeFile(effectivePath, JSON.stringify(doc));
82
+ };
83
+ let queue = Promise.resolve();
84
+ const enqueue = (task) => {
85
+ const next = queue.then(task, task);
86
+ queue = next.catch(() => { });
87
+ return next;
88
+ };
89
+ const accessor = {
90
+ read: async (providerId) => {
91
+ const doc = await readDoc();
92
+ return providerId === undefined ? undefined : doc[providerId];
93
+ },
94
+ write: (providerId, entry) => enqueue(async () => {
95
+ const doc = await readDoc();
96
+ doc[providerId] = entry;
97
+ await writeDoc(doc);
98
+ }),
99
+ delete: (providerId) => enqueue(async () => {
100
+ const doc = await readDoc();
101
+ delete doc[providerId];
102
+ await writeDoc(doc);
103
+ }),
104
+ };
105
+ // Only cache the default-path accessor (singleton)
106
+ if (storePath === undefined) {
107
+ modelsStoreCache = accessor;
108
+ }
109
+ return accessor;
110
+ }
111
+ /**
112
+ * Reset the singleton accessor (for testing).
113
+ */
114
+ export function resetModelsStoreCache() {
115
+ modelsStoreCache = undefined;
116
+ }
117
+ // ---------------------------------------------------------------------------
118
+ // fetchRemoteCatalog (adapted from docs-dsh-llm-pi-ai.patch:104-151)
119
+ // ---------------------------------------------------------------------------
120
+ /**
121
+ * Fetch one route's model list from pi.dev with ETag/304 revalidation.
122
+ *
123
+ * Behavior mirrors the original withRemoteCatalog.refreshModels:
124
+ * - 304 → update checkedAt, return cached entries
125
+ * - 404/501 → store empty overlay, return empty
126
+ * - transient failure → keep cached entries, return error message
127
+ * - success → parse + store + return entries
128
+ *
129
+ * @param route The provider route id (e.g. 'opencode-go')
130
+ * @param timeout Abort budget in ms (default 30s)
131
+ * @param store Optional override for the models-store accessor (testing)
132
+ * @param options Additional options (storePath, force)
133
+ */
134
+ export async function fetchRemoteCatalog(route, timeout, store, options) {
135
+ const effectiveStore = store ?? loadModelsStore(options?.storePath);
136
+ const stored = await effectiveStore.read(route);
137
+ // I-5: throttle — return cached entries if checkedAt is within revalidation interval
138
+ if (!options?.force && stored !== undefined && stored.models.length > 0) {
139
+ const elapsed = Date.now() - stored.checkedAt;
140
+ if (elapsed >= 0 && elapsed < REMOTE_CATALOG_REFRESH_INTERVAL_MS) {
141
+ return { entries: stored.models, fromCache: true };
142
+ }
143
+ }
144
+ const url = new URL(`/api/models/providers/${encodeURIComponent(route)}`, REMOTE_CATALOG_BASE_URL);
145
+ const headers = { accept: 'application/json' };
146
+ if (stored?.models?.length && stored.etag) {
147
+ headers['if-none-match'] = stored.etag;
148
+ }
149
+ const controller = new AbortController();
150
+ const timer = timeout !== undefined
151
+ ? setTimeout(() => controller.abort(), timeout)
152
+ : undefined;
153
+ try {
154
+ const response = await fetch(url, {
155
+ headers,
156
+ signal: controller.signal,
157
+ });
158
+ const checkedAt = Date.now();
159
+ // 304: body unchanged, just refresh checkedAt
160
+ if (response.status === 304 && stored) {
161
+ await effectiveStore.write(route, { ...stored, checkedAt });
162
+ return { entries: stored.models, fromCache: true };
163
+ }
164
+ // 404/501: provider not found on pi.dev; store empty overlay
165
+ if (response.status === 404 || response.status === 501) {
166
+ const entry = {
167
+ models: stored?.models ?? [],
168
+ checkedAt,
169
+ lastModified: 0,
170
+ etag: undefined,
171
+ };
172
+ await effectiveStore.write(route, entry);
173
+ return { entries: [], fromCache: false };
174
+ }
175
+ // Transient failure: keep cached entries, report error
176
+ if (!response.ok) {
177
+ const entry = {
178
+ models: stored?.models ?? [],
179
+ checkedAt,
180
+ lastModified: stored?.lastModified ?? 0,
181
+ etag: stored?.etag,
182
+ };
183
+ await effectiveStore.write(route, entry);
184
+ return {
185
+ entries: stored?.models ?? [],
186
+ fromCache: false,
187
+ error: `Model catalog request failed for ${route}: ${response.status}`,
188
+ };
189
+ }
190
+ // Success: parse and store
191
+ const refreshed = parseRemoteCatalog(route, await response.json());
192
+ const lastModified = Date.parse(response.headers.get('last-modified') ?? '');
193
+ const etag = response.headers.get('etag') ?? undefined;
194
+ const storeEntry = {
195
+ models: refreshed,
196
+ checkedAt,
197
+ lastModified: Number.isNaN(lastModified) ? 0 : lastModified,
198
+ etag,
199
+ };
200
+ await effectiveStore.write(route, storeEntry);
201
+ return { entries: refreshed, fromCache: false };
202
+ }
203
+ catch (err) {
204
+ const message = err instanceof Error ? err.message : String(err);
205
+ // On abort or network error, return cached entries
206
+ return {
207
+ entries: stored?.models ?? [],
208
+ fromCache: false,
209
+ error: `Fetch failed for ${route}: ${message}`,
210
+ };
211
+ }
212
+ finally {
213
+ if (timer !== undefined)
214
+ clearTimeout(timer);
215
+ }
216
+ }
217
+ //# sourceMappingURL=remote-catalog.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"remote-catalog.js","sourceRoot":"","sources":["../src/remote-catalog.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAE5E;;;;;;;;;GASG;AAEH,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAA;AACjC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AACzC,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAA;AAE7D,8EAA8E;AAC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AM,EAAE;aACvE,CAAA;QACH,CAAC;QAED,2BAA2B;QAC3B,MAAM,SAAS,GAAG,kBAAkB,CAAC,KAAK,EAAE,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC,CAAA;QAClE,MAAM,YAAY,GAAG,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,eAAe,CAAC,IAAI,EAAE,CAAC,CAAA;QAC5E,MAAM,IAAI,GAAG,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,SAAS,CAAA;QAEtD,MAAM,UAAU,GAAqB;YACnC,MAAM,EAAE,SAAS;YACjB,SAAS;YACT,YAAY,EAAE,MAAM,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,YAAY;YAC3D,IAAI;SACL,CAAA;QACD,MAAM,cAAc,CAAC,KAAK,CAAC,KAAK,EAAE,UAAU,CAAC,CAAA;QAE7C,OAAO,EAAE,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,KAAK,EAAE,CAAA;IACjD,CAAC;IAAC,OAAO,GAAY,EAAE,CAAC;QACtB,MAAM,OAAO,GAAG,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAA;QAChE,mDAAmD;QACnD,OAAO;YACL,OAAO,EAAE,MAAM,EAAE,MAAM,IAAI,EAAE;YAC7B,SAAS,EAAE,KAAK;YAChB,KAAK,EAAE,oBAAoB,KAAK,KAAK,OAAO,EAAE;SAC/C,CAAA;IACH,CAAC;YAAS,CAAC;QACT,IAAI,KAAK,KAAK,SAAS;YAAE,YAAY,CAAC,KAAK,CAAC,CAAA;IAC9C,CAAC;AACH,CAAC"}
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Translate pi.dev remote catalog entries into settings-writable model profiles.
3
+ *
4
+ * Implements the 14 translation rules from the design doc §3.3, including:
5
+ * - base-matching vs base-less classification (§3.4)
6
+ * - reasoningEfforts derivation with S2 gate (§3.5)
7
+ * - compat api gate for S5 (§3.3 rules 8/9)
8
+ * - maxTokens classification (§3.3 rule 5)
9
+ * - drop logic for mixed-protocol routes (§3.3 rule 13)
10
+ * - keepBuiltinOnly behavior (§5.2)
11
+ *
12
+ * @module dsh-model-sync/translate
13
+ */
14
+ import type { RemoteCatalogEntry } from './remote-catalog.ts';
15
+ /** A model profile as written to settings.models (the narrow writable shape). */
16
+ export interface SettingsModelProfile {
17
+ id: string;
18
+ name?: string;
19
+ contextWindow?: number;
20
+ input?: string[];
21
+ maxTokens?: number;
22
+ reasoningEfforts?: Record<string, string | null>;
23
+ compat?: {
24
+ thinkingFormat?: string;
25
+ supportsReasoningEffort?: boolean;
26
+ };
27
+ [key: string]: unknown;
28
+ }
29
+ /** Options for the translation pass. */
30
+ export interface TranslateOptions {
31
+ /**
32
+ * true = target list = pi.dev ∪ builtin-only ids (smooth migration, don't
33
+ * delete existing models). false = strict mirror of pi.dev only.
34
+ */
35
+ keepBuiltinOnly: boolean;
36
+ /**
37
+ * true = drop unserviceable entries and continue; false = if any entry is
38
+ * dropped, abort the entire route (don't write).
39
+ */
40
+ dropUnserviceable: boolean;
41
+ /** Specific drop warnings to filter (currently unused, reserved). */
42
+ dropWarnings: DropWarning[];
43
+ /**
44
+ * true = force all models with non-empty thinkingFormat to have max
45
+ * reasoning effort. Skips S2 gate SRE check, ensures reasoningEfforts
46
+ * contains low/high/max, and forces compat.supportsReasoningEffort=true
47
+ * (S5 gate, openai-completions only). 400 risk is on the user.
48
+ */
49
+ forceMaxReasoningEffort: boolean;
50
+ }
51
+ /** A warning about a dropped or degraded entry. */
52
+ export interface DropWarning {
53
+ id: string;
54
+ route: string;
55
+ reason: string;
56
+ severity: 'drop' | 'degrade';
57
+ }
58
+ /** Result of the translation pass for one route. */
59
+ export interface TranslateResult {
60
+ /** Settings-writable entries, sorted by id. Empty when aborted. */
61
+ entries: SettingsModelProfile[];
62
+ /** Ids that were dropped (with reason). */
63
+ dropped: DropWarning[];
64
+ /** Ids that are degraded but still written (with reason). */
65
+ warnings: DropWarning[];
66
+ /** true when dropUnserviceable=false and drops exist — entries must not be written. */
67
+ aborted: boolean;
68
+ }
69
+ /**
70
+ * Builtin catalog data per route: needed for base-matching classification,
71
+ * maxTokens stripping, and api-gate resolution.
72
+ */
73
+ export interface BuiltinModelData {
74
+ id: string;
75
+ api: string;
76
+ maxTokens?: number;
77
+ }
78
+ /**
79
+ * Translate a route's pi.dev entries into settings-writable profiles.
80
+ *
81
+ * @param entries Raw entries from pi.dev for this route
82
+ * @param builtinIds Set of model ids present in the installed builtin catalog for this route
83
+ * @param builtinData Array of builtin catalog data (id, api, maxTokens) for this route
84
+ * @param route The route id (e.g. 'opencode-go')
85
+ * @param options Translation options
86
+ * @param builtinOnlyEntries Entries from builtin catalog that are not in pi.dev (for keepBuiltinOnly)
87
+ */
88
+ export declare function translateEntries(entries: RemoteCatalogEntry[], builtinIds: Set<string>, builtinData: BuiltinModelData[], route: string, options: TranslateOptions, builtinOnlyEntries?: RemoteCatalogEntry[]): TranslateResult;
@@ -0,0 +1,173 @@
1
+ // Plan C (settings-seam): translate pi.dev entries into settings-writable profiles.
2
+ // ---------------------------------------------------------------------------
3
+ // THINKING_LEVELS whitelist (§3.5)
4
+ // ---------------------------------------------------------------------------
5
+ /** Allowed thinking level keys and their valid wire-spelling constraints. */
6
+ const THINKING_LEVELS = new Set([
7
+ 'off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max',
8
+ ]);
9
+ // ---------------------------------------------------------------------------
10
+ // Core translation
11
+ // ---------------------------------------------------------------------------
12
+ /**
13
+ * Translate a route's pi.dev entries into settings-writable profiles.
14
+ *
15
+ * @param entries Raw entries from pi.dev for this route
16
+ * @param builtinIds Set of model ids present in the installed builtin catalog for this route
17
+ * @param builtinData Array of builtin catalog data (id, api, maxTokens) for this route
18
+ * @param route The route id (e.g. 'opencode-go')
19
+ * @param options Translation options
20
+ * @param builtinOnlyEntries Entries from builtin catalog that are not in pi.dev (for keepBuiltinOnly)
21
+ */
22
+ export function translateEntries(entries, builtinIds, builtinData, route, options, builtinOnlyEntries) {
23
+ const dropped = [];
24
+ const warnings = [];
25
+ const result = [];
26
+ for (const entry of entries) {
27
+ const isBaseMatching = builtinIds.has(entry.id);
28
+ const builtin = builtinData.find((b) => b.id === entry.id);
29
+ // Determine resolved api for compat gate (rules 8/9):
30
+ // Use builtin api if base-matching, otherwise the entry's own api
31
+ const resolvedApi = isBaseMatching && builtin ? builtin.api : entry.api;
32
+ // Rule 13: drop base-less entries only when they truly have no api
33
+ if (!isBaseMatching && (!entry.api || entry.api === '')) {
34
+ dropped.push({
35
+ id: entry.id,
36
+ route,
37
+ reason: `base-less entry "${entry.id}" has no api — cannot resolve`,
38
+ severity: 'drop',
39
+ });
40
+ continue;
41
+ }
42
+ // Rule 1: id (always written)
43
+ const profile = { id: entry.id };
44
+ // Rule 2: name
45
+ if (entry.name !== undefined)
46
+ profile.name = entry.name;
47
+ // Rule 3: contextWindow
48
+ if (entry.contextWindow !== undefined)
49
+ profile.contextWindow = entry.contextWindow;
50
+ // Rule 4: input (modalities)
51
+ if (entry.input !== undefined && entry.input.length > 0) {
52
+ profile.input = [...entry.input];
53
+ }
54
+ // Rule 5: maxTokens — base-matching: strip; base-less: keep
55
+ if (!isBaseMatching && entry.maxTokens !== undefined) {
56
+ profile.maxTokens = entry.maxTokens;
57
+ }
58
+ // base-matching: don't write maxTokens (pi-ai falls back to catalog value)
59
+ // Rule 6: reasoning (boolean) — never write
60
+ // Rule 7: reasoningEfforts — derive with S2 gate
61
+ const thinkingFormat = entry.compat?.thinkingFormat;
62
+ const supportsRE = entry.compat?.supportsReasoningEffort;
63
+ // S2 gate: thinkingFormat non-empty AND (forceMaxReasoningEffort OR supportsReasoningEffort !== false)
64
+ if (thinkingFormat !== undefined && thinkingFormat !== '' && (options.forceMaxReasoningEffort || supportsRE !== false)) {
65
+ // Derive reasoningEfforts as dict (§3.5)
66
+ profile.reasoningEfforts = deriveReasoningEfforts(entry, options.forceMaxReasoningEffort);
67
+ }
68
+ // Rules 8/9: compat.thinkingFormat / compat.supportsReasoningEffort
69
+ // S5 gate: only write when resolved api === 'openai-completions'
70
+ if (resolvedApi === 'openai-completions') {
71
+ const compat = {};
72
+ if (entry.compat?.thinkingFormat !== undefined) {
73
+ compat.thinkingFormat = entry.compat.thinkingFormat;
74
+ }
75
+ if (entry.compat?.supportsReasoningEffort !== undefined) {
76
+ compat.supportsReasoningEffort = entry.compat.supportsReasoningEffort;
77
+ }
78
+ // force mode: override supportsReasoningEffort to true (only when thinkingFormat is present)
79
+ if (options.forceMaxReasoningEffort && entry.compat?.thinkingFormat) {
80
+ compat.supportsReasoningEffort = true;
81
+ }
82
+ if (Object.keys(compat).length > 0) {
83
+ profile.compat = compat;
84
+ }
85
+ }
86
+ // else: drop the compat keys (don't drop the entry itself)
87
+ // Rules 10-12: other compat keys, api/baseUrl/provider per entry, cost/etc — never write
88
+ // Rule 14: api-divergent entries must be written (accept protocol override)
89
+ if (isBaseMatching && builtin && entry.api !== builtin.api) {
90
+ warnings.push({
91
+ id: entry.id,
92
+ route,
93
+ reason: `api divergence: pi.dev=${entry.api} vs installed=${builtin.api} — written, protocol will use installed`,
94
+ severity: 'degrade',
95
+ });
96
+ }
97
+ result.push(profile);
98
+ }
99
+ // keepBuiltinOnly: merge in builtin-only entries (§5.2)
100
+ // Emit minimal {id} only — the adapter's ...base spread restores all fields.
101
+ if (options.keepBuiltinOnly && builtinOnlyEntries !== undefined) {
102
+ for (const entry of builtinOnlyEntries) {
103
+ // Already present in pi.dev list? Skip (shouldn't happen, but guard)
104
+ if (result.some((r) => r.id === entry.id))
105
+ continue;
106
+ // Minimal profile: only id. All other fields come from ...base at runtime.
107
+ result.push({ id: entry.id });
108
+ }
109
+ }
110
+ // Sort by id for stable output (§4.4)
111
+ result.sort((a, b) => a.id.localeCompare(b.id));
112
+ // If dropUnserviceable is false and there are drops, return empty (don't write)
113
+ if (!options.dropUnserviceable && dropped.length > 0) {
114
+ return { entries: [], dropped, warnings, aborted: true };
115
+ }
116
+ return { entries: result, dropped, warnings, aborted: false };
117
+ }
118
+ // ---------------------------------------------------------------------------
119
+ // Derive reasoningEfforts (§3.5)
120
+ // ---------------------------------------------------------------------------
121
+ /**
122
+ * Derive reasoningEfforts dict from a pi.dev entry.
123
+ *
124
+ * Schema requires dict: z.dict(z.union([z.string(), z.null()]), z.union(THINKING_LEVELS)).
125
+ * Key = effort level, value = wire spelling (string|null).
126
+ *
127
+ * We derive from thinkingLevelMap when available, otherwise produce a minimal
128
+ * two-level dict with low/high using the effort name as wire spelling.
129
+ *
130
+ * Design doc §3.5: "dict { low: '<wire>', high: '<wire>' } — value is wire
131
+ * spelling, not level name; may include off: null"
132
+ *
133
+ * @param entry The pi.dev entry
134
+ * @param force When true, ensure low/high/max are all present in the result
135
+ */
136
+ function deriveReasoningEfforts(entry, force) {
137
+ const tlm = entry.thinkingLevelMap;
138
+ if (tlm !== undefined && Object.keys(tlm).length > 0) {
139
+ // Filter: only keep keys in THINKING_LEVELS whitelist with non-empty string values
140
+ const filtered = {};
141
+ for (const [k, v] of Object.entries(tlm)) {
142
+ if (!THINKING_LEVELS.has(k))
143
+ continue;
144
+ if (typeof v === 'string' && v.length > 0) {
145
+ filtered[k] = v;
146
+ }
147
+ }
148
+ // If filtering left only 'off' (or empty), supplement with low/high defaults
149
+ const nonOffKeys = Object.keys(filtered).filter((k) => k !== 'off');
150
+ if (nonOffKeys.length === 0) {
151
+ const base = { low: 'low', high: 'high' };
152
+ if (force)
153
+ base.max = 'max';
154
+ return base;
155
+ }
156
+ // force mode: ensure low/high/max are present
157
+ if (force) {
158
+ if (!filtered.low)
159
+ filtered.low = 'low';
160
+ if (!filtered.high)
161
+ filtered.high = 'high';
162
+ if (!filtered.max)
163
+ filtered.max = 'max';
164
+ }
165
+ return filtered;
166
+ }
167
+ // Fallback: minimal two-level dict (low/high)
168
+ const base = { low: 'low', high: 'high' };
169
+ if (force)
170
+ base.max = 'max';
171
+ return base;
172
+ }
173
+ //# sourceMappingURL=translate.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"translate.js","sourceRoot":"","sources":["../src/translate.ts"],"names":[],"mappings":"AAAA,oFAAoF;AAgFpF,8EAA8E;AAC9E,mCAAmC;AACnC,8EAA8E;AAE9E,6EAA6E;AAC7E,MAAM,eAAe,GAAG,IAAI,GAAG,CAAC;IAC9B,KAAK,EAAE,SAAS,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK;CAC1D,CAAC,CAAA;AAYF,8EAA8E;AAC9E,mBAAmB;AACnB,8EAA8E;AAE9E;;;;;;;;;GASG;AACH,MAAM,UAAU,gBAAgB,CAC9B,OAA6B,EAC7B,UAAuB,EACvB,WAA+B,EAC/B,KAAa,EACb,OAAyB,EACzB,kBAAyC;IAEzC,MAAM,OAAO,GAAkB,EAAE,CAAA;IACjC,MAAM,QAAQ,GAAkB,EAAE,CAAA;IAClC,MAAM,MAAM,GAA2B,EAAE,CAAA;IAEzC,KAAK,MAAM,KAAK,IAAI,OAAO,EAAE,CAAC;QAC5B,MAAM,cAAc,GAAG,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC,CAAA;QAC/C,MAAM,OAAO,GAAG,WAAW,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,KAAK,KAAK,CAAC,EAAE,CAAC,CAAA;QAE1D,sDAAsD;QACtD,kEAAkE;QAClE,MAAM,WAAW,GAAG,cAAc,IAAI,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAA;QAEvE,mEAAmE;QACnE,IAAI,CAAC,cAAc,IAAI,CAAC,CAAC,KAAK,CAAC,GAAG,IAAI,KAAK,CAAC,GAAG,KAAK,EAAE,CAAC,EAAE,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
1
+ /**
2
+ * Write translated model profiles to dsh settings via the settings.mutate API.
3
+ *
4
+ * Key behaviors (design doc §4):
5
+ * - Change-only writes: compare against raw user segment (desc.user), not
6
+ * resolved values (which have schema defaults applied)
7
+ * - Revision conflict retry: catch SETTINGS_CONFLICT, re-read, re-translate,
8
+ * re-write once
9
+ * - Never touches ~/.dsh/settings.yaml directly — only through settings.mutate
10
+ *
11
+ * @module dsh-model-sync/writer
12
+ */
13
+ import type { SettingsModelProfile } from './translate.ts';
14
+ /**
15
+ * The settings seam this module needs — injected via parameter, not imported
16
+ * from dsh internals (design doc §4.1: "writer.ts 不能直接 import dsh 的
17
+ * Context").
18
+ */
19
+ export interface SettingsDescriptor {
20
+ ns: string;
21
+ revision: number;
22
+ user?: Record<string, unknown>;
23
+ value?: Record<string, unknown>;
24
+ }
25
+ export interface SettingsMutationOp {
26
+ op: 'set';
27
+ path: string[];
28
+ value: unknown;
29
+ }
30
+ export interface SettingsService {
31
+ describe(): SettingsDescriptor[];
32
+ mutate(ns: string, ops: SettingsMutationOp[], expectedRevision?: number): Promise<void>;
33
+ }
34
+ /** Logger interface (matches ctx.logger shape). */
35
+ export interface Logger {
36
+ info(format: string, ...args: unknown[]): void;
37
+ warn(format: string, ...args: unknown[]): void;
38
+ debug(format: string, ...args: unknown[]): void;
39
+ }
40
+ export interface SyncResult {
41
+ wrote: boolean;
42
+ reason: 'no-change' | 'wrote' | 'conflict-retry-ok' | 'conflict-retry-failed' | 'skipped';
43
+ }
44
+ /**
45
+ * Deep equality check for two settings model profile arrays.
46
+ * Both arrays must be sorted by id for deterministic comparison.
47
+ */
48
+ export declare function profilesEqual(current: SettingsModelProfile[], target: SettingsModelProfile[]): boolean;
49
+ /**
50
+ * Write translated model profiles to settings for a given route.
51
+ *
52
+ * Implements the full §4 protocol:
53
+ * 1. Get revision from describe()
54
+ * 2. Compare against raw user segment (change-only write)
55
+ * 3. Call mutate with expectedRevision
56
+ * 4. On SETTINGS_CONFLICT: re-read, re-translate (caller's job), re-write once
57
+ *
58
+ * @param settings The settings service (injected, not imported)
59
+ * @param route The provider route id
60
+ * @param target Translated settings-writable entries (sorted by id)
61
+ * @param logger Logger for warnings/errors
62
+ * @param retranslate Callback to re-translate on conflict (receives new revision)
63
+ */
64
+ export declare function syncToSettings(settings: SettingsService | undefined, route: string, target: SettingsModelProfile[], logger: Logger, retranslate?: (newRevision: number) => Promise<SettingsModelProfile[]>): Promise<SyncResult>;