@finalai/agent-provider 0.1.5 → 0.1.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/HOSTING.md +49 -9
- package/dist/modules/conformance/sandbox-kit.d.mts +8 -0
- package/dist/modules/conformance/sandbox-kit.mjs +228 -6
- package/dist/modules/conformance/sandbox-kit.mjs.map +2 -2
- package/dist/modules/harness.mjs +2 -1
- package/dist/modules/harness.mjs.map +2 -2
- package/dist/modules/sandbox/memory-sandbox.d.mts +1 -0
- package/dist/modules/sandbox/memory-sandbox.mjs +37 -10
- package/dist/modules/sandbox/memory-sandbox.mjs.map +2 -2
- package/dist/modules/sandbox/memory-shell.d.mts +1 -0
- package/dist/modules/sandbox/memory-shell.mjs +14 -0
- package/dist/modules/sandbox/memory-shell.mjs.map +2 -2
- package/dist/modules/sandbox/types.d.mts +13 -1
- package/dist/modules/sandbox/types.mjs +47 -2
- package/dist/modules/sandbox/types.mjs.map +2 -2
- package/dist/modules/schemas.mjs +1 -1
- package/dist/modules/schemas.mjs.map +1 -1
- package/package.json +1 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/harness.ts"],
|
|
4
|
-
"sourcesContent": ["import type { McpServer } from '@agentclientprotocol/sdk/experimental/v2';\nimport * as z from 'zod';\nimport { CredentialRoute, routeGrantSchema, type RouteGrantIface } from \"./credential-routes.mjs\";\nimport { CredentialDelivery, InferenceCredentialKind } from \"./credentials.mjs\";\nimport type { JsonSchema, JsonValue } from \"./json.mjs\";\nimport type { HostedBindingsIface } from \"./hosted-bindings.mjs\";\nimport { jsonObjectSchema, jsonSchemaSchema } from \"./json.mjs\";\nimport { BaseCapability, InstructionRole, type ResolvedAgentManifestIface } from \"./manifest.mjs\";\nimport { bundleRef, providerRefSchema, type ProviderRef } from \"./provider-ref.mjs\";\nimport { referencedSharedSchemas, SCHEMA_IDS } from \"./schemas.mjs\";\n\n// Placeholder export name the compiler replaces with the defining module's path.\nexport const PENDING_BUNDLE_EXPORT = '<pending>';\n\n// A harness is a specific ACP agent program together with how to reach it. Hosting is part of what a harness is, so there is no\n// engine parameter: \"Pi on Final's serverless runtime\" and \"Pi on a server you\n// run\" are two harnesses. The hosting half is deliberately small; everything\n// about what the agent does goes over ACP v2.\n\nexport enum AcpTransport {\n Relay = 'relay',\n Ws = 'ws',\n Http = 'http',\n Stdio = 'stdio',\n}\n\nexport enum McpTransportKind {\n Acp = 'acp',\n Http = 'http',\n Stdio = 'stdio',\n}\n\n// How a harness provides one base capability.\nexport enum BaseToolProvision {\n // Routed to the declared sandbox target.\n Bound = 'bound',\n // Native on the harness's host and switchable through its own allow-lists.\n HostDisableable = 'host-disableable',\n // Native on the harness's host and not switchable.\n HostFixed = 'host-fixed',\n}\n\n// SDK wires a harness speaks to reach a bound sandbox target.\nexport enum SandboxWire {\n HandleRpc = 'handle-rpc',\n Mcp = 'mcp',\n}\n\nexport enum UserInstructionDelivery {\n History = 'history',\n System = 'system',\n}\n\n// Who operates the place a harness's credentials land. Every\n// harness, Final's included, gets the same grant forms; a subscription goes to\n// a third-party harness only when its owner allowed third-party harnesses.\n// Only installed provider packages may declare first-party; a bundle-declared\n// harness is third-party whatever it declares.\nexport enum HarnessTrustClass {\n // The provider operates the harness on infrastructure it runs (Final's serverless harnesses).\n FirstParty = 'first-party',\n // Someone else's host or program (remote hosts, external ACP agents, local processes).\n ThirdParty = 'third-party',\n}\n\n// What an accepted session/prompt does while the session is running. Both are valid; refusing one is a conformance failure.\nexport enum PromptWhileRunning {\n // Joins the running work: the model sees it at its next step.\n Inject = 'inject',\n // Runs after the current work goes idle; dropped by session/cancel if not started.\n Queue = 'queue',\n}\n\n// Defaults for a description that does not declare the hosting contract's\n// newer fields (bundle harnesses, older registrations): the session service\n// then assumes nothing survives a dropped connection and that a prompt while\n// running waits for idle.\nexport const DEFAULT_PROMPT_WHILE_RUNNING = PromptWhileRunning.Queue;\nexport const DEFAULT_SESSION_SURVIVES_DISCONNECT = false;\n\nexport const baseToolDeclarationSchema = z.object({\n provision: z.nativeEnum(BaseToolProvision),\n nativeTools: z.array(z.string()),\n});\n\nexport const harnessDescriptionSchema = z.object({\n // Everything configurable about this harness (model, reasoning, credentials,\n // permission mode, instructions, skills, cwd, ...). JSON Schema so Build can\n // render it; may $ref the shared final://schemas/* fragments.\n configSchema: jsonSchemaSchema,\n // Absent: user fragments enter history. System-only programs declare their conversion.\n userInstructionDelivery: z.nativeEnum(UserInstructionDelivery).optional(),\n acp: z.object({\n transports: z.array(z.nativeEnum(AcpTransport)).min(1),\n mcp: z.array(z.nativeEnum(McpTransportKind)),\n }),\n // A capability missing here is unavailable on this harness.\n baseTools: z.partialRecord(z.nativeEnum(BaseCapability), baseToolDeclarationSchema),\n consumes: z.array(z.nativeEnum(SandboxWire)),\n inference: z.object({\n vendors: z.array(z.string()),\n kinds: z.array(z.nativeEnum(InferenceCredentialKind)),\n delivery: z.nativeEnum(CredentialDelivery),\n }),\n // Absent: third-party.\n trust: z.nativeEnum(HarnessTrustClass).optional(),\n supports: z.object({\n observe: z.boolean(),\n resumeReplay: z.boolean(),\n fork: z.boolean(),\n // Renders _meta[\"final.ai\"].author itself; otherwise the channel prepends\n // the author's name to the text.\n authorMeta: z.boolean(),\n // Explicit false: native toolPolicy cannot be enforced by this adapter's public surface.\n nativeToolPolicy: z.boolean().optional(),\n // Defers and searches MCP tools itself (a harness-native tool search): the\n // host lists every exposed tool, ignoring connections' `tools.load`, and\n // adds no search of its own. Absent: the host applies `load` and serves search.\n deferredToolSearch: z.boolean().optional(),\n }),\n promptWhileRunning: z.nativeEnum(PromptWhileRunning).default(DEFAULT_PROMPT_WHILE_RUNNING),\n // Keeps the session, its running work and its open requests across a dropped\n // connection, buffers updates for replay, and re-raises the open requests\n // with the same JSON-RPC ids on the next session/resume. False:\n // open turns end `harness_state_lost` after a reconnect.\n sessionSurvivesDisconnect: z.boolean().default(DEFAULT_SESSION_SURVIVES_DISCONNECT),\n});\n\nexport type BaseToolDeclarationIface = z.infer<typeof baseToolDeclarationSchema>;\nexport type HarnessDescriptionIface = z.infer<typeof harnessDescriptionSchema>;\n\nexport const deliveredHarnessConfig = (args: {\n config: JsonValue;\n description: HarnessDescriptionIface;\n}): JsonValue => {\n if (args.description.userInstructionDelivery !== UserInstructionDelivery.System)\n return args.config;\n const config = jsonObjectSchema.safeParse(args.config);\n if (!config.success) return args.config;\n const fields = referencedSharedSchemas(args.description.configSchema);\n const field =\n Object.entries(fields).find(([, schema]) => schema === SCHEMA_IDS.instructions)?.[0] ??\n 'instructions';\n const instructions = config.data[field];\n if (!Array.isArray(instructions)) return args.config;\n return {\n ...config.data,\n [field]: instructions.map((value) => {\n const fragment = jsonObjectSchema.safeParse(value);\n return fragment.success && fragment.data['role'] === InstructionRole.User\n ? { ...fragment.data, role: InstructionRole.System }\n : value;\n }),\n };\n};\n\nexport const harnessSessionRefSchema = z.object({\n harness: providerRefSchema,\n // Opaque to the session service; the harness's own id for the session.\n harnessSessionRef: z.string().min(1),\n // Bumped whenever the harness loses state; a mismatch on resume means the\n // session service must re-seed with session/new.\n generation: z.number().int().nonnegative(),\n});\n\nexport type HarnessSessionRefIface = z.infer<typeof harnessSessionRefSchema>;\n\n// Route-scoped, short-lived grants: credential-routes.ts.\nexport {\n credentialRefreshRequestSchema,\n CredentialRoute,\n routeGrantSchema,\n type CredentialRefreshRequestIface,\n type RouteGrantIface,\n} from \"./credential-routes.mjs\";\n\nexport interface CredentialGrantIface {\n // Base URL of the broker routes (`<base>/model`, `<base>/refresh`, ...).\n brokerUrl: string;\n grants: RouteGrantIface[];\n // What the model grant resolved to, for harnesses that hand credentials over\n // at open (delivery 'at-open'). Null for per-request harnesses.\n atOpen: AtOpenModelCredentialIface | null;\n // How to renew this grant; null only when it carries no route grant.\n refresh: CredentialGrantRefreshIface | null;\n}\n\n// Renewal is pulled, never pushed. Per-request harnesses fetch\n// `<brokerUrl>/model` on every request. At-open harnesses (or their host)\n// POST `url` with `authorization: Bearer <token>` and a\n// `credentialRefreshRequestSchema` body before `expiresAt` and once after a\n// vendor 401; the answer is the grant's next generation (a\n// `credentialRefreshResultSchema` body with its own `refresh`), which replaces\n// this one. The broker resolves the policy again for it, so a disconnected\n// credential falls through; a revoked grant (every open revokes the previous\n// open's grants) or a closed harness session is refused (401).\nexport interface CredentialGrantRefreshIface {\n // `<brokerUrl>/refresh`.\n url: string;\n // One of this grant's own route grants (the model route's).\n token: string;\n harnessSessionId: string;\n // When `token` expires; a refresh after it is refused.\n expiresAt: string;\n}\n\nexport interface AtOpenModelCredentialIface {\n vendor: string;\n kind: InferenceCredentialKind;\n // Base URL and bearer for an OpenAI- or Anthropic-compatible endpoint (the\n // platform proxy, a corporate gateway) or the vendor itself.\n baseUrl: string | null;\n apiKey: string | null;\n // Subscription material for Final-managed harnesses only (Claude setup token,\n // Codex app-server chatgptAuthTokens); renewed through the grant's refresh route.\n subscription: { format: 'claude-setup-token' | 'chatgpt-auth-tokens'; value: string } | null;\n fingerprint: string;\n}\n\nexport const atOpenModelCredentialSchema = z.object({\n vendor: z.string(),\n kind: z.nativeEnum(InferenceCredentialKind),\n baseUrl: z.string().min(1).nullable(),\n apiKey: z.string().min(1).nullable(),\n subscription: z\n .object({\n format: z.union([z.literal('claude-setup-token'), z.literal('chatgpt-auth-tokens')]),\n value: z.string().min(1),\n })\n .nullable(),\n fingerprint: z.string(),\n}) satisfies z.ZodType<AtOpenModelCredentialIface>;\n\nexport const credentialGrantRefreshSchema = z.object({\n url: z.string().min(1),\n token: z.string().min(1),\n harnessSessionId: z.string().min(1),\n expiresAt: z.string(),\n}) satisfies z.ZodType<CredentialGrantRefreshIface>;\n\nexport const credentialGrantSchema = z.object({\n brokerUrl: z.string().min(1),\n grants: z.array(routeGrantSchema),\n atOpen: atOpenModelCredentialSchema.nullable(),\n refresh: credentialGrantRefreshSchema.nullable(),\n}) satisfies z.ZodType<CredentialGrantIface>;\n\n// An `http` MCP server entry the harness was handed in `session/new`\n// (`mcpServers`), with fresh headers. Same name and url; the harness swaps the\n// headers of the entry with that url.\nexport interface RenewedMcpServerIface {\n name: string;\n url: string;\n headers: { name: string; value: string }[];\n}\n\n// What a refresh answers: the grant's next generation, plus fresh copies of the\n// other short-lived material the harness was handed at open. Renewing the\n// `mcp` route renews the session's `http` MCP server headers; renewing\n// `sandbox` renews the bound sandbox targets' endpoint tokens.\nexport interface CredentialRefreshResultIface extends CredentialGrantIface {\n mcpServers: RenewedMcpServerIface[];\n sandboxes: Record<string, SandboxTargetEndpointIface>;\n}\n\nconst endpointTokenSchema = z.object({\n url: z.string().min(1),\n token: z.string(),\n expiresAt: z.string(),\n});\n\nexport const sandboxTargetEndpointSchema = z.object({\n target: z.string().min(1),\n bindingId: z.string().min(1),\n capabilities: z.array(z.string()),\n rpc: endpointTokenSchema.nullable(),\n mcp: endpointTokenSchema.nullable(),\n}) satisfies z.ZodType<SandboxTargetEndpointIface>;\n\nexport const renewedMcpServerSchema = z.object({\n name: z.string().min(1),\n url: z.string().min(1),\n headers: z.array(z.object({ name: z.string().min(1), value: z.string() })),\n}) satisfies z.ZodType<RenewedMcpServerIface>;\n\n// Absent renewals parse as none, so an answer without them still parses.\nexport const credentialRefreshResultSchema = credentialGrantSchema.extend({\n mcpServers: z.array(renewedMcpServerSchema).default([]),\n sandboxes: z.record(z.string(), sandboxTargetEndpointSchema).default({}),\n}) satisfies z.ZodType<CredentialRefreshResultIface, unknown>;\n\n// The refresh descriptor for a set of route grants: authenticated by the model\n// grant (else the first), due when that token expires.\nexport const grantRefreshFor = (args: {\n brokerUrl: string;\n harnessSessionId: string;\n grants: readonly RouteGrantIface[];\n}): CredentialGrantRefreshIface | null => {\n const grant =\n args.grants.find((candidate) => candidate.route === CredentialRoute.Model) ?? args.grants[0];\n if (grant == null) return null;\n return {\n url: `${args.brokerUrl.replace(/\\/+$/, '')}/refresh`,\n token: grant.token,\n harnessSessionId: args.harnessSessionId,\n expiresAt: grant.expiresAt,\n };\n};\n\nexport interface SecretReaderIface {\n get(name: string): Promise<string | null>;\n}\n\nexport interface TraceContextIface {\n traceparent: string | null;\n tracestate: string | null;\n}\n\n// A bound sandbox target as the session service hands it to a harness: a stable\n// per-binding address that starts the sandbox on the first tool call. Never a lease, a data-plane token for a live VM, or provider code.\nexport interface SandboxTargetEndpointIface {\n target: string;\n bindingId: string;\n capabilities: string[];\n rpc: { url: string; token: string; expiresAt: string } | null;\n mcp: { url: string; token: string; expiresAt: string } | null;\n}\n\nexport interface HarnessSessionContextIface {\n bindings?: HostedBindingsIface;\n sessionId: string;\n organizationId: string;\n definitionId: string;\n revisionId: string;\n // Public base URL of the session service for this session (MCP over HTTP,\n // sandbox endpoints, the broker).\n sessionServiceUrl: string;\n // The region of the session service serving the session and its sandbox\n // bindings, so a harness can run near it; null when unknown.\n sessionServiceRegion?: string | null;\n}\n\n// Lifecycle signals a harness implementation may report about the runtime\n// hosting a session (invocations, metering, traces). Informational: the\n// session service records them (agent.harness_invocations, Tinybird) and never\n// depends on them for correctness.\nexport interface HarnessObserverIface {\n // The runtime accepted the invocation request (its response began).\n invocationAccepted?(event: { invocationRef: string; at: string }): void;\n invocationStarted?(event: {\n invocationRef: string;\n at: string;\n bootMs: number | null;\n // The runtime's deployed version (Workers version id, commit), for rollouts.\n versionId?: string | null;\n commitSha?: string | null;\n }): void;\n invocationKeepalive?(event: { invocationRef: string; at: string; activeWork: number }): void;\n invocationEnded?(event: {\n invocationRef: string;\n at: string;\n reason: string;\n error: string | null;\n metering: Record<string, number>;\n }): void;\n trace?(event: { name: string; at: string; fields: Record<string, JsonValue> }): void;\n}\n\nexport interface OpenHarnessSessionArgsIface {\n session: HarnessSessionContextIface;\n // The session service's id for this harness session (agent.harness_sessions);\n // implementations key their runtime state and route grants by it.\n harnessSessionId: string;\n // Hosting may authorize the child endpoint to fork this source through ACP.\n forkSource?: { ref: HarnessSessionRefIface; acpSessionId: string };\n observer?: HarnessObserverIface;\n // The binding's config, validated against configSchema, dynamic slots resolved.\n config: JsonValue;\n manifest: ResolvedAgentManifestIface;\n // Already materialized ACP MCP server entries: authored tools, connections\n // (Final's MCP server among them), sandbox MCP projections where applicable.\n mcpServers: McpServer[];\n // Declared base capabilities with the target endpoint each is bound to.\n baseTools: Partial<Record<BaseCapability, SandboxTargetEndpointIface>>;\n sandboxes: Record<string, SandboxTargetEndpointIface>;\n credentials: CredentialGrantIface;\n secrets: SecretReaderIface;\n trace: TraceContextIface;\n}\n\nexport interface ResumeHarnessSessionArgsIface extends OpenHarnessSessionArgsIface {\n ref: HarnessSessionRefIface;\n // Last log seq the session service holds from this harness session; the\n // harness replays anything newer after session/resume.\n lastSeq: number;\n}\n\n// Resolved only in memory; refs/manifests retain secret names, never TLS keys.\nexport interface HarnessClientTlsIface {\n cert: string;\n key: string;\n ca?: string;\n}\n\nexport type HarnessEndpointIface =\n | {\n ref: HarnessSessionRefIface;\n transport: AcpTransport.Ws;\n url: string;\n headers: Record<string, string>;\n resolveHeaders?: () => Promise<Record<string, string>>;\n tls?: HarnessClientTlsIface;\n }\n | {\n ref: HarnessSessionRefIface;\n transport: AcpTransport.Http;\n url: string;\n headers: Record<string, string>;\n resolveHeaders?: () => Promise<Record<string, string>>;\n tls?: HarnessClientTlsIface;\n }\n // websocket-gateway relay channel (Final-managed harnesses).\n | { ref: HarnessSessionRefIface; transport: AcpTransport.Relay; channel: string; token: string }\n // Local development, CI and conformance only.\n | {\n ref: HarnessSessionRefIface;\n transport: AcpTransport.Stdio;\n command: string;\n args: string[];\n env: Record<string, string>;\n };\n\nexport interface HarnessHealthIface {\n ok: boolean;\n detail?: string;\n checkedAt: string;\n}\n\n// The binding a description is asked for: its config (validated against the\n// configSchema of the binding-free description) and the definition's secrets.\nexport interface DescribeHarnessArgsIface {\n config: JsonValue;\n secrets: SecretReaderIface;\n}\n\nexport interface HarnessIface {\n // Without a binding: what Build renders before one exists (configSchema,\n // declared capabilities). With one: the description of that binding, which a\n // harness reaching an arbitrary agent derives from the agent itself (e.g. its\n // `initialize`). Every harness implements both; most ignore the binding.\n describe(binding?: DescribeHarnessArgsIface): Promise<HarnessDescriptionIface>;\n open(args: OpenHarnessSessionArgsIface): Promise<HarnessEndpointIface>;\n resume(args: ResumeHarnessSessionArgsIface): Promise<HarnessEndpointIface>;\n park(ref: HarnessSessionRefIface): Promise<void>;\n // Graceful by default: the program's state is durable (resumable) before it\n // stops, bounded by the implementation's timeout, then forced. `force` skips\n // the wait; the session service passes it when the program did not settle\n // ACP `session/close` within its bound.\n close(ref: HarnessSessionRefIface, opts?: CloseHarnessSessionOptsIface): Promise<void>;\n health(\n ref: HarnessSessionRefIface,\n context?: DescribeHarnessArgsIface,\n ): Promise<HarnessHealthIface>;\n}\n\nexport interface CloseHarnessSessionOptsIface {\n force?: boolean;\n // As with health, retained refs can resolve current client TLS without storing keys in the ref.\n context?: DescribeHarnessArgsIface;\n}\n\n// What an installed harness module exports: the implementation plus an\n// authoring helper that builds the manifest binding.\nexport interface HarnessModuleIface<Config> {\n ref: ProviderRef;\n harness: HarnessIface;\n binding: (config: Config) => { harness: ProviderRef; config: JsonValue };\n}\n\n// Custom harnesses in a definition's bundle. Calling the result\n// with a config yields the manifest binding; the implementation is resolved\n// from the bundle by export name.\nexport interface DefinedHarnessBindingIface {\n harness: ProviderRef;\n config: JsonValue;\n definedHarness: true;\n}\n\nexport interface DefinedHarnessIface<Config> extends HarnessIface {\n (config: Config): DefinedHarnessBindingIface;\n}\n\nexport const defineHarness = <Config extends JsonValue = JsonValue>(\n implementation: HarnessIface,\n): DefinedHarnessIface<Config> => {\n // The export name is unknown here; the compiler rewrites `bundle:<pending>`\n // to the module path that exported this harness.\n const binding = (config: Config): DefinedHarnessBindingIface => ({\n harness: bundleRef(PENDING_BUNDLE_EXPORT),\n config,\n definedHarness: true,\n });\n return Object.assign(binding, implementation);\n};\n\nexport const describeConfigSchema = (description: HarnessDescriptionIface): JsonSchema =>\n description.configSchema;\n"],
|
|
5
|
-
"mappings": "AACA,YAA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AAE,OAAO,CAAC;AACjC,CAAC;AAEM,MAAM,2BAA2B,EAAE,OAAO;AAAA;AAAA;AAAA;AAAA,EAI/C,cAAc;AAAA;AAAA,EAEd,yBAAyB,EAAE,WAAW,uBAAuB,EAAE,SAAS;AAAA,EACxE,KAAK,EAAE,OAAO;AAAA,IACZ,YAAY,EAAE,MAAM,EAAE,WAAW,YAAY,CAAC,EAAE,IAAI,CAAC;AAAA,IACrD,KAAK,EAAE,MAAM,EAAE,WAAW,gBAAgB,CAAC;AAAA,EAC7C,CAAC;AAAA;AAAA,EAED,WAAW,EAAE,cAAc,EAAE,WAAW,cAAc,GAAG,yBAAyB;AAAA,EAClF,UAAU,EAAE,MAAM,EAAE,WAAW,WAAW,CAAC;AAAA,EAC3C,WAAW,EAAE,OAAO;AAAA,IAClB,SAAS,EAAE,MAAM,EAAE,OAAO,CAAC;AAAA,IAC3B,OAAO,EAAE,MAAM,EAAE,WAAW,uBAAuB,CAAC;AAAA,IACpD,UAAU,EAAE,WAAW,kBAAkB;AAAA,EAC3C,CAAC;AAAA;AAAA,EAED,OAAO,EAAE,WAAW,iBAAiB,EAAE,SAAS;AAAA,EAChD,UAAU,EAAE,OAAO;AAAA,IACjB,SAAS,EAAE,QAAQ;AAAA,IACnB,cAAc,EAAE,QAAQ;AAAA,IACxB,MAAM,EAAE,QAAQ;AAAA;AAAA;AAAA,IAGhB,YAAY,EAAE,QAAQ;AAAA;AAAA,IAEtB,kBAAkB,EAAE,QAAQ,EAAE,SAAS;AAAA;AAAA;AAAA;AAAA,
|
|
4
|
+
"sourcesContent": ["import type { McpServer } from '@agentclientprotocol/sdk/experimental/v2';\nimport * as z from 'zod';\nimport { CredentialRoute, routeGrantSchema, type RouteGrantIface } from \"./credential-routes.mjs\";\nimport { CredentialDelivery, InferenceCredentialKind } from \"./credentials.mjs\";\nimport type { JsonSchema, JsonValue } from \"./json.mjs\";\nimport type { HostedBindingsIface } from \"./hosted-bindings.mjs\";\nimport { jsonObjectSchema, jsonSchemaSchema } from \"./json.mjs\";\nimport { BaseCapability, InstructionRole, type ResolvedAgentManifestIface } from \"./manifest.mjs\";\nimport { bundleRef, providerRefSchema, type ProviderRef } from \"./provider-ref.mjs\";\nimport { referencedSharedSchemas, SCHEMA_IDS } from \"./schemas.mjs\";\n\n// Placeholder export name the compiler replaces with the defining module's path.\nexport const PENDING_BUNDLE_EXPORT = '<pending>';\n\n// A harness is a specific ACP agent program together with how to reach it. Hosting is part of what a harness is, so there is no\n// engine parameter: \"Pi on Final's serverless runtime\" and \"Pi on a server you\n// run\" are two harnesses. The hosting half is deliberately small; everything\n// about what the agent does goes over ACP v2.\n\nexport enum AcpTransport {\n Relay = 'relay',\n Ws = 'ws',\n Http = 'http',\n Stdio = 'stdio',\n}\n\nexport enum McpTransportKind {\n Acp = 'acp',\n Http = 'http',\n Stdio = 'stdio',\n}\n\n// How a harness provides one base capability.\nexport enum BaseToolProvision {\n // Routed to the declared sandbox target.\n Bound = 'bound',\n // Native on the harness's host and switchable through its own allow-lists.\n HostDisableable = 'host-disableable',\n // Native on the harness's host and not switchable.\n HostFixed = 'host-fixed',\n}\n\n// SDK wires a harness speaks to reach a bound sandbox target.\nexport enum SandboxWire {\n HandleRpc = 'handle-rpc',\n Mcp = 'mcp',\n}\n\nexport enum UserInstructionDelivery {\n History = 'history',\n System = 'system',\n}\n\n// Who operates the place a harness's credentials land. Every\n// harness, Final's included, gets the same grant forms; a subscription goes to\n// a third-party harness only when its owner allowed third-party harnesses.\n// Only installed provider packages may declare first-party; a bundle-declared\n// harness is third-party whatever it declares.\nexport enum HarnessTrustClass {\n // The provider operates the harness on infrastructure it runs (Final's serverless harnesses).\n FirstParty = 'first-party',\n // Someone else's host or program (remote hosts, external ACP agents, local processes).\n ThirdParty = 'third-party',\n}\n\n// What an accepted session/prompt does while the session is running. Both are valid; refusing one is a conformance failure.\nexport enum PromptWhileRunning {\n // Joins the running work: the model sees it at its next step.\n Inject = 'inject',\n // Runs after the current work goes idle; dropped by session/cancel if not started.\n Queue = 'queue',\n}\n\n// Defaults for a description that does not declare the hosting contract's\n// newer fields (bundle harnesses, older registrations): the session service\n// then assumes nothing survives a dropped connection and that a prompt while\n// running waits for idle.\nexport const DEFAULT_PROMPT_WHILE_RUNNING = PromptWhileRunning.Queue;\nexport const DEFAULT_SESSION_SURVIVES_DISCONNECT = false;\n\nexport const baseToolDeclarationSchema = z.object({\n provision: z.nativeEnum(BaseToolProvision),\n nativeTools: z.array(z.string()),\n});\n\nexport const harnessDescriptionSchema = z.object({\n // Everything configurable about this harness (model, reasoning, credentials,\n // permission mode, instructions, skills, cwd, ...). JSON Schema so Build can\n // render it; may $ref the shared final://schemas/* fragments.\n configSchema: jsonSchemaSchema,\n // Absent: user fragments enter history. System-only programs declare their conversion.\n userInstructionDelivery: z.nativeEnum(UserInstructionDelivery).optional(),\n acp: z.object({\n transports: z.array(z.nativeEnum(AcpTransport)).min(1),\n mcp: z.array(z.nativeEnum(McpTransportKind)),\n }),\n // A capability missing here is unavailable on this harness.\n baseTools: z.partialRecord(z.nativeEnum(BaseCapability), baseToolDeclarationSchema),\n consumes: z.array(z.nativeEnum(SandboxWire)),\n inference: z.object({\n vendors: z.array(z.string()),\n kinds: z.array(z.nativeEnum(InferenceCredentialKind)),\n delivery: z.nativeEnum(CredentialDelivery),\n }),\n // Absent: third-party.\n trust: z.nativeEnum(HarnessTrustClass).optional(),\n supports: z.object({\n observe: z.boolean(),\n resumeReplay: z.boolean(),\n fork: z.boolean(),\n // Renders _meta[\"final.ai\"].author itself; otherwise the channel prepends\n // the author's name to the text.\n authorMeta: z.boolean(),\n // Explicit false: native toolPolicy cannot be enforced by this adapter's public surface.\n nativeToolPolicy: z.boolean().optional(),\n // Defers and searches MCP tools itself (a harness-native tool search): the\n // host lists every exposed tool, ignoring connections' `tools.load`, and\n // adds no search of its own. Absent: the host lists what `load` (or, without\n // it, HOSTING.md's defaults) leaves listed and serves search for the rest.\n deferredToolSearch: z.boolean().optional(),\n }),\n promptWhileRunning: z.nativeEnum(PromptWhileRunning).default(DEFAULT_PROMPT_WHILE_RUNNING),\n // Keeps the session, its running work and its open requests across a dropped\n // connection, buffers updates for replay, and re-raises the open requests\n // with the same JSON-RPC ids on the next session/resume. False:\n // open turns end `harness_state_lost` after a reconnect.\n sessionSurvivesDisconnect: z.boolean().default(DEFAULT_SESSION_SURVIVES_DISCONNECT),\n});\n\nexport type BaseToolDeclarationIface = z.infer<typeof baseToolDeclarationSchema>;\nexport type HarnessDescriptionIface = z.infer<typeof harnessDescriptionSchema>;\n\nexport const deliveredHarnessConfig = (args: {\n config: JsonValue;\n description: HarnessDescriptionIface;\n}): JsonValue => {\n if (args.description.userInstructionDelivery !== UserInstructionDelivery.System)\n return args.config;\n const config = jsonObjectSchema.safeParse(args.config);\n if (!config.success) return args.config;\n const fields = referencedSharedSchemas(args.description.configSchema);\n const field =\n Object.entries(fields).find(([, schema]) => schema === SCHEMA_IDS.instructions)?.[0] ??\n 'instructions';\n const instructions = config.data[field];\n if (!Array.isArray(instructions)) return args.config;\n return {\n ...config.data,\n [field]: instructions.map((value) => {\n const fragment = jsonObjectSchema.safeParse(value);\n return fragment.success && fragment.data['role'] === InstructionRole.User\n ? { ...fragment.data, role: InstructionRole.System }\n : value;\n }),\n };\n};\n\nexport const harnessSessionRefSchema = z.object({\n harness: providerRefSchema,\n // Opaque to the session service; the harness's own id for the session.\n harnessSessionRef: z.string().min(1),\n // Bumped whenever the harness loses state; a mismatch on resume means the\n // session service must re-seed with session/new.\n generation: z.number().int().nonnegative(),\n});\n\nexport type HarnessSessionRefIface = z.infer<typeof harnessSessionRefSchema>;\n\n// Route-scoped, short-lived grants: credential-routes.ts.\nexport {\n credentialRefreshRequestSchema,\n CredentialRoute,\n routeGrantSchema,\n type CredentialRefreshRequestIface,\n type RouteGrantIface,\n} from \"./credential-routes.mjs\";\n\nexport interface CredentialGrantIface {\n // Base URL of the broker routes (`<base>/model`, `<base>/refresh`, ...).\n brokerUrl: string;\n grants: RouteGrantIface[];\n // What the model grant resolved to, for harnesses that hand credentials over\n // at open (delivery 'at-open'). Null for per-request harnesses.\n atOpen: AtOpenModelCredentialIface | null;\n // How to renew this grant; null only when it carries no route grant.\n refresh: CredentialGrantRefreshIface | null;\n}\n\n// Renewal is pulled, never pushed. Per-request harnesses fetch\n// `<brokerUrl>/model` on every request. At-open harnesses (or their host)\n// POST `url` with `authorization: Bearer <token>` and a\n// `credentialRefreshRequestSchema` body before `expiresAt` and once after a\n// vendor 401; the answer is the grant's next generation (a\n// `credentialRefreshResultSchema` body with its own `refresh`), which replaces\n// this one. The broker resolves the policy again for it, so a disconnected\n// credential falls through; a revoked grant (every open revokes the previous\n// open's grants) or a closed harness session is refused (401).\nexport interface CredentialGrantRefreshIface {\n // `<brokerUrl>/refresh`.\n url: string;\n // One of this grant's own route grants (the model route's).\n token: string;\n harnessSessionId: string;\n // When `token` expires; a refresh after it is refused.\n expiresAt: string;\n}\n\nexport interface AtOpenModelCredentialIface {\n vendor: string;\n kind: InferenceCredentialKind;\n // Base URL and bearer for an OpenAI- or Anthropic-compatible endpoint (the\n // platform proxy, a corporate gateway) or the vendor itself.\n baseUrl: string | null;\n apiKey: string | null;\n // Subscription material for Final-managed harnesses only (Claude setup token,\n // Codex app-server chatgptAuthTokens); renewed through the grant's refresh route.\n subscription: { format: 'claude-setup-token' | 'chatgpt-auth-tokens'; value: string } | null;\n fingerprint: string;\n}\n\nexport const atOpenModelCredentialSchema = z.object({\n vendor: z.string(),\n kind: z.nativeEnum(InferenceCredentialKind),\n baseUrl: z.string().min(1).nullable(),\n apiKey: z.string().min(1).nullable(),\n subscription: z\n .object({\n format: z.union([z.literal('claude-setup-token'), z.literal('chatgpt-auth-tokens')]),\n value: z.string().min(1),\n })\n .nullable(),\n fingerprint: z.string(),\n}) satisfies z.ZodType<AtOpenModelCredentialIface>;\n\nexport const credentialGrantRefreshSchema = z.object({\n url: z.string().min(1),\n token: z.string().min(1),\n harnessSessionId: z.string().min(1),\n expiresAt: z.string(),\n}) satisfies z.ZodType<CredentialGrantRefreshIface>;\n\nexport const credentialGrantSchema = z.object({\n brokerUrl: z.string().min(1),\n grants: z.array(routeGrantSchema),\n atOpen: atOpenModelCredentialSchema.nullable(),\n refresh: credentialGrantRefreshSchema.nullable(),\n}) satisfies z.ZodType<CredentialGrantIface>;\n\n// An `http` MCP server entry the harness was handed in `session/new`\n// (`mcpServers`), with fresh headers. Same name and url; the harness swaps the\n// headers of the entry with that url.\nexport interface RenewedMcpServerIface {\n name: string;\n url: string;\n headers: { name: string; value: string }[];\n}\n\n// What a refresh answers: the grant's next generation, plus fresh copies of the\n// other short-lived material the harness was handed at open. Renewing the\n// `mcp` route renews the session's `http` MCP server headers; renewing\n// `sandbox` renews the bound sandbox targets' endpoint tokens.\nexport interface CredentialRefreshResultIface extends CredentialGrantIface {\n mcpServers: RenewedMcpServerIface[];\n sandboxes: Record<string, SandboxTargetEndpointIface>;\n}\n\nconst endpointTokenSchema = z.object({\n url: z.string().min(1),\n token: z.string(),\n expiresAt: z.string(),\n});\n\nexport const sandboxTargetEndpointSchema = z.object({\n target: z.string().min(1),\n bindingId: z.string().min(1),\n capabilities: z.array(z.string()),\n rpc: endpointTokenSchema.nullable(),\n mcp: endpointTokenSchema.nullable(),\n}) satisfies z.ZodType<SandboxTargetEndpointIface>;\n\nexport const renewedMcpServerSchema = z.object({\n name: z.string().min(1),\n url: z.string().min(1),\n headers: z.array(z.object({ name: z.string().min(1), value: z.string() })),\n}) satisfies z.ZodType<RenewedMcpServerIface>;\n\n// Absent renewals parse as none, so an answer without them still parses.\nexport const credentialRefreshResultSchema = credentialGrantSchema.extend({\n mcpServers: z.array(renewedMcpServerSchema).default([]),\n sandboxes: z.record(z.string(), sandboxTargetEndpointSchema).default({}),\n}) satisfies z.ZodType<CredentialRefreshResultIface, unknown>;\n\n// The refresh descriptor for a set of route grants: authenticated by the model\n// grant (else the first), due when that token expires.\nexport const grantRefreshFor = (args: {\n brokerUrl: string;\n harnessSessionId: string;\n grants: readonly RouteGrantIface[];\n}): CredentialGrantRefreshIface | null => {\n const grant =\n args.grants.find((candidate) => candidate.route === CredentialRoute.Model) ?? args.grants[0];\n if (grant == null) return null;\n return {\n url: `${args.brokerUrl.replace(/\\/+$/, '')}/refresh`,\n token: grant.token,\n harnessSessionId: args.harnessSessionId,\n expiresAt: grant.expiresAt,\n };\n};\n\nexport interface SecretReaderIface {\n get(name: string): Promise<string | null>;\n}\n\nexport interface TraceContextIface {\n traceparent: string | null;\n tracestate: string | null;\n}\n\n// A bound sandbox target as the session service hands it to a harness: a stable\n// per-binding address that starts the sandbox on the first tool call. Never a lease, a data-plane token for a live VM, or provider code.\nexport interface SandboxTargetEndpointIface {\n target: string;\n bindingId: string;\n capabilities: string[];\n rpc: { url: string; token: string; expiresAt: string } | null;\n mcp: { url: string; token: string; expiresAt: string } | null;\n}\n\nexport interface HarnessSessionContextIface {\n bindings?: HostedBindingsIface;\n sessionId: string;\n organizationId: string;\n definitionId: string;\n revisionId: string;\n // Public base URL of the session service for this session (MCP over HTTP,\n // sandbox endpoints, the broker).\n sessionServiceUrl: string;\n // The region of the session service serving the session and its sandbox\n // bindings, so a harness can run near it; null when unknown.\n sessionServiceRegion?: string | null;\n}\n\n// Lifecycle signals a harness implementation may report about the runtime\n// hosting a session (invocations, metering, traces). Informational: the\n// session service records them (agent.harness_invocations, Tinybird) and never\n// depends on them for correctness.\nexport interface HarnessObserverIface {\n // The runtime accepted the invocation request (its response began).\n invocationAccepted?(event: { invocationRef: string; at: string }): void;\n invocationStarted?(event: {\n invocationRef: string;\n at: string;\n bootMs: number | null;\n // The runtime's deployed version (Workers version id, commit), for rollouts.\n versionId?: string | null;\n commitSha?: string | null;\n }): void;\n invocationKeepalive?(event: { invocationRef: string; at: string; activeWork: number }): void;\n invocationEnded?(event: {\n invocationRef: string;\n at: string;\n reason: string;\n error: string | null;\n metering: Record<string, number>;\n }): void;\n trace?(event: { name: string; at: string; fields: Record<string, JsonValue> }): void;\n}\n\nexport interface OpenHarnessSessionArgsIface {\n session: HarnessSessionContextIface;\n // The session service's id for this harness session (agent.harness_sessions);\n // implementations key their runtime state and route grants by it.\n harnessSessionId: string;\n // Hosting may authorize the child endpoint to fork this source through ACP.\n forkSource?: { ref: HarnessSessionRefIface; acpSessionId: string };\n observer?: HarnessObserverIface;\n // The binding's config, validated against configSchema, dynamic slots resolved.\n config: JsonValue;\n manifest: ResolvedAgentManifestIface;\n // Already materialized ACP MCP server entries: authored tools, connections\n // (Final's MCP server among them), sandbox MCP projections where applicable.\n mcpServers: McpServer[];\n // Declared base capabilities with the target endpoint each is bound to.\n baseTools: Partial<Record<BaseCapability, SandboxTargetEndpointIface>>;\n sandboxes: Record<string, SandboxTargetEndpointIface>;\n credentials: CredentialGrantIface;\n secrets: SecretReaderIface;\n trace: TraceContextIface;\n}\n\nexport interface ResumeHarnessSessionArgsIface extends OpenHarnessSessionArgsIface {\n ref: HarnessSessionRefIface;\n // Last log seq the session service holds from this harness session; the\n // harness replays anything newer after session/resume.\n lastSeq: number;\n}\n\n// Resolved only in memory; refs/manifests retain secret names, never TLS keys.\nexport interface HarnessClientTlsIface {\n cert: string;\n key: string;\n ca?: string;\n}\n\nexport type HarnessEndpointIface =\n | {\n ref: HarnessSessionRefIface;\n transport: AcpTransport.Ws;\n url: string;\n headers: Record<string, string>;\n resolveHeaders?: () => Promise<Record<string, string>>;\n tls?: HarnessClientTlsIface;\n }\n | {\n ref: HarnessSessionRefIface;\n transport: AcpTransport.Http;\n url: string;\n headers: Record<string, string>;\n resolveHeaders?: () => Promise<Record<string, string>>;\n tls?: HarnessClientTlsIface;\n }\n // websocket-gateway relay channel (Final-managed harnesses).\n | { ref: HarnessSessionRefIface; transport: AcpTransport.Relay; channel: string; token: string }\n // Local development, CI and conformance only.\n | {\n ref: HarnessSessionRefIface;\n transport: AcpTransport.Stdio;\n command: string;\n args: string[];\n env: Record<string, string>;\n };\n\nexport interface HarnessHealthIface {\n ok: boolean;\n detail?: string;\n checkedAt: string;\n}\n\n// The binding a description is asked for: its config (validated against the\n// configSchema of the binding-free description) and the definition's secrets.\nexport interface DescribeHarnessArgsIface {\n config: JsonValue;\n secrets: SecretReaderIface;\n}\n\nexport interface HarnessIface {\n // Without a binding: what Build renders before one exists (configSchema,\n // declared capabilities). With one: the description of that binding, which a\n // harness reaching an arbitrary agent derives from the agent itself (e.g. its\n // `initialize`). Every harness implements both; most ignore the binding.\n describe(binding?: DescribeHarnessArgsIface): Promise<HarnessDescriptionIface>;\n open(args: OpenHarnessSessionArgsIface): Promise<HarnessEndpointIface>;\n resume(args: ResumeHarnessSessionArgsIface): Promise<HarnessEndpointIface>;\n park(ref: HarnessSessionRefIface): Promise<void>;\n // Graceful by default: the program's state is durable (resumable) before it\n // stops, bounded by the implementation's timeout, then forced. `force` skips\n // the wait; the session service passes it when the program did not settle\n // ACP `session/close` within its bound.\n close(ref: HarnessSessionRefIface, opts?: CloseHarnessSessionOptsIface): Promise<void>;\n health(\n ref: HarnessSessionRefIface,\n context?: DescribeHarnessArgsIface,\n ): Promise<HarnessHealthIface>;\n}\n\nexport interface CloseHarnessSessionOptsIface {\n force?: boolean;\n // As with health, retained refs can resolve current client TLS without storing keys in the ref.\n context?: DescribeHarnessArgsIface;\n}\n\n// What an installed harness module exports: the implementation plus an\n// authoring helper that builds the manifest binding.\nexport interface HarnessModuleIface<Config> {\n ref: ProviderRef;\n harness: HarnessIface;\n binding: (config: Config) => { harness: ProviderRef; config: JsonValue };\n}\n\n// Custom harnesses in a definition's bundle. Calling the result\n// with a config yields the manifest binding; the implementation is resolved\n// from the bundle by export name.\nexport interface DefinedHarnessBindingIface {\n harness: ProviderRef;\n config: JsonValue;\n definedHarness: true;\n}\n\nexport interface DefinedHarnessIface<Config> extends HarnessIface {\n (config: Config): DefinedHarnessBindingIface;\n}\n\nexport const defineHarness = <Config extends JsonValue = JsonValue>(\n implementation: HarnessIface,\n): DefinedHarnessIface<Config> => {\n // The export name is unknown here; the compiler rewrites `bundle:<pending>`\n // to the module path that exported this harness.\n const binding = (config: Config): DefinedHarnessBindingIface => ({\n harness: bundleRef(PENDING_BUNDLE_EXPORT),\n config,\n definedHarness: true,\n });\n return Object.assign(binding, implementation);\n};\n\nexport const describeConfigSchema = (description: HarnessDescriptionIface): JsonSchema =>\n description.configSchema;\n"],
|
|
5
|
+
"mappings": "AACA,YAAY,OAAO;AACnB,SAAS,iBAAiB,wBAA8C;AACxE,SAAS,oBAAoB,+BAA+B;AAG5D,SAAS,kBAAkB,wBAAwB;AACnD,SAAS,gBAAgB,uBAAwD;AACjF,SAAS,WAAW,yBAA2C;AAC/D,SAAS,yBAAyB,kBAAkB;AAG7C,MAAM,wBAAwB;AAO9B,IAAK,eAAL,kBAAKA,kBAAL;AACL,EAAAA,cAAA,WAAQ;AACR,EAAAA,cAAA,QAAK;AACL,EAAAA,cAAA,UAAO;AACP,EAAAA,cAAA,WAAQ;AAJE,SAAAA;AAAA,GAAA;AAOL,IAAK,mBAAL,kBAAKC,sBAAL;AACL,EAAAA,kBAAA,SAAM;AACN,EAAAA,kBAAA,UAAO;AACP,EAAAA,kBAAA,WAAQ;AAHE,SAAAA;AAAA,GAAA;AAOL,IAAK,oBAAL,kBAAKC,uBAAL;AAEL,EAAAA,mBAAA,WAAQ;AAER,EAAAA,mBAAA,qBAAkB;AAElB,EAAAA,mBAAA,eAAY;AANF,SAAAA;AAAA,GAAA;AAUL,IAAK,cAAL,kBAAKC,iBAAL;AACL,EAAAA,aAAA,eAAY;AACZ,EAAAA,aAAA,SAAM;AAFI,SAAAA;AAAA,GAAA;AAKL,IAAK,0BAAL,kBAAKC,6BAAL;AACL,EAAAA,yBAAA,aAAU;AACV,EAAAA,yBAAA,YAAS;AAFC,SAAAA;AAAA,GAAA;AAUL,IAAK,oBAAL,kBAAKC,uBAAL;AAEL,EAAAA,mBAAA,gBAAa;AAEb,EAAAA,mBAAA,gBAAa;AAJH,SAAAA;AAAA,GAAA;AAQL,IAAK,qBAAL,kBAAKC,wBAAL;AAEL,EAAA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OAAO,EAAE,IAAI,CAAC;AAAA,EACtB,KAAK,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EACrB,SAAS,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,IAAI,CAAC,GAAG,OAAO,EAAE,OAAO,EAAE,CAAC,CAAC;AAC3E,CAAC;AAGM,MAAM,gCAAgC,sBAAsB,OAAO;AAAA,EACxE,YAAY,EAAE,MAAM,sBAAsB,EAAE,QAAQ,CAAC,CAAC;AAAA,EACtD,WAAW,EAAE,OAAO,EAAE,OAAO,GAAG,2BAA2B,EAAE,QAAQ,CAAC,CAAC;AACzE,CAAC;AAIM,MAAM,kBAAkB,CAAC,SAIU;AACxC,QAAM,QACJ,KAAK,OAAO,KAAK,CAAC,cAAc,UAAU,UAAU,gBAAgB,KAAK,KAAK,KAAK,OAAO,CAAC;AAC7F,MAAI,SAAS,KAAM,QAAO;AAC1B,SAAO;AAAA,IACL,KAAK,GAAG,KAAK,UAAU,QAAQ,QAAQ,EAAE,CAAC;AAAA,IAC1C,OAAO,MAAM;AAAA,IACb,kBAAkB,KAAK;AAAA,IACvB,WAAW,MAAM;AAAA,EACnB;AACF;AAyLO,MAAM,gBAAgB,CAC3B,mBACgC;AAGhC,QAAM,UAAU,CAAC,YAAgD;AAAA,IAC/D,SAAS,UAAU,qBAAqB;AAAA,IACxC;AAAA,IACA,gBAAgB;AAAA,EAClB;AACA,SAAO,OAAO,OAAO,SAAS,cAAc;AAC9C;AAEO,MAAM,uBAAuB,CAAC,gBACnC,YAAY;",
|
|
6
6
|
"names": ["AcpTransport", "McpTransportKind", "BaseToolProvision", "SandboxWire", "UserInstructionDelivery", "HarnessTrustClass", "PromptWhileRunning", "CredentialRoute", "routeGrantSchema"]
|
|
7
7
|
}
|
|
@@ -17,6 +17,7 @@ export interface CreateMemorySandboxArgsIface {
|
|
|
17
17
|
screen?: NetworkSandboxSessionIface['screen'];
|
|
18
18
|
localMcp?: () => Promise<SandboxMcpEndpoint[]>;
|
|
19
19
|
networkPolicy?: boolean;
|
|
20
|
+
baseEnv?: () => Promise<Record<string, string>>;
|
|
20
21
|
now?: () => Date;
|
|
21
22
|
}
|
|
22
23
|
export declare const createMemorySandbox: (args?: CreateMemorySandboxArgsIface) => MemorySandboxIface;
|
|
@@ -6,8 +6,13 @@ import { normalizePosixPath, posixDirname, resolvePosixPath } from "./paths.mjs"
|
|
|
6
6
|
import {
|
|
7
7
|
defineSandboxProvider,
|
|
8
8
|
NetworkPolicy,
|
|
9
|
+
PLATFORM_ENVIRONMENT_NAMES,
|
|
10
|
+
platformProcessEnvironment,
|
|
9
11
|
PortProtocol,
|
|
10
|
-
|
|
12
|
+
reportPlatformNetworkPolicy,
|
|
13
|
+
SandboxEntryType,
|
|
14
|
+
withPlatformEgressHosts,
|
|
15
|
+
writePlatformFiles
|
|
11
16
|
} from "./types.mjs";
|
|
12
17
|
const fsError = (code, message) => Object.assign(new Error(`${code}: ${message}`), { code });
|
|
13
18
|
const abortableSleep = (ms, signal) => new Promise((resolve, reject) => {
|
|
@@ -114,6 +119,7 @@ const createMemorySandbox = (args = {}) => {
|
|
|
114
119
|
};
|
|
115
120
|
};
|
|
116
121
|
const spawn = async (options) => {
|
|
122
|
+
const env = { ...await args.baseEnv?.(), ...options.env };
|
|
117
123
|
const controller = new AbortController();
|
|
118
124
|
let killedWith = null;
|
|
119
125
|
const outputs = { stdout: null, stderr: null };
|
|
@@ -166,6 +172,7 @@ const createMemorySandbox = (args = {}) => {
|
|
|
166
172
|
signal: controller.signal
|
|
167
173
|
},
|
|
168
174
|
cwd: options.cwd == null ? cwd : resolve(options.cwd),
|
|
175
|
+
env,
|
|
169
176
|
sleep: abortableSleep
|
|
170
177
|
};
|
|
171
178
|
const timeout = options.timeoutMs == null ? null : setTimeout(() => {
|
|
@@ -365,7 +372,11 @@ const memorySandboxTextFiles = async (sandbox, root = "/") => {
|
|
|
365
372
|
const memoryEnvironmentSchema = z.object({
|
|
366
373
|
files: z.record(z.string(), z.string()).optional(),
|
|
367
374
|
cwd: z.string().optional(),
|
|
368
|
-
ports: z.array(z.number().int()).optional()
|
|
375
|
+
ports: z.array(z.number().int()).optional(),
|
|
376
|
+
// Plain variables for every process, under the platform's.
|
|
377
|
+
env: z.record(z.string(), z.string()).optional(),
|
|
378
|
+
// Recorded, not enforced: the memory sandbox has no network.
|
|
379
|
+
networkPolicy: z.object({ mode: z.nativeEnum(NetworkPolicy), allow: z.array(z.string()).optional() }).optional()
|
|
369
380
|
}).nullable().optional();
|
|
370
381
|
const fingerprint = (value) => {
|
|
371
382
|
let hash = 2166136261;
|
|
@@ -390,20 +401,36 @@ const memorySandboxProvider = defineSandboxProvider({
|
|
|
390
401
|
cwd: options.cwd ?? "/workspace",
|
|
391
402
|
ports: options.ports ?? []
|
|
392
403
|
});
|
|
393
|
-
const
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
404
|
+
const specEnv = options.env ?? {};
|
|
405
|
+
const open = async (ctx, bindingId, artifact) => {
|
|
406
|
+
for (const name of Object.keys(specEnv))
|
|
407
|
+
if (PLATFORM_ENVIRONMENT_NAMES.has(name)) throw new Error(`${name} is reserved`);
|
|
408
|
+
const sandbox = createMemorySandbox({
|
|
409
|
+
id: bindingId,
|
|
410
|
+
files: artifact.files,
|
|
411
|
+
cwd: artifact.cwd,
|
|
412
|
+
ports: artifact.ports,
|
|
413
|
+
networkPolicy: options.networkPolicy != null,
|
|
414
|
+
baseEnv: platformProcessEnvironment(ctx, specEnv)
|
|
415
|
+
});
|
|
416
|
+
if (options.networkPolicy != null) {
|
|
417
|
+
const policy = withPlatformEgressHosts(ctx, options.networkPolicy);
|
|
418
|
+
await sandbox.setNetworkPolicy?.(policy);
|
|
419
|
+
await reportPlatformNetworkPolicy(ctx, policy);
|
|
420
|
+
}
|
|
421
|
+
await writePlatformFiles(ctx, sandbox);
|
|
422
|
+
return sandbox;
|
|
423
|
+
};
|
|
399
424
|
return {
|
|
400
425
|
artifactKey: async (ctx) => `memory:${fingerprint(JSON.stringify(artifactFor(ctx.files)))}`,
|
|
401
426
|
prepare: async (ctx) => artifactFor(ctx.files),
|
|
427
|
+
// An in-memory sandbox runs from the moment it exists.
|
|
428
|
+
awaitRunning: async () => void 0,
|
|
402
429
|
start: async (ctx, _openOptions, artifact) => ({
|
|
403
|
-
handle: memoryHandle(open(ctx.session.bindingId, artifact)),
|
|
430
|
+
handle: memoryHandle(await open(ctx, ctx.session.bindingId, artifact)),
|
|
404
431
|
state: { id: ctx.session.bindingId }
|
|
405
432
|
}),
|
|
406
|
-
resume: async (
|
|
433
|
+
resume: async (ctx, artifact, state) => memoryHandle(await open(ctx, state.id, artifact)),
|
|
407
434
|
park: async (_ctx, _artifact, state) => state
|
|
408
435
|
};
|
|
409
436
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../src/sandbox/memory-sandbox.ts"],
|
|
4
|
-
"sourcesContent": ["import * as z from 'zod';\nimport type { JsonValue } from \"../json.mjs\";\nimport { encodeSandboxText, readAllBytes, utf8Encode } from \"./bytes.mjs\";\nimport { readTextFileStream, runCollect } from \"./convenience.mjs\";\nimport { runMemoryArgv, runMemoryScript, type MemoryShellFsIface } from \"./memory-shell.mjs\";\nimport { normalizePosixPath, posixDirname, resolvePosixPath } from \"./paths.mjs\";\nimport {\n defineSandboxProvider,\n NetworkPolicy,\n PortProtocol,\n SandboxEntryType,\n type DirEntryIface,\n type NetworkPolicyIface,\n type NetworkSandboxSessionIface,\n type SandboxMcpEndpoint,\n type SandboxProcessIface,\n type SandboxProcessOptionsIface,\n type SandboxProviderHandleIface,\n type StatIface,\n} from \"./types.mjs\";\n\n// An in-memory reference sandbox: a virtual filesystem plus a tiny command\n// interpreter (memory-shell.ts). Used by tests and the conformance kit, and as\n// the smallest complete example of the sandbox contract.\n\nexport interface MemorySandboxIface extends NetworkSandboxSessionIface {\n readonly networkPolicy: NetworkPolicyIface;\n readonly stopped: boolean;\n}\n\nexport interface CreateMemorySandboxArgsIface {\n id?: string;\n files?: Record<string, string | Uint8Array>;\n cwd?: string;\n ports?: number[];\n portUrl?: (args: { port: number; protocol: PortProtocol }) => string;\n // Optional capabilities; present only when given.\n computerUse?: () => Promise<SandboxMcpEndpoint>;\n screen?: NetworkSandboxSessionIface['screen'];\n localMcp?: () => Promise<SandboxMcpEndpoint[]>;\n networkPolicy?: boolean;\n now?: () => Date;\n}\n\ntype MemoryEntry =\n | { type: 'file'; data: Uint8Array; modifiedAt: Date }\n | { type: 'directory'; modifiedAt: Date };\n\ninterface ProcessOutputsIface {\n stdout: ReadableStreamDefaultController<Uint8Array> | null;\n stderr: ReadableStreamDefaultController<Uint8Array> | null;\n}\n\nconst fsError = (code: string, message: string) =>\n Object.assign(new Error(`${code}: ${message}`), { code });\n\nconst abortableSleep = (ms: number, signal: AbortSignal): Promise<void> =>\n new Promise<void>((resolve, reject) => {\n if (signal.aborted) {\n reject(signal.reason);\n return;\n }\n const timer = setTimeout(() => {\n signal.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n const onAbort = () => {\n clearTimeout(timer);\n reject(signal.reason);\n };\n signal.addEventListener('abort', onAbort, { once: true });\n });\n\nconst signalExitCode = (signal: string | undefined): number => {\n if (signal === 'SIGKILL' || signal === 'KILL' || signal === '9') return 137;\n if (signal === 'SIGINT' || signal === 'INT') return 130;\n return 143;\n};\n\nexport const createMemorySandbox = (\n args: CreateMemorySandboxArgsIface = {},\n): MemorySandboxIface => {\n const id = args.id ?? `memory-${crypto.randomUUID()}`;\n const cwd = normalizePosixPath(args.cwd ?? '/workspace');\n const now = args.now ?? (() => new Date());\n const entries = new Map<string, MemoryEntry>();\n const processes = new Set<SandboxProcessIface>();\n let networkPolicy: NetworkPolicyIface = { mode: NetworkPolicy.AllowAll };\n let stopped = false;\n\n const resolve = (path: string) => resolvePosixPath(cwd, path);\n\n const ensureDirectory = (path: string) => {\n const normalized = normalizePosixPath(path);\n const existing = entries.get(normalized);\n if (existing?.type === 'directory') return;\n if (existing?.type === 'file') throw fsError('ENOTDIR', `${normalized} is a file`);\n if (normalized !== '/') ensureDirectory(posixDirname(normalized));\n entries.set(normalized, { type: 'directory', modifiedAt: now() });\n };\n\n const putFile = (path: string, data: Uint8Array) => {\n const normalized = normalizePosixPath(path);\n if (entries.get(normalized)?.type === 'directory')\n throw fsError('EISDIR', `${normalized} is a directory`);\n ensureDirectory(posixDirname(normalized));\n entries.set(normalized, { type: 'file', data, modifiedAt: now() });\n };\n\n const children = (path: string): string[] => {\n const prefix = path === '/' ? '/' : `${path}/`;\n const names: string[] = [];\n for (const key of entries.keys()) {\n if (key !== path && key.startsWith(prefix) && !key.slice(prefix.length).includes('/')) {\n names.push(key.slice(prefix.length));\n }\n }\n return names.sort();\n };\n\n ensureDirectory('/');\n ensureDirectory(cwd);\n for (const [path, content] of Object.entries(args.files ?? {})) {\n putFile(resolve(path), content instanceof Uint8Array ? content : utf8Encode(content));\n }\n\n const shellFs: MemoryShellFsIface = {\n readFile: (path) => {\n const entry = entries.get(normalizePosixPath(path));\n return entry?.type === 'file' ? entry.data : null;\n },\n writeFile: (path, data, options) => {\n const entry = entries.get(normalizePosixPath(path));\n if (options.append && entry?.type === 'file') {\n const merged = new Uint8Array(entry.data.byteLength + data.byteLength);\n merged.set(entry.data, 0);\n merged.set(data, entry.data.byteLength);\n putFile(path, merged);\n return;\n }\n putFile(path, data);\n },\n kind: (path) => {\n const entry = entries.get(normalizePosixPath(path));\n return entry == null ? null : entry.type;\n },\n list: (path) => {\n const normalized = normalizePosixPath(path);\n return entries.get(normalized)?.type === 'directory' ? children(normalized) : null;\n },\n mkdir: (path, options) => {\n const normalized = normalizePosixPath(path);\n if (!options.parents && entries.get(posixDirname(normalized))?.type !== 'directory') {\n throw fsError('ENOENT', 'No such file or directory');\n }\n if (!options.parents && entries.has(normalized)) throw fsError('EEXIST', 'File exists');\n ensureDirectory(normalized);\n },\n };\n\n const statOf = (path: string): StatIface | null => {\n const entry = entries.get(path);\n if (entry == null) return null;\n return {\n path,\n type: entry.type === 'file' ? SandboxEntryType.File : SandboxEntryType.Directory,\n size: entry.type === 'file' ? entry.data.byteLength : 0,\n modifiedAt: entry.modifiedAt.toISOString(),\n mode: entry.type === 'file' ? 0o644 : 0o755,\n };\n };\n\n const spawn = async (options: SandboxProcessOptionsIface): Promise<SandboxProcessIface> => {\n const controller = new AbortController();\n let killedWith: string | null = null;\n const outputs: ProcessOutputsIface = { stdout: null, stderr: null };\n const stdout = new ReadableStream<Uint8Array>({\n start: (c) => {\n outputs.stdout = c;\n },\n });\n const stderr = new ReadableStream<Uint8Array>({\n start: (c) => {\n outputs.stderr = c;\n },\n });\n let self: SandboxProcessIface | null = null;\n let stdinWriter: WritableStreamDefaultWriter<Uint8Array> | null = null;\n let stdinSource: ReadableStream<Uint8Array>;\n if (options.stdin == null) {\n const pipe = new TransformStream<Uint8Array, Uint8Array>();\n stdinWriter = pipe.writable.getWriter();\n stdinSource = pipe.readable;\n } else if (options.stdin instanceof ReadableStream) {\n stdinSource = options.stdin;\n } else {\n const bytes = utf8Encode(options.stdin);\n stdinSource = new ReadableStream<Uint8Array>({\n start: (c) => {\n if (bytes.byteLength > 0) c.enqueue(bytes);\n c.close();\n },\n });\n }\n const stdinReader = stdinSource.getReader();\n const abortPromise = new Promise<null>((resolveAbort) =>\n controller.signal.addEventListener('abort', () => resolveAbort(null), { once: true }),\n );\n const readStdin = async (): Promise<Uint8Array | null> => {\n const result = await Promise.race([stdinReader.read(), abortPromise]);\n if (result == null) throw controller.signal.reason;\n return result.done ? null : result.value;\n };\n const emit = (\n target: ReadableStreamDefaultController<Uint8Array> | null,\n bytes: Uint8Array,\n ) => {\n if (bytes.byteLength > 0) target?.enqueue(bytes.slice());\n };\n const context = {\n fs: shellFs,\n io: {\n readStdin,\n stdout: (bytes: Uint8Array) => emit(outputs.stdout, bytes),\n stderr: (bytes: Uint8Array) => emit(outputs.stderr, bytes),\n signal: controller.signal,\n },\n cwd: options.cwd == null ? cwd : resolve(options.cwd),\n sleep: abortableSleep,\n };\n const timeout =\n options.timeoutMs == null\n ? null\n : setTimeout(() => {\n killedWith = 'timeout';\n controller.abort(new Error('timed out'));\n }, options.timeoutMs);\n const onAbortSignal = () => {\n killedWith ??= 'SIGTERM';\n controller.abort(new Error('aborted'));\n };\n options.abortSignal?.addEventListener('abort', onAbortSignal, { once: true });\n const exited = (async (): Promise<{ exitCode: number }> => {\n let exitCode: number;\n try {\n if (context.fs.kind(context.cwd) !== 'directory') {\n context.io.stderr(utf8Encode(`cd: ${context.cwd}: No such file or directory\\n`));\n exitCode = 1;\n } else if (options.shell === true) {\n const script = [options.command, ...(options.args ?? [])].join(' ');\n exitCode = await runMemoryScript({ ...context, script });\n } else {\n exitCode = await runMemoryArgv({\n ...context,\n argv: [options.command, ...(options.args ?? [])],\n });\n }\n } catch (error) {\n if (!controller.signal.aborted) {\n context.io.stderr(\n utf8Encode(`${error instanceof Error ? error.message : String(error)}\\n`),\n );\n exitCode = 1;\n } else {\n exitCode = killedWith === 'timeout' ? 124 : signalExitCode(killedWith ?? undefined);\n }\n }\n if (timeout != null) clearTimeout(timeout);\n options.abortSignal?.removeEventListener('abort', onAbortSignal);\n stdinReader.cancel().catch(() => undefined);\n outputs.stdout?.close();\n outputs.stderr?.close();\n if (self != null) processes.delete(self);\n return { exitCode };\n })();\n const child: SandboxProcessIface = {\n pid: null,\n stdout,\n stderr,\n write: async (data, writeOptions) => {\n if (stdinWriter == null) throw new Error('stdin was provided at spawn');\n const bytes = data instanceof Uint8Array ? data : utf8Encode(data);\n if (bytes.byteLength > 0) await stdinWriter.write(bytes);\n if (writeOptions?.end === true) await stdinWriter.close();\n },\n wait: () => exited,\n kill: async (signal) => {\n killedWith ??= signal ?? 'SIGTERM';\n controller.abort(new Error(`killed (${signal ?? 'SIGTERM'})`));\n await exited;\n },\n };\n self = child;\n processes.add(child);\n return child;\n };\n\n const sandbox: MemorySandboxIface = {\n id,\n defaultWorkingDirectory: cwd,\n ports: args.ports ?? [],\n get description() {\n return `In-memory sandbox ${id}. Working directory ${cwd}. Commands: echo, cat, ls, pwd, cd, true, false, sleep, exit, mkdir, sh -c.`;\n },\n get networkPolicy() {\n return networkPolicy;\n },\n get stopped() {\n return stopped;\n },\n readFile: async (options) => {\n const path = resolve(options.path);\n const entry = entries.get(path);\n if (entry == null) return null;\n if (entry.type === 'directory') throw fsError('EISDIR', `${path} is a directory`);\n const data = entry.data;\n const chunkBytes = 64 * 1024;\n let offset = 0;\n return new ReadableStream<Uint8Array>({\n pull: (controller) => {\n if (offset >= data.byteLength) {\n controller.close();\n return;\n }\n const end = Math.min(data.byteLength, offset + chunkBytes);\n controller.enqueue(data.slice(offset, end));\n offset = end;\n },\n });\n },\n readBinaryFile: async (options) => {\n const stream = await sandbox.readFile(options);\n return stream == null ? null : readAllBytes(stream);\n },\n readTextFile: async (options) => {\n const stream = await sandbox.readFile(options);\n return stream == null ? null : readTextFileStream(stream, options);\n },\n writeFile: async (options) => {\n const data = await readAllBytes(options.content);\n putFile(resolve(options.path), data);\n },\n writeBinaryFile: async (options) => {\n putFile(resolve(options.path), options.content.slice());\n },\n writeTextFile: async (options) => {\n putFile(resolve(options.path), encodeSandboxText(options.content, options.encoding));\n },\n spawn,\n run: (options) => runCollect({ spawn }, options),\n stat: async (options) => statOf(resolve(options.path)),\n readDir: async (options): Promise<DirEntryIface[]> => {\n const path = resolve(options.path);\n const entry = entries.get(path);\n if (entry == null) throw fsError('ENOENT', `${path}: No such file or directory`);\n if (entry.type !== 'directory') throw fsError('ENOTDIR', `${path} is not a directory`);\n return children(path).map((name) => {\n const childPath = path === '/' ? `/${name}` : `${path}/${name}`;\n const child = entries.get(childPath);\n return {\n name,\n path: childPath,\n type: child?.type === 'file' ? SandboxEntryType.File : SandboxEntryType.Directory,\n size: child?.type === 'file' ? child.data.byteLength : null,\n };\n });\n },\n resolvePath: resolve,\n removePath: async (options) => {\n const path = resolve(options.path);\n const entry = entries.get(path);\n if (entry == null) {\n if (options.force === true) return;\n throw fsError('ENOENT', `${path}: No such file or directory`);\n }\n if (path === '/') throw fsError('EPERM', 'refusing to remove /');\n if (entry.type === 'directory') {\n const prefix = `${path}/`;\n const nested = [...entries.keys()].filter((key) => key.startsWith(prefix));\n if (nested.length > 0 && options.recursive !== true)\n throw fsError('ENOTEMPTY', `${path}: Directory not empty`);\n for (const key of nested) entries.delete(key);\n }\n entries.delete(path);\n },\n getPortEndpoint: async (options) => {\n const protocol = options.protocol ?? PortProtocol.Http;\n return {\n url:\n args.portUrl?.({ port: options.port, protocol }) ??\n `${protocol}://127.0.0.1:${options.port}`,\n };\n },\n getPortUrl: async (options) => (await sandbox.getPortEndpoint(options)).url,\n stop: async () => {\n stopped = true;\n await Promise.all([...processes].map((child) => child.kill()));\n },\n destroy: async () => {\n await sandbox.stop();\n entries.clear();\n ensureDirectory('/');\n },\n };\n if (args.networkPolicy === true) {\n sandbox.setNetworkPolicy = async (policy) => {\n networkPolicy = policy;\n };\n }\n if (args.computerUse != null) sandbox.computerUse = args.computerUse;\n if (args.screen != null) sandbox.screen = args.screen;\n if (args.localMcp != null) sandbox.localMcp = args.localMcp;\n return sandbox;\n};\n\n// Every file of a memory sandbox as path \u2192 base64-free UTF-8 text (binary\n// files are skipped); handy for assertions.\nexport const memorySandboxTextFiles = async (\n sandbox: NetworkSandboxSessionIface,\n root = '/',\n): Promise<Record<string, string>> => {\n const out: Record<string, string> = {};\n const walk = async (path: string) => {\n for (const entry of await sandbox.readDir({ path })) {\n if (entry.type === SandboxEntryType.Directory) await walk(entry.path);\n else {\n const text = await sandbox.readTextFile({ path: entry.path });\n if (text != null) out[entry.path] = text;\n }\n }\n };\n await walk(root);\n return out;\n};\n\nconst memoryEnvironmentSchema = z\n .object({\n files: z.record(z.string(), z.string()).optional(),\n cwd: z.string().optional(),\n ports: z.array(z.number().int()).optional(),\n })\n .nullable()\n .optional();\n\nexport type MemorySandboxArtifact = { files: Record<string, string>; cwd: string; ports: number[] };\nexport type MemorySandboxState = { id: string };\n\nconst fingerprint = (value: string): string => {\n // FNV-1a, enough for a content key in an example provider.\n let hash = 0x811c9dc5;\n for (let i = 0; i < value.length; i += 1) {\n hash ^= value.charCodeAt(i);\n hash = Math.imul(hash, 0x01000193) >>> 0;\n }\n return hash.toString(16).padStart(8, '0');\n};\n\nconst memoryHandle = (\n sandbox: MemorySandboxIface,\n): SandboxProviderHandleIface<MemorySandboxIface> => ({\n sandbox,\n onSandboxStop: () => sandbox.stop(),\n onSandboxDelete: () => sandbox.destroy(),\n onRuntimeShutdown: () => sandbox.stop(),\n});\n\n// Example provider over the memory sandbox. Ephemeral: `resume` starts again\n// from the prepared artifact, so files written before a park are lost.\nexport const memorySandboxProvider = defineSandboxProvider<\n JsonValue,\n JsonValue,\n MemorySandboxArtifact,\n MemorySandboxState,\n MemorySandboxIface\n>({\n name: 'memory',\n environment: (rawOptions) => {\n const options = memoryEnvironmentSchema.parse(rawOptions) ?? {};\n const artifactFor = (files: Record<string, string>): MemorySandboxArtifact => ({\n files: { ...options.files, ...files },\n cwd: options.cwd ?? '/workspace',\n ports: options.ports ?? [],\n });\n const open = (bindingId: string, artifact: MemorySandboxArtifact) =>\n createMemorySandbox({\n id: bindingId,\n files: artifact.files,\n cwd: artifact.cwd,\n ports: artifact.ports,\n });\n return {\n artifactKey: async (ctx) => `memory:${fingerprint(JSON.stringify(artifactFor(ctx.files)))}`,\n prepare: async (ctx) => artifactFor(ctx.files),\n start: async (ctx, _openOptions, artifact) => ({\n handle: memoryHandle(open(ctx.session.bindingId, artifact)),\n state: { id: ctx.session.bindingId },\n }),\n resume: async (_ctx, artifact, state) => memoryHandle(open(state.id, artifact)),\n park: async (_ctx, _artifact, state) => state,\n };\n },\n});\n"],
|
|
5
|
-
"mappings": "AAAA,YAAY,OAAO;AAEnB,SAAS,mBAAmB,cAAc,kBAAkB;AAC5D,SAAS,oBAAoB,kBAAkB;AAC/C,SAAS,eAAe,uBAA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ChB,KAAK,SAAS;AAAA,MACd,OAAO,SAAS;AAAA,IAClB,CAAC;AACH,WAAO;AAAA,MACL,aAAa,OAAO,QAAQ,UAAU,YAAY,KAAK,UAAU,YAAY,IAAI,KAAK,CAAC,CAAC,CAAC;AAAA,MACzF,SAAS,OAAO,QAAQ,YAAY,IAAI,KAAK;AAAA,MAC7C,OAAO,OAAO,KAAK,cAAc,cAAc;AAAA,QAC7C,QAAQ,aAAa,KAAK,IAAI,QAAQ,WAAW,QAAQ,CAAC;AAAA,QAC1D,OAAO,EAAE,IAAI,IAAI,QAAQ,UAAU;AAAA,MACrC;AAAA,MACA,QAAQ,OAAO,MAAM,UAAU,UAAU,aAAa,KAAK,MAAM,IAAI,QAAQ,CAAC;AAAA,MAC9E,MAAM,OAAO,MAAM,WAAW,UAAU;AAAA,IAC1C;AAAA,EACF;AACF,CAAC;",
|
|
4
|
+
"sourcesContent": ["import * as z from 'zod';\nimport type { JsonValue } from \"../json.mjs\";\nimport { encodeSandboxText, readAllBytes, utf8Encode } from \"./bytes.mjs\";\nimport { readTextFileStream, runCollect } from \"./convenience.mjs\";\nimport { runMemoryArgv, runMemoryScript, type MemoryShellFsIface } from \"./memory-shell.mjs\";\nimport { normalizePosixPath, posixDirname, resolvePosixPath } from \"./paths.mjs\";\nimport {\n defineSandboxProvider,\n NetworkPolicy,\n PLATFORM_ENVIRONMENT_NAMES,\n platformProcessEnvironment,\n PortProtocol,\n reportPlatformNetworkPolicy,\n SandboxEntryType,\n withPlatformEgressHosts,\n writePlatformFiles,\n type DirEntryIface,\n type NetworkPolicyIface,\n type NetworkSandboxSessionIface,\n type SandboxMcpEndpoint,\n type SandboxProcessIface,\n type SandboxProcessOptionsIface,\n type SandboxProviderHandleIface,\n type SandboxStartContextIface,\n type StatIface,\n} from \"./types.mjs\";\n\n// An in-memory reference sandbox: a virtual filesystem plus a tiny command\n// interpreter (memory-shell.ts). Used by tests and the conformance kit, and as\n// the smallest complete example of the sandbox contract.\n\nexport interface MemorySandboxIface extends NetworkSandboxSessionIface {\n readonly networkPolicy: NetworkPolicyIface;\n readonly stopped: boolean;\n}\n\nexport interface CreateMemorySandboxArgsIface {\n id?: string;\n files?: Record<string, string | Uint8Array>;\n cwd?: string;\n ports?: number[];\n portUrl?: (args: { port: number; protocol: PortProtocol }) => string;\n // Optional capabilities; present only when given.\n computerUse?: () => Promise<SandboxMcpEndpoint>;\n screen?: NetworkSandboxSessionIface['screen'];\n localMcp?: () => Promise<SandboxMcpEndpoint[]>;\n networkPolicy?: boolean;\n // Every process's environment, under per-call env; read again for each process.\n baseEnv?: () => Promise<Record<string, string>>;\n now?: () => Date;\n}\n\ntype MemoryEntry =\n | { type: 'file'; data: Uint8Array; modifiedAt: Date }\n | { type: 'directory'; modifiedAt: Date };\n\ninterface ProcessOutputsIface {\n stdout: ReadableStreamDefaultController<Uint8Array> | null;\n stderr: ReadableStreamDefaultController<Uint8Array> | null;\n}\n\nconst fsError = (code: string, message: string) =>\n Object.assign(new Error(`${code}: ${message}`), { code });\n\nconst abortableSleep = (ms: number, signal: AbortSignal): Promise<void> =>\n new Promise<void>((resolve, reject) => {\n if (signal.aborted) {\n reject(signal.reason);\n return;\n }\n const timer = setTimeout(() => {\n signal.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n const onAbort = () => {\n clearTimeout(timer);\n reject(signal.reason);\n };\n signal.addEventListener('abort', onAbort, { once: true });\n });\n\nconst signalExitCode = (signal: string | undefined): number => {\n if (signal === 'SIGKILL' || signal === 'KILL' || signal === '9') return 137;\n if (signal === 'SIGINT' || signal === 'INT') return 130;\n return 143;\n};\n\nexport const createMemorySandbox = (\n args: CreateMemorySandboxArgsIface = {},\n): MemorySandboxIface => {\n const id = args.id ?? `memory-${crypto.randomUUID()}`;\n const cwd = normalizePosixPath(args.cwd ?? '/workspace');\n const now = args.now ?? (() => new Date());\n const entries = new Map<string, MemoryEntry>();\n const processes = new Set<SandboxProcessIface>();\n let networkPolicy: NetworkPolicyIface = { mode: NetworkPolicy.AllowAll };\n let stopped = false;\n\n const resolve = (path: string) => resolvePosixPath(cwd, path);\n\n const ensureDirectory = (path: string) => {\n const normalized = normalizePosixPath(path);\n const existing = entries.get(normalized);\n if (existing?.type === 'directory') return;\n if (existing?.type === 'file') throw fsError('ENOTDIR', `${normalized} is a file`);\n if (normalized !== '/') ensureDirectory(posixDirname(normalized));\n entries.set(normalized, { type: 'directory', modifiedAt: now() });\n };\n\n const putFile = (path: string, data: Uint8Array) => {\n const normalized = normalizePosixPath(path);\n if (entries.get(normalized)?.type === 'directory')\n throw fsError('EISDIR', `${normalized} is a directory`);\n ensureDirectory(posixDirname(normalized));\n entries.set(normalized, { type: 'file', data, modifiedAt: now() });\n };\n\n const children = (path: string): string[] => {\n const prefix = path === '/' ? '/' : `${path}/`;\n const names: string[] = [];\n for (const key of entries.keys()) {\n if (key !== path && key.startsWith(prefix) && !key.slice(prefix.length).includes('/')) {\n names.push(key.slice(prefix.length));\n }\n }\n return names.sort();\n };\n\n ensureDirectory('/');\n ensureDirectory(cwd);\n for (const [path, content] of Object.entries(args.files ?? {})) {\n putFile(resolve(path), content instanceof Uint8Array ? content : utf8Encode(content));\n }\n\n const shellFs: MemoryShellFsIface = {\n readFile: (path) => {\n const entry = entries.get(normalizePosixPath(path));\n return entry?.type === 'file' ? entry.data : null;\n },\n writeFile: (path, data, options) => {\n const entry = entries.get(normalizePosixPath(path));\n if (options.append && entry?.type === 'file') {\n const merged = new Uint8Array(entry.data.byteLength + data.byteLength);\n merged.set(entry.data, 0);\n merged.set(data, entry.data.byteLength);\n putFile(path, merged);\n return;\n }\n putFile(path, data);\n },\n kind: (path) => {\n const entry = entries.get(normalizePosixPath(path));\n return entry == null ? null : entry.type;\n },\n list: (path) => {\n const normalized = normalizePosixPath(path);\n return entries.get(normalized)?.type === 'directory' ? children(normalized) : null;\n },\n mkdir: (path, options) => {\n const normalized = normalizePosixPath(path);\n if (!options.parents && entries.get(posixDirname(normalized))?.type !== 'directory') {\n throw fsError('ENOENT', 'No such file or directory');\n }\n if (!options.parents && entries.has(normalized)) throw fsError('EEXIST', 'File exists');\n ensureDirectory(normalized);\n },\n };\n\n const statOf = (path: string): StatIface | null => {\n const entry = entries.get(path);\n if (entry == null) return null;\n return {\n path,\n type: entry.type === 'file' ? SandboxEntryType.File : SandboxEntryType.Directory,\n size: entry.type === 'file' ? entry.data.byteLength : 0,\n modifiedAt: entry.modifiedAt.toISOString(),\n mode: entry.type === 'file' ? 0o644 : 0o755,\n };\n };\n\n const spawn = async (options: SandboxProcessOptionsIface): Promise<SandboxProcessIface> => {\n const env = { ...(await args.baseEnv?.()), ...options.env };\n const controller = new AbortController();\n let killedWith: string | null = null;\n const outputs: ProcessOutputsIface = { stdout: null, stderr: null };\n const stdout = new ReadableStream<Uint8Array>({\n start: (c) => {\n outputs.stdout = c;\n },\n });\n const stderr = new ReadableStream<Uint8Array>({\n start: (c) => {\n outputs.stderr = c;\n },\n });\n let self: SandboxProcessIface | null = null;\n let stdinWriter: WritableStreamDefaultWriter<Uint8Array> | null = null;\n let stdinSource: ReadableStream<Uint8Array>;\n if (options.stdin == null) {\n const pipe = new TransformStream<Uint8Array, Uint8Array>();\n stdinWriter = pipe.writable.getWriter();\n stdinSource = pipe.readable;\n } else if (options.stdin instanceof ReadableStream) {\n stdinSource = options.stdin;\n } else {\n const bytes = utf8Encode(options.stdin);\n stdinSource = new ReadableStream<Uint8Array>({\n start: (c) => {\n if (bytes.byteLength > 0) c.enqueue(bytes);\n c.close();\n },\n });\n }\n const stdinReader = stdinSource.getReader();\n const abortPromise = new Promise<null>((resolveAbort) =>\n controller.signal.addEventListener('abort', () => resolveAbort(null), { once: true }),\n );\n const readStdin = async (): Promise<Uint8Array | null> => {\n const result = await Promise.race([stdinReader.read(), abortPromise]);\n if (result == null) throw controller.signal.reason;\n return result.done ? null : result.value;\n };\n const emit = (\n target: ReadableStreamDefaultController<Uint8Array> | null,\n bytes: Uint8Array,\n ) => {\n if (bytes.byteLength > 0) target?.enqueue(bytes.slice());\n };\n const context = {\n fs: shellFs,\n io: {\n readStdin,\n stdout: (bytes: Uint8Array) => emit(outputs.stdout, bytes),\n stderr: (bytes: Uint8Array) => emit(outputs.stderr, bytes),\n signal: controller.signal,\n },\n cwd: options.cwd == null ? cwd : resolve(options.cwd),\n env,\n sleep: abortableSleep,\n };\n const timeout =\n options.timeoutMs == null\n ? null\n : setTimeout(() => {\n killedWith = 'timeout';\n controller.abort(new Error('timed out'));\n }, options.timeoutMs);\n const onAbortSignal = () => {\n killedWith ??= 'SIGTERM';\n controller.abort(new Error('aborted'));\n };\n options.abortSignal?.addEventListener('abort', onAbortSignal, { once: true });\n const exited = (async (): Promise<{ exitCode: number }> => {\n let exitCode: number;\n try {\n if (context.fs.kind(context.cwd) !== 'directory') {\n context.io.stderr(utf8Encode(`cd: ${context.cwd}: No such file or directory\\n`));\n exitCode = 1;\n } else if (options.shell === true) {\n const script = [options.command, ...(options.args ?? [])].join(' ');\n exitCode = await runMemoryScript({ ...context, script });\n } else {\n exitCode = await runMemoryArgv({\n ...context,\n argv: [options.command, ...(options.args ?? [])],\n });\n }\n } catch (error) {\n if (!controller.signal.aborted) {\n context.io.stderr(\n utf8Encode(`${error instanceof Error ? error.message : String(error)}\\n`),\n );\n exitCode = 1;\n } else {\n exitCode = killedWith === 'timeout' ? 124 : signalExitCode(killedWith ?? undefined);\n }\n }\n if (timeout != null) clearTimeout(timeout);\n options.abortSignal?.removeEventListener('abort', onAbortSignal);\n stdinReader.cancel().catch(() => undefined);\n outputs.stdout?.close();\n outputs.stderr?.close();\n if (self != null) processes.delete(self);\n return { exitCode };\n })();\n const child: SandboxProcessIface = {\n pid: null,\n stdout,\n stderr,\n write: async (data, writeOptions) => {\n if (stdinWriter == null) throw new Error('stdin was provided at spawn');\n const bytes = data instanceof Uint8Array ? data : utf8Encode(data);\n if (bytes.byteLength > 0) await stdinWriter.write(bytes);\n if (writeOptions?.end === true) await stdinWriter.close();\n },\n wait: () => exited,\n kill: async (signal) => {\n killedWith ??= signal ?? 'SIGTERM';\n controller.abort(new Error(`killed (${signal ?? 'SIGTERM'})`));\n await exited;\n },\n };\n self = child;\n processes.add(child);\n return child;\n };\n\n const sandbox: MemorySandboxIface = {\n id,\n defaultWorkingDirectory: cwd,\n ports: args.ports ?? [],\n get description() {\n return `In-memory sandbox ${id}. Working directory ${cwd}. Commands: echo, cat, ls, pwd, cd, true, false, sleep, exit, mkdir, sh -c.`;\n },\n get networkPolicy() {\n return networkPolicy;\n },\n get stopped() {\n return stopped;\n },\n readFile: async (options) => {\n const path = resolve(options.path);\n const entry = entries.get(path);\n if (entry == null) return null;\n if (entry.type === 'directory') throw fsError('EISDIR', `${path} is a directory`);\n const data = entry.data;\n const chunkBytes = 64 * 1024;\n let offset = 0;\n return new ReadableStream<Uint8Array>({\n pull: (controller) => {\n if (offset >= data.byteLength) {\n controller.close();\n return;\n }\n const end = Math.min(data.byteLength, offset + chunkBytes);\n controller.enqueue(data.slice(offset, end));\n offset = end;\n },\n });\n },\n readBinaryFile: async (options) => {\n const stream = await sandbox.readFile(options);\n return stream == null ? null : readAllBytes(stream);\n },\n readTextFile: async (options) => {\n const stream = await sandbox.readFile(options);\n return stream == null ? null : readTextFileStream(stream, options);\n },\n writeFile: async (options) => {\n const data = await readAllBytes(options.content);\n putFile(resolve(options.path), data);\n },\n writeBinaryFile: async (options) => {\n putFile(resolve(options.path), options.content.slice());\n },\n writeTextFile: async (options) => {\n putFile(resolve(options.path), encodeSandboxText(options.content, options.encoding));\n },\n spawn,\n run: (options) => runCollect({ spawn }, options),\n stat: async (options) => statOf(resolve(options.path)),\n readDir: async (options): Promise<DirEntryIface[]> => {\n const path = resolve(options.path);\n const entry = entries.get(path);\n if (entry == null) throw fsError('ENOENT', `${path}: No such file or directory`);\n if (entry.type !== 'directory') throw fsError('ENOTDIR', `${path} is not a directory`);\n return children(path).map((name) => {\n const childPath = path === '/' ? `/${name}` : `${path}/${name}`;\n const child = entries.get(childPath);\n return {\n name,\n path: childPath,\n type: child?.type === 'file' ? SandboxEntryType.File : SandboxEntryType.Directory,\n size: child?.type === 'file' ? child.data.byteLength : null,\n };\n });\n },\n resolvePath: resolve,\n removePath: async (options) => {\n const path = resolve(options.path);\n const entry = entries.get(path);\n if (entry == null) {\n if (options.force === true) return;\n throw fsError('ENOENT', `${path}: No such file or directory`);\n }\n if (path === '/') throw fsError('EPERM', 'refusing to remove /');\n if (entry.type === 'directory') {\n const prefix = `${path}/`;\n const nested = [...entries.keys()].filter((key) => key.startsWith(prefix));\n if (nested.length > 0 && options.recursive !== true)\n throw fsError('ENOTEMPTY', `${path}: Directory not empty`);\n for (const key of nested) entries.delete(key);\n }\n entries.delete(path);\n },\n getPortEndpoint: async (options) => {\n const protocol = options.protocol ?? PortProtocol.Http;\n return {\n url:\n args.portUrl?.({ port: options.port, protocol }) ??\n `${protocol}://127.0.0.1:${options.port}`,\n };\n },\n getPortUrl: async (options) => (await sandbox.getPortEndpoint(options)).url,\n stop: async () => {\n stopped = true;\n await Promise.all([...processes].map((child) => child.kill()));\n },\n destroy: async () => {\n await sandbox.stop();\n entries.clear();\n ensureDirectory('/');\n },\n };\n if (args.networkPolicy === true) {\n sandbox.setNetworkPolicy = async (policy) => {\n networkPolicy = policy;\n };\n }\n if (args.computerUse != null) sandbox.computerUse = args.computerUse;\n if (args.screen != null) sandbox.screen = args.screen;\n if (args.localMcp != null) sandbox.localMcp = args.localMcp;\n return sandbox;\n};\n\n// Every file of a memory sandbox as path \u2192 base64-free UTF-8 text (binary\n// files are skipped); handy for assertions.\nexport const memorySandboxTextFiles = async (\n sandbox: NetworkSandboxSessionIface,\n root = '/',\n): Promise<Record<string, string>> => {\n const out: Record<string, string> = {};\n const walk = async (path: string) => {\n for (const entry of await sandbox.readDir({ path })) {\n if (entry.type === SandboxEntryType.Directory) await walk(entry.path);\n else {\n const text = await sandbox.readTextFile({ path: entry.path });\n if (text != null) out[entry.path] = text;\n }\n }\n };\n await walk(root);\n return out;\n};\n\nconst memoryEnvironmentSchema = z\n .object({\n files: z.record(z.string(), z.string()).optional(),\n cwd: z.string().optional(),\n ports: z.array(z.number().int()).optional(),\n // Plain variables for every process, under the platform's.\n env: z.record(z.string(), z.string()).optional(),\n // Recorded, not enforced: the memory sandbox has no network.\n networkPolicy: z\n .object({ mode: z.nativeEnum(NetworkPolicy), allow: z.array(z.string()).optional() })\n .optional(),\n })\n .nullable()\n .optional();\n\nexport type MemorySandboxArtifact = { files: Record<string, string>; cwd: string; ports: number[] };\nexport type MemorySandboxState = { id: string };\n\nconst fingerprint = (value: string): string => {\n // FNV-1a, enough for a content key in an example provider.\n let hash = 0x811c9dc5;\n for (let i = 0; i < value.length; i += 1) {\n hash ^= value.charCodeAt(i);\n hash = Math.imul(hash, 0x01000193) >>> 0;\n }\n return hash.toString(16).padStart(8, '0');\n};\n\nconst memoryHandle = (\n sandbox: MemorySandboxIface,\n): SandboxProviderHandleIface<MemorySandboxIface> => ({\n sandbox,\n onSandboxStop: () => sandbox.stop(),\n onSandboxDelete: () => sandbox.destroy(),\n onRuntimeShutdown: () => sandbox.stop(),\n});\n\n// Example provider over the memory sandbox. Ephemeral: `resume` starts again\n// from the prepared artifact, so files written before a park are lost.\nexport const memorySandboxProvider = defineSandboxProvider<\n JsonValue,\n JsonValue,\n MemorySandboxArtifact,\n MemorySandboxState,\n MemorySandboxIface\n>({\n name: 'memory',\n environment: (rawOptions) => {\n const options = memoryEnvironmentSchema.parse(rawOptions) ?? {};\n const artifactFor = (files: Record<string, string>): MemorySandboxArtifact => ({\n files: { ...options.files, ...files },\n cwd: options.cwd ?? '/workspace',\n ports: options.ports ?? [],\n });\n const specEnv = options.env ?? {};\n const open = async (\n ctx: SandboxStartContextIface,\n bindingId: string,\n artifact: MemorySandboxArtifact,\n ) => {\n for (const name of Object.keys(specEnv))\n if (PLATFORM_ENVIRONMENT_NAMES.has(name)) throw new Error(`${name} is reserved`);\n const sandbox = createMemorySandbox({\n id: bindingId,\n files: artifact.files,\n cwd: artifact.cwd,\n ports: artifact.ports,\n networkPolicy: options.networkPolicy != null,\n baseEnv: platformProcessEnvironment(ctx, specEnv),\n });\n if (options.networkPolicy != null) {\n const policy = withPlatformEgressHosts(ctx, options.networkPolicy);\n await sandbox.setNetworkPolicy?.(policy);\n await reportPlatformNetworkPolicy(ctx, policy);\n }\n await writePlatformFiles(ctx, sandbox);\n return sandbox;\n };\n return {\n artifactKey: async (ctx) => `memory:${fingerprint(JSON.stringify(artifactFor(ctx.files)))}`,\n prepare: async (ctx) => artifactFor(ctx.files),\n // An in-memory sandbox runs from the moment it exists.\n awaitRunning: async () => undefined,\n start: async (ctx, _openOptions, artifact) => ({\n handle: memoryHandle(await open(ctx, ctx.session.bindingId, artifact)),\n state: { id: ctx.session.bindingId },\n }),\n resume: async (ctx, artifact, state) => memoryHandle(await open(ctx, state.id, artifact)),\n park: async (_ctx, _artifact, state) => state,\n };\n },\n});\n"],
|
|
5
|
+
"mappings": "AAAA,YAAY,OAAO;AAEnB,SAAS,mBAAmB,cAAc,kBAAkB;AAC5D,SAAS,oBAAoB,kBAAkB;AAC/C,SAAS,eAAe,uBAAgD;AACxE,SAAS,oBAAoB,cAAc,wBAAwB;AACnE;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAUK;AAoCP,MAAM,UAAU,CAAC,MAAc,YAC7B,OAAO,OAAO,IAAI,MAAM,GAAG,IAAI,KAAK,OAAO,EAAE,GAAG,EAAE,KAAK,CAAC;AAE1D,MAAM,iBAAiB,CAAC,IAAY,WAClC,IAAI,QAAc,CAAC,SAAS,WAAW;AACrC,MAAI,OAAO,SAAS;AAClB,WAAO,OAAO,MAAM;AACpB;AAAA,EACF;AACA,QAAM,QAAQ,WAAW,MAAM;AAC7B,WAAO,oBAAoB,SAAS,OAAO;AAC3C,YAAQ;AAAA,EACV,GAAG,EAAE;AACL,QAAM,UAAU,MAAM;AACpB,iBAAa,KAAK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AS;AAAA,QACd,OAAO,SAAS;AAAA,QAChB,eAAe,QAAQ,iBAAiB;AAAA,QACxC,SAAS,2BAA2B,KAAK,OAAO;AAAA,MAClD,CAAC;AACD,UAAI,QAAQ,iBAAiB,MAAM;AACjC,cAAM,SAAS,wBAAwB,KAAK,QAAQ,aAAa;AACjE,cAAM,QAAQ,mBAAmB,MAAM;AACvC,cAAM,4BAA4B,KAAK,MAAM;AAAA,MAC/C;AACA,YAAM,mBAAmB,KAAK,OAAO;AACrC,aAAO;AAAA,IACT;AACA,WAAO;AAAA,MACL,aAAa,OAAO,QAAQ,UAAU,YAAY,KAAK,UAAU,YAAY,IAAI,KAAK,CAAC,CAAC,CAAC;AAAA,MACzF,SAAS,OAAO,QAAQ,YAAY,IAAI,KAAK;AAAA;AAAA,MAE7C,cAAc,YAAY;AAAA,MAC1B,OAAO,OAAO,KAAK,cAAc,cAAc;AAAA,QAC7C,QAAQ,aAAa,MAAM,KAAK,KAAK,IAAI,QAAQ,WAAW,QAAQ,CAAC;AAAA,QACrE,OAAO,EAAE,IAAI,IAAI,QAAQ,UAAU;AAAA,MACrC;AAAA,MACA,QAAQ,OAAO,KAAK,UAAU,UAAU,aAAa,MAAM,KAAK,KAAK,MAAM,IAAI,QAAQ,CAAC;AAAA,MACxF,MAAM,OAAO,MAAM,WAAW,UAAU;AAAA,IAC1C;AAAA,EACF;AACF,CAAC;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -19,6 +19,7 @@ export interface MemoryShellContextIface {
|
|
|
19
19
|
fs: MemoryShellFsIface;
|
|
20
20
|
io: MemoryShellIoIface;
|
|
21
21
|
cwd: string;
|
|
22
|
+
env?: Record<string, string>;
|
|
22
23
|
sleep: (ms: number, signal: AbortSignal) => Promise<void>;
|
|
23
24
|
}
|
|
24
25
|
export declare const runMemoryScript: (args: MemoryShellContextIface & {
|
|
@@ -189,6 +189,20 @@ const runCommand = async (context, command) => {
|
|
|
189
189
|
context.cwd = path;
|
|
190
190
|
return 0;
|
|
191
191
|
}
|
|
192
|
+
case "printenv": {
|
|
193
|
+
const env = context.env ?? {};
|
|
194
|
+
if (args.length === 0) {
|
|
195
|
+
for (const [key, value] of Object.entries(env)) out(line(`${key}=${value}`));
|
|
196
|
+
return 0;
|
|
197
|
+
}
|
|
198
|
+
let status2 = 0;
|
|
199
|
+
for (const arg of args) {
|
|
200
|
+
const value = Object.hasOwn(env, arg) ? env[arg] : void 0;
|
|
201
|
+
if (value == null) status2 = 1;
|
|
202
|
+
else out(line(value));
|
|
203
|
+
}
|
|
204
|
+
return status2;
|
|
205
|
+
}
|
|
192
206
|
case "true":
|
|
193
207
|
return 0;
|
|
194
208
|
case "false":
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../src/sandbox/memory-shell.ts"],
|
|
4
|
-
"sourcesContent": ["import * as z from 'zod';\nimport { utf8Encode } from \"./bytes.mjs\";\nimport { posixBasename, resolvePosixPath } from \"./paths.mjs\";\n\n// A tiny command interpreter for the in-memory reference sandbox: enough of a\n// shell for tests and the conformance kit. Supports `;`, `&&`, `||`, newlines,\n// single and double quotes, `> file`, `>> file`, `>&2`, and the commands echo,\n// cat, ls, pwd, cd, true, false, sleep, exit, mkdir and `sh -c` / `bash -c`.\n\nexport interface MemoryShellFsIface {\n readFile(path: string): Uint8Array | null;\n writeFile(path: string, data: Uint8Array, options: { append: boolean }): void;\n kind(path: string): 'file' | 'directory' | null;\n list(path: string): string[] | null;\n mkdir(path: string, options: { parents: boolean }): void;\n}\n\nexport interface MemoryShellIoIface {\n // Next stdin chunk, or null at end of input.\n readStdin: () => Promise<Uint8Array | null>;\n stdout: (bytes: Uint8Array) => void;\n stderr: (bytes: Uint8Array) => void;\n signal: AbortSignal;\n}\n\nexport interface MemoryShellContextIface {\n fs: MemoryShellFsIface;\n io: MemoryShellIoIface;\n cwd: string;\n sleep: (ms: number, signal: AbortSignal) => Promise<void>;\n}\n\ntype Token = { kind: 'word'; value: string } | { kind: 'op'; value: string };\n\ninterface CommandIface {\n argv: string[];\n stdoutTo: { path: string; append: boolean } | 'stderr' | null;\n}\n\ninterface StepIface {\n connector: ';' | '&&' | '||';\n command: CommandIface;\n}\n\n// `exit N` unwinds the script as an error carrying the status.\ninterface ExitRequestIface extends Error {\n code: number;\n}\n\nconst EXIT_REQUEST = 'MemoryShellExit';\nconst exitFieldsSchema = z.object({ code: z.number() });\n\nconst exitRequest = (code: number): ExitRequestIface =>\n Object.assign(new Error(`exit ${code}`), { name: EXIT_REQUEST, code });\n\nconst isExitRequest = (cause: unknown): cause is ExitRequestIface =>\n cause instanceof Error &&\n cause.name === EXIT_REQUEST &&\n exitFieldsSchema.safeParse(cause).success;\n\nconst tokenize = (script: string): Token[] => {\n const tokens: Token[] = [];\n let word: string | null = null;\n const flush = () => {\n if (word != null) tokens.push({ kind: 'word', value: word });\n word = null;\n };\n for (let i = 0; i < script.length; i += 1) {\n const char = script[i] ?? '';\n if (char === \"'\") {\n const end = script.indexOf(\"'\", i + 1);\n const stop = end < 0 ? script.length : end;\n word = (word ?? '') + script.slice(i + 1, stop);\n i = stop;\n continue;\n }\n if (char === '\"') {\n let value = '';\n let j = i + 1;\n for (; j < script.length && script[j] !== '\"'; j += 1) {\n if (script[j] === '\\\\' && j + 1 < script.length) {\n j += 1;\n }\n value += script[j] ?? '';\n }\n word = (word ?? '') + value;\n i = j;\n continue;\n }\n if (char === '\\\\' && i + 1 < script.length) {\n word = (word ?? '') + (script[i + 1] ?? '');\n i += 1;\n continue;\n }\n if (char === ' ' || char === '\\t') {\n flush();\n continue;\n }\n if (char === '\\n' || char === ';') {\n flush();\n tokens.push({ kind: 'op', value: ';' });\n continue;\n }\n if (char === '&' && script[i + 1] === '&') {\n flush();\n tokens.push({ kind: 'op', value: '&&' });\n i += 1;\n continue;\n }\n if (char === '|' && script[i + 1] === '|') {\n flush();\n tokens.push({ kind: 'op', value: '||' });\n i += 1;\n continue;\n }\n if (char === '>') {\n flush();\n if (script.startsWith('>&2', i)) {\n tokens.push({ kind: 'op', value: '>&2' });\n i += 2;\n } else if (script[i + 1] === '>') {\n tokens.push({ kind: 'op', value: '>>' });\n i += 1;\n } else {\n tokens.push({ kind: 'op', value: '>' });\n }\n continue;\n }\n if (char === '#' && word == null) {\n const end = script.indexOf('\\n', i);\n i = end < 0 ? script.length : end - 1;\n continue;\n }\n word = (word ?? '') + char;\n }\n flush();\n return tokens;\n};\n\nconst parse = (script: string): StepIface[] => {\n const steps: StepIface[] = [];\n let connector: StepIface['connector'] = ';';\n let command: CommandIface = { argv: [], stdoutTo: null };\n const push = () => {\n if (command.argv.length > 0) steps.push({ connector, command });\n command = { argv: [], stdoutTo: null };\n };\n const tokens = tokenize(script);\n for (let i = 0; i < tokens.length; i += 1) {\n const token = tokens[i];\n if (token == null) continue;\n if (token.kind === 'word') {\n command.argv.push(token.value);\n continue;\n }\n if (token.value === '>&2') {\n command.stdoutTo = 'stderr';\n continue;\n }\n if (token.value === '>' || token.value === '>>') {\n const target = tokens[i + 1];\n if (target?.kind === 'word') {\n command.stdoutTo = { path: target.value, append: token.value === '>>' };\n i += 1;\n }\n continue;\n }\n push();\n connector = token.value === '&&' ? '&&' : token.value === '||' ? '||' : ';';\n }\n push();\n return steps;\n};\n\nconst line = (text: string) => utf8Encode(`${text}\\n`);\n\nconst runCommand = async (\n context: MemoryShellContextIface,\n command: CommandIface,\n): Promise<number> => {\n const [name, ...args] = command.argv;\n const captured: Uint8Array[] = [];\n const out = (bytes: Uint8Array) => {\n if (command.stdoutTo == null) context.io.stdout(bytes);\n else if (command.stdoutTo === 'stderr') context.io.stderr(bytes);\n else captured.push(bytes);\n };\n const err = (text: string) => context.io.stderr(line(text));\n const status = await (async (): Promise<number> => {\n switch (name) {\n case 'echo': {\n const noNewline = args[0] === '-n';\n const text = (noNewline ? args.slice(1) : args).join(' ');\n out(utf8Encode(noNewline ? text : `${text}\\n`));\n return 0;\n }\n case 'cat': {\n if (args.length === 0) {\n for (;;) {\n const chunk = await context.io.readStdin();\n if (chunk == null) return 0;\n out(chunk);\n }\n }\n let status = 0;\n for (const arg of args) {\n const path = resolvePosixPath(context.cwd, arg);\n const data = context.fs.readFile(path);\n if (data == null) {\n err(\n `cat: ${arg}: ${context.fs.kind(path) === 'directory' ? 'Is a directory' : 'No such file or directory'}`,\n );\n status = 1;\n } else {\n out(data);\n }\n }\n return status;\n }\n case 'ls': {\n const targets = args.filter((arg) => !arg.startsWith('-'));\n let status = 0;\n for (const arg of targets.length === 0 ? ['.'] : targets) {\n const path = resolvePosixPath(context.cwd, arg);\n const kind = context.fs.kind(path);\n if (kind == null) {\n err(`ls: cannot access '${arg}': No such file or directory`);\n status = 2;\n } else if (kind === 'file') {\n out(line(posixBasename(path)));\n } else {\n for (const entry of context.fs.list(path) ?? []) out(line(entry));\n }\n }\n return status;\n }\n case 'pwd':\n out(line(context.cwd));\n return 0;\n case 'cd': {\n const path = resolvePosixPath(context.cwd, args[0] ?? '/');\n if (context.fs.kind(path) !== 'directory') {\n err(`cd: ${args[0] ?? '/'}: No such file or directory`);\n return 1;\n }\n context.cwd = path;\n return 0;\n }\n case 'true':\n return 0;\n case 'false':\n return 1;\n case 'sleep': {\n const seconds = Number(args[0] ?? '0');\n if (!Number.isFinite(seconds) || seconds < 0) {\n err(`sleep: invalid time interval '${args[0] ?? ''}'`);\n return 1;\n }\n await context.sleep(seconds * 1000, context.io.signal);\n return 0;\n }\n case 'exit': {\n const code = Number(args[0] ?? '0');\n throw exitRequest(Number.isInteger(code) ? code & 0xff : 2);\n }\n case 'mkdir': {\n const parents = args.includes('-p');\n for (const arg of args.filter((value) => !value.startsWith('-'))) {\n try {\n context.fs.mkdir(resolvePosixPath(context.cwd, arg), { parents });\n } catch (error) {\n err(\n `mkdir: cannot create directory '${arg}': ${error instanceof Error ? error.message : 'error'}`,\n );\n return 1;\n }\n }\n return 0;\n }\n case 'sh':\n case 'bash': {\n const flag = args.indexOf('-c');\n const script = flag >= 0 ? args[flag + 1] : undefined;\n if (script == null) {\n err(`${name}: interactive shells are not supported by the memory sandbox`);\n return 127;\n }\n return runMemoryScript({ ...context, script });\n }\n default:\n err(`${name ?? ''}: command not found`);\n return 127;\n }\n })();\n if (command.stdoutTo != null && command.stdoutTo !== 'stderr') {\n const path = resolvePosixPath(context.cwd, command.stdoutTo.path);\n const total = captured.reduce((sum, chunk) => sum + chunk.byteLength, 0);\n const data = new Uint8Array(total);\n let offset = 0;\n for (const chunk of captured) {\n data.set(chunk, offset);\n offset += chunk.byteLength;\n }\n context.fs.writeFile(path, data, { append: command.stdoutTo.append });\n }\n return status;\n};\n\n// Runs a script; resolves with its exit status. Aborting the signal stops it\n// between commands and inside `sleep` and stdin reads (the caller maps the\n// abort to a signal exit status).\nexport const runMemoryScript = async (\n args: MemoryShellContextIface & { script: string },\n): Promise<number> => {\n let status = 0;\n try {\n for (const step of parse(args.script)) {\n args.io.signal.throwIfAborted();\n if (step.connector === '&&' && status !== 0) continue;\n if (step.connector === '||' && status === 0) continue;\n status = await runCommand(args, step.command);\n }\n } catch (error) {\n if (isExitRequest(error)) return error.code;\n throw error;\n }\n return status;\n};\n\nexport const runMemoryArgv = async (\n args: MemoryShellContextIface & { argv: string[] },\n): Promise<number> => {\n try {\n return await runCommand(args, { argv: args.argv, stdoutTo: null });\n } catch (error) {\n if (isExitRequest(error)) return error.code;\n throw error;\n }\n};\n"],
|
|
5
|
-
"mappings": "AAAA,YAAY,OAAO;AACnB,SAAS,kBAAkB;AAC3B,SAAS,eAAe,wBAAwB;
|
|
4
|
+
"sourcesContent": ["import * as z from 'zod';\nimport { utf8Encode } from \"./bytes.mjs\";\nimport { posixBasename, resolvePosixPath } from \"./paths.mjs\";\n\n// A tiny command interpreter for the in-memory reference sandbox: enough of a\n// shell for tests and the conformance kit. Supports `;`, `&&`, `||`, newlines,\n// single and double quotes, `> file`, `>> file`, `>&2`, and the commands echo,\n// cat, ls, pwd, cd, true, false, sleep, exit, mkdir, printenv and `sh -c` / `bash -c`.\n\nexport interface MemoryShellFsIface {\n readFile(path: string): Uint8Array | null;\n writeFile(path: string, data: Uint8Array, options: { append: boolean }): void;\n kind(path: string): 'file' | 'directory' | null;\n list(path: string): string[] | null;\n mkdir(path: string, options: { parents: boolean }): void;\n}\n\nexport interface MemoryShellIoIface {\n // Next stdin chunk, or null at end of input.\n readStdin: () => Promise<Uint8Array | null>;\n stdout: (bytes: Uint8Array) => void;\n stderr: (bytes: Uint8Array) => void;\n signal: AbortSignal;\n}\n\nexport interface MemoryShellContextIface {\n fs: MemoryShellFsIface;\n io: MemoryShellIoIface;\n cwd: string;\n // The process's environment, which only printenv reads (no `$` expansion).\n env?: Record<string, string>;\n sleep: (ms: number, signal: AbortSignal) => Promise<void>;\n}\n\ntype Token = { kind: 'word'; value: string } | { kind: 'op'; value: string };\n\ninterface CommandIface {\n argv: string[];\n stdoutTo: { path: string; append: boolean } | 'stderr' | null;\n}\n\ninterface StepIface {\n connector: ';' | '&&' | '||';\n command: CommandIface;\n}\n\n// `exit N` unwinds the script as an error carrying the status.\ninterface ExitRequestIface extends Error {\n code: number;\n}\n\nconst EXIT_REQUEST = 'MemoryShellExit';\nconst exitFieldsSchema = z.object({ code: z.number() });\n\nconst exitRequest = (code: number): ExitRequestIface =>\n Object.assign(new Error(`exit ${code}`), { name: EXIT_REQUEST, code });\n\nconst isExitRequest = (cause: unknown): cause is ExitRequestIface =>\n cause instanceof Error &&\n cause.name === EXIT_REQUEST &&\n exitFieldsSchema.safeParse(cause).success;\n\nconst tokenize = (script: string): Token[] => {\n const tokens: Token[] = [];\n let word: string | null = null;\n const flush = () => {\n if (word != null) tokens.push({ kind: 'word', value: word });\n word = null;\n };\n for (let i = 0; i < script.length; i += 1) {\n const char = script[i] ?? '';\n if (char === \"'\") {\n const end = script.indexOf(\"'\", i + 1);\n const stop = end < 0 ? script.length : end;\n word = (word ?? '') + script.slice(i + 1, stop);\n i = stop;\n continue;\n }\n if (char === '\"') {\n let value = '';\n let j = i + 1;\n for (; j < script.length && script[j] !== '\"'; j += 1) {\n if (script[j] === '\\\\' && j + 1 < script.length) {\n j += 1;\n }\n value += script[j] ?? '';\n }\n word = (word ?? '') + value;\n i = j;\n continue;\n }\n if (char === '\\\\' && i + 1 < script.length) {\n word = (word ?? '') + (script[i + 1] ?? '');\n i += 1;\n continue;\n }\n if (char === ' ' || char === '\\t') {\n flush();\n continue;\n }\n if (char === '\\n' || char === ';') {\n flush();\n tokens.push({ kind: 'op', value: ';' });\n continue;\n }\n if (char === '&' && script[i + 1] === '&') {\n flush();\n tokens.push({ kind: 'op', value: '&&' });\n i += 1;\n continue;\n }\n if (char === '|' && script[i + 1] === '|') {\n flush();\n tokens.push({ kind: 'op', value: '||' });\n i += 1;\n continue;\n }\n if (char === '>') {\n flush();\n if (script.startsWith('>&2', i)) {\n tokens.push({ kind: 'op', value: '>&2' });\n i += 2;\n } else if (script[i + 1] === '>') {\n tokens.push({ kind: 'op', value: '>>' });\n i += 1;\n } else {\n tokens.push({ kind: 'op', value: '>' });\n }\n continue;\n }\n if (char === '#' && word == null) {\n const end = script.indexOf('\\n', i);\n i = end < 0 ? script.length : end - 1;\n continue;\n }\n word = (word ?? '') + char;\n }\n flush();\n return tokens;\n};\n\nconst parse = (script: string): StepIface[] => {\n const steps: StepIface[] = [];\n let connector: StepIface['connector'] = ';';\n let command: CommandIface = { argv: [], stdoutTo: null };\n const push = () => {\n if (command.argv.length > 0) steps.push({ connector, command });\n command = { argv: [], stdoutTo: null };\n };\n const tokens = tokenize(script);\n for (let i = 0; i < tokens.length; i += 1) {\n const token = tokens[i];\n if (token == null) continue;\n if (token.kind === 'word') {\n command.argv.push(token.value);\n continue;\n }\n if (token.value === '>&2') {\n command.stdoutTo = 'stderr';\n continue;\n }\n if (token.value === '>' || token.value === '>>') {\n const target = tokens[i + 1];\n if (target?.kind === 'word') {\n command.stdoutTo = { path: target.value, append: token.value === '>>' };\n i += 1;\n }\n continue;\n }\n push();\n connector = token.value === '&&' ? '&&' : token.value === '||' ? '||' : ';';\n }\n push();\n return steps;\n};\n\nconst line = (text: string) => utf8Encode(`${text}\\n`);\n\nconst runCommand = async (\n context: MemoryShellContextIface,\n command: CommandIface,\n): Promise<number> => {\n const [name, ...args] = command.argv;\n const captured: Uint8Array[] = [];\n const out = (bytes: Uint8Array) => {\n if (command.stdoutTo == null) context.io.stdout(bytes);\n else if (command.stdoutTo === 'stderr') context.io.stderr(bytes);\n else captured.push(bytes);\n };\n const err = (text: string) => context.io.stderr(line(text));\n const status = await (async (): Promise<number> => {\n switch (name) {\n case 'echo': {\n const noNewline = args[0] === '-n';\n const text = (noNewline ? args.slice(1) : args).join(' ');\n out(utf8Encode(noNewline ? text : `${text}\\n`));\n return 0;\n }\n case 'cat': {\n if (args.length === 0) {\n for (;;) {\n const chunk = await context.io.readStdin();\n if (chunk == null) return 0;\n out(chunk);\n }\n }\n let status = 0;\n for (const arg of args) {\n const path = resolvePosixPath(context.cwd, arg);\n const data = context.fs.readFile(path);\n if (data == null) {\n err(\n `cat: ${arg}: ${context.fs.kind(path) === 'directory' ? 'Is a directory' : 'No such file or directory'}`,\n );\n status = 1;\n } else {\n out(data);\n }\n }\n return status;\n }\n case 'ls': {\n const targets = args.filter((arg) => !arg.startsWith('-'));\n let status = 0;\n for (const arg of targets.length === 0 ? ['.'] : targets) {\n const path = resolvePosixPath(context.cwd, arg);\n const kind = context.fs.kind(path);\n if (kind == null) {\n err(`ls: cannot access '${arg}': No such file or directory`);\n status = 2;\n } else if (kind === 'file') {\n out(line(posixBasename(path)));\n } else {\n for (const entry of context.fs.list(path) ?? []) out(line(entry));\n }\n }\n return status;\n }\n case 'pwd':\n out(line(context.cwd));\n return 0;\n case 'cd': {\n const path = resolvePosixPath(context.cwd, args[0] ?? '/');\n if (context.fs.kind(path) !== 'directory') {\n err(`cd: ${args[0] ?? '/'}: No such file or directory`);\n return 1;\n }\n context.cwd = path;\n return 0;\n }\n case 'printenv': {\n const env = context.env ?? {};\n if (args.length === 0) {\n for (const [key, value] of Object.entries(env)) out(line(`${key}=${value}`));\n return 0;\n }\n let status = 0;\n for (const arg of args) {\n const value = Object.hasOwn(env, arg) ? env[arg] : undefined;\n if (value == null) status = 1;\n else out(line(value));\n }\n return status;\n }\n case 'true':\n return 0;\n case 'false':\n return 1;\n case 'sleep': {\n const seconds = Number(args[0] ?? '0');\n if (!Number.isFinite(seconds) || seconds < 0) {\n err(`sleep: invalid time interval '${args[0] ?? ''}'`);\n return 1;\n }\n await context.sleep(seconds * 1000, context.io.signal);\n return 0;\n }\n case 'exit': {\n const code = Number(args[0] ?? '0');\n throw exitRequest(Number.isInteger(code) ? code & 0xff : 2);\n }\n case 'mkdir': {\n const parents = args.includes('-p');\n for (const arg of args.filter((value) => !value.startsWith('-'))) {\n try {\n context.fs.mkdir(resolvePosixPath(context.cwd, arg), { parents });\n } catch (error) {\n err(\n `mkdir: cannot create directory '${arg}': ${error instanceof Error ? error.message : 'error'}`,\n );\n return 1;\n }\n }\n return 0;\n }\n case 'sh':\n case 'bash': {\n const flag = args.indexOf('-c');\n const script = flag >= 0 ? args[flag + 1] : undefined;\n if (script == null) {\n err(`${name}: interactive shells are not supported by the memory sandbox`);\n return 127;\n }\n return runMemoryScript({ ...context, script });\n }\n default:\n err(`${name ?? ''}: command not found`);\n return 127;\n }\n })();\n if (command.stdoutTo != null && command.stdoutTo !== 'stderr') {\n const path = resolvePosixPath(context.cwd, command.stdoutTo.path);\n const total = captured.reduce((sum, chunk) => sum + chunk.byteLength, 0);\n const data = new Uint8Array(total);\n let offset = 0;\n for (const chunk of captured) {\n data.set(chunk, offset);\n offset += chunk.byteLength;\n }\n context.fs.writeFile(path, data, { append: command.stdoutTo.append });\n }\n return status;\n};\n\n// Runs a script; resolves with its exit status. Aborting the signal stops it\n// between commands and inside `sleep` and stdin reads (the caller maps the\n// abort to a signal exit status).\nexport const runMemoryScript = async (\n args: MemoryShellContextIface & { script: string },\n): Promise<number> => {\n let status = 0;\n try {\n for (const step of parse(args.script)) {\n args.io.signal.throwIfAborted();\n if (step.connector === '&&' && status !== 0) continue;\n if (step.connector === '||' && status === 0) continue;\n status = await runCommand(args, step.command);\n }\n } catch (error) {\n if (isExitRequest(error)) return error.code;\n throw error;\n }\n return status;\n};\n\nexport const runMemoryArgv = async (\n args: MemoryShellContextIface & { argv: string[] },\n): Promise<number> => {\n try {\n return await runCommand(args, { argv: args.argv, stdoutTo: null });\n } catch (error) {\n if (isExitRequest(error)) return error.code;\n throw error;\n }\n};\n"],
|
|
5
|
+
"mappings": "AAAA,YAAY,OAAO;AACnB,SAAS,kBAAkB;AAC3B,SAAS,eAAe,wBAAwB;AAiDhD,MAAM,eAAe;AACrB,MAAM,mBAAmB,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC;AAEtD,MAAM,cAAc,CAAC,SACnB,OAAO,OAAO,IAAI,MAAM,QAAQ,IAAI,EAAE,GAAG,EAAE,MAAM,cAAc,KAAK,CAAC;AAEvE,MAAM,gBAAgB,CAAC,UACrB,iBAAiB,SACjB,MAAM,SAAS,gBACf,iBAAiB,UAAU,KAAK,EAAE;AAEpC,MAAM,WAAW,CAAC,WAA4B;AAC5C,QAAM,SAAkB,CAAC;AACzB,MAAI,OAAsB;AAC1B,QAAM,QAAQ,MAAM;AAClB,QAAI,QAAQ,KAAM,QAAO,KAAK,EAAE,MAAM,QAAQ,OAAO,KAAK,CAAC;AAC3D,WAAO;AAAA,EACT;AACA,WAAS,IAAI,GAAG,IAAI,OAAO,QAAQ,KAAK,GAAG;AACzC,UAAM,OAAO,OAAO,CAAC,KAAK;AAC1B,QAAI,SAAS,KAAK;AAChB,YAAM,MAAM,OAAO,QAAQ,KAAK,IAAI,CAAC;AACrC,YAAM,OAAO,MAAM,IAAI,OAAO,SAAS;AACvC,cAAQ,QAAQ,MAAM,OAAO,MAAM,IAAI,GAAG,IAAI;AAC9C,UAAI;AACJ;AAAA,IACF;AACA,QAAI,SAAS,KAAK;AAChB,UAAI,QAAQ;AACZ,U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MAAI,QAAQ,YAAY,QAAQ,QAAQ,aAAa,UAAU;AAC7D,UAAM,OAAO,iBAAiB,QAAQ,KAAK,QAAQ,SAAS,IAAI;AAChE,UAAM,QAAQ,SAAS,OAAO,CAAC,KAAK,UAAU,MAAM,MAAM,YAAY,CAAC;AACvE,UAAM,OAAO,IAAI,WAAW,KAAK;AACjC,QAAI,SAAS;AACb,eAAW,SAAS,UAAU;AAC5B,WAAK,IAAI,OAAO,MAAM;AACtB,gBAAU,MAAM;AAAA,IAClB;AACA,YAAQ,GAAG,UAAU,MAAM,MAAM,EAAE,QAAQ,QAAQ,SAAS,OAAO,CAAC;AAAA,EACtE;AACA,SAAO;AACT;AAKO,MAAM,kBAAkB,OAC7B,SACoB;AACpB,MAAI,SAAS;AACb,MAAI;AACF,eAAW,QAAQ,MAAM,KAAK,MAAM,GAAG;AACrC,WAAK,GAAG,OAAO,eAAe;AAC9B,UAAI,KAAK,cAAc,QAAQ,WAAW,EAAG;AAC7C,UAAI,KAAK,cAAc,QAAQ,WAAW,EAAG;AAC7C,eAAS,MAAM,WAAW,MAAM,KAAK,OAAO;AAAA,IAC9C;AAAA,EACF,SAAS,OAAO;AACd,QAAI,cAAc,KAAK,EAAG,QAAO,MAAM;AACvC,UAAM;AAAA,EACR;AACA,SAAO;AACT;AAEO,MAAM,gBAAgB,OAC3B,SACoB;AACpB,MAAI;AACF,WAAO,MAAM,WAAW,MAAM,EAAE,MAAM,KAAK,MAAM,UAAU,KAAK,CAAC;AAAA,EACnE,SAAS,OAAO;AACd,QAAI,cAAc,KAAK,EAAG,QAAO,MAAM;AACvC,UAAM;AAAA,EACR;AACF;",
|
|
6
6
|
"names": ["status"]
|
|
7
7
|
}
|
|
@@ -291,7 +291,16 @@ export interface SandboxStartContextIface {
|
|
|
291
291
|
variables: SandboxVariablesIface;
|
|
292
292
|
repositories: SandboxRepositoriesIface;
|
|
293
293
|
actingUser: SandboxActingUserIface;
|
|
294
|
-
|
|
294
|
+
platformEnvironment?: () => Promise<Record<string, string>>;
|
|
295
|
+
platformEgressHosts?: string[];
|
|
296
|
+
platformNetworkPolicy: (policy: NetworkPolicyIface) => Promise<void>;
|
|
297
|
+
platformFiles?: () => Promise<Record<string, string>>;
|
|
298
|
+
}
|
|
299
|
+
export declare const PLATFORM_ENVIRONMENT_NAMES: ReadonlySet<string>;
|
|
300
|
+
export declare const platformProcessEnvironment: (ctx: Pick<SandboxStartContextIface, "platformEnvironment">, specEnv: Record<string, string>) => (() => Promise<Record<string, string>>);
|
|
301
|
+
export declare const writePlatformFiles: (ctx: Pick<SandboxStartContextIface, "platformFiles">, sandbox: Pick<SandboxSessionIface, "writeTextFile">) => Promise<void>;
|
|
302
|
+
export declare const reportPlatformNetworkPolicy: (ctx: Pick<SandboxStartContextIface, "platformNetworkPolicy">, policy: NetworkPolicyIface) => Promise<void>;
|
|
303
|
+
export declare const withPlatformEgressHosts: (ctx: Pick<SandboxStartContextIface, "platformEgressHosts">, policy: NetworkPolicyIface) => NetworkPolicyIface;
|
|
295
304
|
export declare enum SandboxSessionEndReason {
|
|
296
305
|
Completed = "completed",
|
|
297
306
|
Expired = "expired",
|
|
@@ -313,6 +322,9 @@ export interface SandboxProviderImplementationIface<OpenOptions, Artifact extend
|
|
|
313
322
|
editor?(ctx: SandboxOfferContextIface, state: State, request: SandboxEditorRequestIface): Promise<SandboxEditorResultIface>;
|
|
314
323
|
artifactKey(ctx: SandboxPrepareContextIface): Promise<string>;
|
|
315
324
|
prepare(ctx: SandboxPrepareContextIface): Promise<Artifact>;
|
|
325
|
+
awaitRunning(ctx: SandboxStartContextIface, state: State, options: {
|
|
326
|
+
timeoutMs: number;
|
|
327
|
+
}): Promise<void>;
|
|
316
328
|
start(ctx: SandboxStartContextIface, options: OpenOptions | undefined, artifact: Artifact): Promise<{
|
|
317
329
|
handle: SandboxProviderHandleIface<S>;
|
|
318
330
|
state: State;
|