Skip to content

Commit ebff12e

Browse files
committed
fix(agents): finalize embedded lifecycle backstop
1 parent d51af16 commit ebff12e

3 files changed

Lines changed: 172 additions & 0 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ Docs: https://docs.openclaw.ai
2626

2727
### Fixes
2828

29+
- Agents/sessions: emit a terminal lifecycle backstop when embedded timeout/error turns return without `agent_end`, so Gateway sessions no longer stay stuck in `running` after failover surfaces a timeout. Fixes #74607. Thanks @millerc79.
2930
- Agents/Codex: bound embedded-run cleanup, trajectory flushing, and command-lane task timeouts after runtime failures, so Discord and other chat sessions return to idle instead of staying stuck in processing. Thanks @vincentkoc.
3031
- Heartbeat/exec: consume successful metadata-only async exec completions silently so Telegram and other chat surfaces no longer ask users for missing command logs after `No session found`. Fixes #74595. Thanks @gkoch02.
3132
- Web fetch: add a documented `tools.web.fetch.ssrfPolicy.allowIpv6UniqueLocalRange` opt-in and thread it through cache keys and DNS/IP checks so trusted fake-IP proxy stacks using `fc00::/7` can work without broad private-network access. Fixes #74351. Thanks @jeffrey701.

‎src/auto-reply/reply/agent-runner-execution.test.ts‎

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1194,6 +1194,110 @@ describe("runAgentTurnWithFallback", () => {
11941194
});
11951195
});
11961196

1197+
it("emits an embedded lifecycle terminal backstop when the runner returns without one", async () => {
1198+
const agentEvents = await import("../../infra/agent-events.js");
1199+
const emitAgentEvent = vi.mocked(agentEvents.emitAgentEvent);
1200+
state.runEmbeddedPiAgentMock.mockImplementationOnce(async (params: EmbeddedAgentParams) => {
1201+
await params.onAgentEvent?.({
1202+
stream: "lifecycle",
1203+
data: { phase: "start", startedAt: 1_000 },
1204+
});
1205+
return {
1206+
payloads: [{ text: "Request timed out before a response was generated.", isError: true }],
1207+
meta: { aborted: true, livenessState: "blocked", replayInvalid: true },
1208+
};
1209+
});
1210+
1211+
const runAgentTurnWithFallback = await getRunAgentTurnWithFallback();
1212+
const result = await runAgentTurnWithFallback({
1213+
commandBody: "hello",
1214+
followupRun: createFollowupRun(),
1215+
sessionCtx: {
1216+
Provider: "whatsapp",
1217+
MessageSid: "msg",
1218+
} as unknown as TemplateContext,
1219+
opts: { runId: "run-timeout" } as GetReplyOptions,
1220+
typingSignals: createMockTypingSignaler(),
1221+
blockReplyPipeline: null,
1222+
blockStreamingEnabled: false,
1223+
resolvedBlockStreamingBreak: "message_end",
1224+
applyReplyToMode: (payload) => payload,
1225+
shouldEmitToolResult: () => true,
1226+
shouldEmitToolOutput: () => false,
1227+
pendingToolTasks: new Set(),
1228+
resetSessionAfterCompactionFailure: async () => false,
1229+
resetSessionAfterRoleOrderingConflict: async () => false,
1230+
isHeartbeat: false,
1231+
sessionKey: "main",
1232+
getActiveSessionEntry: () => undefined,
1233+
resolvedVerboseLevel: "off",
1234+
});
1235+
1236+
expect(result.kind).toBe("success");
1237+
expect(emitAgentEvent).toHaveBeenCalledWith({
1238+
runId: "run-timeout",
1239+
sessionKey: "main",
1240+
stream: "lifecycle",
1241+
data: {
1242+
phase: "end",
1243+
startedAt: 1_000,
1244+
endedAt: expect.any(Number),
1245+
aborted: true,
1246+
livenessState: "blocked",
1247+
replayInvalid: true,
1248+
},
1249+
});
1250+
});
1251+
1252+
it("does not duplicate embedded lifecycle terminal events already reported by the runner", async () => {
1253+
const agentEvents = await import("../../infra/agent-events.js");
1254+
const emitAgentEvent = vi.mocked(agentEvents.emitAgentEvent);
1255+
state.runEmbeddedPiAgentMock.mockImplementationOnce(async (params: EmbeddedAgentParams) => {
1256+
await params.onAgentEvent?.({
1257+
stream: "lifecycle",
1258+
data: { phase: "start", startedAt: 1_000 },
1259+
});
1260+
await params.onAgentEvent?.({
1261+
stream: "lifecycle",
1262+
data: { phase: "end", endedAt: 1_500 },
1263+
});
1264+
return { payloads: [{ text: "final" }], meta: {} };
1265+
});
1266+
1267+
const runAgentTurnWithFallback = await getRunAgentTurnWithFallback();
1268+
const result = await runAgentTurnWithFallback({
1269+
commandBody: "hello",
1270+
followupRun: createFollowupRun(),
1271+
sessionCtx: {
1272+
Provider: "whatsapp",
1273+
MessageSid: "msg",
1274+
} as unknown as TemplateContext,
1275+
opts: { runId: "run-complete" } as GetReplyOptions,
1276+
typingSignals: createMockTypingSignaler(),
1277+
blockReplyPipeline: null,
1278+
blockStreamingEnabled: false,
1279+
resolvedBlockStreamingBreak: "message_end",
1280+
applyReplyToMode: (payload) => payload,
1281+
shouldEmitToolResult: () => true,
1282+
shouldEmitToolOutput: () => false,
1283+
pendingToolTasks: new Set(),
1284+
resetSessionAfterCompactionFailure: async () => false,
1285+
resetSessionAfterRoleOrderingConflict: async () => false,
1286+
isHeartbeat: false,
1287+
sessionKey: "main",
1288+
getActiveSessionEntry: () => undefined,
1289+
resolvedVerboseLevel: "off",
1290+
});
1291+
1292+
expect(result.kind).toBe("success");
1293+
expect(emitAgentEvent).not.toHaveBeenCalledWith(
1294+
expect.objectContaining({
1295+
runId: "run-complete",
1296+
stream: "lifecycle",
1297+
}),
1298+
);
1299+
});
1300+
11971301
it("trims chatty GPT ack-turn final prose", async () => {
11981302
state.runWithModelFallbackMock.mockImplementationOnce(async (params: FallbackRunnerParams) => ({
11991303
result: await params.run("openai", "gpt-5.4"),

‎src/auto-reply/reply/agent-runner-execution.ts‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -807,6 +807,66 @@ function isReplyOperationRestartAbort(replyOperation?: ReplyOperation): boolean
807807
);
808808
}
809809

810+
function createEmbeddedLifecycleTerminalBackstop(params: { runId: string; sessionKey?: string }) {
811+
let terminalEmitted = false;
812+
let startedAt: number | undefined;
813+
814+
const note = (evt: { stream: string; data: Record<string, unknown> }) => {
815+
if (evt.stream !== "lifecycle") {
816+
return;
817+
}
818+
const phase = readStringValue(evt.data.phase);
819+
if (phase === "start" && typeof evt.data.startedAt === "number") {
820+
startedAt = evt.data.startedAt;
821+
}
822+
if (phase === "end" || phase === "error") {
823+
terminalEmitted = true;
824+
}
825+
};
826+
827+
const emit = (phase: "end" | "error", resultOrError: unknown) => {
828+
if (terminalEmitted) {
829+
return;
830+
}
831+
terminalEmitted = true;
832+
const data: Record<string, unknown> = {
833+
phase,
834+
endedAt: Date.now(),
835+
...(startedAt !== undefined ? { startedAt } : {}),
836+
};
837+
if (phase === "error") {
838+
data.error = formatErrorMessage(resultOrError);
839+
} else {
840+
const meta =
841+
resultOrError && typeof resultOrError === "object" && "meta" in resultOrError
842+
? (resultOrError as { meta?: Record<string, unknown> }).meta
843+
: undefined;
844+
if (meta?.aborted === true) {
845+
data.aborted = true;
846+
}
847+
const stopReason = readStringValue(meta?.stopReason);
848+
if (stopReason) {
849+
data.stopReason = stopReason;
850+
}
851+
const livenessState = readStringValue(meta?.livenessState);
852+
if (livenessState) {
853+
data.livenessState = livenessState;
854+
}
855+
if (meta?.replayInvalid === true) {
856+
data.replayInvalid = true;
857+
}
858+
}
859+
emitAgentEvent({
860+
runId: params.runId,
861+
...(params.sessionKey ? { sessionKey: params.sessionKey } : {}),
862+
stream: "lifecycle",
863+
data,
864+
});
865+
};
866+
867+
return { emit, note };
868+
}
869+
810870
export async function runAgentTurnWithFallback(params: {
811871
commandBody: string;
812872
transcriptCommandBody?: string;
@@ -1333,6 +1393,10 @@ export async function runAgentTurnWithFallback(params: {
13331393
);
13341394
return (async () => {
13351395
let attemptCompactionCount = 0;
1396+
const lifecycleBackstop = createEmbeddedLifecycleTerminalBackstop({
1397+
runId,
1398+
sessionKey: params.sessionKey,
1399+
});
13361400
try {
13371401
const result = await runEmbeddedPiAgent({
13381402
...embeddedContext,
@@ -1405,6 +1469,7 @@ export async function runAgentTurnWithFallback(params: {
14051469
: undefined,
14061470
onReasoningEnd: params.opts?.onReasoningEnd,
14071471
onAgentEvent: async (evt) => {
1472+
lifecycleBackstop.note(evt);
14081473
if (evt.stream.startsWith("codex_app_server.")) {
14091474
emitAgentEvent({
14101475
runId,
@@ -1598,6 +1663,7 @@ export async function runAgentTurnWithFallback(params: {
15981663
bootstrapPromptWarningSignaturesSeen = resolveBootstrapWarningSignaturesSeen(
15991664
result.meta?.systemPromptReport,
16001665
);
1666+
lifecycleBackstop.emit("end", result);
16011667
const resultCompactionCount = Math.max(
16021668
0,
16031669
result.meta?.agentMeta?.compactionCount ?? 0,
@@ -1615,6 +1681,7 @@ export async function runAgentTurnWithFallback(params: {
16151681
);
16161682
}
16171683
}
1684+
lifecycleBackstop.emit("error", err);
16181685
throw err;
16191686
} finally {
16201687
autoCompactionCount += attemptCompactionCount;

0 commit comments

Comments
 (0)