pi-web-ui 0.111.0 → 0.113.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +92 -2
- package/bin/frp-manager.mjs +9 -2
- package/bin/pi-web-ui.mjs +325 -45
- package/dist/server/agent-service-daemon.js +29 -4
- package/dist/server/agent-service.js +1527 -510
- package/dist/server/approval-audit.js +119 -0
- package/dist/server/approval-default-rules.js +4 -4
- package/dist/server/approval-rules.js +42 -17
- package/dist/server/attachment-store.js +8 -8
- package/dist/server/canvas/canvas-agent-tool.js +8 -0
- package/dist/server/canvas/canvas-orchestrator.js +128 -22
- package/dist/server/canvas/pstack-skills-data.js +498 -0
- package/dist/server/client-state.js +28 -0
- package/dist/server/delegate-mode.js +6 -3
- package/dist/server/delegate-task.js +18 -3
- package/dist/server/dispatch-domain-handlers.js +39 -11
- package/dist/server/dsh/dsh-agent-service.js +294 -15
- package/dist/server/dsh/dsh-serialize.js +1 -1
- package/dist/server/durable/durable-driver.js +112 -107
- package/dist/server/durable/durable-event-projector.js +253 -0
- package/dist/server/durable/durable-loader.js +1 -14
- package/dist/server/durable/durable-models.js +107 -0
- package/dist/server/durable/index.js +0 -4
- package/dist/server/engine-probe.js +111 -48
- package/dist/server/eval-tool.js +28 -3
- package/dist/server/goal-service.js +7 -0
- package/dist/server/index.js +371 -57
- package/dist/server/json-utils.js +57 -0
- package/dist/server/marker-service.js +8 -0
- package/dist/server/message-window.js +43 -10
- package/dist/server/model-admin.js +247 -163
- package/dist/server/model-resolver.js +66 -44
- package/dist/server/plan-manager.js +3 -6
- package/dist/server/plugin-api-catalog.js +1 -0
- package/dist/server/plugin-assets.js +238 -0
- package/dist/server/plugin-facilities.js +22 -0
- package/dist/server/plugin-ui-slots.js +1 -0
- package/dist/server/plugins.js +209 -11
- package/dist/server/preset-fields.js +25 -1
- package/dist/server/preset-share.js +5 -2
- package/dist/server/prompt-assembler.js +2 -1
- package/dist/server/prompt-composer.js +18 -8
- package/dist/server/protocol-version.js +1 -1
- package/dist/server/queue-utils.js +156 -0
- package/dist/server/remote-ssh-service.js +110 -12
- package/dist/server/sdk-builtin-extensions.js +85 -0
- package/dist/server/serialize.js +1 -1
- package/dist/server/server-config.js +66 -0
- package/dist/server/session-parser.js +49 -13
- package/dist/server/session-search.js +4 -3
- package/dist/server/settings-service.js +74 -53
- package/dist/server/setup-page.js +632 -0
- package/dist/server/skill-discovery.js +361 -59
- package/dist/server/skill-maintenance.js +231 -0
- package/dist/server/skill-tool.js +32 -3
- package/dist/server/soft-cap.js +30 -6
- package/dist/server/subagent-helpers.js +22 -1
- package/dist/server/subagent-notify.js +93 -0
- package/dist/server/subagent-security-gate.js +282 -0
- package/dist/server/subagent-templates.js +8 -0
- package/dist/server/subagents.js +390 -48
- package/dist/server/terminals.js +196 -8
- package/dist/server/text-quote.js +61 -0
- package/dist/server/tool-approval.js +63 -4
- package/dist/server/tool-guards.js +208 -0
- package/dist/server/tool-host-factories.js +48 -10
- package/dist/server/tool-manager.js +106 -28
- package/dist/server/tool-overrides.js +21 -11
- package/dist/server/universal/driver-base.js +8 -0
- package/dist/server/universal/drivers/claude-code.js +116 -7
- package/dist/server/universal/drivers/dsh-driver.js +3 -0
- package/dist/server/universal/index.js +0 -1
- package/dist/server/universal/universal-session.js +106 -10
- package/dist/server/worktree-service.js +189 -1
- package/docs/dsh-engine.md +1 -5
- package/package.json +1 -1
- package/plugin-sdk/client-utils.mjs +192 -5
- package/plugin-sdk/index.d.ts +63 -1
- package/plugin-sdk/index.mjs +94 -0
- package/plugin-sdk/package.json +5 -1
- package/plugins/catalog.json +21 -0
- package/web/dist/assets/{TerminalPanel-BiUNySMA.js → TerminalPanel-3wojLfLk.js} +2 -2
- package/web/dist/assets/index-A8YXwnpZ.js +2008 -0
- package/web/dist/assets/index-BwL7qBh6.css +1 -0
- package/web/dist/index.html +11 -2
- package/web/dist/sw.js +1 -1
- package/web/dist/assets/index-B0ajS__T.js +0 -697
- package/web/dist/assets/index-BHik5WGG.css +0 -1
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* skill-maintenance.ts — 通用多智能体技能(Universal Multi-Agent Skills)维护管理工具。
|
|
3
|
+
*
|
|
4
|
+
* 功能定位:
|
|
5
|
+
* 1. 跨智能体全源技能扫描与结构化维护报告(输出各生态覆盖、作用域、同名覆盖冲突);
|
|
6
|
+
* 2. 技能文件合规性与健康检查(文件大小、8KB 上限、frontmatter 规范等);
|
|
7
|
+
* 3. 跨 Agent 技能物理同步/软链维护(一键汇聚外部技能至当前工作区或全局目录)。
|
|
8
|
+
*/
|
|
9
|
+
import { copyFileSync, existsSync, mkdirSync, readFileSync, statSync, symlinkSync } from "node:fs";
|
|
10
|
+
import { basename, dirname, join } from "node:path";
|
|
11
|
+
import { discoverDiskSkills, getMultiAgentSkillCandidateDirs, parseSkillFrontmatter, } from "./skill-discovery.js";
|
|
12
|
+
import { decodeText } from "./text-sniff.js";
|
|
13
|
+
/** 执行全源技能扫描与维护统计 */
|
|
14
|
+
export function scanAllAgentSkills(opts) {
|
|
15
|
+
const allDirs = getMultiAgentSkillCandidateDirs(opts);
|
|
16
|
+
const existingDirs = allDirs.filter((d) => existsSync(d.path)).map((d) => d.path);
|
|
17
|
+
// 获取胜出的主技能
|
|
18
|
+
const primarySkills = discoverDiskSkills({ ...opts, includeConflicts: false });
|
|
19
|
+
// 获取所有发现的候选技能(包含同名被覆盖的)
|
|
20
|
+
const allSkills = discoverDiskSkills({ ...opts, includeConflicts: true });
|
|
21
|
+
const bySource = {
|
|
22
|
+
pi: 0,
|
|
23
|
+
agents: 0,
|
|
24
|
+
claude: 0,
|
|
25
|
+
cursor: 0,
|
|
26
|
+
windsurf: 0,
|
|
27
|
+
github: 0,
|
|
28
|
+
opencode: 0,
|
|
29
|
+
cline: 0,
|
|
30
|
+
roo: 0,
|
|
31
|
+
npm: 0,
|
|
32
|
+
"data-dir": 0,
|
|
33
|
+
custom: 0,
|
|
34
|
+
};
|
|
35
|
+
const byScope = {
|
|
36
|
+
project: 0,
|
|
37
|
+
ancestor: 0,
|
|
38
|
+
global: 0,
|
|
39
|
+
package: 0,
|
|
40
|
+
};
|
|
41
|
+
for (const s of primarySkills) {
|
|
42
|
+
if (s.source)
|
|
43
|
+
bySource[s.source] = (bySource[s.source] || 0) + 1;
|
|
44
|
+
if (s.scope)
|
|
45
|
+
byScope[s.scope] = (byScope[s.scope] || 0) + 1;
|
|
46
|
+
}
|
|
47
|
+
// 识别冲突覆盖
|
|
48
|
+
const mapAll = new Map();
|
|
49
|
+
for (const s of allSkills) {
|
|
50
|
+
const key = s.name.toLowerCase();
|
|
51
|
+
const list = mapAll.get(key) ?? [];
|
|
52
|
+
list.push(s);
|
|
53
|
+
mapAll.set(key, list);
|
|
54
|
+
}
|
|
55
|
+
const conflicts = [];
|
|
56
|
+
for (const chosen of primarySkills) {
|
|
57
|
+
const key = chosen.name.toLowerCase();
|
|
58
|
+
const allSameName = mapAll.get(key) || [];
|
|
59
|
+
if (allSameName.length > 1) {
|
|
60
|
+
const overridden = allSameName.filter((item) => item.filePath !== chosen.filePath);
|
|
61
|
+
if (overridden.length > 0) {
|
|
62
|
+
conflicts.push({
|
|
63
|
+
name: chosen.name,
|
|
64
|
+
chosen,
|
|
65
|
+
overridden,
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
return {
|
|
71
|
+
totalUnique: primarySkills.length,
|
|
72
|
+
totalDiscovered: allSkills.length,
|
|
73
|
+
skills: primarySkills,
|
|
74
|
+
bySource,
|
|
75
|
+
byScope,
|
|
76
|
+
conflicts,
|
|
77
|
+
scannedDirs: existingDirs,
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
/** 生成格式化的人类与智能体可读维护报告 */
|
|
81
|
+
export function generateSkillsReport(result, lang = "zh") {
|
|
82
|
+
const isZh = lang === "zh";
|
|
83
|
+
const lines = [];
|
|
84
|
+
lines.push(isZh ? "=== 跨智能体全源技能扫描与维护报告 ===" : "=== Universal Multi-Agent Skills Report ===");
|
|
85
|
+
lines.push(isZh
|
|
86
|
+
? `整合唯一技能数: ${result.totalUnique} 个 (全源物理发现: ${result.totalDiscovered} 个, 扫描目录: ${result.scannedDirs.length} 处)`
|
|
87
|
+
: `Total Unique Skills: ${result.totalUnique} (Discovered: ${result.totalDiscovered}, Scanned Dirs: ${result.scannedDirs.length})`);
|
|
88
|
+
lines.push("");
|
|
89
|
+
// 来源分布
|
|
90
|
+
lines.push(isZh ? "【各智能体生态分布】:" : "[Agent Distribution]:");
|
|
91
|
+
for (const [source, count] of Object.entries(result.bySource)) {
|
|
92
|
+
if (count > 0) {
|
|
93
|
+
lines.push(` - ${source.toUpperCase()}: ${count} skills`);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
lines.push("");
|
|
97
|
+
// 作用域分布
|
|
98
|
+
lines.push(isZh ? "【作用域层级分布】:" : "[Scope Distribution]:");
|
|
99
|
+
for (const [scope, count] of Object.entries(result.byScope)) {
|
|
100
|
+
if (count > 0) {
|
|
101
|
+
lines.push(` - ${scope}: ${count} skills`);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
lines.push("");
|
|
105
|
+
// 冲突与覆盖信息
|
|
106
|
+
if (result.conflicts.length > 0) {
|
|
107
|
+
lines.push(isZh
|
|
108
|
+
? `【同名技能优先级决议 (${result.conflicts.length} 处)】:`
|
|
109
|
+
: `[Skill Precedence Conflicts (${result.conflicts.length})]:`);
|
|
110
|
+
for (const c of result.conflicts) {
|
|
111
|
+
lines.push(` * ${c.name}:`);
|
|
112
|
+
lines.push(` [生效] [${c.chosen.source}/${c.chosen.scope}] ${c.chosen.filePath}`);
|
|
113
|
+
for (const o of c.overridden) {
|
|
114
|
+
lines.push(` [覆盖] [${o.source}/${o.scope}] ${o.filePath}`);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
lines.push("");
|
|
118
|
+
}
|
|
119
|
+
// 技能简表
|
|
120
|
+
lines.push(isZh ? "【整合生效技能清单】:" : "[Effective Skills Catalog]:");
|
|
121
|
+
for (const s of result.skills) {
|
|
122
|
+
const tag = `[${(s.source || "custom").toUpperCase()}|${s.scope || "global"}]`;
|
|
123
|
+
lines.push(` - ${s.name} ${tag}: ${s.description || "No description"} (${s.filePath})`);
|
|
124
|
+
}
|
|
125
|
+
return lines.join("\n");
|
|
126
|
+
}
|
|
127
|
+
/** 校验技能文件健康状态与规格预算 */
|
|
128
|
+
export function verifySkillFile(filePath) {
|
|
129
|
+
const issues = [];
|
|
130
|
+
if (!existsSync(filePath)) {
|
|
131
|
+
return {
|
|
132
|
+
valid: false,
|
|
133
|
+
filePath,
|
|
134
|
+
sizeBytes: 0,
|
|
135
|
+
exceedsBudget: false,
|
|
136
|
+
hasFrontmatter: false,
|
|
137
|
+
name: basename(filePath, ".md"),
|
|
138
|
+
description: "",
|
|
139
|
+
issues: ["File does not exist"],
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
let sizeBytes = 0;
|
|
143
|
+
try {
|
|
144
|
+
const st = statSync(filePath);
|
|
145
|
+
sizeBytes = st.size;
|
|
146
|
+
}
|
|
147
|
+
catch {
|
|
148
|
+
issues.push("Cannot read file metadata");
|
|
149
|
+
}
|
|
150
|
+
const exceedsBudget = sizeBytes > 8192;
|
|
151
|
+
if (exceedsBudget) {
|
|
152
|
+
issues.push(`File size (${sizeBytes} B) exceeds the 8KB skill budget limit`);
|
|
153
|
+
}
|
|
154
|
+
let raw = "";
|
|
155
|
+
try {
|
|
156
|
+
raw = decodeText(readFileSync(filePath));
|
|
157
|
+
}
|
|
158
|
+
catch {
|
|
159
|
+
issues.push("Cannot decode file text");
|
|
160
|
+
}
|
|
161
|
+
const hasFrontmatter = raw.trim().startsWith("---");
|
|
162
|
+
if (!hasFrontmatter) {
|
|
163
|
+
issues.push("Missing YAML frontmatter (recommend adding --- name & description ---)");
|
|
164
|
+
}
|
|
165
|
+
const fallback = basename(filePath).toLowerCase() === "skill.md" ? basename(dirname(filePath)) : basename(filePath, ".md");
|
|
166
|
+
const parsed = parseSkillFrontmatter(raw, fallback);
|
|
167
|
+
if (!parsed.description || parsed.description === `Skill ${parsed.name}`) {
|
|
168
|
+
issues.push("Missing informative description");
|
|
169
|
+
}
|
|
170
|
+
return {
|
|
171
|
+
valid: issues.length === 0,
|
|
172
|
+
filePath,
|
|
173
|
+
sizeBytes,
|
|
174
|
+
exceedsBudget,
|
|
175
|
+
hasFrontmatter,
|
|
176
|
+
name: parsed.name,
|
|
177
|
+
description: parsed.description,
|
|
178
|
+
issues,
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* 跨 Agent 技能物理同步/软链维护:
|
|
183
|
+
* 将外部 Agent(如 Claude Code 或通用 Agents)的技能同步或软链至工作区或指定目录中。
|
|
184
|
+
*/
|
|
185
|
+
export function syncAgentSkills(opts) {
|
|
186
|
+
const targetDir = opts.targetDir ? opts.targetDir : join(opts.cwd, ".pi", "skills");
|
|
187
|
+
const mode = opts.mode || "copy";
|
|
188
|
+
const dryRun = !!opts.dryRun;
|
|
189
|
+
const scan = scanAllAgentSkills({ cwd: opts.cwd });
|
|
190
|
+
const targetSources = opts.sources && opts.sources.length > 0 ? new Set(opts.sources) : null;
|
|
191
|
+
const synced = [];
|
|
192
|
+
const skipped = [];
|
|
193
|
+
if (!dryRun && !existsSync(targetDir)) {
|
|
194
|
+
mkdirSync(targetDir, { recursive: true });
|
|
195
|
+
}
|
|
196
|
+
for (const skill of scan.skills) {
|
|
197
|
+
if (targetSources && skill.source && !targetSources.has(skill.source)) {
|
|
198
|
+
continue;
|
|
199
|
+
}
|
|
200
|
+
// 如果目标技能已经在目标目录中,跳过
|
|
201
|
+
if (skill.filePath.startsWith(targetDir)) {
|
|
202
|
+
skipped.push({ name: skill.name, reason: "Already in target directory" });
|
|
203
|
+
continue;
|
|
204
|
+
}
|
|
205
|
+
const isDirSkill = basename(skill.filePath).toLowerCase() === "skill.md";
|
|
206
|
+
const destPath = isDirSkill ? join(targetDir, skill.name, "SKILL.md") : join(targetDir, `${skill.name}.md`);
|
|
207
|
+
if (existsSync(destPath)) {
|
|
208
|
+
skipped.push({ name: skill.name, reason: "Destination already exists" });
|
|
209
|
+
continue;
|
|
210
|
+
}
|
|
211
|
+
if (!dryRun) {
|
|
212
|
+
try {
|
|
213
|
+
if (isDirSkill) {
|
|
214
|
+
mkdirSync(dirname(destPath), { recursive: true });
|
|
215
|
+
}
|
|
216
|
+
if (mode === "symlink") {
|
|
217
|
+
symlinkSync(skill.filePath, destPath);
|
|
218
|
+
}
|
|
219
|
+
else {
|
|
220
|
+
copyFileSync(skill.filePath, destPath);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
catch (err) {
|
|
224
|
+
skipped.push({ name: skill.name, reason: `FS Error: ${err.message}` });
|
|
225
|
+
continue;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
synced.push({ name: skill.name, from: skill.filePath, to: destPath });
|
|
229
|
+
}
|
|
230
|
+
return { synced, skipped };
|
|
231
|
+
}
|
|
@@ -45,9 +45,31 @@ export function formatSkillCatalog(skills, lang) {
|
|
|
45
45
|
return pick(lang, "当前没有可用技能。", "No skills are currently available.", "skill.catalog.empty");
|
|
46
46
|
}
|
|
47
47
|
const head = pick(lang, `可用技能(${skills.length}):`, `Available skills (${skills.length}):`, "skill.catalog.title", { count: skills.length });
|
|
48
|
-
const lines = skills.map((s) =>
|
|
48
|
+
const lines = skills.map((s) => {
|
|
49
|
+
const tag = s.source ? ` [${s.source.toUpperCase()}]` : "";
|
|
50
|
+
return `- ${s.name}${tag}${s.description.trim() ? ` — ${s.description.trim()}` : ""}`;
|
|
51
|
+
});
|
|
49
52
|
return `${head}\n${lines.join("\n")}`;
|
|
50
53
|
}
|
|
54
|
+
/** 生成多智能体技能整合分布统计报告文本 */
|
|
55
|
+
export function formatSkillSourcesReport(skills, lang) {
|
|
56
|
+
const counts = {};
|
|
57
|
+
for (const s of skills) {
|
|
58
|
+
const src = (s.source || "custom").toLowerCase();
|
|
59
|
+
counts[src] = (counts[src] || 0) + 1;
|
|
60
|
+
}
|
|
61
|
+
const isZh = lang === "zh";
|
|
62
|
+
const lines = [];
|
|
63
|
+
lines.push(isZh
|
|
64
|
+
? `【跨智能体技能整合报告】共整合 ${skills.length} 个可用技能:`
|
|
65
|
+
: `[Universal Skills Report] Total ${skills.length} available skills:`);
|
|
66
|
+
for (const [src, num] of Object.entries(counts)) {
|
|
67
|
+
lines.push(` - ${src.toUpperCase()}: ${num}`);
|
|
68
|
+
}
|
|
69
|
+
lines.push("");
|
|
70
|
+
lines.push(formatSkillCatalog(skills, lang));
|
|
71
|
+
return lines.join("\n");
|
|
72
|
+
}
|
|
51
73
|
/** 技能全文块(与 SDK 的 /skill:name 展开格式一致,前端按 skill 卡片渲染)。 */
|
|
52
74
|
export function renderSkillContent(name, location, body) {
|
|
53
75
|
return `<skill name="${name}" location="${location}">\n${body.trim()}\n</skill>`;
|
|
@@ -68,6 +90,9 @@ export function makeSkillTool(host, lang) {
|
|
|
68
90
|
name: Type.Optional(Type.String({
|
|
69
91
|
description: "Exact skill name from the catalog. Omit to list the current catalog.",
|
|
70
92
|
})),
|
|
93
|
+
action: Type.Optional(Type.String({
|
|
94
|
+
description: "Action: omit or 'read' to load skill text; 'list' to show catalog; 'report' to view multi-agent sources.",
|
|
95
|
+
})),
|
|
71
96
|
}),
|
|
72
97
|
execute: async (_id, p) => {
|
|
73
98
|
let skills = [];
|
|
@@ -78,9 +103,13 @@ export function makeSkillTool(host, lang) {
|
|
|
78
103
|
skills = [];
|
|
79
104
|
}
|
|
80
105
|
const L = getLang();
|
|
106
|
+
const action = typeof p.action === "string" ? p.action.trim().toLowerCase() : "";
|
|
81
107
|
const name = typeof p.name === "string" ? p.name.trim() : "";
|
|
82
|
-
|
|
83
|
-
|
|
108
|
+
if (action === "report") {
|
|
109
|
+
return text(formatSkillSourcesReport(skills, L), { count: skills.length });
|
|
110
|
+
}
|
|
111
|
+
// 无名或请求列表 → 名录 + 用法。
|
|
112
|
+
if (!name || action === "list") {
|
|
84
113
|
const hint = pick(L, "用 skill({name}) 按名取全文。", "Use skill({name}) to load the full text by name.", "skill.catalog.hint");
|
|
85
114
|
return text(`${formatSkillCatalog(skills, L)}\n${hint}`, { count: skills.length });
|
|
86
115
|
}
|
package/dist/server/soft-cap.js
CHANGED
|
@@ -1,15 +1,24 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* 自定义上下文压缩阈值(Soft Cap,issue #229)。
|
|
2
|
+
* 自定义上下文压缩阈值(Soft Cap,issue #229,issue #716,issue #773)。
|
|
3
3
|
*
|
|
4
4
|
* 背景:SDK 的自动压缩只看物理上限(shouldCompact:tokens > window - reserveTokens,
|
|
5
5
|
* reserveTokens 默认 16384)。对 1M 上下文的模型会堆到 ~900K 才压;对 Grok 这类
|
|
6
6
|
* 200K 起阶梯翻倍计费的模型,会在高价区跑很久,还伴随长上下文降智。
|
|
7
7
|
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
8
|
+
* 实现机制(双层管控,两层共用同一个软上限 cap):
|
|
9
|
+
* 1. 回合内层(SDK reserve,issue #773):把 compaction.reserveTokens 逐会话算成
|
|
10
|
+
* cw - cap(下限仍是默认 16384),让 SDK 在**每次工具调用间隙**的
|
|
11
|
+
* _compactBeforeNextAssistantResponse 里就能在 cap 处压缩。自治长跑(子代理、
|
|
12
|
+
* 单回合几十次工具调用)全程没有空闲态,只有这一层能拦住它。
|
|
13
|
+
* 必须是「逐会话无状态重算」(各自用自己当前模型算),否则换模型会残留上一模型的
|
|
14
|
+
* W - C,这正是 #716 当初撤掉注入的原因;重算点见 applyCompactionOverrides。
|
|
15
|
+
* 2. 空闲态层(pi-web-ui 主动压缩):回合结算后 / 新一轮提问前,若有效 token 已达 cap
|
|
16
|
+
* 则主动 session.compact()。它负责 reserve 管不到的场景:cap 中途下调、附件注入
|
|
17
|
+
* 超阈、从磁盘恢复的已超阈会话(首个请求前没有任何检查点)。
|
|
18
|
+
* 3. 物理防爆始终在:reserve 只取 max(默认 16384, cw - cap),触发点永远不晚于
|
|
19
|
+
* cw - 16384;cap 关闭/非法时 reserve 回落默认值,等于原样的物理兜底线。
|
|
20
|
+
*
|
|
21
|
+
* softCapToReserve / softCapReserveFor 同时服务分层上下文预算裁剪(context-budget-runner)。
|
|
13
22
|
*/
|
|
14
23
|
import { DEFAULT_COMPACTION_SETTINGS } from "@earendil-works/pi-coding-agent";
|
|
15
24
|
/** SDK 默认保留 token(软上限关闭时的回填值)。 */
|
|
@@ -100,3 +109,18 @@ export function softCapToReserve(contextWindow, cap) {
|
|
|
100
109
|
return null;
|
|
101
110
|
return reserve;
|
|
102
111
|
}
|
|
112
|
+
/** 注入 SDK 的 reserveTokens(issue #773):软上限合法时 = cw - cap,否则回落默认值。
|
|
113
|
+
*
|
|
114
|
+
* 额外守卫(keepRecentTokens):SDK 压缩按 keepRecentTokens(默认 20000)留尾部,
|
|
115
|
+
* 若 cap ≤ keepRecent + SOFT_CAP_MIN_HEADROOM,压完立刻又超阈 → 回合内每个工具间隙
|
|
116
|
+
* 都重压一次(每次都要付摘要请求的钱),比撞墙还贵。这种「压不下来」的 cap 一律不注射,
|
|
117
|
+
* 交给空闲态层与物理兜底。keepRecentTokens 未知(0/非法)时不做该守卫。 */
|
|
118
|
+
export function softCapReserveFor(contextWindow, cap, keepRecentTokens = 0) {
|
|
119
|
+
const reserve = softCapToReserve(contextWindow, cap);
|
|
120
|
+
if (reserve === null)
|
|
121
|
+
return null;
|
|
122
|
+
if (Number.isFinite(keepRecentTokens) && keepRecentTokens > 0 && cap <= keepRecentTokens + SOFT_CAP_MIN_HEADROOM) {
|
|
123
|
+
return null;
|
|
124
|
+
}
|
|
125
|
+
return Math.max(DEFAULT_COMPACTION_RESERVE_TOKENS, reserve);
|
|
126
|
+
}
|
|
@@ -80,9 +80,18 @@ export function toSubagentSnapshot(conv) {
|
|
|
80
80
|
catch {
|
|
81
81
|
// session being replaced — report defaults
|
|
82
82
|
}
|
|
83
|
+
let thinkingLevel;
|
|
84
|
+
try {
|
|
85
|
+
thinkingLevel = conv.session.thinkingLevel ?? conv.subagentThinking;
|
|
86
|
+
}
|
|
87
|
+
catch {
|
|
88
|
+
thinkingLevel = conv.subagentThinking;
|
|
89
|
+
}
|
|
83
90
|
const fullPrompt = conv.subagentPrompt ?? "";
|
|
84
91
|
const sm = conv.session.sessionManager;
|
|
85
92
|
const isPersisted = !conv.isSubagent || (typeof sm?.isPersisted === "function" && sm.isPersisted());
|
|
93
|
+
const m = conv.session.model;
|
|
94
|
+
const modelKey = m ? `${m.provider}/${m.id}` : (conv.subagentTemplate?.model ?? undefined);
|
|
86
95
|
return {
|
|
87
96
|
convId: conv.id,
|
|
88
97
|
type: conv.subagentType ?? "general",
|
|
@@ -95,12 +104,24 @@ export function toSubagentSnapshot(conv) {
|
|
|
95
104
|
error,
|
|
96
105
|
canceled,
|
|
97
106
|
messageCount,
|
|
98
|
-
model:
|
|
107
|
+
model: modelKey,
|
|
108
|
+
thinkingLevel,
|
|
99
109
|
output: conv.session.getLastAssistantText() ?? "",
|
|
100
110
|
parentId: conv.parentId,
|
|
101
111
|
persisted: isPersisted,
|
|
102
112
|
handoffTo: conv.peerHandoffTo ? [...conv.peerHandoffTo] : undefined,
|
|
103
113
|
handoffFrom: conv.peerHandoffFrom ? [...conv.peerHandoffFrom] : undefined,
|
|
114
|
+
worktree: conv.subagentWorktree
|
|
115
|
+
? {
|
|
116
|
+
path: conv.subagentWorktree.worktreePath,
|
|
117
|
+
branch: conv.subagentWorktree.branch,
|
|
118
|
+
cleanedUp: Boolean(conv.subagentWorktree.cleanedUp),
|
|
119
|
+
isDirty: conv.subagentWorktree.isDirty,
|
|
120
|
+
uncommittedCount: conv.subagentWorktree.uncommittedCount,
|
|
121
|
+
aheadCount: conv.subagentWorktree.aheadCount,
|
|
122
|
+
error: conv.subagentWorktree.error,
|
|
123
|
+
}
|
|
124
|
+
: undefined,
|
|
104
125
|
};
|
|
105
126
|
}
|
|
106
127
|
/** 列举并排序子代理快照集合 */
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
// ---------------------------------------------------------------------------
|
|
2
|
+
// subagent-notify.ts — 子代理终态自动通知与结构化交付契约(issue #713)
|
|
3
|
+
// ---------------------------------------------------------------------------
|
|
4
|
+
// 负责:
|
|
5
|
+
// 1. extractSubagentConclusion: 提炼子代理输出的核心结论(保留首尾重点,折叠冗余日志)
|
|
6
|
+
// 2. formatSubagentsCompletionNotice: 将批处理/防抖收敛的一组终态子代理格式化为
|
|
7
|
+
// 高信噪比、低 Token 占用的父对话唤醒汇报
|
|
8
|
+
// ---------------------------------------------------------------------------
|
|
9
|
+
import { pick } from "./i18n.js";
|
|
10
|
+
import { subagentRunOutcome } from "./subagent-helpers.js";
|
|
11
|
+
/**
|
|
12
|
+
* 从子代理的长文本输出中提取核心结论:
|
|
13
|
+
* - 输出较短(<= 20 行)时原样返回;
|
|
14
|
+
* - 输出较长时保留前 3 行任务概况与后 15 行最终总结/结论,中间过程性输出自适应折叠;
|
|
15
|
+
* - 空输出给出可读占位符。
|
|
16
|
+
*/
|
|
17
|
+
export function extractSubagentConclusion(output, lang = "en") {
|
|
18
|
+
const trimmed = (output ?? "").trim();
|
|
19
|
+
if (!trimmed) {
|
|
20
|
+
return lang === "zh" ? "(无输出结果)" : "(no output produced)";
|
|
21
|
+
}
|
|
22
|
+
const lines = trimmed.split("\n");
|
|
23
|
+
if (lines.length <= 20) {
|
|
24
|
+
return trimmed;
|
|
25
|
+
}
|
|
26
|
+
const head = lines.slice(0, 3).join("\n");
|
|
27
|
+
const tail = lines.slice(-15).join("\n");
|
|
28
|
+
const omitted = lines.length - 18;
|
|
29
|
+
const omitMarker = lang === "zh"
|
|
30
|
+
? `… [中间省略 ${omitted} 行过程日志,完整转录可通过 get_result 查看] …`
|
|
31
|
+
: `… [${omitted} lines omitted, full transcript available via get_result] …`;
|
|
32
|
+
return `${head}\n${omitMarker}\n${tail}`;
|
|
33
|
+
}
|
|
34
|
+
/** 短 id(前 8 字符) */
|
|
35
|
+
function shortId(id) {
|
|
36
|
+
return id.slice(0, 8);
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* 格式化聚合的一组终态子代理为父对话的入站通知。
|
|
40
|
+
* 多个子代理同时完成时合成一条结构化汇报,避免碎片化打断父对话。
|
|
41
|
+
*/
|
|
42
|
+
export function formatSubagentsCompletionNotice(subagents, lang = "en", fallbackOriginalParentId) {
|
|
43
|
+
if (subagents.length === 0)
|
|
44
|
+
return "";
|
|
45
|
+
const count = subagents.length;
|
|
46
|
+
const fallbackNote = fallbackOriginalParentId
|
|
47
|
+
? pick(lang, `(原父对话 ${shortId(fallbackOriginalParentId)} 已不在,转至当前活跃对话继续)\n`, `(Original parent chat ${shortId(fallbackOriginalParentId)} is gone; redirected here)\n`, "subagents.notify.fallback", { parentId: shortId(fallbackOriginalParentId) })
|
|
48
|
+
: "";
|
|
49
|
+
const titleHeader = pick(lang, `[子代理执行完成通知] 共有 ${count} 个子代理已完成:`, `[Subagent Completion Notice] ${count} subagent(s) completed:`, "subagents.notify.header", { count });
|
|
50
|
+
const items = subagents.map((conv) => {
|
|
51
|
+
const sId = shortId(conv.id);
|
|
52
|
+
const type = conv.subagentType ?? "general";
|
|
53
|
+
const roleModel = conv.session.model
|
|
54
|
+
? `${conv.session.model.provider}/${conv.session.model.id}`
|
|
55
|
+
: conv.subagentTemplate?.model || "default";
|
|
56
|
+
const thinking = conv.session.thinkingLevel ?? conv.subagentThinking ?? "default";
|
|
57
|
+
const metaTag = `${type} · ${roleModel}:${thinking}`;
|
|
58
|
+
const outcome = subagentRunOutcome(conv);
|
|
59
|
+
let statusLabel;
|
|
60
|
+
if (outcome.error) {
|
|
61
|
+
statusLabel = pick(lang, `❌ 运行失败(${outcome.error})`, `❌ Failed (${outcome.error})`, "subagents.notify.status.failed", { error: outcome.error });
|
|
62
|
+
}
|
|
63
|
+
else if (outcome.canceled) {
|
|
64
|
+
statusLabel = pick(lang, "⚠️ 已中止", "⚠️ Canceled", "subagents.notify.status.canceled");
|
|
65
|
+
}
|
|
66
|
+
else {
|
|
67
|
+
statusLabel = pick(lang, "✅ 正常完成", "✅ Done", "subagents.notify.status.done");
|
|
68
|
+
}
|
|
69
|
+
const rawOutput = conv.session.getLastAssistantText() ?? "";
|
|
70
|
+
const conclusion = extractSubagentConclusion(rawOutput, lang);
|
|
71
|
+
const indentedConclusion = conclusion
|
|
72
|
+
.split("\n")
|
|
73
|
+
.map((l) => ` > ${l}`)
|
|
74
|
+
.join("\n");
|
|
75
|
+
const taskLine = conv.title ? ` - ${pick(lang, "目标", "Goal", "subagents.notify.goal")}: ${conv.title}\n` : "";
|
|
76
|
+
let wtLine = "";
|
|
77
|
+
if (conv.subagentWorktree) {
|
|
78
|
+
const wt = conv.subagentWorktree;
|
|
79
|
+
if (wt.cleanedUp) {
|
|
80
|
+
wtLine = ` - ${pick(lang, "工作树隔离", "Worktree isolation", "subagents.notify.worktree")}: ${pick(lang, "无文件修改,临时工作树已自动清理", "No changes made; temporary worktree cleaned up", "subagents.notify.worktree.cleaned")}\n`;
|
|
81
|
+
}
|
|
82
|
+
else {
|
|
83
|
+
wtLine =
|
|
84
|
+
` - ${pick(lang, "工作树隔离", "Worktree isolation", "subagents.notify.worktree")}: ` +
|
|
85
|
+
pick(lang, `已保留分支 ${wt.branch}(${wt.uncommittedCount ?? 0} 处未提交修改,${wt.aheadCount ?? 0} 个新提交)`, `Preserved branch ${wt.branch} (${wt.uncommittedCount ?? 0} uncommitted, ${wt.aheadCount ?? 0} commits ahead)`, "subagents.notify.worktree.preserved", { branch: wt.branch, uncommitted: wt.uncommittedCount ?? 0, ahead: wt.aheadCount ?? 0 }) +
|
|
86
|
+
`\n - ${pick(lang, "工作树路径", "Worktree path", "subagents.notify.worktree.path")}: ${wt.worktreePath}\n`;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
return `- **${sId}**(${metaTag})— ${statusLabel}\n${taskLine}${wtLine} - ${pick(lang, "产出摘要", "Summary", "subagents.notify.summary")}:\n${indentedConclusion}`;
|
|
90
|
+
});
|
|
91
|
+
const footer = pick(lang, '\n如需调取子代理完整对话转录与工具执行详情,可调用 subagent(action="get_result", runId="<id>")。', '\nFor full transcripts or detailed tool logs, call subagent(action="get_result", runId="<id>").', "subagents.notify.footer");
|
|
92
|
+
return `${fallbackNote}${titleHeader}\n\n${items.join("\n\n")}${footer}`;
|
|
93
|
+
}
|