Skip to content

Commit c49714f

Browse files
harjothkharaclaudevincentkoc
authored
fix(agents): don't inject A2A turns into isolated-cron sessions_send (#92257) (#92283)
* fix(agents): don't inject A2A turns into isolated-cron sessions_send (#92257) Fire-and-forget sessions_send (timeoutSeconds === 0) with announce delivery runs the A2A ping-pong loop. For a cross-session send (requester != target) the loop's first iteration feeds the target agent's reply back into the requester session as a new turn. For a normal requester that roundtrip is intended, but for an *isolated cron* requester it injects reply context into the isolated run and causes an agent feedback loop. Narrow the fix to isolated-cron requesters only (detected by a session key containing ":cron:" or channel "cron" -- the same signal used by src/agents/subagent-registry.ts and set in src/cron/isolated-agent/run.ts), NOT by timeoutSeconds. Gating on timeoutSeconds was too broad: it disabled the intended ping-pong for normal cross-session fire-and-forget sends. Two hunks in src/agents/tools/sessions-send-tool.ts, both reusing one `isIsolatedCronRequester` gate: 1. Force maxPingPongTurns to 0 in the runSessionsSendA2AFlow invocation only for an isolated-cron requester. The a2a flow's ping-pong guard (`maxPingPongTurns > 0`) then skips the requester-injection loop and proceeds straight to the announce step in the TARGET session, preserving fire-and-forget announce delivery. Normal requesters keep the configured turn count. 2. Read baselineReply for fire-and-forget sends when same-session (prior behavior) OR isolated-cron. Without a baseline fingerprint, a2a.ts would treat pre-existing assistant text in the target session (e.g. an unrelated concurrent cron's output) as "the reply" and misattribute it. The normal cross-session fire leg's history-call count is unchanged from origin/main. Read failures are tolerated so a snapshot error never blocks accepting the send. Tests (sessions.test.ts): an isolated-cron cross-session fire-and-forget forwards maxPingPongTurns: 0; a normal-requester regression guard (discord:group:req / channel discord) forwards the configured turn count (not 0), proving the normal ping-pong is preserved. a2a flow tests (sessions-send-tool.a2a.test.ts): with turns=0 + requester!=target the requester is never stepped but the target is still announced, and a baseline-matching reply is neither injected nor announced. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(agents): gate isolated-cron A2A on canonical cron-run classifier (#92257) Address Codex [P2] review: replace the raw `:cron:` substring detector with the canonical isCronRunSessionKey so a non-canonical cron-like requester key (e.g. agent:main:slack:cron:job:run:uuid) keeps its intended cross-session ping-pong. Keep the requesterChannel === "cron" arm (isolated cron runs set that channel in src/cron/isolated-agent/run.ts). Add a regression covering the non-canonical key. * refactor(agents): drop dead cron-channel A2A arm, gate on canonical key only (#92257) The requesterChannel === "cron" arm was unreachable: agentChannel is always a DeliverableMessageChannel from resolveGatewayMessageChannel(messageProvider), never the literal "cron". The channel: "cron" in src/cron/isolated-agent/run.ts labels diagnostics events/lifecycle, not the tool channel. Gate on isCronRunSessionKey alone and fix the misleading comment. Tests drove the dead arm via agentChannel/requesterChannel "cron" plus a non-canonical key (agent:main:cron:run:abc, which isCronRunSessionKey rejects). Switch them to a canonical cron-run key (agent:main:cron:job:run:abc) and a normal delivery channel so they exercise the real production gate. * fix(agents): align cron A2A fallback baselines * chore: prepare branch refresh --------- Co-authored-by: Claude Fable 5 <[email protected]> Co-authored-by: Vincent Koc <[email protected]>
1 parent 273729b commit c49714f

4 files changed

Lines changed: 158 additions & 6 deletions

File tree

‎src/agents/openclaw-tools.sessions.test.ts‎

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1696,6 +1696,7 @@ describe("sessions tools", () => {
16961696

16971697
it("sessions_send falls back from stranded cron run key to durable cron parent", async () => {
16981698
const calls: Array<{ method?: string; params?: unknown }> = [];
1699+
const requesterKey = "agent:main:cron:source-job:run:source-run";
16991700
const runScopedCallerKey = "agent:leasing-ops:cron:monthly-utility:run:run-fast";
17001701
const durableCronCallerKey = "agent:leasing-ops:cron:monthly-utility";
17011702
const queueMessage = vi.fn(async () => {});
@@ -1714,14 +1715,33 @@ describe("sessions tools", () => {
17141715
callGatewayMock.mockImplementation(async (opts: unknown) => {
17151716
const request = opts as { method?: string; params?: unknown };
17161717
calls.push(request);
1718+
if (request.method === "chat.history") {
1719+
const params = request.params as { sessionKey?: string } | undefined;
1720+
const text =
1721+
params?.sessionKey === durableCronCallerKey
1722+
? "existing durable reply"
1723+
: "existing run reply";
1724+
return {
1725+
messages: [
1726+
{
1727+
role: "assistant",
1728+
content: [{ type: "text", text }],
1729+
timestamp: 20,
1730+
},
1731+
],
1732+
};
1733+
}
17171734
if (request.method === "agent") {
17181735
return { runId: "durable-fallback-run", status: "accepted", acceptedAt: 2000 };
17191736
}
1737+
if (request.method === "agent.wait") {
1738+
return { runId: "durable-fallback-run", status: "ok" };
1739+
}
17201740
return {};
17211741
});
17221742

17231743
const tool = createOpenClawTools({
1724-
agentSessionKey: "agent:re-portal:main",
1744+
agentSessionKey: requesterKey,
17251745
agentChannel: "telegram",
17261746
config: {
17271747
...TEST_CONFIG,
@@ -1752,6 +1772,25 @@ describe("sessions tools", () => {
17521772
expect(params.sessionKey).toBe(durableCronCallerKey);
17531773
expect(params.message).toContain("[Inter-session message]");
17541774
expect(params.message).toContain("[TASK-COMPLETE] re-portal occupancy ready");
1775+
await waitForCalls(
1776+
() =>
1777+
countMatching(
1778+
calls,
1779+
(call) =>
1780+
call.method === "chat.history" &&
1781+
(call.params as { sessionKey?: string } | undefined)?.sessionKey ===
1782+
durableCronCallerKey,
1783+
),
1784+
2,
1785+
);
1786+
const firstFallbackHistoryIndex = calls.findIndex(
1787+
(call) =>
1788+
call.method === "chat.history" &&
1789+
(call.params as { sessionKey?: string } | undefined)?.sessionKey === durableCronCallerKey,
1790+
);
1791+
const fallbackAgentIndex = calls.findIndex((call) => call.method === "agent");
1792+
expect(firstFallbackHistoryIndex).toBeLessThan(fallbackAgentIndex);
1793+
expect(calls.filter((call) => call.method === "agent")).toHaveLength(1);
17551794
});
17561795

17571796
it("sessions_send rejects non-cron run-looking keys without durable-session fallback", async () => {

‎src/agents/tools/sessions-send-tool.a2a.test.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -339,6 +339,27 @@ describe("runSessionsSendA2AFlow announce delivery", () => {
339339
expect(gatewayCalls.find((call) => call.method === "send")).toBeUndefined();
340340
});
341341

342+
it("skips requester steps when ping-pong is disabled but still announces from the target", async () => {
343+
const targetSessionKey = "agent:other:discord:group:ops";
344+
345+
await runSessionsSendA2AFlow({
346+
targetSessionKey,
347+
displayKey: targetSessionKey,
348+
message: "Test message",
349+
announceTimeoutMs: 10_000,
350+
maxPingPongTurns: 0,
351+
requesterSessionKey: "agent:main:cron:job:run:abc",
352+
requesterChannel: "telegram",
353+
roundOneReply: "Worker completed successfully",
354+
});
355+
356+
expect(runAgentStep).toHaveBeenCalledOnce();
357+
expect(firstMockArg(vi.mocked(runAgentStep), "agent step")).toMatchObject({
358+
sessionKey: targetSessionKey,
359+
message: "Agent-to-agent announce step.",
360+
});
361+
});
362+
342363
it.each(["NO_REPLY", "HEARTBEAT_OK", "ANNOUNCE_SKIP"])(
343364
"suppresses exact announce control reply %s before channel delivery",
344365
async (announceReply) => {

‎src/agents/tools/sessions-send-tool.ts‎

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -555,27 +555,43 @@ export function createSessionsSendTool(opts?: {
555555
const requesterSessionKey = opts?.agentSessionKey;
556556
const requesterChannel = opts?.agentChannel;
557557
const sameSessionA2A = requesterSessionKey === resolvedKey;
558+
const isIsolatedCronRequester = isCronRunSessionKey(requesterSessionKey);
559+
const fallbackA2ASessionKey =
560+
timeoutSeconds === 0 && isIsolatedCronRequester
561+
? resolveCronRunScopedFallbackSessionKey(displayKey)
562+
: undefined;
558563

559564
// Capture the pre-run assistant snapshot before starting the nested run.
560565
// Fast in-process test doubles and short-circuit agent paths can finish
561566
// before we reach the post-run read, which would otherwise make the new
562567
// reply look like the baseline and hide it from the caller.
563568
// Fire-and-forget same-session sends still need this baseline because the
564-
// A2A follow-up may deliver directly to the source channel.
569+
// A2A follow-up may deliver directly to the source channel. Isolated cron
570+
// requesters also need it to avoid attributing a stale target reply.
565571
const baselineReply =
566572
timeoutSeconds !== 0
567573
? await readLatestAssistantReplySnapshot({
568574
sessionKey: resolvedKey,
569575
limit: SESSIONS_SEND_REPLY_HISTORY_LIMIT,
570576
callGateway: gatewayCall,
571577
})
572-
: sameSessionA2A
578+
: sameSessionA2A || isIsolatedCronRequester
573579
? await readLatestAssistantReplySnapshot({
574580
sessionKey: resolvedKey,
575581
limit: SESSIONS_SEND_REPLY_HISTORY_LIMIT,
576582
callGateway: gatewayCall,
577583
}).catch(() => undefined)
578584
: undefined;
585+
// Active-run delivery can fall back to the durable cron parent. Snapshot
586+
// that target before dispatch so a fast reply cannot become its baseline.
587+
const fallbackBaselineReply =
588+
fallbackA2ASessionKey && fallbackA2ASessionKey !== resolvedKey
589+
? await readLatestAssistantReplySnapshot({
590+
sessionKey: fallbackA2ASessionKey,
591+
limit: SESSIONS_SEND_REPLY_HISTORY_LIMIT,
592+
callGateway: gatewayCall,
593+
}).catch(() => undefined)
594+
: undefined;
579595

580596
const agentMessageContext = buildAgentToAgentMessageContext({
581597
requesterSessionKey: opts?.agentSessionKey,
@@ -653,15 +669,19 @@ export function createSessionsSendTool(opts?: {
653669
if (skipA2AFlow) {
654670
return;
655671
}
672+
const flowBaseline =
673+
flowTargetSessionKey === fallbackA2ASessionKey ? fallbackBaselineReply : baselineReply;
656674
void runSessionsSendA2AFlow({
657675
targetSessionKey: flowTargetSessionKey,
658676
displayKey: flowDisplayKey,
659677
message,
660678
announceTimeoutMs,
661-
maxPingPongTurns,
679+
// Cron runs are isolated jobs; target replies must not become new
680+
// requester turns, but the target-side announce still runs.
681+
maxPingPongTurns: isIsolatedCronRequester ? 0 : maxPingPongTurns,
662682
requesterSessionKey,
663683
requesterChannel,
664-
baseline: baselineReply,
684+
baseline: flowBaseline,
665685
roundOneReply,
666686
waitRunId,
667687
});

‎src/agents/tools/sessions.test.ts‎

Lines changed: 73 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ vi.mock("../../gateway/call.js", () => ({
1515
}));
1616

1717
type SessionsToolTestConfig = {
18-
session: { scope: "per-sender"; mainKey: string };
18+
session: { scope: "per-sender"; mainKey: string; agentToAgent?: { maxPingPongTurns: number } };
1919
tools: {
2020
agentToAgent: { enabled: boolean };
2121
sessions?: { visibility: "self" | "tree" | "agent" | "all" };
@@ -206,6 +206,52 @@ function createMainSessionsSendTool() {
206206
});
207207
}
208208

209+
async function executeFireAndForgetA2AFrom(requesterSessionKey: string) {
210+
const { runSessionsSendA2AFlow } = await import("./sessions-send-tool.a2a.js");
211+
vi.mocked(runSessionsSendA2AFlow).mockClear();
212+
const targetSessionKey = "agent:other:discord:group:ops";
213+
loadConfigMock.mockReturnValue({
214+
session: { scope: "per-sender", mainKey: "main", agentToAgent: { maxPingPongTurns: 5 } },
215+
tools: {
216+
agentToAgent: { enabled: true },
217+
sessions: { visibility: "all" },
218+
},
219+
});
220+
callGatewayMock.mockImplementation(async (opts: unknown) => {
221+
const request = opts as { method?: string };
222+
if (request.method === "sessions.list") {
223+
return {
224+
path: "/tmp/sessions.json",
225+
sessions: [{ key: targetSessionKey, kind: "group" }],
226+
};
227+
}
228+
if (request.method === "chat.history") {
229+
return { messages: [] };
230+
}
231+
if (request.method === "agent") {
232+
return { runId: "run-fire-and-forget", acceptedAt: 123 };
233+
}
234+
return {};
235+
});
236+
const tool = createSessionsSendTool({
237+
agentSessionKey: requesterSessionKey,
238+
agentChannel: "telegram",
239+
});
240+
241+
const result = await tool.execute("call-fire-and-forget", {
242+
sessionKey: targetSessionKey,
243+
message: "ping",
244+
timeoutSeconds: 0,
245+
});
246+
247+
expect(requireDetails(result).status).toBe("accepted");
248+
const flowParams = vi.mocked(runSessionsSendA2AFlow).mock.calls[0]?.[0];
249+
if (!flowParams) {
250+
throw new Error("expected A2A flow");
251+
}
252+
return flowParams;
253+
}
254+
209255
function getFirstListedSession(result: SessionsListResult) {
210256
const details = result.details as
211257
| { sessions?: Array<{ key?: string; transcriptPath?: string }> }
@@ -1109,6 +1155,32 @@ describe("sessions_send gating", () => {
11091155
expect(flowParams?.baseline).toBeUndefined();
11101156
});
11111157

1158+
it.each([
1159+
{
1160+
label: "canonical cron run",
1161+
requesterSessionKey: "agent:main:cron:job:run:abc",
1162+
expected: 0,
1163+
},
1164+
{
1165+
label: "normal requester",
1166+
requesterSessionKey: "agent:main:telegram:direct:user",
1167+
expected: 5,
1168+
},
1169+
{
1170+
label: "non-canonical cron-like requester",
1171+
requesterSessionKey: "agent:main:slack:cron:job:run:uuid",
1172+
expected: 5,
1173+
},
1174+
] as const)(
1175+
"uses the expected ping-pong turns for a $label",
1176+
async ({ requesterSessionKey, expected }) => {
1177+
const flowParams = await executeFireAndForgetA2AFrom(requesterSessionKey);
1178+
1179+
expect(flowParams.maxPingPongTurns).toBe(expected);
1180+
expect(flowParams.requesterSessionKey).toBe(requesterSessionKey);
1181+
},
1182+
);
1183+
11121184
it("caps oversized timeoutSeconds before waiting for the target run", async () => {
11131185
const tool = createMainSessionsSendTool();
11141186
const waitTimeouts: unknown[] = [];

0 commit comments

Comments
 (0)