Skip to main content

github_copilot_sdk/
session.rs

1use std::collections::HashMap;
2use std::path::{Path, PathBuf};
3use std::sync::Arc;
4use std::time::{Duration, Instant};
5
6use parking_lot::Mutex as ParkingLotMutex;
7use serde_json::Value;
8use tokio::sync::oneshot;
9use tokio::task::JoinHandle;
10use tokio_util::sync::CancellationToken;
11use tracing::{Instrument, warn};
12
13use crate::canvas::CanvasHandler;
14use crate::generated::api_types::{
15    LogRequest, ModelSwitchToRequest, OpenCanvasInstance, PermissionDecisionRequest,
16    RegisterEventInterestParams, ToolsGetCurrentMetadataResult, rpc_methods,
17};
18use crate::generated::session_events::{
19    CommandExecuteData, ElicitationRequestedData, ExternalToolRequestedData, McpOauthRequiredData,
20    SessionCanvasClosedData, SessionErrorData, SessionEventType,
21};
22use crate::handler::{
23    AutoModeSwitchHandler, AutoModeSwitchResponse, ElicitationHandler, ExitPlanModeHandler,
24    McpAuthHandler, McpAuthRequest, McpAuthResult, PermissionHandler, PermissionResult,
25    UserInputHandler, UserInputResponse,
26};
27use crate::hooks::SessionHooks;
28use crate::provider_token::BearerTokenProvider;
29use crate::session_fs::SessionFsProvider;
30use crate::trace_context::inject_trace_context;
31use crate::transforms::SystemMessageTransform;
32use crate::types::{
33    CommandContext, CommandDefinition, CommandHandler, CreateSessionResult, ElicitationRequest,
34    ElicitationResult, ExitPlanModeData, GetMessagesResponse, MessageOptions,
35    PermissionRequestData, RequestId, ResumeSessionConfig, ResumeSessionResult, SectionOverride,
36    SessionCapabilities, SessionConfig, SessionEvent, SessionId, SetModelOptions,
37    SystemMessageConfig, ToolInvocation, ToolResult, ToolResultExpanded, TraceContext,
38    UiInputOptions, ensure_attachment_display_names,
39};
40use crate::{
41    Client, Error, ErrorKind, JsonRpcResponse, SessionErrorKind, SessionEventNotification,
42    error_codes,
43};
44
45/// Fixed name of the runtime's built-in tool-search tool. A client can replace
46/// its behavior by registering a tool with this exact name and
47/// `overrides_built_in_tool` set to `true`.
48const TOOL_SEARCH_TOOL_NAME: &str = "tool_search_tool";
49
50/// Bundle of the per-session callbacks the SDK dispatches to. Built from a
51/// [`SessionConfig`] / [`ResumeSessionConfig`] at
52/// [`Client::create_session`] / [`Client::resume_session`] time. Each
53/// field is `None` (or an empty map for tools) when the caller didn't
54/// install a handler -- in that case the SDK skips dispatch for that
55/// event type. The wire flags on `session.create` / `session.resume`
56/// are derived from these fields.
57#[derive(Clone)]
58pub(crate) struct SessionHandlers {
59    pub permission: Option<Arc<dyn PermissionHandler>>,
60    pub managed_settings_enabled: bool,
61    pub elicitation: Option<Arc<dyn ElicitationHandler>>,
62    pub mcp_auth: Option<Arc<dyn McpAuthHandler>>,
63    pub user_input: Option<Arc<dyn UserInputHandler>>,
64    pub exit_plan_mode: Option<Arc<dyn ExitPlanModeHandler>>,
65    pub auto_mode_switch: Option<Arc<dyn AutoModeSwitchHandler>>,
66    pub tools: Arc<HashMap<String, Arc<dyn crate::tool::ToolHandler>>>,
67}
68
69fn has_managed_settings(
70    enable_managed_settings: Option<bool>,
71    managed_settings: Option<&crate::types::ManagedSettings>,
72) -> bool {
73    enable_managed_settings == Some(true) || managed_settings.is_some()
74}
75
76/// Shared state between a [`Session`] and its event loop, used by [`Session::send_and_wait`].
77struct IdleWaiter {
78    tx: oneshot::Sender<Result<Option<SessionEvent>, Error>>,
79    last_assistant_message: Option<SessionEvent>,
80    started_at: Instant,
81    first_assistant_message_seen: bool,
82}
83
84/// RAII guard that clears the [`Session::idle_waiter`] slot on drop. Used
85/// by [`Session::send_and_wait`] to ensure the slot doesn't leak if the
86/// caller's future is cancelled (outer `tokio::time::timeout` / `select!`
87/// / dropped JoinHandle). Synchronous clear via `parking_lot::Mutex` —
88/// no async drop needed.
89///
90/// Without this, an outer cancellation between "install waiter" and
91/// "drain channel" would leave the slot occupied, causing all subsequent
92/// `send` and `send_and_wait` calls on the session to return
93/// [`SendWhileWaiting`](SessionErrorKind::SendWhileWaiting). Closes RFD-400
94/// review finding #2.
95struct WaiterGuard {
96    slot: Arc<ParkingLotMutex<Option<IdleWaiter>>>,
97}
98
99impl Drop for WaiterGuard {
100    fn drop(&mut self) {
101        self.slot.lock().take();
102    }
103}
104
105struct PendingSessionRegistration {
106    client: Client,
107    session_id: SessionId,
108    shutdown: CancellationToken,
109    disarmed: bool,
110}
111
112impl PendingSessionRegistration {
113    fn new(client: Client, session_id: SessionId, shutdown: CancellationToken) -> Self {
114        Self {
115            client,
116            session_id,
117            shutdown,
118            disarmed: false,
119        }
120    }
121
122    async fn cleanup(mut self, event_loop: JoinHandle<()>) {
123        self.shutdown.cancel();
124        let _ = event_loop.await;
125        self.client.unregister_session(&self.session_id);
126        self.disarmed = true;
127    }
128
129    fn disarm(&mut self) {
130        self.disarmed = true;
131    }
132}
133
134impl Drop for PendingSessionRegistration {
135    fn drop(&mut self) {
136        if !self.disarmed {
137            self.shutdown.cancel();
138            self.client.unregister_session(&self.session_id);
139        }
140    }
141}
142
143/// A session on a GitHub Copilot CLI server.
144///
145/// Created via [`Client::create_session`] or [`Client::resume_session`].
146/// Owns an internal event loop that dispatches events to the per-callback
147/// handlers installed on the session config.
148///
149/// Protocol methods (`send`, `get_events`, `abort`, etc.) automatically
150/// inject the session ID into RPC params.
151///
152/// Call [`destroy`](Self::destroy) for graceful cleanup (RPC + local). If dropped
153/// without calling `destroy`, the `Drop` impl aborts the event loop and
154/// unregisters from the router as a best-effort safety net.
155pub struct Session {
156    id: SessionId,
157    cwd: PathBuf,
158    workspace_path: Option<PathBuf>,
159    remote_url: Option<String>,
160    client: Client,
161    /// Handle to the spawned event-loop task. Sync `parking_lot::Mutex`
162    /// because the lock is never held across an `.await` and the `Drop`
163    /// impl needs to take the handle synchronously without `try_lock`
164    /// fallibility.
165    event_loop: ParkingLotMutex<Option<JoinHandle<()>>>,
166    /// Cooperative shutdown signal for the event loop. The loop selects
167    /// on [`shutdown.cancelled()`](CancellationToken::cancelled) alongside
168    /// its inbound channels; [`Session::stop_event_loop`] and [`Drop`]
169    /// both call [`cancel()`](CancellationToken::cancel) to ask the loop
170    /// to exit between iterations rather than aborting the task (which
171    /// can land at any await point and leave the session mid-protocol).
172    /// See RFD-400 review finding #3.
173    ///
174    /// `CancellationToken` is the canonical signalling primitive in
175    /// `tokio_util`; it is what `tonic` uses for the equivalent task-
176    /// coordination case. Advanced consumers can obtain a child token
177    /// via [`Session::cancellation_token`] to bind their own work to
178    /// the session lifetime.
179    shutdown: CancellationToken,
180    /// Only populated while a `send_and_wait` call is in flight.
181    ///
182    /// Sync `parking_lot::Mutex` because the lock is never held across an
183    /// `.await`, and synchronous access lets the `WaiterGuard` RAII helper
184    /// in `send_and_wait` clear the slot from a `Drop` impl on caller-side
185    /// cancellation. See RFD-400 review (cancel-safety hardening).
186    idle_waiter: Arc<ParkingLotMutex<Option<IdleWaiter>>>,
187    /// Capabilities negotiated with the CLI, updated on `capabilities.changed` events.
188    capabilities: Arc<parking_lot::RwLock<SessionCapabilities>>,
189    /// Canvas instances currently known to be open for this session.
190    open_canvases: Arc<parking_lot::RwLock<Vec<OpenCanvasInstance>>>,
191    /// Broadcast channel for runtime event subscribers — see [`Session::subscribe`].
192    event_tx: tokio::sync::broadcast::Sender<SessionEvent>,
193}
194
195impl Session {
196    /// Session ID assigned by the CLI.
197    pub fn id(&self) -> &SessionId {
198        &self.id
199    }
200
201    /// Working directory of the CLI process.
202    pub fn cwd(&self) -> &PathBuf {
203        &self.cwd
204    }
205
206    /// Workspace directory for the session (if using infinite sessions).
207    pub fn workspace_path(&self) -> Option<&Path> {
208        self.workspace_path.as_deref()
209    }
210
211    /// Remote session URL, if the session is running remotely.
212    pub fn remote_url(&self) -> Option<&str> {
213        self.remote_url.as_deref()
214    }
215
216    /// Session capabilities negotiated with the CLI.
217    ///
218    /// Capabilities are set during session creation and updated at runtime
219    /// via `capabilities.changed` events.
220    pub fn capabilities(&self) -> SessionCapabilities {
221        self.capabilities.read().clone()
222    }
223
224    /// Open canvas instances reported by the most recent `session.resume`
225    /// response or surfaced by inbound `canvas.opened` events.
226    pub fn open_canvases(&self) -> Vec<OpenCanvasInstance> {
227        self.open_canvases.read().clone()
228    }
229
230    /// Returns a [`CancellationToken`] that fires when this session shuts
231    /// down (via [`Session::stop_event_loop`], [`Session::destroy`], or
232    /// [`Drop`]).
233    ///
234    /// Use this to bind an external task's lifetime to the session — when
235    /// the session shuts down, awaiting [`cancelled()`](CancellationToken::cancelled)
236    /// resolves so cooperative consumers can stop cleanly.
237    ///
238    /// The returned handle is a *child* token: calling
239    /// [`cancel()`](CancellationToken::cancel) on it cancels only the
240    /// caller's child, not the session itself. To cancel the session, call
241    /// [`Session::stop_event_loop`].
242    ///
243    /// # Example
244    ///
245    /// ```no_run
246    /// # async fn example(session: github_copilot_sdk::session::Session) {
247    /// let token = session.cancellation_token();
248    /// tokio::select! {
249    ///     _ = token.cancelled() => println!("session shut down"),
250    ///     _ = tokio::time::sleep(std::time::Duration::from_secs(60)) => {
251    ///         println!("60s elapsed, session still alive");
252    ///     }
253    /// }
254    /// # }
255    /// ```
256    pub fn cancellation_token(&self) -> CancellationToken {
257        self.shutdown.child_token()
258    }
259
260    /// Subscribe to events for this session.
261    ///
262    /// Returns an [`EventSubscription`](crate::subscription::EventSubscription)
263    /// that yields every [`SessionEvent`] dispatched on this session's
264    /// event loop. Drop the value to unsubscribe; there is no separate
265    /// cancel handle.
266    ///
267    /// **Observe-only.** Subscribers receive a clone of every
268    /// [`SessionEvent`] but cannot influence permission decisions, tool
269    /// results, or anything else that requires returning a value. Those
270    /// remain the responsibility of the per-callback handlers passed via
271    /// [`SessionConfig`]'s `with_*_handler`
272    /// builder methods.
273    ///
274    /// The returned handle implements both an inherent
275    /// [`recv`](crate::subscription::EventSubscription::recv) method and
276    /// [`Stream`](tokio_stream::Stream), so callers can use a `while let`
277    /// loop or any combinator from `tokio_stream::StreamExt` /
278    /// `futures::StreamExt`.
279    ///
280    /// Each subscriber maintains its own queue. If a consumer cannot keep
281    /// up, the oldest events are dropped and `recv` returns
282    /// [`RecvErrorKind::Lagged`](crate::subscription::RecvErrorKind::Lagged)
283    /// reporting the count of skipped events. Slow consumers do not block
284    /// the session's event loop.
285    ///
286    /// # Example
287    ///
288    /// ```no_run
289    /// # async fn example(session: github_copilot_sdk::session::Session) {
290    /// let mut events = session.subscribe();
291    /// tokio::spawn(async move {
292    ///     while let Ok(event) = events.recv().await {
293    ///         println!("[{}] event {}", event.id, event.event_type);
294    ///     }
295    /// });
296    /// # }
297    /// ```
298    pub fn subscribe(&self) -> crate::subscription::EventSubscription {
299        crate::subscription::EventSubscription::new(self.event_tx.subscribe())
300    }
301
302    /// The underlying Client (for advanced use cases).
303    pub fn client(&self) -> &Client {
304        &self.client
305    }
306
307    /// Typed RPC namespace for this session.
308    ///
309    /// Every protocol method lives here under its schema-aligned path —
310    /// e.g. `session.rpc().workspaces().list_files()`. Wire method names
311    /// and request/response types are generated from the protocol schema,
312    /// so the typed namespace can't drift from the wire contract.
313    ///
314    /// The hand-authored helpers on [`Session`] delegate to this namespace
315    /// and remain the recommended entry point for everyday use; reach for
316    /// `rpc()` when you want a method without a hand-written wrapper.
317    pub fn rpc(&self) -> crate::generated::rpc::SessionRpc<'_> {
318        crate::generated::rpc::SessionRpc { session: self }
319    }
320
321    /// Stop the internal event loop. Called automatically on [`destroy`](Self::destroy).
322    ///
323    /// Cooperative: signals shutdown via the session's [`CancellationToken`]
324    /// and awaits the loop's natural exit rather than aborting the task.
325    /// Any in-flight handler (permission callback, tool call, elicitation
326    /// response) completes before the loop exits, so the CLI never sees a
327    /// half-handled request. See RFD-400 review finding #3.
328    pub async fn stop_event_loop(&self) {
329        self.shutdown.cancel();
330        let handle = self.event_loop.lock().take();
331        if let Some(handle) = handle {
332            let _ = handle.await;
333        }
334        // Fail any pending send_and_wait so it returns immediately.
335        if let Some(waiter) = self.idle_waiter.lock().take() {
336            let _ = waiter.tx.send(Err(
337                ErrorKind::Session(SessionErrorKind::EventLoopClosed).into()
338            ));
339        }
340    }
341
342    /// Send a user message to the agent.
343    ///
344    /// Accepts anything convertible to [`MessageOptions`] — pass a `&str` for the
345    /// trivial case, or build a `MessageOptions` for mode/attachments. The
346    /// `wait_timeout` field on `MessageOptions` is ignored here (use
347    /// [`send_and_wait`](Self::send_and_wait) if you need to wait).
348    ///
349    /// Returns the assigned message ID, which can be used to correlate the
350    /// send with later [`SessionEvent`]s emitted in
351    /// response (assistant messages, tool requests, etc.).
352    ///
353    /// Returns an error if a [`send_and_wait`](Self::send_and_wait) call is
354    /// currently in flight, since the plain send would race with the waiter.
355    ///
356    /// # Cancel safety
357    ///
358    /// **Cancel-safe.** The underlying `session.send` RPC is dispatched
359    /// through the writer-actor (see [`Client::call`](crate::Client::call)),
360    /// so dropping this future after the actor has committed to writing
361    /// will not produce a partial frame on the wire. If the caller's
362    /// future is dropped between "frame enqueued" and "response received",
363    /// the message has already landed on the wire — the agent will process
364    /// it and emit events normally; the caller just won't see the returned
365    /// message ID.
366    pub async fn send(&self, opts: impl Into<MessageOptions>) -> Result<String, Error> {
367        if self.idle_waiter.lock().is_some() {
368            return Err(ErrorKind::Session(SessionErrorKind::SendWhileWaiting).into());
369        }
370        self.send_inner(opts.into()).await
371    }
372
373    async fn send_inner(&self, opts: MessageOptions) -> Result<String, Error> {
374        let mut params = serde_json::json!({
375            "sessionId": self.id,
376            "prompt": opts.prompt,
377        });
378        if let Some(m) = opts.mode {
379            params["mode"] = serde_json::to_value(m)?;
380        }
381        if let Some(am) = opts.agent_mode {
382            params["agentMode"] = serde_json::to_value(am)?;
383        }
384        if let Some(mut a) = opts.attachments {
385            ensure_attachment_display_names(&mut a);
386            params["attachments"] = serde_json::to_value(a)?;
387        }
388        if let Some(headers) = opts.request_headers
389            && !headers.is_empty()
390        {
391            params["requestHeaders"] = serde_json::to_value(headers)?;
392        }
393        if let Some(display_prompt) = opts.display_prompt {
394            params["displayPrompt"] = serde_json::to_value(display_prompt)?;
395        }
396        let trace_ctx = if opts.traceparent.is_some() || opts.tracestate.is_some() {
397            TraceContext {
398                traceparent: opts.traceparent,
399                tracestate: opts.tracestate,
400            }
401        } else {
402            self.client.resolve_trace_context().await
403        };
404        inject_trace_context(&mut params, &trace_ctx);
405        let rpc_start = Instant::now();
406        let result = self.client.call("session.send", Some(params)).await?;
407        let message_id = result
408            .get("messageId")
409            .and_then(|v| v.as_str())
410            .map(|s| s.to_string())
411            .unwrap_or_default();
412        tracing::debug!(
413            elapsed_ms = rpc_start.elapsed().as_millis(),
414            session_id = %self.id,
415            message_id = %message_id,
416            "Session::send completed successfully"
417        );
418        Ok(message_id)
419    }
420
421    /// Send a user message and wait for the agent to finish processing.
422    ///
423    /// Accepts anything convertible to [`MessageOptions`] — pass a `&str` for the
424    /// trivial case, or build a `MessageOptions` for mode/attachments/timeout.
425    /// Blocks until `session.idle` (success) or `session.error` (failure),
426    /// returning the last `assistant.message` event captured during streaming.
427    /// Times out after `MessageOptions::wait_timeout` (default 60 seconds).
428    ///
429    /// Only one `send_and_wait` call may be active per session at a time.
430    /// Calling [`send`](Self::send) while a `send_and_wait`
431    /// is in flight will also return an error.
432    ///
433    /// # Cancel safety
434    ///
435    /// **Cancel-safe.** A `WaiterGuard` clears the in-flight slot on every
436    /// exit path (success, internal failure, internal timeout, *and*
437    /// external cancellation via `tokio::time::timeout` / `select!` /
438    /// dropped JoinHandle). Subsequent `send` and `send_and_wait` calls on
439    /// this session will succeed normally — the slot is never leaked.
440    pub async fn send_and_wait(
441        &self,
442        opts: impl Into<MessageOptions>,
443    ) -> Result<Option<SessionEvent>, Error> {
444        let total_start = Instant::now();
445        let opts = opts.into();
446        let timeout_duration = opts.wait_timeout.unwrap_or(Duration::from_secs(60));
447        let (tx, rx) = oneshot::channel();
448
449        {
450            let mut guard = self.idle_waiter.lock();
451            if guard.is_some() {
452                return Err(ErrorKind::Session(SessionErrorKind::SendWhileWaiting).into());
453            }
454            *guard = Some(IdleWaiter {
455                tx,
456                last_assistant_message: None,
457                started_at: total_start,
458                first_assistant_message_seen: false,
459            });
460        }
461
462        // RAII: clears the idle_waiter slot on every exit path, including
463        // external cancellation (caller's outer `select!` / `timeout` /
464        // dropped future). Without this, an outer cancellation would leak
465        // the slot and brick subsequent `send`/`send_and_wait` calls.
466        let _waiter_guard = WaiterGuard {
467            slot: self.idle_waiter.clone(),
468        };
469
470        let result = tokio::time::timeout(timeout_duration, async {
471            self.send_inner(opts).await?;
472            match rx.await {
473                Ok(result) => result,
474                Err(_) => Err(ErrorKind::Session(SessionErrorKind::EventLoopClosed).into()),
475            }
476        })
477        .await;
478
479        match result {
480            Ok(inner) => {
481                tracing::debug!(
482                    elapsed_ms = total_start.elapsed().as_millis(),
483                    session_id = %self.id,
484                    completed_by = if inner.is_ok() { "idle" } else { "error" },
485                    "Session::send_and_wait complete"
486                );
487                inner
488            }
489            Err(_) => {
490                tracing::warn!(
491                    elapsed_ms = total_start.elapsed().as_millis(),
492                    session_id = %self.id,
493                    completed_by = "timeout",
494                    "Session::send_and_wait failed"
495                );
496                Err(ErrorKind::Session(SessionErrorKind::Timeout(timeout_duration)).into())
497            }
498        }
499    }
500
501    /// Retrieve the session's timeline events.
502    pub async fn get_events(&self) -> Result<Vec<SessionEvent>, Error> {
503        let result = self
504            .client
505            .call(
506                "session.getMessages",
507                Some(serde_json::json!({ "sessionId": self.id })),
508            )
509            .await?;
510        let response: GetMessagesResponse = serde_json::from_value(result)?;
511        Ok(response.events)
512    }
513
514    /// Deprecated alias for [`get_events`](Self::get_events).
515    #[deprecated(since = "0.1.0", note = "Use `get_events()` instead")]
516    pub async fn get_messages(&self) -> Result<Vec<SessionEvent>, Error> {
517        self.get_events().await
518    }
519
520    /// Abort the current agent turn.
521    ///
522    /// # Cancel safety
523    ///
524    /// **Cancel-safe.** Single `session.abort` RPC; the underlying
525    /// [`Client::call`](crate::Client::call) is cancel-safe via the
526    /// writer-actor.
527    pub async fn abort(&self) -> Result<(), Error> {
528        self.client
529            .call(
530                "session.abort",
531                Some(serde_json::json!({ "sessionId": self.id })),
532            )
533            .await?;
534        Ok(())
535    }
536
537    /// Switch to a different model.
538    ///
539    /// Pass `None` for `opts` if no extra configuration is needed.
540    pub async fn set_model(&self, model: &str, opts: Option<SetModelOptions>) -> Result<(), Error> {
541        let opts = opts.unwrap_or_default();
542        let request = ModelSwitchToRequest {
543            compaction_decision: None,
544            context_tier: opts.context_tier,
545            defer_if_model_change_queued: None,
546            model_capabilities: opts.model_capabilities,
547            model_change_scope: None,
548            model_id: model.to_string(),
549            picker_persistence: None,
550            reasoning_effort: opts.reasoning_effort,
551            reasoning_summary: opts.reasoning_summary,
552            repo_scope: None,
553            require_available: None,
554            run_compaction_preflight: None,
555            source: None,
556            verbosity: None,
557        };
558        self.rpc().model().switch_to(request).await?;
559        Ok(())
560    }
561
562    /// Disconnect this session from the CLI.
563    ///
564    /// Sends the `session.destroy` RPC, stops the event loop, and unregisters
565    /// the session from the client. **Session state on disk** (conversation
566    /// history, planning state, artifacts) is **preserved**, so the
567    /// conversation can be resumed later via [`Client::resume_session`]
568    /// using this session's ID. To permanently remove all on-disk session
569    /// data, use [`Client::delete_session`] instead.
570    ///
571    /// The caller should ensure the session is idle (e.g. [`send_and_wait`]
572    /// has returned) before disconnecting; in-flight tool or event handlers
573    /// may otherwise observe failures.
574    ///
575    /// [`Client::resume_session`]: crate::Client::resume_session
576    /// [`Client::delete_session`]: crate::Client::delete_session
577    /// [`send_and_wait`]: Self::send_and_wait
578    pub async fn disconnect(&self) -> Result<(), Error> {
579        self.client
580            .call(
581                "session.destroy",
582                Some(serde_json::json!({ "sessionId": self.id })),
583            )
584            .await?;
585        self.stop_event_loop().await;
586        self.client.unregister_session(&self.id);
587        Ok(())
588    }
589
590    /// Deprecated alias for [`disconnect`](Self::disconnect). The
591    /// underlying wire RPC happens to be named `session.destroy`, but it
592    /// only severs the connection — on-disk session state is preserved.
593    /// Prefer `disconnect` in new code.
594    #[deprecated(since = "0.1.0", note = "Use `disconnect()` instead")]
595    pub async fn destroy(&self) -> Result<(), Error> {
596        self.disconnect().await
597    }
598
599    /// Write a log message to the session.
600    ///
601    /// Pass `None` for `opts` to use defaults (info level, persisted).
602    pub async fn log(
603        &self,
604        message: &str,
605        opts: Option<crate::types::LogOptions>,
606    ) -> Result<(), Error> {
607        let opts = opts.unwrap_or_default();
608        let level = match opts.level {
609            Some(level) => Some(serde_json::from_value(serde_json::to_value(level)?)?),
610            None => None,
611        };
612        let request = LogRequest {
613            message: message.to_string(),
614            level,
615            ephemeral: opts.ephemeral,
616            r#type: None,
617            tip: None,
618            url: None,
619        };
620        self.rpc().log(request).await?;
621        Ok(())
622    }
623
624    /// Returns the UI sub-API for elicitation, confirmation, selection, and
625    /// free-form input.
626    ///
627    /// All UI methods route through `session.ui.*` RPCs and require host
628    /// support — check `session.capabilities().ui.elicitation` before use.
629    pub fn ui(&self) -> SessionUi<'_> {
630        SessionUi { session: self }
631    }
632
633    /// Returns an error if the host doesn't support elicitation.
634    fn assert_elicitation(&self) -> Result<(), Error> {
635        if self
636            .capabilities
637            .read()
638            .ui
639            .as_ref()
640            .and_then(|u| u.elicitation)
641            != Some(true)
642        {
643            return Err(ErrorKind::Session(SessionErrorKind::ElicitationNotSupported).into());
644        }
645        Ok(())
646    }
647}
648
649impl Drop for Session {
650    fn drop(&mut self) {
651        // Cooperative shutdown: cancel the event loop's token to signal
652        // exit between iterations. The loop will see the cancellation on
653        // its next select poll and break cleanly without interrupting an
654        // in-flight handler. We do NOT abort the JoinHandle — that would
655        // land at any await point in the loop body, potentially leaving
656        // the CLI with an unanswered request id. RFD-400 review finding
657        // #3.
658        //
659        // The handle itself is left in `event_loop` to be reaped by the
660        // tokio runtime when it next polls; we intentionally don't await
661        // it here because Drop is sync.
662        self.shutdown.cancel();
663        self.client.unregister_session(&self.id);
664    }
665}
666
667/// UI sub-API for a [`Session`] — elicitation, confirmation, selection,
668/// and free-form input.
669///
670/// Acquired via [`Session::ui`]. Methods route to `session.ui.*` RPCs and
671/// require host elicitation support — check
672/// `session.capabilities().ui.elicitation` before use.
673pub struct SessionUi<'a> {
674    session: &'a Session,
675}
676
677impl<'a> SessionUi<'a> {
678    /// Request user input via an interactive UI form (elicitation).
679    ///
680    /// Sends a JSON Schema describing form fields to the CLI host. The host
681    /// renders a form dialog and returns the user's response.
682    ///
683    /// Prefer the typed convenience methods [`confirm`](Self::confirm),
684    /// [`select`](Self::select), and [`input`](Self::input) for common cases.
685    pub async fn elicitation(
686        &self,
687        message: &str,
688        schema: Value,
689    ) -> Result<ElicitationResult, Error> {
690        self.session.assert_elicitation()?;
691        let result = self
692            .session
693            .client
694            .call(
695                "session.ui.elicitation",
696                Some(serde_json::json!({
697                    "sessionId": self.session.id,
698                    "message": message,
699                    "requestedSchema": schema,
700                })),
701            )
702            .await?;
703        let elicitation: ElicitationResult = serde_json::from_value(result)?;
704        Ok(elicitation)
705    }
706
707    /// Ask the user a yes/no confirmation question.
708    ///
709    /// Returns `true` if the user accepted and confirmed, `false` otherwise.
710    pub async fn confirm(&self, message: &str) -> Result<bool, Error> {
711        self.session.assert_elicitation()?;
712        let schema = serde_json::json!({
713            "type": "object",
714            "properties": {
715                "confirmed": {
716                    "type": "boolean",
717                    "default": true,
718                }
719            },
720            "required": ["confirmed"]
721        });
722        let result = self.elicitation(message, schema).await?;
723        Ok(result.action == "accept"
724            && result
725                .content
726                .and_then(|c| c.get("confirmed").and_then(|v| v.as_bool()))
727                == Some(true))
728    }
729
730    /// Ask the user to select from a list of options.
731    ///
732    /// Returns the selected option string on accept, or `None` on decline/cancel.
733    pub async fn select(&self, message: &str, options: &[&str]) -> Result<Option<String>, Error> {
734        self.session.assert_elicitation()?;
735        let schema = serde_json::json!({
736            "type": "object",
737            "properties": {
738                "selection": {
739                    "type": "string",
740                    "enum": options,
741                }
742            },
743            "required": ["selection"]
744        });
745        let result = self.elicitation(message, schema).await?;
746        if result.action != "accept" {
747            return Ok(None);
748        }
749        let selection = result.content.and_then(|c| {
750            c.get("selection")
751                .and_then(|v| v.as_str())
752                .map(String::from)
753        });
754        Ok(selection)
755    }
756
757    /// Ask the user for free-form text input.
758    ///
759    /// Returns the input string on accept, or `None` on decline/cancel.
760    /// Use [`UiInputOptions`] to set validation constraints and field metadata.
761    pub async fn input(
762        &self,
763        message: &str,
764        options: Option<&UiInputOptions<'_>>,
765    ) -> Result<Option<String>, Error> {
766        self.session.assert_elicitation()?;
767        let mut field = serde_json::json!({ "type": "string" });
768        if let Some(opts) = options {
769            if let Some(title) = opts.title {
770                field["title"] = Value::String(title.to_string());
771            }
772            if let Some(desc) = opts.description {
773                field["description"] = Value::String(desc.to_string());
774            }
775            if let Some(min) = opts.min_length {
776                field["minLength"] = Value::Number(min.into());
777            }
778            if let Some(max) = opts.max_length {
779                field["maxLength"] = Value::Number(max.into());
780            }
781            if let Some(fmt) = &opts.format {
782                field["format"] = Value::String(fmt.as_str().to_string());
783            }
784            if let Some(default) = opts.default {
785                field["default"] = Value::String(default.to_string());
786            }
787        }
788        let schema = serde_json::json!({
789            "type": "object",
790            "properties": { "value": field },
791            "required": ["value"]
792        });
793        let result = self.elicitation(message, schema).await?;
794        if result.action != "accept" {
795            return Ok(None);
796        }
797        let value = result
798            .content
799            .and_then(|c| c.get("value").and_then(|v| v.as_str()).map(String::from));
800        Ok(value)
801    }
802}
803
804impl Client {
805    /// Create a new session on the CLI.
806    ///
807    /// Sends `session.create`, registers the session on the router,
808    /// and spawns an internal event loop that dispatches to the handler.
809    ///
810    /// All callbacks (per-event handlers, tool handlers, hooks, transform)
811    /// are configured via [`SessionConfig`] using its `with_*_handler` /
812    /// `with_tools` / `with_hooks` / `with_system_message_transform` builder
813    /// methods.
814    ///
815    /// If [`hooks_handler`](SessionConfig::hooks_handler) is set, the
816    /// wire-level `hooks` flag is automatically enabled.
817    ///
818    /// If [`system_message_transform`](SessionConfig::system_message_transform) is set, the SDK injects
819    /// `action: "transform"` sections into the [`SystemMessageConfig`] wire
820    /// format and handles `systemMessage.transform` RPC callbacks during
821    /// the session.
822    ///
823    /// Each per-event handler is independently optional. If a handler is
824    /// not installed, the SDK signals the runtime not to emit the matching
825    /// broadcast (and silently skips dispatch if one arrives anyway).
826    pub async fn create_session(&self, mut config: SessionConfig) -> Result<Session, Error> {
827        let total_start = Instant::now();
828        // For cloud sessions, let the CLI/server assign the session id and
829        // register the session lazily once the response arrives. For non-cloud
830        // sessions we generate the id client-side (when the caller didn't
831        // supply one) so the session can be registered BEFORE the RPC — the
832        // CLI may issue session-scoped requests (e.g. sessionFs.writeFile for
833        // workspace metadata) during session.create processing, before it has
834        // sent the response.
835        let caller_session_id = config.session_id.clone();
836        let use_server_generated_id = config.cloud.is_some() && caller_session_id.is_none();
837        let local_session_id: Option<SessionId> = if use_server_generated_id {
838            None
839        } else {
840            Some(
841                caller_session_id
842                    .clone()
843                    .unwrap_or_else(|| SessionId::new(uuid::Uuid::new_v4().to_string())),
844            )
845        };
846        if config.hooks_handler.is_some() && config.hooks.is_none() {
847            config.hooks = Some(true);
848        }
849        if let Some(transforms) = config.system_message_transform.clone() {
850            inject_transform_sections(&mut config, transforms.as_ref());
851        }
852        let mode = self.inner.mode;
853        if mode == crate::ClientMode::Empty && config.available_tools.is_none() {
854            return Err(Error::with_message(
855                ErrorKind::InvalidConfig,
856                "ClientMode::Empty requires available_tools to be set on the session config. \
857                 Use ToolSet to specify which tools the session may use (e.g. \
858                 ToolSet::new().add_builtin_many(BUILTIN_TOOLS_ISOLATED)).",
859            ));
860        }
861        crate::mode::validate_tool_filter_list(
862            "available_tools",
863            config.available_tools.as_deref(),
864        )?;
865        crate::mode::validate_tool_filter_list("excluded_tools", config.excluded_tools.as_deref())?;
866        config.system_message =
867            crate::mode::system_message_for_mode(mode, config.system_message.take());
868        config.memory = crate::mode::memory_for_mode(mode, config.memory.take());
869        config.enable_experimental_mode =
870            crate::mode::experimental_mode_for_mode(mode, config.enable_experimental_mode);
871        if mode == crate::ClientMode::Empty {
872            if config.enable_session_telemetry.is_none() {
873                config.enable_session_telemetry = Some(false);
874            }
875            if config.skip_embedding_retrieval.is_none() {
876                config.skip_embedding_retrieval = Some(true);
877            }
878            if config.enable_on_demand_instruction_discovery.is_none() {
879                config.enable_on_demand_instruction_discovery = Some(false);
880            }
881            if config.enable_file_hooks.is_none() {
882                config.enable_file_hooks = Some(false);
883            }
884            if config.enable_host_git_operations.is_none() {
885                config.enable_host_git_operations = Some(false);
886            }
887            if config.enable_session_store.is_none() {
888                config.enable_session_store = Some(false);
889            }
890            if config.enable_skills.is_none() {
891                config.enable_skills = Some(false);
892            }
893        }
894        if mode == crate::ClientMode::Empty && config.mcp_oauth_token_storage.is_none() {
895            config.mcp_oauth_token_storage = Some("in-memory".into());
896        }
897        if mode == crate::ClientMode::Empty && config.embedding_cache_storage.is_none() {
898            config.embedding_cache_storage = Some("in-memory".into());
899        }
900        config.custom_agents_local_only =
901            crate::mode::resolve_custom_agents_local_only(mode, config.custom_agents_local_only);
902        let opt_skip_custom_instructions = config.skip_custom_instructions;
903        let opt_custom_agents_local_only = config.custom_agents_local_only;
904        let opt_coauthor_enabled = config.coauthor_enabled;
905        let opt_manage_schedule_enabled = config.manage_schedule_enabled;
906        let (mut wire, mut runtime) = config.into_wire(local_session_id.clone())?;
907        wire.enable_github_telemetry_forwarding =
908            self.inner.on_github_telemetry.is_some().then_some(true);
909
910        let permission_handler = crate::permission::resolve_handler(
911            runtime.permission_handler.take(),
912            runtime.permission_policy.take(),
913        );
914        let handlers = SessionHandlers {
915            permission: permission_handler,
916            managed_settings_enabled: has_managed_settings(
917                wire.enable_managed_settings,
918                wire.managed_settings.as_ref(),
919            ),
920            elicitation: runtime.elicitation_handler.take(),
921            mcp_auth: runtime.mcp_auth_handler.take(),
922            user_input: runtime.user_input_handler.take(),
923            exit_plan_mode: runtime.exit_plan_mode_handler.take(),
924            auto_mode_switch: runtime.auto_mode_switch_handler.take(),
925            tools: Arc::new(std::mem::take(&mut runtime.tool_handlers)),
926        };
927        let hooks = runtime.hooks_handler.take();
928        let transforms = runtime.system_message_transform.take();
929        let tools_count = wire.tools.as_ref().map_or(0, Vec::len);
930        let commands_count = runtime.commands.as_ref().map_or(0, Vec::len);
931        let has_hooks = hooks.is_some();
932        let command_handlers = build_command_handler_map(runtime.commands.as_deref());
933        let canvas_handler = runtime.canvas_handler.take();
934        let session_fs_provider = runtime.session_fs_provider.take();
935        let bearer_token_providers = std::mem::take(&mut runtime.bearer_token_providers);
936        let has_mcp_auth_handler = handlers.mcp_auth.is_some();
937        if self.inner.session_fs_configured && session_fs_provider.is_none() {
938            return Err(ErrorKind::Session(SessionErrorKind::SessionFsProviderRequired).into());
939        }
940        if self.inner.session_fs_sqlite_declared
941            && let Some(ref provider) = session_fs_provider
942            && provider.sqlite().is_none()
943        {
944            return Err(Error::with_message(
945                ErrorKind::InvalidConfig,
946                "SessionFs capabilities declare SQLite support but the provider \
947                 does not implement SessionFsSqliteProvider",
948            ));
949        }
950
951        let mut params = serde_json::to_value(&wire)?;
952        let trace_ctx = self.resolve_trace_context().await;
953        inject_trace_context(&mut params, &trace_ctx);
954
955        let setup_start = Instant::now();
956        let capabilities = Arc::new(parking_lot::RwLock::new(SessionCapabilities::default()));
957        let idle_waiter = Arc::new(ParkingLotMutex::new(None));
958        let open_canvases = Arc::new(parking_lot::RwLock::new(Vec::new()));
959        let shutdown = CancellationToken::new();
960        let (event_tx, _) = tokio::sync::broadcast::channel(512);
961
962        // For cloud sessions (use_server_generated_id), defer session
963        // registration to the inline callback so the read task registers
964        // the session synchronously the instant the response arrives.
965        // For non-cloud sessions, register up-front so the CLI can issue
966        // session-scoped requests during session.create processing.
967        let inline_stash: Arc<
968            ParkingLotMutex<Option<(SessionId, crate::router::SessionChannels)>>,
969        > = Arc::new(ParkingLotMutex::new(None));
970
971        let inline_callback: Option<crate::jsonrpc::InlineResponseCallback> = if let Some(ref sid) =
972            local_session_id
973        {
974            let channels = self.register_session(sid);
975            *inline_stash.lock() = Some((sid.clone(), channels));
976            None
977        } else {
978            let client = self.clone();
979            let stash = inline_stash.clone();
980            let expected = caller_session_id.clone();
981            Some(Box::new(move |response| {
982                let result = response.result.as_ref().ok_or_else(|| {
983                    Error::with_message(ErrorKind::Json, "session.create response had no result")
984                })?;
985                let parsed: CreateSessionResult =
986                    serde_json::from_value(result.clone()).map_err(Error::from)?;
987                if let Some(requested) = expected.as_ref()
988                    && parsed.session_id != *requested
989                {
990                    return Err(ErrorKind::Session(SessionErrorKind::SessionIdMismatch {
991                        requested: requested.clone(),
992                        returned: parsed.session_id,
993                    })
994                    .into());
995                }
996                let channels = client.register_session(&parsed.session_id);
997                *stash.lock() = Some((parsed.session_id, channels));
998                Ok(())
999            }))
1000        };
1001
1002        let rpc_start = Instant::now();
1003        let result = match self
1004            .call_with_inline_callback("session.create", Some(params), inline_callback)
1005            .await
1006        {
1007            Ok(result) => result,
1008            Err(error) => {
1009                if let Some((id, _channels)) = inline_stash.lock().take() {
1010                    self.unregister_session(&id);
1011                }
1012                return Err(error);
1013            }
1014        };
1015        tracing::debug!(
1016            elapsed_ms = rpc_start.elapsed().as_millis(),
1017            "Client::create_session session creation request completed successfully"
1018        );
1019        let create_result: CreateSessionResult = match serde_json::from_value(result) {
1020            Ok(result) => result,
1021            Err(error) => {
1022                if let Some((id, _channels)) = inline_stash.lock().take() {
1023                    self.unregister_session(&id);
1024                }
1025                return Err(error.into());
1026            }
1027        };
1028
1029        if let Some(ref requested) = local_session_id
1030            && create_result.session_id != *requested
1031        {
1032            if let Some((id, _channels)) = inline_stash.lock().take() {
1033                self.unregister_session(&id);
1034            }
1035            return Err(ErrorKind::Session(SessionErrorKind::SessionIdMismatch {
1036                requested: requested.clone(),
1037                returned: create_result.session_id.clone(),
1038            })
1039            .into());
1040        }
1041
1042        let (session_id, channels) = inline_stash
1043            .lock()
1044            .take()
1045            .expect("session registration must have populated stash on success");
1046        let event_loop = spawn_event_loop(
1047            session_id.clone(),
1048            self.clone(),
1049            handlers,
1050            hooks,
1051            transforms,
1052            command_handlers,
1053            canvas_handler,
1054            session_fs_provider,
1055            bearer_token_providers,
1056            channels,
1057            idle_waiter.clone(),
1058            capabilities.clone(),
1059            open_canvases.clone(),
1060            event_tx.clone(),
1061            shutdown.clone(),
1062        );
1063        tracing::debug!(
1064            elapsed_ms = setup_start.elapsed().as_millis(),
1065            session_id = %session_id,
1066            tools_count,
1067            commands_count,
1068            has_hooks,
1069            "Client::create_session local setup complete"
1070        );
1071        *capabilities.write() = create_result.capabilities.unwrap_or_default();
1072        if has_mcp_auth_handler {
1073            register_mcp_auth_interest(self, &session_id).await?;
1074        }
1075
1076        tracing::debug!(
1077            elapsed_ms = total_start.elapsed().as_millis(),
1078            session_id = %session_id,
1079            "Client::create_session complete"
1080        );
1081        let session = Session {
1082            id: session_id,
1083            cwd: self.cwd().clone(),
1084            workspace_path: create_result.workspace_path,
1085            remote_url: create_result.remote_url,
1086            client: self.clone(),
1087            event_loop: ParkingLotMutex::new(Some(event_loop)),
1088            shutdown,
1089            idle_waiter,
1090            capabilities,
1091            open_canvases,
1092            event_tx,
1093        };
1094        apply_mode_post_create_patch(
1095            &session,
1096            mode,
1097            opt_skip_custom_instructions,
1098            opt_custom_agents_local_only,
1099            opt_coauthor_enabled,
1100            opt_manage_schedule_enabled,
1101        )
1102        .await?;
1103        Ok(session)
1104    }
1105
1106    /// Resume an existing session on the CLI.
1107    ///
1108    /// Sends `session.resume` and `session.skills.reload`, registers the
1109    /// session on the router, and spawns the event loop.
1110    ///
1111    /// All callbacks (event handler, hooks, transform) are configured
1112    /// via [`ResumeSessionConfig`] using its `with_*` builder methods.
1113    ///
1114    /// See [`Self::create_session`] for the defaults applied when callback
1115    /// fields are unset.
1116    pub async fn resume_session(&self, mut config: ResumeSessionConfig) -> Result<Session, Error> {
1117        let total_start = Instant::now();
1118        let session_id = config.session_id.clone();
1119        if config.hooks_handler.is_some() && config.hooks.is_none() {
1120            config.hooks = Some(true);
1121        }
1122        if let Some(transforms) = config.system_message_transform.clone() {
1123            inject_transform_sections_resume(&mut config, transforms.as_ref());
1124        }
1125        let mode = self.inner.mode;
1126        if mode == crate::ClientMode::Empty && config.available_tools.is_none() {
1127            return Err(Error::with_message(
1128                ErrorKind::InvalidConfig,
1129                "ClientMode::Empty requires available_tools to be set on the session config. \
1130                 Use ToolSet to specify which tools the session may use (e.g. \
1131                 ToolSet::new().add_builtin_many(BUILTIN_TOOLS_ISOLATED)).",
1132            ));
1133        }
1134        crate::mode::validate_tool_filter_list(
1135            "available_tools",
1136            config.available_tools.as_deref(),
1137        )?;
1138        crate::mode::validate_tool_filter_list("excluded_tools", config.excluded_tools.as_deref())?;
1139        config.system_message =
1140            crate::mode::system_message_for_mode(mode, config.system_message.take());
1141        config.memory = crate::mode::memory_for_mode(mode, config.memory.take());
1142        config.enable_experimental_mode =
1143            crate::mode::experimental_mode_for_mode(mode, config.enable_experimental_mode);
1144        if mode == crate::ClientMode::Empty {
1145            if config.enable_session_telemetry.is_none() {
1146                config.enable_session_telemetry = Some(false);
1147            }
1148            if config.skip_embedding_retrieval.is_none() {
1149                config.skip_embedding_retrieval = Some(true);
1150            }
1151            if config.enable_on_demand_instruction_discovery.is_none() {
1152                config.enable_on_demand_instruction_discovery = Some(false);
1153            }
1154            if config.enable_file_hooks.is_none() {
1155                config.enable_file_hooks = Some(false);
1156            }
1157            if config.enable_host_git_operations.is_none() {
1158                config.enable_host_git_operations = Some(false);
1159            }
1160            if config.enable_session_store.is_none() {
1161                config.enable_session_store = Some(false);
1162            }
1163            if config.enable_skills.is_none() {
1164                config.enable_skills = Some(false);
1165            }
1166        }
1167        if mode == crate::ClientMode::Empty && config.mcp_oauth_token_storage.is_none() {
1168            config.mcp_oauth_token_storage = Some("in-memory".into());
1169        }
1170        if mode == crate::ClientMode::Empty && config.embedding_cache_storage.is_none() {
1171            config.embedding_cache_storage = Some("in-memory".into());
1172        }
1173        config.custom_agents_local_only =
1174            crate::mode::resolve_custom_agents_local_only(mode, config.custom_agents_local_only);
1175        let opt_skip_custom_instructions = config.skip_custom_instructions;
1176        let opt_custom_agents_local_only = config.custom_agents_local_only;
1177        let opt_coauthor_enabled = config.coauthor_enabled;
1178        let opt_manage_schedule_enabled = config.manage_schedule_enabled;
1179        let (mut wire, mut runtime) = config.into_wire()?;
1180        wire.enable_github_telemetry_forwarding =
1181            self.inner.on_github_telemetry.is_some().then_some(true);
1182
1183        let permission_handler = crate::permission::resolve_handler(
1184            runtime.permission_handler.take(),
1185            runtime.permission_policy.take(),
1186        );
1187        let handlers = SessionHandlers {
1188            permission: permission_handler,
1189            managed_settings_enabled: has_managed_settings(
1190                wire.enable_managed_settings,
1191                wire.managed_settings.as_ref(),
1192            ),
1193            elicitation: runtime.elicitation_handler.take(),
1194            mcp_auth: runtime.mcp_auth_handler.take(),
1195            user_input: runtime.user_input_handler.take(),
1196            exit_plan_mode: runtime.exit_plan_mode_handler.take(),
1197            auto_mode_switch: runtime.auto_mode_switch_handler.take(),
1198            tools: Arc::new(std::mem::take(&mut runtime.tool_handlers)),
1199        };
1200        let hooks = runtime.hooks_handler.take();
1201        let transforms = runtime.system_message_transform.take();
1202        let tools_count = wire.tools.as_ref().map_or(0, Vec::len);
1203        let commands_count = runtime.commands.as_ref().map_or(0, Vec::len);
1204        let has_hooks = hooks.is_some();
1205        let command_handlers = build_command_handler_map(runtime.commands.as_deref());
1206        let canvas_handler = runtime.canvas_handler.take();
1207        let session_fs_provider = runtime.session_fs_provider.take();
1208        let bearer_token_providers = std::mem::take(&mut runtime.bearer_token_providers);
1209        let has_mcp_auth_handler = handlers.mcp_auth.is_some();
1210        if self.inner.session_fs_configured && session_fs_provider.is_none() {
1211            return Err(ErrorKind::Session(SessionErrorKind::SessionFsProviderRequired).into());
1212        }
1213        if self.inner.session_fs_sqlite_declared
1214            && let Some(ref provider) = session_fs_provider
1215            && provider.sqlite().is_none()
1216        {
1217            return Err(Error::with_message(
1218                ErrorKind::InvalidConfig,
1219                "SessionFs capabilities declare SQLite support but the provider \
1220                 does not implement SessionFsSqliteProvider",
1221            ));
1222        }
1223
1224        let mut params = serde_json::to_value(&wire)?;
1225        let trace_ctx = self.resolve_trace_context().await;
1226        inject_trace_context(&mut params, &trace_ctx);
1227
1228        let capabilities = Arc::new(parking_lot::RwLock::new(SessionCapabilities::default()));
1229        let setup_start = Instant::now();
1230        let channels = self.register_session(&session_id);
1231        let idle_waiter = Arc::new(ParkingLotMutex::new(None));
1232        let open_canvases = Arc::new(parking_lot::RwLock::new(Vec::new()));
1233        let shutdown = CancellationToken::new();
1234        let (event_tx, _) = tokio::sync::broadcast::channel(512);
1235        let event_loop = spawn_event_loop(
1236            session_id.clone(),
1237            self.clone(),
1238            handlers,
1239            hooks,
1240            transforms,
1241            command_handlers,
1242            canvas_handler,
1243            session_fs_provider,
1244            bearer_token_providers,
1245            channels,
1246            idle_waiter.clone(),
1247            capabilities.clone(),
1248            open_canvases.clone(),
1249            event_tx.clone(),
1250            shutdown.clone(),
1251        );
1252        let mut registration =
1253            PendingSessionRegistration::new(self.clone(), session_id.clone(), shutdown.clone());
1254        tracing::debug!(
1255            elapsed_ms = setup_start.elapsed().as_millis(),
1256            session_id = %session_id,
1257            tools_count,
1258            commands_count,
1259            has_hooks,
1260            "Client::resume_session local setup complete"
1261        );
1262
1263        let rpc_start = Instant::now();
1264        let result = match self.call("session.resume", Some(params)).await {
1265            Ok(result) => result,
1266            Err(error) => {
1267                registration.cleanup(event_loop).await;
1268                return Err(error);
1269            }
1270        };
1271        tracing::debug!(
1272            elapsed_ms = rpc_start.elapsed().as_millis(),
1273            session_id = %session_id,
1274            "Client::resume_session session resume request completed successfully"
1275        );
1276
1277        let resume_result: ResumeSessionResult = match serde_json::from_value(result) {
1278            Ok(result) => result,
1279            Err(error) => {
1280                registration.cleanup(event_loop).await;
1281                return Err(error.into());
1282            }
1283        };
1284        let cli_session_id = resume_result
1285            .session_id
1286            .clone()
1287            .unwrap_or_else(|| session_id.clone());
1288        if cli_session_id != session_id {
1289            registration.cleanup(event_loop).await;
1290            return Err(ErrorKind::Session(SessionErrorKind::SessionIdMismatch {
1291                requested: session_id,
1292                returned: cli_session_id,
1293            })
1294            .into());
1295        }
1296        if has_mcp_auth_handler {
1297            register_mcp_auth_interest(self, &session_id).await?;
1298        }
1299
1300        // Reload skills after resume (best-effort).
1301        let skills_reload_start = Instant::now();
1302        if let Err(e) = self
1303            .call(
1304                "session.skills.reload",
1305                Some(serde_json::json!({ "sessionId": session_id })),
1306            )
1307            .await
1308        {
1309            warn!(
1310                elapsed_ms = skills_reload_start.elapsed().as_millis(),
1311                session_id = %session_id,
1312                error = %e,
1313                "Client::resume_session skills reload request failed"
1314            );
1315        } else {
1316            tracing::debug!(
1317                elapsed_ms = skills_reload_start.elapsed().as_millis(),
1318                session_id = %session_id,
1319                "Client::resume_session skills reload request completed successfully"
1320            );
1321        }
1322
1323        *capabilities.write() = resume_result.capabilities.unwrap_or_default();
1324        // Upsert resume snapshots rather than replacing wholesale. Live
1325        // `session.canvas.opened` notifications can arrive on the event loop
1326        // while `session.resume` is in flight; a wholesale replace would
1327        // discard those updates.
1328        {
1329            let mut snapshots = open_canvases.write();
1330            for snapshot in resume_result.open_canvases.unwrap_or_default() {
1331                upsert_open_canvas_snapshot(&mut snapshots, snapshot);
1332            }
1333        }
1334
1335        tracing::debug!(
1336            elapsed_ms = total_start.elapsed().as_millis(),
1337            session_id = %session_id,
1338            "Client::resume_session complete"
1339        );
1340        registration.disarm();
1341        let session = Session {
1342            id: session_id,
1343            cwd: self.cwd().clone(),
1344            workspace_path: resume_result.workspace_path,
1345            remote_url: resume_result.remote_url,
1346            client: self.clone(),
1347            event_loop: ParkingLotMutex::new(Some(event_loop)),
1348            shutdown,
1349            idle_waiter,
1350            capabilities,
1351            open_canvases,
1352            event_tx,
1353        };
1354        apply_mode_post_create_patch(
1355            &session,
1356            mode,
1357            opt_skip_custom_instructions,
1358            opt_custom_agents_local_only,
1359            opt_coauthor_enabled,
1360            opt_manage_schedule_enabled,
1361        )
1362        .await?;
1363        Ok(session)
1364    }
1365}
1366
1367type CommandHandlerMap = HashMap<String, Arc<dyn CommandHandler>>;
1368
1369async fn apply_mode_post_create_patch(
1370    session: &Session,
1371    mode: crate::ClientMode,
1372    opt_skip_custom_instructions: Option<bool>,
1373    opt_custom_agents_local_only: Option<bool>,
1374    opt_coauthor_enabled: Option<bool>,
1375    opt_manage_schedule_enabled: Option<bool>,
1376) -> Result<(), Error> {
1377    use crate::generated::api_types::SessionUpdateOptionsParams;
1378    let mut patch = SessionUpdateOptionsParams::default();
1379    let should_send = if mode == crate::ClientMode::Empty {
1380        patch.skip_custom_instructions = Some(opt_skip_custom_instructions.unwrap_or(true));
1381        patch.custom_agents_local_only = Some(opt_custom_agents_local_only.unwrap_or(true));
1382        patch.coauthor_enabled = Some(opt_coauthor_enabled.unwrap_or(false));
1383        patch.manage_schedule_enabled = Some(opt_manage_schedule_enabled.unwrap_or(false));
1384        patch.installed_plugins = Some(Vec::new());
1385        true
1386    } else {
1387        let mut any = false;
1388        if let Some(v) = opt_skip_custom_instructions {
1389            patch.skip_custom_instructions = Some(v);
1390            any = true;
1391        }
1392        if let Some(v) = opt_custom_agents_local_only {
1393            patch.custom_agents_local_only = Some(v);
1394            any = true;
1395        }
1396        if let Some(v) = opt_coauthor_enabled {
1397            patch.coauthor_enabled = Some(v);
1398            any = true;
1399        }
1400        if let Some(v) = opt_manage_schedule_enabled {
1401            patch.manage_schedule_enabled = Some(v);
1402            any = true;
1403        }
1404        any
1405    };
1406    if !should_send {
1407        return Ok(());
1408    }
1409    if let Err(error) = session.rpc().options().update(patch).await {
1410        let _ = session.disconnect().await;
1411        return Err(error);
1412    }
1413    Ok(())
1414}
1415
1416fn build_command_handler_map(commands: Option<&[CommandDefinition]>) -> Arc<CommandHandlerMap> {
1417    let map = match commands {
1418        Some(commands) => commands
1419            .iter()
1420            .filter(|cmd| !cmd.name.is_empty())
1421            .map(|cmd| (cmd.name.clone(), cmd.handler.clone()))
1422            .collect(),
1423        None => HashMap::new(),
1424    };
1425    Arc::new(map)
1426}
1427
1428fn upsert_open_canvas_snapshot(
1429    snapshots: &mut Vec<OpenCanvasInstance>,
1430    snapshot: OpenCanvasInstance,
1431) {
1432    if let Some(existing) = snapshots
1433        .iter_mut()
1434        .find(|open| open.instance_id == snapshot.instance_id)
1435    {
1436        *existing = snapshot;
1437    } else {
1438        snapshots.push(snapshot);
1439    }
1440}
1441
1442fn remove_open_canvas_snapshot(snapshots: &mut Vec<OpenCanvasInstance>, instance_id: &str) {
1443    snapshots.retain(|open| open.instance_id != instance_id);
1444}
1445
1446#[allow(clippy::too_many_arguments)]
1447fn spawn_event_loop(
1448    session_id: SessionId,
1449    client: Client,
1450    handlers: SessionHandlers,
1451    hooks: Option<Arc<dyn SessionHooks>>,
1452    transforms: Option<Arc<dyn SystemMessageTransform>>,
1453    command_handlers: Arc<CommandHandlerMap>,
1454    canvas_handler: Option<Arc<dyn CanvasHandler>>,
1455    session_fs_provider: Option<Arc<dyn SessionFsProvider>>,
1456    bearer_token_providers: HashMap<String, Arc<dyn BearerTokenProvider>>,
1457    channels: crate::router::SessionChannels,
1458    idle_waiter: Arc<ParkingLotMutex<Option<IdleWaiter>>>,
1459    capabilities: Arc<parking_lot::RwLock<SessionCapabilities>>,
1460    open_canvases: Arc<parking_lot::RwLock<Vec<OpenCanvasInstance>>>,
1461    event_tx: tokio::sync::broadcast::Sender<SessionEvent>,
1462    shutdown: CancellationToken,
1463) -> JoinHandle<()> {
1464    let crate::router::SessionChannels {
1465        mut notifications,
1466        mut requests,
1467    } = channels;
1468
1469    let span = tracing::error_span!("session_event_loop", session_id = %session_id);
1470    tokio::spawn(
1471        async move {
1472            loop {
1473                // `mpsc::UnboundedReceiver::recv` and
1474                // `CancellationToken::cancelled` are both cancel-safe per
1475                // RFD 400.
1476                //
1477                // Inbound JSON-RPC *requests* are dispatched fire-and-forget:
1478                // each `handle_request` runs in its own spawned task that
1479                // awaits the handler and sends that request's response. This
1480                // mirrors the other Copilot SDKs and moves concurrency to the
1481                // request-dispatch boundary, so any slow handler — not just
1482                // `userInput.request` (which can stay pending for the full
1483                // input backstop of several minutes), but also `exitPlanMode`,
1484                // `autoModeSwitch`, hooks, transforms, or canvas/session-FS
1485                // providers — cannot park the reader loop and starve sibling
1486                // requests or co-emitted notifications. JSON-RPC permits
1487                // concurrent requests and out-of-order responses, so the SDK
1488                // does not serialize them.
1489                //
1490                // `handle_notification` is awaited inline because it only
1491                // performs fast dispatch work; its slow interactive callbacks
1492                // (permission/tool/elicitation) are themselves spawned as child
1493                // tasks. All of these spawned tasks intentionally outlive the
1494                // parent loop and own their own cleanup — RFD 400's "spawn
1495                // background tasks to perform cancel-unsafe operations" pattern.
1496                tokio::select! {
1497                    _ = shutdown.cancelled() => break,
1498                    Some(notification) = notifications.recv() => {
1499                        handle_notification(
1500                            &session_id, &client, &handlers, &command_handlers, notification, &idle_waiter, &capabilities, &open_canvases, &event_tx,
1501                        ).await;
1502                    }
1503                    Some(request) = requests.recv() => {
1504                        // Clone the Arc-backed dispatch context into the task so
1505                        // the spawned `handle_request` future is `'static`. All
1506                        // clones are cheap (Arc refcount bumps / small maps).
1507                        let span = tracing::error_span!("session_request_handler", session_id = %session_id);
1508                        let session_id = session_id.clone();
1509                        let client = client.clone();
1510                        let handlers = handlers.clone();
1511                        let hooks = hooks.clone();
1512                        let transforms = transforms.clone();
1513                        let canvas_handler = canvas_handler.clone();
1514                        let session_fs_provider = session_fs_provider.clone();
1515                        let bearer_token_providers = bearer_token_providers.clone();
1516                        tokio::spawn(
1517                            async move {
1518                                let ctx = RequestDispatchContext {
1519                                    client: &client,
1520                                    handlers: &handlers,
1521                                    hooks: hooks.as_deref(),
1522                                    transforms: transforms.as_deref(),
1523                                    canvas_handler: canvas_handler.as_ref(),
1524                                    session_fs_provider: session_fs_provider.as_ref(),
1525                                    bearer_token_providers: &bearer_token_providers,
1526                                };
1527                                handle_request(&session_id, ctx, request).await;
1528                            }
1529                            .instrument(span),
1530                        );
1531                    }
1532                    else => break,
1533                }
1534            }
1535            // Channels closed or shutdown signaled — fail any pending
1536            // send_and_wait so the caller observes a clean error.
1537            if let Some(waiter) = idle_waiter.lock().take() {
1538                let _ = waiter
1539                    .tx
1540                    .send(Err(ErrorKind::Session(SessionErrorKind::EventLoopClosed).into()));
1541            }
1542        }
1543        .instrument(span),
1544    )
1545}
1546
1547fn extract_request_id(data: &Value) -> Option<RequestId> {
1548    data.get("requestId")
1549        .and_then(|v| v.as_str())
1550        .filter(|s| !s.is_empty())
1551        .map(RequestId::new)
1552}
1553
1554fn permission_request_data(
1555    event_data: &Value,
1556    managed_settings_enabled: bool,
1557) -> PermissionRequestData {
1558    let request_data = event_data
1559        .get("permissionRequest")
1560        .cloned()
1561        .unwrap_or_else(|| event_data.clone());
1562    let managed_approval_required = match request_data.get("managedApprovalRequired") {
1563        None => None,
1564        Some(Value::Bool(value)) => Some(*value),
1565        Some(_) => Some(true),
1566    };
1567    match serde_json::from_value::<PermissionRequestData>(request_data) {
1568        Ok(mut data) => {
1569            data.extra = event_data.clone();
1570            data.managed_settings_enabled = managed_settings_enabled;
1571            data
1572        }
1573        Err(_) => PermissionRequestData {
1574            kind: None,
1575            tool_call_id: None,
1576            managed_approval_required,
1577            managed_settings_enabled,
1578            extra: event_data.clone(),
1579        },
1580    }
1581}
1582
1583/// Build the full `session.permissions.handlePendingPermissionRequest`
1584/// params for a permission result.
1585///
1586/// `decisionContext` is a sibling of `result` and is only present when the
1587/// handler attributed the decision — omitting it preserves legacy behavior.
1588///
1589/// Returns `None` when the SDK must not send a response.
1590fn permission_response_params(
1591    session_id: &SessionId,
1592    request_id: &RequestId,
1593    result: &PermissionResult,
1594) -> Option<Value> {
1595    let (decision, decision_context) = match result {
1596        PermissionResult::Decision { decision, context } => (decision, context.clone()),
1597        PermissionResult::NoResult => return None,
1598    };
1599    let mut params = serde_json::to_value(PermissionDecisionRequest {
1600        decision_context,
1601        request_id: request_id.clone(),
1602        result: decision.clone(),
1603    })
1604    .expect("serializing permission response should succeed");
1605    params["sessionId"] =
1606        serde_json::to_value(session_id).expect("serializing session ID should succeed");
1607    Some(params)
1608}
1609
1610async fn register_mcp_auth_interest(client: &Client, session_id: &SessionId) -> Result<(), Error> {
1611    let mut params = serde_json::to_value(RegisterEventInterestParams {
1612        event_type: "mcp.oauth_required".to_string(),
1613    })?;
1614    params["sessionId"] = Value::String(session_id.to_string());
1615    client
1616        .call(rpc_methods::SESSION_EVENTLOG_REGISTERINTEREST, Some(params))
1617        .await?;
1618    Ok(())
1619}
1620
1621fn tool_failure_result(message: impl Into<String>) -> ToolResult {
1622    let message = message.into();
1623    ToolResult::Expanded(ToolResultExpanded {
1624        text_result_for_llm: message.clone(),
1625        result_type: "failure".to_string(),
1626        binary_results_for_llm: None,
1627        session_log: None,
1628        error: Some(message),
1629        tool_telemetry: None,
1630        tool_references: None,
1631    })
1632}
1633
1634/// Process a notification from the CLI's broadcast channel.
1635#[allow(clippy::too_many_arguments)]
1636async fn handle_notification(
1637    session_id: &SessionId,
1638    client: &Client,
1639    handlers: &SessionHandlers,
1640    command_handlers: &Arc<CommandHandlerMap>,
1641    notification: SessionEventNotification,
1642    idle_waiter: &Arc<ParkingLotMutex<Option<IdleWaiter>>>,
1643    capabilities: &Arc<parking_lot::RwLock<SessionCapabilities>>,
1644    open_canvases: &Arc<parking_lot::RwLock<Vec<OpenCanvasInstance>>>,
1645    event_tx: &tokio::sync::broadcast::Sender<SessionEvent>,
1646) {
1647    let dispatch_start = Instant::now();
1648    let event = notification.event.clone();
1649    let event_type = event.parsed_type();
1650    if event_type == SessionEventType::PermissionRequested {
1651        tracing::debug!(
1652            session_id = %session_id,
1653            event_type = %event.event_type,
1654            "Session::handle_notification permission request received"
1655        );
1656    }
1657
1658    // Signal send_and_wait if active. The lock is only contended when
1659    // a send_and_wait call is in flight (idle_waiter is Some).
1660    match event_type {
1661        SessionEventType::AssistantMessage
1662        | SessionEventType::SessionIdle
1663        | SessionEventType::SessionError => {
1664            let mut guard = idle_waiter.lock();
1665            if let Some(waiter) = guard.as_mut() {
1666                match event_type {
1667                    SessionEventType::AssistantMessage => {
1668                        if !waiter.first_assistant_message_seen {
1669                            waiter.first_assistant_message_seen = true;
1670                            tracing::debug!(
1671                                elapsed_ms = waiter.started_at.elapsed().as_millis(),
1672                                session_id = %session_id,
1673                                "Session::send_and_wait first assistant message"
1674                            );
1675                        }
1676                        waiter.last_assistant_message = Some(event.clone());
1677                    }
1678                    SessionEventType::SessionIdle | SessionEventType::SessionError => {
1679                        if let Some(waiter) = guard.take() {
1680                            if event_type == SessionEventType::SessionIdle {
1681                                tracing::debug!(
1682                                    elapsed_ms = waiter.started_at.elapsed().as_millis(),
1683                                    session_id = %session_id,
1684                                    "Session::send_and_wait idle received"
1685                                );
1686                                let _ = waiter.tx.send(Ok(waiter.last_assistant_message));
1687                            } else {
1688                                let error_msg = event
1689                                    .typed_data::<SessionErrorData>()
1690                                    .map(|d| d.message)
1691                                    .or_else(|| {
1692                                        event
1693                                            .data
1694                                            .get("message")
1695                                            .and_then(|v| v.as_str())
1696                                            .map(|s| s.to_string())
1697                                    })
1698                                    .unwrap_or_else(|| "session error".to_string());
1699                                let _ = waiter.tx.send(Err(Error::with_message(
1700                                    ErrorKind::Session(SessionErrorKind::AgentError),
1701                                    error_msg,
1702                                )));
1703                            }
1704                        }
1705                    }
1706                    _ => {}
1707                }
1708            }
1709        }
1710        _ => {}
1711    }
1712
1713    // Update the snapshot caches BEFORE broadcasting so subscribers that
1714    // call `Session::capabilities()` / `Session::open_canvases()` in
1715    // response to the event observe the new state.
1716    if event_type == SessionEventType::CapabilitiesChanged {
1717        match serde_json::from_value::<SessionCapabilities>(notification.event.data.clone()) {
1718            Ok(changed) => *capabilities.write() = changed,
1719            Err(e) => warn!(error = %e, "failed to deserialize capabilities.changed payload"),
1720        }
1721    }
1722    if event_type == SessionEventType::SessionCanvasOpened {
1723        match serde_json::from_value::<OpenCanvasInstance>(notification.event.data.clone()) {
1724            Ok(open_canvas) => {
1725                upsert_open_canvas_snapshot(&mut open_canvases.write(), open_canvas);
1726            }
1727            Err(e) => warn!(error = %e, "failed to deserialize session.canvas.opened payload"),
1728        }
1729    }
1730    if event_type == SessionEventType::SessionCanvasClosed {
1731        match serde_json::from_value::<SessionCanvasClosedData>(notification.event.data.clone()) {
1732            Ok(closed) => {
1733                if closed.instance_id.is_empty() {
1734                    warn!("failed to deserialize session.canvas.closed payload");
1735                } else {
1736                    remove_open_canvas_snapshot(&mut open_canvases.write(), &closed.instance_id);
1737                }
1738            }
1739            Err(e) => warn!(error = %e, "failed to deserialize session.canvas.closed payload"),
1740        }
1741    }
1742
1743    // Fan out the event to runtime subscribers (`Session::subscribe`). `send`
1744    // only errors when there are no receivers, which is the normal case
1745    // before any consumer subscribes.
1746    let _ = event_tx.send(event.clone());
1747
1748    tracing::debug!(
1749        elapsed_ms = dispatch_start.elapsed().as_millis(),
1750        session_id = %session_id,
1751        event_type = %notification.event.event_type,
1752        "Session::handle_notification dispatch"
1753    );
1754
1755    // Notification-based permission/tool/elicitation requests require a
1756    // separate RPC callback. Spawn concurrently since the CLI doesn't block.
1757    match event_type {
1758        SessionEventType::PermissionRequested => {
1759            let Some(request_id) = extract_request_id(&notification.event.data) else {
1760                return;
1761            };
1762            // Honor the runtime's `resolvedByHook` signal — when the
1763            // server has already resolved the permission via a hook,
1764            // clients must not send a second response.
1765            if notification
1766                .event
1767                .data
1768                .get("resolvedByHook")
1769                .and_then(|v| v.as_bool())
1770                .unwrap_or(false)
1771            {
1772                return;
1773            }
1774            // Multi-client safety: if this client has no permission
1775            // handler installed, don't respond — another client on the
1776            // same CLI may handle it.
1777            let Some(permission_handler) = handlers.permission.clone() else {
1778                return;
1779            };
1780            let client = client.clone();
1781            let sid = session_id.clone();
1782            let data = permission_request_data(
1783                &notification.event.data,
1784                handlers.managed_settings_enabled,
1785            );
1786            let span = tracing::error_span!(
1787                "permission_request_handler",
1788                session_id = %sid,
1789                request_id = %request_id
1790            );
1791            tokio::spawn(
1792                async move {
1793                    let handler_start = Instant::now();
1794                    let result = permission_handler
1795                        .handle(sid.clone(), request_id.clone(), data)
1796                        .await;
1797                    tracing::debug!(
1798                        elapsed_ms = handler_start.elapsed().as_millis(),
1799                        session_id = %sid,
1800                        request_id = %request_id,
1801                        "PermissionHandler::handle dispatch"
1802                    );
1803                    let Some(params) = permission_response_params(&sid, &request_id, &result)
1804                    else {
1805                        // Handler returned Deferred / NoResult — it will
1806                        // call handlePendingPermissionRequest itself (or
1807                        // leave the request unanswered).
1808                        return;
1809                    };
1810                    let rpc_start = Instant::now();
1811                    let _ = client
1812                        .call(
1813                            rpc_methods::SESSION_PERMISSIONS_HANDLEPENDINGPERMISSIONREQUEST,
1814                            Some(params),
1815                        )
1816                        .await;
1817                    tracing::debug!(
1818                        elapsed_ms = rpc_start.elapsed().as_millis(),
1819                        session_id = %sid,
1820                        request_id = %request_id,
1821                        "Session::handle_notification response sent successfully"
1822                    );
1823                }
1824                .instrument(span),
1825            );
1826        }
1827        SessionEventType::ExternalToolRequested => {
1828            let Some(request_id) = extract_request_id(&notification.event.data) else {
1829                return;
1830            };
1831            let data: ExternalToolRequestedData =
1832                match serde_json::from_value(notification.event.data.clone()) {
1833                    Ok(d) => d,
1834                    Err(e) => {
1835                        warn!(error = %e, "failed to deserialize external_tool.requested");
1836                        let client = client.clone();
1837                        let sid = session_id.clone();
1838                        let span = tracing::error_span!(
1839                            "external_tool_deserialize_error",
1840                            session_id = %sid,
1841                            request_id = %request_id
1842                        );
1843                        tokio::spawn(
1844                            async move {
1845                                let rpc_start = Instant::now();
1846                                let _ = client
1847                                .call(
1848                                    "session.tools.handlePendingToolCall",
1849                                    Some(serde_json::json!({
1850                                        "sessionId": sid,
1851                                        "requestId": request_id,
1852                                        "error": format!("Failed to deserialize tool request: {e}"),
1853                                    })),
1854                                )
1855                                .await;
1856                                tracing::debug!(
1857                                    elapsed_ms = rpc_start.elapsed().as_millis(),
1858                                    session_id = %sid,
1859                                    request_id = %request_id,
1860                                    "Session::handle_notification response sent successfully"
1861                                );
1862                            }
1863                            .instrument(span),
1864                        );
1865                        return;
1866                    }
1867                };
1868            // Multi-client safety: look up a handler for the requested
1869            // tool name. If this client has no handler installed for that
1870            // tool, don't respond — another connected client may have one.
1871            let tool_handler = if data.tool_name.is_empty() {
1872                None
1873            } else {
1874                handlers.tools.get(&data.tool_name).cloned()
1875            };
1876            let Some(tool_handler) = tool_handler else {
1877                return;
1878            };
1879            let client = client.clone();
1880            let sid = session_id.clone();
1881            let span = tracing::error_span!(
1882                "external_tool_handler",
1883                session_id = %sid,
1884                request_id = %request_id
1885            );
1886            tokio::spawn(
1887                async move {
1888                    // `tool_name.is_empty()` would have produced a `None`
1889                    // lookup in `handlers.tools` and short-circuited at the
1890                    // outer guard above, so only the tool_call_id check is
1891                    // reachable here.
1892                    if data.tool_call_id.is_empty() {
1893                        let error_msg = "Missing toolCallId";
1894                        let rpc_start = Instant::now();
1895                        let _ = client
1896                            .call(
1897                                "session.tools.handlePendingToolCall",
1898                                Some(serde_json::json!({
1899                                    "sessionId": sid,
1900                                    "requestId": request_id,
1901                                    "error": error_msg,
1902                                })),
1903                            )
1904                            .await;
1905                        tracing::debug!(
1906                            elapsed_ms = rpc_start.elapsed().as_millis(),
1907                            session_id = %sid,
1908                            request_id = %request_id,
1909                            "Session::handle_notification response sent successfully"
1910                        );
1911                        return;
1912                    }
1913                    let tool_call_id = data.tool_call_id.clone();
1914                    let tool_name = data.tool_name.clone();
1915                    // The built-in tool-search tool receives a snapshot of the
1916                    // session's currently initialized tools so an override can
1917                    // filter the live catalog without issuing its own RPC. Fetch
1918                    // it only for that tool to avoid a round-trip on every tool
1919                    // call; a failed fetch leaves the snapshot `None` rather than
1920                    // failing the tool.
1921                    let available_tools = if tool_name == TOOL_SEARCH_TOOL_NAME {
1922                        match client
1923                            .call(
1924                                rpc_methods::SESSION_TOOLS_GETCURRENTMETADATA,
1925                                Some(serde_json::json!({ "sessionId": sid })),
1926                            )
1927                            .await
1928                        {
1929                            Ok(value) => {
1930                                serde_json::from_value::<ToolsGetCurrentMetadataResult>(value)
1931                                    .ok()
1932                                    .and_then(|result| result.tools)
1933                            }
1934                            Err(_) => None,
1935                        }
1936                    } else {
1937                        None
1938                    };
1939                    let invocation = ToolInvocation {
1940                        session_id: sid.clone(),
1941                        tool_call_id: data.tool_call_id,
1942                        tool_name: data.tool_name,
1943                        arguments: data
1944                            .arguments
1945                            .unwrap_or(Value::Object(serde_json::Map::new())),
1946                        available_tools,
1947                        traceparent: data.traceparent,
1948                        tracestate: data.tracestate,
1949                    };
1950                    let handler_start = Instant::now();
1951                    let tool_result = match tool_handler.call(invocation).await {
1952                        Ok(r) => r,
1953                        Err(e) => tool_failure_result(e.to_string()),
1954                    };
1955                    tracing::debug!(
1956                        elapsed_ms = handler_start.elapsed().as_millis(),
1957                        session_id = %sid,
1958                        request_id = %request_id,
1959                        tool_call_id = %tool_call_id,
1960                        tool_name = %tool_name,
1961                        "ToolHandler::call dispatch"
1962                    );
1963                    let result_value = serde_json::to_value(tool_result).unwrap_or(Value::Null);
1964                    let rpc_start = Instant::now();
1965                    let _ = client
1966                        .call(
1967                            "session.tools.handlePendingToolCall",
1968                            Some(serde_json::json!({
1969                                "sessionId": sid,
1970                                "requestId": request_id,
1971                                "result": result_value,
1972                            })),
1973                        )
1974                        .await;
1975                    tracing::debug!(
1976                        elapsed_ms = rpc_start.elapsed().as_millis(),
1977                        session_id = %sid,
1978                        request_id = %request_id,
1979                        tool_call_id = %tool_call_id,
1980                        tool_name = %tool_name,
1981                        "Session::handle_notification response sent successfully"
1982                    );
1983                }
1984                .instrument(span),
1985            );
1986        }
1987        SessionEventType::UserInputRequested => {
1988            // Notification-only signal for observers (UI, telemetry).
1989            // The CLI follows up with a `userInput.request` JSON-RPC call
1990            // that drives the `UserInputHandler` dispatch — handling
1991            // the notification here too would double-fire the handler
1992            // and produce duplicate prompts on the consumer side. See
1993            // github/github-app#4249.
1994        }
1995        SessionEventType::ElicitationRequested => {
1996            let Some(request_id) = extract_request_id(&notification.event.data) else {
1997                return;
1998            };
1999            // Multi-client safety: if this client has no elicitation
2000            // handler installed, don't respond — another client on the
2001            // same CLI may handle it.
2002            let Some(elicitation_handler) = handlers.elicitation.clone() else {
2003                return;
2004            };
2005            let elicitation_data: ElicitationRequestedData =
2006                match serde_json::from_value(notification.event.data.clone()) {
2007                    Ok(d) => d,
2008                    Err(e) => {
2009                        warn!(error = %e, "failed to deserialize elicitation request");
2010                        return;
2011                    }
2012                };
2013            let request = ElicitationRequest {
2014                message: elicitation_data.message,
2015                requested_schema: elicitation_data
2016                    .requested_schema
2017                    .map(|s| serde_json::to_value(s).unwrap_or(Value::Null)),
2018                mode: elicitation_data.mode.map(|m| match m {
2019                    crate::generated::session_events::ElicitationRequestedMode::Form => {
2020                        crate::types::ElicitationMode::Form
2021                    }
2022                    crate::generated::session_events::ElicitationRequestedMode::Url => {
2023                        crate::types::ElicitationMode::Url
2024                    }
2025                    _ => crate::types::ElicitationMode::Unknown,
2026                }),
2027                elicitation_source: elicitation_data.elicitation_source,
2028                url: elicitation_data.url,
2029            };
2030            let client = client.clone();
2031            let sid = session_id.clone();
2032            let span = tracing::error_span!(
2033                "elicitation_request_handler",
2034                session_id = %sid,
2035                request_id = %request_id
2036            );
2037            tokio::spawn(
2038                async move {
2039                    let cancel = ElicitationResult {
2040                        action: "cancel".to_string(),
2041                        content: None,
2042                    };
2043                    // Dispatch to a nested task so panics are caught as JoinErrors.
2044                    let handler_task = tokio::spawn({
2045                        let sid = sid.clone();
2046                        let request_id = request_id.clone();
2047                        let span = tracing::error_span!(
2048                            "elicitation_callback",
2049                            session_id = %sid,
2050                            request_id = %request_id
2051                        );
2052                        async move {
2053                            let handler_start = Instant::now();
2054                            let response = elicitation_handler
2055                                .handle(sid.clone(), request_id.clone(), request)
2056                                .await;
2057                            tracing::debug!(
2058                                elapsed_ms = handler_start.elapsed().as_millis(),
2059                                session_id = %sid,
2060                                request_id = %request_id,
2061                                "ElicitationHandler::handle dispatch"
2062                            );
2063                            response
2064                        }
2065                        .instrument(span)
2066                    });
2067                    let result = match handler_task.await {
2068                        Ok(r) => r,
2069                        Err(_) => cancel.clone(),
2070                    };
2071                    let rpc_start = Instant::now();
2072                    if let Err(e) = client
2073                        .call(
2074                            "session.ui.handlePendingElicitation",
2075                            Some(serde_json::json!({
2076                                "sessionId": sid,
2077                                "requestId": request_id,
2078                                "result": result,
2079                            })),
2080                        )
2081                        .await
2082                    {
2083                        // RPC failed — attempt cancel as last resort
2084                        warn!(error = %e, "handlePendingElicitation failed, sending cancel");
2085                        let _ = client
2086                            .call(
2087                                "session.ui.handlePendingElicitation",
2088                                Some(serde_json::json!({
2089                                    "sessionId": sid,
2090                                    "requestId": request_id,
2091                                    "result": cancel,
2092                                })),
2093                            )
2094                            .await;
2095                    } else {
2096                        tracing::debug!(
2097                            elapsed_ms = rpc_start.elapsed().as_millis(),
2098                            session_id = %sid,
2099                            request_id = %request_id,
2100                            "Session::handle_notification response sent successfully"
2101                        );
2102                    }
2103                }
2104                .instrument(span),
2105            );
2106        }
2107        SessionEventType::McpOauthRequired => {
2108            let Some(request_id) = extract_request_id(&notification.event.data) else {
2109                return;
2110            };
2111            let Some(mcp_auth_handler) = handlers.mcp_auth.clone() else {
2112                warn!(
2113                    session_id = %session_id,
2114                    request_id = %request_id,
2115                    "received MCP OAuth request without a registered MCP auth handler"
2116                );
2117                return;
2118            };
2119            let data: McpOauthRequiredData =
2120                match serde_json::from_value(notification.event.data.clone()) {
2121                    Ok(d) => d,
2122                    Err(e) => {
2123                        warn!(error = %e, "failed to deserialize MCP OAuth request");
2124                        return;
2125                    }
2126                };
2127            let request = McpAuthRequest {
2128                request_id: request_id.clone(),
2129                server_name: data.server_name,
2130                server_url: data.server_url,
2131                reason: data.reason,
2132                www_authenticate_params: data.www_authenticate_params,
2133                resource_metadata: data.resource_metadata,
2134                static_client_config: data.static_client_config,
2135            };
2136            let client = client.clone();
2137            let sid = session_id.clone();
2138            let span = tracing::error_span!(
2139                "mcp_auth_request_handler",
2140                session_id = %sid,
2141                request_id = %request_id
2142            );
2143            tokio::spawn(
2144                async move {
2145                    let cancel = McpAuthResult::Cancelled;
2146                    let handler_task = tokio::spawn({
2147                        let sid = sid.clone();
2148                        let request_id = request_id.clone();
2149                        let span = tracing::error_span!(
2150                            "mcp_auth_callback",
2151                            session_id = %sid,
2152                            request_id = %request_id
2153                        );
2154                        async move {
2155                            let handler_start = Instant::now();
2156                            let response = mcp_auth_handler
2157                                .handle(sid.clone(), request_id.clone(), request)
2158                                .await;
2159                            tracing::debug!(
2160                                elapsed_ms = handler_start.elapsed().as_millis(),
2161                                session_id = %sid,
2162                                request_id = %request_id,
2163                                "McpAuthHandler::handle dispatch"
2164                            );
2165                            response
2166                        }
2167                        .instrument(span)
2168                    });
2169                    let result = match handler_task.await {
2170                        Ok(result) => result,
2171                        Err(_) => cancel,
2172                    };
2173                    let rpc_start = Instant::now();
2174                    let _ = client
2175                        .call(
2176                            "session.mcp.oauth.handlePendingRequest",
2177                            Some(serde_json::json!({
2178                                "sessionId": sid,
2179                                "requestId": request_id,
2180                                "result": result.into_wire(),
2181                            })),
2182                        )
2183                        .await;
2184                    tracing::debug!(
2185                        elapsed_ms = rpc_start.elapsed().as_millis(),
2186                        "Session::handle_notification MCP auth response sent"
2187                    );
2188                }
2189                .instrument(span),
2190            );
2191        }
2192        SessionEventType::CommandExecute => {
2193            let data: CommandExecuteData =
2194                match serde_json::from_value(notification.event.data.clone()) {
2195                    Ok(d) => d,
2196                    Err(e) => {
2197                        warn!(error = %e, "failed to deserialize command.execute");
2198                        return;
2199                    }
2200                };
2201            let client = client.clone();
2202            let command_handlers = command_handlers.clone();
2203            let sid = session_id.clone();
2204            let span = tracing::error_span!("command_handler", session_id = %sid);
2205            tokio::spawn(
2206                async move {
2207                    let request_id = data.request_id;
2208                    let ack_error = match command_handlers.get(&data.command_name).cloned() {
2209                        None => Some(format!("Unknown command: {}", data.command_name)),
2210                        Some(handler) => {
2211                            let command_name = data.command_name.clone();
2212                            let ctx = CommandContext {
2213                                session_id: sid.clone(),
2214                                command: data.command,
2215                                command_name: data.command_name,
2216                                args: data.args,
2217                            };
2218                            let handler_start = Instant::now();
2219                            let result = handler.on_command(ctx).await;
2220                            tracing::debug!(
2221                                elapsed_ms = handler_start.elapsed().as_millis(),
2222                                session_id = %sid,
2223                                request_id = %request_id,
2224                                command_name = %command_name,
2225                                "CommandHandler::call dispatch"
2226                            );
2227                            match result {
2228                                Ok(()) => None,
2229                                Err(e) => Some(e.to_string()),
2230                            }
2231                        }
2232                    };
2233                    let mut params = serde_json::json!({
2234                        "sessionId": sid,
2235                        "requestId": request_id,
2236                    });
2237                    if let Some(error_msg) = ack_error {
2238                        params["error"] = serde_json::Value::String(error_msg);
2239                    }
2240                    let rpc_start = Instant::now();
2241                    let _ = client
2242                        .call("session.commands.handlePendingCommand", Some(params))
2243                        .await;
2244                    tracing::debug!(
2245                        elapsed_ms = rpc_start.elapsed().as_millis(),
2246                        session_id = %sid,
2247                        request_id = %request_id,
2248                        "Session::handle_notification response sent successfully"
2249                    );
2250                }
2251                .instrument(span),
2252            );
2253        }
2254        _ => {}
2255    }
2256}
2257
2258struct RequestDispatchContext<'a> {
2259    client: &'a Client,
2260    handlers: &'a SessionHandlers,
2261    hooks: Option<&'a dyn SessionHooks>,
2262    transforms: Option<&'a dyn SystemMessageTransform>,
2263    canvas_handler: Option<&'a Arc<dyn CanvasHandler>>,
2264    session_fs_provider: Option<&'a Arc<dyn SessionFsProvider>>,
2265    bearer_token_providers: &'a HashMap<String, Arc<dyn BearerTokenProvider>>,
2266}
2267
2268/// Process a JSON-RPC request from the CLI.
2269async fn handle_request(
2270    session_id: &SessionId,
2271    ctx: RequestDispatchContext<'_>,
2272    request: crate::JsonRpcRequest,
2273) {
2274    let sid = session_id.clone();
2275    let client = ctx.client;
2276    let handlers = ctx.handlers;
2277    let hooks = ctx.hooks;
2278    let transforms = ctx.transforms;
2279    let canvas_handler = ctx.canvas_handler;
2280    let session_fs_provider = ctx.session_fs_provider;
2281    let bearer_token_providers = ctx.bearer_token_providers;
2282
2283    if request.method.starts_with("sessionFs.") {
2284        crate::session_fs_dispatch::dispatch(client, session_fs_provider, request).await;
2285        return;
2286    }
2287
2288    if request.method.starts_with("canvas.") {
2289        crate::canvas_dispatch::dispatch(client, canvas_handler, request).await;
2290        return;
2291    }
2292
2293    if request.method == crate::generated::api_types::rpc_methods::PROVIDERTOKEN_GETTOKEN {
2294        crate::provider_token_dispatch::dispatch(client, bearer_token_providers, request).await;
2295        return;
2296    }
2297
2298    match request.method.as_str() {
2299        "hooks.invoke" => {
2300            let params = request.params.as_ref();
2301            let hook_type = params
2302                .and_then(|p| p.get("hookType"))
2303                .and_then(|v| v.as_str())
2304                .unwrap_or("");
2305            let input = params
2306                .and_then(|p| p.get("input"))
2307                .cloned()
2308                .unwrap_or(Value::Object(Default::default()));
2309
2310            let rpc_result = if let Some(hooks) = hooks {
2311                match crate::hooks::dispatch_hook(hooks, &sid, hook_type, input).await {
2312                    Ok(output) => output,
2313                    Err(e) => {
2314                        warn!(error = %e, hook_type = hook_type, "hook dispatch failed");
2315                        serde_json::json!({ "output": {} })
2316                    }
2317                }
2318            } else {
2319                serde_json::json!({ "output": {} })
2320            };
2321
2322            let rpc_response = JsonRpcResponse {
2323                jsonrpc: "2.0".to_string(),
2324                id: request.id,
2325                result: Some(rpc_result),
2326                error: None,
2327            };
2328            let _ = client.send_response(&rpc_response).await;
2329        }
2330
2331        "userInput.request" => {
2332            let params = request.params.as_ref();
2333            let Some(question) = params
2334                .and_then(|p| p.get("question"))
2335                .and_then(|v| v.as_str())
2336            else {
2337                warn!("userInput.request missing 'question' field");
2338                let rpc_response = JsonRpcResponse {
2339                    jsonrpc: "2.0".to_string(),
2340                    id: request.id,
2341                    result: None,
2342                    error: Some(crate::JsonRpcError {
2343                        code: error_codes::INVALID_PARAMS,
2344                        message: "missing required field: question".to_string(),
2345                        data: None,
2346                    }),
2347                };
2348                let _ = client.send_response(&rpc_response).await;
2349                return;
2350            };
2351            let question = question.to_string();
2352            let choices = params
2353                .and_then(|p| p.get("choices"))
2354                .and_then(|v| v.as_array())
2355                .map(|arr| {
2356                    arr.iter()
2357                        .filter_map(|v| v.as_str().map(|s| s.to_string()))
2358                        .collect()
2359                });
2360            let allow_freeform = params
2361                .and_then(|p| p.get("allowFreeform"))
2362                .and_then(|v| v.as_bool());
2363
2364            let handler_start = Instant::now();
2365            let response = if let Some(user_input_handler) = handlers.user_input.as_ref() {
2366                user_input_handler
2367                    .handle(sid.clone(), question, choices, allow_freeform)
2368                    .await
2369            } else {
2370                None
2371            };
2372            tracing::debug!(
2373                elapsed_ms = handler_start.elapsed().as_millis(),
2374                session_id = %sid,
2375                "UserInputHandler::handle dispatch"
2376            );
2377
2378            let rpc_result = match response {
2379                Some(UserInputResponse {
2380                    answer,
2381                    was_freeform,
2382                }) => serde_json::json!({
2383                    "answer": answer,
2384                    "wasFreeform": was_freeform,
2385                }),
2386                None => serde_json::json!({ "noResponse": true }),
2387            };
2388            let rpc_response = JsonRpcResponse {
2389                jsonrpc: "2.0".to_string(),
2390                id: request.id,
2391                result: Some(rpc_result),
2392                error: None,
2393            };
2394            let _ = client.send_response(&rpc_response).await;
2395        }
2396
2397        "exitPlanMode.request" => {
2398            let params = request
2399                .params
2400                .as_ref()
2401                .cloned()
2402                .unwrap_or(Value::Object(serde_json::Map::new()));
2403            let data: ExitPlanModeData = match serde_json::from_value(params) {
2404                Ok(d) => d,
2405                Err(e) => {
2406                    warn!(error = %e, "failed to deserialize exitPlanMode.request params, using defaults");
2407                    ExitPlanModeData::default()
2408                }
2409            };
2410
2411            let rpc_result = if let Some(exit_plan_handler) = handlers.exit_plan_mode.as_ref() {
2412                let result = exit_plan_handler.handle(sid, data).await;
2413                serde_json::to_value(result).expect("ExitPlanModeResult serialization cannot fail")
2414            } else {
2415                serde_json::json!({ "approved": true })
2416            };
2417            let rpc_response = JsonRpcResponse {
2418                jsonrpc: "2.0".to_string(),
2419                id: request.id,
2420                result: Some(rpc_result),
2421                error: None,
2422            };
2423            let _ = client.send_response(&rpc_response).await;
2424        }
2425
2426        "autoModeSwitch.request" => {
2427            let error_code = request
2428                .params
2429                .as_ref()
2430                .and_then(|p| p.get("errorCode"))
2431                .and_then(|v| v.as_str())
2432                .map(|s| s.to_string());
2433            let retry_after_seconds = request
2434                .params
2435                .as_ref()
2436                .and_then(|p| p.get("retryAfterSeconds"))
2437                .and_then(|v| v.as_f64());
2438
2439            let answer = if let Some(auto_mode_handler) = handlers.auto_mode_switch.as_ref() {
2440                auto_mode_handler
2441                    .handle(sid, error_code, retry_after_seconds)
2442                    .await
2443            } else {
2444                AutoModeSwitchResponse::No
2445            };
2446            let rpc_response = JsonRpcResponse {
2447                jsonrpc: "2.0".to_string(),
2448                id: request.id,
2449                result: Some(serde_json::json!({ "response": answer })),
2450                error: None,
2451            };
2452            let _ = client.send_response(&rpc_response).await;
2453        }
2454
2455        "systemMessage.transform" => {
2456            let params = request.params.as_ref();
2457            let sections: HashMap<String, crate::transforms::TransformSection> =
2458                match params.and_then(|p| p.get("sections")) {
2459                    Some(v) => match serde_json::from_value(v.clone()) {
2460                        Ok(s) => s,
2461                        Err(e) => {
2462                            let _ = send_error_response(
2463                                client,
2464                                request.id,
2465                                error_codes::INVALID_PARAMS,
2466                                &format!("invalid sections: {e}"),
2467                            )
2468                            .await;
2469                            return;
2470                        }
2471                    },
2472                    None => {
2473                        let _ = send_error_response(
2474                            client,
2475                            request.id,
2476                            error_codes::INVALID_PARAMS,
2477                            "missing sections parameter",
2478                        )
2479                        .await;
2480                        return;
2481                    }
2482                };
2483
2484            let rpc_result = if let Some(transforms) = transforms {
2485                let transform_start = Instant::now();
2486                let response =
2487                    crate::transforms::dispatch_transform(transforms, &sid, sections).await;
2488                tracing::debug!(
2489                    elapsed_ms = transform_start.elapsed().as_millis(),
2490                    session_id = %sid,
2491                    "SystemMessageTransform::transform_section dispatch"
2492                );
2493                match serde_json::to_value(response) {
2494                    Ok(v) => v,
2495                    Err(e) => {
2496                        warn!(error = %e, "failed to serialize transform response");
2497                        serde_json::json!({ "sections": {} })
2498                    }
2499                }
2500            } else {
2501                // No transforms registered — pass through all sections unchanged.
2502                let passthrough: HashMap<String, crate::transforms::TransformSection> = sections;
2503                serde_json::json!({ "sections": passthrough })
2504            };
2505
2506            let rpc_response = JsonRpcResponse {
2507                jsonrpc: "2.0".to_string(),
2508                id: request.id,
2509                result: Some(rpc_result),
2510                error: None,
2511            };
2512            let _ = client.send_response(&rpc_response).await;
2513        }
2514
2515        method => {
2516            warn!(
2517                method = method,
2518                "unhandled request method in session event loop"
2519            );
2520            let _ = send_error_response(
2521                client,
2522                request.id,
2523                error_codes::METHOD_NOT_FOUND,
2524                &format!("unknown method: {method}"),
2525            )
2526            .await;
2527        }
2528    }
2529}
2530
2531async fn send_error_response(
2532    client: &Client,
2533    id: u64,
2534    code: i32,
2535    message: &str,
2536) -> Result<(), Error> {
2537    let response = JsonRpcResponse {
2538        jsonrpc: "2.0".to_string(),
2539        id,
2540        result: None,
2541        error: Some(crate::JsonRpcError {
2542            code,
2543            message: message.to_string(),
2544            data: None,
2545        }),
2546    };
2547    client.send_response(&response).await
2548}
2549
2550/// Inject `action: "transform"` sections into a `SystemMessageConfig`,
2551/// forcing `mode: "customize"` (required by the CLI for transforms to fire).
2552/// Preserves any existing caller-provided section overrides.
2553fn apply_transform_sections(
2554    sys_msg: &mut SystemMessageConfig,
2555    transforms: &dyn SystemMessageTransform,
2556) {
2557    sys_msg.mode = Some("customize".to_string());
2558    let sections = sys_msg.sections.get_or_insert_with(HashMap::new);
2559    for id in transforms.section_ids() {
2560        sections.entry(id).or_insert_with(|| SectionOverride {
2561            action: Some("transform".to_string()),
2562            content: None,
2563        });
2564    }
2565}
2566
2567fn inject_transform_sections(config: &mut SessionConfig, transforms: &dyn SystemMessageTransform) {
2568    let sys_msg = config.system_message.get_or_insert_with(Default::default);
2569    apply_transform_sections(sys_msg, transforms);
2570}
2571
2572fn inject_transform_sections_resume(
2573    config: &mut ResumeSessionConfig,
2574    transforms: &dyn SystemMessageTransform,
2575) {
2576    let sys_msg = config.system_message.get_or_insert_with(Default::default);
2577    apply_transform_sections(sys_msg, transforms);
2578}
2579
2580#[cfg(test)]
2581mod tests {
2582    use serde_json::json;
2583
2584    use super::{has_managed_settings, permission_request_data, permission_response_params};
2585    use crate::handler::PermissionResult;
2586    use crate::types::{
2587        PermissionDecisionContext, PermissionDecisionOutcome, PermissionDecisionSource,
2588        PermissionDecisionSurface, RequestId, SessionId,
2589    };
2590
2591    #[test]
2592    fn direct_injection_enables_managed_safeguards() {
2593        let settings = crate::types::ManagedSettings::default();
2594        assert!(has_managed_settings(None, Some(&settings)));
2595        assert!(!has_managed_settings(None, None));
2596    }
2597
2598    fn attribution_context() -> PermissionDecisionContext {
2599        PermissionDecisionContext {
2600            outcome: PermissionDecisionOutcome::AutoApproved,
2601            source: PermissionDecisionSource::AssistedApproval,
2602            surface: PermissionDecisionSurface::CopilotApp,
2603        }
2604    }
2605
2606    #[test]
2607    fn response_params_omit_decision_context_without_attribution() {
2608        for (result, expected) in [
2609            (
2610                PermissionResult::approve_once(),
2611                json!({ "kind": "approve-once" }),
2612            ),
2613            (PermissionResult::reject(None), json!({ "kind": "reject" })),
2614            (
2615                PermissionResult::reject(Some("bad".to_string())),
2616                json!({ "kind": "reject", "feedback": "bad" }),
2617            ),
2618            (
2619                PermissionResult::user_not_available(),
2620                json!({ "kind": "user-not-available" }),
2621            ),
2622        ] {
2623            let params = permission_response_params(
2624                &SessionId::from("session-1"),
2625                &RequestId::from("permission-1"),
2626                &result,
2627            )
2628            .unwrap();
2629            assert_eq!(
2630                params,
2631                json!({
2632                    "sessionId": "session-1",
2633                    "requestId": "permission-1",
2634                    "result": expected,
2635                })
2636            );
2637        }
2638    }
2639
2640    #[test]
2641    fn response_params_forward_decision_context_alongside_result() {
2642        let params = permission_response_params(
2643            &SessionId::from("session-1"),
2644            &RequestId::from("permission-1"),
2645            &PermissionResult::approve_once().with_context(attribution_context()),
2646        )
2647        .unwrap();
2648        assert_eq!(
2649            params,
2650            json!({
2651                "sessionId": "session-1",
2652                "requestId": "permission-1",
2653                "result": { "kind": "approve-once" },
2654                "decisionContext": {
2655                    "outcome": "auto_approved",
2656                    "source": "assisted_approval",
2657                    "surface": "copilot_app",
2658                },
2659            })
2660        );
2661        // The context is a sibling of `result`, never nested inside it.
2662        assert!(params["result"].get("decisionContext").is_none());
2663    }
2664
2665    #[test]
2666    fn response_params_suppressed_for_no_result() {
2667        assert!(
2668            permission_response_params(
2669                &SessionId::from("session-1"),
2670                &RequestId::from("permission-1"),
2671                &PermissionResult::NoResult,
2672            )
2673            .is_none()
2674        );
2675    }
2676
2677    #[test]
2678    fn with_context_is_a_no_op_on_no_result() {
2679        let result = PermissionResult::no_result().with_context(attribution_context());
2680        assert!(matches!(result, PermissionResult::NoResult));
2681    }
2682
2683    #[test]
2684    fn with_context_replaces_rather_than_nests() {
2685        let result = PermissionResult::approve_once()
2686            .with_context(attribution_context())
2687            .with_context(PermissionDecisionContext {
2688                outcome: PermissionDecisionOutcome::PromptedUser,
2689                source: PermissionDecisionSource::HumanResponse,
2690                surface: PermissionDecisionSurface::Sdk,
2691            });
2692        let params = permission_response_params(
2693            &SessionId::from("session-1"),
2694            &RequestId::from("permission-1"),
2695            &result,
2696        )
2697        .unwrap();
2698        assert_eq!(
2699            params["decisionContext"],
2700            json!({
2701                "outcome": "prompted_user",
2702                "source": "human_response",
2703                "surface": "sdk",
2704            })
2705        );
2706    }
2707
2708    #[test]
2709    fn permission_request_data_reads_nested_managed_approval_metadata() {
2710        let data = permission_request_data(
2711            &json!({
2712                "requestId": "permission-1",
2713                "permissionRequest": {
2714                    "kind": "read",
2715                    "managedApprovalRequired": true,
2716                    "path": "/workspace/file.txt"
2717                }
2718            }),
2719            false,
2720        );
2721
2722        assert_eq!(data.managed_approval_required, Some(true));
2723        assert_eq!(
2724            data.extra["permissionRequest"]["path"],
2725            "/workspace/file.txt"
2726        );
2727    }
2728
2729    #[test]
2730    fn permission_request_data_preserves_managed_flag_when_other_fields_are_malformed() {
2731        let data = permission_request_data(
2732            &json!({
2733                "requestId": "permission-1",
2734                "permissionRequest": {
2735                    "kind": "read",
2736                    "managedApprovalRequired": true,
2737                    "toolCallId": 42
2738                }
2739            }),
2740            false,
2741        );
2742
2743        assert_eq!(data.managed_approval_required, Some(true));
2744        assert_eq!(data.extra["requestId"], "permission-1");
2745    }
2746
2747    #[test]
2748    fn permission_request_data_fails_closed_for_malformed_managed_flag() {
2749        let data = permission_request_data(
2750            &json!({
2751                "requestId": "permission-1",
2752                "permissionRequest": {
2753                    "kind": "read",
2754                    "managedApprovalRequired": "yes",
2755                    "path": "/workspace/file.txt"
2756                }
2757            }),
2758            false,
2759        );
2760
2761        assert_eq!(data.managed_approval_required, Some(true));
2762    }
2763
2764    #[test]
2765    fn permission_request_data_preserves_valid_false_managed_flag() {
2766        let data = permission_request_data(
2767            &json!({
2768                "requestId": "permission-1",
2769                "permissionRequest": {
2770                    "kind": "read",
2771                    "managedApprovalRequired": false,
2772                    "path": "/workspace/file.txt"
2773                }
2774            }),
2775            false,
2776        );
2777
2778        assert_eq!(data.managed_approval_required, Some(false));
2779    }
2780}