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.
Files changed (72) hide show
  1. package/README.md +1 -1
  2. package/package.json +1 -1
  3. package/src/advisor/README.md +12 -0
  4. package/src/advisor/advisorNudge.js +4 -2
  5. package/src/advisor/advisorNudge.ts +6 -2
  6. package/src/cli/wizards/advisorWizard.js +2 -2
  7. package/src/cli/wizards/advisorWizard.tsx +2 -2
  8. package/src/cli/wizards/providerPresets.js +1 -1
  9. package/src/cli/wizards/providerPresets.ts +1 -1
  10. package/src/config/configFile.js +10 -5
  11. package/src/config/configFile.ts +10 -5
  12. package/src/config/configService.js +1 -1
  13. package/src/config/configService.ts +1 -1
  14. package/src/config.js +2 -2
  15. package/src/config.ts +2 -2
  16. package/src/context/budgetPlan.js +3 -1
  17. package/src/context/budgetPlan.ts +3 -1
  18. package/src/context/microCompactLite.js +3 -2
  19. package/src/context/microCompactLite.ts +3 -2
  20. package/src/context/toolResultArchive.js +2 -1
  21. package/src/context/toolResultArchive.ts +2 -1
  22. package/src/llm/client.js +20 -1
  23. package/src/llm/client.ts +20 -1
  24. package/src/llm/messageProvenance.js +72 -1
  25. package/src/llm/messageProvenance.ts +72 -1
  26. package/src/loop/toolExecutor.js +7 -0
  27. package/src/loop/toolExecutor.ts +7 -0
  28. package/src/memory/episodicMemory.js +3 -3
  29. package/src/memory/episodicMemory.ts +12 -8
  30. package/src/memory/sessionPipeline.js +32 -2
  31. package/src/memory/sessionPipeline.ts +38 -2
  32. package/src/memory/taskEvidence.js +2 -1
  33. package/src/memory/taskEvidence.ts +2 -1
  34. package/src/prompts/delegation.js +3 -4
  35. package/src/prompts/delegation.ts +3 -4
  36. package/src/prompts/policyRegistry.js +24 -22
  37. package/src/prompts/policyRegistry.ts +23 -23
  38. package/src/prompts/promptAssembly.js +1 -1
  39. package/src/prompts/promptAssembly.ts +1 -1
  40. package/src/runtime/deliveryGate.js +20 -3
  41. package/src/runtime/deliveryGate.ts +17 -3
  42. package/src/session/sessionState.ts +2 -0
  43. package/src/tools/advisor/advisor.js +245 -40
  44. package/src/tools/advisor/advisor.ts +272 -34
  45. package/src/tools/advisor/advisorDescription.js +5 -0
  46. package/src/tools/advisor/advisorDescription.ts +5 -0
  47. package/src/tools/advisor/advisorVerify.js +84 -0
  48. package/src/tools/advisor/advisorVerify.ts +96 -0
  49. package/src/tools/agent/README.md +3 -0
  50. package/src/tools/agent/agent.js +9 -2
  51. package/src/tools/agent/agent.ts +9 -2
  52. package/src/tools/agent/agentHandoff.js +59 -6
  53. package/src/tools/agent/agentHandoff.ts +55 -6
  54. package/src/tools/agent/agentTypes.js +2 -2
  55. package/src/tools/agent/agentTypes.ts +2 -2
  56. package/src/tools/agent/baselineAttach.js +72 -0
  57. package/src/tools/agent/baselineAttach.ts +80 -0
  58. package/src/tools/agent/executedCalls.js +12 -0
  59. package/src/tools/agent/executedCalls.ts +28 -0
  60. package/src/tools/bash/bash.js +2 -1
  61. package/src/tools/bash/bash.ts +2 -1
  62. package/src/tools/read/read.js +2 -1
  63. package/src/tools/read/read.ts +2 -1
  64. package/src/tools/shared/toolOutputStore.js +5 -4
  65. package/src/tools/shared/toolOutputStore.ts +5 -4
  66. package/src/tools/toolPromptGuides.js +11 -10
  67. package/src/tools/toolPromptGuides.ts +11 -11
  68. package/src/types.ts +3 -2
  69. package/src/ui/InputBox.js +53 -2
  70. package/src/ui/InputBox.tsx +50 -2
  71. package/src/utils/safeText.js +30 -0
  72. package/src/utils/safeText.ts +34 -0
package/README.md CHANGED
@@ -69,7 +69,7 @@ MINIMAL_AGENT_BASE_URL=https://api.minimax.cn/v1 # 必需:API 地址
69
69
  MINIMAL_AGENT_API_KEY=your-api-key # 必需:API key
70
70
  MINIMAL_AGENT_MODEL=MiniMax-M3.1-Flash # 必需:模型名
71
71
  MINIMAL_AGENT_PROVIDER=minimax # 可选:友好名,默认 "env"
72
- MINIMAL_AGENT_CONTEXT_WINDOW=204800 # 可选:上下文窗口,默认 128000
72
+ MINIMAL_AGENT_CONTEXT_WINDOW=204800 # 可选:上下文窗口,默认 1000000
73
73
  TAVILY_API_KEY= # 可选:WebSearch 工具用(https://tavily.com)
74
74
  ```
75
75
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "minimal-agent",
3
- "version": "0.18.17",
3
+ "version": "0.18.19",
4
4
  "description": "Bun-first 的本地 Agent 内核,支持工具、插件、工作流、上下文压缩、长期记忆与 OpenAI 兼容接口;Tauri 桌面宿主和 Node.js npm 发布可复用同一内核",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "author": "Bill Wang <leiwang0359@gmail.com>",
@@ -47,6 +47,16 @@
47
47
  (`test/advisorBackground.test.ts` 锁这条)。这只是一次批内的顺序规则,不是检查点:顾问不会因此
48
48
  推迟任何独立的工具调用,也不会扣下回答。
49
49
 
50
+ ## 顾问自己能核实(只读工具)
51
+
52
+ 顾问有 Read / Grep / Glob,仅限工作区(`tools/advisor/advisorVerify.ts`):它怀疑「某处没覆盖」时自己去读,
53
+ 核实到的写成【有证据】,不再把「缺失材料」丢回执行助手。三条确定性边界:只读(其它工具名一律拒绝);
54
+ 路径必须落在 cwd 内(Glob/Grep 的 glob 不许绝对路径或 `..`);读到的内容和对话一样先抹密钥再回给顾问。
55
+ 核实最多 6 轮,到顶后最后一次请求不带工具、必须给出意见;服务商不接受工具参数时退回纯评审,咨询不整体失败。
56
+ 没有工作目录(无宿主上下文的手动咨询)时不提供工具。persona 的能力声明随之切换(`advisorPersona(canVerify)`),
57
+ 同时要求顾问先判断执行助手所处阶段、把意见写成「去核实 X 是否满足 Y」、并回看自己上次意见之后发生了什么(错了就收回)。
58
+ 效果验证见 `test/advisor.live.test.ts`(需真实模型);接线见 `test/advisorVerify.test.ts`(确定性)。
59
+
50
60
  ## 谁来停住重复失败
51
61
 
52
62
  `StallGuard`:同一调用连续两次返回相同失败,第三次在执行前被拒绝——**与顾问是否可用无关**。
@@ -57,6 +67,8 @@
57
67
 
58
68
  每次咨询只尝试一次;不可用、失败、空答、超时都以 `ok:false` 回到主模型,由它自行继续,
59
69
  不自动重试、不转成人工审批、不宣称获得验证。不设咨询配额。
70
+ 唯一例外:服务商明确报「输入超出上下文窗口」时,缩小材料(先 85%、再 60%,报错带真实上限则以它为准)重建后重发,最多两次,
71
+ 重发时不再带核实工具;限流、超时、网络错误仍只试一次。
60
72
 
61
73
  回归入口:`bun test test/advisorNudge.test.ts test/loop.advisorNudge.test.ts test/deliveryReview.test.ts
62
74
  test/advisorContextFidelity.test.ts test/advisor.test.ts`。
@@ -151,7 +151,9 @@ export class AdvisorNudge {
151
151
  return '';
152
152
  const lines = [];
153
153
  if (this.#stalled.size > 0) {
154
- lines.push('Advisor 提醒:检测到同一问题连续失败或执行没有进展。继续重试之前先咨询 Advisor(只读诊断和换路径不受影响)。');
154
+ lines.push(this.#consultations > 0
155
+ ? 'Advisor 提醒:照顾问的意见处理后仍然连续失败或没有进展。继续重试之前先咨询 Advisor:带着这次的实测与失败证据再问一次,不要默默改道(只读诊断和换路径不受影响)。'
156
+ : 'Advisor 提醒:检测到同一问题连续失败或执行没有进展。继续重试之前先咨询 Advisor(只读诊断和换路径不受影响)。');
155
157
  }
156
158
  if (this.#signal && this.#consultations === 0) {
157
159
  lines.push(this.#signal === 'user_dissatisfaction'
@@ -165,7 +167,7 @@ export class AdvisorNudge {
165
167
  lines.push('Advisor 提醒:本回合还没有咨询顾问。要动手修改,或要给出分析结论之前,先咨询一次 Advisor;简短的即时问答不需要。');
166
168
  }
167
169
  else if (substantive && this.#unreviewed()) {
168
- lines.push('Advisor 提醒:本回合已有实质成果(改动、验证或调查结论),自上次咨询后又有新进展。给出最终结论或交付之前,先咨询一次 Advisor。');
170
+ lines.push('Advisor 提醒:本回合已有实质成果(改动、验证或调查结论),自上次咨询后又有新进展。给出最终结论或交付之前,或打算改变已定的方案/方向之前,先咨询一次 Advisor。');
169
171
  }
170
172
  return lines.join('\n');
171
173
  }
@@ -181,7 +181,11 @@ export class AdvisorNudge {
181
181
  if (!this.#available) return '';
182
182
  const lines: string[] = [];
183
183
  if (this.#stalled.size > 0) {
184
- lines.push('Advisor 提醒:检测到同一问题连续失败或执行没有进展。继续重试之前先咨询 Advisor(只读诊断和换路径不受影响)。');
184
+ lines.push(
185
+ this.#consultations > 0
186
+ ? 'Advisor 提醒:照顾问的意见处理后仍然连续失败或没有进展。继续重试之前先咨询 Advisor:带着这次的实测与失败证据再问一次,不要默默改道(只读诊断和换路径不受影响)。'
187
+ : 'Advisor 提醒:检测到同一问题连续失败或执行没有进展。继续重试之前先咨询 Advisor(只读诊断和换路径不受影响)。',
188
+ );
185
189
  }
186
190
  if (this.#signal && this.#consultations === 0) {
187
191
  lines.push(
@@ -196,7 +200,7 @@ export class AdvisorNudge {
196
200
  if (substantive && this.#consultations === 0 && this.#mutations === 0 && !this.#delivered) {
197
201
  lines.push('Advisor 提醒:本回合还没有咨询顾问。要动手修改,或要给出分析结论之前,先咨询一次 Advisor;简短的即时问答不需要。');
198
202
  } else if (substantive && this.#unreviewed()) {
199
- lines.push('Advisor 提醒:本回合已有实质成果(改动、验证或调查结论),自上次咨询后又有新进展。给出最终结论或交付之前,先咨询一次 Advisor。');
203
+ lines.push('Advisor 提醒:本回合已有实质成果(改动、验证或调查结论),自上次咨询后又有新进展。给出最终结论或交付之前,或打算改变已定的方案/方向之前,先咨询一次 Advisor。');
200
204
  }
201
205
  return lines.join('\n');
202
206
  }
@@ -64,7 +64,7 @@ export function AdvisorWizard({ existing, models, onDone, onCancel }) {
64
64
  { key: 'baseURL', label: 'API 完整端点地址(含 /chat/completions 后缀)', type: 'text', default: '' },
65
65
  { key: 'apiKey', label: 'API Key', type: 'password', default: '' },
66
66
  { key: 'model', label: 'Model', type: 'text', default: '' },
67
- { key: 'contextWindow', label: 'Context Window(token 数)', type: 'text', default: '128000', optional: true },
67
+ { key: 'contextWindow', label: 'Context Window(token 数)', type: 'text', default: '1000000', optional: true },
68
68
  ], onSubmit: async (values) => {
69
69
  const baseURL = String(values.baseURL ?? '').trim();
70
70
  const apiKey = String(values.apiKey ?? '').trim();
@@ -75,7 +75,7 @@ export function AdvisorWizard({ existing, models, onDone, onCancel }) {
75
75
  baseURL,
76
76
  apiKey,
77
77
  model,
78
- contextWindow: parsePositiveInt(values.contextWindow, 128_000),
78
+ contextWindow: parsePositiveInt(values.contextWindow, 1_000_000),
79
79
  supportsVision: true,
80
80
  });
81
81
  setPhase('advisor-fields');
@@ -101,7 +101,7 @@ export function AdvisorWizard({ existing, models, onDone, onCancel }: Props): JS
101
101
  { key: 'baseURL', label: 'API 完整端点地址(含 /chat/completions 后缀)', type: 'text', default: '' },
102
102
  { key: 'apiKey', label: 'API Key', type: 'password', default: '' },
103
103
  { key: 'model', label: 'Model', type: 'text', default: '' },
104
- { key: 'contextWindow', label: 'Context Window(token 数)', type: 'text', default: '128000', optional: true },
104
+ { key: 'contextWindow', label: 'Context Window(token 数)', type: 'text', default: '1000000', optional: true },
105
105
  ]}
106
106
  onSubmit={async (values: FieldValues) => {
107
107
  const baseURL = String(values.baseURL ?? '').trim();
@@ -112,7 +112,7 @@ export function AdvisorWizard({ existing, models, onDone, onCancel }: Props): JS
112
112
  baseURL,
113
113
  apiKey,
114
114
  model,
115
- contextWindow: parsePositiveInt(values.contextWindow, 128_000),
115
+ contextWindow: parsePositiveInt(values.contextWindow, 1_000_000),
116
116
  supportsVision: true,
117
117
  });
118
118
  setPhase('advisor-fields');
@@ -10,7 +10,7 @@
10
10
  import { REASONING_EFFORTS, normalizeReasoningEffort, } from '../../config/reasoningEffort.js';
11
11
  // 兜底值:custom 或表外 model 都退到这里。
12
12
  // 与 src/config.ts 的同名常量含义对齐("既没 env、saved 也没填 contextWindow" 的最终兜底)。
13
- export const FALLBACK_CONTEXT_WINDOW = 128_000;
13
+ export const FALLBACK_CONTEXT_WINDOW = 1_000_000;
14
14
  export const PRESETS = [
15
15
  {
16
16
  name: 'minimax',
@@ -19,7 +19,7 @@ import {
19
19
 
20
20
  // 兜底值:custom 或表外 model 都退到这里。
21
21
  // 与 src/config.ts 的同名常量含义对齐("既没 env、saved 也没填 contextWindow" 的最终兜底)。
22
- export const FALLBACK_CONTEXT_WINDOW = 128_000;
22
+ export const FALLBACK_CONTEXT_WINDOW = 1_000_000;
23
23
 
24
24
  export interface ProviderPreset {
25
25
  name: string;
@@ -12,16 +12,21 @@ export { REASONING_EFFORTS, normalizeReasoningEffort } from './reasoningEffort.j
12
12
  export function normalizeApiFormat(value) {
13
13
  return value === 'anthropic' || value === 'openai-responses' ? value : 'openai';
14
14
  }
15
- export const DEFAULT_CONTEXT_WINDOW = 128_000;
15
+ export const DEFAULT_CONTEXT_WINDOW = 1_000_000;
16
16
  const LOCK_STALE_MS = 120_000;
17
17
  const LOCK_WAIT_MS = 15_000;
18
18
  /**
19
- * 建议的单次输出 token 上限:min(32768, max(4096, contextWindow×0.25))。
20
- * 上限 32768(非更保守的 16384)呼应 .env.example 的实测教训——16384 偏紧,写大 JSON
21
- * 输出时会被截断;maxTokens 是上限不是预订额度,设大不额外花钱。
19
+ * 建议的单次输出 token 上限:min(cap, max(4096, contextWindow×0.25)),
20
+ * cap = 窗口 ≥ 500K 时 65536,否则 32768。
21
+ * 32768(非更保守的 16384)呼应 .env.example 的实测教训——16384 偏紧,写大 JSON
22
+ * 输出时会被截断;百万级窗口的模型思考 + 长输出更吃额度,给到 65536。
23
+ * 门槛取 500K 是为了让「压缩阈值(85%) + 输出上限」始终不超过窗口:500K×0.85+65K<500K,
24
+ * 而 262K 窗口放 65K 就会超(Anthropic 式端点要求输入+max_tokens ≤ 窗口)。
25
+ * maxTokens 是上限不是预订额度,设大不额外花钱。
22
26
  */
23
27
  export function defaultMaxTokens(contextWindow) {
24
- return Math.min(32_768, Math.max(4_096, Math.round(contextWindow * 0.25)));
28
+ const cap = contextWindow >= 500_000 ? 65_536 : 32_768;
29
+ return Math.min(cap, Math.max(4_096, Math.round(contextWindow * 0.25)));
25
30
  }
26
31
  function homeConfigPath() {
27
32
  return join(process.env.MINIMAL_AGENT_HOME ?? homedir(), '.minimal-agent', 'config.json');
@@ -163,17 +163,22 @@ export interface ConfigDrafts {
163
163
  tools?: Record<string, Record<string, unknown>>;
164
164
  }
165
165
 
166
- export const DEFAULT_CONTEXT_WINDOW = 128_000;
166
+ export const DEFAULT_CONTEXT_WINDOW = 1_000_000;
167
167
  const LOCK_STALE_MS = 120_000;
168
168
  const LOCK_WAIT_MS = 15_000;
169
169
 
170
170
  /**
171
- * 建议的单次输出 token 上限:min(32768, max(4096, contextWindow×0.25))。
172
- * 上限 32768(非更保守的 16384)呼应 .env.example 的实测教训——16384 偏紧,写大 JSON
173
- * 输出时会被截断;maxTokens 是上限不是预订额度,设大不额外花钱。
171
+ * 建议的单次输出 token 上限:min(cap, max(4096, contextWindow×0.25)),
172
+ * cap = 窗口 ≥ 500K 时 65536,否则 32768。
173
+ * 32768(非更保守的 16384)呼应 .env.example 的实测教训——16384 偏紧,写大 JSON
174
+ * 输出时会被截断;百万级窗口的模型思考 + 长输出更吃额度,给到 65536。
175
+ * 门槛取 500K 是为了让「压缩阈值(85%) + 输出上限」始终不超过窗口:500K×0.85+65K<500K,
176
+ * 而 262K 窗口放 65K 就会超(Anthropic 式端点要求输入+max_tokens ≤ 窗口)。
177
+ * maxTokens 是上限不是预订额度,设大不额外花钱。
174
178
  */
175
179
  export function defaultMaxTokens(contextWindow: number): number {
176
- return Math.min(32_768, Math.max(4_096, Math.round(contextWindow * 0.25)));
180
+ const cap = contextWindow >= 500_000 ? 65_536 : 32_768;
181
+ return Math.min(cap, Math.max(4_096, Math.round(contextWindow * 0.25)));
177
182
  }
178
183
 
179
184
  function homeConfigPath(): string {
@@ -4,7 +4,7 @@ import { fetchOnlineModels, loadTeamCredentials, resolveOnlineModel, } from '../
4
4
  import { normalizeApiFormat, normalizeReasoningEffort, DEFAULT_ADVISOR_CONFIG, DEFAULT_BROWSER_CONFIG, DEFAULT_COMPUTER_USE_CONFIG, DEFAULT_NETWORK_PROXY_CONFIG, DEFAULT_SUBAGENTS_CONFIG, defaultMaxTokens, readMinimalAgentConfig, updateMinimalAgentConfig, } from './configFile.js';
5
5
  import { CONFIG_LIMITS, normalizeLimited } from './numericLimits.js';
6
6
  import { applyNetworkProxy } from '../network/proxy.js';
7
- const DEFAULT_CONTEXT_WINDOW = 128_000;
7
+ const DEFAULT_CONTEXT_WINDOW = 1_000_000;
8
8
  function gatewayFallbackReason(model, error) {
9
9
  const state = model?.availability?.state;
10
10
  if (state === 'quota_exhausted' || state === 'concurrency_exceeded')
@@ -107,7 +107,7 @@ export interface ConfigPatch {
107
107
  };
108
108
  }
109
109
 
110
- const DEFAULT_CONTEXT_WINDOW = 128_000;
110
+ const DEFAULT_CONTEXT_WINDOW = 1_000_000;
111
111
 
112
112
  export interface ModelResolution {
113
113
  provider: Provider | null;
package/src/config.js CHANGED
@@ -11,13 +11,13 @@
11
11
  *
12
12
  * 可选的环境变量:
13
13
  * MINIMAL_AGENT_PROVIDER - 友好名称,默认 "env"
14
- * MINIMAL_AGENT_CONTEXT_WINDOW - 上下文窗口,默认 128000
14
+ * MINIMAL_AGENT_CONTEXT_WINDOW - 上下文窗口,默认 1000000
15
15
  * MINIMAL_AGENT_MAX_TOKENS - 单次输出 token 上限,默认 16384(弱 provider 默认偏小会截断长输出)
16
16
  * ============================================================
17
17
  */
18
18
  import { configService } from './config/configService.js';
19
19
  import { applyNetworkProxy } from './network/proxy.js';
20
- const DEFAULT_CONTEXT_WINDOW = 128_000;
20
+ const DEFAULT_CONTEXT_WINDOW = 1_000_000;
21
21
  /**
22
22
  * 单次输出 token 上限的默认值。
23
23
  *
package/src/config.ts CHANGED
@@ -11,7 +11,7 @@
11
11
  *
12
12
  * 可选的环境变量:
13
13
  * MINIMAL_AGENT_PROVIDER - 友好名称,默认 "env"
14
- * MINIMAL_AGENT_CONTEXT_WINDOW - 上下文窗口,默认 128000
14
+ * MINIMAL_AGENT_CONTEXT_WINDOW - 上下文窗口,默认 1000000
15
15
  * MINIMAL_AGENT_MAX_TOKENS - 单次输出 token 上限,默认 16384(弱 provider 默认偏小会截断长输出)
16
16
  * ============================================================
17
17
  */
@@ -20,7 +20,7 @@ import { configService } from './config/configService.js';
20
20
  import { applyNetworkProxy } from './network/proxy.js';
21
21
  import type { LocalProvider, Provider } from './types.js';
22
22
 
23
- const DEFAULT_CONTEXT_WINDOW = 128_000;
23
+ const DEFAULT_CONTEXT_WINDOW = 1_000_000;
24
24
 
25
25
  /**
26
26
  * 单次输出 token 上限的默认值。
@@ -20,7 +20,9 @@ export function buildContextBudgetPlan(input) {
20
20
  overBudget: totalInputTokens > inputLimit,
21
21
  };
22
22
  }
23
- const AUXILIARY_REMOVAL_ORDER = ['Advisor', 'Agent'];
23
+ // Agent first (largest schema); the advisor goes last because it is cheap and is the
24
+ // capability that matters most when the request is already under pressure.
25
+ const AUXILIARY_REMOVAL_ORDER = ['Agent', 'Advisor'];
24
26
  /**
25
27
  * Last-resort schema reduction. Normal requests keep the full catalog; this is
26
28
  * used only after history compaction still cannot fit the provider window.
@@ -47,7 +47,9 @@ export interface EmergencyToolFit {
47
47
  plan: ContextBudgetPlan;
48
48
  }
49
49
 
50
- const AUXILIARY_REMOVAL_ORDER = ['Advisor', 'Agent'];
50
+ // Agent first (largest schema); the advisor goes last because it is cheap and is the
51
+ // capability that matters most when the request is already under pressure.
52
+ const AUXILIARY_REMOVAL_ORDER = ['Agent', 'Advisor'];
51
53
 
52
54
  /**
53
55
  * Last-resort schema reduction. Normal requests keep the full catalog; this is
@@ -32,6 +32,7 @@
32
32
  import { createHash, randomUUID } from 'node:crypto';
33
33
  import { countTextTokens } from './tokenCounter.js';
34
34
  import { clearToolResultArchive } from './toolResultArchive.js';
35
+ import { safeSlice } from '../utils/safeText.js';
35
36
  // ==================== 配置常量 ====================
36
37
  /** 同一内容最多原样保留多少次,之后用压缩引用替代 */
37
38
  const MAX_REPEAT_COUNT = 3;
@@ -344,7 +345,7 @@ export function getToolResultPolicy(toolName) {
344
345
  }
345
346
  function truncateContent(content) {
346
347
  const omitted = content.length - HEAD_KEEP_CHARS - TAIL_KEEP_CHARS;
347
- return (content.slice(0, HEAD_KEEP_CHARS) +
348
+ return (safeSlice(content, 0, HEAD_KEEP_CHARS) +
348
349
  `\n\n[... 省略了 ${omitted.toLocaleString()} 字符 ...]\n\n` +
349
- content.slice(-TAIL_KEEP_CHARS));
350
+ safeSlice(content, -TAIL_KEEP_CHARS));
350
351
  }
@@ -34,6 +34,7 @@ import { createHash, randomUUID } from 'node:crypto';
34
34
  import type { CacheEditsState, ToolResultPolicy } from '../types.js';
35
35
  import { countTextTokens } from './tokenCounter.js';
36
36
  import { clearToolResultArchive } from './toolResultArchive.js';
37
+ import { safeSlice } from '../utils/safeText.js';
37
38
 
38
39
  // ==================== 配置常量 ====================
39
40
 
@@ -460,8 +461,8 @@ function truncateContent(content: string): string {
460
461
  const omitted = content.length - HEAD_KEEP_CHARS - TAIL_KEEP_CHARS;
461
462
 
462
463
  return (
463
- content.slice(0, HEAD_KEEP_CHARS) +
464
+ safeSlice(content, 0, HEAD_KEEP_CHARS) +
464
465
  `\n\n[... 省略了 ${omitted.toLocaleString()} 字符 ...]\n\n` +
465
- content.slice(-TAIL_KEEP_CHARS)
466
+ safeSlice(content, -TAIL_KEEP_CHARS)
466
467
  );
467
468
  }
@@ -2,6 +2,7 @@ import { createHash, randomUUID } from 'node:crypto';
2
2
  import { mkdir, readdir, stat, unlink, writeFile, rename, rm } from 'node:fs/promises';
3
3
  import { homedir } from 'node:os';
4
4
  import { join } from 'node:path';
5
+ import { safeSlice } from '../utils/safeText.js';
5
6
  const MAX_ARCHIVE_RESULT_CHARS = 12_000;
6
7
  const MAX_SESSION_ARCHIVE_BYTES = 64 * 1024 * 1024;
7
8
  function agentHome() {
@@ -36,7 +37,7 @@ export async function archiveToolResult(content, sessionKey, toolName) {
36
37
  await unlink(finalPath);
37
38
  return { content, originalChars: content.length, degraded: 'session-limit' };
38
39
  }
39
- const preview = `${content.slice(0, 2_000)}\n\n` +
40
+ const preview = `${safeSlice(content, 0, 2_000)}\n\n` +
40
41
  `[工具结果已归档:${toolName},原文 ${content.length.toLocaleString()} 字符。` +
41
42
  `需要完整内容时,请使用 Read 读取:${finalPath}]`;
42
43
  return { content: preview, archiveRef: finalPath, originalChars: content.length };
@@ -2,6 +2,7 @@ import { createHash, randomUUID } from 'node:crypto';
2
2
  import { mkdir, readdir, stat, unlink, writeFile, rename, rm } from 'node:fs/promises';
3
3
  import { homedir } from 'node:os';
4
4
  import { join } from 'node:path';
5
+ import { safeSlice } from '../utils/safeText.js';
5
6
 
6
7
  const MAX_ARCHIVE_RESULT_CHARS = 12_000;
7
8
  const MAX_SESSION_ARCHIVE_BYTES = 64 * 1024 * 1024;
@@ -62,7 +63,7 @@ export async function archiveToolResult(
62
63
  return { content, originalChars: content.length, degraded: 'session-limit' };
63
64
  }
64
65
 
65
- const preview = `${content.slice(0, 2_000)}\n\n` +
66
+ const preview = `${safeSlice(content, 0, 2_000)}\n\n` +
66
67
  `[工具结果已归档:${toolName},原文 ${content.length.toLocaleString()} 字符。` +
67
68
  `需要完整内容时,请使用 Read 读取:${finalPath}]`;
68
69
  return { content: preview, archiveRef: finalPath, originalChars: content.length };
package/src/llm/client.js CHANGED
@@ -195,10 +195,29 @@ function sleep(ms, signal) {
195
195
  signal?.addEventListener('abort', onAbort, { once: true });
196
196
  });
197
197
  }
198
+ /**
199
+ * 从 provider 的错误正文里挑出最关键的 `code`。
200
+ *
201
+ * 真实事故:OpenAI 对请求体里的孤立代理项/非法 JSON 参数回 400,正文
202
+ * `{"error":{"message":"Invalid body: failed to parse JSON value…","code":"invalid_json"}}`
203
+ * 很长,`body.slice(0, 500)` 恰好把 code 截掉 —— 界面上只剩半句 "Invalid body:…",
204
+ * 看不出这是序列化问题而不是模型/额度问题。标题里带上 code,正文仍只留 500 字。
205
+ */
206
+ export function providerErrorCode(body) {
207
+ try {
208
+ const parsed = JSON.parse(body);
209
+ const code = parsed?.error?.code ?? parsed?.error?.type;
210
+ return typeof code === 'string' && code.trim() ? code.trim() : undefined;
211
+ }
212
+ catch {
213
+ return undefined;
214
+ }
215
+ }
198
216
  /** 构造带诊断的 Error;401/403 走专属文案,避免"重试 5 次才发现是 key 失效"。 */
199
217
  function buildChatError(resp, body) {
200
218
  const status = resp.status;
201
- const head = `[${status} ${resp.statusText}]`;
219
+ const code = providerErrorCode(body);
220
+ const head = `[${status} ${resp.statusText}]${code ? ` ${code}` : ''}`;
202
221
  if (isClientAuthError(status)) {
203
222
  return new Error(`LLM 鉴权失败 ${head}:API key 可能失效、过期或无权访问 model "${resp.url.split('/').pop()}".\n` +
204
223
  `请检查 .env / ~/.minimal-agent/config.json 的模型配置。\n` +
package/src/llm/client.ts CHANGED
@@ -241,10 +241,29 @@ function sleep(ms: number, signal?: AbortSignal): Promise<void> {
241
241
  });
242
242
  }
243
243
 
244
+ /**
245
+ * 从 provider 的错误正文里挑出最关键的 `code`。
246
+ *
247
+ * 真实事故:OpenAI 对请求体里的孤立代理项/非法 JSON 参数回 400,正文
248
+ * `{"error":{"message":"Invalid body: failed to parse JSON value…","code":"invalid_json"}}`
249
+ * 很长,`body.slice(0, 500)` 恰好把 code 截掉 —— 界面上只剩半句 "Invalid body:…",
250
+ * 看不出这是序列化问题而不是模型/额度问题。标题里带上 code,正文仍只留 500 字。
251
+ */
252
+ export function providerErrorCode(body: string): string | undefined {
253
+ try {
254
+ const parsed = JSON.parse(body) as { error?: { code?: unknown; type?: unknown } };
255
+ const code = parsed?.error?.code ?? parsed?.error?.type;
256
+ return typeof code === 'string' && code.trim() ? code.trim() : undefined;
257
+ } catch {
258
+ return undefined;
259
+ }
260
+ }
261
+
244
262
  /** 构造带诊断的 Error;401/403 走专属文案,避免"重试 5 次才发现是 key 失效"。 */
245
263
  function buildChatError(resp: Response, body: string): Error {
246
264
  const status = resp.status;
247
- const head = `[${status} ${resp.statusText}]`;
265
+ const code = providerErrorCode(body);
266
+ const head = `[${status} ${resp.statusText}]${code ? ` ${code}` : ''}`;
248
267
  if (isClientAuthError(status)) {
249
268
  return new Error(
250
269
  `LLM 鉴权失败 ${head}:API key 可能失效、过期或无权访问 model "${resp.url.split('/').pop()}".\n` +
@@ -13,6 +13,73 @@ export function provenanceLabel(provenance, currentGroupId) {
13
13
  ].filter(Boolean);
14
14
  return `[${fields.join(';')}]`;
15
15
  }
16
+ /** 孤立(不成对)的 UTF-16 代理项:`\uD800`–`\uDBFF` 后面没有低位,或低位前面没有高位。 */
17
+ const UNPAIRED_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g;
18
+ /**
19
+ * 把不成对的 UTF-16 代理项替换成 U+FFFD。
20
+ *
21
+ * 真实事故:工具结果按定长截断时会把一个 emoji 的代理对劈成两半,`JSON.stringify`
22
+ * 写出的是 `"\ud83c"` —— 语法合法但**不是合法 Unicode**。OpenAI(Responses/Chat)
23
+ * 的 body 解析直接回 400 `invalid_json`("Invalid body: failed to parse JSON
24
+ * value…"),而且坏内容一旦进了 history,此后每一轮请求都发不出去,界面上只剩
25
+ * 「生成未完成」。截断点分散在十几个工具里,出站前统一修好才不会再犯。
26
+ */
27
+ export function sanitizeUnpairedSurrogates(text) {
28
+ return text.replace(UNPAIRED_SURROGATE, '\uFFFD');
29
+ }
30
+ /** 深拷贝一份出站副本,同时修好所有字符串里的孤立代理项(入参原样不动)。 */
31
+ function sanitizeStringsDeep(value) {
32
+ if (typeof value === 'string')
33
+ return sanitizeUnpairedSurrogates(value);
34
+ if (Array.isArray(value))
35
+ return value.map((item) => sanitizeStringsDeep(item));
36
+ if (value && typeof value === 'object') {
37
+ const copy = {};
38
+ for (const [key, item] of Object.entries(value)) {
39
+ copy[key] = sanitizeStringsDeep(item);
40
+ }
41
+ return copy;
42
+ }
43
+ return value;
44
+ }
45
+ function isParseableJson(text) {
46
+ try {
47
+ JSON.parse(text);
48
+ return true;
49
+ }
50
+ catch {
51
+ return false;
52
+ }
53
+ }
54
+ /**
55
+ * `tool_calls[].function.arguments` 在协议里必须是**合法 JSON 字符串**。
56
+ *
57
+ * 真实事故:流式响应中途被截断时,半个 `arguments` 会以非法 JSON 落进 history,
58
+ * provider 的 body 校验直接判整包 `invalid_json`,此后每一轮都发不出去 —— 与
59
+ * 孤立代理项是同一句报错的两条入口。出站副本里把不可解析/类型不对的参数收敛成
60
+ * `{}`:保住 assistant 调用与 tool 结果的配对(删调用会留下孤儿 tool 消息),
61
+ * 代价只是这一次调用的参数看起来是空的。
62
+ */
63
+ function repairToolCallArguments(message) {
64
+ const calls = message.tool_calls;
65
+ if (!Array.isArray(calls) || calls.length === 0)
66
+ return message;
67
+ let repaired = false;
68
+ const next = calls.map((call) => {
69
+ const fn = call?.function;
70
+ if (!fn || typeof fn !== 'object')
71
+ return call;
72
+ const args = fn.arguments;
73
+ if (typeof args === 'string' && isParseableJson(args))
74
+ return call;
75
+ repaired = true;
76
+ const normalized = typeof args === 'object' && args !== null
77
+ ? JSON.stringify(args)
78
+ : '{}';
79
+ return { ...call, function: { ...fn, arguments: normalized } };
80
+ });
81
+ return repaired ? { ...message, tool_calls: next } : message;
82
+ }
16
83
  function decorateContent(content, provenance, currentGroupId) {
17
84
  if (!provenance || content === null)
18
85
  return content;
@@ -59,5 +126,9 @@ export function prepareMessagesForProvider(messages, conversationMode = 'private
59
126
  };
60
127
  }
61
128
  return rest;
62
- });
129
+ })
130
+ // 最后一关:任何历史(工具结果、用户粘贴、上游截断)都可能带孤立代理项或
131
+ // 被截断的 tool_calls 参数,出站副本统一修好,别让一条坏消息把之后每一轮
132
+ // 请求都打成 400。
133
+ .map((message) => repairToolCallArguments(sanitizeStringsDeep(message)));
63
134
  }
@@ -16,6 +16,73 @@ export function provenanceLabel(provenance: ConversationProvenance, currentGroup
16
16
  return `[${fields.join(';')}]`;
17
17
  }
18
18
 
19
+ /** 孤立(不成对)的 UTF-16 代理项:`\uD800`–`\uDBFF` 后面没有低位,或低位前面没有高位。 */
20
+ const UNPAIRED_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g;
21
+
22
+ /**
23
+ * 把不成对的 UTF-16 代理项替换成 U+FFFD。
24
+ *
25
+ * 真实事故:工具结果按定长截断时会把一个 emoji 的代理对劈成两半,`JSON.stringify`
26
+ * 写出的是 `"\ud83c"` —— 语法合法但**不是合法 Unicode**。OpenAI(Responses/Chat)
27
+ * 的 body 解析直接回 400 `invalid_json`("Invalid body: failed to parse JSON
28
+ * value…"),而且坏内容一旦进了 history,此后每一轮请求都发不出去,界面上只剩
29
+ * 「生成未完成」。截断点分散在十几个工具里,出站前统一修好才不会再犯。
30
+ */
31
+ export function sanitizeUnpairedSurrogates(text: string): string {
32
+ return text.replace(UNPAIRED_SURROGATE, '\uFFFD');
33
+ }
34
+
35
+ /** 深拷贝一份出站副本,同时修好所有字符串里的孤立代理项(入参原样不动)。 */
36
+ function sanitizeStringsDeep<T>(value: T): T {
37
+ if (typeof value === 'string') return sanitizeUnpairedSurrogates(value) as T;
38
+ if (Array.isArray(value)) return value.map((item) => sanitizeStringsDeep(item)) as T;
39
+ if (value && typeof value === 'object') {
40
+ const copy: Record<string, unknown> = {};
41
+ for (const [key, item] of Object.entries(value as Record<string, unknown>)) {
42
+ copy[key] = sanitizeStringsDeep(item);
43
+ }
44
+ return copy as T;
45
+ }
46
+ return value;
47
+ }
48
+
49
+ function isParseableJson(text: string): boolean {
50
+ try {
51
+ JSON.parse(text);
52
+ return true;
53
+ } catch {
54
+ return false;
55
+ }
56
+ }
57
+
58
+ /**
59
+ * `tool_calls[].function.arguments` 在协议里必须是**合法 JSON 字符串**。
60
+ *
61
+ * 真实事故:流式响应中途被截断时,半个 `arguments` 会以非法 JSON 落进 history,
62
+ * provider 的 body 校验直接判整包 `invalid_json`,此后每一轮都发不出去 —— 与
63
+ * 孤立代理项是同一句报错的两条入口。出站副本里把不可解析/类型不对的参数收敛成
64
+ * `{}`:保住 assistant 调用与 tool 结果的配对(删调用会留下孤儿 tool 消息),
65
+ * 代价只是这一次调用的参数看起来是空的。
66
+ */
67
+ function repairToolCallArguments<T extends Message>(message: T): T {
68
+ const calls = (message as { tool_calls?: unknown }).tool_calls;
69
+ if (!Array.isArray(calls) || calls.length === 0) return message;
70
+ let repaired = false;
71
+ const next = calls.map((call) => {
72
+ const fn = (call as { function?: unknown } | null)?.function;
73
+ if (!fn || typeof fn !== 'object') return call;
74
+ const args = (fn as { arguments?: unknown }).arguments;
75
+ if (typeof args === 'string' && isParseableJson(args)) return call;
76
+ repaired = true;
77
+ const normalized =
78
+ typeof args === 'object' && args !== null
79
+ ? JSON.stringify(args)
80
+ : '{}';
81
+ return { ...(call as object), function: { ...(fn as object), arguments: normalized } };
82
+ });
83
+ return repaired ? ({ ...message, tool_calls: next } as T) : message;
84
+ }
85
+
19
86
  function decorateContent(
20
87
  content: string | ChatContentPart[] | null,
21
88
  provenance: ConversationProvenance | undefined,
@@ -71,5 +138,9 @@ export function prepareMessagesForProvider(
71
138
  } as Message;
72
139
  }
73
140
  return rest as Message;
74
- });
141
+ })
142
+ // 最后一关:任何历史(工具结果、用户粘贴、上游截断)都可能带孤立代理项或
143
+ // 被截断的 tool_calls 参数,出站副本统一修好,别让一条坏消息把之后每一轮
144
+ // 请求都打成 400。
145
+ .map((message) => repairToolCallArguments(sanitizeStringsDeep(message)));
75
146
  }
@@ -1,3 +1,4 @@
1
+ import { recordExecutedCall } from '../tools/agent/executedCalls.js';
1
2
  import { dirname, resolve } from 'node:path';
2
3
  import { countTextTokens } from '../context/tokenCounter.js';
3
4
  import { loadProjectPromptInstructions } from '../prompts/projectInstructions.js';
@@ -12,6 +13,10 @@ import { advisorSemanticsFor } from './toolSemantics.js';
12
13
  export function createToolExecutor(input) {
13
14
  const { options, runtimeContext, toolCallContext, readBudgets, currentEffectiveToolSet, advisorNudge, stallGuard, modelEnvironmentCwd, observedRuleScopes, pendingRuleScopes, currentUserMessageId, executeToolFn, } = input;
14
15
  const { signal, sessionState } = options;
16
+ // 有会话状态就挂在上面(跨回合存活);否则挂在本次运行的调用上下文上(子任务等)。
17
+ const executedLedger = sessionState
18
+ ? (sessionState.executedCalls ??= new Map())
19
+ : (toolCallContext.executedCalls ??= new Map());
15
20
  // Convert tool execution failures/aborts into results; host hook failures are
16
21
  // not a successful tool outcome and may propagate to the batch boundary.
17
22
  const failureReviews = [];
@@ -224,8 +229,10 @@ export function createToolExecutor(input) {
224
229
  delegationTools: currentEffectiveToolSet.tools,
225
230
  cwd: sessionState?.activeWorktree?.path ?? toolCallContext.cwd,
226
231
  toolCallId: tc.id,
232
+ executedCalls: executedLedger,
227
233
  reportProgress,
228
234
  });
235
+ recordExecutedCall(executedLedger, tc.id, tc.function.name);
229
236
  }
230
237
  finally {
231
238
  releaseWorkspace?.();