Skip to content

Commit b82ad64

Browse files
authored
fix(delivery): preserve suppressed send outcomes (#122421)
* fix(delivery): preserve suppressed send outcomes Preserve authoritative durable-send suppression outcomes so task, subagent, and exec followups no longer report false delivery or duplicate ambiguous adapter dispatches. * fix(delivery): keep suppression reason internal Derive the outbound projection from the existing durable batch result union so the repair does not change the public plugin SDK contract. * fix(delivery): avoid retrying ambiguous task updates Advance the state-change event cursor after an adapter returns no identity so a possibly visible progress notification is not sent twice; intentional suppression remains retryable.
1 parent a3b2700 commit b82ad64

8 files changed

Lines changed: 261 additions & 36 deletions

‎src/agents/bash-tools.exec-approval-followup.test.ts‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -758,6 +758,57 @@ describe("exec approval followup", () => {
758758
expect(callGatewayTool).not.toHaveBeenCalled();
759759
});
760760

761+
it.each([
762+
{
763+
suppressionReason: "cancelled_by_message_sending_hook",
764+
expectedMessage: "delivery was suppressed",
765+
},
766+
{
767+
suppressionReason: "adapter_returned_no_identity",
768+
expectedMessage: "delivery could not be confirmed",
769+
},
770+
] as const)(
771+
"rejects direct followup after $suppressionReason",
772+
async ({ suppressionReason, expectedMessage }) => {
773+
vi.mocked(sendMessage).mockResolvedValueOnce({
774+
channel: "discord",
775+
to: "123",
776+
via: "direct",
777+
mediaUrl: null,
778+
deliveryStatus: "suppressed",
779+
suppressionReason,
780+
});
781+
782+
await expect(
783+
sendExecApprovalFollowup({
784+
approvalId: `req-${suppressionReason}`,
785+
turnSourceChannel: "discord",
786+
turnSourceTo: "123",
787+
resultText: "Exec finished (gateway id=req-suppressed, code 0)\nall good",
788+
}),
789+
).rejects.toThrow(expectedMessage);
790+
},
791+
);
792+
793+
it("accepts direct followup success without a delivery status", async () => {
794+
vi.mocked(sendMessage).mockResolvedValueOnce({
795+
channel: "discord",
796+
to: "123",
797+
via: "gateway",
798+
mediaUrl: null,
799+
result: { messageId: "gateway-message-1" },
800+
});
801+
802+
await expect(
803+
sendExecApprovalFollowup({
804+
approvalId: "req-gateway-compatible",
805+
turnSourceChannel: "discord",
806+
turnSourceTo: "123",
807+
resultText: "Exec finished (gateway id=req-gateway-compatible, code 0)\nall good",
808+
}),
809+
).resolves.toBe(true);
810+
});
811+
761812
it("redacts credentials before direct delivery", async () => {
762813
const secret = "sk-abcdefghijklmnopqrstuvwxyz123456";
763814

‎src/agents/bash-tools.exec-approval-followup.ts‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -414,7 +414,7 @@ async function sendDirectFollowupFallback(params: {
414414
Math.max(0, directText.length - Math.max(1, availableBodyUnits)),
415415
)}`;
416416
const deliveryIntentId = `exec-approval-followup:${params.approvalId}`;
417-
await sendMessage({
417+
const sendResult = await sendMessage({
418418
channel: params.deliveryTarget.channel,
419419
to: params.deliveryTarget.to ?? "",
420420
accountId: params.deliveryTarget.accountId,
@@ -427,6 +427,16 @@ async function sendDirectFollowupFallback(params: {
427427
reusePendingDeliveryIntent: true,
428428
completionRetention: DIRECT_FOLLOWUP_COMPLETION_RETENTION,
429429
});
430+
if (sendResult.deliveryStatus === "suppressed") {
431+
if (sendResult.suppressionReason === "adapter_returned_no_identity") {
432+
throw new Error(
433+
"exec approval followup delivery could not be confirmed: adapter returned no identity",
434+
);
435+
}
436+
throw new Error(
437+
`exec approval followup delivery was suppressed: ${sendResult.suppressionReason ?? "unknown reason"}`,
438+
);
439+
}
430440
return true;
431441
}
432442

‎src/agents/subagents/announce/subagent-announce-delivery.test.ts‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1313,6 +1313,45 @@ describe("deliverSubagentAnnouncement completion delivery", () => {
13131313
}
13141314
});
13151315

1316+
it.each([
1317+
{
1318+
name: "intentional suppression",
1319+
suppressionReason: "cancelled_by_message_sending_hook",
1320+
disposition: "intentional_non_delivery",
1321+
},
1322+
{
1323+
name: "adapter ambiguity",
1324+
suppressionReason: "adapter_returned_no_identity",
1325+
disposition: "ambiguous",
1326+
},
1327+
] as const)("reports $name from direct text completion fallback", async (testCase) => {
1328+
const callGateway = createPayloadGatewayMock();
1329+
const onDeliveryResult = vi.fn();
1330+
const sendMessage = vi.fn(async () => ({
1331+
channel: "discord",
1332+
to: "dm:U123",
1333+
via: "direct" as const,
1334+
mediaUrl: null,
1335+
deliveryStatus: "suppressed" as const,
1336+
suppressionReason: testCase.suppressionReason,
1337+
})) as unknown as typeof runtimeSendMessage;
1338+
1339+
const result = await deliverDiscordDirectMessageCompletion({
1340+
callGateway,
1341+
sendMessage,
1342+
internalEvents: taskCompletionEvents({ childSessionId: "child-session-id" }),
1343+
onDeliveryResult,
1344+
});
1345+
1346+
expectRecordFields(result, {
1347+
delivered: false,
1348+
path: "direct",
1349+
disposition: testCase.disposition,
1350+
});
1351+
expect(onDeliveryResult).not.toHaveBeenCalled();
1352+
expect(sendMessage).toHaveBeenCalledTimes(1);
1353+
});
1354+
13161355
it("sanitizes and bounds text before direct completion fallback delivery", async () => {
13171356
const callGateway = createPayloadGatewayMock();
13181357
const sendMessage = createSendMessageMock();

‎src/agents/subagents/announce/subagent-announce-delivery.ts‎

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -760,7 +760,7 @@ async function deliverCompletionDirect(params: {
760760
if (params.isSourceSessionEffectsAllowed?.() === false) {
761761
return sourceOwnerChangedResult();
762762
}
763-
await subagentAnnounceDeliveryDeps.sendMessage({
763+
const sendResult = await subagentAnnounceDeliveryDeps.sendMessage({
764764
cfg: params.cfg,
765765
channel: params.deliveryTarget.channel,
766766
to: params.deliveryTarget.to,
@@ -786,7 +786,23 @@ async function deliverCompletionDirect(params: {
786786
idempotencyKey,
787787
},
788788
});
789-
return committedDelivery ?? { delivered: true, path: "direct" };
789+
if (committedDelivery) {
790+
return committedDelivery;
791+
}
792+
if (sendResult.deliveryStatus === "suppressed") {
793+
const ambiguous = sendResult.suppressionReason === "adapter_returned_no_identity";
794+
return {
795+
delivered: false,
796+
path: "direct",
797+
error: ambiguous
798+
? "text completion direct delivery could not be confirmed: adapter returned no identity"
799+
: `text completion direct delivery was suppressed: ${sendResult.suppressionReason ?? "unknown reason"}`,
800+
...(ambiguous
801+
? { disposition: "ambiguous" as const }
802+
: { disposition: "intentional_non_delivery" as const, terminal: true }),
803+
};
804+
}
805+
return { delivered: true, path: "direct" };
790806
} catch (err) {
791807
if (committedDelivery) {
792808
// Post-send bookkeeping must never turn an identified delivery into a

‎src/infra/outbound/message.test.ts‎

Lines changed: 35 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -554,40 +554,44 @@ describe("sendMessage", () => {
554554
expectDeliveryCallFields({ to: "prepared:123456" });
555555
});
556556

557-
it("preserves suppressed direct-send status", async () => {
558-
mocks.deliverOutboundPayloads.mockImplementationOnce(async (params: unknown) => {
559-
const callbacks = params as {
560-
onPayloadDeliveryOutcome?: (outcome: unknown) => void;
561-
};
562-
callbacks.onPayloadDeliveryOutcome?.({
563-
index: 0,
564-
status: "suppressed",
565-
reason: "cancelled_by_message_sending_hook",
566-
hookEffect: {
567-
cancelReason: "owned-by-other-agent",
568-
metadata: { unsafeForJson: 1n },
569-
},
557+
it.each(["cancelled_by_message_sending_hook", "adapter_returned_no_identity"] as const)(
558+
"preserves aggregate suppression reason %s",
559+
async (reason) => {
560+
mocks.deliverOutboundPayloads.mockImplementationOnce(async (params: unknown) => {
561+
const callbacks = params as {
562+
onPayloadDeliveryOutcome?: (outcome: unknown) => void;
563+
};
564+
callbacks.onPayloadDeliveryOutcome?.({
565+
index: 0,
566+
status: "suppressed",
567+
reason,
568+
hookEffect: {
569+
cancelReason: "owned-by-other-agent",
570+
metadata: { unsafeForJson: 1n },
571+
},
572+
});
573+
return [];
570574
});
571-
return [];
572-
});
573575

574-
const result = await sendMessage({
575-
cfg: {},
576-
channel: "forum",
577-
to: "123456",
578-
content: "hidden",
579-
});
576+
const result = await sendMessage({
577+
cfg: {},
578+
channel: "forum",
579+
to: "123456",
580+
content: "hidden",
581+
});
580582

581-
expect(result.deliveryStatus).toBe("suppressed");
582-
expect(result.payloadOutcomes).toEqual([
583-
{
584-
index: 0,
585-
status: "suppressed",
586-
reason: "cancelled_by_message_sending_hook",
587-
},
588-
]);
589-
expect(() => JSON.stringify(result)).not.toThrow();
590-
});
583+
expect(result.deliveryStatus).toBe("suppressed");
584+
expect(result).toMatchObject({ suppressionReason: reason });
585+
expect(result.payloadOutcomes).toEqual([
586+
{
587+
index: 0,
588+
status: "suppressed",
589+
reason,
590+
},
591+
]);
592+
expect(() => JSON.stringify(result)).not.toThrow();
593+
},
594+
);
591595

592596
it("does not throw best-effort direct send failures but reports the failure", async () => {
593597
mocks.deliverOutboundPayloads.mockImplementationOnce(async (params: unknown) => {

‎src/infra/outbound/message.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { deriveDurableFinalDeliveryRequirementsForBatch } from "../../channels/m
66
import {
77
sendDurableMessageBatchCore,
88
serializeDurableMessagePayloadOutcomes,
9+
type DurableMessageBatchSendResult,
910
type SerializedDurableMessagePayloadOutcome,
1011
} from "../../channels/message/runtime.js";
1112
import type { DurableMessageSendIntent } from "../../channels/message/types.js";
@@ -129,6 +130,7 @@ export type MessageSendResult = {
129130
mediaUrls?: string[];
130131
result?: OutboundDeliveryResult | { messageId: string };
131132
deliveryStatus?: "sent" | "suppressed" | "partial_failed" | "failed";
133+
suppressionReason?: Extract<DurableMessageBatchSendResult, { status: "suppressed" }>["reason"];
132134
/** Formatted send error when deliveryStatus is "failed" or "partial_failed". */
133135
error?: string;
134136
sentBeforeError?: boolean;
@@ -441,6 +443,7 @@ export async function sendMessage(params: MessageSendParams): Promise<MessageSen
441443
mediaUrls: mirrorMediaUrls.length ? mirrorMediaUrls : undefined,
442444
result: results.at(-1),
443445
deliveryStatus: send.status,
446+
...(send.status === "suppressed" ? { suppressionReason: send.reason } : {}),
444447
...(send.status === "failed" || send.status === "partial_failed"
445448
? { error: formatErrorMessage(send.error) }
446449
: {}),

‎src/tasks/task-registry-delivery.ts‎

Lines changed: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -309,7 +309,7 @@ async function maybeDeliverTaskTerminalUpdateUnderAdmission(
309309
}
310310
const requesterAgentId = parseAgentSessionKey(ownerSessionKey)?.agentId;
311311
const idempotencyKey = resolveTaskTerminalIdempotencyKey(latest);
312-
await sendMessage({
312+
const sendResult = await sendMessage({
313313
channel: owner.requesterOrigin?.channel,
314314
to: owner.requesterOrigin?.to ?? "",
315315
accountId: owner.requesterOrigin?.accountId,
@@ -327,6 +327,23 @@ async function maybeDeliverTaskTerminalUpdateUnderAdmission(
327327
if (!afterSend || !shouldAutoDeliverTaskTerminalUpdate(afterSend)) {
328328
return afterSend ? cloneTaskRecord(afterSend) : null;
329329
}
330+
if (sendResult.deliveryStatus === "suppressed") {
331+
if (sendResult.suppressionReason === "adapter_returned_no_identity") {
332+
taskRegistryLog.warn("Background task update delivery was not confirmed", {
333+
taskId,
334+
ownerKey: ownerSessionKey,
335+
requesterOrigin: owner.requesterOrigin,
336+
suppressionReason: sendResult.suppressionReason,
337+
});
338+
return updateTask(taskId, {
339+
deliveryStatus: "failed",
340+
lastEventAt: Date.now(),
341+
});
342+
}
343+
throw new Error(
344+
`background task update suppressed: ${sendResult.suppressionReason ?? "unknown reason"}`,
345+
);
346+
}
330347
if (afterSend.terminalOutcome === "blocked") {
331348
queueBlockedTaskFollowup(afterSend);
332349
}
@@ -420,7 +437,7 @@ async function maybeDeliverTaskStateChangeUpdateUnderAdmission(
420437
latestEvent,
421438
owner,
422439
});
423-
await sendMessage({
440+
const sendResult = await sendMessage({
424441
channel: owner.requesterOrigin?.channel,
425442
to: owner.requesterOrigin?.to ?? "",
426443
accountId: owner.requesterOrigin?.accountId,
@@ -434,6 +451,19 @@ async function maybeDeliverTaskStateChangeUpdateUnderAdmission(
434451
idempotencyKey,
435452
},
436453
});
454+
if (sendResult.deliveryStatus === "suppressed") {
455+
if (sendResult.suppressionReason !== "adapter_returned_no_identity") {
456+
throw new Error(
457+
`background task state change suppressed: ${sendResult.suppressionReason ?? "unknown reason"}`,
458+
);
459+
}
460+
taskRegistryLog.warn("Background task state change delivery was not confirmed", {
461+
taskId,
462+
ownerKey: current.ownerKey,
463+
requesterOrigin: owner.requesterOrigin,
464+
suppressionReason: sendResult.suppressionReason,
465+
});
466+
}
437467
upsertTaskDeliveryState({
438468
taskId,
439469
requesterOrigin: deliveryState?.requesterOrigin,

0 commit comments

Comments
 (0)