dsh-plugin-console-oh 0.0.0-stage → 0.6.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 (38) hide show
  1. package/README.md +80 -2
  2. package/cordis.patch.yml +16 -0
  3. package/lib/client.js +451 -0
  4. package/lib/index.js +1358 -0
  5. package/lib/server.mjs +681 -0
  6. package/lib/tunnel.mjs +238 -0
  7. package/lib/vendor/README.md +11 -0
  8. package/lib/vendor/dijkstrajs/LICENSE.md +19 -0
  9. package/lib/vendor/dijkstrajs/index.js +165 -0
  10. package/lib/vendor/dijkstrajs/package.json +5 -0
  11. package/lib/vendor/qrcode/LICENSE +10 -0
  12. package/lib/vendor/qrcode/core/alignment-pattern.js +83 -0
  13. package/lib/vendor/qrcode/core/alphanumeric-data.js +59 -0
  14. package/lib/vendor/qrcode/core/bit-buffer.js +37 -0
  15. package/lib/vendor/qrcode/core/bit-matrix.js +65 -0
  16. package/lib/vendor/qrcode/core/byte-data.js +30 -0
  17. package/lib/vendor/qrcode/core/error-correction-code.js +135 -0
  18. package/lib/vendor/qrcode/core/error-correction-level.js +50 -0
  19. package/lib/vendor/qrcode/core/finder-pattern.js +22 -0
  20. package/lib/vendor/qrcode/core/format-info.js +29 -0
  21. package/lib/vendor/qrcode/core/galois-field.js +69 -0
  22. package/lib/vendor/qrcode/core/kanji-data.js +54 -0
  23. package/lib/vendor/qrcode/core/mask-pattern.js +234 -0
  24. package/lib/vendor/qrcode/core/mode.js +167 -0
  25. package/lib/vendor/qrcode/core/numeric-data.js +43 -0
  26. package/lib/vendor/qrcode/core/polynomial.js +62 -0
  27. package/lib/vendor/qrcode/core/qrcode.js +495 -0
  28. package/lib/vendor/qrcode/core/reed-solomon-encoder.js +56 -0
  29. package/lib/vendor/qrcode/core/regex.js +31 -0
  30. package/lib/vendor/qrcode/core/segments.js +330 -0
  31. package/lib/vendor/qrcode/core/utils.js +63 -0
  32. package/lib/vendor/qrcode/core/version-check.js +9 -0
  33. package/lib/vendor/qrcode/core/version.js +163 -0
  34. package/lib/vendor/qrcode/index.js +20 -0
  35. package/lib/vendor/qrcode/package.json +5 -0
  36. package/lib/vendor/qrcode/renderer/svg-tag.js +81 -0
  37. package/lib/vendor/qrcode/renderer/utils.js +99 -0
  38. package/package.json +64 -4
package/lib/index.js ADDED
@@ -0,0 +1,1358 @@
1
+ import fs from 'node:fs'
2
+ // DSH 控制台 · 宿主半边
3
+ // 职责:把 sessionController 包成手机能用的 4 个动作(列会话 / 读轮次 / 发消息 / 停),
4
+ // 起局域网服务,按需拉 cloudflared 隧道,并把面板数据注册给 DSH 客户端。
5
+ import os from 'node:os'
6
+ import path from 'node:path'
7
+ import { randomUUID } from 'node:crypto'
8
+ import { createRequire } from 'node:module'
9
+ import { createConsoleServer, VERSION } from './server.mjs'
10
+ import { CloudflaredTunnel } from './tunnel.mjs'
11
+
12
+ export const name = 'dsh-console-oh'
13
+ // connection 是面板用的,拿不到也不该拖垮整个插件,所以只在需要时 ctx.get
14
+ export const inject = ['sessionController']
15
+
16
+ const STATE_PATH = '/api/dsh-console-oh/state'
17
+ const NEWCODE_PATH = '/api/dsh-console-oh/newcode'
18
+ const TOGGLE_PATH = '/api/dsh-console-oh/toggle'
19
+ const TUNNEL_PATH = '/api/dsh-console-oh/tunnel'
20
+ const QR_PATH = '/api/dsh-console-oh/qr'
21
+ const SESSIONS_PATH = '/api/dsh-console-oh/sessions'
22
+ const TURNS_PATH = '/api/dsh-console-oh/turns'
23
+ const SEND_PATH = '/api/dsh-console-oh/send'
24
+
25
+ const log = (...a) => {
26
+ try { console.log('[dsh-console-oh]', ...a) } catch (_) { }
27
+ }
28
+
29
+ function timeout(ms) { return AbortSignal.timeout(ms) }
30
+
31
+ /** 单轮思考上限:正常轮次全量下发(不再 4000 字就截),只挡 10 万字级的病态长思考 */
32
+ const THINKING_MAX = 120000
33
+ /** 一次 /v1/turns 里所有思考过程的总预算,按「从新到旧」分配 */
34
+ const THINKING_BUDGET = 400000
35
+
36
+ function clean(s, max) {
37
+ const t = String(s == null ? '' : s)
38
+ return t.length > max ? t.slice(0, max) : t
39
+ }
40
+
41
+ // 二维码用内联的小实现(lib/vendor/qrcode),不依赖 profile 里装没装三方包
42
+ const requireFrom = createRequire(import.meta.url)
43
+ let qrMod = null
44
+ function qrSvg(text) {
45
+ if (!qrMod) qrMod = requireFrom('./vendor/qrcode/index.js')
46
+ return qrMod.toSvg(text, {
47
+ margin: 1,
48
+ width: 260,
49
+ ecc: 'M',
50
+ dark: '#0E0F12ff',
51
+ light: '#ffffffff'
52
+ })
53
+ }
54
+
55
+ function evMs(ev) {
56
+ const raw = ev && (ev.time || ev.ts || ev.createdAt || ev.timestamp)
57
+ const n = Number(raw) || 0
58
+ if (n <= 0) return 0
59
+ return n > 1e12 ? n : n * 1000
60
+ }
61
+
62
+ function contentText(content) {
63
+ if (!content) return ''
64
+ if (typeof content === 'string') return content
65
+ if (!Array.isArray(content)) return ''
66
+ const parts = []
67
+ for (const b of content) {
68
+ if (b && b.type === 'text' && typeof b.text === 'string' && b.text) parts.push(b.text)
69
+ }
70
+ return parts.join('\n')
71
+ }
72
+
73
+ // 思考过程是单独的 reasoning 内容块(DSH 网页端也是从这里渲染的),
74
+ // 不能混进正文,否则手机上会把「想」和「答」揉成一段。
75
+ function contentReasoning(content) {
76
+ if (!content || !Array.isArray(content)) return ''
77
+ const parts = []
78
+ for (const b of content) {
79
+ if (!b) continue
80
+ const t = String(b.type || '')
81
+ if (t !== 'reasoning' && t !== 'reasoning-text') continue
82
+ const txt = typeof b.text === 'string' ? b.text : (typeof b.reasoning === 'string' ? b.reasoning : '')
83
+ if (txt) parts.push(txt)
84
+ }
85
+ return parts.join('\n\n')
86
+ }
87
+
88
+ // 有些插件(hindsight / hook / system-reminder)会把上下文塞进用户消息里,
89
+ // 手机上会把「你是谁」+ 一大段内部提示渲染成同一句话,看着像发错了。
90
+ // 这些块有固定标签,直接在展示层剥掉(电脑端记录不动)。
91
+ const INJECT_TAG = /<(hook_prompt|task-notification|system-reminder|hindsight_memory|hindsight_memories|hindsight_bank|relevant_memories|user_feedback|hindsight_pages|hindsight_page_refresh|hindsight_knowledge|hindsight_knowledge_refresh)\b[^>]*>[\s\S]*?<\/\1>/g
92
+
93
+ function stripInjected(text) {
94
+ let t = String(text == null ? '' : text)
95
+ if (t.indexOf('<') >= 0) t = t.replace(INJECT_TAG, '')
96
+ // 还有一类注入不带标签:直接以「[Plugin context from "xxx"...]」开头追加在用户消息后面
97
+ // (如 batching-guidance)。这类内容一律从标记处截断,只留用户真正打的字。
98
+ const markers = ['[Plugin context from "', '[Plugin context from ', '[System context from "', '[Hook context from "',
99
+ 'Time sampled while preparing', 'Browser time zone for this request', 'Elapsed since the preceding',
100
+ '[model changed:', 'model changed: assistant turns above']
101
+ for (const m of markers) {
102
+ const i = t.indexOf(m)
103
+ if (i >= 0) t = t.substring(0, i)
104
+ }
105
+ // 还有一种以裸时间戳开头的旁白(billion-context 追加):\n\n2026-11-20T21:44:16+08:00[Asia/Shanghai]
106
+ const m2 = t.match(/\n{2,}20\d{2}-\d{2}-\d{2}T\d{2}:\d{2}/)
107
+ if (m2 && m2.index !== undefined) t = t.substring(0, m2.index)
108
+ return t.replace(/\n{3,}/g, '\n\n').trim()
109
+ }
110
+
111
+ // 采样用:数一下 assistant/message 里到底有哪些内容块
112
+ function blockTypes(content, out) {
113
+ if (!content || !Array.isArray(content)) return
114
+ for (const b of content) {
115
+ const t = String((b && b.type) || '?')
116
+ out[t] = (out[t] || 0) + 1
117
+ }
118
+ }
119
+
120
+ function historyEvents(h) {
121
+ if (!h) return []
122
+ if (Array.isArray(h)) return h
123
+ if (Array.isArray(h.events)) return h.events
124
+ if (h.value && Array.isArray(h.value.events)) return h.value.events
125
+ if (h.history && Array.isArray(h.history.events)) return h.history.events
126
+ if (Array.isArray(h.records)) return h.records
127
+ return []
128
+ }
129
+
130
+ // 从历史事件流里折出「完整正文」。turnOutline 是模型生成的摘要,长回答会被截断;
131
+ // 真正逐字的内容在 user/message 与 assistant/message 的 content 块里。
132
+ export function foldHistory(h) {
133
+ const out = []
134
+ const byNo = new Map()
135
+ let lastNo = 0
136
+
137
+ const note = (no, seq, ev) => {
138
+ let n = Number(no) || 0
139
+ if (n < 1) n = lastNo
140
+ if (n < 1) n = out.length + 1
141
+ let t = byNo.get(n)
142
+ if (!t) {
143
+ t = {
144
+ turn: n,
145
+ seq: Number(seq) || 0,
146
+ prompt: '',
147
+ response: '',
148
+ thinking: '',
149
+ chunk: '',
150
+ thinkingChunk: '',
151
+ startedMs: 0,
152
+ endedMs: 0,
153
+ full: false
154
+ }
155
+ byNo.set(n, t)
156
+ out.push(t)
157
+ }
158
+ if (!t.seq && Number(seq)) t.seq = Number(seq)
159
+ if (!t.startedMs) t.startedMs = evMs(ev)
160
+ return t
161
+ }
162
+
163
+ for (const raw of historyEvents(h)) {
164
+ const ev = raw && typeof raw === 'object' && raw.event ? raw.event : raw
165
+ if (!ev || typeof ev.type !== 'string') continue
166
+ const d = ev.data || {}
167
+ const n = Number(d.turn) || 0
168
+ if (n > 0) lastNo = n
169
+
170
+ if (ev.type === 'user/message') {
171
+ // 剥掉插件注入的上下文标签,只留用户真正打的那句话
172
+ const txt = stripInjected(contentText(d.content))
173
+ if (!txt) continue
174
+ const t = note(n, ev.seq, ev)
175
+ t.prompt = t.prompt ? t.prompt + '\n\n' + txt : txt
176
+ } else if (ev.type === 'assistant/message') {
177
+ const m = d.message || d
178
+ const txt = contentText(m && m.content)
179
+ const think = contentReasoning(m && m.content)
180
+ const t = note(n, ev.seq, ev)
181
+ if (txt) {
182
+ t.response = t.response ? t.response + '\n\n' + txt : txt
183
+ t.full = true
184
+ }
185
+ if (think) t.thinking = t.thinking ? t.thinking + '\n\n' + think : think
186
+ } else if (ev.type === 'assistant/chunk') {
187
+ const c = d.chunk || {}
188
+ if (c.type === 'text-delta' && typeof c.text === 'string' && c.text) {
189
+ note(n, ev.seq, ev).chunk += c.text
190
+ } else if (c.type === 'reasoning-delta' && typeof c.text === 'string' && c.text) {
191
+ note(n, ev.seq, ev).thinkingChunk += c.text
192
+ }
193
+ } else if (ev.type === 'turn/end') {
194
+ note(n, ev.seq, ev).endedMs = evMs(ev)
195
+ }
196
+ }
197
+
198
+ for (const t of out) {
199
+ if (!t.response && t.chunk) t.response = t.chunk
200
+ if (!t.thinking && t.thinkingChunk) t.thinking = t.thinkingChunk
201
+ delete t.chunk
202
+ delete t.thinkingChunk
203
+ delete t.full
204
+ // 思考过程可能几万字(实测单轮最高 57 万),整段下发会把隧道和手机都拖死。
205
+ // 留开头看思路、留结尾看结论,中间省略。
206
+ if (t.thinking && t.thinking.length > THINKING_MAX) {
207
+ const cut = t.thinking.length - THINKING_MAX
208
+ t.thinking = t.thinking.slice(0, THINKING_MAX - 1200)
209
+ + '\n\n…(中间省略 ' + cut + ' 字)…\n\n'
210
+ + t.thinking.slice(-1200)
211
+ }
212
+ if (!t.thinking) delete t.thinking
213
+ }
214
+ return out.filter((t) => t.prompt || t.response)
215
+ }
216
+
217
+ // 读会话的完整历史事件。DSH 新版入口是 events(),page() 只是给旧客户端的别名;
218
+ // 一次只返回「消息预算内」的尾部,所以 hasMore 时要按 cursor 继续往前翻,
219
+ // 否则早先的轮次会整段缺失(手机上看就是对话只剩最后几条)。
220
+ export async function readSessionHistory(c, sessionId, maxPages = 8, firstPageOnly = false) {
221
+ let method = ''
222
+ if (typeof c.events === 'function') method = 'events'
223
+ else if (typeof c.page === 'function') method = 'page'
224
+ if (method === '') return { method, events: [], pages: 0, hasMore: false, fromSeq: 0 }
225
+
226
+ const events = []
227
+ const seen = new Set()
228
+ let beforeSeq = 0
229
+ let pages = 0
230
+ let hasMore = false
231
+ for (let i = 0; i < maxPages; i++) {
232
+ const req = { address: { kind: 'session', sessionId }, maxMessages: 200 }
233
+ if (beforeSeq > 0) req.beforeSeq = beforeSeq
234
+ const page = await c[method](req, timeout(20000))
235
+ pages += 1
236
+ let minSeq = Number.POSITIVE_INFINITY
237
+ for (const raw of historyEvents(page)) {
238
+ const ev = raw && typeof raw === 'object' && raw.event ? raw.event : raw
239
+ const seq = Number(ev && ev.seq)
240
+ if (Number.isFinite(seq)) {
241
+ if (seq < minSeq) minSeq = seq
242
+ if (seen.has(seq)) continue
243
+ seen.add(seq)
244
+ }
245
+ events.push(raw)
246
+ }
247
+ hasMore = !!(page && page.hasMore === true)
248
+ if (!hasMore || firstPageOnly) break
249
+ // page.cursor 是「这次读到的日志切点」,不是下一页的游标,拿它当 beforeSeq 会原地打转。
250
+ // 真正的前进量是本页最老那条事件的 seq。
251
+ const next = Number.isFinite(minSeq) && minSeq > 0 ? minSeq : 0
252
+ // 没前进就停,避免死循环
253
+ if (next <= 0) break
254
+ if (beforeSeq > 0 && next >= beforeSeq) break
255
+ beforeSeq = next
256
+ }
257
+ events.sort((a, b) => {
258
+ const ea = a && typeof a === 'object' && a.event ? a.event : a
259
+ const eb = b && typeof b === 'object' && b.event ? b.event : b
260
+ return (Number(ea && ea.seq) || 0) - (Number(eb && eb.seq) || 0)
261
+ })
262
+ const first = events.length > 0 ? events[0] : null
263
+ const fe = first && typeof first === 'object' && first.event ? first.event : first
264
+ return { method, events, pages, hasMore, fromSeq: Number(fe && fe.seq) || 0 }
265
+ }
266
+
267
+ export function mergeTurns(outline, full) {
268
+ if (!full || full.length === 0) return outline
269
+ const byNo = new Map()
270
+ for (const t of outline) byNo.set(Number(t.turn) || 0, t)
271
+ for (const f of full) {
272
+ const n = Number(f.turn) || 0
273
+ const base = byNo.get(n)
274
+ if (!base) {
275
+ byNo.set(n, {
276
+ turn: n,
277
+ seq: f.seq,
278
+ prompt: f.prompt,
279
+ response: f.response,
280
+ thinking: f.thinking,
281
+ startedMs: f.startedMs,
282
+ endedMs: f.endedMs
283
+ })
284
+ continue
285
+ }
286
+ // 摘要可能比全文长(加了「…」),取更长的那个
287
+ if (f.prompt && f.prompt.length > base.prompt.length) base.prompt = f.prompt
288
+ if (f.response && f.response.length > base.response.length) base.response = f.response
289
+ if (f.thinking && (!base.thinking || f.thinking.length > base.thinking.length)) base.thinking = f.thinking
290
+ if (!base.startedMs) base.startedMs = f.startedMs
291
+ if (!base.endedMs) base.endedMs = f.endedMs
292
+ }
293
+ const out = []
294
+ for (const t of byNo.values()) if (t.prompt || t.response) out.push(t)
295
+ out.sort((a, b) => (Number(a.turn) || 0) - (Number(b.turn) || 0))
296
+ return out
297
+ }
298
+
299
+ function turnList(values) {
300
+ const raw = values && Array.isArray(values.turnOutline) ? values.turnOutline : []
301
+ const out = []
302
+ for (const t of raw) {
303
+ const prompt = stripInjected(clean(t && t.prompt, 20000))
304
+ const response = clean(t && t.response, 60000)
305
+ if (!prompt && !response) continue
306
+ out.push({
307
+ turn: Number(t && t.turn) || out.length + 1,
308
+ seq: Number(t && t.seq) || 0,
309
+ prompt,
310
+ response,
311
+ startedMs: Number(t && t.startedMs) || 0,
312
+ endedMs: Number(t && t.endedMs) || 0
313
+ })
314
+ }
315
+ return out
316
+ }
317
+
318
+ export function apply(ctx, config = {}) {
319
+ const cfg = config || {}
320
+ const dataDir = path.join(os.homedir(), '.dsh', 'dsh-console-oh')
321
+ const port = Number(cfg.port) || 8909
322
+ const nodeName = String(cfg.name || os.hostname() || 'DSH 电脑')
323
+
324
+ const ctl = () => {
325
+ try { return ctx && typeof ctx.get === 'function' ? ctx.get('sessionController') : null } catch (_) { return null }
326
+ }
327
+
328
+ // 会话 → { asOf, at, turns }:完整正文比摘要贵,按 asOfSeq 复用
329
+ const histCache = new Map()
330
+
331
+ // ── 已删除会话:DSH 没有删除接口,只能把会话目录挪进回收站 ─────────────
332
+ // 直接 rm 太狠(误删没救),挪到 dataDir/trash/<id> 还能手工捞回来;
333
+ // hidden.json 记住 id,列表里过滤掉(DSH 进程内可能仍持有会话对象)。
334
+ const hiddenPath = path.join(dataDir, 'hidden.json')
335
+ const trashDir = path.join(dataDir, 'trash')
336
+ let hidden = {}
337
+ try {
338
+ const raw = JSON.parse(fs.readFileSync(hiddenPath, 'utf8'))
339
+ hidden = (raw && raw.ids) || {}
340
+ } catch (_) { hidden = {} }
341
+
342
+ const saveHidden = () => {
343
+ try {
344
+ fs.mkdirSync(dataDir, { recursive: true })
345
+ fs.writeFileSync(hiddenPath, JSON.stringify({ ids: hidden }, null, 1))
346
+ } catch (_) { }
347
+ }
348
+
349
+ // ── 模式(DSH 的 agent preset)───────────────────────────────────────
350
+ // 官方只有 standard(标准)和 creator(创造)两种固定叫法,其余全部由
351
+ // agent preset 注册表动态给出:用户在 dsh 里装/删模式插件,这里跟着变,
352
+ // 不为某个具体插件(比如 dsh-ops)写死任何判断。
353
+ const presetRoot = path.join(os.homedir(), '.dsh', '.agent-presets')
354
+ const OFFICIAL_MODES = {
355
+ standard: { name: '标准模式', description: '写代码、读文件、查资料,日常任务用它' },
356
+ creator: { name: '创造模式', description: '让 Agent 帮你做预设模式或插件,扩展 DSH 的能力' }
357
+ }
358
+ /** 官方预设在注册表里通常不带 name(靠本地化文案),这里补齐中文名 */
359
+ const KNOWN_NAMES = {
360
+ standard: '标准模式',
361
+ creator: '创造模式',
362
+ ptc: 'PTC 模式',
363
+ minimal: '极简模式',
364
+ cordis: 'Cordis 模式'
365
+ }
366
+ let modesRev = 1
367
+ let modesSnap = { rev: 1, modes: [] }
368
+ let modesWatcher = null
369
+
370
+ const bumpModes = () => {
371
+ modesRev = Date.now()
372
+ }
373
+
374
+ /** preset.yml 只有 name / description / order 三个字段,手写解析够了,不引 yaml 依赖 */
375
+ function readPresetMeta(dir) {
376
+ const meta = { id: path.basename(dir), name: '', description: '', order: 0 }
377
+ try {
378
+ const txt = fs.readFileSync(path.join(dir, 'preset.yml'), 'utf8')
379
+ for (const raw of txt.split(/\r?\n/)) {
380
+ const line = raw.trim()
381
+ if (line === '' || line.startsWith('#')) continue
382
+ const m = /^(name|description|order)\s*:\s*(.*)$/.exec(line)
383
+ if (!m) continue
384
+ let v = m[2].trim()
385
+ if ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'"))) {
386
+ v = v.slice(1, -1)
387
+ }
388
+ if (m[1] === 'order') meta.order = Number(v) || 0
389
+ else meta[m[1]] = v
390
+ }
391
+ } catch (_) { }
392
+ return meta
393
+ }
394
+
395
+ /** 扫目录而不是只信注册表:插件刚装上、宿主还没重启时也能看到新模式 */
396
+ function scanPresetDirs() {
397
+ const out = []
398
+ let names = []
399
+ try { names = fs.readdirSync(presetRoot) } catch (_) { return out }
400
+ for (const n of names) {
401
+ const dir = path.join(presetRoot, n)
402
+ try {
403
+ if (!fs.statSync(dir).isDirectory()) continue
404
+ if (!fs.existsSync(path.join(dir, 'agent.cordis.yml'))) continue
405
+ const meta = readPresetMeta(dir)
406
+ meta.mtime = fs.statSync(path.join(dir, 'agent.cordis.yml')).mtimeMs || 0
407
+ out.push(meta)
408
+ } catch (_) { }
409
+ }
410
+ return out
411
+ }
412
+
413
+ /** 注册表是权威(它会处理重名),目录扫描是兜底(宿主没重启/未激活) */
414
+ async function listModes() {
415
+ const svc = (() => {
416
+ try { return ctx && typeof ctx.get === 'function' ? ctx.get('agentPresets') : null } catch (_) { return null }
417
+ })()
418
+ let roster = []
419
+ if (svc && typeof svc.remoteExportList === 'function') {
420
+ try {
421
+ const r = await svc.remoteExportList()
422
+ roster = Array.isArray(r && r.presets) ? r.presets : []
423
+ } catch (_) { roster = [] }
424
+ }
425
+ const dirs = scanPresetDirs()
426
+ const byId = new Map()
427
+ // 官方两个永远在:注册表没起来时也能看到「标准 / 创造」
428
+ for (const id of ['standard', 'creator']) {
429
+ byId.set(id, {
430
+ id,
431
+ name: OFFICIAL_MODES[id].name,
432
+ description: OFFICIAL_MODES[id].description,
433
+ official: true,
434
+ source: 'official',
435
+ broken: false,
436
+ pending: roster.length === 0,
437
+ isDefault: false
438
+ })
439
+ }
440
+ for (const row of roster) {
441
+ if (!row || !row.id) continue
442
+ const id = String(row.id)
443
+ const off = OFFICIAL_MODES[id]
444
+ const prev = byId.get(id)
445
+ byId.set(id, {
446
+ id,
447
+ name: String(row.name || (off && off.name) || (prev && prev.name) || KNOWN_NAMES[id] || id),
448
+ description: String(row.description || (off && off.description) || (prev && prev.description) || ''),
449
+ official: id === 'standard' || id === 'creator',
450
+ source: 'registry',
451
+ broken: row.broken !== undefined,
452
+ pending: false,
453
+ isDefault: row.isDefault === true
454
+ })
455
+ }
456
+ for (const d of dirs) {
457
+ const hit = byId.get(d.id)
458
+ if (hit) {
459
+ // 注册表给了 id 但没给名字(官方预设),用目录里的名字补
460
+ if (d.name) hit.name = d.name
461
+ if (d.description && !hit.description) hit.description = d.description
462
+ continue
463
+ }
464
+ // 只在目录里存在:说明插件已装但宿主没重启,或注册失败(冲突/报错)
465
+ byId.set(d.id, {
466
+ id: d.id,
467
+ name: d.name || KNOWN_NAMES[d.id] || d.id,
468
+ description: d.description || '',
469
+ official: false,
470
+ source: 'directory',
471
+ broken: false,
472
+ pending: true,
473
+ isDefault: false
474
+ })
475
+ }
476
+ const modes = Array.from(byId.values())
477
+ // 官方两个置顶:标准、创造;其余按 order/名字
478
+ const rank = (id) => (id === 'standard' ? 0 : id === 'creator' ? 1 : 10)
479
+ modes.sort((a, b) => rank(a.id) - rank(b.id) || a.name.localeCompare(b.name))
480
+ const stamp = modes.map((m) => m.id + ':' + m.name + ':' + (m.pending ? 'p' : '')).join('|')
481
+ + '#' + dirs.map((d) => d.id + d.mtime).join(',')
482
+ if (stamp !== modesSnap.stamp) {
483
+ modesRev = (Number(modesRev) || 1) + 1
484
+ modesSnap = { rev: modesRev, modes, stamp }
485
+ } else {
486
+ modesSnap = { rev: modesRev, modes, stamp }
487
+ }
488
+ return { rev: modesRev, modes }
489
+ }
490
+
491
+ // 目录一变就涨版本号,手机端下一次轮询就能看到(新增 / 卸载 / 改名都算)
492
+ try {
493
+ if (fs.existsSync(presetRoot)) {
494
+ modesWatcher = fs.watch(presetRoot, { persistent: false }, () => bumpModes())
495
+ if (modesWatcher && typeof modesWatcher.on === 'function') {
496
+ modesWatcher.on('error', () => { })
497
+ }
498
+ }
499
+ } catch (_) { modesWatcher = null }
500
+
501
+ const sessionsRoot = () => path.join(os.homedir(), '.dsh', 'sessions')
502
+
503
+ /** 会话目录是 sessions/<工作目录编码>/<session-id>/,按 id 全局找一次 */
504
+ function findSessionDir(sessionId) {
505
+ const root = sessionsRoot()
506
+ let buckets = []
507
+ try { buckets = fs.readdirSync(root) } catch (_) { return '' }
508
+ for (const b of buckets) {
509
+ const p = path.join(root, b, sessionId)
510
+ try {
511
+ if (fs.statSync(p).isDirectory()) return p
512
+ } catch (_) { }
513
+ }
514
+ return ''
515
+ }
516
+
517
+ const wsctl = () => {
518
+ try { return ctx && typeof ctx.get === 'function' ? ctx.get('workspaceController') : null } catch (_) { return null }
519
+ }
520
+
521
+ // ── 归档集合的真源在 DSH 自己的 workspace 存储里 ─────────────────────
522
+ // sessionController.list() 不过滤归档会话,返回的 summary 也没有 archived 字段,
523
+ // 所以只看 list 会有两个后果:归档过的仍留在手机列表、归档库永远为空。
524
+ // 这里直接读 ~/.dsh/storages/workspace.json 的 global.archivedSessionIds。
525
+ const archivedPath = cfg.archivedFile
526
+ ? String(cfg.archivedFile)
527
+ : path.join(os.homedir(), '.dsh', 'storages', 'workspace.json')
528
+ let archivedCache = { at: 0, ids: new Set() }
529
+
530
+ /** 归档集合(1s 内复用,避免列表每次刷新都读盘) */
531
+ function archivedIds() {
532
+ const now = Date.now()
533
+ if (now - archivedCache.at < 1000) return archivedCache.ids
534
+ const ids = new Set()
535
+ try {
536
+ const raw = JSON.parse(fs.readFileSync(archivedPath, 'utf8'))
537
+ const arr = (raw && raw.global && raw.global.archivedSessionIds) || []
538
+ for (const x of arr) ids.add(String(x))
539
+ } catch (_) { }
540
+ archivedCache = { at: now, ids }
541
+ return ids
542
+ }
543
+
544
+ /** 归档命令返回的是完整归档集合,直接拿它刷新缓存 */
545
+ function setArchivedFrom(list) {
546
+ if (!Array.isArray(list)) return
547
+ const ids = new Set()
548
+ for (const x of list) ids.add(String(x))
549
+ archivedCache = { at: Date.now(), ids }
550
+ }
551
+
552
+ const idsOf = (r) => {
553
+ if (!r) return []
554
+ const v = Array.isArray(r) ? r : (Array.isArray(r.archivedSessionIds) ? r.archivedSessionIds : [])
555
+ return v.map((x) => String(x || '')).filter(Boolean)
556
+ }
557
+
558
+ // ── 手机侧的窄接口 ───────────────────────────────────────────────────
559
+ const bridge = {
560
+ async health() {
561
+ const c = ctl()
562
+ if (!c) return { ok: false, error: '拿不到 sessionController' }
563
+ return { ok: true, version: VERSION, methods: ['list', 'projections', 'prompt', 'cancel'].filter((k) => typeof c[k] === 'function') }
564
+ },
565
+
566
+ async listSessions() {
567
+ const c = ctl()
568
+ if (!c || typeof c.list !== 'function') throw new Error('这个 DSH 版本没有 sessionController.list')
569
+ const r = await c.list({}, timeout(15000))
570
+ const items = Array.isArray(r) ? r : (r && Array.isArray(r.items) ? r.items : [])
571
+ const arch = archivedIds()
572
+ const out = []
573
+ for (const s of items) {
574
+ if (!s) continue
575
+ // DSH 的 id 可能在 id,也可能在 sessionId;标题可能在 title 或 projections.values.title
576
+ const id = String(s.id || s.sessionId || '')
577
+ if (!id) continue
578
+ const origin = String(s.origin || '')
579
+ if (origin === 'subagent') continue
580
+ if (s.__blank === true) continue
581
+ // 已经在手机上删掉的,不要因为 DSH 进程里还留着对象又冒出来
582
+ if (hidden[id]) continue
583
+ const pv = (s.projections && s.projections.values) || {}
584
+ const title = String(s.title || pv.title || s.name || '').trim()
585
+ // 还没有任何一轮对话的会话不进列表(手机端「新建」会先建壳,用户没说话就不该占位)
586
+ const outline = pv.turnOutline
587
+ const empty = s.__blank === true || (Array.isArray(outline) && outline.length === 0)
588
+ out.push({
589
+ id,
590
+ title: title.length > 0 ? title.slice(0, 120) : '未命名会话',
591
+ cwd: String(s.cwd || ''),
592
+ updatedAt: Number(s.updatedAt) || Number(s.lastTurnEndAt) || 0,
593
+ createdAt: Number(s.createdAt) || 0,
594
+ running: s.running === true,
595
+ archived: arch.has(id) || s.archived === true,
596
+ pinned: s.pinned === true,
597
+ empty
598
+ })
599
+ }
600
+ out.sort((a, b) => (b.updatedAt || b.createdAt) - (a.updatedAt || a.createdAt))
601
+ return out
602
+ },
603
+
604
+ /** 模式清单:注册表为准,目录兜底;rev 变化说明桌面端装了/删了模式插件 */
605
+ async modes() {
606
+ const r = await listModes()
607
+ return { rev: r.rev, modes: r.modes }
608
+ },
609
+
610
+ /** 只读版本号,给 /v1/info 每 2 秒轮询用,不做完整扫描 */
611
+ modesRev() {
612
+ return modesRev
613
+ },
614
+
615
+ async turns(sessionId) {
616
+ const c = ctl()
617
+ if (!c || typeof c.projections !== 'function') throw new Error('这个 DSH 版本没有 sessionController.projections')
618
+ const raw = await c.projections({ sessionId }, timeout(20000))
619
+ const values = (raw && raw.values) || {}
620
+
621
+ // 完整正文:turnOutline 是给对话导航栏用的「预览」,上限只有 120 字,
622
+ // 长回答会被截成「…」。真正逐字的内容要从历史事件流折出来。
623
+ let full = []
624
+ try {
625
+ const asOf = Number(raw && raw.asOfSeq) || 0
626
+ const hit = histCache.get(sessionId)
627
+ // 刚读过就复用,避免轮询把同一段历史反复拉一遍
628
+ if (hit && Date.now() - hit.at < 1500) {
629
+ full = hit.turns
630
+ } else {
631
+ // 已经翻到 seq 0 的会话,只需要补尾部;否则从头翻几页
632
+ const hadAll = !!(hit && hit.fromSeq === 0 && Array.isArray(hit.events))
633
+ let got = await readSessionHistory(c, sessionId, hadAll ? 1 : 4)
634
+ let evs = got.events
635
+ let fromSeq = got.fromSeq
636
+ if (hadAll && got.hasMore) {
637
+ // 尾部一页没盖住(隔了很久又长出一大段),退回完整翻页
638
+ got = await readSessionHistory(c, sessionId, 4)
639
+ evs = got.events
640
+ fromSeq = got.fromSeq
641
+ } else if (hadAll) {
642
+ const map = new Map()
643
+ for (const one of hit.events) {
644
+ const ev = one && typeof one === 'object' && one.event ? one.event : one
645
+ map.set(Number(ev && ev.seq) || 0, one)
646
+ }
647
+ for (const one of evs) {
648
+ const ev = one && typeof one === 'object' && one.event ? one.event : one
649
+ map.set(Number(ev && ev.seq) || 0, one)
650
+ }
651
+ evs = [...map.values()].sort((a, b) => {
652
+ const ea = a && typeof a === 'object' && a.event ? a.event : a
653
+ const eb = b && typeof b === 'object' && b.event ? b.event : b
654
+ return (Number(ea && ea.seq) || 0) - (Number(eb && eb.seq) || 0)
655
+ })
656
+ fromSeq = 0
657
+ }
658
+ full = foldHistory({ events: evs })
659
+ histCache.set(sessionId, { asOf, at: Date.now(), turns: full, events: evs, fromSeq })
660
+ if (histCache.size > 24) {
661
+ const oldest = histCache.keys().next()
662
+ if (!oldest.done) histCache.delete(oldest.value)
663
+ }
664
+ // 采样:只写一份紧凑摘要,用来核对「到底读到了什么」
665
+ try {
666
+ const types = {}
667
+ const blocks = {}
668
+ for (const one of evs) {
669
+ const ev = one && typeof one === 'object' && one.event ? one.event : one
670
+ const t = String((ev && ev.type) || '?')
671
+ types[t] = (types[t] || 0) + 1
672
+ if (t === 'assistant/message') {
673
+ const d = (ev && ev.data) || {}
674
+ const m = d.message || d
675
+ blockTypes(m && m.content, blocks)
676
+ }
677
+ }
678
+ fs.writeFileSync(path.join(dataDir, 'debug-history.json'), JSON.stringify({
679
+ at: new Date().toISOString(),
680
+ sessionId,
681
+ method: got.method,
682
+ pages: got.pages,
683
+ hasMore: got.hasMore,
684
+ fromSeq,
685
+ events: evs.length,
686
+ turns: full.length,
687
+ types,
688
+ blocks,
689
+ lengths: full.slice(-5).map((t) => ({
690
+ turn: t.turn,
691
+ prompt: t.prompt.length,
692
+ response: t.response.length,
693
+ thinking: (t.thinking || '').length
694
+ }))
695
+ }, null, 1))
696
+ } catch (_) { }
697
+ }
698
+ } catch (e) {
699
+ log('[turns] 读历史事件失败,退回摘要:' + String((e && e.message) || e))
700
+ }
701
+
702
+ const tb = values.turnBoundary
703
+ const running = !!(tb && typeof tb === 'object' && Number(tb.openTurnStartSeq) > 0)
704
+ const stats = values.sessionStats || {}
705
+ const mergedTurns = mergeTurns(turnList(values), full)
706
+ // 思考过程总量控制:从最新一轮往前分预算,太早的长思考就不下发(正文照旧)
707
+ let thinkBudget = THINKING_BUDGET
708
+ for (let i = mergedTurns.length - 1; i >= 0; i--) {
709
+ const th = mergedTurns[i].thinking || ''
710
+ if (!th) continue
711
+ if (th.length > thinkBudget) mergedTurns[i].thinking = ''
712
+ else thinkBudget -= th.length
713
+ }
714
+ return {
715
+ sessionId,
716
+ title: clean(values.title || '', 120),
717
+ running,
718
+ // 当前会话跑的是哪个 agent preset(模式);空会话才有意义
719
+ preset: String(values.agentPreset || ''),
720
+ asOfSeq: Number(raw && raw.asOfSeq) || 0,
721
+ turns: mergedTurns,
722
+ stats: { turns: Number(stats.turns) || 0, steps: Number(stats.steps) || 0 },
723
+ tokens: (() => {
724
+ const tk = values.tokenUsage || {}
725
+ const cached = Number(tk.cacheReadTokens) || 0
726
+ const uncached = Number(tk.uncachedInputTokens) || 0
727
+ return {
728
+ input: uncached,
729
+ output: Number(tk.outputTokens) || 0,
730
+ cacheRead: cached,
731
+ hitRate: (cached + uncached) > 0 ? Math.round(cached * 100 / (cached + uncached)) : 0
732
+ }
733
+ })(),
734
+ context: (() => {
735
+ const cp = values.contextPressure || {}
736
+ const used = Number(cp.pressureTokens) || 0
737
+ const win = Number(cp.contextWindow) || 0
738
+ return { used, window: win, percent: win ? Math.round(used * 1000 / win) / 10 : 0 }
739
+ })(),
740
+ // 上下文构成:系统提示词 / 工具定义 / 对话消息(DSH 的 contextBreakdown 投影)
741
+ ctxParts: (() => {
742
+ const cb = values.contextBreakdown || {}
743
+ return {
744
+ system: Number(cb.systemTokens) || 0,
745
+ tools: Number(cb.toolsTokens) || 0,
746
+ messages: Number(cb.messageTokens) || 0
747
+ }
748
+ })()
749
+ }
750
+ },
751
+
752
+ async command(op, p) {
753
+ const c = ctl()
754
+ if (!c) throw new Error('拿不到 sessionController')
755
+ const payload = p || {}
756
+
757
+ if (op === 'send') {
758
+ const sessionId = String(payload.sessionId || '')
759
+ const text = String(payload.text || '').trim()
760
+ if (!sessionId) throw new Error('缺少 sessionId')
761
+ if (typeof c.prompt !== 'function') throw new Error('这个 DSH 版本没有 sessionController.prompt')
762
+
763
+ // 只发图、不发字是允许的:内容数组里只要有东西就行
764
+ const content = []
765
+ if (text !== '') content.push({ type: 'text', text: clean(text, 32000) })
766
+
767
+ const imgs = Array.isArray(payload.images) ? payload.images : []
768
+ let imgCount = 0
769
+ for (const one of imgs.slice(0, 9)) {
770
+ const mime = String((one && one.mime) || '')
771
+ const data = String((one && one.data) || '')
772
+ if (!mime.startsWith('image/') || data === '') continue
773
+ if (data.length > 12 * 1024 * 1024) throw new Error('单张图片太大(base64 超过 12MB)')
774
+ const name = String((one && one.name) || '')
775
+ content.push(name !== ''
776
+ ? { type: 'image', mediaType: mime, data, name }
777
+ : { type: 'image', mediaType: mime, data })
778
+ imgCount += 1
779
+ }
780
+ if (content.length === 0) throw new Error('消息和图片都是空的')
781
+
782
+ await c.prompt({
783
+ requestId: randomUUID(),
784
+ sessionId,
785
+ mode: payload.mode === 'steer' ? 'steer' : 'queue',
786
+ content
787
+ }, timeout(30000))
788
+ return { sent: true, images: imgCount }
789
+ }
790
+
791
+ if (op === 'cancel') {
792
+ const sessionId = String(payload.sessionId || '')
793
+ if (!sessionId) throw new Error('缺少 sessionId')
794
+ if (typeof c.cancel !== 'function') throw new Error('这个 DSH 版本没有 sessionController.cancel')
795
+ await c.cancel({ sessionId }, timeout(15000))
796
+ return { cancelled: true }
797
+ }
798
+
799
+ if (op === 'create') {
800
+ if (typeof c.create !== 'function') throw new Error('这个 DSH 版本没有 sessionController.create')
801
+ // 不接受客户端指定 cwd:手机端只能建在 DSH 默认位置,避免被拿来在任意目录开工
802
+ // 允许带模式:相当于桌面端新建时先选好 agent preset
803
+ const presetId = String(payload.presetId || '')
804
+ const request = presetId !== '' ? { agentPreset: presetId } : {}
805
+ const r = await c.create(request, timeout(20000))
806
+ const id = String((r && (r.sessionId || r.id)) || (r && r.session && r.session.id) || '')
807
+ return { sessionId: id, agentPreset: String((r && r.agentPreset) || presetId) }
808
+ }
809
+
810
+ // 切模式=给「还没有任何一轮」的会话重新选 agent preset。
811
+ // DSH 的约束是 preset 只能在空白会话上切(否则 agent-preset/locked),
812
+ // 这里提前判断,失败时给一句人话,而不是把系统错误抛给用户。
813
+ if (op === 'selectMode') {
814
+ const sessionId = String(payload.sessionId || '')
815
+ const presetId = String(payload.presetId || '')
816
+ if (!sessionId) throw new Error('缺少 sessionId')
817
+ if (!presetId) throw new Error('缺少预设')
818
+ if (typeof c.create !== 'function') throw new Error('这个 DSH 版本没有 sessionController.create')
819
+ if (typeof c.projections !== 'function') throw new Error('这个 DSH 版本没有 sessionController.projections')
820
+
821
+ const known = await listModes()
822
+ if (!known.modes.some((m) => m.id === presetId)) throw new Error('电脑上没有这个模式:' + presetId)
823
+
824
+ let outline = []
825
+ try {
826
+ const raw = await c.projections({ sessionId }, timeout(15000))
827
+ const pv = (raw && raw.values) || {}
828
+ outline = Array.isArray(pv.turnOutline) ? pv.turnOutline : []
829
+ } catch (e) {
830
+ throw new Error('读不到这个会话:' + String((e && e.message) || e))
831
+ }
832
+ if (outline.length > 0) throw new Error('这个会话已经聊过了,模式只对还没开始的新会话生效')
833
+
834
+ const r = await c.create({ sessionId, agentPreset: presetId }, timeout(20000))
835
+ const gotId = String((r && (r.sessionId || r.id)) || '')
836
+ if (gotId !== '' && gotId !== sessionId) {
837
+ // 没复用说明会话已经不是空白:把刚多出来的空壳藏掉,别让它污染列表
838
+ hidden[gotId] = { at: Date.now(), dir: '' }
839
+ saveHidden()
840
+ throw new Error('会话已经开始对话,模式没切成功;新建一个会话再选模式')
841
+ }
842
+ return { sessionId, agentPreset: String((r && r.agentPreset) || presetId) }
843
+ }
844
+
845
+ if (op === 'rename') {
846
+ const sessionId = String(payload.sessionId || '')
847
+ const title = clean(payload.title, 120)
848
+ if (!sessionId) throw new Error('缺少 sessionId')
849
+ if (!title) throw new Error('标题是空的')
850
+ if (typeof c.rename !== 'function') throw new Error('这个 DSH 版本没有 sessionController.rename')
851
+ await c.rename({ sessionId, title }, timeout(15000))
852
+ return { renamed: true }
853
+ }
854
+
855
+ // 归档是 DSH 自己的概念(workspace.archiveSession),
856
+ // 用原生实现才能让电脑端和手机端看到一致的归档状态。
857
+ if (op === 'archive' || op === 'unarchive') {
858
+ const sessionId = String(payload.sessionId || '')
859
+ if (!sessionId) throw new Error('缺少 sessionId')
860
+ const w = wsctl()
861
+ if (!w) throw new Error('这个 DSH 版本拿不到 workspaceController')
862
+ if (op === 'archive') {
863
+ if (typeof w.archiveSession !== 'function') throw new Error('这个 DSH 版本没有 archiveSession')
864
+ const r = await w.archiveSession({ sessionId, stopActivity: payload.stopActivity === true || payload.stopActivity === 'true' }, timeout(20000))
865
+ setArchivedFrom(idsOf(r))
866
+ return { archived: true, ids: idsOf(r) }
867
+ }
868
+ if (typeof w.unarchiveSession !== 'function') throw new Error('这个 DSH 版本没有 unarchiveSession')
869
+ const r = await w.unarchiveSession({ sessionId }, timeout(20000))
870
+ setArchivedFrom(idsOf(r))
871
+ return { archived: false, ids: idsOf(r) }
872
+ }
873
+
874
+ // 删除:挪进本插件的回收站并记入 hidden,列表立刻消失;
875
+ // 想彻底抹掉再调 purge(归档库里的「彻底删除」)。
876
+ if (op === 'delete' || op === 'purge') {
877
+ const listed = Array.isArray(payload.sessionIds)
878
+ ? payload.sessionIds
879
+ : (payload.sessionId ? [payload.sessionId] : [])
880
+ const ids = [...new Set(listed.map((x) => String(x || '')).filter(Boolean))]
881
+ if (ids.length === 0) throw new Error('没有要删的会话')
882
+
883
+ if (op === 'purge') {
884
+ let n = 0
885
+ for (const id of ids) {
886
+ try {
887
+ fs.rmSync(path.join(trashDir, id), { recursive: true, force: true })
888
+ n += 1
889
+ } catch (_) { }
890
+ }
891
+ return { purged: n }
892
+ }
893
+
894
+ const all = typeof c.list === 'function' ? await bridge.listSessions() : []
895
+ const byId = new Map(all.map((s) => [s.id, s]))
896
+ const w = wsctl()
897
+ const deleted = []
898
+ const failed = []
899
+ for (const id of ids) {
900
+ const s = byId.get(id)
901
+ if (s && s.running === true) {
902
+ failed.push({ id, error: '会话正在运行,先停止再删' })
903
+ continue
904
+ }
905
+ // 归档集合里不能留一个已经不存在的会话
906
+ if (s && s.archived === true && w && typeof w.unarchiveSession === 'function') {
907
+ try { await w.unarchiveSession({ sessionId: id }, timeout(15000)) } catch (_) { }
908
+ }
909
+ const dir = findSessionDir(id)
910
+ if (dir) {
911
+ try {
912
+ fs.mkdirSync(trashDir, { recursive: true })
913
+ const target = path.join(trashDir, id)
914
+ try { fs.rmSync(target, { recursive: true, force: true }) } catch (_) { }
915
+ fs.renameSync(dir, target)
916
+ } catch (e) {
917
+ failed.push({ id, error: '挪走会话目录失败:' + String((e && e.message) || e) })
918
+ continue
919
+ }
920
+ }
921
+ hidden[id] = { at: Date.now(), dir }
922
+ deleted.push(id)
923
+ }
924
+ saveHidden()
925
+ return { deleted, failed }
926
+ }
927
+
928
+ if (op === 'models') {
929
+ const sessionId = String(payload.sessionId || '')
930
+ if (!sessionId) throw new Error('缺少 sessionId')
931
+
932
+ const errs = []
933
+ const attempts = []
934
+ if (typeof c.modelCatalog === 'function') {
935
+ // 参考实现按这个顺序调用:带 request 和 signal 的那次才是 RPC 正解。
936
+ // 之前只试无参调用,代理返回空对象也不报错,界面就成了「选择模型」。
937
+ attempts.push(['modelCatalog(request,signal)', () => c.modelCatalog({ sessionId }, timeout(15000))])
938
+ attempts.push(['modelCatalog(request)', () => c.modelCatalog({ sessionId })])
939
+ attempts.push(['modelCatalog()', () => c.modelCatalog()])
940
+ }
941
+
942
+ const looksLikeCatalog = (x) => !!x && typeof x === 'object'
943
+ && (Array.isArray(x.groups) || (x.default && typeof x.default === 'object'))
944
+
945
+ // RPC 可能把结果包在 value / result / data / catalog 里,逐层剥开
946
+ const unwrap = (raw) => {
947
+ let v = raw
948
+ if (typeof v === 'string') { try { v = JSON.parse(v) } catch (_) { v = null } }
949
+ for (let i = 0; i < 4; i++) {
950
+ if (looksLikeCatalog(v)) return v
951
+ if (v && typeof v === 'object') {
952
+ const inner = v.value || v.result || v.data || v.catalog
953
+ if (inner && typeof inner === 'object') { v = inner; continue }
954
+ }
955
+ break
956
+ }
957
+ return v
958
+ }
959
+
960
+ let v = null
961
+ let via = ''
962
+ for (const [label, fn] of attempts) {
963
+ try {
964
+ const got = unwrap(await fn())
965
+ if (looksLikeCatalog(got)) { v = got; via = label; break }
966
+ errs.push(label + ' → 返回形状不对:' + (got === null ? 'null' : typeof got))
967
+ } catch (e) {
968
+ errs.push(label + ' → ' + String((e && e.message) || e))
969
+ }
970
+ }
971
+
972
+ // 兜底:直接问 LLM 注册表(桌面端模型列表就是从这里来的)
973
+ if (v === null && ctx && typeof ctx.get === 'function') {
974
+ try {
975
+ const llm = ctx.get('llm')
976
+ if (llm && typeof llm.listProviders === 'function') {
977
+ const provs = await llm.listProviders()
978
+ const groups = []
979
+ const failures = []
980
+ for (const p of (Array.isArray(provs) ? provs : [])) {
981
+ const pid = String((p && p.id) || '')
982
+ if (pid === '') continue
983
+ try {
984
+ const models = await llm.listModels(pid)
985
+ const entries = []
986
+ for (const m of (Array.isArray(models) ? models : [])) {
987
+ const mid = String((m && m.id) || '')
988
+ if (mid === '') continue
989
+ let reasoning = m && m.reasoning
990
+ if (!reasoning && typeof llm.resolveModelInfo === 'function') {
991
+ try {
992
+ const info = await llm.resolveModelInfo(pid, mid)
993
+ reasoning = info && info.reasoning
994
+ } catch (_) { }
995
+ }
996
+ entries.push({
997
+ id: mid,
998
+ name: String((m && m.name) || mid),
999
+ description: String((m && m.description) || ''),
1000
+ reasoning: reasoning || undefined
1001
+ })
1002
+ }
1003
+ groups.push({ id: pid, name: String((p && p.name) || pid), models: entries })
1004
+ } catch (e) {
1005
+ failures.push({ id: pid, name: String((p && p.name) || pid), message: String((e && e.message) || e) })
1006
+ }
1007
+ }
1008
+ if (groups.some((g) => g.models.length > 0)) {
1009
+ v = { groups, failures, default: {} }
1010
+ via = 'llm registry'
1011
+ } else {
1012
+ errs.push('llm registry → 没有可用模型')
1013
+ }
1014
+ }
1015
+ } catch (e) {
1016
+ errs.push('llm registry → ' + String((e && e.message) || e))
1017
+ }
1018
+ }
1019
+
1020
+ // 一律留一份体检记录,出问题不用再猜
1021
+ try {
1022
+ const brief = {
1023
+ at: new Date().toISOString(),
1024
+ sessionId,
1025
+ via: via || 'none',
1026
+ groupCount: v === null ? 0 : (v.groups || []).length,
1027
+ groups: v === null ? [] : (v.groups || []).map((g) => ({
1028
+ id: String(g.id || ''),
1029
+ name: String(g.name || ''),
1030
+ models: (g.models || []).slice(0, 40).map((m) => String(m.id || ''))
1031
+ })),
1032
+ failures: v === null ? [] : (v.failures || []).map((f) => String(f.id || '') + ': ' + String(f.message || '')),
1033
+ attempts: errs
1034
+ }
1035
+ fs.writeFileSync(path.join(dataDir, 'debug-models.log'), JSON.stringify(brief, null, 1))
1036
+ } catch (_) { }
1037
+
1038
+ if (v === null) throw new Error('模型目录读不了:' + (errs.join(' | ') || '没有可用的读取方式'))
1039
+
1040
+ // DSH 的目录里当前选择在 default(全局默认);会话自己的选择在投影 modelSelection.next。
1041
+ // 只有拿不到投影时才退回 default,否则会显示成「选择模型」。
1042
+ let cur = v.current || v.default || {}
1043
+ try {
1044
+ if (typeof c.projections === 'function') {
1045
+ const proj = await c.projections({ sessionId }, timeout(15000))
1046
+ const vals = (proj && proj.values) || {}
1047
+ const ms = vals.modelSelection || vals.model || null
1048
+ const next = ms && (ms.next || ms.current || ms)
1049
+ if (next && next.provider && next.model) cur = next
1050
+ }
1051
+ } catch (e) { log('[models] 读会话模型选择失败:' + String((e && e.message) || e)) }
1052
+
1053
+ return {
1054
+ current: {
1055
+ provider: String(cur.provider || ''),
1056
+ model: String(cur.model || cur.id || ''),
1057
+ reasoningEffort: cur.reasoningEffort ? String(cur.reasoningEffort) : ''
1058
+ },
1059
+ groups: (v.groups || []).map((g) => ({
1060
+ id: String(g.id || ''),
1061
+ name: String(g.name || g.id || ''),
1062
+ models: (g.models || []).map((m) => ({
1063
+ id: String(m.id || ''),
1064
+ name: String(m.name || m.id || ''),
1065
+ provider: String(m.provider || g.id || ''),
1066
+ description: String(m.description || ''),
1067
+ efforts: ((m.reasoning && m.reasoning.efforts) || []).map((e) => ({
1068
+ id: String(e.id || ''), name: String(e.name || e.id || '')
1069
+ })),
1070
+ defaultEffort: (m.reasoning && m.reasoning.defaultEffort) ? String(m.reasoning.defaultEffort) : ''
1071
+ }))
1072
+ })),
1073
+ failures: (v.failures || []).map((f) => ({ id: String(f.id || ''), name: String(f.name || ''), message: String(f.message || '') }))
1074
+ }
1075
+ }
1076
+
1077
+ if (op === 'selectModel') {
1078
+ const sessionId = String(payload.sessionId || '')
1079
+ if (!sessionId) throw new Error('缺少 sessionId')
1080
+ if (typeof c.selectModel !== 'function') throw new Error('这个 DSH 版本没有 selectModel')
1081
+ const args = {
1082
+ sessionId,
1083
+ provider: String(payload.provider || ''),
1084
+ model: String(payload.model || '')
1085
+ }
1086
+ if (!args.provider || !args.model) throw new Error('缺少 provider 或 model')
1087
+ const effort = String(payload.reasoningEffort || '')
1088
+ if (effort) args.reasoningEffort = effort
1089
+ const r = await c.selectModel(args)
1090
+ return { selected: { provider: args.provider, model: args.model, reasoningEffort: effort } }
1091
+ }
1092
+
1093
+ throw new Error('不支持的指令:' + op)
1094
+ }
1095
+ }
1096
+
1097
+ let panelServer = null
1098
+ const tunnel = new CloudflaredTunnel({
1099
+ dir: path.join(dataDir, 'bin'),
1100
+ port: () => (panelServer ? panelServer.port : port),
1101
+ binPath: cfg.cloudflaredPath || '',
1102
+ downloadBase: cfg.downloadBase || '',
1103
+ log
1104
+ })
1105
+
1106
+ panelServer = createConsoleServer({ bridge, dataDir, port, name: nodeName, log, tunnel })
1107
+
1108
+ let disposed = false
1109
+
1110
+ async function boot() {
1111
+ try {
1112
+ const real = await panelServer.start()
1113
+ log('局域网服务已起:0.0.0.0:' + real + ' · 节点「' + nodeName + '」')
1114
+ log('配对码在 DSH 设置 → DSH 控制台 里看,或翻上面那行 [pair]。')
1115
+ } catch (e) {
1116
+ log('服务起不来:' + ((e && e.message) || e))
1117
+ }
1118
+ if (cfg.tunnel === true || panelServer.getTunnelAuto()) {
1119
+ tunnel.start().then((s) => {
1120
+ log('隧道状态:' + s.state + (s.url ? ' ' + s.url : ''))
1121
+ if (s.state === 'up') log('二维码现在带的是公网地址')
1122
+ }).catch(() => { })
1123
+ }
1124
+ }
1125
+
1126
+ // ── 面板路由(DSH 客户端半边读这个) ──────────────────────────────────
1127
+ const routes = []
1128
+ function jsonOf(status, payload) {
1129
+ return new Response(JSON.stringify(payload), {
1130
+ status,
1131
+ headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }
1132
+ })
1133
+ }
1134
+
1135
+ // 面板这几条路由只允许回环访问:DSH 的 web 端口一旦被暴露到局域网,
1136
+ // 别人直接打开 /api/dsh-console-oh/state 就能看到配对码,等于绕过一切配对。
1137
+ // 面板这几条路由的守卫。判定顺序:
1138
+ // 1) 非 http(s) 的 URL(Electron 自定义协议)——只可能来自宿主自己,放行
1139
+ // 2) 回环主机名——放行
1140
+ // 3) 同源请求(浏览器里页面自己发起的 fetch)——放行
1141
+ // 4) 其余(别人直接在浏览器里打开这个地址)——403
1142
+ // 被拒时把 host 写进日志文件,方便排查到底是谁在调。
1143
+ function panelGuard(request) {
1144
+ let u = null
1145
+ try { u = new URL(String(request.url)) } catch (_) { u = null }
1146
+ const host = u ? String(u.hostname || '').toLowerCase() : ''
1147
+ const proto = u ? String(u.protocol || '') : ''
1148
+
1149
+ if (proto !== '' && proto !== 'http:' && proto !== 'https:') return null
1150
+
1151
+ const name = host.replace(/^\[/, '').replace(/\]?$/, '')
1152
+ // dsh.internal 是宿主自己的内部域名(Electron 内部映射),面板的请求就长这样
1153
+ if (name === '' || name === '127.0.0.1' || name === 'localhost' || name === '::1' || name === 'dsh.internal') return null
1154
+
1155
+ // 同源判定:Origin / Referer 任一匹配,或浏览器自己标了 same-origin
1156
+ let originHost = ''
1157
+ for (const key of ['origin', 'referer']) {
1158
+ try {
1159
+ const raw = request.headers.get(key) || ''
1160
+ if (raw === '' || raw === 'null') continue
1161
+ const oh = new URL(raw).host
1162
+ if (oh !== '') { originHost = oh; break }
1163
+ } catch (_) { }
1164
+ }
1165
+ let site = ''
1166
+ try { site = String(request.headers.get('sec-fetch-site') || '') } catch (_) { site = '' }
1167
+ if (site === 'same-origin' || site === 'same-site') return null
1168
+ if (originHost !== '' && u && originHost === u.host) return null
1169
+
1170
+ try {
1171
+ fs.appendFileSync(path.join(os.homedir(), '.dsh', 'dsh-console-oh', 'panel-denied.log'),
1172
+ new Date().toISOString() + ' host=' + host + ' proto=' + proto + ' origin=' + originHost + ' site=' + site + ' url=' + String(request.url) + '\n')
1173
+ } catch (_) { }
1174
+ log('[panel] 拒绝访问:host=' + host + ' proto=' + proto + ' origin=' + originHost)
1175
+ return new Response(JSON.stringify({ ok: false, error: '只允许在本机访问控制台面板' }), {
1176
+ status: 403,
1177
+ headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }
1178
+ })
1179
+ }
1180
+
1181
+ function scrub(m) {
1182
+ return String(m == null ? '' : m)
1183
+ .replace(/[A-Za-z]:\\[^\s"']+/g, '<path>')
1184
+ .replace(/\/(?:[\w.-]+\/){2,}[\w.-]+/g, '<path>')
1185
+ .slice(0, 160)
1186
+ }
1187
+
1188
+ function registerRoutes() {
1189
+ let conn = null
1190
+ try { conn = ctx && typeof ctx.get === 'function' ? ctx.get('connection') : null } catch (_) { conn = null }
1191
+ if (!conn || !conn.fetch || typeof conn.fetch.register !== 'function') {
1192
+ log('拿不到 connection.fetch,面板没有数据(App 侧不受影响)')
1193
+ return false
1194
+ }
1195
+ const add = (route) => {
1196
+ try {
1197
+ const inner = route.fetch
1198
+ route.fetch = async (request) => {
1199
+ const denied = panelGuard(request)
1200
+ if (denied) return denied
1201
+ return inner(request)
1202
+ }
1203
+ const off = conn.fetch.register(route)
1204
+ if (typeof off === 'function') routes.push(off)
1205
+ } catch (e) {
1206
+ log('路由注册失败 ' + route.path + ':' + ((e && e.message) || e))
1207
+ }
1208
+ }
1209
+
1210
+ add({
1211
+ path: STATE_PATH, methods: ['GET'], requestBody: 'buffered',
1212
+ fetch: async () => {
1213
+ try { return jsonOf(200, panelServer.panelState()) } catch (e) { return jsonOf(500, { ok: false, error: scrub(e && e.message || e) }) }
1214
+ }
1215
+ })
1216
+
1217
+ add({
1218
+ path: NEWCODE_PATH, methods: ['POST'], requestBody: 'buffered',
1219
+ fetch: async (request) => {
1220
+ try {
1221
+ let body = {}
1222
+ try { body = await request.json() } catch (_) { }
1223
+ panelServer.newCode(body && body.scope === 'lan' ? 'lan' : 'wan')
1224
+ return jsonOf(200, panelServer.panelState())
1225
+ } catch (e) { return jsonOf(500, { ok: false, error: scrub(e && e.message || e) }) }
1226
+ }
1227
+ })
1228
+
1229
+ add({
1230
+ path: TOGGLE_PATH, methods: ['POST'], requestBody: 'buffered',
1231
+ fetch: async (request) => {
1232
+ try {
1233
+ let body = {}
1234
+ try { body = await request.json() } catch (_) { }
1235
+ if (typeof body.remotePair === 'boolean') panelServer.setRemotePair(body.remotePair)
1236
+ if (typeof body.readOnly === 'boolean') panelServer.setReadOnly(body.readOnly)
1237
+ if (typeof body.lanAccess === 'boolean') await panelServer.setLanAccess(body.lanAccess)
1238
+ if (typeof body.deviceId === 'string' && body.deviceId !== '') {
1239
+ const n = panelServer.revokeDevice(body.deviceId)
1240
+ log('[devices] 踢掉 ' + n + ' 台设备')
1241
+ }
1242
+ return jsonOf(200, panelServer.panelState())
1243
+ } catch (e) { return jsonOf(500, { ok: false, error: scrub(e && e.message || e) }) }
1244
+ }
1245
+ })
1246
+
1247
+ add({
1248
+ path: TUNNEL_PATH, methods: ['POST'], requestBody: 'buffered',
1249
+ fetch: async (request) => {
1250
+ try {
1251
+ let body = {}
1252
+ try { body = await request.json() } catch (_) { }
1253
+ if (String(body.action || '') === 'stop') { tunnel.stop(); panelServer.setTunnelAuto(false) }
1254
+ // 起隧道可能要下载几十兆,别让面板请求挂在这儿等
1255
+ else {
1256
+ panelServer.setTunnelAuto(true)
1257
+ tunnel.start().then((s) => log('隧道:' + s.state + (s.url ? ' ' + s.url : ''))).catch(() => { })
1258
+ }
1259
+ return jsonOf(200, panelServer.panelState())
1260
+ } catch (e) { return jsonOf(500, { ok: false, error: scrub(e && e.message || e) }) }
1261
+ }
1262
+ })
1263
+
1264
+ add({
1265
+ path: QR_PATH, methods: ['GET'], requestBody: 'buffered',
1266
+ fetch: async () => {
1267
+ try {
1268
+ const link = panelServer.pairLink()
1269
+ if (!link) return new Response('还没有可用地址', { status: 409, headers: { 'content-type': 'text/plain; charset=utf-8' } })
1270
+ const svg = await qrSvg(link)
1271
+ return new Response(svg, {
1272
+ headers: { 'content-type': 'image/svg+xml; charset=utf-8', 'cache-control': 'no-store' }
1273
+ })
1274
+ } catch (e) {
1275
+ log('二维码生成失败:' + ((e && e.message) || e))
1276
+ return new Response('二维码生成失败', { status: 500, headers: { 'content-type': 'text/plain; charset=utf-8' } })
1277
+ }
1278
+ }
1279
+ })
1280
+
1281
+ add({
1282
+ path: SESSIONS_PATH, methods: ['GET'], requestBody: 'buffered',
1283
+ fetch: async () => {
1284
+ try {
1285
+ const list = await bridge.listSessions()
1286
+ return jsonOf(200, { ok: true, sessions: list })
1287
+ } catch (e) { return jsonOf(500, { ok: false, error: scrub(e && e.message || e) }) }
1288
+ }
1289
+ })
1290
+
1291
+ add({
1292
+ path: TURNS_PATH, methods: ['GET'], requestBody: 'buffered',
1293
+ fetch: async (request) => {
1294
+ try {
1295
+ const id = new URL(String(request.url)).searchParams.get('id') || ''
1296
+ if (id === '') return jsonOf(400, { ok: false, error: '缺少 id' })
1297
+ const detail = await bridge.turns(id)
1298
+ return jsonOf(200, Object.assign({ ok: true }, detail))
1299
+ } catch (e) { return jsonOf(500, { ok: false, error: scrub(e && e.message || e) }) }
1300
+ }
1301
+ })
1302
+
1303
+ add({
1304
+ path: SEND_PATH, methods: ['POST'], requestBody: 'buffered',
1305
+ fetch: async (request) => {
1306
+ try {
1307
+ let body = {}
1308
+ try { body = await request.json() } catch (_) { }
1309
+ const sessionId = String(body.sessionId || '')
1310
+ const text = String(body.text || '').trim()
1311
+ if (sessionId === '' || text === '') return jsonOf(400, { ok: false, error: '缺 sessionId 或内容' })
1312
+ await bridge.command('send', { sessionId, text })
1313
+ return jsonOf(200, { ok: true })
1314
+ } catch (e) { return jsonOf(500, { ok: false, error: scrub(e && e.message || e) }) }
1315
+ }
1316
+ })
1317
+
1318
+ log('面板路由已注册:' + STATE_PATH)
1319
+ return true
1320
+ }
1321
+
1322
+ const bootAll = () => {
1323
+ if (disposed) return
1324
+ boot()
1325
+ if (!registerRoutes()) {
1326
+ let n = 0
1327
+ const iv = setInterval(() => {
1328
+ n += 1
1329
+ if (disposed || n > 20 || registerRoutes()) clearInterval(iv)
1330
+ }, 500)
1331
+ }
1332
+ }
1333
+
1334
+ try {
1335
+ if (typeof ctx.effect === 'function') {
1336
+ ctx.effect(() => {
1337
+ bootAll()
1338
+ return () => {
1339
+ disposed = true
1340
+ for (const off of routes) { try { off() } catch (_) { } }
1341
+ try { if (modesWatcher) modesWatcher.close() } catch (_) { }
1342
+ modesWatcher = null
1343
+ tunnel.stop()
1344
+ panelServer.stop()
1345
+ }
1346
+ }, 'dsh-console-oh: server')
1347
+ } else {
1348
+ bootAll()
1349
+ }
1350
+ } catch (e) {
1351
+ log('初始化失败:' + ((e && e.stack) || e))
1352
+ }
1353
+
1354
+ // 兜底:进程退出时收拾子进程
1355
+ try {
1356
+ process.once('exit', () => { try { tunnel.stop() } catch (_) { } })
1357
+ } catch (_) { }
1358
+ }