@finalai/agent-provider 0.9.0 → 0.10.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 (200) hide show
  1. package/HOSTING.md +334 -245
  2. package/README.md +93 -14
  3. package/dist/modules/canonical-json.d.mts +4 -0
  4. package/dist/modules/canonical-json.mjs +33 -0
  5. package/dist/modules/canonical-json.mjs.map +7 -0
  6. package/dist/modules/channel.d.mts +0 -3
  7. package/dist/modules/channel.mjs.map +1 -1
  8. package/dist/modules/code-host/host.d.mts +10 -0
  9. package/dist/modules/code-host/host.mjs +88 -0
  10. package/dist/modules/code-host/host.mjs.map +7 -0
  11. package/dist/modules/code-host/in-process.d.mts +24 -0
  12. package/dist/modules/code-host/in-process.mjs +89 -0
  13. package/dist/modules/code-host/in-process.mjs.map +7 -0
  14. package/dist/modules/code-host/index.d.mts +4 -0
  15. package/dist/modules/code-host/index.mjs +5 -0
  16. package/dist/modules/code-host/index.mjs.map +7 -0
  17. package/dist/modules/code-host/serverless.d.mts +63 -0
  18. package/dist/modules/code-host/serverless.mjs +27 -0
  19. package/dist/modules/code-host/serverless.mjs.map +7 -0
  20. package/dist/modules/code-host/types.d.mts +152 -0
  21. package/dist/modules/code-host/types.mjs +85 -0
  22. package/dist/modules/code-host/types.mjs.map +7 -0
  23. package/dist/modules/conformance/agent.mjs +72 -6
  24. package/dist/modules/conformance/agent.mjs.map +2 -2
  25. package/dist/modules/conformance/harness-kit.d.mts +9 -2
  26. package/dist/modules/conformance/harness-kit.mjs +224 -63
  27. package/dist/modules/conformance/harness-kit.mjs.map +3 -3
  28. package/dist/modules/conformance/local-harness.d.mts +1 -4
  29. package/dist/modules/conformance/local-harness.mjs +21 -22
  30. package/dist/modules/conformance/local-harness.mjs.map +2 -2
  31. package/dist/modules/conformance/protocol.d.mts +1 -0
  32. package/dist/modules/conformance/protocol.mjs +2 -0
  33. package/dist/modules/conformance/protocol.mjs.map +2 -2
  34. package/dist/modules/conformance/sandbox-kit.d.mts +12 -4
  35. package/dist/modules/conformance/sandbox-kit.mjs +189 -103
  36. package/dist/modules/conformance/sandbox-kit.mjs.map +2 -2
  37. package/dist/modules/conformance/scripted-model/chat-completions.mjs +1 -0
  38. package/dist/modules/conformance/scripted-model/chat-completions.mjs.map +2 -2
  39. package/dist/modules/conformance/scripted-model/directives.d.mts +3 -0
  40. package/dist/modules/conformance/scripted-model/directives.mjs +26 -10
  41. package/dist/modules/conformance/scripted-model/directives.mjs.map +2 -2
  42. package/dist/modules/conformance/scripted-model/messages.mjs +1 -0
  43. package/dist/modules/conformance/scripted-model/messages.mjs.map +2 -2
  44. package/dist/modules/conformance/scripted-model/responses.mjs +2 -0
  45. package/dist/modules/conformance/scripted-model/responses.mjs.map +2 -2
  46. package/dist/modules/conformance/stdio.d.mts +21 -0
  47. package/dist/modules/conformance/stdio.mjs +158 -0
  48. package/dist/modules/conformance/stdio.mjs.map +7 -0
  49. package/dist/modules/credential-routes.d.mts +2 -0
  50. package/dist/modules/credential-routes.mjs +2 -0
  51. package/dist/modules/credential-routes.mjs.map +2 -2
  52. package/dist/modules/document.d.mts +376 -0
  53. package/dist/modules/document.mjs +208 -0
  54. package/dist/modules/document.mjs.map +7 -0
  55. package/dist/modules/harness-configuration.d.mts +16 -0
  56. package/dist/modules/harness-configuration.mjs +83 -0
  57. package/dist/modules/harness-configuration.mjs.map +7 -0
  58. package/dist/modules/harness-definition.d.mts +280 -0
  59. package/dist/modules/harness-definition.mjs +430 -0
  60. package/dist/modules/harness-definition.mjs.map +7 -0
  61. package/dist/modules/harness-provider.d.mts +197 -0
  62. package/dist/modules/harness-provider.mjs +108 -0
  63. package/dist/modules/harness-provider.mjs.map +7 -0
  64. package/dist/modules/harness-requirements.d.mts +19 -0
  65. package/dist/modules/harness-requirements.mjs +40 -0
  66. package/dist/modules/harness-requirements.mjs.map +7 -0
  67. package/dist/modules/harness-start.d.mts +33 -0
  68. package/dist/modules/harness-start.mjs +107 -0
  69. package/dist/modules/harness-start.mjs.map +7 -0
  70. package/dist/modules/harness.d.mts +84 -109
  71. package/dist/modules/harness.mjs +56 -111
  72. package/dist/modules/harness.mjs.map +3 -3
  73. package/dist/modules/identity.d.mts +1 -0
  74. package/dist/modules/identity.mjs +2 -0
  75. package/dist/modules/identity.mjs.map +7 -0
  76. package/dist/modules/index.d.mts +12 -6
  77. package/dist/modules/index.mjs +12 -6
  78. package/dist/modules/index.mjs.map +2 -2
  79. package/dist/modules/inference.d.mts +35 -0
  80. package/dist/modules/inference.mjs +74 -0
  81. package/dist/modules/inference.mjs.map +7 -0
  82. package/dist/modules/local-channel-context.mjs +1 -1
  83. package/dist/modules/local-channel-context.mjs.map +2 -2
  84. package/dist/modules/requirements-check.d.mts +30 -0
  85. package/dist/modules/requirements-check.mjs +164 -0
  86. package/dist/modules/requirements-check.mjs.map +7 -0
  87. package/dist/modules/room-surface.d.mts +0 -5
  88. package/dist/modules/room-surface.mjs.map +2 -2
  89. package/dist/modules/sandbox/client.d.mts +3 -0
  90. package/dist/modules/sandbox/client.mjs +101 -18
  91. package/dist/modules/sandbox/client.mjs.map +2 -2
  92. package/dist/modules/sandbox/grant.d.mts +78 -0
  93. package/dist/modules/sandbox/grant.mjs +134 -0
  94. package/dist/modules/sandbox/grant.mjs.map +7 -0
  95. package/dist/modules/sandbox/index.d.mts +3 -3
  96. package/dist/modules/sandbox/index.mjs +4 -5
  97. package/dist/modules/sandbox/index.mjs.map +2 -2
  98. package/dist/modules/sandbox/mcp-hosted.d.mts +1 -1
  99. package/dist/modules/sandbox/mcp-hosted.mjs +4 -7
  100. package/dist/modules/sandbox/mcp-hosted.mjs.map +2 -2
  101. package/dist/modules/sandbox/mcp.d.mts +4 -2
  102. package/dist/modules/sandbox/mcp.mjs +14 -7
  103. package/dist/modules/sandbox/mcp.mjs.map +2 -2
  104. package/dist/modules/sandbox/memory-sandbox.d.mts +2 -1
  105. package/dist/modules/sandbox/memory-sandbox.mjs +71 -41
  106. package/dist/modules/sandbox/memory-sandbox.mjs.map +2 -2
  107. package/dist/modules/sandbox/networking.d.mts +7 -7
  108. package/dist/modules/sandbox/networking.mjs +16 -9
  109. package/dist/modules/sandbox/networking.mjs.map +2 -2
  110. package/dist/modules/sandbox/remote/adapter.d.mts +30 -0
  111. package/dist/modules/sandbox/remote/adapter.mjs +381 -0
  112. package/dist/modules/sandbox/remote/adapter.mjs.map +7 -0
  113. package/dist/modules/sandbox/remote/errors.d.mts +10 -0
  114. package/dist/modules/sandbox/remote/errors.mjs +62 -0
  115. package/dist/modules/sandbox/remote/errors.mjs.map +7 -0
  116. package/dist/modules/sandbox/remote/index.d.mts +5 -0
  117. package/dist/modules/sandbox/remote/index.mjs +6 -0
  118. package/dist/modules/sandbox/remote/index.mjs.map +7 -0
  119. package/dist/modules/sandbox/remote/ndjson.d.mts +6 -0
  120. package/dist/modules/sandbox/remote/ndjson.mjs +80 -0
  121. package/dist/modules/sandbox/remote/ndjson.mjs.map +7 -0
  122. package/dist/modules/sandbox/remote/platform-api.d.mts +8 -0
  123. package/dist/modules/sandbox/remote/platform-api.mjs +15 -0
  124. package/dist/modules/sandbox/remote/platform-api.mjs.map +7 -0
  125. package/dist/modules/sandbox/remote/preamble.d.mts +7 -0
  126. package/dist/modules/sandbox/remote/preamble.mjs +51 -0
  127. package/dist/modules/sandbox/remote/preamble.mjs.map +7 -0
  128. package/dist/modules/sandbox/remote/serve.d.mts +34 -0
  129. package/dist/modules/sandbox/remote/serve.mjs +519 -0
  130. package/dist/modules/sandbox/remote/serve.mjs.map +7 -0
  131. package/dist/modules/sandbox/remote/testing.d.mts +34 -0
  132. package/dist/modules/sandbox/remote/testing.mjs +275 -0
  133. package/dist/modules/sandbox/remote/testing.mjs.map +7 -0
  134. package/dist/modules/sandbox/seeds.d.mts +2 -2
  135. package/dist/modules/sandbox/seeds.mjs +2 -2
  136. package/dist/modules/sandbox/seeds.mjs.map +2 -2
  137. package/dist/modules/sandbox/server.d.mts +4 -6
  138. package/dist/modules/sandbox/server.mjs +93 -49
  139. package/dist/modules/sandbox/server.mjs.map +2 -2
  140. package/dist/modules/sandbox/setup/apply.d.mts +41 -0
  141. package/dist/modules/sandbox/setup/apply.mjs +204 -0
  142. package/dist/modules/sandbox/setup/apply.mjs.map +7 -0
  143. package/dist/modules/sandbox/setup/describe.d.mts +10 -0
  144. package/dist/modules/sandbox/setup/describe.mjs +62 -0
  145. package/dist/modules/sandbox/setup/describe.mjs.map +7 -0
  146. package/dist/modules/sandbox/setup/index.d.mts +6 -0
  147. package/dist/modules/sandbox/setup/index.mjs +17 -0
  148. package/dist/modules/sandbox/setup/index.mjs.map +7 -0
  149. package/dist/modules/sandbox/setup/paths.d.mts +8 -0
  150. package/dist/modules/sandbox/setup/paths.mjs +18 -0
  151. package/dist/modules/sandbox/setup/paths.mjs.map +7 -0
  152. package/dist/modules/sandbox/setup/schema.d.mts +42 -0
  153. package/dist/modules/sandbox/setup/schema.mjs +58 -0
  154. package/dist/modules/sandbox/setup/schema.mjs.map +7 -0
  155. package/dist/modules/sandbox/tool-policy.d.mts +1 -1
  156. package/dist/modules/sandbox/tool-policy.mjs +1 -1
  157. package/dist/modules/sandbox/tool-policy.mjs.map +2 -2
  158. package/dist/modules/sandbox/types.d.mts +117 -130
  159. package/dist/modules/sandbox/types.mjs +46 -50
  160. package/dist/modules/sandbox/types.mjs.map +3 -3
  161. package/dist/modules/sandbox/wire.d.mts +93 -6
  162. package/dist/modules/sandbox/wire.mjs +61 -38
  163. package/dist/modules/sandbox/wire.mjs.map +2 -2
  164. package/dist/modules/schemas.d.mts +5 -76
  165. package/dist/modules/schemas.mjs +18 -85
  166. package/dist/modules/schemas.mjs.map +2 -2
  167. package/dist/modules/tool-annotations.d.mts +15 -6
  168. package/dist/modules/tool-annotations.mjs +9 -3
  169. package/dist/modules/tool-annotations.mjs.map +2 -2
  170. package/dist/modules/tool-descriptor.d.mts +16 -0
  171. package/dist/modules/tool-descriptor.mjs +19 -0
  172. package/dist/modules/tool-descriptor.mjs.map +7 -0
  173. package/dist/modules/tool-patterns.d.mts +7 -7
  174. package/dist/modules/tool-patterns.mjs +10 -9
  175. package/dist/modules/tool-patterns.mjs.map +2 -2
  176. package/package.json +86 -36
  177. package/dist/modules/credentials.d.mts +0 -206
  178. package/dist/modules/credentials.mjs +0 -207
  179. package/dist/modules/credentials.mjs.map +0 -7
  180. package/dist/modules/dynamic.d.mts +0 -40
  181. package/dist/modules/dynamic.mjs +0 -79
  182. package/dist/modules/dynamic.mjs.map +0 -7
  183. package/dist/modules/hosted-bindings.d.mts +0 -15
  184. package/dist/modules/hosted-bindings.mjs +0 -21
  185. package/dist/modules/hosted-bindings.mjs.map +0 -7
  186. package/dist/modules/manifest.d.mts +0 -791
  187. package/dist/modules/manifest.mjs +0 -322
  188. package/dist/modules/manifest.mjs.map +0 -7
  189. package/dist/modules/provider-ref.d.mts +0 -29
  190. package/dist/modules/provider-ref.mjs +0 -55
  191. package/dist/modules/provider-ref.mjs.map +0 -7
  192. package/dist/modules/sandbox/open-scope-node.d.mts +0 -4
  193. package/dist/modules/sandbox/open-scope-node.mjs +0 -19
  194. package/dist/modules/sandbox/open-scope-node.mjs.map +0 -7
  195. package/dist/modules/sandbox/open-scope.d.mts +0 -16
  196. package/dist/modules/sandbox/open-scope.mjs +0 -66
  197. package/dist/modules/sandbox/open-scope.mjs.map +0 -7
  198. package/dist/modules/sandbox/workspace-identity.d.mts +0 -5
  199. package/dist/modules/sandbox/workspace-identity.mjs +0 -14
  200. package/dist/modules/sandbox/workspace-identity.mjs.map +0 -7
@@ -0,0 +1,78 @@
1
+ import { Capability, FilesAccess, ScreenAccess, ShellAccess, type CapabilityAccess } from '@finalai/agent-protocol';
2
+ import * as z from 'zod';
3
+ import type { JsonValue } from "../json.mjs";
4
+ import { HandleRpcMethod } from "./wire.mjs";
5
+ export interface SandboxGrantIface {
6
+ [Capability.Files]?: FilesAccess;
7
+ [Capability.Shell]?: ShellAccess;
8
+ [Capability.ComputerUse]?: ScreenAccess;
9
+ [Capability.BrowserUse]?: ScreenAccess;
10
+ }
11
+ export declare const sandboxGrantSchema: z.ZodObject<{
12
+ files: z.ZodOptional<z.ZodEnum<typeof FilesAccess>>;
13
+ shell: z.ZodOptional<z.ZodEnum<typeof ShellAccess>>;
14
+ computerUse: z.ZodOptional<z.ZodEnum<typeof ScreenAccess>>;
15
+ browserUse: z.ZodOptional<z.ZodEnum<typeof ScreenAccess>>;
16
+ }, z.core.$strict>;
17
+ export declare const FULL_SANDBOX_GRANT: Readonly<SandboxGrantIface>;
18
+ export declare const grantAllows: (grant: SandboxGrantIface, capability: Capability, access: CapabilityAccess) => boolean;
19
+ export declare const narrowerGrant: (a: SandboxGrantIface, b: SandboxGrantIface) => SandboxGrantIface;
20
+ export declare const sandboxGrantFor: (args: {
21
+ capabilities: readonly Capability[];
22
+ required: Partial<Record<Capability, {
23
+ access: CapabilityAccess;
24
+ }>>;
25
+ }) => SandboxGrantIface;
26
+ export interface HandleMethodNeedIface {
27
+ capability: Capability;
28
+ access: CapabilityAccess;
29
+ }
30
+ export interface HandleMethodGateIface {
31
+ needs: HandleMethodNeedIface | null;
32
+ lifecycle: boolean;
33
+ channel: boolean;
34
+ }
35
+ export declare const HANDLE_METHOD_GATES: {
36
+ readonly initialize: HandleMethodGateIface;
37
+ readonly "sandbox/describe": HandleMethodGateIface;
38
+ readonly "auth/refresh": HandleMethodGateIface;
39
+ readonly "identity/refresh": HandleMethodGateIface;
40
+ readonly "sandbox/readFile": HandleMethodGateIface;
41
+ readonly "sandbox/readTextFile": HandleMethodGateIface;
42
+ readonly "sandbox/stat": HandleMethodGateIface;
43
+ readonly "sandbox/readDir": HandleMethodGateIface;
44
+ readonly "sandbox/writeFile": HandleMethodGateIface;
45
+ readonly "sandbox/removePath": HandleMethodGateIface;
46
+ readonly "sandbox/spawn": HandleMethodGateIface;
47
+ readonly "sandbox/run": HandleMethodGateIface;
48
+ readonly "sandbox/startWorker": HandleMethodGateIface;
49
+ readonly "process/wait": HandleMethodGateIface;
50
+ readonly "process/kill": HandleMethodGateIface;
51
+ readonly "process/attach": HandleMethodGateIface;
52
+ readonly "process/detach": HandleMethodGateIface;
53
+ readonly "sandbox/getPortEndpoint": HandleMethodGateIface;
54
+ readonly "sandbox/localMcp": HandleMethodGateIface;
55
+ readonly "sandbox/computerUse": HandleMethodGateIface;
56
+ readonly "sandbox/screen": HandleMethodGateIface;
57
+ readonly "mcp/open": HandleMethodGateIface;
58
+ readonly "mcp/send": HandleMethodGateIface;
59
+ readonly "mcp/receive": HandleMethodGateIface;
60
+ readonly "mcp/close": HandleMethodGateIface;
61
+ readonly "sandbox/egress": HandleMethodGateIface;
62
+ readonly "sandbox/setNetworkPolicy": HandleMethodGateIface;
63
+ readonly "sandbox/stop": HandleMethodGateIface;
64
+ readonly "sandbox/destroy": HandleMethodGateIface;
65
+ readonly "handle/onSandboxStop": HandleMethodGateIface;
66
+ readonly "handle/onSandboxDelete": HandleMethodGateIface;
67
+ readonly "handle/onRuntimeShutdown": HandleMethodGateIface;
68
+ };
69
+ export declare const handleMethodGate: (method: HandleRpcMethod, params: JsonValue | undefined) => HandleMethodGateIface;
70
+ export interface HandleAccessPolicyIface {
71
+ grant: SandboxGrantIface;
72
+ lifecycle: boolean;
73
+ }
74
+ export declare const handleMethodRefusal: (args: {
75
+ access: HandleAccessPolicyIface;
76
+ method: HandleRpcMethod;
77
+ params?: JsonValue;
78
+ }) => string | null;
@@ -0,0 +1,134 @@
1
+ import {
2
+ Capability,
3
+ capabilityAccessCovers,
4
+ FilesAccess,
5
+ ScreenAccess,
6
+ ShellAccess
7
+ } from "@finalai/agent-protocol";
8
+ import * as z from "zod";
9
+ import { HandleRpcMethod } from "./wire.mjs";
10
+ const sandboxGrantSchema = z.strictObject({
11
+ [Capability.Files]: z.nativeEnum(FilesAccess).optional(),
12
+ [Capability.Shell]: z.nativeEnum(ShellAccess).optional(),
13
+ [Capability.ComputerUse]: z.nativeEnum(ScreenAccess).optional(),
14
+ [Capability.BrowserUse]: z.nativeEnum(ScreenAccess).optional()
15
+ });
16
+ const FULL_SANDBOX_GRANT = {
17
+ [Capability.Files]: FilesAccess.Write,
18
+ [Capability.Shell]: ShellAccess.Execute,
19
+ [Capability.ComputerUse]: ScreenAccess.Control,
20
+ [Capability.BrowserUse]: ScreenAccess.Control
21
+ };
22
+ const grantAllows = (grant, capability, access) => {
23
+ const granted = grant[capability];
24
+ return granted != null && capabilityAccessCovers(granted, access);
25
+ };
26
+ const lesser = (a, b) => {
27
+ if (a == null || b == null) return void 0;
28
+ return capabilityAccessCovers(a, b) ? b : a;
29
+ };
30
+ const narrowerGrant = (a, b) => {
31
+ const grant = {};
32
+ const files = lesser(a[Capability.Files], b[Capability.Files]);
33
+ if (files != null) grant[Capability.Files] = files;
34
+ const shell = lesser(a[Capability.Shell], b[Capability.Shell]);
35
+ if (shell != null) grant[Capability.Shell] = shell;
36
+ const computerUse = lesser(a[Capability.ComputerUse], b[Capability.ComputerUse]);
37
+ if (computerUse != null) grant[Capability.ComputerUse] = computerUse;
38
+ const browserUse = lesser(a[Capability.BrowserUse], b[Capability.BrowserUse]);
39
+ if (browserUse != null) grant[Capability.BrowserUse] = browserUse;
40
+ return grant;
41
+ };
42
+ const sandboxGrantFor = (args) => {
43
+ const grant = {};
44
+ for (const capability of args.capabilities) {
45
+ const access = args.required[capability]?.access;
46
+ if (access == null) continue;
47
+ const parsed = sandboxGrantSchema.shape[capability].safeParse(access);
48
+ if (!parsed.success || parsed.data == null) continue;
49
+ Object.assign(grant, { [capability]: parsed.data });
50
+ }
51
+ return grant;
52
+ };
53
+ const none = { needs: null, lifecycle: false, channel: false };
54
+ const needs = (capability, access) => ({
55
+ needs: { capability, access },
56
+ lifecycle: false,
57
+ channel: false
58
+ });
59
+ const lifecycle = (need = null) => ({
60
+ needs: need,
61
+ lifecycle: true,
62
+ channel: false
63
+ });
64
+ const channel = { needs: null, lifecycle: false, channel: true };
65
+ const readFiles = needs(Capability.Files, FilesAccess.Read);
66
+ const writeFiles = needs(Capability.Files, FilesAccess.Write);
67
+ const execute = needs(Capability.Shell, ShellAccess.Execute);
68
+ const HANDLE_METHOD_GATES = {
69
+ [HandleRpcMethod.Initialize]: none,
70
+ [HandleRpcMethod.Describe]: none,
71
+ [HandleRpcMethod.AuthRefresh]: none,
72
+ [HandleRpcMethod.IdentityRefresh]: none,
73
+ [HandleRpcMethod.ReadFile]: readFiles,
74
+ [HandleRpcMethod.ReadTextFile]: readFiles,
75
+ [HandleRpcMethod.Stat]: readFiles,
76
+ [HandleRpcMethod.ReadDir]: readFiles,
77
+ [HandleRpcMethod.WriteFile]: writeFiles,
78
+ [HandleRpcMethod.RemovePath]: writeFiles,
79
+ [HandleRpcMethod.Spawn]: execute,
80
+ [HandleRpcMethod.Run]: execute,
81
+ // The platform starts a harness program; the model never does. `process/*`
82
+ // on a worker program are gated the same way.
83
+ [HandleRpcMethod.StartWorker]: lifecycle(),
84
+ [HandleRpcMethod.ProcessWait]: execute,
85
+ [HandleRpcMethod.ProcessKill]: execute,
86
+ [HandleRpcMethod.ProcessAttach]: execute,
87
+ [HandleRpcMethod.ProcessDetach]: execute,
88
+ // A URL for a port only serves something a command started.
89
+ [HandleRpcMethod.GetPortEndpoint]: execute,
90
+ // Servers the sandbox hosts run as processes on it.
91
+ [HandleRpcMethod.LocalMcp]: execute,
92
+ [HandleRpcMethod.ComputerUse]: needs(Capability.ComputerUse, ScreenAccess.Control),
93
+ [HandleRpcMethod.Screen]: needs(Capability.ComputerUse, ScreenAccess.View),
94
+ [HandleRpcMethod.McpOpen]: channel,
95
+ [HandleRpcMethod.McpSend]: channel,
96
+ [HandleRpcMethod.McpReceive]: channel,
97
+ [HandleRpcMethod.McpClose]: channel,
98
+ [HandleRpcMethod.Egress]: lifecycle({
99
+ capability: Capability.Shell,
100
+ access: ShellAccess.Execute
101
+ }),
102
+ // Network policy only matters to something that runs commands.
103
+ [HandleRpcMethod.SetNetworkPolicy]: lifecycle({
104
+ capability: Capability.Shell,
105
+ access: ShellAccess.Execute
106
+ }),
107
+ [HandleRpcMethod.Stop]: lifecycle(),
108
+ [HandleRpcMethod.Destroy]: lifecycle(),
109
+ [HandleRpcMethod.OnSandboxStop]: lifecycle(),
110
+ [HandleRpcMethod.OnSandboxDelete]: lifecycle(),
111
+ [HandleRpcMethod.OnRuntimeShutdown]: lifecycle()
112
+ };
113
+ const screenControlSchema = z.object({ viewOnly: z.literal(false) });
114
+ const handleMethodGate = (method, params) => method === HandleRpcMethod.Screen && screenControlSchema.safeParse(params).success ? needs(Capability.ComputerUse, ScreenAccess.Control) : HANDLE_METHOD_GATES[method];
115
+ const handleMethodRefusal = (args) => {
116
+ const gate = handleMethodGate(args.method, args.params);
117
+ if (gate.lifecycle && !args.access.lifecycle)
118
+ return `${args.method} is not allowed on this connection`;
119
+ const need = gate.needs;
120
+ if (need != null && !grantAllows(args.access.grant, need.capability, need.access))
121
+ return `${args.method} needs ${need.capability} ${need.access}`;
122
+ return null;
123
+ };
124
+ export {
125
+ FULL_SANDBOX_GRANT,
126
+ HANDLE_METHOD_GATES,
127
+ grantAllows,
128
+ handleMethodGate,
129
+ handleMethodRefusal,
130
+ narrowerGrant,
131
+ sandboxGrantFor,
132
+ sandboxGrantSchema
133
+ };
134
+ //# sourceMappingURL=grant.mjs.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 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,MA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-2,7 +2,6 @@ export { withSandboxExecutionGuard, SandboxExecutionOperation, type SandboxExecu
2
2
  export { withSandboxOverrides } from "./overrides.mjs";
3
3
  export { createSandboxHandle, mapSandboxHandle, type CreateSandboxHandleOptionsIface, type SandboxExecutionPolicyIface, } from "./handle.mjs";
4
4
  export * from "./networking.mjs";
5
- export { sandboxWorkspaceId } from "./workspace-identity.mjs";
6
5
  export { resolveSandboxToolPolicy } from "./tool-policy.mjs";
7
6
  export { WorkspaceEgressAction, workspaceEgressRequestSchema, workspaceEgressStatusSchema, type WorkspaceEgressRequestIface, type WorkspaceEgressStatusIface, } from '@finalai/agent-protocol/device-egress';
8
7
  export { ProcessInspectionOperation, inspectedProcessSchema, processInspectionDetailSchema, processInspectionPageSchema, processInspectionRequestSchema, processInspectionResultSchema, type InspectedProcessIface, type ProcessInspectionDetailIface, type ProcessInspectionPageIface, type ProcessInspectionRequestIface, type ProcessInspectionResultIface, } from '@finalai/agent-protocol/process-inspection';
@@ -13,12 +12,13 @@ export * from "./convenience.mjs";
13
12
  export * from "./mcp.mjs";
14
13
  export * from "./mcp-testing.mjs";
15
14
  export * from "./memory-sandbox.mjs";
16
- export * from "./open-scope.mjs";
17
- export { MAX_SANDBOX_SEED_BYTES, SANDBOX_SEED_MARKER, SANDBOX_SEED_PROTOCOL, materializeSandboxSeeds, sandboxPreparationInputs, sandboxSeedArtifact, sandboxSeedArtifactSchema, sandboxSeedFiles, sandboxSeedFilesForStart, sandboxSeedFilesSchema, sandboxSeedIdentity, } from "./seeds.mjs";
15
+ export { MAX_SANDBOX_SEED_BYTES, SANDBOX_SEED_MARKER, SANDBOX_SEED_PROTOCOL, materializeSandboxSeeds, sandboxPreparationInputs, sandboxSeedArtifact, sandboxSeedArtifactSchema, sandboxSeedFiles, sandboxSeedFilesForAttach, sandboxSeedFilesSchema, sandboxSeedIdentity, } from "./seeds.mjs";
18
16
  export * from "./server.mjs";
19
17
  export * from "./testing.mjs";
20
18
  export * from "./types.mjs";
21
19
  export * from "./wire.mjs";
20
+ export * from "./grant.mjs";
21
+ export * from "./setup/index.mjs";
22
22
  export { mapSessionPath, withSessionWorkspaceRoot } from "./workspace-root.mjs";
23
23
  export type { MapSessionPathArgsIface } from "./workspace-root.mjs";
24
24
  export * from "./snapshots.mjs";
@@ -8,7 +8,6 @@ import {
8
8
  mapSandboxHandle
9
9
  } from "./handle.mjs";
10
10
  export * from "./networking.mjs";
11
- import { sandboxWorkspaceId } from "./workspace-identity.mjs";
12
11
  import { resolveSandboxToolPolicy } from "./tool-policy.mjs";
13
12
  import {
14
13
  WorkspaceEgressAction,
@@ -30,7 +29,6 @@ export * from "./convenience.mjs";
30
29
  export * from "./mcp.mjs";
31
30
  export * from "./mcp-testing.mjs";
32
31
  export * from "./memory-sandbox.mjs";
33
- export * from "./open-scope.mjs";
34
32
  import {
35
33
  MAX_SANDBOX_SEED_BYTES,
36
34
  SANDBOX_SEED_MARKER,
@@ -40,7 +38,7 @@ import {
40
38
  sandboxSeedArtifact,
41
39
  sandboxSeedArtifactSchema,
42
40
  sandboxSeedFiles,
43
- sandboxSeedFilesForStart,
41
+ sandboxSeedFilesForAttach,
44
42
  sandboxSeedFilesSchema,
45
43
  sandboxSeedIdentity
46
44
  } from "./seeds.mjs";
@@ -48,6 +46,8 @@ export * from "./server.mjs";
48
46
  export * from "./testing.mjs";
49
47
  export * from "./types.mjs";
50
48
  export * from "./wire.mjs";
49
+ export * from "./grant.mjs";
50
+ export * from "./setup/index.mjs";
51
51
  import { mapSessionPath, withSessionWorkspaceRoot } from "./workspace-root.mjs";
52
52
  export * from "./snapshots.mjs";
53
53
  import {
@@ -86,10 +86,9 @@ export {
86
86
  sandboxSeedArtifact,
87
87
  sandboxSeedArtifactSchema,
88
88
  sandboxSeedFiles,
89
- sandboxSeedFilesForStart,
89
+ sandboxSeedFilesForAttach,
90
90
  sandboxSeedFilesSchema,
91
91
  sandboxSeedIdentity,
92
- sandboxWorkspaceId,
93
92
  withSandboxExecutionGuard,
94
93
  withSandboxOverrides,
95
94
  withSessionWorkspaceRoot,
@@ -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 { sandboxWorkspaceId } from \"./workspace-identity.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 * from \"./open-scope.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 sandboxSeedFilesForStart,\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 { 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,0BAA0B;AACnC,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,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,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 * 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;",
6
6
  "names": []
7
7
  }
@@ -1,7 +1,7 @@
1
1
  import { type FetchLike } from '@modelcontextprotocol/client';
2
2
  import type { CallToolResult } from '@modelcontextprotocol/server';
3
3
  import type { JsonObject } from "../json.mjs";
4
- import { type ToolDescriptorIface } from "../manifest.mjs";
4
+ import { type ToolDescriptorIface } from "../tool-descriptor.mjs";
5
5
  import { type McpEndpointIface, type NetworkSandboxSessionIface, type SandboxMcpCatalogIface } from "./types.mjs";
6
6
  export declare enum SandboxHostedServerKind {
7
7
  ComputerUse = "computerUse",
@@ -5,7 +5,7 @@ import {
5
5
  SdkErrorCode,
6
6
  StreamableHTTPClientTransport
7
7
  } from "@modelcontextprotocol/client";
8
- import { toolDescriptorSchema } from "../manifest.mjs";
8
+ import { toolDescriptorSchema } from "../tool-descriptor.mjs";
9
9
  import { markHostedMcpEndpoints } from "./mcp-hosted-marker.mjs";
10
10
  import { createMcpChannelTransport, mcpMessageNotSent } from "./mcp-channel.mjs";
11
11
  import {
@@ -251,12 +251,9 @@ const createHostedMcpConnections = (args) => {
251
251
  name: endpoint.name
252
252
  };
253
253
  try {
254
- local[endpoint.name] = await withClient(
255
- serverKeyOf(server),
256
- async () => endpoint,
257
- toolsOf
258
- );
259
- localCatalogs.set(endpoint.name, local[endpoint.name]);
254
+ const tools = await withClient(serverKeyOf(server), async () => endpoint, toolsOf);
255
+ local[endpoint.name] = tools;
256
+ localCatalogs.set(endpoint.name, tools);
260
257
  } catch (cause) {
261
258
  if (closed) throw cause;
262
259
  unknownLocalCatalogs.add(endpoint.name);
@@ -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 \"../manifest.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 local[endpoint.name] = await withClient(\n serverKeyOf(server),\n async () => endpoint,\n toolsOf,\n );\n localCatalogs.set(endpoint.name, local[endpoint.name]);\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,2BAA2B;AAEjC,MAAM,oBAA4C,EAAE,aAAa,MAAM,UAAU,KAAK;AAY7F,MAAM,eAAe,CAAC,UAA0B,MAAM,QAAQ,mBAAmB,GAAG;AAM7E,MAAM,cAAc,CAAC,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AS,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 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;AASL,MAAM,2BAA2B;AAE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BAAM,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;",
6
6
  "names": ["SandboxHostedServerKind"]
7
7
  }
@@ -1,7 +1,9 @@
1
1
  import type { FetchLike } from '@modelcontextprotocol/client';
2
2
  import { type CallToolResult } from '@modelcontextprotocol/server';
3
3
  import type { JsonObject } from "../json.mjs";
4
- import { SandboxAccess, ToolApproval, type ToolDescriptorIface } from "../manifest.mjs";
4
+ import { ToolApprovalMode as ToolApproval } from "../document.mjs";
5
+ import type { ToolDescriptorIface } from "../tool-descriptor.mjs";
6
+ import { type SandboxGrantIface } from "./grant.mjs";
5
7
  import { SandboxShellMode } from "./mcp-shell.mjs";
6
8
  import { SandboxCapability, type NetworkSandboxSessionIface, type SandboxMcpCatalogIface } from "./types.mjs";
7
9
  export { COMPUTER_USE_SERVER_NAME, SandboxHostedServerKind, withHostedMcpEndpoints, type SandboxHostedServer, } from "./mcp-hosted.mjs";
@@ -37,7 +39,7 @@ export type SandboxMcpScope = {
37
39
  export declare const SANDBOX_FILE_RESOURCE_SCHEME = "sandbox-file";
38
40
  export interface SandboxMcpDescriptorOptionsIface {
39
41
  capabilities: readonly SandboxCapability[];
40
- access?: SandboxAccess;
42
+ grant?: SandboxGrantIface;
41
43
  lifecycle?: boolean;
42
44
  catalog?: SandboxMcpCatalogIface;
43
45
  scope?: SandboxMcpScope;
@@ -11,7 +11,9 @@ import {
11
11
  workspaceEgressRequestSchema,
12
12
  workspaceEgressStatusSchema
13
13
  } from "@finalai/agent-protocol/device-egress";
14
- import { SandboxAccess, ToolApproval } from "../manifest.mjs";
14
+ import { Capability, FilesAccess, ScreenAccess, ShellAccess } from "@finalai/agent-protocol";
15
+ import { ToolApprovalMode as ToolApproval } from "../document.mjs";
16
+ import { FULL_SANDBOX_GRANT, grantAllows } from "./grant.mjs";
15
17
  import { bytesToBase64, utf8Decode } from "./bytes.mjs";
16
18
  import {
17
19
  createHostedMcpConnections,
@@ -328,12 +330,18 @@ const BUILT_IN_TOOLS = [
328
330
  })
329
331
  ];
330
332
  const scopeOf = (options) => options.scope ?? { kind: "all" /* All */ };
333
+ const grantOf = (options) => options.grant ?? FULL_SANDBOX_GRANT;
334
+ const grantAllowsSpec = (grant, spec) => {
335
+ if (spec.capability === SandboxCapability.Files)
336
+ return grantAllows(grant, Capability.Files, spec.write ? FilesAccess.Write : FilesAccess.Read);
337
+ return grantAllows(grant, Capability.Shell, ShellAccess.Execute);
338
+ };
331
339
  const hostedServersOf = (options) => {
332
- if (options.access === SandboxAccess.Read) return { computerUse: false, localMcp: false };
340
+ const grant = grantOf(options);
333
341
  const capabilities = new Set(options.capabilities);
334
342
  const scope = scopeOf(options);
335
- const computerUse = capabilities.has(SandboxCapability.ComputerUse) && scope.kind !== "localServer" /* LocalServer */;
336
- const localMcp = capabilities.has(SandboxCapability.LocalMcp) && scope.kind !== "computerUse" /* ComputerUse */;
343
+ const computerUse = capabilities.has(SandboxCapability.ComputerUse) && scope.kind !== "localServer" /* LocalServer */ && grantAllows(grant, Capability.ComputerUse, ScreenAccess.Control);
344
+ const localMcp = capabilities.has(SandboxCapability.LocalMcp) && scope.kind !== "computerUse" /* ComputerUse */ && grantAllows(grant, Capability.Shell, ShellAccess.Execute);
337
345
  return scope.kind === "localServer" /* LocalServer */ ? { computerUse, localMcp, localServer: scope.server } : { computerUse, localMcp };
338
346
  };
339
347
  const hostedSpec = (hosted) => {
@@ -351,9 +359,8 @@ const toolSpecs = (options) => {
351
359
  const builtIn = scopeOf(options).kind === "all" /* All */ ? BUILT_IN_TOOLS.filter(
352
360
  (spec) => capabilities.has(spec.capability) && (spec.capability !== SandboxCapability.Egress || options.lifecycle === true)
353
361
  ) : [];
354
- const visible = options.access === SandboxAccess.Read ? builtIn.filter((spec) => !spec.write) : options.access === SandboxAccess.Execute ? builtIn.filter(
355
- (spec) => !spec.write || ![SandboxCapability.Files, SandboxCapability.Egress].includes(spec.capability)
356
- ) : builtIn;
362
+ const grant = grantOf(options);
363
+ const visible = builtIn.filter((spec) => grantAllowsSpec(grant, spec));
357
364
  const hosted = hostedTools({
358
365
  catalog: options.catalog ?? EMPTY_MCP_CATALOG,
359
366
  ...hostedServersOf(options),