Repository navigation
Expand file tree
/
Copy pathSessionExecutor.cs
More file actions
1027 lines (935 loc) · 39.5 KB
/
Copy pathSessionExecutor.cs
File metadata and controls
1027 lines (935 loc) · 39.5 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
using System.Globalization;
using OpenClaw.Launcher.Mxc;
using OpenClaw.SessionProtocol;
namespace OpenClaw.Launcher.Session;
/// <summary>
/// What to run inside the session.
/// </summary>
internal sealed record SessionExecutionRequest(
string HelperPath,
string NodePath,
string ApplicationDirectory,
IReadOnlyList<string> Arguments,
string WorkingDirectory)
{
/// <summary>
/// Environment determined by the host entrypoint for this invocation.
/// </summary>
public IReadOnlyDictionary<string, string>? AdditionalEnvironment { get; init; }
/// <summary>Node.js runtime arguments placed before the application entrypoint.</summary>
public IReadOnlyList<string>? NodeArgumentsPrefix { get; init; }
/// <summary>
/// Node.js options the agent appends to its own <c>NODE_OPTIONS</c>.
/// </summary>
public string? NodeOptionsSuffix { get; init; }
/// <summary>
/// The staged native dependency root this launch resolves addons through.
/// </summary>
public string? NativeRootPath { get; init; }
}
/// <summary>
/// An arbitrary foreground command to run inside the session.
/// </summary>
/// <remarks>
/// This is the general form of <see cref="SessionExecutionRequest"/>: the
/// diagnostic commands need to run a shell or the guest helper's own
/// collection mode, neither of which goes through Node. The argument vector
/// still travels as JSON, so nothing here reaches the backend command line.
/// </remarks>
internal sealed record SessionCommandRequest(
string HelperPath,
string Executable,
IReadOnlyList<string> Arguments,
string WorkingDirectory)
{
/// <summary>Guest directory that must lead the child process PATH.</summary>
public string? PathPrefix { get; init; }
/// <summary>
/// Values merged over the shared runtime environment for this command only.
/// </summary>
/// <remarks>
/// Kept per request rather than added to the shared environment because
/// these describe how one command was invoked, and OpenClaw itself must not
/// see a variable that only the shell's shim needs.
/// </remarks>
public IReadOnlyDictionary<string, string>? AdditionalEnvironment { get; init; }
/// <summary>
/// Node.js options the agent appends to its own <c>NODE_OPTIONS</c>.
/// </summary>
/// <remarks>
/// Named rather than merged into <see cref="AdditionalEnvironment"/>
/// because that dictionary is assigned over the agent's environment, and
/// the host's own <c>NODE_OPTIONS</c> is not the agent's.
/// </remarks>
public string? NodeOptionsSuffix { get; init; }
/// <summary>
/// The staged native dependency root this command resolves addons through,
/// held open by the guest for the command's lifetime.
/// </summary>
public string? NativeRootPath { get; init; }
}
/// <summary>
/// Captured output from a non-interactive command run in the isolated session.
/// </summary>
internal sealed record SessionCommandCaptureResult(
int ExitCode,
string StandardOutput,
string StandardError);
/// <summary>
/// Runs OpenClaw inside the owned session.
/// </summary>
/// <remarks>
/// The backend's execution API takes a command line, not an argument vector,
/// and the pinned runtime flattens it through <c>cmd.exe</c>. Only the guest
/// helper's own path and its request file appear there; the user's arguments
/// travel as JSON in the shared workspace and are never exposed to that
/// flattening.
/// </remarks>
internal sealed partial class SessionExecutor
{
private const int ControlCExitCode = unchecked((int)0xc000013a);
private const int PortableInterruptedExitCode = 130;
private readonly IMxcSessionClient _backend;
private readonly Action<string> _log;
private readonly Func<IReadOnlyDictionary<string, string>> _buildEnvironment;
private readonly Func<string> _createRequestId;
private readonly Func<SessionRecord, bool> _isCurrentRecord;
private readonly TimeProvider _clock;
private readonly Func<string, IInvocationLifetime> _createInvocationLifetime;
public SessionExecutor(IMxcSessionClient backend, Action<string> log,
Func<IReadOnlyDictionary<string, string>>? buildEnvironment = null,
Func<string>? createRequestId = null,
Func<SessionRecord, bool>? isCurrentRecord = null,
TimeProvider? clock = null,
Func<string, IInvocationLifetime>? createInvocationLifetime = null)
{
ArgumentNullException.ThrowIfNull(backend);
ArgumentNullException.ThrowIfNull(log);
_backend = backend;
_log = log;
_buildEnvironment = buildEnvironment ?? (() => OpenClawRuntimeEnvironment.Build());
_createRequestId = createRequestId ?? (() => Guid.NewGuid().ToString("N"));
_isCurrentRecord = isCurrentRecord ?? (_ => true);
_clock = clock ?? TimeProvider.System;
_createInvocationLifetime = createInvocationLifetime ?? WindowsInvocationJob.Create;
}
internal SessionWorkspaceOperation CreateWorkspaceOperation(SessionRecord record) =>
new(record, _isCurrentRecord);
public async Task<int> ExecuteAsync(
SessionRecord record,
SessionExecutionRequest request,
CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(record);
ArgumentNullException.ThrowIfNull(request);
return await ExecuteCommandAsync(
record, CreateOpenClawCommandRequest(request),
"Running OpenClaw in the isolated session.", "OpenClaw",
cancellationToken).ConfigureAwait(false);
}
public Task<SessionCommandCaptureResult> ExecuteCaptureAsync(
SessionRecord record,
SessionExecutionRequest request,
CancellationToken cancellationToken) =>
ExecuteCommandCaptureAsync(
record, CreateOpenClawCommandRequest(request),
"Running OpenClaw in the isolated session.", "OpenClaw", cancellationToken);
private SessionCommandRequest CreateOpenClawCommandRequest(SessionExecutionRequest request)
{
string nodeDirectory = Path.GetDirectoryName(request.NodePath)
?? throw new SessionException("The agent Node.js executable has no parent directory.");
return new SessionCommandRequest(
request.HelperPath, request.NodePath, BuildNodeArguments(request), request.WorkingDirectory)
{
PathPrefix = nodeDirectory,
AdditionalEnvironment = MergeEnvironment(_buildEnvironment(), request.AdditionalEnvironment),
NodeOptionsSuffix = request.NodeOptionsSuffix,
NativeRootPath = request.NativeRootPath
};
}
/// <summary>
/// Runs one arbitrary foreground command inside the session and returns its
/// exit code.
/// </summary>
/// <remarks>
/// The caller supplies the message reported before dispatch and the subject
/// name used in failures, so a shell that never started does not report
/// itself as OpenClaw.
/// </remarks>
public async Task<int> ExecuteCommandAsync(
SessionRecord record,
SessionCommandRequest request,
string startingMessage,
string subject,
CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(record);
ArgumentNullException.ThrowIfNull(request);
string requestId = _createRequestId();
using var operation = new SessionWorkspaceOperation(record, _isCurrentRecord);
string requestPath = operation.FilePath("launch", requestId);
string resultPath = SessionLaunchProtocol.ResultPathFor(requestPath);
SessionLaunchRequest launchRequest = CreateLaunchRequest(requestId, request);
using IInvocationLifetime job = CreateInvocationLifetime(record);
CancellationTokenRegistration cancellation = cancellationToken.Register(job.RequestStop);
try
{
await operation.WriteTextNewAsync(
requestPath,
SessionLaunchProtocol.SerializeRequest(launchRequest),
cancellationToken).ConfigureAwait(false);
string commandLine = BuildGuestCommandLine(request.HelperPath, requestPath, job.Mode);
_log(startingMessage);
int executorExitCode = await _backend.ExecuteAttachedAsync(
record.ToSandboxIdOrThrow(),
new MxcExecutionRequest(commandLine)
{
ProcessCreated = () => ConfirmInvocation(job.MarkDispatched),
ForegroundExited = () => ConfirmInvocation(job.ForegroundExited),
CancelInvocation = job.RequestStop
},
cancellationToken).ConfigureAwait(false);
operation.EnsureCurrent();
int exitCode = ReadOutcome(operation, resultPath, executorExitCode, requestId, subject);
// The matching end of the starting message. Its absence means the
// host itself was terminated while the command ran, which is what
// attributes a lingering guest process to this invocation.
_log($"{subject} exited with code {exitCode}.");
return exitCode;
}
finally
{
// Join the callback before confirming cleanup and releasing its files.
await cancellation.DisposeAsync().ConfigureAwait(false);
ConfirmInvocation(job.Stop);
// Only this invocation's files are removed. Concurrent invocations
// own differently named requests in the same shared workspace.
operation.Delete(requestPath);
operation.Delete(resultPath);
}
}
/// <summary>
/// Runs a non-interactive command inside the session and captures its output.
/// </summary>
/// <remarks>
/// The captured streams can contain authenticated data. This method must not
/// log them.
/// </remarks>
public async Task<SessionCommandCaptureResult> ExecuteCommandCaptureAsync(
SessionRecord record,
SessionCommandRequest request,
string startingMessage,
string subject,
CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(record);
ArgumentNullException.ThrowIfNull(request);
string requestId = _createRequestId();
using var operation = new SessionWorkspaceOperation(record, _isCurrentRecord);
string requestPath = operation.FilePath("launch", requestId);
string resultPath = SessionLaunchProtocol.ResultPathFor(requestPath);
SessionLaunchRequest launchRequest = CreateLaunchRequest(requestId, request);
using IInvocationLifetime job = CreateInvocationLifetime(record);
CancellationTokenRegistration cancellation = cancellationToken.Register(job.RequestStop);
try
{
await operation.WriteTextNewAsync(
requestPath,
SessionLaunchProtocol.SerializeRequest(launchRequest),
cancellationToken).ConfigureAwait(false);
_log(startingMessage);
MxcExecutionResult execution = await ExecuteTimedAsync(
record.ToSandboxIdOrThrow(),
BuildGuestCommandLine(request.HelperPath, requestPath, job.Mode),
subject,
cancellationToken,
() => ConfirmInvocation(job.MarkDispatched),
() => ConfirmInvocation(job.ForegroundExited),
job.RequestStop).ConfigureAwait(false);
operation.EnsureCurrent();
return ReadCapturedOutcome(operation, resultPath, execution, requestId, subject);
}
finally
{
await cancellation.DisposeAsync().ConfigureAwait(false);
ConfirmInvocation(job.Stop);
operation.Delete(requestPath);
operation.Delete(resultPath);
}
}
private IInvocationLifetime CreateInvocationLifetime(SessionRecord record)
{
string sid = record.AgentUserSid
?? throw new SessionException("The recorded session has no agent SID.");
try
{
return _createInvocationLifetime(sid);
}
catch (Exception exception) when (exception is System.ComponentModel.Win32Exception or
ArgumentException or InvalidOperationException or TimeoutException)
{
throw new SessionException(
$"Unable to prepare the isolated invocation lifetime: {DiagnosticFailure.Describe(exception)}",
exception);
}
}
private static void ConfirmInvocation(Action operation)
{
try
{
operation();
}
catch (Exception exception) when (exception is System.ComponentModel.Win32Exception or
InvalidOperationException or TimeoutException)
{
throw new SessionException(
$"The isolated invocation could not confirm process exit: {DiagnosticFailure.Describe(exception)}",
exception);
}
}
private SessionLaunchRequest CreateLaunchRequest(
string requestId,
SessionCommandRequest request) =>
new()
{
RequestId = requestId,
Executable = request.Executable,
Arguments = request.Arguments,
WorkingDirectory = request.WorkingDirectory,
Environment = MergeEnvironment(
_buildEnvironment(), request.AdditionalEnvironment),
PathPrefix = request.PathPrefix,
NodeOptionsSuffix = request.NodeOptionsSuffix,
NativeRootPath = request.NativeRootPath,
};
/// <summary>
/// Runs one buffered helper exchange and records how long the backend took.
/// </summary>
/// <remarks>
/// Every way the exchange ends is recorded. A returned result is logged as
/// soon as the backend returns, before it is validated, and a thrown
/// failure, including cancellation, is logged before it is rethrown
/// unchanged. Only the subject, the duration, and the executor exit code or
/// exception type are recorded: the captured streams can carry
/// authenticated data, and MXC failure messages can carry executor stderr.
/// </remarks>
private async Task<MxcExecutionResult> ExecuteTimedAsync(
MxcSandboxId sandboxId,
string commandLine,
string subject,
CancellationToken cancellationToken,
Action? processCreated = null,
Action? foregroundExited = null,
Action? cancelInvocation = null)
{
long started = _clock.GetTimestamp();
MxcExecutionResult execution;
try
{
execution = await _backend.ExecuteAsync(
sandboxId,
new MxcExecutionRequest(commandLine)
{
ProcessCreated = processCreated,
ForegroundExited = foregroundExited,
CancelInvocation = cancelInvocation
},
cancellationToken).ConfigureAwait(false);
}
catch (Exception exception)
{
string failure = exception is MxcException mxc
? $"{nameof(MxcException)} {mxc.Code}"
: exception.GetType().Name;
_log(string.Create(
CultureInfo.InvariantCulture,
$"{subject} failed after {ElapsedMilliseconds()} ms ({failure})."));
throw;
}
_log(string.Create(
CultureInfo.InvariantCulture,
$"{subject} finished in {ElapsedMilliseconds()} ms (executor exit {execution.ExitCode})."));
return execution;
long ElapsedMilliseconds() =>
(long)_clock.GetElapsedTime(started).TotalMilliseconds;
}
/// <summary>
/// Asks the guest to stage diagnostic files into the shared workspace.
/// </summary>
/// <remarks>
/// Uses the helper's collect mode rather than the launch mode, because
/// nothing is being run inside the session: the guest only copies files the
/// host's own account cannot open.
/// </remarks>
public async Task<SessionCollectResult> CollectAsync(
SessionRecord record,
string helperPath,
string destinationDirectory,
IReadOnlyList<SessionCollectSource> sources,
IReadOnlyList<string> deniedNames,
CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(record);
string requestId = _createRequestId();
using var operation = new SessionWorkspaceOperation(record, _isCurrentRecord);
string requestPath = operation.FilePath("collect", requestId);
string resultPath = SessionLaunchProtocol.ResultPathFor(requestPath);
try
{
await operation.WriteTextNewAsync(
requestPath,
SessionCollectProtocol.SerializeRequest(new SessionCollectRequest
{
RequestId = requestId,
DestinationDirectory = destinationDirectory,
Sources = sources,
DeniedNames = deniedNames
}),
cancellationToken).ConfigureAwait(false);
_log("Collecting agent-side diagnostics from the isolated session.");
MxcExecutionResult execution = await ExecuteTimedAsync(
record.ToSandboxIdOrThrow(),
BuildGuestCommandLine(helperPath, requestPath, "--collect"),
"Diagnostic collection",
cancellationToken).ConfigureAwait(false);
string resultText;
try
{
resultText = await operation.ReadTextAsync(resultPath, cancellationToken)
.ConfigureAwait(false);
}
catch (Exception exception) when (
exception is FileNotFoundException or DirectoryNotFoundException or IOException)
{
throw new SessionException(
"The isolated session did not report a collection " +
DescribeMissingResult(execution),
exception);
}
SessionCollectResult result = SessionCollectProtocol.ReadResult(resultText);
if (result.Error is { Length: > 0 } error)
{
throw new SessionException(
$"The isolated session could not collect diagnostics: {error}");
}
if (!string.Equals(result.RequestId, requestId, StringComparison.Ordinal))
{
throw new SessionException(
"The isolated session reported a collection result for a " +
"different request.");
}
return result;
}
finally
{
operation.Delete(requestPath);
operation.Delete(resultPath);
}
}
public async Task<SessionConfigReadinessResult> CheckConfigReadinessAsync(
SessionRecord record,
string helperPath,
CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(record);
ArgumentException.ThrowIfNullOrWhiteSpace(helperPath);
string requestId = _createRequestId();
using var operation = new SessionWorkspaceOperation(record, _isCurrentRecord);
string requestPath = operation.FilePath("config-readiness", requestId);
string resultPath = SessionLaunchProtocol.ResultPathFor(requestPath);
try
{
await operation.WriteTextNewAsync(
requestPath,
SessionConfigReadinessProtocol.SerializeRequest(
new SessionConfigReadinessRequest { RequestId = requestId }),
cancellationToken).ConfigureAwait(false);
_log("Checking agent-side OpenClaw config readiness.");
MxcExecutionResult execution = await ExecuteTimedAsync(
record.ToSandboxIdOrThrow(),
BuildGuestCommandLine(helperPath, requestPath, "--check-config"),
"Config readiness check",
cancellationToken).ConfigureAwait(false);
string resultText;
try
{
resultText = await operation.ReadTextAsync(resultPath, cancellationToken)
.ConfigureAwait(false);
}
catch (Exception exception) when (
exception is FileNotFoundException or DirectoryNotFoundException or IOException)
{
throw new SessionException(
"The isolated session did not report config readiness " +
DescribeMissingResult(execution),
exception);
}
SessionConfigReadinessResult result =
SessionConfigReadinessProtocol.ReadResult(resultText, requestId);
if (result.Error is { Length: > 0 } error)
{
throw new SessionException(
$"The isolated session could not check config readiness: {error}");
}
return result;
}
finally
{
operation.Delete(requestPath);
operation.Delete(resultPath);
}
}
public async Task<SessionCompanionConfigResult> ConfigureCompanionAsync(
SessionRecord record,
string helperPath,
string nodePath,
string applicationDirectory,
int port,
string? nativeRootPath,
string? preloadPath,
IReadOnlyDictionary<string, string> environment,
bool checkOnly,
string? token,
CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(record);
var request = new SessionCompanionConfigRequest
{
RequestId = _createRequestId(),
Port = port,
NodePath = nodePath,
ApplicationDirectory = applicationDirectory,
NativeRootPath = nativeRootPath,
PreloadPath = preloadPath,
Environment = environment,
CheckOnly = checkOnly,
Token = token
};
(string resultText, int exitCode) = await RunCompanionOperationAsync(
record, helperPath, request, "--companion-config",
"Companion Gateway configuration", cancellationToken).ConfigureAwait(false);
SessionCompanionConfigResult result;
try
{
result = SessionCompanionConfigProtocol.ReadResult(resultText, request.RequestId!);
}
catch (SessionLaunchException exception)
{
throw new SessionException(
$"The isolated session reported an invalid Companion configuration result: {exception.Message}",
exception);
}
if (result.Error is { Length: > 0 } error)
{
throw new SessionException($"The isolated session could not configure the Gateway: {error}");
}
if (exitCode != 0)
{
throw new SessionException(
$"The isolated session failed to configure the Gateway (executor exit code {exitCode}).");
}
return result;
}
private async Task<(string Text, int ExitCode)> RunCompanionOperationAsync(
SessionRecord record,
string helperPath,
SessionCompanionConfigRequest request,
string mode,
string subject,
CancellationToken cancellationToken)
{
using var operation = new SessionWorkspaceOperation(record, _isCurrentRecord);
string requestPath = operation.FilePath(mode[2..], request.RequestId!);
string resultPath = SessionLaunchProtocol.ResultPathFor(requestPath);
try
{
await operation.WriteTextNewAsync(
requestPath,
SessionCompanionConfigProtocol.SerializeRequest(request),
cancellationToken).ConfigureAwait(false);
_log($"Running {subject} inside the isolated session.");
MxcExecutionResult execution = await ExecuteTimedAsync(
record.ToSandboxIdOrThrow(),
BuildGuestCommandLine(helperPath, requestPath, mode),
subject,
cancellationToken).ConfigureAwait(false);
operation.EnsureCurrent();
try
{
string resultText = await operation.ReadTextAsync(resultPath, cancellationToken)
.ConfigureAwait(false);
return (resultText, execution.ExitCode);
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
{
throw new SessionException(
$"The isolated session did not report a {subject} result.", exception);
}
}
finally
{
operation.Delete(requestPath);
operation.Delete(resultPath);
}
}
/// <summary>
/// Installs the packaged Node.js runtime into the agent's profile.
/// </summary>
/// <remarks>
/// Setup invokes this explicitly rather than leaving the first gateway
/// launch to discover a missing agent runtime.
/// </remarks>
public async Task<SessionRuntimeInstallResult> InstallRuntimeAsync(
SessionRecord record,
string helperPath,
string archivePath,
string applicationDirectory,
CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(record);
ArgumentException.ThrowIfNullOrWhiteSpace(helperPath);
ArgumentException.ThrowIfNullOrWhiteSpace(archivePath);
ArgumentException.ThrowIfNullOrWhiteSpace(applicationDirectory);
string requestId = _createRequestId();
using var operation = new SessionWorkspaceOperation(record, _isCurrentRecord);
string requestPath = operation.FilePath("runtime", requestId);
string resultPath = SessionLaunchProtocol.ResultPathFor(requestPath);
try
{
await operation.WriteTextNewAsync(
requestPath,
SessionRuntimeProtocol.SerializeRequest(new SessionRuntimeInstallRequest
{
RequestId = requestId,
ArchivePath = archivePath,
ApplicationDirectory = applicationDirectory
}),
cancellationToken).ConfigureAwait(false);
_log("Installing the packaged Node.js runtime in the isolated session.");
MxcExecutionResult execution = await ExecuteTimedAsync(
record.ToSandboxIdOrThrow(),
BuildGuestCommandLine(helperPath, requestPath, "--install-runtime"),
"Node.js runtime installation",
cancellationToken).ConfigureAwait(false);
string resultText;
try
{
resultText = await operation.ReadTextAsync(resultPath, cancellationToken)
.ConfigureAwait(false);
}
catch (Exception exception) when (
exception is FileNotFoundException or DirectoryNotFoundException)
{
throw new SessionException(
"The isolated session did not report a runtime install " +
DescribeMissingResult(execution),
exception);
}
SessionRuntimeInstallResult result =
SessionRuntimeProtocol.ReadResult(resultText);
if (result.Error is { Length: > 0 } error)
{
throw new SessionException(
$"The packaged Node.js runtime could not be installed in the session: {error}");
}
if (!string.Equals(result.RequestId, requestId, StringComparison.Ordinal))
{
throw new SessionException(
"The isolated session reported a runtime install result " +
"for a different request.");
}
if (string.IsNullOrWhiteSpace(result.ExecutablePath) ||
string.IsNullOrWhiteSpace(result.Version))
{
throw new SessionException(
"The isolated session reported a runtime install without a " +
"Node.js executable path and version.");
}
return result;
}
finally
{
operation.Delete(requestPath);
operation.Delete(resultPath);
}
}
internal static IReadOnlyDictionary<string, string> MergeEnvironment(
IReadOnlyDictionary<string, string> baseEnvironment,
IReadOnlyDictionary<string, string>? additional)
{
ArgumentNullException.ThrowIfNull(baseEnvironment);
if (additional is null || additional.Count == 0)
{
return baseEnvironment;
}
var merged = new Dictionary<string, string>(
baseEnvironment, StringComparer.OrdinalIgnoreCase);
foreach (KeyValuePair<string, string> entry in additional)
{
merged[entry.Key] = entry.Value;
}
return merged;
}
/// <summary>Installs the agent command shim under the guest identity.</summary>
public async Task<SessionToolInstallResult> InstallToolsAsync(
SessionRecord record,
string helperPath,
CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(record);
ArgumentException.ThrowIfNullOrWhiteSpace(helperPath);
string requestId = _createRequestId();
using var operation = new SessionWorkspaceOperation(record, _isCurrentRecord);
string requestPath = operation.FilePath("tools", requestId);
string resultPath = SessionLaunchProtocol.ResultPathFor(requestPath);
try
{
await operation.WriteTextNewAsync(
requestPath,
SessionRuntimeProtocol.SerializeToolInstallRequest(new SessionToolInstallRequest
{
RequestId = requestId,
WorkspacePath = record.WorkspacePath
}),
cancellationToken).ConfigureAwait(false);
_log("Installing OpenClaw agent tools in the isolated session.");
MxcExecutionResult execution = await ExecuteTimedAsync(
record.ToSandboxIdOrThrow(),
BuildGuestCommandLine(helperPath, requestPath, "--install-tools"),
"Agent tool installation",
cancellationToken).ConfigureAwait(false);
string resultText;
try
{
resultText = await operation.ReadTextAsync(resultPath, cancellationToken)
.ConfigureAwait(false);
}
catch (Exception exception) when (
exception is FileNotFoundException or DirectoryNotFoundException)
{
throw new SessionException(
"The isolated session did not report a tool install " +
DescribeMissingResult(execution),
exception);
}
SessionToolInstallResult result =
SessionRuntimeProtocol.ReadToolInstallResult(resultText);
if (!string.Equals(result.RequestId, requestId, StringComparison.Ordinal))
{
throw new SessionException(
"The isolated session reported a tool install result for a different request.");
}
if (!string.IsNullOrWhiteSpace(result.Error))
{
throw new SessionException(
$"The OpenClaw agent tools could not be installed: {result.Error}");
}
if (string.IsNullOrWhiteSpace(result.ShimPath))
{
throw new SessionException(
"The isolated session did not report the installed command shim.");
}
return result;
}
finally
{
operation.Delete(requestPath);
operation.Delete(resultPath);
}
}
private static List<string> BuildNodeArguments(
SessionExecutionRequest request)
{
string entryPoint = Path.Combine(request.ApplicationDirectory, "openclaw.mjs");
var arguments = new List<string>(
(request.NodeArgumentsPrefix?.Count ?? 0) + request.Arguments.Count + 1);
if (request.NodeArgumentsPrefix is not null)
{
arguments.AddRange(request.NodeArgumentsPrefix);
}
arguments.Add(entryPoint);
arguments.AddRange(request.Arguments);
return arguments;
}
/// <summary>
/// Builds the only command line the backend ever sees.
/// </summary>
/// <remarks>
/// <para>
/// The SDK's pipe path uses <c>cmd.exe /c</c>, while its PTY path appends
/// this command after a startup gate. An explicit inner
/// <c>cmd.exe /d /s /c</c> consumes the outer quote pair in both cases,
/// preserving the helper and request paths without relying on their
/// position in the SDK's command line.
/// </para>
/// <para>
/// Both values are paths this package controls, but they are still verified
/// rather than trusted, because <c>cmd.exe</c> also expands <c>%VAR%</c>
/// and lets an embedded quote truncate the rest of the line.
/// </para>
/// </remarks>
internal static string BuildGuestCommandLine(
string helperPath,
string requestPath,
string option = "--request")
{
Verify(helperPath, nameof(helperPath));
Verify(requestPath, nameof(requestPath));
return $"cmd.exe /d /s /c \"\"{helperPath}\" {option} \"{requestPath}\"\"";
static void Verify(string value, string name)
{
if (string.IsNullOrWhiteSpace(value))
{
throw new SessionException($"The {name} is empty.");
}
if (value.Contains('"', StringComparison.Ordinal) ||
value.Contains('%', StringComparison.Ordinal))
{
throw new SessionException(
$"The {name} contains a quote or percent sign, which the " +
"isolated-session command line cannot carry safely: " +
value);
}
}
}
/// <summary>
/// Establishes what actually happened from the helper's control result.
/// </summary>
/// <remarks>
/// The helper returns the child exit code after a launch and its own
/// failure code otherwise. Either code can also be returned by OpenClaw,
/// so the correlated result is required to interpret the executor outcome.
/// </remarks>
private static SessionCommandCaptureResult ReadCapturedOutcome(
SessionWorkspaceOperation operation,
string resultPath,
MxcExecutionResult execution,
string requestId,
string subject)
{
string resultText;
try
{
resultText = operation.ReadTextAsync(resultPath, CancellationToken.None)
.GetAwaiter().GetResult();
}
catch (Exception exception) when (
exception is FileNotFoundException or DirectoryNotFoundException or IOException)
{
throw new SessionException(
"The isolated session did not report a launch result " +
$"(executor exit code {execution.ExitCode}). {subject} may not have started.",
exception);
}
SessionLaunchResult result;
try
{
result = SessionLaunchProtocol.ReadResult(resultText);
}
catch (SessionLaunchException exception)
{
throw new SessionException(
$"The isolated session reported an unreadable launch result: {exception.Message}",
exception);
}
if (!string.Equals(result.RequestId, requestId, StringComparison.Ordinal))
{
throw new SessionException(
"The isolated session reported a launch result for a different request.");
}
if (!result.Launched)
{
throw new SessionException(
$"{subject} could not be started inside the isolated session: " +
(result.Error ?? "no reason was reported."));
}
if (result.ExitCode is not int childExitCode)
{
throw new SessionException(
$"The isolated session reported that it launched {subject} without an exit code.");
}
if (execution.ExitCode != childExitCode)
{
throw new SessionException(
$"The isolated session reported {subject} exit code " +
$"{childExitCode.ToString(CultureInfo.InvariantCulture)}, but the " +
$"executor returned exit code {execution.ExitCode.ToString(CultureInfo.InvariantCulture)}.");
}
return new SessionCommandCaptureResult(
childExitCode,
execution.StandardOutput,
execution.StandardError);
}
private static int ReadOutcome(
SessionWorkspaceOperation operation,
string resultPath,
int executorExitCode,
string requestId,
string subject)
{
string resultText;
try
{
resultText = operation.ReadTextAsync(resultPath, CancellationToken.None)
.GetAwaiter().GetResult();
}
catch (Exception exception) when (
exception is FileNotFoundException or DirectoryNotFoundException or IOException)
{
if (executorExitCode == ControlCExitCode)
{
return PortableInterruptedExitCode;
}
throw new SessionException(
"The isolated session did not report a launch result " +
$"(executor exit code {executorExitCode}). {subject} may not " +
"have started.",
exception);
}
SessionLaunchResult result;
try
{
result = SessionLaunchProtocol.ReadResult(resultText);
}
catch (SessionLaunchException exception)
{
throw new SessionException(
$"The isolated session reported an unreadable launch result: " +
$"{exception.Message}",
exception);
}
if (!result.Launched)
{
throw new SessionException(
$"{subject} could not be started inside the isolated session: " +
(result.Error ?? "no reason was reported."));
}
if (!string.Equals(result.RequestId, requestId, StringComparison.Ordinal))
{
throw new SessionException(
"The isolated session reported a launch result for a " +