Skip to content

Commit 8b7d685

Browse files
authored
fix(agents): preserve oversized Bash final-line output (#133216)
Keep newline-terminated final output visible through the canonical UTF-8 tail truncator and retain completed-line byte sizes for diagnostics. Preserve full spill text and process exit behavior. Refs #133213.
1 parent eb06db6 commit 8b7d685

3 files changed

Lines changed: 146 additions & 53 deletions

File tree

‎src/agents/sessions/tools/bash.test.ts‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { readFile, rm } from "node:fs/promises";
12
import path from "node:path";
23
// Bash tool helper tests cover conversion from model-facing timeout seconds to
34
// timer-safe millisecond values.
@@ -60,6 +61,40 @@ describe("bash tool timeout helpers", () => {
6061
});
6162

6263
describe("bash tool output lifecycle", () => {
64+
it("reports a long final line's tail and size after its newline", async () => {
65+
const text = `${"x".repeat(250_000)}END-MARKER\n`;
66+
const operations: BashOperations = {
67+
exec: async (_command, _cwd, { onData }) => {
68+
onData(Buffer.from(text), "stdout");
69+
return { exitCode: 0 };
70+
},
71+
};
72+
const result = await createBashTool(process.cwd(), { operations }).execute("long-line", {
73+
command: "ignored",
74+
});
75+
const details = result.details;
76+
if (
77+
!details ||
78+
typeof details !== "object" ||
79+
!("fullOutputPath" in details) ||
80+
typeof details.fullOutputPath !== "string"
81+
) {
82+
throw new Error("Expected a full output path for truncated Bash output");
83+
}
84+
const fullOutputPath = details.fullOutputPath;
85+
try {
86+
expect(result.content[0]).toMatchObject({
87+
type: "text",
88+
text: expect.stringContaining(
89+
"END-MARKER\n\n[Showing last 50.0KB of line 1 (line is 244.2KB).",
90+
),
91+
});
92+
expect(await readFile(fullOutputPath, "utf8")).toBe(text);
93+
} finally {
94+
await rm(fullOutputPath, { force: true });
95+
}
96+
});
97+
6398
it.runIf(process.platform !== "win32").each(nativeBashSpillScenarios)(
6499
"settles real Bash output for %s",
65100
async (scenario) => {

‎src/agents/sessions/tools/output-accumulator.test.ts‎

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,95 @@ import { spawnNodeEvalSync } from "../../../test-utils/node-process.js";
77
import { OutputAccumulator } from "./output-accumulator.js";
88

99
describe("OutputAccumulator", () => {
10+
it.each([
11+
{
12+
name: "terminated final line",
13+
chunks: ["a".repeat(40), Buffer.from([0xe7, 0x95]), Buffer.from([0x8c]), "\n"],
14+
maxBytes: 8,
15+
expected: "aaaaa界",
16+
lastLineBytes: 43,
17+
totalLines: 1,
18+
partial: true,
19+
},
20+
{
21+
name: "open final line",
22+
chunks: ["a".repeat(40), "界"],
23+
maxBytes: 8,
24+
expected: "aaaaa界",
25+
lastLineBytes: 43,
26+
totalLines: 1,
27+
partial: true,
28+
},
29+
{
30+
name: "complete following line",
31+
chunks: ["a".repeat(40) + "\n", "short\n"],
32+
maxBytes: 8,
33+
expected: "short",
34+
lastLineBytes: 5,
35+
totalLines: 2,
36+
partial: false,
37+
},
38+
{
39+
name: "small UTF-8 boundary",
40+
chunks: ["A".repeat(20) + "😀ab\nc\n"],
41+
maxBytes: 4,
42+
expected: "c",
43+
lastLineBytes: 1,
44+
totalLines: 2,
45+
partial: false,
46+
},
47+
])(
48+
"retains the canonical tail after rolling compaction: $name",
49+
async ({ chunks, maxBytes, expected, lastLineBytes, totalLines, partial }) => {
50+
const accumulator = new OutputAccumulator({
51+
maxBytes,
52+
tempFilePrefix: "openclaw-output-test",
53+
});
54+
const buffers = chunks.map((chunk) =>
55+
typeof chunk === "string" ? Buffer.from(chunk) : chunk,
56+
);
57+
const fullOutput = Buffer.concat(buffers).toString("utf8");
58+
for (const data of buffers) {
59+
accumulator.append(data, "stdout");
60+
}
61+
accumulator.finish();
62+
const snapshot = accumulator.snapshot({ persistIfTruncated: true });
63+
await accumulator.closeTempFile();
64+
try {
65+
expect(snapshot.content).toBe(expected);
66+
expect(snapshot.truncation).toMatchObject({
67+
truncated: true,
68+
truncatedBy: "bytes",
69+
totalBytes: Buffer.byteLength(fullOutput),
70+
totalLines,
71+
outputBytes: Buffer.byteLength(expected),
72+
outputLines: 1,
73+
lastLinePartial: partial,
74+
});
75+
expect(accumulator.getLastLineBytes()).toBe(lastLineBytes);
76+
expect(await readFile(snapshot.fullOutputPath!, "utf8")).toBe(fullOutput);
77+
} finally {
78+
await rm(snapshot.fullOutputPath!, { force: true });
79+
}
80+
},
81+
);
82+
83+
it("counts completed line bytes until the next line starts", () => {
84+
const accumulator = new OutputAccumulator();
85+
for (const [text, lastLineBytes, totalLines] of [
86+
["ab界", 5, 1],
87+
["\n", 5, 1],
88+
["xy\n", 2, 2],
89+
["\n", 0, 3],
90+
["z", 1, 4],
91+
] as const) {
92+
accumulator.append(Buffer.from(text), "stdout");
93+
expect(accumulator.getLastLineBytes()).toBe(lastLineBytes);
94+
expect(accumulator.snapshot().truncation.totalLines).toBe(totalLines);
95+
}
96+
accumulator.finish();
97+
});
98+
1099
it("stores spilled full output in an owner-only temp file", async () => {
11100
const accumulator = new OutputAccumulator({
12101
maxBytes: 8,

‎src/agents/sessions/tools/output-accumulator.ts‎

Lines changed: 22 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
* Keeps bounded display tails in memory while spilling full output to private temp files when needed.
55
*/
66
import { finished } from "node:stream/promises";
7+
import { truncateUtf8Suffix } from "../../../utils/utf8-truncate.js";
78
import { createPrivateTempWriteStream } from "./private-temp-file.js";
89
import {
910
DEFAULT_MAX_BYTES,
@@ -60,12 +61,11 @@ export class OutputAccumulator {
6061
private spillChunks: Buffer[] = [];
6162
private tailText = "";
6263
private tailBytes = 0;
63-
private tailStartsAtLineBoundary = true;
6464
private totalRawBytes = 0;
6565
private totalDecodedBytes = 0;
6666
private completedLines = 0;
6767
private totalLines = 0;
68-
private currentLineBytes = 0;
68+
private lastLineBytes = 0;
6969
private hasOpenLine = false;
7070
private finished = false;
7171

@@ -76,7 +76,9 @@ export class OutputAccumulator {
7676
constructor(options: OutputAccumulatorOptions = {}) {
7777
this.maxLines = options.maxLines ?? DEFAULT_MAX_LINES;
7878
this.maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
79-
this.maxRollingBytes = Math.max(this.maxBytes * 2, 1);
79+
// UTF-8 trimming can drop three bytes; truncateTail also ignores a final newline.
80+
// Keep enough extra bytes that an incomplete leading line cannot fit the display.
81+
this.maxRollingBytes = Math.max(this.maxBytes * 2, this.maxBytes + 5);
8082
this.tempFilePrefix = options.tempFilePrefix ?? "openclaw-output";
8183
this.createTextTransform = options.createTextTransform;
8284
}
@@ -142,7 +144,7 @@ export class OutputAccumulator {
142144
}
143145

144146
snapshot(options: { persistIfTruncated?: boolean } = {}): OutputSnapshot {
145-
const tailTruncation = truncateTail(this.getSnapshotText(), {
147+
const tailTruncation = truncateTail(this.tailText, {
146148
maxLines: this.maxLines,
147149
maxBytes: this.maxBytes,
148150
});
@@ -182,7 +184,7 @@ export class OutputAccumulator {
182184
}
183185

184186
getLastLineBytes(): number {
185-
return this.currentLineBytes;
187+
return this.lastLineBytes;
186188
}
187189

188190
private appendDecodedText(text: string): void {
@@ -195,56 +197,23 @@ export class OutputAccumulator {
195197
this.tailText += text;
196198
this.tailBytes += bytes;
197199
if (this.tailBytes > this.maxRollingBytes * 2) {
198-
this.trimTail();
199-
}
200-
201-
let newlines = 0;
202-
let lastNewline = -1;
203-
for (let i = text.indexOf("\n"); i !== -1; i = text.indexOf("\n", i + 1)) {
204-
newlines++;
205-
lastNewline = i;
206-
}
207-
if (newlines === 0) {
208-
this.currentLineBytes += bytes;
209-
this.hasOpenLine = true;
210-
} else {
211-
this.completedLines += newlines;
212-
const tail = text.slice(lastNewline + 1);
213-
this.currentLineBytes = byteLength(tail);
214-
this.hasOpenLine = tail.length > 0;
215-
}
216-
this.totalLines = this.completedLines + (this.hasOpenLine ? 1 : 0);
217-
}
218-
219-
private trimTail(): void {
220-
const buffer = Buffer.from(this.tailText, "utf-8");
221-
if (buffer.length <= this.maxRollingBytes) {
222-
this.tailBytes = buffer.length;
223-
return;
224-
}
225-
226-
let start = buffer.length - this.maxRollingBytes;
227-
while (start < buffer.length) {
228-
const byte = buffer.at(start);
229-
if (byte === undefined || (byte & 0xc0) !== 0x80) {
230-
break;
200+
this.tailText = truncateUtf8Suffix(this.tailText, this.maxRollingBytes);
201+
this.tailBytes = byteLength(this.tailText);
202+
}
203+
204+
// A terminator closes the last real line; its size still belongs in the footer.
205+
for (let start = 0; start < text.length;) {
206+
const newline = text.indexOf("\n", start);
207+
const end = newline === -1 ? text.length : newline;
208+
this.lastLineBytes =
209+
(this.hasOpenLine ? this.lastLineBytes : 0) + byteLength(text.slice(start, end));
210+
this.hasOpenLine = newline === -1;
211+
if (!this.hasOpenLine) {
212+
this.completedLines++;
231213
}
232-
start++;
233-
}
234-
235-
this.tailStartsAtLineBoundary =
236-
start === 0 ? this.tailStartsAtLineBoundary : buffer.at(start - 1) === 0x0a;
237-
this.tailText = buffer.subarray(start).toString("utf-8");
238-
this.tailBytes = byteLength(this.tailText);
239-
}
240-
241-
private getSnapshotText(): string {
242-
if (this.tailStartsAtLineBoundary) {
243-
return this.tailText;
214+
start = end + 1;
244215
}
245-
246-
const firstNewline = this.tailText.indexOf("\n");
247-
return firstNewline === -1 ? this.tailText : this.tailText.slice(firstNewline + 1);
216+
this.totalLines = this.completedLines + (this.hasOpenLine ? 1 : 0);
248217
}
249218

250219
private shouldUseTempFile(): boolean {

0 commit comments

Comments
 (0)