dsh-mindmark 0.0.0-stage → 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/CHANGELOG.md +25 -0
- package/LICENSE +21 -0
- package/README.en.md +103 -0
- package/README.md +125 -2
- package/client.js +3239 -0
- package/cordis.patch.yml +14 -0
- package/docs/demo.gif +0 -0
- package/icon.svg +9 -0
- package/index.js +629 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +55 -4
- package/src/inject.js +367 -0
- package/src/lessons.js +187 -0
- package/src/store.js +1028 -0
package/cordis.patch.yml
ADDED
|
@@ -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,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
|
+
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
|
+
}
|
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, rewrite, back with a source or move parts of an answer; the markup reaches the assistant as context on the next turn and it confirms when handled."
|
|
5
|
+
}
|
|
6
|
+
}
|