Repository navigation
Expand file tree
/
Copy pathSessionAssistant.cpp
More file actions
3545 lines (2989 loc) · 111 KB
/
Copy pathSessionAssistant.cpp
File metadata and controls
3545 lines (2989 loc) · 111 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
/*
* SessionAssistant.cpp
*
* Copyright (C) 2026 by Posit Software, PBC
*
* Unless you have received this program directly from Posit Software pursuant
* to the terms of a commercial license agreement with Posit Software, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "SessionAssistant.hpp"
#include "SessionChat.hpp"
#include "chat/ChatInstallation.hpp"
#include "SessionLogging.hpp"
#include "SessionNodeTools.hpp"
#ifndef _WIN32
# include <cerrno>
# include <signal.h>
#endif
#include <algorithm>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/find.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/current_function.hpp>
#include <boost/scope_exit.hpp>
#include <shared_core/Error.hpp>
#include <shared_core/json/Json.hpp>
#include <core/collection/Position.hpp>
#include <core/Exec.hpp>
#include <core/FileSerializer.hpp>
#include <core/http/Header.hpp>
#include <core/json/JsonRpc.hpp>
#include <core/StringUtils.hpp>
#include <core/system/Process.hpp>
#include <core/system/System.hpp>
#include <core/Thread.hpp>
#include <r/RExec.hpp>
#include <r/RJson.hpp>
#include <r/ROptions.hpp>
#include <r/RRoutines.hpp>
#include <r/RSexp.hpp>
#include <r/session/REventLoop.hpp>
#include <session/projects/SessionProjects.hpp>
#include <session/prefs/UserPrefs.hpp>
#include <session/SessionModuleContext.hpp>
#include <session/SessionRUtil.hpp>
#include "SessionLSP.hpp"
#include "session-config.h"
#define kAssistantDefaultDocumentVersion (0)
#define kMaxIndexingFileSize (1048576)
// How long to wait after a failed agent launch before automatic triggers
// (e.g. completion requests) may attempt another launch.
#define kAgentLaunchRetrySeconds (30)
// Maximum number of variables to include in session notifications
#define kAssistantMaxVariables (100)
// Maximum number of children to include for recursive objects
#define kAssistantMaxChildren (50)
// completion was triggered explicitly by a user gesture
#define kAssistantCompletionTriggerUserInvoked (1)
// completion was triggered automatically while editing
#define kAssistantCompletionTriggerAutomatic (2)
using namespace rstudio::core;
using namespace rstudio::core::system;
namespace rstudio {
namespace session {
namespace modules {
namespace assistant {
namespace {
class OnceGuard
{
public:
operator bool() { return value_++ == 0; }
void reset() { value_ = 0; }
private:
int value_ = 0;
};
bool isCopilotAllowedByAdmin()
{
#ifdef COPILOT_ENABLED
return
session::options().allowCopilot() &&
session::options().copilotEnabled();
#else
// RStudio built without GitHub Copilot support
return false;
#endif
}
bool isPositAssistantAllowedByAdmin()
{
return module_context::isPositAssistantEnabledByAdmin();
}
struct AssistantRequest
{
std::string method;
std::string id;
json::Value params;
};
// Requests are held, unwritten, until the agent has answered 'initialize', so
// they get as long as 'initialize' does before the sweep gives up on them.
const std::chrono::seconds kAgentInitializeTimeout(60);
const std::chrono::seconds kAgentRequestTimeout(10);
const std::chrono::seconds kHeldAgentRequestTimeout = kAgentInitializeTimeout;
class AssistantContinuation
{
public:
explicit AssistantContinuation(const json::JsonRpcFunctionContinuation& continuation)
: continuation_(continuation)
{
}
// default ctor needed for compatibility with map
AssistantContinuation()
: AssistantContinuation(json::JsonRpcFunctionContinuation())
{
}
// Start (or restart) the clock on this request, in serviced time.
void startClock(std::chrono::steady_clock::duration now,
std::chrono::steady_clock::duration timeout)
{
started_ = now;
timeout_ = timeout;
}
bool isExpired(std::chrono::steady_clock::duration now) const
{
return now - started_ > timeout_;
}
void invoke(json::Object resultJson)
{
resultJson["cancelled"] = false;
json::JsonRpcResponse response;
response.setResult(resultJson);
if (continuation_)
continuation_(Success(), &response);
}
void cancel()
{
json::Object resultJson;
resultJson["cancelled"] = true;
json::JsonRpcResponse response;
response.setResult(resultJson);
if (continuation_)
continuation_(Success(), &response);
}
private:
json::JsonRpcFunctionContinuation continuation_;
std::chrono::steady_clock::duration started_{};
std::chrono::steady_clock::duration timeout_{};
};
// keep in sync with AssistantResponseTypes.AssistantAgentNotRunningReason
enum class AgentNotRunningReason
{
Unknown,
NotInstalled,
DisabledByAdministrator,
DisabledViaProjectPreferences,
DisabledViaGlobalPreferences,
LaunchError,
Unsupported,
};
// keep in sync with AssistantRuntimeStatusChangedEvent.java
enum class AgentRuntimeStatus
{
Unknown,
Preparing,
Starting,
Running,
Stopping,
Stopped,
};
// The log level for agent-specific logs. Primarily for developer use and debugging.
int s_assistantLogLevel = 0;
// Whether the AI assistant is enabled.
// Computed and cached from user and project preferences.
bool s_assistantEnabled = false;
// The PID of the active agent process.
PidType s_agentPid = -1;
// Incremented on every agent start so a late exit callback from a
// superseded agent process can be told apart from the current one.
uint64_t s_agentGeneration = 0;
// The type of the currently running agent (e.g., "copilot", "posit").
std::string s_runningAgentType;
// Error output (if any) that was written during startup.
AgentStderrTail s_agentStartupError(kAgentStderrMaxBytes);
// The current status of the agent, mainly around if it's enabled
// (and why or why not).
AgentNotRunningReason s_agentNotRunningReason = AgentNotRunningReason::Unknown;
// The current runtime status of the agent process.
AgentRuntimeStatus s_agentRuntimeStatus = AgentRuntimeStatus::Unknown;
// When the last failed agent launch attempt occurred, if any. Used to avoid
// re-attempting (and re-waiting on) doomed launches on every automatic
// trigger; see kAgentLaunchRetrySeconds in ensureAgentRunning().
boost::posix_time::ptime s_agentLastLaunchFailure(boost::posix_time::not_a_date_time);
// Whether or not we've handled the Assistant 'initialized' notification.
// Primarily done to allow proper sequencing of Assistant callbacks.
bool s_agentInitialized = false;
// Whether the running agent has answered 'initialize'. Notifications queued
// from then on follow 'initialized' in s_pendingRequests, so they may be
// queued before s_agentInitialized is set.
bool s_agentInitializeAnswered = false;
// The ID of the document most recently focused, whether or not an agent was
// running to be told. Nothing else tells a new agent which document has focus.
boost::optional<std::string> s_focusedDocumentId;
// A queue of pending requests, to be sent via the agent's stdin.
std::vector<AssistantRequest> s_pendingRequests;
// Metadata related to pending requests.
// Mainly used to map responses to their expected result types.
std::map<std::string, AssistantContinuation> s_pendingContinuations;
// Clock for timing out agent requests. Background processing runs every 50ms
// or so while R services events, so a longer gap means R was blocked.
ServicedClock s_servicedClock(std::chrono::seconds(1));
// A queue of pending responses, sent via the agent's stdout.
std::queue<std::string> s_pendingResponses;
// The agent's stdout, split into responses across reads.
AgentStdoutReader s_agentStdout;
// Whether we're about to shut down.
bool s_isSessionShuttingDown = false;
// Project-specific assistant options.
projects::RProjectAssistantOptions s_assistantProjectOptions;
// Whether the Posit Assistant installation lacks NES, as of the last
// synchronize(). Cached so the session and the client agree on it between
// installs, and so resolving the assistant type stays off the filesystem.
bool s_positNesMissing = false;
// A queue of pending files to be indexed.
std::vector<FileInfo> s_indexQueue;
std::size_t s_indexBatchSize = 200;
// Session ID for the R session, used in session notifications.
std::string s_sessionId;
void setAgentRuntimeStatus(AgentRuntimeStatus status)
{
if (s_agentRuntimeStatus != status)
{
s_agentRuntimeStatus = status;
// notify client of agent status change
json::Object dataJson;
dataJson["status"] = static_cast<int>(status);
ClientEvent event(client_events::kAssistantStatusChanged, dataJson);
module_context::enqueClientEvent(event);
}
}
std::string agentNotRunningReason()
{
switch (s_agentNotRunningReason)
{
case AgentNotRunningReason::Unknown:
return "Unknown";
case AgentNotRunningReason::NotInstalled:
return "The required assistant agent is not installed.";
case AgentNotRunningReason::DisabledByAdministrator:
return "AI assistant use has been disabled by the system administrator.";
case AgentNotRunningReason::DisabledViaProjectPreferences:
return "AI assistant has been disabled via project preferences.";
case AgentNotRunningReason::DisabledViaGlobalPreferences:
return "AI assistant has been disabled via global preferences.";
case AgentNotRunningReason::LaunchError:
return "The AI assistant agent failed to launch: " + s_agentStartupError.text();
case AgentNotRunningReason::Unsupported:
return "The installed AI assistant version is no longer supported.";
}
return "Unknown";
}
int assistantLogLevel()
{
return s_assistantLogLevel;
}
std::vector<std::string> extractVariablesInScope(const std::string& contents,
const std::string& documentType)
{
std::vector<std::string> result;
// Extract R code from the document (handles Rmd, Quarto, etc.)
std::string code;
Error error = r_utils::extractRCode(contents, documentType, &code);
if (error)
{
LOG_ERROR(error);
return result;
}
// Parse the R code to find variable references
r::sexp::Protect protect;
SEXP resultSEXP = R_NilValue;
error = r::exec::RFunction(".rs.assistant.extractVariablesInScope")
.addParam(code)
.addParam(R_GlobalEnv)
.call(&resultSEXP, &protect);
if (error)
{
LOG_ERROR(error);
return result;
}
error = r::sexp::extract(resultSEXP, &result);
if (error)
{
LOG_ERROR(error);
return result;
}
return result;
}
json::Array getVariablesContext(const std::vector<std::string>& variablesInScope)
{
json::Array variablesContext;
// Build the variablesInScope parameter for R
// TRUE means examine all recursive objects, character vector limits to specific names
r::sexp::Protect protect;
SEXP variablesInScopeSEXP = R_NilValue;
if (variablesInScope.empty())
{
// No specific variables in scope - examine all recursive objects
variablesInScopeSEXP = r::sexp::create(true, &protect);
}
else
{
// Specific variables in scope
variablesInScopeSEXP = r::sexp::create(variablesInScope, &protect);
}
// Call the R function to get variable descriptions
SEXP resultSEXP = R_NilValue;
Error error = r::exec::RFunction(".rs.assistant.variableDescriptions")
.addParam(R_GlobalEnv)
.addParam(variablesInScopeSEXP)
.call(&resultSEXP, &protect);
if (error)
{
LOG_ERROR(error);
return variablesContext;
}
// Convert the R list to JSON
json::Value variablesJson;
error = r::json::jsonValueFromList(resultSEXP, &variablesJson);
if (error)
{
LOG_ERROR(error);
return variablesContext;
}
// Wrap in the expected format: [{ languageId: "r", variables: [...] }]
if (variablesJson.isArray() && !variablesJson.getArray().isEmpty())
{
json::Object rContext;
rContext["languageId"] = "r";
rContext["variables"] = variablesJson;
variablesContext.push_back(rContext);
}
return variablesContext;
}
// Whether a file's name or location marks it as one that might hold secrets.
bool isSensitivePath(const FilePath& documentPath)
{
// Hidden files.
if (documentPath.isHidden())
return true;
// R startup files, which might set tokens.
std::string name = documentPath.getFilename();
if (name == "Renviron.site" || name == "Rprofile.site")
return true;
// Files within hidden folders (like .ssh), but not paths that merely go
// through "." or ".."
std::vector<std::string> components;
boost::algorithm::split(components, documentPath.getAbsolutePath(), boost::is_any_of("/"));
for (const std::string& component : components)
{
if (component.size() > 1 && component[0] == '.' && component != "..")
return true;
}
return false;
}
bool isIndexableFile(const FilePath& documentPath)
{
if (isSensitivePath(documentPath))
return false;
// Don't index .Rproj files
std::string ext = documentPath.getExtensionLowerCase();
if (ext == ".rproj")
return false;
// Handle Dockerfile (or its Podman name, Containerfile) with any extension
// (including none, the most common)
std::string stem = documentPath.getStem();
if (stem == "Dockerfile" || stem == "Containerfile")
return true;
// Handle extensionless Makefile / makefile
std::string name = documentPath.getFilename();
if (name == "Makefile" || name == "makefile")
return true;
std::string languageId = lsp::languageIdFromExtension(ext);
return !languageId.empty();
}
// Note: 'checkContents' should be false for documents loaded without their
// contents (e.g. via source_database::get(id, false, pDoc)); the binary-file
// check is skipped for those, and file type heuristics alone decide.
bool isIndexableDocument(const boost::shared_ptr<source_database::SourceDocument>& pDoc,
bool checkContents = true)
{
// Don't index binary files.
if (checkContents && pDoc->contents().find('\0') != std::string::npos)
return false;
// Our source database uses non-standard names for certain R file types,
// so explicitly check for those and allow them to be indexed.
bool isR = pDoc->isRFile() || pDoc->isRMarkdownDocument();
// Allow indexing of Untitled documents if they have a known type.
if (pDoc->isUntitled())
{
if (isR)
return true;
std::string type = pDoc->languageId();
std::string ext = lsp::extensionFromLanguageId(type);
return !ext.empty();
}
// R documents are indexable whatever their extension, but not hidden ones
// (like ~/.Rprofile, which often holds tokens).
FilePath docPath(pDoc->path());
if (isR)
return !isSensitivePath(docPath);
// Otherwise, check for known files / extensions.
return isIndexableFile(docPath);
}
FilePath paiLanguageServerPath()
{
// Resolve the installation the same way the chat backend does, so both
// halves of the assistant run out of the same install -- honoring
// administrator-managed and bundled installs, not just the user one.
FilePath installPath = chat::installation::locatePositAssistantInstallation();
FilePath languageServerPath = nesLanguageServerPath(installPath);
if (!languageServerPath.isEmpty())
{
DLOG("Posit AI Language Server found at '{}'.", languageServerPath.getAbsolutePath());
return languageServerPath;
}
if (RS_ONCE())
{
if (installPath.isEmpty())
DLOG("Posit AI Language Server not found: no Posit Assistant installation.");
else
DLOG("Posit AI Language Server not found in installation '{}'.",
installPath.getAbsolutePath());
}
return FilePath();
}
// The RSTUDIO_AGENT_PATH override to launch the given assistant's agent from,
// or an empty path when there is none or it doesn't apply to that assistant.
FilePath agentPathOverrideFor(const std::string& assistant)
{
std::string value = core::system::getenv("RSTUDIO_AGENT_PATH");
bool overrideExists = !value.empty() && FilePath::exists(value);
if (!agentPathOverrideApplies(assistant,
overrideExists,
!session::options().positAssistantHelper().isEmpty(),
!session::options().copilotHelper().isEmpty()))
{
return FilePath();
}
return FilePath(value);
}
// Refresh s_positNesMissing, telling the client when it changes. An
// RSTUDIO_AGENT_PATH override that Posit AI would launch from supplies its
// own language server, so NES is never missing while one is in effect.
void refreshPositNesMissing()
{
// Where Posit Assistant can't be used, Posit AI isn't offered regardless,
// so skip scanning for an installation.
if (!isPositAssistantAllowedByAdmin())
return;
bool overrideInEffect = !agentPathOverrideFor(kAssistantPosit).isEmpty();
FilePath installPath = chat::installation::locatePositAssistantInstallation();
bool nesMissing = !overrideInEffect && isNesMissing(installPath);
if (nesMissing == s_positNesMissing)
return;
s_positNesMissing = nesMissing;
if (nesMissing)
DLOG("Posit Assistant installation '{}' doesn't include NES; "
"treating a Posit AI assistant selection as (None).",
installPath.getAbsolutePath());
json::Object dataJson;
dataJson["nes_missing"] = nesMissing;
ClientEvent event(client_events::kAssistantNesMissingChanged, dataJson);
module_context::enqueClientEvent(event);
}
FilePath copilotLanguageServerPath()
{
FilePath copilotPath;
std::string copilotJsFolder = core::system::getenv("RSTUDIO_COPILOT_JS_FOLDER");
if (!copilotJsFolder.empty())
{
if (FilePath::exists(copilotJsFolder) && FilePath(copilotJsFolder).isDirectory())
{
DLOG("Using Copilot Language Server path from RSTUDIO_COPILOT_JS_FOLDER: '{}'.", copilotJsFolder);
copilotPath = FilePath(copilotJsFolder);
}
}
if (copilotPath.isEmpty())
{
copilotPath = session::options().copilotPath();
if (copilotPath.exists())
{
DLOG("Using Copilot Language Server path from session options: '{}'.", copilotPath.getAbsolutePath());
}
}
// Accept both directories and paths to language-server.js
if (copilotPath.isDirectory())
{
copilotPath = copilotPath.completeChildPath("language-server.js");
}
if (!copilotPath.exists())
{
ELOG("Copilot Language Server not found at '{}'.", copilotPath.getAbsolutePath());
}
DLOG("Copilot Language Server found at '{}'.", copilotPath.getAbsolutePath());
return copilotPath;
}
FilePath assistantLanguageServerPath(const std::string& assistantType = "");
// Returns the configured assistant type, checking in order:
// 1. Explicit assistantType parameter (if provided)
// 2. Project-level assistant setting (if set and not "default")
// 3. Global user preference
std::string getConfiguredAssistantType(const std::string& assistantType = "")
{
// If an explicit type was provided, use it
if (!assistantType.empty())
return assistantType;
// Check for project-level override
std::string selectedAssistant = s_assistantProjectOptions.assistant;
if (selectedAssistant.empty() || selectedAssistant == "default")
{
// Fall back to global preference
selectedAssistant = prefs::userPrefs().assistant();
}
return effectiveAssistantType(selectedAssistant, s_positNesMissing);
}
FilePath assistantLanguageServerPath(const std::string& assistantType)
{
// Get the configured assistant type
std::string assistant = getConfiguredAssistantType(assistantType);
// Allow override via environment variable, as startAgent() launches it
FilePath agentPathOverride = agentPathOverrideFor(assistant);
if (!agentPathOverride.isEmpty())
return agentPathOverride;
if (assistant == kAssistantPosit)
{
return paiLanguageServerPath();
}
else if (assistant == kAssistantCopilot)
{
return copilotLanguageServerPath();
}
else if (assistant == kAssistantNone)
{
return FilePath();
}
else
{
// unknown assistant type
ELOG("Unknown assistant type '{}'", assistant);
return FilePath();
}
}
bool isAgentInstalled(const std::string& assistantType = "")
{
return assistantLanguageServerPath(assistantType).exists();
}
bool isAssistantEnabled(const std::string& assistantType = "")
{
// Get the configured assistant type
std::string assistant = getConfiguredAssistantType(assistantType);
// If no assistant is selected, we're done.
if (assistant == kAssistantNone)
{
// Determine if disabled via project or global preferences
std::string projectAssistant = s_assistantProjectOptions.assistant;
if (!projectAssistant.empty() && projectAssistant != "default")
s_agentNotRunningReason = AgentNotRunningReason::DisabledViaProjectPreferences;
else
s_agentNotRunningReason = AgentNotRunningReason::DisabledViaGlobalPreferences;
return false;
}
// Check whether the selected assistant type is allowed by the administrator.
if (assistant == kAssistantCopilot)
{
if (!isCopilotAllowedByAdmin())
{
s_agentNotRunningReason = AgentNotRunningReason::DisabledByAdministrator;
return false;
}
}
else if (assistant == kAssistantPosit)
{
if (!isPositAssistantAllowedByAdmin())
{
s_agentNotRunningReason = AgentNotRunningReason::DisabledByAdministrator;
return false;
}
}
// Finally, check whether the selected assistant type is installed.
if (!isAgentInstalled(assistant))
{
s_agentNotRunningReason = AgentNotRunningReason::NotInstalled;
return false;
}
// For Posit Assistant, block if version/protocol is unsupported or manifest unavailable
if (assistant == kAssistantPosit && chat::isPositAssistantUnsupported())
{
s_agentNotRunningReason = AgentNotRunningReason::Unsupported;
return false;
}
return true;
}
// Wait until the callback reports ready, polling in 100ms steps up to
// maxIterations (so the default bound is 10 seconds).
template <typename F>
bool waitFor(F&& callback, int maxIterations = 100)
{
for (int i = 0; i < maxIterations; i++)
{
bool ready = callback();
if (ready)
return true;
// During session shutdown, pump only the process supervisor. The full
// background-processing pass runs every module's background handler plus
// any scheduled commands, and processEvents() runs arbitrary R callbacks;
// dispatching those mid-teardown means any one of them that blocks wedges
// the session's exit permanently, which in turn wedges the desktop /
// server relaunch that is waiting on it (#18394). The supervisor poll
// alone is enough to reap the agent and fire its exit callback. (This
// assumes the wait was entered at top level: poll() is a no-op when
// re-entered from within another supervisor poll -- see
// requestAgentStop -- in which case this wait degrades to a bounded
// sleep.)
if (s_isSessionShuttingDown)
{
module_context::processSupervisor().poll();
}
else
{
module_context::onBackgroundProcessing(false);
r::session::event_loop::processEvents();
}
boost::this_thread::sleep_for(boost::chrono::milliseconds(100));
}
return false;
}
void sendNotification(const std::string& method,
const json::Value& paramsJson)
{
s_pendingRequests.push_back({ method, "", paramsJson });
}
std::string formatRequest(const AssistantRequest& request)
{
// Create the request body
json::Object requestJson;
requestJson["jsonrpc"] = "2.0";
requestJson["method"] = request.method;
requestJson["params"] = request.params;
// Set id if available.
// Requests without an id are 'notifications', and never receive a response.
std::string id = request.id;
if (!id.empty())
requestJson["id"] = id;
// Convert to a JSON string
std::string requestBody = requestJson.write();
// Convert into HTTP request with JSON payload in body
return fmt::format("Content-Length: {}\r\n\r\n{}", requestBody.size(), requestBody);
}
void addPendingContinuation(const std::string& requestId,
const AssistantContinuation& continuation)
{
AssistantContinuation& pending = s_pendingContinuations[requestId];
pending = continuation;
pending.startClock(s_servicedClock.elapsed(), kHeldAgentRequestTimeout);
}
void sendRequest(const std::string& method,
const std::string& requestId,
const json::Value& paramsJson,
const AssistantContinuation& continuation)
{
DLOG("Enqueuing request '{}' with id '{}'.", method, requestId);
// Add the continuation, which is executed in response to the request.
addPendingContinuation(requestId, continuation);
// Create and enqueue the request.
s_pendingRequests.push_back({ method, requestId, paramsJson });
}
// The agent can't start on a request until it has been written to the agent,
// so restart the request's clock then. Writes happen in the supervisor poll,
// before this pass's background handler ticks the clock, so tick it first;
// otherwise the gap before the write would count against the request.
void onRequestWritten(const AssistantRequest& request,
std::chrono::steady_clock::time_point now)
{
s_servicedClock.tick(now);
auto it = s_pendingContinuations.find(request.id);
if (it != s_pendingContinuations.end())
it->second.startClock(s_servicedClock.elapsed(), agentRequestTimeout(request.method));
}
// Should only be used for debugging, as this will block the R session
// while the request is being serviced.
json::Object sendSynchronousRequest(const std::string& method,
const std::string& requestId,
const json::Value& paramsJson)
{
json::Object result;
bool responseReceived = false;
auto continuation = [&](const Error& error, json::JsonRpcResponse* pResponse)
{
responseReceived = true;
if (error == Success() && pResponse->result().isObject())
result = pResponse->result().getObject();
};
sendRequest(method, requestId, paramsJson, AssistantContinuation(continuation));
waitFor([&]() { return responseReceived; });
return result;
}
void setCopilotConfiguration()
{
json::Object paramsJson;
json::Object settingsJson;
// network proxy settings
r::sexp::Protect protect;
// check strict ssl flag
bool proxyStrictSsl = session::options().copilotProxyStrictSsl();
// allow override from envvar
std::string proxyStrictSslOverride = core::system::getenv("COPILOT_PROXY_STRICT_SSL");
if (!proxyStrictSslOverride.empty())
proxyStrictSsl = core::string_utils::isTruthy(proxyStrictSslOverride, true);
// check for server-configured proxy URL
std::string proxyUrl = session::options().copilotProxyUrl();
// allow override from envvar
std::string proxyUrlOverride = core::system::getenv("COPILOT_PROXY_URL");
if (!proxyUrlOverride.empty())
proxyUrl = proxyUrlOverride;
// if the network proxy isn't set, try reading a fallback from R
if (proxyUrl.empty())
{
SEXP networkProxySEXP = R_NilValue;
Error error = r::exec::RFunction(".rs.copilot.networkProxy").call(&networkProxySEXP, &protect);
if (error)
LOG_ERROR(error);
proxyUrl = networkProxySEXP == R_NilValue ? "" : r::sexp::asString(networkProxySEXP);
}
// if we now have a network proxy definition, log it
if (!proxyUrl.empty())
{
SEXP networkProxySEXP = R_NilValue;
// parse the URL into its associated components for logging
Error error = r::exec::RFunction(".rs.copilot.parseNetworkProxyUrl")
.addParam(proxyUrl)
.call(&networkProxySEXP, &protect);
if (error)
{
proxyUrl.clear();
LOG_ERROR(error);
}
if (networkProxySEXP != R_NilValue)
{
json::Value networkProxy;
Error error = r::json::jsonValueFromObject(networkProxySEXP, &networkProxy);
if (error)
LOG_ERROR(error);
if (networkProxy.isObject())
{
json::Object networkProxyJson = networkProxy.getObject();
if (s_assistantLogLevel > 0)
{
json::Object networkProxyClone = networkProxyJson.clone().getObject();
if (networkProxyClone.hasMember("user"))
networkProxyClone["user"] = "<user>";
if (networkProxyClone.hasMember("pass"))
networkProxyClone["pass"] = "<pass>";
DLOG("Using network proxy: {}", networkProxyClone.writeFormatted());
}
}
}
}
// if we have a network proxy, add it to the configuration
if (!proxyUrl.empty())
{
// check for proxy Kerberos service principal setting
std::string kerberosPrincipal = session::options().copilotProxyKerberosPrincipal();
// allow override from envvar
std::string kerberosPrincipalOverride = core::system::getenv("COPILOT_PROXY_KERBEROS_SERVICE_PRINCIPAL");
if (!kerberosPrincipalOverride.empty())
kerberosPrincipal = kerberosPrincipalOverride;
// if the principal isn't set, try reading a fallback from R
if (kerberosPrincipal.empty())
{
SEXP kerberosPrincipalSEXP = R_NilValue;
Error error = r::exec::RFunction(".rs.copilot.proxyKerberosServicePrincipal").call(&kerberosPrincipalSEXP, &protect);
if (error)
LOG_ERROR(error);
kerberosPrincipal = kerberosPrincipalSEXP == R_NilValue ? "" : r::sexp::asString(kerberosPrincipalSEXP);
}
json::Object httpParamsJson;
httpParamsJson["proxy"] = proxyUrl;
httpParamsJson["proxyStrictSSL"] = proxyStrictSsl;
if (!kerberosPrincipal.empty())
httpParamsJson["proxyKerberosServicePrincipal"] = kerberosPrincipal;
settingsJson["http"] = httpParamsJson;
}
// check for authentication provider
std::string authProviderUrl = session::options().copilotAuthProvider();
// allow override from envvar
std::string authProviderUrlOverride = core::system::getenv("COPILOT_AUTH_PROVIDER");
if (!authProviderUrlOverride.empty())
authProviderUrl = authProviderUrlOverride;
if (authProviderUrl.empty())
{
// check for authentication provider configuration from R
SEXP authProviderSEXP = R_NilValue;
Error error = r::exec::RFunction(".rs.copilot.authProvider").call(&authProviderSEXP, &protect);
if (error)
LOG_ERROR(error);
authProviderUrl = authProviderSEXP == R_NilValue ? "" : r::sexp::asString(authProviderSEXP);
}
if (!authProviderUrl.empty())
{
json::Object githubEnterpriseJson;
githubEnterpriseJson["uri"] = authProviderUrl;
DLOG("Using github-enterprise authentication provider: {}", githubEnterpriseJson.writeFormatted());
settingsJson["github-enterprise"] = githubEnterpriseJson;
}
paramsJson["settings"] = settingsJson;
std::string requestId = core::system::generateUuid();
sendNotification("workspace/didChangeConfiguration", paramsJson);
}
void setPositAiConfiguration()
{
// Stub for Posit AI configuration.
}
bool supportsSessionNotifications()
{
return s_agentInitializeAnswered &&
s_runningAgentType == kAssistantPosit;
}