dsh-memory-bond 0.3.0-beta.0 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +6 -7
- package/README.md +125 -91
- package/README.zh-CN.md +122 -92
- package/SECURITY.md +29 -0
- package/dist/audit.js +155 -80
- package/dist/automatic.js +10 -2
- package/dist/client.js +2035 -0
- package/dist/command-scope.js +4 -4
- package/dist/commands.js +15 -9
- package/dist/consolidation-store.js +87 -20
- package/dist/consolidation.js +2 -6
- package/dist/domain.js +8 -4
- package/dist/encoder.js +46 -5
- package/dist/file-import-store.js +120 -0
- package/dist/file-import.js +265 -0
- package/dist/foreground-attempts.js +91 -0
- package/dist/guidance.js +133 -92
- package/dist/host.js +13 -0
- package/dist/index-policy.js +91 -48
- package/dist/index.js +102 -40
- package/dist/knowledge-hooks.js +70 -27
- package/dist/knowledge.js +2 -3
- package/dist/maintenance-store.js +38 -4
- package/dist/maintenance.js +29 -5
- package/dist/personal.js +37 -0
- package/dist/policy.js +45 -47
- package/dist/prompt-copy.js +93 -0
- package/dist/proposal-receipts.js +70 -0
- package/dist/proposal-review.js +656 -0
- package/dist/propose-contract.js +32 -36
- package/dist/question-answers.js +86 -29
- package/dist/retrieval.js +25 -8
- package/dist/scope-narrowing.js +49 -0
- package/dist/search-index.js +93 -13
- package/dist/semantic.js +69 -207
- package/dist/service.js +633 -204
- package/dist/sharing.js +7 -13
- package/dist/sources.js +28 -3
- package/dist/store.js +432 -96
- package/dist/tool-experience.js +87 -0
- package/dist/turn-review-store.js +83 -16
- package/dist/turn-review.js +155 -59
- package/dist/ui.js +128 -26
- package/dist/vector-index.js +69 -33
- package/docs/architecture.zh-CN.md +52 -0
- package/docs/benchmark.zh-CN.md +60 -0
- package/docs/benchmarks/repository-tasks.json +5355 -0
- package/docs/images/bond-memory-principle-en.svg +644 -0
- package/docs/images/bond-memory-principle-zh.svg +644 -0
- package/docs/images/bond-memory-principle.drawio +644 -0
- package/docs/images/memory-settings-en.png +0 -0
- package/docs/images/memory-settings-zh.png +0 -0
- package/docs/images/memory-turn-recalled-en.png +0 -0
- package/docs/images/memory-turn-recalled-zh.png +0 -0
- package/docs/images/memory-turn-saved-en.png +0 -0
- package/docs/images/memory-turn-saved-zh.png +0 -0
- package/docs/media/memory-bond-name-en.gif +0 -0
- package/docs/media/memory-bond-name-en.mp4 +0 -0
- package/docs/media/memory-bond-name-zh.gif +0 -0
- package/docs/media/memory-bond-name-zh.mp4 +0 -0
- package/locale/detail.en.md +5 -1
- package/locale/detail.zh.md +5 -1
- package/locale/en.json +338 -0
- package/locale/zh.json +338 -0
- package/native/embeddings/NOTICE.md +2 -2
- package/package.json +39 -19
- package/scripts/benchmark-bond.mjs +72 -0
- package/scripts/benchmark-conditions.mjs +144 -0
- package/scripts/benchmark-example.mjs +37 -0
- package/scripts/benchmark-scale.mjs +119 -0
- package/scripts/benchmark-scenarios.mjs +57 -0
- package/scripts/benchmark-tasks.mjs +244 -0
- package/src/audit.ts +144 -85
- package/src/automatic.ts +12 -2
- package/src/command-scope.ts +4 -4
- package/src/commands.ts +12 -8
- package/src/consolidation-store.ts +80 -18
- package/src/consolidation.ts +2 -6
- package/src/domain.ts +9 -4
- package/src/encoder.ts +46 -6
- package/src/file-import-store.ts +139 -0
- package/src/file-import.ts +256 -0
- package/src/foreground-attempts.ts +97 -0
- package/src/guidance.ts +138 -102
- package/src/host.ts +22 -2
- package/src/index-policy.ts +93 -46
- package/src/index.ts +87 -43
- package/src/knowledge-hooks.ts +71 -29
- package/src/knowledge.ts +2 -3
- package/src/maintenance-store.ts +37 -4
- package/src/maintenance.ts +25 -5
- package/src/personal.ts +36 -0
- package/src/policy.ts +55 -52
- package/src/prompt-copy.ts +99 -0
- package/src/proposal-receipts.ts +59 -0
- package/src/proposal-review.ts +614 -0
- package/src/propose-contract.ts +31 -35
- package/src/question-answers.ts +99 -29
- package/src/retrieval.ts +26 -9
- package/src/scope-narrowing.ts +58 -0
- package/src/search-index.ts +94 -14
- package/src/semantic.ts +67 -188
- package/src/service.ts +595 -210
- package/src/sharing.ts +7 -14
- package/src/sources.ts +26 -4
- package/src/store.ts +434 -97
- package/src/tool-experience.ts +93 -0
- package/src/turn-review-store.ts +86 -15
- package/src/turn-review.ts +142 -60
- package/src/ui.ts +122 -27
- package/src/vector-index.ts +57 -29
- package/client/index.js +0 -1186
- package/design/dsh-memory-plugin-design.md +0 -46
- package/design/dsh-memory-plugin-evaluation.md +0 -135
- package/design/evaluations/locomo-conv-26-2026-12-03.json +0 -252
- package/design/evaluations/locomo-conv-26-paired-2026-12-03.json +0 -549
- package/design/evaluations/locomo-conv-26-write-replay-2026-12-03.json +0 -289
- package/design/evaluations/project-memory-tasks-2026-12-03.json +0 -1059
- package/design/memory-lifecycle-consolidation.excalidraw +0 -1212
- package/design/memory-lifecycle-consolidation.mobile.excalidraw +0 -1083
- package/design/memory-lifecycle-consolidation.mobile.svg +0 -2
- package/design/memory-lifecycle-consolidation.mobile.zh-CN.excalidraw +0 -1083
- package/design/memory-lifecycle-consolidation.mobile.zh-CN.svg +0 -94
- package/design/memory-lifecycle-consolidation.svg +0 -2
- package/design/memory-lifecycle-consolidation.zh-CN.excalidraw +0 -1212
- package/design/memory-lifecycle-consolidation.zh-CN.svg +0 -94
- package/design/memory-lifecycle.excalidraw +0 -2105
- package/design/memory-lifecycle.mobile.excalidraw +0 -1896
- package/design/memory-lifecycle.mobile.svg +0 -95
- package/design/memory-lifecycle.mobile.zh-CN.excalidraw +0 -1896
- package/design/memory-lifecycle.mobile.zh-CN.svg +0 -97
- package/design/memory-lifecycle.svg +0 -95
- package/design/memory-lifecycle.zh-CN.excalidraw +0 -2105
- package/design/memory-lifecycle.zh-CN.svg +0 -97
- package/native/embeddings/LICENSE +0 -21
- package/native/embeddings/en/model.onnx +0 -4
- package/native/embeddings/en/vocab.txt +0 -30522
- package/native/embeddings/runtime/LICENSE +0 -21
- package/native/embeddings/runtime/ThirdPartyNotices.txt +0 -6156
- package/native/embeddings/runtime/ort-wasm-simd-threaded.mjs +0 -70
- package/native/embeddings/runtime/ort-wasm-simd-threaded.wasm +0 -0
- package/native/embeddings/runtime/ort.wasm.min.mjs +0 -7
- package/native/embeddings/worker.mjs +0 -97
- package/native/embeddings/zh/model.onnx +0 -0
- package/native/embeddings/zh/vocab.txt +0 -21128
package/dist/index-policy.js
CHANGED
|
@@ -1,15 +1,17 @@
|
|
|
1
|
+
import { prompts } from "./prompt-copy.js";
|
|
1
2
|
import { normalizeLabel } from "./personal.js";
|
|
2
3
|
import { searchWords } from "./search-words.js";
|
|
3
4
|
// UTF-8 byte length upper-bounds byte-BPE token count without a model tokenizer.
|
|
4
5
|
export const provisionalLimits = { maxRows: 16, maxTokens: 2048 };
|
|
5
|
-
const searchHint = '所需细节未列出时先查 project_memory_search。';
|
|
6
|
-
const invalidation = '旧索引失效,以当前列出的条目或重新读取的结果为准。';
|
|
7
6
|
const oneline = (s) => s.replace(/[\p{Cc}\p{Zl}\p{Zp}]+/gu, ' ').trim();
|
|
8
7
|
// Common task framing (e.g. "run this in the repository") supplies no topic.
|
|
9
8
|
const generic = new Set('这个 本仓 本项目 仓库 项目 如何 怎么 什么 哪个 一下 帮我 请问 需要 改动 运行 执行 检查 当前 使用 repo repository project run use this that please should when which changes check'.split(' '));
|
|
9
|
+
export function taskTerms(task) {
|
|
10
|
+
return [...new Set(searchWords(normalizeLabel(task.slice(0, 2048))))]
|
|
11
|
+
.filter(word => !generic.has(word) && (word.length > 1 || /^\p{Script=Latin}$/u.test(word))).slice(0, 48);
|
|
12
|
+
}
|
|
10
13
|
export function taskMatcher(task) {
|
|
11
|
-
const terms =
|
|
12
|
-
.filter(word => word.length > 1 && !generic.has(word)).slice(0, 48);
|
|
14
|
+
const terms = typeof task === 'string' ? taskTerms(task) : task;
|
|
13
15
|
if (!terms.length)
|
|
14
16
|
return;
|
|
15
17
|
const patterns = terms.sort((a, b) => b.length - a.length).map(word => {
|
|
@@ -19,39 +21,41 @@ export function taskMatcher(task) {
|
|
|
19
21
|
return new RegExp(patterns.join('|'), 'gu');
|
|
20
22
|
}
|
|
21
23
|
function taskHints(candidates, matcher, keepUnmatched) {
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
.
|
|
24
|
+
const ranked = candidates.map(row => {
|
|
25
|
+
const lazy = row.usage !== 'proactive';
|
|
26
|
+
const labels = [row.semanticTopic, ...(row.keywords ?? []), ...(lazy ? [] : [row.when])];
|
|
27
|
+
const text = normalizeLabel(labels.filter(Boolean).join(' '));
|
|
28
|
+
const matches = [...new Set(matcher ? text.match(matcher) : [])];
|
|
29
|
+
// On-demand metadata may itself contain a value. Only echo terms already in the user's message.
|
|
30
|
+
const trigger = lazy ? matches.join(' ') : oneline([row.subject, row.when].filter(Boolean).join(' '));
|
|
31
|
+
return { row, score: matches.length, trigger };
|
|
32
|
+
}).filter(({ row, score, trigger }) => trigger && (score || (keepUnmatched && row.usage === 'proactive')))
|
|
33
|
+
.sort((a, b) => b.score - a.score || a.row.id.localeCompare(b.row.id));
|
|
34
|
+
const threshold = (ranked[0]?.score ?? 0) * 0.6;
|
|
35
|
+
return ranked.filter(entry => entry.row.usage === 'proactive' || entry.score >= threshold);
|
|
32
36
|
}
|
|
33
|
-
function render(row) {
|
|
34
|
-
const
|
|
37
|
+
function render(row, language) {
|
|
38
|
+
const copy = prompts[language];
|
|
39
|
+
const scopes = [...row.paths, ...(row.hard?.branch ? [copy.branch + row.hard.branch] : [])];
|
|
40
|
+
const topic = oneline(row.semanticTopic ?? '');
|
|
41
|
+
const applicability = oneline(row.when);
|
|
35
42
|
const when = [
|
|
36
|
-
scopes.map(oneline).join(
|
|
37
|
-
oneline(row.subject ?? ''),
|
|
43
|
+
scopes.map(oneline).join(copy.separator),
|
|
44
|
+
oneline(row.subject ?? ''),
|
|
45
|
+
topic && !normalizeLabel(applicability).includes(normalizeLabel(topic)) ? topic : '',
|
|
46
|
+
applicability,
|
|
38
47
|
]
|
|
39
48
|
.filter(Boolean)
|
|
40
49
|
.join(' ');
|
|
41
50
|
const exception = row.localException;
|
|
42
|
-
const
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
';' +
|
|
48
|
-
oneline(exception.scope) +
|
|
49
|
-
')'
|
|
50
|
-
: '';
|
|
51
|
-
return ((when || '长期约定') +
|
|
51
|
+
const path = oneline(row.guidance?.path ?? copy.repo);
|
|
52
|
+
const local = !exception ? '' : language === 'zh'
|
|
53
|
+
? `;本机覆盖 ${path} 的默认项(${oneline(exception.environment)};${oneline(exception.scope)})`
|
|
54
|
+
: ` · local override of ${path} (${oneline(exception.environment)}, ${oneline(exception.scope)})`;
|
|
55
|
+
return ((when || copy.standing) +
|
|
52
56
|
' → ' +
|
|
53
57
|
oneline(row.action) +
|
|
54
|
-
(row.exceptions ?
|
|
58
|
+
(row.exceptions ? copy.except + oneline(row.exceptions) : '') +
|
|
55
59
|
local +
|
|
56
60
|
' [' +
|
|
57
61
|
row.id +
|
|
@@ -66,31 +70,44 @@ export function indexLimits(limits = {}) {
|
|
|
66
70
|
if (!Number.isSafeInteger(maxRows) ||
|
|
67
71
|
maxRows < 2 ||
|
|
68
72
|
!Number.isSafeInteger(maxTokens) ||
|
|
69
|
-
maxTokens < Buffer.byteLength(
|
|
73
|
+
maxTokens < Math.max(...Object.values(prompts).map(copy => Buffer.byteLength(copy.invalid + '\n' + copy.lookup))))
|
|
70
74
|
throw new Error('invalid_index_budget');
|
|
71
75
|
if (limits.overflowHints !== undefined && typeof limits.overflowHints !== 'boolean')
|
|
72
76
|
throw new Error('invalid_index_budget');
|
|
73
77
|
return { maxRows, maxTokens, overflowHints: limits.overflowHints };
|
|
74
78
|
}
|
|
75
|
-
export function buildIndex(rows, revokedIds, limits = {}, currentTask
|
|
79
|
+
export function buildIndex(rows, revokedIds, limits = {}, currentTask, language = 'zh',
|
|
80
|
+
// Rows whose eligibility can change this prompt when other rows are omitted.
|
|
81
|
+
recheck) {
|
|
82
|
+
const copy = prompts[language];
|
|
83
|
+
const searchHint = copy.lookup;
|
|
76
84
|
const { maxRows, maxTokens, overflowHints } = indexLimits(limits);
|
|
77
85
|
const fits = (lines) => lines.length <= maxRows && Buffer.byteLength(lines.join('\n')) <= maxTokens;
|
|
78
86
|
const included = [], overflow = [];
|
|
79
87
|
const onDemand = rows.filter(row => row.usage !== 'proactive' || row.sensitive);
|
|
80
88
|
const lazy = new Set(onDemand);
|
|
81
89
|
overflow.push(...onDemand);
|
|
82
|
-
let lines = [...new Set(revokedIds)].sort().map((id) => '[' + id + ']
|
|
90
|
+
let lines = [...new Set(revokedIds)].sort().map((id) => '[' + id + '] ' + copy.withdrawn);
|
|
83
91
|
if (!fits([...lines, ...(rows.length ? [searchHint] : [])]) && lines.length)
|
|
84
|
-
lines = [
|
|
92
|
+
lines = [copy.invalid];
|
|
85
93
|
if (!fits(lines))
|
|
86
94
|
return { text: '', included, overflow: [...rows] };
|
|
87
95
|
const groups = new Map();
|
|
96
|
+
let proactiveCount = 0;
|
|
88
97
|
for (const row of rows) {
|
|
89
98
|
if (lazy.has(row))
|
|
90
99
|
continue;
|
|
100
|
+
// One more than the row budget proves the complete index cannot fit, even
|
|
101
|
+
// if all remaining unexamined rules have become inapplicable.
|
|
102
|
+
if (++proactiveCount <= maxRows + 1)
|
|
103
|
+
recheck?.add(row);
|
|
91
104
|
const group = groups.get(row.familyId);
|
|
92
|
-
if (group)
|
|
105
|
+
if (group) {
|
|
106
|
+
// Removing a variant can change its family's priority or make it fit.
|
|
107
|
+
recheck?.add(group[0]);
|
|
108
|
+
recheck?.add(row);
|
|
93
109
|
group.push(row);
|
|
110
|
+
}
|
|
94
111
|
else
|
|
95
112
|
groups.set(row.familyId, [row]);
|
|
96
113
|
}
|
|
@@ -100,19 +117,37 @@ export function buildIndex(rows, revokedIds, limits = {}, currentTask) {
|
|
|
100
117
|
group: group.sort((a, b) => a.id.localeCompare(b.id)),
|
|
101
118
|
pinned: group.some((rule) => rule.pinned),
|
|
102
119
|
confirmed: group.reduce((latest, rule) => Math.max(latest, rule.confirmedAt), 0),
|
|
120
|
+
relevance: 0,
|
|
103
121
|
}))
|
|
104
122
|
.sort((a, b) => Number(b.pinned) - Number(a.pinned) ||
|
|
105
123
|
b.confirmed - a.confirmed ||
|
|
106
124
|
a.family.localeCompare(b.family));
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
125
|
+
if (!onDemand.length && lines.length + proactiveCount <= maxRows) {
|
|
126
|
+
const all = ordered.flatMap(entry => entry.group);
|
|
127
|
+
const complete = [...lines, ...all.map(row => render(row, language))];
|
|
128
|
+
if (fits(complete))
|
|
129
|
+
return { text: complete.join('\n'), included: all, overflow };
|
|
130
|
+
}
|
|
131
|
+
const matcher = currentTask?.();
|
|
132
|
+
// When all full agreements fit, keep the stable prompt order across requests.
|
|
133
|
+
// Under pressure, reserve the remaining room for the current task before recency.
|
|
134
|
+
if (matcher && (lines.length + proactiveCount + 1 > maxRows ||
|
|
135
|
+
!fits([...lines, ...ordered.flatMap(({ group }) => group.map(row => render(row, language))), searchHint]))) {
|
|
136
|
+
for (const entry of ordered) {
|
|
137
|
+
for (const row of entry.group) {
|
|
138
|
+
const labels = [row.subject, row.semanticTopic, ...(row.keywords ?? []), row.when, ...row.paths];
|
|
139
|
+
const matched = new Set(normalizeLabel(labels.filter(Boolean).join(' ')).match(matcher) ?? []);
|
|
140
|
+
entry.relevance = Math.max(entry.relevance, matched.size);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
ordered.sort((a, b) => Number(b.pinned) - Number(a.pinned) || b.relevance - a.relevance ||
|
|
144
|
+
b.confirmed - a.confirmed || a.family.localeCompare(b.family));
|
|
111
145
|
}
|
|
112
|
-
const hintCandidates = []
|
|
146
|
+
const hintCandidates = overflowHints === false ? [] :
|
|
147
|
+
onDemand.filter(row => !row.sensitive && !row.localException && row.semanticTopic);
|
|
113
148
|
for (const { group } of ordered) {
|
|
114
|
-
const candidates = group.map(render);
|
|
115
|
-
if (fits([...lines, ...candidates, searchHint])) {
|
|
149
|
+
const candidates = lines.length + group.length + 1 <= maxRows ? group.map(row => render(row, language)) : undefined;
|
|
150
|
+
if (candidates && fits([...lines, ...candidates, searchHint])) {
|
|
116
151
|
included.push(...group);
|
|
117
152
|
lines.push(...candidates);
|
|
118
153
|
}
|
|
@@ -128,13 +163,14 @@ export function buildIndex(rows, revokedIds, limits = {}, currentTask) {
|
|
|
128
163
|
const hints = [];
|
|
129
164
|
let lookup = searchHint;
|
|
130
165
|
const candidates = hintCandidates.length
|
|
131
|
-
? taskHints(hintCandidates,
|
|
132
|
-
for (const row of candidates) {
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
const
|
|
166
|
+
? taskHints(hintCandidates, matcher, overflowHints === true) : [];
|
|
167
|
+
for (const { row, trigger } of candidates) {
|
|
168
|
+
// Even a skipped, oversized hint may set the relevance cutoff for later hints.
|
|
169
|
+
recheck?.add(row);
|
|
170
|
+
// A user-authored trigger can itself quote a revision. Reserve bracketed
|
|
171
|
+
// references on this line for the pointers actually selected by Bond.
|
|
172
|
+
const hint = trigger.replace(/\[(?=mem-[\da-f-]+@\d+\])/giu, '[') + ' [' + row.id + '@' + row.rev + ']';
|
|
173
|
+
const withHint = copy.lookupPrefix + [...hints, hint].join(copy.separator) + copy.lookupEnd + searchHint;
|
|
138
174
|
if (!fits([...lines, withHint]))
|
|
139
175
|
continue;
|
|
140
176
|
hints.push(hint);
|
|
@@ -146,3 +182,10 @@ export function buildIndex(rows, revokedIds, limits = {}, currentTask) {
|
|
|
146
182
|
}
|
|
147
183
|
return { text: lines.join('\n'), included, overflow };
|
|
148
184
|
}
|
|
185
|
+
/** Recognize only Bond's own localized lookup line in an admitted runtime context. */
|
|
186
|
+
export function indexHintRefs(line) {
|
|
187
|
+
const copy = Object.values(prompts).find(copy => line.startsWith(copy.lookupPrefix) && line.endsWith(copy.lookupEnd + copy.lookup));
|
|
188
|
+
if (!copy)
|
|
189
|
+
return [];
|
|
190
|
+
return Array.from(line.matchAll(/\[(mem-[\da-f-]+)@(\d+)\]/giu), m => ({ id: m[1], rev: Number(m[2]) }));
|
|
191
|
+
}
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
import { createRequire } from 'node:module';
|
|
2
2
|
import { isAbsolute } from 'node:path';
|
|
3
3
|
import { ProjectMemory, indexName, publicRule } from "./service.js";
|
|
4
|
-
import { indexLimits
|
|
4
|
+
import { indexLimits } from "./policy.js";
|
|
5
|
+
import { prompts } from "./prompt-copy.js";
|
|
6
|
+
import { proposalContract } from "./propose-contract.js";
|
|
7
|
+
import { reviewProposals } from "./proposal-review.js";
|
|
5
8
|
import { registerMaintenance } from "./maintenance.js";
|
|
6
9
|
import { registerKnowledge } from "./knowledge.js";
|
|
7
10
|
import { newSearchTrace } from "./retrieval.js";
|
|
@@ -11,6 +14,7 @@ import { registerConsolidation } from "./consolidation.js";
|
|
|
11
14
|
import { registerCommands, parseRef } from "./commands.js";
|
|
12
15
|
import { registerUI } from "./ui.js";
|
|
13
16
|
import { StoreError } from "./store.js";
|
|
17
|
+
import { registerConditionalTool } from "./host.js";
|
|
14
18
|
export const name = 'dsh-memory-bond';
|
|
15
19
|
export const inject = ['agents', 'workingDirectory', 'tools', 'systemPrompt', 'llm'];
|
|
16
20
|
const output = {
|
|
@@ -38,11 +42,20 @@ export function toolErrorStatus(error) {
|
|
|
38
42
|
return /^[a-z_]+$/.test(code) ? code : 'storage_or_validation_error';
|
|
39
43
|
}
|
|
40
44
|
export function apply(ctx, config = {}) {
|
|
45
|
+
function unavailable(missing) {
|
|
46
|
+
ctx.logger.warn('Memory Bond needs ' + missing + '. See /project-memory status.');
|
|
47
|
+
ctx.inject(['commands'], (c) => c.commands.register({
|
|
48
|
+
name: 'project-memory', description: 'Report host compatibility', recordInput: false, input: { hint: 'status' },
|
|
49
|
+
async handler({ rawInput }) {
|
|
50
|
+
return { kind: rawInput.trim() === 'status' ? 'success' : 'error',
|
|
51
|
+
text: JSON.stringify({ status: 'incompatible_host', missing }) };
|
|
52
|
+
},
|
|
53
|
+
}));
|
|
54
|
+
}
|
|
41
55
|
const profileContext = ctx.get('profileContext');
|
|
42
56
|
const profile = profileContext?.dir;
|
|
43
57
|
if (typeof profile !== 'string' || !isAbsolute(profile)) {
|
|
44
|
-
|
|
45
|
-
return;
|
|
58
|
+
return unavailable('absolute profileContext.dir');
|
|
46
59
|
}
|
|
47
60
|
let isAgentLoopRequest;
|
|
48
61
|
let reviewSdk;
|
|
@@ -53,21 +66,36 @@ export function apply(ctx, config = {}) {
|
|
|
53
66
|
// plugin's own file when it is absent can silently resolve a different, wrong copy instead of
|
|
54
67
|
// failing loudly - worse than disabling the plugin, so this composition is declined outright.
|
|
55
68
|
if (!profileContext?.installAnchor) {
|
|
56
|
-
|
|
57
|
-
return;
|
|
69
|
+
return unavailable('profileContext.installAnchor');
|
|
58
70
|
}
|
|
71
|
+
if (typeof ctx.agents.get !== 'function')
|
|
72
|
+
return unavailable('agents.get');
|
|
73
|
+
if (typeof ctx.workingDirectory.get !== 'function')
|
|
74
|
+
return unavailable('workingDirectory.get');
|
|
75
|
+
if (typeof ctx.tools.register !== 'function' || typeof ctx.tools.guard !== 'function')
|
|
76
|
+
return unavailable('tools.register and tools.guard');
|
|
77
|
+
if (typeof ctx.systemPrompt.section !== 'function' || typeof ctx.systemPrompt.context !== 'function')
|
|
78
|
+
return unavailable('systemPrompt.section and systemPrompt.context');
|
|
59
79
|
try {
|
|
60
80
|
const hostRequire = createRequire(profileContext.installAnchor);
|
|
61
81
|
const llm = hostRequire('@deepseek-ai/dsh-llm');
|
|
82
|
+
if (typeof llm?.isAgentLoopRequest !== 'function')
|
|
83
|
+
return unavailable('@deepseek-ai/dsh-llm.isAgentLoopRequest');
|
|
62
84
|
isAgentLoopRequest = llm.isAgentLoopRequest;
|
|
63
|
-
|
|
64
|
-
|
|
85
|
+
if (typeof llm.createUserMessage === 'function' && typeof llm.BlockAssembler === 'function' &&
|
|
86
|
+
typeof llm.BlockAssembler.prototype?.push === 'function' && typeof llm.BlockAssembler.prototype?.blocks === 'function')
|
|
87
|
+
reviewSdk = llm;
|
|
88
|
+
const sessions = hostRequire('@deepseek-ai/dsh-session');
|
|
89
|
+
if (typeof sessions?.appendPluginRecord !== 'function')
|
|
90
|
+
return unavailable('@deepseek-ai/dsh-session.appendPluginRecord');
|
|
91
|
+
appendPluginRecord = sessions.appendPluginRecord;
|
|
65
92
|
}
|
|
66
|
-
catch
|
|
67
|
-
|
|
68
|
-
(error instanceof Error ? error.message : String(error)));
|
|
69
|
-
return;
|
|
93
|
+
catch {
|
|
94
|
+
return unavailable('@deepseek-ai/dsh-llm and @deepseek-ai/dsh-session at profileContext.installAnchor');
|
|
70
95
|
}
|
|
96
|
+
const hostIssues = reviewSdk ? [] : ['model_review_sdk_unavailable'];
|
|
97
|
+
if (hostIssues.length)
|
|
98
|
+
ctx.logger.warn('Memory Bond automatic writes and background review need the host model SDK. See /project-memory status.');
|
|
71
99
|
const memory = new ProjectMemory(ctx, profile, { ...config, ...indexLimits(config) }, appendPluginRecord);
|
|
72
100
|
ctx.on('agent/inbox/claimed', ({ agent, message, turn }) => {
|
|
73
101
|
try {
|
|
@@ -76,12 +104,12 @@ export function apply(ctx, config = {}) {
|
|
|
76
104
|
catch { /* A failed scope read leaves the ordinary search hint available. */ }
|
|
77
105
|
});
|
|
78
106
|
memory.retrieval.vectors.start();
|
|
79
|
-
const stopReview = registerTurnReview(memory, reviewSdk);
|
|
80
|
-
const stopConsolidation = registerConsolidation(memory, reviewSdk);
|
|
107
|
+
const stopReview = reviewSdk && registerTurnReview(memory, reviewSdk);
|
|
108
|
+
const stopConsolidation = reviewSdk && registerConsolidation(memory, reviewSdk);
|
|
81
109
|
const stopMaintenance = registerMaintenance(ctx, memory);
|
|
82
110
|
ctx.effect(() => async () => {
|
|
83
|
-
stopReview();
|
|
84
|
-
await stopConsolidation();
|
|
111
|
+
stopReview?.();
|
|
112
|
+
await stopConsolidation?.();
|
|
85
113
|
await stopMaintenance();
|
|
86
114
|
memory.retrieval.close();
|
|
87
115
|
memory.store.close();
|
|
@@ -132,9 +160,10 @@ export function apply(ctx, config = {}) {
|
|
|
132
160
|
name: 'project-memory:instructions',
|
|
133
161
|
order: 20,
|
|
134
162
|
interpolate: false,
|
|
135
|
-
text: (
|
|
136
|
-
|
|
137
|
-
:
|
|
163
|
+
text: ({ agent } = {}) => {
|
|
164
|
+
const copy = prompts[memory.promptLanguage(agent)];
|
|
165
|
+
return memory.assistantGeneration() === undefined ? copy.disabled : copy.system;
|
|
166
|
+
},
|
|
138
167
|
});
|
|
139
168
|
ctx.systemPrompt.context({
|
|
140
169
|
name: indexName,
|
|
@@ -154,8 +183,8 @@ export function apply(ctx, config = {}) {
|
|
|
154
183
|
}
|
|
155
184
|
},
|
|
156
185
|
});
|
|
157
|
-
const { expanded, shownSearchRows } = registerAudit(memory, isAgentLoopRequest);
|
|
158
|
-
registerKnowledge(ctx, memory, expanded);
|
|
186
|
+
const { expanded, shownSearchRows, executed, blocked, wrote } = registerAudit(memory, isAgentLoopRequest);
|
|
187
|
+
registerKnowledge(ctx, memory, expanded, { executed, blocked });
|
|
159
188
|
const emptySearches = new WeakMap();
|
|
160
189
|
function searchAvailable(agent, generation) {
|
|
161
190
|
const previous = emptySearches.get(agent);
|
|
@@ -175,8 +204,8 @@ export function apply(ctx, config = {}) {
|
|
|
175
204
|
emptySearches.delete(agent);
|
|
176
205
|
return true;
|
|
177
206
|
}
|
|
178
|
-
function tool(name, contract, run, available) {
|
|
179
|
-
ctx
|
|
207
|
+
function tool(name, contract, run, available, visibleWithoutAgent = true) {
|
|
208
|
+
registerConditionalTool(ctx, {
|
|
180
209
|
name,
|
|
181
210
|
...contract,
|
|
182
211
|
output,
|
|
@@ -187,22 +216,52 @@ export function apply(ctx, config = {}) {
|
|
|
187
216
|
const generation = memory.assistantGeneration();
|
|
188
217
|
if (generation === undefined)
|
|
189
218
|
return JSON.stringify({ status: 'memory_disabled' });
|
|
190
|
-
const result = await run(args, exec.agent, exec.callId, generation);
|
|
219
|
+
const result = await run(args, exec.agent, exec.callId, generation, exec.signal);
|
|
191
220
|
return JSON.stringify(memory.assistantGeneration() === generation ? result : { status: 'memory_disabled' });
|
|
192
221
|
}
|
|
193
222
|
catch (error) {
|
|
194
223
|
return JSON.stringify({ status: toolErrorStatus(error) });
|
|
195
224
|
}
|
|
196
225
|
},
|
|
197
|
-
},
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
226
|
+
}, agent => {
|
|
227
|
+
const generation = memory.assistantGeneration();
|
|
228
|
+
return generation !== undefined && (!available || (agent ? available(agent, generation) : visibleWithoutAgent));
|
|
229
|
+
});
|
|
201
230
|
}
|
|
202
|
-
|
|
231
|
+
const toolLanguage = memory.promptLanguage();
|
|
232
|
+
const toolCopy = prompts[toolLanguage];
|
|
233
|
+
tool('project_memory_propose', proposalContract(toolLanguage), async (args, agent, call, generation, signal) => {
|
|
234
|
+
const initial = memory.domain(agent);
|
|
235
|
+
const receipt = await reviewProposals(memory, agent, args, reviewSdk, signal);
|
|
236
|
+
const current = memory.domain(agent);
|
|
237
|
+
if (memory.assistantGeneration() !== generation)
|
|
238
|
+
return { status: 'memory_disabled' };
|
|
239
|
+
if (!initial || !current || current.id !== initial.id || current.root !== initial.root || current.cwd !== initial.cwd ||
|
|
240
|
+
ctx.agents.get(agent.id) !== agent)
|
|
241
|
+
return { status: 'unavailable' };
|
|
242
|
+
try {
|
|
243
|
+
wrote(agent, current, call, receipt.results);
|
|
244
|
+
}
|
|
245
|
+
catch (error) {
|
|
246
|
+
ctx.logger.warn('未能记录本次记忆回执的投递凭据:' + String(error));
|
|
247
|
+
}
|
|
248
|
+
return receipt;
|
|
249
|
+
});
|
|
250
|
+
tool('project_memory_experience', {
|
|
251
|
+
description: toolCopy.experience,
|
|
252
|
+
parameters: parameters({ callId: string, topic: string, action: string }, ['callId', 'topic', 'action']),
|
|
253
|
+
}, (args, agent, _call, generation) => memory.proposeExperience(agent, args, generation), (agent, generation) => {
|
|
254
|
+
try {
|
|
255
|
+
return !!memory.experienceSource(agent, generation);
|
|
256
|
+
}
|
|
257
|
+
catch {
|
|
258
|
+
return false;
|
|
259
|
+
}
|
|
260
|
+
}, false);
|
|
203
261
|
tool('project_memory_search', {
|
|
204
|
-
description:
|
|
205
|
-
parameters: parameters({ query: string, alternateQuery: string, subject: string, topic: string,
|
|
262
|
+
description: toolCopy.search,
|
|
263
|
+
parameters: parameters({ query: string, alternateQuery: string, subject: string, topic: string, limit: { type: 'integer', minimum: 1, maximum: 40 },
|
|
264
|
+
scope: { type: 'string', enum: ['global', 'project'] },
|
|
206
265
|
mode: { type: 'string', enum: ['hybrid', 'keyword', 'semantic'] } }, ['query']),
|
|
207
266
|
}, async (args, agent, call, generation) => {
|
|
208
267
|
const timing = timingFor(agent.session, call);
|
|
@@ -213,13 +272,15 @@ export function apply(ctx, config = {}) {
|
|
|
213
272
|
if (!d)
|
|
214
273
|
return { rules: [] };
|
|
215
274
|
const context = searchContext(agent, d, generation);
|
|
216
|
-
const { subject, topic, scope } = args;
|
|
275
|
+
const { subject, topic, scope, limit = 6 } = args;
|
|
276
|
+
if (typeof limit !== 'number' || !Number.isInteger(limit) || limit < 1 || limit > 40)
|
|
277
|
+
throw new StoreError('invalid_input');
|
|
217
278
|
if (scope !== undefined && scope !== 'global' && scope !== 'project')
|
|
218
279
|
throw new StoreError('invalid_input');
|
|
219
280
|
const rules = await memory.search(agent, args.query, args.mode, { subject, topic, scope: scope === 'global' ? 'profile' : scope, alternateQuery: args.alternateQuery }, trace);
|
|
220
281
|
if (memory.assistantGeneration() !== generation || memory.domain(agent)?.id !== d.id)
|
|
221
282
|
return { rules: [] };
|
|
222
|
-
const rows = rules.slice(0,
|
|
283
|
+
const rows = rules.slice(0, limit);
|
|
223
284
|
if (trace.match === 'empty_scope' && context)
|
|
224
285
|
emptySearches.set(agent, context);
|
|
225
286
|
const seen = shownSearchRows(agent, context);
|
|
@@ -232,10 +293,11 @@ export function apply(ctx, config = {}) {
|
|
|
232
293
|
}
|
|
233
294
|
return trace.match === 'exact_id' ? full : { id: rule.id, rev: rule.rev, alreadyShown: true };
|
|
234
295
|
});
|
|
235
|
-
expanded(agent, d, call, rows
|
|
296
|
+
expanded(agent, d, call, rows, context);
|
|
236
297
|
memory.store.audit(d.id, agent.id, 'search', { call, agent: agent.id, outcome: rows.length });
|
|
237
298
|
return { rules: results, match: trace.match, coverage: trace.coverage,
|
|
238
|
-
...(
|
|
299
|
+
...(rules.length > limit && { totalMatches: rules.length }),
|
|
300
|
+
...(trace.match === 'empty_scope' && { guidance: prompts[memory.promptLanguage(agent)].empty }),
|
|
239
301
|
...(noNewEvidence ? { progress: 'no_new_evidence' } : {}) };
|
|
240
302
|
}
|
|
241
303
|
finally {
|
|
@@ -265,10 +327,10 @@ export function apply(ctx, config = {}) {
|
|
|
265
327
|
if ('id' in row && row.id !== undefined) {
|
|
266
328
|
const owner = memory.owner(agent, d, row.id);
|
|
267
329
|
const current = owner && memory.current(owner, row.id, row.rev);
|
|
268
|
-
if (!current || (
|
|
330
|
+
if (!current || !memory.canPublishEvidence(current, row))
|
|
269
331
|
return { status: 'not_found' };
|
|
270
|
-
if (!source)
|
|
271
|
-
expanded(agent, d, call, [
|
|
332
|
+
if (!source && 'action' in row)
|
|
333
|
+
expanded(agent, d, call, [row]);
|
|
272
334
|
memory.store.audit(owner.id, agent.id, source ? 'expand' : 'read', {
|
|
273
335
|
id: row.id,
|
|
274
336
|
rev: row.rev,
|
|
@@ -279,9 +341,9 @@ export function apply(ctx, config = {}) {
|
|
|
279
341
|
return 'scope' in row ? modelRule(row) : row;
|
|
280
342
|
});
|
|
281
343
|
}
|
|
282
|
-
readTool('project_memory_read',
|
|
283
|
-
readTool('project_memory_source',
|
|
284
|
-
ctx.inject(['commands'], (c) => registerCommands(c, memory));
|
|
344
|
+
readTool('project_memory_read', toolCopy.read);
|
|
345
|
+
readTool('project_memory_source', toolCopy.source);
|
|
346
|
+
ctx.inject(['commands'], (c) => registerCommands(c, memory, hostIssues));
|
|
285
347
|
registerUI(ctx, memory);
|
|
286
348
|
ctx.provide('projectMemoryReady', true);
|
|
287
349
|
}
|