@finalai/agent-provider 0.20.2 → 0.21.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/README.md +9 -3
- package/dist/modules/channel.d.mts +5 -0
- package/dist/modules/channel.mjs +6 -0
- package/dist/modules/channel.mjs.map +3 -3
- package/dist/modules/sandbox/remote/adapter.mjs +14 -0
- package/dist/modules/sandbox/remote/adapter.mjs.map +2 -2
- package/dist/modules/sandbox/remote/serve.mjs +23 -1
- package/dist/modules/sandbox/remote/serve.mjs.map +2 -2
- package/dist/modules/sandbox/types.d.mts +10 -0
- package/dist/modules/sandbox/types.mjs.map +2 -2
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -67,7 +67,10 @@ subscription first again once its limit resets; a 429 on platform credits is pas
|
|
|
67
67
|
A sandbox is a resource. A provider implements `create`, `attach` (reporting
|
|
68
68
|
whether the disk is `fresh` and the machine `booted`), `detach`, `park` and
|
|
69
69
|
`delete`, plus `capabilities` (each capability it serves with the most access it
|
|
70
|
-
grants) and the cached `artifactKey`/`prepare` preparation.
|
|
70
|
+
grants) and the cached `artifactKey`/`prepare` preparation. An optional `fork`
|
|
71
|
+
makes a new sandbox (`ctx.sandboxId`) in place of `create`, its disk a copy of a
|
|
72
|
+
`source` sandbox of the same environment; a retry with the same new sandbox id
|
|
73
|
+
returns the first copy. Every handle RPC method
|
|
71
74
|
is gated by the connection's per-capability grant (`./sandbox/grant`): `{ files:
|
|
72
75
|
'write' }` writes files and runs nothing.
|
|
73
76
|
|
|
@@ -90,7 +93,8 @@ sandbox, so a backend idle timeout can outlast it.
|
|
|
90
93
|
|
|
91
94
|
`/sandbox/remote` is the sandbox-provider wire. `serveSandboxProvider` serves
|
|
92
95
|
providers at the URLs a project registers: lifecycle calls over HTTP (long ones
|
|
93
|
-
answer NDJSON with heartbeats
|
|
96
|
+
answer NDJSON with heartbeats; `/v1/fork` only for an environment that implements
|
|
97
|
+
`fork`, which discovery reports as the `fork` feature), and `/v1/attach`, a WebSocket that carries the
|
|
94
98
|
handle RPC once attached. Each call is authenticated by a sandbox-provider
|
|
95
99
|
assertion; on the attach socket `identity/refresh` replaces it when the acting
|
|
96
100
|
user changes. The client checks it before every call and every message sent on
|
|
@@ -176,7 +180,9 @@ with its `connectUrl` only when the installer provided those pages; otherwise th
|
|
|
176
180
|
channel explains linking in its own words. A shared place cannot target Home.
|
|
177
181
|
`attach` records content without dispatching a turn. It supports recordings and
|
|
178
182
|
other channel-produced attachments. Explicit `anyone`/`group` defaults let `places.resolve`
|
|
179
|
-
create a Shared chat for a new anonymous call.
|
|
183
|
+
create a Shared chat for a new anonymous call. A place whose child places nest (threads in a
|
|
184
|
+
channel) may default `childPlaces: 'own'`: each child then talks in its own conversation,
|
|
185
|
+
grouped under the place, instead of in the place's (`parent`, the default). Input idempotency keys are scoped to
|
|
180
186
|
the selected route; never derive a key from a temporary handle. `places.observers` returns scoped observe
|
|
181
187
|
routes for resource notifications. An anonymous `turns.cancel` may cancel only an
|
|
182
188
|
anonymous turn started by this binding and route. Supply `turnId` to target an
|
|
@@ -59,8 +59,13 @@ export interface PlacePolicy {
|
|
|
59
59
|
replies: ChannelReplies | `${ChannelReplies}`;
|
|
60
60
|
audience: ChannelAudience | `${ChannelAudience}`;
|
|
61
61
|
}
|
|
62
|
+
export declare enum ChannelChildPlaces {
|
|
63
|
+
Parent = "parent",
|
|
64
|
+
Own = "own"
|
|
65
|
+
}
|
|
62
66
|
export interface PlaceDefaultsIface extends PlacePolicy {
|
|
63
67
|
create: ChannelCreate | `${ChannelCreate}`;
|
|
68
|
+
childPlaces?: ChannelChildPlaces | `${ChannelChildPlaces}`;
|
|
64
69
|
}
|
|
65
70
|
export type PlaceResolution = {
|
|
66
71
|
kind: 'connected';
|
package/dist/modules/channel.mjs
CHANGED
|
@@ -36,6 +36,11 @@ const placePolicySchema = z.object({
|
|
|
36
36
|
replies: z.nativeEnum(ChannelReplies),
|
|
37
37
|
audience: z.nativeEnum(ChannelAudience)
|
|
38
38
|
});
|
|
39
|
+
var ChannelChildPlaces = /* @__PURE__ */ ((ChannelChildPlaces2) => {
|
|
40
|
+
ChannelChildPlaces2["Parent"] = "parent";
|
|
41
|
+
ChannelChildPlaces2["Own"] = "own";
|
|
42
|
+
return ChannelChildPlaces2;
|
|
43
|
+
})(ChannelChildPlaces || {});
|
|
39
44
|
const refusalSchema = z.object({
|
|
40
45
|
refused: z.union([
|
|
41
46
|
z.literal("unlinked"),
|
|
@@ -80,6 +85,7 @@ var ChannelOAuthClientAuthentication = /* @__PURE__ */ ((ChannelOAuthClientAuthe
|
|
|
80
85
|
const defineChannel = (definition) => definition;
|
|
81
86
|
export {
|
|
82
87
|
ChannelAudience,
|
|
88
|
+
ChannelChildPlaces,
|
|
83
89
|
ChannelCreate,
|
|
84
90
|
ChannelCredentialKind,
|
|
85
91
|
ChannelOAuthClientAuthentication,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/channel.ts"],
|
|
4
|
-
"sourcesContent": ["import type { ContentBlock } from '@agentclientprotocol/sdk/experimental/v2/unstable';\nimport * as z from 'zod';\nimport { jsonObjectSchema, type JsonObject, type JsonValue } from \"./json.mjs\";\nimport type { ChannelSemanticDataByKindIface } from \"./semantic-events.mjs\";\n\n// Handles carry no authority until the platform validates their binding and invocation signature.\nexport const personHandleSchema = z.string().min(1).brand<'ChannelPerson'>();\nexport const conversationHandleSchema = z.string().min(1).brand<'ChannelConversation'>();\nexport type PersonHandle = z.infer<typeof personHandleSchema>;\nexport type ConversationHandle = z.infer<typeof conversationHandleSchema>;\n\nexport const principalRefSchema = z.object({\n id: z.string().min(1),\n tenant: z.string().min(1).optional(),\n displayName: z.string().optional(),\n});\nexport type PrincipalRef = z.infer<typeof principalRefSchema>;\nexport interface PlaceRef {\n kind: string;\n id: string;\n tenant?: string;\n parent?: PlaceRef;\n title?: string;\n}\nexport const placeRefSchema: z.ZodType<PlaceRef> = z.lazy(() =>\n z.object({\n kind: z.string().min(1),\n id: z.string().min(1),\n tenant: z.string().min(1).optional(),\n parent: placeRefSchema.optional(),\n title: z.string().optional(),\n }),\n);\nexport interface OriginIface {\n place: PlaceRef;\n ref?: JsonObject;\n}\nexport const originSchema = z.object({ place: placeRefSchema, ref: jsonObjectSchema.optional() });\n\nexport type PersonResolution =\n | { kind: 'member'; person: PersonHandle; displayName: string }\n // `linkUrl` is the installer's link page for this person, when the install has one; without\n // it, the channel tells the person how to link in its own words.\n | { kind: 'unlinked'; linkUrl?: string }\n | { kind: 'blocked'; reason: 'not-a-member' | 'suspended' };\nexport enum ChannelReplies {\n Origin = 'origin',\n All = 'all',\n}\nexport enum ChannelAudience {\n Members = 'members',\n Anyone = 'anyone',\n}\nexport enum ChannelCreate {\n DirectWithAgent = 'direct-with-agent',\n Group = 'group',\n}\nexport const placePolicySchema = z.object({\n replies: z.nativeEnum(ChannelReplies),\n audience: z.nativeEnum(ChannelAudience),\n});\nexport interface PlacePolicy {\n replies: ChannelReplies | `${ChannelReplies}`;\n audience: ChannelAudience | `${ChannelAudience}`;\n}\nexport interface PlaceDefaultsIface extends PlacePolicy {\n create: ChannelCreate | `${ChannelCreate}`;\n}\nexport type PlaceResolution =\n | { kind: 'connected'; conversation: ConversationHandle; policy: PlacePolicy }\n // `connectUrl` is the installer's connect page for this place, when the install has one.\n | { kind: 'unconnected'; connectUrl?: string; defaults: PlaceDefaultsIface | null };\nexport interface Refusal {\n refused: 'unlinked' | 'no-access' | 'unconnected' | 'not-audience';\n linkUrl?: string;\n connectUrl?: string;\n message: string;\n}\nexport type ChannelReceiveResult =\n | { accepted: true }\n | { accepted: false; refusal: Refusal }\n | { ignored: true; reason: string };\nexport const refusalSchema = z.object({\n refused: z.union([\n z.literal('unlinked'),\n z.literal('no-access'),\n z.literal('unconnected'),\n z.literal('not-audience'),\n ]),\n linkUrl: z.string().optional(),\n connectUrl: z.string().optional(),\n message: z.string(),\n});\nexport const channelReceiveResultSchema = z.union([\n z.object({ accepted: z.literal(true) }),\n z.object({ accepted: z.literal(false), refusal: refusalSchema }),\n z.object({ ignored: z.literal(true), reason: z.string() }),\n]);\nexport enum ChannelCredentialKind {\n // A provider tenant's token, stored when the tenant installed the channel's app.\n App = 'app',\n // A secret slot of the channel's app, injected without the channel reading it.\n Secret = 'secret',\n OAuth = 'oauth',\n None = 'none',\n}\nexport const channelCredentialHandleSchema = z.string().min(1).brand<'ChannelCredential'>();\nexport type ChannelCredentialHandle = z.infer<typeof channelCredentialHandleSchema>;\nexport type ChannelCredentialRef =\n | { kind: ChannelCredentialKind.App; tenant: string }\n // `scheme` is the Authorization scheme the secret is sent with (`Bearer` when omitted). Frame\n // injection writes the bare value.\n | { kind: ChannelCredentialKind.Secret; slot: string; scheme?: string }\n | { kind: ChannelCredentialKind.OAuth; handle: ChannelCredentialHandle }\n | { kind: ChannelCredentialKind.None };\nexport enum ChannelSigningAlgorithm {\n HmacSha256 = 'hmac-sha256',\n HmacSha1 = 'hmac-sha1',\n Ed25519 = 'ed25519',\n}\nexport enum ChannelSignatureEncoding {\n Hex = 'hex',\n Base64 = 'base64',\n}\nexport enum ChannelOAuthClientAuthentication {\n Body = 'body',\n Basic = 'basic',\n None = 'none',\n}\nexport interface ChannelCredentialRequestInitIface extends RequestInit {\n credential?: ChannelCredentialRef;\n}\nexport interface ChannelVerifyOptionsIface {\n // The app secret slot holding the signing secret or public key; its value is never read.\n secret: string;\n algorithm: ChannelSigningAlgorithm;\n encoding: ChannelSignatureEncoding;\n data: string;\n signature: string;\n}\nexport interface ChannelOAuthExchangeOptionsIface {\n url: string;\n parameters: Record<string, string>;\n authentication: ChannelOAuthClientAuthentication;\n clientId?: string;\n signal?: AbortSignal;\n // Stores the token as this provider tenant's install of the channel's app. Honoured only in a\n // redirect route whose state carries an unused tenant-install ticket for this binding. A\n // provider that names the tenant only in its token response is read at `tenantPath` there.\n store?: { tenant: string } | { tenantPath: string[] };\n}\nexport interface ChannelRedirectOptionsIface {\n // A GET route of this channel declared with `redirect: true`.\n path: string;\n // A tenant-install ticket the install route received; it is bound into the signed state.\n ticket?: string;\n}\nexport interface ChannelRedirectIface {\n url: string;\n state: string;\n}\nexport interface ChannelCredentialConnectOptionsIface {\n url: string;\n signal?: AbortSignal;\n}\nexport interface ChannelCredentialInjectionIface {\n path: string[];\n credential: ChannelCredentialRef;\n}\nexport interface ChannelCredentialSocketIface {\n messages: AsyncIterable<string | Uint8Array>;\n send(\n data: string | Uint8Array,\n options?: { inject?: ChannelCredentialInjectionIface[] },\n ): Promise<void>;\n close(code?: number, reason?: string): Promise<void>;\n closeCode(): number | null;\n}\nexport interface ChannelCredentialsIface {\n // The channel app's credentials stay with the host in every execution mode.\n client(): Promise<{ clientId: string }>;\n verify(args: ChannelVerifyOptionsIface): Promise<boolean>;\n exchange(args: ChannelOAuthExchangeOptionsIface): Promise<ChannelCredentialHandle>;\n // Send `url` as the OAuth redirect URI and `state` unchanged. `url` is the same for every\n // binding, so a provider application registers it once; `state` returns to this binding.\n redirect(args: ChannelRedirectOptionsIface): Promise<ChannelRedirectIface>;\n // Requests without an explicit credential are unauthenticated.\n fetch(input: RequestInfo | URL, init?: ChannelCredentialRequestInitIface): Promise<Response>;\n connect(args: ChannelCredentialConnectOptionsIface): Promise<ChannelCredentialSocketIface>;\n // The value of an app secret slot the channel declares in `require.app.secrets`; null for any\n // other slot.\n secret(slot: string): Promise<string | null>;\n}\nexport interface ChannelPostArgsIface {\n from: PersonHandle;\n content: ContentBlock[];\n context?: string[];\n origin: OriginIface;\n idempotencyKey: string;\n waitForAcceptance?: boolean;\n}\nexport interface ChannelConversationIface {\n post(args: ChannelPostArgsIface): Promise<{ messageId: string; turnId?: string } | Refusal>;\n input(args: {\n label: string;\n principal?: PrincipalRef;\n // The linked person the agent's turn acts for; with nobody, the input waits for the\n // running turn.\n actingAs?: PersonHandle;\n // False when the agent should reply only if it has something to say. Default true.\n replyExpected?: boolean;\n content: ContentBlock[];\n context?: string[];\n origin: OriginIface;\n idempotencyKey: string;\n waitForAcceptance?: boolean;\n }): Promise<{ inputId: string; turnId?: string } | Refusal>;\n attach(args: {\n origin: OriginIface;\n content: ContentBlock[];\n label: string;\n idempotencyKey: string;\n from?: PersonHandle;\n }): Promise<{ messageId: string } | Refusal>;\n edit(args: {\n externalKey: string;\n by: PersonHandle;\n content: ContentBlock[];\n }): Promise<{ messageId: string } | Refusal>;\n remove(args: { externalKey: string; by: PersonHandle }): Promise<{ removed: boolean } | Refusal>;\n react(args: {\n target: { externalKey: string } | { replyOf: { externalKey: string; turnId: string } };\n emoji: string;\n by: PersonHandle;\n op: 'add' | 'remove';\n }): Promise<{ ok: true } | Refusal>;\n}\nexport type SemanticEvent = {\n [Kind in keyof ChannelSemanticDataByKindIface]: {\n type: Kind;\n data: ChannelSemanticDataByKindIface[Kind];\n seq: number;\n };\n}[keyof ChannelSemanticDataByKindIface];\nexport interface ChannelReceiveContextIface<Config = JsonObject> {\n binding: {\n id: string;\n url: string;\n // The project the install belongs to.\n projectId: string;\n };\n config: Config;\n credentials: ChannelCredentialsIface;\n people: {\n resolve(principal: PrincipalRef): Promise<PersonResolution>;\n identify(person: PersonHandle): Promise<PrincipalRef | null>;\n // Tenant-wide uninstall/revocation also disconnects that tenant's places.\n revoke(args: {\n principal?: PrincipalRef;\n tenant?: string;\n reason: 'deactivated' | 'uninstalled' | 'provider-revoked';\n }): Promise<void>;\n confirm(args: { ticket: string; principal: PrincipalRef }): Promise<{ linked: true } | Refusal>;\n };\n places: {\n // Explicit anyone/group defaults may create a Shared chat while resolving a new place.\n resolve(place: PlaceRef): Promise<PlaceResolution>;\n observers(place: PlaceRef): Promise<ConversationHandle[]>;\n connect(\n place: PlaceRef,\n to: {\n by: PersonHandle;\n conversation?: ConversationHandle;\n create?: ChannelCreate | `${ChannelCreate}`;\n },\n ): Promise<ConversationHandle>;\n disconnect(place: PlaceRef, by: PersonHandle): Promise<void>;\n follow(\n place: PlaceRef,\n args: { by: PersonHandle; conversation: ConversationHandle; ttlSeconds?: number },\n ): Promise<void>;\n unfollow(\n place: PlaceRef,\n args: { by: PersonHandle; conversation: ConversationHandle },\n ): Promise<void>;\n };\n conversation(handle: ConversationHandle): ChannelConversationIface;\n observe(\n handle: ConversationHandle,\n args: { turnId: string; signal?: AbortSignal },\n ): AsyncIterable<SemanticEvent>;\n decisions: {\n resolve(args: {\n decisionId: string;\n outcome: JsonValue;\n by: PersonHandle;\n }): Promise<{ resolved: boolean } | Refusal>;\n };\n turns: {\n cancel(args: {\n conversation: ConversationHandle;\n by?: PersonHandle;\n turnId?: string;\n }): Promise<{ accepted: boolean } | Refusal>;\n };\n store: {\n get(key: string): Promise<JsonValue | null>;\n set(key: string, value: JsonValue | null, options?: { ttlSeconds?: number }): Promise<void>;\n };\n log(message: string, details?: JsonObject): void;\n}\nexport interface ChannelSocketIface {\n readonly signal: AbortSignal;\n readonly messages: AsyncIterable<string | Uint8Array>;\n // Authenticate the request before accepting. The selected protocol must have been offered.\n accept(options?: { protocol?: string }): void;\n send(data: string | Uint8Array): void;\n close(code?: number, reason?: string): void;\n}\n// State starts null and persists for the callbacks of one turn.\nexport interface ChannelTurnStateIface<State> {\n get(): State | null;\n set(state: State | null): void;\n}\nexport interface ChannelEventContextIface<Config = JsonObject, State = JsonValue> extends Pick<\n ChannelReceiveContextIface<Config>,\n 'binding' | 'config' | 'credentials' | 'store' | 'log'\n> {\n origin: OriginIface;\n conversation: ConversationHandle;\n turn: { id: string; agent: { displayName: string } };\n state: ChannelTurnStateIface<State>;\n}\nexport interface ChannelRouteContextIface<\n Config = JsonObject,\n> extends ChannelReceiveContextIface<Config> {\n request: Request;\n receive(input: JsonValue): Promise<ChannelReceiveResult>;\n}\nexport interface HttpChannelRouteDefinitionIface<Config = JsonObject> {\n method: 'GET' | 'POST' | 'PUT' | 'DELETE';\n path: string;\n // Served only for a provider returning with `credentials.redirect` state.\n redirect?: boolean;\n // Also served at the app's shared ingress URL, for the binding `ingress.tenantOf` picks.\n shared?: boolean;\n handler(args: ChannelRouteContextIface<Config>): Promise<Response>;\n}\nexport interface WebSocketChannelRouteDefinitionIface<Config = JsonObject> {\n method: 'WS';\n path: string;\n handler(\n args: ChannelRouteContextIface<Config> & { socket: ChannelSocketIface },\n ): Promise<Response | void>;\n}\nexport type RouteDefinitionIface<Config = JsonObject> =\n | HttpChannelRouteDefinitionIface<Config>\n | WebSocketChannelRouteDefinitionIface<Config>;\nexport type ChannelEventHandlersIface<Config, State> = {\n [Kind in keyof ChannelSemanticDataByKindIface]?: (\n data: ChannelSemanticDataByKindIface[Kind],\n ctx: ChannelEventContextIface<Config, State>,\n ) => Promise<void>;\n};\nexport type ChannelEventKind = keyof ChannelSemanticDataByKindIface;\n\n// Provider application credentials the channel needs, satisfied by a channel app: the install's\n// own, or the one the channel's publisher attached.\nexport interface ChannelAppRequirementIface {\n description: string;\n oauthClient?: { description: string; optional?: boolean };\n // Secret slots, by name (a signing secret, an app-level token).\n secrets?: Record<string, { description: string; optional?: boolean }>;\n}\nexport interface ChannelRequireIface {\n app?: ChannelAppRequirementIface;\n}\nexport interface ChannelIngressContextIface {\n app: { id: string };\n credentials: Pick<ChannelCredentialsIface, 'verify' | 'secret' | 'client'>;\n log(message: string, details?: JsonObject): void;\n}\nexport interface ChannelIngressIface {\n // Reads which provider tenant a request to the app's shared ingress URL is for, after verifying\n // it. `respond` answers an app-level request (a URL handshake) with no binding; null rejects it.\n tenantOf(\n request: Request,\n ctx: ChannelIngressContextIface,\n ): Promise<{ tenant: string } | { respond: Response } | null>;\n}\nexport interface ChannelDefinitionIface<\n Config = JsonObject,\n Inbound = JsonValue,\n State = JsonValue,\n> {\n name: string;\n config?: Config;\n configure?(config: Config): ChannelDefinitionIface<Config, Inbound, State>;\n require?: ChannelRequireIface;\n // A GET route that starts the provider's app install for a tenant; it receives `ticket`.\n tenants?: { installPath: string };\n // Present on the publication an app routes its shared ingress through.\n ingress?: ChannelIngressIface;\n identity:\n | {\n kind: 'redirect';\n start(\n args: { ticket: string; principal: PrincipalRef },\n ctx: ChannelReceiveContextIface<Config>,\n ): Promise<URL>;\n }\n | {\n kind: 'challenge';\n deliver(\n args: { principal: PrincipalRef; code: string },\n ctx: ChannelReceiveContextIface<Config>,\n ): Promise<void>;\n }\n | { kind: 'none' };\n places: { kinds: readonly string[]; defaults?(place: PlaceRef): PlaceDefaultsIface | null };\n resources?: {\n authorize(\n args: { place: PlaceRef; principal: PrincipalRef },\n ctx: ChannelReceiveContextIface<Config>,\n ): Promise<boolean>;\n resolve(\n args: { url: string; principal: PrincipalRef },\n ctx: ChannelReceiveContextIface<Config>,\n ): Promise<PlaceRef | null>;\n };\n routes?: RouteDefinitionIface<Config>[];\n listeners?: {\n key: string;\n run(ctx: ChannelReceiveContextIface<Config> & { signal: AbortSignal }): Promise<void>;\n }[];\n receive(input: Inbound, ctx: ChannelReceiveContextIface<Config>): Promise<ChannelReceiveResult>;\n events?: ChannelEventHandlersIface<Config, State>;\n}\nexport const defineChannel = <Config = JsonObject, Inbound = JsonValue, State = JsonValue>(\n definition: ChannelDefinitionIface<Config, Inbound, State>,\n): ChannelDefinitionIface<Config, Inbound, State> => definition;\n"],
|
|
5
|
-
"mappings": "AACA,YAAY,OAAO;AACnB,SAAS,wBAAyD;AAI3D,MAAM,qBAAqB,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,MAAuB;AACpE,MAAM,2BAA2B,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,MAA6B;AAIhF,MAAM,qBAAqB,EAAE,OAAO;AAAA,EACzC,IAAI,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EACpB,QAAQ,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS;AAAA,EACnC,aAAa,EAAE,OAAO,EAAE,SAAS;AACnC,CAAC;AASM,MAAM,iBAAsC,EAAE;AAAA,EAAK,MACxD,EAAE,OAAO;AAAA,IACP,MAAM,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,IACtB,IAAI,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,IACpB,QAAQ,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS;AAAA,IACnC,QAAQ,eAAe,SAAS;AAAA,IAChC,OAAO,EAAE,OAAO,EAAE,SAAS;AAAA,EAC7B,CAAC;AACH;AAKO,MAAM,eAAe,EAAE,OAAO,EAAE,OAAO,gBAAgB,KAAK,iBAAiB,SAAS,EAAE,CAAC;AAQzF,IAAK,iBAAL,kBAAKA,oBAAL;AACL,EAAAA,gBAAA,YAAS;AACT,EAAAA,gBAAA,SAAM;AAFI,SAAAA;AAAA,GAAA;AAIL,IAAK,kBAAL,kBAAKC,qBAAL;AACL,EAAAA,iBAAA,aAAU;AACV,EAAAA,iBAAA,YAAS;AAFC,SAAAA;AAAA,GAAA;AAIL,IAAK,gBAAL,kBAAKC,mBAAL;AACL,EAAAA,eAAA,qBAAkB;AAClB,EAAAA,eAAA,WAAQ;AAFE,SAAAA;AAAA,GAAA;AAIL,MAAM,oBAAoB,EAAE,OAAO;AAAA,EACxC,SAAS,EAAE,WAAW,cAAc;AAAA,EACpC,UAAU,EAAE,WAAW,eAAe;AACxC,CAAC;
|
|
6
|
-
"names": ["ChannelReplies", "ChannelAudience", "ChannelCreate", "ChannelCredentialKind", "ChannelSigningAlgorithm", "ChannelSignatureEncoding", "ChannelOAuthClientAuthentication"]
|
|
4
|
+
"sourcesContent": ["import type { ContentBlock } from '@agentclientprotocol/sdk/experimental/v2/unstable';\nimport * as z from 'zod';\nimport { jsonObjectSchema, type JsonObject, type JsonValue } from \"./json.mjs\";\nimport type { ChannelSemanticDataByKindIface } from \"./semantic-events.mjs\";\n\n// Handles carry no authority until the platform validates their binding and invocation signature.\nexport const personHandleSchema = z.string().min(1).brand<'ChannelPerson'>();\nexport const conversationHandleSchema = z.string().min(1).brand<'ChannelConversation'>();\nexport type PersonHandle = z.infer<typeof personHandleSchema>;\nexport type ConversationHandle = z.infer<typeof conversationHandleSchema>;\n\nexport const principalRefSchema = z.object({\n id: z.string().min(1),\n tenant: z.string().min(1).optional(),\n displayName: z.string().optional(),\n});\nexport type PrincipalRef = z.infer<typeof principalRefSchema>;\nexport interface PlaceRef {\n kind: string;\n id: string;\n tenant?: string;\n parent?: PlaceRef;\n title?: string;\n}\nexport const placeRefSchema: z.ZodType<PlaceRef> = z.lazy(() =>\n z.object({\n kind: z.string().min(1),\n id: z.string().min(1),\n tenant: z.string().min(1).optional(),\n parent: placeRefSchema.optional(),\n title: z.string().optional(),\n }),\n);\nexport interface OriginIface {\n place: PlaceRef;\n ref?: JsonObject;\n}\nexport const originSchema = z.object({ place: placeRefSchema, ref: jsonObjectSchema.optional() });\n\nexport type PersonResolution =\n | { kind: 'member'; person: PersonHandle; displayName: string }\n // `linkUrl` is the installer's link page for this person, when the install has one; without\n // it, the channel tells the person how to link in its own words.\n | { kind: 'unlinked'; linkUrl?: string }\n | { kind: 'blocked'; reason: 'not-a-member' | 'suspended' };\nexport enum ChannelReplies {\n Origin = 'origin',\n All = 'all',\n}\nexport enum ChannelAudience {\n Members = 'members',\n Anyone = 'anyone',\n}\nexport enum ChannelCreate {\n DirectWithAgent = 'direct-with-agent',\n Group = 'group',\n}\nexport const placePolicySchema = z.object({\n replies: z.nativeEnum(ChannelReplies),\n audience: z.nativeEnum(ChannelAudience),\n});\nexport interface PlacePolicy {\n replies: ChannelReplies | `${ChannelReplies}`;\n audience: ChannelAudience | `${ChannelAudience}`;\n}\n// Where a place's child places (threads inside a channel) talk: in the place's conversation, or\n// each in its own conversation, grouped under the place.\nexport enum ChannelChildPlaces {\n Parent = 'parent',\n Own = 'own',\n}\nexport interface PlaceDefaultsIface extends PlacePolicy {\n create: ChannelCreate | `${ChannelCreate}`;\n // Absent: `parent`.\n childPlaces?: ChannelChildPlaces | `${ChannelChildPlaces}`;\n}\nexport type PlaceResolution =\n | { kind: 'connected'; conversation: ConversationHandle; policy: PlacePolicy }\n // `connectUrl` is the installer's connect page for this place, when the install has one.\n | { kind: 'unconnected'; connectUrl?: string; defaults: PlaceDefaultsIface | null };\nexport interface Refusal {\n refused: 'unlinked' | 'no-access' | 'unconnected' | 'not-audience';\n linkUrl?: string;\n connectUrl?: string;\n message: string;\n}\nexport type ChannelReceiveResult =\n | { accepted: true }\n | { accepted: false; refusal: Refusal }\n | { ignored: true; reason: string };\nexport const refusalSchema = z.object({\n refused: z.union([\n z.literal('unlinked'),\n z.literal('no-access'),\n z.literal('unconnected'),\n z.literal('not-audience'),\n ]),\n linkUrl: z.string().optional(),\n connectUrl: z.string().optional(),\n message: z.string(),\n});\nexport const channelReceiveResultSchema = z.union([\n z.object({ accepted: z.literal(true) }),\n z.object({ accepted: z.literal(false), refusal: refusalSchema }),\n z.object({ ignored: z.literal(true), reason: z.string() }),\n]);\nexport enum ChannelCredentialKind {\n // A provider tenant's token, stored when the tenant installed the channel's app.\n App = 'app',\n // A secret slot of the channel's app, injected without the channel reading it.\n Secret = 'secret',\n OAuth = 'oauth',\n None = 'none',\n}\nexport const channelCredentialHandleSchema = z.string().min(1).brand<'ChannelCredential'>();\nexport type ChannelCredentialHandle = z.infer<typeof channelCredentialHandleSchema>;\nexport type ChannelCredentialRef =\n | { kind: ChannelCredentialKind.App; tenant: string }\n // `scheme` is the Authorization scheme the secret is sent with (`Bearer` when omitted). Frame\n // injection writes the bare value.\n | { kind: ChannelCredentialKind.Secret; slot: string; scheme?: string }\n | { kind: ChannelCredentialKind.OAuth; handle: ChannelCredentialHandle }\n | { kind: ChannelCredentialKind.None };\nexport enum ChannelSigningAlgorithm {\n HmacSha256 = 'hmac-sha256',\n HmacSha1 = 'hmac-sha1',\n Ed25519 = 'ed25519',\n}\nexport enum ChannelSignatureEncoding {\n Hex = 'hex',\n Base64 = 'base64',\n}\nexport enum ChannelOAuthClientAuthentication {\n Body = 'body',\n Basic = 'basic',\n None = 'none',\n}\nexport interface ChannelCredentialRequestInitIface extends RequestInit {\n credential?: ChannelCredentialRef;\n}\nexport interface ChannelVerifyOptionsIface {\n // The app secret slot holding the signing secret or public key; its value is never read.\n secret: string;\n algorithm: ChannelSigningAlgorithm;\n encoding: ChannelSignatureEncoding;\n data: string;\n signature: string;\n}\nexport interface ChannelOAuthExchangeOptionsIface {\n url: string;\n parameters: Record<string, string>;\n authentication: ChannelOAuthClientAuthentication;\n clientId?: string;\n signal?: AbortSignal;\n // Stores the token as this provider tenant's install of the channel's app. Honoured only in a\n // redirect route whose state carries an unused tenant-install ticket for this binding. A\n // provider that names the tenant only in its token response is read at `tenantPath` there.\n store?: { tenant: string } | { tenantPath: string[] };\n}\nexport interface ChannelRedirectOptionsIface {\n // A GET route of this channel declared with `redirect: true`.\n path: string;\n // A tenant-install ticket the install route received; it is bound into the signed state.\n ticket?: string;\n}\nexport interface ChannelRedirectIface {\n url: string;\n state: string;\n}\nexport interface ChannelCredentialConnectOptionsIface {\n url: string;\n signal?: AbortSignal;\n}\nexport interface ChannelCredentialInjectionIface {\n path: string[];\n credential: ChannelCredentialRef;\n}\nexport interface ChannelCredentialSocketIface {\n messages: AsyncIterable<string | Uint8Array>;\n send(\n data: string | Uint8Array,\n options?: { inject?: ChannelCredentialInjectionIface[] },\n ): Promise<void>;\n close(code?: number, reason?: string): Promise<void>;\n closeCode(): number | null;\n}\nexport interface ChannelCredentialsIface {\n // The channel app's credentials stay with the host in every execution mode.\n client(): Promise<{ clientId: string }>;\n verify(args: ChannelVerifyOptionsIface): Promise<boolean>;\n exchange(args: ChannelOAuthExchangeOptionsIface): Promise<ChannelCredentialHandle>;\n // Send `url` as the OAuth redirect URI and `state` unchanged. `url` is the same for every\n // binding, so a provider application registers it once; `state` returns to this binding.\n redirect(args: ChannelRedirectOptionsIface): Promise<ChannelRedirectIface>;\n // Requests without an explicit credential are unauthenticated.\n fetch(input: RequestInfo | URL, init?: ChannelCredentialRequestInitIface): Promise<Response>;\n connect(args: ChannelCredentialConnectOptionsIface): Promise<ChannelCredentialSocketIface>;\n // The value of an app secret slot the channel declares in `require.app.secrets`; null for any\n // other slot.\n secret(slot: string): Promise<string | null>;\n}\nexport interface ChannelPostArgsIface {\n from: PersonHandle;\n content: ContentBlock[];\n context?: string[];\n origin: OriginIface;\n idempotencyKey: string;\n waitForAcceptance?: boolean;\n}\nexport interface ChannelConversationIface {\n post(args: ChannelPostArgsIface): Promise<{ messageId: string; turnId?: string } | Refusal>;\n input(args: {\n label: string;\n principal?: PrincipalRef;\n // The linked person the agent's turn acts for; with nobody, the input waits for the\n // running turn.\n actingAs?: PersonHandle;\n // False when the agent should reply only if it has something to say. Default true.\n replyExpected?: boolean;\n content: ContentBlock[];\n context?: string[];\n origin: OriginIface;\n idempotencyKey: string;\n waitForAcceptance?: boolean;\n }): Promise<{ inputId: string; turnId?: string } | Refusal>;\n attach(args: {\n origin: OriginIface;\n content: ContentBlock[];\n label: string;\n idempotencyKey: string;\n from?: PersonHandle;\n }): Promise<{ messageId: string } | Refusal>;\n edit(args: {\n externalKey: string;\n by: PersonHandle;\n content: ContentBlock[];\n }): Promise<{ messageId: string } | Refusal>;\n remove(args: { externalKey: string; by: PersonHandle }): Promise<{ removed: boolean } | Refusal>;\n react(args: {\n target: { externalKey: string } | { replyOf: { externalKey: string; turnId: string } };\n emoji: string;\n by: PersonHandle;\n op: 'add' | 'remove';\n }): Promise<{ ok: true } | Refusal>;\n}\nexport type SemanticEvent = {\n [Kind in keyof ChannelSemanticDataByKindIface]: {\n type: Kind;\n data: ChannelSemanticDataByKindIface[Kind];\n seq: number;\n };\n}[keyof ChannelSemanticDataByKindIface];\nexport interface ChannelReceiveContextIface<Config = JsonObject> {\n binding: {\n id: string;\n url: string;\n // The project the install belongs to.\n projectId: string;\n };\n config: Config;\n credentials: ChannelCredentialsIface;\n people: {\n resolve(principal: PrincipalRef): Promise<PersonResolution>;\n identify(person: PersonHandle): Promise<PrincipalRef | null>;\n // Tenant-wide uninstall/revocation also disconnects that tenant's places.\n revoke(args: {\n principal?: PrincipalRef;\n tenant?: string;\n reason: 'deactivated' | 'uninstalled' | 'provider-revoked';\n }): Promise<void>;\n confirm(args: { ticket: string; principal: PrincipalRef }): Promise<{ linked: true } | Refusal>;\n };\n places: {\n // Explicit anyone/group defaults may create a Shared chat while resolving a new place.\n resolve(place: PlaceRef): Promise<PlaceResolution>;\n observers(place: PlaceRef): Promise<ConversationHandle[]>;\n connect(\n place: PlaceRef,\n to: {\n by: PersonHandle;\n conversation?: ConversationHandle;\n create?: ChannelCreate | `${ChannelCreate}`;\n },\n ): Promise<ConversationHandle>;\n disconnect(place: PlaceRef, by: PersonHandle): Promise<void>;\n follow(\n place: PlaceRef,\n args: { by: PersonHandle; conversation: ConversationHandle; ttlSeconds?: number },\n ): Promise<void>;\n unfollow(\n place: PlaceRef,\n args: { by: PersonHandle; conversation: ConversationHandle },\n ): Promise<void>;\n };\n conversation(handle: ConversationHandle): ChannelConversationIface;\n observe(\n handle: ConversationHandle,\n args: { turnId: string; signal?: AbortSignal },\n ): AsyncIterable<SemanticEvent>;\n decisions: {\n resolve(args: {\n decisionId: string;\n outcome: JsonValue;\n by: PersonHandle;\n }): Promise<{ resolved: boolean } | Refusal>;\n };\n turns: {\n cancel(args: {\n conversation: ConversationHandle;\n by?: PersonHandle;\n turnId?: string;\n }): Promise<{ accepted: boolean } | Refusal>;\n };\n store: {\n get(key: string): Promise<JsonValue | null>;\n set(key: string, value: JsonValue | null, options?: { ttlSeconds?: number }): Promise<void>;\n };\n log(message: string, details?: JsonObject): void;\n}\nexport interface ChannelSocketIface {\n readonly signal: AbortSignal;\n readonly messages: AsyncIterable<string | Uint8Array>;\n // Authenticate the request before accepting. The selected protocol must have been offered.\n accept(options?: { protocol?: string }): void;\n send(data: string | Uint8Array): void;\n close(code?: number, reason?: string): void;\n}\n// State starts null and persists for the callbacks of one turn.\nexport interface ChannelTurnStateIface<State> {\n get(): State | null;\n set(state: State | null): void;\n}\nexport interface ChannelEventContextIface<Config = JsonObject, State = JsonValue> extends Pick<\n ChannelReceiveContextIface<Config>,\n 'binding' | 'config' | 'credentials' | 'store' | 'log'\n> {\n origin: OriginIface;\n conversation: ConversationHandle;\n turn: { id: string; agent: { displayName: string } };\n state: ChannelTurnStateIface<State>;\n}\nexport interface ChannelRouteContextIface<\n Config = JsonObject,\n> extends ChannelReceiveContextIface<Config> {\n request: Request;\n receive(input: JsonValue): Promise<ChannelReceiveResult>;\n}\nexport interface HttpChannelRouteDefinitionIface<Config = JsonObject> {\n method: 'GET' | 'POST' | 'PUT' | 'DELETE';\n path: string;\n // Served only for a provider returning with `credentials.redirect` state.\n redirect?: boolean;\n // Also served at the app's shared ingress URL, for the binding `ingress.tenantOf` picks.\n shared?: boolean;\n handler(args: ChannelRouteContextIface<Config>): Promise<Response>;\n}\nexport interface WebSocketChannelRouteDefinitionIface<Config = JsonObject> {\n method: 'WS';\n path: string;\n handler(\n args: ChannelRouteContextIface<Config> & { socket: ChannelSocketIface },\n ): Promise<Response | void>;\n}\nexport type RouteDefinitionIface<Config = JsonObject> =\n | HttpChannelRouteDefinitionIface<Config>\n | WebSocketChannelRouteDefinitionIface<Config>;\nexport type ChannelEventHandlersIface<Config, State> = {\n [Kind in keyof ChannelSemanticDataByKindIface]?: (\n data: ChannelSemanticDataByKindIface[Kind],\n ctx: ChannelEventContextIface<Config, State>,\n ) => Promise<void>;\n};\nexport type ChannelEventKind = keyof ChannelSemanticDataByKindIface;\n\n// Provider application credentials the channel needs, satisfied by a channel app: the install's\n// own, or the one the channel's publisher attached.\nexport interface ChannelAppRequirementIface {\n description: string;\n oauthClient?: { description: string; optional?: boolean };\n // Secret slots, by name (a signing secret, an app-level token).\n secrets?: Record<string, { description: string; optional?: boolean }>;\n}\nexport interface ChannelRequireIface {\n app?: ChannelAppRequirementIface;\n}\nexport interface ChannelIngressContextIface {\n app: { id: string };\n credentials: Pick<ChannelCredentialsIface, 'verify' | 'secret' | 'client'>;\n log(message: string, details?: JsonObject): void;\n}\nexport interface ChannelIngressIface {\n // Reads which provider tenant a request to the app's shared ingress URL is for, after verifying\n // it. `respond` answers an app-level request (a URL handshake) with no binding; null rejects it.\n tenantOf(\n request: Request,\n ctx: ChannelIngressContextIface,\n ): Promise<{ tenant: string } | { respond: Response } | null>;\n}\nexport interface ChannelDefinitionIface<\n Config = JsonObject,\n Inbound = JsonValue,\n State = JsonValue,\n> {\n name: string;\n config?: Config;\n configure?(config: Config): ChannelDefinitionIface<Config, Inbound, State>;\n require?: ChannelRequireIface;\n // A GET route that starts the provider's app install for a tenant; it receives `ticket`.\n tenants?: { installPath: string };\n // Present on the publication an app routes its shared ingress through.\n ingress?: ChannelIngressIface;\n identity:\n | {\n kind: 'redirect';\n start(\n args: { ticket: string; principal: PrincipalRef },\n ctx: ChannelReceiveContextIface<Config>,\n ): Promise<URL>;\n }\n | {\n kind: 'challenge';\n deliver(\n args: { principal: PrincipalRef; code: string },\n ctx: ChannelReceiveContextIface<Config>,\n ): Promise<void>;\n }\n | { kind: 'none' };\n places: { kinds: readonly string[]; defaults?(place: PlaceRef): PlaceDefaultsIface | null };\n resources?: {\n authorize(\n args: { place: PlaceRef; principal: PrincipalRef },\n ctx: ChannelReceiveContextIface<Config>,\n ): Promise<boolean>;\n resolve(\n args: { url: string; principal: PrincipalRef },\n ctx: ChannelReceiveContextIface<Config>,\n ): Promise<PlaceRef | null>;\n };\n routes?: RouteDefinitionIface<Config>[];\n listeners?: {\n key: string;\n run(ctx: ChannelReceiveContextIface<Config> & { signal: AbortSignal }): Promise<void>;\n }[];\n receive(input: Inbound, ctx: ChannelReceiveContextIface<Config>): Promise<ChannelReceiveResult>;\n events?: ChannelEventHandlersIface<Config, State>;\n}\nexport const defineChannel = <Config = JsonObject, Inbound = JsonValue, State = JsonValue>(\n definition: ChannelDefinitionIface<Config, Inbound, State>,\n): ChannelDefinitionIface<Config, Inbound, State> => definition;\n"],
|
|
5
|
+
"mappings": "AACA,YAAY,OAAO;AACnB,SAAS,wBAAyD;AAI3D,MAAM,qBAAqB,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,MAAuB;AACpE,MAAM,2BAA2B,EAAE,OAAO,EAAE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ChannelReplies", "ChannelAudience", "ChannelCreate", "ChannelChildPlaces", "ChannelCredentialKind", "ChannelSigningAlgorithm", "ChannelSignatureEncoding", "ChannelOAuthClientAuthentication"]
|
|
7
7
|
}
|
|
@@ -337,6 +337,20 @@ const remoteSandboxProvider = (args) => {
|
|
|
337
337
|
const { client } = await attachSocket(ctx, { ...attach, passive: true });
|
|
338
338
|
return handleOf(client, client);
|
|
339
339
|
};
|
|
340
|
+
if (registration.features.fork)
|
|
341
|
+
result.fork = async (ctx, fork) => call({
|
|
342
|
+
path: SandboxProviderWirePath.Fork,
|
|
343
|
+
ctx,
|
|
344
|
+
sandboxId: ctx.sandboxId,
|
|
345
|
+
fields: {
|
|
346
|
+
sandboxId: ctx.sandboxId,
|
|
347
|
+
artifact: fork.artifact,
|
|
348
|
+
source: { sandboxId: fork.source.sandboxId, state: fork.source.state },
|
|
349
|
+
platformEgressHosts: ctx.platformEgressHosts ?? [],
|
|
350
|
+
lifecycle: { parkAfterIdleMs: ctx.lifecycle.parkAfterIdleMs }
|
|
351
|
+
},
|
|
352
|
+
result: createResultSchema
|
|
353
|
+
});
|
|
340
354
|
if (registration.features.readThumbnail)
|
|
341
355
|
result.readThumbnail = async (ctx, state) => call({
|
|
342
356
|
path: SandboxProviderWirePath.ReadThumbnail,
|
|
@@ -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 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 { sandboxPortPreviewResultSchema } from \"../port-preview.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 if (registration.features.portPreview)\n result.portPreview = async (ctx, state, request) =>\n call({\n path: SandboxProviderWirePath.PortPreview,\n ctx,\n sandboxId: requireSandboxId(ctx),\n fields: {\n sandboxId: requireSandboxId(ctx),\n state,\n request: jsonValueSchema.parse(request),\n },\n result: sandboxPortPreviewResultSchema,\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,EAC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AAA,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 { sandboxPortPreviewResultSchema } from \"../port-preview.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.fork)\n result.fork = async (ctx, fork) =>\n call({\n path: SandboxProviderWirePath.Fork,\n ctx,\n sandboxId: ctx.sandboxId,\n fields: {\n sandboxId: ctx.sandboxId,\n artifact: fork.artifact,\n source: { sandboxId: fork.source.sandboxId, state: fork.source.state },\n platformEgressHosts: ctx.platformEgressHosts ?? [],\n lifecycle: { parkAfterIdleMs: ctx.lifecycle.parkAfterIdleMs },\n },\n result: createResultSchema,\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 if (registration.features.portPreview)\n result.portPreview = async (ctx, state, request) =>\n call({\n path: SandboxProviderWirePath.PortPreview,\n ctx,\n sandboxId: requireSandboxId(ctx),\n fields: {\n sandboxId: requireSandboxId(ctx),\n state,\n request: jsonValueSchema.parse(request),\n },\n result: sandboxPortPreviewResultSchema,\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,sCAAsC;AAC/C,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;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AwB,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
|
}
|
|
@@ -17,6 +17,7 @@ import {
|
|
|
17
17
|
sandboxAwaitRunningRequestSchema,
|
|
18
18
|
sandboxCreateRequestSchema,
|
|
19
19
|
sandboxEditorRequestSchema,
|
|
20
|
+
sandboxForkRequestSchema,
|
|
20
21
|
sandboxOfferRequestSchema,
|
|
21
22
|
sandboxParkRequestSchema,
|
|
22
23
|
sandboxPortPreviewRequestSchema,
|
|
@@ -67,6 +68,7 @@ const invalid = (message) => ({
|
|
|
67
68
|
const LONG_CALLS = /* @__PURE__ */ new Set([
|
|
68
69
|
SandboxProviderWirePath.Prepare,
|
|
69
70
|
SandboxProviderWirePath.Create,
|
|
71
|
+
SandboxProviderWirePath.Fork,
|
|
70
72
|
SandboxProviderWirePath.AwaitRunning
|
|
71
73
|
]);
|
|
72
74
|
const featuresOf = (implementation) => ({
|
|
@@ -75,7 +77,8 @@ const featuresOf = (implementation) => ({
|
|
|
75
77
|
processes: implementation?.processes != null,
|
|
76
78
|
editor: implementation?.editor != null,
|
|
77
79
|
portPreview: implementation?.portPreview != null,
|
|
78
|
-
attachPassive: implementation?.attachPassive != null
|
|
80
|
+
attachPassive: implementation?.attachPassive != null,
|
|
81
|
+
fork: implementation?.fork != null
|
|
79
82
|
});
|
|
80
83
|
const serveSandboxProvider = (args) => {
|
|
81
84
|
const now = args.now ?? Date.now;
|
|
@@ -284,6 +287,25 @@ const serveSandboxProvider = (args) => {
|
|
|
284
287
|
);
|
|
285
288
|
return { state: created.state, region: created.region ?? null };
|
|
286
289
|
}
|
|
290
|
+
case SandboxProviderWirePath.Fork: {
|
|
291
|
+
const request = parse(sandboxForkRequestSchema, body);
|
|
292
|
+
requireSandbox(identity, request.sandboxId);
|
|
293
|
+
const implementation = implementationOf(mount, request.environment);
|
|
294
|
+
if (implementation.fork == null) throw unsupported("fork");
|
|
295
|
+
const forked = await implementation.fork(
|
|
296
|
+
resourceContext({
|
|
297
|
+
sandboxId: request.sandboxId,
|
|
298
|
+
secrets: request.secrets,
|
|
299
|
+
platformEgressHosts: request.platformEgressHosts,
|
|
300
|
+
lifecycle: request.lifecycle
|
|
301
|
+
}),
|
|
302
|
+
{
|
|
303
|
+
artifact: json(request.artifact),
|
|
304
|
+
source: { sandboxId: request.source.sandboxId, state: json(request.source.state) }
|
|
305
|
+
}
|
|
306
|
+
);
|
|
307
|
+
return { state: forked.state, region: forked.region ?? null };
|
|
308
|
+
}
|
|
287
309
|
case SandboxProviderWirePath.AwaitRunning: {
|
|
288
310
|
const request = parse(sandboxAwaitRunningRequestSchema, body);
|
|
289
311
|
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 sandboxPortPreviewRequestSchema,\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 { sandboxPortPreviewRequestSchema as portPreviewRequestSchema } from \"../port-preview.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 portPreview: implementation?.portPreview != 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 case SandboxProviderWirePath.PortPreview: {\n const request = parse(sandboxPortPreviewRequestSchema, body);\n requireSandbox(identity, request.sandboxId);\n const implementation = implementationOf(mount, request.environment);\n if (implementation.portPreview == null) throw unsupported('port preview');\n return {\n ...(await implementation.portPreview(\n { ...base(request.secrets), sandboxId: request.sandboxId },\n json(request.state),\n parse(portPreviewRequestSchema, 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,EACA;AAAA,OAOK;AACP,YAAY,OAAO;AACnB,SAAS,uBAAwD;AACjE,SAAS,8BAA8B,2BAA2B;AAClE,SAAS,mCAAmC,gCAAgC;AAC5E,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,UAAU,CAAC,aAAgD;AAAA,EAC/D,MAAM,yBAAyB;AAAA,EAC/B;AAAA,EACA,WAAW;AACb;AAEA,MAAM,UAAU,CAAC,aAAgD;AAAA,EAC/D,MAAM,yBAAyB;AAAA,EAC/B;AAAA,EACA,WAAW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tC,iBAAO;AAAA,QACT;AAAA,MACF;AAGA,YAAM,YAA+B,OAAO,EAAE,UAAU,UAAU,MAAM;AACtE,cAAM,OAAO,MAAM,OAAO,OAAO,aAAa,IAAI;AAClD,YACE,QAAQ,QACR,aAAa,QACb,KAAK,eAAe,SAAS,cAC7B,KAAK,cAAc,SAAS,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;",
|
|
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 sandboxForkRequestSchema,\n sandboxOfferRequestSchema,\n sandboxParkRequestSchema,\n sandboxPortPreviewRequestSchema,\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 { sandboxPortPreviewRequestSchema as portPreviewRequestSchema } from \"../port-preview.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.Fork,\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 portPreview: implementation?.portPreview != null,\n attachPassive: implementation?.attachPassive != null,\n fork: implementation?.fork != 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.Fork: {\n // The assertion names the new sandbox; the platform chose the source it copies.\n const request = parse(sandboxForkRequestSchema, body);\n requireSandbox(identity, request.sandboxId);\n const implementation = implementationOf(mount, request.environment);\n if (implementation.fork == null) throw unsupported('fork');\n const forked = await implementation.fork(\n resourceContext({\n sandboxId: request.sandboxId,\n secrets: request.secrets,\n platformEgressHosts: request.platformEgressHosts,\n lifecycle: request.lifecycle,\n }),\n {\n artifact: json(request.artifact),\n source: { sandboxId: request.source.sandboxId, state: json(request.source.state) },\n },\n );\n return { state: forked.state, region: forked.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 case SandboxProviderWirePath.PortPreview: {\n const request = parse(sandboxPortPreviewRequestSchema, body);\n requireSandbox(identity, request.sandboxId);\n const implementation = implementationOf(mount, request.environment);\n if (implementation.portPreview == null) throw unsupported('port preview');\n return {\n ...(await implementation.portPreview(\n { ...base(request.secrets), sandboxId: request.sandboxId },\n json(request.state),\n parse(portPreviewRequestSchema, 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,EACA;AAAA,EACA;AAAA,OAOK;AACP,YAAY,OAAO;AACnB,SAAS,uBAAwD;A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M,YAA6B;AAAA,QACjC,eAAe,MAAM,OAAO,cAAc;AAAA,QAC1C,iBAAiB,CAAC,YAAY,OAAO,gBAAgB,OAAO;AAAA,QAC5D,mBAAmB,MAAM;AACvB,uBAAa,OAAO,kBAAkB;AACtC,iBAAO;AAAA,QACT;AAAA,MACF;AAGA,YAAM,YAA+B,OAAO,EAAE,UAAU,UAAU,MAAM;AACtE,cAAM,OAAO,MAAM,OAAO,OAAO,aAAa,IAAI;AAClD,YACE,QAAQ,QACR,aAAa,QACb,KAAK,eAAe,SAAS,cAC7B,KAAK,cAAc,SAAS,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
|
}
|
|
@@ -346,6 +346,16 @@ export interface SandboxEnvironmentImplementationIface<Artifact extends JsonValu
|
|
|
346
346
|
state: State;
|
|
347
347
|
region?: string | null;
|
|
348
348
|
}>;
|
|
349
|
+
fork?(ctx: SandboxResourceContextIface, args: {
|
|
350
|
+
artifact: Artifact;
|
|
351
|
+
source: {
|
|
352
|
+
sandboxId: string;
|
|
353
|
+
state: State;
|
|
354
|
+
};
|
|
355
|
+
}): Promise<{
|
|
356
|
+
state: State;
|
|
357
|
+
region?: string | null;
|
|
358
|
+
}>;
|
|
349
359
|
awaitRunning(ctx: SandboxResourceContextIface, state: State, options: {
|
|
350
360
|
timeoutMs: number;
|
|
351
361
|
}): Promise<void>;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../src/sandbox/types.ts"],
|
|
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 { SandboxPortPreviewRequestIface, SandboxPortPreviewResultIface } from \"./port-preview.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 // Browser access to a web server on one port of an existing sandbox. The host decides\n // which ports may be previewed and who may see them; this hook never creates or wakes a\n // backend, and nothing reaches the port until a person opens it.\n portPreview?(\n ctx: SandboxOfferContextIface,\n state: State,\n request: SandboxPortPreviewRequestIface,\n ): Promise<SandboxPortPreviewResultIface>;\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;AACnB,SAAS,wBAAwB;AACjC,SAAS,oBAAAA,yBAAwB;AACjC,SAAS,2BAA6D;AACtE,SAAS,4BAA4B;AACrC,SAAS,qBAA8C;AACvD,SAAS,iBAAAC,sBAA8C;AAOvD;AAAA,EACE;AAAA,OAGK;AACP,SAAS,iCAAiC;AAK1C;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AAwDA,IAAK,iCAAL,kBAAKC,oCAAL;AACL,EAAAA,gCAAA,QAAK;AACL,EAAAA,gCAAA,UAAO;AACP,EAAAA,gCAAA,WAAQ;AAHE,SAAAA;AAAA,GAAA;AAwBL,MAAM,0BAA0B,CACrC,YAC0C,cAAc;AAqGnD,IAAK,eAAL,kBAAKC,kBAAL;AACL,EAAAA,cAAA,UAAO;AACP,EAAAA,cAAA,WAAQ;AACR,EAAAA,cAAA,QAAK;AAHK,SAAAA;AAAA,GAAA;AA2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AAO,CAAC,GAAI,OAAO,SAAS,CAAC,CAAE,EAAE,IACtD,EAAE,MAAM,OAAO,KAAK;AAC1B;AAIK,MAAM,0BAA0B,CACrC,KACA,WACuB;AACvB,QAAM,QAAQ,IAAI,uBAAuB,CAAC;AAC1C,MAAI,OAAO,SAAS,cAAc,aAAa,MAAM,WAAW,EAAG,QAAO;AAC1E,SAAO,EAAE,GAAG,QAAQ,OAAO,CAAC,GAAG,oBAAI,IAAI,CAAC,GAAI,OAAO,SAAS,CAAC,GAAI,GAAG,KAAK,CAAC,CAAC,EAAE;AAC/E;
|
|
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 { SandboxPortPreviewRequestIface, SandboxPortPreviewResultIface } from \"./port-preview.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 // Browser access to a web server on one port of an existing sandbox. The host decides\n // which ports may be previewed and who may see them; this hook never creates or wakes a\n // backend, and nothing reaches the port until a person opens it.\n portPreview?(\n ctx: SandboxOfferContextIface,\n state: State,\n request: SandboxPortPreviewRequestIface,\n ): Promise<SandboxPortPreviewResultIface>;\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 // Makes the backend resource of a new sandbox (`ctx.sandboxId`) whose disk starts as a copy of\n // `source`, a sandbox of this environment that has the same artifact. In place of `create`: the\n // copy keeps the source's network policy, and its first attach is not `fresh`. A retry with the\n // same `ctx.sandboxId` must return the sandbox the first call made, never a second copy. The\n // source keeps running unless the backend cannot fork without stopping it. Absent: sandboxes\n // of this environment cannot be forked.\n fork?(\n ctx: SandboxResourceContextIface,\n args: { artifact: Artifact; source: { sandboxId: string; state: State } },\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;AACnB,SAAS,wBAAwB;AACjC,SAAS,oBAAAA,yBAAwB;AACjC,SAAS,2BAA6D;AACtE,SAAS,4BAA4B;AACrC,SAAS,qBAA8C;AACvD,SAAS,iBAAAC,sBAA8C;AAOvD;AAAA,EACE;AAAA,OAGK;AACP,SAAS,iCAAiC;AAK1C;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AAwDA,IAAK,iCAAL,kBAAKC,oCAAL;AACL,EAAAA,gCAAA,QAAK;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,eAAe,UAAU,MAAM;AACjC,cAAM,SAAS,eAAe,OAAO,KAAK,cAAc;AACxD,kBAAU,SAAS,OAAO,KAAK,OAAO,YAAY;AAChD,cACE,QAAQ,cAAc,uBAAuB,QAC7C,QAAQ,cAAc,uBAAuB;AAE7C,kBAAM,IAAI,iBAAiB,gBAAgB;AAAA,cACzC,WAAW,0BAA0B;AAAA,cACrC,YAAY;AAAA,YACd,CAAC;AACH,iBAAO,OAAO,KAAK,OAAO,OAAO;AAAA,QACnC;AAAA,MACF;AACA,UAAI,eAAe,iBAAiB,MAAM;AACxC,cAAM,gBAAgB,eAAe,cAAc,KAAK,cAAc;AACtE,kBAAU,gBAAgB,OAAO,KAAK,SACpC,oBAAoB;AAAA,UAClB,QAAQ,MAAM,cAAc,KAAK,IAAI;AAAA,UACrC,iBAAiB,IAAI;AAAA,QACvB,CAAC;AAAA,MACL;AACA,aAAO,qBAAqB,gBAAgB,SAAS;AAAA,IACvD;AAAA,EACF,CAAC;AAAA,EACD,MAAM,WAAW;AAAA,EACjB,aAAa,CAAC,aAAa,EAAE,UAAU,WAAW,MAAM,aAAa,QAAQ;AAC/E;AAGO,MAAM,oBAAoB,OAC/B,aAIA,QAC2B;AAC3B,MAAI,YAAY,YAAY,KAAM,QAAO,YAAY,SAAS,GAAG;AACjE,QAAM,QAAQ,MAAM,YAAY,aAAa,GAAG;AAChD,SAAO,MAAM,WAAW,KAAK,KAAK,OAAO,CAAC,IAAI,CAAC,YAAY,OAAO;AACpE;AAWO,IAAK,mBAAL,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.21.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",
|
|
@@ -241,8 +241,8 @@
|
|
|
241
241
|
},
|
|
242
242
|
"dependencies": {
|
|
243
243
|
"@agentclientprotocol/sdk": "2.7.0",
|
|
244
|
-
"@finalai/acp-session": "0.10.
|
|
245
|
-
"@finalai/agent-protocol": "0.
|
|
244
|
+
"@finalai/acp-session": "0.10.4",
|
|
245
|
+
"@finalai/agent-protocol": "0.24.0",
|
|
246
246
|
"@modelcontextprotocol/client": "^2.1.0",
|
|
247
247
|
"@modelcontextprotocol/core": "^2.1.0",
|
|
248
248
|
"@modelcontextprotocol/server": "^2.4.0",
|