@cloudflare/sandbox 0.13.0-next.651.1 → 0.13.0-next.709.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.
Files changed (67) hide show
  1. package/Dockerfile +12 -17
  2. package/README.md +48 -2
  3. package/dist/bridge/index.d.ts.map +1 -1
  4. package/dist/bridge/index.js +1365 -1054
  5. package/dist/bridge/index.js.map +1 -1
  6. package/dist/{contexts-BS0Bs6IU.d.ts → contexts-1EsLHByO.d.ts} +240 -15
  7. package/dist/contexts-1EsLHByO.d.ts.map +1 -0
  8. package/dist/{dist-DF8sudAg.js → dist-Duor5GbS.js} +38 -147
  9. package/dist/dist-Duor5GbS.js.map +1 -0
  10. package/dist/errors/index.d.ts +4 -0
  11. package/dist/errors/index.js +4 -0
  12. package/dist/{errors-BG6NZiPD.js → errors-CXR0xBpw.js} +82 -13
  13. package/dist/errors-CXR0xBpw.js.map +1 -0
  14. package/dist/errors-QYlSkVGz.js +893 -0
  15. package/dist/errors-QYlSkVGz.js.map +1 -0
  16. package/dist/extensions/index.d.ts +4 -74
  17. package/dist/extensions/index.js +5 -152
  18. package/dist/extensions-CFB2xHqY.js +1023 -0
  19. package/dist/extensions-CFB2xHqY.js.map +1 -0
  20. package/dist/filesystem-BWAZCZER.d.ts +732 -0
  21. package/dist/filesystem-BWAZCZER.d.ts.map +1 -0
  22. package/dist/git/index.d.ts +63 -0
  23. package/dist/git/index.d.ts.map +1 -0
  24. package/dist/git/index.js +338 -0
  25. package/dist/git/index.js.map +1 -0
  26. package/dist/index-Bs4bqXDR.d.ts +438 -0
  27. package/dist/index-Bs4bqXDR.d.ts.map +1 -0
  28. package/dist/index-HNYBk-az.d.ts +444 -0
  29. package/dist/index-HNYBk-az.d.ts.map +1 -0
  30. package/dist/index.d.ts +487 -181
  31. package/dist/index.d.ts.map +1 -1
  32. package/dist/index.js +12 -43
  33. package/dist/index.js.map +1 -1
  34. package/dist/interpreter/index.d.ts +311 -0
  35. package/dist/interpreter/index.d.ts.map +1 -0
  36. package/dist/interpreter/index.js +292 -0
  37. package/dist/interpreter/index.js.map +1 -0
  38. package/dist/openai/index.d.ts +5 -4
  39. package/dist/openai/index.d.ts.map +1 -1
  40. package/dist/openai/index.js +11 -6
  41. package/dist/openai/index.js.map +1 -1
  42. package/dist/opencode/index.d.ts +133 -161
  43. package/dist/opencode/index.d.ts.map +1 -1
  44. package/dist/opencode/index.js +284 -203
  45. package/dist/opencode/index.js.map +1 -1
  46. package/dist/process-types-GStiZ8f8.d.ts +73 -0
  47. package/dist/process-types-GStiZ8f8.d.ts.map +1 -0
  48. package/dist/sandbox-Auuwfnur.js +10010 -0
  49. package/dist/sandbox-Auuwfnur.js.map +1 -0
  50. package/dist/sandbox-BbAabq93.d.ts +42 -0
  51. package/dist/sandbox-BbAabq93.d.ts.map +1 -0
  52. package/dist/xterm/index.d.ts +11 -7
  53. package/dist/xterm/index.d.ts.map +1 -1
  54. package/dist/xterm/index.js +61 -18
  55. package/dist/xterm/index.js.map +1 -1
  56. package/package.json +28 -4
  57. package/dist/contexts-BS0Bs6IU.d.ts.map +0 -1
  58. package/dist/dist-DF8sudAg.js.map +0 -1
  59. package/dist/errors-BG6NZiPD.js.map +0 -1
  60. package/dist/extensions/index.d.ts.map +0 -1
  61. package/dist/extensions/index.js.map +0 -1
  62. package/dist/rpc-types-PBUY-xXM.d.ts +0 -1679
  63. package/dist/rpc-types-PBUY-xXM.d.ts.map +0 -1
  64. package/dist/sandbox-BgwMBQ7S.js +0 -8273
  65. package/dist/sandbox-BgwMBQ7S.js.map +0 -1
  66. package/dist/sandbox-D_MMqExx.d.ts +0 -1077
  67. package/dist/sandbox-D_MMqExx.d.ts.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["createOpencodeClient: OpencodeClientFactory | undefined","env: Record<string, string>"],"sources":["../../src/opencode/types.ts","../../src/opencode/opencode.ts"],"sourcesContent":["import type { Config } from '@opencode-ai/sdk/v2';\nimport type { OpencodeClient } from '@opencode-ai/sdk/v2/client';\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 /** Additional environment variables to pass to the OpenCode process */\n env?: Record<string, string>;\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 = OpencodeClient> {\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/v2';\nimport type { OpencodeClient } from '@opencode-ai/sdk/v2/client';\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_STARTUP_TIMEOUT_MS = 180_000;\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\ntype OpencodeClientFactory = (options: {\n baseUrl: string;\n fetch: typeof fetch;\n directory?: string;\n}) => OpencodeClient;\n\n// Dynamic import to handle peer dependency\nlet createOpencodeClient: OpencodeClientFactory | undefined;\n\nasync function ensureSdkLoaded(): Promise<void> {\n if (createOpencodeClient) return;\n\n try {\n const sdk = await import('@opencode-ai/sdk/v2/client');\n createOpencodeClient = sdk.createOpencodeClient as OpencodeClientFactory;\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 customEnv?: Record<string, string>\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: '/path',\n status: 200,\n timeout: OPENCODE_STARTUP_TIMEOUT_MS\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(\n sandbox,\n port,\n directory,\n config,\n customEnv\n );\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: '/path',\n status: 200,\n timeout: OPENCODE_STARTUP_TIMEOUT_MS\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 customEnv?: Record<string, string>\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 === 'cloudflare-ai-gateway') {\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['cloudflare-ai-gateway'];\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 // Custom env vars override config-extracted ones\n if (customEnv) {\n Object.assign(env, customEnv);\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 - check the actual health endpoint\n try {\n await process.waitForPort(port, {\n mode: 'http',\n path: '/path',\n status: 200,\n timeout: OPENCODE_STARTUP_TIMEOUT_MS\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 * // Or use Cloudflare AI Gateway (with unified billing, no provider keys needed).\n * // 'cloudflare-ai-gateway': {\n * // options: {\n * // accountId: env.CF_ACCOUNT_ID,\n * // gatewayId: env.CF_GATEWAY_ID,\n * // apiToken: env.CF_API_TOKEN\n * // },\n * // models: { 'anthropic/claude-sonnet-4-5-20250929': {} }\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 options?.env\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 * // Or use Cloudflare AI Gateway (with unified billing, no provider keys needed).\n * // 'cloudflare-ai-gateway': {\n * // options: {\n * // accountId: env.CF_ACCOUNT_ID,\n * // gatewayId: env.CF_GATEWAY_ID,\n * // apiToken: env.CF_API_TOKEN\n * // },\n * // models: { 'anthropic/claude-sonnet-4-5-20250929': {} }\n * // }\n * }\n * },\n * // Optional: Pass additional environment variables (e.g., for OTEL telemetry)\n * env: {\n * OTEL_EXPORTER_OTLP_ENDPOINT: 'http://127.0.0.1:4318',\n * TRACEPARENT: '00-abc123-def456-01'\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 = OpencodeClient>(\n sandbox: Sandbox<unknown>,\n options?: OpencodeOptions\n): Promise<OpencodeResult<TClient>> {\n await ensureSdkLoaded();\n\n const server = await createOpencodeServer(sandbox, options);\n\n const clientFactory = createOpencodeClient;\n if (!clientFactory) {\n throw new Error('OpenCode SDK client unavailable.');\n }\n\n const client = clientFactory({\n baseUrl: server.url,\n fetch: (input, init?) =>\n sandbox.containerFetch(new Request(input, init), server.port)\n });\n\n return { client: client as TClient, server };\n}\n\n/**\n * Proxy a request directly to the OpenCode server.\n *\n * Unlike `proxyToOpencode()`, this helper does not apply any web UI redirects\n * or query parameter rewrites. Use it for API/CLI traffic where raw request\n * forwarding is preferred.\n */\nexport function proxyToOpencodeServer(\n request: Request,\n sandbox: Sandbox<unknown>,\n server: OpencodeServer\n): Promise<Response> {\n return sandbox.containerFetch(request, server.port);\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 * 'cloudflare-ai-gateway': {\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 proxyToOpencodeServer(request, sandbox, server);\n}\n"],"mappings":";;;;;;;AA4CA,IAAa,uBAAb,cAA0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AsB,eACpB,SACA,SACkC;AAClC,OAAM,iBAAiB;CAEvB,MAAM,SAAS,MAAM,qBAAqB,SAAS,QAAQ;CAE3D,MAAM,gBAAgB;AACtB,KAAI,CAAC,cACH,OAAM,IAAI,MAAM,mCAAmC;AASrD,QAAO;EAAE,QANM,cAAc;GAC3B,SAAS,OAAO;GAChB,QAAQ,OAAO,SACb,QAAQ,eAAe,IAAI,QAAQ,OAAO,KAAK,EAAE,OAAO,KAAK;GAChE,CAAC;EAEkC;EAAQ;;;;;;;;;AAU9C,SAAgB,sBACd,SACA,SACA,QACmB;AACnB,QAAO,QAAQ,eAAe,SAAS,OAAO,KAAK;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkDrD,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,sBAAsB,SAAS,SAAS,OAAO"}
1
+ {"version":3,"file":"index.js","names":["createSDKClient: OpenCodeClientFactory | undefined","DEFAULT_PORT","env: Record<string, string>","#sandbox","#defaults","#storage","#stateKey","#lastOptions","#loadPersisted","#persist","server: OpenCodeServer","#server"],"sources":["../../../../extensions/opencode/src/client.ts","../../../../extensions/opencode/src/types.ts","../../../../extensions/opencode/src/opencode.ts","../../../../extensions/opencode/src/lifecycle.ts","../../../../extensions/opencode/src/proxy.ts"],"sourcesContent":["import type { OpencodeClient } from '@opencode-ai/sdk/v2/client';\nimport type { OpenCodeHandle } from './lifecycle';\nimport type { OpenCodeOptions } from './types';\n\ntype OpenCodeClientFactory = (options: {\n baseUrl: string;\n fetch: typeof fetch;\n directory?: string;\n}) => OpencodeClient;\n\nlet createSDKClient: OpenCodeClientFactory | undefined;\n\nasync function loadSDK(): Promise<OpenCodeClientFactory> {\n if (createSDKClient) return createSDKClient;\n try {\n const sdk = await import('@opencode-ai/sdk/v2/client');\n createSDKClient = sdk.createOpencodeClient as OpenCodeClientFactory;\n return createSDKClient;\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 * Build a typed OpenCode SDK client from a lifecycle handle.\n *\n * Works against either the Worker stub (`sandbox.opencode`) or the in-DO object\n * (`this.opencode`): it ensures the server through the handle, reads the stored\n * config, and routes every request through `handle.fetch`. Because the handle\n * owns `containerFetch`, this helper never touches sandbox transport directly.\n *\n * The SDK is imported lazily so the peer dependency is only required when an\n * OpenCode client is actually built.\n */\nexport async function createOpenCodeClient<TClient = OpencodeClient>(\n handle: OpenCodeHandle,\n options?: OpenCodeOptions\n): Promise<TClient> {\n const server = await handle.start(options);\n const config = await handle.config();\n const directory = options?.directory ?? config.directory;\n\n const factory = await loadSDK();\n const client = factory({\n baseUrl: server.url,\n fetch: (input, init) => handle.fetch(new Request(input, init)),\n directory\n });\n\n return client as TClient;\n}\n","import type { Config } from '@opencode-ai/sdk/v2';\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 /** Additional environment variables to pass to the OpenCode process */\n env?: Record<string, string>;\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 * 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 {\n createExtensionProcessSandbox,\n type SandboxLike\n} from '@cloudflare/sandbox/extensions';\nimport type { Config } from '@opencode-ai/sdk/v2';\nimport {\n createLogger,\n type Logger,\n type SandboxCommand,\n type SandboxProcess\n} from '@repo/shared';\nimport type { OpenCodeOptions, 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\nexport interface OpenCodeSandboxLike extends SandboxLike {\n exec: NonNullable<SandboxLike['exec']>;\n getProcess: NonNullable<SandboxLike['getProcess']>;\n listProcesses: NonNullable<SandboxLike['listProcesses']>;\n containerFetch(request: Request, port: number): Promise<Response>;\n}\n\nconst DEFAULT_PORT = 4096;\nconst OPENCODE_STARTUP_TIMEOUT_MS = 180_000;\nfunction openCodeCommand(port: number): SandboxCommand {\n return ['opencode', 'serve', '--port', String(port), '--hostname', '0.0.0.0'];\n}\n\nfunction commandsEqual(a: SandboxCommand, b: SandboxCommand): boolean {\n return a.length === b.length && a.every((value, index) => value === b[index]);\n}\n\n/** Recover a running OpenCode process from runtime-local process status. */\nexport async function findExistingOpenCodeProcess(\n sandbox: OpenCodeSandboxLike,\n port: number,\n directory?: string\n): Promise<SandboxProcess | null> {\n const command = openCodeCommand(port);\n const processes = createExtensionProcessSandbox(sandbox);\n const status = (await processes.listProcesses()).find(\n (candidate) =>\n candidate.state === 'running' &&\n candidate.cwd === directory &&\n commandsEqual(candidate.command, command)\n );\n return status ? processes.getProcess(status.id) : null;\n}\n\nasync function collectStderr(process: SandboxProcess): Promise<string> {\n const stream = await process.logs({ replay: true, follow: false });\n const reader = stream.getReader();\n const decoder = new TextDecoder();\n let stderr = '';\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n if (value.type === 'stderr') {\n stderr += decoder.decode(value.data, { stream: true });\n }\n }\n return stderr + decoder.decode();\n } finally {\n reader.releaseLock();\n }\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: OpenCodeSandboxLike,\n port: number,\n directory?: string,\n config?: Config,\n customEnv?: Record<string, string>\n): Promise<SandboxProcess> {\n const existingProcess = await findExistingOpenCodeProcess(\n sandbox,\n port,\n directory\n );\n if (existingProcess) {\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(\n sandbox,\n port,\n directory,\n config,\n customEnv\n );\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(\n sandbox,\n port,\n directory\n );\n if (retryProcess) {\n getLogger().debug(\n 'Startup failed but found concurrent process, reusing',\n { port, processId: retryProcess.id }\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: OpenCodeSandboxLike,\n port: number,\n directory?: string,\n config?: Config,\n customEnv?: Record<string, string>\n): Promise<SandboxProcess> {\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 === 'cloudflare-ai-gateway') {\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['cloudflare-ai-gateway'];\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 // Custom env vars override config-extracted ones\n if (customEnv) {\n Object.assign(env, customEnv);\n }\n\n const command = openCodeCommand(port);\n const process = await createExtensionProcessSandbox(sandbox).exec(command, {\n cwd: directory,\n env: Object.keys(env).length > 0 ? env : undefined\n });\n\n // Wait for server to be ready - check the actual health endpoint\n try {\n await process.waitForPort(port, {\n mode: 'http',\n path: '/path',\n status: 200,\n timeout: OPENCODE_STARTUP_TIMEOUT_MS\n });\n getLogger().info('OpenCode server started successfully', {\n port,\n processId: process.id\n });\n } catch (e) {\n const stderr = await collectStderr(process);\n const error = e instanceof Error ? e : undefined;\n getLogger().error('OpenCode server failed to start', error, {\n port,\n stderr\n });\n throw new OpenCodeStartupError(\n `OpenCode server failed to start. Stderr: ${stderr || '(empty)'}`,\n { port, stderr, command: command.join(' ') },\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 `createOpenCodeClient()` 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 * // Or use Cloudflare AI Gateway (with unified billing, no provider keys needed).\n * // 'cloudflare-ai-gateway': {\n * // options: {\n * // accountId: env.CF_ACCOUNT_ID,\n * // gatewayId: env.CF_GATEWAY_ID,\n * // apiToken: env.CF_API_TOKEN\n * // },\n * // models: { 'anthropic/claude-sonnet-4-5-20250929': {} }\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: OpenCodeSandboxLike,\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 options?.env\n );\n\n return {\n port,\n url: `http://localhost:${port}`,\n close: async () => {\n await process.kill(15);\n await process.waitForExit().catch(() => {\n /* exit observed */\n });\n }\n };\n}\n\n/**\n * Proxy a request directly to the OpenCode server.\n *\n * Unlike `proxyToOpenCode()`, this helper does not apply any web UI redirects\n * or query parameter rewrites. Use it for API/CLI traffic where raw request\n * forwarding is preferred.\n */\nexport function proxyToOpenCodeServer(\n request: Request,\n sandbox: OpenCodeSandboxLike,\n server: OpenCodeServer\n): Promise<Response> {\n return sandbox.containerFetch(request, server.port);\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 * 'cloudflare-ai-gateway': {\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: OpenCodeSandboxLike,\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 proxyToOpenCodeServer(request, sandbox, server);\n}\n","import {\n SandboxExtension,\n type SandboxLike\n} from '@cloudflare/sandbox/extensions';\nimport {\n createOpenCodeServer,\n findExistingOpenCodeProcess,\n type OpenCodeSandboxLike\n} from './opencode';\nimport type { OpenCodeOptions, OpenCodeServer } from './types';\n\nconst DEFAULT_PORT = 4096;\n\n/** Resolved server metadata that is safe to return across the RPC boundary. */\nexport interface OpenCodeServerInfo {\n port: number;\n url: string;\n}\n\n/** Snapshot of the resolved lifecycle configuration. */\nexport interface OpenCodeConfig {\n port: number;\n directory?: string;\n}\n\n/** Current server status as observed in the container. */\nexport interface OpenCodeStatus extends OpenCodeServerInfo {\n running: boolean;\n}\n\n/**\n * The slice of `DurableObjectStorage` the handle uses to persist desired-state.\n * Pass `this.ctx.storage` so the server config survives a Durable Object\n * eviction (cold start) and is recovered lazily on the next `start()`.\n */\nexport interface OpenCodeStateStorage {\n get<T>(key: string): Promise<T | undefined>;\n put<T>(key: string, value: T): Promise<void>;\n}\n\n/** Options for {@link withOpenCode}: server defaults plus optional storage. */\nexport interface WithOpenCodeOptions extends OpenCodeOptions {\n /** Persist desired-state here so it survives DO eviction. */\n storage?: OpenCodeStateStorage;\n}\n\nconst STATE_KEY_PREFIX = 'opencode:desired-state:';\n\n/** Recognise the retryable container-unavailable error across RPC. */\nfunction isContainerUnavailable(error: unknown): boolean {\n if (typeof error !== 'object' || error === null) return false;\n return (error as { name?: unknown }).name === 'ContainerUnavailableError';\n}\n\n/**\n * DO-resident lifecycle handle for an OpenCode server. Owns the durable\n * `opencode serve` process: start/reuse, stop, status, and request proxying.\n *\n * It extends {@link SandboxExtension}, so the DO stub exposes it as\n * `sandbox.opencode` and method calls dispatch through `callExtension` — the\n * same path the interpreter extension uses. `createOpenCodeClient` consumes the\n * same handle from either the Worker stub or the in-DO object.\n *\n * The server starts lazily: nothing runs until `start()` (or `fetch()`, which\n * calls it) is invoked. To start optimistically, call `opencode.start()` from\n * your Sandbox subclass's `onStart`.\n */\nexport class OpenCodeHandle extends SandboxExtension {\n readonly #sandbox: OpenCodeSandboxLike;\n readonly #defaults: OpenCodeOptions;\n readonly #storage: OpenCodeStateStorage | undefined;\n readonly #stateKey: string;\n #server: OpenCodeServer | undefined;\n #lastOptions: OpenCodeOptions | undefined;\n\n constructor(\n sandbox: OpenCodeSandboxLike,\n defaults: OpenCodeOptions = {},\n storage?: OpenCodeStateStorage,\n stateIndex = 0\n ) {\n super(sandbox as SandboxLike);\n this.#sandbox = sandbox;\n this.#defaults = defaults;\n this.#storage = storage;\n this.#stateKey = `${STATE_KEY_PREFIX}${stateIndex}`;\n }\n\n /**\n * Start or reuse the OpenCode server, returning RPC-safe metadata. With no\n * options it reuses the last-used config, recovering persisted desired-state\n * after a cold start. Retries once on a transient `CONTAINER_UNAVAILABLE`\n * (e.g. a rollout in flight).\n */\n async start(options?: OpenCodeOptions): Promise<OpenCodeServerInfo> {\n const recovered =\n options ?? this.#lastOptions ?? (await this.#loadPersisted());\n const resolved = { ...this.#defaults, ...recovered };\n this.#lastOptions = resolved;\n await this.#persist(resolved);\n\n let server: OpenCodeServer;\n try {\n server = await createOpenCodeServer(this.#sandbox, resolved);\n } catch (error) {\n if (!isContainerUnavailable(error)) throw error;\n server = await createOpenCodeServer(this.#sandbox, resolved);\n }\n\n this.#server = server;\n return { port: server.port, url: server.url };\n }\n\n /** Stop the running server, if one was started through this handle. */\n async stop(): Promise<void> {\n if (!this.#server) return;\n await this.#server.close();\n this.#server = undefined;\n }\n\n /** Report whether the named OpenCode server is currently running. */\n async status(): Promise<OpenCodeStatus> {\n const resolved = { ...this.#defaults, ...this.#lastOptions };\n const port = resolved.port ?? DEFAULT_PORT;\n const process = await findExistingOpenCodeProcess(\n this.#sandbox,\n port,\n resolved.directory\n );\n return {\n running: process !== null,\n port,\n url: `http://localhost:${port}`\n };\n }\n\n /** Snapshot of the resolved configuration the client builder reads. */\n async config(): Promise<OpenCodeConfig> {\n const resolved = { ...this.#defaults, ...this.#lastOptions };\n return {\n port: resolved.port ?? DEFAULT_PORT,\n directory: resolved.directory\n };\n }\n\n /**\n * Start the server then route a request into the container. This is the\n * transport the SDK client's `fetch` adapter and the Worker proxy use, so it\n * works identically from the Worker stub (one RPC hop) or in-DO (local).\n */\n async fetch(request: Request): Promise<Response> {\n const server = await this.start();\n return this.#sandbox.containerFetch(request, server.port);\n }\n\n /**\n * Persist resolved desired-state so a cold DO can recover it. Best-effort.\n *\n * Secret-bearing fields (`config`, `env`) are never written to storage. They\n * are sourced fresh from the handle's defaults — which the Sandbox rebuilds\n * from the environment on every construction — so a cold start always uses\n * current credentials rather than a durable copy.\n */\n async #persist(options: OpenCodeOptions): Promise<void> {\n if (!this.#storage) return;\n const { config: _config, env: _env, ...safe } = options;\n await this.#storage.put(this.#stateKey, safe);\n }\n\n /** Read persisted desired-state, if any, after a DO eviction. */\n async #loadPersisted(): Promise<OpenCodeOptions | undefined> {\n if (!this.#storage) return undefined;\n return this.#storage.get<OpenCodeOptions>(this.#stateKey);\n }\n}\n\n/**\n * Assigns each handle a stable per-sandbox index so its persisted state key is\n * deterministic across DO reconstruction (field initializers run in the same\n * order each time). Keyed weakly so it is collected with the sandbox.\n */\nconst stateIndexCounter = new WeakMap<OpenCodeSandboxLike, number>();\n\n/**\n * Factory — attach as a field on a Sandbox subclass:\n * `opencode = withOpenCode(this, { directory, config, storage: this.ctx.storage })`.\n *\n * Pass `storage` to persist desired-state so the server is recovered after a DO\n * eviction (cold start). The server starts lazily on first use.\n */\nexport function withOpenCode(\n sandbox: OpenCodeSandboxLike,\n options: WithOpenCodeOptions = {}\n): OpenCodeHandle {\n const { storage, ...defaults } = options;\n const index = stateIndexCounter.get(sandbox) ?? 0;\n stateIndexCounter.set(sandbox, index + 1);\n return new OpenCodeHandle(sandbox, defaults, storage, index);\n}\n","import type { OpenCodeHandle } from './lifecycle';\n\n/** Configuration for {@link createOpenCodeProxy}. */\nexport interface OpenCodeProxyOptions {\n /** Origin the OpenCode web UI should call back through. Defaults to the request origin. */\n callbackOrigin?: string;\n}\n\n/**\n * Proxy a request to the OpenCode web UI through a lifecycle handle.\n *\n * For an initial HTML page load that still lacks the `?url=` parameter, returns\n * a redirect that adds it (so the OpenCode frontend calls back through the\n * proxy instead of `127.0.0.1:4096`). Every other request is routed through\n * `handle.fetch`, which ensures the server is running before forwarding into the\n * container.\n */\nexport function proxyToOpenCodeUI(\n request: Request,\n handle: OpenCodeHandle,\n options?: OpenCodeProxyOptions\n): Response | Promise<Response> {\n const url = new URL(request.url);\n\n // OpenCode's frontend defaults its API base to 127.0.0.1:4096; the ?url=\n // parameter overrides that. Only redirect initial HTML GET loads — redirecting\n // a POST would drop the 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', options?.callbackOrigin ?? url.origin);\n return Response.redirect(url.toString(), 302);\n }\n }\n\n // Ensure-then-forward: the handle starts the server on demand before proxying.\n return handle.fetch(request);\n}\n\n/**\n * Curried Worker fetch wrapper for OpenCode.\n *\n * `createOpenCodeProxy(resolve, options?)` captures a lazy per-request resolver\n * for the OpenCode lifecycle handle (`sandbox.opencode`) and returns a function\n * that wraps the user's worker entrypoint.\n *\n * The wrapped handler runs first. If it returns a 404 (or has no `fetch`), the\n * request falls through to the OpenCode web-UI proxy — the redirect handshake\n * for HTML loads and an ensure-then-forward into the container for everything\n * else. A 404 from the user handler is the \"not mine, proxy it\" signal, so the\n * handler only needs to own its own routes and `return new Response('Not\n * found', { status: 404 })` for the rest.\n *\n * ```ts\n * export default createOpenCodeProxy(\n * (env) => getSandbox(env.Sandbox, 'my-sandbox').opencode\n * )({\n * async fetch(request, env) {\n * // handle your own routes, else:\n * return new Response('Not found', { status: 404 });\n * }\n * });\n * ```\n */\nexport function createOpenCodeProxy<Env>(\n resolve: (env: Env) => OpenCodeHandle,\n options?: OpenCodeProxyOptions\n): (handler: ExportedHandler<Env>) => ExportedHandler<Env> {\n return (handler) => ({\n ...handler,\n async fetch(request, env, ctx) {\n if (handler.fetch) {\n const response = await handler.fetch(request, env, ctx);\n if (response.status !== 404) return response;\n }\n return proxyToOpenCodeUI(request, resolve(env), options);\n }\n });\n}\n"],"mappings":";;;;;;AAUA,IAAIA;AAEJ,eAAe,UAA0C;AACvD,KAAI,gBAAiB,QAAO;AAC5B,KAAI;AAEF,qBADY,MAAM,OAAO,+BACH;AACtB,SAAO;SACD;AACN,QAAM,IAAI,MACR,uGAED;;;;;;;;;;;;;;AAeL,eAAsB,qBACpB,QACA,SACkB;CAClB,MAAM,SAAS,MAAM,OAAO,MAAM,QAAQ;CAC1C,MAAM,SAAS,MAAM,OAAO,QAAQ;CACpC,MAAM,YAAY,SAAS,aAAa,OAAO;AAS/C,SAPgB,MAAM,SAAS,EACR;EACrB,SAAS,OAAO;EAChB,QAAQ,OAAO,SAAS,OAAO,MAAM,IAAI,QAAQ,OAAO,KAAK,CAAC;EAC9D;EACD,CAAC;;;;;;;;AClBJ,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;;;;;;AC5BnB,SAAS,YAAoB;AAC3B,QAAO,aAAa;EAAE,WAAW;EAAc,WAAW;EAAY,CAAC;;AAUzE,MAAMC,iBAAe;AACrB,MAAM,8BAA8B;AACpC,SAAS,gBAAgB,MAA8B;AACrD,QAAO;EAAC;EAAY;EAAS;EAAU,OAAO,KAAK;EAAE;EAAc;EAAU;;AAG/E,SAAS,cAAc,GAAmB,GAA4B;AACpE,QAAO,EAAE,WAAW,EAAE,UAAU,EAAE,OAAO,OAAO,UAAU,UAAU,EAAE,OAAO;;;AAI/E,eAAsB,4BACpB,SACA,MACA,WACgC;CAChC,MAAM,UAAU,gBAAgB,KAAK;CACrC,MAAM,YAAY,8BAA8B,QAAQ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,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,SAAS,kBAAkB,IAAI,OAAO;AAClE,UAAO,SAAS,SAAS,IAAI,UAAU,EAAE,IAAI;;;AAKjD,QAAO,OAAO,MAAM,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4B9B,SAAgB,oBACd,SACA,SACyD;AACzD,SAAQ,aAAa;EACnB,GAAG;EACH,MAAM,MAAM,SAAS,KAAK,KAAK;AAC7B,OAAI,QAAQ,OAAO;IACjB,MAAM,WAAW,MAAM,QAAQ,MAAM,SAAS,KAAK,IAAI;AACvD,QAAI,SAAS,WAAW,IAAK,QAAO;;AAEtC,UAAO,kBAAkB,SAAS,QAAQ,IAAI,EAAE,QAAQ;;EAE3D"}
@@ -0,0 +1,73 @@
1
+ //#region ../shared/dist/process-types.d.ts
2
+ type SandboxCommand = readonly [executable: string, ...args: string[]];
3
+ /**
4
+ * Terminal outcome observed for the root subprocess.
5
+ *
6
+ * The process resource remains running until its supervised process group has
7
+ * settled. Signals delivered only to descendants do not rewrite this outcome.
8
+ */
9
+ interface ProcessExit {
10
+ code: number;
11
+ signal?: number;
12
+ timedOut: boolean;
13
+ }
14
+ interface ProcessFailure {
15
+ code: string;
16
+ message: string;
17
+ }
18
+ interface ProcessStatusBase {
19
+ id: string;
20
+ pid: number;
21
+ command: SandboxCommand;
22
+ cwd?: string;
23
+ startedAt: string;
24
+ }
25
+ /** Lifecycle state for the complete supervised process group. */
26
+ type ProcessStatus = (ProcessStatusBase & {
27
+ state: 'running';
28
+ }) | (ProcessStatusBase & {
29
+ state: 'exited';
30
+ exit: ProcessExit;
31
+ endedAt: string;
32
+ }) | (ProcessStatusBase & {
33
+ state: 'error';
34
+ error: ProcessFailure;
35
+ endedAt: string;
36
+ });
37
+ type ProcessLogCursor = string;
38
+ type ProcessLogEvent = {
39
+ type: 'stdout' | 'stderr';
40
+ cursor: ProcessLogCursor;
41
+ timestamp: string;
42
+ data: Uint8Array;
43
+ } | {
44
+ type: 'terminal';
45
+ state: 'exited';
46
+ cursor: ProcessLogCursor;
47
+ timestamp: string;
48
+ exit: ProcessExit;
49
+ } | {
50
+ type: 'terminal';
51
+ state: 'error';
52
+ cursor: ProcessLogCursor;
53
+ timestamp: string;
54
+ error: ProcessFailure;
55
+ } | {
56
+ type: 'truncated';
57
+ cursor?: ProcessLogCursor;
58
+ timestamp: string;
59
+ };
60
+ interface WaitForLogResult {
61
+ stream: 'stdout' | 'stderr';
62
+ text: string;
63
+ match: string;
64
+ cursor?: ProcessLogCursor;
65
+ }
66
+ interface ProcessLogsRPCOptions {
67
+ since?: ProcessLogCursor;
68
+ replay?: boolean;
69
+ follow?: boolean;
70
+ }
71
+ //#endregion
72
+ export { ProcessLogsRPCOptions as a, WaitForLogResult as c, ProcessLogEvent as i, ProcessFailure as n, ProcessStatus as o, ProcessLogCursor as r, SandboxCommand as s, ProcessExit as t };
73
+ //# sourceMappingURL=process-types-GStiZ8f8.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"process-types-GStiZ8f8.d.ts","names":["SandboxCommand","ProcessExit","ProcessFailure","ProcessStatusBase","ProcessStatus","ProcessLogCursor","ProcessLogEvent","Uint8Array","WaitForLogResult","ProcessStartOptions","Record","ProcessLogsRPCOptions","ProcessLogSubscriptionAPI","ReadableStream","Promise","SandboxProcessesAPI"],"sources":["../../shared/dist/process-types.d.ts"],"sourcesContent":["export type SandboxCommand = readonly [executable: string, ...args: string[]];\n/**\n * Terminal outcome observed for the root subprocess.\n *\n * The process resource remains running until its supervised process group has\n * settled. Signals delivered only to descendants do not rewrite this outcome.\n */\nexport interface ProcessExit {\n code: number;\n signal?: number;\n timedOut: boolean;\n}\nexport interface ProcessFailure {\n code: string;\n message: string;\n}\ninterface ProcessStatusBase {\n id: string;\n pid: number;\n command: SandboxCommand;\n cwd?: string;\n startedAt: string;\n}\n/** Lifecycle state for the complete supervised process group. */\nexport type ProcessStatus = (ProcessStatusBase & {\n state: 'running';\n}) | (ProcessStatusBase & {\n state: 'exited';\n exit: ProcessExit;\n endedAt: string;\n}) | (ProcessStatusBase & {\n state: 'error';\n error: ProcessFailure;\n endedAt: string;\n});\nexport type ProcessLogCursor = string;\nexport type ProcessLogEvent = {\n type: 'stdout' | 'stderr';\n cursor: ProcessLogCursor;\n timestamp: string;\n data: Uint8Array;\n} | {\n type: 'terminal';\n state: 'exited';\n cursor: ProcessLogCursor;\n timestamp: string;\n exit: ProcessExit;\n} | {\n type: 'terminal';\n state: 'error';\n cursor: ProcessLogCursor;\n timestamp: string;\n error: ProcessFailure;\n} | {\n type: 'truncated';\n cursor?: ProcessLogCursor;\n timestamp: string;\n};\nexport interface WaitForLogResult {\n stream: 'stdout' | 'stderr';\n text: string;\n match: string;\n cursor?: ProcessLogCursor;\n}\nexport interface ProcessStartOptions {\n cwd?: string;\n env?: Record<string, string>;\n timeout?: number;\n}\nexport interface ProcessLogsRPCOptions {\n since?: ProcessLogCursor;\n replay?: boolean;\n follow?: boolean;\n}\nexport interface ProcessLogSubscriptionAPI {\n stream(): Promise<ReadableStream<ProcessLogEvent>>;\n cancel(): Promise<void>;\n [Symbol.dispose](): void;\n}\nexport interface SandboxProcessesAPI {\n start(command: SandboxCommand, options?: ProcessStartOptions): Promise<ProcessStatus>;\n get(id: string): Promise<ProcessStatus | null>;\n list(): Promise<ProcessStatus[]>;\n openLogs(id: string, options?: ProcessLogsRPCOptions): Promise<ProcessLogSubscriptionAPI>;\n kill(id: string, signal?: number): Promise<void>;\n hasActive(): Promise<boolean>;\n}\nexport {};\n//# sourceMappingURL=process-types.d.ts.map"],"mappings":";KAAYA,cAAAA;AAAZ;AAOA;AAKA;AAGC;AASD;;AAEMG,UAnBWF,WAAAA,CAmBXE;EAEIF,IAAAA,EAAAA,MAAAA;EAEJE,MAAAA,CAAAA,EAAAA,MAAAA;EAEKD,QAAAA,EAAAA,OAAAA;;AAGCG,UAvBKH,cAAAA,CAuBW;EAChBI,IAAAA,EAAAA,MAAAA;EAEAD,OAAAA,EAAAA,MAAAA;;UAtBFF,iBAAAA,CA4BEE;EAEFJ,EAAAA,EAAAA,MAAAA;EAIEI,GAAAA,EAAAA,MAAAA;EAEDH,OAAAA,EAjCEF,cAiCFE;EAGEG,GAAAA,CAAAA,EAAAA,MAAAA;EAAgB,SAAA,EAAA,MAAA;AAG7B;AAWA;KA7CYD,aAAAA,IAAiBD;;MAEvBA;;QAEIF;;MAEJE;;SAEKD;;;KAGCG,gBAAAA;KACAC,eAAAA;;UAEAD;;QAEFE;;;;UAIEF;;QAEFJ;;;;UAIEI;;SAEDH;;;WAGEG;;;UAGIG,gBAAAA;;;;WAIJH;;UAOIM,qBAAAA;UACLN"}