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
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,30 @@ describe("MESSAGES_SNAPSHOT keeps tool results next to their calls", () => {
);
});

it("moves a large batch of detached results without overflowing the call stack", () => {
const n = 150_000;
const callIds = Array.from({ length: n }, (_, i) => `c${i}`);
const results = callIds.map((id, i) => result(`t${i}`, id));
// Built directly: call("a1", ...callIds) would itself spread n arguments.
const issuer: Message = {
...call("a1"),
toolCalls: callIds.map((id) => ({
id,
type: "function",
function: { name: "lookup", arguments: "{}" },
})),
} as Message;
const history = [issuer, text("x"), ...results];

const repaired = keepToolResultsWithCalls(history);

expect(repaired).toHaveLength(history.length);
expect(repaired[0].id).toBe("a1");
expect(repaired[1].id).toBe("t0");
expect(repaired[n].id).toBe(`t${n - 1}`);
expect(repaired[n + 1].id).toBe("x");
});

it("leaves a result whose call is not in the history where it is", async () => {
const snapshot = [
text("u1", "user"),
Expand Down
6 changes: 5 additions & 1 deletion sdks/typescript/packages/client/src/apply/default.ts
Original file line number Diff line number Diff line change
Expand Up @@ -365,7 +365,11 @@ export function keepToolResultsWithCalls(messages: Message[]): Message[] {
break;
if (role === "reasoning") at = tail;
}
repaired.splice(at, 0, ...owed.map((index) => messages[index]));
// Pushed one by one: spreading a large batch into splice() exceeds the
// engine's argument limit (RangeError: Maximum call stack size exceeded).
const tail = repaired.splice(at);
for (const index of owed) repaired.push(messages[index]);
for (const entry of tail) repaired.push(entry);
}
owed = undefined;
};
Expand Down
Loading