dsh-deepseek-webchat 0.0.0-stage → 0.4.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js ADDED
@@ -0,0 +1,908 @@
1
+ /**
2
+ * dsh-deepseek-webchat — host half.
3
+ *
4
+ * Four jobs, all of them things only the Host process can do:
5
+ *
6
+ * 1. **Read the current DSH Session's messages.** The browser half shows a
7
+ * picker, but it cannot read another part of the app's own conversation
8
+ * without going through a Host route, and the Host already owns the
9
+ * authoritative event log through `ctx.sessionQuery`. `readSession()` returns
10
+ * one Session's complete raw event log; this half reduces it to the
11
+ * user/assistant messages a human would recognise, with the system,
12
+ * developer, tool and injected-prompt events dropped.
13
+ *
14
+ * 2. **Bind DSH Sessions to DeepSeek conversations.** The mapping is a plain
15
+ * JSON file under the user's own DSH home. It is the browser half that learns
16
+ * a DeepSeek conversation id (from the guest's own URL), and the Host that
17
+ * persists it, because a browser guest has no durable storage of its own.
18
+ *
19
+ * 3. **Keep the DeepSeek login alive across restarts.** The shell hands every
20
+ * browser guest a **process-lifetime** session partition
21
+ * (`dsh-sidebar-browser-<uuid>`, no `persist:` prefix, a fresh name every
22
+ * run), so cookies and site storage die with the app. This half stores the
23
+ * guest's `localStorage` and `document.cookie`, captured by the browser half,
24
+ * and hands them back on the next run.
25
+ *
26
+ * Note the honest limit: this Host runs as a plain Node child process
27
+ * (`ELECTRON_RUN_AS_NODE=1`), *not* inside Electron, so it cannot reach
28
+ * `session.fromPartition(...).cookies` and cannot carry **HttpOnly** cookies.
29
+ * The DeepSeek web app keeps its credential in `localStorage.userToken` and
30
+ * sends it as a bearer token, so replaying site storage is what actually
31
+ * restores the login; the non-HttpOnly cookie string rides along. See the
32
+ * README's known limitations.
33
+ *
34
+ * 4. **Report what is reachable**, so the browser half can explain itself when
35
+ * the desktop guest bridge is absent (a plain `dsh web` profile).
36
+ *
37
+ * No agent tools, no model calls, no outbound network of its own.
38
+ */
39
+
40
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
41
+ import { homedir } from 'node:os'
42
+ import { dirname, join } from 'node:path'
43
+
44
+ /** Stable cordis plugin name. */
45
+ export const name = 'deepseek-webchat'
46
+
47
+ /** The web server is the only service this plugin needs. */
48
+ export const inject = ['webServer']
49
+
50
+ /** The page this plugin exists to show. */
51
+ export const PAGE_URL = 'https://chat.deepseek.com/'
52
+
53
+ /**
54
+ * DeepSeek's own route table (read from its shipped bundle) is
55
+ * `/a/:agentId/s/:sessionId`, and the default agent is `chat`. So a conversation
56
+ * is addressable as a plain URL — no in-page JavaScript is needed to open one.
57
+ */
58
+ export const AGENT_ID = 'chat'
59
+
60
+ /**
61
+ * Build the DeepSeek conversation URL for one conversation id.
62
+ * @param sessionId - DeepSeek conversation id.
63
+ * @returns the absolute URL that opens that conversation.
64
+ */
65
+ export function deepseekConversationUrl(sessionId) {
66
+ return `${PAGE_URL}a/${AGENT_ID}/s/${encodeURIComponent(sessionId)}`
67
+ }
68
+
69
+ /**
70
+ * Extract a DeepSeek conversation id from a chat.deepseek.com URL.
71
+ * @param value - any URL string the guest reports.
72
+ * @returns the conversation id, or undefined when the URL names none.
73
+ */
74
+ export function deepseekSessionIdOf(value) {
75
+ if (typeof value !== 'string' || value === '') return undefined
76
+ let url
77
+ try {
78
+ url = new URL(value)
79
+ } catch {
80
+ return undefined
81
+ }
82
+ if (url.hostname !== 'chat.deepseek.com') return undefined
83
+ const match = /^\/a\/[^/]+\/s\/([^/?#]+)\/?$/.exec(url.pathname)
84
+ return match === null ? undefined : decodeURIComponent(match[1])
85
+ }
86
+
87
+ /** Route family; the browser half spells the same paths. */
88
+ export const ROUTES = {
89
+ state: '/api/dsh-deepseek-webchat/state',
90
+ messages: '/api/dsh-deepseek-webchat/messages',
91
+ binding: '/api/dsh-deepseek-webchat/binding',
92
+ sessionRestore: '/api/dsh-deepseek-webchat/session/restore',
93
+ sessionSave: '/api/dsh-deepseek-webchat/session/save',
94
+ diag: '/api/dsh-deepseek-webchat/diag',
95
+ }
96
+
97
+ /**
98
+ * The most recent diagnostics snapshot posted by the browser half.
99
+ *
100
+ * The guest lives in a `<webview>` this plugin cannot inspect from the outside,
101
+ * so when something misbehaves in there the only way to see it is to have the
102
+ * page report on itself. The browser half posts counters and the last few
103
+ * visibility transitions; this holds them until someone reads the route.
104
+ * @type {object|null}
105
+ */
106
+ let lastDiagnostics = null
107
+
108
+ /**
109
+ * The plugin's private state directory. Overridable so tests never touch the
110
+ * real profile directory.
111
+ */
112
+ let stateDirOverride = null
113
+
114
+ /**
115
+ * @returns the directory holding this plugin's two JSON files.
116
+ */
117
+ export function stateDir() {
118
+ return stateDirOverride ?? join(homedir(), '.dsh', 'dsh-deepseek-webchat')
119
+ }
120
+
121
+ /** Point the state directory somewhere else (tests only). @param dir - absolute path. */
122
+ export function setStateDir(dir) {
123
+ stateDirOverride = dir
124
+ }
125
+
126
+ /** @returns the DSH-Session → DeepSeek-conversation mapping file path. */
127
+ export function bindingsFile() {
128
+ return join(stateDir(), 'bindings.json')
129
+ }
130
+
131
+ /** @returns the guest session snapshot file path. */
132
+ export function sessionFile() {
133
+ return join(stateDir(), 'session.json')
134
+ }
135
+
136
+ /**
137
+ * Read one JSON file, treating absence and corruption alike as "nothing saved".
138
+ * @param file - absolute path.
139
+ * @returns the parsed object, or null.
140
+ */
141
+ export function readJsonFile(file) {
142
+ try {
143
+ if (!existsSync(file)) return null
144
+ const parsed = JSON.parse(readFileSync(file, 'utf8'))
145
+ return typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed) ? parsed : null
146
+ } catch {
147
+ return null
148
+ }
149
+ }
150
+
151
+ /**
152
+ * Write one JSON file atomically, so a crash mid-write cannot leave a truncated
153
+ * file that would read back as "nothing saved" and silently lose a login or a
154
+ * whole set of bindings.
155
+ * @param file - absolute path.
156
+ * @param value - JSON-serialisable value.
157
+ */
158
+ export function writeJsonFile(file, value) {
159
+ const dir = dirname(file)
160
+ mkdirSync(dir, { recursive: true })
161
+ const temporary = `${file}.${process.pid}.tmp`
162
+ writeFileSync(temporary, `${JSON.stringify(value, null, 2)}\n`, 'utf8')
163
+ renameSync(temporary, file)
164
+ }
165
+
166
+ //#region message extraction
167
+
168
+ /** The tool the agent calls to ask the human a question. */
169
+ export const ASK_TOOL = 'ask_user_question'
170
+
171
+ /**
172
+ * Selectable row kinds.
173
+ *
174
+ * `user`, `assistant`, `question` and `answer` are the default set — the
175
+ * conversation as a person reads it, including the questions the agent asked
176
+ * them and the options those questions offered. The rest are opt-in through
177
+ * the picker's advanced switch, because they are the machinery behind the
178
+ * conversation rather than the conversation itself.
179
+ */
180
+ export const KINDS = {
181
+ user: 'user',
182
+ assistant: 'assistant',
183
+ question: 'question',
184
+ answer: 'answer',
185
+ reasoning: 'reasoning',
186
+ toolCall: 'tool-call',
187
+ toolResult: 'tool-result',
188
+ todo: 'todo',
189
+ command: 'command',
190
+ summary: 'summary',
191
+ }
192
+
193
+ /** Kinds shown only when the picker's advanced switch is on. */
194
+ export const ADVANCED_KINDS = new Set([
195
+ KINDS.reasoning, KINDS.toolCall, KINDS.toolResult, KINDS.command, KINDS.summary,
196
+ ])
197
+
198
+ /**
199
+ * Plain text of one content-block array.
200
+ *
201
+ * Only `text` blocks contribute by default. `reasoning` is the model's private
202
+ * thinking: it is dropped unless the caller explicitly opts in, matching how the
203
+ * harness itself extracts searchable text (see `extractSessionEventText` in
204
+ * @deepseek-ai/dsh-session-query).
205
+ * @param content - a message's content array.
206
+ * @param options - `{ includeReasoning }` to keep thinking blocks.
207
+ * @returns the joined text.
208
+ */
209
+ export function contentText(content, options = {}) {
210
+ if (!Array.isArray(content)) return ''
211
+ const includeReasoning = options.includeReasoning === true
212
+ const parts = []
213
+ for (const block of content) {
214
+ if (typeof block !== 'object' || block === null) continue
215
+ if (block.type === 'text' && typeof block.text === 'string') parts.push(block.text.trim())
216
+ else if (includeReasoning && block.type === 'reasoning' && typeof block.text === 'string') {
217
+ parts.push(block.text.trim())
218
+ }
219
+ }
220
+ return parts.filter(Boolean).join('\n')
221
+ }
222
+
223
+ /**
224
+ * The `tool-call` blocks of one assistant message.
225
+ *
226
+ * Tool calls are recorded inside the assistant's own content array
227
+ * (`{ type: 'tool-call', id, name, arguments }`), not as a separate message, so
228
+ * they are read from there rather than from a `tool/call` event.
229
+ * @param content - an assistant message's content array.
230
+ * @returns the tool-call blocks.
231
+ */
232
+ export function toolCallBlocks(content) {
233
+ if (!Array.isArray(content)) return []
234
+ const blocks = []
235
+ for (const block of content) {
236
+ if (typeof block !== 'object' || block === null) continue
237
+ if (block.type !== 'tool-call') continue
238
+ blocks.push({
239
+ name: typeof block.name === 'string' ? block.name : '',
240
+ arguments: typeof block.arguments === 'string' ? block.arguments : '',
241
+ })
242
+ }
243
+ return blocks
244
+ }
245
+
246
+ /**
247
+ * Whether a `user/message` event is something the human actually typed.
248
+ *
249
+ * DSH records injected context — agent instructions, skill catalogs, goal
250
+ * rounds, time context, compaction checkpoints, team and webhook deliveries —
251
+ * as `user/message` events too, distinguished by `data.source.kind`. Only
252
+ * `kind === 'user'` (and its RPC variant, which also reports `kind: 'user'`) is
253
+ * the person at the keyboard, which is exactly the set the acceptance criteria
254
+ * call "消息" and the privacy rules call "not system prompts".
255
+ * @param event - one raw session event.
256
+ * @returns true for a human turn.
257
+ */
258
+ export function isHumanUserMessage(event) {
259
+ const source = event?.data?.source
260
+ return typeof source === 'object' && source !== null && source.kind === 'user'
261
+ }
262
+
263
+ /**
264
+ * Whether a `user/message` event is the human's answer to an agent question.
265
+ *
266
+ * These arrive as ordinary user messages tagged
267
+ * `source.kind === 'user-question-reply'`, so the plain human filter above
268
+ * drops them. They belong in the default set: a question without its answer is
269
+ * half a decision, and the answer is often the part worth quoting.
270
+ * @param event - one raw session event.
271
+ * @returns true for a question reply.
272
+ */
273
+ export function isQuestionReply(event) {
274
+ const source = event?.data?.source
275
+ return typeof source === 'object' && source !== null && source.kind === 'user-question-reply'
276
+ }
277
+
278
+ /**
279
+ * Read a question batch out of an `ask_user_question` call's arguments.
280
+ *
281
+ * Mirrors `questionsOf` in @deepseek-ai/dsh-user-questions: the arguments are a
282
+ * JSON string, and each question carries an id, the question text, an optional
283
+ * header, optional options (`{ label, description }`), and an optional
284
+ * `multi_select` flag that the service renames to `multiSelect`.
285
+ * @param argumentsText - raw JSON arguments from the event.
286
+ * @returns the questions, or `[]` when unreadable.
287
+ */
288
+ export function questionsOf(argumentsText) {
289
+ if (typeof argumentsText !== 'string' || argumentsText.trim() === '') return []
290
+ let parsed
291
+ try {
292
+ parsed = JSON.parse(argumentsText)
293
+ } catch {
294
+ return []
295
+ }
296
+ const questions = parsed?.questions
297
+ if (!Array.isArray(questions)) return []
298
+ const out = []
299
+ for (const question of questions) {
300
+ if (typeof question !== 'object' || question === null) continue
301
+ const text = typeof question.question === 'string' ? question.question.trim() : ''
302
+ if (text === '') continue
303
+ const row = { question: text }
304
+ if (typeof question.header === 'string' && question.header.trim() !== '') {
305
+ row.header = question.header.trim()
306
+ }
307
+ if (Array.isArray(question.options)) {
308
+ const options = []
309
+ for (const option of question.options) {
310
+ if (typeof option !== 'object' || option === null) continue
311
+ const label = typeof option.label === 'string' ? option.label.trim() : ''
312
+ if (label === '') continue
313
+ const entry = { label }
314
+ if (typeof option.description === 'string' && option.description.trim() !== '') {
315
+ entry.description = option.description.trim()
316
+ }
317
+ options.push(entry)
318
+ }
319
+ if (options.length > 0) row.options = options
320
+ }
321
+ if (question.multi_select === true) row.multiSelect = true
322
+ out.push(row)
323
+ }
324
+ return out
325
+ }
326
+
327
+ /**
328
+ * Render a question batch as the text the picker shows and quotes.
329
+ * @param questions - the batch from {@link questionsOf}.
330
+ * @returns one block of readable lines.
331
+ */
332
+ export function formatQuestions(questions) {
333
+ const lines = []
334
+ for (const question of questions) {
335
+ const head = question.header === undefined ? '' : question.header + ':'
336
+ lines.push(head + question.question)
337
+ for (const option of question.options ?? []) {
338
+ const suffix = option.description === undefined ? '' : ' — ' + option.description
339
+ lines.push(' · ' + option.label + suffix)
340
+ }
341
+ if (question.multiSelect === true) lines.push(' · (可多选 / multiple choice)')
342
+ }
343
+ return lines.join('\n')
344
+ }
345
+
346
+ /** Truncate long single-line payloads so a picker row stays readable. */
347
+ function clip(text, limit = 2000) {
348
+ const value = String(text ?? '').trim()
349
+ return value.length <= limit ? value : value.slice(0, limit) + ' …'
350
+ }
351
+
352
+ /**
353
+ * Reduce one Session's raw event log to the rows a human would recognise.
354
+ *
355
+ * Default set: the human's turns, the assistant's replies, the questions the
356
+ * agent asked the human (with their options), and the human's answers to them.
357
+ * Advanced set: the assistant's reasoning, its tool calls, the tool results,
358
+ * todo lists, slash commands, and compaction summaries.
359
+ *
360
+ * Deliberately excluded in both modes: `system/message`, `developer/message`,
361
+ * injected `user/message` context (agent instructions, time context, goals,
362
+ * compaction checkpoints, team deliveries), approval records, and the raw
363
+ * request headers — the same exclusions the privacy section documents.
364
+ *
365
+ * @param events - raw events from `ctx.sessionQuery.readSession`.
366
+ * @param options - `{ advanced }` to include the machinery rows.
367
+ * @returns `{ seq, role, kind, text }` rows in log order, empty ones dropped.
368
+ */
369
+ export function extractMessages(events, options = {}) {
370
+ if (!Array.isArray(events)) return []
371
+ const advanced = options.advanced === true
372
+ const rows = []
373
+
374
+ /** Assistant text, plus the advanced-only reasoning and tool-call blocks. */
375
+ const pushAssistant = (event, content) => {
376
+ const text = contentText(content)
377
+ if (text !== '') rows.push({ seq: event.seq, role: 'assistant', kind: KINDS.assistant, text })
378
+ if (!advanced) return
379
+ // Reasoning blocks are read directly rather than through `contentText`,
380
+ // which merges text and thinking into one string; the two are separate
381
+ // rows here so a reader can quote the answer without the deliberation.
382
+ const thinking = []
383
+ if (Array.isArray(content)) {
384
+ for (const block of content) {
385
+ if (block?.type === 'reasoning' && typeof block.text === 'string') {
386
+ const value = block.text.trim()
387
+ if (value !== '') thinking.push(value)
388
+ }
389
+ }
390
+ }
391
+ if (thinking.length > 0) {
392
+ rows.push({ seq: event.seq, role: 'assistant', kind: KINDS.reasoning, text: thinking.join('\n') })
393
+ }
394
+ for (const call of toolCallBlocks(content)) {
395
+ if (call.name === ASK_TOOL) continue // rendered as the question row instead
396
+ rows.push({
397
+ seq: event.seq,
398
+ role: 'assistant',
399
+ kind: KINDS.toolCall,
400
+ text: call.name + '(' + clip(call.arguments, 800) + ')',
401
+ })
402
+ }
403
+ }
404
+
405
+ for (const event of events) {
406
+ if (typeof event !== 'object' || event === null) continue
407
+
408
+ if (event.type === 'user/message') {
409
+ if (isQuestionReply(event)) {
410
+ const text = contentText(event.data?.content)
411
+ if (text !== '') rows.push({ seq: event.seq, role: 'user', kind: KINDS.answer, text })
412
+ continue
413
+ }
414
+ if (!isHumanUserMessage(event)) continue
415
+ const text = contentText(event.data?.content)
416
+ if (text !== '') rows.push({ seq: event.seq, role: 'user', kind: KINDS.user, text })
417
+ continue
418
+ }
419
+
420
+ if (event.type === 'assistant/message') {
421
+ pushAssistant(event, event.data?.message?.content)
422
+ continue
423
+ }
424
+
425
+ // The agent's question is a tool call, so it is read from `tool/call`
426
+ // rather than from a message — and it is a default row, not advanced.
427
+ if (event.type === 'tool/call') {
428
+ if (event.data?.name === ASK_TOOL) {
429
+ const questions = questionsOf(event.data?.arguments)
430
+ if (questions.length > 0) {
431
+ rows.push({
432
+ seq: event.seq, role: 'assistant', kind: KINDS.question,
433
+ text: formatQuestions(questions),
434
+ })
435
+ }
436
+ continue
437
+ }
438
+ if (advanced) {
439
+ rows.push({
440
+ seq: event.seq, role: 'assistant', kind: KINDS.toolCall,
441
+ text: String(event.data?.name ?? 'tool') + '(' + clip(event.data?.arguments, 800) + ')',
442
+ })
443
+ }
444
+ continue
445
+ }
446
+
447
+ // A todo list is the agent's own plan, which the user is already looking at
448
+ // on screen, so it is offered by default rather than hidden behind the
449
+ // advanced switch the way its raw tool traffic is.
450
+ if (event.type === 'todo/write') {
451
+ const todos = event.data?.todos
452
+ if (!Array.isArray(todos)) continue
453
+ const lines = []
454
+ for (const todo of todos) {
455
+ if (typeof todo !== 'object' || todo === null) continue
456
+ const content = typeof todo.content === 'string' ? todo.content.trim() : ''
457
+ if (content === '') continue
458
+ const mark = todo.status === 'completed' ? '[x]' : todo.status === 'in_progress' ? '[~]' : '[ ]'
459
+ lines.push(mark + ' ' + content)
460
+ }
461
+ if (lines.length > 0) {
462
+ rows.push({ seq: event.seq, role: 'assistant', kind: KINDS.todo, text: lines.join('\n') })
463
+ }
464
+ continue
465
+ }
466
+
467
+ if (!advanced) continue
468
+
469
+ if (event.type === 'tool/result') {
470
+ const message = event.data?.message
471
+ const text = contentText(message?.content)
472
+ const failed = message?.isError === true || event.data?.error !== undefined
473
+ const body = text === '' ? clip(JSON.stringify(event.data?.error ?? ''), 400) : text
474
+ if (body !== '') {
475
+ rows.push({
476
+ seq: event.seq, role: 'tool', kind: KINDS.toolResult,
477
+ text: (failed ? '⚠ ' : '') + body,
478
+ })
479
+ }
480
+ continue
481
+ }
482
+
483
+ if (event.type === 'command/run') {
484
+ const name = typeof event.data?.name === 'string' ? event.data.name : ''
485
+ const args = typeof event.data?.args === 'string' ? event.data.args : ''
486
+ const text = ('/' + name + (args === '' ? '' : ' ' + args)).trim()
487
+ if (text !== '/') rows.push({ seq: event.seq, role: 'user', kind: KINDS.command, text })
488
+ continue
489
+ }
490
+
491
+ if (event.type === 'command/done') {
492
+ const text = contentText(event.data?.text === undefined ? [] : [{ type: 'text', text: event.data.text }])
493
+ const body = text === '' ? String(event.data?.kind ?? '') : text
494
+ if (body !== '') rows.push({ seq: event.seq, role: 'tool', kind: KINDS.command, text: body })
495
+ continue
496
+ }
497
+
498
+ if (event.type === 'compaction/summary') {
499
+ const text = contentText(event.data?.summary)
500
+ if (text !== '') rows.push({ seq: event.seq, role: 'assistant', kind: KINDS.summary, text })
501
+ }
502
+ }
503
+
504
+ return rows
505
+ }
506
+
507
+ //#endregion
508
+
509
+ //#region HTTP helpers
510
+
511
+ /**
512
+ * Read and parse a JSON request body.
513
+ * @param req - incoming request.
514
+ * @param limit - maximum accepted byte length.
515
+ * @returns the parsed body, or null when absent/oversized/malformed.
516
+ */
517
+ export async function readJsonBody(req, limit = 4 * 1024 * 1024) {
518
+ const chunks = []
519
+ let size = 0
520
+ for await (const chunk of req) {
521
+ size += chunk.length
522
+ if (size > limit) return null
523
+ chunks.push(chunk)
524
+ }
525
+ if (size === 0) return null
526
+ try {
527
+ const parsed = JSON.parse(Buffer.concat(chunks).toString('utf8'))
528
+ return typeof parsed === 'object' && parsed !== null ? parsed : null
529
+ } catch {
530
+ return null
531
+ }
532
+ }
533
+
534
+ /**
535
+ * Answer one request with JSON.
536
+ * @param res - response to write.
537
+ * @param status - HTTP status code.
538
+ * @param body - JSON-serialisable body.
539
+ */
540
+ export function json(res, status, body) {
541
+ const text = JSON.stringify(body)
542
+ res.writeHead(status, {
543
+ 'content-type': 'application/json; charset=utf-8',
544
+ 'cache-control': 'no-store',
545
+ 'content-length': Buffer.byteLength(text),
546
+ })
547
+ res.end(text)
548
+ }
549
+
550
+ /** @returns the value of one query parameter, or undefined. */
551
+ function queryParam(url, key) {
552
+ try {
553
+ return new URL(url, 'http://127.0.0.1').searchParams.get(key) ?? undefined
554
+ } catch {
555
+ return undefined
556
+ }
557
+ }
558
+
559
+ //#endregion
560
+
561
+ //#region binding store
562
+
563
+ /**
564
+ * Reduce a DSH Session id to one canonical form.
565
+ *
566
+ * DSH names the same Session two ways: its event and query APIs hand out the
567
+ * bare uuid (`e07a9659-…`), while the session store names the directory
568
+ * `session-e07a9659-…`. A plugin sees whichever form its caller happens to hold,
569
+ * so keying the map on the raw string made a Session look unbound depending on
570
+ * where the id came from — and an unbound Session gets sent to DeepSeek's root,
571
+ * which is what made the binding look unreliable. Both forms reduce to the bare
572
+ * uuid, so either one finds the same entry.
573
+ * @param value - a Session id in either form.
574
+ * @returns the canonical id, or '' when there is none.
575
+ */
576
+ export function canonicalSessionId(value) {
577
+ if (typeof value !== 'string') return ''
578
+ const trimmed = value.trim()
579
+ if (trimmed === '') return ''
580
+ return trimmed.startsWith('session-') ? trimmed.slice('session-'.length) : trimmed
581
+ }
582
+
583
+ /** @returns the whole DSH-Session → DeepSeek-conversation map, canonically keyed. */
584
+ export function readBindings() {
585
+ const raw = readJsonFile(bindingsFile())
586
+ const map = raw?.bindings
587
+ if (typeof map !== 'object' || map === null || Array.isArray(map)) return {}
588
+ // Canonicalise on read, so entries written before this existed — and entries
589
+ // written by a caller holding the prefixed form — still resolve.
590
+ const out = {}
591
+ for (const [key, value] of Object.entries(map)) {
592
+ const canonical = canonicalSessionId(key)
593
+ if (canonical === '') continue
594
+ if (typeof value !== 'string' || value === '') continue
595
+ out[canonical] = value
596
+ }
597
+ return out
598
+ }
599
+
600
+ /**
601
+ * @param dshSessionId - DSH Session id, in either form.
602
+ * @returns the bound DeepSeek conversation id, or undefined.
603
+ */
604
+ export function readBinding(dshSessionId) {
605
+ const value = readBindings()[canonicalSessionId(dshSessionId)]
606
+ return typeof value === 'string' && value !== '' ? value : undefined
607
+ }
608
+
609
+ /**
610
+ * Record one binding, so this Session follows the conversation it was last in.
611
+ *
612
+ * Rewriting the same pair is a no-op, so the browser half can call this on every
613
+ * navigation without churning the disk. A conversation already claimed by a
614
+ * *different* Session is refused: the guest landing in someone else's
615
+ * conversation must not quietly steal its binding. Re-pointing this Session at a
616
+ * conversation nobody owns is allowed, and is how "the current conversation
617
+ * changed, so follow it" works.
618
+ * @param dshSessionId - DSH Session id, in either form.
619
+ * @param deepseekSessionId - DeepSeek conversation id.
620
+ * @returns true when the file changed.
621
+ */
622
+ export function writeBinding(dshSessionId, deepseekSessionId) {
623
+ const dsh = canonicalSessionId(dshSessionId)
624
+ if (dsh === '') return false
625
+ if (typeof deepseekSessionId !== 'string' || deepseekSessionId === '') return false
626
+ const bindings = readBindings()
627
+ if (bindings[dsh] === deepseekSessionId) return false
628
+ for (const [owner, value] of Object.entries(bindings)) {
629
+ if (owner !== dsh && value === deepseekSessionId) return false
630
+ }
631
+ bindings[dsh] = deepseekSessionId
632
+ writeJsonFile(bindingsFile(), { version: 1, bindings })
633
+ return true
634
+ }
635
+
636
+ /**
637
+ * Find which DSH Session owns a DeepSeek conversation.
638
+ *
639
+ * The browser half needs this before it can tell whether the guest is already
640
+ * sitting in *this* Session's conversation or in one belonging to a Session the
641
+ * user has since switched away from — the difference between adopting the page
642
+ * and leaving it alone.
643
+ * @param deepseekSessionId - DeepSeek conversation id.
644
+ * @returns the owning DSH Session id, or undefined.
645
+ */
646
+ export function findOwner(deepseekSessionId) {
647
+ if (typeof deepseekSessionId !== 'string' || deepseekSessionId === '') return undefined
648
+ const bindings = readBindings()
649
+ for (const [dshSessionId, value] of Object.entries(bindings)) {
650
+ if (value === deepseekSessionId) return dshSessionId
651
+ }
652
+ return undefined
653
+ }
654
+
655
+ /**
656
+ * Forget one binding, so the next visit starts a fresh DeepSeek conversation.
657
+ * @param dshSessionId - DSH Session id, in either form.
658
+ * @returns true when something was removed.
659
+ */
660
+ export function deleteBinding(dshSessionId) {
661
+ const dsh = canonicalSessionId(dshSessionId)
662
+ if (dsh === '') return false
663
+ const bindings = readBindings()
664
+ if (!(dsh in bindings)) return false
665
+ delete bindings[dsh]
666
+ writeJsonFile(bindingsFile(), { version: 1, bindings })
667
+ return true
668
+ }
669
+
670
+ //#endregion
671
+
672
+ //#region guest session snapshot
673
+
674
+ /**
675
+ * Persist the guest's own storage and cookie string.
676
+ * @param storage - `[key, value]` pairs from the guest's localStorage.
677
+ * @param cookie - the guest's `document.cookie`.
678
+ * @returns the snapshot that was written.
679
+ */
680
+ export function saveGuestSession(storage, cookie) {
681
+ const snapshot = {
682
+ version: 1,
683
+ savedAt: new Date().toISOString(),
684
+ storage: Array.isArray(storage)
685
+ ? storage.filter(
686
+ (pair) => Array.isArray(pair) && typeof pair[0] === 'string' && typeof pair[1] === 'string',
687
+ )
688
+ : [],
689
+ cookie: typeof cookie === 'string' ? cookie : '',
690
+ }
691
+ writeJsonFile(sessionFile(), snapshot)
692
+ return snapshot
693
+ }
694
+
695
+ /**
696
+ * @returns the stored guest state, or null when nothing usable is saved.
697
+ */
698
+ export function loadGuestSession() {
699
+ const snapshot = readJsonFile(sessionFile())
700
+ if (snapshot === null) return null
701
+ const storage = Array.isArray(snapshot.storage) ? snapshot.storage : []
702
+ const cookie = typeof snapshot.cookie === 'string' ? snapshot.cookie : ''
703
+ if (storage.length === 0 && cookie === '') return null
704
+ return { storage, cookie }
705
+ }
706
+
707
+ //#endregion
708
+
709
+ /**
710
+ * Cache of extracted rows, keyed by session id and mode.
711
+ *
712
+ * Reading one session costs `sessionQuery.readSession`, which parses the whole
713
+ * session log — measured at 2.3 seconds for a 3.6 MB session, and that read is
714
+ * synchronous work on the host. Opening the picker did it every time, so the
715
+ * panel appeared to freeze for seconds on each open even though nothing was
716
+ * looping. The log only ever grows, so a result stays valid while the session's
717
+ * event count is unchanged, and that count is cheap to read.
718
+ *
719
+ * @type {Map<string, { count: number, messages: object[] }>}
720
+ */
721
+ const messageCache = new Map()
722
+
723
+ /** Bound the cache so a long-lived host cannot accumulate sessions forever. */
724
+ const MESSAGE_CACHE_LIMIT = 8
725
+
726
+ /**
727
+ * @param sessionId - DSH Session id.
728
+ * @param advanced - whether the advanced row set was requested.
729
+ * @returns the cache key for that pair.
730
+ */
731
+ function messageCacheKey(sessionId, advanced) {
732
+ return (advanced ? 'a\u0000' : 'p\u0000') + sessionId
733
+ }
734
+
735
+ /**
736
+ * Read one Session's pickable messages through the Host's own query service.
737
+ * @param ctx - Host context.
738
+ * @param sessionId - DSH Session id.
739
+ * @param advanced - include reasoning, tool calls, results, todos, commands.
740
+ * @returns the messages, or a reason they could not be read.
741
+ */
742
+ async function readSessionMessages(ctx, sessionId, advanced = false) {
743
+ const query = ctx.get('sessionQuery')
744
+ if (query === undefined) {
745
+ return { ok: false, error: 'this profile provides no sessionQuery service', messages: [] }
746
+ }
747
+ if (typeof sessionId !== 'string' || sessionId === '') {
748
+ return { ok: false, error: 'a session id is required', messages: [] }
749
+ }
750
+ try {
751
+ const session = await query.readSession(sessionId)
752
+ const events = session?.events
753
+ const count = Array.isArray(events) ? events.length : 0
754
+ const key = messageCacheKey(sessionId, advanced)
755
+ const cached = messageCache.get(key)
756
+ if (cached !== undefined && cached.count === count) {
757
+ return { ok: true, error: '', messages: cached.messages, cached: true }
758
+ }
759
+ const messages = extractMessages(events, { advanced })
760
+ // Re-inserting moves the key to the end, so the oldest falls out first.
761
+ messageCache.delete(key)
762
+ messageCache.set(key, { count, messages })
763
+ while (messageCache.size > MESSAGE_CACHE_LIMIT) {
764
+ const oldest = messageCache.keys().next().value
765
+ messageCache.delete(oldest)
766
+ }
767
+ return { ok: true, error: '', messages, cached: false }
768
+ } catch (error) {
769
+ return { ok: false, error: messageOf(error), messages: [] }
770
+ }
771
+ }
772
+
773
+ /** Drop cached rows, so a test or a reload cannot observe a stale list. */
774
+ export function clearMessageCache() {
775
+ messageCache.clear()
776
+ }
777
+
778
+ /** @param error - anything thrown. @returns a readable message. */
779
+ function messageOf(error) {
780
+ return error instanceof Error ? error.message : String(error)
781
+ }
782
+
783
+ /**
784
+ * Register this plugin's routes.
785
+ * @param ctx - Host context carrying `webServer`.
786
+ */
787
+ export function apply(ctx) {
788
+ ctx.effect(() => ctx.webServer.register({
789
+ kind: 'exact',
790
+ path: ROUTES.state,
791
+ handler: (req, res) => {
792
+ json(res, 200, {
793
+ ok: true,
794
+ pageUrl: PAGE_URL,
795
+ agentId: AGENT_ID,
796
+ sessionQuery: ctx.get('sessionQuery') !== undefined,
797
+ bindings: Object.keys(readBindings()).length,
798
+ sessionSaved: readJsonFile(sessionFile()) !== null,
799
+ })
800
+ },
801
+ }), 'deepseek-webchat: state route')
802
+
803
+ ctx.effect(() => ctx.webServer.register({
804
+ kind: 'exact',
805
+ path: ROUTES.messages,
806
+ handler: async (req, res) => {
807
+ const sessionId = queryParam(req.url, 'sessionId')
808
+ // The picker's advanced switch is a per-request choice, so the host
809
+ // filters rather than shipping the whole log and hiding rows in the UI.
810
+ const advanced = queryParam(req.url, 'advanced') === '1'
811
+ json(res, 200, await readSessionMessages(ctx, sessionId, advanced))
812
+ },
813
+ }), 'deepseek-webchat: messages route')
814
+
815
+ ctx.effect(() => ctx.webServer.register({
816
+ kind: 'exact',
817
+ path: ROUTES.binding,
818
+ handler: async (req, res) => {
819
+ // One route serves read, write and forget, because all three are the same
820
+ // mapping seen from different sides and splitting them would let the
821
+ // browser half observe a half-applied state.
822
+ if (req.method === 'GET') {
823
+ // Forward lookup asks "which conversation does this Session own"; the
824
+ // reverse one asks "whose conversation is this".
825
+ const reverse = queryParam(req.url, 'deepseekSessionId')
826
+ if (reverse !== undefined) {
827
+ json(res, 200, { ok: true, dshSessionId: findOwner(reverse) ?? null })
828
+ return
829
+ }
830
+ const sessionId = queryParam(req.url, 'sessionId')
831
+ json(res, 200, { ok: true, deepseekSessionId: readBinding(sessionId) ?? null })
832
+ return
833
+ }
834
+ const body = await readJsonBody(req)
835
+ if (body === null) {
836
+ json(res, 400, { ok: false, error: 'a JSON body is required' })
837
+ return
838
+ }
839
+ if (body.forget === true) {
840
+ json(res, 200, { ok: true, removed: deleteBinding(body.dshSessionId), deepseekSessionId: null })
841
+ return
842
+ }
843
+ const changed = writeBinding(body.dshSessionId, body.deepseekSessionId)
844
+ json(res, 200, { ok: true, changed, deepseekSessionId: body.deepseekSessionId })
845
+ },
846
+ }), 'deepseek-webchat: binding route')
847
+
848
+ // Diagnostics the browser half reports about itself. Read-only in effect: a
849
+ // GET returns the last snapshot, a POST replaces it. Nothing here is needed
850
+ // for the plugin to work, which is why it is one small route rather than
851
+ // anything woven into the rest.
852
+ ctx.effect(() => ctx.webServer.register({
853
+ kind: 'exact',
854
+ path: ROUTES.diag,
855
+ handler: async (req, res) => {
856
+ if (req.method === 'GET') {
857
+ // `?since=<epochMs>` returns only the events after that mark, so a
858
+ // deliberately reproduced flicker can be read without the noise of
859
+ // everything that happened before it.
860
+ const since = queryParam(req.url, 'since')
861
+ const cut = since === undefined ? 0 : Number(since)
862
+ const all = lastDiagnostics === null || !Array.isArray(lastDiagnostics.events)
863
+ ? []
864
+ : lastDiagnostics.events
865
+ json(res, 200, {
866
+ ok: true,
867
+ diagnostics: lastDiagnostics,
868
+ recent: Number.isFinite(cut) ? all.filter((event) => event.t > cut) : all,
869
+ })
870
+ return
871
+ }
872
+ const body = await readJsonBody(req)
873
+ if (body === null) {
874
+ json(res, 400, { ok: false, error: 'a JSON body is required' })
875
+ return
876
+ }
877
+ lastDiagnostics = { at: Date.now(), ...body }
878
+ json(res, 200, { ok: true })
879
+ },
880
+ }), 'deepseek-webchat: diagnostics route')
881
+
882
+ ctx.effect(() => ctx.webServer.register({
883
+ kind: 'exact',
884
+ path: ROUTES.sessionRestore,
885
+ handler: (req, res) => {
886
+ const saved = loadGuestSession()
887
+ json(res, 200, {
888
+ ok: true,
889
+ storage: saved === null ? [] : saved.storage,
890
+ cookie: saved === null ? '' : saved.cookie,
891
+ })
892
+ },
893
+ }), 'deepseek-webchat: session restore route')
894
+
895
+ ctx.effect(() => ctx.webServer.register({
896
+ kind: 'exact',
897
+ path: ROUTES.sessionSave,
898
+ handler: async (req, res) => {
899
+ const body = await readJsonBody(req)
900
+ if (body === null) {
901
+ json(res, 400, { ok: false, error: 'a JSON body is required' })
902
+ return
903
+ }
904
+ const snapshot = saveGuestSession(body.storage, body.cookie)
905
+ json(res, 200, { ok: true, storage: snapshot.storage.length, cookie: snapshot.cookie !== '' })
906
+ },
907
+ }), 'deepseek-webchat: session save route')
908
+ }