Repository navigation
Expand file tree
/
Copy pathStateArchiveApplication.cs
More file actions
476 lines (460 loc) · 23.3 KB
/
Copy pathStateArchiveApplication.cs
File metadata and controls
476 lines (460 loc) · 23.3 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
using System.Text.Json;
using OpenClaw.SessionProtocol;
namespace OpenClaw.SessionHost;
internal sealed record StateArchiveApplicationResult(
string ArchivePath,
IReadOnlyList<StateTransferAsset> Assets,
IReadOnlyList<string> Warnings,
string? SourceProfile = null);
internal interface IStateArchiveApplication
{
StateArchiveApplicationResult Capture(string profile, string output, bool dryRun);
StateArchiveApplicationResult Extract(string profile, string archive, string destination);
IReadOnlyList<string> RequiredSources(
string profile, string previousProfile, IReadOnlyList<string>? resolvedSources = null);
void RebaseConfiguration(string profile, string previousProfile, string currentProfile);
}
internal sealed class StateArchiveApplication : IStateArchiveApplication
{
private readonly SessionStateTransferRequest _request;
public StateArchiveApplication(SessionStateTransferRequest request)
{
_request = request;
}
public StateArchiveApplicationResult Capture(string profile, string output, bool dryRun)
{
List<string> arguments = ["backup", "create", "--json", "--output", output];
arguments.Add(dryRun ? "--dry-run" : "--verify");
using JsonDocument document = Run(profile, arguments);
JsonElement root = document.RootElement;
string archivePath = ReadString(root, "archivePath");
if (!dryRun &&
(!root.TryGetProperty("verified", out JsonElement verified) ||
verified.ValueKind != JsonValueKind.True))
{
throw new SessionLaunchException("Upstream did not verify the captured backup.");
}
return new StateArchiveApplicationResult(
archivePath,
ReadAssets(root),
ReadWarnings(root));
}
public StateArchiveApplicationResult Extract(
string profile,
string archive,
string destination)
{
using JsonDocument document = Run(
profile,
["backup", "restore", archive, "--target", destination, "--json"]);
JsonElement root = document.RootElement;
string archiveRoot = ReadString(root, "archiveRoot");
string manifestPath = Path.Combine(destination, archiveRoot, "manifest.json");
using FileStream manifest = TrustedPath.OpenRead(destination, manifestPath, protectContents: true);
using JsonDocument metadata = JsonDocument.Parse(manifest);
return new StateArchiveApplicationResult(
archive,
ReadAssets(metadata.RootElement),
ReadWarnings(root),
ReadSourceProfile(metadata.RootElement));
}
public IReadOnlyList<string> RequiredSources(
string profile, string previousProfile, IReadOnlyList<string>? resolvedSources = null)
{
using JsonDocument document = ConfigurationOperation(
profile, previousProfile, profile, "inspect", resolvedSources);
return [.. document.RootElement.GetProperty("requiredSources").EnumerateArray()
.Select(value => value.GetString() ??
throw new SessionLaunchException("A required configuration dependency has no path."))];
}
public void RebaseConfiguration(
string profile,
string previousProfile,
string currentProfile)
{
using JsonDocument result = ConfigurationOperation(profile, previousProfile, currentProfile, "write");
}
private JsonDocument ConfigurationOperation(
string profile,
string previousProfile,
string currentProfile,
string mode,
IReadOnlyList<string>? resolvedSources = null)
{
const string expression = """
import { resolve, relative, isAbsolute, join, dirname, sep } from "node:path";
import { readFile, writeFile } from "node:fs/promises";
import { existsSync } from "node:fs";
import { createRequire } from "node:module";
import { pathToFileURL } from "node:url";
class StateOperationError extends Error {}
try {
const [app, physicalHome, previousHome, currentHome, mode, resolvedJson] = process.argv.slice(1);
// null: the profile is complete (an archive), so every absent lazy directory is truly absent.
// A list: recovery discovery, where only paths the host already looked for may be absent.
const resolved = JSON.parse(resolvedJson);
const looked = resolved === null ? null : new Set(resolved.map((value) => value.toLowerCase()));
const expectedPath = join(physicalHome, ".openclaw", "openclaw.json");
const JSON5 = createRequire(join(app, "package.json"))("json5");
const sdk = (name) => pathToFileURL(resolve(app, "dist", "plugin-sdk", `${name}.js`)).href;
const required = new Set();
const documents = new Map();
const suffix = (home, value) => {
const result = relative(home, value);
if (isAbsolute(result) || result === ".." || result.startsWith(`..${sep}`))
throw new StateOperationError("external-dependency");
return result;
};
const sourcePath = (value, base = previousHome, optional = false) => {
if (typeof value !== "string" || !value.trim() || value.includes("${"))
throw new StateOperationError("unresolved-dependency");
let absolute = value === "~" ? previousHome :
value.startsWith("~/") || value.startsWith("~\\") ? join(previousHome, value.slice(2)) :
resolve(base, value);
if (isAbsolute(value)) {
const inPhysical = relative(physicalHome, absolute);
if (!isAbsolute(inPhysical) && inPhysical !== ".." && !inPhysical.startsWith(`..${sep}`))
absolute = join(previousHome, inPhysical);
}
suffix(previousHome, absolute);
// Upstream writes default workspace and agent directories into the configuration
// before it creates them, so an absent one is nothing to carry, not a missing dependency.
if (!optional || (looked !== null && !looked.has(absolute.toLowerCase())) ||
existsSync(physical(absolute))) required.add(absolute);
return absolute;
};
const physical = (absolute) => join(physicalHome, suffix(previousHome, absolute));
const rebase = (value, base = previousHome, optional = false) => {
const absolute = sourcePath(value, base, optional);
return isAbsolute(value) ? join(currentHome, suffix(previousHome, absolute)) : value;
};
const property = (object, key, base, optional = false) => {
if (object?.[key] !== undefined) {
const value = object[key];
if (typeof value !== "string" || (!isAbsolute(value) &&
value !== "~" && !value.startsWith("~/") && !value.startsWith("~\\")))
throw new StateOperationError("unresolved-dependency");
object[key] = rebase(value, base, optional);
}
};
const paths = (object, key) => {
if (object?.[key] !== undefined) {
if (!Array.isArray(object[key])) throw new StateOperationError("invalid-configuration");
object[key] = object[key].map((value) => {
const holder = { value };
property(holder, "value");
return holder.value;
});
}
};
const scalarPaths = new Set([
"agents.defaults.workspace", "agents.list.*.workspace", "agents.list.*.agentDir",
"agents.entries.*.workspace", "agents.entries.*.agentDir",
"plugins.installs.*.installPath", "plugins.installs.*.sourcePath",
]);
// Keyed maps whose entries are named by the user: the key is not part of the schema path.
const mapScopes = new Set(["plugins.installs", "agents.entries"]);
const lazyDirectories = new Set([
"agents.defaults.workspace", "agents.list.*.workspace", "agents.list.*.agentDir",
"agents.entries.*.workspace", "agents.entries.*.agentDir",
]);
const arrayPaths = new Set(["skills.load.extraDirs", "plugins.load.paths"]);
const visit = async (draft, base, scope = "") => {
if (!draft || typeof draft !== "object") return;
if ("$include" in draft) {
const includes = Array.isArray(draft.$include) ? draft.$include : [draft.$include];
for (const include of includes) await load(sourcePath(include, base), scope);
draft.$include = Array.isArray(draft.$include)
? includes.map((value) => rebase(value, base)) : rebase(draft.$include, base);
}
for (const [key, value] of Object.entries(draft)) {
if (key === "$include") continue;
const childScope = mapScopes.has(scope) ? `${scope}.*` :
scope ? `${scope}.${key}` : key;
if (scalarPaths.has(childScope)) property(draft, key, undefined, lazyDirectories.has(childScope));
if (arrayPaths.has(childScope)) paths(draft, key);
if (Array.isArray(value)) {
for (const child of value) if (child && typeof child === "object")
await visit(child, base, `${childScope}.*`);
} else if (value && typeof value === "object") await visit(value, base, childScope);
}
};
const load = async (absolute, scope = "") => {
if (documents.has(absolute)) {
if (documents.get(absolute).scope !== scope)
throw new StateOperationError("invalid-configuration");
return;
}
if (!existsSync(physical(absolute))) return;
if (documents.size >= 10000) throw new StateOperationError("invalid-configuration");
const draft = JSON5.parse(await readFile(physical(absolute), "utf8"));
documents.set(absolute, { draft, scope });
await visit(draft, dirname(absolute), scope);
};
const originalConfig = join(previousHome, ".openclaw", "openclaw.json");
await load(originalConfig);
const missing = () => [...required].some((path) => !existsSync(physical(path)));
const readSnapshot = async () => {
const { readConfigFileSnapshot } = await import(sdk("health"));
const snapshot = await readConfigFileSnapshot({
observe: false, recoverSuspicious: false, pluginValidation: "core-only",
});
if (!snapshot.valid || resolve(snapshot.path).toLowerCase() !== resolve(expectedPath).toLowerCase())
throw new StateOperationError("invalid-configuration");
return snapshot;
};
const writeDocuments = async () => {
for (const [path, { draft }] of documents)
await writeFile(physical(path), JSON.stringify(draft, null, 2) + "\n");
};
// The global registry stores a custom agent's database as an absolute path.
// A path inside the previous profile must follow the profile, or the upstream
// producer would stat (or capture) the abandoned original instead of this copy.
// State-relative rows already move with the state directory and are left alone.
const relocateAgentDatabases = async () => {
const registry = join(physicalHome, ".openclaw", "state", "openclaw.sqlite");
if (!existsSync(registry)) return;
const { DatabaseSync } = await import("node:sqlite");
const database = new DatabaseSync(registry);
try {
const table = database.prepare(
"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'agent_databases'").get();
if (!table) return;
database.exec("BEGIN IMMEDIATE");
try {
const move = database.prepare(
"UPDATE OR REPLACE agent_databases SET path = ? WHERE agent_id = ? AND path = ?");
for (const row of database.prepare("SELECT agent_id, path FROM agent_databases").all()) {
if (typeof row.path !== "string" || !isAbsolute(row.path)) continue;
let absolute = resolve(row.path);
const inPhysical = relative(physicalHome, absolute);
if (!isAbsolute(inPhysical) && inPhysical !== ".." && !inPhysical.startsWith(`..${sep}`))
absolute = join(previousHome, inPhysical);
const inPrevious = relative(previousHome, absolute);
if (isAbsolute(inPrevious) || inPrevious === ".." || inPrevious.startsWith(`..${sep}`)) continue;
const target = join(currentHome, inPrevious);
if (target !== row.path) move.run(target, row.agent_id, row.path);
}
database.exec("COMMIT");
} catch (error) {
database.exec("ROLLBACK");
throw error;
}
} catch (error) {
throw error instanceof StateOperationError ? error : new StateOperationError("invalid-registry");
} finally {
database.close();
}
};
if (mode === "inspect" && !missing()) {
await writeDocuments();
const snapshot = await readSnapshot();
await visit(structuredClone(snapshot.config), join(previousHome, ".openclaw"));
}
if (mode === "write") {
if (missing()) throw new StateOperationError("missing-dependency");
const mutate = async () => {
const { mutateConfigFile } = await import(sdk("config-mutation"));
await mutateConfigFile({
base: "source", writeOptions: { expectedConfigPath: expectedPath },
afterWrite: { mode: "none", reason: "The package owns state activation." },
async mutate(draft) { await visit(draft, join(previousHome, ".openclaw")); },
});
};
if (currentHome !== physicalHome && existsSync(expectedPath)) await mutate();
// Included files must be relocated before the upstream loader can resolve them.
// All writes are in task-owned staging, never the original account's profile.
await writeDocuments();
await relocateAgentDatabases();
if (currentHome === physicalHome) {
const snapshot = await readSnapshot();
if (snapshot.exists) await mutate();
}
}
process.stdout.write(JSON.stringify({ requiredSources: [...required] }));
} catch (error) {
process.stdout.write(JSON.stringify({
errorCode: error instanceof StateOperationError ? error.message : "invalid-configuration",
}));
process.exitCode = 64;
}
""";
return Run(
profile,
["--input-type=module", "--eval", expression,
_request.ApplicationDirectory!, profile, previousProfile, currentProfile,
mode, EncodeResolved(resolvedSources)],
nodeExpression: true);
}
// Hand-built so no reflection-based serializer is needed under NativeAOT.
private static string EncodeResolved(IReadOnlyList<string>? resolvedSources) =>
resolvedSources is null
? "null"
: "[" + string.Join(",", resolvedSources.Select(path => $"\"{System.Text.Encodings.Web.JavaScriptEncoder.Default.Encode(path)}\"")) + "]";
private JsonDocument Run(
string profile,
IReadOnlyList<string> arguments,
bool nodeExpression = false)
{
foreach (string name in new[] { "OPENCLAW_HOME", "OPENCLAW_STATE_DIR", "OPENCLAW_CONFIG_PATH", "OPENCLAW_PROFILE" })
{
string? effective = _request.Environment?.TryGetValue(name, out string? value) == true
? value : Environment.GetEnvironmentVariable(name);
if (!string.IsNullOrWhiteSpace(effective))
{
throw new SessionLaunchException(
$"The agent has a {name} override. Remove it before using packaged state transfer.");
}
}
List<string> nodeArguments = [];
if (_request.NativePreloadPath is { Length: > 0 } preload)
{
nodeArguments.AddRange(["--import", new Uri(preload).AbsoluteUri]);
}
if (!nodeExpression)
{
nodeArguments.Add(Path.Combine(_request.ApplicationDirectory!, "openclaw.mjs"));
}
nodeArguments.AddRange(arguments);
Dictionary<string, string> environment = new(StringComparer.OrdinalIgnoreCase);
foreach ((string name, string value) in _request.Environment ?? new Dictionary<string, string>())
{
environment.Add(name, value);
}
environment["OPENCLAW_HOME"] = profile;
environment["OPENCLAW_STATE_DIR"] = Path.Combine(profile, ".openclaw");
environment["OPENCLAW_CONFIG_PATH"] = Path.Combine(profile, ".openclaw", "openclaw.json");
string workspace = _request.WorkspaceDirectory ??
throw new SessionLaunchException("The state operation has no private scratch workspace.");
string scratch = Path.Combine(workspace, $"t-{Guid.NewGuid():N}");
using (TrustedPath.ValidatedDirectory root =
TrustedPath.TryOpenValidatedDirectory(workspace, expectedIdentity: null) ??
throw new SessionLaunchException("The private scratch workspace is unavailable."))
{
TrustedPath.EnsureDirectory(root, scratch);
}
environment["TEMP"] = scratch;
environment["TMP"] = scratch;
SessionProcessOutput output = SessionProcessLauncher.Capture(new SessionLaunchRequest
{
RequestId = _request.RequestId,
Executable = _request.NodePath,
Arguments = nodeArguments,
WorkingDirectory = profile,
Environment = environment,
NativeRootPath = _request.NativeRootPath,
NodeOptionsSuffix = _request.NodeOptionsSuffix
});
if (output.ExitCode != 0)
{
if (nodeExpression)
{
string reason = ReadConfigurationFailure(output.StandardOutput);
throw new SessionLaunchException(reason +
" No source or live state was changed. Use `--dry-run` to inspect scope, or `clawctl collect-logs`.");
}
throw new SessionLaunchException(
$"The bundled OpenClaw state operation failed (exit {output.ExitCode}). " +
"Confirm the package supports backup create/verify/restore and run `clawctl collect-logs`.");
}
try
{
return JsonDocument.Parse(output.StandardOutput);
}
catch (JsonException)
{
throw new SessionLaunchException(
"The bundled OpenClaw state operation did not return its supported JSON contract.");
}
}
private static string ReadConfigurationFailure(string output)
{
try
{
using JsonDocument document = JsonDocument.Parse(output);
if (document.RootElement.TryGetProperty("errorCode", out JsonElement code))
{
return code.GetString() switch
{
"external-dependency" => "Recovery requires a configuration, workspace, plugin, skill, or agent path outside the profile.",
"unresolved-dependency" => "A configured path is relative, environment-dependent, or otherwise unresolvable for automatic recovery.",
"missing-dependency" => "Recovery is missing a required profile-contained dependency.",
"invalid-registry" => "The agent database registry in the profile could not be relocated.",
_ => "The recovery configuration is invalid, unreadable, or unsupported by the bundled SDK."
};
}
}
catch (JsonException)
{
return "The bundled configuration SDK did not return its supported recovery contract.";
}
return "The bundled configuration SDK did not return its supported recovery contract.";
}
private static string ReadSourceProfile(JsonElement manifest)
{
if (!manifest.TryGetProperty("paths", out JsonElement paths) || paths.ValueKind != JsonValueKind.Object)
{
throw new SessionLaunchException("The archive does not identify its source state directory.");
}
string state = ReadString(paths, "stateDir");
if (!Path.IsPathFullyQualified(state) ||
!Path.GetFileName(state).Equals(".openclaw", StringComparison.OrdinalIgnoreCase))
{
throw new SessionLaunchException(
"Automatic activation requires a full archive of a profile-contained .openclaw directory.");
}
return Path.GetDirectoryName(state)!;
}
private static string ReadString(JsonElement root, string name)
{
if (!root.TryGetProperty(name, out JsonElement property) ||
property.ValueKind != JsonValueKind.String ||
property.GetString() is not { Length: > 0 } value)
{
throw new SessionLaunchException($"Upstream state metadata has no '{name}'.");
}
return value;
}
private static List<StateTransferAsset> ReadAssets(JsonElement root)
{
if (!root.TryGetProperty("assets", out JsonElement assets) ||
assets.ValueKind != JsonValueKind.Array)
{
throw new SessionLaunchException("Upstream state metadata has no asset inventory.");
}
List<StateTransferAsset> result = [];
foreach (JsonElement asset in assets.EnumerateArray())
{
if (asset.ValueKind != JsonValueKind.Object)
{
throw new SessionLaunchException("Upstream returned a malformed state asset inventory.");
}
result.Add(new StateTransferAsset(
ReadString(asset, "kind"),
ReadString(asset, "sourcePath"),
ReadString(asset, "archivePath")));
}
return result;
}
private static List<string> ReadWarnings(JsonElement root)
{
List<string> warnings = [];
if (root.TryGetProperty("warnings", out JsonElement values) &&
values.ValueKind == JsonValueKind.Array)
{
foreach (JsonElement value in values.EnumerateArray())
{
if (value.ValueKind == JsonValueKind.String && value.GetString() is { } warning)
{
warnings.Add(warning);
}
}
}
if (root.TryGetProperty("sqliteInventoryVerified", out JsonElement inventory) &&
inventory.ValueKind == JsonValueKind.False)
{
warnings.Add("This legacy archive cannot prove complete SQLite inventory coverage.");
}
return warnings;
}
}