cladogram 0.5.5-beta.6 → 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/docs/release.md +7 -0
- package/package.json +2 -2
- package/plugins/agent/index.js +1795 -407
- package/plugins/agent/style.css +1123 -420
- package/plugins/brand/index.js +199 -2
- 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/plugin-ui.css +284 -0
- package/src/server/agent.js +818 -50
- package/src/server/assets/library-canvas.js +305 -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/plugins/brand/index.js
CHANGED
|
@@ -123,7 +123,191 @@
|
|
|
123
123
|
};
|
|
124
124
|
}
|
|
125
125
|
|
|
126
|
-
function
|
|
126
|
+
function mountPluginMarket(market) {
|
|
127
|
+
if (!market || !document.body) return null;
|
|
128
|
+
const overlay = document.createElement('div');
|
|
129
|
+
overlay.id = 'clado-market-overlay';
|
|
130
|
+
overlay.className = 'clado-market-overlay';
|
|
131
|
+
overlay.innerHTML = `
|
|
132
|
+
<div class="clado-market-sheet">
|
|
133
|
+
<div class="clado-market-well" style="padding:12px;display:flex;flex-direction:column;gap:9px;">
|
|
134
|
+
<div style="display:flex;align-items:center;justify-content:space-between;gap:6px;flex-wrap:wrap;">
|
|
135
|
+
<strong style="font-size:15px;">插件市场</strong>
|
|
136
|
+
<div style="display:flex;align-items:center;gap:5px;">
|
|
137
|
+
<div class="clado-market-tabs">
|
|
138
|
+
<button type="button" class="clado-market-tab active" data-m-src="official">官方源</button>
|
|
139
|
+
<button type="button" class="clado-market-tab" data-m-src="team">团队私有源</button>
|
|
140
|
+
</div>
|
|
141
|
+
<button type="button" class="clado-market-tab active" data-m-close style="padding:4.5px 10px;">完成</button>
|
|
142
|
+
</div>
|
|
143
|
+
</div>
|
|
144
|
+
<input type="text" data-m-search placeholder="搜索插件…" style="width:100%;padding:8px 11px;border-radius:10px;border:1px solid var(--clado-ui-well-border);background:var(--clado-ui-well);color:var(--clado-ui-text);font:inherit;font-size:13px;outline:none;" />
|
|
145
|
+
<div style="display:flex;gap:4px;overflow-x:auto;">
|
|
146
|
+
<button type="button" class="clado-market-tab active" data-m-cat="all">全部</button>
|
|
147
|
+
<button type="button" class="clado-market-tab" data-m-cat="multi">多实例</button>
|
|
148
|
+
<button type="button" class="clado-market-tab" data-m-cat="tool">纯工具</button>
|
|
149
|
+
<button type="button" class="clado-market-tab" data-m-cat="hybrid">视图+工具</button>
|
|
150
|
+
<button type="button" class="clado-market-tab" data-m-cat="executor">执行器</button>
|
|
151
|
+
</div>
|
|
152
|
+
</div>
|
|
153
|
+
<div data-m-list style="display:flex;flex-direction:column;gap:8px;"></div>
|
|
154
|
+
<div data-m-detail class="clado-market-well" style="display:none;padding:14px;flex-direction:column;gap:11px;"></div>
|
|
155
|
+
</div>`;
|
|
156
|
+
document.body.append(overlay);
|
|
157
|
+
|
|
158
|
+
const searchInput = overlay.querySelector('[data-m-search]');
|
|
159
|
+
const listEl = overlay.querySelector('[data-m-list]');
|
|
160
|
+
const detailEl = overlay.querySelector('[data-m-detail]');
|
|
161
|
+
let sourceFilter = 'official';
|
|
162
|
+
let catFilter = 'all';
|
|
163
|
+
let catalog = [];
|
|
164
|
+
let installedSet = new Set();
|
|
165
|
+
|
|
166
|
+
const kindLabels = { multi: '多实例', tool: '纯工具', hybrid: '视图+工具', executor: '执行器', ui: '界面插件' };
|
|
167
|
+
const inferKind = p => p.kind || (p.category === 'executor' ? 'executor' : 'tool');
|
|
168
|
+
|
|
169
|
+
function renderList() {
|
|
170
|
+
const q = (searchInput.value || '').trim().toLowerCase();
|
|
171
|
+
detailEl.style.display = 'none';
|
|
172
|
+
listEl.style.display = 'flex';
|
|
173
|
+
listEl.replaceChildren();
|
|
174
|
+
|
|
175
|
+
const filtered = catalog.filter(p => {
|
|
176
|
+
const pSrc = p.source || 'official';
|
|
177
|
+
if (sourceFilter === 'team' && pSrc !== 'team') return false;
|
|
178
|
+
const k = inferKind(p);
|
|
179
|
+
if (catFilter !== 'all' && k !== catFilter) return false;
|
|
180
|
+
if (q && !(p.name + ' ' + p.description + ' ' + p.id).toLowerCase().includes(q)) return false;
|
|
181
|
+
return true;
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
if (!filtered.length) {
|
|
185
|
+
const empty = document.createElement('div');
|
|
186
|
+
empty.className = 'clado-market-well';
|
|
187
|
+
empty.style.cssText = 'padding:16px;text-align:center;color:var(--clado-ui-muted);font-size:12.5px;';
|
|
188
|
+
empty.textContent = '当前筛选下暂无匹配插件';
|
|
189
|
+
listEl.append(empty);
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
for (const p of filtered) {
|
|
194
|
+
const card = document.createElement('div');
|
|
195
|
+
card.className = 'clado-market-well clado-market-card';
|
|
196
|
+
card.dataset.mId = p.id;
|
|
197
|
+
const risk = p.audit?.highestRisk || 'low';
|
|
198
|
+
const k = inferKind(p);
|
|
199
|
+
const installed = installedSet.has(p.id);
|
|
200
|
+
card.innerHTML = `
|
|
201
|
+
<div style="display:flex;align-items:flex-start;gap:10px;">
|
|
202
|
+
<span style="width:36px;height:36px;border-radius:11px;background:var(--clado-ui-well);border:1px solid var(--clado-ui-well-border);display:inline-flex;align-items:center;justify-content:center;font-size:17px;flex:none;">${p.icon || '🧩'}</span>
|
|
203
|
+
<div style="flex:1;min-width:0;">
|
|
204
|
+
<div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap;">
|
|
205
|
+
<strong style="font-size:13.5px;">${p.name}</strong>
|
|
206
|
+
<span style="padding:1px 6px;border-radius:6px;background:rgba(59,130,246,0.13);color:var(--clado-ui-brand);font-size:10px;font-weight:600;">${kindLabels[k] || '扩展'}</span>
|
|
207
|
+
${installed ? '<span style="font-size:10px;color:#059669;font-weight:600;">已安装</span>' : ''}
|
|
208
|
+
<span class="clado-risk-pill clado-risk-${risk}" style="margin-left:auto;">${risk}</span>
|
|
209
|
+
</div>
|
|
210
|
+
<div style="font-size:12px;color:var(--clado-ui-muted);margin-top:4px;line-height:1.45;">${p.description || ''}</div>
|
|
211
|
+
</div>
|
|
212
|
+
</div>`;
|
|
213
|
+
card.onclick = () => openDetail(p);
|
|
214
|
+
listEl.append(card);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function openDetail(p) {
|
|
219
|
+
listEl.style.display = 'none';
|
|
220
|
+
detailEl.style.display = 'flex';
|
|
221
|
+
const risk = p.audit?.highestRisk || 'low';
|
|
222
|
+
const installed = installedSet.has(p.id);
|
|
223
|
+
const auditItems = Array.isArray(p.audit?.items) ? p.audit.items : [];
|
|
224
|
+
detailEl.innerHTML = `
|
|
225
|
+
<div style="display:flex;justify-content:space-between;align-items:center;">
|
|
226
|
+
<button type="button" class="clado-market-tab active" data-m-back>← 返回列表</button>
|
|
227
|
+
<span class="clado-risk-pill clado-risk-${risk}">权限风险:${risk}</span>
|
|
228
|
+
</div>
|
|
229
|
+
<div style="display:flex;align-items:center;gap:10px;">
|
|
230
|
+
<span style="width:42px;height:42px;border-radius:12px;background:var(--clado-ui-well);border:1px solid var(--clado-ui-well-border);display:inline-flex;align-items:center;justify-content:center;font-size:20px;flex:none;">${p.icon || '🧩'}</span>
|
|
231
|
+
<div style="flex:1;min-width:0;">
|
|
232
|
+
<div style="font-size:15px;font-weight:700;">${p.name}</div>
|
|
233
|
+
<div style="font-size:11.5px;color:var(--clado-ui-subtle);">${p.id} · v${p.version} · ${p.author || 'community'}</div>
|
|
234
|
+
</div>
|
|
235
|
+
<button type="button" data-m-toggle style="height:32px;padding:0 13px;border-radius:9px;border:0;background:${installed ? 'var(--clado-ui-well)' : 'var(--clado-ui-brand)'};color:${installed ? 'var(--clado-ui-text)' : '#fff'};font:inherit;font-size:12px;font-weight:600;cursor:pointer;">${installed ? '卸载' : '安装'}</button>
|
|
236
|
+
</div>
|
|
237
|
+
<div style="font-size:12.5px;line-height:1.55;color:var(--clado-ui-muted);">${p.readme || p.description || ''}</div>
|
|
238
|
+
<div style="border-top:1px solid var(--clado-ui-edge);padding-top:9px;font-size:11.5px;color:var(--clado-ui-muted);display:flex;flex-direction:column;gap:4px;">
|
|
239
|
+
<strong style="color:var(--clado-ui-text);font-size:11.5px;">权限审计明细</strong>
|
|
240
|
+
${auditItems.length ? auditItems.map(a => `<div>· [${a.risk}] ${a.summary}</div>`).join('') : '<div>· 无额外敏感权限声明</div>'}
|
|
241
|
+
</div>
|
|
242
|
+
<div data-m-status style="font-size:11.5px;color:var(--clado-ui-brand);"></div>`;
|
|
243
|
+
|
|
244
|
+
detailEl.querySelector('[data-m-back]').onclick = () => renderList();
|
|
245
|
+
const toggleBtn = detailEl.querySelector('[data-m-toggle]');
|
|
246
|
+
const statusLine = detailEl.querySelector('[data-m-status]');
|
|
247
|
+
toggleBtn.onclick = async () => {
|
|
248
|
+
toggleBtn.disabled = true;
|
|
249
|
+
statusLine.textContent = installed ? '正在卸载…' : '正在安装并审计…';
|
|
250
|
+
try {
|
|
251
|
+
if (installed) {
|
|
252
|
+
await market.uninstall(p.id);
|
|
253
|
+
installedSet.delete(p.id);
|
|
254
|
+
} else {
|
|
255
|
+
await market.install(p.id);
|
|
256
|
+
installedSet.add(p.id);
|
|
257
|
+
}
|
|
258
|
+
openDetail(p);
|
|
259
|
+
} catch (err) {
|
|
260
|
+
statusLine.textContent = err.message || '操作失败';
|
|
261
|
+
toggleBtn.disabled = false;
|
|
262
|
+
}
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
async function open() {
|
|
267
|
+
overlay.classList.add('show');
|
|
268
|
+
try {
|
|
269
|
+
const res = await market.load();
|
|
270
|
+
catalog = Array.isArray(res?.plugins) ? res.plugins : [];
|
|
271
|
+
installedSet = new Set(res?.installedIds || []);
|
|
272
|
+
if (res?.origin && res.origin !== 'builtin') {
|
|
273
|
+
for (const p of catalog) if (!p.source) p.source = 'team';
|
|
274
|
+
}
|
|
275
|
+
} catch {}
|
|
276
|
+
renderList();
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
function close() {
|
|
280
|
+
overlay.classList.remove('show');
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
overlay.addEventListener('click', ev => {
|
|
284
|
+
if (ev.target === overlay || ev.target.closest('[data-m-close]')) {
|
|
285
|
+
close();
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
const srcBtn = ev.target.closest('[data-m-src]');
|
|
289
|
+
if (srcBtn) {
|
|
290
|
+
sourceFilter = srcBtn.dataset.mSrc;
|
|
291
|
+
overlay.querySelectorAll('[data-m-src]').forEach(b => b.classList.toggle('active', b === srcBtn));
|
|
292
|
+
renderList();
|
|
293
|
+
return;
|
|
294
|
+
}
|
|
295
|
+
const catBtn = ev.target.closest('[data-m-cat]');
|
|
296
|
+
if (catBtn) {
|
|
297
|
+
catFilter = catBtn.dataset.mCat;
|
|
298
|
+
overlay.querySelectorAll('[data-m-cat]').forEach(b => b.classList.toggle('active', b === catBtn));
|
|
299
|
+
renderList();
|
|
300
|
+
}
|
|
301
|
+
});
|
|
302
|
+
searchInput.addEventListener('input', () => renderList());
|
|
303
|
+
window.addEventListener('clado:open-market', () => open());
|
|
304
|
+
document.addEventListener('keydown', ev => {
|
|
305
|
+
if (ev.key === 'Escape' && overlay.classList.contains('show')) close();
|
|
306
|
+
});
|
|
307
|
+
return { open, close };
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
function mountBrand(host, { setTheme, capture, plugins, market }) {
|
|
127
311
|
const brand = document.createElement('div');
|
|
128
312
|
brand.className = 'clado-brand-plugin';
|
|
129
313
|
const brandLogo = '<svg viewBox="0 0 64 64" fill="none" aria-hidden="true">' +
|
|
@@ -178,6 +362,19 @@
|
|
|
178
362
|
};
|
|
179
363
|
panel.append(action);
|
|
180
364
|
}
|
|
365
|
+
const marketCtrl = mountPluginMarket(market);
|
|
366
|
+
if (marketCtrl) {
|
|
367
|
+
const marketBtn = document.createElement('button');
|
|
368
|
+
marketBtn.type = 'button';
|
|
369
|
+
marketBtn.className = 'clado-ui-button clado-brand-choice clado-brand-capture';
|
|
370
|
+
marketBtn.dataset.openMarket = 'true';
|
|
371
|
+
marketBtn.innerHTML = icon('<path d="M4 9h16l-1.5 10.5a2 2 0 0 1-2 1.5H7.5a2 2 0 0 1-2-1.5L4 9Zm2-5h12l2 5H4l2-5Z"/>') + '<span>插件市场</span>';
|
|
372
|
+
marketBtn.onclick = () => {
|
|
373
|
+
setOpen(false);
|
|
374
|
+
marketCtrl.open();
|
|
375
|
+
};
|
|
376
|
+
panel.append(marketBtn);
|
|
377
|
+
}
|
|
181
378
|
if (plugins) {
|
|
182
379
|
const action = document.createElement('button');
|
|
183
380
|
action.type = 'button';
|
|
@@ -265,7 +462,7 @@
|
|
|
265
462
|
sync(theme) {
|
|
266
463
|
for (const entry of choices) entry.choice.setAttribute('aria-pressed', String(entry.theme === theme));
|
|
267
464
|
},
|
|
268
|
-
close: () => setOpen(false),
|
|
465
|
+
close: () => { setOpen(false); marketCtrl?.close(); },
|
|
269
466
|
};
|
|
270
467
|
}
|
|
271
468
|
|
|
@@ -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
|
+
}
|