Skip to content

v1.2.0

Choose a tag to compare

@ya-luotao ya-luotao released this 03 Oct 09:30
· 66 commits to main since this release

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.

Added

  • 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)
  • 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)

Changed

  • 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.
  • 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.
  • 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)
  • 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)
  • 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)
  • 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)
  • 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)
  • 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)
  • 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)
  • 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)
  • 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)

Fixed

  • 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)
  • 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)
  • "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)
  • 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)
  • 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)
  • 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)
  • 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)
  • #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)
  • 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)
  • 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)
  • A callback that fails with NotImplementedError, LoadError, SystemStackError or SecurityError is answered like any other failing callback. These are not StandardErrors, 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)
  • 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)
  • 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)
  • 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)
  • 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)
  • 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)
  • 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)
  • 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)
  • 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)
  • 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)
  • 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)
  • 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)
  • 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). The mirror's retry backoff uses Kernel#sleep instead of the deprecated Async::Task#sleep. (#159)
  • 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)
  • Session reads, listings and mutations — other fixes (#157):
    • 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).
    • 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.
    • 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.
    • 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).
    • 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.
    • list_sessions no longer returns [] when the config directory path contains [ or {.
    • 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.
    • fork_session without title: names the fork after the title the listing shows for the source, on disk and with session_store: alike.
    • 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.
    • 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.
    • docs/sessions.md: rename / tag / fork are safe while the session's CLI runs; delete only sessions whose CLI has exited.
  • 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)
  • 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)
  • 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)
  • 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)
  • 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)
  • 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)
  • 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)
  • 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)
  • 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)
  • 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)
  • 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)
  • 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, #156, #159)
  • 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)
  • 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)
  • #[] 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)
  • 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)
  • 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)
  • 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)
  • 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)
  • 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)
  • .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)
  • Documentation that contradicted the code (#155):
    • 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.
    • 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.
    • 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.
    • 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.
    • 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.
    • 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.
    • 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).
    • .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.
    • 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); 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); docs/rails.md says hooks and custom tools work with query too (#158).

Usage

# Multi-user hosts: keep one user's "remember …" out of every other user's session
ClaudeAgentSDK.configure do |config|
  config.default_options = { env: { 'CLAUDE_CODE_DISABLE_AUTO_MEMORY' => '1' } }
end

# A tools: String now restricts the session to the tools it names (it used to be ignored)
options = ClaudeAgentSDK::ClaudeAgentOptions.new(tools: 'Read,Grep')

What's changed

  • #165 Bump PINNED_CLI_VERSION to 2.1.288 — @github-actions
  • #164 Keep the stderr drain thread off rspec doubles in connect specs — @ya-luotao
  • #163 CHANGELOG for the October exploration fixes (#148–#161) — merge last — @ya-luotao
  • #161 Let a disconnect from another thread finish the CLI's graceful shutdown — @ya-luotao
  • #160 Accept the natural Ruby spellings in Hash-form options (sandbox keys, Symbol type:, String tools:, Pathname) — @ya-luotao
  • #159 Store-backed resume: Keychain for a custom config dir, a scrubbed preserved dir, no batch lost to a cancelled flush — @ya-luotao
  • #158 Railtie wrapper: stop reporting SDK-handled errors; make the Rails guide say what callbacks really see — @ya-luotao
  • #157 Fix session reads, listing and mutations (parallel tool results, worktrees, encodings, long and odd paths) — @ya-luotao
  • #156 Resolve the CLI to one absolute path; contain stderr-callback failures; warn when the sandbox is off — @ya-luotao
  • #155 Docs and packaging: make the published reference match the code — @ya-luotao
  • #154 Fix runtime lifecycle defects in Query, FiberBoundary, query() and Client — @ya-luotao
  • #153 Harden the test suite and CI (seed order, Ruby 4.0, hang bounds, protocol pins, keyless CLI smoke) — @ya-luotao
  • #152 Fix CLI installer defects (fiber deadlock, proxy, read-only dir, fsync) and SDK MCP schema/result bugs — @ya-luotao
  • #151 Filter more credentials in #inspect, make it never raise, fix #[] with a setter-shaped name — @ya-luotao
  • #150 Answer every failing callback: non-StandardError failures and unencodable messages — @ya-luotao
  • #149 Honor Hash hook outputs in any key style; fix other wire-shape contract bugs — @ya-luotao
  • #148 Fix OTelObserver token usage per response; trace sessions that fail before init — @ya-luotao
  • #147 Bump PINNED_CLI_VERSION to 2.1.287 — @github-actions
  • #146 Keep the pin's CHANGELOG entry in the bump PR; batch pin-only releases — @ya-luotao
  • #132 Bump the github-actions group across 1 directory with 3 updates — @dependabot

Full Changelog: v1.1.0...v1.2.0


gem install claude-agent-sdk -v 1.2.0