Skip to content

refactor(ai): share Chat Completions request assembly - #140604

Merged
steipete merged 2 commits into
mainfrom
steipete/dedup-ai-openai-runners-0906
Sep 7, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/dedup-ai-openai-runners-0906

Conversation

@steipete

@steipete steipete commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Chat Completions request assembly had two implementations, so fixes to shared message, response-format, tool and generation fields could drift between direct provider calls and managed transports. This is a maintainer-requested consolidation from the provider/runner de-duplication campaign.

Why This Change Was Made

Both entrypoints now use one request builder in packages/ai/src/transports/openai-completions-params.ts, with explicit direct and managed policies. Direct reasoning/routing remains a policy helper; managed replay, strict tool shaping, proxy tool omission and context-aware output budgeting retain their existing rules. Client creation, payload hooks and stream terminal handling remain with their lifecycle owners.

This incorporates the shared cache-marker owner from #140781 and the native prompt-cache capability/lifetime policy from #140853. Cache opt-outs, stable-prefix and history anchors, Model Studio tool-marker omission, string-only endpoints, and payload identity remain intact. All existing exported signatures remain available. The nearby #138329 was inspected and does not overlap this package-level change.

User Impact

No intended behavior change. Direct and managed requests retain their reasoning defaults, cache policy, tool behavior and output caps. Production code decreases by 108 lines; no tests are removed. Maintainer-approved assertion baseline maintenance only shrinks the provider count from 9 to 6 (main had already reduced 10 to 9) and params from 9 to 7.

Evidence

  • Refreshed focused provider, transport, cache and wrapper tests: 30 files, 575 tests passed. Command: node scripts/run-vitest.mjs packages/ai/src/providers/openai-completions{.,-}*.test.ts packages/ai/src/transports/openai-completions-*.test.ts src/llm/providers/stream-wrappers/proxy.test.ts extensions/deepinfra/cache-wrapper.test.ts src/agents/embedded-agent-runner/extra-params.openrouter-cache-control.test.ts.
  • Core typecheck passed after correcting the shared request type to retain required request fields and derive tools from the actual schema projection. No suppression or double assertion was added.
  • Final independent Codex autoreview: scoped-clean, zero actionable P0–P2 findings. The final syntax-only lint correction passed all 9 focused compat/tool-choice tests.
  • Full pnpm build passed on Blacksmith Testbox in 3m24.2s. The earlier local full build also passed.
  • Credentialed live proof: Blacksmith Testbox tbx_01m1x95npamnzvcdhaew94ahra, Actions run, wrapper exit 0. Both OpenAI suites made real provider round-trips: direct completion with nonempty output/positive usage (571ms), plus the profile suite's prompt, file-read and image probes for openai/gpt-5.6-luna (5.564s). Two files, 38 tests passed; two unrelated OpenRouter/Z.AI tests were deliberately excluded. No OpenAI test skipped or passed vacuously. The lease stopped successfully. A subsequent runner-portal sync warning did not affect command success.
  • Full build/live proof used commit 4e351e779a43e183cd037c90b5ea153b6d30137d; the only subsequent source change flattens an equivalent nested else/if to satisfy lint. The initial CI lint stripe reported that one error and zero warnings; exact-head CI passed after its correction: run 34092022603, head b2d28d06ffa4a39c41efc05a5ebc153fea697755.
  • node scripts/check-changed.mjs passed completely after the lint correction, including core/core-test typechecks, all three dead-export scans, core/script lint and every remaining guard. A direct lint-wrapper attempt hit the documented nested-worktree Declaration input escapes checkout boundary. No boundary or ancestor installation was modified.

The profile allowlist alone defaults to Responses, so the command uses a temporary secret-free config selecting Chat Completions at both provider and model levels. Credentials come only from the remote hydration helper. The command below is the argument to node scripts/crabbox-wrapper.mjs run --timing-json -- bash -lc (quoted to expand $HOME remotely):

set -euo pipefail
pnpm build
L03_LIVE_DIR=$(mktemp -d /tmp/openclaw-L03-live.XXXXXX)
trap 'rm -rf "$L03_LIVE_DIR"' EXIT
cat > "$L03_LIVE_DIR/openclaw.json" <<'JSON'
{"models":{"mode":"merge","providers":{"openai":{"baseUrl":"https://api.openai.com/v1","auth":"api-key","api":"openai-completions","models":[{"id":"gpt-5.6-luna","name":"GPT-5.6 Luna","api":"openai-completions"}]}}}}
JSON
"$HOME/.local/bin/openclaw-testbox-env" env -u OPENROUTER_API_KEY -u ZAI_API_KEY OPENCLAW_CONFIG_PATH="$L03_LIVE_DIR/openclaw.json" OPENCLAW_STATE_DIR="$L03_LIVE_DIR/state" OPENCLAW_LIVE_TEST=1 OPENCLAW_LIVE_MODELS="openai/gpt-5.6-luna" OPENCLAW_LIVE_PROVIDERS=openai node --import ./scripts/tsx.mjs scripts/test-live.mts --no-quiet -- packages/ai/src/providers/openai-completions.live.test.ts src/agents/models.profiles.live.test.ts

@clawsweeper

clawsweeper Bot commented Sep 7, 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.

@openclaw-barnacle openclaw-barnacle Bot added size: L maintainer Maintainer-authored PR labels Sep 7, 2026
@clawsweeper clawsweeper Bot added P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. 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 Sep 7, 2026
@clawsweeper

clawsweeper Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 7, 2026, 2:49 AM ET / 06:49 UTC.

ClawSweeper review

What this changes

Shares Chat Completions request assembly between direct provider calls and managed transports while preserving their existing request policies.

Merge readiness

✅ Ready for maintainer review

This remains a useful maintainer-requested consolidation: current main still has separate request builders, and the reviewed patch preserves their distinct policies. No actionable correctness or security defect was found.

Priority: P3
Reviewed head: b2d28d06ffa4a39c41efc05a5ebc153fea697755

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused consolidation with preserved policy distinctions, meaningful supplied live results, and no actionable findings.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The captured Testbox observations exercise direct request assembly and configured Chat Completions profile probes, reporting successful output, usage, file-read, and image results at the parent revision. The supplied follow-up is syntax-only; linked logs and the prior blob could not be independently retrieved.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The captured Testbox observations exercise direct request assembly and configured Chat Completions profile probes, reporting successful output, usage, file-read, and image results at the parent revision. The supplied follow-up is syntax-only; linked logs and the prior blob could not be independently retrieved.
Evidence reviewed 10 items Repository policy and review scope: Read the full root AGENTS.md, contribution guidance, PR template, and CODEOWNERS. No ancestor-scoped AGENTS.md exists for the changed paths, and .agents/maintainer-notes is absent. The checkout was clean before and after inspection.
Introduced request-builder changes: Inspected the complete merge-base-to-head builder diff. Managed replay, string shaping, strict tool normalization, proxy omission, and context budgeting remain conditional on managed policy; direct reasoning and routing return through the extracted policy helper.
Current-main necessity: Fetched main still calls its private buildParams implementation in the direct provider. The related merged cache fixes do not perform this request-assembly consolidation. The new direct-policy file is absent from both fetched main and the supplied latest release tag.
Findings None None.
Security None None.

How this fits together

OpenClaw’s AI package converts conversation history, tools, model capabilities, and generation options into provider requests. Direct provider calls and managed transports send those requests through their existing clients and return streamed assistant output.

flowchart TD
  A[Conversation and tools] --> D[Shared request assembly]
  B[Model and generation options] --> D
  C[Direct or managed policy] --> D
  D --> E[Existing provider client]
  E --> F[Chat Completions endpoint]
  F --> G[Streamed assistant output]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source -108, Other 0. Total -108 across 4 files.

View PR surface stats
Area Files Added Removed Net
Source 3 237 345 -108
Tests 0 0 0 0
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 2 2 0
Total 4 239 347 -108

Review metrics

None.

Technical review

Best possible solution:

Keep one request-assembly owner with explicit direct and managed policies, preserving payload hooks and client lifecycle boundaries.

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

Not applicable: this PR consolidates existing code rather than reporting a failing behavior; current-main source confirms the duplicated assembly.

Is this the best way to solve the issue?

Yes: sharing assembly while retaining explicit policy differences removes duplication without imposing managed defaults on direct calls.

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P3: This is a behavior-preserving consolidation without an identified urgent user-facing defect.
  • 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 Testbox observations exercise direct request assembly and configured Chat Completions profile probes, reporting successful output, usage, file-read, and image results at the parent revision. The supplied follow-up is syntax-only; linked logs and the prior blob could not be independently retrieved.
  • proof: sufficient: Contributor real behavior proof is sufficient. The captured Testbox observations exercise direct request assembly and configured Chat Completions profile probes, reporting successful output, usage, file-read, and image results at the parent revision. The supplied follow-up is syntax-only; linked logs and the prior blob could not be independently retrieved.

Evidence

What I checked:

  • Repository policy and review scope: Read the full root AGENTS.md, contribution guidance, PR template, and CODEOWNERS. No ancestor-scoped AGENTS.md exists for the changed paths, and .agents/maintainer-notes is absent. The checkout was clean before and after inspection. (AGENTS.md:1, b2d28d06ffa4)
  • Introduced request-builder changes: Inspected the complete merge-base-to-head builder diff. Managed replay, string shaping, strict tool normalization, proxy omission, and context budgeting remain conditional on managed policy; direct reasoning and routing return through the extracted policy helper. (packages/ai/src/transports/openai-completions-params.ts:325, b2d28d06ffa4)
  • Current-main necessity: Fetched main still calls its private buildParams implementation in the direct provider. The related merged cache fixes do not perform this request-assembly consolidation. The new direct-policy file is absent from both fetched main and the supplied latest release tag. (packages/ai/src/providers/openai-completions.ts:301, 72913f02470d)
  • Equivalent shared helpers: The managed tool sorter is an alias of the original direct sorter. resolvePromptCacheKey uses the same retention opt-out, explicit-key/session fallback, and code-point clamp as the removed direct implementation. (packages/ai/src/transports/openai-transport-shared.ts:316, b2d28d06ffa4)
  • Preserved cache contract: The documented shared marker layout, retention opt-out, string-only managed requests, and custom-endpoint lifetime capability remain represented in the builder and unchanged cache-policy owner. Public docs: docs/reference/prompt-caching.md. (docs/reference/prompt-caching.md:188, b2d28d06ffa4)
  • Implementation boundary: The changed code belongs to OpenClaw’s reusable AI package and constructs requests for the OpenAI SDK. The package README assigns credentials and host policy to the application; neither the introduced diff nor its proof depends on a Codex harness contract. (packages/ai/README.md:20, b2d28d06ffa4)

Likely related people:

  • steipete: 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 (3 earlier review cycles)
  • reviewed 2026-09-07T02:01:21.922Z sha f8e6795 :: blocked before merge. :: none
  • reviewed 2026-09-07T06:24:58.972Z sha 760b7f0b81de2675c313414fdf4829d9eee31bc5 :: blocked before merge. :: none
  • reviewed 2026-09-07T06:38:28.197Z sha 4e351e7 :: needs maintainer review before merge. :: none

@steipete
steipete force-pushed the steipete/dedup-ai-openai-runners-0906 branch from f8e6795 to 760b7f0 Compare September 7, 2026 06:19
Preserve direct reasoning and managed replay, strict tools, proxy omission,
and output budgeting. Integrate shared cache policies from #140781 and #140853.

Apply maintainer-approved shrink-only assertion baseline maintenance:
provider 9 to 6 (main already reduced 10 to 9), params 9 to 7.

Proof: focused provider, transport, cache and wrapper suites pass
(30 files, 575 tests), and core typecheck passes;
Codex autoreview found no actionable P0-P2 issues.
@steipete
steipete force-pushed the steipete/dedup-ai-openai-runners-0906 branch from 760b7f0 to 4e351e7 Compare September 7, 2026 06:32
@steipete
steipete marked this pull request as ready for review September 7, 2026 06:32
Preserve the same empty-tool history fallback while satisfying no-lonely-if. The focused compat/tool-choice suite passes all 9 tests; Codex autoreview reports no actionable P0-P2 findings.
@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Sep 7, 2026
@steipete
steipete merged commit a9676bd into main Sep 7, 2026
145 of 146 checks passed
@steipete
steipete deleted the steipete/dedup-ai-openai-runners-0906 branch September 7, 2026 06:54
@steipete

steipete commented Sep 7, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 8, 2026
* refactor(ai): share Chat Completions request assembly

Preserve direct reasoning and managed replay, strict tools, proxy omission,
and output budgeting. Integrate shared cache policies from openclaw#140781 and openclaw#140853.

Apply maintainer-approved shrink-only assertion baseline maintenance:
provider 9 to 6 (main already reduced 10 to 9), params 9 to 7.

Proof: focused provider, transport, cache and wrapper suites pass
(30 files, 575 tests), and core typecheck passes;
Codex autoreview found no actionable P0-P2 issues.

* style(ai): flatten completions tool-history condition

Preserve the same empty-tool history fallback while satisfying no-lonely-if. The focused compat/tool-choice suite passes all 9 tests; Codex autoreview reports no actionable P0-P2 findings.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

maintainer Maintainer-authored PR P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. 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.

1 participant