dsh-memory-bond 0.0.0-stage → 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.
Files changed (126) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/LICENSE +21 -0
  3. package/README.md +181 -2
  4. package/README.zh-CN.md +180 -0
  5. package/SECURITY.md +29 -0
  6. package/client/memory-icon.svg +21 -0
  7. package/cordis.patch.yml +3 -0
  8. package/dist/audit.js +286 -0
  9. package/dist/automatic.js +16 -0
  10. package/dist/cache.js +40 -0
  11. package/dist/client.js +2035 -0
  12. package/dist/command-scope.js +123 -0
  13. package/dist/commands.js +156 -0
  14. package/dist/consolidation-store.js +357 -0
  15. package/dist/consolidation.js +182 -0
  16. package/dist/domain.js +245 -0
  17. package/dist/encoder.js +138 -0
  18. package/dist/export-files.js +161 -0
  19. package/dist/file-import-store.js +120 -0
  20. package/dist/file-import.js +265 -0
  21. package/dist/foreground-attempts.js +91 -0
  22. package/dist/guidance.js +242 -0
  23. package/dist/host.js +19 -0
  24. package/dist/index-policy.js +191 -0
  25. package/dist/index.js +349 -0
  26. package/dist/knowledge-hooks.js +398 -0
  27. package/dist/knowledge.js +359 -0
  28. package/dist/maintenance-episodes.js +73 -0
  29. package/dist/maintenance-import.js +92 -0
  30. package/dist/maintenance-store.js +738 -0
  31. package/dist/maintenance.js +376 -0
  32. package/dist/model-review.js +16 -0
  33. package/dist/personal.js +60 -0
  34. package/dist/policy.js +382 -0
  35. package/dist/prompt-copy.js +93 -0
  36. package/dist/proposal-receipts.js +70 -0
  37. package/dist/proposal-review.js +656 -0
  38. package/dist/propose-contract.js +38 -0
  39. package/dist/question-answers.js +176 -0
  40. package/dist/retrieval.js +126 -0
  41. package/dist/scope-narrowing.js +49 -0
  42. package/dist/search-index.js +164 -0
  43. package/dist/search-words.js +5 -0
  44. package/dist/semantic.js +157 -0
  45. package/dist/service.js +1473 -0
  46. package/dist/sharing.js +289 -0
  47. package/dist/sources.js +149 -0
  48. package/dist/store.js +1578 -0
  49. package/dist/tool-experience.js +87 -0
  50. package/dist/turn-review-store.js +159 -0
  51. package/dist/turn-review.js +459 -0
  52. package/dist/ui.js +346 -0
  53. package/dist/vector-index.js +232 -0
  54. package/docs/architecture.zh-CN.md +52 -0
  55. package/docs/benchmark.zh-CN.md +60 -0
  56. package/docs/benchmarks/repository-tasks.json +5355 -0
  57. package/docs/images/bond-memory-principle-en.svg +644 -0
  58. package/docs/images/bond-memory-principle-zh.svg +644 -0
  59. package/docs/images/bond-memory-principle.drawio +644 -0
  60. package/docs/images/memory-settings-en.png +0 -0
  61. package/docs/images/memory-settings-zh.png +0 -0
  62. package/docs/images/memory-turn-recalled-en.png +0 -0
  63. package/docs/images/memory-turn-recalled-zh.png +0 -0
  64. package/docs/images/memory-turn-saved-en.png +0 -0
  65. package/docs/images/memory-turn-saved-zh.png +0 -0
  66. package/docs/media/memory-bond-name-en.gif +0 -0
  67. package/docs/media/memory-bond-name-en.mp4 +0 -0
  68. package/docs/media/memory-bond-name-zh.gif +0 -0
  69. package/docs/media/memory-bond-name-zh.mp4 +0 -0
  70. package/locale/detail.en.md +13 -0
  71. package/locale/detail.zh.md +13 -0
  72. package/locale/en.json +345 -0
  73. package/locale/zh.json +345 -0
  74. package/native/embeddings/NOTICE.md +12 -0
  75. package/package.json +117 -4
  76. package/scripts/benchmark-bond.mjs +72 -0
  77. package/scripts/benchmark-conditions.mjs +144 -0
  78. package/scripts/benchmark-example.mjs +37 -0
  79. package/scripts/benchmark-scale.mjs +119 -0
  80. package/scripts/benchmark-scenarios.mjs +57 -0
  81. package/scripts/benchmark-tasks.mjs +244 -0
  82. package/src/audit.ts +286 -0
  83. package/src/automatic.ts +21 -0
  84. package/src/cache.ts +38 -0
  85. package/src/command-scope.ts +125 -0
  86. package/src/commands.ts +159 -0
  87. package/src/consolidation-store.ts +350 -0
  88. package/src/consolidation.ts +176 -0
  89. package/src/domain.ts +254 -0
  90. package/src/encoder.ts +142 -0
  91. package/src/export-files.ts +178 -0
  92. package/src/file-import-store.ts +139 -0
  93. package/src/file-import.ts +256 -0
  94. package/src/foreground-attempts.ts +97 -0
  95. package/src/guidance.ts +265 -0
  96. package/src/host.ts +119 -0
  97. package/src/index-policy.ts +231 -0
  98. package/src/index.ts +333 -0
  99. package/src/knowledge-hooks.ts +456 -0
  100. package/src/knowledge.ts +432 -0
  101. package/src/maintenance-episodes.ts +76 -0
  102. package/src/maintenance-import.ts +107 -0
  103. package/src/maintenance-store.ts +868 -0
  104. package/src/maintenance.ts +380 -0
  105. package/src/model-review.ts +27 -0
  106. package/src/personal.ts +68 -0
  107. package/src/policy.ts +508 -0
  108. package/src/prompt-copy.ts +99 -0
  109. package/src/proposal-receipts.ts +59 -0
  110. package/src/proposal-review.ts +614 -0
  111. package/src/propose-contract.ts +39 -0
  112. package/src/question-answers.ts +181 -0
  113. package/src/retrieval.ts +133 -0
  114. package/src/scope-narrowing.ts +58 -0
  115. package/src/search-index.ts +177 -0
  116. package/src/search-words.ts +6 -0
  117. package/src/semantic.ts +178 -0
  118. package/src/service.ts +1488 -0
  119. package/src/sharing.ts +349 -0
  120. package/src/sources.ts +150 -0
  121. package/src/store.ts +1829 -0
  122. package/src/tool-experience.ts +93 -0
  123. package/src/turn-review-store.ts +158 -0
  124. package/src/turn-review.ts +418 -0
  125. package/src/ui.ts +385 -0
  126. package/src/vector-index.ts +228 -0
@@ -0,0 +1,182 @@
1
+ import { prompts } from "./prompt-copy.js";
2
+ import { reviewText } from "./model-review.js";
3
+ const maxOutput = 64;
4
+ const hour = 60 * 60 * 1000;
5
+ function describe({ topic, subject, kind, usage, action, when, exceptions, paths }) {
6
+ return { topic, subject, kind, usage, action, when, exceptions, paths };
7
+ }
8
+ const modelInput = (pair) => JSON.stringify({ left: describe(pair.left), right: describe(pair.right) });
9
+ function decision(text) {
10
+ const clean = text.trim().replace(/^\x60\x60\x60(?:json)?\s*\n([\s\S]*)\n\x60\x60\x60$/iu, '$1');
11
+ const answer = JSON.parse(clean);
12
+ if (answer && Object.keys(answer).length === 1 && ['duplicate', 'distinct'].includes(answer.decision))
13
+ return answer.decision;
14
+ throw new Error('invalid_consolidation_result');
15
+ }
16
+ /** Keep only a bounded set of completed root sessions. Their live project and route authorize each call. */
17
+ export function registerConsolidation(memory, sdk, { idleMs = 1500, intervalMs = hour, timeoutMs = 30_000, checkMs = 1000 } = {}) {
18
+ const host = memory.ctx;
19
+ const store = memory.store.consolidation;
20
+ const projects = new Map();
21
+ let timer;
22
+ let active;
23
+ let closed = false;
24
+ function live(job) {
25
+ const agent = host.agents.get(job.sessionId);
26
+ if (!agent || !job.idle || agent.session !== job.session.deref())
27
+ return;
28
+ const route = agent.model?.current();
29
+ if (route?.provider !== job.route.provider || route.model !== job.route.model)
30
+ return;
31
+ const domain = memory.rootDomain(agent, true);
32
+ return domain.id === job.domain && domain.cwd === job.cwd ? domain : undefined;
33
+ }
34
+ async function run(job, controller) {
35
+ if (closed || controller.signal.aborted)
36
+ return;
37
+ const domain = live(job);
38
+ if (!domain) {
39
+ if (projects.get(job.domain) === job)
40
+ projects.delete(job.domain);
41
+ return;
42
+ }
43
+ const llm = host.get('llm');
44
+ if (!memory.store.memoryEnabled() || !store.status().enabled || !llm?.stream)
45
+ return;
46
+ const pair = store.next(job.domain, ref => !!memory.current(domain, ref.id, ref.rev));
47
+ host.emit('project-memory/consolidation-updated');
48
+ if (!pair)
49
+ return;
50
+ const request = {
51
+ ...job.route, system: prompts[memory.promptLanguage(host.agents.get(job.sessionId))].consolidate, maxTokens: maxOutput,
52
+ signal: controller.signal, messages: [sdk.createUserMessage({
53
+ source: { kind: 'project-memory-consolidation' }, content: [{ type: 'text', text: modelInput(pair) }],
54
+ })],
55
+ };
56
+ const lease = store.reserve(job.domain, pair);
57
+ if (!lease)
58
+ return;
59
+ let outcome = 'failed';
60
+ let timeout;
61
+ let guard;
62
+ let timedOut = false;
63
+ let onAbort;
64
+ const eligible = () => {
65
+ const now = live(job);
66
+ return now && store.current(lease) && memory.current(now, pair.left.id, pair.left.rev) &&
67
+ memory.current(now, pair.right.id, pair.right.rev);
68
+ };
69
+ try {
70
+ host.emit('project-memory/consolidation-updated');
71
+ if (controller.signal.aborted || !eligible()) {
72
+ outcome = 'stale';
73
+ return;
74
+ }
75
+ const aborted = new Promise((_, reject) => {
76
+ onAbort = () => reject(new Error('cancelled'));
77
+ controller.signal.addEventListener('abort', onAbort, { once: true });
78
+ });
79
+ timeout = setTimeout(() => { timedOut = true; controller.abort(); }, timeoutMs);
80
+ timeout.unref();
81
+ // Other DSH processes may change settings/revisions without notifying this host.
82
+ guard = setInterval(() => {
83
+ try {
84
+ if (eligible())
85
+ return;
86
+ }
87
+ catch { /* access may have been revoked */ }
88
+ controller.abort();
89
+ }, checkMs);
90
+ guard.unref();
91
+ const classify = async () => {
92
+ // DSH rejects reasoningEffort even as "off" on models which do not advertise it.
93
+ // Preparation checks controls without sending memory to the provider.
94
+ const prepared = await llm.prepareCall?.({ ...job.route, maxTokens: maxOutput }, controller.signal, (controls, info) => info.reasoning?.efforts.some(e => e.id === 'off') ? { ...controls, reasoningEffort: 'off' } : controls);
95
+ controller.signal.throwIfAborted();
96
+ if (!eligible()) {
97
+ controller.abort();
98
+ throw new Error('cancelled');
99
+ }
100
+ return reviewText(prepared ?? llm, sdk, { ...request, ...prepared?.config });
101
+ };
102
+ const reply = await Promise.race([aborted, classify()]);
103
+ outcome = !controller.signal.aborted && eligible() ? decision(reply) : 'stale';
104
+ }
105
+ catch {
106
+ outcome = controller.signal.aborted && !timedOut ? 'stale' : 'failed';
107
+ }
108
+ finally {
109
+ clearInterval(guard);
110
+ clearTimeout(timeout);
111
+ if (onAbort)
112
+ controller.signal.removeEventListener('abort', onAbort);
113
+ store.finish(lease, outcome);
114
+ host.emit('project-memory/consolidation-updated');
115
+ }
116
+ }
117
+ function schedule() {
118
+ clearTimeout(timer);
119
+ if (closed || active)
120
+ return;
121
+ const next = [...projects.values()].filter(job => job.idle).sort((a, b) => a.nextAt - b.nextAt)[0];
122
+ if (!next)
123
+ return;
124
+ timer = setTimeout(() => {
125
+ next.nextAt = Date.now() + intervalMs;
126
+ const controller = new AbortController();
127
+ const done = Promise.resolve().then(() => run(next, controller)).catch(() => {
128
+ if (!controller.signal.aborted)
129
+ host.logger.warn('跨会话记忆整理暂缓,待下次空闲检查。');
130
+ }).finally(() => { active = undefined; schedule(); });
131
+ active = { job: next, controller, done };
132
+ }, Math.max(0, next.nextAt - Date.now()));
133
+ timer.unref();
134
+ }
135
+ host.on('session/event', (session, event) => {
136
+ if (closed || session.header.origin === 'subagent' || event.seq < session.inheritedEventCount)
137
+ return;
138
+ if (event.type === 'turn/start') {
139
+ for (const job of projects.values())
140
+ if (job.session.deref() === session)
141
+ job.idle = false;
142
+ if (active?.job.session.deref() === session)
143
+ active.controller.abort();
144
+ schedule();
145
+ return;
146
+ }
147
+ if (event.type !== 'turn/end' || event.data.reason?.kind !== 'completed')
148
+ return;
149
+ try {
150
+ const agent = host.agents.get(session.id);
151
+ const route = agent?.model?.current();
152
+ if (!agent || agent.session !== session || !route?.provider || !route.model)
153
+ return;
154
+ const d = memory.rootDomain(agent, true);
155
+ if (d.id === memory.personal.id)
156
+ return;
157
+ const previous = projects.get(d.id);
158
+ const nextAt = Math.max(previous?.nextAt ?? 0, Date.now() + idleMs);
159
+ if (!previous && projects.size >= 64)
160
+ projects.delete(projects.keys().next().value);
161
+ projects.set(d.id, { sessionId: session.id, session: new WeakRef(session), domain: d.id,
162
+ cwd: d.cwd, route: { provider: route.provider, model: route.model }, idle: true, nextAt });
163
+ schedule();
164
+ }
165
+ catch { /* a read-only or inaccessible project cannot authorize a background call */ }
166
+ });
167
+ host.on('project-memory/consolidation-settings-changed', () => {
168
+ if (closed)
169
+ return;
170
+ active?.controller.abort();
171
+ for (const job of projects.values())
172
+ job.nextAt = Date.now() + idleMs;
173
+ schedule();
174
+ });
175
+ return async () => {
176
+ closed = true;
177
+ clearTimeout(timer);
178
+ projects.clear();
179
+ active?.controller.abort();
180
+ await active?.done;
181
+ };
182
+ }
package/dist/domain.js ADDED
@@ -0,0 +1,245 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { createHash } from 'node:crypto';
3
+ import { existsSync, lstatSync, readFileSync, realpathSync, statSync } from 'node:fs';
4
+ import { hostname } from 'node:os';
5
+ import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
6
+ import { SignatureCache } from "./cache.js";
7
+ export const digest = (value) => createHash('sha256').update(value).digest('hex');
8
+ export function inside(root, child) {
9
+ const rel = relative(root, child);
10
+ return rel !== '..' && !rel.startsWith('..' + sep) && !isAbsolute(rel);
11
+ }
12
+ function gitValue(cwd, ...args) {
13
+ // Ignore process-level repository overrides inherited from a parent Git command.
14
+ const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith('GIT_')));
15
+ try {
16
+ return execFileSync('git', ['-C', cwd, ...args], {
17
+ env,
18
+ encoding: 'utf8',
19
+ stdio: ['ignore', 'pipe', 'ignore'],
20
+ timeout: 1500,
21
+ }).replace(/\r?\n$/, '');
22
+ }
23
+ catch {
24
+ return undefined;
25
+ }
26
+ }
27
+ export function resolveDomain(profileDir, cwd, nonGitRoots = []) {
28
+ try {
29
+ if (!isAbsolute(cwd) || !isAbsolute(profileDir))
30
+ return;
31
+ cwd = realpathSync(cwd);
32
+ profileDir = realpathSync(profileDir);
33
+ if (!statSync(cwd).isDirectory() || !statSync(profileDir).isDirectory())
34
+ return;
35
+ const machine = digest(JSON.stringify([hostname(), process.getuid?.() ?? process.env.USERNAME]));
36
+ const top = gitValue(cwd, 'rev-parse', '--show-toplevel');
37
+ let root, identity;
38
+ if (top) {
39
+ root = realpathSync(top);
40
+ // --git-common-dir predates --path-format. Some desktop PATHs select a Git
41
+ // that prints the unrecognized switch literally with a successful exit status.
42
+ const common = gitValue(cwd, 'rev-parse', '--git-common-dir');
43
+ if (!common || !inside(root, cwd))
44
+ return;
45
+ identity = realpathSync(resolve(cwd, common));
46
+ }
47
+ else {
48
+ // A broken/inaccessible Git checkout cannot be reinterpreted as a trusted non-Git root.
49
+ for (let dir = cwd;; dir = dirname(dir)) {
50
+ if (existsSync(join(dir, '.git')))
51
+ return;
52
+ if (dir === dirname(dir))
53
+ break;
54
+ }
55
+ const allowed = [];
56
+ for (const candidate of nonGitRoots) {
57
+ if (!isAbsolute(candidate))
58
+ continue;
59
+ try {
60
+ const real = realpathSync(candidate);
61
+ if (inside(real, cwd))
62
+ allowed.push(real);
63
+ }
64
+ catch {
65
+ /* unavailable configured root */
66
+ }
67
+ }
68
+ if (!allowed.length)
69
+ return;
70
+ root = allowed.sort((a, b) => b.length - a.length)[0];
71
+ identity = root;
72
+ }
73
+ const location = statSync(identity, { bigint: true });
74
+ const id = digest(JSON.stringify([
75
+ machine,
76
+ profileDir,
77
+ top ? 'git' : 'directory',
78
+ identity,
79
+ String(location.dev),
80
+ String(location.ino),
81
+ ]));
82
+ return { id, profileDir, root, cwd, machine, git: Boolean(top) };
83
+ }
84
+ catch {
85
+ return undefined;
86
+ }
87
+ }
88
+ export function branchOf(domain) {
89
+ return domain.git ? gitValue(domain.root, 'symbolic-ref', '--quiet', '--short', 'HEAD') : undefined;
90
+ }
91
+ // --- Cached variants ---------------------------------------------------------------------
92
+ // resolveDomain()/branchOf() above are kept exact and uncached: tests and maintenance-import.ts
93
+ // rely on calling them directly for a guaranteed-fresh answer. The cached wrappers below exist
94
+ // for the hot, repeated call sites (one resolution per model step, searched multiple times per
95
+ // query) and are safe to reuse there because their signature is re-derived, cheaply, on every
96
+ // call from exactly the filesystem facts that could change the answer - never a blind TTL.
97
+ const domainCache = new SignatureCache();
98
+ /** Every directory from cwd to the filesystem root, by its `.git` marker - a repo/worktree boundary. */
99
+ function gitBoundary(cwd) {
100
+ const watch = [cwd];
101
+ let dir = cwd;
102
+ for (let depth = 0; depth < 256; depth++) {
103
+ watch.push(join(dir, '.git'));
104
+ const parent = dirname(dir);
105
+ if (parent === dir)
106
+ break;
107
+ dir = parent;
108
+ }
109
+ return watch;
110
+ }
111
+ /**
112
+ * Cached resolveDomain(): re-validated on every call via a stat-only walk of exactly the
113
+ * boundary a new/removed repository or worktree would touch (no process spawn), so a real cd,
114
+ * `git init`, worktree add/remove, or clone is always seen on the next call.
115
+ */
116
+ export function resolveDomainCached(profileDir, cwd, nonGitRoots = []) {
117
+ if (!isAbsolute(cwd) || !isAbsolute(profileDir))
118
+ return resolveDomain(profileDir, cwd, nonGitRoots);
119
+ let real;
120
+ try {
121
+ real = realpathSync(cwd);
122
+ }
123
+ catch {
124
+ return resolveDomain(profileDir, cwd, nonGitRoots);
125
+ }
126
+ const key = [profileDir, real, ...nonGitRoots].join('\u0000');
127
+ const watch = gitBoundary(real);
128
+ // A launch-time Git timeout in an existing checkout says nothing about its identity.
129
+ // Its .git marker will not change when the executable recovers. Retry on the next lookup.
130
+ return domainCache.get(key, watch, () => resolveDomain(profileDir, cwd, nonGitRoots), domain => domain !== undefined || !watch.slice(1).some(marker => existsSync(marker)));
131
+ }
132
+ /** The exact HEAD file this checkout's symbolic ref lives in, resolving a worktree's private gitdir. */
133
+ function headFile(root) {
134
+ try {
135
+ const marker = join(root, '.git');
136
+ const info = lstatSync(marker);
137
+ if (info.isDirectory())
138
+ return join(marker, 'HEAD');
139
+ if (!info.isFile())
140
+ return undefined;
141
+ const pointer = readFileSync(marker, 'utf8').match(/^gitdir:\s*(.+?)\s*$/mu)?.[1];
142
+ return pointer ? join(isAbsolute(pointer) ? pointer : resolve(root, pointer), 'HEAD') : undefined;
143
+ }
144
+ catch {
145
+ return undefined;
146
+ }
147
+ }
148
+ const branchCache = new SignatureCache();
149
+ /** Cached branchOf(): invalidated by this exact checkout's own HEAD file, never a blind TTL. */
150
+ export function branchOfCached(domain) {
151
+ if (!domain.git)
152
+ return undefined;
153
+ const head = headFile(domain.root);
154
+ if (!head)
155
+ return branchOf(domain);
156
+ return branchCache.get(domain.root, [head], () => branchOf(domain));
157
+ }
158
+ // Stored project paths and tool schemas use slash-separated paths on every platform.
159
+ export function projectRelative(root, path) {
160
+ return relative(root, path).split(sep).join('/');
161
+ }
162
+ export function cleanRelative(value) {
163
+ const p = value.trim();
164
+ if (!p ||
165
+ isAbsolute(p) ||
166
+ p.includes('\\') ||
167
+ /[\x00-\x1f\x7f]/u.test(p) ||
168
+ /^[A-Za-z]:/.test(p) ||
169
+ p.split('/').some((part) => part === '..' || part.toLowerCase() === '.git'))
170
+ throw new Error('invalid_path');
171
+ return (p
172
+ .split('/')
173
+ .filter((part) => part && part !== '.')
174
+ .join('/') || '.');
175
+ }
176
+ /** Resolve inside the active checkout. A same-tree symlink is allowed, a foreign checkout is not. */
177
+ export function projectPath(domain, rel) {
178
+ const clean = cleanRelative(rel);
179
+ let path = domain.root;
180
+ for (const part of clean === '.' ? [] : clean.split('/')) {
181
+ path = join(path, part);
182
+ // Checking every existing ancestor also catches dangling symlinks on optional paths.
183
+ let symbolic = false;
184
+ try {
185
+ symbolic = lstatSync(path).isSymbolicLink();
186
+ }
187
+ catch (error) {
188
+ if (error.code !== 'ENOENT')
189
+ throw error;
190
+ }
191
+ if (symbolic) {
192
+ try {
193
+ path = realpathSync(path);
194
+ }
195
+ catch {
196
+ throw new Error('invalid_path');
197
+ }
198
+ if (!inside(domain.root, path))
199
+ throw new Error('invalid_path');
200
+ const target = cleanRelative(projectRelative(domain.root, path) || '.');
201
+ // A link directly to a file in a nested checkout skips that checkout's root lexically.
202
+ for (let dir = resolve(domain.root, target); dir !== domain.root; dir = dirname(dir)) {
203
+ if (existsSync(join(dir, '.git')))
204
+ throw new Error('invalid_path');
205
+ }
206
+ }
207
+ if (path !== domain.root && existsSync(join(path, '.git')))
208
+ throw new Error('invalid_path');
209
+ }
210
+ return path;
211
+ }
212
+ /** Walk components in filesystem order so a symlink followed by ".." cannot hide an escape. */
213
+ export function scopedPath(domain, target, base = domain.cwd) {
214
+ if (!target || typeof target !== 'string')
215
+ throw new Error('invalid_path');
216
+ let current = base;
217
+ if (isAbsolute(target)) {
218
+ const prefix = domain.root.endsWith(sep) ? domain.root : domain.root + sep;
219
+ if (target === domain.root)
220
+ return domain.root;
221
+ if (!target.startsWith(prefix))
222
+ throw new Error('invalid_path');
223
+ target = target.slice(prefix.length);
224
+ current = domain.root;
225
+ }
226
+ for (const part of target.replaceAll(sep, '/').split('/')) {
227
+ if (!part || part === '.')
228
+ continue;
229
+ current = part === '..' ? dirname(current) : join(current, part);
230
+ if (!inside(domain.root, current))
231
+ throw new Error('invalid_path');
232
+ current = projectPath(domain, projectRelative(domain.root, current) || '.');
233
+ }
234
+ return current;
235
+ }
236
+ /** Resolve the effective target of a file tool (or a reported Bash cwd) in this worktree. */
237
+ export function toolPathInDomain(domain, target, workdir = domain.cwd) {
238
+ try {
239
+ scopedPath(domain, target, scopedPath(domain, workdir));
240
+ return true;
241
+ }
242
+ catch {
243
+ return false;
244
+ }
245
+ }
@@ -0,0 +1,138 @@
1
+ import { createRequire } from 'node:module';
2
+ import { pathToFileURL } from 'node:url';
3
+ import { Worker } from 'node:worker_threads';
4
+ export const modelLanguages = ['en', 'zh'];
5
+ export const language = (text) => /\p{Script=Han}/u.test(text) ? 'zh' : 'en';
6
+ // Mixed queries can search both installed monolingual indexes. Each query vector
7
+ // is compared only to passages encoded by that same model.
8
+ export function queryLanguages(text) {
9
+ return modelLanguages.filter(lang => lang === 'zh' ? /\p{Script=Han}/u.test(text) : /\p{Script=Latin}/u.test(text));
10
+ }
11
+ export const encoderId = (language) => language === 'zh' ? 'bge-small-zh-v1.5/int8/75c43b06/cls-v1' : 'bge-small-en-v1.5/int8/ea104dac/cls-v1';
12
+ function installedModels() {
13
+ const require = createRequire(import.meta.url);
14
+ const models = {};
15
+ let worker;
16
+ for (const lang of modelLanguages) {
17
+ try {
18
+ const manifest = require.resolve(`dsh-memory-bond-model-${lang}/package.json`);
19
+ const fromModel = createRequire(manifest);
20
+ fromModel.resolve('./model.onnx');
21
+ fromModel.resolve('./vocab.txt');
22
+ const entry = fromModel.resolve('dsh-memory-bond-onnx/worker.mjs');
23
+ models[lang] = pathToFileURL(manifest).href;
24
+ worker ??= pathToFileURL(entry);
25
+ }
26
+ catch {
27
+ // An absent model or its runtime leaves this language on the FTS path.
28
+ }
29
+ }
30
+ return { models, worker };
31
+ }
32
+ // A stalled WASM call (not a crash) would otherwise wait forever: nothing but this deadline
33
+ // settles the pending request, and the worker's queue is strictly sequential,
34
+ // so every later call on the same worker would starve behind it too.
35
+ const encodeDeadlineMs = 10_000;
36
+ // Frees the ONNX runtime and loaded model (hundreds of MB) once nothing has asked for an
37
+ // embedding in a while; the next encode() call pays the cold-start cost again on demand.
38
+ const idleUnloadMs = 5 * 60_000;
39
+ /** Lazily own one inference worker. No installation, network or external executable on the search path. */
40
+ export class SentenceEncoder {
41
+ worker;
42
+ serial = 0;
43
+ pending = new Map();
44
+ idleTimer;
45
+ languages;
46
+ models;
47
+ workerUrl;
48
+ deadlineMs;
49
+ idleMs;
50
+ constructor(workerUrl, deadlineMs = encodeDeadlineMs, idleMs = idleUnloadMs) {
51
+ if (workerUrl) {
52
+ this.workerUrl = workerUrl;
53
+ this.languages = modelLanguages;
54
+ }
55
+ else {
56
+ const { models, worker } = installedModels();
57
+ this.models = models;
58
+ this.workerUrl = worker;
59
+ this.languages = modelLanguages.filter(lang => models[lang]);
60
+ }
61
+ this.deadlineMs = deadlineMs;
62
+ this.idleMs = idleMs;
63
+ }
64
+ start() {
65
+ const worker = new Worker(this.workerUrl, { execArgv: [], workerData: this.models });
66
+ this.worker = worker;
67
+ worker.on('message', (m) => {
68
+ const pending = this.pending.get(m.id);
69
+ if (!pending)
70
+ return;
71
+ this.pending.delete(m.id);
72
+ if (m.vectors)
73
+ pending.resolve(m.vectors);
74
+ else
75
+ pending.reject(new Error('embedding_unavailable'));
76
+ if (!this.pending.size) {
77
+ worker.unref();
78
+ this.scheduleIdleUnload(worker);
79
+ }
80
+ });
81
+ const stopped = () => {
82
+ if (this.worker !== worker)
83
+ return;
84
+ this.worker = undefined;
85
+ clearTimeout(this.idleTimer);
86
+ for (const request of this.pending.values())
87
+ request.reject(new Error('embedding_unavailable'));
88
+ this.pending.clear();
89
+ };
90
+ worker.once('error', stopped);
91
+ worker.once('exit', stopped);
92
+ return worker;
93
+ }
94
+ scheduleIdleUnload(worker) {
95
+ clearTimeout(this.idleTimer);
96
+ if (!(this.idleMs > 0) || !Number.isFinite(this.idleMs))
97
+ return;
98
+ this.idleTimer = setTimeout(() => {
99
+ // Only this exact worker, and only if nothing started using it again meanwhile.
100
+ if (this.worker === worker && !this.pending.size)
101
+ void worker.terminate();
102
+ }, this.idleMs);
103
+ this.idleTimer.unref?.();
104
+ }
105
+ encode(lang, texts) {
106
+ if (!this.languages.includes(lang))
107
+ return Promise.reject(new Error('embedding_unavailable'));
108
+ clearTimeout(this.idleTimer);
109
+ const worker = this.worker ?? this.start(), id = ++this.serial;
110
+ worker.ref();
111
+ return new Promise((resolve, reject) => {
112
+ const timer = setTimeout(() => {
113
+ // The worker received this request but never answered it: replace the worker so a
114
+ // stalled inference call doesn't starve every request queued behind it forever, not
115
+ // just this one. The 'exit' handler above settles this and every other pending request.
116
+ if (this.worker === worker)
117
+ void worker.terminate();
118
+ }, this.deadlineMs);
119
+ timer.unref?.();
120
+ this.pending.set(id, {
121
+ resolve: (v) => {
122
+ clearTimeout(timer);
123
+ resolve(v);
124
+ },
125
+ reject: (e) => {
126
+ clearTimeout(timer);
127
+ reject(e);
128
+ },
129
+ });
130
+ worker.postMessage({ id, lang, texts });
131
+ });
132
+ }
133
+ close() {
134
+ clearTimeout(this.idleTimer);
135
+ if (this.worker)
136
+ void this.worker.terminate();
137
+ }
138
+ }