@zhengxiantai/dsh-mindmap 0.0.0-stage → 0.7.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,697 @@
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
+ */
150
+ function collectTurns(surface) {
151
+ const turns = []
152
+ let current
153
+ for (const event of surface.events ?? []) {
154
+ const type = event.type ?? event.ty
155
+ const seq = Number.isSafeInteger(event.seq) ? event.seq : undefined
156
+ if (type === 'user/message') {
157
+ const data = event.data ?? {}
158
+ const sourceKind = data.source?.kind
159
+ if (sourceKind !== undefined && sourceKind !== 'user') continue
160
+ const text = textOfContent(data.content)
161
+ if (text === '') continue
162
+ current = {
163
+ index: turns.length + 1,
164
+ startSeq: seq,
165
+ endSeq: seq,
166
+ at: typeof event.time === 'number' ? event.time : (typeof data.time === 'number' ? data.time : undefined),
167
+ user: cleanLine(text, 220),
168
+ assistant: '',
169
+ }
170
+ turns.push(current)
171
+ continue
172
+ }
173
+ if (current === undefined) continue
174
+ if (seq !== undefined) current.endSeq = seq
175
+ if (type === 'assistant/message') {
176
+ const text = textOfContent(event.data?.message?.content)
177
+ if (text !== '' && current.assistant === '') current.assistant = cleanLine(text, 220)
178
+ }
179
+ }
180
+ return turns.map((turn) => ({
181
+ ...turn,
182
+ rewindAt: turn.startSeq === undefined || turn.startSeq <= 0 ? undefined : turn.startSeq - 1,
183
+ }))
184
+ }
185
+
186
+ /** Accept both a bare title string and the folded title snapshot record. */
187
+ function titleText(value) {
188
+ if (typeof value === 'string') return value
189
+ if (value !== null && typeof value === 'object' && typeof value.title === 'string') return value.title
190
+ return undefined
191
+ }
192
+
193
+ /** A short deterministic title when no model summary is available yet. */
194
+ function fallbackFromTranscript(title, turns) {
195
+ const first = turns.find((turn) => turn.role === 'user')?.text ?? ''
196
+ const topic = cleanLine(title !== undefined && title !== '' ? title : first, 40)
197
+ const summary = cleanLine(first, 240)
198
+ return {
199
+ topic: topic === '' ? 'Untitled topic' : topic,
200
+ summary,
201
+ open: [],
202
+ }
203
+ }
204
+
205
+ /** Take only model-provided strings; ignore numbers, objects, and arrays. */
206
+ function stringField(value) {
207
+ return typeof value === 'string' ? value : ''
208
+ }
209
+
210
+ /** Parse one JSON object out of model output, tolerating code fences and prose. */
211
+ function parseSummaryOutput(text, title) {
212
+ const raw = String(text ?? '').trim()
213
+ const start = raw.indexOf('{')
214
+ const end = raw.lastIndexOf('}')
215
+ let value
216
+ if (start !== -1 && end > start) {
217
+ try {
218
+ value = JSON.parse(raw.slice(start, end + 1))
219
+ } catch {
220
+ value = undefined
221
+ }
222
+ }
223
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return undefined
224
+ const topic = cleanLine(stringField(value.topic) !== '' ? value.topic : title ?? '', 40)
225
+ const summary = cleanLine(stringField(value.summary), 400)
226
+ if (topic === '' && summary === '') return undefined
227
+ const open = Array.isArray(value.open)
228
+ ? value.open
229
+ .map((item) => cleanLine(stringField(item), 120))
230
+ .filter((item) => item !== '')
231
+ .slice(0, 4)
232
+ : []
233
+ return { topic: topic === '' ? cleanLine(title ?? '', 40) : topic, summary, open }
234
+ }
235
+
236
+ /** Build the summarizer prompt from one branch's bounded transcript. */
237
+ function buildPrompt({ title, parentTitle, turns }) {
238
+ const payload = {
239
+ currentTitle: title ?? '',
240
+ parentTopic: parentTitle ?? '',
241
+ transcript: turns.map((turn) => ({ role: turn.role, text: turn.text })),
242
+ }
243
+ return [
244
+ 'You maintain the topic map of a long learning conversation for a mind-map view.',
245
+ 'You receive ONE branch of the conversation as JSON. Write a map label and a short summary for this branch.',
246
+ '',
247
+ 'Return exactly one JSON object, with no markdown and no code fence:',
248
+ '{"topic": "...", "summary": "...", "open": ["..."]}',
249
+ '',
250
+ 'Rules:',
251
+ '- "topic": a noun phrase of at most 20 characters naming this branch, in the language of the discussion.',
252
+ '- "summary": 2-3 complete sentences, at most 400 characters: what was discussed and where it landed. Do not invent facts.',
253
+ '- "open": up to 3 questions that remain unresolved and may deserve a subtopic; use [] when none.',
254
+ '- Summarize THIS branch only. The parent topic is context, not the subject.',
255
+ '',
256
+ JSON.stringify(payload),
257
+ ].join('\n')
258
+ }
259
+
260
+ /* ── summary cache ──────────────────────────────────────────────────────── */
261
+
262
+ class SummaryStore {
263
+ constructor(ctx, config) {
264
+ this.ctx = ctx
265
+ this.config = config
266
+ this.file = typeof config.dataFile === 'string' && config.dataFile !== '' ? config.dataFile : defaultDataFile()
267
+ this.summaries = Object.create(null)
268
+ this.inflight = new Map()
269
+ this.controllers = new Set()
270
+ this.writeChain = Promise.resolve()
271
+ this.ready = this.load()
272
+ this.disposed = false
273
+ }
274
+
275
+ async load() {
276
+ try {
277
+ const text = await readFile(this.file, 'utf8')
278
+ const parsed = JSON.parse(text)
279
+ if (parsed !== null && typeof parsed === 'object' && parsed.version === STORE_VERSION
280
+ && parsed.summaries !== null && typeof parsed.summaries === 'object') {
281
+ for (const [id, value] of Object.entries(parsed.summaries)) {
282
+ if (value !== null && typeof value === 'object' && typeof value.at === 'number') {
283
+ this.summaries[id] = value
284
+ }
285
+ }
286
+ }
287
+ } catch (error) {
288
+ if (error?.code !== 'ENOENT') warn(this.ctx, 'summary cache unreadable; starting empty', error)
289
+ }
290
+ }
291
+
292
+ persist() {
293
+ const payload = `${JSON.stringify({ version: STORE_VERSION, summaries: this.summaries })}\n`
294
+ this.writeChain = this.writeChain
295
+ .then(async () => {
296
+ await mkdir(dirname(this.file), { recursive: true })
297
+ const temporary = `${this.file}.${process.pid}.tmp`
298
+ await writeFile(temporary, payload, 'utf8')
299
+ await rename(temporary, this.file)
300
+ })
301
+ .catch((error) => warn(this.ctx, 'summary cache write failed', error))
302
+ return this.writeChain
303
+ }
304
+
305
+ cached(ids) {
306
+ const result = Object.create(null)
307
+ for (const id of ids) {
308
+ if (typeof id !== 'string' || id === '') continue
309
+ const value = this.summaries[id]
310
+ if (value !== undefined) result[id] = value
311
+ }
312
+ return result
313
+ }
314
+
315
+ close() {
316
+ this.disposed = true
317
+ for (const controller of this.controllers) controller.abort(new Error('mindmap plugin disposed'))
318
+ this.controllers.clear()
319
+ }
320
+
321
+ /**
322
+ * Summarize one logical session.
323
+ * @param {string} sessionId
324
+ * @param {{force?: boolean}} options
325
+ */
326
+ async summarize(sessionId, options = {}) {
327
+ if (this.disposed) throw new Error('mindmap plugin is disposed')
328
+ const running = this.inflight.get(sessionId)
329
+ if (running !== undefined) return running
330
+ const task = this.#summarize(sessionId, options).finally(() => {
331
+ this.inflight.delete(sessionId)
332
+ })
333
+ this.inflight.set(sessionId, task)
334
+ return task
335
+ }
336
+
337
+ async #summarize(sessionId, options) {
338
+ await this.ready
339
+ const surface = await this.ctx.sessionQuery.readSurface(sessionId)
340
+ const capturedThroughSeq = surface.capturedThroughSeq
341
+ const cached = this.summaries[sessionId]
342
+ if (options.force !== true && cached !== undefined && cached.seq === capturedThroughSeq) {
343
+ return { ...cached, cached: true }
344
+ }
345
+
346
+ const header = surface.session ?? {}
347
+ let title = titleText(header.title)
348
+ if (title === undefined || title === '') {
349
+ try {
350
+ title = titleText((await this.ctx.sessionQuery.readTitleSnapshot(sessionId))?.title)
351
+ } catch {
352
+ title = undefined
353
+ }
354
+ }
355
+ let parentTitle
356
+ if (typeof header.parentSession === 'string') {
357
+ try {
358
+ parentTitle = titleText(await this.ctx.sessionQuery.readTitle(header.parentSession))
359
+ } catch {
360
+ parentTitle = undefined
361
+ }
362
+ }
363
+
364
+ const { turns, route } = collectTranscript(surface, this.config.summaryMaxInputChars)
365
+ if (turns.length === 0) {
366
+ const empty = { seq: capturedThroughSeq, at: Date.now(), degraded: true, ...fallbackFromTranscript(title, turns), model: null }
367
+ this.summaries[sessionId] = empty
368
+ void this.persist()
369
+ return { ...empty, cached: false }
370
+ }
371
+
372
+ const provider = this.config.provider ?? route?.provider
373
+ const model = this.config.model ?? route?.model
374
+ if (provider === undefined || model === undefined) {
375
+ const degraded = {
376
+ seq: capturedThroughSeq,
377
+ at: Date.now(),
378
+ degraded: true,
379
+ ...fallbackFromTranscript(title, turns),
380
+ model: null,
381
+ reason: 'no-route',
382
+ }
383
+ this.summaries[sessionId] = degraded
384
+ void this.persist()
385
+ return { ...degraded, cached: false }
386
+ }
387
+
388
+ const controller = new AbortController()
389
+ this.controllers.add(controller)
390
+ const timeout = setTimeout(
391
+ () => controller.abort(new Error(`summary timed out after ${this.config.summaryTimeoutMs}ms`)),
392
+ this.config.summaryTimeoutMs,
393
+ )
394
+ try {
395
+ const prepared = await this.ctx.llm.prepareCall(
396
+ {
397
+ provider,
398
+ model,
399
+ messages: [{ role: 'user', content: [{ type: 'text', text: buildPrompt({ title, parentTitle, turns }) }] }],
400
+ },
401
+ controller.signal,
402
+ (controls) => ({ ...controls, maxTokens: this.config.summaryMaxOutputTokens }),
403
+ )
404
+ let output = ''
405
+ let finish
406
+ for await (const chunk of prepared.stream(prepared.config)) {
407
+ if (chunk.type === 'text-delta') output += chunk.text
408
+ else if (chunk.type === 'finish') finish = chunk.reason
409
+ }
410
+ if (finish?.kind !== 'stop') {
411
+ throw new Error(`summary model finished with ${finish?.kind ?? 'no finish reason'}`)
412
+ }
413
+ const parsed = parseSummaryOutput(output, title)
414
+ if (parsed === undefined) throw new Error('summary model returned no usable JSON')
415
+ const value = {
416
+ seq: capturedThroughSeq,
417
+ at: Date.now(),
418
+ topic: parsed.topic,
419
+ summary: parsed.summary,
420
+ open: parsed.open,
421
+ model: `${provider}/${model}`,
422
+ degraded: false,
423
+ }
424
+ this.summaries[sessionId] = value
425
+ void this.persist()
426
+ return { ...value, cached: false }
427
+ } catch (error) {
428
+ warn(this.ctx, `summary failed for ${sessionId}`, error)
429
+ const degraded = {
430
+ seq: capturedThroughSeq,
431
+ at: Date.now(),
432
+ ...fallbackFromTranscript(title, turns),
433
+ model: `${provider}/${model}`,
434
+ degraded: true,
435
+ reason: error instanceof Error ? error.message : String(error),
436
+ }
437
+ this.summaries[sessionId] = degraded
438
+ void this.persist()
439
+ return { ...degraded, cached: false }
440
+ } finally {
441
+ clearTimeout(timeout)
442
+ this.controllers.delete(controller)
443
+ }
444
+ }
445
+ }
446
+
447
+ /* ── HTTP helpers ──────────────────────────────────────────────────────── */
448
+
449
+ function sendJson(res, status, value) {
450
+ const body = `${JSON.stringify(value)}\n`
451
+ res.writeHead(status, {
452
+ 'content-type': 'application/json; charset=utf-8',
453
+ 'cache-control': 'no-store',
454
+ 'content-length': Buffer.byteLength(body),
455
+ })
456
+ res.end(body)
457
+ }
458
+
459
+ async function readJsonBody(req) {
460
+ let size = 0
461
+ const chunks = []
462
+ for await (const chunk of req) {
463
+ size += chunk.length
464
+ if (size > MAX_BODY_BYTES) {
465
+ const error = new Error('request body too large')
466
+ error.status = 413
467
+ throw error
468
+ }
469
+ chunks.push(chunk)
470
+ }
471
+ if (size === 0) return {}
472
+ try {
473
+ return JSON.parse(Buffer.concat(chunks).toString('utf8'))
474
+ } catch {
475
+ const error = new Error('request body is not valid JSON')
476
+ error.status = 400
477
+ throw error
478
+ }
479
+ }
480
+
481
+ /** Loopback / trusted-authority fence for the plugin routes. */
482
+ function isTrustedRequest(req, trustedHosts) {
483
+ const host = req.headers.host
484
+ if (typeof host !== 'string' || host === '') return false
485
+ let hostUrl
486
+ try {
487
+ hostUrl = new URL(`http://${host}`)
488
+ } catch {
489
+ return false
490
+ }
491
+ const hostname = hostUrl.hostname
492
+ const loopback = hostname === 'localhost' || hostname === '[::1]' || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(hostname)
493
+ if (!loopback && !trustedHosts.includes(host)) return false
494
+ const origin = req.headers.origin
495
+ // A desktop file:// page sends the opaque origin "null"; the Host fence above
496
+ // already binds the request to this process's own listener.
497
+ if (origin !== undefined && origin !== 'null') {
498
+ try {
499
+ if (new URL(origin).hostname !== hostname) return false
500
+ } catch {
501
+ return false
502
+ }
503
+ }
504
+ return true
505
+ }
506
+
507
+ /* ── topic tree for the model-facing tool ──────────────────────────────── */
508
+
509
+ async function buildTopicOutline(ctx, currentId, summaries, limit) {
510
+ const records = await ctx.sessionQuery.listSessions()
511
+ const byId = new Map()
512
+ for (const record of records) {
513
+ const header = record.header ?? record
514
+ if (typeof header.id === 'string') byId.set(header.id, header)
515
+ }
516
+ const ids = [...byId.keys()]
517
+ const titles = new Map()
518
+ try {
519
+ const results = await ctx.sessionQuery.readTitleSnapshots(ids)
520
+ for (const result of results) {
521
+ const text = result.status === 'fulfilled' ? titleText(result.value?.title) : undefined
522
+ if (text !== undefined && result.value?.session?.id !== undefined) titles.set(result.value.session.id, text)
523
+ }
524
+ } catch (error) {
525
+ warn(ctx, 'title batch failed', error)
526
+ }
527
+ const children = new Map()
528
+ const roots = []
529
+ for (const header of byId.values()) {
530
+ const parentId = header.parentSession
531
+ if (typeof parentId === 'string' && byId.has(parentId)) {
532
+ const list = children.get(parentId) ?? []
533
+ list.push(header)
534
+ children.set(parentId, list)
535
+ } else {
536
+ roots.push(header)
537
+ }
538
+ }
539
+ for (const list of children.values()) list.sort((a, b) => (a.createdAt ?? 0) - (b.createdAt ?? 0))
540
+
541
+ let rootId = currentId
542
+ const seen = new Set()
543
+ while (typeof byId.get(rootId)?.parentSession === 'string' && !seen.has(rootId)) {
544
+ seen.add(rootId)
545
+ rootId = byId.get(rootId).parentSession
546
+ }
547
+ const lines = []
548
+ const visit = (header, depth) => {
549
+ if (lines.length >= limit) return
550
+ const id = header.id
551
+ const label = titles.get(id) ?? id
552
+ const summary = summaries[id]
553
+ const marker = id === currentId ? ' ←(当前话题)' : ''
554
+ const topic = summary !== undefined && summary.topic !== '' ? `${label} 〔${summary.topic}〕` : label
555
+ const detail = summary !== undefined && summary.summary !== '' ? ` — ${cleanLine(summary.summary, 180)}` : ''
556
+ lines.push(`${' '.repeat(depth)}- ${topic}${detail}${marker}`)
557
+ for (const child of children.get(id) ?? []) visit(child, depth + 1)
558
+ }
559
+ const root = byId.get(rootId)
560
+ if (root !== undefined) visit(root, 0)
561
+ else for (const header of roots) visit(header, 0)
562
+ const truncated = lines.length >= limit ? `\n…(仅显示前 ${limit} 个话题)` : ''
563
+ return `话题树(/ 表示分支层级;〔〕是自动总结):\n${lines.join('\n')}${truncated}`
564
+ }
565
+
566
+ /* ── plugin ─────────────────────────────────────────────────────────────── */
567
+
568
+ export function apply(ctx, rawConfig) {
569
+ const config = resolveConfig(rawConfig)
570
+ const store = new SummaryStore(ctx, config)
571
+
572
+ const route = {
573
+ kind: 'prefix',
574
+ path: ROUTE_PREFIX,
575
+ handler: async (req, res) => {
576
+ if (!isTrustedRequest(req, config.trustedHosts)) {
577
+ sendJson(res, 403, { ok: false, error: { code: 'forbidden', message: 'request is not from this host' } })
578
+ return
579
+ }
580
+ const url = new URL(req.url ?? '/', 'http://dsh.internal')
581
+ const method = url.pathname.startsWith(`${ROUTE_PREFIX}/`)
582
+ ? url.pathname.slice(ROUTE_PREFIX.length + 1)
583
+ : undefined
584
+ if (method === undefined || method === '' || method.includes('/')) {
585
+ sendJson(res, 404, { ok: false, error: { code: 'not-found', message: 'unknown mindmap method' } })
586
+ return
587
+ }
588
+ try {
589
+ if (method === 'health' && req.method === 'GET') {
590
+ sendJson(res, 200, {
591
+ ok: true,
592
+ plugin: 'dsh-mindmap',
593
+ version: '0.7.0',
594
+ cached: Object.keys(store.summaries).length,
595
+ autoSummarize: config.autoSummarize,
596
+ active: store.inflight.size,
597
+ })
598
+ return
599
+ }
600
+ if (req.method !== 'POST') {
601
+ sendJson(res, 405, { ok: false, error: { code: 'method-error', message: 'POST required' } })
602
+ return
603
+ }
604
+ const payload = await readJsonBody(req)
605
+ if (method === 'summaries') {
606
+ const ids = Array.isArray(payload.ids)
607
+ ? payload.ids
608
+ .filter((id) => typeof id === 'string')
609
+ .slice(0, Math.min(MAX_IDS_PER_REQUEST, config.maxTopicsPerRequest))
610
+ : []
611
+ await store.ready
612
+ sendJson(res, 200, { ok: true, summaries: store.cached(ids) })
613
+ return
614
+ }
615
+ if (method === 'turns') {
616
+ const sessionId = typeof payload.sessionId === 'string' ? payload.sessionId : ''
617
+ if (sessionId === '') {
618
+ sendJson(res, 400, { ok: false, error: { code: 'bad-request', message: 'sessionId is required' } })
619
+ return
620
+ }
621
+ const lease = await ctx.sessionQuery.observeSession(sessionId)
622
+ try {
623
+ const events = lease.events
624
+ sendJson(res, 200, {
625
+ ok: true,
626
+ capturedThroughSeq: events.at(-1)?.seq ?? null,
627
+ turns: collectTurns({ events }),
628
+ })
629
+ } finally {
630
+ try {
631
+ lease[Symbol.dispose]?.()
632
+ } catch {
633
+ // The lease is already disposed; the read remains valid.
634
+ }
635
+ }
636
+ return
637
+ }
638
+ if (method === 'summarize') {
639
+ const sessionId = typeof payload.sessionId === 'string' ? payload.sessionId : ''
640
+ if (sessionId === '') {
641
+ sendJson(res, 400, { ok: false, error: { code: 'bad-request', message: 'sessionId is required' } })
642
+ return
643
+ }
644
+ if (config.autoSummarize !== true && payload.force !== true) {
645
+ sendJson(res, 200, {
646
+ ok: true,
647
+ summary: store.cached([sessionId])[sessionId] ?? null,
648
+ disabled: true,
649
+ })
650
+ return
651
+ }
652
+ const summary = await store.summarize(sessionId, { force: payload.force === true })
653
+ sendJson(res, 200, { ok: true, summary })
654
+ return
655
+ }
656
+ sendJson(res, 404, { ok: false, error: { code: 'not-found', message: `unknown mindmap method "${method}"` } })
657
+ } catch (error) {
658
+ const status = typeof error?.status === 'number' ? error.status : 500
659
+ if (status >= 500) warn(ctx, 'route failed', error)
660
+ sendJson(res, status, {
661
+ ok: false,
662
+ error: {
663
+ code: status === 400 ? 'bad-request' : status === 413 ? 'too-large' : 'internal',
664
+ message: error instanceof Error ? error.message : String(error),
665
+ },
666
+ })
667
+ }
668
+ },
669
+ }
670
+
671
+ ctx.effect(() => ctx.webServer.register(route), 'mindmap: /mindmap/api routes')
672
+ ctx.effect(() => () => store.close(), 'mindmap: summary store')
673
+
674
+ ctx.effect(() => ctx.tools.register(defineTool({
675
+ name: 'mindmap_topics',
676
+ description:
677
+ '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.',
678
+ parameters: {},
679
+ output: {
680
+ schema: {
681
+ type: 'object',
682
+ additionalProperties: false,
683
+ properties: {
684
+ outline: { type: 'string', required: true, description: 'Indented topic tree with cached summaries.' },
685
+ },
686
+ },
687
+ render: (_args, value) => [{ type: 'text', text: value.outline }],
688
+ },
689
+ async execute(_args, exec) {
690
+ const session = exec.agent?.session
691
+ if (session === undefined) throw new Error('mindmap_topics requires an agent Session')
692
+ await store.ready
693
+ const outline = await buildTopicOutline(ctx, session.id, store.summaries, MAX_TREE_NODES)
694
+ return { outline }
695
+ },
696
+ })), 'mindmap: mindmap_topics tool')
697
+ }