pub struct Session(/* private fields */);Expand description
A live Claude Code session. Cheap to clone — backed by Arc<SessionInner>.
Implementations§
Source§impl Session
impl Session
Sourcepub async fn spawn(opts: SessionOptions, init: Initialize) -> Result<Self>
pub async fn spawn(opts: SessionOptions, init: Initialize) -> Result<Self>
Spawn a Claude Code subprocess and complete the initialize handshake.
- spawn
claude --output-format stream-json --verbose --input-format stream-json --await-initialize … - write the
initializecontrol request (withopts.hooks) - wait for its
control_response
Sourcepub async fn reconnect(
previous_id: &str,
opts: SessionOptions,
init: Initialize,
) -> Result<Self>
pub async fn reconnect( previous_id: &str, opts: SessionOptions, init: Initialize, ) -> Result<Self>
Spawn with --resume <previous_id>; the CLI reloads its own transcript.
Sourcepub async fn send<T: Serialize>(&self, msg: &T) -> Result<()>
pub async fn send<T: Serialize>(&self, msg: &T) -> Result<()>
Send a raw JSON line to the subprocess stdin.
Sourcepub async fn control<B: Serialize>(&self, body: &B) -> Result<Value>
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.
Sourcepub async fn interrupt(&self) -> Result<()>
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.
Sourcepub async fn interrupt_all(&self) -> Result<()>
pub async fn interrupt_all(&self) -> Result<()>
Interrupt the running turn and cancel every queued prompt.
Source: binary interrupt schema (cancel_queued)
Sourcepub async fn set_model(&self, model: Option<&str>) -> Result<()>
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
Sourcepub async fn set_model_and_system_prompt(
&self,
model: &str,
system_prompt: &str,
) -> Result<()>
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)
Sourcepub async fn set_system_prompt(
&self,
model: &str,
system_prompt: &str,
) -> Result<()>
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)
Sourcepub async fn set_max_thinking_tokens(
&self,
tokens: Option<u32>,
display: Option<ThinkingDisplay>,
) -> Result<()>
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
Sourcepub async fn set_effort(&self, effort: Option<Effort>) -> Result<()>
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)
Sourcepub async fn set_permission_mode(&self, mode: PermissionMode) -> Result<()>
pub async fn set_permission_mode(&self, mode: PermissionMode) -> Result<()>
Source: binary set_permission_mode schema
Sourcepub async fn stop_task(&self, task_id: &str) -> Result<()>
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
Sourcepub async fn context_usage(&self, exact: bool) -> Result<Value>
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
Sourcepub async fn cancel_prompt(&self, uuid: &str) -> Result<()>
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
Sourcepub async fn rename_session(&self, title: &str) -> Result<()>
pub async fn rename_session(&self, title: &str) -> Result<()>
Set the session’s display title. Source: binary rename_session schema
Sourcepub async fn rewind_files(
&self,
user_message_id: &str,
dry_run: bool,
) -> Result<Value>
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
Sourcepub async fn mcp_status(&self) -> Result<Value>
pub async fn mcp_status(&self) -> Result<Value>
Connection status of every MCP server. Source: binary mcp_status schema
Sourcepub async fn mcp_toggle(&self, server: &str, enabled: bool) -> Result<()>
pub async fn mcp_toggle(&self, server: &str, enabled: bool) -> Result<()>
Enable or disable an MCP server. Source: binary mcp_toggle schema
Sourcepub async fn mcp_reconnect(&self, server: &str) -> Result<()>
pub async fn mcp_reconnect(&self, server: &str) -> Result<()>
Reconnect a failed or disconnected MCP server. Source: binary mcp_reconnect schema
Sourcepub async fn set_mcp_servers(
&self,
sdk: Vec<SdkMcpServer>,
external: Map<String, Value>,
) -> Result<Value>
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
Sourcepub async fn list_models(&self) -> Result<Value>
pub async fn list_models(&self) -> Result<Value>
Models the session can switch to. Source: binary list_models schema
Sourcepub async fn get_settings(&self) -> Result<Value>
pub async fn get_settings(&self) -> Result<Value>
Effective merged settings plus each source’s raw settings. Source: binary get_settings schema
Sourcepub async fn update_settings(
&self,
local: bool,
settings: Value,
) -> Result<Value>
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
Sourcepub async fn get_usage(&self, skip_behaviors: bool) -> Result<Value>
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
Sourcepub async fn reload_skills(&self) -> Result<Value>
pub async fn reload_skills(&self) -> Result<Value>
Re-read skills from disk. Source: binary reload_skills schema
Sourcepub async fn reload_plugins(&self, opts: ReloadPlugins) -> Result<Value>
pub async fn reload_plugins(&self, opts: ReloadPlugins) -> Result<Value>
Re-read plugins from disk. Source: binary reload_plugins schema
Sourcepub async fn task_output(&self, task_id: &str) -> Result<Value>
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
Sourcepub async fn register_repo_root(&self, directory: &str) -> Result<Value>
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
Sourcepub async fn mcp_call(
&self,
tool: &str,
arguments: Value,
opts: McpCall,
) -> Result<Value>
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
Sourcepub async fn mcp_read_resource(&self, server: &str, uri: &str) -> Result<Value>
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
Sourcepub async fn read_file(
&self,
path: &str,
max_bytes: Option<u64>,
base64: bool,
) -> Result<Value>
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
Sourcepub async fn file_suggestions(&self, query: &str) -> Result<Value>
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
Sourcepub async fn hooks_listing(&self) -> Result<Value>
pub async fn hooks_listing(&self) -> Result<Value>
Every hook (settings, session, plugin) grouped by event and matcher. Source: binary get_hooks_listing schema
Sourcepub async fn permission_rules(&self) -> Result<Value>
pub async fn permission_rules(&self) -> Result<Value>
The live permission rules and workspace directories. Source: binary list_permission_rules schema
Sourcepub async fn session_cost(&self) -> Result<Value>
pub async fn session_cost(&self) -> Result<Value>
The formatted session cost summary (/usage text).
Source: binary get_session_cost schema
Sourcepub async fn reload_output_styles(&self) -> Result<Value>
pub async fn reload_output_styles(&self) -> Result<Value>
Re-read output styles from disk. Source: binary reload_output_styles schema
Sourcepub async fn seed_read_state(&self, path: &str, mtime_ms: u64) -> Result<()>
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
Sourcepub fn cli_version(&self) -> Option<&str>
pub fn cli_version(&self) -> Option<&str>
The CLI’s version, read when the session started.
Sourcepub fn subscribe(&self) -> EventRx
pub fn subscribe(&self) -> EventRx
Receive every frame the CLI emits from now on. Lossless: a slow receiver buffers instead of dropping frames.
Sourcepub fn session_id(&self) -> Option<String>
pub fn session_id(&self) -> Option<String>
Current session id — known once the CLI emits its first system
frame; changes after /clear.
Sourcepub fn initialize_response(&self) -> Option<&Value>
pub fn initialize_response(&self) -> Option<&Value>
Payload of the initialize control_response (commands, models, account, …).
pub fn include_partial(&self) -> bool
Sourcepub fn is_busy(&self) -> bool
pub fn is_busy(&self) -> bool
Whether a prompt sent with Agent is still waiting for its result.
Sourcepub async fn close(&self) -> Option<i32>
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. Tools it started (background
Bash commands keep the CLI alive past stdin EOF) end with it.
Returns the CLI’s exit code (None when it ended by a signal).