Skip to content

[TASK] Improve Claude Code Headless Integration with Streaming Events #743

Closed

Description

@edenreich

The Claude Code headless integration is already implemented, but the current flow only fetches the final result after execution completes.

We should improve it by running Claude Code with streaming JSON, verbose output, and hook events:

claude -p "<prompt>" \
  --output-format stream-json \
  --verbose \
  --include-hook-events

Goal

Allow infer to consume Claude Code events in real time instead of waiting only for the final JSON result.

The goal is to be able to capture these and then we can send them to inference gateway otel collector in #741

This will help infer:

  • stream progress while Claude Code is running
  • capture hook lifecycle events
  • detect tool-call failures more reliably
  • surface intermediate agent activity in the normal infer UX
  • still extract the final result at the end

Acceptance Criteria

  • Claude Code runner supports --output-format stream-json
  • Claude Code runner supports --verbose
  • Claude Code runner supports --include-hook-events
  • streamed events are parsed incrementally
  • hook events are captured and normalized
  • final result is still captured correctly
  • tool-call failures are detected from the stream when available
  • existing non-streaming JSON mode still works as fallback
  • malformed or interrupted streams are handled cleanly

Notes

This is an improvement to the existing Claude Code headless implementation, not a full rewrite.

The main change is moving from “wait for final result” to “stream events, normalize them, capture hook events, and then return the final result.”

Example Stream JSON Events

When running Claude Code with:

claude -p "<prompt>" \
  --output-format stream-json \
  --verbose \
  --include-hook-events

infer should parse the JSONL stream incrementally.

Only the important event fields need to be normalized.

Session Init

{
  "type": "system",
  "subtype": "init",
  "session_id": "xxx",
  "cwd": "/path/to/repo",
  "model": "claude-fable-5",
  "permissionMode": "auto",
  "claude_code_version": "2.1.197",
  "tools": ["Read", "Bash", "Write", "Edit"]
}

Tool Call

{
  "type": "assistant",
  "session_id": "xxx",
  "message": {
    "role": "assistant",
    "content": [
      {
        "type": "tool_use",
        "id": "toolu_xxx",
        "name": "Read",
        "input": {
          "file_path": "/path/to/repo/README2.md"
        }
      }
    ]
  }
}

Failed Tool Result

{
  "type": "user",
  "session_id": "xxx",
  "message": {
    "role": "user",
    "content": [
      {
        "type": "tool_result",
        "tool_use_id": "toolu_xxx",
        "is_error": true,
        "content": "File does not exist."
      }
    ]
  },
  "tool_use_result": "Error: File does not exist."
}

Successful Tool Result

{
  "type": "user",
  "session_id": "xxx",
  "message": {
    "role": "user",
    "content": [
      {
        "type": "tool_result",
        "tool_use_id": "toolu_xxx",
        "is_error": false,
        "content": "README.md\nCHANGELOG.md\nCONTRIBUTING.md"
      }
    ]
  },
  "tool_use_result": {
    "stdout": "README.md\nCHANGELOG.md\nCONTRIBUTING.md",
    "stderr": "",
    "interrupted": false
  }
}

Assistant Text Response

{
  "type": "assistant",
  "session_id": "xxx",
  "message": {
    "role": "assistant",
    "content": [
      {
        "type": "text",
        "text": "There's no README2.md in the repo root. Did you mean README.md?"
      }
    ]
  }
}

Final Result

{
  "type": "result",
  "subtype": "success",
  "is_error": false,
  "session_id": "xxx",
  "duration_ms": 14073,
  "num_turns": 3,
  "result": "There's no README2.md in the repo root. Did you mean README.md?",
  "stop_reason": "end_turn",
  "total_cost_usd": 0.378879,
  "permission_denials": [],
  "terminal_reason": "completed"
}

Important Behavior

A Claude Code run can finish successfully even when an internal tool call failed.

For example:

{
  "type": "result",
  "subtype": "success",
  "is_error": false
}

does not mean every tool call succeeded.

Tool failures should be detected from streamed tool_result events:

{
  "type": "tool_result",
  "is_error": true,
  "tool_use_id": "toolu_xxx"
}

So the runner should track tool calls by tool_use.id and match them with tool_result.tool_use_id.

Activity

  1. added theissue type on Jul 4, 2026
  2. added
    refactor
    on Jul 4, 2026
  3. moved this to Todo in 2026on Jul 4, 2026
  4. edenreich commented on Jul 4, 2026

    @edenreich
    ContributorAuthor

    @infer /model deepseek/deepseek-v4-flash Can you work on this? use /go /go-concurrency and any other skills that maybe necessary.

  5. inference-gateway-maintainer commented on Jul 4, 2026

    @inference-gateway-maintainer
    Contributor

    Model: deepseek/deepseek-v4-flash · View Job

    Todos

    • Explore codebase to understand current Claude Code headless integration
    • Update ClaudeCodeMessage struct with all stream event fields
    • Add --include-hook-events to buildArgs()
    • Implement tool-call failure detection in stream parsing
    • Enhance transformMessage for all event types (system init, hooks, tool results with is_error)
    • Handle malformed/interrupted streams gracefully
    • Add comprehensive tests for new functionality
    • Commit, push, and create PR

    Pull Request

    #744

    ✅ Infer Result: Success

    No additional work is needed. The implementation fully addresses all acceptance criteria from issue #743.

    Model: deepseek/deepseek-v4-flash · Exit Code: 0 · Duration: 9m 50s

    Tokens: 6,325,220 in · 30,193 out · 6,355,413 total (54 requests)

    Cost: $0.8855 in · $0.0085 out · $0.894 total

    Tool calls: 60 total · 97% success rate

    ⚠️ 2 failed tool call(s)
    • Bash: exit status 1: # github.com/inference-gateway/cli/internal/infra/adapters [github.com/inference-gateway/cli/internal/infra/adapters.test]
      internal/infra/adapters/claude_code_client_test.go:426:17: json.Unmarshal undefined (type string has no field or method Unmarshal)
      internal/infra/adapters/claude_code_client_test.go:466:17: json.Unmarshal undefined (type string has no field or method Unmarshal)
      internal/infra/adapters/claude_code_client_test.go:512:17: json.Unmarshal undefined (type string has no field or method Unmarshal)
      internal/infra/adapters/claude_code_client_test.go:517:17: json.Unmarshal undefined (type string has no field or method Unmarshal)
      FAIL github.com/inference-gateway/cli/internal/infra/adapters [build failed]
      FAIL
    • Edit: old_string not found in file /home/runner/work/cli/cli/internal/infra/adapters/claude_code_client_test.go

    No similar content found. Please verify the content exists and matches exactly (including whitespace).

    Triggered by edenreich · Infer Action

  6. added a commit that references this issue on Jul 4, 2026
    6c7ba09
  7. inference-gateway-releaser commented on Jul 4, 2026

    @inference-gateway-releaser
    Contributor

    🎉 This issue has been resolved in version 0.132.0 🎉

    The release is available on:

    Your semantic-release bot 📦🚀

  8. moved this from Todo to Done in 2026on Jul 5, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    refactorreleased

    Type

    Projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions