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.
- package/README.md +1 -1
- package/package.json +1 -1
- package/src/advisor/README.md +2 -0
- 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/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/taskEvidence.js +2 -1
- package/src/memory/taskEvidence.ts +2 -1
- package/src/prompts/delegation.js +2 -2
- package/src/prompts/delegation.ts +2 -2
- 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 +88 -11
- package/src/tools/advisor/advisor.ts +98 -11
- package/src/tools/agent/README.md +3 -0
- package/src/tools/agent/agent.js +8 -0
- package/src/tools/agent/agent.ts +8 -0
- package/src/tools/agent/agentHandoff.js +59 -6
- package/src/tools/agent/agentHandoff.ts +55 -6
- 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/types.ts +3 -1
- 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
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 # 可选:上下文窗口,默认
|
|
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.
|
|
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>",
|
package/src/advisor/README.md
CHANGED
|
@@ -67,6 +67,8 @@
|
|
|
67
67
|
|
|
68
68
|
每次咨询只尝试一次;不可用、失败、空答、超时都以 `ok:false` 回到主模型,由它自行继续,
|
|
69
69
|
不自动重试、不转成人工审批、不宣称获得验证。不设咨询配额。
|
|
70
|
+
唯一例外:服务商明确报「输入超出上下文窗口」时,缩小材料(先 85%、再 60%,报错带真实上限则以它为准)重建后重发,最多两次,
|
|
71
|
+
重发时不再带核实工具;限流、超时、网络错误仍只试一次。
|
|
70
72
|
|
|
71
73
|
回归入口:`bun test test/advisorNudge.test.ts test/loop.advisorNudge.test.ts test/deliveryReview.test.ts
|
|
72
74
|
test/advisorContextFidelity.test.ts test/advisor.test.ts`。
|
|
@@ -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: '
|
|
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,
|
|
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: '
|
|
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,
|
|
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 =
|
|
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 =
|
|
22
|
+
export const FALLBACK_CONTEXT_WINDOW = 1_000_000;
|
|
23
23
|
|
|
24
24
|
export interface ProviderPreset {
|
|
25
25
|
name: string;
|
package/src/config/configFile.js
CHANGED
|
@@ -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 =
|
|
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(
|
|
20
|
-
*
|
|
21
|
-
*
|
|
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
|
-
|
|
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');
|
package/src/config/configFile.ts
CHANGED
|
@@ -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 =
|
|
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(
|
|
172
|
-
*
|
|
173
|
-
*
|
|
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
|
-
|
|
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 =
|
|
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')
|
package/src/config.js
CHANGED
|
@@ -11,13 +11,13 @@
|
|
|
11
11
|
*
|
|
12
12
|
* 可选的环境变量:
|
|
13
13
|
* MINIMAL_AGENT_PROVIDER - 友好名称,默认 "env"
|
|
14
|
-
* MINIMAL_AGENT_CONTEXT_WINDOW - 上下文窗口,默认
|
|
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 =
|
|
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 - 上下文窗口,默认
|
|
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 =
|
|
23
|
+
const DEFAULT_CONTEXT_WINDOW = 1_000_000;
|
|
24
24
|
|
|
25
25
|
/**
|
|
26
26
|
* 单次输出 token 上限的默认值。
|
|
@@ -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
|
|
348
|
+
return (safeSlice(content, 0, HEAD_KEEP_CHARS) +
|
|
348
349
|
`\n\n[... 省略了 ${omitted.toLocaleString()} 字符 ...]\n\n` +
|
|
349
|
-
content
|
|
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
|
|
464
|
+
safeSlice(content, 0, HEAD_KEEP_CHARS) +
|
|
464
465
|
`\n\n[... 省略了 ${omitted.toLocaleString()} 字符 ...]\n\n` +
|
|
465
|
-
content
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
}
|
package/src/loop/toolExecutor.js
CHANGED
|
@@ -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?.();
|
package/src/loop/toolExecutor.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { recordExecutedCall, type ExecutedCalls } from '../tools/agent/executedCalls.js';
|
|
1
2
|
import { dirname, resolve } from 'node:path';
|
|
2
3
|
import type { AdvisorNudge } from '../advisor/advisorNudge.js';
|
|
3
4
|
import { countTextTokens } from '../context/tokenCounter.js';
|
|
@@ -53,6 +54,10 @@ export function createToolExecutor(input: ToolExecutorInput) {
|
|
|
53
54
|
executeToolFn,
|
|
54
55
|
} = input;
|
|
55
56
|
const { signal, sessionState } = options;
|
|
57
|
+
// 有会话状态就挂在上面(跨回合存活);否则挂在本次运行的调用上下文上(子任务等)。
|
|
58
|
+
const executedLedger: ExecutedCalls = sessionState
|
|
59
|
+
? (sessionState.executedCalls ??= new Map())
|
|
60
|
+
: (toolCallContext.executedCalls ??= new Map());
|
|
56
61
|
// Convert tool execution failures/aborts into results; host hook failures are
|
|
57
62
|
// not a successful tool outcome and may propagate to the batch boundary.
|
|
58
63
|
const failureReviews: StallObservation[] = [];
|
|
@@ -279,8 +284,10 @@ export function createToolExecutor(input: ToolExecutorInput) {
|
|
|
279
284
|
delegationTools: currentEffectiveToolSet.tools,
|
|
280
285
|
cwd: sessionState?.activeWorktree?.path ?? toolCallContext.cwd,
|
|
281
286
|
toolCallId: tc.id,
|
|
287
|
+
executedCalls: executedLedger,
|
|
282
288
|
reportProgress,
|
|
283
289
|
});
|
|
290
|
+
recordExecutedCall(executedLedger, tc.id, tc.function.name);
|
|
284
291
|
} finally {
|
|
285
292
|
releaseWorkspace?.();
|
|
286
293
|
}
|
|
@@ -2,6 +2,7 @@ import { createHash, randomUUID } from 'node:crypto';
|
|
|
2
2
|
import { open, readFile, readdir, stat, unlink } from 'node:fs/promises';
|
|
3
3
|
import { dirname, basename, join } from 'node:path';
|
|
4
4
|
import { agentStateDir } from '../context/agentHome.js';
|
|
5
|
+
import { safeSlice } from '../utils/safeText.js';
|
|
5
6
|
import { containsForbiddenSecret, sha256 } from './codec.js';
|
|
6
7
|
import { acquireFileLock, appendPrivateLine, atomicWriteFile, ensurePrivateDir, } from './fileStore.js';
|
|
7
8
|
import { memoryTerms } from './retrieval.js';
|
|
@@ -89,11 +90,10 @@ function workspaceJournalLockPath(workspaceId) {
|
|
|
89
90
|
return join(episodeRoot(), `.workspace-${validPart(workspaceId)}.journal`);
|
|
90
91
|
}
|
|
91
92
|
export function sanitizeEpisodeContent(content, maxChars = MAX_EPISODE_CHARS) {
|
|
92
|
-
const normalized = content
|
|
93
|
+
const normalized = safeSlice(content
|
|
93
94
|
.replace(/data:[^;\s]+;base64,[A-Za-z0-9+/=]{80,}/g, '[binary omitted]')
|
|
94
95
|
.replace(/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/gi, '[secret omitted]')
|
|
95
|
-
.trim()
|
|
96
|
-
.slice(0, maxChars);
|
|
96
|
+
.trim(), 0, maxChars);
|
|
97
97
|
if (!normalized || containsForbiddenSecret(normalized))
|
|
98
98
|
return null;
|
|
99
99
|
return normalized;
|
|
@@ -3,6 +3,7 @@ import { open, readFile, readdir, stat, unlink } from 'node:fs/promises';
|
|
|
3
3
|
import { dirname, basename, join } from 'node:path';
|
|
4
4
|
|
|
5
5
|
import { agentStateDir } from '../context/agentHome.js';
|
|
6
|
+
import { safeSlice } from '../utils/safeText.js';
|
|
6
7
|
import { containsForbiddenSecret, sha256 } from './codec.js';
|
|
7
8
|
import {
|
|
8
9
|
acquireFileLock,
|
|
@@ -145,14 +146,17 @@ function workspaceJournalLockPath(workspaceId: string): string {
|
|
|
145
146
|
}
|
|
146
147
|
|
|
147
148
|
export function sanitizeEpisodeContent(content: string, maxChars = MAX_EPISODE_CHARS): string | null {
|
|
148
|
-
const normalized =
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
149
|
+
const normalized = safeSlice(
|
|
150
|
+
content
|
|
151
|
+
.replace(/data:[^;\s]+;base64,[A-Za-z0-9+/=]{80,}/g, '[binary omitted]')
|
|
152
|
+
.replace(
|
|
153
|
+
/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/gi,
|
|
154
|
+
'[secret omitted]',
|
|
155
|
+
)
|
|
156
|
+
.trim(),
|
|
157
|
+
0,
|
|
158
|
+
maxChars,
|
|
159
|
+
);
|
|
156
160
|
if (!normalized || containsForbiddenSecret(normalized)) return null;
|
|
157
161
|
return normalized;
|
|
158
162
|
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { safeSlice } from '../utils/safeText.js';
|
|
1
2
|
/** Keep causal failures even when a long exploration follows them. */
|
|
2
3
|
export function selectTaskEvidence(items) {
|
|
3
4
|
const failures = items.filter(item => item.kind === 'failure');
|
|
@@ -14,5 +15,5 @@ export function taskExcerpt(text, limit = 2000) {
|
|
|
14
15
|
return text;
|
|
15
16
|
const marker = '\n[中段省略;不是完整记录]\n';
|
|
16
17
|
const head = Math.floor((limit - marker.length) / 2);
|
|
17
|
-
return text
|
|
18
|
+
return safeSlice(text, 0, head) + marker + safeSlice(text, -(limit - marker.length - head));
|
|
18
19
|
}
|