pi-web-ui 0.98.0 → 0.100.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 +85 -5
- package/README.md +2 -1
- package/README.zh-CN.md +2 -1
- package/bin/pi-web-ui.mjs +174 -36
- package/dist/server/agent-service.js +1169 -152
- package/dist/server/approval-rules.js +95 -23
- package/dist/server/attachments.js +55 -0
- package/dist/server/bg-servers.js +82 -2
- package/dist/server/claim-files-tool.js +4 -4
- package/dist/server/client-state.js +41 -0
- package/dist/server/compact-context-tool.js +10 -9
- package/dist/server/conversation-read-tool.js +7 -8
- package/dist/server/conversation-touches.js +19 -0
- package/dist/server/delegate-task.js +10 -14
- package/dist/server/dsh/dsh-agent-service.js +116 -12
- package/dist/server/edit-soft-tool.js +10 -12
- package/dist/server/eval-tool.js +26 -6
- package/dist/server/goal-evidence.js +173 -0
- package/dist/server/goal-service.js +78 -15
- package/dist/server/hashline-engine.js +198 -31
- package/dist/server/index.js +55 -9
- package/dist/server/load-tools-tool.js +100 -0
- package/dist/server/lsp-tool.js +10 -16
- package/dist/server/marker-service.js +53 -12
- package/dist/server/markers/builtins/action.js +108 -0
- package/dist/server/markers/index.js +4 -1
- package/dist/server/model-enrich.js +2 -0
- package/dist/server/patch-remote-catalog.js +28 -10
- package/dist/server/patch-tool.js +74 -38
- package/dist/server/plan-manager.js +71 -30
- package/dist/server/plan-mode.js +7 -6
- package/dist/server/plugin-api-catalog.js +10 -3
- package/dist/server/plugin-conversation-view.js +47 -0
- package/dist/server/plugins.js +113 -26
- package/dist/server/present-files-tool.js +10 -11
- package/dist/server/preset-fields.js +693 -0
- package/dist/server/preset-share.js +1178 -0
- package/dist/server/prompt-composer.js +23 -9
- package/dist/server/protocol-version.js +1 -1
- package/dist/server/read-tool.js +8 -10
- package/dist/server/resolve-global-sdk.js +80 -18
- package/dist/server/schedule-agent-tool.js +147 -146
- package/dist/server/sdk-origin.js +125 -37
- package/dist/server/settings-service.js +103 -84
- package/dist/server/skill-tool.js +3 -4
- package/dist/server/subagents.js +15 -22
- package/dist/server/terminals.js +29 -39
- package/dist/server/tool-approval.js +3 -1
- package/dist/server/tool-manager.js +63 -27
- package/dist/server/tool-prompt-overrides.js +158 -0
- package/dist/server/tool-prompts.js +42 -0
- package/dist/server/tool-signature.js +104 -0
- package/dist/server/update-check.js +0 -15
- package/dist/server/workspace-snapshot.js +42 -11
- package/package.json +5 -3
- package/plugin-sdk/README.md +8 -4
- package/plugin-sdk/import-check.mjs +210 -0
- package/plugin-sdk/index.d.ts +4 -1
- package/plugin-sdk/index.mjs +1 -0
- package/plugins/catalog.json +33 -2
- package/themes/zhupi-dark.css +1 -1
- package/themes/zhupi.css +1 -1
- package/web/dist/assets/{TerminalPanel-C88r3r3Q.js → TerminalPanel-C3I1Mc-C.js} +2 -2
- package/web/dist/assets/index-B-E2EM_0.css +1 -0
- package/web/dist/assets/index-BYumAaGi.js +379 -0
- package/web/dist/index.html +2 -2
- package/web/dist/sw.js +1 -1
- package/web/dist/assets/index-2jDtjHvW.css +0 -1
- package/web/dist/assets/index-BjdK7s1M.js +0 -368
|
@@ -532,7 +532,9 @@ export class GoalService {
|
|
|
532
532
|
conv.goalGeneration += 1;
|
|
533
533
|
// 上一轮目标可能还留着常驻执行者子代理(委托执行):先停掉再开新的,
|
|
534
534
|
// 否则旧循环会在新目标上继续派活(代次已作废,但角色对话得收)。
|
|
535
|
-
|
|
535
|
+
// await 到 dismiss 完全落定:后面的 spawn 名额检查才不会数到还在收尾的
|
|
536
|
+
// 旧执行者而误报上限(issue #464;stopDelegated 自身已按会话串行化)。
|
|
537
|
+
await this.stopDelegated(conv);
|
|
536
538
|
const goal = conv.goal;
|
|
537
539
|
goal.reviewing = false;
|
|
538
540
|
goal.conversationId = goalConversationId;
|
|
@@ -1125,7 +1127,8 @@ export class GoalService {
|
|
|
1125
1127
|
const conv = this.host.activeConv();
|
|
1126
1128
|
conv.goalGeneration += 1;
|
|
1127
1129
|
// 委托执行:停掉在飞的执行者(循环靠代次作废 + 代次守卫退出)。
|
|
1128
|
-
|
|
1130
|
+
// await 落定,保证旧执行者已移出会话表,后续重设目标不再误报名额(issue #464)。
|
|
1131
|
+
await this.stopDelegated(conv);
|
|
1129
1132
|
this.resetLoopCounters(conv);
|
|
1130
1133
|
this.clearGoalFields(conv);
|
|
1131
1134
|
this.emitGoalStatus();
|
|
@@ -1159,14 +1162,15 @@ export class GoalService {
|
|
|
1159
1162
|
*/
|
|
1160
1163
|
async stopAllGoals() {
|
|
1161
1164
|
let stopped = 0;
|
|
1162
|
-
//
|
|
1163
|
-
|
|
1164
|
-
for (const convId of this.delegatedLoops.keys()) {
|
|
1165
|
+
// 快照迭代:await stopDelegated 期间,循环退出的回调可能增删这张表。
|
|
1166
|
+
for (const convId of [...this.delegatedLoops.keys()]) {
|
|
1165
1167
|
const conv = this.host.getConv(convId);
|
|
1166
1168
|
if (!conv)
|
|
1167
1169
|
continue;
|
|
1168
1170
|
conv.goalGeneration += 1; // 作废在飞回调(循环靠代次守卫退出)
|
|
1169
|
-
|
|
1171
|
+
// 逐个 await 停/收落定(stopDelegated 已按会话串行化,issue #464):
|
|
1172
|
+
// 停执行者 + 唤醒 verdict 等待者 + 清 roles/phase
|
|
1173
|
+
await this.stopDelegated(conv);
|
|
1170
1174
|
this.resetLoopCounters(conv);
|
|
1171
1175
|
this.clearGoalFields(conv);
|
|
1172
1176
|
stopped++;
|
|
@@ -1210,6 +1214,8 @@ export class GoalService {
|
|
|
1210
1214
|
}
|
|
1211
1215
|
conv.goalGeneration += 1;
|
|
1212
1216
|
// 委托执行:手动停止也要把在飞的执行者停掉(否则它还在后台改工作区)。
|
|
1217
|
+
// 本钩子是同步上下文,fire-and-forget 即可:stopDelegated 已按会话
|
|
1218
|
+
// 串行化(issue #464),重设/清除目标的一方会先等这次 dismiss 落定。
|
|
1213
1219
|
this.stopDelegated(conv);
|
|
1214
1220
|
this.resetLoopCounters(conv);
|
|
1215
1221
|
g.conversationId = null;
|
|
@@ -1403,7 +1409,24 @@ export class GoalService {
|
|
|
1403
1409
|
conv.goal.roles = {};
|
|
1404
1410
|
return exec?.convId;
|
|
1405
1411
|
}
|
|
1406
|
-
|
|
1412
|
+
stopInflight = new Map();
|
|
1413
|
+
/**
|
|
1414
|
+
* 停掉委托执行者(stop + dismiss + 唤醒等待者)。同一会话并发调用时按序串行:
|
|
1415
|
+
* 上一次 stop/dismiss 未落定前,下一次先等它 —— 否则重设目标时旧执行者尚未
|
|
1416
|
+
* 移出会话表,随后 spawn 的名额检查会数到它而误报容量上限(issue #464)。
|
|
1417
|
+
* 同步上下文(onAgentEnd 等钩子)可以继续 fire-and-forget,串行化由这里兜住。
|
|
1418
|
+
*/
|
|
1419
|
+
stopDelegated(conv) {
|
|
1420
|
+
const prev = this.stopInflight.get(conv.id);
|
|
1421
|
+
const run = prev ? prev.catch(() => { }).then(() => this.stopDelegatedNow(conv)) : this.stopDelegatedNow(conv);
|
|
1422
|
+
this.stopInflight.set(conv.id, run);
|
|
1423
|
+
void run.finally(() => {
|
|
1424
|
+
if (this.stopInflight.get(conv.id) === run)
|
|
1425
|
+
this.stopInflight.delete(conv.id);
|
|
1426
|
+
});
|
|
1427
|
+
return run;
|
|
1428
|
+
}
|
|
1429
|
+
async stopDelegatedNow(conv) {
|
|
1407
1430
|
// 排队的启动请求一并作废:setGoal 会在后面按新代次重新排,clearGoal 则不需要。
|
|
1408
1431
|
this.delegatedPending.delete(conv.id);
|
|
1409
1432
|
conv.awaitingVerdict = undefined;
|
|
@@ -1554,16 +1577,19 @@ export class GoalService {
|
|
|
1554
1577
|
g.status = `审查中(第 ${round}${this.roundsLabel(budget)} 轮)…`;
|
|
1555
1578
|
g.statusEn = `Reviewing (round ${round}${this.roundsLabel(budget)})…`;
|
|
1556
1579
|
this.emitGoalStatus();
|
|
1557
|
-
const verdict = await this.askDelegatedReview(conv, goalGeneration, round, budget, sample.output);
|
|
1580
|
+
const verdict = await this.askDelegatedReview(conv, goalGeneration, round, budget, sample.output, execId);
|
|
1558
1581
|
if (!this.isCurrentDelegated(conv, goalGeneration))
|
|
1559
1582
|
return;
|
|
1560
1583
|
if (verdict === "invalid" || verdict === "timeout" || verdict === "gone") {
|
|
1561
1584
|
await this.finishDelegated(conv, goalGeneration, "blocked", round, this.roleFailureText(`review-${verdict}`), goalText);
|
|
1562
1585
|
return;
|
|
1563
1586
|
}
|
|
1587
|
+
// #543 §2:空 feedback 兜底 —— verdict JSON 允许 `{"verdict":"fail","feedback":""}`,
|
|
1588
|
+
// 照原样传下去,下一轮执行者只会收到「上一轮审查意见:」+ 空行,白烧一轮。
|
|
1589
|
+
const verdictFeedback = this.ensureReviewerFeedback(verdict.verdict, verdict.feedback, feedback);
|
|
1564
1590
|
// 审查结论卡:把 verdict JSON 翻译成人话框住(裸 JSON 留在流里,但不再是唯一载体)。
|
|
1565
1591
|
if (this.isCurrentDelegated(conv, goalGeneration)) {
|
|
1566
|
-
await this.pushReviewCard(conv, this.reviewCardText(verdict.verdict, round, budget,
|
|
1592
|
+
await this.pushReviewCard(conv, this.reviewCardText(verdict.verdict, round, budget, verdictFeedback), {
|
|
1567
1593
|
phase: "result",
|
|
1568
1594
|
round,
|
|
1569
1595
|
verdict: verdict.verdict,
|
|
@@ -1572,10 +1598,10 @@ export class GoalService {
|
|
|
1572
1598
|
if (!this.isCurrentDelegated(conv, goalGeneration))
|
|
1573
1599
|
return;
|
|
1574
1600
|
if (verdict.verdict === "pass") {
|
|
1575
|
-
await this.finishDelegated(conv, goalGeneration, "pass", round,
|
|
1601
|
+
await this.finishDelegated(conv, goalGeneration, "pass", round, verdictFeedback, goalText);
|
|
1576
1602
|
return;
|
|
1577
1603
|
}
|
|
1578
|
-
feedback =
|
|
1604
|
+
feedback = verdictFeedback;
|
|
1579
1605
|
// fail:回到循环顶部(预算检查在那里兜底)。
|
|
1580
1606
|
}
|
|
1581
1607
|
}
|
|
@@ -1721,7 +1747,7 @@ export class GoalService {
|
|
|
1721
1747
|
return { output, errorSnippet: currentError };
|
|
1722
1748
|
}
|
|
1723
1749
|
/** 审查:把审查指令交给主对话,等 verdict;无 JSON 允许重试一次。 */
|
|
1724
|
-
async askDelegatedReview(conv, goalGeneration, round, budget, execOutput) {
|
|
1750
|
+
async askDelegatedReview(conv, goalGeneration, round, budget, execOutput, execId) {
|
|
1725
1751
|
for (let attempt = 0; attempt < 2; attempt++) {
|
|
1726
1752
|
// 委托执行下用户仍可自由聊天:先等主对话空闲,否则审查指令会被当成
|
|
1727
1753
|
// steer 插进用户自己的回合里(语义冲突)。
|
|
@@ -1732,7 +1758,7 @@ export class GoalService {
|
|
|
1732
1758
|
return "timeout";
|
|
1733
1759
|
const planDesc = this.host.describePlan?.(conv.id) ?? "";
|
|
1734
1760
|
const text = attempt === 0
|
|
1735
|
-
? this.reviewerRoundPrompt(conv.goal.goal ?? "", round, budget, execOutput, planDesc)
|
|
1761
|
+
? this.reviewerRoundPrompt(conv.goal.goal ?? "", round, budget, execOutput, planDesc, this.readExecutorEvidence(execId))
|
|
1736
1762
|
: this.verdictRetryPrompt();
|
|
1737
1763
|
const verdict = await this.deliverAndWait(conv, round, text);
|
|
1738
1764
|
if (verdict !== "invalid")
|
|
@@ -1740,6 +1766,34 @@ export class GoalService {
|
|
|
1740
1766
|
}
|
|
1741
1767
|
return "invalid";
|
|
1742
1768
|
}
|
|
1769
|
+
/** 执行者会话最近的工具/命令证据(#543 §1)。宿主未接线 / 读失败 / 空会话 → 空串,
|
|
1770
|
+
* 提示词据此跳过整段(不注入空标题、不改变老行为)。 */
|
|
1771
|
+
readExecutorEvidence(execId) {
|
|
1772
|
+
try {
|
|
1773
|
+
return this.host.readRoleEvidence?.(execId)?.trim() ?? "";
|
|
1774
|
+
}
|
|
1775
|
+
catch {
|
|
1776
|
+
return "";
|
|
1777
|
+
}
|
|
1778
|
+
}
|
|
1779
|
+
/** 审查结论 feedback 为空时的兜底(#543 §2;调用点见 runDelegatedLoop)。
|
|
1780
|
+
* - 有内容 → 原样返回(不动审查者的措辞);
|
|
1781
|
+
* - pass 且无说明 → 不编造通过理由,只补一句中性标注;
|
|
1782
|
+
* - fail 且上一轮有意见 → 沿用上一轮(标注是沿用的,避免执行者以为拿到了新指令);
|
|
1783
|
+
* - fail 且两轮都空 → 给一条可执行的失败说明(复核目标 + 补证据),别让执行者空转。 */
|
|
1784
|
+
ensureReviewerFeedback(verdict, feedback, prevFeedback) {
|
|
1785
|
+
const fb = feedback.trim();
|
|
1786
|
+
if (fb)
|
|
1787
|
+
return fb;
|
|
1788
|
+
if (verdict === "pass") {
|
|
1789
|
+
return pick(this.lang(), "(审查者未附说明)", "(the reviewer gave no note)", "goal.role.review.feedback.pass");
|
|
1790
|
+
}
|
|
1791
|
+
const prev = prevFeedback.trim();
|
|
1792
|
+
if (prev) {
|
|
1793
|
+
return pick(this.lang(), `(审查者本轮未给出新意见,沿用上一轮意见)\n${prev}`, `(the reviewer gave no new feedback this round — carrying the previous round's over)\n${prev}`, "goal.role.review.feedback.prev");
|
|
1794
|
+
}
|
|
1795
|
+
return pick(this.lang(), "审查者判 fail 但未给出说明。请复核目标的每一条要求,补齐尚未完成或尚未验证的部分,并在自述里给出可核验的证据(跑过的命令与输出)。", "The reviewer returned fail without a note. Re-check every requirement in the goal, finish what is unfinished or unverified, and back it up with verifiable evidence (the commands you ran and their output).", "goal.role.review.feedback.empty");
|
|
1796
|
+
}
|
|
1743
1797
|
/** 等主对话空闲(事件驱动,不轮询);超上限返回 false。 */
|
|
1744
1798
|
async waitMainIdle(conv) {
|
|
1745
1799
|
const end = Date.now() + this.roleDeadline();
|
|
@@ -2033,7 +2087,7 @@ export class GoalService {
|
|
|
2033
2087
|
? `✅ Review round ${round}${rounds} passed${fb ? `: ${fb}` : ""}`
|
|
2034
2088
|
: `❌ Review round ${round}${rounds} failed${fb ? `: ${fb}` : ""}`, "goal.role.card.result");
|
|
2035
2089
|
}
|
|
2036
|
-
reviewerRoundPrompt(goalText, round, budget, execOutput, planDesc = "") {
|
|
2090
|
+
reviewerRoundPrompt(goalText, round, budget, execOutput, planDesc = "", evidence = "") {
|
|
2037
2091
|
const rounds = this.roundsLabel(budget);
|
|
2038
2092
|
const out = execOutput.trim().slice(0, 4000);
|
|
2039
2093
|
const planBlockZh = planDesc && planDesc !== "No active plan."
|
|
@@ -2042,7 +2096,16 @@ export class GoalService {
|
|
|
2042
2096
|
const planBlockEn = planDesc && planDesc !== "No active plan."
|
|
2043
2097
|
? `\n\n# Task Plan Board\n${planDesc}\nWhen verifying, also check whether the above plan steps have been legitimately advanced or completed.`
|
|
2044
2098
|
: "";
|
|
2045
|
-
|
|
2099
|
+
// #543 §1:执行者的工具/命令证据(服务端自动采集)。只保留输出尾部、可能被截断 ——
|
|
2100
|
+
// 契约里写明这一点,免得审查者把「没看到」读成「没发生」。
|
|
2101
|
+
const ev = evidence.trim();
|
|
2102
|
+
const evidenceBlockZh = ev
|
|
2103
|
+
? `\n\n【执行者最近的工具与命令证据(服务端自动采集,只保留输出尾部,可能被截断)】\n${ev}`
|
|
2104
|
+
: "";
|
|
2105
|
+
const evidenceBlockEn = ev
|
|
2106
|
+
? `\n\n# Executor's recent tool & command evidence (auto-collected, output tails only, may be truncated)\n${ev}`
|
|
2107
|
+
: "";
|
|
2108
|
+
return pick(this.lang(), `你是严格、独立的验收者。只判断目标是否被完全满足:不要相信描述,去看工作区的实际状态。\n\n【目标】\n${goalText}\n\n【这是第 ${round}${rounds} 轮】${planBlockZh}\n\n【执行者本轮自述】\n${out || "(执行者本轮没有给出自述)"}${evidenceBlockZh}\n\n你可以用只读手段核实:read / grep / scm(只读 git)/ 只读 bash(跑测试)。\n\n判定口径:\n- 只判【执行者本轮自述】里**声称已完成**的条目;本轮没声称完成的后续阶段不构成 fail 理由(目标写成「完成阶段 3 并收尾后续」也不代表这一轮要做完所有阶段)。\n- 忽略与目标无关的本地改动(其它项目的补丁、工具/模型配置、临时文件)。\n- 声称完成但自述与证据里都没有对应命令输出或文件证据的,必须 fail,并点名缺哪条命令的输出。\n- feedback 不得为空:fail 时必须给出可以直接动手改的具体待改项。\n\n只输出一个 JSON 对象,不要有任何其他文本、不要代码围栏、不要复述下面的形状示例。本回合写类与派发类工具会被服务端直接拒绝(不要试)。字段:verdict 只能填 pass(目标已完全满足,一句话说明满足了什么)或 fail(未满足,给出可以直接动手改的具体待改项);feedback 是一句话说明。形状示例(不要照抄尖括号里的占位符):\n{"verdict":"<pass|fail>","feedback":"<一句话说明>"}\n[goal-review]`, `You are a strict, independent acceptor. Judge only whether the goal is fully satisfied: do not trust the summary — inspect the actual workspace state.\n\n# Goal\n${goalText}\n\n# This is round ${round}${rounds}${planBlockEn}\n\n# Executor's summary this round\n${out || "(the executor produced no summary)"}${evidenceBlockEn}\n\nYou may verify with read-only means: read / grep / scm (read-only git) / read-only bash (run tests).\n\nJudging rules:\n- Judge only the items the executor's summary **claims to have completed this round**; later phases it did not claim this round are NOT grounds for fail (a goal phrased as "finish phase 3 and wrap up the rest" does not mean all phases must land this round).\n- Ignore local changes unrelated to the goal (other projects' patches, tool/model settings, scratch files).\n- If a claimed item has no matching command output or file evidence in the summary or the evidence above, you MUST fail and name which command's output is missing.\n- feedback must not be empty: on fail, give concrete items the executor can act on directly.\n\nReply with ONLY one JSON object — no other text, no code fences, do not echo the shape example below. Write and dispatch tools are blocked by the server during this round — do not try them. Fields: verdict must be pass (goal fully satisfied, say what in one sentence) or fail (not satisfied, give concrete items the executor must fix); feedback is one short sentence. Shape example (do not copy the placeholders in angle brackets):\n{"verdict":"<pass|fail>","feedback":"<one sentence>"}\n[goal-review]`, "goal.role.review");
|
|
2046
2109
|
}
|
|
2047
2110
|
verdictRetryPrompt() {
|
|
2048
2111
|
return pick(this.lang(), `你上一条回复没有给出约定的 JSON。现在只回一个 JSON 对象,不要有任何其他文本或代码围栏:\n{"verdict":"pass|fail","feedback":"…"}\n[goal-review]`, `Your last reply did not contain the required JSON. Reply with ONLY one JSON object now — no other text, no code fences:\n{"verdict":"pass|fail","feedback":"..."}\n[goal-review]`, "goal.role.review.retry");
|
|
@@ -10,8 +10,8 @@
|
|
|
10
10
|
* 4. 寄存器支持(CUT / PUT @reg):支持在跨文件或同文件内部移动代码段。
|
|
11
11
|
*/
|
|
12
12
|
import { createHash } from "node:crypto";
|
|
13
|
-
import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
|
|
14
|
-
import { dirname, isAbsolute, relative, resolve, sep } from "node:path";
|
|
13
|
+
import { existsSync, mkdirSync, readFileSync, readdirSync, unlinkSync, writeFileSync } from "node:fs";
|
|
14
|
+
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
15
15
|
export const HL_HASH_LENGTH = 4;
|
|
16
16
|
/** 归一化文本换行符与尾随空白(确保哈希跨平台一致) */
|
|
17
17
|
export function normalizeLineEndings(text) {
|
|
@@ -376,15 +376,121 @@ export function tryRecoverEdits(baseText, currentText, hunks, filePath) {
|
|
|
376
376
|
});
|
|
377
377
|
}
|
|
378
378
|
else {
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
379
|
+
// 平移后上下文仍不匹配:±6 行窗口内做 trim 归一化重锚定
|
|
380
|
+
const baseCtx = baseLines
|
|
381
|
+
.slice(Math.max(0, start - 2), Math.min(baseLines.length, end + 1))
|
|
382
|
+
.join("\n")
|
|
383
|
+
.trim();
|
|
384
|
+
let matched = null;
|
|
385
|
+
if (baseCtx) {
|
|
386
|
+
for (let w = 1; w <= 6 && matched === null; w++) {
|
|
387
|
+
for (const off of [w, -w]) {
|
|
388
|
+
const s2 = Math.max(1, start + delta + off);
|
|
389
|
+
const e2 = Math.max(1, end + delta + off);
|
|
390
|
+
const curCtx = curLines
|
|
391
|
+
.slice(Math.max(0, s2 - 2), Math.min(curLines.length, e2 + 1))
|
|
392
|
+
.join("\n")
|
|
393
|
+
.trim();
|
|
394
|
+
if (curCtx && curCtx === baseCtx) {
|
|
395
|
+
matched = off;
|
|
396
|
+
break;
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
if (matched !== null) {
|
|
402
|
+
remapped.push({
|
|
403
|
+
...hunk,
|
|
404
|
+
lineStart: Math.max(1, start + delta + matched),
|
|
405
|
+
lineEnd: hunk.lineEnd !== undefined ? Math.max(1, end + delta + matched) : undefined,
|
|
406
|
+
});
|
|
407
|
+
}
|
|
408
|
+
else {
|
|
409
|
+
return {
|
|
410
|
+
success: false,
|
|
411
|
+
reason: `目标文件在第 ${firstDiff} 行附近发生外部修改,补丁锚点(第 ${start} 行)产生冲突`,
|
|
412
|
+
};
|
|
413
|
+
}
|
|
383
414
|
}
|
|
384
415
|
}
|
|
385
416
|
}
|
|
386
417
|
return { success: true, remappedHunks: remapped };
|
|
387
418
|
}
|
|
419
|
+
/**
|
|
420
|
+
* 错误消息附带当前内容摘录(行号: 内容,锚点附近 ±2 行),
|
|
421
|
+
* 让模型基于现内容一次重试到位,而不是被迫整文件重读。
|
|
422
|
+
*/
|
|
423
|
+
function patchFileExcerpt(lines, aroundLine, filePath, hash) {
|
|
424
|
+
let n = lines.length;
|
|
425
|
+
if (n > 0 && lines[n - 1] === "")
|
|
426
|
+
n--; // 尾随换行 split 出的幻影空行不计入行数(与引擎 lines 口径一致)
|
|
427
|
+
const head = `当前共 ${n} 行,最新锚点:[${filePath}#${hash}]`;
|
|
428
|
+
if (n === 0)
|
|
429
|
+
return `${head}(空文件)`;
|
|
430
|
+
const center = Math.max(1, Math.min(n, aroundLine ?? n));
|
|
431
|
+
const lo = Math.max(1, center - 2);
|
|
432
|
+
const hi = Math.min(n, center + 2);
|
|
433
|
+
const rows = [];
|
|
434
|
+
for (let i = lo; i <= hi; i++)
|
|
435
|
+
rows.push(`${i}: ${String(lines[i - 1]).slice(0, 160)}`);
|
|
436
|
+
return `${head};第 ${lo}-${hi} 行现内容:\n${rows.join("\n")}`;
|
|
437
|
+
}
|
|
438
|
+
/** 同名文件解析时跳过的高风险/重目录 */
|
|
439
|
+
const SAME_BASENAME_SKIP_DIRS = new Set([
|
|
440
|
+
"node_modules",
|
|
441
|
+
".git",
|
|
442
|
+
"__pycache__",
|
|
443
|
+
".venv",
|
|
444
|
+
"venv",
|
|
445
|
+
"dist",
|
|
446
|
+
"build",
|
|
447
|
+
".pytest_cache",
|
|
448
|
+
".mypy_cache",
|
|
449
|
+
"target",
|
|
450
|
+
".next",
|
|
451
|
+
]);
|
|
452
|
+
/**
|
|
453
|
+
* 带锚头但文件读不到时:工作区内找同名唯一文件(典型场景:模型写错目录层级)。
|
|
454
|
+
* 只接受唯一命中;歧义/无命中交回原错误路径并附候选清单。
|
|
455
|
+
*/
|
|
456
|
+
function findUniqueSameBasename(cwd, targetPath) {
|
|
457
|
+
const base = basename(targetPath);
|
|
458
|
+
if (!base || base.startsWith("."))
|
|
459
|
+
return { status: "none", candidates: [] };
|
|
460
|
+
const same = [];
|
|
461
|
+
const ci = [];
|
|
462
|
+
const walk = (dir, depth) => {
|
|
463
|
+
if (depth > 6 || same.length + ci.length > 16)
|
|
464
|
+
return;
|
|
465
|
+
let entries;
|
|
466
|
+
try {
|
|
467
|
+
entries = readdirSync(dir, { withFileTypes: true });
|
|
468
|
+
}
|
|
469
|
+
catch {
|
|
470
|
+
return;
|
|
471
|
+
}
|
|
472
|
+
for (const e of entries) {
|
|
473
|
+
if (e.name.startsWith("."))
|
|
474
|
+
continue;
|
|
475
|
+
const full = join(dir, e.name);
|
|
476
|
+
if (e.isDirectory()) {
|
|
477
|
+
if (!SAME_BASENAME_SKIP_DIRS.has(e.name))
|
|
478
|
+
walk(full, depth + 1);
|
|
479
|
+
continue;
|
|
480
|
+
}
|
|
481
|
+
if (e.name === base)
|
|
482
|
+
same.push(full);
|
|
483
|
+
else if (e.name.toLowerCase() === base.toLowerCase())
|
|
484
|
+
ci.push(full);
|
|
485
|
+
}
|
|
486
|
+
};
|
|
487
|
+
walk(cwd, 0);
|
|
488
|
+
if (same.length === 1)
|
|
489
|
+
return { status: "resolved", path: relative(cwd, same[0]) || same[0], candidates: same };
|
|
490
|
+
if (same.length === 0 && ci.length === 1)
|
|
491
|
+
return { status: "resolved", path: relative(cwd, ci[0]) || ci[0], candidates: ci };
|
|
492
|
+
return { status: same.length + ci.length > 1 ? "ambiguous" : "none", candidates: [...same, ...ci].slice(0, 8) };
|
|
493
|
+
}
|
|
388
494
|
/**
|
|
389
495
|
* 应用 Hashline 补丁
|
|
390
496
|
* 支持传入虚拟或物理文件读写器(便于单元测试或沙箱执行)
|
|
@@ -420,8 +526,12 @@ export function applyHashlinePatch(patchText, options = {}) {
|
|
|
420
526
|
return { ok: false, summary: "未能从输入中解析出有效的 [path#TAG] 补丁段", results: [] };
|
|
421
527
|
}
|
|
422
528
|
const clipboard = new Map(); // 命名剪切板寄存器
|
|
423
|
-
const plannedWrites = new Map(); //
|
|
529
|
+
const plannedWrites = new Map(); // foldKey(absPath) -> 新内容
|
|
424
530
|
const plannedDeletes = new Set();
|
|
531
|
+
// Windows 文件系统大小写不敏感:键做大小写折叠,避免 [a]/[A] 变体绕过路径归一化造成双写覆盖;
|
|
532
|
+
// plannedPaths 记录首次见到的原始路径(保持相对/绝对形态)供落盘与自定义读写器使用。
|
|
533
|
+
const foldKey = (abs) => (process.platform === "win32" ? abs.toLowerCase() : abs);
|
|
534
|
+
const plannedPaths = new Map();
|
|
425
535
|
const results = [];
|
|
426
536
|
// ===== 阶段 1: 预检所有文件并计算目标内容 =====
|
|
427
537
|
for (const sec of sections) {
|
|
@@ -439,15 +549,45 @@ export function applyHashlinePatch(patchText, options = {}) {
|
|
|
439
549
|
error: `Path traversal denied: ${sec.filePath}`,
|
|
440
550
|
};
|
|
441
551
|
}
|
|
442
|
-
// 同一次 patch
|
|
443
|
-
|
|
552
|
+
// 同一次 patch 内对同文件的后续段落,优先使用前面段落生成的新内容。
|
|
553
|
+
// plannedWrites/plannedDeletes 一律按折叠绝对路径做键:[a] 与 [./a]、大小写变体视为同一文件。
|
|
554
|
+
let currentText = plannedWrites.get(foldKey(resolve(cwd, sec.filePath))) ?? read(sec.filePath);
|
|
555
|
+
let fuzzyNote = "";
|
|
556
|
+
if (currentText === null && sec.expectedHash) {
|
|
557
|
+
// 带 #TAG 却读不到:先尝试工作区内同名唯一文件解析(典型:模型写错目录层级)
|
|
558
|
+
const cand = findUniqueSameBasename(cwd, sec.filePath);
|
|
559
|
+
if (cand.status === "resolved" && cand.path) {
|
|
560
|
+
fuzzyNote = `(路径 ${sec.filePath} 不存在,已解析为同名文件 ${cand.path})`;
|
|
561
|
+
sec.filePath = cand.path;
|
|
562
|
+
currentText = plannedWrites.get(foldKey(resolve(cwd, sec.filePath))) ?? read(cand.path);
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
const isNewFile = currentText === null;
|
|
444
566
|
if (currentText === null) {
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
567
|
+
// [path] 段头(无 #TAG)+ 内容 hunk = 创建新文件
|
|
568
|
+
if (sec.hunks.some((h) => h.kind === "remove_file" || h.kind === "move_file")) {
|
|
569
|
+
return {
|
|
570
|
+
ok: false,
|
|
571
|
+
summary: `文件不存在,无法 REM/MV:${sec.filePath}(新建文件请用 [path] 段头 + PUT <1: 提供内容)`,
|
|
572
|
+
results: [],
|
|
573
|
+
error: `File not found: ${sec.filePath}`,
|
|
574
|
+
};
|
|
575
|
+
}
|
|
576
|
+
if (sec.expectedHash) {
|
|
577
|
+
// 附工作区相近文件候选(相对路径),有候选时不建议新建遮蔽
|
|
578
|
+
const cand = findUniqueSameBasename(cwd, sec.filePath);
|
|
579
|
+
const candRel = cand.candidates.map((c) => relative(cwd, c) || c);
|
|
580
|
+
const advice = candRel.length
|
|
581
|
+
? `工作区内相近文件:${candRel.join("、")}。请核对目录层级后用上述路径重试,勿新建同名文件遮蔽。`
|
|
582
|
+
: `新建文件时段头不能带 #TAG(无法对不存在的文件校验哈希),请写 [${sec.filePath}] 并用 PUT <1: 提供内容。`;
|
|
583
|
+
return {
|
|
584
|
+
ok: false,
|
|
585
|
+
summary: `文件不存在:${sec.filePath}。${advice}`,
|
|
586
|
+
results: [],
|
|
587
|
+
error: `Tagged header on nonexistent file: ${sec.filePath}`,
|
|
588
|
+
};
|
|
589
|
+
}
|
|
590
|
+
currentText = ""; // 新建:从空文件起步
|
|
451
591
|
}
|
|
452
592
|
const isCrlf = currentText.includes("\r\n");
|
|
453
593
|
const eol = isCrlf ? "\r\n" : "\n";
|
|
@@ -465,18 +605,24 @@ export function applyHashlinePatch(patchText, options = {}) {
|
|
|
465
605
|
isRecovered = true;
|
|
466
606
|
}
|
|
467
607
|
else {
|
|
608
|
+
// 附现内容摘录,模型可基于现内容一次重锚定
|
|
609
|
+
const excerptLines = normalizeLineEndings(currentText).split("\n");
|
|
610
|
+
const firstHunk = sec.hunks.find((h) => h.kind !== "remove_file" && h.kind !== "move_file");
|
|
468
611
|
return {
|
|
469
612
|
ok: false,
|
|
470
|
-
summary: `文件内容已发生变动,且三方合流失败:${sec.filePath}(预期哈希 #${sec.expectedHash},实际哈希 #${liveHash};${recovery.reason ?? "冲突"})\n
|
|
613
|
+
summary: `文件内容已发生变动,且三方合流失败:${sec.filePath}(预期哈希 #${sec.expectedHash},实际哈希 #${liveHash};${recovery.reason ?? "冲突"})\n${patchFileExcerpt(excerptLines, firstHunk?.lineStart, sec.filePath, liveHash)}\n请基于上述现内容修正行号后重提交,或重新使用 read 工具查看该文件。`,
|
|
471
614
|
results: [],
|
|
472
615
|
error: `Hash mismatch and recovery failed on ${sec.filePath}`,
|
|
473
616
|
};
|
|
474
617
|
}
|
|
475
618
|
}
|
|
476
619
|
else {
|
|
620
|
+
// 附现内容摘录,模型可基于现内容一次重锚定
|
|
621
|
+
const excerptLines = normalizeLineEndings(currentText).split("\n");
|
|
622
|
+
const firstHunk = sec.hunks.find((h) => h.kind !== "remove_file" && h.kind !== "move_file");
|
|
477
623
|
return {
|
|
478
624
|
ok: false,
|
|
479
|
-
summary: `文件内容与锚点不一致:${sec.filePath}(预期哈希 #${sec.expectedHash},实际哈希 #${liveHash}
|
|
625
|
+
summary: `文件内容与锚点不一致:${sec.filePath}(预期哈希 #${sec.expectedHash},实际哈希 #${liveHash})${fuzzyNote}\n${patchFileExcerpt(excerptLines, firstHunk?.lineStart, sec.filePath, liveHash)}\n请基于上述现内容修正行号后重提交,或重新使用 read 工具读取该文件。`,
|
|
480
626
|
results: [],
|
|
481
627
|
error: `Hash mismatch on ${sec.filePath} (#${sec.expectedHash} vs #${liveHash})`,
|
|
482
628
|
};
|
|
@@ -487,6 +633,9 @@ export function applyHashlinePatch(patchText, options = {}) {
|
|
|
487
633
|
if (hasTrailingNewline && lines.length > 0 && lines[lines.length - 1] === "") {
|
|
488
634
|
lines.pop();
|
|
489
635
|
}
|
|
636
|
+
if (isNewFile) {
|
|
637
|
+
lines = []; // 新文件按 0 行处理,PUT <1: / PUT >$: 直接写入内容
|
|
638
|
+
}
|
|
490
639
|
let isDeleted = false;
|
|
491
640
|
let moveDest = undefined;
|
|
492
641
|
// 倒序/顺序处理 hunks。为了保证行号不受前面 hunk 影响,从后往前执行行号替换;
|
|
@@ -536,10 +685,12 @@ export function applyHashlinePatch(patchText, options = {}) {
|
|
|
536
685
|
}
|
|
537
686
|
}
|
|
538
687
|
if (isDeleted) {
|
|
539
|
-
plannedDeletes.add(
|
|
688
|
+
plannedDeletes.add(foldKey(absFilePath));
|
|
689
|
+
plannedPaths.set(foldKey(absFilePath), sec.filePath);
|
|
540
690
|
results.push({
|
|
541
691
|
filePath: sec.filePath,
|
|
542
692
|
op: "deleted",
|
|
693
|
+
note: fuzzyNote || undefined,
|
|
543
694
|
oldHash: liveHash,
|
|
544
695
|
linesChanged: lines.length,
|
|
545
696
|
});
|
|
@@ -551,9 +702,10 @@ export function applyHashlinePatch(patchText, options = {}) {
|
|
|
551
702
|
continue;
|
|
552
703
|
if (h.lineStart !== -1 && typeof h.lineStart === "number") {
|
|
553
704
|
if (h.lineStart < 1 || h.lineStart > Math.max(1, lines.length)) {
|
|
705
|
+
// 附文件尾部摘录,模型可自行改用 PUT >$ 或修正行号
|
|
554
706
|
return {
|
|
555
707
|
ok: false,
|
|
556
|
-
summary: `行号越界:${sec.filePath} 第 ${h.lineStart} 行(文件总共只有 ${lines.length}
|
|
708
|
+
summary: `行号越界:${sec.filePath} 第 ${h.lineStart} 行(文件总共只有 ${lines.length} 行)。${patchFileExcerpt(lines, lines.length, sec.filePath, liveHash)}`,
|
|
557
709
|
results: [],
|
|
558
710
|
error: `Line out of bounds: line ${h.lineStart} in ${sec.filePath} (${lines.length} lines total)`,
|
|
559
711
|
};
|
|
@@ -561,7 +713,7 @@ export function applyHashlinePatch(patchText, options = {}) {
|
|
|
561
713
|
if (h.lineEnd !== undefined && h.lineEnd > Math.max(1, lines.length)) {
|
|
562
714
|
return {
|
|
563
715
|
ok: false,
|
|
564
|
-
summary: `行号越界:${sec.filePath} 结束行 ${h.lineEnd} 超过文件总行数(总共 ${lines.length}
|
|
716
|
+
summary: `行号越界:${sec.filePath} 结束行 ${h.lineEnd} 超过文件总行数(总共 ${lines.length} 行)。${patchFileExcerpt(lines, h.lineStart, sec.filePath, liveHash)}`,
|
|
565
717
|
results: [],
|
|
566
718
|
error: `Line out of bounds: end line ${h.lineEnd} in ${sec.filePath} (${lines.length} lines total)`,
|
|
567
719
|
};
|
|
@@ -650,13 +802,21 @@ export function applyHashlinePatch(patchText, options = {}) {
|
|
|
650
802
|
linesChangedCount += Math.max(count, contentToInsert.length);
|
|
651
803
|
}
|
|
652
804
|
}
|
|
653
|
-
const newContent =
|
|
805
|
+
const newContent = isNewFile
|
|
806
|
+
? lines.length > 0
|
|
807
|
+
? lines.join(eol) + eol
|
|
808
|
+
: ""
|
|
809
|
+
: lines.join(eol) + (hasTrailingNewline ? eol : "");
|
|
654
810
|
if (moveDest) {
|
|
655
|
-
|
|
656
|
-
|
|
811
|
+
const moveKey = foldKey(resolve(cwd, moveDest));
|
|
812
|
+
plannedDeletes.add(foldKey(absFilePath));
|
|
813
|
+
plannedPaths.set(foldKey(absFilePath), sec.filePath);
|
|
814
|
+
plannedWrites.set(moveKey, newContent);
|
|
815
|
+
plannedPaths.set(moveKey, moveDest);
|
|
657
816
|
results.push({
|
|
658
817
|
filePath: sec.filePath,
|
|
659
818
|
op: "moved",
|
|
819
|
+
note: fuzzyNote || undefined,
|
|
660
820
|
oldHash: liveHash,
|
|
661
821
|
newHash: computeFileHash(newContent),
|
|
662
822
|
linesChanged: linesChangedCount,
|
|
@@ -665,10 +825,14 @@ export function applyHashlinePatch(patchText, options = {}) {
|
|
|
665
825
|
});
|
|
666
826
|
}
|
|
667
827
|
else {
|
|
668
|
-
|
|
828
|
+
const updateKey = foldKey(absFilePath);
|
|
829
|
+
plannedWrites.set(updateKey, newContent);
|
|
830
|
+
plannedPaths.set(updateKey, sec.filePath);
|
|
669
831
|
results.push({
|
|
670
832
|
filePath: sec.filePath,
|
|
671
833
|
op: "updated",
|
|
834
|
+
created: isNewFile,
|
|
835
|
+
note: fuzzyNote || undefined,
|
|
672
836
|
oldHash: liveHash,
|
|
673
837
|
newHash: computeFileHash(newContent),
|
|
674
838
|
linesChanged: linesChangedCount,
|
|
@@ -678,22 +842,25 @@ export function applyHashlinePatch(patchText, options = {}) {
|
|
|
678
842
|
}
|
|
679
843
|
// ===== 阶段 2: 全部校验通过,统一落盘 =====
|
|
680
844
|
// 先执行所有写入,确保新文件与移动目标成功落盘,避免先删后写异常时永久丢失源文件
|
|
681
|
-
for (const [
|
|
845
|
+
for (const [key, content] of plannedWrites.entries()) {
|
|
846
|
+
const p = plannedPaths.get(key) ?? key;
|
|
682
847
|
write(p, content);
|
|
683
848
|
// 记住新快照(统一采用绝对路径隔离多工作区)
|
|
684
849
|
store.record(resolve(cwd, p), content);
|
|
685
850
|
}
|
|
686
|
-
for (const
|
|
687
|
-
if (!plannedWrites.has(
|
|
688
|
-
remove(
|
|
851
|
+
for (const key of plannedDeletes) {
|
|
852
|
+
if (!plannedWrites.has(key)) {
|
|
853
|
+
remove(plannedPaths.get(key) ?? key);
|
|
689
854
|
}
|
|
690
855
|
}
|
|
691
856
|
const summaryParts = results.map((r) => {
|
|
692
857
|
if (r.op === "deleted")
|
|
693
|
-
return `删除 ${r.filePath}`;
|
|
858
|
+
return `删除 ${r.filePath}${r.note ?? ""}`;
|
|
859
|
+
if (r.created)
|
|
860
|
+
return `新建 ${r.filePath}(${r.linesChanged} 行,新哈希 #${r.newHash})${r.note ?? ""}`;
|
|
694
861
|
if (r.op === "moved")
|
|
695
|
-
return `移动 ${r.filePath} -> ${r.newPath}(新哈希 #${r.newHash}
|
|
696
|
-
return `修改 ${r.filePath}(${r.linesChanged} 行变动,新哈希 #${r.newHash}${r.recovered ? ",三方自愈" : ""}
|
|
862
|
+
return `移动 ${r.filePath} -> ${r.newPath}(新哈希 #${r.newHash})${r.note ?? ""}`;
|
|
863
|
+
return `修改 ${r.filePath}(${r.linesChanged} 行变动,新哈希 #${r.newHash}${r.recovered ? ",三方自愈" : ""})${r.note ?? ""}`;
|
|
697
864
|
});
|
|
698
865
|
return {
|
|
699
866
|
ok: true,
|