dsh-plugin-memory 0.11.0 → 0.13.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 +32 -0
- package/README.md +25 -2
- package/README.zh.md +25 -2
- package/docs/PROACTIVE-PROTOCOL.md +81 -0
- package/lib/boot.js +22 -3
- package/lib/client.js +169 -5
- package/lib/config-store.js +19 -1
- package/lib/digest-guard.js +35 -1
- package/lib/growth.js +201 -0
- package/lib/index.js +116 -4
- package/lib/proactive-lock.js +122 -0
- package/lib/recall-nudge.js +179 -2
- package/lib/schema.js +10 -0
- package/lib/tone.js +86 -0
- package/lib/types/index.d.ts +44 -0
- package/package.json +3 -2
package/lib/index.js
CHANGED
|
@@ -52,6 +52,11 @@
|
|
|
52
52
|
* | `registerSkill` | `true` | register the embedded `memory` skill |
|
|
53
53
|
* | `scaffold` | `true` | create the store layout + templates when missing |
|
|
54
54
|
* | `configFile` | `<dshHome>/memory.json` | user-facing config file (Settings panel) |
|
|
55
|
+
* | `proactiveCooldownSeconds` | `180` | shared proactive-speech lock with heartbeat (0 = off) |
|
|
56
|
+
* | `toneGuideEnabled` | `true` | inject the context-sensitive tone section after SOUL |
|
|
57
|
+
* | `toneIntensity` | `low` | `low` / `medium` / `off` (pure engineering voice) |
|
|
58
|
+
* | `growthRecapEnabled` | `true` | weekly growth recap on the recall channel |
|
|
59
|
+
* | `growthRecapIntervalDays` | `7` | days between growth recaps |
|
|
55
60
|
*
|
|
56
61
|
* `enabled`, `memoryDir`, `autoInject` and `registerSkill` are editable in
|
|
57
62
|
* the Settings panel and hot-apply: boot injection, the skill registration
|
|
@@ -99,6 +104,8 @@ import { MemoryConfigStore } from './config-store.js'
|
|
|
99
104
|
import { SettingsSchema } from './schema.js'
|
|
100
105
|
import { DigestGuard } from './digest-guard.js'
|
|
101
106
|
import { RecallNudge } from './recall-nudge.js'
|
|
107
|
+
import { buildToneGuide } from './tone.js'
|
|
108
|
+
import { claimProactiveLock, defaultProactiveCooldownPath } from './proactive-lock.js'
|
|
102
109
|
import { AutoCommitter } from './autocommit.js'
|
|
103
110
|
import { ActivityTracker } from './activity-tracker.js'
|
|
104
111
|
import {
|
|
@@ -118,6 +125,7 @@ export const INSIGHTS_ROUTE_PATH = '/api/memory/insights'
|
|
|
118
125
|
|
|
119
126
|
/** Read-only HTTP route serving the memory graph (nodes + edges). */
|
|
120
127
|
export const GRAPH_ROUTE_PATH = '/api/memory/graph'
|
|
128
|
+
export const CONTROL_ROUTE_PATH = '/api/memory/control'
|
|
121
129
|
|
|
122
130
|
export const inject = ['systemPrompt', 'skills', 'agents']
|
|
123
131
|
|
|
@@ -155,6 +163,16 @@ export const Config = z.object({
|
|
|
155
163
|
recallIntervalMinMinutes: z.number().default(30),
|
|
156
164
|
recallIntervalMaxMinutes: z.number().default(240),
|
|
157
165
|
recallMaxPerSession: z.number().default(3),
|
|
166
|
+
// Shared proactive-speech arbitration with dsh-plugin-heartbeat: one JSON
|
|
167
|
+
// file, claimed before any synthetic followup. 180s default; 0 = off.
|
|
168
|
+
proactiveCooldownSeconds: z.number().default(180),
|
|
169
|
+
// Tone drift: inject a bounded "how to shift register by context" section
|
|
170
|
+
// after SOUL. `off` restores the pre-0.12.0 boot block exactly.
|
|
171
|
+
toneGuideEnabled: z.boolean().default(true),
|
|
172
|
+
toneIntensity: z.union([z.const('low'), z.const('medium'), z.const('off')]).default('low'),
|
|
173
|
+
// Weekly growth recap, delivered on the recall channel.
|
|
174
|
+
growthRecapEnabled: z.boolean().default(true),
|
|
175
|
+
growthRecapIntervalDays: z.number().default(7),
|
|
158
176
|
// Auto-commit: keep the store's git history current after a quiet period.
|
|
159
177
|
autoCommit: z.boolean().default(true),
|
|
160
178
|
autoCommitQuietSeconds: z.number().default(60),
|
|
@@ -199,6 +217,11 @@ export function apply(ctx, config = {}) {
|
|
|
199
217
|
recallIntervalMinMinutes: config.recallIntervalMinMinutes ?? 30,
|
|
200
218
|
recallIntervalMaxMinutes: config.recallIntervalMaxMinutes ?? 240,
|
|
201
219
|
recallMaxPerSession: config.recallMaxPerSession ?? 3,
|
|
220
|
+
proactiveCooldownSeconds: config.proactiveCooldownSeconds ?? 180,
|
|
221
|
+
toneGuideEnabled: config.toneGuideEnabled !== false,
|
|
222
|
+
toneIntensity: ['low', 'medium', 'off'].includes(config.toneIntensity) ? config.toneIntensity : 'low',
|
|
223
|
+
growthRecapEnabled: config.growthRecapEnabled !== false,
|
|
224
|
+
growthRecapIntervalDays: config.growthRecapIntervalDays ?? 7,
|
|
202
225
|
},
|
|
203
226
|
})
|
|
204
227
|
|
|
@@ -279,9 +302,16 @@ export function apply(ctx, config = {}) {
|
|
|
279
302
|
// Per-agent gate: no agent context (e.g. a global preview) injects
|
|
280
303
|
// unconditionally; an agent injects only once it has spoken and is
|
|
281
304
|
// the active session.
|
|
305
|
+
const resolved = store.get()
|
|
282
306
|
const agent = context?.agent
|
|
283
|
-
if (agent && !tracker.shouldInject(agent.id,
|
|
284
|
-
|
|
307
|
+
if (agent && !tracker.shouldInject(agent.id, resolved)) return ''
|
|
308
|
+
// Tone drift rides on the boot block (charged to its budget). Read
|
|
309
|
+
// live from the store so the Settings select applies on the next
|
|
310
|
+
// prompt build without a reload.
|
|
311
|
+
const toneGuide = resolved.toneGuideEnabled
|
|
312
|
+
? buildToneGuide({ intensity: resolved.toneIntensity, language: 'zh' })
|
|
313
|
+
: ''
|
|
314
|
+
return renderBootBlock(memoryDir, { bootFiles, bootMaxChars, bootFileBudgets, toneGuide })
|
|
285
315
|
},
|
|
286
316
|
})
|
|
287
317
|
} else {
|
|
@@ -363,6 +393,14 @@ export function apply(ctx, config = {}) {
|
|
|
363
393
|
}, 'memory.page-access()')
|
|
364
394
|
}
|
|
365
395
|
|
|
396
|
+
/** Claim the cross-plugin proactive lock (see lib/proactive-lock.js). */
|
|
397
|
+
const claimSharedProactiveLock = ({ now, cooldownSeconds }) => claimProactiveLock({
|
|
398
|
+
path: defaultProactiveCooldownPath(),
|
|
399
|
+
speaker: 'memory',
|
|
400
|
+
cooldownSeconds,
|
|
401
|
+
now,
|
|
402
|
+
})
|
|
403
|
+
|
|
366
404
|
// Digest guard: one per live ROOT agent, so a skipped end-of-session
|
|
367
405
|
// digest is caught mechanically instead of relying on the agent's
|
|
368
406
|
// self-discipline. Independent of dsh-plugin-heartbeat — the nudge is
|
|
@@ -381,12 +419,14 @@ export function apply(ctx, config = {}) {
|
|
|
381
419
|
maxPerSession: config.digestNudgeMaxPerSession,
|
|
382
420
|
deferUntilUserSpeaks: resolved.deferUntilUserSpeaks,
|
|
383
421
|
activeSessionOnly: resolved.activeSessionOnly,
|
|
422
|
+
proactiveCooldownSeconds: resolved.proactiveCooldownSeconds,
|
|
384
423
|
}
|
|
385
424
|
},
|
|
386
425
|
getMemoryDir: () => currentMemoryDir,
|
|
387
426
|
agents: ctx.agents,
|
|
388
427
|
tracker,
|
|
389
428
|
logger: ctx.logger,
|
|
429
|
+
claimLock: claimSharedProactiveLock,
|
|
390
430
|
})
|
|
391
431
|
agent.ctx.effect(() => {
|
|
392
432
|
guard.start()
|
|
@@ -402,7 +442,10 @@ export function apply(ctx, config = {}) {
|
|
|
402
442
|
// Recall nudge: one per live ROOT agent, on the same idle boundary as the
|
|
403
443
|
// digest guard but on a cadence (interval + per-session cap) instead of
|
|
404
444
|
// store staleness. Conversational only — it never writes the store.
|
|
405
|
-
|
|
445
|
+
// Live recall nudges by agent id: the settings-panel "review now" button
|
|
446
|
+
// reaches them through /api/memory/control (manual growth recap).
|
|
447
|
+
const nudges = new Map()
|
|
448
|
+
{
|
|
406
449
|
ctx.effect(() => {
|
|
407
450
|
const stopCreated = ctx.on('agent/created', ({ agent }) => {
|
|
408
451
|
if (!ctx.agents.roots().includes(agent)) return
|
|
@@ -410,22 +453,35 @@ export function apply(ctx, config = {}) {
|
|
|
410
453
|
readConfig: () => {
|
|
411
454
|
const resolved = store.get()
|
|
412
455
|
return {
|
|
413
|
-
enabled: resolved.enabled
|
|
456
|
+
enabled: resolved.enabled,
|
|
457
|
+
recallEnabled: resolved.recallEnabled !== false,
|
|
414
458
|
minMinutes: resolved.recallIntervalMinMinutes,
|
|
415
459
|
maxMinutes: resolved.recallIntervalMaxMinutes,
|
|
416
460
|
maxPerSession: resolved.recallMaxPerSession,
|
|
417
461
|
deferUntilUserSpeaks: resolved.deferUntilUserSpeaks,
|
|
418
462
|
activeSessionOnly: resolved.activeSessionOnly,
|
|
463
|
+
proactiveCooldownSeconds: resolved.proactiveCooldownSeconds,
|
|
464
|
+
}
|
|
465
|
+
},
|
|
466
|
+
readGrowthConfig: () => {
|
|
467
|
+
const resolved = store.get()
|
|
468
|
+
return {
|
|
469
|
+
enabled: resolved.growthRecapEnabled !== false,
|
|
470
|
+
intervalDays: resolved.growthRecapIntervalDays,
|
|
471
|
+
language: 'zh',
|
|
419
472
|
}
|
|
420
473
|
},
|
|
421
474
|
getMemoryDir: () => currentMemoryDir,
|
|
422
475
|
agents: ctx.agents,
|
|
423
476
|
tracker,
|
|
424
477
|
logger: ctx.logger,
|
|
478
|
+
claimLock: claimSharedProactiveLock,
|
|
425
479
|
})
|
|
480
|
+
nudges.set(agent.id, nudge)
|
|
426
481
|
agent.ctx.effect(() => {
|
|
427
482
|
nudge.start()
|
|
428
483
|
return () => {
|
|
484
|
+
nudges.delete(agent.id)
|
|
429
485
|
nudge.dispose()
|
|
430
486
|
}
|
|
431
487
|
})
|
|
@@ -482,6 +538,59 @@ export function apply(ctx, config = {}) {
|
|
|
482
538
|
webCtx.effect(() => disposeRoute, 'memory.config-route()')
|
|
483
539
|
ctx.logger?.info(`memory: config route at ${CONFIG_ROUTE_PATH} (store ${store.path})`)
|
|
484
540
|
|
|
541
|
+
// Manual proactive controls: today only "review my week now", which rides
|
|
542
|
+
// the same recall channel as the weekly recap (same message shape, same
|
|
543
|
+
// arbitration lock) but ignores the weekly cadence because the user asked.
|
|
544
|
+
const disposeControlRoute = webCtx.webServer.register({
|
|
545
|
+
kind: 'exact',
|
|
546
|
+
path: CONTROL_ROUTE_PATH,
|
|
547
|
+
handler: async (req, res) => {
|
|
548
|
+
try {
|
|
549
|
+
if (req.method !== 'POST') {
|
|
550
|
+
res.writeHead(405, { 'content-type': 'application/json; charset=utf-8' })
|
|
551
|
+
res.end(JSON.stringify({ error: 'method not allowed' }))
|
|
552
|
+
return
|
|
553
|
+
}
|
|
554
|
+
const chunks = []
|
|
555
|
+
for await (const chunk of req) chunks.push(chunk)
|
|
556
|
+
let body
|
|
557
|
+
try {
|
|
558
|
+
body = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}')
|
|
559
|
+
} catch {
|
|
560
|
+
res.writeHead(400, { 'content-type': 'application/json; charset=utf-8' })
|
|
561
|
+
res.end(JSON.stringify({ error: 'body must be JSON' }))
|
|
562
|
+
return
|
|
563
|
+
}
|
|
564
|
+
const action = typeof body?.action === 'string' ? body.action : ''
|
|
565
|
+
if (action !== 'growth-now') {
|
|
566
|
+
res.writeHead(400, { 'content-type': 'application/json; charset=utf-8' })
|
|
567
|
+
res.end(JSON.stringify({ error: `unknown action ${JSON.stringify(action)}` }))
|
|
568
|
+
return
|
|
569
|
+
}
|
|
570
|
+
const wanted = typeof body?.sessionId === 'string' ? body.sessionId : undefined
|
|
571
|
+
const candidates = [...nudges.entries()]
|
|
572
|
+
.filter(([id]) => wanted === undefined || id === wanted)
|
|
573
|
+
.map(([, nudge]) => nudge)
|
|
574
|
+
if (candidates.length === 0) {
|
|
575
|
+
res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' })
|
|
576
|
+
res.end(JSON.stringify({ ok: true, delivered: false, reason: 'no-session' }))
|
|
577
|
+
return
|
|
578
|
+
}
|
|
579
|
+
let last = { delivered: false, reason: 'no-session' }
|
|
580
|
+
for (const nudge of candidates) {
|
|
581
|
+
last = nudge.forceGrowthRecap()
|
|
582
|
+
if (last.delivered) break
|
|
583
|
+
}
|
|
584
|
+
res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' })
|
|
585
|
+
res.end(JSON.stringify(last.delivered ? { ok: true, delivered: true } : { ok: true, delivered: false, reason: last.reason }))
|
|
586
|
+
} catch (error) {
|
|
587
|
+
res.writeHead(500, { 'content-type': 'application/json; charset=utf-8' })
|
|
588
|
+
res.end(JSON.stringify({ error: error instanceof Error ? error.message : String(error) }))
|
|
589
|
+
}
|
|
590
|
+
},
|
|
591
|
+
})
|
|
592
|
+
webCtx.effect(() => disposeControlRoute, 'memory.control-route()')
|
|
593
|
+
|
|
485
594
|
// Read-only health dashboard payload. Built fresh on every request from the
|
|
486
595
|
// store on disk, so the panel always reflects the newest state and the
|
|
487
596
|
// plugin never caches a stale view of the user's memory.
|
|
@@ -558,3 +667,6 @@ export { renderBootBlock, ensureMemoryScaffold, SettingsSchema, MemoryConfigStor
|
|
|
558
667
|
export { touchPages, touchPageFile, extractReferencedPages, listPagePaths, accessSummary, today }
|
|
559
668
|
export { collectInsights, readRecentLog } from './insights.js'
|
|
560
669
|
export { buildMemoryGraph, EDGE_KINDS } from './graph.js'
|
|
670
|
+
export { buildToneGuide, TONE_INTENSITIES, TONE_GUIDE_MAX_LINES } from './tone.js'
|
|
671
|
+
export { claimProactiveLock, readProactiveLock, defaultProactiveCooldownPath } from './proactive-lock.js'
|
|
672
|
+
export { collectGrowth, renderGrowthRecap, growthRecapDue } from './growth.js'
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Proactive-speech arbitration: the shared "who may speak right now" lock.
|
|
3
|
+
*
|
|
4
|
+
* Two independent plugins can each decide, on their own timer, that the agent
|
|
5
|
+
* should say something unprompted — dsh-plugin-memory (recall / digest /
|
|
6
|
+
* growth recap) and dsh-plugin-heartbeat. Without arbitration both fire in the
|
|
7
|
+
* same quiet window and the user gets a burst of synthetic followups.
|
|
8
|
+
*
|
|
9
|
+
* They cannot import each other (plugin boundary: zero cross-plugin imports),
|
|
10
|
+
* so the protocol is a single JSON file both implementations understand:
|
|
11
|
+
*
|
|
12
|
+
* ```json
|
|
13
|
+
* { "version": 1, "speaker": "memory" | "heartbeat", "at": 1760000000000 }
|
|
14
|
+
* ```
|
|
15
|
+
*
|
|
16
|
+
* A speaker may claim only when the file is absent, corrupt, owns the same
|
|
17
|
+
* `speaker` name (its own lock), or the previous claim is older than the
|
|
18
|
+
* cooldown. Writes are atomic (tmp + rename) so a reader never sees a partial
|
|
19
|
+
* document; a corrupt file degrades to "no lock" because a broken cooldown
|
|
20
|
+
* must never silence the plugin forever.
|
|
21
|
+
*
|
|
22
|
+
* This module depends only on `node:*` builtins.
|
|
23
|
+
*
|
|
24
|
+
* @module dsh-plugin-memory/proactive-lock
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
|
|
28
|
+
import { homedir } from 'node:os'
|
|
29
|
+
import { dirname, join } from 'node:path'
|
|
30
|
+
|
|
31
|
+
/** File name of the shared arbitration protocol (same on both sides). */
|
|
32
|
+
export const PROACTIVE_COOLDOWN_FILENAME = 'proactive-cooldown.json'
|
|
33
|
+
|
|
34
|
+
/** Protocol version written into the file. */
|
|
35
|
+
export const PROACTIVE_LOCK_VERSION = 1
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* The shared cooldown file location: `${DSH_HOME||~/.dsh}/proactive-cooldown.json`.
|
|
39
|
+
* Both plugins resolve it the same way so they meet on the same file.
|
|
40
|
+
* @returns {string} absolute path
|
|
41
|
+
*/
|
|
42
|
+
export function defaultProactiveCooldownPath() {
|
|
43
|
+
return join(process.env.DSH_HOME || join(homedir(), '.dsh'), PROACTIVE_COOLDOWN_FILENAME)
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Read the current lock, tolerating every kind of damage.
|
|
48
|
+
*
|
|
49
|
+
* @param {string} path absolute lock-file path
|
|
50
|
+
* @returns {{version: number, speaker: string, at: number} | undefined}
|
|
51
|
+
* the parsed lock, or undefined when missing/corrupt (== no lock)
|
|
52
|
+
*/
|
|
53
|
+
export function readProactiveLock(path) {
|
|
54
|
+
if (typeof path !== 'string' || path.length === 0 || !existsSync(path)) return undefined
|
|
55
|
+
let raw
|
|
56
|
+
try {
|
|
57
|
+
raw = JSON.parse(readFileSync(path, 'utf8'))
|
|
58
|
+
} catch {
|
|
59
|
+
return undefined
|
|
60
|
+
}
|
|
61
|
+
if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return undefined
|
|
62
|
+
const at = Number(raw.at)
|
|
63
|
+
if (!Number.isFinite(at)) return undefined
|
|
64
|
+
return {
|
|
65
|
+
version: Number.isFinite(Number(raw.version)) ? Number(raw.version) : PROACTIVE_LOCK_VERSION,
|
|
66
|
+
speaker: typeof raw.speaker === 'string' && raw.speaker.length > 0 ? raw.speaker : 'unknown',
|
|
67
|
+
at,
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Try to take the proactive-speech lock.
|
|
73
|
+
*
|
|
74
|
+
* The lock is advisory and single-file: claim right before injecting a
|
|
75
|
+
* followup, and if it is refused, skip this round (the next scheduled trigger
|
|
76
|
+
* tries again). `cooldownSeconds <= 0` turns arbitration off entirely (the
|
|
77
|
+
* config escape hatch) and writes nothing.
|
|
78
|
+
*
|
|
79
|
+
* @param {object} [options]
|
|
80
|
+
* @param {string} [options.path] lock-file path (defaults to the shared path)
|
|
81
|
+
* @param {string} [options.speaker] who is speaking ('memory' here)
|
|
82
|
+
* @param {number} [options.cooldownSeconds] arbitration window; default 180, 0 = off
|
|
83
|
+
* @param {number} [options.now] epoch ms (injectable for tests)
|
|
84
|
+
* @returns {{ ok: true, disabled?: true } | { ok: false, deferredBy: string }}
|
|
85
|
+
*/
|
|
86
|
+
export function claimProactiveLock(options = {}) {
|
|
87
|
+
const path = typeof options.path === 'string' && options.path.length > 0
|
|
88
|
+
? options.path
|
|
89
|
+
: defaultProactiveCooldownPath()
|
|
90
|
+
const speaker = typeof options.speaker === 'string' && options.speaker.length > 0
|
|
91
|
+
? options.speaker
|
|
92
|
+
: 'memory'
|
|
93
|
+
const rawCooldown = Number(options.cooldownSeconds ?? 180)
|
|
94
|
+
const cooldownSeconds = Number.isFinite(rawCooldown) ? Math.max(0, rawCooldown) : 180
|
|
95
|
+
const rawNow = Number(options.now ?? Date.now())
|
|
96
|
+
const now = Number.isFinite(rawNow) ? rawNow : Date.now()
|
|
97
|
+
|
|
98
|
+
// Explicitly disabled: everyone may speak, and we leave the protocol file
|
|
99
|
+
// untouched so the other side's state is not clobbered for nothing.
|
|
100
|
+
if (cooldownSeconds === 0) return { ok: true, disabled: true }
|
|
101
|
+
|
|
102
|
+
const current = readProactiveLock(path)
|
|
103
|
+
if (current !== undefined && current.speaker !== speaker) {
|
|
104
|
+
const cooldownMs = cooldownSeconds * 1000
|
|
105
|
+
if (current.at > now - cooldownMs) {
|
|
106
|
+
return { ok: false, deferredBy: current.speaker }
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const lock = { version: PROACTIVE_LOCK_VERSION, speaker, at: now }
|
|
111
|
+
try {
|
|
112
|
+
mkdirSync(dirname(path), { recursive: true })
|
|
113
|
+
const tmp = `${path}.tmp`
|
|
114
|
+
writeFileSync(tmp, `${JSON.stringify(lock)}\n`, 'utf8')
|
|
115
|
+
renameSync(tmp, path)
|
|
116
|
+
} catch {
|
|
117
|
+
// An unwritable lock file must not break the caller: arbitration is
|
|
118
|
+
// best-effort, the message itself is still worth delivering.
|
|
119
|
+
return { ok: true, disabled: true }
|
|
120
|
+
}
|
|
121
|
+
return { ok: true }
|
|
122
|
+
}
|
package/lib/recall-nudge.js
CHANGED
|
@@ -26,6 +26,13 @@ import { randomUUID } from 'node:crypto'
|
|
|
26
26
|
import { existsSync, readFileSync } from 'node:fs'
|
|
27
27
|
import { join } from 'node:path'
|
|
28
28
|
import { parseLogEntries } from './boot.js'
|
|
29
|
+
import {
|
|
30
|
+
GROWTH_STATE_FILENAME,
|
|
31
|
+
collectGrowth,
|
|
32
|
+
growthRecapDue,
|
|
33
|
+
renderGrowthRecap,
|
|
34
|
+
writeGrowthState,
|
|
35
|
+
} from './growth.js'
|
|
29
36
|
|
|
30
37
|
/** Poll cadence while the agent sits idle (ms). Short enough to feel prompt, long enough to stay cheap. */
|
|
31
38
|
const POLL_INTERVAL_MS = 30000
|
|
@@ -102,9 +109,34 @@ export function buildRecallNudgeMessage(candidates) {
|
|
|
102
109
|
}
|
|
103
110
|
}
|
|
104
111
|
|
|
112
|
+
/**
|
|
113
|
+
* Build the growth-recap followup: the weekly "what I kept this week" line,
|
|
114
|
+
* delivered on the same channel as a recall and in the same message shape.
|
|
115
|
+
* @param {string} recap first-person recap text from renderGrowthRecap()
|
|
116
|
+
* @returns {{ id: string, role: 'user', content: [{type:'text', text:string}], source: {kind:'plugin:memory'} }}
|
|
117
|
+
*/
|
|
118
|
+
export function buildGrowthRecapNudgeMessage(recap) {
|
|
119
|
+
const text = typeof recap === 'string' ? recap.trim() : ''
|
|
120
|
+
return {
|
|
121
|
+
id: `memory-growth-${randomUUID()}`,
|
|
122
|
+
role: 'user',
|
|
123
|
+
content: [{
|
|
124
|
+
type: 'text',
|
|
125
|
+
text: [
|
|
126
|
+
'【小蓝成长回顾】距离上次回顾有一阵子了。下面是我这周真实记住的事(第一人称,最多五句):',
|
|
127
|
+
text,
|
|
128
|
+
'用自然口语说给阿周听,别念成汇报、别加戏,也不要编造这里没写的事;说完继续手头的事即可。',
|
|
129
|
+
].filter(Boolean).join('\n'),
|
|
130
|
+
}],
|
|
131
|
+
source: { kind: 'plugin:memory' },
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
105
135
|
/**
|
|
106
136
|
* @typedef {object} RecallNudgeOptions
|
|
107
|
-
* @property {() => { enabled: boolean, minMinutes: number, maxMinutes: number, maxPerSession: number, deferUntilUserSpeaks?: boolean, activeSessionOnly?: boolean }} readConfig
|
|
137
|
+
* @property {() => { enabled: boolean, minMinutes: number, maxMinutes: number, maxPerSession: number, deferUntilUserSpeaks?: boolean, activeSessionOnly?: boolean, proactiveCooldownSeconds?: number }} readConfig
|
|
138
|
+
* @property {() => { enabled: boolean, intervalDays: number, language?: 'zh'|'en' }} [readGrowthConfig] weekly-recap config; omitted = no recap
|
|
139
|
+
* @property {(options: { now: number, cooldownSeconds: number }) => { ok: boolean, deferredBy?: string }} [claimLock] shared proactive lock (see proactive-lock.js)
|
|
108
140
|
* @property {() => string} getMemoryDir resolve the current store dir on every check
|
|
109
141
|
* @property {unknown} [agents] optional live-agent registry for liveness checks
|
|
110
142
|
* @property {import('./activity-tracker.js').ActivityTracker} [tracker] gate source: has-user-spoken + active-session
|
|
@@ -128,6 +160,8 @@ export class RecallNudge {
|
|
|
128
160
|
this.agents = options.agents
|
|
129
161
|
this.tracker = options.tracker
|
|
130
162
|
this.logger = options.logger
|
|
163
|
+
this.claimLock = options.claimLock
|
|
164
|
+
this.readGrowthConfig = options.readGrowthConfig
|
|
131
165
|
this.pollIntervalMs = options.pollIntervalMs ?? POLL_INTERVAL_MS
|
|
132
166
|
this.disposed = false
|
|
133
167
|
this.stopTurnStopping = undefined
|
|
@@ -163,6 +197,62 @@ export class RecallNudge {
|
|
|
163
197
|
}
|
|
164
198
|
}
|
|
165
199
|
|
|
200
|
+
/**
|
|
201
|
+
* Deliver one growth recap now because the user asked for it (settings-panel
|
|
202
|
+
* "review now"). Manual means: the weekly cadence is not required and the
|
|
203
|
+
* per-session recall cap is not consulted, but the plugin must still be
|
|
204
|
+
* enabled, the agent idle, growth material must exist, and the shared
|
|
205
|
+
* speech-floor lock still wins. Never throws.
|
|
206
|
+
*
|
|
207
|
+
* @returns {{ delivered: boolean, reason: string }}
|
|
208
|
+
*/
|
|
209
|
+
forceGrowthRecap() {
|
|
210
|
+
if (this.disposed) return { delivered: false, reason: 'disposed' }
|
|
211
|
+
if (this.agents && this.agents.get(this.agent.id) !== this.agent) return { delivered: false, reason: 'agent-gone' }
|
|
212
|
+
let config
|
|
213
|
+
try {
|
|
214
|
+
config = this.readConfig()
|
|
215
|
+
} catch (error) {
|
|
216
|
+
this.logger?.warn?.(`memory: growth-now config read failed: ${error instanceof Error ? error.message : String(error)}`)
|
|
217
|
+
return { delivered: false, reason: 'error' }
|
|
218
|
+
}
|
|
219
|
+
if (!config || config.enabled !== true) return { delivered: false, reason: 'disabled' }
|
|
220
|
+
if (this.agent.status !== 'idle') return { delivered: false, reason: 'busy' }
|
|
221
|
+
if (typeof this.readGrowthConfig !== 'function') return { delivered: false, reason: 'growth-disabled' }
|
|
222
|
+
let growthConfig
|
|
223
|
+
try {
|
|
224
|
+
growthConfig = this.readGrowthConfig()
|
|
225
|
+
} catch {
|
|
226
|
+
return { delivered: false, reason: 'growth-disabled' }
|
|
227
|
+
}
|
|
228
|
+
if (!growthConfig || growthConfig.enabled !== true) return { delivered: false, reason: 'growth-disabled' }
|
|
229
|
+
const now = Date.now()
|
|
230
|
+
try {
|
|
231
|
+
const storeDir = this.getMemoryDir()
|
|
232
|
+
const intervalDays = Math.max(1, Number(growthConfig.intervalDays ?? 7))
|
|
233
|
+
const growth = collectGrowth({ storeDir, sinceDays: intervalDays, max: 5, now })
|
|
234
|
+
if (growth.entries.length === 0 && growth.pagesChanged === 0) return { delivered: false, reason: 'no-content' }
|
|
235
|
+
const recap = renderGrowthRecap({
|
|
236
|
+
...growth,
|
|
237
|
+
language: growthConfig.language === 'en' ? 'en' : 'zh',
|
|
238
|
+
})
|
|
239
|
+
if (recap.length === 0) return { delivered: false, reason: 'no-content' }
|
|
240
|
+
const claim = this.claimProactive(now, config)
|
|
241
|
+
if (!claim.ok) return { delivered: false, reason: 'deferred', deferredBy: claim.deferredBy }
|
|
242
|
+
try {
|
|
243
|
+
writeGrowthState(join(storeDir, GROWTH_STATE_FILENAME), now)
|
|
244
|
+
} catch (error) {
|
|
245
|
+
this.logger?.warn?.(`memory: growth-now state write failed: ${error instanceof Error ? error.message : String(error)}`)
|
|
246
|
+
}
|
|
247
|
+
this.agent.followup(buildGrowthRecapNudgeMessage(recap))
|
|
248
|
+
this.recalls += 1
|
|
249
|
+
return { delivered: true, reason: 'delivered' }
|
|
250
|
+
} catch (error) {
|
|
251
|
+
this.logger?.warn?.(`memory: growth-now failed: ${error instanceof Error ? error.message : String(error)}`)
|
|
252
|
+
return { delivered: false, reason: 'error' }
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
166
256
|
/** Cancel subscriptions and the poll timer; the nudge stops observing. */
|
|
167
257
|
dispose() {
|
|
168
258
|
this.disposed = true
|
|
@@ -182,7 +272,7 @@ export class RecallNudge {
|
|
|
182
272
|
return
|
|
183
273
|
}
|
|
184
274
|
const config = this.readConfig()
|
|
185
|
-
if (!config.enabled) return
|
|
275
|
+
if (!config.enabled || config.recallEnabled === false) return
|
|
186
276
|
// Both gates: don't recall before the user has spoken, and only for the
|
|
187
277
|
// currently active session (most recent user message).
|
|
188
278
|
if (this.tracker && !this.tracker.shouldInject(this.agent.id, config)) return
|
|
@@ -200,12 +290,99 @@ export class RecallNudge {
|
|
|
200
290
|
}
|
|
201
291
|
if (now < this.nextRecallAt) return
|
|
202
292
|
|
|
293
|
+
// Growth recap first: when the week is due it replaces this recall, but it
|
|
294
|
+
// shares the same cadence, per-session cap and arbitration lock.
|
|
295
|
+
const growth = this.planGrowth(now)
|
|
296
|
+
if (growth !== undefined) {
|
|
297
|
+
const claim = this.claimProactive(now, config)
|
|
298
|
+
if (!claim.ok) {
|
|
299
|
+
this.logger?.info?.(`memory: growth recap deferred for agent "${this.agent.id}" (${claim.deferredBy} holds the lock)`)
|
|
300
|
+
return // next trigger retries; the cadence is not consumed
|
|
301
|
+
}
|
|
302
|
+
try {
|
|
303
|
+
writeGrowthState(growth.statePath, now)
|
|
304
|
+
} catch (error) {
|
|
305
|
+
// Losing the timestamp only means the recap may repeat; it must not
|
|
306
|
+
// eat the message the user was about to see.
|
|
307
|
+
this.logger?.warn?.(`memory: growth recap state write failed: ${error instanceof Error ? error.message : String(error)}`)
|
|
308
|
+
}
|
|
309
|
+
this.agent.followup(growth.message)
|
|
310
|
+
this.nextRecallAt = now + randomIntervalMs(config.minMinutes, config.maxMinutes)
|
|
311
|
+
this.recalls += 1
|
|
312
|
+
this.logger?.info?.(`memory: growth recap #${this.recalls} for agent "${this.agent.id}"`)
|
|
313
|
+
return
|
|
314
|
+
}
|
|
315
|
+
|
|
203
316
|
const candidates = listRecallCandidates(this.getMemoryDir(), 3)
|
|
204
317
|
if (candidates.length === 0) return
|
|
205
318
|
|
|
319
|
+
const claim = this.claimProactive(now, config)
|
|
320
|
+
if (!claim.ok) {
|
|
321
|
+
this.logger?.info?.(`memory: recall deferred for agent "${this.agent.id}" (${claim.deferredBy} holds the lock)`)
|
|
322
|
+
return // next trigger retries; the cadence is not consumed
|
|
323
|
+
}
|
|
324
|
+
|
|
206
325
|
this.agent.followup(buildRecallNudgeMessage(candidates))
|
|
207
326
|
this.nextRecallAt = now + randomIntervalMs(config.minMinutes, config.maxMinutes)
|
|
208
327
|
this.recalls += 1
|
|
209
328
|
this.logger?.info?.(`memory: recall nudge #${this.recalls} for agent "${this.agent.id}"`)
|
|
210
329
|
}
|
|
330
|
+
|
|
331
|
+
/**
|
|
332
|
+
* Ask the shared proactive lock for permission to speak. A missing lock
|
|
333
|
+
* (no other proactive plugin installed) or a broken/unwritable lock file
|
|
334
|
+
* never blocks the message: arbitration is best-effort, not a gate.
|
|
335
|
+
* @param {number} now epoch ms
|
|
336
|
+
* @param {{ proactiveCooldownSeconds?: number }} config
|
|
337
|
+
* @returns {{ ok: boolean, deferredBy?: string }}
|
|
338
|
+
*/
|
|
339
|
+
claimProactive(now, config) {
|
|
340
|
+
if (typeof this.claimLock !== 'function') return { ok: true }
|
|
341
|
+
try {
|
|
342
|
+
const result = this.claimLock({
|
|
343
|
+
now,
|
|
344
|
+
cooldownSeconds: Math.max(0, Number(config.proactiveCooldownSeconds ?? 180)),
|
|
345
|
+
})
|
|
346
|
+
return result ?? { ok: true }
|
|
347
|
+
} catch (error) {
|
|
348
|
+
this.logger?.warn?.(`memory: proactive lock failed: ${error instanceof Error ? error.message : String(error)}`)
|
|
349
|
+
return { ok: true }
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
/**
|
|
354
|
+
* Plan a weekly growth recap, or undefined when it is not due / has nothing
|
|
355
|
+
* to say. Reads only the store; never throws (a broken recap must fall
|
|
356
|
+
* through to the normal recall path).
|
|
357
|
+
* @param {number} now epoch ms
|
|
358
|
+
* @returns {{ message: object, statePath: string } | undefined}
|
|
359
|
+
*/
|
|
360
|
+
planGrowth(now) {
|
|
361
|
+
if (typeof this.readGrowthConfig !== 'function') return undefined
|
|
362
|
+
let growthConfig
|
|
363
|
+
try {
|
|
364
|
+
growthConfig = this.readGrowthConfig()
|
|
365
|
+
} catch (error) {
|
|
366
|
+
this.logger?.warn?.(`memory: growth config unavailable: ${error instanceof Error ? error.message : String(error)}`)
|
|
367
|
+
return undefined
|
|
368
|
+
}
|
|
369
|
+
if (!growthConfig || growthConfig.enabled !== true) return undefined
|
|
370
|
+
try {
|
|
371
|
+
const storeDir = this.getMemoryDir()
|
|
372
|
+
const intervalDays = Math.max(1, Number(growthConfig.intervalDays ?? 7))
|
|
373
|
+
const statePath = join(storeDir, GROWTH_STATE_FILENAME)
|
|
374
|
+
if (!growthRecapDue({ statePath, intervalDays, now })) return undefined
|
|
375
|
+
const growth = collectGrowth({ storeDir, sinceDays: intervalDays, max: 5, now })
|
|
376
|
+
if (growth.entries.length === 0 && growth.pagesChanged === 0) return undefined
|
|
377
|
+
const recap = renderGrowthRecap({
|
|
378
|
+
...growth,
|
|
379
|
+
language: growthConfig.language === 'en' ? 'en' : 'zh',
|
|
380
|
+
})
|
|
381
|
+
if (recap.length === 0) return undefined
|
|
382
|
+
return { statePath, message: buildGrowthRecapNudgeMessage(recap) }
|
|
383
|
+
} catch (error) {
|
|
384
|
+
this.logger?.warn?.(`memory: growth recap skipped: ${error instanceof Error ? error.message : String(error)}`)
|
|
385
|
+
return undefined
|
|
386
|
+
}
|
|
387
|
+
}
|
|
211
388
|
}
|
package/lib/schema.js
CHANGED
|
@@ -23,4 +23,14 @@ export const SettingsSchema = z.object({
|
|
|
23
23
|
recallIntervalMinMinutes: z.number().default(30),
|
|
24
24
|
recallIntervalMaxMinutes: z.number().default(240),
|
|
25
25
|
recallMaxPerSession: z.number().default(3),
|
|
26
|
+
// 0.12.0: shared proactive-speech arbitration with dsh-plugin-heartbeat.
|
|
27
|
+
// 180s default; 0 turns arbitration off (each plugin speaks freely).
|
|
28
|
+
proactiveCooldownSeconds: z.number().default(180),
|
|
29
|
+
// 0.12.0: tone drift — how to shift register by context. The intensity
|
|
30
|
+
// select is the only knob; `off` ships a pure engineering voice.
|
|
31
|
+
toneGuideEnabled: z.boolean().default(true),
|
|
32
|
+
toneIntensity: z.union([z.const('low'), z.const('medium'), z.const('off')]).default('low'),
|
|
33
|
+
// 0.12.0: weekly growth recap delivered on the recall channel.
|
|
34
|
+
growthRecapEnabled: z.boolean().default(true),
|
|
35
|
+
growthRecapIntervalDays: z.number().default(7),
|
|
26
36
|
})
|
package/lib/tone.js
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tone drift: the "how to speak" half of the persona, injected into the boot
|
|
3
|
+
* block after the soul.
|
|
4
|
+
*
|
|
5
|
+
* A soul describes who the agent is; nothing in it tells the agent how to
|
|
6
|
+
* *shift register* when the user is in a hurry, when it is 3 a.m., or when it
|
|
7
|
+
* has to deliver bad news. That gap is what made replies read like a status
|
|
8
|
+
* report at the exact moment a companion would be brief and warm. This module
|
|
9
|
+
* turns the intended behaviour into a small, observable rule set — no mantle
|
|
10
|
+
* adjectives, only "in this context, do that".
|
|
11
|
+
*
|
|
12
|
+
* It also carries the emotional-expression layer: the agent may *express*
|
|
13
|
+
* care about a situation it can observe, and must never *fake* an inner
|
|
14
|
+
* feeling it cannot have. Three occasions only: risk/bad news, milestones,
|
|
15
|
+
* and the first line after a long silence.
|
|
16
|
+
*
|
|
17
|
+
* The output is capped at a dozen lines and charged to the boot budget: this
|
|
18
|
+
* text rides on every request, so it has to earn its characters.
|
|
19
|
+
*
|
|
20
|
+
* This module depends only on `node:*` builtins.
|
|
21
|
+
*
|
|
22
|
+
* @module dsh-plugin-memory/tone
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
/** Maximum lines the injected section may occupy (heading included). */
|
|
26
|
+
export const TONE_GUIDE_MAX_LINES = 12
|
|
27
|
+
|
|
28
|
+
/** Supported intensity levels; anything else degrades to `low`. */
|
|
29
|
+
export const TONE_INTENSITIES = ['low', 'medium', 'off']
|
|
30
|
+
|
|
31
|
+
const ZH_HEADING = '## 语气(按语境微调)'
|
|
32
|
+
|
|
33
|
+
const ZH_RULES = [
|
|
34
|
+
'- 赶工/紧急修复:短句、先结论、零玩笑。',
|
|
35
|
+
'- 深夜(23:00–06:00):更简短、更温和。',
|
|
36
|
+
'- 报错/坏消息:先给事实与修复动作,再谈感受。',
|
|
37
|
+
'- 里程碑/完成:可以轻松一句,然后回到正事。',
|
|
38
|
+
'- 闲聊:默认小蓝口吻(外松内紧),先结论后细节。',
|
|
39
|
+
'- 情绪表达(只表达不假装):只描述观察到的处境与关心,不宣称内心情绪;仅限风险/坏消息、里程碑/完成、超过 3 天没联系后的第一次开口(例:「看你连着加班,有点担心你硬扛」)。',
|
|
40
|
+
]
|
|
41
|
+
|
|
42
|
+
const ZH_INTENSITY = {
|
|
43
|
+
low: '- 强度 low:只做轻微调味;事实准确性永远优先,不越 SOUL 边界。',
|
|
44
|
+
medium: '- 强度 medium:语气可以更明显(该短则短、该暖则暖),但事实优先,不越 SOUL 边界。',
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const EN_HEADING = '## Tone (adapt to context)'
|
|
48
|
+
|
|
49
|
+
const EN_RULES = [
|
|
50
|
+
'- Crunch/urgent fix: short sentences, conclusion first, zero jokes.',
|
|
51
|
+
'- Deep night (23:00–06:00): shorter and gentler.',
|
|
52
|
+
'- Errors/bad news: give the facts and the fix before any feelings.',
|
|
53
|
+
'- Milestone/finished: one light line, then back to business.',
|
|
54
|
+
'- Small talk: default Small-Blue voice, conclusion before detail.',
|
|
55
|
+
'- Emotion (express, never fake): describe the observed situation and care, never claim an inner feeling; only for risk/bad news, milestones, and the first line after 3+ days without contact (e.g. "you have been working late — I am a bit worried you are pushing yourself").',
|
|
56
|
+
]
|
|
57
|
+
|
|
58
|
+
const EN_INTENSITY = {
|
|
59
|
+
low: '- Intensity low: light seasoning only; facts always win, never cross the SOUL boundary.',
|
|
60
|
+
medium: '- Intensity medium: let the tone show more clearly (tender when it matters) while keeping facts first and staying inside the SOUL boundary.',
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Render the tone section for injection into the boot block.
|
|
65
|
+
*
|
|
66
|
+
* `language` is the language of the injected prompt material (the memory
|
|
67
|
+
* plugin ships Chinese boot content; `en` is available for English stores).
|
|
68
|
+
* `intensity: 'off'` returns `''` — the boot block then looks exactly as it
|
|
69
|
+
* did before this feature existed.
|
|
70
|
+
*
|
|
71
|
+
* @param {object} [options]
|
|
72
|
+
* @param {'low'|'medium'|'off'} [options.intensity] default 'low'
|
|
73
|
+
* @param {'zh'|'en'} [options.language] default 'zh'
|
|
74
|
+
* @returns {string} complete section (heading + rules), '' when off
|
|
75
|
+
*/
|
|
76
|
+
export function buildToneGuide(options = {}) {
|
|
77
|
+
const intensity = TONE_INTENSITIES.includes(options.intensity) ? options.intensity : 'low'
|
|
78
|
+
if (intensity === 'off') return ''
|
|
79
|
+
const language = options.language === 'en' ? 'en' : 'zh'
|
|
80
|
+
const lines = language === 'en'
|
|
81
|
+
? [EN_HEADING, '', ...EN_RULES, EN_INTENSITY[intensity]]
|
|
82
|
+
: [ZH_HEADING, '', ...ZH_RULES, ZH_INTENSITY[intensity]]
|
|
83
|
+
// The cap is a contract (see TONE_GUIDE_MAX_LINES / test/tone.test.mjs):
|
|
84
|
+
// trim defensively rather than ever letting the section grow unbounded.
|
|
85
|
+
return lines.slice(0, TONE_GUIDE_MAX_LINES).join('\n')
|
|
86
|
+
}
|