-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathadvanced.html
More file actions
1511 lines (1364 loc) · 74.2 KB
/
Copy pathadvanced.html
File metadata and controls
1511 lines (1364 loc) · 74.2 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
<!DOCTYPE html>
<!--
| Generated by Apache Maven Doxia Site Renderer 2.0.0 from target/filtered-site/markdown/advanced.md at 2026-05-16
| Rendered using Apache Maven Fluido Skin 2.1.0
-->
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="generator" content="Apache Maven Doxia Site Renderer 2.0.0" />
<title>Advanced Usage – GitHub Copilot SDK :: Java</title>
<link rel="stylesheet" href="./css/apache-maven-fluido-2.1.0.min.css" />
<link rel="stylesheet" href="./css/site.css" />
<link rel="stylesheet" href="./css/print.css" media="print" />
<script src="./js/apache-maven-fluido-2.1.0.min.js"></script>
<style>.github-fork-ribbon:before { background-color: gray; }</style>
</head>
<body class="topBarEnabled">
<a class="github-fork-ribbon right-top" href="https://github.com/github/copilot-sdk-java" data-ribbon="Fork me on GitHub">Fork me on GitHub</a>
<header id="topbar" class="navbar navbar-fixed-top ">
<div class="navbar-inner">
<div class="container-fluid">
<a data-target=".nav-collapse" data-toggle="collapse" class="btn btn-navbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="index.html">GitHub Copilot SDK for Java
</a>
<ul class="nav">
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown">Overview <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="index.html">Introduction</a></li>
<li><a href="getting-started.html">Getting Started</a></li>
<li><a href="setup.html">Setup</a></li>
<li><a href="documentation.html">Documentation</a></li>
<li><a href="mcp.html">MCP Servers</a></li>
<li><a href="hooks.html">Session Hooks</a></li>
<li><a>Advanced Usage</a></li>
<li><a href="apidocs/index.html">API Javadoc</a></li>
</ul>
</li>
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown">Guides <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="documentation.html#Basic_Usage">Basic Usage</a></li>
<li><a href="documentation.html#Handling_Responses">Handling Responses</a></li>
<li><a href="documentation.html#Streaming_Responses">Streaming</a></li>
<li><a href="documentation.html#Choosing_a_Model">Choosing a Model</a></li>
<li><a href="documentation.html#Session_Management">Session Management</a></li>
</ul>
</li>
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown">Advanced <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="advanced.html#Custom_Tools">Custom Tools</a></li>
<li><a href="advanced.html#System_Messages">System Messages</a></li>
<li><a href="advanced.html#File_Attachments">File Attachments</a></li>
<li><a href="advanced.html#Bring_Your_Own_Key_.28BYOK.29">BYOK</a></li>
<li><a href="advanced.html#Infinite_Sessions">Infinite Sessions</a></li>
<li><a href="advanced.html#MCP_Servers">MCP Servers</a></li>
<li><a href="advanced.html#Slash_Commands">Slash Commands</a></li>
<li><a href="advanced.html#Elicitation_UI_Dialogs">Elicitation</a></li>
<li><a href="advanced.html#Getting_Session_Metadata_by_ID">Session Metadata</a></li>
<li><a href="hooks.html">Session Hooks</a></li>
</ul>
</li>
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown">Cookbook <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="cookbook/README.html">Overview</a></li>
<li><a href="cookbook/error-handling.html">Error Handling</a></li>
<li><a href="cookbook/multiple-sessions.html">Multiple Sessions</a></li>
<li><a href="cookbook/managing-local-files.html">Managing Local Files</a></li>
<li><a href="cookbook/pr-visualization.html">PR Visualization</a></li>
<li><a href="cookbook/persisting-sessions.html">Persisting Sessions</a></li>
</ul>
</li>
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown">Project Documentation <b class="caret"></b></a>
<ul class="dropdown-menu">
<li class="dropdown-submenu">
<a href="project-info.html">Project Information</a>
<ul class="dropdown-menu">
<li><a href="dependencies.html">Dependencies</a></li>
<li><a href="dependency-info.html">Maven Coordinates</a></li>
<li><a href="distribution-management.html">Distribution Management</a></li>
<li><a href="index.html">About</a></li>
<li><a href="licenses.html">Licenses</a></li>
<li><a href="plugin-management.html">Plugin Management</a></li>
<li><a href="plugins.html">Plugins</a></li>
<li><a href="scm.html">Source Code Management</a></li>
<li><a href="summary.html">Summary</a></li>
<li><a href="team.html">Team</a></li>
</ul>
</li>
<li class="dropdown-submenu">
<a href="project-reports.html">Project Reports</a>
<ul class="dropdown-menu">
<li><a href="apidocs/index.html">Javadoc</a></li>
<li><a href="surefire.html">Surefire</a></li>
<li><a href="spotbugs.html">SpotBugs</a></li>
<li><a href="taglist.html">Tag List</a></li>
<li><a href="dependency-analysis.html">Dependency Analysis</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
</header>
<div class="container-fluid container-fluid-top">
<header>
<div id="banner">
<div class="pull-left"></div>
<div class="pull-right"></div>
<div class="clear"><hr/></div>
</div>
<div id="breadcrumbs">
<ul class="breadcrumb">
<li id="publishDate">Last Published: 2026-05-16<span class="divider">|</span>
</li>
<li id="projectVersion">Version: 1.0.0-beta-java.4<span class="divider">|</span></li>
<li><a href="index.html">Home</a><span class="divider">/</span></li>
<li class="active">Advanced Usage</li>
</ul>
</div>
</header>
<div class="row-fluid">
<header id="leftColumn" class="span2">
<nav class="well sidebar-nav">
<ul class="nav nav-list">
<li class="nav-header">Overview</li>
<li><a href="index.html">Introduction</a></li>
<li><a href="getting-started.html">Getting Started</a></li>
<li><a href="setup.html">Setup</a></li>
<li><a href="documentation.html">Documentation</a></li>
<li><a href="mcp.html">MCP Servers</a></li>
<li><a href="hooks.html">Session Hooks</a></li>
<li class="active"><a>Advanced Usage</a></li>
<li><a href="apidocs/index.html">API Javadoc</a></li>
<li class="nav-header">Guides</li>
<li><a href="documentation.html#Basic_Usage">Basic Usage</a></li>
<li><a href="documentation.html#Handling_Responses">Handling Responses</a></li>
<li><a href="documentation.html#Streaming_Responses">Streaming</a></li>
<li><a href="documentation.html#Choosing_a_Model">Choosing a Model</a></li>
<li><a href="documentation.html#Session_Management">Session Management</a></li>
<li class="nav-header">Advanced</li>
<li><a href="advanced.html#Custom_Tools">Custom Tools</a></li>
<li><a href="advanced.html#System_Messages">System Messages</a></li>
<li><a href="advanced.html#File_Attachments">File Attachments</a></li>
<li><a href="advanced.html#Bring_Your_Own_Key_.28BYOK.29">BYOK</a></li>
<li><a href="advanced.html#Infinite_Sessions">Infinite Sessions</a></li>
<li><a href="advanced.html#MCP_Servers">MCP Servers</a></li>
<li><a href="advanced.html#Slash_Commands">Slash Commands</a></li>
<li><a href="advanced.html#Elicitation_UI_Dialogs">Elicitation</a></li>
<li><a href="advanced.html#Getting_Session_Metadata_by_ID">Session Metadata</a></li>
<li><a href="hooks.html">Session Hooks</a></li>
<li class="nav-header">Cookbook</li>
<li><a href="cookbook/README.html">Overview</a></li>
<li><a href="cookbook/error-handling.html">Error Handling</a></li>
<li><a href="cookbook/multiple-sessions.html">Multiple Sessions</a></li>
<li><a href="cookbook/managing-local-files.html">Managing Local Files</a></li>
<li><a href="cookbook/pr-visualization.html">PR Visualization</a></li>
<li><a href="cookbook/persisting-sessions.html">Persisting Sessions</a></li>
<li class="nav-header">Project Documentation</li>
<li><a href="project-info.html"><span class="icon-chevron-right"></span>Project Information</a></li>
<li><a href="project-reports.html"><span class="icon-chevron-right"></span>Project Reports</a></li>
</ul>
</nav>
<div class="well sidebar-nav">
<div id="poweredBy">
<div class="clear"></div>
<div class="clear"></div>
<a href="https://maven.apache.org/" class="builtBy" target="_blank"><img class="builtBy" alt="Built by Maven" src="./images/logos/maven-feather.png" /></a>
</div>
</div>
</header>
<main id="bodyColumn" class="span10">
<section><a id="Advanced_Usage"></a>
<h1>Advanced Usage</h1>
<p>This guide covers advanced scenarios for extending and customizing your Copilot integration.</p><section><a id="Table_of_Contents"></a>
<h2>Table of Contents</h2>
<ul>
<li><a href="#Custom_Tools">Custom Tools</a>
<ul>
<li><a href="#Overriding_Built-in_Tools">Overriding Built-in Tools</a></li>
<li><a href="#Skipping_Permission_for_Safe_Tools">Skipping Permission for Safe Tools</a></li>
</ul></li>
<li><a href="#Switching_Models_Mid-Session">Switching Models Mid-Session</a></li>
<li><a href="#System_Messages">System Messages</a>
<ul>
<li><a href="#Adding_Rules">Adding Rules</a></li>
<li><a href="#Full_Control">Full Control</a></li>
<li><a href="#Fine-grained_Customization">Fine-grained Customization</a></li>
</ul></li>
<li><a href="#File_Attachments">File Attachments</a>
<ul>
<li><a href="#Inline_Blob_Attachments">Inline Blob Attachments</a></li>
</ul></li>
<li><a href="#OpenTelemetry">OpenTelemetry</a></li>
<li><a href="#Bring_Your_Own_Key_BYOK">Bring Your Own Key (BYOK)</a></li>
<li><a href="#Infinite_Sessions">Infinite Sessions</a>
<ul>
<li><a href="#Manual_Compaction">Manual Compaction</a></li>
<li><a href="#Compaction_Events">Compaction Events</a></li>
</ul></li>
<li><a href="#MCP_Servers">MCP Servers</a></li>
<li><a href="#Custom_Agents">Custom Agents</a>
<ul>
<li><a href="#Programmatic_Agent_Selection">Programmatic Agent Selection</a></li>
</ul></li>
<li><a href="#Skills_Configuration">Skills Configuration</a>
<ul>
<li><a href="#Loading_Skills">Loading Skills</a></li>
<li><a href="#Disabling_Skills">Disabling Skills</a></li>
</ul></li>
<li><a href="#Custom_Configuration_Directory">Custom Configuration Directory</a></li>
<li><a href="#Session_Logging">Session Logging</a></li>
<li><a href="#Early_Event_Registration">Early Event Registration</a></li>
<li><a href="#User_Input_Handling">User Input Handling</a></li>
<li><a href="#Permission_Handling">Permission Handling</a></li>
<li><a href="#Session_Hooks">Session Hooks</a></li>
<li><a href="#Manual_Server_Control">Manual Server Control</a></li>
<li><a href="#Session_Context_and_Filtering">Session Context and Filtering</a>
<ul>
<li><a href="#Listing_Sessions_with_Context">Listing Sessions with Context</a></li>
<li><a href="#Filtering_Sessions_by_Context">Filtering Sessions by Context</a></li>
<li><a href="#Context_Changed_Events">Context Changed Events</a></li>
</ul></li>
<li><a href="#Session_Lifecycle_Events">Session Lifecycle Events</a>
<ul>
<li><a href="#Subscribing_to_All_Lifecycle_Events">Subscribing to All Lifecycle Events</a></li>
<li><a href="#Subscribing_to_Specific_Event_Types">Subscribing to Specific Event Types</a></li>
</ul></li>
<li><a href="#Foreground_Session_Control_TUIServer_Mode">Foreground Session Control (TUI+Server Mode)</a>
<ul>
<li><a href="#Getting_the_Foreground_Session">Getting the Foreground Session</a></li>
<li><a href="#Setting_the_Foreground_Session">Setting the Foreground Session</a></li>
</ul></li>
<li><a href="#Error_Handling">Error Handling</a>
<ul>
<li><a href="#Event_Handler_Exceptions">Event Handler Exceptions</a></li>
<li><a href="#Custom_Event_Error_Handler">Custom Event Error Handler</a></li>
<li><a href="#Event_Error_Policy">Event Error Policy</a></li>
</ul></li>
<li><a href="#OpenTelemetry">OpenTelemetry</a></li>
<li><a href="#Slash_Commands">Slash Commands</a>
<ul>
<li><a href="#Registering_Commands">Registering Commands</a></li>
</ul></li>
<li><a href="#Elicitation_UI_Dialogs">Elicitation (UI Dialogs)</a>
<ul>
<li><a href="#Incoming_Elicitation_Handler">Incoming Elicitation Handler</a></li>
<li><a href="#Session_Capabilities">Session Capabilities</a></li>
<li><a href="#Outgoing_Elicitation_via_session.getUi">Outgoing Elicitation via session.getUi()</a></li>
</ul></li>
<li><a href="#Mode_Handlers">Mode Handlers</a>
<ul>
<li><a href="#Exit_Plan_Mode">Exit Plan Mode</a></li>
<li><a href="#Auto_Mode_Switch">Auto Mode Switch</a></li>
</ul></li>
<li><a href="#Getting_Session_Metadata_by_ID">Getting Session Metadata by ID</a></li>
</ul><hr /></section><section><a id="Custom_Tools"></a>
<h2>Custom Tools</h2>
<p>Let the AI call back into your application to fetch data or perform actions.</p>
<pre class="prettyprint"><code class="language-java">// Define strongly-typed arguments with a record
record IssueArgs(String id) {}
var lookupTool = ToolDefinition.create(
"lookup_issue",
"Fetch issue details from our tracker",
Map.of(
"type", "object",
"properties", Map.of(
"id", Map.of("type", "string", "description", "Issue identifier")
),
"required", List.of("id")
),
invocation -> {
IssueArgs args = invocation.getArgumentsAs(IssueArgs.class);
return CompletableFuture.completedFuture(fetchIssue(args.id()));
}
);
var session = client.createSession(
new SessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL)
.setTools(List.of(lookupTool))
).get();
</code></pre>
<p>See <a href="apidocs/com/github/copilot/sdk/json/ToolDefinition.html">ToolDefinition</a> Javadoc for schema details.</p><section><a id="Overriding_Built-in_Tools"></a>
<h3>Overriding Built-in Tools</h3>
<p>You can replace a built-in CLI tool (such as <code>grep</code> or <code>read_file</code>) with your own implementation
by using <code>ToolDefinition.createOverride()</code>. This signals to the CLI that the name collision is
intentional and your custom implementation should be used instead.</p>
<pre class="prettyprint"><code class="language-java">var customGrep = ToolDefinition.createOverride(
"grep",
"Project-aware search with custom filtering",
Map.of(
"type", "object",
"properties", Map.of(
"query", Map.of("type", "string", "description", "Search query")
),
"required", List.of("query")
),
invocation -> {
String query = (String) invocation.getArguments().get("query");
// Your custom search logic here
return CompletableFuture.completedFuture("Results for: " + query);
}
);
var session = client.createSession(
new SessionConfig()
.setTools(List.of(customGrep))
.setOnPermissionRequest(PermissionHandler.APPROVE_ALL)
).get();
</code></pre></section><section><a id="Skipping_Permission_for_Safe_Tools"></a>
<h3>Skipping Permission for Safe Tools</h3>
<p>When a tool performs only read-only or non-destructive operations, you can mark it to skip the
permission prompt entirely using <code>ToolDefinition.createSkipPermission()</code>:</p>
<pre class="prettyprint"><code class="language-java">var safeLookup = ToolDefinition.createSkipPermission(
"safe_lookup",
"Look up a record by ID (read-only, no side effects)",
Map.of(
"type", "object",
"properties", Map.of(
"id", Map.of("type", "string")
),
"required", List.of("id")
),
invocation -> {
String id = (String) invocation.getArguments().get("id");
return CompletableFuture.completedFuture("Record: " + lookupRecord(id));
}
);
</code></pre>
<p>The CLI bypasses the permission request for this tool invocation, so no <code>PermissionRequestedEvent</code>
is emitted and the <code>onPermissionRequest</code> handler is not called.</p>
<p>See <a href="apidocs/com/github/copilot/sdk/json/ToolDefinition.html">ToolDefinition</a> Javadoc for details.</p><hr /></section></section><section><a id="Switching_Models_Mid-Session"></a>
<h2>Switching Models Mid-Session</h2>
<p>You can change the model used by an existing session without losing conversation history.
The new model takes effect starting with the next message sent.</p>
<pre class="prettyprint"><code class="language-java">var session = client.createSession(
new SessionConfig()
.setOnPermissionRequest(PermissionHandler.APPROVE_ALL)
).get();
// Switch to a different model mid-conversation
session.setModel("gpt-4.1").get();
// Switch with a specific reasoning effort level
session.setModel("claude-sonnet-4.6", "high").get();
// Next message will use the new model
session.sendAndWait(new MessageOptions().setPrompt("Continue with the new model")).get();
</code></pre>
<p>The <code>reasoningEffort</code> parameter accepts <code>"low"</code>, <code>"medium"</code>, <code>"high"</code>, or <code>"xhigh"</code> for models
that support reasoning. Pass <code>null</code> (or use the single-argument overload) to use the default.</p>
<p>The session emits a <a href="apidocs/com/github/copilot/sdk/generated/SessionModelChangeEvent.html"><code>SessionModelChangeEvent</code></a>
when the switch completes, which you can observe with <code>session.on(SessionModelChangeEvent.class, event -> ...)</code>.</p>
<p>See <a href="apidocs/com/github/copilot/sdk/CopilotSession.html#setModel.28java.lang.String.29">CopilotSession.setModel()</a> Javadoc for details.</p><hr /></section><section><a id="System_Messages"></a>
<h2>System Messages</h2>
<p>Customize the AI's behavior by adding rules or replacing the default prompt.</p><section><a id="Adding_Rules"></a>
<h3>Adding Rules</h3>
<p>Use <code>APPEND</code> mode to add constraints while keeping default guardrails:</p>
<pre class="prettyprint"><code class="language-java">var session = client.createSession(
new SessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL)
.setSystemMessage(new SystemMessageConfig()
.setMode(SystemMessageMode.APPEND)
.setContent("""
<rules>
- Always check for security vulnerabilities
- Suggest performance improvements
</rules>
"""))
).get();
</code></pre></section><section><a id="Full_Control"></a>
<h3>Full Control</h3>
<p>Use <code>REPLACE</code> mode for complete control (removes default guardrails):</p>
<pre class="prettyprint"><code class="language-java">var session = client.createSession(
new SessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL)
.setSystemMessage(new SystemMessageConfig()
.setMode(SystemMessageMode.REPLACE)
.setContent("You are a helpful coding assistant."))
).get();
</code></pre></section><section><a id="Fine-grained_Customization"></a>
<h3>Fine-grained Customization</h3>
<p>Use <code>CUSTOMIZE</code> mode to override individual sections of the default system prompt without
replacing it entirely. You can replace, remove, append, prepend, or transform specific sections
using the section identifiers from <code>SystemPromptSections</code>.</p>
<p><strong>Static overrides:</strong></p>
<pre class="prettyprint"><code class="language-java">var session = client.createSession(
new SessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL)
.setSystemMessage(new SystemMessageConfig()
.setMode(SystemMessageMode.CUSTOMIZE)
.setSections(Map.of(
// Replace the tone section
SystemPromptSections.TONE,
new SectionOverride()
.setAction(SectionOverrideAction.REPLACE)
.setContent("Be concise and formal in all responses."),
// Remove the code-change-rules section entirely
SystemPromptSections.CODE_CHANGE_RULES,
new SectionOverride()
.setAction(SectionOverrideAction.REMOVE)
))
// Optional: extra content appended after all sections
.setContent("Always mention quarterly earnings."))
).get();
</code></pre>
<p><strong>Transform callbacks</strong> let you inspect and modify section content at runtime:</p>
<pre class="prettyprint"><code class="language-java">var session = client.createSession(
new SessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL)
.setSystemMessage(new SystemMessageConfig()
.setMode(SystemMessageMode.CUSTOMIZE)
.setSections(Map.of(
SystemPromptSections.IDENTITY,
new SectionOverride()
.setTransform(content ->
CompletableFuture.completedFuture(
content + "\nAlways end your reply with DONE."))
)))
).get();
</code></pre>
<p>See <a href="apidocs/com/github/copilot/sdk/json/SystemMessageConfig.html">SystemMessageConfig</a>,
<a href="apidocs/com/github/copilot/sdk/json/SectionOverride.html">SectionOverride</a>, and
<a href="apidocs/com/github/copilot/sdk/json/SystemPromptSections.html">SystemPromptSections</a> Javadoc for details.</p><hr /></section></section><section><a id="File_Attachments"></a>
<h2>File Attachments</h2>
<p>Include files as context for the AI to analyze. The <code>Attachment</code> record takes three parameters:</p>
<table class="table table-striped">
<thead>
<tr class="a">
<th>Parameter</th>
<th>Type</th>
<th>Description</th></tr></thead><tbody>
<tr class="b">
<td><code>type</code></td>
<td>String</td>
<td>The attachment type — use <code>"file"</code> for filesystem files</td></tr>
<tr class="a">
<td><code>path</code></td>
<td>String</td>
<td>The absolute path to the file on disk</td></tr>
<tr class="b">
<td><code>displayName</code></td>
<td>String</td>
<td>A human-readable label shown to the AI (e.g., the filename or a description)</td></tr></tbody>
</table>
<pre class="prettyprint"><code class="language-java">session.send(new MessageOptions()
.setPrompt("Review this file for bugs")
.setAttachments(List.of(
new Attachment("file", "/path/to/file.java", "MyService.java")
))
).get();
</code></pre>
<p>You can attach multiple files in a single message:</p>
<pre class="prettyprint"><code class="language-java">session.send(new MessageOptions()
.setPrompt("Compare these two implementations")
.setAttachments(List.of(
new Attachment("file", "/src/main/OldImpl.java", "Old Implementation"),
new Attachment("file", "/src/main/NewImpl.java", "New Implementation")
))
).get();
</code></pre><section><a id="Inline_Blob_Attachments"></a>
<h3>Inline Blob Attachments</h3>
<p>Use <code>BlobAttachment</code> to pass inline base64-encoded binary data — for example, an image captured
at runtime — without writing it to disk first:</p>
<pre class="prettyprint"><code class="language-java">// Load image bytes and base64-encode them
byte[] imageBytes = Files.readAllBytes(Path.of("/path/to/screenshot.png"));
String base64Data = Base64.getEncoder().encodeToString(imageBytes);
session.send(new MessageOptions()
.setPrompt("Describe this screenshot")
.setAttachments(List.of(
new BlobAttachment()
.setData(base64Data)
.setMimeType("image/png")
.setDisplayName("screenshot.png")
))
).get();
</code></pre>
<p>See <a href="apidocs/com/github/copilot/sdk/json/BlobAttachment.html">BlobAttachment</a> Javadoc for details.</p>
<p>Both <code>Attachment</code> and <code>BlobAttachment</code> implement the sealed <code>MessageAttachment</code> interface.
For a mixed list with both types, use an explicit type hint:</p>
<pre class="prettyprint"><code class="language-java">session.send(new MessageOptions()
.setPrompt("Analyze these")
.setAttachments(List.<MessageAttachment>of(
new Attachment("file", "/path/to/file.java", "Source"),
new BlobAttachment()
.setData(base64Data)
.setMimeType("image/png")
.setDisplayName("screenshot.png")
))
).get();
</code></pre><hr /></section></section><section><a id="Bring_Your_Own_Key_.28BYOK.29"></a>
<h2>Bring Your Own Key (BYOK)</h2>
<p>Use your own OpenAI or Azure OpenAI API key instead of GitHub Copilot.</p>
<p>Supported providers:</p>
<table class="table table-striped">
<thead>
<tr class="a">
<th>Provider</th>
<th>Type value</th>
<th>Notes</th></tr></thead><tbody>
<tr class="b">
<td>OpenAI</td>
<td><code>"openai"</code></td>
<td>Standard OpenAI API</td></tr>
<tr class="a">
<td>Azure OpenAI / Azure AI Foundry</td>
<td><code>"azure"</code></td>
<td>Azure-hosted models</td></tr>
<tr class="b">
<td>Anthropic</td>
<td><code>"anthropic"</code></td>
<td>Claude models</td></tr>
<tr class="a">
<td>Ollama</td>
<td><code>"openai"</code></td>
<td>Local models via OpenAI-compatible API</td></tr>
<tr class="b">
<td>Microsoft Foundry Local</td>
<td><code>"openai"</code></td>
<td>Run AI models locally on your device via OpenAI-compatible API</td></tr>
<tr class="a">
<td>Other OpenAI-compatible</td>
<td><code>"openai"</code></td>
<td>vLLM, LiteLLM, etc.</td></tr></tbody>
</table>
<section><a id="API_Key_Authentication"></a>
<h3>API Key Authentication</h3>
<pre class="prettyprint"><code class="language-java">var session = client.createSession(
new SessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL)
.setProvider(new ProviderConfig()
.setType("openai")
.setBaseUrl("https://api.openai.com/v1")
.setApiKey("sk-..."))
).get();
</code></pre></section><section><a id="Bearer_Token_Authentication"></a>
<h3>Bearer Token Authentication</h3>
<p>Some providers require bearer token authentication instead of API keys:</p>
<pre class="prettyprint"><code class="language-java">var session = client.createSession(
new SessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL)
.setProvider(new ProviderConfig()
.setType("openai")
.setBaseUrl("https://my-custom-endpoint.example.com/v1")
.setBearerToken(System.getenv("MY_BEARER_TOKEN")))
).get();
</code></pre>
<blockquote>
<p><strong>Note:</strong> The <code>bearerToken</code> option accepts a <strong>static token string</strong> only. The SDK does not refresh this token automatically. If your token expires, requests will fail and you'll need to create a new session with a fresh token.</p>
</blockquote></section><section><a id="Model_Overrides"></a>
<h3>Model Overrides</h3>
<p>Use <code>modelId</code> and <code>wireModel</code> to control model resolution and the model name on the wire:</p>
<pre class="prettyprint"><code class="language-java">var session = client.createSession(
new SessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL)
.setProvider(new ProviderConfig()
.setType("openai")
.setBaseUrl("https://api.openai.com/v1")
.setApiKey("sk-...")
.setModelId("gpt-4o") // Runtime config lookup
.setWireModel("my-finetune-v3") // Sent to the provider API
.setMaxPromptTokens(100_000) // Override max prompt tokens
.setMaxOutputTokens(4096)) // Override max output tokens
).get();
</code></pre>
<ul>
<li><strong><code>modelId</code></strong> — Well-known model name used by the runtime to look up agent configuration (tools, prompts, reasoning behavior) and default token limits. Also used as the wire model when <code>wireModel</code> is not set.</li>
<li><strong><code>wireModel</code></strong> — Model name sent to the provider API for inference. Use when the provider's model name (e.g., an Azure deployment name or a custom fine-tune name) differs from <code>modelId</code>.</li>
<li><strong><code>maxPromptTokens</code></strong> — Overrides the resolved model's default max prompt tokens. The runtime triggers conversation compaction when the prompt would exceed this limit.</li>
<li><strong><code>maxOutputTokens</code></strong> — Overrides the resolved model's default max output tokens.</li>
</ul></section><section><a id="Microsoft_Foundry_Local"></a>
<h3>Microsoft Foundry Local</h3>
<p><a href="https://foundrylocal.ai" class="externalLink">Microsoft Foundry Local</a> lets you run AI models locally on your own device with an OpenAI-compatible API. Install it via the Foundry Local CLI, then point the SDK at your local endpoint:</p>
<pre class="prettyprint"><code class="language-java">var session = client.createSession(
new SessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL)
.setProvider(new ProviderConfig()
.setType("openai")
.setBaseUrl("http://localhost:<PORT>/v1"))
// No apiKey needed for local Foundry Local
).get();
</code></pre>
<blockquote>
<p><strong>Note:</strong> Foundry Local starts on a <strong>dynamic port</strong> — the port is not fixed. Use <code>foundry service status</code> to confirm the port the service is currently listening on, then use that port in your <code>baseUrl</code>.</p>
</blockquote>
<p>To get started with Foundry Local:</p>
<pre class="prettyprint"><code class="language-bash"># Windows: Install Foundry Local CLI (requires winget)
winget install Microsoft.FoundryLocal
# macOS / Linux: see https://foundrylocal.ai for installation instructions
# List available models
foundry model list
# Run a model (starts the local server automatically)
foundry model run phi-4-mini
# Check the port the service is running on
foundry service status
</code></pre></section><section><a id="Limitations"></a>
<h3>Limitations</h3>
<p>When using BYOK, be aware of these limitations:</p><section><a id="Identity_Limitations"></a>
<h4>Identity Limitations</h4>
<p>BYOK authentication uses <strong>static credentials only</strong>. The following identity providers are NOT supported:</p>
<ul>
<li>❌ <strong>Microsoft Entra ID (Azure AD)</strong> - No support for Entra managed identities or service principals</li>
<li>❌ <strong>Third-party identity providers</strong> - No OIDC, SAML, or other federated identity</li>
<li>❌ <strong>Managed identities</strong> - Azure Managed Identity is not supported</li>
</ul>
<p>You must use an API key or static bearer token that you manage yourself.</p>
<p><strong>Why not Entra ID?</strong> While Entra ID does issue bearer tokens, these tokens are short-lived (typically 1 hour) and require automatic refresh via the Azure Identity SDK. The <code>bearerToken</code> option only accepts a static string—there is no callback mechanism for the SDK to request fresh tokens. For long-running workloads requiring Entra authentication, you would need to implement your own token refresh logic and create new sessions with updated tokens.</p><hr /></section></section></section><section><a id="Infinite_Sessions"></a>
<h2>Infinite Sessions</h2>
<p>Run long conversations without hitting context limits.</p>
<p>When enabled (default), the session automatically compacts older messages as the context window fills up.</p>
<pre class="prettyprint"><code class="language-java">var session = client.createSession(
new SessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL)
.setInfiniteSessions(new InfiniteSessionConfig()
.setEnabled(true)
.setBackgroundCompactionThreshold(0.80) // Start compacting at 80%
.setBufferExhaustionThreshold(0.95)) // Block at 95%
).get();
// Access the workspace where session state is persisted
var workspace = session.getWorkspacePath();
</code></pre><section><a id="Manual_Compaction"></a>
<h3>Manual Compaction</h3>
<p>Trigger compaction immediately when you want to reduce context usage before the automatic threshold is reached:</p>
<pre class="prettyprint"><code class="language-java">session.compact().get();
</code></pre></section><section><a id="Compaction_Events"></a>
<h3>Compaction Events</h3>
<p>When compaction occurs, the session emits events that you can listen for:</p>
<pre class="prettyprint"><code class="language-java">session.on(SessionCompactionStartEvent.class, start -> {
System.out.println("Compaction started");
});
session.on(SessionCompactionCompleteEvent.class, complete -> {
var data = complete.getData();
System.out.println("Compaction completed - success: " + data.success()
+ ", tokens removed: " + data.tokensRemoved());
});
</code></pre>
<p>For short conversations, disable to avoid overhead:</p>
<pre class="prettyprint"><code class="language-java">new InfiniteSessionConfig().setEnabled(false)
</code></pre><hr /></section></section><section><a id="MCP_Servers"></a>
<h2>MCP Servers</h2>
<p>Extend the AI with external tools via the Model Context Protocol.</p>
<pre class="prettyprint"><code class="language-java">Map<String, Object> server = Map.of(
"type", "local",
"command", "npx",
"args", List.of("-y", "@modelcontextprotocol/server-filesystem", "/tmp"),
"tools", List.of("*")
);
var session = client.createSession(
new SessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL)
.setMcpServers(Map.of("filesystem", server))
).get();
</code></pre>
<p>📖 <strong><a href="mcp.html">Full MCP documentation →</a></strong> for local/remote servers and all options.</p><hr /></section><section><a id="Custom_Agents"></a>
<h2>Custom Agents</h2>
<p>Extend the base Copilot assistant with specialized agents that have their own tools, prompts, and behavior. Users can invoke agents using the <code>@agent-name</code> mention syntax in messages.</p>
<pre class="prettyprint"><code class="language-java">var reviewer = new CustomAgentConfig()
.setName("code-reviewer")
.setDisplayName("Code Reviewer")
.setDescription("Reviews code for best practices and security")
.setPrompt("You are a code review expert. Focus on security, performance, and maintainability.")
.setTools(List.of("read_file", "search_code"));
var session = client.createSession(
new SessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL)
.setCustomAgents(List.of(reviewer))
).get();
// The user can now mention @code-reviewer in messages
session.send("@code-reviewer Review src/Main.java").get();
</code></pre><section><a id="Configuration_Options"></a>
<h3>Configuration Options</h3>
<table class="table table-striped">
<thead>
<tr class="a">
<th>Option</th>
<th>Type</th>
<th>Description</th></tr></thead><tbody>
<tr class="b">
<td><code>name</code></td>
<td>String</td>
<td>Unique identifier used for <code>@mentions</code> (alphanumeric and hyphens)</td></tr>
<tr class="a">
<td><code>displayName</code></td>
<td>String</td>
<td>Human-readable name shown to users</td></tr>
<tr class="b">
<td><code>description</code></td>
<td>String</td>
<td>Describes the agent's capabilities</td></tr>
<tr class="a">
<td><code>prompt</code></td>
<td>String</td>
<td>System prompt that defines the agent's behavior</td></tr>
<tr class="b">
<td><code>tools</code></td>
<td>List<String></td>
<td>Tool names available to this agent</td></tr>
<tr class="a">
<td><code>mcpServers</code></td>
<td>Map</td>
<td>MCP servers available to this agent</td></tr>
<tr class="b">
<td><code>infer</code></td>
<td>Boolean</td>
<td>Whether the agent can be auto-selected based on context</td></tr></tbody>
</table>
</section><section><a id="Multiple_Agents"></a>
<h3>Multiple Agents</h3>
<p>Register multiple agents for different tasks:</p>
<pre class="prettyprint"><code class="language-java">var agents = List.of(
new CustomAgentConfig()
.setName("reviewer")
.setDescription("Code review")
.setPrompt("You review code for issues."),
new CustomAgentConfig()
.setName("documenter")
.setDescription("Documentation writer")
.setPrompt("You write clear documentation.")
.setInfer(true) // Auto-select when appropriate
);
var session = client.createSession(
new SessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL).setCustomAgents(agents)
).get();
</code></pre>
<p>See <a href="apidocs/com/github/copilot/sdk/json/CustomAgentConfig.html">CustomAgentConfig</a> Javadoc for full details.</p></section><section><a id="Programmatic_Agent_Selection"></a>
<h3>Programmatic Agent Selection</h3>
<p>You can inspect and switch agents at runtime:</p>
<pre class="prettyprint"><code class="language-java">var available = session.listAgents().get();
var current = session.getCurrentAgent().get();
if (current != null) {
System.out.println("Current agent: " + current.name());
}
var selected = session.selectAgent("reviewer").get();
System.out.println("Selected: " + selected.name());
session.deselectAgent().get(); // Return to the default agent
</code></pre><hr /></section></section><section><a id="Skills_Configuration"></a>
<h2>Skills Configuration</h2>
<p>Load custom skills from directories to extend the AI's capabilities with domain-specific knowledge.</p><section><a id="Loading_Skills"></a>
<h3>Loading Skills</h3>
<p>Skills are loaded from <code>SKILL.md</code> files in subdirectories of the specified skill directories:</p>
<pre class="prettyprint"><code class="language-java">var session = client.createSession(
new SessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL)
.setSkillDirectories(List.of("/path/to/skills"))
).get();
</code></pre>
<p>Each skill subdirectory should contain a <code>SKILL.md</code> file with YAML frontmatter:</p>
<pre class="prettyprint"><code class="language-markdown">---
name: my-skill
description: A skill that provides domain-specific knowledge
---
# Skill Instructions
Your skill instructions go here...
</code></pre></section><section><a id="Disabling_Skills"></a>
<h3>Disabling Skills</h3>
<p>Disable specific skills by name:</p>
<pre class="prettyprint"><code class="language-java">var session = client.createSession(
new SessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL)
.setSkillDirectories(List.of("/path/to/skills"))
.setDisabledSkills(List.of("my-skill"))
).get();
</code></pre><hr /></section></section><section><a id="Instruction_Directories"></a>
<h2>Instruction Directories</h2>
<p>Provide additional directories containing custom instruction files. These instructions are automatically included in the system message for all conversations in the session.</p>
<pre class="prettyprint"><code class="language-java">var session = client.createSession(
new SessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL)
.setInstructionDirectories(List.of("/path/to/instructions"))
).get();
</code></pre>
<p>Instruction files are discovered from <code>.github/instructions/</code> subdirectories within each specified path and should use the <code>.instructions.md</code> extension.</p>
<p>This is also supported on session resume:</p>
<pre class="prettyprint"><code class="language-java">var session = client.resumeSession(sessionId,
new ResumeSessionConfig()
.setOnPermissionRequest(PermissionHandler.APPROVE_ALL)
.setInstructionDirectories(List.of("/path/to/instructions"))
);
</code></pre><hr /></section><section><a id="Custom_Configuration_Directory"></a>
<h2>Custom Configuration Directory</h2>
<p>Use a custom configuration directory for session settings:</p>
<pre class="prettyprint"><code class="language-java">var session = client.createSession(
new SessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL)
.setConfigDir("/path/to/custom/config")
).get();
</code></pre>
<p>This is useful when you need to isolate session configuration or use different settings for different environments.</p><hr /></section><section><a id="Session_Logging"></a>
<h2>Session Logging</h2>
<p>Send log messages to the session for debugging, status updates, or UI feedback.</p>
<pre class="prettyprint"><code class="language-java">// Simple log message (defaults to "info" level)
session.log("Processing step 1 of 3").get();
// Log with explicit level and ephemeral flag
session.log("Downloading dependencies...", "info", true).get();
</code></pre>
<table class="table table-striped">
<thead>
<tr class="a">
<th>Parameter</th>
<th>Type</th>
<th>Description</th></tr></thead><tbody>
<tr class="b">
<td><code>message</code></td>
<td>String</td>
<td>The log message text</td></tr>
<tr class="a">
<td><code>level</code></td>
<td>String</td>
<td>Log level: <code>"info"</code>, <code>"warning"</code>, <code>"error"</code></td></tr>
<tr class="b">
<td><code>ephemeral</code></td>
<td>Boolean</td>
<td>If <code>true</code>, the message is transient and may not be persisted</td></tr></tbody>
</table>
<p>Use cases:</p>
<ul>
<li>Displaying progress in a UI while the session processes a request</li>
<li>Sending status updates to the session log</li>
<li>Debugging session behavior with contextual messages</li>
</ul>
<p>See <a href="apidocs/com/github/copilot/sdk/CopilotSession.html#log.28java.lang.String.29">CopilotSession.log()</a> Javadoc for details.</p><hr /></section><section><a id="Early_Event_Registration"></a>
<h2>Early Event Registration</h2>
<p>Register an event handler <em>before</em> the <code>session.create</code> RPC is issued, ensuring no early events are missed.</p>
<p>When you register handlers with <code>session.on()</code> after <code>createSession()</code> returns, you may miss events emitted during session creation (e.g., <code>SessionStartEvent</code>). Use <code>SessionConfig.setOnEvent()</code> to guarantee delivery of all events from the very start:</p>
<pre class="prettyprint"><code class="language-java">var events = new CopyOnWriteArrayList<SessionEvent>();
var session = client.createSession(
new SessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL)
.setOnEvent(events::add) // Registered before session.create RPC
).get();
// events list now includes SessionStartEvent and any other early events
</code></pre>
<p>This is equivalent to calling <code>session.on(handler)</code> immediately after creation, but executes earlier in the lifecycle. The same option is available on <code>ResumeSessionConfig.setOnEvent()</code> for resumed sessions.</p><hr /></section><section><a id="User_Input_Handling"></a>
<h2>User Input Handling</h2>
<p>Handle user input requests when the AI uses the <code>ask_user</code> tool to gather information from the user.</p>
<pre class="prettyprint"><code class="language-java">var session = client.createSession(
new SessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL)
.setOnUserInputRequest((request, invocation) -> {
System.out.println("Agent asks: " + request.getQuestion());
// Check if choices are provided
if (request.getChoices() != null && !request.getChoices().isEmpty()) {
System.out.println("Options: " + request.getChoices());
// Return one of the provided choices
var selectedChoice = request.getChoices().get(0);
return CompletableFuture.completedFuture(
new UserInputResponse()
.setAnswer(selectedChoice)
.setWasFreeform(false)
);
}
// Freeform input
var userAnswer = getUserInput(); // your input method
return CompletableFuture.completedFuture(
new UserInputResponse()
.setAnswer(userAnswer)
.setWasFreeform(true)
);
})
).get();
</code></pre>
<p>The <code>UserInputRequest</code> contains:</p>
<ul>
<li><code>getQuestion()</code> - The question the AI is asking</li>
<li><code>getChoices()</code> - Optional list of choices for the user to select from</li>
</ul>
<p>The <code>UserInputResponse</code> should include:</p>
<ul>
<li><code>setAnswer(String)</code> - The user's answer</li>
<li><code>setWasFreeform(boolean)</code> - <code>true</code> if the answer was freeform text, <code>false</code> if it was from the provided choices</li>
</ul>
<p>See <a href="apidocs/com/github/copilot/sdk/json/UserInputHandler.html">UserInputHandler</a> Javadoc for more details.</p><hr /></section><section><a id="Permission_Handling"></a>
<h2>Permission Handling</h2>
<p>Approve or deny permission requests from the AI.</p>
<pre class="prettyprint"><code class="language-java">var session = client.createSession(
new SessionConfig().setOnPermissionRequest((request, invocation) -> {
// Inspect request and approve/deny using typed constants
var result = new PermissionRequestResult();
result.setKind(PermissionRequestResultKind.APPROVED);
return CompletableFuture.completedFuture(result);
})
).get();
</code></pre>
<p>The <code>PermissionRequestResultKind</code> class provides well-known constants for common outcomes:</p>
<table class="table table-striped">
<thead>
<tr class="a">
<th>Constant</th>
<th>Value</th>
<th>Meaning</th></tr></thead><tbody>
<tr class="b">
<td><code>PermissionRequestResultKind.APPROVED</code></td>
<td><code>"approve-once"</code></td>
<td>The permission was approved for this one instance</td></tr>
<tr class="a">
<td><code>PermissionRequestResultKind.REJECTED</code></td>
<td><code>"reject"</code></td>
<td>The permission was denied interactively by the user</td></tr>
<tr class="b">
<td><code>PermissionRequestResultKind.USER_NOT_AVAILABLE</code></td>
<td><code>"user-not-available"</code></td>
<td>Denied because user confirmation was unavailable</td></tr>
<tr class="a">
<td><code>PermissionRequestResultKind.NO_RESULT</code></td>
<td><code>"no-result"</code></td>
<td>No permission decision was made (protocol v3 only)</td></tr></tbody>
</table>
<p>You can also pass a raw string to <code>setKind(String)</code> for custom or extension values. Use
<a href="apidocs/com/github/copilot/sdk/json/PermissionHandler.html"><code>PermissionHandler.APPROVE_ALL</code></a> to approve all
requests without writing a handler.</p><hr /></section><section><a id="Session_Hooks"></a>
<h2>Session Hooks</h2>
<p>Intercept tool execution and session lifecycle events using hooks.</p>
<pre class="prettyprint"><code class="language-java">var hooks = new SessionHooks()
.setOnPreToolUse((input, invocation) -> {
System.out.println("Tool: " + input.getToolName());
return CompletableFuture.completedFuture(PreToolUseHookOutput.allow());
})
.setOnPostToolUse((input, invocation) -> {
System.out.println("Result: " + input.getToolResult());
return CompletableFuture.completedFuture(null);
});
var session = client.createSession(
new SessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL).setHooks(hooks)
).get();