-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathsession.rs
More file actions
2481 lines (2373 loc) · 101 KB
/
Copy pathsession.rs
File metadata and controls
2481 lines (2373 loc) · 101 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{Duration, Instant};
use parking_lot::Mutex as ParkingLotMutex;
use serde_json::Value;
use tokio::sync::oneshot;
use tokio::task::JoinHandle;
use tokio_util::sync::CancellationToken;
use tracing::{Instrument, warn};
use crate::canvas::CanvasHandler;
use crate::generated::api_types::{
LogRequest, ModelSwitchToRequest, OpenCanvasInstance, RegisterEventInterestParams, rpc_methods,
};
use crate::generated::session_events::{
CommandExecuteData, ElicitationRequestedData, ExternalToolRequestedData, McpOauthRequiredData,
SessionCanvasClosedData, SessionErrorData, SessionEventType,
};
use crate::handler::{
AutoModeSwitchHandler, AutoModeSwitchResponse, ElicitationHandler, ExitPlanModeHandler,
McpAuthHandler, McpAuthRequest, McpAuthResult, PermissionHandler, PermissionResult,
UserInputHandler, UserInputResponse,
};
use crate::hooks::SessionHooks;
use crate::provider_token::BearerTokenProvider;
use crate::session_fs::SessionFsProvider;
use crate::trace_context::inject_trace_context;
use crate::transforms::SystemMessageTransform;
use crate::types::{
CommandContext, CommandDefinition, CommandHandler, CreateSessionResult, ElicitationRequest,
ElicitationResult, ExitPlanModeData, GetMessagesResponse, MessageOptions,
PermissionRequestData, RequestId, ResumeSessionConfig, ResumeSessionResult, SectionOverride,
SessionCapabilities, SessionConfig, SessionEvent, SessionId, SetModelOptions,
SystemMessageConfig, ToolInvocation, ToolResult, ToolResultExpanded, TraceContext,
UiInputOptions, ensure_attachment_display_names,
};
use crate::{
Client, Error, ErrorKind, JsonRpcResponse, SessionErrorKind, SessionEventNotification,
error_codes,
};
/// Bundle of the per-session callbacks the SDK dispatches to. Built from a
/// [`SessionConfig`] / [`ResumeSessionConfig`] at
/// [`Client::create_session`] / [`Client::resume_session`] time. Each
/// field is `None` (or an empty map for tools) when the caller didn't
/// install a handler -- in that case the SDK skips dispatch for that
/// event type. The wire flags on `session.create` / `session.resume`
/// are derived from these fields.
#[derive(Clone)]
pub(crate) struct SessionHandlers {
pub permission: Option<Arc<dyn PermissionHandler>>,
pub elicitation: Option<Arc<dyn ElicitationHandler>>,
pub mcp_auth: Option<Arc<dyn McpAuthHandler>>,
pub user_input: Option<Arc<dyn UserInputHandler>>,
pub exit_plan_mode: Option<Arc<dyn ExitPlanModeHandler>>,
pub auto_mode_switch: Option<Arc<dyn AutoModeSwitchHandler>>,
pub tools: Arc<HashMap<String, Arc<dyn crate::tool::ToolHandler>>>,
}
/// Shared state between a [`Session`] and its event loop, used by [`Session::send_and_wait`].
struct IdleWaiter {
tx: oneshot::Sender<Result<Option<SessionEvent>, Error>>,
last_assistant_message: Option<SessionEvent>,
started_at: Instant,
first_assistant_message_seen: bool,
}
/// RAII guard that clears the [`Session::idle_waiter`] slot on drop. Used
/// by [`Session::send_and_wait`] to ensure the slot doesn't leak if the
/// caller's future is cancelled (outer `tokio::time::timeout` / `select!`
/// / dropped JoinHandle). Synchronous clear via `parking_lot::Mutex` —
/// no async drop needed.
///
/// Without this, an outer cancellation between "install waiter" and
/// "drain channel" would leave the slot occupied, causing all subsequent
/// `send` and `send_and_wait` calls on the session to return
/// [`SendWhileWaiting`](SessionErrorKind::SendWhileWaiting). Closes RFD-400
/// review finding #2.
struct WaiterGuard {
slot: Arc<ParkingLotMutex<Option<IdleWaiter>>>,
}
impl Drop for WaiterGuard {
fn drop(&mut self) {
self.slot.lock().take();
}
}
struct PendingSessionRegistration {
client: Client,
session_id: SessionId,
shutdown: CancellationToken,
disarmed: bool,
}
impl PendingSessionRegistration {
fn new(client: Client, session_id: SessionId, shutdown: CancellationToken) -> Self {
Self {
client,
session_id,
shutdown,
disarmed: false,
}
}
async fn cleanup(mut self, event_loop: JoinHandle<()>) {
self.shutdown.cancel();
let _ = event_loop.await;
self.client.unregister_session(&self.session_id);
self.disarmed = true;
}
fn disarm(&mut self) {
self.disarmed = true;
}
}
impl Drop for PendingSessionRegistration {
fn drop(&mut self) {
if !self.disarmed {
self.shutdown.cancel();
self.client.unregister_session(&self.session_id);
}
}
}
/// A session on a GitHub Copilot CLI server.
///
/// Created via [`Client::create_session`] or [`Client::resume_session`].
/// Owns an internal event loop that dispatches events to the per-callback
/// handlers installed on the session config.
///
/// Protocol methods (`send`, `get_events`, `abort`, etc.) automatically
/// inject the session ID into RPC params.
///
/// Call [`destroy`](Self::destroy) for graceful cleanup (RPC + local). If dropped
/// without calling `destroy`, the `Drop` impl aborts the event loop and
/// unregisters from the router as a best-effort safety net.
pub struct Session {
id: SessionId,
cwd: PathBuf,
workspace_path: Option<PathBuf>,
remote_url: Option<String>,
client: Client,
/// Handle to the spawned event-loop task. Sync `parking_lot::Mutex`
/// because the lock is never held across an `.await` and the `Drop`
/// impl needs to take the handle synchronously without `try_lock`
/// fallibility.
event_loop: ParkingLotMutex<Option<JoinHandle<()>>>,
/// Cooperative shutdown signal for the event loop. The loop selects
/// on [`shutdown.cancelled()`](CancellationToken::cancelled) alongside
/// its inbound channels; [`Session::stop_event_loop`] and [`Drop`]
/// both call [`cancel()`](CancellationToken::cancel) to ask the loop
/// to exit between iterations rather than aborting the task (which
/// can land at any await point and leave the session mid-protocol).
/// See RFD-400 review finding #3.
///
/// `CancellationToken` is the canonical signalling primitive in
/// `tokio_util`; it is what `tonic` uses for the equivalent task-
/// coordination case. Advanced consumers can obtain a child token
/// via [`Session::cancellation_token`] to bind their own work to
/// the session lifetime.
shutdown: CancellationToken,
/// Only populated while a `send_and_wait` call is in flight.
///
/// Sync `parking_lot::Mutex` because the lock is never held across an
/// `.await`, and synchronous access lets the `WaiterGuard` RAII helper
/// in `send_and_wait` clear the slot from a `Drop` impl on caller-side
/// cancellation. See RFD-400 review (cancel-safety hardening).
idle_waiter: Arc<ParkingLotMutex<Option<IdleWaiter>>>,
/// Capabilities negotiated with the CLI, updated on `capabilities.changed` events.
capabilities: Arc<parking_lot::RwLock<SessionCapabilities>>,
/// Canvas instances currently known to be open for this session.
open_canvases: Arc<parking_lot::RwLock<Vec<OpenCanvasInstance>>>,
/// Broadcast channel for runtime event subscribers — see [`Session::subscribe`].
event_tx: tokio::sync::broadcast::Sender<SessionEvent>,
}
impl Session {
/// Session ID assigned by the CLI.
pub fn id(&self) -> &SessionId {
&self.id
}
/// Working directory of the CLI process.
pub fn cwd(&self) -> &PathBuf {
&self.cwd
}
/// Workspace directory for the session (if using infinite sessions).
pub fn workspace_path(&self) -> Option<&Path> {
self.workspace_path.as_deref()
}
/// Remote session URL, if the session is running remotely.
pub fn remote_url(&self) -> Option<&str> {
self.remote_url.as_deref()
}
/// Session capabilities negotiated with the CLI.
///
/// Capabilities are set during session creation and updated at runtime
/// via `capabilities.changed` events.
pub fn capabilities(&self) -> SessionCapabilities {
self.capabilities.read().clone()
}
/// Open canvas instances reported by the most recent `session.resume`
/// response or surfaced by inbound `canvas.opened` events.
pub fn open_canvases(&self) -> Vec<OpenCanvasInstance> {
self.open_canvases.read().clone()
}
/// Returns a [`CancellationToken`] that fires when this session shuts
/// down (via [`Session::stop_event_loop`], [`Session::destroy`], or
/// [`Drop`]).
///
/// Use this to bind an external task's lifetime to the session — when
/// the session shuts down, awaiting [`cancelled()`](CancellationToken::cancelled)
/// resolves so cooperative consumers can stop cleanly.
///
/// The returned handle is a *child* token: calling
/// [`cancel()`](CancellationToken::cancel) on it cancels only the
/// caller's child, not the session itself. To cancel the session, call
/// [`Session::stop_event_loop`].
///
/// # Example
///
/// ```no_run
/// # async fn example(session: github_copilot_sdk::session::Session) {
/// let token = session.cancellation_token();
/// tokio::select! {
/// _ = token.cancelled() => println!("session shut down"),
/// _ = tokio::time::sleep(std::time::Duration::from_secs(60)) => {
/// println!("60s elapsed, session still alive");
/// }
/// }
/// # }
/// ```
pub fn cancellation_token(&self) -> CancellationToken {
self.shutdown.child_token()
}
/// Subscribe to events for this session.
///
/// Returns an [`EventSubscription`](crate::subscription::EventSubscription)
/// that yields every [`SessionEvent`] dispatched on this session's
/// event loop. Drop the value to unsubscribe; there is no separate
/// cancel handle.
///
/// **Observe-only.** Subscribers receive a clone of every
/// [`SessionEvent`] but cannot influence permission decisions, tool
/// results, or anything else that requires returning a value. Those
/// remain the responsibility of the per-callback handlers passed via
/// [`SessionConfig`]'s `with_*_handler`
/// builder methods.
///
/// The returned handle implements both an inherent
/// [`recv`](crate::subscription::EventSubscription::recv) method and
/// [`Stream`](tokio_stream::Stream), so callers can use a `while let`
/// loop or any combinator from `tokio_stream::StreamExt` /
/// `futures::StreamExt`.
///
/// Each subscriber maintains its own queue. If a consumer cannot keep
/// up, the oldest events are dropped and `recv` returns
/// [`RecvErrorKind::Lagged`](crate::subscription::RecvErrorKind::Lagged)
/// reporting the count of skipped events. Slow consumers do not block
/// the session's event loop.
///
/// # Example
///
/// ```no_run
/// # async fn example(session: github_copilot_sdk::session::Session) {
/// let mut events = session.subscribe();
/// tokio::spawn(async move {
/// while let Ok(event) = events.recv().await {
/// println!("[{}] event {}", event.id, event.event_type);
/// }
/// });
/// # }
/// ```
pub fn subscribe(&self) -> crate::subscription::EventSubscription {
crate::subscription::EventSubscription::new(self.event_tx.subscribe())
}
/// The underlying Client (for advanced use cases).
pub fn client(&self) -> &Client {
&self.client
}
/// Typed RPC namespace for this session.
///
/// Every protocol method lives here under its schema-aligned path —
/// e.g. `session.rpc().workspaces().list_files()`. Wire method names
/// and request/response types are generated from the protocol schema,
/// so the typed namespace can't drift from the wire contract.
///
/// The hand-authored helpers on [`Session`] delegate to this namespace
/// and remain the recommended entry point for everyday use; reach for
/// `rpc()` when you want a method without a hand-written wrapper.
pub fn rpc(&self) -> crate::generated::rpc::SessionRpc<'_> {
crate::generated::rpc::SessionRpc { session: self }
}
/// Stop the internal event loop. Called automatically on [`destroy`](Self::destroy).
///
/// Cooperative: signals shutdown via the session's [`CancellationToken`]
/// and awaits the loop's natural exit rather than aborting the task.
/// Any in-flight handler (permission callback, tool call, elicitation
/// response) completes before the loop exits, so the CLI never sees a
/// half-handled request. See RFD-400 review finding #3.
pub async fn stop_event_loop(&self) {
self.shutdown.cancel();
let handle = self.event_loop.lock().take();
if let Some(handle) = handle {
let _ = handle.await;
}
// Fail any pending send_and_wait so it returns immediately.
if let Some(waiter) = self.idle_waiter.lock().take() {
let _ = waiter.tx.send(Err(
ErrorKind::Session(SessionErrorKind::EventLoopClosed).into()
));
}
}
/// Send a user message to the agent.
///
/// Accepts anything convertible to [`MessageOptions`] — pass a `&str` for the
/// trivial case, or build a `MessageOptions` for mode/attachments. The
/// `wait_timeout` field on `MessageOptions` is ignored here (use
/// [`send_and_wait`](Self::send_and_wait) if you need to wait).
///
/// Returns the assigned message ID, which can be used to correlate the
/// send with later [`SessionEvent`]s emitted in
/// response (assistant messages, tool requests, etc.).
///
/// Returns an error if a [`send_and_wait`](Self::send_and_wait) call is
/// currently in flight, since the plain send would race with the waiter.
///
/// # Cancel safety
///
/// **Cancel-safe.** The underlying `session.send` RPC is dispatched
/// through the writer-actor (see [`Client::call`](crate::Client::call)),
/// so dropping this future after the actor has committed to writing
/// will not produce a partial frame on the wire. If the caller's
/// future is dropped between "frame enqueued" and "response received",
/// the message has already landed on the wire — the agent will process
/// it and emit events normally; the caller just won't see the returned
/// message ID.
pub async fn send(&self, opts: impl Into<MessageOptions>) -> Result<String, Error> {
if self.idle_waiter.lock().is_some() {
return Err(ErrorKind::Session(SessionErrorKind::SendWhileWaiting).into());
}
self.send_inner(opts.into()).await
}
async fn send_inner(&self, opts: MessageOptions) -> Result<String, Error> {
let mut params = serde_json::json!({
"sessionId": self.id,
"prompt": opts.prompt,
});
if let Some(m) = opts.mode {
params["mode"] = serde_json::to_value(m)?;
}
if let Some(am) = opts.agent_mode {
params["agentMode"] = serde_json::to_value(am)?;
}
if let Some(mut a) = opts.attachments {
ensure_attachment_display_names(&mut a);
params["attachments"] = serde_json::to_value(a)?;
}
if let Some(headers) = opts.request_headers
&& !headers.is_empty()
{
params["requestHeaders"] = serde_json::to_value(headers)?;
}
if let Some(display_prompt) = opts.display_prompt {
params["displayPrompt"] = serde_json::to_value(display_prompt)?;
}
let trace_ctx = if opts.traceparent.is_some() || opts.tracestate.is_some() {
TraceContext {
traceparent: opts.traceparent,
tracestate: opts.tracestate,
}
} else {
self.client.resolve_trace_context().await
};
inject_trace_context(&mut params, &trace_ctx);
let rpc_start = Instant::now();
let result = self.client.call("session.send", Some(params)).await?;
let message_id = result
.get("messageId")
.and_then(|v| v.as_str())
.map(|s| s.to_string())
.unwrap_or_default();
tracing::debug!(
elapsed_ms = rpc_start.elapsed().as_millis(),
session_id = %self.id,
message_id = %message_id,
"Session::send completed successfully"
);
Ok(message_id)
}
/// Send a user message and wait for the agent to finish processing.
///
/// Accepts anything convertible to [`MessageOptions`] — pass a `&str` for the
/// trivial case, or build a `MessageOptions` for mode/attachments/timeout.
/// Blocks until `session.idle` (success) or `session.error` (failure),
/// returning the last `assistant.message` event captured during streaming.
/// Times out after `MessageOptions::wait_timeout` (default 60 seconds).
///
/// Only one `send_and_wait` call may be active per session at a time.
/// Calling [`send`](Self::send) while a `send_and_wait`
/// is in flight will also return an error.
///
/// # Cancel safety
///
/// **Cancel-safe.** A `WaiterGuard` clears the in-flight slot on every
/// exit path (success, internal failure, internal timeout, *and*
/// external cancellation via `tokio::time::timeout` / `select!` /
/// dropped JoinHandle). Subsequent `send` and `send_and_wait` calls on
/// this session will succeed normally — the slot is never leaked.
pub async fn send_and_wait(
&self,
opts: impl Into<MessageOptions>,
) -> Result<Option<SessionEvent>, Error> {
let total_start = Instant::now();
let opts = opts.into();
let timeout_duration = opts.wait_timeout.unwrap_or(Duration::from_secs(60));
let (tx, rx) = oneshot::channel();
{
let mut guard = self.idle_waiter.lock();
if guard.is_some() {
return Err(ErrorKind::Session(SessionErrorKind::SendWhileWaiting).into());
}
*guard = Some(IdleWaiter {
tx,
last_assistant_message: None,
started_at: total_start,
first_assistant_message_seen: false,
});
}
// RAII: clears the idle_waiter slot on every exit path, including
// external cancellation (caller's outer `select!` / `timeout` /
// dropped future). Without this, an outer cancellation would leak
// the slot and brick subsequent `send`/`send_and_wait` calls.
let _waiter_guard = WaiterGuard {
slot: self.idle_waiter.clone(),
};
let result = tokio::time::timeout(timeout_duration, async {
self.send_inner(opts).await?;
match rx.await {
Ok(result) => result,
Err(_) => Err(ErrorKind::Session(SessionErrorKind::EventLoopClosed).into()),
}
})
.await;
match result {
Ok(inner) => {
tracing::debug!(
elapsed_ms = total_start.elapsed().as_millis(),
session_id = %self.id,
completed_by = if inner.is_ok() { "idle" } else { "error" },
"Session::send_and_wait complete"
);
inner
}
Err(_) => {
tracing::warn!(
elapsed_ms = total_start.elapsed().as_millis(),
session_id = %self.id,
completed_by = "timeout",
"Session::send_and_wait failed"
);
Err(ErrorKind::Session(SessionErrorKind::Timeout(timeout_duration)).into())
}
}
}
/// Retrieve the session's timeline events.
pub async fn get_events(&self) -> Result<Vec<SessionEvent>, Error> {
let result = self
.client
.call(
"session.getMessages",
Some(serde_json::json!({ "sessionId": self.id })),
)
.await?;
let response: GetMessagesResponse = serde_json::from_value(result)?;
Ok(response.events)
}
/// Deprecated alias for [`get_events`](Self::get_events).
#[deprecated(since = "0.1.0", note = "Use `get_events()` instead")]
pub async fn get_messages(&self) -> Result<Vec<SessionEvent>, Error> {
self.get_events().await
}
/// Abort the current agent turn.
///
/// # Cancel safety
///
/// **Cancel-safe.** Single `session.abort` RPC; the underlying
/// [`Client::call`](crate::Client::call) is cancel-safe via the
/// writer-actor.
pub async fn abort(&self) -> Result<(), Error> {
self.client
.call(
"session.abort",
Some(serde_json::json!({ "sessionId": self.id })),
)
.await?;
Ok(())
}
/// Switch to a different model.
///
/// Pass `None` for `opts` if no extra configuration is needed.
pub async fn set_model(&self, model: &str, opts: Option<SetModelOptions>) -> Result<(), Error> {
let opts = opts.unwrap_or_default();
let request = ModelSwitchToRequest {
model_id: model.to_string(),
reasoning_effort: opts.reasoning_effort,
reasoning_summary: opts.reasoning_summary,
verbosity: None,
context_tier: opts.context_tier,
model_capabilities: opts.model_capabilities,
};
self.rpc().model().switch_to(request).await?;
Ok(())
}
/// Disconnect this session from the CLI.
///
/// Sends the `session.destroy` RPC, stops the event loop, and unregisters
/// the session from the client. **Session state on disk** (conversation
/// history, planning state, artifacts) is **preserved**, so the
/// conversation can be resumed later via [`Client::resume_session`]
/// using this session's ID. To permanently remove all on-disk session
/// data, use [`Client::delete_session`] instead.
///
/// The caller should ensure the session is idle (e.g. [`send_and_wait`]
/// has returned) before disconnecting; in-flight tool or event handlers
/// may otherwise observe failures.
///
/// [`Client::resume_session`]: crate::Client::resume_session
/// [`Client::delete_session`]: crate::Client::delete_session
/// [`send_and_wait`]: Self::send_and_wait
pub async fn disconnect(&self) -> Result<(), Error> {
self.client
.call(
"session.destroy",
Some(serde_json::json!({ "sessionId": self.id })),
)
.await?;
self.stop_event_loop().await;
self.client.unregister_session(&self.id);
Ok(())
}
/// Deprecated alias for [`disconnect`](Self::disconnect). The
/// underlying wire RPC happens to be named `session.destroy`, but it
/// only severs the connection — on-disk session state is preserved.
/// Prefer `disconnect` in new code.
#[deprecated(since = "0.1.0", note = "Use `disconnect()` instead")]
pub async fn destroy(&self) -> Result<(), Error> {
self.disconnect().await
}
/// Write a log message to the session.
///
/// Pass `None` for `opts` to use defaults (info level, persisted).
pub async fn log(
&self,
message: &str,
opts: Option<crate::types::LogOptions>,
) -> Result<(), Error> {
let opts = opts.unwrap_or_default();
let level = match opts.level {
Some(level) => Some(serde_json::from_value(serde_json::to_value(level)?)?),
None => None,
};
let request = LogRequest {
message: message.to_string(),
level,
ephemeral: opts.ephemeral,
r#type: None,
tip: None,
url: None,
};
self.rpc().log(request).await?;
Ok(())
}
/// Returns the UI sub-API for elicitation, confirmation, selection, and
/// free-form input.
///
/// All UI methods route through `session.ui.*` RPCs and require host
/// support — check `session.capabilities().ui.elicitation` before use.
pub fn ui(&self) -> SessionUi<'_> {
SessionUi { session: self }
}
/// Returns an error if the host doesn't support elicitation.
fn assert_elicitation(&self) -> Result<(), Error> {
if self
.capabilities
.read()
.ui
.as_ref()
.and_then(|u| u.elicitation)
!= Some(true)
{
return Err(ErrorKind::Session(SessionErrorKind::ElicitationNotSupported).into());
}
Ok(())
}
}
impl Drop for Session {
fn drop(&mut self) {
// Cooperative shutdown: cancel the event loop's token to signal
// exit between iterations. The loop will see the cancellation on
// its next select poll and break cleanly without interrupting an
// in-flight handler. We do NOT abort the JoinHandle — that would
// land at any await point in the loop body, potentially leaving
// the CLI with an unanswered request id. RFD-400 review finding
// #3.
//
// The handle itself is left in `event_loop` to be reaped by the
// tokio runtime when it next polls; we intentionally don't await
// it here because Drop is sync.
self.shutdown.cancel();
self.client.unregister_session(&self.id);
}
}
/// UI sub-API for a [`Session`] — elicitation, confirmation, selection,
/// and free-form input.
///
/// Acquired via [`Session::ui`]. Methods route to `session.ui.*` RPCs and
/// require host elicitation support — check
/// `session.capabilities().ui.elicitation` before use.
pub struct SessionUi<'a> {
session: &'a Session,
}
impl<'a> SessionUi<'a> {
/// Request user input via an interactive UI form (elicitation).
///
/// Sends a JSON Schema describing form fields to the CLI host. The host
/// renders a form dialog and returns the user's response.
///
/// Prefer the typed convenience methods [`confirm`](Self::confirm),
/// [`select`](Self::select), and [`input`](Self::input) for common cases.
pub async fn elicitation(
&self,
message: &str,
schema: Value,
) -> Result<ElicitationResult, Error> {
self.session.assert_elicitation()?;
let result = self
.session
.client
.call(
"session.ui.elicitation",
Some(serde_json::json!({
"sessionId": self.session.id,
"message": message,
"requestedSchema": schema,
})),
)
.await?;
let elicitation: ElicitationResult = serde_json::from_value(result)?;
Ok(elicitation)
}
/// Ask the user a yes/no confirmation question.
///
/// Returns `true` if the user accepted and confirmed, `false` otherwise.
pub async fn confirm(&self, message: &str) -> Result<bool, Error> {
self.session.assert_elicitation()?;
let schema = serde_json::json!({
"type": "object",
"properties": {
"confirmed": {
"type": "boolean",
"default": true,
}
},
"required": ["confirmed"]
});
let result = self.elicitation(message, schema).await?;
Ok(result.action == "accept"
&& result
.content
.and_then(|c| c.get("confirmed").and_then(|v| v.as_bool()))
== Some(true))
}
/// Ask the user to select from a list of options.
///
/// Returns the selected option string on accept, or `None` on decline/cancel.
pub async fn select(&self, message: &str, options: &[&str]) -> Result<Option<String>, Error> {
self.session.assert_elicitation()?;
let schema = serde_json::json!({
"type": "object",
"properties": {
"selection": {
"type": "string",
"enum": options,
}
},
"required": ["selection"]
});
let result = self.elicitation(message, schema).await?;
if result.action != "accept" {
return Ok(None);
}
let selection = result.content.and_then(|c| {
c.get("selection")
.and_then(|v| v.as_str())
.map(String::from)
});
Ok(selection)
}
/// Ask the user for free-form text input.
///
/// Returns the input string on accept, or `None` on decline/cancel.
/// Use [`UiInputOptions`] to set validation constraints and field metadata.
pub async fn input(
&self,
message: &str,
options: Option<&UiInputOptions<'_>>,
) -> Result<Option<String>, Error> {
self.session.assert_elicitation()?;
let mut field = serde_json::json!({ "type": "string" });
if let Some(opts) = options {
if let Some(title) = opts.title {
field["title"] = Value::String(title.to_string());
}
if let Some(desc) = opts.description {
field["description"] = Value::String(desc.to_string());
}
if let Some(min) = opts.min_length {
field["minLength"] = Value::Number(min.into());
}
if let Some(max) = opts.max_length {
field["maxLength"] = Value::Number(max.into());
}
if let Some(fmt) = &opts.format {
field["format"] = Value::String(fmt.as_str().to_string());
}
if let Some(default) = opts.default {
field["default"] = Value::String(default.to_string());
}
}
let schema = serde_json::json!({
"type": "object",
"properties": { "value": field },
"required": ["value"]
});
let result = self.elicitation(message, schema).await?;
if result.action != "accept" {
return Ok(None);
}
let value = result
.content
.and_then(|c| c.get("value").and_then(|v| v.as_str()).map(String::from));
Ok(value)
}
}
impl Client {
/// Create a new session on the CLI.
///
/// Sends `session.create`, registers the session on the router,
/// and spawns an internal event loop that dispatches to the handler.
///
/// All callbacks (per-event handlers, tool handlers, hooks, transform)
/// are configured via [`SessionConfig`] using its `with_*_handler` /
/// `with_tools` / `with_hooks` / `with_system_message_transform` builder
/// methods.
///
/// If [`hooks_handler`](SessionConfig::hooks_handler) is set, the
/// wire-level `hooks` flag is automatically enabled.
///
/// If [`system_message_transform`](SessionConfig::system_message_transform) is set, the SDK injects
/// `action: "transform"` sections into the [`SystemMessageConfig`] wire
/// format and handles `systemMessage.transform` RPC callbacks during
/// the session.
///
/// Each per-event handler is independently optional. If a handler is
/// not installed, the SDK signals the runtime not to emit the matching
/// broadcast (and silently skips dispatch if one arrives anyway).
pub async fn create_session(&self, mut config: SessionConfig) -> Result<Session, Error> {
let total_start = Instant::now();
// For cloud sessions, let the CLI/server assign the session id and
// register the session lazily once the response arrives. For non-cloud
// sessions we generate the id client-side (when the caller didn't
// supply one) so the session can be registered BEFORE the RPC — the
// CLI may issue session-scoped requests (e.g. sessionFs.writeFile for
// workspace metadata) during session.create processing, before it has
// sent the response.
let caller_session_id = config.session_id.clone();
let use_server_generated_id = config.cloud.is_some() && caller_session_id.is_none();
let local_session_id: Option<SessionId> = if use_server_generated_id {
None
} else {
Some(
caller_session_id
.clone()
.unwrap_or_else(|| SessionId::new(uuid::Uuid::new_v4().to_string())),
)
};
if config.hooks_handler.is_some() && config.hooks.is_none() {
config.hooks = Some(true);
}
if let Some(transforms) = config.system_message_transform.clone() {
inject_transform_sections(&mut config, transforms.as_ref());
}
let mode = self.inner.mode;
if mode == crate::ClientMode::Empty && config.available_tools.is_none() {
return Err(Error::with_message(
ErrorKind::InvalidConfig,
"ClientMode::Empty requires available_tools to be set on the session config. \
Use ToolSet to specify which tools the session may use (e.g. \
ToolSet::new().add_builtin_many(BUILTIN_TOOLS_ISOLATED)).",
));
}
crate::mode::validate_tool_filter_list(
"available_tools",
config.available_tools.as_deref(),
)?;
crate::mode::validate_tool_filter_list("excluded_tools", config.excluded_tools.as_deref())?;
config.system_message =
crate::mode::system_message_for_mode(mode, config.system_message.take());
config.memory = crate::mode::memory_for_mode(mode, config.memory.take());
if mode == crate::ClientMode::Empty {
if config.enable_session_telemetry.is_none() {
config.enable_session_telemetry = Some(false);
}
if config.skip_embedding_retrieval.is_none() {
config.skip_embedding_retrieval = Some(true);
}
if config.enable_on_demand_instruction_discovery.is_none() {
config.enable_on_demand_instruction_discovery = Some(false);
}
if config.enable_file_hooks.is_none() {
config.enable_file_hooks = Some(false);
}
if config.enable_host_git_operations.is_none() {
config.enable_host_git_operations = Some(false);
}
if config.enable_session_store.is_none() {
config.enable_session_store = Some(false);
}
if config.enable_skills.is_none() {
config.enable_skills = Some(false);
}
}
if mode == crate::ClientMode::Empty && config.mcp_oauth_token_storage.is_none() {
config.mcp_oauth_token_storage = Some("in-memory".into());
}
if mode == crate::ClientMode::Empty && config.embedding_cache_storage.is_none() {
config.embedding_cache_storage = Some("in-memory".into());
}
let opt_skip_custom_instructions = config.skip_custom_instructions;
let opt_custom_agents_local_only = config.custom_agents_local_only;
let opt_coauthor_enabled = config.coauthor_enabled;
let opt_manage_schedule_enabled = config.manage_schedule_enabled;
let (mut wire, mut runtime) = config.into_wire(local_session_id.clone())?;
wire.enable_github_telemetry_forwarding =
self.inner.on_github_telemetry.is_some().then_some(true);
let permission_handler = crate::permission::resolve_handler(
runtime.permission_handler.take(),
runtime.permission_policy.take(),
);
let handlers = SessionHandlers {
permission: permission_handler,
elicitation: runtime.elicitation_handler.take(),
mcp_auth: runtime.mcp_auth_handler.take(),
user_input: runtime.user_input_handler.take(),
exit_plan_mode: runtime.exit_plan_mode_handler.take(),
auto_mode_switch: runtime.auto_mode_switch_handler.take(),
tools: Arc::new(std::mem::take(&mut runtime.tool_handlers)),
};
let hooks = runtime.hooks_handler.take();
let transforms = runtime.system_message_transform.take();
let tools_count = wire.tools.as_ref().map_or(0, Vec::len);
let commands_count = runtime.commands.as_ref().map_or(0, Vec::len);
let has_hooks = hooks.is_some();
let command_handlers = build_command_handler_map(runtime.commands.as_deref());
let canvas_handler = runtime.canvas_handler.take();
let session_fs_provider = runtime.session_fs_provider.take();
let bearer_token_providers = std::mem::take(&mut runtime.bearer_token_providers);
let has_mcp_auth_handler = handlers.mcp_auth.is_some();
if self.inner.session_fs_configured && session_fs_provider.is_none() {
return Err(ErrorKind::Session(SessionErrorKind::SessionFsProviderRequired).into());
}
if self.inner.session_fs_sqlite_declared
&& let Some(ref provider) = session_fs_provider
&& provider.sqlite().is_none()
{
return Err(Error::with_message(
ErrorKind::InvalidConfig,
"SessionFs capabilities declare SQLite support but the provider \
does not implement SessionFsSqliteProvider",
));
}
let mut params = serde_json::to_value(&wire)?;
let trace_ctx = self.resolve_trace_context().await;
inject_trace_context(&mut params, &trace_ctx);
let setup_start = Instant::now();
let capabilities = Arc::new(parking_lot::RwLock::new(SessionCapabilities::default()));
let idle_waiter = Arc::new(ParkingLotMutex::new(None));
let open_canvases = Arc::new(parking_lot::RwLock::new(Vec::new()));
let shutdown = CancellationToken::new();
let (event_tx, _) = tokio::sync::broadcast::channel(512);
// For cloud sessions (use_server_generated_id), defer session
// registration to the inline callback so the read task registers
// the session synchronously the instant the response arrives.
// For non-cloud sessions, register up-front so the CLI can issue
// session-scoped requests during session.create processing.
let inline_stash: Arc<
ParkingLotMutex<Option<(SessionId, crate::router::SessionChannels)>>,
> = Arc::new(ParkingLotMutex::new(None));
let inline_callback: Option<crate::jsonrpc::InlineResponseCallback> = if let Some(ref sid) =
local_session_id
{
let channels = self.register_session(sid);
*inline_stash.lock() = Some((sid.clone(), channels));
None
} else {
let client = self.clone();
let stash = inline_stash.clone();
let expected = caller_session_id.clone();
Some(Box::new(move |response| {
let result = response.result.as_ref().ok_or_else(|| {
Error::with_message(ErrorKind::Json, "session.create response had no result")
})?;
let parsed: CreateSessionResult =
serde_json::from_value(result.clone()).map_err(Error::from)?;
if let Some(requested) = expected.as_ref()
&& parsed.session_id != *requested
{
return Err(ErrorKind::Session(SessionErrorKind::SessionIdMismatch {
requested: requested.clone(),
returned: parsed.session_id,
})
.into());
}
let channels = client.register_session(&parsed.session_id);
*stash.lock() = Some((parsed.session_id, channels));
Ok(())
}))
};
let rpc_start = Instant::now();
let result = match self
.call_with_inline_callback("session.create", Some(params), inline_callback)
.await
{
Ok(result) => result,
Err(error) => {
if let Some((id, _channels)) = inline_stash.lock().take() {
self.unregister_session(&id);
}
return Err(error);
}
};
tracing::debug!(
elapsed_ms = rpc_start.elapsed().as_millis(),
"Client::create_session session creation request completed successfully"
);
let create_result: CreateSessionResult = match serde_json::from_value(result) {
Ok(result) => result,
Err(error) => {
if let Some((id, _channels)) = inline_stash.lock().take() {
self.unregister_session(&id);
}
return Err(error.into());
}
};
if let Some(ref requested) = local_session_id
&& create_result.session_id != *requested