Skip to content

Commit 5af6df9

Browse files
committed
fix(cron): mirror announce delivery into session transcripts
1 parent efd88dc commit 5af6df9

2 files changed

Lines changed: 149 additions & 1 deletion

File tree

‎src/cron/delivery.failure-notify.test.ts‎

Lines changed: 82 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,8 @@ vi.mock("../logging.js", () => ({
3636
})),
3737
}));
3838

39-
const { sendFailureNotificationAnnounce } = await import("./delivery.js");
39+
const { sendCronAnnouncePayloadStrict, sendFailureNotificationAnnounce } =
40+
await import("./delivery.js");
4041

4142
type DeliveryRequest = {
4243
abortSignal?: unknown;
@@ -46,6 +47,12 @@ type DeliveryRequest = {
4647
channel?: string;
4748
deps?: unknown;
4849
identity?: unknown;
50+
mirror?: {
51+
agentId?: string;
52+
idempotencyKey?: string;
53+
sessionKey?: string;
54+
text?: string;
55+
};
4956
payloads?: unknown;
5057
session?: unknown;
5158
threadId?: number;
@@ -119,6 +126,80 @@ describe("sendFailureNotificationAnnounce", () => {
119126
expect(deliveryRequest.abortSignal).toBeInstanceOf(AbortSignal);
120127
});
121128

129+
it("mirrors successful announces into custom delivery session transcripts", async () => {
130+
const abortController = new AbortController();
131+
132+
await sendCronAnnouncePayloadStrict({
133+
deps: {} as never,
134+
cfg: {} as never,
135+
agentId: "main",
136+
jobId: "job-1",
137+
target: {
138+
channel: "telegram",
139+
sessionKey: "agent:main:session:daily-digest",
140+
},
141+
message: "Cron summary",
142+
abortSignal: abortController.signal,
143+
});
144+
145+
const [deliveryRequest] = mocks.deliverOutboundPayloads.mock.calls[0] as [
146+
{
147+
mirror?: {
148+
agentId?: string;
149+
idempotencyKey?: string;
150+
sessionKey?: string;
151+
text?: string;
152+
};
153+
},
154+
];
155+
expect(deliveryRequest.mirror).toMatchObject({
156+
sessionKey: "agent:main:session:daily-digest",
157+
agentId: "main",
158+
text: "Cron summary",
159+
});
160+
expect(deliveryRequest.mirror?.idempotencyKey).toMatch(/^cron-announce-mirror:v1:job-1:/);
161+
});
162+
163+
it("skips mirrors for routed peer session keys to avoid active chat lock races", async () => {
164+
const abortController = new AbortController();
165+
166+
await sendCronAnnouncePayloadStrict({
167+
deps: {} as never,
168+
cfg: {} as never,
169+
agentId: "main",
170+
jobId: "job-1",
171+
target: {
172+
channel: "telegram",
173+
sessionKey: "agent:main:telegram:direct:123:thread:99",
174+
},
175+
message: "Cron summary",
176+
abortSignal: abortController.signal,
177+
});
178+
179+
const deliveryRequest = firstDeliveryRequest();
180+
expect(deliveryRequest.mirror).toBeUndefined();
181+
});
182+
183+
it("skips mirrors for legacy dm routed peer session keys", async () => {
184+
const abortController = new AbortController();
185+
186+
await sendCronAnnouncePayloadStrict({
187+
deps: {} as never,
188+
cfg: {} as never,
189+
agentId: "main",
190+
jobId: "job-1",
191+
target: {
192+
channel: "telegram",
193+
sessionKey: "agent:main:telegram:dm:123:thread:99",
194+
},
195+
message: "Cron summary",
196+
abortSignal: abortController.signal,
197+
});
198+
199+
const deliveryRequest = firstDeliveryRequest();
200+
expect(deliveryRequest.mirror).toBeUndefined();
201+
});
202+
122203
it("uses sessionKey for delivery-target resolution and outbound context", async () => {
123204
await sendFailureNotificationAnnounce(
124205
{} as never,

‎src/cron/delivery.ts‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { createHash } from "node:crypto";
12
import { sendDurableMessageBatch } from "../channels/message/runtime.js";
23
import type { CliDeps } from "../cli/deps.types.js";
34
import { createOutboundSendDeps } from "../cli/outbound-send-deps.js";
@@ -6,6 +7,7 @@ import { formatErrorMessage } from "../infra/errors.js";
67
import { resolveAgentOutboundIdentity } from "../infra/outbound/identity.js";
78
import { buildOutboundSessionContext } from "../infra/outbound/session-context.js";
89
import { getChildLogger } from "../logging.js";
10+
import { parseAgentSessionKey, parseThreadSessionSuffix } from "../routing/session-key.js";
911
import {
1012
resolveFailureDestination,
1113
type CronFailureDeliveryPlan,
@@ -30,6 +32,7 @@ export {
3032

3133
const FAILURE_NOTIFICATION_TIMEOUT_MS = 30_000;
3234
const cronDeliveryLogger = getChildLogger({ subsystem: "cron-delivery" });
35+
const ROUTED_PEER_SESSION_KINDS = new Set(["direct", "dm", "group", "channel"]);
3336

3437
export type CronAnnounceTarget = {
3538
channel?: string;
@@ -40,6 +43,48 @@ export type CronAnnounceTarget = {
4043

4144
type SuccessfulDeliveryTarget = Extract<DeliveryTargetResolution, { ok: true }>;
4245

46+
function buildCronAnnounceMirrorIdempotencyKey(params: {
47+
jobId: string;
48+
target: SuccessfulDeliveryTarget;
49+
message: string;
50+
}): string {
51+
const digest = createHash("sha256")
52+
.update(
53+
JSON.stringify([
54+
params.target.channel,
55+
params.target.accountId ?? "",
56+
params.target.to,
57+
params.target.threadId ?? "",
58+
params.message,
59+
]),
60+
)
61+
.digest("hex")
62+
.slice(0, 24);
63+
return `cron-announce-mirror:v1:${params.jobId}:${digest}`;
64+
}
65+
66+
function isRoutedPeerSessionKey(sessionKey: string): boolean {
67+
const { baseSessionKey } = parseThreadSessionSuffix(sessionKey);
68+
const parsed = parseAgentSessionKey(baseSessionKey ?? sessionKey);
69+
if (!parsed) {
70+
return false;
71+
}
72+
73+
const parts = parsed.rest.split(":").filter(Boolean);
74+
const peerKind = parts.length >= 2 ? parts[parts.length - 2] : undefined;
75+
return typeof peerKind === "string" && ROUTED_PEER_SESSION_KINDS.has(peerKind);
76+
}
77+
78+
function resolveCronAnnounceMirrorSessionKey(sessionKey: string | undefined): string | undefined {
79+
const trimmed = sessionKey?.trim();
80+
if (!trimmed) {
81+
return undefined;
82+
}
83+
// Routed peer sessions can be active embedded conversations. Mirror only
84+
// into custom/main session keys here so cron delivery does not race locks.
85+
return isRoutedPeerSessionKey(trimmed) ? undefined : trimmed;
86+
}
87+
4388
async function resolveCronAnnounceDelivery(params: {
4489
cfg: OpenClawConfig;
4590
agentId: string;
@@ -51,6 +96,7 @@ async function resolveCronAnnounceDelivery(params: {
5196
resolvedTarget: SuccessfulDeliveryTarget;
5297
session: ReturnType<typeof buildOutboundSessionContext>;
5398
identity: ReturnType<typeof resolveAgentOutboundIdentity>;
99+
mirrorSessionKey?: string;
54100
}
55101
| { ok: false; error: Error }
56102
> {
@@ -74,12 +120,14 @@ async function resolveCronAnnounceDelivery(params: {
74120
sessionKey: params.target.sessionKey,
75121
}),
76122
});
123+
const mirrorSessionKey = resolveCronAnnounceMirrorSessionKey(params.target.sessionKey);
77124

78125
return {
79126
ok: true,
80127
resolvedTarget,
81128
session,
82129
identity,
130+
...(mirrorSessionKey ? { mirrorSessionKey } : {}),
83131
};
84132
}
85133

@@ -90,7 +138,10 @@ async function deliverCronAnnouncePayload(params: {
90138
resolvedTarget: SuccessfulDeliveryTarget;
91139
session: ReturnType<typeof buildOutboundSessionContext>;
92140
identity: ReturnType<typeof resolveAgentOutboundIdentity>;
141+
mirrorSessionKey?: string;
93142
};
143+
agentId: string;
144+
jobId: string;
94145
message: string;
95146
abortSignal: AbortSignal;
96147
}): Promise<void> {
@@ -106,6 +157,18 @@ async function deliverCronAnnouncePayload(params: {
106157
bestEffort: false,
107158
deps: createOutboundSendDeps(params.deps),
108159
signal: params.abortSignal,
160+
mirror: params.delivery.mirrorSessionKey
161+
? {
162+
sessionKey: params.delivery.mirrorSessionKey,
163+
agentId: params.agentId,
164+
text: params.message,
165+
idempotencyKey: buildCronAnnounceMirrorIdempotencyKey({
166+
jobId: params.jobId,
167+
target: params.delivery.resolvedTarget,
168+
message: params.message,
169+
}),
170+
}
171+
: undefined,
109172
});
110173
if (send.status === "failed" || send.status === "partial_failed") {
111174
throw send.error;
@@ -129,6 +192,8 @@ export async function sendCronAnnouncePayloadStrict(params: {
129192
deps: params.deps,
130193
cfg: params.cfg,
131194
delivery,
195+
agentId: params.agentId,
196+
jobId: params.jobId,
132197
message: params.message,
133198
abortSignal: params.abortSignal,
134199
});
@@ -162,6 +227,8 @@ export async function sendFailureNotificationAnnounce(
162227
deps,
163228
cfg,
164229
delivery,
230+
agentId,
231+
jobId,
165232
message,
166233
abortSignal: abortController.signal,
167234
});

0 commit comments

Comments
 (0)