@finalai/agent-provider 0.16.2 → 0.17.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 +16 -2
- package/README.md +4 -0
- package/dist/modules/sandbox/remote/adapter.mjs +10 -1
- package/dist/modules/sandbox/remote/adapter.mjs.map +2 -2
- package/dist/modules/sandbox/remote/serve.mjs +22 -0
- package/dist/modules/sandbox/remote/serve.mjs.map +2 -2
- package/dist/modules/sandbox/types.d.mts +5 -0
- package/dist/modules/sandbox/types.mjs +6 -0
- package/dist/modules/sandbox/types.mjs.map +2 -2
- package/package.json +3 -3
package/HOSTING.md
CHANGED
|
@@ -54,7 +54,7 @@ Routes, under `/api/v1/projects/:projectId/agents`:
|
|
|
54
54
|
|
|
55
55
|
| Route | Body / query | Response |
|
|
56
56
|
| ---------------- | ----------------------------------- | -------------------------------------- |
|
|
57
|
-
| `PUT /documents` | `{ document, hash? }`
|
|
57
|
+
| `PUT /documents` | `{ document \| source, hash? }` | `{ hash }`; refuse a hash that differs |
|
|
58
58
|
| `POST /publish` | `{ name, hash }` | `{ id, name, hash, publishedAt }` |
|
|
59
59
|
| `GET /lookup` | exactly one of `name`, `id`, `hash` | `agentInfoSchema` |
|
|
60
60
|
| `GET /history` | `name`, `cursor?`, `limit?` | `agentHistorySchema` |
|
|
@@ -62,6 +62,19 @@ Routes, under `/api/v1/projects/:projectId/agents`:
|
|
|
62
62
|
An agent is always passed as an object, `{ hash, document? }`, never a name. A
|
|
63
63
|
request whose document is absent names a hash the host already stores.
|
|
64
64
|
|
|
65
|
+
A store sends either the document or its `source` (`agentSourceSchema`): the
|
|
66
|
+
files the document is made from, by path. A host given `source` makes the
|
|
67
|
+
document from those files itself and keeps them with it. It refuses a source
|
|
68
|
+
that does not make a document (`agent_source_invalid`, with
|
|
69
|
+
`details.diagnostics`) and, when `hash` is sent, one whose document hashes
|
|
70
|
+
differently (`hash_mismatch`). `GET /lookup` returns the kept files as `source`
|
|
71
|
+
(null when there are none).
|
|
72
|
+
|
|
73
|
+
Every publication keeps its source: `POST /publish` refuses a hash stored without one. A host
|
|
74
|
+
that keeps drafts makes a publication made elsewhere the next draft, and refuses one that lacks
|
|
75
|
+
what was published from drafts since its publisher last published (`draft_conflict`), keeping
|
|
76
|
+
the merge as the newest draft.
|
|
77
|
+
|
|
65
78
|
## Provide documents
|
|
66
79
|
|
|
67
80
|
```json
|
|
@@ -353,7 +366,8 @@ These packages define contracts and client behaviour, not a platform. A host
|
|
|
353
366
|
implementing them must:
|
|
354
367
|
|
|
355
368
|
1. Store documents by `agentDocumentHash`, re-check self-contained serverless
|
|
356
|
-
source,
|
|
369
|
+
source, make documents from agent `source` without giving that code network
|
|
370
|
+
or host access, and point names at hashes only when someone publishes.
|
|
357
371
|
2. Run `unmetRequirements` on every call that starts work and at every session
|
|
358
372
|
open, and create nothing when it fails.
|
|
359
373
|
3. Store each `provide` as given; never fill a requirement on a caller's behalf.
|
package/README.md
CHANGED
|
@@ -242,3 +242,7 @@ durable spawn, treats the spawn and attach `abortSignal` as detach rather than k
|
|
|
242
242
|
enforces `timeoutMs` inside the sandbox for durable processes, and returns null for a
|
|
243
243
|
ref it cannot resolve, including another provider's. `runSandboxConformance` runs the
|
|
244
244
|
durable cases on any sandbox with `attachProcess`, directly and through the handle RPC.
|
|
245
|
+
|
|
246
|
+
### Retained desktop thumbnails
|
|
247
|
+
|
|
248
|
+
Providers may implement `environment.readThumbnail(ctx, state)` for authorized reads of a retained desktop image; see its contract in `types.ts` (no attach, wake, fresh capture or idle extension).
|
|
@@ -7,7 +7,8 @@ import {
|
|
|
7
7
|
sandboxArtifactKeyResultSchema,
|
|
8
8
|
sandboxAttachReplyFrameSchema,
|
|
9
9
|
sandboxOfferResultSchema,
|
|
10
|
-
sandboxProcessesResultSchema
|
|
10
|
+
sandboxProcessesResultSchema,
|
|
11
|
+
sandboxReadThumbnailResultSchema
|
|
11
12
|
} from "@finalai/agent-protocol/sandbox-provider-wire";
|
|
12
13
|
import * as z from "zod";
|
|
13
14
|
import { jsonValueSchema } from "../../json.mjs";
|
|
@@ -335,6 +336,14 @@ const remoteSandboxProvider = (args) => {
|
|
|
335
336
|
const { client } = await attachSocket(ctx, { ...attach, passive: true });
|
|
336
337
|
return handleOf(client, client);
|
|
337
338
|
};
|
|
339
|
+
if (registration.features.readThumbnail)
|
|
340
|
+
result.readThumbnail = async (ctx, state) => call({
|
|
341
|
+
path: SandboxProviderWirePath.ReadThumbnail,
|
|
342
|
+
ctx,
|
|
343
|
+
sandboxId: ctx.sandboxId,
|
|
344
|
+
fields: { sandboxId: ctx.sandboxId, state },
|
|
345
|
+
result: sandboxReadThumbnailResultSchema
|
|
346
|
+
});
|
|
338
347
|
if (registration.features.readSnapshot)
|
|
339
348
|
result.readSnapshot = async (ctx, state, request) => call({
|
|
340
349
|
path: SandboxProviderWirePath.ReadSnapshot,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
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;A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,EACT;AAEA,SAAO,sBAAmF;AAAA,IACxF,MAAM,aAAa;AAAA,IACnB,GAAI,aAAa,wBAAwB,OACrC,CAAC,IACD,EAAE,sBAAsB,aAAa,qBAAqB;AAAA,IAC9D,aAAa,CAAC,YAAY,eAAe,WAAW,IAAI;AAAA,EAC1D,CAAC;AACH;",
|
|
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 sandboxReadThumbnailResultSchema,\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.readThumbnail)\n result.readThumbnail = async (ctx, state) =>\n call({\n path: SandboxProviderWirePath.ReadThumbnail,\n ctx,\n sandboxId: ctx.sandboxId,\n fields: { sandboxId: ctx.sandboxId, state },\n result: sandboxReadThumbnailResultSchema,\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,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;AAClD,SAAO,OAAO,UAAU,CAAC,OAAO,IAAI,IAAI,CAAC;AAC3C,CAAC;AAEH,MAAM,sBAAsB,CAAC,UAC3B,OAAO,OAAO,iBAAiB,EAAE,KAAK,CAAC,eAAe,eAAe,KAAK;AAE5E,MA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;AAAA,IACnB,GAAI,aAAa,wBAAwB,OACrC,CAAC,IACD,EAAE,sBAAsB,aAAa,qBAAqB;AAAA,IAC9D,aAAa,CAAC,YAAY,eAAe,WAAW,IAAI;AAAA,EAC1D,CAAC;AACH;",
|
|
6
6
|
"names": ["call"]
|
|
7
7
|
}
|
|
@@ -22,6 +22,8 @@ import {
|
|
|
22
22
|
sandboxPrepareRequestSchema,
|
|
23
23
|
sandboxProcessesRequestSchema,
|
|
24
24
|
sandboxReadSnapshotRequestSchema,
|
|
25
|
+
sandboxReadThumbnailRequestSchema,
|
|
26
|
+
sandboxReadThumbnailResultSchema,
|
|
25
27
|
sandboxStateRequestSchema
|
|
26
28
|
} from "@finalai/agent-protocol/sandbox-provider-wire";
|
|
27
29
|
import * as z from "zod";
|
|
@@ -67,6 +69,7 @@ const LONG_CALLS = /* @__PURE__ */ new Set([
|
|
|
67
69
|
]);
|
|
68
70
|
const featuresOf = (implementation) => ({
|
|
69
71
|
readSnapshot: implementation?.readSnapshot != null,
|
|
72
|
+
readThumbnail: implementation?.readThumbnail != null,
|
|
70
73
|
processes: implementation?.processes != null,
|
|
71
74
|
editor: implementation?.editor != null,
|
|
72
75
|
attachPassive: implementation?.attachPassive != null
|
|
@@ -311,6 +314,25 @@ const serveSandboxProvider = (args) => {
|
|
|
311
314
|
)
|
|
312
315
|
};
|
|
313
316
|
}
|
|
317
|
+
case SandboxProviderWirePath.ReadThumbnail: {
|
|
318
|
+
const request = parse(sandboxReadThumbnailRequestSchema, body);
|
|
319
|
+
requireSandbox(identity, request.sandboxId);
|
|
320
|
+
const implementation = implementationOf(mount, request.environment);
|
|
321
|
+
if (implementation.readThumbnail == null) throw unsupported("thumbnail reads");
|
|
322
|
+
const result = sandboxReadThumbnailResultSchema.safeParse(
|
|
323
|
+
await implementation.readThumbnail(
|
|
324
|
+
{ ...base(request.secrets), sandboxId: request.sandboxId },
|
|
325
|
+
json(request.state)
|
|
326
|
+
)
|
|
327
|
+
);
|
|
328
|
+
if (!result.success)
|
|
329
|
+
throw sandboxProviderWireError({
|
|
330
|
+
code: SandboxProviderErrorCode.Unavailable,
|
|
331
|
+
message: `the provider returned an invalid retained thumbnail: ${z.prettifyError(result.error)}`,
|
|
332
|
+
retryable: false
|
|
333
|
+
});
|
|
334
|
+
return result.data;
|
|
335
|
+
}
|
|
314
336
|
case SandboxProviderWirePath.ReadSnapshot: {
|
|
315
337
|
const request = parse(sandboxReadSnapshotRequestSchema, body);
|
|
316
338
|
requireSandbox(identity, request.sandboxId);
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../src/sandbox/remote/serve.ts"],
|
|
4
|
-
"sourcesContent": ["import type { RuntimeKind } from '@finalai/agent-protocol';\nimport { platformIdentityExchangeResponseSchema } from '@finalai/agent-protocol/agent-platform/sandbox-providers';\nimport {\n JWKS_PATH,\n PlatformIdentityVariant,\n verifyPlatformIdentity,\n type JwksIface,\n type JwksKeySourceIface,\n type SandboxProviderIdentityIface,\n} from '@finalai/agent-protocol/identity';\nimport {\n SANDBOX_PROVIDER_DISCOVERY_PATH,\n SANDBOX_PROVIDER_HEARTBEAT_INTERVAL_MS,\n SANDBOX_PROVIDER_MAX_BODY_BYTES,\n SANDBOX_PROVIDER_WIRE_VERSION,\n SandboxProviderErrorCode,\n SandboxProviderWirePath,\n sandboxArtifactKeyRequestSchema,\n sandboxAttachFrameSchema,\n sandboxCapabilityOfferSchema,\n sandboxAwaitRunningRequestSchema,\n sandboxCreateRequestSchema,\n sandboxEditorRequestSchema,\n sandboxOfferRequestSchema,\n sandboxParkRequestSchema,\n sandboxPrepareRequestSchema,\n sandboxProcessesRequestSchema,\n sandboxReadSnapshotRequestSchema,\n sandboxStateRequestSchema,\n type SandboxAttachFrameIface,\n type SandboxAttachedFrameIface,\n type SandboxFormFactor,\n type SandboxProviderDiscoveryIface,\n type SandboxProviderErrorIface,\n type SandboxProviderFeaturesIface,\n} from '@finalai/agent-protocol/sandbox-provider-wire';\nimport * as z from 'zod';\nimport { jsonValueSchema, type JsonObject, type JsonValue } from \"../../json.mjs\";\nimport { sandboxEditorRequestSchema as editorRequestSchema } from \"../editor.mjs\";\nimport { FULL_SANDBOX_GRANT } from \"../grant.mjs\";\nimport { serveSandboxHandle, type HandleAuthorizeFn, type HandleLifecycle } from \"../server.mjs\";\nimport { sandboxSnapshotRequestSchema } from \"../snapshots.mjs\";\nimport {\n sandboxRuntimesOf,\n type AnySandboxProviderIface,\n type NetworkPolicyIface,\n type NetworkSandboxSessionIface,\n type SandboxCapabilityOffer,\n type SandboxEnvironmentImplementationIface,\n type SandboxIdentityFn,\n type SandboxIdentityTokenIface,\n type SandboxOfferContextIface,\n type SandboxPrepareContextIface,\n type SandboxProviderContextIface,\n type SandboxProviderHandleIface,\n type SandboxResourceContextIface,\n} from \"../types.mjs\";\nimport {\n frameChannelFromWebSocket,\n HandleRpcCloseCode,\n handleRpcTokenFromRequest,\n type WebSocketLikeIface,\n} from \"../wire.mjs\";\nimport { SANDBOX_PROVIDER_ERROR_STATUS, sandboxProviderWireError, wireErrorOf } from \"./errors.mjs\";\nimport { readBodyText } from \"./body.mjs\";\nimport { ndjsonResponse } from \"./ndjson.mjs\";\nimport {\n platformIdentityExchangeUrl,\n sandboxProviderArtifactBodySchema,\n sandboxProviderArtifactUrl,\n} from \"./platform-api.mjs\";\nimport { preambleChannel } from \"./preamble.mjs\";\n\n// Serves sandbox providers over the sandbox-provider wire\n// (`@finalai/agent-protocol/sandbox-provider-wire`), so a platform drives them\n// by URL exactly as it would in process. Each provider is mounted at its\n// registered URL (`publicUrl(name)`): lifecycle calls are HTTP, and `/v1/attach`\n// is a WebSocket whose frames, after the attach reply, are the handle RPC.\n//\n// Every call is authenticated by a sandbox-provider assertion the platform\n// signed for that URL, verified against the platform's JWKS. The provider's\n// context comes from it: the organization, project and sandbox it names, the\n// acting user it carries (replaced on the attach socket by\n// `identity/refresh`), the secrets the call forwards, and `identity`, which\n// exchanges the assertion for one to a backend the registration was granted.\n// Platform environment variables and files never reach the provider: the\n// platform's adapter applies them through the handle.\n\n// What a provider's discovery document says beyond what its definition does.\nexport interface SandboxProviderDiscoveryInputIface {\n title?: string | null;\n formFactor: SandboxFormFactor;\n // JSON Schema of the environment options.\n environmentSchema?: JsonObject | null;\n capabilities: SandboxCapabilityOffer;\n runtimes?: RuntimeKind[];\n // The optional calls it serves; by default, those its environment without\n // options implements.\n features?: SandboxProviderFeaturesIface;\n}\n\nexport interface ServedSandboxProviderIface {\n provider: AnySandboxProviderIface;\n discovery: SandboxProviderDiscoveryInputIface;\n}\n\nexport interface ServeSandboxProviderArgsIface {\n // Path segment (the name a project registers it under) \u2192 provider.\n providers: Record<string, ServedSandboxProviderIface>;\n // The platform's origin: the assertions' issuer, and where the exchange and\n // artifact routes are.\n issuer: string;\n // Defaults to the issuer's `/.well-known/jwks.json`.\n jwksUrl?: string;\n // A key set to verify against instead of fetching one.\n jwks?: JwksIface | JwksKeySourceIface;\n // The URL a provider is registered at: its assertions' audience.\n publicUrl: (name: string) => string;\n // For calls to the platform (exchange, artifacts).\n fetch?: typeof fetch;\n heartbeatMs?: number;\n now?: () => number;\n log?: (message: string, fields?: Record<string, string | number | boolean | null>) => void;\n}\n\nexport interface SandboxProviderServerIface {\n fetch(request: Request): Promise<Response>;\n // `/v1/attach`: the host accepted the upgrade; `request` is the upgrade request.\n upgrade(request: Request, socket: WebSocketLikeIface): void;\n}\n\n// Wire JSON as this package's JSON.\nconst json = (value: unknown): JsonValue => jsonValueSchema.parse(value);\n\n// An identity exchanged this long before it expires is asked for again.\nconst IDENTITY_REUSE_MARGIN_MS = 60_000;\n\nconst errorResponse = (error: SandboxProviderErrorIface, status?: number): Response =>\n Response.json({ error }, { status: status ?? SANDBOX_PROVIDER_ERROR_STATUS[error.code] });\n\nconst refused = (message: string): SandboxProviderErrorIface => ({\n code: SandboxProviderErrorCode.Forbidden,\n message,\n retryable: false,\n});\n\nconst invalid = (message: string): SandboxProviderErrorIface => ({\n code: SandboxProviderErrorCode.InvalidEnvironment,\n message,\n retryable: false,\n});\n\nconst LONG_CALLS: ReadonlySet<string> = new Set([\n SandboxProviderWirePath.Prepare,\n SandboxProviderWirePath.Create,\n SandboxProviderWirePath.AwaitRunning,\n]);\n\ninterface MountIface {\n name: string;\n served: ServedSandboxProviderIface;\n audience: string;\n // The URL's path without its trailing slash.\n prefix: string;\n}\n\n// The caller a call or an attach socket acts for: its assertion in force.\ninterface CallerIface {\n token: string;\n identity: SandboxProviderIdentityIface;\n}\n\ntype ImplementationType = SandboxEnvironmentImplementationIface<\n JsonValue,\n JsonValue,\n NetworkSandboxSessionIface\n>;\n\nconst featuresOf = (implementation: ImplementationType | null): SandboxProviderFeaturesIface => ({\n readSnapshot: implementation?.readSnapshot != null,\n processes: implementation?.processes != null,\n editor: implementation?.editor != null,\n attachPassive: implementation?.attachPassive != null,\n});\n\nexport const serveSandboxProvider = (\n args: ServeSandboxProviderArgsIface,\n): SandboxProviderServerIface => {\n const now = args.now ?? Date.now;\n const doFetch = args.fetch ?? fetch;\n const heartbeatMs = args.heartbeatMs ?? SANDBOX_PROVIDER_HEARTBEAT_INTERVAL_MS / 2;\n const keys =\n args.jwks != null\n ? { jwks: args.jwks }\n : { jwksUrl: args.jwksUrl ?? new URL(JWKS_PATH, args.issuer).toString() };\n const mounts: MountIface[] = Object.entries(args.providers).map(([name, served]) => {\n const audience = args.publicUrl(name);\n return { name, served, audience, prefix: new URL(audience).pathname.replace(/\\/+$/u, '') };\n });\n\n // The mount a request path is under, longest first, and the path within it.\n const route = (url: URL): { mount: MountIface; path: string } | null => {\n let best: { mount: MountIface; path: string } | null = null;\n for (const mount of mounts) {\n if (url.pathname !== mount.prefix && !url.pathname.startsWith(`${mount.prefix}/`)) continue;\n if (best != null && best.mount.prefix.length >= mount.prefix.length) continue;\n best = { mount, path: url.pathname.slice(mount.prefix.length) };\n }\n return best;\n };\n\n const verify = async (\n mount: MountIface,\n token: string | null,\n ): Promise<SandboxProviderIdentityIface | null> => {\n if (token == null) return null;\n const verified = await verifyPlatformIdentity({\n token,\n audience: mount.audience,\n variant: PlatformIdentityVariant.SandboxProvider,\n issuer: args.issuer,\n now: now(),\n ...keys,\n });\n return verified.ok ? verified.claims : null;\n };\n\n // `ctx.identity`: the current assertion exchanged for one to `audience`,\n // reused while the assertion it came from is in force.\n const identityFor = (caller: () => CallerIface): SandboxIdentityFn => {\n const cache = new Map<string, { subject: string; token: SandboxIdentityTokenIface }>();\n return async ({ audience, refresh }) => {\n const { token: subject } = caller();\n const cached = cache.get(audience);\n if (\n refresh !== true &&\n cached != null &&\n cached.subject === subject &&\n Date.parse(cached.token.expiresAt) - now() > IDENTITY_REUSE_MARGIN_MS\n )\n return cached.token;\n const response = await doFetch(platformIdentityExchangeUrl(args.issuer), {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ subjectToken: subject, audience }),\n });\n const text = await response.text();\n if (!response.ok)\n throw sandboxProviderWireError(\n refused(\n `identity for ${audience} was refused (${response.status}): ${text.slice(0, 200)}`,\n ),\n );\n const parsed = platformIdentityExchangeResponseSchema.safeParse(JSON.parse(text));\n if (!parsed.success) throw new Error(`unexpected identity exchange answer for ${audience}`);\n cache.set(audience, { subject, token: parsed.data });\n return parsed.data;\n };\n };\n\n const contextFor = (\n caller: () => CallerIface,\n secrets: Record<string, string>,\n ): SandboxProviderContextIface => ({\n organizationId: caller().identity.organizationId,\n projectId: caller().identity.projectId,\n credentials: { secret: async ({ secretRef }) => secrets[secretRef] ?? null },\n actingUser: { current: async () => caller().identity.userId },\n identity: identityFor(caller),\n log: args.log,\n });\n\n const artifactsFor = (caller: () => CallerIface): SandboxPrepareContextIface['artifacts'] => ({\n get: async (key) => {\n const response = await doFetch(sandboxProviderArtifactUrl(args.issuer, key), {\n headers: { authorization: `Bearer ${caller().token}` },\n });\n const text = await response.text();\n if (response.status === 404) return null;\n if (!response.ok) throw new Error(`reading artifact ${key} failed (${response.status})`);\n return sandboxProviderArtifactBodySchema.parse(JSON.parse(text)).artifact;\n },\n put: async (key, artifact) => {\n const response = await doFetch(sandboxProviderArtifactUrl(args.issuer, key), {\n method: 'PUT',\n headers: { authorization: `Bearer ${caller().token}`, 'content-type': 'application/json' },\n body: JSON.stringify({ artifact }),\n });\n await response.text();\n if (!response.ok) throw new Error(`storing artifact ${key} failed (${response.status})`);\n },\n });\n\n const storagePathOf = (identity: SandboxProviderIdentityIface, sandboxId: string | null) =>\n `${identity.organizationId}/${sandboxId ?? 'preparations'}`;\n\n const implementationOf = (mount: MountIface, environment: unknown): ImplementationType =>\n mount.served.provider.definition.environment(json(environment));\n\n const discoveryOf = (mount: MountIface): SandboxProviderDiscoveryIface => {\n let implementation: ImplementationType | null = null;\n if (mount.served.discovery.features == null)\n try {\n implementation = mount.served.provider.definition.environment(undefined);\n } catch {\n implementation = null;\n }\n return {\n wire: SANDBOX_PROVIDER_WIRE_VERSION,\n name: mount.name,\n title: mount.served.discovery.title ?? null,\n formFactor: mount.served.discovery.formFactor,\n environmentSchema: mount.served.discovery.environmentSchema ?? null,\n capabilities: sandboxCapabilityOfferSchema.parse(mount.served.discovery.capabilities),\n runtimes: mount.served.discovery.runtimes ?? [],\n features: mount.served.discovery.features ?? featuresOf(implementation),\n stateProtocolVersion: mount.served.provider.definition.stateProtocolVersion ?? null,\n };\n };\n\n const readBody = async (request: Request): Promise<unknown> => {\n const declared = Number(request.headers.get('content-length') ?? '0');\n if (declared > SANDBOX_PROVIDER_MAX_BODY_BYTES)\n throw sandboxProviderWireError(invalid('the request body is over the size limit'));\n const text = await readBodyText(request, SANDBOX_PROVIDER_MAX_BODY_BYTES);\n if (text == null)\n throw sandboxProviderWireError(invalid('the request body is over the size limit'));\n try {\n return JSON.parse(text);\n } catch {\n throw sandboxProviderWireError(invalid('the request body is not JSON'));\n }\n };\n\n const parse = <S extends z.ZodType>(schema: S, body: unknown): z.output<S> => {\n const parsed = schema.safeParse(body);\n if (!parsed.success) throw sandboxProviderWireError(invalid(z.prettifyError(parsed.error)));\n return parsed.data;\n };\n\n // A call about one sandbox must carry that sandbox's assertion.\n const requireSandbox = (identity: SandboxProviderIdentityIface, sandboxId: string) => {\n if (identity.sandboxId !== sandboxId)\n throw sandboxProviderWireError(refused('the assertion is for another sandbox'));\n };\n\n const unsupported = (what: string) =>\n sandboxProviderWireError({\n code: SandboxProviderErrorCode.NotFound,\n message: `this provider has no ${what}`,\n retryable: false,\n });\n\n // One wire call; the result is the JSON the answer carries.\n const dispatch = async (\n mount: MountIface,\n path: string,\n caller: CallerIface,\n body: unknown,\n ): Promise<JsonValue> => {\n const { identity } = caller;\n const callerOf = () => caller;\n const base = (secrets: Record<string, string>) => contextFor(callerOf, secrets);\n const resourceContext = (fields: {\n sandboxId: string;\n secrets: Record<string, string>;\n platformEgressHosts?: string[];\n lifecycle?: SandboxResourceContextIface['lifecycle'];\n }): SandboxResourceContextIface => ({\n ...base(fields.secrets),\n sandboxId: fields.sandboxId,\n storagePath: storagePathOf(identity, fields.sandboxId),\n lifecycle: fields.lifecycle ?? { parkAfterIdleMs: null },\n platformEgressHosts: fields.platformEgressHosts,\n // Lifecycle calls apply no network policy; attach reports it on the socket.\n platformNetworkPolicy: async () => undefined,\n });\n switch (path) {\n case SandboxProviderWirePath.Offer: {\n const request = parse(sandboxOfferRequestSchema, body);\n if (request.sandboxId != null) requireSandbox(identity, request.sandboxId);\n const implementation = implementationOf(mount, request.environment);\n const ctx: SandboxOfferContextIface = {\n ...base(request.secrets),\n ...(request.sandboxId == null ? {} : { sandboxId: request.sandboxId }),\n };\n const [capabilities, runtimes, features, additionalFeatures, mcpCatalog] =\n await Promise.all([\n implementation.capabilities(ctx),\n sandboxRuntimesOf(implementation, ctx),\n implementation.features?.(ctx) ?? null,\n implementation.additionalFeatures?.(ctx) ?? [],\n implementation.mcpCatalog?.(ctx) ?? null,\n ]);\n return {\n capabilities: { ...capabilities },\n runtimes,\n features,\n additionalFeatures,\n mcpCatalog:\n mcpCatalog == null\n ? null\n : {\n computerUse: mcpCatalog.computerUse,\n localMcp: mcpCatalog.localMcp,\n ...(mcpCatalog.localMcpIncomplete == null\n ? {}\n : { localMcpIncomplete: mcpCatalog.localMcpIncomplete }),\n },\n };\n }\n case SandboxProviderWirePath.ArtifactKey:\n case SandboxProviderWirePath.Prepare: {\n const request = parse(\n path === SandboxProviderWirePath.Prepare\n ? sandboxPrepareRequestSchema\n : sandboxArtifactKeyRequestSchema,\n body,\n );\n const implementation = implementationOf(mount, request.environment);\n const ctx: SandboxPrepareContextIface = {\n ...base(request.secrets),\n files: request.files,\n resources: z.record(z.string(), jsonValueSchema).parse(request.resources),\n sourceRevision: request.sourceRevision,\n storagePath: storagePathOf(identity, identity.sandboxId),\n artifacts: artifactsFor(callerOf),\n };\n if (path === SandboxProviderWirePath.ArtifactKey)\n return { key: await implementation.artifactKey(ctx) };\n return { artifact: await implementation.prepare(ctx) };\n }\n case SandboxProviderWirePath.Create: {\n const request = parse(sandboxCreateRequestSchema, body);\n requireSandbox(identity, request.sandboxId);\n const implementation = implementationOf(mount, request.environment);\n const created = await implementation.create(\n resourceContext({\n sandboxId: request.sandboxId,\n secrets: request.secrets,\n platformEgressHosts: request.platformEgressHosts,\n lifecycle: request.lifecycle,\n }),\n { artifact: json(request.artifact), setup: request.setup },\n );\n return { state: created.state, region: created.region ?? null };\n }\n case SandboxProviderWirePath.AwaitRunning: {\n const request = parse(sandboxAwaitRunningRequestSchema, body);\n requireSandbox(identity, request.sandboxId);\n await implementationOf(mount, request.environment).awaitRunning(\n resourceContext({ sandboxId: request.sandboxId, secrets: request.secrets }),\n json(request.state),\n { timeoutMs: request.timeoutMs },\n );\n return {};\n }\n case SandboxProviderWirePath.Detach:\n case SandboxProviderWirePath.Delete: {\n const request = parse(sandboxStateRequestSchema, body);\n requireSandbox(identity, request.sandboxId);\n const implementation = implementationOf(mount, request.environment);\n const ctx = resourceContext({ sandboxId: request.sandboxId, secrets: request.secrets });\n if (path === SandboxProviderWirePath.Delete) {\n await implementation.delete(ctx, { state: json(request.state) });\n return {};\n }\n return { state: await implementation.detach(ctx, { state: json(request.state) }) };\n }\n case SandboxProviderWirePath.Park: {\n const request = parse(sandboxParkRequestSchema, body);\n requireSandbox(identity, request.sandboxId);\n const implementation = implementationOf(mount, request.environment);\n return {\n state: await implementation.park(\n resourceContext({ sandboxId: request.sandboxId, secrets: request.secrets }),\n { artifact: json(request.artifact), state: json(request.state) },\n ),\n };\n }\n case SandboxProviderWirePath.ReadSnapshot: {\n const request = parse(sandboxReadSnapshotRequestSchema, body);\n requireSandbox(identity, request.sandboxId);\n const implementation = implementationOf(mount, request.environment);\n if (implementation.readSnapshot == null) throw unsupported('snapshot reads');\n const response = await implementation.readSnapshot(\n { ...base(request.secrets), sandboxId: request.sandboxId },\n json(request.state),\n parse(sandboxSnapshotRequestSchema, request.request),\n );\n return response == null ? null : { ...response };\n }\n case SandboxProviderWirePath.Processes: {\n const request = parse(sandboxProcessesRequestSchema, body);\n requireSandbox(identity, request.sandboxId);\n const implementation = implementationOf(mount, request.environment);\n if (implementation.processes == null) throw unsupported('process inspection');\n return {\n ...(await implementation.processes(\n { ...base(request.secrets), sandboxId: request.sandboxId },\n json(request.state),\n request.request,\n )),\n };\n }\n case SandboxProviderWirePath.Editor: {\n const request = parse(sandboxEditorRequestSchema, body);\n requireSandbox(identity, request.sandboxId);\n const implementation = implementationOf(mount, request.environment);\n if (implementation.editor == null) throw unsupported('editor');\n return {\n ...(await implementation.editor(\n { ...base(request.secrets), sandboxId: request.sandboxId },\n json(request.state),\n parse(editorRequestSchema, request.request),\n )),\n };\n }\n default:\n throw unsupported(`call ${path}`);\n }\n };\n\n const fetchHandler = async (request: Request): Promise<Response> => {\n const url = new URL(request.url);\n const routed = route(url);\n if (routed == null)\n return errorResponse({\n code: SandboxProviderErrorCode.NotFound,\n message: 'no sandbox provider is served here',\n retryable: false,\n });\n const { mount, path } = routed;\n if (request.method === 'GET' && path === SANDBOX_PROVIDER_DISCOVERY_PATH)\n return Response.json(discoveryOf(mount));\n if (request.method !== 'POST' || path === SandboxProviderWirePath.Attach)\n return errorResponse(invalid(`${request.method} ${path} is not a provider call`), 405);\n const token = /^Bearer\\s+(.+)$/iu.exec(request.headers.get('authorization')?.trim() ?? '')?.[1];\n const identity = await verify(mount, token ?? null);\n if (identity == null || token == null)\n return errorResponse(refused('a valid sandbox-provider assertion is required'), 401);\n const caller: CallerIface = { token, identity };\n let body: unknown;\n try {\n body = await readBody(request);\n } catch (cause) {\n return errorResponse(wireErrorOf(cause));\n }\n if (LONG_CALLS.has(path))\n return ndjsonResponse({ work: () => dispatch(mount, path, caller, body), heartbeatMs });\n try {\n return Response.json(await dispatch(mount, path, caller, body));\n } catch (cause) {\n return errorResponse(wireErrorOf(cause));\n }\n };\n\n const upgrade = (request: Request, socket: WebSocketLikeIface): void => {\n const { channel } = frameChannelFromWebSocket(socket);\n const preamble = preambleChannel(channel);\n const fail = (error: SandboxProviderErrorIface, code: number = HandleRpcCloseCode.Normal) => {\n channel.send(JSON.stringify({ type: 'error', error }));\n channel.close(code, error.message.slice(0, 120));\n };\n void (async () => {\n const routed = route(new URL(request.url));\n if (routed == null || routed.path !== SandboxProviderWirePath.Attach) {\n fail({\n code: SandboxProviderErrorCode.NotFound,\n message: 'no sandbox provider attaches here',\n retryable: false,\n });\n return;\n }\n const { mount } = routed;\n const token = handleRpcTokenFromRequest(request);\n const identity = await verify(mount, token);\n if (identity == null || token == null) {\n fail(\n refused('a valid sandbox-provider assertion is required'),\n HandleRpcCloseCode.Unauthorized,\n );\n return;\n }\n let caller: CallerIface = { token, identity };\n let frame: SandboxAttachFrameIface;\n try {\n const first = await preamble.next();\n if (typeof first !== 'string') throw new Error('the attach request must be a text frame');\n frame = parse(sandboxAttachFrameSchema, JSON.parse(first));\n requireSandbox(identity, frame.sandboxId);\n } catch (cause) {\n fail(wireErrorOf(cause));\n return;\n }\n const heartbeat = setInterval(\n () => channel.send(JSON.stringify({ type: 'heartbeat' })),\n heartbeatMs,\n );\n let reported: NetworkPolicyIface | null = null;\n const ctx: SandboxResourceContextIface = {\n ...contextFor(() => caller, frame.secrets),\n sandboxId: frame.sandboxId,\n storagePath: storagePathOf(identity, frame.sandboxId),\n lifecycle: frame.lifecycle,\n platformEgressHosts: frame.platformEgressHosts,\n platformNetworkPolicy: async (policy) => {\n reported = policy;\n },\n };\n let handle: SandboxProviderHandleIface<NetworkSandboxSessionIface>;\n let attached: SandboxAttachedFrameIface;\n try {\n const implementation = implementationOf(mount, frame.environment);\n if (frame.passive) {\n if (implementation.attachPassive == null) throw unsupported('passive attach');\n handle = await implementation.attachPassive(ctx, {\n artifact: json(frame.artifact),\n state: json(frame.state),\n });\n attached = {\n type: 'attached',\n state: json(frame.state),\n fresh: false,\n booted: false,\n region: null,\n networkPolicy: null,\n };\n } else {\n const attachment = await implementation.attach(ctx, {\n artifact: json(frame.artifact),\n state: json(frame.state),\n });\n handle = attachment.handle;\n attached = {\n type: 'attached',\n state: attachment.state,\n fresh: attachment.fresh,\n booted: attachment.booted,\n region: attachment.region ?? null,\n networkPolicy: reported,\n };\n }\n } catch (cause) {\n clearInterval(heartbeat);\n fail(wireErrorOf(cause));\n return;\n }\n clearInterval(heartbeat);\n // The handle is released once, by the platform or when the socket goes.\n let shutdown: Promise<void> | null = null;\n const lifecycle: HandleLifecycle = {\n onSandboxStop: () => handle.onSandboxStop(),\n onSandboxDelete: (options) => handle.onSandboxDelete(options),\n onRuntimeShutdown: () => {\n shutdown ??= handle.onRuntimeShutdown();\n return shutdown;\n },\n };\n // `initialize { identity }` and `identity/refresh`: an assertion for the\n // same provider and sandbox, which becomes the caller's.\n const authorize: HandleAuthorizeFn = async ({ identity: assertion }) => {\n const next = await verify(mount, assertion ?? null);\n if (\n next == null ||\n assertion == null ||\n next.providerId !== identity.providerId ||\n next.sandboxId !== identity.sandboxId ||\n next.organizationId !== identity.organizationId ||\n next.projectId !== identity.projectId\n )\n return null;\n caller = { token: assertion, identity: next };\n return { expiresAt: new Date(next.expiresAt).toISOString() };\n };\n channel.send(JSON.stringify(attached));\n serveSandboxHandle({\n sandbox: handle.sandbox,\n handle: lifecycle,\n authorize,\n access: { grant: FULL_SANDBOX_GRANT, lifecycle: true },\n mcpChannels: true,\n }).attach(preamble.rest());\n await preamble.closed;\n await lifecycle.onRuntimeShutdown().catch((cause: unknown) =>\n args.log?.('sandbox provider handle shutdown failed', {\n provider: mount.name,\n sandboxId: frame.sandboxId,\n error: cause instanceof Error ? cause.message : String(cause),\n }),\n );\n })();\n };\n\n return { fetch: fetchHandler, upgrade };\n};\n"],
|
|
5
|
-
"mappings": "AACA,SAAS,8CAA8C;AACvD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAIK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAOK;AACP,YAAY,OAAO;AACnB,SAAS,uBAAwD;AACjE,SAAS,8BAA8B,2BAA2B;AAClE,SAAS,0BAA0B;AACnC,SAAS,0BAAwE;AACjF,SAAS,oCAAoC;AAC7C;AAAA,EACE;AAAA,OAaK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,+BAA+B,0BAA0B,mBAAmB;AACrF,SAAS,oBAAoB;AAC7B,SAAS,sBAAsB;AAC/B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,uBAAuB;AA6DhC,MAAM,OAAO,CAAC,UAA8B,gBAAgB,MAAM,KAAK;AAGvE,MAAM,2BAA2B;AAEjC,MAAM,gBAAgB,CAAC,OAAkC,WACvD,SAAS,KAAK,EAAE,MAAM,GAAG,EAAE,QAAQ,UAAU,8BAA8B,MAAM,IAAI,EAAE,CAAC;AAE1F,MAAM,UAA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EAAE,OAAO,cAAc,QAAQ;AACxC;",
|
|
4
|
+
"sourcesContent": ["import type { RuntimeKind } from '@finalai/agent-protocol';\nimport { platformIdentityExchangeResponseSchema } from '@finalai/agent-protocol/agent-platform/sandbox-providers';\nimport {\n JWKS_PATH,\n PlatformIdentityVariant,\n verifyPlatformIdentity,\n type JwksIface,\n type JwksKeySourceIface,\n type SandboxProviderIdentityIface,\n} from '@finalai/agent-protocol/identity';\nimport {\n SANDBOX_PROVIDER_DISCOVERY_PATH,\n SANDBOX_PROVIDER_HEARTBEAT_INTERVAL_MS,\n SANDBOX_PROVIDER_MAX_BODY_BYTES,\n SANDBOX_PROVIDER_WIRE_VERSION,\n SandboxProviderErrorCode,\n SandboxProviderWirePath,\n sandboxArtifactKeyRequestSchema,\n sandboxAttachFrameSchema,\n sandboxCapabilityOfferSchema,\n sandboxAwaitRunningRequestSchema,\n sandboxCreateRequestSchema,\n sandboxEditorRequestSchema,\n sandboxOfferRequestSchema,\n sandboxParkRequestSchema,\n sandboxPrepareRequestSchema,\n sandboxProcessesRequestSchema,\n sandboxReadSnapshotRequestSchema,\n sandboxReadThumbnailRequestSchema,\n sandboxReadThumbnailResultSchema,\n sandboxStateRequestSchema,\n type SandboxAttachFrameIface,\n type SandboxAttachedFrameIface,\n type SandboxFormFactor,\n type SandboxProviderDiscoveryIface,\n type SandboxProviderErrorIface,\n type SandboxProviderFeaturesIface,\n} from '@finalai/agent-protocol/sandbox-provider-wire';\nimport * as z from 'zod';\nimport { jsonValueSchema, type JsonObject, type JsonValue } from \"../../json.mjs\";\nimport { sandboxEditorRequestSchema as editorRequestSchema } from \"../editor.mjs\";\nimport { FULL_SANDBOX_GRANT } from \"../grant.mjs\";\nimport { serveSandboxHandle, type HandleAuthorizeFn, type HandleLifecycle } from \"../server.mjs\";\nimport { sandboxSnapshotRequestSchema } from \"../snapshots.mjs\";\nimport {\n sandboxRuntimesOf,\n type AnySandboxProviderIface,\n type NetworkPolicyIface,\n type NetworkSandboxSessionIface,\n type SandboxCapabilityOffer,\n type SandboxEnvironmentImplementationIface,\n type SandboxIdentityFn,\n type SandboxIdentityTokenIface,\n type SandboxOfferContextIface,\n type SandboxPrepareContextIface,\n type SandboxProviderContextIface,\n type SandboxProviderHandleIface,\n type SandboxResourceContextIface,\n} from \"../types.mjs\";\nimport {\n frameChannelFromWebSocket,\n HandleRpcCloseCode,\n handleRpcTokenFromRequest,\n type WebSocketLikeIface,\n} from \"../wire.mjs\";\nimport { SANDBOX_PROVIDER_ERROR_STATUS, sandboxProviderWireError, wireErrorOf } from \"./errors.mjs\";\nimport { readBodyText } from \"./body.mjs\";\nimport { ndjsonResponse } from \"./ndjson.mjs\";\nimport {\n platformIdentityExchangeUrl,\n sandboxProviderArtifactBodySchema,\n sandboxProviderArtifactUrl,\n} from \"./platform-api.mjs\";\nimport { preambleChannel } from \"./preamble.mjs\";\n\n// Serves sandbox providers over the sandbox-provider wire\n// (`@finalai/agent-protocol/sandbox-provider-wire`), so a platform drives them\n// by URL exactly as it would in process. Each provider is mounted at its\n// registered URL (`publicUrl(name)`): lifecycle calls are HTTP, and `/v1/attach`\n// is a WebSocket whose frames, after the attach reply, are the handle RPC.\n//\n// Every call is authenticated by a sandbox-provider assertion the platform\n// signed for that URL, verified against the platform's JWKS. The provider's\n// context comes from it: the organization, project and sandbox it names, the\n// acting user it carries (replaced on the attach socket by\n// `identity/refresh`), the secrets the call forwards, and `identity`, which\n// exchanges the assertion for one to a backend the registration was granted.\n// Platform environment variables and files never reach the provider: the\n// platform's adapter applies them through the handle.\n\n// What a provider's discovery document says beyond what its definition does.\nexport interface SandboxProviderDiscoveryInputIface {\n title?: string | null;\n formFactor: SandboxFormFactor;\n // JSON Schema of the environment options.\n environmentSchema?: JsonObject | null;\n capabilities: SandboxCapabilityOffer;\n runtimes?: RuntimeKind[];\n // The optional calls it serves; by default, those its environment without\n // options implements.\n features?: SandboxProviderFeaturesIface;\n}\n\nexport interface ServedSandboxProviderIface {\n provider: AnySandboxProviderIface;\n discovery: SandboxProviderDiscoveryInputIface;\n}\n\nexport interface ServeSandboxProviderArgsIface {\n // Path segment (the name a project registers it under) \u2192 provider.\n providers: Record<string, ServedSandboxProviderIface>;\n // The platform's origin: the assertions' issuer, and where the exchange and\n // artifact routes are.\n issuer: string;\n // Defaults to the issuer's `/.well-known/jwks.json`.\n jwksUrl?: string;\n // A key set to verify against instead of fetching one.\n jwks?: JwksIface | JwksKeySourceIface;\n // The URL a provider is registered at: its assertions' audience.\n publicUrl: (name: string) => string;\n // For calls to the platform (exchange, artifacts).\n fetch?: typeof fetch;\n heartbeatMs?: number;\n now?: () => number;\n log?: (message: string, fields?: Record<string, string | number | boolean | null>) => void;\n}\n\nexport interface SandboxProviderServerIface {\n fetch(request: Request): Promise<Response>;\n // `/v1/attach`: the host accepted the upgrade; `request` is the upgrade request.\n upgrade(request: Request, socket: WebSocketLikeIface): void;\n}\n\n// Wire JSON as this package's JSON.\nconst json = (value: unknown): JsonValue => jsonValueSchema.parse(value);\n\n// An identity exchanged this long before it expires is asked for again.\nconst IDENTITY_REUSE_MARGIN_MS = 60_000;\n\nconst errorResponse = (error: SandboxProviderErrorIface, status?: number): Response =>\n Response.json({ error }, { status: status ?? SANDBOX_PROVIDER_ERROR_STATUS[error.code] });\n\nconst refused = (message: string): SandboxProviderErrorIface => ({\n code: SandboxProviderErrorCode.Forbidden,\n message,\n retryable: false,\n});\n\nconst invalid = (message: string): SandboxProviderErrorIface => ({\n code: SandboxProviderErrorCode.InvalidEnvironment,\n message,\n retryable: false,\n});\n\nconst LONG_CALLS: ReadonlySet<string> = new Set([\n SandboxProviderWirePath.Prepare,\n SandboxProviderWirePath.Create,\n SandboxProviderWirePath.AwaitRunning,\n]);\n\ninterface MountIface {\n name: string;\n served: ServedSandboxProviderIface;\n audience: string;\n // The URL's path without its trailing slash.\n prefix: string;\n}\n\n// The caller a call or an attach socket acts for: its assertion in force.\ninterface CallerIface {\n token: string;\n identity: SandboxProviderIdentityIface;\n}\n\ntype ImplementationType = SandboxEnvironmentImplementationIface<\n JsonValue,\n JsonValue,\n NetworkSandboxSessionIface\n>;\n\nconst featuresOf = (implementation: ImplementationType | null): SandboxProviderFeaturesIface => ({\n readSnapshot: implementation?.readSnapshot != null,\n readThumbnail: implementation?.readThumbnail != null,\n processes: implementation?.processes != null,\n editor: implementation?.editor != null,\n attachPassive: implementation?.attachPassive != null,\n});\n\nexport const serveSandboxProvider = (\n args: ServeSandboxProviderArgsIface,\n): SandboxProviderServerIface => {\n const now = args.now ?? Date.now;\n const doFetch = args.fetch ?? fetch;\n const heartbeatMs = args.heartbeatMs ?? SANDBOX_PROVIDER_HEARTBEAT_INTERVAL_MS / 2;\n const keys =\n args.jwks != null\n ? { jwks: args.jwks }\n : { jwksUrl: args.jwksUrl ?? new URL(JWKS_PATH, args.issuer).toString() };\n const mounts: MountIface[] = Object.entries(args.providers).map(([name, served]) => {\n const audience = args.publicUrl(name);\n return { name, served, audience, prefix: new URL(audience).pathname.replace(/\\/+$/u, '') };\n });\n\n // The mount a request path is under, longest first, and the path within it.\n const route = (url: URL): { mount: MountIface; path: string } | null => {\n let best: { mount: MountIface; path: string } | null = null;\n for (const mount of mounts) {\n if (url.pathname !== mount.prefix && !url.pathname.startsWith(`${mount.prefix}/`)) continue;\n if (best != null && best.mount.prefix.length >= mount.prefix.length) continue;\n best = { mount, path: url.pathname.slice(mount.prefix.length) };\n }\n return best;\n };\n\n const verify = async (\n mount: MountIface,\n token: string | null,\n ): Promise<SandboxProviderIdentityIface | null> => {\n if (token == null) return null;\n const verified = await verifyPlatformIdentity({\n token,\n audience: mount.audience,\n variant: PlatformIdentityVariant.SandboxProvider,\n issuer: args.issuer,\n now: now(),\n ...keys,\n });\n return verified.ok ? verified.claims : null;\n };\n\n // `ctx.identity`: the current assertion exchanged for one to `audience`,\n // reused while the assertion it came from is in force.\n const identityFor = (caller: () => CallerIface): SandboxIdentityFn => {\n const cache = new Map<string, { subject: string; token: SandboxIdentityTokenIface }>();\n return async ({ audience, refresh }) => {\n const { token: subject } = caller();\n const cached = cache.get(audience);\n if (\n refresh !== true &&\n cached != null &&\n cached.subject === subject &&\n Date.parse(cached.token.expiresAt) - now() > IDENTITY_REUSE_MARGIN_MS\n )\n return cached.token;\n const response = await doFetch(platformIdentityExchangeUrl(args.issuer), {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ subjectToken: subject, audience }),\n });\n const text = await response.text();\n if (!response.ok)\n throw sandboxProviderWireError(\n refused(\n `identity for ${audience} was refused (${response.status}): ${text.slice(0, 200)}`,\n ),\n );\n const parsed = platformIdentityExchangeResponseSchema.safeParse(JSON.parse(text));\n if (!parsed.success) throw new Error(`unexpected identity exchange answer for ${audience}`);\n cache.set(audience, { subject, token: parsed.data });\n return parsed.data;\n };\n };\n\n const contextFor = (\n caller: () => CallerIface,\n secrets: Record<string, string>,\n ): SandboxProviderContextIface => ({\n organizationId: caller().identity.organizationId,\n projectId: caller().identity.projectId,\n credentials: { secret: async ({ secretRef }) => secrets[secretRef] ?? null },\n actingUser: { current: async () => caller().identity.userId },\n identity: identityFor(caller),\n log: args.log,\n });\n\n const artifactsFor = (caller: () => CallerIface): SandboxPrepareContextIface['artifacts'] => ({\n get: async (key) => {\n const response = await doFetch(sandboxProviderArtifactUrl(args.issuer, key), {\n headers: { authorization: `Bearer ${caller().token}` },\n });\n const text = await response.text();\n if (response.status === 404) return null;\n if (!response.ok) throw new Error(`reading artifact ${key} failed (${response.status})`);\n return sandboxProviderArtifactBodySchema.parse(JSON.parse(text)).artifact;\n },\n put: async (key, artifact) => {\n const response = await doFetch(sandboxProviderArtifactUrl(args.issuer, key), {\n method: 'PUT',\n headers: { authorization: `Bearer ${caller().token}`, 'content-type': 'application/json' },\n body: JSON.stringify({ artifact }),\n });\n await response.text();\n if (!response.ok) throw new Error(`storing artifact ${key} failed (${response.status})`);\n },\n });\n\n const storagePathOf = (identity: SandboxProviderIdentityIface, sandboxId: string | null) =>\n `${identity.organizationId}/${sandboxId ?? 'preparations'}`;\n\n const implementationOf = (mount: MountIface, environment: unknown): ImplementationType =>\n mount.served.provider.definition.environment(json(environment));\n\n const discoveryOf = (mount: MountIface): SandboxProviderDiscoveryIface => {\n let implementation: ImplementationType | null = null;\n if (mount.served.discovery.features == null)\n try {\n implementation = mount.served.provider.definition.environment(undefined);\n } catch {\n implementation = null;\n }\n return {\n wire: SANDBOX_PROVIDER_WIRE_VERSION,\n name: mount.name,\n title: mount.served.discovery.title ?? null,\n formFactor: mount.served.discovery.formFactor,\n environmentSchema: mount.served.discovery.environmentSchema ?? null,\n capabilities: sandboxCapabilityOfferSchema.parse(mount.served.discovery.capabilities),\n runtimes: mount.served.discovery.runtimes ?? [],\n features: mount.served.discovery.features ?? featuresOf(implementation),\n stateProtocolVersion: mount.served.provider.definition.stateProtocolVersion ?? null,\n };\n };\n\n const readBody = async (request: Request): Promise<unknown> => {\n const declared = Number(request.headers.get('content-length') ?? '0');\n if (declared > SANDBOX_PROVIDER_MAX_BODY_BYTES)\n throw sandboxProviderWireError(invalid('the request body is over the size limit'));\n const text = await readBodyText(request, SANDBOX_PROVIDER_MAX_BODY_BYTES);\n if (text == null)\n throw sandboxProviderWireError(invalid('the request body is over the size limit'));\n try {\n return JSON.parse(text);\n } catch {\n throw sandboxProviderWireError(invalid('the request body is not JSON'));\n }\n };\n\n const parse = <S extends z.ZodType>(schema: S, body: unknown): z.output<S> => {\n const parsed = schema.safeParse(body);\n if (!parsed.success) throw sandboxProviderWireError(invalid(z.prettifyError(parsed.error)));\n return parsed.data;\n };\n\n // A call about one sandbox must carry that sandbox's assertion.\n const requireSandbox = (identity: SandboxProviderIdentityIface, sandboxId: string) => {\n if (identity.sandboxId !== sandboxId)\n throw sandboxProviderWireError(refused('the assertion is for another sandbox'));\n };\n\n const unsupported = (what: string) =>\n sandboxProviderWireError({\n code: SandboxProviderErrorCode.NotFound,\n message: `this provider has no ${what}`,\n retryable: false,\n });\n\n // One wire call; the result is the JSON the answer carries.\n const dispatch = async (\n mount: MountIface,\n path: string,\n caller: CallerIface,\n body: unknown,\n ): Promise<JsonValue> => {\n const { identity } = caller;\n const callerOf = () => caller;\n const base = (secrets: Record<string, string>) => contextFor(callerOf, secrets);\n const resourceContext = (fields: {\n sandboxId: string;\n secrets: Record<string, string>;\n platformEgressHosts?: string[];\n lifecycle?: SandboxResourceContextIface['lifecycle'];\n }): SandboxResourceContextIface => ({\n ...base(fields.secrets),\n sandboxId: fields.sandboxId,\n storagePath: storagePathOf(identity, fields.sandboxId),\n lifecycle: fields.lifecycle ?? { parkAfterIdleMs: null },\n platformEgressHosts: fields.platformEgressHosts,\n // Lifecycle calls apply no network policy; attach reports it on the socket.\n platformNetworkPolicy: async () => undefined,\n });\n switch (path) {\n case SandboxProviderWirePath.Offer: {\n const request = parse(sandboxOfferRequestSchema, body);\n if (request.sandboxId != null) requireSandbox(identity, request.sandboxId);\n const implementation = implementationOf(mount, request.environment);\n const ctx: SandboxOfferContextIface = {\n ...base(request.secrets),\n ...(request.sandboxId == null ? {} : { sandboxId: request.sandboxId }),\n };\n const [capabilities, runtimes, features, additionalFeatures, mcpCatalog] =\n await Promise.all([\n implementation.capabilities(ctx),\n sandboxRuntimesOf(implementation, ctx),\n implementation.features?.(ctx) ?? null,\n implementation.additionalFeatures?.(ctx) ?? [],\n implementation.mcpCatalog?.(ctx) ?? null,\n ]);\n return {\n capabilities: { ...capabilities },\n runtimes,\n features,\n additionalFeatures,\n mcpCatalog:\n mcpCatalog == null\n ? null\n : {\n computerUse: mcpCatalog.computerUse,\n localMcp: mcpCatalog.localMcp,\n ...(mcpCatalog.localMcpIncomplete == null\n ? {}\n : { localMcpIncomplete: mcpCatalog.localMcpIncomplete }),\n },\n };\n }\n case SandboxProviderWirePath.ArtifactKey:\n case SandboxProviderWirePath.Prepare: {\n const request = parse(\n path === SandboxProviderWirePath.Prepare\n ? sandboxPrepareRequestSchema\n : sandboxArtifactKeyRequestSchema,\n body,\n );\n const implementation = implementationOf(mount, request.environment);\n const ctx: SandboxPrepareContextIface = {\n ...base(request.secrets),\n files: request.files,\n resources: z.record(z.string(), jsonValueSchema).parse(request.resources),\n sourceRevision: request.sourceRevision,\n storagePath: storagePathOf(identity, identity.sandboxId),\n artifacts: artifactsFor(callerOf),\n };\n if (path === SandboxProviderWirePath.ArtifactKey)\n return { key: await implementation.artifactKey(ctx) };\n return { artifact: await implementation.prepare(ctx) };\n }\n case SandboxProviderWirePath.Create: {\n const request = parse(sandboxCreateRequestSchema, body);\n requireSandbox(identity, request.sandboxId);\n const implementation = implementationOf(mount, request.environment);\n const created = await implementation.create(\n resourceContext({\n sandboxId: request.sandboxId,\n secrets: request.secrets,\n platformEgressHosts: request.platformEgressHosts,\n lifecycle: request.lifecycle,\n }),\n { artifact: json(request.artifact), setup: request.setup },\n );\n return { state: created.state, region: created.region ?? null };\n }\n case SandboxProviderWirePath.AwaitRunning: {\n const request = parse(sandboxAwaitRunningRequestSchema, body);\n requireSandbox(identity, request.sandboxId);\n await implementationOf(mount, request.environment).awaitRunning(\n resourceContext({ sandboxId: request.sandboxId, secrets: request.secrets }),\n json(request.state),\n { timeoutMs: request.timeoutMs },\n );\n return {};\n }\n case SandboxProviderWirePath.Detach:\n case SandboxProviderWirePath.Delete: {\n const request = parse(sandboxStateRequestSchema, body);\n requireSandbox(identity, request.sandboxId);\n const implementation = implementationOf(mount, request.environment);\n const ctx = resourceContext({ sandboxId: request.sandboxId, secrets: request.secrets });\n if (path === SandboxProviderWirePath.Delete) {\n await implementation.delete(ctx, { state: json(request.state) });\n return {};\n }\n return { state: await implementation.detach(ctx, { state: json(request.state) }) };\n }\n case SandboxProviderWirePath.Park: {\n const request = parse(sandboxParkRequestSchema, body);\n requireSandbox(identity, request.sandboxId);\n const implementation = implementationOf(mount, request.environment);\n return {\n state: await implementation.park(\n resourceContext({ sandboxId: request.sandboxId, secrets: request.secrets }),\n { artifact: json(request.artifact), state: json(request.state) },\n ),\n };\n }\n case SandboxProviderWirePath.ReadThumbnail: {\n const request = parse(sandboxReadThumbnailRequestSchema, body);\n requireSandbox(identity, request.sandboxId);\n const implementation = implementationOf(mount, request.environment);\n if (implementation.readThumbnail == null) throw unsupported('thumbnail reads');\n const result = sandboxReadThumbnailResultSchema.safeParse(\n await implementation.readThumbnail(\n { ...base(request.secrets), sandboxId: request.sandboxId },\n json(request.state),\n ),\n );\n if (!result.success)\n throw sandboxProviderWireError({\n code: SandboxProviderErrorCode.Unavailable,\n message: `the provider returned an invalid retained thumbnail: ${z.prettifyError(result.error)}`,\n retryable: false,\n });\n return result.data;\n }\n case SandboxProviderWirePath.ReadSnapshot: {\n const request = parse(sandboxReadSnapshotRequestSchema, body);\n requireSandbox(identity, request.sandboxId);\n const implementation = implementationOf(mount, request.environment);\n if (implementation.readSnapshot == null) throw unsupported('snapshot reads');\n const response = await implementation.readSnapshot(\n { ...base(request.secrets), sandboxId: request.sandboxId },\n json(request.state),\n parse(sandboxSnapshotRequestSchema, request.request),\n );\n return response == null ? null : { ...response };\n }\n case SandboxProviderWirePath.Processes: {\n const request = parse(sandboxProcessesRequestSchema, body);\n requireSandbox(identity, request.sandboxId);\n const implementation = implementationOf(mount, request.environment);\n if (implementation.processes == null) throw unsupported('process inspection');\n return {\n ...(await implementation.processes(\n { ...base(request.secrets), sandboxId: request.sandboxId },\n json(request.state),\n request.request,\n )),\n };\n }\n case SandboxProviderWirePath.Editor: {\n const request = parse(sandboxEditorRequestSchema, body);\n requireSandbox(identity, request.sandboxId);\n const implementation = implementationOf(mount, request.environment);\n if (implementation.editor == null) throw unsupported('editor');\n return {\n ...(await implementation.editor(\n { ...base(request.secrets), sandboxId: request.sandboxId },\n json(request.state),\n parse(editorRequestSchema, request.request),\n )),\n };\n }\n default:\n throw unsupported(`call ${path}`);\n }\n };\n\n const fetchHandler = async (request: Request): Promise<Response> => {\n const url = new URL(request.url);\n const routed = route(url);\n if (routed == null)\n return errorResponse({\n code: SandboxProviderErrorCode.NotFound,\n message: 'no sandbox provider is served here',\n retryable: false,\n });\n const { mount, path } = routed;\n if (request.method === 'GET' && path === SANDBOX_PROVIDER_DISCOVERY_PATH)\n return Response.json(discoveryOf(mount));\n if (request.method !== 'POST' || path === SandboxProviderWirePath.Attach)\n return errorResponse(invalid(`${request.method} ${path} is not a provider call`), 405);\n const token = /^Bearer\\s+(.+)$/iu.exec(request.headers.get('authorization')?.trim() ?? '')?.[1];\n const identity = await verify(mount, token ?? null);\n if (identity == null || token == null)\n return errorResponse(refused('a valid sandbox-provider assertion is required'), 401);\n const caller: CallerIface = { token, identity };\n let body: unknown;\n try {\n body = await readBody(request);\n } catch (cause) {\n return errorResponse(wireErrorOf(cause));\n }\n if (LONG_CALLS.has(path))\n return ndjsonResponse({ work: () => dispatch(mount, path, caller, body), heartbeatMs });\n try {\n return Response.json(await dispatch(mount, path, caller, body));\n } catch (cause) {\n return errorResponse(wireErrorOf(cause));\n }\n };\n\n const upgrade = (request: Request, socket: WebSocketLikeIface): void => {\n const { channel } = frameChannelFromWebSocket(socket);\n const preamble = preambleChannel(channel);\n const fail = (error: SandboxProviderErrorIface, code: number = HandleRpcCloseCode.Normal) => {\n channel.send(JSON.stringify({ type: 'error', error }));\n channel.close(code, error.message.slice(0, 120));\n };\n void (async () => {\n const routed = route(new URL(request.url));\n if (routed == null || routed.path !== SandboxProviderWirePath.Attach) {\n fail({\n code: SandboxProviderErrorCode.NotFound,\n message: 'no sandbox provider attaches here',\n retryable: false,\n });\n return;\n }\n const { mount } = routed;\n const token = handleRpcTokenFromRequest(request);\n const identity = await verify(mount, token);\n if (identity == null || token == null) {\n fail(\n refused('a valid sandbox-provider assertion is required'),\n HandleRpcCloseCode.Unauthorized,\n );\n return;\n }\n let caller: CallerIface = { token, identity };\n let frame: SandboxAttachFrameIface;\n try {\n const first = await preamble.next();\n if (typeof first !== 'string') throw new Error('the attach request must be a text frame');\n frame = parse(sandboxAttachFrameSchema, JSON.parse(first));\n requireSandbox(identity, frame.sandboxId);\n } catch (cause) {\n fail(wireErrorOf(cause));\n return;\n }\n const heartbeat = setInterval(\n () => channel.send(JSON.stringify({ type: 'heartbeat' })),\n heartbeatMs,\n );\n let reported: NetworkPolicyIface | null = null;\n const ctx: SandboxResourceContextIface = {\n ...contextFor(() => caller, frame.secrets),\n sandboxId: frame.sandboxId,\n storagePath: storagePathOf(identity, frame.sandboxId),\n lifecycle: frame.lifecycle,\n platformEgressHosts: frame.platformEgressHosts,\n platformNetworkPolicy: async (policy) => {\n reported = policy;\n },\n };\n let handle: SandboxProviderHandleIface<NetworkSandboxSessionIface>;\n let attached: SandboxAttachedFrameIface;\n try {\n const implementation = implementationOf(mount, frame.environment);\n if (frame.passive) {\n if (implementation.attachPassive == null) throw unsupported('passive attach');\n handle = await implementation.attachPassive(ctx, {\n artifact: json(frame.artifact),\n state: json(frame.state),\n });\n attached = {\n type: 'attached',\n state: json(frame.state),\n fresh: false,\n booted: false,\n region: null,\n networkPolicy: null,\n };\n } else {\n const attachment = await implementation.attach(ctx, {\n artifact: json(frame.artifact),\n state: json(frame.state),\n });\n handle = attachment.handle;\n attached = {\n type: 'attached',\n state: attachment.state,\n fresh: attachment.fresh,\n booted: attachment.booted,\n region: attachment.region ?? null,\n networkPolicy: reported,\n };\n }\n } catch (cause) {\n clearInterval(heartbeat);\n fail(wireErrorOf(cause));\n return;\n }\n clearInterval(heartbeat);\n // The handle is released once, by the platform or when the socket goes.\n let shutdown: Promise<void> | null = null;\n const lifecycle: HandleLifecycle = {\n onSandboxStop: () => handle.onSandboxStop(),\n onSandboxDelete: (options) => handle.onSandboxDelete(options),\n onRuntimeShutdown: () => {\n shutdown ??= handle.onRuntimeShutdown();\n return shutdown;\n },\n };\n // `initialize { identity }` and `identity/refresh`: an assertion for the\n // same provider and sandbox, which becomes the caller's.\n const authorize: HandleAuthorizeFn = async ({ identity: assertion }) => {\n const next = await verify(mount, assertion ?? null);\n if (\n next == null ||\n assertion == null ||\n next.providerId !== identity.providerId ||\n next.sandboxId !== identity.sandboxId ||\n next.organizationId !== identity.organizationId ||\n next.projectId !== identity.projectId\n )\n return null;\n caller = { token: assertion, identity: next };\n return { expiresAt: new Date(next.expiresAt).toISOString() };\n };\n channel.send(JSON.stringify(attached));\n serveSandboxHandle({\n sandbox: handle.sandbox,\n handle: lifecycle,\n authorize,\n access: { grant: FULL_SANDBOX_GRANT, lifecycle: true },\n mcpChannels: true,\n }).attach(preamble.rest());\n await preamble.closed;\n await lifecycle.onRuntimeShutdown().catch((cause: unknown) =>\n args.log?.('sandbox provider handle shutdown failed', {\n provider: mount.name,\n sandboxId: frame.sandboxId,\n error: cause instanceof Error ? cause.message : String(cause),\n }),\n );\n })();\n };\n\n return { fetch: fetchHandler, upgrade };\n};\n"],
|
|
5
|
+
"mappings": "AACA,SAAS,8CAA8C;AACvD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAIK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAOK;AACP,YAAY,OAAO;AACnB,SAAS,uBAAwD;AACjE,SAAS,8BAA8B,2BAA2B;AAClE,SAAS,0BAA0B;AACnC,SAAS,0BAAwE;AACjF,SAAS,oCAAoC;AAC7C;AAAA,EACE;AAAA,OAaK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,+BAA+B,0BAA0B,mBAAmB;AACrF,SAAS,oBAAoB;AAC7B,SAAS,sBAAsB;AAC/B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,uBAAuB;AA6DhC,MAAM,OAAO,CAAC,UAA8B,gBAAgB,MAAM,KAAK;AAGvE,MAAM,2BAA2B;AAEjC,MAAM,gBAAgB,CAAC,OAAkC,WACvD,SAAS,KAAK,EAAE,MA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S,aAC5B,KAAK,mBAAmB,SAAS,kBACjC,KAAK,cAAc,SAAS;AAE5B,iBAAO;AACT,iBAAS,EAAE,OAAO,WAAW,UAAU,KAAK;AAC5C,eAAO,EAAE,WAAW,IAAI,KAAK,KAAK,SAAS,EAAE,YAAY,EAAE;AAAA,MAC7D;AACA,cAAQ,KAAK,KAAK,UAAU,QAAQ,CAAC;AACrC,yBAAmB;AAAA,QACjB,SAAS,OAAO;AAAA,QAChB,QAAQ;AAAA,QACR;AAAA,QACA,QAAQ,EAAE,OAAO,oBAAoB,WAAW,KAAK;AAAA,QACrD,aAAa;AAAA,MACf,CAAC,EAAE,OAAO,SAAS,KAAK,CAAC;AACzB,YAAM,SAAS;AACf,YAAM,UAAU,kBAAkB,EAAE;AAAA,QAAM,CAAC,UACzC,KAAK,MAAM,2CAA2C;AAAA,UACpD,UAAU,MAAM;AAAA,UAChB,WAAW,MAAM;AAAA,UACjB,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAAA,QAC9D,CAAC;AAAA,MACH;AAAA,IACF,GAAG;AAAA,EACL;AAEA,SAAO,EAAE,OAAO,cAAc,QAAQ;AACxC;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { SandboxThumbnailIface } from '@finalai/agent-protocol/sandbox-provider-wire';
|
|
1
2
|
import { Capability, RuntimeKind, type CapabilityAccess } from '@finalai/agent-protocol';
|
|
2
3
|
import * as z from 'zod';
|
|
3
4
|
import { SandboxEntryType } from "./file-kind.mjs";
|
|
@@ -11,6 +12,7 @@ import type { ToolDescriptorIface } from "../tool-descriptor.mjs";
|
|
|
11
12
|
import { type SandboxEditorRequestIface, type SandboxEditorResultIface } from "./editor.mjs";
|
|
12
13
|
import type { SandboxSetupIface } from "./setup/schema.mjs";
|
|
13
14
|
import type { SandboxSnapshotRequestIface, SandboxSnapshotResponseIface } from "./snapshots.mjs";
|
|
15
|
+
export { SandboxThumbnailContentType, sandboxThumbnailSchema, type SandboxThumbnailIface, } from '@finalai/agent-protocol/sandbox-provider-wire';
|
|
14
16
|
export interface AbortableIface {
|
|
15
17
|
abortSignal?: AbortSignal;
|
|
16
18
|
}
|
|
@@ -325,6 +327,9 @@ export interface SandboxEnvironmentImplementationIface<Artifact extends JsonValu
|
|
|
325
327
|
features?(ctx: SandboxOfferContextIface): Promise<SandboxCapability[] | null>;
|
|
326
328
|
additionalFeatures?(ctx: SandboxOfferContextIface): Promise<SandboxCapability[]>;
|
|
327
329
|
mcpCatalog?(ctx: SandboxOfferContextIface): Promise<SandboxMcpCatalogIface | null>;
|
|
330
|
+
readThumbnail?(ctx: SandboxOfferContextIface & {
|
|
331
|
+
sandboxId: string;
|
|
332
|
+
}, state: State): Promise<SandboxThumbnailIface | null>;
|
|
328
333
|
readSnapshot?(ctx: SandboxOfferContextIface, state: State, request: SandboxSnapshotRequestIface): Promise<SandboxSnapshotResponseIface | null>;
|
|
329
334
|
processes?(ctx: SandboxOfferContextIface & {
|
|
330
335
|
sandboxId: string;
|
|
@@ -10,6 +10,10 @@ import {
|
|
|
10
10
|
SandboxEditorOperation
|
|
11
11
|
} from "./editor.mjs";
|
|
12
12
|
import { SandboxExecutionOperation } from "./execution-guard.mjs";
|
|
13
|
+
import {
|
|
14
|
+
SandboxThumbnailContentType,
|
|
15
|
+
sandboxThumbnailSchema
|
|
16
|
+
} from "@finalai/agent-protocol/sandbox-provider-wire";
|
|
13
17
|
var SandboxWorkerEndpointTransport = /* @__PURE__ */ ((SandboxWorkerEndpointTransport2) => {
|
|
14
18
|
SandboxWorkerEndpointTransport2["Ws"] = "ws";
|
|
15
19
|
SandboxWorkerEndpointTransport2["Http"] = "http";
|
|
@@ -139,6 +143,7 @@ export {
|
|
|
139
143
|
SandboxCapability,
|
|
140
144
|
SandboxEntryType2 as SandboxEntryType,
|
|
141
145
|
SandboxEventKind,
|
|
146
|
+
SandboxThumbnailContentType,
|
|
142
147
|
SandboxWorkerEndpointTransport,
|
|
143
148
|
defineSandboxProvider,
|
|
144
149
|
isMcpChannelEndpoint,
|
|
@@ -150,6 +155,7 @@ export {
|
|
|
150
155
|
reportPlatformNetworkPolicy,
|
|
151
156
|
sandboxCredentialRefSchema,
|
|
152
157
|
sandboxRuntimesOf,
|
|
158
|
+
sandboxThumbnailSchema,
|
|
153
159
|
withPlatformEgressHosts,
|
|
154
160
|
writePlatformFiles
|
|
155
161
|
};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../src/sandbox/types.ts"],
|
|
4
|
-
"sourcesContent": ["import { Capability, RuntimeKind, type CapabilityAccess } from '@finalai/agent-protocol';\nimport * as z from 'zod';\nimport { SandboxEntryType } from \"./file-kind.mjs\";\nexport { SandboxEntryType } from \"./file-kind.mjs\";\nimport { createSandboxHandle, type SandboxExecutionPolicyIface } from \"./handle.mjs\";\nimport { withSandboxOverrides } from \"./overrides.mjs\";\nimport { NetworkPolicy, type NetworkPolicyIface } from '@finalai/agent-protocol/network-policy';\nexport { NetworkPolicy, type NetworkPolicyIface } from '@finalai/agent-protocol/network-policy';\nimport type {\n ProcessInspectionRequestIface,\n ProcessInspectionResultIface,\n} from '@finalai/agent-protocol/process-inspection';\nimport type { JsonValue } from \"../json.mjs\";\nimport type { ToolDescriptorIface } from \"../tool-descriptor.mjs\";\nimport {\n SandboxEditorOperation,\n type SandboxEditorRequestIface,\n type SandboxEditorResultIface,\n} from \"./editor.mjs\";\nimport { SandboxExecutionOperation } from \"./execution-guard.mjs\";\nimport type { SandboxSetupIface } from \"./setup/schema.mjs\";\nimport type { SandboxSnapshotRequestIface, SandboxSnapshotResponseIface } from \"./snapshots.mjs\";\n\n// Sandbox providers and consumers share the streaming session contract.\n\nexport interface AbortableIface {\n abortSignal?: AbortSignal;\n}\n\nexport interface SandboxProcessOptionsIface extends AbortableIface {\n command: string;\n args?: string[];\n cwd?: string;\n env?: Record<string, string>;\n // Run through the sandbox's login shell (`bash -lc`) instead of exec'ing.\n shell?: boolean;\n stdin?: ReadableStream<Uint8Array> | string;\n timeoutMs?: number;\n // Spawn only (`run` ignores it): ask for a durable process on a sandbox with\n // SandboxCapability.DurableProcesses; ignored elsewhere (the handle's `ref`\n // is then null). A durable process ends only on its own exit, `kill`,\n // `timeoutMs` (enforced inside the sandbox, not by a provider-side timer) or\n // sandbox stop/destroy. Dropping its handle (connection close, runtime\n // shutdown, `abortSignal`) detaches without killing: the handle's streams\n // fail and `wait` rejects, and `attachProcess` finds the process again.\n durable?: boolean;\n}\n\nexport interface SandboxProcessIface {\n readonly pid: string | null;\n // Opaque, provider-encoded (versioned) reference for `attachProcess`; non-null\n // only for a durable process on a sandbox with durable processes. Optional so\n // implementations without them need not set it.\n readonly ref?: string | null;\n readonly stdout: ReadableStream<Uint8Array>;\n readonly stderr: ReadableStream<Uint8Array>;\n // Writes to the process's stdin; closes stdin when `end` is true.\n write(data: Uint8Array | string, options?: { end?: boolean }): Promise<void>;\n wait(): Promise<{ exitCode: number }>;\n kill(signal?: string): Promise<void>;\n}\n\n// A program built for the sandbox's worker runtime, started for one harness\n// session. Its handle is a process's: what is written to it is its input\n// stream, stdout its output stream, stderr its diagnostics.\nexport interface SandboxWorkerOptionsIface extends AbortableIface {\n program: string;\n env?: Record<string, string>;\n // Handed to the program when it starts.\n input?: JsonValue;\n // As for spawn: survives the handle on a sandbox with durable processes.\n durable?: boolean;\n // A platform-identity assertion for the program's run (variant `harness-run`),\n // for a runtime that authenticates the programs it starts.\n identity?: string;\n}\n\nexport enum SandboxWorkerEndpointTransport {\n Ws = 'ws',\n Http = 'http',\n Relay = 'relay',\n}\n\n// Where a started worker program serves its stream itself, for the caller to\n// dial directly: an ACP endpoint by URL, or a relay channel.\nexport type SandboxWorkerEndpointType =\n | {\n transport: SandboxWorkerEndpointTransport.Ws | SandboxWorkerEndpointTransport.Http;\n url: string;\n headers: Record<string, string>;\n }\n | { transport: SandboxWorkerEndpointTransport.Relay; channel: string; token: string };\n\nexport interface SandboxWorkerEndpointIface {\n readonly endpoint: SandboxWorkerEndpointType;\n}\n\n// A started worker program: a process whose streams carry its stream, or an\n// endpoint it serves.\nexport type SandboxWorkerStartType = SandboxProcessIface | SandboxWorkerEndpointIface;\n\nexport const isSandboxWorkerEndpoint = (\n started: SandboxWorkerStartType,\n): started is SandboxWorkerEndpointIface => 'endpoint' in started;\n\nexport interface SandboxAttachProcessOptionsIface extends AbortableIface {\n ref: string;\n // Bytes of each stream the caller already has; output resumes there.\n stdoutOffset: number;\n stderrOffset: number;\n}\n\n// A durable process found again by its ref. Its output is read from the\n// provider, which is the source of truth for output and exit; aborting\n// `abortSignal` detaches this handle as it does a spawned durable one.\n//\n// Limitation: stdin belongs to the spawning handle only. A re-attached\n// process can be watched, waited for and killed, but not written to; a process\n// that needs input after a re-attach must read it from somewhere else (a file).\nexport interface SandboxAttachedProcessIface {\n readonly ref: string;\n // Where the streams actually start: the requested offsets, or later when the\n // provider no longer retains the earlier bytes (see each provider's retention).\n readonly stdoutOffset: number;\n readonly stderrOffset: number;\n readonly stdout: ReadableStream<Uint8Array>;\n readonly stderr: ReadableStream<Uint8Array>;\n wait(): Promise<{ exitCode: number }>;\n kill(signal?: string): Promise<void>;\n}\n\nexport interface SandboxRunResultIface {\n exitCode: number;\n stdout: string;\n stderr: string;\n}\n\nexport interface StatIface {\n path: string;\n type: SandboxEntryType;\n size: number;\n modifiedAt: string | null;\n mode: number | null;\n}\n\nexport interface DirEntryIface {\n name: string;\n path: string;\n type: SandboxEntryType;\n size: number | null;\n}\n\nexport interface ConfinedSandboxFilesIface {\n readFile(\n options: { path: string; root: string } & AbortableIface,\n ): Promise<ReadableStream<Uint8Array> | null>;\n stat(options: { path: string; root: string } & AbortableIface): Promise<StatIface | null>;\n readDir(\n options: { path: string; root: string } & AbortableIface,\n ): Promise<DirEntryIface[] | null>;\n}\n\nexport interface SandboxSessionIface {\n readonly description: string;\n readonly confinedFileReader?: ConfinedSandboxFilesIface;\n // On the RPC surface, root confines viewer reads to this directory, rejects\n // symlink ancestors and requires Python 3 in the sandbox (confinedFiles feature).\n readFile(\n options: { path: string; root?: string } & AbortableIface,\n ): Promise<ReadableStream<Uint8Array> | null>;\n readBinaryFile(options: { path: string } & AbortableIface): Promise<Uint8Array | null>;\n readTextFile(\n options: {\n path: string;\n encoding?: string;\n startLine?: number;\n endLine?: number;\n } & AbortableIface,\n ): Promise<string | null>;\n writeFile(\n options: { path: string; content: ReadableStream<Uint8Array> } & AbortableIface,\n ): Promise<void>;\n writeBinaryFile(options: { path: string; content: Uint8Array } & AbortableIface): Promise<void>;\n // Writes create missing parent directories.\n writeTextFile(\n options: { path: string; content: string; encoding?: string } & AbortableIface,\n ): Promise<void>;\n spawn(options: SandboxProcessOptionsIface): Promise<SandboxProcessIface>;\n // Present on sandboxes with durable processes. Null when the process is\n // unknown: the sandbox restarted or was deleted, or the ref expired, is\n // malformed or belongs to another sandbox. Attaching after the process\n // exited still yields its retained output and exit code.\n attachProcess?(\n options: SandboxAttachProcessOptionsIface,\n ): Promise<SandboxAttachedProcessIface | null>;\n run(options: SandboxProcessOptionsIface): Promise<SandboxRunResultIface>;\n stat(options: { path: string; root?: string } & AbortableIface): Promise<StatIface | null>;\n readDir(options: { path: string; root?: string } & AbortableIface): Promise<DirEntryIface[]>;\n resolvePath(path: string): string;\n removePath(\n options: { path: string; recursive?: boolean; force?: boolean } & AbortableIface,\n ): Promise<void>;\n}\n\nexport enum PortProtocol {\n Http = 'http',\n Https = 'https',\n Ws = 'ws',\n}\n\n// An MCP transport the sandbox serves for an optional capability: an HTTP MCP\n// endpoint the harness (or the host) can dial.\nexport interface McpEndpointIface {\n name: string;\n url: string;\n headers: Record<string, string>;\n}\n\n// A JSON-RPC message channel to an MCP server the sandbox hosts, for backends\n// whose API reaches it some other way than HTTP MCP (a byte pipe, a socket).\n// Messages are JSON-RPC objects, in order.\nexport interface McpChannelIface {\n send(message: JsonValue, options?: AbortableIface): Promise<void>;\n // The messages that arrived since the last call; [] when none did.\n receive(options?: AbortableIface): Promise<JsonValue[]>;\n close(): Promise<void>;\n}\n\n// An MCP server the sandbox hosts, opened in process by whoever runs the handle.\n// It cannot cross the handle RPC wire.\nexport interface McpChannelEndpointIface {\n name: string;\n connect(options?: AbortableIface): Promise<McpChannelIface>;\n}\n\nexport type SandboxMcpEndpoint = McpEndpointIface | McpChannelEndpointIface;\n\n// The tools of a sandbox's hosted MCP servers, as far as they are known without\n// starting it. Null: unknown until the sandbox is attached and asked.\nexport interface SandboxMcpCatalogIface {\n computerUse: ToolDescriptorIface[] | null;\n // Local MCP server name \u2192 its tools.\n localMcp: Record<string, ToolDescriptorIface[]> | null;\n // Partial discovery retains known tools and must be retried, including after caching.\n localMcpIncomplete?: boolean;\n}\n\nexport const isMcpChannelEndpoint = (\n endpoint: SandboxMcpEndpoint,\n): endpoint is McpChannelEndpointIface => 'connect' in endpoint;\n\nexport interface ScreenOptionsIface {\n // View-only by default; explicit input control requires execute access.\n viewOnly?: boolean;\n}\n\nexport interface ScreenSessionIface {\n // A short-lived viewer grant; providers enforce the requested input access.\n url: string;\n token: string;\n expiresAt: string;\n}\n\nexport interface NetworkSandboxSessionIface extends SandboxSessionIface {\n readonly id: string;\n readonly defaultWorkingDirectory: string;\n readonly ports: readonly number[];\n getPortEndpoint(options: {\n port: number;\n protocol?: PortProtocol;\n }): Promise<{ url: string; headers?: Record<string, string> }>;\n getPortUrl(options: { port: number; protocol?: PortProtocol }): Promise<string>;\n stop(): Promise<void>;\n destroy(): Promise<void>;\n setNetworkPolicy?(policy: NetworkPolicyIface): Promise<void>;\n computerUse?(): Promise<SandboxMcpEndpoint>;\n // Present on sandboxes whose provider offers RuntimeKind.Worker.\n startWorker?(options: SandboxWorkerOptionsIface): Promise<SandboxWorkerStartType>;\n screen?(options?: ScreenOptionsIface): Promise<ScreenSessionIface>;\n localMcp?(): Promise<SandboxMcpEndpoint[]>;\n}\n\n// Features a live sandbox handle advertises over the handle RPC (`describe`).\n// Finer than the model's capabilities (`Capability`): `files` is served by the\n// file methods, `shell` by processes and ports, `computerUse` by computer use\n// and the screen; the rest are handle extensions a capability may use.\nexport enum SandboxCapability {\n Files = 'files',\n Process = 'process',\n Ports = 'ports',\n NetworkPolicy = 'networkPolicy',\n ComputerUse = 'computerUse',\n Screen = 'screen',\n LocalMcp = 'localMcp',\n Browser = 'browser',\n // `spawn({ durable: true })` and `attachProcess` (see SandboxProcessOptionsIface.durable).\n DurableProcesses = 'durableProcesses',\n // `startWorker`: the sandbox runs worker programs.\n Workers = 'workers',\n}\n\n// The capabilities a provider's sandboxes serve, each with the most access a\n// session can be granted on it. A capability left out is not served.\nexport type SandboxCapabilityOffer = Partial<Record<Capability, CapabilityAccess>>;\n\nexport interface SandboxProviderHandleIface<S extends SandboxSessionIface> {\n readonly sandbox: S;\n // Pending policy; the generic handle constructor consumes it before exposing execution.\n readonly executionPolicy?: SandboxExecutionPolicyIface;\n onSandboxStop(): Promise<void>;\n onSandboxDelete(options?: { reason?: string }): Promise<void>;\n onRuntimeShutdown(): Promise<void>;\n}\n\n// The person a sandbox acts for on this call: the author of the running turn,\n// else whoever opened the sandbox's viewer. Null when it acts for no person\n// (an unprompted turn, a preparation). Read on each call: it changes between\n// turns and between callers.\nexport interface SandboxActingUserIface {\n current(): Promise<string | null>;\n}\n\nexport const noSandboxActingUser: SandboxActingUserIface = { current: async () => null };\n\n// Credentials the host supplies to a provider. A provider reads no secrets of\n// its own and names no project: it gets the value of the secret its\n// environment's `credential.secretRef` names, resolved in the sandbox's project.\nexport interface SandboxCredentialsIface {\n secret(args: { secretRef: string }): Promise<string | null>;\n}\n\nexport const noSandboxCredentials: SandboxCredentialsIface = { secret: async () => null };\n\n// A provider's credential by reference, in its environment options: the name\n// of a project secret, never its value.\nexport const sandboxCredentialRefSchema = z.strictObject({\n secretRef: z.string().min(1).max(256),\n});\n\nexport type SandboxCredentialRefIface = z.infer<typeof sandboxCredentialRefSchema>;\n\n// A platform-identity assertion (`@finalai/agent-protocol/identity`) for one\n// backend audience, valid until `expiresAt`.\nexport interface SandboxIdentityTokenIface {\n token: string;\n expiresAt: string;\n}\n\n// How a provider authenticates to a backend it needs (its vendor's API): an\n// assertion for `audience`, which the platform issues only for audiences the\n// provider's registration was granted. It names the sandbox's organization,\n// project and sandbox, and the acting user at the time it was issued. Ask\n// before each backend call (hosts cache it); `refresh` asks for a new one\n// after the backend rejected the last.\nexport type SandboxIdentityFn = (args: {\n audience: string;\n refresh?: boolean;\n}) => Promise<SandboxIdentityTokenIface>;\n\nexport const noSandboxIdentity: SandboxIdentityFn = async ({ audience }) => {\n throw new Error(`no identity was granted for ${audience}`);\n};\n\n// What every provider call is given: the project the sandbox belongs to, the\n// host's credentials and the provider's identity for the backends it was\n// granted.\nexport interface SandboxProviderContextIface {\n organizationId: string;\n projectId: string;\n credentials: SandboxCredentialsIface;\n actingUser: SandboxActingUserIface;\n identity: SandboxIdentityFn;\n log?: (message: string, fields?: Record<string, string | number | boolean | null>) => void;\n}\n\n// How the platform runs a sandbox's lifecycle, for the provider to align its\n// backend with: after `parkAfterIdleMs` of idleness the platform parks the\n// sandbox (null: the provider's own default), so a backend idle timeout\n// should be longer.\nexport interface SandboxLifecycleIface {\n parkAfterIdleMs: number | null;\n}\n\n// What reads that start nothing are given (capabilities, catalogs, snapshots,\n// process inspection, the editor). `sandboxId` is set for reads about an\n// existing sandbox.\nexport interface SandboxOfferContextIface extends SandboxProviderContextIface {\n sandboxId?: string;\n executionPolicy?: SandboxExecutionPolicyIface;\n platformNetworkPolicy?: (policy: NetworkPolicyIface) => Promise<void>;\n // Retain platform transport access when an extension restores an allowlist.\n platformEgressHosts?: string[];\n}\n\n// Scoped by the host to this project and provider. Providers can retain\n// reusable intermediate artifacts independently of a sandbox's seed files.\nexport interface SandboxArtifactsIface {\n get(key: string): Promise<JsonValue | null>;\n put(key: string, artifact: JsonValue): Promise<void>;\n}\n\nexport interface SandboxPreparationSourceIface {\n sourceRevision: string;\n read(): Promise<{ files: Record<string, string>; resources: Record<string, JsonValue> }>;\n}\n\n// A preparation builds what an environment's sandboxes start from (an image\n// built into a base, a snapshot). It depends on the environment's options and\n// the seed files only, never on a sandbox setup.\nexport interface SandboxPrepareContextIface extends SandboxProviderContextIface {\n // A host-persisted resource source; artifacts may retain its identity instead of seed contents.\n preparation?: SandboxPreparationSourceIface;\n artifacts?: SandboxArtifactsIface;\n // Workspace-relative seed files and named resources.\n files: Record<string, string>;\n resources: Record<string, JsonValue>;\n sourceRevision: string;\n storagePath: string;\n}\n\n// What a provider is given for one sandbox: its create, attach, detach, park\n// and delete calls.\nexport interface SandboxResourceContextIface extends SandboxProviderContextIface {\n // The platform's id for the sandbox, stable for its whole life.\n sandboxId: string;\n lifecycle: SandboxLifecycleIface;\n // Host policy composes before the provider's policy, on every exposed execution path.\n executionPolicy?: SandboxExecutionPolicyIface;\n preparation?: SandboxPreparationSourceIface;\n storagePath: string;\n // Variables the platform sets in every process of this sandbox: the egress\n // proxy, trust for its CA, one placeholder per bound secret and the sandbox\n // setup's variables. Evaluated again for every spawn/run, never once per\n // attach: a secret bound later must reach the next command. May resolve to\n // {}. Platform values override the environment's own.\n platformEnvironment?: () => Promise<Record<string, string>>;\n // Hosts the sandbox must be able to reach for the proxy to work, appended\n // to any allowlist network policy.\n platformEgressHosts?: string[];\n // Reports the network policy now in force, exactly as the provider applied\n // it to its backend (after withPlatformEgressHosts); the platform permits\n // only those destinations. Called on every attach after awaitRunning and\n // before platformFiles or any command; never for a session's own\n // setNetworkPolicy. A rejection fails the attach.\n platformNetworkPolicy: (policy: NetworkPolicyIface) => Promise<void>;\n // Files the platform needs before any command runs: written right after the\n // sandbox is running, on every attach. Paths are absolute; missing parent\n // directories are created.\n platformFiles?: () => Promise<Record<string, string>>;\n}\n\n// The variables `platformEnvironment` owns. An environment that sets one is\n// refused at create.\nexport const PLATFORM_ENVIRONMENT_NAMES: ReadonlySet<string> = new Set([\n 'HTTPS_PROXY',\n 'HTTP_PROXY',\n 'NO_PROXY',\n 'NODE_USE_ENV_PROXY',\n 'SSL_CERT_FILE',\n 'CURL_CA_BUNDLE',\n 'REQUESTS_CA_BUNDLE',\n 'GIT_SSL_CAINFO',\n 'CARGO_HTTP_CAINFO',\n 'DENO_CERT',\n 'NODE_EXTRA_CA_CERTS',\n 'FINAL_EGRESS_URL',\n 'FINAL_EGRESS_TOKEN',\n]);\n\n// A process's base environment: the environment's variables under the\n// platform's, read again on every call.\nexport const platformProcessEnvironment =\n (\n ctx: Pick<SandboxResourceContextIface, 'platformEnvironment'>,\n specEnv: Record<string, string>,\n ): (() => Promise<Record<string, string>>) =>\n async () => ({ ...specEnv, ...(await ctx.platformEnvironment?.()) });\n\n// Writes `platformFiles` into a sandbox that is now running, before it runs anything.\n// Relies on writeTextFile creating missing parent directories.\nexport const writePlatformFiles = async (\n ctx: Pick<SandboxResourceContextIface, 'platformFiles'>,\n sandbox: Pick<SandboxSessionIface, 'writeTextFile'>,\n): Promise<void> => {\n for (const [path, content] of Object.entries((await ctx.platformFiles?.()) ?? {}))\n await sandbox.writeTextFile({ path, content });\n};\n\n// Reports the policy a provider just applied to its backend: `allow` only for an\n// allowlist, its entries (hosts, `*.suffix` patterns, CIDRs) unchanged.\nexport const reportPlatformNetworkPolicy = async (\n ctx: Pick<SandboxResourceContextIface, 'platformNetworkPolicy'>,\n policy: NetworkPolicyIface,\n): Promise<void> =>\n ctx.platformNetworkPolicy(\n policy.mode === NetworkPolicy.Allowlist\n ? { mode: policy.mode, allow: [...(policy.allow ?? [])] }\n : { mode: policy.mode },\n );\n\n// An allowlist policy with the platform's egress hosts appended; any other\n// policy unchanged.\nexport const withPlatformEgressHosts = (\n ctx: Pick<SandboxResourceContextIface, 'platformEgressHosts'>,\n policy: NetworkPolicyIface,\n): NetworkPolicyIface => {\n const hosts = ctx.platformEgressHosts ?? [];\n if (policy.mode !== NetworkPolicy.Allowlist || hosts.length === 0) return policy;\n return { ...policy, allow: [...new Set([...(policy.allow ?? []), ...hosts])] };\n};\n\n// One attach of a sandbox: the live handle, and what the attach lost, so the\n// platform knows which phases of the sandbox setup to redo.\nexport interface SandboxAttachmentIface<\n State extends JsonValue,\n S extends NetworkSandboxSessionIface,\n> {\n handle: SandboxProviderHandleIface<S>;\n // The state to keep for the next call (a resumed backend may change ids).\n state: State;\n // The disk is new: nothing written by a setup, the workspace seeds or a\n // session survives on it (first attach, or a backend that lost it).\n fresh: boolean;\n // The machine started on this attach: no process from before is running.\n booted: boolean;\n // Where the backend runs the sandbox (its own region name), so the host can\n // place the harness near it; null when unknown.\n region?: string | null;\n}\n\n// One environment of a provider, as the host drives it. A sandbox is a\n// resource the platform owns: `create` makes it (nothing need boot), `attach`\n// makes it reachable for a while, `detach` lets it go idle, `park` makes it as\n// cheap as the provider can while keeping its disk, `delete` destroys it.\n//\n// Order on attach: attach (boot or resume) \u2192 awaitRunning \u2192\n// platformNetworkPolicy \u2192 platformFiles \u2192 handle; the platform then applies\n// the sandbox setup through the handle (./setup). A provider never runs a\n// setup's steps itself.\nexport interface SandboxEnvironmentImplementationIface<\n Artifact extends JsonValue,\n State extends JsonValue,\n S extends NetworkSandboxSessionIface,\n> {\n // The capabilities this environment's sandboxes serve and the most access\n // each grants, known without creating one.\n capabilities(ctx: SandboxOfferContextIface): Promise<SandboxCapabilityOffer>;\n // What a harness can run in this environment's sandboxes: processes, worker\n // programs (`startWorker`), or both. Absent: processes when it offers `shell`.\n runtimes?(ctx: SandboxOfferContextIface): Promise<RuntimeKind[]>;\n // Handle features this environment's sandboxes advertise, read before\n // anything starts. Absent or null: unknown until attached; local MCP is then\n // not projected.\n features?(ctx: SandboxOfferContextIface): Promise<SandboxCapability[] | null>;\n // Known positive features when the rest of the pre-attach set is unknown.\n additionalFeatures?(ctx: SandboxOfferContextIface): Promise<SandboxCapability[]>;\n // The hosted MCP servers' tool catalogs the backend can give without\n // attaching, so the MCP projection lists them from the first `tools/list`.\n // A catalog left unknown can only be learned from a live sandbox, so the\n // first `tools/list` that finds it unknown attaches in the background.\n mcpCatalog?(ctx: SandboxOfferContextIface): Promise<SandboxMcpCatalogIface | null>;\n // Reads committed files without attaching. Null means the backend is live\n // or offers no snapshot. An unavailable sleeping snapshot must throw, never\n // fall through to a read that wakes it. Pin later ranges by snapshotId.\n readSnapshot?(\n ctx: SandboxOfferContextIface,\n state: State,\n request: SandboxSnapshotRequestIface,\n ): Promise<SandboxSnapshotResponseIface | null>;\n // Inspect retained backend processes without attaching or extending a sandbox.\n // Stopping one requires shell access; the provider also enforces backend ownership.\n processes?(\n ctx: SandboxOfferContextIface & { sandboxId: string },\n state: State,\n request: ProcessInspectionRequestIface,\n ): Promise<ProcessInspectionResultIface>;\n // Browser editor for an existing sandbox. The host checks write\n // authorization; this hook never creates or wakes a backend. Credentials stay\n // in the authentication form, never the editor URL or stored provider state.\n editor?(\n ctx: SandboxOfferContextIface,\n state: State,\n request: SandboxEditorRequestIface,\n ): Promise<SandboxEditorResultIface>;\n // Content-addressed by `artifactKey`; the host caches artifacts and calls\n // prepare only on a miss.\n artifactKey(ctx: SandboxPrepareContextIface): Promise<string>;\n prepare(ctx: SandboxPrepareContextIface): Promise<Artifact>;\n // Makes the sandbox's backend resource. The setup is given so the\n // provider enforces its network policy from the first boot (or refuses);\n // its repositories, steps and services are applied by the platform.\n create(\n ctx: SandboxResourceContextIface,\n args: { artifact: Artifact; setup: SandboxSetupIface | null },\n ): Promise<{ state: State; region?: string | null }>;\n // Resolves once the backend named by `state` is running and will accept a\n // command or a file write; rejects with a clear error after `timeoutMs`.\n // The provider chooses the readiness signal and backoff; the platform never\n // polls a backend itself.\n awaitRunning(\n ctx: SandboxResourceContextIface,\n state: State,\n options: { timeoutMs: number },\n ): Promise<void>;\n // Boots or resumes the sandbox and returns a live handle.\n attach(\n ctx: SandboxResourceContextIface,\n args: { artifact: Artifact; state: State },\n ): Promise<SandboxAttachmentIface<State, S>>;\n // Reconnects to an already running backend for a read-only viewer: never\n // boots, creates, seeds or restarts anything. Absent: viewers use a live\n // handle or nothing.\n attachPassive?(\n ctx: SandboxResourceContextIface,\n args: { artifact: Artifact; state: State },\n ): Promise<SandboxProviderHandleIface<S>>;\n // The host is done with its handle for now; the sandbox may go idle on the\n // provider's own policy. Returns the state the next attach needs.\n detach(ctx: SandboxResourceContextIface, args: { state: State }): Promise<State>;\n // Pauses or stops the sandbox, keeping its disk. Returns the state the next attach needs.\n park(\n ctx: SandboxResourceContextIface,\n args: { artifact: Artifact; state: State },\n ): Promise<State>;\n // Destroys the backend resource and its disk. Deleting one already gone succeeds.\n delete(ctx: SandboxResourceContextIface, args: { state: State }): Promise<void>;\n}\n\nexport interface SandboxProviderDefinitionIface<\n EnvOptions,\n Artifact extends JsonValue,\n State extends JsonValue,\n S extends NetworkSandboxSessionIface,\n> {\n name: string;\n // The version of `State`'s shape. The host records it with each sandbox and\n // refuses to attach a state written under another version.\n stateProtocolVersion?: number;\n // Validates the options and returns the environment they describe.\n environment(options?: EnvOptions): SandboxEnvironmentImplementationIface<Artifact, State, S>;\n}\n\n// What `project.sandboxes.create(environment, \u2026)` takes: a provider by name\n// and that provider's own environment options, as plain data.\nexport interface SandboxEnvironmentValueIface<EnvOptions = JsonValue> {\n provider: string;\n environment: EnvOptions;\n}\n\n// A defined provider: the definition the host drives, and `environment(opts)`\n// returning the plain value a caller creates sandboxes from.\nexport interface SandboxProviderIface<\n EnvOptions,\n Artifact extends JsonValue,\n State extends JsonValue,\n S extends NetworkSandboxSessionIface,\n> {\n readonly definition: SandboxProviderDefinitionIface<EnvOptions, Artifact, State, S>;\n readonly name: string;\n environment(options: EnvOptions): SandboxEnvironmentValueIface<EnvOptions>;\n}\n\nexport const defineSandboxProvider = <\n EnvOptions,\n Artifact extends JsonValue,\n State extends JsonValue,\n S extends NetworkSandboxSessionIface,\n>(\n definition: SandboxProviderDefinitionIface<EnvOptions, Artifact, State, S>,\n): SandboxProviderIface<EnvOptions, Artifact, State, S> => ({\n definition: withSandboxOverrides(definition, {\n environment: (options?: EnvOptions) => {\n const implementation = definition.environment(options);\n for (const method of [\n 'create',\n 'attach',\n 'detach',\n 'park',\n 'delete',\n 'awaitRunning',\n ] as const)\n if (typeof implementation[method] !== 'function')\n throw new Error(`sandbox provider ${definition.name} does not implement ${method}`);\n const overrides: Partial<typeof implementation> = {\n attach: async (ctx, args) => {\n const attached = await implementation.attach(ctx, args);\n return {\n ...attached,\n handle: createSandboxHandle({\n handle: attached.handle,\n executionPolicy: ctx.executionPolicy,\n }),\n };\n },\n };\n if (implementation.editor != null) {\n const editor = implementation.editor.bind(implementation);\n overrides.editor = async (ctx, state, request) => {\n if (\n request.operation === SandboxEditorOperation.Open ||\n request.operation === SandboxEditorOperation.Refresh\n )\n await ctx.executionPolicy?.beforeExecution({\n operation: SandboxExecutionOperation.Editor,\n background: false,\n });\n return editor(ctx, state, request);\n };\n }\n if (implementation.attachPassive != null) {\n const attachPassive = implementation.attachPassive.bind(implementation);\n overrides.attachPassive = async (ctx, args) =>\n createSandboxHandle({\n handle: await attachPassive(ctx, args),\n executionPolicy: ctx.executionPolicy,\n });\n }\n return withSandboxOverrides(implementation, overrides);\n },\n }),\n name: definition.name,\n environment: (options) => ({ provider: definition.name, environment: options }),\n});\n\n// The runtime kinds an environment declares, or its default.\nexport const sandboxRuntimesOf = async (\n environment: Pick<\n SandboxEnvironmentImplementationIface<JsonValue, JsonValue, NetworkSandboxSessionIface>,\n 'capabilities' | 'runtimes'\n >,\n ctx: SandboxOfferContextIface,\n): Promise<RuntimeKind[]> => {\n if (environment.runtimes != null) return environment.runtimes(ctx);\n const offer = await environment.capabilities(ctx);\n return offer[Capability.Shell] == null ? [] : [RuntimeKind.Process];\n};\n\n// Erased form a host stores in its provider registry.\nexport type AnySandboxProviderIface = SandboxProviderIface<\n JsonValue,\n JsonValue,\n JsonValue,\n NetworkSandboxSessionIface\n>;\n\n// Events emitted through a sandbox provider's process lifecycle.\nexport enum SandboxEventKind {\n ProcessExited = 'process_exited',\n}\n"],
|
|
5
|
-
"mappings": "
|
|
4
|
+
"sourcesContent": ["import type { SandboxThumbnailIface } from '@finalai/agent-protocol/sandbox-provider-wire';\nimport { Capability, RuntimeKind, type CapabilityAccess } from '@finalai/agent-protocol';\nimport * as z from 'zod';\nimport { SandboxEntryType } from \"./file-kind.mjs\";\nexport { SandboxEntryType } from \"./file-kind.mjs\";\nimport { createSandboxHandle, type SandboxExecutionPolicyIface } from \"./handle.mjs\";\nimport { withSandboxOverrides } from \"./overrides.mjs\";\nimport { NetworkPolicy, type NetworkPolicyIface } from '@finalai/agent-protocol/network-policy';\nexport { NetworkPolicy, type NetworkPolicyIface } from '@finalai/agent-protocol/network-policy';\nimport type {\n ProcessInspectionRequestIface,\n ProcessInspectionResultIface,\n} from '@finalai/agent-protocol/process-inspection';\nimport type { JsonValue } from \"../json.mjs\";\nimport type { ToolDescriptorIface } from \"../tool-descriptor.mjs\";\nimport {\n SandboxEditorOperation,\n type SandboxEditorRequestIface,\n type SandboxEditorResultIface,\n} from \"./editor.mjs\";\nimport { SandboxExecutionOperation } from \"./execution-guard.mjs\";\nimport type { SandboxSetupIface } from \"./setup/schema.mjs\";\nimport type { SandboxSnapshotRequestIface, SandboxSnapshotResponseIface } from \"./snapshots.mjs\";\n\nexport {\n SandboxThumbnailContentType,\n sandboxThumbnailSchema,\n type SandboxThumbnailIface,\n} from '@finalai/agent-protocol/sandbox-provider-wire';\n\n// Sandbox providers and consumers share the streaming session contract.\n\nexport interface AbortableIface {\n abortSignal?: AbortSignal;\n}\n\nexport interface SandboxProcessOptionsIface extends AbortableIface {\n command: string;\n args?: string[];\n cwd?: string;\n env?: Record<string, string>;\n // Run through the sandbox's login shell (`bash -lc`) instead of exec'ing.\n shell?: boolean;\n stdin?: ReadableStream<Uint8Array> | string;\n timeoutMs?: number;\n // Spawn only (`run` ignores it): ask for a durable process on a sandbox with\n // SandboxCapability.DurableProcesses; ignored elsewhere (the handle's `ref`\n // is then null). A durable process ends only on its own exit, `kill`,\n // `timeoutMs` (enforced inside the sandbox, not by a provider-side timer) or\n // sandbox stop/destroy. Dropping its handle (connection close, runtime\n // shutdown, `abortSignal`) detaches without killing: the handle's streams\n // fail and `wait` rejects, and `attachProcess` finds the process again.\n durable?: boolean;\n}\n\nexport interface SandboxProcessIface {\n readonly pid: string | null;\n // Opaque, provider-encoded (versioned) reference for `attachProcess`; non-null\n // only for a durable process on a sandbox with durable processes. Optional so\n // implementations without them need not set it.\n readonly ref?: string | null;\n readonly stdout: ReadableStream<Uint8Array>;\n readonly stderr: ReadableStream<Uint8Array>;\n // Writes to the process's stdin; closes stdin when `end` is true.\n write(data: Uint8Array | string, options?: { end?: boolean }): Promise<void>;\n wait(): Promise<{ exitCode: number }>;\n kill(signal?: string): Promise<void>;\n}\n\n// A program built for the sandbox's worker runtime, started for one harness\n// session. Its handle is a process's: what is written to it is its input\n// stream, stdout its output stream, stderr its diagnostics.\nexport interface SandboxWorkerOptionsIface extends AbortableIface {\n program: string;\n env?: Record<string, string>;\n // Handed to the program when it starts.\n input?: JsonValue;\n // As for spawn: survives the handle on a sandbox with durable processes.\n durable?: boolean;\n // A platform-identity assertion for the program's run (variant `harness-run`),\n // for a runtime that authenticates the programs it starts.\n identity?: string;\n}\n\nexport enum SandboxWorkerEndpointTransport {\n Ws = 'ws',\n Http = 'http',\n Relay = 'relay',\n}\n\n// Where a started worker program serves its stream itself, for the caller to\n// dial directly: an ACP endpoint by URL, or a relay channel.\nexport type SandboxWorkerEndpointType =\n | {\n transport: SandboxWorkerEndpointTransport.Ws | SandboxWorkerEndpointTransport.Http;\n url: string;\n headers: Record<string, string>;\n }\n | { transport: SandboxWorkerEndpointTransport.Relay; channel: string; token: string };\n\nexport interface SandboxWorkerEndpointIface {\n readonly endpoint: SandboxWorkerEndpointType;\n}\n\n// A started worker program: a process whose streams carry its stream, or an\n// endpoint it serves.\nexport type SandboxWorkerStartType = SandboxProcessIface | SandboxWorkerEndpointIface;\n\nexport const isSandboxWorkerEndpoint = (\n started: SandboxWorkerStartType,\n): started is SandboxWorkerEndpointIface => 'endpoint' in started;\n\nexport interface SandboxAttachProcessOptionsIface extends AbortableIface {\n ref: string;\n // Bytes of each stream the caller already has; output resumes there.\n stdoutOffset: number;\n stderrOffset: number;\n}\n\n// A durable process found again by its ref. Its output is read from the\n// provider, which is the source of truth for output and exit; aborting\n// `abortSignal` detaches this handle as it does a spawned durable one.\n//\n// Limitation: stdin belongs to the spawning handle only. A re-attached\n// process can be watched, waited for and killed, but not written to; a process\n// that needs input after a re-attach must read it from somewhere else (a file).\nexport interface SandboxAttachedProcessIface {\n readonly ref: string;\n // Where the streams actually start: the requested offsets, or later when the\n // provider no longer retains the earlier bytes (see each provider's retention).\n readonly stdoutOffset: number;\n readonly stderrOffset: number;\n readonly stdout: ReadableStream<Uint8Array>;\n readonly stderr: ReadableStream<Uint8Array>;\n wait(): Promise<{ exitCode: number }>;\n kill(signal?: string): Promise<void>;\n}\n\nexport interface SandboxRunResultIface {\n exitCode: number;\n stdout: string;\n stderr: string;\n}\n\nexport interface StatIface {\n path: string;\n type: SandboxEntryType;\n size: number;\n modifiedAt: string | null;\n mode: number | null;\n}\n\nexport interface DirEntryIface {\n name: string;\n path: string;\n type: SandboxEntryType;\n size: number | null;\n}\n\nexport interface ConfinedSandboxFilesIface {\n readFile(\n options: { path: string; root: string } & AbortableIface,\n ): Promise<ReadableStream<Uint8Array> | null>;\n stat(options: { path: string; root: string } & AbortableIface): Promise<StatIface | null>;\n readDir(\n options: { path: string; root: string } & AbortableIface,\n ): Promise<DirEntryIface[] | null>;\n}\n\nexport interface SandboxSessionIface {\n readonly description: string;\n readonly confinedFileReader?: ConfinedSandboxFilesIface;\n // On the RPC surface, root confines viewer reads to this directory, rejects\n // symlink ancestors and requires Python 3 in the sandbox (confinedFiles feature).\n readFile(\n options: { path: string; root?: string } & AbortableIface,\n ): Promise<ReadableStream<Uint8Array> | null>;\n readBinaryFile(options: { path: string } & AbortableIface): Promise<Uint8Array | null>;\n readTextFile(\n options: {\n path: string;\n encoding?: string;\n startLine?: number;\n endLine?: number;\n } & AbortableIface,\n ): Promise<string | null>;\n writeFile(\n options: { path: string; content: ReadableStream<Uint8Array> } & AbortableIface,\n ): Promise<void>;\n writeBinaryFile(options: { path: string; content: Uint8Array } & AbortableIface): Promise<void>;\n // Writes create missing parent directories.\n writeTextFile(\n options: { path: string; content: string; encoding?: string } & AbortableIface,\n ): Promise<void>;\n spawn(options: SandboxProcessOptionsIface): Promise<SandboxProcessIface>;\n // Present on sandboxes with durable processes. Null when the process is\n // unknown: the sandbox restarted or was deleted, or the ref expired, is\n // malformed or belongs to another sandbox. Attaching after the process\n // exited still yields its retained output and exit code.\n attachProcess?(\n options: SandboxAttachProcessOptionsIface,\n ): Promise<SandboxAttachedProcessIface | null>;\n run(options: SandboxProcessOptionsIface): Promise<SandboxRunResultIface>;\n stat(options: { path: string; root?: string } & AbortableIface): Promise<StatIface | null>;\n readDir(options: { path: string; root?: string } & AbortableIface): Promise<DirEntryIface[]>;\n resolvePath(path: string): string;\n removePath(\n options: { path: string; recursive?: boolean; force?: boolean } & AbortableIface,\n ): Promise<void>;\n}\n\nexport enum PortProtocol {\n Http = 'http',\n Https = 'https',\n Ws = 'ws',\n}\n\n// An MCP transport the sandbox serves for an optional capability: an HTTP MCP\n// endpoint the harness (or the host) can dial.\nexport interface McpEndpointIface {\n name: string;\n url: string;\n headers: Record<string, string>;\n}\n\n// A JSON-RPC message channel to an MCP server the sandbox hosts, for backends\n// whose API reaches it some other way than HTTP MCP (a byte pipe, a socket).\n// Messages are JSON-RPC objects, in order.\nexport interface McpChannelIface {\n send(message: JsonValue, options?: AbortableIface): Promise<void>;\n // The messages that arrived since the last call; [] when none did.\n receive(options?: AbortableIface): Promise<JsonValue[]>;\n close(): Promise<void>;\n}\n\n// An MCP server the sandbox hosts, opened in process by whoever runs the handle.\n// It cannot cross the handle RPC wire.\nexport interface McpChannelEndpointIface {\n name: string;\n connect(options?: AbortableIface): Promise<McpChannelIface>;\n}\n\nexport type SandboxMcpEndpoint = McpEndpointIface | McpChannelEndpointIface;\n\n// The tools of a sandbox's hosted MCP servers, as far as they are known without\n// starting it. Null: unknown until the sandbox is attached and asked.\nexport interface SandboxMcpCatalogIface {\n computerUse: ToolDescriptorIface[] | null;\n // Local MCP server name \u2192 its tools.\n localMcp: Record<string, ToolDescriptorIface[]> | null;\n // Partial discovery retains known tools and must be retried, including after caching.\n localMcpIncomplete?: boolean;\n}\n\nexport const isMcpChannelEndpoint = (\n endpoint: SandboxMcpEndpoint,\n): endpoint is McpChannelEndpointIface => 'connect' in endpoint;\n\nexport interface ScreenOptionsIface {\n // View-only by default; explicit input control requires execute access.\n viewOnly?: boolean;\n}\n\nexport interface ScreenSessionIface {\n // A short-lived viewer grant; providers enforce the requested input access.\n url: string;\n token: string;\n expiresAt: string;\n}\n\nexport interface NetworkSandboxSessionIface extends SandboxSessionIface {\n readonly id: string;\n readonly defaultWorkingDirectory: string;\n readonly ports: readonly number[];\n getPortEndpoint(options: {\n port: number;\n protocol?: PortProtocol;\n }): Promise<{ url: string; headers?: Record<string, string> }>;\n getPortUrl(options: { port: number; protocol?: PortProtocol }): Promise<string>;\n stop(): Promise<void>;\n destroy(): Promise<void>;\n setNetworkPolicy?(policy: NetworkPolicyIface): Promise<void>;\n computerUse?(): Promise<SandboxMcpEndpoint>;\n // Present on sandboxes whose provider offers RuntimeKind.Worker.\n startWorker?(options: SandboxWorkerOptionsIface): Promise<SandboxWorkerStartType>;\n screen?(options?: ScreenOptionsIface): Promise<ScreenSessionIface>;\n localMcp?(): Promise<SandboxMcpEndpoint[]>;\n}\n\n// Features a live sandbox handle advertises over the handle RPC (`describe`).\n// Finer than the model's capabilities (`Capability`): `files` is served by the\n// file methods, `shell` by processes and ports, `computerUse` by computer use\n// and the screen; the rest are handle extensions a capability may use.\nexport enum SandboxCapability {\n Files = 'files',\n Process = 'process',\n Ports = 'ports',\n NetworkPolicy = 'networkPolicy',\n ComputerUse = 'computerUse',\n Screen = 'screen',\n LocalMcp = 'localMcp',\n Browser = 'browser',\n // `spawn({ durable: true })` and `attachProcess` (see SandboxProcessOptionsIface.durable).\n DurableProcesses = 'durableProcesses',\n // `startWorker`: the sandbox runs worker programs.\n Workers = 'workers',\n}\n\n// The capabilities a provider's sandboxes serve, each with the most access a\n// session can be granted on it. A capability left out is not served.\nexport type SandboxCapabilityOffer = Partial<Record<Capability, CapabilityAccess>>;\n\nexport interface SandboxProviderHandleIface<S extends SandboxSessionIface> {\n readonly sandbox: S;\n // Pending policy; the generic handle constructor consumes it before exposing execution.\n readonly executionPolicy?: SandboxExecutionPolicyIface;\n onSandboxStop(): Promise<void>;\n onSandboxDelete(options?: { reason?: string }): Promise<void>;\n onRuntimeShutdown(): Promise<void>;\n}\n\n// The person a sandbox acts for on this call: the author of the running turn,\n// else whoever opened the sandbox's viewer. Null when it acts for no person\n// (an unprompted turn, a preparation). Read on each call: it changes between\n// turns and between callers.\nexport interface SandboxActingUserIface {\n current(): Promise<string | null>;\n}\n\nexport const noSandboxActingUser: SandboxActingUserIface = { current: async () => null };\n\n// Credentials the host supplies to a provider. A provider reads no secrets of\n// its own and names no project: it gets the value of the secret its\n// environment's `credential.secretRef` names, resolved in the sandbox's project.\nexport interface SandboxCredentialsIface {\n secret(args: { secretRef: string }): Promise<string | null>;\n}\n\nexport const noSandboxCredentials: SandboxCredentialsIface = { secret: async () => null };\n\n// A provider's credential by reference, in its environment options: the name\n// of a project secret, never its value.\nexport const sandboxCredentialRefSchema = z.strictObject({\n secretRef: z.string().min(1).max(256),\n});\n\nexport type SandboxCredentialRefIface = z.infer<typeof sandboxCredentialRefSchema>;\n\n// A platform-identity assertion (`@finalai/agent-protocol/identity`) for one\n// backend audience, valid until `expiresAt`.\nexport interface SandboxIdentityTokenIface {\n token: string;\n expiresAt: string;\n}\n\n// How a provider authenticates to a backend it needs (its vendor's API): an\n// assertion for `audience`, which the platform issues only for audiences the\n// provider's registration was granted. It names the sandbox's organization,\n// project and sandbox, and the acting user at the time it was issued. Ask\n// before each backend call (hosts cache it); `refresh` asks for a new one\n// after the backend rejected the last.\nexport type SandboxIdentityFn = (args: {\n audience: string;\n refresh?: boolean;\n}) => Promise<SandboxIdentityTokenIface>;\n\nexport const noSandboxIdentity: SandboxIdentityFn = async ({ audience }) => {\n throw new Error(`no identity was granted for ${audience}`);\n};\n\n// What every provider call is given: the project the sandbox belongs to, the\n// host's credentials and the provider's identity for the backends it was\n// granted.\nexport interface SandboxProviderContextIface {\n organizationId: string;\n projectId: string;\n credentials: SandboxCredentialsIface;\n actingUser: SandboxActingUserIface;\n identity: SandboxIdentityFn;\n log?: (message: string, fields?: Record<string, string | number | boolean | null>) => void;\n}\n\n// How the platform runs a sandbox's lifecycle, for the provider to align its\n// backend with: after `parkAfterIdleMs` of idleness the platform parks the\n// sandbox (null: the provider's own default), so a backend idle timeout\n// should be longer.\nexport interface SandboxLifecycleIface {\n parkAfterIdleMs: number | null;\n}\n\n// What reads that start nothing are given (capabilities, catalogs, snapshots,\n// process inspection, the editor). `sandboxId` is set for reads about an\n// existing sandbox.\nexport interface SandboxOfferContextIface extends SandboxProviderContextIface {\n sandboxId?: string;\n executionPolicy?: SandboxExecutionPolicyIface;\n platformNetworkPolicy?: (policy: NetworkPolicyIface) => Promise<void>;\n // Retain platform transport access when an extension restores an allowlist.\n platformEgressHosts?: string[];\n}\n\n// Scoped by the host to this project and provider. Providers can retain\n// reusable intermediate artifacts independently of a sandbox's seed files.\nexport interface SandboxArtifactsIface {\n get(key: string): Promise<JsonValue | null>;\n put(key: string, artifact: JsonValue): Promise<void>;\n}\n\nexport interface SandboxPreparationSourceIface {\n sourceRevision: string;\n read(): Promise<{ files: Record<string, string>; resources: Record<string, JsonValue> }>;\n}\n\n// A preparation builds what an environment's sandboxes start from (an image\n// built into a base, a snapshot). It depends on the environment's options and\n// the seed files only, never on a sandbox setup.\nexport interface SandboxPrepareContextIface extends SandboxProviderContextIface {\n // A host-persisted resource source; artifacts may retain its identity instead of seed contents.\n preparation?: SandboxPreparationSourceIface;\n artifacts?: SandboxArtifactsIface;\n // Workspace-relative seed files and named resources.\n files: Record<string, string>;\n resources: Record<string, JsonValue>;\n sourceRevision: string;\n storagePath: string;\n}\n\n// What a provider is given for one sandbox: its create, attach, detach, park\n// and delete calls.\nexport interface SandboxResourceContextIface extends SandboxProviderContextIface {\n // The platform's id for the sandbox, stable for its whole life.\n sandboxId: string;\n lifecycle: SandboxLifecycleIface;\n // Host policy composes before the provider's policy, on every exposed execution path.\n executionPolicy?: SandboxExecutionPolicyIface;\n preparation?: SandboxPreparationSourceIface;\n storagePath: string;\n // Variables the platform sets in every process of this sandbox: the egress\n // proxy, trust for its CA, one placeholder per bound secret and the sandbox\n // setup's variables. Evaluated again for every spawn/run, never once per\n // attach: a secret bound later must reach the next command. May resolve to\n // {}. Platform values override the environment's own.\n platformEnvironment?: () => Promise<Record<string, string>>;\n // Hosts the sandbox must be able to reach for the proxy to work, appended\n // to any allowlist network policy.\n platformEgressHosts?: string[];\n // Reports the network policy now in force, exactly as the provider applied\n // it to its backend (after withPlatformEgressHosts); the platform permits\n // only those destinations. Called on every attach after awaitRunning and\n // before platformFiles or any command; never for a session's own\n // setNetworkPolicy. A rejection fails the attach.\n platformNetworkPolicy: (policy: NetworkPolicyIface) => Promise<void>;\n // Files the platform needs before any command runs: written right after the\n // sandbox is running, on every attach. Paths are absolute; missing parent\n // directories are created.\n platformFiles?: () => Promise<Record<string, string>>;\n}\n\n// The variables `platformEnvironment` owns. An environment that sets one is\n// refused at create.\nexport const PLATFORM_ENVIRONMENT_NAMES: ReadonlySet<string> = new Set([\n 'HTTPS_PROXY',\n 'HTTP_PROXY',\n 'NO_PROXY',\n 'NODE_USE_ENV_PROXY',\n 'SSL_CERT_FILE',\n 'CURL_CA_BUNDLE',\n 'REQUESTS_CA_BUNDLE',\n 'GIT_SSL_CAINFO',\n 'CARGO_HTTP_CAINFO',\n 'DENO_CERT',\n 'NODE_EXTRA_CA_CERTS',\n 'FINAL_EGRESS_URL',\n 'FINAL_EGRESS_TOKEN',\n]);\n\n// A process's base environment: the environment's variables under the\n// platform's, read again on every call.\nexport const platformProcessEnvironment =\n (\n ctx: Pick<SandboxResourceContextIface, 'platformEnvironment'>,\n specEnv: Record<string, string>,\n ): (() => Promise<Record<string, string>>) =>\n async () => ({ ...specEnv, ...(await ctx.platformEnvironment?.()) });\n\n// Writes `platformFiles` into a sandbox that is now running, before it runs anything.\n// Relies on writeTextFile creating missing parent directories.\nexport const writePlatformFiles = async (\n ctx: Pick<SandboxResourceContextIface, 'platformFiles'>,\n sandbox: Pick<SandboxSessionIface, 'writeTextFile'>,\n): Promise<void> => {\n for (const [path, content] of Object.entries((await ctx.platformFiles?.()) ?? {}))\n await sandbox.writeTextFile({ path, content });\n};\n\n// Reports the policy a provider just applied to its backend: `allow` only for an\n// allowlist, its entries (hosts, `*.suffix` patterns, CIDRs) unchanged.\nexport const reportPlatformNetworkPolicy = async (\n ctx: Pick<SandboxResourceContextIface, 'platformNetworkPolicy'>,\n policy: NetworkPolicyIface,\n): Promise<void> =>\n ctx.platformNetworkPolicy(\n policy.mode === NetworkPolicy.Allowlist\n ? { mode: policy.mode, allow: [...(policy.allow ?? [])] }\n : { mode: policy.mode },\n );\n\n// An allowlist policy with the platform's egress hosts appended; any other\n// policy unchanged.\nexport const withPlatformEgressHosts = (\n ctx: Pick<SandboxResourceContextIface, 'platformEgressHosts'>,\n policy: NetworkPolicyIface,\n): NetworkPolicyIface => {\n const hosts = ctx.platformEgressHosts ?? [];\n if (policy.mode !== NetworkPolicy.Allowlist || hosts.length === 0) return policy;\n return { ...policy, allow: [...new Set([...(policy.allow ?? []), ...hosts])] };\n};\n\n// One attach of a sandbox: the live handle, and what the attach lost, so the\n// platform knows which phases of the sandbox setup to redo.\nexport interface SandboxAttachmentIface<\n State extends JsonValue,\n S extends NetworkSandboxSessionIface,\n> {\n handle: SandboxProviderHandleIface<S>;\n // The state to keep for the next call (a resumed backend may change ids).\n state: State;\n // The disk is new: nothing written by a setup, the workspace seeds or a\n // session survives on it (first attach, or a backend that lost it).\n fresh: boolean;\n // The machine started on this attach: no process from before is running.\n booted: boolean;\n // Where the backend runs the sandbox (its own region name), so the host can\n // place the harness near it; null when unknown.\n region?: string | null;\n}\n\n// One environment of a provider, as the host drives it. A sandbox is a\n// resource the platform owns: `create` makes it (nothing need boot), `attach`\n// makes it reachable for a while, `detach` lets it go idle, `park` makes it as\n// cheap as the provider can while keeping its disk, `delete` destroys it.\n//\n// Order on attach: attach (boot or resume) \u2192 awaitRunning \u2192\n// platformNetworkPolicy \u2192 platformFiles \u2192 handle; the platform then applies\n// the sandbox setup through the handle (./setup). A provider never runs a\n// setup's steps itself.\nexport interface SandboxEnvironmentImplementationIface<\n Artifact extends JsonValue,\n State extends JsonValue,\n S extends NetworkSandboxSessionIface,\n> {\n // The capabilities this environment's sandboxes serve and the most access\n // each grants, known without creating one.\n capabilities(ctx: SandboxOfferContextIface): Promise<SandboxCapabilityOffer>;\n // What a harness can run in this environment's sandboxes: processes, worker\n // programs (`startWorker`), or both. Absent: processes when it offers `shell`.\n runtimes?(ctx: SandboxOfferContextIface): Promise<RuntimeKind[]>;\n // Handle features this environment's sandboxes advertise, read before\n // anything starts. Absent or null: unknown until attached; local MCP is then\n // not projected.\n features?(ctx: SandboxOfferContextIface): Promise<SandboxCapability[] | null>;\n // Known positive features when the rest of the pre-attach set is unknown.\n additionalFeatures?(ctx: SandboxOfferContextIface): Promise<SandboxCapability[]>;\n // The hosted MCP servers' tool catalogs the backend can give without\n // attaching, so the MCP projection lists them from the first `tools/list`.\n // A catalog left unknown can only be learned from a live sandbox, so the\n // first `tools/list` that finds it unknown attaches in the background.\n mcpCatalog?(ctx: SandboxOfferContextIface): Promise<SandboxMcpCatalogIface | null>;\n // An authorized read of the provider's last retained desktop image, including while asleep.\n // Never attach, start, resume, capture a new frame or extend idle time here. Null means no image.\n // Providers own capture and retention; callers may display this retained image.\n // A permission denial must throw. Null withdraws any previously displayed image.\n readThumbnail?(\n ctx: SandboxOfferContextIface & { sandboxId: string },\n state: State,\n ): Promise<SandboxThumbnailIface | null>;\n // Reads committed files without attaching. Null means the backend is live\n // or offers no snapshot. An unavailable sleeping snapshot must throw, never\n // fall through to a read that wakes it. Pin later ranges by snapshotId.\n readSnapshot?(\n ctx: SandboxOfferContextIface,\n state: State,\n request: SandboxSnapshotRequestIface,\n ): Promise<SandboxSnapshotResponseIface | null>;\n // Inspect retained backend processes without attaching or extending a sandbox.\n // Stopping one requires shell access; the provider also enforces backend ownership.\n processes?(\n ctx: SandboxOfferContextIface & { sandboxId: string },\n state: State,\n request: ProcessInspectionRequestIface,\n ): Promise<ProcessInspectionResultIface>;\n // Browser editor for an existing sandbox. The host checks write\n // authorization; this hook never creates or wakes a backend. Credentials stay\n // in the authentication form, never the editor URL or stored provider state.\n editor?(\n ctx: SandboxOfferContextIface,\n state: State,\n request: SandboxEditorRequestIface,\n ): Promise<SandboxEditorResultIface>;\n // Content-addressed by `artifactKey`; the host caches artifacts and calls\n // prepare only on a miss.\n artifactKey(ctx: SandboxPrepareContextIface): Promise<string>;\n prepare(ctx: SandboxPrepareContextIface): Promise<Artifact>;\n // Makes the sandbox's backend resource. The setup is given so the\n // provider enforces its network policy from the first boot (or refuses);\n // its repositories, steps and services are applied by the platform.\n create(\n ctx: SandboxResourceContextIface,\n args: { artifact: Artifact; setup: SandboxSetupIface | null },\n ): Promise<{ state: State; region?: string | null }>;\n // Resolves once the backend named by `state` is running and will accept a\n // command or a file write; rejects with a clear error after `timeoutMs`.\n // The provider chooses the readiness signal and backoff; the platform never\n // polls a backend itself.\n awaitRunning(\n ctx: SandboxResourceContextIface,\n state: State,\n options: { timeoutMs: number },\n ): Promise<void>;\n // Boots or resumes the sandbox and returns a live handle.\n attach(\n ctx: SandboxResourceContextIface,\n args: { artifact: Artifact; state: State },\n ): Promise<SandboxAttachmentIface<State, S>>;\n // Reconnects to an already running backend for a read-only viewer: never\n // boots, creates, seeds or restarts anything. Absent: viewers use a live\n // handle or nothing.\n attachPassive?(\n ctx: SandboxResourceContextIface,\n args: { artifact: Artifact; state: State },\n ): Promise<SandboxProviderHandleIface<S>>;\n // The host is done with its handle for now; the sandbox may go idle on the\n // provider's own policy. Returns the state the next attach needs.\n detach(ctx: SandboxResourceContextIface, args: { state: State }): Promise<State>;\n // Pauses or stops the sandbox, keeping its disk. Returns the state the next attach needs.\n park(\n ctx: SandboxResourceContextIface,\n args: { artifact: Artifact; state: State },\n ): Promise<State>;\n // Destroys the backend resource and its disk. Deleting one already gone succeeds.\n delete(ctx: SandboxResourceContextIface, args: { state: State }): Promise<void>;\n}\n\nexport interface SandboxProviderDefinitionIface<\n EnvOptions,\n Artifact extends JsonValue,\n State extends JsonValue,\n S extends NetworkSandboxSessionIface,\n> {\n name: string;\n // The version of `State`'s shape. The host records it with each sandbox and\n // refuses to attach a state written under another version.\n stateProtocolVersion?: number;\n // Validates the options and returns the environment they describe.\n environment(options?: EnvOptions): SandboxEnvironmentImplementationIface<Artifact, State, S>;\n}\n\n// What `project.sandboxes.create(environment, \u2026)` takes: a provider by name\n// and that provider's own environment options, as plain data.\nexport interface SandboxEnvironmentValueIface<EnvOptions = JsonValue> {\n provider: string;\n environment: EnvOptions;\n}\n\n// A defined provider: the definition the host drives, and `environment(opts)`\n// returning the plain value a caller creates sandboxes from.\nexport interface SandboxProviderIface<\n EnvOptions,\n Artifact extends JsonValue,\n State extends JsonValue,\n S extends NetworkSandboxSessionIface,\n> {\n readonly definition: SandboxProviderDefinitionIface<EnvOptions, Artifact, State, S>;\n readonly name: string;\n environment(options: EnvOptions): SandboxEnvironmentValueIface<EnvOptions>;\n}\n\nexport const defineSandboxProvider = <\n EnvOptions,\n Artifact extends JsonValue,\n State extends JsonValue,\n S extends NetworkSandboxSessionIface,\n>(\n definition: SandboxProviderDefinitionIface<EnvOptions, Artifact, State, S>,\n): SandboxProviderIface<EnvOptions, Artifact, State, S> => ({\n definition: withSandboxOverrides(definition, {\n environment: (options?: EnvOptions) => {\n const implementation = definition.environment(options);\n for (const method of [\n 'create',\n 'attach',\n 'detach',\n 'park',\n 'delete',\n 'awaitRunning',\n ] as const)\n if (typeof implementation[method] !== 'function')\n throw new Error(`sandbox provider ${definition.name} does not implement ${method}`);\n const overrides: Partial<typeof implementation> = {\n attach: async (ctx, args) => {\n const attached = await implementation.attach(ctx, args);\n return {\n ...attached,\n handle: createSandboxHandle({\n handle: attached.handle,\n executionPolicy: ctx.executionPolicy,\n }),\n };\n },\n };\n if (implementation.editor != null) {\n const editor = implementation.editor.bind(implementation);\n overrides.editor = async (ctx, state, request) => {\n if (\n request.operation === SandboxEditorOperation.Open ||\n request.operation === SandboxEditorOperation.Refresh\n )\n await ctx.executionPolicy?.beforeExecution({\n operation: SandboxExecutionOperation.Editor,\n background: false,\n });\n return editor(ctx, state, request);\n };\n }\n if (implementation.attachPassive != null) {\n const attachPassive = implementation.attachPassive.bind(implementation);\n overrides.attachPassive = async (ctx, args) =>\n createSandboxHandle({\n handle: await attachPassive(ctx, args),\n executionPolicy: ctx.executionPolicy,\n });\n }\n return withSandboxOverrides(implementation, overrides);\n },\n }),\n name: definition.name,\n environment: (options) => ({ provider: definition.name, environment: options }),\n});\n\n// The runtime kinds an environment declares, or its default.\nexport const sandboxRuntimesOf = async (\n environment: Pick<\n SandboxEnvironmentImplementationIface<JsonValue, JsonValue, NetworkSandboxSessionIface>,\n 'capabilities' | 'runtimes'\n >,\n ctx: SandboxOfferContextIface,\n): Promise<RuntimeKind[]> => {\n if (environment.runtimes != null) return environment.runtimes(ctx);\n const offer = await environment.capabilities(ctx);\n return offer[Capability.Shell] == null ? [] : [RuntimeKind.Process];\n};\n\n// Erased form a host stores in its provider registry.\nexport type AnySandboxProviderIface = SandboxProviderIface<\n JsonValue,\n JsonValue,\n JsonValue,\n NetworkSandboxSessionIface\n>;\n\n// Events emitted through a sandbox provider's process lifecycle.\nexport enum SandboxEventKind {\n ProcessExited = 'process_exited',\n}\n"],
|
|
5
|
+
"mappings": "AACA,SAAS,YAAY,mBAA0C;AAC/D,YAAY,OAAO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AL,kBAAKC,sBAAL;AACL,EAAAA,kBAAA,mBAAgB;AADN,SAAAA;AAAA,GAAA;",
|
|
6
6
|
"names": ["SandboxEntryType", "NetworkPolicy", "SandboxWorkerEndpointTransport", "PortProtocol", "SandboxCapability", "SandboxEventKind"]
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@finalai/agent-provider",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.17.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "Provider contracts for the agent stack: the agent document, requirements and inference, harnesses, sandboxes (handle, wire, grants, setups, MCP projection), the code host, channels, and the conformance kit.",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -242,8 +242,8 @@
|
|
|
242
242
|
},
|
|
243
243
|
"dependencies": {
|
|
244
244
|
"@agentclientprotocol/sdk": "1.8.0",
|
|
245
|
-
"@finalai/acp-session": "0.8.
|
|
246
|
-
"@finalai/agent-protocol": "0.
|
|
245
|
+
"@finalai/acp-session": "0.8.4",
|
|
246
|
+
"@finalai/agent-protocol": "0.18.0",
|
|
247
247
|
"@modelcontextprotocol/client": "^2.1.0",
|
|
248
248
|
"@modelcontextprotocol/core": "^2.1.0",
|
|
249
249
|
"@modelcontextprotocol/server": "^2.1.0",
|