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/src/host.ts
CHANGED
|
@@ -21,7 +21,7 @@ export interface HostEvent {
|
|
|
21
21
|
data: Message & {
|
|
22
22
|
turn?: number
|
|
23
23
|
step?: number
|
|
24
|
-
refs?: { id: string; rev: number }[]
|
|
24
|
+
refs?: { id: string; rev: number; bodyDigest: string }[]
|
|
25
25
|
callId?: string
|
|
26
26
|
message?: Message & { isError?: boolean; toolCallId?: string }
|
|
27
27
|
name?: string
|
|
@@ -53,6 +53,7 @@ export interface Agent {
|
|
|
53
53
|
export interface Execution {
|
|
54
54
|
name: string
|
|
55
55
|
agent?: Agent
|
|
56
|
+
signal?: AbortSignal
|
|
56
57
|
callId: string
|
|
57
58
|
arguments: unknown
|
|
58
59
|
}
|
|
@@ -71,7 +72,11 @@ export interface Host {
|
|
|
71
72
|
agents: { get(id: string): Agent | undefined }
|
|
72
73
|
workingDirectory: { get(session: Session): string; defaultDirectory?: string }
|
|
73
74
|
systemPrompt: { section(value: object): void; context(value: object): void }
|
|
74
|
-
tools: {
|
|
75
|
+
tools: {
|
|
76
|
+
register(value: object, options?: { when: (step?: { agent: Agent }) => boolean }): void
|
|
77
|
+
include?(registry: { get(name: string, scope?: object): object | undefined; getAll(scope?: object): object[] }): void
|
|
78
|
+
guard(fn: (exec: Execution) => string | undefined): unknown
|
|
79
|
+
}
|
|
75
80
|
// Cordis hook and optional service signatures vary by installed composition.
|
|
76
81
|
emit(name: string, ...args: unknown[]): void
|
|
77
82
|
on(name: string, listener: (...args: any[]) => any, options?: object): void
|
|
@@ -82,7 +87,22 @@ export interface Host {
|
|
|
82
87
|
effect(dispose: () => () => void): void
|
|
83
88
|
logger: { warn(message: string): void }
|
|
84
89
|
}
|
|
90
|
+
|
|
91
|
+
// 0.2.2 freezes registrations using a per-step predicate. 0.2.3 asks a
|
|
92
|
+
// registry for the definitions visible in an Agent (or preset) scope.
|
|
93
|
+
export function registerConditionalTool<T extends { name: string }>(ctx: Host, tool: T, visible: (agent?: Agent) => boolean) {
|
|
94
|
+
if (typeof ctx.tools.include !== 'function') {
|
|
95
|
+
ctx.tools.register(tool, { when: step => visible(step?.agent) })
|
|
96
|
+
return
|
|
97
|
+
}
|
|
98
|
+
const available = (scope?: object) => visible(scope && 'session' in scope && 'id' in scope ? scope as Agent : undefined)
|
|
99
|
+
ctx.tools.include({
|
|
100
|
+
get: (name, scope) => name === tool.name && available(scope) ? tool : undefined,
|
|
101
|
+
getAll: scope => available(scope) ? [tool] : [],
|
|
102
|
+
})
|
|
103
|
+
}
|
|
85
104
|
export interface PluginConfig {
|
|
105
|
+
promptLanguage?: 'en' | 'zh'
|
|
86
106
|
nonGitRoots?: string[]
|
|
87
107
|
maxRows?: number
|
|
88
108
|
overflowHints?: boolean
|
package/src/index-policy.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { prompts, type PromptLanguage } from './prompt-copy.ts'
|
|
1
2
|
import { normalizeLabel } from './personal.ts'
|
|
2
3
|
import { searchWords } from './search-words.ts'
|
|
3
4
|
|
|
@@ -29,16 +30,18 @@ export interface IndexLimits {
|
|
|
29
30
|
}
|
|
30
31
|
// UTF-8 byte length upper-bounds byte-BPE token count without a model tokenizer.
|
|
31
32
|
export const provisionalLimits = { maxRows: 16, maxTokens: 2048 } as const
|
|
32
|
-
const searchHint = '所需细节未列出时先查 project_memory_search。'
|
|
33
|
-
const invalidation = '旧索引失效,以当前列出的条目或重新读取的结果为准。'
|
|
34
33
|
const oneline = (s: string): string => s.replace(/[\p{Cc}\p{Zl}\p{Zp}]+/gu, ' ').trim()
|
|
35
34
|
|
|
36
35
|
// Common task framing (e.g. "run this in the repository") supplies no topic.
|
|
37
36
|
const generic = new Set('这个 本仓 本项目 仓库 项目 如何 怎么 什么 哪个 一下 帮我 请问 需要 改动 运行 执行 检查 当前 使用 repo repository project run use this that please should when which changes check'.split(' '))
|
|
38
37
|
|
|
39
|
-
export function
|
|
40
|
-
|
|
41
|
-
.filter(word => word.length > 1
|
|
38
|
+
export function taskTerms(task: string) {
|
|
39
|
+
return [...new Set(searchWords(normalizeLabel(task.slice(0, 2048))))]
|
|
40
|
+
.filter(word => !generic.has(word) && (word.length > 1 || /^\p{Script=Latin}$/u.test(word))).slice(0, 48)
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function taskMatcher(task: string | string[]) {
|
|
44
|
+
const terms = typeof task === 'string' ? taskTerms(task) : task
|
|
42
45
|
if (!terms.length) return
|
|
43
46
|
const patterns = terms.sort((a, b) => b.length - a.length).map(word => {
|
|
44
47
|
const literal = word.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&')
|
|
@@ -48,40 +51,43 @@ export function taskMatcher(task: string) {
|
|
|
48
51
|
}
|
|
49
52
|
|
|
50
53
|
function taskHints<T extends IndexRule>(candidates: T[], matcher: RegExp | undefined, keepUnmatched: boolean) {
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
const
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
54
|
+
const ranked = candidates.map(row => {
|
|
55
|
+
const lazy = row.usage !== 'proactive'
|
|
56
|
+
const labels = [row.semanticTopic, ...(row.keywords ?? []), ...(lazy ? [] : [row.when])]
|
|
57
|
+
const text = normalizeLabel(labels.filter(Boolean).join(' '))
|
|
58
|
+
const matches = [...new Set(matcher ? text.match(matcher) : [])]
|
|
59
|
+
// On-demand metadata may itself contain a value. Only echo terms already in the user's message.
|
|
60
|
+
const trigger = lazy ? matches.join(' ') : oneline([row.subject, row.when].filter(Boolean).join(' '))
|
|
61
|
+
return { row, score: matches.length, trigger }
|
|
62
|
+
}).filter(({ row, score, trigger }) => trigger && (score || (keepUnmatched && row.usage === 'proactive')))
|
|
63
|
+
.sort((a, b) => b.score - a.score || a.row.id.localeCompare(b.row.id))
|
|
64
|
+
const threshold = (ranked[0]?.score ?? 0) * 0.6
|
|
65
|
+
return ranked.filter(entry => entry.row.usage === 'proactive' || entry.score >= threshold)
|
|
60
66
|
}
|
|
61
67
|
|
|
62
|
-
function render(row: IndexRule): string {
|
|
63
|
-
const
|
|
68
|
+
function render(row: IndexRule, language: PromptLanguage): string {
|
|
69
|
+
const copy = prompts[language]
|
|
70
|
+
const scopes = [...row.paths, ...(row.hard?.branch ? [copy.branch + row.hard.branch] : [])]
|
|
71
|
+
const topic = oneline(row.semanticTopic ?? '')
|
|
72
|
+
const applicability = oneline(row.when)
|
|
64
73
|
const when = [
|
|
65
|
-
scopes.map(oneline).join(
|
|
66
|
-
oneline(row.subject ?? ''),
|
|
74
|
+
scopes.map(oneline).join(copy.separator),
|
|
75
|
+
oneline(row.subject ?? ''),
|
|
76
|
+
topic && !normalizeLabel(applicability).includes(normalizeLabel(topic)) ? topic : '',
|
|
77
|
+
applicability,
|
|
67
78
|
]
|
|
68
79
|
.filter(Boolean)
|
|
69
80
|
.join(' ')
|
|
70
81
|
const exception = row.localException
|
|
71
|
-
const
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
oneline(exception.environment) +
|
|
76
|
-
';' +
|
|
77
|
-
oneline(exception.scope) +
|
|
78
|
-
')'
|
|
79
|
-
: ''
|
|
82
|
+
const path = oneline(row.guidance?.path ?? copy.repo)
|
|
83
|
+
const local = !exception ? '' : language === 'zh'
|
|
84
|
+
? `;本机覆盖 ${path} 的默认项(${oneline(exception.environment)};${oneline(exception.scope)})`
|
|
85
|
+
: ` · local override of ${path} (${oneline(exception.environment)}, ${oneline(exception.scope)})`
|
|
80
86
|
return (
|
|
81
|
-
(when ||
|
|
87
|
+
(when || copy.standing) +
|
|
82
88
|
' → ' +
|
|
83
89
|
oneline(row.action) +
|
|
84
|
-
(row.exceptions ?
|
|
90
|
+
(row.exceptions ? copy.except + oneline(row.exceptions) : '') +
|
|
85
91
|
local +
|
|
86
92
|
' [' +
|
|
87
93
|
row.id +
|
|
@@ -99,7 +105,7 @@ export function indexLimits(limits: IndexLimits = {}) {
|
|
|
99
105
|
!Number.isSafeInteger(maxRows) ||
|
|
100
106
|
maxRows < 2 ||
|
|
101
107
|
!Number.isSafeInteger(maxTokens) ||
|
|
102
|
-
maxTokens < Buffer.byteLength(
|
|
108
|
+
maxTokens < Math.max(...Object.values(prompts).map(copy => Buffer.byteLength(copy.invalid + '\n' + copy.lookup)))
|
|
103
109
|
)
|
|
104
110
|
throw new Error('invalid_index_budget')
|
|
105
111
|
if (limits.overflowHints !== undefined && typeof limits.overflowHints !== 'boolean')
|
|
@@ -112,7 +118,12 @@ export function buildIndex<T extends IndexRule>(
|
|
|
112
118
|
revokedIds: readonly string[],
|
|
113
119
|
limits: IndexLimits = {},
|
|
114
120
|
currentTask?: () => RegExp | undefined,
|
|
121
|
+
language: PromptLanguage = 'zh',
|
|
122
|
+
// Rows whose eligibility can change this prompt when other rows are omitted.
|
|
123
|
+
recheck?: Set<T>,
|
|
115
124
|
) {
|
|
125
|
+
const copy = prompts[language]
|
|
126
|
+
const searchHint = copy.lookup
|
|
116
127
|
const { maxRows, maxTokens, overflowHints } = indexLimits(limits)
|
|
117
128
|
const fits = (lines: string[]): boolean =>
|
|
118
129
|
lines.length <= maxRows && Buffer.byteLength(lines.join('\n')) <= maxTokens
|
|
@@ -121,14 +132,23 @@ export function buildIndex<T extends IndexRule>(
|
|
|
121
132
|
const onDemand = rows.filter(row => row.usage !== 'proactive' || row.sensitive)
|
|
122
133
|
const lazy = new Set(onDemand)
|
|
123
134
|
overflow.push(...onDemand)
|
|
124
|
-
let lines = [...new Set(revokedIds)].sort().map((id) => '[' + id + ']
|
|
125
|
-
if (!fits([...lines, ...(rows.length ? [searchHint] : [])]) && lines.length) lines = [
|
|
135
|
+
let lines = [...new Set(revokedIds)].sort().map((id) => '[' + id + '] ' + copy.withdrawn)
|
|
136
|
+
if (!fits([...lines, ...(rows.length ? [searchHint] : [])]) && lines.length) lines = [copy.invalid]
|
|
126
137
|
if (!fits(lines)) return { text: '', included, overflow: [...rows] }
|
|
127
138
|
const groups = new Map<string, T[]>()
|
|
139
|
+
let proactiveCount = 0
|
|
128
140
|
for (const row of rows) {
|
|
129
141
|
if (lazy.has(row)) continue
|
|
142
|
+
// One more than the row budget proves the complete index cannot fit, even
|
|
143
|
+
// if all remaining unexamined rules have become inapplicable.
|
|
144
|
+
if (++proactiveCount <= maxRows + 1) recheck?.add(row)
|
|
130
145
|
const group = groups.get(row.familyId)
|
|
131
|
-
if (group)
|
|
146
|
+
if (group) {
|
|
147
|
+
// Removing a variant can change its family's priority or make it fit.
|
|
148
|
+
recheck?.add(group[0])
|
|
149
|
+
recheck?.add(row)
|
|
150
|
+
group.push(row)
|
|
151
|
+
}
|
|
132
152
|
else groups.set(row.familyId, [row])
|
|
133
153
|
}
|
|
134
154
|
const ordered = [...groups]
|
|
@@ -137,6 +157,7 @@ export function buildIndex<T extends IndexRule>(
|
|
|
137
157
|
group: group.sort((a, b) => a.id.localeCompare(b.id)),
|
|
138
158
|
pinned: group.some((rule) => rule.pinned),
|
|
139
159
|
confirmed: group.reduce((latest, rule) => Math.max(latest, rule.confirmedAt), 0),
|
|
160
|
+
relevance: 0,
|
|
140
161
|
}))
|
|
141
162
|
.sort(
|
|
142
163
|
(a, b) =>
|
|
@@ -144,15 +165,31 @@ export function buildIndex<T extends IndexRule>(
|
|
|
144
165
|
b.confirmed - a.confirmed ||
|
|
145
166
|
a.family.localeCompare(b.family),
|
|
146
167
|
)
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
return { text: complete.join('\n'), included: all, overflow }
|
|
168
|
+
if (!onDemand.length && lines.length + proactiveCount <= maxRows) {
|
|
169
|
+
const all = ordered.flatMap(entry => entry.group)
|
|
170
|
+
const complete = [...lines, ...all.map(row => render(row, language))]
|
|
171
|
+
if (fits(complete)) return { text: complete.join('\n'), included: all, overflow }
|
|
151
172
|
}
|
|
152
|
-
const
|
|
173
|
+
const matcher = currentTask?.()
|
|
174
|
+
// When all full agreements fit, keep the stable prompt order across requests.
|
|
175
|
+
// Under pressure, reserve the remaining room for the current task before recency.
|
|
176
|
+
if (matcher && (lines.length + proactiveCount + 1 > maxRows ||
|
|
177
|
+
!fits([...lines, ...ordered.flatMap(({group}) => group.map(row => render(row, language))), searchHint]))) {
|
|
178
|
+
for (const entry of ordered) {
|
|
179
|
+
for (const row of entry.group) {
|
|
180
|
+
const labels = [row.subject, row.semanticTopic, ...(row.keywords ?? []), row.when, ...row.paths]
|
|
181
|
+
const matched = new Set(normalizeLabel(labels.filter(Boolean).join(' ')).match(matcher) ?? [])
|
|
182
|
+
entry.relevance = Math.max(entry.relevance, matched.size)
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
ordered.sort((a, b) => Number(b.pinned) - Number(a.pinned) || b.relevance - a.relevance ||
|
|
186
|
+
b.confirmed - a.confirmed || a.family.localeCompare(b.family))
|
|
187
|
+
}
|
|
188
|
+
const hintCandidates = overflowHints === false ? [] :
|
|
189
|
+
onDemand.filter(row => !row.sensitive && !row.localException && row.semanticTopic)
|
|
153
190
|
for (const { group } of ordered) {
|
|
154
|
-
const candidates = group.map(render)
|
|
155
|
-
if (fits([...lines, ...candidates, searchHint])) {
|
|
191
|
+
const candidates = lines.length + group.length + 1 <= maxRows ? group.map(row => render(row, language)) : undefined
|
|
192
|
+
if (candidates && fits([...lines, ...candidates, searchHint])) {
|
|
156
193
|
included.push(...group)
|
|
157
194
|
lines.push(...candidates)
|
|
158
195
|
} else {
|
|
@@ -167,12 +204,14 @@ export function buildIndex<T extends IndexRule>(
|
|
|
167
204
|
const hints: string[] = []
|
|
168
205
|
let lookup = searchHint
|
|
169
206
|
const candidates = hintCandidates.length
|
|
170
|
-
? taskHints(hintCandidates,
|
|
171
|
-
for (const row of candidates) {
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
207
|
+
? taskHints(hintCandidates, matcher, overflowHints === true) : []
|
|
208
|
+
for (const { row, trigger } of candidates) {
|
|
209
|
+
// Even a skipped, oversized hint may set the relevance cutoff for later hints.
|
|
210
|
+
recheck?.add(row)
|
|
211
|
+
// A user-authored trigger can itself quote a revision. Reserve bracketed
|
|
212
|
+
// references on this line for the pointers actually selected by Bond.
|
|
213
|
+
const hint = trigger.replace(/\[(?=mem-[\da-f-]+@\d+\])/giu, '[') + ' [' + row.id + '@' + row.rev + ']'
|
|
214
|
+
const withHint = copy.lookupPrefix + [...hints, hint].join(copy.separator) + copy.lookupEnd + searchHint
|
|
176
215
|
if (!fits([...lines, withHint])) continue
|
|
177
216
|
hints.push(hint)
|
|
178
217
|
lookup = withHint
|
|
@@ -182,3 +221,11 @@ export function buildIndex<T extends IndexRule>(
|
|
|
182
221
|
}
|
|
183
222
|
return { text: lines.join('\n'), included, overflow }
|
|
184
223
|
}
|
|
224
|
+
|
|
225
|
+
/** Recognize only Bond's own localized lookup line in an admitted runtime context. */
|
|
226
|
+
export function indexHintRefs(line: string) {
|
|
227
|
+
const copy = Object.values(prompts).find(copy =>
|
|
228
|
+
line.startsWith(copy.lookupPrefix) && line.endsWith(copy.lookupEnd + copy.lookup))
|
|
229
|
+
if (!copy) return []
|
|
230
|
+
return Array.from(line.matchAll(/\[(mem-[\da-f-]+)@(\d+)\]/giu), m => ({ id: m[1], rev: Number(m[2]) }))
|
|
231
|
+
}
|
package/src/index.ts
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.ts'
|
|
4
|
-
import { indexLimits
|
|
4
|
+
import { indexLimits } from './policy.ts'
|
|
5
|
+
import { prompts } from './prompt-copy.ts'
|
|
6
|
+
import { proposalContract } from './propose-contract.ts'
|
|
7
|
+
import { reviewProposals } from './proposal-review.ts'
|
|
5
8
|
import { registerMaintenance } from './maintenance.ts'
|
|
6
9
|
import { registerKnowledge } from './knowledge.ts'
|
|
7
10
|
import { newSearchTrace, type SearchMode, type SearchOptions, type SearchTrace } from './retrieval.ts'
|
|
@@ -11,6 +14,7 @@ import { registerConsolidation } from './consolidation.ts'
|
|
|
11
14
|
import { registerCommands, parseRef } from './commands.ts'
|
|
12
15
|
import { registerUI } from './ui.ts'
|
|
13
16
|
import { StoreError } from './store.ts'
|
|
17
|
+
import { registerConditionalTool } from './host.ts'
|
|
14
18
|
import type { Agent, Execution, Host, HostEvent, PluginConfig, RecordEvent, Session } from './host.ts'
|
|
15
19
|
|
|
16
20
|
export const name = 'dsh-memory-bond'
|
|
@@ -43,14 +47,23 @@ export function toolErrorStatus(error: unknown): string {
|
|
|
43
47
|
}
|
|
44
48
|
|
|
45
49
|
export function apply(ctx: Host, config: PluginConfig = {}) {
|
|
50
|
+
function unavailable(missing: string) {
|
|
51
|
+
ctx.logger.warn('Memory Bond needs ' + missing + '. See /project-memory status.')
|
|
52
|
+
ctx.inject(['commands'], (c: Host) => c.commands!.register({
|
|
53
|
+
name: 'project-memory', description: 'Report host compatibility', recordInput: false, input: { hint: 'status' },
|
|
54
|
+
async handler({ rawInput }) {
|
|
55
|
+
return { kind: rawInput.trim() === 'status' ? 'success' : 'error',
|
|
56
|
+
text: JSON.stringify({ status: 'incompatible_host', missing }) }
|
|
57
|
+
},
|
|
58
|
+
}))
|
|
59
|
+
}
|
|
46
60
|
const profileContext = ctx.get('profileContext')
|
|
47
61
|
const profile = profileContext?.dir
|
|
48
62
|
if (typeof profile !== 'string' || !isAbsolute(profile)) {
|
|
49
|
-
|
|
50
|
-
return
|
|
63
|
+
return unavailable('absolute profileContext.dir')
|
|
51
64
|
}
|
|
52
65
|
let isAgentLoopRequest: (req: unknown) => boolean
|
|
53
|
-
let reviewSdk: Parameters<typeof registerTurnReview>[1]
|
|
66
|
+
let reviewSdk: Parameters<typeof registerTurnReview>[1] | undefined
|
|
54
67
|
let appendPluginRecord: RecordEvent
|
|
55
68
|
// installAnchor is the one guarantee that hostRequire() resolves the SAME loaded copy of these
|
|
56
69
|
// host packages the running agent loop/session code uses (module-private state like
|
|
@@ -58,33 +71,41 @@ export function apply(ctx: Host, config: PluginConfig = {}) {
|
|
|
58
71
|
// plugin's own file when it is absent can silently resolve a different, wrong copy instead of
|
|
59
72
|
// failing loudly - worse than disabling the plugin, so this composition is declined outright.
|
|
60
73
|
if (!profileContext?.installAnchor) {
|
|
61
|
-
|
|
62
|
-
return
|
|
74
|
+
return unavailable('profileContext.installAnchor')
|
|
63
75
|
}
|
|
76
|
+
if (typeof ctx.agents.get !== 'function') return unavailable('agents.get')
|
|
77
|
+
if (typeof ctx.workingDirectory.get !== 'function') return unavailable('workingDirectory.get')
|
|
78
|
+
if (typeof ctx.tools.register !== 'function' || typeof ctx.tools.guard !== 'function')
|
|
79
|
+
return unavailable('tools.register and tools.guard')
|
|
80
|
+
if (typeof ctx.systemPrompt.section !== 'function' || typeof ctx.systemPrompt.context !== 'function')
|
|
81
|
+
return unavailable('systemPrompt.section and systemPrompt.context')
|
|
64
82
|
try {
|
|
65
83
|
const hostRequire = createRequire(profileContext.installAnchor)
|
|
66
84
|
const llm = hostRequire('@deepseek-ai/dsh-llm')
|
|
85
|
+
if (typeof llm?.isAgentLoopRequest !== 'function') return unavailable('@deepseek-ai/dsh-llm.isAgentLoopRequest')
|
|
67
86
|
isAgentLoopRequest = llm.isAgentLoopRequest
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
return
|
|
87
|
+
if (typeof llm.createUserMessage === 'function' && typeof llm.BlockAssembler === 'function' &&
|
|
88
|
+
typeof llm.BlockAssembler.prototype?.push === 'function' && typeof llm.BlockAssembler.prototype?.blocks === 'function')
|
|
89
|
+
reviewSdk = llm
|
|
90
|
+
const sessions = hostRequire('@deepseek-ai/dsh-session')
|
|
91
|
+
if (typeof sessions?.appendPluginRecord !== 'function') return unavailable('@deepseek-ai/dsh-session.appendPluginRecord')
|
|
92
|
+
appendPluginRecord = sessions.appendPluginRecord
|
|
93
|
+
} catch {
|
|
94
|
+
return unavailable('@deepseek-ai/dsh-llm and @deepseek-ai/dsh-session at profileContext.installAnchor')
|
|
76
95
|
}
|
|
96
|
+
const hostIssues = reviewSdk ? [] : ['model_review_sdk_unavailable']
|
|
97
|
+
if (hostIssues.length) ctx.logger.warn('Memory Bond automatic writes and background review need the host model SDK. See /project-memory status.')
|
|
77
98
|
const memory = new ProjectMemory(ctx, profile, { ...config, ...indexLimits(config) }, appendPluginRecord)
|
|
78
99
|
ctx.on('agent/inbox/claimed', ({ agent, message, turn }) => {
|
|
79
100
|
try { memory.captureTask(agent, message, turn) } catch { /* A failed scope read leaves the ordinary search hint available. */ }
|
|
80
101
|
})
|
|
81
102
|
memory.retrieval.vectors.start()
|
|
82
|
-
const stopReview = registerTurnReview(memory, reviewSdk)
|
|
83
|
-
const stopConsolidation = registerConsolidation(memory, reviewSdk)
|
|
103
|
+
const stopReview = reviewSdk && registerTurnReview(memory, reviewSdk)
|
|
104
|
+
const stopConsolidation = reviewSdk && registerConsolidation(memory, reviewSdk)
|
|
84
105
|
const stopMaintenance = registerMaintenance(ctx, memory)
|
|
85
106
|
ctx.effect(() => async () => {
|
|
86
|
-
stopReview()
|
|
87
|
-
await stopConsolidation()
|
|
107
|
+
stopReview?.()
|
|
108
|
+
await stopConsolidation?.()
|
|
88
109
|
await stopMaintenance()
|
|
89
110
|
memory.retrieval.close()
|
|
90
111
|
memory.store.close()
|
|
@@ -128,9 +149,10 @@ export function apply(ctx: Host, config: PluginConfig = {}) {
|
|
|
128
149
|
name: 'project-memory:instructions',
|
|
129
150
|
order: 20,
|
|
130
151
|
interpolate: false,
|
|
131
|
-
text: (
|
|
132
|
-
|
|
133
|
-
:
|
|
152
|
+
text: ({ agent }: { agent?: Agent } = {}) => {
|
|
153
|
+
const copy = prompts[memory.promptLanguage(agent)]
|
|
154
|
+
return memory.assistantGeneration() === undefined ? copy.disabled : copy.system
|
|
155
|
+
},
|
|
134
156
|
})
|
|
135
157
|
ctx.systemPrompt.context({
|
|
136
158
|
name: indexName,
|
|
@@ -149,8 +171,8 @@ export function apply(ctx: Host, config: PluginConfig = {}) {
|
|
|
149
171
|
}
|
|
150
172
|
},
|
|
151
173
|
})
|
|
152
|
-
const { expanded, shownSearchRows } = registerAudit(memory, isAgentLoopRequest)
|
|
153
|
-
registerKnowledge(ctx, memory, expanded)
|
|
174
|
+
const { expanded, shownSearchRows, executed, blocked, wrote } = registerAudit(memory, isAgentLoopRequest)
|
|
175
|
+
registerKnowledge(ctx, memory, expanded, { executed, blocked })
|
|
154
176
|
const emptySearches = new WeakMap<Agent, string>()
|
|
155
177
|
function searchAvailable(agent: Agent, generation: number) {
|
|
156
178
|
const previous = emptySearches.get(agent)
|
|
@@ -167,9 +189,9 @@ export function apply(ctx: Host, config: PluginConfig = {}) {
|
|
|
167
189
|
emptySearches.delete(agent)
|
|
168
190
|
return true
|
|
169
191
|
}
|
|
170
|
-
function tool(name: string, contract: object, run: (args: Input, agent: Agent, call: string, generation: number) => unknown,
|
|
171
|
-
available?: (agent: Agent, generation: number) => boolean) {
|
|
172
|
-
ctx
|
|
192
|
+
function tool(name: string, contract: object, run: (args: Input, agent: Agent, call: string, generation: number, signal?: AbortSignal) => unknown,
|
|
193
|
+
available?: (agent: Agent, generation: number) => boolean, visibleWithoutAgent = true) {
|
|
194
|
+
registerConditionalTool(ctx, {
|
|
173
195
|
name,
|
|
174
196
|
...contract,
|
|
175
197
|
output,
|
|
@@ -178,25 +200,44 @@ export function apply(ctx: Host, config: PluginConfig = {}) {
|
|
|
178
200
|
try {
|
|
179
201
|
const generation = memory.assistantGeneration()
|
|
180
202
|
if (generation === undefined) return JSON.stringify({ status: 'memory_disabled' })
|
|
181
|
-
const result = await run(args, exec.agent, exec.callId, generation)
|
|
203
|
+
const result = await run(args, exec.agent, exec.callId, generation, exec.signal)
|
|
182
204
|
return JSON.stringify(memory.assistantGeneration() === generation ? result : { status: 'memory_disabled' })
|
|
183
205
|
} catch (error) {
|
|
184
206
|
return JSON.stringify({ status: toolErrorStatus(error) })
|
|
185
207
|
}
|
|
186
208
|
},
|
|
187
|
-
},
|
|
209
|
+
}, agent => {
|
|
188
210
|
const generation = memory.assistantGeneration()
|
|
189
|
-
return generation !== undefined && (!available ||
|
|
190
|
-
}
|
|
211
|
+
return generation !== undefined && (!available || (agent ? available(agent, generation) : visibleWithoutAgent))
|
|
212
|
+
})
|
|
191
213
|
}
|
|
192
|
-
|
|
214
|
+
const toolLanguage = memory.promptLanguage()
|
|
215
|
+
const toolCopy = prompts[toolLanguage]
|
|
216
|
+
tool('project_memory_propose', proposalContract(toolLanguage), async (args, agent, call, generation, signal) => {
|
|
217
|
+
const initial = memory.domain(agent)
|
|
218
|
+
const receipt = await reviewProposals(memory, agent, args, reviewSdk, signal)
|
|
219
|
+
const current = memory.domain(agent)
|
|
220
|
+
if (memory.assistantGeneration() !== generation) return { status: 'memory_disabled' }
|
|
221
|
+
if (!initial || !current || current.id !== initial.id || current.root !== initial.root || current.cwd !== initial.cwd ||
|
|
222
|
+
ctx.agents.get(agent.id) !== agent) return { status: 'unavailable' }
|
|
223
|
+
try { wrote(agent, current, call, receipt.results) }
|
|
224
|
+
catch (error) { ctx.logger.warn('未能记录本次记忆回执的投递凭据:' + String(error)) }
|
|
225
|
+
return receipt
|
|
226
|
+
})
|
|
227
|
+
tool('project_memory_experience', {
|
|
228
|
+
description: toolCopy.experience,
|
|
229
|
+
parameters: parameters({ callId: string, topic: string, action: string }, ['callId', 'topic', 'action']),
|
|
230
|
+
}, (args, agent, _call, generation) => memory.proposeExperience(agent, args, generation),
|
|
231
|
+
(agent, generation) => {
|
|
232
|
+
try { return !!memory.experienceSource(agent, generation) } catch { return false }
|
|
233
|
+
}, false)
|
|
193
234
|
tool(
|
|
194
235
|
'project_memory_search',
|
|
195
236
|
{
|
|
196
|
-
description:
|
|
197
|
-
'搜索全局与本项目的记忆。知道对象和主题时传 subject 和 topic,否则用自然语言 query。查项目约定且记录语言可能不同时,同时传另一语言的等义短语 alternateQuery(中英各一),保留命令和专名。命中按相关性排序,alreadyShown 表示当前对话步骤已收到该版本的完整条目。no_new_evidence 表示本次没有补充证据,同一细节停止改写搜索词,依据已有信息回答或说明未知;独立线索可另查。empty_scope 表示所查范围没有可用记忆,直接按当前任务或用户给出的备用方式继续。ambiguous 表示需要核对多个候选。coverage 为 partial/missing/unavailable 时语义覆盖不完整。',
|
|
237
|
+
description: toolCopy.search,
|
|
198
238
|
parameters: parameters(
|
|
199
|
-
{ query: string, alternateQuery: string, subject: string, topic: string,
|
|
239
|
+
{ query: string, alternateQuery: string, subject: string, topic: string, limit: { type: 'integer', minimum: 1, maximum: 40 },
|
|
240
|
+
scope: { type: 'string', enum: ['global', 'project'] },
|
|
200
241
|
mode: { type: 'string', enum: ['hybrid', 'keyword', 'semantic'] } },
|
|
201
242
|
['query'],
|
|
202
243
|
),
|
|
@@ -209,12 +250,14 @@ export function apply(ctx: Host, config: PluginConfig = {}) {
|
|
|
209
250
|
const d = memory.domain(agent)
|
|
210
251
|
if (!d) return { rules: [] }
|
|
211
252
|
const context = searchContext(agent, d, generation)
|
|
212
|
-
const { subject, topic, scope } = args
|
|
253
|
+
const { subject, topic, scope, limit = 6 } = args
|
|
254
|
+
if (typeof limit !== 'number' || !Number.isInteger(limit) || limit < 1 || limit > 40)
|
|
255
|
+
throw new StoreError('invalid_input')
|
|
213
256
|
if (scope !== undefined && scope !== 'global' && scope !== 'project') throw new StoreError('invalid_input')
|
|
214
257
|
const rules = await memory.search(agent, args.query as string, args.mode as SearchMode,
|
|
215
258
|
{ subject, topic, scope: scope === 'global' ? 'profile' : scope, alternateQuery: args.alternateQuery } as SearchOptions, trace)
|
|
216
259
|
if (memory.assistantGeneration() !== generation || memory.domain(agent)?.id !== d.id) return { rules: [] }
|
|
217
|
-
const rows = rules.slice(0,
|
|
260
|
+
const rows = rules.slice(0, limit)
|
|
218
261
|
if (trace.match === 'empty_scope' && context) emptySearches.set(agent, context)
|
|
219
262
|
const seen = shownSearchRows(agent, context)
|
|
220
263
|
let noNewEvidence = Boolean(seen)
|
|
@@ -226,10 +269,11 @@ export function apply(ctx: Host, config: PluginConfig = {}) {
|
|
|
226
269
|
}
|
|
227
270
|
return trace.match === 'exact_id' ? full : { id: rule.id, rev: rule.rev, alreadyShown: true }
|
|
228
271
|
})
|
|
229
|
-
expanded(agent, d, call, rows
|
|
272
|
+
expanded(agent, d, call, rows, context)
|
|
230
273
|
memory.store.audit(d.id, agent.id, 'search', { call, agent: agent.id, outcome: rows.length })
|
|
231
274
|
return { rules: results, match: trace.match, coverage: trace.coverage,
|
|
232
|
-
...(
|
|
275
|
+
...(rules.length > limit && { totalMatches: rules.length }),
|
|
276
|
+
...(trace.match === 'empty_scope' && { guidance: prompts[memory.promptLanguage(agent)].empty }),
|
|
233
277
|
...(noNewEvidence ? { progress: 'no_new_evidence' } : {}) }
|
|
234
278
|
} finally {
|
|
235
279
|
timing.returned = performance.now()
|
|
@@ -264,8 +308,8 @@ export function apply(ctx: Host, config: PluginConfig = {}) {
|
|
|
264
308
|
if ('id' in row && row.id !== undefined) {
|
|
265
309
|
const owner = memory.owner(agent, d, row.id)
|
|
266
310
|
const current = owner && memory.current(owner, row.id, row.rev)
|
|
267
|
-
if (!current || (
|
|
268
|
-
if (!source) expanded(agent, d, call, [
|
|
311
|
+
if (!current || !memory.canPublishEvidence(current, row)) return { status: 'not_found' }
|
|
312
|
+
if (!source && 'action' in row) expanded(agent, d, call, [row])
|
|
269
313
|
memory.store.audit(
|
|
270
314
|
owner.id,
|
|
271
315
|
agent.id,
|
|
@@ -281,9 +325,9 @@ export function apply(ctx: Host, config: PluginConfig = {}) {
|
|
|
281
325
|
return 'scope' in row ? modelRule(row) : row
|
|
282
326
|
})
|
|
283
327
|
}
|
|
284
|
-
readTool('project_memory_read',
|
|
285
|
-
readTool('project_memory_source',
|
|
286
|
-
ctx.inject(['commands'], (c) => registerCommands(c, memory))
|
|
328
|
+
readTool('project_memory_read', toolCopy.read)
|
|
329
|
+
readTool('project_memory_source', toolCopy.source)
|
|
330
|
+
ctx.inject(['commands'], (c) => registerCommands(c, memory, hostIssues))
|
|
287
331
|
registerUI(ctx, memory)
|
|
288
332
|
ctx.provide('projectMemoryReady', true)
|
|
289
333
|
}
|