@zhengxiantai/dsh-mindmap 0.0.0-stage → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js ADDED
@@ -0,0 +1,732 @@
1
+ /**
2
+ * dsh-mindmap — host half.
3
+ *
4
+ * Keeps the topic-tree data behind the browser mind map:
5
+ * - `POST /mindmap/api/summarize` one branch -> { topic, summary, open[] }
6
+ * - `POST /mindmap/api/summaries` cached summaries for a batch of ids
7
+ * - `POST /mindmap/api/turns` user-turn boundaries for the rewind UI
8
+ * - `GET /mindmap/api/health` activation probe
9
+ *
10
+ * Summaries are plugin-owned metadata, cached in
11
+ * `$DSH_HOME/storages/mindmap/summaries.json`, and never written into a
12
+ * session log. The session tree itself is derived from the public
13
+ * `ctx.sessionQuery` / `ctx.sessions` services, so this half adds no new
14
+ * session storage and no model-visible context.
15
+ *
16
+ * The model-facing `mindmap_topics` tool exposes the same tree read-only, so
17
+ * an agent can see sibling branches and their summaries without paying their
18
+ * token cost in the conversation.
19
+ *
20
+ * @module dsh-mindmap
21
+ */
22
+ import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
23
+ import { homedir } from 'node:os'
24
+ import { dirname, join } from 'node:path'
25
+ import { defineTool } from '@deepseek-ai/dsh-tools'
26
+
27
+ export const name = 'mindmap'
28
+
29
+ /** Services this half needs before it can activate. */
30
+ export const inject = ['webServer', 'sessionQuery', 'sessions', 'llm', 'tools']
31
+
32
+ const ROUTE_PREFIX = '/mindmap/api'
33
+ const STORE_VERSION = 1
34
+ const MAX_BODY_BYTES = 64 * 1024
35
+ const MAX_IDS_PER_REQUEST = 200
36
+ const MAX_TREE_NODES = 80
37
+
38
+ const DEFAULTS = Object.freeze({
39
+ autoSummarize: true,
40
+ summaryMaxInputChars: 12_000,
41
+ summaryMaxOutputTokens: 700,
42
+ summaryTimeoutMs: 60_000,
43
+ maxTopicsPerRequest: 64,
44
+ trustedHosts: [],
45
+ })
46
+
47
+ /** Resolve the plugin configuration against defaults, rejecting nonsense. */
48
+ function resolveConfig(raw) {
49
+ const input = raw !== null && typeof raw === 'object' ? raw : {}
50
+ const positive = (value, fallback) =>
51
+ typeof value === 'number' && Number.isFinite(value) && value > 0 ? Math.floor(value) : fallback
52
+ return {
53
+ autoSummarize: input.autoSummarize !== false,
54
+ summaryMaxInputChars: positive(input.summaryMaxInputChars, DEFAULTS.summaryMaxInputChars),
55
+ summaryMaxOutputTokens: positive(input.summaryMaxOutputTokens, DEFAULTS.summaryMaxOutputTokens),
56
+ summaryTimeoutMs: positive(input.summaryTimeoutMs, DEFAULTS.summaryTimeoutMs),
57
+ maxTopicsPerRequest: positive(input.maxTopicsPerRequest, DEFAULTS.maxTopicsPerRequest),
58
+ trustedHosts: Array.isArray(input.trustedHosts)
59
+ ? input.trustedHosts.filter((entry) => typeof entry === 'string' && entry.length > 0)
60
+ : [],
61
+ provider: typeof input.provider === 'string' && input.provider !== '' ? input.provider : undefined,
62
+ model: typeof input.model === 'string' && input.model !== '' ? input.model : undefined,
63
+ dataFile: typeof input.dataFile === 'string' && input.dataFile !== '' ? input.dataFile : defaultDataFile(),
64
+ }
65
+ }
66
+
67
+ /** Default on-disk summary cache, shared by every workspace of one DSH home. */
68
+ function defaultDataFile() {
69
+ const home = process.env.DSH_HOME !== undefined && process.env.DSH_HOME !== ''
70
+ ? process.env.DSH_HOME
71
+ : join(homedir(), '.dsh')
72
+ return join(home, 'storages', 'mindmap', 'summaries.json')
73
+ }
74
+
75
+ function warn(ctx, message, error) {
76
+ try {
77
+ ctx.logger?.warn?.(`[mindmap] ${message}${error === undefined ? '' : `: ${String(error)}`}`)
78
+ } catch {
79
+ // A logger mismatch must never break the plugin.
80
+ }
81
+ }
82
+
83
+ /* ── text helpers ───────────────────────────────────────────────────────── */
84
+
85
+ /** Join the text blocks of one persisted content array. */
86
+ function textOfContent(content) {
87
+ if (!Array.isArray(content)) return ''
88
+ const parts = []
89
+ for (const block of content) {
90
+ if (block !== null && typeof block === 'object' && block.type === 'text' && typeof block.text === 'string') {
91
+ parts.push(block.text)
92
+ }
93
+ }
94
+ return parts.join('\n').trim()
95
+ }
96
+
97
+ /** Collapse whitespace and strip terminal control bytes from model output. */
98
+ function cleanLine(text, maxLength) {
99
+ const flattened = String(text ?? '')
100
+ // eslint-disable-next-line no-control-regex -- deliberate terminal-control scrub
101
+ .replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g, '')
102
+ .replace(/\s+/g, ' ')
103
+ .trim()
104
+ return flattened.length > maxLength ? `${flattened.slice(0, maxLength - 1)}…` : flattened
105
+ }
106
+
107
+ /** Read the model surface into a bounded, role-labelled transcript. */
108
+ function collectTranscript(surface, maxChars) {
109
+ const turns = []
110
+ let route
111
+ for (const event of surface.events ?? []) {
112
+ const type = event.type ?? event.ty
113
+ if (type === 'user/message') {
114
+ const data = event.data ?? {}
115
+ const sourceKind = data.source?.kind
116
+ // Injected tool/command context is not part of the human discussion.
117
+ if (sourceKind !== undefined && sourceKind !== 'user') continue
118
+ const text = textOfContent(data.content)
119
+ if (text !== '') turns.push({ role: 'user', text })
120
+ } else if (type === 'assistant/message') {
121
+ const message = event.data?.message
122
+ const source = message?.source
123
+ if (source?.kind === 'model' && typeof source.provider === 'string' && typeof source.model === 'string') {
124
+ route = { provider: source.provider, model: source.model }
125
+ }
126
+ const text = textOfContent(message?.content)
127
+ if (text !== '') turns.push({ role: 'assistant', text })
128
+ }
129
+ }
130
+ const firstUser = turns.find((turn) => turn.role === 'user')
131
+ const tail = []
132
+ let used = 0
133
+ for (let index = turns.length - 1; index >= 0; index -= 1) {
134
+ const turn = turns[index]
135
+ const cost = turn.text.length + 8
136
+ if (used + cost > maxChars) break
137
+ used += cost
138
+ tail.unshift(turn)
139
+ }
140
+ if (firstUser !== undefined && !tail.includes(firstUser) && used + firstUser.text.length + 8 <= maxChars) {
141
+ tail.unshift(firstUser)
142
+ }
143
+ return { turns: tail, route, totalTurns: turns.length }
144
+ }
145
+
146
+ /**
147
+ * Turn starts for the rewind UI. `atSeq` is an inclusive fork cut, so a turn
148
+ * starting at seq S is removed by forking at S - 1.
149
+ * Fork seeds copy the inherited prefix and append a `session/end-seed` event;
150
+ * each such boundary in this log marks one ancestor level.
151
+ */
152
+ function collectForkBoundaries(events) {
153
+ const boundaries = []
154
+ for (const event of events ?? []) {
155
+ const type = event.type ?? event.ty
156
+ if (type !== 'session/end-seed') continue
157
+ if (event.data?.inherited !== true) continue
158
+ if (!Number.isSafeInteger(event.seq)) continue
159
+ if (!boundaries.includes(event.seq)) boundaries.push(event.seq)
160
+ }
161
+ return boundaries.sort((a, b) => a - b)
162
+ }
163
+
164
+ function collectRailLevels(events, forkBoundaries = [], outlineTurns) {
165
+ const starts = Array.isArray(outlineTurns) && outlineTurns.length > 0
166
+ ? outlineTurns.map((turn) => turn.seq).filter(Number.isSafeInteger)
167
+ : (events ?? [])
168
+ .filter((event) => (event.type ?? event.ty) === 'turn/start')
169
+ .map((event) => event.seq)
170
+ .filter(Number.isSafeInteger)
171
+ return starts.map((seq) => forkBoundaries.filter((boundary) => boundary >= seq).length)
172
+ }
173
+
174
+ function collectTurns(surface, forkBoundaries = []) {
175
+ const turns = []
176
+ let current
177
+ for (const event of surface.events ?? []) {
178
+ const type = event.type ?? event.ty
179
+ const seq = Number.isSafeInteger(event.seq) ? event.seq : undefined
180
+ if (type === 'user/message') {
181
+ const data = event.data ?? {}
182
+ const sourceKind = data.source?.kind
183
+ if (sourceKind !== undefined && sourceKind !== 'user') continue
184
+ const text = textOfContent(data.content)
185
+ if (text === '') continue
186
+ current = {
187
+ index: turns.length + 1,
188
+ startSeq: seq,
189
+ endSeq: seq,
190
+ at: typeof event.time === 'number' ? event.time : (typeof data.time === 'number' ? data.time : undefined),
191
+ user: cleanLine(text, 220),
192
+ assistant: '',
193
+ }
194
+ turns.push(current)
195
+ continue
196
+ }
197
+ if (current === undefined) continue
198
+ if (seq !== undefined) current.endSeq = seq
199
+ if (type === 'assistant/message') {
200
+ const text = textOfContent(event.data?.message?.content)
201
+ if (text !== '' && current.assistant === '') current.assistant = cleanLine(text, 220)
202
+ }
203
+ }
204
+ return turns.map((turn) => {
205
+ const level = turn.startSeq === undefined
206
+ ? 0
207
+ : forkBoundaries.filter((seq) => seq >= turn.startSeq).length
208
+ return {
209
+ ...turn,
210
+ level,
211
+ rewindAt: turn.startSeq === undefined || turn.startSeq <= 0 ? undefined : turn.startSeq - 1,
212
+ }
213
+ })
214
+ }
215
+
216
+ /** Accept both a bare title string and the folded title snapshot record. */
217
+ function titleText(value) {
218
+ if (typeof value === 'string') return value
219
+ if (value !== null && typeof value === 'object' && typeof value.title === 'string') return value.title
220
+ return undefined
221
+ }
222
+
223
+ /** A short deterministic title when no model summary is available yet. */
224
+ function fallbackFromTranscript(title, turns) {
225
+ const first = turns.find((turn) => turn.role === 'user')?.text ?? ''
226
+ const topic = cleanLine(title !== undefined && title !== '' ? title : first, 40)
227
+ const summary = cleanLine(first, 240)
228
+ return {
229
+ topic: topic === '' ? 'Untitled topic' : topic,
230
+ summary,
231
+ open: [],
232
+ }
233
+ }
234
+
235
+ /** Take only model-provided strings; ignore numbers, objects, and arrays. */
236
+ function stringField(value) {
237
+ return typeof value === 'string' ? value : ''
238
+ }
239
+
240
+ /** Parse one JSON object out of model output, tolerating code fences and prose. */
241
+ function parseSummaryOutput(text, title) {
242
+ const raw = String(text ?? '').trim()
243
+ const start = raw.indexOf('{')
244
+ const end = raw.lastIndexOf('}')
245
+ let value
246
+ if (start !== -1 && end > start) {
247
+ try {
248
+ value = JSON.parse(raw.slice(start, end + 1))
249
+ } catch {
250
+ value = undefined
251
+ }
252
+ }
253
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return undefined
254
+ const topic = cleanLine(stringField(value.topic) !== '' ? value.topic : title ?? '', 40)
255
+ const summary = cleanLine(stringField(value.summary), 400)
256
+ if (topic === '' && summary === '') return undefined
257
+ const open = Array.isArray(value.open)
258
+ ? value.open
259
+ .map((item) => cleanLine(stringField(item), 120))
260
+ .filter((item) => item !== '')
261
+ .slice(0, 4)
262
+ : []
263
+ return { topic: topic === '' ? cleanLine(title ?? '', 40) : topic, summary, open }
264
+ }
265
+
266
+ /** Build the summarizer prompt from one branch's bounded transcript. */
267
+ function buildPrompt({ title, parentTitle, turns }) {
268
+ const payload = {
269
+ currentTitle: title ?? '',
270
+ parentTopic: parentTitle ?? '',
271
+ transcript: turns.map((turn) => ({ role: turn.role, text: turn.text })),
272
+ }
273
+ return [
274
+ 'You maintain the topic map of a long learning conversation for a mind-map view.',
275
+ 'You receive ONE branch of the conversation as JSON. Write a map label and a short summary for this branch.',
276
+ '',
277
+ 'Return exactly one JSON object, with no markdown and no code fence:',
278
+ '{"topic": "...", "summary": "...", "open": ["..."]}',
279
+ '',
280
+ 'Rules:',
281
+ '- "topic": a noun phrase of at most 20 characters naming this branch, in the language of the discussion.',
282
+ '- "summary": 2-3 complete sentences, at most 400 characters: what was discussed and where it landed. Do not invent facts.',
283
+ '- "open": up to 3 questions that remain unresolved and may deserve a subtopic; use [] when none.',
284
+ '- Summarize THIS branch only. The parent topic is context, not the subject.',
285
+ '',
286
+ JSON.stringify(payload),
287
+ ].join('\n')
288
+ }
289
+
290
+ /* ── summary cache ──────────────────────────────────────────────────────── */
291
+
292
+ class SummaryStore {
293
+ constructor(ctx, config) {
294
+ this.ctx = ctx
295
+ this.config = config
296
+ this.file = typeof config.dataFile === 'string' && config.dataFile !== '' ? config.dataFile : defaultDataFile()
297
+ this.summaries = Object.create(null)
298
+ this.inflight = new Map()
299
+ this.controllers = new Set()
300
+ this.writeChain = Promise.resolve()
301
+ this.ready = this.load()
302
+ this.disposed = false
303
+ }
304
+
305
+ async load() {
306
+ try {
307
+ const text = await readFile(this.file, 'utf8')
308
+ const parsed = JSON.parse(text)
309
+ if (parsed !== null && typeof parsed === 'object' && parsed.version === STORE_VERSION
310
+ && parsed.summaries !== null && typeof parsed.summaries === 'object') {
311
+ for (const [id, value] of Object.entries(parsed.summaries)) {
312
+ if (value !== null && typeof value === 'object' && typeof value.at === 'number') {
313
+ this.summaries[id] = value
314
+ }
315
+ }
316
+ }
317
+ } catch (error) {
318
+ if (error?.code !== 'ENOENT') warn(this.ctx, 'summary cache unreadable; starting empty', error)
319
+ }
320
+ }
321
+
322
+ persist() {
323
+ const payload = `${JSON.stringify({ version: STORE_VERSION, summaries: this.summaries })}\n`
324
+ this.writeChain = this.writeChain
325
+ .then(async () => {
326
+ await mkdir(dirname(this.file), { recursive: true })
327
+ const temporary = `${this.file}.${process.pid}.tmp`
328
+ await writeFile(temporary, payload, 'utf8')
329
+ await rename(temporary, this.file)
330
+ })
331
+ .catch((error) => warn(this.ctx, 'summary cache write failed', error))
332
+ return this.writeChain
333
+ }
334
+
335
+ cached(ids) {
336
+ const result = Object.create(null)
337
+ for (const id of ids) {
338
+ if (typeof id !== 'string' || id === '') continue
339
+ const value = this.summaries[id]
340
+ if (value !== undefined) result[id] = value
341
+ }
342
+ return result
343
+ }
344
+
345
+ close() {
346
+ this.disposed = true
347
+ for (const controller of this.controllers) controller.abort(new Error('mindmap plugin disposed'))
348
+ this.controllers.clear()
349
+ }
350
+
351
+ /**
352
+ * Summarize one logical session.
353
+ * @param {string} sessionId
354
+ * @param {{force?: boolean}} options
355
+ */
356
+ async summarize(sessionId, options = {}) {
357
+ if (this.disposed) throw new Error('mindmap plugin is disposed')
358
+ const running = this.inflight.get(sessionId)
359
+ if (running !== undefined) return running
360
+ const task = this.#summarize(sessionId, options).finally(() => {
361
+ this.inflight.delete(sessionId)
362
+ })
363
+ this.inflight.set(sessionId, task)
364
+ return task
365
+ }
366
+
367
+ async #summarize(sessionId, options) {
368
+ await this.ready
369
+ const surface = await this.ctx.sessionQuery.readSurface(sessionId)
370
+ const capturedThroughSeq = surface.capturedThroughSeq
371
+ const cached = this.summaries[sessionId]
372
+ if (options.force !== true && cached !== undefined && cached.seq === capturedThroughSeq) {
373
+ return { ...cached, cached: true }
374
+ }
375
+
376
+ const header = surface.session ?? {}
377
+ let title = titleText(header.title)
378
+ if (title === undefined || title === '') {
379
+ try {
380
+ title = titleText((await this.ctx.sessionQuery.readTitleSnapshot(sessionId))?.title)
381
+ } catch {
382
+ title = undefined
383
+ }
384
+ }
385
+ let parentTitle
386
+ if (typeof header.parentSession === 'string') {
387
+ try {
388
+ parentTitle = titleText(await this.ctx.sessionQuery.readTitle(header.parentSession))
389
+ } catch {
390
+ parentTitle = undefined
391
+ }
392
+ }
393
+
394
+ const { turns, route } = collectTranscript(surface, this.config.summaryMaxInputChars)
395
+ if (turns.length === 0) {
396
+ const empty = { seq: capturedThroughSeq, at: Date.now(), degraded: true, ...fallbackFromTranscript(title, turns), model: null }
397
+ this.summaries[sessionId] = empty
398
+ void this.persist()
399
+ return { ...empty, cached: false }
400
+ }
401
+
402
+ const provider = this.config.provider ?? route?.provider
403
+ const model = this.config.model ?? route?.model
404
+ if (provider === undefined || model === undefined) {
405
+ const degraded = {
406
+ seq: capturedThroughSeq,
407
+ at: Date.now(),
408
+ degraded: true,
409
+ ...fallbackFromTranscript(title, turns),
410
+ model: null,
411
+ reason: 'no-route',
412
+ }
413
+ this.summaries[sessionId] = degraded
414
+ void this.persist()
415
+ return { ...degraded, cached: false }
416
+ }
417
+
418
+ const controller = new AbortController()
419
+ this.controllers.add(controller)
420
+ const timeout = setTimeout(
421
+ () => controller.abort(new Error(`summary timed out after ${this.config.summaryTimeoutMs}ms`)),
422
+ this.config.summaryTimeoutMs,
423
+ )
424
+ try {
425
+ const prepared = await this.ctx.llm.prepareCall(
426
+ {
427
+ provider,
428
+ model,
429
+ messages: [{ role: 'user', content: [{ type: 'text', text: buildPrompt({ title, parentTitle, turns }) }] }],
430
+ },
431
+ controller.signal,
432
+ (controls) => ({ ...controls, maxTokens: this.config.summaryMaxOutputTokens }),
433
+ )
434
+ let output = ''
435
+ let finish
436
+ for await (const chunk of prepared.stream(prepared.config)) {
437
+ if (chunk.type === 'text-delta') output += chunk.text
438
+ else if (chunk.type === 'finish') finish = chunk.reason
439
+ }
440
+ if (finish?.kind !== 'stop') {
441
+ throw new Error(`summary model finished with ${finish?.kind ?? 'no finish reason'}`)
442
+ }
443
+ const parsed = parseSummaryOutput(output, title)
444
+ if (parsed === undefined) throw new Error('summary model returned no usable JSON')
445
+ const value = {
446
+ seq: capturedThroughSeq,
447
+ at: Date.now(),
448
+ topic: parsed.topic,
449
+ summary: parsed.summary,
450
+ open: parsed.open,
451
+ model: `${provider}/${model}`,
452
+ degraded: false,
453
+ }
454
+ this.summaries[sessionId] = value
455
+ void this.persist()
456
+ return { ...value, cached: false }
457
+ } catch (error) {
458
+ warn(this.ctx, `summary failed for ${sessionId}`, error)
459
+ const degraded = {
460
+ seq: capturedThroughSeq,
461
+ at: Date.now(),
462
+ ...fallbackFromTranscript(title, turns),
463
+ model: `${provider}/${model}`,
464
+ degraded: true,
465
+ reason: error instanceof Error ? error.message : String(error),
466
+ }
467
+ this.summaries[sessionId] = degraded
468
+ void this.persist()
469
+ return { ...degraded, cached: false }
470
+ } finally {
471
+ clearTimeout(timeout)
472
+ this.controllers.delete(controller)
473
+ }
474
+ }
475
+ }
476
+
477
+ /* ── HTTP helpers ──────────────────────────────────────────────────────── */
478
+
479
+ function sendJson(res, status, value) {
480
+ const body = `${JSON.stringify(value)}\n`
481
+ res.writeHead(status, {
482
+ 'content-type': 'application/json; charset=utf-8',
483
+ 'cache-control': 'no-store',
484
+ 'content-length': Buffer.byteLength(body),
485
+ })
486
+ res.end(body)
487
+ }
488
+
489
+ async function readJsonBody(req) {
490
+ let size = 0
491
+ const chunks = []
492
+ for await (const chunk of req) {
493
+ size += chunk.length
494
+ if (size > MAX_BODY_BYTES) {
495
+ const error = new Error('request body too large')
496
+ error.status = 413
497
+ throw error
498
+ }
499
+ chunks.push(chunk)
500
+ }
501
+ if (size === 0) return {}
502
+ try {
503
+ return JSON.parse(Buffer.concat(chunks).toString('utf8'))
504
+ } catch {
505
+ const error = new Error('request body is not valid JSON')
506
+ error.status = 400
507
+ throw error
508
+ }
509
+ }
510
+
511
+ /** Loopback / trusted-authority fence for the plugin routes. */
512
+ function isTrustedRequest(req, trustedHosts) {
513
+ const host = req.headers.host
514
+ if (typeof host !== 'string' || host === '') return false
515
+ let hostUrl
516
+ try {
517
+ hostUrl = new URL(`http://${host}`)
518
+ } catch {
519
+ return false
520
+ }
521
+ const hostname = hostUrl.hostname
522
+ const loopback = hostname === 'localhost' || hostname === '[::1]' || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(hostname)
523
+ if (!loopback && !trustedHosts.includes(host)) return false
524
+ const origin = req.headers.origin
525
+ // A desktop file:// page sends the opaque origin "null"; the Host fence above
526
+ // already binds the request to this process's own listener.
527
+ if (origin !== undefined && origin !== 'null') {
528
+ try {
529
+ if (new URL(origin).hostname !== hostname) return false
530
+ } catch {
531
+ return false
532
+ }
533
+ }
534
+ return true
535
+ }
536
+
537
+ /* ── topic tree for the model-facing tool ──────────────────────────────── */
538
+
539
+ async function buildTopicOutline(ctx, currentId, summaries, limit) {
540
+ const records = await ctx.sessionQuery.listSessions()
541
+ const byId = new Map()
542
+ for (const record of records) {
543
+ const header = record.header ?? record
544
+ if (typeof header.id === 'string') byId.set(header.id, header)
545
+ }
546
+ const ids = [...byId.keys()]
547
+ const titles = new Map()
548
+ try {
549
+ const results = await ctx.sessionQuery.readTitleSnapshots(ids)
550
+ for (const result of results) {
551
+ const text = result.status === 'fulfilled' ? titleText(result.value?.title) : undefined
552
+ if (text !== undefined && result.value?.session?.id !== undefined) titles.set(result.value.session.id, text)
553
+ }
554
+ } catch (error) {
555
+ warn(ctx, 'title batch failed', error)
556
+ }
557
+ const children = new Map()
558
+ const roots = []
559
+ for (const header of byId.values()) {
560
+ const parentId = header.parentSession
561
+ if (typeof parentId === 'string' && byId.has(parentId)) {
562
+ const list = children.get(parentId) ?? []
563
+ list.push(header)
564
+ children.set(parentId, list)
565
+ } else {
566
+ roots.push(header)
567
+ }
568
+ }
569
+ for (const list of children.values()) list.sort((a, b) => (a.createdAt ?? 0) - (b.createdAt ?? 0))
570
+
571
+ let rootId = currentId
572
+ const seen = new Set()
573
+ while (typeof byId.get(rootId)?.parentSession === 'string' && !seen.has(rootId)) {
574
+ seen.add(rootId)
575
+ rootId = byId.get(rootId).parentSession
576
+ }
577
+ const lines = []
578
+ const visit = (header, depth) => {
579
+ if (lines.length >= limit) return
580
+ const id = header.id
581
+ const label = titles.get(id) ?? id
582
+ const summary = summaries[id]
583
+ const marker = id === currentId ? ' ←(当前话题)' : ''
584
+ const topic = summary !== undefined && summary.topic !== '' ? `${label} 〔${summary.topic}〕` : label
585
+ const detail = summary !== undefined && summary.summary !== '' ? ` — ${cleanLine(summary.summary, 180)}` : ''
586
+ lines.push(`${' '.repeat(depth)}- ${topic}${detail}${marker}`)
587
+ for (const child of children.get(id) ?? []) visit(child, depth + 1)
588
+ }
589
+ const root = byId.get(rootId)
590
+ if (root !== undefined) visit(root, 0)
591
+ else for (const header of roots) visit(header, 0)
592
+ const truncated = lines.length >= limit ? `\n…(仅显示前 ${limit} 个话题)` : ''
593
+ return `话题树(/ 表示分支层级;〔〕是自动总结):\n${lines.join('\n')}${truncated}`
594
+ }
595
+
596
+ /* ── plugin ─────────────────────────────────────────────────────────────── */
597
+
598
+ export function apply(ctx, rawConfig) {
599
+ const config = resolveConfig(rawConfig)
600
+ const store = new SummaryStore(ctx, config)
601
+
602
+ const route = {
603
+ kind: 'prefix',
604
+ path: ROUTE_PREFIX,
605
+ handler: async (req, res) => {
606
+ if (!isTrustedRequest(req, config.trustedHosts)) {
607
+ sendJson(res, 403, { ok: false, error: { code: 'forbidden', message: 'request is not from this host' } })
608
+ return
609
+ }
610
+ const url = new URL(req.url ?? '/', 'http://dsh.internal')
611
+ const method = url.pathname.startsWith(`${ROUTE_PREFIX}/`)
612
+ ? url.pathname.slice(ROUTE_PREFIX.length + 1)
613
+ : undefined
614
+ if (method === undefined || method === '' || method.includes('/')) {
615
+ sendJson(res, 404, { ok: false, error: { code: 'not-found', message: 'unknown mindmap method' } })
616
+ return
617
+ }
618
+ try {
619
+ if (method === 'health' && req.method === 'GET') {
620
+ sendJson(res, 200, {
621
+ ok: true,
622
+ plugin: 'dsh-mindmap',
623
+ version: '0.8.0',
624
+ cached: Object.keys(store.summaries).length,
625
+ autoSummarize: config.autoSummarize,
626
+ active: store.inflight.size,
627
+ })
628
+ return
629
+ }
630
+ if (req.method !== 'POST') {
631
+ sendJson(res, 405, { ok: false, error: { code: 'method-error', message: 'POST required' } })
632
+ return
633
+ }
634
+ const payload = await readJsonBody(req)
635
+ if (method === 'summaries') {
636
+ const ids = Array.isArray(payload.ids)
637
+ ? payload.ids
638
+ .filter((id) => typeof id === 'string')
639
+ .slice(0, Math.min(MAX_IDS_PER_REQUEST, config.maxTopicsPerRequest))
640
+ : []
641
+ await store.ready
642
+ sendJson(res, 200, { ok: true, summaries: store.cached(ids) })
643
+ return
644
+ }
645
+ if (method === 'turns') {
646
+ const sessionId = typeof payload.sessionId === 'string' ? payload.sessionId : ''
647
+ if (sessionId === '') {
648
+ sendJson(res, 400, { ok: false, error: { code: 'bad-request', message: 'sessionId is required' } })
649
+ return
650
+ }
651
+ const lease = await ctx.sessionQuery.observeSession(sessionId)
652
+ try {
653
+ const events = lease.events
654
+ const forkBoundaries = collectForkBoundaries(events)
655
+ const outlineTurns = lease.projections?.turnOutline?.turns
656
+ const railOnly = payload.railOnly === true
657
+ sendJson(res, 200, {
658
+ ok: true,
659
+ capturedThroughSeq: events.at(-1)?.seq ?? null,
660
+ forkBoundaries,
661
+ railLevels: collectRailLevels(events, forkBoundaries, outlineTurns),
662
+ ...(railOnly ? {} : { turns: collectTurns({ events }, forkBoundaries) }),
663
+ })
664
+ } finally {
665
+ try {
666
+ lease[Symbol.dispose]?.()
667
+ } catch {
668
+ // The lease is already disposed; the read remains valid.
669
+ }
670
+ }
671
+ return
672
+ }
673
+ if (method === 'summarize') {
674
+ const sessionId = typeof payload.sessionId === 'string' ? payload.sessionId : ''
675
+ if (sessionId === '') {
676
+ sendJson(res, 400, { ok: false, error: { code: 'bad-request', message: 'sessionId is required' } })
677
+ return
678
+ }
679
+ if (config.autoSummarize !== true && payload.force !== true) {
680
+ sendJson(res, 200, {
681
+ ok: true,
682
+ summary: store.cached([sessionId])[sessionId] ?? null,
683
+ disabled: true,
684
+ })
685
+ return
686
+ }
687
+ const summary = await store.summarize(sessionId, { force: payload.force === true })
688
+ sendJson(res, 200, { ok: true, summary })
689
+ return
690
+ }
691
+ sendJson(res, 404, { ok: false, error: { code: 'not-found', message: `unknown mindmap method "${method}"` } })
692
+ } catch (error) {
693
+ const status = typeof error?.status === 'number' ? error.status : 500
694
+ if (status >= 500) warn(ctx, 'route failed', error)
695
+ sendJson(res, status, {
696
+ ok: false,
697
+ error: {
698
+ code: status === 400 ? 'bad-request' : status === 413 ? 'too-large' : 'internal',
699
+ message: error instanceof Error ? error.message : String(error),
700
+ },
701
+ })
702
+ }
703
+ },
704
+ }
705
+
706
+ ctx.effect(() => ctx.webServer.register(route), 'mindmap: /mindmap/api routes')
707
+ ctx.effect(() => () => store.close(), 'mindmap: summary store')
708
+
709
+ ctx.effect(() => ctx.tools.register(defineTool({
710
+ name: 'mindmap_topics',
711
+ description:
712
+ 'Read the topic tree of the current discussion: the current branch, its parent chain, sibling branches, and child subtopics, with the cached auto-summary of each. Read-only and cheap; use it when the user refers to another branch or asks what was already discussed elsewhere. It never loads those branches into this conversation.',
713
+ parameters: {},
714
+ output: {
715
+ schema: {
716
+ type: 'object',
717
+ additionalProperties: false,
718
+ properties: {
719
+ outline: { type: 'string', required: true, description: 'Indented topic tree with cached summaries.' },
720
+ },
721
+ },
722
+ render: (_args, value) => [{ type: 'text', text: value.outline }],
723
+ },
724
+ async execute(_args, exec) {
725
+ const session = exec.agent?.session
726
+ if (session === undefined) throw new Error('mindmap_topics requires an agent Session')
727
+ await store.ready
728
+ const outline = await buildTopicOutline(ctx, session.id, store.summaries, MAX_TREE_NODES)
729
+ return { outline }
730
+ },
731
+ })), 'mindmap: mindmap_topics tool')
732
+ }