@waffle-os/runtime 0.0.156 → 0.0.157

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 (75) hide show
  1. package/browser/filesystem-backend.ts +11 -1
  2. package/browser/preview-protocol.ts +2 -0
  3. package/browser/preview.ts +128 -18
  4. package/browser/runtime-terminals.ts +65 -24
  5. package/browser/shared-fs.ts +141 -14
  6. package/browser/worker.ts +73 -6
  7. package/core/descriptors.ts +19 -2
  8. package/core/devices.ts +237 -2
  9. package/core/fd-reopen.ts +105 -20
  10. package/core/filesystem.ts +71 -0
  11. package/core/index.ts +4 -0
  12. package/core/open-file.ts +212 -18
  13. package/core/wasi.ts +397 -46
  14. package/dist/browser/filesystem-backend.js +4 -2
  15. package/dist/browser/preview.js +120 -17
  16. package/dist/browser/runtime-terminals.js +53 -10
  17. package/dist/browser/shared-fs.js +124 -11
  18. package/dist/browser/worker.js +59 -6
  19. package/dist/core/descriptors.js +9 -1
  20. package/dist/core/devices.js +211 -1
  21. package/dist/core/fd-reopen.js +79 -18
  22. package/dist/core/filesystem.js +13 -0
  23. package/dist/core/open-file.js +166 -13
  24. package/dist/core/wasi.js +353 -27
  25. package/dist/fs/backend.js +29 -2
  26. package/dist/fs/client.js +199 -6
  27. package/dist/fs/index.js +21 -1
  28. package/dist/fs/indexeddb.js +30 -2
  29. package/dist/fs/locks.js +1112 -0
  30. package/dist/fs/memory.js +109 -1
  31. package/dist/fs/multitab-backend.js +315 -195
  32. package/dist/fs/multitab-protocol.js +1 -0
  33. package/dist/fs/persistent.js +13 -6
  34. package/dist/fs/protocol.js +9 -3
  35. package/dist/fs/service.js +386 -22
  36. package/dist/fs/shared.js +54 -1
  37. package/dist/fs/storage-geometry.js +2 -0
  38. package/dist/interrupt/rewriter-internal.js +4 -1
  39. package/dist/proc/abi.js +80 -6
  40. package/dist/proc/errors.js +1 -0
  41. package/dist/proc/filesystem-codec.js +40 -9
  42. package/dist/proc/index.js +10 -1
  43. package/dist/proc/pty.js +193 -0
  44. package/dist/proc/worker-client.js +11 -2
  45. package/dist/proc/worker-pipes.js +51 -0
  46. package/dist/runtime.js +11 -2
  47. package/dist/search/engine.js +53 -0
  48. package/dist/tooling/program/program-transformer.json +1 -1
  49. package/fs/backend.ts +33 -1
  50. package/fs/client.ts +225 -6
  51. package/fs/index.ts +22 -1
  52. package/fs/indexeddb.ts +36 -2
  53. package/fs/locks.ts +1406 -0
  54. package/fs/memory.ts +114 -1
  55. package/fs/multitab-backend.ts +561 -303
  56. package/fs/multitab-protocol.ts +1 -0
  57. package/fs/persistent.ts +14 -3
  58. package/fs/protocol.ts +17 -5
  59. package/fs/service.ts +468 -23
  60. package/fs/shared.ts +60 -2
  61. package/fs/storage-geometry.ts +3 -0
  62. package/index.ts +2 -0
  63. package/interrupt/rewriter-internal.ts +4 -1
  64. package/package.json +2 -2
  65. package/proc/abi.ts +79 -6
  66. package/proc/errors.ts +1 -0
  67. package/proc/filesystem-codec.ts +39 -9
  68. package/proc/index.ts +11 -0
  69. package/proc/pty.ts +227 -0
  70. package/proc/worker-client.ts +28 -6
  71. package/proc/worker-pipes.ts +57 -0
  72. package/runtime.ts +12 -2
  73. package/search/engine.ts +49 -0
  74. package/testing/indexeddb-storage-browser.ts +173 -2
  75. package/tooling/program/program-transformer.json +1 -1
package/fs/shared.ts CHANGED
@@ -48,6 +48,7 @@ import {
48
48
  PAGE_CELLS,
49
49
  SLOT_WORDS,
50
50
  HEADER_WORDS,
51
+ MACHINE_ID_OFFSET,
51
52
  SLOT_OFFSET,
52
53
  TABLE_OWNER_OFFSET,
53
54
  PAGE_CELL_OFFSET,
@@ -55,6 +56,7 @@ import {
55
56
  DATA_OFFSET,
56
57
  SHARED_ROOT_BYTES,
57
58
  } from "./storage-geometry.js";
59
+ import { validateMachineId } from "../core/devices.js";
58
60
  import { SHARED_SEGMENT_BYTES } from "./shared-capacity.js";
59
61
  export { SLOT_WORDS } from "./storage-geometry.js";
60
62
 
@@ -77,6 +79,8 @@ const FREED_REVISION_HIGH = 8;
77
79
  // signals, 16 to 24 the identity allocator, and 32 onward the dirty-admission ledger.
78
80
  const REGISTERED_SLOTS = 11;
79
81
  const CHANGE_SEQUENCE = 12;
82
+ /** Active POSIX byte-range lock count maintained by FilesystemService so fd_close skips RPCs when 0. */
83
+ export const POSIX_LOCK_COUNT = 13;
80
84
  // Unlinks of this table, for capability trimming. Kept across remount, so it never repeats.
81
85
  const UNLINK_GENERATION = 31;
82
86
  // Global-lock accelerators. Nothing below a hint is free; ownership stays authoritative.
@@ -107,6 +111,50 @@ const RESIDENT = 1;
107
111
  // The intrinsic copy, so a guest iovec subclass's set() cannot reenter under a file lock. WASI
108
112
  // iovecs are plain views; a subclass's overridden length/buffer/byteOffset getters still run there.
109
113
  const copyBytes = Uint8Array.prototype.set;
114
+ const HEX_DIGITS = "0123456789abcdef";
115
+
116
+ function hexWord(word: number): string {
117
+ let out = "";
118
+ for (let shift = 28; shift >= 0; shift -= 4) out += HEX_DIGITS[(word >>> shift) & 0xf]!;
119
+ return out;
120
+ }
121
+
122
+ /** Derive a stable 32-char lowercase hex machine-id(5) from a UUID workspace identifier. */
123
+ export function machineIdFromWorkspace(workspaceId: string): string {
124
+ return validateMachineId(workspaceId.replaceAll("-", "").toLowerCase());
125
+ }
126
+
127
+ /** Publish a 32-char lowercase hex machine-id into the shared root header using a seqlock. */
128
+ export function writeSharedMachineId(cells: Int32Array, machineId: string): void {
129
+ const valid = validateMachineId(machineId);
130
+ const seqWord = MACHINE_ID_OFFSET + 4;
131
+ const current = Atomics.load(cells, seqWord) >>> 0;
132
+ const base = current & ~1;
133
+ Atomics.store(cells, seqWord, (base + 1) | 0);
134
+ for (let i = 0; i < 4; i++) {
135
+ const word = Number.parseInt(valid.slice(i * 8, i * 8 + 8), 16) | 0;
136
+ Atomics.store(cells, MACHINE_ID_OFFSET + i, word);
137
+ }
138
+ const nextEven = (base + 2) | 0;
139
+ Atomics.store(cells, seqWord, nextEven === 0 ? 2 : nextEven);
140
+ }
141
+
142
+ /** Lock-free read of the shared root header's 32-char lowercase hex machine-id. */
143
+ export function readSharedMachineId(cells: Int32Array): string | undefined {
144
+ const seqWord = MACHINE_ID_OFFSET + 4;
145
+ for (let attempt = 0; attempt < 64; attempt++) {
146
+ const seq1 = atomicsLoad(cells, seqWord);
147
+ if (seq1 === 0) return undefined;
148
+ if ((seq1 & 1) !== 0) continue;
149
+ const w0 = atomicsLoad(cells, MACHINE_ID_OFFSET);
150
+ const w1 = atomicsLoad(cells, MACHINE_ID_OFFSET + 1);
151
+ const w2 = atomicsLoad(cells, MACHINE_ID_OFFSET + 2);
152
+ const w3 = atomicsLoad(cells, MACHINE_ID_OFFSET + 3);
153
+ const seq2 = atomicsLoad(cells, seqWord);
154
+ if (seq1 === seq2) return hexWord(w0) + hexWord(w1) + hexWord(w2) + hexWord(w3);
155
+ }
156
+ return undefined;
157
+ }
110
158
 
111
159
  export class MissingSegmentError extends Error {}
112
160
  export class MissingDataError extends Error {}
@@ -297,6 +345,12 @@ export class SharedFilesystemState {
297
345
  setClientMode(mode: number): void {
298
346
  Atomics.store(this.cells, CLIENT_MODE, mode | 0);
299
347
  }
348
+ setMachineId(machineId: string): void {
349
+ writeSharedMachineId(this.cells, machineId);
350
+ }
351
+ getMachineId(): string | undefined {
352
+ return readSharedMachineId(this.cells);
353
+ }
300
354
  isDirectDisabled(): boolean {
301
355
  return (atomicsLoad(this.cells, CLIENT_MODE) & CLIENT_MODE_NO_DIRECT_IO) !== 0;
302
356
  }
@@ -308,7 +362,8 @@ export class SharedFilesystemState {
308
362
  }
309
363
  /** Reset all per-mount filesystem state in place across Host remount/demotion while preserving
310
364
  * tab-lifetime header invariants (`MAGIC`, `maxSegments`, owner/probe words, `WATCH_OFFSET`,
311
- * `watch.cells[3]`, `CLIENT_MODE`, `UNLINK_GENERATION`) and reusing tab-lifetime segments at their exact indexes. */
365
+ * `watch.cells[3]`, `CLIENT_MODE`, `UNLINK_GENERATION`, `MACHINE_ID_OFFSET..76`) and reusing
366
+ * tab-lifetime segments at their exact indexes. */
312
367
  resetForRemount(retainedSegments: readonly (SharedArrayBuffer | undefined)[] = []): void {
313
368
  Atomics.store(this.cells, GLOBAL_LOCK, 0);
314
369
  Atomics.store(this.cells, USED_PAGES, 0);
@@ -316,7 +371,7 @@ export class SharedFilesystemState {
316
371
  Atomics.store(this.cells, PHYSICAL_HINT, 0);
317
372
  Atomics.store(this.cells, TABLE_HINT, 0);
318
373
  Atomics.store(this.cells, PINNED_PAGES, 0);
319
- for (let i = 32; i < HEADER_WORDS; i++) Atomics.store(this.cells, i, 0);
374
+ for (let i = 32; i < MACHINE_ID_OFFSET; i++) Atomics.store(this.cells, i, 0);
320
375
  this.owners.fill(0);
321
376
  this.slots.fill(0);
322
377
  this.tableOwners.fill(0);
@@ -2441,6 +2496,9 @@ export class SharedFilesystemState {
2441
2496
  unlinkGeneration(): number {
2442
2497
  return Atomics.load(this.cells, UNLINK_GENERATION);
2443
2498
  }
2499
+ posixLockCount(): number {
2500
+ return atomicsLoad(this.cells, POSIX_LOCK_COUNT);
2501
+ }
2444
2502
  /** A table that replaces another starts past its count, so the generation never repeats. */
2445
2503
  continueUnlinks(previous: SharedFilesystemState): void {
2446
2504
  const floor = previous.unlinkGeneration() + 1;
@@ -25,6 +25,9 @@ export const PAGE_CELLS = ROOT_CELL_BASE + MAX_FILES * FILE_ROOT_WORDS;
25
25
  // Even, so each slot's 64-bit time fields stay 8-byte aligned for a BigUint64Array view.
26
26
  export const SLOT_WORDS = 28;
27
27
  const DIRTY_HEADER_WORDS = 48;
28
+ /** DirtyAdmission owns words 32..71 (20 Float64 slots); words 72..76 hold the 128-bit machine-id + seqlock. */
29
+ const DIRTY_LEDGER_WORDS = 40;
30
+ export const MACHINE_ID_OFFSET = 32 + DIRTY_LEDGER_WORDS;
28
31
  export const HEADER_WORDS = 32 + DIRTY_HEADER_WORDS;
29
32
  export const WATCH_CAPACITY = 128;
30
33
  export const WATCH_RECORD_WORDS = 288;
package/index.ts CHANGED
@@ -60,6 +60,8 @@ export type {
60
60
  SharedFilesystemStatus,
61
61
  SharedFilesystemStateObserver,
62
62
  RemoveCondition,
63
+ StatOptions,
64
+ PathStat,
63
65
  } from "./browser/shared-fs.js";
64
66
 
65
67
  export { getVfsDescriptor, VfsError } from "./fs/vfs.js";
@@ -1,5 +1,5 @@
1
1
  // Bump on every edit. interrupt-transform-pin.test.ts binds this revision to the implementation.
2
- export const INTERRUPT_REWRITER_REVISION = 8;
2
+ export const INTERRUPT_REWRITER_REVISION = 9;
3
3
 
4
4
  /**
5
5
  * Fail-closed core-Wasm interrupt instrumentation. Supported features are MVP,
@@ -51,6 +51,9 @@ const runtimeProcSignatures = new Map<string, FunctionSignature>([
51
51
  ["spawn_error", { params: [0x7f, 0x7f, 0x7f], results: [0x7f] }],
52
52
  ["job_of", { params: [0x7f], results: [0x7f] }],
53
53
  ["pipe", { params: [0x7f], results: [0x7f] }],
54
+ ["pty_open", { params: [0x7f, 0x7f, 0x7f], results: [0x7f] }],
55
+ ["pty_resize", { params: [0x7f, 0x7f, 0x7f], results: [0x7f] }],
56
+ ["pty_size", { params: [0x7f, 0x7f], results: [0x7f] }],
54
57
  ["dup", { params: [0x7f], results: [0x7f] }],
55
58
  ["fd_kind", { params: [0x7f], results: [0x7f] }],
56
59
  ["inherited_fd", { params: [0x7f], results: [0x7f] }],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@waffle-os/runtime",
3
- "version": "0.0.156",
3
+ "version": "0.0.157",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/ShaulLavo/waffle.git",
@@ -685,7 +685,7 @@
685
685
  "size": "bun tooling/runtime-size.ts",
686
686
  "check:nodenext": "tsc -p tsconfig.nodenext.json",
687
687
  "check:dom-consumer": "tsc -p tsconfig.dom-consumer.json",
688
- "lint": "oxlint --deny-warnings --report-unused-disable-directives .",
688
+ "lint": "oxlint --deny-warnings --report-unused-disable-directives . && bun tooling/nested-ternary-baseline.ts",
689
689
  "format": "oxfmt .",
690
690
  "format:check": "oxfmt --check .",
691
691
  "check:tooling": "tsc -p tsconfig.tooling.json",
package/proc/abi.ts CHANGED
@@ -4,6 +4,7 @@ import {
4
4
  arrayAppend,
5
5
  atomicsAdd,
6
6
  atomicsNotify,
7
+ isInstance,
7
8
  isSharedArrayBuffer,
8
9
  DataViewConstructor,
9
10
  Uint8ArrayConstructor,
@@ -40,7 +41,8 @@ import {
40
41
  type AsyncFileOffsetLease,
41
42
  } from "../core/open-file.js";
42
43
  import type { DirectDisabledIOControl, FilesystemCompletion } from "../fs/client.js";
43
- import { PipeController } from "./pipes.js";
44
+ import { PipeController, type PipeEndpoint } from "./pipes.js";
45
+ import { PtyEndpoint, allocatePtyGeometry, validatePtyDimensions } from "./pty.js";
44
46
  import { readOutcome } from "./outcome.js";
45
47
  import { WasiExit } from "../core/wasi.js";
46
48
  import { waitStatus } from "./wait-status.js";
@@ -147,6 +149,8 @@ export interface ProcessABIOptions {
147
149
  pipeCapacity?: number;
148
150
  /** Workers inject broker-owned endpoints; the default is an in-process controller. */
149
151
  createPipe?(): readonly [Stream, Stream];
152
+ /** Workers inject broker-owned PTY endpoints; the default uses in-process pipe controllers. */
153
+ createPty?(cols: number, rows: number): readonly [Stream, Stream];
150
154
  /** One shared readiness sequence. Publishers increment and notify after publishing state. */
151
155
  wake?: Int32Array;
152
156
  /** Synchronous wait hook, primarily for embedders and deterministic tests. poll and blocking wait_job call it. */
@@ -167,9 +171,11 @@ export class ProcessSignalExit extends ExecutionUnwind {
167
171
  }
168
172
 
169
173
  const READ = 1n << 1n,
174
+ FDSTAT_SET_FLAGS = 1n << 3n,
170
175
  WRITE = 1n << 6n,
171
176
  FILESTAT_GET = 1n << 21n,
172
177
  POLL = 1n << 27n;
178
+ const PTY_RIGHTS = READ | WRITE | FILESTAT_GET | POLL | FDSTAT_SET_FLAGS;
173
179
  const FAULT = 21,
174
180
  ISDIR = 31,
175
181
  NOSYS = 52,
@@ -274,6 +280,9 @@ export class ProcessABI {
274
280
  exec: (ptr, length) => this.result(() => this.exec(ptr!, length!)),
275
281
  job_of: (pid) => this.result(() => options.service.jobOf(pid === 0 ? options.pid : pid!)),
276
282
  pipe: (ptr) => this.result(() => this.pipe(ptr!)),
283
+ pty_open: (cols, rows, ptr) => this.result(() => this.ptyOpen(cols!, rows!, ptr!)),
284
+ pty_resize: (fd, cols, rows) => this.result(() => this.ptyResize(fd!, cols!, rows!)),
285
+ pty_size: (fd, ptr) => this.result(() => this.ptySize(fd!, ptr!)),
277
286
  dup: (fd) => options.descriptors.dup(fd! >>> 0),
278
287
  fd_kind: (fd) => options.descriptors.kind(fd! >>> 0),
279
288
  fd_reopen: (
@@ -552,7 +561,7 @@ export class ProcessABI {
552
561
  private pipe(ptr: number): number {
553
562
  // Validate before retaining endpoints or mutating the descriptor namespace.
554
563
  this.span(ptr, 8);
555
- const endpoints = this.options.createPipe?.() ?? this.localPipe();
564
+ const endpoints = this.options.createPipe?.() ?? this.localPipeEndpoints();
556
565
  let read: number | undefined, write: number | undefined;
557
566
  try {
558
567
  read = this.options.descriptors.open(endpoints[0], READ | FILESTAT_GET | POLL, 0n);
@@ -569,17 +578,81 @@ export class ProcessABI {
569
578
  throw error;
570
579
  }
571
580
  }
572
- private localPipe(): readonly [Stream, Stream] {
581
+ private ptyOpen(cols: number, rows: number, ptr: number): number {
582
+ validatePtyDimensions(cols, rows);
583
+ this.span(ptr, 8);
584
+ const endpoints = this.options.createPty?.(cols, rows) ?? this.localPty(cols, rows);
585
+ let master: number | undefined, slave: number | undefined;
586
+ try {
587
+ master = this.options.descriptors.open(endpoints[0], PTY_RIGHTS, 0n);
588
+ slave = this.options.descriptors.open(endpoints[1], PTY_RIGHTS, 0n);
589
+ const output = this.view(ptr, 8);
590
+ dataViewSetUint32(output, 0, master, true);
591
+ dataViewSetUint32(output, 4, slave, true);
592
+ return 0;
593
+ } catch (error) {
594
+ if (master !== undefined) this.options.descriptors.close(master);
595
+ else endpoints[0].close?.();
596
+ if (slave !== undefined) this.options.descriptors.close(slave);
597
+ else endpoints[1].close?.();
598
+ throw error;
599
+ }
600
+ }
601
+ private ptyEndpoint(fd: number): PtyEndpoint {
602
+ const entry = this.options.descriptors.get(fd >>> 0);
603
+ if (!entry) throw new ProcessError(ProcessErrno.BADF, `missing descriptor ${fd}`);
604
+ if (!isInstance(entry.resource, PtyEndpoint))
605
+ throw new ProcessError(ProcessErrno.NOTTY, `descriptor ${fd} is not a pty`);
606
+ return entry.resource;
607
+ }
608
+ private ptyResize(fd: number, cols: number, rows: number): number {
609
+ validatePtyDimensions(cols, rows);
610
+ this.ptyEndpoint(fd).resize(cols, rows);
611
+ return 0;
612
+ }
613
+ private ptySize(fd: number, ptr: number): number {
614
+ this.span(ptr, 12);
615
+ const size = this.ptyEndpoint(fd).size();
616
+ const output = this.view(ptr, 12);
617
+ dataViewSetUint32(output, 0, size.cols, true);
618
+ dataViewSetUint32(output, 4, size.rows, true);
619
+ dataViewSetUint32(output, 8, size.seq, true);
620
+ return 0;
621
+ }
622
+ private localPty(cols: number, rows: number): readonly [PtyEndpoint, PtyEndpoint] {
623
+ const geometry = allocatePtyGeometry(cols, rows);
624
+ const input = this.localPipeEndpoints();
625
+ const slaveIn = input[0];
626
+ const masterOut = input[1];
627
+ let masterIn: PipeEndpoint | undefined;
628
+ let slaveOut: PipeEndpoint | undefined;
629
+ try {
630
+ const output = this.localPipeEndpoints();
631
+ masterIn = output[0];
632
+ slaveOut = output[1];
633
+ return [
634
+ new PtyEndpoint("master", masterIn, masterOut, geometry),
635
+ new PtyEndpoint("slave", slaveIn, slaveOut, geometry),
636
+ ];
637
+ } catch (error) {
638
+ slaveIn.close();
639
+ masterOut.close();
640
+ masterIn?.close();
641
+ slaveOut?.close();
642
+ throw error;
643
+ }
644
+ }
645
+ private localPipeEndpoints(): readonly [PipeEndpoint, PipeEndpoint] {
573
646
  const controller = new PipeController({
574
647
  capacity: this.options.pipeCapacity,
575
648
  wake: this.options.wake,
576
649
  });
577
650
  const read = controller.retain(this.options.pid, "read");
578
- let write: Stream;
651
+ let write: PipeEndpoint;
579
652
  try {
580
653
  write = controller.retain(this.options.pid, "write");
581
654
  } catch (error) {
582
- read.close?.();
655
+ read.close();
583
656
  throw error;
584
657
  }
585
658
  const unregister = this.options.service.registerRevocation?.(this.options.pid, () =>
@@ -596,7 +669,7 @@ export class ProcessABI {
596
669
  if (closed) return;
597
670
  closed = true;
598
671
  try {
599
- if (close) reflectApply(close, endpoint, []);
672
+ reflectApply(close, endpoint, []);
600
673
  } finally {
601
674
  if (--remaining === 0) unregister();
602
675
  }
package/proc/errors.ts CHANGED
@@ -16,6 +16,7 @@ export const ProcessErrno = objectFreeze({
16
16
  INVAL: 28,
17
17
  NOMEM: 48,
18
18
  NOTSUP: 58,
19
+ NOTTY: 59,
19
20
  PERM: 63,
20
21
  SRCH: 71,
21
22
  });
@@ -1,6 +1,11 @@
1
1
  import { isInstance, isSharedArrayBuffer } from "./intrinsics.ts";
2
2
  import { OpenDescription, type Descriptor, type Resource } from "../core/descriptors.js";
3
- import { shareFileResource } from "../core/open-file.js";
3
+ import {
4
+ readSharedOfdBuffer,
5
+ retainSharedOfdTransfer,
6
+ shareDirectoryOfd,
7
+ shareFileResource,
8
+ } from "../core/open-file.js";
4
9
  import { FilesystemClient } from "../fs/client.js";
5
10
  import {
6
11
  releaseFilesystemReservation,
@@ -14,6 +19,7 @@ export interface FilesystemDescriptorToken {
14
19
  resource: "file" | "directory";
15
20
  reservation: FilesystemReservation;
16
21
  offset?: SharedArrayBuffer;
22
+ ofd?: SharedArrayBuffer;
17
23
  }
18
24
  export function isFilesystemDescriptorToken(token: unknown): token is FilesystemDescriptorToken {
19
25
  return (
@@ -21,6 +27,19 @@ export function isFilesystemDescriptorToken(token: unknown): token is Filesystem
21
27
  );
22
28
  }
23
29
 
30
+ function tokenOfdBuffer(token: FilesystemDescriptorToken): SharedArrayBuffer | undefined {
31
+ const candidate = token.resource === "file" ? token.offset : token.ofd;
32
+ return isSharedArrayBuffer(candidate) ? candidate : undefined;
33
+ }
34
+
35
+ function releaseTokenOfd(client: FilesystemClient, token: FilesystemDescriptorToken): void {
36
+ const buffer = tokenOfdBuffer(token);
37
+ if (!buffer) return;
38
+ const ofd = readSharedOfdBuffer(buffer);
39
+ if (!ofd?.locked) return;
40
+ client.locks.releaseOfd(token.reservation.handle, ofd.id, ofd.pendingTransfers > 0);
41
+ }
42
+
24
43
  /** Controller imports need only the identity and a live controller sweep notifier; guests pass
25
44
  * their actual client. Both import the same reference, whose release is shared and idempotent.
26
45
  * An undefined identity supplies discard-only cleanup, independent of admission metadata. */
@@ -34,12 +53,11 @@ export function createFilesystemDescriptorCodec(
34
53
  const discard = (token: unknown) => {
35
54
  if (!isFilesystemDescriptorToken(token))
36
55
  throw new TypeError("not a filesystem descriptor token");
37
- if (client && token.reservation.targetOwner === client.connection.owner)
38
- client.releaseReservation(token.reservation);
39
- else {
40
- releaseFilesystemReservation(token.reservation);
41
- (sweep ?? (() => client?.sweep()))();
42
- }
56
+ const won = releaseFilesystemReservation(token.reservation);
57
+ const localOwner = client && token.reservation.targetOwner === client.connection.owner;
58
+ if (won && localOwner) releaseTokenOfd(client, token);
59
+ if (localOwner) client.finishReleasedReservation(token.reservation, won);
60
+ else if (won) (sweep ?? (() => client?.sweep()))();
43
61
  };
44
62
  return {
45
63
  export(descriptor: Descriptor): FilesystemDescriptorToken {
@@ -51,11 +69,20 @@ export function createFilesystemDescriptorCodec(
51
69
  // Promote before reserving: a failed offset conversion cannot strand a child pin.
52
70
  const offset =
53
71
  resource.kind === "file" ? shareFileResource(resource, client.connection) : undefined;
72
+ const dirOfd =
73
+ resource.kind === "directory" ? shareDirectoryOfd(resource, client.connection) : undefined;
74
+ const reservation = client.reserve(resource.handle, target);
75
+ const ofd = offset ?? dirOfd;
76
+ if (ofd) {
77
+ reservation.ofd = ofd;
78
+ retainSharedOfdTransfer(ofd);
79
+ }
54
80
  return {
55
81
  kind: "filesystem",
56
82
  resource: resource.kind,
57
- reservation: client.reserve(resource.handle, target),
83
+ reservation,
58
84
  offset,
85
+ ...(dirOfd ? { ofd: dirOfd } : {}),
59
86
  };
60
87
  },
61
88
  import(token: unknown): OpenDescription {
@@ -70,7 +97,10 @@ export function createFilesystemDescriptorCodec(
70
97
  if (!isSharedArrayBuffer(token.offset)) throw new TypeError("file offset is missing");
71
98
  resource = { kind: "file", handle, offset: 0, append: false };
72
99
  shareFileResource(resource, identity, token.offset);
73
- } else resource = { kind: "directory", handle };
100
+ } else {
101
+ resource = { kind: "directory", handle };
102
+ if (isSharedArrayBuffer(token.ofd)) shareDirectoryOfd(resource, identity, token.ofd);
103
+ }
74
104
  client?.adopt(token.reservation);
75
105
  return new OpenDescription(resource, () => discard(token));
76
106
  },
package/proc/index.ts CHANGED
@@ -100,13 +100,24 @@ export {
100
100
  WorkerPipeBroker,
101
101
  createWorkerPipeCodec,
102
102
  isWorkerPipeDescriptorToken,
103
+ isWorkerPtyDescriptorToken,
103
104
  } from "./worker-pipes.js";
104
105
  export type {
105
106
  WorkerPipeDescriptorToken,
107
+ WorkerPtyDescriptorToken,
106
108
  WorkerPipeCodecOptions,
107
109
  WorkerPipeHostOptions,
108
110
  WorkerPipeBrokerOptions,
109
111
  } from "./worker-pipes.js";
112
+ export {
113
+ PtyEndpoint,
114
+ PTY_GEOMETRY_BYTES,
115
+ MAX_PTY_DIMENSION,
116
+ isValidPtyDimension,
117
+ allocatePtyGeometry,
118
+ attachPtyEndpoint,
119
+ } from "./pty.js";
120
+ export type { PtyRole, PtySize, PtyEndpointHandle } from "./pty.js";
110
121
  export { ProcessABI, ProcessSignalExit } from "./abi.js";
111
122
  export type {
112
123
  PollSubscription,
package/proc/pty.ts ADDED
@@ -0,0 +1,227 @@
1
+ import type { Readiness, Stream } from "../core/descriptors.js";
2
+ import { allocateSharedControl } from "../memory/control.ts";
3
+ import { ProcessErrno, ProcessError } from "./errors.ts";
4
+ import {
5
+ BigInt64ArrayConstructor,
6
+ Int32ArrayConstructor,
7
+ atomicsAdd,
8
+ atomicsCompareExchange,
9
+ atomicsLoad,
10
+ atomicsNotify,
11
+ atomicsStore,
12
+ isSharedArrayBuffer,
13
+ typedArrayLength,
14
+ } from "./intrinsics.ts";
15
+
16
+ const bigintConstructor = BigInt;
17
+ const bigIntAsIntN = BigInt.asIntN;
18
+ const numberConstructor = Number;
19
+ import {
20
+ PipeEndpoint,
21
+ attachPipeEndpoint,
22
+ type PipeEndpointHandle,
23
+ type PipeOptions,
24
+ } from "./pipes.js";
25
+
26
+ export type PtyRole = "master" | "slave";
27
+
28
+ export interface PtySize {
29
+ readonly cols: number;
30
+ readonly rows: number;
31
+ readonly seq: number;
32
+ }
33
+
34
+ export interface PtyEndpointHandle {
35
+ readonly role: PtyRole;
36
+ readonly read: PipeEndpointHandle;
37
+ readonly write: PipeEndpointHandle;
38
+ readonly geometry: SharedArrayBuffer;
39
+ }
40
+
41
+ /** Two BigUint64 words: [word0 = (resizeSeq << 32) | (rows << 16) | cols, word1 = reserved]. */
42
+ export const PTY_GEOMETRY_BYTES = 16;
43
+ export const MAX_PTY_DIMENSION = 0xffff;
44
+
45
+ export function isValidPtyDimension(value: number): boolean {
46
+ return Number.isInteger(value) && value >= 1 && value <= MAX_PTY_DIMENSION;
47
+ }
48
+
49
+ export function validatePtyDimensions(cols: number, rows: number): void {
50
+ if (!isValidPtyDimension(cols) || !isValidPtyDimension(rows))
51
+ throw new ProcessError(ProcessErrno.INVAL, "invalid pty dimensions");
52
+ }
53
+
54
+ function isValidPtyGeometryBuffer(buffer: unknown): buffer is SharedArrayBuffer {
55
+ if (!isSharedArrayBuffer(buffer)) return false;
56
+ return typedArrayLength(new Int32ArrayConstructor(buffer)) >= 4;
57
+ }
58
+
59
+ function packPtySize(cols: number, rows: number): number {
60
+ return (((rows & 0xffff) << 16) | (cols & 0xffff)) >>> 0;
61
+ }
62
+
63
+ function packGeometryWord(cols: number, rows: number, seq: number): bigint {
64
+ return bigIntAsIntN(
65
+ 64,
66
+ (bigintConstructor(seq >>> 0) << 32n) | bigintConstructor(packPtySize(cols, rows)),
67
+ );
68
+ }
69
+
70
+ export function allocatePtyGeometry(
71
+ cols: number,
72
+ rows: number,
73
+ allocateShared?: (bytes: number) => SharedArrayBuffer,
74
+ ): SharedArrayBuffer {
75
+ validatePtyDimensions(cols, rows);
76
+ const buffer = allocateShared
77
+ ? allocateShared(PTY_GEOMETRY_BYTES)
78
+ : allocateSharedControl(PTY_GEOMETRY_BYTES);
79
+ const words = new BigInt64ArrayConstructor(buffer, 0, 2);
80
+ atomicsStore(words, 0, packGeometryWord(cols, rows, 0));
81
+ atomicsStore(words, 1, 0n);
82
+ return buffer;
83
+ }
84
+
85
+ /** Bidirectional guest-allocatable PTY endpoint backed by two shared pipe rings and one
86
+ * shared geometry control block. Slave endpoints report `kind: "terminal"` (TTY), while
87
+ * master endpoints report `kind: "pipe"` (controller stream). */
88
+ export class PtyEndpoint implements Stream {
89
+ readonly kind: "pipe" | "terminal";
90
+ readonly notification: Int32Array;
91
+ private readonly geometry: BigInt64Array<SharedArrayBuffer>;
92
+ private closed = false;
93
+ constructor(
94
+ readonly role: PtyRole,
95
+ private readonly readEnd: PipeEndpoint,
96
+ private readonly writeEnd: PipeEndpoint,
97
+ private readonly geometryBuffer: SharedArrayBuffer,
98
+ ) {
99
+ if (!isValidPtyGeometryBuffer(geometryBuffer))
100
+ throw new TypeError("invalid pty geometry buffer");
101
+ this.kind = role === "slave" ? "terminal" : "pipe";
102
+ this.notification = readEnd.notification;
103
+ this.geometry = new BigInt64ArrayConstructor(geometryBuffer, 0, 2);
104
+ }
105
+ get pid(): number {
106
+ return this.readEnd.pid;
107
+ }
108
+ get live(): boolean {
109
+ return !this.closed && this.readEnd.live && this.writeEnd.live;
110
+ }
111
+ get fdflags(): number {
112
+ return this.readEnd.fdflags;
113
+ }
114
+ set fdflags(value: number) {
115
+ this.readEnd.fdflags = value;
116
+ this.writeEnd.fdflags = value;
117
+ }
118
+ read(chunks: readonly Uint8Array[]): number {
119
+ return this.readEnd.read(chunks);
120
+ }
121
+ tryRead(chunks: readonly Uint8Array[]): number {
122
+ return this.readEnd.tryRead(chunks);
123
+ }
124
+ write(chunks: readonly Uint8Array[]): number {
125
+ return this.writeEnd.write(chunks);
126
+ }
127
+ tryWrite(chunks: readonly Uint8Array[]): number {
128
+ return this.writeEnd.tryWrite(chunks);
129
+ }
130
+ readiness(): Readiness {
131
+ const readState = this.readEnd.readiness();
132
+ const writeState = this.writeEnd.readiness();
133
+ return {
134
+ readable: readState.readable,
135
+ writable: writeState.writable,
136
+ hangup: readState.hangup || writeState.hangup,
137
+ nbytes: readState.nbytes,
138
+ };
139
+ }
140
+ size(): PtySize {
141
+ const word = atomicsLoad(this.geometry, 0);
142
+ const packed = numberConstructor(word & 0xffffffffn);
143
+ const seq = numberConstructor((word >> 32n) & 0xffffffffn);
144
+ return {
145
+ cols: packed & 0xffff,
146
+ rows: (packed >>> 16) & 0xffff,
147
+ seq,
148
+ };
149
+ }
150
+ resize(cols: number, rows: number): void {
151
+ validatePtyDimensions(cols, rows);
152
+ const dims = bigintConstructor(packPtySize(cols, rows));
153
+ for (;;) {
154
+ const prev = atomicsLoad(this.geometry, 0);
155
+ const nextSeq = (((prev >> 32n) & 0xffffffffn) + 1n) & 0xffffffffn;
156
+ const next = bigIntAsIntN(64, (nextSeq << 32n) | dims);
157
+ if (atomicsCompareExchange(this.geometry, 0, prev, next) === prev) break;
158
+ }
159
+ atomicsAdd(this.notification, 0, 1);
160
+ atomicsNotify(this.notification, 0);
161
+ }
162
+ handle(): PtyEndpointHandle {
163
+ return {
164
+ role: this.role,
165
+ read: this.readEnd.handle(),
166
+ write: this.writeEnd.handle(),
167
+ geometry: this.geometryBuffer,
168
+ };
169
+ }
170
+ forProcess(pid: number): PtyEndpoint {
171
+ if (!this.live) throw new Error("pty endpoint is closed");
172
+ if (pid === this.pid) return this;
173
+ const nextRead = this.readEnd.forProcess(pid);
174
+ try {
175
+ const nextWrite = this.writeEnd.forProcess(pid);
176
+ return new PtyEndpoint(this.role, nextRead, nextWrite, this.geometryBuffer);
177
+ } catch (error) {
178
+ nextRead.close();
179
+ throw error;
180
+ }
181
+ }
182
+ retainSuccessor(): PtyEndpoint {
183
+ if (!this.live) throw new Error("pty endpoint is closed");
184
+ const nextRead = this.readEnd.retainSuccessor();
185
+ try {
186
+ const nextWrite = this.writeEnd.retainSuccessor();
187
+ return new PtyEndpoint(this.role, nextRead, nextWrite, this.geometryBuffer);
188
+ } catch (error) {
189
+ nextRead.close();
190
+ throw error;
191
+ }
192
+ }
193
+ revoke(): void {
194
+ try {
195
+ this.readEnd.revoke();
196
+ } finally {
197
+ this.writeEnd.revoke();
198
+ }
199
+ }
200
+ close(): void {
201
+ if (this.closed) return;
202
+ this.closed = true;
203
+ try {
204
+ this.readEnd.close();
205
+ } finally {
206
+ this.writeEnd.close();
207
+ }
208
+ }
209
+ }
210
+
211
+ export function attachPtyEndpoint(
212
+ handle: PtyEndpointHandle,
213
+ options?: Pick<PipeOptions, "allocateShared">,
214
+ ): PtyEndpoint {
215
+ if (handle.role !== "master" && handle.role !== "slave")
216
+ throw new TypeError("invalid pty endpoint role");
217
+ if (!isValidPtyGeometryBuffer(handle.geometry))
218
+ throw new TypeError("invalid pty geometry buffer");
219
+ const readEnd = attachPipeEndpoint(handle.read, options);
220
+ try {
221
+ const writeEnd = attachPipeEndpoint(handle.write, options);
222
+ return new PtyEndpoint(handle.role, readEnd, writeEnd, handle.geometry);
223
+ } catch (error) {
224
+ readEnd.close();
225
+ throw error;
226
+ }
227
+ }