@amalgm/shell 0.1.164-main.41474889901 → 0.1.164-main.41526666971

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/dist/cli.js +34 -41
  2. package/dist/cli.js.map +1 -1
  3. package/dist/drive/fuse.d.ts +13 -116
  4. package/dist/drive/fuse.js +36 -145
  5. package/dist/drive/fuse.js.map +1 -1
  6. package/dist/drive/kernel.d.ts +17 -0
  7. package/dist/drive/kernel.js +32 -0
  8. package/dist/drive/kernel.js.map +1 -0
  9. package/dist/drive/layout.d.ts +2 -0
  10. package/dist/drive/layout.js +8 -4
  11. package/dist/drive/layout.js.map +1 -1
  12. package/dist/drive/mount.d.ts +16 -6
  13. package/dist/drive/mount.js +50 -24
  14. package/dist/drive/mount.js.map +1 -1
  15. package/dist/drive/mountpoint.d.ts +14 -0
  16. package/dist/drive/mountpoint.js +51 -0
  17. package/dist/drive/mountpoint.js.map +1 -0
  18. package/dist/drive/nfs/apple-double.d.ts +6 -0
  19. package/dist/drive/nfs/apple-double.js +140 -0
  20. package/dist/drive/nfs/apple-double.js.map +1 -0
  21. package/dist/drive/nfs/attributes.d.ts +64 -0
  22. package/dist/drive/nfs/attributes.js +97 -0
  23. package/dist/drive/nfs/attributes.js.map +1 -0
  24. package/dist/drive/nfs/handles.d.ts +44 -0
  25. package/dist/drive/nfs/handles.js +209 -0
  26. package/dist/drive/nfs/handles.js.map +1 -0
  27. package/dist/drive/nfs/mount3.d.ts +16 -0
  28. package/dist/drive/nfs/mount3.js +38 -0
  29. package/dist/drive/nfs/mount3.js.map +1 -0
  30. package/dist/drive/nfs/nfs3.d.ts +27 -0
  31. package/dist/drive/nfs/nfs3.js +458 -0
  32. package/dist/drive/nfs/nfs3.js.map +1 -0
  33. package/dist/drive/nfs/rpc.d.ts +66 -0
  34. package/dist/drive/nfs/rpc.js +122 -0
  35. package/dist/drive/nfs/rpc.js.map +1 -0
  36. package/dist/drive/nfs/server.d.ts +30 -0
  37. package/dist/drive/nfs/server.js +109 -0
  38. package/dist/drive/nfs/server.js.map +1 -0
  39. package/dist/drive/nfs/xdr.d.ts +44 -0
  40. package/dist/drive/nfs/xdr.js +111 -0
  41. package/dist/drive/nfs/xdr.js.map +1 -0
  42. package/dist/drive/nfs.d.ts +60 -0
  43. package/dist/drive/nfs.js +181 -0
  44. package/dist/drive/nfs.js.map +1 -0
  45. package/dist/drive/operations.d.ts +125 -0
  46. package/dist/drive/operations.js +141 -0
  47. package/dist/drive/operations.js.map +1 -0
  48. package/dist/error-facts.d.ts +24 -0
  49. package/dist/error-facts.js +35 -0
  50. package/dist/error-facts.js.map +1 -0
  51. package/dist/files-program/client.d.ts +122 -0
  52. package/dist/files-program/client.js +430 -0
  53. package/dist/files-program/client.js.map +1 -0
  54. package/dist/files-program/journeys.d.ts +15 -0
  55. package/dist/files-program/journeys.js +79 -0
  56. package/dist/files-program/journeys.js.map +1 -0
  57. package/dist/files-program/program.d.ts +1 -0
  58. package/dist/files-program/program.js +255 -0
  59. package/dist/files-program/program.js.map +1 -0
  60. package/dist/files-program/protocol.d.ts +154 -0
  61. package/dist/files-program/protocol.js +7 -0
  62. package/dist/files-program/protocol.js.map +1 -0
  63. package/dist/machine-host.d.ts +35 -32
  64. package/dist/machine-host.js +124 -195
  65. package/dist/machine-host.js.map +1 -1
  66. package/dist/runtime-node-flags.d.ts +6 -6
  67. package/dist/runtime-node-flags.js +6 -6
  68. package/dist/sharing-host.d.ts +6 -11
  69. package/dist/sharing-host.js +6 -10
  70. package/dist/sharing-host.js.map +1 -1
  71. package/dist/sync-cli.js +1 -1
  72. package/dist/sync-cli.js.map +1 -1
  73. package/npm-shrinkwrap.json +2 -2
  74. package/package.json +4 -4
@@ -3,26 +3,28 @@ import type { ChannelsCommands } from "@amalgm/channels";
3
3
  import type { ChatRuntimePort } from "@amalgm/chat";
4
4
  import { laneLayout, type JoinMachineInput, type MachineSetupPorts, type ReadyMachine, type RuntimeBinding, type UserLayout } from "@amalgm/core/identity";
5
5
  import { type Activity, type ActivityState } from "@amalgm/core/supervision";
6
- import type { FilesAddResult } from "@amalgm/live/files";
7
6
  import type { Receipt } from "@amalgm/live/drive";
8
- import { type FilesStageObserver } from "./files-observability.js";
7
+ import type { FilesStageObserver } from "./files-observability.js";
8
+ import type { AddedWorkspace } from "./files-program/journeys.js";
9
9
  import type { EntityApplyStageEvidence } from "./apply-window-host.js";
10
10
  import { type DeviceKeyStore } from "./authorization/index.js";
11
11
  import { type AuthorizationKeyRecoveryResult } from "./authorization/recovery-host.js";
12
12
  import type { PlatformProductHostOptions } from "./platform-product-host.js";
13
13
  import { type RuntimeCommandPath, type RuntimeCommandConnection } from "./runtime-command-host.js";
14
- import type { UserGroundHost, DetectScanEvidence, UserGroundCloseOptions, UserGroundClosed, InstallStage } from "./user-ground-host.js";
15
- import type { OpenNativeWatch, WatchCoverageEvidence, WatchHealth } from "./watching/index.js";
16
- import type { ServedDrive } from "./drive/mount.js";
14
+ import type { DetectScanEvidence, UserGroundCloseOptions, UserGroundClosed, InstallStage } from "./user-ground-host.js";
15
+ import type { WatchCoverageEvidence, WatchHealth } from "./watching/index.js";
17
16
  export interface MachineHostOptions {
18
17
  readonly onWireError?: (error: unknown) => void;
19
18
  readonly homedir?: string;
20
19
  /** Required for an unambiguous resume when more than one user is present. */
21
20
  readonly userEmail?: string;
22
21
  /** The home is the drive: each person's ground stands on a home shelf at a
23
- * private place of the lane's, and `serveDrive` mounts the drive at their
24
- * conventional home. Off, the conventional home is the ground itself. */
22
+ * private place of the lane's, and the Files program mounts the drive at
23
+ * their conventional home once their ground converges. Off, the
24
+ * conventional home is the ground itself. */
25
25
  readonly drive?: boolean;
26
+ /** Each placement the drive made on a first touch. */
27
+ readonly onPlaced?: (receipt: Receipt) => void;
26
28
  readonly appUrl: string;
27
29
  readonly runtimeVersion: string;
28
30
  readonly runtimeLabel?: string;
@@ -42,7 +44,9 @@ export interface MachineHostOptions {
42
44
  readonly authorizationPlatform?: NodeJS.Platform;
43
45
  readonly runtimePort?: number;
44
46
  readonly chatRuntime?: ChatRuntimePort<any, any>;
45
- readonly openWatch?: OpenNativeWatch;
47
+ /** A module whose default export opens native Watch in the Files program;
48
+ * platform certification and failure examinations only. */
49
+ readonly openWatchModule?: string;
46
50
  readonly onWatchHealth?: (health: WatchHealth) => void;
47
51
  /** Examination hook for proving that a command scopes Detect work to its
48
52
  * requested root. It observes work and never changes scheduling. */
@@ -110,6 +114,9 @@ export declare class MachineHost {
110
114
  readonly wireComposed: boolean;
111
115
  private readonly ownership;
112
116
  private selectedUserEmail;
117
+ /** The Wire, the Files ground and the drive run here, in a program of
118
+ * their own (files-program/client.ts). */
119
+ private files;
113
120
  private groundHost;
114
121
  /** The drive serving the selected person's home, while it is mounted. */
115
122
  private servedDrive;
@@ -131,7 +138,6 @@ export declare class MachineHost {
131
138
  /** A Files Register or Add holds local ground the cloud has not yet
132
139
  * accepted until its journey ends. */
133
140
  private readonly filesJourneys;
134
- private readonly stages;
135
141
  constructor(options: MachineHostOptions);
136
142
  private approveSetup;
137
143
  join(input: HostJoinInput): Promise<ReadyMachine>;
@@ -146,37 +152,34 @@ export declare class MachineHost {
146
152
  /** One read-only answer for platform adapters deciding whether to adopt a
147
153
  * running Shell, resume a durable registration, or begin installation. */
148
154
  status(): Promise<MachineStatus>;
149
- /** Serve one root on demand at a mountpoint (drive/mount.ts): the drive
150
- * lists the root's map over its placed ground and places on first touch.
151
- * Placements in flight are Live's `placing` count. The placer is the ground
152
- * host's `enterNow`, asked for each unit of a touch's chain, parent before
153
- * child (a folder directly above the next unit of its root is placed with
154
- * that unit, not asked for itself), answering once the unit's rows are
155
- * verified. The drive mounts at
156
- * the selected person's conventional home, over their home shelf; it needs
157
- * the `drive` option, since only then does their ground stand apart from
158
- * that home. */
159
- serveDrive(input?: {
160
- readonly onPlaced?: (receipt: Receipt) => void;
161
- }): Promise<ServedDrive>;
155
+ /** The Files program, started when Files is first needed. */
156
+ private filesProgram;
157
+ /** Converges a ground. With the home as the drive, the drive then serves
158
+ * the ground at the person's conventional home, over their home shelf,
159
+ * until the whole runtime stops (drive/mount.ts). */
160
+ private convergeGround;
161
+ /** Where the drive serves the home while it is mounted. */
162
+ driveServed(): {
163
+ readonly home: string;
164
+ readonly mountpoint: string;
165
+ readonly shelf: string;
166
+ } | null;
162
167
  /** Whether a folder stands at a path, for in-process code: under the
163
168
  * mountpoint the drive answers (drive/README.md, one door), and before the
164
169
  * drive is up nothing there is a folder yet; anywhere else, the kernel. */
165
170
  private folderAt;
166
- filesCommandPorts(): ReturnType<UserGroundHost["filesCommandPorts"]>;
167
171
  /** Materialize through Live and prove the same runtime owns ongoing Watch. */
168
- addWorkspace(workspaceId: string, destinationParent: string): Promise<FilesAddResult & {
169
- readonly watch: WatchCoverageEvidence;
170
- }>;
172
+ addWorkspace(workspaceId: string, destinationParent: string): Promise<AddedWorkspace>;
171
173
  /** Route the complete user-visible register journey through Live's
172
174
  * declaration and this already-running Files owner. */
173
175
  registerWorkspace(requestedPath: string): Promise<Record<string, unknown>>;
174
- /** Run one Files journey, returning its own stage ledger with the result
175
- * when the caller asked to be traced. The CLI process owns no Files
176
- * effects and never sees this runtime's stdout, so returning the ledger
177
- * is the only way a typed command can report what its journey spent. */
176
+ /** Run one Files journey in the Files program, which returns its own
177
+ * stage ledger with the result when the caller asked to be traced. The CLI
178
+ * process owns no Files effects and never sees this runtime's stdout, so
179
+ * returning the ledger is the only way a typed command can report what its
180
+ * journey spent. */
178
181
  private journey;
179
- watchEvidence(): WatchCoverageEvidence;
182
+ watchEvidence(): Promise<WatchCoverageEvidence>;
180
183
  callFilesRuntime(path: RuntimeCommandPath, body: Record<string, unknown>): Promise<Record<string, unknown>>;
181
184
  /** The running runtime's loopback address and admission token, for product commands. */
182
185
  runtimeConnection(): Promise<RuntimeCommandConnection>;
@@ -193,7 +196,7 @@ export declare class MachineHost {
193
196
  private drainRuntime;
194
197
  private syncSettingFile;
195
198
  syncMode(): SyncMode;
196
- syncStatus(): SyncStatus;
199
+ syncStatus(): Promise<SyncStatus>;
197
200
  /** Live's Files counts, handed out again: the instance handed them last is
198
201
  * their one reporter. */
199
202
  private filesCounts;
@@ -6,14 +6,12 @@ import { homedir as osHomedir, hostname, platform, release } from "node:os";
6
6
  import { isAbsolute, join, relative, resolve, sep } from "node:path";
7
7
  import { admitRuntimeFormat } from './updates/store.js';
8
8
  import { serviceIdentity } from './service/registration.js';
9
- import { RuntimeWireHost } from './runtime-wire-host.js';
10
- import { readSyncMode, writeSyncMode, syncPausedError, syncBlocked } from './sync-setting.js';
9
+ import { readSyncMode, writeSyncMode, syncPausedError } from './sync-setting.js';
11
10
  import { buildRootManifest, requireCurrentLayout, approveMachineSetup, adoptMachineSetup, joinApprovedMachine, mergeRecordAuth, resumeMachine, resolveRuntimeBinding, runtimeBindingsMatch, runtimeBindingFromRecord, RUNTIME_IDENTITY_PATH, createRuntimeIdentity, laneLayout, laneRoot, resolveRuntimeEndpoint, userFolderName, userLayout, } from "@amalgm/core/identity";
12
11
  import { createActivity } from "@amalgm/core/supervision";
13
12
  import { StateRail } from "@amalgm/core/state";
14
13
  import { atomicJson, atomicJsonSet, ensurePrivateDir, readJson, } from "./filesystem.js";
15
- import { emitFilesStage, } from "./files-observability.js";
16
- import { FilesStageRecorder, serializeStages } from "./files-trace.js";
14
+ import { FilesProgram } from "./files-program/client.js";
17
15
  import { createShellAuthorization, loadInstallationDeviceKey, } from "./authorization/index.js";
18
16
  import { recoverMachineAuthorization, } from "./authorization/recovery-host.js";
19
17
  import { postRegistration } from "./authorization/registration-http.js";
@@ -23,7 +21,6 @@ import { InstallationOwnership } from "./installation/ownership.js";
23
21
  import { runtimeAppOrigin, runtimeProxyOrigin, runtimeWireUrl } from "./installation/environment.js";
24
22
  import { forwardMount } from "./forward.js";
25
23
  import { filesBrowserMount } from "./files-browser-host.js";
26
- import { createConstructPort } from "./construct-products.js";
27
24
  import { createGateway } from "./gateway.js";
28
25
  import { localMount } from "./local-host.js";
29
26
  import { stateMount } from "./state-host.js";
@@ -52,6 +49,9 @@ export class MachineHost {
52
49
  wireComposed;
53
50
  ownership;
54
51
  selectedUserEmail;
52
+ /** The Wire, the Files ground and the drive run here, in a program of
53
+ * their own (files-program/client.ts). */
54
+ files = null;
55
55
  groundHost = null;
56
56
  /** The drive serving the selected person's home, while it is mounted. */
57
57
  servedDrive = null;
@@ -73,7 +73,6 @@ export class MachineHost {
73
73
  /** A Files Register or Add holds local ground the cloud has not yet
74
74
  * accepted until its journey ends. */
75
75
  filesJourneys = counted(this.activity.hook("live", "commands"));
76
- stages;
77
76
  constructor(options) {
78
77
  keepSocketMarkingBestEffort();
79
78
  setupOrigin(options.appUrl);
@@ -90,7 +89,6 @@ export class MachineHost {
90
89
  }
91
90
  this.options = { ...options, ...this.binding };
92
91
  this.wireComposed = this.binding.runtimeLabel !== 'local' || Boolean(options.wireUrl);
93
- this.stages = new FilesStageRecorder(options.onFilesStage);
94
92
  this.homedir = resolve(options.homedir ?? osHomedir());
95
93
  this.lane = laneLayout(laneRoot(this.homedir, this.binding));
96
94
  this.homes = options.drive ? driveLayout(this.lane).homes : this.lane.users;
@@ -176,45 +174,31 @@ export class MachineHost {
176
174
  await this.stopGround(this.groundHost);
177
175
  this.groundHost = null;
178
176
  await this.runtimeWire?.close();
179
- this.runtimeWire = new RuntimeWireHost({
177
+ this.runtimeWire = null;
178
+ const files = this.filesProgram();
179
+ this.runtimeWire = await files.openWire({
180
180
  url: runtimeWireUrl(this.binding, this.options.appUrl, tunnelUrl, this.options.wireUrl),
181
181
  token: tunnelToken,
182
182
  runtimeVersion: this.options.runtimeVersion,
183
- }, (error) => this.options.onWireError?.(error));
183
+ });
184
184
  this.activeSyncMode = this.syncMode();
185
185
  if (!existsSync(this.syncSettingFile()))
186
186
  writeSyncMode(this.syncSettingFile(), this.activeSyncMode);
187
187
  this.syncIdentity = identity;
188
- this.createGround = async () => {
189
- const { UserGroundHost } = await import("./user-ground-host.js");
190
- const user = this.user(identity.userEmail);
191
- return new UserGroundHost({
192
- wire: this.runtimeWire.client,
193
- userRoot: user.root,
194
- dir: user.computer.live,
195
- // Login places the home's map when the drive serves it, the home
196
- // whole otherwise (Live user-ground.ts).
197
- drive: this.options.drive === true,
198
- // Outside every user's ground, as self-held worktrees' storage must be.
199
- gitStorage: join(this.lane.dir, "git"),
200
- tunnelUrl,
201
- tunnelToken,
202
- runtimeVersion: this.options.runtimeVersion,
203
- reserveWritableRoot: (path) => { this.ownership.reserve(path, identity.userEmail); },
204
- openWatch: this.options.openWatch,
205
- onWatchHealth: this.options.onWatchHealth,
206
- onDetectScan: this.options.onDetectScan,
207
- onApplyStage: this.options.onApplyStage,
208
- onBackgroundError: this.options.onBackgroundError,
209
- onInstallStage: this.options.onInstallStage,
210
- onFilesStage: this.stages.observe,
211
- filesTraceActive: () => this.stages.listening,
212
- // The products are selected when the runtime starts, after this
213
- // rail exists, so the owner of a construct type is asked per act.
214
- constructProduct: (type) => (type === "app" ? this.appsProduct : null),
215
- activity: this.filesCounts(),
216
- });
217
- };
188
+ const user = this.user(identity.userEmail);
189
+ this.createGround = () => files.createGround({
190
+ userEmail: identity.userEmail,
191
+ userRoot: user.root,
192
+ dir: user.computer.live,
193
+ // Login places the home's map when the drive serves it, the home
194
+ // whole otherwise (Live user-ground.ts).
195
+ drive: this.options.drive === true,
196
+ // Outside every user's ground, as self-held worktrees' storage must be.
197
+ gitStorage: join(this.lane.dir, "git"),
198
+ tunnelUrl,
199
+ tunnelToken,
200
+ runtimeVersion: this.options.runtimeVersion,
201
+ }, () => this.filesCounts());
218
202
  if (this.activeSyncMode === 'paused') {
219
203
  this.syncPhase = 'paused';
220
204
  return {
@@ -224,7 +208,7 @@ export class MachineHost {
224
208
  }
225
209
  this.syncPhase = 'starting';
226
210
  this.groundHost = await this.createGround();
227
- const evidence = await this.groundHost.port.converge(identity);
211
+ const evidence = await this.convergeGround(this.groundHost, identity);
228
212
  this.syncPhase = 'enabled';
229
213
  return evidence;
230
214
  },
@@ -404,41 +388,51 @@ export class MachineHost {
404
388
  userRoot: paths.root,
405
389
  };
406
390
  }
407
- /** Serve one root on demand at a mountpoint (drive/mount.ts): the drive
408
- * lists the root's map over its placed ground and places on first touch.
409
- * Placements in flight are Live's `placing` count. The placer is the ground
410
- * host's `enterNow`, asked for each unit of a touch's chain, parent before
411
- * child (a folder directly above the next unit of its root is placed with
412
- * that unit, not asked for itself), answering once the unit's rows are
413
- * verified. The drive mounts at
414
- * the selected person's conventional home, over their home shelf; it needs
415
- * the `drive` option, since only then does their ground stand apart from
416
- * that home. */
417
- async serveDrive(input = {}) {
418
- this.assertSyncEnabled();
419
- if (!this.options.drive)
420
- throw new Error("the drive needs a runtime started with the home as the drive (--drive)");
421
- const ground = this.groundHost;
422
- if (!ground)
423
- throw new Error("the drive requires a running authenticated runtime");
424
- const { serveDrive } = await import("./drive/mount.js");
425
- const layout = driveLayout(this.lane);
426
- const served = await serveDrive(ground, {
427
- mountpoint: layout.mountpoint(this.requireSelectedUser()),
428
- layout,
429
- placer: { place: (unit) => ground.enterNow(unit.uuid, { rootShelf: layout.rootShelf }) },
430
- activity: this.activity.hook("live", "placing"),
431
- ...(input.onPlaced ? { onPlaced: input.onPlaced } : {}),
432
- });
433
- this.servedDrive = served;
434
- return {
435
- ...served,
436
- unmount: async () => {
437
- if (this.servedDrive === served)
438
- this.servedDrive = null;
439
- await served.unmount();
391
+ /** The Files program, started when Files is first needed. */
392
+ filesProgram() {
393
+ return this.files ??= new FilesProgram({
394
+ // Real disk: nothing the program starts may wait on the drive it serves.
395
+ cwd: this.lane.root,
396
+ home: this.homedir,
397
+ binding: this.binding,
398
+ ...(this.options.openWatchModule ? { openWatchModule: this.options.openWatchModule } : {}),
399
+ observers: {
400
+ wireError: this.options.onWireError,
401
+ backgroundError: this.options.onBackgroundError,
402
+ watchHealth: this.options.onWatchHealth,
403
+ detectScan: this.options.onDetectScan,
404
+ applyStage: this.options.onApplyStage,
405
+ filesStage: this.options.onFilesStage,
406
+ placed: this.options.onPlaced,
440
407
  },
441
- };
408
+ ...(this.options.onInstallStage ? { installStage: this.options.onInstallStage } : {}),
409
+ // Apps runs here; the program asks it about each app it records or
410
+ // applies.
411
+ app: async (method, args) => {
412
+ const product = this.appsProduct;
413
+ const act = product?.[method];
414
+ if (typeof act !== "function")
415
+ throw new Error(`Apps is not running here to answer ${method}`);
416
+ return act.apply(product, args);
417
+ },
418
+ });
419
+ }
420
+ /** Converges a ground. With the home as the drive, the drive then serves
421
+ * the ground at the person's conventional home, over their home shelf,
422
+ * until the whole runtime stops (drive/mount.ts). */
423
+ async convergeGround(ground, identity) {
424
+ const evidence = await ground.converge(identity);
425
+ if (this.options.drive && this.groundHost === ground) {
426
+ // A drive that rested while its ground was closed (a pause) serves
427
+ // again over this one, through the same mount.
428
+ this.servedDrive = await this.filesProgram().serveDrive(ground, identity.userEmail, () => this.activity.hook("live", "placing"));
429
+ }
430
+ return evidence;
431
+ }
432
+ /** Where the drive serves the home while it is mounted. */
433
+ driveServed() {
434
+ const served = this.servedDrive;
435
+ return served && { home: served.home, mountpoint: served.mountpoint, shelf: served.shelf };
442
436
  }
443
437
  /** Whether a folder stands at a path, for in-process code: under the
444
438
  * mountpoint the drive answers (drive/README.md, one door), and before the
@@ -450,110 +444,29 @@ export class MachineHost {
450
444
  const served = this.servedDrive;
451
445
  return served !== null && served.folder(address === "" ? [] : address.split(sep));
452
446
  }
453
- filesCommandPorts() {
454
- this.assertSyncEnabled();
455
- if (!this.groundHost)
456
- throw new Error("Files commands require a resumed authenticated machine");
457
- return this.groundHost.filesCommandPorts();
458
- }
459
447
  /** Materialize through Live and prove the same runtime owns ongoing Watch. */
460
- async addWorkspace(workspaceId, destinationParent) {
461
- this.assertSyncEnabled();
462
- if (!this.groundHost)
463
- throw new Error("add requires a running authenticated runtime");
464
- const ground = this.groundHost;
465
- return ground.operation(async () => {
466
- const started = performance.now();
467
- emitFilesStage(this.stages.observe, {
468
- primitive: "download", stage: "files-add", status: "started", workspaceId,
469
- });
470
- try {
471
- const { addFilesWorkspace } = await import("@amalgm/live/files");
472
- const added = await addFilesWorkspace(workspaceId, destinationParent, ground.filesCommandPorts().add);
473
- const result = { ...added, watch: ground.addedWorkspaceEvidence(added.workspaceId) };
474
- emitFilesStage(this.stages.observe, {
475
- primitive: "download",
476
- stage: "files-add",
477
- status: "completed",
478
- workspaceId,
479
- durationMs: performance.now() - started,
480
- });
481
- return result;
482
- }
483
- catch (error) {
484
- emitFilesStage(this.stages.observe, {
485
- primitive: "download",
486
- stage: "files-add",
487
- status: "failed",
488
- workspaceId,
489
- durationMs: performance.now() - started,
490
- });
491
- throw error;
492
- }
493
- });
448
+ addWorkspace(workspaceId, destinationParent) {
449
+ return this.journey((ground) => ground.add(workspaceId, destinationParent, false));
494
450
  }
495
451
  /** Route the complete user-visible register journey through Live's
496
452
  * declaration and this already-running Files owner. */
497
- async registerWorkspace(requestedPath) {
498
- this.assertSyncEnabled();
499
- if (!this.groundHost)
500
- throw new Error("register requires a running authenticated runtime");
501
- const ground = this.groundHost;
502
- return ground.operation(async () => {
503
- const journeyStarted = performance.now();
504
- const declarationStarted = performance.now();
505
- emitFilesStage(this.stages.observe, {
506
- primitive: "register", stage: "files-register", status: "started", path: requestedPath,
507
- });
508
- emitFilesStage(this.stages.observe, {
509
- primitive: "register", stage: "durable-declaration", status: "started", path: requestedPath,
510
- });
511
- try {
512
- const declared = await (await import("@amalgm/live/files")).registerFilesWorkspace(requestedPath, ground.filesCommandPorts().register);
513
- emitFilesStage(this.stages.observe, {
514
- primitive: "register",
515
- stage: "durable-declaration",
516
- status: "completed",
517
- path: requestedPath,
518
- workspaceId: declared.workspaceId,
519
- durationMs: performance.now() - declarationStarted,
520
- });
521
- const completed = await ground.completeWorkspaceRegistration(declared.workspaceId);
522
- emitFilesStage(this.stages.observe, {
523
- primitive: "register",
524
- stage: "files-register",
525
- status: "completed",
526
- path: requestedPath,
527
- workspaceId: declared.workspaceId,
528
- durationMs: performance.now() - journeyStarted,
529
- });
530
- return { ...declared, ...completed };
531
- }
532
- catch (error) {
533
- emitFilesStage(this.stages.observe, {
534
- primitive: "register",
535
- stage: "files-register",
536
- status: "failed",
537
- path: requestedPath,
538
- durationMs: performance.now() - journeyStarted,
539
- });
540
- throw error;
541
- }
542
- });
453
+ registerWorkspace(requestedPath) {
454
+ return this.journey((ground) => ground.register(requestedPath, false));
543
455
  }
544
- /** Run one Files journey, returning its own stage ledger with the result
545
- * when the caller asked to be traced. The CLI process owns no Files
546
- * effects and never sees this runtime's stdout, so returning the ledger
547
- * is the only way a typed command can report what its journey spent. */
548
- async journey(body, run) {
456
+ /** Run one Files journey in the Files program, which returns its own
457
+ * stage ledger with the result when the caller asked to be traced. The CLI
458
+ * process owns no Files effects and never sees this runtime's stdout, so
459
+ * returning the ledger is the only way a typed command can report what its
460
+ * journey spent. */
461
+ journey(run) {
549
462
  return this.filesJourneys(async () => {
550
- if (body?.trace !== true)
551
- return run();
552
- const captured = await this.stages.capture(run);
553
- return { ...captured.result, stages: serializeStages(captured.stages) };
463
+ this.assertSyncEnabled();
464
+ if (!this.groundHost)
465
+ throw new Error("Files commands require a running authenticated runtime");
466
+ return run(this.groundHost);
554
467
  });
555
468
  }
556
- watchEvidence() {
469
+ async watchEvidence() {
557
470
  this.assertSyncEnabled();
558
471
  if (!this.groundHost)
559
472
  throw new Error("Watch evidence requires a running authenticated runtime");
@@ -615,20 +528,41 @@ export class MachineHost {
615
528
  this.groundHost = null;
616
529
  for (const runtime of runtimes)
617
530
  await runtime.stop().catch(() => undefined);
618
- await this.runtimeWire?.close();
531
+ const drive = this.servedDrive;
532
+ const wire = this.runtimeWire;
533
+ const files = this.files;
534
+ this.servedDrive = null;
619
535
  this.runtimeWire = null;
536
+ this.files = null;
620
537
  this.createGround = null;
621
538
  this.syncIdentity = null;
622
539
  this.syncPhase = 'stopped';
540
+ // The drive unmounts only here, as the whole runtime stops, once
541
+ // nothing that may look under it still runs.
542
+ try {
543
+ await drive?.unmount();
544
+ await wire?.close();
545
+ }
546
+ finally {
547
+ await files?.close();
548
+ }
623
549
  }
624
550
  }
625
551
  syncSettingFile() { return this.user().computer.sync; }
626
552
  syncMode() { return readSyncMode(this.syncSettingFile()); }
627
- syncStatus() {
553
+ async syncStatus() {
554
+ // Sync stays on through a stopped Files program, but Watch and Record do
555
+ // not stand until it does: saying so never waits on its restart.
556
+ const down = this.syncPhase === 'enabled' ? this.files?.down() : null;
557
+ if (down) {
558
+ return { configured: this.syncMode(), state: down.parked ? 'failed' : 'starting', error: down.reason };
559
+ }
560
+ // A Files program that stopped for good holds back nothing it can name.
561
+ const blocked = await this.groundHost?.blocked().catch(() => undefined);
628
562
  return { configured: this.syncMode(),
629
563
  state: this.wireComposed ? this.syncPhase : 'unavailable',
630
564
  ...(this.syncError ? { error: this.syncError } : {}),
631
- ...(this.groundHost ? { blocked: syncBlocked(this.groundHost.applyWaiting()) } : {}) };
565
+ ...(blocked ? { blocked } : {}) };
632
566
  }
633
567
  /** Live's Files counts, handed out again: the instance handed them last is
634
568
  * their one reporter. */
@@ -679,7 +613,7 @@ export class MachineHost {
679
613
  return this.syncStatus();
680
614
  }
681
615
  this.groundHost = ground;
682
- this.syncStart = ground.port.converge(this.syncIdentity).then(() => {
616
+ this.syncStart = this.convergeGround(ground, this.syncIdentity).then(() => {
683
617
  if (this.activeSyncMode === 'enabled')
684
618
  this.syncPhase = 'enabled';
685
619
  }, async (error) => {
@@ -958,10 +892,9 @@ export class MachineHost {
958
892
  parked: user.computer.parked,
959
893
  recordConstruct: (change) => {
960
894
  this.assertSyncEnabled();
961
- const ground = this.groundHost;
962
- if (!ground)
895
+ if (!this.groundHost)
963
896
  throw new Error("Recording an app requires a converged runtime");
964
- return ground.operation(() => ground.recordConstruct({ entityType: "app", ...change }));
897
+ return this.groundHost.recordConstruct({ entityType: "app", ...change });
965
898
  },
966
899
  // A crash loop that gives up, or a callback that fails, is never silent.
967
900
  onError: (error) => this.options.onBackgroundError?.(error),
@@ -972,6 +905,7 @@ export class MachineHost {
972
905
  let appsBooted = null;
973
906
  const appsMcp = appsService ? appsSdk.createMcpServer({ apps: appsService }) : null;
974
907
  this.appsProduct = appsService ? appsSdk.appConstructSurface(appsService) : null;
908
+ await this.files?.products(this.appsProduct !== null);
975
909
  const platformTools = services.has("tools")
976
910
  ? await (await import("./platform-tools.js")).platformToolDefinitions({
977
911
  ...(agentsMcp ? { agents: agentsMcp } : {}),
@@ -1025,25 +959,15 @@ export class MachineHost {
1025
959
  // The Sharing doors. Constructs are entity types on the rails, so the
1026
960
  // surface is mounted for every installation: which products answer for a
1027
961
  // construct kind is an installation fact, reported in that kind's own
1028
- // lane. The ports are read per call because the rail stops and starts
1029
- // under a long-lived mount.
962
+ // lane. Each command runs on the ground converged when it is asked,
963
+ // because the rail stops and starts under a long-lived mount.
1030
964
  const sharing = (await import("./sharing-host.js")).createSharingSurface({
1031
- ports: () => {
965
+ execute: async (name, request) => {
1032
966
  this.assertSyncEnabled();
1033
967
  if (!this.groundHost)
1034
968
  throw new Error("Sharing requires a running authenticated runtime");
1035
- return this.groundHost.sharingPorts({
1036
- constructs: createConstructPort({
1037
- // Apps records its constructs through the intentional door, so
1038
- // it answers for `app`. A kind no product owns here resolves to
1039
- // "not selected in this installation"; no other kind is hurt.
1040
- products: this.appsProduct ? { app: this.appsProduct } : {},
1041
- kindOf: async (uuid) => this.groundHost?.constructKind(uuid) ?? null,
1042
- }),
1043
- link: (id) => `${this.options.appUrl.replace(/\/+$/, "")}/c/${id}`,
1044
- });
969
+ return this.groundHost.share(name, request, { userId, email: userEmail }, this.options.appUrl.replace(/\/+$/, ""));
1045
970
  },
1046
- actor: () => ({ userId, email: userEmail }),
1047
971
  });
1048
972
  let gateway = null;
1049
973
  const gatewayPort = () => {
@@ -1111,6 +1035,7 @@ export class MachineHost {
1111
1035
  const chatMcp = chat ? (await import("@amalgm/chat/mcp")).createChatMcpServer(chat.chat, { agentRunner: chat.agentRunner }) : null;
1112
1036
  const closeSelectedProducts = async () => {
1113
1037
  this.appsProduct = null;
1038
+ await this.files?.products(false).catch((error) => this.options.onBackgroundError?.(error));
1114
1039
  await appsBooted;
1115
1040
  await appsService?.close();
1116
1041
  await browserHost?.close();
@@ -1130,11 +1055,11 @@ export class MachineHost {
1130
1055
  } },
1131
1056
  {
1132
1057
  prefix: "/entities/register",
1133
- handle: (body) => this.journey(body, () => this.registerWorkspace(bodyText(body, "path"))),
1058
+ handle: (body) => this.journey((ground) => ground.register(bodyText(body, "path"), traced(body))),
1134
1059
  },
1135
1060
  {
1136
1061
  prefix: "/entities/add",
1137
- handle: (body) => this.journey(body, () => this.addWorkspace(bodyText(body, "uuid"), bodyText(body, "path"))),
1062
+ handle: (body) => this.journey((ground) => ground.add(bodyText(body, "uuid"), bodyText(body, "path"), traced(body))),
1138
1063
  },
1139
1064
  {
1140
1065
  prefix: "/sharing/cli",
@@ -1261,7 +1186,7 @@ export class MachineHost {
1261
1186
  this.running.delete(running);
1262
1187
  if (commandPublication)
1263
1188
  unpublishRuntimeCommands(commandPublication);
1264
- this.runtimeWire?.client.configureRuntime({});
1189
+ await this.runtimeWire?.configure().catch(() => undefined);
1265
1190
  const terminalsClosed = Promise.allSettled([pty.close()]);
1266
1191
  try {
1267
1192
  const closed = new Promise((resolve) => gateway.close(() => resolve()));
@@ -1290,7 +1215,7 @@ export class MachineHost {
1290
1215
  catch (error) {
1291
1216
  if (commandPublication)
1292
1217
  unpublishRuntimeCommands(commandPublication);
1293
- this.runtimeWire?.client.configureRuntime({});
1218
+ await this.runtimeWire?.configure().catch(() => undefined);
1294
1219
  const terminalsClosed = Promise.allSettled([pty.close()]);
1295
1220
  for (const close of [
1296
1221
  () => browserHost?.close(),
@@ -1327,6 +1252,10 @@ function normalizeEmail(value) {
1327
1252
  function text(value) {
1328
1253
  return typeof value === "string" ? value.trim() : "";
1329
1254
  }
1255
+ /** Whether a Files command asked for its stage ledger. */
1256
+ function traced(body) {
1257
+ return body?.trace === true;
1258
+ }
1330
1259
  function bodyText(body, key) {
1331
1260
  if (!body || typeof body !== "object" || Array.isArray(body)) {
1332
1261
  throw new Error("Files runtime requires a JSON object");