@finalai/agent-provider 0.10.0 → 0.11.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 +15 -8
- package/dist/modules/channel.d.mts +51 -12
- package/dist/modules/channel.mjs +1 -0
- package/dist/modules/channel.mjs.map +2 -2
- package/dist/modules/credential-routes.d.mts +1 -3
- package/dist/modules/credential-routes.mjs +0 -2
- package/dist/modules/credential-routes.mjs.map +2 -2
- package/dist/modules/document.d.mts +0 -18
- package/dist/modules/document.mjs +1 -16
- package/dist/modules/document.mjs.map +3 -3
- package/dist/modules/index.d.mts +0 -1
- package/dist/modules/index.mjs +0 -1
- package/dist/modules/index.mjs.map +2 -2
- package/dist/modules/local-channel-context.d.mts +1 -1
- package/dist/modules/local-channel-context.mjs +1 -1
- package/dist/modules/local-channel-context.mjs.map +2 -2
- package/dist/modules/sandbox/remote/body.d.mts +1 -0
- package/dist/modules/sandbox/remote/body.mjs +27 -0
- package/dist/modules/sandbox/remote/body.mjs.map +7 -0
- package/dist/modules/sandbox/remote/serve.mjs +3 -2
- package/dist/modules/sandbox/remote/serve.mjs.map +2 -2
- package/dist/modules/sandbox/setup/apply.d.mts +1 -2
- package/dist/modules/sandbox/setup/apply.mjs +6 -20
- package/dist/modules/sandbox/setup/apply.mjs.map +2 -2
- package/dist/modules/sandbox/setup/describe.mjs +1 -1
- package/dist/modules/sandbox/setup/describe.mjs.map +1 -1
- package/dist/modules/sandbox/setup/schema.d.mts +2 -1
- package/dist/modules/sandbox/types.d.mts +0 -12
- package/dist/modules/sandbox/types.mjs +1 -7
- package/dist/modules/sandbox/types.mjs.map +2 -2
- package/package.json +3 -8
- package/dist/modules/room-surface.d.mts +0 -350
- package/dist/modules/room-surface.mjs +0 -156
- package/dist/modules/room-surface.mjs.map +0 -7
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
const readBodyText = async (request, limit) => {
|
|
2
|
+
const reader = request.body?.getReader();
|
|
3
|
+
if (reader == null) return "";
|
|
4
|
+
const chunks = [];
|
|
5
|
+
let size = 0;
|
|
6
|
+
for (; ; ) {
|
|
7
|
+
const next = await reader.read();
|
|
8
|
+
if (next.done) break;
|
|
9
|
+
size += next.value.byteLength;
|
|
10
|
+
if (size > limit) {
|
|
11
|
+
await reader.cancel().catch(() => void 0);
|
|
12
|
+
return null;
|
|
13
|
+
}
|
|
14
|
+
chunks.push(next.value);
|
|
15
|
+
}
|
|
16
|
+
const bytes = new Uint8Array(size);
|
|
17
|
+
let offset = 0;
|
|
18
|
+
for (const chunk of chunks) {
|
|
19
|
+
bytes.set(chunk, offset);
|
|
20
|
+
offset += chunk.byteLength;
|
|
21
|
+
}
|
|
22
|
+
return new TextDecoder().decode(bytes);
|
|
23
|
+
};
|
|
24
|
+
export {
|
|
25
|
+
readBodyText
|
|
26
|
+
};
|
|
27
|
+
//# sourceMappingURL=body.mjs.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../../../../src/sandbox/remote/body.ts"],
|
|
4
|
+
"sourcesContent": ["// A request body as text, read incrementally: a body over `limit` bytes stops the\n// read as soon as it passes the limit, whatever the request declared. Null when\n// it is over.\nexport const readBodyText = async (request: Request, limit: number): Promise<string | null> => {\n const reader = request.body?.getReader();\n if (reader == null) return '';\n const chunks: Uint8Array[] = [];\n let size = 0;\n for (;;) {\n const next = await reader.read();\n if (next.done) break;\n size += next.value.byteLength;\n if (size > limit) {\n await reader.cancel().catch(() => undefined);\n return null;\n }\n chunks.push(next.value);\n }\n const bytes = new Uint8Array(size);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return new TextDecoder().decode(bytes);\n};\n"],
|
|
5
|
+
"mappings": "AAGO,MAAM,eAAe,OAAO,SAAkB,UAA0C;AAC7F,QAAM,SAAS,QAAQ,MAAM,UAAU;AACvC,MAAI,UAAU,KAAM,QAAO;AAC3B,QAAM,SAAuB,CAAC;AAC9B,MAAI,OAAO;AACX,aAAS;AACP,UAAM,OAAO,MAAM,OAAO,KAAK;AAC/B,QAAI,KAAK,KAAM;AACf,YAAQ,KAAK,MAAM;AACnB,QAAI,OAAO,OAAO;AAChB,YAAM,OAAO,OAAO,EAAE,MAAM,MAAM,MAAS;AAC3C,aAAO;AAAA,IACT;AACA,WAAO,KAAK,KAAK,KAAK;AAAA,EACxB;AACA,QAAM,QAAQ,IAAI,WAAW,IAAI;AACjC,MAAI,SAAS;AACb,aAAW,SAAS,QAAQ;AAC1B,UAAM,IAAI,OAAO,MAAM;AACvB,cAAU,MAAM;AAAA,EAClB;AACA,SAAO,IAAI,YAAY,EAAE,OAAO,KAAK;AACvC;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -39,6 +39,7 @@ import {
|
|
|
39
39
|
handleRpcTokenFromRequest
|
|
40
40
|
} from "../wire.mjs";
|
|
41
41
|
import { SANDBOX_PROVIDER_ERROR_STATUS, sandboxProviderWireError, wireErrorOf } from "./errors.mjs";
|
|
42
|
+
import { readBodyText } from "./body.mjs";
|
|
42
43
|
import { ndjsonResponse } from "./ndjson.mjs";
|
|
43
44
|
import {
|
|
44
45
|
platformIdentityExchangeUrl,
|
|
@@ -179,8 +180,8 @@ const serveSandboxProvider = (args) => {
|
|
|
179
180
|
const declared = Number(request.headers.get("content-length") ?? "0");
|
|
180
181
|
if (declared > SANDBOX_PROVIDER_MAX_BODY_BYTES)
|
|
181
182
|
throw sandboxProviderWireError(invalid("the request body is over the size limit"));
|
|
182
|
-
const text = await request
|
|
183
|
-
if (
|
|
183
|
+
const text = await readBodyText(request, SANDBOX_PROVIDER_MAX_BODY_BYTES);
|
|
184
|
+
if (text == null)
|
|
184
185
|
throw sandboxProviderWireError(invalid("the request body is over the size limit"));
|
|
185
186
|
try {
|
|
186
187
|
return JSON.parse(text);
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../src/sandbox/remote/serve.ts"],
|
|
4
|
-
"sourcesContent": ["import type { RuntimeKind } from '@finalai/agent-protocol';\nimport { platformIdentityExchangeResponseSchema } from '@finalai/agent-protocol/agent-platform/sandbox-providers';\nimport {\n JWKS_PATH,\n PlatformIdentityVariant,\n verifyPlatformIdentity,\n type JwksIface,\n type JwksKeySourceIface,\n type SandboxProviderIdentityIface,\n} from '@finalai/agent-protocol/identity';\nimport {\n SANDBOX_PROVIDER_DISCOVERY_PATH,\n SANDBOX_PROVIDER_HEARTBEAT_INTERVAL_MS,\n SANDBOX_PROVIDER_MAX_BODY_BYTES,\n SANDBOX_PROVIDER_WIRE_VERSION,\n SandboxProviderErrorCode,\n SandboxProviderWirePath,\n sandboxArtifactKeyRequestSchema,\n sandboxAttachFrameSchema,\n sandboxCapabilityOfferSchema,\n sandboxAwaitRunningRequestSchema,\n sandboxCreateRequestSchema,\n sandboxEditorRequestSchema,\n sandboxOfferRequestSchema,\n sandboxParkRequestSchema,\n sandboxPrepareRequestSchema,\n sandboxProcessesRequestSchema,\n sandboxReadSnapshotRequestSchema,\n sandboxStateRequestSchema,\n type SandboxAttachFrameIface,\n type SandboxAttachedFrameIface,\n type SandboxFormFactor,\n type SandboxProviderDiscoveryIface,\n type SandboxProviderErrorIface,\n type SandboxProviderFeaturesIface,\n} from '@finalai/agent-protocol/sandbox-provider-wire';\nimport * as z from 'zod';\nimport { jsonValueSchema, type JsonObject, type JsonValue } from \"../../json.mjs\";\nimport { sandboxEditorRequestSchema as editorRequestSchema } from \"../editor.mjs\";\nimport { FULL_SANDBOX_GRANT } from \"../grant.mjs\";\nimport { serveSandboxHandle, type HandleAuthorizeFn, type HandleLifecycle } from \"../server.mjs\";\nimport { sandboxSnapshotRequestSchema } from \"../snapshots.mjs\";\nimport {\n sandboxRuntimesOf,\n type AnySandboxProviderIface,\n type NetworkPolicyIface,\n type NetworkSandboxSessionIface,\n type SandboxCapabilityOffer,\n type SandboxEnvironmentImplementationIface,\n type SandboxIdentityFn,\n type SandboxIdentityTokenIface,\n type SandboxOfferContextIface,\n type SandboxPrepareContextIface,\n type SandboxProviderContextIface,\n type SandboxProviderHandleIface,\n type SandboxResourceContextIface,\n} from \"../types.mjs\";\nimport {\n frameChannelFromWebSocket,\n HandleRpcCloseCode,\n handleRpcTokenFromRequest,\n type WebSocketLikeIface,\n} from \"../wire.mjs\";\nimport { SANDBOX_PROVIDER_ERROR_STATUS, sandboxProviderWireError, wireErrorOf } from \"./errors.mjs\";\nimport { ndjsonResponse } from \"./ndjson.mjs\";\nimport {\n platformIdentityExchangeUrl,\n sandboxProviderArtifactBodySchema,\n sandboxProviderArtifactUrl,\n} from \"./platform-api.mjs\";\nimport { preambleChannel } from \"./preamble.mjs\";\n\n// Serves sandbox providers over the sandbox-provider wire\n// (`@finalai/agent-protocol/sandbox-provider-wire`), so a platform drives them\n// by URL exactly as it would in process. Each provider is mounted at its\n// registered URL (`publicUrl(name)`): lifecycle calls are HTTP, and `/v1/attach`\n// is a WebSocket whose frames, after the attach reply, are the handle RPC.\n//\n// Every call is authenticated by a sandbox-provider assertion the platform\n// signed for that URL, verified against the platform's JWKS. The provider's\n// context comes from it: the organization, project and sandbox it names, the\n// acting user it carries (replaced on the attach socket by\n// `identity/refresh`), the secrets the call forwards, and `identity`, which\n// exchanges the assertion for one to a backend the registration was granted.\n// Platform environment variables and files never reach the provider: the\n// platform's adapter applies them through the handle.\n\n// What a provider's discovery document says beyond what its definition does.\nexport interface SandboxProviderDiscoveryInputIface {\n title?: string | null;\n formFactor: SandboxFormFactor;\n // JSON Schema of the environment options.\n environmentSchema?: JsonObject | null;\n capabilities: SandboxCapabilityOffer;\n runtimes?: RuntimeKind[];\n // The optional calls it serves; by default, those its environment without\n // options implements.\n features?: SandboxProviderFeaturesIface;\n}\n\nexport interface ServedSandboxProviderIface {\n provider: AnySandboxProviderIface;\n discovery: SandboxProviderDiscoveryInputIface;\n}\n\nexport interface ServeSandboxProviderArgsIface {\n // Path segment (the name a project registers it under) \u2192 provider.\n providers: Record<string, ServedSandboxProviderIface>;\n // The platform's origin: the assertions' issuer, and where the exchange and\n // artifact routes are.\n issuer: string;\n // Defaults to the issuer's `/.well-known/jwks.json`.\n jwksUrl?: string;\n // A key set to verify against instead of fetching one.\n jwks?: JwksIface | JwksKeySourceIface;\n // The URL a provider is registered at: its assertions' audience.\n publicUrl: (name: string) => string;\n // For calls to the platform (exchange, artifacts).\n fetch?: typeof fetch;\n heartbeatMs?: number;\n now?: () => number;\n log?: (message: string, fields?: Record<string, string | number | boolean | null>) => void;\n}\n\nexport interface SandboxProviderServerIface {\n fetch(request: Request): Promise<Response>;\n // `/v1/attach`: the host accepted the upgrade; `request` is the upgrade request.\n upgrade(request: Request, socket: WebSocketLikeIface): void;\n}\n\n// Wire JSON as this package's JSON.\nconst json = (value: unknown): JsonValue => jsonValueSchema.parse(value);\n\n// An identity exchanged this long before it expires is asked for again.\nconst IDENTITY_REUSE_MARGIN_MS = 60_000;\n\nconst errorResponse = (error: SandboxProviderErrorIface, status?: number): Response =>\n Response.json({ error }, { status: status ?? SANDBOX_PROVIDER_ERROR_STATUS[error.code] });\n\nconst refused = (message: string): SandboxProviderErrorIface => ({\n code: SandboxProviderErrorCode.Forbidden,\n message,\n retryable: false,\n});\n\nconst invalid = (message: string): SandboxProviderErrorIface => ({\n code: SandboxProviderErrorCode.InvalidEnvironment,\n message,\n retryable: false,\n});\n\nconst LONG_CALLS: ReadonlySet<string> = new Set([\n SandboxProviderWirePath.Prepare,\n SandboxProviderWirePath.Create,\n SandboxProviderWirePath.AwaitRunning,\n]);\n\ninterface MountIface {\n name: string;\n served: ServedSandboxProviderIface;\n audience: string;\n // The URL's path without its trailing slash.\n prefix: string;\n}\n\n// The caller a call or an attach socket acts for: its assertion in force.\ninterface CallerIface {\n token: string;\n identity: SandboxProviderIdentityIface;\n}\n\ntype ImplementationType = SandboxEnvironmentImplementationIface<\n JsonValue,\n JsonValue,\n NetworkSandboxSessionIface\n>;\n\nconst featuresOf = (implementation: ImplementationType | null): SandboxProviderFeaturesIface => ({\n readSnapshot: implementation?.readSnapshot != null,\n processes: implementation?.processes != null,\n editor: implementation?.editor != null,\n attachPassive: implementation?.attachPassive != null,\n});\n\nexport const serveSandboxProvider = (\n args: ServeSandboxProviderArgsIface,\n): SandboxProviderServerIface => {\n const now = args.now ?? Date.now;\n const doFetch = args.fetch ?? fetch;\n const heartbeatMs = args.heartbeatMs ?? SANDBOX_PROVIDER_HEARTBEAT_INTERVAL_MS / 2;\n const keys =\n args.jwks != null\n ? { jwks: args.jwks }\n : { jwksUrl: args.jwksUrl ?? new URL(JWKS_PATH, args.issuer).toString() };\n const mounts: MountIface[] = Object.entries(args.providers).map(([name, served]) => {\n const audience = args.publicUrl(name);\n return { name, served, audience, prefix: new URL(audience).pathname.replace(/\\/+$/u, '') };\n });\n\n // The mount a request path is under, longest first, and the path within it.\n const route = (url: URL): { mount: MountIface; path: string } | null => {\n let best: { mount: MountIface; path: string } | null = null;\n for (const mount of mounts) {\n if (url.pathname !== mount.prefix && !url.pathname.startsWith(`${mount.prefix}/`)) continue;\n if (best != null && best.mount.prefix.length >= mount.prefix.length) continue;\n best = { mount, path: url.pathname.slice(mount.prefix.length) };\n }\n return best;\n };\n\n const verify = async (\n mount: MountIface,\n token: string | null,\n ): Promise<SandboxProviderIdentityIface | null> => {\n if (token == null) return null;\n const verified = await verifyPlatformIdentity({\n token,\n audience: mount.audience,\n variant: PlatformIdentityVariant.SandboxProvider,\n issuer: args.issuer,\n now: now(),\n ...keys,\n });\n return verified.ok ? verified.claims : null;\n };\n\n // `ctx.identity`: the current assertion exchanged for one to `audience`,\n // reused while the assertion it came from is in force.\n const identityFor = (caller: () => CallerIface): SandboxIdentityFn => {\n const cache = new Map<string, { subject: string; token: SandboxIdentityTokenIface }>();\n return async ({ audience, refresh }) => {\n const { token: subject } = caller();\n const cached = cache.get(audience);\n if (\n refresh !== true &&\n cached != null &&\n cached.subject === subject &&\n Date.parse(cached.token.expiresAt) - now() > IDENTITY_REUSE_MARGIN_MS\n )\n return cached.token;\n const response = await doFetch(platformIdentityExchangeUrl(args.issuer), {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ subjectToken: subject, audience }),\n });\n const text = await response.text();\n if (!response.ok)\n throw sandboxProviderWireError(\n refused(\n `identity for ${audience} was refused (${response.status}): ${text.slice(0, 200)}`,\n ),\n );\n const parsed = platformIdentityExchangeResponseSchema.safeParse(JSON.parse(text));\n if (!parsed.success) throw new Error(`unexpected identity exchange answer for ${audience}`);\n cache.set(audience, { subject, token: parsed.data });\n return parsed.data;\n };\n };\n\n const contextFor = (\n caller: () => CallerIface,\n secrets: Record<string, string>,\n ): SandboxProviderContextIface => ({\n organizationId: caller().identity.organizationId,\n projectId: caller().identity.projectId,\n credentials: { secret: async ({ secretRef }) => secrets[secretRef] ?? null },\n actingUser: { current: async () => caller().identity.userId },\n identity: identityFor(caller),\n log: args.log,\n });\n\n const artifactsFor = (caller: () => CallerIface): SandboxPrepareContextIface['artifacts'] => ({\n get: async (key) => {\n const response = await doFetch(sandboxProviderArtifactUrl(args.issuer, key), {\n headers: { authorization: `Bearer ${caller().token}` },\n });\n const text = await response.text();\n if (response.status === 404) return null;\n if (!response.ok) throw new Error(`reading artifact ${key} failed (${response.status})`);\n return sandboxProviderArtifactBodySchema.parse(JSON.parse(text)).artifact;\n },\n put: async (key, artifact) => {\n const response = await doFetch(sandboxProviderArtifactUrl(args.issuer, key), {\n method: 'PUT',\n headers: { authorization: `Bearer ${caller().token}`, 'content-type': 'application/json' },\n body: JSON.stringify({ artifact }),\n });\n await response.text();\n if (!response.ok) throw new Error(`storing artifact ${key} failed (${response.status})`);\n },\n });\n\n const storagePathOf = (identity: SandboxProviderIdentityIface, sandboxId: string | null) =>\n `${identity.organizationId}/${sandboxId ?? 'preparations'}`;\n\n const implementationOf = (mount: MountIface, environment: unknown): ImplementationType =>\n mount.served.provider.definition.environment(json(environment));\n\n const discoveryOf = (mount: MountIface): SandboxProviderDiscoveryIface => {\n let implementation: ImplementationType | null = null;\n if (mount.served.discovery.features == null)\n try {\n implementation = mount.served.provider.definition.environment(undefined);\n } catch {\n implementation = null;\n }\n return {\n wire: SANDBOX_PROVIDER_WIRE_VERSION,\n name: mount.name,\n title: mount.served.discovery.title ?? null,\n formFactor: mount.served.discovery.formFactor,\n environmentSchema: mount.served.discovery.environmentSchema ?? null,\n capabilities: sandboxCapabilityOfferSchema.parse(mount.served.discovery.capabilities),\n runtimes: mount.served.discovery.runtimes ?? [],\n features: mount.served.discovery.features ?? featuresOf(implementation),\n stateProtocolVersion: mount.served.provider.definition.stateProtocolVersion ?? null,\n };\n };\n\n const readBody = async (request: Request): Promise<unknown> => {\n const declared = Number(request.headers.get('content-length') ?? '0');\n if (declared > SANDBOX_PROVIDER_MAX_BODY_BYTES)\n throw sandboxProviderWireError(invalid('the request body is over the size limit'));\n const text = await request.text();\n if (new TextEncoder().encode(text).byteLength > SANDBOX_PROVIDER_MAX_BODY_BYTES)\n throw sandboxProviderWireError(invalid('the request body is over the size limit'));\n try {\n return JSON.parse(text);\n } catch {\n throw sandboxProviderWireError(invalid('the request body is not JSON'));\n }\n };\n\n const parse = <S extends z.ZodType>(schema: S, body: unknown): z.output<S> => {\n const parsed = schema.safeParse(body);\n if (!parsed.success) throw sandboxProviderWireError(invalid(z.prettifyError(parsed.error)));\n return parsed.data;\n };\n\n // A call about one sandbox must carry that sandbox's assertion.\n const requireSandbox = (identity: SandboxProviderIdentityIface, sandboxId: string) => {\n if (identity.sandboxId !== sandboxId)\n throw sandboxProviderWireError(refused('the assertion is for another sandbox'));\n };\n\n const unsupported = (what: string) =>\n sandboxProviderWireError({\n code: SandboxProviderErrorCode.NotFound,\n message: `this provider has no ${what}`,\n retryable: false,\n });\n\n // One wire call; the result is the JSON the answer carries.\n const dispatch = async (\n mount: MountIface,\n path: string,\n caller: CallerIface,\n body: unknown,\n ): Promise<JsonValue> => {\n const { identity } = caller;\n const callerOf = () => caller;\n const base = (secrets: Record<string, string>) => contextFor(callerOf, secrets);\n const resourceContext = (fields: {\n sandboxId: string;\n secrets: Record<string, string>;\n platformEgressHosts?: string[];\n lifecycle?: SandboxResourceContextIface['lifecycle'];\n }): SandboxResourceContextIface => ({\n ...base(fields.secrets),\n sandboxId: fields.sandboxId,\n storagePath: storagePathOf(identity, fields.sandboxId),\n lifecycle: fields.lifecycle ?? { parkAfterIdleMs: null },\n platformEgressHosts: fields.platformEgressHosts,\n // Lifecycle calls apply no network policy; attach reports it on the socket.\n platformNetworkPolicy: async () => undefined,\n });\n switch (path) {\n case SandboxProviderWirePath.Offer: {\n const request = parse(sandboxOfferRequestSchema, body);\n if (request.sandboxId != null) requireSandbox(identity, request.sandboxId);\n const implementation = implementationOf(mount, request.environment);\n const ctx: SandboxOfferContextIface = {\n ...base(request.secrets),\n ...(request.sandboxId == null ? {} : { sandboxId: request.sandboxId }),\n };\n const [capabilities, runtimes, features, additionalFeatures, mcpCatalog] =\n await Promise.all([\n implementation.capabilities(ctx),\n sandboxRuntimesOf(implementation, ctx),\n implementation.features?.(ctx) ?? null,\n implementation.additionalFeatures?.(ctx) ?? [],\n implementation.mcpCatalog?.(ctx) ?? null,\n ]);\n return {\n capabilities: { ...capabilities },\n runtimes,\n features,\n additionalFeatures,\n mcpCatalog:\n mcpCatalog == null\n ? null\n : {\n computerUse: mcpCatalog.computerUse,\n localMcp: mcpCatalog.localMcp,\n ...(mcpCatalog.localMcpIncomplete == null\n ? {}\n : { localMcpIncomplete: mcpCatalog.localMcpIncomplete }),\n },\n };\n }\n case SandboxProviderWirePath.ArtifactKey:\n case SandboxProviderWirePath.Prepare: {\n const request = parse(\n path === SandboxProviderWirePath.Prepare\n ? sandboxPrepareRequestSchema\n : sandboxArtifactKeyRequestSchema,\n body,\n );\n const implementation = implementationOf(mount, request.environment);\n const ctx: SandboxPrepareContextIface = {\n ...base(request.secrets),\n files: request.files,\n resources: z.record(z.string(), jsonValueSchema).parse(request.resources),\n sourceRevision: request.sourceRevision,\n storagePath: storagePathOf(identity, identity.sandboxId),\n artifacts: artifactsFor(callerOf),\n };\n if (path === SandboxProviderWirePath.ArtifactKey)\n return { key: await implementation.artifactKey(ctx) };\n return { artifact: await implementation.prepare(ctx) };\n }\n case SandboxProviderWirePath.Create: {\n const request = parse(sandboxCreateRequestSchema, body);\n requireSandbox(identity, request.sandboxId);\n const implementation = implementationOf(mount, request.environment);\n const created = await implementation.create(\n resourceContext({\n sandboxId: request.sandboxId,\n secrets: request.secrets,\n platformEgressHosts: request.platformEgressHosts,\n lifecycle: request.lifecycle,\n }),\n { artifact: json(request.artifact), setup: request.setup },\n );\n return { state: created.state, region: created.region ?? null };\n }\n case SandboxProviderWirePath.AwaitRunning: {\n const request = parse(sandboxAwaitRunningRequestSchema, body);\n requireSandbox(identity, request.sandboxId);\n await implementationOf(mount, request.environment).awaitRunning(\n resourceContext({ sandboxId: request.sandboxId, secrets: request.secrets }),\n json(request.state),\n { timeoutMs: request.timeoutMs },\n );\n return {};\n }\n case SandboxProviderWirePath.Detach:\n case SandboxProviderWirePath.Delete: {\n const request = parse(sandboxStateRequestSchema, body);\n requireSandbox(identity, request.sandboxId);\n const implementation = implementationOf(mount, request.environment);\n const ctx = resourceContext({ sandboxId: request.sandboxId, secrets: request.secrets });\n if (path === SandboxProviderWirePath.Delete) {\n await implementation.delete(ctx, { state: json(request.state) });\n return {};\n }\n return { state: await implementation.detach(ctx, { state: json(request.state) }) };\n }\n case SandboxProviderWirePath.Park: {\n const request = parse(sandboxParkRequestSchema, body);\n requireSandbox(identity, request.sandboxId);\n const implementation = implementationOf(mount, request.environment);\n return {\n state: await implementation.park(\n resourceContext({ sandboxId: request.sandboxId, secrets: request.secrets }),\n { artifact: json(request.artifact), state: json(request.state) },\n ),\n };\n }\n case SandboxProviderWirePath.ReadSnapshot: {\n const request = parse(sandboxReadSnapshotRequestSchema, body);\n requireSandbox(identity, request.sandboxId);\n const implementation = implementationOf(mount, request.environment);\n if (implementation.readSnapshot == null) throw unsupported('snapshot reads');\n const response = await implementation.readSnapshot(\n { ...base(request.secrets), sandboxId: request.sandboxId },\n json(request.state),\n parse(sandboxSnapshotRequestSchema, request.request),\n );\n return response == null ? null : { ...response };\n }\n case SandboxProviderWirePath.Processes: {\n const request = parse(sandboxProcessesRequestSchema, body);\n requireSandbox(identity, request.sandboxId);\n const implementation = implementationOf(mount, request.environment);\n if (implementation.processes == null) throw unsupported('process inspection');\n return {\n ...(await implementation.processes(\n { ...base(request.secrets), sandboxId: request.sandboxId },\n json(request.state),\n request.request,\n )),\n };\n }\n case SandboxProviderWirePath.Editor: {\n const request = parse(sandboxEditorRequestSchema, body);\n requireSandbox(identity, request.sandboxId);\n const implementation = implementationOf(mount, request.environment);\n if (implementation.editor == null) throw unsupported('editor');\n return {\n ...(await implementation.editor(\n { ...base(request.secrets), sandboxId: request.sandboxId },\n json(request.state),\n parse(editorRequestSchema, request.request),\n )),\n };\n }\n default:\n throw unsupported(`call ${path}`);\n }\n };\n\n const fetchHandler = async (request: Request): Promise<Response> => {\n const url = new URL(request.url);\n const routed = route(url);\n if (routed == null)\n return errorResponse({\n code: SandboxProviderErrorCode.NotFound,\n message: 'no sandbox provider is served here',\n retryable: false,\n });\n const { mount, path } = routed;\n if (request.method === 'GET' && path === SANDBOX_PROVIDER_DISCOVERY_PATH)\n return Response.json(discoveryOf(mount));\n if (request.method !== 'POST' || path === SandboxProviderWirePath.Attach)\n return errorResponse(invalid(`${request.method} ${path} is not a provider call`), 405);\n const token = /^Bearer\\s+(.+)$/iu.exec(request.headers.get('authorization')?.trim() ?? '')?.[1];\n const identity = await verify(mount, token ?? null);\n if (identity == null || token == null)\n return errorResponse(refused('a valid sandbox-provider assertion is required'), 401);\n const caller: CallerIface = { token, identity };\n let body: unknown;\n try {\n body = await readBody(request);\n } catch (cause) {\n return errorResponse(wireErrorOf(cause));\n }\n if (LONG_CALLS.has(path))\n return ndjsonResponse({ work: () => dispatch(mount, path, caller, body), heartbeatMs });\n try {\n return Response.json(await dispatch(mount, path, caller, body));\n } catch (cause) {\n return errorResponse(wireErrorOf(cause));\n }\n };\n\n const upgrade = (request: Request, socket: WebSocketLikeIface): void => {\n const { channel } = frameChannelFromWebSocket(socket);\n const preamble = preambleChannel(channel);\n const fail = (error: SandboxProviderErrorIface, code: number = HandleRpcCloseCode.Normal) => {\n channel.send(JSON.stringify({ type: 'error', error }));\n channel.close(code, error.message.slice(0, 120));\n };\n void (async () => {\n const routed = route(new URL(request.url));\n if (routed == null || routed.path !== SandboxProviderWirePath.Attach) {\n fail({\n code: SandboxProviderErrorCode.NotFound,\n message: 'no sandbox provider attaches here',\n retryable: false,\n });\n return;\n }\n const { mount } = routed;\n const token = handleRpcTokenFromRequest(request);\n const identity = await verify(mount, token);\n if (identity == null || token == null) {\n fail(\n refused('a valid sandbox-provider assertion is required'),\n HandleRpcCloseCode.Unauthorized,\n );\n return;\n }\n let caller: CallerIface = { token, identity };\n let frame: SandboxAttachFrameIface;\n try {\n const first = await preamble.next();\n if (typeof first !== 'string') throw new Error('the attach request must be a text frame');\n frame = parse(sandboxAttachFrameSchema, JSON.parse(first));\n requireSandbox(identity, frame.sandboxId);\n } catch (cause) {\n fail(wireErrorOf(cause));\n return;\n }\n const heartbeat = setInterval(\n () => channel.send(JSON.stringify({ type: 'heartbeat' })),\n heartbeatMs,\n );\n let reported: NetworkPolicyIface | null = null;\n const ctx: SandboxResourceContextIface = {\n ...contextFor(() => caller, frame.secrets),\n sandboxId: frame.sandboxId,\n storagePath: storagePathOf(identity, frame.sandboxId),\n lifecycle: frame.lifecycle,\n platformEgressHosts: frame.platformEgressHosts,\n platformNetworkPolicy: async (policy) => {\n reported = policy;\n },\n };\n let handle: SandboxProviderHandleIface<NetworkSandboxSessionIface>;\n let attached: SandboxAttachedFrameIface;\n try {\n const implementation = implementationOf(mount, frame.environment);\n if (frame.passive) {\n if (implementation.attachPassive == null) throw unsupported('passive attach');\n handle = await implementation.attachPassive(ctx, {\n artifact: json(frame.artifact),\n state: json(frame.state),\n });\n attached = {\n type: 'attached',\n state: json(frame.state),\n fresh: false,\n booted: false,\n region: null,\n networkPolicy: null,\n };\n } else {\n const attachment = await implementation.attach(ctx, {\n artifact: json(frame.artifact),\n state: json(frame.state),\n });\n handle = attachment.handle;\n attached = {\n type: 'attached',\n state: attachment.state,\n fresh: attachment.fresh,\n booted: attachment.booted,\n region: attachment.region ?? null,\n networkPolicy: reported,\n };\n }\n } catch (cause) {\n clearInterval(heartbeat);\n fail(wireErrorOf(cause));\n return;\n }\n clearInterval(heartbeat);\n // The handle is released once, by the platform or when the socket goes.\n let shutdown: Promise<void> | null = null;\n const lifecycle: HandleLifecycle = {\n onSandboxStop: () => handle.onSandboxStop(),\n onSandboxDelete: (options) => handle.onSandboxDelete(options),\n onRuntimeShutdown: () => {\n shutdown ??= handle.onRuntimeShutdown();\n return shutdown;\n },\n };\n // `initialize { identity }` and `identity/refresh`: an assertion for the\n // same provider and sandbox, which becomes the caller's.\n const authorize: HandleAuthorizeFn = async ({ identity: assertion }) => {\n const next = await verify(mount, assertion ?? null);\n if (\n next == null ||\n assertion == null ||\n next.providerId !== identity.providerId ||\n next.sandboxId !== identity.sandboxId ||\n next.organizationId !== identity.organizationId ||\n next.projectId !== identity.projectId\n )\n return null;\n caller = { token: assertion, identity: next };\n return { expiresAt: new Date(next.expiresAt).toISOString() };\n };\n channel.send(JSON.stringify(attached));\n serveSandboxHandle({\n sandbox: handle.sandbox,\n handle: lifecycle,\n authorize,\n access: { grant: FULL_SANDBOX_GRANT, lifecycle: true },\n mcpChannels: true,\n }).attach(preamble.rest());\n await preamble.closed;\n await lifecycle.onRuntimeShutdown().catch((cause: unknown) =>\n args.log?.('sandbox provider handle shutdown failed', {\n provider: mount.name,\n sandboxId: frame.sandboxId,\n error: cause instanceof Error ? cause.message : String(cause),\n }),\n );\n })();\n };\n\n return { fetch: fetchHandler, upgrade };\n};\n"],
|
|
5
|
-
"mappings": "AACA,SAAS,8CAA8C;AACv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,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 sandboxOfferRequestSchema,\n sandboxParkRequestSchema,\n sandboxPrepareRequestSchema,\n sandboxProcessesRequestSchema,\n sandboxReadSnapshotRequestSchema,\n sandboxStateRequestSchema,\n type SandboxAttachFrameIface,\n type SandboxAttachedFrameIface,\n type SandboxFormFactor,\n type SandboxProviderDiscoveryIface,\n type SandboxProviderErrorIface,\n type SandboxProviderFeaturesIface,\n} from '@finalai/agent-protocol/sandbox-provider-wire';\nimport * as z from 'zod';\nimport { jsonValueSchema, type JsonObject, type JsonValue } from \"../../json.mjs\";\nimport { sandboxEditorRequestSchema as editorRequestSchema } from \"../editor.mjs\";\nimport { FULL_SANDBOX_GRANT } from \"../grant.mjs\";\nimport { serveSandboxHandle, type HandleAuthorizeFn, type HandleLifecycle } from \"../server.mjs\";\nimport { sandboxSnapshotRequestSchema } from \"../snapshots.mjs\";\nimport {\n sandboxRuntimesOf,\n type AnySandboxProviderIface,\n type NetworkPolicyIface,\n type NetworkSandboxSessionIface,\n type SandboxCapabilityOffer,\n type SandboxEnvironmentImplementationIface,\n type SandboxIdentityFn,\n type SandboxIdentityTokenIface,\n type SandboxOfferContextIface,\n type SandboxPrepareContextIface,\n type SandboxProviderContextIface,\n type SandboxProviderHandleIface,\n type SandboxResourceContextIface,\n} from \"../types.mjs\";\nimport {\n frameChannelFromWebSocket,\n HandleRpcCloseCode,\n handleRpcTokenFromRequest,\n type WebSocketLikeIface,\n} from \"../wire.mjs\";\nimport { SANDBOX_PROVIDER_ERROR_STATUS, sandboxProviderWireError, wireErrorOf } from \"./errors.mjs\";\nimport { readBodyText } from \"./body.mjs\";\nimport { ndjsonResponse } from \"./ndjson.mjs\";\nimport {\n platformIdentityExchangeUrl,\n sandboxProviderArtifactBodySchema,\n sandboxProviderArtifactUrl,\n} from \"./platform-api.mjs\";\nimport { preambleChannel } from \"./preamble.mjs\";\n\n// Serves sandbox providers over the sandbox-provider wire\n// (`@finalai/agent-protocol/sandbox-provider-wire`), so a platform drives them\n// by URL exactly as it would in process. Each provider is mounted at its\n// registered URL (`publicUrl(name)`): lifecycle calls are HTTP, and `/v1/attach`\n// is a WebSocket whose frames, after the attach reply, are the handle RPC.\n//\n// Every call is authenticated by a sandbox-provider assertion the platform\n// signed for that URL, verified against the platform's JWKS. The provider's\n// context comes from it: the organization, project and sandbox it names, the\n// acting user it carries (replaced on the attach socket by\n// `identity/refresh`), the secrets the call forwards, and `identity`, which\n// exchanges the assertion for one to a backend the registration was granted.\n// Platform environment variables and files never reach the provider: the\n// platform's adapter applies them through the handle.\n\n// What a provider's discovery document says beyond what its definition does.\nexport interface SandboxProviderDiscoveryInputIface {\n title?: string | null;\n formFactor: SandboxFormFactor;\n // JSON Schema of the environment options.\n environmentSchema?: JsonObject | null;\n capabilities: SandboxCapabilityOffer;\n runtimes?: RuntimeKind[];\n // The optional calls it serves; by default, those its environment without\n // options implements.\n features?: SandboxProviderFeaturesIface;\n}\n\nexport interface ServedSandboxProviderIface {\n provider: AnySandboxProviderIface;\n discovery: SandboxProviderDiscoveryInputIface;\n}\n\nexport interface ServeSandboxProviderArgsIface {\n // Path segment (the name a project registers it under) \u2192 provider.\n providers: Record<string, ServedSandboxProviderIface>;\n // The platform's origin: the assertions' issuer, and where the exchange and\n // artifact routes are.\n issuer: string;\n // Defaults to the issuer's `/.well-known/jwks.json`.\n jwksUrl?: string;\n // A key set to verify against instead of fetching one.\n jwks?: JwksIface | JwksKeySourceIface;\n // The URL a provider is registered at: its assertions' audience.\n publicUrl: (name: string) => string;\n // For calls to the platform (exchange, artifacts).\n fetch?: typeof fetch;\n heartbeatMs?: number;\n now?: () => number;\n log?: (message: string, fields?: Record<string, string | number | boolean | null>) => void;\n}\n\nexport interface SandboxProviderServerIface {\n fetch(request: Request): Promise<Response>;\n // `/v1/attach`: the host accepted the upgrade; `request` is the upgrade request.\n upgrade(request: Request, socket: WebSocketLikeIface): void;\n}\n\n// Wire JSON as this package's JSON.\nconst json = (value: unknown): JsonValue => jsonValueSchema.parse(value);\n\n// An identity exchanged this long before it expires is asked for again.\nconst IDENTITY_REUSE_MARGIN_MS = 60_000;\n\nconst errorResponse = (error: SandboxProviderErrorIface, status?: number): Response =>\n Response.json({ error }, { status: status ?? SANDBOX_PROVIDER_ERROR_STATUS[error.code] });\n\nconst refused = (message: string): SandboxProviderErrorIface => ({\n code: SandboxProviderErrorCode.Forbidden,\n message,\n retryable: false,\n});\n\nconst invalid = (message: string): SandboxProviderErrorIface => ({\n code: SandboxProviderErrorCode.InvalidEnvironment,\n message,\n retryable: false,\n});\n\nconst LONG_CALLS: ReadonlySet<string> = new Set([\n SandboxProviderWirePath.Prepare,\n SandboxProviderWirePath.Create,\n SandboxProviderWirePath.AwaitRunning,\n]);\n\ninterface MountIface {\n name: string;\n served: ServedSandboxProviderIface;\n audience: string;\n // The URL's path without its trailing slash.\n prefix: string;\n}\n\n// The caller a call or an attach socket acts for: its assertion in force.\ninterface CallerIface {\n token: string;\n identity: SandboxProviderIdentityIface;\n}\n\ntype ImplementationType = SandboxEnvironmentImplementationIface<\n JsonValue,\n JsonValue,\n NetworkSandboxSessionIface\n>;\n\nconst featuresOf = (implementation: ImplementationType | null): SandboxProviderFeaturesIface => ({\n readSnapshot: implementation?.readSnapshot != null,\n processes: implementation?.processes != null,\n editor: implementation?.editor != null,\n attachPassive: implementation?.attachPassive != null,\n});\n\nexport const serveSandboxProvider = (\n args: ServeSandboxProviderArgsIface,\n): SandboxProviderServerIface => {\n const now = args.now ?? Date.now;\n const doFetch = args.fetch ?? fetch;\n const heartbeatMs = args.heartbeatMs ?? SANDBOX_PROVIDER_HEARTBEAT_INTERVAL_MS / 2;\n const keys =\n args.jwks != null\n ? { jwks: args.jwks }\n : { jwksUrl: args.jwksUrl ?? new URL(JWKS_PATH, args.issuer).toString() };\n const mounts: MountIface[] = Object.entries(args.providers).map(([name, served]) => {\n const audience = args.publicUrl(name);\n return { name, served, audience, prefix: new URL(audience).pathname.replace(/\\/+$/u, '') };\n });\n\n // The mount a request path is under, longest first, and the path within it.\n const route = (url: URL): { mount: MountIface; path: string } | null => {\n let best: { mount: MountIface; path: string } | null = null;\n for (const mount of mounts) {\n if (url.pathname !== mount.prefix && !url.pathname.startsWith(`${mount.prefix}/`)) continue;\n if (best != null && best.mount.prefix.length >= mount.prefix.length) continue;\n best = { mount, path: url.pathname.slice(mount.prefix.length) };\n }\n return best;\n };\n\n const verify = async (\n mount: MountIface,\n token: string | null,\n ): Promise<SandboxProviderIdentityIface | null> => {\n if (token == null) return null;\n const verified = await verifyPlatformIdentity({\n token,\n audience: mount.audience,\n variant: PlatformIdentityVariant.SandboxProvider,\n issuer: args.issuer,\n now: now(),\n ...keys,\n });\n return verified.ok ? verified.claims : null;\n };\n\n // `ctx.identity`: the current assertion exchanged for one to `audience`,\n // reused while the assertion it came from is in force.\n const identityFor = (caller: () => CallerIface): SandboxIdentityFn => {\n const cache = new Map<string, { subject: string; token: SandboxIdentityTokenIface }>();\n return async ({ audience, refresh }) => {\n const { token: subject } = caller();\n const cached = cache.get(audience);\n if (\n refresh !== true &&\n cached != null &&\n cached.subject === subject &&\n Date.parse(cached.token.expiresAt) - now() > IDENTITY_REUSE_MARGIN_MS\n )\n return cached.token;\n const response = await doFetch(platformIdentityExchangeUrl(args.issuer), {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ subjectToken: subject, audience }),\n });\n const text = await response.text();\n if (!response.ok)\n throw sandboxProviderWireError(\n refused(\n `identity for ${audience} was refused (${response.status}): ${text.slice(0, 200)}`,\n ),\n );\n const parsed = platformIdentityExchangeResponseSchema.safeParse(JSON.parse(text));\n if (!parsed.success) throw new Error(`unexpected identity exchange answer for ${audience}`);\n cache.set(audience, { subject, token: parsed.data });\n return parsed.data;\n };\n };\n\n const contextFor = (\n caller: () => CallerIface,\n secrets: Record<string, string>,\n ): SandboxProviderContextIface => ({\n organizationId: caller().identity.organizationId,\n projectId: caller().identity.projectId,\n credentials: { secret: async ({ secretRef }) => secrets[secretRef] ?? null },\n actingUser: { current: async () => caller().identity.userId },\n identity: identityFor(caller),\n log: args.log,\n });\n\n const artifactsFor = (caller: () => CallerIface): SandboxPrepareContextIface['artifacts'] => ({\n get: async (key) => {\n const response = await doFetch(sandboxProviderArtifactUrl(args.issuer, key), {\n headers: { authorization: `Bearer ${caller().token}` },\n });\n const text = await response.text();\n if (response.status === 404) return null;\n if (!response.ok) throw new Error(`reading artifact ${key} failed (${response.status})`);\n return sandboxProviderArtifactBodySchema.parse(JSON.parse(text)).artifact;\n },\n put: async (key, artifact) => {\n const response = await doFetch(sandboxProviderArtifactUrl(args.issuer, key), {\n method: 'PUT',\n headers: { authorization: `Bearer ${caller().token}`, 'content-type': 'application/json' },\n body: JSON.stringify({ artifact }),\n });\n await response.text();\n if (!response.ok) throw new Error(`storing artifact ${key} failed (${response.status})`);\n },\n });\n\n const storagePathOf = (identity: SandboxProviderIdentityIface, sandboxId: string | null) =>\n `${identity.organizationId}/${sandboxId ?? 'preparations'}`;\n\n const implementationOf = (mount: MountIface, environment: unknown): ImplementationType =>\n mount.served.provider.definition.environment(json(environment));\n\n const discoveryOf = (mount: MountIface): SandboxProviderDiscoveryIface => {\n let implementation: ImplementationType | null = null;\n if (mount.served.discovery.features == null)\n try {\n implementation = mount.served.provider.definition.environment(undefined);\n } catch {\n implementation = null;\n }\n return {\n wire: SANDBOX_PROVIDER_WIRE_VERSION,\n name: mount.name,\n title: mount.served.discovery.title ?? null,\n formFactor: mount.served.discovery.formFactor,\n environmentSchema: mount.served.discovery.environmentSchema ?? null,\n capabilities: sandboxCapabilityOfferSchema.parse(mount.served.discovery.capabilities),\n runtimes: mount.served.discovery.runtimes ?? [],\n features: mount.served.discovery.features ?? featuresOf(implementation),\n stateProtocolVersion: mount.served.provider.definition.stateProtocolVersion ?? null,\n };\n };\n\n const readBody = async (request: Request): Promise<unknown> => {\n const declared = Number(request.headers.get('content-length') ?? '0');\n if (declared > SANDBOX_PROVIDER_MAX_BODY_BYTES)\n throw sandboxProviderWireError(invalid('the request body is over the size limit'));\n const text = await readBodyText(request, SANDBOX_PROVIDER_MAX_BODY_BYTES);\n if (text == null)\n throw sandboxProviderWireError(invalid('the request body is over the size limit'));\n try {\n return JSON.parse(text);\n } catch {\n throw sandboxProviderWireError(invalid('the request body is not JSON'));\n }\n };\n\n const parse = <S extends z.ZodType>(schema: S, body: unknown): z.output<S> => {\n const parsed = schema.safeParse(body);\n if (!parsed.success) throw sandboxProviderWireError(invalid(z.prettifyError(parsed.error)));\n return parsed.data;\n };\n\n // A call about one sandbox must carry that sandbox's assertion.\n const requireSandbox = (identity: SandboxProviderIdentityIface, sandboxId: string) => {\n if (identity.sandboxId !== sandboxId)\n throw sandboxProviderWireError(refused('the assertion is for another sandbox'));\n };\n\n const unsupported = (what: string) =>\n sandboxProviderWireError({\n code: SandboxProviderErrorCode.NotFound,\n message: `this provider has no ${what}`,\n retryable: false,\n });\n\n // One wire call; the result is the JSON the answer carries.\n const dispatch = async (\n mount: MountIface,\n path: string,\n caller: CallerIface,\n body: unknown,\n ): Promise<JsonValue> => {\n const { identity } = caller;\n const callerOf = () => caller;\n const base = (secrets: Record<string, string>) => contextFor(callerOf, secrets);\n const resourceContext = (fields: {\n sandboxId: string;\n secrets: Record<string, string>;\n platformEgressHosts?: string[];\n lifecycle?: SandboxResourceContextIface['lifecycle'];\n }): SandboxResourceContextIface => ({\n ...base(fields.secrets),\n sandboxId: fields.sandboxId,\n storagePath: storagePathOf(identity, fields.sandboxId),\n lifecycle: fields.lifecycle ?? { parkAfterIdleMs: null },\n platformEgressHosts: fields.platformEgressHosts,\n // Lifecycle calls apply no network policy; attach reports it on the socket.\n platformNetworkPolicy: async () => undefined,\n });\n switch (path) {\n case SandboxProviderWirePath.Offer: {\n const request = parse(sandboxOfferRequestSchema, body);\n if (request.sandboxId != null) requireSandbox(identity, request.sandboxId);\n const implementation = implementationOf(mount, request.environment);\n const ctx: SandboxOfferContextIface = {\n ...base(request.secrets),\n ...(request.sandboxId == null ? {} : { sandboxId: request.sandboxId }),\n };\n const [capabilities, runtimes, features, additionalFeatures, mcpCatalog] =\n await Promise.all([\n implementation.capabilities(ctx),\n sandboxRuntimesOf(implementation, ctx),\n implementation.features?.(ctx) ?? null,\n implementation.additionalFeatures?.(ctx) ?? [],\n implementation.mcpCatalog?.(ctx) ?? null,\n ]);\n return {\n capabilities: { ...capabilities },\n runtimes,\n features,\n additionalFeatures,\n mcpCatalog:\n mcpCatalog == null\n ? null\n : {\n computerUse: mcpCatalog.computerUse,\n localMcp: mcpCatalog.localMcp,\n ...(mcpCatalog.localMcpIncomplete == null\n ? {}\n : { localMcpIncomplete: mcpCatalog.localMcpIncomplete }),\n },\n };\n }\n case SandboxProviderWirePath.ArtifactKey:\n case SandboxProviderWirePath.Prepare: {\n const request = parse(\n path === SandboxProviderWirePath.Prepare\n ? sandboxPrepareRequestSchema\n : sandboxArtifactKeyRequestSchema,\n body,\n );\n const implementation = implementationOf(mount, request.environment);\n const ctx: SandboxPrepareContextIface = {\n ...base(request.secrets),\n files: request.files,\n resources: z.record(z.string(), jsonValueSchema).parse(request.resources),\n sourceRevision: request.sourceRevision,\n storagePath: storagePathOf(identity, identity.sandboxId),\n artifacts: artifactsFor(callerOf),\n };\n if (path === SandboxProviderWirePath.ArtifactKey)\n return { key: await implementation.artifactKey(ctx) };\n return { artifact: await implementation.prepare(ctx) };\n }\n case SandboxProviderWirePath.Create: {\n const request = parse(sandboxCreateRequestSchema, body);\n requireSandbox(identity, request.sandboxId);\n const implementation = implementationOf(mount, request.environment);\n const created = await implementation.create(\n resourceContext({\n sandboxId: request.sandboxId,\n secrets: request.secrets,\n platformEgressHosts: request.platformEgressHosts,\n lifecycle: request.lifecycle,\n }),\n { artifact: json(request.artifact), setup: request.setup },\n );\n return { state: created.state, region: created.region ?? null };\n }\n case SandboxProviderWirePath.AwaitRunning: {\n const request = parse(sandboxAwaitRunningRequestSchema, body);\n requireSandbox(identity, request.sandboxId);\n await implementationOf(mount, request.environment).awaitRunning(\n resourceContext({ sandboxId: request.sandboxId, secrets: request.secrets }),\n json(request.state),\n { timeoutMs: request.timeoutMs },\n );\n return {};\n }\n case SandboxProviderWirePath.Detach:\n case SandboxProviderWirePath.Delete: {\n const request = parse(sandboxStateRequestSchema, body);\n requireSandbox(identity, request.sandboxId);\n const implementation = implementationOf(mount, request.environment);\n const ctx = resourceContext({ sandboxId: request.sandboxId, secrets: request.secrets });\n if (path === SandboxProviderWirePath.Delete) {\n await implementation.delete(ctx, { state: json(request.state) });\n return {};\n }\n return { state: await implementation.detach(ctx, { state: json(request.state) }) };\n }\n case SandboxProviderWirePath.Park: {\n const request = parse(sandboxParkRequestSchema, body);\n requireSandbox(identity, request.sandboxId);\n const implementation = implementationOf(mount, request.environment);\n return {\n state: await implementation.park(\n resourceContext({ sandboxId: request.sandboxId, secrets: request.secrets }),\n { artifact: json(request.artifact), state: json(request.state) },\n ),\n };\n }\n case SandboxProviderWirePath.ReadSnapshot: {\n const request = parse(sandboxReadSnapshotRequestSchema, body);\n requireSandbox(identity, request.sandboxId);\n const implementation = implementationOf(mount, request.environment);\n if (implementation.readSnapshot == null) throw unsupported('snapshot reads');\n const response = await implementation.readSnapshot(\n { ...base(request.secrets), sandboxId: request.sandboxId },\n json(request.state),\n parse(sandboxSnapshotRequestSchema, request.request),\n );\n return response == null ? null : { ...response };\n }\n case SandboxProviderWirePath.Processes: {\n const request = parse(sandboxProcessesRequestSchema, body);\n requireSandbox(identity, request.sandboxId);\n const implementation = implementationOf(mount, request.environment);\n if (implementation.processes == null) throw unsupported('process inspection');\n return {\n ...(await implementation.processes(\n { ...base(request.secrets), sandboxId: request.sandboxId },\n json(request.state),\n request.request,\n )),\n };\n }\n case SandboxProviderWirePath.Editor: {\n const request = parse(sandboxEditorRequestSchema, body);\n requireSandbox(identity, request.sandboxId);\n const implementation = implementationOf(mount, request.environment);\n if (implementation.editor == null) throw unsupported('editor');\n return {\n ...(await implementation.editor(\n { ...base(request.secrets), sandboxId: request.sandboxId },\n json(request.state),\n parse(editorRequestSchema, request.request),\n )),\n };\n }\n default:\n throw unsupported(`call ${path}`);\n }\n };\n\n const fetchHandler = async (request: Request): Promise<Response> => {\n const url = new URL(request.url);\n const routed = route(url);\n if (routed == null)\n return errorResponse({\n code: SandboxProviderErrorCode.NotFound,\n message: 'no sandbox provider is served here',\n retryable: false,\n });\n const { mount, path } = routed;\n if (request.method === 'GET' && path === SANDBOX_PROVIDER_DISCOVERY_PATH)\n return Response.json(discoveryOf(mount));\n if (request.method !== 'POST' || path === SandboxProviderWirePath.Attach)\n return errorResponse(invalid(`${request.method} ${path} is not a provider call`), 405);\n const token = /^Bearer\\s+(.+)$/iu.exec(request.headers.get('authorization')?.trim() ?? '')?.[1];\n const identity = await verify(mount, token ?? null);\n if (identity == null || token == null)\n return errorResponse(refused('a valid sandbox-provider assertion is required'), 401);\n const caller: CallerIface = { token, identity };\n let body: unknown;\n try {\n body = await readBody(request);\n } catch (cause) {\n return errorResponse(wireErrorOf(cause));\n }\n if (LONG_CALLS.has(path))\n return ndjsonResponse({ work: () => dispatch(mount, path, caller, body), heartbeatMs });\n try {\n return Response.json(await dispatch(mount, path, caller, body));\n } catch (cause) {\n return errorResponse(wireErrorOf(cause));\n }\n };\n\n const upgrade = (request: Request, socket: WebSocketLikeIface): void => {\n const { channel } = frameChannelFromWebSocket(socket);\n const preamble = preambleChannel(channel);\n const fail = (error: SandboxProviderErrorIface, code: number = HandleRpcCloseCode.Normal) => {\n channel.send(JSON.stringify({ type: 'error', error }));\n channel.close(code, error.message.slice(0, 120));\n };\n void (async () => {\n const routed = route(new URL(request.url));\n if (routed == null || routed.path !== SandboxProviderWirePath.Attach) {\n fail({\n code: SandboxProviderErrorCode.NotFound,\n message: 'no sandbox provider attaches here',\n retryable: false,\n });\n return;\n }\n const { mount } = routed;\n const token = handleRpcTokenFromRequest(request);\n const identity = await verify(mount, token);\n if (identity == null || token == null) {\n fail(\n refused('a valid sandbox-provider assertion is required'),\n HandleRpcCloseCode.Unauthorized,\n );\n return;\n }\n let caller: CallerIface = { token, identity };\n let frame: SandboxAttachFrameIface;\n try {\n const first = await preamble.next();\n if (typeof first !== 'string') throw new Error('the attach request must be a text frame');\n frame = parse(sandboxAttachFrameSchema, JSON.parse(first));\n requireSandbox(identity, frame.sandboxId);\n } catch (cause) {\n fail(wireErrorOf(cause));\n return;\n }\n const heartbeat = setInterval(\n () => channel.send(JSON.stringify({ type: 'heartbeat' })),\n heartbeatMs,\n );\n let reported: NetworkPolicyIface | null = null;\n const ctx: SandboxResourceContextIface = {\n ...contextFor(() => caller, frame.secrets),\n sandboxId: frame.sandboxId,\n storagePath: storagePathOf(identity, frame.sandboxId),\n lifecycle: frame.lifecycle,\n platformEgressHosts: frame.platformEgressHosts,\n platformNetworkPolicy: async (policy) => {\n reported = policy;\n },\n };\n let handle: SandboxProviderHandleIface<NetworkSandboxSessionIface>;\n let attached: SandboxAttachedFrameIface;\n try {\n const implementation = implementationOf(mount, frame.environment);\n if (frame.passive) {\n if (implementation.attachPassive == null) throw unsupported('passive attach');\n handle = await implementation.attachPassive(ctx, {\n artifact: json(frame.artifact),\n state: json(frame.state),\n });\n attached = {\n type: 'attached',\n state: json(frame.state),\n fresh: false,\n booted: false,\n region: null,\n networkPolicy: null,\n };\n } else {\n const attachment = await implementation.attach(ctx, {\n artifact: json(frame.artifact),\n state: json(frame.state),\n });\n handle = attachment.handle;\n attached = {\n type: 'attached',\n state: attachment.state,\n fresh: attachment.fresh,\n booted: attachment.booted,\n region: attachment.region ?? null,\n networkPolicy: reported,\n };\n }\n } catch (cause) {\n clearInterval(heartbeat);\n fail(wireErrorOf(cause));\n return;\n }\n clearInterval(heartbeat);\n // The handle is released once, by the platform or when the socket goes.\n let shutdown: Promise<void> | null = null;\n const lifecycle: HandleLifecycle = {\n onSandboxStop: () => handle.onSandboxStop(),\n onSandboxDelete: (options) => handle.onSandboxDelete(options),\n onRuntimeShutdown: () => {\n shutdown ??= handle.onRuntimeShutdown();\n return shutdown;\n },\n };\n // `initialize { identity }` and `identity/refresh`: an assertion for the\n // same provider and sandbox, which becomes the caller's.\n const authorize: HandleAuthorizeFn = async ({ identity: assertion }) => {\n const next = await verify(mount, assertion ?? null);\n if (\n next == null ||\n assertion == null ||\n next.providerId !== identity.providerId ||\n next.sandboxId !== identity.sandboxId ||\n next.organizationId !== identity.organizationId ||\n next.projectId !== identity.projectId\n )\n return null;\n caller = { token: assertion, identity: next };\n return { expiresAt: new Date(next.expiresAt).toISOString() };\n };\n channel.send(JSON.stringify(attached));\n serveSandboxHandle({\n sandbox: handle.sandbox,\n handle: lifecycle,\n authorize,\n access: { grant: FULL_SANDBOX_GRANT, lifecycle: true },\n mcpChannels: true,\n }).attach(preamble.rest());\n await preamble.closed;\n await lifecycle.onRuntimeShutdown().catch((cause: unknown) =>\n args.log?.('sandbox provider handle shutdown failed', {\n provider: mount.name,\n sandboxId: frame.sandboxId,\n error: cause instanceof Error ? cause.message : String(cause),\n }),\n );\n })();\n };\n\n return { fetch: fetchHandler, upgrade };\n};\n"],
|
|
5
|
+
"mappings": "AACA,SAAS,8CAA8C;AACvD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAIK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAOK;AACP,YAAY,OAAO;AACnB,SAAS,uBAAwD;AACjE,SAAS,8BAA8B,2BAA2B;AAClE,SAAS,0BAA0B;AACnC,SAAS,0BAAwE;AACjF,SAAS,oCAAoC;AAC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AAAA,QACjB,SAAS,OAAO;AAAA,QAChB,QAAQ;AAAA,QACR;AAAA,QACA,QAAQ,EAAE,OAAO,oBAAoB,WAAW,KAAK;AAAA,QACrD,aAAa;AAAA,MACf,CAAC,EAAE,OAAO,SAAS,KAAK,CAAC;AACzB,YAAM,SAAS;AACf,YAAM,UAAU,kBAAkB,EAAE;AAAA,QAAM,CAAC,UACzC,KAAK,MAAM,2CAA2C;AAAA,UACpD,UAAU,MAAM;AAAA,UAChB,WAAW,MAAM;AAAA,UACjB,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAAA,QAC9D,CAAC;AAAA,MACH;AAAA,IACF,GAAG;AAAA,EACL;AAEA,SAAO,EAAE,OAAO,cAAc,QAAQ;AACxC;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import * as z from 'zod';
|
|
2
|
-
import type { NetworkSandboxSessionIface
|
|
2
|
+
import type { NetworkSandboxSessionIface } from "../types.mjs";
|
|
3
3
|
import type { SandboxSetupIface } from "./schema.mjs";
|
|
4
4
|
export declare const SETUP_STEP_TIMEOUT_MS: number;
|
|
5
5
|
export declare enum SandboxSetupPhase {
|
|
@@ -27,7 +27,6 @@ export interface ApplySandboxSetupArgsIface {
|
|
|
27
27
|
fresh: boolean;
|
|
28
28
|
booted: boolean;
|
|
29
29
|
};
|
|
30
|
-
repositories: SandboxRepositoriesIface;
|
|
31
30
|
sandboxId: string;
|
|
32
31
|
saveState?: (state: SandboxSetupStateIface) => Promise<void>;
|
|
33
32
|
log?: (message: string, fields?: Record<string, string | number | boolean | null>) => void;
|
|
@@ -44,7 +44,6 @@ const resolveEnvironment = async (setup, secrets) => {
|
|
|
44
44
|
}
|
|
45
45
|
return { environment, secretValues };
|
|
46
46
|
};
|
|
47
|
-
const isGitUrl = (value) => /^(https?:\/\/|ssh:\/\/|git@)/.test(value);
|
|
48
47
|
const commandScript = (args) => [
|
|
49
48
|
"#!/bin/bash",
|
|
50
49
|
"set -eu",
|
|
@@ -92,44 +91,31 @@ const applySandboxSetup = async (args) => {
|
|
|
92
91
|
const ref = repository.ref ?? null;
|
|
93
92
|
const cloned = await handle.stat({ path: `${destination}/.git` }) != null;
|
|
94
93
|
if (cloned && ref == null) continue;
|
|
95
|
-
const source = await args.repositories.cloneSource({ repository: repository.repository, ref }) ?? (isGitUrl(repository.repository) ? { url: repository.repository, ref, authorization: null } : null);
|
|
96
|
-
if (source == null)
|
|
97
|
-
throw new Error(
|
|
98
|
-
`repository ${repository.repository} (${repository.alias}) is not one this project can reach`
|
|
99
|
-
);
|
|
100
|
-
const credential = source.authorization == null ? {} : {
|
|
101
|
-
GIT_CONFIG_COUNT: "1",
|
|
102
|
-
GIT_CONFIG_KEY_0: "http.extraHeader",
|
|
103
|
-
GIT_CONFIG_VALUE_0: `Authorization: ${source.authorization}`
|
|
104
|
-
};
|
|
105
94
|
const git = `git -C ${shellQuote(destination)}`;
|
|
106
|
-
const checkout =
|
|
107
|
-
`want=$(${git} rev-parse --verify --quiet ${shellQuote(`${
|
|
108
|
-
`if [ -z "$want" ] || [ "$(${git} rev-parse HEAD)" != "$want" ]; then ${git} checkout --quiet ${shellQuote(
|
|
95
|
+
const checkout = ref == null ? null : [
|
|
96
|
+
`want=$(${git} rev-parse --verify --quiet ${shellQuote(`${ref}^{commit}`)} || true)`,
|
|
97
|
+
`if [ -z "$want" ] || [ "$(${git} rev-parse HEAD)" != "$want" ]; then ${git} checkout --quiet ${shellQuote(ref)} 2>/dev/null || { ${git} fetch --quiet origin && ${git} checkout --quiet ${shellQuote(ref)}; }; fi`
|
|
109
98
|
].join("; ");
|
|
110
99
|
if (cloned && checkout == null) continue;
|
|
111
100
|
log("sandbox_setup.checkout", { alias: repository.alias });
|
|
112
|
-
const redact = scrubber(
|
|
113
|
-
source.authorization == null ? secretValues : [...secretValues, source.authorization]
|
|
114
|
-
);
|
|
115
101
|
const result = await handle.run({
|
|
116
102
|
command: [
|
|
117
103
|
"set -eu",
|
|
118
104
|
...cloned ? [] : [
|
|
119
105
|
`mkdir -p ${shellQuote(root)}`,
|
|
120
|
-
`git clone --quiet -- ${shellQuote(
|
|
106
|
+
`git clone --quiet -- ${shellQuote(repository.url)} ${shellQuote(destination)}`
|
|
121
107
|
],
|
|
122
108
|
...checkout == null ? [] : [checkout]
|
|
123
109
|
].join("; "),
|
|
124
110
|
shell: true,
|
|
125
111
|
// Paths are absolute; a sandbox may refuse `/` as outside it.
|
|
126
112
|
cwd: root,
|
|
127
|
-
env: { GIT_TERMINAL_PROMPT: "0"
|
|
113
|
+
env: { GIT_TERMINAL_PROMPT: "0" },
|
|
128
114
|
timeoutMs: SETUP_STEP_TIMEOUT_MS
|
|
129
115
|
});
|
|
130
116
|
if (result.exitCode !== 0)
|
|
131
117
|
throw new Error(
|
|
132
|
-
`checkout of ${repository.alias} failed (exit ${result.exitCode}): ${
|
|
118
|
+
`checkout of ${repository.alias} failed (exit ${result.exitCode}): ${scrub(result.stderr.trim()).slice(-2e3)}`
|
|
133
119
|
);
|
|
134
120
|
}
|
|
135
121
|
await finish("checkout" /* Checkout */);
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../src/sandbox/setup/apply.ts"],
|
|
4
|
-
"sourcesContent": ["import * as z from 'zod';\nimport { contentHash } from \"../../canonical-json.mjs\";\nimport { jsonValueSchema } from \"../../json.mjs\";\nimport type {\n NetworkSandboxSessionIface,\n SandboxRepositoriesIface,\n SandboxRunResultIface,\n} from \"../types.mjs\";\nimport { describeSandbox, SANDBOX_DESCRIPTION_PATH } from \"./describe.mjs\";\nimport { checkoutPath, commandPath, commandsDirectory, setupPath, setupRoot } from \"./paths.mjs\";\nimport type { SandboxSetupIface, SetupServiceIface } from \"./schema.mjs\";\n\n// The platform applies a sandbox setup through the standard handle, after the\n// provider reports the machine running. Each phase is idempotent and recorded\n// in the setup state the platform keeps with the sandbox, so a resumed sandbox\n// redoes only what its attach lost: a fresh disk redoes everything, a boot\n// restarts the services, a plain reconnect does nothing.\n//\n// Secrets reach process environments only. They are resolved on every apply,\n// passed as `env` to the commands that need them, never written to a file, the\n// state or a log line, and scrubbed from error text.\n\n// How long a checkout, or a setup step that names no timeout, may run.\nexport const SETUP_STEP_TIMEOUT_MS = 20 * 60_000;\n\nexport enum SandboxSetupPhase {\n Checkout = 'checkout',\n Commands = 'commands',\n Steps = 'steps',\n}\n\nexport const sandboxSetupStateSchema = z.object({\n // contentHash of the setup the recorded phases belong to.\n setup: z.string(),\n // Disk phases finished: they survive until the disk is replaced.\n done: z.array(z.nativeEnum(SandboxSetupPhase)).default([]),\n // Steps finished so far, in order; a retry resumes after them.\n steps: z.number().int().nonnegative().default(0),\n // Services started on the current boot.\n services: z.array(z.string()).default([]),\n});\n\nexport type SandboxSetupStateIface = z.output<typeof sandboxSetupStateSchema>;\n\nexport type SetupHandleIface = Pick<\n NetworkSandboxSessionIface,\n 'defaultWorkingDirectory' | 'run' | 'stat' | 'writeTextFile' | 'getPortUrl'\n>;\n\nexport interface SetupSecretsIface {\n // A project secret's value; null when it is not set.\n get(name: string): Promise<string | null>;\n}\n\nexport interface ApplySandboxSetupArgsIface {\n handle: SetupHandleIface;\n setup: SandboxSetupIface;\n secrets: SetupSecretsIface;\n // What the platform recorded for this sandbox; null before the first apply.\n state: SandboxSetupStateIface | null;\n // What the attach that produced `handle` reported (SandboxAttachmentIface).\n attachment: { fresh: boolean; booted: boolean };\n repositories: SandboxRepositoriesIface;\n // The platform's id for the sandbox, for its description.\n sandboxId: string;\n // Called after each phase or step, so progress survives a failure.\n saveState?: (state: SandboxSetupStateIface) => Promise<void>;\n log?: (message: string, fields?: Record<string, string | number | boolean | null>) => void;\n}\n\nexport interface AppliedSandboxSetupIface {\n state: SandboxSetupStateIface;\n // Every process in the sandbox gets these: the setup's variables with its\n // secrets resolved. In memory only; the platform merges them into\n // `platformEnvironment`.\n environment: Record<string, string>;\n // Where the setup's named commands are; the platform puts it on PATH so a\n // command runs by name.\n commandsDirectory: string;\n}\n\nconst shellQuote = (value: string): string => `'${value.replaceAll(\"'\", \"'\\\\''\")}'`;\n\n// Replaces every secret value in text bound for an error or a log.\nconst scrubber =\n (secrets: readonly string[]) =>\n (text: string): string =>\n secrets.reduce(\n (scrubbed, secret) => (secret.length < 4 ? scrubbed : scrubbed.replaceAll(secret, '****')),\n text,\n );\n\n// The setup's identity: phases recorded for one setup are not trusted for another.\nexport const setupHash = (setup: SandboxSetupIface): Promise<string> =>\n contentHash(jsonValueSchema.parse(JSON.parse(JSON.stringify(setup))));\n\nconst resolveEnvironment = async (\n setup: SandboxSetupIface,\n secrets: SetupSecretsIface,\n): Promise<{ environment: Record<string, string>; secretValues: string[] }> => {\n const environment: Record<string, string> = {};\n const secretValues: string[] = [];\n for (const [name, variable] of Object.entries(setup.variables)) {\n if ('value' in variable) {\n environment[name] = variable.value;\n continue;\n }\n const value = await secrets.get(variable.secret);\n if (value == null)\n throw new Error(\n `variable ${name} needs the project secret ${variable.secret}, which is not set`,\n );\n environment[name] = value;\n secretValues.push(value);\n }\n return { environment, secretValues };\n};\n\nconst isGitUrl = (value: string): boolean => /^(https?:\\/\\/|ssh:\\/\\/|git@)/.test(value);\n\nconst commandScript = (args: { name: string; cwd: string; run: string }): string =>\n [\n '#!/bin/bash',\n 'set -eu',\n `cd -- ${shellQuote(args.cwd)}`,\n `exec bash -c ${shellQuote(args.run)} ${shellQuote(args.name)} \"$@\"`,\n '',\n ].join('\\n');\n\nexport const applySandboxSetup = async (\n args: ApplySandboxSetupArgsIface,\n): Promise<AppliedSandboxSetupIface> => {\n const { handle, setup } = args;\n const log = args.log ?? (() => undefined);\n const hash = await setupHash(setup);\n const { environment, secretValues } = await resolveEnvironment(setup, args.secrets);\n const scrub = scrubber(secretValues);\n const root = setupRoot(handle);\n\n const recorded =\n args.state != null && args.state.setup === hash && !args.attachment.fresh ? args.state : null;\n let state: SandboxSetupStateIface = {\n setup: hash,\n done: recorded?.done ?? [],\n steps: recorded?.steps ?? 0,\n // A boot (or a new disk) stops every process: services start again.\n services: recorded == null || args.attachment.booted ? [] : recorded.services,\n };\n const save = async (next: SandboxSetupStateIface) => {\n state = next;\n await args.saveState?.(next);\n };\n const finish = (phase: SandboxSetupPhase) =>\n save({ ...state, done: state.done.includes(phase) ? state.done : [...state.done, phase] });\n\n const runOrThrow = async (\n label: string,\n options: Parameters<SetupHandleIface['run']>[0],\n ): Promise<SandboxRunResultIface> => {\n const result = await handle.run(options);\n if (result.exitCode !== 0)\n throw new Error(\n `${label} failed (exit ${result.exitCode}): ${scrub(result.stderr.trim()).slice(-2000)}`,\n );\n return result;\n };\n const requireDirectory = async (label: string, cwd: string | undefined): Promise<string> => {\n const path = setupPath(handle, cwd);\n if ((await handle.stat({ path })) == null)\n throw new Error(`${label} runs in ${path}, which does not exist`);\n return path;\n };\n\n if (!state.done.includes(SandboxSetupPhase.Checkout)) {\n for (const repository of setup.repositories) {\n const destination = checkoutPath(handle, repository.alias);\n const ref = repository.ref ?? null;\n const cloned = (await handle.stat({ path: `${destination}/.git` })) != null;\n // A clone with no ref to check out is done; one with a ref is checked\n // below, since an earlier attempt may have cloned and then failed.\n if (cloned && ref == null) continue;\n const source =\n (await args.repositories.cloneSource({ repository: repository.repository, ref })) ??\n (isGitUrl(repository.repository)\n ? { url: repository.repository, ref, authorization: null }\n : null);\n if (source == null)\n throw new Error(\n `repository ${repository.repository} (${repository.alias}) is not one this project can reach`,\n );\n // GIT_CONFIG_* applies the credential to this process only, never to the checkout's config.\n const credential: Record<string, string> =\n source.authorization == null\n ? {}\n : {\n GIT_CONFIG_COUNT: '1',\n GIT_CONFIG_KEY_0: 'http.extraHeader',\n GIT_CONFIG_VALUE_0: `Authorization: ${source.authorization}`,\n };\n const git = `git -C ${shellQuote(destination)}`;\n // Checks the ref out unless HEAD is already its commit; a ref the clone\n // lacks (added since) is fetched first.\n const checkout =\n source.ref == null\n ? null\n : [\n `want=$(${git} rev-parse --verify --quiet ${shellQuote(`${source.ref}^{commit}`)} || true)`,\n `if [ -z \"$want\" ] || [ \"$(${git} rev-parse HEAD)\" != \"$want\" ]; then ${git} checkout --quiet ${shellQuote(source.ref)} 2>/dev/null || { ${git} fetch --quiet origin && ${git} checkout --quiet ${shellQuote(source.ref)}; }; fi`,\n ].join('; ');\n if (cloned && checkout == null) continue;\n log('sandbox_setup.checkout', { alias: repository.alias });\n const redact = scrubber(\n source.authorization == null ? secretValues : [...secretValues, source.authorization],\n );\n const result = await handle.run({\n command: [\n 'set -eu',\n ...(cloned\n ? []\n : [\n `mkdir -p ${shellQuote(root)}`,\n `git clone --quiet -- ${shellQuote(source.url)} ${shellQuote(destination)}`,\n ]),\n ...(checkout == null ? [] : [checkout]),\n ].join('; '),\n shell: true,\n // Paths are absolute; a sandbox may refuse `/` as outside it.\n cwd: root,\n env: { GIT_TERMINAL_PROMPT: '0', ...credential },\n timeoutMs: SETUP_STEP_TIMEOUT_MS,\n });\n if (result.exitCode !== 0)\n throw new Error(\n `checkout of ${repository.alias} failed (exit ${result.exitCode}): ${redact(result.stderr.trim()).slice(-2000)}`,\n );\n }\n await finish(SandboxSetupPhase.Checkout);\n }\n\n if (!state.done.includes(SandboxSetupPhase.Commands)) {\n const names = Object.keys(setup.commands);\n for (const [name, command] of Object.entries(setup.commands))\n await handle.writeTextFile({\n path: commandPath(handle, name),\n content: commandScript({ name, cwd: setupPath(handle, command.cwd), run: command.run }),\n });\n if (names.length > 0)\n await runOrThrow('installing commands', {\n command: `chmod 0755 ${names.map((name) => shellQuote(commandPath(handle, name))).join(' ')}`,\n shell: true,\n cwd: root,\n timeoutMs: 60_000,\n });\n await finish(SandboxSetupPhase.Commands);\n }\n\n if (!state.done.includes(SandboxSetupPhase.Steps)) {\n for (const [index, step] of setup.steps.entries()) {\n if (index < state.steps) continue;\n const label = `setup step ${index + 1}${step.name == null ? '' : ` (${step.name})`}`;\n log('sandbox_setup.step', { index });\n const run = async () =>\n runOrThrow(label, {\n command: `set -eu\\n${step.run}`,\n shell: true,\n cwd: await requireDirectory(label, step.cwd),\n env: environment,\n timeoutMs:\n step.timeoutSeconds == null ? SETUP_STEP_TIMEOUT_MS : step.timeoutSeconds * 1000,\n });\n if (step.optional === true)\n await run().catch(() => log('sandbox_setup.optional_step_failed', { index }));\n else await run();\n await save({ ...state, steps: index + 1 });\n }\n await finish(SandboxSetupPhase.Steps);\n }\n\n const startService = async (service: SetupServiceIface): Promise<void> => {\n const label = `service ${service.name}`;\n const logFile = `${root}/.final/services/${service.name}.log`;\n // Detached from this call: a service outlives the connection that started it.\n await runOrThrow(`starting ${label}`, {\n command: `mkdir -p ${shellQuote(`${root}/.final/services`)} && nohup bash -lc ${shellQuote(service.run)} >${shellQuote(logFile)} 2>&1 </dev/null &`,\n shell: true,\n cwd: await requireDirectory(label, service.cwd),\n env: environment,\n timeoutMs: 60_000,\n });\n log('sandbox_setup.service_started', { service: service.name });\n };\n // Each service is recorded as it starts, so a retry on the same boot starts\n // only the ones that had not.\n for (const service of setup.services) {\n if (state.services.includes(service.name)) continue;\n await startService(service);\n await save({ ...state, services: [...state.services, service.name] });\n }\n\n const description = await describeSandbox({ handle, setup, sandboxId: args.sandboxId });\n await handle.writeTextFile({\n path: setupPath(handle, SANDBOX_DESCRIPTION_PATH),\n content: description.markdown,\n });\n return { state, environment, commandsDirectory: commandsDirectory(handle) };\n};\n"],
|
|
5
|
-
"mappings": "AAAA,YAAY,OAAO;AACnB,SAAS,mBAAmB;AAC5B,SAAS,uBAAuB;
|
|
4
|
+
"sourcesContent": ["import * as z from 'zod';\nimport { contentHash } from \"../../canonical-json.mjs\";\nimport { jsonValueSchema } from \"../../json.mjs\";\nimport type { NetworkSandboxSessionIface, SandboxRunResultIface } from \"../types.mjs\";\nimport { describeSandbox, SANDBOX_DESCRIPTION_PATH } from \"./describe.mjs\";\nimport { checkoutPath, commandPath, commandsDirectory, setupPath, setupRoot } from \"./paths.mjs\";\nimport type { SandboxSetupIface, SetupServiceIface } from \"./schema.mjs\";\n\n// The platform applies a sandbox setup through the standard handle, after the\n// provider reports the machine running. Each phase is idempotent and recorded\n// in the setup state the platform keeps with the sandbox, so a resumed sandbox\n// redoes only what its attach lost: a fresh disk redoes everything, a boot\n// restarts the services, a plain reconnect does nothing.\n//\n// Secrets reach process environments only. They are resolved on every apply,\n// passed as `env` to the commands that need them, never written to a file, the\n// state or a log line, and scrubbed from error text.\n\n// How long a checkout, or a setup step that names no timeout, may run.\nexport const SETUP_STEP_TIMEOUT_MS = 20 * 60_000;\n\nexport enum SandboxSetupPhase {\n Checkout = 'checkout',\n Commands = 'commands',\n Steps = 'steps',\n}\n\nexport const sandboxSetupStateSchema = z.object({\n // contentHash of the setup the recorded phases belong to.\n setup: z.string(),\n // Disk phases finished: they survive until the disk is replaced.\n done: z.array(z.nativeEnum(SandboxSetupPhase)).default([]),\n // Steps finished so far, in order; a retry resumes after them.\n steps: z.number().int().nonnegative().default(0),\n // Services started on the current boot.\n services: z.array(z.string()).default([]),\n});\n\nexport type SandboxSetupStateIface = z.output<typeof sandboxSetupStateSchema>;\n\nexport type SetupHandleIface = Pick<\n NetworkSandboxSessionIface,\n 'defaultWorkingDirectory' | 'run' | 'stat' | 'writeTextFile' | 'getPortUrl'\n>;\n\nexport interface SetupSecretsIface {\n // A project secret's value; null when it is not set.\n get(name: string): Promise<string | null>;\n}\n\nexport interface ApplySandboxSetupArgsIface {\n handle: SetupHandleIface;\n setup: SandboxSetupIface;\n secrets: SetupSecretsIface;\n // What the platform recorded for this sandbox; null before the first apply.\n state: SandboxSetupStateIface | null;\n // What the attach that produced `handle` reported (SandboxAttachmentIface).\n attachment: { fresh: boolean; booted: boolean };\n // The platform's id for the sandbox, for its description.\n sandboxId: string;\n // Called after each phase or step, so progress survives a failure.\n saveState?: (state: SandboxSetupStateIface) => Promise<void>;\n log?: (message: string, fields?: Record<string, string | number | boolean | null>) => void;\n}\n\nexport interface AppliedSandboxSetupIface {\n state: SandboxSetupStateIface;\n // Every process in the sandbox gets these: the setup's variables with its\n // secrets resolved. In memory only; the platform merges them into\n // `platformEnvironment`.\n environment: Record<string, string>;\n // Where the setup's named commands are; the platform puts it on PATH so a\n // command runs by name.\n commandsDirectory: string;\n}\n\nconst shellQuote = (value: string): string => `'${value.replaceAll(\"'\", \"'\\\\''\")}'`;\n\n// Replaces every secret value in text bound for an error or a log.\nconst scrubber =\n (secrets: readonly string[]) =>\n (text: string): string =>\n secrets.reduce(\n (scrubbed, secret) => (secret.length < 4 ? scrubbed : scrubbed.replaceAll(secret, '****')),\n text,\n );\n\n// The setup's identity: phases recorded for one setup are not trusted for another.\nexport const setupHash = (setup: SandboxSetupIface): Promise<string> =>\n contentHash(jsonValueSchema.parse(JSON.parse(JSON.stringify(setup))));\n\nconst resolveEnvironment = async (\n setup: SandboxSetupIface,\n secrets: SetupSecretsIface,\n): Promise<{ environment: Record<string, string>; secretValues: string[] }> => {\n const environment: Record<string, string> = {};\n const secretValues: string[] = [];\n for (const [name, variable] of Object.entries(setup.variables)) {\n if ('value' in variable) {\n environment[name] = variable.value;\n continue;\n }\n const value = await secrets.get(variable.secret);\n if (value == null)\n throw new Error(\n `variable ${name} needs the project secret ${variable.secret}, which is not set`,\n );\n environment[name] = value;\n secretValues.push(value);\n }\n return { environment, secretValues };\n};\n\nconst commandScript = (args: { name: string; cwd: string; run: string }): string =>\n [\n '#!/bin/bash',\n 'set -eu',\n `cd -- ${shellQuote(args.cwd)}`,\n `exec bash -c ${shellQuote(args.run)} ${shellQuote(args.name)} \"$@\"`,\n '',\n ].join('\\n');\n\nexport const applySandboxSetup = async (\n args: ApplySandboxSetupArgsIface,\n): Promise<AppliedSandboxSetupIface> => {\n const { handle, setup } = args;\n const log = args.log ?? (() => undefined);\n const hash = await setupHash(setup);\n const { environment, secretValues } = await resolveEnvironment(setup, args.secrets);\n const scrub = scrubber(secretValues);\n const root = setupRoot(handle);\n\n const recorded =\n args.state != null && args.state.setup === hash && !args.attachment.fresh ? args.state : null;\n let state: SandboxSetupStateIface = {\n setup: hash,\n done: recorded?.done ?? [],\n steps: recorded?.steps ?? 0,\n // A boot (or a new disk) stops every process: services start again.\n services: recorded == null || args.attachment.booted ? [] : recorded.services,\n };\n const save = async (next: SandboxSetupStateIface) => {\n state = next;\n await args.saveState?.(next);\n };\n const finish = (phase: SandboxSetupPhase) =>\n save({ ...state, done: state.done.includes(phase) ? state.done : [...state.done, phase] });\n\n const runOrThrow = async (\n label: string,\n options: Parameters<SetupHandleIface['run']>[0],\n ): Promise<SandboxRunResultIface> => {\n const result = await handle.run(options);\n if (result.exitCode !== 0)\n throw new Error(\n `${label} failed (exit ${result.exitCode}): ${scrub(result.stderr.trim()).slice(-2000)}`,\n );\n return result;\n };\n const requireDirectory = async (label: string, cwd: string | undefined): Promise<string> => {\n const path = setupPath(handle, cwd);\n if ((await handle.stat({ path })) == null)\n throw new Error(`${label} runs in ${path}, which does not exist`);\n return path;\n };\n\n if (!state.done.includes(SandboxSetupPhase.Checkout)) {\n for (const repository of setup.repositories) {\n const destination = checkoutPath(handle, repository.alias);\n const ref = repository.ref ?? null;\n const cloned = (await handle.stat({ path: `${destination}/.git` })) != null;\n // A clone with no ref to check out is done; one with a ref is checked\n // below, since an earlier attempt may have cloned and then failed.\n if (cloned && ref == null) continue;\n const git = `git -C ${shellQuote(destination)}`;\n // Checks the ref out unless HEAD is already its commit; a ref the clone\n // lacks (added since) is fetched first.\n const checkout =\n ref == null\n ? null\n : [\n `want=$(${git} rev-parse --verify --quiet ${shellQuote(`${ref}^{commit}`)} || true)`,\n `if [ -z \"$want\" ] || [ \"$(${git} rev-parse HEAD)\" != \"$want\" ]; then ${git} checkout --quiet ${shellQuote(ref)} 2>/dev/null || { ${git} fetch --quiet origin && ${git} checkout --quiet ${shellQuote(ref)}; }; fi`,\n ].join('; ');\n if (cloned && checkout == null) continue;\n // The clone carries no credential: the sandbox's egress adds one for the URL's host,\n // when an integration serving it is provided.\n log('sandbox_setup.checkout', { alias: repository.alias });\n const result = await handle.run({\n command: [\n 'set -eu',\n ...(cloned\n ? []\n : [\n `mkdir -p ${shellQuote(root)}`,\n `git clone --quiet -- ${shellQuote(repository.url)} ${shellQuote(destination)}`,\n ]),\n ...(checkout == null ? [] : [checkout]),\n ].join('; '),\n shell: true,\n // Paths are absolute; a sandbox may refuse `/` as outside it.\n cwd: root,\n env: { GIT_TERMINAL_PROMPT: '0' },\n timeoutMs: SETUP_STEP_TIMEOUT_MS,\n });\n if (result.exitCode !== 0)\n throw new Error(\n `checkout of ${repository.alias} failed (exit ${result.exitCode}): ${scrub(result.stderr.trim()).slice(-2000)}`,\n );\n }\n await finish(SandboxSetupPhase.Checkout);\n }\n\n if (!state.done.includes(SandboxSetupPhase.Commands)) {\n const names = Object.keys(setup.commands);\n for (const [name, command] of Object.entries(setup.commands))\n await handle.writeTextFile({\n path: commandPath(handle, name),\n content: commandScript({ name, cwd: setupPath(handle, command.cwd), run: command.run }),\n });\n if (names.length > 0)\n await runOrThrow('installing commands', {\n command: `chmod 0755 ${names.map((name) => shellQuote(commandPath(handle, name))).join(' ')}`,\n shell: true,\n cwd: root,\n timeoutMs: 60_000,\n });\n await finish(SandboxSetupPhase.Commands);\n }\n\n if (!state.done.includes(SandboxSetupPhase.Steps)) {\n for (const [index, step] of setup.steps.entries()) {\n if (index < state.steps) continue;\n const label = `setup step ${index + 1}${step.name == null ? '' : ` (${step.name})`}`;\n log('sandbox_setup.step', { index });\n const run = async () =>\n runOrThrow(label, {\n command: `set -eu\\n${step.run}`,\n shell: true,\n cwd: await requireDirectory(label, step.cwd),\n env: environment,\n timeoutMs:\n step.timeoutSeconds == null ? SETUP_STEP_TIMEOUT_MS : step.timeoutSeconds * 1000,\n });\n if (step.optional === true)\n await run().catch(() => log('sandbox_setup.optional_step_failed', { index }));\n else await run();\n await save({ ...state, steps: index + 1 });\n }\n await finish(SandboxSetupPhase.Steps);\n }\n\n const startService = async (service: SetupServiceIface): Promise<void> => {\n const label = `service ${service.name}`;\n const logFile = `${root}/.final/services/${service.name}.log`;\n // Detached from this call: a service outlives the connection that started it.\n await runOrThrow(`starting ${label}`, {\n command: `mkdir -p ${shellQuote(`${root}/.final/services`)} && nohup bash -lc ${shellQuote(service.run)} >${shellQuote(logFile)} 2>&1 </dev/null &`,\n shell: true,\n cwd: await requireDirectory(label, service.cwd),\n env: environment,\n timeoutMs: 60_000,\n });\n log('sandbox_setup.service_started', { service: service.name });\n };\n // Each service is recorded as it starts, so a retry on the same boot starts\n // only the ones that had not.\n for (const service of setup.services) {\n if (state.services.includes(service.name)) continue;\n await startService(service);\n await save({ ...state, services: [...state.services, service.name] });\n }\n\n const description = await describeSandbox({ handle, setup, sandboxId: args.sandboxId });\n await handle.writeTextFile({\n path: setupPath(handle, SANDBOX_DESCRIPTION_PATH),\n content: description.markdown,\n });\n return { state, environment, commandsDirectory: commandsDirectory(handle) };\n};\n"],
|
|
5
|
+
"mappings": "AAAA,YAAY,OAAO;AACnB,SAAS,mBAAmB;AAC5B,SAAS,uBAAuB;AAEhC,SAAS,iBAAiB,gCAAgC;AAC1D,SAAS,cAAc,aAAa,mBAAmB,WAAW,iBAAiB;AAc5E,MAAM,wBAAwB,KAAK;AAEnC,IAAK,oBAAL,kBAAKA,uBAAL;AACL,EAAAA,mBAAA,cAAW;AACX,EAAAA,mBAAA,cAAW;AACX,EAAAA,mBAAA,WAAQ;AAHE,SAAAA;AAAA,GAAA;AAML,MAAM,0BAA0B,EAAE,OAAO;AAAA;AAAA,EAE9C,OAAO,EAAE,OAAO;AAAA;AAAA,EAEhB,MAAM,EAAE,MAAM,EAAE,WAAW,iBAAiB,CAAC,EAAE,QAAQ,CAAC,CAAC;AAAA;AAAA,EAEzD,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,YAAY,EAAE,QAAQ,CAAC;AAAA;AAAA,EAE/C,UAAU,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,QAAQ,CAAC,CAAC;AAC1C,CAAC;AAwCD,MAAM,aAAa,CAAC,UAA0B,IAA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,UAAU,GAAG,IAAI,oBAAoB,QAAQ,IAAI;AAEvD,UAAM,WAAW,YAAY,KAAK,IAAI;AAAA,MACpC,SAAS,YAAY,WAAW,GAAG,IAAI,kBAAkB,CAAC,sBAAsB,WAAW,QAAQ,GAAG,CAAC,KAAK,WAAW,OAAO,CAAC;AAAA,MAC/H,OAAO;AAAA,MACP,KAAK,MAAM,iBAAiB,OAAO,QAAQ,GAAG;AAAA,MAC9C,KAAK;AAAA,MACL,WAAW;AAAA,IACb,CAAC;AACD,QAAI,iCAAiC,EAAE,SAAS,QAAQ,KAAK,CAAC;AAAA,EAChE;AAGA,aAAW,WAAW,MAAM,UAAU;AACpC,QAAI,MAAM,SAAS,SAAS,QAAQ,IAAI,EAAG;AAC3C,UAAM,aAAa,OAAO;AAC1B,UAAM,KAAK,EAAE,GAAG,OAAO,UAAU,CAAC,GAAG,MAAM,UAAU,QAAQ,IAAI,EAAE,CAAC;AAAA,EACtE;AAEA,QAAM,cAAc,MAAM,gBAAgB,EAAE,QAAQ,OAAO,WAAW,KAAK,UAAU,CAAC;AACtF,QAAM,OAAO,cAAc;AAAA,IACzB,MAAM,UAAU,QAAQ,wBAAwB;AAAA,IAChD,SAAS,YAAY;AAAA,EACvB,CAAC;AACD,SAAO,EAAE,OAAO,aAAa,mBAAmB,kBAAkB,MAAM,EAAE;AAC5E;",
|
|
6
6
|
"names": ["SandboxSetupPhase"]
|
|
7
7
|
}
|
|
@@ -42,7 +42,7 @@ const describeSandbox = async (args) => {
|
|
|
42
42
|
workspace: setupRoot(handle),
|
|
43
43
|
checkouts: (setup?.repositories ?? []).map((repository) => ({
|
|
44
44
|
alias: repository.alias,
|
|
45
|
-
repository: repository.
|
|
45
|
+
repository: repository.url,
|
|
46
46
|
ref: repository.ref ?? null,
|
|
47
47
|
path: checkoutPath(handle, repository.alias)
|
|
48
48
|
})),
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../src/sandbox/setup/describe.ts"],
|
|
4
|
-
"sourcesContent": ["import type { SandboxDescriptionIface } from '@finalai/agent-protocol/agent-platform';\nimport type { NetworkSandboxSessionIface } from \"../types.mjs\";\nimport { checkoutPath, setupRoot } from \"./paths.mjs\";\nimport type { SandboxSetupIface } from \"./schema.mjs\";\n\n// What is known about a sandbox once its setup is applied: where each\n// repository really is, the URL of each service, the commands it can run by\n// name and the setup's notes, in the shape `GET \u2026/sandboxes/:id/description`\n// answers. The markdown is also written into the sandbox as\n// SANDBOX_DESCRIPTION_PATH. Nothing puts it into an agent's context; a caller\n// that wants it there adds it to the instructions.\n\nexport type { SandboxDescriptionIface } from '@finalai/agent-protocol/agent-platform';\n\n// Relative to the working directory.\nexport const SANDBOX_DESCRIPTION_PATH = '.final/sandbox.md';\n\nconst renderMarkdown = (\n description: Omit<SandboxDescriptionIface, 'markdown'>,\n commandDescriptions: Partial<Record<string, string>>,\n): string => {\n const lines = ['# This sandbox'];\n if (description.workspace != null)\n lines.push('', `Working directory: \\`${description.workspace}\\``);\n if (description.checkouts.length > 0) {\n lines.push('', '## Repositories', '');\n for (const checkout of description.checkouts)\n lines.push(\n `- \\`${checkout.path}\\`: ${checkout.repository}${checkout.ref == null ? '' : ` at ${checkout.ref}`}`,\n );\n }\n if (description.services.length > 0) {\n lines.push('', '## Services', '');\n for (const service of description.services) {\n const where = service.url ?? (service.port == null ? null : `port ${service.port}`);\n lines.push(`- ${service.name}${where == null ? '' : `: ${where}`}`);\n }\n }\n if (description.commands.length > 0) {\n lines.push('', '## Commands', '');\n for (const command of description.commands) {\n const about = commandDescriptions[command];\n lines.push(`- \\`${command}\\`${about == null ? '' : `: ${about}`}`);\n }\n }\n if (description.notes != null) lines.push('', '## Notes', '', description.notes);\n return `${lines.join('\\n')}\\n`;\n};\n\nexport const describeSandbox = async (args: {\n handle: Pick<NetworkSandboxSessionIface, 'defaultWorkingDirectory' | 'getPortUrl'>;\n setup: SandboxSetupIface | null;\n sandboxId: string;\n}): Promise<SandboxDescriptionIface> => {\n const { handle } = args;\n const setup = args.setup;\n const services: SandboxDescriptionIface['services'] = [];\n for (const service of setup?.services ?? []) {\n const url =\n service.port == null\n ? null\n : await handle.getPortUrl({ port: service.port }).catch(() => null);\n services.push({ name: service.name, port: service.port ?? null, url });\n }\n const description: Omit<SandboxDescriptionIface, 'markdown'> = {\n sandboxId: args.sandboxId,\n workspace: setupRoot(handle),\n checkouts: (setup?.repositories ?? []).map((repository) => ({\n alias: repository.alias,\n repository: repository.
|
|
4
|
+
"sourcesContent": ["import type { SandboxDescriptionIface } from '@finalai/agent-protocol/agent-platform';\nimport type { NetworkSandboxSessionIface } from \"../types.mjs\";\nimport { checkoutPath, setupRoot } from \"./paths.mjs\";\nimport type { SandboxSetupIface } from \"./schema.mjs\";\n\n// What is known about a sandbox once its setup is applied: where each\n// repository really is, the URL of each service, the commands it can run by\n// name and the setup's notes, in the shape `GET \u2026/sandboxes/:id/description`\n// answers. The markdown is also written into the sandbox as\n// SANDBOX_DESCRIPTION_PATH. Nothing puts it into an agent's context; a caller\n// that wants it there adds it to the instructions.\n\nexport type { SandboxDescriptionIface } from '@finalai/agent-protocol/agent-platform';\n\n// Relative to the working directory.\nexport const SANDBOX_DESCRIPTION_PATH = '.final/sandbox.md';\n\nconst renderMarkdown = (\n description: Omit<SandboxDescriptionIface, 'markdown'>,\n commandDescriptions: Partial<Record<string, string>>,\n): string => {\n const lines = ['# This sandbox'];\n if (description.workspace != null)\n lines.push('', `Working directory: \\`${description.workspace}\\``);\n if (description.checkouts.length > 0) {\n lines.push('', '## Repositories', '');\n for (const checkout of description.checkouts)\n lines.push(\n `- \\`${checkout.path}\\`: ${checkout.repository}${checkout.ref == null ? '' : ` at ${checkout.ref}`}`,\n );\n }\n if (description.services.length > 0) {\n lines.push('', '## Services', '');\n for (const service of description.services) {\n const where = service.url ?? (service.port == null ? null : `port ${service.port}`);\n lines.push(`- ${service.name}${where == null ? '' : `: ${where}`}`);\n }\n }\n if (description.commands.length > 0) {\n lines.push('', '## Commands', '');\n for (const command of description.commands) {\n const about = commandDescriptions[command];\n lines.push(`- \\`${command}\\`${about == null ? '' : `: ${about}`}`);\n }\n }\n if (description.notes != null) lines.push('', '## Notes', '', description.notes);\n return `${lines.join('\\n')}\\n`;\n};\n\nexport const describeSandbox = async (args: {\n handle: Pick<NetworkSandboxSessionIface, 'defaultWorkingDirectory' | 'getPortUrl'>;\n setup: SandboxSetupIface | null;\n sandboxId: string;\n}): Promise<SandboxDescriptionIface> => {\n const { handle } = args;\n const setup = args.setup;\n const services: SandboxDescriptionIface['services'] = [];\n for (const service of setup?.services ?? []) {\n const url =\n service.port == null\n ? null\n : await handle.getPortUrl({ port: service.port }).catch(() => null);\n services.push({ name: service.name, port: service.port ?? null, url });\n }\n const description: Omit<SandboxDescriptionIface, 'markdown'> = {\n sandboxId: args.sandboxId,\n workspace: setupRoot(handle),\n checkouts: (setup?.repositories ?? []).map((repository) => ({\n alias: repository.alias,\n repository: repository.url,\n ref: repository.ref ?? null,\n path: checkoutPath(handle, repository.alias),\n })),\n services,\n commands: Object.keys(setup?.commands ?? {}),\n notes: setup?.notes ?? null,\n };\n const commandDescriptions: Partial<Record<string, string>> = {};\n for (const [name, command] of Object.entries(setup?.commands ?? {}))\n if (command.description != null) commandDescriptions[name] = command.description;\n return { ...description, markdown: renderMarkdown(description, commandDescriptions) };\n};\n"],
|
|
5
5
|
"mappings": "AAEA,SAAS,cAAc,iBAAiB;AAajC,MAAM,2BAA2B;AAExC,MAAM,iBAAiB,CACrB,aACA,wBACW;AACX,QAAM,QAAQ,CAAC,gBAAgB;AAC/B,MAAI,YAAY,aAAa;AAC3B,UAAM,KAAK,IAAI,wBAAwB,YAAY,SAAS,IAAI;AAClE,MAAI,YAAY,UAAU,SAAS,GAAG;AACpC,UAAM,KAAK,IAAI,mBAAmB,EAAE;AACpC,eAAW,YAAY,YAAY;AACjC,YAAM;AAAA,QACJ,OAAO,SAAS,IAAI,OAAO,SAAS,UAA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C,gBAAgB;AAAA,MAC1D,OAAO,WAAW;AAAA,MAClB,YAAY,WAAW;AAAA,MACvB,KAAK,WAAW,OAAO;AAAA,MACvB,MAAM,aAAa,QAAQ,WAAW,KAAK;AAAA,IAC7C,EAAE;AAAA,IACF;AAAA,IACA,UAAU,OAAO,KAAK,OAAO,YAAY,CAAC,CAAC;AAAA,IAC3C,OAAO,OAAO,SAAS;AAAA,EACzB;AACA,QAAM,sBAAuD,CAAC;AAC9D,aAAW,CAAC,MAAM,OAAO,KAAK,OAAO,QAAQ,OAAO,YAAY,CAAC,CAAC;AAChE,QAAI,QAAQ,eAAe,KAAM,qBAAoB,IAAI,IAAI,QAAQ;AACvE,SAAO,EAAE,GAAG,aAAa,UAAU,eAAe,aAAa,mBAAmB,EAAE;AACtF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -8,8 +8,9 @@ export declare const SETUP_ROOT_CWD = ".";
|
|
|
8
8
|
export declare const sandboxSetupSchema: import("zod").ZodObject<{
|
|
9
9
|
repositories: import("zod").ZodDefault<import("zod").ZodArray<import("zod").ZodObject<{
|
|
10
10
|
alias: import("zod").ZodString;
|
|
11
|
-
|
|
11
|
+
url: import("zod").ZodString;
|
|
12
12
|
ref: import("zod").ZodOptional<import("zod").ZodString>;
|
|
13
|
+
integration: import("zod").ZodOptional<import("zod").ZodString>;
|
|
13
14
|
}, import("zod/v4/core").$strict>>>;
|
|
14
15
|
variables: import("zod").ZodDefault<import("zod").ZodRecord<import("zod").ZodString, import("zod").ZodUnion<readonly [import("zod").ZodObject<{
|
|
15
16
|
value: import("zod").ZodString;
|
|
@@ -239,18 +239,6 @@ export interface SandboxProviderHandleIface<S extends SandboxSessionIface> {
|
|
|
239
239
|
}): Promise<void>;
|
|
240
240
|
onRuntimeShutdown(): Promise<void>;
|
|
241
241
|
}
|
|
242
|
-
export interface SandboxRepositoryCloneSourceIface {
|
|
243
|
-
url: string;
|
|
244
|
-
ref: string | null;
|
|
245
|
-
authorization: string | null;
|
|
246
|
-
}
|
|
247
|
-
export interface SandboxRepositoriesIface {
|
|
248
|
-
cloneSource(args: {
|
|
249
|
-
repository: string;
|
|
250
|
-
ref: string | null;
|
|
251
|
-
}): Promise<SandboxRepositoryCloneSourceIface | null>;
|
|
252
|
-
}
|
|
253
|
-
export declare const noSandboxRepositories: SandboxRepositoriesIface;
|
|
254
242
|
export interface SandboxActingUserIface {
|
|
255
243
|
current(): Promise<string | null>;
|
|
256
244
|
}
|
|
@@ -40,9 +40,6 @@ var SandboxCapability = /* @__PURE__ */ ((SandboxCapability2) => {
|
|
|
40
40
|
SandboxCapability2["Workers"] = "workers";
|
|
41
41
|
return SandboxCapability2;
|
|
42
42
|
})(SandboxCapability || {});
|
|
43
|
-
const noSandboxRepositories = {
|
|
44
|
-
cloneSource: async () => null
|
|
45
|
-
};
|
|
46
43
|
const noSandboxActingUser = { current: async () => null };
|
|
47
44
|
const noSandboxCredentials = { secret: async () => null };
|
|
48
45
|
const sandboxCredentialRefSchema = z.strictObject({
|
|
@@ -64,9 +61,7 @@ const PLATFORM_ENVIRONMENT_NAMES = /* @__PURE__ */ new Set([
|
|
|
64
61
|
"DENO_CERT",
|
|
65
62
|
"NODE_EXTRA_CA_CERTS",
|
|
66
63
|
"FINAL_EGRESS_URL",
|
|
67
|
-
"FINAL_EGRESS_TOKEN"
|
|
68
|
-
"GH_TOKEN",
|
|
69
|
-
"GITHUB_TOKEN"
|
|
64
|
+
"FINAL_EGRESS_TOKEN"
|
|
70
65
|
]);
|
|
71
66
|
const platformProcessEnvironment = (ctx, specEnv) => async () => ({ ...specEnv, ...await ctx.platformEnvironment?.() });
|
|
72
67
|
const writePlatformFiles = async (ctx, sandbox) => {
|
|
@@ -154,7 +149,6 @@ export {
|
|
|
154
149
|
noSandboxActingUser,
|
|
155
150
|
noSandboxCredentials,
|
|
156
151
|
noSandboxIdentity,
|
|
157
|
-
noSandboxRepositories,
|
|
158
152
|
platformProcessEnvironment,
|
|
159
153
|
reportPlatformNetworkPolicy,
|
|
160
154
|
sandboxCredentialRefSchema,
|