forked from 0xeb/copilot-sdk-cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtypes.hpp
More file actions
2166 lines (1865 loc) · 67.9 KB
/
Copy pathtypes.hpp
File metadata and controls
2166 lines (1865 loc) · 67.9 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) 2025 Elias Bachaalany
// SPDX-License-Identifier: MIT
#pragma once
#include <chrono>
#include <cstdlib>
#include <functional>
#include <map>
#include <memory>
#include <nlohmann/json.hpp>
#include <optional>
#include <string>
#include <variant>
#include <vector>
namespace copilot
{
// =============================================================================
// Type Aliases
// =============================================================================
/// JSON type alias for cleaner API
using json = nlohmann::json;
// Forward declarations
class Session;
struct SessionEvent;
using EventHandler = std::function<void(const SessionEvent&)>;
// =============================================================================
// Protocol Version
// =============================================================================
/// Maximum SDK protocol version supported (matches copilot-agent-runtime server).
/// Upstream nodejs SDK_PROTOCOL_VERSION = 3 since v0.1.24-series.
inline constexpr int kSdkProtocolVersion = 3;
/// Minimum SDK protocol version this SDK can communicate with.
/// Older servers (reporting < kMinProtocolVersion) are rejected.
inline constexpr int kMinProtocolVersion = 2;
// =============================================================================
// Enums
// =============================================================================
/// Connection state of the client
enum class ConnectionState
{
Disconnected,
Connecting,
Connected,
Error
};
/// System message mode for session configuration
enum class SystemMessageMode
{
Append,
Replace,
Customize
};
/// Section override action for system message customization
enum class SectionOverrideAction
{
Replace,
Remove,
Append,
Prepend,
Transform
};
/// OAuth grant type for an MCP HTTP server
enum class McpHttpServerConfigOauthGrantType
{
AuthorizationCode,
ClientCredentials
};
// JSON enum serialization
NLOHMANN_JSON_SERIALIZE_ENUM(
ConnectionState,
{
{ConnectionState::Disconnected, "disconnected"},
{ConnectionState::Connecting, "connecting"},
{ConnectionState::Connected, "connected"},
{ConnectionState::Error, "error"},
}
)
NLOHMANN_JSON_SERIALIZE_ENUM(
SystemMessageMode,
{
{SystemMessageMode::Append, "append"},
{SystemMessageMode::Replace, "replace"},
{SystemMessageMode::Customize, "customize"},
}
)
NLOHMANN_JSON_SERIALIZE_ENUM(
SectionOverrideAction,
{
{SectionOverrideAction::Replace, "replace"},
{SectionOverrideAction::Remove, "remove"},
{SectionOverrideAction::Append, "append"},
{SectionOverrideAction::Prepend, "prepend"},
{SectionOverrideAction::Transform, "transform"},
}
)
NLOHMANN_JSON_SERIALIZE_ENUM(
McpHttpServerConfigOauthGrantType,
{
{McpHttpServerConfigOauthGrantType::AuthorizationCode, "authorization_code"},
{McpHttpServerConfigOauthGrantType::ClientCredentials, "client_credentials"},
}
)
/// Log level for the CLI
enum class LogLevel
{
None,
Error,
Warning,
Info,
Debug,
All
};
NLOHMANN_JSON_SERIALIZE_ENUM(
LogLevel,
{
{LogLevel::None, "none"},
{LogLevel::Error, "error"},
{LogLevel::Warning, "warning"},
{LogLevel::Info, "info"},
{LogLevel::Debug, "debug"},
{LogLevel::All, "all"},
}
)
/// Result type for tool execution
enum class ToolResultType
{
Success,
Failure,
Rejected,
Denied,
Timeout, ///< Added upstream in v0.1.49 series.
};
NLOHMANN_JSON_SERIALIZE_ENUM(
ToolResultType,
{
{ToolResultType::Success, "success"},
{ToolResultType::Failure, "failure"},
{ToolResultType::Rejected, "rejected"},
{ToolResultType::Denied, "denied"},
{ToolResultType::Timeout, "timeout"},
}
)
/// Reasoning effort level for model inference
enum class ReasoningEffort
{
Low,
Medium,
High,
XHigh
};
NLOHMANN_JSON_SERIALIZE_ENUM(
ReasoningEffort,
{
{ReasoningEffort::Low, "low"},
{ReasoningEffort::Medium, "medium"},
{ReasoningEffort::High, "high"},
{ReasoningEffort::XHigh, "xhigh"},
}
)
// =============================================================================
// Tool Types
// =============================================================================
/// Binary result from a tool execution
struct ToolBinaryResult
{
std::string data;
std::string mime_type;
std::string type;
std::optional<std::string> description;
};
inline void to_json(json& j, const ToolBinaryResult& r)
{
j = json{{"data", r.data}, {"mimeType", r.mime_type}, {"type", r.type}};
if (r.description)
j["description"] = *r.description;
}
inline void from_json(const json& j, ToolBinaryResult& r)
{
j.at("data").get_to(r.data);
j.at("mimeType").get_to(r.mime_type);
j.at("type").get_to(r.type);
if (j.contains("description"))
r.description = j.at("description").get<std::string>();
}
/// Result object returned from tool execution
struct ToolResultObject
{
std::string text_result_for_llm;
std::optional<std::vector<ToolBinaryResult>> binary_results_for_llm;
ToolResultType result_type = ToolResultType::Success;
std::optional<std::string> error;
std::optional<std::string> session_log;
std::optional<std::map<std::string, json>> tool_telemetry;
};
inline void to_json(json& j, const ToolResultObject& r)
{
j = json{{"textResultForLlm", r.text_result_for_llm}, {"resultType", r.result_type}};
if (r.binary_results_for_llm)
j["binaryResultsForLlm"] = *r.binary_results_for_llm;
if (r.error)
j["error"] = *r.error;
if (r.session_log)
j["sessionLog"] = *r.session_log;
if (r.tool_telemetry)
j["toolTelemetry"] = *r.tool_telemetry;
}
inline void from_json(const json& j, ToolResultObject& r)
{
j.at("textResultForLlm").get_to(r.text_result_for_llm);
if (j.contains("resultType"))
j.at("resultType").get_to(r.result_type);
if (j.contains("binaryResultsForLlm"))
r.binary_results_for_llm = j.at("binaryResultsForLlm").get<std::vector<ToolBinaryResult>>();
if (j.contains("error"))
r.error = j.at("error").get<std::string>();
if (j.contains("sessionLog"))
r.session_log = j.at("sessionLog").get<std::string>();
if (j.contains("toolTelemetry"))
r.tool_telemetry = j.at("toolTelemetry").get<std::map<std::string, json>>();
}
/// Information about a tool invocation from the server
struct ToolInvocation
{
std::string session_id;
std::string tool_call_id;
std::string tool_name;
std::optional<json> arguments;
};
/// Tool handler function type
using ToolHandler = std::function<ToolResultObject(const ToolInvocation&)>;
// =============================================================================
// Permission Types
// =============================================================================
/// Permission request from the server
struct PermissionRequest
{
std::string kind;
std::optional<std::string> tool_call_id;
std::map<std::string, json> extension_data;
};
inline void to_json(json& j, const PermissionRequest& r)
{
j = json{{"kind", r.kind}};
if (r.tool_call_id)
j["toolCallId"] = *r.tool_call_id;
for (const auto& [k, v] : r.extension_data)
j[k] = v;
}
inline void from_json(const json& j, PermissionRequest& r)
{
j.at("kind").get_to(r.kind);
if (j.contains("toolCallId"))
r.tool_call_id = j.at("toolCallId").get<std::string>();
// Collect extension data (all fields except kind and toolCallId)
for (auto& [k, v] : j.items())
if (k != "kind" && k != "toolCallId")
r.extension_data[k] = v;
}
/// Result of a permission request (response to CLI)
struct PermissionRequestResult
{
std::string kind; // e.g., "approved", "denied-no-approval-rule-and-could-not-request-from-user"
std::optional<std::vector<json>> rules;
};
inline void to_json(json& j, const PermissionRequestResult& r)
{
j = json{{"kind", r.kind}};
if (r.rules)
j["rules"] = *r.rules;
}
inline void from_json(const json& j, PermissionRequestResult& r)
{
j.at("kind").get_to(r.kind);
if (j.contains("rules"))
r.rules = j.at("rules").get<std::vector<json>>();
}
/// Context for permission invocation
struct PermissionInvocation
{
std::string session_id;
};
/// Permission handler function type
using PermissionHandler = std::function<PermissionRequestResult(const PermissionRequest& request)>;
// =============================================================================
// User Input Types
// =============================================================================
/// Request for user input from the agent (ask_user tool)
struct UserInputRequest
{
std::string question;
std::optional<std::vector<std::string>> choices;
std::optional<bool> allow_freeform;
};
inline void from_json(const json& j, UserInputRequest& r)
{
j.at("question").get_to(r.question);
if (j.contains("choices") && !j["choices"].is_null())
r.choices = j.at("choices").get<std::vector<std::string>>();
if (j.contains("allowFreeform") && !j["allowFreeform"].is_null())
r.allow_freeform = j.at("allowFreeform").get<bool>();
}
inline void to_json(json& j, const UserInputRequest& r)
{
j = json{{"question", r.question}};
if (r.choices)
j["choices"] = *r.choices;
if (r.allow_freeform)
j["allowFreeform"] = *r.allow_freeform;
}
/// Response to a user input request
struct UserInputResponse
{
std::string answer;
bool was_freeform = false;
};
inline void from_json(const json& j, UserInputResponse& r)
{
j.at("answer").get_to(r.answer);
if (j.contains("wasFreeform"))
j.at("wasFreeform").get_to(r.was_freeform);
}
inline void to_json(json& j, const UserInputResponse& r)
{
j = json{{"answer", r.answer}, {"wasFreeform", r.was_freeform}};
}
/// Context for a user input request invocation
struct UserInputInvocation
{
std::string session_id;
};
/// Handler for user input requests from the agent
using UserInputHandler = std::function<UserInputResponse(const UserInputRequest&, const UserInputInvocation&)>;
// =============================================================================
// Elicitation Types
// =============================================================================
/// Elicitation display mode
enum class ElicitationRequestedMode
{
Form,
Url
};
NLOHMANN_JSON_SERIALIZE_ENUM(
ElicitationRequestedMode,
{
{ElicitationRequestedMode::Form, "form"},
{ElicitationRequestedMode::Url, "url"},
}
)
/// JSON Schema for elicitation form fields
struct ElicitationSchema
{
std::string type = "object";
std::optional<std::map<std::string, json>> properties;
std::optional<std::vector<std::string>> required;
};
inline void to_json(json& j, const ElicitationSchema& s)
{
j = json{{"type", s.type}};
if (s.properties)
j["properties"] = *s.properties;
if (s.required)
j["required"] = *s.required;
}
inline void from_json(const json& j, ElicitationSchema& s)
{
if (j.contains("type"))
j.at("type").get_to(s.type);
if (j.contains("properties"))
s.properties = j.at("properties").get<std::map<std::string, json>>();
if (j.contains("required"))
s.required = j.at("required").get<std::vector<std::string>>();
}
/// User action for elicitation response
enum class ElicitationAction
{
Accept,
Decline,
Cancel
};
NLOHMANN_JSON_SERIALIZE_ENUM(
ElicitationAction,
{
{ElicitationAction::Accept, "accept"},
{ElicitationAction::Decline, "decline"},
{ElicitationAction::Cancel, "cancel"},
}
)
/// Context for an elicitation request from the server
struct ElicitationContext
{
std::string session_id;
std::string message;
std::optional<ElicitationSchema> requested_schema;
std::optional<ElicitationRequestedMode> mode;
std::optional<std::string> elicitation_source;
std::optional<std::string> url;
};
inline void from_json(const json& j, ElicitationContext& c)
{
if (j.contains("sessionId"))
j.at("sessionId").get_to(c.session_id);
j.at("message").get_to(c.message);
if (j.contains("requestedSchema") && !j["requestedSchema"].is_null())
c.requested_schema = j.at("requestedSchema").get<ElicitationSchema>();
if (j.contains("mode") && !j["mode"].is_null())
c.mode = j.at("mode").get<ElicitationRequestedMode>();
if (j.contains("elicitationSource") && !j["elicitationSource"].is_null())
c.elicitation_source = j.at("elicitationSource").get<std::string>();
if (j.contains("url") && !j["url"].is_null())
c.url = j.at("url").get<std::string>();
}
inline void to_json(json& j, const ElicitationContext& c)
{
j = json{{"message", c.message}};
if (!c.session_id.empty())
j["sessionId"] = c.session_id;
if (c.requested_schema)
j["requestedSchema"] = *c.requested_schema;
if (c.mode)
j["mode"] = *c.mode;
if (c.elicitation_source)
j["elicitationSource"] = *c.elicitation_source;
if (c.url)
j["url"] = *c.url;
}
/// Result returned from an elicitation dialog
struct ElicitationResult
{
ElicitationAction action = ElicitationAction::Cancel;
std::optional<std::map<std::string, json>> content;
};
inline void to_json(json& j, const ElicitationResult& r)
{
j = json{{"action", r.action}};
if (r.content)
j["content"] = *r.content;
}
inline void from_json(const json& j, ElicitationResult& r)
{
j.at("action").get_to(r.action);
if (j.contains("content") && !j["content"].is_null())
r.content = j.at("content").get<std::map<std::string, json>>();
}
/// Elicitation handler function type
using ElicitationHandler = std::function<ElicitationResult(const ElicitationContext&)>;
// =============================================================================
// Exit Plan Mode Types
// =============================================================================
/// Request to exit plan mode
struct ExitPlanModeRequest
{
std::string summary;
std::optional<std::string> plan_content;
std::vector<std::string> actions;
std::string recommended_action = "autopilot";
};
inline void from_json(const json& j, ExitPlanModeRequest& r)
{
j.at("summary").get_to(r.summary);
if (j.contains("planContent") && !j["planContent"].is_null())
r.plan_content = j.at("planContent").get<std::string>();
if (j.contains("actions"))
r.actions = j.at("actions").get<std::vector<std::string>>();
if (j.contains("recommendedAction"))
j.at("recommendedAction").get_to(r.recommended_action);
}
inline void to_json(json& j, const ExitPlanModeRequest& r)
{
j = json{{"summary", r.summary}, {"recommendedAction", r.recommended_action}};
if (r.plan_content)
j["planContent"] = *r.plan_content;
if (!r.actions.empty())
j["actions"] = r.actions;
}
/// Response to an exit-plan-mode request
struct ExitPlanModeResult
{
bool approved = true;
std::optional<std::string> selected_action;
std::optional<std::string> feedback;
};
inline void to_json(json& j, const ExitPlanModeResult& r)
{
j = json{{"approved", r.approved}};
if (r.selected_action)
j["selectedAction"] = *r.selected_action;
if (r.feedback)
j["feedback"] = *r.feedback;
}
inline void from_json(const json& j, ExitPlanModeResult& r)
{
j.at("approved").get_to(r.approved);
if (j.contains("selectedAction") && !j["selectedAction"].is_null())
r.selected_action = j.at("selectedAction").get<std::string>();
if (j.contains("feedback") && !j["feedback"].is_null())
r.feedback = j.at("feedback").get<std::string>();
}
/// Context for exit-plan-mode invocation
struct ExitPlanModeInvocation
{
std::string session_id;
};
/// Exit plan mode handler function type
using ExitPlanModeHandler =
std::function<ExitPlanModeResult(const ExitPlanModeRequest&, const ExitPlanModeInvocation&)>;
// =============================================================================
// Auto Mode Switch Types
// =============================================================================
/// Request to switch to auto mode after a rate limit
struct AutoModeSwitchRequest
{
std::optional<std::string> error_code;
std::optional<double> retry_after_seconds;
};
inline void from_json(const json& j, AutoModeSwitchRequest& r)
{
if (j.contains("errorCode") && !j["errorCode"].is_null())
r.error_code = j.at("errorCode").get<std::string>();
if (j.contains("retryAfterSeconds") && !j["retryAfterSeconds"].is_null())
r.retry_after_seconds = j.at("retryAfterSeconds").get<double>();
}
inline void to_json(json& j, const AutoModeSwitchRequest& r)
{
j = json::object();
if (r.error_code)
j["errorCode"] = *r.error_code;
if (r.retry_after_seconds)
j["retryAfterSeconds"] = *r.retry_after_seconds;
}
/// Response to auto-mode-switch request
enum class AutoModeSwitchResponse
{
Yes,
YesAlways,
No
};
NLOHMANN_JSON_SERIALIZE_ENUM(
AutoModeSwitchResponse,
{
{AutoModeSwitchResponse::Yes, "yes"},
{AutoModeSwitchResponse::YesAlways, "yes_always"},
{AutoModeSwitchResponse::No, "no"},
}
)
/// Context for auto-mode-switch invocation
struct AutoModeSwitchInvocation
{
std::string session_id;
};
/// Auto mode switch handler function type
using AutoModeSwitchHandler =
std::function<AutoModeSwitchResponse(const AutoModeSwitchRequest&, const AutoModeSwitchInvocation&)>;
// =============================================================================
// Hook Handler Types
// =============================================================================
/// Context for a hook invocation
struct HookInvocation
{
std::string session_id;
};
/// Input for a pre-tool-use hook
struct PreToolUseHookInput
{
int64_t timestamp = 0;
std::string cwd;
std::string tool_name;
std::optional<json> tool_args;
};
inline void from_json(const json& j, PreToolUseHookInput& h)
{
if (j.contains("timestamp")) j.at("timestamp").get_to(h.timestamp);
if (j.contains("cwd")) j.at("cwd").get_to(h.cwd);
if (j.contains("toolName")) j.at("toolName").get_to(h.tool_name);
if (j.contains("toolArgs") && !j["toolArgs"].is_null()) h.tool_args = j["toolArgs"];
}
/// Output for a pre-tool-use hook
struct PreToolUseHookOutput
{
std::optional<std::string> permission_decision; ///< "allow", "deny", or "ask"
std::optional<std::string> permission_decision_reason;
std::optional<json> modified_args;
std::optional<std::string> additional_context;
std::optional<bool> suppress_output;
};
inline void to_json(json& j, const PreToolUseHookOutput& h)
{
j = json::object();
if (h.permission_decision) j["permissionDecision"] = *h.permission_decision;
if (h.permission_decision_reason) j["permissionDecisionReason"] = *h.permission_decision_reason;
if (h.modified_args) j["modifiedArgs"] = *h.modified_args;
if (h.additional_context) j["additionalContext"] = *h.additional_context;
if (h.suppress_output) j["suppressOutput"] = *h.suppress_output;
}
using PreToolUseHandler = std::function<std::optional<PreToolUseHookOutput>(const PreToolUseHookInput&, const HookInvocation&)>;
/// Input for a post-tool-use hook
struct PostToolUseHookInput
{
int64_t timestamp = 0;
std::string cwd;
std::string tool_name;
std::optional<json> tool_args;
std::optional<json> tool_result;
};
inline void from_json(const json& j, PostToolUseHookInput& h)
{
if (j.contains("timestamp")) j.at("timestamp").get_to(h.timestamp);
if (j.contains("cwd")) j.at("cwd").get_to(h.cwd);
if (j.contains("toolName")) j.at("toolName").get_to(h.tool_name);
if (j.contains("toolArgs") && !j["toolArgs"].is_null()) h.tool_args = j["toolArgs"];
if (j.contains("toolResult") && !j["toolResult"].is_null()) h.tool_result = j["toolResult"];
}
/// Output for a post-tool-use hook
struct PostToolUseHookOutput
{
std::optional<json> modified_result;
std::optional<std::string> additional_context;
std::optional<bool> suppress_output;
};
inline void to_json(json& j, const PostToolUseHookOutput& h)
{
j = json::object();
if (h.modified_result) j["modifiedResult"] = *h.modified_result;
if (h.additional_context) j["additionalContext"] = *h.additional_context;
if (h.suppress_output) j["suppressOutput"] = *h.suppress_output;
}
using PostToolUseHandler = std::function<std::optional<PostToolUseHookOutput>(const PostToolUseHookInput&, const HookInvocation&)>;
/// Input for a user-prompt-submitted hook
struct UserPromptSubmittedHookInput
{
int64_t timestamp = 0;
std::string cwd;
std::string prompt;
};
inline void from_json(const json& j, UserPromptSubmittedHookInput& h)
{
if (j.contains("timestamp")) j.at("timestamp").get_to(h.timestamp);
if (j.contains("cwd")) j.at("cwd").get_to(h.cwd);
if (j.contains("prompt")) j.at("prompt").get_to(h.prompt);
}
/// Output for a user-prompt-submitted hook
struct UserPromptSubmittedHookOutput
{
std::optional<std::string> modified_prompt;
std::optional<std::string> additional_context;
std::optional<bool> suppress_output;
};
inline void to_json(json& j, const UserPromptSubmittedHookOutput& h)
{
j = json::object();
if (h.modified_prompt) j["modifiedPrompt"] = *h.modified_prompt;
if (h.additional_context) j["additionalContext"] = *h.additional_context;
if (h.suppress_output) j["suppressOutput"] = *h.suppress_output;
}
using UserPromptSubmittedHandler = std::function<std::optional<UserPromptSubmittedHookOutput>(const UserPromptSubmittedHookInput&, const HookInvocation&)>;
/// Input for a session-start hook
struct SessionStartHookInput
{
int64_t timestamp = 0;
std::string cwd;
std::string source; ///< "startup", "resume", or "new"
std::optional<std::string> initial_prompt;
};
inline void from_json(const json& j, SessionStartHookInput& h)
{
if (j.contains("timestamp")) j.at("timestamp").get_to(h.timestamp);
if (j.contains("cwd")) j.at("cwd").get_to(h.cwd);
if (j.contains("source")) j.at("source").get_to(h.source);
if (j.contains("initialPrompt") && !j["initialPrompt"].is_null())
h.initial_prompt = j.at("initialPrompt").get<std::string>();
}
/// Output for a session-start hook
struct SessionStartHookOutput
{
std::optional<std::string> additional_context;
std::optional<std::map<std::string, json>> modified_config;
};
inline void to_json(json& j, const SessionStartHookOutput& h)
{
j = json::object();
if (h.additional_context) j["additionalContext"] = *h.additional_context;
if (h.modified_config) j["modifiedConfig"] = *h.modified_config;
}
using SessionStartHandler = std::function<std::optional<SessionStartHookOutput>(const SessionStartHookInput&, const HookInvocation&)>;
/// Input for a session-end hook
struct SessionEndHookInput
{
int64_t timestamp = 0;
std::string cwd;
std::string reason; ///< "complete", "error", "abort", "timeout", or "user_exit"
std::optional<std::string> final_message;
std::optional<std::string> error;
};
inline void from_json(const json& j, SessionEndHookInput& h)
{
if (j.contains("timestamp")) j.at("timestamp").get_to(h.timestamp);
if (j.contains("cwd")) j.at("cwd").get_to(h.cwd);
if (j.contains("reason")) j.at("reason").get_to(h.reason);
if (j.contains("finalMessage") && !j["finalMessage"].is_null())
h.final_message = j.at("finalMessage").get<std::string>();
if (j.contains("error") && !j["error"].is_null())
h.error = j.at("error").get<std::string>();
}
/// Output for a session-end hook
struct SessionEndHookOutput
{
std::optional<bool> suppress_output;
std::optional<std::vector<std::string>> cleanup_actions;
std::optional<std::string> session_summary;
};
inline void to_json(json& j, const SessionEndHookOutput& h)
{
j = json::object();
if (h.suppress_output) j["suppressOutput"] = *h.suppress_output;
if (h.cleanup_actions) j["cleanupActions"] = *h.cleanup_actions;
if (h.session_summary) j["sessionSummary"] = *h.session_summary;
}
using SessionEndHandler = std::function<std::optional<SessionEndHookOutput>(const SessionEndHookInput&, const HookInvocation&)>;
/// Input for an error-occurred hook
struct ErrorOccurredHookInput
{
int64_t timestamp = 0;
std::string cwd;
std::string error;
std::string error_context; ///< "model_call", "tool_execution", "system", or "user_input"
bool recoverable = false;
};
inline void from_json(const json& j, ErrorOccurredHookInput& h)
{
if (j.contains("timestamp")) j.at("timestamp").get_to(h.timestamp);
if (j.contains("cwd")) j.at("cwd").get_to(h.cwd);
if (j.contains("error")) j.at("error").get_to(h.error);
if (j.contains("errorContext")) j.at("errorContext").get_to(h.error_context);
if (j.contains("recoverable")) j.at("recoverable").get_to(h.recoverable);
}
/// Output for an error-occurred hook
struct ErrorOccurredHookOutput
{
std::optional<bool> suppress_output;
std::optional<std::string> error_handling; ///< "retry", "skip", or "abort"
std::optional<int> retry_count;
std::optional<std::string> user_notification;
};
inline void to_json(json& j, const ErrorOccurredHookOutput& h)
{
j = json::object();
if (h.suppress_output) j["suppressOutput"] = *h.suppress_output;
if (h.error_handling) j["errorHandling"] = *h.error_handling;
if (h.retry_count) j["retryCount"] = *h.retry_count;
if (h.user_notification) j["userNotification"] = *h.user_notification;
}
using ErrorOccurredHandler = std::function<std::optional<ErrorOccurredHookOutput>(const ErrorOccurredHookInput&, const HookInvocation&)>;
/// Hook handlers configuration for a session
struct SessionHooks
{
std::optional<PreToolUseHandler> on_pre_tool_use;
std::optional<PostToolUseHandler> on_post_tool_use;
std::optional<UserPromptSubmittedHandler> on_user_prompt_submitted;
std::optional<SessionStartHandler> on_session_start;
std::optional<SessionEndHandler> on_session_end;
std::optional<ErrorOccurredHandler> on_error_occurred;
/// Returns true if any hook handler is registered
bool has_any() const
{
return on_pre_tool_use || on_post_tool_use || on_user_prompt_submitted ||
on_session_start || on_session_end || on_error_occurred;
}
};
// =============================================================================
// Configuration Types
// =============================================================================
/// Override operation for a single system prompt section
struct SectionOverride
{
SectionOverrideAction action = SectionOverrideAction::Replace;
std::optional<std::string> content;
};
inline void to_json(json& j, const SectionOverride& c)
{
j = json{{"action", c.action}};
if (c.content)
j["content"] = *c.content;
}
inline void from_json(const json& j, SectionOverride& c)
{
if (j.contains("action"))
c.action = j.at("action").get<SectionOverrideAction>();
if (j.contains("content"))
c.content = j.at("content").get<std::string>();
}
/// System message configuration
struct SystemMessageConfig
{
std::optional<SystemMessageMode> mode;
std::optional<std::string> content;
std::optional<std::map<std::string, SectionOverride>> sections;
};
inline void to_json(json& j, const SystemMessageConfig& c)
{
j = json::object();
if (c.mode)
j["mode"] = *c.mode;
if (c.content)
j["content"] = *c.content;
if (c.sections)
j["sections"] = *c.sections;
}
inline void from_json(const json& j, SystemMessageConfig& c)
{
if (j.contains("mode"))
c.mode = j.at("mode").get<SystemMessageMode>();
if (j.contains("content"))
c.content = j.at("content").get<std::string>();
if (j.contains("sections"))
c.sections = j.at("sections").get<std::map<std::string, SectionOverride>>();
}
/// Azure-specific provider options
struct AzureOptions
{
std::optional<std::string> api_version;
};
inline void to_json(json& j, const AzureOptions& o)
{
j = json::object();
if (o.api_version)
j["apiVersion"] = *o.api_version;
}
inline void from_json(const json& j, AzureOptions& o)
{
if (j.contains("apiVersion"))
o.api_version = j.at("apiVersion").get<std::string>();
}
/// Provider configuration for BYOK (Bring Your Own Key)
struct ProviderConfig
{
std::optional<std::string> type;
std::optional<std::string> wire_api;
std::string base_url;
std::optional<std::string> api_key;
std::optional<std::string> bearer_token;
std::optional<AzureOptions> azure;
std::optional<std::map<std::string, std::string>> headers;
std::optional<std::string> model_id;
std::optional<std::string> wire_model;
std::optional<int> max_input_tokens;
std::optional<int> max_output_tokens;
// ─────────────────────────────────────────────────────────────────────────
// Environment Variable Support
// ─────────────────────────────────────────────────────────────────────────
/// Environment variable names for BYOK configuration
static constexpr const char* ENV_API_KEY = "COPILOT_SDK_BYOK_API_KEY";
static constexpr const char* ENV_BASE_URL = "COPILOT_SDK_BYOK_BASE_URL";
static constexpr const char* ENV_PROVIDER_TYPE = "COPILOT_SDK_BYOK_PROVIDER_TYPE";
static constexpr const char* ENV_MODEL = "COPILOT_SDK_BYOK_MODEL";
/// Check if BYOK environment variables are configured
/// @return true if COPILOT_SDK_BYOK_API_KEY is set and non-empty
static bool is_env_configured()
{
const char* key = std::getenv(ENV_API_KEY);
return key != nullptr && key[0] != '\0';
}
/// Load ProviderConfig from COPILOT_SDK_BYOK_* environment variables
/// @return ProviderConfig if API key is set, nullopt otherwise
static std::optional<ProviderConfig> from_env()
{
if (!is_env_configured())
return std::nullopt;
ProviderConfig config;