### Run Telemetry Setup Example Source: https://github.com/copilot-community-sdk/copilot-sdk-rust/blob/main/README.md Execute the telemetry example to set up and verify OpenTelemetry integration. ```bash cargo run --example telemetry # OpenTelemetry setup ``` -------------------------------- ### Quick Start: Initialize and Use Copilot Client Source: https://github.com/copilot-community-sdk/copilot-sdk-rust/blob/main/README.md Basic example demonstrating how to initialize the Copilot client, start a session, send a message, and collect the response. ```rust use copilot_sdk::{Client, SessionConfig}; #[tokio::main] async fn main() -> copilot_sdk::Result<()> { let client = Client::builder().build()?; client.start().await?; let session = client.create_session(SessionConfig::default()).await?; let response = session.send_and_collect("Hello!", None).await?; println!("{}", response); client.stop().await; Ok(()) } ``` -------------------------------- ### Run Streaming Responses Example Source: https://github.com/copilot-community-sdk/copilot-sdk-rust/blob/main/README.md Execute the streaming example to observe how responses are handled in a streaming fashion. ```bash cargo run --example streaming # Streaming responses ``` -------------------------------- ### Run Mode Switching Example Source: https://github.com/copilot-community-sdk/copilot-sdk-rust/blob/main/README.md Execute the mode switching example to manage and switch between different operational modes. ```bash cargo run --example mode_switching # Mode management ``` -------------------------------- ### Run Model Switching Example Source: https://github.com/copilot-community-sdk/copilot-sdk-rust/blob/main/README.md Execute the set model example to test the functionality of switching between different models. ```bash cargo run --example set_model # Model switching ``` -------------------------------- ### Run Session Hooks Example Source: https://github.com/copilot-community-sdk/copilot-sdk-rust/blob/main/README.md Execute the session hooks example to demonstrate the usage of session lifecycle hooks. ```bash cargo run --example hooks # Session hooks ``` -------------------------------- ### Get Account Quota and List Tools with Rust Copilot SDK Source: https://context7.com/copilot-community-sdk/copilot-sdk-rust/llms.txt Initializes the client, retrieves account quota information, and lists available tools. Ensure the client is started before making requests and stopped afterwards. ```rust use copilot_sdk::Client; #[tokio::main] async fn main() -> copilot_sdk::Result<()> { let client = Client::builder().build()?; client.start().await?; let quota = client.get_quota().await?; for q in "a.quotas { println!("Type={} used={:?}/{:?} resets={:?}", q.quota_type, q.used, q.limit, q.resets_at); } let tools = client.tools_list(Some("gpt-4.1")).await?; for t in &tools.tools { println!("Tool: {} — {:?}", t.name, t.description); } client.stop().await; Ok(()) } ``` -------------------------------- ### Run Bring Your Own Key Example Source: https://github.com/copilot-community-sdk/copilot-sdk-rust/blob/main/README.md Execute the BYOK example to test the Bring Your Own Key functionality for custom provider integration. ```bash cargo run --example byok # Bring Your Own Key ``` -------------------------------- ### Run Agent Management Example Source: https://github.com/copilot-community-sdk/copilot-sdk-rust/blob/main/README.md Execute the agent management example to test operations related to managing agents. ```bash cargo run --example agent_management # Agent operations ``` -------------------------------- ### Run Custom Tool Usage Example Source: https://github.com/copilot-community-sdk/copilot-sdk-rust/blob/main/README.md Execute the tool usage example to demonstrate the integration and use of custom tools within the Copilot SDK. ```bash cargo run --example tool_usage # Custom tools ``` -------------------------------- ### Run Basic Chat Example Source: https://github.com/copilot-community-sdk/copilot-sdk-rust/blob/main/README.md Execute the basic chat example to perform simple question-and-answer interactions with the Copilot SDK. ```bash cargo run --example basic_chat # Simple Q&A ``` -------------------------------- ### Run Shell Execution Example Source: https://github.com/copilot-community-sdk/copilot-sdk-rust/blob/main/README.md Execute the shell execution example to test the ability to run shell commands. ```bash cargo run --example shell_exec # Shell commands ``` -------------------------------- ### Run Plan Operations Example Source: https://github.com/copilot-community-sdk/copilot-sdk-rust/blob/main/README.md Execute the plan operations example to test the CRUD (Create, Read, Update, Delete) operations for plans. ```bash cargo run --example plan_ops # Plan CRUD ``` -------------------------------- ### Fleet Management - Start Fleet Source: https://github.com/copilot-community-sdk/copilot-sdk-rust/blob/main/README.md Allows starting parallel agent fleets with an optional initial prompt. ```APIDOC ## Fleet Management - Start Fleet ### Description Starts parallel agent fleets, optionally providing an initial prompt. ### Method `session.start_fleet(options)` ### Parameters #### `start_fleet` Parameters - **options** (Option) - **prompt** (Option) - The initial prompt for the fleet. ### Example ```rust session.start_fleet(Some(FleetStartOptions { prompt: Some("Build and test the project".into()), })).await?; ``` ``` -------------------------------- ### Manage Copilot CLI client lifecycle Source: https://context7.com/copilot-community-sdk/copilot-sdk-rust/llms.txt Use `start()` to connect to the Copilot CLI, `stop()` for graceful shutdown, and `force_stop()` to immediately terminate. `start()` negotiates the protocol version and registers handlers. `stop()` destroys sessions and terminates the process. ```rust use copilot_sdk::Client; #[tokio::main] async fn main() -> copilot_sdk::Result<()> { let client = Client::builder().build()?; client.start().await?; println!("Connected, protocol: {:?}", client.negotiated_protocol_version().await); // … do work … let errors = client.stop().await; for e in errors { eprintln!("Stop error: {e}"); } Ok(()) } ``` -------------------------------- ### Create Session with Custom Configuration Source: https://github.com/copilot-community-sdk/copilot-sdk-rust/blob/main/README.md Example of creating a new session with specific model, streaming, and client name configurations. ```rust let session = client.create_session(SessionConfig { model: Some("gpt-4.1".into()), streaming: true, client_name: Some("my-app".into()), ..Default::default() }).await?; ``` -------------------------------- ### Client Initialization and Session Management Source: https://github.com/copilot-community-sdk/copilot-sdk-rust/blob/main/README.md Demonstrates how to initialize the Copilot SDK client, start a session, send a message, and collect the response. It also shows how to stop the client when done. ```APIDOC ## Client Initialization and Session Management ### Description Initializes the Copilot SDK client, starts a session, sends a message, collects the response, and stops the client. ### Method `Client::builder().build()?` - Initializes the client. `client.start().await?` - Starts the Copilot CLI agent. `client.create_session(SessionConfig::default()).await?` - Creates a new session. `session.send_and_collect("Hello!", None).await?` - Sends a message and collects the response. `client.stop().await` - Stops the Copilot CLI agent. ### Example ```rust use copilot_sdk::{Client, SessionConfig}; #[tokio::main] async fn main() -> copilot_sdk::Result<()> { let client = Client::builder().build()?; client.start().await?; let session = client.create_session(SessionConfig::default()).await?; let response = session.send_and_collect("Hello!", None).await?; println!("{}", response); client.stop().await; Ok(()) } ``` ``` -------------------------------- ### Start Agent Fleet Source: https://github.com/copilot-community-sdk/copilot-sdk-rust/blob/main/README.md Initiate a parallel agent fleet with an optional prompt. ```rust session.start_fleet(Some(FleetStartOptions { prompt: Some("Build and test the project".into()), })).await?; ``` -------------------------------- ### Setup Pre-commit Hooks Source: https://github.com/copilot-community-sdk/copilot-sdk-rust/blob/main/README.md Configure Git to use local pre-commit hooks for automated code formatting and linting checks before each commit. ```bash git config core.hooksPath .githooks ``` -------------------------------- ### Register Custom Tool with Handler Source: https://github.com/copilot-community-sdk/copilot-sdk-rust/blob/main/README.md Example of defining and registering a custom tool that the assistant can invoke, with permission control. ```rust let tool = Tool::new("get_weather") .description("Get current weather") .parameter("city", "string", "City name", true) .skip_permission(true); session.register_tool_with_handler(tool, Some(handler)).await; ``` -------------------------------- ### Client Utilities for Status and Information Source: https://github.com/copilot-community-sdk/copilot-sdk-rust/blob/main/README.md Examples of retrieving various status and information from the Copilot client, including CLI version, authentication, available models, tools, and account quota. ```rust let status = client.get_status().await?; let auth = client.get_auth_status().await?; let models = client.list_models().await?; let tools = client.tools_list(None).await?; let quota = client.get_quota().await?; ``` -------------------------------- ### Client::start / Client::stop / Client::force_stop Source: https://context7.com/copilot-community-sdk/copilot-sdk-rust/llms.txt Methods to manage the connection lifecycle with the Copilot CLI. `start` initiates the connection, `stop` gracefully terminates it, and `force_stop` abruptly kills the process. ```APIDOC ## Client::start / Client::stop / Client::force_stop Manage the connection lifecycle. `start` spawns the CLI process (or connects via TCP), negotiates the protocol version, and registers RPC handlers. `stop` gracefully destroys all active sessions before terminating. `force_stop` kills the process immediately. ### Usage Example: ```rust use copilot_sdk::Client; #[tokio::main] async fn main() -> copilot_sdk::Result<()> { let client = Client::builder().build()?; client.start().await?; println!("Connected, protocol: {:?}", client.negotiated_protocol_version().await); // … do work … let errors = client.stop().await; for e in errors { eprintln!("Stop error: {e}"); } Ok(()) } ``` ``` -------------------------------- ### Switch Session Mode Source: https://github.com/copilot-community-sdk/copilot-sdk-rust/blob/main/README.md Examples of switching the session mode between Plan, Autopilot, and Interactive. ```rust session.set_mode(SessionMode::Plan).await?; session.set_mode(SessionMode::Autopilot).await?; session.set_mode(SessionMode::Interactive).await?; ``` -------------------------------- ### Execute and Kill Shell Commands Source: https://github.com/copilot-community-sdk/copilot-sdk-rust/blob/main/README.md Example of executing a shell command, retrieving its process ID, and then terminating it with a signal. ```rust let result = session.shell_exec(ShellExecOptions { command: "cargo test".into(), cwd: Some("/my/project".into()), env: None, }).await?; session.shell_kill(&result.process_id, ShellSignal::SIGTERM).await?; ``` -------------------------------- ### Get and Set Session Model with Reasoning Effort Source: https://github.com/copilot-community-sdk/copilot-sdk-rust/blob/main/README.md Demonstrates how to retrieve the current model and set a new model with specified reasoning effort. ```rust let model = session.get_model().await?; session.set_model("claude-sonnet-4", Some(SetModelOptions { reasoning_effort: Some("high".into()), })).await?; ``` -------------------------------- ### Manage Copilot Sessions (List, Delete, Get Last) Source: https://context7.com/copilot-community-sdk/copilot-sdk-rust/llms.txt Demonstrates server-side session management, including listing all sessions with their summaries, retrieving the ID of the last active session, and deleting sessions marked as 'stale'. ```rust use copilot_sdk::Client; #[tokio::main] async fn main() -> copilot_sdk::Result<()> { let client = Client::builder().build()?; client.start().await?; // List all sessions on the server let sessions = client.list_sessions().await?; for s in &sessions { println!("ID: {} Summary: {:?}", s.session_id, s.summary); } // Get the last active session if let Some(last_id) = client.get_last_session_id().await? { println!("Last session: {last_id}"); } // Delete stale sessions for s in &sessions { if s.summary.as_deref() == Some("stale") { client.delete_session(&s.session_id).await?; } } client.stop().await; Ok(()) } ``` -------------------------------- ### Model Management - Get and Set Model Source: https://github.com/copilot-community-sdk/copilot-sdk-rust/blob/main/README.md Allows retrieving the current model of a session and setting a new model with optional reasoning effort. ```APIDOC ## Model Management - Get and Set Model ### Description Allows retrieving the current model of a session and setting a new model with optional reasoning effort. ### Method `session.get_model().await?` - Retrieves the current model. `session.set_model(model, options)` - Sets a new model for the session. ### Parameters #### `set_model` Parameters - **model** (String) - The name of the new model to set. - **options** (Option) - Optional settings for the model change. - **reasoning_effort** (Option) - The desired reasoning effort (e.g., "high"). ### Example ```rust let model = session.get_model().await?; session.set_model("claude-sonnet-4", Some(SetModelOptions { reasoning_effort: Some("high".into()), })).await?; ``` ``` -------------------------------- ### Stream Session Events with Rust Copilot SDK Source: https://context7.com/copilot-community-sdk/copilot-sdk-rust/llms.txt Subscribes to session events for real-time updates, including message deltas, usage tokens, and session status. This example processes streamed assistant messages and breaks on session idle or error. Ensure stdout is flushed for timely output. ```rust use copilot_sdk::{Client, SessionConfig, SessionEventData}; use std::io::{self, Write}; #[tokio::main] async fn main() -> copilot_sdk::Result<()> { let client = Client::builder().build()?; client.start().await?; let session = client.create_session(SessionConfig { streaming: true, ..Default::default() }).await?; let mut events = session.subscribe(); session.send("List 5 Rust tips.").await?; loop { match events.recv().await { Ok(event) => match &event.data { SessionEventData::AssistantTurnStart(_) => print!("Assistant: "), SessionEventData::AssistantMessageDelta(d) => { print!("{}", d.delta_content); io::stdout().flush().unwrap(); } SessionEventData::AssistantUsage(u) => { if let (Some(i), Some(o)) = (u.input_tokens, u.output_tokens) { println!("\n[tokens in={i:.0} out={o:.0}]"); } } SessionEventData::SessionIdle(_) => break, SessionEventData::SessionError(e) => { eprintln!("\nError: {}", e.message); break; } _ => {} // Ignore other event types }, Err(e) => { eprintln!("Channel error: {:?}", e); break; } } } client.stop().await; Ok(()) } ``` -------------------------------- ### Register Custom Permission Handler in Rust Source: https://context7.com/copilot-community-sdk/copilot-sdk-rust/llms.txt Register a custom handler for tool permission requests. This example approves 'read_file' and 'list_dir' operations, and conditionally approves shell commands starting with 'cargo' or 'ls'. Denies all others. ```rust use copilot_sdk::{Client, PermissionRequest, PermissionRequestResult, SessionConfig}; #[tokio::main] async fn main() -> copilot_sdk::Result<()> { let client = Client::builder().build()?; client.start().await?; let session = client.create_session(SessionConfig { request_permission: Some(true), ..Default::default() }).await?; session.register_permission_handler(|req: &PermissionRequest| { // Approve read operations, deny write/shell let approved = match req.kind.as_str() { "read_file" | "list_dir" => true, "shell_exec" => { let cmd = req.extension_data.get("command") .and_then(|v| v.as_str()) .unwrap_or(""); cmd.starts_with("cargo") || cmd.starts_with("ls") } _ => false, }; if approved { PermissionRequestResult::approved() } else { PermissionRequestResult::denied() } }).await; let response = session.send_and_collect("List files in the current directory", None).await?; println!("{response}"); client.stop().await; Ok(()) } ``` -------------------------------- ### Enable Infinite Sessions and Manual Compaction Source: https://github.com/copilot-community-sdk/copilot-sdk-rust/blob/main/README.md Configure the session to use infinite sessions and demonstrate triggering manual compaction. ```rust let config = SessionConfig { infinite_sessions: Some(InfiniteSessionConfig::enabled()), ..Default::default() }; // Trigger manual compaction session.compact().await?; ``` -------------------------------- ### Configure Custom AI Provider (OpenAI/Azure) Source: https://context7.com/copilot-community-sdk/copilot-sdk-rust/llms.txt Configure the session to use a custom AI provider like OpenAI or Azure OpenAI. Credentials can be set explicitly or loaded from environment variables. ```rust use copilot_sdk::{AzureOptions, Client, ProviderConfig, SessionConfig}; use std::env; #[tokio::main] async fn main() -> copilot_sdk::Result<()> { let client = Client::builder().build()?; client.start().await?; // OpenAI provider let session = client.create_session(SessionConfig { provider: Some(ProviderConfig { base_url: "https://api.openai.com/v1".into(), provider_type: Some("openai".into()), wire_api: Some("openai".into()), api_key: env::var("OPENAI_API_KEY").ok(), bearer_token: None, azure: None, }), model: Some("gpt-4o".into()), ..Default::default() }).await?; println!("{}", session.send_and_collect("Hello from OpenAI!", None).await?); // Azure OpenAI provider let azure_session = client.create_session(SessionConfig { provider: Some(ProviderConfig { base_url: "https://my-resource.openai.azure.com".into(), provider_type: Some("azure".into()), wire_api: Some("openai".into()), api_key: env::var("AZURE_OPENAI_API_KEY").ok(), bearer_token: None, azure: Some(AzureOptions { api_version: Some("2024-02-15-preview".into()), }), }), model: Some("gpt-4".into()), ..Default::default() }).await?; println!("{}", azure_session.send_and_collect("Hello from Azure!", None).await?); // Load from environment: COPILOT_SDK_BYOK_API_KEY, COPILOT_SDK_BYOK_BASE_URL, etc. let env_session = client.create_session(SessionConfig { auto_byok_from_env: true, ..Default::default() }).await?; client.stop().await; Ok(()) } ``` -------------------------------- ### Workspace File Operations Source: https://github.com/copilot-community-sdk/copilot-sdk-rust/blob/main/README.md Demonstrates listing files in the workspace, reading a file's content, and creating a new file. ```rust let files = session.workspace_list_files().await?; let content = session.workspace_read_file("plan.md").await?; session.workspace_create_file("notes.md", "# Notes").await?; ``` -------------------------------- ### Get and Set Session Mode in Rust Source: https://context7.com/copilot-community-sdk/copilot-sdk-rust/llms.txt Switch between `Interactive`, `Plan`, and `Autopilot` session modes. This controls the AI's behavior and interaction style during the session. ```rust use copilot_sdk::{Client, SessionConfig, SessionMode}; #[tokio::main] async fn main() -> copilot_sdk::Result<()> { let client = Client::builder().build()?; client.start().await?; let session = client.create_session(SessionConfig::default()).await?; println!("Initial mode: {:?}", session.get_mode().await?); session.set_mode(SessionMode::Plan).await?; session.send_and_collect("Create a plan to refactor the auth module.", None).await?; session.set_mode(SessionMode::Autopilot).await?; session.send_and_collect("Execute the plan.", None).await?; session.set_mode(SessionMode::Interactive).await?; client.stop().await; Ok(()) } ``` -------------------------------- ### Configure and build a Copilot CLI client Source: https://context7.com/copilot-community-sdk/copilot-sdk-rust/llms.txt Use `Client::builder()` to configure transport, authentication, tool restrictions, and telemetry. The `build()` method constructs the client instance. Requires Rust 1.85+ and an authenticated GitHub Copilot CLI. ```rust use copilot_sdk::{Client, LogLevel, TelemetryConfig}; // Minimal default (auto-discovers copilot CLI in PATH, uses stdio) let client = Client::builder().build()?; ``` ```rust let client = Client::builder() .cli_path("/usr/local/bin/copilot") .use_stdio(true) .log_level(LogLevel::Debug) .cwd("/my/project") .env("CUSTOM_VAR", "value") .github_token("ghp_abc123") // PAT auth (mutually exclusive with cli_url) .auto_start(true) .auto_restart(true) .allow_all_tools(true) // auto-approve all tools … .deny_tool("shell(git push)") // … except these .deny_tool("shell(rm)") .telemetry(TelemetryConfig { otlp_endpoint: Some("http://localhost:4318".into()), exporter_type: Some("otlp-http".into()), source_name: Some("my-app".into()), capture_content: Some(true), file_path: None, }) .build()?; ``` ```rust let client = Client::builder() .cli_url("localhost:9000") // also accepts "http://host:port" or just "9000" .build()?; ``` -------------------------------- ### Create a new Copilot CLI conversation session Source: https://context7.com/copilot-community-sdk/copilot-sdk-rust/llms.txt Use `client.create_session()` to initiate a new conversation. Configure model, streaming, system messages, infinite sessions, and more via `SessionConfig`. Requires an active client connection. ```rust use copilot_sdk::{Client, InfiniteSessionConfig, SessionConfig, SystemMessageConfig, SystemMessageMode}; #[tokio::main] async fn main() -> copilot_sdk::Result<()> { let client = Client::builder().build()?; client.start().await?; let session = client.create_session(SessionConfig { model: Some("gpt-4.1".into()), streaming: true, client_name: Some("my-app".into()), working_directory: Some("/my/project".into()), reasoning_effort: Some("high".into()), system_message: Some(SystemMessageConfig { mode: Some(SystemMessageMode::Append), content: Some("Always respond in Rust.".into()), }), infinite_sessions: Some(InfiniteSessionConfig::with_thresholds(0.8, 0.95)), ..Default::default() }).await?; println!("Session ID: {}", session.session_id()); println!("Workspace: {:?}", session.workspace_path()); client.stop().await; Ok(()) } ``` -------------------------------- ### Get and Set AI Model in Rust Source: https://context7.com/copilot-community-sdk/copilot-sdk-rust/llms.txt Inspect and switch the AI model mid-session, optionally specifying reasoning effort. This allows dynamic control over the AI model used for responses. ```rust use copilot_sdk::{Client, SessionConfig, SetModelOptions}; #[tokio::main] async fn main() -> copilot_sdk::Result<()> { let client = Client::builder().build()?; client.start().await?; let session = client.create_session(SessionConfig::default()).await?; let current = session.get_model().await?; println!("Current model: {current}"); // Switch to a different model with high reasoning effort session.set_model("claude-sonnet-4", Some(SetModelOptions { reasoning_effort: Some("high".into()), })).await?; let text = session.send_and_collect("Solve this logic puzzle step by step: ...", None).await?; println!("{text}"); client.stop().await; Ok(()) } ``` -------------------------------- ### Manage Workspace Files in Rust Session Source: https://context7.com/copilot-community-sdk/copilot-sdk-rust/llms.txt Demonstrates creating, listing, and reading files within a session's workspace. Requires infinite sessions to be enabled. ```rust use copilot_sdk::{Client, InfiniteSessionConfig, SessionConfig}; #[tokio::main] async fn main() -> copilot_sdk::Result<()> { let client = Client::builder().build()?; client.start().await?; let session = client.create_session(SessionConfig { infinite_sessions: Some(InfiniteSessionConfig::enabled()), ..Default::default() }).await?; // Create a workspace file session.workspace_create_file("notes.md", "# Session Notes\n- Started refactor").await?; // List all workspace files let files = session.workspace_list_files().await?; for f in &files { println!("{} ({:?} bytes)", f.path, f.size); } // Read a file back let content = session.workspace_read_file("notes.md").await?; println!("notes.md:\n{content}"); client.stop().await; Ok(()) } ``` -------------------------------- ### Add Copilot SDK to Dependencies Source: https://github.com/copilot-community-sdk/copilot-sdk-rust/blob/main/README.md Add the copilot-sdk and tokio to your Cargo.toml for standard usage. ```toml copilot-sdk = "0.1" tokio = { version = "1", features = ["rt-multi-thread", "macros"] } ``` -------------------------------- ### Client::builder() / ClientBuilder Source: https://context7.com/copilot-community-sdk/copilot-sdk-rust/llms.txt Provides a fluent builder pattern for configuring and constructing a `Client` instance. It supports various configurations for transport (stdio/TCP), authentication, tool management, and telemetry. ```APIDOC ## Client::builder() / ClientBuilder Fluent builder for configuring and constructing a `Client`. Supports stdio or TCP transport, authentication, tool allow/deny lists, auto-start/restart, working directory, custom environment variables, and OpenTelemetry. ### Usage Examples: **Minimal default (auto-discovers copilot CLI in PATH, uses stdio):** ```rust use copilot_sdk::Client; let client = Client::builder().build()?; ``` **Full configuration example:** ```rust use copilot_sdk::{Client, LogLevel, TelemetryConfig}; let client = Client::builder() .cli_path("/usr/local/bin/copilot") .use_stdio(true) .log_level(LogLevel::Debug) .cwd("/my/project") .env("CUSTOM_VAR", "value") .github_token("ghp_abc123") // PAT auth (mutually exclusive with cli_url) .auto_start(true) .auto_restart(true) .allow_all_tools(true) // auto-approve all tools … .deny_tool("shell(git push)") // … except these .deny_tool("shell(rm)") .telemetry(TelemetryConfig { otlp_endpoint: Some("http://localhost:4318".into()), exporter_type: Some("otlp-http".into()), source_name: Some("my-app".into()), capture_content: Some(true), file_path: None, }) .build()?; ``` **TCP mode: connect to an already-running CLI server:** ```rust use copilot_sdk::Client; let client = Client::builder() .cli_url("localhost:9000") // also accepts "http://host:port" or just "9000" .build()?; ``` ``` -------------------------------- ### Enable Automatic Context Compaction Source: https://context7.com/copilot-community-sdk/copilot-sdk-rust/llms.txt Configure `InfiniteSessionConfig` to automatically manage context window size. Listen for `SessionCompactionStart` and `SessionCompactionComplete` events. Manual compaction can be triggered with `session.compact()`. ```rust use copilot_sdk::{Client, InfiniteSessionConfig, SessionConfig, SessionEventData}; #[tokio::main] async fn main() -> copilot_sdk::Result<()> { let client = Client::builder().build()?; client.start().await?; let session = client.create_session(SessionConfig { infinite_sessions: Some(InfiniteSessionConfig::with_thresholds(0.75, 0.90)), ..Default::default() }).await?; // Listen for automatic compaction events let mut events = session.subscribe(); tokio::spawn(async move { while let Ok(event) = events.recv().await { match &event.data { SessionEventData::SessionCompactionStart(_) => println!("[Compaction started]"), SessionEventData::SessionCompactionComplete(_) => println!("[Compaction complete]"), _ => {} } } }); // Run a long session; trigger manual compaction if needed for i in 0..10 { session.send_and_collect(&format!("Step {i}: describe item {i}"), None).await?; } session.compact().await?; // force compaction now client.stop().await; Ok(()) } ``` -------------------------------- ### Build and Test Commands for Copilot SDK Rust Source: https://github.com/copilot-community-sdk/copilot-sdk-rust/blob/main/AGENTS.md Standard commands for building, formatting, linting, and testing the Rust crate. Feature-gated tests require specific flags. ```bash cargo build ``` ```bash cargo test ``` ```bash cargo fmt --all ``` ```bash cargo clippy --all-targets --all-features -- -D warnings ``` ```bash cargo doc --no-deps ``` ```bash cargo test --features e2e -- --test-threads=1 ``` ```bash cargo test --features snapshots --test snapshot_conformance ``` -------------------------------- ### Infinite Sessions - Configuration and Compaction Source: https://github.com/copilot-community-sdk/copilot-sdk-rust/blob/main/README.md Enables and configures infinite sessions for automatic context window management, with support for manual compaction. ```APIDOC ## Infinite Sessions - Configuration and Compaction ### Description Configures and manages infinite sessions, including automatic context window management and manual compaction. ### Method `session.compact().await?` - Triggers manual compaction of the context window. ### Parameters #### `SessionConfig` for `infinite_sessions` - **infinite_sessions** (Option) - Enables infinite session capabilities. - `InfiniteSessionConfig::enabled()` - A static method to enable infinite sessions. ### Example ```rust let config = SessionConfig { infinite_sessions: Some(InfiniteSessionConfig::enabled()), ..Default::default() }; // Trigger manual compaction session.compact().await?; ``` ``` -------------------------------- ### Run Snapshot Conformance Tests Source: https://github.com/copilot-community-sdk/copilot-sdk-rust/blob/main/README.md Execute snapshot conformance tests, which are optional and compare behavior against upstream YAML snapshots. Ensure `COPILOT_SDK_RUST_SNAPSHOT_DIR` or `UPSTREAM_SNAPSHOTS` are set if auto-detection fails. ```bash cargo test --features snapshots --test snapshot_conformance ``` -------------------------------- ### Configure OpenTelemetry Integration Source: https://github.com/copilot-community-sdk/copilot-sdk-rust/blob/main/README.md Set up distributed tracing for the CLI process by configuring the TelemetryConfig with OTLP endpoint and exporter details. ```rust let client = Client::builder() .telemetry(TelemetryConfig { otlp_endpoint: Some("http://localhost:4318".into()), exporter_type: Some("otlp-http".into()), source_name: Some("my-app".into()), capture_content: Some(true), file_path: None, }) .build()?; ``` -------------------------------- ### Session::compact / InfiniteSessionConfig Source: https://context7.com/copilot-community-sdk/copilot-sdk-rust/llms.txt Enable automatic context compaction to prevent context-window exhaustion. `compact()` triggers manual compaction, while `InfiniteSessionConfig` allows configuration of thresholds for automatic compaction. ```APIDOC ## `Session::compact` / `InfiniteSessionConfig` Enable automatic context compaction to prevent context-window exhaustion. ### Description - `compact()`: Manually triggers context compaction for the session. - `InfiniteSessionConfig`: A configuration struct to set thresholds for automatic context compaction. Use `InfiniteSessionConfig::with_thresholds(low_threshold, high_threshold)` to initialize. ### Usage Example ```rust use copilot_sdk::{Client, InfiniteSessionConfig, SessionConfig, SessionEventData}; #[tokio::main] async fn main() -> copilot_sdk::Result<()> { let client = Client::builder().build()?; client.start().await?; let session = client.create_session(SessionConfig { infinite_sessions: Some(InfiniteSessionConfig::with_thresholds(0.75, 0.90)), ..Default::default() }).await?; // Listen for automatic compaction events let mut events = session.subscribe(); tokio::spawn(async move { while let Ok(event) = events.recv().await { match &event.data { SessionEventData::SessionCompactionStart(_) => println!("[Compaction started]"), SessionEventData::SessionCompactionComplete(_) => println!("[Compaction complete]"), _ => {{}} } } }); // Run a long session; trigger manual compaction if needed for i in 0..10 { session.send_and_collect(&format!("Step {i}: describe item {i}"), None).await?; } session.compact().await?; // force compaction now client.stop().await; Ok(()) } ``` ``` -------------------------------- ### Spawn Fleet of Agents in Rust Session Source: https://context7.com/copilot-community-sdk/copilot-sdk-rust/llms.txt Shows how to spawn a fleet of parallel agents to perform tasks concurrently. Events like agent start/completion are received via a subscription channel. ```rust use copilot_sdk::{Client, FleetStartOptions, SessionConfig}; #[tokio::main] async fn main() -> copilot_sdk::Result<()> { let client = Client::builder().build()?; client.start().await?; let session = client.create_session(SessionConfig::default()).await?; session.start_fleet(Some(FleetStartOptions { prompt: Some("Run the full test suite and summarize failures.".into()), })).await?; // Fleet events (CustomAgentStarted, CustomAgentCompleted, etc.) arrive on the event channel let mut events = session.subscribe(); while let Ok(event) = events.recv().await { use copilot_sdk::SessionEventData; match &event.data { SessionEventData::CustomAgentStarted(d) => println!("Agent started: {:?}", d.agent_id), SessionEventData::CustomAgentCompleted(d) => println!("Agent done: {:?}", d.agent_id), SessionEventData::SessionIdle(_) => break, _ => {} } } client.stop().await; Ok(()) } ``` -------------------------------- ### Run Unit Tests Source: https://github.com/copilot-community-sdk/copilot-sdk-rust/blob/main/README.md Execute all unit tests for the project using the `cargo test` command. ```bash cargo test ``` -------------------------------- ### Manage Custom Agents Source: https://github.com/copilot-community-sdk/copilot-sdk-rust/blob/main/README.md Demonstrates listing available agents, selecting a specific agent, and deselecting the current agent. ```rust let agents = session.list_agents().await?; session.select_agent("code-reviewer").await?; session.deselect_agent().await?; ``` -------------------------------- ### Send Messages and Collect Responses with Rust Copilot SDK Source: https://context7.com/copilot-community-sdk/copilot-sdk-rust/llms.txt Demonstrates sending messages to a session using different methods: `send_and_collect` for full response, `send` for message ID, and `send_and_wait` for the last assistant message. Supports simple strings and complex options with attachments. ```rust use copilot_sdk::{Client, MessageOptions, SessionConfig, UserMessageAttachment, AttachmentType}; use std::time::Duration; #[tokio::main] async fn main() -> copilot_sdk::Result<()> { let client = Client::builder().build()?; client.start().await?; let session = client.create_session(SessionConfig::default()).await?; // Simple string shorthand let text = session.send_and_collect("What is 2 + 2?", None).await?; println!("{text}"); // With file attachment and custom timeout let msg_id = session.send(MessageOptions { prompt: "Explain this file.".into(), attachments: Some(vec![UserMessageAttachment { attachment_type: AttachmentType::File, path: "src/main.rs".into(), display_name: "main.rs".into(), }]), mode: None, }).await?; println!("Message ID: {msg_id}"); let response = session.wait_for_idle(Some(Duration::from_secs(120))).await?; if let Some(event) = response { println!("{event:?}"); } client.stop().await; Ok(()) } ``` -------------------------------- ### Session Workspace File Management Source: https://context7.com/copilot-community-sdk/copilot-sdk-rust/llms.txt Demonstrates how to create, list, and read files within the session's workspace directory. This feature is available for infinite sessions with a configured workspace path. ```APIDOC ## `Session::workspace_list_files` / `Session::workspace_read_file` / `Session::workspace_create_file` Manage files in the session's workspace directory (available for infinite sessions with a `workspace_path`). ### Usage Example ```rust use copilot_sdk::{Client, InfiniteSessionConfig, SessionConfig}; #[tokio::main] async fn main() -> copilot_sdk::Result<()> { let client = Client::builder().build()?; client.start().await?; let session = client.create_session(SessionConfig { infinite_sessions: Some(InfiniteSessionConfig::enabled()), ..Default::default() }).await?; // Create a workspace file session.workspace_create_file("notes.md", "# Session Notes\n- Started refactor").await?; // List all workspace files let files = session.workspace_list_files().await?; for f in &files { println!("{} ({:?} bytes)", f.path, f.size); } // Read a file back let content = session.workspace_read_file("notes.md").await?; println!("notes.md:\n{content}"); client.stop().await; Ok(()) } ``` ``` -------------------------------- ### Discover and Activate Agents in a Session Source: https://context7.com/copilot-community-sdk/copilot-sdk-rust/llms.txt Use `list_agents` to discover available agents, `select_agent` to activate one, and `deselect_agent` to deactivate it. Custom agents can be configured with prompts, display names, descriptions, and tools. ```rust use copilot_sdk::{Client, CustomAgentConfig, SessionConfig}; use std::collections::HashMap; #[tokio::main] async fn main() -> copilot_sdk::Result<()> { let client = Client::builder().build()?; client.start().await?; let session = client.create_session(SessionConfig { custom_agents: Some(vec![CustomAgentConfig { name: "code-reviewer".into(), prompt: "You are a strict code reviewer. Point out all issues.".into(), display_name: Some("Code Reviewer".into()), description: Some("Reviews code for quality and correctness".into()), tools: Some(vec!["read_file".into()]), mcp_servers: None, infer: None, }]), ..Default::default() }).await?; let agents = session.list_agents().await?; for a in &agents { println!("Agent: {} — {:?}", a.name, a.description); } session.select_agent("code-reviewer").await?; let review = session.send_and_collect("Review my latest commit.", None).await?; println!("{review}"); session.deselect_agent().await?; client.stop().await; Ok(()) } ``` -------------------------------- ### Configure BYOK with Custom Model Listing Source: https://github.com/copilot-community-sdk/copilot-sdk-rust/blob/main/README.md Set up the client to use your own API keys with a custom model listing callback. This is useful for integrating with compatible providers that require specific API key configurations. ```rust let client = Client::builder() .on_list_models(|| async { Ok(vec![ModelInfo { /* ... */ }]) }) .build()?; let config = SessionConfig { provider: Some(ProviderConfig { base_url: "https://api.openai.com/v1".into(), api_key: Some("sk-...".into()), ..Default::default() }), auto_byok_from_env: true, ..Default::default() }; ``` -------------------------------- ### Handle Copilot SDK Errors Source: https://context7.com/copilot-community-sdk/copilot-sdk-rust/llms.txt Demonstrates how to handle various errors that can occur during SDK operations, including timeouts, protocol mismatches, JSON-RPC errors, and tool-specific errors. ```rust use copilot_sdk::{Client, CopilotError}; use std::time::Duration; #[tokio::main] async fn main() { let client = Client::builder().build().unwrap(); client.start().await.unwrap(); let session = client.create_session(Default::default()).await.unwrap(); match session.send_and_collect("Query", Some(Duration::from_secs(5))).await { Ok(text) => println!("{text}"), Err(CopilotError::Timeout(d)) => eprintln!("Timed out after {:?}", d), Err(CopilotError::ProtocolMismatch { min, max, actual }) => eprintln!("Protocol {} not in [{},{}]", actual, min, max), Err(CopilotError::JsonRpc { code, message, .. }) => eprintln!("RPC error {}: {message}", code), Err(CopilotError::ToolNotFound(name)) => eprintln!("Tool '{}' is not registered", name), Err(e) if e.is_fatal() => eprintln!("Fatal error (reconnect needed): {e}"), Err(e) => eprintln!("Error: {e}"), } client.stop().await; } ``` -------------------------------- ### Session::register_tool_with_handler / Tool builder Source: https://context7.com/copilot-community-sdk/copilot-sdk-rust/llms.txt Register custom tools that the assistant can invoke. Use the `Tool` builder to define the name, description, and JSON Schema for parameters. The handler receives the tool name and arguments as `serde_json::Value` and returns a `ToolResultObject`. ```APIDOC ## `Session::register_tool_with_handler` / `Tool` builder Register custom tools that the assistant can invoke. Use the `Tool` builder to define the name, description, and JSON Schema for parameters. The handler receives the tool name and arguments as `serde_json::Value` and returns a `ToolResultObject`. ```rust use copilot_sdk::{Client, SessionConfig, SessionEventData, Tool, ToolHandler, ToolResultObject}; use std::sync::Arc; #[tokio::main] async fn main() -> copilot_sdk::Result<()> { let client = Client::builder().build()?; client.start().await?; let weather_tool = Tool::new("get_weather") .description("Get the current weather for a location") .parameter("location", "string", "City name", true) .parameter("unit", "string", "celsius or fahrenheit", false) .skip_permission(true); // no approval prompt let config = SessionConfig { tools: vec![weather_tool.clone()], ..Default::default() }; let session = client.create_session(config).await?; let handler: ToolHandler = Arc::new(|_name, args| { let location = args.get("location").and_then(|v| v.as_str()).unwrap_or("Unknown"); let unit = args.get("unit").and_then(|v| v.as_str()).unwrap_or("fahrenheit"); let (temp, sym) = if unit == "celsius" { (22, "°C") } else { (72, "°F") }; ToolResultObject::text(format!("Weather in {location}: sunny, {temp}{sym}")) }); session.register_tool_with_handler(weather_tool, Some(handler)).await; let mut events = session.subscribe(); session.send("What's the weather in Paris?").await?; while let Ok(event) = events.recv().await { match &event.data { SessionEventData::ToolExecutionStart(t) => println!("[Calling tool: {t.tool_name}]"); SessionEventData::AssistantMessage(m) => { println!("{m.content}"); } SessionEventData::SessionIdle(_) => break, _ => {{}} } } client.stop().await; Ok(()) } ``` ``` -------------------------------- ### Format Code with Cargo Source: https://github.com/copilot-community-sdk/copilot-sdk-rust/blob/main/README.md Run `cargo fmt` to format all code within the project according to standard Rust formatting conventions. ```bash cargo fmt --all ``` -------------------------------- ### OpenTelemetry Integration Source: https://github.com/copilot-community-sdk/copilot-sdk-rust/blob/main/README.md Demonstrates how to configure OpenTelemetry for distributed tracing within the Copilot CLI process. ```APIDOC ## OpenTelemetry Integration ### Description Configures OpenTelemetry for distributed tracing of the Copilot CLI process. ### Method `Client::builder().telemetry(TelemetryConfig).build()?` ### Parameters #### `TelemetryConfig` Parameters - **otlp_endpoint** (Option) - The OTLP endpoint URL (e.g., "http://localhost:4318"). - **exporter_type** (Option) - The type of exporter to use (e.g., "otlp-http"). - **source_name** (Option) - The name of the telemetry source. - **capture_content** (Option) - Whether to capture content in traces. - **file_path** (Option) - Path for file-based export (if applicable). ### Example ```rust let client = Client::builder() .telemetry(TelemetryConfig { otlp_endpoint: Some("http://localhost:4318".into()), exporter_type: Some("otlp-http".into()), source_name: Some("my-app".into()), capture_content: Some(true), file_path: None, }) .build()?; ``` ``` -------------------------------- ### Client::get_quota and Client::tools_list Source: https://context7.com/copilot-community-sdk/copilot-sdk-rust/llms.txt Retrieve account quota information and a list of available server-side tools. `get_quota` provides details about usage limits and reset times, while `tools_list` can filter tools by model. ```APIDOC ## `Client::get_quota` / `Client::tools_list` Account quota introspection and server-side tool enumeration. ### Description Retrieves account quota information and a list of available server-side tools. `get_quota` provides details about usage limits and reset times, while `tools_list` can filter tools by model. ### Method - `get_quota()`: Retrieves account quota. - `tools_list(model: Option<&str>)`: Retrieves a list of tools, optionally filtered by model. ### Response - `get_quota()` returns a struct containing quota details. - `tools_list()` returns a struct containing a list of tools. ``` -------------------------------- ### Session::get_mode / Session::set_mode Source: https://context7.com/copilot-community-sdk/copilot-sdk-rust/llms.txt Enables switching between different session modes: `Interactive`, `Plan`, and `Autopilot`. ```APIDOC ## `Session::get_mode` / `Session::set_mode` Switch between `Interactive`, `Plan`, and `Autopilot` session modes. ```rust use copilot_sdk::{Client, SessionConfig, SessionMode}; #[tokio::main] async fn main() -> copilot_sdk::Result<()> { let client = Client::builder().build()?; client.start().await?; let session = client.create_session(SessionConfig::default()).await?; println!("Initial mode: {:?}", session.get_mode().await?); session.set_mode(SessionMode::Plan).await?; session.send_and_collect("Create a plan to refactor the auth module.", None).await?; session.set_mode(SessionMode::Autopilot).await?; session.send_and_collect("Execute the plan.", None).await?; session.set_mode(SessionMode::Interactive).await?; client.stop().await; Ok(()) } ``` ``` -------------------------------- ### Custom Tools - Registration Source: https://github.com/copilot-community-sdk/copilot-sdk-rust/blob/main/README.md Allows registering custom tools that the assistant can invoke, including defining parameters and handling permissions. ```APIDOC ## Custom Tools - Registration ### Description Registers custom tools that the assistant can invoke, with options for defining parameters and controlling permissions. ### Method `session.register_tool_with_handler(tool, handler)` ### Parameters #### `tool` Parameters - **Tool::new(name)** - Creates a new tool with a given name. - `.description(description)` - Sets the tool's description. - `.parameter(name, type, description, required)` - Adds a parameter to the tool. - `.skip_permission(skip)` - Controls whether permission skipping is enabled for the tool. #### `handler` Parameter - **handler** (Option) - A function or closure to handle the tool invocation. ### Example ```rust let tool = Tool::new("get_weather") .description("Get current weather") .parameter("city", "string", "City name", true) .skip_permission(true); session.register_tool_with_handler(tool, Some(handler)).await; ``` ```