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