dsh-mindmark 0.3.0 → 0.4.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/index.js CHANGED
@@ -1,566 +1,629 @@
1
- // dsh-mindmark — Host half.
2
- //
3
- // Registers:
4
- // • the read/write HTTP API the Web client uses to store annotations and the
5
- // per-session injection mode (`/plugins/dsh-mindmark/annotations`);
6
- // • `annotations`, the model-facing tool that lists / resolves / reopens /
7
- // deletes the annotations of the current conversation;
8
- // • an `agent/pre-step` listener that, at the start of each turn, enters one
9
- // user-role context message carrying the pending annotations (so the model
10
- // sees "the answer as the user marked it up"), logged like every other
11
- // model-visible input;
12
- // • a short protocol section in the system prompt while annotations are pending.
13
- //
14
- // No DSH package is imported on purpose: the plugin must boot from a linked
15
- // profile directory whose loader can resolve only Node builtins.
16
-
17
- import {
18
- AnnotationStore,
19
- AnnotateInputError,
20
- ANNOTATION_STYLES,
21
- INJECTION_MODES,
22
- resolveStatePath,
23
- validateMode,
24
- validateSessionId,
25
- } from './src/store.js'
26
- import {
27
- buildInjection,
28
- buildProtocolSection,
29
- SOURCE_KIND,
30
- STYLE_META,
31
- TOOL_NAME,
32
- } from './src/inject.js'
33
- import { LessonStore, resolveInstructionsPath } from './src/lessons.js'
34
-
35
- export const name = 'mindmark'
36
- export const inject = ['tools', 'systemPrompt', 'webServer']
37
-
38
- export const ROUTE = '/plugins/dsh-mindmark/annotations'
39
- export { TOOL_NAME }
40
- export const SECTION_NAME = 'tool:annotations'
41
- export const SECTION_ORDER = 9100
42
- /** How many turns one annotation is re-injected before it settles on its own. */
43
- export const DEFAULT_MAX_INJECTIONS = 3
44
-
45
- const MAX_BODY_BYTES = 64 * 1024
46
- // Plain-browser loopback origins and the Desktop shell's own boundary. The
47
- // Desktop shell proxies the page's request without an Origin header, so an
48
- // absent Origin is accepted here exactly like the shipped routes do.
49
- const LOOPBACK_ORIGIN_RE = /^https?:\/\/(?:127\.0\.0\.1|localhost|\[::1\])(?::\d+)?$/i
50
-
51
- function styleLabel(style) {
52
- return STYLE_META[style]?.label ?? '标注'
53
- }
54
-
55
- // ------------------------------------------------------------------- HTTP
56
-
57
- function corsHeaders(req) {
58
- const origin = req?.headers?.origin
59
- if (typeof origin !== 'string') return {}
60
- if (origin === 'null' || LOOPBACK_ORIGIN_RE.test(origin)) {
61
- return {
62
- 'access-control-allow-origin': origin,
63
- 'access-control-allow-methods': 'GET, POST, OPTIONS',
64
- 'access-control-allow-headers': 'content-type',
65
- 'access-control-max-age': '600',
66
- vary: 'Origin',
67
- }
68
- }
69
- return {}
70
- }
71
-
72
- function originAllowed(req) {
73
- const origin = req?.headers?.origin
74
- if (typeof origin !== 'string' || origin === '') return true
75
- if (origin === 'null' || origin === 'dsh-app://app') return true
76
- if (LOOPBACK_ORIGIN_RE.test(origin)) return true
77
- const host = req?.headers?.host
78
- if (typeof host === 'string' && (origin === `http://${host}` || origin === `https://${host}`)) {
79
- return true
80
- }
81
- return false
82
- }
83
-
84
- function sendJson(req, res, status, value) {
85
- const payload = JSON.stringify(value)
86
- res.writeHead(status, {
87
- 'content-type': 'application/json; charset=utf-8',
88
- 'cache-control': 'no-store',
89
- 'content-length': Buffer.byteLength(payload),
90
- 'x-content-type-options': 'nosniff',
91
- ...corsHeaders(req),
92
- })
93
- res.end(payload)
94
- }
95
-
96
- function sendError(req, res, status, code, message) {
97
- sendJson(req, res, status, { ok: false, error: { code, message } })
98
- }
99
-
100
- async function readJsonBody(req) {
101
- const chunks = []
102
- let size = 0
103
- for await (const chunk of req) {
104
- const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
105
- size += buffer.length
106
- if (size > MAX_BODY_BYTES) {
107
- const error = new Error('request-too-large')
108
- error.code = 'request-too-large'
109
- throw error
110
- }
111
- chunks.push(buffer)
112
- }
113
- if (size === 0) {
114
- const error = new Error('empty-body')
115
- error.code = 'invalid-json'
116
- throw error
117
- }
118
- try {
119
- return JSON.parse(Buffer.concat(chunks).toString('utf8'))
120
- } catch {
121
- const error = new Error('invalid-json')
122
- error.code = 'invalid-json'
123
- throw error
124
- }
125
- }
126
-
127
- function sessionIdFromUrl(req) {
128
- try {
129
- const url = new URL(typeof req?.url === 'string' ? req.url : '', 'http://127.0.0.1')
130
- return url.searchParams.get('sessionId') ?? undefined
131
- } catch {
132
- return undefined
133
- }
134
- }
135
-
136
- function sessionPayload(store, sessionId, extra = {}) {
137
- const lessons = typeof store.lessons?.list === 'function' ? store.lessons.list() : []
138
- return { ok: true, annotations: store.list(sessionId), mode: store.getMode(sessionId), lessons, ...extra }
139
- }
140
-
141
- function stringIds(ids, code, message) {
142
- if (ids === undefined || ids === null) return []
143
- if (!Array.isArray(ids) || ids.some(id => typeof id !== 'string')) {
144
- throw new AnnotateInputError(code, message)
145
- }
146
- return ids
147
- }
148
-
149
- /**
150
- * Build the annotations HTTP handler. Exported for tests; `apply` registers it
151
- * as-is. `deps = { store, logger }`.
152
- */
153
- export function createAnnotationsHandler(deps) {
154
- const store = deps?.store
155
- const logger = deps?.logger
156
- if (!store || typeof store.list !== 'function') {
157
- throw new TypeError('createAnnotationsHandler requires deps.store')
158
- }
159
-
160
- return async function annotationsHandler(req, res) {
161
- try {
162
- if (req?.method === 'OPTIONS') {
163
- res.writeHead(204, corsHeaders(req))
164
- res.end()
165
- return
166
- }
167
- if (!originAllowed(req)) {
168
- sendError(req, res, 403, 'forbidden', '请求来源不被允许。')
169
- return
170
- }
171
-
172
- if (req?.method === 'GET') {
173
- const sessionId = sessionIdFromUrl(req)
174
- let key
175
- try {
176
- key = validateSessionId(sessionId)
177
- } catch {
178
- sendError(req, res, 400, 'invalid-session-id', '会话 ID 无效。')
179
- return
180
- }
181
- sendJson(req, res, 200, sessionPayload(store, key))
182
- return
183
- }
184
-
185
- if (req?.method !== 'POST') {
186
- sendError(req, res, 405, 'method-not-allowed', '只支持 GET 和 POST。')
187
- return
188
- }
189
-
190
- const contentType = req.headers?.['content-type']
191
- if (typeof contentType !== 'string' || !contentType.toLowerCase().startsWith('application/json')) {
192
- sendError(req, res, 415, 'unsupported-media-type', '请使用 application/json。')
193
- return
194
- }
195
-
196
- let body
197
- try {
198
- body = await readJsonBody(req)
199
- } catch (error) {
200
- const tooLarge = error?.code === 'request-too-large'
201
- if (tooLarge) {
202
- sendError(req, res, 413, 'request-too-large', '请求过大。')
203
- } else {
204
- sendError(req, res, 400, 'invalid-json', '请求体不是有效 JSON。')
205
- }
206
- return
207
- }
208
- if (body === null || typeof body !== 'object' || Array.isArray(body)) {
209
- sendError(req, res, 400, 'invalid-body', '请求体必须是 JSON 对象。')
210
- return
211
- }
212
-
213
- const sessionId = validateSessionId(body.sessionId)
214
- const action = body.action
215
-
216
- if (action === undefined || action === null || action === 'list') {
217
- sendJson(req, res, 200, sessionPayload(store, sessionId))
218
- return
219
- }
220
- if (action === 'add') {
221
- const result = store.add(sessionId, body.annotation, body.message)
222
- sendJson(req, res, 200, sessionPayload(store, sessionId, { added: result.deduped !== true }))
223
- return
224
- }
225
- if (action === 'remove') {
226
- const ids = stringIds(body.ids, 'invalid-ids', 'ids 必须是标注 id 的字符串数组。')
227
- if (ids.length === 0) throw new AnnotateInputError('invalid-ids', 'ids 必须是标注 id 的字符串数组。')
228
- const removed = store.remove(sessionId, ids)
229
- sendJson(req, res, 200, sessionPayload(store, sessionId, { removed }))
230
- return
231
- }
232
- if (action === 'clear') {
233
- const removed = store.clear(sessionId)
234
- sendJson(req, res, 200, sessionPayload(store, sessionId, { removed }))
235
- return
236
- }
237
- if (action === 'resolve' || action === 'reopen') {
238
- const ids = stringIds(body.ids, 'invalid-ids', 'ids 必须是标注 id 的字符串数组。')
239
- const changed = action === 'resolve' ? store.resolve(sessionId, ids, { by: 'user' }) : store.reopen(sessionId, ids)
240
- sendJson(req, res, 200, sessionPayload(store, sessionId, { changed }))
241
- return
242
- }
243
- if (action === 'set-mode') {
244
- store.setMode(sessionId, body.mode)
245
- sendJson(req, res, 200, sessionPayload(store, sessionId))
246
- return
247
- }
248
- if (action === 'forget-lesson') {
249
- const targets = stringIds(body.lessons, 'invalid-lessons', 'lessons 必须是字符串数组。')
250
- const removed = store.lessons ? store.lessons.remove(targets) : []
251
- sendJson(req, res, 200, sessionPayload(store, sessionId, { removed: removed.length }))
252
- return
253
- }
254
- throw new AnnotateInputError(
255
- 'invalid-action',
256
- '未知的 action,只支持 list、add、remove、clear、resolve、reopen、set-mode、forget-lesson。',
257
- )
258
- } catch (error) {
259
- if (error instanceof AnnotateInputError) {
260
- try {
261
- sendError(req, res, 400, error.code, error.message)
262
- } catch {
263
- // The response is already gone; nothing left to report.
264
- }
265
- return
266
- }
267
- logger?.warn?.(`dsh-mindmark: annotation request failed: ${String(error)}`)
268
- try {
269
- sendError(req, res, 500, 'internal', '标注读写失败。')
270
- } catch {
271
- // The response is already gone; nothing left to report.
272
- }
273
- }
274
- }
275
- }
276
-
277
- // --------------------------------------------------------------- the tool
278
-
279
- const TIMESTAMP_PAD = number => String(number).padStart(2, '0')
280
-
281
- /** Local `YYYY-MM-DD HH:MM`; '' when the timestamp is missing/unparseable. */
282
- export function formatLocalTimestamp(value) {
283
- if (typeof value !== 'string' || value === '') return ''
284
- const date = new Date(value)
285
- if (Number.isNaN(date.getTime())) return ''
286
- return (
287
- `${date.getFullYear()}-${TIMESTAMP_PAD(date.getMonth() + 1)}-${TIMESTAMP_PAD(date.getDate())}` +
288
- ` ${TIMESTAMP_PAD(date.getHours())}:${TIMESTAMP_PAD(date.getMinutes())}`
289
- )
290
- }
291
-
292
- const ANNOTATION_OUTPUT_ITEM = {
293
- type: 'object',
294
- additionalProperties: true,
295
- properties: {
296
- id: { type: 'string' },
297
- style: { type: 'string', enum: ANNOTATION_STYLES },
298
- quote: { type: 'string' },
299
- note: { type: 'string' },
300
- status: { type: 'string', enum: ['pending', 'resolved'] },
301
- createdAt: { type: 'string' },
302
- },
303
- required: ['id', 'style', 'quote', 'status', 'createdAt'],
304
- }
305
-
306
- const TOOL_OUTPUT = {
307
- type: 'object',
308
- additionalProperties: false,
309
- properties: {
310
- action: { type: 'string' },
311
- mode: { type: 'string', enum: INJECTION_MODES },
312
- total: { type: 'integer' },
313
- pending: { type: 'integer' },
314
- changed: { type: 'array', items: { type: 'string' } },
315
- annotations: { type: 'array', items: ANNOTATION_OUTPUT_ITEM },
316
- lessons: { type: 'array', items: { type: 'string' } },
317
- },
318
- required: ['action', 'mode', 'total', 'pending', 'changed', 'annotations', 'lessons'],
319
- }
320
-
321
- function renderToolResult(_args, value) {
322
- const annotations = Array.isArray(value?.annotations) ? value.annotations : []
323
- const changed = Array.isArray(value?.changed) ? value.changed : []
324
- const lines = []
325
- const action = value?.action ?? 'list'
326
- if (action === 'resolve') lines.push(changed.length === 0 ? '没有需要确认的标注。' : `已确认处理 ${changed.length} 条标注。`)
327
- if (action === 'reopen') lines.push(changed.length === 0 ? '没有标注被重新打开。' : `已重新打开 ${changed.length} 条标注。`)
328
- if (action === 'delete') lines.push(changed.length === 0 ? '没有标注被删除。' : `已删除 ${changed.length} 条标注。`)
329
- if (action === 'clear') lines.push(`已清空 ${changed.length} 条标注。`)
330
- if (action === 'set-mode') lines.push(`注入模式已改为 ${value?.mode === 'full' ? '完整' : '精简'}。`)
331
- const lessons = Array.isArray(value?.lessons) ? value.lessons : []
332
- if (action === 'distill') {
333
- lines.push(changed.length === 0 ? '没有新的偏好被沉淀(可能已存在)。' : `已沉淀 ${changed.length} 条长期偏好到用户全局 AGENTS.md,新对话会自动遵守。`)
334
- }
335
- if (action === 'forget') lines.push(changed.length === 0 ? '没有偏好被移除。' : `已移除 ${changed.length} 条长期偏好。`)
336
- if (action === 'distill' || action === 'forget' || action === 'lessons') {
337
- lines.push(lessons.length === 0 ? '当前没有沉淀的偏好。' : `当前沉淀的偏好(${lessons.length} 条):`)
338
- lessons.forEach((lesson, index) => lines.push(`${index + 1}. ${lesson}`))
339
- return [{ type: 'text', text: lines.join('\n') }]
340
- }
341
- if (annotations.length === 0) {
342
- lines.push('当前对话没有标注。')
343
- return [{ type: 'text', text: lines.join('\n') }]
344
- }
345
- const pending = typeof value?.pending === 'number' ? value.pending : 0
346
- lines.push(`当前对话共 ${annotations.length} 条标注,其中 ${pending} 条待处理:`)
347
- for (const annotation of annotations) {
348
- const time = formatLocalTimestamp(annotation?.createdAt)
349
- const state = annotation?.status === 'resolved' ? '已处理' : '待处理'
350
- let line = `- [#${annotation?.id}] ${styleLabel(annotation?.style)}(${state})“${annotation?.quote ?? ''}”`
351
- if (annotation?.note) line += `|${annotation.style === 'rewrite' ? '改为' : '批注'}:${annotation.note}`
352
- if (time !== '') line += `(${time})`
353
- lines.push(line)
354
- }
355
- return [{ type: 'text', text: lines.join('\n') }]
356
- }
357
-
358
- function createAnnotationsTool(store) {
359
- return {
360
- name: TOOL_NAME,
361
- description:
362
- '查看或处理用户对你之前回答做的标注(高亮/下划线/删除/批注/改写)。' +
363
- '处理完待处理标注后用 action=resolve 确认(ids 可省略表示全部);' +
364
- '用户要看标注时 action=list;用户要撤销处理或再处理一遍用 reopen;删除用 delete/clear。' +
365
- '用户要求把标注归纳成长期偏好/习惯时,先总结成每条一句的可执行偏好,再用 action=distill 写入 lessons;' +
366
- 'lessons 列出已沉淀的偏好;forget 按原文或序号移除。',
367
- parameters: {
368
- type: 'object',
369
- additionalProperties: false,
370
- properties: {
371
- action: {
372
- type: 'string',
373
- enum: ['list', 'resolve', 'reopen', 'delete', 'clear', 'set-mode', 'distill', 'lessons', 'forget'],
374
- description:
375
- 'list=列出(默认);resolve=确认已处理;reopen=重新打开让它们下一轮再出现;' +
376
- 'delete=按 ids 删除;clear=清空;set-mode=切换注入模式(配合 mode);' +
377
- 'distill=把 lessons 里的偏好沉淀到用户全局 AGENTS.md;lessons=列出已沉淀的偏好;forget=移除 lessons 指定的偏好(原文或序号)。',
378
- },
379
- lessons: {
380
- type: 'array',
381
- items: { type: 'string' },
382
- description: 'distill/forget 使用:每条一句、可直接执行的用户偏好,例如“解释概念时先给具体例子再讲原理”。',
383
- },
384
- ids: {
385
- type: 'array',
386
- items: { type: 'string' },
387
- description: 'resolve/reopen/delete 作用的标注 id;resolve 与 reopen 省略时表示全部。',
388
- },
389
- mode: {
390
- type: 'string',
391
- enum: INJECTION_MODES,
392
- description: 'set-mode 时使用:brief=只注入被标注的段落;full=注入整条回答的修订视图。',
393
- },
394
- },
395
- },
396
- output: {
397
- schema: TOOL_OUTPUT,
398
- render: renderToolResult,
399
- },
400
- async execute(args, exec) {
401
- const sessionId = exec?.agent?.id
402
- if (typeof sessionId !== 'string' || sessionId === '') {
403
- throw new AnnotateInputError('no-session', '当前没有可用的对话,无法读取标注。')
404
- }
405
- const action = args?.action ?? 'list'
406
- const ids = Array.isArray(args?.ids)
407
- ? args.ids.filter(id => typeof id === 'string' && id.trim() !== '')
408
- : []
409
- let changed = []
410
- if (action === 'list') {
411
- // nothing to change
412
- } else if (action === 'resolve') {
413
- changed = store.resolve(sessionId, ids, { by: 'model' })
414
- } else if (action === 'reopen') {
415
- changed = store.reopen(sessionId, ids)
416
- } else if (action === 'delete') {
417
- if (ids.length === 0) throw new AnnotateInputError('missing-ids', 'delete 需要提供要删除的标注 id。')
418
- changed = store.list(sessionId).filter(item => ids.includes(item.id)).map(item => item.id)
419
- store.remove(sessionId, ids)
420
- } else if (action === 'clear') {
421
- changed = store.list(sessionId).map(item => item.id)
422
- store.clear(sessionId)
423
- } else if (action === 'set-mode') {
424
- store.setMode(sessionId, validateMode(args?.mode))
425
- } else if (action === 'distill') {
426
- const texts = Array.isArray(args?.lessons) ? args.lessons.filter(item => typeof item === 'string' && item.trim() !== '') : []
427
- if (texts.length === 0) throw new AnnotateInputError('missing-lessons', 'distill 需要在 lessons 里给出至少一条偏好。')
428
- changed = store.lessons.add(texts).added
429
- } else if (action === 'forget') {
430
- const targets = Array.isArray(args?.lessons) ? args.lessons.filter(item => typeof item === 'string' && item.trim() !== '') : []
431
- if (targets.length === 0) throw new AnnotateInputError('missing-lessons', 'forget 需要在 lessons 里给出要移除的偏好原文或序号。')
432
- changed = store.lessons.remove(targets)
433
- } else if (action === 'lessons') {
434
- // nothing to change
435
- } else {
436
- throw new AnnotateInputError('invalid-action', '未知的 action。')
437
- }
438
- const annotations = store.list(sessionId)
439
- return {
440
- action,
441
- mode: store.getMode(sessionId),
442
- total: annotations.length,
443
- pending: annotations.filter(item => item.status !== 'resolved').length,
444
- changed,
445
- annotations,
446
- lessons: store.lessons.list().map(lesson => lesson.text),
447
- }
448
- },
449
- presentCall: args => ({
450
- card: 'generic',
451
- title: 'Annotations',
452
- kind: 'other',
453
- rawInput: {
454
- action: args?.action ?? 'list',
455
- ...(Array.isArray(args?.ids) ? { ids: args.ids } : {}),
456
- ...(Array.isArray(args?.lessons) ? { lessons: args.lessons } : {}),
457
- },
458
- }),
459
- }
460
- }
461
-
462
- // ------------------------------------------------------------- injection
463
-
464
- function isDirectUserMessage(message) {
465
- const kind = message?.source?.kind
466
- return kind === 'user' || kind === undefined
467
- }
468
-
469
- /**
470
- * Build the pre-step listener. Exported for tests. The listener enters one
471
- * context message right after the user's own message on the first step of a
472
- * turn that has pending, still-injectable annotations.
473
- */
474
- export function createPreStepListener(store, { logger, maxInjections = DEFAULT_MAX_INJECTIONS, messageId } = {}) {
475
- const newId = typeof messageId === 'function' ? messageId : () => `dsa_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`
476
- return async function onPreStep(payload, next) {
477
- const decision = await next()
478
- try {
479
- if (decision?.kind !== 'enter' || !Array.isArray(decision.messages)) return decision
480
- if (payload?.step !== 1) return decision
481
- if (payload?.signal?.aborted) return decision
482
- const sessionId = payload?.agent?.id
483
- if (typeof sessionId !== 'string' || sessionId === '') return decision
484
- // Only a turn the user started gets the context; tool continuations and
485
- // other plugins' synthetic turns are left alone.
486
- const anchorIndex = decision.messages.findLastIndex(isDirectUserMessage)
487
- if (anchorIndex < 0) return decision
488
- const pending = store.pending(sessionId)
489
- if (pending.length === 0) return decision
490
- // Count this turn for every pending annotation; the ones past the cap
491
- // settle as `cap` here so they stop showing up as pending in the UI.
492
- const marked = store.markInjected(
493
- sessionId,
494
- pending.map(item => item.id),
495
- { turn: payload?.turn, cap: maxInjections },
496
- )
497
- if (marked.injected.length === 0) return decision
498
- const snapshot = store.snapshot(sessionId)
499
- const injected = snapshot.annotations.filter(item => marked.injected.includes(item.id))
500
- const text = buildInjection({ ...snapshot, annotations: injected }, { turn: payload?.turn })
501
- if (text === '') return decision
502
- const message = Object.freeze({
503
- id: newId(),
504
- role: 'user',
505
- content: [{ type: 'text', text }],
506
- source: { kind: SOURCE_KIND, form: 'snapshot', sections: [{ name: SOURCE_KIND, text }] },
507
- })
508
- const messages = decision.messages.slice()
509
- messages.splice(anchorIndex + 1, 0, message)
510
- return { ...decision, messages }
511
- } catch (error) {
512
- logger?.warn?.(`dsh-mindmark: cannot inject annotations: ${String(error)}`)
513
- return decision
514
- }
515
- }
516
- }
517
-
518
- // ------------------------------------------------------------------ plugin
519
-
520
- export function apply(ctx, config = {}) {
521
- const logger = ctx.logger ?? console
522
- const statePath = resolveStatePath()
523
- const maxInjections = Number.isInteger(config?.maxInjections) && config.maxInjections > 0
524
- ? config.maxInjections
525
- : DEFAULT_MAX_INJECTIONS
526
- const store = new AnnotationStore(statePath, { logger, defaultMode: config?.defaultMode })
527
- store.lessons = new LessonStore(resolveInstructionsPath(), { logger })
528
- const handler = createAnnotationsHandler({ store, logger })
529
-
530
- ctx.effect(
531
- () => ctx.webServer.register({ kind: 'exact', path: ROUTE, handler }),
532
- 'dsh-mindmark: annotations route',
533
- )
534
-
535
- ctx.effect(
536
- () => ctx.tools.register(createAnnotationsTool(store)),
537
- 'dsh-mindmark: annotations tool',
538
- )
539
-
540
- ctx.effect(
541
- () =>
542
- ctx.systemPrompt.section({
543
- name: SECTION_NAME,
544
- order: SECTION_ORDER,
545
- text: ({ scope } = {}) => {
546
- try {
547
- const sessionId = typeof scope?.id === 'string' ? scope.id : ''
548
- if (sessionId === '') return ''
549
- return buildProtocolSection(store.pending(sessionId).length)
550
- } catch (error) {
551
- logger?.warn?.(`dsh-mindmark: cannot build the annotations prompt section: ${String(error)}`)
552
- return ''
553
- }
554
- },
555
- }),
556
- 'dsh-mindmark: annotations prompt section',
557
- )
558
-
559
- if (typeof ctx.on === 'function') {
560
- ctx.on('agent/pre-step', createPreStepListener(store, { logger, maxInjections }))
561
- } else {
562
- logger?.warn?.('dsh-mindmark: ctx.on is unavailable; annotations will not be injected')
563
- }
564
-
565
- logger?.info?.(`dsh-mindmark: ready (${statePath}, mode=${store.defaultMode}, maxInjections=${maxInjections})`)
566
- }
1
+ // dsh-mindmark — Host half.
2
+ //
3
+ // Registers:
4
+ // • the read/write HTTP API the Web client uses to store annotations and the
5
+ // per-session injection mode (`/plugins/dsh-mindmark/annotations`);
6
+ // • `annotations`, the model-facing tool that lists / resolves / reopens /
7
+ // deletes the annotations of the current conversation;
8
+ // • an `agent/pre-step` listener that, at the start of each turn, enters one
9
+ // user-role context message carrying the pending annotations (so the model
10
+ // sees "the answer as the user marked it up"), logged like every other
11
+ // model-visible input;
12
+ // • a short protocol section in the system prompt while annotations are pending.
13
+ //
14
+ // No DSH package is imported on purpose: the plugin must boot from a linked
15
+ // profile directory whose loader can resolve only Node builtins.
16
+
17
+ import {
18
+ AnnotationStore,
19
+ AnnotateInputError,
20
+ ANNOTATION_STYLES,
21
+ INJECTION_MODES,
22
+ resolveStatePath,
23
+ validateMode,
24
+ validateSessionId,
25
+ } from './src/store.js'
26
+ import {
27
+ buildInjection,
28
+ buildProtocolSection,
29
+ SOURCE_KIND,
30
+ STYLE_META,
31
+ TOOL_NAME,
32
+ bookTitle,
33
+ targetText,
34
+ } from './src/inject.js'
35
+ import { LessonStore, resolveInstructionsPath } from './src/lessons.js'
36
+
37
+ export const name = 'mindmark'
38
+ export const inject = ['tools', 'systemPrompt', 'webServer']
39
+
40
+ export const ROUTE = '/plugins/dsh-mindmark/annotations'
41
+ export { TOOL_NAME }
42
+ export const SECTION_NAME = 'tool:annotations'
43
+ export const SECTION_ORDER = 9100
44
+ /** How many turns one annotation is re-injected before it settles on its own. */
45
+ export const DEFAULT_MAX_INJECTIONS = 3
46
+
47
+ // Room for a pasted reference material (200k characters of CJK text).
48
+ const MAX_BODY_BYTES = 1024 * 1024
49
+ // Plain-browser loopback origins and the Desktop shell's own boundary. The
50
+ // Desktop shell proxies the page's request without an Origin header, so an
51
+ // absent Origin is accepted here exactly like the shipped routes do.
52
+ const LOOPBACK_ORIGIN_RE = /^https?:\/\/(?:127\.0\.0\.1|localhost|\[::1\])(?::\d+)?$/i
53
+
54
+ function styleLabel(style) {
55
+ return STYLE_META[style]?.label ?? '标注'
56
+ }
57
+
58
+ // ------------------------------------------------------------------- HTTP
59
+
60
+ function corsHeaders(req) {
61
+ const origin = req?.headers?.origin
62
+ if (typeof origin !== 'string') return {}
63
+ if (origin === 'null' || LOOPBACK_ORIGIN_RE.test(origin)) {
64
+ return {
65
+ 'access-control-allow-origin': origin,
66
+ 'access-control-allow-methods': 'GET, POST, OPTIONS',
67
+ 'access-control-allow-headers': 'content-type',
68
+ 'access-control-max-age': '600',
69
+ vary: 'Origin',
70
+ }
71
+ }
72
+ return {}
73
+ }
74
+
75
+ function originAllowed(req) {
76
+ const origin = req?.headers?.origin
77
+ if (typeof origin !== 'string' || origin === '') return true
78
+ if (origin === 'null' || origin === 'dsh-app://app') return true
79
+ if (LOOPBACK_ORIGIN_RE.test(origin)) return true
80
+ const host = req?.headers?.host
81
+ if (typeof host === 'string' && (origin === `http://${host}` || origin === `https://${host}`)) {
82
+ return true
83
+ }
84
+ return false
85
+ }
86
+
87
+ function sendJson(req, res, status, value) {
88
+ const payload = JSON.stringify(value)
89
+ res.writeHead(status, {
90
+ 'content-type': 'application/json; charset=utf-8',
91
+ 'cache-control': 'no-store',
92
+ 'content-length': Buffer.byteLength(payload),
93
+ 'x-content-type-options': 'nosniff',
94
+ ...corsHeaders(req),
95
+ })
96
+ res.end(payload)
97
+ }
98
+
99
+ function sendError(req, res, status, code, message) {
100
+ sendJson(req, res, status, { ok: false, error: { code, message } })
101
+ }
102
+
103
+ async function readJsonBody(req) {
104
+ const chunks = []
105
+ let size = 0
106
+ for await (const chunk of req) {
107
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
108
+ size += buffer.length
109
+ if (size > MAX_BODY_BYTES) {
110
+ const error = new Error('request-too-large')
111
+ error.code = 'request-too-large'
112
+ throw error
113
+ }
114
+ chunks.push(buffer)
115
+ }
116
+ if (size === 0) {
117
+ const error = new Error('empty-body')
118
+ error.code = 'invalid-json'
119
+ throw error
120
+ }
121
+ try {
122
+ return JSON.parse(Buffer.concat(chunks).toString('utf8'))
123
+ } catch {
124
+ const error = new Error('invalid-json')
125
+ error.code = 'invalid-json'
126
+ throw error
127
+ }
128
+ }
129
+
130
+ function sessionIdFromUrl(req) {
131
+ try {
132
+ const url = new URL(typeof req?.url === 'string' ? req.url : '', 'http://127.0.0.1')
133
+ return url.searchParams.get('sessionId') ?? undefined
134
+ } catch {
135
+ return undefined
136
+ }
137
+ }
138
+
139
+ function sessionPayload(store, sessionId, extra = {}) {
140
+ const lessons = typeof store.lessons?.list === 'function' ? store.lessons.list() : []
141
+ return { ok: true, annotations: store.list(sessionId), mode: store.getMode(sessionId), lessons, ...extra }
142
+ }
143
+
144
+ function stringIds(ids, code, message) {
145
+ if (ids === undefined || ids === null) return []
146
+ if (!Array.isArray(ids) || ids.some(id => typeof id !== 'string')) {
147
+ throw new AnnotateInputError(code, message)
148
+ }
149
+ return ids
150
+ }
151
+
152
+ /**
153
+ * Build the annotations HTTP handler. Exported for tests; `apply` registers it
154
+ * as-is. `deps = { store, logger }`.
155
+ */
156
+ export function createAnnotationsHandler(deps) {
157
+ const store = deps?.store
158
+ const logger = deps?.logger
159
+ if (!store || typeof store.list !== 'function') {
160
+ throw new TypeError('createAnnotationsHandler requires deps.store')
161
+ }
162
+
163
+ return async function annotationsHandler(req, res) {
164
+ try {
165
+ if (req?.method === 'OPTIONS') {
166
+ res.writeHead(204, corsHeaders(req))
167
+ res.end()
168
+ return
169
+ }
170
+ if (!originAllowed(req)) {
171
+ sendError(req, res, 403, 'forbidden', '请求来源不被允许。')
172
+ return
173
+ }
174
+
175
+ if (req?.method === 'GET') {
176
+ const sessionId = sessionIdFromUrl(req)
177
+ let key
178
+ try {
179
+ key = validateSessionId(sessionId)
180
+ } catch {
181
+ sendError(req, res, 400, 'invalid-session-id', '会话 ID 无效。')
182
+ return
183
+ }
184
+ sendJson(req, res, 200, sessionPayload(store, key))
185
+ return
186
+ }
187
+
188
+ if (req?.method !== 'POST') {
189
+ sendError(req, res, 405, 'method-not-allowed', '只支持 GET 和 POST。')
190
+ return
191
+ }
192
+
193
+ const contentType = req.headers?.['content-type']
194
+ if (typeof contentType !== 'string' || !contentType.toLowerCase().startsWith('application/json')) {
195
+ sendError(req, res, 415, 'unsupported-media-type', '请使用 application/json。')
196
+ return
197
+ }
198
+
199
+ let body
200
+ try {
201
+ body = await readJsonBody(req)
202
+ } catch (error) {
203
+ const tooLarge = error?.code === 'request-too-large'
204
+ if (tooLarge) {
205
+ sendError(req, res, 413, 'request-too-large', '请求过大。')
206
+ } else {
207
+ sendError(req, res, 400, 'invalid-json', '请求体不是有效 JSON。')
208
+ }
209
+ return
210
+ }
211
+ if (body === null || typeof body !== 'object' || Array.isArray(body)) {
212
+ sendError(req, res, 400, 'invalid-body', '请求体必须是 JSON 对象。')
213
+ return
214
+ }
215
+
216
+ const sessionId = validateSessionId(body.sessionId)
217
+ const action = body.action
218
+
219
+ if (action === undefined || action === null || action === 'list') {
220
+ sendJson(req, res, 200, sessionPayload(store, sessionId))
221
+ return
222
+ }
223
+ if (action === 'add') {
224
+ const result = store.add(sessionId, body.annotation, body.message)
225
+ sendJson(req, res, 200, sessionPayload(store, sessionId, { added: result.deduped !== true }))
226
+ return
227
+ }
228
+ if (action === 'remove') {
229
+ const ids = stringIds(body.ids, 'invalid-ids', 'ids 必须是标注 id 的字符串数组。')
230
+ if (ids.length === 0) throw new AnnotateInputError('invalid-ids', 'ids 必须是标注 id 的字符串数组。')
231
+ const removed = store.remove(sessionId, ids)
232
+ sendJson(req, res, 200, sessionPayload(store, sessionId, { removed }))
233
+ return
234
+ }
235
+ if (action === 'clear') {
236
+ const removed = store.clear(sessionId)
237
+ sendJson(req, res, 200, sessionPayload(store, sessionId, { removed }))
238
+ return
239
+ }
240
+ if (action === 'resolve' || action === 'reopen') {
241
+ const ids = stringIds(body.ids, 'invalid-ids', 'ids 必须是标注 id 的字符串数组。')
242
+ const changed = action === 'resolve' ? store.resolve(sessionId, ids, { by: 'user' }) : store.reopen(sessionId, ids)
243
+ sendJson(req, res, 200, sessionPayload(store, sessionId, { changed }))
244
+ return
245
+ }
246
+ if (action === 'set-mode') {
247
+ store.setMode(sessionId, body.mode)
248
+ sendJson(req, res, 200, sessionPayload(store, sessionId))
249
+ return
250
+ }
251
+ if (action === 'forget-lesson') {
252
+ const targets = stringIds(body.lessons, 'invalid-lessons', 'lessons 必须是字符串数组。')
253
+ const removed = store.lessons ? store.lessons.remove(targets) : []
254
+ sendJson(req, res, 200, sessionPayload(store, sessionId, { removed: removed.length }))
255
+ return
256
+ }
257
+ throw new AnnotateInputError(
258
+ 'invalid-action',
259
+ '未知的 action,只支持 list、add、remove、clear、resolve、reopen、set-mode、forget-lesson。',
260
+ )
261
+ } catch (error) {
262
+ if (error instanceof AnnotateInputError) {
263
+ try {
264
+ sendError(req, res, 400, error.code, error.message)
265
+ } catch {
266
+ // The response is already gone; nothing left to report.
267
+ }
268
+ return
269
+ }
270
+ logger?.warn?.(`dsh-mindmark: annotation request failed: ${String(error)}`)
271
+ try {
272
+ sendError(req, res, 500, 'internal', '标注读写失败。')
273
+ } catch {
274
+ // The response is already gone; nothing left to report.
275
+ }
276
+ }
277
+ }
278
+ }
279
+
280
+ // --------------------------------------------------------------- the tool
281
+
282
+ const TIMESTAMP_PAD = number => String(number).padStart(2, '0')
283
+
284
+ /** Local `YYYY-MM-DD HH:MM`; '' when the timestamp is missing/unparseable. */
285
+ export function formatLocalTimestamp(value) {
286
+ if (typeof value !== 'string' || value === '') return ''
287
+ const date = new Date(value)
288
+ if (Number.isNaN(date.getTime())) return ''
289
+ return (
290
+ `${date.getFullYear()}-${TIMESTAMP_PAD(date.getMonth() + 1)}-${TIMESTAMP_PAD(date.getDate())}` +
291
+ ` ${TIMESTAMP_PAD(date.getHours())}:${TIMESTAMP_PAD(date.getMinutes())}`
292
+ )
293
+ }
294
+
295
+ const ANNOTATION_OUTPUT_ITEM = {
296
+ type: 'object',
297
+ additionalProperties: true,
298
+ properties: {
299
+ id: { type: 'string' },
300
+ style: { type: 'string', enum: ANNOTATION_STYLES },
301
+ quote: { type: 'string' },
302
+ note: { type: 'string' },
303
+ status: { type: 'string', enum: ['pending', 'resolved'] },
304
+ createdAt: { type: 'string' },
305
+ },
306
+ required: ['id', 'style', 'quote', 'status', 'createdAt'],
307
+ }
308
+
309
+ const TOOL_OUTPUT = {
310
+ type: 'object',
311
+ additionalProperties: false,
312
+ properties: {
313
+ action: { type: 'string' },
314
+ mode: { type: 'string', enum: INJECTION_MODES },
315
+ total: { type: 'integer' },
316
+ pending: { type: 'integer' },
317
+ changed: { type: 'array', items: { type: 'string' } },
318
+ annotations: { type: 'array', items: ANNOTATION_OUTPUT_ITEM },
319
+ lessons: { type: 'array', items: { type: 'string' } },
320
+ materials: {
321
+ type: 'array',
322
+ items: {
323
+ type: 'object',
324
+ additionalProperties: true,
325
+ properties: {
326
+ id: { type: 'string' },
327
+ kind: { type: 'string' },
328
+ title: { type: 'string' },
329
+ url: { type: 'string' },
330
+ total: { type: 'integer' },
331
+ offset: { type: 'integer' },
332
+ content: { type: 'string' },
333
+ nextOffset: { type: 'integer', description: '续读位置;-1 表示已读完' },
334
+ },
335
+ required: ['id', 'kind', 'title', 'total', 'offset', 'content'],
336
+ },
337
+ },
338
+ },
339
+ required: ['action', 'mode', 'total', 'pending', 'changed', 'annotations', 'lessons'],
340
+ }
341
+
342
+ function renderToolResult(_args, value) {
343
+ const annotations = Array.isArray(value?.annotations) ? value.annotations : []
344
+ const changed = Array.isArray(value?.changed) ? value.changed : []
345
+ const lines = []
346
+ const action = value?.action ?? 'list'
347
+ if (action === 'resolve') lines.push(changed.length === 0 ? '没有需要确认的标注。' : `已确认处理 ${changed.length} 条标注。`)
348
+ if (action === 'reopen') lines.push(changed.length === 0 ? '没有标注被重新打开。' : `已重新打开 ${changed.length} 条标注。`)
349
+ if (action === 'delete') lines.push(changed.length === 0 ? '没有标注被删除。' : `已删除 ${changed.length} 条标注。`)
350
+ if (action === 'clear') lines.push(`已清空 ${changed.length} 条标注。`)
351
+ if (action === 'set-mode') lines.push(`注入模式已改为 ${value?.mode === 'full' ? '完整' : '精简'}。`)
352
+ const lessons = Array.isArray(value?.lessons) ? value.lessons : []
353
+ if (action === 'distill') {
354
+ lines.push(changed.length === 0 ? '没有新的偏好被沉淀(可能已存在)。' : `已沉淀 ${changed.length} 条长期偏好到用户全局 AGENTS.md,新对话会自动遵守。`)
355
+ }
356
+ if (action === 'forget') lines.push(changed.length === 0 ? '没有偏好被移除。' : `已移除 ${changed.length} 条长期偏好。`)
357
+ if (action === 'material') {
358
+ const materials = Array.isArray(value?.materials) ? value.materials : []
359
+ if (materials.length === 0) lines.push('没有找到这些标注的参考材料。')
360
+ for (const material of materials) {
361
+ if (material.kind === 'url') {
362
+ lines.push(`[#${material.id}] 材料是一个链接:${material.url}(请用联网或网页读取工具打开)`)
363
+ continue
364
+ }
365
+ const end = material.offset + material.content.length
366
+ lines.push(`[#${material.id}] 材料${bookTitle(material.title)}第 ${material.offset + 1}–${end} 字(共 ${material.total} 字):`)
367
+ lines.push(material.content)
368
+ if (Number.isInteger(material.nextOffset) && material.nextOffset >= 0) {
369
+ lines.push(`(未完,继续读传 offset=${material.nextOffset})`)
370
+ }
371
+ }
372
+ return [{ type: 'text', text: lines.join('\n') }]
373
+ }
374
+ if (action === 'distill' || action === 'forget' || action === 'lessons') {
375
+ lines.push(lessons.length === 0 ? '当前没有沉淀的偏好。' : `当前沉淀的偏好(${lessons.length} 条):`)
376
+ lessons.forEach((lesson, index) => lines.push(`${index + 1}. ${lesson}`))
377
+ return [{ type: 'text', text: lines.join('\n') }]
378
+ }
379
+ if (annotations.length === 0) {
380
+ lines.push('当前对话没有标注。')
381
+ return [{ type: 'text', text: lines.join('\n') }]
382
+ }
383
+ const pending = typeof value?.pending === 'number' ? value.pending : 0
384
+ lines.push(`当前对话共 ${annotations.length} 条标注,其中 ${pending} 条待处理:`)
385
+ for (const annotation of annotations) {
386
+ const time = formatLocalTimestamp(annotation?.createdAt)
387
+ const state = annotation?.status === 'resolved' ? '已处理' : '待处理'
388
+ let line = `- [#${annotation?.id}] ${styleLabel(annotation?.style)}(${state})“${annotation?.quote ?? ''}”`
389
+ if (annotation?.style === 'move') line += `|移到:${targetText(annotation)}`
390
+ if (annotation?.style === 'reference' && annotation.material) {
391
+ const material = annotation.material
392
+ line += material.kind === 'url' ? `|材料链接:${material.url}` : `|材料${bookTitle(material.title)}${material.length} 字`
393
+ }
394
+ if (annotation?.note) {
395
+ const label = { rewrite: '改为', move: '理由', reference: '要求' }[annotation.style] ?? '批注'
396
+ line += `|${label}:${annotation.note}`
397
+ }
398
+ if (time !== '') line += `(${time})`
399
+ lines.push(line)
400
+ }
401
+ return [{ type: 'text', text: lines.join('\n') }]
402
+ }
403
+
404
+ function createAnnotationsTool(store) {
405
+ return {
406
+ name: TOOL_NAME,
407
+ description:
408
+ '查看或处理用户对你之前回答做的标注(高亮/下划线/删除/批注/改写/移动/依据)。' +
409
+ '依据标注附了用户的参考材料,材料较长时用 action=material(ids 指定标注,offset 续读)读取全文;' +
410
+ '处理完待处理标注后用 action=resolve 确认(ids 可省略表示全部);' +
411
+ '用户要看标注时 action=list;用户要撤销处理或再处理一遍用 reopen;删除用 delete/clear。' +
412
+ '用户要求把标注归纳成长期偏好/习惯时,先总结成每条一句的可执行偏好,再用 action=distill 写入 lessons;' +
413
+ 'lessons 列出已沉淀的偏好;forget 按原文或序号移除。',
414
+ parameters: {
415
+ type: 'object',
416
+ additionalProperties: false,
417
+ properties: {
418
+ action: {
419
+ type: 'string',
420
+ enum: ['list', 'resolve', 'reopen', 'delete', 'clear', 'set-mode', 'distill', 'lessons', 'forget', 'material'],
421
+ description:
422
+ 'list=列出(默认);resolve=确认已处理;reopen=重新打开让它们下一轮再出现;' +
423
+ 'delete=按 ids 删除;clear=清空;set-mode=切换注入模式(配合 mode);' +
424
+ 'distill=把 lessons 里的偏好沉淀到用户全局 AGENTS.md;lessons=列出已沉淀的偏好;forget=移除 lessons 指定的偏好(原文或序号);' +
425
+ 'material=读取依据标注附带的参考材料(配合 ids 与 offset)。',
426
+ },
427
+ offset: {
428
+ type: 'integer',
429
+ description: 'material 使用:从材料的第几个字开始读,默认 0;上次结果里的 nextOffset 就是续读位置。',
430
+ },
431
+ lessons: {
432
+ type: 'array',
433
+ items: { type: 'string' },
434
+ description: 'distill/forget 使用:每条一句、可直接执行的用户偏好,例如“解释概念时先给具体例子再讲原理”。',
435
+ },
436
+ ids: {
437
+ type: 'array',
438
+ items: { type: 'string' },
439
+ description: 'resolve/reopen/delete/material 作用的标注 id;resolve 与 reopen 省略时表示全部;material 省略时读取全部依据标注的材料。',
440
+ },
441
+ mode: {
442
+ type: 'string',
443
+ enum: INJECTION_MODES,
444
+ description: 'set-mode 时使用:brief=只注入被标注的段落;full=注入整条回答的修订视图。',
445
+ },
446
+ },
447
+ },
448
+ output: {
449
+ schema: TOOL_OUTPUT,
450
+ render: renderToolResult,
451
+ },
452
+ async execute(args, exec) {
453
+ const sessionId = exec?.agent?.id
454
+ if (typeof sessionId !== 'string' || sessionId === '') {
455
+ throw new AnnotateInputError('no-session', '当前没有可用的对话,无法读取标注。')
456
+ }
457
+ const action = args?.action ?? 'list'
458
+ const ids = Array.isArray(args?.ids)
459
+ ? args.ids.filter(id => typeof id === 'string' && id.trim() !== '')
460
+ : []
461
+ let changed = []
462
+ let materials
463
+ if (action === 'list') {
464
+ // nothing to change
465
+ } else if (action === 'resolve') {
466
+ changed = store.resolve(sessionId, ids, { by: 'model' })
467
+ } else if (action === 'reopen') {
468
+ changed = store.reopen(sessionId, ids)
469
+ } else if (action === 'delete') {
470
+ if (ids.length === 0) throw new AnnotateInputError('missing-ids', 'delete 需要提供要删除的标注 id。')
471
+ changed = store.list(sessionId).filter(item => ids.includes(item.id)).map(item => item.id)
472
+ store.remove(sessionId, ids)
473
+ } else if (action === 'clear') {
474
+ changed = store.list(sessionId).map(item => item.id)
475
+ store.clear(sessionId)
476
+ } else if (action === 'set-mode') {
477
+ store.setMode(sessionId, validateMode(args?.mode))
478
+ } else if (action === 'distill') {
479
+ const texts = Array.isArray(args?.lessons) ? args.lessons.filter(item => typeof item === 'string' && item.trim() !== '') : []
480
+ if (texts.length === 0) throw new AnnotateInputError('missing-lessons', 'distill 需要在 lessons 里给出至少一条偏好。')
481
+ changed = store.lessons.add(texts).added
482
+ } else if (action === 'forget') {
483
+ const targets = Array.isArray(args?.lessons) ? args.lessons.filter(item => typeof item === 'string' && item.trim() !== '') : []
484
+ if (targets.length === 0) throw new AnnotateInputError('missing-lessons', 'forget 需要在 lessons 里给出要移除的偏好原文或序号。')
485
+ changed = store.lessons.remove(targets)
486
+ } else if (action === 'lessons') {
487
+ // nothing to change
488
+ } else if (action === 'material') {
489
+ const offset = Number.isInteger(args?.offset) && args.offset >= 0 ? args.offset : 0
490
+ const targets = ids.length > 0
491
+ ? ids
492
+ : store.list(sessionId).filter(item => item.style === 'reference').map(item => item.id)
493
+ materials = targets
494
+ .map(id => store.material(sessionId, id, { offset }))
495
+ .filter(item => item !== undefined)
496
+ } else {
497
+ throw new AnnotateInputError('invalid-action', '未知的 action。')
498
+ }
499
+ const annotations = store.list(sessionId)
500
+ return {
501
+ action,
502
+ mode: store.getMode(sessionId),
503
+ total: annotations.length,
504
+ pending: annotations.filter(item => item.status !== 'resolved').length,
505
+ changed,
506
+ annotations,
507
+ lessons: store.lessons.list().map(lesson => lesson.text),
508
+ ...(materials === undefined ? {} : { materials }),
509
+ }
510
+ },
511
+ presentCall: args => ({
512
+ card: 'generic',
513
+ title: 'Annotations',
514
+ kind: 'other',
515
+ rawInput: {
516
+ action: args?.action ?? 'list',
517
+ ...(Array.isArray(args?.ids) ? { ids: args.ids } : {}),
518
+ ...(Array.isArray(args?.lessons) ? { lessons: args.lessons } : {}),
519
+ ...(Number.isInteger(args?.offset) ? { offset: args.offset } : {}),
520
+ },
521
+ }),
522
+ }
523
+ }
524
+
525
+ // ------------------------------------------------------------- injection
526
+
527
+ function isDirectUserMessage(message) {
528
+ const kind = message?.source?.kind
529
+ return kind === 'user' || kind === undefined
530
+ }
531
+
532
+ /**
533
+ * Build the pre-step listener. Exported for tests. The listener enters one
534
+ * context message right after the user's own message on the first step of a
535
+ * turn that has pending, still-injectable annotations.
536
+ */
537
+ export function createPreStepListener(store, { logger, maxInjections = DEFAULT_MAX_INJECTIONS, messageId } = {}) {
538
+ const newId = typeof messageId === 'function' ? messageId : () => `dsa_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`
539
+ return async function onPreStep(payload, next) {
540
+ const decision = await next()
541
+ try {
542
+ if (decision?.kind !== 'enter' || !Array.isArray(decision.messages)) return decision
543
+ if (payload?.step !== 1) return decision
544
+ if (payload?.signal?.aborted) return decision
545
+ const sessionId = payload?.agent?.id
546
+ if (typeof sessionId !== 'string' || sessionId === '') return decision
547
+ // Only a turn the user started gets the context; tool continuations and
548
+ // other plugins' synthetic turns are left alone.
549
+ const anchorIndex = decision.messages.findLastIndex(isDirectUserMessage)
550
+ if (anchorIndex < 0) return decision
551
+ const pending = store.pending(sessionId)
552
+ if (pending.length === 0) return decision
553
+ // Count this turn for every pending annotation; the ones past the cap
554
+ // settle as `cap` here so they stop showing up as pending in the UI.
555
+ const marked = store.markInjected(
556
+ sessionId,
557
+ pending.map(item => item.id),
558
+ { turn: payload?.turn, cap: maxInjections },
559
+ )
560
+ if (marked.injected.length === 0) return decision
561
+ const snapshot = store.snapshot(sessionId)
562
+ const injected = snapshot.annotations.filter(item => marked.injected.includes(item.id))
563
+ const text = buildInjection({ ...snapshot, annotations: injected }, { turn: payload?.turn })
564
+ if (text === '') return decision
565
+ const message = Object.freeze({
566
+ id: newId(),
567
+ role: 'user',
568
+ content: [{ type: 'text', text }],
569
+ source: { kind: SOURCE_KIND, form: 'snapshot', sections: [{ name: SOURCE_KIND, text }] },
570
+ })
571
+ const messages = decision.messages.slice()
572
+ messages.splice(anchorIndex + 1, 0, message)
573
+ return { ...decision, messages }
574
+ } catch (error) {
575
+ logger?.warn?.(`dsh-mindmark: cannot inject annotations: ${String(error)}`)
576
+ return decision
577
+ }
578
+ }
579
+ }
580
+
581
+ // ------------------------------------------------------------------ plugin
582
+
583
+ export function apply(ctx, config = {}) {
584
+ const logger = ctx.logger ?? console
585
+ const statePath = resolveStatePath()
586
+ const maxInjections = Number.isInteger(config?.maxInjections) && config.maxInjections > 0
587
+ ? config.maxInjections
588
+ : DEFAULT_MAX_INJECTIONS
589
+ const store = new AnnotationStore(statePath, { logger, defaultMode: config?.defaultMode })
590
+ store.lessons = new LessonStore(resolveInstructionsPath(), { logger })
591
+ const handler = createAnnotationsHandler({ store, logger })
592
+
593
+ ctx.effect(
594
+ () => ctx.webServer.register({ kind: 'exact', path: ROUTE, handler }),
595
+ 'dsh-mindmark: annotations route',
596
+ )
597
+
598
+ ctx.effect(
599
+ () => ctx.tools.register(createAnnotationsTool(store)),
600
+ 'dsh-mindmark: annotations tool',
601
+ )
602
+
603
+ ctx.effect(
604
+ () =>
605
+ ctx.systemPrompt.section({
606
+ name: SECTION_NAME,
607
+ order: SECTION_ORDER,
608
+ text: ({ scope } = {}) => {
609
+ try {
610
+ const sessionId = typeof scope?.id === 'string' ? scope.id : ''
611
+ if (sessionId === '') return ''
612
+ return buildProtocolSection(store.pending(sessionId).length)
613
+ } catch (error) {
614
+ logger?.warn?.(`dsh-mindmark: cannot build the annotations prompt section: ${String(error)}`)
615
+ return ''
616
+ }
617
+ },
618
+ }),
619
+ 'dsh-mindmark: annotations prompt section',
620
+ )
621
+
622
+ if (typeof ctx.on === 'function') {
623
+ ctx.on('agent/pre-step', createPreStepListener(store, { logger, maxInjections }))
624
+ } else {
625
+ logger?.warn?.('dsh-mindmark: ctx.on is unavailable; annotations will not be injected')
626
+ }
627
+
628
+ logger?.info?.(`dsh-mindmark: ready (${statePath}, mode=${store.defaultMode}, maxInjections=${maxInjections})`)
629
+ }