-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathCopilotSession.java
More file actions
1358 lines (1279 loc) · 54 KB
/
CopilotSession.java
File metadata and controls
1358 lines (1279 loc) · 54 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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------------------------------------------*/
package com.github.copilot.sdk;
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.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.sdk.events.AbstractSessionEvent;
import com.github.copilot.sdk.events.AssistantMessageEvent;
import com.github.copilot.sdk.events.ExternalToolRequestedEvent;
import com.github.copilot.sdk.events.PermissionRequestedEvent;
import com.github.copilot.sdk.events.SessionErrorEvent;
import com.github.copilot.sdk.events.SessionEventParser;
import com.github.copilot.sdk.events.SessionIdleEvent;
import com.github.copilot.sdk.json.AgentInfo;
import com.github.copilot.sdk.json.GetMessagesResponse;
import com.github.copilot.sdk.json.HookInvocation;
import com.github.copilot.sdk.json.MessageOptions;
import com.github.copilot.sdk.json.PermissionHandler;
import com.github.copilot.sdk.json.PermissionInvocation;
import com.github.copilot.sdk.json.PermissionRequest;
import com.github.copilot.sdk.json.PermissionRequestResult;
import com.github.copilot.sdk.json.PermissionRequestResultKind;
import com.github.copilot.sdk.json.PostToolUseHookInput;
import com.github.copilot.sdk.json.PreToolUseHookInput;
import com.github.copilot.sdk.json.SendMessageRequest;
import com.github.copilot.sdk.json.SendMessageResponse;
import com.github.copilot.sdk.json.SessionEndHookInput;
import com.github.copilot.sdk.json.SessionHooks;
import com.github.copilot.sdk.json.SessionStartHookInput;
import com.github.copilot.sdk.json.ToolDefinition;
import com.github.copilot.sdk.json.ToolResultObject;
import com.github.copilot.sdk.json.UserInputHandler;
import com.github.copilot.sdk.json.UserInputInvocation;
import com.github.copilot.sdk.json.UserInputRequest;
import com.github.copilot.sdk.json.UserInputResponse;
import com.github.copilot.sdk.json.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.sdk.json.SessionConfig)
* @see CopilotClient#resumeSession(String,
* com.github.copilot.sdk.json.ResumeSessionConfig)
* @see AbstractSessionEvent
* @since 1.0.0
*/
public final class CopilotSession implements AutoCloseable {
private static final Logger LOG = Logger.getLogger(CopilotSession.class.getName());
private static final ObjectMapper MAPPER = JsonRpcClient.getObjectMapper();
/**
* 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;
private final JsonRpcClient rpc;
private final Set<Consumer<AbstractSessionEvent>> eventHandlers = ConcurrentHashMap.newKeySet();
private final Map<String, ToolDefinition> toolHandlers = new ConcurrentHashMap<>();
private final AtomicReference<PermissionHandler> permissionHandler = new AtomicReference<>();
private final AtomicReference<UserInputHandler> userInputHandler = new AtomicReference<>();
private final AtomicReference<SessionHooks> hooksHandler = new AtomicReference<>();
private volatile EventErrorHandler eventErrorHandler;
private volatile EventErrorPolicy eventErrorPolicy = EventErrorPolicy.PROPAGATE_AND_LOG_ERRORS;
private volatile Map<String, java.util.function.Function<String, CompletableFuture<String>>> transformCallbacks;
private final ScheduledExecutorService timeoutScheduler;
/** Tracks whether this session instance has been terminated via close(). */
private volatile boolean isTerminated = false;
/**
* 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) {
this(sessionId, rpc, null);
}
/**
* 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
*/
CopilotSession(String sessionId, JsonRpcClient rpc, String workspacePath) {
this.sessionId = sessionId;
this.rpc = rpc;
this.workspacePath = workspacePath;
var executor = new ScheduledThreadPoolExecutor(1, r -> {
var t = new Thread(r, "sendAndWait-timeout");
t.setDaemon(true);
return t;
});
executor.setRemoveOnCancelPolicy(true);
this.timeoutScheduler = executor;
}
/**
* Gets the unique identifier for this session.
*
* @return the session ID
*/
public String getSessionId() {
return sessionId;
}
/**
* 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) {
this.sessionId = sessionId;
}
/**
* 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() {
return workspacePath;
}
/**
* 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) {
this.workspacePath = workspacePath;
}
/**
* 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) {
ensureNotTerminated();
this.eventErrorHandler = handler;
}
/**
* 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) {
ensureNotTerminated();
if (policy == null) {
throw new NullPointerException("policy must not be null");
}
this.eventErrorPolicy = policy;
}
/**
* 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) {
ensureNotTerminated();
return send(new MessageOptions().setPrompt(prompt));
}
/**
* 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) {
ensureNotTerminated();
return sendAndWait(new MessageOptions().setPrompt(prompt));
}
/**
* 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) {
ensureNotTerminated();
var request = new SendMessageRequest();
request.setSessionId(sessionId);
request.setPrompt(options.getPrompt());
request.setAttachments(options.getAttachments());
request.setMode(options.getMode());
return rpc.invoke("session.send", request, SendMessageResponse.class).thenApply(SendMessageResponse::messageId);
}
/**
* 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) {
ensureNotTerminated();
var future = new CompletableFuture<AssistantMessageEvent>();
var lastAssistantMessage = new AtomicReference<AssistantMessageEvent>();
Consumer<AbstractSessionEvent> handler = evt -> {
if (evt instanceof AssistantMessageEvent msg) {
lastAssistantMessage.set(msg);
} else if (evt instanceof SessionIdleEvent) {
future.complete(lastAssistantMessage.get());
} else if (evt instanceof SessionErrorEvent errorEvent) {
String message = errorEvent.getData() != null ? errorEvent.getData().message() : "session error";
future.completeExceptionally(new RuntimeException("Session error: " + message));
}
};
Closeable subscription = on(handler);
send(options).exceptionally(ex -> {
try {
subscription.close();
} catch (Exception e) {
LOG.log(Level.SEVERE, "Error closing subscription", e);
}
future.completeExceptionally(ex);
return null;
});
var result = new CompletableFuture<AssistantMessageEvent>();
// Schedule timeout on the shared session-level scheduler.
// Per Javadoc, timeoutMs <= 0 means "no timeout".
ScheduledFuture<?> timeoutTask = null;
if (timeoutMs > 0) {
try {
timeoutTask = timeoutScheduler.schedule(() -> {
if (!future.isDone()) {
future.completeExceptionally(
new TimeoutException("sendAndWait timed out after " + timeoutMs + "ms"));
}
}, timeoutMs, TimeUnit.MILLISECONDS);
} catch (RejectedExecutionException e) {
try {
subscription.close();
} catch (IOException closeEx) {
e.addSuppressed(closeEx);
}
result.completeExceptionally(e);
return result;
}
}
// When inner future completes, run cleanup and propagate to result
final ScheduledFuture<?> taskToCancel = timeoutTask;
future.whenComplete((r, ex) -> {
try {
subscription.close();
} catch (IOException e) {
LOG.log(Level.SEVERE, "Error closing subscription", e);
}
if (taskToCancel != null) {
taskToCancel.cancel(false);
}
if (!result.isDone()) {
if (ex != null) {
result.completeExceptionally(ex);
} else {
result.complete(r);
}
}
});
// When result is cancelled externally, cancel inner future to trigger cleanup
result.whenComplete((v, ex) -> {
if (result.isCancelled() && !future.isDone()) {
future.cancel(true);
}
});
return result;
}
/**
* 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) {
ensureNotTerminated();
return sendAndWait(options, 60000);
}
/**
* 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<AbstractSessionEvent>();
* 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 AbstractSessionEvent
* @see #setEventErrorPolicy(EventErrorPolicy)
*/
public Closeable on(Consumer<AbstractSessionEvent> handler) {
ensureNotTerminated();
eventHandlers.add(handler);
return () -> eventHandlers.remove(handler);
}
/**
* 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 AbstractSessionEvent
*/
public <T extends AbstractSessionEvent> Closeable on(Class<T> eventType, Consumer<T> handler) {
ensureNotTerminated();
Consumer<AbstractSessionEvent> wrapper = event -> {
if (eventType.isInstance(event)) {
handler.accept(eventType.cast(event));
}
};
eventHandlers.add(wrapper);
return () -> eventHandlers.remove(wrapper);
}
/**
* 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(AbstractSessionEvent event) {
// Handle broadcast request events (protocol v3) before dispatching to user
// handlers. These are fire-and-forget: the response is sent asynchronously.
handleBroadcastEventAsync(event);
for (Consumer<AbstractSessionEvent> handler : eventHandlers) {
try {
handler.accept(event);
} catch (Exception e) {
LOG.log(Level.WARNING, "Error in event handler", e);
EventErrorHandler errorHandler = this.eventErrorHandler;
if (errorHandler != null) {
try {
errorHandler.handleError(event, e);
} catch (Exception errorHandlerException) {
LOG.log(Level.SEVERE, "Error in event error handler", errorHandlerException);
break; // error handler itself failed — stop regardless of policy
}
}
if (eventErrorPolicy == EventErrorPolicy.PROPAGATE_AND_LOG_ERRORS) {
break;
}
}
}
}
/**
* 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(AbstractSessionEvent event) {
if (event instanceof ExternalToolRequestedEvent toolEvent) {
var data = toolEvent.getData();
if (data == null || data.requestId() == null || data.toolName() == null) {
return;
}
ToolDefinition tool = getTool(data.toolName());
if (tool == null) {
return; // This client doesn't handle this tool; another client will
}
executeToolAndRespondAsync(data.requestId(), data.toolName(), data.toolCallId(), data.arguments(), tool);
} else if (event instanceof PermissionRequestedEvent permEvent) {
var data = permEvent.getData();
if (data == null || data.requestId() == null || data.permissionRequest() == null) {
return;
}
PermissionHandler handler = permissionHandler.get();
if (handler == null) {
return; // This client doesn't handle permissions; another client will
}
executePermissionAndRespondAsync(data.requestId(), data.permissionRequest(), handler);
}
}
/**
* 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) {
CompletableFuture.runAsync(() -> {
try {
JsonNode argumentsNode = arguments instanceof JsonNode jn
? jn
: (arguments != null ? MAPPER.valueToTree(arguments) : null);
var invocation = new com.github.copilot.sdk.json.ToolInvocation().setSessionId(sessionId)
.setToolCallId(toolCallId).setToolName(toolName).setArguments(argumentsNode);
tool.handler().invoke(invocation).thenAccept(result -> {
try {
ToolResultObject toolResult;
if (result instanceof ToolResultObject tr) {
toolResult = tr;
} else {
toolResult = ToolResultObject
.success(result instanceof String s ? s : MAPPER.writeValueAsString(result));
}
rpc.invoke("session.tools.handlePendingToolCall",
Map.of("sessionId", sessionId, "requestId", requestId, "result", toolResult),
Object.class);
} catch (Exception e) {
LOG.log(Level.WARNING, "Error sending tool result for requestId=" + requestId, e);
}
}).exceptionally(ex -> {
try {
rpc.invoke(
"session.tools.handlePendingToolCall", Map.of("sessionId", sessionId, "requestId",
requestId, "error", ex.getMessage() != null ? ex.getMessage() : ex.toString()),
Object.class);
} catch (Exception e) {
LOG.log(Level.WARNING, "Error sending tool error for requestId=" + requestId, e);
}
return null;
});
} catch (Exception e) {
LOG.log(Level.WARNING, "Error executing tool for requestId=" + requestId, e);
try {
rpc.invoke(
"session.tools.handlePendingToolCall", Map.of("sessionId", sessionId, "requestId",
requestId, "error", e.getMessage() != null ? e.getMessage() : e.toString()),
Object.class);
} catch (Exception sendEx) {
LOG.log(Level.WARNING, "Error sending tool error for requestId=" + requestId, sendEx);
}
}
});
}
/**
* Executes a permission handler and sends the result back via
* {@code session.permissions.handlePendingPermissionRequest}.
*/
private void executePermissionAndRespondAsync(String requestId, PermissionRequest permissionRequest,
PermissionHandler handler) {
CompletableFuture.runAsync(() -> {
try {
var invocation = new PermissionInvocation();
invocation.setSessionId(sessionId);
handler.handle(permissionRequest, invocation).thenAccept(result -> {
try {
PermissionRequestResultKind kind = new PermissionRequestResultKind(result.getKind());
if (PermissionRequestResultKind.NO_RESULT.equals(kind)) {
// Handler explicitly abstains — leave the request unanswered
// so another client can handle it.
return;
}
rpc.invoke("session.permissions.handlePendingPermissionRequest",
Map.of("sessionId", sessionId, "requestId", requestId, "result", result), Object.class);
} catch (Exception e) {
LOG.log(Level.WARNING, "Error sending permission result for requestId=" + requestId, e);
}
}).exceptionally(ex -> {
try {
PermissionRequestResult denied = new PermissionRequestResult();
denied.setKind(PermissionRequestResultKind.DENIED_COULD_NOT_REQUEST_FROM_USER);
rpc.invoke("session.permissions.handlePendingPermissionRequest",
Map.of("sessionId", sessionId, "requestId", requestId, "result", denied), Object.class);
} catch (Exception e) {
LOG.log(Level.WARNING, "Error sending permission denied for requestId=" + requestId, e);
}
return null;
});
} catch (Exception e) {
LOG.log(Level.WARNING, "Error executing permission handler for requestId=" + requestId, e);
try {
PermissionRequestResult denied = new PermissionRequestResult();
denied.setKind(PermissionRequestResultKind.DENIED_COULD_NOT_REQUEST_FROM_USER);
rpc.invoke("session.permissions.handlePendingPermissionRequest",
Map.of("sessionId", sessionId, "requestId", requestId, "result", denied), Object.class);
} catch (Exception sendEx) {
LOG.log(Level.WARNING, "Error sending permission denied for requestId=" + requestId, sendEx);
}
}
});
}
/**
* 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) {
toolHandlers.clear();
if (tools != null) {
for (ToolDefinition tool : tools) {
toolHandlers.put(tool.name(), tool);
}
}
}
/**
* Retrieves a registered tool by name.
*
* @param name
* the tool name
* @return the tool definition, or {@code null} if not found
*/
ToolDefinition getTool(String name) {
return toolHandlers.get(name);
}
/**
* Registers a handler for permission requests.
* <p>
* Called internally when creating or resuming a session with permission
* handling.
*
* @param handler
* the permission handler
*/
void registerPermissionHandler(PermissionHandler handler) {
permissionHandler.set(handler);
}
/**
* Handles a permission request from the Copilot CLI.
* <p>
* Called internally when the server requests permission for an operation.
*
* @param permissionRequestData
* the JSON data for the permission request
* @return a future that resolves with the permission result
*/
CompletableFuture<PermissionRequestResult> handlePermissionRequest(JsonNode permissionRequestData) {
PermissionHandler handler = permissionHandler.get();
if (handler == null) {
PermissionRequestResult result = new PermissionRequestResult();
result.setKind("denied-no-approval-rule-and-could-not-request-from-user");
return CompletableFuture.completedFuture(result);
}
try {
PermissionRequest request = MAPPER.treeToValue(permissionRequestData, PermissionRequest.class);
var invocation = new PermissionInvocation();
invocation.setSessionId(sessionId);
return handler.handle(request, invocation).exceptionally(ex -> {
LOG.log(Level.SEVERE, "Permission handler threw an exception", ex);
PermissionRequestResult result = new PermissionRequestResult();
result.setKind("denied-no-approval-rule-and-could-not-request-from-user");
return result;
});
} catch (Exception e) {
LOG.log(Level.SEVERE, "Failed to process permission request", e);
PermissionRequestResult result = new PermissionRequestResult();
result.setKind("denied-no-approval-rule-and-could-not-request-from-user");
return CompletableFuture.completedFuture(result);
}
}
/**
* Registers a handler for user input requests.
* <p>
* Called internally when creating or resuming a session with user input
* handling.
*
* @param handler
* the user input handler
*/
void registerUserInputHandler(UserInputHandler handler) {
userInputHandler.set(handler);
}
/**
* Handles a user input request from the Copilot CLI.
* <p>
* Called internally when the server requests user input.
*
* @param request
* the user input request
* @return a future that resolves with the user input response
*/
CompletableFuture<UserInputResponse> handleUserInputRequest(UserInputRequest request) {
UserInputHandler handler = userInputHandler.get();
if (handler == null) {
return CompletableFuture.failedFuture(new IllegalStateException("No user input handler registered"));
}
try {
var invocation = new UserInputInvocation().setSessionId(sessionId);
return handler.handle(request, invocation).exceptionally(ex -> {
LOG.log(Level.SEVERE, "User input handler threw an exception", ex);
throw new RuntimeException("User input handler error", ex);
});
} catch (Exception e) {
LOG.log(Level.SEVERE, "Failed to process user input request", e);
return CompletableFuture.failedFuture(e);
}
}
/**
* Registers hook handlers for this session.
* <p>
* Called internally when creating or resuming a session with hooks.
*
* @param hooks
* the hooks configuration
*/
void registerHooks(SessionHooks hooks) {
hooksHandler.set(hooks);
}
/**
* Registers transform callbacks for system message sections.
* <p>
* Called internally when creating or resuming a session with
* {@link com.github.copilot.sdk.SystemMessageMode#CUSTOMIZE} and transform
* callbacks.
*
* @param callbacks
* the transform callbacks keyed by section identifier; {@code null}
* clears any previously registered callbacks
*/
void registerTransformCallbacks(
Map<String, java.util.function.Function<String, CompletableFuture<String>>> callbacks) {
this.transformCallbacks = callbacks;
}
/**
* Handles a {@code systemMessage.transform} RPC call from the Copilot CLI.
* <p>
* The CLI sends section content; the SDK invokes the registered transform
* callbacks and returns the transformed sections.
*
* @param sections
* JSON node containing sections keyed by section identifier
* @return a future resolving with a map of transformed sections
*/
CompletableFuture<Map<String, Object>> handleSystemMessageTransform(JsonNode sections) {
var callbacks = this.transformCallbacks;
var result = new java.util.LinkedHashMap<String, Object>();
var futures = new ArrayList<CompletableFuture<Void>>();
if (sections != null && sections.isObject()) {
sections.fields().forEachRemaining(entry -> {
String sectionId = entry.getKey();
String content = entry.getValue().has("content") ? entry.getValue().get("content").asText("") : "";
java.util.function.Function<String, CompletableFuture<String>> cb = callbacks != null
? callbacks.get(sectionId)
: null;
if (cb != null) {
CompletableFuture<Void> f = cb.apply(content).exceptionally(ex -> content)
.thenAccept(transformed -> {
synchronized (result) {
result.put(sectionId, Map.of("content", transformed != null ? transformed : ""));
}
});
futures.add(f);
} else {
result.put(sectionId, Map.of("content", content));
}
});
}
return CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).thenApply(v -> {
Map<String, Object> response = new java.util.LinkedHashMap<>();
response.put("sections", result);
return response;
});
}
/**
* Handles a hook invocation from the Copilot CLI.
* <p>
* Called internally when the server invokes a hook.
*
* @param hookType
* the type of hook to invoke
* @param input
* the hook input data
* @return a future that resolves with the hook output
*/
CompletableFuture<Object> handleHooksInvoke(String hookType, JsonNode input) {
SessionHooks hooks = hooksHandler.get();
if (hooks == null) {
return CompletableFuture.completedFuture(null);
}
var invocation = new HookInvocation().setSessionId(sessionId);
try {
switch (hookType) {
case "preToolUse" :
if (hooks.getOnPreToolUse() != null) {
PreToolUseHookInput preInput = MAPPER.treeToValue(input, PreToolUseHookInput.class);
return hooks.getOnPreToolUse().handle(preInput, invocation)
.thenApply(output -> (Object) output);
}
break;
case "postToolUse" :
if (hooks.getOnPostToolUse() != null) {
PostToolUseHookInput postInput = MAPPER.treeToValue(input, PostToolUseHookInput.class);
return hooks.getOnPostToolUse().handle(postInput, invocation)
.thenApply(output -> (Object) output);
}
break;
case "userPromptSubmitted" :
if (hooks.getOnUserPromptSubmitted() != null) {
UserPromptSubmittedHookInput promptInput = MAPPER.treeToValue(input,
UserPromptSubmittedHookInput.class);
return hooks.getOnUserPromptSubmitted().handle(promptInput, invocation)