dsh-plugin-agent-memory 0.1.8 → 0.2.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
@@ -49,12 +49,24 @@ Open the plugin's settings page (or the panel's gear button) and set:
49
49
  | `topK` | Max memories per recall (1–10, default 4) |
50
50
  | `layers` | Memory layers injected each turn (default `L3,L2`, matching the official proxy) |
51
51
  | `timeoutMs` | Per-request timeout (default 6000) |
52
- | `kernelUrl` | Kernel API base for wiki / code-graph / skills (default: Hub host on port 8420) |
53
- | `tools` | Register the four read-only asset tools (default on) |
52
+ | `kernelUrl` | Kernel API base for wiki / code-graph / skills (default: Hub host on port 8420). The knowledge service address is discovered from the kernel, and the proxy endpoint is not used |
53
+ | `tools` | Register the read-only asset tools (default on) |
54
+ | `skillLearning` | Send each finished turn to the kernel (`/v3/skill/conversation/add`) so agent-memory can archive it and extract skills (default **off**) |
54
55
  | `debug` | Append diagnostics to `~/.dsh/agent-memory-debug.log` (default off, 256 KiB cap) |
55
56
 
56
57
  With no `hubUrl` or `userKey` the plugin stays idle: the selector is hidden and nothing is sent.
57
58
 
59
+ ## Skill learning
60
+
61
+ agent-memory grows skills by reading finished conversations. With `skillLearning` on, each closed
62
+ turn is posted to the kernel with its user message, the turn's tool calls and results, and the
63
+ assistant's reply. The kernel buffers turns per session and archives them on its own thresholds
64
+ (roughly ten tool calls or 40 KiB), which is what queues a skill-extraction task; a single short
65
+ turn staying `ok` instead of `archived` is expected.
66
+
67
+ The plugin sends one turn per request, strictly ordered per session, and only when the session has an
68
+ expert selected (the expert supplies the team and agent the skill belongs to).
69
+
58
70
  ## What data leaves the machine
59
71
 
60
72
  - The Hub URL and user key are only used by the Host half; the browser talks to same-origin
package/client.js CHANGED
@@ -138,7 +138,7 @@ window.__ModuleLoader__.load({
138
138
  const [config, setConfig] = React.useState(null);
139
139
  const [configured, setConfigured] = React.useState(true);
140
140
  const [health, setHealth] = React.useState({ state: 'idle', text: '连接未检测' });
141
- const [form, setForm] = React.useState({ hubUrl: '', instanceId: '', userKey: '' });
141
+ const [form, setForm] = React.useState({ hubUrl: '', instanceId: '', kernelUrl: '', userKey: '' });
142
142
  const [flags, setFlags] = React.useState({ injectMemory: true, writeMemory: false });
143
143
  const [refreshMs, setRefreshMs] = React.useState(10000);
144
144
  const [saving, setSaving] = React.useState(false);
@@ -160,6 +160,7 @@ window.__ModuleLoader__.load({
160
160
  setForm({
161
161
  hubUrl: String(current.hubUrl ?? ''),
162
162
  instanceId: String(current.instanceId ?? ''),
163
+ kernelUrl: String(current.kernelUrl ?? ''),
163
164
  userKey: '',
164
165
  });
165
166
  setFlags({
@@ -181,9 +182,13 @@ window.__ModuleLoader__.load({
181
182
  json(`${ROUTE}/health`)
182
183
  .then((payload) => {
183
184
  const agents = (payload.teams ?? []).reduce((total, team) => total + (team.agents ?? 0), 0);
185
+ const down = (payload.services ?? []).filter((service) => service.ok !== true);
184
186
  setHealth({
185
- state: 'ok',
186
- text: `已连接 · ${payload.user?.username ?? '未知用户'} · ${(payload.teams ?? []).length} 团队 / ${agents} agent · ${payload.latencyMs ?? '?'}ms`,
187
+ state: down.length === 0 && payload.ok !== false ? 'ok' : 'bad',
188
+ text:
189
+ down.length === 0
190
+ ? `已连接 · ${payload.user?.username ?? '未知用户'} · ${(payload.teams ?? []).length} 团队 / ${agents} agent`
191
+ : `部分服务不可用:${down.map((service) => `${service.name}(${service.detail})`).join(';')}`,
187
192
  });
188
193
  })
189
194
  .catch((failure) => setHealth({ state: 'bad', text: `连接失败:${String(failure.message ?? failure)}` }));
@@ -198,6 +203,7 @@ window.__ModuleLoader__.load({
198
203
  body: JSON.stringify({
199
204
  hubUrl: form.hubUrl,
200
205
  instanceId: form.instanceId,
206
+ kernelUrl: form.kernelUrl,
201
207
  userKey: form.userKey,
202
208
  injectMemory: flags.injectMemory,
203
209
  refreshMs,
@@ -402,6 +408,18 @@ window.__ModuleLoader__.load({
402
408
  onChange: (event) => setForm({ ...form, instanceId: event.target.value }),
403
409
  }),
404
410
  ),
411
+ h(
412
+ 'label',
413
+ { style: fieldStyle },
414
+ h('span', { style: fieldLabelStyle }, '内核地址(选填,默认 Hub 主机名:8420)'),
415
+ h('input', {
416
+ style: inputStyle,
417
+ type: 'text',
418
+ value: form.kernelUrl,
419
+ placeholder: 'http://memhub.example.com:8420',
420
+ onChange: (event) => setForm({ ...form, kernelUrl: event.target.value }),
421
+ }),
422
+ ),
405
423
  h(
406
424
  'label',
407
425
  { style: fieldStyle },
package/docs/DETAIL.md CHANGED
@@ -23,11 +23,25 @@
23
23
  | `layers` | 每轮预注入的记忆层,逗号分隔,默认 `L3,L2`;需要更细的原文可加 `L1,L0`,或用 `am_memory_search` 按需查 |
24
24
  | `timeoutMs` | 单次 Hub 请求超时 |
25
25
  | `kernelUrl` | 内核 API 地址(知识库 / code-graph / 技能),默认按 Hub 主机名 + `8420` 推断;显式填写更稳妥 |
26
- | `tools` | 是否注册上述 4 个资产工具(默认开) |
26
+ | `tools` | 是否注册上述资产工具(默认开) |
27
+ | `skillLearning` | 每轮结束后把该轮对话(用户消息 + 工具调用/结果 + 助手回复)写入内核 `/v3/skill/conversation/add`,让 agent-memory 归档会话并抽取技能(默认关) |
27
28
  | `debug` | 是否写诊断日志(默认关) |
28
29
 
29
30
  Host 半侧导出了 `z.object` 形式的 `Config`(`userKey` 标了 `role('secret')`),因此插件详情页也能看到同名字段的表单;字段保存走框架的 `configEditor`,写入后提示重启插件以重建内存状态。
30
31
 
32
+ ## 需要配置哪些服务
33
+
34
+ AM 一套部署有四个服务,插件只用到其中三个,且只有两个需要填:
35
+
36
+ | 服务 | 本实例地址 | 插件是否用 | 配置项 |
37
+ | --- | --- | --- | --- |
38
+ | Panel UI(Memory Hub 控制面) | `:8125` | 用:`auth/verify`、`team/list`、`agent/list`、`chat-memory/*` | `hubUrl` + `userKey`(必填) |
39
+ | Core Gateway(记忆内核) | `:8420` | 用:`/v3/knowledge/list`、`/v3/skill/*` | `kernelUrl`(可留空,按 Hub 主机名 + 8420 推断) |
40
+ | Knowledge 知识服务 | `:8424` | 用:每个资源的 `/tools/list`、`/tools/call` | **不需要配**:地址由内核 `knowledge/list` 返回的 `service_url` 下发,一个实例可能有多个 |
41
+ | Proxy 客户端接入点 | `:8096` | **不用**:那条链路是把整轮 LLM 请求换到 AM,本插件走 Host 内直连 | 无 |
42
+
43
+ 「检测连接」会分别探测这三个用到的服务,任何一项挂掉会在面板上直接点名。
44
+
31
45
  ## 边界
32
46
 
33
47
  - user key 只存在 Host 进程里,浏览器侧只访问本机同源路由,不接触凭据。
@@ -36,6 +50,7 @@ Host 半侧导出了 `z.object` 形式的 `Config`(`userKey` 标了 `role('sec
36
50
  - 写回时会丢掉运行期注入的噪声文本(子 agent 完成通知、审批策略变更通知、计划任务消息、技能注入),否则这些模板文字会污染记忆。
37
51
  - Hub 没有可用的按条删除路由(`chat-memory/clear` 恒返回 `BLOCK_NOT_FOUND`),写错的记忆只能在记忆管理界面清理。
38
52
  - 团队与 agent 列表有缓存,默认 10 秒(`refreshMs`),选择器按同一间隔自动刷新。
53
+ - 技能自学习走内核 `/v3/skill/conversation/add`:每轮一次、按 session 严格串行、只在该会话选了专家时发送(团队与 agent 由专家提供)。内核按阈值(约 10 次工具调用或 40 KiB)归档后才会排入技能抽取任务,短回合返回 `ok` 而非 `archived` 属正常。
39
54
  - 资产工具只读:知识库 / code-graph 走知识服务的 `tools/list` + `tools/call`,技能走内核 `/v3/skill/*`;user key 只在 Host 里加进请求头,不进 prompt、不进浏览器。
40
55
  - code-graph 是分支快照,需要某段代码此刻的精确内容时应读工作区源码;插件在工具描述里也这样要求模型。
41
56
  - 插件自带 `GET /plugins/agent-memory/health`(回连 Hub 校验 userkey 并汇总团队 / agent 数)与 `POST /plugins/agent-memory/config`(保存设置);两条路由都只接受回环地址来源的浏览器请求,跨站请求返回 403。
package/index.js CHANGED
@@ -53,6 +53,10 @@ export const Config = z.object({
53
53
  .default('')
54
54
  .description('内核 API 地址(知识库 / code-graph / 技能),例如 http://memhub.example.com:8420;留空则按 Hub 主机名 + 8420 推断'),
55
55
  tools: z.boolean().default(true).description('向模型提供知识库 / code-graph / 技能三类只读工具'),
56
+ skillLearning: z
57
+ .boolean()
58
+ .default(false)
59
+ .description('每轮结束后把该轮对话写入内核(/v3/skill/conversation/add),让 agent-memory 归档会话并抽取技能'),
56
60
  debug: z.boolean().default(false).description('把召回/写回诊断写入 ~/.dsh/agent-memory-debug.log'),
57
61
  });
58
62
 
@@ -80,6 +84,7 @@ function lastUserText(messages) {
80
84
  }
81
85
 
82
86
  const WRITE_NOISE = [
87
+ /^Time sampled while preparing turn /,
83
88
  /^Background subagent /,
84
89
  /^The user changed the approval policy/,
85
90
  /^\[Scheduled message\]/,
@@ -124,6 +129,7 @@ function normalizeConfig(config) {
124
129
  refreshMs: Number.isFinite(value.refreshMs) ? Math.max(3000, Math.min(600000, value.refreshMs)) : DEFAULT_REFRESH_MS,
125
130
  kernelUrl: typeof value.kernelUrl === 'string' ? value.kernelUrl.trim().replace(/\/+$/, '') : '',
126
131
  tools: value.tools !== false,
132
+ skillLearning: value.skillLearning === true,
127
133
  debug: value.debug === true,
128
134
  };
129
135
  }
@@ -152,6 +158,9 @@ export function apply(ctx, config) {
152
158
  selections: new Map(),
153
159
  blocks: new Map(),
154
160
  assets: new Map(),
161
+ assistantText: new Map(),
162
+ turnTools: new Map(),
163
+ learnChains: new Map(),
155
164
  lastInjection: new Map(),
156
165
  lastUser: new Map(),
157
166
  };
@@ -510,17 +519,64 @@ export function apply(ctx, config) {
510
519
  return () => off();
511
520
  }, 'agent-memory: recall injection');
512
521
 
522
+ /** Collect the assistant's text for the current turn; `agent/turn-stopping` carries no messages. */
513
523
  ctx.effect(() => {
514
- const onTurnStopping = async function (payload) {
515
- if (settings.writeMemory !== true) return;
524
+ const onStream = function (payload) {
525
+ const frame = payload?.frame;
526
+ if (frame === undefined || frame.type !== 'chunk') return;
527
+ const chunk = frame.chunk;
528
+ if (chunk === undefined || chunk.type !== 'text-delta' || typeof chunk.text !== 'string') return;
516
529
  const sessionId = String(payload?.agent?.id ?? '');
517
530
  if (sessionId === '') return;
518
- const text = writeBackText(state.lastUser.get(sessionId) ?? '');
519
- state.lastUser.delete(sessionId);
520
- if (text.length < 20) {
521
- debug({ at: 'write-skip', sessionId, reason: 'too-short', chars: text.length });
522
- return;
531
+ const current = state.assistantText.get(sessionId) ?? '';
532
+ // One turn is bounded; a runaway stream must not grow without limit.
533
+ if (current.length > 20000) return;
534
+ state.assistantText.set(sessionId, current + chunk.text);
535
+ };
536
+ const off = ctx.on('agent/assistant-stream', onStream, { global: true });
537
+ return () => off();
538
+ }, 'agent-memory: assistant text capture');
539
+
540
+ // The kernel archives a conversation into skill extraction by counting tool calls and bytes,
541
+ // so a turn that never reports its tool calls may never produce a skill.
542
+ ctx.effect(() => {
543
+ const TOOL_ENTRY_LIMIT = 30;
544
+ const TOOL_CONTENT_LIMIT = 2000;
545
+ const onSessionEvent = function (session, event) {
546
+ const type = typeof event?.type === 'string' ? event.type : '';
547
+ if (type !== 'tool/call' && type !== 'tool/result') return;
548
+ const sessionId = String(session?.id ?? '');
549
+ if (sessionId === '') return;
550
+ const data = event.data ?? {};
551
+ const bucket = state.turnTools.get(sessionId) ?? [];
552
+ if (bucket.length >= TOOL_ENTRY_LIMIT) return;
553
+ // `SessionEvent` wraps its payload in `data`, and the kernel rejects an empty
554
+ // tool_call_id, so a call without one gets a positional placeholder.
555
+ const fallbackId = `tool-${bucket.length + 1}`;
556
+ if (type === 'tool/call') {
557
+ const name = typeof data.name === 'string' ? data.name : 'tool';
558
+ bucket.push({
559
+ role: 'tool_call',
560
+ tool_name: name,
561
+ tool_call_id: String(data.callId ?? '') || fallbackId,
562
+ content: `${name}(${String(data.arguments ?? '').slice(0, TOOL_CONTENT_LIMIT)})`,
563
+ });
564
+ } else {
565
+ const message = data.message ?? {};
566
+ bucket.push({
567
+ role: 'tool_result',
568
+ tool_call_id: String(message.toolCallId ?? '') || fallbackId,
569
+ content: textOf(message.content).trim().slice(0, TOOL_CONTENT_LIMIT),
570
+ });
523
571
  }
572
+ state.turnTools.set(sessionId, bucket);
573
+ };
574
+ const off = ctx.on('session/event', onSessionEvent, { global: true });
575
+ return () => off();
576
+ }, 'agent-memory: tool call capture');
577
+
578
+ ctx.effect(() => {
579
+ async function writeMemory(sessionId, text) {
524
580
  try {
525
581
  const selection = await selectionFor(sessionId);
526
582
  if (selection === null) return;
@@ -540,6 +596,75 @@ export function apply(ctx, config) {
540
596
  } catch (error) {
541
597
  debug({ at: 'write-error', sessionId, message: String(error?.message ?? error) });
542
598
  }
599
+ }
600
+
601
+ /**
602
+ * The skill extractor reads finished conversations from the kernel; without this call a DSH
603
+ * conversation never becomes a skill. The kernel requires one session's adds to be ordered.
604
+ */
605
+ async function learnSkills(sessionId, userText, assistantText, toolEntries) {
606
+ try {
607
+ const selection = await selectionFor(sessionId);
608
+ if (selection === null || selection.agentId === '') return;
609
+ const messages = [];
610
+ if (userText !== '') messages.push({ role: 'user', content: userText.slice(0, 12000) });
611
+ for (const entry of toolEntries) messages.push(entry);
612
+ if (assistantText !== '') messages.push({ role: 'assistant', content: assistantText.slice(0, 12000) });
613
+ if (messages.length === 0) return;
614
+ // The kernel validates IdFields strictly: user_id is required even though the
615
+ // agent and team already identify the memory scope.
616
+ const me = await identity();
617
+ const data = await kernel('/v3/skill/conversation/add', {
618
+ user_id: me.userId,
619
+ team_id: selection.teamId,
620
+ agent_id: selection.agentId,
621
+ session_id: sessionId,
622
+ messages,
623
+ });
624
+ debug({
625
+ at: 'learn',
626
+ sessionId,
627
+ agent: selection.agentId,
628
+ chars: userText.length + assistantText.length,
629
+ tools: toolEntries.length,
630
+ status: data.status ?? null,
631
+ archived: data.archived?.reason ?? null,
632
+ });
633
+ } catch (error) {
634
+ debug({ at: 'learn-error', sessionId, message: String(error?.message ?? error) });
635
+ }
636
+ }
637
+
638
+ const onTurnStopping = function (payload) {
639
+ const sessionId = String(payload?.agent?.id ?? '');
640
+ if (sessionId === '') return;
641
+ const assistantText = state.assistantText.get(sessionId) ?? '';
642
+ state.assistantText.delete(sessionId);
643
+ const userText = writeBackText(state.lastUser.get(sessionId) ?? '');
644
+ state.lastUser.delete(sessionId);
645
+ const toolEntries = state.turnTools.get(sessionId) ?? [];
646
+ state.turnTools.delete(sessionId);
647
+
648
+ if (settings.writeMemory === true) {
649
+ if (userText.length < 20) {
650
+ debug({ at: 'write-skip', sessionId, reason: 'too-short', chars: userText.length });
651
+ } else {
652
+ void writeMemory(sessionId, userText);
653
+ }
654
+ }
655
+ if (settings.skillLearning !== true) return;
656
+ if (userText.length + assistantText.length + toolEntries.length < 20) {
657
+ debug({ at: 'learn-skip', sessionId, reason: 'too-short' });
658
+ return;
659
+ }
660
+ const previous = state.learnChains.get(sessionId) ?? Promise.resolve();
661
+ const next = previous
662
+ .catch(() => {})
663
+ .then(() => learnSkills(sessionId, userText, assistantText, toolEntries))
664
+ .finally(() => {
665
+ if (state.learnChains.get(sessionId) === next) state.learnChains.delete(sessionId);
666
+ });
667
+ state.learnChains.set(sessionId, next);
543
668
  };
544
669
  const off = ctx.on('agent/turn-stopping', onTurnStopping, { global: true });
545
670
  return () => off();
@@ -845,6 +970,7 @@ export function apply(ctx, config) {
845
970
  refreshMs: settings.refreshMs,
846
971
  kernelUrl: kernelBase(),
847
972
  tools: settings.tools,
973
+ skillLearning: settings.skillLearning,
848
974
  debug: settings.debug,
849
975
  },
850
976
  });
@@ -884,13 +1010,58 @@ export function apply(ctx, config) {
884
1010
  owned,
885
1011
  });
886
1012
  }
1013
+ // The asset tools depend on two more services; report them separately so a
1014
+ // broken kernel or knowledge endpoint is visible without reading logs.
1015
+ const services = [
1016
+ { name: 'hub', url: settings.hubUrl, ok: true, detail: `user ${me.username || me.userId}` },
1017
+ ];
1018
+ let knowledgeItem = null;
1019
+ try {
1020
+ const items = await knowledgeResourcesAll();
1021
+ knowledgeItem = items[0] ?? null;
1022
+ services.push({
1023
+ name: 'kernel',
1024
+ url: kernelBase(),
1025
+ ok: true,
1026
+ detail: `${items.length} 个知识资源`,
1027
+ });
1028
+ } catch (error) {
1029
+ services.push({
1030
+ name: 'kernel',
1031
+ url: kernelBase(),
1032
+ ok: false,
1033
+ detail: String(error?.message ?? error),
1034
+ });
1035
+ }
1036
+ if (knowledgeItem !== null) {
1037
+ try {
1038
+ await knowledgeService(knowledgeItem.service_url, '/tools/list', {
1039
+ knowledge_id: knowledgeItem.knowledge_id,
1040
+ });
1041
+ services.push({
1042
+ name: 'knowledge',
1043
+ url: String(knowledgeItem.service_url),
1044
+ ok: true,
1045
+ detail: `tools/list 可达(${knowledgeItem.name})`,
1046
+ });
1047
+ } catch (error) {
1048
+ services.push({
1049
+ name: 'knowledge',
1050
+ url: String(knowledgeItem.service_url),
1051
+ ok: false,
1052
+ detail: String(error?.message ?? error),
1053
+ });
1054
+ }
1055
+ }
887
1056
  reply(response, 200, {
888
- ok: true,
1057
+ ok: services.every((service) => service.ok),
889
1058
  hubUrl: settings.hubUrl,
1059
+ kernelUrl: kernelBase(),
890
1060
  latencyMs: Date.now() - startedAt,
891
1061
  user: { userId: me.userId, username: me.username },
892
1062
  agents: agentCount,
893
1063
  teams: teamDetails,
1064
+ services,
894
1065
  });
895
1066
  } catch (error) {
896
1067
  reply(response, 502, { ok: false, error: String(error?.message ?? error) });
@@ -948,6 +1119,7 @@ export function apply(ctx, config) {
948
1119
  if (typeof body.debug === 'boolean') patch.debug = body.debug;
949
1120
  if (typeof body.kernelUrl === 'string') patch.kernelUrl = body.kernelUrl.trim().replace(/\/+$/, '');
950
1121
  if (typeof body.tools === 'boolean') patch.tools = body.tools;
1122
+ if (typeof body.skillLearning === 'boolean') patch.skillLearning = body.skillLearning;
951
1123
  if (Object.keys(patch).length === 0) {
952
1124
  reply(response, 400, { error: 'no editable field in request' });
953
1125
  return;
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "dsh-plugin-agent-memory",
3
- "version": "0.1.8",
3
+ "version": "0.2.0",
4
4
  "type": "module",
5
- "description": "Tencent agent-memory integration: pick a team agent as an expert at the composer, recall its memories into each turn, and expose its wiki, code-graph and skill assets as tools.",
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.",
6
6
  "license": "MIT",
7
7
  "keywords": [
8
8
  "dsh-plugin",