Skip to main content

Session

Struct Session 

Source
pub struct Session { /* private fields */ }
Expand description

A Copilot conversation session.

Sessions maintain conversation state, handle events, and manage tool execution.

§Example

use copilot_sdk::{Client, SessionConfig, SessionEventData};

#[tokio::main]
async fn main() -> copilot_sdk::Result<()> {
let client = Client::builder().build()?;
client.start().await?;
let session = client.create_session(SessionConfig::default()).await?;

// Subscribe to events
let mut events = session.subscribe();

// Send a message
session.send("Hello!").await?;

// Process events
while let Ok(event) = events.recv().await {
    match &event.data {
        SessionEventData::AssistantMessage(msg) => println!("{}", msg.content),
        SessionEventData::SessionIdle(_) => break,
        _ => {}
    }
}
client.stop().await;

Implementations§

Source§

impl Session

Source

pub fn new<F>( session_id: String, workspace_path: Option<String>, invoke_fn: F, ) -> Self
where F: Fn(&str, Option<Value>) -> InvokeFuture + Send + Sync + 'static,

Create a new session.

This is typically called by the Client when creating a session.

Source

pub fn session_id(&self) -> &str

Get the session ID.

Source

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

Get the workspace path for infinite sessions.

Contains checkpoints/, plan.md, and files/ subdirectories. Returns None if infinite sessions are disabled.

Source

pub fn subscribe(&self) -> EventSubscription

Subscribe to session events.

Returns a receiver that will receive all session events.

Source

pub async fn on<F>(&self, handler: F) -> impl FnOnce()
where F: Fn(&SessionEvent) + Send + Sync + 'static,

Register a callback-based event handler.

Returns an unsubscribe closure. Call it to remove the handler. Alternatively, use [off] with the internal handler ID.

Source

pub async fn off(&self, handler_id: u64)

Unsubscribe a callback-based event handler.

Source

pub async fn dispatch_event(&self, event: SessionEvent)

Dispatch an event to all subscribers.

This is called by the Client when events are received.

Source

pub async fn send(&self, options: impl Into<MessageOptions>) -> Result<String>

Send a message to the session.

Returns the message ID.

Source

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

Abort the current message processing.

Source

pub async fn get_messages(&self) -> Result<Vec<SessionEvent>>

Get all messages in the session.

Source

pub async fn register_tool(&self, tool: Tool)

Register a tool with this session.

Source

pub async fn register_tool_with_handler( &self, tool: Tool, handler: Option<ToolHandler>, )

Register a tool with a handler.

Source

pub async fn register_tools(&self, tools: Vec<Tool>)

Register multiple tools.

Source

pub async fn get_tool(&self, name: &str) -> Option<Tool>

Get a registered tool by name.

Source

pub async fn get_tools(&self) -> Vec<Tool>

Get all registered tools.

Source

pub async fn invoke_tool( &self, name: &str, arguments: &Value, ) -> Result<ToolResultObject>

Invoke a tool handler.

Source

pub async fn register_permission_handler<F>(&self, handler: F)

Register a permission handler.

Source

pub async fn handle_permission_request( &self, request: &PermissionRequest, ) -> PermissionRequestResult

Handle a permission request.

Delegates to the registered permission handler, or denies by default if no handler is set.

Source

pub async fn register_user_input_handler<F>(&self, handler: F)

Register a handler for user input requests from the server.

Source

pub async fn handle_user_input_request( &self, request: &UserInputRequest, ) -> Result<UserInputResponse>

Handle a user input request from the server.

Source

pub async fn has_user_input_handler(&self) -> bool

Check if a user input handler is registered.

Source

pub async fn register_hooks(&self, hooks: SessionHooks)

Register session hooks.

Source

pub async fn has_hooks(&self) -> bool

Check if any hooks are registered.

Source

pub async fn handle_hooks_invoke( &self, hook_type: &str, input: &Value, ) -> Result<Value>

Handle a hooks.invoke callback from the server.

Dispatches to the appropriate hook handler based on hook_type and returns the serialized output JSON.

Source

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

Destroy the session.

Source§

impl Session

Source

pub async fn wait_for_idle( &self, timeout: Option<Duration>, ) -> Result<Option<SessionEvent>>

Wait for the session to become idle.

Returns the last assistant message event, or None if no message was received. Uses the specified timeout, or 60 seconds if None.

Source

pub async fn send_and_wait( &self, options: impl Into<MessageOptions>, timeout: Option<Duration>, ) -> Result<Option<SessionEvent>>

Send a message and wait for the complete response.

Returns the last AssistantMessage event, or None if session became idle without producing an assistant message. Uses the specified timeout, or 60 seconds if None.

Source

pub async fn send_and_collect( &self, options: impl Into<MessageOptions>, timeout: Option<Duration>, ) -> Result<String>

Send a message and wait for the response content as a string.

Convenience method that collects all assistant message/delta content. Uses the specified timeout, or 60 seconds if None.

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> 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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

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

Source§

type Error = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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