Skip to main content

Session

Struct Session 

Source
pub struct Session(/* private fields */);
Expand description

A live Claude Code session. Cheap to clone — backed by Arc<SessionInner>.

Handlers in SessionOptions (can_use_tool, hooks, …) are owned by the session; one that needs the session should capture Session::downgrade(), since a captured Session keeps it, and the CLI, alive forever.

Implementations§

Source§

impl Session

Source

pub async fn spawn(opts: SessionOptions, init: Initialize) -> Result<Self>

Spawn a Claude Code subprocess and complete the initialize handshake.

  1. spawn claude --output-format stream-json --verbose --input-format stream-json --await-initialize …
  2. write the initialize control request (with opts.hooks)
  3. wait for its control_response
Source

pub async fn reconnect( previous_id: &str, opts: SessionOptions, init: Initialize, ) -> Result<Self>

Spawn with --resume <previous_id>; the CLI reloads its own transcript.

Source

pub async fn send<T: Serialize>(&self, msg: &T) -> Result<()>

Send a raw JSON line to the subprocess stdin.

Source

pub async fn control<B: Serialize>(&self, body: &B) -> Result<Value>

Send a host → CLI control request and wait for its response payload. body must serialize to an object with a subtype field.

Source

pub async fn interrupt(&self) -> Result<()>

Interrupt the running turn; its stream ends with an AgentEvent::Error of kind TurnErrorKind::Execution. Queued prompts still run.

Source

pub async fn interrupt_all(&self) -> Result<()>

Interrupt the running turn and cancel every queued prompt. Source: binary interrupt schema (cancel_queued)

Source

pub async fn set_model(&self, model: Option<&str>) -> Result<()>

Switch model for the following turns. None clears the override, so the CLI falls back to its default model (not to SessionOptions::model). Source: binary set_model schema

Source

pub async fn set_model_and_system_prompt( &self, model: &str, system_prompt: &str, ) -> Result<()>

Switch model and replace the custom system prompt. The new prompt is sent from the next compaction on (from the next turn with Initialize::system_prompt_snapshot: Some(false)). Source: binary set_model schema (system_prompt)

Source

pub async fn set_system_prompt( &self, model: &str, system_prompt: &str, ) -> Result<()>

Replace the custom system prompt without switching model. model must name the session’s current model, or the CLI refuses. CLI 2.1.329 can confirm the model only while the session runs the account’s default model (no SessionOptions::model, no set_model); otherwise use set_model_and_system_prompt. The new prompt is sent from the next compaction on. Source: binary set_model schema (only_if_model_is_current)

Source

pub async fn set_max_thinking_tokens( &self, tokens: Option<u32>, display: Option<ThinkingDisplay>, ) -> Result<()>

Thinking-token budget for the following turns (older models); None restores the session’s setting. Source: binary set_max_thinking_tokens schema

Source

pub async fn set_effort(&self, effort: Option<Effort>) -> Result<()>

Switch effort level for the following turns; None clears the override, so the CLI falls back to its default level (not to SessionOptions::effort). Source: binary apply_flag_settings handler (effortLevel)

Source

pub async fn set_permission_mode(&self, mode: PermissionMode) -> Result<()>

Source: binary set_permission_mode schema

Source

pub async fn stop_task(&self, task_id: &str) -> Result<()>

Stop a background task by its task_id (see AgentEvent::BackgroundTasks). Source: binary stop_task schema

Source

pub async fn context_usage(&self, exact: bool) -> Result<Value>

Context-window usage of the session, as reported by the CLI. exact: true counts each category with the token-count API; false estimates from the last response’s usage, without those calls. Source: binary get_context_usage schema

Source

pub async fn cancel_prompt(&self, uuid: &str) -> Result<()>

Withdraw a prompt: drop it from the queue if it has not started, else interrupt its turn. Another prompt’s turn is never interrupted. Source: binary cancel_async_message and interrupt (for_user_message_uuids) schemas

Source

pub async fn rename_session(&self, title: &str) -> Result<()>

Set the session’s display title. Source: binary rename_session schema

Source

pub async fn rewind_files( &self, user_message_id: &str, dry_run: bool, ) -> Result<Value>

Restore files Claude changed to their state at user_message_id (the uuid of a prompt). dry_run reports without changing files. Source: binary rewind_files schema

Source

pub async fn mcp_status(&self) -> Result<Value>

Connection status of every MCP server. Source: binary mcp_status schema

Source

pub async fn mcp_toggle(&self, server: &str, enabled: bool) -> Result<()>

Enable or disable an MCP server. Source: binary mcp_toggle schema

Source

pub async fn mcp_reconnect(&self, server: &str) -> Result<()>

Reconnect a failed or disconnected MCP server. Source: binary mcp_reconnect schema

Source

pub async fn set_mcp_servers( &self, sdk: Vec<SdkMcpServer>, external: Map<String, Value>, ) -> Result<Value>

Replace the MCP servers added at runtime: in-process sdk servers plus external configs (stdio/http/sse, keyed by name). Servers from SessionOptions and settings stay. Their tools are not pre-allowed: they go through the permission mode and can_use_tool. Source: binary mcp_set_servers schema

Source

pub async fn list_models(&self) -> Result<Value>

Models the session can switch to. Source: binary list_models schema

Source

pub async fn get_settings(&self) -> Result<Value>

Effective merged settings plus each source’s raw settings. Source: binary get_settings schema

Source

pub async fn update_settings( &self, local: bool, settings: Value, ) -> Result<Value>

Write settings through the CLI’s own writer. local = the project’s local settings (allowlist: outputStyle); otherwise the user’s settings (effortLevel only). Source: binary update_settings schema

Source

pub async fn get_usage(&self, skip_behaviors: bool) -> Result<Value>

Session cost and usage, plus plan rate-limit use when available. skip_behaviors skips the scan of local transcripts (its section is then null) — enough for a rate-limit meter. Experimental in the CLI. Source: binary get_usage schema

Source

pub async fn reload_skills(&self) -> Result<Value>

Re-read skills from disk. Source: binary reload_skills schema

Source

pub async fn reload_plugins(&self, opts: ReloadPlugins) -> Result<Value>

Re-read plugins from disk. Source: binary reload_plugins schema

Source

pub async fn task_output(&self, task_id: &str) -> Result<Value>

The last output (≤ 8 KiB) of a background shell or Monitor task. Source: binary get_task_output schema

Source

pub async fn register_repo_root(&self, directory: &str) -> Result<Value>

Add a working-directory root (a subdirectory of cwd or of an add_dirs entry) and reload CLAUDE.md, skills and plugins for it. Source: binary register_repo_root schema

Source

pub async fn mcp_call( &self, tool: &str, arguments: Value, opts: McpCall, ) -> Result<Value>

Call a tool of an external MCP server directly, without a model turn and without a permission check. tool is fully qualified (mcp__server__tool). In-process servers are refused: call their Rust functions directly. Source: binary mcp_call schema

Source

pub async fn mcp_read_resource(&self, server: &str, uri: &str) -> Result<Value>

Read a ui:// resource from a connected external MCP server. Source: binary mcp_read_resource schema

Source

pub async fn read_file( &self, path: &str, max_bytes: Option<u64>, base64: bool, ) -> Result<Value>

Read a file through the CLI, under the session’s read permissions (path relative to cwd). base64 for binary files such as images; otherwise lossy UTF-8. Source: binary read_file schema

Source

pub async fn file_suggestions(&self, query: &str) -> Result<Value>

@-mention file suggestions for a partial path, as the terminal shows. Source: binary file_suggestions schema

Source

pub async fn hooks_listing(&self) -> Result<Value>

Every hook (settings, session, plugin) grouped by event and matcher. Source: binary get_hooks_listing schema

Source

pub async fn permission_rules(&self) -> Result<Value>

The live permission rules and workspace directories. Source: binary list_permission_rules schema

Source

pub async fn session_cost(&self) -> Result<Value>

The formatted session cost summary (/usage text). Source: binary get_session_cost schema

Source

pub async fn reload_output_styles(&self) -> Result<Value>

Re-read output styles from disk. Source: binary reload_output_styles schema

Source

pub async fn seed_read_state(&self, path: &str, mtime_ms: u64) -> Result<()>

Tell the CLI the file at path was read at mtime_ms, so Edit works on it after the Read left the context. Source: binary seed_read_state schema

Source

pub fn downgrade(&self) -> WeakSession

A handle that does not keep the session alive; see WeakSession.

Source

pub fn pid(&self) -> Option<u32>

Process id of the CLI (None for a replay).

Source

pub fn cli_version(&self) -> Option<&str>

The CLI’s version, read when the session started.

Source

pub fn subscribe(&self) -> EventRx

Receive every frame the CLI emits from now on. Lossless: a slow receiver buffers instead of dropping frames, so memory grows until it catches up. Poll the receiver, or drop it once done.

Source

pub fn session_id(&self) -> Option<String>

Current session id — known once the CLI emits its first system frame; changes after /clear.

Source

pub fn initialize_response(&self) -> Option<&Value>

Payload of the initialize control_response (commands, models, account, …).

Source

pub fn include_partial(&self) -> bool

Whether the session streams partial messages (SessionOptions::include_partial).

Source

pub fn is_busy(&self) -> bool

Whether a prompt sent with Agent is still waiting for its result.

Source

pub fn is_alive(&self) -> bool

Whether the subprocess is still running.

Source

pub async fn close(&self) -> Option<i32>

End the session: close stdin and give the CLI 5 s to exit, then SIGTERM, then SIGKILL its process group. Hooks and Bash tools still running (the CLI starts each in a process group of its own) end with it: SIGTERM, then SIGKILL after 2 s. A process a hook or tool detached that outlived it ((cmd &), nohup cmd &) is out of reach. Returns the CLI’s exit code (None when it ended by a signal).

Trait Implementations§

Source§

impl Clone for Session

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more