-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchannel-computers.ts
More file actions
2130 lines (1998 loc) · 126 KB
/
Copy pathchannel-computers.ts
File metadata and controls
2130 lines (1998 loc) · 126 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
import { createHash, randomBytes } from "node:crypto";
import { spawn, spawnSync, type ChildProcessWithoutNullStreams } from "node:child_process";
import { createReadStream, createWriteStream, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
import { cpus as hostCpus, freemem, platform, totalmem } from "node:os";
import { basename, dirname, join, relative, resolve, sep } from "node:path";
import { Readable } from "node:stream";
import { pipeline } from "node:stream/promises";
import { spawn as spawnPty, type IPty } from "node-pty";
import { WebSocket } from "ws";
import { DATA_DIR, now, q, q1, run, type Row } from "./db.ts";
import { channelFilesPath, channelFilesystemRoot, channelUsesRuntimeStorage, channelWorkspacePath, installationScopedRuntimeName, ociHostStateRoot } from "./channel-storage.ts";
export type ChannelComputerBackend = "apple" | "oci" | "native" | "mock";
export type ChannelComputer = {
channel_id: number;
backend: ChannelComputerBackend;
machine_id: string;
image: string;
desired_state: "auto" | "running" | "stopped" | "deleted";
observed_state: string;
cpus: number;
memory_bytes: number;
disk_bytes: number;
home_mount: "none";
provision_status: string;
maintenance_state: string;
host_revision: number;
synced_host_revision: number;
guest_revision: number;
pressure_json: string;
low_pressure_streak: number;
last_update: number;
last_update_attempt: number;
last_health: number;
last_used: number;
last_error: string;
created: number;
updated: number;
};
export type ComputerCommandResult = { status: string; exit_code: number | null; output: string };
export type MachineTerminal = {
id: string;
channelId: number;
ownerId: number;
machineId: string;
backend: ChannelComputerBackend;
pty: IPty;
clients: Set<WebSocket>;
scrollback: Buffer[];
bytes: number;
cols: number;
rows: number;
closed: boolean;
};
type MachineInspection = {
id?: string;
status?: string;
cpus?: number;
memory?: number;
diskSize?: number | null;
homeMount?: string;
image?: { reference?: string; descriptor?: { digest?: string } } | string;
};
const APPLE_RUNTIME_VERSION = "1.1.0";
export const APPLE_RUNTIME_PACKAGE = `container-${APPLE_RUNTIME_VERSION}-installer-signed.pkg`;
export const APPLE_RUNTIME_URL = `https://github.com/apple/container/releases/download/${APPLE_RUNTIME_VERSION}/${APPLE_RUNTIME_PACKAGE}`;
export const APPLE_RUNTIME_SHA256 = "0ca1c42a2269c2557efb1d82b1b38ac553e6a3a3da1b1179c439bcee1e7d6714";
export const DEFAULT_CHANNEL_IMAGE = process.env.HELM_CHANNEL_MACHINE_IMAGE || "local/1helm-channel-machine:0.0.41";
const CONTAINER_CANDIDATES = [process.env.HELM_CONTAINER_CLI, "/usr/local/bin/container", "/opt/homebrew/bin/container", "container"].filter(Boolean) as string[];
const OCI_RUNTIME_VERSION = "1helm-oci-runtime-v1";
const OCI_HELPER_CANDIDATES = [
process.env.HELM_OCI_HELPER,
"/usr/libexec/1helm-oci-runtime",
"/usr/local/libexec/1helm-oci-runtime",
join(process.env.HELM_APP_ROOT || process.cwd(), "scripts", "1helm-oci-runtime"),
].filter(Boolean) as string[];
const COMMAND_TIMEOUT_MS = Math.max(5_000, Number(process.env.HELM_MACHINE_COMMAND_TIMEOUT_MS || 120_000));
const IDLE_AFTER_MS = Math.max(60_000, Number(process.env.HELM_MACHINE_IDLE_MS || 15 * 60_000));
const RECONCILE_EVERY_MS = Math.max(15_000, Number(process.env.HELM_FLEET_INTERVAL_MS || 60_000));
const INITIAL_RECONCILE_MS = Math.max(25, Number(process.env.HELM_FLEET_INITIAL_MS || 2_000));
const UPDATE_EVERY_MS = Math.max(24 * 60 * 60_000, Number(process.env.HELM_MACHINE_UPDATE_MS || 7 * 24 * 60 * 60_000));
const UPDATE_RETRY_MS = Math.max(60 * 60_000, Number(process.env.HELM_MACHINE_UPDATE_RETRY_MS || 6 * 60 * 60_000));
const MAX_WORKSPACE_SYNC_BYTES = Math.max(64 * 1024 ** 2, Number(process.env.HELM_WORKSPACE_SYNC_MAX_BYTES || 2 * 1024 ** 3));
// Apple's machine runtime exposes a host-backed filesystem capacity in `df`
// and does not offer a disk-size creation flag. This is the honest writable
// allocation 1Helm manages and mirrors for a channel, not that virtual ceiling.
export const MANAGED_CHANNEL_DISK_BYTES = MAX_WORKSPACE_SYNC_BYTES;
const MAX_WORKSPACE_SYNC_ENTRIES = Math.max(10_000, Number(process.env.HELM_WORKSPACE_SYNC_MAX_ENTRIES || 200_000));
const SCROLLBACK_CAP = 256 * 1024;
const terminalSessions = new Map<string, MachineTerminal>();
const channelLocks = new Map<number, Promise<unknown>>();
// Provisioning is a long host operation (the first OCI image build installs
// its guest toolchain). The reconciler must not race that transaction.
const activeProvisioning = new Set<number>();
const syncTimers = new Map<number, NodeJS.Timeout>();
let reconcileTimer: NodeJS.Timeout | null = null;
let reconcileStartupTimer: NodeJS.Timeout | null = null;
let reconcileRunning = false;
let reconcileEnabled = false;
let reconcilePass: Promise<void> | null = null;
const installationId = (): string => {
let id = String(q1("SELECT installation_id FROM workspace WHERE id=1")?.installation_id || "");
if (!/^[a-f0-9]{16}$/.test(id)) {
id = randomBytes(8).toString("hex");
run("UPDATE workspace SET installation_id=? WHERE id=1", id);
}
return id;
};
export const configuredChannelBackend = (): ChannelComputerBackend => {
const hostDefault: ChannelComputerBackend = platform() === "darwin" ? "apple" : "oci";
const configured = String(process.env.HELM_CHANNEL_COMPUTER_BACKEND || hostDefault);
return ["apple", "oci", "native", "mock"].includes(configured) ? configured as ChannelComputerBackend : hostDefault;
};
const explicitComputerId = (channelId: number): string => `1helm-${installationId()}-channel-${channelId}`;
const hostWorldRoot = (channelId: number): string => join(DATA_DIR, "channels", String(channelId));
const hostWorkspace = channelWorkspacePath;
const hostFiles = channelFilesPath;
const workspaceMirrorRefreshes = new Map<number, Promise<void>>();
let appleNetworkRepair: Promise<void> | null = null;
let appleNetworkRepairAt = 0;
function withChannelLock<T>(channelId: number, fn: () => Promise<T>): Promise<T> {
const previous = channelLocks.get(channelId) || Promise.resolve();
const current = previous.catch(() => undefined).then(fn);
channelLocks.set(channelId, current);
const release = (): void => { if (channelLocks.get(channelId) === current) channelLocks.delete(channelId); };
void current.then(release, release);
return current;
}
export function channelComputer(channelId: number): ChannelComputer | undefined {
return q1("SELECT * FROM channel_computers WHERE channel_id=?", channelId) as ChannelComputer | undefined;
}
function channelComputerPressure(computer: ChannelComputer): Record<string, unknown> | undefined {
let value: Record<string, unknown>;
try {
const parsed = JSON.parse(String(computer.pressure_json || "{}"));
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return undefined;
value = parsed as Record<string, unknown>;
} catch { return undefined; }
const load1 = Number(value.load1);
const memoryAvailableKb = Number(value.memoryAvailableKb);
const diskUsedPercent = Number(value.diskUsedPercent);
if (!Number.isFinite(load1) || load1 < 0
|| !Number.isFinite(memoryAvailableKb) || memoryAvailableKb < 0
|| !Number.isFinite(diskUsedPercent) || diskUsedPercent < 0 || diskUsedPercent > 100) return undefined;
return {
load1,
memoryAvailableKb,
memoryAvailableBytes: memoryAvailableKb * 1024,
diskUsedPercent,
sampledAt: Number(computer.last_health || 0) || null,
status: computer.observed_state === "running" ? "live" : "last_known",
};
}
export function channelComputerView(channelId: number): Record<string, unknown> | null {
const computer = channelComputer(channelId);
if (!computer) return null;
const obligations = computerObligations(channelId);
const pressure = channelComputerPressure(computer);
return {
backend: computer.backend,
machine_id: computer.machine_id,
image: computer.image,
desired_state: computer.desired_state,
observed_state: computer.observed_state,
cpus: computer.cpus,
memory_bytes: computer.memory_bytes,
// `disk_bytes` in the persistence model predates the mirror boundary and
// is not a VM disk allocation. Never serialize it under a capacity-like
// name. Apple's runtime in particular exposes the host filesystem's
// ceiling inside the guest, which is not storage reserved for this VM.
mirror_quota_bytes: computer.disk_bytes,
mirror_quota_purpose: "Maximum channel workspace copied across the guest-to-host mirror safety boundary; not VM storage capacity.",
guest_disk_capacity_bytes: null,
guest_disk_capacity_status: "unknown",
pressure,
pressure_status: pressure ? pressure.status : "unknown",
home_mount: computer.home_mount,
provision_status: computer.provision_status,
maintenance_state: computer.maintenance_state,
last_update: computer.last_update,
last_health: computer.last_health,
last_used: computer.last_used,
last_error: computer.last_error,
obligations,
};
}
function automaticResources(channelCount = Math.max(1, Number(q1("SELECT COUNT(*) n FROM channel_computers WHERE desired_state<>'deleted'")?.n || 1))): { cpus: number; memoryBytes: number } {
const cores = Math.max(1, hostCpus().length);
const hostMemory = Math.max(2 * 1024 ** 3, totalmem());
const macReserve = Math.max(4 * 1024 ** 3, Math.floor(hostMemory * 0.35));
const usableMemory = Math.max(1024 ** 3, hostMemory - macReserve);
const perMachine = Math.floor(usableMemory / Math.min(channelCount, 4));
const memoryBytes = Math.max(1024 ** 3, Math.min(4 * 1024 ** 3, perMachine));
const vcpus = cores >= 8 ? 2 : 1;
return { cpus: vcpus, memoryBytes };
}
export function ensureChannelComputerRecord(channelId: number): ChannelComputer {
const channel = q1(`SELECT c.id,c.status FROM channels c
JOIN agent_channels ac ON ac.channel_id=c.id JOIN agents a ON a.id=ac.agent_id AND a.kind='channel' AND a.status<>'deleted'
WHERE c.id=? AND c.kind='channel' AND c.name<>'main' AND c.status<>'deleted'`, channelId);
if (!channel) throw new Error("Channel computer not found.");
const existing = channelComputer(channelId);
if (existing) return existing;
const resources = automaticResources();
const stamp = now();
run(`INSERT INTO channel_computers
(channel_id,backend,machine_id,image,desired_state,observed_state,cpus,memory_bytes,disk_bytes,home_mount,provision_status,last_used,created,updated)
VALUES (?,?,?,?,?,'unknown',?,?,?,'none','pending',?,?,?)`,
channelId, configuredChannelBackend(), explicitComputerId(channelId), DEFAULT_CHANNEL_IMAGE,
String(channel.status) === "archived" ? "stopped" : "auto", resources.cpus, resources.memoryBytes, MANAGED_CHANNEL_DISK_BYTES, stamp, stamp, stamp);
markWorkspaceDirty(channelId, "*", "full");
return channelComputer(channelId)!;
}
export function markWorkspaceDirty(channelId: number, relativePath = "*", operation: "upsert" | "delete" | "full" = "upsert"): void {
const computer = q1("SELECT backend FROM channel_computers WHERE channel_id=?", channelId);
if (!computer || String(computer.backend) === "oci") return;
const path = relativePath === "*" ? "*" : normalizeWorldRelative(relativePath);
const effective = path === "*" ? "full" : operation;
run(`INSERT INTO channel_workspace_changes (channel_id,relative_path,operation,created) VALUES (?,?,?,?)
ON CONFLICT(channel_id,relative_path) DO UPDATE SET operation=excluded.operation,created=excluded.created`, channelId, path, effective, now());
run("UPDATE channel_computers SET host_revision=host_revision+1,updated=? WHERE channel_id=?", now(), channelId);
}
function normalizeWorldRelative(input: string): string {
const value = String(input || "").replaceAll("\\", "/").replace(/^\/+/, "");
if (!value || value === "." || value.split("/").some((part) => part === "..")) throw new Error("Unsafe channel-world path.");
return value.startsWith("workspace/") || value.startsWith("files/") ? value : `workspace/${value}`;
}
function resolveHostWorldPath(channelId: number, worldRelative: string): string {
const rel = normalizeWorldRelative(worldRelative);
const root = resolve(hostWorldRoot(channelId));
const target = resolve(root, rel);
if (target !== root && !target.startsWith(root + sep)) throw new Error("Unsafe channel-world path.");
return target;
}
function resolveContainerCli(): string {
for (const candidate of CONTAINER_CANDIDATES) {
if (candidate.includes("/") ? existsSync(candidate) : spawnSync("/usr/bin/which", [candidate], { stdio: "ignore" }).status === 0) return candidate;
}
throw new Error("Apple container runtime is not installed. 1Helm can guide the one-time installation from Computer setup.");
}
function resolveOciHelper(): string {
if (platform() === "win32") return "/usr/libexec/1helm-oci-runtime";
if (process.env.HELM_INSTALL_KIND === "linux-systemd") {
const installed = "/usr/libexec/1helm-oci-runtime";
if (process.env.HELM_OCI_HELPER && process.env.HELM_OCI_HELPER !== installed) {
throw new Error("The installed Linux service has an unsafe OCI helper path.");
}
if (existsSync(installed)) return installed;
throw new Error("The installed Linux OCI runtime helper is missing; source-tree fallback is disabled for systemd installations.");
}
for (const candidate of OCI_HELPER_CANDIDATES) if (existsSync(candidate)) return candidate;
throw new Error("1Helm's root-owned OCI runtime helper is not installed.");
}
function resolveWslCli(): string {
if (windowsSystemAccount()) throw new Error("1Helm cannot use WSL while running as Windows Local System. Launch 1Helm in the signed-in Windows user's session so WSL and its retained distributions are available.");
const candidates = [process.env.HELM_WSL_CLI, process.env.SystemRoot ? join(process.env.SystemRoot, "System32", "wsl.exe") : "", "wsl.exe"].filter(Boolean) as string[];
for (const candidate of candidates) {
if (candidate.includes("/") || candidate.includes("\\")) { if (existsSync(candidate)) return candidate; }
else if (spawnSync(candidate, ["--status"], { stdio: "ignore", timeout: 10_000 }).status === 0) return candidate;
}
throw new Error("WSL 2 is not installed. Run Windows' verified 1Helm setup as Administrator once.");
}
/** WSL distributions are scoped to an interactive Windows user and Microsoft
* explicitly rejects Local System. This accepts injected values for CI. */
export function windowsSystemAccount(env: NodeJS.ProcessEnv = process.env, hostPlatform = platform()): boolean {
if (hostPlatform !== "win32") return false;
const username = String(env.USERNAME || env.USER || "").trim().toLowerCase();
const profile = String(env.USERPROFILE || "").replaceAll("/", "\\").toLowerCase();
return username === "system" || profile.endsWith("\\windows\\system32\\config\\systemprofile");
}
function appendLimited(chunks: Buffer[], chunk: Buffer, byteState: { value: number }, limit = 8 * 1024 * 1024): void {
if (byteState.value >= limit) return;
const accepted = chunk.subarray(0, Math.max(0, limit - byteState.value));
chunks.push(accepted);
byteState.value += accepted.length;
}
function spawnCollected(command: string, args: string[], opts: { cwd?: string; env?: NodeJS.ProcessEnv; input?: Buffer | Readable; signal?: AbortSignal; timeoutMs?: number } = {}): Promise<{ code: number; stdout: Buffer; stderr: Buffer }> {
return new Promise((resolvePromise, reject) => {
const child = spawn(command, args, { cwd: opts.cwd, env: opts.env || process.env, stdio: ["pipe", "pipe", "pipe"] }) as ChildProcessWithoutNullStreams;
const stdout: Buffer[] = [], stderr: Buffer[] = [];
const stdoutBytes = { value: 0 }, stderrBytes = { value: 0 };
child.stdout.on("data", (chunk: Buffer) => appendLimited(stdout, chunk, stdoutBytes));
child.stderr.on("data", (chunk: Buffer) => appendLimited(stderr, chunk, stderrBytes));
let timedOut = false;
let settled = false;
const timeout = setTimeout(() => { timedOut = true; child.kill("SIGTERM"); setTimeout(() => child.kill("SIGKILL"), 5_000).unref(); }, opts.timeoutMs || COMMAND_TIMEOUT_MS);
const abort = (): void => { child.kill("SIGTERM"); };
opts.signal?.addEventListener("abort", abort, { once: true });
child.once("error", (error) => { if (settled) return; settled = true; clearTimeout(timeout); opts.signal?.removeEventListener("abort", abort); reject(error); });
child.once("close", (code, signal) => {
if (settled) return;
settled = true;
clearTimeout(timeout);
opts.signal?.removeEventListener("abort", abort);
if (opts.signal?.aborted) { const error = new Error("Channel computer command was cancelled."); error.name = "AbortError"; reject(error); return; }
if (timedOut) { reject(new Error(`Channel computer command timed out after ${Math.round((opts.timeoutMs || COMMAND_TIMEOUT_MS) / 1000)} seconds.`)); return; }
resolvePromise({ code: code ?? (signal ? 128 : 1), stdout: Buffer.concat(stdout), stderr: Buffer.concat(stderr) });
});
if (Buffer.isBuffer(opts.input)) { child.stdin.end(opts.input); }
else if (opts.input) { opts.input.pipe(child.stdin); }
else child.stdin.end();
});
}
async function apple(args: string[], opts: Parameters<typeof spawnCollected>[2] = {}): Promise<{ code: number; stdout: Buffer; stderr: Buffer }> {
return spawnCollected(resolveContainerCli(), args, opts);
}
async function resolveContainerCliAsync(): Promise<string> {
for (const candidate of CONTAINER_CANDIDATES) {
if (candidate.includes("/")) {
if (existsSync(candidate)) return candidate;
continue;
}
try {
const result = await spawnCollected("/usr/bin/which", [candidate], { timeoutMs: 10_000 });
if (result.code === 0) return candidate;
} catch { /* try the next supported location */ }
}
throw new Error("Apple container runtime is not installed. 1Helm can guide the one-time installation from Computer setup.");
}
async function resolveWslCliAsync(): Promise<string> {
if (windowsSystemAccount()) throw new Error("1Helm cannot use WSL while running as Windows Local System. Launch 1Helm in the signed-in Windows user's session so WSL and its retained distributions are available.");
const candidates = [process.env.HELM_WSL_CLI, process.env.SystemRoot ? join(process.env.SystemRoot, "System32", "wsl.exe") : "", "wsl.exe"].filter(Boolean) as string[];
for (const candidate of candidates) {
if (candidate.includes("/") || candidate.includes("\\")) {
if (existsSync(candidate)) return candidate;
continue;
}
try {
const result = await spawnCollected(candidate, ["--status"], { timeoutMs: 10_000 });
if (result.code === 0) return candidate;
} catch { /* try the next supported location */ }
}
throw new Error("WSL 2 is not installed. Run Windows' verified 1Helm setup as Administrator once.");
}
/** Keep the in-WSL OCI helper synchronized with the packaged app so hotfixes and updates apply. */
let windowsOciHelperDigest = "";
let windowsOciHelperInstallPass: Promise<void> | null = null;
function ensureWindowsOciHelperInstalled(): void {
if (platform() !== "win32") return;
const appRoot = process.env.HELM_APP_ROOT || process.cwd();
const source = join(appRoot, "scripts", "1helm-oci-runtime");
if (!existsSync(source)) return;
const encoded = readFileSync(source);
const digest = createHash("sha256").update(encoded).digest("hex");
if (windowsOciHelperDigest === digest) return;
const runtime = installationScopedRuntimeName();
const wsl = resolveWslCli();
// Wake the distro first; cold start can exceed a short copy timeout.
spawnSync(wsl, ["--distribution", runtime, "--user", "root", "--exec", "/bin/true"], {
encoding: "buffer", timeout: 120_000, windowsHide: true,
});
// Copy via wsl so we never depend on a ready \\wsl.localhost mount race.
const result = spawnSync(wsl, [
"--distribution", runtime, "--user", "root", "--exec", "/bin/bash", "-lc",
"cat > /usr/libexec/1helm-oci-runtime && chmod 0755 /usr/libexec/1helm-oci-runtime",
], { input: encoded, encoding: "buffer", timeout: 60_000, windowsHide: true });
if (result.status !== 0) {
const detail = Buffer.concat([
Buffer.isBuffer(result.stderr) ? result.stderr : Buffer.alloc(0),
Buffer.isBuffer(result.stdout) ? result.stdout : Buffer.alloc(0),
]).toString("utf8").replaceAll("\0", " ").trim();
throw new Error(detail || "Could not install the shared OCI runtime helper into the Windows WSL runtime.");
}
windowsOciHelperDigest = digest;
}
/** Async twin used by readiness and preparation. The older synchronous helper
* remains only for synchronous Windows storage APIs, never for HTTP readiness. */
async function ensureWindowsOciHelperInstalledAsync(): Promise<void> {
if (platform() !== "win32") return;
const appRoot = process.env.HELM_APP_ROOT || process.cwd();
const source = join(appRoot, "scripts", "1helm-oci-runtime");
if (!existsSync(source)) return;
const encoded = readFileSync(source);
const digest = createHash("sha256").update(encoded).digest("hex");
if (windowsOciHelperDigest === digest) return;
if (windowsOciHelperInstallPass) return windowsOciHelperInstallPass;
const pass = (async () => {
const runtime = installationScopedRuntimeName();
const wsl = await resolveWslCliAsync();
try {
await spawnCollected(wsl, ["--distribution", runtime, "--user", "root", "--exec", "/bin/true"], { timeoutMs: 120_000 });
} catch { /* the copy below reports an actionable error */ }
const result = await spawnCollected(wsl, [
"--distribution", runtime, "--user", "root", "--exec", "/bin/bash", "-lc",
"cat > /usr/libexec/1helm-oci-runtime && chmod 0755 /usr/libexec/1helm-oci-runtime",
], { input: encoded, timeoutMs: 60_000 });
if (result.code !== 0) {
const detail = windowsLines(Buffer.concat([result.stderr, result.stdout])).join(" ").trim();
throw new Error(detail || "Could not install the shared OCI runtime helper into the Windows WSL runtime.");
}
windowsOciHelperDigest = digest;
})();
windowsOciHelperInstallPass = pass;
try { await pass; }
finally { if (windowsOciHelperInstallPass === pass) windowsOciHelperInstallPass = null; }
}
/**
* Create OCI channel workspace dirs inside the WSL runtime as root.
* Host-side mkdir on \\wsl.localhost\\... fails on Windows (permissions / 9p / distro-not-ready).
* The live failure was: UNKNOWN mkdir '...\\workspace\\notes' after a successful container provision.
*/
export function ensureOciChannelWorkspaceDirs(channelId: number): void {
const machineId = String(channelComputer(channelId)?.machine_id || "").trim()
|| `1helm-${String(q1("SELECT installation_id FROM workspace WHERE id=1")?.installation_id || "")}-channel-${channelId}`;
if (!/^1helm-[a-f0-9]{16}-channel-\d+$/.test(machineId)) {
throw new Error("Channel computer identity is not ready for workspace layout.");
}
if (platform() !== "win32") {
const root = channelFilesystemRoot(channelId);
mkdirSync(join(root, "workspace"), { recursive: true });
mkdirSync(join(root, "files"), { recursive: true });
for (const directory of ["notes", "whiteboards", "code", "docs", "presentations"]) {
mkdirSync(join(root, "workspace", directory), { recursive: true });
}
return;
}
ensureWindowsOciHelperInstalled();
const runtime = installationScopedRuntimeName();
const wsl = resolveWslCli();
// Workspace/files must be reachable from the Windows host Files/Cowork UI via
// \\wsl.localhost\... Mode 0700 agent-only makes Node existsSync/readdir look
// like "Folder not found." The distro has no Windows interop/automount, so
// opening these trees for the distro owner is the intended host-access path.
const script = [
"set -euo pipefail",
`root="/var/lib/1helm-oci-v1/runtime/oci/channels/${machineId}"`,
// 0711 root matches the helper's verify_storage contract. workspace/files
// stay agent-owned 0700; Windows Files/Cowork use storage-* helper ops,
// never the disabled-interop 9p share.
'install -d -o root -g root -m 0711 "$root"',
'chmod 0711 "$root" || true',
'chown root:root "$root" || true',
'install -d -o 1000 -g 1000 -m 0700 "$root/workspace" "$root/files" "$root/home"',
"for d in notes whiteboards code docs presentations; do",
' install -d -o 1000 -g 1000 -m 0700 "$root/workspace/$d"',
"done",
].join("\n");
const result = spawnSync(wsl, [
"--distribution", runtime, "--user", "root", "--exec", "/bin/bash", "-lc", script,
], { encoding: "buffer", timeout: 60_000, windowsHide: true });
if (result.status !== 0) {
const detail = Buffer.concat([
Buffer.isBuffer(result.stderr) ? result.stderr : Buffer.alloc(0),
Buffer.isBuffer(result.stdout) ? result.stdout : Buffer.alloc(0),
]).toString("utf8").replaceAll("\0", " ").trim();
throw new Error(detail || "Could not create the channel workspace directories inside the Windows WSL runtime.");
}
}
/**
* Windows OCI host access for Files/Cowork.
*
* Isolation keeps WSL interop disabled, which also kills the 9p file server
* behind \\wsl.localhost. Direct Node fs against that UNC path can never work.
* All host-side Files/Cowork IO therefore goes through the OCI helper's
* storage-* operations (wsl.exe --exec → 1helm-oci-runtime).
*/
export function windowsOciStorageRequired(channelId: number): boolean {
return platform() === "win32" && channelUsesRuntimeStorage(channelId);
}
/** @deprecated No longer probes UNC; kept as a no-op for call-site stability. */
export function ensureWindowsOciHostAccess(channelId: number): void {
if (!windowsOciStorageRequired(channelId)) return;
ensureOciChannelWorkspaceDirs(channelId);
}
type StorageArea = "workspace" | "files";
type StorageEntry = { name: string; kind: "file" | "directory"; size: number; modified: number };
function storageMachineAndOwner(channelId: number): { name: string; owner: string } {
const computer = ensureChannelComputerRecord(channelId);
return { name: computer.machine_id, owner: ownerMarker(computer) };
}
function ociStorageJson(args: string[], opts: { input?: Buffer; timeoutMs?: number } = {}): unknown {
const invocation = ociInvocation(args);
const result = spawnSync(invocation.command, invocation.args, {
encoding: "buffer",
timeout: opts.timeoutMs || 60_000,
env: invocation.env,
windowsHide: true,
input: opts.input,
});
const stdout = Buffer.isBuffer(result.stdout) ? result.stdout : Buffer.alloc(0);
const stderr = Buffer.isBuffer(result.stderr) ? result.stderr : Buffer.alloc(0);
if (result.status !== 0) {
const detail = windowsLines(Buffer.concat([stderr, stdout])).join(" ").replace(/^1Helm OCI runtime:\s*/i, "").trim();
throw new Error(detail || `storage operation failed (exit ${result.status ?? "timeout"})`);
}
const text = windowsLines(stdout).join("\n").trim() || Buffer.from(stdout).toString("utf8").replaceAll("\0", "").trim();
if (!text) return null;
try { return JSON.parse(text); }
catch { throw new Error("storage operation returned unreadable JSON"); }
}
function ociStorageBytes(args: string[], opts: { input?: Buffer; timeoutMs?: number } = {}): Buffer {
const invocation = ociInvocation(args);
const result = spawnSync(invocation.command, invocation.args, {
encoding: "buffer",
timeout: opts.timeoutMs || 60_000,
env: invocation.env,
windowsHide: true,
input: opts.input,
});
const stdout = Buffer.isBuffer(result.stdout) ? result.stdout : Buffer.alloc(0);
const stderr = Buffer.isBuffer(result.stderr) ? result.stderr : Buffer.alloc(0);
if (result.status !== 0) {
const detail = windowsLines(Buffer.concat([stderr, stdout])).join(" ").replace(/^1Helm OCI runtime:\s*/i, "").trim();
throw new Error(detail || `storage operation failed (exit ${result.status ?? "timeout"})`);
}
// Binary body: do not strip NULs via windowsLines.
return Buffer.from(stdout);
}
export function windowsOciStorageList(channelId: number, area: StorageArea, relative = ""): StorageEntry[] {
const { name, owner } = storageMachineAndOwner(channelId);
const payload = ociStorageJson(["storage-list", name, owner, area, ...(relative ? [relative] : [])]) as { entries?: StorageEntry[] };
return Array.isArray(payload?.entries) ? payload.entries : [];
}
export function windowsOciStorageStat(channelId: number, area: StorageArea, relative = ""): StorageEntry & { exists: boolean } {
const { name, owner } = storageMachineAndOwner(channelId);
return ociStorageJson(["storage-stat", name, owner, area, ...(relative ? [relative] : [])]) as StorageEntry & { exists: boolean };
}
export function windowsOciStorageMkdir(channelId: number, area: StorageArea, relative: string): StorageEntry {
const { name, owner } = storageMachineAndOwner(channelId);
return ociStorageJson(["storage-mkdir", name, owner, area, relative]) as StorageEntry;
}
export function windowsOciStorageWrite(channelId: number, area: StorageArea, relative: string, body: Buffer | string, mode: "create" | "overwrite" = "overwrite"): StorageEntry {
const { name, owner } = storageMachineAndOwner(channelId);
const input = Buffer.isBuffer(body) ? body : Buffer.from(body, "utf8");
return ociStorageJson(["storage-write", name, owner, area, relative, mode], { input }) as StorageEntry;
}
export function windowsOciStorageRead(channelId: number, area: StorageArea, relative: string): Buffer {
const { name, owner } = storageMachineAndOwner(channelId);
return ociStorageBytes(["storage-read", name, owner, area, relative]);
}
export function windowsOciStorageRm(channelId: number, area: StorageArea, relative: string, recursive = false): void {
const { name, owner } = storageMachineAndOwner(channelId);
ociStorageJson(["storage-rm", name, owner, area, relative, recursive ? "1" : "0"]);
}
export function windowsOciStorageRename(channelId: number, area: StorageArea, from: string, to: string): StorageEntry {
const { name, owner } = storageMachineAndOwner(channelId);
return ociStorageJson(["storage-rename", name, owner, area, from, to]) as StorageEntry;
}
export function windowsOciStorageCopy(channelId: number, area: StorageArea, from: string, to: string): StorageEntry {
const { name, owner } = storageMachineAndOwner(channelId);
return ociStorageJson(["storage-copy", name, owner, area, from, to]) as StorageEntry;
}
function linuxOciInvocation(args: string[]): { command: string; args: string[]; env?: NodeJS.ProcessEnv } {
const helper = resolveOciHelper();
if (process.env.HELM_OCI_HELPER_USE_SUDO === "0" || process.getuid?.() === 0) {
const appRoot = process.env.HELM_APP_ROOT || process.cwd();
return {
command: helper,
args,
env: {
...process.env,
...(helper === join(appRoot, "scripts", "1helm-oci-runtime") ? {
HELM_OCI_RUNTIME_MANIFEST: process.env.HELM_OCI_RUNTIME_MANIFEST || join(appRoot, "deploy", "1helm-oci-runtime-v1.conf"),
HELM_OCI_STATE_ROOT_OVERRIDE: process.env.HELM_OCI_STATE_ROOT_OVERRIDE || ociHostStateRoot(),
HELM_OCI_CONTAINERFILE_OVERRIDE: process.env.HELM_OCI_CONTAINERFILE_OVERRIDE || join(appRoot, "container", "Containerfile.oci"),
HELM_OCI_IMAGE_ARCHIVE_OVERRIDE: process.env.HELM_OCI_IMAGE_ARCHIVE_OVERRIDE || join(appRoot, "container", "channel-machine.oci.tar"),
HELM_OCI_IMAGE_SHA256_FILE_OVERRIDE: process.env.HELM_OCI_IMAGE_SHA256_FILE_OVERRIDE || join(appRoot, "container", "channel-machine.oci.sha256"),
// Development checkouts without a sealed archive may still live-build.
HELM_OCI_ALLOW_LIVE_BUILD: process.env.HELM_OCI_ALLOW_LIVE_BUILD || (existsSync(join(appRoot, "container", "channel-machine.oci.tar")) ? "0" : "1"),
} : {}),
},
};
}
return { command: "sudo", args: ["-n", helper, ...args] };
}
function ociInvocation(args: string[]): { command: string; args: string[]; env?: NodeJS.ProcessEnv } {
if (platform() === "win32") {
ensureWindowsOciHelperInstalled();
return { command: resolveWslCli(), args: ["--distribution", installationScopedRuntimeName(), "--user", "root", "--exec", "/usr/libexec/1helm-oci-runtime", ...args] };
}
return linuxOciInvocation(args);
}
async function ociAsyncInvocation(args: string[]): Promise<{ command: string; args: string[]; env?: NodeJS.ProcessEnv }> {
if (platform() === "win32") {
await ensureWindowsOciHelperInstalledAsync();
const wsl = await resolveWslCliAsync();
return { command: wsl, args: ["--distribution", installationScopedRuntimeName(), "--user", "root", "--exec", "/usr/libexec/1helm-oci-runtime", ...args] };
}
return linuxOciInvocation(args);
}
async function oci(args: string[], opts: Parameters<typeof spawnCollected>[2] = {}): Promise<{ code: number; stdout: Buffer; stderr: Buffer }> {
const invocation = ociInvocation(args);
return spawnCollected(invocation.command, invocation.args, { ...opts, env: invocation.env || opts.env });
}
/** OCI call path for readiness/preparation: even Windows helper sync and WSL
* discovery are asynchronous, so a background refresh can never stall Node. */
async function ociAsync(args: string[], opts: Parameters<typeof spawnCollected>[2] = {}): Promise<{ code: number; stdout: Buffer; stderr: Buffer }> {
const invocation = await ociAsyncInvocation(args);
return spawnCollected(invocation.command, invocation.args, { ...opts, env: invocation.env || opts.env });
}
const ownerMarker = (computer: ChannelComputer): string => `${installationId()}:${computer.channel_id}`;
function isolatedInvocation(args: string[], computer: ChannelComputer, user: "agent" | "root" = "agent", workdir = "/workspace", terminal = false, pipeInput = false): { command: string; args: string[]; env?: NodeJS.ProcessEnv } {
if (computer.backend === "apple") {
const words = ["machine", "run", ...(terminal ? ["-it"] : pipeInput ? ["-i"] : []), ...(user === "root" ? ["--root"] : []), "-n", computer.machine_id, "-w", workdir, "--"];
return { command: resolveContainerCli(), args: [...words, ...guestWords(...args)] };
}
if (computer.backend === "oci") {
const helperArgs = terminal
? ["terminal", computer.machine_id, ownerMarker(computer)]
: ["exec", computer.machine_id, ownerMarker(computer), user, workdir, "--", ...args];
const invocation = ociInvocation(helperArgs);
return invocation;
}
throw new Error(`Backend ${computer.backend} is not an isolated channel computer.`);
}
async function isolated(args: string[], computer: ChannelComputer, user: "agent" | "root" = "agent", workdir = "/workspace", opts: Parameters<typeof spawnCollected>[2] = {}): Promise<{ code: number; stdout: Buffer; stderr: Buffer }> {
const invocation = isolatedInvocation(args, computer, user, workdir, false, Boolean(opts.input));
return spawnCollected(invocation.command, invocation.args, { ...opts, env: invocation.env || opts.env });
}
const APPLE_GUEST_NETWORK_CHECK = "test \"$(cat /sys/class/net/eth0/operstate 2>/dev/null)\" = up && ip route show default | grep -q .";
async function appleGuestNetworkHealthy(computer: ChannelComputer): Promise<boolean> {
if (computer.backend !== "apple") return true;
const checked = await isolated(["/bin/sh", "-lc", APPLE_GUEST_NETWORK_CHECK], computer, "root", "/", { timeoutMs: 15_000 });
return checked.code === 0;
}
/** Apple container 1.1.0 can leave every machine reported as running while
* its shared vmnet service has detached their NICs. Restart only that service,
* then reboot the affected VM so its durable disk receives a fresh attachment. */
async function repairAppleGuestNetwork(computer: ChannelComputer): Promise<void> {
if (computer.backend !== "apple") return;
if (!appleNetworkRepair) {
appleNetworkRepair = (async () => {
// Avoid repeatedly bouncing shared vmnet while several machines detect
// the same fleet-wide outage during one reconciliation pass.
if (now() - appleNetworkRepairAt > 30_000) {
const activeCommands = Number(q1("SELECT COUNT(*) n FROM channel_computer_obligations WHERE kind='command' AND status='active'")?.n || 0);
const activeTurns = Number(q1("SELECT COUNT(*) n FROM agent_turns WHERE state='running'")?.n || 0);
if (terminalSessions.size > 0 || activeCommands > 1 || activeTurns > 1) {
throw new Error("resident computer network is unavailable; automatic repair is waiting for concurrent work to finish");
}
const stopped = await apple(["system", "stop"], { timeoutMs: 90_000 });
const started = await apple(["system", "start"], { timeoutMs: 90_000 });
if (stopped.code !== 0) throw new Error(stopped.stderr.toString("utf8").trim() || "Apple container services could not stop for network recovery");
if (started.code !== 0) throw new Error(started.stderr.toString("utf8").trim() || "Apple container services could not restart");
appleNetworkRepairAt = now();
}
})().finally(() => { appleNetworkRepair = null; });
}
await appleNetworkRepair;
const competingCommands = Number(q1(`SELECT COUNT(*) n FROM channel_computer_obligations
WHERE channel_id=? AND kind='command' AND status='active'`, computer.channel_id)?.n || 0);
const runningTurns = Number(q1("SELECT COUNT(*) n FROM agent_turns WHERE channel_id=? AND state='running'", computer.channel_id)?.n || 0);
if ([...terminalSessions.values()].some((session) => session.channelId === computer.channel_id)
|| competingCommands > 1 || runningTurns > 1) {
throw new Error("resident computer network is unavailable; automatic repair is waiting for concurrent work to finish");
}
const stopped = await apple(["machine", "stop", computer.machine_id], { timeoutMs: 90_000 });
if (stopped.code !== 0 && !/not running|stopped/i.test(Buffer.concat([stopped.stderr, stopped.stdout]).toString("utf8"))) {
throw new Error(stopped.stderr.toString("utf8").trim() || "network repair could not stop the channel computer");
}
const restarted = await apple(["machine", "run", "-n", computer.machine_id, "--", ...guestWords("/bin/sh", "-lc", APPLE_GUEST_NETWORK_CHECK)], { timeoutMs: 90_000 });
if (restarted.code !== 0 || !await appleGuestNetworkHealthy(computer)) throw new Error("channel computer network remained unavailable after automatic repair");
run("UPDATE channel_computers SET observed_state='running',provision_status='ready',last_health=?,last_error='',updated=? WHERE channel_id=?", now(), now(), computer.channel_id);
recordComputerActivity(computer.channel_id, "Recovered the resident computer's network without replacing its Linux disk.", "complete");
}
const isolatedBackend = (computer: ChannelComputer): boolean => ["apple", "oci"].includes(computer.backend);
const guestAgentIds = (computer: ChannelComputer): { uid: string; gid: string } => computer.backend === "apple"
? { uid: String(process.getuid?.() ?? 501), gid: String(process.getgid?.() ?? 20) }
: { uid: "1000", gid: "1000" };
const transientGuestTransport = (result: { code: number; stdout: Buffer; stderr: Buffer }): boolean => result.code !== 0
&& /operation not supported on socket|inappropriate ioctl for device/i.test(Buffer.concat([result.stderr, result.stdout]).toString("utf8"));
async function setupNewAppleMachine(machineId: string, owner: string): Promise<{ code: number; stdout: Buffer; stderr: Buffer }> {
const args = ["machine", "run", "--root", "-n", machineId, "--", ...guestWords("/bin/sh", "-lc",
"set -eu; test \"$(cat /var/lib/1helm/image-contract)\" = 1helm-channel-machine-v1; mkdir -p /workspace/files; test -x /sbin/init; printf '%s\\n' \"$1\" > /var/lib/1helm/owner", "1helm-setup", owner)];
let result = await apple(args, { timeoutMs: 60_000 });
// Apple 1.1.0 can report its newly booted machine as created/running before
// the first guest command socket accepts traffic. Retry only the two exact
// transport-readiness errors observed from the signed runtime; never retry a
// real guest setup failure or weaken the image/ownership checks.
for (let attempt = 1; attempt < 6 && transientGuestTransport(result); attempt++) {
await new Promise((resolveWait) => setTimeout(resolveWait, attempt * 400));
result = await apple(args, { timeoutMs: 60_000 });
}
return result;
}
// Apple container-machine commands are handed to /sbin.machine/init, whose
// `-s` path deliberately reconstructs them through the guest login shell as
// `<shell> -c "$*"`. Quote each intended argv word for that documented second
// parse; passing raw strings would turn spaces/semicolons into guest shell
// syntax before the requested executable receives them.
function guestWords(...words: string[]): string[] {
return words.map((word) => `'${String(word).replaceAll("'", `'"'"'`)}'`);
}
function parsedInspection(output: Buffer): MachineInspection | null {
try {
const parsed = JSON.parse(output.toString("utf8"));
return (Array.isArray(parsed) ? parsed[0] : parsed) as MachineInspection;
} catch { return null; }
}
async function inspectApple(machineId: string): Promise<MachineInspection | null> {
const result = await apple(["machine", "inspect", machineId], { timeoutMs: 30_000 });
if (result.code !== 0) {
const detail = Buffer.concat([result.stderr, result.stdout]).toString("utf8").trim();
if (/not found|does not exist|no such (?:machine|virtual machine)|could not find/i.test(detail)) return null;
throw new Error(detail || `could not inspect channel machine ${machineId}`);
}
const parsed = parsedInspection(result.stdout);
if (!parsed) throw new Error(`Apple container returned an unreadable inspection for ${machineId}`);
return parsed;
}
async function ensureAppleImage(image: string): Promise<void> {
const existing = await apple(["image", "inspect", image], { timeoutMs: 30_000 });
if (existing.code === 0) return;
if (!image.startsWith("local/1helm-channel-machine:")) return;
const appRoot = process.env.HELM_APP_ROOT || process.cwd();
const context = join(appRoot, "container");
const containerfile = join(context, "Containerfile");
if (!existsSync(containerfile)) throw new Error("The packaged 1Helm channel-machine image recipe is missing.");
const built = await apple(["build", "--platform", "linux/arm64", "--progress", "plain", "-t", image, "-f", containerfile, context], { timeoutMs: 30 * 60_000 });
if (built.code !== 0) throw new Error(built.stderr.toString("utf8").trim() || built.stdout.toString("utf8").trim() || "channel machine image build failed");
const verified = await apple(["image", "inspect", image], { timeoutMs: 30_000 });
if (verified.code !== 0) throw new Error("The channel machine image did not exist after its build completed.");
}
function recordObserved(computer: ChannelComputer, inspection: MachineInspection | null, error = ""): void {
if (!inspection) {
run("UPDATE channel_computers SET observed_state='missing',last_error=?,updated=? WHERE channel_id=?", error.slice(0, 1000), now(), computer.channel_id);
return;
}
run(`UPDATE channel_computers SET observed_state=?,cpus=?,memory_bytes=?,disk_bytes=?,home_mount='none',provision_status='ready',last_health=?,last_error='',updated=? WHERE channel_id=?`,
String(inspection.status || "unknown"), Number(inspection.cpus || computer.cpus), Number(inspection.memory || computer.memory_bytes),
MANAGED_CHANNEL_DISK_BYTES, now(), now(), computer.channel_id);
}
async function ensureAppleProvisioned(computer: ChannelComputer): Promise<void> {
let inspection: MachineInspection | null = null;
try { inspection = await inspectApple(computer.machine_id); } catch (error) {
run("UPDATE channel_computers SET provision_status='error',last_error=?,updated=? WHERE channel_id=?", (error as Error).message.slice(0, 1000), now(), computer.channel_id);
throw error;
}
if (inspection) {
if (inspection.homeMount !== "none") {
throw new Error(`Refusing to adopt ${computer.machine_id}: its home mount is ${inspection.homeMount || "unknown"}, not none.`);
}
const ownership = await apple(["machine", "run", "-n", computer.machine_id, "--", ...guestWords("/bin/cat", "/var/lib/1helm/owner")], { timeoutMs: 30_000 });
const expectedOwner = `${installationId()}:${computer.channel_id}`;
if (ownership.code !== 0 || ownership.stdout.toString("utf8").trim() !== expectedOwner) {
throw new Error(`Refusing to adopt ${computer.machine_id}: its 1Helm ownership marker does not match this installation and channel.`);
}
recordObserved(computer, inspection);
run("UPDATE channel_computers SET provision_status='ready',last_error='',updated=? WHERE channel_id=?", now(), computer.channel_id);
run(`UPDATE agents SET status='ready' WHERE id=(SELECT agent_id FROM agent_channels WHERE channel_id=?) AND status='waiting'
AND NOT EXISTS (SELECT 1 FROM threads WHERE channel_id=? AND status='waiting')`, computer.channel_id, computer.channel_id);
return;
}
run("UPDATE channel_computers SET provision_status='provisioning',last_error='',updated=? WHERE channel_id=?", now(), computer.channel_id);
// If a previously managed machine vanished, the narrow host mirror is the
// recovery source. Force a full replay into the replacement rather than
// creating an empty VM with an already-consumed change journal.
markWorkspaceDirty(computer.channel_id, "*", "full");
await ensureAppleImage(computer.image);
const memory = `${Math.max(1024, Math.round(computer.memory_bytes / 1024 ** 2))}M`;
const created = await apple(["machine", "create", computer.image, "--name", computer.machine_id, "--cpus", String(computer.cpus), "--memory", memory, "--home-mount", "none", "--progress", "none"], { timeoutMs: 15 * 60_000 });
if (created.code !== 0) {
const detail = created.stderr.toString("utf8").trim() || created.stdout.toString("utf8").trim() || "machine creation failed";
run("UPDATE channel_computers SET provision_status='error',last_error=?,updated=? WHERE channel_id=?", detail.slice(0, 1000), now(), computer.channel_id);
throw new Error(detail);
}
const setup = await setupNewAppleMachine(computer.machine_id, `${installationId()}:${computer.channel_id}`);
if (setup.code !== 0) throw new Error(setup.stderr.toString("utf8").trim() || "machine workspace setup failed");
inspection = await inspectApple(computer.machine_id);
if (!inspection || inspection.homeMount !== "none") throw new Error("Provisioned machine failed the no-home-mount verification.");
recordObserved(computer, inspection);
run("UPDATE channel_computers SET provision_status='ready',desired_state='auto',last_update=?,last_update_attempt=?,last_error='',updated=? WHERE channel_id=?", now(), now(), now(), computer.channel_id);
run(`UPDATE agents SET status='ready' WHERE id=(SELECT agent_id FROM agent_channels WHERE channel_id=?) AND status='waiting'
AND NOT EXISTS (SELECT 1 FROM threads WHERE channel_id=? AND status='waiting')`, computer.channel_id, computer.channel_id);
recordComputerActivity(computer.channel_id, "Provisioned a persistent isolated Linux computer with no Mac home mount.", "complete");
}
async function inspectOci(computer: ChannelComputer): Promise<MachineInspection | null> {
// Cold WSL start + helper sync routinely exceeds 30s on Windows; use a longer floor.
const inspectTimeout = platform() === "win32" ? 120_000 : 30_000;
const result = await oci(["inspect", computer.machine_id, ownerMarker(computer)], { timeoutMs: inspectTimeout });
if (result.code !== 0) {
const detail = Buffer.concat([result.stderr, result.stdout]).toString("utf8").trim();
if (/does not exist/i.test(detail)) return null;
throw new Error(detail || `could not inspect OCI channel computer ${computer.machine_id}`);
}
if (result.stdout.toString("utf8").trim() === "null") return null;
const parsed = parsedInspection(result.stdout);
if (!parsed) throw new Error(`OCI runtime returned an unreadable inspection for ${computer.machine_id}`);
return parsed;
}
function windowsLines(buffer: Buffer): string[] {
const raw = buffer.toString("utf8");
const decoded = raw.includes("\0") ? buffer.toString("utf16le") : raw;
return decoded.replaceAll("\0", "").split(/\r?\n/).map((line) => line.trim().replace(/^\*\s*/, "")).filter(Boolean);
}
async function inspectIsolated(computer: ChannelComputer): Promise<MachineInspection | null> {
if (computer.backend === "apple") return inspectApple(computer.machine_id);
if (computer.backend === "oci") return inspectOci(computer);
return null;
}
async function ensureOciProvisioned(computer: ChannelComputer): Promise<void> {
let inspection = await inspectOci(computer);
if (!inspection) {
activeProvisioning.add(computer.channel_id);
try {
run("UPDATE channel_computers SET provision_status='provisioning',last_error='',updated=? WHERE channel_id=?", now(), computer.channel_id);
let recovered = false;
if (!existsSync(channelFilesystemRoot(computer.channel_id))) {
const backups = await oci(["backups", computer.machine_id, ownerMarker(computer)], { timeoutMs: 5 * 60_000 });
if (backups.code !== 0) throw new Error(backups.stderr.toString("utf8").trim() || "OCI recovery inventory failed");
let available: Array<{ backup: string; sha256: string }> = [];
try { available = JSON.parse(backups.stdout.toString("utf8")); } catch { throw new Error("OCI recovery inventory was unreadable"); }
const latest = available[0];
if (latest) {
const restored = await oci(["restore", computer.machine_id, ownerMarker(computer), latest.backup, latest.sha256], { timeoutMs: 30 * 60_000 });
if (restored.code !== 0) throw new Error(restored.stderr.toString("utf8").trim() || "OCI channel recovery failed");
recovered = true;
recordComputerActivity(computer.channel_id, "Recovered the channel computer from its latest digest-verified OCI backup.", "complete");
}
}
if (!recovered) {
const image = await oci(["image", computer.image], { timeoutMs: 30 * 60_000 });
if (image.code !== 0) throw new Error(image.stderr.toString("utf8").trim() || image.stdout.toString("utf8").trim() || "OCI channel image build failed");
const created = await oci(["create", computer.machine_id, ownerMarker(computer), String(computer.cpus), String(Math.round(computer.memory_bytes / 1024 ** 2)), computer.image], { timeoutMs: 30 * 60_000 });
if (created.code !== 0) throw new Error(created.stderr.toString("utf8").trim() || created.stdout.toString("utf8").trim() || "OCI channel computer creation failed");
}
inspection = await inspectOci(computer);
if (!inspection || inspection.homeMount !== "none" || inspection.status !== "running") throw new Error("Provisioned OCI computer failed its ownership, storage, or runtime verification.");
recordComputerActivity(computer.channel_id, "Provisioned a durable OCI channel computer with runtime-owned storage.", "complete");
} finally { activeProvisioning.delete(computer.channel_id); }
} else if (inspection.status !== "running") {
const started = await oci(["start", computer.machine_id, ownerMarker(computer)], { timeoutMs: 90_000 });
if (started.code !== 0) throw new Error(started.stderr.toString("utf8").trim() || "OCI channel computer did not start");
inspection = await inspectOci(computer);
}
recordObserved(computer, inspection);
// Never mkdir through \\wsl.localhost on Windows — that is the post-provision failure mode.
ensureOciChannelWorkspaceDirs(computer.channel_id);
run("DELETE FROM channel_workspace_changes WHERE channel_id=?", computer.channel_id);
run("UPDATE channel_computers SET provision_status='ready',desired_state='auto',synced_host_revision=host_revision,last_update=?,last_update_attempt=?,last_error='',updated=? WHERE channel_id=?", now(), now(), now(), computer.channel_id);
}
async function ensureNativeProvisioned(computer: ChannelComputer): Promise<void> {
mkdirSync(hostWorkspace(computer.channel_id), { recursive: true });
mkdirSync(hostFiles(computer.channel_id), { recursive: true });
run("UPDATE channel_computers SET observed_state='running',provision_status='ready',last_health=?,last_error='',updated=? WHERE channel_id=?", now(), now(), computer.channel_id);
}
export async function provisionChannelComputer(channelId: number): Promise<ChannelComputer> {
return withChannelLock(channelId, async () => {
let computer = ensureChannelComputerRecord(channelId);
if (computer.backend === "apple") await ensureAppleProvisioned(computer);
else if (computer.backend === "oci") await ensureOciProvisioned(computer);
else await ensureNativeProvisioned(computer);
computer = channelComputer(channelId)!;
if (computer.backend === "apple") await syncHostChangesToGuest(computer);
return channelComputer(channelId)!;
});
}
export async function ensureChannelComputerRunning(channelId: number, reason = "channel activity"): Promise<ChannelComputer> {
return withChannelLock(channelId, async () => {
let computer = ensureChannelComputerRecord(channelId);
const channel = q1("SELECT status FROM channels WHERE id=?", channelId);
if (!channel || channel.status !== "active") throw new Error("Restore the channel before using its computer.");
if (computer.desired_state === "stopped" || computer.desired_state === "deleted") throw new Error("Restore the channel before using its computer.");
if (computer.backend === "apple") {
await ensureAppleProvisioned(computer);
computer = channelComputer(channelId)!;
// machine run is the supported boot path; this no-op also verifies the guest.
const boot = await apple(["machine", "run", "-n", computer.machine_id, "--", ...guestWords("/bin/sh", "-lc", "set -eu; mkdir -p /workspace/files; test ! -d /Users || test -z \"$(find /Users -mindepth 1 -maxdepth 1 -print -quit 2>/dev/null)\"")], { timeoutMs: 90_000 });
if (boot.code !== 0) throw new Error(boot.stderr.toString("utf8").trim() || "channel computer did not start");
await syncHostChangesToGuest(computer);
const inspection = await inspectApple(computer.machine_id);
recordObserved(computer, inspection);
if (!await appleGuestNetworkHealthy(computer)) await repairAppleGuestNetwork(computer);
} else if (computer.backend === "oci") {
await ensureOciProvisioned(computer);
computer = channelComputer(channelId)!;
// ensureOciProvisioned already inspects and recordObserved — a redundant
// inspect here doubled the subprocess cost for every OCI channel request.
} else await ensureNativeProvisioned(computer);
run("UPDATE channel_computers SET last_used=?,last_error='',updated=? WHERE channel_id=?", now(), now(), channelId);
recordComputerActivity(channelId, `Computer ready for ${reason}.`, "complete", true);
return channelComputer(channelId)!;
});
}
async function syncHostChangesToGuest(computer: ChannelComputer, attempt = 0): Promise<void> {
if (!isolatedBackend(computer) || computer.backend === "oci") return;
const targetRevision = Number(channelComputer(computer.channel_id)?.host_revision || computer.host_revision);
const changes = q("SELECT relative_path,operation FROM channel_workspace_changes WHERE channel_id=? ORDER BY created", computer.channel_id);
if (!changes.length) return;
const full = changes.some((change) => change.operation === "full" || change.relative_path === "*");
if (full) {
mkdirSync(hostWorkspace(computer.channel_id), { recursive: true });
mkdirSync(hostFiles(computer.channel_id), { recursive: true });
validateMirrorTree(hostWorkspace(computer.channel_id));
validateMirrorTree(hostFiles(computer.channel_id));
const tar = spawn("tar", ["-C", hostWorldRoot(computer.channel_id), "-cf", "-", "workspace", "files"], { stdio: ["ignore", "pipe", "ignore"] });
const tarClosed = new Promise<number>((resolvePromise) => tar.once("close", (code) => resolvePromise(code ?? 1)));
const ids = guestAgentIds(computer);
const applied = await isolated(["/bin/sh", "-lc", "set -eu; mkdir -p /workspace; find /workspace -mindepth 1 -maxdepth 1 -exec rm -rf -- {} +; rm -rf /files; tar -xf - -C / --no-same-owner; mkdir -p /workspace/files; if test -d /files; then cp -a /files/. /workspace/files/; rm -rf /files; fi; chown -R \"$1:$2\" /workspace", "1helm-sync", ids.uid, ids.gid], computer, "root", "/", { input: tar.stdout!, timeoutMs: 5 * 60_000 });
const tarCode = await tarClosed;
if (tarCode !== 0 || applied.code !== 0) throw new Error(applied.stderr.toString("utf8").trim() || "workspace import failed");
} else {
for (const change of changes) {
const rel = normalizeWorldRelative(String(change.relative_path));
const guest = rel.startsWith("files/") ? `/workspace/${rel}` : `/${rel}`;
const host = resolveHostWorldPath(computer.channel_id, rel);
if (String(change.operation) === "delete" || !existsSync(host)) {
const removed = await isolated(["/bin/rm", "-rf", "--", guest], computer, "root", "/");
if (removed.code !== 0) throw new Error(removed.stderr.toString("utf8").trim() || `failed to remove ${rel}`);
continue;
}
if (lstatSync(host).isSymbolicLink()) throw new Error(`refusing to import symlink ${rel} into a channel computer`);
if (lstatSync(host).isDirectory()) validateMirrorTree(host);
const parent = dirname(guest);
const tar = spawn("tar", ["-C", dirname(host), "-cf", "-", basename(host)], { stdio: ["ignore", "pipe", "ignore"] });
const tarClosed = new Promise<number>((resolvePromise) => tar.once("close", (code) => resolvePromise(code ?? 1)));
const ids = guestAgentIds(computer);
const applied = await isolated(["/bin/sh", "-lc", "set -eu; mkdir -p \"$1\"; rm -rf -- \"$1/$2\"; tar -xf - -C \"$1\" --no-same-owner; chown -R \"$3:$4\" \"$1/$2\"", "1helm-sync", parent, basename(guest), ids.uid, ids.gid], computer, "root", "/", { input: tar.stdout!, timeoutMs: 5 * 60_000 });
const tarCode = await tarClosed;
if (tarCode !== 0 || applied.code !== 0) throw new Error(applied.stderr.toString("utf8").trim() || `failed to import ${rel}`);
}
}
// A host upload can arrive while the tar/CLI processes are awaiting I/O.
// Only consume the change journal when the exact revision we copied is
// still current; otherwise leave it intact and safely replay it.
const currentRevision = Number(channelComputer(computer.channel_id)?.host_revision || 0);
if (currentRevision === targetRevision) {
run("DELETE FROM channel_workspace_changes WHERE channel_id=?", computer.channel_id);
run("UPDATE channel_computers SET synced_host_revision=?,updated=? WHERE channel_id=?", targetRevision, now(), computer.channel_id);
return;
}
if (attempt >= 2) throw new Error("channel files kept changing during guest import; a later fleet-care pass will retry");
await syncHostChangesToGuest(channelComputer(computer.channel_id) || computer, attempt + 1);
}
export async function syncGuestToHost(channelId: number): Promise<void> {
return withChannelLock(channelId, async () => {
const computer = channelComputer(channelId);
if (!computer) return;
await syncGuestToHostUnlocked(computer);
});