Skip to content

Commit 3d2082a

Browse files
committed
fix: harden agent live event regressions
1 parent 0941804 commit 3d2082a

5 files changed

Lines changed: 305 additions & 26 deletions

‎src/agents/pi-embedded-runner/tool-result-context-guard.test.ts‎

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -600,6 +600,85 @@ describe("installContextEngineLoopHook", () => {
600600
expect(transformed).toBe(compactedView);
601601
});
602602

603+
it("clears an assembled view when the engine fails on a later source", async () => {
604+
const agent = makeGuardableAgent();
605+
const compactedView = [makeUser("compacted")];
606+
const engine = makeMockEngine({
607+
assemble: async () => ({ messages: compactedView, estimatedTokens: 0 }),
608+
});
609+
engine.assemble
610+
.mockResolvedValueOnce({ messages: compactedView, estimatedTokens: 0 })
611+
.mockRejectedValueOnce(new Error("assemble failed"))
612+
.mockImplementation(async (params: Parameters<ContextEngine["assemble"]>[0]) => ({
613+
messages: params.messages,
614+
estimatedTokens: 0,
615+
}));
616+
installHook(agent, engine, 1);
617+
618+
const firstSource = [makeUser("first"), makeToolResult("call_1", "r1")];
619+
expect(await callTransform(agent, firstSource)).toBe(compactedView);
620+
621+
const secondSource = [...firstSource, makeToolResult("call_2", "r2")];
622+
expect(await callTransform(agent, secondSource)).toBe(secondSource);
623+
624+
const retry = await callTransform(agent, secondSource);
625+
expect(retry).toBe(secondSource);
626+
expect(retry).not.toBe(compactedView);
627+
expect(engine.assemble).toHaveBeenCalledTimes(3);
628+
});
629+
630+
it("clears an assembled view when source history shrinks", async () => {
631+
const agent = makeGuardableAgent();
632+
const compactedView = [makeUser("compacted")];
633+
const engine = makeMockEngine({
634+
assemble: async () => ({ messages: compactedView, estimatedTokens: 0 }),
635+
});
636+
engine.assemble.mockResolvedValueOnce({ messages: compactedView, estimatedTokens: 0 });
637+
engine.assemble.mockImplementation(
638+
async (params: Parameters<ContextEngine["assemble"]>[0]) => ({
639+
messages: params.messages,
640+
estimatedTokens: 0,
641+
}),
642+
);
643+
installHook(agent, engine, 1);
644+
645+
const longSource = [
646+
makeUser("first"),
647+
makeToolResult("call_1", "r1"),
648+
makeToolResult("call_2", "r2"),
649+
];
650+
expect(await callTransform(agent, longSource)).toBe(compactedView);
651+
652+
const resetSource = [makeUser("reset")];
653+
expect(await callTransform(agent, resetSource)).toBe(resetSource);
654+
});
655+
656+
it("clears an assembled view when source history resets at the same length", async () => {
657+
const agent = makeGuardableAgent();
658+
const compactedView = [makeUser("compacted")];
659+
const engine = makeMockEngine({
660+
assemble: async () => ({ messages: compactedView, estimatedTokens: 0 }),
661+
});
662+
engine.assemble.mockResolvedValueOnce({ messages: compactedView, estimatedTokens: 0 });
663+
engine.assemble.mockImplementation(
664+
async (params: Parameters<ContextEngine["assemble"]>[0]) => ({
665+
messages: params.messages,
666+
estimatedTokens: 0,
667+
}),
668+
);
669+
installHook(agent, engine, 1);
670+
671+
const source = [
672+
makeUser("first"),
673+
makeToolResult("call_1", "r1"),
674+
makeToolResult("call_2", "r2"),
675+
];
676+
expect(await callTransform(agent, source)).toBe(compactedView);
677+
678+
const resetSource = [makeUser("reset"), makeToolResult("call_3", "r3"), makeUser("fresh")];
679+
expect(await callTransform(agent, resetSource)).toBe(resetSource);
680+
});
681+
603682
it("returns the assembled view when the engine rewrites content without changing count", async () => {
604683
const agent = makeGuardableAgent();
605684
const rewrittenView = [makeUser("rewritten-1"), makeUser("rewritten-2")];

‎src/agents/pi-embedded-runner/tool-result-context-guard.ts‎

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -250,12 +250,27 @@ export function installContextEngineLoopHook(params: {
250250
const originalTransformContext = mutableAgent.transformContext;
251251
let lastSeenLength: number | null = null;
252252
let lastAssembledView: AgentMessage[] | null = null;
253+
let lastSourceMessages: AgentMessage[] | null = null;
253254

254255
mutableAgent.transformContext = (async (messages: AgentMessage[], signal: AbortSignal) => {
255256
const transformed = originalTransformContext
256257
? await originalTransformContext.call(mutableAgent, messages, signal)
257258
: messages;
258259
const sourceMessages = Array.isArray(transformed) ? transformed : messages;
260+
const checkedPrefixLength =
261+
lastSeenLength == null ? 0 : Math.min(lastSeenLength, sourceMessages.length);
262+
const sourceHistoryChanged =
263+
lastSeenLength != null &&
264+
lastSourceMessages != null &&
265+
(sourceMessages.length < lastSeenLength ||
266+
(sourceMessages.length === lastSeenLength &&
267+
sourceMessages
268+
.slice(0, checkedPrefixLength)
269+
.some((message, index) => message !== lastSourceMessages?.[index])));
270+
if (sourceHistoryChanged) {
271+
lastSeenLength = null;
272+
lastAssembledView = null;
273+
}
259274

260275
// Seed the loop fence from the attempt's pre-prompt message count when available.
261276
// This keeps the first real post-tool-call iteration eligible for compaction even
@@ -267,10 +282,11 @@ export function installContextEngineLoopHook(params: {
267282
lastSeenLength ?? params.getPrePromptMessageCount?.() ?? sourceMessages.length,
268283
),
269284
);
270-
lastSeenLength = prePromptMessageCount;
271285

272286
const hasNewMessages = sourceMessages.length > prePromptMessageCount;
273287
if (!hasNewMessages) {
288+
lastSeenLength = prePromptMessageCount;
289+
lastSourceMessages = sourceMessages;
274290
return lastAssembledView ?? sourceMessages;
275291
}
276292
try {
@@ -308,6 +324,7 @@ export function installContextEngineLoopHook(params: {
308324
}
309325
}
310326
lastSeenLength = sourceMessages.length;
327+
lastSourceMessages = sourceMessages;
311328
const assembled = await contextEngine.assemble({
312329
sessionId,
313330
sessionKey,
@@ -323,6 +340,9 @@ export function installContextEngineLoopHook(params: {
323340
} catch {
324341
// Best-effort: any engine failure falls through to the raw source
325342
// messages so the tool loop still makes forward progress.
343+
lastSeenLength = prePromptMessageCount;
344+
lastAssembledView = null;
345+
lastSourceMessages = sourceMessages;
326346
}
327347

328348
return sourceMessages;

‎src/agents/pi-embedded-subscribe.handlers.tools.test.ts‎

Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -755,6 +755,119 @@ describe("handleToolExecutionEnd derived tool events", () => {
755755
);
756756
});
757757

758+
it("caps and throttles exec update output before live events", async () => {
759+
resetAgentEventsForTest();
760+
const events: Array<{ stream?: string; data?: Record<string, unknown> }> = [];
761+
registerAgentEventListener((evt) => {
762+
events.push(evt as never);
763+
});
764+
const { ctx, onAgentEvent } = createTestContext();
765+
const largeOutput = "x".repeat(9000);
766+
767+
await handleToolExecutionStart(
768+
ctx as never,
769+
{
770+
type: "tool_execution_start",
771+
toolName: "exec",
772+
toolCallId: "tool-exec-large-update",
773+
args: { command: "yes" },
774+
} as never,
775+
);
776+
777+
handleToolExecutionUpdate(
778+
ctx as never,
779+
{
780+
type: "tool_execution_update",
781+
toolName: "exec",
782+
toolCallId: "tool-exec-large-update",
783+
partialResult: {
784+
details: {
785+
status: "running",
786+
aggregated: largeOutput,
787+
},
788+
},
789+
} as never,
790+
);
791+
handleToolExecutionUpdate(
792+
ctx as never,
793+
{
794+
type: "tool_execution_update",
795+
toolName: "exec",
796+
toolCallId: "tool-exec-large-update",
797+
partialResult: {
798+
details: {
799+
status: "running",
800+
aggregated: `${largeOutput}again`,
801+
},
802+
},
803+
} as never,
804+
);
805+
806+
const updateEvents = events.filter(
807+
(evt) => evt.stream === "tool" && (evt.data as { phase?: string })?.phase === "update",
808+
);
809+
expect(updateEvents).toHaveLength(1);
810+
const partialResult = updateEvents[0]?.data?.partialResult as
811+
| { details?: { aggregated?: string } }
812+
| undefined;
813+
expect(partialResult?.details?.aggregated).toContain("...(live output truncated)...");
814+
expect(partialResult?.details?.aggregated?.length).toBeLessThan(largeOutput.length);
815+
816+
const commandOutputCalls = onAgentEvent.mock.calls
817+
.map((call) => call[0])
818+
.filter((arg: unknown) => (arg as { stream?: string })?.stream === "command_output");
819+
expect(commandOutputCalls).toHaveLength(1);
820+
const output = (commandOutputCalls[0] as { data?: { output?: string } }).data?.output;
821+
expect(output).toContain("...(live output truncated)...");
822+
expect(output?.length).toBeLessThan(largeOutput.length);
823+
824+
resetAgentEventsForTest();
825+
});
826+
827+
it("caps exec final output before result and command output events", async () => {
828+
resetAgentEventsForTest();
829+
const events: Array<{ stream?: string; data?: Record<string, unknown> }> = [];
830+
registerAgentEventListener((evt) => {
831+
events.push(evt as never);
832+
});
833+
const { ctx, onAgentEvent } = createTestContext();
834+
const largeOutput = "z".repeat(9000);
835+
836+
await handleToolExecutionEnd(
837+
ctx as never,
838+
{
839+
type: "tool_execution_end",
840+
toolName: "exec",
841+
toolCallId: "tool-exec-large-result",
842+
isError: false,
843+
result: {
844+
details: {
845+
status: "completed",
846+
aggregated: largeOutput,
847+
exitCode: 0,
848+
},
849+
},
850+
} as never,
851+
);
852+
853+
const resultEvent = events.find(
854+
(evt) => evt.stream === "tool" && (evt.data as { phase?: string })?.phase === "result",
855+
);
856+
const result = resultEvent?.data?.result as { details?: { aggregated?: string } } | undefined;
857+
expect(result?.details?.aggregated).toContain("...(live output truncated)...");
858+
expect(result?.details?.aggregated?.length).toBeLessThan(largeOutput.length);
859+
860+
const commandOutputCalls = onAgentEvent.mock.calls
861+
.map((call) => call[0])
862+
.filter((arg: unknown) => (arg as { stream?: string })?.stream === "command_output");
863+
const output = (commandOutputCalls.at(-1) as { data?: { output?: string } } | undefined)?.data
864+
?.output;
865+
expect(output).toContain("...(live output truncated)...");
866+
expect(output?.length).toBeLessThan(largeOutput.length);
867+
868+
resetAgentEventsForTest();
869+
});
870+
758871
it("emits command output events for exec results", async () => {
759872
const { ctx, onAgentEvent } = createTestContext();
760873

0 commit comments

Comments
 (0)