@wwwfz/dsh-agent-bridge 0.8.3 → 0.10.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 (45) hide show
  1. package/README.md +132 -194
  2. package/THIRD_PARTY_NOTICES.md +67 -0
  3. package/cordis.patch.yml +4 -4
  4. package/package.json +40 -40
  5. package/src/assets.js +405 -348
  6. package/src/catalog.js +999 -605
  7. package/src/client.js +883 -4
  8. package/src/config.js +88 -88
  9. package/src/conversation-readers.js +198 -0
  10. package/src/conversation-store.js +583 -0
  11. package/src/export.js +273 -12
  12. package/src/index.js +282 -136
  13. package/src/native-transcript.js +217 -0
  14. package/src/project-archive.js +145 -145
  15. package/src/projects.js +1837 -980
  16. package/src/session-import.js +138 -93
  17. package/src/session-trace.js +121 -0
  18. package/src/skill-handoff.js +1327 -0
  19. package/src/skill-package.js +417 -0
  20. package/src/skill-provider.js +249 -0
  21. package/src/watch.js +319 -309
  22. package/web/Geist-OFL.txt +93 -93
  23. package/web/agent-icons/NOTICE.md +19 -19
  24. package/web/agent-icons/antigravity.svg +76 -76
  25. package/web/agent-icons/claude.svg +3 -3
  26. package/web/agent-icons/dsh.svg +58 -58
  27. package/web/agent-icons/licenses/copilot.txt +21 -21
  28. package/web/agent-icons/licenses/dsh.txt +21 -21
  29. package/web/agent-icons/licenses/gemini.txt +201 -201
  30. package/web/agent-icons/licenses/opencode.txt +21 -21
  31. package/web/agent-icons/licenses/qoder-notice.txt +18 -18
  32. package/web/agent-icons/licenses/qoder.txt +22 -22
  33. package/web/agent-icons/licenses/qwen.txt +202 -202
  34. package/web/agent-icons/qoder.svg +4 -4
  35. package/web/agent-icons/qwen.svg +5 -5
  36. package/web/agent-icons/workbuddy.svg +29 -29
  37. package/web/inline-process.css +22 -0
  38. package/web/markdown.js +225 -0
  39. package/web/panel.css +168 -151
  40. package/web/panel.html +82 -43
  41. package/web/panel.js +1316 -93
  42. package/web/project-context.js +25 -25
  43. package/web/reader.css +259 -0
  44. package/web/vendor/markdown-it-LICENSE.txt +156 -0
  45. package/web/vendor/markdown-it.mjs +3064 -0
package/src/assets.js CHANGED
@@ -1,348 +1,405 @@
1
- import { constants } from 'node:fs';
2
- import { lstat, open, readdir, realpath } from 'node:fs/promises';
3
- import { homedir } from 'node:os';
4
- import path from 'node:path';
5
-
6
- const MAX_ASSET_BYTES = 96 * 1024;
7
- const MAX_ASSETS_PER_ROOT = 320;
8
- const proof = Symbol('asset location');
9
- const sensitiveName = /(?:^|[._ -])(?:api[-_ ]?keys?|access[-_ ]?tokens?|auth|credentials?|passwords?|secrets?|oauth)(?:[._ -]|$)/i;
10
- const hubFolders = ['决策', '经验', '资料', '交接', '笔记'];
11
- const agentHomes = {
12
- antigravity: ['.gemini/antigravity', '.gemini/antigravity-cli'],
13
- claude: ['.claude'],
14
- codex: ['.codex'],
15
- dsh: ['.dsh'],
16
- gemini: ['.gemini'],
17
- opencode: ['.local/share/opencode'],
18
- qoder: ['.qoder-cn', '.qoder'],
19
- qwen: ['.qwen'],
20
- reasonix: ['.reasonix'],
21
- trae: ['.trae-cn', '.trae'],
22
- workbuddy: ['.workbuddy'],
23
- };
24
- const projectAgentFolders = {
25
- '.agent': 'antigravity',
26
- '.claude': 'claude',
27
- '.codex': 'codex',
28
- '.dsh': 'dsh',
29
- '.gemini': 'gemini',
30
- '.opencode': 'opencode',
31
- '.qoder': 'qoder',
32
- '.qwen': 'qwen',
33
- '.trae': 'trae',
34
- '.workbuddy': 'workbuddy',
35
- };
36
- const projectInstructions = {
37
- 'AGENTS.md': 'shared',
38
- 'CLAUDE.md': 'claude',
39
- 'GEMINI.md': 'gemini',
40
- 'QWEN.md': 'qwen',
41
- 'MEMORY.md': 'shared',
42
- };
43
-
44
- function canonicalKey(file) {
45
- const normalized = path.normalize(file);
46
- return process.platform === 'win32' ? normalized.toLowerCase() : normalized;
47
- }
48
-
49
- function inside(root, file) {
50
- const relative = path.relative(canonicalKey(root), canonicalKey(file));
51
- return relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
52
- }
53
-
54
- function sameFile(first, second) {
55
- return first.dev === second.dev && first.ino === second.ino;
56
- }
57
-
58
- async function directory(file) {
59
- if (typeof file !== 'string' || !path.isAbsolute(file) || file === path.parse(file).root) return null;
60
- try {
61
- const resolved = await realpath(file);
62
- return (await lstat(resolved)).isDirectory() ? resolved : null;
63
- } catch {
64
- return null;
65
- }
66
- }
67
-
68
- async function children(root, child = '.') {
69
- try {
70
- const target = await realpath(path.join(root, child));
71
- if (!inside(root, target)) return [];
72
- const entries = await readdir(target, { withFileTypes: true });
73
- return entries.sort((a, b) => a.name.localeCompare(b.name)).slice(0, MAX_ASSETS_PER_ROOT);
74
- } catch {
75
- return [];
76
- }
77
- }
78
-
79
- async function located(file, root) {
80
- const resolved = await realpath(file);
81
- if (!inside(root, resolved) || canonicalKey(file) !== canonicalKey(resolved)) {
82
- throw new Error('Asset path changed or is outside its source root');
83
- }
84
- const info = await lstat(file, { bigint: true });
85
- if (!info.isFile() || info.nlink > 1n) throw new Error('Asset is not a regular, unlinked file');
86
- return info;
87
- }
88
-
89
- async function recordAsset(root, file, meta) {
90
- try {
91
- const info = await located(file, root);
92
- const revision = `${info.ino}:${info.mtimeNs}:${info.size}`;
93
- return { ...meta, file, revision, [proof]: { root, file, info } };
94
- } catch {
95
- return null;
96
- }
97
- }
98
-
99
- export async function readAsset(item) {
100
- const source = item?.[proof];
101
- if (!source || source.file !== item.file) throw new Error('Asset source is unavailable');
102
- const current = await located(source.file, source.root);
103
- if (!sameFile(source.info, current)) throw new Error('Asset changed since discovery');
104
- const handle = await open(source.file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
105
- try {
106
- const opened = await handle.stat({ bigint: true });
107
- const confirmed = await located(source.file, source.root);
108
- if (!sameFile(current, opened) || !sameFile(opened, confirmed)) throw new Error('Asset changed while opening');
109
- const bytes = Buffer.alloc(MAX_ASSET_BYTES + 1);
110
- let length = 0;
111
- while (length < bytes.length) {
112
- const { bytesRead } = await handle.read(bytes, length, bytes.length - length, length);
113
- if (bytesRead === 0) break;
114
- length += bytesRead;
115
- }
116
- const completed = await handle.stat({ bigint: true });
117
- if (opened.size !== completed.size || opened.mtimeNs !== completed.mtimeNs || opened.ctimeNs !== completed.ctimeNs) {
118
- throw new Error('Asset changed while reading');
119
- }
120
- const truncated = length > MAX_ASSET_BYTES;
121
- const text = new TextDecoder('utf-8', { fatal: true }).decode(bytes.subarray(0, Math.min(length, MAX_ASSET_BYTES)), {
122
- stream: truncated,
123
- });
124
- if (text.includes('\0')) throw new Error('Asset is not UTF-8 text');
125
- return { text, truncated };
126
- } finally {
127
- await handle.close();
128
- }
129
- }
130
-
131
- function agentId(value) {
132
- const label = String(value).toLowerCase().trim();
133
- if (label.startsWith('open-code')) return 'opencode';
134
- return Object.keys(agentHomes).find((agent) => label.startsWith(agent))
135
- ?? (label.startsWith('deepseek') ? 'dsh' : label);
136
- }
137
-
138
- function noteName(name) {
139
- return !name.startsWith('.') && /\.md$/i.test(name) && !sensitiveName.test(name);
140
- }
141
-
142
- async function addNote(items, root, relative, agent, scope, detail) {
143
- if (!noteName(path.basename(relative))) return;
144
- const note = await recordAsset(root, path.join(root, relative), {
145
- agent, scope, detail, name: path.basename(relative, path.extname(relative)),
146
- });
147
- if (note) items.push(note);
148
- }
149
-
150
- async function notesIn(items, root, folder, agent, scope, detail) {
151
- const entries = await children(root, folder);
152
- await Promise.all(entries.filter((entry) => entry.isFile() && noteName(entry.name)).map((entry) => (
153
- addNote(items, root, path.join(folder, entry.name), agent, scope, detail)
154
- )));
155
- }
156
-
157
- function registryPaths(text) {
158
- return [...text.matchAll(/^(?:canonicalPath:|\s+path:)[ \t]+([^\r\n]+)$/gm)].map((match) => {
159
- const value = match[1].trim();
160
- if (value.startsWith("'") && value.endsWith("'")) return value.slice(1, -1).replaceAll("''", "'");
161
- if (value.startsWith('"') && value.endsWith('"')) {
162
- try { return JSON.parse(value); } catch { return ''; }
163
- }
164
- return value;
165
- }).filter((value) => typeof value === 'string' && path.isAbsolute(value));
166
- }
167
-
168
- async function hubNotes(items, root, cwd, projectIds) {
169
- for (const id of projectIds.filter((value) => /^P\d{3,}$/.test(value))) {
170
- const folder = path.join('项目档案', id);
171
- const record = await recordAsset(root, path.join(root, folder, 'project.yaml'), {});
172
- if (!record) continue;
173
- try {
174
- const { text, truncated } = await readAsset(record);
175
- if (truncated) continue;
176
- const directories = await Promise.all(registryPaths(text).map(directory));
177
- if (!directories.some((directory) => directory && canonicalKey(directory) === canonicalKey(cwd))) continue;
178
- } catch {
179
- continue;
180
- }
181
- await Promise.all(['.', ...hubFolders].map((subfolder) => (
182
- notesIn(items, root, path.join(folder, subfolder), 'workspacehub', 'shared', `${id} · ${subfolder === '.' ? '项目记忆' : subfolder}`)
183
- )));
184
- }
185
- }
186
-
187
- async function exportedNotes(items, cwd, memoryExports) {
188
- await Promise.all(Object.entries(memoryExports ?? {}).map(async ([workspace, paths]) => {
189
- const projectRoot = await directory(workspace);
190
- if (!projectRoot || canonicalKey(projectRoot) !== canonicalKey(cwd)) return;
191
- await Promise.all(paths.map(async (source) => {
192
- if (typeof source !== 'string' || !path.isAbsolute(source)) return;
193
- const folder = await directory(source);
194
- if (folder) {
195
- await notesIn(items, folder, '.', 'export', 'project', '配置的记忆导出');
196
- return;
197
- }
198
- const parent = await directory(path.dirname(source));
199
- if (parent) await addNote(items, parent, path.basename(source), 'export', 'project', '配置的记忆导出');
200
- }));
201
- }));
202
- }
203
-
204
- async function nativeNotes(items, root, cwd, agent) {
205
- const globalFolders = {
206
- antigravity: ['knowledge'], claude: ['agent-memory'],
207
- codex: ['memories', 'memories_v2', 'memories/extensions/ad_hoc/notes', 'memories_v2/extensions/ad_hoc/notes'],
208
- dsh: ['diary'], opencode: ['memory'], qoder: ['memory', 'qoder-knowledge'], reasonix: ['memory/global'],
209
- trae: ['memory'], workbuddy: ['memory'],
210
- };
211
- for (const folder of globalFolders[agent] ?? []) {
212
- await notesIn(items, root, folder, agent, 'agent', '智能体记忆');
213
- if (agent === 'claude' || agent === 'antigravity') {
214
- const buckets = await children(root, folder);
215
- await Promise.all(buckets.filter((entry) => entry.isDirectory() && !entry.name.startsWith('.')).map((entry) => (
216
- notesIn(items, root, path.join(folder, entry.name, agent === 'antigravity' ? 'artifacts' : ''), agent, 'agent', entry.name)
217
- )));
218
- }
219
- }
220
- const instructionFiles = {
221
- claude: ['CLAUDE.md'], codex: ['AGENTS.md'], dsh: ['AGENTS.md'], gemini: ['GEMINI.md'],
222
- opencode: ['AGENTS.md', 'MEMORY.md'], qwen: ['QWEN.md'], workbuddy: ['USER.md', 'SOUL.md', 'MEMORY.md'],
223
- };
224
- await Promise.all((instructionFiles[agent] ?? []).map((name) => addNote(items, root, name, agent, 'agent', '用户指引')));
225
- if (cwd && ['claude', 'qoder', 'qwen'].includes(agent)) {
226
- const slug = cwd.replace(/[^\p{L}\p{N}]/gu, '-');
227
- const asciiSlug = cwd.replace(/[^a-zA-Z0-9]/g, '-');
228
- for (const name of new Set([slug, asciiSlug, slug.toLowerCase()])) {
229
- await notesIn(items, root, path.join('projects', name, 'memory'), agent, 'project', '原生工作区记忆');
230
- }
231
- }
232
- }
233
-
234
- async function skillFolder(items, root, relative, agent, scope, linkedRoots, detail, includeSystem = true) {
235
- const entries = await children(root, relative);
236
- for (const entry of entries) {
237
- if ((!entry.isDirectory() && !entry.isSymbolicLink()) || (entry.name.startsWith('.') && entry.name !== '.system')) continue;
238
- const child = path.join(relative, entry.name);
239
- if (entry.name === '.system' && includeSystem && entry.isDirectory()) {
240
- await skillFolder(items, root, child, agent, scope, linkedRoots, detail, false);
241
- continue;
242
- }
243
- const target = await directory(path.join(root, child));
244
- const boundary = target && [root, ...linkedRoots].find((candidate) => inside(candidate, target));
245
- if (!boundary) continue;
246
- const item = await recordAsset(boundary, path.join(target, 'SKILL.md'), { name: entry.name, agent, scope, detail });
247
- if (item) items.push(item);
248
- }
249
- }
250
-
251
- async function cachedPluginSkills(items, root, agent) {
252
- const cache = 'plugins/cache';
253
- for (const market of (await children(root, cache)).filter((entry) => entry.isDirectory() && !entry.name.startsWith('.'))) {
254
- const marketFolder = path.join(cache, market.name);
255
- const packages = (await children(root, marketFolder)).filter((entry) => entry.isDirectory() && !entry.name.startsWith('.'));
256
- await Promise.all(packages.map(async (plugin) => {
257
- const packageFolder = path.join(marketFolder, plugin.name);
258
- const versions = (await children(root, packageFolder)).filter((entry) => entry.isDirectory() && !entry.name.startsWith('.'));
259
- versions.sort((a, b) => b.name.localeCompare(a.name, undefined, { numeric: true }));
260
- for (const version of versions) {
261
- const found = [];
262
- await skillFolder(found, root, path.join(packageFolder, version.name, 'skills'), agent, 'agent', [], `${plugin.name} · ${version.name} · 本地缓存`);
263
- if (found.length) {
264
- items.push(...found);
265
- break;
266
- }
267
- }
268
- }));
269
- }
270
- }
271
-
272
- function unique(items) {
273
- const indexed = new Map();
274
- for (const item of items) {
275
- const key = `${item.agent}:${item.scope}:${canonicalKey(item.file)}`;
276
- if (!indexed.has(key)) indexed.set(key, item);
277
- }
278
- return [...indexed.values()].sort((a, b) => a.agent.localeCompare(b.agent) || a.name.localeCompare(b.name));
279
- }
280
-
281
- export async function listProjectAssets(project, config = {}) {
282
- const home = config.home ?? homedir();
283
- const cwd = await directory(project.cwd);
284
- const hubs = (await Promise.all((config.workspaceHubRoots ?? []).map(directory))).filter(Boolean);
285
- const sharedCandidates = [
286
- path.join(home, '.agents/skills'), path.join(home, '.config/skillshare/skills'),
287
- path.join(home, '.skillshare/skills'), path.join(home, 'AppData/Roaming/skillshare/skills'),
288
- ...(config.skillRoots ?? []), ...hubs.map((root) => path.join(root, 'skills/source')),
289
- ];
290
- const sharedRoots = [...new Set((await Promise.all(sharedCandidates.map(directory))).filter(Boolean))];
291
- const agents = new Set((project.agents ?? []).map(agentId));
292
- const configured = Object.entries(config.agentRoots ?? {});
293
- const memories = [];
294
- const skills = [];
295
-
296
- if (cwd) {
297
- const instructions = Object.entries(projectInstructions).map(([file, agent]) => addNote(memories, cwd, file, agent, 'project', '项目指引'));
298
- const folders = Object.entries(projectAgentFolders).map(async ([folder, agent]) => {
299
- await Promise.all([
300
- notesIn(memories, cwd, path.join(folder, 'memory'), agent, 'project', '项目记忆'),
301
- ...Object.entries(projectInstructions).filter(([, owner]) => owner === agent).map(([file]) => (
302
- addNote(memories, cwd, path.join(folder, file), agent, 'project', '项目指引')
303
- )),
304
- skillFolder(skills, cwd, path.join(folder, 'skills'), agent, 'project', sharedRoots, '项目 Skill'),
305
- ]);
306
- });
307
- await Promise.all([
308
- ...instructions, ...folders,
309
- notesIn(memories, cwd, '.agent-bridge/memory', 'shared', 'project', '项目共享记忆'),
310
- notesIn(memories, cwd, '.agent-bridge/handoffs', 'shared', 'project', '项目交接'),
311
- ...hubs.map((root) => hubNotes(memories, root, cwd, project.projectIds ?? [])),
312
- exportedNotes(memories, cwd, config.memoryExports),
313
- ...['.agents/skills', '.skillshare/skills', 'skills'].map((folder) => (
314
- skillFolder(skills, cwd, folder, 'shared', 'project', sharedRoots, '项目 Skill')
315
- )),
316
- ]);
317
- }
318
-
319
- await Promise.all([
320
- ...sharedRoots.map((root) => skillFolder(skills, root, '.', 'shared', 'shared', sharedRoots, '共享 Skill')),
321
- ...[...agents].map(async (agent) => {
322
- const overrides = configured.filter(([name]) => agentId(name) === agent);
323
- const candidates = overrides.length
324
- ? overrides.flatMap(([, roots]) => roots)
325
- : (agentHomes[agent] ?? []).map((folder) => path.join(home, folder));
326
- const roots = [...new Set((await Promise.all(candidates.map(directory))).filter(Boolean))];
327
- if (agent === 'opencode') {
328
- const configDirs = config.opencodeSkillRoots ?? [path.join(home, '.config/opencode')];
329
- const configRoots = (await Promise.all(configDirs.map(directory))).filter(Boolean);
330
- const memoryRoots = [...new Set([...roots, ...configRoots])];
331
- const skillRoots = config.opencodeSkillRoots === undefined ? memoryRoots : [...new Set(configRoots)];
332
- await Promise.all([
333
- ...memoryRoots.map((root) => nativeNotes(memories, root, cwd, agent)),
334
- ...skillRoots.flatMap((root) => ['skills', 'skill'].map((folder) => (
335
- skillFolder(skills, root, folder, agent, 'agent', sharedRoots, '智能体 Skill')
336
- ))),
337
- ]);
338
- return;
339
- }
340
- await Promise.all(roots.flatMap((root) => [
341
- nativeNotes(memories, root, cwd, agent),
342
- skillFolder(skills, root, 'skills', agent, 'agent', sharedRoots, '智能体 Skill'),
343
- ...(['claude', 'codex'].includes(agent) ? [cachedPluginSkills(skills, root, agent)] : []),
344
- ]));
345
- }),
346
- ]);
347
- return { memories: unique(memories), skills: unique(skills) };
348
- }
1
+ import { constants } from 'node:fs';
2
+ import { lstat, open, readdir, realpath } from 'node:fs/promises';
3
+ import { homedir } from 'node:os';
4
+ import path from 'node:path';
5
+
6
+ const MAX_ASSET_BYTES = 96 * 1024;
7
+ const MAX_ASSETS_PER_ROOT = 320;
8
+ const proof = Symbol('asset location');
9
+ const sensitiveName = /(?:^|[._ -])(?:api[-_ ]?keys?|access[-_ ]?tokens?|auth|credentials?|passwords?|secrets?|oauth)(?:[._ -]|$)/i;
10
+ const openableReference = /\.(?:md|markdown|mdx|txt|rst|log|csv|tsv|jsonc?|ya?ml|toml|xml|css|tsx?|jsx|rs|go|java|kt|cs|c|cc|cpp|h|hh|hpp|swift|sql|pdf|png|jpe?g|gif|webp)$/i;
11
+ const hubFolders = ['决策', '经验', '资料', '交接', '笔记'];
12
+ const agentHomes = {
13
+ antigravity: ['.gemini/antigravity', '.gemini/antigravity-cli'],
14
+ claude: ['.claude'],
15
+ codex: ['.codex'],
16
+ dsh: ['.dsh'],
17
+ gemini: ['.gemini'],
18
+ opencode: ['.local/share/opencode'],
19
+ qoder: ['.qoder-cn', '.qoder'],
20
+ qwen: ['.qwen'],
21
+ reasonix: ['.reasonix'],
22
+ trae: ['.trae-cn', '.trae'],
23
+ workbuddy: ['.workbuddy'],
24
+ };
25
+ const projectAgentFolders = {
26
+ '.agent': 'antigravity',
27
+ '.claude': 'claude',
28
+ '.codex': 'codex',
29
+ '.dsh': 'dsh',
30
+ '.gemini': 'gemini',
31
+ '.opencode': 'opencode',
32
+ '.qoder': 'qoder',
33
+ '.qwen': 'qwen',
34
+ '.trae': 'trae',
35
+ '.workbuddy': 'workbuddy',
36
+ };
37
+ const projectInstructions = {
38
+ 'AGENTS.md': 'shared',
39
+ 'CLAUDE.md': 'claude',
40
+ 'GEMINI.md': 'gemini',
41
+ 'QWEN.md': 'qwen',
42
+ 'MEMORY.md': 'shared',
43
+ };
44
+
45
+ function canonicalKey(file) {
46
+ const normalized = path.normalize(file);
47
+ return process.platform === 'win32' ? normalized.toLowerCase() : normalized;
48
+ }
49
+
50
+ function inside(root, file) {
51
+ const relative = path.relative(canonicalKey(root), canonicalKey(file));
52
+ return relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
53
+ }
54
+
55
+ function sameFile(first, second) {
56
+ return first.dev === second.dev && first.ino === second.ino;
57
+ }
58
+
59
+ function sourceChanged(message) {
60
+ return Object.assign(new Error(message), { code: 'ASSET_SOURCE_CHANGED' });
61
+ }
62
+
63
+ async function directory(file) {
64
+ if (typeof file !== 'string' || !path.isAbsolute(file) || file === path.parse(file).root) return null;
65
+ try {
66
+ const resolved = await realpath(file);
67
+ return (await lstat(resolved)).isDirectory() ? resolved : null;
68
+ } catch {
69
+ return null;
70
+ }
71
+ }
72
+
73
+ async function children(root, child = '.') {
74
+ try {
75
+ const target = await realpath(path.join(root, child));
76
+ if (!inside(root, target)) return [];
77
+ const entries = await readdir(target, { withFileTypes: true });
78
+ return entries.sort((a, b) => a.name.localeCompare(b.name)).slice(0, MAX_ASSETS_PER_ROOT);
79
+ } catch {
80
+ return [];
81
+ }
82
+ }
83
+
84
+ async function locateSource(file, root) {
85
+ if (typeof file !== 'string' || !path.isAbsolute(file)
86
+ || typeof root !== 'string' || !path.isAbsolute(root)) {
87
+ throw sourceChanged('Asset source is not an absolute path');
88
+ }
89
+ const resolved = await realpath(file);
90
+ if (!inside(root, resolved) || canonicalKey(file) !== canonicalKey(resolved)) {
91
+ throw sourceChanged('Asset path changed or is outside its source root');
92
+ }
93
+ const directory = path.dirname(file);
94
+ const resolvedDirectory = await realpath(directory);
95
+ if (!inside(root, resolvedDirectory) || canonicalKey(directory) !== canonicalKey(resolvedDirectory)) {
96
+ throw sourceChanged('Asset directory changed or is outside its source root');
97
+ }
98
+ const directoryInfo = await lstat(directory, { bigint: true });
99
+ if (!directoryInfo.isDirectory() || directoryInfo.isSymbolicLink()) {
100
+ throw sourceChanged('Asset directory is not a regular directory');
101
+ }
102
+ const info = await lstat(file, { bigint: true });
103
+ if (!info.isFile() || info.nlink > 1n) throw sourceChanged('Asset is not a regular, unlinked file');
104
+ return { root, file, directory, fileInfo: info, directoryInfo };
105
+ }
106
+
107
+ export async function authorizeProjectReference(root, documentFile, href) {
108
+ let relative;
109
+ try { relative = decodeURIComponent(href.split(/[?#]/, 1)[0]); } catch { /* Invalid URL encoding. */ }
110
+ if (!relative || /^[\/]/.test(relative) || /[\\:\u0000-\u001f]/.test(relative)) {
111
+ return { path: href, error: '文件链接格式无效。' };
112
+ }
113
+ const target = path.resolve(path.dirname(documentFile), relative);
114
+ if (!inside(root, documentFile) || !inside(root, target)) {
115
+ return { path: target, error: '文件不在项目范围内。' };
116
+ }
117
+ const name = path.basename(target);
118
+ if (sensitiveName.test(name)) {
119
+ return { path: target, error: '当前文件类型无法从正文链接打开。' };
120
+ }
121
+ try {
122
+ const revealOnly = !openableReference.test(name);
123
+ return { path: target, authorization: await locateSource(target, root), revealOnly };
124
+ } catch {
125
+ return { path: target, error: '文件已移动、不可访问或指向项目范围外。' };
126
+ }
127
+ }
128
+
129
+ async function recordAsset(root, file, meta) {
130
+ try {
131
+ const source = await locateSource(file, root);
132
+ const { fileInfo } = source;
133
+ const revision = `${fileInfo.ino}:${fileInfo.mtimeNs}:${fileInfo.size}`;
134
+ return { ...meta, file, revision, [proof]: source };
135
+ } catch {
136
+ return null;
137
+ }
138
+ }
139
+
140
+ export async function verifyAssetSource(item) {
141
+ const source = item?.[proof];
142
+ if (!source || source.file !== item.file) throw sourceChanged('Asset source is unavailable');
143
+ return verifySourceAuthorization(source);
144
+ }
145
+
146
+ export async function verifySourceAuthorization(authorization) {
147
+ if (!authorization || typeof authorization !== 'object') throw sourceChanged('Asset authorization is unavailable');
148
+ const current = await locateSource(authorization.file, authorization.root);
149
+ if (!sameFile(authorization.fileInfo, current.fileInfo)
150
+ || !sameFile(authorization.directoryInfo, current.directoryInfo)) {
151
+ throw sourceChanged('Asset changed since discovery');
152
+ }
153
+ return current;
154
+ }
155
+
156
+ export async function readAsset(item) {
157
+ const source = await verifyAssetSource(item);
158
+ const handle = await open(source.file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
159
+ try {
160
+ const opened = await handle.stat({ bigint: true });
161
+ const confirmed = await verifySourceAuthorization(source);
162
+ if (!sameFile(source.fileInfo, opened) || !sameFile(source.directoryInfo, confirmed.directoryInfo)
163
+ || !sameFile(opened, confirmed.fileInfo)) {
164
+ throw new Error('Asset changed while opening');
165
+ }
166
+ const bytes = Buffer.alloc(MAX_ASSET_BYTES + 1);
167
+ let length = 0;
168
+ while (length < bytes.length) {
169
+ const { bytesRead } = await handle.read(bytes, length, bytes.length - length, length);
170
+ if (bytesRead === 0) break;
171
+ length += bytesRead;
172
+ }
173
+ const completed = await handle.stat({ bigint: true });
174
+ if (opened.size !== completed.size || opened.mtimeNs !== completed.mtimeNs || opened.ctimeNs !== completed.ctimeNs) {
175
+ throw new Error('Asset changed while reading');
176
+ }
177
+ const truncated = length > MAX_ASSET_BYTES;
178
+ const text = new TextDecoder('utf-8', { fatal: true }).decode(bytes.subarray(0, Math.min(length, MAX_ASSET_BYTES)), {
179
+ stream: truncated,
180
+ });
181
+ if (text.includes('\0')) throw new Error('Asset is not UTF-8 text');
182
+ return { text, truncated };
183
+ } finally {
184
+ await handle.close();
185
+ }
186
+ }
187
+
188
+ function agentId(value) {
189
+ const label = String(value).toLowerCase().trim();
190
+ if (label.startsWith('open-code')) return 'opencode';
191
+ return Object.keys(agentHomes).find((agent) => label.startsWith(agent))
192
+ ?? (label.startsWith('deepseek') ? 'dsh' : label);
193
+ }
194
+
195
+ function noteName(name) {
196
+ return !name.startsWith('.') && /\.md$/i.test(name) && !sensitiveName.test(name);
197
+ }
198
+
199
+ async function addNote(items, root, relative, agent, scope, detail) {
200
+ if (!noteName(path.basename(relative))) return;
201
+ const note = await recordAsset(root, path.join(root, relative), {
202
+ agent, scope, detail, name: path.basename(relative, path.extname(relative)),
203
+ });
204
+ if (note) items.push(note);
205
+ }
206
+
207
+ async function notesIn(items, root, folder, agent, scope, detail) {
208
+ const entries = await children(root, folder);
209
+ await Promise.all(entries.filter((entry) => entry.isFile() && noteName(entry.name)).map((entry) => (
210
+ addNote(items, root, path.join(folder, entry.name), agent, scope, detail)
211
+ )));
212
+ }
213
+
214
+ function registryPaths(text) {
215
+ return [...text.matchAll(/^(?:canonicalPath:|\s+path:)[ \t]+([^\r\n]+)$/gm)].map((match) => {
216
+ const value = match[1].trim();
217
+ if (value.startsWith("'") && value.endsWith("'")) return value.slice(1, -1).replaceAll("''", "'");
218
+ if (value.startsWith('"') && value.endsWith('"')) {
219
+ try { return JSON.parse(value); } catch { return ''; }
220
+ }
221
+ return value;
222
+ }).filter((value) => typeof value === 'string' && path.isAbsolute(value));
223
+ }
224
+
225
+ async function hubNotes(items, root, cwd, projectIds) {
226
+ for (const id of projectIds.filter((value) => /^P\d{3,}$/.test(value))) {
227
+ const folder = path.join('项目档案', id);
228
+ const record = await recordAsset(root, path.join(root, folder, 'project.yaml'), {});
229
+ if (!record) continue;
230
+ try {
231
+ const { text, truncated } = await readAsset(record);
232
+ if (truncated) continue;
233
+ const directories = await Promise.all(registryPaths(text).map(directory));
234
+ if (!directories.some((directory) => directory && canonicalKey(directory) === canonicalKey(cwd))) continue;
235
+ } catch {
236
+ continue;
237
+ }
238
+ await Promise.all(['.', ...hubFolders].map((subfolder) => (
239
+ notesIn(items, root, path.join(folder, subfolder), 'workspacehub', 'shared', `${id} · ${subfolder === '.' ? '项目记忆' : subfolder}`)
240
+ )));
241
+ }
242
+ }
243
+
244
+ async function exportedNotes(items, cwd, memoryExports) {
245
+ await Promise.all(Object.entries(memoryExports ?? {}).map(async ([workspace, paths]) => {
246
+ const projectRoot = await directory(workspace);
247
+ if (!projectRoot || canonicalKey(projectRoot) !== canonicalKey(cwd)) return;
248
+ await Promise.all(paths.map(async (source) => {
249
+ if (typeof source !== 'string' || !path.isAbsolute(source)) return;
250
+ const folder = await directory(source);
251
+ if (folder) {
252
+ await notesIn(items, folder, '.', 'export', 'project', '配置的记忆导出');
253
+ return;
254
+ }
255
+ const parent = await directory(path.dirname(source));
256
+ if (parent) await addNote(items, parent, path.basename(source), 'export', 'project', '配置的记忆导出');
257
+ }));
258
+ }));
259
+ }
260
+
261
+ async function nativeNotes(items, root, cwd, agent) {
262
+ const globalFolders = {
263
+ antigravity: ['knowledge'], claude: ['agent-memory'],
264
+ codex: ['memories', 'memories_v2', 'memories/extensions/ad_hoc/notes', 'memories_v2/extensions/ad_hoc/notes'],
265
+ dsh: ['diary'], opencode: ['memory'], qoder: ['memory', 'qoder-knowledge'], reasonix: ['memory/global'],
266
+ trae: ['memory'], workbuddy: ['memory'],
267
+ };
268
+ for (const folder of globalFolders[agent] ?? []) {
269
+ await notesIn(items, root, folder, agent, 'agent', '智能体记忆');
270
+ if (agent === 'claude' || agent === 'antigravity') {
271
+ const buckets = await children(root, folder);
272
+ await Promise.all(buckets.filter((entry) => entry.isDirectory() && !entry.name.startsWith('.')).map((entry) => (
273
+ notesIn(items, root, path.join(folder, entry.name, agent === 'antigravity' ? 'artifacts' : ''), agent, 'agent', entry.name)
274
+ )));
275
+ }
276
+ }
277
+ const instructionFiles = {
278
+ claude: ['CLAUDE.md'], codex: ['AGENTS.md'], dsh: ['AGENTS.md'], gemini: ['GEMINI.md'],
279
+ opencode: ['AGENTS.md', 'MEMORY.md'], qwen: ['QWEN.md'], workbuddy: ['USER.md', 'SOUL.md', 'MEMORY.md'],
280
+ };
281
+ await Promise.all((instructionFiles[agent] ?? []).map((name) => addNote(items, root, name, agent, 'agent', '用户指引')));
282
+ if (cwd && ['claude', 'qoder', 'qwen'].includes(agent)) {
283
+ const slug = cwd.replace(/[^\p{L}\p{N}]/gu, '-');
284
+ const asciiSlug = cwd.replace(/[^a-zA-Z0-9]/g, '-');
285
+ for (const name of new Set([slug, asciiSlug, slug.toLowerCase()])) {
286
+ await notesIn(items, root, path.join('projects', name, 'memory'), agent, 'project', '原生工作区记忆');
287
+ }
288
+ }
289
+ }
290
+
291
+ async function skillFolder(items, root, relative, agent, scope, linkedRoots, detail, includeSystem = true) {
292
+ const entries = await children(root, relative);
293
+ for (const entry of entries) {
294
+ if ((!entry.isDirectory() && !entry.isSymbolicLink()) || (entry.name.startsWith('.') && entry.name !== '.system')) continue;
295
+ const child = path.join(relative, entry.name);
296
+ if (entry.name === '.system' && includeSystem && entry.isDirectory()) {
297
+ await skillFolder(items, root, child, agent, scope, linkedRoots, detail, false);
298
+ continue;
299
+ }
300
+ const target = await directory(path.join(root, child));
301
+ const boundary = target && [root, ...linkedRoots].find((candidate) => inside(candidate, target));
302
+ if (!boundary) continue;
303
+ const item = await recordAsset(boundary, path.join(target, 'SKILL.md'), { name: entry.name, agent, scope, detail });
304
+ if (item) items.push(item);
305
+ }
306
+ }
307
+
308
+ async function cachedPluginSkills(items, root, agent) {
309
+ const cache = 'plugins/cache';
310
+ for (const market of (await children(root, cache)).filter((entry) => entry.isDirectory() && !entry.name.startsWith('.'))) {
311
+ const marketFolder = path.join(cache, market.name);
312
+ const packages = (await children(root, marketFolder)).filter((entry) => entry.isDirectory() && !entry.name.startsWith('.'));
313
+ await Promise.all(packages.map(async (plugin) => {
314
+ const packageFolder = path.join(marketFolder, plugin.name);
315
+ const versions = (await children(root, packageFolder)).filter((entry) => entry.isDirectory() && !entry.name.startsWith('.'));
316
+ versions.sort((a, b) => b.name.localeCompare(a.name, undefined, { numeric: true }));
317
+ for (const version of versions) {
318
+ const found = [];
319
+ await skillFolder(found, root, path.join(packageFolder, version.name, 'skills'), agent, 'agent', [], `${plugin.name} · ${version.name} · 本地缓存`);
320
+ if (found.length) {
321
+ items.push(...found);
322
+ break;
323
+ }
324
+ }
325
+ }));
326
+ }
327
+ }
328
+
329
+ function unique(items) {
330
+ const indexed = new Map();
331
+ for (const item of items) {
332
+ const key = `${item.agent}:${item.scope}:${canonicalKey(item.file)}`;
333
+ if (!indexed.has(key)) indexed.set(key, item);
334
+ }
335
+ return [...indexed.values()].sort((a, b) => a.agent.localeCompare(b.agent) || a.name.localeCompare(b.name));
336
+ }
337
+
338
+ export async function listProjectAssets(project, config = {}) {
339
+ const home = config.home ?? homedir();
340
+ const cwd = await directory(project.cwd);
341
+ const hubs = (await Promise.all((config.workspaceHubRoots ?? []).map(directory))).filter(Boolean);
342
+ const sharedCandidates = [
343
+ path.join(home, '.agents/skills'), path.join(home, '.config/skillshare/skills'),
344
+ path.join(home, '.skillshare/skills'), path.join(home, 'AppData/Roaming/skillshare/skills'),
345
+ ...(config.skillRoots ?? []), ...hubs.map((root) => path.join(root, 'skills/source')),
346
+ ];
347
+ const sharedRoots = [...new Set((await Promise.all(sharedCandidates.map(directory))).filter(Boolean))];
348
+ const agents = new Set((project.agents ?? []).map(agentId));
349
+ const configured = Object.entries(config.agentRoots ?? {});
350
+ const memories = [];
351
+ const skills = [];
352
+
353
+ if (cwd) {
354
+ const instructions = Object.entries(projectInstructions).map(([file, agent]) => addNote(memories, cwd, file, agent, 'project', '项目指引'));
355
+ const folders = Object.entries(projectAgentFolders).map(async ([folder, agent]) => {
356
+ await Promise.all([
357
+ notesIn(memories, cwd, path.join(folder, 'memory'), agent, 'project', '项目记忆'),
358
+ ...Object.entries(projectInstructions).filter(([, owner]) => owner === agent).map(([file]) => (
359
+ addNote(memories, cwd, path.join(folder, file), agent, 'project', '项目指引')
360
+ )),
361
+ skillFolder(skills, cwd, path.join(folder, 'skills'), agent, 'project', sharedRoots, '项目 Skill'),
362
+ ]);
363
+ });
364
+ await Promise.all([
365
+ ...instructions, ...folders,
366
+ notesIn(memories, cwd, '.agent-bridge/memory', 'shared', 'project', '项目共享记忆'),
367
+ notesIn(memories, cwd, '.agent-bridge/handoffs', 'shared', 'project', '项目交接'),
368
+ ...hubs.map((root) => hubNotes(memories, root, cwd, project.projectIds ?? [])),
369
+ exportedNotes(memories, cwd, config.memoryExports),
370
+ ...['.agents/skills', '.skillshare/skills', 'skills'].map((folder) => (
371
+ skillFolder(skills, cwd, folder, 'shared', 'project', sharedRoots, '项目 Skill')
372
+ )),
373
+ ]);
374
+ }
375
+
376
+ await Promise.all([
377
+ ...sharedRoots.map((root) => skillFolder(skills, root, '.', 'shared', 'shared', sharedRoots, '共享 Skill')),
378
+ ...[...agents].map(async (agent) => {
379
+ const overrides = configured.filter(([name]) => agentId(name) === agent);
380
+ const candidates = overrides.length
381
+ ? overrides.flatMap(([, roots]) => roots)
382
+ : (agentHomes[agent] ?? []).map((folder) => path.join(home, folder));
383
+ const roots = [...new Set((await Promise.all(candidates.map(directory))).filter(Boolean))];
384
+ if (agent === 'opencode') {
385
+ const configDirs = config.opencodeSkillRoots ?? [path.join(home, '.config/opencode')];
386
+ const configRoots = (await Promise.all(configDirs.map(directory))).filter(Boolean);
387
+ const memoryRoots = [...new Set([...roots, ...configRoots])];
388
+ const skillRoots = config.opencodeSkillRoots === undefined ? memoryRoots : [...new Set(configRoots)];
389
+ await Promise.all([
390
+ ...memoryRoots.map((root) => nativeNotes(memories, root, cwd, agent)),
391
+ ...skillRoots.flatMap((root) => ['skills', 'skill'].map((folder) => (
392
+ skillFolder(skills, root, folder, agent, 'agent', sharedRoots, '智能体 Skill')
393
+ ))),
394
+ ]);
395
+ return;
396
+ }
397
+ await Promise.all(roots.flatMap((root) => [
398
+ nativeNotes(memories, root, cwd, agent),
399
+ skillFolder(skills, root, 'skills', agent, 'agent', sharedRoots, '智能体 Skill'),
400
+ ...(['claude', 'codex'].includes(agent) ? [cachedPluginSkills(skills, root, agent)] : []),
401
+ ]));
402
+ }),
403
+ ]);
404
+ return { memories: unique(memories), skills: unique(skills) };
405
+ }