Skip to content

fix(btw): strip empty tools array for strict OpenAI-compatible endpoints - #59669

Closed
GitZhangChi wants to merge 1 commit into
openclaw:mainfrom
GitZhangChi:fix/btw-empty-tools
Closed

GitZhangChi wants to merge 1 commit into
openclaw:mainfrom
GitZhangChi:fix/btw-empty-tools

Conversation

@GitZhangChi

@GitZhangChi GitZhangChi commented Apr 2, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Problem: The /btw command fails with 400 [] is too short - 'tools' error when using Qwen, GLM, Kimi and some strict OpenAI-compatible endpoints.
  • Why it matters: Users cannot use the side-question feature (/btw) with these models if the active session has prior tool call history.
  • What changed: Added an onPayload hook in src/agents/btw.ts to intercept the provider request and safely strip the tools property if it is an empty array.
  • What did NOT change: Core agent tool calling logic, upstream @mariozechner/pi-ai behavior, and main session tool calls remain untouched.

Change Type

  • Bug fix

Scope

  • Skills / tool execution

Linked Issue/PR

Root Cause / Regression History

  • Root cause: Upstream @mariozechner/pi-ai injects tools: [] when hasToolHistory(context.messages) is true (to satisfy certain Anthropic proxy requirements). However, the /btw side-channel deliberately omits tools. When tools: [] is sent to Kimi/GLM APIs, they strictly reject it with a 400 error.
  • Missing detection / guardrail: Provider compatibility testing for empty tool arrays in tool-disabled execution paths.

Regression Test Plan

  • Coverage level that should have caught this:
    • Seam / integration test
  • Target test or file: src/agents/btw.test.ts
  • Scenario the test should lock in: /btw command execution with a session history containing tool calls, asserting that the outgoing payload does not contain an empty tools array.

User-visible / Behavior Changes

Users of Kimi, Qwen, GLM, and strict OpenAI-compatible endpoints will now be able to use /btw successfully without receiving a 400 Bad Request error.

Security Impact

  • New permissions/capabilities? No
  • Secrets/tokens handling changed? No
  • New/changed network calls? No
  • Command/tool execution surface changed? No
  • Data access scope changed? No

Repro + Verification

Environment

  • OS: macOS Tahoe 26.4
  • Runtime/container: nodejs v25.8.1
  • Model/provider: qwen3.5-plus GLM-5 MiniMax-M2.5 kimi-k2.5
  • Integration/channel: Telegram

Steps

  1. Start a session using an qwen3.5-plus model.
  2. Trigger a normal tool call (e.g., "Search the web").
  3. Once the tool call finishes, send a BTW command: /btw what did we just do?

Expected

  • The BTW command returns a successful context-aware response.

Actual (before fix)

  • The BTW command fails with 400 [] is too short - 'tools'.

Evidence

  • Trace/log snippets
  • Manual testing with Qwen model

Human Verification

  • Verified scenarios: Local testing with qwen3.5-plus model enforcing non-empty tools array.
  • Edge cases checked: Ensured normal tool calls in the main session are not affected since the hook is only injected in runBtwSideQuestion.

Review Conversations

  • I replied to or resolved every bot review conversation I addressed in this PR.

Compatibility / Migration

  • Backward compatible? Yes
  • Config/env changes? No
  • Migration needed? No

Risks and Mitigations

  • Risk: Certain Anthropic proxies explicitly required tools: [] when tool history is present.
  • Mitigation: If an upstream proxy explicitly requires this for /btw, it might fail. However, standardizing on omitting the empty array is the safer universal default, as it conforms strictly to the OpenAI API specification.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: XS labels Apr 2, 2026
@greptile-apps

greptile-apps Bot commented Apr 2, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes a 400 [] is too short - 'tools' error that occurs when /btw is used with Aliyun (Qwen), GLM, and other strict OpenAI-compatible endpoints that reject an empty tools array. The root cause is that @mariozechner/pi-ai injects tools: [] when the session has tool call history, but /btw is a lightweight side-question path that intentionally omits tools. The fix adds an onPayload hook to runBtwSideQuestion that strips the tools property when it is an empty array before the request is sent.

  • The core logic is correct: the in-place delete p.tools mutation is safe and will cause tools: [] to be omitted from the outgoing payload for all affected providers.
  • The onPayload hook returns payload rather than undefined, which diverges from the established pattern in the rest of the codebase (where the convention is to mutate in-place and return undefined or chain to originalOnPayload?.(payload, model)). This is a style inconsistency but is functionally equivalent due to the nextPayload ?? payload fallback used by all callers.
  • The PR description's own regression test plan calls for a test in src/agents/btw.test.ts asserting that the outgoing payload does not contain an empty tools array, but no such test was added. Given that similar mutations in the codebase all have dedicated test assertions, this omission leaves the fix unguarded against future regressions.

Confidence Score: 4/5

  • Safe to merge — the fix is narrowly scoped, correctly targets the reported failure mode, and does not affect main-session tool calls.
  • The logic is sound and well-isolated (only applies inside runBtwSideQuestion). The primary gap is missing test coverage that the PR's own regression plan promised; without it the fix is unguarded against future regressions. The return-value style inconsistency is cosmetic but worth aligning. No security, data, or behavioral regressions are introduced.
  • src/agents/btw.ts — the new onPayload hook lacks a corresponding test in src/agents/btw.test.ts.
Prompt To Fix All With AI
This is a comment left during a code review.
Path: src/agents/btw.ts
Line: 310-318

Comment:
**No test coverage for the new `onPayload` logic**

The PR description explicitly outlines a regression test that should lock in this fix (`src/agents/btw.test.ts` — "BTW command execution with a session history containing tool calls, asserting that the outgoing payload does not contain an empty `tools` array"), but no test was added.

Every other `onPayload` mutation in the codebase (e.g. `openai-stream-wrappers.ts`, `anthropic-family-tool-payload-compat.ts`) has corresponding test assertions that the payload sent downstream matches expectations. Without a test here, the next refactor of `streamSimple`'s options handling could silently re-introduce the bug.

A minimal test in `btw.test.ts` would look like:

```ts
it("strips empty tools array from onPayload to fix Aliyun/GLM compat", async () => {
  mockDoneAnswer("Some answer.");

  await runSideQuestion();

  const [, , options] = streamSimpleMock.mock.calls[0] ?? [];
  // Simulate the upstream injection of tools: []
  const payloadWithEmptyTools = { messages: [], tools: [] };
  const result = options?.onPayload?.(payloadWithEmptyTools);
  expect(payloadWithEmptyTools).not.toHaveProperty("tools");
  // Return value should still be the (mutated) payload or truthy
  expect(result ?? payloadWithEmptyTools).not.toHaveProperty("tools");
});
```

How can I resolve this? If you propose a fix, please make it concise.

---

This is a comment left during a code review.
Path: src/agents/btw.ts
Line: 310-318

Comment:
**`onPayload` return value diverges from established codebase pattern**

Every other `onPayload` hook in this codebase (see `openai-stream-wrappers.ts` lines 325, 366, 408; `stream-payload-utils.ts` line 17; `anthropic-family-tool-payload-compat.ts` line 179) follows this pattern:

```ts
const originalOnPayload = options?.onPayload;
onPayload: (payload) => {
  // mutate payload...
  return originalOnPayload?.(payload, model);  // returns undefined when no prior handler
}
```

The callers that consume the return value (e.g. `openai-ws-stream.ts` line 511) all use `nextPayload ?? payload`, so returning `undefined` is the signal "use the mutated original", while returning a new object replaces the payload entirely.

The new code returns `payload` (the mutated original). While this is functionally equivalent today — because `nextPayload ?? payload` collapses to `payload` either way — it breaks the semantic contract: returning the payload object itself is typically reserved for callers that want to *replace* it. Returning `undefined` (by not returning, or via a chain) communicates "I mutated in place; use the original."

Consider aligning with the established pattern:

```suggestion
      onPayload: (payload) => {
        if (payload && typeof payload === "object" && "tools" in payload) {
          const p = payload as { tools?: unknown[] };
          if (Array.isArray(p.tools) && p.tools.length === 0) {
            delete p.tools;
          }
        }
      },
```

How can I resolve this? If you propose a fix, please make it concise.

Reviews (1): Last reviewed commit: "fix(btw): strip empty tools array to fix..." | Re-trigger Greptile

Comment thread src/agents/btw.ts Resolved
Comment thread src/agents/btw.ts Resolved
Fixes #53472

The /btw command was failing with `400 [] is too short - 'tools'` when using
Aliyun (Qwen), GLM, and other strict OpenAI-compatible endpoints.

Root cause: upstream `@mariozechner/pi-ai` injects `tools: []` when the session
has tool history, but these providers reject empty tools arrays.

Solution: add an `onPayload` hook in `runBtwSideQuestion` to strip the empty
`tools` array before sending it to the provider. This is a general, localized
fix that handles any provider rejecting empty tools arrays without affecting
normal tool calls in the main session.

Verified locally with qwen3.5-plus-ali.
@GitZhangChi GitZhangChi changed the title fix(btw): strip empty tools array to fix compatibility with Aliyun/GLM models fix(btw): strip empty tools array for strict OpenAI-compatible endpoints Apr 3, 2026
@GitZhangChi

Copy link
Copy Markdown
Contributor Author

Closing — the root cause was already fixed upstream in @mariozechner/pi-ai 0.64.0: the tools: [] injection in openai-completions.js is now commented out with an explicit note about Bailian/Aliyun API compatibility. Users on 0.64.0 no longer hit the 400 error. The onPayload hook in this PR is therefore no longer needed.

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

Labels

agents Agent runtime and tooling size: XS

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant