@finalai/agent-provider 0.2.3 → 0.4.1

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 (60) hide show
  1. package/README.md +61 -0
  2. package/dist/modules/sandbox/client.mjs +3 -0
  3. package/dist/modules/sandbox/client.mjs.map +2 -2
  4. package/dist/modules/sandbox/confined-files.d.mts +2 -2
  5. package/dist/modules/sandbox/confined-files.mjs +5 -2
  6. package/dist/modules/sandbox/confined-files.mjs.map +2 -2
  7. package/dist/modules/sandbox/execution-guard.d.mts +36 -0
  8. package/dist/modules/sandbox/execution-guard.mjs +322 -0
  9. package/dist/modules/sandbox/execution-guard.mjs.map +7 -0
  10. package/dist/modules/sandbox/file-kind.d.mts +6 -0
  11. package/dist/modules/sandbox/file-kind.mjs +11 -0
  12. package/dist/modules/sandbox/file-kind.mjs.map +7 -0
  13. package/dist/modules/sandbox/file-schemas.d.mts +15 -0
  14. package/dist/modules/sandbox/file-schemas.mjs +22 -0
  15. package/dist/modules/sandbox/file-schemas.mjs.map +7 -0
  16. package/dist/modules/sandbox/handle.d.mts +15 -0
  17. package/dist/modules/sandbox/handle.mjs +47 -0
  18. package/dist/modules/sandbox/handle.mjs.map +7 -0
  19. package/dist/modules/sandbox/index.d.mts +8 -0
  20. package/dist/modules/sandbox/index.mjs +30 -1
  21. package/dist/modules/sandbox/index.mjs.map +2 -2
  22. package/dist/modules/sandbox/mcp-channel.d.mts +8 -1
  23. package/dist/modules/sandbox/mcp-channel.mjs +217 -15
  24. package/dist/modules/sandbox/mcp-channel.mjs.map +3 -3
  25. package/dist/modules/sandbox/mcp-hosted-marker.d.mts +3 -0
  26. package/dist/modules/sandbox/mcp-hosted-marker.mjs +10 -0
  27. package/dist/modules/sandbox/mcp-hosted-marker.mjs.map +7 -0
  28. package/dist/modules/sandbox/mcp-hosted.d.mts +6 -1
  29. package/dist/modules/sandbox/mcp-hosted.mjs +127 -41
  30. package/dist/modules/sandbox/mcp-hosted.mjs.map +2 -2
  31. package/dist/modules/sandbox/mcp-shell.mjs +14 -4
  32. package/dist/modules/sandbox/mcp-shell.mjs.map +2 -2
  33. package/dist/modules/sandbox/mcp.d.mts +5 -2
  34. package/dist/modules/sandbox/mcp.mjs +102 -27
  35. package/dist/modules/sandbox/mcp.mjs.map +2 -2
  36. package/dist/modules/sandbox/networking.d.mts +73 -0
  37. package/dist/modules/sandbox/networking.mjs +149 -0
  38. package/dist/modules/sandbox/networking.mjs.map +7 -0
  39. package/dist/modules/sandbox/overrides.d.mts +2 -0
  40. package/dist/modules/sandbox/overrides.mjs +44 -0
  41. package/dist/modules/sandbox/overrides.mjs.map +7 -0
  42. package/dist/modules/sandbox/server.d.mts +1 -0
  43. package/dist/modules/sandbox/server.mjs +38 -2
  44. package/dist/modules/sandbox/server.mjs.map +2 -2
  45. package/dist/modules/sandbox/testing.d.mts +1 -0
  46. package/dist/modules/sandbox/testing.mjs +1 -0
  47. package/dist/modules/sandbox/testing.mjs.map +2 -2
  48. package/dist/modules/sandbox/tool-policy.d.mts +5 -0
  49. package/dist/modules/sandbox/tool-policy.mjs +62 -0
  50. package/dist/modules/sandbox/tool-policy.mjs.map +7 -0
  51. package/dist/modules/sandbox/types.d.mts +17 -16
  52. package/dist/modules/sandbox/types.mjs +54 -23
  53. package/dist/modules/sandbox/types.mjs.map +3 -3
  54. package/dist/modules/sandbox/wire.d.mts +23 -18
  55. package/dist/modules/sandbox/wire.mjs +21 -20
  56. package/dist/modules/sandbox/wire.mjs.map +3 -3
  57. package/dist/modules/sandbox/workspace-identity.d.mts +5 -0
  58. package/dist/modules/sandbox/workspace-identity.mjs +14 -0
  59. package/dist/modules/sandbox/workspace-identity.mjs.map +7 -0
  60. package/package.json +3 -3
@@ -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 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 { 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 servesComputerUse = async (sandbox: NetworkSandboxSessionIface): Promise<boolean> => {\n if (sandbox.computerUse == null) 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 (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) 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 (!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 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.ComputerUse: {\n if (target.computerUse == null) throw unsupported('computer use');\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 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 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 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 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;AAEnB,SAAS,uBAAuB,eAAe,4BAA4B;AAC3E,SAAS,eAAe,qBAAqB;AAC7C,SAAS,iBAAiB,kBAAkB,oBAAoB;AAChE,SAAS,qBAAqE;AAC9E;AAAA,EACE;AAAA,EACA;AAAA,OAOK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAOK;AAcA,MAAM,wBAAiD;AAAA,EAC5D,MAAM,cAAc;AAAA,EACpB,WAAW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;AAAA,MACA,WAAW,KAAK;AAAA,MAChB;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;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;",
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;AAAA,EACE;AAAA,EACA;AAAA,OAOK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAOK;AAcA,MAAM,wBAAiD;AAAA,EAC5D,MAAM,cAAc;AAAA,EACpB,WAAW;AACb;AAqDA,MAAM,mBAAmB,CAAC,YACxB,yBAAyB,OAAO,KAAK,CAAC,sBAAsB,OAAO;AAErE,MAAM,oBAAoB,OAAO,YAA0D;AACzF,MAAI,QAAQ,eAAe,QAAQ,iBAAiB,OAAO,EAAG,QAAO;AACrE,MAAI;AACF,WAAO,CAAC,qBAAqB,MAAM,QAAQ,YAAY,CAAC;AAAA,EAC1D,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEA,MAAM,iBAAiB,OACrB,SACA,cAAc,UACmB;AACjC,QAAM,eAAe,CAAC,kBAAkB,OAAO,kBAAkB,OAAO;AACxE,MAAI,QAAQ,MAAM,SAAS,EAAG,cAAa,KAAK,kBAAkB,KAAK;AACvE,MAAI,QAAQ,oBAAoB,KAAM,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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
6
  "names": []
7
7
  }
@@ -8,6 +8,7 @@ export interface InMemoryHandleNetworkIface {
8
8
  sandbox: NetworkSandboxSessionIface;
9
9
  handle?: HandleLifecycle;
10
10
  authorize?: HandleAuthorizeFn;
11
+ authorizeOperation?: HandleRpcMessageHandlerOptionsIface['authorizeOperation'];
11
12
  access?: HandleAccessPolicyIface;
12
13
  binary?: boolean;
13
14
  mcpChannels?: boolean;
@@ -17,6 +17,7 @@ const createInMemoryHandleNetwork = () => {
17
17
  sandbox: args.sandbox,
18
18
  handle: args.handle,
19
19
  authorize: args.authorize ?? allowAllTokens,
20
+ authorizeOperation: args.authorizeOperation,
20
21
  access: args.access,
21
22
  binary: args.binary,
22
23
  mcpChannels: args.mcpChannels
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/sandbox/testing.ts"],
4
- "sourcesContent": ["import {\n connectSandboxClient,\n type ConnectSandboxClientArgsIface,\n type SandboxClientIface,\n} from \"./client.mjs\";\nimport {\n createHandleRpcMessageHandler,\n serveSandboxHandle,\n type HandleAccessPolicyIface,\n type HandleAuthorizeFn,\n type HandleLifecycle,\n type HandleRpcMessageHandlerOptionsIface,\n} from \"./server.mjs\";\nimport type { NetworkSandboxSessionIface } from \"./types.mjs\";\nimport { createFrameChannelPair, type FrameChannelIface } from \"./wire.mjs\";\n\n// In-memory hosting for the handle RPC: routes dial URLs to in-process\n// endpoints over frame channel pairs. Used by tests and the conformance kit.\n\nexport interface InMemoryHandleNetworkIface {\n // Serves `sandbox` at `url`.\n serve(args: {\n url: string;\n sandbox: NetworkSandboxSessionIface;\n handle?: HandleLifecycle;\n authorize?: HandleAuthorizeFn;\n access?: HandleAccessPolicyIface;\n binary?: boolean;\n mcpChannels?: boolean;\n }): void;\n // Mounts a raw message handler at `url` (a stable endpoint that starts the\n // sandbox on the first connection).\n mount(\n url: string,\n options: Omit<HandleRpcMessageHandlerOptionsIface, 'send' | 'close' | 'connectionToken'>,\n ): void;\n openChannel(target: { url: string; token: string }): Promise<FrameChannelIface>;\n connect(args: Omit<ConnectSandboxClientArgsIface, 'openChannel'>): Promise<SandboxClientIface>;\n // Closes every connection the network opened (simulates a network drop).\n dropAll(): void;\n dials(): string[];\n}\n\nexport const allowAllTokens: HandleAuthorizeFn = async () => ({ expiresAt: null });\n\nexport const createInMemoryHandleNetwork = (): InMemoryHandleNetworkIface => {\n const endpoints = new Map<string, (channel: FrameChannelIface, token: string) => void>();\n const open = new Set<FrameChannelIface>();\n const dialLog: string[] = [];\n const network: InMemoryHandleNetworkIface = {\n serve: (args) => {\n const server = serveSandboxHandle({\n sandbox: args.sandbox,\n handle: args.handle,\n authorize: args.authorize ?? allowAllTokens,\n access: args.access,\n binary: args.binary,\n mcpChannels: args.mcpChannels,\n });\n endpoints.set(args.url, (channel, token) => {\n server.attach(channel, { token });\n });\n },\n mount: (url, options) => {\n endpoints.set(url, (channel, token) => {\n const handler = createHandleRpcMessageHandler({\n ...options,\n connectionToken: token,\n send: (frame) => channel.send(frame),\n close: (code, reason) => channel.close(code, reason),\n });\n channel.listen({\n frame: (frame) => handler.onFrame(frame),\n close: (info) => handler.onClose(info.code, info.reason),\n });\n });\n },\n openChannel: async (target) => {\n dialLog.push(target.url);\n const endpoint = endpoints.get(target.url);\n if (endpoint == null) throw new Error(`nothing listens at ${target.url}`);\n const [client, server] = createFrameChannelPair();\n open.add(client);\n endpoint(server, target.token);\n return client;\n },\n connect: (args) => connectSandboxClient({ ...args, openChannel: network.openChannel }),\n dropAll: () => {\n for (const channel of open) channel.close(1006, 'network drop');\n open.clear();\n },\n dials: () => [...dialLog],\n };\n return network;\n};\n"],
5
- "mappings": "AAAA;AAAA,EACE;AAAA,OAGK;AACP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,QAAQ,MAAM,IAAI,uBAAuB;AAChD,WAAK,IAAI,MAAM;AACf,eAAS,QAAQ,OAAO,KAAK;AAC7B,aAAO;AAAA,IACT;AAAA,IACA,SAAS,CAAC,SAAS,qBAAqB,EAAE,GAAG,MAAM,aAAa,QAAQ,YAAY,CAAC;AAAA,IACrF,SAAS,MAAM;AACb,iBAAW,WAAW,KAAM,SAAQ,MAAM,MAAM,cAAc;AAC9D,WAAK,MAAM;AAAA,IACb;AAAA,IACA,OAAO,MAAM,CAAC,GAAG,OAAO;AAAA,EAC1B;AACA,SAAO;AACT;",
4
+ "sourcesContent": ["import {\n connectSandboxClient,\n type ConnectSandboxClientArgsIface,\n type SandboxClientIface,\n} from \"./client.mjs\";\nimport {\n createHandleRpcMessageHandler,\n serveSandboxHandle,\n type HandleAccessPolicyIface,\n type HandleAuthorizeFn,\n type HandleLifecycle,\n type HandleRpcMessageHandlerOptionsIface,\n} from \"./server.mjs\";\nimport type { NetworkSandboxSessionIface } from \"./types.mjs\";\nimport { createFrameChannelPair, type FrameChannelIface } from \"./wire.mjs\";\n\n// In-memory hosting for the handle RPC: routes dial URLs to in-process\n// endpoints over frame channel pairs. Used by tests and the conformance kit.\n\nexport interface InMemoryHandleNetworkIface {\n // Serves `sandbox` at `url`.\n serve(args: {\n url: string;\n sandbox: NetworkSandboxSessionIface;\n handle?: HandleLifecycle;\n authorize?: HandleAuthorizeFn;\n authorizeOperation?: HandleRpcMessageHandlerOptionsIface['authorizeOperation'];\n access?: HandleAccessPolicyIface;\n binary?: boolean;\n mcpChannels?: boolean;\n }): void;\n // Mounts a raw message handler at `url` (a stable endpoint that starts the\n // sandbox on the first connection).\n mount(\n url: string,\n options: Omit<HandleRpcMessageHandlerOptionsIface, 'send' | 'close' | 'connectionToken'>,\n ): void;\n openChannel(target: { url: string; token: string }): Promise<FrameChannelIface>;\n connect(args: Omit<ConnectSandboxClientArgsIface, 'openChannel'>): Promise<SandboxClientIface>;\n // Closes every connection the network opened (simulates a network drop).\n dropAll(): void;\n dials(): string[];\n}\n\nexport const allowAllTokens: HandleAuthorizeFn = async () => ({ expiresAt: null });\n\nexport const createInMemoryHandleNetwork = (): InMemoryHandleNetworkIface => {\n const endpoints = new Map<string, (channel: FrameChannelIface, token: string) => void>();\n const open = new Set<FrameChannelIface>();\n const dialLog: string[] = [];\n const network: InMemoryHandleNetworkIface = {\n serve: (args) => {\n const server = serveSandboxHandle({\n sandbox: args.sandbox,\n handle: args.handle,\n authorize: args.authorize ?? allowAllTokens,\n authorizeOperation: args.authorizeOperation,\n access: args.access,\n binary: args.binary,\n mcpChannels: args.mcpChannels,\n });\n endpoints.set(args.url, (channel, token) => {\n server.attach(channel, { token });\n });\n },\n mount: (url, options) => {\n endpoints.set(url, (channel, token) => {\n const handler = createHandleRpcMessageHandler({\n ...options,\n connectionToken: token,\n send: (frame) => channel.send(frame),\n close: (code, reason) => channel.close(code, reason),\n });\n channel.listen({\n frame: (frame) => handler.onFrame(frame),\n close: (info) => handler.onClose(info.code, info.reason),\n });\n });\n },\n openChannel: async (target) => {\n dialLog.push(target.url);\n const endpoint = endpoints.get(target.url);\n if (endpoint == null) throw new Error(`nothing listens at ${target.url}`);\n const [client, server] = createFrameChannelPair();\n open.add(client);\n endpoint(server, target.token);\n return client;\n },\n connect: (args) => connectSandboxClient({ ...args, openChannel: network.openChannel }),\n dropAll: () => {\n for (const channel of open) channel.close(1006, 'network drop');\n open.clear();\n },\n dials: () => [...dialLog],\n };\n return network;\n};\n"],
5
+ "mappings": "AAAA;AAAA,EACE;AAAA,OAGK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OAKK;AAEP,SAAS,8BAAsD;AA8BxD,MAAM,iBAAoC,aAAa,EAAE,WAAW,KAAK;AAEzE,MAAM,8BAA8B,MAAkC;AAC3E,QAAM,YAAY,oBAAI,IAAiE;AACvF,QAAM,OAAO,oBAAI,IAAuB;AACxC,QAAM,UAAoB,CAAC;AAC3B,QAAM,UAAsC;AAAA,IAC1C,OAAO,CAA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Q,MAAM,MAAM,cAAc;AAC9D,WAAK,MAAM;AAAA,IACb;AAAA,IACA,OAAO,MAAM,CAAC,GAAG,OAAO;AAAA,EAC1B;AACA,SAAO;AACT;",
6
6
  "names": []
7
7
  }
@@ -0,0 +1,5 @@
1
+ import { ToolApproval } from "../manifest.mjs";
2
+ export declare const resolveSandboxToolPolicy: (policy: Record<string, ToolApproval>, keys: readonly string[]) => {
3
+ key: string;
4
+ decision: ToolApproval;
5
+ } | null;
@@ -0,0 +1,62 @@
1
+ import { ToolApproval } from "../manifest.mjs";
2
+ const nativePolicyKeys = /* @__PURE__ */ new Set([
3
+ "run",
4
+ "spawn",
5
+ "process_output",
6
+ "process_input",
7
+ "process_terminate",
8
+ "read_file",
9
+ "write_file",
10
+ "edit_file",
11
+ "list_dir",
12
+ "stat",
13
+ "grep",
14
+ "glob",
15
+ "get_host",
16
+ "files",
17
+ "process",
18
+ "ports",
19
+ "networkPolicy",
20
+ "egress",
21
+ "computerUse",
22
+ "screen",
23
+ "localMcp",
24
+ "browser",
25
+ "shell",
26
+ "files.read",
27
+ "files.write",
28
+ "lifecycle",
29
+ "network",
30
+ "network.egress",
31
+ "network.egress.configure",
32
+ "network.egress.disable",
33
+ "network.egress.status"
34
+ ]);
35
+ const resolveSandboxToolPolicy = (policy, keys) => {
36
+ const valueOf = (key) => Object.hasOwn(policy, key) ? policy[key] : void 0;
37
+ const egress = keys.includes("egress") && keys.includes("network.egress");
38
+ if (egress) {
39
+ const key = keys.find((candidate) => valueOf(candidate) === ToolApproval.Ask);
40
+ if (key != null) return { key, decision: ToolApproval.Ask };
41
+ }
42
+ if (egress && (keys.includes("network.egress.configure") || keys.includes("network.egress.disable"))) {
43
+ const actionKey = keys.includes("network.egress.configure") ? "network.egress.configure" : "network.egress.disable";
44
+ const key = valueOf(actionKey) === ToolApproval.Allow ? actionKey : void 0;
45
+ return {
46
+ key: key ?? actionKey,
47
+ decision: key == null ? ToolApproval.Ask : ToolApproval.Allow
48
+ };
49
+ }
50
+ const hosted = keys.length > 1 && (keys.includes("localMcp") || keys.includes("computerUse"));
51
+ for (const [index, key] of keys.entries()) {
52
+ const decision = valueOf(key);
53
+ if (hosted && index === 0 && nativePolicyKeys.has(key) && decision === ToolApproval.Allow)
54
+ continue;
55
+ if (decision === ToolApproval.Ask || decision === ToolApproval.Allow) return { key, decision };
56
+ }
57
+ return null;
58
+ };
59
+ export {
60
+ resolveSandboxToolPolicy
61
+ };
62
+ //# sourceMappingURL=tool-policy.mjs.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../../src/sandbox/tool-policy.ts"],
4
+ "sourcesContent": ["import { ToolApproval } from \"../manifest.mjs\";\n\n// Native names remain eligible for Ask, but cannot lend an Allow to a hosted tool.\nconst nativePolicyKeys = new Set([\n 'run',\n 'spawn',\n 'process_output',\n 'process_input',\n 'process_terminate',\n 'read_file',\n 'write_file',\n 'edit_file',\n 'list_dir',\n 'stat',\n 'grep',\n 'glob',\n 'get_host',\n 'files',\n 'process',\n 'ports',\n 'networkPolicy',\n 'egress',\n 'computerUse',\n 'screen',\n 'localMcp',\n 'browser',\n 'shell',\n 'files.read',\n 'files.write',\n 'lifecycle',\n 'network',\n 'network.egress',\n 'network.egress.configure',\n 'network.egress.disable',\n 'network.egress.status',\n]);\n\n// Network and lifecycle consent both apply to egress mutations; neither Allow can waive an Ask.\nexport const resolveSandboxToolPolicy = (\n policy: Record<string, ToolApproval>,\n keys: readonly string[],\n): { key: string; decision: ToolApproval } | null => {\n const valueOf = (key: string) => (Object.hasOwn(policy, key) ? policy[key] : undefined);\n const egress = keys.includes('egress') && keys.includes('network.egress');\n if (egress) {\n const key = keys.find((candidate) => valueOf(candidate) === ToolApproval.Ask);\n if (key != null) return { key, decision: ToolApproval.Ask };\n }\n if (\n egress &&\n (keys.includes('network.egress.configure') || keys.includes('network.egress.disable'))\n ) {\n const actionKey = keys.includes('network.egress.configure')\n ? 'network.egress.configure'\n : 'network.egress.disable';\n const key = valueOf(actionKey) === ToolApproval.Allow ? actionKey : undefined;\n return {\n key: key ?? actionKey,\n decision: key == null ? ToolApproval.Ask : ToolApproval.Allow,\n };\n }\n const hosted = keys.length > 1 && (keys.includes('localMcp') || keys.includes('computerUse'));\n for (const [index, key] of keys.entries()) {\n const decision = valueOf(key);\n if (hosted && index === 0 && nativePolicyKeys.has(key) && decision === ToolApproval.Allow)\n continue;\n if (decision === ToolApproval.Ask || decision === ToolApproval.Allow) return { key, decision };\n }\n return null;\n};\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAG7B,MAAM,mBAAmB,oBAAI,IAAI;AAAA,EAC/B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAGM,MAAM,2BAA2B,CACtC,QACA,SACmD;AACnD,QAAM,UAAU,CAAC,QAAiB,OAAO,OAAO,QAAQ,GAAG,IAAI,OAAO,GAAG,IAAI;AAC7E,QAAM,SAAS,KAAK,SAAS,QAAQ,KAAK,KAAK,SAAS,gBAAgB;AACxE,MAAI,QAAQ;AACV,UAAM,MAAM,KAAK,KAAK,CAAC,cAAc,QAAQ,SAAS,MAAM,aAAa,GAAG;AAC5E,QAAI,OAAO,KAAM,QAAO,EAAE,KAAK,UAAU,aAAa,IAAI;AAAA,EAC5D;AACA,MACE,WACC,KAAK,SAAS,0BAA0B,KAAK,KAAK,SAAS,wBAAwB,IACpF;AACA,UAAM,YAAY,KAAK,SAAS,0BAA0B,IACtD,6BACA;AACJ,UAAM,MAAM,QAAQ,SAAS,MAAM,aAAa,QAAQ,YAAY;AACpE,WAAO;AAAA,MACL,KAAK,OAAO;AAAA,MACZ,UAAU,OAAO,OAAO,aAAa,MAAM,aAAa;AAAA,IAC1D;AAAA,EACF;AACA,QAAM,SAAS,KAAK,SAAS,MAAM,KAAK,SAAS,UAAU,KAAK,KAAK,SAAS,aAAa;AAC3F,aAAW,CAAC,OAAO,GAAG,KAAK,KAAK,QAAQ,GAAG;AACzC,UAAM,WAAW,QAAQ,GAAG;AAC5B,QAAI,UAAU,UAAU,KAAK,iBAAiB,IAAI,GAAG,KAAK,aAAa,aAAa;AAClF;AACF,QAAI,aAAa,aAAa,OAAO,aAAa,aAAa,MAAO,QAAO,EAAE,KAAK,SAAS;AAAA,EAC/F;AACA,SAAO;AACT;",
6
+ "names": []
7
+ }
@@ -1,8 +1,13 @@
1
+ import { SandboxEntryType } from "./file-kind.mjs";
2
+ export { SandboxEntryType } from "./file-kind.mjs";
1
3
  import type { HostedBindingsIface } from "../hosted-bindings.mjs";
4
+ import { type SandboxExecutionPolicyIface } from "./handle.mjs";
5
+ import type { WorkspaceEgressRequestIface, WorkspaceEgressStatusIface, WorkspaceNetworkPolicyIface as NetworkPolicyIface } from '@finalai/agent-protocol/device-egress';
6
+ export { WorkspaceNetworkPolicy as NetworkPolicy, type WorkspaceNetworkPolicyIface as NetworkPolicyIface, } from '@finalai/agent-protocol/device-egress';
2
7
  import type { ProcessInspectionRequestIface, ProcessInspectionResultIface } from '@finalai/agent-protocol/process-inspection';
3
8
  import type { JsonValue } from "../json.mjs";
4
9
  import type { ToolDescriptorIface } from "../manifest.mjs";
5
- import type { SandboxEditorRequestIface, SandboxEditorResultIface } from "./editor.mjs";
10
+ import { type SandboxEditorRequestIface, type SandboxEditorResultIface } from "./editor.mjs";
6
11
  import { type AwaitableSandboxOpenRequestIface } from "./open-scope.mjs";
7
12
  import type { SandboxSnapshotRequestIface, SandboxSnapshotResponseIface } from "./snapshots.mjs";
8
13
  export interface AbortableIface {
@@ -34,12 +39,6 @@ export interface SandboxRunResultIface {
34
39
  stdout: string;
35
40
  stderr: string;
36
41
  }
37
- export declare enum SandboxEntryType {
38
- File = "file",
39
- Directory = "directory",
40
- Symlink = "symlink",
41
- Other = "other"
42
- }
43
42
  export interface StatIface {
44
43
  path: string;
45
44
  type: SandboxEntryType;
@@ -113,15 +112,6 @@ export interface SandboxSessionIface {
113
112
  force?: boolean;
114
113
  } & AbortableIface): Promise<void>;
115
114
  }
116
- export declare enum NetworkPolicy {
117
- AllowAll = "allow-all",
118
- DenyAll = "deny-all",
119
- Allowlist = "allowlist"
120
- }
121
- export interface NetworkPolicyIface {
122
- mode: NetworkPolicy;
123
- allow?: string[];
124
- }
125
115
  export declare enum PortProtocol {
126
116
  Http = "http",
127
117
  Https = "https",
@@ -145,6 +135,7 @@ export type SandboxMcpEndpoint = McpEndpointIface | McpChannelEndpointIface;
145
135
  export interface SandboxMcpCatalogIface {
146
136
  computerUse: ToolDescriptorIface[] | null;
147
137
  localMcp: Record<string, ToolDescriptorIface[]> | null;
138
+ localMcpIncomplete?: boolean;
148
139
  }
149
140
  export declare const isMcpChannelEndpoint: (endpoint: SandboxMcpEndpoint) => endpoint is McpChannelEndpointIface;
150
141
  export interface ScreenOptionsIface {
@@ -173,6 +164,7 @@ export interface NetworkSandboxSessionIface extends SandboxSessionIface {
173
164
  stop(): Promise<void>;
174
165
  destroy(): Promise<void>;
175
166
  setNetworkPolicy?(policy: NetworkPolicyIface): Promise<void>;
167
+ egress?(request: WorkspaceEgressRequestIface): Promise<WorkspaceEgressStatusIface>;
176
168
  computerUse?(): Promise<SandboxMcpEndpoint>;
177
169
  screen?(options?: ScreenOptionsIface): Promise<ScreenSessionIface>;
178
170
  localMcp?(): Promise<SandboxMcpEndpoint[]>;
@@ -182,6 +174,7 @@ export declare enum SandboxCapability {
182
174
  Process = "process",
183
175
  Ports = "ports",
184
176
  NetworkPolicy = "networkPolicy",
177
+ Egress = "egress",
185
178
  ComputerUse = "computerUse",
186
179
  Screen = "screen",
187
180
  LocalMcp = "localMcp",
@@ -189,6 +182,7 @@ export declare enum SandboxCapability {
189
182
  }
190
183
  export interface SandboxProviderHandleIface<S extends SandboxSessionIface> {
191
184
  readonly sandbox: S;
185
+ readonly executionPolicy?: SandboxExecutionPolicyIface;
192
186
  onSandboxStop(): Promise<void>;
193
187
  onSandboxDelete(options?: {
194
188
  reason?: string;
@@ -240,6 +234,10 @@ export interface SandboxActingUserIface {
240
234
  }
241
235
  export declare const noSandboxActingUser: SandboxActingUserIface;
242
236
  export interface SandboxOfferContextIface {
237
+ executionPolicy?: SandboxExecutionPolicyIface;
238
+ platformNetworkPolicy?: (policy: NetworkPolicyIface) => Promise<void>;
239
+ platformEgressHosts?: string[];
240
+ workspaceId?: string;
243
241
  bindings?: HostedBindingsIface;
244
242
  organizationId: string;
245
243
  actingUser: SandboxActingUserIface;
@@ -274,6 +272,7 @@ export interface SandboxPrepareContextIface {
274
272
  log?: (message: string) => void;
275
273
  }
276
274
  export interface SandboxStartContextIface {
275
+ executionPolicy?: SandboxExecutionPolicyIface;
277
276
  bindings?: HostedBindingsIface;
278
277
  /** Passive recovery only: never wake, create, seed, or restart backend services. */
279
278
  passive?: boolean;
@@ -284,6 +283,7 @@ export interface SandboxStartContextIface {
284
283
  conversationId: string | null;
285
284
  definitionId: string;
286
285
  bindingId: string;
286
+ workspaceId?: string;
287
287
  target: string;
288
288
  };
289
289
  storagePath: string;
@@ -314,6 +314,7 @@ export declare enum SandboxWorkspace {
314
314
  export interface SandboxProviderImplementationIface<OpenOptions, Artifact extends JsonValue, State extends JsonValue, S extends NetworkSandboxSessionIface> {
315
315
  workspace?(ctx: SandboxEnvironmentContextIface): Promise<SandboxWorkspace | null>;
316
316
  capabilities?(ctx: SandboxOfferContextIface): Promise<SandboxCapability[] | null>;
317
+ additionalCapabilities?(ctx: SandboxOfferContextIface): Promise<SandboxCapability[]>;
317
318
  mcpCatalog?(ctx: SandboxOfferContextIface): Promise<SandboxMcpCatalogIface | null>;
318
319
  readSnapshot?(ctx: SandboxOfferContextIface, state: State, request: SandboxSnapshotRequestIface): Promise<SandboxSnapshotResponseIface | null>;
319
320
  processes?(ctx: SandboxOfferContextIface & {
@@ -1,17 +1,16 @@
1
+ import { SandboxEntryType } from "./file-kind.mjs";
2
+ import { SandboxEntryType as SandboxEntryType2 } from "./file-kind.mjs";
3
+ import { createSandboxHandle } from "./handle.mjs";
4
+ import { withSandboxOverrides } from "./overrides.mjs";
5
+ import { WorkspaceNetworkPolicy as NetworkPolicy } from "@finalai/agent-protocol/device-egress";
6
+ import {
7
+ WorkspaceNetworkPolicy
8
+ } from "@finalai/agent-protocol/device-egress";
9
+ import {
10
+ SandboxEditorOperation
11
+ } from "./editor.mjs";
12
+ import { SandboxExecutionOperation } from "./execution-guard.mjs";
1
13
  import { awaitableOpenRequest } from "./open-scope.mjs";
2
- var SandboxEntryType = /* @__PURE__ */ ((SandboxEntryType2) => {
3
- SandboxEntryType2["File"] = "file";
4
- SandboxEntryType2["Directory"] = "directory";
5
- SandboxEntryType2["Symlink"] = "symlink";
6
- SandboxEntryType2["Other"] = "other";
7
- return SandboxEntryType2;
8
- })(SandboxEntryType || {});
9
- var NetworkPolicy = /* @__PURE__ */ ((NetworkPolicy2) => {
10
- NetworkPolicy2["AllowAll"] = "allow-all";
11
- NetworkPolicy2["DenyAll"] = "deny-all";
12
- NetworkPolicy2["Allowlist"] = "allowlist";
13
- return NetworkPolicy2;
14
- })(NetworkPolicy || {});
15
14
  var PortProtocol = /* @__PURE__ */ ((PortProtocol2) => {
16
15
  PortProtocol2["Http"] = "http";
17
16
  PortProtocol2["Https"] = "https";
@@ -24,6 +23,7 @@ var SandboxCapability = /* @__PURE__ */ ((SandboxCapability2) => {
24
23
  SandboxCapability2["Process"] = "process";
25
24
  SandboxCapability2["Ports"] = "ports";
26
25
  SandboxCapability2["NetworkPolicy"] = "networkPolicy";
26
+ SandboxCapability2["Egress"] = "egress";
27
27
  SandboxCapability2["ComputerUse"] = "computerUse";
28
28
  SandboxCapability2["Screen"] = "screen";
29
29
  SandboxCapability2["LocalMcp"] = "localMcp";
@@ -62,11 +62,11 @@ const writePlatformFiles = async (ctx, sandbox) => {
62
62
  await sandbox.writeTextFile({ path, content });
63
63
  };
64
64
  const reportPlatformNetworkPolicy = async (ctx, policy) => ctx.platformNetworkPolicy(
65
- policy.mode === "allowlist" /* Allowlist */ ? { mode: policy.mode, allow: [...policy.allow ?? []] } : { mode: policy.mode }
65
+ policy.mode === NetworkPolicy.Allowlist ? { mode: policy.mode, allow: [...policy.allow ?? []] } : { mode: policy.mode }
66
66
  );
67
67
  const withPlatformEgressHosts = (ctx, policy) => {
68
68
  const hosts = ctx.platformEgressHosts ?? [];
69
- if (policy.mode !== "allowlist" /* Allowlist */ || hosts.length === 0) return policy;
69
+ if (policy.mode !== NetworkPolicy.Allowlist || hosts.length === 0) return policy;
70
70
  return { ...policy, allow: [.../* @__PURE__ */ new Set([...policy.allow ?? [], ...hosts])] };
71
71
  };
72
72
  var SandboxSessionEndReason = /* @__PURE__ */ ((SandboxSessionEndReason2) => {
@@ -82,17 +82,48 @@ var SandboxWorkspace = /* @__PURE__ */ ((SandboxWorkspace2) => {
82
82
  return SandboxWorkspace2;
83
83
  })(SandboxWorkspace || {});
84
84
  const defineSandboxProvider = (definition) => ({
85
- // An implementation exists only once its options are given, so awaitRunning is
86
- // checked as each environment is defined, before anything can start from it.
87
- definition: {
88
- ...definition,
85
+ definition: withSandboxOverrides(definition, {
89
86
  environment: (options) => {
90
87
  const implementation = definition.environment(options);
91
88
  if (typeof implementation.awaitRunning !== "function")
92
89
  throw new Error(`sandbox provider ${definition.name} does not implement awaitRunning`);
93
- return implementation;
90
+ const overrides = {
91
+ start: async (ctx, openOptions, artifact) => {
92
+ const started = await implementation.start(ctx, openOptions, artifact);
93
+ return {
94
+ ...started,
95
+ handle: createSandboxHandle({
96
+ handle: started.handle,
97
+ executionPolicy: ctx.executionPolicy
98
+ })
99
+ };
100
+ },
101
+ resume: async (ctx, artifact, state) => createSandboxHandle({
102
+ handle: await implementation.resume(ctx, artifact, state),
103
+ executionPolicy: ctx.executionPolicy
104
+ })
105
+ };
106
+ if (implementation.editor != null) {
107
+ const editor = implementation.editor.bind(implementation);
108
+ overrides.editor = async (ctx, state, request) => {
109
+ if (request.operation === SandboxEditorOperation.Open || request.operation === SandboxEditorOperation.Refresh)
110
+ await ctx.executionPolicy?.beforeExecution({
111
+ operation: SandboxExecutionOperation.Editor,
112
+ background: false
113
+ });
114
+ return editor(ctx, state, request);
115
+ };
116
+ }
117
+ if (implementation.resumePassive != null) {
118
+ const resumePassive = implementation.resumePassive.bind(implementation);
119
+ overrides.resumePassive = async (ctx, artifact, state) => createSandboxHandle({
120
+ handle: await resumePassive(ctx, artifact, state),
121
+ executionPolicy: ctx.executionPolicy
122
+ });
123
+ }
124
+ return withSandboxOverrides(implementation, overrides);
94
125
  }
95
- },
126
+ }),
96
127
  name: definition.name,
97
128
  environment: (options) => ({
98
129
  providerName: definition.name,
@@ -109,11 +140,11 @@ var SandboxEventKind = /* @__PURE__ */ ((SandboxEventKind2) => {
109
140
  return SandboxEventKind2;
110
141
  })(SandboxEventKind || {});
111
142
  export {
112
- NetworkPolicy,
143
+ WorkspaceNetworkPolicy as NetworkPolicy,
113
144
  PLATFORM_ENVIRONMENT_NAMES,
114
145
  PortProtocol,
115
146
  SandboxCapability,
116
- SandboxEntryType,
147
+ SandboxEntryType2 as SandboxEntryType,
117
148
  SandboxEventKind,
118
149
  SandboxSessionEndReason,
119
150
  SandboxWorkspace,