Skip to content

Commit e27db7b

Browse files
committed
fix(agents): preserve eligible settled-turn fallback
1 parent 659e381 commit e27db7b

7 files changed

Lines changed: 152 additions & 39 deletions

File tree

‎docs/plugins/sdk-agent-harness.md‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -778,13 +778,25 @@ not a substitute for removing the native capability surface.
778778
A projection-backed harness must capture the active branch after the settled
779779
turn is mirrored and prove that the current prompt and every current tool
780780
call/result are present through that boundary. Put the frozen evidence on
781-
`settledAttempt.settledTurnFinalizationContext` as either:
781+
`settledAttempt.settledTurnFinalizationContext` as one of:
782782

783783
- `source: "openclaw-transcript"` with `messages`: the complete application
784784
transcript through the boundary.
785785
- `source: "harness"` with `data`: an immutable, bounded projection interpreted
786786
only by the owning harness. Core passes this opaque value through; the
787787
finalizer must verify its own context type before using it.
788+
- `source: "unavailable"`: the harness permits finalization for this settled
789+
turn, but safe replay evidence could not be captured. The finalizer must
790+
reject this state before provider or native I/O; core can still use its
791+
existing host-owned fallback without repeating tools.
792+
793+
The unavailable state records eligibility, not validated history. Eligible
794+
capture failures, including missing, drifting, or oversized evidence, can reach
795+
that no-model fallback. Do not emit it for failures the harness excludes from
796+
finalization, such as authentication or usage-limit errors. Command-only
797+
harnesses must retain the attributed assistant tool-call entry in
798+
`messagesSnapshot`; the host fallback can use that settled-batch identity when
799+
visible-assistant fields are absent.
788800

789801
Enforce projection limits while acquiring messages, rather than cloning the
790802
whole transcript before checking its size. Successful capture must finish all

‎extensions/codex/src/app-server/run-attempt-finalize.ts‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -359,16 +359,16 @@ export async function finalizeCodexAttempt(
359359
result.messagesSnapshot.some((message) => message.role === "toolResult") &&
360360
(!finalPromptError || activeProjector.settledTurnFailureFinalizationAllowed);
361361
const settledTurnFinalizationContext = shouldCaptureSettledTurnFinalizationContext
362-
? await captureCodexSettledTurnFinalizationContext({
362+
? ((await captureCodexSettledTurnFinalizationContext({
363363
...activeTranscriptTarget,
364364
mirroredMessages: mirrorOutcome.mirroredMessages,
365365
settledMessages: result.messagesSnapshot,
366366
turnId: activeTurnId,
367-
})
367+
})) ?? Object.freeze({ source: "unavailable" as const }))
368368
: undefined;
369-
if (shouldCaptureSettledTurnFinalizationContext && !settledTurnFinalizationContext) {
370-
// The isolated child must not infer around a partial or drifting transcript.
371-
// Omitting this field preserves the existing incomplete-turn failure.
369+
if (settledTurnFinalizationContext?.source === "unavailable") {
370+
// Unavailable evidence forbids native inference, but must not revoke this
371+
// eligible turn's path to the existing host-owned fallback.
372372
embeddedAgentLog.warn("codex settled-turn finalization context is unavailable", {
373373
threadId: resourceState.thread.threadId,
374374
turnId: activeTurnId,

‎extensions/codex/src/app-server/run-attempt.test.ts‎

Lines changed: 55 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -4775,45 +4775,60 @@ describe("runCodexAppServerAttempt", () => {
47754775
});
47764776
});
47774777

4778-
it.each([
4779-
{ label: "completed turn", failure: undefined, expectedContext: true },
4780-
{
4781-
label: "provider overload after the tool result",
4782-
failure: {
4783-
message: "Selected model is at capacity. Please try a different model.",
4784-
codexErrorInfo: "serverOverloaded",
4778+
it.each(
4779+
[
4780+
{ label: "completed turn", failure: undefined, expectedContext: true },
4781+
{
4782+
label: "provider overload after the tool result",
4783+
failure: {
4784+
message: "Selected model is at capacity. Please try a different model.",
4785+
codexErrorInfo: "serverOverloaded",
4786+
},
4787+
expectedContext: true,
47854788
},
4786-
expectedContext: true,
4787-
},
4788-
{
4789-
label: "usage limit after the tool result",
4790-
failure: {
4791-
message: "Usage limit exceeded.",
4792-
codexErrorInfo: "usageLimitExceeded",
4789+
{
4790+
label: "usage limit after the tool result",
4791+
failure: {
4792+
message: "Usage limit exceeded.",
4793+
codexErrorInfo: "usageLimitExceeded",
4794+
},
4795+
expectedContext: false,
47934796
},
4794-
expectedContext: false,
4795-
},
4796-
{
4797-
label: "unauthorized response after the tool result",
4798-
failure: {
4799-
message: "Unauthorized.",
4800-
codexErrorInfo: "unauthorized",
4797+
{
4798+
label: "unauthorized response after the tool result",
4799+
failure: {
4800+
message: "Unauthorized.",
4801+
codexErrorInfo: "unauthorized",
4802+
},
4803+
expectedContext: false,
48014804
},
4802-
expectedContext: false,
4803-
},
4804-
])(
4805-
"captures the complete mirrored branch through a settled tool-result boundary for a $label",
4806-
async ({ failure, expectedContext }) => {
4805+
].flatMap((scenario) =>
4806+
[false, true].map((oversizedHistory) => ({ scenario, oversizedHistory })),
4807+
),
4808+
)(
4809+
"preserves settled finalization eligibility for a $scenario.label (oversized history: $oversizedHistory)",
4810+
async ({ scenario: { failure, expectedContext }, oversizedHistory }) => {
48074811
const storePath = path.join(tempDir, "settled-finalization-context.sqlite");
48084812
const sessionId = "session-settled-finalization-context";
48094813
const sessionFile = `agent:main:${sessionId}`;
48104814
const workspaceDir = path.join(tempDir, "workspace-settled-finalization-context");
48114815
const harness = createStartedThreadHarness();
48124816
const params = createParams(sessionFile, workspaceDir);
48134817
await attachSqliteSessionTarget(params, storePath, sessionId);
4818+
if (oversizedHistory) {
4819+
for (let index = 0; index < 201; index += 1) {
4820+
await appendSqliteHistoryMessage(
4821+
params,
4822+
userMessage(`Prior message ${index}`, index + 1),
4823+
);
4824+
}
4825+
}
48144826
params.prompt = "Send the update to Alice.";
48154827
const run = runCodexAppServerAttempt(params);
48164828
await harness.waitForMethod("turn/start");
4829+
const emptyAssistant = { type: "agentMessage", id: "empty-assistant", text: "" };
4830+
await harness.notify(itemNotification("item/started", emptyAssistant));
4831+
await harness.notify(itemNotification("item/completed", emptyAssistant));
48174832
await harness.notify(
48184833
itemNotification("item/started", {
48194834
type: "commandExecution",
@@ -4852,7 +4867,20 @@ describe("runCodexAppServerAttempt", () => {
48524867
const result = await run;
48534868
expect(Boolean(readAttemptTerminal(result).promptError)).toBe(Boolean(failure));
48544869
expect(Boolean(result.settledTurnFinalizationContext)).toBe(expectedContext);
4855-
if (result.settledTurnFinalizationContext) {
4870+
expect(result.currentAttemptAssistant).toBeDefined();
4871+
expect(result.replayMetadata).toMatchObject({
4872+
hadPotentialSideEffects: true,
4873+
replaySafe: false,
4874+
});
4875+
expect(result.itemLifecycle).toMatchObject({
4876+
startedCount: 2,
4877+
completedCount: 2,
4878+
activeCount: 0,
4879+
});
4880+
if (expectedContext && oversizedHistory) {
4881+
expect(result.settledTurnFinalizationContext).toEqual({ source: "unavailable" });
4882+
expect(Object.isFrozen(result.settledTurnFinalizationContext)).toBe(true);
4883+
} else if (result.settledTurnFinalizationContext) {
48564884
expect(result.settledTurnFinalizationContext).toMatchObject({
48574885
source: "harness",
48584886
data: [

‎extensions/codex/src/app-server/settled-turn-finalizer.test.ts‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -337,12 +337,16 @@ describe("runCodexSettledTurnFinalization", () => {
337337
expect(mocks.mirror).not.toHaveBeenCalled();
338338
});
339339

340-
it.each(["missing", "foreign"])(
341-
"rejects a %s context before starting the isolated turn",
340+
it.each(["missing", "foreign", "unavailable"])(
341+
"rejects %s context before starting the isolated turn",
342342
async (kind) => {
343343
const settledAttempt = createSettledAttempt();
344344
settledAttempt.settledTurnFinalizationContext =
345-
kind === "missing" ? undefined : { source: "harness", data: [] };
345+
kind === "missing"
346+
? undefined
347+
: kind === "foreign"
348+
? { source: "harness", data: [] }
349+
: { source: "unavailable" };
346350
await expect(
347351
runCodexSettledTurnFinalization({ attempt: createAttempt(), settledAttempt }, {}),
348352
).rejects.toThrow("finalization context is unavailable");

‎src/agents/embedded-agent-runner/run/settled-turn-finalization.test.ts‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -623,6 +623,70 @@ describe("prepareTerminalWithSettledTurnFinalization", () => {
623623
});
624624
});
625625

626+
it.each([false, true])(
627+
"uses the settled tool-batch identity for command-only fallback (context unavailable: %s)",
628+
async (unavailable) => {
629+
const assistant = buildEmbeddedRunnerAssistant({
630+
model: "gpt-5.6-luna",
631+
stopReason: "toolUse",
632+
content: [{ type: "toolCall", id: "command-1", name: "exec", arguments: {} }],
633+
});
634+
const messagesSnapshot: EmbeddedRunAttemptWithReceiptEvidence["messagesSnapshot"] = [
635+
{ role: "user", content: "Run the command.", timestamp: 1 },
636+
assistant,
637+
{
638+
role: "toolResult",
639+
toolCallId: "command-1",
640+
toolName: "exec",
641+
content: [{ type: "text", text: "done" }],
642+
isError: false,
643+
timestamp: 3,
644+
},
645+
];
646+
const attempt = {
647+
...makeEmbeddedRunnerAttempt({
648+
terminal: {
649+
kind: "failed",
650+
source: "prompt",
651+
error: new Error("The provider is overloaded"),
652+
},
653+
sessionIdUsed: "session-settled",
654+
sessionFileUsed: "/tmp/session-settled.jsonl",
655+
messagesSnapshot,
656+
toolMetas: [
657+
{ toolName: "exec", toolCallId: "command-1", isError: false, replaySafe: false },
658+
],
659+
itemLifecycle: { startedCount: 1, completedCount: 1, activeCount: 0 },
660+
currentAttemptReplayMetadata: { hadPotentialSideEffects: true, replaySafe: false },
661+
replayMetadata: { hadPotentialSideEffects: true, replaySafe: false },
662+
currentAttemptAssistant: undefined,
663+
lastAssistant: undefined,
664+
settledTurnFinalizationContext: unavailable
665+
? { source: "unavailable" }
666+
: { source: "openclaw-transcript", messages: messagesSnapshot },
667+
}),
668+
successfulNestedToolNames: [],
669+
};
670+
const input = finalizationInput(attempt);
671+
input.terminalBase.runParams.trigger = "user";
672+
backendMocks.runSettledFinalization.mockRejectedValueOnce(new Error("finalizer failed"));
673+
674+
const result = await prepareTerminalWithSettledTurnFinalization(input);
675+
676+
expect(backendMocks.runSettledFinalization).toHaveBeenCalledOnce();
677+
expect(result.finalizationOutcome).toBe("failed");
678+
expect(result.prepared.payloadsWithToolMedia).toEqual([
679+
expect.objectContaining({ text: SETTLED_TOOL_FINALIZATION_FALLBACK_TEXT }),
680+
]);
681+
expect(result.prepared.payloadsWithToolMedia?.[0]?.isError).not.toBe(true);
682+
expect(result.prepared.failureSignal).toBeUndefined();
683+
expect(result.attempt.currentAttemptAssistant).toMatchObject({
684+
provider: assistant.provider,
685+
model: assistant.model,
686+
});
687+
},
688+
);
689+
626690
it("preserves an explicit cancellation instead of delivering a fallback", async () => {
627691
const attempt = settledFailedAttempt();
628692
const input = finalizationInput(attempt);

‎src/agents/embedded-agent-runner/run/settled-turn-finalization.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import {
2424
resolveRuntimeModelAttempt,
2525
runEmbeddedSettledTurnFinalizationWithBackend,
2626
} from "./backend.js";
27+
import { resolveSettledToolBatchEvidence } from "./incomplete-turn-recovery.js";
2728
import { withEmbeddedRunLaneProgressHeartbeat } from "./lane-runtime.js";
2829
import {
2930
resolveEmbeddedRunAttemptTerminalOutcome,
@@ -404,11 +405,14 @@ function buildSettledToolFallbackAttemptResult(input: {
404405
runtimePlan?: EmbeddedRunAttemptParams["runtimePlan"];
405406
transcriptIdempotencyKey?: string;
406407
}): EmbeddedRunAttemptWithReceiptEvidence {
408+
// Command-only harnesses retain assistant identity in the settled tool batch,
409+
// even when neither visible-assistant field exists.
407410
const sourceAssistant =
408411
input.sourceAttempt.currentAttemptAssistant ??
409412
input.sourceAttempt.lastAssistant ??
410413
input.settledAttempt.currentAttemptAssistant ??
411-
input.settledAttempt.lastAssistant;
414+
input.settledAttempt.lastAssistant ??
415+
resolveSettledToolBatchEvidence(input.settledAttempt).assistant;
412416
if (!sourceAssistant) {
413417
throw new Error("Settled-turn fallback has no assistant identity");
414418
}

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

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -296,10 +296,11 @@ export type EmbeddedRunAttemptResult = {
296296
/** Exact provider-response count when the harness can observe model iterations directly. */
297297
modelIterations?: number;
298298
messagesSnapshot: AgentMessage[];
299-
/** Complete settled evidence, frozen as transcript messages or an owning harness's bounded projection. */
299+
/** Owner-eligible settled finalization, with frozen evidence or an unavailable projection. */
300300
settledTurnFinalizationContext?:
301301
| { readonly source: "openclaw-transcript"; readonly messages: readonly AgentMessage[] }
302-
| { readonly source: "harness"; readonly data: unknown };
302+
| { readonly source: "harness"; readonly data: unknown }
303+
| { readonly source: "unavailable" };
303304
beforeAgentFinalizeRevisionReason?: string;
304305
assistantTexts: string[];
305306
latestMcpAppChannelView?: McpAppChannelView;

0 commit comments

Comments
 (0)