dsh-plugin-tool-management 0.22.4 → 0.22.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +1624 -1395
- package/README.md +194 -177
- package/README_EN.md +194 -177
- package/docs/ARCHITECTURE.md +137 -0
- package/docs/COMPATIBILITY.md +112 -0
- package/docs/TROUBLESHOOTING.md +287 -0
- package/lib/client.js +14984 -12279
- package/lib/compat/capability-specs.js +66 -16
- package/lib/compat/host-contracts.js +14 -3
- package/lib/compat/host-roots.js +1 -1
- package/lib/compat/manual-review.js +1 -1
- package/lib/compat/preset-reach.js +1 -1
- package/lib/compat/probe.js +96 -11
- package/lib/confirm-gate.js +40 -6
- package/lib/context-inject-contract.js +31 -14
- package/lib/context-inject-delta.js +146 -0
- package/lib/context-inject-frame.js +38 -19
- package/lib/context-inject-select.js +33 -4
- package/lib/context-inject-surface.js +74 -22
- package/lib/context-inject.js +107 -15
- package/lib/evolution/cold.js +389 -0
- package/lib/evolution/config.js +507 -0
- package/lib/evolution/digest.js +48 -0
- package/lib/evolution/episodes.js +287 -0
- package/lib/evolution/evidence.js +167 -0
- package/lib/evolution/gates.js +874 -0
- package/lib/evolution/limits.js +21 -0
- package/lib/evolution/maintenance.js +516 -0
- package/lib/evolution/notes.js +328 -0
- package/lib/evolution/organize.js +118 -0
- package/lib/evolution/review.js +524 -0
- package/lib/evolution/route.js +91 -0
- package/lib/evolution/runtime.js +179 -0
- package/lib/evolution/scope-card.js +144 -0
- package/lib/evolution/state.js +514 -0
- package/lib/evolution/write.js +1773 -0
- package/lib/imports/unzip.js +144 -26
- package/lib/index.js +1371 -79
- package/lib/legacy-tool-names.js +19 -4
- package/lib/mcp/manager.js +1 -0
- package/lib/mcp/tool-visibility.js +204 -11
- package/lib/memories/catalog.js +215 -0
- package/lib/memories/constants.js +115 -7
- package/lib/memories/discovery.js +59 -25
- package/lib/memories/projection.js +116 -31
- package/lib/memories/render-auto.js +198 -0
- package/lib/memories/search.js +3 -5
- package/lib/memories/service.js +252 -17
- package/lib/memories/snapshot.js +174 -23
- package/lib/op-registry.js +59 -0
- package/lib/ops/compat.js +2 -0
- package/lib/ops/evolution.js +887 -0
- package/lib/ops/memory.js +95 -72
- package/lib/ops/trash.js +14 -2
- package/lib/prompts/service.js +30 -0
- package/lib/scope/workspace-key.js +39 -0
- package/lib/settings-sidecars.js +2 -2
- package/lib/skills/dir-watch.js +49 -22
- package/lib/skills/official.js +180 -36
- package/lib/skills/service.js +2 -2
- package/lib/subagents/run-provider.js +35 -22
- package/lib/text-width.js +59 -0
- package/lib/tool-table-switch.js +104 -16
- package/lib/tools/control.js +45 -12
- package/lib/tools/deps.js +2 -2
- package/lib/tools/mcp.js +6 -4
- package/lib/tools/memory.js +1045 -267
- package/lib/tools/note-ref.js +20 -0
- package/lib/tools/remove.js +1 -1
- package/lib/tools/scene.js +3 -3
- package/lib/tools/table.js +76 -20
- package/package.json +155 -152
- package/docs/UPDATE.md +0 -49
package/lib/tools/memory.js
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
|
-
// 记忆(rules)域的 model 工具:
|
|
1
|
+
// 记忆(rules)域的 model 工具:memory_get / memory_switch / memory_remember。
|
|
2
2
|
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
//
|
|
6
|
-
//
|
|
7
|
-
//
|
|
8
|
-
//
|
|
9
|
-
//
|
|
3
|
+
// 自主笔记(agent 学的一句话)是另一族 `memory_note`:两族按对象分开,读取统一走
|
|
4
|
+
// `memory_get`,id 形状也不同(用户记忆 `<scene>/<name>`,笔记 `note:<layer>/<slug>`)。
|
|
5
|
+
//
|
|
6
|
+
// 为什么工具名是 `memory_*` 而不是 `scene_memory_manager_*`:后者描述的是**域**,
|
|
7
|
+
// 而这些工具操作的全是记忆。加场景能力时这个错配就现形了 —— 场景是另一个对象(容器,
|
|
8
|
+
// 进入时切换 mcp / 技能 / 人设),硬塞进同一个写工具会让 `description` 变成双义参数、
|
|
9
|
+
// 门禁按参数分叉(记忆写入有开关可放行,场景写入是改运行时环境、不该有那条路)。
|
|
10
|
+
// 所以拆成两族:这里管记忆内容,`scene_manager_*`(tools/scene.ts)管场景本身。
|
|
10
11
|
//
|
|
11
12
|
// 场景清单也不挂在这条 list 的尾巴上(「记忆就管记忆,场景就管场景」)——
|
|
12
13
|
// 它在 `scene_manager_list`,理由记在 tools/scene.ts 头部,别当"少写了一段"再加回来。
|
|
@@ -16,176 +17,459 @@
|
|
|
16
17
|
// 模型必须自己先查一次再决定调哪条,而它手里的清单可能已经过期。合并后由工具侧兜住。
|
|
17
18
|
//
|
|
18
19
|
// 活动场景的记忆正文会自动注入上下文(无需调用工具读取);这里的工具用于查询/编辑规则
|
|
19
|
-
// 本身。
|
|
20
|
+
// 本身。memory_remember 受 tools/pre-execute 审批门禁。
|
|
20
21
|
// 路径锚点:$DSH_HOME/tool-management/memories/<场景>/…(场景 `global` = 界面「全局」)。
|
|
21
|
-
import { GLOBAL_SCENE, SHARED_GROUP } from '../memories/constants.js';
|
|
22
|
-
import {
|
|
22
|
+
import { GLOBAL_SCENE, MAX_GROUP_SEGMENT_LENGTH, SHARED_GROUP } from '../memories/constants.js';
|
|
23
|
+
import { MAX_AUTO_TEXT_WIDTH, MAX_AUTO_TITLE_WIDTH } from '../evolution/write.js';
|
|
24
|
+
import { textContains } from '../evolution/gates.js';
|
|
25
|
+
import { textWidthOf, truncateToWidth } from '../text-width.js';
|
|
26
|
+
import { LIST_LIMIT_MAX, effectiveScope, existingNote, globalActionNote, globalUnchangedNote, isolationOffNote, listLimit, moreNotShown, scopeOnlyNote, scopeSessionDesc, sessionScopeOf, text, toolOrNeutral } from './deps.js';
|
|
27
|
+
import { PROACTIVE_MEMORY_TOOL } from './table.js';
|
|
28
|
+
import { isNoteRef, noteRefOf, stripNoteRef } from './note-ref.js';
|
|
23
29
|
/** 注册记忆域的 model 工具(列表 / 读取 / 检索 / 切换 / 保存)。 */
|
|
24
30
|
export function buildMemoryTools(deps) {
|
|
25
31
|
const { defineTool, register } = deps;
|
|
32
|
+
/**
|
|
33
|
+
* 运行时点名自主笔记工具:它不在工具表里时退回中性说法。
|
|
34
|
+
*
|
|
35
|
+
* 静态描述不能点名(契约测试拦),错误消息与回执同理 —— 指一条模型没有的工具
|
|
36
|
+
* 等于把它往墙上推。`toolOrNeutral` 只在可见时说出真实名字。
|
|
37
|
+
*/
|
|
38
|
+
const noteTool = (agent, named, neutral) => toolOrNeutral(deps, agent, PROACTIVE_MEMORY_TOOL, named, neutral);
|
|
39
|
+
const evo = deps.evolutionOps;
|
|
40
|
+
/**
|
|
41
|
+
* 取一个自主记忆 op,缺失就抛。
|
|
42
|
+
*
|
|
43
|
+
* `evolutionOps` 的类型是 `Record<string, fn>`,所以严格模式下每个索引取值都是
|
|
44
|
+
* 「可能 undefined」;实际上这张表由 `buildEvolutionOps` 一次构造成完整对象,
|
|
45
|
+
* 要么全有、要么整个 `evolutionOps` 是 undefined(已被调用点的 `if (!evo)` 拦住)。
|
|
46
|
+
* 收口成一个取值函数:类型检查过得了,真缺 op 时也报得出是哪一个。
|
|
47
|
+
*/
|
|
48
|
+
const opOf = (table, name) => {
|
|
49
|
+
const fn = table[name];
|
|
50
|
+
if (typeof fn !== 'function')
|
|
51
|
+
throw new Error('missing op: ' + name + ' (the plugin is only partly assembled)');
|
|
52
|
+
return fn;
|
|
53
|
+
};
|
|
54
|
+
/**
|
|
55
|
+
* 这条规则是不是自主笔记而不是用户记忆。
|
|
56
|
+
*
|
|
57
|
+
* `memory_get` 把两族并成一份输出,用户记忆那一半必须把笔记摘掉 —— 否则同一句话
|
|
58
|
+
* 会在「user memories」与「agent notes」各出现一次。`origin` 是权威字段;旧数据
|
|
59
|
+
* 没有它时按目录判(`_ws` / `_session` 只由笔记后端写入,见 memories/catalog.ts)。
|
|
60
|
+
*/
|
|
61
|
+
const isAutoRule = (x) => {
|
|
62
|
+
if (x && x.origin === 'auto')
|
|
63
|
+
return true;
|
|
64
|
+
if (x && x.origin === 'user')
|
|
65
|
+
return false;
|
|
66
|
+
// 搜索结果把场景叫 `scene`,清单叫 `group`;两边都要认。
|
|
67
|
+
const group = String((x && (x.group !== undefined ? x.group : x.scene)) || '');
|
|
68
|
+
return group === '_ws' || group.startsWith('_ws/') ||
|
|
69
|
+
group === '_session' || group.startsWith('_session/');
|
|
70
|
+
};
|
|
71
|
+
/**
|
|
72
|
+
* 把模型给的引用解析成一条笔记:id(可带 `note:`)→ slot → title → 原文,唯一命中才算。
|
|
73
|
+
*
|
|
74
|
+
* 三条口径(都由真实测试暴露出来):
|
|
75
|
+
* - **原文 = 注入行里那一行**(`oneLine`,去标点的首句),不是整段正文。模型的引用
|
|
76
|
+
* 来自它看到的注入行,让它去猜"整段正文"只会白试一轮。末尾标点也一并忽略。
|
|
77
|
+
* - **先按活跃状态过滤**:同 slot 冲突替换后会留下一条 `superseded`,它与新的那条
|
|
78
|
+
* 同 key。不过滤就会报 ambiguous —— 而 agent 用 slot 当稳定句柄的前提就没了。
|
|
79
|
+
* 只有多条**活跃**同引用时才报歧义,防删错的初衷不变。
|
|
80
|
+
* - 活跃状态一个都没有时退回全量匹配,让错误消息能给出候选。
|
|
81
|
+
*/
|
|
82
|
+
const resolveNote = async (ref) => {
|
|
83
|
+
const raw = stripNoteRef(ref);
|
|
84
|
+
if (raw === '' || !evo)
|
|
85
|
+
return { id: null, hits: [] };
|
|
86
|
+
const list = await opOf(evo, 'evolution-list')({ all: true });
|
|
87
|
+
const rows = list && Array.isArray(list.entries) ? list.entries : [];
|
|
88
|
+
const trimEnd = (s) => String(s ?? '').replace(/[。..!!??\s]+$/, '');
|
|
89
|
+
const matches = (e) => String(e.id || '') === raw ||
|
|
90
|
+
String(e.key || '') === raw ||
|
|
91
|
+
String(e.title || '') === raw ||
|
|
92
|
+
String(e.oneLine || '') === raw ||
|
|
93
|
+
trimEnd(e.oneLine) === trimEnd(raw);
|
|
94
|
+
const live = rows.filter((e) => {
|
|
95
|
+
const st = String(e.status || '');
|
|
96
|
+
return st === 'candidate' || st === 'active' || st === 'core' || st === 'playbook';
|
|
97
|
+
});
|
|
98
|
+
const activeHits = live.filter(matches);
|
|
99
|
+
if (activeHits.length === 1)
|
|
100
|
+
return { id: String(activeHits[0].id), hits: activeHits };
|
|
101
|
+
if (activeHits.length > 1)
|
|
102
|
+
return { id: null, hits: activeHits };
|
|
103
|
+
const hits = rows.filter(matches);
|
|
104
|
+
return hits.length === 1 ? { id: String(hits[0].id), hits } : { id: null, hits };
|
|
105
|
+
};
|
|
106
|
+
const describeNoteHits = (hits) => hits.map((e) => noteRefOf(String(e.id)) + (e.title ? ' (' + String(e.title) + ')' : '')).join(', ');
|
|
107
|
+
/** forget 的引用参数:新名 `note`,旧名 `memory` 兼容一次(改名前的调用习惯)。 */
|
|
108
|
+
const noteArgOf = (a) => String((a && (a.note !== undefined ? a.note : a.memory)) || '').trim();
|
|
109
|
+
/**
|
|
110
|
+
* 用户记忆里有没有一条已经在说这件事。有就返回它的 id,没有返回 `null`。
|
|
111
|
+
*
|
|
112
|
+
* 为什么要在**写笔记之前**查:两族记忆的保留策略完全不同 —— 用户记忆永久、恒注入、
|
|
113
|
+
* 不进回收站;笔记会被 TTL 提醒、被合并、被归档。模型看不见这个差别,于是同一条规则
|
|
114
|
+
* 常常在页面上出现两遍,而其中一遍会自己过期。
|
|
115
|
+
*
|
|
116
|
+
* 判据故意保守(**只拦明确重复**):
|
|
117
|
+
* - 归一化后正文完全相同;或
|
|
118
|
+
* - 一方是另一方的子串,且短的那边不短于 `COVER_MIN_WIDTH`。
|
|
119
|
+
*
|
|
120
|
+
* 不做语义相似度:笔记的价值恰恰在"换个说法补上用户没写的那半句",模糊匹配会把
|
|
121
|
+
* 真正该记的补充拦掉。宁可偶尔留一条冗余,也不要让模型学不到东西。
|
|
122
|
+
*
|
|
123
|
+
* 读不到记忆清单时返回 `null`(照常写):一次读失败不该变成"什么都不记"。
|
|
124
|
+
*/
|
|
125
|
+
const userMemoryCovering = async (text) => {
|
|
126
|
+
/** 短边至少要有的实义字符数:比冲突门宽松,宁可偶尔留一条冗余也不拦掉真正的补充。 */
|
|
127
|
+
const COVER_MIN_CHARS = 8;
|
|
128
|
+
const want = String(text ?? '').trim();
|
|
129
|
+
if (want === '')
|
|
130
|
+
return null;
|
|
131
|
+
let all;
|
|
132
|
+
try {
|
|
133
|
+
all = await opOf(deps.rulesOps, 'rules-list')({});
|
|
134
|
+
}
|
|
135
|
+
catch {
|
|
136
|
+
return null;
|
|
137
|
+
}
|
|
138
|
+
if (!all || all.ok === false || !Array.isArray(all.rules))
|
|
139
|
+
return null;
|
|
140
|
+
for (const x of all.rules) {
|
|
141
|
+
if (isAutoRule(x))
|
|
142
|
+
continue;
|
|
143
|
+
const have = String((x && (x.body !== undefined ? x.body : x.text)) ?? '');
|
|
144
|
+
if (have.trim() === '')
|
|
145
|
+
continue;
|
|
146
|
+
// 包含判据只有一份实现(`textContains`):这里自己写一套 `includes` 会在标点、
|
|
147
|
+
// 空白与大小写口径上与冲突门分家,同一条内容可能"记忆页说是重复、写入侧说不是"。
|
|
148
|
+
if (textContains(have, want, COVER_MIN_CHARS))
|
|
149
|
+
return String(x.id);
|
|
150
|
+
}
|
|
151
|
+
return null;
|
|
152
|
+
};
|
|
153
|
+
/** 一条笔记的正文 + 证据链;`note:` 前缀由调用方决定是否剥掉。 */
|
|
154
|
+
const noteReadText = async (ref) => {
|
|
155
|
+
if (!evo)
|
|
156
|
+
throw new Error('agent notes are not available in this build');
|
|
157
|
+
const raw = stripNoteRef(ref);
|
|
158
|
+
if (raw === '')
|
|
159
|
+
throw new Error('missing argument: id — the note id (note:...), its slot, its title, or the first line of the note as injected (trailing punctuation ignored).');
|
|
160
|
+
let a = await opOf(evo, 'evolution-read')({ id: raw, touch: true });
|
|
161
|
+
if (!a || a.ok === false) {
|
|
162
|
+
const resolved = await resolveNote(raw);
|
|
163
|
+
if (resolved.id !== null)
|
|
164
|
+
a = await opOf(evo, 'evolution-read')({ id: resolved.id, touch: true });
|
|
165
|
+
else if (resolved.hits.length > 1) {
|
|
166
|
+
throw new Error('ambiguous: "' + ref + '" matches ' + describeNoteHits(resolved.hits) + '; pass one of these ids.');
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
if (!a || a.ok === false)
|
|
170
|
+
throw new Error(String((a && a.error) || 'no such agent note: ' + ref));
|
|
171
|
+
const st = a.state || {};
|
|
172
|
+
const bits = [
|
|
173
|
+
'status ' + String(a.status || 'active'),
|
|
174
|
+
// 档位取代原来的 confidence 小数:三档能直接读懂,小数只由来源表换算。
|
|
175
|
+
'tier ' + String(a.tier || 'inferred'),
|
|
176
|
+
a.layer,
|
|
177
|
+
// 类型是「这条以后怎么用」的判据:做法要照着执行,偏好只是风格,事实是可核对的陈述。
|
|
178
|
+
// 它同时决定保质期,所以读全文时也该看见。
|
|
179
|
+
...(a.kind ? ['kind ' + String(a.kind)] : []),
|
|
180
|
+
];
|
|
181
|
+
const lines = ['# ' + noteRefOf(String(a.id || raw)) + ' (agent note)', bits.join(' · ')];
|
|
182
|
+
if (a.title)
|
|
183
|
+
lines.push('title: ' + String(a.title));
|
|
184
|
+
if (a.key)
|
|
185
|
+
lines.push('slot: ' + String(a.key));
|
|
186
|
+
if (a.basis)
|
|
187
|
+
lines.push('basis: ' + String(a.basis));
|
|
188
|
+
if (a.boundary)
|
|
189
|
+
lines.push('boundary: ' + String(a.boundary));
|
|
190
|
+
if (a.alias)
|
|
191
|
+
lines.push('also said as: ' + String(a.alias));
|
|
192
|
+
if (a.degraded)
|
|
193
|
+
lines.push('degraded: ' + String(a.degraded));
|
|
194
|
+
lines.push('', String(a.body || ''));
|
|
195
|
+
const ev = Array.isArray(st.evidence) ? st.evidence : [];
|
|
196
|
+
if (ev.length) {
|
|
197
|
+
lines.push('', 'evidence (latest ' + ev.length + '):');
|
|
198
|
+
for (const e of ev)
|
|
199
|
+
lines.push('- [' + String(e.source || '') + '] ' + String(e.quote || '').slice(0, 200));
|
|
200
|
+
}
|
|
201
|
+
const tr = Array.isArray(st.transitions) ? st.transitions : [];
|
|
202
|
+
if (tr.length) {
|
|
203
|
+
lines.push('', 'timeline:');
|
|
204
|
+
for (const x of tr)
|
|
205
|
+
lines.push('- ' + String(x.at || '') + ' ' + String(x.from || '') + ' → ' + String(x.to || '') + ' (' + String(x.actor || '') + ': ' + String(x.reason || '') + ')');
|
|
206
|
+
}
|
|
207
|
+
return lines.join('\n');
|
|
208
|
+
};
|
|
209
|
+
const noteCatalogText = async (all, limit) => {
|
|
210
|
+
if (!evo)
|
|
211
|
+
return '';
|
|
212
|
+
const r = await opOf(evo, 'evolution-list')({ all });
|
|
213
|
+
if (!r || r.ok === false)
|
|
214
|
+
throw new Error(String((r && r.error) || 'failed to read agent notes'));
|
|
215
|
+
const rows = Array.isArray(r.entries) ? r.entries : [];
|
|
216
|
+
const shown = rows.slice(0, limit);
|
|
217
|
+
const order = ['workspace', 'global'];
|
|
218
|
+
const lines = [];
|
|
219
|
+
for (const layer of order) {
|
|
220
|
+
const group = shown.filter((e) => e.layer === layer);
|
|
221
|
+
if (!group.length)
|
|
222
|
+
continue;
|
|
223
|
+
lines.push('[' + layer + ']');
|
|
224
|
+
for (const e of group) {
|
|
225
|
+
// slot 与 id 末段相同时不重复写:模型要的是「怎么引用这条」,id 已经给了;
|
|
226
|
+
// 两者不同才需要说明(合并时显式 slot 会覆盖 id 末段)。
|
|
227
|
+
lines.push('- ' + noteRefOf(String(e.id)) + ' · ' + String(e.status || 'active') +
|
|
228
|
+
(e.key && String(e.key) !== String(e.id).slice(String(e.id).lastIndexOf('/') + 1) ? ' · slot ' + String(e.key) : '') +
|
|
229
|
+
(e.title ? ' · ' + String(e.title) : '') +
|
|
230
|
+
// 类型决定保质期,也是「这条是做法还是偏好」的唯一机器可读标记:
|
|
231
|
+
// 模型要靠它决定该不该照着做、值不值得 `memory_get` 读全文。
|
|
232
|
+
// `evolution-list` 一直在返回 `kind`,这里此前没读。
|
|
233
|
+
(e.kind ? ' · ' + String(e.kind) : '') +
|
|
234
|
+
' · ' + String(e.tier || 'inferred') +
|
|
235
|
+
' · ' + (e.injects ? 'injects' : 'not injected') +
|
|
236
|
+
(e.pendingReason ? ' · pending: ' + String(e.pendingReason) : '') +
|
|
237
|
+
(e.reviewDue ? ' · review due: ' + String(e.reviewDue) : '') +
|
|
238
|
+
(e.oneLine ? ' — ' + String(e.oneLine) : ''));
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
const head = 'agent notes: ' + rows.length + ' listed' +
|
|
242
|
+
(r.total !== undefined ? ' / ' + r.total + ' in catalog' : '') +
|
|
243
|
+
(rows.length > shown.length ? ' (showing ' + shown.length + ', raise limit for more)' : '');
|
|
244
|
+
return head + '\n' + (lines.join('\n') || '(none)');
|
|
245
|
+
};
|
|
246
|
+
const noteSearchText = async (query, limit) => {
|
|
247
|
+
if (!evo)
|
|
248
|
+
return '';
|
|
249
|
+
// 与用户记忆搜索同口径:搜索覆盖归档 / 未注入的条目,`all` 只影响清单。
|
|
250
|
+
// 带正文:`oneLine` 只是压平后按 160 宽度截断的摘要,只搜它等于搜不到正文后半截。
|
|
251
|
+
const r = await opOf(evo, 'evolution-list')({ all: true, withBody: true });
|
|
252
|
+
if (!r || r.ok === false)
|
|
253
|
+
throw new Error(String((r && r.error) || 'failed to read agent notes'));
|
|
254
|
+
const words = query.toLowerCase().split(/\s+/).filter((w) => w !== '');
|
|
255
|
+
const rows = (Array.isArray(r.entries) ? r.entries : []).filter((e) => {
|
|
256
|
+
// `kind` 也要能搜:结果行里印着它(「列出所有做法类笔记」是很自然的请求),
|
|
257
|
+
// 只显示不索引等于「看得见、搜不到」。类型是四个固定词,不会污染正文匹配。
|
|
258
|
+
const hay = [e.id, e.key, e.title, e.oneLine, e.body, e.boundary, e.alias, e.kind]
|
|
259
|
+
.map((x) => String(x || '').toLowerCase()).join(' ');
|
|
260
|
+
return words.every((w) => hay.includes(w));
|
|
261
|
+
});
|
|
262
|
+
const shown = rows.slice(0, limit);
|
|
263
|
+
const lines = shown.map((e) => '- ' + noteRefOf(String(e.id)) + ' · ' + String(e.status || 'active') +
|
|
264
|
+
(e.kind ? ' · ' + String(e.kind) : '') +
|
|
265
|
+
(e.title ? ' · ' + String(e.title) : '') +
|
|
266
|
+
(e.oneLine ? ' — ' + String(e.oneLine) : ''));
|
|
267
|
+
return 'agent notes matching "' + query + '": ' + rows.length +
|
|
268
|
+
(rows.length > shown.length ? ' (showing ' + shown.length + ')' : '') +
|
|
269
|
+
'\n' + (lines.join('\n') || '(none)');
|
|
270
|
+
};
|
|
271
|
+
const userCatalogText = async (all, limit, scene, exec) => {
|
|
272
|
+
const opArgs = {};
|
|
273
|
+
if (scene !== undefined)
|
|
274
|
+
opArgs.group = scene;
|
|
275
|
+
const scoped = sessionScopeOf(deps, exec && exec.agent);
|
|
276
|
+
if (scoped !== null)
|
|
277
|
+
opArgs.sessionId = scoped.sessionId;
|
|
278
|
+
const r = await opOf(deps.rulesOps, 'rules-list')(opArgs);
|
|
279
|
+
if (!r || r.ok === false)
|
|
280
|
+
throw new Error((r && r.error) || 'failed to read memories');
|
|
281
|
+
// 「会注入」的判定与记忆段同源(renderSceneMemory):global 与 _shared 恒常注入,
|
|
282
|
+
// 其余场景要在 index.active 里,再叠加单条 enabled 与同名 bundle 的 shadowed。
|
|
283
|
+
const alwaysInjects = (group) => group === GLOBAL_SCENE || group === SHARED_GROUP;
|
|
284
|
+
const sceneOn = (group) => alwaysInjects(group) ||
|
|
285
|
+
(group !== '' && (r.activeMode === 'all' || String(r.activeScene || '') === group));
|
|
286
|
+
const stateOf = (x) => {
|
|
287
|
+
if (x.shadowed === true)
|
|
288
|
+
return { injects: false, label: 'shadowed' };
|
|
289
|
+
if (x.enabled === false)
|
|
290
|
+
return { injects: false, label: 'disabled' };
|
|
291
|
+
if (!sceneOn(String(x.group || '')))
|
|
292
|
+
return { injects: false, label: 'scene off' };
|
|
293
|
+
return { injects: true, label: 'injects' };
|
|
294
|
+
};
|
|
295
|
+
const rows = (r.rules || []).filter((x) => !isAutoRule(x)).map((x) => ({ x, ...stateOf(x) }));
|
|
296
|
+
const shown = all ? rows : rows.filter((row) => row.injects);
|
|
297
|
+
const visible = shown.slice(0, limit);
|
|
298
|
+
const lines = visible.map(({ x, label }) => ('- ' + x.id + ' [' + (x.group || 'no scene') + '] ' + label +
|
|
299
|
+
(x.form === 'bundle'
|
|
300
|
+
? ' · bundle' + (x.attach && x.attach.count ? ' (' + x.attach.count + ' attachment(s))' : '')
|
|
301
|
+
: '')));
|
|
302
|
+
const scope = r.activeMode === 'all'
|
|
303
|
+
? 'every scene (historical default, not narrowed)'
|
|
304
|
+
: (r.activeScene ? '"' + String(r.activeScene) + '"' : 'no scene is on');
|
|
305
|
+
const viewNoun = deps.scopeMode?.() === 'workspace' ? 'this workspace' : 'this conversation';
|
|
306
|
+
const sessionNote = scoped === null || scoped.scope === undefined
|
|
307
|
+
? ''
|
|
308
|
+
: '\nthis is ' + viewNoun + "'s view" +
|
|
309
|
+
(scoped.scope.scene !== undefined ? ' — scene pinned to "' + scoped.scope.scene + '"; the machine-wide scene may differ' : '') +
|
|
310
|
+
(scoped.scope.memory !== undefined ? '; ' + Object.keys(scoped.scope.memory).length + ' switch(es) applied here' : '');
|
|
311
|
+
const sharedHere = rows.some(({ x }) => String(x.group || '') === SHARED_GROUP);
|
|
312
|
+
const header = 'user memories: ' + (all
|
|
313
|
+
? rows.length + ' total'
|
|
314
|
+
: shown.length + ' injecting / ' + rows.length + ' total' +
|
|
315
|
+
(shown.length === rows.length ? '' : ' (pass all=true for all)')) +
|
|
316
|
+
'\ninjects from: ' + scope + ' + global' + (sharedHere ? ' + _shared' : '') + ' (always on)' + sessionNote + '\n';
|
|
317
|
+
const notice = await deps.reachNoticeForAgent(deps.presetRoster(), exec && exec.agent && exec.agent.ctx, deps.injectNoticeOptions());
|
|
318
|
+
return header + (lines.join('\n') || '(none)') + moreNotShown(shown.length, visible.length) + notice;
|
|
319
|
+
};
|
|
320
|
+
const userSearchText = async (query, limit, scene, exec) => {
|
|
321
|
+
// 搜索不跟随 `all`:找一条已停用 / 归档的条目正是搜索的用途(新建前先确认有没有)。
|
|
322
|
+
// 带场景过滤时向 op 要满上限,否则 op 先按 limit 截断、再过滤,目标场景的命中会被挤掉。
|
|
323
|
+
const opArgs = { query, limit: scene !== undefined ? LIST_LIMIT_MAX : limit };
|
|
324
|
+
const scoped = sessionScopeOf(deps, exec && exec.agent);
|
|
325
|
+
if (scoped !== null)
|
|
326
|
+
opArgs.sessionId = scoped.sessionId;
|
|
327
|
+
const r = await opOf(deps.rulesOps, 'rules-search')(opArgs);
|
|
328
|
+
if (!r || r.ok === false)
|
|
329
|
+
throw new Error((r && r.error) || 'failed to search memories');
|
|
330
|
+
let hits = Array.isArray(r.hits) ? r.hits : [];
|
|
331
|
+
hits = hits.filter((h) => !isAutoRule(h));
|
|
332
|
+
if (scene !== undefined)
|
|
333
|
+
hits = hits.filter((h) => String(h.scene || '') === scene);
|
|
334
|
+
if (!hits.length)
|
|
335
|
+
return 'user memories: no match for "' + query + '"';
|
|
336
|
+
const lines = hits.slice(0, limit).map((h) => '- ' + h.id + ' [' + (h.scene || 'no scene') + ']' +
|
|
337
|
+
(h.enabled === false ? ' (off here)' : '') +
|
|
338
|
+
(h.snippet ? ' — ' + h.snippet : ''));
|
|
339
|
+
return 'user memories matching "' + query + '": ' + hits.length +
|
|
340
|
+
(hits.length > limit ? ' (showing ' + limit + ')' : '') + '\n' + lines.join('\n');
|
|
341
|
+
};
|
|
342
|
+
const userReadText = async (id, exec) => {
|
|
343
|
+
const r = await opOf(deps.rulesOps, 'rules-read')({ id });
|
|
344
|
+
if (!r || r.ok === false)
|
|
345
|
+
return null;
|
|
346
|
+
const rule = r.rule || {};
|
|
347
|
+
// 自动条目由笔记渲染器负责;这里返回 null,让 readEntry 走 noteReadText。
|
|
348
|
+
if (isAutoRule(rule))
|
|
349
|
+
return null;
|
|
350
|
+
const attach = Array.isArray(rule.attachments) ? rule.attachments : [];
|
|
351
|
+
const form = rule.form === 'bundle' ? 'bundle' : 'flat';
|
|
352
|
+
const attLine = attach.length
|
|
353
|
+
? '\nattachments (' + attach.length + '): ' + attach.map((a) => String((a && a.name) || a)).join(', ')
|
|
354
|
+
: '';
|
|
355
|
+
const scoped = sessionScopeOf(deps, exec && exec.agent);
|
|
356
|
+
const over = scoped?.scope?.memory?.[String(rule.id)];
|
|
357
|
+
const offHere = over === false
|
|
358
|
+
? '\n(switched off here only — the body above is not injected here; the global setting is unchanged) '
|
|
359
|
+
: '';
|
|
360
|
+
return '# ' + rule.id + ' (memory, ' + form + ')' + attLine + '\n\n' + (rule.body || '') + offHere;
|
|
361
|
+
};
|
|
362
|
+
const readEntry = async (id, exec) => {
|
|
363
|
+
if (isNoteRef(id))
|
|
364
|
+
return noteReadText(id);
|
|
365
|
+
const mem = await userReadText(id, exec);
|
|
366
|
+
if (mem !== null)
|
|
367
|
+
return mem;
|
|
368
|
+
if (evo) {
|
|
369
|
+
try {
|
|
370
|
+
return await noteReadText(id);
|
|
371
|
+
}
|
|
372
|
+
catch (e) {
|
|
373
|
+
throw new Error('no user memory with id "' + id + '"; ' + (e instanceof Error ? e.message : String(e)));
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
throw new Error('no user memory with id "' + id + '". Call memory_get with no id to list what exists.');
|
|
377
|
+
};
|
|
378
|
+
/**
|
|
379
|
+
* 从标题或正文首行派生文件名:保留 Unicode,去掉路径分隔符与控制字符,空白压成 `-`。
|
|
380
|
+
*
|
|
381
|
+
* 用户说的是「记录一下:以后提交前跑测试」,不会给文件 slug。文件名必须是一个合法路径段
|
|
382
|
+
* (`isValidGroupSegment` 允许 Unicode),所以这里只做最低限度的清洗;真正的合法性
|
|
383
|
+
* 仍由 `rules-create` 兜底。
|
|
384
|
+
*/
|
|
385
|
+
const slugOf = (raw) => {
|
|
386
|
+
const line = String(raw || '').split('\n').map((l) => l.trim()).find((l) => l !== '') || '';
|
|
387
|
+
const cleaned = line
|
|
388
|
+
.replace(/^#+\s*/, '')
|
|
389
|
+
.replace(/[\\/:*?"<>|\u0000-\u001f]/g, ' ')
|
|
390
|
+
.replace(/\s+/g, '-')
|
|
391
|
+
.replace(/-+/g, '-')
|
|
392
|
+
.replace(/^[-.]+|[-.]+$/g, '')
|
|
393
|
+
.slice(0, MAX_GROUP_SEGMENT_LENGTH);
|
|
394
|
+
return cleaned !== '' ? cleaned : 'memory';
|
|
395
|
+
};
|
|
396
|
+
/** 正文首行(去掉 markdown 标题标记),用于派生描述。 */
|
|
397
|
+
const firstLineOf = (raw) => {
|
|
398
|
+
const line = String(raw || '').split('\n').map((l) => l.trim()).find((l) => l !== '') || '';
|
|
399
|
+
return line.replace(/^#+\s*/, '').slice(0, 500);
|
|
400
|
+
};
|
|
401
|
+
/** 当前可用场景名:`scenes` 行与规则里的 group 取并集(有记忆但没显式记录的场景也要认)。 */
|
|
402
|
+
const sceneNamesOf = (r) => {
|
|
403
|
+
const names = new Set();
|
|
404
|
+
const rows = Array.isArray(r && r.scenes) ? r.scenes : [];
|
|
405
|
+
for (const s of rows) {
|
|
406
|
+
const name = String((s && (s.key || s.name)) || '');
|
|
407
|
+
if (name !== '')
|
|
408
|
+
names.add(name);
|
|
409
|
+
}
|
|
410
|
+
for (const x of (Array.isArray(r && r.rules) ? r.rules : [])) {
|
|
411
|
+
const group = String((x && x.group) || '');
|
|
412
|
+
if (group !== '')
|
|
413
|
+
names.add(group);
|
|
414
|
+
}
|
|
415
|
+
return [...names];
|
|
416
|
+
};
|
|
26
417
|
register(defineTool({
|
|
27
|
-
name: '
|
|
28
|
-
|
|
29
|
-
// 工具只会让它去猜名字(用户 把默认名单扩到十五条时去掉的这句)。
|
|
30
|
-
description: 'List memories (id, scene, enabled, form flat|bundle, description) plus the scene the injection follows. What is injected each turn is in the "Current memories" reminder; use this for ids and for entries that are off. Pass `scene` to filter; all=true lists everything.',
|
|
31
|
-
parameters: {
|
|
32
|
-
// 参数名与其余五个域同词:同一个概念在工具面只该有一个名字
|
|
33
|
-
// 而 `scene` 是它在 `scene_manager_*`、`<scene>/<name>` 与注入段标题里的叫法。
|
|
34
|
-
// op 的内部契约字段仍是 `group`(`rules-list` 与界面侧调用方都读它),所以 execute 里
|
|
35
|
-
// 显式映射一次 —— 改 op 的字段名要动界面,那不是这一条能顺手做的事。
|
|
36
|
-
scene: { type: 'string', description: 'Optional scene filter; `global` and `_shared` are the always-on scenes.' },
|
|
37
|
-
all: { type: 'boolean', description: 'Include memories that are off, in an inactive scene, or shadowed (default false).' },
|
|
38
|
-
limit: { type: 'number', description: 'Max entries (default 50, max 100).' },
|
|
39
|
-
},
|
|
40
|
-
output: { schema: { type: 'string' }, render: (_a, v) => text(v) },
|
|
41
|
-
async execute(args, exec) {
|
|
42
|
-
const showAll = Boolean(args && args.all === true);
|
|
43
|
-
// `scene` → `group`:只把 op 认的那个字段传过去,别把 `scene` 也塞给它(它不认)。
|
|
44
|
-
const opArgs = {};
|
|
45
|
-
if (args && args.scene !== undefined)
|
|
46
|
-
opArgs.group = args.scene;
|
|
47
|
-
// 会话层(`memory_manager_list` 只列本会话场景):带上 sessionId,
|
|
48
|
-
// op 就按本会话钉住的场景与逐条开关投影 —— 「会注入」这一栏与模型真实看到的一致。
|
|
49
|
-
// 取不到会话 = 不给,op 退回全局口径(不报错)。
|
|
50
|
-
const scoped = sessionScopeOf(deps, exec && exec.agent);
|
|
51
|
-
if (scoped !== null)
|
|
52
|
-
opArgs.sessionId = scoped.sessionId;
|
|
53
|
-
const r = await deps.rulesOps['rules-list'](opArgs);
|
|
54
|
-
if (!r || r.ok === false)
|
|
55
|
-
throw new Error((r && r.error) || 'failed to read memories');
|
|
56
|
-
// 「会注入」的判定与记忆段同源(renderSceneMemory):global 场景恒常注入,其余场景要
|
|
57
|
-
// 在 index.active 里,再叠加单条 enabled 与同名 bundle 的 shadowed。默认只列这些,
|
|
58
|
-
// 全列一次会把没启用的条目也算进上下文(与技能列表同口径)。
|
|
59
|
-
//
|
|
60
|
-
// **两个**保留桶恒常注入,不是一个:`global`(界面「全局」)之外还有 `_shared`
|
|
61
|
-
// (公共基线)。注入侧 `resolveActiveScenes` 无条件把两者都放进 active
|
|
62
|
-
// (见 memories/projection.ts),这里只认 `global` 就会把 `_shared` 标成
|
|
63
|
-
// "scene off" 并默认藏起来 —— 而它每轮都在上下文里。模型照这份名单回答
|
|
64
|
-
// 「没有这条记忆」,实际它正躺在自己眼前。`activeScene` 永远报不到 `_shared`
|
|
65
|
-
// (`enabledSceneOf` 只回非保留场景),所以只能在这一层显式认。
|
|
66
|
-
const alwaysInjects = (group) => group === GLOBAL_SCENE || group === SHARED_GROUP;
|
|
67
|
-
const sceneOn = (group) => alwaysInjects(group) ||
|
|
68
|
-
(group !== '' && (r.activeMode === 'all' || String(r.activeScene || '') === group));
|
|
69
|
-
const stateOf = (x) => {
|
|
70
|
-
if (x.shadowed === true)
|
|
71
|
-
return { injects: false, label: 'shadowed' };
|
|
72
|
-
if (x.enabled === false)
|
|
73
|
-
return { injects: false, label: 'disabled' };
|
|
74
|
-
if (!sceneOn(String(x.group || '')))
|
|
75
|
-
return { injects: false, label: 'scene off' };
|
|
76
|
-
return { injects: true, label: 'injects' };
|
|
77
|
-
};
|
|
78
|
-
const rows = (r.rules || []).map((x) => ({ x, ...stateOf(x) }));
|
|
79
|
-
const shown = showAll ? rows : rows.filter((row) => row.injects);
|
|
80
|
-
// 返回体也要有上限:返回值进上下文,而工具表只管 schema —— 这一笔它管不着。
|
|
81
|
-
const limit = listLimit(args && args.limit);
|
|
82
|
-
const visible = shown.slice(0, limit);
|
|
83
|
-
const lines = visible.map(({ x, label }) => ('- ' + x.id + ' [' + (x.group || 'no scene') + '] ' + label +
|
|
84
|
-
// 形态与附件:此前不报,模型分不清哪条是 bundle、更不知道它带了几个附件
|
|
85
|
-
// (`rules-list` 早就把 `form` 与 bundle 的附件摘要给了出来,只是这里没渲染)。
|
|
86
|
-
(x.form === 'bundle'
|
|
87
|
-
? ' · bundle' + (x.attach && x.attach.count ? ' (' + x.attach.count + ' attachment(s))' : '')
|
|
88
|
-
: '') +
|
|
89
|
-
(x.description ? ' — ' + x.description : '')));
|
|
90
|
-
// 注入按哪个场景走 —— 上面那句「场景未启用」只有配上它才可解读:少了这一行,
|
|
91
|
-
// 模型看到一片"未启用"会以为是条目自己的问题。(场景本身的清单在 `scene_manager_list`,
|
|
92
|
-
const scope = r.activeMode === 'all'
|
|
93
|
-
? 'every scene (historical default, not narrowed)'
|
|
94
|
-
: (r.activeScene ? '"' + String(r.activeScene) + '"' : 'no scene is on');
|
|
95
|
-
// 会话层:本会话钉了场景 / 改了个别开关时,上面那行报的是**本会话**的投影
|
|
96
|
-
// 与全局可能不同。不说清的话,模型会拿这份名单去回答"全局现在是什么" —— 那是错的答案。
|
|
97
|
-
// 粒度决定这句话的主语:工作区粒度下那一格是同工作区共享的,"本对话"是假话。
|
|
98
|
-
const viewNoun = deps.scopeMode?.() === 'workspace' ? 'this workspace' : 'this conversation';
|
|
99
|
-
const sessionNote = scoped === null || scoped.scope === undefined
|
|
100
|
-
? ''
|
|
101
|
-
: '\nthis is ' + viewNoun + "'s view" +
|
|
102
|
-
(scoped.scope.scene !== undefined ? ' — scene pinned to "' + scoped.scope.scene + '"; the machine-wide scene may differ' : '') +
|
|
103
|
-
(scoped.scope.memory !== undefined ? '; ' + Object.keys(scoped.scope.memory).length + ' switch(es) applied here' : '');
|
|
104
|
-
// `_shared` 只在真有这类条目时点名:没有就不付这几个字,而有了不说的话,
|
|
105
|
-
// 上面那句「只列会注入的」会让人以为名单里全是 global + 当前场景。
|
|
106
|
-
const sharedHere = rows.some(({ x }) => String(x.group || '') === SHARED_GROUP);
|
|
107
|
-
const header = 'memories: ' + (showAll
|
|
108
|
-
? rows.length + ' total'
|
|
109
|
-
: shown.length + ' injecting / ' + rows.length + ' total' +
|
|
110
|
-
(shown.length === rows.length ? '' : ' (pass all=true for all)')) +
|
|
111
|
-
'\ninjects from: ' + scope + ' + global' + (sharedHere ? ' + _shared' : '') + ' (always on)' + sessionNote + '\n';
|
|
112
|
-
// 注入边界:压制型预设(persona complete / 关闭运行时上下文)下本插件默认不注入,
|
|
113
|
-
// 此时列出的记忆**不在**模型上下文里。必须说出来,否则模型会假设自己已经看到正文。
|
|
114
|
-
const notice = await deps.reachNoticeForAgent(deps.presetRoster(), exec && exec.agent && exec.agent.ctx, deps.injectNoticeOptions());
|
|
115
|
-
return header + (lines.join('\n') || '(none)') + moreNotShown(shown.length, visible.length) + notice;
|
|
116
|
-
},
|
|
117
|
-
}));
|
|
118
|
-
register(defineTool({
|
|
119
|
-
name: 'memory_manager_read',
|
|
120
|
-
// "dropped by the byte budget" 改成"left out of it":byte budget
|
|
121
|
-
// 是本插件内部术语,模型没有这个概念 —— 它只知道"这条在不在我上下文里"。说内部机制
|
|
122
|
-
// 等于让它去猜一个它观测不到的量。
|
|
123
|
-
description: 'Read one memory\'s full body, its form (flat|bundle) and its attachment names. Only for ones not already in your context (disabled, in an inactive scene, or left out). Attachment contents are not returned — use your file tools.',
|
|
124
|
-
parameters: {
|
|
125
|
-
memory: { type: 'string', required: true, description: 'Memory id like <scene>/<name>.' },
|
|
126
|
-
},
|
|
127
|
-
output: { schema: { type: 'string' }, render: (_a, v) => text(v) },
|
|
128
|
-
async execute(args, exec) {
|
|
129
|
-
// op 的字段名是 `id`,不改 op:这里显式转换(键名对模型是 `<场景>/<名字>`,对 op 是 `id`)。
|
|
130
|
-
const r = await deps.rulesOps['rules-read']({ id: String((args && args.memory) || '') });
|
|
131
|
-
if (!r || r.ok === false)
|
|
132
|
-
throw new Error((r && r.error) || 'failed to read memories');
|
|
133
|
-
const rule = r.rule || {};
|
|
134
|
-
// 形态与附件名:op 一直把 `attachments` 给了出来,这里此前**整个丢掉**,
|
|
135
|
-
// 于是模型连"这条记忆是 bundle、带了 3 个附件"都看不到。只给名字不给内容 ——
|
|
136
|
-
// 附件可能是图片或大 md,全文塞回来会吃光这一轮的上下文(与注入段附件行同口径)。
|
|
137
|
-
const attach = Array.isArray(rule.attachments) ? rule.attachments : [];
|
|
138
|
-
const form = rule.form === 'bundle' ? 'bundle' : 'flat';
|
|
139
|
-
const attLine = attach.length
|
|
140
|
-
? '\nattachments (' + attach.length + '): ' + attach.map((a) => String((a && a.name) || a)).join(', ')
|
|
141
|
-
: '';
|
|
142
|
-
// 会话层:这条记忆在本会话是关着的(或不在本会话钉住的场景里)时,读得到
|
|
143
|
-
// 正文 ≠ 它会进上下文。不说清的话,模型会以为自己已经掌握了它、下一轮却看不到。
|
|
144
|
-
const scoped = sessionScopeOf(deps, exec && exec.agent);
|
|
145
|
-
const over = scoped?.scope?.memory?.[String(rule.id)];
|
|
146
|
-
const offHere = over === false
|
|
147
|
-
? '\n(switched off here only — the body above is not injected here; the global setting is unchanged) '
|
|
148
|
-
: '';
|
|
149
|
-
return '# ' + rule.id + ' (' + form + ')' + attLine + '\n\n' + (rule.body || '') + offHere;
|
|
150
|
-
},
|
|
151
|
-
}));
|
|
152
|
-
register(defineTool({
|
|
153
|
-
name: 'memory_manager_search',
|
|
154
|
-
// 为什么单独一条而不是给 list 加 `query`:list 是"清单"(每条都要占一行输出),
|
|
155
|
-
// 搜索是"找一条"(片段 + 排序)。混在一起时,搜不到就等于清单为空 —— 模型分不清
|
|
156
|
-
// "没有这条记忆"和"这个词没匹配上"。默认在工具表里**关着**(见 tools/table.ts):
|
|
157
|
-
// 它是按需检索,不是每轮都该付 schema 成本的能力。
|
|
158
|
-
description: 'Search memories by words in id, scene, description, tags or body. Returns ids plus a short snippet; read the memory itself for the full body. All words must match (case-insensitive).',
|
|
418
|
+
name: 'memory_get',
|
|
419
|
+
description: 'Look up user-written memories and agent notes. No id → catalog (what exists and what injects); `id` → full body; `query` → filtered catalog with snippets. Agent note ids start with `note:`. Use this for ids and for entries not already in your context. Does not modify any memory; reading an agent note does count as a use, which keeps a note that is actually needed from aging out.',
|
|
159
420
|
parameters: {
|
|
160
|
-
|
|
161
|
-
|
|
421
|
+
id: { type: 'string', description: 'Read one entry: a user memory id (<scene>/<name>) or an agent note id (note:...).' },
|
|
422
|
+
query: { type: 'string', description: 'Filter the catalog by words in id, scene, tags, body or type; every word must match (case-insensitive). For agent notes the type is one of preference / fact / correction / procedure, so `query: "procedure"` lists the repeatable ones.' },
|
|
423
|
+
kind: { type: 'string', enum: ['memory', 'note'], description: 'Limit the catalog to user-written memories or agent notes.' },
|
|
424
|
+
scene: { type: 'string', description: 'Only user memories in this scene; `global` is the always-on scene.' },
|
|
425
|
+
all: { type: 'boolean', description: 'Catalog only: include entries that are off, in an inactive scene, or archived (default false). Search always covers everything.' },
|
|
426
|
+
limit: { type: 'number', description: 'Max entries per kind (default 50, max 100).' },
|
|
162
427
|
},
|
|
163
428
|
output: { schema: { type: 'string' }, render: (_a, v) => text(v) },
|
|
164
429
|
async execute(args, exec) {
|
|
430
|
+
// 参数写错要报错,不能静默降级:`limit` 被夹取、空 `query` / 空 `id` 被当成没传,
|
|
431
|
+
// 调用方会以为查询按自己的意图跑了。
|
|
432
|
+
if (args && args.limit !== undefined) {
|
|
433
|
+
const n = Number(args.limit);
|
|
434
|
+
if (!Number.isFinite(n) || n < 1 || n > LIST_LIMIT_MAX) {
|
|
435
|
+
throw new Error('limit must be a number between 1 and ' + LIST_LIMIT_MAX);
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
if (args && args.query !== undefined && String(args.query).trim() === '') {
|
|
439
|
+
throw new Error('query is empty: pass words to search for, or omit it to list the catalog');
|
|
440
|
+
}
|
|
441
|
+
if (args && args.id !== undefined && String(args.id).trim() === '') {
|
|
442
|
+
throw new Error('id is empty: pass a memory id, or omit it to list the catalog');
|
|
443
|
+
}
|
|
444
|
+
const id = String((args && args.id) || '').trim();
|
|
445
|
+
if (id !== '')
|
|
446
|
+
return readEntry(id, exec);
|
|
165
447
|
const query = String((args && args.query) || '').trim();
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
const
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
//
|
|
172
|
-
const
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
448
|
+
const kind = args && args.kind === 'note' ? 'note' : args && args.kind === 'memory' ? 'memory' : '';
|
|
449
|
+
const all = args && args.all === true;
|
|
450
|
+
const limit = listLimit(args && args.limit);
|
|
451
|
+
const scene = args && typeof args.scene === 'string' && args.scene !== '' ? args.scene : undefined;
|
|
452
|
+
// 自主记忆关着时,笔记不在这份清单里出现:功能没开,模型不该看到「有笔记可读」
|
|
453
|
+
// 这种半开状态(直接给 note: id 仍然读得到 —— 那是显式请求)。
|
|
454
|
+
const readable = deps.autoNotesReadable ?? deps.autoLearnEnabled;
|
|
455
|
+
const notesOn = Boolean(evo && readable && readable(exec && exec.agent));
|
|
456
|
+
if (kind === 'note' && !notesOn) {
|
|
457
|
+
throw new Error('autonomous memory is off here, so agent notes are not available. The user can turn it on in Memory → Autonomous memory.');
|
|
458
|
+
}
|
|
459
|
+
const sections = [];
|
|
460
|
+
if (kind !== 'note') {
|
|
461
|
+
sections.push(query !== ''
|
|
462
|
+
? await userSearchText(query, limit, scene, exec)
|
|
463
|
+
: await userCatalogText(all, limit, scene, exec));
|
|
464
|
+
}
|
|
465
|
+
if (kind !== 'memory' && notesOn) {
|
|
466
|
+
sections.push(query !== '' ? await noteSearchText(query, limit) : await noteCatalogText(all, limit));
|
|
467
|
+
}
|
|
468
|
+
return sections.filter((s) => s !== '').join('\n\n') || '(none)';
|
|
185
469
|
},
|
|
186
470
|
}));
|
|
187
471
|
register(defineTool({
|
|
188
|
-
name: '
|
|
472
|
+
name: 'memory_switch',
|
|
189
473
|
// 为什么叫 `_switch` 而不是 `_set_enabled`:六个域里"拨一个开关"
|
|
190
474
|
// 是同一件事,名字该同形 —— `mcp_manager_switch` 早就是这个名字,`_set_enabled` 只剩
|
|
191
475
|
// 记忆 / 技能 / 人设三族在叫。**参数保留 `enabled` 布尔**:这里没有 `restart` 那第三个
|
|
@@ -201,16 +485,25 @@ export function buildMemoryTools(deps) {
|
|
|
201
485
|
// 描述同时按"省 token"重写了一遍 —— 这几段文字每次请求都要发出去,废话是常驻成本。
|
|
202
486
|
// 后半句"freeing the byte budget"删掉:byte budget 是本插件
|
|
203
487
|
// 内部术语,模型据此做不了任何判断 —— "不再被注入"已经是它需要的全部因果。
|
|
204
|
-
description: 'Enable or disable one memory. Disabled memories stop being injected. Reversible. Only when the user asks or approves.',
|
|
488
|
+
description: 'Enable or disable one user-written memory. Disabled memories stop being injected. Reversible. Agent notes are not switched here — forget them with the agent-note tool. Only when the user asks or approves.',
|
|
205
489
|
parameters: {
|
|
206
|
-
|
|
490
|
+
id: { type: 'string', description: 'Memory id like <scene>/<name>.' },
|
|
491
|
+
// 改名前的参数名。保留在 schema 里,旧调用习惯(以及确认门的兼容分支)才真的走得通。
|
|
492
|
+
memory: { type: 'string', description: 'Deprecated alias for id; use id.' },
|
|
207
493
|
enabled: { type: 'boolean', required: true, description: 'true = enable, false = disable.' },
|
|
208
494
|
// 默认只改**这个对话**。写全局要显式说明。
|
|
209
495
|
scope: { type: 'string', enum: ['session', 'global'], description: scopeSessionDesc('global = every conversation.') },
|
|
210
496
|
},
|
|
211
497
|
output: { schema: { type: 'string' }, render: (_a, v) => text(v) },
|
|
212
498
|
async execute(args, exec) {
|
|
213
|
-
|
|
499
|
+
// `memory` 是改名前的参数名,兼容一次;新调用方用 `id`。
|
|
500
|
+
const memory = String((args && (args.id !== undefined ? args.id : args.memory)) || '').trim();
|
|
501
|
+
if (memory === '')
|
|
502
|
+
throw new Error('missing argument: id — the memory id like <scene>/<name>.');
|
|
503
|
+
// 笔记不是用户记忆:这条工具拨的是索引里的开关,笔记的删除/停用走另一族。
|
|
504
|
+
if (isNoteRef(memory)) {
|
|
505
|
+
throw new Error('that is an agent note, not a user memory: use ' + noteTool(exec && exec.agent, 'memory_note action=forget', 'the agent-note tool') + '. User memory ids look like <scene>/<name>.');
|
|
506
|
+
}
|
|
214
507
|
// `enabled` 必须是布尔:`rules-toggle` 缺了它直接拒(ops/memory.ts),但那是给用户看的
|
|
215
508
|
// 中文 op 错;这里先挡一句说清"这条工具要什么"。
|
|
216
509
|
if (typeof (args && args.enabled) !== 'boolean')
|
|
@@ -230,6 +523,11 @@ export function buildMemoryTools(deps) {
|
|
|
230
523
|
if (sessionOnly) {
|
|
231
524
|
if (!deps.sessionScopeSet)
|
|
232
525
|
throw new Error('per-conversation switches are unavailable in this host: pass scope="global" to change it for every conversation');
|
|
526
|
+
// 会话覆盖只对真实存在的记忆有意义:拼错的 id 会静默写一条永远不会生效的覆盖。
|
|
527
|
+
const read = await opOf(deps.rulesOps, 'rules-read')({ id: memory });
|
|
528
|
+
if (!read || read.ok === false) {
|
|
529
|
+
throw new Error('no such memory: ' + memory + ' (per-conversation switches only apply to existing memories)');
|
|
530
|
+
}
|
|
233
531
|
const sc = await deps.sessionScopeSet(exec && exec.agent, 'memory', memory, args.enabled === true);
|
|
234
532
|
if (!sc || sc.ok === false)
|
|
235
533
|
throw new Error((sc && sc.error) || 'failed to switch this memory here');
|
|
@@ -237,7 +535,7 @@ export function buildMemoryTools(deps) {
|
|
|
237
535
|
(sc.cleared === true ? ' (that matches what this scope would see anyway, so the override was removed)' : '') +
|
|
238
536
|
'. ' + globalUnchangedNote(deps) + ' Pass scope="global" to change it for every conversation.';
|
|
239
537
|
}
|
|
240
|
-
const r = await deps.rulesOps
|
|
538
|
+
const r = await opOf(deps.rulesOps, 'rules-toggle')({ id: memory, enabled: args.enabled });
|
|
241
539
|
if (!r || r.ok === false)
|
|
242
540
|
throw new Error((r && r.error) || 'failed to switch this memory');
|
|
243
541
|
const rule = r.rule || {};
|
|
@@ -245,10 +543,11 @@ export function buildMemoryTools(deps) {
|
|
|
245
543
|
// 这一句不说,模型会以为已经生效 —— 与 skill_manager_switch 说清影子副本同一条理由。
|
|
246
544
|
let sceneNote = '';
|
|
247
545
|
try {
|
|
248
|
-
const all = await deps.rulesOps
|
|
546
|
+
const all = await opOf(deps.rulesOps, 'rules-list')({});
|
|
249
547
|
if (all && all.ok !== false) {
|
|
250
548
|
const group = String(rule.group || '');
|
|
251
|
-
const on = group ===
|
|
549
|
+
const on = group === GLOBAL_SCENE || group === SHARED_GROUP ||
|
|
550
|
+
(group !== '' && (all.activeMode === 'all' || String(all.activeScene || '') === group));
|
|
252
551
|
if (!on)
|
|
253
552
|
sceneNote = ' — BUT its scene "' + group + '" is not the one injecting, so it still will not be injected; turn that scene on (or move it to global) first';
|
|
254
553
|
}
|
|
@@ -260,136 +559,615 @@ export function buildMemoryTools(deps) {
|
|
|
260
559
|
},
|
|
261
560
|
}));
|
|
262
561
|
register(defineTool({
|
|
263
|
-
name: '
|
|
264
|
-
//
|
|
265
|
-
//
|
|
266
|
-
//
|
|
267
|
-
|
|
268
|
-
description: 'Create a memory, or update the one with this id — the receipt says which. Memories cost context on every later request: record only what cannot be re-derived from code, config or git, and update an existing one rather than adding a near-duplicate. Blocked while the active scene is locked. Asks the user to confirm before it runs. Only on the user\'s instruction.',
|
|
562
|
+
name: 'memory_remember',
|
|
563
|
+
// 写入口只按**范围**分叉,不再按内容长短分叉:用户说「记录 a」时,唯一要判断的是
|
|
564
|
+
// 「记到哪儿」,而那是用户的问题,不是模型能猜的。旧版按"一句话 → 笔记 / 多段 → 记忆"
|
|
565
|
+
// 重定向,模型于是要在两条工具、三种后端之间选,参数串用是必然的。
|
|
566
|
+
description: 'Remember something the user explicitly asked you to keep. scope=global → every project; scope=workspace → only the project in this conversation; scope=scene → only when that working mode is on. Omit scope and ask the user where it belongs; do not guess. Pass `id` to update an existing memory or note instead of creating one. To delete a user memory the user asked you to remove, pass `action: "forget"` and `id` (moved to the recycle bin). For your own inferences use the agent-note tool, not this. User-memory writes are blocked while the active scene is locked.',
|
|
269
567
|
parameters: {
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
nextName: { type: 'string', description: '
|
|
568
|
+
action: { type: 'string', enum: ['forget'], description: 'forget: delete an existing user memory by `id` (moved to the recycle bin, restorable on the Memory page). Omit to create or update.' },
|
|
569
|
+
content: { type: 'string', description: 'What to remember: the memory body (Markdown, <=2400 display width: about 1200 Chinese chars / 2400 letters). Required when creating; do not pass with action=forget.' },
|
|
570
|
+
title: { type: 'string', description: 'Short name: the file name of the memory. Omit to derive from the first line.' },
|
|
571
|
+
id: { type: 'string', description: 'Update an existing entry instead of creating: a user memory id (<scene>/<name>) or an agent note id (note:...).' },
|
|
572
|
+
scope: { type: 'string', enum: ['scene', 'global', 'workspace'], description: 'Where it belongs: global (every project), workspace (only the project in this conversation), scene (only when that working mode is on). Ask the user when unsure.' },
|
|
573
|
+
scene: { type: 'string', description: 'scope=scene: the scene name; defaults to the active scene. `global` is the always-on scene.' },
|
|
574
|
+
nextName: { type: 'string', description: 'User memories: rename the existing memory to this file name.' },
|
|
277
575
|
},
|
|
278
576
|
output: { schema: { type: 'string' }, render: (_a, v) => text(v) },
|
|
279
577
|
async execute(args, exec) {
|
|
578
|
+
const agent = exec && exec.agent;
|
|
579
|
+
// 旧两条工具的字段名做一次兼容:`memory`/`body` 来自 save,`text`/`layer`/`slot`
|
|
580
|
+
// 来自 note。模型按旧习惯传进来时不该整次失败 —— 这正是合并写入入口要消掉的摩擦。
|
|
581
|
+
// 只做 fallback,不写进 schema:新调用方看到的仍是 content / id / scope。
|
|
582
|
+
const rawId = String((args && (args.id !== undefined ? args.id : args.memory)) || '').trim();
|
|
583
|
+
const content = String((args && (args.content !== undefined ? args.content : (args.body !== undefined ? args.body : (args.text !== undefined ? args.text : '')))) || '');
|
|
584
|
+
const title = String((args && args.title) || '').trim();
|
|
585
|
+
const nextName = String((args && args.nextName) || '').trim();
|
|
586
|
+
const scopeArg = String((args && (args.scope !== undefined ? args.scope : args.layer)) || '').trim();
|
|
587
|
+
const sceneArg = String((args && args.scene) || '').trim();
|
|
588
|
+
const slotArg = String((args && (args.slot !== undefined ? args.slot : args.key)) || '').trim();
|
|
589
|
+
const actionArg = String((args && args.action) || '').trim();
|
|
590
|
+
// 删除是用户明确要求时才走的另一条路:只按 id 定位,绝不把同时带来的 content
|
|
591
|
+
// 当成一次更新写回去 —— 真实会话里 `action=forget` + `content` 就把一条待删
|
|
592
|
+
// 记忆的正文改成了「删」,回执却说更新成功。
|
|
593
|
+
if (actionArg !== '' && actionArg !== 'forget') {
|
|
594
|
+
throw new Error('unknown action: ' + actionArg + ' — memory_remember creates or updates; use action=forget with id to delete a user memory.');
|
|
595
|
+
}
|
|
596
|
+
if (actionArg === 'forget') {
|
|
597
|
+
if (rawId === '')
|
|
598
|
+
throw new Error('missing argument: id — the user memory to delete (<scene>/<name>). Agent notes use memory_note action=forget.');
|
|
599
|
+
if (isNoteRef(rawId))
|
|
600
|
+
throw new Error('that is an agent note: delete it with memory_note action=forget.');
|
|
601
|
+
// 与 update 路径同一条兜底:裸 id 也可能是笔记 id(`note:` 前缀可省)。
|
|
602
|
+
// 两条路不一致时,模型按 update 的习惯传裸 id 来删,会得到"这不是用户记忆"的
|
|
603
|
+
// 错误,而它其实只是忘了加前缀。
|
|
604
|
+
if (!rawId.includes('/') && evo) {
|
|
605
|
+
let note = null;
|
|
606
|
+
try {
|
|
607
|
+
note = await opOf(evo, 'evolution-read')({ id: rawId });
|
|
608
|
+
}
|
|
609
|
+
catch {
|
|
610
|
+
note = null;
|
|
611
|
+
}
|
|
612
|
+
if (note && note.ok !== false) {
|
|
613
|
+
throw new Error('"' + rawId + '" is an agent note, not a user memory: delete it with memory_note action=forget (note=' + rawId + ').');
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
if (!rawId.includes('/'))
|
|
617
|
+
throw new Error('id must be <scene>/<name> (a user memory): ' + rawId);
|
|
618
|
+
if (content.trim() !== '' || nextName !== '' || title !== '' || slotArg !== '' || scopeArg !== '' || sceneArg !== '') {
|
|
619
|
+
throw new Error('action=forget deletes by id only: do not pass content, title, nextName, scope or scene.');
|
|
620
|
+
}
|
|
621
|
+
const blocked = await deps.lockedSceneGuard();
|
|
622
|
+
if (blocked)
|
|
623
|
+
throw new Error(blocked);
|
|
624
|
+
const all = await opOf(deps.rulesOps, 'rules-list')({});
|
|
625
|
+
if (!all || all.ok === false)
|
|
626
|
+
throw new Error((all && all.error) || 'failed to read memories');
|
|
627
|
+
const hit = (all.rules || []).find((x) => String(x.id) === rawId);
|
|
628
|
+
if (!hit)
|
|
629
|
+
throw new Error('no memory with id "' + rawId + '".' + existingNote((all.rules || []).map((x) => String(x.id)), 'memory ids'));
|
|
630
|
+
if (isAutoRule(hit))
|
|
631
|
+
throw new Error('that is an agent note: delete it with memory_note action=forget.');
|
|
632
|
+
const r = await opOf(deps.rulesOps, 'rules-remove')({ id: rawId });
|
|
633
|
+
if (!r || r.ok === false)
|
|
634
|
+
throw new Error(String((r && r.error) || 'failed to delete the memory'));
|
|
635
|
+
return 'OK: deleted ' + rawId + ' (moved to the recycle bin; restore it on the Memory page).';
|
|
636
|
+
}
|
|
637
|
+
/** 就地更新一条已有笔记:id / 层 / 状态不变,正文与标题替换。 */
|
|
638
|
+
const updateNote = async (a, ref) => {
|
|
639
|
+
if (nextName !== '')
|
|
640
|
+
throw new Error('nextName is for user memories; a note uses title.');
|
|
641
|
+
const layer = String(a.layer || '');
|
|
642
|
+
if (layer !== 'global' && layer !== 'workspace') {
|
|
643
|
+
throw new Error('that note is not a global or workspace note, so memory_remember cannot update it: ' + ref);
|
|
644
|
+
}
|
|
645
|
+
const id = String(a.id || stripNoteRef(ref));
|
|
646
|
+
const text = content !== '' ? content.trim() : String(a.body || '').trim();
|
|
647
|
+
if (text === '')
|
|
648
|
+
throw new Error('missing argument: content — the updated note text.');
|
|
649
|
+
if (textWidthOf(text) > MAX_AUTO_TEXT_WIDTH || /\n\s*\n/.test(text)) {
|
|
650
|
+
throw new Error('an agent note is one sentence (<= about 1200 Chinese chars / 2400 letters). This content is longer — use a user memory (scope=scene / global) instead.');
|
|
651
|
+
}
|
|
652
|
+
// 笔记的正文编辑是 `evolution-update`(就地改文件、id/层/状态不变);
|
|
653
|
+
// `evolution-learn` 是"学一条新的"——同 key 只会合并/追加,没 key 会新建 id,
|
|
654
|
+
// 拿它做更新会把原文留在旧条目里,回执却说"updated"。
|
|
655
|
+
const updateOp = evo['evolution-update'];
|
|
656
|
+
if (typeof updateOp !== 'function') {
|
|
657
|
+
throw new Error('this host cannot edit an agent note in place. Forget it with memory_note action=forget and learn a new one, or use memory_note action=learn with the same slot.');
|
|
658
|
+
}
|
|
659
|
+
// 并发编辑保护:先读一次拿当前正文指纹,写回时带上。缺了它,模型与用户同时改
|
|
660
|
+
// 同一条笔记时后保存的会静默覆盖先保存的,且没有任何 `stale` 提示 —— 界面编辑
|
|
661
|
+
// 弹窗一直传 `baseHash`,只有模型这条路漏了。
|
|
662
|
+
const readOp = evo['evolution-read'];
|
|
663
|
+
let baseHash = '';
|
|
664
|
+
if (typeof readOp === 'function') {
|
|
665
|
+
try {
|
|
666
|
+
const cur = await readOp({ id });
|
|
667
|
+
if (cur && cur.ok !== false && typeof cur.hash === 'string')
|
|
668
|
+
baseHash = cur.hash;
|
|
669
|
+
}
|
|
670
|
+
catch { /* 读不到指纹就按无指纹写(与旧行为一致),不因此拒掉整次更新 */ }
|
|
671
|
+
}
|
|
672
|
+
const payload = { id, text };
|
|
673
|
+
if (baseHash !== '')
|
|
674
|
+
payload.baseHash = baseHash;
|
|
675
|
+
if (title !== '')
|
|
676
|
+
payload.title = truncateToWidth(title, MAX_AUTO_TITLE_WIDTH);
|
|
677
|
+
const r = await updateOp(payload);
|
|
678
|
+
if (!r || r.ok === false)
|
|
679
|
+
throw new Error(String((r && r.error) || 'failed to update the note'));
|
|
680
|
+
const status = String(r.status || a.status || 'active');
|
|
681
|
+
const state = status === 'active' ? 'active' : status + ' — confirm it in Memory → Autonomous memory before it injects';
|
|
682
|
+
return 'OK: updated ' + noteRefOf(String(r.id || id)) + ' (' + String(r.layer || layer) + ' note, ' + state + ')';
|
|
683
|
+
};
|
|
684
|
+
// 带 id 时 scope 不参与路由,但仍要先挡掉不可能的范围:用户说「只在这个对话里」
|
|
685
|
+
// 时不能因为传了 id 就悄悄改掉磁盘上那份全局记忆。
|
|
686
|
+
if (scopeArg === 'conversation') {
|
|
687
|
+
throw new Error('scope=conversation is not supported: per-conversation memories are not injected. Use scope=scene (this working mode) or scope=global (every project).');
|
|
688
|
+
}
|
|
689
|
+
if (rawId !== '' && scopeArg === 'workspace' && !isNoteRef(rawId)) {
|
|
690
|
+
throw new Error('scope=workspace is for agent notes; to update a user memory pass id alone (or use id=note:... for a note).');
|
|
691
|
+
}
|
|
692
|
+
if (rawId !== '') {
|
|
693
|
+
if (isNoteRef(rawId)) {
|
|
694
|
+
if (!evo)
|
|
695
|
+
throw new Error('agent notes are not available in this build');
|
|
696
|
+
if (!(deps.autoLearnEnabled && deps.autoLearnEnabled(agent))) {
|
|
697
|
+
throw new Error('autonomous memory is off here, so agent notes cannot be updated. The user can turn it on in Memory → Autonomous memory.');
|
|
698
|
+
}
|
|
699
|
+
const raw = stripNoteRef(rawId);
|
|
700
|
+
let a = await opOf(evo, 'evolution-read')({ id: raw, touch: true });
|
|
701
|
+
if (!a || a.ok === false) {
|
|
702
|
+
const resolved = await resolveNote(raw);
|
|
703
|
+
if (resolved.id !== null) {
|
|
704
|
+
const found = await opOf(evo, 'evolution-read')({ id: resolved.id, touch: true });
|
|
705
|
+
if (found && found.ok !== false)
|
|
706
|
+
a = found;
|
|
707
|
+
}
|
|
708
|
+
else if (resolved.hits.length > 1) {
|
|
709
|
+
throw new Error('ambiguous: "' + rawId + '" matches ' + describeNoteHits(resolved.hits) + '; pass one of these ids.');
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
if (!a || a.ok === false)
|
|
713
|
+
throw new Error(String((a && a.error) || 'no such agent note: ' + rawId));
|
|
714
|
+
return updateNote(a, rawId);
|
|
715
|
+
}
|
|
716
|
+
if (!rawId.includes('/')) {
|
|
717
|
+
throw new Error('id must be <scene>/<name> (a user memory) or note:... (an agent note): ' + rawId);
|
|
718
|
+
}
|
|
719
|
+
const blocked = await deps.lockedSceneGuard();
|
|
720
|
+
if (blocked)
|
|
721
|
+
throw new Error(blocked);
|
|
722
|
+
const all = await opOf(deps.rulesOps, 'rules-list')({});
|
|
723
|
+
if (!all || all.ok === false)
|
|
724
|
+
throw new Error((all && all.error) || 'failed to read memories');
|
|
725
|
+
const hit = (all.rules || []).find((x) => String(x.id) === rawId);
|
|
726
|
+
if (!hit) {
|
|
727
|
+
// 与 memory_get 同一条回退:裸 id 也可能是笔记 id(`note:` 前缀可省)。
|
|
728
|
+
if (evo) {
|
|
729
|
+
let note = null;
|
|
730
|
+
try {
|
|
731
|
+
note = await opOf(evo, 'evolution-read')({ id: rawId, touch: true });
|
|
732
|
+
}
|
|
733
|
+
catch {
|
|
734
|
+
note = null;
|
|
735
|
+
}
|
|
736
|
+
if (note && note.ok !== false) {
|
|
737
|
+
if (!(deps.autoLearnEnabled && deps.autoLearnEnabled(agent))) {
|
|
738
|
+
throw new Error('autonomous memory is off here, so agent notes cannot be updated. The user can turn it on in Memory → Autonomous memory.');
|
|
739
|
+
}
|
|
740
|
+
return updateNote(note, rawId);
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
const ids = (all.rules || []).map((x) => String(x.id));
|
|
744
|
+
throw new Error('no memory with id "' + rawId + '"' + existingNote(ids, 'memory ids') + '. Pass scope=scene/global/workspace to create a new one.');
|
|
745
|
+
}
|
|
746
|
+
if (isAutoRule(hit)) {
|
|
747
|
+
throw new Error('that is an agent note, not a user memory: update it with id=note:' + rawId + ' or the agent-note tool.');
|
|
748
|
+
}
|
|
749
|
+
const touched = [];
|
|
750
|
+
const payload = { id: rawId };
|
|
751
|
+
const contentGiven = Boolean(args && (args.content !== undefined || args.body !== undefined || args.text !== undefined));
|
|
752
|
+
if (contentGiven) {
|
|
753
|
+
if (content.trim() === '')
|
|
754
|
+
throw new Error('content cannot be empty when updating a memory');
|
|
755
|
+
payload.body = content;
|
|
756
|
+
touched.push('content');
|
|
757
|
+
}
|
|
758
|
+
if (nextName !== '') {
|
|
759
|
+
payload.name = nextName;
|
|
760
|
+
touched.push('nextName');
|
|
761
|
+
}
|
|
762
|
+
if (!touched.length)
|
|
763
|
+
throw new Error('nothing to change: give content or nextName');
|
|
764
|
+
const r = await opOf(deps.rulesOps, 'rules-update')(payload);
|
|
765
|
+
if (!r || r.ok === false)
|
|
766
|
+
throw new Error((r && r.error) || 'failed to update the memory');
|
|
767
|
+
const rule = r.rule || {};
|
|
768
|
+
return 'OK: updated ' + String(rule.id || rawId) + ' (changed ' + touched.join(', ') + ')' +
|
|
769
|
+
(rule.id && String(rule.id) !== rawId ? ' → now ' + rule.id : '');
|
|
770
|
+
}
|
|
771
|
+
if (content.trim() === '') {
|
|
772
|
+
throw new Error('missing argument: content — what to remember. (The old body / text arguments are now content.)');
|
|
773
|
+
}
|
|
774
|
+
if (nextName !== '')
|
|
775
|
+
throw new Error('nextName renames an existing memory; to name a new one use title.');
|
|
776
|
+
const scope = scopeArg !== '' ? scopeArg : (sceneArg !== '' ? 'scene' : '');
|
|
777
|
+
if (scope === '') {
|
|
778
|
+
throw new Error('where should this be remembered? Pass scope=scene (only when this working mode is active), scope=global (every project), or scope=workspace (this project). Ask the user which one; do not guess.');
|
|
779
|
+
}
|
|
780
|
+
if (scope !== 'scene' && scope !== 'global' && scope !== 'workspace') {
|
|
781
|
+
throw new Error('unknown scope: ' + scope + ' (expected scene / global / workspace)');
|
|
782
|
+
}
|
|
783
|
+
if (scope === 'workspace') {
|
|
784
|
+
// 工作区记忆是**用户的资产**:写进用户记忆库的 `_ws/<hash16>` 组,与自主笔记完全分开
|
|
785
|
+
// (那棵树的同一层是 agent 自己的缓存,会衰减、会被合并、会进回收站)。
|
|
786
|
+
// 因此它不需要自主记忆开关 —— 用户说「记住这个项目的约定」不该被一个"agent 能不能
|
|
787
|
+
// 自学"的开关挡住。
|
|
788
|
+
const identity = deps.sessionIdentity ? deps.sessionIdentity(agent) : null;
|
|
789
|
+
const cwd = identity?.cwd;
|
|
790
|
+
if (!cwd) {
|
|
791
|
+
throw new Error('this conversation has no working directory, so there is no workspace to attach the memory to. Use scope=global, or scope=scene for the current working mode.');
|
|
792
|
+
}
|
|
793
|
+
const group = deps.workspaceGroupOf ? deps.workspaceGroupOf(agent) : '';
|
|
794
|
+
if (group === '') {
|
|
795
|
+
throw new Error('could not resolve a workspace for this conversation. Use scope=global, or scope=scene for the current working mode.');
|
|
796
|
+
}
|
|
797
|
+
const body = content;
|
|
798
|
+
const name = slugOf(title !== '' ? title : firstLineOf(body));
|
|
799
|
+
const r = await opOf(deps.rulesOps, 'rules-create')({
|
|
800
|
+
group,
|
|
801
|
+
name,
|
|
802
|
+
body,
|
|
803
|
+
enabled: true,
|
|
804
|
+
});
|
|
805
|
+
if (!r || r.ok === false)
|
|
806
|
+
throw new Error((r && r.error) || 'failed to save the workspace memory');
|
|
807
|
+
const id = String((r.rule && r.rule.id) || group + '/' + name);
|
|
808
|
+
return 'OK: remembered as a workspace memory ' + id + ' (only this project; injected whenever you work in it).';
|
|
809
|
+
}
|
|
810
|
+
if (scope === 'global' && sceneArg !== '' && sceneArg !== GLOBAL_SCENE) {
|
|
811
|
+
throw new Error('scope=global does not take a scene (got "' + sceneArg + '"). Use scope=scene with that scene, or omit scene.');
|
|
812
|
+
}
|
|
280
813
|
const blocked = await deps.lockedSceneGuard();
|
|
281
814
|
if (blocked)
|
|
282
815
|
throw new Error(blocked);
|
|
283
|
-
const
|
|
284
|
-
// 拆成 `<场景>/<名字>`:要求两段都非空。**不做"没有斜杠就落 global"的兜底** —— 那会把
|
|
285
|
-
// 一次拼错的 id 变成一条"每轮都注入"的全局记忆,而清单上看起来完全正常。
|
|
286
|
-
// 清单里打印的就是 `<场景>/<名字>`,照抄比拼装准。
|
|
287
|
-
const slash = memory.indexOf('/');
|
|
288
|
-
if (slash <= 0 || slash === memory.length - 1) {
|
|
289
|
-
// 这一条错得最有规律:用户口语里说的是「编程约定」,模型手里没有 id,就把那个名字
|
|
290
|
-
// 直接传进来了。给两条现成的 id 比再解释一遍格式有用;读失败就只报格式
|
|
291
|
-
// (`candidateNote` 自己吞掉失败,不改变错误结论)。
|
|
292
|
-
const note = await candidateNote(async () => {
|
|
293
|
-
const r = await deps.rulesOps['rules-list']({});
|
|
294
|
-
return r && r.ok !== false ? (r.rules || []).map((x) => String(x.id)) : [];
|
|
295
|
-
}, 'memory ids');
|
|
296
|
-
throw new Error('memory must be <scene>/<name> (copy that from the listing; the always-on scene is written global/<name>): ' + (memory || '(empty)') + note);
|
|
297
|
-
}
|
|
298
|
-
const group = memory.slice(0, slash);
|
|
299
|
-
const name = memory.slice(slash + 1);
|
|
300
|
-
// 先取全量:既用来定位(命中 = 改、未命中 = 建),也是查重的数据源。判定必须在工具
|
|
301
|
-
// 这一侧 —— `rules-create` 对同名是**拒绝**的(`error.rules.exists`),op 不会 upsert。
|
|
302
|
-
const all = await deps.rulesOps['rules-list']({});
|
|
816
|
+
const all = await opOf(deps.rulesOps, 'rules-list')({});
|
|
303
817
|
if (!all || all.ok === false)
|
|
304
818
|
throw new Error((all && all.error) || 'failed to read memories');
|
|
305
|
-
|
|
819
|
+
// `_shared` 不进候选:它恒常注入、在界面上也没有开关,agent 往里写等于**自己造一个
|
|
820
|
+
// 常开场景**,绕开了用户对"哪条记忆该生效"的控制。恒常注入的只有 `global` 一个。
|
|
821
|
+
const knownGroups = new Set(sceneNamesOf(all).filter((s) => s !== SHARED_GROUP));
|
|
822
|
+
knownGroups.add(GLOBAL_SCENE);
|
|
823
|
+
let group = scope === 'global' ? GLOBAL_SCENE : sceneArg;
|
|
824
|
+
if (scope === 'scene' && group === '') {
|
|
825
|
+
group = String((deps.activeSceneOf ? deps.activeSceneOf(agent) : '') || '');
|
|
826
|
+
}
|
|
827
|
+
if (group === '') {
|
|
828
|
+
const scenes = [...knownGroups].filter((s) => s !== '').sort();
|
|
829
|
+
throw new Error('scope=scene needs a scene, and this conversation has no active scene. Existing scenes: ' + scenes.join(', ') + '. Ask the user which one; do not guess.');
|
|
830
|
+
}
|
|
831
|
+
if (group === SHARED_GROUP) {
|
|
832
|
+
// 显式传了也拒:这条路径上没有"用户明确要求"的证据,而写进去的记忆不受任何开关
|
|
833
|
+
// 控制。要全局生效就用 scope=global;要场景生效就让用户先建 / 开一个场景。
|
|
834
|
+
throw new Error('_shared is not a writable scene: memories there are injected in every conversation and have no on/off switch, so an agent must not create one. Use scope=global for something that should apply everywhere, or scope=scene with a scene the user has turned on.');
|
|
835
|
+
}
|
|
836
|
+
if (group === '_ws' || group.startsWith('_ws/') || group === '_session' || group.startsWith('_session/')) {
|
|
837
|
+
throw new Error('"' + group + '" is internal storage for agent notes, not a user scene. For a workspace note use scope=workspace; for a user memory use an existing scene (global, …).');
|
|
838
|
+
}
|
|
839
|
+
if (!knownGroups.has(group)) {
|
|
840
|
+
const scenes = [...knownGroups].filter((s) => s !== '').sort();
|
|
841
|
+
throw new Error('scene "' + group + '" does not exist — memories can only be created inside an existing scene. Existing scenes: ' + scenes.join(', ') + '. The user creates scenes in the plugin panel (Scenes page); then remember again.');
|
|
842
|
+
}
|
|
843
|
+
const body = content;
|
|
844
|
+
const name = slugOf(title !== '' ? title : firstLineOf(body));
|
|
845
|
+
const id = group + '/' + name;
|
|
846
|
+
const hit = (all.rules || []).find((x) => String(x.id) === id);
|
|
306
847
|
if (hit) {
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
const payload = { id: memory };
|
|
314
|
-
// 只带模型真给过的键:`description` 传空串在 op 里是"删除并重新派生",与"未给"是两种
|
|
315
|
-
// 意图,都必须原样透传 —— 所以用 `!== undefined` 而不是真值判断。
|
|
316
|
-
if (args.body !== undefined)
|
|
317
|
-
payload.body = args.body;
|
|
318
|
-
if (args.description !== undefined)
|
|
319
|
-
payload.description = args.description;
|
|
320
|
-
if (args.nextName !== undefined)
|
|
321
|
-
payload.name = args.nextName;
|
|
322
|
-
const r = await deps.rulesOps['rules-update'](payload);
|
|
848
|
+
if (isAutoRule(hit)) {
|
|
849
|
+
throw new Error('the derived id "' + id + '" belongs to an agent note, not a user memory. Pick a different title, or use scope=workspace for a note.');
|
|
850
|
+
}
|
|
851
|
+
// 同名 upsert:用户说「记住」两次,第二句通常是在改同一条;替换正文而不是再建一条。
|
|
852
|
+
const payload = { id, body };
|
|
853
|
+
const r = await opOf(deps.rulesOps, 'rules-update')(payload);
|
|
323
854
|
if (!r || r.ok === false)
|
|
324
855
|
throw new Error((r && r.error) || 'failed to update the memory');
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
}
|
|
329
|
-
// 建的分支:正文与描述都必填。`rules-create` 自己会拒空正文与非法名(ops/memory.ts),
|
|
330
|
-
// 但那是给用户看的中文 op 错;模型需要的是"这条工具要什么",所以在工具侧先挡、点名缺哪个。
|
|
331
|
-
const body = args && args.body !== undefined ? String(args.body) : '';
|
|
332
|
-
const description = args && args.description !== undefined ? String(args.description) : '';
|
|
333
|
-
const missing = [
|
|
334
|
-
body.trim() === '' ? 'body' : '',
|
|
335
|
-
description.trim() === '' ? 'description' : '',
|
|
336
|
-
].filter((x) => x !== '');
|
|
337
|
-
if (missing.length) {
|
|
338
|
-
// id 不存在 + 内容也不全:最可能是名字记差了一个字。先给**同一场景**里现成的 id
|
|
339
|
-
// (整个库列出来只会把这条错误变成噪音),一条都没有才退回全库。
|
|
340
|
-
const ids = (all.rules || []).map((x) => String(x.id));
|
|
341
|
-
const here = ids.filter((id) => id.indexOf(group + '/') === 0);
|
|
342
|
-
throw new Error('creating a memory needs ' + missing.join(' and ') + ' (' + memory + ' does not exist yet)'
|
|
343
|
-
+ existingNote(here.length ? here : ids, 'memory ids'));
|
|
344
|
-
}
|
|
345
|
-
// 查重只**说出来**,不拒绝 —— 猜错一次就把该记的东西记不下去,比多记一条代价大得多;
|
|
346
|
-
// 而且"像不像同一条"本来就是人判断的事。只在建的分支提示:改的分支没有"再记一条"的风险。
|
|
856
|
+
return 'OK: updated ' + String((r.rule && r.rule.id) || id) + ' (same name already existed; content replaced)' +
|
|
857
|
+
globalActionNote(deps, agent, 'memory', 'memory');
|
|
858
|
+
}
|
|
347
859
|
const norm = (value) => String(value ?? '').toLowerCase().replace(/\s+/g, ' ').trim();
|
|
348
860
|
const wantName = norm(name);
|
|
349
|
-
const wantDesc = norm(description);
|
|
350
861
|
const similar = (all.rules || [])
|
|
862
|
+
.filter((x) => !isAutoRule(x))
|
|
351
863
|
.filter((x) => {
|
|
352
864
|
const have = norm(x.name);
|
|
353
|
-
const desc = norm(x.description);
|
|
354
865
|
if (have === wantName)
|
|
355
866
|
return true;
|
|
356
|
-
if (wantDesc !== '' && desc !== '' && desc === wantDesc)
|
|
357
|
-
return true;
|
|
358
867
|
// 名字互相包含:只在两边都不短于 4 个字符时算,否则 "git" 会把所有条目都匹配上。
|
|
359
868
|
return have.length >= 4 && wantName.length >= 4 && (have.includes(wantName) || wantName.includes(have));
|
|
360
869
|
})
|
|
361
870
|
.map((x) => String(x.id))
|
|
362
871
|
.slice(0, 3);
|
|
363
|
-
const r = await deps.rulesOps
|
|
872
|
+
const r = await opOf(deps.rulesOps, 'rules-create')({ group, name, body, enabled: true });
|
|
364
873
|
if (!r || r.ok === false)
|
|
365
874
|
throw new Error((r && r.error) || 'failed to create the memory');
|
|
366
875
|
// 刚建好的这条自己会在列表里,从名单里去掉。
|
|
367
|
-
const dup = similar.filter((
|
|
876
|
+
const dup = similar.filter((sid) => sid !== String(r.rule.id));
|
|
368
877
|
const warn = dup.length
|
|
369
|
-
? `\nnote: ${dup.length} existing memories have a similar name
|
|
878
|
+
? `\nnote: ${dup.length} existing memories have a similar name (${dup.join(', ')}) — if it is the same thing, update that one instead of keeping two.`
|
|
370
879
|
: '';
|
|
371
|
-
//
|
|
372
|
-
//
|
|
373
|
-
//
|
|
374
|
-
//
|
|
375
|
-
|
|
376
|
-
// 那个场景在这个对话里根本没开着 —— 照全局口径回一句"打开就能用"是错的答案。
|
|
377
|
-
const scoped = sessionScopeOf(deps, exec && exec.agent);
|
|
880
|
+
// 回执必须同时说清**两个**条件:记忆本身已开启(本工具创建时传了 `enabled: true`),
|
|
881
|
+
// 但它落进的场景在这个对话里未必开着 —— 场景没开,单条开关拨上去也不会注入。
|
|
882
|
+
// 「会不会注入」按**本会话**的投影判:会话钉了别的场景时,照全局口径回一句
|
|
883
|
+
// "打开就能用"是错的答案。
|
|
884
|
+
const scoped = sessionScopeOf(deps, agent);
|
|
378
885
|
const effScene = scoped?.scope?.scene;
|
|
379
886
|
const activeNow = effScene === undefined ? all.activeScene : effScene;
|
|
380
887
|
const activeMode = effScene === undefined ? all.activeMode : 'custom';
|
|
381
|
-
const sceneActive = group ===
|
|
888
|
+
const sceneActive = group === GLOBAL_SCENE || group === SHARED_GROUP ||
|
|
382
889
|
(group !== '' && (activeMode === 'all' || String(activeNow || '') === group));
|
|
383
|
-
const
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
const enableHint = deps.toolVisibleFor('memory_manager_switch', exec && exec.agent)
|
|
387
|
-
? ' (created disabled — turn it on first with memory_manager_switch' + sceneTail + ')'
|
|
388
|
-
: ' (created disabled — the user has to turn it on first' + sceneTail + ')';
|
|
389
|
-
// 会话层:这条记忆写的是**磁盘上的那一份**(所有对话共用),本会话的开关只决定
|
|
390
|
-
// "这里看不看得到"。模型据此回一句"记下了"时,用户很容易读成"只在这个对话里"。
|
|
890
|
+
const enableHint = sceneActive
|
|
891
|
+
? ' (created enabled)'
|
|
892
|
+
: ' (created enabled, but scene "' + group + '" is not on in this conversation, so it will not be injected here until that scene is turned on)';
|
|
391
893
|
return 'OK: created ' + r.rule.id + enableHint + warn +
|
|
392
|
-
globalActionNote(deps,
|
|
894
|
+
globalActionNote(deps, agent, 'memory', 'memory');
|
|
393
895
|
},
|
|
394
896
|
}));
|
|
897
|
+
// ── 自主笔记(只在开关打开时出现在工具表里)────────────────────────────────
|
|
898
|
+
//
|
|
899
|
+
// 为什么不复用 `memory_remember`:那条的契约是「Only on the user's instruction」并且
|
|
900
|
+
// 受确认门禁。自主笔记需要零摩擦:给 `save` 加一个 `auto` 参数会让同一个工具同时代表
|
|
901
|
+
// 两种授权,门禁只能按参数分叉;模型传错一次就是"该问的没问"。授权边界写在工具名上。
|
|
902
|
+
//
|
|
903
|
+
// 与用户记忆分开的另一点是**对象**:笔记是一句话、按层(global / workspace)走;
|
|
904
|
+
// 用户记忆是多段、按场景走。读取统一走 `memory_get`,这里只保留写入与删除。
|
|
905
|
+
// 弹卡策略:自动确认关 → 每次都问;开 → 不弹卡,由 agent 决定。生效判断在 gates 的 `autoActive`。
|
|
906
|
+
if (!deps.evolutionOps || !deps.autoLearnEnabled)
|
|
907
|
+
return;
|
|
908
|
+
const noteOps = deps.evolutionOps;
|
|
909
|
+
register(defineTool({
|
|
910
|
+
name: PROACTIVE_MEMORY_TOOL,
|
|
911
|
+
description: 'Agent notes (autonomous memory) — one-line notes YOU decided are worth keeping across conversations: a preference, a fact, a correction of your behaviour, or a repeatable procedure. Use this for your own judgement; when the user explicitly asks you to remember something, use memory_remember instead (that is their asset, this is your cache).\n\nWrite it in one call and move on. If a call is refused, the reply names every problem at once — fix them in one retry, or drop the note and get back to the task. Do not reword the same idea repeatedly: a note that keeps failing is one the user did not need.\n\nRecord what will still hold in a different conversation, and nothing else:\n- A one-off ("this time", "for now", "next step") is not a note.\n- Something re-derivable from the code or config (dependency versions, file lists, config values) is not a note — read the file instead.\n- Say the thing itself, in words. Fragments, markup, and pure punctuation are refused.\n\nlearn: `title` (2-8 words) + `text` (<=1200 Chinese chars / 2400 letters; 1-2 clear sentences, or follow the style line in the learned-notes section); `kind` — preference / fact / correction / procedure (it sets the review interval: fact and procedure are re-checked after 30 days, preference and correction never expire, so a procedure filed as a correction stays forever); `layer` global = every project / workspace = this one; pass `slot` (a stable name) when you may update or forget it later; pass `quote` (their exact words) when you are recording something the user actually said — it is checked verbatim against this conversation, and if it does not match the note is still saved but with weaker evidence, so quote exactly when you can.\n\nEvery note shows the user a card unless they turned auto-confirm on. Check for an existing note on the same thing first (the memory read tool with kind=note lists them) — two notes saying the same thing in different words are both injected into every later conversation, and the duplicate check compares wording, not meaning. forget: `note` = id (note:...), slot, title, or the first line as it was injected. Inspect notes with the memory read tool.',
|
|
912
|
+
parameters: {
|
|
913
|
+
action: { type: 'string', enum: ['learn', 'forget'], required: true, description: 'learn or forget.' },
|
|
914
|
+
// ── learn ──
|
|
915
|
+
title: { type: 'string', description: 'learn: a short name for the row (2-8 words, <=50 Chinese chars / 100 letters), in the user\'s language.' },
|
|
916
|
+
text: { type: 'string', description: 'learn: the note itself (<=1200 Chinese chars / 2400 letters), in the user\'s language; by default 1-2 clear sentences, conclusion first, key reason only when it matters. Follow the style shown in the learned-notes section when present. `note` is accepted as an alias.' },
|
|
917
|
+
quote: { type: 'string', description: 'learn: the user\'s exact words, copied verbatim, when you are recording something they said. Checked against this conversation; a quote that does not match does not fail the call — the note is kept with weaker evidence. Omit it for your own inferences.' },
|
|
918
|
+
slot: { type: 'string', description: 'learn: optional stable slot name; learning again with the same slot merges when it says the same thing, and replaces the old note when it conflicts.' },
|
|
919
|
+
boundary: { type: 'string', description: 'learn: optional; when it may not hold.' },
|
|
920
|
+
layer: { type: 'string', enum: ['global', 'workspace'], description: 'learn: global (every project) or workspace (this project). Omit only when unsure; the card asks, or auto-confirm uses the default.' },
|
|
921
|
+
ttlDays: { type: 'number', description: 'learn: optional; re-check after N days.' },
|
|
922
|
+
// `kind` 决定保质期(事实 / 做法 30 天后提醒复核,偏好 / 纠正不过期)。不给时由
|
|
923
|
+
// `inferKind` 按措辞猜,而它只能看字面 —— 「必须 / 不要」这类约束词会把做法误判成
|
|
924
|
+
// 纠正,于是一条会过期的做法被永久固化。模型知道这句话是什么,就让它自己说。
|
|
925
|
+
kind: {
|
|
926
|
+
type: 'string',
|
|
927
|
+
enum: ['preference', 'fact', 'correction', 'procedure'],
|
|
928
|
+
description: 'learn: how this note changes your future behaviour — preference (how to answer / which tool / which style), fact (a stable fact about the user or project), procedure (a repeatable sequence of steps), correction (the user fixing something you already did). Omit only when unsure.',
|
|
929
|
+
},
|
|
930
|
+
// ── forget ──
|
|
931
|
+
note: { type: 'string', description: 'forget: the note — id (note:...), slot, title, or the first line of the note as it was injected (trailing punctuation ignored; the full body is not required). learn: alias for text (the note body).' },
|
|
932
|
+
},
|
|
933
|
+
output: { schema: { type: 'string' }, render: (_a, v) => text(v) },
|
|
934
|
+
async execute(args, exec) {
|
|
935
|
+
const agent = exec && exec.agent;
|
|
936
|
+
if (!deps.autoLearnEnabled(agent)) {
|
|
937
|
+
// 开关在调用途中被关掉(另一个窗口 / 本会话切了)也要说清,而不是静默什么都不做。
|
|
938
|
+
throw new Error('autonomous memory is off here, so nothing was done. The user can turn it on in Memory → Autonomous memory.');
|
|
939
|
+
}
|
|
940
|
+
const action = String((args && args.action) || 'learn');
|
|
941
|
+
if (action === 'forget') {
|
|
942
|
+
const ref = noteArgOf(args);
|
|
943
|
+
if (ref === '')
|
|
944
|
+
throw new Error('missing argument: note — the note id (note:...), its slot, its title, or the first line of the note as injected (trailing punctuation ignored).');
|
|
945
|
+
const raw = stripNoteRef(ref);
|
|
946
|
+
const forget = async (id) => opOf(noteOps, 'evolution-forget')({ id, actor: 'model' });
|
|
947
|
+
let r = await forget(raw);
|
|
948
|
+
if (!r || r.ok === false) {
|
|
949
|
+
// 注入行只显示 key / 摘要,模型不一定记得 id:按 id / slot / title / 原文反查一次,唯一命中才删。
|
|
950
|
+
const resolved = await resolveNote(raw);
|
|
951
|
+
if (resolved.id !== null)
|
|
952
|
+
r = await forget(resolved.id);
|
|
953
|
+
else if (resolved.hits.length > 1) {
|
|
954
|
+
throw new Error('ambiguous: "' + ref + '" matches ' + describeNoteHits(resolved.hits) + '; pass one of these ids.');
|
|
955
|
+
}
|
|
956
|
+
}
|
|
957
|
+
if (!r || r.ok === false) {
|
|
958
|
+
// 带 `note:` 前缀的一定是笔记:它只是不存在了,别再说"这像是用户记忆"。
|
|
959
|
+
if (isNoteRef(ref)) {
|
|
960
|
+
throw new Error('no such agent note: ' + ref + ' (it may have been forgotten or archived). List the current notes with memory_get kind=note.');
|
|
961
|
+
}
|
|
962
|
+
// 用户记忆 id 也是 `<scene>/<name>` 形状;零命中时明确说这不是笔记,别让模型再猜。
|
|
963
|
+
if (raw.includes('/')) {
|
|
964
|
+
throw new Error('no such agent note: ' + ref + '. That looks like a user memory id (<scene>/<name>) — user memories are disabled or deleted on the Memory page, not here. Agent note ids start with note:.');
|
|
965
|
+
}
|
|
966
|
+
// 走到这里说明 id / slot / title / 注入行都没命中。`evolution-forget` 的内部错
|
|
967
|
+
// (`not a memory id`)对模型没有任何可执行信息 —— 它要的是"下一步做什么"。
|
|
968
|
+
throw new Error('no such agent note: "' + ref + '". Pass its id (note:<layer>/<slug>), its slot, its title, or the first line exactly as it was injected; list the current notes with memory_get kind=note to find one.');
|
|
969
|
+
}
|
|
970
|
+
return 'OK: forgot ' + noteRefOf(String(r.id || raw)) + '. It will not be learned again for 30 days.';
|
|
971
|
+
}
|
|
972
|
+
if (action !== 'learn')
|
|
973
|
+
throw new Error('unknown action: ' + action + ' (expected learn / forget)');
|
|
974
|
+
// save 的参数串进来时(`body` / `memory`),直接指回用户记忆,
|
|
975
|
+
// 别让一次完整记忆被当成一句话笔记丢掉。
|
|
976
|
+
if (args && (args.body !== undefined || args.memory !== undefined)) {
|
|
977
|
+
throw new Error('those are user-memory parameters, not note parameters: for a full memory call memory_remember with content and scope=scene/global. For a note pass title and text (the same slot merges the same meaning and replaces a conflicting note).');
|
|
978
|
+
}
|
|
979
|
+
// ── learn(默认)──
|
|
980
|
+
//
|
|
981
|
+
// 先查用户记忆里是不是已经有同一条:用户自己写过的(或让模型写过的)记忆**永久生效、
|
|
982
|
+
// 不衰减、不进回收站**,而笔记是会被 TTL 提醒、被合并、被归档的缓存。模型不知道这件事,
|
|
983
|
+
// 于是常见症状是——用户说「记住这个仓库用 pnpm」,模型先用 memory_remember 存了一条,
|
|
984
|
+
// 之后每次看到又顺手记一条笔记,页面上同一条规则出现两遍,其中一遍还会自己过期。
|
|
985
|
+
//
|
|
986
|
+
// 命中就**不写**,并把已有的那条 id 告诉模型:它可以去更新那条,而不是另立一条。
|
|
987
|
+
const identity = deps.sessionIdentity ? deps.sessionIdentity(agent) : null;
|
|
988
|
+
// `note` 是模型按工具名最常写的那个字段(真实会话里就有人把正文塞进 `note`,
|
|
989
|
+
// 然后在 `text` 的必填校验上白跑一次)。learn 时把它当正文别名;forget 仍只读 `note`。
|
|
990
|
+
const bodyArg = args && String(args.text || '').trim() !== '' ? args.text : args && args.note;
|
|
991
|
+
const text = String(bodyArg || '').trim();
|
|
992
|
+
if (text === '')
|
|
993
|
+
throw new Error('missing argument: text (or note) — the note itself, one sentence.');
|
|
994
|
+
// 已经在用户记忆里说过的事不再记一条笔记:见 `userMemoryCovering` 的说明。
|
|
995
|
+
const covered = await userMemoryCovering(text);
|
|
996
|
+
if (covered !== null) {
|
|
997
|
+
return 'Already covered by the user memory ' + covered + ', so nothing was recorded. That memory is permanent and always injected — update it with memory_remember (id=' + covered + ', content=...) if the wording needs to change. Do not keep a second copy as a note.';
|
|
998
|
+
}
|
|
999
|
+
// 非法 TTL 不能静默落默认值:调用方会以为"30 天后重查"生效了。
|
|
1000
|
+
if (args && args.ttlDays !== undefined) {
|
|
1001
|
+
const ttl = Number(args.ttlDays);
|
|
1002
|
+
if (!Number.isFinite(ttl) || ttl <= 0)
|
|
1003
|
+
throw new Error('ttlDays must be a positive number of days');
|
|
1004
|
+
}
|
|
1005
|
+
const payload = { text };
|
|
1006
|
+
// 没有 `source`:证据档位由门禁按 `quote` 的逐字核对结果判定,模型无从声明。
|
|
1007
|
+
for (const key of ['title', 'quote', 'boundary', 'layer', 'ttlDays', 'kind']) {
|
|
1008
|
+
if (args && args[key] !== undefined && args[key] !== '')
|
|
1009
|
+
payload[key] = args[key];
|
|
1010
|
+
}
|
|
1011
|
+
// `slot` 是模型面的名字;op 的字段仍是 `key`(同 slot 合并)。`key` 作为旧名兼容一次。
|
|
1012
|
+
const slot = String((args && (args.slot !== undefined ? args.slot : args.key)) || '');
|
|
1013
|
+
if (slot !== '')
|
|
1014
|
+
payload.key = slot;
|
|
1015
|
+
if (identity?.sessionId)
|
|
1016
|
+
payload.sessionId = identity.sessionId;
|
|
1017
|
+
if (identity?.cwd)
|
|
1018
|
+
payload.cwd = identity.cwd;
|
|
1019
|
+
const scene = deps.activeSceneOf ? deps.activeSceneOf(agent) : undefined;
|
|
1020
|
+
if (scene !== undefined)
|
|
1021
|
+
payload.scene = scene;
|
|
1022
|
+
// 门禁拒绝是**正常的业务结果**,不是异常 —— 但工具层只能通过 throw 回话。
|
|
1023
|
+
// 这里统一成一句给模型看的话:首条理由 + 同一轮命中的其余理由。
|
|
1024
|
+
// 一次给全,模型不必「改一道撞一道」(门禁原本串行短路,那是最贵的往返)。
|
|
1025
|
+
const gateError = (r) => new Error(gateErrorText(r, 'failed to record it'));
|
|
1026
|
+
// 没有 preview / 卡片依赖(旧装配、测试):保持原来的待确认路径。
|
|
1027
|
+
const previewOp = noteOps['evolution-preview'];
|
|
1028
|
+
const ask = deps.askMemoryScope;
|
|
1029
|
+
if (!previewOp || !ask) {
|
|
1030
|
+
const r = await opOf(noteOps, 'evolution-learn')(payload);
|
|
1031
|
+
if (!r || r.ok === false)
|
|
1032
|
+
throw gateError(r);
|
|
1033
|
+
return learnReceipt(r, 'none', payload);
|
|
1034
|
+
}
|
|
1035
|
+
// 先只读预演:同时拿到「弹卡后会发生什么」与「不弹卡直接落盘会发生什么」。
|
|
1036
|
+
const preview = await previewOp(payload);
|
|
1037
|
+
if (!preview || preview.ok === false)
|
|
1038
|
+
throw gateError(preview);
|
|
1039
|
+
// 自动确认:不弹卡,模型给的层就是最终层;后台复习也走这条授权。
|
|
1040
|
+
if (preview.autoConfirm === true) {
|
|
1041
|
+
const r = await opOf(noteOps, 'evolution-learn')({ ...payload, autoActive: true });
|
|
1042
|
+
if (!r || r.ok === false)
|
|
1043
|
+
throw gateError(r);
|
|
1044
|
+
return learnReceipt(r, 'auto', payload);
|
|
1045
|
+
}
|
|
1046
|
+
const layerProvided = payload.layer === 'global' || payload.layer === 'workspace';
|
|
1047
|
+
const layer = preview.layer === 'global' ? 'global' : 'workspace';
|
|
1048
|
+
// 合并进一条已生效的记忆:层已经定了,结果也仍是 active,不必再问一次。
|
|
1049
|
+
if (typeof preview.mergeInto === 'string' && preview.mergeInto !== '' && preview.status === 'active') {
|
|
1050
|
+
const r = await opOf(noteOps, 'evolution-learn')(payload);
|
|
1051
|
+
if (!r || r.ok === false)
|
|
1052
|
+
throw new Error(String((r && r.error) || 'failed to record it'));
|
|
1053
|
+
return learnReceipt(r, 'none', payload);
|
|
1054
|
+
}
|
|
1055
|
+
// 其余一律弹卡:新条目、候选合并、冲突都由用户选层;选了就批准并立即生效。
|
|
1056
|
+
const allowed = Array.isArray(preview.allowedLayers)
|
|
1057
|
+
? preview.allowedLayers.filter((l) => l === 'global' || l === 'workspace')
|
|
1058
|
+
: [];
|
|
1059
|
+
const request = {
|
|
1060
|
+
text: String(preview.text || payload.text || ''),
|
|
1061
|
+
...(typeof preview.boundary === 'string' && preview.boundary !== '' ? { boundary: preview.boundary } : {}),
|
|
1062
|
+
// 门禁最终判定的类型(模型给了就用它,否则 `inferKind` 兜底)。卡片据此写明保质期 ——
|
|
1063
|
+
// 用户在决定「要不要这条」时,看不到类型就不知道自己批准的东西会不会过一阵被催复核。
|
|
1064
|
+
...(typeof preview.kind === 'string' ? { kind: preview.kind } : {}),
|
|
1065
|
+
// 只有模型明确给了层才标「推荐」;省略层就是不确定,让用户自己选。
|
|
1066
|
+
...(layerProvided ? { recommended: layer } : {}),
|
|
1067
|
+
allowed: allowed.length > 0 ? allowed : [layer],
|
|
1068
|
+
...(typeof preview.mergeInto === 'string' && preview.mergeInto !== '' ? { mergeInto: preview.mergeInto } : {}),
|
|
1069
|
+
...(Array.isArray(preview.supersedes) && preview.supersedes.length > 0
|
|
1070
|
+
? { supersedes: preview.supersedes.filter((x) => typeof x === 'string') }
|
|
1071
|
+
: {}),
|
|
1072
|
+
...(exec && exec.signal !== undefined ? { signal: exec.signal } : {}),
|
|
1073
|
+
};
|
|
1074
|
+
const choice = await ask(agent, request);
|
|
1075
|
+
// 没有可用卡片(headless / 非 live root / 卡片异常):退回待确认,不丢笔记。
|
|
1076
|
+
if (choice === null) {
|
|
1077
|
+
const r = await opOf(noteOps, 'evolution-learn')(payload);
|
|
1078
|
+
if (!r || r.ok === false)
|
|
1079
|
+
throw new Error(String((r && r.error) || 'failed to record it'));
|
|
1080
|
+
return learnReceipt(r, 'unavailable', payload);
|
|
1081
|
+
}
|
|
1082
|
+
// 用户在卡片里自己写了说法:不写盘,交回模型按他们的话重写,再调一次 learn 弹卡。
|
|
1083
|
+
// 不在同一次工具调用里循环,是因为用户写的可能是一句修改要求(「改成只在写代码时用」),
|
|
1084
|
+
// 而不是可以直接落盘的完整正文。
|
|
1085
|
+
if (choice.choice === 'revise') {
|
|
1086
|
+
return 'Not saved yet. The user wants this note worded differently:\n' +
|
|
1087
|
+
String(choice.custom ?? '') + '\n\n' +
|
|
1088
|
+
'Rewrite the note to match their wording, then call memory_note action=learn again with the revised text. The card will ask them to confirm the new version.';
|
|
1089
|
+
}
|
|
1090
|
+
if (choice.choice === 'skip') {
|
|
1091
|
+
return 'Not saved: the user chose not to add it. Do not save it again unless they ask.';
|
|
1092
|
+
}
|
|
1093
|
+
const r = await opOf(noteOps, 'evolution-learn')({
|
|
1094
|
+
...payload,
|
|
1095
|
+
layer: choice.choice,
|
|
1096
|
+
approved: true,
|
|
1097
|
+
});
|
|
1098
|
+
if (!r || r.ok === false)
|
|
1099
|
+
throw new Error(String((r && r.error) || 'failed to record it'));
|
|
1100
|
+
return learnReceipt(r, 'approved', payload);
|
|
1101
|
+
},
|
|
1102
|
+
}));
|
|
1103
|
+
}
|
|
1104
|
+
/**
|
|
1105
|
+
* 门禁拒绝 → 一句给模型看的话。
|
|
1106
|
+
*
|
|
1107
|
+
* 门禁可能在同一轮命中多个拒绝点(`also`)。逐条列出而不是只报第一条:门禁原本串行
|
|
1108
|
+
* 短路,模型撞一道改一道,每撞一次一轮往返 —— 热路径上那是最贵的一段,而它完全不知道
|
|
1109
|
+
* 后面还挡着什么。一次给全,它就能一轮决定「改哪里」或「这条不值得记,继续正事」。
|
|
1110
|
+
*
|
|
1111
|
+
* 措辞分工明确:`not recorded` 开头的是**别记了**,`refused` 开头的是**改一下再来**。
|
|
1112
|
+
* 模型据此能分辨该放弃还是该修正,不必靠猜。
|
|
1113
|
+
*/
|
|
1114
|
+
function gateErrorText(r, fallback) {
|
|
1115
|
+
const head = String((r && r.error) || fallback);
|
|
1116
|
+
const also = r && Array.isArray(r.also) ? r.also : [];
|
|
1117
|
+
if (also.length === 0)
|
|
1118
|
+
return head;
|
|
1119
|
+
const rest = also.map(function (x) { return '- ' + String((x && x.error) || ''); }).filter(function (s) { return s !== '- '; });
|
|
1120
|
+
if (rest.length === 0)
|
|
1121
|
+
return head;
|
|
1122
|
+
return head + '\n\nAlso rejected for:' + '\n' + rest.join('\n');
|
|
1123
|
+
}
|
|
1124
|
+
/** learn 回执。状态(active / pending)以 learn 的返回为准,`card` 只补充「卡片 / 自动路径那一侧发生了什么」。 */
|
|
1125
|
+
function learnReceipt(r, card, payload) {
|
|
1126
|
+
const parts = ['OK: recorded ' + noteRefOf(String(r.id))];
|
|
1127
|
+
// 回执要给出之后能原样引用的东西:id 与 slot 都在,模型就不必猜 title/quote 哪个是键。
|
|
1128
|
+
if (payload && typeof payload.key === 'string' && payload.key !== '')
|
|
1129
|
+
parts.push('slot: ' + payload.key);
|
|
1130
|
+
// 回执要报落盘值:标题超宽时写入侧会截到 MAX_AUTO_TITLE_WIDTH,回显原串会让模型以为它存下了完整标题。
|
|
1131
|
+
if (payload && typeof payload.title === 'string' && payload.title !== '')
|
|
1132
|
+
parts.push('title: ' + truncateToWidth(payload.title.trim(), MAX_AUTO_TITLE_WIDTH));
|
|
1133
|
+
if (r.merged === true) {
|
|
1134
|
+
parts.push(String(r.status === 'active' ? 'merged into an existing active note' : 'merged into an existing pending note'));
|
|
1135
|
+
}
|
|
1136
|
+
else if (r.status === 'active') {
|
|
1137
|
+
parts.push('saved as active');
|
|
1138
|
+
}
|
|
1139
|
+
else {
|
|
1140
|
+
parts.push('saved as pending review — not injected until the user confirms it on the Memory page');
|
|
1141
|
+
}
|
|
1142
|
+
if (r.merged !== true && typeof r.tier === 'string')
|
|
1143
|
+
parts.push('tier ' + r.tier);
|
|
1144
|
+
// 类型要回显:它是保质期的来源(事实 / 做法 30 天后提醒复核,偏好 / 纠正不过期)。
|
|
1145
|
+
// 模型没传 `kind` 时这里是 `inferKind` 按措辞猜的结果 —— 不回显,它无从知道猜成了什么。
|
|
1146
|
+
if (typeof r.kind === 'string' && r.kind !== '')
|
|
1147
|
+
parts.push('kind ' + r.kind);
|
|
1148
|
+
if (Array.isArray(r.supersedes) && r.supersedes.length)
|
|
1149
|
+
parts.push('replaced ' + r.supersedes.join(', '));
|
|
1150
|
+
if (r.note)
|
|
1151
|
+
parts.push(String(r.note));
|
|
1152
|
+
if (r.pendingReason)
|
|
1153
|
+
parts.push('needs review: ' + String(r.pendingReason));
|
|
1154
|
+
if (card === 'approved' && r.status !== 'active' && r.pendingReason) {
|
|
1155
|
+
parts.push('the card approved it, but it stayed pending for the reason above');
|
|
1156
|
+
}
|
|
1157
|
+
if (card === 'unavailable')
|
|
1158
|
+
parts.push('no interactive card was available, so it stayed pending');
|
|
1159
|
+
if (card === 'pending-conflict')
|
|
1160
|
+
parts.push('it conflicts with a memory the user wrote; they can resolve it on the Memory page');
|
|
1161
|
+
if (card === 'pending')
|
|
1162
|
+
parts.push('it stayed pending for the reason above');
|
|
1163
|
+
// 层要说出来:用户以为"只在这个项目里",实际它进了全局(别的项目也会出现)——
|
|
1164
|
+
// 这个误读比记错内容更难发现。
|
|
1165
|
+
const layerNote = {
|
|
1166
|
+
global: 'applies in every project',
|
|
1167
|
+
workspace: 'applies in this project (visible to other conversations here too)',
|
|
1168
|
+
};
|
|
1169
|
+
const layerLine = typeof r.layer === 'string' ? layerNote[r.layer] : undefined;
|
|
1170
|
+
if (layerLine !== undefined)
|
|
1171
|
+
parts.push(layerLine);
|
|
1172
|
+
return parts.join('; ');
|
|
395
1173
|
}
|