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