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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
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::generated::api_types::{
LogRequest, ModelSwitchToRequest, PermissionDecision, PermissionDecisionApproveOnce,
PermissionDecisionApproveOnceKind, PermissionDecisionReject, PermissionDecisionRejectKind,
};
use crate::generated::session_events::{
CommandExecuteData, ElicitationRequestedData, ExternalToolRequestedData, SessionErrorData,
SessionEventType,
};
use crate::handler::{
AutoModeSwitchResponse, ExitPlanModeResult, HandlerEvent, HandlerResponse, PermissionResult,
SessionHandler, UserInputResponse,
};
use crate::hooks::SessionHooks;
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, InputOptions, MessageOptions,
PermissionRequestData, RequestId, ResumeSessionConfig, SectionOverride, SessionCapabilities,
SessionConfig, SessionEvent, SessionId, SetModelOptions, SystemMessageConfig, ToolInvocation,
ToolResult, ToolResultResponse, TraceContext, ensure_attachment_display_names,
};
use crate::{Client, Error, JsonRpcResponse, SessionError, SessionEventNotification, error_codes};
/// 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>,
}
/// 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`](SessionError::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();
}
}
/// 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 [`SessionHandler`].
///
/// Protocol methods (`send`, `get_messages`, `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>>,
/// 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()
}
/// 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
/// [`HandlerResponse`]. Those remain
/// the responsibility of the [`SessionHandler`] passed via
/// [`SessionConfig::handler`](crate::types::SessionConfig::handler).
///
/// 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
/// [`RecvError::Lagged`](crate::subscription::RecvError::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(Error::Session(SessionError::EventLoopClosed)));
}
}
/// 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(Error::Session(SessionError::SendWhileWaiting));
}
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(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)?;
}
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 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();
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 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(Error::Session(SessionError::SendWhileWaiting));
}
*guard = Some(IdleWaiter {
tx,
last_assistant_message: None,
});
}
// 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(Error::Session(SessionError::EventLoopClosed)),
}
})
.await;
match result {
Ok(inner) => inner,
Err(_) => Err(Error::Session(SessionError::Timeout(timeout_duration))),
}
}
/// Retrieve the session's message history.
pub async fn get_messages(&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)
}
/// 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,
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(())
}
/// Alias for [`disconnect`](Self::disconnect).
///
/// Named after the `session.destroy` wire RPC. Prefer `disconnect` in
/// new code — the wire-level "destroy" is misleading because on-disk
/// state is preserved.
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,
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(Error::Session(SessionError::ElicitationNotSupported));
}
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 [`InputOptions`] to set validation constraints and field metadata.
pub async fn input(
&self,
message: &str,
options: Option<&InputOptions<'_>>,
) -> 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 (event handler, hooks, transform) are configured
/// via [`SessionConfig`] using [`with_handler`](SessionConfig::with_handler),
/// [`with_hooks`](SessionConfig::with_hooks), and
/// [`with_transform`](SessionConfig::with_transform).
///
/// If [`hooks_handler`](SessionConfig::hooks_handler) is set, the
/// wire-level `hooks` flag is automatically enabled.
///
/// If [`transform`](SessionConfig::transform) is set, the SDK injects
/// `action: "transform"` sections into the [`SystemMessageConfig`] wire
/// format and handles `systemMessage.transform` RPC callbacks during
/// the session.
///
/// If [`handler`](SessionConfig::handler) is `None`, the session uses
/// [`DenyAllHandler`](crate::handler::DenyAllHandler) — permission
/// requests are denied; other events are no-ops.
pub async fn create_session(&self, mut config: SessionConfig) -> Result<Session, Error> {
let handler = config
.handler
.take()
.unwrap_or_else(|| Arc::new(crate::handler::DenyAllHandler));
let hooks = config.hooks_handler.take();
let transforms = config.transform.take();
let command_handlers = build_command_handler_map(config.commands.as_deref());
let session_fs_provider = config.session_fs_provider.take();
if self.inner.session_fs_configured && session_fs_provider.is_none() {
return Err(Error::Session(SessionError::SessionFsProviderRequired));
}
if hooks.is_some() && config.hooks.is_none() {
config.hooks = Some(true);
}
if let Some(ref transforms) = transforms {
inject_transform_sections(&mut config, transforms.as_ref());
}
let mut params = serde_json::to_value(&config)?;
let trace_ctx = self.resolve_trace_context().await;
inject_trace_context(&mut params, &trace_ctx);
let result = self.call("session.create", Some(params)).await?;
let create_result: CreateSessionResult = serde_json::from_value(result)?;
let session_id = create_result.session_id;
let capabilities = Arc::new(parking_lot::RwLock::new(
create_result.capabilities.unwrap_or_default(),
));
let channels = self.register_session(&session_id);
let idle_waiter = Arc::new(ParkingLotMutex::new(None));
let shutdown = CancellationToken::new();
let (event_tx, _) = tokio::sync::broadcast::channel(512);
let event_loop = spawn_event_loop(
session_id.clone(),
self.clone(),
handler,
hooks,
transforms,
command_handlers,
session_fs_provider,
channels,
idle_waiter.clone(),
capabilities.clone(),
event_tx.clone(),
shutdown.clone(),
);
Ok(Session {
id: session_id,
cwd: self.cwd().clone(),
workspace_path: create_result.workspace_path,
remote_url: create_result.remote_url,
client: self.clone(),
event_loop: ParkingLotMutex::new(Some(event_loop)),
shutdown,
idle_waiter,
capabilities,
event_tx,
})
}
/// Resume an existing session on the CLI.
///
/// Sends `session.resume` and `session.skills.reload`, registers the
/// session on the router, and spawns the event loop.
///
/// All callbacks (event handler, hooks, transform) are configured
/// via [`ResumeSessionConfig`] using its `with_*` builder methods.
///
/// See [`Self::create_session`] for the defaults applied when callback
/// fields are unset.
pub async fn resume_session(&self, mut config: ResumeSessionConfig) -> Result<Session, Error> {
let handler = config
.handler
.take()
.unwrap_or_else(|| Arc::new(crate::handler::DenyAllHandler));
let hooks = config.hooks_handler.take();
let transforms = config.transform.take();
let command_handlers = build_command_handler_map(config.commands.as_deref());
let session_fs_provider = config.session_fs_provider.take();
if self.inner.session_fs_configured && session_fs_provider.is_none() {
return Err(Error::Session(SessionError::SessionFsProviderRequired));
}
if hooks.is_some() && config.hooks.is_none() {
config.hooks = Some(true);
}
if let Some(ref transforms) = transforms {
inject_transform_sections_resume(&mut config, transforms.as_ref());
}
let session_id = config.session_id.clone();
let mut params = serde_json::to_value(&config)?;
let trace_ctx = self.resolve_trace_context().await;
inject_trace_context(&mut params, &trace_ctx);
let result = self.call("session.resume", Some(params)).await?;
// The CLI may reassign the session ID on resume.
let cli_session_id: SessionId = result
.get("sessionId")
.and_then(|v| v.as_str())
.unwrap_or(&session_id)
.into();
let resume_capabilities: Option<SessionCapabilities> = result
.get("capabilities")
.and_then(|v| {
serde_json::from_value(v.clone())
.map_err(|e| warn!(error = %e, "failed to deserialize capabilities from resume response"))
.ok()
});
let remote_url = result
.get("remoteUrl")
.or_else(|| result.get("remote_url"))
.and_then(|value| value.as_str())
.map(ToString::to_string);
// Reload skills after resume (best-effort).
if let Err(e) = self
.call(
"session.skills.reload",
Some(serde_json::json!({ "sessionId": cli_session_id })),
)
.await
{
warn!(error = %e, "failed to reload skills after resume");
}
let capabilities = Arc::new(parking_lot::RwLock::new(
resume_capabilities.unwrap_or_default(),
));
let channels = self.register_session(&cli_session_id);
let idle_waiter = Arc::new(ParkingLotMutex::new(None));
let shutdown = CancellationToken::new();
let (event_tx, _) = tokio::sync::broadcast::channel(512);
let event_loop = spawn_event_loop(
cli_session_id.clone(),
self.clone(),
handler,
hooks,
transforms,
command_handlers,
session_fs_provider,
channels,
idle_waiter.clone(),
capabilities.clone(),
event_tx.clone(),
shutdown.clone(),
);
Ok(Session {
id: cli_session_id,
cwd: self.cwd().clone(),
workspace_path: None,
remote_url,
client: self.clone(),
event_loop: ParkingLotMutex::new(Some(event_loop)),
shutdown,
idle_waiter,
capabilities,
event_tx,
})
}
}
type CommandHandlerMap = HashMap<String, Arc<dyn CommandHandler>>;
fn build_command_handler_map(commands: Option<&[CommandDefinition]>) -> Arc<CommandHandlerMap> {
let map = match commands {
Some(commands) => commands
.iter()
.filter(|cmd| !cmd.name.is_empty())
.map(|cmd| (cmd.name.clone(), cmd.handler.clone()))
.collect(),
None => HashMap::new(),
};
Arc::new(map)
}
#[allow(clippy::too_many_arguments)]
fn spawn_event_loop(
session_id: SessionId,
client: Client,
handler: Arc<dyn SessionHandler>,
hooks: Option<Arc<dyn SessionHooks>>,
transforms: Option<Arc<dyn SystemMessageTransform>>,
command_handlers: Arc<CommandHandlerMap>,
session_fs_provider: Option<Arc<dyn SessionFsProvider>>,
channels: crate::router::SessionChannels,
idle_waiter: Arc<ParkingLotMutex<Option<IdleWaiter>>>,
capabilities: Arc<parking_lot::RwLock<SessionCapabilities>>,
event_tx: tokio::sync::broadcast::Sender<SessionEvent>,
shutdown: CancellationToken,
) -> JoinHandle<()> {
let crate::router::SessionChannels {
mut notifications,
mut requests,
} = channels;
let span = tracing::error_span!("session_event_loop", session_id = %session_id);
tokio::spawn(
async move {
loop {
// `mpsc::UnboundedReceiver::recv` and
// `CancellationToken::cancelled` are both cancel-safe per
// RFD 400. The selected branch's `await`'d handler is
// *not* mid-cancelled by the select — once a branch fires
// it runs to completion within the loop's iteration.
// Spawned child tasks inside `handle_notification`
// (permission/tool/elicitation callbacks) intentionally
// outlive the parent loop and own their own cleanup;
// this is RFD 400's "spawn background tasks to perform
// cancel-unsafe operations" pattern and is correct as-is.
tokio::select! {
_ = shutdown.cancelled() => break,
Some(notification) = notifications.recv() => {
handle_notification(
&session_id, &client, &handler, &command_handlers, notification, &idle_waiter, &capabilities, &event_tx,
).await;
}
Some(request) = requests.recv() => {
handle_request(
&session_id, &client, &handler, hooks.as_deref(), transforms.as_deref(), session_fs_provider.as_ref(), request,
).await;
}
else => break,
}
}
// Channels closed or shutdown signaled — fail any pending
// send_and_wait so the caller observes a clean error.
if let Some(waiter) = idle_waiter.lock().take() {
let _ = waiter
.tx
.send(Err(Error::Session(SessionError::EventLoopClosed)));
}
}
.instrument(span),
)
}
fn extract_request_id(data: &Value) -> Option<RequestId> {
data.get("requestId")
.and_then(|v| v.as_str())
.filter(|s| !s.is_empty())
.map(RequestId::new)
}
fn pending_permission_result_kind(response: &HandlerResponse) -> &'static str {
match response {
HandlerResponse::Permission(PermissionResult::Approved) => "approve-once",
HandlerResponse::Permission(PermissionResult::Denied) => "reject",
HandlerResponse::Permission(PermissionResult::NoResult) => "no-result",
// Fallback to "user-not-available" for UserNotAvailable, Deferred (when
// forced through this path), Custom (handled separately upstream), and
// any non-permission HandlerResponse that gets here defensively.
_ => "user-not-available",
}
}
fn permission_request_response(response: &HandlerResponse) -> PermissionDecision {
match response {
HandlerResponse::Permission(PermissionResult::Approved) => {
PermissionDecision::ApproveOnce(PermissionDecisionApproveOnce {
kind: PermissionDecisionApproveOnceKind::ApproveOnce,
})
}
_ => PermissionDecision::Reject(PermissionDecisionReject {
kind: PermissionDecisionRejectKind::Reject,
feedback: None,
}),
}
}
/// Map a handler response into the `result` payload for the notification
/// path (`session.permissions.handlePendingPermissionRequest`).
///
/// Returns `None` when the SDK must not respond — currently only the
/// [`PermissionResult::Deferred`] case, where the handler takes over
/// responsibility for the round-trip itself.
fn notification_permission_payload(response: &HandlerResponse) -> Option<Value> {
match response {
HandlerResponse::Permission(PermissionResult::Deferred) => None,
HandlerResponse::Permission(PermissionResult::Custom(value)) => Some(value.clone()),
_ => Some(serde_json::json!({
"kind": pending_permission_result_kind(response),
})),
}
}
/// Map a handler response into the JSON-RPC `result` payload for the
/// direct-RPC path (`permission.request`).
///
/// Always returns a value. [`PermissionResult::Deferred`] is treated as
/// [`PermissionResult::Approved`] here because the JSON-RPC contract
/// requires a reply — see the variant's doc comment.
fn direct_permission_payload(response: &HandlerResponse) -> Value {
match response {
HandlerResponse::Permission(PermissionResult::Custom(value)) => value.clone(),
HandlerResponse::Permission(PermissionResult::Deferred) => serde_json::to_value(
permission_request_response(&HandlerResponse::Permission(PermissionResult::Approved)),
)
.expect("serializing direct permission response should succeed"),
HandlerResponse::Permission(PermissionResult::NoResult)
| HandlerResponse::Permission(PermissionResult::UserNotAvailable) => serde_json::json!({
"kind": pending_permission_result_kind(response),
}),
_ => serde_json::to_value(permission_request_response(response))
.expect("serializing direct permission response should succeed"),
}
}
/// Process a notification from the CLI's broadcast channel.
#[allow(clippy::too_many_arguments)]
async fn handle_notification(
session_id: &SessionId,
client: &Client,
handler: &Arc<dyn SessionHandler>,
command_handlers: &Arc<CommandHandlerMap>,
notification: SessionEventNotification,
idle_waiter: &Arc<ParkingLotMutex<Option<IdleWaiter>>>,
capabilities: &Arc<parking_lot::RwLock<SessionCapabilities>>,
event_tx: &tokio::sync::broadcast::Sender<SessionEvent>,
) {
let event = notification.event.clone();
let event_type = event.parsed_type();
// Signal send_and_wait if active. The lock is only contended when
// a send_and_wait call is in flight (idle_waiter is Some).
match event_type {
SessionEventType::AssistantMessage
| SessionEventType::SessionIdle
| SessionEventType::SessionError => {
let mut guard = idle_waiter.lock();
if let Some(waiter) = guard.as_mut() {
match event_type {
SessionEventType::AssistantMessage => {
waiter.last_assistant_message = Some(event.clone());
}
SessionEventType::SessionIdle | SessionEventType::SessionError => {
if let Some(waiter) = guard.take() {
if event_type == SessionEventType::SessionIdle {
let _ = waiter.tx.send(Ok(waiter.last_assistant_message));
} else {
let error_msg = event
.typed_data::<SessionErrorData>()
.map(|d| d.message)
.or_else(|| {
event
.data
.get("message")
.and_then(|v| v.as_str())
.map(|s| s.to_string())
})
.unwrap_or_else(|| "session error".to_string());
let _ = waiter
.tx
.send(Err(Error::Session(SessionError::AgentError(error_msg))));
}
}
}
_ => {}
}
}
}
_ => {}
}
// Fan out the event to runtime subscribers (`Session::subscribe`). `send`
// only errors when there are no receivers, which is the normal case
// before any consumer subscribes.
let _ = event_tx.send(event.clone());
// Fire-and-forget dispatch for the general event.
handler
.on_event(HandlerEvent::SessionEvent {
session_id: session_id.clone(),
event,
})
.await;
// Update capabilities when the CLI reports changes. The CLI sends
// the full updated capabilities object — replace wholesale so removals
// and new subfields are handled correctly.
if event_type == SessionEventType::CapabilitiesChanged {
match serde_json::from_value::<SessionCapabilities>(notification.event.data.clone()) {
Ok(changed) => *capabilities.write() = changed,
Err(e) => warn!(error = %e, "failed to deserialize capabilities.changed payload"),
}
}
// Notification-based permission/tool/elicitation requests require a
// separate RPC callback. Spawn concurrently since the CLI doesn't block.
match event_type {
SessionEventType::PermissionRequested => {
let Some(request_id) = extract_request_id(¬ification.event.data) else {
return;
};
let client = client.clone();
let handler = handler.clone();
let sid = session_id.clone();
let data: PermissionRequestData =
serde_json::from_value(notification.event.data.clone()).unwrap_or_else(|_| {
PermissionRequestData {
kind: None,
tool_call_id: None,
extra: notification.event.data.clone(),
}
});
tokio::spawn(async move {
let response = handler
.on_event(HandlerEvent::PermissionRequest {
session_id: sid.clone(),
request_id: request_id.clone(),
data,
})
.await;
let Some(result_value) = notification_permission_payload(&response) else {
// Handler returned Deferred — it will call
// handlePendingPermissionRequest itself.
return;
};
let _ = client
.call(
"session.permissions.handlePendingPermissionRequest",
Some(serde_json::json!({
"sessionId": sid,
"requestId": request_id,
"result": result_value,
})),
)
.await;
});
}
SessionEventType::ExternalToolRequested => {
let Some(request_id) = extract_request_id(¬ification.event.data) else {
return;
};
let data: ExternalToolRequestedData =
match serde_json::from_value(notification.event.data.clone()) {
Ok(d) => d,
Err(e) => {
warn!(error = %e, "failed to deserialize external_tool.requested");
let client = client.clone();
let sid = session_id.clone();
tokio::spawn(async move {
let _ = client
.call(
"session.tools.handlePendingToolCall",
Some(serde_json::json!({
"sessionId": sid,
"requestId": request_id,
"error": format!("Failed to deserialize tool request: {e}"),
})),
)
.await;
});
return;
}
};
let client = client.clone();
let handler = handler.clone();
let sid = session_id.clone();
tokio::spawn(async move {
if data.tool_call_id.is_empty() || data.tool_name.is_empty() {
let error_msg = if data.tool_call_id.is_empty() {
"Missing toolCallId"
} else {
"Missing toolName"
};
let _ = client
.call(
"session.tools.handlePendingToolCall",
Some(serde_json::json!({
"sessionId": sid,
"requestId": request_id,
"error": error_msg,
})),
)
.await;
return;
}
let invocation = ToolInvocation {
session_id: sid.clone(),
tool_call_id: data.tool_call_id,
tool_name: data.tool_name,
arguments: data
.arguments
.unwrap_or(Value::Object(serde_json::Map::new())),
traceparent: data.traceparent,
tracestate: data.tracestate,
};
let response = handler
.on_event(HandlerEvent::ExternalTool { invocation })
.await;
let tool_result = match response {
HandlerResponse::ToolResult(r) => r,
_ => ToolResult::Text("Unexpected handler response".to_string()),
};
let result_value = serde_json::to_value(&tool_result).unwrap_or(Value::Null);
let _ = client
.call(
"session.tools.handlePendingToolCall",
Some(serde_json::json!({
"sessionId": sid,
"requestId": request_id,
"result": result_value,
})),
)
.await;
});
}
SessionEventType::UserInputRequested => {
// Notification-only signal for observers (UI, telemetry).
// The CLI follows up with a `userInput.request` JSON-RPC call
// that drives `HandlerEvent::UserInput` dispatch — handling
// the notification here too would double-fire the handler
// and produce duplicate prompts on the consumer side. See
// github/github-app#4249.
}
SessionEventType::ElicitationRequested => {
let Some(request_id) = extract_request_id(¬ification.event.data) else {
return;
};
let elicitation_data: ElicitationRequestedData =
match serde_json::from_value(notification.event.data.clone()) {
Ok(d) => d,
Err(e) => {
warn!(error = %e, "failed to deserialize elicitation request");
return;
}
};
let request = ElicitationRequest {
message: elicitation_data.message,
requested_schema: elicitation_data
.requested_schema
.map(|s| serde_json::to_value(s).unwrap_or(Value::Null)),
mode: elicitation_data.mode.map(|m| match m {
crate::generated::session_events::ElicitationRequestedMode::Form => {
crate::types::ElicitationMode::Form
}
crate::generated::session_events::ElicitationRequestedMode::Url => {
crate::types::ElicitationMode::Url
}
_ => crate::types::ElicitationMode::Unknown,
}),
elicitation_source: elicitation_data.elicitation_source,
url: elicitation_data.url,
};
let client = client.clone();
let handler = handler.clone();
let sid = session_id.clone();
tokio::spawn(async move {
let cancel = ElicitationResult {
action: "cancel".to_string(),
content: None,
};
// Dispatch to handler inside a nested task so panics are
// caught as JoinErrors (matches Node SDK's try/catch pattern).
let handler_task = tokio::spawn({
let sid = sid.clone();
let request_id = request_id.clone();
async move {
handler
.on_event(HandlerEvent::ElicitationRequest {
session_id: sid,
request_id,
request,
})
.await
}
});
let result = match handler_task.await {
Ok(HandlerResponse::Elicitation(r)) => r,
_ => cancel.clone(),
};
if let Err(e) = client
.call(
"session.ui.handlePendingElicitation",
Some(serde_json::json!({
"sessionId": sid,
"requestId": request_id,
"result": result,
})),
)
.await
{
// RPC failed — attempt cancel as last resort
warn!(error = %e, "handlePendingElicitation failed, sending cancel");
let _ = client
.call(
"session.ui.handlePendingElicitation",
Some(serde_json::json!({
"sessionId": sid,
"requestId": request_id,
"result": cancel,
})),
)
.await;
}
});
}
SessionEventType::CommandExecute => {
let data: CommandExecuteData =
match serde_json::from_value(notification.event.data.clone()) {
Ok(d) => d,
Err(e) => {
warn!(error = %e, "failed to deserialize command.execute");
return;
}
};
let client = client.clone();
let command_handlers = command_handlers.clone();
let sid = session_id.clone();
tokio::spawn(async move {
let request_id = data.request_id;
let ack_error = match command_handlers.get(&data.command_name).cloned() {
None => Some(format!("Unknown command: {}", data.command_name)),
Some(handler) => {
let ctx = CommandContext {
session_id: sid.clone(),
command: data.command,
command_name: data.command_name,
args: data.args,
};
match handler.on_command(ctx).await {
Ok(()) => None,
Err(e) => Some(e.to_string()),
}
}
};
let mut params = serde_json::json!({
"sessionId": sid,
"requestId": request_id,
});
if let Some(error_msg) = ack_error {
params["error"] = serde_json::Value::String(error_msg);
}
let _ = client
.call("session.commands.handlePendingCommand", Some(params))
.await;
});
}
_ => {}
}
}
/// Process a JSON-RPC request from the CLI.
async fn handle_request(
session_id: &SessionId,
client: &Client,
handler: &Arc<dyn SessionHandler>,
hooks: Option<&dyn SessionHooks>,
transforms: Option<&dyn SystemMessageTransform>,
session_fs_provider: Option<&Arc<dyn SessionFsProvider>>,
request: crate::JsonRpcRequest,
) {
let sid = session_id.clone();
if request.method.starts_with("sessionFs.") {
crate::session_fs_dispatch::dispatch(client, session_fs_provider, request).await;
return;
}
match request.method.as_str() {
"hooks.invoke" => {
let params = request.params.as_ref();
let hook_type = params
.and_then(|p| p.get("hookType"))
.and_then(|v| v.as_str())
.unwrap_or("");
let input = params
.and_then(|p| p.get("input"))
.cloned()
.unwrap_or(Value::Object(Default::default()));
let rpc_result = if let Some(hooks) = hooks {
match crate::hooks::dispatch_hook(hooks, &sid, hook_type, input).await {
Ok(output) => output,
Err(e) => {
warn!(error = %e, hook_type = hook_type, "hook dispatch failed");
serde_json::json!({ "output": {} })
}
}
} else {
serde_json::json!({ "output": {} })
};
let rpc_response = JsonRpcResponse {
jsonrpc: "2.0".to_string(),
id: request.id,
result: Some(rpc_result),
error: None,
};
let _ = client.send_response(&rpc_response).await;
}
"tool.call" => {
let invocation: ToolInvocation = match request
.params
.as_ref()
.and_then(|p| serde_json::from_value::<ToolInvocation>(p.clone()).ok())
{
Some(inv) => inv,
None => {
let _ = send_error_response(
client,
request.id,
error_codes::INVALID_PARAMS,
"invalid tool.call params",
)
.await;
return;
}
};
let response = handler
.on_event(HandlerEvent::ExternalTool { invocation })
.await;
let tool_result = match response {
HandlerResponse::ToolResult(r) => r,
_ => ToolResult::Text("Unexpected handler response".to_string()),
};
let rpc_response = JsonRpcResponse {
jsonrpc: "2.0".to_string(),
id: request.id,
result: Some(serde_json::json!(ToolResultResponse {
result: tool_result
})),
error: None,
};
let _ = client.send_response(&rpc_response).await;
}
"userInput.request" => {
let params = request.params.as_ref();
let Some(question) = params
.and_then(|p| p.get("question"))
.and_then(|v| v.as_str())
else {
warn!("userInput.request missing 'question' field");
let rpc_response = JsonRpcResponse {
jsonrpc: "2.0".to_string(),
id: request.id,
result: None,
error: Some(crate::JsonRpcError {
code: error_codes::INVALID_PARAMS,
message: "missing required field: question".to_string(),
data: None,
}),
};
let _ = client.send_response(&rpc_response).await;
return;
};
let question = question.to_string();
let choices = params
.and_then(|p| p.get("choices"))
.and_then(|v| v.as_array())
.map(|arr| {
arr.iter()
.filter_map(|v| v.as_str().map(|s| s.to_string()))
.collect()
});
let allow_freeform = params
.and_then(|p| p.get("allowFreeform"))
.and_then(|v| v.as_bool());
let response = handler
.on_event(HandlerEvent::UserInput {
session_id: sid,
question,
choices,
allow_freeform,
})
.await;
let rpc_result = match response {
HandlerResponse::UserInput(Some(UserInputResponse {
answer,
was_freeform,
})) => serde_json::json!({
"answer": answer,
"wasFreeform": was_freeform,
}),
_ => serde_json::json!({ "noResponse": true }),
};
let rpc_response = JsonRpcResponse {
jsonrpc: "2.0".to_string(),
id: request.id,
result: Some(rpc_result),
error: None,
};
let _ = client.send_response(&rpc_response).await;
}
"exitPlanMode.request" => {
let params = request
.params
.as_ref()
.cloned()
.unwrap_or(Value::Object(serde_json::Map::new()));
let data: ExitPlanModeData = match serde_json::from_value(params) {
Ok(d) => d,
Err(e) => {
warn!(error = %e, "failed to deserialize exitPlanMode.request params, using defaults");
ExitPlanModeData::default()
}
};
let response = handler
.on_event(HandlerEvent::ExitPlanMode {
session_id: sid,
data,
})
.await;
let rpc_result = match response {
HandlerResponse::ExitPlanMode(ExitPlanModeResult {
approved,
selected_action,
feedback,
}) => serde_json::json!({
"approved": approved,
"selectedAction": selected_action,
"feedback": feedback,
}),
_ => serde_json::json!({ "approved": true }),
};
let rpc_response = JsonRpcResponse {
jsonrpc: "2.0".to_string(),
id: request.id,
result: Some(rpc_result),
error: None,
};
let _ = client.send_response(&rpc_response).await;
}
"autoModeSwitch.request" => {
let error_code = request
.params
.as_ref()
.and_then(|p| p.get("errorCode"))
.and_then(|v| v.as_str())
.map(|s| s.to_string());
let retry_after_seconds = request
.params
.as_ref()
.and_then(|p| p.get("retryAfterSeconds"))
.and_then(|v| v.as_u64());
let response = handler
.on_event(HandlerEvent::AutoModeSwitch {
session_id: sid,
error_code,
retry_after_seconds,
})
.await;
let answer = match response {
HandlerResponse::AutoModeSwitch(answer) => answer,
_ => AutoModeSwitchResponse::No,
};
let rpc_response = JsonRpcResponse {
jsonrpc: "2.0".to_string(),
id: request.id,
result: Some(serde_json::json!({ "response": answer })),
error: None,
};
let _ = client.send_response(&rpc_response).await;
}
"permission.request" => {
let Some(request_id) = request
.params
.as_ref()
.and_then(|p| p.get("requestId"))
.and_then(|v| v.as_str())
.filter(|s| !s.is_empty())
else {
warn!("permission.request missing 'requestId' field");
let rpc_response = JsonRpcResponse {
jsonrpc: "2.0".to_string(),
id: request.id,
result: None,
error: Some(crate::JsonRpcError {
code: error_codes::INVALID_PARAMS,
message: "missing required field: requestId".to_string(),
data: None,
}),
};
let _ = client.send_response(&rpc_response).await;
return;
};
let request_id = RequestId::new(request_id);
let raw_params = request
.params
.as_ref()
.cloned()
.unwrap_or(Value::Object(serde_json::Map::new()));
let data: PermissionRequestData =
serde_json::from_value(raw_params.clone()).unwrap_or(PermissionRequestData {
kind: None,
tool_call_id: None,
extra: raw_params,
});
let response = handler
.on_event(HandlerEvent::PermissionRequest {
session_id: sid,
request_id,
data,
})
.await;
let rpc_response = JsonRpcResponse {
jsonrpc: "2.0".to_string(),
id: request.id,
result: Some(direct_permission_payload(&response)),
error: None,
};
let _ = client.send_response(&rpc_response).await;
}
"systemMessage.transform" => {
let params = request.params.as_ref();
let sections: HashMap<String, crate::transforms::TransformSection> =
match params.and_then(|p| p.get("sections")) {
Some(v) => match serde_json::from_value(v.clone()) {
Ok(s) => s,
Err(e) => {
let _ = send_error_response(
client,
request.id,
error_codes::INVALID_PARAMS,
&format!("invalid sections: {e}"),
)
.await;
return;
}
},
None => {
let _ = send_error_response(
client,
request.id,
error_codes::INVALID_PARAMS,
"missing sections parameter",
)
.await;
return;
}
};
let rpc_result = if let Some(transforms) = transforms {
let response =
crate::transforms::dispatch_transform(transforms, &sid, sections).await;
match serde_json::to_value(response) {
Ok(v) => v,
Err(e) => {
warn!(error = %e, "failed to serialize transform response");
serde_json::json!({ "sections": {} })
}
}
} else {
// No transforms registered — pass through all sections unchanged.
let passthrough: HashMap<String, crate::transforms::TransformSection> = sections;
serde_json::json!({ "sections": passthrough })
};
let rpc_response = JsonRpcResponse {
jsonrpc: "2.0".to_string(),
id: request.id,
result: Some(rpc_result),
error: None,
};
let _ = client.send_response(&rpc_response).await;
}
method => {
warn!(
method = method,
"unhandled request method in session event loop"
);
let _ = send_error_response(
client,
request.id,
error_codes::METHOD_NOT_FOUND,
&format!("unknown method: {method}"),
)
.await;
}
}
}
async fn send_error_response(
client: &Client,
id: u64,
code: i32,
message: &str,
) -> Result<(), Error> {
let response = JsonRpcResponse {
jsonrpc: "2.0".to_string(),
id,
result: None,
error: Some(crate::JsonRpcError {
code,
message: message.to_string(),
data: None,
}),
};
client.send_response(&response).await
}
/// Inject `action: "transform"` sections into a `SystemMessageConfig`,
/// forcing `mode: "customize"` (required by the CLI for transforms to fire).
/// Preserves any existing caller-provided section overrides.
fn apply_transform_sections(
sys_msg: &mut SystemMessageConfig,
transforms: &dyn SystemMessageTransform,
) {
sys_msg.mode = Some("customize".to_string());
let sections = sys_msg.sections.get_or_insert_with(HashMap::new);
for id in transforms.section_ids() {
sections.entry(id).or_insert_with(|| SectionOverride {
action: Some("transform".to_string()),
content: None,
});
}
}
fn inject_transform_sections(config: &mut SessionConfig, transforms: &dyn SystemMessageTransform) {
let sys_msg = config.system_message.get_or_insert_with(Default::default);
apply_transform_sections(sys_msg, transforms);
}
fn inject_transform_sections_resume(
config: &mut ResumeSessionConfig,
transforms: &dyn SystemMessageTransform,
) {
let sys_msg = config.system_message.get_or_insert_with(Default::default);
apply_transform_sections(sys_msg, transforms);
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::{
direct_permission_payload, notification_permission_payload, pending_permission_result_kind,
permission_request_response,
};
use crate::handler::{HandlerResponse, PermissionResult};
#[test]
fn pending_permission_requests_use_decision_kinds() {
assert_eq!(
pending_permission_result_kind(&HandlerResponse::Permission(
PermissionResult::Approved,
)),
"approve-once"
);
assert_eq!(
pending_permission_result_kind(&HandlerResponse::Permission(PermissionResult::Denied)),
"reject"
);
assert_eq!(
pending_permission_result_kind(&HandlerResponse::Ok),
"user-not-available"
);
}
#[test]
fn direct_permission_requests_use_decision_response_kinds() {
assert_eq!(
serde_json::to_value(permission_request_response(&HandlerResponse::Permission(
PermissionResult::Approved
),))
.expect("serializing approved permission response should succeed"),
json!({ "kind": "approve-once" })
);
assert_eq!(
serde_json::to_value(permission_request_response(&HandlerResponse::Permission(
PermissionResult::Denied
),))
.expect("serializing denied permission response should succeed"),
json!({ "kind": "reject" })
);
assert_eq!(
serde_json::to_value(permission_request_response(&HandlerResponse::Ok))
.expect("serializing fallback permission response should succeed"),
json!({ "kind": "reject" })
);
}
#[test]
fn notification_payload_handles_deferred_and_custom() {
// Deferred → no payload, SDK must not respond.
assert!(
notification_permission_payload(&HandlerResponse::Permission(
PermissionResult::Deferred,
))
.is_none()
);
// Custom → handler-supplied value passed through verbatim.
let custom = json!({
"kind": "approve-and-remember",
"allowlist": ["ls", "grep"],
});
assert_eq!(
notification_permission_payload(&HandlerResponse::Permission(
PermissionResult::Custom(custom.clone()),
)),
Some(custom)
);
// Approved/Denied → existing kind-only shape.
assert_eq!(
notification_permission_payload(&HandlerResponse::Permission(
PermissionResult::Approved,
)),
Some(json!({ "kind": "approve-once" }))
);
assert_eq!(
notification_permission_payload(
&HandlerResponse::Permission(PermissionResult::Denied,)
),
Some(json!({ "kind": "reject" }))
);
}
#[test]
fn direct_payload_handles_deferred_and_custom() {
// Custom → handler-supplied value passed through verbatim.
let custom = json!({
"kind": "approve-and-remember",
"allowlist": ["ls", "grep"],
});
assert_eq!(
direct_permission_payload(&HandlerResponse::Permission(PermissionResult::Custom(
custom.clone(),
))),
custom
);
// Deferred → falls back to Approved because the direct RPC must reply.
assert_eq!(
direct_permission_payload(&HandlerResponse::Permission(PermissionResult::Deferred)),
json!({ "kind": "approve-once" })
);
// Approved/Denied → existing kind-only shape.
assert_eq!(
direct_permission_payload(&HandlerResponse::Permission(PermissionResult::Approved)),
json!({ "kind": "approve-once" })
);
assert_eq!(
direct_permission_payload(&HandlerResponse::Permission(PermissionResult::Denied)),
json!({ "kind": "reject" })
);
}
}