@cloudflare/sandbox 0.6.11 → 0.7.1

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.
@@ -1,4 +1,4 @@
1
- import { t as Sandbox } from "../sandbox-HCG7Oeg0.js";
1
+ import { t as Sandbox } from "../sandbox-CgjQQZGw.js";
2
2
  import { ApplyPatchOperation, ApplyPatchResult, Editor as Editor$1, Shell as Shell$1, ShellAction, ShellResult } from "@openai/agents";
3
3
 
4
4
  //#region src/openai/index.d.ts
@@ -1,4 +1,4 @@
1
- import { l as createLogger } from "../dist-c_xYW5i_.js";
1
+ import { l as createLogger } from "../dist-D9B_6gn_.js";
2
2
  import { applyDiff } from "@openai/agents";
3
3
 
4
4
  //#region src/openai/index.ts
@@ -1,5 +1,5 @@
1
- import { t as Sandbox } from "../sandbox-HCG7Oeg0.js";
2
- import { t as OpencodeStartupContext } from "../contexts-CdrlvHWK.js";
1
+ import { t as Sandbox } from "../sandbox-CgjQQZGw.js";
2
+ import { t as OpencodeStartupContext } from "../contexts-uY_burk0.js";
3
3
  import { Config } from "@opencode-ai/sdk";
4
4
 
5
5
  //#region src/opencode/types.d.ts
@@ -66,7 +66,21 @@ declare class OpencodeStartupError extends Error {
66
66
  * const sandbox = getSandbox(env.Sandbox, 'my-agent')
67
67
  * const server = await createOpencodeServer(sandbox, {
68
68
  * directory: '/home/user/my-project',
69
- * config: { provider: { anthropic: { options: { apiKey: env.ANTHROPIC_KEY } } } }
69
+ * config: {
70
+ * provider: {
71
+ * anthropic: {
72
+ * options: { apiKey: env.ANTHROPIC_KEY }
73
+ * },
74
+ * // Optional: Route all providers through Cloudflare AI Gateway
75
+ * cloudflareAIGateway: {
76
+ * options: {
77
+ * accountId: env.CF_ACCOUNT_ID,
78
+ * gatewayId: env.CF_GATEWAY_ID,
79
+ * apiToken: env.CF_API_TOKEN
80
+ * }
81
+ * }
82
+ * }
83
+ * }
70
84
  * })
71
85
  *
72
86
  * // Proxy requests to the web UI
@@ -99,7 +113,21 @@ declare function createOpencodeServer(sandbox: Sandbox<unknown>, options?: Openc
99
113
  * const sandbox = getSandbox(env.Sandbox, 'my-agent')
100
114
  * const { client, server } = await createOpencode(sandbox, {
101
115
  * directory: '/home/user/my-project',
102
- * config: { provider: { anthropic: { options: { apiKey: env.ANTHROPIC_KEY } } } }
116
+ * config: {
117
+ * provider: {
118
+ * anthropic: {
119
+ * options: { apiKey: env.ANTHROPIC_KEY }
120
+ * },
121
+ * // Optional: Route all providers through Cloudflare AI Gateway
122
+ * cloudflareAIGateway: {
123
+ * options: {
124
+ * accountId: env.CF_ACCOUNT_ID,
125
+ * gatewayId: env.CF_GATEWAY_ID,
126
+ * apiToken: env.CF_API_TOKEN
127
+ * }
128
+ * }
129
+ * }
130
+ * }
103
131
  * })
104
132
  *
105
133
  * // Use the SDK client for programmatic access
@@ -136,7 +164,21 @@ declare function createOpencode<TClient = unknown>(sandbox: Sandbox<unknown>, op
136
164
  * const sandbox = getSandbox(env.Sandbox, 'opencode')
137
165
  * const server = await createOpencodeServer(sandbox, {
138
166
  * directory: '/home/user/project',
139
- * config: { provider: { anthropic: { options: { apiKey: env.ANTHROPIC_KEY } } } }
167
+ * config: {
168
+ * provider: {
169
+ * anthropic: {
170
+ * options: { apiKey: env.ANTHROPIC_KEY }
171
+ * },
172
+ * // Optional: Route all providers through Cloudflare AI Gateway
173
+ * cloudflareAIGateway: {
174
+ * options: {
175
+ * accountId: env.CF_ACCOUNT_ID,
176
+ * gatewayId: env.CF_GATEWAY_ID,
177
+ * apiToken: env.CF_API_TOKEN
178
+ * }
179
+ * }
180
+ * }
181
+ * }
140
182
  * })
141
183
  * return proxyToOpencode(request, sandbox, server)
142
184
  * }
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/opencode/types.ts","../../src/opencode/opencode.ts"],"sourcesContent":[],"mappings":";;;;;;;;AAMiB,UAAA,eAAA,CAMN;EAMM;EAaA,IAAA,CAAA,EAAA,M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AmEM,MAAA,EDzYN,OCyYM;EACL;EACA,MAAA,EDzYD,cCyYC;;;;;AAEU,cDrYR,oBAAA,SAA6B,KAAA,CCqYrB;;oBDnYM;wCAId,kCACC;;;;;;;AA1Cd;AAYA;AAaA;AAUA;;;;;;;;;AC0PA;;;;;;AAiEA;;;;;;;AAsEA;;;;;;;;;;;;;;;;;iBAvIsB,oBAAA,UACX,4BACC,kBACT,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA8DW,2CACX,4BACC,kBACT,QAAQ,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAmEV,eAAA,UACL,kBACA,0BACD,iBACP,WAAW,QAAQ"}
@@ -1,5 +1,5 @@
1
- import { l as createLogger } from "../dist-c_xYW5i_.js";
2
- import { t as ErrorCode } from "../errors-BCXUmJUn.js";
1
+ import { l as createLogger } from "../dist-D9B_6gn_.js";
2
+ import { t as ErrorCode } from "../errors-Bzl0ZNia.js";
3
3
 
4
4
  //#region src/opencode/types.ts
5
5
  /**
@@ -129,12 +129,22 @@ async function startOpencodeServer(sandbox, port, directory, config) {
129
129
  const env = {};
130
130
  if (config) {
131
131
  env.OPENCODE_CONFIG_CONTENT = JSON.stringify(config);
132
- if (config.provider && typeof config.provider === "object" && !Array.isArray(config.provider)) for (const [providerId, providerConfig] of Object.entries(config.provider)) {
133
- let apiKey = providerConfig?.options?.apiKey;
134
- if (!apiKey) apiKey = providerConfig?.apiKey;
135
- if (typeof apiKey === "string") {
136
- const envVar = `${providerId.toUpperCase()}_API_KEY`;
137
- env[envVar] = apiKey;
132
+ if (config.provider && typeof config.provider === "object" && !Array.isArray(config.provider)) {
133
+ for (const [providerId, providerConfig] of Object.entries(config.provider)) {
134
+ if (providerId === "cloudflareAIGateway") continue;
135
+ let apiKey = providerConfig?.options?.apiKey;
136
+ if (!apiKey) apiKey = providerConfig?.apiKey;
137
+ if (typeof apiKey === "string") {
138
+ const envVar = `${providerId.toUpperCase()}_API_KEY`;
139
+ env[envVar] = apiKey;
140
+ }
141
+ }
142
+ const aiGatewayConfig = config.provider.cloudflareAIGateway;
143
+ if (aiGatewayConfig?.options) {
144
+ const options = aiGatewayConfig.options;
145
+ if (typeof options.accountId === "string") env.CLOUDFLARE_ACCOUNT_ID = options.accountId;
146
+ if (typeof options.gatewayId === "string") env.CLOUDFLARE_GATEWAY_ID = options.gatewayId;
147
+ if (typeof options.apiToken === "string") env.CLOUDFLARE_API_TOKEN = options.apiToken;
138
148
  }
139
149
  }
140
150
  }
@@ -186,7 +196,21 @@ async function startOpencodeServer(sandbox, port, directory, config) {
186
196
  * const sandbox = getSandbox(env.Sandbox, 'my-agent')
187
197
  * const server = await createOpencodeServer(sandbox, {
188
198
  * directory: '/home/user/my-project',
189
- * config: { provider: { anthropic: { options: { apiKey: env.ANTHROPIC_KEY } } } }
199
+ * config: {
200
+ * provider: {
201
+ * anthropic: {
202
+ * options: { apiKey: env.ANTHROPIC_KEY }
203
+ * },
204
+ * // Optional: Route all providers through Cloudflare AI Gateway
205
+ * cloudflareAIGateway: {
206
+ * options: {
207
+ * accountId: env.CF_ACCOUNT_ID,
208
+ * gatewayId: env.CF_GATEWAY_ID,
209
+ * apiToken: env.CF_API_TOKEN
210
+ * }
211
+ * }
212
+ * }
213
+ * }
190
214
  * })
191
215
  *
192
216
  * // Proxy requests to the web UI
@@ -227,7 +251,21 @@ async function createOpencodeServer(sandbox, options) {
227
251
  * const sandbox = getSandbox(env.Sandbox, 'my-agent')
228
252
  * const { client, server } = await createOpencode(sandbox, {
229
253
  * directory: '/home/user/my-project',
230
- * config: { provider: { anthropic: { options: { apiKey: env.ANTHROPIC_KEY } } } }
254
+ * config: {
255
+ * provider: {
256
+ * anthropic: {
257
+ * options: { apiKey: env.ANTHROPIC_KEY }
258
+ * },
259
+ * // Optional: Route all providers through Cloudflare AI Gateway
260
+ * cloudflareAIGateway: {
261
+ * options: {
262
+ * accountId: env.CF_ACCOUNT_ID,
263
+ * gatewayId: env.CF_GATEWAY_ID,
264
+ * apiToken: env.CF_API_TOKEN
265
+ * }
266
+ * }
267
+ * }
268
+ * }
231
269
  * })
232
270
  *
233
271
  * // Use the SDK client for programmatic access
@@ -274,7 +312,21 @@ async function createOpencode(sandbox, options) {
274
312
  * const sandbox = getSandbox(env.Sandbox, 'opencode')
275
313
  * const server = await createOpencodeServer(sandbox, {
276
314
  * directory: '/home/user/project',
277
- * config: { provider: { anthropic: { options: { apiKey: env.ANTHROPIC_KEY } } } }
315
+ * config: {
316
+ * provider: {
317
+ * anthropic: {
318
+ * options: { apiKey: env.ANTHROPIC_KEY }
319
+ * },
320
+ * // Optional: Route all providers through Cloudflare AI Gateway
321
+ * cloudflareAIGateway: {
322
+ * options: {
323
+ * accountId: env.CF_ACCOUNT_ID,
324
+ * gatewayId: env.CF_GATEWAY_ID,
325
+ * apiToken: env.CF_API_TOKEN
326
+ * }
327
+ * }
328
+ * }
329
+ * }
278
330
  * })
279
331
  * return proxyToOpencode(request, sandbox, server)
280
332
  * }
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["createOpencodeClient: unknown","env: Record<string, string>"],"sources":["../../src/opencode/types.ts","../../src/opencode/opencode.ts"],"sourcesContent":["import type { Config } from '@opencode-ai/sdk';\nimport { ErrorCode, type OpencodeStartupContext } from '@repo/shared/errors';\n\n/**\n * Configuration options for starting OpenCode server\n */\nexport interface OpencodeOptions {\n /** Port for OpenCode server (default: 4096) */\n port?: number;\n /** Working directory for OpenCode (default: container's cwd) */\n directory?: string;\n /** OpenCode configuration */\n config?: Config;\n}\n\n/**\n * Server lifecycle management\n */\nexport interface OpencodeServer {\n /** Port the server is running on */\n port: number;\n /** Base URL for SDK client (http://localhost:{port}) */\n url: string;\n /** Close the server gracefully */\n close(): Promise<void>;\n}\n\n/**\n * Result from createOpencode()\n * Client type comes from @opencode-ai/sdk (user's version)\n */\nexport interface OpencodeResult<TClient = unknown> {\n /** OpenCode SDK client with Sandbox transport */\n client: TClient;\n /** Server lifecycle management */\n server: OpencodeServer;\n}\n\n/**\n * Error thrown when OpenCode server fails to start\n */\nexport class OpencodeStartupError extends Error {\n public readonly code = ErrorCode.OPENCODE_STARTUP_FAILED;\n public readonly context: OpencodeStartupContext;\n\n constructor(\n message: string,\n context: OpencodeStartupContext,\n options?: ErrorOptions\n ) {\n super(message, options);\n this.name = 'OpencodeStartupError';\n this.context = context;\n }\n}\n","import type { Config } from '@opencode-ai/sdk';\nimport { createLogger, type Logger, type Process } from '@repo/shared';\nimport type { Sandbox } from '../sandbox';\nimport type { OpencodeOptions, OpencodeResult, OpencodeServer } from './types';\nimport { OpencodeStartupError } from './types';\n\n// Lazy logger creation to avoid global scope restrictions in Workers\nfunction getLogger(): Logger {\n return createLogger({ component: 'sandbox-do', operation: 'opencode' });\n}\n\nconst DEFAULT_PORT = 4096;\nconst OPENCODE_SERVE = (port: number) =>\n `opencode serve --port ${port} --hostname 0.0.0.0`;\n\n/**\n * Build the full command, optionally with a directory prefix.\n * If directory is provided, we cd to it first so OpenCode uses it as cwd.\n */\nfunction buildOpencodeCommand(port: number, directory?: string): string {\n const serve = OPENCODE_SERVE(port);\n return directory ? `cd ${directory} && ${serve}` : serve;\n}\n\n// Dynamic import to handle peer dependency\n// Using unknown since SDK is optional peer dep - cast at usage site\nlet createOpencodeClient: unknown;\n\nasync function ensureSdkLoaded(): Promise<void> {\n if (createOpencodeClient) return;\n\n try {\n const sdk = await import('@opencode-ai/sdk');\n createOpencodeClient = sdk.createOpencodeClient;\n } catch {\n throw new Error(\n '@opencode-ai/sdk is required for OpenCode integration. ' +\n 'Install it with: npm install @opencode-ai/sdk'\n );\n }\n}\n\n/**\n * Find an existing OpenCode server process running on the specified port.\n * Returns the process if found and still active, null otherwise.\n * Matches by the serve command pattern since directory prefix may vary.\n */\nasync function findExistingOpencodeProcess(\n sandbox: Sandbox<unknown>,\n port: number\n): Promise<Process | null> {\n const processes = await sandbox.listProcesses();\n const serveCommand = OPENCODE_SERVE(port);\n\n for (const proc of processes) {\n // Match commands that contain the serve command (with or without cd prefix)\n if (proc.command.includes(serveCommand)) {\n if (proc.status === 'starting' || proc.status === 'running') {\n return proc;\n }\n }\n }\n\n return null;\n}\n\n/**\n * Ensures OpenCode server is running in the container.\n * Reuses existing process if one is already running on the specified port.\n * Handles concurrent startup attempts gracefully by retrying on failure.\n * Returns the process handle.\n */\nasync function ensureOpencodeServer(\n sandbox: Sandbox<unknown>,\n port: number,\n directory?: string,\n config?: Config\n): Promise<Process> {\n // Check if OpenCode is already running on this port\n const existingProcess = await findExistingOpencodeProcess(sandbox, port);\n if (existingProcess) {\n // Reuse existing process - wait for it to be ready if still starting\n if (existingProcess.status === 'starting') {\n getLogger().debug('Found starting OpenCode process, waiting for ready', {\n port,\n processId: existingProcess.id\n });\n try {\n await existingProcess.waitForPort(port, {\n mode: 'http',\n path: '/',\n timeout: 60_000\n });\n } catch (e) {\n const logs = await existingProcess.getLogs();\n throw new OpencodeStartupError(\n `OpenCode server failed to start. Stderr: ${logs.stderr || '(empty)'}`,\n { port, stderr: logs.stderr, command: existingProcess.command },\n { cause: e }\n );\n }\n }\n getLogger().debug('Reusing existing OpenCode process', {\n port,\n processId: existingProcess.id\n });\n return existingProcess;\n }\n\n // Try to start a new OpenCode server\n try {\n return await startOpencodeServer(sandbox, port, directory, config);\n } catch (startupError) {\n // Startup failed - check if another concurrent request started the server\n // This handles the race condition where multiple requests try to start simultaneously\n const retryProcess = await findExistingOpencodeProcess(sandbox, port);\n if (retryProcess) {\n getLogger().debug(\n 'Startup failed but found concurrent process, reusing',\n {\n port,\n processId: retryProcess.id\n }\n );\n // Wait for the concurrent server to be ready\n if (retryProcess.status === 'starting') {\n try {\n await retryProcess.waitForPort(port, {\n mode: 'http',\n path: '/',\n timeout: 60_000\n });\n } catch (e) {\n const logs = await retryProcess.getLogs();\n throw new OpencodeStartupError(\n `OpenCode server failed to start. Stderr: ${logs.stderr || '(empty)'}`,\n { port, stderr: logs.stderr, command: retryProcess.command },\n { cause: e }\n );\n }\n }\n return retryProcess;\n }\n\n // No concurrent server found - the failure was genuine\n throw startupError;\n }\n}\n\n/**\n * Internal function to start a new OpenCode server process.\n */\nasync function startOpencodeServer(\n sandbox: Sandbox<unknown>,\n port: number,\n directory?: string,\n config?: Config\n): Promise<Process> {\n getLogger().info('Starting OpenCode server', { port, directory });\n\n // Pass config via OPENCODE_CONFIG_CONTENT and also extract API keys to env vars\n // because OpenCode's provider auth looks for env vars like ANTHROPIC_API_KEY\n const env: Record<string, string> = {};\n\n if (config) {\n env.OPENCODE_CONFIG_CONTENT = JSON.stringify(config);\n\n // Extract API keys from provider config\n // Support both options.apiKey (official type) and legacy top-level apiKey\n if (\n config.provider &&\n typeof config.provider === 'object' &&\n !Array.isArray(config.provider)\n ) {\n for (const [providerId, providerConfig] of Object.entries(\n config.provider\n )) {\n // Try options.apiKey first (official Config type)\n let apiKey = providerConfig?.options?.apiKey;\n // Fall back to top-level apiKey for convenience\n if (!apiKey) {\n apiKey = (providerConfig as Record<string, unknown> | undefined)\n ?.apiKey as string | undefined;\n }\n if (typeof apiKey === 'string') {\n const envVar = `${providerId.toUpperCase()}_API_KEY`;\n env[envVar] = apiKey;\n }\n }\n }\n }\n\n const command = buildOpencodeCommand(port, directory);\n const process = await sandbox.startProcess(command, {\n env: Object.keys(env).length > 0 ? env : undefined\n });\n\n // Wait for server to be ready\n try {\n await process.waitForPort(port, {\n mode: 'http',\n path: '/',\n timeout: 60_000\n });\n getLogger().info('OpenCode server started successfully', {\n port,\n processId: process.id\n });\n } catch (e) {\n const logs = await process.getLogs();\n const error = e instanceof Error ? e : undefined;\n getLogger().error('OpenCode server failed to start', error, {\n port,\n stderr: logs.stderr\n });\n throw new OpencodeStartupError(\n `OpenCode server failed to start. Stderr: ${logs.stderr || '(empty)'}`,\n { port, stderr: logs.stderr, command },\n { cause: e }\n );\n }\n\n return process;\n}\n\n/**\n * Starts an OpenCode server inside a Sandbox container.\n *\n * This function manages the server lifecycle only - use `createOpencode()` if you\n * also need a typed SDK client for programmatic access.\n *\n * If an OpenCode server is already running on the specified port, this function\n * will reuse it instead of starting a new one.\n *\n * @param sandbox - The Sandbox instance to run OpenCode in\n * @param options - Configuration options\n * @returns Promise resolving to server handle { port, url, close() }\n *\n * @example\n * ```typescript\n * import { getSandbox } from '@cloudflare/sandbox'\n * import { createOpencodeServer } from '@cloudflare/sandbox/opencode'\n *\n * const sandbox = getSandbox(env.Sandbox, 'my-agent')\n * const server = await createOpencodeServer(sandbox, {\n * directory: '/home/user/my-project',\n * config: { provider: { anthropic: { options: { apiKey: env.ANTHROPIC_KEY } } } }\n * })\n *\n * // Proxy requests to the web UI\n * return sandbox.containerFetch(request, server.port)\n *\n * // When done\n * await server.close()\n * ```\n */\nexport async function createOpencodeServer(\n sandbox: Sandbox<unknown>,\n options?: OpencodeOptions\n): Promise<OpencodeServer> {\n const port = options?.port ?? DEFAULT_PORT;\n const process = await ensureOpencodeServer(\n sandbox,\n port,\n options?.directory,\n options?.config\n );\n\n return {\n port,\n url: `http://localhost:${port}`,\n close: () => process.kill('SIGTERM')\n };\n}\n\n/**\n * Creates an OpenCode server inside a Sandbox container and returns a typed SDK client.\n *\n * This function is API-compatible with OpenCode's own createOpencode(), but uses\n * Sandbox process management instead of Node.js spawn. The returned client uses\n * a custom fetch adapter to route requests through the Sandbox container.\n *\n * If an OpenCode server is already running on the specified port, this function\n * will reuse it instead of starting a new one.\n *\n * @param sandbox - The Sandbox instance to run OpenCode in\n * @param options - Configuration options\n * @returns Promise resolving to { client, server }\n *\n * @example\n * ```typescript\n * import { getSandbox } from '@cloudflare/sandbox'\n * import { createOpencode } from '@cloudflare/sandbox/opencode'\n *\n * const sandbox = getSandbox(env.Sandbox, 'my-agent')\n * const { client, server } = await createOpencode(sandbox, {\n * directory: '/home/user/my-project',\n * config: { provider: { anthropic: { options: { apiKey: env.ANTHROPIC_KEY } } } }\n * })\n *\n * // Use the SDK client for programmatic access\n * const session = await client.session.create()\n *\n * // When done\n * await server.close()\n * ```\n */\nexport async function createOpencode<TClient = unknown>(\n sandbox: Sandbox<unknown>,\n options?: OpencodeOptions\n): Promise<OpencodeResult<TClient>> {\n await ensureSdkLoaded();\n\n const server = await createOpencodeServer(sandbox, options);\n\n // Create SDK client with Sandbox transport\n // Cast from unknown - SDK is optional peer dependency loaded dynamically\n const clientFactory = createOpencodeClient as (options: {\n baseUrl: string;\n fetch: (request: Request) => Promise<Response>;\n }) => TClient;\n\n const client = clientFactory({\n baseUrl: server.url,\n fetch: (request: Request) => sandbox.containerFetch(request, server.port)\n });\n\n return { client, server };\n}\n\n/**\n * Proxy a request to the OpenCode web UI.\n *\n * This function handles the redirect and proxying only - you must start the\n * server separately using `createOpencodeServer()`.\n *\n * Specifically handles:\n * 1. Ensuring the `?url=` parameter is set (required for OpenCode's frontend to\n * make API calls through the proxy instead of directly to localhost:4096)\n * 2. Proxying the request to the container\n *\n * @param request - The incoming HTTP request\n * @param sandbox - The Sandbox instance running OpenCode\n * @param server - The OpenCode server handle from createOpencodeServer()\n * @returns Response from OpenCode or a redirect response\n *\n * @example\n * ```typescript\n * import { getSandbox } from '@cloudflare/sandbox'\n * import { createOpencodeServer, proxyToOpencode } from '@cloudflare/sandbox/opencode'\n *\n * export default {\n * async fetch(request: Request, env: Env) {\n * const sandbox = getSandbox(env.Sandbox, 'opencode')\n * const server = await createOpencodeServer(sandbox, {\n * directory: '/home/user/project',\n * config: { provider: { anthropic: { options: { apiKey: env.ANTHROPIC_KEY } } } }\n * })\n * return proxyToOpencode(request, sandbox, server)\n * }\n * }\n * ```\n */\nexport function proxyToOpencode(\n request: Request,\n sandbox: Sandbox<unknown>,\n server: OpencodeServer\n): Response | Promise<Response> {\n const url = new URL(request.url);\n\n // OpenCode's frontend defaults to http://127.0.0.1:4096 when hostname includes\n // \"localhost\" or \"opencode.ai\". The ?url= parameter overrides this behavior.\n // We only redirect GET requests for HTML pages (initial page load).\n // API calls (POST, PATCH, etc.) and asset requests are proxied directly\n // since redirecting POST loses the request body.\n if (!url.searchParams.has('url') && request.method === 'GET') {\n const accept = request.headers.get('accept') || '';\n const isHtmlRequest = accept.includes('text/html') || url.pathname === '/';\n if (isHtmlRequest) {\n url.searchParams.set('url', url.origin);\n return Response.redirect(url.toString(), 302);\n }\n }\n\n return sandbox.containerFetch(request, server.port);\n}\n"],"mappings":";;;;;;;AAyCA,IAAa,uBAAb,cAA0C,MAAM;CAC9C,AAAgB,OAAO,UAAU;CACjC,AAAgB;CAEhB,YACE,SACA,SACA,SACA;AACA,QAAM,SAAS,QAAQ;AACvB,OAAK,OAAO;AACZ,OAAK,UAAU;;;;;;AC7CnB,SAAS,YAAoB;AAC3B,QAAO,aAAa;EAAE,WAAW;EAAc,WAAW;EAAY,CAAC;;AAGzE,MAAM,eAAe;AACrB,MAAM,kBAAkB,SACtB,yBAAyB,KAAK;;;;;AAMhC,SAAS,qBAAqB,MAAc,WAA4B;CACtE,MAAM,QAAQ,eAAe,KAAK;AAClC,QAAO,YAAY,MAAM,UAAU,MAAM,UAAU;;AAKrD,IAAIA;AAEJ,eAAe,kBAAiC;AAC9C,KAAI,qBAAsB;AAE1B,KAAI;AAEF,0BADY,MAAM,OAAO,qBACE;SACrB;AACN,QAAM,IAAI,MACR,uGAED;;;;;;;;AASL,eAAe,4BACb,SACA,MACyB;CACzB,MAAM,YAAY,MAAM,QAAQ,eAAe;CAC/C,MAAM,eAAe,eAAe,KAAK;AAEzC,MAAK,MAAM,QAAQ,UAEjB,KAAI,KAAK,QAAQ,SAAS,aAAa,EACrC;MAAI,KAAK,WAAW,cAAc,KAAK,WAAW,UAChD,QAAO;;AAKb,QAAO;;;;;;;;AAST,eAAe,qBACb,SACA,MACA,WACA,QACkB;CAElB,MAAM,kBAAkB,MAAM,4BAA4B,SAAS,KAAK;AACxE,KAAI,iBAAiB;AAEnB,MAAI,gBAAgB,WAAW,YAAY;AACzC,cAAW,CAAC,MAAM,sDAAsD;IACtE;IACA,WAAW,gBAAgB;IAC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AC;EAEe;EAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoC3B,SAAgB,gBACd,SACA,SACA,QAC8B;CAC9B,MAAM,MAAM,IAAI,IAAI,QAAQ,IAAI;AAOhC,KAAI,CAAC,IAAI,aAAa,IAAI,MAAM,IAAI,QAAQ,WAAW,OAGrD;OAFe,QAAQ,QAAQ,IAAI,SAAS,IAAI,IACnB,SAAS,YAAY,IAAI,IAAI,aAAa,KACpD;AACjB,OAAI,aAAa,IAAI,OAAO,IAAI,OAAO;AACvC,UAAO,SAAS,SAAS,IAAI,UAAU,EAAE,IAAI;;;AAIjD,QAAO,QAAQ,eAAe,SAAS,OAAO,KAAK"}
1
+ {"version":3,"file":"index.js","names":["createOpencodeClient: unknown","env: Record<string, string>"],"sources":["../../src/opencode/types.ts","../../src/opencode/opencode.ts"],"sourcesContent":["import type { Config } from '@opencode-ai/sdk';\nimport { ErrorCode, type OpencodeStartupContext } from '@repo/shared/errors';\n\n/**\n * Configuration options for starting OpenCode server\n */\nexport interface OpencodeOptions {\n /** Port for OpenCode server (default: 4096) */\n port?: number;\n /** Working directory for OpenCode (default: container's cwd) */\n directory?: string;\n /** OpenCode configuration */\n config?: Config;\n}\n\n/**\n * Server lifecycle management\n */\nexport interface OpencodeServer {\n /** Port the server is running on */\n port: number;\n /** Base URL for SDK client (http://localhost:{port}) */\n url: string;\n /** Close the server gracefully */\n close(): Promise<void>;\n}\n\n/**\n * Result from createOpencode()\n * Client type comes from @opencode-ai/sdk (user's version)\n */\nexport interface OpencodeResult<TClient = unknown> {\n /** OpenCode SDK client with Sandbox transport */\n client: TClient;\n /** Server lifecycle management */\n server: OpencodeServer;\n}\n\n/**\n * Error thrown when OpenCode server fails to start\n */\nexport class OpencodeStartupError extends Error {\n public readonly code = ErrorCode.OPENCODE_STARTUP_FAILED;\n public readonly context: OpencodeStartupContext;\n\n constructor(\n message: string,\n context: OpencodeStartupContext,\n options?: ErrorOptions\n ) {\n super(message, options);\n this.name = 'OpencodeStartupError';\n this.context = context;\n }\n}\n","import type { Config } from '@opencode-ai/sdk';\nimport { createLogger, type Logger, type Process } from '@repo/shared';\nimport type { Sandbox } from '../sandbox';\nimport type { OpencodeOptions, OpencodeResult, OpencodeServer } from './types';\nimport { OpencodeStartupError } from './types';\n\n// Lazy logger creation to avoid global scope restrictions in Workers\nfunction getLogger(): Logger {\n return createLogger({ component: 'sandbox-do', operation: 'opencode' });\n}\n\nconst DEFAULT_PORT = 4096;\nconst OPENCODE_SERVE = (port: number) =>\n `opencode serve --port ${port} --hostname 0.0.0.0`;\n\n/**\n * Build the full command, optionally with a directory prefix.\n * If directory is provided, we cd to it first so OpenCode uses it as cwd.\n */\nfunction buildOpencodeCommand(port: number, directory?: string): string {\n const serve = OPENCODE_SERVE(port);\n return directory ? `cd ${directory} && ${serve}` : serve;\n}\n\n// Dynamic import to handle peer dependency\n// Using unknown since SDK is optional peer dep - cast at usage site\nlet createOpencodeClient: unknown;\n\nasync function ensureSdkLoaded(): Promise<void> {\n if (createOpencodeClient) return;\n\n try {\n const sdk = await import('@opencode-ai/sdk');\n createOpencodeClient = sdk.createOpencodeClient;\n } catch {\n throw new Error(\n '@opencode-ai/sdk is required for OpenCode integration. ' +\n 'Install it with: npm install @opencode-ai/sdk'\n );\n }\n}\n\n/**\n * Find an existing OpenCode server process running on the specified port.\n * Returns the process if found and still active, null otherwise.\n * Matches by the serve command pattern since directory prefix may vary.\n */\nasync function findExistingOpencodeProcess(\n sandbox: Sandbox<unknown>,\n port: number\n): Promise<Process | null> {\n const processes = await sandbox.listProcesses();\n const serveCommand = OPENCODE_SERVE(port);\n\n for (const proc of processes) {\n // Match commands that contain the serve command (with or without cd prefix)\n if (proc.command.includes(serveCommand)) {\n if (proc.status === 'starting' || proc.status === 'running') {\n return proc;\n }\n }\n }\n\n return null;\n}\n\n/**\n * Ensures OpenCode server is running in the container.\n * Reuses existing process if one is already running on the specified port.\n * Handles concurrent startup attempts gracefully by retrying on failure.\n * Returns the process handle.\n */\nasync function ensureOpencodeServer(\n sandbox: Sandbox<unknown>,\n port: number,\n directory?: string,\n config?: Config\n): Promise<Process> {\n // Check if OpenCode is already running on this port\n const existingProcess = await findExistingOpencodeProcess(sandbox, port);\n if (existingProcess) {\n // Reuse existing process - wait for it to be ready if still starting\n if (existingProcess.status === 'starting') {\n getLogger().debug('Found starting OpenCode process, waiting for ready', {\n port,\n processId: existingProcess.id\n });\n try {\n await existingProcess.waitForPort(port, {\n mode: 'http',\n path: '/',\n timeout: 60_000\n });\n } catch (e) {\n const logs = await existingProcess.getLogs();\n throw new OpencodeStartupError(\n `OpenCode server failed to start. Stderr: ${logs.stderr || '(empty)'}`,\n { port, stderr: logs.stderr, command: existingProcess.command },\n { cause: e }\n );\n }\n }\n getLogger().debug('Reusing existing OpenCode process', {\n port,\n processId: existingProcess.id\n });\n return existingProcess;\n }\n\n // Try to start a new OpenCode server\n try {\n return await startOpencodeServer(sandbox, port, directory, config);\n } catch (startupError) {\n // Startup failed - check if another concurrent request started the server\n // This handles the race condition where multiple requests try to start simultaneously\n const retryProcess = await findExistingOpencodeProcess(sandbox, port);\n if (retryProcess) {\n getLogger().debug(\n 'Startup failed but found concurrent process, reusing',\n {\n port,\n processId: retryProcess.id\n }\n );\n // Wait for the concurrent server to be ready\n if (retryProcess.status === 'starting') {\n try {\n await retryProcess.waitForPort(port, {\n mode: 'http',\n path: '/',\n timeout: 60_000\n });\n } catch (e) {\n const logs = await retryProcess.getLogs();\n throw new OpencodeStartupError(\n `OpenCode server failed to start. Stderr: ${logs.stderr || '(empty)'}`,\n { port, stderr: logs.stderr, command: retryProcess.command },\n { cause: e }\n );\n }\n }\n return retryProcess;\n }\n\n // No concurrent server found - the failure was genuine\n throw startupError;\n }\n}\n\n/**\n * Internal function to start a new OpenCode server process.\n */\nasync function startOpencodeServer(\n sandbox: Sandbox<unknown>,\n port: number,\n directory?: string,\n config?: Config\n): Promise<Process> {\n getLogger().info('Starting OpenCode server', { port, directory });\n\n // Pass config via OPENCODE_CONFIG_CONTENT and also extract API keys to env vars\n // because OpenCode's provider auth looks for env vars like ANTHROPIC_API_KEY\n const env: Record<string, string> = {};\n\n if (config) {\n env.OPENCODE_CONFIG_CONTENT = JSON.stringify(config);\n\n // Extract API keys from provider config\n // Support both options.apiKey (official type) and legacy top-level apiKey\n if (\n config.provider &&\n typeof config.provider === 'object' &&\n !Array.isArray(config.provider)\n ) {\n for (const [providerId, providerConfig] of Object.entries(\n config.provider\n )) {\n if (providerId === 'cloudflareAIGateway') {\n continue;\n }\n\n // Try options.apiKey first (official Config type)\n let apiKey = providerConfig?.options?.apiKey;\n // Fall back to top-level apiKey for convenience\n if (!apiKey) {\n apiKey = (providerConfig as Record<string, unknown> | undefined)\n ?.apiKey as string | undefined;\n }\n if (typeof apiKey === 'string') {\n const envVar = `${providerId.toUpperCase()}_API_KEY`;\n env[envVar] = apiKey;\n }\n }\n\n const aiGatewayConfig = config.provider.cloudflareAIGateway;\n if (aiGatewayConfig?.options) {\n const options = aiGatewayConfig.options as Record<string, unknown>;\n\n if (typeof options.accountId === 'string') {\n env.CLOUDFLARE_ACCOUNT_ID = options.accountId;\n }\n\n if (typeof options.gatewayId === 'string') {\n env.CLOUDFLARE_GATEWAY_ID = options.gatewayId;\n }\n\n if (typeof options.apiToken === 'string') {\n env.CLOUDFLARE_API_TOKEN = options.apiToken;\n }\n }\n }\n }\n\n const command = buildOpencodeCommand(port, directory);\n const process = await sandbox.startProcess(command, {\n env: Object.keys(env).length > 0 ? env : undefined\n });\n\n // Wait for server to be ready\n try {\n await process.waitForPort(port, {\n mode: 'http',\n path: '/',\n timeout: 60_000\n });\n getLogger().info('OpenCode server started successfully', {\n port,\n processId: process.id\n });\n } catch (e) {\n const logs = await process.getLogs();\n const error = e instanceof Error ? e : undefined;\n getLogger().error('OpenCode server failed to start', error, {\n port,\n stderr: logs.stderr\n });\n throw new OpencodeStartupError(\n `OpenCode server failed to start. Stderr: ${logs.stderr || '(empty)'}`,\n { port, stderr: logs.stderr, command },\n { cause: e }\n );\n }\n\n return process;\n}\n\n/**\n * Starts an OpenCode server inside a Sandbox container.\n *\n * This function manages the server lifecycle only - use `createOpencode()` if you\n * also need a typed SDK client for programmatic access.\n *\n * If an OpenCode server is already running on the specified port, this function\n * will reuse it instead of starting a new one.\n *\n * @param sandbox - The Sandbox instance to run OpenCode in\n * @param options - Configuration options\n * @returns Promise resolving to server handle { port, url, close() }\n *\n * @example\n * ```typescript\n * import { getSandbox } from '@cloudflare/sandbox'\n * import { createOpencodeServer } from '@cloudflare/sandbox/opencode'\n *\n * const sandbox = getSandbox(env.Sandbox, 'my-agent')\n * const server = await createOpencodeServer(sandbox, {\n * directory: '/home/user/my-project',\n * config: {\n * provider: {\n * anthropic: {\n * options: { apiKey: env.ANTHROPIC_KEY }\n * },\n * // Optional: Route all providers through Cloudflare AI Gateway\n * cloudflareAIGateway: {\n * options: {\n * accountId: env.CF_ACCOUNT_ID,\n * gatewayId: env.CF_GATEWAY_ID,\n * apiToken: env.CF_API_TOKEN\n * }\n * }\n * }\n * }\n * })\n *\n * // Proxy requests to the web UI\n * return sandbox.containerFetch(request, server.port)\n *\n * // When done\n * await server.close()\n * ```\n */\nexport async function createOpencodeServer(\n sandbox: Sandbox<unknown>,\n options?: OpencodeOptions\n): Promise<OpencodeServer> {\n const port = options?.port ?? DEFAULT_PORT;\n const process = await ensureOpencodeServer(\n sandbox,\n port,\n options?.directory,\n options?.config\n );\n\n return {\n port,\n url: `http://localhost:${port}`,\n close: () => process.kill('SIGTERM')\n };\n}\n\n/**\n * Creates an OpenCode server inside a Sandbox container and returns a typed SDK client.\n *\n * This function is API-compatible with OpenCode's own createOpencode(), but uses\n * Sandbox process management instead of Node.js spawn. The returned client uses\n * a custom fetch adapter to route requests through the Sandbox container.\n *\n * If an OpenCode server is already running on the specified port, this function\n * will reuse it instead of starting a new one.\n *\n * @param sandbox - The Sandbox instance to run OpenCode in\n * @param options - Configuration options\n * @returns Promise resolving to { client, server }\n *\n * @example\n * ```typescript\n * import { getSandbox } from '@cloudflare/sandbox'\n * import { createOpencode } from '@cloudflare/sandbox/opencode'\n *\n * const sandbox = getSandbox(env.Sandbox, 'my-agent')\n * const { client, server } = await createOpencode(sandbox, {\n * directory: '/home/user/my-project',\n * config: {\n * provider: {\n * anthropic: {\n * options: { apiKey: env.ANTHROPIC_KEY }\n * },\n * // Optional: Route all providers through Cloudflare AI Gateway\n * cloudflareAIGateway: {\n * options: {\n * accountId: env.CF_ACCOUNT_ID,\n * gatewayId: env.CF_GATEWAY_ID,\n * apiToken: env.CF_API_TOKEN\n * }\n * }\n * }\n * }\n * })\n *\n * // Use the SDK client for programmatic access\n * const session = await client.session.create()\n *\n * // When done\n * await server.close()\n * ```\n */\nexport async function createOpencode<TClient = unknown>(\n sandbox: Sandbox<unknown>,\n options?: OpencodeOptions\n): Promise<OpencodeResult<TClient>> {\n await ensureSdkLoaded();\n\n const server = await createOpencodeServer(sandbox, options);\n\n // Create SDK client with Sandbox transport\n // Cast from unknown - SDK is optional peer dependency loaded dynamically\n const clientFactory = createOpencodeClient as (options: {\n baseUrl: string;\n fetch: (request: Request) => Promise<Response>;\n }) => TClient;\n\n const client = clientFactory({\n baseUrl: server.url,\n fetch: (request: Request) => sandbox.containerFetch(request, server.port)\n });\n\n return { client, server };\n}\n\n/**\n * Proxy a request to the OpenCode web UI.\n *\n * This function handles the redirect and proxying only - you must start the\n * server separately using `createOpencodeServer()`.\n *\n * Specifically handles:\n * 1. Ensuring the `?url=` parameter is set (required for OpenCode's frontend to\n * make API calls through the proxy instead of directly to localhost:4096)\n * 2. Proxying the request to the container\n *\n * @param request - The incoming HTTP request\n * @param sandbox - The Sandbox instance running OpenCode\n * @param server - The OpenCode server handle from createOpencodeServer()\n * @returns Response from OpenCode or a redirect response\n *\n * @example\n * ```typescript\n * import { getSandbox } from '@cloudflare/sandbox'\n * import { createOpencodeServer, proxyToOpencode } from '@cloudflare/sandbox/opencode'\n *\n * export default {\n * async fetch(request: Request, env: Env) {\n * const sandbox = getSandbox(env.Sandbox, 'opencode')\n * const server = await createOpencodeServer(sandbox, {\n * directory: '/home/user/project',\n * config: {\n * provider: {\n * anthropic: {\n * options: { apiKey: env.ANTHROPIC_KEY }\n * },\n * // Optional: Route all providers through Cloudflare AI Gateway\n * cloudflareAIGateway: {\n * options: {\n * accountId: env.CF_ACCOUNT_ID,\n * gatewayId: env.CF_GATEWAY_ID,\n * apiToken: env.CF_API_TOKEN\n * }\n * }\n * }\n * }\n * })\n * return proxyToOpencode(request, sandbox, server)\n * }\n * }\n * ```\n */\nexport function proxyToOpencode(\n request: Request,\n sandbox: Sandbox<unknown>,\n server: OpencodeServer\n): Response | Promise<Response> {\n const url = new URL(request.url);\n\n // OpenCode's frontend defaults to http://127.0.0.1:4096 when hostname includes\n // \"localhost\" or \"opencode.ai\". The ?url= parameter overrides this behavior.\n // We only redirect GET requests for HTML pages (initial page load).\n // API calls (POST, PATCH, etc.) and asset requests are proxied directly\n // since redirecting POST loses the request body.\n if (!url.searchParams.has('url') && request.method === 'GET') {\n const accept = request.headers.get('accept') || '';\n const isHtmlRequest = accept.includes('text/html') || url.pathname === '/';\n if (isHtmlRequest) {\n url.searchParams.set('url', url.origin);\n return Response.redirect(url.toString(), 302);\n }\n }\n\n return sandbox.containerFetch(request, server.port);\n}\n"],"mappings":";;;;;;;AAyCA,IAAa,uBAAb,cAA0C,MAAM;CAC9C,AAAgB,OAAO,UAAU;CACjC,AAAgB;CAEhB,YACE,SACA,SACA,SACA;AACA,QAAM,SAAS,QAAQ;AACvB,OAAK,OAAO;AACZ,OAAK,UAAU;;;;;;AC7CnB,SAAS,YAAoB;AAC3B,QAAO,aAAa;EAAE,WAAW;EAAc,WAAW;EAAY,CAAC;;AAGzE,MAAM,eAAe;AACrB,MAAM,kBAAkB,SACtB,yBAAyB,KAAK;;;;;AAMhC,SAAS,qBAAqB,MAAc,WAA4B;CACtE,MAAM,QAAQ,eAAe,KAAK;AAClC,QAAO,YAAY,MAAM,UAAU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a,KACpD;AACjB,OAAI,aAAa,IAAI,OAAO,IAAI,OAAO;AACvC,UAAO,SAAS,SAAS,IAAI,UAAU,EAAE,IAAI;;;AAIjD,QAAO,QAAQ,eAAe,SAAS,OAAO,KAAK"}
@@ -110,9 +110,10 @@ interface CreateContextOptions {
110
110
  */
111
111
  cwd?: string;
112
112
  /**
113
- * Environment variables for the context
113
+ * Environment variables for the context.
114
+ * Undefined values are skipped (treated as "not configured").
114
115
  */
115
- envVars?: Record<string, string>;
116
+ envVars?: Record<string, string | undefined>;
116
117
  /**
117
118
  * Request timeout in milliseconds
118
119
  * @default 30000
@@ -152,9 +153,10 @@ interface RunCodeOptions {
152
153
  */
153
154
  language?: 'python' | 'javascript' | 'typescript';
154
155
  /**
155
- * Environment variables for this execution
156
+ * Environment variables for this execution.
157
+ * Undefined values are skipped (treated as "not configured").
156
158
  */
157
- envVars?: Record<string, string>;
159
+ envVars?: Record<string, string | undefined>;
158
160
  /**
159
161
  * Execution timeout in milliseconds
160
162
  * @default 60000
@@ -340,6 +342,12 @@ declare class Execution {
340
342
  toJSON(): ExecutionResult;
341
343
  }
342
344
  //#endregion
345
+ //#region ../shared/dist/pty-types.d.ts
346
+ interface PtyOptions {
347
+ cols?: number;
348
+ rows?: number;
349
+ }
350
+ //#endregion
343
351
  //#region ../shared/dist/types.d.ts
344
352
  interface BaseExecOptions {
345
353
  /**
@@ -350,8 +358,9 @@ interface BaseExecOptions {
350
358
  * Environment variables for this command invocation.
351
359
  * Values temporarily override session-level/container-level env for the
352
360
  * duration of the command but do not persist after it completes.
361
+ * Undefined values are skipped (treated as "not configured").
353
362
  */
354
- env?: Record<string, string>;
363
+ env?: Record<string, string | undefined>;
355
364
  /**
356
365
  * Working directory for command execution
357
366
  */
@@ -638,9 +647,10 @@ interface SessionOptions {
638
647
  */
639
648
  name?: string;
640
649
  /**
641
- * Environment variables for this session
650
+ * Environment variables for this session.
651
+ * Undefined values are skipped (treated as "not configured").
642
652
  */
643
- env?: Record<string, string>;
653
+ env?: Record<string, string | undefined>;
644
654
  /**
645
655
  * Working directory
646
656
  */
@@ -991,7 +1001,7 @@ interface ExecutionSession {
991
1001
  /** Clone depth for shallow clones (e.g., 1 for latest commit only) */
992
1002
  depth?: number;
993
1003
  }): Promise<GitCheckoutResult>;
994
- setEnvVars(envVars: Record<string, string>): Promise<void>;
1004
+ setEnvVars(envVars: Record<string, string | undefined>): Promise<void>;
995
1005
  createCodeContext(options?: CreateContextOptions): Promise<CodeContext>;
996
1006
  runCode(code: string, options?: RunCodeOptions): Promise<ExecutionResult>;
997
1007
  runCodeStream(code: string, options?: RunCodeOptions): Promise<ReadableStream<Uint8Array>>;
@@ -999,6 +1009,7 @@ interface ExecutionSession {
999
1009
  deleteCodeContext(contextId: string): Promise<void>;
1000
1010
  mountBucket(bucket: string, mountPath: string, options: MountBucketOptions): Promise<void>;
1001
1011
  unmountBucket(mountPath: string): Promise<void>;
1012
+ terminal(request: Request, options?: PtyOptions): Promise<Response>;
1002
1013
  }
1003
1014
  /**
1004
1015
  * Supported S3-compatible storage providers
@@ -1107,7 +1118,7 @@ interface ISandbox {
1107
1118
  /** Clone depth for shallow clones (e.g., 1 for latest commit only) */
1108
1119
  depth?: number;
1109
1120
  }): Promise<GitCheckoutResult>;
1110
- setEnvVars(envVars: Record<string, string>): Promise<void>;
1121
+ setEnvVars(envVars: Record<string, string | undefined>): Promise<void>;
1111
1122
  mountBucket(bucket: string, mountPath: string, options: MountBucketOptions): Promise<void>;
1112
1123
  unmountBucket(mountPath: string): Promise<void>;
1113
1124
  createSession(options?: SessionOptions): Promise<ExecutionSession>;
@@ -1333,7 +1344,7 @@ declare class CommandClient extends BaseHttpClient {
1333
1344
  */
1334
1345
  execute(command: string, sessionId: string, options?: {
1335
1346
  timeoutMs?: number;
1336
- env?: Record<string, string>;
1347
+ env?: Record<string, string | undefined>;
1337
1348
  cwd?: string;
1338
1349
  }): Promise<ExecuteResponse>;
1339
1350
  /**
@@ -1344,7 +1355,7 @@ declare class CommandClient extends BaseHttpClient {
1344
1355
  */
1345
1356
  executeStream(command: string, sessionId: string, options?: {
1346
1357
  timeoutMs?: number;
1347
- env?: Record<string, string>;
1358
+ env?: Record<string, string | undefined>;
1348
1359
  cwd?: string;
1349
1360
  }): Promise<ReadableStream<Uint8Array>>;
1350
1361
  }
@@ -1513,13 +1524,6 @@ declare class InterpreterClient extends BaseHttpClient {
1513
1524
  }
1514
1525
  //#endregion
1515
1526
  //#region src/clients/port-client.d.ts
1516
- /**
1517
- * Request interface for exposing ports
1518
- */
1519
- interface ExposePortRequest {
1520
- port: number;
1521
- name?: string;
1522
- }
1523
1527
  /**
1524
1528
  * Request interface for unexposing ports
1525
1529
  */
@@ -1570,7 +1574,7 @@ declare class ProcessClient extends BaseHttpClient {
1570
1574
  startProcess(command: string, sessionId: string, options?: {
1571
1575
  processId?: string;
1572
1576
  timeoutMs?: number;
1573
- env?: Record<string, string>;
1577
+ env?: Record<string, string | undefined>;
1574
1578
  cwd?: string;
1575
1579
  encoding?: string;
1576
1580
  autoCleanup?: boolean;
@@ -1625,7 +1629,7 @@ interface CommandsResponse extends BaseApiResponse {
1625
1629
  */
1626
1630
  interface CreateSessionRequest {
1627
1631
  id: string;
1628
- env?: Record<string, string>;
1632
+ env?: Record<string, string | undefined>;
1629
1633
  cwd?: string;
1630
1634
  }
1631
1635
  /**
@@ -1753,7 +1757,7 @@ declare class Sandbox<Env = unknown> extends Container<Env> implements ISandbox
1753
1757
  setBaseUrl(baseUrl: string): Promise<void>;
1754
1758
  setSleepAfter(sleepAfter: string | number): Promise<void>;
1755
1759
  setKeepAlive(keepAlive: boolean): Promise<void>;
1756
- setEnvVars(envVars: Record<string, string>): Promise<void>;
1760
+ setEnvVars(envVars: Record<string, string | undefined>): Promise<void>;
1757
1761
  /**
1758
1762
  * RPC method to configure container startup timeouts
1759
1763
  */
@@ -1961,9 +1965,34 @@ declare class Sandbox<Env = unknown> extends Container<Env> implements ISandbox
1961
1965
  includeHidden?: boolean;
1962
1966
  }): Promise<ListFilesResult>;
1963
1967
  exists(path: string, sessionId?: string): Promise<FileExistsResult>;
1968
+ /**
1969
+ * Expose a port and get a preview URL for accessing services running in the sandbox
1970
+ *
1971
+ * @param port - Port number to expose (1024-65535)
1972
+ * @param options - Configuration options
1973
+ * @param options.hostname - Your Worker's domain name (required for preview URL construction)
1974
+ * @param options.name - Optional friendly name for the port
1975
+ * @param options.token - Optional custom token for the preview URL (1-16 characters: lowercase letters, numbers, hyphens, underscores)
1976
+ * If not provided, a random 16-character token will be generated automatically
1977
+ * @returns Preview URL information including the full URL, port number, and optional name
1978
+ *
1979
+ * @example
1980
+ * // With auto-generated token
1981
+ * const { url } = await sandbox.exposePort(8080, { hostname: 'example.com' });
1982
+ * // url: https://8080-sandbox-id-abc123random4567.example.com
1983
+ *
1984
+ * @example
1985
+ * // With custom token for stable URLs across deployments
1986
+ * const { url } = await sandbox.exposePort(8080, {
1987
+ * hostname: 'example.com',
1988
+ * token: 'my-token-v1'
1989
+ * });
1990
+ * // url: https://8080-sandbox-id-my-token-v1.example.com
1991
+ */
1964
1992
  exposePort(port: number, options: {
1965
1993
  name?: string;
1966
1994
  hostname: string;
1995
+ token?: string;
1967
1996
  }): Promise<{
1968
1997
  url: string;
1969
1998
  port: number;
@@ -1977,6 +2006,7 @@ declare class Sandbox<Env = unknown> extends Container<Env> implements ISandbox
1977
2006
  }[]>;
1978
2007
  isPortExposed(port: number): Promise<boolean>;
1979
2008
  validatePortToken(port: number, token: string): Promise<boolean>;
2009
+ private validateCustomToken;
1980
2010
  private generatePortToken;
1981
2011
  private constructPreviewUrl;
1982
2012
  /**
@@ -2006,10 +2036,6 @@ declare class Sandbox<Env = unknown> extends Container<Env> implements ISandbox
2006
2036
  * @throws Error if attempting to delete the default session
2007
2037
  */
2008
2038
  deleteSession(sessionId: string): Promise<SessionDeleteResult>;
2009
- /**
2010
- * Internal helper to create ExecutionSession wrapper for a given sessionId
2011
- * Used by both createSession and getSession
2012
- */
2013
2039
  private getSessionWrapper;
2014
2040
  createCodeContext(options?: CreateContextOptions): Promise<CodeContext>;
2015
2041
  runCode(code: string, options?: RunCodeOptions): Promise<ExecutionResult>;
@@ -2018,5 +2044,5 @@ declare class Sandbox<Env = unknown> extends Container<Env> implements ISandbox
2018
2044
  deleteCodeContext(contextId: string): Promise<void>;
2019
2045
  }
2020
2046
  //#endregion
2021
- export { ProcessInfoResult as $, RequestConfig as A, FileChunk as B, WriteFileRequest as C, ContainerStub as D, BaseApiResponse as E, BucketProvider as F, ListFilesOptions as G, FileStreamEvent as H, ExecEvent as I, PortCloseResult as J, LogEvent as K, ExecOptions as L, SessionRequest as M, BaseExecOptions as N, ErrorResponse as O, BucketCredentials as P, ProcessCleanupResult as Q, ExecResult as R, ReadFileRequest as S, ExecuteResponse as T, GitCheckoutResult as U, FileMetadata as V, ISandbox as W, PortListResult as X, PortExposeResult as Y, Process as Z, GitCheckoutRequest as _, ExecutionResult as _t, CreateSessionRequest as a, ProcessStatus as at, FileOperationRequest as b, DeleteSessionResponse as c, StreamOptions as ct, ProcessClient as d, isExecResult as dt, ProcessKillResult as et, ExposePortRequest as f, isProcess as ft, InterpreterClient as g, Execution as gt, ExecutionCallbacks as h, CreateContextOptions as ht, CommandsResponse as i, ProcessStartResult as it, ResponseHandler as j, HttpClientOptions as k, PingResponse as l, WaitForLogResult as lt, UnexposePortRequest as m, CodeContext as mt, getSandbox as n, ProcessLogsResult as nt, CreateSessionResponse as o, SandboxOptions as ot, PortClient as p, isProcessStatus as pt, MountBucketOptions as q, SandboxClient as r, ProcessOptions as rt, DeleteSessionRequest as s, SessionOptions as st, Sandbox as t, ProcessListResult as tt, UtilityClient as u, WaitForPortOptions as ut, GitClient as v, RunCodeOptions as vt, CommandClient as w, MkdirRequest as x, FileClient as y, ExecutionSession as z };
2022
- //# sourceMappingURL=sandbox-HCG7Oeg0.d.ts.map
2047
+ export { ProcessKillResult as $, ResponseHandler as A, FileMetadata as B, CommandClient as C, ErrorResponse as D, ContainerStub as E, ExecEvent as F, LogEvent as G, GitCheckoutResult as H, ExecOptions as I, PortExposeResult as J, MountBucketOptions as K, ExecResult as L, BaseExecOptions as M, BucketCredentials as N, HttpClientOptions as O, BucketProvider as P, ProcessInfoResult as Q, ExecutionSession as R, WriteFileRequest as S, BaseApiResponse as T, ISandbox as U, FileStreamEvent as V, ListFilesOptions as W, Process as X, PortListResult as Y, ProcessCleanupResult as Z, GitClient as _, ExecutionResult as _t, CreateSessionRequest as a, SandboxOptions as at, MkdirRequest as b, DeleteSessionResponse as c, WaitForLogResult as ct, ProcessClient as d, isProcess as dt, ProcessListResult as et, PortClient as f, isProcessStatus as ft, GitCheckoutRequest as g, Execution as gt, InterpreterClient as h, CreateContextOptions as ht, CommandsResponse as i, ProcessStatus as it, SessionRequest as j, RequestConfig as k, PingResponse as l, WaitForPortOptions as lt, ExecutionCallbacks as m, CodeContext as mt, getSandbox as n, ProcessOptions as nt, CreateSessionResponse as o, SessionOptions as ot, UnexposePortRequest as p, PtyOptions as pt, PortCloseResult as q, SandboxClient as r, ProcessStartResult as rt, DeleteSessionRequest as s, StreamOptions as st, Sandbox as t, ProcessLogsResult as tt, UtilityClient as u, isExecResult as ut, FileClient as v, RunCodeOptions as vt, ExecuteResponse as w, ReadFileRequest as x, FileOperationRequest as y, FileChunk as z };
2048
+ //# sourceMappingURL=sandbox-CgjQQZGw.d.ts.map