Skip to content

Commit b75cfab

Browse files
author
linyuan.yang
committed
tool 结果截断
1 parent cd3ec26 commit b75cfab

3 files changed

Lines changed: 133 additions & 2 deletions

File tree

‎packages/sbot/src/Agent/AgentFactory.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import {
55
IAgentSaverService, AgentMemorySaver, ILoggerService,
66
ConversationCompactor, IConversationCompactor, T_SummaryModelService,
77
T_CompactPromptTemplate, T_PostCompactMessageTemplate, T_PostCompactContinuation,
8+
T_ToolOverflowDir,
89
} from "scorpio.ai";
910
import {
1011
IAgentToolService, AgentToolService,
@@ -213,6 +214,7 @@ export class AgentFactory {
213214
container.registerWithArgs(SingleAgentService, {
214215
[IModelService]: await config.getModelService(entry.model, true),
215216
[T_StaticSystemPrompts]: systemPrompts,
217+
[T_ToolOverflowDir]: config.getConfigPath("tool-overflow", true),
216218
...(entry.modelCallTimeout != null && { [T_ModelCallTimeout]: entry.modelCallTimeout * 1000 }),
217219
});
218220
return container.resolve(SingleAgentService);

‎packages/scorpio.ai/src/Agents/Single/SingleAgentService.ts‎

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { StateGraph, START, END } from '../../Graph';
22
import { type StructuredToolInterface } from "@langchain/core/tools";
3-
import { inject, T_StaticSystemPrompts, T_DynamicSystemPrompts, T_ModelCallTimeout, truncate } from "../../Core";
3+
import { inject, T_StaticSystemPrompts, T_DynamicSystemPrompts, T_ModelCallTimeout, T_ToolOverflowDir, truncate } from "../../Core";
44
import { IModelService } from "../../Model";
55
import { ISkillService } from "../../Skills";
66
import { IInsightService } from "../../Insight";
@@ -12,7 +12,7 @@ import { IAgentSaverService } from "../../Saver";
1212
import { ConversationCompactor, IConversationCompactor, METADATA_KEY_INPUT_TOKENS } from "../../Saver/ConversationCompactor";
1313
import { IAgentToolService } from "../../AgentTool";
1414
import { ILoggerService } from "../../Logger";
15-
import { normalizeToMCPResult, MCPContentType, type MCPToolResult } from '../../Tools';
15+
import { normalizeToMCPResult, truncateMCPToolResult, MCPContentType, type MCPToolResult } from '../../Tools';
1616
import { AgentServiceBase, GraphNodeType, ToolApproval, IAgentCallback, AgentCancelledError, DEFAULT_MAX_HISTORY_TOKENS, ChatMessage, MessageRole, type TokenUsage } from "../AgentServiceBase";
1717
import type { MessageContent } from "../../Saver/IAgentSaverService";
1818
import { contentToString, truncateForLog } from "../../Utils/contentUtils";
@@ -63,6 +63,7 @@ export class SingleAgentService extends AgentServiceBase {
6363
protected dynamicSystemPrompts: string[];
6464
protected modelCallTimeout?: number;
6565
protected compactor?: ConversationCompactor;
66+
protected toolOverflowDir?: string;
6667

6768
constructor(
6869
@inject(IModelService) modelService: IModelService,
@@ -78,6 +79,7 @@ export class SingleAgentService extends AgentServiceBase {
7879
@inject(IWikiService, { optional: true }) wikiServices?: IWikiService[],
7980
@inject(T_ModelCallTimeout, { optional: true }) modelCallTimeout?: number,
8081
@inject(IConversationCompactor, { optional: true }) compactor?: ConversationCompactor,
82+
@inject(T_ToolOverflowDir, { optional: true }) toolOverflowDir?: string,
8183
) {
8284
super(loggerService, agentSaver, noteServices, wikiServices);
8385
this.modelService = modelService;
@@ -89,6 +91,7 @@ export class SingleAgentService extends AgentServiceBase {
8991
this.dynamicSystemPrompts = dynamicSystemPrompts ?? [];
9092
this.modelCallTimeout = modelCallTimeout;
9193
this.compactor = compactor;
94+
this.toolOverflowDir = toolOverflowDir;
9295
}
9396

9497
override addStaticSystemPrompts(prompts: string[]): void {
@@ -295,6 +298,21 @@ export class SingleAgentService extends AgentServiceBase {
295298

296299
// 标准化为 MCP 格式(自动检测和转换各种格式)
297300
let mcpResult = normalizeToMCPResult(result);
301+
302+
// 单条 result 过大时 head+tail 截断 + 溢出落盘,防止 token 一下被打爆。
303+
// 失败降级为不带路径的截断;spillDir 未注入则跳过整个步骤。
304+
if (this.toolOverflowDir) {
305+
try {
306+
mcpResult = await truncateMCPToolResult(mcpResult, {
307+
spillDir: this.toolOverflowDir,
308+
toolCallId: toolCall.id ?? `noid-${Date.now()}-${i}`,
309+
toolName: tool.name,
310+
});
311+
} catch (err: any) {
312+
this.logger?.warn(`工具结果截断失败 ${tool.name}: ${err?.message ?? err}`);
313+
}
314+
}
315+
298316
const resultStr = JSON.stringify(mcpResult);
299317
this.logger?.info(`执行工具结束 ${tool.name} 结果: ${truncate(resultStr, 300)}`);
300318

Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
import * as fs from 'fs/promises';
2+
import * as path from 'path';
3+
import { MCPContentType, type MCPContent, type MCPToolResult } from './types';
4+
5+
const MAX_BYTES = 32 * 1024;
6+
7+
export interface TruncateToolResultOptions {
8+
spillDir: string;
9+
toolCallId: string;
10+
toolName: string;
11+
}
12+
13+
/**
14+
* 对单条 tool result 中的文本块做 head+tail 截断;超限部分整段写入 spillDir
15+
* 下的临时文件,截断标记中带上文件绝对路径,便于人工/工具回查。
16+
*
17+
* - 仅处理 MCPContentType.Text 块;image/audio/document 块原样保留
18+
* - 单个 text 块字节数 ≤ MAX_BYTES 时不动
19+
* - 落盘失败时降级为不带路径的截断,保证主链路不中断
20+
*/
21+
export async function truncateMCPToolResult(
22+
result: MCPToolResult,
23+
opts: TruncateToolResultOptions,
24+
): Promise<MCPToolResult> {
25+
let touched = false;
26+
const newContent: MCPContent[] = [];
27+
let textBlockIdx = 0;
28+
29+
for (const block of result.content) {
30+
if (block.type !== MCPContentType.Text) {
31+
newContent.push(block);
32+
continue;
33+
}
34+
// 防御:normalizeToMCPResult 在某些边界(比如 tool 返回 undefined)会把 text 写成非 string;
35+
// Buffer.byteLength(undefined) 会抛 TypeError,这里直接跳过让外层逻辑去处理即可。
36+
if (typeof block.text !== 'string') {
37+
newContent.push(block);
38+
textBlockIdx++;
39+
continue;
40+
}
41+
const fullText = block.text;
42+
const fullLen = Buffer.byteLength(fullText, 'utf8');
43+
if (fullLen <= MAX_BYTES) {
44+
newContent.push(block);
45+
textBlockIdx++;
46+
continue;
47+
}
48+
49+
const filename = `${sanitizeName(opts.toolName)}-${sanitizeName(opts.toolCallId)}-${textBlockIdx}.txt`;
50+
const filePath = path.join(opts.spillDir, filename);
51+
let spillNote: string;
52+
try {
53+
await fs.writeFile(filePath, fullText, 'utf8');
54+
spillNote = `full output saved to ${filePath}`;
55+
} catch (err: any) {
56+
spillNote = `spill failed: ${err?.message ?? err}`;
57+
}
58+
59+
newContent.push({
60+
type: MCPContentType.Text,
61+
text: headTailWithMarker(fullText, fullLen, MAX_BYTES, spillNote),
62+
});
63+
touched = true;
64+
textBlockIdx++;
65+
}
66+
67+
if (!touched) return result;
68+
return { ...result, content: newContent };
69+
}
70+
71+
function headTailWithMarker(text: string, fullLen: number, maxBytes: number, note: string): string {
72+
// 上界估算:所有数字都用 fullLen 占位,实际 marker 一定 ≤ 这个长度(其他三个数都 ≤ fullLen)
73+
const markerEstimate = `\n\n…[truncated: bytes ${fullLen}..${fullLen} of ${fullLen} omitted (${fullLen} bytes); ${note}]…\n\n`;
74+
const markerLen = Buffer.byteLength(markerEstimate, 'utf8');
75+
const budget = Math.max(0, maxBytes - markerLen);
76+
const headBudget = Math.floor(budget / 2);
77+
const tailBudget = budget - headBudget;
78+
79+
const head = takeBytesFromStart(text, headBudget);
80+
const tail = takeBytesFromEnd(text, tailBudget);
81+
const headBytes = Buffer.byteLength(head, 'utf8');
82+
const tailBytes = Buffer.byteLength(tail, 'utf8');
83+
const omitted = fullLen - headBytes - tailBytes;
84+
const tailStart = fullLen - tailBytes;
85+
// 暴露字节区间,方便有 read_file 工具的 LLM 直接 offset=headBytes、limit=omitted 精准捞缺失部分
86+
const marker = `\n\n…[truncated: bytes ${headBytes}..${tailStart} of ${fullLen} omitted (${omitted} bytes); ${note}]…\n\n`;
87+
return head + marker + tail;
88+
}
89+
90+
// 按字节截取并对齐到 UTF-8 字符边界(避免出现半截多字节字符)
91+
function takeBytesFromStart(text: string, maxBytes: number): string {
92+
if (maxBytes <= 0) return '';
93+
const buf = Buffer.from(text, 'utf8');
94+
if (buf.length <= maxBytes) return text;
95+
let end = maxBytes;
96+
while (end > 0 && (buf[end] & 0xC0) === 0x80) end--;
97+
return buf.slice(0, end).toString('utf8');
98+
}
99+
100+
function takeBytesFromEnd(text: string, maxBytes: number): string {
101+
if (maxBytes <= 0) return '';
102+
const buf = Buffer.from(text, 'utf8');
103+
if (buf.length <= maxBytes) return text;
104+
let start = buf.length - maxBytes;
105+
while (start < buf.length && (buf[start] & 0xC0) === 0x80) start++;
106+
return buf.slice(start).toString('utf8');
107+
}
108+
109+
function sanitizeName(s: string): string {
110+
return (s || 'unknown').replace(/[^a-zA-Z0-9._-]/g, '_').slice(0, 64);
111+
}

0 commit comments

Comments
 (0)