claude-agent-sdk 1.1.0 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/.yardopts +10 -0
- data/CHANGELOG.md +90 -0
- data/README.md +43 -31
- data/docs/cli-installer.md +26 -4
- data/docs/client.md +29 -11
- data/docs/configuration.md +164 -1
- data/docs/errors.md +32 -2
- data/docs/hooks-and-permissions.md +30 -10
- data/docs/mcp-servers.md +30 -9
- data/docs/observability.md +61 -10
- data/docs/options.md +232 -0
- data/docs/rails.md +263 -18
- data/docs/sessions.md +40 -12
- data/docs/subagents.md +1 -1
- data/docs/types.md +100 -11
- data/lib/claude_agent_sdk/cli_installer.rb +140 -19
- data/lib/claude_agent_sdk/command_builder.rb +84 -27
- data/lib/claude_agent_sdk/fiber_boundary.rb +45 -2
- data/lib/claude_agent_sdk/instrumentation/otel.rb +90 -28
- data/lib/claude_agent_sdk/query.rb +228 -77
- data/lib/claude_agent_sdk/railtie.rb +27 -2
- data/lib/claude_agent_sdk/sdk_mcp_server.rb +78 -26
- data/lib/claude_agent_sdk/session_mutations.rb +112 -92
- data/lib/claude_agent_sdk/session_resume.rb +356 -39
- data/lib/claude_agent_sdk/session_store.rb +31 -2
- data/lib/claude_agent_sdk/sessions.rb +720 -138
- data/lib/claude_agent_sdk/subprocess_cli_transport.rb +227 -29
- data/lib/claude_agent_sdk/testing/session_store_conformance.rb +18 -7
- data/lib/claude_agent_sdk/transcript_mirror_batcher.rb +45 -37
- data/lib/claude_agent_sdk/transport.rb +28 -12
- data/lib/claude_agent_sdk/types/attributes.rb +9 -0
- data/lib/claude_agent_sdk/types/base.rb +85 -15
- data/lib/claude_agent_sdk/types/hooks.rb +73 -0
- data/lib/claude_agent_sdk/types/mcp.rb +37 -1
- data/lib/claude_agent_sdk/types/option_values.rb +186 -4
- data/lib/claude_agent_sdk/types/options.rb +35 -5
- data/lib/claude_agent_sdk/types/permissions.rb +18 -9
- data/lib/claude_agent_sdk/version.rb +1 -1
- data/lib/claude_agent_sdk.rb +94 -46
- data/lib/generators/claude_agent_sdk/install/templates/claude_agent_sdk.rb.tt +6 -0
- data/sig/claude_agent_sdk/types/hooks.rbs +6 -3
- data/sig/claude_agent_sdk/types/option_values.rbs +23 -6
- data/sig/claude_agent_sdk/types/options.rbs +11 -7
- data/sig/claude_agent_sdk/types/permissions.rbs +4 -2
- metadata +6 -4
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: '0830ea985ad6a281cbdf19d50a13e4309b45d900c0024bd4e1b28949afeb0587'
|
|
4
|
+
data.tar.gz: fa9946c463c428d9c3128a1e8acd010eccbda18760a1993e9e12ced8da2d56a9
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 36cb49cbd769299019cf24098fb7ad4d81a4fe78a750e77b7b17ea90c4f57e66b6b6f344b7bde4ad04cfe048cb55d6420f3a004200ba0029063da1225240cb74
|
|
7
|
+
data.tar.gz: 84c081d5d2639e395e87927b28a3187584d9cd9323282d49dc2744fa530a579426f5393f883cc763a5b8772679eed2152608e8ad0508641d8b9145291f1e0a93
|
data/.yardopts
ADDED
data/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,96 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [1.2.0] - 2026-10-03
|
|
11
|
+
|
|
12
|
+
Fixes from a review of the whole SDK, a reference for every option (`docs/options.md`), and Claude Code 2.1.288 as the pinned CLI. Settings the SDK used to drop without an error now take effect — hook outputs and `sandbox:` Hashes in Ruby spelling, a `tools:` String, option Hashes with a Symbol `type` — so read the entries in bold before upgrading: they say what changes for code that relied on the old behavior.
|
|
13
|
+
|
|
14
|
+
### Added
|
|
15
|
+
- **`docs/options.md`**: a reference for every `ClaudeAgentOptions` attribute — its type, its default, and the CLI flag, `initialize` field or environment variable it becomes — plus what an option reads when it is left out, passed as `nil` or given a configured default, and the environment variables the SDK reads. It documents options that had no entry anywhere before (`extra_args`, `include_partial_messages`, `include_hook_events`, `task_budget`, `strict_mcp_config`) and the `CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS` ceiling from 1.1.0. A spec checks every row against the code. `docs/client.md` documents the `transport:` argument of `query` / `ask`. ([#155](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/155))
|
|
16
|
+
- `Pathname` where a path goes: `settings:` (a settings file; used to send no `--settings` at all), `SystemPromptFile#path`, the `path` of a `{ type: 'file' }` system prompt Hash, and a plugin path, typed or Hash (these failed at connect with `no implicit conversion of Pathname into String`). `tools:` is signed `String` as well; the RBS signatures are widened accordingly. ([#160](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/160))
|
|
17
|
+
|
|
18
|
+
### Changed
|
|
19
|
+
- `docs/cli-installer.md` now says when `CLIInstaller::PINNED_CLI_VERSION` moves: pin-only changes ship with the next gem release rather than one release per CLI bump. It also covers how a gem patch can move your CLI and how to take a newer CLI before a release pins it. The pin-bump workflow keeps a single `[Unreleased]` entry for the pin.
|
|
20
|
+
- `CLIInstaller::PINNED_CLI_VERSION` moves from 2.1.285 to **2.1.288**, following the CLI the Python SDK bundles. `CLIInstaller.install_pinned` installs it. See the [Claude Code changelog](https://github.com/anthropics/claude-code/blob/main/CHANGELOG.md).
|
|
21
|
+
- **The Rails guide and both Rails examples turn off the CLI's per-project auto-memory** (`env: { 'CLAUDE_CODE_DISABLE_AUTO_MEMORY' => '1' }`). Every SDK session reads that memory and a `claude_code`-preset session writes it without a permission check, so in a multi-user app one user's "remember …" would reach every other user's session. The generated initializer only documents the switch: it carries the same line commented out, so **a newly generated app is not isolated until you uncomment it** (or set it per call). If you copied the examples, add the line; the value must be `'1'`. ([#158](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/158))
|
|
22
|
+
- **`docs/configuration.md` has a "Session Isolation" section.** Claude Code's per-project auto-memory is on in SDK sessions: every session loads the project's `MEMORY.md` index into its context (`setting_sources: []` does not prevent it), and a session on the `claude_code` preset also writes memory files, which the CLI allows without any permission setup. Servers and multi-tenant hosts should set `env: { 'CLAUDE_CODE_DISABLE_AUTO_MEMORY' => '1' }` (or `settings: { autoMemoryEnabled: false }`); a custom transport has to pass either one through to its CLI itself; `Client#context_usage[:memoryFiles]` shows what a session loaded. ([#155](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/155))
|
|
23
|
+
- **A requested sandbox that is not active now produces a warning.** `sandbox: { enabled: true }` does not guarantee a sandbox: when the CLI cannot start one (a Linux container without `bubblewrap` and `socat`, for example) it prints `⚠ Sandbox disabled: …` to its stderr and runs commands unsandboxed, which a host only saw through a `stderr:` callback. The SDK now repeats that line as a Ruby warning, prefixed `[claude-agent-sdk]`, once per session, when the `sandbox:` option enabled the sandbox. The default is unchanged; set `fail_if_unavailable: true` to make the CLI exit instead. ([#156](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/156))
|
|
24
|
+
- **`OTelObserver` now leaves a span for a session that fails before its first `InitMessage`.** A CLI that could not be found or started, or an `initialize` that failed or timed out, raised to the caller but exported no span at all (0.18.0's "crashed sessions now produce OTel traces with error status" only held once an `InitMessage` had arrived). `on_error` now emits a `claude_agent.session` span with the observer's default attributes, the prompt if one had been sent, the exception event and error status, and ends it at once. The span has no model or `session.id`. Nothing changes once a trace has started. If you count `claude_agent.session` spans, failed starts are now among them. ([#148](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/148))
|
|
25
|
+
- `docs/observability.md` no longer promises "standard `gen_ai.*` semantic conventions … any OTel backend". The attributes follow the Langfuse and OpenInference conventions plus a subset of OTel `gen_ai.*`; the page now lists every attribute, event and status `OTelObserver` sets, and how the `gen_ai.*` names differ from the OTel GenAI semantic conventions — notably that `gen_ai.usage.input_tokens` leaves cache tokens out, and that the inclusive count is `llm.token_count.prompt` on the session span. No attribute changed. ([#148](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/148))
|
|
26
|
+
- **`docs/rails.md` no longer says callbacks inherit the request's state.** A callback runs on a thread or fiber Rails never set up: `Current` attributes, `Time.zone`, log tags, the error context and the `connected_to` role / shard read as their defaults there (a write under `connected_to(shard:)` lands in the default shard), with or without `Railtie.callback_wrapper`; `I18n.locale` depends on the i18n version. The guide now has the table, a per-call recipe that carries the state across, the rule for composing your own wrapper with the Rails one, a section on transactions and the connection pool (a callback is outside the caller's transaction and uses its own connection), and a note that in development an agent run holds the reload lock. ([#158](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/158))
|
|
27
|
+
- `docs/configuration.md` says what the CLI does with an invalid sandbox value: it discards the whole `--settings` value, sandbox and `permissions` rules alike. The SDK does not surface this — `connect` succeeds and nothing appears on stderr; only the CLI's `get_settings` control response lists the error. That holds for every form, the typed classes included. ([#160](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/160))
|
|
28
|
+
- Disk listings (`list_sessions`, `get_session_info`) scan each transcript's head and tail windows as bytes; with non-ASCII text in a window this takes a fraction of the CPU time it did. Results are unchanged. ([#157](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/157))
|
|
29
|
+
- Development only: the gemspec's development dependency on Bundler is `>= 2.0` (was `~> 2.0`), so `bundle install` works in a checkout on Ruby 4.0, which ships Bundler 4. CI now runs the suite and RuboCop on Ruby 4.0, and a keyless smoke runs the pinned CLI on PRs that touch the installer, the transport, `Query` or the message parser; the API-key integration job shows as skipped instead of passed when the key is absent. Runtime dependencies are unchanged. ([#153](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/153))
|
|
30
|
+
|
|
31
|
+
### Fixed
|
|
32
|
+
- **A hook callback's Hash return value now means what the equivalent typed output means, whatever its key style.** Only five top-level keys were renamed before, and only as Symbols, so `{ hook_specific_output: { hook_event_name: 'PreToolUse', permission_decision: 'deny' } }` reached the CLI under keys it does not read: the decision was ignored and the tool ran. A String-keyed Hash (e.g. after `JSON.parse`) and a `SyncHookJSONOutput` holding a snake_case Hash failed the same way. The fields the typed output classes model are now accepted in snake_case or camelCase, as Symbols or Strings, at the top level and inside `hook_specific_output`; any other key is sent as written, and the keys inside `updated_input`, the tool outputs and a `PermissionRequest` `decision` are not renamed. **If a hook of yours returns snake_case keys, they now take effect.** When one Hash spells a field both ways the CLI's spelling is sent, and a Symbol and a String spelling the same key are written once (json 3.x used to fail the hook with `detected duplicate key`). ([#149](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/149))
|
|
33
|
+
- **A `sandbox:` Hash written in Ruby spelling is now applied.** The typed sandbox classes take snake_case attributes and write the camelCase keys the CLI reads, but a Hash was forwarded as written: `sandbox: { enabled: true, network: { denied_domains: ['evil.example'] }, filesystem: { deny_read: ['~/.aws'] } }` reached the CLI under keys it does not know, and the CLI ignored them without an error — the session ran with `network: {}` and `filesystem: {}`, no deny rule. `SandboxSettings.new(network: { denied_domains: [...] })` lost its rules the same way. The fields of `SandboxSettings`, `SandboxNetworkConfig` and `SandboxFilesystemConfig` are now accepted in snake_case or camelCase, as Symbols or Strings, at the top level and inside `network` / `filesystem`; any other key is sent as written. **If a sandbox Hash of yours has snake_case keys, they now take effect.** A snake_case key is renamed only when its value has the shape the CLI accepts for it (`true` / `false`, an Array of Strings, a port number from 0 to 65535); with any other value it is sent as written and stays without effect, as before — so the rename can never make the CLI discard your settings. When one Hash spells a field both ways the camelCase one is sent; a field holding `nil` is left out (the CLI rejects `null` there); a Symbol and a String spelling the same key are written once. A typed `SandboxNetworkConfig` / `SandboxFilesystemConfig` inside a `sandbox:` Hash is written as the Hash it stands for (it reached the CLI as its `#inspect` text, which made the CLI drop the sandbox). ([#160](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/160))
|
|
34
|
+
- **"Always allow" answers from `can_use_tool` now stick for whole-tool rules.** `PermissionUpdate#to_h` wrote `"ruleContent": null` for a rule without content and omitted a nil `destination`; the CLI accepts neither and drops the **whole** `updatedPermissions` array when one entry is malformed, so `PermissionResultAllow.new(updated_permissions: context.suggestions)` silently persisted nothing for the suggestions the CLI builds for `WebSearch` or MCP tools, and the callback was asked again on every call. `ruleContent` is now omitted when nil, and an update that has a `type` but no `destination` is sent to `'session'` (this run only; no settings file is written). ([#149](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/149))
|
|
35
|
+
- **`tools: 'Read,Grep'` is no longer ignored.** A String had no branch in the command builder, so no `--tools` flag was sent and the session got every built-in tool. It is now passed to `--tools` as written (the CLI's own comma-separated form). **If you pass `tools:` as a String, the session is now restricted to the tools it names.** ([#160](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/160))
|
|
36
|
+
- **`system_prompt`, `tools`, `output_format` and `plugins` Hashes accept a Symbol `type`**, like `thinking` and the MCP server configs already did. `tools: { type: :preset, preset: :claude_code }` sent the Hash's JSON text as a tool name and the session started with **no tools**; `system_prompt: { type: :custom, prompt: '…' }` (and `:file`, `:preset`) sent no flag, so the prompt and its options were dropped; `output_format: { type: :json_schema, schema: {…} }` made the CLI exit; `plugins: [{ type: :local, … }]` raised `Unsupported plugin type`. An `output_format` Hash with `type` and `schema` under different key styles silently turned structured output off; `schema` is now found under either. A Symbol-typed Hash means what the String-typed one means, including its check: `{ type: :custom }` without a `:prompt` String raises the same `ArgumentError`. ([#160](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/160))
|
|
37
|
+
- **Directory-scoped session APIs could read and modify another project's sessions.** For project paths over 200 characters, `list_sessions(directory: B)`, `get_session_messages` and `rename_session` / `tag_session` / `delete_session` / `fork_session` fell back to ANY project directory sharing the first 200 characters, so they could return or change the sessions of a sibling path A. In a directory found by that fallback, only sessions whose own transcript records the requested path as its top-level `cwd` are listed, read or modified (worktrees whose paths share such a directory are each listed). ([#157](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/157))
|
|
38
|
+
- **A relative CLI path could run a different binary than the one the SDK checked.** The version probe runs in the process's working directory but the CLI is spawned in `cwd:`, so `cli_path: 'bin/claude'`, or a `claude` found through a relative `PATH` entry (`bin`, `.`, an empty entry), was checked in one directory and executed in the other — whatever file sat at that path inside the directory the agent was pointed at. The transport now settles one absolute path and uses it for both: a relative `cli_path` is resolved against the process's working directory (a leading `~` is expanded), and a bare name is looked up on `PATH` by the SDK, with relative `PATH` entries resolved against the process's working directory. Discovery no longer runs `which`: the SDK searches the process's `PATH` for `claude` itself, so a `which` found through a relative `PATH` entry can neither run nor redirect the lookup (a host without a `which` program now finds `claude` on `PATH`; with no `PATH` at all, discovery searches the system directories, never the working directory). If you relied on a relative `cli_path` resolving inside `cwd:`, pass an absolute path. A subclass whose `#build_command` runs the CLI through another program (docker exec, ssh) still gets `cli_path` as given, since it names a file on the far side. ([#156](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/156))
|
|
39
|
+
- **`#inspect` no longer prints credentials held outside `env` and `headers`.** `ClaudeAgentOptions#inspect` (and `#to_s`, `pp`, string interpolation) now filters `settings` and `extra_args` the way it filters `env`: a Hash keeps its keys with `"[FILTERED]"` values, and a String `settings` (JSON or a file path) prints as `"[FILTERED]"`. `mcp_servers` given as a String (JSON or a file path) prints as `"[FILTERED]"` too. `McpStdioServerConfig#args` is filtered. The `url` of `McpHttpServerConfig` / `McpSSEServerConfig` prints as scheme, host and port only (`"https://mcp.example.com/[FILTERED]"`), since a token can sit in its userinfo, path or query. Raw Hash server configs are filtered the same way (`type`, `command` and the redacted `url` are shown; `args`, `env`, `headers` and any other key print as `"[FILTERED]"`): inside `mcp_servers`, where they used to rely on the nesting limit, and in `McpServerStatus#config`, where the CLI echoes each server's `headers`, `url` and `args` back in `mcp_status`. Display only: the objects are not modified and nothing sent to the CLI changes. ([#151](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/151))
|
|
40
|
+
- **A materialized resume directory preserved after a mirror failure now holds only `projects/`.** The cleanup removed four known files and left whatever else the CLI had written — including `backups/.claude.json.backup.<ts>`, a full copy of the seeded `.claude.json`, which can hold MCP header secrets. Every entry except `projects/` is now deleted. To do that safely the SDK first moves the directory into a fresh private one next to it (`claude-preserved-resume-*`), so **the preserved transcript is no longer at the temp dir's old path: the warning names the new one.** If what it moved is not the directory it created (the path had been replaced by a symlink or another directory), or it cannot be moved, nothing is deleted and the warning says the scrub was skipped and why; symlinks are never followed, permissions are repaired only on the directory that was checked, an entry that cannot be removed is named in the warning, and an interrupted scrub says which directory to remove once the transcript is imported. Calling `disconnect` again after a teardown that was interrupted while it preserved the directory no longer deletes it. ([#159](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/159))
|
|
41
|
+
- **`ClaudeAgentSDK::Railtie.callback_wrapper` no longer reports to `Rails.error`.** In production it ran callbacks inside `executor.wrap`, which reports whatever passes through it as an unhandled error: a message-block exception was reported from the callback thread with an empty context (and then skipped by the request / job layer as already reported), exceptions the SDK handles itself (hook, `can_use_tool`, SDK MCP tool, observer) were reported although the run continued, and — on Rails 7.2.3, 8.0.2 and later — so were the SDK's own cancellations under `callback_scheduling: :inline`. The wrapper now enters the executor with `run!` / `complete!` (same hooks, no report), so an exception that escapes a callback is reported once, by the layer that called the SDK, with its controller / job context. If you relied on those reports to see hook or tool failures, report them inside the callback (`Rails.error.report`). ([#158](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/158))
|
|
42
|
+
- **A callback that fails with `NotImplementedError`, `LoadError`, `SystemStackError` or `SecurityError` is answered like any other failing callback.** These are not `StandardError`s, so nothing rescued them when a hook, a `can_use_tool` callback, an SDK MCP tool, resource or prompt handler, or the `callback_wrapper` raised one: the CLI never got a response for that request, and the exception stopped the whole Async reactor, taking every other session and task on it down (`query()` raised the raw exception). Now hooks and `can_use_tool` get the error response, a tool handler's failure reaches the model as an `isError: true` result, and a resource or prompt handler gets the JSON-RPC `-32603` error, exactly as for a `RuntimeError`; the session carries on. `SdkMcpServer#call_tool` called directly returns the `isError` result for these exceptions instead of raising. `exit`, `Interrupt`, signals and cancellation behave as before, and `NoMemoryError` is still fatal. ([#150](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/150))
|
|
43
|
+
- **A callback failure whose message is not valid UTF-8 is answered.** When a hook or `can_use_tool` callback raised an exception whose message held invalid bytes (a multibyte character cut by `byteslice`, binary subprocess or HTTP output), building the error response raised `JSON::GeneratorError` and the CLI was never answered. On the process-exit path the same error replaced the `SystemExit` the SDK promises to re-raise: under `:inline` scheduling `exit` did not end the process. An `exit` or signal exception whose message was in an encoding that is not ASCII-compatible (UTF-16) failed the same way, with `Encoding::CompatibilityError`. The error text is now normalized first — invalid bytes become U+FFFD, text in another valid encoding is transcoded — and a response that still cannot be serialized is replaced by a fixed message, so the request is always answered and the original exception is the one re-raised. ([#150](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/150))
|
|
44
|
+
- **`query()` with a streamed (Enumerator) prompt no longer closes stdin right after writing a message.** With hooks, `can_use_tool` or SDK MCP servers, stdin could close before that message's turn had produced a frame, so the turn's hook, permission and SDK MCP requests failed with "Stream closed". It happened when the CLI's `idle` for the previous run and the next message became ready in the same reactor pass: `Query#end_run` stopped the between-turns ceiling task (which yields) before it marked the run ended, and the message joined the run that was about to end. The run is now marked ended first. ([#154](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/154))
|
|
45
|
+
- **A `Client` control method called from a fiber on another thread's reactor no longer breaks the session.** `interrupt`, `set_model`, `set_permission_mode`, `mcp_status`, … called through `Sync { client.interrupt }` on a request thread while the session runs on a background reactor, or from a `Sync` block inside a `:thread`-mode callback: on async 2.10–2.28 the response raised `FiberError: fiber called across threads` in the session's read loop, which ended the session and left the caller waiting for the control-request timeout (20 minutes by default); on async ≥ 2.29 the response could be missed, with the same wait. Such callers now wait the way plain threads already did. ([#154](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/154))
|
|
46
|
+
- **`receive_response` / `receive_messages` no longer hang after the CLI is gone.** After the CLI exited or crashed while a `Client` was connected, the first call raised the stream error (or returned the last turn), the second returned without messages, and every later call hung forever with no error and no timeout (from plain Ruby after the reactor had finished, async 2.10 raised `NoMethodError` instead). Every call after the end of the stream now returns at once; the stream error is still raised once. ([#154](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/154))
|
|
47
|
+
- **A deadline around a `Client` call is no longer swallowed while an observer runs.** With observers configured, a deadline around `Client#receive_response`, `#receive_messages`, `#query` or `#disconnect` (`task.with_timeout`, or `Timeout.timeout` inside a reactor) was silently dropped when it expired while an observer callback was still running: nothing was raised and the turn carried on, calling the message block after the deadline. Only what the observer (or its `callback_wrapper`) raises is contained now. With `callback_scheduling: :inline` the observer runs on the caller's own fiber, where such a deadline cannot be told from the observer's own failure, and it is still contained. ([#154](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/154))
|
|
48
|
+
- **`Client#disconnect`, and the cleanup of a failing `Client#connect`, always tear the session down.** When the call was interrupted while an observer's `on_close` / `on_error` was running — the caller's task stopped (`Async::Stop`), or an inline hook's cooperative timeout fired — the CLI process, the session's read loop and the materialized resume directory (with its credentials copy) were left behind. The teardown now always runs, and the interruption propagates after it. ([#154](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/154))
|
|
49
|
+
- **A `Client#disconnect` from another thread completes the CLI's graceful shutdown.** From an application thread, or from a tool handler, hook or `can_use_tool` callback under the default `callback_scheduling: :thread`, the close was handed to a transient task on the session's reactor; when the session had nothing else left to do the reactor wound down and stopped that task mid-teardown, so the CLI got SIGTERM instead of stdin EOF and its 5-second grace period (the time it has to finish its last session write), and `disconnect` returned before the child was reaped. The close now runs on a task the reactor waits for: such a `disconnect` takes as long as the teardown, like one made on the reactor. ([#161](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/161))
|
|
50
|
+
- **A callback's thread hop no longer returns before the callback has finished.** When an exception (`Async::Stop`, a timeout) had been raised into the waiting fiber just as the previous hop's thread ended, the stale wakeup resumed the next hop, which returned `nil` as its result; with a `timeout:` (session-store adapter calls) the same wakeup was reported as `timed out` although no time had passed. `FiberBoundary.invoke` now waits until the thread has really finished or the deadline has really passed. ([#154](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/154))
|
|
51
|
+
- An error raised by `ClaudeAgentSDK.query` / `.ask` from synchronous code (CLI not found, `ProcessError`, `ResultError`, an exception in your own block) was also logged by Async as `Task may have ended with unhandled exception.`, with the message and a backtrace, even when your code rescued it. The error is now only raised. Inside a reactor the same applied to failures before the first suspension, such as a transport that cannot connect. ([#154](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/154))
|
|
52
|
+
- **A `stderr:` callback that raised `NotImplementedError`, `LoadError` or `SystemStackError` could hang the session.** Only `StandardError` was contained, so those ended the thread that reads the CLI's stderr; once the CLI had written another 64 KiB of stderr it blocked for good. They are now handled like any other callback error: dropped, and the callback is called again for the next line. The same holds for a `debug_stderr:` sink and for the SDK's own sandbox warning when a custom `Warning.warn` or `$stderr` raises one of them. ([#156](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/156))
|
|
53
|
+
- **Store-backed resume now authenticates on macOS with a custom `CLAUDE_CONFIG_DIR`.** There the CLI keeps its OAuth credentials in the Keychain under `Claude Code-credentials-<first 8 hex of SHA-256(config dir)>` and writes no `.credentials.json`; the SDK only bridged the default config dir's entry, so the resumed subprocess reported "Not logged in" (and the failed attempt was mirrored into the store). The Keychain is now consulted for a custom config dir too — only when that directory has no `.credentials.json`, and never under `ANTHROPIC_API_KEY` / `CLAUDE_CODE_OAUTH_TOKEN`. The seeded copy still has the refresh token removed and mode `0600`. ([#159](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/159))
|
|
54
|
+
- **A mirror flush cancelled while it waited behind an in-flight append no longer loses its batch.** The batcher detached the pending entries before queueing on its lock, so a `#flush` whose task was stopped there (a timeout around the caller, `Task#stop`) dropped them: they never reached the store and no `MirrorErrorMessage` was produced. The buffer is now detached inside the lock, so those entries go out with the next flush; a frame that arrives while the final flush is still waiting is delivered rather than counted as dropped (Python [#1289](https://github.com/anthropics/claude-agent-sdk-python/pull/1289)). The mirror's retry backoff uses `Kernel#sleep` instead of the deprecated `Async::Task#sleep`. ([#159](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/159))
|
|
55
|
+
- **`get_session_messages` and `get_subagent_messages` (disk and `session_store:`) no longer drop the results of parallel tool calls.** The CLI parents each `tool_result` on the entry holding its own `tool_use`, so with several tool calls in one assistant turn only the last-written result lay on the path the readers walk; the others were silently missing, leaving `tool_use` blocks without a `tool_result`. They are now returned, after the turn's `tool_use` messages and before the result the conversation continued from; the chain's own result wins, so a call answered again after a rewind is not returned twice, and the result of a branch a rewind dropped is not brought back. Affected sessions return more messages than before, so `offset:`/`limit:` pages over them shift. ([#157](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/157))
|
|
56
|
+
- **Session reads, listings and mutations — other fixes** ([#157](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/157)):
|
|
57
|
+
- `get_session_messages` (disk and store) no longer returns `[]` for a session whose last entry is an unanswered meta injection (a slash-command or skill body, a stop-hook message, a system reminder written just before the session was closed).
|
|
58
|
+
- The message readers no longer raise `Encoding::CompatibilityError` under a non-UTF-8 locale (`LANG=C` / `LC_ALL=C`), nor on a transcript whose last line was cut inside a multibyte character or that holds a raw non-UTF-8 byte (a torn line is skipped; invalid bytes come back as U+FFFD); `import_session_to_store` no longer stops half-way on such a line. Under `LC_ALL=C` a non-ASCII `CLAUDE_CONFIG_DIR`, `directory: Dir.pwd` and a non-ASCII worktree path no longer raise or hide every worktree.
|
|
59
|
+
- `list_sessions(directory:)` no longer leaves out the directory's own sessions when it is a subdirectory of a repository with several git worktrees; worktree paths git reports in decomposed Unicode form are NFC-normalized.
|
|
60
|
+
- Project paths containing a character outside the BMP (an emoji, a CJK Extension B ideograph) map to the project directory the CLI creates (two hyphens per such character). **`project_key_for_directory` changes for affected paths**: store entries written under the old key by `import_session_to_store` or the store mutations no longer match (the transcript mirror never used that key).
|
|
61
|
+
- `rename_session`, `tag_session`, `fork_session` and `delete_session` no longer raise `Errno::ENOENT` when `directory:` names a removed project directory (a deleted worktree); a missing path is resolved as far as it exists, following symlinks whose target is gone and applying a `..` after a link to the link's target, as `os.path.realpath` does.
|
|
62
|
+
- `list_sessions` no longer returns `[]` when the config directory path contains `[` or `{`.
|
|
63
|
+
- Disk listings find a first prompt beyond the first 64 KiB of the transcript (a bounded scan of up to 1 MiB) and take `created_at` only from a top-level `timestamp`, as the store path does; `created_at` is no longer 1 ms low for about one ISO timestamp in eight. `docs/sessions.md` lists what the disk path still does not see.
|
|
64
|
+
- `fork_session` without `title:` names the fork after the title the listing shows for the source, on disk and with `session_store:` alike.
|
|
65
|
+
- `get_session_info(session_store:)` reports the adapter's `mtime` as `last_modified`, as `list_sessions(session_store:)` does; the store subagent readers skip non-String `list_subkeys` values; `rename_session` / `tag_session` raise `ArgumentError` for a title or tag that is not a usable String (`tag: false` used to clear the tag, only `nil` does; a binary String, as `File.binread` returns, is read as UTF-8 instead of failing later with a JSON or encoding error); `list_subagents` on disk returns each id once.
|
|
66
|
+
- An optional `SessionStore` method that raises `NotImplementedError` when called (a stub behind a delegating wrapper, an adapter declining at run time) is treated as not implemented — the documented fallback is taken and `run_session_store_conformance` skips its contracts — while a required `load` that raises still fails the resume.
|
|
67
|
+
- `docs/sessions.md`: rename / tag / fork are safe while the session's CLI runs; delete only sessions whose CLI has exited.
|
|
68
|
+
- **`CLIInstaller.install` no longer deadlocks when two fibers of one `Async` reactor install into the same directory.** The second fiber blocked the reactor thread in `flock` while the first, which held the lock, was waiting on the network inside the critical section, so neither returned; with the default `version: 'stable'` this happened even when nothing needed installing. A waiting installer now polls the lock (every 50 ms) instead of blocking its thread. Threads and separate processes were never affected, and mutual exclusion is unchanged. ([#152](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/152))
|
|
69
|
+
- **`CLIInstaller.install` / `install_pinned` no longer fail in a read-only install directory when the requested version is already installed.** In an image built as root and run as another user, or on a read-only root filesystem, a boot-time `install_pinned` raised `CLIInstallError` (`EACCES`) because the lock file could not be opened, although the binary was intact. When the lock file cannot be opened (`EACCES`, `EROFS`, `EPERM`), a concrete version that is installed and matches its recorded checksum and platform is now returned without the lock. A dist-tag (`'stable'` / `'latest'`), a different version or a damaged binary still raises there. ([#152](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/152))
|
|
70
|
+
- **`CLIInstaller` honors `HTTPS_PROXY` / `https_proxy`.** `Net::HTTP` only looks at `http_proxy` unless it is told otherwise, even for a TLS connection, so an environment that exported only `HTTPS_PROXY` was bypassed, and where direct egress is blocked the install timed out with no mention of the proxy. The proxy for each request (redirect hops included) is now resolved from the `https` URL and passed explicitly, with its credentials; `NO_PROXY` / `no_proxy` apply as before, and an environment that only sets `http_proxy` keeps working. `ALL_PROXY` is not read, and only `http://` proxy URLs are used. `docs/cli-installer.md` has a new "Proxies and custom CAs" section (`HTTPS_PROXY`, `NO_PROXY`, `SSL_CERT_FILE`). ([#152](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/152))
|
|
71
|
+
- **`CLIInstaller` fsyncs what it publishes.** The downloaded binary and `VERSION` are flushed to disk before they are renamed into place (the binary again after it is made executable, so its mode survives too), and the directory after it (best-effort). Previously a power loss shortly after an install could leave an empty or partial executable `claude` under the published name, which discovery kept selecting until the next `install`. ([#152](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/152))
|
|
72
|
+
- `CLIInstaller.install` with no `dir:` names the default directory (`vendor/claude`) in its error when the process's working directory no longer exists, instead of an empty path. `docs/cli-installer.md` states the locked sequence in the order the code uses (record `VERSION`, then place the binary), and that a failed first install never publishes a binary — it can leave the directory, its lock file and, after a failed final rename, a recorded `VERSION`. ([#152](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/152))
|
|
73
|
+
- **Shorthand tool schemas with `Array` / `Hash` parameters are advertised correctly.** `{ order_id: Integer, tags: Array }` told the model `tags` was a string, so it sent `"fragile,gift"` and the handler got a String; a model that did send an array had the call rejected. `Array` / `:array` now map to `array` and `Hash` / `:object` to `object`, in `tools/list` and in `tools/call` argument validation alike. Other shorthand values are unchanged. `docs/mcp-servers.md` lists the shorthand types. ([#152](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/152))
|
|
74
|
+
- **A tool handler that returns a non-Array `:content` gets a clear error.** `{ content: 'text' }`, a single block Hash, or a present `false` or `nil`, was forwarded unchanged; the CLI rejected it and told the model the server "returned a malformed result", so the text never arrived. It is now an in-band `isError` result naming the tool: `Tool 'x' must return :content as an Array of content blocks (got String)`. A result without a `:content` key keeps the existing message. Return the String itself, or `content: [{ type: 'text', text: ... }]`. ([#152](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/152))
|
|
75
|
+
- **`create_tool(annotations: { maxResultSizeChars: … }, meta: { … })` keeps the size hint.** An explicit `meta:` replaced the `_meta['anthropic/maxResultSizeChars']` entry derived from the annotation, so large results were truncated to a preview again. The two are now merged; a size key set in `meta:` wins. ([#152](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/152))
|
|
76
|
+
- **`OTelObserver` no longer counts an API response's token usage once per content block.** The CLI sends one `AssistantMessage` per content block, and each repeats the response's `message_id` and `usage`. The observer put that usage on every `claude_agent.generation` span, so a response with a thinking block and a tool call reported its input, cache-read and cache-creation tokens twice (N times for N blocks). The `gen_ai.usage.*` token attributes are now set on the first generation span of each `message_id` only. Span count, names and parentage are unchanged, and the session span was already correct. **Sums of `gen_ai.usage.*` over generation spans drop by the duplication factor.** `gen_ai.usage.output_tokens` on a generation span is still the snapshot taken when the response started; `docs/observability.md` now says so, and that the session span carries the authoritative totals. ([#148](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/148))
|
|
77
|
+
- `examples/advanced_hooks_example.rb` and `examples/lifecycle_hooks_example.rb` returned a `*HookSpecificOutput#to_h` as the whole hook output, which leaves `permissionDecision`, `additionalContext`, `retry` and `watchPaths` at the top level where the CLI does not read them — the example's "deny" did not deny. They now wrap the typed output in `SyncHookJSONOutput`. If you copied that pattern, wrap yours the same way (or return `{ hook_specific_output: … }`). ([#149](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/149))
|
|
78
|
+
- `agents:` accepts a Hash for an agent, as its signature says: `agents: { reviewer: { description: '…', prompt: '…' } }` used to raise `NoMethodError` at connect. The Hash is read like `AgentDefinition.new(hash)`, so a misspelled key raises the same `ArgumentError`. ([#149](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/149))
|
|
79
|
+
- `allowed_tools`, `disallowed_tools`, `add_dirs`, `extra_args`, `env` and `load_timeout_ms` can be set back to `nil` after construction (`options.dup_with(allowed_tools: nil)`, `options.extra_args = nil`), as their signatures say. The command builder, the transport and store-backed resume used to raise an anonymous `NoMethodError` at connect; they now read `nil` as the default. ([#149](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/149), [#156](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/156), [#159](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/159))
|
|
80
|
+
- The `sandbox:` option now replaces a `sandbox` section already present in `settings:` instead of being added beside it. Settings given as a JSON String, a file path or a String-keyed Hash produced a `--settings` value with the key twice: under json 3.x connect raised a raw `JSON::GeneratorError: detected duplicate key "sandbox"`, which made the documented `sandbox: false` override unusable; under json 2.x it only worked as long as the CLI kept the last duplicate. ([#149](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/149))
|
|
81
|
+
- Hooks registered for one event under both a String and a Symbol key (`{ 'PreToolUse' => [a], PreToolUse: [b] }`) are all registered, in the order written. The second key used to replace the first silently, so `a` never ran. ([#149](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/149))
|
|
82
|
+
- **`#[]` returns `nil` for a writer's name instead of raising.** `msg[:session_id=]`, `msg['sessionId=']` and `options[:env=]` called the setter without an argument (`ArgumentError: wrong number of arguments`); they now read as `nil`, like any other name that is not an attribute. ([#151](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/151))
|
|
83
|
+
- **`ClaudeAgentOptions` reports `'[]'` as an unknown option.** `ClaudeAgentOptions.new('[]' => 1)` raised `wrong number of arguments (given 1, expected 2)`; it now raises the usual `unknown ClaudeAgentOptions option: "[]"`. The keys `'='`, `'!'` and `'=='` used to resolve to `#==`, `#!=` and `#===` and were dropped without an error; they now raise the same `ArgumentError`. Setters you define on your own `ClaudeAgentOptions` subclass are still accepted. ([#151](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/151))
|
|
84
|
+
- **`Type#inspect` no longer raises on a value it cannot render.** A `BasicObject` attribute raised `NoMethodError` (`nil?`), and a String, Hash or Array subclass whose `#length` / `#size` raises took `#inspect` down with it — inside a logger or `puts`. Such a value now shows as `#<ClassName>` (`#<?>` for a `BasicObject`) and the rest of the object still prints. `Interrupt`, `SystemExit` and other non-`StandardError` exceptions are not rescued. ([#151](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/151))
|
|
85
|
+
- **`cli_path:` given as a `Pathname` failed at connect.** The signature has always allowed it, but the spawn raised `no implicit conversion of Pathname into String`. The transport now converts it once, before the version check and the spawn. ([#156](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/156))
|
|
86
|
+
- No more `Async::Task#sleep is deprecated` warnings under `ruby -w` from the transport: while it waited for the CLI to exit, or for the version check, it printed one every 50 ms. It now uses `Kernel#sleep`, which parks only the calling fiber on a reactor. ([#156](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/156))
|
|
87
|
+
- The Postgres reference adapter (`examples/session_stores/`) stores entries in a `json` column instead of `jsonb`, which rejects the JSON escape for U+0000: one transcript entry with a NUL character (binary tool output) failed the whole `INSERT` and the mirror dropped that batch. An existing table is not changed by `create_schema`; the README gives the migration (`ALTER TABLE … ALTER COLUMN entry TYPE json USING entry::json`). ([#159](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/159))
|
|
88
|
+
- **`.yardopts` is packaged in the gem.** rubydoc.info builds the API reference from the gem's own files; without it YARD ran with its defaults, so the reference listed every `@api private` internal (`Query`, `FiberBoundary`, `MessageParser`, …) next to the public API and did not render `CHANGELOG.md` or `UPGRADING-1.0.md`. Takes effect on rubydoc.info from this release on. ([#155](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/155))
|
|
89
|
+
- **Documentation that contradicted the code** ([#155](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/155)):
|
|
90
|
+
- `docs/types.md` lists every message and content-block class the SDK can yield (`ToolProgressMessage`, `AuthStatusMessage`, `ToolUseSummaryMessage`, `PromptSuggestionMessage`, `ServerToolUseBlock` and `ServerToolResultBlock` were missing), with a table of the system and progress messages and what `#data` holds; the `SandboxIgnoreViolations` row (removed in 0.12.0) is gone. `docs/errors.md` documents `CLIInstallError`, and that a control request the CLI rejects raises a plain `StandardError`, not a `ClaudeSDKError`.
|
|
91
|
+
- Hooks, custom tools and permission callbacks do not require `Client` (`docs/client.md`, the README and the bundled skill said they did); `query()` and `ask` have run all three for many releases.
|
|
92
|
+
- The custom-transport contract is stated once: `connect`, `write`, `read_messages`, `end_input` and `close` are required, `ready?` is optional. `docs/client.md` listed six methods and the bundled skill four (a transport written from the skill's list made `query()` hang). The YARD of `ClaudeAgentSDK::Transport` no longer calls it an internal API.
|
|
93
|
+
- README: links are absolute GitHub URLs (relative ones were 404 on rubydoc.info, and the banner was missing from the installed gem); the CLI install snippet uses `CLIInstaller.install_pinned` instead of the literal `2.1.220`; a new Authentication section says how the CLI authenticates and what a missing login looks like; the comparison table's Python column is corrected.
|
|
94
|
+
- The bundled skill's configure examples no longer put `ENV.fetch('ANTHROPIC_API_KEY')` into the default options (the CLI inherits the environment anyway, and the line made every boot without the key raise `KeyError`); the skill and `docs/options.md` say that a `CLAUDE_CLI_PATH` naming a missing file is skipped and discovery continues.
|
|
95
|
+
- Four clarifications, each checked against Claude Code 2.1.287: `sandbox: { enabled: true }` does not make the sandbox a requirement (set `fail_if_unavailable: true`; otherwise the CLI warns on stderr and runs unsandboxed); `setting_sources: []` does not stop the MCP servers of the logged-in claude.ai account (`strict_mcp_config: true` does); `Client#query(prompt, session_id:)` does not start a separate conversation; an explicit `tools:` list must include `'Skill'` for `skills:` to work. Sandbox settings travel inside `--settings`, not a `--sandbox` flag.
|
|
96
|
+
- The `Client` examples in the guides and the `Client` YARD use `Client.open` (the `connect` … `disconnect` shape they showed leaves the session open when the block raises).
|
|
97
|
+
- `.claude-plugin/marketplace.json` no longer declares a version for the plugin (it said `0.13.1`); `SECURITY.md` states the supported versions for 1.x; `examples/message_types_example.rb` handles all 28 typed message classes.
|
|
98
|
+
- In the pages other PRs of this batch own: the documented Gemfile lines for the OpenTelemetry setup list the `base64` gem, which is no longer a default gem on Ruby 3.4 (`docs/observability.md`, [#148](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/148)); `docs/cli-installer.md` says an unusable `CLAUDE_CLI_PATH` is skipped without a warning and discovery continues, instead of "no discovery at all" ([#156](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/156)); `docs/rails.md` says hooks and custom tools work with `query` too ([#158](https://github.com/ya-luotao/claude-agent-sdk-ruby/pull/158)).
|
|
99
|
+
|
|
10
100
|
## [1.1.0] - 2026-09-30
|
|
11
101
|
|
|
12
102
|
Syncs with Python SDK 0.2.162. Additive only: one new option and a fix to when `query()` closes stdin.
|
data/README.md
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-

|
|
1
|
+

|
|
2
2
|
|
|
3
3
|
# Claude Agent SDK for Ruby
|
|
4
4
|
|
|
@@ -6,17 +6,17 @@
|
|
|
6
6
|
[](https://github.com/ya-luotao/claude-agent-sdk-ruby/actions/workflows/ci.yml)
|
|
7
7
|
[](https://www.ruby-lang.org/)
|
|
8
8
|
[](https://rubydoc.info/gems/claude-agent-sdk)
|
|
9
|
-
[](LICENSE)
|
|
9
|
+
[](https://github.com/ya-luotao/claude-agent-sdk-ruby/blob/main/LICENSE)
|
|
10
10
|
|
|
11
11
|
A Ruby SDK for the [Claude Code](https://docs.claude.com/en/docs/claude-code-overview) agent runtime, built for running agents in production Ruby and Rails apps. It has the same capabilities as the official [TypeScript](https://github.com/anthropics/claude-agent-sdk-typescript) and [Python](https://github.com/anthropics/claude-agent-sdk-python) SDKs, plus what a Rails deploy needs around them: a generator and CLI-vendoring rake task, callbacks that are safe to touch ActiveRecord from, a pinned CLI binary, built-in OpenTelemetry tracing, and transcript mirroring to your own storage.
|
|
12
12
|
|
|
13
|
-
> **Unofficial and community-maintained.** This project is not affiliated with or supported by Anthropic. It tracks the official SDKs release by release; see the [CHANGELOG](CHANGELOG.md) for the currently synced version.
|
|
13
|
+
> **Unofficial and community-maintained.** This project is not affiliated with or supported by Anthropic. It tracks the official SDKs release by release; see the [CHANGELOG](https://github.com/ya-luotao/claude-agent-sdk-ruby/blob/main/CHANGELOG.md) for the currently synced version.
|
|
14
14
|
|
|
15
|
-
> **Upgrading from 0.x?** 1.0 raises on unknown keys, limits `#[]` to attributes and adds `SessionStoreError`. [UPGRADING-1.0.md](UPGRADING-1.0.md) has the checklist.
|
|
15
|
+
> **Upgrading from 0.x?** 1.0 raises on unknown keys, limits `#[]` to attributes and adds `SessionStoreError`. [UPGRADING-1.0.md](https://github.com/ya-luotao/claude-agent-sdk-ruby/blob/main/UPGRADING-1.0.md) has the checklist.
|
|
16
16
|
|
|
17
17
|
## Highlights
|
|
18
18
|
|
|
19
|
-
- **Rails integration.** `bin/rails generate claude_agent_sdk:install` writes the initializer and `bin/rails claude_agent_sdk:install_cli` vendors the CLI; [docs/rails.md](docs/rails.md) covers jobs, ActionCable streaming, session resumption, and solid_queue fiber workers (`callback_scheduling: :inline`).
|
|
19
|
+
- **Rails integration.** `bin/rails generate claude_agent_sdk:install` writes the initializer and `bin/rails claude_agent_sdk:install_cli` vendors the CLI; [docs/rails.md](https://github.com/ya-luotao/claude-agent-sdk-ruby/blob/main/docs/rails.md) covers jobs, ActionCable streaming, session resumption, and solid_queue fiber workers (`callback_scheduling: :inline`).
|
|
20
20
|
- **Callbacks that are safe around ActiveRecord.** Tool handlers, hooks, permission callbacks, and message blocks run on a plain thread by default, outside the SDK's fiber scheduler, so thread-keyed libraries (ActiveRecord, `pg`, per-thread caches) behave as they do everywhere else in your app. `ClaudeAgentSDK::Railtie.callback_wrapper` runs them in the Rails executor so connections go back to the pool, without deadlocking development code reloading.
|
|
21
21
|
- **Hermetic deploys.** `CLIInstaller` vendors a checksum-verified CLI binary, pinned to the version each gem release is tested with, so production never depends on a global `npm install`.
|
|
22
22
|
- **Built-in OpenTelemetry observer** with Langfuse support; no third-party instrumentation library required.
|
|
@@ -39,14 +39,25 @@ Then `bundle install`, or install directly with `gem install claude-agent-sdk`.
|
|
|
39
39
|
**Prerequisites**
|
|
40
40
|
|
|
41
41
|
- Ruby 3.2 or newer
|
|
42
|
+
- Credentials for Claude Code: `ANTHROPIC_API_KEY`, `CLAUDE_CODE_OAUTH_TOKEN`, or a login the CLI has already stored (see [Authentication](#authentication))
|
|
42
43
|
- Claude Code CLI 2.0.0 or newer, either installed globally (`npm install -g @anthropic-ai/claude-code`) or vendored with `CLIInstaller`:
|
|
43
44
|
|
|
44
45
|
```ruby
|
|
45
|
-
# bin/setup or a cached Docker layer
|
|
46
|
-
ClaudeAgentSDK::CLIInstaller.
|
|
46
|
+
# bin/setup or a cached Docker layer: the CLI version this gem release was tested with
|
|
47
|
+
ClaudeAgentSDK::CLIInstaller.install_pinned # => "/app/vendor/claude/claude"
|
|
47
48
|
```
|
|
48
49
|
|
|
49
|
-
The vendored binary is found ahead of `PATH`, installs are idempotent and concurrency-safe, and a failed upgrade never breaks a working install. See [docs/cli-installer.md](docs/cli-installer.md) for the full behaviour, supported platforms, and the CLI discovery order.
|
|
50
|
+
`install_pinned` installs `CLIInstaller::PINNED_CLI_VERSION`, so upgrading the gem carries the CLI forward with it; `CLIInstaller.install(version: 'x.y.z')` pins a version of your own. The vendored binary is found ahead of `PATH`, installs are idempotent and concurrency-safe, and a failed upgrade never breaks a working install. See [docs/cli-installer.md](https://github.com/ya-luotao/claude-agent-sdk-ruby/blob/main/docs/cli-installer.md) for the full behaviour, supported platforms, and the CLI discovery order.
|
|
51
|
+
|
|
52
|
+
### Authentication
|
|
53
|
+
|
|
54
|
+
The SDK holds no credentials of its own. The `claude` process it starts authenticates the way Claude Code does, with one of:
|
|
55
|
+
|
|
56
|
+
- `ANTHROPIC_API_KEY`, in the environment of your Ruby process (the CLI inherits it) or per session with `ClaudeAgentOptions.new(env: { 'ANTHROPIC_API_KEY' => key })`
|
|
57
|
+
- `CLAUDE_CODE_OAUTH_TOKEN`, a long-lived token for a Claude subscription (`claude setup-token` creates one), set the same way
|
|
58
|
+
- a login the CLI has already stored for the user your process runs as (`claude auth login`)
|
|
59
|
+
|
|
60
|
+
A machine with none of them, such as a fresh container or a CI runner, does not fail at startup. The first prompt comes back as an `AssistantMessage` whose `error` is `'authentication_failed'` (its text is "Not logged in · Please run /login", a command an SDK host cannot run), followed by a `ResultMessage` with `is_error` set. `query()` and `ask` then raise `ResultError` with `terminal_reason == 'api_error'`; a `Client` session stays open, so check the result's `is_error` there. A key or token the API rejects ends the same way, with `api_error_status` 401, but only after the CLI has retried: watch for `APIRetryMessage` (ten of them over about three minutes when tested) rather than waiting for the error. [docs/errors.md](https://github.com/ya-luotao/claude-agent-sdk-ruby/blob/main/docs/errors.md) shows how to handle both.
|
|
50
61
|
|
|
51
62
|
### Rails in a minute
|
|
52
63
|
|
|
@@ -70,7 +81,7 @@ class SummarizeTicketJob < ApplicationJob
|
|
|
70
81
|
end
|
|
71
82
|
```
|
|
72
83
|
|
|
73
|
-
The block runs on a plain thread, so ActiveRecord calls inside it just work. [docs/rails.md](docs/rails.md) continues with multi-turn sessions, ActionCable streaming, and fiber workers.
|
|
84
|
+
The block runs on a plain thread, so ActiveRecord calls inside it just work. [docs/rails.md](https://github.com/ya-luotao/claude-agent-sdk-ruby/blob/main/docs/rails.md) continues with multi-turn sessions, ActionCable streaming, and fiber workers.
|
|
74
85
|
|
|
75
86
|
## Quick Start
|
|
76
87
|
|
|
@@ -89,7 +100,7 @@ end
|
|
|
89
100
|
puts result
|
|
90
101
|
```
|
|
91
102
|
|
|
92
|
-
It raises the same errors as `query()` (see [docs/errors.md](docs/errors.md)), plus `CLIConnectionError` if the stream ends without a result.
|
|
103
|
+
It raises the same errors as `query()` (see [docs/errors.md](https://github.com/ya-luotao/claude-agent-sdk-ruby/blob/main/docs/errors.md)), plus `CLIConnectionError` if the stream ends without a result.
|
|
93
104
|
|
|
94
105
|
### `query()` — one-shot and streaming
|
|
95
106
|
|
|
@@ -121,7 +132,7 @@ end
|
|
|
121
132
|
|
|
122
133
|
### `Client` — bidirectional sessions
|
|
123
134
|
|
|
124
|
-
`Client` keeps a session open so you can send follow-up queries, interrupt, switch
|
|
135
|
+
`Client` keeps a session open so you can send follow-up queries, interrupt, and switch the model or the permission mode mid-session. (Hooks, permission callbacks and custom tools are not a reason to choose it: they work with `query()` and `ask` too.) `Client.open` connects, yields the client, and always disconnects when the block exits, even on an exception. It returns the block's value.
|
|
125
136
|
|
|
126
137
|
```ruby
|
|
127
138
|
require 'claude_agent_sdk'
|
|
@@ -148,7 +159,7 @@ ensure
|
|
|
148
159
|
end
|
|
149
160
|
```
|
|
150
161
|
|
|
151
|
-
See [docs/client.md](docs/client.md) for `interrupt`, mid-session model and permission switching, MCP status, and custom transports.
|
|
162
|
+
See [docs/client.md](https://github.com/ya-luotao/claude-agent-sdk-ruby/blob/main/docs/client.md) for `interrupt`, mid-session model and permission switching, MCP status, and custom transports.
|
|
152
163
|
|
|
153
164
|
### Custom tools (SDK MCP servers)
|
|
154
165
|
|
|
@@ -167,7 +178,7 @@ options = ClaudeAgentSDK::ClaudeAgentOptions.new(
|
|
|
167
178
|
)
|
|
168
179
|
```
|
|
169
180
|
|
|
170
|
-
A String return is sent to Claude as a single text block. Return a Hash instead (`{ content: [...], is_error: true }`) to flag an error, attach `structured_content:`, or send several content blocks or images. Arguments are validated against the tool's JSON Schema before your handler runs, and handler exceptions are reported back to the model in-band so it can self-correct. See [docs/mcp-servers.md](docs/mcp-servers.md) for resources, prompts, mixed SDK + external servers, and schema details.
|
|
181
|
+
A String return is sent to Claude as a single text block. Return a Hash instead (`{ content: [...], is_error: true }`) to flag an error, attach `structured_content:`, or send several content blocks or images. Arguments are validated against the tool's JSON Schema before your handler runs, and handler exceptions are reported back to the model in-band so it can self-correct. See [docs/mcp-servers.md](https://github.com/ya-luotao/claude-agent-sdk-ruby/blob/main/docs/mcp-servers.md) for resources, prompts, mixed SDK + external servers, and schema details.
|
|
171
182
|
|
|
172
183
|
### Hooks and permission callbacks
|
|
173
184
|
|
|
@@ -180,23 +191,24 @@ options = ClaudeAgentSDK::ClaudeAgentOptions.new(
|
|
|
180
191
|
)
|
|
181
192
|
```
|
|
182
193
|
|
|
183
|
-
See [docs/hooks-and-permissions.md](docs/hooks-and-permissions.md) for the full event list and worked examples.
|
|
194
|
+
See [docs/hooks-and-permissions.md](https://github.com/ya-luotao/claude-agent-sdk-ruby/blob/main/docs/hooks-and-permissions.md) for the full event list and worked examples.
|
|
184
195
|
|
|
185
196
|
## Documentation
|
|
186
197
|
|
|
187
198
|
| Topic | Guide |
|
|
188
199
|
|-------|-------|
|
|
189
|
-
| `Client` advanced features and custom transports | [docs/client.md](docs/client.md) |
|
|
190
|
-
| SDK MCP servers: tools, resources, prompts, schema compatibility | [docs/mcp-servers.md](docs/mcp-servers.md) |
|
|
191
|
-
| All hook events, typed inputs, permission callbacks | [docs/hooks-and-permissions.md](docs/hooks-and-permissions.md) |
|
|
192
|
-
| Structured output, thinking, budget, fallback and advisor models, sandbox, bare mode, checkpointing | [docs/configuration.md](docs/configuration.md) |
|
|
193
|
-
|
|
|
194
|
-
|
|
|
195
|
-
|
|
|
196
|
-
|
|
|
197
|
-
|
|
|
198
|
-
|
|
|
199
|
-
|
|
|
200
|
+
| `Client` advanced features and custom transports | [docs/client.md](https://github.com/ya-luotao/claude-agent-sdk-ruby/blob/main/docs/client.md) |
|
|
201
|
+
| SDK MCP servers: tools, resources, prompts, schema compatibility | [docs/mcp-servers.md](https://github.com/ya-luotao/claude-agent-sdk-ruby/blob/main/docs/mcp-servers.md) |
|
|
202
|
+
| All hook events, typed inputs, permission callbacks | [docs/hooks-and-permissions.md](https://github.com/ya-luotao/claude-agent-sdk-ruby/blob/main/docs/hooks-and-permissions.md) |
|
|
203
|
+
| Structured output, thinking, budget, fallback and advisor models, sandbox, bare mode, session isolation, checkpointing | [docs/configuration.md](https://github.com/ya-luotao/claude-agent-sdk-ruby/blob/main/docs/configuration.md) |
|
|
204
|
+
| Every `ClaudeAgentOptions` attribute: type, default, and the CLI flag or protocol field it becomes; environment variables | [docs/options.md](https://github.com/ya-luotao/claude-agent-sdk-ruby/blob/main/docs/options.md) |
|
|
205
|
+
| Session listing, reading, renaming, tagging, forking, resume-at-message | [docs/sessions.md](https://github.com/ya-luotao/claude-agent-sdk-ruby/blob/main/docs/sessions.md) |
|
|
206
|
+
| Subagent capabilities, event contracts, and minimal example | [docs/subagents.md](https://github.com/ya-luotao/claude-agent-sdk-ruby/blob/main/docs/subagents.md) |
|
|
207
|
+
| OpenTelemetry tracing, Langfuse, custom observers | [docs/observability.md](https://github.com/ya-luotao/claude-agent-sdk-ruby/blob/main/docs/observability.md) |
|
|
208
|
+
| Rails: generator, `install_cli` task, callback wrapper, fiber safety, solid_queue fiber workers, ActionCable, jobs | [docs/rails.md](https://github.com/ya-luotao/claude-agent-sdk-ruby/blob/main/docs/rails.md) |
|
|
209
|
+
| Vendoring a pinned CLI binary and CLI discovery order | [docs/cli-installer.md](https://github.com/ya-luotao/claude-agent-sdk-ruby/blob/main/docs/cli-installer.md) |
|
|
210
|
+
| Hash-key rule, attribute access, and the message, content block, and configuration type reference | [docs/types.md](https://github.com/ya-luotao/claude-agent-sdk-ruby/blob/main/docs/types.md) |
|
|
211
|
+
| Error handling, exception hierarchy, timeouts | [docs/errors.md](https://github.com/ya-luotao/claude-agent-sdk-ruby/blob/main/docs/errors.md) |
|
|
200
212
|
|
|
201
213
|
API reference: [rubydoc.info/gems/claude-agent-sdk](https://rubydoc.info/gems/claude-agent-sdk). Available built-in tools: [Claude Code documentation](https://docs.anthropic.com/en/docs/claude-code/settings#tools-available-to-claude).
|
|
202
214
|
|
|
@@ -223,18 +235,18 @@ All three SDKs drive the same CLI over the same protocol, so capabilities line u
|
|
|
223
235
|
| Bidirectional `Client` | ✅ | ✅ | ✅ |
|
|
224
236
|
| Streaming input | `AsyncIterable` | `AsyncIterable` | `Enumerator` |
|
|
225
237
|
| Custom tools (SDK MCP servers) | `tool()` | `@tool` decorator | `create_tool` block |
|
|
226
|
-
| Hooks (all 27 events) | ✅ |
|
|
238
|
+
| Hooks (all 27 events) | ✅ | 10 typed, the rest by name | ✅ |
|
|
227
239
|
| Permission callbacks | ✅ | ✅ | ✅ |
|
|
228
240
|
| Structured output | ✅ | ✅ | ✅ |
|
|
229
241
|
| All 28 message types | ✅ | partial | ✅ |
|
|
230
242
|
| [Sandbox](https://github.com/anthropic-experimental/sandbox-runtime) settings | ✅ | partial | ✅ |
|
|
231
|
-
| Bare mode (`--bare`) | ✅ |
|
|
243
|
+
| Bare mode (`--bare`) | ✅ | via `extra_args` | ✅ |
|
|
232
244
|
| File checkpointing & rewind | ✅ | ✅ | ✅ |
|
|
233
245
|
| Session browsing & mutations | ✅ | ✅ | ✅ |
|
|
234
246
|
| Programmatic subagents | ✅ | ✅ | ✅ |
|
|
235
247
|
| CLI binary | bundled | bundled | vendored on demand (`CLIInstaller`) |
|
|
236
248
|
| Observability (OTel / Langfuse) | via [Arize](https://github.com/Arize-ai/openinference) | — | ✅ built-in |
|
|
237
|
-
| Custom transport (pluggable I/O) | — |
|
|
249
|
+
| Custom transport (pluggable I/O) | — | ✅ | ✅ |
|
|
238
250
|
| Rails integration | — | — | ✅ |
|
|
239
251
|
|
|
240
252
|
Types are plain Ruby classes with `attr_accessor` and keyword arguments, mirroring the field names of the TypeScript Zod schemas and Python dataclasses; there is no runtime type checking.
|
|
@@ -260,12 +272,12 @@ RUN_INTEGRATION=1 bundle exec rspec # also run the real-CLI integration suite (
|
|
|
260
272
|
BUNDLE_GEMFILE=gemfiles/rails_8.gemfile bundle exec rspec --options spec/rails/.rspec # Rails integration specs
|
|
261
273
|
```
|
|
262
274
|
|
|
263
|
-
CI runs the suite and RuboCop on Ruby 3.2, 3.3,
|
|
275
|
+
CI runs the suite and RuboCop on Ruby 3.2, 3.3, 3.4 and 4.0 on Linux, the suite on macOS, and the Rails specs against Rails 7.1 and 8, validates the RBS signatures and runs the suite under RBS runtime type checking. Weekly, and on PRs that touch the installer, the transport, `Query` or the message parser, it runs a keyless smoke test against the pinned CLI, and the integration suite as well when the repository has an API key. The gem ships RBS signatures for its public API in `sig/`, which Steep and other RBS tools pick up through `rbs collection`. See [CONTRIBUTING.md](https://github.com/ya-luotao/claude-agent-sdk-ruby/blob/main/CONTRIBUTING.md) for the development setup and [spec/README.md](https://github.com/ya-luotao/claude-agent-sdk-ruby/blob/main/spec/README.md) for the test layout.
|
|
264
276
|
|
|
265
277
|
## Contributing
|
|
266
278
|
|
|
267
|
-
Bug reports and pull requests are welcome on [GitHub](https://github.com/ya-luotao/claude-agent-sdk-ruby/issues). Please include a failing spec with bug reports where possible, and keep pull requests focused on one change; [CONTRIBUTING.md](https://github.com/ya-luotao/claude-agent-sdk-ruby/blob/main/CONTRIBUTING.md) has the details. Report security vulnerabilities privately, as described in [SECURITY.md](https://github.com/ya-luotao/claude-agent-sdk-ruby/blob/main/SECURITY.md). Releases follow [Semantic Versioning](https://semver.org/) and are recorded in the [CHANGELOG](CHANGELOG.md).
|
|
279
|
+
Bug reports and pull requests are welcome on [GitHub](https://github.com/ya-luotao/claude-agent-sdk-ruby/issues). Please include a failing spec with bug reports where possible, and keep pull requests focused on one change; [CONTRIBUTING.md](https://github.com/ya-luotao/claude-agent-sdk-ruby/blob/main/CONTRIBUTING.md) has the details. Report security vulnerabilities privately, as described in [SECURITY.md](https://github.com/ya-luotao/claude-agent-sdk-ruby/blob/main/SECURITY.md). Releases follow [Semantic Versioning](https://semver.org/) and are recorded in the [CHANGELOG](https://github.com/ya-luotao/claude-agent-sdk-ruby/blob/main/CHANGELOG.md).
|
|
268
280
|
|
|
269
281
|
## License
|
|
270
282
|
|
|
271
|
-
Released under the [MIT License](LICENSE).
|
|
283
|
+
Released under the [MIT License](https://github.com/ya-luotao/claude-agent-sdk-ruby/blob/main/LICENSE).
|
data/docs/cli-installer.md
CHANGED
|
@@ -27,11 +27,20 @@ ClaudeAgentSDK::CLIInstaller.installed_path
|
|
|
27
27
|
`install` is idempotent and safe to run concurrently, so it fits `bin/setup`, a cached Docker layer, and every process of a multi-process boot:
|
|
28
28
|
|
|
29
29
|
- The install directory's `VERSION` file records the installed version, verified SHA-256, and target platform (OS, architecture, libc). The shortcut re-hashes the vendored binary (~0.1s for the real 245MB binary) and only skips the download when all three match — a truncated binary or a cache copied from another platform is reinstalled instead of trusted. It makes **no network request**, so same-platform repeat boots work offline — with a pinned concrete version; `'stable'`/`'latest'` must always re-resolve through the endpoint, which is one more reason to pin in production. Older one- or two-line metadata lacks a platform and requires one online reinstall to migrate; subsequent pinned installs work offline again.
|
|
30
|
-
- An exclusive `flock` on `<dir>/.install.lock` covers the whole check → download →
|
|
30
|
+
- An exclusive `flock` on `<dir>/.install.lock` covers the whole check → download → record → place sequence, so parallel installs into one directory don't race — whether they come from separate processes, threads, or fibers of one `Async` reactor (a waiting installer polls the lock rather than blocking its thread on it); the loser simply observes the finished install.
|
|
31
|
+
- The shortcut also works where the running process cannot write the install directory: an image built as root and run as another user, or a read-only root filesystem. `install` cannot open its lock file there (`EACCES`, `EROFS` or `EPERM`), and still returns the binary when the request is a concrete version that is already installed and intact — the same `VERSION` and SHA-256 check, without the lock. Anything that would need a write raises `CLIInstallError` as before: a dist-tag (`'stable'` / `'latest'`, which has to be resolved and may have to be installed), a different version, a damaged binary, an empty directory.
|
|
31
32
|
|
|
32
33
|
Failures (unsupported platform, invalid version, HTTP error, response-size cap, oversized download, checksum mismatch, filesystem errors) raise `ClaudeAgentSDK::CLIInstallError`.
|
|
33
34
|
|
|
34
|
-
**A failed install never breaks a working one.** The new binary is downloaded to a temp file, checksum-verified and recorded, and only then renamed into place — the rename is the last step, and nothing can fail after it. So a failed upgrade leaves the previously installed binary intact and runnable (the SDK keeps working), and the next `install` redoes it cleanly. A first install that fails
|
|
35
|
+
**A failed install never breaks a working one.** The new binary is downloaded to a temp file, checksum-verified and recorded, and only then renamed into place — the rename is the last step, and nothing can fail after it. So a failed upgrade leaves the previously installed binary intact and runnable (the SDK keeps working), and the next `install` redoes it cleanly. The binary and `VERSION` are also flushed to disk (`fsync`) before they are renamed into place, so a machine that loses power right after an install comes back with a complete binary or with the previous state, not with a truncated file under the published name. A first install that fails never publishes a binary. It can leave the install directory and its `.install.lock` behind and — when the step that failed is the last one, the rename — a `VERSION` that already records the version. Nothing trusts that file on its own: discovery finds no binary there and moves on, and the next `install` redoes it cleanly.
|
|
36
|
+
|
|
37
|
+
## When the pin moves
|
|
38
|
+
|
|
39
|
+
`PINNED_CLI_VERSION` follows the CLI the Python SDK bundles. A bot PR moves it on `main`, usually within a few days, but the new pin reaches rubygems only with the next gem release: pin-only changes are batched rather than released one by one. A CLI security fix, or an SDK change that needs a newer CLI, gets a release sooner. Each release's CHANGELOG says when the pin moved. So `install_pinned` can trail the newest CLI by days. That is the price of installing the version the gem was tested with.
|
|
40
|
+
|
|
41
|
+
A gem upgrade can therefore move your CLI, even in a patch release. If Dependabot merges gem patches for you, check the CHANGELOG for a `PINNED_CLI_VERSION` entry: a new CLI can behave differently even where the SDK's API does not change.
|
|
42
|
+
|
|
43
|
+
To run a newer CLI before a gem release pins it, pin it yourself with `install(version: 'x.y.z')`, or `CLAUDE_CLI_VERSION=x.y.z` for the rake task and the `bin/setup` example below. Go back to `install_pinned` once a gem release catches up. `'stable'` and `'latest'` follow the newest CLI automatically, but they are not pins: a rebuild can pick up a different version.
|
|
35
44
|
|
|
36
45
|
## Where `vendor/claude` is
|
|
37
46
|
|
|
@@ -88,6 +97,17 @@ RUN bin/rails claude_agent_sdk:install_cli
|
|
|
88
97
|
|
|
89
98
|
The variable is deliberately not rake's conventional `VERSION`, which Rails' `db:migrate` uses and build environments often export for an app version or git SHA. An empty `CLAUDE_CLI_VERSION` means the gem's pin.
|
|
90
99
|
|
|
100
|
+
## Proxies and custom CAs
|
|
101
|
+
|
|
102
|
+
The installer downloads over HTTPS with Ruby's `Net::HTTP` and reads the usual environment variables:
|
|
103
|
+
|
|
104
|
+
- **`HTTPS_PROXY`** (or `https_proxy`) names the proxy to download through, as an `http://` URL: `HTTPS_PROXY=http://proxy.corp.example:3128`, with `user:password@` in front of the host for an authenticating proxy (percent-encode special characters). The download is tunnelled through it with `CONNECT`, so TLS still ends at the release endpoint.
|
|
105
|
+
- **`NO_PROXY`** (or `no_proxy`) lists the hosts, domain suffixes and IP ranges to reach directly, separated by commas.
|
|
106
|
+
- With neither spelling of `HTTPS_PROXY` set, `Net::HTTP`'s own default applies: it goes through `http_proxy` when that is set.
|
|
107
|
+
- **`SSL_CERT_FILE`** points OpenSSL at another CA bundle, which is what a TLS-inspecting proxy needs. Set it in the environment the process starts with. The server certificate is always verified; there is no switch to turn that off.
|
|
108
|
+
|
|
109
|
+
This is not everything `curl` understands. `ALL_PROXY` is not read, and only an `http://` proxy URL is used: a value without a scheme (`proxy.corp.example:3128`), a `socks5://` proxy or an `https://` one is ignored.
|
|
110
|
+
|
|
91
111
|
## Supported platforms
|
|
92
112
|
|
|
93
113
|
`darwin-arm64`, `darwin-x64` (Rosetta 2 gets the arm64 build), `linux-x64`, `linux-arm64`, and the `-musl` variants. Windows is not supported.
|
|
@@ -96,7 +116,9 @@ The variable is deliberately not rake's conventional `VERSION`, which Rails' `db
|
|
|
96
116
|
|
|
97
117
|
With no explicit `cli_path:` in `ClaudeAgentOptions`, the transport probes in this order:
|
|
98
118
|
|
|
99
|
-
1. `CLAUDE_CLI_PATH` —
|
|
119
|
+
1. `CLAUDE_CLI_PATH` — a path to the CLI, used when it names an executable regular file (a relative value is resolved against the process's working directory, not `cwd:`). A value that names anything else — a missing file, a directory, a file that is not executable — is skipped without a warning, and discovery continues with the steps below
|
|
100
120
|
2. The vendored binary (`CLIInstaller.installed_path`, i.e. `vendor/claude` under `CLIInstaller.root` or the working directory — see [above](#where-vendorclaude-is)) — deliberately ahead of `PATH`, so a pinned install beats whatever is installed globally
|
|
101
|
-
3. `which
|
|
121
|
+
3. `claude` on the process's `PATH` — the first executable regular file of that name. The SDK searches `PATH` itself and does not run `which`. A `PATH` passed in `env:` belongs to the session and is not searched here. When the process has no `PATH` at all, the system directories are searched (`/usr/local/bin`, `/usr/bin`, `/bin`), as Ruby's own command lookup would — never the working directory
|
|
102
122
|
4. Common install locations (`~/.claude/local/claude`, `/usr/local/bin/claude`, …) — only an executable regular file counts, and the `~` ones are skipped when there is no usable home directory (HOME unset with no passwd entry, or a non-absolute HOME)
|
|
123
|
+
|
|
124
|
+
However the CLI is named, the transport settles on one absolute path before it runs anything, and uses that path for both the version check and the session. Anything relative is resolved against the process's working directory, never against `cwd:` — a relative `cli_path:` (a leading `~` expands to the home directory), and a `PATH` hit that came from a relative `PATH` entry (`bin`, `.`, an empty entry). A `PATH` entry that is `~` or starts with `~/` is not one of those: it is expanded against the home directory, as Ruby's own command lookup does. A bare `cli_path: 'claude'` is looked up by the SDK in the same way, but on the `PATH` the session will get: the one in `env:` when you set one there, otherwise the process's. A `cli_path:` that names no file raises `CLINotFoundError` from `connect`.
|
data/docs/client.md
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
# Client & Custom Transport
|
|
2
2
|
|
|
3
|
-
`ClaudeAgentSDK::Client`
|
|
3
|
+
`ClaudeAgentSDK::Client` keeps one Claude Code session open for a conversation you drive. What it adds over `query()` is lifecycle: you can send follow-up queries in the same session, and you can call the CLI while the session runs (`interrupt`, switch the model or the permission mode, inspect and reconnect MCP servers, rewind files, stop or background a task).
|
|
4
|
+
|
|
5
|
+
**Custom tools**, **hooks** and **permission callbacks** are not part of that difference. `query()` and `ask` speak the same control protocol as `Client`, so all three run them; each is a Ruby proc or lambda you pass in `ClaudeAgentOptions`.
|
|
4
6
|
|
|
5
7
|
For a single question you don't need a session: `ClaudeAgentSDK.ask(prompt, options:)` runs `query()` to completion and returns the final `ResultMessage` (`#result` is the answer text), optionally yielding each message to a block on the way. See the README's [Quick Start](../README.md#quick-start).
|
|
6
8
|
|
|
@@ -27,6 +29,8 @@ end
|
|
|
27
29
|
|
|
28
30
|
Called outside a reactor, `break` inside the `Client.open` block raises `LocalJumpError` (the client still disconnects), so return a value from the block instead. `break` inside `receive_response` / `receive_messages` is fine. It stops the iteration.
|
|
29
31
|
|
|
32
|
+
Every `client.query` on one client continues the same conversation. The `session_id:` keyword of `Client#query` does not change that: it is a label on the message the SDK sends, and the CLI keeps a single session per client. Every `ResultMessage#session_id` is the CLI's own id, whatever you passed, and all the turns land in one transcript. For separate contexts, one per user for instance, use one `Client` (or one `query()`) each.
|
|
33
|
+
|
|
30
34
|
If your code already runs inside an `Async` reactor and you want to manage the connection yourself, call `connect` and `disconnect` directly:
|
|
31
35
|
|
|
32
36
|
```ruby
|
|
@@ -43,10 +47,7 @@ end
|
|
|
43
47
|
## Advanced Features
|
|
44
48
|
|
|
45
49
|
```ruby
|
|
46
|
-
|
|
47
|
-
client = ClaudeAgentSDK::Client.new
|
|
48
|
-
client.connect
|
|
49
|
-
|
|
50
|
+
ClaudeAgentSDK::Client.open do |client|
|
|
50
51
|
client.interrupt # Send interrupt signal
|
|
51
52
|
client.permission_mode = 'acceptEdits' # Change permission mode mid-conversation
|
|
52
53
|
client.model = 'claude-sonnet-5' # Switch model mid-conversation (nil = default)
|
|
@@ -60,9 +61,7 @@ Async do
|
|
|
60
61
|
client.background_tasks(tool_use_id: 'toolu_01') # Only the task spawned by that tool_use block
|
|
61
62
|
# => { backgrounded: true } | { backgrounded: false } (definitive miss)
|
|
62
63
|
# '' or a non-String raises ArgumentError; nil is the all-tasks form
|
|
63
|
-
|
|
64
|
-
client.disconnect
|
|
65
|
-
end.wait
|
|
64
|
+
end
|
|
66
65
|
```
|
|
67
66
|
|
|
68
67
|
The Ruby-style names above sit next to the Python SDK's spellings, and both work, so code ported from the Python docs runs unchanged:
|
|
@@ -106,7 +105,7 @@ end
|
|
|
106
105
|
|
|
107
106
|
By default, `Client` uses `SubprocessCLITransport` to spawn the Claude Code CLI locally. You can provide a custom transport class to connect via other channels (e.g., remote SSH, WebSocket, or a sandbox VM).
|
|
108
107
|
|
|
109
|
-
A transport must implement
|
|
108
|
+
A transport must implement five methods. It can subclass `ClaudeAgentSDK::Transport`, whose methods raise `NotImplementedError` until you override them, or be any object that has them:
|
|
110
109
|
|
|
111
110
|
| Method | Purpose |
|
|
112
111
|
|---|---|
|
|
@@ -114,8 +113,9 @@ A transport must implement six methods:
|
|
|
114
113
|
| `write(data)` | Send raw JSON-line bytes to stdin |
|
|
115
114
|
| `read_messages { \|hash\| ... }` | Yield each stdout line as a Hash parsed with `JSON.parse(line, symbolize_names: true)` (the SDK reads Symbol keys; see [Hash keys](types.md#hash-keys)); block until the stream closes |
|
|
116
115
|
| `end_input` | Signal EOF on stdin |
|
|
117
|
-
| `close` | Terminate and clean up |
|
|
118
|
-
|
|
116
|
+
| `close` | Terminate and clean up. Must be safe to call more than once |
|
|
117
|
+
|
|
118
|
+
`ready?` (report whether the transport can accept I/O) is on the `Transport` base class as well, but the SDK never calls it, so it is optional. `end_input` is not: a one-shot `query()` calls it when the run is over, and `Client` calls it when a streamed prompt is exhausted.
|
|
119
119
|
|
|
120
120
|
**Environment your transport should give the CLI.** `SubprocessCLITransport`
|
|
121
121
|
sets a few variables that a custom transport has to set itself. The one that
|
|
@@ -138,6 +138,24 @@ client = ClaudeAgentSDK::Client.new(
|
|
|
138
138
|
)
|
|
139
139
|
```
|
|
140
140
|
|
|
141
|
+
### One-shot queries over a custom transport
|
|
142
|
+
|
|
143
|
+
`ClaudeAgentSDK.query` and `ClaudeAgentSDK.ask` take a transport as well: a ready-made instance in `transport:`, not a class.
|
|
144
|
+
|
|
145
|
+
```ruby
|
|
146
|
+
transport = MyTransport.new(options, foo: 'bar')
|
|
147
|
+
ClaudeAgentSDK.query(prompt: 'Hello', options: options, transport: transport) { |message| puts message }
|
|
148
|
+
|
|
149
|
+
result = ClaudeAgentSDK.ask('Hello', options: options, transport: MyTransport.new(options, foo: 'bar'))
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
- The SDK connects the transport, runs the query over it and closes it, so one instance serves one query. `close` is called even when `connect` raised, and it must be idempotent.
|
|
153
|
+
- `options` still drives everything the SDK does on its own side: hooks, SDK MCP servers, agents, observers, callback scheduling. The command line and the environment are whatever your transport gives the CLI. `query` does not rebuild them from `options`, so build the transport from the same options.
|
|
154
|
+
- `can_use_tool` needs one more step. The CLI asks the callback only when it is started with `--permission-prompt-tool stdio`. The SDK adds that to the options of a transport it builds (a `transport_class:` transport receives options with `permission_prompt_tool_name: 'stdio'`), but `query` cannot add it to a transport you built. Build that transport from `options.dup_with(permission_prompt_tool_name: 'stdio')` and still pass the original `options` to `query`; passing the copy raises `ArgumentError`, because `can_use_tool` and `permission_prompt_tool_name` cannot be combined there.
|
|
155
|
+
- Anything that does not respond to `connect` raises `ArgumentError`.
|
|
156
|
+
|
|
157
|
+
Resuming from a `session_store` is not available over a custom transport, through `query(transport:)` or `transport_class:`: the SDK prepares the transcript only for a CLI it starts with `SubprocessCLITransport` (or a subclass of it).
|
|
158
|
+
|
|
141
159
|
### Reference: running `claude` inside an E2B sandbox
|
|
142
160
|
|
|
143
161
|
[`examples/e2b_transport_example.rb`](https://github.com/ya-luotao/claude-agent-sdk-ruby/blob/main/examples/e2b_transport_example.rb) is a working transport that runs the Claude Code CLI inside an [E2B](https://e2b.dev) Firecracker microVM instead of on your host. The wire protocol stays identical — only the I/O layer changes:
|