minimal-agent 0.18.17 → 0.18.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/package.json +1 -1
- package/src/advisor/README.md +12 -0
- package/src/advisor/advisorNudge.js +4 -2
- package/src/advisor/advisorNudge.ts +6 -2
- package/src/cli/wizards/advisorWizard.js +2 -2
- package/src/cli/wizards/advisorWizard.tsx +2 -2
- package/src/cli/wizards/providerPresets.js +1 -1
- package/src/cli/wizards/providerPresets.ts +1 -1
- package/src/config/configFile.js +10 -5
- package/src/config/configFile.ts +10 -5
- package/src/config/configService.js +1 -1
- package/src/config/configService.ts +1 -1
- package/src/config.js +2 -2
- package/src/config.ts +2 -2
- package/src/context/budgetPlan.js +3 -1
- package/src/context/budgetPlan.ts +3 -1
- package/src/context/microCompactLite.js +3 -2
- package/src/context/microCompactLite.ts +3 -2
- package/src/context/toolResultArchive.js +2 -1
- package/src/context/toolResultArchive.ts +2 -1
- package/src/llm/client.js +20 -1
- package/src/llm/client.ts +20 -1
- package/src/llm/messageProvenance.js +72 -1
- package/src/llm/messageProvenance.ts +72 -1
- package/src/loop/toolExecutor.js +7 -0
- package/src/loop/toolExecutor.ts +7 -0
- package/src/memory/episodicMemory.js +3 -3
- package/src/memory/episodicMemory.ts +12 -8
- package/src/memory/sessionPipeline.js +32 -2
- package/src/memory/sessionPipeline.ts +38 -2
- package/src/memory/taskEvidence.js +2 -1
- package/src/memory/taskEvidence.ts +2 -1
- package/src/prompts/delegation.js +3 -4
- package/src/prompts/delegation.ts +3 -4
- package/src/prompts/policyRegistry.js +24 -22
- package/src/prompts/policyRegistry.ts +23 -23
- package/src/prompts/promptAssembly.js +1 -1
- package/src/prompts/promptAssembly.ts +1 -1
- package/src/runtime/deliveryGate.js +20 -3
- package/src/runtime/deliveryGate.ts +17 -3
- package/src/session/sessionState.ts +2 -0
- package/src/tools/advisor/advisor.js +245 -40
- package/src/tools/advisor/advisor.ts +272 -34
- package/src/tools/advisor/advisorDescription.js +5 -0
- package/src/tools/advisor/advisorDescription.ts +5 -0
- package/src/tools/advisor/advisorVerify.js +84 -0
- package/src/tools/advisor/advisorVerify.ts +96 -0
- package/src/tools/agent/README.md +3 -0
- package/src/tools/agent/agent.js +9 -2
- package/src/tools/agent/agent.ts +9 -2
- package/src/tools/agent/agentHandoff.js +59 -6
- package/src/tools/agent/agentHandoff.ts +55 -6
- package/src/tools/agent/agentTypes.js +2 -2
- package/src/tools/agent/agentTypes.ts +2 -2
- package/src/tools/agent/baselineAttach.js +72 -0
- package/src/tools/agent/baselineAttach.ts +80 -0
- package/src/tools/agent/executedCalls.js +12 -0
- package/src/tools/agent/executedCalls.ts +28 -0
- package/src/tools/bash/bash.js +2 -1
- package/src/tools/bash/bash.ts +2 -1
- package/src/tools/read/read.js +2 -1
- package/src/tools/read/read.ts +2 -1
- package/src/tools/shared/toolOutputStore.js +5 -4
- package/src/tools/shared/toolOutputStore.ts +5 -4
- package/src/tools/toolPromptGuides.js +11 -10
- package/src/tools/toolPromptGuides.ts +11 -11
- package/src/types.ts +3 -2
- package/src/ui/InputBox.js +53 -2
- package/src/ui/InputBox.tsx +50 -2
- package/src/utils/safeText.js +30 -0
- package/src/utils/safeText.ts +34 -0
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 顾问的只读核实能力:Read / Grep / Glob,仅限执行助手的工作区。
|
|
3
|
+
*
|
|
4
|
+
* 顾问以前只能「读材料、给意见」:它怀疑「某处没覆盖」时,只能在意见里写「缺失材料:
|
|
5
|
+
* 请去读 X」,再由执行助手回头补查——一来一回既慢,又把核实的负担推回了被评审的一方。
|
|
6
|
+
* 现在它可以自己去读,核实到的写成【有证据】。边界只有三条,都是确定性的:
|
|
7
|
+
*
|
|
8
|
+
* - 只读:只暴露 Read / Grep / Glob,其它工具名一律拒绝(不能写、不能跑命令、不能递归)。
|
|
9
|
+
* - 仅限工作区:路径参数解析后必须落在 cwd 内;Glob/Grep 的 glob 不许绝对路径或 `..`。
|
|
10
|
+
* - 读到的内容和对话一样要抹密钥后才回到顾问(顾问常是另一家服务商)。
|
|
11
|
+
*
|
|
12
|
+
* 这里只放纯判断与取工具对象;循环和流式在 advisor.ts,保持那里是顾问的唯一入口。
|
|
13
|
+
*/
|
|
14
|
+
import { realpath } from 'node:fs/promises';
|
|
15
|
+
import { isAbsolute, resolve } from 'node:path';
|
|
16
|
+
|
|
17
|
+
import { pathContains } from '../../utils/pathContains.js';
|
|
18
|
+
|
|
19
|
+
export const ADVISOR_VERIFY_TOOL_NAMES = ['Read', 'Grep', 'Glob'] as const;
|
|
20
|
+
/** 顾问最多核实多少轮;到顶后最后一次请求不再带工具,必须给出意见。 */
|
|
21
|
+
export const ADVISOR_MAX_VERIFY_ROUNDS = 6;
|
|
22
|
+
/** 单次核实结果回给顾问的字符上限(防止一次读入整个大文件撑满它的窗口)。 */
|
|
23
|
+
export const ADVISOR_VERIFY_RESULT_CHARS = 30_000;
|
|
24
|
+
|
|
25
|
+
const PATH_KEYS = ['file_path', 'path', 'notebook_path'] as const;
|
|
26
|
+
/** 各工具里「是 glob」的参数名:Grep 的 pattern 是正则,不按 glob 规则判。 */
|
|
27
|
+
const GLOB_KEYS_BY_TOOL: Record<string, readonly string[]> = {
|
|
28
|
+
Glob: ['pattern'],
|
|
29
|
+
Grep: ['glob'],
|
|
30
|
+
Read: [],
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
export type AdvisorToolCheck = { ok: true } | { ok: false; error: string };
|
|
34
|
+
|
|
35
|
+
function isVerifyTool(name: string): boolean {
|
|
36
|
+
return (ADVISOR_VERIFY_TOOL_NAMES as readonly string[]).includes(name);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** 顾问发出的核实调用是否允许执行。拒绝原因会原样回给顾问,让它换一种方式。 */
|
|
40
|
+
export async function checkAdvisorToolCall(
|
|
41
|
+
name: string,
|
|
42
|
+
rawArguments: string,
|
|
43
|
+
cwd: string,
|
|
44
|
+
): Promise<AdvisorToolCheck> {
|
|
45
|
+
if (!isVerifyTool(name))
|
|
46
|
+
return { ok: false, error: `顾问只读:只能使用 ${ADVISOR_VERIFY_TOOL_NAMES.join('、')},不能使用 ${name}。` };
|
|
47
|
+
let args: Record<string, unknown>;
|
|
48
|
+
try {
|
|
49
|
+
const parsed = JSON.parse(rawArguments || '{}');
|
|
50
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error('not an object');
|
|
51
|
+
args = parsed as Record<string, unknown>;
|
|
52
|
+
} catch {
|
|
53
|
+
return { ok: false, error: '工具参数不是合法的 JSON 对象。' };
|
|
54
|
+
}
|
|
55
|
+
for (const key of PATH_KEYS) {
|
|
56
|
+
const value = args[key];
|
|
57
|
+
if (typeof value !== 'string') continue;
|
|
58
|
+
const lexical = resolve(cwd, value);
|
|
59
|
+
if (!pathContains(cwd, lexical))
|
|
60
|
+
return { ok: false, error: `路径超出工作区,已拒绝:${value}。顾问只能读取工作区内的文件。` };
|
|
61
|
+
// 工作区内的符号链接可以指向工作区外:存在的路径还要按真实路径再判一次。
|
|
62
|
+
const real = await realpath(lexical).catch(() => undefined);
|
|
63
|
+
const root = await realpath(cwd).catch(() => cwd);
|
|
64
|
+
if (real && !pathContains(root, real))
|
|
65
|
+
return { ok: false, error: `路径经符号链接指向工作区外,已拒绝:${value}。` };
|
|
66
|
+
}
|
|
67
|
+
for (const key of GLOB_KEYS_BY_TOOL[name] ?? []) {
|
|
68
|
+
const value = args[key];
|
|
69
|
+
if (typeof value !== 'string') continue;
|
|
70
|
+
const unsafe =
|
|
71
|
+
isAbsolute(value) ||
|
|
72
|
+
/^[A-Za-z]:/.test(value) ||
|
|
73
|
+
value.split(/[\\/]+/).includes('..');
|
|
74
|
+
if (unsafe)
|
|
75
|
+
return { ok: false, error: `匹配模式超出工作区(不许绝对路径或 ..),已拒绝:${value}。` };
|
|
76
|
+
}
|
|
77
|
+
return { ok: true };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** 回给顾问的核实结果:截断到上限并如实标注。 */
|
|
81
|
+
export function clipVerifyResult(text: string): string {
|
|
82
|
+
if (text.length <= ADVISOR_VERIFY_RESULT_CHARS) return text;
|
|
83
|
+
return `${text.slice(0, ADVISOR_VERIFY_RESULT_CHARS)}\n…(结果过长,已截断 ${text.length - ADVISOR_VERIFY_RESULT_CHARS} 字符;请用更窄的范围再查)`;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** 顾问可见的工具定义:从全局注册表里按名字取,保持和主 Agent 同一份 schema。 */
|
|
87
|
+
export async function loadAdvisorVerifyTools<T extends { name: string }>(
|
|
88
|
+
/** 本回合执行方真正拿得到的工具;给了就取交集,顾问不能比执行方拿到更多。 */
|
|
89
|
+
available?: readonly { name: string }[],
|
|
90
|
+
): Promise<T[]> {
|
|
91
|
+
const { ALL_TOOLS } = await import('../index.js');
|
|
92
|
+
const allowed = available ? new Set(available.map((tool) => tool.name)) : undefined;
|
|
93
|
+
return (ALL_TOOLS as unknown as T[]).filter(
|
|
94
|
+
(tool) => isVerifyTool(tool.name) && (!allowed || allowed.has(tool.name)),
|
|
95
|
+
);
|
|
96
|
+
}
|
|
@@ -53,6 +53,9 @@
|
|
|
53
53
|
|
|
54
54
|
## 结果与证据
|
|
55
55
|
|
|
56
|
+
- **执行台账**(`executedCalls.ts`):执行器在工具真正执行后记录 tool_call_id→{工具, 时间},挂在各自运行的 `sessionState` 上(子任务有独立 sessionState,调用不会进主会话台账)。`AgentReport`/`AgentResolve` 校验证据 ID 时取「当前历史 ∪ 台账」,所以压缩掉旧工具消息后,真实做过的检查仍可引用。台账只证明「这个调用发生过」,不证明命令成功或检查充分;写任务验收仍要求检查类工具且晚于任务创建。压缩后正文内容本身的回看靠阅读证据索引与 `TaskOutput` 分页。
|
|
57
|
+
- **自动基线**(`baselineAttach.ts`):只读任务书出现「新引入/基线/对比 HEAD」等措辞又没给 `context.baseline` 时,派发时由宿主附带 `git diff HEAD`(含状态与未跟踪文件,超长按文件截断并声明);取不到则写入「缺少基线、无法判断」的声明,仍照常派发。关键词只是启发式,所以绝不因它拒绝派发。
|
|
58
|
+
|
|
56
59
|
模型失败、轮数耗尽不因为有文本就成功。错误包含最后进展、已知改动及证据,完整私有历史保留在 Session runtime,供 Followup 续接。`coveredFiles` 来自执行时成功的观察工具;搜索范围或部分读取不是全文覆盖保证。需要审查业务结论和产物,不把状态 completed 当验收通过。
|
|
57
60
|
|
|
58
61
|
进程级并发队列按根 Session 轮换,真实写路径重叠时串行,租约释放幂等;不同根之间不共享私有上下文。父 Agent 的前台修改取得工作目录租约,委派和控制调用不持该锁,避免嵌套死锁。
|
package/src/tools/agent/agent.js
CHANGED
|
@@ -45,6 +45,7 @@ import { acquireSubagentLease, normalizeWriteScopes } from './coordinator.js';
|
|
|
45
45
|
import { commitWorktreeChanges, createAgentWorktree, hasWorktreeChanges, removeAgentWorktree, worktreeChangedFiles, worktreeDiffStat, withAgentGitSignal, } from './worktree.js';
|
|
46
46
|
import { appendAgentEvent, attachAgentHistory, loadAgentRecord, saveAgentRecord } from './agentTaskService.js';
|
|
47
47
|
import { agentReportTool } from './agentHandoff.js';
|
|
48
|
+
import { BASELINE_UNAVAILABLE, captureGitBaseline, needsChangeBaseline } from './baselineAttach.js';
|
|
48
49
|
import { disposeDetachedSessionState } from '../../session/sessionState.js';
|
|
49
50
|
let corePromise = null;
|
|
50
51
|
/** 首次调用时才真正加载 loop/tools——此刻模块图早已初始化完毕,环安全。 */
|
|
@@ -112,7 +113,6 @@ const description = AGENT_TOOL_DESCRIPTION;
|
|
|
112
113
|
/** 任务回传契约。能力与权限已经由 assembleBasePrompt profile 精确注入。 */
|
|
113
114
|
const SUBAGENT_COMMON_APPENDIX = `# 你是子 agent(fork 分身)
|
|
114
115
|
你是主 agent 派生出的子 agent,正在执行一个自包含的子任务:
|
|
115
|
-
- 你看不到主对话;首次依据自包含任务书执行,续接时同时使用自己的历史和主 Agent 后续消息。
|
|
116
116
|
- 最终文字报告必须自包含:结论 + 关键证据(文件路径/行号)+ 未尽事项。有结构化交接时,以当前 attempt 的交接状态为准,文字补充证据与说明,两者必须一致;工具拒绝或提交失败不算交接成功。
|
|
117
117
|
不要输出「我完成了」这类无信息量收尾。遇到阻塞,报告已尝试方法、需要的信息及可继续部分;主 Agent 可通过消息或 Followup 补充并续接。
|
|
118
118
|
- 独立且路径已知的读取在同一消息中批量发出;搜索结果尚未知时先定位,不猜测后续参数。
|
|
@@ -129,7 +129,7 @@ const SUBAGENT_COMMON_APPENDIX = `# 你是子 agent(fork 分身)
|
|
|
129
129
|
*/
|
|
130
130
|
const PROMPT_CACHE_TTL_MS = 60_000;
|
|
131
131
|
const promptCache = new Map();
|
|
132
|
-
async function buildSubSystemPrompt(cwd, def, allTools, conversationMode = 'private', output) {
|
|
132
|
+
export async function buildSubSystemPrompt(cwd, def, allTools, conversationMode = 'private', output) {
|
|
133
133
|
// Effective capabilities are part of prompt identity; a child must never
|
|
134
134
|
// reuse a cached parent-capability prompt (notably Desktop WebBrowser).
|
|
135
135
|
const key = `${cwd}::${def.type}::${conversationMode}::${JSON.stringify(output ?? null)}::${allTools.map((tool) => tool.name).join(',')}`;
|
|
@@ -808,6 +808,13 @@ async function runManagedAgentTaskImpl(input, signal, ctx, deps = {}) {
|
|
|
808
808
|
resume_agent_id: undefined,
|
|
809
809
|
};
|
|
810
810
|
}
|
|
811
|
+
// 只读审查需要「改动前后」基线却没给:宿主自动附带 git diff HEAD;取不到就在派发前说清,不让子任务白跑。
|
|
812
|
+
if (!input.resume_agent_id && needsChangeBaseline(coreInput)) {
|
|
813
|
+
const baseline = await captureGitBaseline(ctx.sessionState.activeWorktree?.path ?? ctx.cwd ?? getWorkingDir(), signal);
|
|
814
|
+
// 取不到也照常派发(关键词只是启发式,可能只是「性能基线」之类的无关用法),
|
|
815
|
+
// 但把限制写进基线,子任务据此在报告里如实说明,而不是凭当前代码断言「新引入」。
|
|
816
|
+
coreInput = { ...coreInput, context: { ...coreInput.context, baseline: baseline ?? BASELINE_UNAVAILABLE } };
|
|
817
|
+
}
|
|
811
818
|
for (const dependency of coreInput.depends_on ?? []) {
|
|
812
819
|
if (dependency === id)
|
|
813
820
|
return { ok: false, error: '子任务不能依赖自身' };
|
package/src/tools/agent/agent.ts
CHANGED
|
@@ -65,6 +65,7 @@ import {
|
|
|
65
65
|
} from './worktree.js';
|
|
66
66
|
import { appendAgentEvent, attachAgentHistory, loadAgentRecord, saveAgentRecord, type AgentTaskRecord, type LiveAgentTask } from './agentTaskService.js';
|
|
67
67
|
import { agentReportTool } from './agentHandoff.js';
|
|
68
|
+
import { BASELINE_UNAVAILABLE, captureGitBaseline, needsChangeBaseline } from './baselineAttach.js';
|
|
68
69
|
import { disposeDetachedSessionState } from '../../session/sessionState.js';
|
|
69
70
|
|
|
70
71
|
// ---------------- 0. 环内模块懒加载(见文件头「循环依赖纪律」) ----------------
|
|
@@ -160,7 +161,6 @@ const description = AGENT_TOOL_DESCRIPTION;
|
|
|
160
161
|
/** 任务回传契约。能力与权限已经由 assembleBasePrompt profile 精确注入。 */
|
|
161
162
|
const SUBAGENT_COMMON_APPENDIX = `# 你是子 agent(fork 分身)
|
|
162
163
|
你是主 agent 派生出的子 agent,正在执行一个自包含的子任务:
|
|
163
|
-
- 你看不到主对话;首次依据自包含任务书执行,续接时同时使用自己的历史和主 Agent 后续消息。
|
|
164
164
|
- 最终文字报告必须自包含:结论 + 关键证据(文件路径/行号)+ 未尽事项。有结构化交接时,以当前 attempt 的交接状态为准,文字补充证据与说明,两者必须一致;工具拒绝或提交失败不算交接成功。
|
|
165
165
|
不要输出「我完成了」这类无信息量收尾。遇到阻塞,报告已尝试方法、需要的信息及可继续部分;主 Agent 可通过消息或 Followup 补充并续接。
|
|
166
166
|
- 独立且路径已知的读取在同一消息中批量发出;搜索结果尚未知时先定位,不猜测后续参数。
|
|
@@ -179,7 +179,7 @@ const SUBAGENT_COMMON_APPENDIX = `# 你是子 agent(fork 分身)
|
|
|
179
179
|
const PROMPT_CACHE_TTL_MS = 60_000;
|
|
180
180
|
const promptCache = new Map<string, { value: string; at: number }>();
|
|
181
181
|
|
|
182
|
-
async function buildSubSystemPrompt(
|
|
182
|
+
export async function buildSubSystemPrompt(
|
|
183
183
|
cwd: string,
|
|
184
184
|
def: AgentTypeDef,
|
|
185
185
|
allTools: Tool[],
|
|
@@ -879,6 +879,13 @@ async function runManagedAgentTaskImpl(
|
|
|
879
879
|
resume_agent_id: undefined,
|
|
880
880
|
};
|
|
881
881
|
}
|
|
882
|
+
// 只读审查需要「改动前后」基线却没给:宿主自动附带 git diff HEAD;取不到就在派发前说清,不让子任务白跑。
|
|
883
|
+
if (!input.resume_agent_id && needsChangeBaseline(coreInput)) {
|
|
884
|
+
const baseline = await captureGitBaseline(ctx.sessionState.activeWorktree?.path ?? ctx.cwd ?? getWorkingDir(), signal);
|
|
885
|
+
// 取不到也照常派发(关键词只是启发式,可能只是「性能基线」之类的无关用法),
|
|
886
|
+
// 但把限制写进基线,子任务据此在报告里如实说明,而不是凭当前代码断言「新引入」。
|
|
887
|
+
coreInput = { ...coreInput, context: { ...coreInput.context, baseline: baseline ?? BASELINE_UNAVAILABLE } };
|
|
888
|
+
}
|
|
882
889
|
for (const dependency of coreInput.depends_on ?? []) {
|
|
883
890
|
if (dependency === id) return { ok: false, error: '子任务不能依赖自身' };
|
|
884
891
|
const record = ctx.sessionState.agentTasks.tasks.get(dependency) ?? await loadAgentRecord(ctx, dependency);
|
|
@@ -18,6 +18,57 @@ const reportSchema = z.object({
|
|
|
18
18
|
if (value.kind === 'result' && value.remaining.length)
|
|
19
19
|
context.addIssue({ code: 'custom', path: ['remaining'], message: '还有必需工作未完成时使用 blocked,不把缺口作为成功结果' });
|
|
20
20
|
});
|
|
21
|
+
const WRITE_REVIEW_INSPECTION_TOOLS = new Set(['Read', 'Grep', 'Glob', 'LSP', 'Bash', 'PowerShell']);
|
|
22
|
+
/**
|
|
23
|
+
* 校验写任务验收证据:必须是主历史里本任务创建后、非 deferred 的检查类工具调用的
|
|
24
|
+
* tool_call_id。不通过时错误里说明**哪几个**引用不对、为什么,并列出当前可直接引用的
|
|
25
|
+
* 候选——此前只有一句泛泛的话,主 Agent 把后台进程句柄(proc_…,给 TaskOutput/TaskStop 用)
|
|
26
|
+
* 当调用 ID 填进去后,既不知道错在哪,也没处查可用 ID。
|
|
27
|
+
*/
|
|
28
|
+
export function writeReviewEvidenceError(history, createdAt, refs, executed) {
|
|
29
|
+
const calls = new Map();
|
|
30
|
+
for (const m of history)
|
|
31
|
+
if (m.role === 'assistant')
|
|
32
|
+
for (const c of m.tool_calls ?? [])
|
|
33
|
+
calls.set(c.id, c.function.name);
|
|
34
|
+
const valid = new Map();
|
|
35
|
+
// 台账:压缩掉历史后,真实执行过的检查仍可引用。
|
|
36
|
+
for (const [id, entry] of executed ?? []) {
|
|
37
|
+
if (!calls.has(id))
|
|
38
|
+
calls.set(id, entry.tool);
|
|
39
|
+
if (entry.at >= createdAt && WRITE_REVIEW_INSPECTION_TOOLS.has(entry.tool))
|
|
40
|
+
valid.set(id, entry.tool);
|
|
41
|
+
}
|
|
42
|
+
for (const m of history) {
|
|
43
|
+
if (m.role !== 'tool' || m.timestamp === undefined || m.timestamp < createdAt)
|
|
44
|
+
continue;
|
|
45
|
+
if (m.toolResultDisposition === 'deferred')
|
|
46
|
+
continue;
|
|
47
|
+
const name = calls.get(m.tool_call_id);
|
|
48
|
+
if (name && WRITE_REVIEW_INSPECTION_TOOLS.has(name))
|
|
49
|
+
valid.set(m.tool_call_id, name);
|
|
50
|
+
}
|
|
51
|
+
const bad = refs.filter((ref) => !valid.has(ref));
|
|
52
|
+
if (!bad.length)
|
|
53
|
+
return null;
|
|
54
|
+
const reasons = bad.map((ref) => {
|
|
55
|
+
if (/^proc_/i.test(ref))
|
|
56
|
+
return `${ref}(这是后台进程句柄,供 TaskOutput/TaskStop 使用,不是工具调用 ID)`;
|
|
57
|
+
const name = calls.get(ref);
|
|
58
|
+
if (name && !WRITE_REVIEW_INSPECTION_TOOLS.has(name))
|
|
59
|
+
return `${ref}(${name} 不是检查类工具)`;
|
|
60
|
+
if (name)
|
|
61
|
+
return `${ref}(该调用早于本任务创建,或结果仍是 deferred 占位)`;
|
|
62
|
+
return `${ref}(当前主历史里没有这个调用,可能已被压缩)`;
|
|
63
|
+
});
|
|
64
|
+
const candidates = [...valid].slice(-8).map(([id, name]) => `${id}(${name})`);
|
|
65
|
+
return [
|
|
66
|
+
`writeReview 证据必须是当前主历史中本任务创建后的实际检查调用 ID(Read/Grep/Glob/LSP/Bash/PowerShell 的 tool_call_id),不能引用控制回执。无效:${reasons.join(';')}。`,
|
|
67
|
+
candidates.length
|
|
68
|
+
? `当前可引用的最近检查调用:${candidates.join('、')}。`
|
|
69
|
+
: '当前历史里没有可引用的检查调用;请先由主 Agent 亲自运行测试/读取改动,再登记。',
|
|
70
|
+
].join('');
|
|
71
|
+
}
|
|
21
72
|
/** Private host control channel; not a workspace capability delegated by name. */
|
|
22
73
|
export const agentReportTool = {
|
|
23
74
|
name: 'AgentReport', inputSchema: reportSchema, parameters: toToolParameters(reportSchema),
|
|
@@ -27,7 +78,11 @@ export const agentReportTool = {
|
|
|
27
78
|
callWithContext: async (input, _signal, ctx) => {
|
|
28
79
|
if (!ctx.agentHandoff)
|
|
29
80
|
return { ok: false, error: '当前没有主 Agent 交接通道' };
|
|
30
|
-
|
|
81
|
+
// 历史 ∪ 执行台账:长任务压缩掉旧工具消息后,真实做过的检查仍可引用。
|
|
82
|
+
const known = new Set([
|
|
83
|
+
...(ctx.history?.filter((m) => m.role === 'tool').map((m) => m.tool_call_id) ?? []),
|
|
84
|
+
...(ctx.executedCalls?.keys() ?? []),
|
|
85
|
+
]);
|
|
31
86
|
const refs = [...input.evidenceRefs, ...(input.findings ?? []).flatMap(finding => finding.evidenceRefs)];
|
|
32
87
|
if (refs.some((ref) => !known.has(ref))) {
|
|
33
88
|
// Hand back real handles instead of making the model guess: only IDs the
|
|
@@ -134,11 +189,9 @@ export const agentResolveTool = {
|
|
|
134
189
|
if (record.input.agent_type === 'general' && ['accept', 'complete'].includes(input.action)) {
|
|
135
190
|
if (!input.writeReview)
|
|
136
191
|
return { ok: false, error: '写任务必须提供 writeReview:说明主工作区集成、最终验证和主 Agent 检查证据;子任务 completed 不等于集成完成' };
|
|
137
|
-
const
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
if (input.writeReview.evidenceRefs.some(ref => !known.has(ref)))
|
|
141
|
-
return { ok: false, error: 'writeReview 证据必须来自当前主历史中本任务创建后的实际检查,不能引用控制回执;压缩后不可定位时请重新核验' };
|
|
192
|
+
const evidenceError = writeReviewEvidenceError(ctx.history ?? [], record.createdAt, input.writeReview.evidenceRefs, ctx.executedCalls);
|
|
193
|
+
if (evidenceError)
|
|
194
|
+
return { ok: false, error: evidenceError };
|
|
142
195
|
}
|
|
143
196
|
const previous = record.resolution;
|
|
144
197
|
record.resolution = { action: input.action, summary: input.summary, at: Date.now(), ...(input.coverage ? { coverage: input.coverage } : {}), ...(input.superseded_by ? { supersededBy: input.superseded_by } : {}), ...(input.writeReview ? { writeReview: input.writeReview } : {}) };
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
2
|
import { researchFindingSchema } from './research.js';
|
|
3
|
-
import type { Tool, ToolResult } from '../../types.js';
|
|
3
|
+
import type { Message, Tool, ToolResult } from '../../types.js';
|
|
4
4
|
import { toToolParameters } from '../../utils/zodToJson.js';
|
|
5
5
|
import { getLiveAgentTask, loadAgentRecord, saveAgentRecord, waitAgentCompletion } from './agentTaskService.js';
|
|
6
6
|
|
|
@@ -21,6 +21,53 @@ const reportSchema = z.object({
|
|
|
21
21
|
context.addIssue({ code: 'custom', path: ['remaining'], message: '还有必需工作未完成时使用 blocked,不把缺口作为成功结果' });
|
|
22
22
|
});
|
|
23
23
|
|
|
24
|
+
const WRITE_REVIEW_INSPECTION_TOOLS = new Set(['Read', 'Grep', 'Glob', 'LSP', 'Bash', 'PowerShell']);
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* 校验写任务验收证据:必须是主历史里本任务创建后、非 deferred 的检查类工具调用的
|
|
28
|
+
* tool_call_id。不通过时错误里说明**哪几个**引用不对、为什么,并列出当前可直接引用的
|
|
29
|
+
* 候选——此前只有一句泛泛的话,主 Agent 把后台进程句柄(proc_…,给 TaskOutput/TaskStop 用)
|
|
30
|
+
* 当调用 ID 填进去后,既不知道错在哪,也没处查可用 ID。
|
|
31
|
+
*/
|
|
32
|
+
export function writeReviewEvidenceError(
|
|
33
|
+
history: readonly Message[],
|
|
34
|
+
createdAt: number,
|
|
35
|
+
refs: readonly string[],
|
|
36
|
+
executed?: ReadonlyMap<string, { tool: string; at: number }>,
|
|
37
|
+
): string | null {
|
|
38
|
+
const calls = new Map<string, string>();
|
|
39
|
+
for (const m of history)
|
|
40
|
+
if (m.role === 'assistant') for (const c of m.tool_calls ?? []) calls.set(c.id, c.function.name);
|
|
41
|
+
const valid = new Map<string, string>();
|
|
42
|
+
// 台账:压缩掉历史后,真实执行过的检查仍可引用。
|
|
43
|
+
for (const [id, entry] of executed ?? []) {
|
|
44
|
+
if (!calls.has(id)) calls.set(id, entry.tool);
|
|
45
|
+
if (entry.at >= createdAt && WRITE_REVIEW_INSPECTION_TOOLS.has(entry.tool)) valid.set(id, entry.tool);
|
|
46
|
+
}
|
|
47
|
+
for (const m of history) {
|
|
48
|
+
if (m.role !== 'tool' || m.timestamp === undefined || m.timestamp < createdAt) continue;
|
|
49
|
+
if (m.toolResultDisposition === 'deferred') continue;
|
|
50
|
+
const name = calls.get(m.tool_call_id);
|
|
51
|
+
if (name && WRITE_REVIEW_INSPECTION_TOOLS.has(name)) valid.set(m.tool_call_id, name);
|
|
52
|
+
}
|
|
53
|
+
const bad = refs.filter((ref) => !valid.has(ref));
|
|
54
|
+
if (!bad.length) return null;
|
|
55
|
+
const reasons = bad.map((ref) => {
|
|
56
|
+
if (/^proc_/i.test(ref)) return `${ref}(这是后台进程句柄,供 TaskOutput/TaskStop 使用,不是工具调用 ID)`;
|
|
57
|
+
const name = calls.get(ref);
|
|
58
|
+
if (name && !WRITE_REVIEW_INSPECTION_TOOLS.has(name)) return `${ref}(${name} 不是检查类工具)`;
|
|
59
|
+
if (name) return `${ref}(该调用早于本任务创建,或结果仍是 deferred 占位)`;
|
|
60
|
+
return `${ref}(当前主历史里没有这个调用,可能已被压缩)`;
|
|
61
|
+
});
|
|
62
|
+
const candidates = [...valid].slice(-8).map(([id, name]) => `${id}(${name})`);
|
|
63
|
+
return [
|
|
64
|
+
`writeReview 证据必须是当前主历史中本任务创建后的实际检查调用 ID(Read/Grep/Glob/LSP/Bash/PowerShell 的 tool_call_id),不能引用控制回执。无效:${reasons.join(';')}。`,
|
|
65
|
+
candidates.length
|
|
66
|
+
? `当前可引用的最近检查调用:${candidates.join('、')}。`
|
|
67
|
+
: '当前历史里没有可引用的检查调用;请先由主 Agent 亲自运行测试/读取改动,再登记。',
|
|
68
|
+
].join('');
|
|
69
|
+
}
|
|
70
|
+
|
|
24
71
|
/** Private host control channel; not a workspace capability delegated by name. */
|
|
25
72
|
export const agentReportTool: Tool<z.infer<typeof reportSchema>> = {
|
|
26
73
|
name: 'AgentReport', inputSchema: reportSchema, parameters: toToolParameters(reportSchema),
|
|
@@ -29,7 +76,11 @@ export const agentReportTool: Tool<z.infer<typeof reportSchema>> = {
|
|
|
29
76
|
call: async () => ({ ok: false, error: 'AgentReport requires a parent channel' }),
|
|
30
77
|
callWithContext: async (input, _signal, ctx) => {
|
|
31
78
|
if (!ctx.agentHandoff) return { ok: false, error: '当前没有主 Agent 交接通道' };
|
|
32
|
-
|
|
79
|
+
// 历史 ∪ 执行台账:长任务压缩掉旧工具消息后,真实做过的检查仍可引用。
|
|
80
|
+
const known = new Set([
|
|
81
|
+
...(ctx.history?.filter((m) => m.role === 'tool').map((m) => m.tool_call_id) ?? []),
|
|
82
|
+
...(ctx.executedCalls?.keys() ?? []),
|
|
83
|
+
]);
|
|
33
84
|
const refs = [...input.evidenceRefs, ...(input.findings ?? []).flatMap(finding => finding.evidenceRefs)];
|
|
34
85
|
if (refs.some((ref) => !known.has(ref))) {
|
|
35
86
|
// Hand back real handles instead of making the model guess: only IDs the
|
|
@@ -136,10 +187,8 @@ export const agentResolveTool: Tool<z.infer<typeof resolveSchema>> = {
|
|
|
136
187
|
return { ok: false, error: '必须先接管,再登记主 Agent 已完成' };
|
|
137
188
|
if (record.input.agent_type === 'general' && ['accept', 'complete'].includes(input.action)) {
|
|
138
189
|
if (!input.writeReview) return { ok: false, error: '写任务必须提供 writeReview:说明主工作区集成、最终验证和主 Agent 检查证据;子任务 completed 不等于集成完成' };
|
|
139
|
-
const
|
|
140
|
-
|
|
141
|
-
const known = new Set(ctx.history?.filter(m => m.role === 'tool' && m.timestamp !== undefined && m.timestamp >= record.createdAt && m.toolResultDisposition !== 'deferred' && inspectionTools.has(calls.get(m.tool_call_id) ?? '')).map(m => m.role === 'tool' ? m.tool_call_id : ''));
|
|
142
|
-
if (input.writeReview.evidenceRefs.some(ref => !known.has(ref))) return { ok: false, error: 'writeReview 证据必须来自当前主历史中本任务创建后的实际检查,不能引用控制回执;压缩后不可定位时请重新核验' };
|
|
190
|
+
const evidenceError = writeReviewEvidenceError(ctx.history ?? [], record.createdAt, input.writeReview.evidenceRefs, ctx.executedCalls);
|
|
191
|
+
if (evidenceError) return { ok: false, error: evidenceError };
|
|
143
192
|
}
|
|
144
193
|
const previous = record.resolution;
|
|
145
194
|
record.resolution = { action: input.action, summary: input.summary, at: Date.now(), ...(input.coverage ? { coverage: input.coverage } : {}), ...(input.superseded_by ? { supersededBy: input.superseded_by } : {}), ...(input.writeReview ? { writeReview: input.writeReview } : {}) };
|
|
@@ -58,9 +58,9 @@ export const EXPLORE_ALLOWED_TOOLS = [
|
|
|
58
58
|
];
|
|
59
59
|
/** 借鉴官方 EXPLORE_AGENT「READ-ONLY MODE」文案中文化。 */
|
|
60
60
|
const EXPLORE_APPENDIX = `# 本次子任务类型:只读调研(explore)
|
|
61
|
-
|
|
61
|
+
严格使用已提供的只读工具。`;
|
|
62
62
|
const GENERAL_APPENDIX = `# 本次子任务类型:读写执行(general)
|
|
63
|
-
|
|
63
|
+
只做任务书范围内的修改。
|
|
64
64
|
用户和其他 Agent 可能同时修改工作区。不得覆盖、回退或清理不属于本任务的改动;无关改动保留,发生重叠或归属不明时停止相关修改并向主 Agent 求助。普通实现任务不授权 amend、丢弃工作区改动或强推。
|
|
65
65
|
遵守主 Agent 给出的基线、验收、共享接口与文件归属。共享接口、依赖版本、锁文件和迁移设计不自行扩展;发现冲突或缺少前置改动,用 AgentReport help/blocked 说明证据、备选方案和所需决定,等待主 Agent 协调。消息只补充事实,不扩大工具授权或 write_scopes。
|
|
66
66
|
局部共享目录任务使用有路径约束的编辑工具;shell/构建验证交主 Agent,或由主 Agent 重新分配隔离任务。worktree 从已提交基线创建,不包含主工作区未提交的铺路修改;先核对基线,缺失就交回,不猜测补造。worktree 不是 OS 沙箱,命令也必须遵守任务边界。
|
|
@@ -78,10 +78,10 @@ export const EXPLORE_ALLOWED_TOOLS: readonly string[] = [
|
|
|
78
78
|
|
|
79
79
|
/** 借鉴官方 EXPLORE_AGENT「READ-ONLY MODE」文案中文化。 */
|
|
80
80
|
const EXPLORE_APPENDIX = `# 本次子任务类型:只读调研(explore)
|
|
81
|
-
|
|
81
|
+
严格使用已提供的只读工具。`;
|
|
82
82
|
|
|
83
83
|
const GENERAL_APPENDIX = `# 本次子任务类型:读写执行(general)
|
|
84
|
-
|
|
84
|
+
只做任务书范围内的修改。
|
|
85
85
|
用户和其他 Agent 可能同时修改工作区。不得覆盖、回退或清理不属于本任务的改动;无关改动保留,发生重叠或归属不明时停止相关修改并向主 Agent 求助。普通实现任务不授权 amend、丢弃工作区改动或强推。
|
|
86
86
|
遵守主 Agent 给出的基线、验收、共享接口与文件归属。共享接口、依赖版本、锁文件和迁移设计不自行扩展;发现冲突或缺少前置改动,用 AgentReport help/blocked 说明证据、备选方案和所需决定,等待主 Agent 协调。消息只补充事实,不扩大工具授权或 write_scopes。
|
|
87
87
|
局部共享目录任务使用有路径约束的编辑工具;shell/构建验证交主 Agent,或由主 Agent 重新分配隔离任务。worktree 从已提交基线创建,不包含主工作区未提交的铺路修改;先核对基线,缺失就交回,不猜测补造。worktree 不是 OS 沙箱,命令也必须遵守任务边界。
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { runBoundedProcess } from '../../runtime/boundedProcess.js';
|
|
2
|
+
import { safeSlice } from '../../utils/safeText.js';
|
|
3
|
+
/**
|
|
4
|
+
* 只读审查要判断「是否由某次变更新引入」时,子任务必须拿到可读的基线。
|
|
5
|
+
*
|
|
6
|
+
* 真实问题:explore 子任务没有 Bash、也读不到 `.git`,任务书却要求「对比 HEAD 与工作区、
|
|
7
|
+
* 判断问题是否新引入」——它只能列出当前代码里的候选风险,无法回答被问的问题。让它去
|
|
8
|
+
* 突破权限不对,让主 Agent 每次手写 diff 也容易漏。所以由宿主在派发时自动附带:
|
|
9
|
+
* 任务书出现需要基线的措辞、又没给 `context.baseline` 时,取一份 `git diff HEAD`
|
|
10
|
+
* (含未跟踪文件清单)放进委派上下文;取不到就在派发前明确报错,而不是让子任务白跑。
|
|
11
|
+
*/
|
|
12
|
+
const NEEDS_BASELINE = /新引入|是否(?:由|为).{0,12}(?:变更|改动|提交|修改)(?:引入|造成|导致)|引入了?(?:回归|缺陷|问题)|回归(?:缺陷|问题)|基线|baseline|git\s+diff|(?:对比|比较|比对).{0,16}(?:HEAD|工作区|基线|改动前)|(?:HEAD|基线).{0,16}(?:对比|比较|比对)|\bregression\b|newly introduced|introduced by/i;
|
|
13
|
+
/** 只读子任务的任务书是否需要「改动前后」基线,且调用方没有提供。 */
|
|
14
|
+
export function needsChangeBaseline(input) {
|
|
15
|
+
if (input.agent_type === 'general')
|
|
16
|
+
return false;
|
|
17
|
+
if (input.context?.baseline?.trim())
|
|
18
|
+
return false;
|
|
19
|
+
const text = [
|
|
20
|
+
input.prompt,
|
|
21
|
+
input.description ?? '',
|
|
22
|
+
input.context?.goal ?? '',
|
|
23
|
+
input.context?.acceptance ?? '',
|
|
24
|
+
input.context?.researchQuestions ? JSON.stringify(input.context.researchQuestions) : '',
|
|
25
|
+
].join('\n');
|
|
26
|
+
return NEEDS_BASELINE.test(text);
|
|
27
|
+
}
|
|
28
|
+
/** 宿主取不到 git diff 时写进 context.baseline 的说明:不拒绝派发,但要求子任务如实声明限制。 */
|
|
29
|
+
export const BASELINE_UNAVAILABLE = '[宿主未能取得 git diff(不是 git 仓库、没有任何提交或 git 不可用),且只读子任务读不到 .git,因此没有可用的改动前基线。'
|
|
30
|
+
+ '若任务要判断某问题是否由变更新引入,请在报告里如实说明「缺少基线、无法判断」,只报告当前代码中的候选风险,不要凭当前代码断言是新引入。]';
|
|
31
|
+
/** 附带基线的体量上限(字符)。超出时保留文件清单与统计,正文按文件截断并如实说明。 */
|
|
32
|
+
export const BASELINE_MAX_CHARS = 60_000;
|
|
33
|
+
async function git(args, cwd, signal) {
|
|
34
|
+
try {
|
|
35
|
+
const result = await runBoundedProcess('git', args, {
|
|
36
|
+
cwd, timeoutMs: 30_000, signal,
|
|
37
|
+
env: { GIT_TERMINAL_PROMPT: '0', GIT_ASKPASS: '' },
|
|
38
|
+
});
|
|
39
|
+
return result.exitCode === 0 ? result.stdout : undefined;
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
return undefined;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* 取 `HEAD → 工作区` 的差异作为基线文本;不是 git 仓库、没有提交或 git 不可用时返回 undefined。
|
|
47
|
+
* 无改动也是有效基线(明确告诉子任务「工作区与 HEAD 一致」)。
|
|
48
|
+
*/
|
|
49
|
+
export async function captureGitBaseline(cwd, signal) {
|
|
50
|
+
const head = (await git(['rev-parse', '--short', 'HEAD'], cwd, signal))?.trim();
|
|
51
|
+
if (!head)
|
|
52
|
+
return undefined;
|
|
53
|
+
const status = (await git(['status', '--porcelain'], cwd, signal)) ?? '';
|
|
54
|
+
const stat = (await git(['diff', 'HEAD', '--stat'], cwd, signal)) ?? '';
|
|
55
|
+
const diff = (await git(['diff', 'HEAD', '--no-color'], cwd, signal)) ?? '';
|
|
56
|
+
const untracked = status.split('\n').filter((line) => line.startsWith('??')).map((line) => line.slice(3).trim());
|
|
57
|
+
const header = `[宿主自动附带的基线:git diff HEAD(HEAD=${head});子任务不能运行 git,请以此为「改动前」依据。`
|
|
58
|
+
+ '修改前的内容在 `-` 行与 HEAD,修改后在 `+` 行与工作区。]';
|
|
59
|
+
const parts = [header];
|
|
60
|
+
parts.push(status.trim() ? `文件状态:\n${status.trim()}` : '工作区与 HEAD 一致,没有未提交改动。');
|
|
61
|
+
if (untracked.length)
|
|
62
|
+
parts.push(`未跟踪的新文件(不在 diff 里,请直接 Read):${untracked.join('、')}`);
|
|
63
|
+
if (stat.trim())
|
|
64
|
+
parts.push(`统计:\n${stat.trim()}`);
|
|
65
|
+
let body = diff;
|
|
66
|
+
if (body.length > BASELINE_MAX_CHARS) {
|
|
67
|
+
body = `${safeSlice(body, 0, BASELINE_MAX_CHARS)}\n…(diff 过长,已截断 ${diff.length - BASELINE_MAX_CHARS} 字符;其余文件请 Read 当前内容并结合上面的统计判断,不能假定未显示部分无改动)`;
|
|
68
|
+
}
|
|
69
|
+
if (body.trim())
|
|
70
|
+
parts.push(`差异:\n${body}`);
|
|
71
|
+
return parts.join('\n\n');
|
|
72
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { runBoundedProcess } from '../../runtime/boundedProcess.js';
|
|
2
|
+
import { safeSlice } from '../../utils/safeText.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* 只读审查要判断「是否由某次变更新引入」时,子任务必须拿到可读的基线。
|
|
6
|
+
*
|
|
7
|
+
* 真实问题:explore 子任务没有 Bash、也读不到 `.git`,任务书却要求「对比 HEAD 与工作区、
|
|
8
|
+
* 判断问题是否新引入」——它只能列出当前代码里的候选风险,无法回答被问的问题。让它去
|
|
9
|
+
* 突破权限不对,让主 Agent 每次手写 diff 也容易漏。所以由宿主在派发时自动附带:
|
|
10
|
+
* 任务书出现需要基线的措辞、又没给 `context.baseline` 时,取一份 `git diff HEAD`
|
|
11
|
+
* (含未跟踪文件清单)放进委派上下文;取不到就在派发前明确报错,而不是让子任务白跑。
|
|
12
|
+
*/
|
|
13
|
+
const NEEDS_BASELINE =
|
|
14
|
+
/新引入|是否(?:由|为).{0,12}(?:变更|改动|提交|修改)(?:引入|造成|导致)|引入了?(?:回归|缺陷|问题)|回归(?:缺陷|问题)|基线|baseline|git\s+diff|(?:对比|比较|比对).{0,16}(?:HEAD|工作区|基线|改动前)|(?:HEAD|基线).{0,16}(?:对比|比较|比对)|\bregression\b|newly introduced|introduced by/i;
|
|
15
|
+
|
|
16
|
+
export interface BaselineCheckInput {
|
|
17
|
+
prompt: string;
|
|
18
|
+
description?: string;
|
|
19
|
+
agent_type?: string;
|
|
20
|
+
context?: { baseline?: string; researchQuestions?: unknown; goal?: string; acceptance?: string };
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** 只读子任务的任务书是否需要「改动前后」基线,且调用方没有提供。 */
|
|
24
|
+
export function needsChangeBaseline(input: BaselineCheckInput): boolean {
|
|
25
|
+
if (input.agent_type === 'general') return false;
|
|
26
|
+
if (input.context?.baseline?.trim()) return false;
|
|
27
|
+
const text = [
|
|
28
|
+
input.prompt,
|
|
29
|
+
input.description ?? '',
|
|
30
|
+
input.context?.goal ?? '',
|
|
31
|
+
input.context?.acceptance ?? '',
|
|
32
|
+
input.context?.researchQuestions ? JSON.stringify(input.context.researchQuestions) : '',
|
|
33
|
+
].join('\n');
|
|
34
|
+
return NEEDS_BASELINE.test(text);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** 宿主取不到 git diff 时写进 context.baseline 的说明:不拒绝派发,但要求子任务如实声明限制。 */
|
|
38
|
+
export const BASELINE_UNAVAILABLE =
|
|
39
|
+
'[宿主未能取得 git diff(不是 git 仓库、没有任何提交或 git 不可用),且只读子任务读不到 .git,因此没有可用的改动前基线。'
|
|
40
|
+
+ '若任务要判断某问题是否由变更新引入,请在报告里如实说明「缺少基线、无法判断」,只报告当前代码中的候选风险,不要凭当前代码断言是新引入。]';
|
|
41
|
+
|
|
42
|
+
/** 附带基线的体量上限(字符)。超出时保留文件清单与统计,正文按文件截断并如实说明。 */
|
|
43
|
+
export const BASELINE_MAX_CHARS = 60_000;
|
|
44
|
+
|
|
45
|
+
async function git(args: string[], cwd: string, signal?: AbortSignal): Promise<string | undefined> {
|
|
46
|
+
try {
|
|
47
|
+
const result = await runBoundedProcess('git', args, {
|
|
48
|
+
cwd, timeoutMs: 30_000, signal,
|
|
49
|
+
env: { GIT_TERMINAL_PROMPT: '0', GIT_ASKPASS: '' },
|
|
50
|
+
});
|
|
51
|
+
return result.exitCode === 0 ? result.stdout : undefined;
|
|
52
|
+
} catch {
|
|
53
|
+
return undefined;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* 取 `HEAD → 工作区` 的差异作为基线文本;不是 git 仓库、没有提交或 git 不可用时返回 undefined。
|
|
59
|
+
* 无改动也是有效基线(明确告诉子任务「工作区与 HEAD 一致」)。
|
|
60
|
+
*/
|
|
61
|
+
export async function captureGitBaseline(cwd: string, signal?: AbortSignal): Promise<string | undefined> {
|
|
62
|
+
const head = (await git(['rev-parse', '--short', 'HEAD'], cwd, signal))?.trim();
|
|
63
|
+
if (!head) return undefined;
|
|
64
|
+
const status = (await git(['status', '--porcelain'], cwd, signal)) ?? '';
|
|
65
|
+
const stat = (await git(['diff', 'HEAD', '--stat'], cwd, signal)) ?? '';
|
|
66
|
+
const diff = (await git(['diff', 'HEAD', '--no-color'], cwd, signal)) ?? '';
|
|
67
|
+
const untracked = status.split('\n').filter((line) => line.startsWith('??')).map((line) => line.slice(3).trim());
|
|
68
|
+
const header = `[宿主自动附带的基线:git diff HEAD(HEAD=${head});子任务不能运行 git,请以此为「改动前」依据。`
|
|
69
|
+
+ '修改前的内容在 `-` 行与 HEAD,修改后在 `+` 行与工作区。]';
|
|
70
|
+
const parts = [header];
|
|
71
|
+
parts.push(status.trim() ? `文件状态:\n${status.trim()}` : '工作区与 HEAD 一致,没有未提交改动。');
|
|
72
|
+
if (untracked.length) parts.push(`未跟踪的新文件(不在 diff 里,请直接 Read):${untracked.join('、')}`);
|
|
73
|
+
if (stat.trim()) parts.push(`统计:\n${stat.trim()}`);
|
|
74
|
+
let body = diff;
|
|
75
|
+
if (body.length > BASELINE_MAX_CHARS) {
|
|
76
|
+
body = `${safeSlice(body, 0, BASELINE_MAX_CHARS)}\n…(diff 过长,已截断 ${diff.length - BASELINE_MAX_CHARS} 字符;其余文件请 Read 当前内容并结合上面的统计判断,不能假定未显示部分无改动)`;
|
|
77
|
+
}
|
|
78
|
+
if (body.trim()) parts.push(`差异:\n${body}`);
|
|
79
|
+
return parts.join('\n\n');
|
|
80
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/** 单个台账最多保留的条目;超出时淘汰最旧的。 */
|
|
2
|
+
export const EXECUTED_CALLS_MAX = 600;
|
|
3
|
+
export function recordExecutedCall(ledger, toolCallId, tool, at = Date.now()) {
|
|
4
|
+
ledger.delete(toolCallId);
|
|
5
|
+
ledger.set(toolCallId, { tool, at });
|
|
6
|
+
while (ledger.size > EXECUTED_CALLS_MAX) {
|
|
7
|
+
const oldest = ledger.keys().next().value;
|
|
8
|
+
if (oldest === undefined)
|
|
9
|
+
break;
|
|
10
|
+
ledger.delete(oldest);
|
|
11
|
+
}
|
|
12
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 「本会话实际执行过的工具调用」台账:tool_call_id → { tool, at }。
|
|
3
|
+
*
|
|
4
|
+
* 为什么需要它(真实问题):AgentReport / AgentResolve 校验证据 ID 时只看当前可见历史。
|
|
5
|
+
* 长任务压缩之后,旧工具消息被摘要掉,历史里找不到这些 ID,于是**真实做过的检查**
|
|
6
|
+
* 也被判成「不可定位」,子任务报告被拒、主 Agent 验收被拒。台账由执行器在工具真正
|
|
7
|
+
* 执行后记录(暂缓/被拒的调用不会进来),不依赖历史是否被压缩;校验时历史与台账取并集。
|
|
8
|
+
* 台账只证明「这个调用确实发生过」,不证明命令成功或检查范围充分。
|
|
9
|
+
*/
|
|
10
|
+
export type ExecutedCalls = Map<string, { tool: string; at: number }>;
|
|
11
|
+
|
|
12
|
+
/** 单个台账最多保留的条目;超出时淘汰最旧的。 */
|
|
13
|
+
export const EXECUTED_CALLS_MAX = 600;
|
|
14
|
+
|
|
15
|
+
export function recordExecutedCall(
|
|
16
|
+
ledger: ExecutedCalls,
|
|
17
|
+
toolCallId: string,
|
|
18
|
+
tool: string,
|
|
19
|
+
at: number = Date.now(),
|
|
20
|
+
): void {
|
|
21
|
+
ledger.delete(toolCallId);
|
|
22
|
+
ledger.set(toolCallId, { tool, at });
|
|
23
|
+
while (ledger.size > EXECUTED_CALLS_MAX) {
|
|
24
|
+
const oldest = ledger.keys().next().value;
|
|
25
|
+
if (oldest === undefined) break;
|
|
26
|
+
ledger.delete(oldest);
|
|
27
|
+
}
|
|
28
|
+
}
|
package/src/tools/bash/bash.js
CHANGED
|
@@ -47,6 +47,7 @@ import { sanitizeCredentialEnv } from '../../config/configService.js';
|
|
|
47
47
|
import { DEFAULT_MAX_RESULT_SIZE_CHARS } from '../types.js';
|
|
48
48
|
import { killTree } from '../shared/killTree.js';
|
|
49
49
|
import { toToolParameters } from '../../utils/zodToJson.js';
|
|
50
|
+
import { safeSlice } from '../../utils/safeText.js';
|
|
50
51
|
import { MAX_ATTACH_IMAGES, extractAttachImageDirectives, resolveAttachImages, } from './attachImage.js';
|
|
51
52
|
import { interpretCommandResult } from './semantics.js';
|
|
52
53
|
import { scanDestructiveCommand } from './warnings.js';
|
|
@@ -617,7 +618,7 @@ async function call(input, signal, context) {
|
|
|
617
618
|
if (combinedOutput.length + outputReference.length > DEFAULT_MAX_RESULT_SIZE_CHARS) {
|
|
618
619
|
const suffix = `\n\n... (输出超过 ${DEFAULT_MAX_RESULT_SIZE_CHARS} 字符,预览已截断)${outputReference}`;
|
|
619
620
|
combinedOutput =
|
|
620
|
-
combinedOutput
|
|
621
|
+
safeSlice(combinedOutput, 0, Math.max(0, DEFAULT_MAX_RESULT_SIZE_CHARS - suffix.length)) + suffix;
|
|
621
622
|
}
|
|
622
623
|
else
|
|
623
624
|
combinedOutput += outputReference;
|
package/src/tools/bash/bash.ts
CHANGED
|
@@ -50,6 +50,7 @@ import { sanitizeCredentialEnv } from '../../config/configService.js';
|
|
|
50
50
|
import { DEFAULT_MAX_RESULT_SIZE_CHARS } from '../types.js';
|
|
51
51
|
import { killTree } from '../shared/killTree.js';
|
|
52
52
|
import { toToolParameters } from '../../utils/zodToJson.js';
|
|
53
|
+
import { safeSlice } from '../../utils/safeText.js';
|
|
53
54
|
import {
|
|
54
55
|
MAX_ATTACH_IMAGES,
|
|
55
56
|
extractAttachImageDirectives,
|
|
@@ -659,7 +660,7 @@ async function call(input: BashInput, signal?: AbortSignal, context?: ToolCallCo
|
|
|
659
660
|
if (combinedOutput.length + outputReference.length > DEFAULT_MAX_RESULT_SIZE_CHARS) {
|
|
660
661
|
const suffix = `\n\n... (输出超过 ${DEFAULT_MAX_RESULT_SIZE_CHARS} 字符,预览已截断)${outputReference}`;
|
|
661
662
|
combinedOutput =
|
|
662
|
-
combinedOutput
|
|
663
|
+
safeSlice(combinedOutput, 0, Math.max(0, DEFAULT_MAX_RESULT_SIZE_CHARS - suffix.length)) + suffix;
|
|
663
664
|
} else combinedOutput += outputReference;
|
|
664
665
|
|
|
665
666
|
// 4e. 中断 / 超时仍然算硬失败
|