Skip to content

Commit 3a555d5

Browse files
authored
refactor(agents): centralize terminal lifecycle outcomes (#118254)
* refactor(agents): centralize terminal lifecycle outcomes * fix(agents): preserve terminal projection contracts * refactor(agents): split terminal error boundary * test(gateway): align stale lifecycle projection
1 parent 347f16d commit 3a555d5

27 files changed

Lines changed: 363 additions & 276 deletions

‎src/acp/control-plane/manager.background-task.test.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
11
/** Regression coverage for ACP background-task summary truncation boundaries. */
22
import { describe, expect, it } from "vitest";
33
import type { OpenClawConfig } from "../../config/types.openclaw.js";
4+
import { AcpRuntimeError } from "../runtime/errors.js";
45
import {
56
appendBackgroundTaskProgressSummary,
67
resolveBackgroundTaskContext,
8+
resolveBackgroundTaskFailureStatus,
79
} from "./manager.background-task.js";
10+
import { ACP_TURN_TIMEOUT_DETAIL_CODE } from "./manager.turn-timeout.js";
811
import type { AcpSessionManagerDeps } from "./manager.types.js";
912

1013
// U+1F99E (🦞) is a surrogate pair in UTF-16; a raw .slice() boundary can split it.
@@ -65,3 +68,20 @@ describe("resolveBackgroundTaskContext", () => {
6568
expect(context?.task).toBe(`summarize ${LOBSTER} feedback`);
6669
});
6770
});
71+
72+
describe("resolveBackgroundTaskFailureStatus", () => {
73+
it("uses the structured timeout detail instead of message text", () => {
74+
expect(
75+
resolveBackgroundTaskFailureStatus(
76+
new AcpRuntimeError("ACP_TURN_FAILED", "turn deadline reached", {
77+
detailCode: ACP_TURN_TIMEOUT_DETAIL_CODE,
78+
}),
79+
),
80+
).toBe("timed_out");
81+
expect(
82+
resolveBackgroundTaskFailureStatus(
83+
new AcpRuntimeError("ACP_TURN_FAILED", "backend said the request timed out"),
84+
),
85+
).toBe("failed");
86+
});
87+
});

‎src/acp/control-plane/manager.background-task.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import {
1111
import { resolveRequiredCompletionTerminalResult } from "../../tasks/task-completion-contract.js";
1212
import { deliveryContextFromSession, type DeliveryContext } from "../../utils/delivery-context.js";
1313
import { AcpRuntimeError } from "../runtime/errors.js";
14+
import { ACP_TURN_TIMEOUT_DETAIL_CODE } from "./manager.turn-timeout.js";
1415
import type { AcpSessionManagerDeps } from "./manager.types.js";
1516
import { normalizeText } from "./runtime-options.js";
1617

@@ -55,7 +56,7 @@ export function appendBackgroundTaskProgressSummary(current: string, chunk: stri
5556

5657
/** Maps ACP runtime failures to detached-task terminal states. */
5758
export function resolveBackgroundTaskFailureStatus(error: AcpRuntimeError): "failed" | "timed_out" {
58-
return /\btimed out\b/i.test(error.message) ? "timed_out" : "failed";
59+
return error.detailCode === ACP_TURN_TIMEOUT_DETAIL_CODE ? "timed_out" : "failed";
5960
}
6061

6162
/** Infers blocked terminal outcomes from final progress text when the child turn reports one. */

‎src/acp/control-plane/manager.turn-runner.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,7 @@ export async function runManagerTurn(params: {
121121
? new AcpRuntimeError(
122122
error.code,
123123
`All ACP backends failed (${backendAttempts.length}): ${failedBackends}`,
124+
{ detailCode: error.detailCode },
124125
)
125126
: error;
126127
params.recordTurnCompletion({
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/** Carries and discovers canonical terminal outcomes through thrown-error boundaries. */
2+
import type { AgentRunTerminalOutcome } from "./agent-run-terminal-outcome.js";
3+
4+
/** Carries a canonical terminal outcome when an embedded attempt exits by throwing. */
5+
export class AgentRunTerminalOutcomeError extends Error {
6+
readonly terminalOutcome: AgentRunTerminalOutcome;
7+
8+
constructor(error: unknown, terminalOutcome: AgentRunTerminalOutcome) {
9+
super(error instanceof Error ? error.message : String(error), { cause: error });
10+
this.name = "AgentRunTerminalOutcomeError";
11+
this.terminalOutcome = terminalOutcome;
12+
}
13+
}
14+
15+
/** Finds a canonical terminal outcome through ordinary error wrapper boundaries. */
16+
export function findAgentRunTerminalOutcome(error: unknown): AgentRunTerminalOutcome | undefined {
17+
let candidate = error;
18+
const seen = new Set<object>();
19+
while (candidate && typeof candidate === "object" && !seen.has(candidate)) {
20+
seen.add(candidate);
21+
if (candidate instanceof AgentRunTerminalOutcomeError) {
22+
return candidate.terminalOutcome;
23+
}
24+
candidate = (candidate as { cause?: unknown }).cause;
25+
}
26+
return undefined;
27+
}

‎src/agents/agent-run-terminal-outcome.test.ts‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
import { describe, expect, it } from "vitest";
33
import {
44
buildAgentRunTerminalOutcome,
5+
buildAgentRunTerminalOutcomeFromLifecycleEvent,
6+
classifyAgentRunTerminalOutcome,
57
mergeAgentRunAttemptTerminal,
68
mergeAgentRunTerminalOutcome,
79
normalizeAgentRunAttemptTerminal,
@@ -11,6 +13,46 @@ import {
1113
} from "./agent-run-terminal-outcome.js";
1214

1315
describe("agent run terminal outcome", () => {
16+
it.each([
17+
["completed", "success"],
18+
["hard_timeout", "timeout"],
19+
["timed_out", "timeout"],
20+
["cancelled", "cancellation"],
21+
["aborted", "cancellation"],
22+
["blocked", "failure"],
23+
["abandoned", "failure"],
24+
["failed", "failure"],
25+
] as const)("classifies %s as %s", (reason, classification) => {
26+
expect(classifyAgentRunTerminalOutcome({ reason })).toBe(classification);
27+
});
28+
29+
it("normalizes lifecycle signals with timeout, cancellation, failure precedence", () => {
30+
expect(
31+
buildAgentRunTerminalOutcomeFromLifecycleEvent({
32+
phase: "end",
33+
data: { aborted: true },
34+
}),
35+
).toMatchObject({ reason: "aborted", status: "error", stopReason: "aborted" });
36+
expect(
37+
buildAgentRunTerminalOutcomeFromLifecycleEvent({
38+
phase: "end",
39+
data: { aborted: true, stopReason: "timeout", timeoutPhase: "provider" },
40+
}),
41+
).toMatchObject({ reason: "hard_timeout", status: "timeout" });
42+
expect(
43+
buildAgentRunTerminalOutcomeFromLifecycleEvent({
44+
phase: "error",
45+
data: { error: "provider failed" },
46+
}),
47+
).toMatchObject({ reason: "failed", status: "error", error: "provider failed" });
48+
expect(
49+
buildAgentRunTerminalOutcomeFromLifecycleEvent({
50+
phase: "end",
51+
data: { status: "cancelled", stopReason: "relay-closed" },
52+
}),
53+
).toMatchObject({ reason: "cancelled", status: "error", stopReason: "relay-closed" });
54+
});
55+
1456
it("treats provider/preflight/post-turn timeout phases as hard run timeouts", () => {
1557
expect(
1658
["preflight", "provider", "post_turn", "queue", "gateway_draining"].map(

‎src/agents/agent-run-terminal-outcome.ts‎

Lines changed: 78 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -402,16 +402,19 @@ export function projectAgentRunAttemptTerminal(terminal: AgentRunAttemptTerminal
402402
};
403403
}
404404

405+
const AGENT_RUN_TERMINAL_CLASSIFICATION = {
406+
completed: "success",
407+
hard_timeout: "timeout",
408+
timed_out: "timeout",
409+
cancelled: "cancellation",
410+
aborted: "cancellation",
411+
blocked: "failure",
412+
abandoned: "failure",
413+
failed: "failure",
414+
} as const;
415+
405416
/** Normalized terminal reason for an agent run. */
406-
type AgentRunTerminalReason =
407-
| "completed"
408-
| "hard_timeout"
409-
| "timed_out"
410-
| "cancelled"
411-
| "aborted"
412-
| "blocked"
413-
| "abandoned"
414-
| "failed";
417+
type AgentRunTerminalReason = keyof typeof AGENT_RUN_TERMINAL_CLASSIFICATION;
415418

416419
/** Normalized terminal outcome for an agent run. */
417420
export type AgentRunTerminalOutcome = {
@@ -426,29 +429,9 @@ export type AgentRunTerminalOutcome = {
426429
endedAt?: number;
427430
};
428431

429-
/** Carries a canonical terminal outcome when an embedded attempt exits by throwing. */
430-
export class AgentRunTerminalOutcomeError extends Error {
431-
readonly terminalOutcome: AgentRunTerminalOutcome;
432-
433-
constructor(error: unknown, terminalOutcome: AgentRunTerminalOutcome) {
434-
super(error instanceof Error ? error.message : String(error), { cause: error });
435-
this.name = "AgentRunTerminalOutcomeError";
436-
this.terminalOutcome = terminalOutcome;
437-
}
438-
}
439-
440-
/** Finds a canonical terminal outcome through ordinary error wrapper boundaries. */
441-
export function findAgentRunTerminalOutcome(error: unknown): AgentRunTerminalOutcome | undefined {
442-
let candidate = error;
443-
const seen = new Set<object>();
444-
while (candidate && typeof candidate === "object" && !seen.has(candidate)) {
445-
seen.add(candidate);
446-
if (candidate instanceof AgentRunTerminalOutcomeError) {
447-
return candidate.terminalOutcome;
448-
}
449-
candidate = (candidate as { cause?: unknown }).cause;
450-
}
451-
return undefined;
432+
/** Collapses terminal reasons into the four projections shared by run consumers. */
433+
export function classifyAgentRunTerminalOutcome(outcome: Pick<AgentRunTerminalOutcome, "reason">) {
434+
return AGENT_RUN_TERMINAL_CLASSIFICATION[outcome.reason];
452435
}
453436

454437
/** Raw terminal input collected from run wait/liveness/timeout paths. */
@@ -468,6 +451,11 @@ type AgentRunTerminalWaitInput = Omit<AgentRunTerminalInput, "status"> & {
468451
status?: unknown;
469452
};
470453

454+
type AgentRunLifecycleTerminalData = Omit<AgentRunTerminalWaitInput, "status"> & {
455+
aborted?: unknown;
456+
status?: unknown;
457+
};
458+
471459
/** Shared grace window for terminal observations that may still be followed by a retry. */
472460
export const AGENT_RUN_TERMINAL_RETRY_GRACE_MS = 15_000;
473461

@@ -574,6 +562,64 @@ export function buildAgentRunTerminalOutcome(
574562
};
575563
}
576564

565+
/** Builds the canonical outcome directly from a terminal lifecycle event. */
566+
export function buildAgentRunTerminalOutcomeFromLifecycleEvent(input: {
567+
phase: "end" | "error";
568+
data?: AgentRunLifecycleTerminalData;
569+
abortSignal?: AbortSignal;
570+
startedAt?: unknown;
571+
endedAt?: unknown;
572+
}): AgentRunTerminalOutcome {
573+
const data = input.data;
574+
const abortFields =
575+
typeof data?.aborted === "boolean"
576+
? {}
577+
: resolveAgentRunAbortLifecycleFields(input.abortSignal);
578+
const stopReason = asNonEmptyString(data?.stopReason) ?? abortFields.stopReason;
579+
const timeoutPhase = normalizeAgentRunTimeoutPhase(data?.timeoutPhase);
580+
const lifecycleStatus = asNonEmptyString(data?.status)?.toLowerCase();
581+
// Bare `aborted` is cancellation; timeout needs a structured status, stop
582+
// reason, or phase so legacy lifecycle gaps cannot turn user stops into timeouts.
583+
const timedOut =
584+
stopReason === "timeout" ||
585+
timeoutPhase !== undefined ||
586+
lifecycleStatus === "timeout" ||
587+
lifecycleStatus === "timed_out";
588+
const aborted =
589+
data?.aborted === true || abortFields.aborted === true || lifecycleStatus === "aborted";
590+
const cancellationStatus =
591+
lifecycleStatus === "cancelled" ||
592+
lifecycleStatus === "canceled" ||
593+
lifecycleStatus === "aborted";
594+
const cancelled = cancellationStatus || aborted;
595+
const failed =
596+
input.phase === "error" ||
597+
lifecycleStatus === "error" ||
598+
lifecycleStatus === "failed" ||
599+
stopReason === "error";
600+
const normalizedStopReason =
601+
!timedOut &&
602+
cancelled &&
603+
!isAbortedAgentStopReason(stopReason) &&
604+
!isCancellationStopReason(stopReason) &&
605+
(stopReason === undefined || cancellationStatus)
606+
? aborted
607+
? "aborted"
608+
: "stop"
609+
: stopReason;
610+
const outcome = buildAgentRunTerminalOutcome({
611+
status: timedOut ? "timeout" : cancelled || failed ? "error" : "ok",
612+
error: data?.error,
613+
stopReason: normalizedStopReason,
614+
livenessState: data?.livenessState,
615+
timeoutPhase,
616+
providerStarted: data?.providerStarted,
617+
startedAt: input.startedAt ?? data?.startedAt,
618+
endedAt: input.endedAt ?? data?.endedAt,
619+
});
620+
return stopReason && outcome.stopReason !== stopReason ? { ...outcome, stopReason } : outcome;
621+
}
622+
577623
function hasRestartAbortReason(value: unknown): boolean {
578624
let candidate = value;
579625
for (let depth = 0; depth < 3; depth += 1) {

‎src/agents/command/lifecycle.ts‎

Lines changed: 2 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { emitAgentEvent } from "../../infra/agent-events.js";
22
import { formatErrorMessage } from "../../infra/errors.js";
33
import { createSubsystemLogger } from "../../logging/subsystem.js";
44
import {
5-
buildAgentRunTerminalOutcome,
5+
buildAgentRunTerminalOutcomeFromLifecycleEvent,
66
type AgentRunTerminalOutcome,
77
} from "../agent-run-terminal-outcome.js";
88
import type { EmbeddedAgentRunEntryTerminal } from "../embedded-agent-runner/run-entry.js";
@@ -35,20 +35,7 @@ export function resolveAgentRunLifecycleEndLogLevel(meta: {
3535
timeoutPhase?: unknown;
3636
providerStarted?: unknown;
3737
}): "info" | "warn" | "error" | undefined {
38-
const status =
39-
meta.stopReason === "timeout" || meta.timeoutPhase
40-
? "timeout"
41-
: meta.aborted === true || meta.error || meta.stopReason === "error"
42-
? "error"
43-
: "ok";
44-
const outcome = buildAgentRunTerminalOutcome({
45-
status,
46-
error: meta.error,
47-
stopReason: meta.stopReason,
48-
livenessState: meta.livenessState,
49-
timeoutPhase: meta.timeoutPhase,
50-
providerStarted: meta.providerStarted,
51-
});
38+
const outcome = buildAgentRunTerminalOutcomeFromLifecycleEvent({ phase: "end", data: meta });
5239
return resolveTerminalLogLevel(outcome);
5340
}
5441

‎src/agents/embedded-agent-runner/run/attempt.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@ import {
66
import { resolveContextEngineOwnerPluginId } from "../../../context-engine/registry.js";
77
import { createBundleLspToolRuntime } from "../../agent-bundle-lsp-runtime.js";
88
import { materializeBundleMcpToolsForRun } from "../../agent-bundle-mcp-tools.js";
9+
import { AgentRunTerminalOutcomeError } from "../../agent-run-terminal-error.js";
910
import {
10-
AgentRunTerminalOutcomeError,
1111
buildAgentRunTerminalOutcomeFromAttempt,
1212
mergeAgentRunAttemptTerminal,
1313
projectAgentRunAttemptTerminal,

‎src/agents/model-fallback-attempt.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import type { OpenClawConfig } from "../config/types.openclaw.js";
55
import { isCronTerminalAbortReasonText } from "../cron/service/execution-errors.js";
66
import { formatErrorMessage, toErrorObject } from "../infra/errors.js";
77
import { isCommandLaneTaskTimeoutError } from "../process/command-queue.js";
8-
import { findAgentRunTerminalOutcome } from "./agent-run-terminal-outcome.js";
8+
import { findAgentRunTerminalOutcome } from "./agent-run-terminal-error.js";
99
import { isDefaultAgentRuntimeId, normalizeOptionalAgentRuntimeId } from "./agent-runtime-id.js";
1010
import { externalCliDiscoveryForProviders } from "./auth-profiles/external-cli-discovery.js";
1111
import type { AuthProfileStore } from "./auth-profiles/types.js";

‎src/agents/model-fallback.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ import { setCurrentPluginMetadataSnapshot } from "../plugins/current-plugin-meta
1717
import { clearCurrentPluginMetadataSnapshot } from "../plugins/current-plugin-metadata-state.js";
1818
import { loadPluginMetadataSnapshot } from "../plugins/plugin-metadata-snapshot.js";
1919
import { GatewayDrainingError } from "../process/gateway-work-admission.js";
20-
import { AgentRunTerminalOutcomeError } from "./agent-run-terminal-outcome.js";
20+
import { AgentRunTerminalOutcomeError } from "./agent-run-terminal-error.js";
2121
import { AUTH_STORE_VERSION } from "./auth-profiles/constants.js";
2222
import type { AuthProfileStore } from "./auth-profiles/types.js";
2323
import { testing as cliBackendsTesting } from "./cli-backends.test-support.js";

0 commit comments

Comments
 (0)