Repository navigation
Expand file tree
/
Copy pathsession.cpp
More file actions
1123 lines (1005 loc) · 35.8 KB
/
Copy pathsession.cpp
File metadata and controls
1123 lines (1005 loc) · 35.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2025 Elias Bachaalany
// SPDX-License-Identifier: MIT
#include <copilot/client.hpp>
#include <copilot/canvas.hpp>
#include <copilot/factory.hpp>
#include <copilot/rpc_methods.hpp>
#include <copilot/session.hpp>
#include <condition_variable>
#include <thread>
namespace copilot
{
json build_mcp_auth_response(
const McpAuthHandler& handler,
const json& request,
const std::string& session_id)
{
try
{
if (handler)
{
if (auto token = handler(request, session_id))
{
json result{
{"kind", "token"},
{"accessToken", token->access_token},
};
if (token->token_type)
result["tokenType"] = *token->token_type;
if (token->expires_in)
result["expiresIn"] = *token->expires_in;
return result;
}
}
}
catch (...)
{
}
return json{{"kind", "cancelled"}};
}
// =============================================================================
// Constructor / Destructor
// =============================================================================
Session::Session(const std::string& session_id, Client* client,
const std::optional<std::string>& workspace_path,
SessionCapabilities capabilities,
bool managed_settings_enabled)
: session_id_(session_id),
client_(client),
workspace_path_(workspace_path),
capabilities_(std::move(capabilities)),
managed_settings_enabled_(managed_settings_enabled)
{
}
Session::~Session()
{
std::vector<std::future<void>> tasks;
{
std::lock_guard<std::mutex> lock(background_tasks_mutex_);
tasks.swap(background_tasks_);
}
for (auto& task : tasks)
if (task.valid())
task.wait();
}
void Session::cancel_pending_tool_invocations() noexcept
{
tool_invocations_cancelled_.store(true, std::memory_order_release);
}
int Session::pending_tool_invocations() const noexcept
{
return pending_tool_invocations_.load(std::memory_order_relaxed);
}
void Session::enqueue_background(std::function<void()> task)
{
auto future = std::async(std::launch::async, std::move(task));
std::lock_guard<std::mutex> lock(background_tasks_mutex_);
background_tasks_.push_back(std::move(future));
}
void Session::set_initial_state(
std::optional<std::string> workspace_path,
SessionCapabilities capabilities)
{
workspace_path_ = std::move(workspace_path);
capabilities_ = std::move(capabilities);
}
// =============================================================================
// Messaging
// =============================================================================
std::future<std::string> Session::send(MessageOptions options)
{
return std::async(
std::launch::async,
[this, options = std::move(options)]()
{
json params = options;
params["sessionId"] = session_id_;
params.update(client_->trace_context());
auto response = client_->rpc_client()->invoke(copilot::rpc::methods::kSessionSend, params).get();
return response["messageId"].get<std::string>();
}
);
}
std::future<void> Session::abort()
{
return std::async(
std::launch::async,
[this]()
{
json params;
params["sessionId"] = session_id_;
client_->rpc_client()->invoke(copilot::rpc::methods::kSessionAbort, params).get();
}
);
}
std::future<std::vector<SessionEvent>> Session::get_messages()
{
return std::async(
std::launch::async,
[this]()
{
json params;
params["sessionId"] = session_id_;
auto response = client_->rpc_client()->invoke(copilot::rpc::methods::kSessionGetMessages, params).get();
std::vector<SessionEvent> events;
if (response.contains("events") && response["events"].is_array())
for (const auto& event_json : response["events"])
events.push_back(parse_session_event(event_json));
return events;
}
);
}
std::future<std::optional<SessionEvent>> Session::send_and_wait(
MessageOptions options,
std::chrono::seconds timeout)
{
return std::async(
std::launch::async,
[this, options = std::move(options), timeout]() -> std::optional<SessionEvent>
{
std::mutex mtx;
std::condition_variable cv;
bool done = false;
std::optional<SessionEvent> last_assistant_message;
std::optional<std::string> error_message;
// Subscribe to events
auto subscription = on(
[&](const SessionEvent& evt)
{
std::lock_guard<std::mutex> lock(mtx);
if (evt.type == SessionEventType::AssistantMessage)
{
last_assistant_message = evt;
}
else if (evt.type == SessionEventType::SessionIdle)
{
done = true;
cv.notify_one();
}
else if (evt.type == SessionEventType::SessionError)
{
if (auto* data = evt.try_as<SessionErrorData>())
error_message = data->message;
else
error_message = "Session error";
done = true;
cv.notify_one();
}
}
);
// Send the message
send(options).get();
// Wait for completion or timeout
{
std::unique_lock<std::mutex> lock(mtx);
if (!cv.wait_for(lock, timeout, [&] { return done; }))
{
throw std::runtime_error("Timeout waiting for session to become idle");
}
}
if (error_message.has_value())
{
throw std::runtime_error("Session error: " + *error_message);
}
return last_assistant_message;
}
);
}
// =============================================================================
// Event Handling
// =============================================================================
Subscription Session::on(EventHandler handler)
{
std::lock_guard<std::mutex> lock(handlers_mutex_);
int id = next_handler_id_++;
event_handlers_.emplace_back(id, std::move(handler));
// Return subscription that removes this handler when destroyed
// Use weak_ptr to avoid UAF if Subscription outlives Session
std::weak_ptr<Session> weak_self = shared_from_this();
return Subscription(
[weak_self, id]()
{
if (auto self = weak_self.lock())
{
std::lock_guard<std::mutex> lock(self->handlers_mutex_);
self->event_handlers_.erase(
std::remove_if(
self->event_handlers_.begin(),
self->event_handlers_.end(),
[id](const auto& pair) { return pair.first == id; }
),
self->event_handlers_.end()
);
}
}
);
}
void Session::register_persistent_event_handler(EventHandler handler)
{
auto subscription = on(std::move(handler));
std::lock_guard<std::mutex> lock(owned_event_subscriptions_mutex_);
owned_event_subscriptions_.push_back(std::move(subscription));
}
void Session::dispatch_event(const SessionEvent& event)
{
if (event.type == SessionEventType::ExternalToolRequested)
{
const auto* data = event.try_as<ExternalToolRequestedData>();
if (data)
{
Tool tool;
{
std::lock_guard<std::mutex> lock(tools_mutex_);
const auto it = tools_.find(data->tool_name);
if (it != tools_.end())
tool = it->second;
}
if (tool.handler)
{
const auto request = *data;
pending_tool_invocations_.fetch_add(1, std::memory_order_relaxed);
enqueue_background(
[this, tool = std::move(tool), request]
{
// Answering after the connection has gone means an RPC into
// a transport being torn down. The handler itself cannot be
// interrupted, so the result is simply dropped.
const auto answer = [this](json payload)
{
if (tool_invocations_cancelled_.load(std::memory_order_acquire))
return;
invoke("session.tools.handlePendingToolCall", std::move(payload)).get();
};
try
{
ToolInvocation invocation{
.session_id = session_id_,
.tool_call_id = request.tool_call_id,
.tool_name = request.tool_name,
.arguments = request.arguments,
.traceparent = request.traceparent,
.tracestate = request.tracestate,
};
const auto result = tool.handler(invocation);
answer(json{{"requestId", request.request_id}, {"result", result}});
}
catch (const std::exception& error)
{
try
{
answer(json{
{"requestId", request.request_id},
{"error", error.what()},
});
}
catch (...)
{
}
}
pending_tool_invocations_.fetch_sub(1, std::memory_order_relaxed);
});
}
}
}
if (event.type == SessionEventType::PermissionRequested &&
(permission_handler_ || permission_handler_with_context_))
{
const auto* data = event.try_as<PermissionRequestedData>();
if (data && !data->resolved_by_hook.value_or(false))
{
const auto request_id = data->request_id;
const auto request_json = data->permission_request;
enqueue_background(
[this, request_id, request_json]
{
try
{
const auto request = request_json.get<PermissionRequest>();
auto result = handle_permission_request(request);
if (result.kind == "no-result")
return;
if (result.kind == "approved")
result.kind = "approve-once";
json params{{"requestId", request_id}, {"result", json(result)}};
if (result.decision_context)
params["decisionContext"] = *result.decision_context;
invoke(
"session.permissions.handlePendingPermissionRequest",
std::move(params)).get();
}
catch (...)
{
try
{
invoke(
"session.permissions.handlePendingPermissionRequest",
json{
{"requestId", request_id},
{"result", {{"kind", "user-not-available"}}},
}).get();
}
catch (...)
{
}
}
});
}
}
if (event.type == SessionEventType::UserInputRequested && user_input_handler_)
{
const auto* data = event.try_as<UserInputRequestedData>();
if (data)
{
const auto value = *data;
enqueue_background(
[this, value]
{
UserInputRequest request{
.question = value.question,
.choices = value.choices,
.allow_freeform = value.allow_freeform,
};
const auto response = handle_user_input_request(request);
invoke(
"session.ui.handlePendingUserInput",
json{
{"requestId", value.request_id},
{"response", response},
}).get();
});
}
}
if (event.type == SessionEventType::McpOauthRequired && mcp_auth_handler_)
{
const auto* data = event.try_as<McpOauthRequiredData>();
if (data)
{
json request{
{"requestId", data->request_id},
{"serverName", data->server_name},
{"serverUrl", data->server_url},
};
if (data->reason)
request["reason"] = *data->reason;
if (data->www_authenticate_params)
request["wwwAuthenticateParams"] = *data->www_authenticate_params;
if (data->resource_metadata)
request["resourceMetadata"] = *data->resource_metadata;
if (data->static_client_config)
{
json config{{"clientId", data->static_client_config->client_id}};
if (data->static_client_config->client_secret)
config["clientSecret"] = *data->static_client_config->client_secret;
if (data->static_client_config->grant_type)
config["grantType"] = *data->static_client_config->grant_type;
if (data->static_client_config->public_client)
config["publicClient"] = *data->static_client_config->public_client;
request["staticClientConfig"] = std::move(config);
}
const auto handler = mcp_auth_handler_;
const auto request_id = data->request_id;
enqueue_background(
[this, handler, request = std::move(request), request_id]
{
const json result =
build_mcp_auth_response(handler, request, session_id_);
if (!client_)
return;
try
{
invoke(
"session.mcp.oauth.handlePendingRequest",
json{{"requestId", request_id}, {"result", result}}).get();
}
catch (...)
{
}
});
}
}
std::vector<EventHandler> handlers_copy;
{
std::lock_guard<std::mutex> lock(handlers_mutex_);
handlers_copy.reserve(event_handlers_.size());
for (const auto& [id, handler] : event_handlers_)
handlers_copy.push_back(handler);
}
for (const auto& handler : handlers_copy)
{
try
{
handler(event);
}
catch (...)
{
// Ignore handler exceptions to prevent one handler from
// breaking others
}
}
}
// =============================================================================
// Tool Management
// =============================================================================
void Session::register_tool(Tool tool)
{
std::lock_guard<std::mutex> lock(tools_mutex_);
tools_[tool.name] = std::move(tool);
}
void Session::register_tools(const std::vector<Tool>& tools)
{
std::lock_guard<std::mutex> lock(tools_mutex_);
for (const auto& tool : tools)
tools_[tool.name] = tool;
}
const Tool* Session::get_tool(const std::string& name) const
{
std::lock_guard<std::mutex> lock(tools_mutex_);
auto it = tools_.find(name);
return (it != tools_.end()) ? &it->second : nullptr;
}
void Session::register_canvases(
const std::vector<std::shared_ptr<Canvas>>& canvases)
{
std::lock_guard<std::mutex> lock(tools_mutex_);
for (const auto& canvas : canvases)
if (canvas)
canvases_[canvas->id()] = canvas;
}
json Session::handle_canvas_request(
const std::string& method, const json& params)
{
const auto canvas_id = params.value("canvasId", "");
std::shared_ptr<Canvas> canvas;
{
std::lock_guard<std::mutex> lock(tools_mutex_);
const auto it = canvases_.find(canvas_id);
if (it == canvases_.end())
throw CanvasError("canvas_not_found", "Unknown canvas " + canvas_id);
canvas = it->second;
}
try
{
if (method == "canvas.open")
return canvas->handle_open(params);
if (method == "canvas.close")
{
canvas->handle_close(params);
return json::object();
}
return canvas->handle_action(params.value("actionName", ""), params);
}
catch (const CanvasError& error)
{
return json{{"error", {{"code", error.code()}, {"message", error.what()}}}};
}
}
void Session::register_factories(
const std::vector<std::shared_ptr<FactoryHandle>>& factories)
{
std::lock_guard<std::mutex> lock(tools_mutex_);
for (const auto& factory : factories)
{
if (!factory || !factory->meta.contains("name"))
continue;
factories_[factory->meta.at("name").get<std::string>()] = factory;
}
}
json Session::handle_factory_request(
const std::string& method, const json& params)
{
if (method == "factory.abort")
return json::object();
const auto name = params.value("name", "");
std::shared_ptr<FactoryHandle> factory;
{
std::lock_guard<std::mutex> lock(tools_mutex_);
const auto it = factories_.find(name);
if (it == factories_.end())
throw std::runtime_error("Unknown factory " + name);
factory = it->second;
}
json context = params;
context["sessionId"] = session_id_;
return json{{"result", factory->run(context)}};
}
// =============================================================================
// Permission Handling
// =============================================================================
void Session::register_permission_handler(PermissionHandler handler)
{
permission_handler_ = std::move(handler);
}
void Session::register_permission_handler(PermissionHandlerWithContext handler)
{
permission_handler_with_context_ = std::move(handler);
}
void Session::register_mcp_auth_handler(McpAuthHandler handler)
{
mcp_auth_handler_ = std::move(handler);
}
PermissionRequestResult Session::handle_permission_request(const PermissionRequest& request)
{
PermissionInvocation invocation{
.session_id = session_id_,
.managed_settings_enabled = managed_settings_enabled_,
};
if (permission_handler_with_context_)
return permission_handler_with_context_(request, invocation);
if (permission_handler_)
return permission_handler_(request);
return PermissionRequestResult::no_result();
}
// =============================================================================
// User Input Handling
// =============================================================================
void Session::register_user_input_handler(UserInputHandler handler)
{
std::lock_guard<std::mutex> lock(user_input_mutex_);
user_input_handler_ = std::move(handler);
}
UserInputResponse Session::handle_user_input_request(const UserInputRequest& request)
{
UserInputHandler handler;
{
std::lock_guard<std::mutex> lock(user_input_mutex_);
handler = user_input_handler_;
}
if (!handler)
throw std::runtime_error("No user input handler registered");
UserInputInvocation invocation;
invocation.session_id = session_id_;
return handler(request, invocation);
}
// =============================================================================
// Elicitation Handling
// =============================================================================
void Session::register_elicitation_handler(ElicitationHandler handler)
{
std::lock_guard<std::mutex> lock(elicitation_mutex_);
elicitation_handler_ = std::move(handler);
}
ElicitationResult Session::handle_elicitation_request(const ElicitationContext& context)
{
ElicitationHandler handler;
{
std::lock_guard<std::mutex> lock(elicitation_mutex_);
handler = elicitation_handler_;
}
if (!handler)
return ElicitationResult{ElicitationAction::Cancel};
return handler(context);
}
// =============================================================================
// Exit Plan Mode Handling
// =============================================================================
void Session::register_exit_plan_mode_handler(ExitPlanModeHandler handler)
{
std::lock_guard<std::mutex> lock(exit_plan_mode_mutex_);
exit_plan_mode_handler_ = std::move(handler);
}
ExitPlanModeResult Session::handle_exit_plan_mode_request(const ExitPlanModeRequest& request)
{
ExitPlanModeHandler handler;
{
std::lock_guard<std::mutex> lock(exit_plan_mode_mutex_);
handler = exit_plan_mode_handler_;
}
if (!handler)
return ExitPlanModeResult{};
ExitPlanModeInvocation invocation;
invocation.session_id = session_id_;
return handler(request, invocation);
}
// =============================================================================
// Auto Mode Switch Handling
// =============================================================================
void Session::register_auto_mode_switch_handler(AutoModeSwitchHandler handler)
{
std::lock_guard<std::mutex> lock(auto_mode_switch_mutex_);
auto_mode_switch_handler_ = std::move(handler);
}
AutoModeSwitchResponse Session::handle_auto_mode_switch_request(const AutoModeSwitchRequest& request)
{
AutoModeSwitchHandler handler;
{
std::lock_guard<std::mutex> lock(auto_mode_switch_mutex_);
handler = auto_mode_switch_handler_;
}
if (!handler)
return AutoModeSwitchResponse::No;
AutoModeSwitchInvocation invocation;
invocation.session_id = session_id_;
return handler(request, invocation);
}
// =============================================================================
// Hooks
// =============================================================================
void Session::register_hooks(SessionHooks hooks)
{
std::lock_guard<std::mutex> lock(hooks_mutex_);
hooks_ = std::move(hooks);
}
json Session::handle_hooks_invoke(const std::string& hook_type, const json& input)
{
std::optional<SessionHooks> hooks;
{
std::lock_guard<std::mutex> lock(hooks_mutex_);
hooks = hooks_;
}
if (!hooks)
return nullptr;
HookInvocation invocation;
invocation.session_id = session_id_;
try
{
if (hook_type == "preToolUse" && hooks->on_pre_tool_use)
{
auto result = (*hooks->on_pre_tool_use)(input.get<PreToolUseHookInput>(), invocation);
if (result)
{
json output;
to_json(output, *result);
return output;
}
return nullptr;
}
else if (hook_type == "postToolUse" && hooks->on_post_tool_use)
{
auto result = (*hooks->on_post_tool_use)(input.get<PostToolUseHookInput>(), invocation);
if (result)
{
json output;
to_json(output, *result);
return output;
}
return nullptr;
}
else if (hook_type == "userPromptSubmitted" && hooks->on_user_prompt_submitted)
{
auto result = (*hooks->on_user_prompt_submitted)(input.get<UserPromptSubmittedHookInput>(), invocation);
if (result)
{
json output;
to_json(output, *result);
return output;
}
return nullptr;
}
else if (hook_type == "sessionStart" && hooks->on_session_start)
{
auto result = (*hooks->on_session_start)(input.get<SessionStartHookInput>(), invocation);
if (result)
{
json output;
to_json(output, *result);
return output;
}
return nullptr;
}
else if (hook_type == "sessionEnd" && hooks->on_session_end)
{
auto result = (*hooks->on_session_end)(input.get<SessionEndHookInput>(), invocation);
if (result)
{
json output;
to_json(output, *result);
return output;
}
return nullptr;
}
else if (hook_type == "errorOccurred" && hooks->on_error_occurred)
{
auto result = (*hooks->on_error_occurred)(input.get<ErrorOccurredHookInput>(), invocation);
if (result)
{
json output;
to_json(output, *result);
return output;
}
return nullptr;
}
const JsonHookHandler* generic = nullptr;
if (hook_type == "preMcpToolCall" && hooks->on_pre_mcp_tool_call)
generic = &*hooks->on_pre_mcp_tool_call;
else if (hook_type == "postToolUseFailure" && hooks->on_post_tool_use_failure)
generic = &*hooks->on_post_tool_use_failure;
else if (hook_type == "userPromptTransformed" && hooks->on_user_prompt_transformed)
generic = &*hooks->on_user_prompt_transformed;
else if (hook_type == "agentStop" && hooks->on_agent_stop)
generic = &*hooks->on_agent_stop;
else if (hook_type == "subagentStop" && hooks->on_subagent_stop)
generic = &*hooks->on_subagent_stop;
else if (hook_type == "permissionRequest" && hooks->on_permission_request)
generic = &*hooks->on_permission_request;
if (generic)
{
const auto result = (*generic)(input, invocation);
return result.value_or(json(nullptr));
}
}
catch (const json::exception&)
{
// Unknown or newly-null hook fields must not block session startup.
return nullptr;
}
return nullptr;
}
// =============================================================================
// Lifecycle
// =============================================================================
std::future<Session::DetachResult> Session::detach()
{
return std::async(
std::launch::async,
[this]() -> DetachResult
{
json params;
params["sessionId"] = session_id_;
const json response =
client_->rpc_client()->invoke(copilot::rpc::methods::kSessionDetach, params).get();
DetachResult result;
result.raw = response;
if (response.is_object())
{
if (const auto it = response.find("success");
it != response.end() && it->is_boolean())
result.success = it->get<bool>();
if (const auto it = response.find("error"); it != response.end() && it->is_string())
result.error = it->get<std::string>();
}
return result;
}
);
}
std::future<void> Session::destroy()
{
return std::async(
std::launch::async,
[this]()
{
// A declined detach is deliberately not raised: this runs on the
// teardown path, and failing it would leave callers unable to close
// a session the runtime already considers gone. Callers who need the
// status call detach() directly.
(void)detach().get();
}
);
}
std::future<json> Session::invoke(const std::string& method, json params)
{
return std::async(
std::launch::async,
[this, method, params = std::move(params)]() mutable
{
if (!params.is_object())
throw std::invalid_argument("session RPC params must be a JSON object");
params["sessionId"] = session_id_;
return client_->rpc_client()->invoke(method, params).get();
}
);
}
std::future<generated::api::McpServerList> Session::list_mcp_servers()
{
return invoke_typed<generated::api::McpServerList>("session.mcp.list");
}
std::future<generated::api::AuthIdentity> Session::get_current_auth_info()
{
return invoke_typed<generated::api::AuthIdentity>(
"session.gitHubAuth.getCurrentAuthInfo"
);
}
std::future<generated::api::AgentList> Session::list_agents(json params)
{
return invoke_typed<generated::api::AgentList>(
"session.agent.list", std::move(params)
);
}
std::future<generated::api::SkillList> Session::list_skills()
{
return invoke_typed<generated::api::SkillList>("session.skills.list");
}
std::future<generated::api::TaskList> Session::list_tasks()
{
return invoke_typed<generated::api::TaskList>("session.tasks.list");
}
std::future<generated::api::CommandList> Session::list_commands(json params)
{
return invoke_typed<generated::api::CommandList>(
"session.commands.list", std::move(params)
);
}
std::future<generated::api::HistoryListRewindPointsResult>
Session::list_rewind_points()
{
return invoke_typed<generated::api::HistoryListRewindPointsResult>(
"session.history.listRewindPoints"
);
}
std::future<generated::api::UsageGetMetricsResult> Session::get_usage_metrics()
{
return invoke_typed<generated::api::UsageGetMetricsResult>(
"session.usage.getMetrics"
);
}
std::future<generated::api::RemoteEnableResult> Session::enable_remote(json params)
{
return invoke_typed<generated::api::RemoteEnableResult>(
"session.remote.enable", std::move(params)
);
}
std::future<void> Session::disable_remote()
{
return std::async(
std::launch::async,
[future = invoke("session.remote.disable")]() mutable
{
future.get();
}
);
}
SessionFactoryApi Session::factory()
{
return SessionFactoryApi(*this);
}
std::future<generated::api::SandboxEnforcementStatus>
Session::get_sandbox_enforcement_status()
{
return invoke_typed<generated::api::SandboxEnforcementStatus>(
"session.sandbox.getEnforcementStatus"
);
}
// =============================================================================
// Model & Mode (v0.1.49 additions)
// =============================================================================
std::future<void> Session::set_model(const std::string& model_id, SetModelOptions options)
{
return std::async(
std::launch::async,
[this, model_id, options]()
{
json params;
params["sessionId"] = session_id_;
params["modelId"] = model_id;
if (options.reasoning_effort.has_value())
params["reasoningEffort"] = *options.reasoning_effort;
client_->rpc_client()->invoke(copilot::rpc::methods::kSessionModelSwitchTo, params).get();
}
);
}
namespace
{
const char* auto_tier_wire(Session::AutoTier tier)
{
switch (tier)
{
case Session::AutoTier::Efficiency:
return "efficiency";
case Session::AutoTier::Balance:
return "balance";
case Session::AutoTier::Intelligence:
return "intelligence";
case Session::AutoTier::Fast:
return "fast";
}
return "balance";
}
std::optional<Session::AutoTier> auto_tier_from_wire(const json& value)
{
if (!value.is_string())
return std::nullopt;
const auto text = value.get<std::string>();
if (text == "efficiency")
return Session::AutoTier::Efficiency;