minimal-agent 0.18.18 → 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.
Files changed (54) hide show
  1. package/README.md +1 -1
  2. package/package.json +1 -1
  3. package/src/advisor/README.md +2 -0
  4. package/src/cli/wizards/advisorWizard.js +2 -2
  5. package/src/cli/wizards/advisorWizard.tsx +2 -2
  6. package/src/cli/wizards/providerPresets.js +1 -1
  7. package/src/cli/wizards/providerPresets.ts +1 -1
  8. package/src/config/configFile.js +10 -5
  9. package/src/config/configFile.ts +10 -5
  10. package/src/config/configService.js +1 -1
  11. package/src/config/configService.ts +1 -1
  12. package/src/config.js +2 -2
  13. package/src/config.ts +2 -2
  14. package/src/context/microCompactLite.js +3 -2
  15. package/src/context/microCompactLite.ts +3 -2
  16. package/src/context/toolResultArchive.js +2 -1
  17. package/src/context/toolResultArchive.ts +2 -1
  18. package/src/llm/client.js +20 -1
  19. package/src/llm/client.ts +20 -1
  20. package/src/llm/messageProvenance.js +72 -1
  21. package/src/llm/messageProvenance.ts +72 -1
  22. package/src/loop/toolExecutor.js +7 -0
  23. package/src/loop/toolExecutor.ts +7 -0
  24. package/src/memory/episodicMemory.js +3 -3
  25. package/src/memory/episodicMemory.ts +12 -8
  26. package/src/memory/taskEvidence.js +2 -1
  27. package/src/memory/taskEvidence.ts +2 -1
  28. package/src/prompts/delegation.js +2 -2
  29. package/src/prompts/delegation.ts +2 -2
  30. package/src/runtime/deliveryGate.js +20 -3
  31. package/src/runtime/deliveryGate.ts +17 -3
  32. package/src/session/sessionState.ts +2 -0
  33. package/src/tools/advisor/advisor.js +88 -11
  34. package/src/tools/advisor/advisor.ts +98 -11
  35. package/src/tools/agent/README.md +3 -0
  36. package/src/tools/agent/agent.js +8 -0
  37. package/src/tools/agent/agent.ts +8 -0
  38. package/src/tools/agent/agentHandoff.js +59 -6
  39. package/src/tools/agent/agentHandoff.ts +55 -6
  40. package/src/tools/agent/baselineAttach.js +72 -0
  41. package/src/tools/agent/baselineAttach.ts +80 -0
  42. package/src/tools/agent/executedCalls.js +12 -0
  43. package/src/tools/agent/executedCalls.ts +28 -0
  44. package/src/tools/bash/bash.js +2 -1
  45. package/src/tools/bash/bash.ts +2 -1
  46. package/src/tools/read/read.js +2 -1
  47. package/src/tools/read/read.ts +2 -1
  48. package/src/tools/shared/toolOutputStore.js +5 -4
  49. package/src/tools/shared/toolOutputStore.ts +5 -4
  50. package/src/types.ts +3 -1
  51. package/src/ui/InputBox.js +53 -2
  52. package/src/ui/InputBox.tsx +50 -2
  53. package/src/utils/safeText.js +30 -0
  54. package/src/utils/safeText.ts +34 -0
@@ -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
- const known = new Set(ctx.history?.filter((m) => m.role === 'tool').map((m) => m.tool_call_id));
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 inspectionTools = new Set(['Read', 'Grep', 'Glob', 'LSP', 'Bash', 'PowerShell']);
138
- const calls = new Map(ctx.history?.flatMap(m => m.role === 'assistant' ? (m.tool_calls ?? []).map(c => [c.id, c.function.name]) : []));
139
- 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 : ''));
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
- const known = new Set(ctx.history?.filter((m) => m.role === 'tool').map((m) => m.tool_call_id));
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 inspectionTools = new Set(['Read', 'Grep', 'Glob', 'LSP', 'Bash', 'PowerShell']);
140
- const calls = new Map(ctx.history?.flatMap(m => m.role === 'assistant' ? (m.tool_calls ?? []).map(c => [c.id, c.function.name] as const) : []));
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 } : {}) };
@@ -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
+ }
@@ -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.slice(0, Math.max(0, DEFAULT_MAX_RESULT_SIZE_CHARS - suffix.length)) + suffix;
621
+ safeSlice(combinedOutput, 0, Math.max(0, DEFAULT_MAX_RESULT_SIZE_CHARS - suffix.length)) + suffix;
621
622
  }
622
623
  else
623
624
  combinedOutput += outputReference;
@@ -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.slice(0, Math.max(0, DEFAULT_MAX_RESULT_SIZE_CHARS - suffix.length)) + suffix;
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. 中断 / 超时仍然算硬失败
@@ -7,6 +7,7 @@ import { join } from 'node:path';
7
7
  import { randomUUID } from 'node:crypto';
8
8
  import { z } from 'zod';
9
9
  import { dlog } from '../../utils/debugLog.js';
10
+ import { safeSlice } from '../../utils/safeText.js';
10
11
  import { toToolParameters } from '../../utils/zodToJson.js';
11
12
  import { DEFAULT_MAX_RESULT_SIZE_CHARS, MAX_FILE_SIZE_BYTES, MAX_LINES_TO_READ, } from '../types.js';
12
13
  import { fileActivityMetadata } from '../shared/fileActivity.js';
@@ -419,7 +420,7 @@ async function call(input, state, cwd, runtimeIdentity, signal, maxChars = DEFAU
419
420
  let truncated = false;
420
421
  if (content.length > maxChars || clippedLine !== undefined) {
421
422
  const nextColumn = (input.column ?? 1) + Math.max(0, content.length - String(offset).length - 1);
422
- content = `${content.slice(0, maxChars)}\n\n⚠️ 重要:Read 输出已截断;截断范围外仍有内容。超长行请提高 max_chars 或使用流式处理,不能跳过未显示内容。`;
423
+ content = `${safeSlice(content, 0, maxChars)}\n\n⚠️ 重要:Read 输出已截断;截断范围外仍有内容。超长行请提高 max_chars 或使用流式处理,不能跳过未显示内容。`;
423
424
  if (clippedLine !== undefined)
424
425
  content += `\n继续读取 offset=${clippedLine} column=${nextColumn}`;
425
426
  truncated = true;
@@ -9,6 +9,7 @@ import { z } from 'zod';
9
9
 
10
10
  import type { Tool, ToolCallContext, ToolResult } from '../../types.js';
11
11
  import { dlog } from '../../utils/debugLog.js';
12
+ import { safeSlice } from '../../utils/safeText.js';
12
13
  import { toToolParameters } from '../../utils/zodToJson.js';
13
14
  import {
14
15
  DEFAULT_MAX_RESULT_SIZE_CHARS,
@@ -508,7 +509,7 @@ async function call(
508
509
  let truncated = false;
509
510
  if (content.length > maxChars || clippedLine !== undefined) {
510
511
  const nextColumn = (input.column ?? 1) + Math.max(0, content.length - String(offset).length - 1);
511
- content = `${content.slice(0, maxChars)}\n\n⚠️ 重要:Read 输出已截断;截断范围外仍有内容。超长行请提高 max_chars 或使用流式处理,不能跳过未显示内容。`;
512
+ content = `${safeSlice(content, 0, maxChars)}\n\n⚠️ 重要:Read 输出已截断;截断范围外仍有内容。超长行请提高 max_chars 或使用流式处理,不能跳过未显示内容。`;
512
513
  if (clippedLine !== undefined) content += `\n继续读取 offset=${clippedLine} column=${nextColumn}`;
513
514
  truncated = true;
514
515
  }
@@ -2,6 +2,7 @@ import { createHash, randomUUID } from 'node:crypto';
2
2
  import { createWriteStream, mkdirSync } from 'node:fs';
3
3
  import { join } from 'node:path';
4
4
  import { sessionRuntimeDir, pruneRuntimeOutputs, registerRuntimeOutput, unregisterRuntimeOutput, } from '../../session/runtimeStore.js';
5
+ import { safeSlice } from '../../utils/safeText.js';
5
6
  const SPILL_AT = 64 * 1024, MAX_BYTES = 512 * 1024 * 1024, PREVIEW = 32 * 1024;
6
7
  export class ToolOutputStore {
7
8
  stdout = '';
@@ -60,13 +61,13 @@ export class ToolOutputStore {
60
61
  const text = selected.toString('utf8');
61
62
  if (source === 'stdout') {
62
63
  if (this.stdout.length < PREVIEW)
63
- this.stdout += text.slice(0, PREVIEW - this.stdout.length);
64
- this.stdoutTail = (this.stdoutTail + text).slice(-PREVIEW);
64
+ this.stdout += safeSlice(text, 0, PREVIEW - this.stdout.length);
65
+ this.stdoutTail = safeSlice(this.stdoutTail + text, -PREVIEW);
65
66
  }
66
67
  else {
67
68
  if (this.stderr.length < PREVIEW)
68
- this.stderr += text.slice(0, PREVIEW - this.stderr.length);
69
- this.stderrTail = (this.stderrTail + text).slice(-PREVIEW);
69
+ this.stderr += safeSlice(text, 0, PREVIEW - this.stderr.length);
70
+ this.stderrTail = safeSlice(this.stderrTail + text, -PREVIEW);
70
71
  }
71
72
  if (this.stream)
72
73
  return this.writeFrame(source, selected);
@@ -8,6 +8,7 @@ import {
8
8
  type RuntimeIdentity,
9
9
  unregisterRuntimeOutput,
10
10
  } from '../../session/runtimeStore.js';
11
+ import { safeSlice } from '../../utils/safeText.js';
11
12
 
12
13
  const SPILL_AT = 64 * 1024,
13
14
  MAX_BYTES = 512 * 1024 * 1024,
@@ -75,12 +76,12 @@ export class ToolOutputStore {
75
76
  const text = selected.toString('utf8');
76
77
  if (source === 'stdout') {
77
78
  if (this.stdout.length < PREVIEW)
78
- this.stdout += text.slice(0, PREVIEW - this.stdout.length);
79
- this.stdoutTail = (this.stdoutTail + text).slice(-PREVIEW);
79
+ this.stdout += safeSlice(text, 0, PREVIEW - this.stdout.length);
80
+ this.stdoutTail = safeSlice(this.stdoutTail + text, -PREVIEW);
80
81
  } else {
81
82
  if (this.stderr.length < PREVIEW)
82
- this.stderr += text.slice(0, PREVIEW - this.stderr.length);
83
- this.stderrTail = (this.stderrTail + text).slice(-PREVIEW);
83
+ this.stderr += safeSlice(text, 0, PREVIEW - this.stderr.length);
84
+ this.stderrTail = safeSlice(this.stderrTail + text, -PREVIEW);
84
85
  }
85
86
  if (this.stream) return this.writeFrame(source, selected);
86
87
  this.pending.push({ source, data: Buffer.from(selected) });
package/src/types.ts CHANGED
@@ -582,6 +582,8 @@ export interface ToolCallContext {
582
582
  /** Live effective catalog, including per-turn restrictions. */
583
583
  availableToolNames?: () => ReadonlySet<string>;
584
584
  messageProvenance?: ConversationProvenance;
585
+ /** 本会话实际执行过的工具调用台账(压缩后仍可用于证据校验)。 */
586
+ executedCalls?: import('./tools/agent/executedCalls.js').ExecutedCalls;
585
587
  agentHandoff?: {
586
588
  questionIds?: readonly string[];
587
589
  report: (packet: AgentHandoffPacket) => Promise<void>;
@@ -827,7 +829,7 @@ export interface ToolAvailability {
827
829
  // MINIMAL_AGENT_API_KEY - API key
828
830
  // MINIMAL_AGENT_MODEL - 模型名
829
831
  // MINIMAL_AGENT_PROVIDER - 友好名称(可选,默认 "env")
830
- // MINIMAL_AGENT_CONTEXT_WINDOW - 上下文窗口(可选,默认 128000)
832
+ // MINIMAL_AGENT_CONTEXT_WINDOW - 上下文窗口(可选,默认 1000000)
831
833
 
832
834
  interface ProviderCommon {
833
835
  /** 友好名(仅展示用),如 "deepseek" */
@@ -43,6 +43,33 @@ export function isClipboardImageKey(input, key) {
43
43
  return false;
44
44
  return Boolean(key.ctrl) !== Boolean(key.meta);
45
45
  }
46
+ /**
47
+ * 同一个 stdin chunk 里连在一起的退格字节数。
48
+ *
49
+ * Ink 5 的 useInput 把「一次 data chunk」当成一个按键:parseKeypress 只认单字节,
50
+ * 遇到 `\x7f\x7f\x7f` 这种合并块时 name 为空(`\b` 是 backspace、`\x7f` 是 delete,
51
+ * 都只匹配长度为 1 的串),key.backspace / key.delete 全为 false,于是这段原始
52
+ * 字节落进「字符输入」分支被当成正文插入 —— 终端把不可打印的 DEL 渲染成 "?"。
53
+ *
54
+ * Windows 上按住 Backspace 时(终端发 `\x7f`,conhost 还可能发 `\x08`)系统会把
55
+ * 重复按键合并进同一个 chunk,这就是「长按删除键输入框不断冒 ?,重启才消失」。
56
+ * 返回 0 表示这不是纯退格合并块。
57
+ */
58
+ export function repeatedBackspaceCount(input) {
59
+ if (input.length < 2)
60
+ return 0;
61
+ return /^[\x08\x7f]+$/.test(input) ? input.length : 0;
62
+ }
63
+ /**
64
+ * 控制字符与 ANSI 转义序列永远不是用户"输入的文字"。合并块被误判成正文时,
65
+ * 至少保证它们不进缓冲区,否则终端要么渲染成 "?",要么把光标吞掉。
66
+ * 保留 \t / \n / \r —— Alt+Enter 换行依赖后两者,粘贴带缩进的代码依赖制表符。
67
+ */
68
+ export function stripControlChars(text) {
69
+ return text
70
+ .replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g, '')
71
+ .replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, '');
72
+ }
46
73
  // ============================================================
47
74
  // IME 启发式(中文输入法防护)
48
75
  // ------------------------------------------------------------
@@ -188,6 +215,25 @@ function InputBoxImpl({ onSubmit, disabled, onAbort, onClear, onCompact, onWorks
188
215
  return;
189
216
  }
190
217
  // pasteResult === 'continue',继续普通处理
218
+ // ---- ✅ 合并块里的重复退格(Windows 长按删除键)----
219
+ // Ink 5 不拆 chunk,`\x7f\x7f…` 会绕过 key.backspace/key.delete 被当正文插入,
220
+ // 终端把 DEL 渲染成 "?"。这里按字节回放,让长按真的删除。
221
+ const backspaces = repeatedBackspaceCount(input);
222
+ if (backspaces > 0) {
223
+ if (searchMode !== null) {
224
+ const nextQuery = searchMode.query.slice(0, Math.max(0, searchMode.query.length - backspaces));
225
+ if (nextQuery.length === 0)
226
+ setSearchMode(null);
227
+ else
228
+ setSearchMode({ query: nextQuery, hit: hist.search(nextQuery)[0] ?? null });
229
+ }
230
+ else {
231
+ for (let i = 0; i < backspaces; i++)
232
+ buf.deleteBefore();
233
+ forceRefresh();
234
+ }
235
+ return;
236
+ }
191
237
  // ---- ✅ Ctrl+R 反向搜索模式(独占按键流)----
192
238
  if (searchMode !== null) {
193
239
  // ESC 退出搜索
@@ -229,7 +275,10 @@ function InputBoxImpl({ onSubmit, disabled, onAbort, onClear, onCompact, onWorks
229
275
  }
230
276
  // 字面字符(排除控制键)追加到 query
231
277
  if (input && !key.ctrl && !key.meta && !key.return && !key.escape) {
232
- const nextQuery = searchMode.query + input;
278
+ const typed = stripControlChars(input);
279
+ if (!typed)
280
+ return; // 不可打印字节不进 query(否则渲染成 "?")
281
+ const nextQuery = searchMode.query + typed;
233
282
  const nextHit = hist.search(nextQuery)[0] ?? null;
234
283
  setSearchMode({ query: nextQuery, hit: nextHit });
235
284
  return;
@@ -457,7 +506,9 @@ function InputBoxImpl({ onSubmit, disabled, onAbort, onClear, onCompact, onWorks
457
506
  // key.meta=false,从这里落地。把 \r/\r\n 统一成 \n,textBuffer 才能真切分逻辑行
458
507
  // (否则 layout 永远 1 行 → ↑/↓ 失效、输入框不长高,光标只能左右)。
459
508
  if (input && !key.meta) {
460
- const normalized = input.replace(/\r\n?/g, '\n');
509
+ const normalized = stripControlChars(input.replace(/\r\n?/g, '\n'));
510
+ if (!normalized)
511
+ return; // 只有控制/不可打印字节:宁可丢弃也不塞进缓冲区
461
512
  noteTextInsert(normalized.length);
462
513
  buf.insert(normalized);
463
514
  forceRefresh();