Skip to content

fix(executor): capture Claude CLI stderr via SDK callback - #105

Merged
chrisleekr merged 3 commits into
mainfrom
fix/capture-cli-stderr
May 6, 2026
Merged

fix(executor): capture Claude CLI stderr via SDK callback#105
chrisleekr merged 3 commits into
mainfrom
fix/capture-cli-stderr

Conversation

@chrisleekr

@chrisleekr chrisleekr commented May 6, 2026

Copy link
Copy Markdown
Owner

Summary

When the bundled Claude Code CLI subprocess exits non-zero, the Agent SDK throws a content-free Error("Claude Code process exited with code N") and the daemon logs only that wrapper — the CLI's actual stderr (auth failure, 429 rate-limit, model rejection, OOM, missing binary, etc.) is never surfaced. Today's pod failure (github-app-playground-daemon-default-5b89f6dc4-twmdk on issue #93, durationMs: 248ms) was diagnosable only by kubectl exec into the pod and reproducing the call by hand. The SDK already exposes a stderr: (data: string) => void callback hook in query() options — we just weren't wiring it.

This change subscribes the daemon's request-scoped pino logger to that callback. No new deps, no env-var changes, no API surface changes.

Diagram

flowchart LR
  subgraph Flow["Failure surfacing path"]
    direction TB
    BeforeCLI["Claude CLI exits 1<br/>writes to stderr"]:::before
    BeforeSDK["SDK wraps in<br/>Error 'exited with code 1'"]:::before
    BeforePino["pino logs<br/>err.message only<br/>stderr SWALLOWED"]:::beforeBad
    BeforeOps["Operator must kubectl exec<br/>and reproduce by hand"]:::beforeBad

    BeforeCLI --> BeforeSDK --> BeforePino --> BeforeOps

    AfterCLI["Claude CLI exits 1<br/>writes to stderr"]:::after
    AfterSDK["SDK pipes stderr chunks<br/>to callback hook"]:::after
    AfterPino["pino logs each line as<br/>warn 'Claude CLI stderr'"]:::afterGood
    AfterOps["Operator reads pod log<br/>root cause visible"]:::afterGood

    AfterCLI --> AfterSDK --> AfterPino --> AfterOps
  end

  classDef before fill:#fde8e8,stroke:#9b1c1c,color:#1a1a1a
  classDef beforeBad fill:#9b1c1c,stroke:#1a1a1a,color:#ffffff
  classDef after fill:#def7ec,stroke:#03543f,color:#1a1a1a
  classDef afterGood fill:#03543f,stroke:#1a1a1a,color:#ffffff
Loading

Changes

  • src/core/executor.ts: add stderr callback to queryOptions passed to the SDK query() call. Each non-empty stderr chunk is trimmed and logged at warn level on the existing request-scoped logger as { stderr: <line> }, "Claude CLI stderr". Empty/whitespace-only chunks are skipped to avoid log spam.

Related Issues

Test plan

  • Tested locally — bun run typecheck clean
  • Existing tests pass — bun test test/core/executor.test.ts 5/5
  • Added/updated tests — none added; the change is a pure pass-through to pino. A unit test would have to assert pino received a specific structured-log call when the SDK mock emits stderr, which couples the test to SDK internals. Manual verification on next CLI failure in a non-prod pod is the cheaper signal.
  • No new lint warnings introduced (the two pre-existing executeAgent complexity/length warnings are unchanged in kind, count went 146 → 152 lines on a function already over the 120 limit).

Summary by CodeRabbit

  • New Features
    • CLI execution can now be properly cancelled using abort signals.
    • Improved error diagnostics with enhanced stderr output logging for better troubleshooting.

Copilot AI review requested due to automatic review settings May 6, 2026 10:46
@coderabbitai

coderabbitai Bot commented May 6, 2026

Copy link
Copy Markdown

Warning

Rate limit exceeded

@chrisleekr has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 31 minutes and 14 seconds before requesting another review.

To continue reviewing without waiting, purchase usage credits in the billing tab.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: e08e63ed-238c-4d96-ad50-ae1e6a53fb5c

📥 Commits

Reviewing files that changed from the base of the PR and between b5ba774 and b975284.

📒 Files selected for processing (2)
  • src/core/executor.ts
  • test/core/executor.test.ts
📝 Walkthrough

Walkthrough

The PR adds two observable properties to the Claude Agent SDK execution path: an abortController for external cancellation of the Claude Code CLI, and a stderr callback for logging CLI diagnostic output. No public API signatures change.

Changes

Executor Query Options Enhancement

Layer / File(s) Summary
Query Options Data Shape
src/core/executor.ts (lines 237–239)
Query options now include abortController: controller to enable external cancellation of the Claude Code CLI.
Stderr Callback Implementation
src/core/executor.ts (lines 240–249)
Query options include stderr callback that trims CLI output and logs warning messages for non-empty stderr streams.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: wiring the SDK stderr callback to capture Claude CLI stderr output for better error diagnostics, which is the core modification made to src/core/executor.ts.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

This PR improves daemon/operator observability by wiring the Claude Agent SDK’s stderr streaming callback into the request-scoped pino logger, so Claude Code CLI failures surface their real root-cause text (instead of only the SDK’s generic “process exited” wrapper error).

Changes:

  • Add an stderr callback to the SDK query() options in executeAgent().
  • Trim and skip whitespace-only stderr chunks, logging non-empty output as warn with structured { stderr }.

Comment thread src/core/executor.ts Outdated
Comment thread src/core/executor.ts Outdated
Comment thread src/core/executor.ts
chrisleekr added 2 commits May 6, 2026 20:58
Apply Copilot review feedback on PR #105:
- length-cap stderr at 500 chars + truncated flag (matches updater.ts /
  scoped-rebase-executor.ts convention)
- swap trim() for trimEnd() so leading indentation in multi-line stack
  traces stays readable
- add 5 unit tests covering forwarding, logging, indentation preservation,
  whitespace-skip, and truncation
CLI stderr can echo bearer tokens, OAuth tokens, or DB URLs (e.g. a
failed HTTP call dumping its Authorization header). The new pino
log path would surface those into pod logs and any cluster-wide log
aggregator, undoing the protection that buildProviderEnv's allowlist
provides on the subprocess side.

Pipe each chunk through redactSecrets() before truncation/logging
and surface a structured redactedSecretCount + redactedSecretKinds
log field so operators can attribute redactions without ever seeing
the matched bytes. If the chunk becomes empty after redaction it is
skipped, matching the existing whitespace-only behaviour.

Comment also corrected: SDK forwards stderr in stream chunks, not
strictly line-by-line.
@chrisleekr
chrisleekr requested a review from Copilot May 6, 2026 11:15
@chrisleekr

Copy link
Copy Markdown
Owner Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented May 6, 2026

Copy link
Copy Markdown
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copilot AI left a comment

Copy link
Copy Markdown

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 2 out of 2 changed files in this pull request and generated 1 comment.

Comment thread src/core/executor.ts
@chrisleekr
chrisleekr merged commit 3482443 into main May 6, 2026
26 checks passed
@chrisleekr
chrisleekr deleted the fix/capture-cli-stderr branch May 6, 2026 11:34
chrisleekr pushed a commit that referenced this pull request May 6, 2026
## [1.10.1](v1.10.0...v1.10.1) (2026-05-06)

### Bug Fixes

* **executor:** capture Claude CLI stderr via SDK callback ([#105](#105)) ([3482443](3482443))
@chrisleekr

Copy link
Copy Markdown
Owner Author

🎉 This PR is included in version 1.10.1 🎉

The release is available on GitHub release

Your semantic-release bot 📦🚀

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants