@finalai/agent-provider 0.9.0 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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 +0 -3
- package/dist/modules/channel.mjs.map +1 -1
- 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 +1 -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 -791
- package/dist/modules/manifest.mjs +0 -322
- 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
|
@@ -0,0 +1,381 @@
|
|
|
1
|
+
import {
|
|
2
|
+
SANDBOX_PROVIDER_MAX_BODY_BYTES,
|
|
3
|
+
SANDBOX_PROVIDER_NDJSON_CONTENT_TYPE,
|
|
4
|
+
SANDBOX_PROVIDER_WIRE_VERSION,
|
|
5
|
+
SandboxProviderErrorCode,
|
|
6
|
+
SandboxProviderWirePath,
|
|
7
|
+
sandboxArtifactKeyResultSchema,
|
|
8
|
+
sandboxAttachReplyFrameSchema,
|
|
9
|
+
sandboxOfferResultSchema,
|
|
10
|
+
sandboxProcessesResultSchema
|
|
11
|
+
} from "@finalai/agent-protocol/sandbox-provider-wire";
|
|
12
|
+
import * as z from "zod";
|
|
13
|
+
import { jsonValueSchema } from "../../json.mjs";
|
|
14
|
+
import { toolDescriptorSchema } from "../../tool-descriptor.mjs";
|
|
15
|
+
import { connectSandboxClient } from "../client.mjs";
|
|
16
|
+
import { sandboxEditorResultSchema } from "../editor.mjs";
|
|
17
|
+
import { withSandboxOverrides } from "../overrides.mjs";
|
|
18
|
+
import { sandboxSnapshotResponseSchema } from "../snapshots.mjs";
|
|
19
|
+
import {
|
|
20
|
+
defineSandboxProvider,
|
|
21
|
+
SandboxCapability
|
|
22
|
+
} from "../types.mjs";
|
|
23
|
+
import {
|
|
24
|
+
frameChannelFromWebSocket,
|
|
25
|
+
handleRpcClientProtocols,
|
|
26
|
+
handleRpcError,
|
|
27
|
+
HandleRpcErrorCode
|
|
28
|
+
} from "../wire.mjs";
|
|
29
|
+
import { sandboxProviderWireError } from "./errors.mjs";
|
|
30
|
+
import { readWireAnswer } from "./ndjson.mjs";
|
|
31
|
+
import { preambleChannel } from "./preamble.mjs";
|
|
32
|
+
const ASSERTION_RENEW_MS = 4 * 6e4;
|
|
33
|
+
const offerSchema = sandboxOfferResultSchema;
|
|
34
|
+
const stateResultSchema = z.object({ state: jsonValueSchema });
|
|
35
|
+
const createResultSchema = z.object({
|
|
36
|
+
state: jsonValueSchema,
|
|
37
|
+
region: z.string().nullable().default(null)
|
|
38
|
+
});
|
|
39
|
+
const prepareResultSchema = z.object({ artifact: jsonValueSchema });
|
|
40
|
+
const descriptorsOf = (tools) => tools.flatMap((tool) => {
|
|
41
|
+
const parsed = toolDescriptorSchema.safeParse(tool);
|
|
42
|
+
return parsed.success ? [parsed.data] : [];
|
|
43
|
+
});
|
|
44
|
+
const isSandboxCapability = (value) => Object.values(SandboxCapability).some((capability) => capability === value);
|
|
45
|
+
const capabilitiesOf = (values) => values.filter(isSandboxCapability);
|
|
46
|
+
const catalogOf = (catalog) => catalog == null ? null : {
|
|
47
|
+
computerUse: catalog.computerUse == null ? null : descriptorsOf(catalog.computerUse),
|
|
48
|
+
localMcp: catalog.localMcp == null ? null : Object.fromEntries(
|
|
49
|
+
Object.entries(catalog.localMcp).map(([name, tools]) => [
|
|
50
|
+
name,
|
|
51
|
+
descriptorsOf(tools)
|
|
52
|
+
])
|
|
53
|
+
),
|
|
54
|
+
...catalog.localMcpIncomplete == null ? {} : { localMcpIncomplete: catalog.localMcpIncomplete }
|
|
55
|
+
};
|
|
56
|
+
const attachUrlOf = (url) => {
|
|
57
|
+
const target = new URL(`${url.replace(/\/+$/u, "")}${SandboxProviderWirePath.Attach}`);
|
|
58
|
+
target.protocol = target.protocol === "http:" ? "ws:" : "wss:";
|
|
59
|
+
return target.toString();
|
|
60
|
+
};
|
|
61
|
+
const withPlatformEnvironment = (ctx, client) => {
|
|
62
|
+
const platformEnvironment = ctx.platformEnvironment;
|
|
63
|
+
if (platformEnvironment == null) return client;
|
|
64
|
+
const envOf = async (env) => ({
|
|
65
|
+
...env,
|
|
66
|
+
...await platformEnvironment()
|
|
67
|
+
});
|
|
68
|
+
const overrides = {
|
|
69
|
+
spawn: async (options) => client.spawn({ ...options, env: await envOf(options.env) }),
|
|
70
|
+
run: async (options) => client.run({ ...options, env: await envOf(options.env) })
|
|
71
|
+
};
|
|
72
|
+
const startWorker = client.startWorker;
|
|
73
|
+
if (startWorker != null)
|
|
74
|
+
overrides.startWorker = async (options) => startWorker({ ...options, env: await envOf(options.env) });
|
|
75
|
+
return withSandboxOverrides(client, overrides);
|
|
76
|
+
};
|
|
77
|
+
const remoteSandboxProvider = (args) => {
|
|
78
|
+
const { registration } = args;
|
|
79
|
+
const doFetch = args.fetch ?? fetch;
|
|
80
|
+
const openSocket = args.openSocket ?? ((url, protocols) => {
|
|
81
|
+
const WebSocketImpl = args.WebSocket ?? globalThis.WebSocket;
|
|
82
|
+
if (WebSocketImpl == null) throw new Error("no WebSocket implementation; pass WebSocket");
|
|
83
|
+
return new WebSocketImpl(url, protocols);
|
|
84
|
+
});
|
|
85
|
+
const baseUrl = registration.url.replace(/\/+$/u, "");
|
|
86
|
+
const assertionFor = async (ctx, sandboxId) => {
|
|
87
|
+
const userId = await ctx.actingUser.current();
|
|
88
|
+
const token = await args.mintAssertion({
|
|
89
|
+
providerId: registration.id,
|
|
90
|
+
audience: registration.url,
|
|
91
|
+
organizationId: ctx.organizationId,
|
|
92
|
+
projectId: ctx.projectId,
|
|
93
|
+
sandboxId,
|
|
94
|
+
userId
|
|
95
|
+
});
|
|
96
|
+
return { token, userId };
|
|
97
|
+
};
|
|
98
|
+
const secretsOf = (ctx) => args.forwardedSecrets({ organizationId: ctx.organizationId, projectId: ctx.projectId });
|
|
99
|
+
const implementation = (environment) => {
|
|
100
|
+
const call = async (call2) => {
|
|
101
|
+
const [{ token }, secrets] = await Promise.all([
|
|
102
|
+
assertionFor(call2.ctx, call2.sandboxId),
|
|
103
|
+
secretsOf(call2.ctx)
|
|
104
|
+
]);
|
|
105
|
+
const body = JSON.stringify({
|
|
106
|
+
wire: SANDBOX_PROVIDER_WIRE_VERSION,
|
|
107
|
+
environment,
|
|
108
|
+
secrets,
|
|
109
|
+
...call2.fields
|
|
110
|
+
});
|
|
111
|
+
if (new TextEncoder().encode(body).byteLength > SANDBOX_PROVIDER_MAX_BODY_BYTES)
|
|
112
|
+
throw sandboxProviderWireError({
|
|
113
|
+
code: SandboxProviderErrorCode.InvalidEnvironment,
|
|
114
|
+
message: `the ${call2.path} request is over the sandbox provider wire's size limit`,
|
|
115
|
+
retryable: false
|
|
116
|
+
});
|
|
117
|
+
const response = await doFetch(`${baseUrl}${call2.path}`, {
|
|
118
|
+
method: "POST",
|
|
119
|
+
headers: {
|
|
120
|
+
authorization: `Bearer ${token}`,
|
|
121
|
+
"content-type": "application/json",
|
|
122
|
+
accept: `application/json, ${SANDBOX_PROVIDER_NDJSON_CONTENT_TYPE}`
|
|
123
|
+
},
|
|
124
|
+
body
|
|
125
|
+
});
|
|
126
|
+
const parsed = call2.result.safeParse(await readWireAnswer(response));
|
|
127
|
+
if (!parsed.success)
|
|
128
|
+
throw sandboxProviderWireError({
|
|
129
|
+
code: SandboxProviderErrorCode.Unavailable,
|
|
130
|
+
message: `unexpected ${call2.path} answer from ${registration.name}: ${z.prettifyError(parsed.error)}`,
|
|
131
|
+
retryable: false
|
|
132
|
+
});
|
|
133
|
+
return parsed.data;
|
|
134
|
+
};
|
|
135
|
+
const offers = /* @__PURE__ */ new WeakMap();
|
|
136
|
+
const offerOf = (ctx) => {
|
|
137
|
+
const existing = offers.get(ctx);
|
|
138
|
+
if (existing != null) return existing;
|
|
139
|
+
const offer = call({
|
|
140
|
+
path: SandboxProviderWirePath.Offer,
|
|
141
|
+
ctx,
|
|
142
|
+
sandboxId: ctx.sandboxId ?? null,
|
|
143
|
+
fields: { sandboxId: ctx.sandboxId ?? null },
|
|
144
|
+
result: offerSchema
|
|
145
|
+
});
|
|
146
|
+
offers.set(ctx, offer);
|
|
147
|
+
offer.catch(() => offers.delete(ctx));
|
|
148
|
+
return offer;
|
|
149
|
+
};
|
|
150
|
+
const requireSandboxId = (ctx) => {
|
|
151
|
+
if (ctx.sandboxId == null) throw new Error("this call needs the sandbox it is about");
|
|
152
|
+
return ctx.sandboxId;
|
|
153
|
+
};
|
|
154
|
+
const attachSocket = async (ctx, attach) => {
|
|
155
|
+
const [first, secrets] = await Promise.all([
|
|
156
|
+
assertionFor(ctx, ctx.sandboxId),
|
|
157
|
+
secretsOf(ctx)
|
|
158
|
+
]);
|
|
159
|
+
let identity = { ...first, mintedAt: Date.now() };
|
|
160
|
+
const { channel, opened } = frameChannelFromWebSocket(
|
|
161
|
+
openSocket(attachUrlOf(registration.url), handleRpcClientProtocols(first.token))
|
|
162
|
+
);
|
|
163
|
+
await opened;
|
|
164
|
+
const preamble = preambleChannel(channel);
|
|
165
|
+
channel.send(
|
|
166
|
+
JSON.stringify({
|
|
167
|
+
type: "attach",
|
|
168
|
+
wire: SANDBOX_PROVIDER_WIRE_VERSION,
|
|
169
|
+
environment,
|
|
170
|
+
secrets,
|
|
171
|
+
sandboxId: ctx.sandboxId,
|
|
172
|
+
artifact: attach.artifact,
|
|
173
|
+
state: attach.state,
|
|
174
|
+
passive: attach.passive,
|
|
175
|
+
platformEgressHosts: ctx.platformEgressHosts ?? [],
|
|
176
|
+
lifecycle: ctx.lifecycle
|
|
177
|
+
})
|
|
178
|
+
);
|
|
179
|
+
let attached = null;
|
|
180
|
+
try {
|
|
181
|
+
while (attached == null) {
|
|
182
|
+
const frame = await preamble.next();
|
|
183
|
+
if (typeof frame !== "string") throw new Error("the attach reply must be a text frame");
|
|
184
|
+
const reply = sandboxAttachReplyFrameSchema.parse(JSON.parse(frame));
|
|
185
|
+
if (reply.type === "error") throw sandboxProviderWireError(reply.error);
|
|
186
|
+
if (reply.type === "attached") attached = reply;
|
|
187
|
+
}
|
|
188
|
+
} catch (cause) {
|
|
189
|
+
channel.close();
|
|
190
|
+
throw cause;
|
|
191
|
+
}
|
|
192
|
+
let handed = false;
|
|
193
|
+
const openChannel = async () => {
|
|
194
|
+
if (handed)
|
|
195
|
+
throw handleRpcError({
|
|
196
|
+
code: HandleRpcErrorCode.ConnectionClosed,
|
|
197
|
+
message: `the ${registration.name} attach socket closed; attach again`,
|
|
198
|
+
retryable: true
|
|
199
|
+
});
|
|
200
|
+
handed = true;
|
|
201
|
+
return preamble.rest();
|
|
202
|
+
};
|
|
203
|
+
try {
|
|
204
|
+
const client = await connectSandboxClient({
|
|
205
|
+
url: attachUrlOf(registration.url),
|
|
206
|
+
token: "",
|
|
207
|
+
openChannel,
|
|
208
|
+
reconnect: { attempts: 1 },
|
|
209
|
+
identity: async ({ renew }) => {
|
|
210
|
+
const userId = await ctx.actingUser.current();
|
|
211
|
+
if (renew || userId !== identity.userId || Date.now() - identity.mintedAt >= ASSERTION_RENEW_MS) {
|
|
212
|
+
const next = await assertionFor(ctx, ctx.sandboxId);
|
|
213
|
+
identity = { ...next, mintedAt: Date.now() };
|
|
214
|
+
}
|
|
215
|
+
return identity.token;
|
|
216
|
+
}
|
|
217
|
+
});
|
|
218
|
+
return { client, attached };
|
|
219
|
+
} catch (cause) {
|
|
220
|
+
channel.close();
|
|
221
|
+
throw cause;
|
|
222
|
+
}
|
|
223
|
+
};
|
|
224
|
+
const handleOf = (client, sandbox) => ({
|
|
225
|
+
sandbox,
|
|
226
|
+
onSandboxStop: () => client.onSandboxStop(),
|
|
227
|
+
onSandboxDelete: (options) => client.onSandboxDelete(options),
|
|
228
|
+
onRuntimeShutdown: async () => {
|
|
229
|
+
try {
|
|
230
|
+
await client.onRuntimeShutdown();
|
|
231
|
+
} catch {
|
|
232
|
+
} finally {
|
|
233
|
+
client.close();
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
});
|
|
237
|
+
const result = {
|
|
238
|
+
capabilities: async (ctx) => ({ ...(await offerOf(ctx)).capabilities }),
|
|
239
|
+
runtimes: async (ctx) => (await offerOf(ctx)).runtimes,
|
|
240
|
+
features: async (ctx) => {
|
|
241
|
+
const { features } = await offerOf(ctx);
|
|
242
|
+
return features == null ? null : capabilitiesOf(features);
|
|
243
|
+
},
|
|
244
|
+
additionalFeatures: async (ctx) => capabilitiesOf((await offerOf(ctx)).additionalFeatures),
|
|
245
|
+
mcpCatalog: async (ctx) => catalogOf((await offerOf(ctx)).mcpCatalog),
|
|
246
|
+
artifactKey: async (ctx) => (await call({
|
|
247
|
+
path: SandboxProviderWirePath.ArtifactKey,
|
|
248
|
+
ctx,
|
|
249
|
+
sandboxId: null,
|
|
250
|
+
fields: {
|
|
251
|
+
files: ctx.files,
|
|
252
|
+
resources: ctx.resources,
|
|
253
|
+
sourceRevision: ctx.sourceRevision
|
|
254
|
+
},
|
|
255
|
+
result: sandboxArtifactKeyResultSchema
|
|
256
|
+
})).key,
|
|
257
|
+
prepare: async (ctx) => (await call({
|
|
258
|
+
path: SandboxProviderWirePath.Prepare,
|
|
259
|
+
ctx,
|
|
260
|
+
sandboxId: null,
|
|
261
|
+
fields: {
|
|
262
|
+
files: ctx.files,
|
|
263
|
+
resources: ctx.resources,
|
|
264
|
+
sourceRevision: ctx.sourceRevision
|
|
265
|
+
},
|
|
266
|
+
result: prepareResultSchema
|
|
267
|
+
})).artifact,
|
|
268
|
+
create: async (ctx, create) => call({
|
|
269
|
+
path: SandboxProviderWirePath.Create,
|
|
270
|
+
ctx,
|
|
271
|
+
sandboxId: ctx.sandboxId,
|
|
272
|
+
fields: {
|
|
273
|
+
sandboxId: ctx.sandboxId,
|
|
274
|
+
artifact: create.artifact,
|
|
275
|
+
setup: create.setup == null ? null : jsonValueSchema.parse(create.setup),
|
|
276
|
+
platformEgressHosts: ctx.platformEgressHosts ?? [],
|
|
277
|
+
lifecycle: { parkAfterIdleMs: ctx.lifecycle.parkAfterIdleMs }
|
|
278
|
+
},
|
|
279
|
+
result: createResultSchema
|
|
280
|
+
}),
|
|
281
|
+
awaitRunning: async (ctx, state, options) => {
|
|
282
|
+
await call({
|
|
283
|
+
path: SandboxProviderWirePath.AwaitRunning,
|
|
284
|
+
ctx,
|
|
285
|
+
sandboxId: ctx.sandboxId,
|
|
286
|
+
fields: { sandboxId: ctx.sandboxId, state, timeoutMs: options.timeoutMs },
|
|
287
|
+
result: z.object({})
|
|
288
|
+
});
|
|
289
|
+
},
|
|
290
|
+
attach: async (ctx, attach) => {
|
|
291
|
+
const { client, attached } = await attachSocket(ctx, { ...attach, passive: false });
|
|
292
|
+
try {
|
|
293
|
+
if (attached.networkPolicy != null)
|
|
294
|
+
await ctx.platformNetworkPolicy(attached.networkPolicy);
|
|
295
|
+
for (const [path, content] of Object.entries(await ctx.platformFiles?.() ?? {}))
|
|
296
|
+
await client.writeTextFile({ path, content });
|
|
297
|
+
} catch (cause) {
|
|
298
|
+
client.close();
|
|
299
|
+
throw cause;
|
|
300
|
+
}
|
|
301
|
+
return {
|
|
302
|
+
handle: handleOf(client, withPlatformEnvironment(ctx, client)),
|
|
303
|
+
state: jsonValueSchema.parse(attached.state),
|
|
304
|
+
fresh: attached.fresh,
|
|
305
|
+
booted: attached.booted,
|
|
306
|
+
region: attached.region
|
|
307
|
+
};
|
|
308
|
+
},
|
|
309
|
+
detach: async (ctx, detach) => (await call({
|
|
310
|
+
path: SandboxProviderWirePath.Detach,
|
|
311
|
+
ctx,
|
|
312
|
+
sandboxId: ctx.sandboxId,
|
|
313
|
+
fields: { sandboxId: ctx.sandboxId, state: detach.state },
|
|
314
|
+
result: stateResultSchema
|
|
315
|
+
})).state,
|
|
316
|
+
park: async (ctx, park) => (await call({
|
|
317
|
+
path: SandboxProviderWirePath.Park,
|
|
318
|
+
ctx,
|
|
319
|
+
sandboxId: ctx.sandboxId,
|
|
320
|
+
fields: { sandboxId: ctx.sandboxId, artifact: park.artifact, state: park.state },
|
|
321
|
+
result: stateResultSchema
|
|
322
|
+
})).state,
|
|
323
|
+
delete: async (ctx, remove) => {
|
|
324
|
+
await call({
|
|
325
|
+
path: SandboxProviderWirePath.Delete,
|
|
326
|
+
ctx,
|
|
327
|
+
sandboxId: ctx.sandboxId,
|
|
328
|
+
fields: { sandboxId: ctx.sandboxId, state: remove.state },
|
|
329
|
+
result: z.object({})
|
|
330
|
+
});
|
|
331
|
+
}
|
|
332
|
+
};
|
|
333
|
+
if (registration.features.attachPassive)
|
|
334
|
+
result.attachPassive = async (ctx, attach) => {
|
|
335
|
+
const { client } = await attachSocket(ctx, { ...attach, passive: true });
|
|
336
|
+
return handleOf(client, client);
|
|
337
|
+
};
|
|
338
|
+
if (registration.features.readSnapshot)
|
|
339
|
+
result.readSnapshot = async (ctx, state, request) => call({
|
|
340
|
+
path: SandboxProviderWirePath.ReadSnapshot,
|
|
341
|
+
ctx,
|
|
342
|
+
sandboxId: requireSandboxId(ctx),
|
|
343
|
+
fields: {
|
|
344
|
+
sandboxId: requireSandboxId(ctx),
|
|
345
|
+
state,
|
|
346
|
+
request: jsonValueSchema.parse(request)
|
|
347
|
+
},
|
|
348
|
+
result: sandboxSnapshotResponseSchema.nullable()
|
|
349
|
+
});
|
|
350
|
+
if (registration.features.processes)
|
|
351
|
+
result.processes = async (ctx, state, request) => call({
|
|
352
|
+
path: SandboxProviderWirePath.Processes,
|
|
353
|
+
ctx,
|
|
354
|
+
sandboxId: ctx.sandboxId,
|
|
355
|
+
fields: { sandboxId: ctx.sandboxId, state, request: jsonValueSchema.parse(request) },
|
|
356
|
+
result: sandboxProcessesResultSchema
|
|
357
|
+
});
|
|
358
|
+
if (registration.features.editor)
|
|
359
|
+
result.editor = async (ctx, state, request) => call({
|
|
360
|
+
path: SandboxProviderWirePath.Editor,
|
|
361
|
+
ctx,
|
|
362
|
+
sandboxId: requireSandboxId(ctx),
|
|
363
|
+
fields: {
|
|
364
|
+
sandboxId: requireSandboxId(ctx),
|
|
365
|
+
state,
|
|
366
|
+
request: jsonValueSchema.parse(request)
|
|
367
|
+
},
|
|
368
|
+
result: sandboxEditorResultSchema
|
|
369
|
+
});
|
|
370
|
+
return result;
|
|
371
|
+
};
|
|
372
|
+
return defineSandboxProvider({
|
|
373
|
+
name: registration.name,
|
|
374
|
+
...registration.stateProtocolVersion == null ? {} : { stateProtocolVersion: registration.stateProtocolVersion },
|
|
375
|
+
environment: (options) => implementation(options ?? null)
|
|
376
|
+
});
|
|
377
|
+
};
|
|
378
|
+
export {
|
|
379
|
+
remoteSandboxProvider
|
|
380
|
+
};
|
|
381
|
+
//# sourceMappingURL=adapter.mjs.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../../../../src/sandbox/remote/adapter.ts"],
|
|
4
|
+
"sourcesContent": ["import {\n SANDBOX_PROVIDER_MAX_BODY_BYTES,\n SANDBOX_PROVIDER_NDJSON_CONTENT_TYPE,\n SANDBOX_PROVIDER_WIRE_VERSION,\n SandboxProviderErrorCode,\n SandboxProviderWirePath,\n sandboxArtifactKeyResultSchema,\n sandboxAttachReplyFrameSchema,\n sandboxOfferResultSchema,\n sandboxProcessesResultSchema,\n type SandboxAttachedFrameIface,\n type SandboxProviderFeaturesIface,\n} from '@finalai/agent-protocol/sandbox-provider-wire';\nimport * as z from 'zod';\nimport { jsonValueSchema, type JsonValue } from \"../../json.mjs\";\nimport { toolDescriptorSchema, type ToolDescriptorIface } from \"../../tool-descriptor.mjs\";\nimport { connectSandboxClient, type SandboxClientIface } from \"../client.mjs\";\nimport { sandboxEditorResultSchema } from \"../editor.mjs\";\nimport { withSandboxOverrides } from \"../overrides.mjs\";\nimport { sandboxSnapshotResponseSchema } from \"../snapshots.mjs\";\nimport {\n defineSandboxProvider,\n SandboxCapability,\n type AnySandboxProviderIface,\n type NetworkSandboxSessionIface,\n type SandboxAttachmentIface,\n type SandboxEnvironmentImplementationIface,\n type SandboxMcpCatalogIface,\n type SandboxOfferContextIface,\n type SandboxProcessOptionsIface,\n type SandboxProviderContextIface,\n type SandboxProviderHandleIface,\n type SandboxResourceContextIface,\n type SandboxWorkerOptionsIface,\n} from \"../types.mjs\";\nimport {\n frameChannelFromWebSocket,\n handleRpcClientProtocols,\n handleRpcError,\n HandleRpcErrorCode,\n type FrameChannelIface,\n type WebSocketConstructorIface,\n type WebSocketLikeIface,\n} from \"../wire.mjs\";\nimport { sandboxProviderWireError } from \"./errors.mjs\";\nimport { readWireAnswer } from \"./ndjson.mjs\";\nimport { preambleChannel } from \"./preamble.mjs\";\n\n// A sandbox provider registered by URL, as the platform drives it: every\n// provider call is one request on the sandbox-provider wire, and an attach is\n// one WebSocket that then carries the handle RPC. Built with\n// defineSandboxProvider, so execution policy, approvals and grants compose on\n// the platform's side and never depend on the provider. What the platform owns\n// stays on its side of the wire too: after the provider reports the network\n// policy it applied, the adapter reports it to the platform, writes the\n// platform's files through the handle, and adds the platform's environment to\n// every process it starts there, re-read each time and over the caller's.\n\nexport interface SandboxProviderAssertionArgsIface {\n providerId: string;\n // The registration URL, which the assertion is for.\n audience: string;\n organizationId: string;\n projectId: string;\n // Null for calls that name no sandbox (offers, preparations).\n sandboxId: string | null;\n // The acting user now; null for nobody.\n userId: string | null;\n}\n\nexport interface RemoteSandboxProviderRegistrationIface {\n id: string;\n name: string;\n url: string;\n stateProtocolVersion: number | null;\n // The optional calls the provider serves, from its discovery document.\n features: SandboxProviderFeaturesIface;\n}\n\nexport interface RemoteSandboxProviderArgsIface {\n registration: RemoteSandboxProviderRegistrationIface;\n // A sandbox-provider assertion (`@finalai/agent-protocol/identity`) for the call.\n mintAssertion: (claims: SandboxProviderAssertionArgsIface) => Promise<string>;\n // The project secrets the registration forwards, by name.\n forwardedSecrets: (scope: {\n organizationId: string;\n projectId: string;\n }) => Promise<Record<string, string>>;\n fetch?: typeof fetch;\n // Dials the attach socket: a WebSocket constructor, or `openSocket` in its place.\n WebSocket?: WebSocketConstructorIface;\n openSocket?: (url: string, protocols: string[]) => WebSocketLikeIface;\n}\n\n// The attach socket's assertion is replaced at least this often, and as soon\n// as the acting user changes.\nconst ASSERTION_RENEW_MS = 4 * 60_000;\n\nconst offerSchema = sandboxOfferResultSchema;\n// Provider state and artifacts, as this package's JSON.\nconst stateResultSchema = z.object({ state: jsonValueSchema });\nconst createResultSchema = z.object({\n state: jsonValueSchema,\n region: z.string().nullable().default(null),\n});\nconst prepareResultSchema = z.object({ artifact: jsonValueSchema });\ntype OfferType = z.infer<typeof offerSchema>;\n\nconst descriptorsOf = (tools: readonly unknown[]): ToolDescriptorIface[] =>\n tools.flatMap((tool) => {\n const parsed = toolDescriptorSchema.safeParse(tool);\n return parsed.success ? [parsed.data] : [];\n });\n\nconst isSandboxCapability = (value: string): value is SandboxCapability =>\n Object.values(SandboxCapability).some((capability) => capability === value);\n\nconst capabilitiesOf = (values: readonly string[]): SandboxCapability[] =>\n values.filter(isSandboxCapability);\n\nconst catalogOf = (catalog: OfferType['mcpCatalog']): SandboxMcpCatalogIface | null =>\n catalog == null\n ? null\n : {\n computerUse: catalog.computerUse == null ? null : descriptorsOf(catalog.computerUse),\n localMcp:\n catalog.localMcp == null\n ? null\n : Object.fromEntries(\n Object.entries(catalog.localMcp).map(([name, tools]) => [\n name,\n descriptorsOf(tools),\n ]),\n ),\n ...(catalog.localMcpIncomplete == null\n ? {}\n : { localMcpIncomplete: catalog.localMcpIncomplete }),\n };\n\nconst attachUrlOf = (url: string): string => {\n const target = new URL(`${url.replace(/\\/+$/u, '')}${SandboxProviderWirePath.Attach}`);\n target.protocol = target.protocol === 'http:' ? 'ws:' : 'wss:';\n return target.toString();\n};\n\n// The platform's environment over the caller's, read again for every process.\nconst withPlatformEnvironment = (\n ctx: Pick<SandboxResourceContextIface, 'platformEnvironment'>,\n client: SandboxClientIface,\n): NetworkSandboxSessionIface => {\n const platformEnvironment = ctx.platformEnvironment;\n if (platformEnvironment == null) return client;\n const envOf = async (env: Record<string, string> | undefined) => ({\n ...env,\n ...(await platformEnvironment()),\n });\n const overrides: Partial<NetworkSandboxSessionIface> = {\n spawn: async (options: SandboxProcessOptionsIface) =>\n client.spawn({ ...options, env: await envOf(options.env) }),\n run: async (options: SandboxProcessOptionsIface) =>\n client.run({ ...options, env: await envOf(options.env) }),\n };\n const startWorker = client.startWorker;\n if (startWorker != null)\n overrides.startWorker = async (options: SandboxWorkerOptionsIface) =>\n startWorker({ ...options, env: await envOf(options.env) });\n return withSandboxOverrides<NetworkSandboxSessionIface>(client, overrides);\n};\n\nexport const remoteSandboxProvider = (\n args: RemoteSandboxProviderArgsIface,\n): AnySandboxProviderIface => {\n const { registration } = args;\n const doFetch = args.fetch ?? fetch;\n const openSocket =\n args.openSocket ??\n ((url: string, protocols: string[]): WebSocketLikeIface => {\n const WebSocketImpl = args.WebSocket ?? globalThis.WebSocket;\n if (WebSocketImpl == null) throw new Error('no WebSocket implementation; pass WebSocket');\n return new WebSocketImpl(url, protocols);\n });\n const baseUrl = registration.url.replace(/\\/+$/u, '');\n\n const assertionFor = async (\n ctx: SandboxProviderContextIface,\n sandboxId: string | null,\n ): Promise<{ token: string; userId: string | null }> => {\n const userId = await ctx.actingUser.current();\n const token = await args.mintAssertion({\n providerId: registration.id,\n audience: registration.url,\n organizationId: ctx.organizationId,\n projectId: ctx.projectId,\n sandboxId,\n userId,\n });\n return { token, userId };\n };\n\n const secretsOf = (ctx: SandboxProviderContextIface) =>\n args.forwardedSecrets({ organizationId: ctx.organizationId, projectId: ctx.projectId });\n\n const implementation = (\n environment: JsonValue,\n ): SandboxEnvironmentImplementationIface<JsonValue, JsonValue, NetworkSandboxSessionIface> => {\n const call = async <S extends z.ZodType>(call: {\n path: SandboxProviderWirePath;\n ctx: SandboxProviderContextIface;\n sandboxId: string | null;\n fields: Record<string, JsonValue>;\n result: S;\n }): Promise<z.output<S>> => {\n const [{ token }, secrets] = await Promise.all([\n assertionFor(call.ctx, call.sandboxId),\n secretsOf(call.ctx),\n ]);\n const body = JSON.stringify({\n wire: SANDBOX_PROVIDER_WIRE_VERSION,\n environment,\n secrets,\n ...call.fields,\n });\n if (new TextEncoder().encode(body).byteLength > SANDBOX_PROVIDER_MAX_BODY_BYTES)\n throw sandboxProviderWireError({\n code: SandboxProviderErrorCode.InvalidEnvironment,\n message: `the ${call.path} request is over the sandbox provider wire's size limit`,\n retryable: false,\n });\n const response = await doFetch(`${baseUrl}${call.path}`, {\n method: 'POST',\n headers: {\n authorization: `Bearer ${token}`,\n 'content-type': 'application/json',\n accept: `application/json, ${SANDBOX_PROVIDER_NDJSON_CONTENT_TYPE}`,\n },\n body,\n });\n const parsed = call.result.safeParse(await readWireAnswer(response));\n if (!parsed.success)\n throw sandboxProviderWireError({\n code: SandboxProviderErrorCode.Unavailable,\n message: `unexpected ${call.path} answer from ${registration.name}: ${z.prettifyError(parsed.error)}`,\n retryable: false,\n });\n return parsed.data;\n };\n\n // One `offer` call answers every pre-attach read made with the same context.\n const offers = new WeakMap<SandboxOfferContextIface, Promise<OfferType>>();\n const offerOf = (ctx: SandboxOfferContextIface): Promise<OfferType> => {\n const existing = offers.get(ctx);\n if (existing != null) return existing;\n const offer = call({\n path: SandboxProviderWirePath.Offer,\n ctx,\n sandboxId: ctx.sandboxId ?? null,\n fields: { sandboxId: ctx.sandboxId ?? null },\n result: offerSchema,\n });\n offers.set(ctx, offer);\n offer.catch(() => offers.delete(ctx));\n return offer;\n };\n\n const requireSandboxId = (ctx: SandboxOfferContextIface): string => {\n if (ctx.sandboxId == null) throw new Error('this call needs the sandbox it is about');\n return ctx.sandboxId;\n };\n\n const attachSocket = async (\n ctx: SandboxResourceContextIface,\n attach: { artifact: JsonValue; state: JsonValue; passive: boolean },\n ): Promise<{ client: SandboxClientIface; attached: SandboxAttachedFrameIface }> => {\n const [first, secrets] = await Promise.all([\n assertionFor(ctx, ctx.sandboxId),\n secretsOf(ctx),\n ]);\n let identity = { ...first, mintedAt: Date.now() };\n const { channel, opened } = frameChannelFromWebSocket(\n openSocket(attachUrlOf(registration.url), handleRpcClientProtocols(first.token)),\n );\n await opened;\n const preamble = preambleChannel(channel);\n channel.send(\n JSON.stringify({\n type: 'attach',\n wire: SANDBOX_PROVIDER_WIRE_VERSION,\n environment,\n secrets,\n sandboxId: ctx.sandboxId,\n artifact: attach.artifact,\n state: attach.state,\n passive: attach.passive,\n platformEgressHosts: ctx.platformEgressHosts ?? [],\n lifecycle: ctx.lifecycle,\n }),\n );\n let attached: SandboxAttachedFrameIface | null = null;\n try {\n while (attached == null) {\n const frame = await preamble.next();\n if (typeof frame !== 'string') throw new Error('the attach reply must be a text frame');\n const reply = sandboxAttachReplyFrameSchema.parse(JSON.parse(frame));\n if (reply.type === 'error') throw sandboxProviderWireError(reply.error);\n if (reply.type === 'attached') attached = reply;\n }\n } catch (cause) {\n channel.close();\n throw cause;\n }\n let handed = false;\n const openChannel = async (): Promise<FrameChannelIface> => {\n if (handed)\n throw handleRpcError({\n code: HandleRpcErrorCode.ConnectionClosed,\n message: `the ${registration.name} attach socket closed; attach again`,\n retryable: true,\n });\n handed = true;\n return preamble.rest();\n };\n try {\n const client = await connectSandboxClient({\n url: attachUrlOf(registration.url),\n token: '',\n openChannel,\n reconnect: { attempts: 1 },\n identity: async ({ renew }) => {\n const userId = await ctx.actingUser.current();\n if (\n renew ||\n userId !== identity.userId ||\n Date.now() - identity.mintedAt >= ASSERTION_RENEW_MS\n ) {\n const next = await assertionFor(ctx, ctx.sandboxId);\n identity = { ...next, mintedAt: Date.now() };\n }\n return identity.token;\n },\n });\n return { client, attached };\n } catch (cause) {\n channel.close();\n throw cause;\n }\n };\n\n const handleOf = (\n client: SandboxClientIface,\n sandbox: NetworkSandboxSessionIface,\n ): SandboxProviderHandleIface<NetworkSandboxSessionIface> => ({\n sandbox,\n onSandboxStop: () => client.onSandboxStop(),\n onSandboxDelete: (options) => client.onSandboxDelete(options),\n onRuntimeShutdown: async () => {\n try {\n await client.onRuntimeShutdown();\n } catch {\n // The socket is already gone, and with it the provider's handle.\n } finally {\n client.close();\n }\n },\n });\n\n const result: SandboxEnvironmentImplementationIface<\n JsonValue,\n JsonValue,\n NetworkSandboxSessionIface\n > = {\n capabilities: async (ctx) => ({ ...(await offerOf(ctx)).capabilities }),\n runtimes: async (ctx) => (await offerOf(ctx)).runtimes,\n features: async (ctx) => {\n const { features } = await offerOf(ctx);\n return features == null ? null : capabilitiesOf(features);\n },\n additionalFeatures: async (ctx) => capabilitiesOf((await offerOf(ctx)).additionalFeatures),\n mcpCatalog: async (ctx) => catalogOf((await offerOf(ctx)).mcpCatalog),\n artifactKey: async (ctx) =>\n (\n await call({\n path: SandboxProviderWirePath.ArtifactKey,\n ctx,\n sandboxId: null,\n fields: {\n files: ctx.files,\n resources: ctx.resources,\n sourceRevision: ctx.sourceRevision,\n },\n result: sandboxArtifactKeyResultSchema,\n })\n ).key,\n prepare: async (ctx) =>\n (\n await call({\n path: SandboxProviderWirePath.Prepare,\n ctx,\n sandboxId: null,\n fields: {\n files: ctx.files,\n resources: ctx.resources,\n sourceRevision: ctx.sourceRevision,\n },\n result: prepareResultSchema,\n })\n ).artifact,\n create: async (ctx, create) =>\n call({\n path: SandboxProviderWirePath.Create,\n ctx,\n sandboxId: ctx.sandboxId,\n fields: {\n sandboxId: ctx.sandboxId,\n artifact: create.artifact,\n setup: create.setup == null ? null : jsonValueSchema.parse(create.setup),\n platformEgressHosts: ctx.platformEgressHosts ?? [],\n lifecycle: { parkAfterIdleMs: ctx.lifecycle.parkAfterIdleMs },\n },\n result: createResultSchema,\n }),\n awaitRunning: async (ctx, state, options) => {\n await call({\n path: SandboxProviderWirePath.AwaitRunning,\n ctx,\n sandboxId: ctx.sandboxId,\n fields: { sandboxId: ctx.sandboxId, state, timeoutMs: options.timeoutMs },\n result: z.object({}),\n });\n },\n attach: async (\n ctx,\n attach,\n ): Promise<SandboxAttachmentIface<JsonValue, NetworkSandboxSessionIface>> => {\n const { client, attached } = await attachSocket(ctx, { ...attach, passive: false });\n try {\n // The order a provider keeps in process: policy, then files, then the\n // handle. A provider that applies no policy (a person's own machine)\n // reports none, as in process.\n if (attached.networkPolicy != null)\n await ctx.platformNetworkPolicy(attached.networkPolicy);\n for (const [path, content] of Object.entries((await ctx.platformFiles?.()) ?? {}))\n await client.writeTextFile({ path, content });\n } catch (cause) {\n client.close();\n throw cause;\n }\n return {\n handle: handleOf(client, withPlatformEnvironment(ctx, client)),\n state: jsonValueSchema.parse(attached.state),\n fresh: attached.fresh,\n booted: attached.booted,\n region: attached.region,\n };\n },\n detach: async (ctx, detach) =>\n (\n await call({\n path: SandboxProviderWirePath.Detach,\n ctx,\n sandboxId: ctx.sandboxId,\n fields: { sandboxId: ctx.sandboxId, state: detach.state },\n result: stateResultSchema,\n })\n ).state,\n park: async (ctx, park) =>\n (\n await call({\n path: SandboxProviderWirePath.Park,\n ctx,\n sandboxId: ctx.sandboxId,\n fields: { sandboxId: ctx.sandboxId, artifact: park.artifact, state: park.state },\n result: stateResultSchema,\n })\n ).state,\n delete: async (ctx, remove) => {\n await call({\n path: SandboxProviderWirePath.Delete,\n ctx,\n sandboxId: ctx.sandboxId,\n fields: { sandboxId: ctx.sandboxId, state: remove.state },\n result: z.object({}),\n });\n },\n };\n if (registration.features.attachPassive)\n result.attachPassive = async (ctx, attach) => {\n const { client } = await attachSocket(ctx, { ...attach, passive: true });\n return handleOf(client, client);\n };\n if (registration.features.readSnapshot)\n result.readSnapshot = async (ctx, state, request) =>\n call({\n path: SandboxProviderWirePath.ReadSnapshot,\n ctx,\n sandboxId: requireSandboxId(ctx),\n fields: {\n sandboxId: requireSandboxId(ctx),\n state,\n request: jsonValueSchema.parse(request),\n },\n result: sandboxSnapshotResponseSchema.nullable(),\n });\n if (registration.features.processes)\n result.processes = async (ctx, state, request) =>\n call({\n path: SandboxProviderWirePath.Processes,\n ctx,\n sandboxId: ctx.sandboxId,\n fields: { sandboxId: ctx.sandboxId, state, request: jsonValueSchema.parse(request) },\n result: sandboxProcessesResultSchema,\n });\n if (registration.features.editor)\n result.editor = async (ctx, state, request) =>\n call({\n path: SandboxProviderWirePath.Editor,\n ctx,\n sandboxId: requireSandboxId(ctx),\n fields: {\n sandboxId: requireSandboxId(ctx),\n state,\n request: jsonValueSchema.parse(request),\n },\n result: sandboxEditorResultSchema,\n });\n return result;\n };\n\n return defineSandboxProvider<JsonValue, JsonValue, JsonValue, NetworkSandboxSessionIface>({\n name: registration.name,\n ...(registration.stateProtocolVersion == null\n ? {}\n : { stateProtocolVersion: registration.stateProtocolVersion }),\n environment: (options) => implementation(options ?? null),\n });\n};\n"],
|
|
5
|
+
"mappings": "AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AACP,YAAY,OAAO;AACnB,SAAS,uBAAuC;AAChD,SAAS,4BAAsD;AAC/D,SAAS,4BAAqD;AAC9D,SAAS,iCAAiC;AAC1C,SAAS,4BAA4B;AACrC,SAAS,qCAAqC;AAC9C;AAAA,EACE;AAAA,EACA;AAAA,OAYK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAIK;AACP,SAAS,gCAAgC;AACzC,SAAS,sBAAsB;AAC/B,SAAS,uBAAuB;AAkDhC,MAAM,qBAAqB,IAAI;AAE/B,MAAM,cAAc;AAEpB,MAAM,oBAAoB,EAAE,OAAO,EAAE,OAAO,gBAAgB,CAAC;AAC7D,MAAM,qBAAqB,EAAE,OAAO;AAAA,EAClC,OAAO;AAAA,EACP,QAAQ,EAAE,OAAO,EAAE,SAAS,EAAE,QAAQ,IAAI;AAC5C,CAAC;AACD,MAAM,sBAAsB,EAAE,OAAO,EAAE,UAAU,gBAAgB,CAAC;AAGlE,MAAM,gBAAgB,CAAC,UACrB,MAAM,QAAQ,CAAC,SAAS;AACtB,QAAM,SAAS,qBAAqB,UAAU,IAAI;A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D,EAAE,sBAAsB,aAAa,qBAAqB;AAAA,IAC9D,aAAa,CAAC,YAAY,eAAe,WAAW,IAAI;AAAA,EAC1D,CAAC;AACH;",
|
|
6
|
+
"names": ["call"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { SandboxProviderErrorCode, type SandboxProviderErrorIface } from '@finalai/agent-protocol/sandbox-provider-wire';
|
|
2
|
+
export interface SandboxProviderWireErrorIface extends Error {
|
|
3
|
+
readonly code: SandboxProviderErrorCode;
|
|
4
|
+
readonly retryable: boolean;
|
|
5
|
+
}
|
|
6
|
+
export declare const sandboxProviderWireError: (error: SandboxProviderErrorIface) => SandboxProviderWireErrorIface;
|
|
7
|
+
export declare const isSandboxProviderWireError: (cause: unknown) => cause is SandboxProviderWireErrorIface;
|
|
8
|
+
export declare const SANDBOX_PROVIDER_ERROR_STATUS: Readonly<Record<SandboxProviderErrorCode, number>>;
|
|
9
|
+
export declare const wireErrorOf: (cause: unknown) => SandboxProviderErrorIface;
|
|
10
|
+
export declare const wireErrorFromBody: (status: number, text: string) => SandboxProviderWireErrorIface;
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import {
|
|
2
|
+
SandboxProviderErrorCode,
|
|
3
|
+
sandboxProviderErrorBodySchema
|
|
4
|
+
} from "@finalai/agent-protocol/sandbox-provider-wire";
|
|
5
|
+
import * as z from "zod";
|
|
6
|
+
const sandboxProviderWireError = (error) => Object.assign(new Error(error.message), {
|
|
7
|
+
name: "SandboxProviderWireError",
|
|
8
|
+
code: error.code,
|
|
9
|
+
retryable: error.retryable
|
|
10
|
+
});
|
|
11
|
+
const wireErrorFieldsSchema = z.object({
|
|
12
|
+
code: z.nativeEnum(SandboxProviderErrorCode),
|
|
13
|
+
retryable: z.boolean()
|
|
14
|
+
});
|
|
15
|
+
const isSandboxProviderWireError = (cause) => cause instanceof Error && wireErrorFieldsSchema.safeParse(cause).success;
|
|
16
|
+
const SANDBOX_PROVIDER_ERROR_STATUS = {
|
|
17
|
+
[SandboxProviderErrorCode.InvalidEnvironment]: 400,
|
|
18
|
+
[SandboxProviderErrorCode.Forbidden]: 403,
|
|
19
|
+
[SandboxProviderErrorCode.NotFound]: 404,
|
|
20
|
+
[SandboxProviderErrorCode.StateVersion]: 409,
|
|
21
|
+
[SandboxProviderErrorCode.Unavailable]: 503,
|
|
22
|
+
[SandboxProviderErrorCode.Timeout]: 504
|
|
23
|
+
};
|
|
24
|
+
const wireErrorOf = (cause) => {
|
|
25
|
+
if (isSandboxProviderWireError(cause))
|
|
26
|
+
return { code: cause.code, message: cause.message, retryable: cause.retryable };
|
|
27
|
+
if (cause instanceof z.ZodError)
|
|
28
|
+
return {
|
|
29
|
+
code: SandboxProviderErrorCode.InvalidEnvironment,
|
|
30
|
+
message: z.prettifyError(cause),
|
|
31
|
+
retryable: false
|
|
32
|
+
};
|
|
33
|
+
return {
|
|
34
|
+
code: SandboxProviderErrorCode.Unavailable,
|
|
35
|
+
message: cause instanceof Error ? cause.message : String(cause),
|
|
36
|
+
retryable: true
|
|
37
|
+
};
|
|
38
|
+
};
|
|
39
|
+
const wireErrorFromBody = (status, text) => {
|
|
40
|
+
let parsed = null;
|
|
41
|
+
try {
|
|
42
|
+
parsed = JSON.parse(text);
|
|
43
|
+
} catch {
|
|
44
|
+
parsed = null;
|
|
45
|
+
}
|
|
46
|
+
const body = sandboxProviderErrorBodySchema.safeParse(parsed);
|
|
47
|
+
return sandboxProviderWireError(
|
|
48
|
+
body.success ? body.data.error : {
|
|
49
|
+
code: status === 401 || status === 403 ? SandboxProviderErrorCode.Forbidden : SandboxProviderErrorCode.Unavailable,
|
|
50
|
+
message: `sandbox provider answered ${status}: ${text.slice(0, 200)}`,
|
|
51
|
+
retryable: status >= 500
|
|
52
|
+
}
|
|
53
|
+
);
|
|
54
|
+
};
|
|
55
|
+
export {
|
|
56
|
+
SANDBOX_PROVIDER_ERROR_STATUS,
|
|
57
|
+
isSandboxProviderWireError,
|
|
58
|
+
sandboxProviderWireError,
|
|
59
|
+
wireErrorFromBody,
|
|
60
|
+
wireErrorOf
|
|
61
|
+
};
|
|
62
|
+
//# sourceMappingURL=errors.mjs.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../../../../src/sandbox/remote/errors.ts"],
|
|
4
|
+
"sourcesContent": ["import {\n SandboxProviderErrorCode,\n sandboxProviderErrorBodySchema,\n type SandboxProviderErrorIface,\n} from '@finalai/agent-protocol/sandbox-provider-wire';\nimport * as z from 'zod';\n\n// Errors on the sandbox-provider wire: a provider answers\n// `{ error: { code, message, retryable } }`, and the adapter throws them as\n// SandboxProviderWireErrorIface so the platform can tell a lost backend\n// (`not_found`) or a refused environment from a provider that is down.\n\nexport interface SandboxProviderWireErrorIface extends Error {\n readonly code: SandboxProviderErrorCode;\n readonly retryable: boolean;\n}\n\nexport const sandboxProviderWireError = (\n error: SandboxProviderErrorIface,\n): SandboxProviderWireErrorIface =>\n Object.assign(new Error(error.message), {\n name: 'SandboxProviderWireError',\n code: error.code,\n retryable: error.retryable,\n });\n\nconst wireErrorFieldsSchema = z.object({\n code: z.nativeEnum(SandboxProviderErrorCode),\n retryable: z.boolean(),\n});\n\nexport const isSandboxProviderWireError = (\n cause: unknown,\n): cause is SandboxProviderWireErrorIface =>\n cause instanceof Error && wireErrorFieldsSchema.safeParse(cause).success;\n\nexport const SANDBOX_PROVIDER_ERROR_STATUS: Readonly<Record<SandboxProviderErrorCode, number>> = {\n [SandboxProviderErrorCode.InvalidEnvironment]: 400,\n [SandboxProviderErrorCode.Forbidden]: 403,\n [SandboxProviderErrorCode.NotFound]: 404,\n [SandboxProviderErrorCode.StateVersion]: 409,\n [SandboxProviderErrorCode.Unavailable]: 503,\n [SandboxProviderErrorCode.Timeout]: 504,\n};\n\n// What a provider answers for a thrown value: its own wire error, a refused\n// environment for invalid options, else `unavailable` (retryable).\nexport const wireErrorOf = (cause: unknown): SandboxProviderErrorIface => {\n if (isSandboxProviderWireError(cause))\n return { code: cause.code, message: cause.message, retryable: cause.retryable };\n if (cause instanceof z.ZodError)\n return {\n code: SandboxProviderErrorCode.InvalidEnvironment,\n message: z.prettifyError(cause),\n retryable: false,\n };\n return {\n code: SandboxProviderErrorCode.Unavailable,\n message: cause instanceof Error ? cause.message : String(cause),\n retryable: true,\n };\n};\n\n// The error a non-success answer carries; an answer that is not a wire error\n// (a proxy's page) is `unavailable`.\nexport const wireErrorFromBody = (status: number, text: string): SandboxProviderWireErrorIface => {\n let parsed: unknown = null;\n try {\n parsed = JSON.parse(text);\n } catch {\n parsed = null;\n }\n const body = sandboxProviderErrorBodySchema.safeParse(parsed);\n return sandboxProviderWireError(\n body.success\n ? body.data.error\n : {\n code:\n status === 401 || status === 403\n ? SandboxProviderErrorCode.Forbidden\n : SandboxProviderErrorCode.Unavailable,\n message: `sandbox provider answered ${status}: ${text.slice(0, 200)}`,\n retryable: status >= 500,\n },\n );\n};\n"],
|
|
5
|
+
"mappings": "AAAA;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP,YAAY,OAAO;AAYZ,MAAM,2BAA2B,CACtC,UAEA,OAAO,OAAO,IAAI,MAAM,MAAM,OAAO,GAAG;AAAA,EACtC,MAAM;AAAA,EACN,MAAM,MAAM;AAAA,EACZ,WAAW,MAAM;AACnB,CAAC;AAEH,MAAM,wBAAwB,EAAE,OAAO;AAAA,EACrC,MAAM,EAAE,WAAW,wBAAwB;AAAA,EAC3C,WAAW,EAAE,QAAQ;AACvB,CAAC;AAEM,MAAM,6BAA6B,CACxC,UAEA,iBAAiB,SAAS,sBAAsB,UAAU,KAAK,EAAE;AAE5D,MAAM,gCAAoF;AAAA,EAC/F,CAAC,yBAAyB,kBAAkB,GAAG;AAAA,EAC/C,CAAC,yBAAyB,SAAS,GAAG;AAAA,EACtC,CAAC,yBAAyB,QAAQ,GAAG;AAAA,EACrC,CAAC,yBAAyB,YAAY,GAAG;AAAA,EACzC,CAAC,yBAAyB,WAAW,GAAG;AAAA,EACxC,CAAC,yBAAyB,OAAO,GAAG;AACtC;AAIO,MAAM,cAAc,CAAC,UAA8C;AACxE,MAAI,2BAA2B,KAAK;AAClC,WAAO,EAAE,MAAM,MAAM,MAAM,SAAS,MAAM,SAAS,WAAW,MAAM,UAAU;AAChF,MAAI,iBAAiB,EAAE;AACrB,WAAO;AAAA,MACL,MAAM,yBAAyB;AAAA,MAC/B,SAAS,EAAE,cAAc,KAAK;AAAA,MAC9B,WAAW;AAAA,IACb;AACF,SAAO;AAAA,IACL,MAAM,yBAAyB;AAAA,IAC/B,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAAA,IAC9D,WAAW;AAAA,EACb;AACF;AAIO,MAAM,oBAAoB,CAAC,QAAgB,SAAgD;AAChG,MAAI,SAAkB;AACtB,MAAI;AACF,aAAS,KAAK,MAAM,IAAI;AAAA,EAC1B,QAAQ;AACN,aAAS;AAAA,EACX;AACA,QAAM,OAAO,+BAA+B,UAAU,MAAM;AAC5D,SAAO;AAAA,IACL,KAAK,UACD,KAAK,KAAK,QACV;AAAA,MACE,MACE,WAAW,OAAO,WAAW,MACzB,yBAAyB,YACzB,yBAAyB;AAAA,MAC/B,SAAS,6BAA6B,MAAM,KAAK,KAAK,MAAM,GAAG,GAAG,CAAC;AAAA,MACnE,WAAW,UAAU;AAAA,IACvB;AAAA,EACN;AACF;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../../../../src/sandbox/remote/index.ts"],
|
|
4
|
+
"sourcesContent": ["// The sandbox-provider wire: serve providers by URL (serveSandboxProvider) and\n// drive a provider registered by URL as an ordinary provider\n// (remoteSandboxProvider). The wire's shapes are in\n// `@finalai/agent-protocol/sandbox-provider-wire`.\n\nexport * from \"./adapter.mjs\";\nexport * from \"./errors.mjs\";\nexport * from \"./platform-api.mjs\";\nexport * from \"./serve.mjs\";\nexport * from \"./testing.mjs\";\n"],
|
|
5
|
+
"mappings": "AAKA,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import {
|
|
2
|
+
SANDBOX_PROVIDER_NDJSON_CONTENT_TYPE,
|
|
3
|
+
SandboxProviderErrorCode,
|
|
4
|
+
sandboxProviderErrorSchema
|
|
5
|
+
} from "@finalai/agent-protocol/sandbox-provider-wire";
|
|
6
|
+
import * as z from "zod";
|
|
7
|
+
import { sandboxProviderWireError, wireErrorFromBody, wireErrorOf } from "./errors.mjs";
|
|
8
|
+
const HEARTBEAT_LINE = `${JSON.stringify({ heartbeat: true })}
|
|
9
|
+
`;
|
|
10
|
+
const ndjsonResponse = (args) => {
|
|
11
|
+
const encoder = new TextEncoder();
|
|
12
|
+
let timer = null;
|
|
13
|
+
let cancelled = false;
|
|
14
|
+
const body = new ReadableStream({
|
|
15
|
+
start: (controller) => {
|
|
16
|
+
timer = setInterval(
|
|
17
|
+
() => controller.enqueue(encoder.encode(HEARTBEAT_LINE)),
|
|
18
|
+
args.heartbeatMs
|
|
19
|
+
);
|
|
20
|
+
void args.work().then(
|
|
21
|
+
(result) => ({ result }),
|
|
22
|
+
(cause) => ({ error: wireErrorOf(cause) })
|
|
23
|
+
).then((line) => {
|
|
24
|
+
if (timer != null) clearInterval(timer);
|
|
25
|
+
if (cancelled) return;
|
|
26
|
+
controller.enqueue(encoder.encode(`${JSON.stringify(line)}
|
|
27
|
+
`));
|
|
28
|
+
controller.close();
|
|
29
|
+
});
|
|
30
|
+
},
|
|
31
|
+
cancel: () => {
|
|
32
|
+
cancelled = true;
|
|
33
|
+
if (timer != null) clearInterval(timer);
|
|
34
|
+
}
|
|
35
|
+
});
|
|
36
|
+
return new Response(body, {
|
|
37
|
+
status: 200,
|
|
38
|
+
headers: { "content-type": SANDBOX_PROVIDER_NDJSON_CONTENT_TYPE }
|
|
39
|
+
});
|
|
40
|
+
};
|
|
41
|
+
const lineSchema = z.union([
|
|
42
|
+
z.object({ heartbeat: z.literal(true) }),
|
|
43
|
+
z.object({ result: z.unknown() }),
|
|
44
|
+
z.object({ error: sandboxProviderErrorSchema })
|
|
45
|
+
]);
|
|
46
|
+
const readWireAnswer = async (response) => {
|
|
47
|
+
const text = await response.text();
|
|
48
|
+
if (!response.ok) throw wireErrorFromBody(response.status, text);
|
|
49
|
+
const contentType = response.headers.get("content-type") ?? "";
|
|
50
|
+
if (!contentType.startsWith(SANDBOX_PROVIDER_NDJSON_CONTENT_TYPE)) {
|
|
51
|
+
try {
|
|
52
|
+
return JSON.parse(text);
|
|
53
|
+
} catch {
|
|
54
|
+
throw wireErrorFromBody(502, text);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
for (const raw of text.split("\n")) {
|
|
58
|
+
if (raw.trim() === "") continue;
|
|
59
|
+
let parsed;
|
|
60
|
+
try {
|
|
61
|
+
parsed = JSON.parse(raw);
|
|
62
|
+
} catch {
|
|
63
|
+
throw wireErrorFromBody(502, raw);
|
|
64
|
+
}
|
|
65
|
+
const line = lineSchema.safeParse(parsed);
|
|
66
|
+
if (!line.success) throw wireErrorFromBody(502, raw);
|
|
67
|
+
if ("error" in line.data) throw sandboxProviderWireError(line.data.error);
|
|
68
|
+
if ("result" in line.data) return line.data.result;
|
|
69
|
+
}
|
|
70
|
+
throw sandboxProviderWireError({
|
|
71
|
+
code: SandboxProviderErrorCode.Unavailable,
|
|
72
|
+
message: "the sandbox provider ended its answer without a result",
|
|
73
|
+
retryable: true
|
|
74
|
+
});
|
|
75
|
+
};
|
|
76
|
+
export {
|
|
77
|
+
ndjsonResponse,
|
|
78
|
+
readWireAnswer
|
|
79
|
+
};
|
|
80
|
+
//# sourceMappingURL=ndjson.mjs.map
|