@cloudflare/sandbox 0.12.10 → 0.12.12

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 +1 @@
1
- {"version":3,"file":"index.js","names":["sandbox: Sandbox","output: ShellResult['output']","exitCode: number | null","outcome: ShellOutputResult['outcome']","error: unknown","root: string","result: FileOperationResult","original: string","stack: string[]"],"sources":["../../src/openai/index.ts"],"sourcesContent":["/**\n * OpenAI Agents adapters for executing shell commands and file operations\n * inside a Cloudflare Sandbox.\n */\nimport {\n type ApplyPatchOperation,\n type ApplyPatchResult,\n applyDiff,\n type Editor as OpenAIEeditor,\n type Shell as OpenAIShell,\n type ShellAction,\n type ShellOutputResult,\n type ShellResult\n} from '@openai/agents';\n\n// Command result for API responses\nexport interface CommandResult {\n command: string;\n stdout: string;\n stderr: string;\n exitCode: number | null;\n timestamp: number;\n}\n\n// File operation result for API responses\nexport interface FileOperationResult {\n operation: 'create' | 'update' | 'delete';\n path: string;\n status: 'completed' | 'failed';\n output: string;\n error?: string;\n timestamp: number;\n}\n\nimport { createLogger, type Logger } from '@repo/shared';\nimport type { Sandbox } from '../sandbox';\n\n// Helper functions for error handling\nfunction isErrorWithProperties(error: unknown): error is {\n message?: string;\n exitCode?: number;\n stdout?: string;\n stderr?: string;\n status?: number;\n stack?: string;\n} {\n return typeof error === 'object' && error !== null;\n}\n\nfunction getErrorMessage(error: unknown): string {\n if (isErrorWithProperties(error) && typeof error.message === 'string') {\n return error.message;\n }\n return String(error);\n}\n\n/**\n * Convert unknown values to Error instances when possible so downstream\n * loggers can include stack traces without losing type safety.\n */\nfunction toError(error: unknown): Error | undefined {\n return error instanceof Error ? error : undefined;\n}\n\n/**\n * Shell implementation that adapts Cloudflare Sandbox exec calls to the\n * OpenAI Agents `Shell` contract, including structured result collection.\n */\nexport class Shell implements OpenAIShell {\n private cwd: string = '/workspace';\n public results: CommandResult[] = [];\n private readonly logger: Logger;\n\n constructor(private readonly sandbox: Sandbox) {\n this.logger = createLogger({\n component: 'sandbox-do',\n operation: 'openai-shell'\n });\n }\n\n async run(action: ShellAction): Promise<ShellResult> {\n this.logger.debug('SandboxShell.run called', {\n commands: action.commands,\n timeout: action.timeoutMs\n });\n const output: ShellResult['output'] = [];\n\n for (const command of action.commands) {\n this.logger.debug('Executing command', { command, cwd: this.cwd });\n let stdout = '';\n let stderr = '';\n let exitCode: number | null = 0;\n let outcome: ShellOutputResult['outcome'] = {\n type: 'exit',\n exitCode: 0\n };\n try {\n const result = await this.sandbox.exec(command, {\n timeout: action.timeoutMs,\n cwd: this.cwd\n });\n stdout = result.stdout;\n stderr = result.stderr;\n exitCode = result.exitCode;\n // exec returns a result even for failed commands, so check success field\n // Timeout would be indicated by a specific error or exit code\n outcome = { type: 'exit', exitCode };\n\n this.logger.debug('Command executed successfully', {\n command,\n exitCode,\n stdoutLength: stdout.length,\n stderrLength: stderr.length\n });\n\n // Log warnings for non-zero exit codes or stderr output\n if (exitCode !== 0) {\n this.logger.warn(`Command failed with exit code ${exitCode}`, {\n command,\n stderr\n });\n } else if (stderr) {\n this.logger.warn(`Command produced stderr output`, {\n command,\n stderr\n });\n } else {\n this.logger.info(`Command completed successfully`, { command });\n }\n } catch (error: unknown) {\n // Handle network/HTTP errors or timeout errors\n const errorObj = isErrorWithProperties(error) ? error : {};\n exitCode =\n typeof errorObj.exitCode === 'number' ? errorObj.exitCode : null;\n stdout = typeof errorObj.stdout === 'string' ? errorObj.stdout : '';\n stderr = typeof errorObj.stderr === 'string' ? errorObj.stderr : '';\n\n // Check if it's a timeout error\n const errorMessage = getErrorMessage(error);\n if (\n errorMessage.includes('timeout') ||\n errorMessage.includes('Timeout') ||\n errorMessage.includes('timed out')\n ) {\n this.logger.error(`Command timed out`, undefined, {\n command,\n timeout: action.timeoutMs\n });\n outcome = { type: 'timeout' };\n } else {\n this.logger.error(`Error executing command`, toError(error), {\n command,\n error: errorMessage || error,\n exitCode\n });\n outcome = { type: 'exit', exitCode: exitCode ?? 1 };\n }\n }\n output.push({\n command,\n stdout,\n stderr,\n outcome\n });\n\n // Collect results for API responses\n const collectedExitCode =\n outcome.type === 'exit' ? outcome.exitCode : null;\n const timestamp = Date.now();\n this.results.push({\n command: String(command),\n stdout: String(stdout),\n stderr: String(stderr),\n exitCode: collectedExitCode,\n timestamp\n });\n this.logger.debug('Result collected', {\n command,\n exitCode: collectedExitCode,\n timestamp\n });\n\n if (outcome.type === 'timeout') {\n this.logger.warn('Breaking command loop due to timeout');\n break;\n }\n }\n\n this.logger.debug('SandboxShell.run completed', {\n totalCommands: action.commands.length,\n resultsCount: this.results.length\n });\n return {\n output,\n providerData: {\n working_directory: this.cwd\n }\n };\n }\n}\n\n/**\n * Editor implementation that projects applyPatch operations from Agents\n * into calls against the sandbox filesystem APIs.\n */\nexport class Editor implements OpenAIEeditor {\n public results: FileOperationResult[] = [];\n private readonly logger: Logger;\n\n constructor(\n private readonly sandbox: Sandbox,\n private readonly root: string = '/workspace'\n ) {\n this.logger = createLogger({\n component: 'sandbox-do',\n operation: 'openai-editor'\n });\n }\n\n /**\n * Create a new file inside the sandbox by applying the provided diff.\n */\n async createFile(\n operation: Extract<ApplyPatchOperation, { type: 'create_file' }>\n ): Promise<ApplyPatchResult | undefined> {\n const targetPath = this.resolve(operation.path);\n this.logger.debug('WorkspaceEditor.createFile called', {\n path: operation.path,\n targetPath\n });\n\n try {\n // Create parent directory if needed\n const dirPath = this.getDirname(targetPath);\n if (dirPath !== this.root && dirPath !== '/') {\n this.logger.debug('Creating parent directory', { dirPath });\n await this.sandbox.mkdir(dirPath, { recursive: true });\n }\n\n const content = applyDiff('', operation.diff, 'create');\n this.logger.debug('Writing file content', {\n path: targetPath,\n contentLength: content.length\n });\n await this.sandbox.writeFile(targetPath, content, { encoding: 'utf-8' });\n const timestamp = Date.now();\n const result: FileOperationResult = {\n operation: 'create',\n path: operation.path,\n status: 'completed',\n output: `Created ${operation.path}`,\n timestamp\n };\n this.results.push(result);\n this.logger.info('File created successfully', {\n path: operation.path,\n timestamp\n });\n return { status: 'completed', output: `Created ${operation.path}` };\n } catch (error: unknown) {\n const timestamp = Date.now();\n const errorMessage = getErrorMessage(error);\n const result: FileOperationResult = {\n operation: 'create',\n path: operation.path,\n status: 'failed',\n output: `Failed to create ${operation.path}`,\n error: errorMessage,\n timestamp\n };\n this.results.push(result);\n this.logger.error('Failed to create file', toError(error), {\n path: operation.path,\n error: errorMessage\n });\n throw error;\n }\n }\n\n /**\n * Update an existing file by reading its content, applying a diff, and\n * writing the patched output back to the sandbox.\n */\n async updateFile(\n operation: Extract<ApplyPatchOperation, { type: 'update_file' }>\n ): Promise<ApplyPatchResult | undefined> {\n const targetPath = this.resolve(operation.path);\n this.logger.debug('WorkspaceEditor.updateFile called', {\n path: operation.path,\n targetPath\n });\n\n try {\n let original: string;\n try {\n this.logger.debug('Reading original file', { path: targetPath });\n const fileInfo = await this.sandbox.readFile(targetPath, {\n encoding: 'utf-8'\n });\n original = fileInfo.content;\n this.logger.debug('Original file read', {\n path: targetPath,\n originalLength: original.length\n });\n } catch (error: unknown) {\n // Sandbox API may throw errors for missing files\n const errorObj = isErrorWithProperties(error) ? error : {};\n const errorMessage = getErrorMessage(error);\n if (\n errorMessage.includes('not found') ||\n errorMessage.includes('ENOENT') ||\n errorObj.status === 404\n ) {\n this.logger.error('Cannot update missing file', undefined, {\n path: operation.path\n });\n throw new Error(`Cannot update missing file: ${operation.path}`);\n }\n this.logger.error('Error reading file', toError(error), {\n path: operation.path,\n error: errorMessage\n });\n throw error;\n }\n\n const patched = applyDiff(original, operation.diff);\n this.logger.debug('Applied diff', {\n path: targetPath,\n originalLength: original.length,\n patchedLength: patched.length\n });\n await this.sandbox.writeFile(targetPath, patched, { encoding: 'utf-8' });\n const timestamp = Date.now();\n const result: FileOperationResult = {\n operation: 'update',\n path: operation.path,\n status: 'completed',\n output: `Updated ${operation.path}`,\n timestamp\n };\n this.results.push(result);\n this.logger.info('File updated successfully', {\n path: operation.path,\n timestamp\n });\n return { status: 'completed', output: `Updated ${operation.path}` };\n } catch (error: unknown) {\n const timestamp = Date.now();\n const errorMessage = getErrorMessage(error);\n const result: FileOperationResult = {\n operation: 'update',\n path: operation.path,\n status: 'failed',\n output: `Failed to update ${operation.path}`,\n error: errorMessage,\n timestamp\n };\n this.results.push(result);\n this.logger.error('Failed to update file', toError(error), {\n path: operation.path,\n error: errorMessage\n });\n throw error;\n }\n }\n\n /**\n * Delete a file that was previously created through applyPatch calls.\n */\n async deleteFile(\n operation: Extract<ApplyPatchOperation, { type: 'delete_file' }>\n ): Promise<ApplyPatchResult | undefined> {\n const targetPath = this.resolve(operation.path);\n this.logger.debug('WorkspaceEditor.deleteFile called', {\n path: operation.path,\n targetPath\n });\n\n try {\n await this.sandbox.deleteFile(targetPath);\n const timestamp = Date.now();\n const result: FileOperationResult = {\n operation: 'delete',\n path: operation.path,\n status: 'completed',\n output: `Deleted ${operation.path}`,\n timestamp\n };\n this.results.push(result);\n this.logger.info('File deleted successfully', {\n path: operation.path,\n timestamp\n });\n return { status: 'completed', output: `Deleted ${operation.path}` };\n } catch (error: unknown) {\n const timestamp = Date.now();\n const errorMessage = getErrorMessage(error);\n const result: FileOperationResult = {\n operation: 'delete',\n path: operation.path,\n status: 'failed',\n output: `Failed to delete ${operation.path}`,\n error: errorMessage,\n timestamp\n };\n this.results.push(result);\n this.logger.error('Failed to delete file', toError(error), {\n path: operation.path,\n error: errorMessage\n });\n throw error;\n }\n }\n\n private resolve(relativePath: string): string {\n // If the path already starts with the root, strip it to get the relative part\n let pathToProcess = relativePath;\n if (relativePath.startsWith(this.root)) {\n pathToProcess = relativePath.slice(this.root.length);\n // Remove leading slash if present after stripping root\n pathToProcess = pathToProcess.replace(/^\\//, '');\n }\n\n // Remove leading ./ or / if present, then join with root\n const normalized = pathToProcess.replace(/^\\.\\//, '').replace(/^\\//, '');\n const resolved = normalized ? `${this.root}/${normalized}` : this.root;\n\n // Normalize path separators first\n const pathWithNormalizedSeparators = resolved.replace(/\\/+/g, '/');\n\n // Normalize .. segments by processing path segments\n const segments = pathWithNormalizedSeparators\n .split('/')\n .filter((s) => s && s !== '.');\n const stack: string[] = [];\n\n for (const segment of segments) {\n if (segment === '..') {\n if (stack.length === 0) {\n throw new Error(`Operation outside workspace: ${relativePath}`);\n }\n stack.pop();\n } else {\n stack.push(segment);\n }\n }\n\n const normalizedPath = `/${stack.join('/')}`;\n\n // Ensure the resolved path is within the workspace\n if (!normalizedPath.startsWith(this.root)) {\n throw new Error(`Operation outside workspace: ${relativePath}`);\n }\n\n return normalizedPath;\n }\n\n private getDirname(filePath: string): string {\n const lastSlash = filePath.lastIndexOf('/');\n if (lastSlash === -1) {\n return '/';\n }\n return filePath.substring(0, lastSlash) || '/';\n }\n}\n"],"mappings":";;;;;;;;AAsCA,SAAS,sBAAsB,OAO7B;AACA,QAAO,OAAO,UAAU,YAAY,UAAU;;AAGhD,SAAS,gBAAgB,OAAwB;AAC/C,KAAI,sBAAsB,MAAM,IAAI,OAAO,MAAM,YAAY,SAC3D,QAAO,MAAM;AAEf,QAAO,OAAO,MAAM;;;;;;AAOtB,SAAS,QAAQ,OAAmC;AAClD,QAAO,iBAAiB,QAAQ,QAAQ;;;;;;AAO1C,IAAa,QAAb,MAA0C;CACxC,AAAQ,MAAc;CACtB,AAAO,UAA2B,EAAE;CACpC,AAAiB;CAEjB,YAAY,AAAiBA,SAAkB;EAAlB;AAC3B,OAAK,SAAS,aAAa;GACzB,WAAW;GACX,WAAW;GACZ,CAAC;;CAGJ,MAAM,IAAI,QAA2C;AACnD,OAAK,OAAO,MAAM,2BAA2B;GAC3C,UAAU,OAAO;GACjB,SAAS,OAAO;GACjB,CAAC;EACF,MAAMC,SAAgC,EAAE;AAExC,OAAK,MAAM,WAAW,OAAO,UAAU;AACrC,QAAK,OAAO,MAAM,qBAAqB;IAAE;IAAS,KAAK,KAAK;IAAK,CAAC;GAClE,IAAI,SAAS;GACb,IAAI,SAAS;GACb,IAAIC,WAA0B;GAC9B,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AS,YAAY,IAAI;AAC3C,MAAI,cAAc,GAChB,QAAO;AAET,SAAO,SAAS,UAAU,GAAG,UAAU,IAAI"}
1
+ {"version":3,"file":"index.js","names":["sandbox: Sandbox","output: ShellResult['output']","exitCode: number | null","outcome: ShellOutputResult['outcome']","error: unknown","root: string","result: FileOperationResult","original: string","stack: string[]"],"sources":["../../src/openai/index.ts"],"sourcesContent":["/**\n * OpenAI Agents adapters for executing shell commands and file operations\n * inside a Cloudflare Sandbox.\n */\nimport {\n type ApplyPatchOperation,\n type ApplyPatchResult,\n applyDiff,\n type Editor as OpenAIEeditor,\n type Shell as OpenAIShell,\n type ShellAction,\n type ShellOutputResult,\n type ShellResult\n} from '@openai/agents';\n\n// Command result for API responses\nexport interface CommandResult {\n command: string;\n stdout: string;\n stderr: string;\n exitCode: number | null;\n timestamp: number;\n}\n\n// File operation result for API responses\nexport interface FileOperationResult {\n operation: 'create' | 'update' | 'delete';\n path: string;\n status: 'completed' | 'failed';\n output: string;\n error?: string;\n timestamp: number;\n}\n\nimport { createLogger, type Logger } from '@repo/shared';\nimport type { Sandbox } from '../sandbox';\n\n// Helper functions for error handling\nfunction isErrorWithProperties(error: unknown): error is {\n message?: string;\n exitCode?: number;\n stdout?: string;\n stderr?: string;\n status?: number;\n stack?: string;\n} {\n return typeof error === 'object' && error !== null;\n}\n\nfunction getErrorMessage(error: unknown): string {\n if (isErrorWithProperties(error) && typeof error.message === 'string') {\n return error.message;\n }\n return String(error);\n}\n\n/**\n * Convert unknown values to Error instances when possible so downstream\n * loggers can include stack traces without losing type safety.\n */\nfunction toError(error: unknown): Error | undefined {\n return error instanceof Error ? error : undefined;\n}\n\n/**\n * Shell implementation that adapts Cloudflare Sandbox exec calls to the\n * OpenAI Agents `Shell` contract, including structured result collection.\n */\nexport class Shell implements OpenAIShell {\n private cwd: string = '/workspace';\n public results: CommandResult[] = [];\n private readonly logger: Logger;\n\n constructor(private readonly sandbox: Sandbox) {\n this.logger = createLogger({\n component: 'sandbox-do',\n operation: 'openai-shell'\n });\n }\n\n async run(action: ShellAction): Promise<ShellResult> {\n this.logger.debug('SandboxShell.run called', {\n commandCount: action.commands.length,\n timeout: action.timeoutMs\n });\n const output: ShellResult['output'] = [];\n\n for (const command of action.commands) {\n this.logger.debug('Executing command', { cwd: this.cwd });\n let stdout = '';\n let stderr = '';\n let exitCode: number | null = 0;\n let outcome: ShellOutputResult['outcome'] = {\n type: 'exit',\n exitCode: 0\n };\n try {\n const result = await this.sandbox.exec(command, {\n timeout: action.timeoutMs,\n cwd: this.cwd\n });\n stdout = result.stdout;\n stderr = result.stderr;\n exitCode = result.exitCode;\n // exec returns a result even for failed commands, so check success field\n // Timeout would be indicated by a specific error or exit code\n outcome = { type: 'exit', exitCode };\n\n this.logger.debug('Command executed successfully', {\n exitCode,\n stdoutLength: stdout.length,\n stderrLength: stderr.length\n });\n\n // Log warnings for non-zero exit codes or stderr output\n if (exitCode !== 0) {\n this.logger.warn(`Command failed with exit code ${exitCode}`, {\n stderrLength: stderr.length\n });\n } else if (stderr) {\n this.logger.warn(`Command produced stderr output`, {\n stderrLength: stderr.length\n });\n } else {\n this.logger.info(`Command completed successfully`);\n }\n } catch (error: unknown) {\n // Handle network/HTTP errors or timeout errors\n const errorObj = isErrorWithProperties(error) ? error : {};\n exitCode =\n typeof errorObj.exitCode === 'number' ? errorObj.exitCode : null;\n stdout = typeof errorObj.stdout === 'string' ? errorObj.stdout : '';\n stderr = typeof errorObj.stderr === 'string' ? errorObj.stderr : '';\n\n // Check if it's a timeout error\n const errorMessage = getErrorMessage(error);\n if (\n errorMessage.includes('timeout') ||\n errorMessage.includes('Timeout') ||\n errorMessage.includes('timed out')\n ) {\n this.logger.error(`Command timed out`, undefined, {\n timeout: action.timeoutMs\n });\n outcome = { type: 'timeout' };\n } else {\n this.logger.error(`Error executing command`, toError(error), {\n exitCode\n });\n outcome = { type: 'exit', exitCode: exitCode ?? 1 };\n }\n }\n output.push({\n command,\n stdout,\n stderr,\n outcome\n });\n\n // Collect results for API responses\n const collectedExitCode =\n outcome.type === 'exit' ? outcome.exitCode : null;\n const timestamp = Date.now();\n this.results.push({\n command: String(command),\n stdout: String(stdout),\n stderr: String(stderr),\n exitCode: collectedExitCode,\n timestamp\n });\n this.logger.debug('Result collected', {\n exitCode: collectedExitCode,\n timestamp\n });\n\n if (outcome.type === 'timeout') {\n this.logger.warn('Breaking command loop due to timeout');\n break;\n }\n }\n\n this.logger.debug('SandboxShell.run completed', {\n totalCommands: action.commands.length,\n resultsCount: this.results.length\n });\n return {\n output,\n providerData: {\n working_directory: this.cwd\n }\n };\n }\n}\n\n/**\n * Editor implementation that projects applyPatch operations from Agents\n * into calls against the sandbox filesystem APIs.\n */\nexport class Editor implements OpenAIEeditor {\n public results: FileOperationResult[] = [];\n private readonly logger: Logger;\n\n constructor(\n private readonly sandbox: Sandbox,\n private readonly root: string = '/workspace'\n ) {\n this.logger = createLogger({\n component: 'sandbox-do',\n operation: 'openai-editor'\n });\n }\n\n /**\n * Create a new file inside the sandbox by applying the provided diff.\n */\n async createFile(\n operation: Extract<ApplyPatchOperation, { type: 'create_file' }>\n ): Promise<ApplyPatchResult | undefined> {\n const targetPath = this.resolve(operation.path);\n this.logger.debug('WorkspaceEditor.createFile called', {\n path: operation.path,\n targetPath\n });\n\n try {\n // Create parent directory if needed\n const dirPath = this.getDirname(targetPath);\n if (dirPath !== this.root && dirPath !== '/') {\n this.logger.debug('Creating parent directory', { dirPath });\n await this.sandbox.mkdir(dirPath, { recursive: true });\n }\n\n const content = applyDiff('', operation.diff, 'create');\n this.logger.debug('Writing file content', {\n path: targetPath,\n contentLength: content.length\n });\n await this.sandbox.writeFile(targetPath, content, { encoding: 'utf-8' });\n const timestamp = Date.now();\n const result: FileOperationResult = {\n operation: 'create',\n path: operation.path,\n status: 'completed',\n output: `Created ${operation.path}`,\n timestamp\n };\n this.results.push(result);\n this.logger.info('File created successfully', {\n path: operation.path,\n timestamp\n });\n return { status: 'completed', output: `Created ${operation.path}` };\n } catch (error: unknown) {\n const timestamp = Date.now();\n const errorMessage = getErrorMessage(error);\n const result: FileOperationResult = {\n operation: 'create',\n path: operation.path,\n status: 'failed',\n output: `Failed to create ${operation.path}`,\n error: errorMessage,\n timestamp\n };\n this.results.push(result);\n // applyDiff errors quote patch lines, which can hold file contents.\n // The caller still gets the full error.\n this.logger.error('Failed to create file', undefined, {\n path: operation.path\n });\n throw error;\n }\n }\n\n /**\n * Update an existing file by reading its content, applying a diff, and\n * writing the patched output back to the sandbox.\n */\n async updateFile(\n operation: Extract<ApplyPatchOperation, { type: 'update_file' }>\n ): Promise<ApplyPatchResult | undefined> {\n const targetPath = this.resolve(operation.path);\n this.logger.debug('WorkspaceEditor.updateFile called', {\n path: operation.path,\n targetPath\n });\n\n try {\n let original: string;\n try {\n this.logger.debug('Reading original file', { path: targetPath });\n const fileInfo = await this.sandbox.readFile(targetPath, {\n encoding: 'utf-8'\n });\n original = fileInfo.content;\n this.logger.debug('Original file read', {\n path: targetPath,\n originalLength: original.length\n });\n } catch (error: unknown) {\n // Sandbox API may throw errors for missing files\n const errorObj = isErrorWithProperties(error) ? error : {};\n const errorMessage = getErrorMessage(error);\n if (\n errorMessage.includes('not found') ||\n errorMessage.includes('ENOENT') ||\n errorObj.status === 404\n ) {\n this.logger.error('Cannot update missing file', undefined, {\n path: operation.path\n });\n throw new Error(`Cannot update missing file: ${operation.path}`);\n }\n this.logger.error('Error reading file', toError(error), {\n path: operation.path,\n error: errorMessage\n });\n throw error;\n }\n\n const patched = applyDiff(original, operation.diff);\n this.logger.debug('Applied diff', {\n path: targetPath,\n originalLength: original.length,\n patchedLength: patched.length\n });\n await this.sandbox.writeFile(targetPath, patched, { encoding: 'utf-8' });\n const timestamp = Date.now();\n const result: FileOperationResult = {\n operation: 'update',\n path: operation.path,\n status: 'completed',\n output: `Updated ${operation.path}`,\n timestamp\n };\n this.results.push(result);\n this.logger.info('File updated successfully', {\n path: operation.path,\n timestamp\n });\n return { status: 'completed', output: `Updated ${operation.path}` };\n } catch (error: unknown) {\n const timestamp = Date.now();\n const errorMessage = getErrorMessage(error);\n const result: FileOperationResult = {\n operation: 'update',\n path: operation.path,\n status: 'failed',\n output: `Failed to update ${operation.path}`,\n error: errorMessage,\n timestamp\n };\n this.results.push(result);\n // applyDiff errors quote patch lines, which can hold file contents.\n // The caller still gets the full error.\n this.logger.error('Failed to update file', undefined, {\n path: operation.path\n });\n throw error;\n }\n }\n\n /**\n * Delete a file that was previously created through applyPatch calls.\n */\n async deleteFile(\n operation: Extract<ApplyPatchOperation, { type: 'delete_file' }>\n ): Promise<ApplyPatchResult | undefined> {\n const targetPath = this.resolve(operation.path);\n this.logger.debug('WorkspaceEditor.deleteFile called', {\n path: operation.path,\n targetPath\n });\n\n try {\n await this.sandbox.deleteFile(targetPath);\n const timestamp = Date.now();\n const result: FileOperationResult = {\n operation: 'delete',\n path: operation.path,\n status: 'completed',\n output: `Deleted ${operation.path}`,\n timestamp\n };\n this.results.push(result);\n this.logger.info('File deleted successfully', {\n path: operation.path,\n timestamp\n });\n return { status: 'completed', output: `Deleted ${operation.path}` };\n } catch (error: unknown) {\n const timestamp = Date.now();\n const errorMessage = getErrorMessage(error);\n const result: FileOperationResult = {\n operation: 'delete',\n path: operation.path,\n status: 'failed',\n output: `Failed to delete ${operation.path}`,\n error: errorMessage,\n timestamp\n };\n this.results.push(result);\n this.logger.error('Failed to delete file', toError(error), {\n path: operation.path,\n error: errorMessage\n });\n throw error;\n }\n }\n\n private resolve(relativePath: string): string {\n // If the path already starts with the root, strip it to get the relative part\n let pathToProcess = relativePath;\n if (relativePath.startsWith(this.root)) {\n pathToProcess = relativePath.slice(this.root.length);\n // Remove leading slash if present after stripping root\n pathToProcess = pathToProcess.replace(/^\\//, '');\n }\n\n // Remove leading ./ or / if present, then join with root\n const normalized = pathToProcess.replace(/^\\.\\//, '').replace(/^\\//, '');\n const resolved = normalized ? `${this.root}/${normalized}` : this.root;\n\n // Normalize path separators first\n const pathWithNormalizedSeparators = resolved.replace(/\\/+/g, '/');\n\n // Normalize .. segments by processing path segments\n const segments = pathWithNormalizedSeparators\n .split('/')\n .filter((s) => s && s !== '.');\n const stack: string[] = [];\n\n for (const segment of segments) {\n if (segment === '..') {\n if (stack.length === 0) {\n throw new Error(`Operation outside workspace: ${relativePath}`);\n }\n stack.pop();\n } else {\n stack.push(segment);\n }\n }\n\n const normalizedPath = `/${stack.join('/')}`;\n\n // Ensure the resolved path is within the workspace\n if (!normalizedPath.startsWith(this.root)) {\n throw new Error(`Operation outside workspace: ${relativePath}`);\n }\n\n return normalizedPath;\n }\n\n private getDirname(filePath: string): string {\n const lastSlash = filePath.lastIndexOf('/');\n if (lastSlash === -1) {\n return '/';\n }\n return filePath.substring(0, lastSlash) || '/';\n }\n}\n"],"mappings":";;;;;;;;AAsCA,SAAS,sBAAsB,OAO7B;AACA,QAAO,OAAO,UAAU,YAAY,UAAU;;AAGhD,SAAS,gBAAgB,OAAwB;AAC/C,KAAI,sBAAsB,MAAM,IAAI,OAAO,MAAM,YAAY,SAC3D,QAAO,MAAM;AAEf,QAAO,OAAO,MAAM;;;;;;AAOtB,SAAS,QAAQ,OAAmC;AAClD,QAAO,iBAAiB,QAAQ,QAAQ;;;;;;AAO1C,IAAa,QAAb,MAA0C;CACxC,AAAQ,MAAc;CACtB,AAAO,UAA2B,EAAE;CACpC,AAAiB;CAEjB,YAAY,AAAiBA,SAAkB;EAAlB;AAC3B,OAAK,SAAS,aAAa;GACzB,WAAW;GACX,WAAW;GACZ,CAAC;;CAGJ,MAAM,IAAI,QAA2C;AACnD,OAAK,OAAO,MAAM,2BAA2B;GAC3C,cAAc,OAAO,SAAS;GAC9B,SAAS,OAAO;GACjB,CAAC;EACF,MAAMC,SAAgC,EAAE;AAExC,OAAK,MAAM,WAAW,OAAO,UAAU;AACrC,QAAK,OAAO,MAAM,qBAAqB,EAAE,KAAK,KAAK,KAAK,CAAC;GACzD,IAAI,SAAS;GACb,IAAI,SAAS;GACb,IAAIC,WAA0B;GAC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AAI"}
@@ -1,5 +1,5 @@
1
- import { n as Sandbox } from "../sandbox-BtaWcmmG.js";
2
- import { c as OpencodeStartupContext } from "../contexts-C186NnAB.js";
1
+ import { n as Sandbox } from "../sandbox-mYLglwK1.js";
2
+ import { c as OpencodeStartupContext } from "../contexts-CxAJGHFf.js";
3
3
  import { OpencodeClient } from "@opencode-ai/sdk/v2/client";
4
4
  import { Config } from "@opencode-ai/sdk/v2";
5
5
 
@@ -14,7 +14,11 @@ interface OpencodeOptions {
14
14
  directory?: string;
15
15
  /** OpenCode configuration */
16
16
  config?: Config;
17
- /** Additional environment variables to pass to the OpenCode process */
17
+ /**
18
+ * Additional environment variables to pass to the OpenCode process. When
19
+ * this sets `OPENCODE_SERVER_PASSWORD`, the client from `createOpencode()`
20
+ * authenticates with it.
21
+ */
18
22
  env?: Record<string, string>;
19
23
  }
20
24
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/opencode/types.ts","../../src/opencode/opencode.ts"],"sourcesContent":[],"mappings":";;;;;;;;;AAOiB,UAAA,eAAA,CAAe;EAcf;EAaA,IAAA,CAAA,EAAA,MAAA;EAAyB;EAEhC,SAAA,CAAA,EAAA,MAAA;EAEA;EAAc,MAAA,CAAA,EAzBb,MAyBa;EAMX;EAEc,GAAA,CAAA,EA/BnB,MA+BmB,CAAA,MAAA,EAAA,MAAA,CAAA;;;;;UAzBV,cAAA;;;ECsSK;EACX,GAAA,EAAA,MAAA;EACC;EACD,KAAA,EAAA,EDnSA,OCmSA,CAAA,IAAA,CAAA;;;AAqEX;;;AAEY,UDnWK,cCmWL,CAAA,UDnW8B,cCmW9B,CAAA,CAAA;EACc;EAAf,MAAA,EDlWD,OCkWC;EAAR;EAAO,MAAA,EDhWA,cCgWA;AA0BV;;;;AAIW,cDxXE,oBAAA,SAA6B,KAAA,CCwX/B;EAAR,SAAA,IAAA,EAAA,yBAAA;EAAO,SAAA,OAAA,EDtXiB,sBCsXjB;EAmDM,WAAA,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BAAA,SAA6B,KAAA,CC2b/B;EACA,SAAA,IAAA,EAAA,yBAAA;EACD,SAAA,OAAA,ED3biB,sBC2bjB;EACP,WAAA,CAAA,OAAA,EAAA,MAAA,EAAA,OAAA,EDxbU,sBCwbV,EAAA,OAAA,CAAA,EDvbW,YCubX;;;;;;;ADveH;AAkBA;AAaA;;;;;AAUA;;;;;;;;;AC+QA;;;;;;AAwEA;;;;;;;;AA4CA;;;;;;;AAuDA;;;;;;AAIc,iBA/KQ,oBAAA,CA+KR,OAAA,EA9KH,OA8KG,CAAA,OAAA,CAAA,EAAA,OAAA,CAAA,EA7KF,eA6KE,CAAA,EA5KX,OA4KW,CA5KH,cA4KG,CAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAvGQ,yBAAyB,yBACpC,4BACC,kBACT,QAAQ,eAAe;;;;;;;;iBAyCV,qBAAA,UACL,kBACA,0BACD,iBACP,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAmDK,eAAA,UACL,kBACA,0BACD,iBACP,WAAW,QAAQ"}
@@ -1,5 +1,5 @@
1
- import { u as createLogger } from "../dist-B_eXrP83.js";
2
- import { r as ErrorCode } from "../errors-CpkKPbWC.js";
1
+ import { d as createLogger } from "../dist-CqPJfREN.js";
2
+ import { r as ErrorCode } from "../errors-CHhwDJNh.js";
3
3
 
4
4
  //#region src/opencode/types.ts
5
5
  /**
@@ -27,6 +27,21 @@ const DEFAULT_PORT = 4096;
27
27
  const OPENCODE_STARTUP_TIMEOUT_MS = 18e4;
28
28
  const OPENCODE_SERVE = (port) => `opencode serve --port ${port} --hostname 0.0.0.0`;
29
29
  /**
30
+ * `GET /path` returns 200 once OpenCode has bootstrapped its project. When
31
+ * `OPENCODE_SERVER_PASSWORD` is set, OpenCode answers this unauthenticated
32
+ * probe with 401 instead, which still means the server is up. The range also
33
+ * admits 3xx and 400, which `/path` does not return.
34
+ */
35
+ const OPENCODE_READY_CHECK = {
36
+ mode: "http",
37
+ path: "/path",
38
+ status: {
39
+ min: 200,
40
+ max: 401
41
+ },
42
+ timeout: OPENCODE_STARTUP_TIMEOUT_MS
43
+ };
44
+ /**
30
45
  * Build the full command, optionally with a directory prefix.
31
46
  * If directory is provided, we cd to it first so OpenCode uses it as cwd.
32
47
  */
@@ -71,12 +86,7 @@ async function ensureOpencodeServer(sandbox, port, directory, config, customEnv)
71
86
  processId: existingProcess.id
72
87
  });
73
88
  try {
74
- await existingProcess.waitForPort(port, {
75
- mode: "http",
76
- path: "/path",
77
- status: 200,
78
- timeout: OPENCODE_STARTUP_TIMEOUT_MS
79
- });
89
+ await existingProcess.waitForPort(port, OPENCODE_READY_CHECK);
80
90
  } catch (e) {
81
91
  const logs = await existingProcess.getLogs();
82
92
  throw new OpencodeStartupError(`OpenCode server failed to start. Stderr: ${logs.stderr || "(empty)"}`, {
@@ -102,12 +112,7 @@ async function ensureOpencodeServer(sandbox, port, directory, config, customEnv)
102
112
  processId: retryProcess.id
103
113
  });
104
114
  if (retryProcess.status === "starting") try {
105
- await retryProcess.waitForPort(port, {
106
- mode: "http",
107
- path: "/path",
108
- status: 200,
109
- timeout: OPENCODE_STARTUP_TIMEOUT_MS
110
- });
115
+ await retryProcess.waitForPort(port, OPENCODE_READY_CHECK);
111
116
  } catch (e) {
112
117
  const logs = await retryProcess.getLogs();
113
118
  throw new OpencodeStartupError(`OpenCode server failed to start. Stderr: ${logs.stderr || "(empty)"}`, {
@@ -155,12 +160,7 @@ async function startOpencodeServer(sandbox, port, directory, config, customEnv)
155
160
  const command = buildOpencodeCommand(port, directory);
156
161
  const process = await sandbox.startProcess(command, { env: Object.keys(env).length > 0 ? env : void 0 });
157
162
  try {
158
- await process.waitForPort(port, {
159
- mode: "http",
160
- path: "/path",
161
- status: 200,
162
- timeout: OPENCODE_STARTUP_TIMEOUT_MS
163
- });
163
+ await process.waitForPort(port, OPENCODE_READY_CHECK);
164
164
  getLogger().info("OpenCode server started successfully", {
165
165
  port,
166
166
  processId: process.id
@@ -295,12 +295,24 @@ async function createOpencode(sandbox, options) {
295
295
  return {
296
296
  client: clientFactory({
297
297
  baseUrl: server.url,
298
+ headers: authorizationHeaders(options?.env),
298
299
  fetch: (input, init) => sandbox.containerFetch(new Request(input, init), server.port)
299
300
  }),
300
301
  server
301
302
  };
302
303
  }
303
304
  /**
305
+ * Basic auth for an OpenCode server started with `OPENCODE_SERVER_PASSWORD`
306
+ * in `env`. OpenCode's default username is `opencode`.
307
+ */
308
+ function authorizationHeaders(env) {
309
+ const password = env?.OPENCODE_SERVER_PASSWORD;
310
+ if (!password) return void 0;
311
+ const username = env.OPENCODE_SERVER_USERNAME || "opencode";
312
+ const bytes = new TextEncoder().encode(`${username}:${password}`);
313
+ return { Authorization: `Basic ${btoa(String.fromCharCode(...bytes))}` };
314
+ }
315
+ /**
304
316
  * Proxy a request directly to the OpenCode server.
305
317
  *
306
318
  * Unlike `proxyToOpencode()`, this helper does not apply any web UI redirects
@@ -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,cAA0C,MAAM;CAC9C,AAAgB,OAAO,UAAU;CACjC,AAAgB;CAEhB,YACE,SACA,SACA,SACA;AACA,QAAM,SAAS,QAAQ;AACvB,OAAK,OAAO;AACZ,OAAK,UAAU;;;;;;AC/CnB,SAAS,YAAoB;AAC3B,QAAO,aAAa;EAAE,WAAW;EAAc,WAAW;EAAY,CAAC;;AAGzE,MAAM,eAAe;AACrB,MAAM,8BAA8B;AACpC,MAAM,kBAAkB,SACtB,yBAAyB,KAAK;;;;;AAMhC,SAAS,qBAAqB,MAAc,WAA4B;CACtE,MAAM,QAAQ,eAAe,KAAK;AAClC,QAAO,YAAY,MAAM,UAAU,MAAM,UAAU;;AAUrD,IAAIA;AAEJ,e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;;;;;;;;;;;;;;;;;;;;;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":["OPENCODE_READY_CHECK: WaitForPortOptions","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 /**\n * Additional environment variables to pass to the OpenCode process. When\n * this sets `OPENCODE_SERVER_PASSWORD`, the client from `createOpencode()`\n * authenticates with it.\n */\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 {\n createLogger,\n type Logger,\n type Process,\n type WaitForPortOptions\n} 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 * `GET /path` returns 200 once OpenCode has bootstrapped its project. When\n * `OPENCODE_SERVER_PASSWORD` is set, OpenCode answers this unauthenticated\n * probe with 401 instead, which still means the server is up. The range also\n * admits 3xx and 400, which `/path` does not return.\n */\nconst OPENCODE_READY_CHECK: WaitForPortOptions = {\n mode: 'http',\n path: '/path',\n status: { min: 200, max: 401 },\n timeout: OPENCODE_STARTUP_TIMEOUT_MS\n};\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 headers?: Record<string, 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, OPENCODE_READY_CHECK);\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, OPENCODE_READY_CHECK);\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, OPENCODE_READY_CHECK);\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 headers: authorizationHeaders(options?.env),\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 * Basic auth for an OpenCode server started with `OPENCODE_SERVER_PASSWORD`\n * in `env`. OpenCode's default username is `opencode`.\n */\nfunction authorizationHeaders(\n env: Record<string, string> | undefined\n): Record<string, string> | undefined {\n const password = env?.OPENCODE_SERVER_PASSWORD;\n if (!password) return undefined;\n const username = env.OPENCODE_SERVER_USERNAME || 'opencode';\n const bytes = new TextEncoder().encode(`${username}:${password}`);\n return { Authorization: `Basic ${btoa(String.fromCharCode(...bytes))}` };\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":";;;;;;;AAgDA,IAAa,uBAAb,cAA0C,MAAM;CAC9C,AAAgB,OAAO,UAAU;CACjC,AAAgB;CAEhB,YACE,SACA,SACA,SACA;AACA,QAAM,SAAS,QAAQ;AACvB,OA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