Repository navigation
Expand file tree
/
Copy pathSessionRuntime.cs
More file actions
313 lines (269 loc) · 11 KB
/
Copy pathSessionRuntime.cs
File metadata and controls
313 lines (269 loc) · 11 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
using OpenClaw.Launcher.Mxc;
using OpenClaw.Launcher.Gateway;
using OpenClaw.SessionProtocol;
namespace OpenClaw.Launcher.Session;
/// <summary>
/// Assembles the session stack from the running installation.
/// </summary>
/// <remarks>
/// Composition lives here rather than in <c>Program</c> so both the agent and
/// control entry points build the same coordinator, over the same state root
/// and the same lifecycle lock, for the same package identity.
/// </remarks>
internal sealed class SessionRuntime
{
/// <summary>
/// Directory under the application base holding the guest helper, staged
/// per architecture exactly like the MXC runtime.
/// </summary>
public const string HelperDirectoryName = "session-host";
public const string HelperFileName = "openclaw-session-host.exe";
private SessionRuntime(
SessionCoordinator coordinator,
SessionExecutor executor,
IMxcSessionClient backend,
string helperPath,
string applicationId,
HostPaths paths,
SetupStateStore setupState,
GatewayStateStore gatewayState,
ISessionLock lifecycleLock,
Func<bool?> isInteractiveLogon)
{
Coordinator = coordinator;
Executor = executor;
Backend = backend;
HelperPath = helperPath;
ApplicationId = applicationId;
Paths = paths;
SetupState = setupState;
GatewayState = gatewayState;
LifecycleLock = lifecycleLock;
_isInteractiveLogon = isInteractiveLogon;
}
private readonly Func<bool?> _isInteractiveLogon;
public SessionCoordinator Coordinator { get; }
public SessionExecutor Executor { get; }
/// <summary>
/// The one backend instance this process uses, so the gateway and ordinary
/// invocations cannot end up talking to differently configured clients.
/// </summary>
public IMxcSessionClient Backend { get; }
public string HelperPath { get; }
public string ApplicationId { get; }
public HostPaths Paths { get; }
public SetupStateStore SetupState { get; }
public GatewayStateStore GatewayState { get; }
public ISessionLock LifecycleLock { get; }
public ISessionLockHandle AcquireLifecycleLock() =>
LifecycleLock.TryAcquire(SessionCoordinator.DefaultLockTimeout)
?? throw new SessionBusyException(SessionCoordinator.DefaultLockTimeout);
public async Task<SessionRecord> StartForExecutionAsync(CancellationToken cancellationToken)
{
using ISessionLockHandle handle = AcquireLifecycleLock();
RequireSetup();
try
{
return await Coordinator.StartRecordedAsync(cancellationToken).ConfigureAwait(false);
}
catch (MxcException exception) when (exception.Code == MxcErrorCode.RuntimeUnavailable)
{
if (IsActivationAccessDenied(exception) && _isInteractiveLogon() == false)
{
throw SessionSupportPolicy.NonInteractiveLogon(exception);
}
throw new SessionCapabilityUnavailableException(exception.Message, exception);
}
}
private const string AccessDeniedNativeCode = "0x80070005";
private static bool IsActivationAccessDenied(MxcException exception) =>
string.Equals(exception.NativeCode, AccessDeniedNativeCode, StringComparison.OrdinalIgnoreCase);
public string StageHelper(SessionRecord record)
{
ArgumentNullException.ThrowIfNull(record);
return SessionHelperStager.Stage(
HelperPath,
RequireWorkspace(record));
}
public string RequireStagedHelper(SessionRecord record)
{
ArgumentNullException.ThrowIfNull(record);
return SessionHelperStager.RequireStaged(
HelperPath,
RequireWorkspace(record));
}
public static SessionRuntime Create(Action<string> log) =>
Create(
HostPaths.Create(),
MxcRuntimeLocator.Locate,
AppContext.BaseDirectory,
log);
internal static SessionRuntime Create(
HostPaths paths,
Func<MxcRuntimeLocation> locateRuntime,
string baseDirectory,
Action<string> log,
IMxcSessionClient? backend = null,
ISessionLock? lifecycleLock = null,
Func<bool?>? isInteractiveLogon = null)
{
ArgumentNullException.ThrowIfNull(paths);
ArgumentNullException.ThrowIfNull(log);
if (paths.PackageFamilyName is null)
{
throw new SessionCapabilityUnavailableException(
"OpenClaw is not running from its installed package, so it " +
"has no identity to provision an isolated session with.");
}
string applicationId =
PackageIdentity.ToApplicationId(paths.PackageFamilyName);
IMxcSessionClient client = backend ?? new LazyMxcSessionClient(
() => new MxcSdkSessionClient(locateRuntime(), log: log));
var coordinator = new SessionCoordinator(
client,
new SessionStateStore(paths.SessionStatePath),
new NamedSessionLock(paths.SessionStatePath),
applicationId,
log);
return new SessionRuntime(
coordinator,
new SessionExecutor(
client,
log,
isCurrentRecord: record => IsCurrentSessionRecord(coordinator, record)),
client,
ResolveHelperPath(baseDirectory),
applicationId,
paths,
new SetupStateStore(paths.SetupStatePath),
new GatewayStateStore(paths.GatewayStatePath),
lifecycleLock ??
new NamedSessionLock(paths.SessionStatePath + "_Installation"),
isInteractiveLogon ?? WindowsLogon.IsInteractive);
}
public bool IsCurrentSessionRecord(SessionRecord record)
{
ArgumentNullException.ThrowIfNull(record);
return IsCurrentSessionRecord(Coordinator, record);
}
private static bool IsCurrentSessionRecord(
SessionCoordinator coordinator,
SessionRecord record)
{
SessionStatus status = coordinator.GetRecordedStatus();
return status.Record is not null &&
string.Equals(status.Record.SandboxId, record.SandboxId, StringComparison.Ordinal) &&
string.Equals(status.Record.Generation, record.Generation, StringComparison.Ordinal);
}
/// <summary>
/// Requires both the explicit setup marker and the owned session record.
/// </summary>
/// <remarks>
/// This is read-only. Starting the session remains a separate operation so
/// a race with teardown cannot turn a stale marker into a new provision.
/// </remarks>
public SessionRecord RequireSetup()
{
SetupStateResult setup = SetupState.Read(ApplicationId);
if (setup.Record is null)
{
throw new SessionException(
setup.Fault == SetupStateFault.Missing
? "OpenClaw has not been set up. Run `clawctl setup` first."
: setup.Detail!);
}
SessionStatus session = Coordinator.GetRecordedStatus();
if (session.Fault == SessionStateFault.Missing &&
SessionCoordinator.MayLocateProvision(setup))
{
throw new UnownedSetupEvidenceException(SetupState.FilePath);
}
if (setup.Record.Phase != SetupPhase.Ready)
{
throw new SessionException(
setup.Record.Phase == SetupPhase.TearingDown
? "OpenClaw teardown is incomplete. Run `clawctl teardown` again."
: "OpenClaw setup is incomplete. Run `clawctl setup` again.");
}
if (session.Record is null)
{
throw new SessionException(
session.Detail is null
? "OpenClaw setup is incomplete because its isolated session is " +
"not recorded. Run `clawctl setup` again."
: $"{session.Detail} Run `clawctl setup` again.");
}
if (setup.Record.SandboxId is { } sandboxId &&
!string.Equals(sandboxId, session.Record.SandboxId, StringComparison.Ordinal))
{
throw new SessionException(
"The setup marker names a different session. Run `clawctl setup` again.");
}
return session.Record;
}
/// <summary>
/// Returns the Node.js executable extracted by the agent for the currently
/// packaged runtime.
/// </summary>
public string RequireAgentNodePath(string packagedArchivePath)
{
ArgumentException.ThrowIfNullOrWhiteSpace(packagedArchivePath);
SetupStateResult setup = SetupState.Read(ApplicationId);
SetupRecord? record = setup.Record;
if (record?.AgentNodePath is not { Length: > 0 } executablePath ||
!string.Equals(
record.AgentNodeArchive,
Path.GetFileName(packagedArchivePath),
StringComparison.Ordinal))
{
throw new SessionException(
"The isolated session runtime does not match this package. " +
"Run `clawctl setup` again.");
}
return executablePath;
}
/// <summary>
/// Returns the agent-owned root holding the mirrored native dependency
/// packages, or <see langword="null"/> when setup staged none.
/// </summary>
/// <remarks>
/// Absence is not an error: an application without native dependencies
/// stages nothing, and the redirect is simply not applied.
/// </remarks>
public string? GetAgentNativeRoot() =>
SetupState.Read(ApplicationId).Record?.AgentNativeRoot;
/// <summary>Records a completed guest runtime installation.</summary>
public void CompleteSetup(
SessionRecord session,
SessionRuntimeInstallResult runtime,
bool startupEnabled)
{
ArgumentNullException.ThrowIfNull(session);
ArgumentNullException.ThrowIfNull(runtime);
SetupState.Write(new SetupRecord
{
ApplicationId = ApplicationId,
SandboxId = session.SandboxId,
Phase = SetupPhase.Ready,
StartupEnabled = startupEnabled,
CompletedUtc = DateTimeOffset.UtcNow,
AgentNodePath = runtime.ExecutablePath,
AgentNodeVersion = runtime.Version,
AgentNodeArchive = runtime.ArchiveName,
AgentNativeRoot = runtime.NativeRootPath
});
}
internal static string ResolveHelperPath(string baseDirectory) =>
Path.GetFullPath(
Path.Combine(
baseDirectory,
HelperDirectoryName,
MxcRuntimeLocator.CurrentArchitectureName(),
HelperFileName));
private static string RequireWorkspace(SessionRecord record) =>
string.IsNullOrWhiteSpace(record.WorkspacePath)
? throw new SessionException(
"The recorded session has no shared workspace, so the session " +
"helper cannot be staged.")
: record.WorkspacePath;
}