Skip to content

feat(plugins): let tools deliver their finished reply without a second model turn - #164558

Merged
mbelinky merged 14 commits into
mainfrom
feat/tool-authored-source-reply
Oct 4, 2026
Merged

mbelinky merged 14 commits into
mainfrom
feat/tool-authored-source-reply

Conversation

@mbelinky

@mbelinky mbelinky commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

A plugin tool that already produces the finished user reply (a report, a confirmation, a formatted answer) still costs a second model turn: OpenClaw feeds the tool result back to the model, which restates the same text before anything reaches the channel. On a Telegram sales bot with such tools that extra turn is about 6 seconds of every reply.

User Impact

User impact: a plugin tool can declare canDeliverSourceReply and return its finished reply in details.sourceReply. OpenClaw delivers that reply to the conversation the turn came from, ends the tool batch, and records the reply as the assistant turn after the send. Nothing opts in by default; existing tools and the message tool are unchanged.

Why This Change Was Made

The runtime already has a source-reply path for the built-in message tool: such replies are delivered even when automatic replies are suppressed, and mirrored into the transcript by delivery, with its session, lifecycle-revision and writer-run checks. This PR lets an author-declared tool capability feed that same path, instead of adding a parallel one.

  • Admission is narrow. The capability lives on the tool definition, never in a result. Error results, calls made from inside a Code Mode program, results without nonblank text or media, and sourceReply.final: false are never admitted; the model continues as usual. Admission and delivery resolve media through one shared function, so a reply whose media entries are all blank cannot end a turn that delivery would then drop. On the embedded runtime, nested calls carry a parent call id and are rejected at completion. On Codex, only calls in the model-only openclaw_direct namespace qualify; Codex never exposes that namespace to Code Mode programs, so a program call cannot end the turn or reach the conversation.
  • Middleware stays in charge. The reply is read from the effective result after hooks, result middleware and extensions, so middleware can rewrite or withdraw it. This holds on the embedded runtime and the Codex bridge.
  • No early writes. Nothing is persisted at tool time. The transcript row is written by delivery after a successful send.
  • Turn completion. A captured reply ends the turn once every call from that model step has settled, whatever the other calls returned and whether or not they executed. The agent loop gains one internal, OpenClaw-only hook for this: it runs once per assistant message after all its tool batches settle and may end the turn even when not every result asked to terminate. Steering still takes precedence, exactly as with a terminating batch. The hook admits exactly what the completion handler captures (a direct, capable, non-error result with a deliverable final reply), so it can never end a turn without a reply to deliver. The batch-combining step moved into tool-batch-completion.ts, which keeps agent-loop.ts under its line cap. Incomplete-turn resolution treats the captured reply as a complete turn: the delivery state still reads "missing" until the host sends it.
  • Codex batch release. The Codex harness releases a turn after a terminal dynamic tool only when no ordinary sibling result arrived in the batch. A captured tool-authored final reply now marks its batch complete, so an ordinary sibling still settles but cannot reopen the turn, in either completion order. Other terminal tools keep the existing behavior. The per-result classification moved from the server-request handler into the lifecycle controller (recordDynamicToolResult), where both orders are tested.

The SDK gains one helper, captureToolAuthoredSourceReply, used by the Codex harness; the pinned surface budget is raised by one with a reason comment. The Codex bridge's source-reply decisions moved into dynamic-tool-source-reply.ts, so dynamic-tools.ts does not grow past its line cap.

Evidence

Live on Telegram, an agent on the embedded runtime (gpt-5.6-terra) with a test plugin exposing two identical tools, one with the capability and one without, after the review-driven rework:

Turn Tool finished Telegram send Transcript row Post-tool time
Tool-authored reply 06:21:04.81 06:21:05.02 06:21:05.04 (written by delivery, after the send) 0.2 s
Ordinary tool, model restates 06:21:14.15 06:21:20.26 06:21:19.90 (model turn) 6.1 s

The reply text arrived verbatim, with no warning and no post-tool model turn.

Session writer replacement. The captured reply takes the same final-reply delivery path as the model's own final answer. Delivery mirrors it into the transcript only after a successful send, under the dispatching run's session, lifecycle-revision and writer-run fence. A new test drives the payload built from a tool-authored capture through that mirror against a real session store: with the admitted writer it writes exactly one assistant row (a repeat is deduped), and after the session writer is replaced it writes none. The channel send itself is fenced exactly as for any ordinary final answer: this PR adds no new send path and does not widen that boundary.

✓ tool-authored source reply transcript mirror > writes the assistant row once for the admitted writer
✓ tool-authored source reply transcript mirror > writes nothing after the session writer is replaced
✓ turn completion > ends the turn after the whole batch settles when the capable tool finishes first
✓ turn completion > ends the turn after the whole batch settles when the ordinary tool finishes first
✓ turn completion > ends the turn when a second capable tool in the batch returns a progress reply / an error / ordinary details
✓ turn completion > ends the turn when another call is rejected before it executes
✓ turn completion > lets the model continue when the capable tool authored a progress reply / failed / reported ok: false / returned no source reply
✓ turn completion > reads the result after afterToolCall hooks, so a hook can withdraw the reply
✓ Codex tool-authored source replies > ignores a reply from a call in the searchable namespace, which Code Mode programs can reach
✓ Codex tool-authored source replies > ignores a reply from a call in the dynamic-tool root, which Code Mode programs can reach
✓ Codex batch release after a tool-authored final reply > releases the turn once the batch settles, completing reply then note / note then reply
✓ Codex batch release after a tool-authored final reply > keeps an ordinary terminal tool's batch open after a non-terminal sibling, both orders

The turn-completion tests drive the real agent loop with parallel tools held on explicit gates (no timers), assert the completion order, and count provider requests. Five of them fail on the previous head, including one more defect it had: a capable tool reporting ok: false ended the turn although the completion handler never captured its reply. The Codex namespace tests also fail on the previous head.

Test cost (local Vitest, per new or changed test file):

Test file Tests Duration
embedded-agent-messaging-extraction.tool-authored.test.ts 11 3 ms
message-tool-terminal.tool-authored.test.ts (real agent loop) 16 16 ms
payloads.tool-authored.test.ts 3 6 ms
embedded-agent-subscribe.handlers.tools.source-reply.test.ts 6 13 ms
dynamic-tools.tool-authored-source-reply.test.ts (Codex) 7 33 ms
dispatch-from-config.transcript.tool-authored.test.ts (real session store) 2 2.1 s

The transcript-mirror file spends its time opening a real SQLite session store on the first test; the second test takes about 140 ms.

The live runs also caught two real defects, both fixed with regression tests that fail without the fix:

  • The base agent session answers afterToolCall with { isError }; an early per-call hook misread that partial override and never ended the turn. Turn completion now reads the finalized tool results after every hook has applied.
  • A live run starts with the source-reply delivery state at "missing", which makes the existing delivery check ignore the final marker. Tool-authored evidence is now checked directly. The unit test uses that real starting state.

Tests cover extraction (text, media, blank media, attachments-only, final: false), turn completion through the real agent loop (completion orders, two capable tools, pre-execution rejection, errors, ok: false, afterToolCall withdrawal, name normalization), the transcript mirror under writer replacement, the completion handler (capability gate, errors, nested calls, non-final replies), the payload builder (delivery despite suppression, transcript mirror without an owner, in both reply modes), incomplete-turn resolution, client tool-set collection, the session prepare hook installation, the Codex bridge (terminate, middleware rewrite and withdrawal, non-final, capability gate, program-reachable namespaces), and Codex batch release in both sibling orders, including an ordinary terminal tool whose batch must stay open.

Checks on this branch, rebased on current main: pnpm tsgo:core, tsgo:extensions, tsgo:core:test, tsgo:extensions:test; 1,700+ tests across the affected suites; pnpm format:check, format:docs:check; the plugin SDK surface check; and the line-cap, assertion-safety and mock-export ratchets.

🤖 Generated with Claude Code

@clawsweeper

clawsweeper Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@github-actions

github-actions Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Security sensitive changes

This maintainer PR changes sensitive security components.

No secops approval is required. This comment is informational because the PR author has Maintain or Admin access.

  • Current SHA: 9c8d3d30ec7862a6808f5943dca1fdf4cd1a5795
  • Maintainer: @mbelinky
  • Repository role: maintain

These security sensitive changes were made:

  • src/agents/embedded-agent-tool-authored-source-reply.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.

Carefully review these changes before merging.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime agents Agent runtime and tooling extensions: codex size: L labels Oct 3, 2026
@clawsweeper

clawsweeper Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed October 4, 2026, 4:59 AM ET / 08:59 UTC (Revision 11).

ClawSweeper review

What this changes

Adds an optional plugin-tool capability that delivers a finished reply through OpenClaw’s conversation delivery pipeline without another model turn.

Merge readiness

✅ Ready for maintainer review

The work remains useful: current main and the latest release lack this capability. The latest head resolves the prior Codex sibling-completion blocker, and no remaining actionable introduced defect was identified.

Priority: P2
Reviewed head: 9c8d3d30ec7862a6808f5943dca1fdf4cd1a5795

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A useful, focused capability with concrete live evidence and resolved prior completion findings.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The captured live Telegram comparison exercises embedded reply capture through delivery and shows verbatim output without a post-tool model turn; Codex sibling-order and writer-replacement tests supplement that evidence. No stored-data format or migration contract changes.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The captured live Telegram comparison exercises embedded reply capture through delivery and shows verbatim output without a post-tool model turn; Codex sibling-order and writer-replacement tests supplement that evidence. No stored-data format or migration contract changes.
Evidence reviewed 10 items Pinned introduction and review continuity: Reviewed the merge-base-to-head introduced changes. GitHub’s exact-head commit patch independently confirms that the latest commit carries the admitted-final-reply fact into lifecycle classification, preserves it across ordinary siblings, and adds both completion-order cases. This resolves the previous completed review’s concrete blocker.
Embedded batch completion: The completion hook evaluates finalized results after all batches settle. Regression coverage exercises both sibling orders, rejection before execution, another capable tool without a final reply, structured errors, middleware withdrawal, and blank media; provider-request counts verify the intended continuation decision.
Reply admission and dependency signal: The Codex bridge captures the effective result after middleware and extensions, requires the author-declared capability, rejects errors, and admits only the openclaw_direct namespace. Its explicit reliance on Codex excluding that namespace from program calls establishes the dependency-specific inspection requirement.
Findings None None.
Security None None.

How this fits together

The agent runtime processes tool results before deciding whether to request another model response. Admitted tool-authored replies pass through the existing conversation delivery owner, which sends them and records the assistant reply after successful delivery.

flowchart TD
  A[Model tool calls] --> B[Tools and result middleware]
  B --> C{Direct capable call with final reply?}
  C -->|No| D[Continue model response]
  C -->|Yes| E[Settle sibling calls and finish turn]
  E --> F[Conversation delivery]
  F --> G[Send reply and mirror transcript]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +346, Tests +930, Docs +51, Other +1. Total +1328 across 44 files.

View PR surface stats
Area Files Added Removed Net
Source 25 409 63 +346
Tests 16 933 3 +930
Docs 1 51 0 +51
Config 0 0 0 0
Generated 0 0 0 0
Other 2 4 3 +1
Total 44 1397 69 +1328

Review metrics

Metric Value Why it matters
Production versus regression coverage Production +346 net lines; tests and support +930 net lines Production growth implements the shared opt-in capability in both runtimes, with most added coverage protecting admission and completion regressions.
Plugin contract expansion 1 optional tool capability; 1 SDK helper; 0 config options The new public surface is documented in the PR and tool-plugin guide, while existing tools remain opt-out by default.

Technical review

Best possible solution:

Keep one opt-in reply-admission contract across runtimes, with ordinary tools continuing normally and the existing delivery owner retaining send and transcript authority.

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

Not applicable as a feature request; the captured live comparison demonstrates the extra model-turn cost and the embedded runtime’s improved result.

Is this the best way to solve the issue?

Yes. The patch extends the existing source-reply delivery owner and adds a narrow capability rather than introducing another send or transcript-writing pipeline.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against bced15851945.

Labels

Label changes:

  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The captured live Telegram comparison exercises embedded reply capture through delivery and shows verbatim output without a post-tool model turn; Codex sibling-order and writer-replacement tests supplement that evidence. No stored-data format or migration contract changes.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.
  • remove merge-risk: 🚨 message-delivery: Current PR review selected no merge-risk labels.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: This is a bounded plugin-runtime latency improvement with opt-in behavior and no demonstrated urgent existing-user regression.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The captured live Telegram comparison exercises embedded reply capture through delivery and shows verbatim output without a post-tool model turn; Codex sibling-order and writer-replacement tests supplement that evidence. No stored-data format or migration contract changes.
  • proof: sufficient: Contributor real behavior proof is sufficient. The captured live Telegram comparison exercises embedded reply capture through delivery and shows verbatim output without a post-tool model turn; Codex sibling-order and writer-replacement tests supplement that evidence. No stored-data format or migration contract changes.
  • proof: telegram-e2e: This PR needs Telegram Test Server proof with the repository E2E skill. The capability changes visible Telegram reply text and timing; the supplied live comparison demonstrates the embedded behavior.

Evidence

What I checked:

  • Pinned introduction and review continuity: Reviewed the merge-base-to-head introduced changes. GitHub’s exact-head commit patch independently confirms that the latest commit carries the admitted-final-reply fact into lifecycle classification, preserves it across ordinary siblings, and adds both completion-order cases. This resolves the previous completed review’s concrete blocker. (extensions/codex/src/app-server/run-attempt-lifecycle-controller.ts:120, 9c8d3d30ec78)
  • Embedded batch completion: The completion hook evaluates finalized results after all batches settle. Regression coverage exercises both sibling orders, rejection before execution, another capable tool without a final reply, structured errors, middleware withdrawal, and blank media; provider-request counts verify the intended continuation decision. (src/agents/embedded-agent-runner/run/message-tool-terminal.tool-authored.test.ts:151, 9c8d3d30ec78)
  • Reply admission and dependency signal: The Codex bridge captures the effective result after middleware and extensions, requires the author-declared capability, rejects errors, and admits only the openclaw_direct namespace. Its explicit reliance on Codex excluding that namespace from program calls establishes the dependency-specific inspection requirement. (extensions/codex/src/app-server/dynamic-tool-source-reply.ts:79, 9c8d3d30ec78)
  • Personally inspected Codex namespace contract: At the inspected dependency revision, configured direct-only namespaces receive DirectModelOnly exposure, and Code Mode’s nested-tool construction excludes that exposure. Repository identity and the exact dependency SHA were independently verified through GitHub. (codex-rs/core/src/tools/spec_plan.rs:520, a956835d0207)
  • Existing delivery and transcript authority: The changed payload builder uses the existing source-reply metadata. The unchanged dispatch owner checks writer delivery authority, binds transcript metadata to the prepared session/lifecycle/writer, and mirrors only after successful delivery. Added real-session-store tests cover deduplication and writer replacement; they are supplemental persistence coverage, not channel-send proof. (src/auto-reply/reply/dispatch-from-config.choose-route.ts:305, 9c8d3d30ec78)
  • Captured real behavior evidence: The supplied complete PR body, captured under sourceRevision 49b779e8d257d0dfa659735f5f27719d5511f888cc154ec17f6f889bd0941d63, records an embedded-runtime Telegram comparison using two otherwise identical plugin tools. The opted-in reply arrived verbatim without another model turn, with about 0.2 seconds after tool completion versus 6.1 seconds for the ordinary tool; transcript recording followed the send. This demonstrates the changed embedded path, while Codex ordering coverage remains supplemental tests. (9c8d3d30ec78)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • sjf-oa: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

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 (10 earlier review cycles; latest 8 shown)
  • reviewed 2026-10-04T03:51:26.704Z sha f8f7853f10e8b6844995b60aba11d483d9c00131 :: needs real behavior proof before merge. :: [P1] [P1] Honor middleware replacements before delivering Codex replies | [P2] [P2] Preserve attachment-only source replies | [P2] [P2] Dispatch progress replies before continuing the model | [P2] [P2] Exclude nested calls from conversation reply admission | [P2] [P2] Join the Codex assistant transcript write before release
  • reviewed 2026-10-04T04:52:08.054Z sha b47ed19db9d2bb2c3675debefd387e33f2f664da :: needs real behavior proof before merge. :: [P1] [P1] Honor middleware replacements before delivering Codex replies | [P2] [P2] Preserve attachment-only source replies | [P2] [P2] Dispatch progress replies before continuing the model | [P2] [P2] Exclude nested calls from conversation reply admission | [P2] [P2] Join the Codex assistant transcript write before release | [P3] [P3] Remove the release-owned changelog entry
  • reviewed 2026-10-04T06:42:45.676Z sha e73e734 :: needs real behavior proof before merge. :: [P2] [P2] Complete mixed batches after capturing a finished reply | [P2] [P2] Reject native Codex program calls before reply capture
  • reviewed 2026-10-04T06:59:10.583Z sha e72ddfc :: needs real behavior proof before merge. :: [P2] [P2] Complete mixed batches after capturing a finished reply | [P2] [P2] Reject native Codex program calls before reply capture
  • reviewed 2026-10-04T07:30:40.199Z sha 77d2e99 :: blocked before merge. :: [P2] Finish mixed batches when another capable call has no final reply | [P3] Control completion order without real timers
  • reviewed 2026-10-04T07:41:23.156Z sha e1591fa :: blocked before merge. :: [P2] Finish the batch after any admitted final tool reply | [P3] Control tool completion order without real timers
  • reviewed 2026-10-04T08:12:02.598Z sha d013fb1 :: blocked before merge. :: [P2] Reject blank media before admitting a finished reply
  • reviewed 2026-10-04T08:31:28.730Z sha 0b3c8b8 :: blocked before merge. :: [P2] Preserve Codex completion across ordinary sibling results

@mbelinky
mbelinky force-pushed the feat/tool-authored-source-reply branch from e447b7e to f5acf38 Compare October 3, 2026 23:28
@openclaw-barnacle openclaw-barnacle Bot added the scripts Repository scripts label Oct 3, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. proof: telegram-e2e This PR needs Telegram Test Server proof with the repository E2E skill. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 3, 2026
@mbelinky
mbelinky force-pushed the feat/tool-authored-source-reply branch from f8f7853 to b47ed19 Compare October 4, 2026 04:45
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Oct 4, 2026
Mariano Belinky and others added 5 commits October 4, 2026 08:22
…odel turn

Tools can declare canDeliverSourceReply and return the finished reply in
details.sourceReply. The embedded runtime and the Codex bridge record it as a
tool-authored source reply payload, persist it as the assistant turn, deliver
it to the current conversation like assistant text, and terminate the tool
batch when the reply is final, so a tool that already wrote the answer no
longer costs a post-tool model turn.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Collapse the four new harness SDK exports into captureToolAuthoredSourceReply,
used by both the embedded runtime and the Codex bridge, and record the +1
public export in the pinned SDK surface budget. Cover the failed transcript
write path: delivery still proceeds and the failure is logged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Move the message-tool source-reply facts, tool-authored reply capture and
turn termination into dynamic-tool-source-reply.ts so dynamic-tools.ts does
not grow past its line cap. Replace the plugin tool type cast with a property
check, and cover the terminal hook installation in the session prepare test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Address review findings:
- Codex reads the reply from the result after middleware and extensions, so
  middleware can rewrite or withdraw it.
- Drop the early transcript write; tool-authored replies take the existing
  source-reply path and delivery writes the transcript row after the send,
  with its session, lifecycle and writer checks.
- Replies are final only; final: false is ignored and the model continues.
- Admission requires text or media, matching final payload delivery.
- Calls nested inside a Code Mode program are never admitted as replies.
- Treat a captured tool-authored reply as a complete turn: the delivery state
  still reads missing until the host sends it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@mbelinky
mbelinky force-pushed the feat/tool-authored-source-reply branch from b47ed19 to 4a7c373 Compare October 4, 2026 06:32
CHANGELOG/** is generated at release time; the PR description carries the note.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 4, 2026
mbelinky and others added 5 commits October 4, 2026 09:34
…ored replies

A per-call terminate hint cannot see the rest of its batch: a second capable
tool without a final reply, or a call rejected before execution, kept the
turn open and let the model restate the captured reply.

Add one internal, OpenClaw-only agent-loop hook that runs once per assistant
message after all its tool batches settle and may end the turn. The
tool-authored hook admits exactly what the completion handler captures (a
direct, capable, non-error result with a deliverable final reply), which also
fixes an ok:false result ending the turn with nothing captured. The batch
combining step moves to tool-batch-completion.ts, shrinking agent-loop.ts.

Tests drive the real agent loop with explicit gates instead of timers and
assert the completion order.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Admission counted blank mediaUrl/mediaUrls entries that source-reply delivery
drops, so a reply with only blank media could end the turn and deliver
nothing. Admission and delivery now resolve media through one shared
function.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…dinary siblings

The Codex harness releases a turn after a terminal dynamic tool only when no
ordinary sibling result arrived in the batch, so a captured final reply plus
an ordinary sibling let Codex run another model step in either completion
order. A captured tool-authored final reply now marks its batch complete:
siblings still settle but cannot reopen the turn. Other terminal tools keep
the existing behavior.

The per-result classification moves from the server-request handler into the
lifecycle controller, where both completion orders are tested.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clawsweeper clawsweeper Bot added 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. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 4, 2026
@mbelinky
mbelinky merged commit 0ed2e0c into main Oct 4, 2026
155 of 157 checks passed
@mbelinky
mbelinky deleted the feat/tool-authored-source-reply branch October 4, 2026 09:07
@mbelinky

mbelinky commented Oct 4, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 5, 2026
…d model turn (openclaw#164558)

* feat(agents): deliver tool-authored source replies without a second model turn

Tools can declare canDeliverSourceReply and return the finished reply in
details.sourceReply. The embedded runtime and the Codex bridge record it as a
tool-authored source reply payload, persist it as the assistant turn, deliver
it to the current conversation like assistant text, and terminate the tool
batch when the reply is final, so a tool that already wrote the answer no
longer costs a post-tool model turn.

* fix(plugins): expose one SDK helper for tool-authored source replies

Collapse the four new harness SDK exports into captureToolAuthoredSourceReply,
used by both the embedded runtime and the Codex bridge, and record the +1
public export in the pinned SDK surface budget. Cover the failed transcript
write path: delivery still proceeds and the failure is logged.

* fix(codex): extract dynamic tool source-reply decisions

Move the message-tool source-reply facts, tool-authored reply capture and
turn termination into dynamic-tool-source-reply.ts so dynamic-tools.ts does
not grow past its line cap. Replace the plugin tool type cast with a property
check, and cover the terminal hook installation in the session prepare test.

* test(agents): keep real exports in tool-authored reply mocks

* fix(agents): deliver tool-authored replies through the source-reply path

Address review findings:
- Codex reads the reply from the result after middleware and extensions, so
  middleware can rewrite or withdraw it.
- Drop the early transcript write; tool-authored replies take the existing
  source-reply path and delivery writes the transcript row after the send,
  with its session, lifecycle and writer checks.
- Replies are final only; final: false is ignored and the model continues.
- Admission requires text or media, matching final payload delivery.
- Calls nested inside a Code Mode program are never admitted as replies.
- Treat a captured tool-authored reply as a complete turn: the delivery state
  still reads missing until the host sends it.

* chore: drop the release-owned changelog entry

CHANGELOG/** is generated at release time; the PR description carries the note.

* fix(agents): match source-reply capable tools by normalized name

The completion handler compares policy-normalized tool names, so the capable
set and the terminal hook must too; otherwise a tool registered with capitals
would end the turn without its reply being captured.

* fix(agents): complete mixed batches and reject Codex program calls for tool-authored replies

- Other calls in a batch with a capable call carry the terminal hint, so a
  captured final reply ends the turn after the whole batch settles.
- Codex only captures tool-authored replies from the model-only
  openclaw_direct namespace, which Code Mode programs cannot reach.
- Prove the transcript mirror writes nothing after session writer replacement.

* test(agents): avoid returning from a promise executor in the mixed-batch test

* test(agents): type the fake provider stop reason in the mixed-batch test

* fix(agents): end the turn after the whole batch settles for tool-authored replies

A per-call terminate hint cannot see the rest of its batch: a second capable
tool without a final reply, or a call rejected before execution, kept the
turn open and let the model restate the captured reply.

Add one internal, OpenClaw-only agent-loop hook that runs once per assistant
message after all its tool batches settle and may end the turn. The
tool-authored hook admits exactly what the completion handler captures (a
direct, capable, non-error result with a deliverable final reply), which also
fixes an ok:false result ending the turn with nothing captured. The batch
combining step moves to tool-batch-completion.ts, shrinking agent-loop.ts.

Tests drive the real agent loop with explicit gates instead of timers and
assert the completion order.

* test(agents): resolve tool gates without optional promises in the turn-completion test

* fix(agents): reject blank media before admitting a tool-authored reply

Admission counted blank mediaUrl/mediaUrls entries that source-reply delivery
drops, so a reply with only blank media could end the turn and deliver
nothing. Admission and delivery now resolve media through one shared
function.

* fix(codex): keep a tool-authored final reply's batch released past ordinary siblings

The Codex harness releases a turn after a terminal dynamic tool only when no
ordinary sibling result arrived in the batch, so a captured final reply plus
an ordinary sibling let Codex run another model step in either completion
order. A captured tool-authored final reply now marks its batch complete:
siblings still settle but cannot reopen the turn. Other terminal tools keep
the existing behavior.

The per-result classification moves from the server-request handler into the
lifecycle controller, where both completion orders are tested.
RomneyDa added a commit that referenced this pull request Oct 17, 2026
Release-line-only harness fixes that 2026.10.1-2026.10.4 carried but main
(and so release/2026.10.5) never received:

- cron-scheduled-authority: seed the cron authority specimen through the
  published baseline's own SQLite writer (seedPublishedCronJobs) instead of a
  raw cron/jobs.json the candidate now refuses as a retired pre-July store;
  drop owner fields for pre-2026.7.1 baselines (usesCronOwnerAtBaseline).
  Cron-seed parts of a9fd56d and 47ecf4d only; the dispatcher
  passes the package root to seedState.
- bundled plugin runtime smoke: join deferred read-only update discovery via
  update.status before the package-manager child watchdog (from 756a515).
- codex npm plugin live: detect the explicit source-reply finality contract
  anywhere under extensions/codex/src/app-server/ since #164558 moved it to
  dynamic-tool-source-reply.ts (new; no 10.4 equivalent, main also affected).

Test/harness files only.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation extensions: codex gateway Gateway runtime P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. proof: telegram-e2e This PR needs Telegram Test Server proof with the repository E2E skill. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. scripts Repository scripts security-sensitive-changed size: XL 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.

1 participant