@samuelchung2010/dshift 0.0.0-stage → 0.3.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.
Files changed (46) hide show
  1. package/CHANGELOG.md +97 -0
  2. package/LICENSE +21 -0
  3. package/README.en.md +116 -0
  4. package/README.md +116 -3
  5. package/assets/dshift-readme.gif +0 -0
  6. package/client.js +18831 -0
  7. package/cordis.patch.yml +58 -0
  8. package/docs/architecture.md +203 -0
  9. package/docs/configuration.md +103 -0
  10. package/docs/development.md +125 -0
  11. package/docs/limitations.md +74 -0
  12. package/docs/math-boxed-qquad.png +0 -0
  13. package/docs/math-boxed-single.png +0 -0
  14. package/docs/memory-integration.md +111 -0
  15. package/docs/perf/baseline-before.json +4872 -0
  16. package/docs/perf/baseline-before.summary.json +659 -0
  17. package/docs/perf/fixed-after.json +2927 -0
  18. package/docs/perf/fixed-after.summary.json +583 -0
  19. package/docs/perf/long-chat-performance.md +340 -0
  20. package/docs/perf/merged-after.json +1953 -0
  21. package/docs/perf/merged-after.summary.json +382 -0
  22. package/docs/perf/mount-after.json +82 -0
  23. package/docs/perf/mount-baseline.json +82 -0
  24. package/docs/user-guide.md +202 -0
  25. package/icon.svg +13 -0
  26. package/index.js +16 -0
  27. package/lib/api.js +336 -0
  28. package/lib/artifact/approval-bus.js +94 -0
  29. package/lib/artifact/prompt.js +99 -0
  30. package/lib/artifact/service.js +602 -0
  31. package/lib/artifact/workspace.js +260 -0
  32. package/lib/import/convert.js +343 -0
  33. package/lib/import/format.js +262 -0
  34. package/lib/import/index.js +585 -0
  35. package/lib/import/media.js +101 -0
  36. package/lib/import/zip.js +296 -0
  37. package/lib/memory-store.js +629 -0
  38. package/lib/memory-text.js +162 -0
  39. package/lib/memory.js +871 -0
  40. package/lib/model-config.js +280 -0
  41. package/lib/protocol.js +593 -0
  42. package/lib/service.js +2102 -0
  43. package/lib/store.js +1011 -0
  44. package/locale/en.json +6 -0
  45. package/locale/zh.json +6 -0
  46. package/package.json +49 -6
@@ -0,0 +1,280 @@
1
+ /**
2
+ * Chat model catalog and the per-conversation model/effort preference.
3
+ *
4
+ * The Messages API of the DeepSeek app integration accepts exactly two model
5
+ * ids (`deepseek-flash`, `deepseek-v4-pro`) and a thinking effort of
6
+ * low / high / max (`none` means thinking off and is expressed through
7
+ * `thinking.type` instead). The client never hard-codes a different list: the
8
+ * Host publishes this catalog in the bootstrap payload, and the request is
9
+ * validated against it before it reaches DeepSeek.
10
+ *
11
+ * Preferences live in their own file next to the chat history. Per-session
12
+ * message data belongs to the history store; keeping model preferences apart
13
+ * means a conversation's model choice survives independently of message
14
+ * versioning and never rewrites the stored message format.
15
+ */
16
+
17
+ import { promises as fs } from 'node:fs'
18
+ import path from 'node:path'
19
+
20
+ export const MODEL_CONFIG_VERSION = 1
21
+
22
+ /** Effort ids the API maps to a distinct behaviour, strongest last. */
23
+ export const EFFORTS = Object.freeze(['low', 'high', 'max'])
24
+ export const DEFAULT_EFFORT = 'high'
25
+
26
+ /**
27
+ * The API accepts compatibility aliases for effort. Only the three real tiers
28
+ * are ever stored or offered in the UI; an alias is folded on the way in.
29
+ */
30
+ const EFFORT_ALIASES = Object.freeze({
31
+ minimal: 'low',
32
+ low: 'low',
33
+ medium: 'high',
34
+ high: 'high',
35
+ xhigh: 'high',
36
+ max: 'max',
37
+ ultra: 'max',
38
+ })
39
+
40
+ /**
41
+ * The real chat models. Capabilities come from the Messages API reference:
42
+ * - `deepseek-flash`: image understanding, document parsing, web tools.
43
+ * - `deepseek-v4-pro`: text reasoning only; images become "[Unsupported Image]".
44
+ * Both support thinking and the web-search server tool, but DeepSeek's web
45
+ * tool guide recommends `deepseek-flash` for the search/read-link tools.
46
+ */
47
+ export const MODEL_CATALOG = Object.freeze([
48
+ Object.freeze({
49
+ id: 'deepseek-flash',
50
+ name: 'DeepSeek V4.1 Flash',
51
+ displayName: 'DeepSeek-V4.1-Flash',
52
+ shortName: 'V4.1 Flash',
53
+ version: 'DeepSeek-V4.1-Flash-1017',
54
+ descriptionKey: 'modelFlashDesc',
55
+ capabilities: Object.freeze({
56
+ vision: true,
57
+ documents: true,
58
+ search: true,
59
+ thinking: true,
60
+ efforts: EFFORTS,
61
+ }),
62
+ }),
63
+ Object.freeze({
64
+ id: 'deepseek-v4-pro',
65
+ name: 'DeepSeek V4 Pro',
66
+ displayName: 'DeepSeek-V4-Pro',
67
+ shortName: 'V4 Pro',
68
+ version: 'DeepSeek-V4-Pro-0813',
69
+ descriptionKey: 'modelProDesc',
70
+ capabilities: Object.freeze({
71
+ vision: false,
72
+ documents: true,
73
+ search: true,
74
+ thinking: true,
75
+ efforts: EFFORTS,
76
+ }),
77
+ }),
78
+ ])
79
+
80
+ export const DEFAULT_MODEL = MODEL_CATALOG[0].id
81
+
82
+ /** The catalog entry for one id, or undefined for an unknown id. */
83
+ export function findModel(id) {
84
+ return MODEL_CATALOG.find(model => model.id === id)
85
+ }
86
+
87
+ /**
88
+ * Validate a requested model id. An absent id means the default model; an
89
+ * unknown id is a client bug or an API change, so the caller gets a clear 400
90
+ * instead of silently charging a different model.
91
+ */
92
+ export function resolveModelId(id) {
93
+ if (id === undefined || id === null || id === '') return DEFAULT_MODEL
94
+ return findModel(id) === undefined ? null : id
95
+ }
96
+
97
+ /** Clamp an effort to what the model actually supports. */
98
+ export function resolveEffort(id, modelId = DEFAULT_MODEL) {
99
+ const model = findModel(modelId) ?? findModel(DEFAULT_MODEL)
100
+ const efforts = model.capabilities.efforts
101
+ const effort = typeof id === 'string' ? EFFORT_ALIASES[id] : undefined
102
+ return effort !== undefined && efforts.includes(effort) ? effort : DEFAULT_EFFORT
103
+ }
104
+
105
+ function sanitizePreference(input, { allowModel = true } = {}) {
106
+ const patch = {}
107
+ if (input === null || typeof input !== 'object') return patch
108
+ if (allowModel && typeof input.model === 'string') {
109
+ const id = resolveModelId(input.model)
110
+ if (id !== null) patch.model = id
111
+ }
112
+ if (typeof input.effort === 'string') patch.effort = resolveEffort(input.effort, input.model)
113
+ return patch
114
+ }
115
+
116
+ function emptyState() {
117
+ return {
118
+ version: MODEL_CONFIG_VERSION,
119
+ defaults: { model: DEFAULT_MODEL, effort: DEFAULT_EFFORT },
120
+ conversations: {},
121
+ }
122
+ }
123
+
124
+ function normalizeState(input) {
125
+ const base = emptyState()
126
+ if (input === null || typeof input !== 'object') return base
127
+ const defaults = sanitizePreference(input.defaults)
128
+ base.defaults = {
129
+ model: defaults.model ?? DEFAULT_MODEL,
130
+ effort: resolveEffort(defaults.effort, defaults.model ?? DEFAULT_MODEL),
131
+ }
132
+ if (input.conversations !== null && typeof input.conversations === 'object') {
133
+ for (const [id, value] of Object.entries(input.conversations)) {
134
+ if (typeof id !== 'string' || id === '') continue
135
+ const preference = sanitizePreference(value)
136
+ if (preference.model === undefined && preference.effort === undefined) continue
137
+ base.conversations[id] = {
138
+ ...(preference.model === undefined ? {} : { model: preference.model }),
139
+ ...(preference.effort === undefined ? {} : { effort: resolveEffort(preference.effort, preference.model) }),
140
+ }
141
+ }
142
+ }
143
+ return base
144
+ }
145
+
146
+ export class ModelConfigStore {
147
+ /**
148
+ * @param directory - the Chat data directory (`$DSH_HOME/deepseek-chat`).
149
+ * @param options.logger - logger used for recoverable load/save problems.
150
+ */
151
+ constructor(directory, { logger = console } = {}) {
152
+ this.directory = directory
153
+ this.file = path.join(directory, 'model-config.json')
154
+ this.logger = logger
155
+ this.state = emptyState()
156
+ this.loaded = false
157
+ this.writeChain = Promise.resolve()
158
+ }
159
+
160
+ async load() {
161
+ if (this.loaded) return this
162
+ this.loaded = true
163
+ try {
164
+ const raw = await fs.readFile(this.file, 'utf8')
165
+ this.state = normalizeState(JSON.parse(raw))
166
+ } catch (error) {
167
+ if (error?.code !== 'ENOENT') {
168
+ // A corrupt preference file must never break chat: fall back to the
169
+ // defaults and replace the file on the next write.
170
+ this.logger.warn?.('deepseek-chat: unreadable model-config.json; using defaults', error)
171
+ this.state = emptyState()
172
+ }
173
+ }
174
+ return this
175
+ }
176
+
177
+ /** The global defaults for a new conversation. */
178
+ getDefaults() {
179
+ return { ...this.state.defaults }
180
+ }
181
+
182
+ /** The stored override of one conversation, if any. */
183
+ getConversation(id) {
184
+ if (typeof id !== 'string' || id === '') return undefined
185
+ const value = this.state.conversations[id]
186
+ return value === undefined ? undefined : { ...value }
187
+ }
188
+
189
+ /** Effective model/effort for one conversation (override, else defaults). */
190
+ resolve(conversationId) {
191
+ const override = this.getConversation(conversationId) ?? {}
192
+ const model = override.model ?? this.state.defaults.model
193
+ return {
194
+ model,
195
+ effort: resolveEffort(override.effort ?? this.state.defaults.effort, model),
196
+ }
197
+ }
198
+
199
+ /** The whole preference document for the browser. */
200
+ snapshot() {
201
+ return {
202
+ defaults: this.getDefaults(),
203
+ conversations: Object.fromEntries(
204
+ Object.entries(this.state.conversations).map(([id, value]) => [id, { ...value }]),
205
+ ),
206
+ }
207
+ }
208
+
209
+ /**
210
+ * Save a selection. Without `conversationId` it becomes the default for new
211
+ * conversations; with one it applies only to that conversation.
212
+ */
213
+ async set(conversationId, patch) {
214
+ const preference = sanitizePreference(patch)
215
+ if (conversationId === undefined || conversationId === null || conversationId === '') {
216
+ const model = preference.model ?? this.state.defaults.model
217
+ this.state.defaults = {
218
+ model,
219
+ effort: resolveEffort(preference.effort ?? this.state.defaults.effort, model),
220
+ }
221
+ } else {
222
+ const existing = this.state.conversations[conversationId] ?? {}
223
+ const model = preference.model ?? existing.model ?? this.state.defaults.model
224
+ this.state.conversations[conversationId] = {
225
+ model,
226
+ effort: resolveEffort(preference.effort ?? existing.effort ?? this.state.defaults.effort, model),
227
+ }
228
+ }
229
+ await this.save()
230
+ return this.snapshot()
231
+ }
232
+
233
+ /** Forget one conversation's override (used when it is deleted). */
234
+ async remove(conversationId) {
235
+ if (this.state.conversations[conversationId] === undefined) return false
236
+ delete this.state.conversations[conversationId]
237
+ await this.save()
238
+ return true
239
+ }
240
+
241
+ /** Drop overrides whose conversation no longer exists. */
242
+ async prune(validIds) {
243
+ const keep = new Set(Array.isArray(validIds) ? validIds : [])
244
+ let changed = false
245
+ for (const id of Object.keys(this.state.conversations)) {
246
+ if (keep.has(id)) continue
247
+ delete this.state.conversations[id]
248
+ changed = true
249
+ }
250
+ if (changed) await this.save()
251
+ return changed
252
+ }
253
+
254
+ async save() {
255
+ const write = () => this.writeNow()
256
+ this.writeChain = this.writeChain.then(write, write)
257
+ return this.writeChain
258
+ }
259
+
260
+ async writeNow() {
261
+ const temporary = `${this.file}.tmp-${process.pid}-${Math.random().toString(16).slice(2)}`
262
+ await fs.mkdir(this.directory, { recursive: true })
263
+ await fs.writeFile(temporary, `${JSON.stringify(this.state)}\n`, 'utf8')
264
+ try {
265
+ await fs.rename(temporary, this.file)
266
+ } catch (error) {
267
+ if (error?.code === 'EEXIST' || error?.code === 'EPERM' || error?.code === 'EACCES') {
268
+ await fs.copyFile(temporary, this.file)
269
+ await fs.rm(temporary, { force: true })
270
+ } else {
271
+ await fs.rm(temporary, { force: true }).catch(() => {})
272
+ throw error
273
+ }
274
+ }
275
+ }
276
+
277
+ async flush() {
278
+ await this.writeChain
279
+ }
280
+ }