github-copilot-sdk 1.0.0-beta.4

Rust SDK for programmatic control of the GitHub Copilot CLI via JSON-RPC. Technical preview, pre-1.0.
Documentation
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
//! Event handler traits for session lifecycle.
//!
//! The [`SessionHandler`](crate::handler::SessionHandler) trait is the primary extension point — implement
//! [`on_event`](crate::handler::SessionHandler::on_event) to control how sessions respond to
//! CLI events, permission requests, tool calls, and user input prompts.

use async_trait::async_trait;
use serde::{Deserialize, Serialize};

use crate::types::{
    ElicitationRequest, ElicitationResult, ExitPlanModeData, PermissionRequestData, RequestId,
    SessionEvent, SessionId, ToolInvocation, ToolResult,
};

/// Events dispatched by the SDK session event loop to the handler.
///
/// The handler returns a [`HandlerResponse`] indicating how the SDK should
/// respond to the CLI. For fire-and-forget events (`SessionEvent`), the
/// response is ignored.
#[non_exhaustive]
#[derive(Debug)]
pub enum HandlerEvent {
    /// Informational session event from the timeline (e.g. assistant.message_delta,
    /// session.idle, tool.execution_start). Fire-and-forget — return `HandlerResponse::Ok`.
    SessionEvent {
        /// The session that emitted this event.
        session_id: SessionId,
        /// The event payload.
        event: SessionEvent,
    },

    /// The CLI requests permission for an action. Return `HandlerResponse::Permission(..)`.
    PermissionRequest {
        /// The requesting session.
        session_id: SessionId,
        /// Unique ID to correlate the response.
        request_id: RequestId,
        /// Permission request payload.
        data: PermissionRequestData,
    },

    /// The CLI requests user input. Return `HandlerResponse::UserInput(..)`.
    /// The handler may block (e.g. awaiting a UI dialog) — this is expected.
    UserInput {
        /// The requesting session.
        session_id: SessionId,
        /// The question text to present.
        question: String,
        /// Optional multiple-choice options.
        choices: Option<Vec<String>>,
        /// Whether free-form text input is allowed.
        allow_freeform: Option<bool>,
    },

    /// The CLI requests execution of a client-defined tool.
    /// Return `HandlerResponse::ToolResult(..)`.
    ExternalTool {
        /// The tool call to execute.
        invocation: ToolInvocation,
    },

    /// The CLI broadcasts an elicitation request for the provider to handle.
    /// Return `HandlerResponse::Elicitation(..)`.
    ElicitationRequest {
        /// The requesting session.
        session_id: SessionId,
        /// Unique ID to correlate the response.
        request_id: RequestId,
        /// The elicitation request payload.
        request: ElicitationRequest,
    },

    /// The CLI requests exiting plan mode. Return `HandlerResponse::ExitPlanMode(..)`.
    ExitPlanMode {
        /// The requesting session.
        session_id: SessionId,
        /// Plan mode exit payload.
        data: ExitPlanModeData,
    },

    /// The CLI asks whether to switch to auto model when an eligible rate
    /// limit is hit. Return [`HandlerResponse::AutoModeSwitch`].
    AutoModeSwitch {
        /// The requesting session.
        session_id: SessionId,
        /// The specific rate-limit error code that triggered the request,
        /// if known (e.g. `user_weekly_rate_limited`, `user_global_rate_limited`).
        error_code: Option<String>,
        /// Seconds until the rate limit resets, when known.
        retry_after_seconds: Option<f64>,
    },
}

/// Response from the handler back to the SDK, used to construct the
/// JSON-RPC reply sent to the CLI.
#[non_exhaustive]
#[derive(Debug)]
pub enum HandlerResponse {
    /// No response needed (used for fire-and-forget `SessionEvent`s).
    Ok,
    /// Permission decision.
    Permission(PermissionResult),
    /// User input response (or `None` to signal no input available).
    UserInput(Option<UserInputResponse>),
    /// Result of a tool execution.
    ToolResult(ToolResult),
    /// Elicitation result (accept/decline/cancel with optional form data).
    Elicitation(ElicitationResult),
    /// Exit plan mode decision.
    ExitPlanMode(ExitPlanModeResult),
    /// Auto-mode-switch decision.
    AutoModeSwitch(AutoModeSwitchResponse),
}

/// Result of a permission request.
///
/// `#[non_exhaustive]` so future variants can be added without a major
/// version bump. Match arms must include a `_` fallback.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum PermissionResult {
    /// Permission granted.
    Approved,
    /// Permission denied.
    Denied,
    /// Defer the response. The handler will resolve this request itself
    /// later — typically after a UI prompt — by calling
    /// `session.permissions.handlePendingPermissionRequest` directly. The
    /// SDK will not send a response for this request.
    ///
    /// **Notification path only** (`permission.requested`). On the direct
    /// RPC path (`permission.request`), `Deferred` falls back to
    /// [`Approved`](Self::Approved) because that path must return a value
    /// to satisfy the JSON-RPC reply contract.
    Deferred,
    /// Provide the full response payload. The SDK passes the value as-is
    /// in the `result` field of `handlePendingPermissionRequest`
    /// (notification path) or as the JSON-RPC `result` directly (direct
    /// RPC path).
    ///
    /// Use this for response shapes beyond `{ "kind": "approve-once" }`
    /// or `{ "kind": "reject" }` — for example, "approve and remember"
    /// with allowlist data.
    Custom(serde_json::Value),
    /// No user is available to respond — for example, headless agents
    /// without an interactive session. Sent as
    /// `{ "kind": "user-not-available" }`.
    UserNotAvailable,
    /// The handler has no result to provide and the CLI should fall back
    /// to its default policy. Sent as `{ "kind": "no-result" }`. Distinct
    /// from [`Deferred`](Self::Deferred), which suppresses the reply
    /// entirely so the handler can resolve later out-of-band.
    NoResult,
}

/// Response to a user input request.
#[derive(Debug, Clone)]
pub struct UserInputResponse {
    /// The user's answer text.
    pub answer: String,
    /// Whether the answer was free-form (not a preset choice).
    pub was_freeform: bool,
}

/// Result of an exit-plan-mode request.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ExitPlanModeResult {
    /// Whether the user approved exiting plan mode.
    pub approved: bool,
    /// The action the user selected (if any).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub selected_action: Option<String>,
    /// Optional feedback text from the user.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub feedback: Option<String>,
}

impl Default for ExitPlanModeResult {
    fn default() -> Self {
        Self {
            approved: true,
            selected_action: None,
            feedback: None,
        }
    }
}

/// Response to a [`HandlerEvent::AutoModeSwitch`] request.
///
/// Wire serialization matches the CLI's `autoModeSwitch.request` response
/// schema: `"yes"`, `"yes_always"`, or `"no"`.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AutoModeSwitchResponse {
    /// Approve the auto-mode switch for this rate-limit cycle only.
    Yes,
    /// Approve and remember — auto-accept future auto-mode switches in this
    /// session without prompting.
    YesAlways,
    /// Decline the auto-mode switch. The session stays on the current model
    /// and surfaces the rate-limit error.
    No,
}

/// Callback trait for session events.
///
/// Implement this trait to control how a session responds to CLI events,
/// permission requests, tool calls, user input prompts, elicitations, and
/// plan-mode exits. There are two styles of implementation — pick whichever
/// fits your use case:
///
/// 1. **Per-event methods (recommended for most handlers).** Override the
///    specific `on_*` methods you care about; every method has a safe
///    default so you only write what you need. This is the pattern used by
///    [`serenity::EventHandler`][serenity], `lapin`, and most Rust SDKs
///    that dispatch broker/client callbacks.
/// 2. **Single [`on_event`](Self::on_event) method.** Override this one
///    method and `match` on [`HandlerEvent`] yourself. Useful for logging
///    middleware, custom routing, or when you want an exhaustiveness check
///    across all variants.
///
/// When you override [`on_event`](Self::on_event) directly, the per-event methods are not
/// called — your implementation is entirely responsible for dispatch. The
/// default [`on_event`](Self::on_event) fans out to the per-event methods.
///
/// [serenity]: https://docs.rs/serenity/latest/serenity/client/trait.EventHandler.html
///
/// # Default behavior
///
/// - Permission requests → **denied** (safe default).
/// - User input → `None` (no answer available).
/// - External tool calls → failure result with "no handler registered".
/// - Elicitation → `"cancel"`.
/// - Exit plan mode → [`ExitPlanModeResult::default`].
/// - Auto-mode-switch → [`AutoModeSwitchResponse::No`] (decline by default; the
///   session stays on its current model and surfaces the rate-limit error).
/// - Session events → ignored (fire-and-forget).
///
/// # Concurrency
///
/// **Request-triggered events** (`UserInput`, `ExternalTool` via `tool.call`,
/// `ExitPlanMode`, `PermissionRequest` via `permission.request`) are awaited
/// inline in the event loop and therefore processed **serially** per session.
/// Blocking here pauses that session's event loop — which is correct, since
/// the CLI is also blocked waiting for the response.
///
/// **Notification-triggered events** (`PermissionRequest` via
/// `permission.requested`, `ExternalTool` via `external_tool.requested`) are
/// dispatched on spawned tasks and may run **concurrently** with each other
/// and with the serial event loop. Implementations must be safe for
/// concurrent invocation.
///
/// # Example
///
/// ```no_run
/// use async_trait::async_trait;
/// use github_copilot_sdk::handler::{PermissionResult, SessionHandler};
/// use github_copilot_sdk::types::{PermissionRequestData, RequestId, SessionId};
///
/// struct ApproveReadsOnly;
///
/// #[async_trait]
/// impl SessionHandler for ApproveReadsOnly {
///     async fn on_permission_request(
///         &self,
///         _sid: SessionId,
///         _rid: RequestId,
///         data: PermissionRequestData,
///     ) -> PermissionResult {
///         match data.extra.get("tool").and_then(|v| v.as_str()) {
///             Some("view") | Some("ls") | Some("grep") => PermissionResult::Approved,
///             _ => PermissionResult::Denied,
///         }
///     }
/// }
/// ```
#[async_trait]
pub trait SessionHandler: Send + Sync + 'static {
    /// Handle an event from the session.
    ///
    /// The default implementation destructures `event` and calls the
    /// matching per-event method (e.g. [`on_permission_request`](Self::on_permission_request)
    /// for [`HandlerEvent::PermissionRequest`]). Override this method only
    /// if you want a single dispatch point with exhaustive matching — most
    /// handlers should override the per-event methods instead.
    ///
    /// See the [trait-level docs](SessionHandler#concurrency) for details on
    /// which events may be dispatched concurrently.
    async fn on_event(&self, event: HandlerEvent) -> HandlerResponse {
        match event {
            HandlerEvent::SessionEvent { session_id, event } => {
                self.on_session_event(session_id, event).await;
                HandlerResponse::Ok
            }
            HandlerEvent::PermissionRequest {
                session_id,
                request_id,
                data,
            } => HandlerResponse::Permission(
                self.on_permission_request(session_id, request_id, data)
                    .await,
            ),
            HandlerEvent::UserInput {
                session_id,
                question,
                choices,
                allow_freeform,
            } => HandlerResponse::UserInput(
                self.on_user_input(session_id, question, choices, allow_freeform)
                    .await,
            ),
            HandlerEvent::ExternalTool { invocation } => {
                HandlerResponse::ToolResult(self.on_external_tool(invocation).await)
            }
            HandlerEvent::ElicitationRequest {
                session_id,
                request_id,
                request,
            } => HandlerResponse::Elicitation(
                self.on_elicitation(session_id, request_id, request).await,
            ),
            HandlerEvent::ExitPlanMode { session_id, data } => {
                HandlerResponse::ExitPlanMode(self.on_exit_plan_mode(session_id, data).await)
            }
            HandlerEvent::AutoModeSwitch {
                session_id,
                error_code,
                retry_after_seconds,
            } => HandlerResponse::AutoModeSwitch(
                self.on_auto_mode_switch(session_id, error_code, retry_after_seconds)
                    .await,
            ),
        }
    }

    /// Informational timeline event (assistant messages, tool execution
    /// markers, session idle, etc.). Fire-and-forget — the return value is
    /// ignored.
    ///
    /// Default: do nothing.
    async fn on_session_event(&self, _session_id: SessionId, _event: SessionEvent) {}

    /// The CLI is asking whether the agent may perform a privileged action.
    ///
    /// Default: [`PermissionResult::Denied`]. The default-deny posture
    /// matches the CLI's safety model; override to implement your own
    /// policy (see the [`permission`](crate::permission) module for common
    /// wrappers like `approve_all` / `approve_if`).
    async fn on_permission_request(
        &self,
        _session_id: SessionId,
        _request_id: RequestId,
        _data: PermissionRequestData,
    ) -> PermissionResult {
        PermissionResult::Denied
    }

    /// The CLI is asking the user a question (optionally with a list of
    /// choices).
    ///
    /// Default: `None` — the CLI interprets this as "no answer available"
    /// and falls back to its own prompt behavior.
    async fn on_user_input(
        &self,
        _session_id: SessionId,
        _question: String,
        _choices: Option<Vec<String>>,
        _allow_freeform: Option<bool>,
    ) -> Option<UserInputResponse> {
        None
    }

    /// The CLI wants to invoke a client-defined ("external") tool.
    ///
    /// Default: a failure [`ToolResult`] indicating no tool handler is
    /// registered. Typical implementations route to a
    /// [`ToolHandlerRouter`](crate::tool::ToolHandlerRouter) which
    /// dispatches to tools registered via
    /// [`define_tool`](crate::tool::define_tool) or custom
    /// [`ToolHandler`](crate::tool::ToolHandler) impls.
    async fn on_external_tool(&self, invocation: ToolInvocation) -> ToolResult {
        let msg = format!("No handler registered for tool '{}'", invocation.tool_name);
        ToolResult::Expanded(crate::types::ToolResultExpanded {
            text_result_for_llm: msg.clone(),
            result_type: "failure".to_string(),
            binary_results_for_llm: None,
            session_log: None,
            error: Some(msg),
            tool_telemetry: None,
        })
    }

    /// The CLI is requesting an elicitation (structured form / URL prompt).
    ///
    /// Default: cancel.
    async fn on_elicitation(
        &self,
        _session_id: SessionId,
        _request_id: RequestId,
        _request: ElicitationRequest,
    ) -> ElicitationResult {
        ElicitationResult {
            action: "cancel".to_string(),
            content: None,
        }
    }

    /// The CLI is asking the user whether to exit plan mode.
    ///
    /// Default: [`ExitPlanModeResult::default`] (approved with no action).
    async fn on_exit_plan_mode(
        &self,
        _session_id: SessionId,
        _data: ExitPlanModeData,
    ) -> ExitPlanModeResult {
        ExitPlanModeResult::default()
    }

    /// The CLI is asking whether to switch to auto model after an eligible
    /// rate limit.
    ///
    /// `retry_after_seconds`, when present, is the number of seconds until the
    /// rate limit resets. Handlers can use it to render a humanized reset time
    /// alongside the prompt.
    ///
    /// Default: [`AutoModeSwitchResponse::No`] — decline. Override only if
    /// your application surfaces a UX for the rate-limit-recovery prompt.
    async fn on_auto_mode_switch(
        &self,
        _session_id: SessionId,
        _error_code: Option<String>,
        _retry_after_seconds: Option<f64>,
    ) -> AutoModeSwitchResponse {
        AutoModeSwitchResponse::No
    }
}

/// A [`SessionHandler`] that auto-approves all permissions and ignores all events.
///
/// Useful for CLI tools, scripts, and tests that don't need interactive
/// permission prompts or custom tool handling.
#[derive(Debug, Clone)]
pub struct ApproveAllHandler;

#[async_trait]
impl SessionHandler for ApproveAllHandler {
    async fn on_permission_request(
        &self,
        _session_id: SessionId,
        _request_id: RequestId,
        _data: PermissionRequestData,
    ) -> PermissionResult {
        PermissionResult::Approved
    }
}

/// A [`SessionHandler`] that denies all permission requests and otherwise
/// relies on the trait's default fallback responses for every other event
/// (e.g. tool invocations return "unhandled", elicitations cancel, plan-mode
/// prompts decline). This is the safe default used when no handler is set on
/// [`SessionConfig::handler`](crate::types::SessionConfig::handler) — sessions
/// will not stall on permission prompts (they're denied immediately) but no
/// privileged actions will be taken without an explicit opt-in.
#[derive(Debug, Clone)]
pub struct DenyAllHandler;

#[async_trait]
impl SessionHandler for DenyAllHandler {
    // All defaults are already safe: permissions deny, everything else is a
    // sensible fallback. We just reuse them here for clarity.
}

#[cfg(test)]
mod tests {
    use serde_json::Value;

    use super::*;
    use crate::types::{PermissionRequestData, RequestId, SessionId};

    fn perm_data() -> PermissionRequestData {
        PermissionRequestData::default()
    }

    // A handler that overrides only `on_permission_request` (per-method style).
    struct ApproveViaPerMethod;

    #[async_trait]
    impl SessionHandler for ApproveViaPerMethod {
        async fn on_permission_request(
            &self,
            _: SessionId,
            _: RequestId,
            _: PermissionRequestData,
        ) -> PermissionResult {
            PermissionResult::Approved
        }
    }

    // A handler that overrides `on_event` directly (legacy / routing style).
    struct ApproveViaOnEvent;

    #[async_trait]
    impl SessionHandler for ApproveViaOnEvent {
        async fn on_event(&self, event: HandlerEvent) -> HandlerResponse {
            match event {
                HandlerEvent::PermissionRequest { .. } => {
                    HandlerResponse::Permission(PermissionResult::Approved)
                }
                _ => HandlerResponse::Ok,
            }
        }
    }

    #[tokio::test]
    async fn per_method_override_dispatches_via_default_on_event() {
        let h = ApproveViaPerMethod;
        let resp = h
            .on_event(HandlerEvent::PermissionRequest {
                session_id: SessionId::from("s1".to_string()),
                request_id: RequestId::new("r1"),
                data: perm_data(),
            })
            .await;
        assert!(matches!(
            resp,
            HandlerResponse::Permission(PermissionResult::Approved)
        ));
    }

    #[tokio::test]
    async fn on_event_override_short_circuits_per_method_defaults() {
        let h = ApproveViaOnEvent;
        let resp = h
            .on_event(HandlerEvent::PermissionRequest {
                session_id: SessionId::from("s1".to_string()),
                request_id: RequestId::new("r1"),
                data: perm_data(),
            })
            .await;
        assert!(matches!(
            resp,
            HandlerResponse::Permission(PermissionResult::Approved)
        ));
    }

    #[tokio::test]
    async fn deny_all_handler_uses_default_permission_deny() {
        let h = DenyAllHandler;
        let resp = h
            .on_event(HandlerEvent::PermissionRequest {
                session_id: SessionId::from("s1".to_string()),
                request_id: RequestId::new("r1"),
                data: perm_data(),
            })
            .await;
        assert!(matches!(
            resp,
            HandlerResponse::Permission(PermissionResult::Denied)
        ));
    }

    #[tokio::test]
    async fn default_on_external_tool_returns_failure() {
        let h = DenyAllHandler;
        let resp = h
            .on_event(HandlerEvent::ExternalTool {
                invocation: crate::types::ToolInvocation {
                    session_id: SessionId::from("s1".to_string()),
                    tool_call_id: "tc1".to_string(),
                    tool_name: "missing".to_string(),
                    arguments: Value::Null,
                    traceparent: None,
                    tracestate: None,
                },
            })
            .await;
        match resp {
            HandlerResponse::ToolResult(crate::types::ToolResult::Expanded(exp)) => {
                assert_eq!(exp.result_type, "failure");
                assert!(exp.text_result_for_llm.contains("missing"));
                assert_eq!(exp.error.as_deref(), Some(exp.text_result_for_llm.as_str()));
            }
            other => panic!("unexpected response: {other:?}"),
        }
    }

    #[tokio::test]
    async fn default_on_elicitation_returns_cancel() {
        let h = DenyAllHandler;
        let resp = h
            .on_event(HandlerEvent::ElicitationRequest {
                session_id: SessionId::from("s1".to_string()),
                request_id: RequestId::new("r1"),
                request: crate::types::ElicitationRequest {
                    message: "test".to_string(),
                    requested_schema: None,
                    mode: Some(crate::types::ElicitationMode::Form),
                    elicitation_source: None,
                    url: None,
                },
            })
            .await;
        match resp {
            HandlerResponse::Elicitation(r) => assert_eq!(r.action, "cancel"),
            other => panic!("unexpected response: {other:?}"),
        }
    }
}