cladogram 0.5.5-beta.5 → 0.5.5-beta.7
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/README.md +2 -2
- package/docs/release.md +13 -0
- package/package.json +2 -4
- package/plugins/agent/index.js +1875 -357
- package/plugins/agent/style.css +1209 -324
- package/plugins/brand/index.js +211 -3
- package/plugins/brand/style.css +18 -14
- package/plugins/directory/style.css +110 -40
- package/plugins/view-controls/style.css +4 -7
- package/src/agent/context.js +430 -0
- package/src/agent/probe.js +58 -0
- package/src/agent/runtime.js +418 -28
- package/src/agent/sessions.js +237 -32
- package/src/html/canvas-ui.css +75 -11
- package/src/html/page.js +1 -0
- package/src/html/plugin-ui.css +382 -86
- package/src/server/agent.js +818 -50
- package/src/server/assets/library-canvas.js +305 -1
- package/src/server/assets/library.html +1 -1
- package/src/server/assets/library.js +329 -5
- package/src/server/plugin-registry.js +98 -0
- package/src/server/plugin-settings.js +1 -1
- package/src/server/workspace.js +113 -8
- package/src/workspace/objects.js +125 -0
- package/docs/plugin-development.md +0 -135
- package/docs/plugin-ui.md +0 -43
|
@@ -0,0 +1,430 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 四段式前缀缓存(Prefix Cache)上下文装配器、工作区持久记忆(.clado/memory.md)与增量画布感知(Baseline @v1 + Tail Delta @v2)。
|
|
3
|
+
*
|
|
4
|
+
* 存储策略(用户确认规范):
|
|
5
|
+
* - 持久记忆 memory.md 与会话记录按子工作区隔离存储于 `<子工作区>/.clado/`,同时只读兼容根工作区 AGENTS.md / CLAUDE.md;
|
|
6
|
+
* - 人设模板与调试开关默认全局共享于 `~/.clado/agent-debug-config.json`,并支持 `<子工作区>/.clado/agent-config.json` 局部覆盖。
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { createHash } from 'node:crypto';
|
|
10
|
+
import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
11
|
+
import { join, resolve } from 'node:path';
|
|
12
|
+
import { parseDocument } from '../core/parse.js';
|
|
13
|
+
import { userTemplatePaths } from '../skill/templates.js';
|
|
14
|
+
import { scanDirectory, workspacePath } from '../workspace/documents.js';
|
|
15
|
+
import { listCanvasObjects, readCanvasObject } from '../workspace/objects.js';
|
|
16
|
+
import { PERSONA_TEMPLATES, compactMessages } from './sessions.js';
|
|
17
|
+
|
|
18
|
+
export const DEFAULT_COMPACT_PROMPT = [
|
|
19
|
+
'请将早期对话压缩为精炼的阶段摘要,保留:',
|
|
20
|
+
'1. 核心目标与业务约束;',
|
|
21
|
+
'2. 已定稿的画布卡片、Tag 锚点与代码修改;',
|
|
22
|
+
'3. 已拍板的架构决策与未完成步骤。',
|
|
23
|
+
].join('\n');
|
|
24
|
+
|
|
25
|
+
export const DEFAULT_AGENT_DEBUG_CONFIG = Object.freeze({
|
|
26
|
+
canvasMemory: 'delta', // 'delta' (智能增量) | 'outline' (仅大纲) | 'full' (每次全量) | 'off' (关闭)
|
|
27
|
+
timeInjection: 'date_only', // 'none' | 'date_only' (仅日期,保缓存) | 'tail_exact' (尾部精确时间) | 'system_head' (系统头时间,破缓存调试对比)
|
|
28
|
+
workspaceMap: true, // 是否注入轻量工作区文档与卡片标题目录索引
|
|
29
|
+
memoryEnabled: true, // 是否注入 .clado/memory.md 持久记忆
|
|
30
|
+
autoArchiveHours: 24, // 空闲会话自动归档时长:6 | 24 | 0 (不自动归档)
|
|
31
|
+
commandPermission: 'readonly_free', // 'readonly_free' (只读免审) | 'ask_always' (每次询问) | 'allow_all' (自动允许)
|
|
32
|
+
compactThresholdPct: 75, // 上下文压缩触发阈值百分比 (50 - 90)
|
|
33
|
+
compactPrompt: DEFAULT_COMPACT_PROMPT,
|
|
34
|
+
personas: Object.fromEntries(
|
|
35
|
+
PERSONA_TEMPLATES.map(p => [p.id, { prompt: p.prompt, initContext: p.initContext }]),
|
|
36
|
+
),
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
function safeReadJson(path) {
|
|
40
|
+
if (!path || !existsSync(path)) return null;
|
|
41
|
+
try {
|
|
42
|
+
const raw = JSON.parse(readFileSync(path, 'utf8'));
|
|
43
|
+
return raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : null;
|
|
44
|
+
} catch {
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function sanitizeConfig(raw = {}) {
|
|
50
|
+
const out = {
|
|
51
|
+
canvasMemory: ['delta', 'outline', 'full', 'off'].includes(raw.canvasMemory) ? raw.canvasMemory : DEFAULT_AGENT_DEBUG_CONFIG.canvasMemory,
|
|
52
|
+
timeInjection: ['none', 'date_only', 'tail_exact', 'system_head'].includes(raw.timeInjection) ? raw.timeInjection : DEFAULT_AGENT_DEBUG_CONFIG.timeInjection,
|
|
53
|
+
workspaceMap: typeof raw.workspaceMap === 'boolean' ? raw.workspaceMap : DEFAULT_AGENT_DEBUG_CONFIG.workspaceMap,
|
|
54
|
+
memoryEnabled: typeof raw.memoryEnabled === 'boolean' ? raw.memoryEnabled : DEFAULT_AGENT_DEBUG_CONFIG.memoryEnabled,
|
|
55
|
+
autoArchiveHours: [0, 6, 24].includes(Number(raw.autoArchiveHours)) ? Number(raw.autoArchiveHours) : DEFAULT_AGENT_DEBUG_CONFIG.autoArchiveHours,
|
|
56
|
+
commandPermission: ['readonly_free', 'ask_always', 'allow_all'].includes(raw.commandPermission) ? raw.commandPermission : DEFAULT_AGENT_DEBUG_CONFIG.commandPermission,
|
|
57
|
+
compactThresholdPct: Math.min(90, Math.max(50, Number(raw.compactThresholdPct) || DEFAULT_AGENT_DEBUG_CONFIG.compactThresholdPct)),
|
|
58
|
+
compactPrompt: typeof raw.compactPrompt === 'string' && raw.compactPrompt.trim()
|
|
59
|
+
? raw.compactPrompt.trim().slice(0, 3000)
|
|
60
|
+
: DEFAULT_AGENT_DEBUG_CONFIG.compactPrompt,
|
|
61
|
+
personas: {},
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
const rawPersonas = raw.personas && typeof raw.personas === 'object' ? raw.personas : {};
|
|
65
|
+
for (const tpl of PERSONA_TEMPLATES) {
|
|
66
|
+
const item = rawPersonas[tpl.id] && typeof rawPersonas[tpl.id] === 'object' ? rawPersonas[tpl.id] : {};
|
|
67
|
+
out.personas[tpl.id] = {
|
|
68
|
+
name: tpl.name,
|
|
69
|
+
pal: tpl.pal,
|
|
70
|
+
summary: tpl.summary,
|
|
71
|
+
prompt: typeof item.prompt === 'string' && item.prompt.trim() ? item.prompt.trim().slice(0, 4000) : tpl.prompt,
|
|
72
|
+
initContext: typeof item.initContext === 'string' ? item.initContext.trim().slice(0, 2000) : tpl.initContext,
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
return out;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function globalAgentConfigPath() {
|
|
79
|
+
return join(userTemplatePaths().state, 'agent-debug-config.json');
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function workspaceAgentConfigPath(stateDir) {
|
|
83
|
+
return stateDir ? join(stateDir, 'agent-config.json') : null;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function readAgentDebugConfig(stateDir) {
|
|
87
|
+
const globalCfg = safeReadJson(globalAgentConfigPath()) || {};
|
|
88
|
+
const wsPath = workspaceAgentConfigPath(stateDir);
|
|
89
|
+
const wsCfg = safeReadJson(wsPath) || {};
|
|
90
|
+
const mergedPersonas = {
|
|
91
|
+
...(globalCfg.personas || {}),
|
|
92
|
+
...(wsCfg.personas || {}),
|
|
93
|
+
};
|
|
94
|
+
const merged = sanitizeConfig({ ...globalCfg, ...wsCfg, personas: mergedPersonas });
|
|
95
|
+
return {
|
|
96
|
+
config: merged,
|
|
97
|
+
hasWorkspaceOverride: Boolean(wsPath && existsSync(wsPath)),
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function saveAgentDebugConfig(stateDir, patch = {}, { scope = 'global' } = {}) {
|
|
102
|
+
const current = readAgentDebugConfig(stateDir).config;
|
|
103
|
+
const nextPersonas = { ...current.personas };
|
|
104
|
+
if (patch.personas && typeof patch.personas === 'object') {
|
|
105
|
+
for (const [k, v] of Object.entries(patch.personas)) {
|
|
106
|
+
if (nextPersonas[k] && v && typeof v === 'object') {
|
|
107
|
+
nextPersonas[k] = { ...nextPersonas[k], ...v };
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
const next = sanitizeConfig({ ...current, ...patch, personas: nextPersonas });
|
|
112
|
+
const targetPath = scope === 'workspace' && stateDir ? workspaceAgentConfigPath(stateDir) : globalAgentConfigPath();
|
|
113
|
+
const dir = resolve(targetPath, '..');
|
|
114
|
+
if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
115
|
+
writeFileSync(targetPath, JSON.stringify(next, null, 2) + '\n');
|
|
116
|
+
return readAgentDebugConfig(stateDir);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export function resetAgentDebugConfig(stateDir, section = 'all') {
|
|
120
|
+
const current = readAgentDebugConfig(stateDir).config;
|
|
121
|
+
let next = { ...current };
|
|
122
|
+
if (section === 'all') {
|
|
123
|
+
const wsPath = workspaceAgentConfigPath(stateDir);
|
|
124
|
+
if (wsPath && existsSync(wsPath)) {
|
|
125
|
+
try { unlinkSync(wsPath); } catch {}
|
|
126
|
+
}
|
|
127
|
+
next = sanitizeConfig({});
|
|
128
|
+
} else if (section === 'compact') {
|
|
129
|
+
next = sanitizeConfig({
|
|
130
|
+
...current,
|
|
131
|
+
compactThresholdPct: DEFAULT_AGENT_DEBUG_CONFIG.compactThresholdPct,
|
|
132
|
+
compactPrompt: DEFAULT_AGENT_DEBUG_CONFIG.compactPrompt,
|
|
133
|
+
});
|
|
134
|
+
} else if (section === 'personas') {
|
|
135
|
+
next = sanitizeConfig({ ...current, personas: {} });
|
|
136
|
+
}
|
|
137
|
+
const targetPath = globalAgentConfigPath();
|
|
138
|
+
const dir = resolve(targetPath, '..');
|
|
139
|
+
if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
140
|
+
writeFileSync(targetPath, JSON.stringify(next, null, 2) + '\n');
|
|
141
|
+
return readAgentDebugConfig(stateDir);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* 读取子工作区持久记忆 `.clado/memory.md`,并只读合并根工作区的 AGENTS.md / CLAUDE.md。
|
|
146
|
+
*/
|
|
147
|
+
export function readWorkspaceMemory(stateDir, rootWorkspace = '') {
|
|
148
|
+
const memPath = stateDir ? join(stateDir, 'memory.md') : '';
|
|
149
|
+
let memoryText = '';
|
|
150
|
+
if (memPath && existsSync(memPath)) {
|
|
151
|
+
try { memoryText = readFileSync(memPath, 'utf8').slice(0, 12000); } catch {}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
const inherited = [];
|
|
155
|
+
if (rootWorkspace) {
|
|
156
|
+
for (const name of ['AGENTS.md', 'CLAUDE.md']) {
|
|
157
|
+
const p = join(rootWorkspace, name);
|
|
158
|
+
if (existsSync(p)) {
|
|
159
|
+
try {
|
|
160
|
+
const content = readFileSync(p, 'utf8').trim().slice(0, 6000);
|
|
161
|
+
if (content) inherited.push({ file: name, content });
|
|
162
|
+
} catch {}
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
return {
|
|
167
|
+
path: '.clado/memory.md',
|
|
168
|
+
text: memoryText,
|
|
169
|
+
inherited,
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
export function saveWorkspaceMemory(stateDir, text = '') {
|
|
174
|
+
if (!stateDir) throw new Error('未找到子工作区状态目录。');
|
|
175
|
+
if (!existsSync(stateDir)) mkdirSync(stateDir, { recursive: true });
|
|
176
|
+
const clean = String(text || '').replace(/\r\n/g, '\n').slice(0, 12000);
|
|
177
|
+
writeFileSync(join(stateDir, 'memory.md'), clean);
|
|
178
|
+
return clean;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function shortHash(text) {
|
|
182
|
+
return createHash('sha1').update(String(text || '')).digest('hex').slice(0, 10);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function estimateTokens(text) {
|
|
186
|
+
const s = String(text || '');
|
|
187
|
+
if (!s) return 0;
|
|
188
|
+
// 中英混合经验估算:约 2.8 字符 / token
|
|
189
|
+
return Math.max(1, Math.ceil(s.length / 2.8));
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
function buildWorkspaceMapText(documentRoot, stateDir = '') {
|
|
193
|
+
const blocks = [];
|
|
194
|
+
if (documentRoot && existsSync(documentRoot)) {
|
|
195
|
+
try {
|
|
196
|
+
const scanned = scanDirectory(documentRoot);
|
|
197
|
+
const docs = Array.isArray(scanned?.documents) ? scanned.documents.slice(0, 30) : [];
|
|
198
|
+
if (docs.length) {
|
|
199
|
+
const lines = docs.map(d => {
|
|
200
|
+
const cards = Array.isArray(d.cards) ? d.cards.slice(0, 10).join(' / ') : '';
|
|
201
|
+
return `- ${d.file}${d.title ? `(${d.title})` : ''}${cards ? `:${cards}` : ''}`;
|
|
202
|
+
});
|
|
203
|
+
blocks.push(`【工作区画布全局索引】\n${lines.join('\n')}`);
|
|
204
|
+
} else {
|
|
205
|
+
blocks.push('(当前工作区暂无画布文档)');
|
|
206
|
+
}
|
|
207
|
+
} catch {}
|
|
208
|
+
}
|
|
209
|
+
if (stateDir) {
|
|
210
|
+
const objs = listCanvasObjects(stateDir, 30);
|
|
211
|
+
if (objs.length) {
|
|
212
|
+
const objLines = objs.map(o => `- [${o.id}] ${o.title} (${o.kind})${o.text ? `:${o.text.slice(0, 60)}` : ''}`);
|
|
213
|
+
blocks.push(`【画布多实例对象索引 (.clado/objects)】\n${objLines.join('\n')}`);
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
return blocks.join('\n\n');
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function inspectCanvasCards(documentRoot, relFile) {
|
|
220
|
+
if (!documentRoot || !relFile) return null;
|
|
221
|
+
try {
|
|
222
|
+
const fullPath = workspacePath(documentRoot, relFile);
|
|
223
|
+
if (!existsSync(fullPath)) return null;
|
|
224
|
+
const raw = readFileSync(fullPath, 'utf8');
|
|
225
|
+
const fileHash = shortHash(raw);
|
|
226
|
+
const { doc } = parseDocument(raw);
|
|
227
|
+
const cards = {};
|
|
228
|
+
const outline = [];
|
|
229
|
+
const flattenNodes = (nodes = []) => {
|
|
230
|
+
const parts = [];
|
|
231
|
+
for (const n of nodes) {
|
|
232
|
+
parts.push(`${'#'.repeat(n.d || 2)} ${n.title}${n.md ? '\n' + n.md : ''}`);
|
|
233
|
+
if (Array.isArray(n.kids) && n.kids.length) parts.push(...flattenNodes(n.kids));
|
|
234
|
+
}
|
|
235
|
+
return parts;
|
|
236
|
+
};
|
|
237
|
+
for (const card of doc.cards || []) {
|
|
238
|
+
const childNodes = Array.isArray(card.nodes) ? card.nodes : [];
|
|
239
|
+
const fullCardText = [card.md || '', ...flattenNodes(childNodes)].filter(Boolean).join('\n').trim();
|
|
240
|
+
const snippet = fullCardText.slice(0, 600);
|
|
241
|
+
const childTitles = childNodes.map(c => c.title);
|
|
242
|
+
const cardSig = shortHash(JSON.stringify([card.title, fullCardText, childTitles]));
|
|
243
|
+
cards[card.title] = {
|
|
244
|
+
hash: cardSig,
|
|
245
|
+
children: childTitles,
|
|
246
|
+
snippet,
|
|
247
|
+
};
|
|
248
|
+
outline.push(`- # ${card.title}${childTitles.length ? `(子节:${childTitles.join('、')})` : ''}`);
|
|
249
|
+
}
|
|
250
|
+
return {
|
|
251
|
+
file: relFile,
|
|
252
|
+
fileHash,
|
|
253
|
+
raw: raw.slice(0, 14000),
|
|
254
|
+
outlineText: outline.join('\n'),
|
|
255
|
+
cards,
|
|
256
|
+
};
|
|
257
|
+
} catch {
|
|
258
|
+
return null;
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/**
|
|
263
|
+
* 组装四段式前缀缓存消息队列与增量画布上下文,并输出缓存命中遥测指标。
|
|
264
|
+
*/
|
|
265
|
+
export function buildSegmentedPromptContext({
|
|
266
|
+
workspace,
|
|
267
|
+
rootWorkspace = workspace,
|
|
268
|
+
documentRoot = workspace,
|
|
269
|
+
stateDir = '',
|
|
270
|
+
debugConfig = DEFAULT_AGENT_DEBUG_CONFIG,
|
|
271
|
+
baseSystemPrompt = '',
|
|
272
|
+
history = [],
|
|
273
|
+
canvas = null,
|
|
274
|
+
canvasBaseline = null,
|
|
275
|
+
activePeerLocks = [],
|
|
276
|
+
incomingPeerMessages = [],
|
|
277
|
+
userInstruction = '',
|
|
278
|
+
isResumeTool = false,
|
|
279
|
+
now = new Date(),
|
|
280
|
+
}) {
|
|
281
|
+
const cfg = sanitizeConfig(debugConfig);
|
|
282
|
+
const isoDate = now.toISOString().slice(0, 10);
|
|
283
|
+
const isoExact = now.toISOString();
|
|
284
|
+
|
|
285
|
+
// ========== 第 1 段:冰封静态系统头(跨轮次、跨分身 100% 共享前缀缓存) ==========
|
|
286
|
+
const seg1Parts = [baseSystemPrompt.trim()];
|
|
287
|
+
if (cfg.timeInjection === 'system_head') {
|
|
288
|
+
// 仅供用户在调试面板直观观察“系统头塞精确时间破坏缓存”的反面对比模式
|
|
289
|
+
seg1Parts.push(`当前系统精确时间:${isoExact}`);
|
|
290
|
+
}
|
|
291
|
+
const seg1Text = seg1Parts.filter(Boolean).join('\n\n');
|
|
292
|
+
|
|
293
|
+
// ========== 第 2 段:工作区静态索引与持久记忆(文件/记忆未改时稳定命中缓存) ==========
|
|
294
|
+
const seg2Parts = [];
|
|
295
|
+
if (cfg.timeInjection === 'date_only') {
|
|
296
|
+
seg2Parts.push(`当前日期:${isoDate}`);
|
|
297
|
+
}
|
|
298
|
+
if (cfg.memoryEnabled && stateDir) {
|
|
299
|
+
const mem = readWorkspaceMemory(stateDir, rootWorkspace);
|
|
300
|
+
for (const inh of mem.inherited) {
|
|
301
|
+
seg2Parts.push(`【继承根工作区规范 · ${inh.file}(只读)】\n${inh.content}`);
|
|
302
|
+
}
|
|
303
|
+
if (mem.text.trim()) {
|
|
304
|
+
seg2Parts.push(`【当前工作区持久记忆 · .clado/memory.md】\n${mem.text.trim()}`);
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
if (cfg.workspaceMap) {
|
|
308
|
+
const mapText = buildWorkspaceMapText(documentRoot, stateDir);
|
|
309
|
+
if (mapText) seg2Parts.push(mapText);
|
|
310
|
+
}
|
|
311
|
+
const seg2Text = seg2Parts.filter(Boolean).join('\n\n');
|
|
312
|
+
const fullSystemText = [seg1Text, seg2Text].filter(Boolean).join('\n\n---\n\n');
|
|
313
|
+
|
|
314
|
+
// ========== 第 3 段:原子级压缩后的历史对话 + 画布基线 @v1 ==========
|
|
315
|
+
const compacted = compactMessages(history, {
|
|
316
|
+
maxChars: 42000,
|
|
317
|
+
thresholdPct: cfg.compactThresholdPct,
|
|
318
|
+
compactPrompt: cfg.compactPrompt,
|
|
319
|
+
});
|
|
320
|
+
|
|
321
|
+
let nextBaseline = canvasBaseline || null;
|
|
322
|
+
let canvasBaselineBlock = '';
|
|
323
|
+
let canvasDeltaBlock = '';
|
|
324
|
+
const snap = canvas?.file ? inspectCanvasCards(documentRoot, canvas.file) : null;
|
|
325
|
+
|
|
326
|
+
if (snap && cfg.canvasMemory !== 'off') {
|
|
327
|
+
if (cfg.canvasMemory === 'outline') {
|
|
328
|
+
canvasDeltaBlock = `【当前画布大纲 · ${snap.file}】\n${snap.outlineText || '(空画布)'}`;
|
|
329
|
+
} else if (cfg.canvasMemory === 'full') {
|
|
330
|
+
canvasDeltaBlock = `【当前画布全量内容 · ${snap.file}】\n${snap.raw}`;
|
|
331
|
+
} else {
|
|
332
|
+
// 默认 'delta'(智能增量:Baseline @v1 + Tail Delta @v2)
|
|
333
|
+
if (!canvasBaseline || canvasBaseline.file !== snap.file) {
|
|
334
|
+
const cardHashes = Object.fromEntries(Object.entries(snap.cards).map(([k, v]) => [k, v.hash]));
|
|
335
|
+
const baselineText = [
|
|
336
|
+
`【画布基线 @v1 · ${snap.file} (rev:${snap.fileHash})】`,
|
|
337
|
+
snap.outlineText || '(空画布)',
|
|
338
|
+
].join('\n');
|
|
339
|
+
nextBaseline = { file: snap.file, fileHash: snap.fileHash, cardHashes, baselineText };
|
|
340
|
+
canvasBaselineBlock = baselineText;
|
|
341
|
+
} else if (canvasBaseline.fileHash === snap.fileHash) {
|
|
342
|
+
canvasBaselineBlock = canvasBaseline.baselineText || '';
|
|
343
|
+
canvasDeltaBlock = `【画布增量 @v2 · ${snap.file}】自基线以来无外部改动。`;
|
|
344
|
+
} else {
|
|
345
|
+
canvasBaselineBlock = canvasBaseline.baselineText || '';
|
|
346
|
+
const prevHashes = canvasBaseline.cardHashes || {};
|
|
347
|
+
const changed = [];
|
|
348
|
+
const removed = [];
|
|
349
|
+
for (const [title, info] of Object.entries(snap.cards)) {
|
|
350
|
+
if (!prevHashes[title]) changed.push(`+ 新增卡片「${title}」:\n${info.snippet}`);
|
|
351
|
+
else if (prevHashes[title] !== info.hash) changed.push(`~ 修改卡片「${title}」:\n${info.snippet}`);
|
|
352
|
+
}
|
|
353
|
+
for (const oldTitle of Object.keys(prevHashes)) {
|
|
354
|
+
if (!snap.cards[oldTitle]) removed.push(`- 已移除卡片「${oldTitle}」`);
|
|
355
|
+
}
|
|
356
|
+
const deltaLines = [...changed, ...removed].slice(0, 12);
|
|
357
|
+
canvasDeltaBlock = deltaLines.length
|
|
358
|
+
? `【画布实时增量 @v2 · ${snap.file}】\n${deltaLines.join('\n\n')}`
|
|
359
|
+
: `【画布实时增量 @v2 · ${snap.file}】仅非结构性空白变动。`;
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
const conversation = [...compacted];
|
|
365
|
+
if (canvasBaselineBlock && !conversation.some(m => typeof m?.content === 'string' && m.content.includes('【画布基线 @v1'))) {
|
|
366
|
+
conversation.unshift({ role: 'user', content: canvasBaselineBlock });
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
// ========== 第 4 段:尾部极小动态增量区(选区 / 多实例对象选区 / 同伴锁 / 同伴来信 / 尾部时间 / 当前指令) ==========
|
|
370
|
+
const tailMeta = [`当前工作区:${workspace}`];
|
|
371
|
+
if (canvas?.file) tailMeta.push(`当前打开画布:${canvas.file}`);
|
|
372
|
+
if (Array.isArray(canvas?.selection) && canvas.selection.length) {
|
|
373
|
+
tailMeta.push(`用户当前选中项:${JSON.stringify(canvas.selection)}`);
|
|
374
|
+
}
|
|
375
|
+
if (Array.isArray(canvas?.objectSelection) && canvas.objectSelection.length) {
|
|
376
|
+
const objDetails = canvas.objectSelection.map(sel => {
|
|
377
|
+
const full = stateDir ? readCanvasObject(stateDir, sel.id) : null;
|
|
378
|
+
const bodyPart = full?.text ? ` · 内容:「${full.text.slice(0, 200)}」` : '';
|
|
379
|
+
const subPart = sel.subtarget ? ` · 子区域靶点:${sel.subtarget}` : '';
|
|
380
|
+
return `- [${sel.id}] ${sel.title || full?.title || sel.kind}${subPart}${bodyPart}`;
|
|
381
|
+
});
|
|
382
|
+
tailMeta.push(`【用户当前选中的多实例组件/子项】\n${objDetails.join('\n')}`);
|
|
383
|
+
}
|
|
384
|
+
if (cfg.timeInjection === 'tail_exact') {
|
|
385
|
+
tailMeta.push(`当前精确时间:${isoExact}`);
|
|
386
|
+
}
|
|
387
|
+
if (canvasDeltaBlock) {
|
|
388
|
+
tailMeta.push(canvasDeltaBlock);
|
|
389
|
+
}
|
|
390
|
+
if (Array.isArray(activePeerLocks) && activePeerLocks.length) {
|
|
391
|
+
tailMeta.push(`【同伴卡片领地占用提示】\n${activePeerLocks.map(l => `- 同伴「${l.peerName}」正在操作 ${l.target},请避免并发覆写同一卡片`).join('\n')}`);
|
|
392
|
+
}
|
|
393
|
+
if (Array.isArray(incomingPeerMessages) && incomingPeerMessages.length) {
|
|
394
|
+
tailMeta.push(`【收到同伴实时协作消息】\n${incomingPeerMessages.map(m => `- 来自「${m.fromName}」(${m.kind === 'notify' ? '单向通知,无需回执' : '协作请求'}):${m.text}`).join('\n')}`);
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
const seg4UserContent = isResumeTool
|
|
398
|
+
? ''
|
|
399
|
+
: `${tailMeta.join('\n')}\n\n用户指令:\n${userInstruction}`;
|
|
400
|
+
|
|
401
|
+
// 计算四段式缓存命中估算
|
|
402
|
+
const seg1Tokens = estimateTokens(seg1Text) + 640; // 含固定工具 Schema
|
|
403
|
+
const seg2Tokens = estimateTokens(seg2Text);
|
|
404
|
+
const seg3Tokens = estimateTokens(JSON.stringify(conversation));
|
|
405
|
+
const seg4Tokens = estimateTokens(seg4UserContent || 'tool_result');
|
|
406
|
+
const totalTokens = Math.max(1, seg1Tokens + seg2Tokens + seg3Tokens + seg4Tokens);
|
|
407
|
+
const brokenBySystemTime = cfg.timeInjection === 'system_head';
|
|
408
|
+
const fullCanvasPenalty = cfg.canvasMemory === 'full' ? Math.min(seg4Tokens, Math.floor(totalTokens * 0.18)) : 0;
|
|
409
|
+
const cachedTokens = brokenBySystemTime
|
|
410
|
+
? 0
|
|
411
|
+
: Math.max(0, seg1Tokens + seg2Tokens + seg3Tokens - fullCanvasPenalty);
|
|
412
|
+
const hitRatePct = Number(((cachedTokens / totalTokens) * 100).toFixed(1));
|
|
413
|
+
|
|
414
|
+
return {
|
|
415
|
+
systemText: fullSystemText,
|
|
416
|
+
conversation,
|
|
417
|
+
seg4UserContent,
|
|
418
|
+
nextBaseline,
|
|
419
|
+
telemetry: {
|
|
420
|
+
seg1Tokens,
|
|
421
|
+
seg2Tokens,
|
|
422
|
+
seg3Tokens,
|
|
423
|
+
seg4Tokens,
|
|
424
|
+
totalTokens,
|
|
425
|
+
cachedTokens,
|
|
426
|
+
hitRatePct,
|
|
427
|
+
brokenBySystemTime,
|
|
428
|
+
},
|
|
429
|
+
};
|
|
430
|
+
}
|
package/src/agent/probe.js
CHANGED
|
@@ -174,3 +174,61 @@ export async function probeGitDiff(workspace, { ref = '', statOnly = false, maxC
|
|
|
174
174
|
return { isGitRepo: false, branch: '', status: '', stat: '', diff: '', truncated: false, message: '当前目录不是 Git 仓库或无法读取 git 状态。' };
|
|
175
175
|
}
|
|
176
176
|
}
|
|
177
|
+
|
|
178
|
+
const READONLY_CMD_RE = /^(git\s+(status|diff|log|show|branch|rev-parse)\b|ls\b|pwd\b|rg\b|grep\b|cat\b|head\b|tail\b|wc\b|which\b|node\s+(-v|--version)\b|npm\s+(-v|--version)\b|pnpm\s+(-v|--version)\b)/i;
|
|
179
|
+
const BLOCKED_CMD_RE = /(\brm\s+-[a-z]*r[a-z]*f?\s+\/(\s|$)|:\(\)\s*\{|\bmkfs\b|\bshutdown\b|\breboot\b|\bdd\s+if=)/i;
|
|
180
|
+
const SHELL_CHAIN_RE = /[;&|`$<>]|\r|\n/;
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* 对命令行调用进行安全分级:blocked(高危拦截)| readonly(只读免审)| write_or_exec(需按策略审批)。
|
|
184
|
+
*/
|
|
185
|
+
export function classifyShellCommand(command) {
|
|
186
|
+
const clean = String(command || '').trim();
|
|
187
|
+
if (!clean) return 'blocked';
|
|
188
|
+
if (BLOCKED_CMD_RE.test(clean)) return 'blocked';
|
|
189
|
+
if (!SHELL_CHAIN_RE.test(clean) && READONLY_CMD_RE.test(clean)) return 'readonly';
|
|
190
|
+
return 'write_or_exec';
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* 在当前工作区根目录受控执行单条命令(带超时与输出截断保护)。
|
|
195
|
+
*/
|
|
196
|
+
export async function executeWorkspaceCommand(workspace, { command, timeoutMs = 20000, maxChars = 16000 } = {}) {
|
|
197
|
+
const clean = String(command || '').trim();
|
|
198
|
+
if (!clean) throw new Error('command 不能为空。');
|
|
199
|
+
if (classifyShellCommand(clean) === 'blocked') {
|
|
200
|
+
throw new Error('该命令命中高危安全规则,已被系统拦截。');
|
|
201
|
+
}
|
|
202
|
+
const { root } = assertInsideWorkspace(workspace, '.');
|
|
203
|
+
const timeout = Math.min(60000, Math.max(2000, Number(timeoutMs) || 20000));
|
|
204
|
+
const limit = Math.min(32000, Math.max(1000, Number(maxChars) || 16000));
|
|
205
|
+
|
|
206
|
+
try {
|
|
207
|
+
const { stdout = '', stderr = '' } = await execFileAsync('bash', ['-lc', clean], {
|
|
208
|
+
cwd: root,
|
|
209
|
+
timeout,
|
|
210
|
+
maxBuffer: 4 * 1024 * 1024,
|
|
211
|
+
env: { ...process.env, PAGER: 'cat', GIT_TERMINAL_PROMPT: '0' },
|
|
212
|
+
});
|
|
213
|
+
const combined = [stdout, stderr].filter(Boolean).join('\n');
|
|
214
|
+
const truncated = combined.length > limit;
|
|
215
|
+
return {
|
|
216
|
+
ok: true,
|
|
217
|
+
exitCode: 0,
|
|
218
|
+
command: clean,
|
|
219
|
+
output: truncated ? combined.slice(0, limit) + '\n... (output truncated)' : combined,
|
|
220
|
+
truncated,
|
|
221
|
+
};
|
|
222
|
+
} catch (error) {
|
|
223
|
+
const out = [error?.stdout || '', error?.stderr || '', error?.message || ''].filter(Boolean).join('\n');
|
|
224
|
+
const truncated = out.length > limit;
|
|
225
|
+
return {
|
|
226
|
+
ok: false,
|
|
227
|
+
exitCode: typeof error?.code === 'number' ? error.code : 1,
|
|
228
|
+
command: clean,
|
|
229
|
+
output: truncated ? out.slice(0, limit) + '\n... (output truncated)' : out,
|
|
230
|
+
truncated,
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|