Skip to content

fix(agents): restore channel and cron replies after a failed final tool - #118344

Merged
steipete merged 1 commit into
mainfrom
codex/fix-118274-terminal-failed-tools-v2
Aug 3, 2026
Merged

steipete merged 1 commit into
mainfrom
codex/fix-118274-terminal-failed-tools-v2

Conversation

@steipete

@steipete steipete commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Closes #118274
Related: #118315

Additional instructions

MUST: Keep Allow edits from maintainers enabled for this PR so maintainers
can help update the branch when needed.

What Problem This Solves

Fixes an issue where users whose final tool call fails would receive no final assistant reply in channel conversations, including Telegram, or isolated cron announcements even though every requested tool had fully settled. The failed operation became a generic missing-reply warning instead of an honest, user-visible explanation.

Reported with a detailed source reproduction by @Cuttingwater in #118274; the Telegram failure mode was independently confirmed by @wzg0911.

Why This Change Was Made

Finish settled failed-tool turns at the existing shared agent-runner owner boundary, with exactly one tools-disabled finalization only after every current-batch tool-call ID and tool owner matches its settled result. Preserve the real model assistant as the terminal owner when Code Mode projects nested tool evidence, recognize the internal synthetic error fallback without dropping genuine visible payloads, and explicitly require the model to report failures honestly.

Existing fail-closed protections remain in place for missing or partial results, wrong tool owners, stale errors, active/background work, child sessions, approvals, yielded turns, and finalization failures. The existing warning remains the fallback if finalization cannot complete.

User Impact

Channel users and scheduled-job operators receive one accurate final reply explaining a completed tool failure instead of a silent turn, generic missing-response warning, or failed cron announcement. Failed tools are never replayed, duplicate side effects are not introduced, and successful tool-turn behavior is unchanged.

Evidence

  • Real gateway + qa-channel + isolated cron end-to-end proof, using the deterministic mock OpenAI provider:

    FS_SAFE_NATIVE_MODE=off pnpm openclaw qa suite \
      --provider-mode mock-openai \
      --scenario qa-channel-failed-tool-terminal-finalization \
      --scenario cron-failed-tool-terminal-finalization \
      --concurrency 1 --fast \
      --output-dir .artifacts/qa-e2e/failed-terminal-118274-stable-owner

    Both scenarios passed. Each executes exactly one real failing Code Mode exec, proves the persisted transcript contains one failed result and zero successful results, verifies the exact normalized parent function_call / function_call_output ID and ENOENT payload, observes exactly one failure-honest tools-disabled finalization, and receives exactly one visible qa-channel reply without replay.

  • Complete owner, projection-sibling, and mock-provider regression suites: 473 tests passed across four complete Vitest shards:

    OPENCLAW_VITEST_NO_OUTPUT_TIMEOUT_MS=420000 \
    OPENCLAW_VITEST_NO_OUTPUT_HEARTBEAT_MS=15000 \
    FS_SAFE_NATIVE_MODE=off pnpm test \
      src/agents/embedded-agent-runner/run.incomplete-turn.test.ts \
      src/agents/embedded-agent-runner/run/attempt-phase-lifecycle.test.ts \
      extensions/qa-lab/src/providers/mock-openai/server.test.ts \
      src/agents/tool-search.test.ts \
      --maxWorkers=1 --reporter=dot
  • Full nine-path pnpm check:changed completed successfully on Blacksmith Testbox, including all-project TypeScript, all core/plugin/script lint lanes, formatting, SDK contract and plugin-boundary guards, dead-export and storage guards, and zero runtime import cycles.

  • Fresh independent xhigh autoreview completed with zero accepted findings. One suggestion to read the ephemeral isolated-cron run session was rejected using direct source and the live scenario: src/cron/isolated-agent/run.ts removes that transient session, while src/cron/isolated-agent/run-session-state.test.ts proves the stable cron job session owns the persisted transcript.

  • Upstream Codex protocol/runtime contract inspected directly at openai/codex@07490c75234ed3c63291a8eb7629f04f647038fa:

AI-assisted; independently reviewed and validated end to end.

Canonical Maintainer Decision and Rank-Up Moves

  • Select this maintainer-authored PR as canonical over bot PR fix(agents): finalize settled failed tool turns #118315. Its three-file patch does not correct the synthetic tool-error payload count or projected target-tool assistant ownership; both independently block the actual channel/cron user path. This PR repairs all three shared-owner causes and proves both real end-to-end delivery paths.
  • Direct Codex upstream inspection was completed personally at openai/codex@07490c75234ed3c63291a8eb7629f04f647038fa: codex-rs/protocol/src/models.rs:676, codex-rs/core/src/tools/context.rs:470, codex-rs/core/src/stream_events_utils.rs:294, and codex-rs/core/src/session/turn.rs:363.
  • Current main was refreshed and all nine changed paths were independently checked: no upstream commit has touched any of them since the reviewed branch base. Following the repository policy not to rebase solely because unrelated main commits advanced, the proven exact head is retained; its required openclaw/ci-gate is SUCCESS.
  • Net production growth is +75 lines, justified by exact failed-call/owner correlation, synthetic-payload ownership, and projected-assistant terminal ownership. Tests and the two executable QA scenarios account for the remaining growth.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling extensions: qa-lab size: L maintainer Maintainer-authored PR labels Aug 3, 2026
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Aug 3, 2026
@clawsweeper clawsweeper Bot added mantis: telegram-visible-proof Mantis should capture Telegram visible proof. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. labels Aug 3, 2026
@clawsweeper

clawsweeper Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 2, 2026, 9:30 PM ET / August 3, 2026, 01:30 UTC.

ClawSweeper review

What this changes

The PR permits one tools-disabled, failure-honest final reply after every terminal tool call has a matching settled result, with regressions and isolated QA scenarios for channel and cron delivery.

Merge readiness

⚠️ Needs maintainer review before merge - 4 items remain

This PR remains necessary: current main still treats a failed toolResult as incomplete and separately rejects lastToolError, so a fully settled failed tool can reach channel or isolated-cron delivery without a model final reply. The exact PR head adds matched call-ID/tool-owner settlement, prevents projected Code Mode evidence from becoming the terminal model turn, and supplies focused and QA coverage; no discrete patch defect was found. It should remain in maintainer review rather than merge automatically because the repository policy requires this reviewer to inspect sibling ../codex source for the invoked protocol contract, and that checkout is unavailable here.

Priority: P1
Reviewed head: 112f37f49cec2871e2f564948c6332d6678aedce
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The patch has strong focused and QA evidence with no discrete defect found, but the repository-required direct Codex dependency audit is still missing from this review environment.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The PR body provides after-fix isolated gateway scenarios that exercise one real failing Code Mode operation, verify one tools-disabled finalization, and assert exactly one visible qa-channel reply for both channel and cron paths.
Patch quality 🦐 gold shrimp (3/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The PR body provides after-fix isolated gateway scenarios that exercise one real failing Code Mode operation, verify one tools-disabled finalization, and assert exactly one visible qa-channel reply for both channel and cron paths.
Evidence reviewed 8 items Current-main failure boundary: Current main only counts post-terminal tool results when isError !== true and independently rejects any lastToolError; therefore a matching failed result cannot authorize the settled-tool finalization path.
Exact repair guard: The PR requires each terminal call ID to map to a result with the same tool owner, allows only attributable settled failures, and retains fail-closed checks for active, spawned, client, yielded, and approval-bound work.
Projected transcript ownership: The PR keeps projected target-tool transcript messages for evidence while deriving lastAssistant and currentAttemptAssistant from the original model snapshot, preventing projected nested tool calls from hiding the parent terminal outcome.
Findings None None.
Security None None.

How this fits together

The embedded agent runner converts a model's tool-call transcript into a final assistant payload. Channel adapters and isolated cron jobs consume that payload, so the runner's settled-turn decision determines whether users receive a final reply or a generic missing-response fallback.

flowchart LR
  A[Model terminal tool call] --> B[Embedded agent runner]
  B --> C[Tool results and lifecycle state]
  C --> D[Settled-turn safety decision]
  D --> E[Tools-disabled final response]
  E --> F[Channel reply or cron announcement]
Loading

Decision needed

Question Recommendation
Can a maintainer or reviewer with the sibling Codex checkout directly verify the function-call output identity and required follow-up-turn contract for this exact finalization path before merge? Complete the direct Codex audit: Inspect the sibling Codex protocol and turn-loop source, then merge if it confirms the PR's exact call-ID and follow-up assumptions.

Why: OpenClaw policy makes direct personal inspection of ../codex a hard gate for a Codex-dependent verdict; this read-only environment has no sibling checkout, while the supplied PR links are not a substitute.

Before merge

  • Resolve merge risk (P1) - The repository-required direct audit of the Codex function-call identity and follow-up-turn contract could not be completed because sibling ../codex is unavailable in this read-only checkout.
  • Resolve merge risk (P1) - Merging changes the final-response decision after failed tools; a contract review must confirm that ID and tool-owner matching remains valid for the supported Codex protocol version.
  • Complete next step (P2) - The PR is active, protected by the maintainer label, and has sufficient runtime evidence, but the missing reviewer-local Codex contract audit is a human proof-sufficiency gate rather than an automated code repair.
Agent review details

Security

None.

PR surface

Source +75, Tests +556, Other +305. Total +936 across 9 files.

View PR surface stats
Area Files Added Removed Net
Source 4 102 27 +75
Tests 3 556 0 +556
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 2 305 0 +305
Total 9 963 27 +936

Review metrics

Metric Value Why it matters
Production versus regression LOC +75 production net; +861 QA/test additions The production growth is bounded to failed-result correlation, synthetic fallback classification, and terminal-assistant ownership; the larger remainder is executable regression evidence.

Stored data model

Persistent data-model change detected: migration/backfill/repair: qa/scenarios/channels/qa-channel-failed-tool-terminal-finalization.yaml, serialized state: extensions/qa-lab/src/providers/mock-openai/server.test.ts. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #118274
Summary: This PR is a concrete candidate fix for the canonical failed settled-tool final-reply report; current main still has the reported decision boundary.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Mantis proof suggestion

A short Telegram Desktop recording would provide direct user-visible confirmation that a failed tool ends with one honest final reply and no replay. A maintainer can ask Mantis to capture proof by posting this exact PR comment:

@openclaw-mantis telegram desktop proof: reproduce one settled failed tool and capture that exactly one failure-honest final reply is delivered without replay.

Merge-risk options

Maintainer options:

  1. Complete the Codex contract audit (recommended)
    Before merge, directly inspect the supported Codex protocol and turn-loop source to confirm exact call-ID ownership and the required tools-disabled follow-up turn.
  2. Pause pending runtime-contract evidence
    Do not merge until a reviewer can supply the required direct dependency evidence for the behavior that authorizes finalization after a failed tool.

Technical review

Best possible solution:

Keep this as the canonical candidate for #118274, complete the required direct Codex contract review, then merge this shared-runner repair if that audit confirms the existing exact-call-ID and follow-up-turn assumptions.

Do we have a high-confidence way to reproduce the issue?

Yes, source-reproducible: current main excludes errored tool results from terminal completion and rejects lastToolError, while the documented attempt shape has a matched failed result and no active work. No local test was run because this review is read-only.

Is this the best way to solve the issue?

Unclear pending the required Codex contract audit: the shared embedded-runner boundary is the right owner and the patch is narrowly guarded, but the runtime assumptions about function-call identity and required follow-up must be directly verified before a merge verdict.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against f2af4e97b356.

Labels

Label justifications:

  • P1: A failed but settled terminal tool can currently suppress the final reply for ordinary channel conversations and required isolated cron announcements.
  • merge-risk: 🚨 message-delivery: The changed finalization decision determines whether the channel or cron delivery layer receives a final payload after a failed tool.
  • merge-risk: 🚨 session-state: The patch changes which transcript assistant owns terminal state and how current-batch tool results are correlated to it.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🦐 gold shrimp.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The PR body provides after-fix isolated gateway scenarios that exercise one real failing Code Mode operation, verify one tools-disabled finalization, and assert exactly one visible qa-channel reply for both channel and cron paths.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body provides after-fix isolated gateway scenarios that exercise one real failing Code Mode operation, verify one tools-disabled finalization, and assert exactly one visible qa-channel reply for both channel and cron paths.
  • mantis: telegram-visible-proof: Mantis should capture Telegram visible proof. The repaired failure mode is visibly user-facing in Telegram: a settled failed tool should produce one honest final reply instead of a missing-response fallback.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: He authored the current-main settled-turn implementation commit and the proposed repair commit, so the shared agent-runner terminal-finalization history points to him most strongly. (role: feature owner and recent area contributor; confidence: high; commits: 181da6f69c45, 112f37f49cec; files: src/agents/embedded-agent-runner/run/incomplete-turn.ts, src/agents/embedded-agent-runner/run/terminal-resolution.ts, src/agents/embedded-agent-runner/run/attempt-stream-settle.ts)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Have a reviewer with sibling ../codex inspect the exact function-call output identity and follow-up-turn contract.
  • If the audit confirms the assumptions, retain the current focused scope and merge without adding another fallback path.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (1 earlier review cycle)
  • reviewed 2026-08-03T01:05:53.029Z sha 112f37f :: needs maintainer review before merge. :: none

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. labels Aug 3, 2026
@steipete
steipete merged commit 1fedcca into main Aug 3, 2026
144 of 164 checks passed
@steipete
steipete deleted the codex/fix-118274-terminal-failed-tools-v2 branch August 3, 2026 02:40
@steipete

steipete commented Aug 3, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

@yubingjiaocn

Copy link
Copy Markdown

Thanks for landing this — treating an explicit failed toolResult as settled and guaranteeing a failure-honest final payload fixes the silent-terminal bug.

One follow-up question: should the runner distinguish recoverable pre-effect tool failures from failures that may have produced side effects, instead of sending every settled failure directly into a tools-disabled finalization?

For example, direct edit can fail before mutation with deterministic diagnostics such as:

  • oldText not found
  • match is not unique
  • edits overlap
  • argument/schema validation failure

Those failures are normally repairable by the model: re-read the current file, construct a new unique anchor, and try once more. With the new disableTools: true finalization path, the agent can only report the failure; it cannot complete the original task. Cron's run-level retry does not help because these errors are not transient (rate_limit, network, timeout, etc.), and blindly restarting the whole cron run would not be the right repair anyway.

A possible bounded policy:

  1. Proven pre-effect/recoverable failure: allow one tools-enabled repair continuation, with an instruction to re-read state and not replay identical arguments.
  2. Mutation outcome uncertain (timeout, post-write verification failure): allow only state inspection first, or keep the current fail-closed finalization.
  3. Auth/policy/permission failure: keep the current tools-disabled finalization.
  4. After the repair budget is exhausted, fall back to the failure-honest tools-disabled finalization added here.

This would be a bounded recoverable-tool continuation, not generic automatic retry. It preserves the safety goal of this PR while avoiding premature termination for clearly fixable, side-effect-free failures. The Code Mode work in #115311 / #115869 seems directionally related, but I could not find equivalent coverage for ordinary direct edit calls.

Would maintainers prefer this as a separate feature/bug issue, or is it considered follow-up scope for the incomplete-turn recovery policy?

@Cuttingwater

Copy link
Copy Markdown
Contributor

I agree with separating this from the merged failure-honest terminal fix.

The proposal changes execution policy, not just terminal presentation: it authorizes another mutating-capable model/tool step after a failure. That deserves a focused follow-up issue and its own safety matrix rather than expanding the settled-failure repair after merge.

The bounded continuation should be driven by typed tool-boundary provenance, not message parsing. A repair continuation should require all of the following:

  • execution is proven not to have started or the tool explicitly reports a precondition/validation failure;
  • the tool classifies the failure as recoverable and pre-effect;
  • no async, child-session, approval, delivery, or external side-effect work exists;
  • the action fingerprint differs from the failed call;
  • the model gets one repair budget and must re-read/inspect current state before retrying.

Examples such as oldText not found, non-unique match, overlapping edits, and argument/schema validation can qualify only when the tool reports those as typed pre-effect outcomes. Unknown outcomes, timeouts, auth/policy/permission failures, post-write verification failures, and provider/transport errors should remain fail closed.

OpenClaw already has useful ingredients in ToolErrorSummary (validationErrorSummary, mutatingAction, actionFingerprint, fileTarget, timedOut, and middlewareError), but the tool boundary should emit an explicit execution-effect classification before the runner consumes it. After the one repair budget is exhausted, fall back to the merged tools-disabled failure-honest finalization.

So my recommendation is: separate follow-up issue, narrow first implementation for direct file edits, and no generic automatic retry.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling extensions: qa-lab maintainer Maintainer-authored PR mantis: telegram-visible-proof Mantis should capture Telegram visible proof. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: L status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Fully settled failed tool turns produce no final assistant payload in channels and cron

3 participants