Repository navigation
Expand file tree
/
Copy pathProgram.cs
More file actions
1425 lines (1353 loc) · 64.6 KB
/
Copy pathProgram.cs
File metadata and controls
1425 lines (1353 loc) · 64.6 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.CommandLine;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text;
using OpenClaw.SessionProtocol;
namespace OpenClaw.Launcher;
internal static class Program
{
public static async Task<int> Main(string[] args) =>
await RunAsync(args, HostStartup.CreateProduction()).ConfigureAwait(false);
// The whole startup path lives here rather than in Main so that tests can
// drive it with fixture-owned diagnostics and writers. Main is only the
// production adapter that supplies the real collaborators.
[SuppressMessage(
"Design",
"CA1031:Do not catch general exception types",
Justification =
"This is the process last-chance handler. Every narrower catch in " +
"this assembly uses an exception filter; this one deliberately does " +
"not, because narrowing it would replace the diagnostic log entry, " +
"the user-facing error message, and the deterministic exit code 1 " +
"with an unhandled-exception crash.")]
internal static async Task<int> RunAsync(string[] args, HostStartup startup)
{
string commandName = startup.Entrypoint == HostEntrypoint.Control
? HostEntrypointResolver.ControlCommandName
: HostEntrypointResolver.AgentCommandName;
HostDiagnosticLog? diagnostics = null;
bool diagnosticWarningWritten = false;
bool consoleWarningWritten = false;
IDisposable? consoleRestore = null;
var controlOutputOptions = new ClawCtlOutputOptions
{
Json = ResolveBooleanOption(args, "--json")
};
TextWriter output = startup.Output;
TextWriter error = startup.Error;
void WriteConsoleError(string message)
{
try
{
error.WriteLine(message);
}
catch (Exception exception) when (
exception is IOException or ObjectDisposedException)
{
if (!consoleWarningWritten)
{
consoleWarningWritten = true;
WriteDiagnostic(
$"Console error output failed: {DiagnosticFailure.Describe(exception)}");
}
}
}
try
{
diagnostics = startup.CreateDiagnostics();
}
catch (Exception exception) when (
exception is IOException or
UnauthorizedAccessException or
InvalidOperationException)
{
diagnosticWarningWritten = true;
WriteConsoleError(
$"{commandName}: Unable to create diagnostics: {exception.Message}");
}
void WriteDiagnostic(string message)
{
if (diagnostics is null)
{
return;
}
try
{
diagnostics.Write(message);
}
catch (Exception exception) when (
exception is IOException or
UnauthorizedAccessException or
ObjectDisposedException)
{
if (!diagnosticWarningWritten)
{
diagnosticWarningWritten = true;
WriteConsoleError(
$"{commandName}: Unable to write diagnostics: {exception.Message}");
}
}
}
void WriteFailureOutput(Action write, string destination)
{
try
{
write();
}
catch (Exception exception) when (
exception is IOException or ObjectDisposedException)
{
WriteDiagnostic(
$"Failure output to {destination} failed: " +
DiagnosticFailure.Describe(exception));
}
}
try
{
WriteDiagnostic($"Host started through the {commandName} entrypoint.");
if (startup.UsesProcessConsoleWriters &&
WindowsHostConsole.Instance.IsInteractive)
{
consoleRestore = WindowsHostConsole.Instance.Capture(WriteDiagnostic);
WindowsHostConsole.Instance.InitializeUtf8();
output = Console.Out;
error = Console.Error;
}
HostOptions options = HostOptions.Parse(args, startup.BaseDirectory);
string environment = (startup.ReadEnvironment ?? (parsed => HostEnvironment.Read(
startup.BaseDirectory,
parsed.PackagedNodeArchivePath)))(options)
.Describe();
WriteDiagnostic($"Environment: {environment}");
return startup.Entrypoint == HostEntrypoint.Control
? await RunControlAsync(
options,
args,
WriteDiagnostic,
output,
error,
startup.InstallationLifecycle,
controlOutputOptions: controlOutputOptions,
environment: environment,
archiveDirectory: startup.ArchiveDirectory).ConfigureAwait(false)
: await RunAgentAsync(
options,
WriteDiagnostic,
startup.InstallationLifecycle is null
? null
: startup.InstallationLifecycle.CreateRuntime,
probeReadiness: startup.ProbeReadiness,
getPackageFamilyName: startup.GetPackageFamilyName,
readEnvironmentVariable: startup.ReadEnvironmentVariable,
isInteractive: startup.IsInteractive,
error: error,
errorIsProcessConsoleWriter:
startup.UsesProcessConsoleWriters ? () => true : null,
installationLifecycle: startup.InstallationLifecycle)
.ConfigureAwait(false);
}
catch (Exception exception)
{
WriteDiagnostic(
$"Unhandled failure: {DiagnosticFailure.DescribeWithStackTrace(exception)}");
if (startup.Entrypoint == HostEntrypoint.Control)
{
string command = ResolveClawCtlCommand(args);
if (controlOutputOptions.Json)
{
WriteFailureOutput(
() => ClawCtlJson.WriteFailure(
output,
command,
exception.Message),
"standard output");
}
else
{
WriteFailureOutput(() =>
{
bool outputIsProcessConsoleWriter =
ReferenceEquals(error, Console.Error);
bool consoleIsInteractive =
WindowsHostConsole.Instance.IsInteractiveOutput(error);
IDisposable? restore = null;
bool useColor = ClawCtlColorPolicy.PrepareOutput(
args.Contains("--no-color", StringComparer.Ordinal),
json: false,
outputIsProcessConsoleWriter,
consoleIsInteractive,
Environment.GetEnvironmentVariable,
() => WindowsHostConsole.Instance
.TryEnableVirtualTerminalProcessing(
error,
WriteDiagnostic,
out restore));
using (restore)
{
if (exception is Session.InteractiveLogonRequiredException or
Session.UnownedSetupEvidenceException)
{
ClawCtlConsole.WriteActionableFailure(
error,
command,
exception.Message,
useColor);
}
else
{
ClawCtlConsole.WriteUnexpectedFailure(
error,
command,
exception.Message,
useColor);
}
}
}, "standard error");
}
}
else
{
WriteConsoleError($"{commandName}: {exception.Message}");
if (diagnostics is not null)
{
WriteConsoleError(
$"{commandName}: See diagnostics: {diagnostics.Path}");
}
}
return 1;
}
finally
{
WriteDiagnostic("Host exiting.");
consoleRestore?.Dispose();
diagnostics?.Dispose();
}
}
private static string ResolveClawCtlCommand(string[] args)
{
for (int index = 0; index < args.Length; index++)
{
string argument = args[index];
if (argument == "gateway-service")
{
string? action = args
.Skip(index + 1)
.FirstOrDefault(candidate =>
candidate is "start" or "status" or "stop" or "restart");
return action is null ? argument : $"{argument} {action}";
}
if (argument == "companion")
{
string? action = args.Skip(index + 1)
.FirstOrDefault(candidate => candidate == "prepare");
return action is null ? argument : $"{argument} {action}";
}
if (argument is "setup" or "status" or "collect-logs" or "teardown" or
"open" or "pwsh" or "backup" or "restore" or "recover")
{
return argument;
}
}
return "command";
}
private static bool ResolveBooleanOption(string[] args, string option)
{
bool value = false;
for (int index = 0; index < args.Length; index++)
{
string argument = args[index];
if (argument.Equals(option, StringComparison.Ordinal))
{
value = index + 1 >= args.Length ||
!bool.TryParse(args[index + 1], out bool explicitValue) ||
explicitValue;
continue;
}
if (argument.StartsWith($"{option}=", StringComparison.Ordinal) ||
argument.StartsWith($"{option}:", StringComparison.Ordinal))
{
int separator = option.Length;
value = bool.TryParse(argument[(separator + 1)..], out bool explicitValue) &&
explicitValue;
}
}
return value;
}
// Every collaborator after the readiness probe is a test seam: tests
// substitute fakes so they can assert launch behavior without provisioning
// a real isolated session.
internal static async Task<int> RunAgentAsync(
HostOptions options,
Action<string> log,
Func<Action<string>, Session.SessionRuntime>? createSessionRuntime = null,
Func<CancellationToken, Task<Mxc.MxcReadinessReport>>? probeReadiness = null,
Func<string?>? getPackageFamilyName = null,
Func<string, string?>? readEnvironmentVariable = null,
Func<bool>? isInteractive = null,
TextWriter? error = null,
Func<string>? getLogonSessionId = null,
TimeProvider? clock = null,
Func<bool>? errorIsProcessConsoleWriter = null,
Func<bool>? errorIsInteractive = null,
Func<bool>? supportsUnicode = null,
Session.IInstallationLifecycle? installationLifecycle = null)
{
string applicationDirectory = options.RequirePackagedApplicationDirectory();
log("Using the OpenClaw application directly from the package.");
Mxc.MxcReadinessReport readiness = await (probeReadiness ??
Mxc.MxcReadiness.ProbeAsync)(CancellationToken.None).ConfigureAwait(false);
log($"Isolated-session support: {readiness.Describe()}");
Session.SessionSupportPolicy.EnsureSupported(
(getPackageFamilyName ?? (() => HostPaths.Create().PackageFamilyName))(),
readiness);
log("The isolated-session backend is available.");
bool interactive =
(isInteractive ?? (() => WindowsHostConsole.Instance.IsInteractive))();
TextWriter errorWriter = error ?? Console.Error;
Func<string, string?> environmentReader =
readEnvironmentVariable ?? Environment.GetEnvironmentVariable;
Session.SessionRuntime runtime = (createSessionRuntime ??
Session.SessionRuntime.Create)(log);
await EnsureSetupForLaunchAsync(
options,
runtime,
installationLifecycle,
applicationDirectory,
interactive,
environmentReader,
errorWriter,
log,
errorIsProcessConsoleWriter,
errorIsInteractive).ConfigureAwait(false);
Session.SessionRecord record =
await runtime.StartForExecutionAsync(CancellationToken.None)
.ConfigureAwait(false);
string agentNodePath = runtime.RequireAgentNodePath(
options.RequirePackagedNodeArchivePath());
int exitCode = await runtime.Executor.ExecuteAsync(
record,
new Session.SessionExecutionRequest(
runtime.RequireStagedHelper(record),
agentNodePath,
applicationDirectory,
options.OpenClawArguments,
record.WorkspacePath!)
{
AdditionalEnvironment = BuildRuntimeEnvironment(
runtime,
applicationDirectory,
interactive,
environmentReader),
NodeArgumentsPrefix = BuildNativeRedirectNodeArguments(runtime),
NativeRootPath = runtime.GetAgentNativeRoot()
},
CancellationToken.None).ConfigureAwait(false);
return await Gateway.AgentPostflight.Create(
options,
runtime,
record,
interactive,
environmentReader,
log,
clock,
getLogonSessionId,
errorIsProcessConsoleWriter,
errorIsInteractive,
supportsUnicode)
.RunAsync(exitCode, interactive, errorWriter)
.ConfigureAwait(false);
}
/// <summary>
/// Provisions this installation, when it has never been set up, before an
/// <c>openclaw</c> launch needs the session.
/// </summary>
/// <remarks>
/// <para>
/// Narration goes to standard error. Standard output belongs to the
/// OpenClaw child, so piping <c>openclaw --version</c> must not pick up a
/// setup message.
/// </para>
/// <para>
/// Only an absent setup marker is provisioned. Anything else is left for
/// <see cref="Session.SessionRuntime.RequireSetup"/> to report with the
/// command that resolves it.
/// </para>
/// </remarks>
private static async Task EnsureSetupForLaunchAsync(
HostOptions options,
Session.SessionRuntime runtime,
Session.IInstallationLifecycle? installationLifecycle,
string applicationDirectory,
bool interactive,
Func<string, string?> environmentReader,
TextWriter errorWriter,
Action<string> log,
Func<bool>? errorIsProcessConsoleWriter,
Func<bool>? errorIsInteractive)
{
if (installationLifecycle is null)
{
log("Automatic setup is unavailable: no installation lifecycle was supplied.");
return;
}
if (!Gateway.AutoBehaviorPolicy.IsAutomaticSetupEnabled(environmentReader))
{
// The operator opted out, so an installation that was never set up
// must fail exactly as it did before automatic setup existed.
log(
"Automatic setup is disabled by " +
$"{OpenClawRuntimeEnvironment.AutoSetupVariable}.");
return;
}
if (!Session.SetupOrchestrator.NeedsProvisioning(runtime))
{
return;
}
IDisposable? restore = null;
bool useColor = ClawCtlColorPolicy.PrepareForegroundOutput(
noColor: false,
json: false,
errorIsProcessConsoleWriter?.Invoke() ??
ReferenceEquals(errorWriter, Console.Error),
interactive,
errorIsInteractive?.Invoke() ??
WindowsHostConsole.Instance.IsInteractiveOutput(errorWriter),
environmentReader,
() => WindowsHostConsole.Instance.TryEnableVirtualTerminalProcessing(
errorWriter,
log,
out restore));
using (restore)
{
_ = await ClawCtlConsole.NarrateAsync(
errorWriter,
useColor,
narrate: true,
new ClawCtlProgress("Setting up OpenClaw for first use."),
progress => Session.SetupOrchestrator.EnsureAsync(
options,
runtime,
installationLifecycle,
applicationDirectory,
log,
progress,
CancellationToken.None)).ConfigureAwait(false);
}
}
/// <summary>
/// The environment for an OpenClaw launch, excluding the pieces the agent
/// account owns.
/// </summary>
/// <remarks>
/// Built in one place so foreground and gateway launch paths resolve native
/// addons the same way. The agent shell carries equivalent values through
/// its command shim because agent tooling may replace process environment
/// values before invoking <c>openclaw</c>. The redirect's preload is not
/// here: it belongs on the agent Node.js argument vector.
/// </remarks>
private static IReadOnlyDictionary<string, string> BuildRuntimeEnvironment(
Session.SessionRuntime runtime,
string applicationDirectory,
bool isInteractive,
Func<string, string?> readEnvironmentVariable)
{
IReadOnlyDictionary<string, string> environment =
OpenClawRuntimeEnvironment.Build(isInteractive, readEnvironmentVariable);
if (runtime.GetAgentNativeRoot() is not { Length: > 0 } nativeRoot)
{
return environment;
}
return Session.SessionExecutor.MergeEnvironment(
environment,
OpenClawRuntimeEnvironment.BuildNativeRedirect(
applicationDirectory,
nativeRoot));
}
/// <summary>
/// The Node.js arguments that load the redirect, or <see langword="null"/>
/// when setup staged nothing to redirect to.
/// </summary>
private static IReadOnlyList<string>? BuildNativeRedirectNodeArguments(
Session.SessionRuntime runtime) =>
runtime.GetAgentNativeRoot() is { Length: > 0 }
? OpenClawRuntimeEnvironment.BuildNativeRedirectNodeArguments(
ResolveNativeRedirectPreloadPath())
: null;
internal static string ResolveNativeRedirectPreloadPath() =>
Path.GetFullPath(
Path.Combine(
AppContext.BaseDirectory,
OpenClawRuntimeEnvironment.NodeScriptDirectoryName,
OpenClawRuntimeEnvironment.NativeRedirectFileName));
// output and error are required parameters (not Console defaults) so tests
// can capture clawctl output without mutating global console state,
// which would be unsafe across parallel test runs.
internal static async Task<int> RunControlAsync(
HostOptions options,
IReadOnlyList<string> args,
Action<string> log,
TextWriter output,
TextWriter error,
Session.IInstallationLifecycle? installationLifecycle = null,
Func<string, string?>? readEnvironmentVariable = null,
ClawCtlOutputOptions? controlOutputOptions = null,
Func<string>? getLogonSessionId = null,
TimeProvider? clock = null,
Func<string, Task>? launchBrowserAsync = null,
Action? beforeBrowserValidation = null,
string? environment = null,
Func<CancellationToken, Task<string?>>? readInputLine = null,
string? archiveDirectory = null,
Gateway.HostPackageDiagnostics? packageDiagnostics = null)
{
Session.IInstallationLifecycle lifecycle =
installationLifecycle ?? Session.InstallationLifecycle.Production;
ClawCtlOutputOptions outputOptions =
controlOutputOptions ?? new ClawCtlOutputOptions();
Session.SessionRuntime? sessionRuntime = null;
Session.SessionRuntime GetSessionRuntime() =>
sessionRuntime ??= lifecycle.CreateRuntime(log);
StateTransfer.StateTransferCoordinator CreateStateTransfer() =>
new(
options,
GetSessionRuntime,
new StateTransfer.StateArchiveStore(
archiveDirectory ??
throw new Session.SessionException(
"The invoking user's archive directory could not be resolved."),
log,
clock),
log,
!outputOptions.Json && !Console.IsInputRedirected &&
ReferenceEquals(output, Console.Out) &&
WindowsHostConsole.Instance.IsInteractiveOutput(output)
? ConfirmStateTransferAsync
: null);
Task<bool> ConfirmStateTransferAsync(string source, CancellationToken token)
{
token.ThrowIfCancellationRequested();
(bool useColor, IDisposable? restore) = PrepareColor(error);
using (restore)
{
return Task.FromResult(ClawCtlConsole.ConfirmStateReplacement(error, useColor, source));
}
}
// Narration goes to standard error and the result to standard output,
// so colour is decided for the stream being written: redirecting one
// must not strip or force colour on the other. The returned scope
// restores the console mode and must be held for as long as that
// stream is being written.
(bool UseColor, IDisposable? Restore) PrepareColor(TextWriter target)
{
IDisposable? restore = null;
bool useColor = ClawCtlColorPolicy.PrepareOutput(
outputOptions.NoColor,
outputOptions.Json,
ReferenceEquals(target, Console.Out) ||
ReferenceEquals(target, Console.Error),
WindowsHostConsole.Instance.IsInteractiveOutput(target),
Environment.GetEnvironmentVariable,
() => WindowsHostConsole.Instance
.TryEnableVirtualTerminalProcessing(target, log, out restore));
return (useColor, restore);
}
async Task<T> NarrateOperationAsync<T>(
ClawCtlProgress initial,
Func<IProgress<ClawCtlProgress>, Task<T>> operation,
bool allowLiveStatus = true)
{
(bool useColor, IDisposable? restore) = outputOptions.Json
? (false, null)
: PrepareColor(error);
using (restore)
{
return await ClawCtlConsole.NarrateAsync(
error,
useColor,
narrate: !outputOptions.Json,
initial,
operation,
allowLiveStatus).ConfigureAwait(false);
}
}
int WriteResult(IClawCtlResult result)
{
if (outputOptions.Json)
{
ClawCtlJson.WriteResult(output, result);
}
else
{
(bool useColor, IDisposable? restore) = PrepareColor(output);
using (restore)
{
ClawCtlConsole.WriteResult(output, result, useColor);
}
}
return result.ExitCode;
}
void AcknowledgeManualGatewayStart(Session.SessionRuntime runtime)
{
new Gateway.AgentGatewayGuidance(
runtime.LifecycleLock,
_ => throw new InvalidOperationException(
"Manual acknowledgement must not check config readiness."),
_ => throw new InvalidOperationException(
"Manual acknowledgement must not inspect the gateway."),
new Gateway.GatewayGuidanceStateStore(
runtime.Paths.GatewayGuidanceStatePath),
getLogonSessionId ?? Gateway.WindowsLogonSession.GetCurrentId,
log,
clock)
.AcknowledgeManualStart();
}
int WriteGatewayStartResult(string action, Gateway.GatewayStartResult result)
{
int? port = result.State == Gateway.GatewayState.Starting
? null
: Gateway.GatewayAddress.ResolvePort(result.Record);
return WriteResult(new GatewayCommandResult(
action,
result.State,
result.Message,
null,
result.State is Gateway.GatewayState.Running or Gateway.GatewayState.Starting ? 0 : 1,
port,
Launch: result.Record.AttemptId is string attemptId
? new Gateway.GatewayLaunchReceipt(attemptId, result.Created ? "created" : "adopted")
: null));
}
IReadOnlyDictionary<string, string> CompanionEnvironment(
string applicationDirectory, string? nativeRoot) =>
nativeRoot is null
? OpenClawRuntimeEnvironment.Build()
: Session.SessionExecutor.MergeEnvironment(
OpenClawRuntimeEnvironment.Build(),
OpenClawRuntimeEnvironment.BuildNativeRedirect(
applicationDirectory, nativeRoot));
async Task<int> RunSetupCommandAsync(
SetupOptions setupOptions,
CancellationToken cancellationToken)
{
try
{
SetupCommandResult result = await NarrateOperationAsync(
new ClawCtlProgress("Checking isolated-session support."),
progress => Session.SetupOrchestrator.RunAsync(
setupOptions,
options,
GetSessionRuntime,
lifecycle,
log,
progress,
cancellationToken))
.ConfigureAwait(false);
return WriteResult(result);
}
catch (Session.SessionException exception) when (outputOptions.Json)
{
log($"Setup failed: {DiagnosticFailure.Describe(exception)}");
return WriteResult(new SetupCommandResult(
1,
options.RequirePackagedApplicationDirectory(),
null,
null,
false,
Error: exception.Message,
Fresh: setupOptions.Fresh));
}
}
RootCommand command = ClawCtlCommandLine.Create(
new ClawCtlHandlers
{
Backup = async (backupOptions, cancellationToken) =>
{
StateArchiveCommandResult result = await NarrateOperationAsync(
new ClawCtlProgress(backupOptions.List
? "Listing retained recovery archives."
: "Capturing and verifying agent state."),
_ => CreateStateTransfer().BackupAsync(backupOptions, cancellationToken))
.ConfigureAwait(false);
return WriteResult(result);
},
Restore = async (restoreOptions, cancellationToken) =>
{
StateArchiveCommandResult result = await NarrateOperationAsync(
new ClawCtlProgress(restoreOptions.DryRun
? "Verifying the state archive and previewing restoration."
: restoreOptions.Rollback
? "Rolling back interrupted state activation."
: "Preparing protected state restoration."),
_ => CreateStateTransfer().RestoreAsync(restoreOptions, cancellationToken),
allowLiveStatus: restoreOptions.DryRun || restoreOptions.Yes)
.ConfigureAwait(false);
return WriteResult(result);
},
Recover = async (recoverOptions, cancellationToken) =>
{
StateArchiveCommandResult result = await NarrateOperationAsync(
new ClawCtlProgress(recoverOptions.DryRun
? "Inspecting the offline profile for recovery."
: "Preparing protected recovery of the offline profile."),
_ => CreateStateTransfer().RecoverAsync(recoverOptions, cancellationToken),
allowLiveStatus: recoverOptions.DryRun || recoverOptions.Yes)
.ConfigureAwait(false);
return WriteResult(result);
},
Setup = RunSetupCommandAsync,
Status = async cancellationToken =>
{
StatusCommandResult result = await NarrateOperationAsync(
new ClawCtlProgress("Checking session, gateway, and recovery status."),
async _ =>
{
Session.SessionRuntime runtime = GetSessionRuntime();
Session.SessionStatus status = await runtime
.Coordinator.ProbeRecordedStatusAsync(cancellationToken)
.ConfigureAwait(false);
Gateway.GatewayStatusReport gateway =
await Gateway.GatewayRuntime
.Create(options, runtime.Paths, runtime, log)
.Controller
.GetStatusAsync(runtime.HelperPath, cancellationToken)
.ConfigureAwait(false);
Gateway.GatewayPersistenceStatus recovery = await lifecycle
.GetRecoveryStatusAsync(log, cancellationToken)
.ConfigureAwait(false);
OpenClaw.SessionProtocol.SessionStateTransferResult? stateTransfer =
await StateTransfer.StateTransferCoordinator.InspectAvailableAsync(
runtime, status, log, cancellationToken).ConfigureAwait(false);
Session.AgentConfigReadinessStatus? configReadiness =
gateway.State == Gateway.GatewayState.Running || stateTransfer?.Pending == true
? null
: await Session.AgentConfigReadinessProbe.CheckAsync(
runtime,
status,
log,
cancellationToken).ConfigureAwait(false);
Session.SetupStateResult setup =
runtime.SetupState.Read(runtime.ApplicationId);
return new StatusCommandResult(
status,
gateway,
recovery,
setup.Record?.AgentNodeVersion,
configReadiness,
stateTransfer,
status.Fault == Session.SessionStateFault.Missing &&
Session.SessionCoordinator.MayLocateProvision(setup)
? Session.SessionCoordinator.DescribeUnownedSetupEvidence(
runtime.SetupState.FilePath)
: null);
}).ConfigureAwait(false);
return WriteResult(result);
},
CollectLogs = async (requestedPath, cancellationToken) =>
{
Session.SessionRuntime runtime = GetSessionRuntime();
Gateway.GatewayRuntime gateway = Gateway.GatewayRuntime.Create(
options,
runtime.Paths,
runtime,
log);
Gateway.DiagnosticsBundleResult result = await NarrateOperationAsync(
new ClawCtlProgress("Collecting redacted diagnostics."),
progress => gateway.CollectLogsAsync(
requestedPath,
environment,
progress,
cancellationToken,
packageDiagnostics ??
Gateway.HostPackageDiagnostics.CreateDefault(runtime.Paths))).ConfigureAwait(false);
return WriteResult(new CollectLogsCommandResult(result));
},
Teardown = async (force, cancellationToken) =>
{
if (!force)
{
const string message =
"Teardown removes the isolated session and its data. " +
"Re-run with --force to continue.";
if (outputOptions.Json)
{
return WriteResult(new TeardownCommandResult(
new Session.TeardownResult(false, message)));
}
await error.WriteLineAsync(message).ConfigureAwait(false);
return 1;
}
Session.SessionRuntime runtime = GetSessionRuntime();
Session.TeardownResult result = await NarrateOperationAsync(
new ClawCtlProgress("Removing the isolated session and its data."),
_ => lifecycle.TeardownAsync(
options,
runtime,
log,
lockAlreadyHeld: false,
cancellationToken)).ConfigureAwait(false);
return WriteResult(new TeardownCommandResult(result));
},
PayloadPrewarm = cancellationToken => Task.FromResult(
OpenClaw.Launcher.PayloadPrewarm.RunWorker(options, log, cancellationToken)),
Open = async cancellationToken =>
{
Session.SessionRuntime runtime = GetSessionRuntime();
try
{
_ = runtime.RequireSetup();
}
catch (Session.SessionException exception)
{
log($"The Control UI cannot be opened: {DiagnosticFailure.Describe(exception)}");
return WriteResult(new OpenCommandResult(null, exception.Message, 1));
}
OpenCommandResult result = await NarrateOperationAsync(
new ClawCtlProgress("Preparing the Control UI handoff."),
async _ =>
{
Gateway.GatewayStatusReport gateway = await Gateway.GatewayRuntime
.Create(options, runtime.Paths, runtime, log)
.Controller
.GetStatusAsync(runtime.HelperPath, cancellationToken)
.ConfigureAwait(false);
if (gateway.State != Gateway.GatewayState.Running)
{
string message = gateway.State is
Gateway.GatewayState.NotStarted or
Gateway.GatewayState.Stopped
? $"{gateway.Message} Run `clawctl gateway-service start` before opening the Control UI."
: gateway.Message;
return new OpenCommandResult(gateway.State, message, 1);
}
Session.SessionRecord record =
await runtime.StartForExecutionAsync(cancellationToken)
.ConfigureAwait(false);
string applicationDirectory =
options.RequirePackagedApplicationDirectory();
string nodePath = runtime.RequireAgentNodePath(
options.RequirePackagedNodeArchivePath());
IReadOnlyDictionary<string, string> dashboardEnvironment =
BuildRuntimeEnvironment(
runtime,
applicationDirectory,
isInteractive: false,
readEnvironmentVariable ??
Environment.GetEnvironmentVariable);
if (gateway.Record?.ObservedPorts is { Count: 1 } observedPorts)
{
dashboardEnvironment = Session.SessionExecutor.MergeEnvironment(
dashboardEnvironment,
new Dictionary<string, string>
{
[Gateway.GatewayConfigurationStore.PortVariable] =
observedPorts[0].ToString(
CultureInfo.InvariantCulture)
});
}
Session.SessionCommandCaptureResult capture = await runtime.Executor
.ExecuteCommandCaptureAsync(
record,
new Session.SessionCommandRequest(
runtime.RequireStagedHelper(record),
nodePath,
[
.. BuildNativeRedirectNodeArguments(runtime) ?? [],
Path.Combine(applicationDirectory, "openclaw.mjs"),
"dashboard",
"--json"
],
record.WorkspacePath!)
{
PathPrefix = Path.GetDirectoryName(nodePath),
AdditionalEnvironment = dashboardEnvironment,
NativeRootPath = runtime.GetAgentNativeRoot()
},
"Resolving the Control UI handoff in the isolated session.",
"OpenClaw dashboard",
cancellationToken)
.ConfigureAwait(false);
if (capture.ExitCode != 0)
{
// Captured output can carry the authenticated
// handoff, so only the exit code reaches the
// diagnostic log that collect-logs bundles.
string dashboardExit =
"The OpenClaw dashboard exited with code " +
$"{capture.ExitCode.ToString(CultureInfo.InvariantCulture)}.";
log($"The Control UI cannot be opened: {dashboardExit}");
return new OpenCommandResult(
gateway.State,
$"{dashboardExit} Run `clawctl collect-logs` and review the diagnostics bundle.",
1);
}
if (!Gateway.ControlUiHandoffParser.TryParse(
capture.StandardOutput,
gateway.Record?.ObservedPorts ?? [],
out string? browserUrl) ||
browserUrl is null)
{
return new OpenCommandResult(
gateway.State,
"OpenClaw did not return a usable Control UI handoff.",
1);
}
beforeBrowserValidation?.Invoke();
if (!runtime.IsCurrentSessionRecord(record))
{
return new OpenCommandResult(
gateway.State,
"The isolated session changed before the Control UI could be opened. Retry the command.",
1);
}
try
{
await (launchBrowserAsync ??
(url => LaunchBrowserAsync(url)))(browserUrl)
.ConfigureAwait(false);
}
catch (Exception exception) when (
exception is System.ComponentModel.Win32Exception or
InvalidOperationException or
NotSupportedException)
{
// The start failure message names the URL it tried to
// open, and a Control UI handoff URL can carry the
// gateway credential, so only the error code is kept.
log(exception is System.ComponentModel.Win32Exception win32
? $"Browser launch failed: Win32Exception [Win32 error {win32.NativeErrorCode}]"
: $"Browser launch failed: {exception.GetType().Name}");
return new OpenCommandResult(
gateway.State,
"The Control UI is ready, but the default browser could not be opened.",
1);
}
return new OpenCommandResult(
gateway.State,
"Opened the Control UI in the default browser.",
0);
}).ConfigureAwait(false);
return WriteResult(result);
},
PowerShell = (powerShellOptions, cancellationToken) => RunPowerShellAsync(
options,
GetSessionRuntime(),
powerShellOptions,
cancellationToken),
Completion = (completionOptions, _) =>
{
if (completionOptions.Uninstall)
{
string uninstalledProfilePath = PowerShellCompletion.Uninstall(
completionOptions.ProfilePath ??
PowerShellCompletion.DefaultProfilePath());
DeleteCompletionCache(GetSessionRuntime().Paths.CompletionCachePath);
return Task.FromResult(WriteResult(new CompletionCommandResult(
PowerShellCompletion.ClawCtlScript,
uninstalledProfilePath,
CachePath: null,
ExitCode: 0)));
}