@secure-exec/browser 0.0.0-agentos-dylib-base.edaa4a4

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 (66) hide show
  1. package/README.md +6 -0
  2. package/dist/child-process-bridge.d.ts +25 -0
  3. package/dist/child-process-bridge.js +50 -0
  4. package/dist/converged-base64.d.ts +2 -0
  5. package/dist/converged-base64.js +41 -0
  6. package/dist/converged-dgram-bridge.d.ts +11 -0
  7. package/dist/converged-dgram-bridge.js +147 -0
  8. package/dist/converged-driver-setup.d.ts +22 -0
  9. package/dist/converged-driver-setup.js +72 -0
  10. package/dist/converged-execution-host-bridge.d.ts +7 -0
  11. package/dist/converged-execution-host-bridge.js +85 -0
  12. package/dist/converged-executor-session.d.ts +60 -0
  13. package/dist/converged-executor-session.js +127 -0
  14. package/dist/converged-fs-bridge.d.ts +42 -0
  15. package/dist/converged-fs-bridge.js +245 -0
  16. package/dist/converged-module-servicer.d.ts +8 -0
  17. package/dist/converged-module-servicer.js +79 -0
  18. package/dist/converged-net-bridge.d.ts +28 -0
  19. package/dist/converged-net-bridge.js +155 -0
  20. package/dist/converged-permissions.d.ts +9 -0
  21. package/dist/converged-permissions.js +46 -0
  22. package/dist/converged-sync-bridge-handler.d.ts +47 -0
  23. package/dist/converged-sync-bridge-handler.js +140 -0
  24. package/dist/converged-sync-bridge-router.d.ts +33 -0
  25. package/dist/converged-sync-bridge-router.js +41 -0
  26. package/dist/driver.d.ts +91 -0
  27. package/dist/driver.js +386 -0
  28. package/dist/encoding.d.ts +4 -0
  29. package/dist/encoding.js +102 -0
  30. package/dist/generated/util-polyfill.d.ts +1 -0
  31. package/dist/generated/util-polyfill.js +2 -0
  32. package/dist/index.d.ts +9 -0
  33. package/dist/index.js +5 -0
  34. package/dist/kernel-backed-filesystem.d.ts +33 -0
  35. package/dist/kernel-backed-filesystem.js +205 -0
  36. package/dist/os-filesystem.d.ts +47 -0
  37. package/dist/os-filesystem.js +409 -0
  38. package/dist/permission-validation.d.ts +15 -0
  39. package/dist/permission-validation.js +62 -0
  40. package/dist/root-filesystem-from-vfs.d.ts +13 -0
  41. package/dist/root-filesystem-from-vfs.js +95 -0
  42. package/dist/runtime-driver.d.ts +66 -0
  43. package/dist/runtime-driver.js +611 -0
  44. package/dist/runtime.d.ts +248 -0
  45. package/dist/runtime.js +2296 -0
  46. package/dist/sidecar-wasm-module.d.ts +62 -0
  47. package/dist/sidecar-wasm-module.js +28 -0
  48. package/dist/sidecar-worker-protocol.d.ts +14 -0
  49. package/dist/sidecar-worker-protocol.js +9 -0
  50. package/dist/sidecar-worker.d.ts +19 -0
  51. package/dist/sidecar-worker.js +63 -0
  52. package/dist/signals.d.ts +13 -0
  53. package/dist/signals.js +89 -0
  54. package/dist/sync-bridge.d.ts +50 -0
  55. package/dist/sync-bridge.js +93 -0
  56. package/dist/wasi-polyfill.d.ts +1 -0
  57. package/dist/wasi-polyfill.js +2154 -0
  58. package/dist/worker-adapter.d.ts +21 -0
  59. package/dist/worker-adapter.js +41 -0
  60. package/dist/worker-protocol.d.ts +104 -0
  61. package/dist/worker-protocol.js +1 -0
  62. package/dist/worker-sidecar-client.d.ts +71 -0
  63. package/dist/worker-sidecar-client.js +152 -0
  64. package/dist/worker.d.ts +1 -0
  65. package/dist/worker.js +2125 -0
  66. package/package.json +111 -0
@@ -0,0 +1,62 @@
1
+ import type { BrowserSidecarWasmModuleFactory } from "./sidecar-worker.js";
2
+ export interface BrowserSidecarWasmBinding {
3
+ readonly sidecarId?: string;
4
+ pushFrame(frame: Uint8Array): Uint8Array | null;
5
+ pollEvent?(): Uint8Array | null;
6
+ free?(): void;
7
+ }
8
+ export interface BrowserSidecarWasmBindingConstructor {
9
+ new (hostBridge?: BrowserSidecarWasmHostBridge): BrowserSidecarWasmBinding;
10
+ }
11
+ export interface BrowserSidecarWasmBindingModule {
12
+ default?: (input?: unknown) => unknown | Promise<unknown>;
13
+ BrowserSidecarWasm: BrowserSidecarWasmBindingConstructor;
14
+ }
15
+ export type BrowserSidecarWasmBindingLoader = () => BrowserSidecarWasmBindingModule | Promise<BrowserSidecarWasmBindingModule>;
16
+ export type BrowserSidecarWasmJsonResponse = string | number | boolean | null | BrowserSidecarWasmJsonResponse[] | {
17
+ [key: string]: BrowserSidecarWasmJsonResponse;
18
+ };
19
+ export type BrowserSidecarWasmBridgeMethod = (requestJson: string) => BrowserSidecarWasmJsonResponse | string | Uint8Array | null | undefined;
20
+ export interface BrowserSidecarWasmHostBridge {
21
+ readFile?: BrowserSidecarWasmBridgeMethod;
22
+ writeFile?: BrowserSidecarWasmBridgeMethod;
23
+ stat?: BrowserSidecarWasmBridgeMethod;
24
+ lstat?: BrowserSidecarWasmBridgeMethod;
25
+ readDir?: BrowserSidecarWasmBridgeMethod;
26
+ createDir?: BrowserSidecarWasmBridgeMethod;
27
+ removeFile?: BrowserSidecarWasmBridgeMethod;
28
+ removeDir?: BrowserSidecarWasmBridgeMethod;
29
+ rename?: BrowserSidecarWasmBridgeMethod;
30
+ symlink?: BrowserSidecarWasmBridgeMethod;
31
+ readLink?: BrowserSidecarWasmBridgeMethod;
32
+ chmod?: BrowserSidecarWasmBridgeMethod;
33
+ truncate?: BrowserSidecarWasmBridgeMethod;
34
+ exists?: BrowserSidecarWasmBridgeMethod;
35
+ checkFilesystemAccess?: BrowserSidecarWasmBridgeMethod;
36
+ checkNetworkAccess?: BrowserSidecarWasmBridgeMethod;
37
+ checkCommandExecution?: BrowserSidecarWasmBridgeMethod;
38
+ checkEnvironmentAccess?: BrowserSidecarWasmBridgeMethod;
39
+ loadFilesystemState?: BrowserSidecarWasmBridgeMethod;
40
+ flushFilesystemState?: BrowserSidecarWasmBridgeMethod;
41
+ wallClock?: BrowserSidecarWasmBridgeMethod;
42
+ monotonicClock?: BrowserSidecarWasmBridgeMethod;
43
+ scheduleTimer?: BrowserSidecarWasmBridgeMethod;
44
+ fillRandomBytes?: BrowserSidecarWasmBridgeMethod;
45
+ emitStructuredEvent?: BrowserSidecarWasmBridgeMethod;
46
+ emitDiagnostic?: BrowserSidecarWasmBridgeMethod;
47
+ emitLog?: BrowserSidecarWasmBridgeMethod;
48
+ emitLifecycle?: BrowserSidecarWasmBridgeMethod;
49
+ createJavascriptContext?: BrowserSidecarWasmBridgeMethod;
50
+ createWasmContext?: BrowserSidecarWasmBridgeMethod;
51
+ startExecution?: BrowserSidecarWasmBridgeMethod;
52
+ writeExecutionStdin?: BrowserSidecarWasmBridgeMethod;
53
+ closeExecutionStdin?: BrowserSidecarWasmBridgeMethod;
54
+ killExecution?: BrowserSidecarWasmBridgeMethod;
55
+ pollExecutionEvent?: BrowserSidecarWasmBridgeMethod;
56
+ createWorker?: BrowserSidecarWasmBridgeMethod;
57
+ terminateWorker?: BrowserSidecarWasmBridgeMethod;
58
+ }
59
+ export declare function createBrowserSidecarWasmModuleFactory(loadBinding: BrowserSidecarWasmBindingLoader, options?: {
60
+ hostBridge?: BrowserSidecarWasmHostBridge;
61
+ initInput?: unknown;
62
+ }): BrowserSidecarWasmModuleFactory;
@@ -0,0 +1,28 @@
1
+ export function createBrowserSidecarWasmModuleFactory(loadBinding, options = {}) {
2
+ return async (_host) => {
3
+ const bindingModule = await loadBinding();
4
+ await bindingModule.default?.(options.initInput);
5
+ const sidecar = new bindingModule.BrowserSidecarWasm(options.hostBridge);
6
+ return {
7
+ sidecarId: sidecar.sidecarId,
8
+ pushFrame(frame) {
9
+ return normalizeOptionalFrame(sidecar.pushFrame(frame));
10
+ },
11
+ pollEvent() {
12
+ return normalizeOptionalFrame(sidecar.pollEvent?.() ?? null);
13
+ },
14
+ dispose() {
15
+ sidecar.free?.();
16
+ },
17
+ };
18
+ };
19
+ }
20
+ function normalizeOptionalFrame(frame) {
21
+ if (frame === null) {
22
+ return null;
23
+ }
24
+ if (frame instanceof Uint8Array) {
25
+ return frame;
26
+ }
27
+ return new Uint8Array(frame);
28
+ }
@@ -0,0 +1,14 @@
1
+ export declare const BROWSER_SIDECAR_READY_MESSAGE = "secure-exec-sidecar:ready";
2
+ export declare const BROWSER_SIDECAR_ERROR_MESSAGE = "secure-exec-sidecar:error";
3
+ export declare const BROWSER_SIDECAR_READY_TIMEOUT_MS = 10000;
4
+ export interface BrowserSidecarReadyMessage {
5
+ type: typeof BROWSER_SIDECAR_READY_MESSAGE;
6
+ sidecarId?: string;
7
+ }
8
+ export interface BrowserSidecarErrorMessage {
9
+ type: typeof BROWSER_SIDECAR_ERROR_MESSAGE;
10
+ message: string;
11
+ stack?: string;
12
+ }
13
+ export type BrowserSidecarControlMessage = BrowserSidecarReadyMessage | BrowserSidecarErrorMessage;
14
+ export declare function isBrowserSidecarControlMessage(value: unknown): value is BrowserSidecarControlMessage;
@@ -0,0 +1,9 @@
1
+ export const BROWSER_SIDECAR_READY_MESSAGE = "secure-exec-sidecar:ready";
2
+ export const BROWSER_SIDECAR_ERROR_MESSAGE = "secure-exec-sidecar:error";
3
+ export const BROWSER_SIDECAR_READY_TIMEOUT_MS = 10_000;
4
+ export function isBrowserSidecarControlMessage(value) {
5
+ return (typeof value === "object" &&
6
+ value !== null &&
7
+ (value.type === BROWSER_SIDECAR_READY_MESSAGE ||
8
+ value.type === BROWSER_SIDECAR_ERROR_MESSAGE));
9
+ }
@@ -0,0 +1,19 @@
1
+ export interface BrowserSidecarWasmModule {
2
+ sidecarId?: string;
3
+ init?(): void | Promise<void>;
4
+ pushFrame(frame: Uint8Array): Uint8Array | null | Promise<Uint8Array | null>;
5
+ pollEvent?(): Uint8Array | null | Promise<Uint8Array | null>;
6
+ dispose?(): void | Promise<void>;
7
+ }
8
+ export interface BrowserSidecarWasmHost {
9
+ postFrame(frame: Uint8Array): void;
10
+ }
11
+ export type BrowserSidecarWasmModuleFactory = (host: BrowserSidecarWasmHost) => BrowserSidecarWasmModule | Promise<BrowserSidecarWasmModule>;
12
+ export interface BrowserSidecarWorkerScope {
13
+ postMessage(message: unknown, transfer?: readonly unknown[]): void;
14
+ addEventListener(type: "message", listener: (event: {
15
+ data: unknown;
16
+ }) => void): void;
17
+ __secureExecCreateBrowserSidecarWasmModule?: BrowserSidecarWasmModuleFactory | undefined;
18
+ }
19
+ export declare function installBrowserSidecarWorker(scope: BrowserSidecarWorkerScope, factory?: BrowserSidecarWasmModuleFactory | undefined): void;
@@ -0,0 +1,63 @@
1
+ import { BROWSER_SIDECAR_ERROR_MESSAGE, BROWSER_SIDECAR_READY_MESSAGE, } from "./sidecar-worker-protocol.js";
2
+ export function installBrowserSidecarWorker(scope, factory = scope.__secureExecCreateBrowserSidecarWasmModule) {
3
+ let module = null;
4
+ let booted = false;
5
+ const postFrame = (frame) => {
6
+ scope.postMessage(frame, [frame.buffer]);
7
+ };
8
+ const postError = (error) => {
9
+ const normalized = error instanceof Error ? error : new Error(String(error));
10
+ scope.postMessage({
11
+ type: BROWSER_SIDECAR_ERROR_MESSAGE,
12
+ message: normalized.message,
13
+ stack: normalized.stack,
14
+ });
15
+ };
16
+ const drainEvents = async () => {
17
+ if (!module?.pollEvent) {
18
+ return;
19
+ }
20
+ for (;;) {
21
+ const event = await module.pollEvent();
22
+ if (!event) {
23
+ return;
24
+ }
25
+ postFrame(event);
26
+ }
27
+ };
28
+ scope.addEventListener("message", (event) => {
29
+ const frame = event.data;
30
+ if (!(frame instanceof Uint8Array)) {
31
+ return;
32
+ }
33
+ void (async () => {
34
+ if (!booted || !module) {
35
+ throw new Error("browser sidecar Worker received a frame before ready");
36
+ }
37
+ const response = await module.pushFrame(frame);
38
+ if (response) {
39
+ postFrame(response);
40
+ }
41
+ await drainEvents();
42
+ })().catch(postError);
43
+ });
44
+ void (async () => {
45
+ if (!factory) {
46
+ throw new Error("browser sidecar WASM module loader is not installed");
47
+ }
48
+ module = await factory({ postFrame });
49
+ await module.init?.();
50
+ booted = true;
51
+ scope.postMessage({
52
+ type: BROWSER_SIDECAR_READY_MESSAGE,
53
+ sidecarId: module.sidecarId,
54
+ });
55
+ await drainEvents();
56
+ })().catch(postError);
57
+ }
58
+ const maybeWorkerScope = globalThis;
59
+ if (typeof maybeWorkerScope.document === "undefined" &&
60
+ typeof maybeWorkerScope.addEventListener === "function" &&
61
+ typeof maybeWorkerScope.postMessage === "function") {
62
+ installBrowserSidecarWorker(maybeWorkerScope);
63
+ }
@@ -0,0 +1,13 @@
1
+ export declare const PROCESS_SIGNAL_NUMBERS: Record<string, number>;
2
+ export type BrowserSignalRegistration = {
3
+ action: "default" | "ignore" | "user";
4
+ mask: number[];
5
+ flags: number;
6
+ };
7
+ export declare function signalNumberForEvent(event: string): number | null;
8
+ export declare function defaultSignalExitCode(signal: number): number | null;
9
+ export declare function parseProcessSignalStateArgs(args: unknown[]): {
10
+ signal: number;
11
+ registration: BrowserSignalRegistration;
12
+ };
13
+ export declare function applyProcessSignalStateUpdate(states: Map<string, Map<number, BrowserSignalRegistration>>, executionId: string, signal: number, registration: BrowserSignalRegistration): void;
@@ -0,0 +1,89 @@
1
+ export const PROCESS_SIGNAL_NUMBERS = {
2
+ SIGHUP: 1,
3
+ SIGINT: 2,
4
+ SIGQUIT: 3,
5
+ SIGILL: 4,
6
+ SIGTRAP: 5,
7
+ SIGABRT: 6,
8
+ SIGIOT: 6,
9
+ SIGBUS: 7,
10
+ SIGFPE: 8,
11
+ SIGKILL: 9,
12
+ SIGUSR1: 10,
13
+ SIGSEGV: 11,
14
+ SIGUSR2: 12,
15
+ SIGPIPE: 13,
16
+ SIGALRM: 14,
17
+ SIGTERM: 15,
18
+ SIGSTKFLT: 16,
19
+ SIGCHLD: 17,
20
+ SIGCONT: 18,
21
+ SIGSTOP: 19,
22
+ SIGTSTP: 20,
23
+ SIGTTIN: 21,
24
+ SIGTTOU: 22,
25
+ SIGURG: 23,
26
+ SIGXCPU: 24,
27
+ SIGXFSZ: 25,
28
+ SIGVTALRM: 26,
29
+ SIGPROF: 27,
30
+ SIGWINCH: 28,
31
+ SIGIO: 29,
32
+ SIGPOLL: 29,
33
+ SIGPWR: 30,
34
+ SIGSYS: 31,
35
+ };
36
+ const VALID_PROCESS_SIGNALS = new Set([0, ...Object.values(PROCESS_SIGNAL_NUMBERS)]);
37
+ export function signalNumberForEvent(event) {
38
+ const upper = event.trim().toUpperCase();
39
+ const signalName = upper.startsWith("SIG") ? upper : `SIG${upper}`;
40
+ return PROCESS_SIGNAL_NUMBERS[signalName] ?? null;
41
+ }
42
+ export function defaultSignalExitCode(signal) {
43
+ return signal > 0 ? 128 + signal : null;
44
+ }
45
+ export function parseProcessSignalStateArgs(args) {
46
+ const signal = parseSignalNumber(args[0], "process.signal_state signal");
47
+ const action = String(args[1] ?? "default").toLowerCase();
48
+ if (action !== "default" && action !== "ignore" && action !== "user") {
49
+ throw new Error(`unsupported process.signal_state action ${action}`);
50
+ }
51
+ const maskValue = typeof args[2] === "string" ? JSON.parse(args[2]) : args[2];
52
+ if (!Array.isArray(maskValue)) {
53
+ throw new Error("process.signal_state mask must be an array");
54
+ }
55
+ const mask = maskValue.map((value) => parseSignalNumber(value, "process.signal_state mask entries"));
56
+ const flags = Number(args[3] ?? 0);
57
+ if (!Number.isInteger(flags) || flags < 0) {
58
+ throw new Error("process.signal_state flags must be a non-negative integer");
59
+ }
60
+ return {
61
+ signal,
62
+ registration: { action, mask, flags },
63
+ };
64
+ }
65
+ export function applyProcessSignalStateUpdate(states, executionId, signal, registration) {
66
+ if (registration.action === "default" &&
67
+ registration.mask.length === 0 &&
68
+ registration.flags === 0) {
69
+ const handlers = states.get(executionId);
70
+ handlers?.delete(signal);
71
+ if (handlers?.size === 0) {
72
+ states.delete(executionId);
73
+ }
74
+ return;
75
+ }
76
+ let handlers = states.get(executionId);
77
+ if (!handlers) {
78
+ handlers = new Map();
79
+ states.set(executionId, handlers);
80
+ }
81
+ handlers.set(signal, registration);
82
+ }
83
+ function parseSignalNumber(value, label) {
84
+ const signal = Number(value);
85
+ if (!Number.isInteger(signal) || !VALID_PROCESS_SIGNALS.has(signal)) {
86
+ throw new Error(`${label} must be a valid POSIX signal`);
87
+ }
88
+ return signal;
89
+ }
@@ -0,0 +1,50 @@
1
+ export declare const SYNC_BRIDGE_SIGNAL_STATE_INDEX = 0;
2
+ export declare const SYNC_BRIDGE_SIGNAL_STATUS_INDEX = 1;
3
+ export declare const SYNC_BRIDGE_SIGNAL_KIND_INDEX = 2;
4
+ export declare const SYNC_BRIDGE_SIGNAL_LENGTH_INDEX = 3;
5
+ export declare const SYNC_BRIDGE_SIGNAL_STATE_IDLE = 0;
6
+ export declare const SYNC_BRIDGE_SIGNAL_STATE_READY = 1;
7
+ export declare const SYNC_BRIDGE_STATUS_OK = 0;
8
+ export declare const SYNC_BRIDGE_STATUS_ERROR = 1;
9
+ export declare const SYNC_BRIDGE_KIND_NONE = 0;
10
+ export declare const SYNC_BRIDGE_KIND_TEXT = 1;
11
+ export declare const SYNC_BRIDGE_KIND_BINARY = 2;
12
+ export declare const SYNC_BRIDGE_KIND_JSON = 3;
13
+ export declare const SYNC_BRIDGE_SIGNAL_BYTES: number;
14
+ export declare const SYNC_BRIDGE_DEFAULT_WAIT_TIMEOUT_MS = 30000;
15
+ export declare const SYNC_BRIDGE_DEFAULT_DATA_BYTES: number;
16
+ export declare const SYNC_BRIDGE_MIN_DATA_BYTES: number;
17
+ export declare const SYNC_BRIDGE_PAYLOAD_LIMIT_ERROR_CODE = "ERR_SANDBOX_PAYLOAD_TOO_LARGE";
18
+ export declare const BROWSER_SYNC_BRIDGE_OPERATIONS: readonly ["fs.readFile", "fs.writeFile", "fs.readFileBinary", "fs.writeFileBinary", "fs.readDir", "fs.createDir", "fs.mkdir", "fs.rmdir", "fs.exists", "fs.stat", "fs.lstat", "fs.unlink", "fs.rename", "fs.realpath", "fs.readlink", "fs.symlink", "fs.link", "fs.chmod", "fs.truncate", "module.resolve", "module.loadFile", "module.format", "module.batchResolve", "child_process.spawn", "child_process.poll", "child_process.write_stdin", "child_process.close_stdin", "child_process.kill", "child_process.spawn_sync", "process.signal_state", "dgram.create", "dgram.bind", "dgram.recv", "dgram.send", "dgram.close", "dgram.address", "dgram.setBufferSize", "dgram.getBufferSize"];
19
+ export type BrowserWorkerSyncOperation = (typeof BROWSER_SYNC_BRIDGE_OPERATIONS)[number];
20
+ export declare function isBrowserWorkerSyncOperation(value: unknown): value is BrowserWorkerSyncOperation;
21
+ export interface BrowserSyncBridgeBuffers {
22
+ signalBuffer: SharedArrayBuffer;
23
+ dataBuffer: SharedArrayBuffer;
24
+ }
25
+ export interface BrowserSyncBridgePayload extends BrowserSyncBridgeBuffers {
26
+ timeoutMs?: number;
27
+ }
28
+ export interface BrowserWorkerSyncRequestMessage {
29
+ type: "sync-request";
30
+ controlToken: string;
31
+ executionId: string;
32
+ processRequestId: number;
33
+ requestId: number;
34
+ operation: BrowserWorkerSyncOperation;
35
+ args: unknown[];
36
+ }
37
+ export interface BrowserSyncBridgeErrorPayload {
38
+ message: string;
39
+ code?: string;
40
+ }
41
+ export declare function assertBrowserSyncBridgeSupport(): void;
42
+ export declare function getBrowserSyncBridgeDataBytes(payloadLimits?: {
43
+ base64TransferBytes?: number;
44
+ jsonPayloadBytes?: number;
45
+ }): number;
46
+ export declare function createBrowserSyncBridgePayload(payloadLimits?: {
47
+ base64TransferBytes?: number;
48
+ jsonPayloadBytes?: number;
49
+ }): BrowserSyncBridgePayload;
50
+ export declare function toBrowserSyncBridgeError(error: unknown): BrowserSyncBridgeErrorPayload;
@@ -0,0 +1,93 @@
1
+ export const SYNC_BRIDGE_SIGNAL_STATE_INDEX = 0;
2
+ export const SYNC_BRIDGE_SIGNAL_STATUS_INDEX = 1;
3
+ export const SYNC_BRIDGE_SIGNAL_KIND_INDEX = 2;
4
+ export const SYNC_BRIDGE_SIGNAL_LENGTH_INDEX = 3;
5
+ export const SYNC_BRIDGE_SIGNAL_STATE_IDLE = 0;
6
+ export const SYNC_BRIDGE_SIGNAL_STATE_READY = 1;
7
+ export const SYNC_BRIDGE_STATUS_OK = 0;
8
+ export const SYNC_BRIDGE_STATUS_ERROR = 1;
9
+ export const SYNC_BRIDGE_KIND_NONE = 0;
10
+ export const SYNC_BRIDGE_KIND_TEXT = 1;
11
+ export const SYNC_BRIDGE_KIND_BINARY = 2;
12
+ export const SYNC_BRIDGE_KIND_JSON = 3;
13
+ export const SYNC_BRIDGE_SIGNAL_BYTES = 4 * Int32Array.BYTES_PER_ELEMENT;
14
+ export const SYNC_BRIDGE_DEFAULT_WAIT_TIMEOUT_MS = 30_000;
15
+ export const SYNC_BRIDGE_DEFAULT_DATA_BYTES = 16 * 1024 * 1024;
16
+ export const SYNC_BRIDGE_MIN_DATA_BYTES = 64 * 1024;
17
+ export const SYNC_BRIDGE_PAYLOAD_LIMIT_ERROR_CODE = "ERR_SANDBOX_PAYLOAD_TOO_LARGE";
18
+ export const BROWSER_SYNC_BRIDGE_OPERATIONS = [
19
+ "fs.readFile",
20
+ "fs.writeFile",
21
+ "fs.readFileBinary",
22
+ "fs.writeFileBinary",
23
+ "fs.readDir",
24
+ "fs.createDir",
25
+ "fs.mkdir",
26
+ "fs.rmdir",
27
+ "fs.exists",
28
+ "fs.stat",
29
+ "fs.lstat",
30
+ "fs.unlink",
31
+ "fs.rename",
32
+ "fs.realpath",
33
+ "fs.readlink",
34
+ "fs.symlink",
35
+ "fs.link",
36
+ "fs.chmod",
37
+ "fs.truncate",
38
+ "module.resolve",
39
+ "module.loadFile",
40
+ "module.format",
41
+ "module.batchResolve",
42
+ "child_process.spawn",
43
+ "child_process.poll",
44
+ "child_process.write_stdin",
45
+ "child_process.close_stdin",
46
+ "child_process.kill",
47
+ "child_process.spawn_sync",
48
+ "process.signal_state",
49
+ "dgram.create",
50
+ "dgram.bind",
51
+ "dgram.recv",
52
+ "dgram.send",
53
+ "dgram.close",
54
+ "dgram.address",
55
+ "dgram.setBufferSize",
56
+ "dgram.getBufferSize",
57
+ ];
58
+ const BROWSER_SYNC_BRIDGE_OPERATION_SET = new Set(BROWSER_SYNC_BRIDGE_OPERATIONS);
59
+ export function isBrowserWorkerSyncOperation(value) {
60
+ return (typeof value === "string" && BROWSER_SYNC_BRIDGE_OPERATION_SET.has(value));
61
+ }
62
+ export function assertBrowserSyncBridgeSupport() {
63
+ if (typeof SharedArrayBuffer === "undefined") {
64
+ throw new Error("Browser runtime requires SharedArrayBuffer for sync filesystem and module loading parity");
65
+ }
66
+ if (typeof Atomics === "undefined" || typeof Atomics.wait !== "function") {
67
+ throw new Error("Browser runtime requires Atomics.wait for sync filesystem and module loading parity");
68
+ }
69
+ }
70
+ export function getBrowserSyncBridgeDataBytes(payloadLimits) {
71
+ return Math.max(payloadLimits?.base64TransferBytes ?? SYNC_BRIDGE_DEFAULT_DATA_BYTES, payloadLimits?.jsonPayloadBytes ?? 4 * 1024 * 1024, SYNC_BRIDGE_MIN_DATA_BYTES);
72
+ }
73
+ export function createBrowserSyncBridgePayload(payloadLimits) {
74
+ assertBrowserSyncBridgeSupport();
75
+ return {
76
+ signalBuffer: new SharedArrayBuffer(SYNC_BRIDGE_SIGNAL_BYTES),
77
+ dataBuffer: new SharedArrayBuffer(getBrowserSyncBridgeDataBytes(payloadLimits)),
78
+ timeoutMs: SYNC_BRIDGE_DEFAULT_WAIT_TIMEOUT_MS,
79
+ };
80
+ }
81
+ export function toBrowserSyncBridgeError(error) {
82
+ if (error instanceof Error) {
83
+ return {
84
+ message: error.message,
85
+ code: typeof error.code === "string"
86
+ ? error.code
87
+ : undefined,
88
+ };
89
+ }
90
+ return {
91
+ message: String(error),
92
+ };
93
+ }
@@ -0,0 +1 @@
1
+ export declare const BROWSER_WASI_POLYFILL_CODE = "\n\t\tglobalThis.__agentOsWasiHost = {\n\t\t\trequireBuiltin: (name) =>\n\t\t\t\tglobalThis.require(String(name).replace(/^node:/, \"\")),\n\t\t\tsyncReadLimitBytes: 16777216,\n\t\t};\n\t\tconst Buffer =\n\t\t\t(typeof globalThis !== \"undefined\" && globalThis.Buffer) ||\n\t\t\t(class __AgentOsWasiBuffer extends Uint8Array {\n\t\t\t\tstatic alloc(size) { return new __AgentOsWasiBuffer(size >>> 0); }\n\t\t\t\tstatic allocUnsafe(size) { return new __AgentOsWasiBuffer(size >>> 0); }\n\t\t\t\tstatic isBuffer(value) { return value instanceof Uint8Array; }\n\t\t\t\tstatic byteLength(value, encoding) {\n\t\t\t\t\tif (value instanceof Uint8Array) return value.length;\n\t\t\t\t\tif (encoding === \"base64\") return Math.floor((String(value).replace(/=+$/, \"\").length * 3) / 4);\n\t\t\t\t\tif (encoding === \"hex\") return String(value).length >> 1;\n\t\t\t\t\treturn new TextEncoder().encode(String(value)).length;\n\t\t\t\t}\n\t\t\t\tstatic from(value, encodingOrOffset, length) {\n\t\t\t\t\tif (typeof value === \"string\") {\n\t\t\t\t\t\tconst encoding = encodingOrOffset || \"utf8\";\n\t\t\t\t\t\tif (encoding === \"base64\") {\n\t\t\t\t\t\t\tconst binary = atob(value);\n\t\t\t\t\t\t\tconst out = new __AgentOsWasiBuffer(binary.length);\n\t\t\t\t\t\t\tfor (let i = 0; i < binary.length; i += 1) out[i] = binary.charCodeAt(i) & 0xff;\n\t\t\t\t\t\t\treturn out;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (encoding === \"hex\") {\n\t\t\t\t\t\t\tconst clean = String(value);\n\t\t\t\t\t\t\tconst out = new __AgentOsWasiBuffer(clean.length >> 1);\n\t\t\t\t\t\t\tfor (let i = 0; i < out.length; i += 1) out[i] = parseInt(clean.substr(i * 2, 2), 16);\n\t\t\t\t\t\t\treturn out;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst encoded = new TextEncoder().encode(value);\n\t\t\t\t\t\tconst out = new __AgentOsWasiBuffer(encoded.length);\n\t\t\t\t\t\tout.set(encoded);\n\t\t\t\t\t\treturn out;\n\t\t\t\t\t}\n\t\t\t\t\tif (value instanceof ArrayBuffer) {\n\t\t\t\t\t\tconst offset = encodingOrOffset || 0;\n\t\t\t\t\t\tconst len = length === undefined ? value.byteLength - offset : length;\n\t\t\t\t\t\tconst view = new Uint8Array(value, offset, len);\n\t\t\t\t\t\tconst out = new __AgentOsWasiBuffer(view.length);\n\t\t\t\t\t\tout.set(view);\n\t\t\t\t\t\treturn out;\n\t\t\t\t\t}\n\t\t\t\t\tif (ArrayBuffer.isView(value)) {\n\t\t\t\t\t\tconst view = new Uint8Array(value.buffer, value.byteOffset, value.byteLength);\n\t\t\t\t\t\tconst out = new __AgentOsWasiBuffer(view.length);\n\t\t\t\t\t\tout.set(view);\n\t\t\t\t\t\treturn out;\n\t\t\t\t\t}\n\t\t\t\t\tconst arr = Array.from(value || []);\n\t\t\t\t\tconst out = new __AgentOsWasiBuffer(arr.length);\n\t\t\t\t\tfor (let i = 0; i < arr.length; i += 1) out[i] = arr[i] & 0xff;\n\t\t\t\t\treturn out;\n\t\t\t\t}\n\t\t\t\tstatic concat(list, totalLength) {\n\t\t\t\t\tconst chunks = Array.from(list || []);\n\t\t\t\t\tif (totalLength === undefined) {\n\t\t\t\t\t\ttotalLength = 0;\n\t\t\t\t\t\tfor (const chunk of chunks) totalLength += chunk.length;\n\t\t\t\t\t}\n\t\t\t\t\tconst out = new __AgentOsWasiBuffer(totalLength >>> 0);\n\t\t\t\t\tlet offset = 0;\n\t\t\t\t\tfor (const chunk of chunks) {\n\t\t\t\t\t\tif (offset >= out.length) break;\n\t\t\t\t\t\tconst slice = offset + chunk.length > out.length ? chunk.subarray(0, out.length - offset) : chunk;\n\t\t\t\t\t\tout.set(slice, offset);\n\t\t\t\t\t\toffset += slice.length;\n\t\t\t\t\t}\n\t\t\t\t\treturn out;\n\t\t\t\t}\n\t\t\t\ttoString(encoding, start, end) {\n\t\t\t\t\tconst view = this.subarray(start || 0, end === undefined ? this.length : end);\n\t\t\t\t\tif (encoding === \"base64\") {\n\t\t\t\t\t\tlet binary = \"\";\n\t\t\t\t\t\tfor (let i = 0; i < view.length; i += 1) binary += String.fromCharCode(view[i]);\n\t\t\t\t\t\treturn btoa(binary);\n\t\t\t\t\t}\n\t\t\t\t\tif (encoding === \"hex\") {\n\t\t\t\t\t\tlet hex = \"\";\n\t\t\t\t\t\tfor (let i = 0; i < view.length; i += 1) hex += view[i].toString(16).padStart(2, \"0\");\n\t\t\t\t\t\treturn hex;\n\t\t\t\t\t}\n\t\t\t\t\treturn new TextDecoder().decode(view);\n\t\t\t\t}\n\t\t\t});\nif (typeof globalThis !== \"undefined\" && typeof globalThis.__agentOsWasiModule === \"undefined\") {\n // Per-backend host seam (C / convergence): native populates it from its own\n // host globals (the `|| __agentOs*` fallbacks below); a non-native backend\n // (the browser converged worker) can pre-set `globalThis.__agentOsWasiHost`\n // with browser-provided equivalents so this same preview1 runner is shared.\n const __agentOsWasiHost =\n (typeof globalThis.__agentOsWasiHost === \"object\" &&\n globalThis.__agentOsWasiHost) ||\n {};\n const __agentOsWasiRequireBuiltin =\n __agentOsWasiHost.requireBuiltin ||\n (typeof __agentOsRequireBuiltin !== \"undefined\"\n ? __agentOsRequireBuiltin\n : (name) => globalThis.require(name));\n const __agentOsFs = () => __agentOsWasiRequireBuiltin(\"node:fs\");\n const __agentOsPath = () => __agentOsWasiRequireBuiltin(\"node:path\");\n const __agentOsCrypto = () => __agentOsWasiRequireBuiltin(\"node:crypto\");\n // Stdio sync-RPC bridge + fd-handle lookup come from the host seam (a\n // non-native backend supplies browser equivalents); native falls back to its\n // own host globals so behavior is unchanged.\n // Lazy resolvers: the native host globals are populated AFTER this module is\n // defined (per-execution), so resolve at call time, not at module-load.\n const __agentOsWasiSyncRpc = () =>\n __agentOsWasiHost.syncRpc ||\n (typeof globalThis.__agentOsSyncRpc !== \"undefined\"\n ? globalThis.__agentOsSyncRpc\n : undefined);\n const __agentOsWasiLookupFdHandle = () =>\n __agentOsWasiHost.lookupFdHandle ||\n (typeof globalThis.lookupFdHandle === \"function\"\n ? globalThis.lookupFdHandle\n : undefined);\n const __agentOsWasiErrnoSuccess = 0;\n const __agentOsWasiErrnoAcces = 2;\n const __agentOsWasiErrnoBadf = 8;\n const __agentOsWasiErrnoExist = 20;\n const __agentOsWasiErrnoFault = 21;\n const __agentOsWasiErrnoInval = 28;\n const __agentOsWasiErrnoIo = 29;\n const __agentOsWasiErrnoNoent = 44;\n const __agentOsWasiErrnoNosys = 52;\n const __agentOsWasiErrnoNotdir = 54;\n const __agentOsWasiErrnoPipe = 64;\n const __agentOsWasiErrnoRofs = 69;\n const __agentOsWasiErrnoXdev = 18;\n const __agentOsWasiFiletypeUnknown = 0;\n const __agentOsWasiFiletypeCharacterDevice = 2;\n const __agentOsWasiFiletypeDirectory = 3;\n const __agentOsWasiFiletypeRegularFile = 4;\n const __agentOsWasiFiletypeSymbolicLink = 7;\n const __agentOsWasiLookupSymlinkFollow = 1;\n const __agentOsWasiOpenCreate = 1;\n const __agentOsWasiOpenDirectory = 2;\n const __agentOsWasiOpenExclusive = 4;\n const __agentOsWasiOpenTruncate = 8;\n const __agentOsWasiRightFdWrite = 1n << 6n;\n const __agentOsWasiDefaultRightsBase = 0xffffffffffffffffn;\n const __agentOsWasiDefaultRightsInheriting = 0xffffffffffffffffn;\n const __agentOsWasiWhenceSet = 0;\n const __agentOsWasiWhenceCur = 1;\n const __agentOsWasiWhenceEnd = 2;\n // Read cap: a non-native backend provides it via the seam; native uses its\n // build-substituted constant. The ternary short-circuits so the native-only\n // placeholder token is never evaluated when the seam supplies a number.\n const __agentOsWasmSyncReadLimitBytes =\n typeof __agentOsWasiHost.syncReadLimitBytes === \"number\"\n ? __agentOsWasiHost.syncReadLimitBytes\n : 16777216;\n const __agentOsKernelStdioSyncRpcEnabled = () =>\n process?.env?.AGENT_OS_WASI_STDIO_SYNC_RPC === \"1\";\n const __agentOsWasiDebugEnabled = () => process?.env?.AGENT_OS_WASM_WASI_DEBUG === \"1\";\n const __agentOsWasiDebug = (message) => {\n if (!__agentOsWasiDebugEnabled() || typeof process?.stderr?.write !== \"function\") {\n return;\n }\n try {\n process.stderr.write(`[secure-exec-wasi] ${message}\\n`);\n } catch {\n // Ignore debug logging failures.\n }\n };\n\n class WASI {\n constructor(options = {}) {\n this.args = Array.isArray(options.args) ? options.args.map((value) => String(value)) : [];\n this.env =\n options.env && typeof options.env === \"object\"\n ? Object.fromEntries(\n Object.entries(options.env).map(([key, value]) => [String(key), String(value)]),\n )\n : {};\n this.preopens = options.preopens && typeof options.preopens === \"object\" ? options.preopens : {};\n this.returnOnExit = options.returnOnExit === true;\n this.instance = null;\n this.nextFd = 3;\n this.fdTable = new Map([\n [0, { kind: \"stdin\", fdFlags: 0 }],\n [1, { kind: \"stdout\", fdFlags: 0 }],\n [2, { kind: \"stderr\", fdFlags: 0 }],\n ]);\n for (const [guestPath, spec] of Object.entries(this.preopens)) {\n const normalized = this._normalizePreopenSpec(spec);\n if (!normalized) {\n continue;\n }\n this.fdTable.set(this.nextFd++, {\n kind: \"preopen\",\n guestPath: String(guestPath),\n hostPath: normalized.hostPath,\n readOnly: normalized.readOnly,\n rightsBase: normalized.rightsBase,\n rightsInheriting: normalized.rightsInheriting,\n fdFlags: 0,\n });\n }\n this.wasiImport = {\n args_get: (...args) => this._argsGet(...args),\n args_sizes_get: (...args) => this._argsSizesGet(...args),\n clock_time_get: (...args) => this._clockTimeGet(...args),\n clock_res_get: (...args) => this._clockResGet(...args),\n environ_get: (...args) => this._environGet(...args),\n environ_sizes_get: (...args) => this._environSizesGet(...args),\n fd_close: (...args) => this._fdClose(...args),\n fd_fdstat_get: (...args) => this._fdFdstatGet(...args),\n fd_fdstat_set_flags: (...args) => this._fdFdstatSetFlags(...args),\n fd_filestat_get: (...args) => this._fdFilestatGet(...args),\n fd_filestat_set_size: (...args) => this._fdFilestatSetSize(...args),\n fd_prestat_dir_name: (...args) => this._fdPrestatDirName(...args),\n fd_prestat_get: (...args) => this._fdPrestatGet(...args),\n fd_pread: (...args) => this._fdPread(...args),\n fd_pwrite: (...args) => this._fdPwrite(...args),\n fd_readdir: (...args) => this._fdReaddir(...args),\n fd_read: (...args) => this._fdRead(...args),\n fd_seek: (...args) => this._fdSeek(...args),\n fd_sync: (...args) => this._fdSync(...args),\n fd_tell: (...args) => this._fdTell(...args),\n fd_write: (...args) => this._fdWrite(...args),\n path_create_directory: (...args) => this._pathCreateDirectory(...args),\n path_filestat_get: (...args) => this._pathFilestatGet(...args),\n path_link: (...args) => this._pathLink(...args),\n path_open: (...args) => this._pathOpen(...args),\n path_readlink: (...args) => this._pathReadlink(...args),\n path_remove_directory: (...args) => this._pathRemoveDirectory(...args),\n path_rename: (...args) => this._pathRename(...args),\n path_symlink: (...args) => this._pathSymlink(...args),\n path_unlink_file: (...args) => this._pathUnlinkFile(...args),\n poll_oneoff: (...args) => this._pollOneoff(...args),\n proc_exit: (...args) => this._procExit(...args),\n random_get: (...args) => this._randomGet(...args),\n sched_yield: (...args) => this._schedYield(...args),\n };\n }\n\n start(instance) {\n this.instance = instance;\n try {\n if (typeof instance?.exports?._start === \"function\") {\n instance.exports._start();\n }\n return 0;\n } catch (error) {\n if (error && error.__agentOsWasiExit === true) {\n return Number(error.code) >>> 0;\n }\n throw error;\n }\n }\n\n _memoryView() {\n const memory = this.instance?.exports?.memory;\n if (!(memory instanceof WebAssembly.Memory)) {\n throw new Error(\"WASI memory export is unavailable\");\n }\n return new DataView(memory.buffer);\n }\n\n _memoryBytes() {\n const memory = this.instance?.exports?.memory;\n if (!(memory instanceof WebAssembly.Memory)) {\n throw new Error(\"WASI memory export is unavailable\");\n }\n return new Uint8Array(memory.buffer);\n }\n\n _boundedIovLength(iovs, iovsLen) {\n const view = this._memoryView();\n let length = 0;\n for (let index = 0; index < (Number(iovsLen) >>> 0); index += 1) {\n const entryOffset = (Number(iovs) >>> 0) + index * 8;\n length += view.getUint32(entryOffset + 4, true);\n if (length > __agentOsWasmSyncReadLimitBytes) {\n throw new RangeError(\n `WASI read iov length ${length} exceeds ${__agentOsWasmSyncReadLimitBytes}`,\n );\n }\n }\n return length >>> 0;\n }\n\n _normalizeRights(value, fallback) {\n try {\n return BigInt(value);\n } catch {\n return fallback;\n }\n }\n\n _normalizePreopenSpec(value) {\n // Path-model seam (convergence item C): native maps guest paths to HOST\n // paths (its preopen specs carry `hostPath`); a non-native backend with no\n // host paths (the browser, whose `require(\"fs\")` IS the kernel VFS) can\n // supply `__agentOsWasiHost.normalizePreopen` to treat the guest/VFS path\n // as the \"hostPath\" identity, so the same runner serves both.\n if (typeof __agentOsWasiHost.normalizePreopen === \"function\") {\n const seamNormalized = __agentOsWasiHost.normalizePreopen(value, {\n defaultRightsBase: __agentOsWasiDefaultRightsBase,\n defaultRightsInheriting: __agentOsWasiDefaultRightsInheriting,\n normalizeRights: (rights, fallback) =>\n this._normalizeRights(rights, fallback),\n });\n return seamNormalized ?? null;\n }\n if (typeof value === \"string\") {\n return {\n hostPath: String(value),\n readOnly: false,\n rightsBase: __agentOsWasiDefaultRightsBase,\n rightsInheriting: __agentOsWasiDefaultRightsInheriting,\n };\n }\n if (!value || typeof value !== \"object\" || typeof value.hostPath !== \"string\") {\n return null;\n }\n return {\n hostPath: String(value.hostPath),\n readOnly: value.readOnly === true,\n rightsBase: this._normalizeRights(\n value.rightsBase,\n __agentOsWasiDefaultRightsBase,\n ),\n rightsInheriting: this._normalizeRights(\n value.rightsInheriting,\n __agentOsWasiDefaultRightsInheriting,\n ),\n };\n }\n\n _descriptorRightsBase(entry) {\n return this._normalizeRights(\n entry?.rightsBase,\n __agentOsWasiDefaultRightsBase,\n );\n }\n\n _descriptorRightsInheriting(entry) {\n return this._normalizeRights(\n entry?.rightsInheriting,\n __agentOsWasiDefaultRightsInheriting,\n );\n }\n\n _hasWriteRights(rights) {\n try {\n return (BigInt(rights) & __agentOsWasiRightFdWrite) !== 0n;\n } catch {\n return true;\n }\n }\n\n _writeUint32(ptr, value) {\n try {\n this._memoryView().setUint32(Number(ptr) >>> 0, Number(value) >>> 0, true);\n return __agentOsWasiErrnoSuccess;\n } catch {\n __agentOsWasiDebug(`writeUint32 failed ptr=${Number(ptr)} value=${Number(value)}`);\n return __agentOsWasiErrnoFault;\n }\n }\n\n _writeUint64(ptr, value) {\n try {\n this._memoryView().setBigUint64(Number(ptr) >>> 0, BigInt(value), true);\n return __agentOsWasiErrnoSuccess;\n } catch {\n __agentOsWasiDebug(`writeUint64 failed ptr=${Number(ptr)} value=${String(value)}`);\n return __agentOsWasiErrnoFault;\n }\n }\n\n _writeBytes(ptr, bytes) {\n try {\n this._memoryBytes().set(bytes, Number(ptr) >>> 0);\n return __agentOsWasiErrnoSuccess;\n } catch {\n __agentOsWasiDebug(`writeBytes failed ptr=${Number(ptr)} len=${bytes?.length ?? 0}`);\n return __agentOsWasiErrnoFault;\n }\n }\n\n _readBytes(ptr, len) {\n const start = Number(ptr) >>> 0;\n const end = start + (Number(len) >>> 0);\n return Buffer.from(this._memoryBytes().slice(start, end));\n }\n\n _readString(ptr, len) {\n return this._readBytes(ptr, len).toString(\"utf8\");\n }\n\n _decodeSyncRpcBytes(value) {\n if (value == null) {\n return null;\n }\n if (typeof Buffer !== \"undefined\" && Buffer.isBuffer(value)) {\n return value;\n }\n if (value instanceof Uint8Array) {\n return Buffer.from(value);\n }\n if (ArrayBuffer.isView(value)) {\n return Buffer.from(value.buffer, value.byteOffset, value.byteLength);\n }\n if (value instanceof ArrayBuffer) {\n return Buffer.from(value);\n }\n if (\n value &&\n typeof value === \"object\" &&\n value.__agentOsType === \"bytes\" &&\n typeof value.base64 === \"string\"\n ) {\n return Buffer.from(value.base64, \"base64\");\n }\n return null;\n }\n\n _dequeuePipeBytes(pipe, maxBytes) {\n if (!pipe || !Array.isArray(pipe.chunks) || pipe.chunks.length === 0) {\n return Buffer.alloc(0);\n }\n\n let remaining = Math.max(0, Number(maxBytes) >>> 0);\n if (remaining === 0) {\n return Buffer.alloc(0);\n }\n\n const parts = [];\n while (remaining > 0 && pipe.chunks.length > 0) {\n const chunk = pipe.chunks[0];\n if (!chunk || chunk.length === 0) {\n pipe.chunks.shift();\n continue;\n }\n\n if (chunk.length <= remaining) {\n parts.push(chunk);\n pipe.chunks.shift();\n remaining -= chunk.length;\n continue;\n }\n\n parts.push(chunk.subarray(0, remaining));\n pipe.chunks[0] = chunk.subarray(remaining);\n remaining = 0;\n }\n\n return Buffer.concat(parts);\n }\n\n _enqueuePipeBytes(pipe, bytes) {\n if (!pipe || !Array.isArray(pipe.chunks)) {\n return;\n }\n const chunk = Buffer.from(bytes ?? []);\n if (chunk.length === 0) {\n return;\n }\n pipe.chunks.push(chunk);\n }\n\n _pipeHasReaders(pipe) {\n return (\n (pipe?.readHandleCount ?? 0) > 0 ||\n (pipe?.consumers?.size ?? 0) > 0\n );\n }\n\n _flushPipeConsumers(pipe) {\n if (\n !pipe ||\n typeof pipe.consumers?.entries !== \"function\" ||\n !Array.isArray(pipe.chunks) ||\n pipe.chunks.length === 0 ||\n typeof globalThis?.__agentOsSyncRpc?.callSync !== \"function\"\n ) {\n return false;\n }\n\n let flushed = false;\n while (pipe.chunks.length > 0) {\n const chunk = pipe.chunks.shift();\n if (!chunk || chunk.length === 0) {\n continue;\n }\n\n for (const [consumerKey, consumer] of Array.from(pipe.consumers.entries())) {\n if (!consumer || typeof consumer.childId !== \"string\") {\n pipe.consumers.delete(consumerKey);\n continue;\n }\n try {\n __agentOsWasiSyncRpc().callSync(\"child_process.write_stdin\", [\n consumer.childId,\n chunk,\n ]);\n flushed = true;\n } catch {\n pipe.consumers.delete(consumerKey);\n }\n }\n }\n\n return flushed;\n }\n\n _closePipeConsumers(pipe) {\n if (\n !pipe ||\n typeof pipe.consumers?.entries !== \"function\" ||\n typeof globalThis?.__agentOsSyncRpc?.callSync !== \"function\"\n ) {\n return false;\n }\n\n let closed = false;\n for (const [consumerKey, consumer] of Array.from(pipe.consumers.entries())) {\n if (!consumer || typeof consumer.childId !== \"string\") {\n pipe.consumers.delete(consumerKey);\n continue;\n }\n try {\n __agentOsWasiSyncRpc().callSync(\"child_process.close_stdin\", [\n consumer.childId,\n ]);\n closed = true;\n } catch {\n // Ignore close errors during teardown.\n }\n pipe.consumers.delete(consumerKey);\n }\n\n return closed;\n }\n\n _pumpPipeProducers(pipe, waitMs) {\n if (\n !pipe ||\n typeof pipe.producers?.entries !== \"function\" ||\n typeof globalThis?.__agentOsSyncRpc?.callSync !== \"function\"\n ) {\n return false;\n }\n\n let processed = false;\n for (const [producerKey, producer] of Array.from(pipe.producers.entries())) {\n if (!producer || typeof producer.childId !== \"string\") {\n pipe.producers.delete(producerKey);\n continue;\n }\n\n let event = null;\n try {\n event = __agentOsWasiSyncRpc().callSync(\"child_process.poll\", [\n producer.childId,\n Math.max(0, Number(waitMs) >>> 0),\n ]);\n } catch {\n pipe.producers.delete(producerKey);\n continue;\n }\n\n if (!event) {\n continue;\n }\n\n processed = true;\n const streamType =\n producer.stream === \"stderr\" ? \"stderr\" : producer.stream === \"stdout\" ? \"stdout\" : null;\n if ((event.type === \"stdout\" || event.type === \"stderr\") && event.type === streamType) {\n const chunk = this._decodeSyncRpcBytes(event.data);\n if (chunk && chunk.length > 0) {\n pipe.chunks.push(Buffer.from(chunk));\n }\n continue;\n }\n\n if (event.type === \"exit\") {\n pipe.producers.delete(producerKey);\n if (pipe.producers.size === 0 && (pipe.writeHandleCount ?? 0) === 0) {\n this._closePipeConsumers(pipe);\n }\n continue;\n }\n }\n\n return processed;\n }\n\n _collectIovs(iovs, iovsLen) {\n const totalLength = this._boundedIovLength(iovs, iovsLen);\n const view = this._memoryView();\n const chunks = [];\n for (let index = 0; index < (Number(iovsLen) >>> 0); index += 1) {\n const entryOffset = (Number(iovs) >>> 0) + index * 8;\n const ptr = view.getUint32(entryOffset, true);\n const len = view.getUint32(entryOffset + 4, true);\n chunks.push(this._readBytes(ptr, len));\n }\n return Buffer.concat(chunks, totalLength);\n }\n\n _writeToIovs(iovs, iovsLen, bytes) {\n const view = this._memoryView();\n const memory = this._memoryBytes();\n let sourceOffset = 0;\n for (let index = 0; index < (Number(iovsLen) >>> 0) && sourceOffset < bytes.length; index += 1) {\n const entryOffset = (Number(iovs) >>> 0) + index * 8;\n const ptr = view.getUint32(entryOffset, true);\n const len = view.getUint32(entryOffset + 4, true);\n const chunk = bytes.subarray(sourceOffset, sourceOffset + len);\n memory.set(chunk, Number(ptr) >>> 0);\n sourceOffset += chunk.length;\n }\n return sourceOffset;\n }\n\n _stringTable(values) {\n return values.map((value) => Buffer.from(`${String(value)}\\0`, \"utf8\"));\n }\n\n _writeStringTable(values, offsetsPtr, bufferPtr) {\n try {\n const view = this._memoryView();\n const memory = this._memoryBytes();\n let cursor = Number(bufferPtr) >>> 0;\n for (let index = 0; index < values.length; index += 1) {\n const bytes = values[index];\n view.setUint32((Number(offsetsPtr) >>> 0) + index * 4, cursor, true);\n memory.set(bytes, cursor);\n cursor += bytes.length;\n }\n return __agentOsWasiErrnoSuccess;\n } catch {\n __agentOsWasiDebug(\n `writeStringTable failed offsetsPtr=${Number(offsetsPtr)} bufferPtr=${Number(bufferPtr)} count=${values.length}`,\n );\n return __agentOsWasiErrnoFault;\n }\n }\n\n _filetypeForStats(stats) {\n if (!stats) {\n return __agentOsWasiFiletypeUnknown;\n }\n if (typeof stats.isDirectory === \"function\" && stats.isDirectory()) {\n return __agentOsWasiFiletypeDirectory;\n }\n if (typeof stats.isFile === \"function\" && stats.isFile()) {\n return __agentOsWasiFiletypeRegularFile;\n }\n if (typeof stats.isSymbolicLink === \"function\" && stats.isSymbolicLink()) {\n return __agentOsWasiFiletypeSymbolicLink;\n }\n if (typeof stats.isCharacterDevice === \"function\" && stats.isCharacterDevice()) {\n return __agentOsWasiFiletypeCharacterDevice;\n }\n return __agentOsWasiFiletypeUnknown;\n }\n\n _fdFiletype(entry) {\n if (!entry) {\n return __agentOsWasiFiletypeUnknown;\n }\n if (\n entry.kind === \"stdin\" ||\n entry.kind === \"stdout\" ||\n entry.kind === \"stderr\"\n ) {\n return __agentOsWasiFiletypeCharacterDevice;\n }\n if (entry.kind === \"preopen\" || entry.kind === \"directory\") {\n return __agentOsWasiFiletypeDirectory;\n }\n if (entry.kind === \"symlink\") {\n return __agentOsWasiFiletypeSymbolicLink;\n }\n return __agentOsWasiFiletypeRegularFile;\n }\n\n _mapFsError(error) {\n switch (error?.code) {\n case \"EACCES\":\n case \"EPERM\":\n return __agentOsWasiErrnoAcces;\n case \"ENOENT\":\n return __agentOsWasiErrnoNoent;\n case \"ENOTDIR\":\n return __agentOsWasiErrnoNotdir;\n case \"EEXIST\":\n return __agentOsWasiErrnoExist;\n case \"EINVAL\":\n return __agentOsWasiErrnoInval;\n case \"EROFS\":\n return __agentOsWasiErrnoRofs;\n case \"EXDEV\":\n return __agentOsWasiErrnoXdev;\n default:\n return __agentOsWasiErrnoIo;\n }\n }\n\n _descriptorEntry(fd) {\n return this.fdTable.get(Number(fd) >>> 0) ?? null;\n }\n\n _localFdHandle(fd) {\n const entry = this._descriptorEntry(fd);\n if (!entry || typeof entry.realFd !== \"number\") {\n return null;\n }\n return {\n kind: \"host-passthrough\",\n targetFd: entry.realFd,\n displayFd: Number(fd) >>> 0,\n refCount: 1,\n open: true,\n readOnly: entry.readOnly === true,\n };\n }\n\n _externalFdHandle(fd) {\n const descriptor = Number(fd) >>> 0;\n const localHandle = this._localFdHandle(descriptor);\n if (localHandle) {\n return localHandle;\n }\n try {\n if (typeof lookupFdHandle === \"function\") {\n return lookupFdHandle(descriptor) ?? null;\n }\n } catch {\n // Fall through to other lookup paths.\n }\n try {\n const __agentOsWasiFdHandleFn = __agentOsWasiLookupFdHandle();\n if (typeof __agentOsWasiFdHandleFn === \"function\") {\n return __agentOsWasiFdHandleFn(descriptor) ?? null;\n }\n } catch {\n // Ignore missing global bridge helpers.\n }\n return null;\n }\n\n _descriptorHostPath(entry) {\n if (!entry) {\n return null;\n }\n if (typeof entry.hostPath === \"string\") {\n return entry.hostPath;\n }\n if (typeof entry.realFd === \"number\") {\n return __agentOsFs().readlinkSync(`/proc/self/fd/${entry.realFd}`);\n }\n return null;\n }\n\n _descriptorFsPath(entry) {\n if (!entry) {\n return null;\n }\n if (typeof entry.hostPath === \"string\" && entry.hostPath.length > 0) {\n return entry.hostPath;\n }\n if (typeof entry.guestPath === \"string\" && entry.guestPath.length > 0) {\n return entry.guestPath;\n }\n return null;\n }\n\n _sidecarManagedProcess() {\n if (\n typeof globalThis.__agentOsWasmInternalEnv?.AGENT_OS_SANDBOX_ROOT ===\n \"string\" &&\n globalThis.__agentOsWasmInternalEnv.AGENT_OS_SANDBOX_ROOT.length > 0\n ) {\n return true;\n }\n return (\n typeof process?.env?.AGENT_OS_SANDBOX_ROOT === \"string\" &&\n process.env.AGENT_OS_SANDBOX_ROOT.length > 0\n );\n }\n\n _descriptorDirectoryFsPath(entry) {\n if (\n (entry?.kind === \"preopen\" || entry?.kind === \"directory\") &&\n this._sidecarManagedProcess()\n ) {\n return this._descriptorGuestPath(entry);\n }\n return this._descriptorFsPath(entry);\n }\n\n _descriptorGuestPath(entry) {\n if (!entry) {\n return null;\n }\n const guestPath = typeof entry.guestPath === \"string\" ? entry.guestPath : null;\n if (guestPath === \".\") {\n return this._currentGuestCwd();\n }\n if (typeof guestPath === \"string\" && guestPath.length > 0) {\n return __agentOsPath().posix.normalize(guestPath);\n }\n return null;\n }\n\n _descriptorPreopenName(entry) {\n if (!entry) {\n return null;\n }\n const guestPath = typeof entry.guestPath === \"string\" ? entry.guestPath : null;\n if (guestPath === \".\") {\n return this._descriptorGuestPath(entry);\n }\n if (typeof guestPath === \"string\" && guestPath.length > 0) {\n return __agentOsPath().posix.normalize(guestPath);\n }\n return null;\n }\n\n _currentDirectoryPreopen() {\n for (const entry of this.fdTable.values()) {\n if (entry?.kind === \"preopen\" && entry.guestPath === \".\") {\n return entry;\n }\n }\n return null;\n }\n\n _descriptorPathBase(entry, target) {\n const baseGuestPath = this._descriptorGuestPath(entry);\n if (typeof baseGuestPath !== \"string\") {\n return null;\n }\n return {\n entry,\n guestPath: baseGuestPath,\n hostPath: typeof entry?.hostPath === \"string\" ? entry.hostPath : null,\n };\n }\n\n _hostPathExists(hostPath) {\n try {\n __agentOsFs().statSync(hostPath);\n return true;\n } catch {\n return false;\n }\n }\n\n _currentGuestCwd() {\n const pwd =\n typeof this.env?.PWD === \"string\" && this.env.PWD.startsWith(\"/\")\n ? this.env.PWD\n : typeof this.env?.HOME === \"string\" && this.env.HOME.startsWith(\"/\")\n ? this.env.HOME\n : \"/\";\n return __agentOsPath().posix.normalize(pwd);\n }\n\n _resolveHostMappingForGuestPath(guestPath) {\n const normalized = __agentOsPath().posix.normalize(guestPath);\n const mappings = [];\n for (const entry of this.fdTable.values()) {\n if (entry?.kind !== \"preopen\" || typeof entry.hostPath !== \"string\") {\n continue;\n }\n const guestRoot = this._descriptorGuestPath(entry);\n if (typeof guestRoot !== \"string\") {\n continue;\n }\n mappings.push({\n guestRoot,\n hostPath: entry.hostPath,\n readOnly: entry.readOnly === true,\n });\n }\n mappings.sort((left, right) => right.guestRoot.length - left.guestRoot.length);\n\n for (const mapping of mappings) {\n const matchesRoot = mapping.guestRoot === \"/\" && normalized.startsWith(\"/\");\n const matchesNested =\n normalized === mapping.guestRoot ||\n normalized.startsWith(`${mapping.guestRoot}/`);\n if (!matchesRoot && !matchesNested) {\n continue;\n }\n const suffix =\n normalized === mapping.guestRoot\n ? \"\"\n : mapping.guestRoot === \"/\"\n ? normalized.slice(1)\n : normalized.slice(mapping.guestRoot.length + 1);\n return {\n hostPath: suffix\n ? __agentOsPath().join(mapping.hostPath, ...suffix.split(\"/\"))\n : mapping.hostPath,\n readOnly: mapping.readOnly,\n };\n }\n\n return null;\n }\n\n _resolveHostPathForGuestPath(guestPath) {\n return this._resolveHostMappingForGuestPath(guestPath)?.hostPath ?? null;\n }\n\n _rootRelativeTargetPrefersCwd(target) {\n const normalizedTarget = __agentOsPath().posix.normalize(target || \".\");\n if (normalizedTarget !== \".\") {\n return false;\n }\n return !this._rootRelativeTargetMatchesAbsoluteArg(target);\n }\n\n _rootRelativeTargetMatchesAbsoluteArg(target) {\n const rootGuestPath = __agentOsPath().posix.resolve(\"/\", target);\n return this.args\n .slice(1)\n .some(\n (arg) =>\n typeof arg === \"string\" &&\n arg.startsWith(\"/\") &&\n __agentOsPath().posix.normalize(arg) === rootGuestPath,\n );\n }\n\n _resolveRootRelativePath(target, preferCreateParent = false) {\n const rootGuestPath = __agentOsPath().posix.resolve(\"/\", target);\n const rootMapping = this._resolveHostMappingForGuestPath(rootGuestPath);\n const rootHostPath = rootMapping?.hostPath ?? null;\n const cwdGuestPath = this._currentGuestCwd();\n if (cwdGuestPath !== \"/\") {\n const cwdGuestTarget = __agentOsPath().posix.resolve(cwdGuestPath, target);\n const cwdMapping = this._resolveHostMappingForGuestPath(cwdGuestTarget);\n const cwdHostTarget = cwdMapping?.hostPath ?? null;\n if (\n typeof cwdHostTarget === \"string\" &&\n (\n (preferCreateParent && !this._rootRelativeTargetMatchesAbsoluteArg(target)) ||\n this._rootRelativeTargetPrefersCwd(target) ||\n (\n this._hostPathExists(cwdHostTarget) &&\n !(typeof rootHostPath === \"string\" && this._hostPathExists(rootHostPath))\n )\n )\n ) {\n return {\n guestPath: cwdGuestTarget,\n hostPath: cwdHostTarget,\n readOnly: cwdMapping?.readOnly === true,\n };\n }\n }\n return {\n guestPath: rootGuestPath,\n hostPath: rootHostPath,\n readOnly: rootMapping?.readOnly === true,\n };\n }\n\n _resolveDescriptorPath(fd, pathPtr, pathLen, options = {}) {\n const entry = this._descriptorEntry(fd);\n if (!entry) {\n return { error: __agentOsWasiErrnoBadf };\n }\n const target = this._readString(pathPtr, pathLen);\n const base = this._descriptorPathBase(entry, target);\n if (!base || typeof base.guestPath !== \"string\") {\n return { error: __agentOsWasiErrnoBadf };\n }\n const guestPath = target.startsWith(\"/\")\n ? __agentOsPath().posix.normalize(target)\n : __agentOsPath().posix.resolve(base.guestPath, target);\n const mapped =\n base.guestPath === \"/\" && !target.startsWith(\"/\")\n ? this._resolveRootRelativePath(\n target,\n options.preferCreateParent === true,\n )\n : {\n guestPath,\n ...(\n this._resolveHostMappingForGuestPath(guestPath) ??\n { hostPath: null, readOnly: false }\n ),\n };\n const hostPath = mapped.hostPath;\n if (typeof hostPath !== \"string\") {\n return { error: __agentOsWasiErrnoNoent };\n }\n return {\n error: __agentOsWasiErrnoSuccess,\n guestPath: mapped.guestPath,\n hostPath,\n readOnly: mapped.readOnly === true,\n };\n }\n\n _resolvedFsPath(resolved) {\n if (this._sidecarManagedProcess() && typeof resolved?.guestPath === \"string\") {\n return resolved.guestPath;\n }\n return resolved?.hostPath ?? null;\n }\n\n _writeFilestat(statPtr, stats, fallbackType) {\n try {\n const view = this._memoryView();\n const offset = Number(statPtr) >>> 0;\n const filetype = stats ? this._filetypeForStats(stats) : fallbackType;\n view.setBigUint64(offset, 0n, true);\n view.setBigUint64(offset + 8, BigInt(stats?.ino ?? 0), true);\n view.setUint8(offset + 16, filetype);\n view.setBigUint64(offset + 24, BigInt(stats?.nlink ?? 1), true);\n view.setBigUint64(offset + 32, BigInt(stats?.size ?? 0), true);\n view.setBigUint64(offset + 40, BigInt(Math.trunc((stats?.atimeMs ?? 0) * 1000000)), true);\n view.setBigUint64(offset + 48, BigInt(Math.trunc((stats?.mtimeMs ?? 0) * 1000000)), true);\n view.setBigUint64(offset + 56, BigInt(Math.trunc((stats?.ctimeMs ?? 0) * 1000000)), true);\n return __agentOsWasiErrnoSuccess;\n } catch (error) {\n return this._mapFsError(error);\n }\n }\n\n _argsSizesGet(argcPtr, argvBufSizePtr) {\n const values = this._stringTable(this.args);\n const total = values.reduce((sum, value) => sum + value.length, 0);\n const argcStatus = this._writeUint32(argcPtr, values.length);\n if (argcStatus !== __agentOsWasiErrnoSuccess) {\n return argcStatus;\n }\n return this._writeUint32(argvBufSizePtr, total);\n }\n\n _argsGet(argvPtr, argvBufPtr) {\n return this._writeStringTable(this._stringTable(this.args), argvPtr, argvBufPtr);\n }\n\n _environEntries() {\n return Object.entries(this.env).map(([key, value]) => `${key}=${value}`);\n }\n\n _environSizesGet(countPtr, bufSizePtr) {\n const values = this._stringTable(this._environEntries());\n const total = values.reduce((sum, value) => sum + value.length, 0);\n const countStatus = this._writeUint32(countPtr, values.length);\n if (countStatus !== __agentOsWasiErrnoSuccess) {\n return countStatus;\n }\n return this._writeUint32(bufSizePtr, total);\n }\n\n _environGet(environPtr, environBufPtr) {\n return this._writeStringTable(\n this._stringTable(this._environEntries()),\n environPtr,\n environBufPtr,\n );\n }\n\n _clockTimeGet(_clockId, _precision, resultPtr) {\n return this._writeUint64(resultPtr, BigInt(Date.now()) * 1000000n);\n }\n\n _clockResGet(_clockId, resultPtr) {\n return this._writeUint64(resultPtr, 1000000n);\n }\n\n _fdWrite(fd, iovs, iovsLen, nwrittenPtr) {\n try {\n const bytes = this._collectIovs(iovs, iovsLen);\n const descriptor = Number(fd) >>> 0;\n const handle = this._externalFdHandle(descriptor);\n if (handle?.kind === \"pipe-write\" && handle.pipe) {\n if (bytes.length > 0 && !this._pipeHasReaders(handle.pipe)) {\n return __agentOsWasiErrnoPipe;\n }\n this._enqueuePipeBytes(handle.pipe, bytes);\n this._flushPipeConsumers(handle.pipe);\n return this._writeUint32(nwrittenPtr, bytes.length);\n }\n if (\n (handle?.kind === \"passthrough\" || handle?.kind === \"host-passthrough\") &&\n typeof handle.targetFd === \"number\"\n ) {\n if (handle.readOnly === true) {\n return __agentOsWasiErrnoRofs;\n }\n if (descriptor === 1 || descriptor === 2) {\n const sidecarManagedProcess =\n typeof process?.env?.AGENT_OS_SANDBOX_ROOT === \"string\" &&\n process.env.AGENT_OS_SANDBOX_ROOT.length > 0;\n const useKernelStdioSyncRpc =\n sidecarManagedProcess || __agentOsKernelStdioSyncRpcEnabled();\n if (useKernelStdioSyncRpc) {\n const written = Number(\n __agentOsWasiSyncRpc().callSync(\"__kernel_stdio_write\", [descriptor, bytes]),\n ) >>> 0;\n return this._writeUint32(nwrittenPtr, written);\n }\n }\n const written = __agentOsFs().writeSync(\n handle.targetFd,\n bytes,\n 0,\n bytes.length,\n null,\n );\n return this._writeUint32(nwrittenPtr, written);\n }\n if (handle?.kind === \"guest-file\" && typeof handle.targetFd === \"number\") {\n const position = handle.append ? null : (handle.position ?? 0);\n const written = __agentOsFs().writeSync(\n handle.targetFd,\n bytes,\n 0,\n bytes.length,\n position,\n );\n if (handle.append) {\n handle.position = Number(__agentOsFs().fstatSync(handle.targetFd).size ?? 0);\n } else {\n handle.position = (handle.position ?? 0) + written;\n }\n return this._writeUint32(nwrittenPtr, written);\n }\n const entry = this.fdTable.get(descriptor);\n if (!entry) {\n return __agentOsWasiErrnoBadf;\n }\n if (entry.kind === \"stdout\") {\n const sidecarManagedProcess =\n typeof process?.env?.AGENT_OS_SANDBOX_ROOT === \"string\" &&\n process.env.AGENT_OS_SANDBOX_ROOT.length > 0;\n const useKernelStdioSyncRpc =\n sidecarManagedProcess || __agentOsKernelStdioSyncRpcEnabled();\n const written = useKernelStdioSyncRpc\n ? Number(__agentOsWasiSyncRpc().callSync(\"__kernel_stdio_write\", [1, bytes])) >>> 0\n : (process.stdout.write(bytes), bytes.length);\n return this._writeUint32(nwrittenPtr, written);\n }\n if (entry.kind === \"stderr\") {\n const sidecarManagedProcess =\n typeof process?.env?.AGENT_OS_SANDBOX_ROOT === \"string\" &&\n process.env.AGENT_OS_SANDBOX_ROOT.length > 0;\n const useKernelStdioSyncRpc =\n sidecarManagedProcess || __agentOsKernelStdioSyncRpcEnabled();\n const written = useKernelStdioSyncRpc\n ? Number(__agentOsWasiSyncRpc().callSync(\"__kernel_stdio_write\", [2, bytes])) >>> 0\n : (process.stderr.write(bytes), bytes.length);\n return this._writeUint32(nwrittenPtr, written);\n }\n if (entry.readOnly === true) {\n return __agentOsWasiErrnoRofs;\n }\n if (entry.kind === \"file\") {\n const position = typeof entry.offset === \"number\" ? entry.offset : null;\n const written = __agentOsFs().writeSync(\n entry.realFd,\n bytes,\n 0,\n bytes.length,\n position,\n );\n if (typeof entry.offset === \"number\") {\n entry.offset += written;\n }\n return this._writeUint32(nwrittenPtr, written);\n }\n return __agentOsWasiErrnoBadf;\n } catch (error) {\n return this._mapFsError(error);\n }\n }\n\n _fdPwrite(fd, iovs, iovsLen, offset, nwrittenPtr) {\n try {\n const bytes = this._collectIovs(iovs, iovsLen);\n const descriptor = Number(fd) >>> 0;\n const handle = this._externalFdHandle(descriptor);\n if (\n (handle?.kind === \"passthrough\" || handle?.kind === \"host-passthrough\") &&\n typeof handle.targetFd === \"number\"\n ) {\n if (handle.readOnly === true) {\n return __agentOsWasiErrnoRofs;\n }\n const written = __agentOsFs().writeSync(\n handle.targetFd,\n bytes,\n 0,\n bytes.length,\n Number(offset) >>> 0,\n );\n return this._writeUint32(nwrittenPtr, written);\n }\n const entry = this.fdTable.get(descriptor);\n if (!entry || entry.kind !== \"file\") {\n return __agentOsWasiErrnoBadf;\n }\n if (entry.readOnly === true) {\n return __agentOsWasiErrnoRofs;\n }\n const written = __agentOsFs().writeSync(\n entry.realFd,\n bytes,\n 0,\n bytes.length,\n Number(offset) >>> 0,\n );\n return this._writeUint32(nwrittenPtr, written);\n } catch {\n return __agentOsWasiErrnoFault;\n }\n }\n\n _fdPread(fd, iovs, iovsLen, offset, nreadPtr) {\n try {\n const descriptor = Number(fd) >>> 0;\n const explicitOffset = Number(offset) >>> 0;\n const totalLength = this._boundedIovLength(iovs, iovsLen);\n const buffer = Buffer.alloc(totalLength);\n const handle = this._externalFdHandle(descriptor);\n if (\n (handle?.kind === \"passthrough\" || handle?.kind === \"host-passthrough\") &&\n typeof handle.targetFd === \"number\"\n ) {\n const bytesRead = __agentOsFs().readSync(\n handle.targetFd,\n buffer,\n 0,\n totalLength,\n explicitOffset,\n );\n const written = this._writeToIovs(iovs, iovsLen, buffer.subarray(0, bytesRead));\n return this._writeUint32(nreadPtr, written);\n }\n const entry = this.fdTable.get(descriptor);\n if (!entry || entry.kind !== \"file\") {\n return __agentOsWasiErrnoBadf;\n }\n const bytesRead = __agentOsFs().readSync(\n entry.realFd,\n buffer,\n 0,\n totalLength,\n explicitOffset,\n );\n const written = this._writeToIovs(iovs, iovsLen, buffer.subarray(0, bytesRead));\n return this._writeUint32(nreadPtr, written);\n } catch {\n return __agentOsWasiErrnoFault;\n }\n }\n\n _fdRead(fd, iovs, iovsLen, nreadPtr) {\n try {\n const descriptor = Number(fd) >>> 0;\n const handle = this._externalFdHandle(descriptor);\n if (handle?.kind === \"pipe-read\" && handle.pipe) {\n const totalLength = this._boundedIovLength(iovs, iovsLen);\n while (handle.pipe.chunks.length === 0) {\n if (handle.pipe.writeHandleCount === 0 && handle.pipe.producers.size === 0) {\n return this._writeUint32(nreadPtr, 0);\n }\n this._pumpPipeProducers(handle.pipe, 10);\n }\n const chunk = this._dequeuePipeBytes(handle.pipe, totalLength);\n const written = this._writeToIovs(iovs, iovsLen, chunk);\n return this._writeUint32(nreadPtr, written);\n }\n const entry = this.fdTable.get(descriptor);\n if (!entry) {\n return __agentOsWasiErrnoBadf;\n }\n if (entry.kind === \"stdin\") {\n const totalLength = this._boundedIovLength(iovs, iovsLen);\n const syncRpc =\n typeof globalThis?.__agentOsSyncRpc?.callSync === \"function\"\n ? __agentOsWasiSyncRpc()\n : null;\n const sidecarManagedProcess =\n typeof process?.env?.AGENT_OS_SANDBOX_ROOT === \"string\" &&\n process.env.AGENT_OS_SANDBOX_ROOT.length > 0;\n if (syncRpc && (sidecarManagedProcess || __agentOsKernelStdioSyncRpcEnabled())) {\n try {\n let chunk = null;\n while (true) {\n const response = syncRpc.callSync(\"__kernel_stdin_read\", [totalLength, 10]);\n if (\n response &&\n typeof response === \"object\" &&\n typeof response.dataBase64 === \"string\"\n ) {\n chunk = Buffer.from(response.dataBase64, \"base64\");\n break;\n }\n if (response && typeof response === \"object\" && response.done === true) {\n chunk = Buffer.alloc(0);\n break;\n }\n if (\n typeof Atomics?.wait === \"function\" &&\n typeof syntheticWaitArray !== \"undefined\"\n ) {\n Atomics.wait(syntheticWaitArray, 0, 0, 10);\n }\n }\n if (!chunk || chunk.length === 0) {\n return this._writeUint32(nreadPtr, 0);\n }\n const written = this._writeToIovs(iovs, iovsLen, chunk);\n return this._writeUint32(nreadPtr, written);\n } catch {\n // Fall back to direct stdin reads when the sync bridge is unavailable\n // in the standalone runner bootstrap.\n }\n }\n const buffer = Buffer.alloc(totalLength);\n const directStdinFd =\n (handle?.kind === \"passthrough\" || handle?.kind === \"host-passthrough\") &&\n typeof handle.targetFd === \"number\"\n ? handle.targetFd\n : typeof process?.stdin?.fd === \"number\"\n ? process.stdin.fd\n : 0;\n const bytesRead = __agentOsFs().readSync(\n directStdinFd,\n buffer,\n 0,\n totalLength,\n null,\n );\n const written = this._writeToIovs(iovs, iovsLen, buffer.subarray(0, bytesRead));\n return this._writeUint32(nreadPtr, written);\n }\n if (\n (handle?.kind === \"passthrough\" || handle?.kind === \"host-passthrough\") &&\n typeof handle.targetFd === \"number\"\n ) {\n const totalLength = this._boundedIovLength(iovs, iovsLen);\n const buffer = Buffer.alloc(totalLength);\n const bytesRead = __agentOsFs().readSync(\n handle.targetFd,\n buffer,\n 0,\n totalLength,\n null,\n );\n const written = this._writeToIovs(iovs, iovsLen, buffer.subarray(0, bytesRead));\n return this._writeUint32(nreadPtr, written);\n }\n if (entry.kind !== \"file\") {\n return __agentOsWasiErrnoBadf;\n }\n const totalLength = this._boundedIovLength(iovs, iovsLen);\n const buffer = Buffer.alloc(totalLength);\n const position = typeof entry.offset === \"number\" ? entry.offset : null;\n const bytesRead = __agentOsFs().readSync(\n entry.realFd,\n buffer,\n 0,\n totalLength,\n position,\n );\n if (typeof entry.offset === \"number\") {\n entry.offset += bytesRead;\n }\n const written = this._writeToIovs(iovs, iovsLen, buffer.subarray(0, bytesRead));\n return this._writeUint32(nreadPtr, written);\n } catch (error) {\n return this._mapFsError(error);\n }\n }\n\n _fdClose(fd) {\n try {\n const descriptor = Number(fd) >>> 0;\n const entry = this.fdTable.get(descriptor);\n if (!entry) {\n return __agentOsWasiErrnoBadf;\n }\n const retainedDelegateRefs = (() => {\n try {\n if (typeof globalThis.__agentOsWasiDelegateFdRefCount === \"function\") {\n return Number(globalThis.__agentOsWasiDelegateFdRefCount(descriptor)) || 0;\n }\n } catch {\n // Fall through to the default close path.\n }\n return 0;\n })();\n if (entry.kind === \"file\" && retainedDelegateRefs <= 0) {\n __agentOsFs().closeSync(entry.realFd);\n }\n if (descriptor > 2 && retainedDelegateRefs <= 0) {\n this.fdTable.delete(descriptor);\n }\n return __agentOsWasiErrnoSuccess;\n } catch {\n return __agentOsWasiErrnoFault;\n }\n }\n\n _fdSync(fd) {\n try {\n const descriptor = Number(fd) >>> 0;\n const handle = this._externalFdHandle(descriptor);\n if (\n (handle?.kind === \"passthrough\" || handle?.kind === \"host-passthrough\") &&\n typeof handle.targetFd === \"number\"\n ) {\n __agentOsFs().fsyncSync(handle.targetFd);\n return __agentOsWasiErrnoSuccess;\n }\n const entry = this.fdTable.get(descriptor);\n if (!entry || entry.kind !== \"file\" || typeof entry.realFd !== \"number\") {\n return __agentOsWasiErrnoBadf;\n }\n __agentOsFs().fsyncSync(entry.realFd);\n return __agentOsWasiErrnoSuccess;\n } catch {\n return __agentOsWasiErrnoFault;\n }\n }\n\n _fdFdstatGet(fd, statPtr) {\n try {\n const entry = this._descriptorEntry(fd);\n if (!entry) {\n return __agentOsWasiErrnoBadf;\n }\n const view = this._memoryView();\n const offset = Number(statPtr) >>> 0;\n view.setUint8(offset, this._fdFiletype(entry));\n view.setUint16(offset + 2, (Number(entry.fdFlags) >>> 0) & 0xffff, true);\n view.setBigUint64(offset + 8, this._descriptorRightsBase(entry), true);\n view.setBigUint64(offset + 16, this._descriptorRightsInheriting(entry), true);\n return __agentOsWasiErrnoSuccess;\n } catch {\n return __agentOsWasiErrnoFault;\n }\n }\n\n _fdFdstatSetFlags(fd, flags) {\n try {\n const entry = this._descriptorEntry(fd);\n if (!entry) {\n return __agentOsWasiErrnoBadf;\n }\n entry.fdFlags = (Number(flags) >>> 0) & 0xffff;\n return __agentOsWasiErrnoSuccess;\n } catch {\n return __agentOsWasiErrnoFault;\n }\n }\n\n _fdFilestatGet(fd, statPtr) {\n try {\n const entry = this._descriptorEntry(fd);\n if (!entry) {\n return __agentOsWasiErrnoBadf;\n }\n if (\n entry.kind === \"stdin\" ||\n entry.kind === \"stdout\" ||\n entry.kind === \"stderr\"\n ) {\n return this._writeFilestat(statPtr, null, __agentOsWasiFiletypeCharacterDevice);\n }\n if (entry.kind === \"preopen\") {\n const stats = __agentOsFs().statSync(entry.guestPath);\n return this._writeFilestat(statPtr, stats, __agentOsWasiFiletypeDirectory);\n }\n const stats =\n typeof entry.realFd === \"number\"\n ? __agentOsFs().fstatSync(entry.realFd)\n : __agentOsFs().statSync(this._descriptorFsPath(entry));\n return this._writeFilestat(statPtr, stats, this._fdFiletype(entry));\n } catch (error) {\n return this._mapFsError(error);\n }\n }\n\n _fdFilestatSetSize(fd, size) {\n try {\n const entry = this._descriptorEntry(fd);\n if (!entry || entry.kind !== \"file\" || typeof entry.realFd !== \"number\") {\n return __agentOsWasiErrnoBadf;\n }\n if (entry.readOnly === true) {\n return __agentOsWasiErrnoRofs;\n }\n __agentOsFs().ftruncateSync(entry.realFd, Number(size));\n return __agentOsWasiErrnoSuccess;\n } catch (error) {\n return this._mapFsError(error);\n }\n }\n\n _fdSeek(fd, offset, whence, newOffsetPtr) {\n try {\n const entry = this._descriptorEntry(fd);\n if (!entry || entry.kind !== \"file\" || typeof entry.realFd !== \"number\") {\n return __agentOsWasiErrnoBadf;\n }\n const delta = Number(offset);\n if (!Number.isFinite(delta)) {\n return __agentOsWasiErrnoInval;\n }\n const currentOffset = typeof entry.offset === \"number\" ? entry.offset : 0;\n let nextOffset = 0;\n switch (Number(whence) >>> 0) {\n case __agentOsWasiWhenceSet:\n nextOffset = delta;\n break;\n case __agentOsWasiWhenceCur:\n nextOffset = currentOffset + delta;\n break;\n case __agentOsWasiWhenceEnd: {\n const stats = __agentOsFs().fstatSync(entry.realFd);\n nextOffset = Number(stats?.size ?? 0) + delta;\n break;\n }\n default:\n return __agentOsWasiErrnoInval;\n }\n if (!Number.isFinite(nextOffset) || nextOffset < 0) {\n return __agentOsWasiErrnoInval;\n }\n entry.offset = nextOffset;\n return this._writeUint64(newOffsetPtr, BigInt(nextOffset));\n } catch (error) {\n return this._mapFsError(error);\n }\n }\n\n _fdTell(fd, offsetPtr) {\n try {\n const entry = this._descriptorEntry(fd);\n if (!entry || entry.kind !== \"file\") {\n return __agentOsWasiErrnoBadf;\n }\n const offset = typeof entry.offset === \"number\" ? entry.offset : 0;\n return this._writeUint64(offsetPtr, BigInt(offset));\n } catch (error) {\n return this._mapFsError(error);\n }\n }\n\n _fdPrestatGet(fd, prestatPtr) {\n try {\n const entry = this._descriptorEntry(fd);\n if (!entry || entry.kind !== \"preopen\") {\n return __agentOsWasiErrnoBadf;\n }\n const guestPath = this._descriptorPreopenName(entry);\n if (typeof guestPath !== \"string\") {\n return __agentOsWasiErrnoBadf;\n }\n const view = this._memoryView();\n const offset = Number(prestatPtr) >>> 0;\n view.setUint8(offset, 0);\n view.setUint32(offset + 4, Buffer.byteLength(guestPath), true);\n return __agentOsWasiErrnoSuccess;\n } catch {\n return __agentOsWasiErrnoFault;\n }\n }\n\n _fdPrestatDirName(fd, pathPtr, pathLen) {\n try {\n const entry = this._descriptorEntry(fd);\n if (!entry || entry.kind !== \"preopen\") {\n return __agentOsWasiErrnoBadf;\n }\n const guestPath = this._descriptorPreopenName(entry);\n if (typeof guestPath !== \"string\") {\n return __agentOsWasiErrnoBadf;\n }\n const bytes = Buffer.from(guestPath, \"utf8\");\n if ((Number(pathLen) >>> 0) < bytes.length) {\n return __agentOsWasiErrnoFault;\n }\n return this._writeBytes(pathPtr, bytes);\n } catch {\n return __agentOsWasiErrnoFault;\n }\n }\n\n _fdReaddir(fd, bufPtr, bufLen, cookie, bufUsedPtr) {\n try {\n const entry = this._descriptorEntry(fd);\n const fsPath = this._descriptorDirectoryFsPath(entry);\n if (\n !entry ||\n (entry.kind !== \"preopen\" && entry.kind !== \"directory\") ||\n typeof fsPath !== \"string\"\n ) {\n return __agentOsWasiErrnoBadf;\n }\n const dirents = __agentOsFs()\n .readdirSync(fsPath, { withFileTypes: true })\n .sort((left, right) => left.name.localeCompare(right.name));\n const view = this._memoryView();\n const memory = this._memoryBytes();\n let offset = Number(bufPtr) >>> 0;\n const limit = offset + (Number(bufLen) >>> 0);\n let used = 0;\n for (let index = Number(cookie) >>> 0; index < dirents.length; index += 1) {\n const dirent = dirents[index];\n const nameBytes = Buffer.from(dirent.name, \"utf8\");\n const recordLen = 24 + nameBytes.length;\n if (offset + recordLen > limit) {\n break;\n }\n view.setBigUint64(offset, BigInt(index + 1), true);\n view.setBigUint64(offset + 8, BigInt(index + 1), true);\n view.setUint32(offset + 16, nameBytes.length, true);\n view.setUint8(\n offset + 20,\n dirent.isDirectory()\n ? __agentOsWasiFiletypeDirectory\n : dirent.isSymbolicLink()\n ? __agentOsWasiFiletypeSymbolicLink\n : __agentOsWasiFiletypeRegularFile,\n );\n memory.set(nameBytes, offset + 24);\n offset += recordLen;\n used += recordLen;\n }\n return this._writeUint32(bufUsedPtr, used);\n } catch (error) {\n return this._mapFsError(error);\n }\n }\n\n _pathCreateDirectory(fd, pathPtr, pathLen) {\n try {\n const resolved = this._resolveDescriptorPath(fd, pathPtr, pathLen);\n if (resolved.error !== __agentOsWasiErrnoSuccess) {\n return resolved.error;\n }\n if (resolved.readOnly) {\n return __agentOsWasiErrnoRofs;\n }\n __agentOsFs().mkdirSync(this._resolvedFsPath(resolved));\n return __agentOsWasiErrnoSuccess;\n } catch (error) {\n return this._mapFsError(error);\n }\n }\n\n _pathLink(oldFd, _oldFlags, oldPathPtr, oldPathLen, newFd, newPathPtr, newPathLen) {\n try {\n const source = this._resolveDescriptorPath(oldFd, oldPathPtr, oldPathLen);\n if (source.error !== __agentOsWasiErrnoSuccess) {\n return source.error;\n }\n const destination = this._resolveDescriptorPath(newFd, newPathPtr, newPathLen);\n if (destination.error !== __agentOsWasiErrnoSuccess) {\n return destination.error;\n }\n if (source.readOnly || destination.readOnly) {\n return __agentOsWasiErrnoRofs;\n }\n __agentOsFs().linkSync(this._resolvedFsPath(source), this._resolvedFsPath(destination));\n return __agentOsWasiErrnoSuccess;\n } catch (error) {\n return this._mapFsError(error);\n }\n }\n\n _pathOpen(fd, _dirflags, pathPtr, pathLen, oflags, rightsBase, rightsInheriting, _fdflags, openedFdPtr) {\n try {\n const entry = this._descriptorEntry(fd);\n if (\n !entry ||\n (entry.kind !== \"preopen\" && entry.kind !== \"directory\") ||\n typeof entry.hostPath !== \"string\"\n ) {\n return __agentOsWasiErrnoBadf;\n }\n const requestedFlags = Number(oflags) >>> 0;\n const createOrTruncate =\n (requestedFlags & __agentOsWasiOpenCreate) !== 0 ||\n (requestedFlags & __agentOsWasiOpenTruncate) !== 0;\n const resolved = this._resolveDescriptorPath(fd, pathPtr, pathLen, {\n preferCreateParent: createOrTruncate,\n });\n if (resolved.error !== __agentOsWasiErrnoSuccess) {\n return resolved.error;\n }\n const guestPath = resolved.guestPath;\n const fsPath = this._resolvedFsPath(resolved);\n const openDirectory = (requestedFlags & __agentOsWasiOpenDirectory) !== 0;\n const allowedRightsBase = this._descriptorRightsBase(entry);\n const allowedRightsInheriting = this._descriptorRightsInheriting(entry);\n const requestedRightsBase = this._normalizeRights(rightsBase, allowedRightsInheriting);\n const requestedRightsInheriting = this._normalizeRights(\n rightsInheriting,\n allowedRightsInheriting,\n );\n if (\n (requestedRightsBase & ~allowedRightsInheriting) !== 0n ||\n (requestedRightsInheriting & ~allowedRightsInheriting) !== 0n\n ) {\n return __agentOsWasiErrnoAcces;\n }\n const requestedWriteAccess =\n !openDirectory &&\n (createOrTruncate || this._hasWriteRights(requestedRightsBase));\n if (\n requestedWriteAccess &&\n !this._hasWriteRights(allowedRightsBase)\n ) {\n return __agentOsWasiErrnoAcces;\n }\n if (requestedWriteAccess && resolved.readOnly) {\n return __agentOsWasiErrnoRofs;\n }\n const fsConstants = __agentOsFs().constants ?? {};\n let openFlags = requestedWriteAccess\n ? fsConstants.O_RDWR ?? 2\n : fsConstants.O_RDONLY ?? 0;\n if ((requestedFlags & __agentOsWasiOpenCreate) !== 0) {\n openFlags |= fsConstants.O_CREAT ?? 64;\n }\n if ((requestedFlags & __agentOsWasiOpenExclusive) !== 0) {\n openFlags |= fsConstants.O_EXCL ?? 128;\n }\n if ((requestedFlags & __agentOsWasiOpenTruncate) !== 0) {\n openFlags |= fsConstants.O_TRUNC ?? 512;\n }\n if (openDirectory) {\n openFlags |= fsConstants.O_DIRECTORY ?? 0;\n }\n if (createOrTruncate && !openDirectory) {\n __agentOsFs().statSync(__agentOsPath().dirname(fsPath));\n } else {\n __agentOsFs().statSync(fsPath);\n }\n const realFd = __agentOsFs().openSync(fsPath, openFlags);\n const stats =\n createOrTruncate && !openDirectory\n ? __agentOsFs().fstatSync(realFd)\n : __agentOsFs().statSync(fsPath);\n const openedFd = this.nextFd++;\n this.fdTable.set(openedFd, {\n kind: stats.isDirectory() ? \"directory\" : \"file\",\n guestPath,\n hostPath: fsPath,\n readOnly: resolved.readOnly === true,\n realFd,\n offset: 0,\n rightsBase: requestedRightsBase & allowedRightsInheriting,\n rightsInheriting: requestedRightsInheriting & allowedRightsInheriting,\n fdFlags: (Number(_fdflags) >>> 0) & 0xffff,\n });\n return this._writeUint32(openedFdPtr, openedFd);\n } catch (error) {\n return this._mapFsError(error);\n }\n }\n\n _pathSymlink(targetPtr, targetLen, fd, pathPtr, pathLen) {\n try {\n const resolved = this._resolveDescriptorPath(fd, pathPtr, pathLen);\n if (resolved.error !== __agentOsWasiErrnoSuccess) {\n return resolved.error;\n }\n if (resolved.readOnly) {\n return __agentOsWasiErrnoRofs;\n }\n const target = this._readString(targetPtr, targetLen);\n __agentOsFs().symlinkSync(target, this._resolvedFsPath(resolved));\n return __agentOsWasiErrnoSuccess;\n } catch (error) {\n return this._mapFsError(error);\n }\n }\n\n _pathRemoveDirectory(fd, pathPtr, pathLen) {\n try {\n const resolved = this._resolveDescriptorPath(fd, pathPtr, pathLen);\n if (resolved.error !== __agentOsWasiErrnoSuccess) {\n return resolved.error;\n }\n if (resolved.readOnly) {\n return __agentOsWasiErrnoRofs;\n }\n __agentOsFs().rmdirSync(this._resolvedFsPath(resolved));\n return __agentOsWasiErrnoSuccess;\n } catch (error) {\n return this._mapFsError(error);\n }\n }\n\n _pathRename(oldFd, oldPathPtr, oldPathLen, newFd, newPathPtr, newPathLen) {\n try {\n const source = this._resolveDescriptorPath(oldFd, oldPathPtr, oldPathLen);\n if (source.error !== __agentOsWasiErrnoSuccess) {\n return source.error;\n }\n const destination = this._resolveDescriptorPath(newFd, newPathPtr, newPathLen);\n if (destination.error !== __agentOsWasiErrnoSuccess) {\n return destination.error;\n }\n if (source.readOnly || destination.readOnly) {\n return __agentOsWasiErrnoRofs;\n }\n __agentOsFs().renameSync(this._resolvedFsPath(source), this._resolvedFsPath(destination));\n return __agentOsWasiErrnoSuccess;\n } catch (error) {\n return this._mapFsError(error);\n }\n }\n\n _pathUnlinkFile(fd, pathPtr, pathLen) {\n try {\n const resolved = this._resolveDescriptorPath(fd, pathPtr, pathLen);\n if (resolved.error !== __agentOsWasiErrnoSuccess) {\n return resolved.error;\n }\n if (resolved.readOnly) {\n return __agentOsWasiErrnoRofs;\n }\n __agentOsFs().unlinkSync(this._resolvedFsPath(resolved));\n return __agentOsWasiErrnoSuccess;\n } catch (error) {\n return this._mapFsError(error);\n }\n }\n\n _pathFilestatGet(fd, flags, pathPtr, pathLen, statPtr) {\n try {\n const resolved = this._resolveDescriptorPath(fd, pathPtr, pathLen);\n if (resolved.error !== __agentOsWasiErrnoSuccess) {\n return resolved.error;\n }\n const follow = (Number(flags) & __agentOsWasiLookupSymlinkFollow) !== 0;\n const stats = follow\n ? __agentOsFs().statSync(this._resolvedFsPath(resolved))\n : __agentOsFs().lstatSync(this._resolvedFsPath(resolved));\n return this._writeFilestat(statPtr, stats, this._filetypeForStats(stats));\n } catch (error) {\n return this._mapFsError(error);\n }\n }\n\n _pathReadlink(fd, pathPtr, pathLen, bufPtr, bufLen, bufUsedPtr) {\n try {\n const resolved = this._resolveDescriptorPath(fd, pathPtr, pathLen);\n if (resolved.error !== __agentOsWasiErrnoSuccess) {\n return resolved.error;\n }\n const bytes = Buffer.from(__agentOsFs().readlinkSync(resolved.guestPath), \"utf8\");\n const length = Math.min(bytes.length, Number(bufLen) >>> 0);\n const writeStatus = this._writeBytes(bufPtr, bytes.subarray(0, length));\n if (writeStatus !== __agentOsWasiErrnoSuccess) {\n return writeStatus;\n }\n return this._writeUint32(bufUsedPtr, length);\n } catch (error) {\n return this._mapFsError(error);\n }\n }\n\n _pollOneoff(inPtr, outPtr, nsubscriptions, neventsPtr) {\n try {\n const subscriptionCount = Number(nsubscriptions) >>> 0;\n if (subscriptionCount === 0) {\n return this._writeUint32(neventsPtr, 0);\n }\n\n const subscriptionSize = 48;\n const eventSize = 32;\n const kernelPollIn = 0x0001;\n const kernelPollOut = 0x0004;\n const kernelPollErr = 0x0008;\n const kernelPollHup = 0x0010;\n const view = this._memoryView();\n const memory = this._memoryBytes();\n const syncRpc =\n typeof globalThis?.__agentOsSyncRpc?.callSync === \"function\"\n ? __agentOsWasiSyncRpc()\n : null;\n const subscriptions = [];\n let timeoutMs = null;\n\n for (let index = 0; index < subscriptionCount; index += 1) {\n const base = (Number(inPtr) >>> 0) + index * subscriptionSize;\n const tag = view.getUint8(base + 8);\n const userdata = memory.slice(base, base + 8);\n if (tag === 0) {\n const timeoutNs = view.getBigUint64(base + 24, true);\n const relativeTimeoutMs = Number(timeoutNs / 1000000n);\n timeoutMs =\n timeoutMs == null ? relativeTimeoutMs : Math.min(timeoutMs, relativeTimeoutMs);\n subscriptions.push({ kind: \"clock\", userdata });\n continue;\n }\n\n if (tag !== 1 && tag !== 2) {\n subscriptions.push({ kind: \"unsupported\", userdata });\n continue;\n }\n\n const fd = view.getUint32(base + 16, true);\n const descriptor = Number(fd) >>> 0;\n const handle = this._externalFdHandle(descriptor);\n const entry = this._descriptorEntry(descriptor);\n let targetFd = null;\n if (\n (handle?.kind === \"passthrough\" || handle?.kind === \"host-passthrough\") &&\n typeof handle.targetFd === \"number\"\n ) {\n targetFd = Number(handle.targetFd) >>> 0;\n } else if (\n entry?.kind === \"stdin\" ||\n entry?.kind === \"stdout\" ||\n entry?.kind === \"stderr\"\n ) {\n targetFd = descriptor;\n }\n\n subscriptions.push({\n kind: tag === 1 ? \"fd_read\" : \"fd_write\",\n fd: descriptor,\n handle,\n targetFd,\n userdata,\n });\n }\n\n const deadline = timeoutMs == null ? null : Date.now() + Math.max(0, timeoutMs);\n const readyEvents = [];\n\n while (readyEvents.length === 0) {\n for (const subscription of subscriptions) {\n if (subscription.kind === \"fd_read\" && subscription.handle?.kind === \"pipe-read\") {\n const pipe = subscription.handle.pipe;\n if (\n pipe &&\n (pipe.chunks.length > 0 ||\n (pipe.writeHandleCount === 0 && pipe.producers.size === 0))\n ) {\n readyEvents.push({\n userdata: subscription.userdata,\n error: __agentOsWasiErrnoSuccess,\n type: 1,\n nbytes: pipe.chunks[0]?.length ?? 0,\n flags: 0,\n });\n }\n continue;\n }\n\n if (subscription.kind === \"fd_write\" && subscription.handle?.kind === \"pipe-write\") {\n readyEvents.push({\n userdata: subscription.userdata,\n error: __agentOsWasiErrnoSuccess,\n type: 2,\n nbytes: 65536,\n flags: 0,\n });\n }\n }\n\n if (readyEvents.length > 0) {\n break;\n }\n\n const pollTargets = subscriptions\n .filter(\n (subscription) =>\n (subscription.kind === \"fd_read\" || subscription.kind === \"fd_write\") &&\n typeof subscription.targetFd === \"number\",\n )\n .map((subscription) => ({\n fd: subscription.targetFd,\n events: subscription.kind === \"fd_read\" ? kernelPollIn : kernelPollOut,\n }));\n const waitMs =\n deadline == null ? 10 : Math.max(0, Math.min(10, deadline - Date.now()));\n\n if (syncRpc && pollTargets.length > 0) {\n let response = null;\n try {\n response = syncRpc.callSync(\"__kernel_poll\", [pollTargets, waitMs]);\n } catch (error) {\n __agentOsWasiDebug(\n `poll_oneoff __kernel_poll failed: ${\n error instanceof Error ? error.message : String(error)\n }`,\n );\n }\n\n const responseEntries = Array.isArray(response?.fds) ? response.fds : [];\n for (const subscription of subscriptions) {\n if (\n (subscription.kind !== \"fd_read\" && subscription.kind !== \"fd_write\") ||\n typeof subscription.targetFd !== \"number\"\n ) {\n continue;\n }\n\n const responseEntry = responseEntries.find(\n (entry) => (Number(entry?.fd) >>> 0) === subscription.targetFd,\n );\n const revents = Number(responseEntry?.revents) >>> 0;\n const interested =\n subscription.kind === \"fd_read\"\n ? kernelPollIn | kernelPollErr | kernelPollHup\n : kernelPollOut | kernelPollErr | kernelPollHup;\n if ((revents & interested) === 0) {\n continue;\n }\n\n readyEvents.push({\n userdata: subscription.userdata,\n error: __agentOsWasiErrnoSuccess,\n type: subscription.kind === \"fd_read\" ? 1 : 2,\n nbytes: subscription.kind === \"fd_read\" ? 1 : 65536,\n flags: 0,\n });\n }\n }\n\n if (readyEvents.length > 0) {\n break;\n }\n\n let pumped = false;\n for (const subscription of subscriptions) {\n if (subscription.kind === \"fd_read\" && subscription.handle?.kind === \"pipe-read\") {\n pumped = this._pumpPipeProducers(subscription.handle.pipe, 10) || pumped;\n }\n }\n\n if (pumped) {\n continue;\n }\n\n if (deadline != null && Date.now() >= deadline) {\n break;\n }\n\n if (\n pollTargets.length === 0 &&\n typeof Atomics?.wait !== \"function\" &&\n deadline == null\n ) {\n break;\n }\n\n if (\n typeof Atomics?.wait === \"function\" &&\n typeof syntheticWaitArray !== \"undefined\"\n ) {\n Atomics.wait(syntheticWaitArray, 0, 0, waitMs);\n } else if (!syncRpc && pollTargets.length === 0) {\n break;\n }\n }\n\n if (\n readyEvents.length === 0 &&\n subscriptions.some((subscription) => subscription.kind === \"clock\")\n ) {\n const clockSubscription = subscriptions.find(\n (subscription) => subscription.kind === \"clock\",\n );\n readyEvents.push({\n userdata: clockSubscription.userdata,\n error: __agentOsWasiErrnoSuccess,\n type: 0,\n nbytes: 0,\n flags: 0,\n });\n }\n\n for (let index = 0; index < readyEvents.length; index += 1) {\n const base = (Number(outPtr) >>> 0) + index * eventSize;\n const event = readyEvents[index];\n memory.set(event.userdata, base);\n view.setUint16(base + 8, event.error, true);\n view.setUint8(base + 10, event.type);\n view.setBigUint64(base + 16, BigInt(event.nbytes), true);\n view.setUint16(base + 24, event.flags, true);\n }\n\n return this._writeUint32(neventsPtr, readyEvents.length);\n } catch (error) {\n __agentOsWasiDebug(\n `poll_oneoff failed: ${error instanceof Error ? error.message : String(error)}`,\n );\n return __agentOsWasiErrnoFault;\n }\n }\n\n _randomGet(bufPtr, bufLen) {\n try {\n const length = Number(bufLen) >>> 0;\n const bytes = Buffer.allocUnsafe(length);\n __agentOsCrypto().randomFillSync(bytes);\n return this._writeBytes(bufPtr, bytes);\n } catch {\n return __agentOsWasiErrnoFault;\n }\n }\n\n _schedYield() {\n return __agentOsWasiErrnoSuccess;\n }\n\n _procExit(code) {\n if (this.returnOnExit) {\n const error = new Error(`wasi exit(${Number(code) >>> 0})`);\n error.__agentOsWasiExit = true;\n error.code = Number(code) >>> 0;\n throw error;\n }\n process.exit(Number(code) >>> 0);\n }\n }\n\n Object.defineProperty(globalThis, \"__agentOsWasiModule\", {\n configurable: true,\n enumerable: false,\n value: { WASI },\n writable: true,\n });\n}\n\n\t\t// Re-export the shared runner WASI class as the browser wasi module.\n\t\tmodule.exports = { WASI: globalThis.__agentOsWasiModule.WASI };\n\t\tmodule.exports.default = { WASI: globalThis.__agentOsWasiModule.WASI };\n";