Skip to content

Commit 54b9e92

Browse files
committed
fix: harden post-tool continuation safety
1 parent 1f7147b commit 54b9e92

10 files changed

Lines changed: 268 additions & 25 deletions

‎src/agents/embedded-agent-runner/run.incomplete-turn.test.ts‎

Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -592,6 +592,108 @@ describe("runEmbeddedAgent incomplete-turn safety", () => {
592592
expect(payload?.text).not.toContain("Adding it now.");
593593
});
594594

595+
it("does not continue automatically after an unclassified plugin tool result", async () => {
596+
mockedClassifyFailoverReason.mockReturnValue(null);
597+
mockedRunEmbeddedAttempt.mockResolvedValueOnce(
598+
makeAttemptResult({
599+
assistantTexts: ["Publishing it now."],
600+
toolMetas: [
601+
{
602+
toolName: "custom_side_effect_tool",
603+
mutatingAction: false,
604+
mutationClassified: false,
605+
},
606+
],
607+
messagesSnapshot: [
608+
{
609+
role: "toolResult",
610+
toolCallId: "call_plugin",
611+
content: [{ type: "text", text: '{"ok":true}' }],
612+
isError: false,
613+
} as unknown as EmbeddedRunAttemptResult["messagesSnapshot"][number],
614+
{
615+
role: "assistant",
616+
stopReason: "stop",
617+
provider: "openai",
618+
model: "gpt-5.4",
619+
content: [],
620+
} as unknown as EmbeddedRunAttemptResult["messagesSnapshot"][number],
621+
],
622+
lastAssistant: {
623+
role: "assistant",
624+
stopReason: "stop",
625+
provider: "openai",
626+
model: "gpt-5.4",
627+
content: [],
628+
} as unknown as EmbeddedRunAttemptResult["lastAssistant"],
629+
}),
630+
);
631+
632+
const result = await runEmbeddedAgent({
633+
...overflowBaseRunParams,
634+
provider: "openai",
635+
model: "gpt-5.4",
636+
runId: "run-post-tool-empty-unclassified-plugin",
637+
});
638+
639+
expect(mockedRunEmbeddedAttempt).toHaveBeenCalledTimes(1);
640+
const [payload] = result.payloads ?? [];
641+
expect(payload?.text).toContain("couldn't generate a response");
642+
expect(payload?.text).toContain("tool actions may have already been executed");
643+
expect(payload?.text).not.toContain("Publishing it now.");
644+
});
645+
646+
it("does not continue when the terminal path already contains tool media", async () => {
647+
mockedClassifyFailoverReason.mockReturnValue(null);
648+
mockedRunEmbeddedAttempt.mockResolvedValueOnce(
649+
makeAttemptResult({
650+
assistantTexts: ["Checking the image."],
651+
toolMetas: [
652+
{
653+
toolName: "image",
654+
mutatingAction: false,
655+
mutationClassified: true,
656+
},
657+
],
658+
toolMediaUrls: ["https://example.com/result.png"],
659+
messagesSnapshot: [
660+
{
661+
role: "toolResult",
662+
toolCallId: "call_image",
663+
content: [{ type: "text", text: '{"ok":true}' }],
664+
isError: false,
665+
} as unknown as EmbeddedRunAttemptResult["messagesSnapshot"][number],
666+
{
667+
role: "assistant",
668+
stopReason: "stop",
669+
provider: "openai",
670+
model: "gpt-5.4",
671+
content: [],
672+
} as unknown as EmbeddedRunAttemptResult["messagesSnapshot"][number],
673+
],
674+
lastAssistant: {
675+
role: "assistant",
676+
stopReason: "stop",
677+
provider: "openai",
678+
model: "gpt-5.4",
679+
content: [],
680+
} as unknown as EmbeddedRunAttemptResult["lastAssistant"],
681+
}),
682+
);
683+
684+
const result = await runEmbeddedAgent({
685+
...overflowBaseRunParams,
686+
provider: "openai",
687+
model: "gpt-5.4",
688+
runId: "run-post-tool-empty-media",
689+
});
690+
691+
expect(mockedRunEmbeddedAttempt).toHaveBeenCalledTimes(1);
692+
expect(result.payloads).toEqual([
693+
expect.objectContaining({ mediaUrl: "https://example.com/result.png" }),
694+
]);
695+
});
696+
595697
it("bounds empty post-tool continuation to one retry", async () => {
596698
mockedClassifyFailoverReason.mockReturnValue(null);
597699
const emptyPostToolAttempt = makeAttemptResult({
@@ -2556,6 +2658,23 @@ describe("runEmbeddedAgent incomplete-turn safety", () => {
25562658
).toEqual({ hadPotentialSideEffects: true, replaySafe: false });
25572659
});
25582660

2661+
it("fails closed when a completed tool call has no mutation classifier", () => {
2662+
expect(
2663+
buildAttemptReplayMetadata({
2664+
toolMetas: [
2665+
{
2666+
toolName: "custom_side_effect_tool",
2667+
mutatingAction: false,
2668+
mutationClassified: false,
2669+
},
2670+
],
2671+
didSendViaMessagingTool: false,
2672+
messagingToolSentTexts: [],
2673+
messagingToolSentMediaUrls: [],
2674+
}),
2675+
).toEqual({ hadPotentialSideEffects: true, replaySafe: false });
2676+
});
2677+
25592678
it("detects a trailing empty assistant turn after a tool result structurally", () => {
25602679
expect(
25612680
isPostToolEmptyAssistantTurn(

‎src/agents/embedded-agent-runner/run.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3395,12 +3395,14 @@ async function runEmbeddedAgentInternal(
33953395
if (
33963396
postToolEmptyAssistantTurn &&
33973397
!emptyAssistantReplyIsSilent &&
3398+
payloadCount === 0 &&
33983399
!aborted &&
33993400
!timedOut &&
34003401
!attempt.clientToolCalls &&
34013402
!attempt.yieldDetected &&
34023403
!attempt.didSendDeterministicApprovalPrompt &&
34033404
!attempt.lastToolError &&
3405+
!hasMessagingToolDeliveryEvidence(attempt) &&
34043406
!resolveAttemptReplayMetadata(attempt).hadPotentialSideEffects &&
34053407
postToolEmptyContinuationAttempts < 1
34063408
) {

‎src/agents/embedded-agent-runner/run/attempt.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3469,6 +3469,7 @@ export async function runEmbeddedAttempt(
34693469
sessionId: params.sessionId,
34703470
agentId: sessionAgentId,
34713471
builtinToolNames,
3472+
mutationClassifiedToolNames: coreBuiltinToolNames,
34723473
internalEvents: params.internalEvents,
34733474
}),
34743475
);

‎src/agents/embedded-agent-runner/run/incomplete-turn.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -249,7 +249,9 @@ export function buildAttemptReplayMetadata(
249249
params: ReplayMetadataAttempt,
250250
): EmbeddedRunAttemptResult["replayMetadata"] {
251251
const hadMutatingTools = params.toolMetas.some(
252-
(toolMeta) => toolMeta.mutatingAction ?? isLikelyMutatingToolName(toolMeta.toolName),
252+
(toolMeta) =>
253+
toolMeta.mutationClassified === false ||
254+
(toolMeta.mutatingAction ?? isLikelyMutatingToolName(toolMeta.toolName)),
253255
);
254256
const hadAsyncStartedTool = params.toolMetas.some((t) => t.asyncStarted === true);
255257
const hadPotentialSideEffects =

‎src/agents/embedded-agent-runner/run/types.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,7 @@ export type EmbeddedRunAttemptResult = {
169169
toolName: string;
170170
meta?: string;
171171
mutatingAction?: boolean;
172+
mutationClassified?: boolean;
172173
asyncStarted?: boolean;
173174
asyncTaskRunId?: string;
174175
asyncTaskId?: string;

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

Lines changed: 85 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import {
88
} from "../infra/agent-events.js";
99
import { setActivePluginRegistry } from "../plugins/runtime.js";
1010
import { createChannelTestPluginBase, createTestRegistry } from "../test-utils/channel-plugins.js";
11+
import { recordAdjustedParamsForToolCall } from "./agent-tools.before-tool-call.js";
1112
import type { MessagingToolSend } from "./embedded-agent-messaging.types.js";
1213
import {
1314
handleToolExecutionEnd,
@@ -333,6 +334,7 @@ describe("handleToolExecutionStart read path checks", () => {
333334
describe("handleToolExecutionEnd cron.add commitment tracking", () => {
334335
it("increments successfulCronAdds when cron add succeeds", async () => {
335336
const { ctx } = createTestContext();
337+
ctx.mutationClassifiedToolNames = new Set(["cron"]);
336338
await handleToolExecutionStart(
337339
ctx as never,
338340
{
@@ -356,12 +358,18 @@ describe("handleToolExecutionEnd cron.add commitment tracking", () => {
356358

357359
expect(ctx.state.successfulCronAdds).toBe(1);
358360
expect(ctx.state.toolMetas).toContainEqual(
359-
expect.objectContaining({ toolName: "cron", mutatingAction: true }),
361+
expect.objectContaining({
362+
toolName: "cron",
363+
mutatingAction: true,
364+
mutationClassified: true,
365+
}),
360366
);
367+
expect(ctx.state.successfulCronAdds).toBe(1);
361368
});
362369

363370
it("retains read-only cron action metadata for replay classification", async () => {
364371
const { ctx } = createTestContext();
372+
ctx.mutationClassifiedToolNames = new Set(["cron"]);
365373
await handleToolExecutionStart(
366374
ctx as never,
367375
{
@@ -384,7 +392,82 @@ describe("handleToolExecutionEnd cron.add commitment tracking", () => {
384392
);
385393

386394
expect(ctx.state.toolMetas).toContainEqual(
387-
expect.objectContaining({ toolName: "cron", mutatingAction: false }),
395+
expect.objectContaining({
396+
toolName: "cron",
397+
mutatingAction: false,
398+
mutationClassified: true,
399+
}),
400+
);
401+
});
402+
403+
it("reclassifies mutation from hook-adjusted execution arguments", async () => {
404+
const { ctx } = createTestContext();
405+
ctx.mutationClassifiedToolNames = new Set(["cron"]);
406+
await handleToolExecutionStart(
407+
ctx as never,
408+
{
409+
type: "tool_execution_start",
410+
toolName: "cron",
411+
toolCallId: "tool-cron-adjusted",
412+
args: { action: "status" },
413+
} as never,
414+
);
415+
recordAdjustedParamsForToolCall(
416+
"tool-cron-adjusted",
417+
{ action: "add", job: { name: "reminder" } },
418+
"run-test",
419+
);
420+
421+
await handleToolExecutionEnd(
422+
ctx as never,
423+
{
424+
type: "tool_execution_end",
425+
toolName: "cron",
426+
toolCallId: "tool-cron-adjusted",
427+
isError: false,
428+
result: { details: { status: "ok" } },
429+
} as never,
430+
);
431+
432+
expect(ctx.state.toolMetas).toContainEqual(
433+
expect.objectContaining({
434+
toolName: "cron",
435+
mutatingAction: true,
436+
mutationClassified: true,
437+
}),
438+
);
439+
});
440+
441+
it("marks plugin tool mutation behavior as unclassified", async () => {
442+
const { ctx } = createTestContext();
443+
ctx.mutationClassifiedToolNames = new Set(["cron"]);
444+
await handleToolExecutionStart(
445+
ctx as never,
446+
{
447+
type: "tool_execution_start",
448+
toolName: "custom_side_effect_tool",
449+
toolCallId: "tool-plugin-side-effect",
450+
args: { action: "publish" },
451+
} as never,
452+
);
453+
454+
await handleToolExecutionEnd(
455+
ctx as never,
456+
{
457+
type: "tool_execution_end",
458+
toolName: "custom_side_effect_tool",
459+
toolCallId: "tool-plugin-side-effect",
460+
isError: false,
461+
result: { ok: true },
462+
} as never,
463+
);
464+
465+
expect(ctx.state.toolMetas).toContainEqual(
466+
expect.objectContaining({
467+
toolName: "custom_side_effect_tool",
468+
mutatingAction: false,
469+
mutationClassified: false,
470+
}),
388471
);
389472
});
390473

0 commit comments

Comments
 (0)