-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathCopilotSession.java.html
More file actions
2036 lines (1933 loc) · 117 KB
/
Copy pathCopilotSession.java.html
File metadata and controls
2036 lines (1933 loc) · 117 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>CopilotSession.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">CopilotSession.java</span></div><h1>CopilotSession.java</h1><pre class="source lang-java linenums">/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------------------------------------------*/
package com.github.copilot;
import java.io.Closeable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.copilot.generated.AssistantMessageEvent;
import com.github.copilot.generated.rpc.SessionCommandsHandlePendingCommandParams;
import com.github.copilot.generated.rpc.SessionLogParams;
import com.github.copilot.generated.rpc.SessionLogLevel;
import com.github.copilot.generated.rpc.ModelCapabilitiesOverride;
import com.github.copilot.generated.rpc.ModelCapabilitiesOverrideLimits;
import com.github.copilot.generated.rpc.ModelCapabilitiesOverrideSupports;
import com.github.copilot.generated.rpc.SessionModelSwitchToParams;
import com.github.copilot.generated.rpc.SessionPermissionsHandlePendingPermissionRequestParams;
import com.github.copilot.generated.rpc.SessionRpc;
import com.github.copilot.generated.rpc.SessionToolsHandlePendingToolCallParams;
import com.github.copilot.generated.rpc.SessionUiElicitationParams;
import com.github.copilot.generated.rpc.SessionUiHandlePendingElicitationParams;
import com.github.copilot.generated.rpc.UIElicitationResponse;
import com.github.copilot.generated.rpc.UIElicitationResponseAction;
import com.github.copilot.generated.rpc.UIElicitationSchema;
import com.github.copilot.generated.CapabilitiesChangedEvent;
import com.github.copilot.generated.CommandExecuteEvent;
import com.github.copilot.generated.ElicitationRequestedEvent;
import com.github.copilot.generated.ExternalToolRequestedEvent;
import com.github.copilot.generated.PermissionRequestedEvent;
import com.github.copilot.generated.SessionErrorEvent;
import com.github.copilot.generated.SessionEvent;
import com.github.copilot.generated.SessionIdleEvent;
import com.github.copilot.rpc.AgentInfo;
import com.github.copilot.rpc.AutoModeSwitchHandler;
import com.github.copilot.rpc.AutoModeSwitchInvocation;
import com.github.copilot.rpc.AutoModeSwitchRequest;
import com.github.copilot.rpc.AutoModeSwitchResponse;
import com.github.copilot.rpc.CommandContext;
import com.github.copilot.rpc.CommandDefinition;
import com.github.copilot.rpc.CommandHandler;
import com.github.copilot.rpc.ElicitationContext;
import com.github.copilot.rpc.ElicitationHandler;
import com.github.copilot.rpc.ElicitationParams;
import com.github.copilot.rpc.ElicitationResult;
import com.github.copilot.rpc.ElicitationResultAction;
import com.github.copilot.rpc.ExitPlanModeHandler;
import com.github.copilot.rpc.ExitPlanModeInvocation;
import com.github.copilot.rpc.ExitPlanModeRequest;
import com.github.copilot.rpc.ExitPlanModeResult;
import com.github.copilot.rpc.ElicitationSchema;
import com.github.copilot.rpc.GetMessagesResponse;
import com.github.copilot.rpc.HookInvocation;
import com.github.copilot.rpc.InputOptions;
import com.github.copilot.rpc.MessageOptions;
import com.github.copilot.rpc.PermissionHandler;
import com.github.copilot.rpc.PermissionInvocation;
import com.github.copilot.rpc.PermissionRequest;
import com.github.copilot.rpc.PermissionRequestResult;
import com.github.copilot.rpc.PermissionRequestResultKind;
import com.github.copilot.rpc.PostToolUseHookInput;
import com.github.copilot.rpc.PostToolUseFailureHookInput;
import com.github.copilot.rpc.PreMcpToolCallHookInput;
import com.github.copilot.rpc.PreToolUseHookInput;
import com.github.copilot.rpc.SendMessageRequest;
import com.github.copilot.rpc.SendMessageResponse;
import com.github.copilot.rpc.SessionCapabilities;
import com.github.copilot.rpc.SessionEndHookInput;
import com.github.copilot.rpc.SessionHooks;
import com.github.copilot.rpc.SessionStartHookInput;
import com.github.copilot.rpc.SessionUiApi;
import com.github.copilot.rpc.SessionUiCapabilities;
import com.github.copilot.rpc.ToolDefinition;
import com.github.copilot.rpc.ToolResultObject;
import com.github.copilot.rpc.UserInputHandler;
import com.github.copilot.rpc.UserInputInvocation;
import com.github.copilot.rpc.UserInputRequest;
import com.github.copilot.rpc.UserInputResponse;
import com.github.copilot.rpc.UserPromptSubmittedHookInput;
/**
* Represents a single conversation session with the Copilot CLI.
* <p>
* A session maintains conversation state, handles events, and manages tool
* execution. Sessions are created via {@link CopilotClient#createSession} or
* resumed via {@link CopilotClient#resumeSession}.
* <p>
* {@code CopilotSession} implements {@link AutoCloseable}. Use the
* try-with-resources pattern for automatic cleanup, or call {@link #close()}
* explicitly. Closing a session releases in-memory resources but preserves
* session data on disk — the conversation can be resumed later via
* {@link CopilotClient#resumeSession}. To permanently delete session data, use
* {@link CopilotClient#deleteSession}.
*
* <h2>Example Usage</h2>
*
* <pre>{@code
* // Create a session with a permission handler (required)
* var session = client
* .createSession(new SessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL).setModel("gpt-5"))
* .get();
*
* // Register type-safe event handlers
* session.on(AssistantMessageEvent.class, msg -> {
* System.out.println(msg.getData().content());
* });
* session.on(SessionIdleEvent.class, idle -> {
* System.out.println("Session is idle");
* });
*
* // Send messages
* session.sendAndWait(new MessageOptions().setPrompt("Hello!")).get();
*
* // Clean up
* session.close();
* }</pre>
*
* @see CopilotClient#createSession(com.github.copilot.rpc.SessionConfig)
* @see CopilotClient#resumeSession(String,
* com.github.copilot.rpc.ResumeSessionConfig)
* @see SessionEvent
* @since 1.0.0
*/
public final class CopilotSession implements AutoCloseable {
<span class="nc" id="L148"> private static final Logger LOG = Logger.getLogger(CopilotSession.class.getName());</span>
<span class="nc" id="L149"> private static final ObjectMapper MAPPER = JsonRpcClient.getObjectMapper();</span>
/**
* The current active session ID. Initialized to the pre-generated value and may
* be updated after session.create / session.resume if the server returns a
* different ID (e.g. when working against a v2 CLI that ignores the
* client-supplied sessionId).
*/
private volatile String sessionId;
private volatile String workspacePath;
<span class="nc" id="L159"> private volatile SessionCapabilities capabilities = new SessionCapabilities();</span>
private final SessionUiApi ui;
private final JsonRpcClient rpc;
private volatile SessionRpc sessionRpc;
<span class="nc" id="L163"> private final Set<Consumer<SessionEvent>> eventHandlers = ConcurrentHashMap.newKeySet();</span>
<span class="nc" id="L164"> private final Map<String, ToolDefinition> toolHandlers = new ConcurrentHashMap<>();</span>
<span class="nc" id="L165"> private final Map<String, CommandHandler> commandHandlers = new ConcurrentHashMap<>();</span>
<span class="nc" id="L166"> private final AtomicReference<PermissionHandler> permissionHandler = new AtomicReference<>();</span>
<span class="nc" id="L167"> private final AtomicReference<UserInputHandler> userInputHandler = new AtomicReference<>();</span>
<span class="nc" id="L168"> private final AtomicReference<ElicitationHandler> elicitationHandler = new AtomicReference<>();</span>
<span class="nc" id="L169"> private final AtomicReference<ExitPlanModeHandler> exitPlanModeHandler = new AtomicReference<>();</span>
<span class="nc" id="L170"> private final AtomicReference<AutoModeSwitchHandler> autoModeSwitchHandler = new AtomicReference<>();</span>
<span class="nc" id="L171"> private final AtomicReference<SessionHooks> hooksHandler = new AtomicReference<>();</span>
private volatile EventErrorHandler eventErrorHandler;
<span class="nc" id="L173"> private volatile EventErrorPolicy eventErrorPolicy = EventErrorPolicy.PROPAGATE_AND_LOG_ERRORS;</span>
private volatile Map<String, java.util.function.Function<String, CompletableFuture<String>>> transformCallbacks;
private final ScheduledExecutorService timeoutScheduler;
private volatile Executor executor;
/** Tracks whether this session instance has been terminated via close(). */
<span class="nc" id="L179"> private volatile boolean isTerminated = false;</span>
/**
* Creates a new session with the given ID and RPC client.
* <p>
* This constructor is package-private. Sessions should be created via
* {@link CopilotClient#createSession} or {@link CopilotClient#resumeSession}.
*
* @param sessionId
* the unique session identifier
* @param rpc
* the JSON-RPC client for communication
*/
CopilotSession(String sessionId, JsonRpcClient rpc) {
<span class="nc" id="L193"> this(sessionId, rpc, null);</span>
<span class="nc" id="L194"> }</span>
/**
* Creates a new session with the given ID, RPC client, and workspace path.
* <p>
* This constructor is package-private. Sessions should be created via
* {@link CopilotClient#createSession} or {@link CopilotClient#resumeSession}.
*
* @param sessionId
* the unique session identifier
* @param rpc
* the JSON-RPC client for communication
* @param workspacePath
* the workspace path if infinite sessions are enabled
*/
<span class="nc" id="L209"> CopilotSession(String sessionId, JsonRpcClient rpc, String workspacePath) {</span>
<span class="nc" id="L210"> this.sessionId = sessionId;</span>
<span class="nc" id="L211"> this.rpc = rpc;</span>
<span class="nc" id="L212"> this.workspacePath = workspacePath;</span>
<span class="nc" id="L213"> this.ui = new SessionUiApiImpl();</span>
<span class="nc" id="L214"> var executor = new ScheduledThreadPoolExecutor(1, r -> {</span>
<span class="nc" id="L215"> var t = new Thread(r, "sendAndWait-timeout");</span>
<span class="nc" id="L216"> t.setDaemon(true);</span>
<span class="nc" id="L217"> return t;</span>
});
<span class="nc" id="L219"> executor.setRemoveOnCancelPolicy(true);</span>
<span class="nc" id="L220"> this.timeoutScheduler = executor;</span>
<span class="nc" id="L221"> }</span>
/**
* Sets the executor for internal async operations. Package-private; called by
* CopilotClient after construction.
*/
void setExecutor(Executor executor) {
<span class="nc" id="L228"> this.executor = executor;</span>
<span class="nc" id="L229"> }</span>
/**
* Gets the unique identifier for this session.
*
* @return the session ID
*/
public String getSessionId() {
<span class="nc" id="L237"> return sessionId;</span>
}
/**
* Updates the active session ID. Package-private; called by CopilotClient if
* the server returns a different session ID than the pre-generated one (e.g.
* when a v2 CLI ignores the client-supplied sessionId).
*
* @param sessionId
* the server-confirmed session ID
*/
void setActiveSessionId(String sessionId) {
<span class="nc" id="L249"> this.sessionId = sessionId;</span>
<span class="nc" id="L250"> this.sessionRpc = null; // Reset so getRpc() lazily re-creates with the new sessionId</span>
<span class="nc" id="L251"> }</span>
/**
* Gets the path to the session workspace directory when infinite sessions are
* enabled.
* <p>
* The workspace directory contains checkpoints/, plan.md, and files/
* subdirectories.
*
* @return the workspace path, or {@code null} if infinite sessions are disabled
*/
public String getWorkspacePath() {
<span class="nc" id="L263"> return workspacePath;</span>
}
/**
* Sets the workspace path. Package-private; called by CopilotClient after
* session.create or session.resume RPC response.
*
* @param workspacePath
* the workspace path
*/
void setWorkspacePath(String workspacePath) {
<span class="nc" id="L274"> this.workspacePath = workspacePath;</span>
<span class="nc" id="L275"> }</span>
/**
* Gets the capabilities reported by the host for this session.
* <p>
* Capabilities are populated from the session create/resume response and
* updated in real time via {@code capabilities.changed} events.
*
* @return the session capabilities (never {@code null})
*/
public SessionCapabilities getCapabilities() {
<span class="nc" id="L286"> return capabilities;</span>
}
/**
* Gets the UI API for eliciting information from the user during this session.
* <p>
* All methods on this API throw {@link IllegalStateException} if the host does
* not report elicitation support via {@link #getCapabilities()}.
*
* @return the UI API
*/
public SessionUiApi getUi() {
<span class="nc" id="L298"> return ui;</span>
}
/**
* Returns the typed RPC client for this session.
* <p>
* Provides strongly-typed access to all session-level API namespaces. The
* {@code sessionId} is injected automatically into every call.
* <p>
* Example usage:
*
* <pre>{@code
* var agents = session.getRpc().agent.list().get();
* }</pre>
*
* @return the session-scoped typed RPC client (never {@code null})
* @throws IllegalStateException
* if the session is not connected
* @since 1.0.0
*/
public SessionRpc getRpc() {
<span class="nc bnc" id="L319" title="All 2 branches missed."> if (rpc == null) {</span>
<span class="nc" id="L320"> throw new IllegalStateException("Session is not connected — RPC client is unavailable");</span>
}
<span class="nc" id="L322"> SessionRpc current = sessionRpc;</span>
<span class="nc bnc" id="L323" title="All 2 branches missed."> if (current == null) {</span>
<span class="nc" id="L324"> synchronized (this) {</span>
<span class="nc" id="L325"> current = sessionRpc;</span>
<span class="nc bnc" id="L326" title="All 2 branches missed."> if (current == null) {</span>
<span class="nc" id="L327"> sessionRpc = current = new SessionRpc(rpc::invoke, sessionId);</span>
}
<span class="nc" id="L329"> }</span>
}
<span class="nc" id="L331"> return current;</span>
}
/**
* Sets a custom error handler for exceptions thrown by event handlers.
* <p>
* When an event handler registered via {@link #on(Consumer)} or
* {@link #on(Class, Consumer)} throws an exception during event dispatch, the
* error handler is invoked with the event and exception. The error is always
* logged at {@link Level#WARNING} regardless of whether a custom handler is
* set.
*
* <p>
* Whether dispatch continues or stops after an error is controlled by the
* {@link EventErrorPolicy} set via {@link #setEventErrorPolicy}. The error
* handler is always invoked regardless of the policy.
*
* <p>
* If the error handler itself throws an exception, that exception is caught and
* logged at {@link Level#SEVERE}, and dispatch is stopped regardless of the
* configured policy.
*
* <p>
* <b>Example:</b>
*
* <pre>{@code
* session.setEventErrorHandler((event, exception) -> {
* metrics.increment("handler.errors");
* logger.error("Handler failed on {}: {}", event.getType(), exception.getMessage());
* });
* }</pre>
*
* @param handler
* the error handler, or {@code null} to use only the default logging
* behavior
* @throws IllegalStateException
* if this session has been terminated
* @see EventErrorHandler
* @see #setEventErrorPolicy(EventErrorPolicy)
* @since 1.0.8
*/
public void setEventErrorHandler(EventErrorHandler handler) {
<span class="nc" id="L373"> ensureNotTerminated();</span>
<span class="nc" id="L374"> this.eventErrorHandler = handler;</span>
<span class="nc" id="L375"> }</span>
/**
* Sets the error propagation policy for event dispatch.
* <p>
* Controls whether remaining event listeners continue to execute when a
* preceding listener throws an exception. Errors are always logged at
* {@link Level#WARNING} regardless of the policy.
*
* <ul>
* <li>{@link EventErrorPolicy#PROPAGATE_AND_LOG_ERRORS} (default) — log the
* error and stop dispatch after the first error</li>
* <li>{@link EventErrorPolicy#SUPPRESS_AND_LOG_ERRORS} — log the error and
* continue dispatching to all remaining listeners</li>
* </ul>
*
* <p>
* The configured {@link EventErrorHandler} (if any) is always invoked
* regardless of the policy.
*
* <p>
* <b>Example:</b>
*
* <pre>{@code
* // Opt-in to suppress errors (continue dispatching despite errors)
* session.setEventErrorPolicy(EventErrorPolicy.SUPPRESS_AND_LOG_ERRORS);
* session.setEventErrorHandler((event, ex) -> logger.error("Handler failed, continuing: {}", ex.getMessage(), ex));
* }</pre>
*
* @param policy
* the error policy (default is
* {@link EventErrorPolicy#PROPAGATE_AND_LOG_ERRORS})
* @throws IllegalStateException
* if this session has been terminated
* @see EventErrorPolicy
* @see #setEventErrorHandler(EventErrorHandler)
* @since 1.0.8
*/
public void setEventErrorPolicy(EventErrorPolicy policy) {
<span class="nc" id="L414"> ensureNotTerminated();</span>
<span class="nc bnc" id="L415" title="All 2 branches missed."> if (policy == null) {</span>
<span class="nc" id="L416"> throw new NullPointerException("policy must not be null");</span>
}
<span class="nc" id="L418"> this.eventErrorPolicy = policy;</span>
<span class="nc" id="L419"> }</span>
/**
* Sends a simple text message to the Copilot session.
* <p>
* This is a convenience method equivalent to
* {@code send(new MessageOptions().setPrompt(prompt))}.
*
* @param prompt
* the message text to send
* @return a future that resolves with the message ID assigned by the server
* @throws IllegalStateException
* if this session has been terminated
* @see #send(MessageOptions)
*/
public CompletableFuture<String> send(String prompt) {
<span class="nc" id="L435"> ensureNotTerminated();</span>
<span class="nc" id="L436"> return send(new MessageOptions().setPrompt(prompt));</span>
}
/**
* Sends a simple text message and waits until the session becomes idle.
* <p>
* This is a convenience method equivalent to
* {@code sendAndWait(new MessageOptions().setPrompt(prompt))}.
*
* @param prompt
* the message text to send
* @return a future that resolves with the final assistant message event, or
* {@code null} if no assistant message was received
* @throws IllegalStateException
* if this session has been terminated
* @see #sendAndWait(MessageOptions)
*/
public CompletableFuture<AssistantMessageEvent> sendAndWait(String prompt) {
<span class="nc" id="L454"> ensureNotTerminated();</span>
<span class="nc" id="L455"> return sendAndWait(new MessageOptions().setPrompt(prompt));</span>
}
/**
* Sends a message to the Copilot session.
* <p>
* This method sends a message asynchronously and returns immediately. Use
* {@link #sendAndWait(MessageOptions)} to wait for the response.
*
* @param options
* the message options containing the prompt and attachments
* @return a future that resolves with the message ID assigned by the server
* @throws IllegalStateException
* if this session has been terminated
* @see #sendAndWait(MessageOptions)
* @see #send(String)
*/
public CompletableFuture<String> send(MessageOptions options) {
<span class="nc" id="L473"> ensureNotTerminated();</span>
<span class="nc" id="L474"> var request = new SendMessageRequest();</span>
<span class="nc" id="L475"> request.setSessionId(sessionId);</span>
<span class="nc" id="L476"> request.setPrompt(options.getPrompt());</span>
<span class="nc" id="L477"> request.setAttachments(options.getAttachments());</span>
<span class="nc" id="L478"> request.setMode(options.getMode());</span>
<span class="nc" id="L479"> request.setAgentMode(options.getAgentMode());</span>
<span class="nc" id="L480"> request.setRequestHeaders(options.getRequestHeaders());</span>
<span class="nc" id="L481"> request.setDisplayPrompt(options.getDisplayPrompt());</span>
<span class="nc" id="L483"> return rpc.invoke("session.send", request, SendMessageResponse.class).thenApply(SendMessageResponse::messageId);</span>
}
/**
* Sends a message and waits until the session becomes idle.
* <p>
* This method blocks until the assistant finishes processing the message or
* until the timeout expires. It's suitable for simple request/response
* interactions where you don't need to process streaming events.
* <p>
* The returned future can be cancelled via
* {@link java.util.concurrent.Future#cancel(boolean)}. If cancelled externally,
* the future completes with {@link java.util.concurrent.CancellationException}.
* If the timeout expires first, the future completes exceptionally with a
* {@link TimeoutException}.
*
* @param options
* the message options containing the prompt and attachments
* @param timeoutMs
* timeout in milliseconds (0 or negative for no timeout)
* @return a future that resolves with the final assistant message event, or
* {@code null} if no assistant message was received. The future
* completes exceptionally with a TimeoutException if the timeout
* expires, or with CancellationException if cancelled externally.
* @throws IllegalStateException
* if this session has been terminated
* @see #sendAndWait(MessageOptions)
* @see #send(MessageOptions)
*/
public CompletableFuture<AssistantMessageEvent> sendAndWait(MessageOptions options, long timeoutMs) {
<span class="nc" id="L513"> ensureNotTerminated();</span>
<span class="nc" id="L514"> long totalNanos = System.nanoTime();</span>
<span class="nc" id="L515"> var future = new CompletableFuture<AssistantMessageEvent>();</span>
<span class="nc" id="L516"> var lastAssistantMessage = new AtomicReference<AssistantMessageEvent>();</span>
<span class="nc" id="L517"> var firstAssistantMessageLogged = new java.util.concurrent.atomic.AtomicBoolean(false);</span>
<span class="nc" id="L519"> Consumer<SessionEvent> handler = evt -> {</span>
<span class="nc bnc" id="L520" title="All 2 branches missed."> if (evt instanceof AssistantMessageEvent msg) {</span>
<span class="nc" id="L521"> lastAssistantMessage.set(msg);</span>
<span class="nc bnc" id="L522" title="All 2 branches missed."> if (firstAssistantMessageLogged.compareAndSet(false, true)) {</span>
<span class="nc" id="L523"> LoggingHelpers.logTiming(LOG, Level.FINE,</span>
"CopilotSession.sendAndWait first assistant message. Elapsed={Elapsed}, SessionId="
+ sessionId,
totalNanos);
}
<span class="nc bnc" id="L528" title="All 2 branches missed."> } else if (evt instanceof SessionIdleEvent) {</span>
<span class="nc" id="L529"> LoggingHelpers.logTiming(LOG, Level.FINE,</span>
"CopilotSession.sendAndWait idle received. Elapsed={Elapsed}, SessionId=" + sessionId,
totalNanos);
<span class="nc" id="L532"> future.complete(lastAssistantMessage.get());</span>
<span class="nc bnc" id="L533" title="All 2 branches missed."> } else if (evt instanceof SessionErrorEvent errorEvent) {</span>
<span class="nc bnc" id="L534" title="All 2 branches missed."> String message = errorEvent.getData() != null ? errorEvent.getData().message() : "session error";</span>
<span class="nc" id="L535"> future.completeExceptionally(new RuntimeException("Session error: " + message));</span>
}
<span class="nc" id="L537"> };</span>
<span class="nc" id="L539"> Closeable subscription = on(handler);</span>
<span class="nc" id="L541"> send(options).exceptionally(ex -> {</span>
try {
<span class="nc" id="L543"> subscription.close();</span>
<span class="nc" id="L544"> } catch (Exception e) {</span>
<span class="nc" id="L545"> LOG.log(Level.SEVERE, "Error closing subscription", e);</span>
<span class="nc" id="L546"> }</span>
<span class="nc" id="L547"> future.completeExceptionally(ex);</span>
<span class="nc" id="L548"> return null;</span>
});
<span class="nc" id="L551"> var result = new CompletableFuture<AssistantMessageEvent>();</span>
// Schedule timeout on the shared session-level scheduler.
// Per Javadoc, timeoutMs <= 0 means "no timeout".
<span class="nc" id="L555"> ScheduledFuture<?> timeoutTask = null;</span>
<span class="nc bnc" id="L556" title="All 2 branches missed."> if (timeoutMs > 0) {</span>
try {
<span class="nc" id="L558"> timeoutTask = timeoutScheduler.schedule(() -> {</span>
<span class="nc bnc" id="L559" title="All 2 branches missed."> if (!future.isDone()) {</span>
<span class="nc" id="L560"> future.completeExceptionally(</span>
new TimeoutException("sendAndWait timed out after " + timeoutMs + "ms"));
}
<span class="nc" id="L563"> }, timeoutMs, TimeUnit.MILLISECONDS);</span>
<span class="nc" id="L564"> } catch (RejectedExecutionException e) {</span>
try {
<span class="nc" id="L566"> subscription.close();</span>
<span class="nc" id="L567"> } catch (IOException closeEx) {</span>
<span class="nc" id="L568"> e.addSuppressed(closeEx);</span>
<span class="nc" id="L569"> }</span>
<span class="nc" id="L570"> result.completeExceptionally(e);</span>
<span class="nc" id="L571"> return result;</span>
<span class="nc" id="L572"> }</span>
}
// When inner future completes, run cleanup and propagate to result.
// Use whenCompleteAsync so that result.complete(r) is not called
// synchronously on the event-dispatch thread while dispatchEvent() is
// still iterating over handlers. Without async dispatch, a caller that
// registered its own session.on() listener before calling sendAndWait()
// could see its listener invoked *after* result.get() returned, because
// sendAndWait's internal handler would complete the future mid-loop. By
// submitting the completion to timeoutScheduler we allow the current
// dispatch loop to finish calling all other handlers first.
<span class="nc" id="L584"> final ScheduledFuture<?> taskToCancel = timeoutTask;</span>
<span class="nc" id="L585"> future.whenCompleteAsync((r, ex) -> {</span>
try {
<span class="nc" id="L587"> subscription.close();</span>
<span class="nc" id="L588"> } catch (IOException e) {</span>
<span class="nc" id="L589"> LOG.log(Level.SEVERE, "Error closing subscription", e);</span>
<span class="nc" id="L590"> }</span>
<span class="nc bnc" id="L591" title="All 2 branches missed."> if (taskToCancel != null) {</span>
<span class="nc" id="L592"> taskToCancel.cancel(false);</span>
}
<span class="nc bnc" id="L594" title="All 2 branches missed."> if (!result.isDone()) {</span>
<span class="nc bnc" id="L595" title="All 2 branches missed."> if (ex != null) {</span>
<span class="nc bnc" id="L596" title="All 2 branches missed."> if (ex instanceof TimeoutException) {</span>
<span class="nc" id="L597"> LoggingHelpers.logTiming(LOG, Level.WARNING, ex,</span>
"CopilotSession.sendAndWait failed. Elapsed={Elapsed}, SessionId=" + sessionId
+ ", CompletedBy=timeout",
totalNanos);
<span class="nc bnc" id="L601" title="All 2 branches missed."> } else if (!(ex instanceof java.util.concurrent.CancellationException)) {</span>
<span class="nc" id="L602"> LoggingHelpers.logTiming(LOG, Level.WARNING, ex,</span>
"CopilotSession.sendAndWait failed. Elapsed={Elapsed}, SessionId=" + sessionId
+ ", CompletedBy=error",
totalNanos);
}
<span class="nc" id="L607"> result.completeExceptionally(ex);</span>
} else {
<span class="nc bnc" id="L609" title="All 2 branches missed."> LoggingHelpers.logTiming(</span>
LOG, Level.FINE, "CopilotSession.sendAndWait complete. Elapsed={Elapsed}, SessionId="
+ sessionId + ", CompletedBy=idle, AssistantMessageReceived=" + (r != null),
totalNanos);
<span class="nc" id="L613"> result.complete(r);</span>
}
}
<span class="nc" id="L616"> }, timeoutScheduler);</span>
// When result is cancelled externally, cancel inner future to trigger cleanup
<span class="nc" id="L619"> result.whenComplete((v, ex) -> {</span>
<span class="nc bnc" id="L620" title="All 4 branches missed."> if (result.isCancelled() && !future.isDone()) {</span>
<span class="nc" id="L621"> future.cancel(true);</span>
}
<span class="nc" id="L623"> });</span>
<span class="nc" id="L625"> return result;</span>
}
/**
* Sends a message and waits until the session becomes idle with default 60
* second timeout.
*
* @param options
* the message options containing the prompt and attachments
* @return a future that resolves with the final assistant message event, or
* {@code null} if no assistant message was received
* @throws IllegalStateException
* if this session has been terminated
* @see #sendAndWait(MessageOptions, long)
*/
public CompletableFuture<AssistantMessageEvent> sendAndWait(MessageOptions options) {
<span class="nc" id="L641"> ensureNotTerminated();</span>
<span class="nc" id="L642"> return sendAndWait(options, 60000);</span>
}
/**
* Registers a callback for all session events.
* <p>
* The handler will be invoked for every event in this session, including
* assistant messages, tool calls, and session state changes. For type-safe
* handling of specific event types, prefer {@link #on(Class, Consumer)}
* instead.
*
* <p>
* <b>Exception handling:</b> If a handler throws an exception, the error is
* routed to the configured {@link EventErrorHandler} (if set). Whether
* remaining handlers execute depends on the configured
* {@link EventErrorPolicy}.
*
* <p>
* <b>Example:</b>
*
* <pre>{@code
* // Collect all events
* var events = new ArrayList<SessionEvent>();
* session.on(events::add);
* }</pre>
*
* @param handler
* a callback to be invoked when a session event occurs
* @return a Closeable that, when closed, unsubscribes the handler
* @throws IllegalStateException
* if this session has been terminated
* @see #on(Class, Consumer)
* @see SessionEvent
* @see #setEventErrorPolicy(EventErrorPolicy)
*/
public Closeable on(Consumer<SessionEvent> handler) {
<span class="nc" id="L678"> ensureNotTerminated();</span>
<span class="nc" id="L679"> eventHandlers.add(handler);</span>
<span class="nc" id="L680"> return () -> eventHandlers.remove(handler);</span>
}
/**
* Registers an event handler for a specific event type.
* <p>
* This provides a type-safe way to handle specific events without needing
* {@code instanceof} checks. The handler will only be called for events
* matching the specified type.
*
* <p>
* <b>Exception handling:</b> If a handler throws an exception, the error is
* routed to the configured {@link EventErrorHandler} (if set). Whether
* remaining handlers execute depends on the configured
* {@link EventErrorPolicy}.
*
* <p>
* <b>Example Usage</b>
* </p>
*
* <pre>{@code
* // Handle assistant messages
* session.on(AssistantMessageEvent.class, msg -> {
* System.out.println(msg.getData().content());
* });
*
* // Handle session idle
* session.on(SessionIdleEvent.class, idle -> {
* done.complete(null);
* });
*
* // Handle streaming deltas
* session.on(AssistantMessageDeltaEvent.class, delta -> {
* System.out.print(delta.getData().deltaContent());
* });
* }</pre>
*
* @param <T>
* the event type
* @param eventType
* the class of the event to listen for
* @param handler
* a callback invoked when events of this type occur
* @return a Closeable that unsubscribes the handler when closed
* @throws IllegalStateException
* if this session has been terminated
* @see #on(Consumer)
* @see SessionEvent
*/
public <T extends SessionEvent> Closeable on(Class<T> eventType, Consumer<T> handler) {
<span class="nc" id="L730"> ensureNotTerminated();</span>
<span class="nc" id="L731"> Consumer<SessionEvent> wrapper = event -> {</span>
<span class="nc bnc" id="L732" title="All 2 branches missed."> if (eventType.isInstance(event)) {</span>
<span class="nc" id="L733"> handler.accept(eventType.cast(event));</span>
}
<span class="nc" id="L735"> };</span>
<span class="nc" id="L736"> eventHandlers.add(wrapper);</span>
<span class="nc" id="L737"> return () -> eventHandlers.remove(wrapper);</span>
}
/**
* Dispatches an event to all registered handlers.
* <p>
* This is called internally when events are received from the server. Each
* handler is invoked in its own try/catch block. Errors are always logged at
* {@link Level#WARNING}. Whether dispatch continues after a handler error
* depends on the configured {@link EventErrorPolicy}:
* <ul>
* <li>{@link EventErrorPolicy#PROPAGATE_AND_LOG_ERRORS} (default) — dispatch
* stops after the first error</li>
* <li>{@link EventErrorPolicy#SUPPRESS_AND_LOG_ERRORS} — remaining handlers
* still execute</li>
* </ul>
* <p>
* The configured {@link EventErrorHandler} is always invoked (if set),
* regardless of the policy. If the error handler itself throws, dispatch stops
* regardless of policy and the error is logged at {@link Level#SEVERE}.
*
* @param event
* the event to dispatch
* @see #setEventErrorHandler(EventErrorHandler)
* @see #setEventErrorPolicy(EventErrorPolicy)
*/
void dispatchEvent(SessionEvent event) {
// Handle broadcast request events (protocol v3) before dispatching to user
// handlers. These are fire-and-forget: the response is sent asynchronously.
<span class="nc" id="L766"> handleBroadcastEventAsync(event);</span>
<span class="nc bnc" id="L768" title="All 2 branches missed."> for (Consumer<SessionEvent> handler : eventHandlers) {</span>
try {
<span class="nc" id="L770"> handler.accept(event);</span>
<span class="nc" id="L771"> } catch (Exception e) {</span>
<span class="nc" id="L772"> LOG.log(Level.WARNING, "Error in event handler", e);</span>
<span class="nc" id="L773"> EventErrorHandler errorHandler = this.eventErrorHandler;</span>
<span class="nc bnc" id="L774" title="All 2 branches missed."> if (errorHandler != null) {</span>
try {
<span class="nc" id="L776"> errorHandler.handleError(event, e);</span>
<span class="nc" id="L777"> } catch (Exception errorHandlerException) {</span>
<span class="nc" id="L778"> LOG.log(Level.SEVERE, "Error in event error handler", errorHandlerException);</span>
<span class="nc" id="L779"> break; // error handler itself failed — stop regardless of policy</span>
<span class="nc" id="L780"> }</span>
}
<span class="nc bnc" id="L782" title="All 2 branches missed."> if (eventErrorPolicy == EventErrorPolicy.PROPAGATE_AND_LOG_ERRORS) {</span>
<span class="nc" id="L783"> break;</span>
}
<span class="nc" id="L785"> }</span>
<span class="nc" id="L786"> }</span>
<span class="nc" id="L787"> }</span>
/**
* Handles broadcast request events by executing local handlers and responding
* via RPC (protocol v3).
* <p>
* Fire-and-forget: the response is sent asynchronously.
*
* @param event
* the event to handle
*/
private void handleBroadcastEventAsync(SessionEvent event) {
<span class="nc bnc" id="L799" title="All 2 branches missed."> if (event instanceof ExternalToolRequestedEvent toolEvent) {</span>
<span class="nc" id="L800"> var data = toolEvent.getData();</span>
<span class="nc bnc" id="L801" title="All 6 branches missed."> if (data == null || data.requestId() == null || data.toolName() == null) {</span>
<span class="nc" id="L802"> return;</span>
}
<span class="nc" id="L804"> ToolDefinition tool = getTool(data.toolName());</span>
<span class="nc bnc" id="L805" title="All 2 branches missed."> if (tool == null) {</span>
<span class="nc" id="L806"> return; // This client doesn't handle this tool; another client will</span>
}
<span class="nc" id="L808"> executeToolAndRespondAsync(data.requestId(), data.toolName(), data.toolCallId(), data.arguments(), tool);</span>
<span class="nc bnc" id="L810" title="All 2 branches missed."> } else if (event instanceof PermissionRequestedEvent permEvent) {</span>
<span class="nc" id="L811"> var data = permEvent.getData();</span>
<span class="nc bnc" id="L812" title="All 6 branches missed."> if (data == null || data.requestId() == null || data.permissionRequest() == null) {</span>
<span class="nc" id="L813"> return;</span>
}
<span class="nc bnc" id="L815" title="All 2 branches missed."> if (Boolean.TRUE.equals(data.resolvedByHook())) {</span>
<span class="nc" id="L816"> return; // Already resolved by a permissionRequest hook; no client action needed.</span>
}
<span class="nc" id="L818"> PermissionHandler handler = permissionHandler.get();</span>
<span class="nc bnc" id="L819" title="All 2 branches missed."> if (handler == null) {</span>
<span class="nc" id="L820"> return; // This client doesn't handle permissions; another client will</span>
}
<span class="nc" id="L822"> executePermissionAndRespondAsync(data.requestId(),</span>
<span class="nc" id="L823"> MAPPER.convertValue(data.permissionRequest(), PermissionRequest.class), handler);</span>
<span class="nc bnc" id="L824" title="All 2 branches missed."> } else if (event instanceof CommandExecuteEvent cmdEvent) {</span>
<span class="nc" id="L825"> var data = cmdEvent.getData();</span>
<span class="nc bnc" id="L826" title="All 6 branches missed."> if (data == null || data.requestId() == null || data.commandName() == null) {</span>
<span class="nc" id="L827"> return;</span>
}
<span class="nc" id="L829"> executeCommandAndRespondAsync(data.requestId(), data.commandName(), data.command(), data.args());</span>
<span class="nc bnc" id="L830" title="All 2 branches missed."> } else if (event instanceof ElicitationRequestedEvent elicitEvent) {</span>
<span class="nc" id="L831"> var data = elicitEvent.getData();</span>
<span class="nc bnc" id="L832" title="All 4 branches missed."> if (data == null || data.requestId() == null) {</span>
<span class="nc" id="L833"> return;</span>
}
<span class="nc" id="L835"> ElicitationHandler handler = elicitationHandler.get();</span>
<span class="nc bnc" id="L836" title="All 2 branches missed."> if (handler != null) {</span>
<span class="nc" id="L837"> ElicitationSchema schema = null;</span>
<span class="nc bnc" id="L838" title="All 2 branches missed."> if (data.requestedSchema() != null) {</span>
<span class="nc" id="L839"> schema = new ElicitationSchema().setType(data.requestedSchema().type())</span>
<span class="nc" id="L840"> .setProperties(data.requestedSchema().properties())</span>
<span class="nc" id="L841"> .setRequired(data.requestedSchema().required());</span>
}
<span class="nc" id="L843"> var context = new ElicitationContext().setSessionId(sessionId).setMessage(data.message())</span>
<span class="nc bnc" id="L844" title="All 2 branches missed."> .setRequestedSchema(schema).setMode(data.mode() != null ? data.mode().getValue() : null)</span>
<span class="nc" id="L845"> .setElicitationSource(data.elicitationSource()).setUrl(data.url());</span>
<span class="nc" id="L846"> handleElicitationRequestAsync(context, data.requestId());</span>
}
<span class="nc bnc" id="L848" title="All 2 branches missed."> } else if (event instanceof CapabilitiesChangedEvent capEvent) {</span>
<span class="nc" id="L849"> var data = capEvent.getData();</span>
<span class="nc bnc" id="L850" title="All 2 branches missed."> if (data != null) {</span>
<span class="nc" id="L851"> var newCapabilities = new SessionCapabilities();</span>
<span class="nc bnc" id="L852" title="All 2 branches missed."> if (data.ui() != null) {</span>
<span class="nc" id="L853"> newCapabilities.setUi(new SessionUiCapabilities().setElicitation(data.ui().elicitation()));</span>
} else {
<span class="nc" id="L855"> newCapabilities.setUi(capabilities.getUi());</span>
}
<span class="nc" id="L857"> capabilities = newCapabilities;</span>
}
}
<span class="nc" id="L860"> }</span>
/**
* Executes a tool handler and sends the result back via
* {@code session.tools.handlePendingToolCall}.
*/
private void executeToolAndRespondAsync(String requestId, String toolName, String toolCallId, Object arguments,
ToolDefinition tool) {
<span class="nc" id="L868"> Runnable task = () -> {</span>
try {
<span class="nc bnc" id="L870" title="All 2 branches missed."> JsonNode argumentsNode = arguments instanceof JsonNode jn</span>
<span class="nc" id="L871"> ? jn</span>
<span class="nc bnc" id="L872" title="All 2 branches missed."> : (arguments != null ? MAPPER.valueToTree(arguments) : null);</span>
<span class="nc" id="L873"> var invocation = new com.github.copilot.rpc.ToolInvocation().setSessionId(sessionId)</span>
<span class="nc" id="L874"> .setToolCallId(toolCallId).setToolName(toolName).setArguments(argumentsNode);</span>
<span class="nc" id="L876"> tool.handler().invoke(invocation).thenAccept(result -> {</span>
try {
ToolResultObject toolResult;
<span class="nc bnc" id="L879" title="All 2 branches missed."> if (result instanceof ToolResultObject tr) {</span>
<span class="nc" id="L880"> toolResult = tr;</span>
} else {
toolResult = ToolResultObject
<span class="nc bnc" id="L883" title="All 2 branches missed."> .success(result instanceof String s ? s : MAPPER.writeValueAsString(result));</span>
}
<span class="nc" id="L885"> getRpc().tools.handlePendingToolCall(</span>
new SessionToolsHandlePendingToolCallParams(sessionId, requestId, toolResult, null));
<span class="nc" id="L887"> } catch (Exception e) {</span>
<span class="nc" id="L888"> LOG.log(Level.WARNING, "Error sending tool result for requestId=" + requestId, e);</span>
<span class="nc" id="L889"> }</span>
<span class="nc" id="L890"> }).exceptionally(ex -> {</span>
try {
<span class="nc" id="L892"> getRpc().tools.handlePendingToolCall(new SessionToolsHandlePendingToolCallParams(sessionId,</span>
<span class="nc bnc" id="L893" title="All 2 branches missed."> requestId, null, ex.getMessage() != null ? ex.getMessage() : ex.toString()));</span>
<span class="nc" id="L894"> } catch (Exception e) {</span>
<span class="nc" id="L895"> LOG.log(Level.WARNING, "Error sending tool error for requestId=" + requestId, e);</span>
<span class="nc" id="L896"> }</span>
<span class="nc" id="L897"> return null;</span>
});
<span class="nc" id="L899"> } catch (Exception e) {</span>
<span class="nc" id="L900"> LOG.log(Level.WARNING, "Error executing tool for requestId=" + requestId, e);</span>
try {
<span class="nc" id="L902"> getRpc().tools.handlePendingToolCall(new SessionToolsHandlePendingToolCallParams(sessionId,</span>
<span class="nc bnc" id="L903" title="All 2 branches missed."> requestId, null, e.getMessage() != null ? e.getMessage() : e.toString()));</span>
<span class="nc" id="L904"> } catch (Exception sendEx) {</span>
<span class="nc" id="L905"> LOG.log(Level.WARNING, "Error sending tool error for requestId=" + requestId, sendEx);</span>
<span class="nc" id="L906"> }</span>
<span class="nc" id="L907"> }</span>
<span class="nc" id="L908"> };</span>
try {
<span class="nc bnc" id="L910" title="All 2 branches missed."> if (executor != null) {</span>
<span class="nc" id="L911"> CompletableFuture.runAsync(task, executor);</span>
} else {
<span class="nc" id="L913"> CompletableFuture.runAsync(task);</span>
}
<span class="nc" id="L915"> } catch (RejectedExecutionException e) {</span>
<span class="nc" id="L916"> LOG.log(Level.WARNING, "Executor rejected tool task for requestId=" + requestId + "; running inline", e);</span>
<span class="nc" id="L917"> task.run();</span>
<span class="nc" id="L918"> }</span>
<span class="nc" id="L919"> }</span>
/**
* Builds a {@link SessionUiHandlePendingElicitationParams} carrying a
* {@code cancel} action, used when an elicitation handler throws or the handler
* future completes exceptionally.
*/
private SessionUiHandlePendingElicitationParams buildElicitationCancelParams(String requestId) {
<span class="nc" id="L927"> var cancelResult = new UIElicitationResponse(UIElicitationResponseAction.CANCEL, null);</span>
<span class="nc" id="L928"> return new SessionUiHandlePendingElicitationParams(sessionId, requestId, cancelResult);</span>
}
/**
* Executes a permission handler and sends the result back via
* {@code session.permissions.handlePendingPermissionRequest}.
*/
private void executePermissionAndRespondAsync(String requestId, PermissionRequest permissionRequest,
PermissionHandler handler) {
<span class="nc" id="L937"> Runnable task = () -> {</span>
try {
<span class="nc" id="L939"> var invocation = new PermissionInvocation();</span>
<span class="nc" id="L940"> invocation.setSessionId(sessionId);</span>
<span class="nc" id="L941"> handler.handle(permissionRequest, invocation).thenAccept(result -> {</span>
try {
<span class="nc" id="L943"> PermissionRequestResultKind kind = new PermissionRequestResultKind(result.getKind());</span>
<span class="nc bnc" id="L944" title="All 2 branches missed."> if (PermissionRequestResultKind.NO_RESULT.equals(kind)) {</span>
// Handler explicitly abstains — leave the request unanswered
// so another client can handle it.
<span class="nc" id="L947"> return;</span>
}
<span class="nc" id="L949"> getRpc().permissions.handlePendingPermissionRequest(</span>
new SessionPermissionsHandlePendingPermissionRequestParams(sessionId, requestId,
result));
<span class="nc" id="L952"> } catch (Exception e) {</span>
<span class="nc" id="L953"> LOG.log(Level.WARNING, "Error sending permission result for requestId=" + requestId, e);</span>
<span class="nc" id="L954"> }</span>
<span class="nc" id="L955"> }).exceptionally(ex -> {</span>
try {
<span class="nc" id="L957"> PermissionRequestResult denied = new PermissionRequestResult();</span>
<span class="nc" id="L958"> denied.setKind(PermissionRequestResultKind.DENIED_COULD_NOT_REQUEST_FROM_USER);</span>
<span class="nc" id="L959"> getRpc().permissions.handlePendingPermissionRequest(</span>
new SessionPermissionsHandlePendingPermissionRequestParams(sessionId, requestId,
denied));
<span class="nc" id="L962"> } catch (Exception e) {</span>
<span class="nc" id="L963"> LOG.log(Level.WARNING, "Error sending permission denied for requestId=" + requestId, e);</span>
<span class="nc" id="L964"> }</span>
<span class="nc" id="L965"> return null;</span>
});
<span class="nc" id="L967"> } catch (Exception e) {</span>
<span class="nc" id="L968"> LOG.log(Level.WARNING, "Error executing permission handler for requestId=" + requestId, e);</span>
try {
<span class="nc" id="L970"> PermissionRequestResult denied = new PermissionRequestResult();</span>
<span class="nc" id="L971"> denied.setKind(PermissionRequestResultKind.DENIED_COULD_NOT_REQUEST_FROM_USER);</span>
<span class="nc" id="L972"> getRpc().permissions.handlePendingPermissionRequest(</span>
new SessionPermissionsHandlePendingPermissionRequestParams(sessionId, requestId, denied));
<span class="nc" id="L974"> } catch (Exception sendEx) {</span>
<span class="nc" id="L975"> LOG.log(Level.WARNING, "Error sending permission denied for requestId=" + requestId, sendEx);</span>
<span class="nc" id="L976"> }</span>
<span class="nc" id="L977"> }</span>
<span class="nc" id="L978"> };</span>
try {
<span class="nc bnc" id="L980" title="All 2 branches missed."> if (executor != null) {</span>
<span class="nc" id="L981"> CompletableFuture.runAsync(task, executor);</span>
} else {
<span class="nc" id="L983"> CompletableFuture.runAsync(task);</span>
}
<span class="nc" id="L985"> } catch (RejectedExecutionException e) {</span>
<span class="nc" id="L986"> LOG.log(Level.WARNING, "Executor rejected perm task for requestId=" + requestId + "; running inline", e);</span>
<span class="nc" id="L987"> task.run();</span>
<span class="nc" id="L988"> }</span>
<span class="nc" id="L989"> }</span>
/**
* Registers custom tool handlers for this session.
* <p>
* Called internally when creating or resuming a session with tools.
*
* @param tools
* the list of tool definitions with handlers
*/
void registerTools(List<ToolDefinition> tools) {
<span class="nc" id="L1000"> toolHandlers.clear();</span>