Skip to content

fix(gateway): preserve every client tool call when agent calls multiple tools per turn (#52288) - #75580

Merged
steipete merged 3 commits into
openclaw:mainfrom
mrinalgaur2005:fix-multi-client-tool-calls-52288
May 2, 2026
Merged

steipete merged 3 commits into
openclaw:mainfrom
mrinalgaur2005:fix-multi-client-tool-calls-52288

Conversation

@mrinalgaur2005

Copy link
Copy Markdown
Contributor

Summary

Fixes #52288. When an agent invoked multiple client tools in a single turn through /v1/responses, only the last call ever made it back to the caller. The bug had four layers and the fix walks all four:

  • attempt.ts ran every onClientToolCall callback through a single nullable variable. Each new call clobbered the previous one. Replaced with an array that pushes in arrival order.
  • EmbeddedAttemptResult.clientToolCall is renamed to clientToolCalls (Array<{ name; params }>). The field stays undefined when no client tool fired, so the existing truthiness predicates in incomplete-turn.ts and run.ts keep their meaning without a .length check.
  • run.ts now builds pendingToolCalls by mapping over the array. Each call gets its own random id, same shape as before.
  • The non-streaming /v1/responses handler iterates pendingToolCalls and emits one function_call output item per call. The streaming handler walks an output_index counter forward instead of hard-coding output_index: 1, so a turn with N tool calls produces N output_item.added/done pairs at indexes 1..N alongside the assistant message at index 0. The final response.completed payload includes every function_call item in arrival order.

I had a draft fix sitting around for a related response-shape issue and was about to open a separate PR when I found this one. Decided this was the better thing to ship since real users (@bonelli in the thread) reported still hitting it.

Closes #52288.

Test plan

Notes

  • I kept the prior PR fix: support multiple client tool calls per agent turn #52287 in mind while writing this and arrived at the same architectural shape (array end to end, four layers). The differences from that branch:
    • Field is undefined (not an empty array) when no calls were detected, so attempt.clientToolCalls || predicates in incomplete-turn.ts stay one-token reads.
    • Streaming branch uses an output_index counter rather than recomputing per call, making the order/index relationship explicit.
    • Adds a gateway-level regression test (the prior PR had only the runner test), so a future regression at the HTTP boundary surfaces immediately.
  • No public schema changes. The clientToolCall -> clientToolCalls rename is internal to the embedded runner; everything passes through pendingToolCalls after run.ts.

@clawsweeper

clawsweeper Bot commented May 1, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

Summary
The branch changes embedded-runner client-tool metadata to an ordered array, emits all pending /v1/responses function calls in JSON and SSE modes, and adds regression tests plus a changelog entry.

Reproducibility: yes. Current main has a source-level reproduction through the overwritten runner slot and pendingToolCalls[0] response emitters; the PR adds JSON, SSE, runner, and out-of-order hook coverage for the corrected path.

Next step before merge
No repair job is needed; the latest head has no concrete automated repair finding and now needs ordinary maintainer review, CI, and merge handling.

Security
Cleared: The diff changes in-memory runner metadata, Gateway response serialization, tests, and changelog text only; it does not touch dependencies, workflows, secrets, install scripts, artifacts, or publishing metadata.

Review details

Best possible solution:

Land this PR after normal maintainer and CI gating so the shipped fix preserves every client tool call in source order and closes the linked bug with regression coverage.

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

Yes. Current main has a source-level reproduction through the overwritten runner slot and pendingToolCalls[0] response emitters; the PR adds JSON, SSE, runner, and out-of-order hook coverage for the corrected path.

Is this the best way to solve the issue?

Yes. The patch is the narrow maintainable fix: carry an ordered array through the runner metadata, reserve slots before async hook latency can reorder callbacks, and emit every pending call without changing the public schema.

What I checked:

Likely related people:

  • steipete: Authored the latest PR head commit that fixes source-order preservation and has recent main history in adjacent Gateway/OpenResponses and embedded-runner paths. (role: recent maintainer and PR follow-up owner; confidence: high; commits: 58d3c3502cba, 4407c317f38e, afca9540bf82; files: src/agents/pi-embedded-runner/run/attempt.ts, src/gateway/openresponses-http.ts, src/agents/pi-tool-definition-adapter.ts)
  • frankekn: The merged fix: pass clientTools to runEmbeddedAttempt in /v1/responses agent path #52171 commit series enabled and shaped /v1/responses hosted-tool loops, session reuse, and changelog placement for this same client-tool surface. (role: introduced related hosted-tool behavior; confidence: medium; commits: e3db494c11f0, 027757448d9c, efbed816f35e; files: src/gateway/openresponses-http.ts, src/agents/pi-embedded-runner/run/attempt.ts)
  • openperf: Recent main history includes client-tool argument coercion work in pi-tool-definition-adapter, which is directly touched by the PR’s recorder API change. (role: adjacent client-tool adapter maintainer; confidence: medium; commits: c6ded0fa54f2; files: src/agents/pi-tool-definition-adapter.ts)
  • vincentkoc: Recent main history includes Gateway agent-first and performance/cycle refactors around the OpenResponses HTTP surface, and the local shallow blame boundary attributes the current checked-out relevant lines to a recent maintenance commit. (role: adjacent Gateway/agent maintainer; confidence: medium; commits: d10669629d73, 59b5db5cbf7d, 74e7b8d47b18; files: src/gateway/openresponses-http.ts)

Codex review notes: model gpt-5.5, reasoning high; reviewed against f7549079ceb3.

@mrinalgaur2005
mrinalgaur2005 force-pushed the fix-multi-client-tool-calls-52288 branch from 9c1a454 to 8a986e9 Compare May 1, 2026 10:56
@mrinalgaur2005

Copy link
Copy Markdown
Contributor Author

Thanks for the review. Two things addressed in the latest push:

Changelog entry added — single-line ### Fixes entry under the Gateway/responses topic, crediting @CharZhou (original report + first fix attempt in #52287) and @bonelli (still-broken signal on the issue thread). pnpm exec oxfmt --check --threads=1 CHANGELOG.md passes.

CI failures — both pre-existing on my old base (48b39bffbe), not caused by this patch:

  • checks-node-core-runtime-infra failed two snapshot tests:
    • src/config/schema.base.generated.test.ts — diff shows new gitCommit/gitRef/gitUrl fields and a git discriminator literal landing on main without baseline regen. Already fixed on main by fe022e409d test(infra): refresh generated config baselines.
    • src/infra/tsdown-config.test.ts — same shape, build-graph snapshot drift from intervening refactor: trim … commits on main.
  • I rebased onto 8d288e2dfd so both fixes come along for the ride. Force-pushed. Targeted suites still green locally:
    • pnpm test src/gateway/openresponses-http.test.ts — 17/17
    • pnpm test src/agents/pi-embedded-runner/sessions-yield.orchestration.test.ts src/agents/pi-embedded-runner/run.incomplete-turn.test.ts — 87/87
    • pnpm exec oxlint + pnpm exec oxfmt --check on touched files — clean

Branch now has two commits: the original fix + a single-line docs(changelog): commit. Happy to squash on request, or leave it for merge-time squash. Re-run welcome.

@mrinalgaur2005

Copy link
Copy Markdown
Contributor Author

Update on the latest CI run after the rebase: my original two failures (schema.base.generated.test.ts and tsdown-config.test.ts) are gone, as expected. But seven new failures showed up that all trace to a different main-side breakage:

checks-fast-contracts-plugins-c -> extension-runtime-dependencies.contract.test.ts (1/357 failed)
check-dependencies               -> Unused dependencies (1) extensions/whatsapp/package.json: qrcode
build-artifacts                  -> installed package root mirror 'qrcode' missing from
                                    package.json openclaw.bundle.mirroredRootRuntimeDependencies
build-smoke / check / check-additional / checks-node-core -> cascade from build-artifacts

Root: 2c488daaf4 fix(whatsapp): stage qrcode runtime dependency (Peter Steinberger, 2026-05-01) added qrcode to extensions/whatsapp/package.json and pnpm-lock.yaml, but did not:

  1. add it to root package.json under openclaw.bundle.mirroredRootRuntimeDependencies (build-artifacts smoke fails),
  2. add a corresponding import "qrcode" (or re-exported usage) anywhere knip can see (deadcode:dependencies fails),
  3. update the plugin contract test that enumerates allowed direct runtime deps per extension (357th test in the contract shard fails).

git show 2c488daaf4 --stat confirms — it only touched CHANGELOG.md, extensions/whatsapp/package.json, pnpm-lock.yaml, and bundled-runtime-deps-drift.test.ts. No follow-up commit on main fixes it (git log origin/main -- extensions/whatsapp shows 2c488daaf4 as the latest).

Other recently-opened PRs aren't tripping on this because they touch only path-filtered subsets (e.g. iMessage-only, plugin-sdk-only) that don't run check-dependencies / build-artifacts. My diff touches src/gateway/ and src/agents/, which fans out to the full battery and surfaces the breakage.

I'm intentionally not adding the WhatsApp mirror/import fix to this PR — it's an unrelated change and would muddy the multi-tool-call repair. Happy to either:

  • wait for a separate maintainer fix on main and rebase, or
  • open a small follow-up PR specifically for the qrcode mirror+import wiring if that's preferred.

@steipete — flagging since you authored 2c488daaf4. Targeted suites for this PR (openresponses-http.test.ts, sessions-yield.orchestration.test.ts, run.incomplete-turn.test.ts) are 17/17 + 87/87 green locally, and the lint/format gates are clean.

@steipete
steipete force-pushed the fix-multi-client-tool-calls-52288 branch from 8a986e9 to 4af9cca Compare May 2, 2026 23:42
Mrinal Gaur and others added 3 commits May 3, 2026 00:42
When an agent invoked multiple client tools in a single turn, only
the last call survived. The detection slot in the embedded runner was
a single nullable variable that each ``onClientToolCall`` callback
overwrote, and both the non-streaming and streaming OpenResponses
handlers downstream read only ``pendingToolCalls[0]``. Multi-tool
plans, graph orchestration calls, and similar batched flows quietly
lost every call but the trailing one.

Switch the detection variable to an ordered array, rename the runner
result field from ``clientToolCall`` to ``clientToolCalls`` (still
``undefined`` when no calls happened so the existing truthiness
predicates stay byte-identical), build ``pendingToolCalls`` by
mapping over that array, and emit one ``function_call`` output item
per pending call from both response modes. The streaming branch now
walks an ``output_index`` counter forward instead of hard-coding
``output_index: 1`` so multiple ``output_item.added``/``done`` pairs
share a single monotonic stream.

Tests: add a runner orchestration test that pushes three tools through
the embedded runner result and asserts ordered ``pendingToolCalls``,
plus two gateway regression tests (JSON and SSE) covering the exact
multi-tool repro from the issue.

Closes openclaw#52288

Made-with: Cursor
@steipete
steipete force-pushed the fix-multi-client-tool-calls-52288 branch from 4af9cca to 58d3c35 Compare May 2, 2026 23:43
@steipete
steipete merged commit 2584d0d into openclaw:main May 2, 2026
101 checks passed
@steipete

steipete commented May 2, 2026

Copy link
Copy Markdown
Contributor

Landed as 2584d0d.

Fixup added before landing: reserved client-tool-call slots before the async before-tool-call hook runs, so parallel tool execution cannot reorder the /v1/responses client_tool_call output items.

Verified:

  • focused agent/gateway test set passed locally
  • pnpm exec tsgo -p tsconfig.core.json --pretty false passed
  • Testbox OPENCLAW_TESTBOX=1 pnpm check:changed passed on tbx_01kqngzhsteb0xzzfv2v75q7te
  • exact-head GitHub checks passed for 58d3c3502cba9e7267d798828be48da7ecad1a90

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

Labels

agents Agent runtime and tooling gateway Gateway runtime size: L

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: only last client tool call returned when agent calls multiple tools per turn

2 participants