Skip to content

Commit 39535f2

Browse files
authored
fix(agent-core): isolate caller message context (#129293)
1 parent e5173ed commit 39535f2

3 files changed

Lines changed: 778 additions & 570 deletions

File tree

‎packages/agent-core/src/agent-loop.test.ts‎

Lines changed: 302 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,97 @@ describe("agentLoop EventStream failures", () => {
218218
});
219219
});
220220

221+
describe("public runner context isolation", () => {
222+
function createAssistantReplyStream(): ReturnType<StreamFn> {
223+
const stream = createAssistantMessageEventStream();
224+
queueMicrotask(() => {
225+
stream.push({
226+
type: "done",
227+
reason: "stop",
228+
message: {
229+
role: "assistant",
230+
content: [{ type: "text", text: "new reply" }],
231+
api: model.api,
232+
provider: model.provider,
233+
model: model.id,
234+
usage: TEST_USAGE,
235+
stopReason: "stop",
236+
timestamp: 2,
237+
},
238+
});
239+
stream.end();
240+
});
241+
return stream;
242+
}
243+
244+
async function expectCallerMessagesUnchanged(
245+
context: AgentContext,
246+
run: (emit: (event: AgentEvent) => void) => Promise<AgentMessage[]>,
247+
): Promise<void> {
248+
const originalMessages = context.messages;
249+
const originalSnapshot = structuredClone(context.messages);
250+
const events: AgentEvent[] = [];
251+
252+
const messages = await run((event) => {
253+
events.push(event);
254+
});
255+
256+
expect(context.messages).toBe(originalMessages);
257+
expect(context.messages).toEqual(originalSnapshot);
258+
expect(messages).toEqual([
259+
expect.objectContaining({
260+
role: "assistant",
261+
content: [{ type: "text", text: "new reply" }],
262+
}),
263+
]);
264+
expect(events).toEqual(
265+
expect.arrayContaining([
266+
expect.objectContaining({
267+
type: "message_end",
268+
message: expect.objectContaining({
269+
role: "assistant",
270+
content: [{ type: "text", text: "new reply" }],
271+
}),
272+
}),
273+
]),
274+
);
275+
}
276+
277+
it("keeps caller messages isolated for empty-prompt runs", async () => {
278+
const context: AgentContext = {
279+
systemPrompt: "",
280+
messages: [{ role: "user", content: "existing prompt", timestamp: 1 }],
281+
};
282+
283+
await expectCallerMessagesUnchanged(context, (emit) =>
284+
runAgentLoop([], context, config, emit, undefined, async () => createAssistantReplyStream()),
285+
);
286+
});
287+
288+
it("keeps caller messages isolated for continuations", async () => {
289+
const context: AgentContext = {
290+
systemPrompt: "",
291+
messages: [
292+
{
293+
role: "toolResult",
294+
toolCallId: "call-ready",
295+
toolName: "read",
296+
content: [{ type: "text", text: "ready" }],
297+
details: {},
298+
isError: false,
299+
timestamp: 1,
300+
},
301+
],
302+
};
303+
304+
await expectCallerMessagesUnchanged(context, (emit) =>
305+
runAgentLoopContinue(context, config, emit, undefined, async () =>
306+
createAssistantReplyStream(),
307+
),
308+
);
309+
});
310+
});
311+
221312
describe("agentLoop continuation guards", () => {
222313
const assistantTailContext: AgentContext = {
223314
systemPrompt: "",
@@ -1643,44 +1734,223 @@ describe("agentLoop tool termination", () => {
16431734
expect(releaseSkippedCalls).not.toHaveBeenCalled();
16441735
});
16451736

1646-
it("does not launch prepared tools when the admission commit fails", async () => {
1647-
const execute = vi.fn(async () => ({ content: [], details: {} }));
1648-
const streamFn = createTurnSequenceStream(
1649-
[[{ type: "toolCall", id: "commit-failure", name: "side-effect", arguments: {} }]],
1650-
[],
1651-
);
1737+
it.each(["sequential", "parallel"] as const)(
1738+
"pairs every tool lifecycle before rejecting a %s admission commit failure",
1739+
async (toolExecution) => {
1740+
const firstExecute = vi.fn(async () => ({ content: [], details: { executed: "first" } }));
1741+
const secondExecute = vi.fn(async () => ({ content: [], details: { executed: "second" } }));
1742+
const thirdExecute = vi.fn(async () => ({ content: [], details: { executed: "third" } }));
1743+
const commitError = new Error("private admission details must not reach tool results");
1744+
const releaseSkippedCalls = vi.fn();
1745+
const afterToolOutcome = vi.fn(async () => undefined);
1746+
const events: AgentEvent[] = [];
1747+
1748+
await expect(
1749+
runAgentLoop(
1750+
[{ role: "user", content: "run", timestamp: 1 }],
1751+
{
1752+
systemPrompt: "",
1753+
messages: [],
1754+
tools: [
1755+
{ ...makeTool("first", []), execute: firstExecute },
1756+
{ ...makeTool("second", []), execute: secondExecute },
1757+
{ ...makeTool("third", []), execute: thirdExecute },
1758+
],
1759+
},
1760+
{
1761+
...config,
1762+
toolExecution,
1763+
afterToolOutcome,
1764+
beforeToolBatch: async () =>
1765+
attachInternalToolBatchLifecycle(
1766+
{},
1767+
{
1768+
commitReadyCalls: (calls) => {
1769+
if (calls.some((call) => call.toolCallId === "commit-second")) {
1770+
throw commitError;
1771+
}
1772+
},
1773+
releaseSkippedCalls,
1774+
},
1775+
),
1776+
},
1777+
(event) => {
1778+
events.push(event);
1779+
},
1780+
undefined,
1781+
createTurnSequenceStream([
1782+
[
1783+
{ type: "toolCall", id: "commit-first", name: "first", arguments: {} },
1784+
{ type: "toolCall", id: "commit-second", name: "second", arguments: {} },
1785+
{ type: "toolCall", id: "commit-third", name: "third", arguments: {} },
1786+
],
1787+
]),
1788+
),
1789+
).rejects.toBe(commitError);
1790+
1791+
expect(firstExecute).toHaveBeenCalledOnce();
1792+
expect(secondExecute).not.toHaveBeenCalled();
1793+
expect(thirdExecute).not.toHaveBeenCalled();
1794+
expect(releaseSkippedCalls).toHaveBeenCalledExactlyOnceWith([
1795+
"commit-second",
1796+
"commit-third",
1797+
]);
1798+
expect(
1799+
events
1800+
.filter((event) => event.type === "tool_execution_start")
1801+
.map((event) => event.toolCallId),
1802+
).toEqual(["commit-first", "commit-second", "commit-third"]);
1803+
const toolEnds = events
1804+
.filter((event) => event.type === "tool_execution_end")
1805+
.map((event) => ({ id: event.toolCallId, started: event.executionStarted }));
1806+
expect(toolEnds).toHaveLength(3);
1807+
expect(toolEnds).toEqual(
1808+
expect.arrayContaining([
1809+
{ id: "commit-first", started: true },
1810+
{ id: "commit-second", started: false },
1811+
{ id: "commit-third", started: false },
1812+
]),
1813+
);
1814+
const toolResults = events
1815+
.filter(
1816+
(
1817+
event,
1818+
): event is Extract<AgentEvent, { type: "message_end" }> & {
1819+
message: { role: "toolResult" };
1820+
} => event.type === "message_end" && event.message.role === "toolResult",
1821+
)
1822+
.map((event) => event.message);
1823+
expect(toolResults.map((message) => message.toolCallId)).toEqual([
1824+
"commit-first",
1825+
"commit-second",
1826+
"commit-third",
1827+
]);
1828+
for (const toolResult of toolResults.slice(1)) {
1829+
expect(toolResult).toMatchObject({
1830+
isError: true,
1831+
content: [{ type: "text", text: "Tool execution was blocked before launch." }],
1832+
details: { status: "blocked", deniedReason: "tool-admission" },
1833+
});
1834+
expect(JSON.stringify(toolResult)).not.toContain(commitError.message);
1835+
}
1836+
expect(afterToolOutcome).toHaveBeenCalledTimes(3);
1837+
for (const toolCallId of ["commit-second", "commit-third"]) {
1838+
expect(afterToolOutcome).toHaveBeenCalledWith(
1839+
expect.objectContaining({
1840+
executionStarted: false,
1841+
toolCall: expect.objectContaining({ id: toolCallId }),
1842+
}),
1843+
undefined,
1844+
);
1845+
}
1846+
expect(events.filter((event) => event.type === "turn_end")).toEqual([
1847+
expect.objectContaining({
1848+
message: expect.objectContaining({ role: "assistant", stopReason: "toolUse" }),
1849+
toolResults,
1850+
}),
1851+
]);
1852+
},
1853+
);
1854+
1855+
it("keeps Agent active until started parallel work settles after a later commit failure", async () => {
1856+
const firstStarted = createDeferred();
1857+
const releaseFirst = createDeferred();
1858+
const secondCommitAttempted = createDeferred();
1859+
const secondExecute = vi.fn(async () => ({ content: [], details: {} }));
16521860
const commitError = new Error("admission commit failed");
16531861
const releaseSkippedCalls = vi.fn();
1654-
1655-
await expect(
1656-
runAgentLoop(
1657-
[{ role: "user", content: "run", timestamp: 1 }],
1658-
{
1659-
systemPrompt: "",
1660-
messages: [],
1661-
tools: [{ ...makeTool("side-effect", []), execute }],
1862+
const events: AgentEvent[] = [];
1863+
let providerCalls = 0;
1864+
let agentEnded = false;
1865+
const agent = new Agent({
1866+
initialState: {
1867+
model,
1868+
tools: [
1869+
{
1870+
...makeTool("first", []),
1871+
execute: async () => {
1872+
firstStarted.resolve();
1873+
await releaseFirst.promise;
1874+
return { content: [], details: { executed: "first" } };
1875+
},
1876+
},
1877+
{ ...makeTool("second", []), execute: secondExecute },
1878+
],
1879+
},
1880+
toolExecution: "parallel",
1881+
streamFn: createTurnSequenceStream(
1882+
[
1883+
[
1884+
{ type: "toolCall", id: "idle-first", name: "first", arguments: {} },
1885+
{ type: "toolCall", id: "idle-second", name: "second", arguments: {} },
1886+
],
1887+
],
1888+
[],
1889+
() => {
1890+
providerCalls += 1;
16621891
},
1892+
),
1893+
});
1894+
setInternalBeforeToolBatch(agent, async () =>
1895+
attachInternalToolBatchLifecycle(
1896+
{},
16631897
{
1664-
...config,
1665-
toolExecution: "parallel",
1666-
beforeToolBatch: async () =>
1667-
attachInternalToolBatchLifecycle(
1668-
{},
1669-
{
1670-
commitReadyCalls: () => {
1671-
throw commitError;
1672-
},
1673-
releaseSkippedCalls,
1674-
},
1675-
),
1898+
commitReadyCalls: (calls) => {
1899+
if (calls.some((call) => call.toolCallId === "idle-second")) {
1900+
secondCommitAttempted.resolve();
1901+
throw commitError;
1902+
}
1903+
},
1904+
releaseSkippedCalls,
16761905
},
1677-
() => {},
1678-
undefined,
1679-
streamFn,
16801906
),
1681-
).rejects.toBe(commitError);
1682-
expect(execute).not.toHaveBeenCalled();
1683-
expect(releaseSkippedCalls).not.toHaveBeenCalled();
1907+
);
1908+
agent.subscribe((event) => {
1909+
events.push(event);
1910+
agentEnded ||= event.type === "agent_end";
1911+
});
1912+
1913+
const prompt = agent.prompt("run");
1914+
await firstStarted.promise;
1915+
await secondCommitAttempted.promise;
1916+
try {
1917+
await new Promise<void>((resolve) => {
1918+
setTimeout(resolve, 0);
1919+
});
1920+
expect(agentEnded).toBe(false);
1921+
expect(agent.state.isStreaming).toBe(true);
1922+
} finally {
1923+
releaseFirst.resolve();
1924+
}
1925+
await prompt;
1926+
1927+
expect(providerCalls).toBe(1);
1928+
expect(secondExecute).not.toHaveBeenCalled();
1929+
expect(releaseSkippedCalls).toHaveBeenCalledWith(["idle-second"]);
1930+
expect(agent.state.messages.map((message) => message.role)).toEqual([
1931+
"user",
1932+
"assistant",
1933+
"toolResult",
1934+
"toolResult",
1935+
"assistant",
1936+
]);
1937+
const toolUseTurnEnd = events.findIndex(
1938+
(event) =>
1939+
event.type === "turn_end" &&
1940+
event.message.role === "assistant" &&
1941+
event.message.stopReason === "toolUse",
1942+
);
1943+
const failureTurnEnd = events.findIndex(
1944+
(event) =>
1945+
event.type === "turn_end" &&
1946+
event.message.role === "assistant" &&
1947+
event.message.stopReason === "error",
1948+
);
1949+
const agentEnd = events.findIndex((event) => event.type === "agent_end");
1950+
expect(toolUseTurnEnd).toBeGreaterThanOrEqual(0);
1951+
expect(failureTurnEnd).toBeGreaterThan(toolUseTurnEnd);
1952+
expect(agentEnd).toBeGreaterThan(failureTurnEnd);
1953+
expect(events.slice(agentEnd + 1)).toEqual([]);
16841954
});
16851955

16861956
it("gives the model one recovery turn with the normal tool catalog", async () => {

0 commit comments

Comments
 (0)