@waffle-os/runtime 0.0.145 → 0.0.146

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 (133) hide show
  1. package/README.md +32 -0
  2. package/browser/command-input.ts +86 -0
  3. package/browser/command-owner.ts +5 -0
  4. package/browser/display/guest.ts +2 -18
  5. package/browser/display/surface-info.ts +19 -0
  6. package/browser/operations/cells.ts +90 -0
  7. package/browser/operations/guest.ts +94 -0
  8. package/browser/operations/owner.ts +201 -0
  9. package/browser/operations/protocol.ts +16 -0
  10. package/browser/operations/types.ts +41 -0
  11. package/browser/operations/writer.ts +106 -0
  12. package/browser/preview1-worker.ts +8 -1
  13. package/browser/process-broker.ts +372 -22
  14. package/browser/process-start.ts +5 -2
  15. package/browser/run-command.ts +388 -0
  16. package/browser/shared-fs.ts +20 -3
  17. package/browser/worker-memory.ts +6 -0
  18. package/browser/worker.ts +121 -27
  19. package/dist/browser/command-input.js +82 -0
  20. package/dist/browser/command-owner.js +2 -0
  21. package/dist/browser/display/guest.js +2 -18
  22. package/dist/browser/display/surface-info.js +18 -0
  23. package/dist/browser/operations/cells.js +80 -0
  24. package/dist/browser/operations/guest.js +67 -0
  25. package/dist/browser/operations/owner.js +175 -0
  26. package/dist/browser/operations/protocol.js +0 -0
  27. package/dist/browser/operations/types.js +0 -0
  28. package/dist/browser/operations/writer.js +98 -0
  29. package/dist/browser/preview1-worker.js +4 -0
  30. package/dist/browser/process-broker.js +317 -18
  31. package/dist/browser/process-start.js +3 -0
  32. package/dist/browser/run-command.js +377 -0
  33. package/dist/browser/shared-fs.js +8 -3
  34. package/dist/browser/worker-memory.js +10 -1
  35. package/dist/browser/worker.js +83 -28
  36. package/dist/fs/client.js +81 -18
  37. package/dist/fs/resolve-observation.js +11 -0
  38. package/dist/fs/service.js +51 -4
  39. package/dist/proc/command-transfer.js +72 -0
  40. package/dist/proc/directory.js +9 -1
  41. package/dist/proc/intrinsics/host.js +4 -1
  42. package/dist/proc/intrinsics.js +1 -0
  43. package/dist/proc/pipes.js +37 -4
  44. package/dist/proc/registry.js +25 -14
  45. package/dist/proc/start-command.js +101 -0
  46. package/dist/proc/supervisor.js +34 -10
  47. package/dist/proc/worker-broker.js +86 -31
  48. package/dist/proc/worker-client.js +67 -31
  49. package/dist/programs/collection.js +2 -0
  50. package/dist/runtime.js +14 -1
  51. package/dist/tooling/program/program-transformer.json +1 -1
  52. package/fs/client.ts +113 -17
  53. package/fs/resolve-observation.ts +25 -0
  54. package/fs/service.ts +63 -4
  55. package/index.ts +5 -0
  56. package/package.json +9 -1
  57. package/proc/command-transfer.ts +96 -0
  58. package/proc/directory.ts +10 -1
  59. package/proc/intrinsics/host.ts +5 -1
  60. package/proc/intrinsics.ts +1 -0
  61. package/proc/pipes.ts +39 -6
  62. package/proc/registry.ts +52 -17
  63. package/proc/start-command.ts +157 -0
  64. package/proc/supervisor.ts +34 -9
  65. package/proc/worker-broker.ts +100 -38
  66. package/proc/worker-client.ts +84 -31
  67. package/programs/collection.ts +4 -0
  68. package/runtime.ts +44 -3
  69. package/scripts/test-browser.ts +49 -29
  70. package/tests/browser-controls-discovery.test.ts +2 -10
  71. package/tests/browser-matrix.test.ts +105 -59
  72. package/tests/browser-navigation.test.ts +1 -1
  73. package/tests/browser-runner-lifecycle.ts +23 -13
  74. package/tests/command-input.test.ts +40 -0
  75. package/tests/command-scope.test.ts +422 -0
  76. package/tests/filesystem-client-intrinsics.test.ts +2 -0
  77. package/tests/filesystem-refcount.test.ts +2 -0
  78. package/tests/filesystem-resolve-observation.test.ts +185 -0
  79. package/tests/fixtures/command-bounded-admission.ts +31 -0
  80. package/tests/fixtures/command-disposal.ts +47 -0
  81. package/tests/fixtures/command-guests.ts +123 -0
  82. package/tests/fixtures/operation-fs-worker.ts +114 -0
  83. package/tests/fixtures/operation-observer-worker.ts +41 -0
  84. package/tests/fixtures/operation-page.ts +522 -0
  85. package/tests/fixtures/process-start-worker.ts +32 -0
  86. package/tests/link-browser-runner.ts +95 -22
  87. package/tests/node-exports.test.ts +29 -0
  88. package/tests/operation-diagnostics-browser.ts +192 -0
  89. package/tests/operation-diagnostics.test.ts +291 -0
  90. package/tests/page-runner/browser-controls-process-fixture.ts +24 -0
  91. package/tests/page-runner/browser-controls-runner.test.ts +20 -0
  92. package/tests/page-runner/browser-controls-runner.ts +1 -0
  93. package/tests/page-runner/browser-controls-suite.ts +20 -3
  94. package/tests/page-runner/control-run.ts +9 -1
  95. package/tests/page-runner/driver.ts +2 -0
  96. package/tests/page-runner/playwright-driver.ts +1 -1
  97. package/tests/page-runner/suite-host.ts +26 -1
  98. package/tests/page-runner/suite-startup.test.ts +39 -0
  99. package/tests/page-runner/threads-runtime-browser.test.ts +4 -6
  100. package/tests/page-runner/threads-runtime-suite.test.ts +14 -5
  101. package/tests/page-runner/worker-capability-controls.ts +174 -15
  102. package/tests/pipe-reader-reuse-races.test.ts +44 -0
  103. package/tests/process-start-browser-runner.ts +12 -4
  104. package/tests/process-start-browser.ts +66 -5
  105. package/tests/program-build-tools.test.ts +1 -1
  106. package/tests/runtime-facade.test.ts +5 -0
  107. package/tests/start-command.test.ts +109 -0
  108. package/tests/threads-guest-fixture.ts +1 -1
  109. package/tests/threads-guest-module.ts +6 -3
  110. package/tests/threads-guest.test.ts +25 -0
  111. package/tests/threads-runtime-browser-runner.ts +36 -13
  112. package/tests/threads-runtime-browser.ts +231 -92
  113. package/tests/threads-runtime-cases.ts +18 -1
  114. package/tests/threads-runtime-cleanup.ts +5 -1
  115. package/tests/threads-runtime-fd-browser.ts +247 -0
  116. package/tests/threads-runtime-fd-control.ts +3 -385
  117. package/tests/threads-runtime-fd-descriptors.test.ts +15 -13
  118. package/tests/threads-runtime-fd-module.ts +13 -2
  119. package/tests/threads-runtime-fd-service.ts +23 -2
  120. package/tests/threads-runtime-growth-worker.ts +61 -0
  121. package/tests/threads-runtime-host.ts +17 -4
  122. package/tests/threads-runtime-modules.ts +23 -5
  123. package/tests/threads-runtime-regression-controls.ts +386 -0
  124. package/tests/threads-runtime-regression-modules.ts +242 -0
  125. package/tests/threads-runtime-service-barrier.ts +8 -1
  126. package/tests/webkit-diagnostics.ts +125 -0
  127. package/tests/webkit-error-output.test.ts +118 -0
  128. package/tests/worker-memory-bootstrap.test.ts +19 -1
  129. package/tests/worker-memory-broker.test.ts +16 -8
  130. package/tooling/ci-paths.test.ts +329 -61
  131. package/tooling/private-authority.ts +14 -0
  132. package/tooling/program/program-transformer.json +1 -1
  133. package/tooling/tarball-smoke.ts +3 -1
@@ -1,3 +1,9 @@
1
+ import {
2
+ commandExecTransfer,
3
+ commandTransferFailed,
4
+ initializeCommandExec,
5
+ readCommandTransferFailure,
6
+ } from "../proc/command-transfer.js";
1
7
  import { WorkerStartError } from "../proc/start-diagnostic.ts";
2
8
  import { requireGroupPlan } from "../link/issuance.js";
3
9
  import type { SharedLinkPlan } from "../link/image.js";
@@ -71,6 +77,9 @@ import type { MemoryGroupMemberRequest } from "../group/protocol.js";
71
77
  import { WorkerExecutableAccess, rejectWorkerAccess } from "../proc/worker-access.js";
72
78
  import {
73
79
  directoryGroups,
80
+ directoryCapacity,
81
+ collectDirectoryJob,
82
+ idleDirectoryAdmission,
74
83
  directoryProcesses,
75
84
  directoryAdmissionVersion,
76
85
  commitDirectoryAdmission,
@@ -132,7 +141,7 @@ import {
132
141
  type WorkerProcessTransport,
133
142
  } from "../proc/worker-client.js";
134
143
  import { createFilesystemDescriptorCodec } from "../proc/filesystem-codec.js";
135
- import { WorkerPipeBroker } from "../proc/worker-pipes.js";
144
+ import { WorkerPipeBroker, WorkerPipeHost } from "../proc/worker-pipes.js";
136
145
  import {
137
146
  attachPipePublicationRegistry,
138
147
  PipeEndpoint,
@@ -150,6 +159,7 @@ import type { RuntimeWorkerRequest, RuntimeWorkerMessage } from "./worker.js";
150
159
  import type { RuntimeNetworkPathScope } from "./net/runtime.js";
151
160
  import type { SignalDelegation } from "../programs/index.js";
152
161
  import { packageIdentity } from "../programs/catalog.js";
162
+ import { preview1Launch } from "../programs/collection.js";
153
163
  import {
154
164
  CommandStdioError,
155
165
  type ProcessQuery,
@@ -158,10 +168,21 @@ import {
158
168
  } from "../proc/command.js";
159
169
  import type { CommandCapabilities } from "../proc/command-runner.js";
160
170
  import type { FileHandle } from "../core/filesystem.js";
171
+ import type { OperationOwner } from "./operations/owner.js";
172
+ import type {
173
+ GuestOperationBinding,
174
+ ObservedPreview1Bootstrap,
175
+ OperationBinding,
176
+ } from "./operations/protocol.js";
177
+ import type { OperationDiagnostics } from "./operations/types.js";
161
178
 
162
179
  export interface ProcessFilesystem {
163
180
  fork?(): FilesystemConnection;
164
- connect(identity: FilesystemIdentity, headroom?: Headroom | null): FilesystemConnection;
181
+ connect(
182
+ identity: FilesystemIdentity,
183
+ headroom?: Headroom | null,
184
+ operations?: OperationBinding,
185
+ ): FilesystemConnection;
165
186
  revoke(identity: FilesystemIdentity): void;
166
187
  reap(identity: FilesystemIdentity): void;
167
188
  quiesce(identity: FilesystemIdentity): Promise<void>;
@@ -200,6 +221,7 @@ export interface BrowserProcessBrokerOptions {
200
221
  onError?(error: unknown): void;
201
222
  /** Opt-in metadata only; observers must not reenter process control. Exceptions are ignored. */
202
223
  onProcessAdmission?: ProcessAdmissionObserver;
224
+ observeOperations?: boolean;
203
225
  /** Memory group policy (W1-W3). Groups are created only by a launch that asks for one. */
204
226
  memoryGroups?: MemoryGroupPolicyOptions;
205
227
  }
@@ -263,6 +285,7 @@ export interface RuntimeRootOptions {
263
285
  export interface WorkerLaunchOptions<T extends RuntimeWorkerRequest = RuntimeWorkerRequest> {
264
286
  /** Module entry stays inert until its first request. A fresh worker is created on demand. */
265
287
  workerUrl: string;
288
+ readonly [preview1Launch]?: true;
266
289
  notificationWorkerUrl?: string;
267
290
  /** Explicit internal proof profile. Source admission is still mandatory. */
268
291
  threaded?: ThreadLaunchOptions;
@@ -332,6 +355,7 @@ interface RuntimeLaunch {
332
355
  }
333
356
  interface RuntimeChild {
334
357
  readonly generation: number;
358
+ operationCapture?: number;
335
359
  readonly transport: WorkerProcessTransport;
336
360
  readonly launch: RuntimeLaunch;
337
361
  /** Shared with the pending launch that created this child. */
@@ -436,6 +460,13 @@ function senderRevoked(
436
460
  return result?.kind === "signaled" || (!result && filesystemRevoked);
437
461
  }
438
462
 
463
+ interface CommandRootState {
464
+ readonly root: WorkerProcessTransport;
465
+ readonly pending: Set<Promise<void>>;
466
+ readonly failures: Map<WorkerProcessTransport, unknown>;
467
+ stopped: boolean;
468
+ }
469
+
439
470
  export class BrowserProcessBroker {
440
471
  private readonly hostIdentity: RuntimeHostIdentity | null;
441
472
  private suspended = false;
@@ -458,6 +489,7 @@ export class BrowserProcessBroker {
458
489
  }
459
490
  >();
460
491
  private readonly completedRoots = new Set<number>();
492
+ private commandRoots?: Map<number, CommandRootState>;
461
493
  private readonly rootLeases = new Map<number, number>();
462
494
  private readonly controllers = new Map<number, ProcessController>();
463
495
  private readonly signalPolicies = new Map<
@@ -477,6 +509,8 @@ export class BrowserProcessBroker {
477
509
  private readonly terminalOutputs = new Map<number, TerminalOutputBudget>();
478
510
  private readonly registries = new Map<number, PipePublicationRegistry>();
479
511
  private readonly children = new Map<number, RuntimeChild>();
512
+ #operations?: OperationOwner;
513
+ #operationsUnavailable = false;
480
514
  private readonly launchStates = new WeakMap<object, RuntimeLaunch>();
481
515
  private readonly fences = new Map<number, Promise<void>>();
482
516
  private readonly startupDiagnostics = new Set<Promise<void>>();
@@ -528,10 +562,14 @@ export class BrowserProcessBroker {
528
562
  nativeReturn: (transport) => this.processNativeReturn(transport),
529
563
  onAdmitted: (transport) => this.acquireProcess(transport),
530
564
  quiesce: (_pid, transport) => this.quiesceUnstarted(transport),
565
+ beforeAdmit: (transport) => this.checkCommandAdmission(transport),
566
+ transferCleanup: (transport, cleanup) => this.trackCommandTransfer(transport, cleanup),
567
+ retireRejected: (transport) => this.retireRejectedCommand(transport),
531
568
  canExec: (transport) => this.canExec(transport),
532
569
  discardExec: (transport) => {
533
570
  const filesystem = this.filesystem(transport);
534
571
  this.options.filesystem.revoke(filesystem);
572
+ if (this.commandScope(transport)) return this.options.filesystem.quiesce(filesystem);
535
573
  this.options.filesystem.reap(filesystem);
536
574
  },
537
575
  });
@@ -546,6 +584,8 @@ export class BrowserProcessBroker {
546
584
  (proc) => {
547
585
  const supervisor = (this.supervisor = new proc.ProcessSupervisor({
548
586
  registry: this.options.registry,
587
+ byteBackedGuestOnly: (rootPid) =>
588
+ rootPid !== undefined && !!this.commandRoots?.has(rootPid),
549
589
  table: this.options.table,
550
590
  launch: (context) => this.launchPrepared(context),
551
591
  launchCommand: (context) => this.launchPrepared(context),
@@ -778,6 +818,12 @@ export class BrowserProcessBroker {
778
818
  context: ProcessContext | CommandProcessContext,
779
819
  ): ProcessHandle | Promise<ProcessHandle> {
780
820
  if (this.suspended) throw new Error("Process broker is disposed");
821
+ const transport = this.transport.get(context.pid);
822
+ const command = transport && this.commandScope(transport);
823
+ if (command) {
824
+ this.traceProcess(context, "launching");
825
+ this.checkCommandAdmission(transport);
826
+ }
781
827
  this.acquireObservation(context.observation, true);
782
828
  const observation = this.observationOwners.get(context.pid);
783
829
  const nativeReturned = this.nativeLaunchReturns.get(context.pid) ?? observation?.acquire();
@@ -799,7 +845,7 @@ export class BrowserProcessBroker {
799
845
  };
800
846
  const invokeLauncher = (): ProcessHandle | Promise<ProcessHandle> => {
801
847
  if ("command" in context) return this.launchCommand(context);
802
- if (context.execution?.kind === "host") return this.options.launch(context);
848
+ if (command || context.execution?.kind === "host") return this.options.launch(context);
803
849
  const controller = this.controllerFor(context.pid);
804
850
  if (!controller?.launch) return this.options.launch(context);
805
851
  controllerReturn = this.controllerNativeReturnFor(context.pid);
@@ -809,7 +855,7 @@ export class BrowserProcessBroker {
809
855
  return this.options.launch(context);
810
856
  };
811
857
  if (nativeReturned) this.nativeLaunchReturns.set(context.pid, nativeReturned);
812
- this.traceProcess(context, "launching");
858
+ if (!command) this.traceProcess(context, "launching");
813
859
  const launch = this.launchState(context);
814
860
  launch.active = true;
815
861
  (this.launches ??= new Set()).add(context.pid);
@@ -1168,6 +1214,7 @@ export class BrowserProcessBroker {
1168
1214
  if (root && !this.options.table.job(root.job)?.members.size)
1169
1215
  this.options.table.removeJob(root.job);
1170
1216
  this.completedRoots.delete(pid);
1217
+ this.commandRoots?.delete(pid);
1171
1218
  this.reservedRoots.delete(pid);
1172
1219
  this.descendantHooks.delete(pid);
1173
1220
  this.signalPolicies.delete(pid);
@@ -1253,6 +1300,7 @@ export class BrowserProcessBroker {
1253
1300
  !this.options.reservations.ownsBuffer("pipe-registry", data.pipeRegistry.buffer)
1254
1301
  )
1255
1302
  throw new TypeError("Root bootstrap requires a ledger-charged registry");
1303
+ const guestControls = this.commandRoots?.get(state.pid)?.root !== transport;
1256
1304
  const ticket = this.options.reservations.admit({
1257
1305
  pid: workerProcessState(transport).pid,
1258
1306
  executable: "adopted root",
@@ -1262,7 +1310,7 @@ export class BrowserProcessBroker {
1262
1310
  : { kind: "declared", memories: options.memory },
1263
1311
  group: "none",
1264
1312
  connection: false,
1265
- controls: true,
1313
+ controls: guestControls,
1266
1314
  });
1267
1315
  const previousData = transport.data;
1268
1316
  let changedData = false;
@@ -1311,7 +1359,7 @@ export class BrowserProcessBroker {
1311
1359
  if (descendant) this.descendantHooks.set(state.pid, descendant);
1312
1360
  this.rootAdmissions.set(state.pid, ticket);
1313
1361
  this.rootTickets.set(state.pid, ticket.launched());
1314
- this.rootGrants.set(state.pid, ticket.control);
1362
+ if (guestControls) this.rootGrants.set(state.pid, ticket.control);
1315
1363
  } catch (error) {
1316
1364
  if (changedData) transport.data = previousData;
1317
1365
  registeredRegistry?.collectProcess(state.pid);
@@ -1324,6 +1372,210 @@ export class BrowserProcessBroker {
1324
1372
  this.activateRuntimeRoot(supervisor, transport);
1325
1373
  }
1326
1374
  }
1375
+ async adoptCommandRoot(
1376
+ transport: WorkerProcessTransport,
1377
+ options: RuntimeRootOptions,
1378
+ ): Promise<void> {
1379
+ if (this.suspended || !this.supervisor) throw new Error("Process broker is unavailable");
1380
+ const processCapacity = directoryCapacity(transport.directory);
1381
+ const registry = new PipePublicationRegistry({
1382
+ processCapacity,
1383
+ cellsPerProcess: 16,
1384
+ maxCells: processCapacity * 128,
1385
+ wake: workerProcessState(transport).wake,
1386
+ allocate: (length, maximum) =>
1387
+ this.options.reservations.buffer("pipe-registry", {
1388
+ kind: "growable-buffer",
1389
+ initial: length,
1390
+ maximum: bytes(maximum),
1391
+ }),
1392
+ });
1393
+ initializeCommandExec(transport);
1394
+ transport.data = { filesystem: options.filesystem, pipeRegistry: registry.handle() };
1395
+ (this.commandRoots ??= new Map()).set(transport.pid, {
1396
+ root: transport,
1397
+ pending: new Set(),
1398
+ failures: new Map(),
1399
+ stopped: false,
1400
+ });
1401
+ try {
1402
+ await this.adoptRuntimeRoot(transport, options);
1403
+ } catch (error) {
1404
+ if (!this.roots.has(transport.pid)) this.commandRoots?.delete(transport.pid);
1405
+ throw error;
1406
+ }
1407
+ }
1408
+ private commandScope(transport: WorkerProcessTransport): CommandRootState | undefined {
1409
+ if (!this.commandRoots?.size) return;
1410
+ let rootPid: number;
1411
+ try {
1412
+ rootPid = workerProcessState(transport).rootPid;
1413
+ } catch (error) {
1414
+ if (!isCollectedProcess(error)) throw error;
1415
+ return;
1416
+ }
1417
+ const scope = this.commandRoots.get(rootPid);
1418
+ if (scope && workerProcessDirectoryId(scope.root) === workerProcessDirectoryId(transport))
1419
+ return scope;
1420
+ }
1421
+ private checkCommandAdmission(transport: WorkerProcessTransport): void {
1422
+ const scope = this.commandScope(transport);
1423
+ if (scope && this.commandAdmissionClosed(scope))
1424
+ throw new ProcessError(ProcessErrno.SRCH, "Command is stopping");
1425
+ }
1426
+ private commandAdmissionClosed(scope: CommandRootState): boolean {
1427
+ return (
1428
+ scope.stopped ||
1429
+ scope.failures.size !== 0 ||
1430
+ commandTransferFailed(scope.root.commandTransfer)
1431
+ );
1432
+ }
1433
+ private trackCommandTransfer(
1434
+ transport: WorkerProcessTransport,
1435
+ cleanup: () => Promise<void>,
1436
+ ): Promise<void> {
1437
+ const scope = this.commandScope(transport);
1438
+ if (!scope) return cleanup();
1439
+ const pending = Promise.resolve().then(cleanup);
1440
+ scope.pending.add(pending);
1441
+ const settle = () => {
1442
+ scope.pending.delete(pending);
1443
+ wakeWorkerProcess(scope.root);
1444
+ };
1445
+ void pending.then(settle, (error) => {
1446
+ scope.failures.set(transport, error);
1447
+ settle();
1448
+ });
1449
+ return pending;
1450
+ }
1451
+ private async retireRejectedCommand(transport: WorkerProcessTransport): Promise<void> {
1452
+ const returned = this.processNativeReturn(transport);
1453
+ if (this.acquiredProcesses.get(transport.pid) === this.processLifetime(transport)) {
1454
+ await this.retireProcess(transport.pid, true);
1455
+ this.retireChildController(transport.pid);
1456
+ }
1457
+ returned();
1458
+ }
1459
+ private commandCleanupFailure(scope: CommandRootState): Error | undefined {
1460
+ if (scope.failures.size) {
1461
+ const [cause] = scope.failures.values();
1462
+ return new Error("Command transfer cleanup failed", { cause });
1463
+ }
1464
+ const buffer = scope.root.commandTransfer;
1465
+ return buffer ? readCommandTransferFailure(buffer)?.error : undefined;
1466
+ }
1467
+ private async joinCommandExec(transport: WorkerProcessTransport): Promise<void> {
1468
+ const scope = this.commandScope(transport);
1469
+ const handoff = commandExecTransfer(transport);
1470
+ if (!scope || !handoff) return;
1471
+ const state = workerProcessState(transport);
1472
+ for (;;) {
1473
+ const expected = Atomics.load(state.wake, 0);
1474
+ const buffer = scope.root.commandTransfer;
1475
+ const local = buffer && readCommandTransferFailure(buffer);
1476
+ if (
1477
+ local?.kind === "exec" &&
1478
+ local.pid === transport.pid &&
1479
+ local.generation === transport.generation
1480
+ )
1481
+ throw local.error;
1482
+ const staged = controlLoad(handoff);
1483
+ if (staged === 0) return;
1484
+ for (const [transfer, cause] of scope.failures) {
1485
+ if (transfer.pid === transport.pid && transfer.generation === staged)
1486
+ throw new Error("Exec transfer cleanup failed", { cause });
1487
+ }
1488
+ await atomicsWaitAsync(state.wake, 0, expected).value;
1489
+ }
1490
+ }
1491
+
1492
+ commandPipeHost(
1493
+ transport: WorkerProcessTransport,
1494
+ postMessage: (message: WorkerProcessMessage) => void,
1495
+ ): WorkerPipeHost {
1496
+ const registry = this.registries.get(transport.pid);
1497
+ if (!registry || !this.commandRoots?.has(transport.pid))
1498
+ throw new Error("Command root is not admitted");
1499
+ return new WorkerPipeHost({
1500
+ transport,
1501
+ registry,
1502
+ postMessage,
1503
+ allocateShared: (length) =>
1504
+ this.options.reservations.buffer("control", {
1505
+ kind: "fixed-buffer",
1506
+ length: bytes(length),
1507
+ }),
1508
+ });
1509
+ }
1510
+ stopCommandRoot(root: WorkerProcessTransport): void {
1511
+ const scope = this.commandRoots?.get(root.pid);
1512
+ if (!scope || scope.stopped) return;
1513
+ scope.stopped = true;
1514
+ this.stopCommandMembers(root);
1515
+ wakeWorkerProcess(root);
1516
+ }
1517
+ private stopCommandMembers(root: WorkerProcessTransport): void {
1518
+ const members = Array.from(directoryProcesses(root.directory)).filter((state) => {
1519
+ try {
1520
+ return state.pid !== root.pid && !readOutcome(state.signals.outcome);
1521
+ } catch (error) {
1522
+ if (!isCollectedProcess(error)) throw error;
1523
+ return false;
1524
+ }
1525
+ });
1526
+ for (const state of members) this.requestSignalIfPresent(state.signals, 9);
1527
+ for (const state of members) {
1528
+ try {
1529
+ this.revokeRuntimeProcess(state.pid, workerProcessDirectoryId(root));
1530
+ } catch (error) {
1531
+ if (!isCollectedProcess(error)) throw error;
1532
+ }
1533
+ }
1534
+ }
1535
+ checkCommandCleanup(root: WorkerProcessTransport, mayCollect: boolean): boolean {
1536
+ const scope = this.commandRoots?.get(root.pid);
1537
+ const supervisor = this.supervisor;
1538
+ if (!scope || !supervisor) throw new Error("Command root is not admitted");
1539
+ const version = idleDirectoryAdmission(root.directory);
1540
+ if (scope.stopped) this.stopCommandMembers(root);
1541
+ this.transport.pump();
1542
+ this.serviceTerminalOutput(root.pid);
1543
+ const failure = this.commandCleanupFailure(scope);
1544
+ if (failure) throw failure;
1545
+ const retired = supervisor.rootConsumersRetired(root.pid);
1546
+ if (!mayCollect) return false;
1547
+ const ownJob = workerProcessState(root).job;
1548
+ for (const group of directoryGroups(root.directory)) {
1549
+ if (group.id === ownJob) continue;
1550
+ try {
1551
+ if (supervisor.job(group.id)) {
1552
+ if (supervisor.jobCleanupReady(root.pid, group.id))
1553
+ supervisor.reapJob(root.pid, group.id);
1554
+ } else if (controlLoad(group.pending) === 0) {
1555
+ collectDirectoryJob(root.directory, group.slot, group.id);
1556
+ }
1557
+ } catch (error) {
1558
+ if (!isCollectedProcess(error)) throw error;
1559
+ }
1560
+ }
1561
+ return (
1562
+ retired &&
1563
+ scope.pending.size === 0 &&
1564
+ !Array.from(directoryGroups(root.directory)).some((group) => group.id !== ownJob) &&
1565
+ !this.terminalOutputs.get(root.pid)?.pending() &&
1566
+ version !== undefined &&
1567
+ idleDirectoryAdmission(root.directory) === version
1568
+ );
1569
+ }
1570
+ async retireCommandRoot(root: WorkerProcessTransport): Promise<void> {
1571
+ const owner = this.observationOwners.get(root.pid);
1572
+ await this.quiesceProcess(root.pid);
1573
+ await this.rootExit(root.pid, 0);
1574
+ this.rootStopped(root.pid);
1575
+ await owner?.join();
1576
+ this.pipes.pump();
1577
+ }
1578
+
1327
1579
  private bindPipeRegistry(transport: WorkerProcessTransport): void {
1328
1580
  const state = workerProcessState(transport);
1329
1581
  const registry = this.registries.get(state.rootPid);
@@ -1678,7 +1930,8 @@ export class BrowserProcessBroker {
1678
1930
  }
1679
1931
  }
1680
1932
  const revoked = !consumingReceipt && senderRevoked(result, filesystemRevoked);
1681
- if ((!sender && !retainedNotice) || this.suspended || revoked) {
1933
+ const stopping = this.commandMessageStopped(message);
1934
+ if ((!sender && !retainedNotice) || this.suspended || revoked || stopping) {
1682
1935
  this.rejectMessage(
1683
1936
  message,
1684
1937
  senderPid,
@@ -1688,7 +1941,9 @@ export class BrowserProcessBroker {
1688
1941
  ? "unknown-sender"
1689
1942
  : result?.kind === "signaled"
1690
1943
  ? "sender-signaled"
1691
- : "sender-revoked",
1944
+ : stopping
1945
+ ? "external-rejection"
1946
+ : "sender-revoked",
1692
1947
  );
1693
1948
  return;
1694
1949
  }
@@ -1700,6 +1955,16 @@ export class BrowserProcessBroker {
1700
1955
  this.retireRoots();
1701
1956
  if (message.operation !== "pipe") this.watch();
1702
1957
  }
1958
+ private commandMessageStopped(message: WorkerProcessMessage): boolean {
1959
+ if (message.operation !== "spawn" && message.operation !== "exec") return false;
1960
+ try {
1961
+ const scope = this.commandScope(message.transport);
1962
+ return scope !== undefined && this.commandAdmissionClosed(scope);
1963
+ } catch (error) {
1964
+ if (!isCollectedProcess(error)) throw error;
1965
+ return false;
1966
+ }
1967
+ }
1703
1968
  private async accessMessage(
1704
1969
  message: Extract<WorkerProcessMessage, { operation: "access" | "access-cancel" }>,
1705
1970
  senderPid: number,
@@ -1810,26 +2075,34 @@ export class BrowserProcessBroker {
1810
2075
  reject = fail;
1811
2076
  });
1812
2077
  this.rejectedTransfers.set(key, pending);
1813
- void this.releaseRejectedTransfer(transport).then(resolve, reject);
2078
+ void this.trackCommandTransfer(transport, () => this.releaseRejectedTransfer(transport)).then(
2079
+ resolve,
2080
+ reject,
2081
+ );
1814
2082
  void pending.then(
1815
2083
  () => this.rejectedTransfers.delete(key),
1816
2084
  (error) => this.report(error),
1817
2085
  );
1818
2086
  }
1819
2087
  private async releaseRejectedTransfer(transport: WorkerProcessTransport): Promise<void> {
1820
- let cleaned = true;
2088
+ const errors: unknown[] = [];
1821
2089
  const codec = this.discardCodec();
1822
2090
  for (const token of transport.resources) {
1823
2091
  try {
1824
2092
  codec.discard(token);
1825
2093
  } catch (error) {
1826
- cleaned = false;
2094
+ errors.push(error);
1827
2095
  this.report(error);
1828
2096
  }
1829
2097
  }
1830
2098
  wakeWorkerProcess(transport);
1831
2099
  await this.quiesceUnstarted(transport);
1832
- if (!cleaned) return;
2100
+ const scope = this.commandScope(transport);
2101
+ if (errors.length) {
2102
+ if (scope) throw new AggregateError(errors, "Rejected spawn descriptor cleanup failed");
2103
+ return;
2104
+ }
2105
+ if (scope) await this.retireRejectedCommand(transport);
1833
2106
  controlStore(workerProcessState(transport).confirmed, 0, 1);
1834
2107
  confirmWorkerProcessJob(transport);
1835
2108
  }
@@ -1934,6 +2207,61 @@ export class BrowserProcessBroker {
1934
2207
  return { ...child.identity, bytes: bytes < 0n ? null : Number(bytes) };
1935
2208
  });
1936
2209
  }
2210
+ async prepareOperationDiagnostics(): Promise<void> {
2211
+ try {
2212
+ const { OperationOwner } = await import("./operations/owner.js");
2213
+ this.#operations = new OperationOwner(
2214
+ (length) =>
2215
+ this.options.reservations.buffer("control", {
2216
+ kind: "fixed-buffer",
2217
+ length: bytes(length),
2218
+ }),
2219
+ ({ pid, generation, captureId }) => {
2220
+ const child = this.children.get(pid);
2221
+ return child?.generation === generation && child.operationCapture === captureId;
2222
+ },
2223
+ );
2224
+ } catch {
2225
+ this.#operationsUnavailable = true;
2226
+ }
2227
+ }
2228
+ operationDiagnostics(): OperationDiagnostics {
2229
+ if (!this.options.observeOperations) return { status: "disabled" };
2230
+ try {
2231
+ return (
2232
+ this.#operations?.snapshot() ?? {
2233
+ status: this.#operationsUnavailable ? "unavailable" : "empty",
2234
+ }
2235
+ );
2236
+ } catch {
2237
+ return { status: "unavailable" };
2238
+ }
2239
+ }
2240
+ private captureOperations(
2241
+ child: RuntimeChild,
2242
+ options: WorkerLaunchOptions,
2243
+ enabled: boolean,
2244
+ ): GuestOperationBinding | undefined {
2245
+ if (!enabled || !this.#operations || options.memoryGroup || options.memories?.length) return;
2246
+ const memories = moduleMemoryDeclarations(options.request.module);
2247
+ if (memories?.length !== 1 || memories[0]?.kind !== "private") return;
2248
+ try {
2249
+ const binding = this.#operations.enroll(child.identity.pid, child.generation);
2250
+ if (binding) child.operationCapture = binding.captureId;
2251
+ return binding;
2252
+ } catch {
2253
+ return;
2254
+ }
2255
+ }
2256
+ private connectWorkerFilesystem(
2257
+ filesystem: FilesystemIdentity,
2258
+ arena: Headroom | null,
2259
+ binding: GuestOperationBinding | undefined,
2260
+ ): FilesystemConnection {
2261
+ if (!binding) return this.options.filesystem.connect(filesystem, arena);
2262
+ const { buffer, slot, captureId } = binding;
2263
+ return this.options.filesystem.connect(filesystem, arena, { buffer, slot, captureId });
2264
+ }
1937
2265
  /**
1938
2266
  * The start step each live launch reached, with page timestamps: a hung start names its
1939
2267
  * stuck step. Fresh authority-free snapshots; see docs/process-observation.md, "Start states".
@@ -2042,7 +2370,11 @@ export class BrowserProcessBroker {
2042
2370
  )
2043
2371
  )
2044
2372
  throw new Error("Threaded Preview 1 requires validated source bytes");
2045
- return this.launchOwnedWorker(context, { ...options, network, graphics });
2373
+ return this.launchOwnedWorker(
2374
+ context,
2375
+ { ...options, network, graphics },
2376
+ !!this.#operations && options[preview1Launch] === true,
2377
+ );
2046
2378
  } catch (error) {
2047
2379
  if (
2048
2380
  !this.children.has(context.pid) &&
@@ -2148,6 +2480,7 @@ export class BrowserProcessBroker {
2148
2480
  private launchOwnedWorker<T extends RuntimeWorkerRequest>(
2149
2481
  context: ProcessContext,
2150
2482
  options: WorkerLaunchOptions<T>,
2483
+ observeOperations: boolean,
2151
2484
  ): ProcessHandle {
2152
2485
  if (this.suspended) {
2153
2486
  options.network?.dispose();
@@ -2177,7 +2510,7 @@ export class BrowserProcessBroker {
2177
2510
  throw error;
2178
2511
  }
2179
2512
  }
2180
- let memory: BigInt64Array;
2513
+ let memory: BigInt64Array<SharedArrayBuffer>;
2181
2514
  try {
2182
2515
  memory = new BigInt64Array(allocateSharedControl(8));
2183
2516
  Atomics.store(memory, 0, -1n);
@@ -2215,6 +2548,7 @@ export class BrowserProcessBroker {
2215
2548
  };
2216
2549
  this.captureImageState(child);
2217
2550
  this.children.set(context.pid, child);
2551
+ const operations = this.captureOperations(child, options, observeOperations);
2218
2552
  context.registerRevocation(() => this.disposeNetwork(child));
2219
2553
  let connection: FilesystemConnection | undefined;
2220
2554
  let worker: Worker;
@@ -2246,7 +2580,7 @@ export class BrowserProcessBroker {
2246
2580
  options.memoryGroup,
2247
2581
  ticket.group,
2248
2582
  );
2249
- connection = this.options.filesystem.connect(filesystem, ticket.arena);
2583
+ connection = this.connectWorkerFilesystem(filesystem, ticket.arena, operations);
2250
2584
  if (readOutcome(context.outcome))
2251
2585
  throw new ProcessError(ProcessErrno.SRCH, "process exited before worker construction");
2252
2586
  worker = child.worker = this.workers.take(options.workerUrl);
@@ -2304,7 +2638,10 @@ export class BrowserProcessBroker {
2304
2638
  if (request.notifications) ports.push(request.notifications.port);
2305
2639
  if (request.network) ports.push(request.network.port);
2306
2640
  if (request.graphics) ports.push(request.graphics.port);
2307
- worker.postMessage(request, group ? ports.concat(group.transfer) : ports);
2641
+ const bootstrap: RuntimeWorkerRequest | ObservedPreview1Bootstrap = operations
2642
+ ? [request, operations]
2643
+ : request;
2644
+ worker.postMessage(bootstrap, group ? ports.concat(group.transfer) : ports);
2308
2645
  markStart(child.start, "start-posted");
2309
2646
  } catch (error) {
2310
2647
  child.failed = true;
@@ -2687,10 +3024,12 @@ export class BrowserProcessBroker {
2687
3024
  if (child && !this.roots.has(pid) && !this.reservedRoots.has(pid)) {
2688
3025
  if (child.finalQuiet) return;
2689
3026
  const terminal = this.terminalLifetimes.get(pid)?.quiesce();
2690
- return (child.finalFence ??= Promise.all([this.imageFence(child), terminal]).then(() => {
2691
- this.collectRuntimeProcess(pid);
2692
- child.finalQuiet = true;
2693
- }));
3027
+ return (child.finalFence ??= Promise.all([this.imageFence(child), terminal])
3028
+ .then(() => this.joinCommandExec(child.transport))
3029
+ .then(() => {
3030
+ this.collectRuntimeProcess(pid);
3031
+ child.finalQuiet = true;
3032
+ }));
2694
3033
  }
2695
3034
  const pending = this.fences.get(pid);
2696
3035
  if (pending) return pending;
@@ -2770,6 +3109,9 @@ export class BrowserProcessBroker {
2770
3109
  }
2771
3110
  }
2772
3111
  }
3112
+ const transport = this.transport.get(pid);
3113
+ if (transport && this.commandScope(transport))
3114
+ return Promise.all(pending).then(() => this.joinCommandExec(transport));
2773
3115
  if (pending.length) return Promise.all(pending).then(() => {});
2774
3116
  }
2775
3117
  private quiesceChild(child: RuntimeChild): void | Promise<void> {
@@ -3189,10 +3531,12 @@ export class BrowserProcessBroker {
3189
3531
  (this.controllerStops ??= new Map()).set(pid, { pending: stopping, controllerStop: true });
3190
3532
  return stopping;
3191
3533
  }
3192
- private async retireProcess(pid: number): Promise<void> {
3534
+ private async retireProcess(pid: number, rejectedTransferFenced = false): Promise<void> {
3193
3535
  await (this.children.get(pid)?.launch.pending ?? this.pendingLaunches?.get(pid))?.acquired;
3194
3536
  this.observationOwners.get(pid)?.close();
3195
- if (this.suspended) {
3537
+ // A rejected transfer never entered a guest adapter. Its own fence is already
3538
+ // complete, and shutdown waits for that rejection before it opens the global stop gate.
3539
+ if (this.suspended && !rejectedTransferFenced) {
3196
3540
  await this.retirementGate.promise;
3197
3541
  return;
3198
3542
  }
@@ -3412,6 +3756,11 @@ export class BrowserProcessBroker {
3412
3756
  async quiesce(): Promise<void> {
3413
3757
  await this.transport.settled();
3414
3758
  await Promise.all(this.rejectedTransfers.values());
3759
+ for (const scope of this.commandRoots?.values() ?? []) {
3760
+ await Promise.all(scope.pending);
3761
+ const failure = this.commandCleanupFailure(scope);
3762
+ if (failure) throw failure;
3763
+ }
3415
3764
  const pids = new Set(
3416
3765
  Array.from(this.options.table.values(), (record) => record.pid).concat(
3417
3766
  Array.from(this.controllers.keys()),
@@ -3572,6 +3921,7 @@ export class BrowserProcessBroker {
3572
3921
  this.completedRoots.clear();
3573
3922
  this.rootLeases.clear();
3574
3923
  this.roots.clear();
3924
+ this.commandRoots?.clear();
3575
3925
  this.outputs.clear();
3576
3926
  this.terminalOutputs.clear();
3577
3927
  this.registries.clear();
@@ -4,8 +4,8 @@ import type { ProcessLifecycle } from "../proc/types.js";
4
4
 
5
5
  /**
6
6
  * Steps of one process start, in order. See docs/process-observation.md, "Start states".
7
- * The worker's bootstrap steps (`runtime-loaded`, `group-joined`, `modules-loaded`) share one
8
- * cell, so the page sees only the latest when it looks, stamped with the worker's own time.
7
+ * The worker's bootstrap steps share one cell until memory is bound. The page sees only the
8
+ * latest when it looks, stamped with the worker's own time.
9
9
  * `memory-bound` and `running` are stamped when the page first saw them.
10
10
  */
11
11
  export type ProcessStartStep =
@@ -26,6 +26,9 @@ const steps: readonly ProcessStartStep[] = [
26
26
  "runtime-loaded",
27
27
  "group-joined",
28
28
  "modules-loaded",
29
+ "installing-bindings",
30
+ "bindings-installed",
31
+ "instantiating",
29
32
  "memory-bound",
30
33
  "instantiated",
31
34
  "running",