@tangjs/dsh-memory 0.0.0-stage → 1.0.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,813 @@
1
+ // End-of-turn memory extraction.
2
+ //
3
+ // CONTRACT (implemented by the extract module; index.js only consumes it):
4
+ //
5
+ // createExtractor({ store, config, log, getLlm, getRoute, spaceOf, digestMaxBytes, llm })
6
+ // → {
7
+ // onSessionEvent(session, event): void,
8
+ // async flush(session): Promise<{ skipped: boolean, reason?: string, written?: string[], deleted?: string[] }>,
9
+ // lastSeqFor(sessionId): number | null,
10
+ // }
11
+ //
12
+ // buildExtractPrompt({ conversation, manifest, maxPerTurn, noteBytes, isIncremental })
13
+ // → string
14
+ // parseExtraction(raw) → { upserts: Array<{name, description, type, body, file?}>, deletes: string[] }
15
+ // or { error: string }
16
+ // applyExtraction({ store, spaceKey, parsed, sessionId, seq })
17
+ // → Promise<{ written: string[], deleted: string[], errors: string[] }>
18
+ //
19
+ // Rules the implementation must keep:
20
+ // - Only the root agent's session is extracted (subagents are ignored).
21
+ // - One extraction per turn at most, and only when new text since the last
22
+ // extraction cursor reaches config.extract.minNewChars.
23
+ // - The prompt carries only the conversation newer than the extraction cursor
24
+ // (at most ~8K characters) plus a bounded manifest of existing notes; the
25
+ // manifest line is bookkeeping, never content.
26
+ // - parseExtraction repairs replies that copied that bookkeeping: a name
27
+ // loses leading/trailing `[type]` tags and a trailing `.md`, a description
28
+ // loses `[type]` tags, and `file` survives only as a safe note file name.
29
+ // - applyExtraction never creates a second file for a topic that already
30
+ // exists: an explicit `file` wins, otherwise a normalized
31
+ // name+description character-bigram similarity at/above the threshold
32
+ // updates the existing note (keeping its name, file, and created stamp).
33
+ // - A malformed model reply is dropped as a whole; the cursor still advances
34
+ // so the same turn is never retried in a loop.
35
+ // - Failures are logged and swallowed: extraction must never break a turn.
36
+
37
+ import {
38
+ appendDigest,
39
+ createDigest,
40
+ DEFAULT_DIGEST_MAX_BYTES,
41
+ digestCharsSince,
42
+ digestTextSince,
43
+ lastSeq,
44
+ } from './digest.mjs'
45
+
46
+ const DEFAULT_MIN_NEW_CHARS = 1500
47
+ const DEFAULT_MAX_PER_TURN = 3
48
+ const DEFAULT_NOTE_BYTES = 8192
49
+ const MANIFEST_LIMIT = 50
50
+ const MANIFEST_MAX_CHARS = 2000
51
+ /** Tail of new conversation sent to the model; the full digest window stays wider. */
52
+ const PROMPT_CONVERSATION_MAX_CHARS = 8000
53
+ /** Character-bigram similarity at or above this means "same topic". */
54
+ const TOPIC_SIMILARITY_THRESHOLD = 0.45
55
+ // Mirrors store.isSafeFile; kept local so the parser can drop hostile file names
56
+ // before they ever reach the store.
57
+ const SAFE_FILE = /^[a-z0-9][a-z0-9._-]*\.md$/
58
+ const MAX_NAME_CHARS = 120
59
+ const MAX_DESCRIPTION_CHARS = 240
60
+ const MAX_SESSIONS = 64
61
+
62
+ export function buildExtractPrompt({
63
+ conversation = '',
64
+ manifest = '',
65
+ maxPerTurn = DEFAULT_MAX_PER_TURN,
66
+ noteBytes = DEFAULT_NOTE_BYTES,
67
+ isIncremental = false,
68
+ } = {}) {
69
+ const existing = manifest.trim() === '' ? '(none yet)' : manifest.trim()
70
+ const conversationHeading = isIncremental
71
+ ? '## New conversation since the last extraction (自上次提取以来的新增对话)'
72
+ : '## Conversation'
73
+ return `You are the memory extraction subagent for a coding agent.
74
+
75
+ Review the conversation below and update the workspace memory notes. Use only facts that appear in the conversation; do not inspect the codebase and do not guess.
76
+
77
+ ## Existing notes
78
+
79
+ Each line below is prompt bookkeeping in exactly this shape:
80
+
81
+ - [type] file-name.md (updated ISO-8601): Note name — one-line description
82
+
83
+ The "[type]" tag, the ISO timestamp, the ".md" file name, and the whole line shape are METADATA: they tell you which note is which. They are never content. Never copy brackets, timestamps, or file names into the "name" or "description" you output.
84
+
85
+ ${existing}
86
+
87
+ If one of these notes already covers a topic, return its exact file name in "file", keep its existing "name", and write the fully merged body. Do not create a near-duplicate note for a topic that already exists.
88
+
89
+ ${conversationHeading}
90
+
91
+ ${conversation}
92
+
93
+ ## Output
94
+
95
+ Return ONLY a JSON object, no prose and no code fence:
96
+
97
+ {"upserts":[{"name":"Human readable topic","description":"One sentence used for recall","type":"user|feedback|project|reference","body":"...","file":"existing-file.md"}],"deletes":["stale-note.md"]}
98
+
99
+ Rules:
100
+ - At most ${maxPerTurn} upserts.
101
+ - "name" is a short, human-readable topic (a subject, not a file). It must not contain ".md", "[...]" type tags, timestamps, or any file name.
102
+ - "description" is one sentence used for recall. It must not start or end with a "[type]" tag and must not contain timestamps or file names.
103
+ - "file" is optional. Set it only to the exact file of an existing note you are updating; reuse that note's "name" so the update lands in the same file.
104
+ - Use only file names that appear under "Existing notes", in "file" and in "deletes"; never invent file names.
105
+ - Skip anything derivable from code, git history, or AGENTS.md; skip ephemeral task state.
106
+ - Each body is at most ${noteBytes} bytes. Convert relative dates to absolute dates.
107
+ - If nothing is worth saving, return {"upserts":[],"deletes":[]}.`
108
+ }
109
+
110
+ function errorMessage(error) {
111
+ return error instanceof Error ? error.message : String(error)
112
+ }
113
+
114
+ function collapseLine(text) {
115
+ return String(text ?? '')
116
+ .replace(/\s+/g, ' ')
117
+ .trim()
118
+ }
119
+
120
+ // `[project]` / `[user]` / ... copied out of the manifest is bookkeeping, not a
121
+ // topic. Strip it only at the edges so brackets the author actually meant stay.
122
+ const TYPE_TAG_START = /^(?:[-*]\s*)?\[(?:user|feedback|project|reference)\]\s*/i
123
+ const TYPE_TAG_END = /\s*\[(?:user|feedback|project|reference)\]\s*$/i
124
+
125
+ function stripTypeTags(text) {
126
+ let value = collapseLine(text)
127
+ for (let pass = 0; pass < 4; pass += 1) {
128
+ const before = value
129
+ value = value.replace(TYPE_TAG_START, '').replace(TYPE_TAG_END, '').trim()
130
+ if (value === before) break
131
+ }
132
+ return value
133
+ }
134
+
135
+ /** A note name is a human-readable topic: no `[type]` tags, no `.md` suffix. */
136
+ function cleanName(raw) {
137
+ let name = stripTypeTags(collapseLine(raw))
138
+ while (/\.md$/i.test(name)) name = name.slice(0, -3).trim()
139
+ return collapseLine(name).slice(0, MAX_NAME_CHARS).trim()
140
+ }
141
+
142
+ /** A note description is one line: no `[type]` tags, no stray edge punctuation. */
143
+ function cleanDescription(raw) {
144
+ const stripped = stripTypeTags(collapseLine(raw))
145
+ const trimmed = stripped.replace(/^[\s:;,|—–-]+/, '').replace(/[\s:;,|—–-]+$/, '')
146
+ return collapseLine(trimmed).slice(0, MAX_DESCRIPTION_CHARS).trim()
147
+ }
148
+
149
+ /** Only a safe note file name survives; anything else is dropped as metadata. */
150
+ function cleanFile(raw) {
151
+ if (typeof raw !== 'string') return undefined
152
+ const file = raw.trim()
153
+ return SAFE_FILE.test(file) ? file : undefined
154
+ }
155
+
156
+ /** Copy only the fields a note may carry, cleaning the ones with known garbage. */
157
+ function sanitizeUpsert(item) {
158
+ if (item === null || typeof item !== 'object' || Array.isArray(item)) return {}
159
+ const cleaned = {}
160
+ if (item.name !== undefined) cleaned.name = typeof item.name === 'string' ? cleanName(item.name) : item.name
161
+ if (item.description !== undefined) {
162
+ cleaned.description = typeof item.description === 'string' ? cleanDescription(item.description) : item.description
163
+ }
164
+ if (item.type !== undefined) cleaned.type = item.type
165
+ if (item.body !== undefined) cleaned.body = item.body
166
+ const file = cleanFile(item.file)
167
+ if (file !== undefined) cleaned.file = file
168
+ return cleaned
169
+ }
170
+
171
+ /** Every plausible JSON payload in a model reply, most literal first. */
172
+ function jsonCandidates(text) {
173
+ const candidates = []
174
+ for (const match of text.matchAll(/```([\s\S]*?)```/g)) {
175
+ const block = String(match[1] ?? '').trim()
176
+ if (block === '') continue
177
+ candidates.push(block)
178
+ const newline = block.indexOf('\n')
179
+ if (newline > 0) {
180
+ const first = block.slice(0, newline).trim()
181
+ if (/^[A-Za-z][\w+.-]*$/.test(first)) {
182
+ const rest = block.slice(newline + 1).trim()
183
+ if (rest !== '') candidates.push(rest)
184
+ }
185
+ }
186
+ }
187
+ candidates.push(text)
188
+ const start = text.indexOf('{')
189
+ const end = text.lastIndexOf('}')
190
+ if (start >= 0 && end > start) candidates.push(text.slice(start, end + 1))
191
+ return candidates
192
+ }
193
+
194
+ export function parseExtraction(raw) {
195
+ const text = String(raw ?? '').trim()
196
+ if (text === '') return { error: 'empty reply' }
197
+ let sawNonObject = false
198
+ let lastError = null
199
+ for (const candidate of jsonCandidates(text)) {
200
+ let parsed
201
+ try {
202
+ parsed = JSON.parse(candidate)
203
+ } catch (error) {
204
+ lastError = error
205
+ continue
206
+ }
207
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
208
+ sawNonObject = true
209
+ continue
210
+ }
211
+ const upserts = Array.isArray(parsed.upserts) ? parsed.upserts.map(sanitizeUpsert) : []
212
+ const deletes = Array.isArray(parsed.deletes)
213
+ ? parsed.deletes.filter(file => typeof file === 'string' && file.trim() !== '').map(file => file.trim())
214
+ : []
215
+ return { upserts, deletes }
216
+ }
217
+ if (sawNonObject) return { error: 'reply is not an object' }
218
+ return { error: `invalid JSON${lastError === null ? '' : `: ${errorMessage(lastError)}`}` }
219
+ }
220
+
221
+ /**
222
+ * Normalize name/description into one comparison key: lower-case letters and
223
+ * digits only, so spacing and punctuation differences never look like a new
224
+ * topic. CJK stays intact (one character is one code point).
225
+ */
226
+ function normalizeTopicText(text) {
227
+ return String(text ?? '')
228
+ .toLowerCase()
229
+ .replace(/[^\p{L}\p{N}]+/gu, '')
230
+ }
231
+
232
+ /** Character bigrams of a normalized string. */
233
+ function bigramSet(text) {
234
+ const chars = [...text]
235
+ const grams = new Set()
236
+ for (let index = 0; index + 1 < chars.length; index += 1) grams.add(chars[index] + chars[index + 1])
237
+ return grams
238
+ }
239
+
240
+ /** Bigram Jaccard similarity of two already-normalized strings, 0..1. */
241
+ function bigramJaccard(left, right) {
242
+ const leftGrams = bigramSet(left)
243
+ const rightGrams = bigramSet(right)
244
+ if (leftGrams.size === 0 || rightGrams.size === 0) return 0
245
+ let shared = 0
246
+ for (const gram of leftGrams) if (rightGrams.has(gram)) shared += 1
247
+ return shared / (leftGrams.size + rightGrams.size - shared)
248
+ }
249
+
250
+ /**
251
+ * Topic similarity: the larger of the name-only match (same subject despite
252
+ * rewording) and the name+description match (same one-liner despite a renamed
253
+ * title). The `|` in the combined key keeps the field boundary.
254
+ */
255
+ function topicSimilarity(left, right) {
256
+ const leftName = normalizeTopicText(left?.name)
257
+ const rightName = normalizeTopicText(right?.name)
258
+ const nameScore = bigramJaccard(leftName, rightName)
259
+ const leftTopic = `${leftName}|${normalizeTopicText(left?.description)}`
260
+ const rightTopic = `${rightName}|${normalizeTopicText(right?.description)}`
261
+ return Math.max(nameScore, bigramJaccard(leftTopic, rightTopic))
262
+ }
263
+
264
+ /**
265
+ * Find the existing note this upsert belongs to: explicit `file` wins, then an
266
+ * identical normalized name, then bigram similarity at/above the threshold.
267
+ */
268
+ function findMatchingNote(notes, upsert) {
269
+ const file = typeof upsert?.file === 'string' ? upsert.file : ''
270
+ if (file !== '') {
271
+ const byFile = notes.find(note => note.file === file)
272
+ if (byFile !== undefined) return byFile
273
+ }
274
+ const name = typeof upsert?.name === 'string' ? upsert.name.trim() : ''
275
+ if (name === '') return null
276
+ const nameKey = normalizeTopicText(name)
277
+ let best = null
278
+ let bestScore = 0
279
+ for (const note of notes) {
280
+ if (nameKey !== '' && normalizeTopicText(note.name) === nameKey) return note
281
+ const score = topicSimilarity({ name, description: upsert?.description }, note)
282
+ if (score > bestScore) {
283
+ bestScore = score
284
+ best = note
285
+ }
286
+ }
287
+ return best !== null && bestScore >= TOPIC_SIMILARITY_THRESHOLD ? best : null
288
+ }
289
+
290
+ /** Best-effort note index for dedupe; a broken read only disables matching. */
291
+ async function loadNoteIndex(store, spaceKey) {
292
+ if (typeof store?.listNotes !== 'function') return []
293
+ try {
294
+ const notes = await store.listNotes(spaceKey)
295
+ if (!Array.isArray(notes)) return []
296
+ return notes
297
+ .filter(note => note !== null && typeof note === 'object' && typeof note.file === 'string')
298
+ .map(note => ({
299
+ file: note.file,
300
+ name: typeof note.name === 'string' ? note.name : '',
301
+ description: typeof note.description === 'string' ? note.description : '',
302
+ type: note.type,
303
+ }))
304
+ } catch {
305
+ return []
306
+ }
307
+ }
308
+
309
+ export async function applyExtraction({ store, spaceKey, parsed, sessionId, seq } = {}) {
310
+ const written = []
311
+ const deleted = []
312
+ const errors = []
313
+ if (store === undefined || store === null) return { written, deleted, errors: ['store is required'] }
314
+ const upserts = Array.isArray(parsed?.upserts) ? parsed.upserts : []
315
+ const deletes = Array.isArray(parsed?.deletes) ? parsed.deletes : []
316
+ // One read per reply; a later item in the same reply can merge into a note the
317
+ // earlier item just wrote, so the index is refreshed after each write.
318
+ const known = await loadNoteIndex(store, spaceKey)
319
+ for (const item of upserts) {
320
+ const label = item?.name ?? '?'
321
+ try {
322
+ const existing = findMatchingNote(known, item)
323
+ // `store.writeNote` locates the file by exact name, so reusing the existing
324
+ // name is what keeps the original path and its `created` timestamp.
325
+ const name = existing === null ? (item?.name ?? '') : existing.name
326
+ const description =
327
+ typeof item?.description === 'string' && item.description.trim() !== ''
328
+ ? item.description
329
+ : (existing?.description ?? '')
330
+ const type = item?.type ?? existing?.type
331
+ const result = await store.writeNote(
332
+ spaceKey,
333
+ { name, description, type, body: item?.body, origin: 'extract' },
334
+ { origin: 'extract', sessionId, seq },
335
+ )
336
+ written.push(result.file)
337
+ if (existing === null) {
338
+ known.push({ file: result.file, name: String(name ?? ''), description, type })
339
+ } else {
340
+ existing.file = result.file
341
+ existing.description = description
342
+ existing.type = type
343
+ }
344
+ } catch (error) {
345
+ errors.push(`${label}: ${errorMessage(error)}`)
346
+ }
347
+ }
348
+ for (const file of deletes) {
349
+ // A reply that creates a note and deletes the same file must not erase what
350
+ // it just wrote; report it instead of silently losing the note.
351
+ if (written.includes(file)) {
352
+ errors.push(`${String(file)}: delete skipped because the same reply wrote it`)
353
+ continue
354
+ }
355
+ try {
356
+ if (await store.deleteNote(spaceKey, file)) deleted.push(file)
357
+ } catch (error) {
358
+ errors.push(`${String(file)}: ${errorMessage(error)}`)
359
+ }
360
+ }
361
+ return { written, deleted, errors }
362
+ }
363
+
364
+ function normalizeExtractConfig(config) {
365
+ const extract = config?.extract ?? {}
366
+ const storage = config?.storage ?? {}
367
+ const minNewChars = Number.isFinite(extract.minNewChars)
368
+ ? Math.max(0, Math.trunc(extract.minNewChars))
369
+ : DEFAULT_MIN_NEW_CHARS
370
+ const maxPerTurn = Number.isFinite(extract.maxPerTurn)
371
+ ? Math.min(10, Math.max(1, Math.trunc(extract.maxPerTurn)))
372
+ : DEFAULT_MAX_PER_TURN
373
+ const noteBytes =
374
+ Number.isFinite(storage.maxNoteBytes) && storage.maxNoteBytes > 0
375
+ ? Math.trunc(storage.maxNoteBytes)
376
+ : DEFAULT_NOTE_BYTES
377
+ return {
378
+ enabled: extract.enabled !== false,
379
+ minNewChars,
380
+ maxPerTurn,
381
+ model: typeof extract.model === 'string' ? extract.model.trim() : '',
382
+ noteBytes,
383
+ }
384
+ }
385
+
386
+ function isSubagentSession(session) {
387
+ const header = session?.header ?? {}
388
+ const depth = session?.delegationDepth ?? header.delegationDepth
389
+ if (typeof depth === 'number' && depth > 0) return true
390
+ for (const value of [session?.parentSessionId, session?.parentId, header.parentSessionId, header.parentId]) {
391
+ if (value !== undefined && value !== null && value !== '') return true
392
+ }
393
+ return false
394
+ }
395
+
396
+ function sessionIdOf(session) {
397
+ const id = session?.id
398
+ if (typeof id !== 'string' || id.trim() === '') return null
399
+ return id
400
+ }
401
+
402
+ function logAt(log, level, ...args) {
403
+ if (log === null || typeof log !== 'object') return
404
+ const write = log[level]
405
+ if (typeof write !== 'function') return
406
+ try {
407
+ write.call(log, ...args)
408
+ } catch {
409
+ // Logging must never take the extraction pipeline down.
410
+ }
411
+ }
412
+
413
+ /**
414
+ * One manifest line per existing note:
415
+ * `- [type] file.md (updated ISO-8601): Name — description`
416
+ * The prompt explains that everything before the colon is bookkeeping. The
417
+ * character budget keeps the whole prompt small even for a full space.
418
+ */
419
+ function manifestLine(note) {
420
+ const file = typeof note?.file === 'string' ? note.file : ''
421
+ if (file === '') return ''
422
+ const type = typeof note?.type === 'string' ? note.type : 'project'
423
+ const name = collapseLine(typeof note?.name === 'string' ? note.name : file) || file
424
+ const description = typeof note?.description === 'string' ? collapseLine(note.description).slice(0, 240) : ''
425
+ const updated = typeof note?.updated === 'string' ? note.updated.trim() : ''
426
+ const when = updated === '' ? 'updated time unknown' : `updated ${updated}`
427
+ const topic = description === '' ? name : `${name} — ${description}`
428
+ return `- [${type}] ${file} (${when}): ${topic}`
429
+ }
430
+
431
+ function formatManifest(notes) {
432
+ if (!Array.isArray(notes) || notes.length === 0) return ''
433
+ const lines = []
434
+ let chars = 0
435
+ for (const note of notes.slice(0, MANIFEST_LIMIT)) {
436
+ const line = manifestLine(note)
437
+ if (line === '') continue
438
+ if (chars + line.length > MANIFEST_MAX_CHARS) break
439
+ lines.push(line)
440
+ chars += line.length + 1
441
+ }
442
+ return lines.join('\n')
443
+ }
444
+
445
+ async function collectReply(llm, request) {
446
+ const stream = llm.stream(request)
447
+ if (
448
+ stream === null ||
449
+ (typeof stream !== 'object' && typeof stream !== 'function') ||
450
+ typeof stream[Symbol.asyncIterator] !== 'function'
451
+ ) {
452
+ throw new Error('llm.stream did not return an async iterable')
453
+ }
454
+ let text = ''
455
+ let failure = null
456
+ for await (const chunk of stream) {
457
+ if (chunk === null || typeof chunk !== 'object') continue
458
+ if (chunk.type === 'text-delta' && typeof chunk.text === 'string') {
459
+ text += chunk.text
460
+ } else if (chunk.type === 'finish') {
461
+ const kind = chunk.reason?.kind
462
+ if (kind === 'error' || kind === 'aborted') failure = kind
463
+ }
464
+ }
465
+ return { text, failure }
466
+ }
467
+
468
+ export function createExtractor(options = {}) {
469
+ const store = options.store ?? null
470
+ const settings = normalizeExtractConfig(options.config)
471
+ const log = options.log ?? null
472
+ const getRoute = typeof options.getRoute === 'function' ? options.getRoute : null
473
+ const spaceOf = typeof options.spaceOf === 'function' ? options.spaceOf : null
474
+ const getLlm =
475
+ typeof options.getLlm === 'function'
476
+ ? options.getLlm
477
+ : typeof options.llm === 'function'
478
+ ? options.llm
479
+ : options.llm === undefined || options.llm === null
480
+ ? null
481
+ : () => options.llm
482
+ const digestMaxBytes =
483
+ Number.isFinite(options.digestMaxBytes) && options.digestMaxBytes > 0
484
+ ? Math.trunc(options.digestMaxBytes)
485
+ : DEFAULT_DIGEST_MAX_BYTES
486
+ /** @type {Map<string, object>} */
487
+ const sessions = new Map()
488
+
489
+ function pruneSessions() {
490
+ if (sessions.size < MAX_SESSIONS) return
491
+ const idle = [...sessions.values()].filter(state => state.inFlight === null)
492
+ idle.sort((left, right) => left.lastSeen - right.lastSeen)
493
+ const excess = sessions.size - MAX_SESSIONS + 1
494
+ for (const state of idle.slice(0, Math.max(1, excess))) sessions.delete(state.id)
495
+ }
496
+
497
+ function ensureState(session) {
498
+ const id = sessionIdOf(session)
499
+ if (id === null) return null
500
+ let state = sessions.get(id)
501
+ if (state === undefined) {
502
+ pruneSessions()
503
+ state = {
504
+ id,
505
+ digest: createDigest({ maxBytes: digestMaxBytes }),
506
+ lastExtractedSeq: null,
507
+ lastEventSeq: null,
508
+ inFlight: null,
509
+ route: null,
510
+ lastSeen: Date.now(),
511
+ }
512
+ sessions.set(id, state)
513
+ }
514
+ state.lastSeen = Date.now()
515
+ return state
516
+ }
517
+
518
+ function rememberRoute(state, provider, model) {
519
+ if (typeof provider !== 'string' || provider.trim() === '') return
520
+ if (typeof model !== 'string' || model.trim() === '') return
521
+ state.route = { provider: provider.trim(), model: model.trim() }
522
+ }
523
+
524
+ /**
525
+ * getRoute is authoritative when provided (null means "no route, skip").
526
+ * When the host does not pass getRoute, fall back to the last route recorded
527
+ * in this session's request/context, request/header, or assistant message
528
+ * source events.
529
+ */
530
+ function learnRoute(state, event) {
531
+ if (getRoute !== null) return
532
+ const data = event.data ?? {}
533
+ if (event.type === 'request/context') {
534
+ rememberRoute(state, data.provider, data.model)
535
+ } else if (event.type === 'request/header') {
536
+ const config = data.header?.config
537
+ if (config !== null && typeof config === 'object') rememberRoute(state, config.provider, config.model)
538
+ } else if (event.type === 'assistant/message') {
539
+ const source = data.message?.source
540
+ if (source !== null && typeof source === 'object' && source.kind === 'model') {
541
+ rememberRoute(state, source.provider, source.model)
542
+ }
543
+ }
544
+ }
545
+
546
+ function resolveRoute(session, state) {
547
+ let route = null
548
+ if (getRoute !== null) {
549
+ try {
550
+ route = getRoute(session)
551
+ } catch (error) {
552
+ logAt(log, 'warn', 'dsh-memory: route lookup failed: %o', error)
553
+ return null
554
+ }
555
+ } else {
556
+ route = state.route
557
+ }
558
+ if (route === null || typeof route !== 'object') return null
559
+ const provider = typeof route.provider === 'string' ? route.provider.trim() : ''
560
+ let model = typeof route.model === 'string' ? route.model.trim() : ''
561
+ if (settings.model !== '') model = settings.model
562
+ if (provider === '' || model === '') return null
563
+ return { provider, model }
564
+ }
565
+
566
+ function resolveLlm() {
567
+ if (getLlm === null) return null
568
+ try {
569
+ const llm = getLlm()
570
+ if (llm === null || llm === undefined) return null
571
+ if ((typeof llm === 'object' || typeof llm === 'function') && typeof llm.stream === 'function') return llm
572
+ return null
573
+ } catch (error) {
574
+ logAt(log, 'warn', 'dsh-memory: llm lookup failed: %o', error)
575
+ return null
576
+ }
577
+ }
578
+
579
+ function resolveSpace(session) {
580
+ if (spaceOf === null) return null
581
+ try {
582
+ const space = spaceOf(session)
583
+ if (space === null || typeof space !== 'object') return null
584
+ const key = typeof space.key === 'string' ? space.key.trim() : ''
585
+ return key === '' ? null : { key }
586
+ } catch (error) {
587
+ logAt(log, 'warn', 'dsh-memory: workspace space lookup failed: %o', error)
588
+ return null
589
+ }
590
+ }
591
+
592
+ /**
593
+ * Move the extraction cursor after every attempt, success or failure: a bad
594
+ * reply must never be retried in a loop, and the cursor doubles as the start
595
+ * of the incremental window for the next extraction.
596
+ */
597
+ function advance(state, seq) {
598
+ if (typeof seq !== 'number' || !Number.isFinite(seq)) return
599
+ state.lastExtractedSeq = state.lastExtractedSeq === null ? seq : Math.max(state.lastExtractedSeq, seq)
600
+ }
601
+
602
+ function seqFor(event, state) {
603
+ if (typeof event.seq === 'number' && Number.isFinite(event.seq)) return event.seq
604
+ if (state.lastEventSeq !== null) return state.lastEventSeq
605
+ return lastSeq(state.digest)
606
+ }
607
+
608
+ async function readManifest(spaceKey) {
609
+ try {
610
+ return formatManifest(await store.listNotes(spaceKey))
611
+ } catch (error) {
612
+ logAt(log, 'debug', 'dsh-memory: cannot read notes for the extraction manifest: %o', error)
613
+ return ''
614
+ }
615
+ }
616
+
617
+ async function runExtraction(session, state, seq) {
618
+ if (!settings.enabled) return { skipped: true, reason: 'extraction disabled' }
619
+ if (digestCharsSince(state.digest, state.lastExtractedSeq) === 0) {
620
+ return { skipped: true, reason: 'no new conversation text' }
621
+ }
622
+ if (store === null) return { skipped: true, reason: 'no store' }
623
+ const space = resolveSpace(session)
624
+ if (space === null) return { skipped: true, reason: 'no workspace space' }
625
+ const route = resolveRoute(session, state)
626
+ if (route === null) {
627
+ logAt(log, 'debug', 'dsh-memory: extraction skipped for %s: no model route', state.id)
628
+ return { skipped: true, reason: 'no model route' }
629
+ }
630
+ const llm = resolveLlm()
631
+ if (llm === null) {
632
+ logAt(log, 'debug', 'dsh-memory: extraction skipped for %s: no llm service', state.id)
633
+ return { skipped: true, reason: 'no llm service' }
634
+ }
635
+
636
+ const manifest = await readManifest(space.key)
637
+ // P3: only the text newer than the last extraction cursor goes to the model.
638
+ // The digest window is a byte-bounded cache; the prompt tail is char-bounded
639
+ // (~8K) so repeated extraction never resends the whole conversation.
640
+ const isIncremental = state.lastExtractedSeq !== null
641
+ const conversation = digestTextSince(state.digest, state.lastExtractedSeq, {
642
+ maxChars: PROMPT_CONVERSATION_MAX_CHARS,
643
+ })
644
+ const prompt = buildExtractPrompt({
645
+ conversation,
646
+ manifest,
647
+ maxPerTurn: settings.maxPerTurn,
648
+ noteBytes: settings.noteBytes,
649
+ isIncremental,
650
+ })
651
+
652
+ let reply
653
+ try {
654
+ reply = await collectReply(llm, {
655
+ provider: route.provider,
656
+ model: route.model,
657
+ messages: [{ role: 'user', content: [{ type: 'text', text: prompt }] }],
658
+ })
659
+ } catch (error) {
660
+ logAt(log, 'warn', 'dsh-memory: extraction model call failed: %o', error)
661
+ advance(state, seq)
662
+ return { skipped: true, reason: 'model call failed', error: errorMessage(error) }
663
+ }
664
+ if (reply.failure !== null) {
665
+ logAt(log, 'warn', 'dsh-memory: extraction stream finished with %s', reply.failure)
666
+ advance(state, seq)
667
+ return { skipped: true, reason: 'model call failed', error: `stream finished with ${reply.failure}` }
668
+ }
669
+
670
+ const parsed = parseExtraction(reply.text)
671
+ if (parsed.error !== undefined) {
672
+ logAt(log, 'warn', 'dsh-memory: dropped extraction reply: %s', parsed.error)
673
+ advance(state, seq)
674
+ return { skipped: true, reason: 'invalid model reply', error: parsed.error }
675
+ }
676
+
677
+ const deletes = parsed.deletes.slice(0, settings.maxPerTurn)
678
+ if (parsed.deletes.length > deletes.length) {
679
+ logAt(log, 'debug', 'dsh-memory: truncated %d delete(s) to the configured maximum of %d', parsed.deletes.length - deletes.length, settings.maxPerTurn)
680
+ }
681
+ const upserts = parsed.upserts.slice(0, settings.maxPerTurn)
682
+ if (parsed.upserts.length > upserts.length) {
683
+ logAt(
684
+ log,
685
+ 'debug',
686
+ 'dsh-memory: truncated %d upsert(s) to the configured maximum of %d',
687
+ parsed.upserts.length - upserts.length,
688
+ settings.maxPerTurn,
689
+ )
690
+ }
691
+
692
+ let applied
693
+ try {
694
+ applied = await applyExtraction({
695
+ store,
696
+ spaceKey: space.key,
697
+ parsed: { upserts, deletes },
698
+ sessionId: state.id,
699
+ seq,
700
+ })
701
+ } catch (error) {
702
+ logAt(log, 'warn', 'dsh-memory: extraction apply failed: %o', error)
703
+ advance(state, seq)
704
+ return { skipped: true, reason: 'apply failed', error: errorMessage(error) }
705
+ }
706
+
707
+ if (applied.errors.length > 0) {
708
+ logAt(log, 'warn', 'dsh-memory: %d extracted note(s) failed: %o', applied.errors.length, applied.errors)
709
+ }
710
+ advance(state, seq)
711
+ logAt(
712
+ log,
713
+ 'debug',
714
+ 'dsh-memory: extraction wrote %d note(s) and deleted %d note(s)',
715
+ applied.written.length,
716
+ applied.deleted.length,
717
+ )
718
+ return { skipped: false, written: applied.written, deleted: applied.deleted, errors: applied.errors }
719
+ }
720
+
721
+ function execute(session, state, seq) {
722
+ if (state.inFlight !== null) return state.inFlight
723
+ const promise = runExtraction(session, state, seq)
724
+ .catch(error => {
725
+ logAt(log, 'warn', 'dsh-memory: extraction failed: %o', error)
726
+ advance(state, seq)
727
+ return { skipped: true, reason: 'extraction failed', error: errorMessage(error) }
728
+ })
729
+ .finally(() => {
730
+ if (state.inFlight === promise) state.inFlight = null
731
+ })
732
+ state.inFlight = promise
733
+ return promise
734
+ }
735
+
736
+ function onSessionEvent(session, event) {
737
+ try {
738
+ if (session === null || typeof session !== 'object') return
739
+ if (isSubagentSession(session)) return
740
+ const state = ensureState(session)
741
+ if (state === null) return
742
+ if (event === null || typeof event !== 'object') return
743
+
744
+ if (typeof event.seq === 'number' && Number.isFinite(event.seq)) {
745
+ state.lastEventSeq = state.lastEventSeq === null ? event.seq : Math.max(state.lastEventSeq, event.seq)
746
+ }
747
+ learnRoute(state, event)
748
+ state.digest = appendDigest(state.digest, event)
749
+
750
+ if (event.type !== 'turn/end') return
751
+ if (!settings.enabled) {
752
+ logAt(log, 'debug', 'dsh-memory: extraction disabled; ignoring turn end')
753
+ return
754
+ }
755
+ if (state.inFlight !== null) {
756
+ logAt(log, 'debug', 'dsh-memory: extraction already running for %s; keeping text for the next turn', state.id)
757
+ return
758
+ }
759
+ const newChars = digestCharsSince(state.digest, state.lastExtractedSeq)
760
+ if (newChars === 0) {
761
+ logAt(log, 'debug', 'dsh-memory: no conversation text to extract')
762
+ return
763
+ }
764
+ if (newChars < settings.minNewChars) return
765
+ void execute(session, state, seqFor(event, state))
766
+ } catch (error) {
767
+ logAt(log, 'warn', 'dsh-memory: extraction event handling failed: %o', error)
768
+ }
769
+ }
770
+
771
+ async function flush(session) {
772
+ try {
773
+ if (session === null || typeof session !== 'object') return { skipped: true, reason: 'no session' }
774
+ if (isSubagentSession(session)) return { skipped: true, reason: 'subagent session' }
775
+ const id = sessionIdOf(session)
776
+ if (id === null) return { skipped: true, reason: 'no session' }
777
+ const state = sessions.get(id)
778
+ if (state === undefined) return { skipped: true, reason: 'no session state' }
779
+
780
+ if (state.inFlight !== null) {
781
+ const running = state.inFlight
782
+ let settled = null
783
+ try {
784
+ settled = await running
785
+ } catch {
786
+ settled = null
787
+ }
788
+ if (state.inFlight === null && digestCharsSince(state.digest, state.lastExtractedSeq) === 0) {
789
+ return settled ?? { skipped: true, reason: 'no new conversation text' }
790
+ }
791
+ if (state.inFlight !== null) return { skipped: true, reason: 'extraction already running' }
792
+ }
793
+
794
+ if (!settings.enabled) return { skipped: true, reason: 'extraction disabled' }
795
+ const seq = state.lastEventSeq ?? lastSeq(state.digest) ?? state.lastExtractedSeq
796
+ if (seq === null) return { skipped: true, reason: 'no events' }
797
+ if (digestCharsSince(state.digest, state.lastExtractedSeq) === 0) {
798
+ return { skipped: true, reason: 'no new conversation text' }
799
+ }
800
+ return await execute(session, state, seq)
801
+ } catch (error) {
802
+ logAt(log, 'warn', 'dsh-memory: extraction flush failed: %o', error)
803
+ return { skipped: true, reason: 'flush failed', error: errorMessage(error) }
804
+ }
805
+ }
806
+
807
+ function lastSeqFor(sessionId) {
808
+ const state = sessions.get(String(sessionId ?? ''))
809
+ return state === undefined ? null : state.lastExtractedSeq
810
+ }
811
+
812
+ return { onSessionEvent, flush, lastSeqFor }
813
+ }