dsh-plugin-agent-memory 0.1.9 → 0.2.1

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
@@ -50,11 +50,23 @@ Open the plugin's settings page (or the panel's gear button) and set:
50
50
  | `layers` | Memory layers injected each turn (default `L3,L2`, matching the official proxy) |
51
51
  | `timeoutMs` | Per-request timeout (default 6000) |
52
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 four read-only asset tools (default on) |
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
@@ -121,6 +121,9 @@ window.__ModuleLoader__.load({
121
121
  ...init,
122
122
  });
123
123
  const payload = await response.json().catch(() => null);
124
+ if (response.status === 404) {
125
+ throw new Error('插件路由未就绪(404):重新加载插件或刷新页面后重试');
126
+ }
124
127
  if (!response.ok) throw new Error(payload?.error ?? `HTTP ${response.status}`);
125
128
  return payload;
126
129
  }
package/docs/DETAIL.md CHANGED
@@ -23,7 +23,8 @@
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`,写入后提示重启插件以重建内存状态。
@@ -49,6 +50,7 @@ AM 一套部署有四个服务,插件只用到其中三个,且只有两个
49
50
  - 写回时会丢掉运行期注入的噪声文本(子 agent 完成通知、审批策略变更通知、计划任务消息、技能注入),否则这些模板文字会污染记忆。
50
51
  - Hub 没有可用的按条删除路由(`chat-memory/clear` 恒返回 `BLOCK_NOT_FOUND`),写错的记忆只能在记忆管理界面清理。
51
52
  - 团队与 agent 列表有缓存,默认 10 秒(`refreshMs`),选择器按同一间隔自动刷新。
53
+ - 技能自学习走内核 `/v3/skill/conversation/add`:每轮一次、按 session 严格串行、只在该会话选了专家时发送(团队与 agent 由专家提供)。内核按阈值(约 10 次工具调用或 40 KiB)归档后才会排入技能抽取任务,短回合返回 `ok` 而非 `archived` 属正常。
52
54
  - 资产工具只读:知识库 / code-graph 走知识服务的 `tools/list` + `tools/call`,技能走内核 `/v3/skill/*`;user key 只在 Host 里加进请求头,不进 prompt、不进浏览器。
53
55
  - code-graph 是分支快照,需要某段代码此刻的精确内容时应读工作区源码;插件在工具描述里也这样要求模型。
54
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();
@@ -559,8 +684,17 @@ export function apply(ctx, config) {
559
684
  }
560
685
  const textOutput = { schema: { type: 'string' }, render: (_args, text) => [{ type: 'text', text }] };
561
686
  const disposers = [];
562
- disposers.push(
563
- tools.register({
687
+ // A duplicate name (a stale fiber still holding it) must not abort activation: the
688
+ // rest of `apply` — the browser routes included — would be skipped.
689
+ const register = (definition) => {
690
+ try {
691
+ disposers.push(tools.register(definition));
692
+ } catch (error) {
693
+ ctx.logger?.warn?.(`[agent-memory] tool ${definition.name} not registered: ${error?.message ?? error}`);
694
+ debug({ at: 'tool-error', name: definition.name, message: String(error?.message ?? error) });
695
+ }
696
+ };
697
+ register({
564
698
  name: 'am_knowledge_resources',
565
699
  description:
566
700
  '列出当前团队 agent-memory 的知识资源:code-graph(仓库的预建代码索引:符号/调用图/结构)与 wiki(工程设计文档)。code-graph 的 repo 与你当前工作区一致时才值得查;wiki 与工作区无关,按 about 判断相关性。拿到 id 后用 am_knowledge_call 读取。',
@@ -579,10 +713,8 @@ export function apply(ctx, config) {
579
713
  const items = await knowledgeResourcesAll();
580
714
  return knowledgeListText(scope, items, args ?? {});
581
715
  },
582
- }),
583
- );
584
- disposers.push(
585
- tools.register({
716
+ });
717
+ register({
586
718
  name: 'am_knowledge_call',
587
719
  description:
588
720
  '调用 agent-memory 知识资源上的工具。省略 tool 时返回该资源可用的工具清单(含参数);给出 tool 时执行它。code-graph 适合跨文件结构、调用链、影响面、定位实现等问题(explore/search/callers/callees/impact/node/files);wiki 适合设计意图、背景、团队约定等问题(search/read_page/list_pages)。索引是分支快照,需要某段代码此刻的精确内容时请读工作区源码。',
@@ -622,10 +754,8 @@ export function apply(ctx, config) {
622
754
  if (typeof data.text === 'string') return clip(data.text);
623
755
  return clip(JSON.stringify(data, null, 2));
624
756
  },
625
- }),
626
- );
627
- disposers.push(
628
- tools.register({
757
+ });
758
+ register({
629
759
  name: 'am_memory_search',
630
760
  description:
631
761
  '按需检索当前专家的分层记忆。默认查 L1(原子记忆)与 L0(原始对话);需要稳定结论时也可传 L2/L3。每轮预注入会使用的层由配置 layers 决定(默认 L3,L2),这里用于补充更细的细节。',
@@ -656,10 +786,8 @@ export function apply(ctx, config) {
656
786
  }
657
787
  return hits.map((hit, index) => `${index + 1}. (${hit.layer}) ${hit.body}`).join('\n');
658
788
  },
659
- }),
660
- );
661
- disposers.push(
662
- tools.register({
789
+ });
790
+ register({
663
791
  name: 'am_skill_search',
664
792
  description:
665
793
  '在团队的 agent-memory 技能库(skill)里检索可复用技能,返回 skill_id、名称与描述。命中后用 am_skill_read 读取正文并按其步骤执行。',
@@ -688,10 +816,8 @@ export function apply(ctx, config) {
688
816
  )
689
817
  .join('\n');
690
818
  },
691
- }),
692
- );
693
- disposers.push(
694
- tools.register({
819
+ });
820
+ register({
695
821
  name: 'am_skill_read',
696
822
  description:
697
823
  '读取 agent-memory 技能库里某个 skill 的完整正文(Markdown,含 frontmatter 说明与执行步骤)。参数可传 skill_id(skl-...)或技能名。',
@@ -720,8 +846,7 @@ export function apply(ctx, config) {
720
846
  if (content === '') return `技能 ${data.name ?? skillId} 没有正文内容。`;
721
847
  return clip(`# 技能 ${data.name ?? skillId}(id=${skillId} v${data.version ?? '?'})\n\n${content}`);
722
848
  },
723
- }),
724
- );
849
+ });
725
850
  return () => {
726
851
  for (const dispose of disposers) {
727
852
  try {
@@ -739,6 +864,21 @@ export function apply(ctx, config) {
739
864
  return;
740
865
  }
741
866
 
867
+ /**
868
+ * Route registration is best effort per route: one refused path (a duplicate left behind
869
+ * by a stale fiber, a carrier that rejects it) must not cost the browser every route.
870
+ */
871
+ const mount = (registerRoute, label) =>
872
+ ctx.effect(() => {
873
+ try {
874
+ return registerRoute();
875
+ } catch (error) {
876
+ ctx.logger?.warn?.(`[agent-memory] ${label} not mounted: ${error?.message ?? error}`);
877
+ debug({ at: 'route-error', label, message: String(error?.message ?? error) });
878
+ return () => {};
879
+ }
880
+ }, label);
881
+
742
882
  const origin = (() => {
743
883
  try {
744
884
  return webServer.getOrigin();
@@ -805,7 +945,7 @@ export function apply(ctx, config) {
805
945
  return JSON.parse(Buffer.concat(chunks).toString('utf8'));
806
946
  }
807
947
 
808
- ctx.effect(
948
+ mount(
809
949
  () =>
810
950
  webServer.register({
811
951
  kind: 'exact',
@@ -845,6 +985,7 @@ export function apply(ctx, config) {
845
985
  refreshMs: settings.refreshMs,
846
986
  kernelUrl: kernelBase(),
847
987
  tools: settings.tools,
988
+ skillLearning: settings.skillLearning,
848
989
  debug: settings.debug,
849
990
  },
850
991
  });
@@ -857,7 +998,7 @@ export function apply(ctx, config) {
857
998
  );
858
999
 
859
1000
  /** Connectivity probe used by the selector's settings panel and by the detail page. */
860
- ctx.effect(
1001
+ mount(
861
1002
  () =>
862
1003
  webServer.register({
863
1004
  kind: 'exact',
@@ -949,7 +1090,7 @@ export function apply(ctx, config) {
949
1090
  * Saves the connection settings from the UI. The `configEditor` service owns the profile
950
1091
  * patch file; editing an ordinary field restarts this plugin so `apply` rebuilds state.
951
1092
  */
952
- ctx.effect(
1093
+ mount(
953
1094
  () =>
954
1095
  webServer.register({
955
1096
  kind: 'exact',
@@ -993,6 +1134,7 @@ export function apply(ctx, config) {
993
1134
  if (typeof body.debug === 'boolean') patch.debug = body.debug;
994
1135
  if (typeof body.kernelUrl === 'string') patch.kernelUrl = body.kernelUrl.trim().replace(/\/+$/, '');
995
1136
  if (typeof body.tools === 'boolean') patch.tools = body.tools;
1137
+ if (typeof body.skillLearning === 'boolean') patch.skillLearning = body.skillLearning;
996
1138
  if (Object.keys(patch).length === 0) {
997
1139
  reply(response, 400, { error: 'no editable field in request' });
998
1140
  return;
@@ -1018,7 +1160,7 @@ export function apply(ctx, config) {
1018
1160
  'agent-memory: config route',
1019
1161
  );
1020
1162
 
1021
- ctx.effect(
1163
+ mount(
1022
1164
  () =>
1023
1165
  webServer.register({
1024
1166
  kind: 'exact',
@@ -1054,7 +1196,7 @@ export function apply(ctx, config) {
1054
1196
  'agent-memory: agents route',
1055
1197
  );
1056
1198
 
1057
- ctx.effect(
1199
+ mount(
1058
1200
  () =>
1059
1201
  webServer.register({
1060
1202
  kind: 'exact',
@@ -1116,7 +1258,7 @@ export function apply(ctx, config) {
1116
1258
  'agent-memory: select route',
1117
1259
  );
1118
1260
 
1119
- ctx.effect(
1261
+ mount(
1120
1262
  () =>
1121
1263
  webServer.register({
1122
1264
  kind: 'exact',
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "dsh-plugin-agent-memory",
3
- "version": "0.1.9",
3
+ "version": "0.2.1",
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",