Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 54 additions & 2 deletions src/agent/toolOutputBudget.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,14 @@ import {
withToolOutputBudget,
} from './toolOutputBudget';

function textTool(name: string, text: string): ToolDefinition {
function textTool(name: string, text: string, details: unknown = { kept: true }): ToolDefinition {
return {
name,
label: name,
description: name,
parameters: { type: 'object', properties: {} } as ToolDefinition['parameters'],
async execute() {
return { content: [{ type: 'text' as const, text }], details: { kept: true } };
return { content: [{ type: 'text' as const, text }], details };
},
};
}
Expand Down Expand Up @@ -172,6 +172,58 @@ describe('ToolOutputBudget', () => {
expect(store.read(details.reference ?? '')).toBe(body);
});

// pi 超限时只保留尾部,正文开头已是原输出的中段;再切「头」就是把中段当开头给模型看
it('pi 已截断时不给假头,预算全给尾巴', async () => {
const store = budget(1024);
const body = [
'HEAD_MARKER prepared workspace',
...Array.from({ length: 4000 }, (_, i) => `plain run line ${i}`),
'ERROR: 3 tests failed',
].join('\n');
const wrapped = withToolOutputBudget(
textTool('bash', body, { truncation: { truncated: true, totalLines: 9000 } }),
store
);
const result = await wrapped.execute(
'call-11',
{ command: 'pnpm test' },
undefined,
undefined,
undefined as never
);
const part = result.content[0];
if (part?.type !== 'text') throw new Error('expected text');
expect(part.text).not.toContain('HEAD_MARKER');
expect(part.text.startsWith('… [')).toBe(true);
expect(part.text).toContain('ERROR: 3 tests failed');
expect(part.text).toContain('bytes omitted');
expect((result.details as { excerpted?: boolean }).excerpted).toBe(true);
});

it('pi 未截断时保留真头', async () => {
const store = budget(1024);
const body = [
'HEAD_MARKER prepared workspace',
...Array.from({ length: 4000 }, (_, i) => `plain run line ${i}`),
'ERROR: 3 tests failed',
].join('\n');
const wrapped = withToolOutputBudget(
textTool('bash', body, { truncation: { truncated: false } }),
store
);
const result = await wrapped.execute(
'call-12',
{ command: 'pnpm build' },
undefined,
undefined,
undefined as never
);
const part = result.content[0];
if (part?.type !== 'text') throw new Error('expected text');
expect(part.text).toContain('HEAD_MARKER');
expect(part.text).toContain('ERROR: 3 tests failed');
});

it('bash 输出超字节预算但摘录装得下时不落盘', async () => {
const store = budget(16);
const body = 'abcdefghij'.repeat(8);
Expand Down
23 changes: 21 additions & 2 deletions src/agent/toolOutputBudget.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ const TOOL_INLINE_BYTES: Record<string, number> = {
* 超限时保留头尾摘录、而不是整段换成回执的工具(流式长输出只放 bash)。
* 整段外置会让「输出啰嗦」的收益归零,模型于是把过滤搬到命令行里(`| tail -12`、`> log 2>&1`),
* 而这些管道与重定向恰好会掐死 UI 滚动和任务日志的增量流;留一段可读的头尾,它就没有在源头截流的动机。
* pi 已经做过「只留尾部」的截断时不再切头(见 truncatedByPi)。
* 数值是摘录的 UTF-16 字符上限(excerpt 的切片单位)。
*/
const TOOL_EXCERPT_CHARS: Record<string, number> = {
Expand Down Expand Up @@ -169,14 +170,23 @@ function buildReceipt(

function excerptText(reference: string, shown: { text: string; omittedBytes: number }): string {
return [
shown.text,
// 纯尾摘录时 head 为空,excerpt 会以换行开头,去掉这个空行
shown.text.replace(/^\n+/, ''),
'',
`[Tool output kept as artifact ${reference}: ${shown.omittedBytes} bytes omitted from the middle.`,
`Search it with grep(path="${reference}", pattern), then read ranges with read(path="${reference}", offset, limit).`,
'The artifact URI works only with read/grep; do not pass it to bash or guess a filesystem path.]',
].join('\n');
}

/** pi 的 bash 在超过 2000 行 / 50KB 时只留尾部,此时正文开头已是原输出的中段 */
function truncatedByPi(details: unknown): boolean {
if (!details || typeof details !== 'object') return false;
const truncation = (details as { truncation?: unknown }).truncation;
if (!truncation || typeof truncation !== 'object') return false;
return (truncation as { truncated?: unknown }).truncated === true;
}

export class ToolOutputBudget {
readonly rootDir: string;
readonly maxInlineBytes: number;
Expand Down Expand Up @@ -267,7 +277,16 @@ export function withToolOutputBudget(
if (!text || originalBytes <= Math.max(inlineBytes, budget.maxInlineBytes)) return result;
const media = result.content.filter((part) => part.type !== 'text');
const excerptChars = TOOL_EXCERPT_CHARS[definition.name];
const shown = excerptChars === undefined ? undefined : excerpt(text.trimEnd(), excerptChars);
const shown =
excerptChars === undefined
? undefined
: excerpt(
text.trimEnd(),
excerptChars,
// 截过头就别再切「头」:那一段是原输出的中段,当开头展示等于骗模型;
// 把预算全给尾巴,真正的开头在 pi 提示里给的临时日志路径,按需 read 即可。
truncatedByPi(result.details) ? { head: '' } : {}
);
// 摘录装得下就不落盘:正文本身已经能一次读完
if (shown && shown.omittedBytes === 0) return result;
try {
Expand Down