@finalai/agent-provider 0.2.2 → 0.4.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 (60) hide show
  1. package/README.md +61 -0
  2. package/dist/modules/sandbox/client.mjs +3 -0
  3. package/dist/modules/sandbox/client.mjs.map +2 -2
  4. package/dist/modules/sandbox/confined-files.d.mts +2 -2
  5. package/dist/modules/sandbox/confined-files.mjs +5 -2
  6. package/dist/modules/sandbox/confined-files.mjs.map +2 -2
  7. package/dist/modules/sandbox/execution-guard.d.mts +36 -0
  8. package/dist/modules/sandbox/execution-guard.mjs +322 -0
  9. package/dist/modules/sandbox/execution-guard.mjs.map +7 -0
  10. package/dist/modules/sandbox/file-kind.d.mts +6 -0
  11. package/dist/modules/sandbox/file-kind.mjs +11 -0
  12. package/dist/modules/sandbox/file-kind.mjs.map +7 -0
  13. package/dist/modules/sandbox/file-schemas.d.mts +15 -0
  14. package/dist/modules/sandbox/file-schemas.mjs +22 -0
  15. package/dist/modules/sandbox/file-schemas.mjs.map +7 -0
  16. package/dist/modules/sandbox/handle.d.mts +15 -0
  17. package/dist/modules/sandbox/handle.mjs +47 -0
  18. package/dist/modules/sandbox/handle.mjs.map +7 -0
  19. package/dist/modules/sandbox/index.d.mts +8 -0
  20. package/dist/modules/sandbox/index.mjs +30 -1
  21. package/dist/modules/sandbox/index.mjs.map +2 -2
  22. package/dist/modules/sandbox/mcp-channel.d.mts +8 -1
  23. package/dist/modules/sandbox/mcp-channel.mjs +217 -15
  24. package/dist/modules/sandbox/mcp-channel.mjs.map +3 -3
  25. package/dist/modules/sandbox/mcp-hosted-marker.d.mts +3 -0
  26. package/dist/modules/sandbox/mcp-hosted-marker.mjs +10 -0
  27. package/dist/modules/sandbox/mcp-hosted-marker.mjs.map +7 -0
  28. package/dist/modules/sandbox/mcp-hosted.d.mts +6 -1
  29. package/dist/modules/sandbox/mcp-hosted.mjs +127 -41
  30. package/dist/modules/sandbox/mcp-hosted.mjs.map +2 -2
  31. package/dist/modules/sandbox/mcp-shell.mjs +14 -4
  32. package/dist/modules/sandbox/mcp-shell.mjs.map +2 -2
  33. package/dist/modules/sandbox/mcp.d.mts +5 -2
  34. package/dist/modules/sandbox/mcp.mjs +102 -27
  35. package/dist/modules/sandbox/mcp.mjs.map +2 -2
  36. package/dist/modules/sandbox/networking.d.mts +73 -0
  37. package/dist/modules/sandbox/networking.mjs +149 -0
  38. package/dist/modules/sandbox/networking.mjs.map +7 -0
  39. package/dist/modules/sandbox/overrides.d.mts +2 -0
  40. package/dist/modules/sandbox/overrides.mjs +44 -0
  41. package/dist/modules/sandbox/overrides.mjs.map +7 -0
  42. package/dist/modules/sandbox/server.d.mts +1 -0
  43. package/dist/modules/sandbox/server.mjs +38 -2
  44. package/dist/modules/sandbox/server.mjs.map +2 -2
  45. package/dist/modules/sandbox/testing.d.mts +1 -0
  46. package/dist/modules/sandbox/testing.mjs +1 -0
  47. package/dist/modules/sandbox/testing.mjs.map +2 -2
  48. package/dist/modules/sandbox/tool-policy.d.mts +5 -0
  49. package/dist/modules/sandbox/tool-policy.mjs +62 -0
  50. package/dist/modules/sandbox/tool-policy.mjs.map +7 -0
  51. package/dist/modules/sandbox/types.d.mts +17 -16
  52. package/dist/modules/sandbox/types.mjs +54 -23
  53. package/dist/modules/sandbox/types.mjs.map +3 -3
  54. package/dist/modules/sandbox/wire.d.mts +23 -18
  55. package/dist/modules/sandbox/wire.mjs +21 -20
  56. package/dist/modules/sandbox/wire.mjs.map +3 -3
  57. package/dist/modules/sandbox/workspace-identity.d.mts +5 -0
  58. package/dist/modules/sandbox/workspace-identity.mjs +14 -0
  59. package/dist/modules/sandbox/workspace-identity.mjs.map +7 -0
  60. package/package.json +3 -3
@@ -1,10 +1,13 @@
1
1
  import {
2
2
  Client,
3
3
  ProtocolError,
4
+ SdkError,
5
+ SdkErrorCode,
4
6
  StreamableHTTPClientTransport
5
7
  } from "@modelcontextprotocol/client";
6
8
  import { toolDescriptorSchema } from "../manifest.mjs";
7
- import { createMcpChannelTransport } from "./mcp-channel.mjs";
9
+ import { markHostedMcpEndpoints } from "./mcp-hosted-marker.mjs";
10
+ import { createMcpChannelTransport, mcpMessageNotSent } from "./mcp-channel.mjs";
8
11
  import {
9
12
  isMcpChannelEndpoint,
10
13
  SandboxCapability
@@ -18,7 +21,14 @@ const COMPUTER_USE_SERVER_NAME = "computer-use";
18
21
  const EMPTY_MCP_CATALOG = { computerUse: null, localMcp: null };
19
22
  const toolNameSafe = (value) => value.replace(/[^A-Za-z0-9_-]/g, "_");
20
23
  const hostedTools = (args) => {
21
- const taken = new Set(args.taken);
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 : []]);
22
32
  const tools = [];
23
33
  const claim = (preferred, fallback) => {
24
34
  const name = taken.has(preferred) ? fallback : preferred;
@@ -65,19 +75,44 @@ const hostedTools = (args) => {
65
75
  const serverKeyOf = (server) => server.kind === "computerUse" /* ComputerUse */ ? "computer-use" : `local\0${server.name}`;
66
76
  const createHostedMcpConnections = (args) => {
67
77
  const clients = /* @__PURE__ */ new Map();
78
+ const unknownLocalCatalogs = /* @__PURE__ */ new Set();
79
+ const localCatalogs = /* @__PURE__ */ new Map();
80
+ const closedClients = /* @__PURE__ */ new WeakSet();
81
+ const instances = /* @__PURE__ */ new Set();
82
+ const active = /* @__PURE__ */ new Map();
83
+ const retired = /* @__PURE__ */ new WeakSet();
84
+ const lifetime = new AbortController();
85
+ let closed = false;
68
86
  const connect = async (endpoint) => {
87
+ if (closed) throw new Error("Hosted MCP connections are closed");
69
88
  const client = new Client({ name: args.name ?? "final-sandbox", version: args.version ?? "1" });
70
- if (isMcpChannelEndpoint(endpoint)) {
71
- await client.connect(createMcpChannelTransport({ channel: await endpoint.connect() }));
89
+ instances.add(client);
90
+ try {
91
+ if (isMcpChannelEndpoint(endpoint)) {
92
+ const channel = await endpoint.connect({ abortSignal: lifetime.signal });
93
+ if (closed) {
94
+ await channel.close();
95
+ throw new Error("Hosted MCP connections are closed");
96
+ }
97
+ await client.connect(createMcpChannelTransport({ channel, receiveWhileIdle: false }), {
98
+ signal: lifetime.signal
99
+ });
100
+ } else {
101
+ await client.connect(
102
+ new StreamableHTTPClientTransport(new URL(endpoint.url), {
103
+ requestInit: { headers: endpoint.headers },
104
+ fetch: args.fetch
105
+ }),
106
+ { signal: lifetime.signal }
107
+ );
108
+ }
109
+ if (closed) throw new Error("Hosted MCP connections are closed");
72
110
  return client;
111
+ } catch (cause) {
112
+ instances.delete(client);
113
+ await client.close().catch(() => void 0);
114
+ throw cause;
73
115
  }
74
- await client.connect(
75
- new StreamableHTTPClientTransport(new URL(endpoint.url), {
76
- requestInit: { headers: endpoint.headers },
77
- fetch: args.fetch
78
- })
79
- );
80
- return client;
81
116
  };
82
117
  const endpointOf = async (sandbox, server) => {
83
118
  if (server.kind === "computerUse" /* ComputerUse */) {
@@ -89,15 +124,18 @@ const createHostedMcpConnections = (args) => {
89
124
  if (found == null) throw new Error(`this sandbox has no local MCP server ${server.name}`);
90
125
  return found;
91
126
  };
92
- const forget = (key) => {
93
- const client = clients.get(key);
94
- clients.delete(key);
95
- void client?.then((connected) => connected.close()).catch(() => void 0);
96
- };
97
127
  const clientFor = (key, endpoint) => {
128
+ if (closed) return Promise.reject(new Error("Hosted MCP connections are closed"));
98
129
  const existing = clients.get(key);
99
130
  if (existing != null) return existing;
100
- const connecting = endpoint().then(connect);
131
+ const connecting = endpoint().then(connect).then((client) => {
132
+ client.onclose = () => {
133
+ closedClients.add(client);
134
+ instances.delete(client);
135
+ if (clients.get(key) === connecting) clients.delete(key);
136
+ };
137
+ return client;
138
+ });
101
139
  clients.set(key, connecting);
102
140
  connecting.catch(() => {
103
141
  if (clients.get(key) === connecting) clients.delete(key);
@@ -106,12 +144,38 @@ const createHostedMcpConnections = (args) => {
106
144
  };
107
145
  const withClient = async (key, endpoint, work, retry = true) => {
108
146
  for (let attempt = 0; ; attempt += 1) {
147
+ const connecting = clientFor(key, endpoint);
148
+ active.set(connecting, (active.get(connecting) ?? 0) + 1);
149
+ let connected = null;
109
150
  try {
110
- return await work(await clientFor(key, endpoint));
151
+ connected = await connecting;
152
+ return await work(connected);
111
153
  } catch (error) {
112
- if (error instanceof ProtocolError) throw error;
113
- forget(key);
154
+ if (error instanceof ProtocolError && (connected == null || !closedClients.has(connected)))
155
+ throw error;
156
+ if (connected != null && error instanceof SdkError && (error.code === SdkErrorCode.RequestTimeout || error.code === SdkErrorCode.ConnectionClosed)) {
157
+ if (clients.get(key) === connecting) clients.delete(key);
158
+ retired.add(connected);
159
+ if (error.code === SdkErrorCode.ConnectionClosed && attempt === 0 && (retry || mcpMessageNotSent in error && error[mcpMessageNotSent] === true))
160
+ continue;
161
+ throw error;
162
+ }
163
+ if (connected != null && clients.get(key) === connecting) {
164
+ clients.delete(key);
165
+ retired.add(connected);
166
+ if (!retry || attempt > 0) throw error;
167
+ continue;
168
+ }
169
+ if (clients.get(key) === connecting) clients.delete(key);
114
170
  if (!retry || attempt > 0) throw error;
171
+ } finally {
172
+ const remaining = (active.get(connecting) ?? 1) - 1;
173
+ if (remaining > 0) active.set(connecting, remaining);
174
+ else {
175
+ active.delete(connecting);
176
+ if (connected != null && retired.has(connected))
177
+ void connected.close().catch(() => void 0);
178
+ }
115
179
  }
116
180
  }
117
181
  };
@@ -119,7 +183,9 @@ const createHostedMcpConnections = (args) => {
119
183
  const tools = [];
120
184
  let cursor;
121
185
  do {
122
- const page = await client.listTools(cursor == null ? void 0 : { cursor });
186
+ const page = await client.listTools(cursor == null ? void 0 : { cursor }, {
187
+ cacheMode: "refresh"
188
+ });
123
189
  for (const tool of page.tools) {
124
190
  const parsed = toolDescriptorSchema.safeParse(
125
191
  JSON.parse(
@@ -139,19 +205,25 @@ const createHostedMcpConnections = (args) => {
139
205
  return tools;
140
206
  };
141
207
  return {
142
- call: async (server, tool, input) => withClient(
143
- serverKeyOf(server),
144
- async () => endpointOf(await args.getSandbox(), server),
145
- async (client) => {
146
- const result = await client.callTool({ name: tool, arguments: input });
147
- const proxied = { content: result.content };
148
- if (result.structuredContent != null)
149
- proxied.structuredContent = result.structuredContent;
150
- if (result.isError === true) proxied.isError = true;
151
- return proxied;
152
- },
153
- false
154
- ),
208
+ call: async (server, tool, input, options) => {
209
+ options?.signal?.throwIfAborted();
210
+ return withClient(
211
+ serverKeyOf(server),
212
+ async () => endpointOf(await args.getSandbox(), server),
213
+ async (client) => {
214
+ const result = await client.callTool(
215
+ { name: tool, arguments: input },
216
+ { signal: options?.signal }
217
+ );
218
+ const proxied = { content: result.content };
219
+ if (result.structuredContent != null)
220
+ proxied.structuredContent = result.structuredContent;
221
+ if (result.isError === true) proxied.isError = true;
222
+ return proxied;
223
+ },
224
+ false
225
+ );
226
+ },
155
227
  tools: async (server) => withClient(
156
228
  serverKeyOf(server),
157
229
  async () => endpointOf(await args.getSandbox(), server),
@@ -169,7 +241,11 @@ const createHostedMcpConnections = (args) => {
169
241
  }
170
242
  if (needed.localMcp && sandbox.localMcp != null) {
171
243
  const local = {};
172
- for (const endpoint of await sandbox.localMcp()) {
244
+ const endpoints = await sandbox.localMcp();
245
+ const names = new Set(endpoints.map((endpoint) => endpoint.name));
246
+ for (const name of localCatalogs.keys()) if (!names.has(name)) localCatalogs.delete(name);
247
+ unknownLocalCatalogs.clear();
248
+ for (const endpoint of endpoints) {
173
249
  const server = {
174
250
  kind: "local" /* Local */,
175
251
  name: endpoint.name
@@ -180,25 +256,35 @@ const createHostedMcpConnections = (args) => {
180
256
  async () => endpoint,
181
257
  toolsOf
182
258
  );
183
- } catch {
184
- local[endpoint.name] = [];
259
+ localCatalogs.set(endpoint.name, local[endpoint.name]);
260
+ } catch (cause) {
261
+ if (closed) throw cause;
262
+ unknownLocalCatalogs.add(endpoint.name);
263
+ const previous = localCatalogs.get(endpoint.name) ?? args.catalog?.().localMcp?.[endpoint.name];
264
+ if (previous != null) local[endpoint.name] = previous;
185
265
  }
186
266
  }
187
267
  learned.localMcp = local;
268
+ learned.localMcpIncomplete = unknownLocalCatalogs.size > 0;
188
269
  }
270
+ if (closed) throw new Error("Hosted MCP connections are closed");
189
271
  return learned;
190
272
  },
191
273
  close: async () => {
192
- const open = [...clients.values()];
274
+ closed = true;
275
+ lifetime.abort(new Error("Hosted MCP connections are closed"));
193
276
  clients.clear();
194
- await Promise.all(
195
- open.map((client) => client.then((connected) => connected.close()).catch(() => void 0))
196
- );
277
+ unknownLocalCatalogs.clear();
278
+ localCatalogs.clear();
279
+ const open = [...instances];
280
+ instances.clear();
281
+ await Promise.all(open.map((client) => client.close().catch(() => void 0)));
197
282
  }
198
283
  };
199
284
  };
200
285
  const withHostedMcpEndpoints = (sandbox, endpointFor) => {
201
286
  const addressed = { ...sandbox };
287
+ markHostedMcpEndpoints(addressed);
202
288
  if (sandbox.computerUse != null) {
203
289
  addressed.computerUse = async () => endpointFor({ kind: "computerUse" /* ComputerUse */ });
204
290
  }
@@ -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 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 { createMcpChannelTransport } 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 HostedMcpConnectionsIface {\n call(server: SandboxHostedServer, tool: string, input: JsonObject): 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}): HostedMcpConnectionsIface => {\n const clients = new Map<string, Promise<Client>>();\n\n const connect = async (endpoint: SandboxMcpEndpoint): Promise<Client> => {\n const client = new Client({ name: args.name ?? 'final-sandbox', version: args.version ?? '1' });\n if (isMcpChannelEndpoint(endpoint)) {\n await client.connect(createMcpChannelTransport({ channel: await endpoint.connect() }));\n return client;\n }\n await client.connect(\n new StreamableHTTPClientTransport(new URL(endpoint.url), {\n requestInit: { headers: endpoint.headers },\n fetch: args.fetch,\n }),\n );\n return client;\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 forget = (key: string) => {\n const client = clients.get(key);\n clients.delete(key);\n void client?.then((connected) => connected.close()).catch(() => undefined);\n };\n\n const clientFor = (key: string, endpoint: () => Promise<SandboxMcpEndpoint>): Promise<Client> => {\n const existing = clients.get(key);\n if (existing != null) return existing;\n const connecting = endpoint().then(connect);\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 try {\n return await work(await clientFor(key, endpoint));\n } catch (error) {\n if (error instanceof ProtocolError) throw error;\n forget(key);\n if (!retry || attempt > 0) throw error;\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 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) =>\n withClient(\n serverKeyOf(server),\n async () => endpointOf(await args.getSandbox(), server),\n async (client) => {\n const result = await client.callTool({ name: tool, arguments: input });\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 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 for (const endpoint of await sandbox.localMcp()) {\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 } catch {\n // A local server that fails to start lists nothing; the rest still do.\n local[endpoint.name] = [];\n }\n }\n learned.localMcp = local;\n }\n return learned;\n },\n close: async () => {\n const open = [...clients.values()];\n clients.clear();\n await Promise.all(\n open.map((client) => client.then((connected) => connected.close()).catch(() => undefined)),\n );\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 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.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\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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AAY,EAAE,MAAM,qBAA+B,MAAM,SAAS,KAAK,CAAC;AAAA,IAC1E;AAAA,EACJ;AACA,SAAO;AACT;",
6
6
  "names": ["SandboxHostedServerKind"]
7
7
  }
@@ -97,8 +97,10 @@ printf '\\n%s\\n' '${sentinel}' >&2
97
97
  shell.stderr = "";
98
98
  try {
99
99
  await shell.process.write(script);
100
- } catch {
101
- return null;
100
+ } catch (cause) {
101
+ if (shell.exited) return null;
102
+ await shell.process.kill().catch(() => void 0);
103
+ throw cause;
102
104
  }
103
105
  const stdoutMarker = new RegExp(`\\n${sentinel} (\\d+)\\n`);
104
106
  const stderrMarker = `
@@ -137,10 +139,15 @@ ${sentinel}
137
139
  try {
138
140
  live = await start(sandbox);
139
141
  } catch {
140
- mode = "per-command" /* PerCommand */;
141
142
  return runOnce(sandbox, run);
142
143
  }
143
- const probe = await exchange(live, { command: "true", timeoutMs: STARTUP_TIMEOUT_MS });
144
+ let probe;
145
+ try {
146
+ probe = await exchange(live, { command: "true", timeoutMs: STARTUP_TIMEOUT_MS });
147
+ } catch (cause) {
148
+ live = null;
149
+ throw cause;
150
+ }
144
151
  if (probe == null || "timedOut" in probe) {
145
152
  await live.process.kill().catch(() => void 0);
146
153
  live = null;
@@ -157,6 +164,9 @@ ${sentinel}
157
164
  let result;
158
165
  try {
159
166
  result = await exchange(shell, run);
167
+ } catch (cause) {
168
+ live = null;
169
+ throw cause;
160
170
  } finally {
161
171
  run.signal?.removeEventListener("abort", abort);
162
172
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/sandbox/mcp-shell.ts"],
4
- "sourcesContent": ["import { bytesToBase64, utf8Encode } from \"./bytes.mjs\";\nimport { shellQuote } from \"./paths.mjs\";\nimport type {\n NetworkSandboxSessionIface,\n SandboxProcessIface,\n SandboxRunResultIface,\n} from \"./types.mjs\";\n\n// A persistent bash per MCP projection, so `cd`, exported variables and shell\n// state survive between `run` calls and no command pays a fresh `bash -lc`. Commands run one at a time; each is sent base64\n// encoded and `eval`ed with stdin from /dev/null, then a random sentinel line\n// carrying the exit status marks the end of its stdout and stderr. A command\n// that exits the shell ends it; the next command starts a new one. Sandboxes\n// without bash fall back to one `run` per command.\n\nexport enum SandboxShellMode {\n Persistent = 'persistent',\n PerCommand = 'per-command',\n}\n\nexport interface ShellRunArgsIface {\n command: string;\n cwd?: string;\n env?: Record<string, string>;\n timeoutMs?: number;\n signal?: AbortSignal;\n}\n\nexport interface SandboxShellIface {\n run(args: ShellRunArgsIface): Promise<SandboxRunResultIface>;\n close(): Promise<void>;\n // Whether the persistent shell is in use (false after a fallback).\n persistent(): boolean;\n}\n\nconst STARTUP_TIMEOUT_MS = 5_000;\nconst TIMEOUT_EXIT_CODE = 124;\nconst ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\ninterface LiveShellIface {\n process: SandboxProcessIface;\n stdout: string;\n stderr: string;\n exited: boolean;\n exitCode: number | null;\n changed: (() => void) | null;\n}\n\nconst randomSentinel = () => `__FINAL_SHELL_${crypto.randomUUID().replace(/-/g, '')}__`;\n\nconst pumpText = async (stream: ReadableStream<Uint8Array>, append: (text: string) => void) => {\n const decoder = new TextDecoder();\n const reader = stream.getReader();\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n append(decoder.decode(value, { stream: true }));\n }\n } catch {\n // The process or connection went away; `exited` reports it.\n }\n};\n\nexport const createSandboxShell = (args: {\n getSandbox: () => Promise<NetworkSandboxSessionIface>;\n mode?: SandboxShellMode;\n}): SandboxShellIface => {\n let mode = args.mode ?? SandboxShellMode.Persistent;\n let live: LiveShellIface | null = null;\n let queue: Promise<unknown> = Promise.resolve();\n\n const notify = (shell: LiveShellIface) => {\n const changed = shell.changed;\n shell.changed = null;\n changed?.();\n };\n\n const start = async (sandbox: NetworkSandboxSessionIface): Promise<LiveShellIface> => {\n const process = await sandbox.spawn({\n command: 'bash',\n args: ['--noprofile', '--norc'],\n cwd: sandbox.defaultWorkingDirectory,\n });\n const shell: LiveShellIface = {\n process,\n stdout: '',\n stderr: '',\n exited: false,\n exitCode: null,\n changed: null,\n };\n void pumpText(process.stdout, (text) => {\n shell.stdout += text;\n notify(shell);\n });\n void pumpText(process.stderr, (text) => {\n shell.stderr += text;\n notify(shell);\n });\n process.wait().then(\n (result) => {\n shell.exited = true;\n shell.exitCode = result.exitCode;\n notify(shell);\n },\n () => {\n shell.exited = true;\n notify(shell);\n },\n );\n return shell;\n };\n\n const waitFor = (\n shell: LiveShellIface,\n done: () => boolean,\n deadline: number | null,\n ): Promise<boolean> =>\n new Promise<boolean>((resolve) => {\n const timer =\n deadline == null\n ? null\n : setTimeout(() => resolve(done()), Math.max(0, deadline - Date.now()));\n const check = () => {\n if (done() || shell.exited) {\n if (timer != null) clearTimeout(timer);\n resolve(done());\n return;\n }\n shell.changed = check;\n };\n check();\n });\n\n // Sends one framed command and collects its output. Returns null when the\n // shell died before reporting (so the caller can fall back or restart).\n const exchange = async (\n shell: LiveShellIface,\n run: ShellRunArgsIface,\n ): Promise<SandboxRunResultIface | { timedOut: true } | null> => {\n const sentinel = randomSentinel();\n const exports = Object.entries(run.env ?? {})\n .filter(([key]) => ENV_NAME.test(key))\n .map(([key, value]) => `export ${key}=${shellQuote(value)}\\n`)\n .join('');\n const cd = run.cwd == null ? '' : `cd -- ${shellQuote(run.cwd)} && `;\n // Per-command variables must not leak into later commands: use a subshell.\n const inner = `${cd}{\\n${run.command}\\n}`;\n const body = exports === '' ? inner : `(\\n${exports}${inner}\\n)`;\n const script =\n `eval \"$(printf '%s' '${bytesToBase64(utf8Encode(body))}' | base64 -d)\" < /dev/null\\n` +\n `__final_status=$?\\n` +\n `printf '\\\\n%s %d\\\\n' '${sentinel}' \"$__final_status\"\\n` +\n `printf '\\\\n%s\\\\n' '${sentinel}' >&2\\n`;\n shell.stdout = '';\n shell.stderr = '';\n try {\n await shell.process.write(script);\n } catch {\n // stdin is gone: the shell exited (or never ran).\n return null;\n }\n const stdoutMarker = new RegExp(`\\\\n${sentinel} (\\\\d+)\\\\n`);\n const stderrMarker = `\\n${sentinel}\\n`;\n const finished = () => stdoutMarker.test(shell.stdout) && shell.stderr.includes(stderrMarker);\n const deadline = run.timeoutMs == null ? null : Date.now() + run.timeoutMs;\n const ok = await waitFor(shell, finished, deadline);\n if (!ok) {\n if (!shell.exited) return { timedOut: true };\n return null;\n }\n const match = stdoutMarker.exec(shell.stdout);\n const stdoutEnd = match?.index ?? shell.stdout.length;\n const stderrEnd = shell.stderr.indexOf(stderrMarker);\n return {\n exitCode: Number(match?.[1] ?? '1'),\n stdout: shell.stdout.slice(0, stdoutEnd),\n stderr: shell.stderr.slice(0, stderrEnd < 0 ? shell.stderr.length : stderrEnd),\n };\n };\n\n const runOnce = async (sandbox: NetworkSandboxSessionIface, run: ShellRunArgsIface) =>\n sandbox.run({\n command: run.command,\n shell: true,\n cwd: run.cwd,\n env: run.env,\n timeoutMs: run.timeoutMs,\n abortSignal: run.signal,\n });\n\n const runPersistent = async (run: ShellRunArgsIface): Promise<SandboxRunResultIface> => {\n run.signal?.throwIfAborted();\n const sandbox = await args.getSandbox();\n if (mode === SandboxShellMode.PerCommand) return runOnce(sandbox, run);\n const fresh = live == null || live.exited;\n if (fresh) {\n try {\n live = await start(sandbox);\n } catch {\n mode = SandboxShellMode.PerCommand;\n return runOnce(sandbox, run);\n }\n // Probe once so a sandbox without bash falls back instead of hanging.\n const probe = await exchange(live, { command: 'true', timeoutMs: STARTUP_TIMEOUT_MS });\n if (probe == null || 'timedOut' in probe) {\n await live.process.kill().catch(() => undefined);\n live = null;\n mode = SandboxShellMode.PerCommand;\n return runOnce(sandbox, run);\n }\n }\n const shell = live;\n if (shell == null) return runOnce(sandbox, run);\n const abort = (): void => {\n void shell.process.kill().catch(() => undefined);\n };\n run.signal?.addEventListener('abort', abort, { once: true });\n let result: Awaited<ReturnType<typeof exchange>>;\n try {\n result = await exchange(shell, run);\n } finally {\n run.signal?.removeEventListener('abort', abort);\n }\n if (run.signal?.aborted === true) {\n live = null;\n run.signal.throwIfAborted();\n }\n if (result == null) {\n // The command ended the shell (`exit`); report what it printed.\n live = null;\n return { exitCode: shell.exitCode ?? 1, stdout: shell.stdout, stderr: shell.stderr };\n }\n if ('timedOut' in result) {\n const partial = { stdout: shell.stdout, stderr: shell.stderr };\n await shell.process.kill().catch(() => undefined);\n live = null;\n return {\n exitCode: TIMEOUT_EXIT_CODE,\n stdout: partial.stdout,\n stderr: `${partial.stderr}\\n[timed out after ${run.timeoutMs ?? 0} ms; the shell was restarted]`,\n };\n }\n return result;\n };\n\n return {\n run: (run) => {\n const next = queue.then(\n () => runPersistent(run),\n () => runPersistent(run),\n );\n queue = next.catch(() => undefined);\n return next;\n },\n close: async () => {\n const shell = live;\n live = null;\n await shell?.process.kill().catch(() => undefined);\n },\n persistent: () => mode === SandboxShellMode.Persistent && live != null,\n };\n};\n"],
5
- "mappings": "AAAA,SAAS,eAAe,kBAAkB;AAC1C,SAAS,kBAAkB;AAcpB,IAAK,mBAAL,kBAAKA,sBAAL;AACL,EAAAA,kBAAA,gBAAa;AACb,EAAAA,kBAAA,gBAAa;AAFH,SAAAA;AAAA,GAAA;AAoBZ,MAAM,qBAAqB;AAC3B,MAAM,oBAAoB;AAC1B,MAAM,WAAW;AAWjB,MAAM,iBAAiB,MAAM,iBAAiB,OAAO,WAAW,EAAE,QAAQ,MAAM,EAAE,CAAC;AAEnF,MAAM,WAAW,OAAO,QAAoC,WAAmC;AAC7F,QAAM,UAAU,IAAI,YAAY;AAChC,QAAM,SAAS,OAAO,UAAU;AAChC,MAAI;AACF,eAAS;AACP,YAAM,EAAE,MAAM,MAAM,IAAI,MAAM,OAAO,KAAK;AAC1C,UAAI,KAAM;AACV,aAAO,QAAQ,OAAO,OAAO,EAAE,QAAQ,KAAK,CAAC,CAAC;AAAA,IAChD;AAAA,EACF,QAAQ;AAAA,EAER;AACF;AAEO,MAAM,qBAAqB,CAAC,SAGV;AACvB,MAAI,OAAO,KAAK,QAAQ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AAI;AACJ,QAAI;AACF,eAAS,MAAM,SAAS,OAAO,GAAG;AAAA,IACpC,UAAE;AACA,UAAI,QAAQ,oBAAoB,SAAS,KAAK;AAAA,IAChD;AACA,QAAI,IAAI,QAAQ,YAAY,MAAM;AAChC,aAAO;AACP,UAAI,OAAO,eAAe;AAAA,IAC5B;AACA,QAAI,UAAU,MAAM;AAElB,aAAO;AACP,aAAO,EAAE,UAAU,MAAM,YAAY,GAAG,QAAQ,MAAM,QAAQ,QAAQ,MAAM,OAAO;AAAA,IACrF;AACA,QAAI,cAAc,QAAQ;AACxB,YAAM,UAAU,EAAE,QAAQ,MAAM,QAAQ,QAAQ,MAAM,OAAO;AAC7D,YAAM,MAAM,QAAQ,KAAK,EAAE,MAAM,MAAM,MAAS;AAChD,aAAO;AACP,aAAO;AAAA,QACL,UAAU;AAAA,QACV,QAAQ,QAAQ;AAAA,QAChB,QAAQ,GAAG,QAAQ,MAAM;AAAA,mBAAsB,IAAI,aAAa,CAAC;AAAA,MACnE;AAAA,IACF;AACA,WAAO;AAAA,EACT;AAEA,SAAO;AAAA,IACL,KAAK,CAAC,QAAQ;AACZ,YAAM,OAAO,MAAM;AAAA,QACjB,MAAM,cAAc,GAAG;AAAA,QACvB,MAAM,cAAc,GAAG;AAAA,MACzB;AACA,cAAQ,KAAK,MAAM,MAAM,MAAS;AAClC,aAAO;AAAA,IACT;AAAA,IACA,OAAO,YAAY;AACjB,YAAM,QAAQ;AACd,aAAO;AACP,YAAM,OAAO,QAAQ,KAAK,EAAE,MAAM,MAAM,MAAS;AAAA,IACnD;AAAA,IACA,YAAY,MAAM,SAAS,iCAA+B,QAAQ;AAAA,EACpE;AACF;",
4
+ "sourcesContent": ["import { bytesToBase64, utf8Encode } from \"./bytes.mjs\";\nimport { shellQuote } from \"./paths.mjs\";\nimport type {\n NetworkSandboxSessionIface,\n SandboxProcessIface,\n SandboxRunResultIface,\n} from \"./types.mjs\";\n\n// A persistent bash per MCP projection, so `cd`, exported variables and shell\n// state survive between `run` calls and no command pays a fresh `bash -lc`. Commands run one at a time; each is sent base64\n// encoded and `eval`ed with stdin from /dev/null, then a random sentinel line\n// carrying the exit status marks the end of its stdout and stderr. A command\n// that exits the shell ends it; the next command starts a new one. Sandboxes\n// without bash fall back to one `run` per command.\n\nexport enum SandboxShellMode {\n Persistent = 'persistent',\n PerCommand = 'per-command',\n}\n\nexport interface ShellRunArgsIface {\n command: string;\n cwd?: string;\n env?: Record<string, string>;\n timeoutMs?: number;\n signal?: AbortSignal;\n}\n\nexport interface SandboxShellIface {\n run(args: ShellRunArgsIface): Promise<SandboxRunResultIface>;\n close(): Promise<void>;\n // Whether the persistent shell is in use (false after a fallback).\n persistent(): boolean;\n}\n\nconst STARTUP_TIMEOUT_MS = 5_000;\nconst TIMEOUT_EXIT_CODE = 124;\nconst ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\ninterface LiveShellIface {\n process: SandboxProcessIface;\n stdout: string;\n stderr: string;\n exited: boolean;\n exitCode: number | null;\n changed: (() => void) | null;\n}\n\nconst randomSentinel = () => `__FINAL_SHELL_${crypto.randomUUID().replace(/-/g, '')}__`;\n\nconst pumpText = async (stream: ReadableStream<Uint8Array>, append: (text: string) => void) => {\n const decoder = new TextDecoder();\n const reader = stream.getReader();\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n append(decoder.decode(value, { stream: true }));\n }\n } catch {\n // The process or connection went away; `exited` reports it.\n }\n};\n\nexport const createSandboxShell = (args: {\n getSandbox: () => Promise<NetworkSandboxSessionIface>;\n mode?: SandboxShellMode;\n}): SandboxShellIface => {\n let mode = args.mode ?? SandboxShellMode.Persistent;\n let live: LiveShellIface | null = null;\n let queue: Promise<unknown> = Promise.resolve();\n\n const notify = (shell: LiveShellIface) => {\n const changed = shell.changed;\n shell.changed = null;\n changed?.();\n };\n\n const start = async (sandbox: NetworkSandboxSessionIface): Promise<LiveShellIface> => {\n const process = await sandbox.spawn({\n command: 'bash',\n args: ['--noprofile', '--norc'],\n cwd: sandbox.defaultWorkingDirectory,\n });\n const shell: LiveShellIface = {\n process,\n stdout: '',\n stderr: '',\n exited: false,\n exitCode: null,\n changed: null,\n };\n void pumpText(process.stdout, (text) => {\n shell.stdout += text;\n notify(shell);\n });\n void pumpText(process.stderr, (text) => {\n shell.stderr += text;\n notify(shell);\n });\n process.wait().then(\n (result) => {\n shell.exited = true;\n shell.exitCode = result.exitCode;\n notify(shell);\n },\n () => {\n shell.exited = true;\n notify(shell);\n },\n );\n return shell;\n };\n\n const waitFor = (\n shell: LiveShellIface,\n done: () => boolean,\n deadline: number | null,\n ): Promise<boolean> =>\n new Promise<boolean>((resolve) => {\n const timer =\n deadline == null\n ? null\n : setTimeout(() => resolve(done()), Math.max(0, deadline - Date.now()));\n const check = () => {\n if (done() || shell.exited) {\n if (timer != null) clearTimeout(timer);\n resolve(done());\n return;\n }\n shell.changed = check;\n };\n check();\n });\n\n // Sends one framed command and collects its output. Returns null when the\n // shell died before reporting (so the caller can fall back or restart).\n const exchange = async (\n shell: LiveShellIface,\n run: ShellRunArgsIface,\n ): Promise<SandboxRunResultIface | { timedOut: true } | null> => {\n const sentinel = randomSentinel();\n const exports = Object.entries(run.env ?? {})\n .filter(([key]) => ENV_NAME.test(key))\n .map(([key, value]) => `export ${key}=${shellQuote(value)}\\n`)\n .join('');\n const cd = run.cwd == null ? '' : `cd -- ${shellQuote(run.cwd)} && `;\n // Per-command variables must not leak into later commands: use a subshell.\n const inner = `${cd}{\\n${run.command}\\n}`;\n const body = exports === '' ? inner : `(\\n${exports}${inner}\\n)`;\n const script =\n `eval \"$(printf '%s' '${bytesToBase64(utf8Encode(body))}' | base64 -d)\" < /dev/null\\n` +\n `__final_status=$?\\n` +\n `printf '\\\\n%s %d\\\\n' '${sentinel}' \"$__final_status\"\\n` +\n `printf '\\\\n%s\\\\n' '${sentinel}' >&2\\n`;\n shell.stdout = '';\n shell.stderr = '';\n try {\n await shell.process.write(script);\n } catch (cause) {\n if (shell.exited) return null;\n await shell.process.kill().catch(() => undefined);\n throw cause;\n }\n const stdoutMarker = new RegExp(`\\\\n${sentinel} (\\\\d+)\\\\n`);\n const stderrMarker = `\\n${sentinel}\\n`;\n const finished = () => stdoutMarker.test(shell.stdout) && shell.stderr.includes(stderrMarker);\n const deadline = run.timeoutMs == null ? null : Date.now() + run.timeoutMs;\n const ok = await waitFor(shell, finished, deadline);\n if (!ok) {\n if (!shell.exited) return { timedOut: true };\n return null;\n }\n const match = stdoutMarker.exec(shell.stdout);\n const stdoutEnd = match?.index ?? shell.stdout.length;\n const stderrEnd = shell.stderr.indexOf(stderrMarker);\n return {\n exitCode: Number(match?.[1] ?? '1'),\n stdout: shell.stdout.slice(0, stdoutEnd),\n stderr: shell.stderr.slice(0, stderrEnd < 0 ? shell.stderr.length : stderrEnd),\n };\n };\n\n const runOnce = async (sandbox: NetworkSandboxSessionIface, run: ShellRunArgsIface) =>\n sandbox.run({\n command: run.command,\n shell: true,\n cwd: run.cwd,\n env: run.env,\n timeoutMs: run.timeoutMs,\n abortSignal: run.signal,\n });\n\n const runPersistent = async (run: ShellRunArgsIface): Promise<SandboxRunResultIface> => {\n run.signal?.throwIfAborted();\n const sandbox = await args.getSandbox();\n if (mode === SandboxShellMode.PerCommand) return runOnce(sandbox, run);\n const fresh = live == null || live.exited;\n if (fresh) {\n try {\n live = await start(sandbox);\n } catch {\n return runOnce(sandbox, run);\n }\n // Probe once so a sandbox without bash falls back instead of hanging.\n let probe: Awaited<ReturnType<typeof exchange>>;\n try {\n probe = await exchange(live, { command: 'true', timeoutMs: STARTUP_TIMEOUT_MS });\n } catch (cause) {\n live = null;\n throw cause;\n }\n if (probe == null || 'timedOut' in probe) {\n await live.process.kill().catch(() => undefined);\n live = null;\n mode = SandboxShellMode.PerCommand;\n return runOnce(sandbox, run);\n }\n }\n const shell = live;\n if (shell == null) return runOnce(sandbox, run);\n const abort = (): void => {\n void shell.process.kill().catch(() => undefined);\n };\n run.signal?.addEventListener('abort', abort, { once: true });\n let result: Awaited<ReturnType<typeof exchange>>;\n try {\n result = await exchange(shell, run);\n } catch (cause) {\n live = null;\n throw cause;\n } finally {\n run.signal?.removeEventListener('abort', abort);\n }\n if (run.signal?.aborted === true) {\n live = null;\n run.signal.throwIfAborted();\n }\n if (result == null) {\n // The command ended the shell (`exit`); report what it printed.\n live = null;\n return { exitCode: shell.exitCode ?? 1, stdout: shell.stdout, stderr: shell.stderr };\n }\n if ('timedOut' in result) {\n const partial = { stdout: shell.stdout, stderr: shell.stderr };\n await shell.process.kill().catch(() => undefined);\n live = null;\n return {\n exitCode: TIMEOUT_EXIT_CODE,\n stdout: partial.stdout,\n stderr: `${partial.stderr}\\n[timed out after ${run.timeoutMs ?? 0} ms; the shell was restarted]`,\n };\n }\n return result;\n };\n\n return {\n run: (run) => {\n const next = queue.then(\n () => runPersistent(run),\n () => runPersistent(run),\n );\n queue = next.catch(() => undefined);\n return next;\n },\n close: async () => {\n const shell = live;\n live = null;\n await shell?.process.kill().catch(() => undefined);\n },\n persistent: () => mode === SandboxShellMode.Persistent && live != null,\n };\n};\n"],
5
+ "mappings": "AAAA,SAAS,eAAe,kBAAkB;AAC1C,SAAS,kBAAkB;AAcpB,IAAK,mBAAL,kBAAKA,sBAAL;AACL,EAAAA,kBAAA,gBAAa;AACb,EAAAA,kBAAA,gBAAa;AAFH,SAAAA;AAAA,GAAA;AAoBZ,MAAM,qBAAqB;AAC3B,MAAM,oBAAoB;AAC1B,MAAM,WAAW;AAWjB,MAAM,iBAAiB,MAAM,iBAAiB,OAAO,WAAW,EAAE,QAAQ,MAAM,EAAE,CAAC;AAEnF,MAAM,WAAW,OAAO,QAAoC,WAAmC;AAC7F,QAAM,UAAU,IAAI,YAAY;AAChC,QAAM,SAAS,OAAO,UAAU;AAChC,MAAI;AACF,eAAS;AACP,YAAM,EAAE,MAAM,MAAM,IAAI,MAAM,OAAO,KAAK;AAC1C,UAAI,KAAM;AACV,aAAO,QAAQ,OAAO,OAAO,EAAE,QAAQ,KA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,YAAM,OAAO,QAAQ,KAAK,EAAE,MAAM,MAAM,MAAS;AAAA,IACnD;AAAA,IACA,YAAY,MAAM,SAAS,iCAA+B,QAAQ;AAAA,EACpE;AACF;",
6
6
  "names": ["SandboxShellMode"]
7
7
  }
@@ -19,7 +19,8 @@ export declare enum SandboxMcpTool {
19
19
  Stat = "stat",
20
20
  Grep = "grep",
21
21
  Glob = "glob",
22
- GetHost = "get_host"
22
+ GetHost = "get_host",
23
+ Egress = "egress"
23
24
  }
24
25
  export declare enum SandboxMcpScopeKind {
25
26
  All = "all",
@@ -37,11 +38,12 @@ export declare const SANDBOX_FILE_RESOURCE_SCHEME = "sandbox-file";
37
38
  export interface SandboxMcpDescriptorOptionsIface {
38
39
  capabilities: readonly SandboxCapability[];
39
40
  access?: SandboxAccess;
41
+ lifecycle?: boolean;
40
42
  catalog?: SandboxMcpCatalogIface;
41
43
  scope?: SandboxMcpScope;
42
44
  }
43
45
  export declare const sandboxMcpToolDescriptors: (options: SandboxMcpDescriptorOptionsIface) => ToolDescriptorIface[];
44
- export declare const sandboxMcpToolPolicyKeys: (options: SandboxMcpDescriptorOptionsIface, name: string) => string[] | null;
46
+ export declare const sandboxMcpToolPolicyKeys: (options: SandboxMcpDescriptorOptionsIface, name: string, input?: JsonObject) => string[] | null;
45
47
  export interface CreateSandboxMcpServerArgsIface extends SandboxMcpDescriptorOptionsIface {
46
48
  getSandbox: () => Promise<NetworkSandboxSessionIface>;
47
49
  toolPolicy?: Record<string, ToolApproval>;
@@ -77,6 +79,7 @@ export interface SandboxMcpServerIface {
77
79
  listTools(): ToolDescriptorIface[];
78
80
  refreshTools(): Promise<ToolDescriptorIface[]>;
79
81
  updateCatalog(catalog: SandboxMcpCatalogIface): void;
82
+ updateCapabilities(capabilities: readonly SandboxCapability[]): void;
80
83
  callTool(name: string, args: JsonObject, signal?: AbortSignal): Promise<CallToolResult>;
81
84
  close(): Promise<void>;
82
85
  }