-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathCopilotClient.java.html
More file actions
1212 lines (1119 loc) · 73.8 KB
/
Copy pathCopilotClient.java.html
File metadata and controls
1212 lines (1119 loc) · 73.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml" lang=""><head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/><link rel="stylesheet" href="../jacoco-resources/report.css" type="text/css"/><link rel="shortcut icon" href="../jacoco-resources/report.gif" type="image/gif"/><title>CopilotClient.java</title><link rel="stylesheet" href="../jacoco-resources/prettify.css" type="text/css"/><script type="text/javascript" src="../jacoco-resources/prettify.js"></script></head><body onload="window['PR_TAB_WIDTH']=4;prettyPrint()"><div class="breadcrumb" id="breadcrumb"><span class="info"><a href="../jacoco-sessions.html" class="el_session">Sessions</a></span><a href="../index.html" class="el_report">GitHub Copilot SDK :: Java</a> > <a href="index.source.html" class="el_package">com.github.copilot</a> > <span class="el_source">CopilotClient.java</span></div><h1>CopilotClient.java</h1><pre class="source lang-java linenums">/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------------------------------------------*/
package com.github.copilot;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.github.copilot.rpc.CopilotClientMode;
import com.github.copilot.rpc.CopilotClientOptions;
import com.github.copilot.rpc.CreateSessionResponse;
import com.github.copilot.generated.rpc.SessionOptionsUpdateParams;
import com.github.copilot.generated.rpc.SessionInstalledPlugin;
import com.github.copilot.generated.rpc.ConnectParams;
import com.github.copilot.generated.rpc.ServerRpc;
import com.github.copilot.rpc.DeleteSessionResponse;
import com.github.copilot.rpc.GetAuthStatusResponse;
import com.github.copilot.rpc.GetLastSessionIdResponse;
import com.github.copilot.rpc.GetSessionMetadataResponse;
import com.github.copilot.rpc.GetModelsResponse;
import com.github.copilot.rpc.GetStatusResponse;
import com.github.copilot.rpc.ListSessionsResponse;
import com.github.copilot.rpc.ModelInfo;
import com.github.copilot.rpc.PingResponse;
import com.github.copilot.rpc.ResumeSessionConfig;
import com.github.copilot.rpc.ResumeSessionResponse;
import com.github.copilot.rpc.SessionConfig;
import com.github.copilot.rpc.SessionLifecycleHandler;
import com.github.copilot.rpc.SessionListFilter;
import com.github.copilot.rpc.SessionMetadata;
/**
* Provides a client for interacting with the Copilot CLI server.
* <p>
* The CopilotClient manages the connection to the Copilot CLI server and
* provides methods to create and manage conversation sessions. It can either
* spawn a CLI server process or connect to an existing server.
* <p>
* Example usage:
*
* <pre>{@code
* try (var client = new CopilotClient()) {
* client.start().get();
*
* var session = client
* .createSession(
* new SessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL).setModel("gpt-5"))
* .get();
*
* session.on(AssistantMessageEvent.class, msg -> {
* System.out.println(msg.getData().content());
* });
*
* session.send(new MessageOptions().setPrompt("Hello!")).get();
* }
* }</pre>
*
* @since 1.0.0
*/
public final class CopilotClient implements AutoCloseable {
<span class="nc" id="L76"> private static final Logger LOG = Logger.getLogger(CopilotClient.class.getName());</span>
/**
* Timeout, in seconds, used by {@link #close()} when waiting for graceful
* shutdown via {@link #stop()}.
*/
public static final int AUTOCLOSEABLE_TIMEOUT_SECONDS = 10;
private static final int FORCE_KILL_TIMEOUT_SECONDS = 10;
/**
* One-shot dispatcher used to run the owned-executor shutdown off any caller
* thread that might itself belong to that executor (e.g. the
* {@link #forceStop()} continuation, which is chained off async work scheduled
* on the internal executor). Spawning a fresh daemon thread guarantees
* {@link java.util.concurrent.ExecutorService#awaitTermination(long, TimeUnit)}
* is never called from inside the very executor it is waiting on.
*/
<span class="nc" id="L93"> private static final Executor SHUTDOWN_DISPATCHER = runnable -> {</span>
<span class="nc" id="L94"> Thread t = new Thread(runnable, "copilot-client-shutdown");</span>
<span class="nc" id="L95"> t.setDaemon(true);</span>
<span class="nc" id="L96"> t.start();</span>
<span class="nc" id="L97"> };</span>
private final CopilotClientOptions options;
private final Executor executor;
private final boolean executorCanBeShutdown;
private final CliServerManager serverManager;
<span class="nc" id="L103"> private final LifecycleEventManager lifecycleManager = new LifecycleEventManager();</span>
<span class="nc" id="L104"> private final Map<String, CopilotSession> sessions = new ConcurrentHashMap<>();</span>
private volatile CompletableFuture<Connection> connectionFuture;
<span class="nc" id="L106"> private volatile boolean disposed = false;</span>
private final String optionsHost;
private final Integer optionsPort;
private final String effectiveConnectionToken;
private volatile List<ModelInfo> modelsCache;
<span class="nc" id="L111"> private final Object modelsCacheLock = new Object();</span>
/**
* Creates a new CopilotClient with default options.
*/
public CopilotClient() {
<span class="nc" id="L117"> this(new CopilotClientOptions());</span>
<span class="nc" id="L118"> }</span>
/**
* Creates a new CopilotClient with the specified options.
*
* @param options
* Options for creating the client
* @throws IllegalArgumentException
* if mutually exclusive options are provided
*/
<span class="nc" id="L128"> public CopilotClient(CopilotClientOptions options) {</span>
<span class="nc bnc" id="L129" title="All 2 branches missed."> this.options = options != null ? options : new CopilotClientOptions();</span>
// When cliUrl is set, auto-correct useStdio since we're connecting via TCP
<span class="nc bnc" id="L132" title="All 4 branches missed."> if (this.options.getCliUrl() != null && !this.options.getCliUrl().isEmpty()) {</span>
<span class="nc" id="L133"> this.options.setUseStdio(false);</span>
}
// Validate mutually exclusive options: cliUrl and cliPath cannot both be set
<span class="nc bnc" id="L137" title="All 4 branches missed."> if (this.options.getCliUrl() != null && !this.options.getCliUrl().isEmpty()</span>
<span class="nc bnc" id="L138" title="All 2 branches missed."> && this.options.getCliPath() != null) {</span>
<span class="nc" id="L139"> throw new IllegalArgumentException("CliUrl is mutually exclusive with CliPath");</span>
}
// Validate auth options with external server
<span class="nc bnc" id="L143" title="All 4 branches missed."> if (this.options.getCliUrl() != null && !this.options.getCliUrl().isEmpty()</span>
<span class="nc bnc" id="L144" title="All 4 branches missed."> && (this.options.getGitHubToken() != null || this.options.getUseLoggedInUser().isPresent())) {</span>
<span class="nc" id="L145"> throw new IllegalArgumentException(</span>
"GitHubToken and UseLoggedInUser cannot be used with CliUrl (external server manages its own auth)");
}
// Validate tcpConnectionToken
<span class="nc bnc" id="L150" title="All 2 branches missed."> if (this.options.getTcpConnectionToken() != null) {</span>
<span class="nc bnc" id="L151" title="All 2 branches missed."> if (this.options.getTcpConnectionToken().isEmpty()) {</span>
<span class="nc" id="L152"> throw new IllegalArgumentException("TcpConnectionToken must be a non-empty string");</span>
}
<span class="nc bnc" id="L154" title="All 2 branches missed."> if (this.options.isUseStdio()) {</span>
<span class="nc" id="L155"> throw new IllegalArgumentException("TcpConnectionToken cannot be used with UseStdio = true");</span>
}
}
// Compute effective connection token: use provided, or auto-generate for
// SDK-spawned TCP mode, or null for stdio/external server
<span class="nc bnc" id="L161" title="All 2 branches missed."> boolean sdkSpawnsCli = !this.options.isUseStdio()</span>
<span class="nc bnc" id="L162" title="All 4 branches missed."> && (this.options.getCliUrl() == null || this.options.getCliUrl().isEmpty());</span>
<span class="nc bnc" id="L163" title="All 2 branches missed."> this.effectiveConnectionToken = this.options.getTcpConnectionToken() != null</span>
<span class="nc" id="L164"> ? this.options.getTcpConnectionToken()</span>
<span class="nc bnc" id="L165" title="All 2 branches missed."> : (sdkSpawnsCli ? java.util.UUID.randomUUID().toString() : null);</span>
// Empty mode: validate at construction time that the app supplied a
// per-session persistence location.
<span class="nc bnc" id="L169" title="All 2 branches missed."> if (this.options.getMode() == CopilotClientMode.EMPTY) {</span>
<span class="nc bnc" id="L170" title="All 4 branches missed."> boolean hasPersistence = (this.options.getCopilotHome() != null && !this.options.getCopilotHome().isEmpty())</span>
<span class="nc bnc" id="L171" title="All 4 branches missed."> || (this.options.getCliUrl() != null && !this.options.getCliUrl().isEmpty());</span>
<span class="nc bnc" id="L172" title="All 2 branches missed."> if (!hasPersistence) {</span>
<span class="nc" id="L173"> throw new IllegalArgumentException(</span>
"CopilotClient was created with Mode = EMPTY but neither CopilotHome nor CliUrl was set. "
+ "Empty mode requires an explicit per-session persistence location.");
}
}
// Parse CliUrl if provided
<span class="nc bnc" id="L180" title="All 4 branches missed."> if (this.options.getCliUrl() != null && !this.options.getCliUrl().isEmpty()) {</span>
<span class="nc" id="L181"> URI uri = CliServerManager.parseCliUrl(this.options.getCliUrl());</span>
<span class="nc" id="L182"> this.optionsHost = uri.getHost();</span>
<span class="nc" id="L183"> this.optionsPort = uri.getPort();</span>
<span class="nc" id="L184"> } else {</span>
<span class="nc" id="L185"> this.optionsHost = null;</span>
<span class="nc" id="L186"> this.optionsPort = null;</span>
}
<span class="nc" id="L189"> InternalExecutorProvider executorProvider = new InternalExecutorProvider(this.options.getExecutor());</span>
<span class="nc" id="L190"> this.executor = executorProvider.get();</span>
<span class="nc" id="L191"> this.executorCanBeShutdown = executorProvider.canBeShutdown();</span>
<span class="nc" id="L193"> this.serverManager = new CliServerManager(this.options);</span>
<span class="nc" id="L194"> this.serverManager.setConnectionToken(this.effectiveConnectionToken);</span>
<span class="nc" id="L195"> }</span>
/**
* Starts the Copilot client and connects to the server.
*
* @return A future that completes when the connection is established
*/
public CompletableFuture<Void> start() {
<span class="nc bnc" id="L203" title="All 2 branches missed."> if (connectionFuture == null) {</span>
<span class="nc" id="L204"> synchronized (this) {</span>
<span class="nc bnc" id="L205" title="All 2 branches missed."> if (connectionFuture == null) {</span>
<span class="nc" id="L206"> connectionFuture = startCore();</span>
}
<span class="nc" id="L208"> }</span>
}
<span class="nc" id="L210"> return connectionFuture.thenApply(c -> null);</span>
}
private CompletableFuture<Connection> startCore() {
<span class="nc" id="L214"> LOG.fine("Starting Copilot client");</span>
try {
<span class="nc" id="L217"> return CompletableFuture.supplyAsync(this::startCoreBody, executor);</span>
<span class="nc" id="L218"> } catch (RejectedExecutionException e) {</span>
<span class="nc" id="L219"> return CompletableFuture.failedFuture(e);</span>
}
}
private Connection startCoreBody() {
<span class="nc" id="L224"> Process process = null;</span>
<span class="nc" id="L225"> long startNanos = System.nanoTime();</span>
try {
JsonRpcClient rpc;
<span class="nc bnc" id="L229" title="All 4 branches missed."> if (optionsHost != null && optionsPort != null) {</span>
// External server (TCP)
<span class="nc" id="L231"> rpc = serverManager.connectToServer(null, optionsHost, optionsPort);</span>
} else {
// Child process (stdio or TCP)
<span class="nc" id="L234"> CliServerManager.ProcessInfo processInfo = serverManager.startCliServer();</span>
<span class="nc" id="L235"> process = processInfo.process();</span>
<span class="nc bnc" id="L236" title="All 2 branches missed."> rpc = serverManager.connectToServer(process, processInfo.port() != null ? "localhost" : null,</span>
<span class="nc" id="L237"> processInfo.port());</span>
}
<span class="nc" id="L240"> LoggingHelpers.logTiming(LOG, Level.FINE, "CopilotClient.start transport setup complete. Elapsed={Elapsed}",</span>
startNanos);
<span class="nc" id="L243"> Connection connection = new Connection(rpc, process, new ServerRpc(rpc::invoke));</span>
// Register handlers for server-to-client calls
<span class="nc" id="L246"> RpcHandlerDispatcher dispatcher = new RpcHandlerDispatcher(sessions, lifecycleManager::dispatch, executor);</span>
<span class="nc" id="L247"> dispatcher.registerHandlers(rpc);</span>
// Verify protocol version
<span class="nc" id="L250"> verifyProtocolVersion(connection);</span>
<span class="nc" id="L251"> LoggingHelpers.logTiming(LOG, Level.FINE,</span>
"CopilotClient.start protocol verification complete. Elapsed={Elapsed}", startNanos);
<span class="nc" id="L254"> LoggingHelpers.logTiming(LOG, Level.FINE, "CopilotClient.start complete. Elapsed={Elapsed}", startNanos);</span>
<span class="nc" id="L255"> return connection;</span>
<span class="nc" id="L256"> } catch (Exception e) {</span>
<span class="nc bnc" id="L257" title="All 2 branches missed."> if (!(e instanceof java.util.concurrent.CancellationException)) {</span>
<span class="nc" id="L258"> LoggingHelpers.logTiming(LOG, Level.WARNING, e, "CopilotClient.start failed. Elapsed={Elapsed}",</span>
startNanos);
}
// Clean up the spawned process if connection setup failed
<span class="nc bnc" id="L262" title="All 2 branches missed."> if (process != null) {</span>
<span class="nc" id="L263"> cleanupCliProcess(process);</span>
}
<span class="nc" id="L265"> String stderr = serverManager.getStderrOutput();</span>
<span class="nc bnc" id="L266" title="All 2 branches missed."> if (!stderr.isEmpty()) {</span>
<span class="nc" id="L267"> throw new CompletionException(new IOException(</span>
<span class="nc" id="L268"> CliServerManager.formatCliExitedMessage("CLI process exited unexpectedly.", stderr), e));</span>
}
<span class="nc" id="L270"> throw new CompletionException(e);</span>
}
}
private static final int MIN_PROTOCOL_VERSION = 2;
private static final int METHOD_NOT_FOUND_ERROR_CODE = -32601;
private void verifyProtocolVersion(Connection connection) throws Exception {
<span class="nc" id="L278"> int expectedVersion = SdkProtocolVersion.get();</span>
Integer serverVersion;
try {
// Try the new 'connect' RPC which supports connection tokens
<span class="nc" id="L283"> var connectParams = new ConnectParams(effectiveConnectionToken);</span>
<span class="nc" id="L284"> var connectResponse = connection.rpc</span>
<span class="nc" id="L285"> .invoke("connect", connectParams, com.github.copilot.generated.rpc.ConnectResult.class)</span>
<span class="nc" id="L286"> .get(30, TimeUnit.SECONDS);</span>
<span class="nc bnc" id="L287" title="All 2 branches missed."> serverVersion = connectResponse.protocolVersion() != null</span>
<span class="nc" id="L288"> ? connectResponse.protocolVersion().intValue()</span>
<span class="nc" id="L289"> : null;</span>
<span class="nc" id="L290"> } catch (Exception e) {</span>
// Unwrap CompletionException/ExecutionException to check inner cause
<span class="nc" id="L292"> Throwable cause = e;</span>
<span class="nc bnc" id="L293" title="All 4 branches missed."> while (cause instanceof java.util.concurrent.ExecutionException || cause instanceof CompletionException) {</span>
<span class="nc" id="L294"> cause = cause.getCause();</span>
}
<span class="nc bnc" id="L296" title="All 4 branches missed."> if (cause instanceof JsonRpcException rpcEx && isUnsupportedConnectMethod(rpcEx)) {</span>
// Legacy server without 'connect'; fall back to 'ping'.
// A token, if any, is silently dropped — the legacy server can't enforce one.
<span class="nc" id="L299"> var params = new HashMap<String, Object>();</span>
<span class="nc" id="L300"> params.put("message", null);</span>
<span class="nc" id="L301"> PingResponse pingResponse = connection.rpc.invoke("ping", params, PingResponse.class).get(30,</span>
TimeUnit.SECONDS);
<span class="nc" id="L303"> serverVersion = pingResponse.protocolVersion();</span>
<span class="nc" id="L304"> } else {</span>
<span class="nc" id="L305"> throw e;</span>
}
<span class="nc" id="L307"> }</span>
<span class="nc bnc" id="L309" title="All 2 branches missed."> if (serverVersion == null) {</span>
<span class="nc" id="L310"> throw new RuntimeException("SDK protocol version mismatch: SDK supports versions " + MIN_PROTOCOL_VERSION</span>
+ "-" + expectedVersion + ", but server does not report a protocol version. "
+ "Please update your server to ensure compatibility.");
}
<span class="nc bnc" id="L315" title="All 4 branches missed."> if (serverVersion < MIN_PROTOCOL_VERSION || serverVersion > expectedVersion) {</span>
<span class="nc" id="L316"> throw new RuntimeException("SDK protocol version mismatch: SDK supports versions " + MIN_PROTOCOL_VERSION</span>
+ "-" + expectedVersion + ", but server reports version " + serverVersion + ". "
+ "Please update your SDK or server to ensure compatibility.");
}
<span class="nc" id="L320"> }</span>
private static boolean isUnsupportedConnectMethod(JsonRpcException ex) {
<span class="nc bnc" id="L323" title="All 4 branches missed."> return ex.getCode() == METHOD_NOT_FOUND_ERROR_CODE || "Unhandled method connect".equals(ex.getMessage());</span>
}
/**
* Disconnects from the Copilot server and closes all active sessions.
* <p>
* This method performs graceful cleanup:
* <ol>
* <li>Closes all active sessions (releases in-memory resources)</li>
* <li>Closes the JSON-RPC connection</li>
* <li>Terminates the CLI server process (if spawned by this client)</li>
* </ol>
* <p>
* Note: session data on disk is preserved, so sessions can be resumed later. To
* permanently remove session data before stopping, call
* {@link #deleteSession(String)} for each session first.
*
* @return A future that completes when the client is stopped
*/
public CompletableFuture<Void> stop() {
<span class="nc" id="L343"> var closeFutures = new ArrayList<CompletableFuture<Void>>();</span>
<span class="nc bnc" id="L345" title="All 2 branches missed."> for (CopilotSession session : new ArrayList<>(sessions.values())) {</span>
<span class="nc" id="L346"> Runnable closeTask = () -> {</span>
try {
<span class="nc" id="L348"> session.close();</span>
<span class="nc" id="L349"> } catch (Exception e) {</span>
<span class="nc" id="L350"> LOG.log(Level.WARNING, "Error closing session " + session.getSessionId(), e);</span>
<span class="nc" id="L351"> }</span>
<span class="nc" id="L352"> };</span>
CompletableFuture<Void> future;
try {
<span class="nc" id="L355"> future = CompletableFuture.runAsync(closeTask, executor);</span>
<span class="nc" id="L356"> } catch (RejectedExecutionException e) {</span>
<span class="nc" id="L357"> LOG.log(Level.WARNING, "Executor rejected session close task; closing inline", e);</span>
<span class="nc" id="L358"> closeTask.run();</span>
<span class="nc" id="L359"> future = CompletableFuture.completedFuture(null);</span>
<span class="nc" id="L360"> }</span>
<span class="nc" id="L361"> closeFutures.add(future);</span>
<span class="nc" id="L362"> }</span>
<span class="nc" id="L363"> sessions.clear();</span>
<span class="nc" id="L365"> return CompletableFuture.allOf(closeFutures.toArray(new CompletableFuture[0]))</span>
<span class="nc" id="L366"> .thenCompose(v -> cleanupConnection());</span>
}
/**
* Forces an immediate stop of the client without graceful cleanup.
*
* @return A future that completes when the client is stopped
*/
public CompletableFuture<Void> forceStop() {
<span class="nc" id="L375"> disposed = true;</span>
<span class="nc" id="L376"> sessions.clear();</span>
// Dispatch the blocking shutdownOwnedExecutor() on a dedicated thread:
// cleanupConnection() is chained off async work running on the owned
// executor, so a plain whenComplete(...) here could land the awaitTermination
// call on one of the very threads it is waiting to drain, forcing the full
// AUTOCLOSEABLE_TIMEOUT_SECONDS timeout followed by shutdownNow().
<span class="nc" id="L382"> return cleanupConnection().whenCompleteAsync((ignored, error) -> shutdownOwnedExecutor(), SHUTDOWN_DISPATCHER);</span>
}
private CompletableFuture<Void> cleanupConnection() {
<span class="nc" id="L386"> CompletableFuture<Connection> future = connectionFuture;</span>
<span class="nc" id="L387"> connectionFuture = null;</span>
// Clear models cache
<span class="nc" id="L390"> modelsCache = null;</span>
<span class="nc bnc" id="L392" title="All 2 branches missed."> if (future == null) {</span>
<span class="nc" id="L393"> return CompletableFuture.completedFuture(null);</span>
}
<span class="nc" id="L396"> return future.thenAccept(connection -> {</span>
try {
<span class="nc" id="L398"> connection.rpc.close();</span>
<span class="nc" id="L399"> } catch (Exception e) {</span>
<span class="nc" id="L400"> LOG.log(Level.FINE, "Error closing RPC", e);</span>
<span class="nc" id="L401"> }</span>
<span class="nc bnc" id="L403" title="All 2 branches missed."> if (connection.process != null) {</span>
<span class="nc" id="L404"> cleanupCliProcess(connection.process);</span>
}
<span class="nc" id="L406"> }).exceptionally(ex -> {</span>
<span class="nc" id="L407"> LOG.log(Level.FINE, "Ignoring failed Copilot client startup during cleanup", ex);</span>
<span class="nc" id="L408"> return null;</span>
});
}
private static void cleanupCliProcess(Process process) {
try {
<span class="nc bnc" id="L414" title="All 2 branches missed."> if (process.isAlive()) {</span>
<span class="nc" id="L415"> Process destroyedProcess = process.destroyForcibly();</span>
<span class="nc bnc" id="L416" title="All 2 branches missed."> if (!destroyedProcess.waitFor(FORCE_KILL_TIMEOUT_SECONDS, TimeUnit.SECONDS)) {</span>
<span class="nc" id="L417"> LOG.fine("Process did not terminate within force kill timeout");</span>
}
}
<span class="nc" id="L420"> } catch (InterruptedException e) {</span>
<span class="nc" id="L421"> Thread.currentThread().interrupt();</span>
<span class="nc" id="L422"> LOG.log(Level.FINE, "Interrupted while killing process", e);</span>
<span class="nc" id="L423"> } catch (Exception e) {</span>
<span class="nc" id="L424"> LOG.log(Level.FINE, "Error killing process", e);</span>
<span class="nc" id="L425"> }</span>
<span class="nc" id="L426"> }</span>
/**
* Creates a new Copilot session with the specified configuration.
* <p>
* The session maintains conversation state and can be used to send messages and
* receive responses. Remember to close the session when done.
* <p>
* A permission handler is required when creating a session. Use
* {@link com.github.copilot.rpc.PermissionHandler#APPROVE_ALL} to approve all
* permission requests, or provide a custom handler to control permissions
* selectively.
*
* <p>
* Example:
*
* <pre>{@code
* var session = client.createSession(new SessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL)).get();
* }</pre>
*
* @param config
* configuration for the session, including the required
* {@link SessionConfig#setOnPermissionRequest(com.github.copilot.rpc.PermissionHandler)}
* handler
* @return a future that resolves with the created CopilotSession
* @throws IllegalArgumentException
* if {@code config} is {@code null} or does not have a permission
* handler set
* @see SessionConfig
* @see com.github.copilot.rpc.PermissionHandler#APPROVE_ALL
*/
public CompletableFuture<CopilotSession> createSession(SessionConfig config) {
<span class="nc bnc" id="L458" title="All 4 branches missed."> if (config == null || config.getOnPermissionRequest() == null) {</span>
<span class="nc" id="L459"> return CompletableFuture.failedFuture(</span>
new IllegalArgumentException("An onPermissionRequest handler is required when creating a session. "
+ "For example, to allow all permissions, use: "
+ "new SessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL)"));
}
<span class="nc" id="L464"> return ensureConnected().thenCompose(connection -> {</span>
<span class="nc" id="L465"> long totalNanos = System.nanoTime();</span>
// For cloud sessions, let the CLI/server assign the session id
// and register the session lazily once the response arrives. For
// non-cloud sessions we generate the id client-side (when the
// caller didn't supply one) so the session can be registered
// BEFORE the RPC — the CLI may issue session-scoped requests
// (e.g. sessionFs.writeFile for workspace metadata) during
// session.create processing, before it has sent the response.
<span class="nc" id="L473"> String callerSessionId = config.getSessionId();</span>
<span class="nc bnc" id="L474" title="All 4 branches missed."> boolean useServerGeneratedId = config.getCloud() != null</span>
<span class="nc bnc" id="L475" title="All 2 branches missed."> && (callerSessionId == null || callerSessionId.isEmpty());</span>
<span class="nc bnc" id="L476" title="All 2 branches missed."> String localSessionId = useServerGeneratedId</span>
<span class="nc" id="L477"> ? null</span>
<span class="nc bnc" id="L478" title="All 4 branches missed."> : (callerSessionId != null && !callerSessionId.isEmpty()</span>
<span class="nc" id="L479"> ? callerSessionId</span>
<span class="nc" id="L480"> : java.util.UUID.randomUUID().toString());</span>
// Extract transform callbacks from the system message config. Callbacks
// are registered with the session; a wire-safe copy of the system
// message (with transform sections replaced by action="transform") is
// used in the RPC request.
<span class="nc" id="L486"> var extracted = SessionRequestBuilder.extractTransformCallbacks(config.getSystemMessage());</span>
// Creates the session, wires up handlers, and registers it in the
// sessions map.
<span class="nc" id="L490"> java.util.function.Function<String, CopilotSession> initializeSession = sid -> {</span>
<span class="nc" id="L491"> long setupNanos = System.nanoTime();</span>
<span class="nc" id="L492"> var s = new CopilotSession(sid, connection.rpc);</span>
<span class="nc" id="L493"> s.setExecutor(executor);</span>
<span class="nc" id="L494"> SessionRequestBuilder.configureSession(s, config);</span>
<span class="nc bnc" id="L495" title="All 2 branches missed."> if (extracted.transformCallbacks() != null) {</span>
<span class="nc" id="L496"> s.registerTransformCallbacks(extracted.transformCallbacks());</span>
}
<span class="nc" id="L498"> sessions.put(sid, s);</span>
<span class="nc" id="L499"> LoggingHelpers.logTiming(LOG, Level.FINE,</span>
"CopilotClient.createSession local setup complete. Elapsed={Elapsed}, SessionId=" + sid,
setupNanos);
<span class="nc" id="L502"> return s;</span>
};
<span class="nc" id="L505"> String[] registeredIdHolder = new String[1];</span>
<span class="nc" id="L506"> CopilotSession[] preRegisteredSessionHolder = new CopilotSession[1];</span>
// Pre-register non-cloud sessions BEFORE issuing the RPC so any
// session-scoped requests the CLI emits during session.create
// processing can be routed to the correct handlers.
<span class="nc bnc" id="L511" title="All 2 branches missed."> if (localSessionId != null) {</span>
<span class="nc" id="L512"> preRegisteredSessionHolder[0] = initializeSession.apply(localSessionId);</span>
<span class="nc" id="L513"> registeredIdHolder[0] = localSessionId;</span>
}
<span class="nc" id="L516"> var request = SessionRequestBuilder.buildCreateRequest(config, localSessionId);</span>
<span class="nc bnc" id="L517" title="All 2 branches missed."> if (extracted.wireSystemMessage() != config.getSystemMessage()) {</span>
<span class="nc" id="L518"> request.setSystemMessage(extracted.wireSystemMessage());</span>
}
// Empty mode: validate availableTools and set toolFilterPrecedence
<span class="nc bnc" id="L522" title="All 2 branches missed."> if (options.getMode() == CopilotClientMode.EMPTY) {</span>
<span class="nc bnc" id="L523" title="All 2 branches missed."> if (config.getAvailableTools() == null) {</span>
<span class="nc bnc" id="L524" title="All 2 branches missed."> if (registeredIdHolder[0] != null) {</span>
<span class="nc" id="L525"> sessions.remove(registeredIdHolder[0]);</span>
}
<span class="nc" id="L527"> throw new IllegalArgumentException(</span>
"CopilotClient is in Mode = EMPTY but the session config did not specify "
+ "availableTools. Empty mode requires every session to explicitly opt into "
+ "the tools it wants — e.g. setAvailableTools(new ToolSet().addBuiltIn(BuiltInTools.ISOLATED)).");
}
<span class="nc" id="L532"> request.setToolFilterPrecedence("excluded");</span>
<span class="nc bnc" id="L533" title="All 2 branches missed."> if (request.getMcpOAuthTokenStorage() == null) {</span>
<span class="nc" id="L534"> request.setMcpOAuthTokenStorage("in-memory");</span>
}
}
<span class="nc" id="L538"> long rpcNanos = System.nanoTime();</span>
<span class="nc" id="L539"> return connection.rpc.invoke("session.create", request, CreateSessionResponse.class)</span>
<span class="nc" id="L540"> .thenCompose(response -> {</span>
<span class="nc" id="L541"> String returnedId = response.sessionId();</span>
<span class="nc" id="L542"> LoggingHelpers.logTiming(LOG, Level.FINE,</span>
"CopilotClient.createSession session creation request completed. Elapsed={Elapsed}, SessionId="
<span class="nc bnc" id="L544" title="All 2 branches missed."> + (returnedId != null ? returnedId : localSessionId),</span>
rpcNanos);
<span class="nc bnc" id="L546" title="All 4 branches missed."> if (returnedId == null || returnedId.isEmpty()) {</span>
<span class="nc" id="L547"> throw new RuntimeException("session.create response did not include a sessionId");</span>
}
<span class="nc bnc" id="L549" title="All 4 branches missed."> if (localSessionId != null && !localSessionId.equals(returnedId)) {</span>
<span class="nc" id="L550"> throw new RuntimeException("session.create returned sessionId " + returnedId</span>
+ " but the caller requested " + localSessionId);
}
<span class="nc bnc" id="L553" title="All 2 branches missed."> CopilotSession session = preRegisteredSessionHolder[0] != null</span>
<span class="nc" id="L554"> ? preRegisteredSessionHolder[0]</span>
<span class="nc" id="L555"> : initializeSession.apply(returnedId);</span>
<span class="nc" id="L556"> registeredIdHolder[0] = returnedId;</span>
<span class="nc" id="L557"> session.setWorkspacePath(response.workspacePath());</span>
<span class="nc" id="L558"> session.setCapabilities(response.capabilities());</span>
<span class="nc" id="L560"> return updateSessionOptionsForMode(session, config.getSkipCustomInstructions().orElse(null),</span>
<span class="nc" id="L561"> config.getCustomAgentsLocalOnly().orElse(null),</span>
<span class="nc" id="L562"> config.getCoauthorEnabled().orElse(null),</span>
<span class="nc" id="L563"> config.getManageScheduleEnabled().orElse(null)).thenApply(v -> {</span>
<span class="nc" id="L564"> LoggingHelpers.logTiming(LOG, Level.FINE,</span>
"CopilotClient.createSession complete. Elapsed={Elapsed}, SessionId="
<span class="nc" id="L566"> + session.getSessionId(),</span>
totalNanos);
<span class="nc" id="L568"> return session;</span>
});
<span class="nc" id="L570"> }).exceptionally(ex -> {</span>
<span class="nc bnc" id="L571" title="All 2 branches missed."> if (registeredIdHolder[0] != null) {</span>
<span class="nc" id="L572"> sessions.remove(registeredIdHolder[0]);</span>
}
<span class="nc" id="L574"> LoggingHelpers.logTiming(LOG, Level.WARNING, ex,</span>
"CopilotClient.createSession failed. Elapsed={Elapsed}, SessionId="
<span class="nc bnc" id="L576" title="All 2 branches missed."> + (registeredIdHolder[0] != null ? registeredIdHolder[0] : "<unassigned>"),</span>
totalNanos);
<span class="nc bnc" id="L578" title="All 2 branches missed."> throw ex instanceof RuntimeException re ? re : new RuntimeException(ex);</span>
});
});
}
/**
* Resumes an existing Copilot session.
* <p>
* This restores a previously saved session, allowing you to continue a
* conversation. The session's history is preserved.
* <p>
* A permission handler is required when resuming a session. Use
* {@link com.github.copilot.rpc.PermissionHandler#APPROVE_ALL} to approve all
* permission requests, or provide a custom handler to control permissions
* selectively.
*
* @param sessionId
* the ID of the session to resume
* @param config
* configuration for the resumed session, including the required
* {@link ResumeSessionConfig#setOnPermissionRequest(com.github.copilot.rpc.PermissionHandler)}
* handler
* @return a future that resolves with the resumed CopilotSession
* @throws IllegalArgumentException
* if {@code config} is {@code null} or does not have a permission
* handler set
* @see #listSessions()
* @see #getLastSessionId()
* @see com.github.copilot.rpc.PermissionHandler#APPROVE_ALL
*/
public CompletableFuture<CopilotSession> resumeSession(String sessionId, ResumeSessionConfig config) {
<span class="nc bnc" id="L609" title="All 4 branches missed."> if (config == null || config.getOnPermissionRequest() == null) {</span>
<span class="nc" id="L610"> return CompletableFuture.failedFuture(</span>
new IllegalArgumentException("An onPermissionRequest handler is required when resuming a session. "
+ "For example, to allow all permissions, use: "
+ "new ResumeSessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL)"));
}
<span class="nc" id="L615"> return ensureConnected().thenCompose(connection -> {</span>
<span class="nc" id="L616"> long totalNanos = System.nanoTime();</span>
// Register the session before the RPC call to avoid missing early events.
<span class="nc" id="L618"> long setupNanos = System.nanoTime();</span>
<span class="nc" id="L619"> var session = new CopilotSession(sessionId, connection.rpc);</span>
<span class="nc" id="L620"> session.setExecutor(executor);</span>
<span class="nc" id="L621"> SessionRequestBuilder.configureSession(session, config);</span>
<span class="nc" id="L622"> sessions.put(sessionId, session);</span>
<span class="nc" id="L623"> LoggingHelpers.logTiming(LOG, Level.FINE,</span>
"CopilotClient.resumeSession local setup complete. Elapsed={Elapsed}, SessionId=" + sessionId,
setupNanos);
// Extract transform callbacks from the system message config.
<span class="nc" id="L628"> var extracted = SessionRequestBuilder.extractTransformCallbacks(config.getSystemMessage());</span>
<span class="nc bnc" id="L629" title="All 2 branches missed."> if (extracted.transformCallbacks() != null) {</span>
<span class="nc" id="L630"> session.registerTransformCallbacks(extracted.transformCallbacks());</span>
}
<span class="nc" id="L633"> var request = SessionRequestBuilder.buildResumeRequest(sessionId, config);</span>
<span class="nc bnc" id="L634" title="All 2 branches missed."> if (extracted.wireSystemMessage() != config.getSystemMessage()) {</span>
<span class="nc" id="L635"> request.setSystemMessage(extracted.wireSystemMessage());</span>
}
// Empty mode: validate availableTools and set toolFilterPrecedence for resume
// path
<span class="nc bnc" id="L640" title="All 2 branches missed."> if (options.getMode() == CopilotClientMode.EMPTY) {</span>
<span class="nc bnc" id="L641" title="All 2 branches missed."> if (config.getAvailableTools() == null) {</span>
<span class="nc" id="L642"> throw new IllegalArgumentException(</span>
"CopilotClient is in Mode = EMPTY but the resume session config did not specify "
+ "availableTools. Empty mode requires every session to explicitly opt into "
+ "the tools it wants — e.g. setAvailableTools(new ToolSet().addBuiltIn(BuiltInTools.ISOLATED)).");
}
<span class="nc" id="L647"> request.setToolFilterPrecedence("excluded");</span>
<span class="nc bnc" id="L648" title="All 2 branches missed."> if (request.getMcpOAuthTokenStorage() == null) {</span>
<span class="nc" id="L649"> request.setMcpOAuthTokenStorage("in-memory");</span>
}
}
<span class="nc" id="L653"> long rpcNanos = System.nanoTime();</span>
<span class="nc" id="L654"> return connection.rpc.invoke("session.resume", request, ResumeSessionResponse.class)</span>
<span class="nc" id="L655"> .thenCompose(response -> {</span>
<span class="nc" id="L656"> LoggingHelpers.logTiming(LOG, Level.FINE,</span>
"CopilotClient.resumeSession session resume request completed. Elapsed={Elapsed}, SessionId="
+ sessionId,
rpcNanos);
<span class="nc" id="L660"> session.setWorkspacePath(response.workspacePath());</span>
<span class="nc" id="L661"> session.setCapabilities(response.capabilities());</span>
// If the server returned a different sessionId than what was requested,
// re-key.
<span class="nc" id="L664"> String returnedId = response.sessionId();</span>
<span class="nc bnc" id="L665" title="All 4 branches missed."> if (returnedId != null && !returnedId.equals(sessionId)) {</span>
<span class="nc" id="L666"> sessions.remove(sessionId);</span>
<span class="nc" id="L667"> session.setActiveSessionId(returnedId);</span>
<span class="nc" id="L668"> sessions.put(returnedId, session);</span>
}
<span class="nc" id="L671"> return updateSessionOptionsForMode(session, config.getSkipCustomInstructions().orElse(null),</span>
<span class="nc" id="L672"> config.getCustomAgentsLocalOnly().orElse(null),</span>
<span class="nc" id="L673"> config.getCoauthorEnabled().orElse(null),</span>
<span class="nc" id="L674"> config.getManageScheduleEnabled().orElse(null)).thenApply(v -> {</span>
<span class="nc" id="L675"> LoggingHelpers.logTiming(LOG, Level.FINE,</span>
"CopilotClient.resumeSession complete. Elapsed={Elapsed}, SessionId="
+ sessionId,
totalNanos);
<span class="nc" id="L679"> return session;</span>
});
<span class="nc" id="L681"> }).exceptionally(ex -> {</span>
<span class="nc" id="L682"> sessions.remove(sessionId);</span>
// Also remove the re-keyed entry if the server returned a different ID
<span class="nc" id="L684"> String activeId = session.getSessionId();</span>
<span class="nc bnc" id="L685" title="All 2 branches missed."> if (!sessionId.equals(activeId)) {</span>
<span class="nc" id="L686"> sessions.remove(activeId);</span>
}
<span class="nc" id="L688"> LoggingHelpers.logTiming(LOG, Level.WARNING, ex,</span>
"CopilotClient.resumeSession failed. Elapsed={Elapsed}, SessionId=" + sessionId,
totalNanos);
<span class="nc bnc" id="L691" title="All 2 branches missed."> throw ex instanceof RuntimeException re ? re : new RuntimeException(ex);</span>
});
});
}
/**
* Applies the post-create / post-resume {@code session.options.update} patch.
* <p>
* In {@link CopilotClientMode#EMPTY EMPTY} mode this defaults the four
* overridable feature flags to safe values (caller values from the config win);
* {@code installedPlugins=[]} is unconditional under empty mode so apps that
* need plugins must switch modes. In {@link CopilotClientMode#COPILOT_CLI
* COPILOT_CLI} mode only explicitly-set fields are forwarded.
*
* @param session
* the session to patch
* @param skipCustomInstructions
* caller-supplied value, or {@code null} if not set
* @param customAgentsLocalOnly
* caller-supplied value, or {@code null} if not set
* @param coauthorEnabled
* caller-supplied value, or {@code null} if not set
* @param manageScheduleEnabled
* caller-supplied value, or {@code null} if not set
* @return a future that completes when the patch has been applied
*/
CompletableFuture<Void> updateSessionOptionsForMode(CopilotSession session, Boolean skipCustomInstructions,
Boolean customAgentsLocalOnly, Boolean coauthorEnabled, Boolean manageScheduleEnabled) {
<span class="nc" id="L720"> Boolean patchSkip = null;</span>
<span class="nc" id="L721"> Boolean patchAgents = null;</span>
<span class="nc" id="L722"> Boolean patchCoauthor = null;</span>
<span class="nc" id="L723"> Boolean patchSchedule = null;</span>
<span class="nc" id="L724"> List<SessionInstalledPlugin> patchPlugins = null;</span>
<span class="nc" id="L725"> boolean hasAnyPatch = false;</span>
<span class="nc bnc" id="L727" title="All 2 branches missed."> if (options.getMode() == CopilotClientMode.EMPTY) {</span>
<span class="nc bnc" id="L728" title="All 2 branches missed."> patchSkip = skipCustomInstructions != null ? skipCustomInstructions : true;</span>
<span class="nc bnc" id="L729" title="All 2 branches missed."> patchAgents = customAgentsLocalOnly != null ? customAgentsLocalOnly : true;</span>
<span class="nc bnc" id="L730" title="All 2 branches missed."> patchCoauthor = coauthorEnabled != null ? coauthorEnabled : false;</span>
<span class="nc bnc" id="L731" title="All 2 branches missed."> patchSchedule = manageScheduleEnabled != null ? manageScheduleEnabled : false;</span>
<span class="nc" id="L732"> patchPlugins = List.of();</span>
<span class="nc" id="L733"> hasAnyPatch = true;</span>
} else {
<span class="nc bnc" id="L735" title="All 2 branches missed."> if (skipCustomInstructions != null) {</span>
<span class="nc" id="L736"> patchSkip = skipCustomInstructions;</span>
<span class="nc" id="L737"> hasAnyPatch = true;</span>
}
<span class="nc bnc" id="L739" title="All 2 branches missed."> if (customAgentsLocalOnly != null) {</span>
<span class="nc" id="L740"> patchAgents = customAgentsLocalOnly;</span>
<span class="nc" id="L741"> hasAnyPatch = true;</span>
}
<span class="nc bnc" id="L743" title="All 2 branches missed."> if (coauthorEnabled != null) {</span>
<span class="nc" id="L744"> patchCoauthor = coauthorEnabled;</span>
<span class="nc" id="L745"> hasAnyPatch = true;</span>
}
<span class="nc bnc" id="L747" title="All 2 branches missed."> if (manageScheduleEnabled != null) {</span>
<span class="nc" id="L748"> patchSchedule = manageScheduleEnabled;</span>
<span class="nc" id="L749"> hasAnyPatch = true;</span>
}
}
<span class="nc bnc" id="L753" title="All 2 branches missed."> if (!hasAnyPatch) {</span>
<span class="nc" id="L754"> return CompletableFuture.completedFuture(null);</span>
}
<span class="nc" id="L757"> var params = new SessionOptionsUpdateParams(null, // sessionId — set by SessionOptionsApi</span>
null, // model
null, // reasoningEffort
null, // clientName
null, // lspClientName
null, // integrationId
null, // featureFlags
null, // isExperimentalMode
null, // provider
null, // workingDirectory
null, // availableTools
null, // excludedTools
null, // toolFilterPrecedence
null, // enableScriptSafety
null, // shellInitProfile
null, // shellProcessFlags
null, // sandboxConfig
null, // logInteractiveShells
null, // envValueMode
null, // skillDirectories
null, // disabledSkills
null, // enableOnDemandInstructionDiscovery
patchPlugins, // installedPlugins
patchAgents, // customAgentsLocalOnly
patchSkip, // skipCustomInstructions
null, // disabledInstructionSources
patchCoauthor, // coauthorEnabled
null, // trajectoryFile
null, // enableStreaming
null, // copilotUrl
null, // askUserDisabled
null, // continueOnAutoMode
null, // runningInInteractiveMode
null, // enableReasoningSummaries
null, // agentContext
null, // eventsLogDirectory
null, // additionalContentExclusionPolicies
patchSchedule // manageScheduleEnabled
);
<span class="nc" id="L797"> return session.getRpc().options.update(params).<Void>thenCompose(result -> {</span>
<span class="nc" id="L798"> LOG.fine("session.options.update applied for session " + session.getSessionId());</span>
<span class="nc" id="L799"> return CompletableFuture.completedFuture(null);</span>
<span class="nc" id="L800"> }).exceptionally(ex -> {</span>
// The runtime session exists but the post-create options patch failed.
// Best-effort disconnect so we don't leak it (in empty mode it would
// otherwise stay alive with permissive defaults).
<span class="nc" id="L804"> LOG.log(Level.WARNING, "session.options.update failed for session " + session.getSessionId(), ex);</span>
<span class="nc" id="L805"> sessions.remove(session.getSessionId());</span>
try {
<span class="nc" id="L807"> session.close();</span>
<span class="nc" id="L808"> } catch (Exception closeEx) {</span>
// Swallow: original error is the one the caller needs.
<span class="nc" id="L810"> }</span>
<span class="nc bnc" id="L811" title="All 2 branches missed."> throw ex instanceof RuntimeException re ? re : new RuntimeException(ex);</span>
});
}
/**
* Gets the current connection state.
*
* @return the current connection state
* @see ConnectionState
*/
public ConnectionState getState() {
<span class="nc bnc" id="L822" title="All 2 branches missed."> if (connectionFuture == null)</span>
<span class="nc" id="L823"> return ConnectionState.DISCONNECTED;</span>
<span class="nc bnc" id="L824" title="All 2 branches missed."> if (connectionFuture.isCompletedExceptionally())</span>
<span class="nc" id="L825"> return ConnectionState.ERROR;</span>
<span class="nc bnc" id="L826" title="All 2 branches missed."> if (!connectionFuture.isDone())</span>
<span class="nc" id="L827"> return ConnectionState.CONNECTING;</span>
<span class="nc" id="L828"> return ConnectionState.CONNECTED;</span>
}
/**
* Returns the typed RPC client for server-level methods.
* <p>
* Provides strongly-typed access to all server-level API namespaces such as
* {@code models}, {@code tools}, {@code account}, and {@code mcp}.
* <p>
* Example usage:
*
* <pre>{@code
* client.start().get();
* var models = client.getRpc().models.list().get();
* }</pre>
*
* @return the server-level typed RPC client
* @throws IllegalStateException
* if the client is not connected; call {@link #start()} first
* @since 1.0.0
*/
public ServerRpc getRpc() {
<span class="nc" id="L850"> CompletableFuture<Connection> future = connectionFuture;</span>
<span class="nc bnc" id="L851" title="All 6 branches missed."> if (future == null || !future.isDone() || future.isCompletedExceptionally()) {</span>
<span class="nc" id="L852"> throw new IllegalStateException("Client not connected; call start() first");</span>
}
<span class="nc" id="L854"> return future.join().serverRpc();</span>
}
/**
* Pings the server to check connectivity.
* <p>
* This can be used to verify that the server is responsive and to check the
* protocol version.
*
* @param message
* an optional message to echo back
* @return a future that resolves with the ping response
* @see PingResponse
*/
public CompletableFuture<PingResponse> ping(String message) {
<span class="nc" id="L869"> return ensureConnected().thenCompose(connection -> connection.rpc.invoke("ping",</span>
<span class="nc bnc" id="L870" title="All 2 branches missed."> Map.of("message", message != null ? message : ""), PingResponse.class));</span>
}
/**
* Gets CLI status including version and protocol information.
*
* @return a future that resolves with the status response containing version
* and protocol version
* @see GetStatusResponse
*/
public CompletableFuture<GetStatusResponse> getStatus() {
<span class="nc" id="L881"> return ensureConnected()</span>
<span class="nc" id="L882"> .thenCompose(connection -> connection.rpc.invoke("status.get", Map.of(), GetStatusResponse.class));</span>
}
/**
* Gets current authentication status.
*
* @return a future that resolves with the authentication status
* @see GetAuthStatusResponse
*/
public CompletableFuture<GetAuthStatusResponse> getAuthStatus() {
<span class="nc" id="L892"> return ensureConnected().thenCompose(</span>
<span class="nc" id="L893"> connection -> connection.rpc.invoke("auth.getStatus", Map.of(), GetAuthStatusResponse.class));</span>
}
/**
* Lists available models with their metadata.
* <p>
* Results are cached after the first successful call to avoid rate limiting.
* The cache is cleared when the client disconnects.
* <p>
* If an {@code onListModels} handler was provided in
* {@link com.github.copilot.rpc.CopilotClientOptions}, it is called instead of
* querying the CLI server. This is useful in BYOK mode.
*
* @return a future that resolves with a list of available models
* @see ModelInfo
*/
public CompletableFuture<List<ModelInfo>> listModels() {
// Check cache first
<span class="nc" id="L911"> List<ModelInfo> cached = modelsCache;</span>
<span class="nc bnc" id="L912" title="All 2 branches missed."> if (cached != null) {</span>
<span class="nc" id="L913"> return CompletableFuture.completedFuture(new ArrayList<>(cached));</span>
}
// If a custom handler is configured, use it instead of querying the CLI server
<span class="nc" id="L917"> var onListModels = options.getOnListModels();</span>
<span class="nc bnc" id="L918" title="All 2 branches missed."> if (onListModels != null) {</span>
<span class="nc" id="L919"> synchronized (modelsCacheLock) {</span>
<span class="nc bnc" id="L920" title="All 2 branches missed."> if (modelsCache != null) {</span>
<span class="nc" id="L921"> return CompletableFuture.completedFuture(new ArrayList<>(modelsCache));</span>
}
<span class="nc" id="L923"> }</span>
<span class="nc" id="L924"> return onListModels.get().thenApply(models -> {</span>
<span class="nc" id="L925"> synchronized (modelsCacheLock) {</span>
<span class="nc" id="L926"> modelsCache = models;</span>
<span class="nc" id="L927"> }</span>
<span class="nc" id="L928"> return new ArrayList<>(models);</span>
});
}
<span class="nc" id="L932"> return ensureConnected().thenCompose(connection -> {</span>
// Double-check cache inside lock
<span class="nc" id="L934"> synchronized (modelsCacheLock) {</span>
<span class="nc bnc" id="L935" title="All 2 branches missed."> if (modelsCache != null) {</span>
<span class="nc" id="L936"> return CompletableFuture.completedFuture(new ArrayList<>(modelsCache));</span>
}
<span class="nc" id="L938"> }</span>
<span class="nc" id="L940"> return connection.rpc.invoke("models.list", Map.of(), GetModelsResponse.class).thenApply(response -> {</span>
<span class="nc" id="L941"> List<ModelInfo> models = response.getModels();</span>
<span class="nc" id="L942"> synchronized (modelsCacheLock) {</span>
<span class="nc" id="L943"> modelsCache = models;</span>
<span class="nc" id="L944"> }</span>
<span class="nc" id="L945"> return new ArrayList<>(models); // Return a copy to prevent cache mutation</span>
});
});
}
/**
* Gets the ID of the most recently used session.
* <p>
* This is useful for resuming the last conversation without needing to list all
* sessions.
*
* @return a future that resolves with the last session ID, or {@code null} if
* no sessions exist
* @see #resumeSession(String, com.github.copilot.rpc.ResumeSessionConfig)
*/
public CompletableFuture<String> getLastSessionId() {
<span class="nc" id="L961"> return ensureConnected().thenCompose(</span>
<span class="nc" id="L962"> connection -> connection.rpc.invoke("session.getLastId", Map.of(), GetLastSessionIdResponse.class)</span>
<span class="nc" id="L963"> .thenApply(GetLastSessionIdResponse::sessionId));</span>
}
/**
* Permanently deletes a session and all its data from disk, including
* conversation history, planning state, and artifacts.
* <p>
* Unlike {@link CopilotSession#close()}, which only releases in-memory
* resources and preserves session data for later resumption, this method is
* irreversible. The session cannot be resumed after deletion.
*
* @param sessionId
* the ID of the session to delete
* @return a future that completes when the session is deleted
* @throws RuntimeException
* if the deletion fails
*/
public CompletableFuture<Void> deleteSession(String sessionId) {
<span class="nc" id="L981"> return ensureConnected().thenCompose(connection -> connection.rpc</span>
<span class="nc" id="L982"> .invoke("session.delete", Map.of("sessionId", sessionId), DeleteSessionResponse.class)</span>
<span class="nc" id="L983"> .thenAccept(response -> {</span>
<span class="nc bnc" id="L984" title="All 2 branches missed."> if (!response.success()) {</span>
<span class="nc" id="L985"> throw new RuntimeException("Failed to delete session " + sessionId + ": " + response.error());</span>
}
<span class="nc" id="L987"> sessions.remove(sessionId);</span>
<span class="nc" id="L988"> }));</span>
}
/**
* Lists all available sessions.
* <p>
* Returns metadata about all sessions that can be resumed, including their IDs,
* start times, and summaries.
*
* @return a future that resolves with a list of session metadata
* @see SessionMetadata
* @see #resumeSession(String, com.github.copilot.rpc.ResumeSessionConfig)
*/