@finalai/agent-provider 0.11.0 → 0.13.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.
Files changed (35) hide show
  1. package/README.md +9 -28
  2. package/dist/modules/channel.d.mts +2 -0
  3. package/dist/modules/channel.mjs.map +2 -2
  4. package/dist/modules/sandbox/client.mjs +0 -3
  5. package/dist/modules/sandbox/client.mjs.map +2 -2
  6. package/dist/modules/sandbox/execution-guard.d.mts +0 -1
  7. package/dist/modules/sandbox/execution-guard.mjs +0 -9
  8. package/dist/modules/sandbox/execution-guard.mjs.map +2 -2
  9. package/dist/modules/sandbox/grant.d.mts +0 -1
  10. package/dist/modules/sandbox/grant.mjs +0 -4
  11. package/dist/modules/sandbox/grant.mjs.map +2 -2
  12. package/dist/modules/sandbox/index.d.mts +0 -3
  13. package/dist/modules/sandbox/index.mjs +1 -11
  14. package/dist/modules/sandbox/index.mjs.map +2 -2
  15. package/dist/modules/sandbox/mcp-hosted.d.mts +0 -1
  16. package/dist/modules/sandbox/mcp-hosted.mjs +1 -8
  17. package/dist/modules/sandbox/mcp-hosted.mjs.map +2 -2
  18. package/dist/modules/sandbox/mcp-testing.mjs.map +2 -2
  19. package/dist/modules/sandbox/mcp.d.mts +2 -4
  20. package/dist/modules/sandbox/mcp.mjs +6 -52
  21. package/dist/modules/sandbox/mcp.mjs.map +2 -2
  22. package/dist/modules/sandbox/server.mjs +0 -14
  23. package/dist/modules/sandbox/server.mjs.map +2 -2
  24. package/dist/modules/sandbox/tool-policy.mjs +1 -19
  25. package/dist/modules/sandbox/tool-policy.mjs.map +2 -2
  26. package/dist/modules/sandbox/types.d.mts +2 -4
  27. package/dist/modules/sandbox/types.mjs +3 -6
  28. package/dist/modules/sandbox/types.mjs.map +3 -3
  29. package/dist/modules/sandbox/wire.d.mts +0 -17
  30. package/dist/modules/sandbox/wire.mjs +0 -12
  31. package/dist/modules/sandbox/wire.mjs.map +2 -2
  32. package/package.json +8 -3
  33. package/dist/modules/sandbox/networking.d.mts +0 -73
  34. package/dist/modules/sandbox/networking.mjs +0 -157
  35. package/dist/modules/sandbox/networking.mjs.map +0 -7
@@ -58,7 +58,6 @@ export declare const HANDLE_METHOD_GATES: {
58
58
  readonly "mcp/send": HandleMethodGateIface;
59
59
  readonly "mcp/receive": HandleMethodGateIface;
60
60
  readonly "mcp/close": HandleMethodGateIface;
61
- readonly "sandbox/egress": HandleMethodGateIface;
62
61
  readonly "sandbox/setNetworkPolicy": HandleMethodGateIface;
63
62
  readonly "sandbox/stop": HandleMethodGateIface;
64
63
  readonly "sandbox/destroy": HandleMethodGateIface;
@@ -95,10 +95,6 @@ const HANDLE_METHOD_GATES = {
95
95
  [HandleRpcMethod.McpSend]: channel,
96
96
  [HandleRpcMethod.McpReceive]: channel,
97
97
  [HandleRpcMethod.McpClose]: channel,
98
- [HandleRpcMethod.Egress]: lifecycle({
99
- capability: Capability.Shell,
100
- access: ShellAccess.Execute
101
- }),
102
98
  // Network policy only matters to something that runs commands.
103
99
  [HandleRpcMethod.SetNetworkPolicy]: lifecycle({
104
100
  capability: Capability.Shell,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/sandbox/grant.ts"],
4
- "sourcesContent": ["import {\n Capability,\n capabilityAccessCovers,\n FilesAccess,\n ScreenAccess,\n ShellAccess,\n type CapabilityAccess,\n} from '@finalai/agent-protocol';\nimport * as z from 'zod';\nimport type { JsonValue } from \"../json.mjs\";\nimport { HandleRpcMethod } from \"./wire.mjs\";\n\n// What one connection to a sandbox handle may do, per capability. A single\n// read < execute < write ladder cannot say \"write files, run nothing\"; a grant\n// can: `{ files: 'write' }` writes and runs nothing, `{ files: 'read', shell:\n// 'execute' }` runs commands and writes no file directly. A capability left out\n// is not granted at all.\nexport interface SandboxGrantIface {\n [Capability.Files]?: FilesAccess;\n [Capability.Shell]?: ShellAccess;\n [Capability.ComputerUse]?: ScreenAccess;\n [Capability.BrowserUse]?: ScreenAccess;\n}\n\nexport const sandboxGrantSchema = z.strictObject({\n [Capability.Files]: z.nativeEnum(FilesAccess).optional(),\n [Capability.Shell]: z.nativeEnum(ShellAccess).optional(),\n [Capability.ComputerUse]: z.nativeEnum(ScreenAccess).optional(),\n [Capability.BrowserUse]: z.nativeEnum(ScreenAccess).optional(),\n}) satisfies z.ZodType<SandboxGrantIface>;\n\n// Everything on every capability: what a provider's own setup and a sandbox\n// owner's tools act with.\nexport const FULL_SANDBOX_GRANT: Readonly<SandboxGrantIface> = {\n [Capability.Files]: FilesAccess.Write,\n [Capability.Shell]: ShellAccess.Execute,\n [Capability.ComputerUse]: ScreenAccess.Control,\n [Capability.BrowserUse]: ScreenAccess.Control,\n};\n\nexport const grantAllows = (\n grant: SandboxGrantIface,\n capability: Capability,\n access: CapabilityAccess,\n): boolean => {\n const granted = grant[capability];\n return granted != null && capabilityAccessCovers(granted, access);\n};\n\nconst lesser = <A extends CapabilityAccess>(a: A | undefined, b: A | undefined): A | undefined => {\n if (a == null || b == null) return undefined;\n return capabilityAccessCovers(a, b) ? b : a;\n};\n\n// The grant both allow: per capability the lesser access, and nothing either leaves out.\nexport const narrowerGrant = (a: SandboxGrantIface, b: SandboxGrantIface): SandboxGrantIface => {\n const grant: SandboxGrantIface = {};\n const files = lesser(a[Capability.Files], b[Capability.Files]);\n if (files != null) grant[Capability.Files] = files;\n const shell = lesser(a[Capability.Shell], b[Capability.Shell]);\n if (shell != null) grant[Capability.Shell] = shell;\n const computerUse = lesser(a[Capability.ComputerUse], b[Capability.ComputerUse]);\n if (computerUse != null) grant[Capability.ComputerUse] = computerUse;\n const browserUse = lesser(a[Capability.BrowserUse], b[Capability.BrowserUse]);\n if (browserUse != null) grant[Capability.BrowserUse] = browserUse;\n return grant;\n};\n\n// The grant a session gets on a sandbox: the access its agent requires on each\n// capability that sandbox was provided for, and nothing else.\nexport const sandboxGrantFor = (args: {\n capabilities: readonly Capability[];\n required: Partial<Record<Capability, { access: CapabilityAccess }>>;\n}): SandboxGrantIface => {\n const grant: SandboxGrantIface = {};\n for (const capability of args.capabilities) {\n const access = args.required[capability]?.access;\n if (access == null) continue;\n const parsed = sandboxGrantSchema.shape[capability].safeParse(access);\n if (!parsed.success || parsed.data == null) continue;\n Object.assign(grant, { [capability]: parsed.data });\n }\n return grant;\n};\n\nexport interface HandleMethodNeedIface {\n capability: Capability;\n access: CapabilityAccess;\n}\n\n// What a handle RPC method needs before the server dispatches it.\nexport interface HandleMethodGateIface {\n // The capability and least access the method needs; null when it needs none.\n needs: HandleMethodNeedIface | null;\n // Changes the sandbox's lifecycle or network: allowed only on connections\n // that may manage the sandbox, whatever their grant.\n lifecycle: boolean;\n // An MCP channel call: authorized when the method that issued the channel's\n // endpoint was (`sandbox/computerUse`, `sandbox/localMcp`).\n channel: boolean;\n}\n\nconst none: HandleMethodGateIface = { needs: null, lifecycle: false, channel: false };\nconst needs = (capability: Capability, access: CapabilityAccess): HandleMethodGateIface => ({\n needs: { capability, access },\n lifecycle: false,\n channel: false,\n});\nconst lifecycle = (need: HandleMethodNeedIface | null = null): HandleMethodGateIface => ({\n needs: need,\n lifecycle: true,\n channel: false,\n});\nconst channel: HandleMethodGateIface = { needs: null, lifecycle: false, channel: true };\n\nconst readFiles = needs(Capability.Files, FilesAccess.Read);\nconst writeFiles = needs(Capability.Files, FilesAccess.Write);\nconst execute = needs(Capability.Shell, ShellAccess.Execute);\n\n// Every handle RPC method, with what it needs. `sandbox/screen` asks for view\n// access here; asking for input control (`viewOnly: false`) needs control\n// (handleMethodGate).\nexport const HANDLE_METHOD_GATES = {\n [HandleRpcMethod.Initialize]: none,\n [HandleRpcMethod.Describe]: none,\n [HandleRpcMethod.AuthRefresh]: none,\n [HandleRpcMethod.IdentityRefresh]: none,\n [HandleRpcMethod.ReadFile]: readFiles,\n [HandleRpcMethod.ReadTextFile]: readFiles,\n [HandleRpcMethod.Stat]: readFiles,\n [HandleRpcMethod.ReadDir]: readFiles,\n [HandleRpcMethod.WriteFile]: writeFiles,\n [HandleRpcMethod.RemovePath]: writeFiles,\n [HandleRpcMethod.Spawn]: execute,\n [HandleRpcMethod.Run]: execute,\n // The platform starts a harness program; the model never does. `process/*`\n // on a worker program are gated the same way.\n [HandleRpcMethod.StartWorker]: lifecycle(),\n [HandleRpcMethod.ProcessWait]: execute,\n [HandleRpcMethod.ProcessKill]: execute,\n [HandleRpcMethod.ProcessAttach]: execute,\n [HandleRpcMethod.ProcessDetach]: execute,\n // A URL for a port only serves something a command started.\n [HandleRpcMethod.GetPortEndpoint]: execute,\n // Servers the sandbox hosts run as processes on it.\n [HandleRpcMethod.LocalMcp]: execute,\n [HandleRpcMethod.ComputerUse]: needs(Capability.ComputerUse, ScreenAccess.Control),\n [HandleRpcMethod.Screen]: needs(Capability.ComputerUse, ScreenAccess.View),\n [HandleRpcMethod.McpOpen]: channel,\n [HandleRpcMethod.McpSend]: channel,\n [HandleRpcMethod.McpReceive]: channel,\n [HandleRpcMethod.McpClose]: channel,\n [HandleRpcMethod.Egress]: lifecycle({\n capability: Capability.Shell,\n access: ShellAccess.Execute,\n }),\n // Network policy only matters to something that runs commands.\n [HandleRpcMethod.SetNetworkPolicy]: lifecycle({\n capability: Capability.Shell,\n access: ShellAccess.Execute,\n }),\n [HandleRpcMethod.Stop]: lifecycle(),\n [HandleRpcMethod.Destroy]: lifecycle(),\n [HandleRpcMethod.OnSandboxStop]: lifecycle(),\n [HandleRpcMethod.OnSandboxDelete]: lifecycle(),\n [HandleRpcMethod.OnRuntimeShutdown]: lifecycle(),\n} as const satisfies Record<HandleRpcMethod, HandleMethodGateIface>;\n\nconst screenControlSchema = z.object({ viewOnly: z.literal(false) });\n\n// The gate for one call, reading the params where they change what it needs.\nexport const handleMethodGate = (\n method: HandleRpcMethod,\n params: JsonValue | undefined,\n): HandleMethodGateIface =>\n method === HandleRpcMethod.Screen && screenControlSchema.safeParse(params).success\n ? needs(Capability.ComputerUse, ScreenAccess.Control)\n : HANDLE_METHOD_GATES[method];\n\nexport interface HandleAccessPolicyIface {\n grant: SandboxGrantIface;\n // Allows the lifecycle and network methods (stop, destroy, provider hooks,\n // network policy, egress).\n lifecycle: boolean;\n}\n\n// Why a call is refused, or null when the policy allows it.\nexport const handleMethodRefusal = (args: {\n access: HandleAccessPolicyIface;\n method: HandleRpcMethod;\n params?: JsonValue;\n}): string | null => {\n const gate = handleMethodGate(args.method, args.params);\n if (gate.lifecycle && !args.access.lifecycle)\n return `${args.method} is not allowed on this connection`;\n const need = gate.needs;\n if (need != null && !grantAllows(args.access.grant, need.capability, need.access))\n return `${args.method} needs ${need.capability} ${need.access}`;\n return null;\n};\n"],
5
- "mappings": "AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,YAAY,OAAO;AAEnB,SAAS,uBAAuB;AAczB,MAAM,qBAAqB,EAAE,aAAa;AAAA,EAC/C,CAAC,WAAW,KAAK,GAAG,EAAE,WAAW,WAAW,EAAE,SAAS;AAAA,EACvD,CAAC,WAAW,KAAK,GAAG,EAAE,WAAW,WAAW,EAAE,SAAS;AAAA,EACvD,CAAC,WAAW,WAAW,GAAG,EAAE,WAAW,YAAY,EAAE,SAAS;AAAA,EAC9D,CAAC,WAAW,UAAU,GAAG,EAAE,WAAW,YAAY,EAAE,SAAS;AAC/D,CAAC;AAIM,MAAM,qBAAkD;AAAA,EAC7D,CAAC,WAAW,KAAK,GAAG,YAAY;AAAA,EAChC,CAAC,WAAW,KAAK,GAAG,YAAY;AAAA,EAChC,CAAC,WAAW,WAAW,GAAG,aAAa;AAAA,EACvC,CAAC,WAAW,UAAU,GAAG,aAAa;AACxC;AAEO,MAAM,cAAc,CACzB,OACA,YACA,WACY;AACZ,QAAM,UAAU,MAAM,UAAU;AAChC,SAAO,WAAW,QAAQ,uBAAuB,SAAS,MAAM;AAClE;AAEA,MAAM,SAAS,CAA6B,GAAkB,MAAoC;AAChG,MAAI,KAAK,QAAQ,KAAK,KAAM,QAAO;AACnC,SAAO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ocol';\nimport * as z from 'zod';\nimport type { JsonValue } from \"../json.mjs\";\nimport { HandleRpcMethod } from \"./wire.mjs\";\n\n// What one connection to a sandbox handle may do, per capability. A single\n// read < execute < write ladder cannot say \"write files, run nothing\"; a grant\n// can: `{ files: 'write' }` writes and runs nothing, `{ files: 'read', shell:\n// 'execute' }` runs commands and writes no file directly. A capability left out\n// is not granted at all.\nexport interface SandboxGrantIface {\n [Capability.Files]?: FilesAccess;\n [Capability.Shell]?: ShellAccess;\n [Capability.ComputerUse]?: ScreenAccess;\n [Capability.BrowserUse]?: ScreenAccess;\n}\n\nexport const sandboxGrantSchema = z.strictObject({\n [Capability.Files]: z.nativeEnum(FilesAccess).optional(),\n [Capability.Shell]: z.nativeEnum(ShellAccess).optional(),\n [Capability.ComputerUse]: z.nativeEnum(ScreenAccess).optional(),\n [Capability.BrowserUse]: z.nativeEnum(ScreenAccess).optional(),\n}) satisfies z.ZodType<SandboxGrantIface>;\n\n// Everything on every capability: what a provider's own setup and a sandbox\n// owner's tools act with.\nexport const FULL_SANDBOX_GRANT: Readonly<SandboxGrantIface> = {\n [Capability.Files]: FilesAccess.Write,\n [Capability.Shell]: ShellAccess.Execute,\n [Capability.ComputerUse]: ScreenAccess.Control,\n [Capability.BrowserUse]: ScreenAccess.Control,\n};\n\nexport const grantAllows = (\n grant: SandboxGrantIface,\n capability: Capability,\n access: CapabilityAccess,\n): boolean => {\n const granted = grant[capability];\n return granted != null && capabilityAccessCovers(granted, access);\n};\n\nconst lesser = <A extends CapabilityAccess>(a: A | undefined, b: A | undefined): A | undefined => {\n if (a == null || b == null) return undefined;\n return capabilityAccessCovers(a, b) ? b : a;\n};\n\n// The grant both allow: per capability the lesser access, and nothing either leaves out.\nexport const narrowerGrant = (a: SandboxGrantIface, b: SandboxGrantIface): SandboxGrantIface => {\n const grant: SandboxGrantIface = {};\n const files = lesser(a[Capability.Files], b[Capability.Files]);\n if (files != null) grant[Capability.Files] = files;\n const shell = lesser(a[Capability.Shell], b[Capability.Shell]);\n if (shell != null) grant[Capability.Shell] = shell;\n const computerUse = lesser(a[Capability.ComputerUse], b[Capability.ComputerUse]);\n if (computerUse != null) grant[Capability.ComputerUse] = computerUse;\n const browserUse = lesser(a[Capability.BrowserUse], b[Capability.BrowserUse]);\n if (browserUse != null) grant[Capability.BrowserUse] = browserUse;\n return grant;\n};\n\n// The grant a session gets on a sandbox: the access its agent requires on each\n// capability that sandbox was provided for, and nothing else.\nexport const sandboxGrantFor = (args: {\n capabilities: readonly Capability[];\n required: Partial<Record<Capability, { access: CapabilityAccess }>>;\n}): SandboxGrantIface => {\n const grant: SandboxGrantIface = {};\n for (const capability of args.capabilities) {\n const access = args.required[capability]?.access;\n if (access == null) continue;\n const parsed = sandboxGrantSchema.shape[capability].safeParse(access);\n if (!parsed.success || parsed.data == null) continue;\n Object.assign(grant, { [capability]: parsed.data });\n }\n return grant;\n};\n\nexport interface HandleMethodNeedIface {\n capability: Capability;\n access: CapabilityAccess;\n}\n\n// What a handle RPC method needs before the server dispatches it.\nexport interface HandleMethodGateIface {\n // The capability and least access the method needs; null when it needs none.\n needs: HandleMethodNeedIface | null;\n // Changes the sandbox's lifecycle or network: allowed only on connections\n // that may manage the sandbox, whatever their grant.\n lifecycle: boolean;\n // An MCP channel call: authorized when the method that issued the channel's\n // endpoint was (`sandbox/computerUse`, `sandbox/localMcp`).\n channel: boolean;\n}\n\nconst none: HandleMethodGateIface = { needs: null, lifecycle: false, channel: false };\nconst needs = (capability: Capability, access: CapabilityAccess): HandleMethodGateIface => ({\n needs: { capability, access },\n lifecycle: false,\n channel: false,\n});\nconst lifecycle = (need: HandleMethodNeedIface | null = null): HandleMethodGateIface => ({\n needs: need,\n lifecycle: true,\n channel: false,\n});\nconst channel: HandleMethodGateIface = { needs: null, lifecycle: false, channel: true };\n\nconst readFiles = needs(Capability.Files, FilesAccess.Read);\nconst writeFiles = needs(Capability.Files, FilesAccess.Write);\nconst execute = needs(Capability.Shell, ShellAccess.Execute);\n\n// Every handle RPC method, with what it needs. `sandbox/screen` asks for view\n// access here; asking for input control (`viewOnly: false`) needs control\n// (handleMethodGate).\nexport const HANDLE_METHOD_GATES = {\n [HandleRpcMethod.Initialize]: none,\n [HandleRpcMethod.Describe]: none,\n [HandleRpcMethod.AuthRefresh]: none,\n [HandleRpcMethod.IdentityRefresh]: none,\n [HandleRpcMethod.ReadFile]: readFiles,\n [HandleRpcMethod.ReadTextFile]: readFiles,\n [HandleRpcMethod.Stat]: readFiles,\n [HandleRpcMethod.ReadDir]: readFiles,\n [HandleRpcMethod.WriteFile]: writeFiles,\n [HandleRpcMethod.RemovePath]: writeFiles,\n [HandleRpcMethod.Spawn]: execute,\n [HandleRpcMethod.Run]: execute,\n // The platform starts a harness program; the model never does. `process/*`\n // on a worker program are gated the same way.\n [HandleRpcMethod.StartWorker]: lifecycle(),\n [HandleRpcMethod.ProcessWait]: execute,\n [HandleRpcMethod.ProcessKill]: execute,\n [HandleRpcMethod.ProcessAttach]: execute,\n [HandleRpcMethod.ProcessDetach]: execute,\n // A URL for a port only serves something a command started.\n [HandleRpcMethod.GetPortEndpoint]: execute,\n // Servers the sandbox hosts run as processes on it.\n [HandleRpcMethod.LocalMcp]: execute,\n [HandleRpcMethod.ComputerUse]: needs(Capability.ComputerUse, ScreenAccess.Control),\n [HandleRpcMethod.Screen]: needs(Capability.ComputerUse, ScreenAccess.View),\n [HandleRpcMethod.McpOpen]: channel,\n [HandleRpcMethod.McpSend]: channel,\n [HandleRpcMethod.McpReceive]: channel,\n [HandleRpcMethod.McpClose]: channel,\n // Network policy only matters to something that runs commands.\n [HandleRpcMethod.SetNetworkPolicy]: lifecycle({\n capability: Capability.Shell,\n access: ShellAccess.Execute,\n }),\n [HandleRpcMethod.Stop]: lifecycle(),\n [HandleRpcMethod.Destroy]: lifecycle(),\n [HandleRpcMethod.OnSandboxStop]: lifecycle(),\n [HandleRpcMethod.OnSandboxDelete]: lifecycle(),\n [HandleRpcMethod.OnRuntimeShutdown]: lifecycle(),\n} as const satisfies Record<HandleRpcMethod, HandleMethodGateIface>;\n\nconst screenControlSchema = z.object({ viewOnly: z.literal(false) });\n\n// The gate for one call, reading the params where they change what it needs.\nexport const handleMethodGate = (\n method: HandleRpcMethod,\n params: JsonValue | undefined,\n): HandleMethodGateIface =>\n method === HandleRpcMethod.Screen && screenControlSchema.safeParse(params).success\n ? needs(Capability.ComputerUse, ScreenAccess.Control)\n : HANDLE_METHOD_GATES[method];\n\nexport interface HandleAccessPolicyIface {\n grant: SandboxGrantIface;\n // Allows the lifecycle and network methods (stop, destroy, provider hooks,\n // network policy).\n lifecycle: boolean;\n}\n\n// Why a call is refused, or null when the policy allows it.\nexport const handleMethodRefusal = (args: {\n access: HandleAccessPolicyIface;\n method: HandleRpcMethod;\n params?: JsonValue;\n}): string | null => {\n const gate = handleMethodGate(args.method, args.params);\n if (gate.lifecycle && !args.access.lifecycle)\n return `${args.method} is not allowed on this connection`;\n const need = gate.needs;\n if (need != null && !grantAllows(args.access.grant, need.capability, need.access))\n return `${args.method} needs ${need.capability} ${need.access}`;\n return null;\n};\n"],
5
+ "mappings": "AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,YAAY,OAAO;AAEnB,SAAS,uBAAuB;AAczB,MAAM,qBAAqB,EAAE,aAAa;AAAA,EAC/C,CAAC,WAAW,KAAK,GAAG,EAAE,WAAW,WAAW,EAAE,SAAS;AAAA,EACvD,CAAC,WAAW,KAAK,GAAG,EAAE,WAAW,WAAW,EAAE,SAAS;AAAA,EACvD,CAAC,WAAW,WAAW,GAAG,EAAE,WAAW,YAAY,EAAE,SAAS;AAAA,EAC9D,CAAC,WAAW,UAAU,GAAG,EAAE,WAAW,YAAY,EAAE,SAAS;AAC/D,CAAC;AAIM,MAAM,qBAAkD;AAAA,EAC7D,CAAC,WAAW,KAAK,GAAG,YAAY;AAAA,EAChC,CAAC,WAAW,KAAK,GAAG,YAAY;AAAA,EAChC,CAAC,WA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AK,MAAM,UAAU,KAAK,UAAU,IAAI,KAAK,MAAM;AAC/D,SAAO;AACT;",
6
6
  "names": []
7
7
  }
@@ -1,16 +1,13 @@
1
1
  export { withSandboxExecutionGuard, SandboxExecutionOperation, type SandboxExecutionContextIface, type SandboxExecutionGuardOptionsIface, } from "./execution-guard.mjs";
2
2
  export { withSandboxOverrides } from "./overrides.mjs";
3
3
  export { createSandboxHandle, mapSandboxHandle, type CreateSandboxHandleOptionsIface, type SandboxExecutionPolicyIface, } from "./handle.mjs";
4
- export * from "./networking.mjs";
5
4
  export { resolveSandboxToolPolicy } from "./tool-policy.mjs";
6
- export { WorkspaceEgressAction, workspaceEgressRequestSchema, workspaceEgressStatusSchema, type WorkspaceEgressRequestIface, type WorkspaceEgressStatusIface, } from '@finalai/agent-protocol/device-egress';
7
5
  export { ProcessInspectionOperation, inspectedProcessSchema, processInspectionDetailSchema, processInspectionPageSchema, processInspectionRequestSchema, processInspectionResultSchema, type InspectedProcessIface, type ProcessInspectionDetailIface, type ProcessInspectionPageIface, type ProcessInspectionRequestIface, type ProcessInspectionResultIface, } from '@finalai/agent-protocol/process-inspection';
8
6
  export { decodeSandboxText, encodeSandboxText } from "./bytes.mjs";
9
7
  export * from "./client.mjs";
10
8
  export { createConfinedFileReader } from "./confined-files.mjs";
11
9
  export * from "./convenience.mjs";
12
10
  export * from "./mcp.mjs";
13
- export * from "./mcp-testing.mjs";
14
11
  export * from "./memory-sandbox.mjs";
15
12
  export { MAX_SANDBOX_SEED_BYTES, SANDBOX_SEED_MARKER, SANDBOX_SEED_PROTOCOL, materializeSandboxSeeds, sandboxPreparationInputs, sandboxSeedArtifact, sandboxSeedArtifactSchema, sandboxSeedFiles, sandboxSeedFilesForAttach, sandboxSeedFilesSchema, sandboxSeedIdentity, } from "./seeds.mjs";
16
13
  export * from "./server.mjs";
@@ -7,13 +7,7 @@ import {
7
7
  createSandboxHandle,
8
8
  mapSandboxHandle
9
9
  } from "./handle.mjs";
10
- export * from "./networking.mjs";
11
10
  import { resolveSandboxToolPolicy } from "./tool-policy.mjs";
12
- import {
13
- WorkspaceEgressAction,
14
- workspaceEgressRequestSchema,
15
- workspaceEgressStatusSchema
16
- } from "@finalai/agent-protocol/device-egress";
17
11
  import {
18
12
  ProcessInspectionOperation,
19
13
  inspectedProcessSchema,
@@ -27,7 +21,6 @@ export * from "./client.mjs";
27
21
  import { createConfinedFileReader } from "./confined-files.mjs";
28
22
  export * from "./convenience.mjs";
29
23
  export * from "./mcp.mjs";
30
- export * from "./mcp-testing.mjs";
31
24
  export * from "./memory-sandbox.mjs";
32
25
  import {
33
26
  MAX_SANDBOX_SEED_BYTES,
@@ -64,7 +57,6 @@ export {
64
57
  SANDBOX_SEED_PROTOCOL,
65
58
  SandboxEditorOperation,
66
59
  SandboxExecutionOperation,
67
- WorkspaceEgressAction,
68
60
  createConfinedFileReader,
69
61
  createHttpMcpChannelEndpoint,
70
62
  createSandboxHandle,
@@ -91,8 +83,6 @@ export {
91
83
  sandboxSeedIdentity,
92
84
  withSandboxExecutionGuard,
93
85
  withSandboxOverrides,
94
- withSessionWorkspaceRoot,
95
- workspaceEgressRequestSchema,
96
- workspaceEgressStatusSchema
86
+ withSessionWorkspaceRoot
97
87
  };
98
88
  //# sourceMappingURL=index.mjs.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/sandbox/index.ts"],
4
- "sourcesContent": ["export {\n withSandboxExecutionGuard,\n SandboxExecutionOperation,\n type SandboxExecutionContextIface,\n type SandboxExecutionGuardOptionsIface,\n} from \"./execution-guard.mjs\";\nexport { withSandboxOverrides } from \"./overrides.mjs\";\nexport {\n createSandboxHandle,\n mapSandboxHandle,\n type CreateSandboxHandleOptionsIface,\n type SandboxExecutionPolicyIface,\n} from \"./handle.mjs\";\nexport * from \"./networking.mjs\";\nexport { resolveSandboxToolPolicy } from \"./tool-policy.mjs\";\nexport {\n WorkspaceEgressAction,\n workspaceEgressRequestSchema,\n workspaceEgressStatusSchema,\n type WorkspaceEgressRequestIface,\n type WorkspaceEgressStatusIface,\n} from '@finalai/agent-protocol/device-egress';\n\nexport {\n ProcessInspectionOperation,\n inspectedProcessSchema,\n processInspectionDetailSchema,\n processInspectionPageSchema,\n processInspectionRequestSchema,\n processInspectionResultSchema,\n type InspectedProcessIface,\n type ProcessInspectionDetailIface,\n type ProcessInspectionPageIface,\n type ProcessInspectionRequestIface,\n type ProcessInspectionResultIface,\n} from '@finalai/agent-protocol/process-inspection';\nexport { decodeSandboxText, encodeSandboxText } from \"./bytes.mjs\";\nexport * from \"./client.mjs\";\nexport { createConfinedFileReader } from \"./confined-files.mjs\";\nexport * from \"./convenience.mjs\";\nexport * from \"./mcp.mjs\";\nexport * from \"./mcp-testing.mjs\";\nexport * from \"./memory-sandbox.mjs\";\nexport {\n MAX_SANDBOX_SEED_BYTES,\n SANDBOX_SEED_MARKER,\n SANDBOX_SEED_PROTOCOL,\n materializeSandboxSeeds,\n sandboxPreparationInputs,\n sandboxSeedArtifact,\n sandboxSeedArtifactSchema,\n sandboxSeedFiles,\n sandboxSeedFilesForAttach,\n sandboxSeedFilesSchema,\n sandboxSeedIdentity,\n} from \"./seeds.mjs\";\nexport * from \"./server.mjs\";\nexport * from \"./testing.mjs\";\nexport * from \"./types.mjs\";\nexport * from \"./wire.mjs\";\nexport * from \"./grant.mjs\";\nexport * from \"./setup/index.mjs\";\nexport { mapSessionPath, withSessionWorkspaceRoot } from \"./workspace-root.mjs\";\nexport type { MapSessionPathArgsIface } from \"./workspace-root.mjs\";\n\nexport * from \"./snapshots.mjs\";\n\nexport {\n SandboxEditorOperation,\n sandboxEditorRequestSchema,\n sandboxEditorResultSchema,\n sandboxEditorSessionSchema,\n type SandboxEditorRequestIface,\n type SandboxEditorResultIface,\n type SandboxEditorSessionIface,\n} from \"./editor.mjs\";\n\nexport { createHttpMcpChannelEndpoint } from \"./mcp-channel.mjs\";\n"],
5
- "mappings": "AAAA;AAAA,EACE;AAAA,EACA;AAAA,OAGK;AACP,SAAS,4BAA4B;AACrC;AAAA,EACE;AAAA,EACA;AAAA,OAGK;AACP,cAAc;AACd,SAAS,gCAAgC;AACzC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AAEP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAMK;AACP,SAAS,mBAAmB,yBAAyB;AACrD,cAAc;AACd,SAAS,gCAAgC;AACzC,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,SAAS,gBAAgB,gCAAgC;AAGzD,cAAc;AAEd;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAIK;AAEP,SAAS,oCAAoC;",
4
+ "sourcesContent": ["export {\n withSandboxExecutionGuard,\n SandboxExecutionOperation,\n type SandboxExecutionContextIface,\n type SandboxExecutionGuardOptionsIface,\n} from \"./execution-guard.mjs\";\nexport { withSandboxOverrides } from \"./overrides.mjs\";\nexport {\n createSandboxHandle,\n mapSandboxHandle,\n type CreateSandboxHandleOptionsIface,\n type SandboxExecutionPolicyIface,\n} from \"./handle.mjs\";\nexport { resolveSandboxToolPolicy } from \"./tool-policy.mjs\";\n\nexport {\n ProcessInspectionOperation,\n inspectedProcessSchema,\n processInspectionDetailSchema,\n processInspectionPageSchema,\n processInspectionRequestSchema,\n processInspectionResultSchema,\n type InspectedProcessIface,\n type ProcessInspectionDetailIface,\n type ProcessInspectionPageIface,\n type ProcessInspectionRequestIface,\n type ProcessInspectionResultIface,\n} from '@finalai/agent-protocol/process-inspection';\nexport { decodeSandboxText, encodeSandboxText } from \"./bytes.mjs\";\nexport * from \"./client.mjs\";\nexport { createConfinedFileReader } from \"./confined-files.mjs\";\nexport * from \"./convenience.mjs\";\nexport * from \"./mcp.mjs\";\nexport * from \"./memory-sandbox.mjs\";\nexport {\n MAX_SANDBOX_SEED_BYTES,\n SANDBOX_SEED_MARKER,\n SANDBOX_SEED_PROTOCOL,\n materializeSandboxSeeds,\n sandboxPreparationInputs,\n sandboxSeedArtifact,\n sandboxSeedArtifactSchema,\n sandboxSeedFiles,\n sandboxSeedFilesForAttach,\n sandboxSeedFilesSchema,\n sandboxSeedIdentity,\n} from \"./seeds.mjs\";\nexport * from \"./server.mjs\";\nexport * from \"./testing.mjs\";\nexport * from \"./types.mjs\";\nexport * from \"./wire.mjs\";\nexport * from \"./grant.mjs\";\nexport * from \"./setup/index.mjs\";\nexport { mapSessionPath, withSessionWorkspaceRoot } from \"./workspace-root.mjs\";\nexport type { MapSessionPathArgsIface } from \"./workspace-root.mjs\";\n\nexport * from \"./snapshots.mjs\";\n\nexport {\n SandboxEditorOperation,\n sandboxEditorRequestSchema,\n sandboxEditorResultSchema,\n sandboxEditorSessionSchema,\n type SandboxEditorRequestIface,\n type SandboxEditorResultIface,\n type SandboxEditorSessionIface,\n} from \"./editor.mjs\";\n\nexport { createHttpMcpChannelEndpoint } from \"./mcp-channel.mjs\";\n"],
5
+ "mappings": "AAAA;AAAA,EACE;AAAA,EACA;AAAA,OAGK;AACP,SAAS,4BAA4B;AACrC;AAAA,EACE;AAAA,EACA;AAAA,OAGK;AACP,SAAS,gCAAgC;AAEzC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAMK;AACP,SAAS,mBAAmB,yBAAyB;AACrD,cAAc;AACd,SAAS,gCAAgC;AACzC,cAAc;AACd,cAAc;AACd,cAAc;AACd;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,SAAS,gBAAgB,gCAAgC;AAGzD,cAAc;AAEd;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAIK;AAEP,SAAS,oCAAoC;",
6
6
  "names": []
7
7
  }
@@ -27,7 +27,6 @@ export declare const hostedTools: (args: {
27
27
  localMcp: boolean;
28
28
  localServer?: string;
29
29
  taken: ReadonlySet<string>;
30
- reserveEgress?: boolean;
31
30
  }) => HostedToolIface[];
32
31
  export interface HostedMcpCallOptionsIface {
33
32
  signal?: AbortSignal;
@@ -21,14 +21,7 @@ const COMPUTER_USE_SERVER_NAME = "computer-use";
21
21
  const EMPTY_MCP_CATALOG = { computerUse: null, localMcp: null };
22
22
  const toolNameSafe = (value) => value.replace(/[^A-Za-z0-9_-]/g, "_");
23
23
  const hostedTools = (args) => {
24
- const reserved = /* @__PURE__ */ new Set([
25
- "egress",
26
- "network.egress",
27
- "network.egress.configure",
28
- "network.egress.disable",
29
- "network.egress.status"
30
- ]);
31
- const taken = /* @__PURE__ */ new Set([...args.taken, ...args.reserveEgress === true ? reserved : []]);
24
+ const taken = new Set(args.taken);
32
25
  const tools = [];
33
26
  const claim = (preferred, fallback) => {
34
27
  const name = taken.has(preferred) ? fallback : preferred;
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/sandbox/mcp-hosted.ts"],
4
- "sourcesContent": ["import {\n Client,\n ProtocolError,\n SdkError,\n SdkErrorCode,\n StreamableHTTPClientTransport,\n type FetchLike,\n} from '@modelcontextprotocol/client';\nimport type { CallToolResult } from '@modelcontextprotocol/server';\nimport type { JsonObject } from \"../json.mjs\";\nimport { toolDescriptorSchema, type ToolDescriptorIface } from \"../tool-descriptor.mjs\";\nimport { markHostedMcpEndpoints } from \"./mcp-hosted-marker.mjs\";\nimport { createMcpChannelTransport, mcpMessageNotSent } from \"./mcp-channel.mjs\";\nimport {\n isMcpChannelEndpoint,\n SandboxCapability,\n type McpEndpointIface,\n type NetworkSandboxSessionIface,\n type SandboxMcpCatalogIface,\n type SandboxMcpEndpoint,\n} from \"./types.mjs\";\n\n// A sandbox's hosted MCP servers (its computer-use server and local MCP\n// servers) as the MCP projection serves them: their own tools, by their own\n// names, proxied through the handle's `computerUse()` / `localMcp()`. Catalogs\n// come from the provider before anything starts when it can give them, and\n// are otherwise learned from the servers once the sandbox is attached.\n\nexport enum SandboxHostedServerKind {\n ComputerUse = 'computerUse',\n Local = 'local',\n}\n\nexport type SandboxHostedServer =\n | { kind: SandboxHostedServerKind.ComputerUse }\n | { kind: SandboxHostedServerKind.Local; name: string };\n\nexport const COMPUTER_USE_SERVER_NAME = 'computer-use';\n\nexport const EMPTY_MCP_CATALOG: SandboxMcpCatalogIface = { computerUse: null, localMcp: null };\n\n// One projected tool of a hosted server.\nexport interface HostedToolIface {\n // The name the projection lists: the tool's own, prefixed only on a collision.\n name: string;\n server: SandboxHostedServer;\n tool: ToolDescriptorIface;\n // toolPolicy keys after `name`, most specific first.\n policyKeys: string[];\n}\n\nconst toolNameSafe = (value: string): string => value.replace(/[^A-Za-z0-9_-]/g, '_');\n\n// Hosted tools under the names the projection lists. Computer-use tools keep\n// their names unless a built-in tool has it (`computer_use_<name>`); a local\n// tool keeps its name unless something else has it or another local server\n// has the same tool (`<server>_<name>`).\nexport const hostedTools = (args: {\n catalog: SandboxMcpCatalogIface;\n computerUse: boolean;\n localMcp: boolean;\n // Only this local server (a per-server endpoint).\n localServer?: string;\n taken: ReadonlySet<string>;\n reserveEgress?: boolean;\n}): HostedToolIface[] => {\n const reserved = new Set([\n 'egress',\n 'network.egress',\n 'network.egress.configure',\n 'network.egress.disable',\n 'network.egress.status',\n ]);\n const taken = new Set([...args.taken, ...(args.reserveEgress === true ? reserved : [])]);\n const tools: HostedToolIface[] = [];\n const claim = (preferred: string, fallback: string): string | null => {\n const name = taken.has(preferred) ? fallback : preferred;\n if (taken.has(name)) return null;\n taken.add(name);\n return name;\n };\n if (args.computerUse) {\n for (const tool of args.catalog.computerUse ?? []) {\n const name = claim(tool.name, `computer_use_${tool.name}`);\n if (name == null) continue;\n tools.push({\n name,\n server: { kind: SandboxHostedServerKind.ComputerUse },\n tool,\n policyKeys: [SandboxCapability.ComputerUse],\n });\n }\n }\n if (args.localMcp) {\n const servers = Object.entries(args.catalog.localMcp ?? {}).filter(\n ([server]) => args.localServer == null || server === args.localServer,\n );\n const counts = new Map<string, number>();\n for (const [, serverTools] of servers) {\n for (const tool of serverTools) counts.set(tool.name, (counts.get(tool.name) ?? 0) + 1);\n }\n for (const [server, serverTools] of servers) {\n for (const tool of serverTools) {\n const prefixed = `${toolNameSafe(server)}_${tool.name}`;\n const name =\n (counts.get(tool.name) ?? 0) > 1 ? claim(prefixed, prefixed) : claim(tool.name, prefixed);\n if (name == null) continue;\n tools.push({\n name,\n server: { kind: SandboxHostedServerKind.Local, name: server },\n tool,\n policyKeys: [`${server}/${tool.name}`, SandboxCapability.LocalMcp],\n });\n }\n }\n }\n return tools;\n};\n\nconst serverKeyOf = (server: SandboxHostedServer): string =>\n server.kind === SandboxHostedServerKind.ComputerUse\n ? 'computer-use'\n : `local\\u0000${server.name}`;\n\nexport interface HostedMcpCallOptionsIface {\n signal?: AbortSignal;\n}\n\nexport interface HostedMcpConnectionsIface {\n call(\n server: SandboxHostedServer,\n tool: string,\n input: JsonObject,\n options?: HostedMcpCallOptionsIface,\n ): Promise<CallToolResult>;\n // One server's live tools, over the connection its calls use.\n tools(server: SandboxHostedServer): Promise<ToolDescriptorIface[]>;\n // Reads the catalogs `needed` asks for (null fields) from the live sandbox.\n learn(\n sandbox: NetworkSandboxSessionIface,\n needed: { computerUse: boolean; localMcp: boolean },\n ): Promise<Partial<SandboxMcpCatalogIface>>;\n close(): Promise<void>;\n}\n\nexport const createHostedMcpConnections = (args: {\n getSandbox: () => Promise<NetworkSandboxSessionIface>;\n fetch?: FetchLike;\n name?: string;\n version?: string;\n catalog?: () => SandboxMcpCatalogIface;\n}): HostedMcpConnectionsIface => {\n const clients = new Map<string, Promise<Client>>();\n const unknownLocalCatalogs = new Set<string>();\n const localCatalogs = new Map<string, ToolDescriptorIface[]>();\n const closedClients = new WeakSet<Client>();\n const instances = new Set<Client>();\n const active = new Map<Promise<Client>, number>();\n const retired = new WeakSet<Client>();\n const lifetime = new AbortController();\n let closed = false;\n\n const connect = async (endpoint: SandboxMcpEndpoint): Promise<Client> => {\n if (closed) throw new Error('Hosted MCP connections are closed');\n const client = new Client({ name: args.name ?? 'final-sandbox', version: args.version ?? '1' });\n instances.add(client);\n try {\n if (isMcpChannelEndpoint(endpoint)) {\n const channel = await endpoint.connect({ abortSignal: lifetime.signal });\n if (closed) {\n await channel.close();\n throw new Error('Hosted MCP connections are closed');\n }\n await client.connect(createMcpChannelTransport({ channel, receiveWhileIdle: false }), {\n signal: lifetime.signal,\n });\n } else {\n await client.connect(\n new StreamableHTTPClientTransport(new URL(endpoint.url), {\n requestInit: { headers: endpoint.headers },\n fetch: args.fetch,\n }),\n { signal: lifetime.signal },\n );\n }\n if (closed) throw new Error('Hosted MCP connections are closed');\n return client;\n } catch (cause) {\n instances.delete(client);\n await client.close().catch(() => undefined);\n throw cause;\n }\n };\n\n const endpointOf = async (\n sandbox: NetworkSandboxSessionIface,\n server: SandboxHostedServer,\n ): Promise<SandboxMcpEndpoint> => {\n if (server.kind === SandboxHostedServerKind.ComputerUse) {\n if (sandbox.computerUse == null) throw new Error('this sandbox has no computer use');\n return sandbox.computerUse();\n }\n if (sandbox.localMcp == null) throw new Error('this sandbox has no local MCP servers');\n const found = (await sandbox.localMcp()).find((endpoint) => endpoint.name === server.name);\n if (found == null) throw new Error(`this sandbox has no local MCP server ${server.name}`);\n return found;\n };\n\n const clientFor = (key: string, endpoint: () => Promise<SandboxMcpEndpoint>): Promise<Client> => {\n if (closed) return Promise.reject(new Error('Hosted MCP connections are closed'));\n const existing = clients.get(key);\n if (existing != null) return existing;\n const connecting = endpoint()\n .then(connect)\n .then((client) => {\n client.onclose = () => {\n closedClients.add(client);\n instances.delete(client);\n if (clients.get(key) === connecting) clients.delete(key);\n };\n return client;\n });\n clients.set(key, connecting);\n connecting.catch(() => {\n if (clients.get(key) === connecting) clients.delete(key);\n });\n return connecting;\n };\n\n // One retry on a fresh connection: a parked or restarted server drops the old\n // one. An error the server answered with leaves the connection as it is.\n const withClient = async <T>(\n key: string,\n endpoint: () => Promise<SandboxMcpEndpoint>,\n work: (client: Client) => Promise<T>,\n retry = true,\n ): Promise<T> => {\n for (let attempt = 0; ; attempt += 1) {\n const connecting = clientFor(key, endpoint);\n // Reserve before awaiting the shared connection so a sibling cannot close under this call.\n active.set(connecting, (active.get(connecting) ?? 0) + 1);\n let connected: Client | null = null;\n try {\n connected = await connecting;\n return await work(connected);\n } catch (error) {\n if (error instanceof ProtocolError && (connected == null || !closedClients.has(connected)))\n throw error;\n if (\n connected != null &&\n error instanceof SdkError &&\n (error.code === SdkErrorCode.RequestTimeout ||\n error.code === SdkErrorCode.ConnectionClosed)\n ) {\n if (clients.get(key) === connecting) clients.delete(key);\n retired.add(connected);\n if (\n error.code === SdkErrorCode.ConnectionClosed &&\n attempt === 0 &&\n (retry || (mcpMessageNotSent in error && error[mcpMessageNotSent] === true))\n )\n continue;\n throw error;\n }\n // Business calls remain isolated; read-only discovery may retry on a fresh channel.\n if (connected != null && clients.get(key) === connecting) {\n clients.delete(key);\n retired.add(connected);\n if (!retry || attempt > 0) throw error;\n continue;\n }\n if (clients.get(key) === connecting) clients.delete(key);\n if (!retry || attempt > 0) throw error;\n } finally {\n const remaining = (active.get(connecting) ?? 1) - 1;\n if (remaining > 0) active.set(connecting, remaining);\n else {\n active.delete(connecting);\n if (connected != null && retired.has(connected))\n void connected.close().catch(() => undefined);\n }\n }\n }\n };\n\n const toolsOf = async (client: Client): Promise<ToolDescriptorIface[]> => {\n const tools: ToolDescriptorIface[] = [];\n let cursor: string | undefined;\n do {\n const page = await client.listTools(cursor == null ? undefined : { cursor }, {\n cacheMode: 'refresh',\n });\n for (const tool of page.tools) {\n const parsed = toolDescriptorSchema.safeParse(\n JSON.parse(\n JSON.stringify({\n name: tool.name,\n description: tool.description ?? tool.title ?? tool.name,\n inputSchema: tool.inputSchema,\n outputSchema: tool.outputSchema,\n annotations: tool.annotations,\n }),\n ),\n );\n if (parsed.success) tools.push(parsed.data);\n }\n cursor = page.nextCursor;\n } while (cursor != null);\n return tools;\n };\n\n return {\n call: async (server, tool, input, options) => {\n options?.signal?.throwIfAborted();\n return withClient(\n serverKeyOf(server),\n async () => endpointOf(await args.getSandbox(), server),\n async (client) => {\n const result = await client.callTool(\n { name: tool, arguments: input },\n { signal: options?.signal },\n );\n const proxied: CallToolResult = { content: result.content };\n if (result.structuredContent != null)\n proxied.structuredContent = result.structuredContent;\n if (result.isError === true) proxied.isError = true;\n return proxied;\n },\n false,\n );\n },\n tools: async (server) =>\n withClient(\n serverKeyOf(server),\n async () => endpointOf(await args.getSandbox(), server),\n toolsOf,\n ),\n learn: async (sandbox, needed) => {\n const learned: Partial<SandboxMcpCatalogIface> = {};\n if (needed.computerUse && sandbox.computerUse != null) {\n const server: SandboxHostedServer = { kind: SandboxHostedServerKind.ComputerUse };\n learned.computerUse = await withClient(\n serverKeyOf(server),\n () => endpointOf(sandbox, server),\n toolsOf,\n );\n }\n if (needed.localMcp && sandbox.localMcp != null) {\n const local: Record<string, ToolDescriptorIface[]> = {};\n const endpoints = await sandbox.localMcp();\n const names = new Set(endpoints.map((endpoint) => endpoint.name));\n for (const name of localCatalogs.keys()) if (!names.has(name)) localCatalogs.delete(name);\n unknownLocalCatalogs.clear();\n for (const endpoint of endpoints) {\n const server: SandboxHostedServer = {\n kind: SandboxHostedServerKind.Local,\n name: endpoint.name,\n };\n try {\n const tools = await withClient(serverKeyOf(server), async () => endpoint, toolsOf);\n local[endpoint.name] = tools;\n localCatalogs.set(endpoint.name, tools);\n } catch (cause) {\n if (closed) throw cause;\n unknownLocalCatalogs.add(endpoint.name);\n const previous =\n localCatalogs.get(endpoint.name) ?? args.catalog?.().localMcp?.[endpoint.name];\n if (previous != null) local[endpoint.name] = previous;\n }\n }\n learned.localMcp = local;\n learned.localMcpIncomplete = unknownLocalCatalogs.size > 0;\n }\n if (closed) throw new Error('Hosted MCP connections are closed');\n return learned;\n },\n close: async () => {\n closed = true;\n lifetime.abort(new Error('Hosted MCP connections are closed'));\n clients.clear();\n unknownLocalCatalogs.clear();\n localCatalogs.clear();\n const open = [...instances];\n instances.clear();\n await Promise.all(open.map((client) => client.close().catch(() => undefined)));\n },\n };\n};\n\n// A handle whose hosted servers are re-addressed: `computerUse()` and\n// `localMcp()` return HTTP endpoints where the host of the handle serves them\n// (its per-binding MCP addresses), so they can cross the handle RPC and the\n// sandbox's own endpoints and credentials never leave the host.\nexport const withHostedMcpEndpoints = <S extends NetworkSandboxSessionIface>(\n sandbox: S,\n endpointFor: (server: SandboxHostedServer) => McpEndpointIface,\n): S => {\n const addressed: S = { ...sandbox };\n // The host's proxy enforces admission on every request; only these replacement URLs cross RPC.\n markHostedMcpEndpoints(addressed);\n if (sandbox.computerUse != null) {\n addressed.computerUse = async () => endpointFor({ kind: SandboxHostedServerKind.ComputerUse });\n }\n const localMcp = sandbox.localMcp;\n if (localMcp != null) {\n addressed.localMcp = async () =>\n (await localMcp()).map((endpoint) =>\n endpointFor({ kind: SandboxHostedServerKind.Local, name: endpoint.name }),\n );\n }\n return addressed;\n};\n"],
5
- "mappings": "AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AAGP,SAAS,4BAAsD;AAC/D,SAAS,8BAA8B;AACvC,SAAS,2BAA2B,yBAAyB;AAC7D;AAAA,EACE;AAAA,EACA;AAAA,OAKK;AAQA,IAAK,0BAAL,kBAAKA,6BAAL;AACL,EAAAA,yBAAA,iBAAc;AACd,EAAAA,yBAAA,WAAQ;AAFE,SAAAA;AAAA,GAAA;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AI,SAAS,IAAI;AACtC,kBAAM,WACJ,cAAc,IAAI,SAAS,IAAI,KAAK,KAAK,UAAU,EAAE,WAAW,SAAS,IAAI;AAC/E,gBAAI,YAAY,KAAM,OAAM,SAAS,IAAI,IAAI;AAAA,UAC/C;AAAA,QACF;AACA,gBAAQ,WAAW;AACnB,gBAAQ,qBAAqB,qBAAqB,OAAO;AAAA,MAC3D;AACA,UAAI,OAAQ,OAAM,IAAI,MAAM,mCAAmC;AAC/D,aAAO;AAAA,IACT;AAAA,IACA,OAAO,YAAY;AACjB,eAAS;AACT,eAAS,MAAM,IAAI,MAAM,mCAAmC,CAAC;AAC7D,cAAQ,MAAM;AACd,2BAAqB,MAAM;AAC3B,oBAAc,MAAM;AACpB,YAAM,OAAO,CAAC,GAAG,SAAS;AAC1B,gBAAU,MAAM;AAChB,YAAM,QAAQ,IAAI,KAAK,IAAI,CAAC,WAAW,OAAO,MAAM,EAAE,MAAM,MAAM,MAAS,CAAC,CAAC;AAAA,IAC/E;AAAA,EACF;AACF;AAMO,MAAM,yBAAyB,CACpC,SACA,gBACM;AACN,QAAM,YAAe,EAAE,GAAG,QAAQ;AAElC,yBAAuB,SAAS;AAChC,MAAI,QAAQ,eAAe,MAAM;AAC/B,cAAU,cAAc,YAAY,YAAY,EAAE,MAAM,gCAAoC,CAAC;AAAA,EAC/F;AACA,QAAM,WAAW,QAAQ;AACzB,MAAI,YAAY,MAAM;AACpB,cAAU,WAAW,aAClB,MAAM,SAAS,GAAG;AAAA,MAAI,CAAC,aACtB,YAAY,EAAE,MAAM,qBAA+B,MAAM,SAAS,KAAK,CAAC;AAAA,IAC1E;AAAA,EACJ;AACA,SAAO;AACT;",
4
+ "sourcesContent": ["import {\n Client,\n ProtocolError,\n SdkError,\n SdkErrorCode,\n StreamableHTTPClientTransport,\n type FetchLike,\n} from '@modelcontextprotocol/client';\nimport type { CallToolResult } from '@modelcontextprotocol/server';\nimport type { JsonObject } from \"../json.mjs\";\nimport { toolDescriptorSchema, type ToolDescriptorIface } from \"../tool-descriptor.mjs\";\nimport { markHostedMcpEndpoints } from \"./mcp-hosted-marker.mjs\";\nimport { createMcpChannelTransport, mcpMessageNotSent } from \"./mcp-channel.mjs\";\nimport {\n isMcpChannelEndpoint,\n SandboxCapability,\n type McpEndpointIface,\n type NetworkSandboxSessionIface,\n type SandboxMcpCatalogIface,\n type SandboxMcpEndpoint,\n} from \"./types.mjs\";\n\n// A sandbox's hosted MCP servers (its computer-use server and local MCP\n// servers) as the MCP projection serves them: their own tools, by their own\n// names, proxied through the handle's `computerUse()` / `localMcp()`. Catalogs\n// come from the provider before anything starts when it can give them, and\n// are otherwise learned from the servers once the sandbox is attached.\n\nexport enum SandboxHostedServerKind {\n ComputerUse = 'computerUse',\n Local = 'local',\n}\n\nexport type SandboxHostedServer =\n | { kind: SandboxHostedServerKind.ComputerUse }\n | { kind: SandboxHostedServerKind.Local; name: string };\n\nexport const COMPUTER_USE_SERVER_NAME = 'computer-use';\n\nexport const EMPTY_MCP_CATALOG: SandboxMcpCatalogIface = { computerUse: null, localMcp: null };\n\n// One projected tool of a hosted server.\nexport interface HostedToolIface {\n // The name the projection lists: the tool's own, prefixed only on a collision.\n name: string;\n server: SandboxHostedServer;\n tool: ToolDescriptorIface;\n // toolPolicy keys after `name`, most specific first.\n policyKeys: string[];\n}\n\nconst toolNameSafe = (value: string): string => value.replace(/[^A-Za-z0-9_-]/g, '_');\n\n// Hosted tools under the names the projection lists. Computer-use tools keep\n// their names unless a built-in tool has it (`computer_use_<name>`); a local\n// tool keeps its name unless something else has it or another local server\n// has the same tool (`<server>_<name>`).\nexport const hostedTools = (args: {\n catalog: SandboxMcpCatalogIface;\n computerUse: boolean;\n localMcp: boolean;\n // Only this local server (a per-server endpoint).\n localServer?: string;\n taken: ReadonlySet<string>;\n}): HostedToolIface[] => {\n const taken = new Set(args.taken);\n const tools: HostedToolIface[] = [];\n const claim = (preferred: string, fallback: string): string | null => {\n const name = taken.has(preferred) ? fallback : preferred;\n if (taken.has(name)) return null;\n taken.add(name);\n return name;\n };\n if (args.computerUse) {\n for (const tool of args.catalog.computerUse ?? []) {\n const name = claim(tool.name, `computer_use_${tool.name}`);\n if (name == null) continue;\n tools.push({\n name,\n server: { kind: SandboxHostedServerKind.ComputerUse },\n tool,\n policyKeys: [SandboxCapability.ComputerUse],\n });\n }\n }\n if (args.localMcp) {\n const servers = Object.entries(args.catalog.localMcp ?? {}).filter(\n ([server]) => args.localServer == null || server === args.localServer,\n );\n const counts = new Map<string, number>();\n for (const [, serverTools] of servers) {\n for (const tool of serverTools) counts.set(tool.name, (counts.get(tool.name) ?? 0) + 1);\n }\n for (const [server, serverTools] of servers) {\n for (const tool of serverTools) {\n const prefixed = `${toolNameSafe(server)}_${tool.name}`;\n const name =\n (counts.get(tool.name) ?? 0) > 1 ? claim(prefixed, prefixed) : claim(tool.name, prefixed);\n if (name == null) continue;\n tools.push({\n name,\n server: { kind: SandboxHostedServerKind.Local, name: server },\n tool,\n policyKeys: [`${server}/${tool.name}`, SandboxCapability.LocalMcp],\n });\n }\n }\n }\n return tools;\n};\n\nconst serverKeyOf = (server: SandboxHostedServer): string =>\n server.kind === SandboxHostedServerKind.ComputerUse\n ? 'computer-use'\n : `local\\u0000${server.name}`;\n\nexport interface HostedMcpCallOptionsIface {\n signal?: AbortSignal;\n}\n\nexport interface HostedMcpConnectionsIface {\n call(\n server: SandboxHostedServer,\n tool: string,\n input: JsonObject,\n options?: HostedMcpCallOptionsIface,\n ): Promise<CallToolResult>;\n // One server's live tools, over the connection its calls use.\n tools(server: SandboxHostedServer): Promise<ToolDescriptorIface[]>;\n // Reads the catalogs `needed` asks for (null fields) from the live sandbox.\n learn(\n sandbox: NetworkSandboxSessionIface,\n needed: { computerUse: boolean; localMcp: boolean },\n ): Promise<Partial<SandboxMcpCatalogIface>>;\n close(): Promise<void>;\n}\n\nexport const createHostedMcpConnections = (args: {\n getSandbox: () => Promise<NetworkSandboxSessionIface>;\n fetch?: FetchLike;\n name?: string;\n version?: string;\n catalog?: () => SandboxMcpCatalogIface;\n}): HostedMcpConnectionsIface => {\n const clients = new Map<string, Promise<Client>>();\n const unknownLocalCatalogs = new Set<string>();\n const localCatalogs = new Map<string, ToolDescriptorIface[]>();\n const closedClients = new WeakSet<Client>();\n const instances = new Set<Client>();\n const active = new Map<Promise<Client>, number>();\n const retired = new WeakSet<Client>();\n const lifetime = new AbortController();\n let closed = false;\n\n const connect = async (endpoint: SandboxMcpEndpoint): Promise<Client> => {\n if (closed) throw new Error('Hosted MCP connections are closed');\n const client = new Client({ name: args.name ?? 'final-sandbox', version: args.version ?? '1' });\n instances.add(client);\n try {\n if (isMcpChannelEndpoint(endpoint)) {\n const channel = await endpoint.connect({ abortSignal: lifetime.signal });\n if (closed) {\n await channel.close();\n throw new Error('Hosted MCP connections are closed');\n }\n await client.connect(createMcpChannelTransport({ channel, receiveWhileIdle: false }), {\n signal: lifetime.signal,\n });\n } else {\n await client.connect(\n new StreamableHTTPClientTransport(new URL(endpoint.url), {\n requestInit: { headers: endpoint.headers },\n fetch: args.fetch,\n }),\n { signal: lifetime.signal },\n );\n }\n if (closed) throw new Error('Hosted MCP connections are closed');\n return client;\n } catch (cause) {\n instances.delete(client);\n await client.close().catch(() => undefined);\n throw cause;\n }\n };\n\n const endpointOf = async (\n sandbox: NetworkSandboxSessionIface,\n server: SandboxHostedServer,\n ): Promise<SandboxMcpEndpoint> => {\n if (server.kind === SandboxHostedServerKind.ComputerUse) {\n if (sandbox.computerUse == null) throw new Error('this sandbox has no computer use');\n return sandbox.computerUse();\n }\n if (sandbox.localMcp == null) throw new Error('this sandbox has no local MCP servers');\n const found = (await sandbox.localMcp()).find((endpoint) => endpoint.name === server.name);\n if (found == null) throw new Error(`this sandbox has no local MCP server ${server.name}`);\n return found;\n };\n\n const clientFor = (key: string, endpoint: () => Promise<SandboxMcpEndpoint>): Promise<Client> => {\n if (closed) return Promise.reject(new Error('Hosted MCP connections are closed'));\n const existing = clients.get(key);\n if (existing != null) return existing;\n const connecting = endpoint()\n .then(connect)\n .then((client) => {\n client.onclose = () => {\n closedClients.add(client);\n instances.delete(client);\n if (clients.get(key) === connecting) clients.delete(key);\n };\n return client;\n });\n clients.set(key, connecting);\n connecting.catch(() => {\n if (clients.get(key) === connecting) clients.delete(key);\n });\n return connecting;\n };\n\n // One retry on a fresh connection: a parked or restarted server drops the old\n // one. An error the server answered with leaves the connection as it is.\n const withClient = async <T>(\n key: string,\n endpoint: () => Promise<SandboxMcpEndpoint>,\n work: (client: Client) => Promise<T>,\n retry = true,\n ): Promise<T> => {\n for (let attempt = 0; ; attempt += 1) {\n const connecting = clientFor(key, endpoint);\n // Reserve before awaiting the shared connection so a sibling cannot close under this call.\n active.set(connecting, (active.get(connecting) ?? 0) + 1);\n let connected: Client | null = null;\n try {\n connected = await connecting;\n return await work(connected);\n } catch (error) {\n if (error instanceof ProtocolError && (connected == null || !closedClients.has(connected)))\n throw error;\n if (\n connected != null &&\n error instanceof SdkError &&\n (error.code === SdkErrorCode.RequestTimeout ||\n error.code === SdkErrorCode.ConnectionClosed)\n ) {\n if (clients.get(key) === connecting) clients.delete(key);\n retired.add(connected);\n if (\n error.code === SdkErrorCode.ConnectionClosed &&\n attempt === 0 &&\n (retry || (mcpMessageNotSent in error && error[mcpMessageNotSent] === true))\n )\n continue;\n throw error;\n }\n // Business calls remain isolated; read-only discovery may retry on a fresh channel.\n if (connected != null && clients.get(key) === connecting) {\n clients.delete(key);\n retired.add(connected);\n if (!retry || attempt > 0) throw error;\n continue;\n }\n if (clients.get(key) === connecting) clients.delete(key);\n if (!retry || attempt > 0) throw error;\n } finally {\n const remaining = (active.get(connecting) ?? 1) - 1;\n if (remaining > 0) active.set(connecting, remaining);\n else {\n active.delete(connecting);\n if (connected != null && retired.has(connected))\n void connected.close().catch(() => undefined);\n }\n }\n }\n };\n\n const toolsOf = async (client: Client): Promise<ToolDescriptorIface[]> => {\n const tools: ToolDescriptorIface[] = [];\n let cursor: string | undefined;\n do {\n const page = await client.listTools(cursor == null ? undefined : { cursor }, {\n cacheMode: 'refresh',\n });\n for (const tool of page.tools) {\n const parsed = toolDescriptorSchema.safeParse(\n JSON.parse(\n JSON.stringify({\n name: tool.name,\n description: tool.description ?? tool.title ?? tool.name,\n inputSchema: tool.inputSchema,\n outputSchema: tool.outputSchema,\n annotations: tool.annotations,\n }),\n ),\n );\n if (parsed.success) tools.push(parsed.data);\n }\n cursor = page.nextCursor;\n } while (cursor != null);\n return tools;\n };\n\n return {\n call: async (server, tool, input, options) => {\n options?.signal?.throwIfAborted();\n return withClient(\n serverKeyOf(server),\n async () => endpointOf(await args.getSandbox(), server),\n async (client) => {\n const result = await client.callTool(\n { name: tool, arguments: input },\n { signal: options?.signal },\n );\n const proxied: CallToolResult = { content: result.content };\n if (result.structuredContent != null)\n proxied.structuredContent = result.structuredContent;\n if (result.isError === true) proxied.isError = true;\n return proxied;\n },\n false,\n );\n },\n tools: async (server) =>\n withClient(\n serverKeyOf(server),\n async () => endpointOf(await args.getSandbox(), server),\n toolsOf,\n ),\n learn: async (sandbox, needed) => {\n const learned: Partial<SandboxMcpCatalogIface> = {};\n if (needed.computerUse && sandbox.computerUse != null) {\n const server: SandboxHostedServer = { kind: SandboxHostedServerKind.ComputerUse };\n learned.computerUse = await withClient(\n serverKeyOf(server),\n () => endpointOf(sandbox, server),\n toolsOf,\n );\n }\n if (needed.localMcp && sandbox.localMcp != null) {\n const local: Record<string, ToolDescriptorIface[]> = {};\n const endpoints = await sandbox.localMcp();\n const names = new Set(endpoints.map((endpoint) => endpoint.name));\n for (const name of localCatalogs.keys()) if (!names.has(name)) localCatalogs.delete(name);\n unknownLocalCatalogs.clear();\n for (const endpoint of endpoints) {\n const server: SandboxHostedServer = {\n kind: SandboxHostedServerKind.Local,\n name: endpoint.name,\n };\n try {\n const tools = await withClient(serverKeyOf(server), async () => endpoint, toolsOf);\n local[endpoint.name] = tools;\n localCatalogs.set(endpoint.name, tools);\n } catch (cause) {\n if (closed) throw cause;\n unknownLocalCatalogs.add(endpoint.name);\n const previous =\n localCatalogs.get(endpoint.name) ?? args.catalog?.().localMcp?.[endpoint.name];\n if (previous != null) local[endpoint.name] = previous;\n }\n }\n learned.localMcp = local;\n learned.localMcpIncomplete = unknownLocalCatalogs.size > 0;\n }\n if (closed) throw new Error('Hosted MCP connections are closed');\n return learned;\n },\n close: async () => {\n closed = true;\n lifetime.abort(new Error('Hosted MCP connections are closed'));\n clients.clear();\n unknownLocalCatalogs.clear();\n localCatalogs.clear();\n const open = [...instances];\n instances.clear();\n await Promise.all(open.map((client) => client.close().catch(() => undefined)));\n },\n };\n};\n\n// A handle whose hosted servers are re-addressed: `computerUse()` and\n// `localMcp()` return HTTP endpoints where the host of the handle serves them\n// (its per-binding MCP addresses), so they can cross the handle RPC and the\n// sandbox's own endpoints and credentials never leave the host.\nexport const withHostedMcpEndpoints = <S extends NetworkSandboxSessionIface>(\n sandbox: S,\n endpointFor: (server: SandboxHostedServer) => McpEndpointIface,\n): S => {\n const addressed: S = { ...sandbox };\n // The host's proxy enforces admission on every request; only these replacement URLs cross RPC.\n markHostedMcpEndpoints(addressed);\n if (sandbox.computerUse != null) {\n addressed.computerUse = async () => endpointFor({ kind: SandboxHostedServerKind.ComputerUse });\n }\n const localMcp = sandbox.localMcp;\n if (localMcp != null) {\n addressed.localMcp = async () =>\n (await localMcp()).map((endpoint) =>\n endpointFor({ kind: SandboxHostedServerKind.Local, name: endpoint.name }),\n );\n }\n return addressed;\n};\n"],
5
+ "mappings": "AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AAGP,SAAS,4BAAsD;AAC/D,SAAS,8BAA8B;AACvC,SAAS,2BAA2B,yBAAyB;AAC7D;AAAA,EACE;AAAA,EACA;AAAA,OAKK;AAQA,IAAK,0BAAL,kBAAKA,6BAAL;AACL,EAAAA,yBAAA,iBAAc;AACd,EAAAA,yBAAA,WAAQ;AAFE,SAAAA;AAAA,GAAA;AASL,MAAM,2B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,gBAAQ,WAAW;AACnB,gBAAQ,qBAAqB,qBAAqB,OAAO;AAAA,MAC3D;AACA,UAAI,OAAQ,OAAM,IAAI,MAAM,mCAAmC;AAC/D,aAAO;AAAA,IACT;AAAA,IACA,OAAO,YAAY;AACjB,eAAS;AACT,eAAS,MAAM,IAAI,MAAM,mCAAmC,CAAC;AAC7D,cAAQ,MAAM;AACd,2BAAqB,MAAM;AAC3B,oBAAc,MAAM;AACpB,YAAM,OAAO,CAAC,GAAG,SAAS;AAC1B,gBAAU,MAAM;AAChB,YAAM,QAAQ,IAAI,KAAK,IAAI,CAAC,WAAW,OAAO,MAAM,EAAE,MAAM,MAAM,MAAS,CAAC,CAAC;AAAA,IAC/E;AAAA,EACF;AACF;AAMO,MAAM,yBAAyB,CACpC,SACA,gBACM;AACN,QAAM,YAAe,EAAE,GAAG,QAAQ;AAElC,yBAAuB,SAAS;AAChC,MAAI,QAAQ,eAAe,MAAM;AAC/B,cAAU,cAAc,YAAY,YAAY,EAAE,MAAM,gCAAoC,CAAC;AAAA,EAC/F;AACA,QAAM,WAAW,QAAQ;AACzB,MAAI,YAAY,MAAM;AACpB,cAAU,WAAW,aAClB,MAAM,SAAS,GAAG;AAAA,MAAI,CAAC,aACtB,YAAY,EAAE,MAAM,qBAA+B,MAAM,SAAS,KAAK,CAAC;AAAA,IAC1E;AAAA,EACJ;AACA,SAAO;AACT;",
6
6
  "names": ["SandboxHostedServerKind"]
7
7
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/sandbox/mcp-testing.ts"],
4
- "sourcesContent": ["import { InMemoryTransport, parseJSONRPCMessage } from '@modelcontextprotocol/client';\nimport { McpServer } from '@modelcontextprotocol/server';\nimport { jsonValueSchema, type JsonValue } from \"../json.mjs\";\nimport type { McpChannelEndpointIface, McpChannelIface } from \"./types.mjs\";\n\n// A sandbox-hosted MCP server as a channel endpoint backed by an in-process MCP\n// server, as a provider whose backend relays a pipe to the sandbox's server\n// would hand it over. For tests of hosts and providers.\n\nexport interface InProcessMcpChannelHooksIface {\n onConnect?: () => void;\n // Fails `receive` while it returns true (a broken pipe).\n failReceive?: () => boolean;\n}\n\nexport const createInProcessMcpChannelEndpoint = (args: {\n name: string;\n register: (server: McpServer) => void;\n hooks?: InProcessMcpChannelHooksIface;\n}): McpChannelEndpointIface => ({\n name: args.name,\n connect: async (): Promise<McpChannelIface> => {\n args.hooks?.onConnect?.();\n const server = new McpServer({ name: args.name, version: '1' });\n args.register(server);\n const [ours, theirs] = InMemoryTransport.createLinkedPair();\n await server.connect(theirs);\n const inbox: JsonValue[] = [];\n ours.onmessage = (message) => {\n inbox.push(jsonValueSchema.parse(JSON.parse(JSON.stringify(message))));\n };\n await ours.start();\n return {\n send: async (message) => ours.send(parseJSONRPCMessage(message)),\n receive: async () => {\n if (args.hooks?.failReceive?.() === true) throw new Error('the MCP pipe broke');\n return inbox.splice(0);\n },\n close: async () => {\n await ours.close();\n await server.close();\n },\n };\n },\n});\n"],
5
- "mappings": "AAAA,SAAS,mBAAmB,2BAA2B;AACvD,SAAS,iBAAiB;AAC1B,SAAS,uBAAuC;AAazC,MAAM,oCAAoC,CAAC,UAIlB;AAAA,EAC9B,MAAM,KAAK;AAAA,EACX,SAAS,YAAsC;AAC7C,SAAK,OAAO,YAAY;AACxB,UAAM,SAAS,IAAI,UAAU,EAAE,MAAM,KAAK,MAAM,SAAS,IAAI,CAAC;AAC9D,SAAK,SAAS,MAAM;AACpB,UAAM,CAAC,MAAM,MAAM,IAAI,kBAAkB,iBAAiB;AAC1D,UAAM,OAAO,QAAQ,MAAM;AAC3B,UAAM,QAAqB,CAAC;AAC5B,SAAK,YAAY,CAAC,YAAY;AAC5B,YAAM,KAAK,gBAAgB,MAAM,KAAK,MAAM,KAAK,UAAU,OAAO,CAAC,CAAC,CAAC;AAAA,IACvE;AACA,UAAM,KAAK,MAAM;AACjB,WAAO;AAAA,MACL,MAAM,OAAO,YAAY,KAAK,KAAK,oBAAoB,OAAO,CAAC;AAAA,MAC/D,SAAS,YAAY;AACnB,YAAI,KAAK,OAAO,cAAc,MAAM,KAAM,OAAM,IAAI,MAAM,oBAAoB;AAC9E,eAAO,MAAM,OAAO,CAAC;AAAA,MACvB;AAAA,MACA,OAAO,YAAY;AACjB,cAAM,KAAK,MAAM;AACjB,cAAM,OAAO,MAAM;AAAA,MACrB;AAAA,IACF;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import { InMemoryTransport, parseJSONRPCMessage } from '@modelcontextprotocol/client';\nimport { McpServer } from '@modelcontextprotocol/server';\nimport { jsonValueSchema, type JsonValue } from \"../json.mjs\";\nimport type { McpChannelEndpointIface, McpChannelIface } from \"./types.mjs\";\n\n// A sandbox-hosted MCP server as a channel endpoint backed by an in-process MCP\n// server, as a provider whose backend relays a pipe to the sandbox's server\n// would hand it over. For tests of hosts and providers, so it is exported as\n// `@finalai/agent-provider/testing/mcp` and not from the sandbox barrel.\n\nexport interface InProcessMcpChannelHooksIface {\n onConnect?: () => void;\n // Fails `receive` while it returns true (a broken pipe).\n failReceive?: () => boolean;\n}\n\nexport const createInProcessMcpChannelEndpoint = (args: {\n name: string;\n register: (server: McpServer) => void;\n hooks?: InProcessMcpChannelHooksIface;\n}): McpChannelEndpointIface => ({\n name: args.name,\n connect: async (): Promise<McpChannelIface> => {\n args.hooks?.onConnect?.();\n const server = new McpServer({ name: args.name, version: '1' });\n args.register(server);\n const [ours, theirs] = InMemoryTransport.createLinkedPair();\n await server.connect(theirs);\n const inbox: JsonValue[] = [];\n ours.onmessage = (message) => {\n inbox.push(jsonValueSchema.parse(JSON.parse(JSON.stringify(message))));\n };\n await ours.start();\n return {\n send: async (message) => ours.send(parseJSONRPCMessage(message)),\n receive: async () => {\n if (args.hooks?.failReceive?.() === true) throw new Error('the MCP pipe broke');\n return inbox.splice(0);\n },\n close: async () => {\n await ours.close();\n await server.close();\n },\n };\n },\n});\n"],
5
+ "mappings": "AAAA,SAAS,mBAAmB,2BAA2B;AACvD,SAAS,iBAAiB;AAC1B,SAAS,uBAAuC;AAczC,MAAM,oCAAoC,CAAC,UAIlB;AAAA,EAC9B,MAAM,KAAK;AAAA,EACX,SAAS,YAAsC;AAC7C,SAAK,OAAO,YAAY;AACxB,UAAM,SAAS,IAAI,UAAU,EAAE,MAAM,KAAK,MAAM,SAAS,IAAI,CAAC;AAC9D,SAAK,SAAS,MAAM;AACpB,UAAM,CAAC,MAAM,MAAM,IAAI,kBAAkB,iBAAiB;AAC1D,UAAM,OAAO,QAAQ,MAAM;AAC3B,UAAM,QAAqB,CAAC;AAC5B,SAAK,YAAY,CAAC,YAAY;AAC5B,YAAM,KAAK,gBAAgB,MAAM,KAAK,MAAM,KAAK,UAAU,OAAO,CAAC,CAAC,CAAC;AAAA,IACvE;AACA,UAAM,KAAK,MAAM;AACjB,WAAO;AAAA,MACL,MAAM,OAAO,YAAY,KAAK,KAAK,oBAAoB,OAAO,CAAC;AAAA,MAC/D,SAAS,YAAY;AACnB,YAAI,KAAK,OAAO,cAAc,MAAM,KAAM,OAAM,IAAI,MAAM,oBAAoB;AAC9E,eAAO,MAAM,OAAO,CAAC;AAAA,MACvB;AAAA,MACA,OAAO,YAAY;AACjB,cAAM,KAAK,MAAM;AACjB,cAAM,OAAO,MAAM;AAAA,MACrB;AAAA,IACF;AAAA,EACF;AACF;",
6
6
  "names": []
7
7
  }
@@ -21,8 +21,7 @@ export declare enum SandboxMcpTool {
21
21
  Stat = "stat",
22
22
  Grep = "grep",
23
23
  Glob = "glob",
24
- GetHost = "get_host",
25
- Egress = "egress"
24
+ GetHost = "get_host"
26
25
  }
27
26
  export declare enum SandboxMcpScopeKind {
28
27
  All = "all",
@@ -40,12 +39,11 @@ export declare const SANDBOX_FILE_RESOURCE_SCHEME = "sandbox-file";
40
39
  export interface SandboxMcpDescriptorOptionsIface {
41
40
  capabilities: readonly SandboxCapability[];
42
41
  grant?: SandboxGrantIface;
43
- lifecycle?: boolean;
44
42
  catalog?: SandboxMcpCatalogIface;
45
43
  scope?: SandboxMcpScope;
46
44
  }
47
45
  export declare const sandboxMcpToolDescriptors: (options: SandboxMcpDescriptorOptionsIface) => ToolDescriptorIface[];
48
- export declare const sandboxMcpToolPolicyKeys: (options: SandboxMcpDescriptorOptionsIface, name: string, input?: JsonObject) => string[] | null;
46
+ export declare const sandboxMcpToolPolicyKeys: (options: SandboxMcpDescriptorOptionsIface, name: string) => string[] | null;
49
47
  export interface CreateSandboxMcpServerArgsIface extends SandboxMcpDescriptorOptionsIface {
50
48
  getSandbox: () => Promise<NetworkSandboxSessionIface>;
51
49
  toolPolicy?: Record<string, ToolApproval>;
@@ -6,11 +6,6 @@ import {
6
6
  ResourceTemplate
7
7
  } from "@modelcontextprotocol/server";
8
8
  import * as z from "zod";
9
- import {
10
- WorkspaceEgressAction,
11
- workspaceEgressRequestSchema,
12
- workspaceEgressStatusSchema
13
- } from "@finalai/agent-protocol/device-egress";
14
9
  import { Capability, FilesAccess, ScreenAccess, ShellAccess } from "@finalai/agent-protocol";
15
10
  import { ToolApprovalMode as ToolApproval } from "../document.mjs";
16
11
  import { FULL_SANDBOX_GRANT, grantAllows } from "./grant.mjs";
@@ -49,7 +44,6 @@ var SandboxMcpTool = /* @__PURE__ */ ((SandboxMcpTool2) => {
49
44
  SandboxMcpTool2["Grep"] = "grep";
50
45
  SandboxMcpTool2["Glob"] = "glob";
51
46
  SandboxMcpTool2["GetHost"] = "get_host";
52
- SandboxMcpTool2["Egress"] = "egress";
53
47
  return SandboxMcpTool2;
54
48
  })(SandboxMcpTool || {});
55
49
  var SandboxMcpScopeKind = /* @__PURE__ */ ((SandboxMcpScopeKind2) => {
@@ -311,22 +305,6 @@ const BUILT_IN_TOOLS = [
311
305
  capability: SandboxCapability.Ports,
312
306
  write: false,
313
307
  policyKeys: ["ports"]
314
- }),
315
- tool({
316
- name: "egress" /* Egress */,
317
- title: "Workspace egress",
318
- description: "Route this Linux workspace\u2019s TCP and UDP traffic through your Final Devices. Configure an ordered list of owned Device IDs, query status, or explicitly disable routing. Losing all exits blocks traffic. IPv6 is blocked while enabled. Configuring or disabling requires approval by default: traffic uses the selected Device\u2019s network access, including private destinations; sandbox destination allowlists do not apply inside the tunnel. Disabling restores the saved direct-access policy. Remote hosted tools have their own network origin.",
319
- inputSchema: objectSchema(
320
- {
321
- action: { type: "string", enum: Object.values(WorkspaceEgressAction) },
322
- deviceIds: { type: "array", items: { type: "string" }, minItems: 1, maxItems: 5 },
323
- dnsResolvers: { type: "array", items: { type: "string" }, minItems: 1, maxItems: 3 }
324
- },
325
- ["action"]
326
- ),
327
- capability: SandboxCapability.Egress,
328
- write: true,
329
- policyKeys: ["network.egress", "lifecycle", SandboxCapability.NetworkPolicy, "network"]
330
308
  })
331
309
  ];
332
310
  const scopeOf = (options) => options.scope ?? { kind: "all" /* All */ };
@@ -356,31 +334,22 @@ const hostedSpec = (hosted) => {
356
334
  };
357
335
  const toolSpecs = (options) => {
358
336
  const capabilities = new Set(options.capabilities);
359
- const builtIn = scopeOf(options).kind === "all" /* All */ ? BUILT_IN_TOOLS.filter(
360
- (spec) => capabilities.has(spec.capability) && (spec.capability !== SandboxCapability.Egress || options.lifecycle === true)
361
- ) : [];
337
+ const builtIn = scopeOf(options).kind === "all" /* All */ ? BUILT_IN_TOOLS.filter((spec) => capabilities.has(spec.capability)) : [];
362
338
  const grant = grantOf(options);
363
339
  const visible = builtIn.filter((spec) => grantAllowsSpec(grant, spec));
364
340
  const hosted = hostedTools({
365
341
  catalog: options.catalog ?? EMPTY_MCP_CATALOG,
366
342
  ...hostedServersOf(options),
367
- taken: new Set(builtIn.map((spec) => spec.descriptor.name)),
368
- reserveEgress: visible.some((spec) => spec.capability === SandboxCapability.Egress)
343
+ taken: new Set(builtIn.map((spec) => spec.descriptor.name))
369
344
  });
370
345
  return [...visible, ...hosted.map(hostedSpec)];
371
346
  };
372
347
  const sandboxMcpToolDescriptors = (options) => toolSpecs(options).map((spec) => spec.descriptor);
373
- const policyKeysFor = (spec, name, input) => {
374
- return spec.hosted == null && name === "egress" /* Egress */ && input?.action === WorkspaceEgressAction.Status ? ["network.egress.status", name] : spec.hosted == null && name === "egress" /* Egress */ ? [
375
- input?.action === WorkspaceEgressAction.Disable ? "network.egress.disable" : "network.egress.configure",
376
- name,
377
- ...spec.policyKeys
378
- ] : [name, ...spec.policyKeys];
379
- };
380
- const sandboxMcpToolPolicyKeys = (options, name, input) => {
348
+ const policyKeysFor = (spec, name) => [name, ...spec.policyKeys];
349
+ const sandboxMcpToolPolicyKeys = (options, name) => {
381
350
  const spec = toolSpecs(options).find((candidate) => candidate.descriptor.name === name);
382
351
  if (spec == null) return null;
383
- return policyKeysFor(spec, name, input);
352
+ return policyKeysFor(spec, name);
384
353
  };
385
354
  const DEFAULT_LIMITS = {
386
355
  maxOutputChars: 64e3,
@@ -591,7 +560,7 @@ const createSandboxMcpServer = (args) => {
591
560
  };
592
561
  const shell = createSandboxShell({ getSandbox: sandboxFor, mode: args.shell });
593
562
  const isAllowed = async (spec, name, input) => {
594
- const keys = policyKeysFor(spec, name, input);
563
+ const keys = policyKeysFor(spec, name);
595
564
  const decision = resolveSandboxToolPolicy(args.toolPolicy ?? {}, keys);
596
565
  return decision?.decision !== ToolApproval.Ask || args.approve != null && await args.approve(name, input);
597
566
  };
@@ -896,16 +865,6 @@ ${truncateMiddle(head, limits.maxOutputChars)}`
896
865
  });
897
866
  return jsonResult({ url: endpoint.url, headers: endpoint.headers ?? {} });
898
867
  }
899
- case "egress" /* Egress */: {
900
- const sandbox = await sandboxFor();
901
- if (sandbox.egress == null)
902
- return errorResult("This sandbox provider does not support Device egress");
903
- return jsonResult(
904
- workspaceEgressStatusSchema.parse(
905
- await sandbox.egress(workspaceEgressRequestSchema.parse(rawArgs))
906
- )
907
- );
908
- }
909
868
  default:
910
869
  return errorResult(`unknown tool ${name}`);
911
870
  }
@@ -913,11 +872,6 @@ ${truncateMiddle(head, limits.maxOutputChars)}`
913
872
  const callTool = async (name, rawArgs, signal) => {
914
873
  const spec = byName.get(name);
915
874
  if (spec == null) return errorResult(`unknown tool ${name}`);
916
- if (spec.hosted == null && name === "egress" /* Egress */) {
917
- const parsed = workspaceEgressRequestSchema.safeParse(rawArgs);
918
- if (!parsed.success)
919
- return errorResult(`invalid arguments: ${z.prettifyError(parsed.error)}`);
920
- }
921
875
  if (!await isAllowed(spec, name, rawArgs)) return errorResult(`${name} was not approved`);
922
876
  try {
923
877
  signal?.throwIfAborted();