github-copilot-sdk 1.0.14

Rust SDK for programmatic control of the GitHub Copilot CLI via JSON-RPC.
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
use std::sync::Arc;
use std::time::Duration;

use github_copilot_sdk::handler::ApproveAllHandler;
use github_copilot_sdk::rpc::{EventLogReadRequest, ModelSwitchAutoTierStatus};
use github_copilot_sdk::session::Session;
use github_copilot_sdk::session_events::{
    AutoTier, AutoTierSwitchFailureReason, SessionAutoTierSwitchFailedData, SessionEventType,
    SessionModelChangeData,
};
use github_copilot_sdk::{
    CapiSessionOptions, MessageOptions, ResumeSessionConfig, SessionConfig, SessionId,
    SetModelOptions,
};
use serde_json::json;

use super::support::{DEFAULT_TEST_TOKEN, wait_for_event, with_dedicated_e2e_context};

const MODEL_ID: &str = "auto";

/// End-to-end coverage for staging and resetting an Auto routing preference
/// (snapshot category "auto_tier").
///
/// The runtime stages an Auto routing preference instead of applying it immediately: a
/// request stays unclaimed until a later turn using the `auto` model mints a usable model
/// and token pair. These tests observe that staged state through `model().get_current()`,
/// so they assert what the runtime actually recorded rather than what the SDK serialized.
async fn pending_auto_tier(session: &Session) -> Option<AutoTier> {
    session
        .rpc()
        .model()
        .get_current()
        .await
        .expect("get current model")
        .pending_auto_tier
}

fn auto_session_config(tier: Option<AutoTier>) -> SessionConfig {
    let capi = CapiSessionOptions::new().with_enable_web_socket_responses(false);
    let capi = match tier {
        Some(tier) => capi.with_auto_tier(tier),
        None => capi,
    };
    SessionConfig::default()
        .with_model(MODEL_ID)
        .with_capi(capi)
        .with_permission_handler(Arc::new(ApproveAllHandler))
        .with_github_token(DEFAULT_TEST_TOKEN)
}

fn auto_resume_config(session_id: SessionId) -> ResumeSessionConfig {
    ResumeSessionConfig::new(session_id)
        .with_permission_handler(Arc::new(ApproveAllHandler))
        .with_github_token(DEFAULT_TEST_TOKEN)
}

async fn send_prompt(session: &Session, prompt: &str) {
    session
        .send_and_wait(MessageOptions::new(prompt).with_wait_timeout(Duration::from_secs(120)))
        .await
        .expect("send prompt");
}

#[tokio::test]
async fn should_stage_and_reset_auto_tier_preference() {
    with_dedicated_e2e_context(
        "auto_tier",
        "should_stage_and_reset_auto_tier_preference",
        |ctx| {
            Box::pin(async move {
                ctx.set_default_copilot_user();
                let client = ctx.start_client().await;
                let session = client
                    .create_session(ctx.approve_all_session_config().with_model(MODEL_ID))
                    .await
                    .expect("create session");

                assert_eq!(pending_auto_tier(&session).await, None);

                let staged = session
                    .set_auto_tier(Some(AutoTier::Efficiency))
                    .await
                    .expect("stage efficiency");
                assert_eq!(staged.status, ModelSwitchAutoTierStatus::Pending);
                assert_eq!(staged.pending_auto_tier, Some(AutoTier::Efficiency));
                assert_eq!(
                    pending_auto_tier(&session).await,
                    Some(AutoTier::Efficiency)
                );

                // A second request replaces the first and reports the one it displaced.
                let superseded = session
                    .set_auto_tier(Some(AutoTier::Fast))
                    .await
                    .expect("stage fast");
                assert_eq!(superseded.status, ModelSwitchAutoTierStatus::Pending);
                assert_eq!(superseded.pending_auto_tier, Some(AutoTier::Fast));
                assert_eq!(superseded.superseded_auto_tier, Some(AutoTier::Efficiency));
                assert_eq!(pending_auto_tier(&session).await, Some(AutoTier::Fast));

                let replaced_fast = session
                    .set_auto_tier(Some(AutoTier::Intelligence))
                    .await
                    .expect("stage intelligence");
                assert_eq!(replaced_fast.status, ModelSwitchAutoTierStatus::Pending);
                assert_eq!(
                    replaced_fast.pending_auto_tier,
                    Some(AutoTier::Intelligence)
                );
                assert_eq!(replaced_fast.superseded_auto_tier, Some(AutoTier::Fast));
                assert_eq!(
                    pending_auto_tier(&session).await,
                    Some(AutoTier::Intelligence)
                );

                // `None` returns the session to provider-default routing. The status is
                // `Unchanged` because provider-default was already the committed
                // preference; the request's effect is cancelling the staged one.
                let reset = session.set_auto_tier(None).await.expect("reset tier");
                assert_eq!(reset.status, ModelSwitchAutoTierStatus::Unchanged);
                assert_eq!(reset.superseded_auto_tier, Some(AutoTier::Intelligence));
                assert_eq!(pending_auto_tier(&session).await, None);

                session.disconnect().await.expect("disconnect session");
                client.stop().await.expect("stop client");
            })
        },
    )
    .await;
}

#[tokio::test]
async fn should_preserve_auto_tier_when_set_model_omits_it() {
    with_dedicated_e2e_context(
        "auto_tier",
        "should_preserve_auto_tier_when_set_model_omits_it",
        |ctx| {
            Box::pin(async move {
                ctx.set_default_copilot_user();
                let client = ctx.start_client().await;
                let session = client
                    .create_session(ctx.approve_all_session_config().with_model(MODEL_ID))
                    .await
                    .expect("create session");

                session
                    .set_auto_tier(Some(AutoTier::Balance))
                    .await
                    .expect("stage balance");
                assert_eq!(pending_auto_tier(&session).await, Some(AutoTier::Balance));

                // Omitting the preference leaves the staged one alone.
                session
                    .set_model(MODEL_ID, None)
                    .await
                    .expect("set model without a tier");
                assert_eq!(pending_auto_tier(&session).await, Some(AutoTier::Balance));

                // Supplying a tier replaces it.
                session
                    .set_model(
                        MODEL_ID,
                        Some(SetModelOptions::default().with_auto_tier(AutoTier::Fast)),
                    )
                    .await
                    .expect("set model with a tier");
                assert_eq!(pending_auto_tier(&session).await, Some(AutoTier::Fast));

                // Requesting a reset clears it. Omission, a tier, and a reset are three
                // distinct outcomes, which `AutoTierPreference` makes explicit.
                session
                    .set_model(
                        MODEL_ID,
                        Some(SetModelOptions::default().with_reset_auto_tier()),
                    )
                    .await
                    .expect("set model with a reset");
                assert_eq!(pending_auto_tier(&session).await, None);

                session.disconnect().await.expect("disconnect session");
                client.stop().await.expect("stop client");
            })
        },
    )
    .await;
}

#[tokio::test]
async fn should_restore_and_override_fast_auto_tier_on_cold_resume() {
    with_dedicated_e2e_context(
        "auto_tier",
        "should_restore_and_override_fast_auto_tier_on_cold_resume",
        |ctx| {
            Box::pin(async move {
                ctx.set_default_copilot_user();
                let client = ctx.start_client().await;
                let fast_session = client
                    .create_session(auto_session_config(Some(AutoTier::Fast)))
                    .await
                    .expect("create fast session");
                let tierless_session = client
                    .create_session(auto_session_config(None))
                    .await
                    .expect("create tierless session");
                let fast_session_id = fast_session.id().clone();
                let tierless_session_id = tierless_session.id().clone();

                send_prompt(
                    &fast_session,
                    "Reply with exactly AUTO_TIER_COLD_RESUME_READY.",
                )
                .await;
                send_prompt(
                    &tierless_session,
                    "Reply with exactly AUTO_TIER_TIERLESS_READY.",
                )
                .await;

                let fast_current = fast_session
                    .rpc()
                    .model()
                    .get_current()
                    .await
                    .expect("get fast current model");
                assert_eq!(fast_current.auto_tier, Some(AutoTier::Fast));
                let tierless_current = tierless_session
                    .rpc()
                    .model()
                    .get_current()
                    .await
                    .expect("get tierless current model");
                assert_eq!(tierless_current.auto_tier, None);

                fast_session
                    .disconnect()
                    .await
                    .expect("disconnect fast session");
                tierless_session
                    .disconnect()
                    .await
                    .expect("disconnect tierless session");
                client.stop().await.expect("stop initial client");

                let restored_client = ctx.start_client().await;
                let restored_fast = restored_client
                    .resume_session(auto_resume_config(fast_session_id.clone()))
                    .await
                    .expect("resume fast session");
                let restored_tierless = restored_client
                    .resume_session(auto_resume_config(tierless_session_id))
                    .await
                    .expect("resume tierless session");
                let restored_fast_current = restored_fast
                    .rpc()
                    .model()
                    .get_current()
                    .await
                    .expect("get restored fast current model");
                assert_eq!(restored_fast_current.auto_tier, Some(AutoTier::Fast));
                let restored_tierless_current = restored_tierless
                    .rpc()
                    .model()
                    .get_current()
                    .await
                    .expect("get restored tierless current model");
                assert_eq!(restored_tierless_current.auto_tier, None);

                restored_fast
                    .disconnect()
                    .await
                    .expect("disconnect restored fast session");
                restored_tierless
                    .disconnect()
                    .await
                    .expect("disconnect restored tierless session");
                restored_client.stop().await.expect("stop restored client");

                let override_client = ctx.start_client().await;
                let overridden = override_client
                    .resume_session(
                        auto_resume_config(fast_session_id)
                            .with_model(MODEL_ID)
                            .with_capi(
                                CapiSessionOptions::new()
                                    .with_auto_tier(AutoTier::Balance)
                                    .with_enable_web_socket_responses(false),
                            ),
                    )
                    .await
                    .expect("resume session with balance override");
                let overridden_current = overridden
                    .rpc()
                    .model()
                    .get_current()
                    .await
                    .expect("get overridden current model");
                assert_eq!(overridden_current.auto_tier, Some(AutoTier::Balance));

                overridden
                    .disconnect()
                    .await
                    .expect("disconnect overridden session");
                override_client.stop().await.expect("stop override client");
            })
        },
    )
    .await;
}

#[tokio::test]
async fn should_commit_fast_auto_tier_after_successful_turn() {
    with_dedicated_e2e_context(
        "auto_tier",
        "should_commit_fast_auto_tier_after_successful_turn",
        |ctx| {
            Box::pin(async move {
                ctx.set_default_copilot_user();
                let client = ctx.start_client().await;
                let session = client
                    .create_session(auto_session_config(Some(AutoTier::Efficiency)))
                    .await
                    .expect("create session");

                let model_change = wait_for_event(
                    session.subscribe(),
                    "Fast Auto tier model change",
                    |event| {
                        event.parsed_type() == SessionEventType::SessionModelChange
                            && event
                                .typed_data::<SessionModelChangeData>()
                                .is_some_and(|data| data.auto_tier == Some(AutoTier::Fast))
                    },
                );

                let staged = session
                    .set_auto_tier(Some(AutoTier::Fast))
                    .await
                    .expect("stage fast");
                assert_eq!(staged.status, ModelSwitchAutoTierStatus::Pending);
                assert_eq!(staged.effective_auto_tier, Some(AutoTier::Efficiency));
                assert_eq!(staged.pending_auto_tier, Some(AutoTier::Fast));

                let before_turn = session
                    .rpc()
                    .model()
                    .get_current()
                    .await
                    .expect("get current model before turn");
                assert_eq!(before_turn.auto_tier, Some(AutoTier::Efficiency));
                assert_eq!(before_turn.pending_auto_tier, Some(AutoTier::Fast));

                send_prompt(&session, "Reply with exactly AUTO_TIER_FAST_COMMITTED.").await;

                let model_change = model_change.await;
                let data = model_change
                    .typed_data::<SessionModelChangeData>()
                    .expect("typed model change data");
                assert_eq!(data.previous_model.as_deref(), Some(MODEL_ID));
                assert_eq!(data.new_model, MODEL_ID);
                assert_eq!(data.previous_auto_tier, Some(AutoTier::Efficiency));
                assert_eq!(data.auto_tier, Some(AutoTier::Fast));

                let committed = session
                    .rpc()
                    .model()
                    .get_current()
                    .await
                    .expect("get current model after turn");
                assert_eq!(committed.auto_tier, Some(AutoTier::Fast));
                assert_eq!(committed.pending_auto_tier, None);
                assert_eq!(committed.activating_auto_tier, None);

                session.disconnect().await.expect("disconnect session");
                client.stop().await.expect("stop client");
            })
        },
    )
    .await;
}

#[tokio::test]
async fn should_preserve_effective_tier_when_fast_activation_fails() {
    with_dedicated_e2e_context(
        "auto_tier",
        "should_preserve_effective_tier_when_fast_activation_fails",
        |ctx| {
            Box::pin(async move {
                ctx.set_default_copilot_user();
                let client = ctx.start_client().await;
                let session = client
                    .create_session(auto_session_config(Some(AutoTier::Efficiency)))
                    .await
                    .expect("create session");
                let session_id = session.id().clone();
                send_prompt(&session, "Reply with exactly AUTO_TIER_INITIAL_READY.").await;

                let failure = wait_for_event(
                    session.subscribe(),
                    "Fast Auto tier activation failure",
                    |event| event.parsed_type() == SessionEventType::SessionAutoTierSwitchFailed,
                );
                let mut model_changes = session.subscribe();

                let staged = session
                    .set_auto_tier(Some(AutoTier::Fast))
                    .await
                    .expect("stage fast");
                assert_eq!(staged.status, ModelSwitchAutoTierStatus::Pending);
                assert_eq!(staged.effective_auto_tier, Some(AutoTier::Efficiency));
                assert_eq!(staged.pending_auto_tier, Some(AutoTier::Fast));

                send_prompt(&session, "Reply with exactly AUTO_TIER_FAILURE_RECOVERED.").await;

                let failure = failure.await;
                assert_eq!(failure.ephemeral, Some(true));
                let data = failure
                    .typed_data::<SessionAutoTierSwitchFailedData>()
                    .expect("typed Auto tier failure data");
                assert_eq!(data.effective_auto_tier, Some(AutoTier::Efficiency));
                assert_eq!(data.requested_auto_tier, Some(AutoTier::Fast));
                assert_eq!(data.reason, AutoTierSwitchFailureReason::RequestFailed);

                while let Ok(Ok(event)) =
                    tokio::time::timeout(Duration::from_millis(25), model_changes.recv()).await
                {
                    assert!(
                        event.parsed_type() != SessionEventType::SessionModelChange
                            || !event
                                .typed_data::<SessionModelChangeData>()
                                .is_some_and(|data| data.auto_tier == Some(AutoTier::Fast)),
                        "Fast tier committed after failed activation"
                    );
                }

                let current = session
                    .rpc()
                    .model()
                    .get_current()
                    .await
                    .expect("get current model after failure");
                assert_eq!(current.auto_tier, Some(AutoTier::Efficiency));
                assert_eq!(current.pending_auto_tier, None);
                assert_eq!(current.activating_auto_tier, None);

                session.disconnect().await.expect("disconnect session");
                client.stop().await.expect("stop initial client");

                let resumed_client = ctx.start_client().await;
                let resumed = resumed_client
                    .resume_session(auto_resume_config(session_id))
                    .await
                    .expect("resume session");
                let resumed_current = resumed
                    .rpc()
                    .model()
                    .get_current()
                    .await
                    .expect("get current model after resume");
                assert_eq!(resumed_current.auto_tier, Some(AutoTier::Efficiency));
                assert_eq!(resumed_current.pending_auto_tier, None);
                assert_eq!(resumed_current.activating_auto_tier, None);

                let persisted = resumed
                    .rpc()
                    .event_log()
                    .read(EventLogReadRequest {
                        agent_ids: None,
                        agent_scope: None,
                        cursor: None,
                        direction: None,
                        include_ephemeral: Some(false),
                        max: Some(100),
                        types: Some(json!("*")),
                        wait_ms: Some(0),
                    })
                    .await
                    .expect("read event log");
                assert!(
                    persisted.events.iter().all(|event| {
                        event.parsed_type() != SessionEventType::SessionAutoTierSwitchFailed
                    }),
                    "ephemeral failure event was replayed after cold resume"
                );

                resumed
                    .disconnect()
                    .await
                    .expect("disconnect resumed session");
                resumed_client.stop().await.expect("stop resumed client");
            })
        },
    )
    .await;
}