@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/lib/writer.js ADDED
@@ -0,0 +1,137 @@
1
+ // Plan C (settings-seam): write translated model profiles to settings via mutate API.
2
+ // ---------------------------------------------------------------------------
3
+ // Constants
4
+ // ---------------------------------------------------------------------------
5
+ /** Error code for revision mismatch in settings.mutate. */
6
+ const SETTINGS_CONFLICT = 'SETTINGS_CONFLICT';
7
+ // ---------------------------------------------------------------------------
8
+ // Content-level comparison (§4.4)
9
+ // ---------------------------------------------------------------------------
10
+ /**
11
+ * Deep equality check for two settings model profile arrays.
12
+ * Both arrays must be sorted by id for deterministic comparison.
13
+ */
14
+ export function profilesEqual(current, target) {
15
+ if (current.length !== target.length)
16
+ return false;
17
+ for (let i = 0; i < current.length; i++) {
18
+ if (!deepEqual(current[i], target[i]))
19
+ return false;
20
+ }
21
+ return true;
22
+ }
23
+ function deepEqual(a, b) {
24
+ if (a === b)
25
+ return true;
26
+ if (a === null || b === null)
27
+ return false;
28
+ if (typeof a !== typeof b)
29
+ return false;
30
+ if (typeof a !== 'object')
31
+ return false;
32
+ const objA = a;
33
+ const objB = b;
34
+ const keysA = Object.keys(objA).sort();
35
+ const keysB = Object.keys(objB).sort();
36
+ if (keysA.length !== keysB.length)
37
+ return false;
38
+ for (let i = 0; i < keysA.length; i++) {
39
+ if (keysA[i] !== keysB[i])
40
+ return false;
41
+ if (!deepEqual(objA[keysA[i]], objB[keysB[i]]))
42
+ return false;
43
+ }
44
+ return true;
45
+ }
46
+ // ---------------------------------------------------------------------------
47
+ // Extract raw user segment (§4.4)
48
+ // ---------------------------------------------------------------------------
49
+ /**
50
+ * Extract the raw user-segment models for a route from a settings descriptor.
51
+ * Returns the raw models array (unresolved, no schema defaults applied).
52
+ */
53
+ function getRawUserModels(desc, route) {
54
+ if (desc === undefined)
55
+ return undefined;
56
+ const providers = desc.user?.providers;
57
+ if (providers === undefined)
58
+ return undefined;
59
+ const routeData = providers[route];
60
+ if (routeData === undefined)
61
+ return undefined;
62
+ const models = routeData.models;
63
+ if (!Array.isArray(models))
64
+ return undefined;
65
+ return models;
66
+ }
67
+ // ---------------------------------------------------------------------------
68
+ // syncToSettings (§4)
69
+ // ---------------------------------------------------------------------------
70
+ /**
71
+ * Write translated model profiles to settings for a given route.
72
+ *
73
+ * Implements the full §4 protocol:
74
+ * 1. Get revision from describe()
75
+ * 2. Compare against raw user segment (change-only write)
76
+ * 3. Call mutate with expectedRevision
77
+ * 4. On SETTINGS_CONFLICT: re-read, re-translate (caller's job), re-write once
78
+ *
79
+ * @param settings The settings service (injected, not imported)
80
+ * @param route The provider route id
81
+ * @param target Translated settings-writable entries (sorted by id)
82
+ * @param logger Logger for warnings/errors
83
+ * @param retranslate Callback to re-translate on conflict (receives new revision)
84
+ */
85
+ export async function syncToSettings(settings, route, target, logger, retranslate) {
86
+ if (settings === undefined) {
87
+ logger.debug('settings service unavailable; skip write for route %s', route);
88
+ return { wrote: false, reason: 'skipped' };
89
+ }
90
+ const descriptors = settings.describe();
91
+ const desc = descriptors.find((d) => d.ns === 'llm-pi-ai');
92
+ if (desc === undefined) {
93
+ logger.debug('llm-pi-ai namespace not registered; skip write for route %s', route);
94
+ return { wrote: false, reason: 'skipped' };
95
+ }
96
+ const revision = desc.revision;
97
+ const rawModels = getRawUserModels(desc, route);
98
+ // Change-only write (§4.4): compare against raw user segment
99
+ if (rawModels !== undefined && profilesEqual(rawModels, target)) {
100
+ logger.debug('no change for route %s; skip write', route);
101
+ return { wrote: false, reason: 'no-change' };
102
+ }
103
+ try {
104
+ await settings.mutate('llm-pi-ai', [{ op: 'set', path: ['providers', route, 'models'], value: target }], revision);
105
+ return { wrote: true, reason: 'wrote' };
106
+ }
107
+ catch (err) {
108
+ // Check for SETTINGS_CONFLICT
109
+ const code = err?.code;
110
+ if (code !== SETTINGS_CONFLICT) {
111
+ logger.warn('mutate failed for route %s: %s', route, err instanceof Error ? err.message : String(err));
112
+ return { wrote: false, reason: 'conflict-retry-failed' };
113
+ }
114
+ // Retry once: re-read revision, re-translate, re-write
115
+ logger.info('SETTINGS_CONFLICT for route %s; retrying once', route);
116
+ if (retranslate === undefined) {
117
+ logger.warn('no retranslate callback; giving up for route %s', route);
118
+ return { wrote: false, reason: 'conflict-retry-failed' };
119
+ }
120
+ try {
121
+ const newDescriptors = settings.describe();
122
+ const newDesc = newDescriptors.find((d) => d.ns === 'llm-pi-ai');
123
+ if (newDesc === undefined) {
124
+ logger.warn('llm-pi-ai namespace disappeared on retry for route %s', route);
125
+ return { wrote: false, reason: 'conflict-retry-failed' };
126
+ }
127
+ const newTarget = await retranslate(newDesc.revision);
128
+ await settings.mutate('llm-pi-ai', [{ op: 'set', path: ['providers', route, 'models'], value: newTarget }], newDesc.revision);
129
+ return { wrote: true, reason: 'conflict-retry-ok' };
130
+ }
131
+ catch (retryErr) {
132
+ logger.warn('conflict retry failed for route %s: %s', route, retryErr instanceof Error ? retryErr.message : String(retryErr));
133
+ return { wrote: false, reason: 'conflict-retry-failed' };
134
+ }
135
+ }
136
+ }
137
+ //# sourceMappingURL=writer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"writer.js","sourceRoot":"","sources":["../src/writer.ts"],"names":[],"mappings":"AAAA,sFAAsF;AAwDtF,8EAA8E;AAC9E,YAAY;AACZ,8EAA8E;AAE9E,2DAA2D;AAC3D,MAAM,iBAAiB,GAAG,mBAAmB,CAAA;AAE7C,8EAA8E;AAC9E,kCAAkC;AAClC,8EAA8E;AAE9E;;;GAGG;AACH,MAAM,UAAU,aAAa,CAC3B,OAA+B,EAC/B,MAA8B;IAE9B,IAAI,OAAO,CAAC,MAAM,KAAK,MAAM,CAAC,MAAM;QAAE,OAAO,KAAK,CAAA;IAClD,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;QACxC,IAAI,CA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1.0",
4
+ "description": "dsh plugin: add-only sync of llm-pi-ai provider routes' model lists from the gateway's /models endpoint, written through the settings seam",
5
+ "type": "module",
6
+ "main": "lib/index.js",
7
+ "types": "lib/index.d.ts",
8
+ "license": "MIT",
9
+ "keywords": [
10
+ "dsh",
11
+ "plugin",
12
+ "model",
13
+ "sync",
14
+ "catalog"
15
+ ],
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/fan56/dsh-model-sync.git"
19
+ },
20
+ "homepage": "https://github.com/fan56/dsh-model-sync",
21
+ "engines": {
22
+ "node": ">=22.19.0"
23
+ },
24
+ "files": [
25
+ "lib",
26
+ "cordis.patch.yml",
27
+ "src"
28
+ ],
29
+ "scripts": {
30
+ "build": "tsc -p tsconfig.json",
31
+ "check": "tsc --noEmit -p tsconfig.json",
32
+ "pretest": "tsc -p tsconfig.json",
33
+ "test": "node --test test/diff.test.mjs test/translate.test.mjs test/writer.test.mjs test/remote-catalog.test.mjs test/serviceability.test.mjs"
34
+ },
35
+ "dependencies": {},
36
+ "peerDependencies": {
37
+ "@deepseek-ai/cordis": "4.0.1",
38
+ "@deepseek-ai/dsh-credentials": "0.1.0-rc.6",
39
+ "@deepseek-ai/dsh-settings": "0.1.0-rc.6",
40
+ "@deepseek-ai/schemastery": "3.18.1"
41
+ },
42
+ "peerDependenciesMeta": {
43
+ "@deepseek-ai/cordis": { "optional": true },
44
+ "@deepseek-ai/dsh-credentials": { "optional": true },
45
+ "@deepseek-ai/dsh-settings": { "optional": true },
46
+ "@deepseek-ai/schemastery": { "optional": true }
47
+ },
48
+ "devDependencies": {
49
+ "@types/node": "^24.0.0",
50
+ "@deepseek-ai/cordis": "4.0.1",
51
+ "@deepseek-ai/dsh-credentials": "0.1.0-rc.6",
52
+ "@deepseek-ai/dsh-settings": "0.1.0-rc.6",
53
+ "@deepseek-ai/schemastery": "3.18.1",
54
+ "typescript": "^5.9.0"
55
+ },
56
+ "dsh": {
57
+ "bundle": {
58
+ "patch": "./cordis.patch.yml"
59
+ }
60
+ },
61
+ "author": "fliu56",
62
+ "publishConfig": {
63
+ "access": "public"
64
+ }
65
+ }
@@ -0,0 +1,60 @@
1
+ // Plan C (settings-seam): builtin catalog snapshot — single source of truth.
2
+
3
+ /**
4
+ * Builtin catalog snapshot for base-matching classification and maxTokens
5
+ * stripping (design doc §3.6).
6
+ *
7
+ * This module is the single source of truth for the hardcoded builtin catalog
8
+ * data used by index.ts, translate.test.mjs, and serviceability.test.mjs.
9
+ *
10
+ * To regenerate: run `node scripts/generate-builtin-snapshot.mjs --generate`
11
+ *
12
+ * @module dsh-model-sync/builtin-catalog-snapshot
13
+ */
14
+
15
+ import type { BuiltinModelData } from './translate.ts'
16
+
17
+ /** Per-route builtin catalog snapshot. */
18
+ export interface BuiltinCatalogSnapshotMap {
19
+ [route: string]: BuiltinModelData[]
20
+ }
21
+
22
+ /** Builtin catalog data keyed by route id. */
23
+ export const BUILTIN_CATALOG_SNAPSHOT: BuiltinCatalogSnapshotMap = {
24
+ 'minimax-cn': [
25
+ { id: 'MiniMax-M2.7', api: 'anthropic-messages', maxTokens: 131072 },
26
+ { id: 'MiniMax-M2.7-highspeed', api: 'anthropic-messages', maxTokens: 131072 },
27
+ { id: 'MiniMax-M3', api: 'anthropic-messages', maxTokens: 128000 }
28
+ ],
29
+ 'opencode-go': [
30
+ { id: 'deepseek-v4-flash', api: 'openai-completions', maxTokens: 384000 },
31
+ { id: 'deepseek-v4-pro', api: 'openai-completions', maxTokens: 384000 },
32
+ { id: 'glm-5.1', api: 'openai-completions', maxTokens: 32768 },
33
+ { id: 'glm-5.2', api: 'openai-completions', maxTokens: 131072 },
34
+ { id: 'grok-4.5', api: 'openai-responses', maxTokens: 500000 },
35
+ { id: 'hy3', api: 'openai-completions', maxTokens: 64000 },
36
+ { id: 'kimi-k2.6', api: 'openai-completions', maxTokens: 65536 },
37
+ { id: 'kimi-k2.7-code', api: 'openai-completions', maxTokens: 262144 },
38
+ { id: 'kimi-k3', api: 'openai-completions', maxTokens: 131072 },
39
+ { id: 'mimo-v2.5', api: 'openai-completions', maxTokens: 128000 },
40
+ { id: 'mimo-v2.5-pro', api: 'openai-completions', maxTokens: 128000 },
41
+ { id: 'minimax-m2.7', api: 'openai-completions', maxTokens: 131072 },
42
+ { id: 'minimax-m3', api: 'anthropic-messages', maxTokens: 131072 },
43
+ { id: 'qwen3.6-plus', api: 'openai-completions', maxTokens: 65536 },
44
+ { id: 'qwen3.7-max', api: 'anthropic-messages', maxTokens: 65536 },
45
+ { id: 'qwen3.7-plus', api: 'anthropic-messages', maxTokens: 65536 }
46
+ ],
47
+ 'xiaomi-token-plan-cn': [
48
+ { id: 'mimo-v2-pro', api: 'openai-completions', maxTokens: 131072 },
49
+ { id: 'mimo-v2.5', api: 'openai-completions', maxTokens: 131072 },
50
+ { id: 'mimo-v2.5-pro', api: 'openai-completions', maxTokens: 131072 }
51
+ ],
52
+ 'zai-coding-cn': [
53
+ { id: 'glm-4.5-air', api: 'openai-completions', maxTokens: 98304 },
54
+ { id: 'glm-4.7', api: 'openai-completions', maxTokens: 131072 },
55
+ { id: 'glm-5-turbo', api: 'openai-completions', maxTokens: 131072 },
56
+ { id: 'glm-5.1', api: 'openai-completions', maxTokens: 131072 },
57
+ { id: 'glm-5.2', api: 'openai-completions', maxTokens: 131072 },
58
+ { id: 'glm-5v-turbo', api: 'openai-completions', maxTokens: 131072 }
59
+ ]
60
+ }
package/src/diff.ts ADDED
@@ -0,0 +1,139 @@
1
+ // Plan C (settings-seam): diff utilities for model sync reporting.
2
+
3
+ /**
4
+ * Diff utilities for model sync: id-level diff (existing) and content-level
5
+ * diff (new, §4.4 change detection and §7.4 report).
6
+ *
7
+ * @module dsh-model-sync/diff
8
+ */
9
+
10
+ import type { SettingsModelProfile } from './translate.ts'
11
+
12
+ // ---------------------------------------------------------------------------
13
+ // Existing: id-level diff (unchanged)
14
+ // ---------------------------------------------------------------------------
15
+
16
+ export interface ModelIdDiff {
17
+ added: string[]
18
+ removed: string[]
19
+ }
20
+
21
+ /**
22
+ * Compare a provider's model ids before and after a refresh. Order of the
23
+ * `after` list is preserved for `added`; `removed` keeps the `before` order.
24
+ */
25
+ export function diffModelIds(before: readonly string[], after: readonly string[]): ModelIdDiff {
26
+ const afterSet = new Set(after)
27
+ const removed = before.filter((id) => !afterSet.has(id))
28
+ const beforeSet = new Set(before)
29
+ const added = after.filter((id) => !beforeSet.has(id))
30
+ return { added, removed }
31
+ }
32
+
33
+ // ---------------------------------------------------------------------------
34
+ // New: content-level diff (§4.4)
35
+ // ---------------------------------------------------------------------------
36
+
37
+ export interface FieldDiff {
38
+ id: string
39
+ field: string
40
+ current: unknown
41
+ target: unknown
42
+ }
43
+
44
+ export interface EntryDiffResult {
45
+ /** Entries in target but not current (new models). */
46
+ added: string[]
47
+ /** Entries in current but not target (removed models). */
48
+ removed: string[]
49
+ /** Entries present in both but with field-level changes. */
50
+ changed: FieldDiff[]
51
+ /** true if there are any differences. */
52
+ hasChanges: boolean
53
+ }
54
+
55
+ /**
56
+ * Content-level diff between current and target settings model profiles.
57
+ *
58
+ * Both arrays must be sorted by id (as translateEntries and settings raw
59
+ * segments are). Reports added/removed ids and per-field changes for
60
+ * entries present in both.
61
+ */
62
+ export function diffEntries(
63
+ current: SettingsModelProfile[],
64
+ target: SettingsModelProfile[],
65
+ ): EntryDiffResult {
66
+ const currentById = new Map(current.map((e) => [e.id, e]))
67
+ const targetById = new Map(target.map((e) => [e.id, e]))
68
+
69
+ const added: string[] = []
70
+ const removed: string[] = []
71
+ const changed: FieldDiff[] = []
72
+
73
+ // Find added (in target, not current)
74
+ for (const id of targetById.keys()) {
75
+ if (!currentById.has(id)) added.push(id)
76
+ }
77
+
78
+ // Find removed (in current, not target)
79
+ for (const id of currentById.keys()) {
80
+ if (!targetById.has(id)) removed.push(id)
81
+ }
82
+
83
+ // Find changed (in both, compare fields)
84
+ for (const [id, targetEntry] of targetById) {
85
+ const currentEntry = currentById.get(id)
86
+ if (currentEntry === undefined) continue
87
+
88
+ const allKeys = new Set([...Object.keys(currentEntry), ...Object.keys(targetEntry)])
89
+ for (const key of allKeys) {
90
+ if (key === 'id') continue
91
+ const currentVal = currentEntry[key]
92
+ const targetVal = targetEntry[key]
93
+ if (!shallowEqual(currentVal, targetVal)) {
94
+ changed.push({ id, field: key, current: currentVal, target: targetVal })
95
+ }
96
+ }
97
+ }
98
+
99
+ return {
100
+ added,
101
+ removed,
102
+ changed,
103
+ hasChanges: added.length > 0 || removed.length > 0 || changed.length > 0,
104
+ }
105
+ }
106
+
107
+ /**
108
+ * Shallow/structural equality for diff comparison.
109
+ * Handles primitives, arrays (element-wise), and plain objects (key-wise).
110
+ */
111
+ function shallowEqual(a: unknown, b: unknown): boolean {
112
+ if (a === b) return true
113
+ if (a === undefined && b === undefined) return true
114
+ if (a === null && b === null) return true
115
+ if (a === null || b === null) return false
116
+ if (typeof a !== typeof b) return false
117
+ if (typeof a !== 'object') return false
118
+
119
+ if (Array.isArray(a) && Array.isArray(b)) {
120
+ if (a.length !== b.length) return false
121
+ for (let i = 0; i < a.length; i++) {
122
+ if (a[i] !== b[i]) return false
123
+ }
124
+ return true
125
+ }
126
+
127
+ if (Array.isArray(a) !== Array.isArray(b)) return false
128
+
129
+ const objA = a as Record<string, unknown>
130
+ const objB = b as Record<string, unknown>
131
+ const keysA = Object.keys(objA).sort()
132
+ const keysB = Object.keys(objB).sort()
133
+ if (keysA.length !== keysB.length) return false
134
+ for (let i = 0; i < keysA.length; i++) {
135
+ if (keysA[i] !== keysB[i]) return false
136
+ if (objA[keysA[i]] !== objB[keysB[i]]) return false
137
+ }
138
+ return true
139
+ }