@cloudflare/sandbox 0.12.9 → 0.12.11

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.
@@ -132,24 +132,6 @@ function redactSensitiveParams(input) {
132
132
  function redactCommand(command) {
133
133
  return redactSensitiveParams(redactCredentials(command));
134
134
  }
135
- /**
136
- * Truncate a string for log output with a truncation indicator
137
- *
138
- * @param value - String to potentially truncate
139
- * @param maxLen - Maximum length before truncation (default 120)
140
- * @returns Object with truncated value and boolean flag
141
- */
142
- function truncateForLog(value, maxLen = 120) {
143
- if (value.length <= maxLen) return {
144
- value,
145
- truncated: false
146
- };
147
- const cutoff = Math.max(0, maxLen - 3);
148
- return {
149
- value: `${value.substring(0, cutoff)}...`,
150
- truncated: true
151
- };
152
- }
153
135
 
154
136
  //#endregion
155
137
  //#region ../shared/dist/git.js
@@ -362,28 +344,16 @@ function sanitizeError(error) {
362
344
  return sanitized;
363
345
  }
364
346
  /**
365
- * Sanitize and prepare payload fields for both message building and context emission.
366
- * Called once by logCanonicalEvent to avoid double-redaction.
367
- */
368
- function sanitizePayload(payload) {
369
- if (payload.command === void 0) return { commandTruncated: false };
370
- const { value, truncated } = truncateForLog(redactCommand(payload.command));
371
- return {
372
- sanitizedCommand: value,
373
- commandTruncated: truncated
374
- };
375
- }
376
- /**
377
347
  * Build a human-readable canonical event message for dashboards and log viewers.
378
348
  *
379
349
  * Format: `{event} {outcome} {key_context} [— {reason}] ({durationMs}ms[, {sizeBytes}B])`
380
350
  *
381
- * The if/else chain for key context has implicit priority: command > path >
382
- * sessionId > port > repoUrl > pid. If a payload has multiple, only the
383
- * highest-priority one appears in the message. All fields are still present
384
- * as discrete queryable keys in the structured log context.
351
+ * The if/else chain for key context has implicit priority: path > sessionId >
352
+ * port > repoUrl > pid. If a payload has multiple, only the highest-priority
353
+ * one appears in the message. All fields are still present as discrete
354
+ * queryable keys in the structured log context.
385
355
  */
386
- function buildMessage(payload, sanitizedCommand) {
356
+ function buildMessage(payload) {
387
357
  const { event } = payload;
388
358
  if (event === "version.check") {
389
359
  const parts$1 = ["version.check"];
@@ -393,11 +363,7 @@ function buildMessage(payload, sanitizedCommand) {
393
363
  return parts$1.join(" ");
394
364
  }
395
365
  const parts = [event, payload.outcome];
396
- if (sanitizedCommand !== void 0) parts.push(sanitizedCommand);
397
- else if (payload.command !== void 0) {
398
- const { value } = truncateForLog(redactCommand(payload.command));
399
- parts.push(value);
400
- } else if (payload.path !== void 0) parts.push(payload.path);
366
+ if (payload.path !== void 0) parts.push(payload.path);
401
367
  else if (event.includes("session") && payload.sessionId !== void 0) parts.push(payload.sessionId);
402
368
  else if (payload.port !== void 0) parts.push(String(payload.port));
403
369
  else if (payload.repoUrl !== void 0) {
@@ -426,8 +392,8 @@ function buildMessage(payload, sanitizedCommand) {
426
392
  /**
427
393
  * Log a canonical event — the single entry point for all structured operational events.
428
394
  *
429
- * Sanitizes command fields once, builds the message, selects log level from
430
- * outcome, and emits a structured log entry with the full payload as context.
395
+ * Redacts error text, builds the message, selects log level from outcome, and
396
+ * emits a structured log entry with the full payload as context.
431
397
  */
432
398
  function logCanonicalEvent(logger, payload, options) {
433
399
  const resolvedErrorMessage = payload.errorMessage ?? payload.error?.message;
@@ -436,17 +402,12 @@ function logCanonicalEvent(logger, payload, options) {
436
402
  ...payload,
437
403
  errorMessage: sanitizedErrorMessage
438
404
  } : payload;
439
- const { sanitizedCommand, commandTruncated } = sanitizePayload(enrichedPayload);
440
- const message = buildMessage(enrichedPayload, sanitizedCommand);
405
+ const message = buildMessage(enrichedPayload);
441
406
  const context = {};
442
407
  for (const [key, value] of Object.entries(enrichedPayload)) {
443
408
  if (key === "error") continue;
444
409
  context[key] = value;
445
410
  }
446
- if (sanitizedCommand !== void 0) {
447
- context.command = sanitizedCommand;
448
- if (commandTruncated) context.commandTruncated = true;
449
- }
450
411
  const level = resolveLogLevel(enrichedPayload, options);
451
412
  if (level === "error") logger.error(message, sanitizeError(payload.error), context);
452
413
  else if (level === "warn") logger.warn(message, context);
@@ -961,4 +922,4 @@ function generateRequestId() {
961
922
 
962
923
  //#endregion
963
924
  export { GitLogger as _, isExecResult as a, getEnvString as b, parseSSEFrames as c, createNoOpLogger as d, TraceContext as f, DEFAULT_GIT_CLONE_TIMEOUT_MS as g, ResultImpl as h, isWSStreamChunk as i, shellEscape as l, Execution as m, isWSError as n, isProcess as o, logCanonicalEvent as p, isWSResponse as r, isProcessStatus as s, generateRequestId as t, createLogger as u, extractRepoName as v, partitionEnvVars as x, filterEnvVars as y };
964
- //# sourceMappingURL=dist-B_eXrP83.js.map
925
+ //# sourceMappingURL=dist-C3AQh4A0.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dist-C3AQh4A0.js","names":["parts","LogLevelEnum","LogLevelEnum"],"sources":["../../shared/dist/env.js","../../shared/dist/logger/sanitize.js","../../shared/dist/git.js","../../shared/dist/interpreter-types.js","../../shared/dist/logger/canonical.js","../../shared/dist/logger/types.js","../../shared/dist/logger/logger.js","../../shared/dist/logger/trace-context.js","../../shared/dist/logger/index.js","../../shared/dist/shell-escape.js","../../shared/dist/sse.js","../../shared/dist/types.js","../../shared/dist/ws-types.js"],"sourcesContent":["/**\n * Safely extract a string value from an environment object\n *\n * @param env - Environment object with dynamic keys\n * @param key - The environment variable key to access\n * @returns The string value if present and is a string, undefined otherwise\n */\nexport function getEnvString(env, key) {\n const value = env?.[key];\n return typeof value === 'string' ? value : undefined;\n}\n/**\n * Filter environment variables object to only include string values.\n * Skips undefined, null, and non-string values.\n *\n * Use this when you only need the defined values (e.g., for per-command env\n * where undefined means \"don't override\").\n *\n * @param envVars - Object that may contain undefined values\n * @returns Clean object with only string values\n */\nexport function filterEnvVars(envVars) {\n const filtered = {};\n for (const [key, value] of Object.entries(envVars)) {\n if (value != null && typeof value === 'string') {\n filtered[key] = value;\n }\n }\n return filtered;\n}\n/**\n * Partition environment variables into values to set and keys to unset.\n *\n * - String values → toSet (will be exported)\n * - undefined/null → toUnset (will be unset)\n *\n * This enables idiomatic JS patterns where undefined means \"remove\":\n * ```typescript\n * await sandbox.setEnvVars({\n * API_KEY: 'new-key', // will be set\n * OLD_VAR: undefined, // will be unset\n * });\n * ```\n */\nexport function partitionEnvVars(envVars) {\n const toSet = {};\n const toUnset = [];\n for (const [key, value] of Object.entries(envVars)) {\n if (value != null && typeof value === 'string') {\n toSet[key] = value;\n }\n else {\n toUnset.push(key);\n }\n }\n return { toSet, toUnset };\n}\n","/**\n * Log-only sanitization helpers\n *\n * These functions redact sensitive values for logging output.\n * They MUST NOT be used to mutate command strings before execution.\n */\n/**\n * Sensitive query parameter names to redact from URLs.\n * Anchored to query string context ([?&]) to avoid matching path segments.\n * Value matching stops at & and common URL/command delimiters.\n */\nconst SENSITIVE_PARAMS = /([?&])(X-Amz-Credential|X-Amz-Signature|X-Amz-Security-Token|token|secret|password)=[^&\\s\"'`<>]*/gi;\n/**\n * Redact credentials from URLs for secure logging\n *\n * Replaces any credentials (username:password, tokens, etc.) embedded\n * in URLs with ****** to prevent sensitive data exposure in logs.\n * Works with URLs embedded in text.\n *\n * @param text - String that may contain URLs with credentials\n * @returns String with credentials redacted from any URLs\n */\nexport function redactCredentials(text) {\n // Scan for http(s):// URLs and redact any credentials found\n let result = text;\n let pos = 0;\n while (pos < result.length) {\n const httpPos = result.indexOf('http://', pos);\n const httpsPos = result.indexOf('https://', pos);\n let protocolPos = -1;\n let protocolLen = 0;\n if (httpPos === -1 && httpsPos === -1)\n break;\n if (httpPos !== -1 && (httpsPos === -1 || httpPos < httpsPos)) {\n protocolPos = httpPos;\n protocolLen = 7; // 'http://'.length\n }\n else {\n protocolPos = httpsPos;\n protocolLen = 8; // 'https://'.length\n }\n // Look for @ after the protocol\n const searchStart = protocolPos + protocolLen;\n const atPos = result.indexOf('@', searchStart);\n // Find where the URL ends (whitespace, quotes, or structural delimiters)\n let urlEnd = searchStart;\n while (urlEnd < result.length) {\n const char = result[urlEnd];\n if (/[\\s\"'`<>,;{}[\\]]/.test(char))\n break;\n urlEnd++;\n }\n if (atPos !== -1 && atPos < urlEnd) {\n result = `${result.substring(0, searchStart)}******${result.substring(atPos)}`;\n pos = searchStart + 6; // Move past '******'\n }\n else {\n pos = protocolPos + protocolLen;\n }\n }\n return result;\n}\n/**\n * Redact sensitive query parameters from URLs\n *\n * Strips X-Amz-Credential, X-Amz-Signature, X-Amz-Security-Token,\n * token, secret, and password query params from URLs. Returns\n * non-URL strings unchanged.\n *\n * @param input - String that may contain URLs with sensitive params\n * @returns String with sensitive params replaced by REDACTED\n */\nexport function redactSensitiveParams(input) {\n if (!input.includes('?') || !input.includes('='))\n return input;\n return input.replace(SENSITIVE_PARAMS, '$1$2=REDACTED');\n}\n/**\n * Redact sensitive data from a command string for logging\n *\n * Composes redactCredentials (URL credentials) and redactSensitiveParams\n * (presigned URL query params). For log values only — never mutate\n * command strings before execution.\n *\n * @param command - Command string to sanitize for logging\n * @returns Sanitized command string\n */\nexport function redactCommand(command) {\n return redactSensitiveParams(redactCredentials(command));\n}\n","import { redactCommand } from './logger/sanitize.js';\n/**\n * Fallback repository name used when URL parsing fails\n */\nexport const FALLBACK_REPO_NAME = 'repository';\n/** Default wall-clock timeout in milliseconds for git clone operations. */\nexport const DEFAULT_GIT_CLONE_TIMEOUT_MS = 600_000;\n/**\n * Extract repository name from a Git URL\n *\n * Supports multiple URL formats:\n * - HTTPS: https://github.com/user/repo.git → repo\n * - HTTPS without .git: https://github.com/user/repo → repo\n * - SSH: git@github.com:user/repo.git → repo\n * - GitLab/others: https://gitlab.com/org/project.git → project\n *\n * @param repoUrl - Git repository URL (HTTPS or SSH format)\n * @returns Repository name extracted from URL, or 'repository' as fallback\n */\nexport function extractRepoName(repoUrl) {\n // Try parsing as standard URL (https://, http://)\n try {\n const url = new URL(repoUrl);\n const pathParts = url.pathname.split('/');\n const lastPart = pathParts[pathParts.length - 1];\n if (lastPart) {\n return lastPart.replace(/\\.git$/, '');\n }\n }\n catch {\n // Not a standard URL, try SSH format\n }\n // For SSH URLs (git@github.com:user/repo.git), split by : and / to get last segment\n // Only process if the URL contains path delimiters\n if (repoUrl.includes(':') || repoUrl.includes('/')) {\n const segments = repoUrl.split(/[:/]/).filter(Boolean);\n const lastSegment = segments[segments.length - 1];\n if (lastSegment) {\n return lastSegment.replace(/\\.git$/, '');\n }\n }\n return FALLBACK_REPO_NAME;\n}\n/**\n * Sanitize data by redacting credentials from any strings\n * Recursively processes objects and arrays to ensure credentials are never leaked\n */\nexport function sanitizeGitData(data) {\n // Handle primitives\n if (typeof data === 'string') {\n return redactCommand(data);\n }\n if (data === null || data === undefined) {\n return data;\n }\n // Handle arrays\n if (Array.isArray(data)) {\n return data.map((item) => sanitizeGitData(item));\n }\n // Handle objects - recursively sanitize all fields\n if (typeof data === 'object') {\n const result = {};\n for (const [key, value] of Object.entries(data)) {\n result[key] = sanitizeGitData(value);\n }\n return result;\n }\n return data;\n}\n/**\n * Logger wrapper that automatically sanitizes git credentials\n */\nexport class GitLogger {\n baseLogger;\n constructor(baseLogger) {\n this.baseLogger = baseLogger;\n }\n sanitizeContext(context) {\n return context\n ? sanitizeGitData(context)\n : context;\n }\n sanitizeError(error) {\n if (!error)\n return error;\n // Create a new error with sanitized message and stack\n const sanitized = new Error(redactCommand(error.message));\n sanitized.name = error.name;\n if (error.stack) {\n sanitized.stack = redactCommand(error.stack);\n }\n // Preserve other enumerable properties\n const sanitizedRecord = sanitized;\n const errorRecord = error;\n for (const key of Object.keys(error)) {\n if (key !== 'message' && key !== 'stack' && key !== 'name') {\n sanitizedRecord[key] = sanitizeGitData(errorRecord[key]);\n }\n }\n return sanitized;\n }\n debug(message, context) {\n this.baseLogger.debug(message, this.sanitizeContext(context));\n }\n info(message, context) {\n this.baseLogger.info(message, this.sanitizeContext(context));\n }\n warn(message, context) {\n this.baseLogger.warn(message, this.sanitizeContext(context));\n }\n error(message, error, context) {\n this.baseLogger.error(message, this.sanitizeError(error), this.sanitizeContext(context));\n }\n child(context) {\n const sanitized = sanitizeGitData(context);\n const childLogger = this.baseLogger.child(sanitized);\n return new GitLogger(childLogger);\n }\n}\n","// Execution Result Container\nexport class Execution {\n code;\n context;\n /**\n * All results from the execution\n */\n results = [];\n /**\n * Accumulated stdout and stderr\n */\n logs = {\n stdout: [],\n stderr: []\n };\n /**\n * Execution error if any\n */\n error;\n /**\n * Execution count (for interpreter)\n */\n executionCount;\n constructor(code, context) {\n this.code = code;\n this.context = context;\n }\n /**\n * Convert to a plain object for serialization\n */\n toJSON() {\n return {\n code: this.code,\n logs: this.logs,\n error: this.error,\n executionCount: this.executionCount,\n results: this.results.map((result) => ({\n text: result.text,\n html: result.html,\n png: result.png,\n jpeg: result.jpeg,\n svg: result.svg,\n latex: result.latex,\n markdown: result.markdown,\n javascript: result.javascript,\n json: result.json,\n chart: result.chart,\n data: result.data\n }))\n };\n }\n}\n// Implementation of Result\nexport class ResultImpl {\n text;\n html;\n png;\n jpeg;\n svg;\n latex;\n markdown;\n javascript;\n json;\n chart;\n data;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- raw SSE data has dynamic shape\n constructor(raw) {\n this.text = raw.text || raw.data?.['text/plain'];\n this.html = raw.html || raw.data?.['text/html'];\n this.png = raw.png || raw.data?.['image/png'];\n this.jpeg = raw.jpeg || raw.data?.['image/jpeg'];\n this.svg = raw.svg || raw.data?.['image/svg+xml'];\n this.latex = raw.latex || raw.data?.['text/latex'];\n this.markdown = raw.markdown || raw.data?.['text/markdown'];\n this.javascript = raw.javascript || raw.data?.['application/javascript'];\n this.json = raw.json || raw.data?.['application/json'];\n this.chart = raw.chart;\n this.data = raw.data;\n }\n formats() {\n const fmts = [];\n if (this.text)\n fmts.push('text');\n if (this.html)\n fmts.push('html');\n if (this.png)\n fmts.push('png');\n if (this.jpeg)\n fmts.push('jpeg');\n if (this.svg)\n fmts.push('svg');\n if (this.latex)\n fmts.push('latex');\n if (this.markdown)\n fmts.push('markdown');\n if (this.javascript)\n fmts.push('javascript');\n if (this.json)\n fmts.push('json');\n if (this.chart)\n fmts.push('chart');\n return fmts;\n }\n}\n","import { redactCommand } from './sanitize.js';\n/** Events that are low-value at info on success */\nconst DEBUG_ON_SUCCESS = new Set([\n 'session.create',\n 'session.destroy',\n 'file.read',\n 'file.write',\n 'file.delete',\n 'file.mkdir'\n]);\nexport function resolveLogLevel(payload, options) {\n if (payload.outcome === 'error')\n return 'error';\n if (options?.successLevel)\n return options.successLevel;\n if (payload.origin === 'internal')\n return 'debug';\n if (DEBUG_ON_SUCCESS.has(payload.event))\n return 'debug';\n return 'info';\n}\n/**\n * Sanitize an Error object by redacting sensitive data from message and stack.\n * Produces a copy so the caller's original Error is not mutated.\n */\nfunction sanitizeError(error) {\n if (!error)\n return undefined;\n const sanitized = new Error(redactCommand(error.message));\n sanitized.name = error.name;\n sanitized.stack = error.stack ? redactCommand(error.stack) : undefined;\n return sanitized;\n}\n/**\n * Build a human-readable canonical event message for dashboards and log viewers.\n *\n * Format: `{event} {outcome} {key_context} [— {reason}] ({durationMs}ms[, {sizeBytes}B])`\n *\n * The if/else chain for key context has implicit priority: path > sessionId >\n * port > repoUrl > pid. If a payload has multiple, only the highest-priority\n * one appears in the message. All fields are still present as discrete\n * queryable keys in the structured log context.\n */\nexport function buildMessage(payload) {\n const { event } = payload;\n // version.check has its own format: no outcome, no duration\n if (event === 'version.check') {\n const parts = ['version.check'];\n if (payload.sdkVersion)\n parts.push(`sdk=${payload.sdkVersion}`);\n if (payload.containerVersion)\n parts.push(`container=${payload.containerVersion}`);\n if (payload.versionOutcome && payload.versionOutcome !== 'compatible') {\n parts.push(`(${payload.versionOutcome})`);\n }\n return parts.join(' ');\n }\n const parts = [event, payload.outcome];\n // Key context — highest priority field shown in message\n if (payload.path !== undefined) {\n parts.push(payload.path);\n }\n else if (event.includes('session') && payload.sessionId !== undefined) {\n parts.push(payload.sessionId);\n }\n else if (payload.port !== undefined) {\n parts.push(String(payload.port));\n }\n else if (payload.repoUrl !== undefined) {\n let gitContext = payload.repoUrl;\n if (payload.branch !== undefined) {\n gitContext += ` ${payload.branch}`;\n }\n parts.push(gitContext);\n }\n else if (payload.pid !== undefined) {\n parts.push(String(payload.pid));\n }\n else if (payload.backupId !== undefined) {\n parts.push(payload.backupId);\n }\n else if (payload.repoPath !== undefined) {\n let gitContext = payload.repoPath;\n if (payload.branch !== undefined) {\n gitContext += ` branch=${payload.branch}`;\n }\n parts.push(gitContext);\n }\n else if (payload.mountsProcessed !== undefined) {\n let destroyContext = `${payload.mountsProcessed} mounts`;\n if (payload.mountFailures)\n destroyContext += `, ${payload.mountFailures} failed`;\n parts.push(destroyContext);\n }\n else if (payload.mountPath !== undefined) {\n parts.push(payload.mountPath);\n }\n // Error reason after em-dash\n if (payload.outcome === 'error') {\n if (payload.errorMessage !== undefined) {\n parts.push(`\\u2014 ${payload.errorMessage}`);\n }\n else if (payload.exitCode !== undefined) {\n parts.push(`\\u2014 exitCode=${payload.exitCode}`);\n }\n }\n // Duration suffix (and optional size)\n const durationSuffix = payload.sizeBytes !== undefined\n ? `(${payload.durationMs}ms, ${payload.sizeBytes}B)`\n : `(${payload.durationMs}ms)`;\n parts.push(durationSuffix);\n return parts.join(' ');\n}\n/**\n * Log a canonical event — the single entry point for all structured operational events.\n *\n * Redacts error text, builds the message, selects log level from outcome, and\n * emits a structured log entry with the full payload as context.\n */\nexport function logCanonicalEvent(logger, payload, options) {\n // Auto-derive errorMessage from error.message when not explicitly set,\n // then sanitize to prevent credential leaks (e.g., presigned URLs in error strings)\n const resolvedErrorMessage = payload.errorMessage ?? payload.error?.message;\n const sanitizedErrorMessage = resolvedErrorMessage\n ? redactCommand(resolvedErrorMessage)\n : undefined;\n const enrichedPayload = sanitizedErrorMessage !== undefined\n ? { ...payload, errorMessage: sanitizedErrorMessage }\n : payload;\n const message = buildMessage(enrichedPayload);\n // Build context from enriched payload, excluding the error object (passed separately)\n const context = {};\n for (const [key, value] of Object.entries(enrichedPayload)) {\n if (key === 'error')\n continue;\n context[key] = value;\n }\n const level = resolveLogLevel(enrichedPayload, options);\n if (level === 'error') {\n logger.error(message, sanitizeError(payload.error), context);\n }\n else if (level === 'warn') {\n logger.warn(message, context);\n }\n else if (level === 'debug') {\n logger.debug(message, context);\n }\n else {\n logger.info(message, context);\n }\n}\n","/**\n * Logger types for Cloudflare Sandbox SDK\n *\n * Provides structured, trace-aware logging across Worker, Durable Object, and Container.\n */\n/**\n * Log levels (from most to least verbose)\n */\nexport var LogLevel;\n(function (LogLevel) {\n LogLevel[LogLevel[\"DEBUG\"] = 0] = \"DEBUG\";\n LogLevel[LogLevel[\"INFO\"] = 1] = \"INFO\";\n LogLevel[LogLevel[\"WARN\"] = 2] = \"WARN\";\n LogLevel[LogLevel[\"ERROR\"] = 3] = \"ERROR\";\n})(LogLevel || (LogLevel = {}));\n","/**\n * Logger implementation\n */\nimport { LogLevel as LogLevelEnum } from './types.js';\n/**\n * ANSI color codes for terminal output\n */\nconst COLORS = {\n reset: '\\x1b[0m',\n debug: '\\x1b[36m', // Cyan\n info: '\\x1b[32m', // Green\n warn: '\\x1b[33m', // Yellow\n error: '\\x1b[31m', // Red\n dim: '\\x1b[2m' // Dim\n};\n/**\n * CloudflareLogger implements structured logging with support for\n * both JSON output (production) and pretty printing (development).\n */\nexport class CloudflareLogger {\n baseContext;\n minLevel;\n outputMode;\n /**\n * Create a new CloudflareLogger\n *\n * @param baseContext Base context included in all log entries\n * @param minLevel Minimum log level to output (default: INFO)\n * @param outputMode How log entries are formatted and emitted (default: 'structured')\n */\n constructor(baseContext, minLevel = LogLevelEnum.INFO, outputMode = 'structured') {\n this.baseContext = baseContext;\n this.minLevel = minLevel;\n this.outputMode = outputMode;\n }\n /**\n * Log debug-level message\n */\n debug(message, context) {\n if (this.shouldLog(LogLevelEnum.DEBUG)) {\n const logData = this.buildLogData('debug', message, context);\n this.output(console.log, logData);\n }\n }\n /**\n * Log info-level message\n */\n info(message, context) {\n if (this.shouldLog(LogLevelEnum.INFO)) {\n const logData = this.buildLogData('info', message, context);\n this.output(console.log, logData);\n }\n }\n /**\n * Log warning-level message\n */\n warn(message, context) {\n if (this.shouldLog(LogLevelEnum.WARN)) {\n const logData = this.buildLogData('warn', message, context);\n this.output(console.warn, logData);\n }\n }\n /**\n * Log error-level message\n */\n error(message, error, context) {\n if (this.shouldLog(LogLevelEnum.ERROR)) {\n const logData = this.buildLogData('error', message, context, error);\n this.output(console.error, logData);\n }\n }\n /**\n * Create a child logger with additional context\n */\n child(context) {\n return new CloudflareLogger({ ...this.baseContext, ...context }, this.minLevel, this.outputMode);\n }\n /**\n * Check if a log level should be output\n */\n shouldLog(level) {\n return level >= this.minLevel;\n }\n /**\n * Build log data object\n */\n buildLogData(level, message, context, error) {\n const logData = {\n level,\n message,\n ...this.baseContext,\n ...context,\n timestamp: new Date().toISOString()\n };\n // Add error details if provided\n if (error) {\n logData.error = {\n message: error.message,\n stack: error.stack,\n name: error.name\n };\n }\n return logData;\n }\n /**\n * Output log data using the configured output mode\n */\n output(consoleFn, data) {\n switch (this.outputMode) {\n case 'pretty':\n this.outputPretty(consoleFn, data);\n break;\n case 'json-line':\n this.outputJsonLine(consoleFn, data);\n break;\n case 'structured':\n this.outputStructured(consoleFn, data);\n break;\n }\n }\n /**\n * Output as JSON string (container stdout — parsed by Containers pipeline)\n */\n outputJsonLine(consoleFn, data) {\n consoleFn(JSON.stringify(data));\n }\n /**\n * Output as raw object (Workers/DOs — Workers Logs auto-indexes fields)\n */\n outputStructured(consoleFn, data) {\n consoleFn(data);\n }\n /**\n * Output as pretty-printed, colored text (development)\n *\n * Each log event is a single consoleFn() call so it appears as one entry\n * in the Cloudflare dashboard. Context is rendered inline as compact key=value pairs.\n *\n * Format: LEVEL [component] message trace=tr_... key=value key=value\n */\n outputPretty(consoleFn, data) {\n const { level, message: msg, timestamp, traceId, component, sandboxId, sessionId, processId, commandId, durationMs, serviceVersion, instanceId, error, ...rest } = data;\n const levelStr = String(level || 'INFO').toUpperCase();\n const levelColor = this.getLevelColor(levelStr);\n const componentBadge = component ? `[${component}]` : '';\n const timeStr = timestamp\n ? `${COLORS.dim}${new Date(timestamp).toISOString().substring(11, 23)}${COLORS.reset} `\n : '';\n let logLine = `${timeStr}${levelColor}${levelStr.padEnd(5)}${COLORS.reset} ${componentBadge} ${msg}`;\n // Append all context as compact key=value pairs on the same line\n const pairs = [];\n if (traceId)\n pairs.push(`trace=${String(traceId).substring(0, 12)}`);\n if (commandId)\n pairs.push(`cmd=${String(commandId).substring(0, 12)}`);\n if (sandboxId)\n pairs.push(`sandbox=${sandboxId}`);\n if (sessionId)\n pairs.push(`session=${String(sessionId).substring(0, 12)}`);\n if (processId)\n pairs.push(`proc=${processId}`);\n if (durationMs !== undefined)\n pairs.push(`dur=${durationMs}ms`);\n // Append remaining context fields inline\n for (const [key, value] of Object.entries(rest)) {\n if (value === undefined || value === null)\n continue;\n const v = typeof value === 'object'\n ? JSON.stringify(value)\n : this.sanitizePrettyValue(String(value));\n pairs.push(`${key}=${v}`);\n }\n // Append error info inline\n if (error && typeof error === 'object') {\n const errorObj = error;\n if (errorObj.name)\n pairs.push(`err.name=${this.sanitizePrettyValue(errorObj.name)}`);\n if (errorObj.message)\n pairs.push(`err.msg=${this.sanitizePrettyValue(errorObj.message)}`);\n if (errorObj.stack)\n pairs.push(`err.stack=${this.sanitizePrettyValue(errorObj.stack)}`);\n }\n if (pairs.length > 0) {\n logLine += ` ${COLORS.dim}${pairs.join(' ')}${COLORS.reset}`;\n }\n // Single consoleFn call = single log entry in the dashboard\n consoleFn(logLine);\n }\n /**\n * Collapse newlines so a single consoleFn() call stays on one line.\n * Cloudflare's log pipeline splits on literal newlines, which fragments\n * stack traces and multi-line error messages into separate entries.\n */\n sanitizePrettyValue(value) {\n return value.replace(/\\r/g, '\\\\r').replace(/\\n/g, '\\\\n');\n }\n /**\n * Get ANSI color code for log level\n */\n getLevelColor(level) {\n const levelLower = level.toLowerCase();\n switch (levelLower) {\n case 'debug':\n return COLORS.debug;\n case 'info':\n return COLORS.info;\n case 'warn':\n return COLORS.warn;\n case 'error':\n return COLORS.error;\n default:\n return COLORS.reset;\n }\n }\n}\n","/**\n * Trace context utilities for request correlation\n *\n * Trace IDs enable correlating logs across distributed components:\n * Worker → Durable Object → Container → back\n *\n * The trace ID is propagated via the X-Trace-Id HTTP header.\n */\n/**\n * Utility for managing trace context across distributed components\n */\n// biome-ignore lint/complexity/noStaticOnlyClass: Keep as class for namespace grouping and discoverability\nexport class TraceContext {\n /**\n * HTTP header name for trace ID propagation\n */\n static TRACE_HEADER = 'X-Trace-Id';\n /**\n * Generate a new trace ID\n *\n * Format: \"tr_\" + 16 random hex characters\n * Example: \"tr_7f3a9b2c4e5d6f1a\"\n *\n * @returns Newly generated trace ID\n */\n static generate() {\n // Use crypto.randomUUID() for randomness, extract 16 hex chars\n const randomHex = crypto.randomUUID().replace(/-/g, '').substring(0, 16);\n return `tr_${randomHex}`;\n }\n /**\n * Extract trace ID from HTTP request headers\n *\n * @param headers Request headers\n * @returns Trace ID if present, null otherwise\n */\n static fromHeaders(headers) {\n return headers.get(TraceContext.TRACE_HEADER);\n }\n /**\n * Create headers object with trace ID for outgoing requests\n *\n * @param traceId Trace ID to include\n * @returns Headers object with X-Trace-Id set\n */\n static toHeaders(traceId) {\n return { [TraceContext.TRACE_HEADER]: traceId };\n }\n /**\n * Get the header name used for trace ID propagation\n *\n * @returns Header name (\"X-Trace-Id\")\n */\n static getHeaderName() {\n return TraceContext.TRACE_HEADER;\n }\n}\n","/**\n * Logger module\n *\n * Provides structured, trace-aware logging with:\n * - Explicit logger passing via constructor injection\n * - Three output modes: structured (Workers/DOs), json-line (container), pretty (local dev)\n * - Environment auto-detection\n * - Log level configuration\n *\n * Usage:\n *\n * ```typescript\n * // Create a logger at entry point\n * const logger = createLogger({ component: 'sandbox-do', traceId: 'tr_abc123' });\n *\n * // Pass to classes via constructor\n * const service = new MyService(logger);\n *\n * // Create child loggers for additional context\n * const execLogger = logger.child({ commandId: 'cmd-456' });\n * execLogger.info('Operation started');\n * ```\n */\nimport { CloudflareLogger } from './logger.js';\nimport { TraceContext } from './trace-context.js';\nimport { LogLevel as LogLevelEnum } from './types.js';\nexport { buildMessage, logCanonicalEvent, resolveLogLevel } from './canonical.js';\nexport { CloudflareLogger } from './logger.js';\nexport { TraceContext } from './trace-context.js';\nexport { LogLevel as LogLevelEnum } from './types.js';\n/**\n * Create a no-op logger for testing\n *\n * Returns a logger that implements the Logger interface but does nothing.\n * Useful for tests that don't need actual logging output.\n *\n * @returns No-op logger instance\n *\n * @example\n * ```typescript\n * // In tests\n * const client = new HttpClient({\n * baseUrl: 'http://test.com',\n * logger: createNoOpLogger() // Optional - tests can enable real logging if needed\n * });\n * ```\n */\nexport function createNoOpLogger() {\n return {\n debug: () => { },\n info: () => { },\n warn: () => { },\n error: () => { },\n child: () => createNoOpLogger()\n };\n}\n/**\n * Create a new logger instance\n *\n * @param context Base context for the logger. Must include 'component'.\n * TraceId will be auto-generated if not provided.\n * @returns New logger instance\n *\n * @example\n * ```typescript\n * // In Durable Object\n * const logger = createLogger({\n * component: 'sandbox-do',\n * traceId: TraceContext.fromHeaders(request.headers) || TraceContext.generate(),\n * sandboxId: this.id\n * });\n *\n * // In Container\n * const logger = createLogger({\n * component: 'container',\n * traceId: TraceContext.fromHeaders(request.headers)!,\n * sessionId: this.id\n * });\n * ```\n */\nexport function createLogger(context) {\n const minLevel = getLogLevelFromEnv();\n const outputMode = getOutputMode(context.component);\n const baseContext = {\n ...context,\n traceId: context.traceId || TraceContext.generate(),\n component: context.component,\n serviceVersion: context.serviceVersion || getEnvVar('SANDBOX_VERSION') || undefined,\n instanceId: context.instanceId ||\n getEnvVar('HOSTNAME') ||\n getEnvVar('SANDBOX_INSTANCE_ID') ||\n undefined\n };\n return new CloudflareLogger(baseContext, minLevel, outputMode);\n}\n/**\n * Get log level from environment variable\n *\n * Checks SANDBOX_LOG_LEVEL env var, falls back to default based on environment.\n * Default: 'debug' for development, 'info' for production\n */\nfunction getLogLevelFromEnv() {\n const envLevel = getEnvVar('SANDBOX_LOG_LEVEL') || 'info';\n switch (envLevel.toLowerCase()) {\n case 'debug':\n return LogLevelEnum.DEBUG;\n case 'info':\n return LogLevelEnum.INFO;\n case 'warn':\n return LogLevelEnum.WARN;\n case 'error':\n return LogLevelEnum.ERROR;\n default:\n // Invalid level, fall back to info\n return LogLevelEnum.INFO;\n }\n}\n/**\n * Determine output mode based on component and environment:\n * - SANDBOX_LOG_FORMAT=pretty → 'pretty' for all components (local wrangler dev)\n * - Container/Executor without pretty → 'json-line' (Bun stdout → Containers pipeline)\n * - Everything else without pretty → 'structured' (Workers/DOs → Workers Logs)\n *\n * In local dev, setting SANDBOX_LOG_FORMAT=pretty gives readable terminal\n * output on both the DO side and container side. In production (where the\n * var isn't set), DOs emit structured objects and containers emit single-line\n * JSON — both queryable by their respective observability pipelines.\n */\nfunction getOutputMode(component) {\n const format = getEnvVar('SANDBOX_LOG_FORMAT');\n if (format?.toLowerCase() === 'pretty') {\n return 'pretty';\n }\n if (component === 'container' || component === 'executor') {\n return 'json-line';\n }\n return 'structured';\n}\n/**\n * Get environment variable value\n *\n * Supports both Node.js (process.env) and Bun (Bun.env)\n */\nfunction getEnvVar(name) {\n // Try process.env first (Node.js / Bun)\n if (typeof process !== 'undefined' && process.env) {\n return process.env[name];\n }\n // Try Bun.env (Bun runtime)\n if (typeof Bun !== 'undefined') {\n const bunEnv = Bun.env;\n if (bunEnv) {\n return bunEnv[name];\n }\n }\n return undefined;\n}\n","/**\n * Escapes a string for safe use in shell commands using POSIX single-quote escaping.\n * Prevents command injection by wrapping the string in single quotes and escaping\n * any single quotes within the string.\n */\nexport function shellEscape(str) {\n return `'${str.replace(/'/g, \"'\\\\''\")}'`;\n}\n","/**\n * Shared SSE parsing utilities.\n *\n * Parses SSE frames from arbitrary text chunks while preserving partial state\n * across chunk boundaries.\n */\n/**\n * Parse SSE frames from a buffer.\n *\n * Returns parsed events, remaining unparsed text, and the current partial event\n * so callers can continue parsing on the next chunk.\n */\nexport function parseSSEFrames(buffer, currentEvent = { data: [] }) {\n const events = [];\n let i = 0;\n while (i < buffer.length) {\n const newlineIndex = buffer.indexOf('\\n', i);\n if (newlineIndex === -1)\n break;\n const rawLine = buffer.substring(i, newlineIndex);\n const line = rawLine.endsWith('\\r') ? rawLine.slice(0, -1) : rawLine;\n i = newlineIndex + 1;\n if (line === '' && currentEvent.data.length > 0) {\n events.push({\n event: currentEvent.event,\n data: currentEvent.data.join('\\n')\n });\n currentEvent = { data: [] };\n continue;\n }\n if (line.startsWith('event:')) {\n const value = line.startsWith('event: ')\n ? line.substring(7)\n : line.substring(6);\n currentEvent.event = value;\n continue;\n }\n if (line.startsWith('data:')) {\n const value = line.startsWith('data: ')\n ? line.substring(6)\n : line.substring(5);\n currentEvent.data.push(value);\n }\n }\n return {\n events,\n remaining: buffer.substring(i),\n currentEvent\n };\n}\n","/**\n * Check if a process status indicates the process has terminated\n */\nexport function isTerminalStatus(status) {\n return (status === 'completed' ||\n status === 'failed' ||\n status === 'killed' ||\n status === 'error');\n}\n// Type guards for runtime validation\nexport function isExecResult(value) {\n return (value &&\n typeof value.success === 'boolean' &&\n typeof value.exitCode === 'number' &&\n typeof value.stdout === 'string' &&\n typeof value.stderr === 'string');\n}\nexport function isProcess(value) {\n return (value &&\n typeof value.id === 'string' &&\n typeof value.command === 'string' &&\n typeof value.status === 'string');\n}\nexport function isProcessStatus(value) {\n return [\n 'starting',\n 'running',\n 'completed',\n 'failed',\n 'killed',\n 'error'\n ].includes(value);\n}\n// Re-export interpreter types for convenience\nexport { Execution, ResultImpl } from './interpreter-types';\n","/**\n * WebSocket transport protocol types\n *\n * Enables multiplexing HTTP-like requests over a single WebSocket connection.\n * This reduces sub-request count when running inside Workers/Durable Objects.\n *\n * Protocol:\n * - Client sends WSRequest messages\n * - Server responds with WSResponse messages (matched by id)\n * - For streaming endpoints, server sends multiple WSStreamChunk messages\n * followed by a final WSResponse\n */\n/**\n * Type guard for WSRequest\n *\n * Note: Only validates the discriminator field (type === 'request').\n * Does not validate other required fields (id, method, path).\n * Use for routing messages; trust TypeScript for field validation.\n */\nexport function isWSRequest(msg) {\n return (typeof msg === 'object' &&\n msg !== null &&\n 'type' in msg &&\n msg.type === 'request');\n}\n/**\n * Type guard for WSResponse\n *\n * Note: Only validates the discriminator field (type === 'response').\n */\nexport function isWSResponse(msg) {\n return (typeof msg === 'object' &&\n msg !== null &&\n 'type' in msg &&\n msg.type === 'response');\n}\n/**\n * Type guard for WSStreamChunk\n *\n * Note: Only validates the discriminator field (type === 'stream').\n */\nexport function isWSStreamChunk(msg) {\n return (typeof msg === 'object' &&\n msg !== null &&\n 'type' in msg &&\n msg.type === 'stream');\n}\n/**\n * Type guard for WSError\n *\n * Note: Only validates the discriminator field (type === 'error').\n */\nexport function isWSError(msg) {\n return (typeof msg === 'object' &&\n msg !== null &&\n 'type' in msg &&\n msg.type === 'error');\n}\n/**\n * Generate a unique request ID\n */\nexport function generateRequestId() {\n return `ws_${Date.now()}_${Math.random().toString(36).substring(2, 10)}`;\n}\n"],"mappings":";;;;;;;;AAOA,SAAgB,aAAa,KAAK,KAAK;CACnC,MAAM,QAAQ,MAAM;AACpB,QAAO,OAAO,UAAU,WAAW,QAAQ;;;;;;;;;;;;AAY/C,SAAgB,cAAc,SAAS;CACnC,MAAM,WAAW,EAAE;AACnB,MAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,QAAQ,CAC9C,KAAI,SAAS,QAAQ,OAAO,UAAU,SAClC,UAAS,OAAO;AAGxB,QAAO;;;;;;;;;;;;;;;;AAgBX,SAAgB,iBAAiB,SAAS;CACtC,MAAM,QAAQ,EAAE;CAChB,MAAM,UAAU,EAAE;AAClB,MAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,QAAQ,CAC9C,KAAI,SAAS,QAAQ,OAAO,UAAU,SAClC,OAAM,OAAO;KAGb,SAAQ,KAAK,IAAI;AAGzB,QAAO;EAAE;EAAO;EAAS;;;;;;;;;;;;;;;;AC5C7B,MAAM,mBAAmB;;;;;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OACV,IAAI,SAAS;;;;;;;AAOrB,SAAgB,UAAU,KAAK;AAC3B,QAAQ,OAAO,QAAQ,YACnB,QAAQ,QACR,UAAU,OACV,IAAI,SAAS;;;;;AAKrB,SAAgB,oBAAoB;AAChC,QAAO,MAAM,KAAK,KAAK,CAAC,GAAG,KAAK,QAAQ,CAAC,SAAS,GAAG,CAAC,UAAU,GAAG,GAAG"}
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { $ as FileStreamEvent, A as RequestConfig, At as CreateContextOptions, B as BackupOptions, C as CommandClient, Ct as WaitForPortOptions, D as ContainerStub, Dt as isProcessStatus, E as BaseApiResponse, Et as isProcess, F as SandboxInterpreterAPI, G as CheckChangesResult, H as BucketCredentials, I as TunnelInfo, J as ExecOptions, K as DirectoryBackup, L as TunnelOptions, M as SessionRequest, Mt as ExecutionResult, N as NamedTunnelInfo, Nt as RunCodeOptions, O as ErrorResponse, Ot as PtyOptions, P as QuickTunnelInfo, Q as FileMetadata, R as ExecuteRequest, S as WriteFileRequest, St as WaitForLogResult, T as BackupClient, Tt as isExecResult, U as BucketProvider, V as BaseExecOptions, W as CheckChangesOptions, X as ExecutionSession, Y as ExecResult, Z as FileChunk, _ as GitClient, _t as RestoreBackupResult, a as CommandsResponse, at as LogEvent, b as MkdirRequest, bt as SessionOptions, c as DeleteSessionRequest, ct as ProcessCleanupResult, d as UtilityClient, dt as ProcessListResult, et as FileWatchSSEEvent, f as ProcessClient, ft as ProcessLogsResult, g as GitCheckoutRequest, gt as RemoteMountBucketOptions, h as InterpreterClient, ht as ProcessStatus, i as SandboxClient, it as LocalMountBucketOptions, j as ResponseHandler, jt as Execution, k as HttpClientOptions, kt as CodeContext, l as DeleteSessionResponse, lt as ProcessInfoResult, m as ExecutionCallbacks, mt as ProcessStartResult, n as Sandbox, nt as ISandbox, o as CreateSessionRequest, ot as MountBucketOptions, p as PortClient, pt as ProcessOptions, q as ExecEvent, r as getSandbox, rt as ListFilesOptions, s as CreateSessionResponse, st as Process, t as ContainerProxy, tt as GitCheckoutResult, u as PingResponse, ut as ProcessKillResult, v as FileClient, vt as SandboxOptions, w as ExecuteResponse, wt as WatchOptions, x as ReadFileRequest, xt as StreamOptions, y as FileOperationRequest, yt as SandboxTransport, z as StartProcessRequest } from "./sandbox-BtaWcmmG.js";
1
+ import { $ as FileStreamEvent, A as RequestConfig, At as CreateContextOptions, B as BackupOptions, C as CommandClient, Ct as WaitForPortOptions, D as ContainerStub, Dt as isProcessStatus, E as BaseApiResponse, Et as isProcess, F as SandboxInterpreterAPI, G as CheckChangesResult, H as BucketCredentials, I as TunnelInfo, J as ExecOptions, K as DirectoryBackup, L as TunnelOptions, M as SessionRequest, Mt as ExecutionResult, N as NamedTunnelInfo, Nt as RunCodeOptions, O as ErrorResponse, Ot as PtyOptions, P as QuickTunnelInfo, Q as FileMetadata, R as ExecuteRequest, S as WriteFileRequest, St as WaitForLogResult, T as BackupClient, Tt as isExecResult, U as BucketProvider, V as BaseExecOptions, W as CheckChangesOptions, X as ExecutionSession, Y as ExecResult, Z as FileChunk, _ as GitClient, _t as RestoreBackupResult, a as CommandsResponse, at as LogEvent, b as MkdirRequest, bt as SessionOptions, c as DeleteSessionRequest, ct as ProcessCleanupResult, d as UtilityClient, dt as ProcessListResult, et as FileWatchSSEEvent, f as ProcessClient, ft as ProcessLogsResult, g as GitCheckoutRequest, gt as RemoteMountBucketOptions, h as InterpreterClient, ht as ProcessStatus, i as SandboxClient, it as LocalMountBucketOptions, j as ResponseHandler, jt as Execution, k as HttpClientOptions, kt as CodeContext, l as DeleteSessionResponse, lt as ProcessInfoResult, m as ExecutionCallbacks, mt as ProcessStartResult, n as Sandbox, nt as ISandbox, o as CreateSessionRequest, ot as MountBucketOptions, p as PortClient, pt as ProcessOptions, q as ExecEvent, r as getSandbox, rt as ListFilesOptions, s as CreateSessionResponse, st as Process, t as ContainerProxy, tt as GitCheckoutResult, u as PingResponse, ut as ProcessKillResult, v as FileClient, vt as SandboxOptions, w as ExecuteResponse, wt as WatchOptions, x as ReadFileRequest, xt as StreamOptions, y as FileOperationRequest, yt as SandboxTransport, z as StartProcessRequest } from "./sandbox-D-IV6AbV.js";
2
2
  import { _ as OperationType, a as ContainerUnavailableContext, d as ProcessExitedBeforeReadyContext, f as ProcessReadyTimeoutContext, g as ErrorResponse$1, h as SessionTerminatedContext, i as BackupRestoreContext, l as OperationInterruptedContext, m as RPCTransportErrorKind, n as BackupExpiredContext, o as ContainerUnavailableReason, p as RPCTransportContext, r as BackupNotFoundContext, s as InvalidBackupConfigContext, t as BackupCreateContext, u as OperationInterruptedReason, v as ErrorCode } from "./contexts-C186NnAB.js";
3
3
 
4
4
  //#region src/platform-errors.d.ts
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../src/platform-errors.ts","../src/errors/classes.ts","../src/file-stream.ts","../src/interpreter.ts","../src/pty/proxy.ts","../src/request-handler.ts","../src/sse-parser.ts","../src/storage-mount/errors.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;iBAgHgB,8BAAA;;;AC+MhB;;AAC2C,iBDnM3B,wBAAA,CCmM2B,KAAA,EAAA,OAAA,CAAA,EAAA,OAAA;;;;;AA9Q3C;;AAEiD,cAFpC,YAEoC,CAAA,WAFZ,MAEY,CAAA,MAAA,EAAA,OAAA,CAAA,CAAA,SAFqB,KAAA,CAErB;EAAd,SAAA,aAAA,EAAA,eAAA,CAAc,QAAd,CAAA;EAAc,WAAA,CAAA,aAAA,EAAd,eAAc,CAAA,QAAA,CAAA,EAAA,OAAD,CAAC,EAAA;IAAd,KAAA,CAAA,EAAA,OAAA;EAAa,CAAA;EAiBnC,IAAA,IAAA,CAAA,CAAA,EAjBmC,SAiBnC;EAAA,IAAA,OAAA,CAAA,CAAA,EAAA,QAAA;EAME,IAAA,UAAA,CAAA,CAAA,EAAA,MAAA;mBANF,aAAA;;EAnByD,IAAA,SAAA,CAAA,CAAA,EAAA,MAAA;EAAK,IAAA,aAAA,CAAA,CAAA,E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A;;;;;;AAEuB,iBKmDzB,uBLnDyB,CAAA,CAAA,CAAA,CAAA,QAAA,EKoDpC,QLpDoC,EAAA,MAAA,CAAA,EKqDrC,WLrDqC,CAAA,EKsD7C,aLtD6C,CKsD/B,CLtD+B,CAAA;;;;;;;AAF2B,iBK4E3D,wBL5E2D,CAAA,CAAA,CAAA,CAAA,MAAA,EK6EjE,aL7EiE,CK6EnD,CL7EmD,CAAA,EAAA,OA8QhC,CA9QgC,EAAA;EA6Q9D,MAAA,CAAA,EK9LA,WL8LA;EAA4C,SAAA,CAAA,EAAA,CAAA,KAAA,EK7LjC,CL6LiC,EAAA,GAAA,MAAA;CACd,CAAA,EK5LxC,cL4LwC,CK5LzB,UL4LyB,CAAA;;;;AA9Q3C;;AAEiD,cMvCpC,gBAAA,SAAyB,KAAA,CNuCW;EAAd,SAAA,IAAA,EMtCX,SNsCW;EAAc,WAAA,CAAA,OAAA,EAAA,MAAA,EAAA,IAAA,CAAA,EMpCZ,SNoCY;;;;;AAuBlC,cMjDF,cAAA,SAAuB,gBAAA,CNiDrB;;;;;AAoPf;AAAyD,cM3R5C,kBAAA,SAA2B,gBAAA,CN2RiB;EACd,WAAA,CAAA,OAAA,EAAA,MAAA;;;;AA4X3C;AAA2D,cM9oB9C,uBAAA,SAAgC,gBAAA,CN8oBc;EAChB,WAAA,CAAA,OAAA,EAAA,MAAA;;;;AAuB3C;AAAgE,cM5pBnD,uBAAA,SAAgC,gBAAA,CN4pBmB;EACrB,WAAA,CAAA,OAAA,EAAA,MAAA"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../src/platform-errors.ts","../src/errors/classes.ts","../src/file-stream.ts","../src/interpreter.ts","../src/pty/proxy.ts","../src/request-handler.ts","../src/sse-parser.ts","../src/storage-mount/errors.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;iBAgHgB,8BAAA;;;AC+MhB;;AAC2C,iBDnM3B,wBAAA,CCmM2B,KAAA,EAAA,OAAA,CAAA,EAAA,OAAA;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AA,OAAA,EAAA,MAAA;;;;AA4X3C;AAA2D,cM9oB9C,uBAAA,SAAgC,gBAAA,CN8oBc;EAChB,WAAA,CAAA,OAAA,EAAA,MAAA;;;;AAuB3C;AAAgE,cM5pBnD,uBAAA,SAAgC,gBAAA,CN4pBmB;EACrB,WAAA,CAAA,OAAA,EAAA,MAAA"}
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
- import { a as isExecResult, f as TraceContext, o as isProcess, s as isProcessStatus, u as createLogger } from "./dist-B_eXrP83.js";
1
+ import { a as isExecResult, f as TraceContext, o as isProcess, s as isProcessStatus, u as createLogger } from "./dist-C3AQh4A0.js";
2
2
  import "./errors-CpkKPbWC.js";
3
- import { A as PortClient, B as InvalidBackupConfigError, C as collectFile, D as SandboxClient, E as isPlatformTransientError, F as BackupCreateError, G as SessionTerminatedError, H as ProcessExitedBeforeReadyError, I as BackupExpiredError, L as BackupNotFoundError, M as FileClient, N as CommandClient, O as UtilityClient, P as BackupClient, R as BackupRestoreError, T as isDurableObjectCodeUpdateReset, U as ProcessReadyTimeoutError, V as OperationInterruptedError, W as RPCTransportError, _ as responseToAsyncIterable, a as PREVIEW_PROXY_HEADER, b as sanitizeSandboxId, c as PREVIEW_PROXY_SANDBOX_ID_HEADER, d as BucketUnmountError, f as InvalidMountConfigError, g as parseSSEStream, h as asyncIterableToSSEStream, i as proxyTerminal, j as GitClient, k as ProcessClient, l as PREVIEW_PROXY_TOKEN_HEADER, m as S3FSMountError, n as Sandbox, o as PREVIEW_PROXY_HEADERS, p as MissingCredentialsError, r as getSandbox, s as PREVIEW_PROXY_PORT_HEADER, t as ContainerProxy, u as BucketMountError, v as CodeInterpreter, w as streamFile, x as validatePort, z as ContainerUnavailableError } from "./sandbox-D0rNqxlr.js";
3
+ import { A as PortClient, B as InvalidBackupConfigError, C as collectFile, D as SandboxClient, E as isPlatformTransientError, F as BackupCreateError, G as SessionTerminatedError, H as ProcessExitedBeforeReadyError, I as BackupExpiredError, L as BackupNotFoundError, M as FileClient, N as CommandClient, O as UtilityClient, P as BackupClient, R as BackupRestoreError, T as isDurableObjectCodeUpdateReset, U as ProcessReadyTimeoutError, V as OperationInterruptedError, W as RPCTransportError, _ as responseToAsyncIterable, a as PREVIEW_PROXY_HEADER, b as sanitizeSandboxId, c as PREVIEW_PROXY_SANDBOX_ID_HEADER, d as BucketUnmountError, f as InvalidMountConfigError, g as parseSSEStream, h as asyncIterableToSSEStream, i as proxyTerminal, j as GitClient, k as ProcessClient, l as PREVIEW_PROXY_TOKEN_HEADER, m as S3FSMountError, n as Sandbox, o as PREVIEW_PROXY_HEADERS, p as MissingCredentialsError, r as getSandbox, s as PREVIEW_PROXY_PORT_HEADER, t as ContainerProxy, u as BucketMountError, v as CodeInterpreter, w as streamFile, x as validatePort, z as ContainerUnavailableError } from "./sandbox-DKbJiquI.js";
4
4
 
5
5
  //#region src/request-handler.ts
6
6
  function createProxyLogger(request) {
@@ -1,4 +1,4 @@
1
- import { n as Sandbox } from "../sandbox-BtaWcmmG.js";
1
+ import { n as Sandbox } from "../sandbox-D-IV6AbV.js";
2
2
  import { ApplyPatchOperation, ApplyPatchResult, Editor as Editor$1, Shell as Shell$1, ShellAction, ShellResult } from "@openai/agents";
3
3
 
4
4
  //#region src/openai/index.d.ts
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/openai/index.ts"],"sourcesContent":[],"mappings":";;;;;AAyBiB,UATA,aAAA,CASmB;EA2CvB,OAAA,EAAM,MAAA;EAED,MAAA,EAAA,MAAA;EAGsB,MAAA,EAAA,MAAA;EAOpB,QAAA,EAAA,MAAA,GAAA,IAAA;EAAsB,SAAA,EAAA,MAAA;;AAZZ,UA3Cb,mBAAA,CA2Ca;EAAW,SAAA,EAAA,QAAA,GAAA,QAAA,GAAA,QAAA;EAyI5B,IAAA,EAAA,MAAO;EACF,MAAA,EAAA,WAAA,GAAA,QAAA;EAIY,MAAA,EAAA,MAAA;EAaP,KAAA,CAAA,EAAA,MA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1
+ import { u as createLogger } from "../dist-C3AQh4A0.js";
2
2
  import { applyDiff } from "@openai/agents";
3
3
 
4
4
  //#region src/openai/index.ts
@@ -37,15 +37,12 @@ var Shell = class {
37
37
  }
38
38
  async run(action) {
39
39
  this.logger.debug("SandboxShell.run called", {
40
- commands: action.commands,
40
+ commandCount: action.commands.length,
41
41
  timeout: action.timeoutMs
42
42
  });
43
43
  const output = [];
44
44
  for (const command of action.commands) {
45
- this.logger.debug("Executing command", {
46
- command,
47
- cwd: this.cwd
48
- });
45
+ this.logger.debug("Executing command", { cwd: this.cwd });
49
46
  let stdout = "";
50
47
  let stderr = "";
51
48
  let exitCode = 0;
@@ -66,20 +63,13 @@ var Shell = class {
66
63
  exitCode
67
64
  };
68
65
  this.logger.debug("Command executed successfully", {
69
- command,
70
66
  exitCode,
71
67
  stdoutLength: stdout.length,
72
68
  stderrLength: stderr.length
73
69
  });
74
- if (exitCode !== 0) this.logger.warn(`Command failed with exit code ${exitCode}`, {
75
- command,
76
- stderr
77
- });
78
- else if (stderr) this.logger.warn(`Command produced stderr output`, {
79
- command,
80
- stderr
81
- });
82
- else this.logger.info(`Command completed successfully`, { command });
70
+ if (exitCode !== 0) this.logger.warn(`Command failed with exit code ${exitCode}`, { stderrLength: stderr.length });
71
+ else if (stderr) this.logger.warn(`Command produced stderr output`, { stderrLength: stderr.length });
72
+ else this.logger.info(`Command completed successfully`);
83
73
  } catch (error) {
84
74
  const errorObj = isErrorWithProperties(error) ? error : {};
85
75
  exitCode = typeof errorObj.exitCode === "number" ? errorObj.exitCode : null;
@@ -87,17 +77,10 @@ var Shell = class {
87
77
  stderr = typeof errorObj.stderr === "string" ? errorObj.stderr : "";
88
78
  const errorMessage = getErrorMessage(error);
89
79
  if (errorMessage.includes("timeout") || errorMessage.includes("Timeout") || errorMessage.includes("timed out")) {
90
- this.logger.error(`Command timed out`, void 0, {
91
- command,
92
- timeout: action.timeoutMs
93
- });
80
+ this.logger.error(`Command timed out`, void 0, { timeout: action.timeoutMs });
94
81
  outcome = { type: "timeout" };
95
82
  } else {
96
- this.logger.error(`Error executing command`, toError(error), {
97
- command,
98
- error: errorMessage || error,
99
- exitCode
100
- });
83
+ this.logger.error(`Error executing command`, toError(error), { exitCode });
101
84
  outcome = {
102
85
  type: "exit",
103
86
  exitCode: exitCode ?? 1
@@ -120,7 +103,6 @@ var Shell = class {
120
103
  timestamp
121
104
  });
122
105
  this.logger.debug("Result collected", {
123
- command,
124
106
  exitCode: collectedExitCode,
125
107
  timestamp
126
108
  });
@@ -204,10 +186,7 @@ var Editor = class {
204
186
  timestamp
205
187
  };
206
188
  this.results.push(result);
207
- this.logger.error("Failed to create file", toError(error), {
208
- path: operation.path,
209
- error: errorMessage
210
- });
189
+ this.logger.error("Failed to create file", void 0, { path: operation.path });
211
190
  throw error;
212
191
  }
213
192
  }
@@ -279,10 +258,7 @@ var Editor = class {
279
258
  timestamp
280
259
  };
281
260
  this.results.push(result);
282
- this.logger.error("Failed to update file", toError(error), {
283
- path: operation.path,
284
- error: errorMessage
285
- });
261
+ this.logger.error("Failed to update file", void 0, { path: operation.path });
286
262
  throw error;
287
263
  }
288
264
  }
@@ -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,SA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AAO,GAAG;;EAIlD,MAAM,aAAa,cAAc,QAAQ,SAAS,GAAG,CAAC,QAAQ,OAAO,GAAG;EAOxE,MAAM,YANW,aAAa,GAAG,KAAK,KAAK,GAAG,eAAe,KAAK,MAGpB,QAAQ,QAAQ,IAAI,CAI/D,MAAM,IAAI,CACV,QAAQ,MAAM,KAAK,MAAM,IAAI;EAChC,MAAME,QAAkB,EAAE;AAE1B,OAAK,MAAM,WAAW,SACpB,KAAI,YAAY,MAAM;AACpB,OAAI,MAAM,WAAW,EACnB,OAAM,IAAI,MAAM,gCAAgC,eAAe;AAEjE,SAAM,KAAK;QAEX,OAAM,KAAK,QAAQ;EAIvB,MAAM,iBAAiB,IAAI,MAAM,KAAK,IAAI;AAG1C,MAAI,CAAC,eAAe,WAAW,KAAK,KAAK,CACvC,OAAM,IAAI,MAAM,gCAAgC,eAAe;AAGjE,SAAO;;CAGT,AAAQ,WAAW,UAA0B;EAC3C,MAAM,YAAY,SAAS,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,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AOxE,MAAM,YANW,aAAa,GAAG,KAAK,KAAK,GAAG,eAAe,KAAK,MAGpB,QAAQ,QAAQ,IAAI,CAI/D,MAAM,IAAI,CACV,QAAQ,MAAM,KAAK,MAAM,IAAI;EAChC,MAAME,QAAkB,EAAE;AAE1B,OAAK,MAAM,WAAW,SACpB,KAAI,YAAY,MAAM;AACpB,OAAI,MAAM,WAAW,EACnB,OAAM,IAAI,MAAM,gCAAgC,eAAe;AAEjE,SAAM,KAAK;QAEX,OAAM,KAAK,QAAQ;EAIvB,MAAM,iBAAiB,IAAI,MAAM,KAAK,IAAI;AAG1C,MAAI,CAAC,eAAe,WAAW,KAAK,KAAK,CACvC,OAAM,IAAI,MAAM,gCAAgC,eAAe;AAGjE,SAAO;;CAGT,AAAQ,WAAW,UAA0B;EAC3C,MAAM,YAAY,SAAS,YAAY,IAAI;AAC3C,MAAI,cAAc,GAChB,QAAO;AAET,SAAO,SAAS,UAAU,GAAG,UAAU,IAAI"}
@@ -1,4 +1,4 @@
1
- import { n as Sandbox } from "../sandbox-BtaWcmmG.js";
1
+ import { n as Sandbox } from "../sandbox-D-IV6AbV.js";
2
2
  import { c as OpencodeStartupContext } from "../contexts-C186NnAB.js";
3
3
  import { OpencodeClient } from "@opencode-ai/sdk/v2/client";
4
4
  import { Config } from "@opencode-ai/sdk/v2";
@@ -1,4 +1,4 @@
1
- import { u as createLogger } from "../dist-B_eXrP83.js";
1
+ import { u as createLogger } from "../dist-C3AQh4A0.js";
2
2
  import { r as ErrorCode } from "../errors-CpkKPbWC.js";
3
3
 
4
4
  //#region src/opencode/types.ts
@@ -1226,9 +1226,13 @@ interface BackupOptions {
1226
1226
  gitignore?: boolean;
1227
1227
  /**
1228
1228
  * Glob patterns to exclude from the backup.
1229
- * These are passed directly to mksquashfs as wildcard exclude patterns.
1229
+ * A single-component pattern, such as `node_modules`, `dist/`, or `*.log`,
1230
+ * matches at any depth. A multi-component pattern, such as `build/output`,
1231
+ * matches only relative to `dir`. mksquashfs does not support `**`, so `**`
1232
+ * components are removed and do not make a multi-component pattern match at
1233
+ * any depth.
1230
1234
  *
1231
- * @example ['node_modules', '*.log', '.cache']
1235
+ * @example ['node_modules', '*.log', '.cache', 'build/output']
1232
1236
  */
1233
1237
  excludes?: string[];
1234
1238
  /**
@@ -1607,7 +1611,9 @@ interface SandboxFilesAPI {
1607
1611
  readFile(path: string, sessionId: string, options?: {
1608
1612
  encoding?: Exclude<FileEncoding, 'none'>;
1609
1613
  }): Promise<ReadFileResult>;
1610
- readFileStream(path: string, sessionId: string): Promise<ReadableStream<Uint8Array>>;
1614
+ readFileStream(path: string, sessionId: string, options?: {
1615
+ encoding?: 'base64';
1616
+ }): Promise<ReadableStream<Uint8Array>>;
1611
1617
  writeFile(path: string, content: string, sessionId: string, options?: {
1612
1618
  encoding?: string;
1613
1619
  permissions?: string;
@@ -2188,8 +2194,11 @@ declare class FileClient extends BaseHttpClient implements SandboxFilesAPI {
2188
2194
  * Returns a ReadableStream of SSE events containing metadata, chunks, and completion
2189
2195
  * @param path - File path to stream
2190
2196
  * @param sessionId - The session ID for this operation
2197
+ * @param options - Optional stream encoding; base64 preserves arbitrary bytes
2191
2198
  */
2192
- readFileStream(path: string, sessionId: string): Promise<ReadableStream<Uint8Array>>;
2199
+ readFileStream(path: string, sessionId: string, options?: {
2200
+ encoding?: 'base64';
2201
+ }): Promise<ReadableStream<Uint8Array>>;
2193
2202
  /**
2194
2203
  * Delete a file
2195
2204
  * @param path - File path to delete
@@ -3675,4 +3684,4 @@ declare class Sandbox<Env = unknown> extends Container<Env> implements ISandbox
3675
3684
  }
3676
3685
  //#endregion
3677
3686
  export { FileStreamEvent as $, RequestConfig as A, CreateContextOptions as At, BackupOptions as B, CommandClient as C, WaitForPortOptions as Ct, ContainerStub as D, isProcessStatus as Dt, BaseApiResponse as E, isProcess as Et, SandboxInterpreterAPI as F, CheckChangesResult as G, BucketCredentials as H, TunnelInfo as I, ExecOptions as J, DirectoryBackup as K, TunnelOptions as L, SessionRequest as M, ExecutionResult as Mt, NamedTunnelInfo as N, RunCodeOptions as Nt, ErrorResponse as O, PtyOptions as Ot, QuickTunnelInfo as P, FileMetadata as Q, ExecuteRequest as R, WriteFileRequest as S, WaitForLogResult as St, BackupClient as T, isExecResult as Tt, BucketProvider as U, BaseExecOptions as V, CheckChangesOptions as W, ExecutionSession as X, ExecResult as Y, FileChunk as Z, GitClient as _, RestoreBackupResult as _t, CommandsResponse as a, LogEvent as at, MkdirRequest as b, SessionOptions as bt, DeleteSessionRequest as c, ProcessCleanupResult as ct, UtilityClient as d, ProcessListResult as dt, FileWatchSSEEvent as et, ProcessClient as f, ProcessLogsResult as ft, GitCheckoutRequest as g, RemoteMountBucketOptions as gt, InterpreterClient as h, ProcessStatus as ht, SandboxClient as i, LocalMountBucketOptions as it, ResponseHandler as j, Execution as jt, HttpClientOptions as k, CodeContext as kt, DeleteSessionResponse as l, ProcessInfoResult as lt, ExecutionCallbacks as m, ProcessStartResult as mt, Sandbox as n, ISandbox as nt, CreateSessionRequest as o, MountBucketOptions as ot, PortClient as p, ProcessOptions as pt, ExecEvent as q, getSandbox as r, ListFilesOptions as rt, CreateSessionResponse as s, Process as st, ContainerProxy$1 as t, GitCheckoutResult as tt, PingResponse as u, ProcessKillResult as ut, FileClient as v, SandboxOptions as vt, ExecuteResponse as w, WatchOptions as wt, ReadFileRequest as x, StreamOptions as xt, FileOperationRequest as y, SandboxTransport as yt, StartProcessRequest as z };
3678
- //# sourceMappingURL=sandbox-BtaWcmmG.d.ts.map
3687
+ //# sourceMappingURL=sandbox-D-IV6AbV.d.ts.map