@finalai/agent-provider 0.6.0 → 0.8.0
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.
- package/HOSTING.md +3 -3
- package/README.md +47 -14
- package/dist/modules/channel.d.mts +102 -40
- package/dist/modules/channel.mjs +29 -1
- package/dist/modules/channel.mjs.map +3 -3
- package/dist/modules/conformance/sandbox-kit.d.mts +1 -0
- package/dist/modules/conformance/sandbox-kit.mjs +174 -0
- package/dist/modules/conformance/sandbox-kit.mjs.map +3 -3
- package/dist/modules/index.d.mts +1 -0
- package/dist/modules/index.mjs +1 -0
- package/dist/modules/index.mjs.map +2 -2
- package/dist/modules/local-channel-context.d.mts +3 -3
- package/dist/modules/local-channel-context.mjs +25 -14
- package/dist/modules/local-channel-context.mjs.map +2 -2
- package/dist/modules/manifest.d.mts +18 -14
- package/dist/modules/manifest.mjs +11 -5
- package/dist/modules/manifest.mjs.map +2 -2
- package/dist/modules/room-surface.d.mts +17 -32
- package/dist/modules/room-surface.mjs +12 -12
- package/dist/modules/room-surface.mjs.map +3 -3
- package/dist/modules/sandbox/client.mjs +108 -27
- package/dist/modules/sandbox/client.mjs.map +3 -3
- package/dist/modules/sandbox/convenience.mjs +1 -1
- package/dist/modules/sandbox/convenience.mjs.map +2 -2
- package/dist/modules/sandbox/execution-guard.d.mts +1 -0
- package/dist/modules/sandbox/execution-guard.mjs +9 -0
- package/dist/modules/sandbox/execution-guard.mjs.map +2 -2
- package/dist/modules/sandbox/memory-sandbox.mjs +8 -0
- package/dist/modules/sandbox/memory-sandbox.mjs.map +2 -2
- package/dist/modules/sandbox/server.mjs +87 -14
- package/dist/modules/sandbox/server.mjs.map +3 -3
- package/dist/modules/sandbox/types.d.mts +21 -1
- package/dist/modules/sandbox/types.mjs +1 -0
- package/dist/modules/sandbox/types.mjs.map +2 -2
- package/dist/modules/sandbox/wire.d.mts +40 -0
- package/dist/modules/sandbox/wire.mjs +32 -2
- package/dist/modules/sandbox/wire.mjs.map +2 -2
- package/package.json +2 -2
|
@@ -48,6 +48,7 @@ const capabilitiesOf = async (sandbox, mcpChannels = false) => {
|
|
|
48
48
|
if (sandbox.screen != null) capabilities.push(SandboxCapability.Screen);
|
|
49
49
|
if (sandbox.localMcp != null && (mcpChannels || !needsMcpChannels(sandbox)))
|
|
50
50
|
capabilities.push(SandboxCapability.LocalMcp);
|
|
51
|
+
if (sandbox.attachProcess != null) capabilities.push(SandboxCapability.DurableProcesses);
|
|
51
52
|
return capabilities;
|
|
52
53
|
};
|
|
53
54
|
const describeSandbox = async (sandbox, mcpChannels = false) => ({
|
|
@@ -140,6 +141,10 @@ const createHandleRpcMessageHandler = (options) => {
|
|
|
140
141
|
}
|
|
141
142
|
};
|
|
142
143
|
};
|
|
144
|
+
const releaseProcess = async (served) => {
|
|
145
|
+
if (served.detach == null) await served.process.kill();
|
|
146
|
+
else served.detach.abort(new Error("process handle released"));
|
|
147
|
+
};
|
|
143
148
|
const createServerConnection = (args) => {
|
|
144
149
|
let sandbox = null;
|
|
145
150
|
let access = args.access;
|
|
@@ -249,6 +254,21 @@ const createServerConnection = (args) => {
|
|
|
249
254
|
const pump = (streamId, source) => {
|
|
250
255
|
peer.streams.openOutgoing(streamId, source).catch(() => void 0);
|
|
251
256
|
};
|
|
257
|
+
const serve = (args2) => {
|
|
258
|
+
if (args2.signal.aborted || shutdown != null) {
|
|
259
|
+
void releaseProcess(args2.served).catch(() => void 0);
|
|
260
|
+
throw handleRpcError({ code: HandleRpcErrorCode.Cancelled, message: "request cancelled" });
|
|
261
|
+
}
|
|
262
|
+
processes.set(args2.processId, args2.served);
|
|
263
|
+
pump(args2.stdout.streamId, args2.stdout.stream);
|
|
264
|
+
pump(args2.stderr.streamId, args2.stderr.stream);
|
|
265
|
+
};
|
|
266
|
+
const servedProcess = (processId) => {
|
|
267
|
+
const served = processes.get(processId);
|
|
268
|
+
if (served == null)
|
|
269
|
+
throw handleRpcError({ code: HandleRpcErrorCode.NotFound, message: "no such process" });
|
|
270
|
+
return served;
|
|
271
|
+
};
|
|
252
272
|
const mcpDescriptor = (endpoint, key) => {
|
|
253
273
|
if (!isMcpChannelEndpoint(endpoint)) return endpoint;
|
|
254
274
|
if (args.mcpChannels !== true) throw unsupported("MCP channels over the handle RPC");
|
|
@@ -348,6 +368,7 @@ const createServerConnection = (args) => {
|
|
|
348
368
|
message: "processId already in use"
|
|
349
369
|
});
|
|
350
370
|
}
|
|
371
|
+
const detach = params.durable === true ? new AbortController() : null;
|
|
351
372
|
const child = await target.spawn({
|
|
352
373
|
command: params.command,
|
|
353
374
|
args: params.args,
|
|
@@ -356,19 +377,65 @@ const createServerConnection = (args) => {
|
|
|
356
377
|
shell: params.shell,
|
|
357
378
|
timeoutMs: params.timeoutMs,
|
|
358
379
|
// A closed stdin is an empty stream.
|
|
359
|
-
stdin: stdin ?? ""
|
|
380
|
+
stdin: stdin ?? "",
|
|
381
|
+
...detach == null ? {} : { durable: true, abortSignal: detach.signal }
|
|
360
382
|
});
|
|
361
383
|
incomingByRequest.delete(context.id);
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
384
|
+
const ref = child.ref ?? null;
|
|
385
|
+
serve({
|
|
386
|
+
processId: params.processId,
|
|
387
|
+
// A sandbox that ignored `durable` gave an ordinary process.
|
|
388
|
+
served: { process: child, detach: ref == null ? null : detach },
|
|
389
|
+
signal: abortSignal,
|
|
390
|
+
stdout: { streamId: params.stdoutStreamId, stream: child.stdout },
|
|
391
|
+
stderr: { streamId: params.stderrStreamId, stream: child.stderr }
|
|
392
|
+
});
|
|
393
|
+
return { pid: child.pid, ref };
|
|
394
|
+
}
|
|
395
|
+
case HandleRpcMethod.ProcessAttach: {
|
|
396
|
+
const params = parseParams(handleRpcMethodSchemas[method].params, context.params);
|
|
397
|
+
if (target.attachProcess == null) throw unsupported("durable processes");
|
|
398
|
+
if (processes.has(params.processId))
|
|
399
|
+
throw handleRpcError({
|
|
400
|
+
code: HandleRpcErrorCode.InvalidParams,
|
|
401
|
+
message: "processId already in use"
|
|
402
|
+
});
|
|
403
|
+
const detach = new AbortController();
|
|
404
|
+
const cancelAttach = () => detach.abort(abortSignal.reason);
|
|
405
|
+
abortSignal.addEventListener("abort", cancelAttach, { once: true });
|
|
406
|
+
let attached;
|
|
407
|
+
try {
|
|
408
|
+
attached = await target.attachProcess({
|
|
409
|
+
ref: params.ref,
|
|
410
|
+
stdoutOffset: params.stdoutOffset,
|
|
411
|
+
stderrOffset: params.stderrOffset,
|
|
412
|
+
abortSignal: detach.signal
|
|
413
|
+
});
|
|
414
|
+
} finally {
|
|
415
|
+
abortSignal.removeEventListener("abort", cancelAttach);
|
|
416
|
+
}
|
|
417
|
+
if (attached == null)
|
|
418
|
+
return {
|
|
419
|
+
found: false,
|
|
420
|
+
stdoutOffset: params.stdoutOffset,
|
|
421
|
+
stderrOffset: params.stderrOffset
|
|
422
|
+
};
|
|
423
|
+
serve({
|
|
424
|
+
processId: params.processId,
|
|
425
|
+
served: { process: attached, detach },
|
|
426
|
+
signal: abortSignal,
|
|
427
|
+
stdout: { streamId: params.stdoutStreamId, stream: attached.stdout },
|
|
428
|
+
stderr: { streamId: params.stderrStreamId, stream: attached.stderr }
|
|
429
|
+
});
|
|
430
|
+
return {
|
|
431
|
+
found: true,
|
|
432
|
+
stdoutOffset: attached.stdoutOffset,
|
|
433
|
+
stderrOffset: attached.stderrOffset
|
|
434
|
+
};
|
|
366
435
|
}
|
|
367
436
|
case HandleRpcMethod.ProcessWait: {
|
|
368
437
|
const params = parseParams(handleRpcMethodSchemas[method].params, context.params);
|
|
369
|
-
const child =
|
|
370
|
-
if (child == null)
|
|
371
|
-
throw handleRpcError({ code: HandleRpcErrorCode.NotFound, message: "no such process" });
|
|
438
|
+
const child = servedProcess(params.processId).process;
|
|
372
439
|
const result = await new Promise((resolve, reject) => {
|
|
373
440
|
const onAbort = () => reject(handleRpcError({ code: HandleRpcErrorCode.Cancelled, message: "cancelled" }));
|
|
374
441
|
abortSignal.addEventListener("abort", onAbort, { once: true });
|
|
@@ -386,12 +453,18 @@ const createServerConnection = (args) => {
|
|
|
386
453
|
processes.delete(params.processId);
|
|
387
454
|
return result;
|
|
388
455
|
}
|
|
456
|
+
case HandleRpcMethod.ProcessDetach: {
|
|
457
|
+
const params = parseParams(handleRpcMethodSchemas[method].params, context.params);
|
|
458
|
+
const served = processes.get(params.processId);
|
|
459
|
+
if (served == null) return {};
|
|
460
|
+
if (served.detach == null) throw unsupported("detaching an ordinary process");
|
|
461
|
+
processes.delete(params.processId);
|
|
462
|
+
await releaseProcess(served);
|
|
463
|
+
return {};
|
|
464
|
+
}
|
|
389
465
|
case HandleRpcMethod.ProcessKill: {
|
|
390
466
|
const params = parseParams(handleRpcMethodSchemas[method].params, context.params);
|
|
391
|
-
|
|
392
|
-
if (child == null)
|
|
393
|
-
throw handleRpcError({ code: HandleRpcErrorCode.NotFound, message: "no such process" });
|
|
394
|
-
await child.kill(params.signal);
|
|
467
|
+
await servedProcess(params.processId).process.kill(params.signal);
|
|
395
468
|
return {};
|
|
396
469
|
}
|
|
397
470
|
case HandleRpcMethod.Run: {
|
|
@@ -437,7 +510,7 @@ const createServerConnection = (args) => {
|
|
|
437
510
|
if (handle == null) throw unsupported("provider lifecycle hooks");
|
|
438
511
|
const shutdownHandle = handle;
|
|
439
512
|
shutdown ??= (async () => {
|
|
440
|
-
await Promise.allSettled([...processes.values()].map(
|
|
513
|
+
await Promise.allSettled([...processes.values()].map(releaseProcess));
|
|
441
514
|
await Promise.allSettled([...mcpConnections.values()].map((channel) => channel.close()));
|
|
442
515
|
processes.clear();
|
|
443
516
|
mcpConnections.clear();
|
|
@@ -540,7 +613,7 @@ const createServerConnection = (args) => {
|
|
|
540
613
|
};
|
|
541
614
|
const onClose = () => {
|
|
542
615
|
if (expiryTimer != null) clearTimeout(expiryTimer);
|
|
543
|
-
for (const
|
|
616
|
+
for (const served of processes.values()) releaseProcess(served).catch(() => void 0);
|
|
544
617
|
for (const channel of mcpConnections.values()) void channel.close().catch(() => void 0);
|
|
545
618
|
mcpConnections.clear();
|
|
546
619
|
mcpEndpoints.clear();
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../src/sandbox/server.ts"],
|
|
4
|
-
"sourcesContent": ["import * as z from 'zod';\nimport { WorkspaceEgressAction } from '@finalai/agent-protocol/device-egress';\nimport type { JsonValue } from \"../json.mjs\";\nimport { narrowerSandboxAccess, SandboxAccess, sandboxAccessAtLeast } from \"../manifest.mjs\";\nimport { base64ToBytes, bytesToStream } from \"./bytes.mjs\";\nimport { confinedReadDir, confinedReadFile, confinedStat } from \"./confined-files.mjs\";\nimport { hasSandboxExecutionGuard } from \"./execution-guard.mjs\";\nimport { hasHostedMcpEndpoints } from \"./mcp-hosted-marker.mjs\";\nimport { createRpcPeer, type RpcPeerIface, type RpcRequestContextIface } from \"./rpc-peer.mjs\";\nimport {\n isMcpChannelEndpoint,\n SandboxCapability,\n type McpChannelEndpointIface,\n type McpChannelIface,\n type NetworkSandboxSessionIface,\n type SandboxMcpEndpoint,\n type SandboxProcessIface,\n type SandboxProviderHandleIface,\n} from \"./types.mjs\";\nimport {\n createFrameChannelPair,\n frameChannelFromStream,\n frameChannelFromWebSocket,\n HANDLE_RPC_EXECUTE_METHODS,\n HANDLE_RPC_FILE_WRITE_METHODS,\n HANDLE_RPC_LIFECYCLE_METHODS,\n HANDLE_RPC_VERSION,\n HandleRpcCloseCode,\n handleRpcError,\n HandleRpcErrorCode,\n HandleRpcMethod,\n handleRpcMethodSchemas,\n parseHandleRpcMethod,\n type DescribeResultIface,\n type FrameChannelIface,\n type FrameStreamIface,\n type HandleRpcResult,\n type WebSocketLikeIface,\n type WireFrame,\n} from \"./wire.mjs\";\n\n// Serves the handle RPC (wire.ts) for a NetworkSandboxSessionIface. The session\n// service runs it for every provider at its stable per-binding endpoint, which\n// may lazily start the sandbox (through the provider) on the first call.\n\nexport interface HandleAccessPolicyIface {\n // Read bindings reject writes, removes, process execution and computer use;\n // execute bindings allow processes and computer use but not file writes.\n mode: SandboxAccess;\n // Allows sandbox/stop, sandbox/destroy and sandbox/setNetworkPolicy.\n lifecycle: boolean;\n}\n\nexport const DEFAULT_HANDLE_ACCESS: HandleAccessPolicyIface = {\n mode: SandboxAccess.Write,\n lifecycle: false,\n};\n\nexport interface HandleAuthorizationIface {\n // When the credential expires; the server closes the connection then unless\n // the client refreshed it.\n expiresAt: string | null;\n // Narrows the server's access policy for this connection.\n access?: HandleAccessPolicyIface;\n}\n\n// Returns null to reject. `token` is null when the client sent none.\nexport type HandleAuthorizeFn = (args: {\n token: string | null;\n}) => Promise<HandleAuthorizationIface | null>;\n\nexport type HandleLifecycle = Pick<\n SandboxProviderHandleIface<NetworkSandboxSessionIface>,\n 'onSandboxStop' | 'onSandboxDelete' | 'onRuntimeShutdown'\n>;\n\nexport interface HandleResolutionIface {\n sandbox: NetworkSandboxSessionIface;\n handle?: HandleLifecycle;\n access?: HandleAccessPolicyIface;\n}\n\nexport interface HandleRpcMessageHandlerOptionsIface {\n send: (frame: WireFrame) => void;\n close: (code: number, reason: string) => void;\n authorize: HandleAuthorizeFn;\n // Called once per connection, after `initialize` is authorized. The session\n // service's stable endpoint starts the sandbox here through its provider.\n resolve: (authorization: HandleAuthorizationIface) => Promise<HandleResolutionIface>;\n access?: HandleAccessPolicyIface;\n // Token presented in the connection request, used when `initialize` has none.\n connectionToken?: string | null;\n // Send stream chunks as binary frames (default true).\n binary?: boolean;\n // The outer host applies hosted-tool policy before exposing this transport.\n mcpChannels?: boolean;\n now?: () => number;\n // Runs for each validated operation, after binding access checks.\n authorizeOperation?: (context: RpcRequestContextIface) => Promise<void>;\n}\n\nexport interface HandleRpcMessageHandlerIface {\n onFrame(frame: WireFrame): void;\n onClose(code?: number, reason?: string): void;\n}\n\n// Computer use counts only when `sandbox/computerUse` can answer it: an MCP\n// channel endpoint does not cross this wire (its host re-addresses it, as the\n// session service does with withHostedMcpEndpoints).\nconst needsMcpChannels = (sandbox: NetworkSandboxSessionIface) =>\n hasSandboxExecutionGuard(sandbox) && !hasHostedMcpEndpoints(sandbox);\n\nconst servesComputerUse = async (sandbox: NetworkSandboxSessionIface): Promise<boolean> => {\n if (sandbox.computerUse == null || needsMcpChannels(sandbox)) return false;\n try {\n return !isMcpChannelEndpoint(await sandbox.computerUse());\n } catch {\n return false;\n }\n};\n\nconst capabilitiesOf = async (\n sandbox: NetworkSandboxSessionIface,\n mcpChannels = false,\n): Promise<SandboxCapability[]> => {\n const capabilities = [SandboxCapability.Files, SandboxCapability.Process];\n if (sandbox.ports.length > 0) capabilities.push(SandboxCapability.Ports);\n if (sandbox.setNetworkPolicy != null) capabilities.push(SandboxCapability.NetworkPolicy);\n if (sandbox.egress != null) capabilities.push(SandboxCapability.Egress);\n if (mcpChannels ? sandbox.computerUse != null : await servesComputerUse(sandbox))\n capabilities.push(SandboxCapability.ComputerUse);\n if (sandbox.screen != null) capabilities.push(SandboxCapability.Screen);\n if (sandbox.localMcp != null && (mcpChannels || !needsMcpChannels(sandbox)))\n capabilities.push(SandboxCapability.LocalMcp);\n return capabilities;\n};\n\nexport const describeSandbox = async (\n sandbox: NetworkSandboxSessionIface,\n mcpChannels = false,\n): Promise<DescribeResultIface> => ({\n handleRpcVersion: HANDLE_RPC_VERSION,\n id: sandbox.id,\n defaultWorkingDirectory: sandbox.defaultWorkingDirectory,\n ports: [...sandbox.ports],\n capabilities: await capabilitiesOf(sandbox, mcpChannels),\n description: sandbox.description,\n});\n\nconst narrowAccess = (\n base: HandleAccessPolicyIface,\n narrower: HandleAccessPolicyIface | undefined,\n): HandleAccessPolicyIface =>\n narrower == null\n ? base\n : {\n mode: narrowerSandboxAccess(base.mode, narrower.mode),\n lifecycle: base.lifecycle && narrower.lifecycle,\n };\n\nconst parseParams = <S extends z.ZodType>(schema: S, params: JsonValue): z.output<S> => {\n const parsed = schema.safeParse(params);\n if (!parsed.success) {\n throw handleRpcError({\n code: HandleRpcErrorCode.InvalidParams,\n message: z.prettifyError(parsed.error),\n });\n }\n return parsed.data;\n};\n\n// The upload stream ids a request names, read before full validation.\nconst uploadStreamIdsSchema = z.object({\n streamId: z.number().int().nonnegative().optional(),\n stdinStreamId: z.number().int().nonnegative().nullable().optional(),\n});\n\nconst unsupported = (what: string) =>\n handleRpcError({ code: HandleRpcErrorCode.Unsupported, message: `this sandbox has no ${what}` });\n\n// Byte-range slice of a stream.\nconst sliceStream = (\n source: ReadableStream<Uint8Array>,\n offset: number,\n length: number | undefined,\n): ReadableStream<Uint8Array> => {\n let position = 0;\n const end = length == null ? Number.POSITIVE_INFINITY : offset + length;\n const reader = source.getReader();\n return new ReadableStream<Uint8Array>({\n pull: async (controller) => {\n for (;;) {\n if (position >= end) {\n controller.close();\n await reader.cancel().catch(() => undefined);\n return;\n }\n const { done, value } = await reader.read();\n if (done) {\n controller.close();\n return;\n }\n const chunkStart = position;\n position += value.byteLength;\n const from = Math.max(0, offset - chunkStart);\n const to = Math.min(value.byteLength, end - chunkStart);\n if (to > from) {\n controller.enqueue(value.subarray(from, to));\n return;\n }\n }\n },\n cancel: (reason) => reader.cancel(reason),\n });\n};\n\n// Low-level, transport-agnostic handler: feed it frames, it calls `send` and\n// `close`. Use it where the host owns the socket (Hono upgradeWebSocket, a\n// Durable Object's hibernation handlers, a relay).\nexport const createHandleRpcMessageHandler = (\n options: HandleRpcMessageHandlerOptionsIface,\n): HandleRpcMessageHandlerIface => {\n const now = options.now ?? Date.now;\n const [local, remote] = createFrameChannelPair();\n let ended = false;\n // `remote` is our side; frames the peer writes to it go out through `send`.\n remote.listen({\n frame: (frame) => options.send(frame),\n close: (info) => {\n if (!ended) {\n ended = true;\n options.close(info.code, info.reason);\n }\n },\n });\n const peerChannel: FrameChannelIface = local;\n const connection = createServerConnection({\n channel: peerChannel,\n authorize: options.authorize,\n resolve: options.resolve,\n access: options.access ?? DEFAULT_HANDLE_ACCESS,\n connectionToken: options.connectionToken ?? null,\n binary: options.binary ?? true,\n mcpChannels: options.mcpChannels,\n now,\n authorizeOperation: options.authorizeOperation,\n });\n return {\n onFrame: (frame) => remote.send(frame),\n onClose: (code, reason) => {\n ended = true;\n connection.close(code ?? 1000, reason ?? '');\n },\n };\n};\n\ninterface ServerConnectionIface {\n close(code: number, reason: string): void;\n}\n\ninterface ServerConnectionArgsIface {\n channel: FrameChannelIface;\n authorize: HandleAuthorizeFn;\n resolve: (authorization: HandleAuthorizationIface) => Promise<HandleResolutionIface>;\n access: HandleAccessPolicyIface;\n connectionToken: string | null;\n binary: boolean;\n mcpChannels?: boolean;\n now: () => number;\n authorizeOperation?: (context: RpcRequestContextIface) => Promise<void>;\n}\n\nconst createServerConnection = (args: ServerConnectionArgsIface): ServerConnectionIface => {\n let sandbox: NetworkSandboxSessionIface | null = null;\n let access = args.access;\n let initializing = false;\n let handle: HandleLifecycle | null = null;\n let expiryTimer: ReturnType<typeof setTimeout> | null = null;\n const processes = new Map<string, SandboxProcessIface>();\n const mcpEndpoints = new Map<string, McpChannelEndpointIface>();\n const mcpConnections = new Map<string, McpChannelIface>();\n let nextMcpChannelId = 0;\n let shutdown: Promise<void> | null = null;\n // Incoming streams registered in beforeRequest, keyed by request id.\n const incomingByRequest = new Map<\n string | number,\n { streamId: number; stream: ReadableStream<Uint8Array> }\n >();\n\n const scheduleExpiry = (expiresAt: string | null) => {\n if (expiryTimer != null) clearTimeout(expiryTimer);\n expiryTimer = null;\n if (expiresAt == null) return;\n const delay = Date.parse(expiresAt) - args.now();\n if (Number.isNaN(delay)) return;\n expiryTimer = setTimeout(\n () =>\n delay > 2_147_483_647\n ? scheduleExpiry(expiresAt)\n : peer.close(HandleRpcCloseCode.Unauthorized, 'credential expired'),\n Math.max(0, Math.min(2_147_483_647, delay)),\n );\n };\n\n const requireSandbox = (): NetworkSandboxSessionIface => {\n if (sandbox == null) {\n throw handleRpcError({\n code: HandleRpcErrorCode.NotInitialized,\n message: 'initialize first',\n });\n }\n return sandbox;\n };\n\n const checkAccess = (method: HandleRpcMethod, params: JsonValue) => {\n if (\n method === HandleRpcMethod.Screen &&\n !parseParams(handleRpcMethodSchemas[method].params, params).viewOnly &&\n !sandboxAccessAtLeast(access.mode, SandboxAccess.Execute)\n )\n throw handleRpcError({\n code: HandleRpcErrorCode.Forbidden,\n message: 'Screen input control requires execute access',\n });\n if (\n !sandboxAccessAtLeast(access.mode, SandboxAccess.Execute) &&\n HANDLE_RPC_EXECUTE_METHODS.includes(method)\n ) {\n throw handleRpcError({\n code: HandleRpcErrorCode.Forbidden,\n message: `${method} is not allowed on a read-only binding`,\n });\n }\n if (\n !sandboxAccessAtLeast(access.mode, SandboxAccess.Write) &&\n HANDLE_RPC_FILE_WRITE_METHODS.includes(method)\n ) {\n throw handleRpcError({\n code: HandleRpcErrorCode.Forbidden,\n message: `${method} is not allowed without write access`,\n });\n }\n if (\n method === HandleRpcMethod.Egress &&\n !sandboxAccessAtLeast(access.mode, SandboxAccess.Write)\n ) {\n throw handleRpcError({\n code: HandleRpcErrorCode.Forbidden,\n message: 'Device egress requires write access',\n });\n }\n if (method === HandleRpcMethod.SetNetworkPolicy && access.mode === SandboxAccess.Read) {\n throw handleRpcError({\n code: HandleRpcErrorCode.Forbidden,\n message: `${method} is not allowed on a read-only binding`,\n });\n }\n if (!access.lifecycle && HANDLE_RPC_LIFECYCLE_METHODS.includes(method)) {\n throw handleRpcError({\n code: HandleRpcErrorCode.Forbidden,\n message: `${method} is not allowed on this binding`,\n });\n }\n };\n\n const featureFlags = (): Pick<DescribeResultIface, 'providerHooks' | 'mcpChannels'> => {\n const flags: Pick<DescribeResultIface, 'providerHooks' | 'mcpChannels'> = {};\n if (handle != null) flags.providerHooks = true;\n if (args.mcpChannels === true) flags.mcpChannels = true;\n return flags;\n };\n\n const initialize = async (\n params: JsonValue,\n ): Promise<HandleRpcResult<HandleRpcMethod.Initialize>> => {\n const parsed = parseParams(handleRpcMethodSchemas[HandleRpcMethod.Initialize].params, params);\n if (sandbox != null || initializing) {\n throw handleRpcError({\n code: HandleRpcErrorCode.InvalidRequest,\n message: 'already initialized',\n });\n }\n initializing = true;\n try {\n const token = parsed.token ?? args.connectionToken;\n const authorization = await args.authorize({ token });\n if (authorization == null) {\n setTimeout(() => peer.close(HandleRpcCloseCode.Unauthorized, 'unauthorized'), 0);\n throw handleRpcError({ code: HandleRpcErrorCode.Unauthorized, message: 'unauthorized' });\n }\n const resolution = await args.resolve(authorization);\n access = narrowAccess(narrowAccess(access, resolution.access), authorization.access);\n sandbox = resolution.sandbox;\n handle = resolution.handle ?? null;\n scheduleExpiry(authorization.expiresAt);\n return {\n ...(await describeSandbox(sandbox, args.mcpChannels)),\n confinedFiles: true,\n ...featureFlags(),\n expiresAt: authorization.expiresAt,\n };\n } finally {\n initializing = false;\n }\n };\n\n const pump = (streamId: number, source: ReadableStream<Uint8Array>) => {\n peer.streams.openOutgoing(streamId, source).catch(() => undefined);\n };\n\n const mcpDescriptor = (endpoint: SandboxMcpEndpoint, key: string) => {\n if (!isMcpChannelEndpoint(endpoint)) return endpoint;\n if (args.mcpChannels !== true) throw unsupported('MCP channels over the handle RPC');\n mcpEndpoints.set(key, endpoint);\n return { name: endpoint.name, endpointKey: key };\n };\n const mcpConnection = (id: string): McpChannelIface => {\n const channel = mcpConnections.get(id);\n if (channel == null)\n throw handleRpcError({\n code: HandleRpcErrorCode.NotFound,\n message: 'MCP channel not found on this connection',\n });\n return channel;\n };\n\n // Fails a request's upload stream when the request fails, so the client\n // stops sending.\n const dispatch = async (context: RpcRequestContextIface): Promise<object> => {\n try {\n return await dispatchMethod(context);\n } catch (error) {\n const entry = incomingByRequest.get(context.id);\n incomingByRequest.delete(context.id);\n if (entry != null) peer.streams.cancelIncoming(entry.streamId, 'request failed');\n throw error;\n }\n };\n\n const dispatchMethod = async (context: RpcRequestContextIface): Promise<object> => {\n const method = parseHandleRpcMethod(context.method);\n if (method == null) {\n throw handleRpcError({\n code: HandleRpcErrorCode.MethodNotFound,\n message: `unknown method ${context.method}`,\n });\n }\n if (method === HandleRpcMethod.Initialize) return initialize(context.params);\n const target = requireSandbox();\n if (shutdown != null && method !== HandleRpcMethod.OnRuntimeShutdown)\n throw handleRpcError({\n code: HandleRpcErrorCode.ConnectionClosed,\n message: 'Provider handle is shutting down',\n });\n checkAccess(method, context.params);\n parseParams(handleRpcMethodSchemas[method].params, context.params);\n if (\n method === HandleRpcMethod.Egress &&\n parseParams(handleRpcMethodSchemas[HandleRpcMethod.Egress].params, context.params).action !==\n WorkspaceEgressAction.Status &&\n args.authorizeOperation == null\n )\n throw handleRpcError({\n code: HandleRpcErrorCode.Forbidden,\n message: 'Device egress changes require an operation authorization hook',\n });\n await args.authorizeOperation?.(context);\n if (context.signal.aborted)\n throw handleRpcError({ code: HandleRpcErrorCode.Cancelled, message: 'request cancelled' });\n const abortSignal = context.signal;\n switch (method) {\n case HandleRpcMethod.Describe:\n return {\n ...(await describeSandbox(target, args.mcpChannels)),\n confinedFiles: true,\n ...featureFlags(),\n };\n case HandleRpcMethod.AuthRefresh: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n const authorization = await args.authorize({ token: params.token });\n if (authorization == null)\n throw handleRpcError({ code: HandleRpcErrorCode.Unauthorized, message: 'unauthorized' });\n access = narrowAccess(access, authorization.access);\n scheduleExpiry(authorization.expiresAt);\n return { expiresAt: authorization.expiresAt };\n }\n case HandleRpcMethod.ReadFile: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n const stream =\n params.root == null\n ? await target.readFile({ path: params.path, abortSignal })\n : await (\n target.confinedFileReader?.readFile ??\n ((options) => confinedReadFile(target, options))\n )({ path: params.path, root: params.root, abortSignal });\n if (stream == null) return { found: false };\n const ranged =\n params.offset != null || params.length != null\n ? sliceStream(stream, params.offset ?? 0, params.length)\n : stream;\n // The client registered the stream before asking, so start right away.\n pump(params.streamId, ranged);\n return { found: true };\n }\n case HandleRpcMethod.ReadTextFile: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n const text = await target.readTextFile({ ...params, abortSignal });\n return { text };\n }\n case HandleRpcMethod.WriteFile: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n const incoming = incomingByRequest.get(context.id)?.stream ?? null;\n const content =\n incoming ??\n bytesToStream(\n params.contentBase64 == null ? new Uint8Array() : base64ToBytes(params.contentBase64),\n );\n await target.writeFile({ path: params.path, content, abortSignal });\n incomingByRequest.delete(context.id);\n return {};\n }\n case HandleRpcMethod.Spawn: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n const stdin = incomingByRequest.get(context.id)?.stream ?? null;\n if (processes.has(params.processId)) {\n throw handleRpcError({\n code: HandleRpcErrorCode.InvalidParams,\n message: 'processId already in use',\n });\n }\n const child = await target.spawn({\n command: params.command,\n args: params.args,\n cwd: params.cwd,\n env: params.env,\n shell: params.shell,\n timeoutMs: params.timeoutMs,\n // A closed stdin is an empty stream.\n stdin: stdin ?? '',\n });\n incomingByRequest.delete(context.id);\n processes.set(params.processId, child);\n pump(params.stdoutStreamId, child.stdout);\n pump(params.stderrStreamId, child.stderr);\n return { pid: child.pid };\n }\n case HandleRpcMethod.ProcessWait: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n const child = processes.get(params.processId);\n if (child == null)\n throw handleRpcError({ code: HandleRpcErrorCode.NotFound, message: 'no such process' });\n const result = await new Promise<{ exitCode: number }>((resolve, reject) => {\n const onAbort = () =>\n reject(handleRpcError({ code: HandleRpcErrorCode.Cancelled, message: 'cancelled' }));\n abortSignal.addEventListener('abort', onAbort, { once: true });\n child.wait().then(\n (value) => {\n abortSignal.removeEventListener('abort', onAbort);\n resolve(value);\n },\n (cause: unknown) => {\n abortSignal.removeEventListener('abort', onAbort);\n reject(cause);\n },\n );\n });\n processes.delete(params.processId);\n return result;\n }\n case HandleRpcMethod.ProcessKill: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n const child = processes.get(params.processId);\n if (child == null)\n throw handleRpcError({ code: HandleRpcErrorCode.NotFound, message: 'no such process' });\n await child.kill(params.signal);\n return {};\n }\n case HandleRpcMethod.Run: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n return target.run({ ...params, abortSignal });\n }\n case HandleRpcMethod.Stat: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n return {\n stat:\n params.root == null\n ? await target.stat({ path: params.path, abortSignal })\n : await (\n target.confinedFileReader?.stat ?? ((options) => confinedStat(target, options))\n )({\n path: params.path,\n root: params.root,\n abortSignal,\n }),\n };\n }\n case HandleRpcMethod.ReadDir: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n return {\n entries:\n params.root == null\n ? await target.readDir({ path: params.path, abortSignal })\n : await (\n target.confinedFileReader?.readDir ??\n ((options) => confinedReadDir(target, options))\n )({\n path: params.path,\n root: params.root,\n abortSignal,\n }),\n };\n }\n case HandleRpcMethod.RemovePath: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n await target.removePath({ ...params, abortSignal });\n return {};\n }\n case HandleRpcMethod.GetPortEndpoint: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n return target.getPortEndpoint(params);\n }\n case HandleRpcMethod.Stop:\n await target.stop();\n return {};\n case HandleRpcMethod.Destroy:\n await target.destroy();\n return {};\n case HandleRpcMethod.OnRuntimeShutdown: {\n if (handle == null) throw unsupported('provider lifecycle hooks');\n const shutdownHandle = handle;\n shutdown ??= (async () => {\n await Promise.allSettled([...processes.values()].map((child) => child.kill()));\n await Promise.allSettled([...mcpConnections.values()].map((channel) => channel.close()));\n processes.clear();\n mcpConnections.clear();\n mcpEndpoints.clear();\n await shutdownHandle.onRuntimeShutdown();\n })();\n await shutdown;\n return {};\n }\n case HandleRpcMethod.OnSandboxStop:\n if (handle == null) throw unsupported('provider lifecycle hooks');\n await handle.onSandboxStop();\n return {};\n case HandleRpcMethod.OnSandboxDelete: {\n if (handle == null) throw unsupported('provider lifecycle hooks');\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n await handle.onSandboxDelete(params);\n return {};\n }\n case HandleRpcMethod.SetNetworkPolicy: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n if (target.setNetworkPolicy == null) throw unsupported('network policy');\n await target.setNetworkPolicy(params);\n return {};\n }\n case HandleRpcMethod.Egress: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n if (target.egress == null) throw unsupported('Device egress');\n return handleRpcMethodSchemas[HandleRpcMethod.Egress].result.parse(\n await target.egress(params),\n );\n }\n case HandleRpcMethod.ComputerUse: {\n if (target.computerUse == null) throw unsupported('computer use');\n if (needsMcpChannels(target) && args.mcpChannels !== true)\n throw unsupported('guarded MCP transport; negotiate mcpChannels');\n const endpoint = await target.computerUse();\n return mcpDescriptor(endpoint, 'computerUse');\n }\n case HandleRpcMethod.McpOpen: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n const endpoint = mcpEndpoints.get(params.endpointKey);\n if (args.mcpChannels !== true || endpoint == null)\n throw unsupported('MCP channel endpoint');\n const channel = await endpoint.connect({ abortSignal });\n if (abortSignal.aborted) {\n await channel.close();\n abortSignal.throwIfAborted();\n }\n const channelId = String(++nextMcpChannelId);\n mcpConnections.set(channelId, channel);\n return { channelId };\n }\n case HandleRpcMethod.McpSend: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n await mcpConnection(params.channelId).send(params.message, { abortSignal });\n return {};\n }\n case HandleRpcMethod.McpReceive: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n return { messages: await mcpConnection(params.channelId).receive({ abortSignal }) };\n }\n case HandleRpcMethod.McpClose: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n const channel = mcpConnection(params.channelId);\n await channel.close();\n mcpConnections.delete(params.channelId);\n return {};\n }\n case HandleRpcMethod.Screen: {\n if (target.screen == null) throw unsupported('screen');\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n return target.screen(params);\n }\n case HandleRpcMethod.LocalMcp:\n if (target.localMcp == null) throw unsupported('local MCP servers');\n if (needsMcpChannels(target) && args.mcpChannels !== true)\n throw unsupported('guarded MCP transport; negotiate mcpChannels');\n return {\n endpoints: (await target.localMcp()).flatMap((endpoint, index) =>\n args.mcpChannels !== true && isMcpChannelEndpoint(endpoint)\n ? []\n : [mcpDescriptor(endpoint, `localMcp:${index}:${endpoint.name}`)],\n ),\n };\n }\n };\n\n // Registers client-to-server streams synchronously, before their chunks.\n const beforeRequest = (context: RpcRequestContextIface) => {\n if (context.method !== HandleRpcMethod.WriteFile && context.method !== HandleRpcMethod.Spawn)\n return;\n const ids = uploadStreamIdsSchema.safeParse(context.params);\n if (!ids.success) return;\n const streamId =\n context.method === HandleRpcMethod.WriteFile ? ids.data.streamId : ids.data.stdinStreamId;\n if (streamId == null) return;\n const stream = peer.streams.openIncoming(streamId);\n // Reject unauthorized or disallowed uploads before buffering their data.\n const floor =\n context.method === HandleRpcMethod.WriteFile ? SandboxAccess.Write : SandboxAccess.Execute;\n if (sandbox == null || !sandboxAccessAtLeast(access.mode, floor)) {\n peer.streams.cancelIncoming(streamId, 'rejected');\n return;\n }\n incomingByRequest.set(context.id, { streamId, stream });\n };\n\n const onClose = () => {\n if (expiryTimer != null) clearTimeout(expiryTimer);\n for (const child of processes.values()) child.kill().catch(() => undefined);\n for (const channel of mcpConnections.values()) void channel.close().catch(() => undefined);\n mcpConnections.clear();\n mcpEndpoints.clear();\n processes.clear();\n incomingByRequest.clear();\n };\n\n const peer: RpcPeerIface = createRpcPeer({\n channel: args.channel,\n binary: args.binary,\n onRequest: dispatch,\n beforeRequest,\n onClose,\n });\n\n return { close: (code, reason) => peer.close(code, reason) };\n};\n\nexport interface ServeSandboxHandleArgsIface {\n sandbox: NetworkSandboxSessionIface;\n handle?: HandleLifecycle;\n authorize: HandleAuthorizeFn;\n authorizeOperation?: HandleRpcMessageHandlerOptionsIface['authorizeOperation'];\n access?: HandleAccessPolicyIface;\n binary?: boolean;\n // The outer host applies hosted-tool policy before exposing this transport.\n mcpChannels?: boolean;\n now?: () => number;\n}\n\nexport interface SandboxHandleServerIface {\n // Attaches a connection; returns a function that closes it.\n attach(channel: FrameChannelIface, context?: { token?: string | null }): () => void;\n attachWebSocket(socket: WebSocketLikeIface, context?: { token?: string | null }): () => void;\n attachStream(stream: FrameStreamIface, context?: { token?: string | null }): () => void;\n messageHandler(args: {\n send: (frame: WireFrame) => void;\n close: (code: number, reason: string) => void;\n token?: string | null;\n }): HandleRpcMessageHandlerIface;\n}\n\nexport const serveSandboxHandle = (args: ServeSandboxHandleArgsIface): SandboxHandleServerIface => {\n const access = args.access ?? DEFAULT_HANDLE_ACCESS;\n const resolve = async (): Promise<HandleResolutionIface> => ({\n sandbox: args.sandbox,\n handle: args.handle,\n });\n const attach = (channel: FrameChannelIface, context?: { token?: string | null }) => {\n const connection = createServerConnection({\n channel,\n authorize: args.authorize,\n authorizeOperation: args.authorizeOperation,\n resolve,\n access,\n connectionToken: context?.token ?? null,\n binary: args.binary ?? true,\n mcpChannels: args.mcpChannels,\n now: args.now ?? Date.now,\n });\n return () => connection.close(HandleRpcCloseCode.Normal, 'closed');\n };\n return {\n attach,\n attachWebSocket: (socket, context) =>\n attach(frameChannelFromWebSocket(socket).channel, context),\n attachStream: (stream, context) => attach(frameChannelFromStream(stream), context),\n messageHandler: (handlerArgs) =>\n createHandleRpcMessageHandler({\n send: handlerArgs.send,\n close: handlerArgs.close,\n authorize: args.authorize,\n authorizeOperation: args.authorizeOperation,\n resolve,\n access,\n connectionToken: handlerArgs.token ?? null,\n binary: args.binary,\n mcpChannels: args.mcpChannels,\n now: args.now,\n }),\n };\n};\n"],
|
|
5
|
-
"mappings": "AAAA,YAAY,OAAO;AACnB,SAAS,6BAA6B;AAEtC,SAAS,uBAAuB,eAAe,4BAA4B;AAC3E,SAAS,eAAe,qBAAqB;AAC7C,SAAS,iBAAiB,kBAAkB,oBAAoB;AAChE,SAAS,gCAAgC;AACzC,SAAS,6BAA6B;AACtC,SAAS,qBAAqE;AAC9E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,UAAU,aAA6C;AAAA,IAC3D,SAAS,KAAK;AAAA,IACd,QAAQ,KAAK;AAAA,EACf;AACA,QAAM,SAAS,CAAC,SAA4B,YAAwC;AAClF,UAAM,aAAa,uBAAuB;AAAA,MACxC;AAAA,MACA,WAAW,KAAK;AAAA,MAChB,oBAAoB,KAAK;AAAA,MACzB;AAAA,MACA;AAAA,MACA,iBAAiB,SAAS,SAAS;AAAA,MACnC,QAAQ,KAAK,UAAU;AAAA,MACvB,aAAa,KAAK;AAAA,MAClB,KAAK,KAAK,OAAO,KAAK;AAAA,IACxB,CAAC;AACD,WAAO,MAAM,WAAW,MAAM,mBAAmB,QAAQ,QAAQ;AAAA,EACnE;AACA,SAAO;AAAA,IACL;AAAA,IACA,iBAAiB,CAAC,QAAQ,YACxB,OAAO,0BAA0B,MAAM,EAAE,SAAS,OAAO;AAAA,IAC3D,cAAc,CAAC,QAAQ,YAAY,OAAO,uBAAuB,MAAM,GAAG,OAAO;AAAA,IACjF,gBAAgB,CAAC,gBACf,8BAA8B;AAAA,MAC5B,MAAM,YAAY;AAAA,MAClB,OAAO,YAAY;AAAA,MACnB,WAAW,KAAK;AAAA,MAChB,oBAAoB,KAAK;AAAA,MACzB;AAAA,MACA;AAAA,MACA,iBAAiB,YAAY,SAAS;AAAA,MACtC,QAAQ,KAAK;AAAA,MACb,aAAa,KAAK;AAAA,MAClB,KAAK,KAAK;AAAA,IACZ,CAAC;AAAA,EACL;AACF;",
|
|
6
|
-
"names": []
|
|
4
|
+
"sourcesContent": ["import * as z from 'zod';\nimport { WorkspaceEgressAction } from '@finalai/agent-protocol/device-egress';\nimport type { JsonValue } from \"../json.mjs\";\nimport { narrowerSandboxAccess, SandboxAccess, sandboxAccessAtLeast } from \"../manifest.mjs\";\nimport { base64ToBytes, bytesToStream } from \"./bytes.mjs\";\nimport { confinedReadDir, confinedReadFile, confinedStat } from \"./confined-files.mjs\";\nimport { hasSandboxExecutionGuard } from \"./execution-guard.mjs\";\nimport { hasHostedMcpEndpoints } from \"./mcp-hosted-marker.mjs\";\nimport { createRpcPeer, type RpcPeerIface, type RpcRequestContextIface } from \"./rpc-peer.mjs\";\nimport {\n isMcpChannelEndpoint,\n SandboxCapability,\n type McpChannelEndpointIface,\n type McpChannelIface,\n type NetworkSandboxSessionIface,\n type SandboxMcpEndpoint,\n type SandboxProcessIface,\n type SandboxProviderHandleIface,\n} from \"./types.mjs\";\nimport {\n createFrameChannelPair,\n frameChannelFromStream,\n frameChannelFromWebSocket,\n HANDLE_RPC_EXECUTE_METHODS,\n HANDLE_RPC_FILE_WRITE_METHODS,\n HANDLE_RPC_LIFECYCLE_METHODS,\n HANDLE_RPC_VERSION,\n HandleRpcCloseCode,\n handleRpcError,\n HandleRpcErrorCode,\n HandleRpcMethod,\n handleRpcMethodSchemas,\n parseHandleRpcMethod,\n type DescribeResultIface,\n type FrameChannelIface,\n type FrameStreamIface,\n type HandleRpcResult,\n type WebSocketLikeIface,\n type WireFrame,\n} from \"./wire.mjs\";\n\n// Serves the handle RPC (wire.ts) for a NetworkSandboxSessionIface. The session\n// service runs it for every provider at its stable per-binding endpoint, which\n// may lazily start the sandbox (through the provider) on the first call.\n\nexport interface HandleAccessPolicyIface {\n // Read bindings reject writes, removes, process execution and computer use;\n // execute bindings allow processes and computer use but not file writes.\n mode: SandboxAccess;\n // Allows sandbox/stop, sandbox/destroy and sandbox/setNetworkPolicy.\n lifecycle: boolean;\n}\n\nexport const DEFAULT_HANDLE_ACCESS: HandleAccessPolicyIface = {\n mode: SandboxAccess.Write,\n lifecycle: false,\n};\n\nexport interface HandleAuthorizationIface {\n // When the credential expires; the server closes the connection then unless\n // the client refreshed it.\n expiresAt: string | null;\n // Narrows the server's access policy for this connection.\n access?: HandleAccessPolicyIface;\n}\n\n// Returns null to reject. `token` is null when the client sent none.\nexport type HandleAuthorizeFn = (args: {\n token: string | null;\n}) => Promise<HandleAuthorizationIface | null>;\n\nexport type HandleLifecycle = Pick<\n SandboxProviderHandleIface<NetworkSandboxSessionIface>,\n 'onSandboxStop' | 'onSandboxDelete' | 'onRuntimeShutdown'\n>;\n\nexport interface HandleResolutionIface {\n sandbox: NetworkSandboxSessionIface;\n handle?: HandleLifecycle;\n access?: HandleAccessPolicyIface;\n}\n\nexport interface HandleRpcMessageHandlerOptionsIface {\n send: (frame: WireFrame) => void;\n close: (code: number, reason: string) => void;\n authorize: HandleAuthorizeFn;\n // Called once per connection, after `initialize` is authorized. The session\n // service's stable endpoint starts the sandbox here through its provider.\n resolve: (authorization: HandleAuthorizationIface) => Promise<HandleResolutionIface>;\n access?: HandleAccessPolicyIface;\n // Token presented in the connection request, used when `initialize` has none.\n connectionToken?: string | null;\n // Send stream chunks as binary frames (default true).\n binary?: boolean;\n // The outer host applies hosted-tool policy before exposing this transport.\n mcpChannels?: boolean;\n now?: () => number;\n // Runs for each validated operation, after binding access checks.\n authorizeOperation?: (context: RpcRequestContextIface) => Promise<void>;\n}\n\nexport interface HandleRpcMessageHandlerIface {\n onFrame(frame: WireFrame): void;\n onClose(code?: number, reason?: string): void;\n}\n\n// Computer use counts only when `sandbox/computerUse` can answer it: an MCP\n// channel endpoint does not cross this wire (its host re-addresses it, as the\n// session service does with withHostedMcpEndpoints).\nconst needsMcpChannels = (sandbox: NetworkSandboxSessionIface) =>\n hasSandboxExecutionGuard(sandbox) && !hasHostedMcpEndpoints(sandbox);\n\nconst servesComputerUse = async (sandbox: NetworkSandboxSessionIface): Promise<boolean> => {\n if (sandbox.computerUse == null || needsMcpChannels(sandbox)) return false;\n try {\n return !isMcpChannelEndpoint(await sandbox.computerUse());\n } catch {\n return false;\n }\n};\n\nconst capabilitiesOf = async (\n sandbox: NetworkSandboxSessionIface,\n mcpChannels = false,\n): Promise<SandboxCapability[]> => {\n const capabilities = [SandboxCapability.Files, SandboxCapability.Process];\n if (sandbox.ports.length > 0) capabilities.push(SandboxCapability.Ports);\n if (sandbox.setNetworkPolicy != null) capabilities.push(SandboxCapability.NetworkPolicy);\n if (sandbox.egress != null) capabilities.push(SandboxCapability.Egress);\n if (mcpChannels ? sandbox.computerUse != null : await servesComputerUse(sandbox))\n capabilities.push(SandboxCapability.ComputerUse);\n if (sandbox.screen != null) capabilities.push(SandboxCapability.Screen);\n if (sandbox.localMcp != null && (mcpChannels || !needsMcpChannels(sandbox)))\n capabilities.push(SandboxCapability.LocalMcp);\n if (sandbox.attachProcess != null) capabilities.push(SandboxCapability.DurableProcesses);\n return capabilities;\n};\n\nexport const describeSandbox = async (\n sandbox: NetworkSandboxSessionIface,\n mcpChannels = false,\n): Promise<DescribeResultIface> => ({\n handleRpcVersion: HANDLE_RPC_VERSION,\n id: sandbox.id,\n defaultWorkingDirectory: sandbox.defaultWorkingDirectory,\n ports: [...sandbox.ports],\n capabilities: await capabilitiesOf(sandbox, mcpChannels),\n description: sandbox.description,\n});\n\nconst narrowAccess = (\n base: HandleAccessPolicyIface,\n narrower: HandleAccessPolicyIface | undefined,\n): HandleAccessPolicyIface =>\n narrower == null\n ? base\n : {\n mode: narrowerSandboxAccess(base.mode, narrower.mode),\n lifecycle: base.lifecycle && narrower.lifecycle,\n };\n\nconst parseParams = <S extends z.ZodType>(schema: S, params: JsonValue): z.output<S> => {\n const parsed = schema.safeParse(params);\n if (!parsed.success) {\n throw handleRpcError({\n code: HandleRpcErrorCode.InvalidParams,\n message: z.prettifyError(parsed.error),\n });\n }\n return parsed.data;\n};\n\n// The upload stream ids a request names, read before full validation.\nconst uploadStreamIdsSchema = z.object({\n streamId: z.number().int().nonnegative().optional(),\n stdinStreamId: z.number().int().nonnegative().nullable().optional(),\n});\n\nconst unsupported = (what: string) =>\n handleRpcError({ code: HandleRpcErrorCode.Unsupported, message: `this sandbox has no ${what}` });\n\n// Byte-range slice of a stream.\nconst sliceStream = (\n source: ReadableStream<Uint8Array>,\n offset: number,\n length: number | undefined,\n): ReadableStream<Uint8Array> => {\n let position = 0;\n const end = length == null ? Number.POSITIVE_INFINITY : offset + length;\n const reader = source.getReader();\n return new ReadableStream<Uint8Array>({\n pull: async (controller) => {\n for (;;) {\n if (position >= end) {\n controller.close();\n await reader.cancel().catch(() => undefined);\n return;\n }\n const { done, value } = await reader.read();\n if (done) {\n controller.close();\n return;\n }\n const chunkStart = position;\n position += value.byteLength;\n const from = Math.max(0, offset - chunkStart);\n const to = Math.min(value.byteLength, end - chunkStart);\n if (to > from) {\n controller.enqueue(value.subarray(from, to));\n return;\n }\n }\n },\n cancel: (reason) => reader.cancel(reason),\n });\n};\n\n// Low-level, transport-agnostic handler: feed it frames, it calls `send` and\n// `close`. Use it where the host owns the socket (Hono upgradeWebSocket, a\n// Durable Object's hibernation handlers, a relay).\nexport const createHandleRpcMessageHandler = (\n options: HandleRpcMessageHandlerOptionsIface,\n): HandleRpcMessageHandlerIface => {\n const now = options.now ?? Date.now;\n const [local, remote] = createFrameChannelPair();\n let ended = false;\n // `remote` is our side; frames the peer writes to it go out through `send`.\n remote.listen({\n frame: (frame) => options.send(frame),\n close: (info) => {\n if (!ended) {\n ended = true;\n options.close(info.code, info.reason);\n }\n },\n });\n const peerChannel: FrameChannelIface = local;\n const connection = createServerConnection({\n channel: peerChannel,\n authorize: options.authorize,\n resolve: options.resolve,\n access: options.access ?? DEFAULT_HANDLE_ACCESS,\n connectionToken: options.connectionToken ?? null,\n binary: options.binary ?? true,\n mcpChannels: options.mcpChannels,\n now,\n authorizeOperation: options.authorizeOperation,\n });\n return {\n onFrame: (frame) => remote.send(frame),\n onClose: (code, reason) => {\n ended = true;\n connection.close(code ?? 1000, reason ?? '');\n },\n };\n};\n\ninterface ServerConnectionIface {\n close(code: number, reason: string): void;\n}\n\n// A process served on one connection. `detach` is set for a durable process:\n// aborting it releases the handle and leaves the process running.\ninterface ServedProcessIface {\n process: Pick<SandboxProcessIface, 'wait' | 'kill'>;\n detach: AbortController | null;\n}\n\n// Ends a connection's hold on a process: detaches a durable one, kills any other.\nconst releaseProcess = async (served: ServedProcessIface): Promise<void> => {\n if (served.detach == null) await served.process.kill();\n else served.detach.abort(new Error('process handle released'));\n};\n\ninterface ServerConnectionArgsIface {\n channel: FrameChannelIface;\n authorize: HandleAuthorizeFn;\n resolve: (authorization: HandleAuthorizationIface) => Promise<HandleResolutionIface>;\n access: HandleAccessPolicyIface;\n connectionToken: string | null;\n binary: boolean;\n mcpChannels?: boolean;\n now: () => number;\n authorizeOperation?: (context: RpcRequestContextIface) => Promise<void>;\n}\n\nconst createServerConnection = (args: ServerConnectionArgsIface): ServerConnectionIface => {\n let sandbox: NetworkSandboxSessionIface | null = null;\n let access = args.access;\n let initializing = false;\n let handle: HandleLifecycle | null = null;\n let expiryTimer: ReturnType<typeof setTimeout> | null = null;\n const processes = new Map<string, ServedProcessIface>();\n const mcpEndpoints = new Map<string, McpChannelEndpointIface>();\n const mcpConnections = new Map<string, McpChannelIface>();\n let nextMcpChannelId = 0;\n let shutdown: Promise<void> | null = null;\n // Incoming streams registered in beforeRequest, keyed by request id.\n const incomingByRequest = new Map<\n string | number,\n { streamId: number; stream: ReadableStream<Uint8Array> }\n >();\n\n const scheduleExpiry = (expiresAt: string | null) => {\n if (expiryTimer != null) clearTimeout(expiryTimer);\n expiryTimer = null;\n if (expiresAt == null) return;\n const delay = Date.parse(expiresAt) - args.now();\n if (Number.isNaN(delay)) return;\n expiryTimer = setTimeout(\n () =>\n delay > 2_147_483_647\n ? scheduleExpiry(expiresAt)\n : peer.close(HandleRpcCloseCode.Unauthorized, 'credential expired'),\n Math.max(0, Math.min(2_147_483_647, delay)),\n );\n };\n\n const requireSandbox = (): NetworkSandboxSessionIface => {\n if (sandbox == null) {\n throw handleRpcError({\n code: HandleRpcErrorCode.NotInitialized,\n message: 'initialize first',\n });\n }\n return sandbox;\n };\n\n const checkAccess = (method: HandleRpcMethod, params: JsonValue) => {\n if (\n method === HandleRpcMethod.Screen &&\n !parseParams(handleRpcMethodSchemas[method].params, params).viewOnly &&\n !sandboxAccessAtLeast(access.mode, SandboxAccess.Execute)\n )\n throw handleRpcError({\n code: HandleRpcErrorCode.Forbidden,\n message: 'Screen input control requires execute access',\n });\n if (\n !sandboxAccessAtLeast(access.mode, SandboxAccess.Execute) &&\n HANDLE_RPC_EXECUTE_METHODS.includes(method)\n ) {\n throw handleRpcError({\n code: HandleRpcErrorCode.Forbidden,\n message: `${method} is not allowed on a read-only binding`,\n });\n }\n if (\n !sandboxAccessAtLeast(access.mode, SandboxAccess.Write) &&\n HANDLE_RPC_FILE_WRITE_METHODS.includes(method)\n ) {\n throw handleRpcError({\n code: HandleRpcErrorCode.Forbidden,\n message: `${method} is not allowed without write access`,\n });\n }\n if (\n method === HandleRpcMethod.Egress &&\n !sandboxAccessAtLeast(access.mode, SandboxAccess.Write)\n ) {\n throw handleRpcError({\n code: HandleRpcErrorCode.Forbidden,\n message: 'Device egress requires write access',\n });\n }\n if (method === HandleRpcMethod.SetNetworkPolicy && access.mode === SandboxAccess.Read) {\n throw handleRpcError({\n code: HandleRpcErrorCode.Forbidden,\n message: `${method} is not allowed on a read-only binding`,\n });\n }\n if (!access.lifecycle && HANDLE_RPC_LIFECYCLE_METHODS.includes(method)) {\n throw handleRpcError({\n code: HandleRpcErrorCode.Forbidden,\n message: `${method} is not allowed on this binding`,\n });\n }\n };\n\n const featureFlags = (): Pick<DescribeResultIface, 'providerHooks' | 'mcpChannels'> => {\n const flags: Pick<DescribeResultIface, 'providerHooks' | 'mcpChannels'> = {};\n if (handle != null) flags.providerHooks = true;\n if (args.mcpChannels === true) flags.mcpChannels = true;\n return flags;\n };\n\n const initialize = async (\n params: JsonValue,\n ): Promise<HandleRpcResult<HandleRpcMethod.Initialize>> => {\n const parsed = parseParams(handleRpcMethodSchemas[HandleRpcMethod.Initialize].params, params);\n if (sandbox != null || initializing) {\n throw handleRpcError({\n code: HandleRpcErrorCode.InvalidRequest,\n message: 'already initialized',\n });\n }\n initializing = true;\n try {\n const token = parsed.token ?? args.connectionToken;\n const authorization = await args.authorize({ token });\n if (authorization == null) {\n setTimeout(() => peer.close(HandleRpcCloseCode.Unauthorized, 'unauthorized'), 0);\n throw handleRpcError({ code: HandleRpcErrorCode.Unauthorized, message: 'unauthorized' });\n }\n const resolution = await args.resolve(authorization);\n access = narrowAccess(narrowAccess(access, resolution.access), authorization.access);\n sandbox = resolution.sandbox;\n handle = resolution.handle ?? null;\n scheduleExpiry(authorization.expiresAt);\n return {\n ...(await describeSandbox(sandbox, args.mcpChannels)),\n confinedFiles: true,\n ...featureFlags(),\n expiresAt: authorization.expiresAt,\n };\n } finally {\n initializing = false;\n }\n };\n\n const pump = (streamId: number, source: ReadableStream<Uint8Array>) => {\n peer.streams.openOutgoing(streamId, source).catch(() => undefined);\n };\n\n // Registers a process the provider just returned, unless the request was\n // cancelled or the connection closed or shut down meanwhile: then it is\n // released at once.\n const serve = (args: {\n processId: string;\n served: ServedProcessIface;\n signal: AbortSignal;\n stdout: { streamId: number; stream: ReadableStream<Uint8Array> };\n stderr: { streamId: number; stream: ReadableStream<Uint8Array> };\n }) => {\n if (args.signal.aborted || shutdown != null) {\n void releaseProcess(args.served).catch(() => undefined);\n throw handleRpcError({ code: HandleRpcErrorCode.Cancelled, message: 'request cancelled' });\n }\n processes.set(args.processId, args.served);\n pump(args.stdout.streamId, args.stdout.stream);\n pump(args.stderr.streamId, args.stderr.stream);\n };\n const servedProcess = (processId: string): ServedProcessIface => {\n const served = processes.get(processId);\n if (served == null)\n throw handleRpcError({ code: HandleRpcErrorCode.NotFound, message: 'no such process' });\n return served;\n };\n\n const mcpDescriptor = (endpoint: SandboxMcpEndpoint, key: string) => {\n if (!isMcpChannelEndpoint(endpoint)) return endpoint;\n if (args.mcpChannels !== true) throw unsupported('MCP channels over the handle RPC');\n mcpEndpoints.set(key, endpoint);\n return { name: endpoint.name, endpointKey: key };\n };\n const mcpConnection = (id: string): McpChannelIface => {\n const channel = mcpConnections.get(id);\n if (channel == null)\n throw handleRpcError({\n code: HandleRpcErrorCode.NotFound,\n message: 'MCP channel not found on this connection',\n });\n return channel;\n };\n\n // Fails a request's upload stream when the request fails, so the client\n // stops sending.\n const dispatch = async (context: RpcRequestContextIface): Promise<object> => {\n try {\n return await dispatchMethod(context);\n } catch (error) {\n const entry = incomingByRequest.get(context.id);\n incomingByRequest.delete(context.id);\n if (entry != null) peer.streams.cancelIncoming(entry.streamId, 'request failed');\n throw error;\n }\n };\n\n const dispatchMethod = async (context: RpcRequestContextIface): Promise<object> => {\n const method = parseHandleRpcMethod(context.method);\n if (method == null) {\n throw handleRpcError({\n code: HandleRpcErrorCode.MethodNotFound,\n message: `unknown method ${context.method}`,\n });\n }\n if (method === HandleRpcMethod.Initialize) return initialize(context.params);\n const target = requireSandbox();\n if (shutdown != null && method !== HandleRpcMethod.OnRuntimeShutdown)\n throw handleRpcError({\n code: HandleRpcErrorCode.ConnectionClosed,\n message: 'Provider handle is shutting down',\n });\n checkAccess(method, context.params);\n parseParams(handleRpcMethodSchemas[method].params, context.params);\n if (\n method === HandleRpcMethod.Egress &&\n parseParams(handleRpcMethodSchemas[HandleRpcMethod.Egress].params, context.params).action !==\n WorkspaceEgressAction.Status &&\n args.authorizeOperation == null\n )\n throw handleRpcError({\n code: HandleRpcErrorCode.Forbidden,\n message: 'Device egress changes require an operation authorization hook',\n });\n await args.authorizeOperation?.(context);\n if (context.signal.aborted)\n throw handleRpcError({ code: HandleRpcErrorCode.Cancelled, message: 'request cancelled' });\n const abortSignal = context.signal;\n switch (method) {\n case HandleRpcMethod.Describe:\n return {\n ...(await describeSandbox(target, args.mcpChannels)),\n confinedFiles: true,\n ...featureFlags(),\n };\n case HandleRpcMethod.AuthRefresh: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n const authorization = await args.authorize({ token: params.token });\n if (authorization == null)\n throw handleRpcError({ code: HandleRpcErrorCode.Unauthorized, message: 'unauthorized' });\n access = narrowAccess(access, authorization.access);\n scheduleExpiry(authorization.expiresAt);\n return { expiresAt: authorization.expiresAt };\n }\n case HandleRpcMethod.ReadFile: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n const stream =\n params.root == null\n ? await target.readFile({ path: params.path, abortSignal })\n : await (\n target.confinedFileReader?.readFile ??\n ((options) => confinedReadFile(target, options))\n )({ path: params.path, root: params.root, abortSignal });\n if (stream == null) return { found: false };\n const ranged =\n params.offset != null || params.length != null\n ? sliceStream(stream, params.offset ?? 0, params.length)\n : stream;\n // The client registered the stream before asking, so start right away.\n pump(params.streamId, ranged);\n return { found: true };\n }\n case HandleRpcMethod.ReadTextFile: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n const text = await target.readTextFile({ ...params, abortSignal });\n return { text };\n }\n case HandleRpcMethod.WriteFile: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n const incoming = incomingByRequest.get(context.id)?.stream ?? null;\n const content =\n incoming ??\n bytesToStream(\n params.contentBase64 == null ? new Uint8Array() : base64ToBytes(params.contentBase64),\n );\n await target.writeFile({ path: params.path, content, abortSignal });\n incomingByRequest.delete(context.id);\n return {};\n }\n case HandleRpcMethod.Spawn: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n const stdin = incomingByRequest.get(context.id)?.stream ?? null;\n if (processes.has(params.processId)) {\n throw handleRpcError({\n code: HandleRpcErrorCode.InvalidParams,\n message: 'processId already in use',\n });\n }\n const detach = params.durable === true ? new AbortController() : null;\n const child = await target.spawn({\n command: params.command,\n args: params.args,\n cwd: params.cwd,\n env: params.env,\n shell: params.shell,\n timeoutMs: params.timeoutMs,\n // A closed stdin is an empty stream.\n stdin: stdin ?? '',\n ...(detach == null ? {} : { durable: true, abortSignal: detach.signal }),\n });\n incomingByRequest.delete(context.id);\n const ref = child.ref ?? null;\n serve({\n processId: params.processId,\n // A sandbox that ignored `durable` gave an ordinary process.\n served: { process: child, detach: ref == null ? null : detach },\n signal: abortSignal,\n stdout: { streamId: params.stdoutStreamId, stream: child.stdout },\n stderr: { streamId: params.stderrStreamId, stream: child.stderr },\n });\n return { pid: child.pid, ref };\n }\n case HandleRpcMethod.ProcessAttach: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n if (target.attachProcess == null) throw unsupported('durable processes');\n if (processes.has(params.processId))\n throw handleRpcError({\n code: HandleRpcErrorCode.InvalidParams,\n message: 'processId already in use',\n });\n const detach = new AbortController();\n // Until it is served, cancelling the request (or closing the connection)\n // cancels the attach; afterwards the handle lives until released.\n const cancelAttach = () => detach.abort(abortSignal.reason);\n abortSignal.addEventListener('abort', cancelAttach, { once: true });\n let attached: Awaited<ReturnType<NonNullable<typeof target.attachProcess>>>;\n try {\n attached = await target.attachProcess({\n ref: params.ref,\n stdoutOffset: params.stdoutOffset,\n stderrOffset: params.stderrOffset,\n abortSignal: detach.signal,\n });\n } finally {\n abortSignal.removeEventListener('abort', cancelAttach);\n }\n if (attached == null)\n return {\n found: false,\n stdoutOffset: params.stdoutOffset,\n stderrOffset: params.stderrOffset,\n };\n serve({\n processId: params.processId,\n served: { process: attached, detach },\n signal: abortSignal,\n stdout: { streamId: params.stdoutStreamId, stream: attached.stdout },\n stderr: { streamId: params.stderrStreamId, stream: attached.stderr },\n });\n return {\n found: true,\n stdoutOffset: attached.stdoutOffset,\n stderrOffset: attached.stderrOffset,\n };\n }\n case HandleRpcMethod.ProcessWait: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n const child = servedProcess(params.processId).process;\n const result = await new Promise<{ exitCode: number }>((resolve, reject) => {\n const onAbort = () =>\n reject(handleRpcError({ code: HandleRpcErrorCode.Cancelled, message: 'cancelled' }));\n abortSignal.addEventListener('abort', onAbort, { once: true });\n child.wait().then(\n (value) => {\n abortSignal.removeEventListener('abort', onAbort);\n resolve(value);\n },\n (cause: unknown) => {\n abortSignal.removeEventListener('abort', onAbort);\n reject(cause);\n },\n );\n });\n processes.delete(params.processId);\n return result;\n }\n case HandleRpcMethod.ProcessDetach: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n const served = processes.get(params.processId);\n // Detaching what is already gone (exited and released, or never known) is done.\n if (served == null) return {};\n if (served.detach == null) throw unsupported('detaching an ordinary process');\n processes.delete(params.processId);\n await releaseProcess(served);\n return {};\n }\n case HandleRpcMethod.ProcessKill: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n await servedProcess(params.processId).process.kill(params.signal);\n return {};\n }\n case HandleRpcMethod.Run: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n return target.run({ ...params, abortSignal });\n }\n case HandleRpcMethod.Stat: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n return {\n stat:\n params.root == null\n ? await target.stat({ path: params.path, abortSignal })\n : await (\n target.confinedFileReader?.stat ?? ((options) => confinedStat(target, options))\n )({\n path: params.path,\n root: params.root,\n abortSignal,\n }),\n };\n }\n case HandleRpcMethod.ReadDir: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n return {\n entries:\n params.root == null\n ? await target.readDir({ path: params.path, abortSignal })\n : await (\n target.confinedFileReader?.readDir ??\n ((options) => confinedReadDir(target, options))\n )({\n path: params.path,\n root: params.root,\n abortSignal,\n }),\n };\n }\n case HandleRpcMethod.RemovePath: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n await target.removePath({ ...params, abortSignal });\n return {};\n }\n case HandleRpcMethod.GetPortEndpoint: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n return target.getPortEndpoint(params);\n }\n case HandleRpcMethod.Stop:\n await target.stop();\n return {};\n case HandleRpcMethod.Destroy:\n await target.destroy();\n return {};\n case HandleRpcMethod.OnRuntimeShutdown: {\n if (handle == null) throw unsupported('provider lifecycle hooks');\n const shutdownHandle = handle;\n shutdown ??= (async () => {\n await Promise.allSettled([...processes.values()].map(releaseProcess));\n await Promise.allSettled([...mcpConnections.values()].map((channel) => channel.close()));\n processes.clear();\n mcpConnections.clear();\n mcpEndpoints.clear();\n await shutdownHandle.onRuntimeShutdown();\n })();\n await shutdown;\n return {};\n }\n case HandleRpcMethod.OnSandboxStop:\n if (handle == null) throw unsupported('provider lifecycle hooks');\n await handle.onSandboxStop();\n return {};\n case HandleRpcMethod.OnSandboxDelete: {\n if (handle == null) throw unsupported('provider lifecycle hooks');\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n await handle.onSandboxDelete(params);\n return {};\n }\n case HandleRpcMethod.SetNetworkPolicy: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n if (target.setNetworkPolicy == null) throw unsupported('network policy');\n await target.setNetworkPolicy(params);\n return {};\n }\n case HandleRpcMethod.Egress: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n if (target.egress == null) throw unsupported('Device egress');\n return handleRpcMethodSchemas[HandleRpcMethod.Egress].result.parse(\n await target.egress(params),\n );\n }\n case HandleRpcMethod.ComputerUse: {\n if (target.computerUse == null) throw unsupported('computer use');\n if (needsMcpChannels(target) && args.mcpChannels !== true)\n throw unsupported('guarded MCP transport; negotiate mcpChannels');\n const endpoint = await target.computerUse();\n return mcpDescriptor(endpoint, 'computerUse');\n }\n case HandleRpcMethod.McpOpen: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n const endpoint = mcpEndpoints.get(params.endpointKey);\n if (args.mcpChannels !== true || endpoint == null)\n throw unsupported('MCP channel endpoint');\n const channel = await endpoint.connect({ abortSignal });\n if (abortSignal.aborted) {\n await channel.close();\n abortSignal.throwIfAborted();\n }\n const channelId = String(++nextMcpChannelId);\n mcpConnections.set(channelId, channel);\n return { channelId };\n }\n case HandleRpcMethod.McpSend: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n await mcpConnection(params.channelId).send(params.message, { abortSignal });\n return {};\n }\n case HandleRpcMethod.McpReceive: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n return { messages: await mcpConnection(params.channelId).receive({ abortSignal }) };\n }\n case HandleRpcMethod.McpClose: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n const channel = mcpConnection(params.channelId);\n await channel.close();\n mcpConnections.delete(params.channelId);\n return {};\n }\n case HandleRpcMethod.Screen: {\n if (target.screen == null) throw unsupported('screen');\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n return target.screen(params);\n }\n case HandleRpcMethod.LocalMcp:\n if (target.localMcp == null) throw unsupported('local MCP servers');\n if (needsMcpChannels(target) && args.mcpChannels !== true)\n throw unsupported('guarded MCP transport; negotiate mcpChannels');\n return {\n endpoints: (await target.localMcp()).flatMap((endpoint, index) =>\n args.mcpChannels !== true && isMcpChannelEndpoint(endpoint)\n ? []\n : [mcpDescriptor(endpoint, `localMcp:${index}:${endpoint.name}`)],\n ),\n };\n }\n };\n\n // Registers client-to-server streams synchronously, before their chunks.\n const beforeRequest = (context: RpcRequestContextIface) => {\n if (context.method !== HandleRpcMethod.WriteFile && context.method !== HandleRpcMethod.Spawn)\n return;\n const ids = uploadStreamIdsSchema.safeParse(context.params);\n if (!ids.success) return;\n const streamId =\n context.method === HandleRpcMethod.WriteFile ? ids.data.streamId : ids.data.stdinStreamId;\n if (streamId == null) return;\n const stream = peer.streams.openIncoming(streamId);\n // Reject unauthorized or disallowed uploads before buffering their data.\n const floor =\n context.method === HandleRpcMethod.WriteFile ? SandboxAccess.Write : SandboxAccess.Execute;\n if (sandbox == null || !sandboxAccessAtLeast(access.mode, floor)) {\n peer.streams.cancelIncoming(streamId, 'rejected');\n return;\n }\n incomingByRequest.set(context.id, { streamId, stream });\n };\n\n const onClose = () => {\n if (expiryTimer != null) clearTimeout(expiryTimer);\n for (const served of processes.values()) releaseProcess(served).catch(() => undefined);\n for (const channel of mcpConnections.values()) void channel.close().catch(() => undefined);\n mcpConnections.clear();\n mcpEndpoints.clear();\n processes.clear();\n incomingByRequest.clear();\n };\n\n const peer: RpcPeerIface = createRpcPeer({\n channel: args.channel,\n binary: args.binary,\n onRequest: dispatch,\n beforeRequest,\n onClose,\n });\n\n return { close: (code, reason) => peer.close(code, reason) };\n};\n\nexport interface ServeSandboxHandleArgsIface {\n sandbox: NetworkSandboxSessionIface;\n handle?: HandleLifecycle;\n authorize: HandleAuthorizeFn;\n authorizeOperation?: HandleRpcMessageHandlerOptionsIface['authorizeOperation'];\n access?: HandleAccessPolicyIface;\n binary?: boolean;\n // The outer host applies hosted-tool policy before exposing this transport.\n mcpChannels?: boolean;\n now?: () => number;\n}\n\nexport interface SandboxHandleServerIface {\n // Attaches a connection; returns a function that closes it.\n attach(channel: FrameChannelIface, context?: { token?: string | null }): () => void;\n attachWebSocket(socket: WebSocketLikeIface, context?: { token?: string | null }): () => void;\n attachStream(stream: FrameStreamIface, context?: { token?: string | null }): () => void;\n messageHandler(args: {\n send: (frame: WireFrame) => void;\n close: (code: number, reason: string) => void;\n token?: string | null;\n }): HandleRpcMessageHandlerIface;\n}\n\nexport const serveSandboxHandle = (args: ServeSandboxHandleArgsIface): SandboxHandleServerIface => {\n const access = args.access ?? DEFAULT_HANDLE_ACCESS;\n const resolve = async (): Promise<HandleResolutionIface> => ({\n sandbox: args.sandbox,\n handle: args.handle,\n });\n const attach = (channel: FrameChannelIface, context?: { token?: string | null }) => {\n const connection = createServerConnection({\n channel,\n authorize: args.authorize,\n authorizeOperation: args.authorizeOperation,\n resolve,\n access,\n connectionToken: context?.token ?? null,\n binary: args.binary ?? true,\n mcpChannels: args.mcpChannels,\n now: args.now ?? Date.now,\n });\n return () => connection.close(HandleRpcCloseCode.Normal, 'closed');\n };\n return {\n attach,\n attachWebSocket: (socket, context) =>\n attach(frameChannelFromWebSocket(socket).channel, context),\n attachStream: (stream, context) => attach(frameChannelFromStream(stream), context),\n messageHandler: (handlerArgs) =>\n createHandleRpcMessageHandler({\n send: handlerArgs.send,\n close: handlerArgs.close,\n authorize: args.authorize,\n authorizeOperation: args.authorizeOperation,\n resolve,\n access,\n connectionToken: handlerArgs.token ?? null,\n binary: args.binary,\n mcpChannels: args.mcpChannels,\n now: args.now,\n }),\n };\n};\n"],
|
|
5
|
+
"mappings": "AAAA,YAAY,OAAO;AACnB,SAAS,6BAA6B;AAEtC,SAAS,uBAAuB,eAAe,4BAA4B;AAC3E,SAAS,eAAe,qBAAqB;AAC7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AAS,CAAC,SAA4B,YAAwC;AAClF,UAAM,aAAa,uBAAuB;AAAA,MACxC;AAAA,MACA,WAAW,KAAK;AAAA,MAChB,oBAAoB,KAAK;AAAA,MACzB;AAAA,MACA;AAAA,MACA,iBAAiB,SAAS,SAAS;AAAA,MACnC,QAAQ,KAAK,UAAU;AAAA,MACvB,aAAa,KAAK;AAAA,MAClB,KAAK,KAAK,OAAO,KAAK;AAAA,IACxB,CAAC;AACD,WAAO,MAAM,WAAW,MAAM,mBAAmB,QAAQ,QAAQ;AAAA,EACnE;AACA,SAAO;AAAA,IACL;AAAA,IACA,iBAAiB,CAAC,QAAQ,YACxB,OAAO,0BAA0B,MAAM,EAAE,SAAS,OAAO;AAAA,IAC3D,cAAc,CAAC,QAAQ,YAAY,OAAO,uBAAuB,MAAM,GAAG,OAAO;AAAA,IACjF,gBAAgB,CAAC,gBACf,8BAA8B;AAAA,MAC5B,MAAM,YAAY;AAAA,MAClB,OAAO,YAAY;AAAA,MACnB,WAAW,KAAK;AAAA,MAChB,oBAAoB,KAAK;AAAA,MACzB;AAAA,MACA;AAAA,MACA,iBAAiB,YAAY,SAAS;AAAA,MACtC,QAAQ,KAAK;AAAA,MACb,aAAa,KAAK;AAAA,MAClB,KAAK,KAAK;AAAA,IACZ,CAAC;AAAA,EACL;AACF;",
|
|
6
|
+
"names": ["args"]
|
|
7
7
|
}
|
|
@@ -21,9 +21,11 @@ export interface SandboxProcessOptionsIface extends AbortableIface {
|
|
|
21
21
|
shell?: boolean;
|
|
22
22
|
stdin?: ReadableStream<Uint8Array> | string;
|
|
23
23
|
timeoutMs?: number;
|
|
24
|
+
durable?: boolean;
|
|
24
25
|
}
|
|
25
26
|
export interface SandboxProcessIface {
|
|
26
27
|
readonly pid: string | null;
|
|
28
|
+
readonly ref?: string | null;
|
|
27
29
|
readonly stdout: ReadableStream<Uint8Array>;
|
|
28
30
|
readonly stderr: ReadableStream<Uint8Array>;
|
|
29
31
|
write(data: Uint8Array | string, options?: {
|
|
@@ -34,6 +36,22 @@ export interface SandboxProcessIface {
|
|
|
34
36
|
}>;
|
|
35
37
|
kill(signal?: string): Promise<void>;
|
|
36
38
|
}
|
|
39
|
+
export interface SandboxAttachProcessOptionsIface extends AbortableIface {
|
|
40
|
+
ref: string;
|
|
41
|
+
stdoutOffset: number;
|
|
42
|
+
stderrOffset: number;
|
|
43
|
+
}
|
|
44
|
+
export interface SandboxAttachedProcessIface {
|
|
45
|
+
readonly ref: string;
|
|
46
|
+
readonly stdoutOffset: number;
|
|
47
|
+
readonly stderrOffset: number;
|
|
48
|
+
readonly stdout: ReadableStream<Uint8Array>;
|
|
49
|
+
readonly stderr: ReadableStream<Uint8Array>;
|
|
50
|
+
wait(): Promise<{
|
|
51
|
+
exitCode: number;
|
|
52
|
+
}>;
|
|
53
|
+
kill(signal?: string): Promise<void>;
|
|
54
|
+
}
|
|
37
55
|
export interface SandboxRunResultIface {
|
|
38
56
|
exitCode: number;
|
|
39
57
|
stdout: string;
|
|
@@ -96,6 +114,7 @@ export interface SandboxSessionIface {
|
|
|
96
114
|
encoding?: string;
|
|
97
115
|
} & AbortableIface): Promise<void>;
|
|
98
116
|
spawn(options: SandboxProcessOptionsIface): Promise<SandboxProcessIface>;
|
|
117
|
+
attachProcess?(options: SandboxAttachProcessOptionsIface): Promise<SandboxAttachedProcessIface | null>;
|
|
99
118
|
run(options: SandboxProcessOptionsIface): Promise<SandboxRunResultIface>;
|
|
100
119
|
stat(options: {
|
|
101
120
|
path: string;
|
|
@@ -178,7 +197,8 @@ export declare enum SandboxCapability {
|
|
|
178
197
|
ComputerUse = "computerUse",
|
|
179
198
|
Screen = "screen",
|
|
180
199
|
LocalMcp = "localMcp",
|
|
181
|
-
Browser = "browser"
|
|
200
|
+
Browser = "browser",
|
|
201
|
+
DurableProcesses = "durableProcesses"
|
|
182
202
|
}
|
|
183
203
|
export interface SandboxProviderHandleIface<S extends SandboxSessionIface> {
|
|
184
204
|
readonly sandbox: S;
|
|
@@ -28,6 +28,7 @@ var SandboxCapability = /* @__PURE__ */ ((SandboxCapability2) => {
|
|
|
28
28
|
SandboxCapability2["Screen"] = "screen";
|
|
29
29
|
SandboxCapability2["LocalMcp"] = "localMcp";
|
|
30
30
|
SandboxCapability2["Browser"] = "browser";
|
|
31
|
+
SandboxCapability2["DurableProcesses"] = "durableProcesses";
|
|
31
32
|
return SandboxCapability2;
|
|
32
33
|
})(SandboxCapability || {});
|
|
33
34
|
const noSandboxGuides = {
|