Skip to content

fix: turns fail after runtime notices on strict chat templates - #167309

Merged
steipete merged 3 commits into
openclaw:mainfrom
jlapenna:fix/167305-runtime-roles-20261008-1551
Oct 8, 2026
Merged

steipete merged 3 commits into
openclaw:mainfrom
jlapenna:fix/167305-runtime-roles-20261008-1551

Conversation

@jlapenna

@jlapenna jlapenna commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #167305

What Problem This Solves

Fixes turns failing after runtime notices on strict Chat Completions templates that allow a system message only at the beginning, including local Qwen backends.

User Impact

Sessions can continue after event, heartbeat, and compaction notices without clearing history, switching models, or rewriting requests in a proxy. No configuration or migration is required.

Why This Change Was Made

The shared Chat Completions converter selects developer for runtime notices when the resolved route supports that role, or labeled user content otherwise. It retains notice positions, text, transcript bytes, and cache exclusions. The leading prompt is unchanged. This is provider-neutral: reasoning capability does not imply that a template accepts later system messages.

ClawSweeper's role-contract question is addressed by the existing runtime-context contract: trusted context is projected at the strongest valid provider authority. Developer support supplies that authority; unsupported routes require the labeled-user representation. The change belongs at that projection owner and introduces no config, protocol, SDK, or storage contract. The earlier managed OpenRouter composition finding is fixed, with its cache assertions retained. No human review findings were present.

Original fix by @jlapenna; maintainer cleanup consolidates the role matrix into the existing prompt-prefix/tool-result regression, preserves legacy-carrier and mixed-media coverage, removes redundant commentary, and documents the notice behavior.

Evidence

Current-main verification: c786f4d4c4ea27630466a529630e56071845a682 still projects notices to system unless both reasoning and developer support are enabled. The production-only negative control uses its exact converter blob 712cd1c53011cb7990cfba5d621b876804a1359b, while retaining final-head tests.

Final head: 132394fc3bb66fea8e0132d820c06c7da430d4d0. Formatting, targeted type-aware lint, and git diff --check passed. Fresh independent Codex autoreview: scoped-clean through P2, with no accepted/actionable findings.

All product execution ran on fresh secretless AWS lease cbx_96f8caf09391 (m7i.2xlarge, approximately 30 GiB RAM), bound to this head. The clean-main trusted bootstrap verified the head, IAM no-role boundary, isolated HOME, and pinned toolchain. No hydration or contributor execution on the maintainer host.

Final-head check Result Wall time
pnpm test packages/ai/src/openai-completions-messages.test.ts --maxWorkers=1 39 passed 5.78s (Vitest 3.80s)
pnpm test src/llm/providers/stream-wrappers/proxy.test.ts --maxWorkers=1 18 passed 11.26s (Vitest 9.38s)
Related Completions params, cache-marker, replay, transport-request, and compatibility suites 88 passed across 5 files 5.41s
pnpm tsgo:core passed 66.59s
pnpm tsgo:core:test --ci-graphs-json '["core-test-packages","core-test-other"]' both passed 109.53s (50.3s + 58.8s per graph)

The regression adds no process boots, timers, sleeps, or production seams. The existing proxy suite's first case pays its shared runtime import/setup cost; its 18 cases are unchanged apart from the corrected notice-role expectation.

Fresh real Gateway proof with a local strict Chat Completions provider passed (103.60s, including cold startup and CLI clients). A separate Gateway process used isolated OPENCLAW_STATE_DIR, a synthetic workspace, and ephemeral ports. Through the public API, two system-event → chat.send → agent.wait → chat.history turns returned TURN_1_OK and TURN_2_OK. Captured request roles were system,user,user and system,user,assistant,user,user; notices reached the provider as labeled user content. The leading system message stayed byte-identical (SHA-256 e8d6b5829f7cd57a7babb286733bd1e645d3f7e5993bde928276523e2c760c32). This is a real Gateway with a synthetic provider, not a new real-Qwen run.

Production-only negative control: replacing only the converter with the exact recorded-main blob made three role-matrix cases fail (system received instead of user/developer), with the supported reasoning/developer control passing. Test command: pnpm test packages/ai/src/openai-completions-messages.test.ts --maxWorkers=1 -t 'preserves prior prompt bytes when runtime notices follow tool results' (5.59s wall).

The identical real-Gateway negative control also failed (92.18s): captured roles system,user,system; Gateway outcome status: "error", LLM request rejected: System role only accepted at index zero. The mock returned HTTP 400. Final production bytes were restored and git diff --exit-code passed. The lease was stopped after proof.

Final-head CI run passed with no failed jobs. Its 23 successful Node test jobs total 3215 job-wall seconds, including setup and all selected coverage; this is not the incremental cost of the regression. No CI reruns were requested. The full repository test suite was not run separately.

Nonfatal Crabbox telemetry-upload timeouts occurred; command output was captured locally, both remote runs exited 0, and all proof above was inspected.

Remote execution and live commands

Launched from a clean trusted origin/main worktree; both runs supplied the full head and the trusted bootstrap:

CRABBOX_ENV_ALLOW=CI crabbox run --provider aws --id cbx_96f8caf09391 \
  --fresh-pr openclaw/openclaw#167309 --no-hydrate --timing-json \
  --script scripts/crabbox-untrusted-bootstrap.sh -- \
  132394fc3bb66fea8e0132d820c06c7da430d4d0 bash -c '<serial proof commands>'

CRABBOX_AWS_INSTANCE_PROFILE was unset; public network and no Tailscale were verified. Unit/type run: run_a9c59936a2dcca5c8166dbb33b5422f6. Live/control run: run_e90594570c5a4a0d96ccc8790780f8bc.

The remote-only harness ran node "$proof_root/runtime-notice-gateway.mjs", spawning:

pnpm --silent openclaw gateway run --port "$gatewayPort" --bind loopback --allow-unconfigured
pnpm --silent openclaw gateway call system-event --port "$gatewayPort" --token "$syntheticToken" --timeout 120000 --params '{"sessionKey":"agent:main:runtime-notice-proof","text":"RUNTIME_NOTICE_1: synthetic maintenance completed","wake":false}' --json
pnpm --silent openclaw gateway call chat.send --port "$gatewayPort" --token "$syntheticToken" --timeout 120000 --params '{"sessionKey":"agent:main:runtime-notice-proof","message":"Reply exactly TURN_1_OK for TURN_1.","idempotencyKey":"<fresh UUID>"}' --json
pnpm --silent openclaw gateway call agent.wait --port "$gatewayPort" --token "$syntheticToken" --timeout 120000 --params '{"runId":"<returned run ID>","timeoutMs":90000}' --json
pnpm --silent openclaw gateway call chat.history --port "$gatewayPort" --token "$syntheticToken" --timeout 120000 --params '{"sessionKey":"agent:main:runtime-notice-proof","limit":20}' --json

The sequence repeated for turn 2. The local provider captured every request and returned HTTP 400 whenever messages.slice(1) contained role: "system"; otherwise it streamed the expected reply. The negative control ran the same harness and tests unchanged after replacing only production bytes.

Diff against the recorded main: production +1/-1 (net 0), tests +78/-50 (net +28; reduced from +58), docs +1/-0. No changelog, tooling, dependency, or CI configuration changes.

File Added Removed
packages/ai/src/openai-completions-messages.ts 1 1
packages/ai/src/openai-completions-messages.test.ts 77 49
src/llm/providers/stream-wrappers/proxy.test.ts 1 1
docs/concepts/model-providers/custom-providers.md 1 0

@clawsweeper

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

@jlapenna
jlapenna marked this pull request as ready for review October 8, 2026 15:49
@clawsweeper clawsweeper Bot added 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. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 8, 2026
@clawsweeper

clawsweeper Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed October 8, 2026, 3:04 PM ET / 19:04 UTC (Revision 6).

ClawSweeper review

What this changes

The shared Chat Completions converter projects runtime notices as developer messages when supported and labeled user messages otherwise, avoiding later system messages.

Example: Send a chat turn after a runtime notice on a strict Chat Completions route.

  • Before: The Gateway reports “LLM request rejected: System role only accepted at index zero”.
  • After: The Gateway completes two successive notice-following turns with TURN_1_OK and TURN_2_OK.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) A focused shared-owner repair with shipped-Gateway proof, a production-only negative control, useful regression coverage, and no open finding.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The complete PR body records exact-head real Gateway requests to a strict synthetic provider: two notice-following turns succeed, request roles exclude later system messages, and the leading prompt remains identical. The same Gateway scenario fails with only main's converter restored; contributor discussion also reports installed-route success. Stored formats and writers are unchanged, with legacy-carrier coverage and transcript immutability retained.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Ongoing sessions fail after runtime notices because strict model templates reject later system messages.
Reason: This restores working turns through a focused shared-owner repair. The final-head matrix and documentation record area-owner acceptance of the capability-based contract.

Merge readiness

✅ Ready for maintainer review

This PR remains necessary: current main retains the reported failure. The owner-authored final-head coverage resolves the earlier role-contract question, real Gateway proof is sufficient, and no blocking finding remains.

Priority: P1
Reviewed head: 132394fc3bb66fea8e0132d820c06c7da430d4d0

Before merge

None.

Findings

None.

Agent review details

How this fits together

OpenClaw combines conversation history and internal runtime notices before sending requests to model providers. The shared Chat Completions converter assigns provider-compatible message roles while preserving conversation order.

flowchart TD
 A[Conversation history] --> C[Chat Completions converter]
 B[Marked runtime notices] --> C
 C --> D{Developer role supported?}
 D -->|Yes| E[Developer notice]
 D -->|No| F[Labeled user notice]
 E --> G[Provider request]
 F --> G
Loading

Technical review

Best possible solution:

Keep the bounded repair at the shared provider-projection owner, retaining notice order, transcript bytes, and existing cache policy.

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

Yes: current-main source emits a later system message for marked notices on unsupported-developer routes, and the supplied real Gateway negative control records the resulting HTTP 400. This read-only review did not execute the reproduction.

Is this the best way to solve the issue?

Yes: using the existing resolved role capability repairs the shared request boundary without provider-specific rewrites, history deletion, or new configuration.

AGENTS.md: found and applied where relevant.

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

Provenance checked

Testing

Proof path: shipped entry point. Added test files: 2.

Security

None.

Evidence

What I checked:

  • Pinned production repair: The introduced delta changes only runtime-notice role selection in production; content conversion and cache exclusions remain intact. (packages/ai/src/openai-completions-messages.ts:121, 132394fc3bb6)
  • Current main still needs the repair: Fetched main retains reasoning-dependent developer/system notice projection. Comparing the four touched paths from the merge base to fetched main produced no changes, so no overlapping base hunks were identified; GitHub reports the PR cleanly mergeable. (packages/ai/src/openai-completions-messages.ts:121, dd0ecdd4bd35)
  • Original behavior and intent: The raw-parent patch adds the exact notice-role branch. The merged fix: prevent internal runtime context from appearing in replies #163471 describes provider-specific projection and labeled-user compatibility as part of the shared runtime-context contract. (packages/ai/src/openai-completions-messages.ts:119, cd9913f1b110)
  • Area-owner direction recorded: Peter Steinberger authored the final-head capability matrix and documentation of developer/user projection. Current-main shortlog records nine prior converter commits under that name, establishing area involvement beyond this branch and resolving the earlier request for owner direction. (packages/ai/src/openai-completions-messages.test.ts:758, 132394fc3bb6)
  • Meaningful regression coverage: The four-case matrix preserves prior prompt bytes and the 30,000-character tool result, verifies notice role and cache exclusions, and checks transcript immutability. Existing legacy and mixed-media cases remain; the earlier OpenRouter assertion is corrected without weakening cache assertions. (packages/ai/src/openai-completions-messages.test.ts:758, 132394fc3bb6)
  • Final-head real Gateway proof: The complete REST-read PR body, captured in context under sourceRevision f388e399af50ab8166641dfbc32874d4a4cf91491197f99aac76b57bd434eaf8, records isolated final-head Gateway execution through system-event, chat.send, agent.wait, and chat.history. Two turns returned TURN_1_OK and TURN_2_OK with request roles system,user,user and system,user,assistant,user,user and an identical leading prompt. Restoring only main's converter produced HTTP 400 and the index-zero system-role error. The provider was synthetic; separate contributor discussion reports installed-Gateway success on the existing route. No target code was executed during this review. (132394fc3bb6)

Likely related people:

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

PR surface

Source 0, Tests +28, Docs +1. Total +29 across 4 files.

View PR surface stats
Area Files Added Removed Net
Source 1 1 1 0
Tests 2 78 50 +28
Docs 1 1 0 +1
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 4 80 51 +29

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #167305
Summary: This PR is the candidate repair for the linked strict-template request-shape defect.

Members:

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

Labels

Label changes:

  • add rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • remove rating: 🐚 platinum hermit: Current PR rating is rating: 🦞 diamond lobster, so this older rating label is no longer current.

Label justifications:

  • P1: Runtime notices can stop ongoing agent turns on strict Chat Completions templates with HTTP 400.
  • merge-risk: 🚨 compatibility: Notice authority changes for existing routes; the area-owner-authored final-head matrix and documentation accept capability-based developer/user projection, with preserved transcript and cache contracts.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only; repair and merge need explicit maintainer commands such as @clawsweeper autofix or @clawsweeper automerge.

History

Review history (5 earlier review cycles)
  • reviewed 2026-10-08T15:55:09.626Z sha 190bda7 :: blocked before merge. :: none
  • reviewed 2026-10-08T16:02:40.740Z sha 190bda7 :: blocked before merge. :: [P2] Complete the managed OpenRouter role assertion cutover
  • reviewed 2026-10-08T16:11:23.774Z sha e48b4b4 :: blocked before merge. :: none
  • reviewed 2026-10-08T16:39:50.788Z sha e48b4b4 :: blocked before merge. :: none
  • reviewed 2026-10-08T18:50:31.396Z sha 132394f :: needs maintainer review before merge. :: none

@clawsweeper clawsweeper Bot added status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 8, 2026
@jlapenna

jlapenna commented Oct 8, 2026

Copy link
Copy Markdown
Contributor Author

Follow-up to the review and CI failure:

  • The failing proxy composition assertion expected a non-leading system notice. Updated that assertion to developer for its developer-capable route; the same wrapper test now passes all 18 cases (pnpm test src/llm/providers/stream-wrappers/proxy.test.ts --maxWorkers=1, 13.47 s wrapper / 11.80 s Vitest on the integration line). No cache assertions or production behavior were weakened. The original CI failure is attributed to this PR, not inherited main.
  • I recommend the capability-based contract in the review: developer when supported, labeled user otherwise, regardless of reasoning. The leading system prompt stays unchanged and later notices remain append-only. This preserves elevated authority where the declared route supports it without producing non-leading system messages on strict templates. Reasoning capability is not evidence that a backend accepts mid-transcript system messages.
  • The supported-route semantic change is intentional and covered by the four-case reasoning/developer-capability matrix. I am not claiming maintainer approval; the runtime-context owner should confirm that contract. I have not reverted to reasoning-dependent system projection or added a proxy rewrite.

The production repair and complete package have passed local build/import-closure checks and are being deployed. Installed Gateway/session verification is still pending; I will report that result separately.

@clawsweeper clawsweeper Bot added merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 8, 2026
@jlapenna

jlapenna commented Oct 8, 2026

Copy link
Copy Markdown
Contributor Author

Installed Gateway verification is complete. The existing main session now completes real turns on the unchanged normal homelab/default route after new runtime notices. A no-action control turn returned exactly RUNTIME_OK; the native transcript contains only that control user message and assistant reply, with zero tool calls.

PR CI is green on e48b4b4c3f82dbc8f61ddd02cdac8b03bc916ea2: https://github.com/openclaw/openclaw/actions/runs/37805851718 . The full integration package build/import-closure checks also passed; this is not a claim that the full local repository test suite ran.

The private integration line includes distinct compaction repairs, which are not part of this PR. No model switch or proxy rewrite was introduced by this change. The capability-based role-contract choice remains explicitly recorded for maintainer confirmation.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

Fold the role matrix into the existing prior-prefix and tool-result regression, retaining cache exclusions and transcript immutability. Document capability-based notice projection and remove redundant commentary. Fixes openclaw#167305. Original fix by @jlapenna.
@openclaw-barnacle openclaw-barnacle Bot added the docs Improvements or additions to documentation label Oct 8, 2026
@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Oct 8, 2026
@steipete steipete changed the title fix: local Qwen turns fail after runtime notices fix: turns fail after runtime notices on strict chat templates Oct 8, 2026
@clawsweeper clawsweeper Bot added rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. labels Oct 8, 2026
@steipete
steipete merged commit 2b51bb8 into openclaw:main Oct 8, 2026
145 checks passed
@steipete

steipete commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 9, 2026
…law#167309)

* fix(ai): keep runtime notices out of mid-transcript system messages

* test(ai): align proxy runtime notice role with transport contract

* test: tighten runtime notice prefix regressions

Fold the role matrix into the existing prior-prefix and tool-result regression, retaining cache exclusions and transcript immutability. Document capability-based notice projection and remove redundant commentary. Fixes openclaw#167305. Original fix by @jlapenna.

---------

Co-authored-by: Peter Steinberger <[email protected]>
RomneyDa pushed a commit that referenced this pull request Oct 11, 2026
* fix(ai): keep runtime notices out of mid-transcript system messages

* test(ai): align proxy runtime notice role with transport contract

* test: tighten runtime notice prefix regressions

Fold the role matrix into the existing prior-prefix and tool-result regression, retaining cache exclusions and transcript immutability. Document capability-based notice projection and remove redundant commentary. Fixes #167305. Original fix by @jlapenna.

---------

Co-authored-by: Peter Steinberger <[email protected]>
(cherry picked from commit 2b51bb8)
RomneyDa pushed a commit that referenced this pull request Oct 11, 2026
…backport)

Runtime notices now use developer or user messages according to provider
support. The memory fixtures still recognized only system messages, so
they selected the notice as the human prompt and returned the wrong reply.
Keep the whole-context marker and empty-after-stripping checks unchanged.

All four original failures reproduced on main. Actual HTTP captures showed
the user-role carrier; all four corrected cases and suppression checks pass,
with scoped types, typed lint and independent P2 review.

(cherry picked from commit e09e5dd)
@jlapenna
jlapenna deleted the fix/167305-runtime-roles-20261008-1551 branch October 12, 2026 00:03
amittell pushed a commit to amittell/openclaw that referenced this pull request Oct 12, 2026
…law#167309)

* fix(ai): keep runtime notices out of mid-transcript system messages

* test(ai): align proxy runtime notice role with transport contract

* test: tighten runtime notice prefix regressions

Fold the role matrix into the existing prior-prefix and tool-result regression, retaining cache exclusions and transcript immutability. Document capability-based notice projection and remove redundant commentary. Fixes openclaw#167305. Original fix by @jlapenna.

---------

Co-authored-by: Peter Steinberger <[email protected]>
(cherry picked from commit 2b51bb8)
amittell added a commit to amittell/openclaw that referenced this pull request Oct 12, 2026
The 9.9 -> 10.1 carry, its rulings, the fork tests adapted to 10.1, the
generated files, the guards, the openclaw#167309 fix and both bots' deploys.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. size: S 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]: Runtime-context notices become mid-transcript system messages and break Qwen Chat Completions

2 participants