dsh-plugin-agent-memory 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -45,7 +45,8 @@ Open the plugin's settings page (or the panel's gear button) and set:
45
45
  | `userKey` | Hub user key, sent as `X-Tdai-User-Key` (stored as a secret field) |
46
46
  | `defaultAgentId` | Agent used before the user picks an expert; empty means "pick one" |
47
47
  | `injectMemory` | Recall memories and inject them before each step (default on) |
48
- | `writeMemory` | Write each turn's user message back to the expert's memory (default off) |
48
+ | `writeMemory` | Write each turn back to the expert's memory (default off) |
49
+ | `writeAssistant` | Include the assistant's reply in that write, matching the official L0 pairing of question + answer (default on) |
49
50
  | `topK` | Max memories per recall (1–10, default 4) |
50
51
  | `layers` | Memory layers injected each turn (default `L3,L2`, matching the official proxy) |
51
52
  | `timeoutMs` | Per-request timeout (default 6000) |
@@ -56,6 +57,16 @@ Open the plugin's settings page (or the panel's gear button) and set:
56
57
 
57
58
  With no `hubUrl` or `userKey` the plugin stays idle: the selector is hidden and nothing is sent.
58
59
 
60
+ ## Where state lives
61
+
62
+ - The user key is stored in the DSH **credentials** store (`dsh-plugin-agent-memory/user-key`), not
63
+ in the profile's `cordis.patch.yml`; the config field is only a fallback for headless setups.
64
+ Saving a key from the panel migrates it there and blanks the config copy.
65
+ - The chosen expert per session is persisted in `~/.dsh/agent-memory-selections.json` (mode `0600`),
66
+ so a plugin reload or an app restart keeps the expert instead of dropping back to 「请选择专家」.
67
+ - The panel shows the last recall / write-back / skill-learning outcome for the session, and a
68
+ **记忆** tab browses the expert's L3 → L0 layers read-only.
69
+
59
70
  ## Skill learning
60
71
 
61
72
  agent-memory grows skills by reading finished conversations. With `skillLearning` on, each closed
@@ -72,7 +83,9 @@ expert selected (the expert supplies the team and agent the skill belongs to).
72
83
  - The Hub URL and user key are only used by the Host half; the browser talks to same-origin
73
84
  plugin routes and never sees the key.
74
85
  - With `injectMemory`, the last user message of a turn is sent to the Hub as a recall query.
75
- - With `writeMemory`, each turn's user message is also sent to the Hub to be stored.
86
+ - With `writeMemory`, each turn is also sent to the Hub to be stored (plus the assistant reply unless
87
+ `writeAssistant` is off).
88
+ - With `skillLearning`, each finished turn is sent to the kernel as described above.
76
89
  - Nothing is sent to any third party.
77
90
 
78
91
  ## Limits
package/client.js CHANGED
@@ -32,6 +32,52 @@ window.__ModuleLoader__.load({
32
32
  maxWidth: '220px',
33
33
  };
34
34
 
35
+
36
+ // Panel copy ships in both languages; the host half never renders text.
37
+ const EN = {
38
+ 'Agent / 专家': 'Agents / experts',
39
+ 'Hub 地址': 'Hub URL',
40
+ '专家记忆': 'Expert memory',
41
+ '保存': 'Save',
42
+ '保存中…': 'Saving…',
43
+ '内核地址(选填,默认 Hub 主机名:8420)': 'Kernel URL (optional, defaults to the Hub host on 8420)',
44
+ '列表刷新间隔(秒)': 'List refresh (seconds)',
45
+ '加载中…': 'Loading…',
46
+ '召回记忆并注入上下文': 'Recall memories into each turn',
47
+ '团队 / 专家': 'Teams / experts',
48
+ '实例 ID': 'Instance ID',
49
+ '对话结束后写回记忆库': 'Write each turn back to memory',
50
+ '把对话写回内核,用于技能自学习': 'Send each turn to the kernel for skill learning',
51
+ '按语义检索这一层': 'Search this layer',
52
+ '改写': 'rewrote',
53
+ '无': 'none',
54
+ '最近一次召回 / 写回 / 技能学习的结果': 'Last recall / write-back / skill-learning result',
55
+ '未知用户': 'unknown user',
56
+ '未配置:点右上「设置」填 Hub 地址与 userkey': 'Not configured: open Settings and enter the Hub URL and user key',
57
+ '检测中…': 'Checking…',
58
+ '检测连接': 'Test connection',
59
+ '检索': 'Search',
60
+ '每轮结束后把该轮对话(含工具调用与结果)写入内核,agent-memory 归档后抽取技能;内核按阈值归档,短回合不会立刻产出技能': 'Posts each finished turn (tool calls included) to the kernel so agent-memory can archive it and extract skills; archiving is threshold based, so a short turn produces nothing yet',
61
+ '没有取到团队,请检查连接设置': 'No teams returned: check the connection settings',
62
+ '清除选择': 'Clear selection',
63
+ '记忆': 'Memory',
64
+ '设置': 'Settings',
65
+ '该团队下没有 agent': 'This team has no agents',
66
+ '该团队下没有属于你的 agent,无法作为专家': 'This team has no agent owned by your user key',
67
+ '请选择专家': 'Choose expert',
68
+ '返回列表': 'Back',
69
+ '这一层没有内容(L1/L2/L3 需要内核异步提炼后才有)': 'Nothing in this layer yet (L1/L2/L3 arrive after the kernel distils them)',
70
+ '连接未检测': 'Not tested yet',
71
+ '连接设置': 'Connection settings',
72
+ '选择 agent-memory 专家': 'Pick an agent-memory expert',
73
+ '先在列表里选一个专家': 'Pick an expert in the list first',
74
+ '插件路由未就绪(404):重新加载插件或刷新页面后重试': 'Plugin routes are not ready (404): reload the plugin or refresh the page',
75
+ '已保存(留空不修改)': 'Saved (leave empty to keep)',
76
+ };
77
+ let panelLang = 'zh';
78
+ const t = (zh) => (panelLang === 'en' ? (EN[zh] ?? zh) : zh);
79
+ const msg = (zh, en) => (panelLang === 'en' ? en : zh);
80
+
35
81
  const panelStyle = {
36
82
  position: 'absolute',
37
83
  bottom: 'calc(100% + 8px)',
@@ -122,7 +168,7 @@ window.__ModuleLoader__.load({
122
168
  });
123
169
  const payload = await response.json().catch(() => null);
124
170
  if (response.status === 404) {
125
- throw new Error('插件路由未就绪(404):重新加载插件或刷新页面后重试');
171
+ throw new Error(t('插件路由未就绪(404):重新加载插件或刷新页面后重试'));
126
172
  }
127
173
  if (!response.ok) throw new Error(payload?.error ?? `HTTP ${response.status}`);
128
174
  return payload;
@@ -140,10 +186,12 @@ window.__ModuleLoader__.load({
140
186
  const [view, setView] = React.useState('list');
141
187
  const [config, setConfig] = React.useState(null);
142
188
  const [configured, setConfigured] = React.useState(true);
143
- const [health, setHealth] = React.useState({ state: 'idle', text: '连接未检测' });
189
+ const [health, setHealth] = React.useState({ state: 'idle', text: t('连接未检测') });
144
190
  const [form, setForm] = React.useState({ hubUrl: '', instanceId: '', kernelUrl: '', userKey: '' });
145
- const [flags, setFlags] = React.useState({ injectMemory: true, writeMemory: false });
191
+ const [flags, setFlags] = React.useState({ injectMemory: true, writeMemory: false, skillLearning: false });
146
192
  const [refreshMs, setRefreshMs] = React.useState(10000);
193
+ const [activity, setActivity] = React.useState(null);
194
+ const [memory, setMemory] = React.useState({ layer: 'L3', items: [], counts: null, query: '', loading: false });
147
195
  const [saving, setSaving] = React.useState(false);
148
196
 
149
197
  const loadState = React.useCallback(() => {
@@ -155,6 +203,7 @@ window.__ModuleLoader__.load({
155
203
  setSelection(payload.selection ?? null);
156
204
  setTeamId(payload.selection?.teamId ?? payload.teams?.[0]?.teamId ?? '');
157
205
  setConfigured(payload.configured !== false);
206
+ setActivity(payload.activity ?? null);
158
207
  if (Number.isFinite(payload.config?.refreshMs)) setRefreshMs(payload.config.refreshMs);
159
208
  if (typeof payload.error === 'string' && payload.error !== '') setError(payload.error);
160
209
  const current = payload.config ?? null;
@@ -169,6 +218,7 @@ window.__ModuleLoader__.load({
169
218
  setFlags({
170
219
  injectMemory: current.injectMemory !== false,
171
220
  writeMemory: current.writeMemory === true,
221
+ skillLearning: current.skillLearning === true,
172
222
  });
173
223
  }
174
224
  })
@@ -181,7 +231,7 @@ window.__ModuleLoader__.load({
181
231
  }, [sessionId]);
182
232
 
183
233
  const checkHealth = React.useCallback(() => {
184
- setHealth({ state: 'busy', text: '检测中…' });
234
+ setHealth({ state: 'busy', text: t('检测中…') });
185
235
  json(`${ROUTE}/health`)
186
236
  .then((payload) => {
187
237
  const agents = (payload.teams ?? []).reduce((total, team) => total + (team.agents ?? 0), 0);
@@ -190,11 +240,17 @@ window.__ModuleLoader__.load({
190
240
  state: down.length === 0 && payload.ok !== false ? 'ok' : 'bad',
191
241
  text:
192
242
  down.length === 0
193
- ? `已连接 · ${payload.user?.username ?? '未知用户'} · ${(payload.teams ?? []).length} 团队 / ${agents} agent`
194
- : `部分服务不可用:${down.map((service) => `${service.name}(${service.detail})`).join(';')}`,
243
+ ? msg(
244
+ `已连接 · ${payload.user?.username ?? t(t('未知用户'))} · ${(payload.teams ?? []).length} 团队 / ${agents} agent`,
245
+ `Connected · ${payload.user?.username ?? t(t('未知用户'))} · ${(payload.teams ?? []).length} teams / ${agents} agents`,
246
+ )
247
+ : msg(
248
+ `部分服务不可用:${down.map((service) => `${service.name}(${service.detail})`).join(';')}`,
249
+ `Some services are down: ${down.map((service) => `${service.name}(${service.detail})`).join('; ')}`,
250
+ ),
195
251
  });
196
252
  })
197
- .catch((failure) => setHealth({ state: 'bad', text: `连接失败:${String(failure.message ?? failure)}` }));
253
+ .catch((failure) => setHealth({ state: 'bad', text: msg(`连接失败:${String(failure.message ?? failure)}`, `Connection failed: ${String(failure.message ?? failure)}`) }));
198
254
  }, []);
199
255
 
200
256
  const saveConfig = React.useCallback(() => {
@@ -209,6 +265,7 @@ window.__ModuleLoader__.load({
209
265
  kernelUrl: form.kernelUrl,
210
266
  userKey: form.userKey,
211
267
  injectMemory: flags.injectMemory,
268
+ skillLearning: flags.skillLearning,
212
269
  refreshMs,
213
270
  writeMemory: flags.writeMemory,
214
271
  }),
@@ -221,7 +278,10 @@ window.__ModuleLoader__.load({
221
278
  loadState();
222
279
  checkHealth();
223
280
  }, 1200);
224
- setHealth({ state: 'busy', text: `已保存(${(payload.saved ?? []).join(', ')}),正在重启插件…` });
281
+ setHealth({ state: 'busy', text: msg(
282
+ `已保存(${(payload.saved ?? []).join(', ')}),正在重启插件…`,
283
+ `Saved (${(payload.saved ?? []).join(', ')}) — restarting the plugin…`,
284
+ ) });
225
285
  })
226
286
  .catch((failure) => setError(String(failure.message ?? failure)))
227
287
  .finally(() => setSaving(false));
@@ -279,6 +339,23 @@ window.__ModuleLoader__.load({
279
339
  [sessionId, teamId],
280
340
  );
281
341
 
342
+ const loadMemory = React.useCallback(
343
+ (layer, query) => {
344
+ setMemory((prev) => ({ ...prev, layer, query, loading: true }));
345
+ const session = encodeURIComponent(String(sessionId ?? ''));
346
+ const q = encodeURIComponent(query);
347
+ json(`${ROUTE}/memory?session=${session}&layer=${layer}&query=${q}`)
348
+ .then((payload) => {
349
+ setMemory({ layer, query, items: payload.items ?? [], counts: payload.counts ?? null, loading: false });
350
+ })
351
+ .catch((failure) => {
352
+ setMemory({ layer, query, items: [], counts: null, loading: false });
353
+ setError(String(failure.message ?? failure));
354
+ });
355
+ },
356
+ [sessionId],
357
+ );
358
+
282
359
  const clear = React.useCallback(() => {
283
360
  json(`${ROUTE}/select`, {
284
361
  method: 'POST',
@@ -292,7 +369,7 @@ window.__ModuleLoader__.load({
292
369
  .catch((failure) => setError(String(failure.message ?? failure)));
293
370
  }, [sessionId]);
294
371
 
295
- const label = selection ? `专家:${selection.agentName}` : '请选择专家';
372
+ const label = selection ? msg(`专家:${selection.agentName}`, `Expert: ${selection.agentName}`) : t(t('请选择专家'));
296
373
  const healthColor =
297
374
  health.state === 'ok' ? '#2e7d32' : health.state === 'bad' ? '#c0392b' : 'rgba(128,128,128,0.85)';
298
375
 
@@ -300,7 +377,7 @@ window.__ModuleLoader__.load({
300
377
  'button',
301
378
  {
302
379
  type: 'button',
303
- title: selection ? `${selection.teamName} / ${selection.agentName}` : '选择 agent-memory 专家',
380
+ title: selection ? `${selection.teamName} / ${selection.agentName}` : t('选择 agent-memory 专家'),
304
381
  style: chipStyle,
305
382
  onClick: () => {
306
383
  const next = !open;
@@ -362,6 +439,54 @@ window.__ModuleLoader__.load({
362
439
  ),
363
440
  );
364
441
 
442
+ const activityText = (() => {
443
+ if (!activity) return '';
444
+ const parts = [];
445
+ if (activity.recall) {
446
+ parts.push(msg(
447
+ `召回 ${activity.recall.hits} 条(${activity.recall.layers || t(t('无'))})${activity.recall.ms}ms`,
448
+ `recalled ${activity.recall.hits} (${activity.recall.layers || t(t('无'))}) ${activity.recall.ms}ms`,
449
+ ));
450
+ }
451
+ if (activity.write) {
452
+ const write = activity.write;
453
+ parts.push(
454
+ write.ok === true
455
+ ? msg(
456
+ `写回 ${write.chars ?? 0} 字${write.replyChars ? `+助手 ${write.replyChars} 字` : ''}`,
457
+ `wrote back ${write.chars ?? 0} chars${write.replyChars ? ` (+${write.replyChars} from the reply)` : ''}`,
458
+ )
459
+ : write.skipped
460
+ ? msg(`写回跳过(${write.chars ?? 0} 字)`, `write-back skipped (${write.chars ?? 0} chars)`)
461
+ : msg('写回失败', 'write-back failed'),
462
+ );
463
+ }
464
+ if (activity.learn) {
465
+ const learn = activity.learn;
466
+ parts.push(
467
+ learn.ok === true
468
+ ? msg(
469
+ `学习 ${learn.status ?? 'ok'}${learn.tools ? `(${learn.tools} 工具)` : ''}`,
470
+ `learned ${learn.status ?? 'ok'}${learn.tools ? ` (${learn.tools} tools)` : ''}`,
471
+ )
472
+ : msg('学习失败', 'skill learning failed'),
473
+ );
474
+ }
475
+ if (activity.update) parts.push(msg(`改写 ${activity.update.layer} 记忆`, `rewrote a ${activity.update.layer} memory`));
476
+ return parts.join(' · ');
477
+ })();
478
+
479
+ const activityLine = activityText
480
+ ? h(
481
+ 'div',
482
+ {
483
+ style: { padding: '0 8px 4px', fontSize: '10px', opacity: 0.7, lineHeight: '1.4' },
484
+ title: t('最近一次召回 / 写回 / 技能学习的结果'),
485
+ },
486
+ activityText,
487
+ )
488
+ : null;
489
+
365
490
  const header = h(
366
491
  'div',
367
492
  {
@@ -372,15 +497,39 @@ window.__ModuleLoader__.load({
372
497
  padding: '2px 8px 2px',
373
498
  },
374
499
  },
375
- h('span', { style: { fontSize: '11px', opacity: 0.6 } }, view === 'settings' ? '连接设置' : '团队 / 专家'),
376
500
  h(
377
- 'button',
378
- {
379
- type: 'button',
380
- style: linkButtonStyle,
381
- onClick: () => setView(view === 'settings' ? 'list' : 'settings'),
382
- },
383
- view === 'settings' ? '返回列表' : '设置',
501
+ 'span',
502
+ { style: { fontSize: '11px', opacity: 0.6 } },
503
+ view === 'settings' ? t('连接设置') : view === 'memory' ? t('专家记忆') : t('团队 / 专家'),
504
+ ),
505
+ h(
506
+ 'div',
507
+ { style: { display: 'flex', gap: '8px' } },
508
+ h(
509
+ 'button',
510
+ {
511
+ type: 'button',
512
+ style: { ...linkButtonStyle, fontWeight: view === 'memory' ? 600 : 400 },
513
+ onClick: () => {
514
+ if (view === 'memory') {
515
+ setView('list');
516
+ return;
517
+ }
518
+ setView('memory');
519
+ loadMemory(memory.layer, memory.query);
520
+ },
521
+ },
522
+ view === 'memory' ? t('返回列表') : t('记忆'),
523
+ ),
524
+ h(
525
+ 'button',
526
+ {
527
+ type: 'button',
528
+ style: { ...linkButtonStyle, fontWeight: view === 'settings' ? 600 : 400 },
529
+ onClick: () => setView(view === 'settings' ? 'list' : 'settings'),
530
+ },
531
+ view === 'settings' ? t('返回列表') : t('设置'),
532
+ ),
384
533
  ),
385
534
  );
386
535
 
@@ -390,7 +539,7 @@ window.__ModuleLoader__.load({
390
539
  h(
391
540
  'label',
392
541
  { style: fieldStyle },
393
- h('span', { style: fieldLabelStyle }, 'Hub 地址'),
542
+ h('span', { style: fieldLabelStyle }, t('Hub 地址')),
394
543
  h('input', {
395
544
  style: inputStyle,
396
545
  type: 'text',
@@ -402,7 +551,7 @@ window.__ModuleLoader__.load({
402
551
  h(
403
552
  'label',
404
553
  { style: fieldStyle },
405
- h('span', { style: fieldLabelStyle }, '实例 ID'),
554
+ h('span', { style: fieldLabelStyle }, t('实例 ID')),
406
555
  h('input', {
407
556
  style: inputStyle,
408
557
  type: 'text',
@@ -414,7 +563,7 @@ window.__ModuleLoader__.load({
414
563
  h(
415
564
  'label',
416
565
  { style: fieldStyle },
417
- h('span', { style: fieldLabelStyle }, '内核地址(选填,默认 Hub 主机名:8420)'),
566
+ h('span', { style: fieldLabelStyle }, t('内核地址(选填,默认 Hub 主机名:8420)')),
418
567
  h('input', {
419
568
  style: inputStyle,
420
569
  type: 'text',
@@ -431,7 +580,7 @@ window.__ModuleLoader__.load({
431
580
  style: inputStyle,
432
581
  type: 'password',
433
582
  value: form.userKey,
434
- placeholder: config?.userKeySet ? `已保存 ${config.userKeyHint ?? ''}(留空不修改)` : 'sk-mem-...',
583
+ placeholder: config?.userKeySet ? msg(`已保存 ${config.userKeyHint ?? ''}(留空不修改)`, `Saved ${config.userKeyHint ?? ''} (leave empty to keep)`) : 'sk-mem-...',
435
584
  onChange: (event) => setForm({ ...form, userKey: event.target.value }),
436
585
  }),
437
586
  ),
@@ -443,7 +592,7 @@ window.__ModuleLoader__.load({
443
592
  checked: flags.injectMemory,
444
593
  onChange: (event) => setFlags({ ...flags, injectMemory: event.target.checked }),
445
594
  }),
446
- h('span', { style: { fontSize: '12px' } }, '召回记忆并注入上下文'),
595
+ h('span', { style: { fontSize: '12px' } }, t('召回记忆并注入上下文')),
447
596
  ),
448
597
  h(
449
598
  'label',
@@ -453,12 +602,30 @@ window.__ModuleLoader__.load({
453
602
  checked: flags.writeMemory,
454
603
  onChange: (event) => setFlags({ ...flags, writeMemory: event.target.checked }),
455
604
  }),
456
- h('span', { style: { fontSize: '12px' } }, '对话结束后写回记忆库'),
605
+ h('span', { style: { fontSize: '12px' } }, t('对话结束后写回记忆库')),
606
+ ),
607
+ h(
608
+ 'label',
609
+ {
610
+ style: { ...fieldStyle, display: 'flex', alignItems: 'flex-start', gap: '6px' },
611
+ title: t('每轮结束后把该轮对话(含工具调用与结果)写入内核,agent-memory 归档后抽取技能;内核按阈值归档,短回合不会立刻产出技能'),
612
+ },
613
+ h('input', {
614
+ type: 'checkbox',
615
+ style: { marginTop: '3px' },
616
+ checked: flags.skillLearning,
617
+ onChange: (event) => setFlags({ ...flags, skillLearning: event.target.checked }),
618
+ }),
619
+ h(
620
+ 'span',
621
+ { style: { fontSize: '12px' } },
622
+ t('把对话写回内核,用于技能自学习'),
623
+ ),
457
624
  ),
458
625
  h(
459
626
  'label',
460
627
  { style: fieldStyle },
461
- h('span', { style: fieldLabelStyle }, '列表刷新间隔(秒)'),
628
+ h('span', { style: fieldLabelStyle }, t('列表刷新间隔(秒)')),
462
629
  h('input', {
463
630
  style: inputStyle,
464
631
  type: 'number',
@@ -484,12 +651,99 @@ window.__ModuleLoader__.load({
484
651
  disabled: saving,
485
652
  onClick: saveConfig,
486
653
  },
487
- saving ? '保存中…' : '保存',
654
+ saving ? t('保存中…') : t('保存'),
488
655
  ),
489
- h('button', { type: 'button', style: buttonStyle, onClick: checkHealth }, '检测连接'),
656
+ h('button', { type: 'button', style: buttonStyle, onClick: checkHealth }, t('检测连接')),
490
657
  ),
491
658
  );
492
659
 
660
+ const memoryView = h(
661
+ 'div',
662
+ null,
663
+ h(
664
+ 'div',
665
+ { style: { display: 'flex', gap: '10px', padding: '0 8px 4px' } },
666
+ ...['L3', 'L2', 'L1', 'L0'].map((layer) =>
667
+ h(
668
+ 'button',
669
+ {
670
+ key: layer,
671
+ type: 'button',
672
+ style: { ...linkButtonStyle, fontWeight: memory.layer === layer ? 600 : 400 },
673
+ onClick: () => loadMemory(layer, memory.query),
674
+ },
675
+ layer,
676
+ ),
677
+ ),
678
+ ),
679
+ memory.counts
680
+ ? h(
681
+ 'div',
682
+ { style: { ...mutedStyle, padding: '0 8px 4px' } },
683
+ msg(
684
+ `Hub 记录的计数(可能滞后):L0 ${memory.counts.L0_messages ?? 0} · L1 ${memory.counts.L1 ?? 0} · L2 ${memory.counts.L2 ?? 0} · L3 ${memory.counts.L3 ?? 0}`,
685
+ `Hub counters (may lag): L0 ${memory.counts.L0_messages ?? 0} · L1 ${memory.counts.L1 ?? 0} · L2 ${memory.counts.L2 ?? 0} · L3 ${memory.counts.L3 ?? 0}`,
686
+ ),
687
+ )
688
+ : null,
689
+ h(
690
+ 'div',
691
+ { style: { padding: '0 8px 4px', display: 'flex', gap: '6px' } },
692
+ h('input', {
693
+ style: { ...inputStyle, flex: '1 1 auto', fontSize: '11px' },
694
+ type: 'search',
695
+ placeholder: t('按语义检索这一层'),
696
+ value: memory.query,
697
+ onChange: (event) => setMemory({ ...memory, query: event.target.value }),
698
+ onKeyDown: (event) => {
699
+ if (event.key === 'Enter') loadMemory(memory.layer, memory.query);
700
+ },
701
+ }),
702
+ h(
703
+ 'button',
704
+ {
705
+ type: 'button',
706
+ style: linkButtonStyle,
707
+ onClick: () => loadMemory(memory.layer, memory.query),
708
+ },
709
+ t('检索'),
710
+ ),
711
+ ),
712
+ memory.loading ? h('div', { style: mutedStyle }, t('加载中…')) : null,
713
+ h(
714
+ 'div',
715
+ { style: { maxHeight: '260px', overflowY: 'auto' } },
716
+ ...memory.items.map((item) =>
717
+ h(
718
+ 'div',
719
+ {
720
+ key: item.id || `${item.createdAt}-${item.body.slice(0, 12)}`,
721
+ style: {
722
+ padding: '4px 8px',
723
+ fontSize: '11px',
724
+ borderBottom: '1px solid var(--dsw-alias-border-subtle, rgba(128,128,128,0.14))',
725
+ },
726
+ },
727
+ h(
728
+ 'div',
729
+ { style: { opacity: 0.55, fontSize: '10px' } },
730
+ `${item.role || 'memory'}${item.createdAt ? ` · ${String(item.createdAt).slice(0, 10)}` : ''}${
731
+ typeof item.score === 'number' ? ` · ${item.score.toFixed(3)}` : ''
732
+ }`,
733
+ ),
734
+ h('div', { style: { lineHeight: '1.45', whiteSpace: 'normal' } }, item.body.slice(0, 240)),
735
+ ),
736
+ ),
737
+ ),
738
+ memory.items.length === 0 && !memory.loading
739
+ ? h(
740
+ 'div',
741
+ { style: mutedStyle },
742
+ selection ? t('这一层没有内容(L1/L2/L3 需要内核异步提炼后才有)') : t('先在列表里选一个专家'),
743
+ )
744
+ : null,
745
+ );
746
+
493
747
  const listView = h(
494
748
  'div',
495
749
  null,
@@ -517,14 +771,14 @@ window.__ModuleLoader__.load({
517
771
  ),
518
772
  ),
519
773
  configured === false
520
- ? h('div', { style: mutedStyle }, '未配置:点右上「设置」填 Hub 地址与 userkey')
774
+ ? h('div', { style: mutedStyle }, t('未配置:点右上「设置」填 Hub 地址与 userkey'))
521
775
  : teams.length === 0
522
- ? h('div', { style: mutedStyle }, '没有取到团队,请检查连接设置')
776
+ ? h('div', { style: mutedStyle }, t('没有取到团队,请检查连接设置'))
523
777
  : null,
524
778
  teams.length === 0
525
779
  ? null
526
- : h('div', { style: { ...mutedStyle, marginTop: '4px' } }, 'Agent / 专家'),
527
- busy ? h('div', { style: mutedStyle }, '加载中…') : null,
780
+ : h('div', { style: { ...mutedStyle, marginTop: '4px' } }, t('Agent / 专家')),
781
+ busy ? h('div', { style: mutedStyle }, t('加载中…')) : null,
528
782
  ...visibleAgents.map((agent) =>
529
783
  h(
530
784
  'button',
@@ -549,14 +803,14 @@ window.__ModuleLoader__.load({
549
803
  ? h(
550
804
  'div',
551
805
  { style: mutedStyle },
552
- agents.length === 0 ? '该团队下没有 agent' : '该团队下没有属于你的 agent,无法作为专家',
806
+ agents.length === 0 ? t('该团队下没有 agent') : t('该团队下没有属于你的 agent,无法作为专家'),
553
807
  )
554
808
  : null,
555
809
  selection
556
810
  ? h(
557
811
  'button',
558
812
  { type: 'button', style: { ...rowStyle, opacity: 0.7, marginTop: '4px' }, onClick: clear },
559
- '清除选择',
813
+ t('清除选择'),
560
814
  )
561
815
  : null,
562
816
  );
@@ -570,8 +824,9 @@ window.__ModuleLoader__.load({
570
824
  'div',
571
825
  { style: panelStyle },
572
826
  healthLine,
827
+ activityLine,
573
828
  header,
574
- view === 'settings' ? settingsView : listView,
829
+ view === 'settings' ? settingsView : view === 'memory' ? memoryView : listView,
575
830
  error ? h('div', { style: { ...mutedStyle, color: '#c0392b' } }, error) : null,
576
831
  )
577
832
  : null,
@@ -581,6 +836,27 @@ window.__ModuleLoader__.load({
581
836
  return {
582
837
  inject: ['slots'],
583
838
  apply(ctx) {
839
+ const locale = (() => {
840
+ try {
841
+ return ctx.get('locale');
842
+ } catch {
843
+ return undefined;
844
+ }
845
+ })();
846
+ const readLang = (snapshot) => {
847
+ const value = snapshot?.locale ?? snapshot?.language ?? '';
848
+ return String(value).toLowerCase().startsWith('en') ? 'en' : 'zh';
849
+ };
850
+ if (locale !== undefined) {
851
+ try {
852
+ panelLang = readLang(locale.getSnapshot?.());
853
+ locale.subscribe?.((snapshot) => {
854
+ panelLang = readLang(snapshot);
855
+ });
856
+ } catch {
857
+ /* locale is advisory: the panel falls back to Chinese */
858
+ }
859
+ }
584
860
  ctx.slots.inject('conversation.input.left', () =>
585
861
  ctx.slots.register(
586
862
  {
package/docs/DETAIL.md CHANGED
@@ -18,7 +18,8 @@
18
18
  | `userKey` | 该实例的 user key,对应 `X-Tdai-User-Key` |
19
19
  | `defaultAgentId` | 会话未选择专家时使用的 agent id;留空则等用户在选择器里挑 |
20
20
  | `injectMemory` | 关闭后只保留选择器,不注入记忆 |
21
- | `writeMemory` | 打开后每轮结束时把该轮用户消息写回专家记忆块(插件默认关闭,本实例安装配置里已开启) |
21
+ | `writeMemory` | 打开后每轮结束时把该轮内容写回专家记忆块(插件默认关闭,本实例安装配置里已开启) |
22
+ | `writeAssistant` | 写回时是否带上助手回复(默认开;官方 tdai-memory 的 L0 是 user_query + assistant reply 成对写入) |
22
23
  | `topK` | 每层最多取回的记忆条数(1–10) |
23
24
  | `layers` | 每轮预注入的记忆层,逗号分隔,默认 `L3,L2`;需要更细的原文可加 `L1,L0`,或用 `am_memory_search` 按需查 |
24
25
  | `timeoutMs` | 单次 Hub 请求超时 |
@@ -51,6 +52,10 @@ AM 一套部署有四个服务,插件只用到其中三个,且只有两个
51
52
  - Hub 没有可用的按条删除路由(`chat-memory/clear` 恒返回 `BLOCK_NOT_FOUND`),写错的记忆只能在记忆管理界面清理。
52
53
  - 团队与 agent 列表有缓存,默认 10 秒(`refreshMs`),选择器按同一间隔自动刷新。
53
54
  - 技能自学习走内核 `/v3/skill/conversation/add`:每轮一次、按 session 严格串行、只在该会话选了专家时发送(团队与 agent 由专家提供)。内核按阈值(约 10 次工具调用或 40 KiB)归档后才会排入技能抽取任务,短回合返回 `ok` 而非 `archived` 属正常。
55
+ - 密钥与状态:userkey 存在 DSH credentials(`dsh-plugin-agent-memory/user-key`,记录 kind 为 `grant`),配置里的 `userKey` 只作 headless 兜底;面板保存密钥时会迁移进凭据库并把配置里的副本置空。会话选中的专家持久化在 `~/.dsh/agent-memory-selections.json`(0600),插件重载或应用重启后保留。
56
+ - 面板可观测:健康行下方显示最近一次召回(命中数 / 用到的层 / 耗时)、写回(字符数、是否带助手回复)与技能学习(status / 工具数)的结果;「记忆」页签按 L3→L0 只读浏览该专家的分层内容,可输入关键词做语义检索。Hub 返回的 `layer_counts` 会滞后,所以列表以实际返回为准。
57
+ - 记忆纠错:`am_memory_update` 用 Hub 的 `chat-memory/layer-update` 覆盖某一条记忆(先用 `am_memory_search` 拿 id)。Hub 没有删除接口,因此测试数据只能覆盖、不能删除。
58
+ - task 维度不适用:Hub 的 `chat-memory` 全部方法(team-assets / agent-fixed / layer / import / layer-update / search)都按 team+agent 作用域,没有 task 字段;`task/*` 是独立实体(任务 ↔ agent 关联),不参与记忆分区。所以本插件不做 task 选择。
54
59
  - 资产工具只读:知识库 / code-graph 走知识服务的 `tools/list` + `tools/call`,技能走内核 `/v3/skill/*`;user key 只在 Host 里加进请求头,不进 prompt、不进浏览器。
55
60
  - code-graph 是分支快照,需要某段代码此刻的精确内容时应读工作区源码;插件在工具描述里也这样要求模型。
56
61
  - 插件自带 `GET /plugins/agent-memory/health`(回连 Hub 校验 userkey 并汇总团队 / agent 数)与 `POST /plugins/agent-memory/config`(保存设置);两条路由都只接受回环地址来源的浏览器请求,跨站请求返回 403。
package/index.js CHANGED
@@ -12,7 +12,7 @@
12
12
  */
13
13
 
14
14
  import { randomUUID } from 'node:crypto';
15
- import { appendFileSync, rmSync, statSync } from 'node:fs';
15
+ import { appendFileSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
16
16
  import { homedir } from 'node:os';
17
17
  import z from '@deepseek-ai/schemastery';
18
18
 
@@ -20,6 +20,10 @@ import z from '@deepseek-ai/schemastery';
20
20
  const DEFAULT_REFRESH_MS = 10 * 1000;
21
21
  const LAYERS = ['L3', 'L2', 'L1', 'L0'];
22
22
  const DEBUG_LOG_LIMIT = 256 * 1024;
23
+ /** Explicit expert choices outlive the process: a plugin reload or an app restart must not
24
+ * silently drop the user back to 「请选择专家」 mid-conversation. */
25
+ const SELECTIONS_FILE = `${homedir()}/.dsh/agent-memory-selections.json`;
26
+ const SELECTIONS_LIMIT = 200;
23
27
 
24
28
  /**
25
29
  * Configuration schema shown on this plugin's detail page and validated at activation.
@@ -34,7 +38,11 @@ export const Config = z.object({
34
38
  userKey: z.string().role('secret').default('').description('Memory Hub userkey(请求头 X-Tdai-User-Key)'),
35
39
  defaultAgentId: z.string().default('').description('未选择专家时默认使用的 agent id;留空则等用户在面板里选择'),
36
40
  injectMemory: z.boolean().default(true).description('每轮对话前召回该专家的记忆并注入上下文'),
37
- writeMemory: z.boolean().default(false).description('每轮对话结束后把用户消息写回记忆库'),
41
+ writeMemory: z.boolean().default(false).description('每轮对话结束后把本轮内容写回记忆库'),
42
+ writeAssistant: z
43
+ .boolean()
44
+ .default(true)
45
+ .description('写回时带上助手回复(官方 tdai-memory 按 user_query + assistant reply 成对写入 L0;关掉则只写用户消息)'),
38
46
  topK: z.number().min(1).max(10).step(1).default(4).description('每次召回的记忆条数'),
39
47
  layers: z
40
48
  .string()
@@ -60,7 +68,7 @@ export const Config = z.object({
60
68
  debug: z.boolean().default(false).description('把召回/写回诊断写入 ~/.dsh/agent-memory-debug.log'),
61
69
  });
62
70
 
63
- function textOf(value) {
71
+ export function textOf(value) {
64
72
  if (typeof value === 'string') return value;
65
73
  if (!Array.isArray(value)) return '';
66
74
  return value
@@ -69,7 +77,7 @@ function textOf(value) {
69
77
  .join('\n');
70
78
  }
71
79
 
72
- function lastUserText(messages) {
80
+ export function lastUserText(messages) {
73
81
  let fallback = '';
74
82
  for (let index = messages.length - 1; index >= 0; index -= 1) {
75
83
  const message = messages[index];
@@ -91,7 +99,7 @@ const WRITE_NOISE = [
91
99
  /^<skill_content>/,
92
100
  ];
93
101
 
94
- function writeBackText(text) {
102
+ export function writeBackText(text) {
95
103
  const trimmed = text.trim();
96
104
  if (trimmed === '') return '';
97
105
  if (WRITE_NOISE.some((pattern) => pattern.test(trimmed))) return '';
@@ -105,7 +113,7 @@ function writeBackText(text) {
105
113
  * The per-turn injection layers. Official proxy injects L3 (persona) + L2 (scene index)
106
114
  * only; L0/L1 stay on demand through tools, which protects the prompt cache.
107
115
  */
108
- function parseLayers(value) {
116
+ export function parseLayers(value) {
109
117
  const allowed = new Set(LAYERS);
110
118
  const picked = String(value ?? '')
111
119
  .split(/[,\s]+/)
@@ -114,7 +122,7 @@ function parseLayers(value) {
114
122
  return picked.length > 0 ? picked : ['L3', 'L2'];
115
123
  }
116
124
 
117
- function normalizeConfig(config) {
125
+ export function normalizeConfig(config) {
118
126
  const value = config ?? {};
119
127
  return {
120
128
  hubUrl: String(value.hubUrl ?? '').replace(/\/+$/, ''),
@@ -123,6 +131,7 @@ function normalizeConfig(config) {
123
131
  defaultAgentId: typeof value.defaultAgentId === 'string' ? value.defaultAgentId : '',
124
132
  injectMemory: value.injectMemory !== false,
125
133
  writeMemory: value.writeMemory === true,
134
+ writeAssistant: value.writeAssistant !== false,
126
135
  topK: Number.isFinite(value.topK) ? Math.max(1, Math.min(10, value.topK)) : 4,
127
136
  layers: parseLayers(value.layers),
128
137
  timeoutMs: Number.isFinite(value.timeoutMs) ? Math.max(1000, value.timeoutMs) : 6000,
@@ -139,16 +148,55 @@ export const inject = ['tools'];
139
148
 
140
149
  export function apply(ctx, config) {
141
150
  const settings = normalizeConfig(config);
142
- // A published bundle ships no Hub address or key, so an unconfigured install must still
143
- // start: the routes below answer `/state` and `/config` so the settings form can be reached.
144
- const configured = settings.hubUrl !== '' && settings.userKey !== '';
145
- if (!configured) ctx.logger?.warn?.('[agent-memory] hubUrl/userKey missing; integration stays idle until configured');
151
+ const configured = settings.hubUrl !== '';
146
152
 
147
- const headers = {
148
- 'X-Tdai-Service-Id': settings.instanceId,
149
- 'X-Tdai-User-Key': settings.userKey,
150
- 'Content-Type': 'application/json',
151
- };
153
+ /**
154
+ * The user key is a secret: it belongs in the credentials store, not in the profile's
155
+ * `cordis.patch.yml` where a backup or a shared profile would leak it. The config field
156
+ * remains a fallback for older installs and for headless use.
157
+ */
158
+ const CREDENTIAL_KEY = 'dsh-plugin-agent-memory/user-key';
159
+ let cachedUserKey = '';
160
+ async function credentialsStore() {
161
+ const store = ctx.get('credentials');
162
+ return store !== undefined && typeof store.readRecord === 'function' ? store : null;
163
+ }
164
+ async function readStoredUserKey() {
165
+ const store = await credentialsStore();
166
+ if (store === null) return '';
167
+ try {
168
+ const record = await store.readRecord(CREDENTIAL_KEY);
169
+ if (record === undefined || record === null) return '';
170
+ const value = record.kind === 'grant' ? record.payload?.userKey : undefined;
171
+ return typeof value === 'string' ? value : '';
172
+ } catch {
173
+ return '';
174
+ }
175
+ }
176
+ async function saveStoredUserKey(value) {
177
+ const store = await credentialsStore();
178
+ if (store === null || typeof store.modifyRecord !== 'function') return false;
179
+ await store.modifyRecord(CREDENTIAL_KEY, async () =>
180
+ value === '' ? undefined : { kind: 'grant', payload: { userKey: value, savedAt: Date.now() } },
181
+ );
182
+ cachedUserKey = value;
183
+ return true;
184
+ }
185
+ async function userKey() {
186
+ if (cachedUserKey !== '') return cachedUserKey;
187
+ const stored = await readStoredUserKey();
188
+ cachedUserKey = stored !== '' ? stored : settings.userKey;
189
+ return cachedUserKey;
190
+ }
191
+ async function authHeaders() {
192
+ const key = await userKey();
193
+ if (key === '') throw new Error('Memory Hub userkey 未配置:请在插件设置里填写 userKey');
194
+ return {
195
+ 'X-Tdai-Service-Id': settings.instanceId,
196
+ 'X-Tdai-User-Key': key,
197
+ 'Content-Type': 'application/json',
198
+ };
199
+ }
152
200
 
153
201
  const state = {
154
202
  teams: [],
@@ -163,8 +211,41 @@ export function apply(ctx, config) {
163
211
  learnChains: new Map(),
164
212
  lastInjection: new Map(),
165
213
  lastUser: new Map(),
214
+ activity: new Map(),
166
215
  };
167
216
 
217
+ (function loadSelections() {
218
+ try {
219
+ const raw = readFileSync(SELECTIONS_FILE, 'utf8');
220
+ const parsed = JSON.parse(raw);
221
+ if (parsed === null || typeof parsed !== 'object') return;
222
+ for (const [sessionId, value] of Object.entries(parsed)) {
223
+ if (typeof sessionId !== 'string' || value === null || typeof value !== 'object') continue;
224
+ if (typeof value.teamId !== 'string' || typeof value.agentId !== 'string') continue;
225
+ state.selections.set(sessionId, {
226
+ teamId: value.teamId,
227
+ teamName: String(value.teamName ?? ''),
228
+ agentId: value.agentId,
229
+ agentName: String(value.agentName ?? ''),
230
+ });
231
+ }
232
+ } catch {
233
+ /* a missing or corrupt file just means "no saved choices" */
234
+ }
235
+ })();
236
+
237
+ function saveSelections() {
238
+ try {
239
+ const entries = [...state.selections.entries()].slice(-SELECTIONS_LIMIT);
240
+ const payload = Object.fromEntries(entries);
241
+ const temp = `${SELECTIONS_FILE}.tmp`;
242
+ writeFileSync(temp, `${JSON.stringify(payload, null, 2)}\n`, { mode: 0o600 });
243
+ renameSync(temp, SELECTIONS_FILE);
244
+ } catch (error) {
245
+ debug({ at: 'selection-save-error', message: String(error?.message ?? error) });
246
+ }
247
+ }
248
+
168
249
  function debug(entry) {
169
250
  if (settings.debug === false) return;
170
251
  const file = `${homedir()}/.dsh/agent-memory-debug.log`;
@@ -177,9 +258,16 @@ export function apply(ctx, config) {
177
258
  }
178
259
  }
179
260
 
261
+ /** Merges one observation into the per-session activity record the panel renders. */
262
+ function noteActivity(sessionId, patch) {
263
+ if (sessionId === '') return;
264
+ const current = state.activity.get(sessionId) ?? {};
265
+ state.activity.set(sessionId, { ...current, ...patch, at: Date.now() });
266
+ }
267
+
180
268
  async function hub(rpc, body) {
181
269
  if (settings.hubUrl === '') throw new Error('Memory Hub 地址未配置:请先在插件设置里填 hubUrl');
182
- if (settings.userKey === '') throw new Error('Memory Hub userkey 未配置:请先在插件设置里填 userKey');
270
+ const headers = await authHeaders();
183
271
  const response = await fetch(`${settings.hubUrl}/api/v1/meta/${rpc}`, {
184
272
  method: 'POST',
185
273
  headers,
@@ -193,6 +281,7 @@ export function apply(ctx, config) {
193
281
  }
194
282
 
195
283
  async function chatMemory(method, body) {
284
+ const headers = await authHeaders();
196
285
  const response = await fetch(`${settings.hubUrl}/api/v1/chat-memory/${method}`, {
197
286
  method: 'POST',
198
287
  headers,
@@ -207,7 +296,7 @@ export function apply(ctx, config) {
207
296
 
208
297
  async function identity() {
209
298
  if (state.identity !== null) return state.identity;
210
- const verified = await hub('auth/verify', { user_key: settings.userKey });
299
+ const verified = await hub('auth/verify', { user_key: await userKey() });
211
300
  const userId = verified?.user?.user_id;
212
301
  if (typeof userId !== 'string' || userId === '') throw new Error('auth/verify returned no user_id');
213
302
  state.identity = { userId, username: verified.user.username ?? '' };
@@ -292,7 +381,7 @@ export function apply(ctx, config) {
292
381
  const body = typeof item.body === 'string' ? item.body.trim() : '';
293
382
  if (body === '' || seen.has(body)) continue;
294
383
  seen.add(body);
295
- collected.push({ layer, body });
384
+ collected.push({ layer, body, id: typeof item.id === 'string' ? item.id : '' });
296
385
  if (collected.length >= limit * 2) break;
297
386
  }
298
387
  if (collected.length >= limit) break;
@@ -326,10 +415,11 @@ export function apply(ctx, config) {
326
415
  async function kernel(path, body) {
327
416
  const base = kernelBase();
328
417
  if (base === '') throw new Error('内核地址未配置:请在插件设置里填 kernelUrl');
329
- if (settings.userKey === '') throw new Error('Memory Hub userkey 未配置:请在插件设置里填 userKey');
418
+ const key = await userKey();
419
+ if (key === '') throw new Error('Memory Hub userkey 未配置:请在插件设置里填 userKey');
330
420
  const response = await fetch(`${base}${path}`, {
331
421
  method: 'POST',
332
- headers: { ...headers, Authorization: `Bearer ${settings.userKey}` },
422
+ headers: { ...(await authHeaders()), Authorization: `Bearer ${key}` },
333
423
  body: JSON.stringify(body ?? {}),
334
424
  signal: AbortSignal.timeout(settings.timeoutMs * 2),
335
425
  });
@@ -419,6 +509,14 @@ export function apply(ctx, config) {
419
509
  : text;
420
510
  }
421
511
 
512
+ /** `updated_at` is the index build time; the model must know a snapshot can lag HEAD. */
513
+ function freshness(item) {
514
+ const stamp = item.updated_at ?? item.created_at ?? '';
515
+ if (typeof stamp !== 'string' || stamp === '') return '';
516
+ const day = stamp.slice(0, 10);
517
+ return day === '' ? '' : ` · 索引 ${day}`;
518
+ }
519
+
422
520
  function knowledgeListText(selection, items, options = {}) {
423
521
  const kind = options.kind === 'wiki' || options.kind === 'code-graph' ? options.kind : '';
424
522
  const needle = String(options.filter ?? '').trim().toLowerCase();
@@ -441,15 +539,19 @@ export function apply(ctx, config) {
441
539
  typeof item.summary === 'string' && item.summary !== ''
442
540
  ? ` — ${item.summary.replace(/\s+/g, ' ').slice(0, 160)}`
443
541
  : '';
444
- lines.push(`- ${item.knowledge_id} ${item.name}${about}`);
542
+ lines.push(`- ${item.knowledge_id} ${item.name}${freshness(item)}${about}`);
445
543
  }
446
544
  }
447
545
  if (graphs.length > 0) {
448
546
  // The team can hold dozens of repositories; show a slice and let the model filter.
449
547
  const shown = needle === '' ? graphs.slice(0, 20) : graphs;
450
- lines.push(`code-graph(${graphs.length} 个仓库;repo 与当前工作区一致时才值得查):`);
548
+ lines.push(
549
+ `code-graph(${graphs.length} 个仓库;repo 与当前工作区一致时才值得查;索引是分支快照,可能落后 HEAD):`,
550
+ );
451
551
  for (const item of shown) {
452
- lines.push(`- ${item.knowledge_id} ${item.name} (${item.branch ?? 'main'}) ${item.repo_url ?? ''}`.trim());
552
+ lines.push(
553
+ `- ${item.knowledge_id} ${item.name} (${item.branch ?? 'main'})${freshness(item)} ${item.repo_url ?? ''}`.trim(),
554
+ );
453
555
  }
454
556
  if (shown.length < graphs.length) {
455
557
  lines.push(`…另有 ${graphs.length - shown.length} 个仓库未列出,传 filter 按仓库名过滤。`);
@@ -493,7 +595,16 @@ export function apply(ctx, config) {
493
595
  // when the user repeats the same question.
494
596
  const dedupeKey = `${sessionId}:${selection.agentId}:${query}`;
495
597
  if (state.lastInjection.get(sessionId) === dedupeKey) return decision;
598
+ const recallStartedAt = Date.now();
496
599
  const hits = await recall(selection, query);
600
+ const recallRecord = {
601
+ agentId: selection.agentId,
602
+ agentName: selection.agentName,
603
+ hits: hits.length,
604
+ layers: [...new Set(hits.map((hit) => hit.layer))].join(','),
605
+ ms: Date.now() - recallStartedAt,
606
+ };
607
+ noteActivity(sessionId, { recall: recallRecord });
497
608
  debug({ at: 'recall', sessionId, agent: selection.agentId, query: query.slice(0, 60), hits: hits.length });
498
609
  if (hits.length === 0) return decision;
499
610
  state.lastInjection.set(sessionId, dedupeKey);
@@ -576,24 +687,31 @@ export function apply(ctx, config) {
576
687
  }, 'agent-memory: tool call capture');
577
688
 
578
689
  ctx.effect(() => {
579
- async function writeMemory(sessionId, text) {
690
+ async function writeMemory(sessionId, text, reply) {
580
691
  try {
581
692
  const selection = await selectionFor(sessionId);
582
693
  if (selection === null) return;
694
+ // The official tdai-memory extractor writes L0 as a user_query + assistant reply
695
+ // pair; a user-only record loses what the answer actually concluded.
696
+ const messages = [{ role: 'user', content: text }];
697
+ const answer = settings.writeAssistant === true ? reply.trim() : '';
698
+ if (answer !== '') messages.push({ role: 'assistant', content: answer.slice(0, 12000) });
583
699
  const data = await chatMemory('import', {
584
700
  team_id: selection.teamId,
585
701
  agent_id: selection.agentId,
586
702
  session_id: sessionId,
587
- messages: [{ role: 'user', content: text }],
703
+ messages,
588
704
  });
589
- debug({
590
- at: 'write',
591
- sessionId,
592
- agent: selection.agentId,
705
+ const record = {
593
706
  chars: text.length,
707
+ replyChars: answer.length,
594
708
  accepted: data.accepted_count ?? null,
595
- });
709
+ ok: true,
710
+ };
711
+ noteActivity(sessionId, { write: record });
712
+ debug({ at: 'write', sessionId, agent: selection.agentId, ...record });
596
713
  } catch (error) {
714
+ noteActivity(sessionId, { write: { ok: false, error: String(error?.message ?? error) } });
597
715
  debug({ at: 'write-error', sessionId, message: String(error?.message ?? error) });
598
716
  }
599
717
  }
@@ -621,16 +739,17 @@ export function apply(ctx, config) {
621
739
  session_id: sessionId,
622
740
  messages,
623
741
  });
624
- debug({
625
- at: 'learn',
626
- sessionId,
627
- agent: selection.agentId,
742
+ const record = {
628
743
  chars: userText.length + assistantText.length,
629
744
  tools: toolEntries.length,
630
745
  status: data.status ?? null,
631
746
  archived: data.archived?.reason ?? null,
632
- });
747
+ ok: true,
748
+ };
749
+ noteActivity(sessionId, { learn: record });
750
+ debug({ at: 'learn', sessionId, agent: selection.agentId, ...record });
633
751
  } catch (error) {
752
+ noteActivity(sessionId, { learn: { ok: false, error: String(error?.message ?? error) } });
634
753
  debug({ at: 'learn-error', sessionId, message: String(error?.message ?? error) });
635
754
  }
636
755
  }
@@ -647,9 +766,10 @@ export function apply(ctx, config) {
647
766
 
648
767
  if (settings.writeMemory === true) {
649
768
  if (userText.length < 20) {
769
+ noteActivity(sessionId, { write: { ok: false, skipped: 'too-short', chars: userText.length } });
650
770
  debug({ at: 'write-skip', sessionId, reason: 'too-short', chars: userText.length });
651
771
  } else {
652
- void writeMemory(sessionId, userText);
772
+ void writeMemory(sessionId, userText, assistantText);
653
773
  }
654
774
  }
655
775
  if (settings.skillLearning !== true) return;
@@ -784,7 +904,12 @@ export function apply(ctx, config) {
784
904
  if (hits.length === 0) {
785
905
  return `在「${scope.teamName}」/ ${scope.agentId || '默认 agent'} 的 ${layers.join('/')} 层没有命中。`;
786
906
  }
787
- return hits.map((hit, index) => `${index + 1}. (${hit.layer}) ${hit.body}`).join('\n');
907
+ return hits
908
+ .map(
909
+ (hit, index) =>
910
+ `${index + 1}. (${hit.layer}) ${hit.body}${hit.id === '' ? '' : `\n id=${hit.id}`}`,
911
+ )
912
+ .join('\n');
788
913
  },
789
914
  });
790
915
  register({
@@ -847,6 +972,43 @@ export function apply(ctx, config) {
847
972
  return clip(`# 技能 ${data.name ?? skillId}(id=${skillId} v${data.version ?? '?'})\n\n${content}`);
848
973
  },
849
974
  });
975
+ register({
976
+ name: 'am_memory_update',
977
+ description:
978
+ '改写当前专家记忆库里的一条 L1(原子记忆)或 L2(场景文件)记忆。先用 am_memory_search 拿到该条的 id 与层,再传新正文;用于纠正过时或错误的约定。L0 原文只读,L3 是整块内容(Hub 不接受按条改写),两者都会被拒绝。Hub 没有删除接口,只能用改写覆盖内容。',
979
+ parameters: {
980
+ type: 'object',
981
+ properties: {
982
+ layer: { type: 'string', description: '只能传 L1 或 L2(L0 原文只读、L3 为整块内容,Hub 拒绝按条改写)。' },
983
+ id: { type: 'string', description: '记忆条目 id,来自 am_memory_search 的 id= 行。' },
984
+ content: { type: 'string', description: '新的正文内容(整条覆盖)。' },
985
+ },
986
+ required: ['layer', 'id', 'content'],
987
+ additionalProperties: false,
988
+ },
989
+ output: textOutput,
990
+ isConcurrencySafe: () => false,
991
+ async execute(args, exec) {
992
+ const layer = String(args.layer ?? '').trim().toUpperCase();
993
+ const id = String(args.id ?? '').trim();
994
+ const content = String(args.content ?? '').trim();
995
+ if (layer === 'L0') {
996
+ throw new Error('L0 是原始对话,Hub 不支持按条改写(layer-update 对 L0 返回 INVALID_LAYER)');
997
+ }
998
+ if (layer === 'L3') {
999
+ throw new Error('L3 是整块内容,layer-update 会覆盖全部 L3(Hub 不接受按条改写),已拒绝');
1000
+ }
1001
+ if (layer !== 'L1' && layer !== 'L2') throw new Error('layer 只能是 L1 或 L2');
1002
+ if (id === '') throw new Error('id 不能为空');
1003
+ if (content === '') throw new Error('content 不能为空');
1004
+ const scope = await toolScope(exec);
1005
+ if (!scope.agentId) throw new Error('当前会话还没有选专家:请先在「请选择专家」里选一个,再改写它的记忆');
1006
+ const block = await blockId(scope.teamId, scope.agentId);
1007
+ await chatMemory('layer-update', { block_id: block, layer, id, content });
1008
+ noteActivity(String(exec?.agent?.id ?? ''), { update: { at: Date.now(), layer, id, chars: content.length } });
1009
+ return `已改写 ${layer} 记忆 ${id}(${content.length} 字符)。`;
1010
+ },
1011
+ });
850
1012
  return () => {
851
1013
  for (const dispose of disposers) {
852
1014
  try {
@@ -957,6 +1119,8 @@ export function apply(ctx, config) {
957
1119
  }
958
1120
  const url = new URL(request.url ?? '/', 'http://localhost');
959
1121
  const sessionId = url.searchParams.get('session') ?? '';
1122
+ const activeKey = await userKey();
1123
+ const credentialBacked = (await readStoredUserKey()) !== '';
960
1124
  try {
961
1125
  let knownTeams = [];
962
1126
  let loadError = '';
@@ -975,11 +1139,12 @@ export function apply(ctx, config) {
975
1139
  config: {
976
1140
  hubUrl: settings.hubUrl,
977
1141
  instanceId: settings.instanceId,
978
- userKeySet: settings.userKey !== '',
979
- userKeyHint:
980
- settings.userKey === '' ? '' : `****${settings.userKey.slice(-4)}`,
1142
+ userKeySet: activeKey !== '',
1143
+ userKeySource: credentialBacked ? 'credentials' : activeKey === '' ? 'none' : 'config',
1144
+ userKeyHint: activeKey === '' ? '' : `****${activeKey.slice(-4)}`,
981
1145
  injectMemory: settings.injectMemory,
982
1146
  writeMemory: settings.writeMemory,
1147
+ writeAssistant: settings.writeAssistant,
983
1148
  topK: settings.topK,
984
1149
  layers: settings.layers.join(','),
985
1150
  refreshMs: settings.refreshMs,
@@ -988,6 +1153,7 @@ export function apply(ctx, config) {
988
1153
  skillLearning: settings.skillLearning,
989
1154
  debug: settings.debug,
990
1155
  },
1156
+ activity: sessionId === '' ? null : (state.activity.get(sessionId) ?? null),
991
1157
  });
992
1158
  } catch (error) {
993
1159
  reply(response, 502, { error: String(error?.message ?? error) });
@@ -1118,13 +1284,18 @@ export function apply(ctx, config) {
1118
1284
  if (typeof body.instanceId === 'string' && body.instanceId.trim() !== '') {
1119
1285
  patch.instanceId = body.instanceId.trim();
1120
1286
  }
1287
+ let savedKey = '';
1121
1288
  if (typeof body.userKey === 'string' && body.userKey.trim() !== '') {
1122
- patch.userKey = body.userKey.trim();
1289
+ savedKey = body.userKey.trim();
1290
+ // The patch keeps `userKey: ''` from now on: the value lives in the
1291
+ // credentials store so the profile file never carries the secret.
1292
+ patch.userKey = '';
1123
1293
  }
1124
1294
  // An empty string clears the default expert, so the composer starts at 「请选择专家」.
1125
1295
  if (typeof body.defaultAgentId === 'string') patch.defaultAgentId = body.defaultAgentId.trim();
1126
1296
  if (typeof body.injectMemory === 'boolean') patch.injectMemory = body.injectMemory;
1127
1297
  if (typeof body.writeMemory === 'boolean') patch.writeMemory = body.writeMemory;
1298
+ if (typeof body.writeAssistant === 'boolean') patch.writeAssistant = body.writeAssistant;
1128
1299
  if (Number.isFinite(body.topK)) patch.topK = Math.max(1, Math.min(10, body.topK));
1129
1300
  if (typeof body.layers === 'string') patch.layers = parseLayers(body.layers).join(',');
1130
1301
  if (Number.isFinite(body.timeoutMs)) patch.timeoutMs = Math.max(1000, body.timeoutMs);
@@ -1135,6 +1306,19 @@ export function apply(ctx, config) {
1135
1306
  if (typeof body.kernelUrl === 'string') patch.kernelUrl = body.kernelUrl.trim().replace(/\/+$/, '');
1136
1307
  if (typeof body.tools === 'boolean') patch.tools = body.tools;
1137
1308
  if (typeof body.skillLearning === 'boolean') patch.skillLearning = body.skillLearning;
1309
+ if (savedKey !== '') {
1310
+ const stored = await saveStoredUserKey(savedKey);
1311
+ if (!stored) {
1312
+ // Without a credentials service the config value is the only place left.
1313
+ patch.userKey = savedKey;
1314
+ } else {
1315
+ state.identity = null;
1316
+ state.teams = [];
1317
+ state.teamsAt = 0;
1318
+ state.blocks.clear();
1319
+ state.assets.clear();
1320
+ }
1321
+ }
1138
1322
  if (Object.keys(patch).length === 0) {
1139
1323
  reply(response, 400, { error: 'no editable field in request' });
1140
1324
  return;
@@ -1222,6 +1406,7 @@ export function apply(ctx, config) {
1222
1406
  if (teamId === '' || agentId === '') {
1223
1407
  state.selections.delete(sessionId);
1224
1408
  state.lastInjection.delete(sessionId);
1409
+ saveSelections();
1225
1410
  reply(response, 200, { selection: null });
1226
1411
  return;
1227
1412
  }
@@ -1249,6 +1434,7 @@ export function apply(ctx, config) {
1249
1434
  };
1250
1435
  state.selections.set(sessionId, selection);
1251
1436
  state.lastInjection.delete(sessionId);
1437
+ saveSelections();
1252
1438
  reply(response, 200, { selection });
1253
1439
  } catch (error) {
1254
1440
  reply(response, 400, { error: String(error?.message ?? error) });
@@ -1258,6 +1444,63 @@ export function apply(ctx, config) {
1258
1444
  'agent-memory: select route',
1259
1445
  );
1260
1446
 
1447
+ mount(
1448
+ () =>
1449
+ webServer.register({
1450
+ kind: 'exact',
1451
+ path: '/plugins/agent-memory/memory',
1452
+ handler: async (request, response) => {
1453
+ if (!sameSite(request)) {
1454
+ reply(response, 403, { error: 'forbidden' });
1455
+ return;
1456
+ }
1457
+ const url = new URL(request.url ?? '/', 'http://localhost');
1458
+ const sessionId = url.searchParams.get('session') ?? '';
1459
+ const layer = (url.searchParams.get('layer') ?? 'L3').toUpperCase();
1460
+ const query = (url.searchParams.get('query') ?? '').trim();
1461
+ const offset = Math.max(0, Number(url.searchParams.get('offset') ?? '0') || 0);
1462
+ if (!['L0', 'L1', 'L2', 'L3'].includes(layer)) {
1463
+ reply(response, 400, { error: 'layer must be L0/L1/L2/L3' });
1464
+ return;
1465
+ }
1466
+ try {
1467
+ const selection = sessionId === '' ? null : await selectionFor(sessionId);
1468
+ if (selection === null || selection.agentId === '') {
1469
+ reply(response, 200, { selection: null, layer, items: [], counts: null });
1470
+ return;
1471
+ }
1472
+ const block = await blockId(selection.teamId, selection.agentId);
1473
+ // An empty query browses the layer in order; a query ranks it by similarity.
1474
+ const data =
1475
+ query === ''
1476
+ ? await chatMemory('layer', { block_id: block, layer, limit: 20, offset })
1477
+ : await chatMemory('search', { block_id: block, layer, query, limit: 20 });
1478
+ const items = Array.isArray(data.items) ? data.items : [];
1479
+ const fixed = await chatMemory('agent-fixed', { agent_id: selection.agentId }).catch(() => null);
1480
+ const fixedItem = Array.isArray(fixed?.items) ? fixed.items[0] : fixed;
1481
+ const counts = fixedItem?.layer_counts ?? null;
1482
+ reply(response, 200, {
1483
+ selection,
1484
+ layer,
1485
+ query,
1486
+ offset,
1487
+ items: items.map((item) => ({
1488
+ id: String(item.id ?? ''),
1489
+ body: typeof item.body === 'string' ? item.body : '',
1490
+ role: String(item.role ?? ''),
1491
+ createdAt: String(item.created_at ?? ''),
1492
+ score: typeof item.score === 'number' ? item.score : null,
1493
+ })),
1494
+ counts,
1495
+ });
1496
+ } catch (error) {
1497
+ reply(response, 502, { error: String(error?.message ?? error) });
1498
+ }
1499
+ },
1500
+ }),
1501
+ 'agent-memory: memory route',
1502
+ );
1503
+
1261
1504
  mount(
1262
1505
  () =>
1263
1506
  webServer.register({
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "dsh-plugin-agent-memory",
3
- "version": "0.2.1",
3
+ "version": "0.3.0",
4
4
  "type": "module",
5
- "description": "Tencent agent-memory integration for DeepSeek Harness: pick a team agent as an expert, recall its memories each turn, use its wiki / code-graph / skill assets as tools, and feed finished turns back for skill learning.",
5
+ "description": "Tencent agent-memory integration for DeepSeek Harness: choose a team agent as the session expert, recall its memories each turn, browse and correct them, use wiki / code-graph / skill assets as tools, and feed finished turns back for skill learning.",
6
6
  "license": "MIT",
7
7
  "keywords": [
8
8
  "dsh-plugin",
@@ -44,5 +44,12 @@
44
44
  "icon": "./icon.svg",
45
45
  "dependencies": {
46
46
  "@deepseek-ai/schemastery": "^3.19.0"
47
+ },
48
+ "devDependencies": {
49
+ "vitest": "^5.1.2"
50
+ },
51
+ "scripts": {
52
+ "test": "vitest run",
53
+ "check": "node --check index.js && node --check client.js"
47
54
  }
48
55
  }