Skip to content

Commit 6eea20c

Browse files
committed
fix(agents): finalize settled tool turns safely
1 parent 7c2829c commit 6eea20c

64 files changed

Lines changed: 3170 additions & 697 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎docs/.generated/plugin-sdk-api-baseline.sha256‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ cbf4e2c3088f8886a7c9ea91325a66e0f0846cea21f0b2891f36399b4811306c module/account
44
6b674e7aa4006240227c16eb5c74360f1d67639e8f5580ad72499d6ed28283c4 module/account-resolution
55
e5e67ddf3cab38fcbf9220bc3160715897e2709d9a9ff6ff36f1ecc9453c2367 module/agent-config-primitives
66
74daa746deb548379d3f0d6eac3c4d082df1034c4360cc03bf51fee0f10a2e4d module/agent-harness
7-
c67e52e5bc6d6917f9a13f4133e7b18e111dbd33b66b6a5eae79623d9ff6e918 module/agent-harness-runtime
7+
60ef6632c59cdb95483fb12d140ca0f5490d20f10b0081c99e9976ad9089a718 module/agent-harness-runtime
88
5168648cd946abad8a92822889f13ceacc87ed502314a66190d0b1eb8ebe76ea module/agent-media-payload
99
8b406b7a50b0b4f088be869ea6a899c0d33229a5c73d3f82bda76ce0be0941b0 module/agent-runtime
1010
dd9282f1eeadf44db2887599b52d80db7f5fb99c6d9eac720dbf1b77065f2145 module/allow-from

‎docs/docs_map.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7457,6 +7457,7 @@ Do not edit it by hand; run `pnpm docs:map:gen`.
74577457
- H2: Native sessions and transcript mirror
74587458
- H2: Tool and media results
74597459
- H3: Terminal tool outcomes
7460+
- H3: Settled tool finalization
74607461
- H2: Current limitations
74617462
- H2: Related
74627463

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

Lines changed: 36 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -484,12 +484,45 @@ settledAttempt })`.
484484

485485
The callback is a separate capability, not another ordinary attempt. It must:
486486

487-
- continue the exact native transcript that contains the settled tool results;
487+
- use either the exact restricted native transcript or a complete application
488+
transcript frozen through the settled tool-result boundary;
488489
- expose no tools, permission-grant or user-input capabilities, native execution
489490
hooks, agents, skills, memory, scheduling, extensions, or remote control;
490491
- send only the host-provided finalization prompt; and
491-
- fail closed if the existing native session cannot be resumed with those
492-
restrictions.
492+
- fail closed if its selected transcript/isolation strategy cannot enforce
493+
those restrictions.
494+
495+
OpenClaw invokes the callback once as a terminal sub-operation, outside the
496+
ordinary attempt and retry loop. A failure ends the run with the
497+
side-effect-aware incomplete-turn warning; it cannot enter ordinary
498+
auth/profile rotation, model fallback, context recovery, compaction
499+
continuation, or hook-requested revision paths. Finalization also skips plugin
500+
prompt mutation, `before_agent_run`, LLM input/output, terminal revision, and
501+
`agent_end` hooks. Core diagnostics still record the operation and its failure.
502+
503+
The callback returns `AgentHarnessSettledTurnFinalizationResult`, not an
504+
ordinary attempt result. Its public fields are limited to the completed
505+
assistant message, finalization-call usage, transcript-ownership metadata, and
506+
diagnostic trace. Tool, delivery, media, spawn, lifecycle, replay, session, and
507+
fallback state cannot cross this result boundary. Unknown fields and assistant
508+
tool calls fail closed.
509+
510+
A harness that internally reuses its full attempt engine can call
511+
`projectSettledTurnFinalizationAttemptResult(...)` before returning. The helper
512+
rejects canonical failure, tool, delivery, replay, and lifecycle evidence, then
513+
projects only the narrow result. It is defense in depth after native isolation,
514+
not a substitute for removing the native capability surface.
515+
516+
A projection-backed harness must put the complete context on
517+
`settledAttempt.settledTurnFinalizationContext` with
518+
`source: "openclaw-transcript"`. It must capture the active branch after the
519+
settled turn is mirrored, prove that the current prompt and every current tool
520+
call/result are present through that boundary, and freeze the resulting message
521+
array before returning the attempt. The finalizer must reject a missing,
522+
unsupported, ambiguous, or oversized context. It must not truncate messages,
523+
drop earlier history, or describe this application transcript as exact native
524+
history. Harnesses that resume one restricted native session do not need this
525+
projection field.
493526

494527
Do not implement this callback by calling `runAttempt` with a best-effort
495528
`disableTools` hint. The harness owner must enforce the complete native

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

Lines changed: 57 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,12 @@ function inProgressTurnResult() {
9797
};
9898
}
9999

100-
function createClientFactory(options: { mcpServers?: unknown[] } = {}) {
100+
function createClientFactory(
101+
options: {
102+
mcpServers?: unknown[];
103+
errorBeforeCompletion?: { message: string; willRetry: boolean };
104+
} = {},
105+
) {
101106
const methods: string[] = [];
102107
const notificationHandlers: Array<(notification: CodexServerNotification) => void> = [];
103108
const request = vi.fn(async (method: string, _params?: unknown) => {
@@ -126,6 +131,17 @@ function createClientFactory(options: { mcpServers?: unknown[] } = {}) {
126131
if (method === "turn/start") {
127132
queueMicrotask(() => {
128133
for (const handler of notificationHandlers) {
134+
if (options.errorBeforeCompletion) {
135+
handler({
136+
method: "error",
137+
params: {
138+
threadId: "thread-finalizer",
139+
turnId: "turn-finalizer",
140+
error: { message: options.errorBeforeCompletion.message },
141+
willRetry: options.errorBeforeCompletion.willRetry,
142+
},
143+
});
144+
}
129145
handler({
130146
method: "rawResponse/completed",
131147
params: {
@@ -175,6 +191,46 @@ function createClientFactory(options: { mcpServers?: unknown[] } = {}) {
175191
}
176192

177193
describe("runBoundedCodexAppServerTurn settled finalization isolation", () => {
194+
it("continues after a retryable error notification", async () => {
195+
const fake = createClientFactory({
196+
errorBeforeCompletion: { message: "temporary upstream disconnect", willRetry: true },
197+
});
198+
199+
await expect(
200+
runBoundedCodexAppServerTurn({
201+
model: { mode: "required", id: "gpt-5.4" },
202+
timeoutMs: 5_000,
203+
options: { clientFactory: fake.factory },
204+
taskLabel: "settled-turn finalization",
205+
developerInstructions: "Finalize only.",
206+
input: [{ type: "text", text: "Produce the final answer.", text_elements: [] }],
207+
requiredModalities: ["text"],
208+
isolation: "private-stdio",
209+
requireNoExternalCapabilities: true,
210+
}),
211+
).resolves.toMatchObject({ text: "The message was sent successfully." });
212+
});
213+
214+
it("still fails on a terminal error notification", async () => {
215+
const fake = createClientFactory({
216+
errorBeforeCompletion: { message: "terminal upstream failure", willRetry: false },
217+
});
218+
219+
await expect(
220+
runBoundedCodexAppServerTurn({
221+
model: { mode: "required", id: "gpt-5.4" },
222+
timeoutMs: 5_000,
223+
options: { clientFactory: fake.factory },
224+
taskLabel: "settled-turn finalization",
225+
developerInstructions: "Finalize only.",
226+
input: [{ type: "text", text: "Produce the final answer.", text_elements: [] }],
227+
requiredModalities: ["text"],
228+
isolation: "private-stdio",
229+
requireNoExternalCapabilities: true,
230+
}),
231+
).rejects.toThrow("terminal upstream failure");
232+
});
233+
178234
it("attests ring-zero and injects frozen history before starting the final turn", async () => {
179235
const fake = createClientFactory();
180236
const historyItems: JsonValue[] = [

‎extensions/codex/src/app-server/bounded-turn.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,10 @@ import type { AuthProfileStore } from "openclaw/plugin-sdk/agent-runtime";
44
import type { OpenClawConfig } from "openclaw/plugin-sdk/config-contracts";
55
import { resolveTimerTimeoutMs } from "openclaw/plugin-sdk/number-runtime";
66
import { resolvePreferredOpenClawTmpDir, withTempWorkspace } from "openclaw/plugin-sdk/temp-path";
7-
import { readCodexNotificationItem } from "./attempt-notifications.js";
7+
import {
8+
isRetryableErrorNotification,
9+
readCodexNotificationItem,
10+
} from "./attempt-notifications.js";
811
import type { CodexAppServerClient } from "./client.js";
912
import { resolveCodexAppServerRuntimeOptions } from "./config.js";
1013
import { normalizeCodexResponseTokenUsage } from "./event-projector-usage.js";
@@ -471,6 +474,9 @@ function createCodexBoundedTurnCollector(threadId: string, taskLabel: string) {
471474
return;
472475
}
473476
if (notification.method === "error") {
477+
if (isRetryableErrorNotification(notification.params)) {
478+
return;
479+
}
474480
promptError =
475481
readCodexErrorNotification(notification.params)?.error.message ??
476482
`codex app-server ${taskLabel} turn failed`;

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

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ import {
3535
} from "./run-attempt-state.js";
3636
import type { prepareCodexAttemptTurnRequest } from "./run-attempt-turn-request.js";
3737
import type { CodexAttemptTurnState } from "./run-attempt-turn-state.js";
38+
import { captureCodexSettledTurnFinalizationContext } from "./settled-turn-context.js";
3839
import { settleCodexSourceReplyFinality } from "./source-reply-finality.js";
3940
import { normalizeCodexTrajectoryError, recordCodexTrajectoryCompletion } from "./trajectory.js";
4041
import { codexTranscriptMirrorRuntime } from "./transcript-mirror.js";
@@ -319,7 +320,7 @@ export async function finalizeCodexAttempt(
319320
} else {
320321
codexModelCallDiagnostics.emitCompleted(result);
321322
}
322-
const assistantTranscriptOwned = await codexTranscriptMirrorRuntime.mirrorBestEffort({
323+
const mirrorOutcome = await codexTranscriptMirrorRuntime.mirrorBestEffort({
323324
params,
324325
agentId: sessionAgentId,
325326
notifyUserMessagePersisted,
@@ -329,6 +330,27 @@ export async function finalizeCodexAttempt(
329330
threadId: resourceState.thread.threadId,
330331
turnId: activeTurnId,
331332
});
333+
const { assistantTranscriptOwned } = mirrorOutcome;
334+
const shouldCaptureSettledTurnFinalizationContext =
335+
turnSucceeded &&
336+
result.assistantTexts.every((text) => !text.trim()) &&
337+
result.messagesSnapshot.some((message) => message.role === "toolResult");
338+
const settledTurnFinalizationContext = shouldCaptureSettledTurnFinalizationContext
339+
? await captureCodexSettledTurnFinalizationContext({
340+
...activeTranscriptTarget,
341+
mirroredMessages: mirrorOutcome.mirroredMessages,
342+
settledMessages: result.messagesSnapshot,
343+
turnId: activeTurnId,
344+
})
345+
: undefined;
346+
if (shouldCaptureSettledTurnFinalizationContext && !settledTurnFinalizationContext) {
347+
// The isolated child must not infer around a partial or drifting transcript.
348+
// Omitting this field preserves the existing incomplete-turn failure.
349+
embeddedAgentLog.warn("codex settled-turn finalization context is unavailable", {
350+
threadId: resourceState.thread.threadId,
351+
turnId: activeTurnId,
352+
});
353+
}
332354
if (activeContextEngine) {
333355
const contextEnginePluginId = resolveContextEngineOwnerPluginId(activeContextEngine);
334356
const isHeartbeat =
@@ -498,6 +520,7 @@ export async function finalizeCodexAttempt(
498520
...(codexAppServerFailure ? { codexAppServerFailure } : {}),
499521
...(promptTimeoutOutcome ? { promptTimeoutOutcome } : {}),
500522
...(assistantTranscriptOwned ? { assistantTranscriptOwned: true } : {}),
523+
...(settledTurnFinalizationContext ? { settledTurnFinalizationContext } : {}),
501524
...(resourceState.runtimeArtifact ? { runtimeArtifact: resourceState.runtimeArtifact } : {}),
502525
...(!finalAborted && !effectiveTimedOut && !finalPromptError && preparedAuthBinding
503526
? { authBindingFingerprint: preparedAuthBinding.fingerprint }

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

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3578,6 +3578,73 @@ describe("runCodexAppServerAttempt", () => {
35783578
});
35793579
});
35803580

3581+
it("captures the complete mirrored branch through a settled tool-result boundary", async () => {
3582+
const storePath = path.join(tempDir, "settled-finalization-context.sqlite");
3583+
const sessionId = "session-settled-finalization-context";
3584+
const sessionFile = `sqlite:main:${sessionId}:${storePath}`;
3585+
const workspaceDir = path.join(tempDir, "workspace-settled-finalization-context");
3586+
const harness = createStartedThreadHarness();
3587+
const params = createParams(sessionFile, workspaceDir);
3588+
attachSqliteSessionTarget(params, storePath, sessionId);
3589+
params.prompt = "Send the update to Alice.";
3590+
3591+
const run = runCodexAppServerAttempt(params);
3592+
await harness.waitForMethod("turn/start");
3593+
await harness.notify({
3594+
method: "item/started",
3595+
params: {
3596+
threadId: "thread-1",
3597+
turnId: "turn-1",
3598+
item: {
3599+
type: "commandExecution",
3600+
id: "tool-settled",
3601+
command: "echo sent-to-alice",
3602+
cwd: workspaceDir,
3603+
processId: null,
3604+
source: "agent",
3605+
status: "inProgress",
3606+
commandActions: [],
3607+
aggregatedOutput: null,
3608+
exitCode: null,
3609+
durationMs: null,
3610+
},
3611+
},
3612+
});
3613+
await harness.notify({
3614+
method: "item/completed",
3615+
params: {
3616+
threadId: "thread-1",
3617+
turnId: "turn-1",
3618+
item: {
3619+
type: "commandExecution",
3620+
id: "tool-settled",
3621+
command: "echo sent-to-alice",
3622+
cwd: workspaceDir,
3623+
processId: 42,
3624+
source: "agent",
3625+
status: "completed",
3626+
commandActions: [],
3627+
aggregatedOutput: "sent-to-alice\n",
3628+
exitCode: 0,
3629+
durationMs: 12,
3630+
},
3631+
},
3632+
});
3633+
await harness.completeTurn({ threadId: "thread-1", turnId: "turn-1" });
3634+
3635+
const result = await run;
3636+
3637+
expect(result.settledTurnFinalizationContext).toMatchObject({
3638+
source: "openclaw-transcript",
3639+
messages: [
3640+
expect.objectContaining({ role: "user" }),
3641+
expect.objectContaining({ role: "assistant" }),
3642+
expect.objectContaining({ role: "toolResult", toolCallId: "tool-settled" }),
3643+
],
3644+
});
3645+
expect(Object.isFrozen(result.settledTurnFinalizationContext?.messages)).toBe(true);
3646+
});
3647+
35813648
it("preserves every command failure from official app-server events", async () => {
35823649
const sessionFile = path.join(tempDir, "session-multi-command-failure.jsonl");
35833650
const workspaceDir = path.join(tempDir, "workspace-multi-command-failure");

0 commit comments

Comments
 (0)