@finalai/agent-provider 0.8.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.
- package/HOSTING.md +334 -245
- package/README.md +93 -14
- package/dist/modules/canonical-json.d.mts +4 -0
- package/dist/modules/canonical-json.mjs +33 -0
- package/dist/modules/canonical-json.mjs.map +7 -0
- package/dist/modules/channel.d.mts +9 -3
- package/dist/modules/channel.mjs.map +2 -2
- package/dist/modules/code-host/host.d.mts +10 -0
- package/dist/modules/code-host/host.mjs +88 -0
- package/dist/modules/code-host/host.mjs.map +7 -0
- package/dist/modules/code-host/in-process.d.mts +24 -0
- package/dist/modules/code-host/in-process.mjs +89 -0
- package/dist/modules/code-host/in-process.mjs.map +7 -0
- package/dist/modules/code-host/index.d.mts +4 -0
- package/dist/modules/code-host/index.mjs +5 -0
- package/dist/modules/code-host/index.mjs.map +7 -0
- package/dist/modules/code-host/serverless.d.mts +63 -0
- package/dist/modules/code-host/serverless.mjs +27 -0
- package/dist/modules/code-host/serverless.mjs.map +7 -0
- package/dist/modules/code-host/types.d.mts +152 -0
- package/dist/modules/code-host/types.mjs +85 -0
- package/dist/modules/code-host/types.mjs.map +7 -0
- package/dist/modules/conformance/agent.mjs +72 -6
- package/dist/modules/conformance/agent.mjs.map +2 -2
- package/dist/modules/conformance/harness-kit.d.mts +9 -2
- package/dist/modules/conformance/harness-kit.mjs +224 -63
- package/dist/modules/conformance/harness-kit.mjs.map +3 -3
- package/dist/modules/conformance/local-harness.d.mts +1 -4
- package/dist/modules/conformance/local-harness.mjs +21 -22
- package/dist/modules/conformance/local-harness.mjs.map +2 -2
- package/dist/modules/conformance/protocol.d.mts +1 -0
- package/dist/modules/conformance/protocol.mjs +2 -0
- package/dist/modules/conformance/protocol.mjs.map +2 -2
- package/dist/modules/conformance/sandbox-kit.d.mts +12 -4
- package/dist/modules/conformance/sandbox-kit.mjs +189 -103
- package/dist/modules/conformance/sandbox-kit.mjs.map +2 -2
- package/dist/modules/conformance/scripted-model/chat-completions.mjs +1 -0
- package/dist/modules/conformance/scripted-model/chat-completions.mjs.map +2 -2
- package/dist/modules/conformance/scripted-model/directives.d.mts +3 -0
- package/dist/modules/conformance/scripted-model/directives.mjs +26 -10
- package/dist/modules/conformance/scripted-model/directives.mjs.map +2 -2
- package/dist/modules/conformance/scripted-model/messages.mjs +1 -0
- package/dist/modules/conformance/scripted-model/messages.mjs.map +2 -2
- package/dist/modules/conformance/scripted-model/responses.mjs +2 -0
- package/dist/modules/conformance/scripted-model/responses.mjs.map +2 -2
- package/dist/modules/conformance/stdio.d.mts +21 -0
- package/dist/modules/conformance/stdio.mjs +158 -0
- package/dist/modules/conformance/stdio.mjs.map +7 -0
- package/dist/modules/credential-routes.d.mts +2 -0
- package/dist/modules/credential-routes.mjs +2 -0
- package/dist/modules/credential-routes.mjs.map +2 -2
- package/dist/modules/document.d.mts +376 -0
- package/dist/modules/document.mjs +208 -0
- package/dist/modules/document.mjs.map +7 -0
- package/dist/modules/harness-configuration.d.mts +16 -0
- package/dist/modules/harness-configuration.mjs +83 -0
- package/dist/modules/harness-configuration.mjs.map +7 -0
- package/dist/modules/harness-definition.d.mts +280 -0
- package/dist/modules/harness-definition.mjs +430 -0
- package/dist/modules/harness-definition.mjs.map +7 -0
- package/dist/modules/harness-provider.d.mts +197 -0
- package/dist/modules/harness-provider.mjs +108 -0
- package/dist/modules/harness-provider.mjs.map +7 -0
- package/dist/modules/harness-requirements.d.mts +19 -0
- package/dist/modules/harness-requirements.mjs +40 -0
- package/dist/modules/harness-requirements.mjs.map +7 -0
- package/dist/modules/harness-start.d.mts +33 -0
- package/dist/modules/harness-start.mjs +107 -0
- package/dist/modules/harness-start.mjs.map +7 -0
- package/dist/modules/harness.d.mts +84 -109
- package/dist/modules/harness.mjs +56 -111
- package/dist/modules/harness.mjs.map +3 -3
- package/dist/modules/identity.d.mts +1 -0
- package/dist/modules/identity.mjs +2 -0
- package/dist/modules/identity.mjs.map +7 -0
- package/dist/modules/index.d.mts +12 -6
- package/dist/modules/index.mjs +12 -6
- package/dist/modules/index.mjs.map +2 -2
- package/dist/modules/inference.d.mts +35 -0
- package/dist/modules/inference.mjs +74 -0
- package/dist/modules/inference.mjs.map +7 -0
- package/dist/modules/local-channel-context.mjs +3 -1
- package/dist/modules/local-channel-context.mjs.map +2 -2
- package/dist/modules/requirements-check.d.mts +30 -0
- package/dist/modules/requirements-check.mjs +164 -0
- package/dist/modules/requirements-check.mjs.map +7 -0
- package/dist/modules/room-surface.d.mts +0 -5
- package/dist/modules/room-surface.mjs.map +2 -2
- package/dist/modules/sandbox/client.d.mts +3 -0
- package/dist/modules/sandbox/client.mjs +101 -18
- package/dist/modules/sandbox/client.mjs.map +2 -2
- package/dist/modules/sandbox/grant.d.mts +78 -0
- package/dist/modules/sandbox/grant.mjs +134 -0
- package/dist/modules/sandbox/grant.mjs.map +7 -0
- package/dist/modules/sandbox/index.d.mts +3 -3
- package/dist/modules/sandbox/index.mjs +4 -5
- package/dist/modules/sandbox/index.mjs.map +2 -2
- package/dist/modules/sandbox/mcp-hosted.d.mts +1 -1
- package/dist/modules/sandbox/mcp-hosted.mjs +4 -7
- package/dist/modules/sandbox/mcp-hosted.mjs.map +2 -2
- package/dist/modules/sandbox/mcp.d.mts +4 -2
- package/dist/modules/sandbox/mcp.mjs +14 -7
- package/dist/modules/sandbox/mcp.mjs.map +2 -2
- package/dist/modules/sandbox/memory-sandbox.d.mts +2 -1
- package/dist/modules/sandbox/memory-sandbox.mjs +71 -41
- package/dist/modules/sandbox/memory-sandbox.mjs.map +2 -2
- package/dist/modules/sandbox/networking.d.mts +7 -7
- package/dist/modules/sandbox/networking.mjs +16 -9
- package/dist/modules/sandbox/networking.mjs.map +2 -2
- package/dist/modules/sandbox/remote/adapter.d.mts +30 -0
- package/dist/modules/sandbox/remote/adapter.mjs +381 -0
- package/dist/modules/sandbox/remote/adapter.mjs.map +7 -0
- package/dist/modules/sandbox/remote/errors.d.mts +10 -0
- package/dist/modules/sandbox/remote/errors.mjs +62 -0
- package/dist/modules/sandbox/remote/errors.mjs.map +7 -0
- package/dist/modules/sandbox/remote/index.d.mts +5 -0
- package/dist/modules/sandbox/remote/index.mjs +6 -0
- package/dist/modules/sandbox/remote/index.mjs.map +7 -0
- package/dist/modules/sandbox/remote/ndjson.d.mts +6 -0
- package/dist/modules/sandbox/remote/ndjson.mjs +80 -0
- package/dist/modules/sandbox/remote/ndjson.mjs.map +7 -0
- package/dist/modules/sandbox/remote/platform-api.d.mts +8 -0
- package/dist/modules/sandbox/remote/platform-api.mjs +15 -0
- package/dist/modules/sandbox/remote/platform-api.mjs.map +7 -0
- package/dist/modules/sandbox/remote/preamble.d.mts +7 -0
- package/dist/modules/sandbox/remote/preamble.mjs +51 -0
- package/dist/modules/sandbox/remote/preamble.mjs.map +7 -0
- package/dist/modules/sandbox/remote/serve.d.mts +34 -0
- package/dist/modules/sandbox/remote/serve.mjs +519 -0
- package/dist/modules/sandbox/remote/serve.mjs.map +7 -0
- package/dist/modules/sandbox/remote/testing.d.mts +34 -0
- package/dist/modules/sandbox/remote/testing.mjs +275 -0
- package/dist/modules/sandbox/remote/testing.mjs.map +7 -0
- package/dist/modules/sandbox/seeds.d.mts +2 -2
- package/dist/modules/sandbox/seeds.mjs +2 -2
- package/dist/modules/sandbox/seeds.mjs.map +2 -2
- package/dist/modules/sandbox/server.d.mts +4 -6
- package/dist/modules/sandbox/server.mjs +93 -49
- package/dist/modules/sandbox/server.mjs.map +2 -2
- package/dist/modules/sandbox/setup/apply.d.mts +41 -0
- package/dist/modules/sandbox/setup/apply.mjs +204 -0
- package/dist/modules/sandbox/setup/apply.mjs.map +7 -0
- package/dist/modules/sandbox/setup/describe.d.mts +10 -0
- package/dist/modules/sandbox/setup/describe.mjs +62 -0
- package/dist/modules/sandbox/setup/describe.mjs.map +7 -0
- package/dist/modules/sandbox/setup/index.d.mts +6 -0
- package/dist/modules/sandbox/setup/index.mjs +17 -0
- package/dist/modules/sandbox/setup/index.mjs.map +7 -0
- package/dist/modules/sandbox/setup/paths.d.mts +8 -0
- package/dist/modules/sandbox/setup/paths.mjs +18 -0
- package/dist/modules/sandbox/setup/paths.mjs.map +7 -0
- package/dist/modules/sandbox/setup/schema.d.mts +42 -0
- package/dist/modules/sandbox/setup/schema.mjs +58 -0
- package/dist/modules/sandbox/setup/schema.mjs.map +7 -0
- package/dist/modules/sandbox/tool-policy.d.mts +1 -1
- package/dist/modules/sandbox/tool-policy.mjs +1 -1
- package/dist/modules/sandbox/tool-policy.mjs.map +2 -2
- package/dist/modules/sandbox/types.d.mts +117 -130
- package/dist/modules/sandbox/types.mjs +46 -50
- package/dist/modules/sandbox/types.mjs.map +3 -3
- package/dist/modules/sandbox/wire.d.mts +93 -6
- package/dist/modules/sandbox/wire.mjs +61 -38
- package/dist/modules/sandbox/wire.mjs.map +2 -2
- package/dist/modules/schemas.d.mts +5 -76
- package/dist/modules/schemas.mjs +18 -85
- package/dist/modules/schemas.mjs.map +2 -2
- package/dist/modules/tool-annotations.d.mts +15 -6
- package/dist/modules/tool-annotations.mjs +9 -3
- package/dist/modules/tool-annotations.mjs.map +2 -2
- package/dist/modules/tool-descriptor.d.mts +16 -0
- package/dist/modules/tool-descriptor.mjs +19 -0
- package/dist/modules/tool-descriptor.mjs.map +7 -0
- package/dist/modules/tool-patterns.d.mts +7 -7
- package/dist/modules/tool-patterns.mjs +10 -9
- package/dist/modules/tool-patterns.mjs.map +2 -2
- package/package.json +86 -36
- package/dist/modules/credentials.d.mts +0 -206
- package/dist/modules/credentials.mjs +0 -207
- package/dist/modules/credentials.mjs.map +0 -7
- package/dist/modules/dynamic.d.mts +0 -40
- package/dist/modules/dynamic.mjs +0 -79
- package/dist/modules/dynamic.mjs.map +0 -7
- package/dist/modules/hosted-bindings.d.mts +0 -15
- package/dist/modules/hosted-bindings.mjs +0 -21
- package/dist/modules/hosted-bindings.mjs.map +0 -7
- package/dist/modules/manifest.d.mts +0 -787
- package/dist/modules/manifest.mjs +0 -320
- package/dist/modules/manifest.mjs.map +0 -7
- package/dist/modules/provider-ref.d.mts +0 -29
- package/dist/modules/provider-ref.mjs +0 -55
- package/dist/modules/provider-ref.mjs.map +0 -7
- package/dist/modules/sandbox/open-scope-node.d.mts +0 -4
- package/dist/modules/sandbox/open-scope-node.mjs +0 -19
- package/dist/modules/sandbox/open-scope-node.mjs.map +0 -7
- package/dist/modules/sandbox/open-scope.d.mts +0 -16
- package/dist/modules/sandbox/open-scope.mjs +0 -66
- package/dist/modules/sandbox/open-scope.mjs.map +0 -7
- package/dist/modules/sandbox/workspace-identity.d.mts +0 -5
- package/dist/modules/sandbox/workspace-identity.mjs +0 -14
- package/dist/modules/sandbox/workspace-identity.mjs.map +0 -7
|
@@ -1,22 +1,24 @@
|
|
|
1
1
|
import * as z from "zod";
|
|
2
2
|
import { WorkspaceEgressAction } from "@finalai/agent-protocol/device-egress";
|
|
3
|
-
import { narrowerSandboxAccess, SandboxAccess, sandboxAccessAtLeast } from "../manifest.mjs";
|
|
4
3
|
import { base64ToBytes, bytesToStream } from "./bytes.mjs";
|
|
5
4
|
import { confinedReadDir, confinedReadFile, confinedStat } from "./confined-files.mjs";
|
|
6
5
|
import { hasSandboxExecutionGuard } from "./execution-guard.mjs";
|
|
6
|
+
import {
|
|
7
|
+
FULL_SANDBOX_GRANT,
|
|
8
|
+
handleMethodRefusal,
|
|
9
|
+
narrowerGrant
|
|
10
|
+
} from "./grant.mjs";
|
|
7
11
|
import { hasHostedMcpEndpoints } from "./mcp-hosted-marker.mjs";
|
|
8
12
|
import { createRpcPeer } from "./rpc-peer.mjs";
|
|
9
13
|
import {
|
|
10
14
|
isMcpChannelEndpoint,
|
|
15
|
+
isSandboxWorkerEndpoint,
|
|
11
16
|
SandboxCapability
|
|
12
17
|
} from "./types.mjs";
|
|
13
18
|
import {
|
|
14
19
|
createFrameChannelPair,
|
|
15
20
|
frameChannelFromStream,
|
|
16
21
|
frameChannelFromWebSocket,
|
|
17
|
-
HANDLE_RPC_EXECUTE_METHODS,
|
|
18
|
-
HANDLE_RPC_FILE_WRITE_METHODS,
|
|
19
|
-
HANDLE_RPC_LIFECYCLE_METHODS,
|
|
20
22
|
HANDLE_RPC_VERSION,
|
|
21
23
|
HandleRpcCloseCode,
|
|
22
24
|
handleRpcError,
|
|
@@ -26,7 +28,7 @@ import {
|
|
|
26
28
|
parseHandleRpcMethod
|
|
27
29
|
} from "./wire.mjs";
|
|
28
30
|
const DEFAULT_HANDLE_ACCESS = {
|
|
29
|
-
|
|
31
|
+
grant: FULL_SANDBOX_GRANT,
|
|
30
32
|
lifecycle: false
|
|
31
33
|
};
|
|
32
34
|
const needsMcpChannels = (sandbox) => hasSandboxExecutionGuard(sandbox) && !hasHostedMcpEndpoints(sandbox);
|
|
@@ -49,9 +51,10 @@ const capabilitiesOf = async (sandbox, mcpChannels = false) => {
|
|
|
49
51
|
if (sandbox.localMcp != null && (mcpChannels || !needsMcpChannels(sandbox)))
|
|
50
52
|
capabilities.push(SandboxCapability.LocalMcp);
|
|
51
53
|
if (sandbox.attachProcess != null) capabilities.push(SandboxCapability.DurableProcesses);
|
|
54
|
+
if (sandbox.startWorker != null) capabilities.push(SandboxCapability.Workers);
|
|
52
55
|
return capabilities;
|
|
53
56
|
};
|
|
54
|
-
const
|
|
57
|
+
const describeSandboxHandle = async (sandbox, mcpChannels = false) => ({
|
|
55
58
|
handleRpcVersion: HANDLE_RPC_VERSION,
|
|
56
59
|
id: sandbox.id,
|
|
57
60
|
defaultWorkingDirectory: sandbox.defaultWorkingDirectory,
|
|
@@ -60,7 +63,7 @@ const describeSandbox = async (sandbox, mcpChannels = false) => ({
|
|
|
60
63
|
description: sandbox.description
|
|
61
64
|
});
|
|
62
65
|
const narrowAccess = (base, narrower) => narrower == null ? base : {
|
|
63
|
-
|
|
66
|
+
grant: narrowerGrant(base.grant, narrower.grant),
|
|
64
67
|
lifecycle: base.lifecycle && narrower.lifecycle
|
|
65
68
|
};
|
|
66
69
|
const parseParams = (schema, params) => {
|
|
@@ -77,6 +80,26 @@ const uploadStreamIdsSchema = z.object({
|
|
|
77
80
|
streamId: z.number().int().nonnegative().optional(),
|
|
78
81
|
stdinStreamId: z.number().int().nonnegative().nullable().optional()
|
|
79
82
|
});
|
|
83
|
+
const PROCESS_CONTROL_METHODS = /* @__PURE__ */ new Set([
|
|
84
|
+
HandleRpcMethod.ProcessWait,
|
|
85
|
+
HandleRpcMethod.ProcessKill,
|
|
86
|
+
HandleRpcMethod.ProcessDetach
|
|
87
|
+
]);
|
|
88
|
+
const processIdOf = (params) => {
|
|
89
|
+
const parsed = z.object({ processId: z.string() }).safeParse(params);
|
|
90
|
+
return parsed.success ? parsed.data.processId : null;
|
|
91
|
+
};
|
|
92
|
+
const pipeInto = async (source, target) => {
|
|
93
|
+
const reader = source.getReader();
|
|
94
|
+
for (; ; ) {
|
|
95
|
+
const { done, value } = await reader.read();
|
|
96
|
+
if (done) {
|
|
97
|
+
await target.write(new Uint8Array(), { end: true });
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
await target.write(value);
|
|
101
|
+
}
|
|
102
|
+
};
|
|
80
103
|
const unsupported = (what) => handleRpcError({ code: HandleRpcErrorCode.Unsupported, message: `this sandbox has no ${what}` });
|
|
81
104
|
const sliceStream = (source, offset, length) => {
|
|
82
105
|
let position = 0;
|
|
@@ -152,6 +175,7 @@ const createServerConnection = (args) => {
|
|
|
152
175
|
let handle = null;
|
|
153
176
|
let expiryTimer = null;
|
|
154
177
|
const processes = /* @__PURE__ */ new Map();
|
|
178
|
+
const workers = /* @__PURE__ */ new Set();
|
|
155
179
|
const mcpEndpoints = /* @__PURE__ */ new Map();
|
|
156
180
|
const mcpConnections = /* @__PURE__ */ new Map();
|
|
157
181
|
let nextMcpChannelId = 0;
|
|
@@ -178,41 +202,11 @@ const createServerConnection = (args) => {
|
|
|
178
202
|
return sandbox;
|
|
179
203
|
};
|
|
180
204
|
const checkAccess = (method, params) => {
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
});
|
|
186
|
-
if (!sandboxAccessAtLeast(access.mode, SandboxAccess.Execute) && HANDLE_RPC_EXECUTE_METHODS.includes(method)) {
|
|
187
|
-
throw handleRpcError({
|
|
188
|
-
code: HandleRpcErrorCode.Forbidden,
|
|
189
|
-
message: `${method} is not allowed on a read-only binding`
|
|
190
|
-
});
|
|
191
|
-
}
|
|
192
|
-
if (!sandboxAccessAtLeast(access.mode, SandboxAccess.Write) && HANDLE_RPC_FILE_WRITE_METHODS.includes(method)) {
|
|
193
|
-
throw handleRpcError({
|
|
194
|
-
code: HandleRpcErrorCode.Forbidden,
|
|
195
|
-
message: `${method} is not allowed without write access`
|
|
196
|
-
});
|
|
197
|
-
}
|
|
198
|
-
if (method === HandleRpcMethod.Egress && !sandboxAccessAtLeast(access.mode, SandboxAccess.Write)) {
|
|
199
|
-
throw handleRpcError({
|
|
200
|
-
code: HandleRpcErrorCode.Forbidden,
|
|
201
|
-
message: "Device egress requires write access"
|
|
202
|
-
});
|
|
203
|
-
}
|
|
204
|
-
if (method === HandleRpcMethod.SetNetworkPolicy && access.mode === SandboxAccess.Read) {
|
|
205
|
-
throw handleRpcError({
|
|
206
|
-
code: HandleRpcErrorCode.Forbidden,
|
|
207
|
-
message: `${method} is not allowed on a read-only binding`
|
|
208
|
-
});
|
|
209
|
-
}
|
|
210
|
-
if (!access.lifecycle && HANDLE_RPC_LIFECYCLE_METHODS.includes(method)) {
|
|
211
|
-
throw handleRpcError({
|
|
212
|
-
code: HandleRpcErrorCode.Forbidden,
|
|
213
|
-
message: `${method} is not allowed on this binding`
|
|
214
|
-
});
|
|
215
|
-
}
|
|
205
|
+
const processId = processIdOf(params);
|
|
206
|
+
const gated = PROCESS_CONTROL_METHODS.has(method) && processId != null && workers.has(processId) ? HandleRpcMethod.StartWorker : method;
|
|
207
|
+
const refusal = handleMethodRefusal({ access, method: gated, params });
|
|
208
|
+
if (refusal != null)
|
|
209
|
+
throw handleRpcError({ code: HandleRpcErrorCode.Forbidden, message: refusal });
|
|
216
210
|
};
|
|
217
211
|
const featureFlags = () => {
|
|
218
212
|
const flags = {};
|
|
@@ -231,7 +225,7 @@ const createServerConnection = (args) => {
|
|
|
231
225
|
initializing = true;
|
|
232
226
|
try {
|
|
233
227
|
const token = parsed.token ?? args.connectionToken;
|
|
234
|
-
const authorization = await args.authorize({ token });
|
|
228
|
+
const authorization = await args.authorize({ token, identity: parsed.identity ?? null });
|
|
235
229
|
if (authorization == null) {
|
|
236
230
|
setTimeout(() => peer.close(HandleRpcCloseCode.Unauthorized, "unauthorized"), 0);
|
|
237
231
|
throw handleRpcError({ code: HandleRpcErrorCode.Unauthorized, message: "unauthorized" });
|
|
@@ -242,7 +236,7 @@ const createServerConnection = (args) => {
|
|
|
242
236
|
handle = resolution.handle ?? null;
|
|
243
237
|
scheduleExpiry(authorization.expiresAt);
|
|
244
238
|
return {
|
|
245
|
-
...await
|
|
239
|
+
...await describeSandboxHandle(sandbox, args.mcpChannels),
|
|
246
240
|
confinedFiles: true,
|
|
247
241
|
...featureFlags(),
|
|
248
242
|
expiresAt: authorization.expiresAt
|
|
@@ -323,7 +317,7 @@ const createServerConnection = (args) => {
|
|
|
323
317
|
switch (method) {
|
|
324
318
|
case HandleRpcMethod.Describe:
|
|
325
319
|
return {
|
|
326
|
-
...await
|
|
320
|
+
...await describeSandboxHandle(target, args.mcpChannels),
|
|
327
321
|
confinedFiles: true,
|
|
328
322
|
...featureFlags()
|
|
329
323
|
};
|
|
@@ -336,6 +330,15 @@ const createServerConnection = (args) => {
|
|
|
336
330
|
scheduleExpiry(authorization.expiresAt);
|
|
337
331
|
return { expiresAt: authorization.expiresAt };
|
|
338
332
|
}
|
|
333
|
+
case HandleRpcMethod.IdentityRefresh: {
|
|
334
|
+
const params = parseParams(handleRpcMethodSchemas[method].params, context.params);
|
|
335
|
+
const authorization = await args.authorize({ token: null, identity: params.assertion });
|
|
336
|
+
if (authorization == null)
|
|
337
|
+
throw handleRpcError({ code: HandleRpcErrorCode.Unauthorized, message: "unauthorized" });
|
|
338
|
+
access = narrowAccess(access, authorization.access);
|
|
339
|
+
scheduleExpiry(authorization.expiresAt);
|
|
340
|
+
return { expiresAt: authorization.expiresAt };
|
|
341
|
+
}
|
|
339
342
|
case HandleRpcMethod.ReadFile: {
|
|
340
343
|
const params = parseParams(handleRpcMethodSchemas[method].params, context.params);
|
|
341
344
|
const stream = params.root == null ? await target.readFile({ path: params.path, abortSignal }) : await (target.confinedFileReader?.readFile ?? ((options) => confinedReadFile(target, options)))({ path: params.path, root: params.root, abortSignal });
|
|
@@ -392,6 +395,42 @@ const createServerConnection = (args) => {
|
|
|
392
395
|
});
|
|
393
396
|
return { pid: child.pid, ref };
|
|
394
397
|
}
|
|
398
|
+
case HandleRpcMethod.StartWorker: {
|
|
399
|
+
const params = parseParams(handleRpcMethodSchemas[method].params, context.params);
|
|
400
|
+
if (target.startWorker == null) throw unsupported("worker programs");
|
|
401
|
+
const stdin = incomingByRequest.get(context.id)?.stream ?? null;
|
|
402
|
+
if (processes.has(params.processId))
|
|
403
|
+
throw handleRpcError({
|
|
404
|
+
code: HandleRpcErrorCode.InvalidParams,
|
|
405
|
+
message: "processId already in use"
|
|
406
|
+
});
|
|
407
|
+
const detach = params.durable === true ? new AbortController() : null;
|
|
408
|
+
const started = await target.startWorker({
|
|
409
|
+
program: params.program,
|
|
410
|
+
env: params.env,
|
|
411
|
+
input: params.input,
|
|
412
|
+
...params.identity == null ? {} : { identity: params.identity },
|
|
413
|
+
...detach == null ? {} : { durable: true, abortSignal: detach.signal }
|
|
414
|
+
});
|
|
415
|
+
const upload = incomingByRequest.get(context.id);
|
|
416
|
+
incomingByRequest.delete(context.id);
|
|
417
|
+
if (isSandboxWorkerEndpoint(started)) {
|
|
418
|
+
if (upload != null) peer.streams.cancelIncoming(upload.streamId, "worker endpoint");
|
|
419
|
+
return { endpoint: started.endpoint };
|
|
420
|
+
}
|
|
421
|
+
const worker = started;
|
|
422
|
+
if (stdin != null) void pipeInto(stdin, worker).catch(() => void 0);
|
|
423
|
+
const ref = worker.ref ?? null;
|
|
424
|
+
workers.add(params.processId);
|
|
425
|
+
serve({
|
|
426
|
+
processId: params.processId,
|
|
427
|
+
served: { process: worker, detach: ref == null ? null : detach },
|
|
428
|
+
signal: abortSignal,
|
|
429
|
+
stdout: { streamId: params.stdoutStreamId, stream: worker.stdout },
|
|
430
|
+
stderr: { streamId: params.stderrStreamId, stream: worker.stderr }
|
|
431
|
+
});
|
|
432
|
+
return { pid: worker.pid, ref };
|
|
433
|
+
}
|
|
395
434
|
case HandleRpcMethod.ProcessAttach: {
|
|
396
435
|
const params = parseParams(handleRpcMethodSchemas[method].params, context.params);
|
|
397
436
|
if (target.attachProcess == null) throw unsupported("durable processes");
|
|
@@ -451,6 +490,7 @@ const createServerConnection = (args) => {
|
|
|
451
490
|
);
|
|
452
491
|
});
|
|
453
492
|
processes.delete(params.processId);
|
|
493
|
+
workers.delete(params.processId);
|
|
454
494
|
return result;
|
|
455
495
|
}
|
|
456
496
|
case HandleRpcMethod.ProcessDetach: {
|
|
@@ -459,6 +499,7 @@ const createServerConnection = (args) => {
|
|
|
459
499
|
if (served == null) return {};
|
|
460
500
|
if (served.detach == null) throw unsupported("detaching an ordinary process");
|
|
461
501
|
processes.delete(params.processId);
|
|
502
|
+
workers.delete(params.processId);
|
|
462
503
|
await releaseProcess(served);
|
|
463
504
|
return {};
|
|
464
505
|
}
|
|
@@ -597,15 +638,18 @@ const createServerConnection = (args) => {
|
|
|
597
638
|
}
|
|
598
639
|
};
|
|
599
640
|
const beforeRequest = (context) => {
|
|
600
|
-
if (context.method !== HandleRpcMethod.WriteFile && context.method !== HandleRpcMethod.Spawn)
|
|
641
|
+
if (context.method !== HandleRpcMethod.WriteFile && context.method !== HandleRpcMethod.Spawn && context.method !== HandleRpcMethod.StartWorker)
|
|
601
642
|
return;
|
|
602
643
|
const ids = uploadStreamIdsSchema.safeParse(context.params);
|
|
603
644
|
if (!ids.success) return;
|
|
604
645
|
const streamId = context.method === HandleRpcMethod.WriteFile ? ids.data.streamId : ids.data.stdinStreamId;
|
|
605
646
|
if (streamId == null) return;
|
|
606
647
|
const stream = peer.streams.openIncoming(streamId);
|
|
607
|
-
|
|
608
|
-
|
|
648
|
+
if (sandbox == null || handleMethodRefusal({
|
|
649
|
+
access,
|
|
650
|
+
method: context.method === HandleRpcMethod.WriteFile || context.method === HandleRpcMethod.StartWorker ? context.method : HandleRpcMethod.Spawn,
|
|
651
|
+
params: context.params
|
|
652
|
+
}) != null) {
|
|
609
653
|
peer.streams.cancelIncoming(streamId, "rejected");
|
|
610
654
|
return;
|
|
611
655
|
}
|
|
@@ -670,7 +714,7 @@ const serveSandboxHandle = (args) => {
|
|
|
670
714
|
export {
|
|
671
715
|
DEFAULT_HANDLE_ACCESS,
|
|
672
716
|
createHandleRpcMessageHandler,
|
|
673
|
-
|
|
717
|
+
describeSandboxHandle,
|
|
674
718
|
serveSandboxHandle
|
|
675
719
|
};
|
|
676
720
|
//# sourceMappingURL=server.mjs.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../src/sandbox/server.ts"],
|
|
4
|
-
"sourcesContent": ["import * as z from 'zod';\nimport { WorkspaceEgressAction } from '@finalai/agent-protocol/device-egress';\nimport type { JsonValue } from \"../json.mjs\";\nimport { narrowerSandboxAccess, SandboxAccess, sandboxAccessAtLeast } from \"../manifest.mjs\";\nimport { base64ToBytes, bytesToStream } from \"./bytes.mjs\";\nimport { confinedReadDir, confinedReadFile, confinedStat } from \"./confined-files.mjs\";\nimport { hasSandboxExecutionGuard } from \"./execution-guard.mjs\";\nimport { hasHostedMcpEndpoints } from \"./mcp-hosted-marker.mjs\";\nimport { createRpcPeer, type RpcPeerIface, type RpcRequestContextIface } from \"./rpc-peer.mjs\";\nimport {\n isMcpChannelEndpoint,\n SandboxCapability,\n type McpChannelEndpointIface,\n type McpChannelIface,\n type NetworkSandboxSessionIface,\n type SandboxMcpEndpoint,\n type SandboxProcessIface,\n type SandboxProviderHandleIface,\n} from \"./types.mjs\";\nimport {\n createFrameChannelPair,\n frameChannelFromStream,\n frameChannelFromWebSocket,\n HANDLE_RPC_EXECUTE_METHODS,\n HANDLE_RPC_FILE_WRITE_METHODS,\n HANDLE_RPC_LIFECYCLE_METHODS,\n HANDLE_RPC_VERSION,\n HandleRpcCloseCode,\n handleRpcError,\n HandleRpcErrorCode,\n HandleRpcMethod,\n handleRpcMethodSchemas,\n parseHandleRpcMethod,\n type DescribeResultIface,\n type FrameChannelIface,\n type FrameStreamIface,\n type HandleRpcResult,\n type WebSocketLikeIface,\n type WireFrame,\n} from \"./wire.mjs\";\n\n// Serves the handle RPC (wire.ts) for a NetworkSandboxSessionIface. The session\n// service runs it for every provider at its stable per-binding endpoint, which\n// may lazily start the sandbox (through the provider) on the first call.\n\nexport interface HandleAccessPolicyIface {\n // Read bindings reject writes, removes, process execution and computer use;\n // execute bindings allow processes and computer use but not file writes.\n mode: SandboxAccess;\n // Allows sandbox/stop, sandbox/destroy and sandbox/setNetworkPolicy.\n lifecycle: boolean;\n}\n\nexport const DEFAULT_HANDLE_ACCESS: HandleAccessPolicyIface = {\n mode: SandboxAccess.Write,\n lifecycle: false,\n};\n\nexport interface HandleAuthorizationIface {\n // When the credential expires; the server closes the connection then unless\n // the client refreshed it.\n expiresAt: string | null;\n // Narrows the server's access policy for this connection.\n access?: HandleAccessPolicyIface;\n}\n\n// Returns null to reject. `token` is null when the client sent none.\nexport type HandleAuthorizeFn = (args: {\n token: string | null;\n}) => Promise<HandleAuthorizationIface | null>;\n\nexport type HandleLifecycle = Pick<\n SandboxProviderHandleIface<NetworkSandboxSessionIface>,\n 'onSandboxStop' | 'onSandboxDelete' | 'onRuntimeShutdown'\n>;\n\nexport interface HandleResolutionIface {\n sandbox: NetworkSandboxSessionIface;\n handle?: HandleLifecycle;\n access?: HandleAccessPolicyIface;\n}\n\nexport interface HandleRpcMessageHandlerOptionsIface {\n send: (frame: WireFrame) => void;\n close: (code: number, reason: string) => void;\n authorize: HandleAuthorizeFn;\n // Called once per connection, after `initialize` is authorized. The session\n // service's stable endpoint starts the sandbox here through its provider.\n resolve: (authorization: HandleAuthorizationIface) => Promise<HandleResolutionIface>;\n access?: HandleAccessPolicyIface;\n // Token presented in the connection request, used when `initialize` has none.\n connectionToken?: string | null;\n // Send stream chunks as binary frames (default true).\n binary?: boolean;\n // The outer host applies hosted-tool policy before exposing this transport.\n mcpChannels?: boolean;\n now?: () => number;\n // Runs for each validated operation, after binding access checks.\n authorizeOperation?: (context: RpcRequestContextIface) => Promise<void>;\n}\n\nexport interface HandleRpcMessageHandlerIface {\n onFrame(frame: WireFrame): void;\n onClose(code?: number, reason?: string): void;\n}\n\n// Computer use counts only when `sandbox/computerUse` can answer it: an MCP\n// channel endpoint does not cross this wire (its host re-addresses it, as the\n// session service does with withHostedMcpEndpoints).\nconst needsMcpChannels = (sandbox: NetworkSandboxSessionIface) =>\n hasSandboxExecutionGuard(sandbox) && !hasHostedMcpEndpoints(sandbox);\n\nconst servesComputerUse = async (sandbox: NetworkSandboxSessionIface): Promise<boolean> => {\n if (sandbox.computerUse == null || needsMcpChannels(sandbox)) return false;\n try {\n return !isMcpChannelEndpoint(await sandbox.computerUse());\n } catch {\n return false;\n }\n};\n\nconst capabilitiesOf = async (\n sandbox: NetworkSandboxSessionIface,\n mcpChannels = false,\n): Promise<SandboxCapability[]> => {\n const capabilities = [SandboxCapability.Files, SandboxCapability.Process];\n if (sandbox.ports.length > 0) capabilities.push(SandboxCapability.Ports);\n if (sandbox.setNetworkPolicy != null) capabilities.push(SandboxCapability.NetworkPolicy);\n if (sandbox.egress != null) capabilities.push(SandboxCapability.Egress);\n if (mcpChannels ? sandbox.computerUse != null : await servesComputerUse(sandbox))\n capabilities.push(SandboxCapability.ComputerUse);\n if (sandbox.screen != null) capabilities.push(SandboxCapability.Screen);\n if (sandbox.localMcp != null && (mcpChannels || !needsMcpChannels(sandbox)))\n capabilities.push(SandboxCapability.LocalMcp);\n if (sandbox.attachProcess != null) capabilities.push(SandboxCapability.DurableProcesses);\n return capabilities;\n};\n\nexport const describeSandbox = async (\n sandbox: NetworkSandboxSessionIface,\n mcpChannels = false,\n): Promise<DescribeResultIface> => ({\n handleRpcVersion: HANDLE_RPC_VERSION,\n id: sandbox.id,\n defaultWorkingDirectory: sandbox.defaultWorkingDirectory,\n ports: [...sandbox.ports],\n capabilities: await capabilitiesOf(sandbox, mcpChannels),\n description: sandbox.description,\n});\n\nconst narrowAccess = (\n base: HandleAccessPolicyIface,\n narrower: HandleAccessPolicyIface | undefined,\n): HandleAccessPolicyIface =>\n narrower == null\n ? base\n : {\n mode: narrowerSandboxAccess(base.mode, narrower.mode),\n lifecycle: base.lifecycle && narrower.lifecycle,\n };\n\nconst parseParams = <S extends z.ZodType>(schema: S, params: JsonValue): z.output<S> => {\n const parsed = schema.safeParse(params);\n if (!parsed.success) {\n throw handleRpcError({\n code: HandleRpcErrorCode.InvalidParams,\n message: z.prettifyError(parsed.error),\n });\n }\n return parsed.data;\n};\n\n// The upload stream ids a request names, read before full validation.\nconst uploadStreamIdsSchema = z.object({\n streamId: z.number().int().nonnegative().optional(),\n stdinStreamId: z.number().int().nonnegative().nullable().optional(),\n});\n\nconst unsupported = (what: string) =>\n handleRpcError({ code: HandleRpcErrorCode.Unsupported, message: `this sandbox has no ${what}` });\n\n// Byte-range slice of a stream.\nconst sliceStream = (\n source: ReadableStream<Uint8Array>,\n offset: number,\n length: number | undefined,\n): ReadableStream<Uint8Array> => {\n let position = 0;\n const end = length == null ? Number.POSITIVE_INFINITY : offset + length;\n const reader = source.getReader();\n return new ReadableStream<Uint8Array>({\n pull: async (controller) => {\n for (;;) {\n if (position >= end) {\n controller.close();\n await reader.cancel().catch(() => undefined);\n return;\n }\n const { done, value } = await reader.read();\n if (done) {\n controller.close();\n return;\n }\n const chunkStart = position;\n position += value.byteLength;\n const from = Math.max(0, offset - chunkStart);\n const to = Math.min(value.byteLength, end - chunkStart);\n if (to > from) {\n controller.enqueue(value.subarray(from, to));\n return;\n }\n }\n },\n cancel: (reason) => reader.cancel(reason),\n });\n};\n\n// Low-level, transport-agnostic handler: feed it frames, it calls `send` and\n// `close`. Use it where the host owns the socket (Hono upgradeWebSocket, a\n// Durable Object's hibernation handlers, a relay).\nexport const createHandleRpcMessageHandler = (\n options: HandleRpcMessageHandlerOptionsIface,\n): HandleRpcMessageHandlerIface => {\n const now = options.now ?? Date.now;\n const [local, remote] = createFrameChannelPair();\n let ended = false;\n // `remote` is our side; frames the peer writes to it go out through `send`.\n remote.listen({\n frame: (frame) => options.send(frame),\n close: (info) => {\n if (!ended) {\n ended = true;\n options.close(info.code, info.reason);\n }\n },\n });\n const peerChannel: FrameChannelIface = local;\n const connection = createServerConnection({\n channel: peerChannel,\n authorize: options.authorize,\n resolve: options.resolve,\n access: options.access ?? DEFAULT_HANDLE_ACCESS,\n connectionToken: options.connectionToken ?? null,\n binary: options.binary ?? true,\n mcpChannels: options.mcpChannels,\n now,\n authorizeOperation: options.authorizeOperation,\n });\n return {\n onFrame: (frame) => remote.send(frame),\n onClose: (code, reason) => {\n ended = true;\n connection.close(code ?? 1000, reason ?? '');\n },\n };\n};\n\ninterface ServerConnectionIface {\n close(code: number, reason: string): void;\n}\n\n// A process served on one connection. `detach` is set for a durable process:\n// aborting it releases the handle and leaves the process running.\ninterface ServedProcessIface {\n process: Pick<SandboxProcessIface, 'wait' | 'kill'>;\n detach: AbortController | null;\n}\n\n// Ends a connection's hold on a process: detaches a durable one, kills any other.\nconst releaseProcess = async (served: ServedProcessIface): Promise<void> => {\n if (served.detach == null) await served.process.kill();\n else served.detach.abort(new Error('process handle released'));\n};\n\ninterface ServerConnectionArgsIface {\n channel: FrameChannelIface;\n authorize: HandleAuthorizeFn;\n resolve: (authorization: HandleAuthorizationIface) => Promise<HandleResolutionIface>;\n access: HandleAccessPolicyIface;\n connectionToken: string | null;\n binary: boolean;\n mcpChannels?: boolean;\n now: () => number;\n authorizeOperation?: (context: RpcRequestContextIface) => Promise<void>;\n}\n\nconst createServerConnection = (args: ServerConnectionArgsIface): ServerConnectionIface => {\n let sandbox: NetworkSandboxSessionIface | null = null;\n let access = args.access;\n let initializing = false;\n let handle: HandleLifecycle | null = null;\n let expiryTimer: ReturnType<typeof setTimeout> | null = null;\n const processes = new Map<string, ServedProcessIface>();\n const mcpEndpoints = new Map<string, McpChannelEndpointIface>();\n const mcpConnections = new Map<string, McpChannelIface>();\n let nextMcpChannelId = 0;\n let shutdown: Promise<void> | null = null;\n // Incoming streams registered in beforeRequest, keyed by request id.\n const incomingByRequest = new Map<\n string | number,\n { streamId: number; stream: ReadableStream<Uint8Array> }\n >();\n\n const scheduleExpiry = (expiresAt: string | null) => {\n if (expiryTimer != null) clearTimeout(expiryTimer);\n expiryTimer = null;\n if (expiresAt == null) return;\n const delay = Date.parse(expiresAt) - args.now();\n if (Number.isNaN(delay)) return;\n expiryTimer = setTimeout(\n () =>\n delay > 2_147_483_647\n ? scheduleExpiry(expiresAt)\n : peer.close(HandleRpcCloseCode.Unauthorized, 'credential expired'),\n Math.max(0, Math.min(2_147_483_647, delay)),\n );\n };\n\n const requireSandbox = (): NetworkSandboxSessionIface => {\n if (sandbox == null) {\n throw handleRpcError({\n code: HandleRpcErrorCode.NotInitialized,\n message: 'initialize first',\n });\n }\n return sandbox;\n };\n\n const checkAccess = (method: HandleRpcMethod, params: JsonValue) => {\n if (\n method === HandleRpcMethod.Screen &&\n !parseParams(handleRpcMethodSchemas[method].params, params).viewOnly &&\n !sandboxAccessAtLeast(access.mode, SandboxAccess.Execute)\n )\n throw handleRpcError({\n code: HandleRpcErrorCode.Forbidden,\n message: 'Screen input control requires execute access',\n });\n if (\n !sandboxAccessAtLeast(access.mode, SandboxAccess.Execute) &&\n HANDLE_RPC_EXECUTE_METHODS.includes(method)\n ) {\n throw handleRpcError({\n code: HandleRpcErrorCode.Forbidden,\n message: `${method} is not allowed on a read-only binding`,\n });\n }\n if (\n !sandboxAccessAtLeast(access.mode, SandboxAccess.Write) &&\n HANDLE_RPC_FILE_WRITE_METHODS.includes(method)\n ) {\n throw handleRpcError({\n code: HandleRpcErrorCode.Forbidden,\n message: `${method} is not allowed without write access`,\n });\n }\n if (\n method === HandleRpcMethod.Egress &&\n !sandboxAccessAtLeast(access.mode, SandboxAccess.Write)\n ) {\n throw handleRpcError({\n code: HandleRpcErrorCode.Forbidden,\n message: 'Device egress requires write access',\n });\n }\n if (method === HandleRpcMethod.SetNetworkPolicy && access.mode === SandboxAccess.Read) {\n throw handleRpcError({\n code: HandleRpcErrorCode.Forbidden,\n message: `${method} is not allowed on a read-only binding`,\n });\n }\n if (!access.lifecycle && HANDLE_RPC_LIFECYCLE_METHODS.includes(method)) {\n throw handleRpcError({\n code: HandleRpcErrorCode.Forbidden,\n message: `${method} is not allowed on this binding`,\n });\n }\n };\n\n const featureFlags = (): Pick<DescribeResultIface, 'providerHooks' | 'mcpChannels'> => {\n const flags: Pick<DescribeResultIface, 'providerHooks' | 'mcpChannels'> = {};\n if (handle != null) flags.providerHooks = true;\n if (args.mcpChannels === true) flags.mcpChannels = true;\n return flags;\n };\n\n const initialize = async (\n params: JsonValue,\n ): Promise<HandleRpcResult<HandleRpcMethod.Initialize>> => {\n const parsed = parseParams(handleRpcMethodSchemas[HandleRpcMethod.Initialize].params, params);\n if (sandbox != null || initializing) {\n throw handleRpcError({\n code: HandleRpcErrorCode.InvalidRequest,\n message: 'already initialized',\n });\n }\n initializing = true;\n try {\n const token = parsed.token ?? args.connectionToken;\n const authorization = await args.authorize({ token });\n if (authorization == null) {\n setTimeout(() => peer.close(HandleRpcCloseCode.Unauthorized, 'unauthorized'), 0);\n throw handleRpcError({ code: HandleRpcErrorCode.Unauthorized, message: 'unauthorized' });\n }\n const resolution = await args.resolve(authorization);\n access = narrowAccess(narrowAccess(access, resolution.access), authorization.access);\n sandbox = resolution.sandbox;\n handle = resolution.handle ?? null;\n scheduleExpiry(authorization.expiresAt);\n return {\n ...(await describeSandbox(sandbox, args.mcpChannels)),\n confinedFiles: true,\n ...featureFlags(),\n expiresAt: authorization.expiresAt,\n };\n } finally {\n initializing = false;\n }\n };\n\n const pump = (streamId: number, source: ReadableStream<Uint8Array>) => {\n peer.streams.openOutgoing(streamId, source).catch(() => undefined);\n };\n\n // Registers a process the provider just returned, unless the request was\n // cancelled or the connection closed or shut down meanwhile: then it is\n // released at once.\n const serve = (args: {\n processId: string;\n served: ServedProcessIface;\n signal: AbortSignal;\n stdout: { streamId: number; stream: ReadableStream<Uint8Array> };\n stderr: { streamId: number; stream: ReadableStream<Uint8Array> };\n }) => {\n if (args.signal.aborted || shutdown != null) {\n void releaseProcess(args.served).catch(() => undefined);\n throw handleRpcError({ code: HandleRpcErrorCode.Cancelled, message: 'request cancelled' });\n }\n processes.set(args.processId, args.served);\n pump(args.stdout.streamId, args.stdout.stream);\n pump(args.stderr.streamId, args.stderr.stream);\n };\n const servedProcess = (processId: string): ServedProcessIface => {\n const served = processes.get(processId);\n if (served == null)\n throw handleRpcError({ code: HandleRpcErrorCode.NotFound, message: 'no such process' });\n return served;\n };\n\n const mcpDescriptor = (endpoint: SandboxMcpEndpoint, key: string) => {\n if (!isMcpChannelEndpoint(endpoint)) return endpoint;\n if (args.mcpChannels !== true) throw unsupported('MCP channels over the handle RPC');\n mcpEndpoints.set(key, endpoint);\n return { name: endpoint.name, endpointKey: key };\n };\n const mcpConnection = (id: string): McpChannelIface => {\n const channel = mcpConnections.get(id);\n if (channel == null)\n throw handleRpcError({\n code: HandleRpcErrorCode.NotFound,\n message: 'MCP channel not found on this connection',\n });\n return channel;\n };\n\n // Fails a request's upload stream when the request fails, so the client\n // stops sending.\n const dispatch = async (context: RpcRequestContextIface): Promise<object> => {\n try {\n return await dispatchMethod(context);\n } catch (error) {\n const entry = incomingByRequest.get(context.id);\n incomingByRequest.delete(context.id);\n if (entry != null) peer.streams.cancelIncoming(entry.streamId, 'request failed');\n throw error;\n }\n };\n\n const dispatchMethod = async (context: RpcRequestContextIface): Promise<object> => {\n const method = parseHandleRpcMethod(context.method);\n if (method == null) {\n throw handleRpcError({\n code: HandleRpcErrorCode.MethodNotFound,\n message: `unknown method ${context.method}`,\n });\n }\n if (method === HandleRpcMethod.Initialize) return initialize(context.params);\n const target = requireSandbox();\n if (shutdown != null && method !== HandleRpcMethod.OnRuntimeShutdown)\n throw handleRpcError({\n code: HandleRpcErrorCode.ConnectionClosed,\n message: 'Provider handle is shutting down',\n });\n checkAccess(method, context.params);\n parseParams(handleRpcMethodSchemas[method].params, context.params);\n if (\n method === HandleRpcMethod.Egress &&\n parseParams(handleRpcMethodSchemas[HandleRpcMethod.Egress].params, context.params).action !==\n WorkspaceEgressAction.Status &&\n args.authorizeOperation == null\n )\n throw handleRpcError({\n code: HandleRpcErrorCode.Forbidden,\n message: 'Device egress changes require an operation authorization hook',\n });\n await args.authorizeOperation?.(context);\n if (context.signal.aborted)\n throw handleRpcError({ code: HandleRpcErrorCode.Cancelled, message: 'request cancelled' });\n const abortSignal = context.signal;\n switch (method) {\n case HandleRpcMethod.Describe:\n return {\n ...(await describeSandbox(target, args.mcpChannels)),\n confinedFiles: true,\n ...featureFlags(),\n };\n case HandleRpcMethod.AuthRefresh: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n const authorization = await args.authorize({ token: params.token });\n if (authorization == null)\n throw handleRpcError({ code: HandleRpcErrorCode.Unauthorized, message: 'unauthorized' });\n access = narrowAccess(access, authorization.access);\n scheduleExpiry(authorization.expiresAt);\n return { expiresAt: authorization.expiresAt };\n }\n case HandleRpcMethod.ReadFile: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n const stream =\n params.root == null\n ? await target.readFile({ path: params.path, abortSignal })\n : await (\n target.confinedFileReader?.readFile ??\n ((options) => confinedReadFile(target, options))\n )({ path: params.path, root: params.root, abortSignal });\n if (stream == null) return { found: false };\n const ranged =\n params.offset != null || params.length != null\n ? sliceStream(stream, params.offset ?? 0, params.length)\n : stream;\n // The client registered the stream before asking, so start right away.\n pump(params.streamId, ranged);\n return { found: true };\n }\n case HandleRpcMethod.ReadTextFile: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n const text = await target.readTextFile({ ...params, abortSignal });\n return { text };\n }\n case HandleRpcMethod.WriteFile: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n const incoming = incomingByRequest.get(context.id)?.stream ?? null;\n const content =\n incoming ??\n bytesToStream(\n params.contentBase64 == null ? new Uint8Array() : base64ToBytes(params.contentBase64),\n );\n await target.writeFile({ path: params.path, content, abortSignal });\n incomingByRequest.delete(context.id);\n return {};\n }\n case HandleRpcMethod.Spawn: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n const stdin = incomingByRequest.get(context.id)?.stream ?? null;\n if (processes.has(params.processId)) {\n throw handleRpcError({\n code: HandleRpcErrorCode.InvalidParams,\n message: 'processId already in use',\n });\n }\n const detach = params.durable === true ? new AbortController() : null;\n const child = await target.spawn({\n command: params.command,\n args: params.args,\n cwd: params.cwd,\n env: params.env,\n shell: params.shell,\n timeoutMs: params.timeoutMs,\n // A closed stdin is an empty stream.\n stdin: stdin ?? '',\n ...(detach == null ? {} : { durable: true, abortSignal: detach.signal }),\n });\n incomingByRequest.delete(context.id);\n const ref = child.ref ?? null;\n serve({\n processId: params.processId,\n // A sandbox that ignored `durable` gave an ordinary process.\n served: { process: child, detach: ref == null ? null : detach },\n signal: abortSignal,\n stdout: { streamId: params.stdoutStreamId, stream: child.stdout },\n stderr: { streamId: params.stderrStreamId, stream: child.stderr },\n });\n return { pid: child.pid, ref };\n }\n case HandleRpcMethod.ProcessAttach: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n if (target.attachProcess == null) throw unsupported('durable processes');\n if (processes.has(params.processId))\n throw handleRpcError({\n code: HandleRpcErrorCode.InvalidParams,\n message: 'processId already in use',\n });\n const detach = new AbortController();\n // Until it is served, cancelling the request (or closing the connection)\n // cancels the attach; afterwards the handle lives until released.\n const cancelAttach = () => detach.abort(abortSignal.reason);\n abortSignal.addEventListener('abort', cancelAttach, { once: true });\n let attached: Awaited<ReturnType<NonNullable<typeof target.attachProcess>>>;\n try {\n attached = await target.attachProcess({\n ref: params.ref,\n stdoutOffset: params.stdoutOffset,\n stderrOffset: params.stderrOffset,\n abortSignal: detach.signal,\n });\n } finally {\n abortSignal.removeEventListener('abort', cancelAttach);\n }\n if (attached == null)\n return {\n found: false,\n stdoutOffset: params.stdoutOffset,\n stderrOffset: params.stderrOffset,\n };\n serve({\n processId: params.processId,\n served: { process: attached, detach },\n signal: abortSignal,\n stdout: { streamId: params.stdoutStreamId, stream: attached.stdout },\n stderr: { streamId: params.stderrStreamId, stream: attached.stderr },\n });\n return {\n found: true,\n stdoutOffset: attached.stdoutOffset,\n stderrOffset: attached.stderrOffset,\n };\n }\n case HandleRpcMethod.ProcessWait: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n const child = servedProcess(params.processId).process;\n const result = await new Promise<{ exitCode: number }>((resolve, reject) => {\n const onAbort = () =>\n reject(handleRpcError({ code: HandleRpcErrorCode.Cancelled, message: 'cancelled' }));\n abortSignal.addEventListener('abort', onAbort, { once: true });\n child.wait().then(\n (value) => {\n abortSignal.removeEventListener('abort', onAbort);\n resolve(value);\n },\n (cause: unknown) => {\n abortSignal.removeEventListener('abort', onAbort);\n reject(cause);\n },\n );\n });\n processes.delete(params.processId);\n return result;\n }\n case HandleRpcMethod.ProcessDetach: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n const served = processes.get(params.processId);\n // Detaching what is already gone (exited and released, or never known) is done.\n if (served == null) return {};\n if (served.detach == null) throw unsupported('detaching an ordinary process');\n processes.delete(params.processId);\n await releaseProcess(served);\n return {};\n }\n case HandleRpcMethod.ProcessKill: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n await servedProcess(params.processId).process.kill(params.signal);\n return {};\n }\n case HandleRpcMethod.Run: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n return target.run({ ...params, abortSignal });\n }\n case HandleRpcMethod.Stat: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n return {\n stat:\n params.root == null\n ? await target.stat({ path: params.path, abortSignal })\n : await (\n target.confinedFileReader?.stat ?? ((options) => confinedStat(target, options))\n )({\n path: params.path,\n root: params.root,\n abortSignal,\n }),\n };\n }\n case HandleRpcMethod.ReadDir: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n return {\n entries:\n params.root == null\n ? await target.readDir({ path: params.path, abortSignal })\n : await (\n target.confinedFileReader?.readDir ??\n ((options) => confinedReadDir(target, options))\n )({\n path: params.path,\n root: params.root,\n abortSignal,\n }),\n };\n }\n case HandleRpcMethod.RemovePath: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n await target.removePath({ ...params, abortSignal });\n return {};\n }\n case HandleRpcMethod.GetPortEndpoint: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n return target.getPortEndpoint(params);\n }\n case HandleRpcMethod.Stop:\n await target.stop();\n return {};\n case HandleRpcMethod.Destroy:\n await target.destroy();\n return {};\n case HandleRpcMethod.OnRuntimeShutdown: {\n if (handle == null) throw unsupported('provider lifecycle hooks');\n const shutdownHandle = handle;\n shutdown ??= (async () => {\n await Promise.allSettled([...processes.values()].map(releaseProcess));\n await Promise.allSettled([...mcpConnections.values()].map((channel) => channel.close()));\n processes.clear();\n mcpConnections.clear();\n mcpEndpoints.clear();\n await shutdownHandle.onRuntimeShutdown();\n })();\n await shutdown;\n return {};\n }\n case HandleRpcMethod.OnSandboxStop:\n if (handle == null) throw unsupported('provider lifecycle hooks');\n await handle.onSandboxStop();\n return {};\n case HandleRpcMethod.OnSandboxDelete: {\n if (handle == null) throw unsupported('provider lifecycle hooks');\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n await handle.onSandboxDelete(params);\n return {};\n }\n case HandleRpcMethod.SetNetworkPolicy: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n if (target.setNetworkPolicy == null) throw unsupported('network policy');\n await target.setNetworkPolicy(params);\n return {};\n }\n case HandleRpcMethod.Egress: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n if (target.egress == null) throw unsupported('Device egress');\n return handleRpcMethodSchemas[HandleRpcMethod.Egress].result.parse(\n await target.egress(params),\n );\n }\n case HandleRpcMethod.ComputerUse: {\n if (target.computerUse == null) throw unsupported('computer use');\n if (needsMcpChannels(target) && args.mcpChannels !== true)\n throw unsupported('guarded MCP transport; negotiate mcpChannels');\n const endpoint = await target.computerUse();\n return mcpDescriptor(endpoint, 'computerUse');\n }\n case HandleRpcMethod.McpOpen: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n const endpoint = mcpEndpoints.get(params.endpointKey);\n if (args.mcpChannels !== true || endpoint == null)\n throw unsupported('MCP channel endpoint');\n const channel = await endpoint.connect({ abortSignal });\n if (abortSignal.aborted) {\n await channel.close();\n abortSignal.throwIfAborted();\n }\n const channelId = String(++nextMcpChannelId);\n mcpConnections.set(channelId, channel);\n return { channelId };\n }\n case HandleRpcMethod.McpSend: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n await mcpConnection(params.channelId).send(params.message, { abortSignal });\n return {};\n }\n case HandleRpcMethod.McpReceive: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n return { messages: await mcpConnection(params.channelId).receive({ abortSignal }) };\n }\n case HandleRpcMethod.McpClose: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n const channel = mcpConnection(params.channelId);\n await channel.close();\n mcpConnections.delete(params.channelId);\n return {};\n }\n case HandleRpcMethod.Screen: {\n if (target.screen == null) throw unsupported('screen');\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n return target.screen(params);\n }\n case HandleRpcMethod.LocalMcp:\n if (target.localMcp == null) throw unsupported('local MCP servers');\n if (needsMcpChannels(target) && args.mcpChannels !== true)\n throw unsupported('guarded MCP transport; negotiate mcpChannels');\n return {\n endpoints: (await target.localMcp()).flatMap((endpoint, index) =>\n args.mcpChannels !== true && isMcpChannelEndpoint(endpoint)\n ? []\n : [mcpDescriptor(endpoint, `localMcp:${index}:${endpoint.name}`)],\n ),\n };\n }\n };\n\n // Registers client-to-server streams synchronously, before their chunks.\n const beforeRequest = (context: RpcRequestContextIface) => {\n if (context.method !== HandleRpcMethod.WriteFile && context.method !== HandleRpcMethod.Spawn)\n return;\n const ids = uploadStreamIdsSchema.safeParse(context.params);\n if (!ids.success) return;\n const streamId =\n context.method === HandleRpcMethod.WriteFile ? ids.data.streamId : ids.data.stdinStreamId;\n if (streamId == null) return;\n const stream = peer.streams.openIncoming(streamId);\n // Reject unauthorized or disallowed uploads before buffering their data.\n const floor =\n context.method === HandleRpcMethod.WriteFile ? SandboxAccess.Write : SandboxAccess.Execute;\n if (sandbox == null || !sandboxAccessAtLeast(access.mode, floor)) {\n peer.streams.cancelIncoming(streamId, 'rejected');\n return;\n }\n incomingByRequest.set(context.id, { streamId, stream });\n };\n\n const onClose = () => {\n if (expiryTimer != null) clearTimeout(expiryTimer);\n for (const served of processes.values()) releaseProcess(served).catch(() => undefined);\n for (const channel of mcpConnections.values()) void channel.close().catch(() => undefined);\n mcpConnections.clear();\n mcpEndpoints.clear();\n processes.clear();\n incomingByRequest.clear();\n };\n\n const peer: RpcPeerIface = createRpcPeer({\n channel: args.channel,\n binary: args.binary,\n onRequest: dispatch,\n beforeRequest,\n onClose,\n });\n\n return { close: (code, reason) => peer.close(code, reason) };\n};\n\nexport interface ServeSandboxHandleArgsIface {\n sandbox: NetworkSandboxSessionIface;\n handle?: HandleLifecycle;\n authorize: HandleAuthorizeFn;\n authorizeOperation?: HandleRpcMessageHandlerOptionsIface['authorizeOperation'];\n access?: HandleAccessPolicyIface;\n binary?: boolean;\n // The outer host applies hosted-tool policy before exposing this transport.\n mcpChannels?: boolean;\n now?: () => number;\n}\n\nexport interface SandboxHandleServerIface {\n // Attaches a connection; returns a function that closes it.\n attach(channel: FrameChannelIface, context?: { token?: string | null }): () => void;\n attachWebSocket(socket: WebSocketLikeIface, context?: { token?: string | null }): () => void;\n attachStream(stream: FrameStreamIface, context?: { token?: string | null }): () => void;\n messageHandler(args: {\n send: (frame: WireFrame) => void;\n close: (code: number, reason: string) => void;\n token?: string | null;\n }): HandleRpcMessageHandlerIface;\n}\n\nexport const serveSandboxHandle = (args: ServeSandboxHandleArgsIface): SandboxHandleServerIface => {\n const access = args.access ?? DEFAULT_HANDLE_ACCESS;\n const resolve = async (): Promise<HandleResolutionIface> => ({\n sandbox: args.sandbox,\n handle: args.handle,\n });\n const attach = (channel: FrameChannelIface, context?: { token?: string | null }) => {\n const connection = createServerConnection({\n channel,\n authorize: args.authorize,\n authorizeOperation: args.authorizeOperation,\n resolve,\n access,\n connectionToken: context?.token ?? null,\n binary: args.binary ?? true,\n mcpChannels: args.mcpChannels,\n now: args.now ?? Date.now,\n });\n return () => connection.close(HandleRpcCloseCode.Normal, 'closed');\n };\n return {\n attach,\n attachWebSocket: (socket, context) =>\n attach(frameChannelFromWebSocket(socket).channel, context),\n attachStream: (stream, context) => attach(frameChannelFromStream(stream), context),\n messageHandler: (handlerArgs) =>\n createHandleRpcMessageHandler({\n send: handlerArgs.send,\n close: handlerArgs.close,\n authorize: args.authorize,\n authorizeOperation: args.authorizeOperation,\n resolve,\n access,\n connectionToken: handlerArgs.token ?? null,\n binary: args.binary,\n mcpChannels: args.mcpChannels,\n now: args.now,\n }),\n };\n};\n"],
|
|
5
|
-
"mappings": "AAAA,YAAY,OAAO;AACnB,SAAS,6BAA6B;AAEtC,SAAS,uBAAuB,eAAe,4BAA4B;AAC3E,SAAS,eAAe,qBAAqB;AAC7C,SAAS,iBAAiB,kBAAkB,oBAAoB;AAChE,SAAS,gCAAgC;AACzC,SAAS,6BAA6B;AACtC,SAAS,qBAAqE;AAC9E;AAAA,EACE;AAAA,EACA;AAAA,OAOK;AACP;AAAA,EACE;AAAA,EACA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SAAS;AAAA,MACnC,QAAQ,KAAK,UAAU;AAAA,MACvB,aAAa,KAAK;AAAA,MAClB,KAAK,KAAK,OAAO,KAAK;AAAA,IACxB,CAAC;AACD,WAAO,MAAM,WAAW,MAAM,mBAAmB,QAAQ,QAAQ;AAAA,EACnE;AACA,SAAO;AAAA,IACL;AAAA,IACA,iBAAiB,CAAC,QAAQ,YACxB,OAAO,0BAA0B,MAAM,EAAE,SAAS,OAAO;AAAA,IAC3D,cAAc,CAAC,QAAQ,YAAY,OAAO,uBAAuB,MAAM,GAAG,OAAO;AAAA,IACjF,gBAAgB,CAAC,gBACf,8BAA8B;AAAA,MAC5B,MAAM,YAAY;AAAA,MAClB,OAAO,YAAY;AAAA,MACnB,WAAW,KAAK;AAAA,MAChB,oBAAoB,KAAK;AAAA,MACzB;AAAA,MACA;AAAA,MACA,iBAAiB,YAAY,SAAS;AAAA,MACtC,QAAQ,KAAK;AAAA,MACb,aAAa,KAAK;AAAA,MAClB,KAAK,KAAK;AAAA,IACZ,CAAC;AAAA,EACL;AACF;",
|
|
4
|
+
"sourcesContent": ["import * as z from 'zod';\nimport { WorkspaceEgressAction } from '@finalai/agent-protocol/device-egress';\nimport type { JsonValue } from \"../json.mjs\";\nimport { base64ToBytes, bytesToStream } from \"./bytes.mjs\";\nimport { confinedReadDir, confinedReadFile, confinedStat } from \"./confined-files.mjs\";\nimport { hasSandboxExecutionGuard } from \"./execution-guard.mjs\";\nimport {\n FULL_SANDBOX_GRANT,\n handleMethodRefusal,\n narrowerGrant,\n type HandleAccessPolicyIface,\n} from \"./grant.mjs\";\nimport { hasHostedMcpEndpoints } from \"./mcp-hosted-marker.mjs\";\nimport { createRpcPeer, type RpcPeerIface, type RpcRequestContextIface } from \"./rpc-peer.mjs\";\nimport {\n isMcpChannelEndpoint,\n isSandboxWorkerEndpoint,\n SandboxCapability,\n type McpChannelEndpointIface,\n type McpChannelIface,\n type NetworkSandboxSessionIface,\n type SandboxMcpEndpoint,\n type SandboxProcessIface,\n type SandboxProviderHandleIface,\n} from \"./types.mjs\";\nimport {\n createFrameChannelPair,\n frameChannelFromStream,\n frameChannelFromWebSocket,\n HANDLE_RPC_VERSION,\n HandleRpcCloseCode,\n handleRpcError,\n HandleRpcErrorCode,\n HandleRpcMethod,\n handleRpcMethodSchemas,\n parseHandleRpcMethod,\n type DescribeResultIface,\n type FrameChannelIface,\n type FrameStreamIface,\n type HandleRpcResult,\n type WebSocketLikeIface,\n type WireFrame,\n} from \"./wire.mjs\";\n\n// Serves the handle RPC (wire.ts) for a NetworkSandboxSessionIface. The session\n// service runs it for every provider at its stable per-binding endpoint, which\n// may lazily start the sandbox (through the provider) on the first call.\n\nexport type { HandleAccessPolicyIface } from \"./grant.mjs\";\n\n// Each method is gated by the connection's per-capability grant\n// (grant.ts HANDLE_METHOD_GATES) before it is dispatched.\nexport const DEFAULT_HANDLE_ACCESS: HandleAccessPolicyIface = {\n grant: FULL_SANDBOX_GRANT,\n lifecycle: false,\n};\n\nexport interface HandleAuthorizationIface {\n // When the credential expires; the server closes the connection then unless\n // the client refreshed it.\n expiresAt: string | null;\n // Narrows the server's access policy for this connection.\n access?: HandleAccessPolicyIface;\n}\n\n// Returns null to reject. `token` is null when the client sent none;\n// `identity` is the platform-identity assertion a sandbox provider's attach\n// socket presents (`initialize { identity }`, `identity/refresh`), else null.\nexport type HandleAuthorizeFn = (args: {\n token: string | null;\n identity?: string | null;\n}) => Promise<HandleAuthorizationIface | null>;\n\nexport type HandleLifecycle = Pick<\n SandboxProviderHandleIface<NetworkSandboxSessionIface>,\n 'onSandboxStop' | 'onSandboxDelete' | 'onRuntimeShutdown'\n>;\n\nexport interface HandleResolutionIface {\n sandbox: NetworkSandboxSessionIface;\n handle?: HandleLifecycle;\n access?: HandleAccessPolicyIface;\n}\n\nexport interface HandleRpcMessageHandlerOptionsIface {\n send: (frame: WireFrame) => void;\n close: (code: number, reason: string) => void;\n authorize: HandleAuthorizeFn;\n // Called once per connection, after `initialize` is authorized. The session\n // service's stable endpoint starts the sandbox here through its provider.\n resolve: (authorization: HandleAuthorizationIface) => Promise<HandleResolutionIface>;\n access?: HandleAccessPolicyIface;\n // Token presented in the connection request, used when `initialize` has none.\n connectionToken?: string | null;\n // Send stream chunks as binary frames (default true).\n binary?: boolean;\n // The outer host applies hosted-tool policy before exposing this transport.\n mcpChannels?: boolean;\n now?: () => number;\n // Runs for each validated operation, after binding access checks.\n authorizeOperation?: (context: RpcRequestContextIface) => Promise<void>;\n}\n\nexport interface HandleRpcMessageHandlerIface {\n onFrame(frame: WireFrame): void;\n onClose(code?: number, reason?: string): void;\n}\n\n// Computer use counts only when `sandbox/computerUse` can answer it: an MCP\n// channel endpoint does not cross this wire (its host re-addresses it, as the\n// session service does with withHostedMcpEndpoints).\nconst needsMcpChannels = (sandbox: NetworkSandboxSessionIface) =>\n hasSandboxExecutionGuard(sandbox) && !hasHostedMcpEndpoints(sandbox);\n\nconst servesComputerUse = async (sandbox: NetworkSandboxSessionIface): Promise<boolean> => {\n if (sandbox.computerUse == null || needsMcpChannels(sandbox)) return false;\n try {\n return !isMcpChannelEndpoint(await sandbox.computerUse());\n } catch {\n return false;\n }\n};\n\nconst capabilitiesOf = async (\n sandbox: NetworkSandboxSessionIface,\n mcpChannels = false,\n): Promise<SandboxCapability[]> => {\n const capabilities = [SandboxCapability.Files, SandboxCapability.Process];\n if (sandbox.ports.length > 0) capabilities.push(SandboxCapability.Ports);\n if (sandbox.setNetworkPolicy != null) capabilities.push(SandboxCapability.NetworkPolicy);\n if (sandbox.egress != null) capabilities.push(SandboxCapability.Egress);\n if (mcpChannels ? sandbox.computerUse != null : await servesComputerUse(sandbox))\n capabilities.push(SandboxCapability.ComputerUse);\n if (sandbox.screen != null) capabilities.push(SandboxCapability.Screen);\n if (sandbox.localMcp != null && (mcpChannels || !needsMcpChannels(sandbox)))\n capabilities.push(SandboxCapability.LocalMcp);\n if (sandbox.attachProcess != null) capabilities.push(SandboxCapability.DurableProcesses);\n if (sandbox.startWorker != null) capabilities.push(SandboxCapability.Workers);\n return capabilities;\n};\n\nexport const describeSandboxHandle = async (\n sandbox: NetworkSandboxSessionIface,\n mcpChannels = false,\n): Promise<DescribeResultIface> => ({\n handleRpcVersion: HANDLE_RPC_VERSION,\n id: sandbox.id,\n defaultWorkingDirectory: sandbox.defaultWorkingDirectory,\n ports: [...sandbox.ports],\n capabilities: await capabilitiesOf(sandbox, mcpChannels),\n description: sandbox.description,\n});\n\nconst narrowAccess = (\n base: HandleAccessPolicyIface,\n narrower: HandleAccessPolicyIface | undefined,\n): HandleAccessPolicyIface =>\n narrower == null\n ? base\n : {\n grant: narrowerGrant(base.grant, narrower.grant),\n lifecycle: base.lifecycle && narrower.lifecycle,\n };\n\nconst parseParams = <S extends z.ZodType>(schema: S, params: JsonValue): z.output<S> => {\n const parsed = schema.safeParse(params);\n if (!parsed.success) {\n throw handleRpcError({\n code: HandleRpcErrorCode.InvalidParams,\n message: z.prettifyError(parsed.error),\n });\n }\n return parsed.data;\n};\n\n// The upload stream ids a request names, read before full validation.\nconst uploadStreamIdsSchema = z.object({\n streamId: z.number().int().nonnegative().optional(),\n stdinStreamId: z.number().int().nonnegative().nullable().optional(),\n});\n\nconst PROCESS_CONTROL_METHODS: ReadonlySet<string> = new Set([\n HandleRpcMethod.ProcessWait,\n HandleRpcMethod.ProcessKill,\n HandleRpcMethod.ProcessDetach,\n]);\n\nconst processIdOf = (params: JsonValue): string | null => {\n const parsed = z.object({ processId: z.string() }).safeParse(params);\n return parsed.success ? parsed.data.processId : null;\n};\n\n// A worker's input stream: what the client writes, until it ends.\nconst pipeInto = async (\n source: ReadableStream<Uint8Array>,\n target: Pick<SandboxProcessIface, 'write'>,\n): Promise<void> => {\n const reader = source.getReader();\n for (;;) {\n const { done, value } = await reader.read();\n if (done) {\n await target.write(new Uint8Array(), { end: true });\n return;\n }\n await target.write(value);\n }\n};\n\nconst unsupported = (what: string) =>\n handleRpcError({ code: HandleRpcErrorCode.Unsupported, message: `this sandbox has no ${what}` });\n\n// Byte-range slice of a stream.\nconst sliceStream = (\n source: ReadableStream<Uint8Array>,\n offset: number,\n length: number | undefined,\n): ReadableStream<Uint8Array> => {\n let position = 0;\n const end = length == null ? Number.POSITIVE_INFINITY : offset + length;\n const reader = source.getReader();\n return new ReadableStream<Uint8Array>({\n pull: async (controller) => {\n for (;;) {\n if (position >= end) {\n controller.close();\n await reader.cancel().catch(() => undefined);\n return;\n }\n const { done, value } = await reader.read();\n if (done) {\n controller.close();\n return;\n }\n const chunkStart = position;\n position += value.byteLength;\n const from = Math.max(0, offset - chunkStart);\n const to = Math.min(value.byteLength, end - chunkStart);\n if (to > from) {\n controller.enqueue(value.subarray(from, to));\n return;\n }\n }\n },\n cancel: (reason) => reader.cancel(reason),\n });\n};\n\n// Low-level, transport-agnostic handler: feed it frames, it calls `send` and\n// `close`. Use it where the host owns the socket (Hono upgradeWebSocket, a\n// Durable Object's hibernation handlers, a relay).\nexport const createHandleRpcMessageHandler = (\n options: HandleRpcMessageHandlerOptionsIface,\n): HandleRpcMessageHandlerIface => {\n const now = options.now ?? Date.now;\n const [local, remote] = createFrameChannelPair();\n let ended = false;\n // `remote` is our side; frames the peer writes to it go out through `send`.\n remote.listen({\n frame: (frame) => options.send(frame),\n close: (info) => {\n if (!ended) {\n ended = true;\n options.close(info.code, info.reason);\n }\n },\n });\n const peerChannel: FrameChannelIface = local;\n const connection = createServerConnection({\n channel: peerChannel,\n authorize: options.authorize,\n resolve: options.resolve,\n access: options.access ?? DEFAULT_HANDLE_ACCESS,\n connectionToken: options.connectionToken ?? null,\n binary: options.binary ?? true,\n mcpChannels: options.mcpChannels,\n now,\n authorizeOperation: options.authorizeOperation,\n });\n return {\n onFrame: (frame) => remote.send(frame),\n onClose: (code, reason) => {\n ended = true;\n connection.close(code ?? 1000, reason ?? '');\n },\n };\n};\n\ninterface ServerConnectionIface {\n close(code: number, reason: string): void;\n}\n\n// A process served on one connection. `detach` is set for a durable process:\n// aborting it releases the handle and leaves the process running.\ninterface ServedProcessIface {\n process: Pick<SandboxProcessIface, 'wait' | 'kill'>;\n detach: AbortController | null;\n}\n\n// Ends a connection's hold on a process: detaches a durable one, kills any other.\nconst releaseProcess = async (served: ServedProcessIface): Promise<void> => {\n if (served.detach == null) await served.process.kill();\n else served.detach.abort(new Error('process handle released'));\n};\n\ninterface ServerConnectionArgsIface {\n channel: FrameChannelIface;\n authorize: HandleAuthorizeFn;\n resolve: (authorization: HandleAuthorizationIface) => Promise<HandleResolutionIface>;\n access: HandleAccessPolicyIface;\n connectionToken: string | null;\n binary: boolean;\n mcpChannels?: boolean;\n now: () => number;\n authorizeOperation?: (context: RpcRequestContextIface) => Promise<void>;\n}\n\nconst createServerConnection = (args: ServerConnectionArgsIface): ServerConnectionIface => {\n let sandbox: NetworkSandboxSessionIface | null = null;\n let access = args.access;\n let initializing = false;\n let handle: HandleLifecycle | null = null;\n let expiryTimer: ReturnType<typeof setTimeout> | null = null;\n const processes = new Map<string, ServedProcessIface>();\n // Process ids of worker programs, controlled as starting them is gated.\n const workers = new Set<string>();\n const mcpEndpoints = new Map<string, McpChannelEndpointIface>();\n const mcpConnections = new Map<string, McpChannelIface>();\n let nextMcpChannelId = 0;\n let shutdown: Promise<void> | null = null;\n // Incoming streams registered in beforeRequest, keyed by request id.\n const incomingByRequest = new Map<\n string | number,\n { streamId: number; stream: ReadableStream<Uint8Array> }\n >();\n\n const scheduleExpiry = (expiresAt: string | null) => {\n if (expiryTimer != null) clearTimeout(expiryTimer);\n expiryTimer = null;\n if (expiresAt == null) return;\n const delay = Date.parse(expiresAt) - args.now();\n if (Number.isNaN(delay)) return;\n expiryTimer = setTimeout(\n () =>\n delay > 2_147_483_647\n ? scheduleExpiry(expiresAt)\n : peer.close(HandleRpcCloseCode.Unauthorized, 'credential expired'),\n Math.max(0, Math.min(2_147_483_647, delay)),\n );\n };\n\n const requireSandbox = (): NetworkSandboxSessionIface => {\n if (sandbox == null) {\n throw handleRpcError({\n code: HandleRpcErrorCode.NotInitialized,\n message: 'initialize first',\n });\n }\n return sandbox;\n };\n\n const checkAccess = (method: HandleRpcMethod, params: JsonValue) => {\n const processId = processIdOf(params);\n const gated =\n PROCESS_CONTROL_METHODS.has(method) && processId != null && workers.has(processId)\n ? HandleRpcMethod.StartWorker\n : method;\n const refusal = handleMethodRefusal({ access, method: gated, params });\n if (refusal != null)\n throw handleRpcError({ code: HandleRpcErrorCode.Forbidden, message: refusal });\n };\n\n const featureFlags = (): Pick<DescribeResultIface, 'providerHooks' | 'mcpChannels'> => {\n const flags: Pick<DescribeResultIface, 'providerHooks' | 'mcpChannels'> = {};\n if (handle != null) flags.providerHooks = true;\n if (args.mcpChannels === true) flags.mcpChannels = true;\n return flags;\n };\n\n const initialize = async (\n params: JsonValue,\n ): Promise<HandleRpcResult<HandleRpcMethod.Initialize>> => {\n const parsed = parseParams(handleRpcMethodSchemas[HandleRpcMethod.Initialize].params, params);\n if (sandbox != null || initializing) {\n throw handleRpcError({\n code: HandleRpcErrorCode.InvalidRequest,\n message: 'already initialized',\n });\n }\n initializing = true;\n try {\n const token = parsed.token ?? args.connectionToken;\n const authorization = await args.authorize({ token, identity: parsed.identity ?? null });\n if (authorization == null) {\n setTimeout(() => peer.close(HandleRpcCloseCode.Unauthorized, 'unauthorized'), 0);\n throw handleRpcError({ code: HandleRpcErrorCode.Unauthorized, message: 'unauthorized' });\n }\n const resolution = await args.resolve(authorization);\n access = narrowAccess(narrowAccess(access, resolution.access), authorization.access);\n sandbox = resolution.sandbox;\n handle = resolution.handle ?? null;\n scheduleExpiry(authorization.expiresAt);\n return {\n ...(await describeSandboxHandle(sandbox, args.mcpChannels)),\n confinedFiles: true,\n ...featureFlags(),\n expiresAt: authorization.expiresAt,\n };\n } finally {\n initializing = false;\n }\n };\n\n const pump = (streamId: number, source: ReadableStream<Uint8Array>) => {\n peer.streams.openOutgoing(streamId, source).catch(() => undefined);\n };\n\n // Registers a process the provider just returned, unless the request was\n // cancelled or the connection closed or shut down meanwhile: then it is\n // released at once.\n const serve = (args: {\n processId: string;\n served: ServedProcessIface;\n signal: AbortSignal;\n stdout: { streamId: number; stream: ReadableStream<Uint8Array> };\n stderr: { streamId: number; stream: ReadableStream<Uint8Array> };\n }) => {\n if (args.signal.aborted || shutdown != null) {\n void releaseProcess(args.served).catch(() => undefined);\n throw handleRpcError({ code: HandleRpcErrorCode.Cancelled, message: 'request cancelled' });\n }\n processes.set(args.processId, args.served);\n pump(args.stdout.streamId, args.stdout.stream);\n pump(args.stderr.streamId, args.stderr.stream);\n };\n const servedProcess = (processId: string): ServedProcessIface => {\n const served = processes.get(processId);\n if (served == null)\n throw handleRpcError({ code: HandleRpcErrorCode.NotFound, message: 'no such process' });\n return served;\n };\n\n const mcpDescriptor = (endpoint: SandboxMcpEndpoint, key: string) => {\n if (!isMcpChannelEndpoint(endpoint)) return endpoint;\n if (args.mcpChannels !== true) throw unsupported('MCP channels over the handle RPC');\n mcpEndpoints.set(key, endpoint);\n return { name: endpoint.name, endpointKey: key };\n };\n const mcpConnection = (id: string): McpChannelIface => {\n const channel = mcpConnections.get(id);\n if (channel == null)\n throw handleRpcError({\n code: HandleRpcErrorCode.NotFound,\n message: 'MCP channel not found on this connection',\n });\n return channel;\n };\n\n // Fails a request's upload stream when the request fails, so the client\n // stops sending.\n const dispatch = async (context: RpcRequestContextIface): Promise<object> => {\n try {\n return await dispatchMethod(context);\n } catch (error) {\n const entry = incomingByRequest.get(context.id);\n incomingByRequest.delete(context.id);\n if (entry != null) peer.streams.cancelIncoming(entry.streamId, 'request failed');\n throw error;\n }\n };\n\n const dispatchMethod = async (context: RpcRequestContextIface): Promise<object> => {\n const method = parseHandleRpcMethod(context.method);\n if (method == null) {\n throw handleRpcError({\n code: HandleRpcErrorCode.MethodNotFound,\n message: `unknown method ${context.method}`,\n });\n }\n if (method === HandleRpcMethod.Initialize) return initialize(context.params);\n const target = requireSandbox();\n if (shutdown != null && method !== HandleRpcMethod.OnRuntimeShutdown)\n throw handleRpcError({\n code: HandleRpcErrorCode.ConnectionClosed,\n message: 'Provider handle is shutting down',\n });\n checkAccess(method, context.params);\n parseParams(handleRpcMethodSchemas[method].params, context.params);\n if (\n method === HandleRpcMethod.Egress &&\n parseParams(handleRpcMethodSchemas[HandleRpcMethod.Egress].params, context.params).action !==\n WorkspaceEgressAction.Status &&\n args.authorizeOperation == null\n )\n throw handleRpcError({\n code: HandleRpcErrorCode.Forbidden,\n message: 'Device egress changes require an operation authorization hook',\n });\n await args.authorizeOperation?.(context);\n if (context.signal.aborted)\n throw handleRpcError({ code: HandleRpcErrorCode.Cancelled, message: 'request cancelled' });\n const abortSignal = context.signal;\n switch (method) {\n case HandleRpcMethod.Describe:\n return {\n ...(await describeSandboxHandle(target, args.mcpChannels)),\n confinedFiles: true,\n ...featureFlags(),\n };\n case HandleRpcMethod.AuthRefresh: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n const authorization = await args.authorize({ token: params.token });\n if (authorization == null)\n throw handleRpcError({ code: HandleRpcErrorCode.Unauthorized, message: 'unauthorized' });\n access = narrowAccess(access, authorization.access);\n scheduleExpiry(authorization.expiresAt);\n return { expiresAt: authorization.expiresAt };\n }\n case HandleRpcMethod.IdentityRefresh: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n const authorization = await args.authorize({ token: null, identity: params.assertion });\n if (authorization == null)\n throw handleRpcError({ code: HandleRpcErrorCode.Unauthorized, message: 'unauthorized' });\n access = narrowAccess(access, authorization.access);\n scheduleExpiry(authorization.expiresAt);\n return { expiresAt: authorization.expiresAt };\n }\n case HandleRpcMethod.ReadFile: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n const stream =\n params.root == null\n ? await target.readFile({ path: params.path, abortSignal })\n : await (\n target.confinedFileReader?.readFile ??\n ((options) => confinedReadFile(target, options))\n )({ path: params.path, root: params.root, abortSignal });\n if (stream == null) return { found: false };\n const ranged =\n params.offset != null || params.length != null\n ? sliceStream(stream, params.offset ?? 0, params.length)\n : stream;\n // The client registered the stream before asking, so start right away.\n pump(params.streamId, ranged);\n return { found: true };\n }\n case HandleRpcMethod.ReadTextFile: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n const text = await target.readTextFile({ ...params, abortSignal });\n return { text };\n }\n case HandleRpcMethod.WriteFile: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n const incoming = incomingByRequest.get(context.id)?.stream ?? null;\n const content =\n incoming ??\n bytesToStream(\n params.contentBase64 == null ? new Uint8Array() : base64ToBytes(params.contentBase64),\n );\n await target.writeFile({ path: params.path, content, abortSignal });\n incomingByRequest.delete(context.id);\n return {};\n }\n case HandleRpcMethod.Spawn: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n const stdin = incomingByRequest.get(context.id)?.stream ?? null;\n if (processes.has(params.processId)) {\n throw handleRpcError({\n code: HandleRpcErrorCode.InvalidParams,\n message: 'processId already in use',\n });\n }\n const detach = params.durable === true ? new AbortController() : null;\n const child = await target.spawn({\n command: params.command,\n args: params.args,\n cwd: params.cwd,\n env: params.env,\n shell: params.shell,\n timeoutMs: params.timeoutMs,\n // A closed stdin is an empty stream.\n stdin: stdin ?? '',\n ...(detach == null ? {} : { durable: true, abortSignal: detach.signal }),\n });\n incomingByRequest.delete(context.id);\n const ref = child.ref ?? null;\n serve({\n processId: params.processId,\n // A sandbox that ignored `durable` gave an ordinary process.\n served: { process: child, detach: ref == null ? null : detach },\n signal: abortSignal,\n stdout: { streamId: params.stdoutStreamId, stream: child.stdout },\n stderr: { streamId: params.stderrStreamId, stream: child.stderr },\n });\n return { pid: child.pid, ref };\n }\n case HandleRpcMethod.StartWorker: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n if (target.startWorker == null) throw unsupported('worker programs');\n const stdin = incomingByRequest.get(context.id)?.stream ?? null;\n if (processes.has(params.processId))\n throw handleRpcError({\n code: HandleRpcErrorCode.InvalidParams,\n message: 'processId already in use',\n });\n const detach = params.durable === true ? new AbortController() : null;\n const started = await target.startWorker({\n program: params.program,\n env: params.env,\n input: params.input,\n ...(params.identity == null ? {} : { identity: params.identity }),\n ...(detach == null ? {} : { durable: true, abortSignal: detach.signal }),\n });\n const upload = incomingByRequest.get(context.id);\n incomingByRequest.delete(context.id);\n // The program serves its own endpoint: nothing flows on the request's streams.\n if (isSandboxWorkerEndpoint(started)) {\n if (upload != null) peer.streams.cancelIncoming(upload.streamId, 'worker endpoint');\n return { endpoint: started.endpoint };\n }\n const worker = started;\n if (stdin != null) void pipeInto(stdin, worker).catch(() => undefined);\n const ref = worker.ref ?? null;\n workers.add(params.processId);\n serve({\n processId: params.processId,\n served: { process: worker, detach: ref == null ? null : detach },\n signal: abortSignal,\n stdout: { streamId: params.stdoutStreamId, stream: worker.stdout },\n stderr: { streamId: params.stderrStreamId, stream: worker.stderr },\n });\n return { pid: worker.pid, ref };\n }\n case HandleRpcMethod.ProcessAttach: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n if (target.attachProcess == null) throw unsupported('durable processes');\n if (processes.has(params.processId))\n throw handleRpcError({\n code: HandleRpcErrorCode.InvalidParams,\n message: 'processId already in use',\n });\n const detach = new AbortController();\n // Until it is served, cancelling the request (or closing the connection)\n // cancels the attach; afterwards the handle lives until released.\n const cancelAttach = () => detach.abort(abortSignal.reason);\n abortSignal.addEventListener('abort', cancelAttach, { once: true });\n let attached: Awaited<ReturnType<NonNullable<typeof target.attachProcess>>>;\n try {\n attached = await target.attachProcess({\n ref: params.ref,\n stdoutOffset: params.stdoutOffset,\n stderrOffset: params.stderrOffset,\n abortSignal: detach.signal,\n });\n } finally {\n abortSignal.removeEventListener('abort', cancelAttach);\n }\n if (attached == null)\n return {\n found: false,\n stdoutOffset: params.stdoutOffset,\n stderrOffset: params.stderrOffset,\n };\n serve({\n processId: params.processId,\n served: { process: attached, detach },\n signal: abortSignal,\n stdout: { streamId: params.stdoutStreamId, stream: attached.stdout },\n stderr: { streamId: params.stderrStreamId, stream: attached.stderr },\n });\n return {\n found: true,\n stdoutOffset: attached.stdoutOffset,\n stderrOffset: attached.stderrOffset,\n };\n }\n case HandleRpcMethod.ProcessWait: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n const child = servedProcess(params.processId).process;\n const result = await new Promise<{ exitCode: number }>((resolve, reject) => {\n const onAbort = () =>\n reject(handleRpcError({ code: HandleRpcErrorCode.Cancelled, message: 'cancelled' }));\n abortSignal.addEventListener('abort', onAbort, { once: true });\n child.wait().then(\n (value) => {\n abortSignal.removeEventListener('abort', onAbort);\n resolve(value);\n },\n (cause: unknown) => {\n abortSignal.removeEventListener('abort', onAbort);\n reject(cause);\n },\n );\n });\n processes.delete(params.processId);\n workers.delete(params.processId);\n return result;\n }\n case HandleRpcMethod.ProcessDetach: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n const served = processes.get(params.processId);\n // Detaching what is already gone (exited and released, or never known) is done.\n if (served == null) return {};\n if (served.detach == null) throw unsupported('detaching an ordinary process');\n processes.delete(params.processId);\n workers.delete(params.processId);\n await releaseProcess(served);\n return {};\n }\n case HandleRpcMethod.ProcessKill: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n await servedProcess(params.processId).process.kill(params.signal);\n return {};\n }\n case HandleRpcMethod.Run: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n return target.run({ ...params, abortSignal });\n }\n case HandleRpcMethod.Stat: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n return {\n stat:\n params.root == null\n ? await target.stat({ path: params.path, abortSignal })\n : await (\n target.confinedFileReader?.stat ?? ((options) => confinedStat(target, options))\n )({\n path: params.path,\n root: params.root,\n abortSignal,\n }),\n };\n }\n case HandleRpcMethod.ReadDir: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n return {\n entries:\n params.root == null\n ? await target.readDir({ path: params.path, abortSignal })\n : await (\n target.confinedFileReader?.readDir ??\n ((options) => confinedReadDir(target, options))\n )({\n path: params.path,\n root: params.root,\n abortSignal,\n }),\n };\n }\n case HandleRpcMethod.RemovePath: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n await target.removePath({ ...params, abortSignal });\n return {};\n }\n case HandleRpcMethod.GetPortEndpoint: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n return target.getPortEndpoint(params);\n }\n case HandleRpcMethod.Stop:\n await target.stop();\n return {};\n case HandleRpcMethod.Destroy:\n await target.destroy();\n return {};\n case HandleRpcMethod.OnRuntimeShutdown: {\n if (handle == null) throw unsupported('provider lifecycle hooks');\n const shutdownHandle = handle;\n shutdown ??= (async () => {\n await Promise.allSettled([...processes.values()].map(releaseProcess));\n await Promise.allSettled([...mcpConnections.values()].map((channel) => channel.close()));\n processes.clear();\n mcpConnections.clear();\n mcpEndpoints.clear();\n await shutdownHandle.onRuntimeShutdown();\n })();\n await shutdown;\n return {};\n }\n case HandleRpcMethod.OnSandboxStop:\n if (handle == null) throw unsupported('provider lifecycle hooks');\n await handle.onSandboxStop();\n return {};\n case HandleRpcMethod.OnSandboxDelete: {\n if (handle == null) throw unsupported('provider lifecycle hooks');\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n await handle.onSandboxDelete(params);\n return {};\n }\n case HandleRpcMethod.SetNetworkPolicy: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n if (target.setNetworkPolicy == null) throw unsupported('network policy');\n await target.setNetworkPolicy(params);\n return {};\n }\n case HandleRpcMethod.Egress: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n if (target.egress == null) throw unsupported('Device egress');\n return handleRpcMethodSchemas[HandleRpcMethod.Egress].result.parse(\n await target.egress(params),\n );\n }\n case HandleRpcMethod.ComputerUse: {\n if (target.computerUse == null) throw unsupported('computer use');\n if (needsMcpChannels(target) && args.mcpChannels !== true)\n throw unsupported('guarded MCP transport; negotiate mcpChannels');\n const endpoint = await target.computerUse();\n return mcpDescriptor(endpoint, 'computerUse');\n }\n case HandleRpcMethod.McpOpen: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n const endpoint = mcpEndpoints.get(params.endpointKey);\n if (args.mcpChannels !== true || endpoint == null)\n throw unsupported('MCP channel endpoint');\n const channel = await endpoint.connect({ abortSignal });\n if (abortSignal.aborted) {\n await channel.close();\n abortSignal.throwIfAborted();\n }\n const channelId = String(++nextMcpChannelId);\n mcpConnections.set(channelId, channel);\n return { channelId };\n }\n case HandleRpcMethod.McpSend: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n await mcpConnection(params.channelId).send(params.message, { abortSignal });\n return {};\n }\n case HandleRpcMethod.McpReceive: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n return { messages: await mcpConnection(params.channelId).receive({ abortSignal }) };\n }\n case HandleRpcMethod.McpClose: {\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n const channel = mcpConnection(params.channelId);\n await channel.close();\n mcpConnections.delete(params.channelId);\n return {};\n }\n case HandleRpcMethod.Screen: {\n if (target.screen == null) throw unsupported('screen');\n const params = parseParams(handleRpcMethodSchemas[method].params, context.params);\n return target.screen(params);\n }\n case HandleRpcMethod.LocalMcp:\n if (target.localMcp == null) throw unsupported('local MCP servers');\n if (needsMcpChannels(target) && args.mcpChannels !== true)\n throw unsupported('guarded MCP transport; negotiate mcpChannels');\n return {\n endpoints: (await target.localMcp()).flatMap((endpoint, index) =>\n args.mcpChannels !== true && isMcpChannelEndpoint(endpoint)\n ? []\n : [mcpDescriptor(endpoint, `localMcp:${index}:${endpoint.name}`)],\n ),\n };\n }\n };\n\n // Registers client-to-server streams synchronously, before their chunks.\n const beforeRequest = (context: RpcRequestContextIface) => {\n if (\n context.method !== HandleRpcMethod.WriteFile &&\n context.method !== HandleRpcMethod.Spawn &&\n context.method !== HandleRpcMethod.StartWorker\n )\n return;\n const ids = uploadStreamIdsSchema.safeParse(context.params);\n if (!ids.success) return;\n const streamId =\n context.method === HandleRpcMethod.WriteFile ? ids.data.streamId : ids.data.stdinStreamId;\n if (streamId == null) return;\n const stream = peer.streams.openIncoming(streamId);\n // Reject unauthorized or disallowed uploads before buffering their data.\n if (\n sandbox == null ||\n handleMethodRefusal({\n access,\n method:\n context.method === HandleRpcMethod.WriteFile ||\n context.method === HandleRpcMethod.StartWorker\n ? context.method\n : HandleRpcMethod.Spawn,\n params: context.params,\n }) != null\n ) {\n peer.streams.cancelIncoming(streamId, 'rejected');\n return;\n }\n incomingByRequest.set(context.id, { streamId, stream });\n };\n\n const onClose = () => {\n if (expiryTimer != null) clearTimeout(expiryTimer);\n for (const served of processes.values()) releaseProcess(served).catch(() => undefined);\n for (const channel of mcpConnections.values()) void channel.close().catch(() => undefined);\n mcpConnections.clear();\n mcpEndpoints.clear();\n processes.clear();\n incomingByRequest.clear();\n };\n\n const peer: RpcPeerIface = createRpcPeer({\n channel: args.channel,\n binary: args.binary,\n onRequest: dispatch,\n beforeRequest,\n onClose,\n });\n\n return { close: (code, reason) => peer.close(code, reason) };\n};\n\nexport interface ServeSandboxHandleArgsIface {\n sandbox: NetworkSandboxSessionIface;\n handle?: HandleLifecycle;\n authorize: HandleAuthorizeFn;\n authorizeOperation?: HandleRpcMessageHandlerOptionsIface['authorizeOperation'];\n access?: HandleAccessPolicyIface;\n binary?: boolean;\n // The outer host applies hosted-tool policy before exposing this transport.\n mcpChannels?: boolean;\n now?: () => number;\n}\n\nexport interface SandboxHandleServerIface {\n // Attaches a connection; returns a function that closes it.\n attach(channel: FrameChannelIface, context?: { token?: string | null }): () => void;\n attachWebSocket(socket: WebSocketLikeIface, context?: { token?: string | null }): () => void;\n attachStream(stream: FrameStreamIface, context?: { token?: string | null }): () => void;\n messageHandler(args: {\n send: (frame: WireFrame) => void;\n close: (code: number, reason: string) => void;\n token?: string | null;\n }): HandleRpcMessageHandlerIface;\n}\n\nexport const serveSandboxHandle = (args: ServeSandboxHandleArgsIface): SandboxHandleServerIface => {\n const access = args.access ?? DEFAULT_HANDLE_ACCESS;\n const resolve = async (): Promise<HandleResolutionIface> => ({\n sandbox: args.sandbox,\n handle: args.handle,\n });\n const attach = (channel: FrameChannelIface, context?: { token?: string | null }) => {\n const connection = createServerConnection({\n channel,\n authorize: args.authorize,\n authorizeOperation: args.authorizeOperation,\n resolve,\n access,\n connectionToken: context?.token ?? null,\n binary: args.binary ?? true,\n mcpChannels: args.mcpChannels,\n now: args.now ?? Date.now,\n });\n return () => connection.close(HandleRpcCloseCode.Normal, 'closed');\n };\n return {\n attach,\n attachWebSocket: (socket, context) =>\n attach(frameChannelFromWebSocket(socket).channel, context),\n attachStream: (stream, context) => attach(frameChannelFromStream(stream), context),\n messageHandler: (handlerArgs) =>\n createHandleRpcMessageHandler({\n send: handlerArgs.send,\n close: handlerArgs.close,\n authorize: args.authorize,\n authorizeOperation: args.authorizeOperation,\n resolve,\n access,\n connectionToken: handlerArgs.token ?? null,\n binary: args.binary,\n mcpChannels: args.mcpChannels,\n now: args.now,\n }),\n };\n};\n"],
|
|
5
|
+
"mappings": "AAAA,YAAY,OAAO;AACnB,SAAS,6BAA6B;AAEtC,SAAS,eAAe,qBAAqB;AAC7C,SAAS,iBAAiB,kBAAkB,oBAAoB;AAChE,SAAS,gCAAgC;AACzC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,6BAA6B;AACtC,SAAS,qBAAqE;AAC9E;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAOK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAOK;AAUA,MAAM,wBAAiD;AAAA,EAC5D,OAAO;AAAA,EACP,WAAW;AACb;AAwDA,MAAM,mBAAmB,CAAC,YACxB,yBAAyB,OAAO,KAAK,CAAC,sBAAsB,OAAO;AAErE,MAAM,oBAAoB,OAAO,YAA0D;AACzF,MAAI,QAAQ,eAAe,QAAQ,iBAAiB,OAAO,EAAG,QAAO;AACrE,MAAI;AACF,WAAO,CAAC,qBAAqB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UAAM,aAAa,uBAAuB;AAAA,MACxC;AAAA,MACA,WAAW,KAAK;AAAA,MAChB,oBAAoB,KAAK;AAAA,MACzB;AAAA,MACA;AAAA,MACA,iBAAiB,SAAS,SAAS;AAAA,MACnC,QAAQ,KAAK,UAAU;AAAA,MACvB,aAAa,KAAK;AAAA,MAClB,KAAK,KAAK,OAAO,KAAK;AAAA,IACxB,CAAC;AACD,WAAO,MAAM,WAAW,MAAM,mBAAmB,QAAQ,QAAQ;AAAA,EACnE;AACA,SAAO;AAAA,IACL;AAAA,IACA,iBAAiB,CAAC,QAAQ,YACxB,OAAO,0BAA0B,MAAM,EAAE,SAAS,OAAO;AAAA,IAC3D,cAAc,CAAC,QAAQ,YAAY,OAAO,uBAAuB,MAAM,GAAG,OAAO;AAAA,IACjF,gBAAgB,CAAC,gBACf,8BAA8B;AAAA,MAC5B,MAAM,YAAY;AAAA,MAClB,OAAO,YAAY;AAAA,MACnB,WAAW,KAAK;AAAA,MAChB,oBAAoB,KAAK;AAAA,MACzB;AAAA,MACA;AAAA,MACA,iBAAiB,YAAY,SAAS;AAAA,MACtC,QAAQ,KAAK;AAAA,MACb,aAAa,KAAK;AAAA,MAClB,KAAK,KAAK;AAAA,IACZ,CAAC;AAAA,EACL;AACF;",
|
|
6
6
|
"names": ["args"]
|
|
7
7
|
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import * as z from 'zod';
|
|
2
|
+
import type { NetworkSandboxSessionIface, SandboxRepositoriesIface } from "../types.mjs";
|
|
3
|
+
import type { SandboxSetupIface } from "./schema.mjs";
|
|
4
|
+
export declare const SETUP_STEP_TIMEOUT_MS: number;
|
|
5
|
+
export declare enum SandboxSetupPhase {
|
|
6
|
+
Checkout = "checkout",
|
|
7
|
+
Commands = "commands",
|
|
8
|
+
Steps = "steps"
|
|
9
|
+
}
|
|
10
|
+
export declare const sandboxSetupStateSchema: z.ZodObject<{
|
|
11
|
+
setup: z.ZodString;
|
|
12
|
+
done: z.ZodDefault<z.ZodArray<z.ZodEnum<typeof SandboxSetupPhase>>>;
|
|
13
|
+
steps: z.ZodDefault<z.ZodNumber>;
|
|
14
|
+
services: z.ZodDefault<z.ZodArray<z.ZodString>>;
|
|
15
|
+
}, z.core.$strip>;
|
|
16
|
+
export type SandboxSetupStateIface = z.output<typeof sandboxSetupStateSchema>;
|
|
17
|
+
export type SetupHandleIface = Pick<NetworkSandboxSessionIface, 'defaultWorkingDirectory' | 'run' | 'stat' | 'writeTextFile' | 'getPortUrl'>;
|
|
18
|
+
export interface SetupSecretsIface {
|
|
19
|
+
get(name: string): Promise<string | null>;
|
|
20
|
+
}
|
|
21
|
+
export interface ApplySandboxSetupArgsIface {
|
|
22
|
+
handle: SetupHandleIface;
|
|
23
|
+
setup: SandboxSetupIface;
|
|
24
|
+
secrets: SetupSecretsIface;
|
|
25
|
+
state: SandboxSetupStateIface | null;
|
|
26
|
+
attachment: {
|
|
27
|
+
fresh: boolean;
|
|
28
|
+
booted: boolean;
|
|
29
|
+
};
|
|
30
|
+
repositories: SandboxRepositoriesIface;
|
|
31
|
+
sandboxId: string;
|
|
32
|
+
saveState?: (state: SandboxSetupStateIface) => Promise<void>;
|
|
33
|
+
log?: (message: string, fields?: Record<string, string | number | boolean | null>) => void;
|
|
34
|
+
}
|
|
35
|
+
export interface AppliedSandboxSetupIface {
|
|
36
|
+
state: SandboxSetupStateIface;
|
|
37
|
+
environment: Record<string, string>;
|
|
38
|
+
commandsDirectory: string;
|
|
39
|
+
}
|
|
40
|
+
export declare const setupHash: (setup: SandboxSetupIface) => Promise<string>;
|
|
41
|
+
export declare const applySandboxSetup: (args: ApplySandboxSetupArgsIface) => Promise<AppliedSandboxSetupIface>;
|