Skip to content

fix(llm): preserve non-array tool result replay text - #98826

Closed
snowzlmbot wants to merge 4 commits into
openclaw:mainfrom
snowzlmbot:fix/tool-result-arbitrary-content-20260702
Closed

snowzlmbot wants to merge 4 commits into
openclaw:mainfrom
snowzlmbot:fix/tool-result-arbitrary-content-20260702

Conversation

@snowzlmbot

@snowzlmbot snowzlmbot commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Preserve useful provider replay text when tool-result content reaches the shared replay boundary as a plain string, primitive value, single structured object, or text-like object instead of the canonical content-block array.

What Problem This Solves

After #97742 introduced shared structured tool-result replay extraction, non-canonical or legacy tool-result content can still reach provider replay as a non-array value. The previous draft normalized only inside extractToolResultText(), but several provider callers still inspected the original msg.content with .some(), .filter(), or direct iteration for image/media handling. That meant the stated string or single-object replay path could still throw or suppress useful output before provider payload creation finished.

Review Context Addressed

  • Normalized non-array content before provider media/image checks instead of only inside text extraction.
  • Routed non-standard text / output / content object fields through the existing redaction, inline-data omission, and provider truncation safeguards before replay.
  • Extended the same normalized image-block handling to OpenAI Responses, OpenAI Chat Completions, Mistral, Google, Anthropic, OpenAI/Anthropic transport replay, Google transport extension, and Copilot vision header detection.

Implementation

  • Export a shared normalizeToolResultBlocks() helper for provider replay boundaries.
  • Add shared image-block helpers so caller media handling works for arrays, single image objects, and non-array text/object content without unsafe direct .some() / .filter() calls on the original value.
  • Keep primitive string/number/boolean/bigint content as explicit replay text.
  • Preserve text-like object fields while applying the same redaction/truncation safeguards used by structured fallback text.
  • Keep existing canonical array behavior intact for text, image, audio, structured fallback, binary omission, inline-data omission, and truncation.

Validation

  • GitHub Actions is the authoritative validation source for this branch.
  • Current-head cloud checks should be re-evaluated after the latest patch commit updates provider caller normalization and the PR evidence sections.
  • Local pre-check only: formatter and git diff --check were attempted in a local OpenClaw checkout. The local session is affected by the tool-result replay output-loss symptom being fixed here, so local terminal output is not used as merge proof.

Evidence

  • Source-level proof: the patch removes direct non-array-unsafe media checks from the provider replay paths listed above and routes image extraction through the shared normalized helper.
  • Regression coverage: focused tests now cover plain string content, single structured object content, text-like object redaction/truncation, and single-object image media placeholders.
  • Review linkage: addresses the ClawSweeper findings on src/llm/providers/tool-result-text.ts for redacted text-like object handling and normalized caller media checks.
  • Cloud proof: GitHub Actions checks for the latest PR head are expected to provide the authoritative current-head result after this body update and branch push.

Risk

Low to moderate. The change broadens defensive handling for non-canonical replay content at provider boundaries, but it preserves canonical array behavior and keeps media payload handling restricted to validated image blocks with string MIME/data fields. The security-sensitive part is text-like object replay; that path now applies redaction, inline-data omission, and truncation before provider-bound text is produced.

Rollback

Revert this PR to restore the previous strict array-shaped replay behavior. No data migration or configuration rollback is required.

Docs Updated

No user-facing docs were changed. This is a defensive runtime compatibility fix with regression coverage.

Related Issue / PR

Not Tested / Limitations

  • Local command output from the investigation session was not reliable enough to serve as proof because it intermittently exhibited the replay output-loss behavior under investigation.
  • Full merge confidence should use the latest GitHub Actions checks and any maintainer-required proof artifacts for the current PR head.

@openclaw-barnacle openclaw-barnacle Bot added size: S triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. labels Jul 2, 2026
@clawsweeper

clawsweeper Bot commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed July 2, 2026, 12:15 AM ET / 04:15 UTC.

Summary
The PR widens provider replay helpers to accept non-array tool-result content and updates provider/media callers and tests to preserve string, object, and single-image tool results.

PR surface: Source +79, Tests +102. Total +181 across 12 files.

Reproducibility: yes. Source inspection gives a high-confidence path: replay a text-only model context with a raw string toolResult content value, and transformMessages can turn it into one-character blocks before provider conversion.

Review metrics: none identified.

Root-cause cluster
Relationship: fixed_by_candidate
Canonical: #98825
Summary: The canonical issue tracks non-array tool-result replay loss after the structured replay changes; this PR is one candidate fix, with parallel candidate PRs taking narrower or different normalization layers.

Members:

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

Merge readiness
Overall: 🧂 unranked krab
Proof: 🧂 unranked krab
Patch quality: 🧂 unranked krab
Result: blocked until real behavior proof from a real setup is added.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Rank-up moves:

  • [P1] Normalize raw string and single-object toolResult content before transformMessages can iterate it, then add focused text-only provider replay coverage.
  • [P1] Add redacted after-fix terminal output, logs, or a linked artifact showing a real replay path preserving the tool result.

Proof guidance:

  • [P1] Needs real behavior proof before merge: The PR body provides source proof, regression coverage, and CI references, but no redacted after-fix terminal output, logs, recording, or linked artifact showing the real replay path; screenshots or terminal/log proof should redact private details and a PR-body update should trigger re-review. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Risk before merge

  • [P1] Text-only provider replay can still corrupt raw string tool-result content because transformMessages can split the string before the PR's provider helpers run.
  • [P1] The PR still lacks contributor-supplied real behavior proof; CI and unit tests do not show an after-fix replay path in a real setup.
  • [P1] A related maintainer-labeled candidate normalizes the malformed content at session ingest, so maintainers should decide whether this provider-boundary tolerance should continue or be replaced by the canonical ingest repair.

Maintainer options:

  1. Fix the pre-provider normalization path (recommended)
    Normalize string and single-object toolResult content before transformMessages image downgrade, then add a text-only provider regression proving the original string replays intact.
  2. Adopt the session-ingest repair instead
    Pause this draft and prefer the related maintainer-labeled ingest-boundary PR if maintainers want runtime providers to keep consuming canonical toolResult arrays.
  3. Accept provider-boundary tolerance deliberately
    Maintainers can keep this broader provider-defense approach, but should explicitly own the compatibility risk and require real replay proof before merge.

Next step before merge

  • [P1] Manual review is needed because the PR is draft, has a blocking replay defect, lacks contributor real-behavior proof, and overlaps with a maintainer-labeled ingest-boundary candidate.

Security
Cleared: The diff changes TypeScript replay helpers, provider callers, and tests only; no dependency, workflow, install, credential, or package-publishing surface is broadened, and text-like replay fields still pass through redaction/truncation.

Review findings

  • [P1] Normalize raw tool results before primitive replay — src/llm/providers/tool-result-text.ts:206-208
Review details

Best possible solution:

Normalize non-array tool-result content at the session/transcript boundary or before transformMessages image downgrade, keep provider replay contracts array-shaped where possible, and add focused text-only provider replay proof.

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

Yes. Source inspection gives a high-confidence path: replay a text-only model context with a raw string toolResult content value, and transformMessages can turn it into one-character blocks before provider conversion.

Is this the best way to solve the issue?

No. Provider-boundary normalization is useful but not sufficient because the pre-provider transform path can corrupt raw string tool results first; the safer fix is to normalize loaded/session toolResult content before provider replay.

Full review comments:

  • [P1] Normalize raw tool results before primitive replay — src/llm/providers/tool-result-text.ts:206-208
    On text-only models, transformMessages() still sends every toolResult through replaceImagesWithPlaceholder(msg.content, ...) before provider conversion. If a JSONL transcript supplies content: "lookup result text", that unchanged path iterates the string into one-character blocks; this new primitive block path then preserves those characters and extractToolResultText() joins them with newlines, so the model sees corrupted tool output instead of the original string. Normalize string/single-object toolResult content at ingest or before image downgrade, and cover a text-only provider replay path.
    Confidence: 0.88

Overall correctness: patch is incorrect
Overall confidence: 0.88

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 6e79ca3cbc7d.

Label changes

Label justifications:

  • P1: The PR targets a live agent replay path where successful tool output can be lost or corrupted on the next model turn, and the current head still has a blocking replay defect.
  • merge-risk: 🚨 compatibility: The diff changes how provider replay handles noncanonical persisted tool-result shapes and text-like objects, which can alter upgrade behavior for existing session transcripts.
  • merge-risk: 🚨 message-delivery: The changed replay path controls whether tool output text and media placeholders reach the next model turn, and the current head can still corrupt raw string output for text-only models.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🧂 unranked krab.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs real behavior proof before merge: The PR body provides source proof, regression coverage, and CI references, but no redacted after-fix terminal output, logs, recording, or linked artifact showing the real replay path; screenshots or terminal/log proof should redact private details and a PR-body update should trigger re-review. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Evidence reviewed

PR surface:

Source +79, Tests +102. Total +181 across 12 files.

View PR surface stats
Area Files Added Removed Net
Source 10 160 81 +79
Tests 2 102 0 +102
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 12 262 81 +181

What I checked:

  • Repository policy read: Read the full root policy plus the scoped extensions and agents guides; the review applied the canonical-shape/runtime-boundary guidance and the real-behavior proof gate. (AGENTS.md:29, 6e79ca3cbc7d)
  • Current contract: Current main types tool-result content as a block array, so raw string or single-object session replay is already outside the declared LLM message contract. (packages/llm-core/src/types.ts:310, 6e79ca3cbc7d)
  • Current-main repro source: Current main's shared extractor iterates the raw blocks value, which explains why a plain string can be skipped character-by-character and why provider callers still hit array methods on non-array content. (src/llm/providers/tool-result-text.ts:180, 6e79ca3cbc7d)
  • Unfixed pre-provider transform path: On the PR head, transformMessages still sends every toolResult through replaceImagesWithPlaceholder for text-only models without first checking or normalizing array shape, so a raw string can become an array of characters before provider conversion. (src/llm/providers/transform-messages.ts:56, 7e0034e57243)
  • PR-head primitive replay defect: The new helper preserves arrays as arrays and then treats primitive blocks as replay text; after transformMessages has split a string into characters, extractToolResultText joins those characters with newlines instead of reconstructing the original tool output. (src/llm/providers/tool-result-text.ts:206, 7e0034e57243)
  • Existing string-tool-result fixtures: Current tests already include raw string toolResult content in session/restart paths, supporting that this is a realistic replay shape rather than a purely hypothetical input. (src/agents/main-session-restart-recovery.test.ts:944, 6e79ca3cbc7d)

Likely related people:

  • snowzlmbot: Authored the merged structured replay predecessor commits and authored this draft branch for the same provider replay area. (role: feature contributor and linked fix author; confidence: high; commits: b63e06f68aa0, 524a4932a1ed, 0fe0e7ed62a3; files: src/llm/providers/tool-result-text.ts, src/llm/providers/openai-completions.ts, extensions/google/transport-stream.ts)
  • obviyus: Merged the predecessor structured replay PR and authored the current maintainer-labeled alternative that normalizes non-array tool results at session ingest. (role: predecessor merger and adjacent owner; confidence: high; commits: b63e06f68aa0, ce28ff90f646, 56ae3f26c9dd; files: src/llm/providers/tool-result-text.ts, src/plugin-sdk/provider-transport-runtime.ts, src/agents/sessions/session-manager.ts)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

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.

How this review workflow works
  • 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.

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P1 High-priority user-facing bug, regression, or broken workflow. 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. labels Jul 2, 2026
@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: M and removed size: S triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. labels Jul 2, 2026
@clawsweeper clawsweeper Bot added merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. and removed merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. labels Jul 2, 2026
@obviyus

obviyus commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator

Closing: the underlying bug (#98825) is fixed on main by #98891 (merge commit e095dc8).

We took a different approach than this PR: instead of widening the shared replay helpers to tolerate non-array content, #98891 normalizes tool-result content once at session-JSONL ingest (src/agents/sessions/session-manager.ts) — string becomes [{ type: "text", text }], a single object becomes [object] — so every downstream consumer (provider converters, transport streams, the .some()/.filter() sites) keeps receiving the canonical (TextContent | ImageContent)[] and ToolResultMessage.content stays honest. Regression coverage lives in src/agents/sessions/session-manager.tool-result-replay.test.ts, including an Anthropic replay symptom test that was red before the fix.

Thanks for digging into this — the character-by-character iteration analysis in #98825 was exactly right. If you hit a path where non-array tool-result content still reaches the extractors after e095dc8 (i.e. one that doesn't enter via session-file load), please open a fresh issue with the repro and we'll extend the boundary normalization there.

@obviyus obviyus closed this Jul 2, 2026
@snowzlmbot

Copy link
Copy Markdown
Contributor Author

关闭:底层错误(#98825main )已通过#98891修复(合并提交e095dc8)。

我们采用了与此 PR 不同的方法: #98891并没有扩展共享的重放辅助函数以容忍非数组content,而是在 session-JSONL 摄取时对工具结果进行一次规范化——字符串变为数组,单个对象变为数组——这样,每个下游消费者(提供程序转换器、传输流、/站点)都能持续接收到规范化的结果,从而保持数据的真实性。回归测试用例位于 [此处应填写具体位置],其中包括一个在修复前被判定为红色的 Anthropic 重放症状测试。content``src/agents/sessions/session-manager.ts``[{ type: "text", text }]``[object]``.some()``.filter()``(TextContent | ImageContent)[]``ToolResultMessage.content``src/agents/sessions/session-manager.tool-result-replay.test.ts

感谢您深入研究这个问题—— #98825中的逐字符迭代分析完全正确。如果您遇到非数组工具结果内容在e095dc8之后仍然到达提取器的情况(即并非通过会话文件加载进入),请提交一个新的 issue 并附上复现步骤,我们将扩展边界规范化。

Thanks for submitting the PR. I'll pull this PR patch locally and test it again to make sure the bug is actually fixed and no new bugs are introduced

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

Labels

agents Agent runtime and tooling extensions: google merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: M status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

bug(llm): tool-result replay can drop non-array output content

2 participants