dsh-mindmark 0.0.0-stage → 0.3.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.
@@ -0,0 +1,14 @@
1
+ # dsh-mindmark — one Host row that serves the annotations route, the
2
+ # `annotations` tool, the pre-step injection and the protocol prompt section,
3
+ # and carries the Web client bundle. The row name equals the package name so
4
+ # dsh-client-modules can resolve '<row-name>/package.json' and pick up dsh.client.
5
+ #
6
+ # config:
7
+ # defaultMode: 'brief' | 'full' (per-session switch in the composer overrides it)
8
+ # maxInjections: integer (turns an unresolved annotation is re-sent before it settles)
9
+ - insert:
10
+ - id: dsh-mindmark
11
+ name: 'dsh-mindmark'
12
+ config:
13
+ defaultMode: brief
14
+ maxInjections: 3
package/docs/demo.gif ADDED
Binary file
package/icon.svg ADDED
@@ -0,0 +1,9 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="Annotation marks">
2
+ <rect x="4" y="4" width="56" height="56" rx="14" fill="#f2f4f7"/>
3
+ <rect x="4.75" y="4.75" width="54.5" height="54.5" rx="13.25" fill="none" stroke="#d3d8e0" stroke-width="1.5"/>
4
+ <path d="M23.2 39.8 36.4 19.6a2.2 2.2 0 0 1 3.2-.6l4.1 2.8a2.2 2.2 0 0 1 .6 3.2L31.1 45.2l-8.1 2.4Z" fill="#ffd75e" stroke="#8a6412" stroke-width="2.2" stroke-linejoin="round"/>
5
+ <path d="m27.9 42.7 3.2.2 2.5-3.4" fill="none" stroke="#8a6412" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"/>
6
+ <path d="M30.4 47.4 37 51l2.3-6.7Z" fill="#f0a93b" stroke="#8a6412" stroke-width="2.2" stroke-linejoin="round"/>
7
+ <path d="M17 51.4h22" fill="none" stroke="#4d7cfe" stroke-width="3.2" stroke-linecap="round"/>
8
+ <path d="M44.5 51.4h3" fill="none" stroke="#4d7cfe" stroke-width="3.2" stroke-linecap="round"/>
9
+ </svg>
package/index.js ADDED
@@ -0,0 +1,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
+ } 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
+ }
package/locale/en.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "MindMark",
4
+ "description": "Show the model your mind: highlight, underline, strike, comment on or rewrite parts of an answer; the markup reaches the assistant as context on the next turn and it confirms when handled."
5
+ }
6
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "思维标注 MindMark",
4
+ "description": "把你的想法直接标在回答上:高亮、下划线、删除、批注、改写;下一轮助手就按你标的来,处理完回传确认。"
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,6 +1,56 @@
1
- {
2
- "name": "dsh-mindmark",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
1
+ {
2
+ "name": "dsh-mindmark",
3
+ "version": "0.3.0",
4
+ "description": "Show the model your mind: mark up an answer like in Word (highlight / underline / strike / comment / rewrite) and your markup reaches DeepSeek Harness as context on the next turn.",
5
+ "type": "module",
6
+ "main": "./index.js",
7
+ "exports": {
8
+ ".": "./index.js",
9
+ "./client": "./client.js",
10
+ "./package.json": "./package.json",
11
+ "./locale/*.json": "./locale/*.json",
12
+ "./icon": "./icon.svg"
13
+ },
14
+ "files": [
15
+ "index.js",
16
+ "client.js",
17
+ "src",
18
+ "locale",
19
+ "cordis.patch.yml",
20
+ "README.md",
21
+ "icon.svg",
22
+ "LICENSE",
23
+ "docs/demo.gif",
24
+ "README.en.md"
25
+ ],
26
+ "dsh": {
27
+ "bundle": {
28
+ "patch": "./cordis.patch.yml"
29
+ },
30
+ "client": {
31
+ "platform": "web"
32
+ }
33
+ },
34
+ "keywords": [
35
+ "dsh-plugin",
36
+ "deepseek-harness",
37
+ "annotation",
38
+ "markup",
39
+ "feedback",
40
+ "human-in-the-loop",
41
+ "intent"
42
+ ],
43
+ "license": "MIT",
44
+ "repository": {
45
+ "type": "git",
46
+ "url": "git+https://github.com/BaiKe-Zhang/dsh-mindmark.git"
47
+ },
48
+ "homepage": "https://github.com/BaiKe-Zhang/dsh-mindmark#readme",
49
+ "bugs": {
50
+ "url": "https://github.com/BaiKe-Zhang/dsh-mindmark/issues"
51
+ },
52
+ "author": "BaiKe-Zhang",
53
+ "scripts": {
54
+ "test": "node --test \"test/*.test.mjs\""
55
+ }
56
+ }