Skip to content

Commit 500c9b4

Browse files
authored
fix(outbound): prevent remote gateway duplicate sends (#128202)
When the agent runtime talks to a remote Gateway (gateway.mode "remote" or a gatewayUrl/gatewayToken override), the message tool withholds the runtime identity, so a proven-not-sent outbound failure kept its durable retry row and also surfaced as an error the model would answer by resending — a duplicate once the queue replayed the row. - deliver-queue-execute: mark the thrown error recoveryOwnedRetry when the proven-not-sent row stays replay-eligible (one retry owner per row) - message.action: additive UNAVAILABLE detail code OUTBOUND_DELIVERY_QUEUED - message tool: project that error into a non-throwing delivery_queued result ("queued, will retry automatically, do not resend") and keep the autogenerated idempotency-key mapping so an identical resend collapses Validated with unit tests and a real-Telegram remote-gateway E2E (affected on main: duplicate; fixed: single send, delivery_queued). Closes #124279 Co-authored-by: Ayaan Zaidi <[email protected]>
1 parent 056d6a1 commit 500c9b4

14 files changed

Lines changed: 249 additions & 44 deletions

File tree

‎apps/shared/OpenClawKit/Sources/OpenClawProtocol/GatewayModels.swift‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1804,6 +1804,20 @@ public struct McpAppViewExpiredErrorDetails: Codable, Sendable {
18041804
}
18051805
}
18061806

1807+
public struct OutboundDeliveryQueuedErrorDetails: Codable, Sendable {
1808+
public let code: String
1809+
1810+
public init(
1811+
code: String)
1812+
{
1813+
self.code = code
1814+
}
1815+
1816+
private enum CodingKeys: String, CodingKey {
1817+
case code
1818+
}
1819+
}
1820+
18071821
public struct SkillProposalRevisionChangedErrorDetails: Codable, Sendable {
18081822
public let code: String
18091823
public let expectedrevisionhash: String
@@ -21544,6 +21558,7 @@ public enum GatewayErrorDetails: Codable, Sendable {
2154421558
case cronJobNotFound(CronJobNotFoundErrorDetails)
2154521559
case missingScope(MissingScopeErrorDetails)
2154621560
case mcpAppViewExpired(McpAppViewExpiredErrorDetails)
21561+
case outboundDeliveryQueued(OutboundDeliveryQueuedErrorDetails)
2154721562
case userPrefsLimitExceeded(UserPrefsLimitExceededErrorDetails)
2154821563
case skillProposalRevisionChanged(SkillProposalRevisionChangedErrorDetails)
2154921564
case projectCloneFailed(ProjectCloneErrorDetails)
@@ -21565,6 +21580,7 @@ public enum GatewayErrorDetails: Codable, Sendable {
2156521580
case .cronJobNotFound(let value): value.code
2156621581
case .missingScope(let value): value.code
2156721582
case .mcpAppViewExpired(let value): value.code
21583+
case .outboundDeliveryQueued(let value): value.code
2156821584
case .userPrefsLimitExceeded(let value): value.code
2156921585
case .skillProposalRevisionChanged(let value): value.code
2157021586
case .projectCloneFailed(let value): value.code
@@ -21594,6 +21610,7 @@ public enum GatewayErrorDetails: Codable, Sendable {
2159421610
case "CRON_JOB_NOT_FOUND": self = try .cronJobNotFound(CronJobNotFoundErrorDetails(from: decoder))
2159521611
case "MISSING_SCOPE": self = try .missingScope(MissingScopeErrorDetails(from: decoder))
2159621612
case "MCP_APP_VIEW_EXPIRED": self = try .mcpAppViewExpired(McpAppViewExpiredErrorDetails(from: decoder))
21613+
case "OUTBOUND_DELIVERY_QUEUED": self = try .outboundDeliveryQueued(OutboundDeliveryQueuedErrorDetails(from: decoder))
2159721614
case "USER_PREFS_LIMIT_EXCEEDED": self = try .userPrefsLimitExceeded(UserPrefsLimitExceededErrorDetails(from: decoder))
2159821615
case "SKILL_PROPOSAL_REVISION_CHANGED": self = try .skillProposalRevisionChanged(SkillProposalRevisionChangedErrorDetails(from: decoder))
2159921616
case "PROJECT_CLONE_FAILED": self = try .projectCloneFailed(ProjectCloneErrorDetails(from: decoder))
@@ -21613,6 +21630,7 @@ public enum GatewayErrorDetails: Codable, Sendable {
2161321630
case .cronJobNotFound(let value): try value.encode(to: encoder)
2161421631
case .missingScope(let value): try value.encode(to: encoder)
2161521632
case .mcpAppViewExpired(let value): try value.encode(to: encoder)
21633+
case .outboundDeliveryQueued(let value): try value.encode(to: encoder)
2161621634
case .userPrefsLimitExceeded(let value): try value.encode(to: encoder)
2161721635
case .skillProposalRevisionChanged(let value): try value.encode(to: encoder)
2161821636
case .projectCloneFailed(let value): try value.encode(to: encoder)

‎packages/gateway-protocol/src/error-details.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ export type {
1515
CronJobNotFoundErrorDetails,
1616
GatewayErrorDetails,
1717
McpAppViewExpiredErrorDetails,
18+
OutboundDeliveryQueuedErrorDetails,
1819
MissingScopeErrorDetails,
1920
SkillProposalRevisionChangedErrorDetails,
2021
UserPrefsLimitExceededErrorDetails,
@@ -26,6 +27,7 @@ export {
2627
CronJobNotFoundErrorDetailsSchema,
2728
GatewayErrorDetailsSchema,
2829
MissingScopeErrorDetailsSchema,
30+
OutboundDeliveryQueuedErrorDetailsSchema,
2931
UserPrefsLimitExceededErrorDetailsSchema,
3032
ProjectCloneErrorDetailsSchema,
3133
SkillProposalRevisionChangedErrorDetailsSchema,

‎packages/gateway-protocol/src/gateway-error-details.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ export const GatewayErrorDetailCodes = {
2626
CRON_JOB_NOT_FOUND: "CRON_JOB_NOT_FOUND",
2727
MISSING_SCOPE: "MISSING_SCOPE",
2828
MCP_APP_VIEW_EXPIRED: "MCP_APP_VIEW_EXPIRED",
29+
OUTBOUND_DELIVERY_QUEUED: "OUTBOUND_DELIVERY_QUEUED",
2930
USER_PREFS_LIMIT_EXCEEDED: "USER_PREFS_LIMIT_EXCEEDED",
3031
SESSION_COMPANION_BUSY: "SESSION_COMPANION_BUSY",
3132
SKILL_PROPOSAL_REVISION_CHANGED: "SKILL_PROPOSAL_REVISION_CHANGED",
@@ -51,6 +52,10 @@ export type McpAppViewExpiredErrorDetails = {
5152
code: typeof GatewayErrorDetailCodes.MCP_APP_VIEW_EXPIRED;
5253
};
5354

55+
export type OutboundDeliveryQueuedErrorDetails = {
56+
code: typeof GatewayErrorDetailCodes.OUTBOUND_DELIVERY_QUEUED;
57+
};
58+
5459
/** Per-profile preference quota details returned by users.prefs.set. */
5560
export type UserPrefsLimitExceededErrorDetails = {
5661
code: typeof GatewayErrorDetailCodes.USER_PREFS_LIMIT_EXCEEDED;
@@ -94,6 +99,7 @@ export type GatewayErrorDetails =
9499
| CronJobNotFoundErrorDetails
95100
| MissingScopeErrorDetails
96101
| McpAppViewExpiredErrorDetails
102+
| OutboundDeliveryQueuedErrorDetails
97103
| UserPrefsLimitExceededErrorDetails
98104
| SkillProposalRevisionChangedErrorDetails
99105
| ProjectCloneErrorDetails

‎packages/gateway-protocol/src/schema/error-codes.test.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import {
88
isMcpAppViewExpiredError,
99
McpAppViewExpiredErrorDetailsSchema,
1010
MissingScopeErrorDetailsSchema,
11+
OutboundDeliveryQueuedErrorDetailsSchema,
1112
ProjectCloneErrorDetailsSchema,
1213
SkillProposalRevisionChangedErrorDetailsSchema,
1314
missingScopeErrorShape,
@@ -54,6 +55,15 @@ describe("gateway error details", () => {
5455
expect(isMcpAppViewExpiredError(new Error("upstream token expired"))).toBe(false);
5556
});
5657

58+
it("validates queued outbound delivery details", () => {
59+
const details = { code: GatewayErrorDetailCodes.OUTBOUND_DELIVERY_QUEUED };
60+
expect(Value.Check(OutboundDeliveryQueuedErrorDetailsSchema, details)).toBe(true);
61+
expect(Value.Check(GatewayErrorDetailsSchema, details)).toBe(true);
62+
expect(Value.Check(OutboundDeliveryQueuedErrorDetailsSchema, { ...details, retry: true })).toBe(
63+
false,
64+
);
65+
});
66+
5767
it("validates unknown-agent details", () => {
5868
const details = { code: GatewayErrorDetailCodes.UNKNOWN_AGENT_ID, agentId: "retired" };
5969
expect(Value.Check(UnknownAgentIdErrorDetailsSchema, details)).toBe(true);

‎packages/gateway-protocol/src/schema/error-codes.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ export {
1717
type ErrorCode,
1818
type GatewayErrorDetails,
1919
type McpAppViewExpiredErrorDetails,
20+
type OutboundDeliveryQueuedErrorDetails,
2021
type MissingScopeErrorDetails,
2122
type SkillProposalRevisionChangedErrorDetails,
2223
type UserPrefsLimitExceededErrorDetails,
@@ -48,6 +49,10 @@ export const McpAppViewExpiredErrorDetailsSchema = closedObject({
4849
code: Type.Literal(GatewayErrorDetailCodes.MCP_APP_VIEW_EXPIRED),
4950
});
5051

52+
export const OutboundDeliveryQueuedErrorDetailsSchema = closedObject({
53+
code: Type.Literal(GatewayErrorDetailCodes.OUTBOUND_DELIVERY_QUEUED),
54+
});
55+
5156
export const UserPrefsLimitExceededErrorDetailsSchema = closedObject({
5257
code: Type.Literal(GatewayErrorDetailCodes.USER_PREFS_LIMIT_EXCEEDED),
5358
limit: Type.Integer({ minimum: 1 }),
@@ -83,6 +88,7 @@ export const GatewayErrorDetailsSchema = Type.Union([
8388
CronJobNotFoundErrorDetailsSchema,
8489
MissingScopeErrorDetailsSchema,
8590
McpAppViewExpiredErrorDetailsSchema,
91+
OutboundDeliveryQueuedErrorDetailsSchema,
8692
UserPrefsLimitExceededErrorDetailsSchema,
8793
SkillProposalRevisionChangedErrorDetailsSchema,
8894
ProjectCloneErrorDetailsSchema,

‎packages/gateway-protocol/src/schema/protocol-schema-fragment-transport.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ export const TransportProtocolSchemas = {
1919
CronJobNotFoundErrorDetails: errorCodes.CronJobNotFoundErrorDetailsSchema,
2020
MissingScopeErrorDetails: errorCodes.MissingScopeErrorDetailsSchema,
2121
McpAppViewExpiredErrorDetails: errorCodes.McpAppViewExpiredErrorDetailsSchema,
22+
OutboundDeliveryQueuedErrorDetails: errorCodes.OutboundDeliveryQueuedErrorDetailsSchema,
2223
SkillProposalRevisionChangedErrorDetails:
2324
errorCodes.SkillProposalRevisionChangedErrorDetailsSchema,
2425
UnknownAgentIdErrorDetails: errorCodes.UnknownAgentIdErrorDetailsSchema,
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
import { describe, expect, it, vi } from "vitest";
2+
import { GatewayClientRequestError } from "../../../packages/gateway-client/src/request-error.js";
3+
import {
4+
ErrorCodes,
5+
GatewayErrorDetailCodes,
6+
} from "../../../packages/gateway-protocol/src/gateway-error-details.js";
7+
import { createMessageTool } from "./message-tool-execution.js";
8+
9+
const EMPTY_CATALOG = {
10+
version: 0,
11+
channels: [],
12+
getChannel: () => undefined,
13+
} as const;
14+
15+
function createFailingMessageTool(error: Error) {
16+
const runMessageAction = vi.fn(async () => {
17+
throw error;
18+
});
19+
const tool = createMessageTool({
20+
config: {},
21+
runId: "run-queued-delivery",
22+
preparedMessageToolCatalog: EMPTY_CATALOG,
23+
sourceReplyOnly: true,
24+
sourceReplyDeliveryMode: "message_tool_only",
25+
currentChannelProvider: "telegram",
26+
currentChannelId: "chat-123",
27+
currentMessagingTarget: "chat-123",
28+
getScopedChannelsCommandSecretTargets: () => ({ targetIds: new Set<string>() }),
29+
resolveCommandSecretRefsViaGateway: async ({ config }) => ({
30+
resolvedConfig: config,
31+
diagnostics: [],
32+
targetStatesByPath: {},
33+
hadUnresolvedTargets: false,
34+
}),
35+
runMessageAction,
36+
});
37+
return { tool, runMessageAction };
38+
}
39+
40+
function sentIdempotencyKey(runMessageAction: ReturnType<typeof vi.fn>, call: number) {
41+
const request = runMessageAction.mock.calls[call]?.[0] as
42+
| { params?: { idempotencyKey?: string } }
43+
| undefined;
44+
return request?.params?.idempotencyKey;
45+
}
46+
47+
describe("message tool queued gateway delivery", () => {
48+
it("returns a do-not-resend result when the gateway owns the retry", async () => {
49+
const { tool, runMessageAction } = createFailingMessageTool(
50+
new GatewayClientRequestError({
51+
code: ErrorCodes.UNAVAILABLE,
52+
message: "connect ECONNREFUSED",
53+
details: { code: GatewayErrorDetailCodes.OUTBOUND_DELIVERY_QUEUED },
54+
}),
55+
);
56+
57+
const result = await tool.execute("queued-send", { action: "send", message: "hello" });
58+
59+
expect(result).toMatchObject({
60+
details: {
61+
status: "delivery_queued",
62+
delivered: false,
63+
message:
64+
"Message not delivered: connect ECONNREFUSED. The gateway queued it and will retry automatically. Do not resend it.",
65+
},
66+
});
67+
68+
// A model that resends anyway must reuse the queued key so the gateway's
69+
// idempotency cache answers instead of a second durable send.
70+
await tool.execute("queued-send-again", { action: "send", message: "hello" });
71+
expect(sentIdempotencyKey(runMessageAction, 0)).toBeDefined();
72+
expect(sentIdempotencyKey(runMessageAction, 1)).toBe(sentIdempotencyKey(runMessageAction, 0));
73+
});
74+
75+
it("keeps an unstructured unavailable error throwable", async () => {
76+
const error = new GatewayClientRequestError({
77+
code: ErrorCodes.UNAVAILABLE,
78+
message: "connect ECONNREFUSED",
79+
});
80+
const { tool } = createFailingMessageTool(error);
81+
82+
await expect(
83+
tool.execute("ordinary-failure", { action: "send", message: "hello" }),
84+
).rejects.toBe(error);
85+
});
86+
});

‎src/agents/tools/message-tool-execution.ts‎

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ import type {
3131
MessageActionGateway,
3232
MessageActionResult,
3333
} from "../../infra/outbound/message-action-contracts.js";
34+
import { projectGatewayQueuedDeliveryResult } from "../../infra/outbound/message-action-execution.js";
3435
import { getToolResult, runMessageAction } from "../../infra/outbound/message-action-runner.js";
3536
import { resolveActionDeliveryTargetAlias } from "../../infra/outbound/message-action-spec.js";
3637
import { stringifyRouteThreadId } from "../../plugin-sdk/channel-route.js";
@@ -87,22 +88,15 @@ function resolveTrustedDecisionChannel(
8788
}
8889

8990
function normalizeMessageToolIdempotencyKeyPart(value: unknown): string | undefined {
90-
const normalized = normalizeOptionalString(value);
91-
if (!normalized) {
92-
return undefined;
93-
}
94-
return normalized.replace(/[^A-Za-z0-9._:-]+/gu, "_");
91+
return normalizeOptionalString(value)?.replace(/[^A-Za-z0-9._:-]+/gu, "_");
9592
}
9693

97-
const MESSAGE_TOOL_IDEMPOTENCY_ENVELOPE_PARAM_NAMES = [
94+
const MESSAGE_TOOL_IDEMPOTENCY_ENVELOPE_PARAM_KEYS = new Set<string>([
9895
"gatewayToken",
9996
"gatewayUrl",
10097
"idempotencyKey",
10198
"timeoutMs",
102-
] satisfies Array<keyof GatewayCallOptions | "idempotencyKey">;
103-
const MESSAGE_TOOL_IDEMPOTENCY_ENVELOPE_PARAM_KEYS = new Set<string>(
104-
MESSAGE_TOOL_IDEMPOTENCY_ENVELOPE_PARAM_NAMES,
105-
);
99+
] satisfies Array<keyof GatewayCallOptions | "idempotencyKey">);
106100

107101
function stripMessageToolIdempotencyEnvelope(
108102
params: Record<string, unknown>,
@@ -694,6 +688,13 @@ export function createMessageTool(options?: MessageToolOptions): AnyAgentTool {
694688
actionIdempotencyKey,
695689
);
696690
}
691+
// Queue-owned retry: the gateway already holds the durable row and
692+
// caches this outcome under the same idempotency key, so a model resend
693+
// of the same content collapses instead of minting a second send.
694+
const queuedDelivery = projectGatewayQueuedDeliveryResult(error);
695+
if (queuedDelivery) {
696+
return jsonResult(queuedDelivery);
697+
}
697698
decisions.recordTypedDenial(error);
698699
throw error;
699700
}

‎src/gateway/server-methods/send.test.ts‎

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,10 @@ import {
99
GATEWAY_CLIENT_MODES,
1010
GATEWAY_CLIENT_NAMES,
1111
} from "../../../packages/gateway-protocol/src/client-info.js";
12-
import { ErrorCodes } from "../../../packages/gateway-protocol/src/index.js";
12+
import {
13+
ErrorCodes,
14+
GatewayErrorDetailCodes,
15+
} from "../../../packages/gateway-protocol/src/index.js";
1316
import { createDeferred } from "../../../test/helpers/promise.js";
1417
import { createOperationalRunInstanceRef } from "../../agents/admitted-run-context.js";
1518
import { jsonResult } from "../../agents/tools/common.js";
@@ -19,6 +22,7 @@ import {
1922
claimAgentRunDelegatedAuthority,
2023
releaseAgentRunDelegatedAuthority,
2124
} from "../../infra/agent-run-registry.js";
25+
import { OutboundDeliveryError } from "../../infra/outbound/deliver-types.js";
2226
import { buildOutboundMediaLoadOptions } from "../../media/load-options.js";
2327
import { loadWebMediaRaw } from "../../media/web-media.js";
2428
import { resetPluginRuntimeStateForTest, setActivePluginRegistry } from "../../plugins/runtime.js";
@@ -1456,6 +1460,40 @@ describe("gateway send mirroring", () => {
14561460
},
14571461
);
14581462

1463+
it.each([
1464+
["queue-owned retry", true],
1465+
["ordinary failure", false],
1466+
])("reports structured details for %s", async (_label, recoveryOwnedRetry) => {
1467+
const dispatchError = new OutboundDeliveryError("connect ECONNREFUSED", {
1468+
cause: new Error("connect ECONNREFUSED"),
1469+
stage: "platform_send",
1470+
});
1471+
if (recoveryOwnedRetry) {
1472+
dispatchError.recoveryOwnedRetry = true;
1473+
}
1474+
mocks.dispatchChannelMessageAction.mockRejectedValueOnce(dispatchError);
1475+
1476+
const { respond } = await runMessageActionRequest(
1477+
{
1478+
channel: "slack",
1479+
action: "send",
1480+
params: { channelId: "C1", message: "hi" },
1481+
idempotencyKey: `idem-queued-detail-${recoveryOwnedRetry}`,
1482+
},
1483+
directCliClient(),
1484+
);
1485+
1486+
const error = firstRespondCall(respond)[2];
1487+
expect(error).toMatchObject({ code: ErrorCodes.UNAVAILABLE });
1488+
if (recoveryOwnedRetry) {
1489+
expect(error?.details).toEqual({
1490+
code: GatewayErrorDetailCodes.OUTBOUND_DELIVERY_QUEUED,
1491+
});
1492+
} else {
1493+
expect(error).not.toHaveProperty("details");
1494+
}
1495+
});
1496+
14591497
it("does not send after delegated authority closes during session preparation", async () => {
14601498
const preparation = createDeferred<null>();
14611499
mocks.resolveOutboundSessionRoute.mockReturnValueOnce(preparation.promise);

‎src/gateway/server-methods/send.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import {
77
} from "@openclaw/normalization-core/string-coerce";
88
import {
99
ErrorCodes,
10+
GatewayErrorDetailCodes,
1011
errorShape,
1112
validateMessageActionParams,
1213
validatePollParams,
@@ -29,6 +30,7 @@ import {
2930
import type { OpenClawConfig } from "../../config/types.openclaw.js";
3031
import { resolveOutboundChannelPlugin } from "../../infra/outbound/channel-resolution.js";
3132
import { resolveMessageChannelSelection } from "../../infra/outbound/channel-selection.js";
33+
import { OutboundDeliveryError } from "../../infra/outbound/deliver-types.js";
3234
import { validateExplicitMessageAccountSelection } from "../../infra/outbound/message-account-selection.js";
3335
import {
3436
hydrateAttachmentParamsForAction,
@@ -837,7 +839,13 @@ function createGatewayInflightUnavailableFailure(params: {
837839
channel: string;
838840
err: unknown;
839841
}): InflightResult {
840-
const error = errorShape(ErrorCodes.UNAVAILABLE, String(params.err));
842+
const error = errorShape(
843+
ErrorCodes.UNAVAILABLE,
844+
String(params.err),
845+
params.err instanceof OutboundDeliveryError && params.err.recoveryOwnedRetry === true
846+
? { details: { code: GatewayErrorDetailCodes.OUTBOUND_DELIVERY_QUEUED } }
847+
: undefined,
848+
);
841849
return createGatewayInflightResult({
842850
...params,
843851
result: { ok: false, error },

0 commit comments

Comments
 (0)