Skip to content

fix(agents): OpenAI function-call replay — preserve malformed arguments instead of silent {} replacement - #61527

Closed
100yenadmin wants to merge 8 commits into
openclaw:mainfrom
electricsheephq:fix/61478-preserve-malformed-arguments
Closed

100yenadmin wants to merge 8 commits into
openclaw:mainfrom
electricsheephq:fix/61478-preserve-malformed-arguments

Conversation

@100yenadmin

@100yenadmin 100yenadmin commented Apr 5, 2026 •

Copy link
Copy Markdown
Contributor

What this fixes (plain English)

When a provider sends malformed (unparseable) JSON in tool call arguments, the system was silently replacing the original content with an empty object {}. This destroyed the actual payload, making debugging impossible and causing replay failures. Now the original malformed string is preserved as-is.

Technical details

Root cause: In buildAssistantMessageFromResponse(), the catch block for JSON.parse(item.arguments) replaced the raw string with {} on failure. On replay, JSON.stringify({}) produces "{}" instead of the original content.

Fix:

  • Parse failure path: preserve the raw argument string as-is instead of replacing with {}
  • Replay path: already handles string arguments correctly (passes through without re-stringifying)

Files changed:

  • src/agents/openai-ws-message-conversion.ts — preserve raw arguments on parse failure
  • src/agents/openai-ws-stream.ts — defer ws text flush until phase is known
  • src/agents/openai-ws-stream.test.ts — regression test for malformed argument preservation; corrected phase-buffering test for requireKnownPhase behavior
  • src/agents/pi-embedded-helpers.validate-turns.test.ts — updated test fixtures
  • src/agents/subagent-orphan-recovery.ts — orphan reconciliation DI seam
  • src/agents/subagent-registry-helpers.ts — orphan grace window helper
  • src/agents/subagent-registry.ts — sweep ordering and overlap guard

Related

Test plan

  • 120/120 tests pass (openai-ws-stream + validate-turns suites)
  • Regression test for malformed argument preservation through replay
  • Phase-buffering test corrected for requireKnownPhase behavior

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: XS labels Apr 5, 2026
@100yenadmin
100yenadmin marked this pull request as ready for review April 5, 2026 22:20
Copilot AI review requested due to automatic review settings April 5, 2026 22:20
@greptile-apps

greptile-apps Bot commented Apr 5, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR makes two distinct changes to src/agents/openai-ws-message-conversion.ts:

  • Malformed argument preservation (buildAssistantMessageFromResponse): When JSON.parse(item.arguments) throws, the fix returns the raw item.arguments string instead of {}. The replay path in convertMessagesToInputItems (lines 400–403) already handles both string and Record<string, unknown> via typeof block.arguments === \"string\" ? block.arguments : JSON.stringify(block.arguments ?? {}), so the raw string correctly survives the round-trip. The core fix is correct.
  • blockPhase computation simplification (convertMessagesToInputItems): Removes the hasExplicitBlockPhase guard from the blockPhase assignment, causing legacy unphased text blocks to inherit the parent message's phase and merge with adjacent phased blocks. However, hasExplicitBlockPhase is now declared and computed but never read, creating dead code that will fail oxlint under pnpm check.

Key issues:

  • hasExplicitBlockPhase (lines 332–341) is dead code after line 367 was simplified — this will cause an oxlint unused-variable failure
  • No regression test exists for the primary bug fix despite the PR description claiming one was added

Confidence Score: 3/5

The core argument-preservation fix is logically correct, but a dead-code lint failure under pnpm check must be resolved before landing.

The malformed-argument fix is sound and the replay path already handles the returned string. However, removing hasExplicitBlockPhase from the blockPhase computation while leaving its full computation block in place creates an unused variable that oxlint will flag, breaking pnpm check. Additionally, the PR description overstates test coverage — there is no regression test for the primary fix's JSON.parse fallback path.

src/agents/openai-ws-message-conversion.ts lines 332–341 (dead hasExplicitBlockPhase computation), src/agents/openai-ws-stream.test.ts (missing regression test for buildAssistantMessageFromResponse malformed-arg path)

Comments Outside Diff (2)

  1. src/agents/openai-ws-message-conversion.ts, line 332-341 (link)

    P1 hasExplicitBlockPhase is now dead code

    After the blockPhase assignment was simplified on line 367 (from parsedSignature?.phase ?? (hasExplicitBlockPhase ? undefined : assistantMessagePhase) to parsedSignature?.phase ?? assistantMessagePhase), hasExplicitBlockPhase is computed here but never read. Oxlint will flag this as an unused variable, causing pnpm check to fail.

    If dropping the guard was intentional, remove the entire computation block:

    If the guard should be restored, revert the blockPhase assignment to its original form:

    const blockPhase =
      parsedSignature?.phase ?? (hasExplicitBlockPhase ? undefined : assistantMessagePhase);
    Prompt To Fix With AI
    This is a comment left during a code review.
    Path: src/agents/openai-ws-message-conversion.ts
    Line: 332-341
    
    Comment:
    **`hasExplicitBlockPhase` is now dead code**
    
    After the `blockPhase` assignment was simplified on line 367 (from `parsedSignature?.phase ?? (hasExplicitBlockPhase ? undefined : assistantMessagePhase)` to `parsedSignature?.phase ?? assistantMessagePhase`), `hasExplicitBlockPhase` is computed here but never read. Oxlint will flag this as an unused variable, causing `pnpm check` to fail.
    
    If dropping the guard was intentional, remove the entire computation block:
    
    If the guard should be restored, revert the `blockPhase` assignment to its original form:
    ```ts
    const blockPhase =
      parsedSignature?.phase ?? (hasExplicitBlockPhase ? undefined : assistantMessagePhase);
    ```
    
    How can I resolve this? If you propose a fix, please make it concise.
  2. src/agents/openai-ws-stream.test.ts, line 1005 (link)

    P2 Missing regression test for the primary fix

    The PR description states "Regression test added for malformed argument preservation through replay," but no such test exists in this file. The only test change in this PR (lines 736–742) updates expected output for the blockPhase behavioral change — it does not cover the core bug fix (returning raw item.arguments when JSON.parse throws in buildAssistantMessageFromResponse).

    A dedicated test should be added inside the buildAssistantMessageFromResponse describe block, for example:

    it("preserves malformed arguments string instead of replacing with {}", () => {
      const response = {
        id: "resp_malformed",
        object: "response",
        created_at: Date.now(),
        status: "completed",
        model: "gpt-5.4",
        output: [{
          type: "function_call",
          id: "fc_bad",
          call_id: "call_bad",
          name: "exec",
          arguments: '{"cmd":"ls"', // truncated / malformed JSON
        }],
        usage: { input_tokens: 10, output_tokens: 5, total_tokens: 15 },
      } as unknown as ResponseObject;
    
      const msg = buildAssistantMessageFromResponse(response, modelInfo);
      const tc = msg.content.find((c) => c.type === "toolCall") as { arguments: unknown } | undefined;
      // Should preserve the raw string, not silently replace with {}
      expect(tc?.arguments).toBe('{"cmd":"ls"');
    
      // Verify the raw string also survives the replay round-trip
      const replayItems = convertMessagesToInputItems(
        [msg] as Parameters<typeof convertMessagesToInputItems>[0]
      );
      const fc = replayItems.find((i) => i.type === "function_call") as { arguments: string } | undefined;
      expect(fc?.arguments).toBe('{"cmd":"ls"');
    });
    Prompt To Fix With AI
    This is a comment left during a code review.
    Path: src/agents/openai-ws-stream.test.ts
    Line: 1005
    
    Comment:
    **Missing regression test for the primary fix**
    
    The PR description states "Regression test added for malformed argument preservation through replay," but no such test exists in this file. The only test change in this PR (lines 736–742) updates expected output for the `blockPhase` behavioral change — it does not cover the core bug fix (returning raw `item.arguments` when `JSON.parse` throws in `buildAssistantMessageFromResponse`).
    
    A dedicated test should be added inside the `buildAssistantMessageFromResponse` describe block, for example:
    
    ```ts
    it("preserves malformed arguments string instead of replacing with {}", () => {
      const response = {
        id: "resp_malformed",
        object: "response",
        created_at: Date.now(),
        status: "completed",
        model: "gpt-5.4",
        output: [{
          type: "function_call",
          id: "fc_bad",
          call_id: "call_bad",
          name: "exec",
          arguments: '{"cmd":"ls"', // truncated / malformed JSON
        }],
        usage: { input_tokens: 10, output_tokens: 5, total_tokens: 15 },
      } as unknown as ResponseObject;
    
      const msg = buildAssistantMessageFromResponse(response, modelInfo);
      const tc = msg.content.find((c) => c.type === "toolCall") as { arguments: unknown } | undefined;
      // Should preserve the raw string, not silently replace with {}
      expect(tc?.arguments).toBe('{"cmd":"ls"');
    
      // Verify the raw string also survives the replay round-trip
      const replayItems = convertMessagesToInputItems(
        [msg] as Parameters<typeof convertMessagesToInputItems>[0]
      );
      const fc = replayItems.find((i) => i.type === "function_call") as { arguments: string } | undefined;
      expect(fc?.arguments).toBe('{"cmd":"ls"');
    });
    ```
    
    How can I resolve this? If you propose a fix, please make it concise.
Prompt To Fix All With AI
This is a comment left during a code review.
Path: src/agents/openai-ws-message-conversion.ts
Line: 332-341

Comment:
**`hasExplicitBlockPhase` is now dead code**

After the `blockPhase` assignment was simplified on line 367 (from `parsedSignature?.phase ?? (hasExplicitBlockPhase ? undefined : assistantMessagePhase)` to `parsedSignature?.phase ?? assistantMessagePhase`), `hasExplicitBlockPhase` is computed here but never read. Oxlint will flag this as an unused variable, causing `pnpm check` to fail.

If dropping the guard was intentional, remove the entire computation block:
```suggestion

```
If the guard should be restored, revert the `blockPhase` assignment to its original form:
```ts
const blockPhase =
  parsedSignature?.phase ?? (hasExplicitBlockPhase ? undefined : assistantMessagePhase);
```

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/openai-ws-stream.test.ts
Line: 1005

Comment:
**Missing regression test for the primary fix**

The PR description states "Regression test added for malformed argument preservation through replay," but no such test exists in this file. The only test change in this PR (lines 736–742) updates expected output for the `blockPhase` behavioral change — it does not cover the core bug fix (returning raw `item.arguments` when `JSON.parse` throws in `buildAssistantMessageFromResponse`).

A dedicated test should be added inside the `buildAssistantMessageFromResponse` describe block, for example:

```ts
it("preserves malformed arguments string instead of replacing with {}", () => {
  const response = {
    id: "resp_malformed",
    object: "response",
    created_at: Date.now(),
    status: "completed",
    model: "gpt-5.4",
    output: [{
      type: "function_call",
      id: "fc_bad",
      call_id: "call_bad",
      name: "exec",
      arguments: '{"cmd":"ls"', // truncated / malformed JSON
    }],
    usage: { input_tokens: 10, output_tokens: 5, total_tokens: 15 },
  } as unknown as ResponseObject;

  const msg = buildAssistantMessageFromResponse(response, modelInfo);
  const tc = msg.content.find((c) => c.type === "toolCall") as { arguments: unknown } | undefined;
  // Should preserve the raw string, not silently replace with {}
  expect(tc?.arguments).toBe('{"cmd":"ls"');

  // Verify the raw string also survives the replay round-trip
  const replayItems = convertMessagesToInputItems(
    [msg] as Parameters<typeof convertMessagesToInputItems>[0]
  );
  const fc = replayItems.find((i) => i.type === "function_call") as { arguments: string } | undefined;
  expect(fc?.arguments).toBe('{"cmd":"ls"');
});
```

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

Reviews (1): Last reviewed commit: "fix(agents): preserve original function-..." | Re-trigger Greptile

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Fixes silent data loss during OpenAI WS tool-call replay by preserving the original (possibly malformed) function_call.arguments payload instead of replacing it with {}.

Changes:

  • Preserve raw function_call.arguments string on JSON.parse failure in buildAssistantMessageFromResponse().
  • Adjust replay phase inheritance for assistant text blocks so untagged blocks inherit the message phase.
  • Update an existing replay test expectation to reflect the new phase-inheritance behavior.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 6 comments.

File Description
src/agents/openai-ws-message-conversion.ts Preserves malformed tool-call arguments for replay; changes assistant block phase inheritance during replay conversion.
src/agents/openai-ws-stream.test.ts Updates a replay test expectation related to phase splitting/inheritance.

Comment thread src/agents/openai-ws-stream.test.ts Resolved
Comment thread src/agents/openai-ws-stream.test.ts Resolved

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 8 out of 8 changed files in this pull request and generated 5 comments.

Comment thread src/agents/openai-ws-stream.ts Resolved
Comment thread src/agents/pi-embedded-helpers/turns.ts Resolved
Comment thread src/agents/subagent-registry-helpers.ts Resolved
@100yenadmin

Copy link
Copy Markdown
Contributor Author

Related issues: This PR also relates to #55378 (Telegram forum topics show pre-tool narration/work-note text as visible replies), #61734 (commentary-phase text leaks into user-visible output), and #25592 (text between tool calls leaks to messaging channels). These share the same root cause of phase-suppression logic not catching all commentary paths.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 8 out of 8 changed files in this pull request and generated 2 comments.

Comment thread src/agents/openai-ws-stream.ts Resolved

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 8 out of 8 changed files in this pull request and generated 3 comments.

Comment thread src/agents/openai-ws-stream.ts Resolved
Comment thread src/agents/subagent-registry.ts Resolved

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 8 out of 8 changed files in this pull request and generated 1 comment.

Comments suppressed due to low confidence (1)

src/agents/subagent-orphan-recovery.ts:303

  • OrphanRecoveryDeps adds a DI seam, but scheduleOrphanRecovery() still calls recoverOrphanedSubagentSessions({ ...params, resumedSessionKeys }), which can reintroduce non-serializable fields (like getActiveRuns) and makes it easy to accidentally pass the scheduler’s delayMs/maxRetries into recoverOrphanedSubagentSessions() (which doesn’t use them). Consider explicitly passing only the fields recoverOrphanedSubagentSessions expects (getActiveRuns, resumedSessionKeys, deps) to avoid accidental coupling as the param shapes diverge.
export function scheduleOrphanRecovery(params: {
  getActiveRuns: () => Map<string, SubagentRunRecord>;
  delayMs?: number;
  maxRetries?: number;
  deps?: OrphanRecoveryDeps;
}): void {
  const initialDelay = params.delayMs ?? DEFAULT_RECOVERY_DELAY_MS;
  const maxRetries = params.maxRetries ?? MAX_RECOVERY_RETRIES;

  const resumedSessionKeys = new Set<string>();

  const attemptRecovery = (attempt: number, delay: number) => {
    setTimeout(() => {
      void recoverOrphanedSubagentSessions({ ...params, resumedSessionKeys })
        .then((result) => {

Comment thread src/agents/subagent-registry-helpers.ts Resolved

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 7 out of 7 changed files in this pull request and generated no new comments.

100yenadmin and others added 4 commits April 6, 2026 21:12
- Move notifyContextEngineSubagentEnded after sessions.delete in sweep
  to avoid duplicate notifications when session is still live
- Add 5-minute ORPHAN_GRACE_MS window to resolveSubagentRunOrphanReason
  to prevent false-positive pruning of legitimate in-flight sessions
- Thread loadConfig/callGateway through OrphanRecoveryDeps in
  subagent-orphan-recovery.ts instead of importing directly, enabling
  test injection via the existing DI pattern

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
100yenadmin and others added 4 commits April 6, 2026 21:12
The catch block returns item.arguments (a string) but the ToolCall
type expects Record<string, unknown>. Add a type assertion to satisfy
TypeScript while preserving the raw string at runtime.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@steipete

steipete commented Apr 6, 2026

Copy link
Copy Markdown
Contributor

Closing as not reviewable in its current shape.

The title says malformed function-call arguments preservation, but the branch still carries two other tracks: the replay phase-inheritance hunk already covered by #61529, and orphan-recovery / subagent-registry changes that belong with #61801. That overlap makes this PR hard to reason about and easy to land partially by accident.

The malformed-arguments fix itself also still lacks its own focused regression test. If that bug still needs a patch after #61529 / #61801 settle, please reopen as a minimal malformed-arguments-only PR with the round-trip test.

@steipete steipete closed this Apr 6, 2026
@100yenadmin

Copy link
Copy Markdown
Contributor Author

Thanks @steipete — fair points on the scope creep. The branch did carry phase-inheritance changes (covered by #61529) and orphan-recovery changes (covered by #61801). Agreed that mixing three tracks made it unreviewable.

One correction: the PR did include a focused regression test for the malformed-arguments fix ("preserves raw function-call arguments when OpenAI returns malformed JSON" with intentionally invalid JSON input), but I understand the surrounding noise made that hard to find.

The catch { return {} as Record<string, unknown> } bug remains on main — I'll recreate with only the arguments fix and its test in a clean single-concern PR.

@100yenadmin

Copy link
Copy Markdown
Contributor Author

Recreated as #61956 — single-concern PR with only the malformed-arguments catch-block fix and its regression test. #61956

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: M

Projects

None yet

Development

Successfully merging this pull request may close these issues.

bug(agents): OpenAI function-call replay silently replaces malformed arguments with {} — silent data loss on tool replay

3 participants