@librechat/agents 3.2.41 → 3.2.42

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/dist/cjs/agents/AgentContext.cjs.map +1 -1
  2. package/dist/cjs/graphs/Graph.cjs +4 -1
  3. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  4. package/dist/cjs/llm/bedrock/index.cjs +9 -1
  5. package/dist/cjs/llm/bedrock/index.cjs.map +1 -1
  6. package/dist/cjs/main.cjs +4 -0
  7. package/dist/cjs/messages/cache.cjs +21 -0
  8. package/dist/cjs/messages/cache.cjs.map +1 -1
  9. package/dist/cjs/tools/cloudflare/CloudflareProgrammaticToolCalling.cjs +2 -2
  10. package/dist/cjs/tools/cloudflare/CloudflareProgrammaticToolCalling.cjs.map +1 -1
  11. package/dist/cjs/tools/cloudflare/CloudflareSandboxExecutionEngine.cjs +87 -7
  12. package/dist/cjs/tools/cloudflare/CloudflareSandboxExecutionEngine.cjs.map +1 -1
  13. package/dist/esm/agents/AgentContext.mjs.map +1 -1
  14. package/dist/esm/graphs/Graph.mjs +5 -2
  15. package/dist/esm/graphs/Graph.mjs.map +1 -1
  16. package/dist/esm/llm/bedrock/index.mjs +10 -2
  17. package/dist/esm/llm/bedrock/index.mjs.map +1 -1
  18. package/dist/esm/main.mjs +3 -3
  19. package/dist/esm/messages/cache.mjs +21 -1
  20. package/dist/esm/messages/cache.mjs.map +1 -1
  21. package/dist/esm/tools/cloudflare/CloudflareProgrammaticToolCalling.mjs +3 -3
  22. package/dist/esm/tools/cloudflare/CloudflareProgrammaticToolCalling.mjs.map +1 -1
  23. package/dist/esm/tools/cloudflare/CloudflareSandboxExecutionEngine.mjs +85 -8
  24. package/dist/esm/tools/cloudflare/CloudflareSandboxExecutionEngine.mjs.map +1 -1
  25. package/dist/types/llm/bedrock/index.d.ts +7 -0
  26. package/dist/types/messages/cache.d.ts +17 -0
  27. package/dist/types/tools/cloudflare/CloudflareSandboxExecutionEngine.d.ts +44 -0
  28. package/package.json +1 -1
  29. package/src/agents/AgentContext.ts +2 -0
  30. package/src/graphs/Graph.ts +17 -5
  31. package/src/llm/bedrock/index.ts +18 -2
  32. package/src/llm/bedrock/llm.spec.ts +97 -0
  33. package/src/messages/cache.test.ts +31 -0
  34. package/src/messages/cache.ts +25 -0
  35. package/src/tools/__tests__/CloudflareSandboxExecution.test.ts +131 -0
  36. package/src/tools/cloudflare/CloudflareProgrammaticToolCalling.ts +7 -2
  37. package/src/tools/cloudflare/CloudflareSandboxExecutionEngine.ts +165 -9
@@ -1 +1 @@
1
- {"version":3,"file":"CloudflareProgrammaticToolCalling.mjs","names":[],"sources":["../../../../src/tools/cloudflare/CloudflareProgrammaticToolCalling.ts"],"sourcesContent":["import { tool } from '@langchain/core/tools';\nimport type { DynamicStructuredTool } from '@langchain/core/tools';\nimport type * as t from '@/types';\n\n/* eslint-disable no-useless-escape -- generated sandbox helper source needs escapes for emitted JS/Python string literals. */\nimport {\n formatCompletedResponse,\n normalizeToPythonIdentifier,\n ProgrammaticToolCallingDescription,\n ProgrammaticToolCallingName,\n ProgrammaticToolCallingSchema,\n filterToolsByUsage,\n} from '@/tools/ProgrammaticToolCalling';\nimport {\n BashProgrammaticToolCallingDescription,\n BashProgrammaticToolCallingSchema,\n filterBashToolsByUsage,\n normalizeToBashIdentifier,\n} from '@/tools/BashProgrammaticToolCalling';\nimport { Constants } from '@/common';\nimport {\n executeCloudflareCode,\n getCloudflareWorkspaceRoot,\n resolveCloudflareSandbox,\n validateCloudflareBashCommand,\n} from './CloudflareSandboxExecutionEngine';\n\ntype ProgrammaticParams = {\n code: string;\n timeout?: number;\n lang?: string;\n runtime?: string;\n language?: string;\n};\n\nconst DEFAULT_TIMEOUT = 60000;\nconst MIN_TIMEOUT = 1000;\nconst MAX_TIMEOUT = 300000;\nconst DEFAULT_MAX_OUTPUT_CHARS = 200000;\n\ntype TimeoutSchema = {\n type: 'integer';\n minimum: number;\n maximum: number;\n default: number;\n description: string;\n};\n\ntype CloudflareProgrammaticToolCallingJsonSchema = {\n type: 'object';\n properties: typeof ProgrammaticToolCallingSchema.properties & {\n timeout: TimeoutSchema;\n lang: {\n type: 'string';\n enum: readonly ['py', 'python', 'bash', 'sh'];\n default: 'bash';\n description: string;\n };\n };\n required: readonly ['code'];\n};\n\ntype CloudflareBashProgrammaticToolCallingJsonSchema = {\n type: 'object';\n properties: typeof BashProgrammaticToolCallingSchema.properties & {\n timeout: TimeoutSchema;\n };\n required: readonly ['code'];\n};\n\nconst NATIVE_TOOL_NAMES = new Set<string>([\n Constants.READ_FILE,\n Constants.WRITE_FILE,\n Constants.EDIT_FILE,\n Constants.GREP_SEARCH,\n Constants.GLOB_SEARCH,\n Constants.LIST_DIRECTORY,\n Constants.COMPILE_CHECK,\n Constants.BASH_TOOL,\n Constants.EXECUTE_CODE,\n]);\n\nfunction normalizeTimeout(timeoutMs: number | undefined): number {\n if (timeoutMs == null || !Number.isFinite(timeoutMs)) {\n return DEFAULT_TIMEOUT;\n }\n return Math.max(MIN_TIMEOUT, Math.floor(timeoutMs));\n}\n\nfunction formatTimeout(timeoutMs: number): string {\n return timeoutMs % 1000 === 0\n ? `${timeoutMs / 1000} seconds`\n : `${timeoutMs} milliseconds`;\n}\n\nfunction createTimeoutSchema(timeoutMs?: number): TimeoutSchema {\n const defaultTimeout = normalizeTimeout(timeoutMs);\n const maxTimeout = Math.max(MAX_TIMEOUT, defaultTimeout);\n return {\n type: 'integer',\n minimum: MIN_TIMEOUT,\n maximum: maxTimeout,\n default: defaultTimeout,\n description:\n 'Maximum Cloudflare Sandbox execution time in milliseconds. ' +\n `Default: ${formatTimeout(defaultTimeout)}. Max: ${formatTimeout(maxTimeout)}.`,\n };\n}\n\nfunction clampExecutionTimeout(\n requestedTimeoutMs: number | undefined,\n configuredTimeoutMs: number | undefined\n): number {\n const defaultTimeout = normalizeTimeout(configuredTimeoutMs);\n const maxTimeout = Math.max(MAX_TIMEOUT, defaultTimeout);\n if (requestedTimeoutMs == null || !Number.isFinite(requestedTimeoutMs)) {\n return defaultTimeout;\n }\n return Math.min(\n Math.max(MIN_TIMEOUT, Math.floor(requestedTimeoutMs)),\n maxTimeout\n );\n}\n\nfunction quoteShell(value: string): string {\n if (/^[A-Za-z0-9_/:=.,@%+-]+$/.test(value)) {\n return value;\n }\n const escapedQuote = String.raw`'\\''`;\n return `'${value.replace(/'/g, escapedQuote)}'`;\n}\n\nfunction truncateOutput(\n value: string,\n maxChars = DEFAULT_MAX_OUTPUT_CHARS\n): string {\n if (value.length <= maxChars) {\n return value;\n }\n const head = Math.floor(maxChars * 0.6);\n const tail = maxChars - head;\n const omitted = value.length - maxChars;\n return `${value.slice(0, head)}\\n\\n[... ${omitted} characters truncated ...]\\n\\n${value.slice(\n value.length - tail\n )}`;\n}\n\nfunction withInSandboxTimeout(command: string, timeoutMs: number): string {\n const timeoutSeconds = Math.max(1, Math.ceil(timeoutMs / 1000));\n return `timeout -k 2s ${timeoutSeconds}s ${command}`;\n}\n\nfunction outerTimeoutMs(timeoutMs: number): number {\n return timeoutMs + 5000;\n}\n\nfunction isInSandboxTimeoutExit(exitCode: number | null): boolean {\n return exitCode === 124 || exitCode === 137;\n}\n\nasync function executeGeneratedCloudflareBash(\n command: string,\n config: t.CloudflareSandboxExecutionConfig\n): ReturnType<typeof executeCloudflareCode> {\n const sandbox = await resolveCloudflareSandbox(config);\n const workspaceRoot = getCloudflareWorkspaceRoot(config);\n const shell = config.shell ?? 'bash';\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT;\n const result = await sandbox.exec(\n withInSandboxTimeout(`${shell} -lc ${quoteShell(command)}`, timeoutMs),\n {\n cwd: workspaceRoot,\n env: config.env,\n timeout: outerTimeoutMs(timeoutMs),\n }\n );\n const maxOutputChars = config.maxOutputChars ?? DEFAULT_MAX_OUTPUT_CHARS;\n return {\n stdout: truncateOutput(result.stdout, maxOutputChars),\n stderr: truncateOutput(result.stderr, maxOutputChars),\n exitCode: result.exitCode,\n timedOut: isInSandboxTimeoutExit(result.exitCode),\n };\n}\n\nfunction createCloudflareProgrammaticToolCallingSchema(\n config: t.CloudflareSandboxExecutionConfig\n): CloudflareProgrammaticToolCallingJsonSchema {\n return {\n ...ProgrammaticToolCallingSchema,\n properties: {\n ...ProgrammaticToolCallingSchema.properties,\n timeout: createTimeoutSchema(config.timeoutMs),\n lang: {\n type: 'string',\n enum: ['py', 'python', 'bash', 'sh'],\n default: 'bash',\n description:\n 'Cloudflare Sandbox runtime for orchestration code. Defaults to bash; use py/python for Python orchestration.',\n },\n },\n } as const;\n}\n\nfunction createCloudflareBashProgrammaticToolCallingSchema(\n config: t.CloudflareSandboxExecutionConfig\n): CloudflareBashProgrammaticToolCallingJsonSchema {\n return {\n ...BashProgrammaticToolCallingSchema,\n properties: {\n ...BashProgrammaticToolCallingSchema.properties,\n timeout: createTimeoutSchema(config.timeoutMs),\n },\n } as const;\n}\n\nfunction resolveRuntime(params: ProgrammaticParams): 'python' | 'bash' {\n const raw = params.lang ?? params.runtime ?? params.language ?? 'bash';\n return raw === 'py' || raw === 'python' ? 'python' : 'bash';\n}\n\nfunction filterNativeTools(\n toolDefs: t.LCTool[],\n code: string,\n runtime: 'python' | 'bash'\n): t.LCTool[] {\n const nativeDefs = toolDefs.filter((def) => NATIVE_TOOL_NAMES.has(def.name));\n const filter =\n runtime === 'bash' ? filterBashToolsByUsage : filterToolsByUsage;\n return filter(nativeDefs, code);\n}\n\nfunction indent(code: string, spaces = 4): string {\n const prefix = ' '.repeat(spaces);\n return code\n .split('\\n')\n .map((line) => (line === '' ? line : prefix + line))\n .join('\\n');\n}\n\nfunction pythonBoolean(value: boolean | undefined): 'True' | 'False' {\n return value === true ? 'True' : 'False';\n}\n\nfunction createPythonNativeToolSource(\n config: t.CloudflareSandboxExecutionConfig,\n workspaceRoot: string\n): string {\n return `\nimport asyncio, fnmatch, glob, json, os, pathlib, re, shlex, shutil, subprocess, sys, tempfile\n\nWORKSPACE = ${JSON.stringify(workspaceRoot)}\nSHELL = ${JSON.stringify(config.shell ?? 'bash')}\nREAD_ONLY = ${pythonBoolean(config.readOnly)}\nALLOW_DANGEROUS_COMMANDS = ${pythonBoolean(config.allowDangerousCommands)}\nDESTRUCTIVE_TARGET = r\"(?:/|~|\\\\$\\\\{?HOME\\\\}?|\\\\.)(?:/?\\\\.?\\\\*|/)?\"\nDANGEROUS_COMMAND_PATTERNS = [\n re.compile(r\"\\\\brm\\\\s+(?:-[^\\\\s]*[rf][^\\\\s]*\\\\s+|-[^\\\\s]*[r][^\\\\s]*\\\\s+-[^\\\\s]*[f][^\\\\s]*\\\\s+)(?:--\\\\s+)?\" + DESTRUCTIVE_TARGET + r\"\\\\s*(?:$|[;&|])\"),\n re.compile(r\"\\\\b(?:mkfs|mkswap|fdisk|parted|diskutil)\\\\b\"),\n re.compile(r\"\\\\bdd\\\\s+[^;&|]*\\\\bof=/dev/\"),\n re.compile(r\"\\\\bchmod\\\\s+-R\\\\s+(?:777|a\\\\+w)\\\\s+(?:--\\\\s+)?\" + DESTRUCTIVE_TARGET + r\"(?:$|\\\\s|[;&|])\"),\n re.compile(r\"\\\\bchown\\\\s+-R\\\\s+[^;&|]+\\\\s+(?:--\\\\s+)?\" + DESTRUCTIVE_TARGET + r\"(?:$|\\\\s|[;&|])\"),\n re.compile(r\":\\\\s*\\\\(\\\\s*\\\\)\\\\s*\\\\{\\\\s*:\\\\s*\\\\|\\\\s*:\\\\s*&\\\\s*\\\\}\\\\s*;\\\\s*:\"),\n]\nQUOTED_DESTRUCTIVE_PATTERNS = [\n re.compile(r\"\\\\brm\\\\s+(?:-[^\\\\s]*[rf][^\\\\s]*\\\\s+){1,3}(?:--\\\\s+)?[\\\\\"']\" + DESTRUCTIVE_TARGET + r\"[\\\\\"']\"),\n re.compile(r\"\\\\bchmod\\\\s+-R\\\\s+(?:777|a\\\\+w)\\\\s+(?:--\\\\s+)?[\\\\\"']\" + DESTRUCTIVE_TARGET + r\"[\\\\\"']\"),\n re.compile(r\"\\\\bchown\\\\s+-R\\\\s+[^;&|]+\\\\s+(?:--\\\\s+)?[\\\\\"']\" + DESTRUCTIVE_TARGET + r\"[\\\\\"']\"),\n]\nNESTED_SHELL_PREFIX = r\"(?:(?:ba|z|da|k)?sh|eval)\\\\s+(?:-l?c\\\\s+)?\"\nNESTED_SHELL_DESTRUCTIVE_PATTERNS = [\n re.compile(NESTED_SHELL_PREFIX + r\"[\\\\\"'][^\\\\\"']*\\\\brm\\\\s+-[^\\\\s\\\\\"']*[rf][^\\\\s\\\\\"']*\\\\s+(?:--\\\\s+)?(?:/|~|\\\\$\\\\{?HOME\\\\}?|\\\\.)\"),\n re.compile(NESTED_SHELL_PREFIX + r\"[\\\\\"'][^\\\\\"']*\\\\bchmod\\\\s+-R\\\\s+(?:777|a\\\\+w)\\\\s+(?:--\\\\s+)?(?:/|~|\\\\$\\\\{?HOME\\\\}?|\\\\.)\"),\n re.compile(NESTED_SHELL_PREFIX + r\"[\\\\\"'][^\\\\\"']*\\\\bchown\\\\s+-R\\\\s+[^;&|]+\\\\s+(?:--\\\\s+)?(?:/|~|\\\\$\\\\{?HOME\\\\}?|\\\\.)\"),\n]\nMUTATING_COMMAND_PATTERN = re.compile(r\"\\\\b(?:rm|mv|cp|touch|mkdir|rmdir|ln|truncate|tee|sed\\\\s+-i|perl\\\\s+-pi|python(?:3)?\\\\s+-c|node\\\\s+-e|npm\\\\s+(?:install|ci|update|publish)|pnpm\\\\s+(?:install|update|publish)|yarn\\\\s+(?:install|add|publish)|git\\\\s+(?:add|commit|checkout|switch|reset|clean|rebase|merge|push|pull|stash|tag|branch)|chmod|chown)\\\\b|(?:^|[^<])>\\\\s*[^&]|\\\\bcat\\\\s+[^|;&]*>\\\\s*\")\nPROTECTED_TARGET_ARG_RE = re.compile(r\"^(?:/|~|\\\\$\\\\{?HOME\\\\}?|\\\\.)(?:/?\\\\.?\\\\*|/)?$\")\nDESTRUCTIVE_OP_IN_COMMAND_RE = re.compile(r\"\\\\b(?:rm\\\\s+-[^\\\\s]*[rf]|chmod\\\\s+-R|chown\\\\s+-R)\\\\b\")\n\ndef _is_within_workspace(file_path):\n resolved = os.path.abspath(file_path)\n root = os.path.abspath(WORKSPACE)\n return os.path.commonpath([root, resolved]) == root\n\ndef _resolve(file_path=\".\"):\n raw = file_path or \".\"\n candidate = raw if os.path.isabs(raw) else os.path.join(WORKSPACE, raw)\n resolved = os.path.abspath(candidate)\n if not _is_within_workspace(resolved):\n raise ValueError(f\"Path is outside the Cloudflare sandbox workspace: {file_path}\")\n return resolved\n\ndef _assert_writable(tool_name):\n if READ_ONLY:\n raise PermissionError(f\"{tool_name} is blocked in read-only Cloudflare sandbox mode.\")\n\ndef _strip_quoted_content(command):\n output = []\n quote = None\n escaped = False\n index = 0\n while index < len(command):\n char = command[index]\n if escaped:\n escaped = False\n output.append(\" \")\n index += 1\n continue\n if char == \"\\\\\\\\\":\n escaped = True\n output.append(\" \")\n index += 1\n continue\n if quote is not None:\n if char == quote:\n quote = None\n output.append(\" \")\n index += 1\n continue\n if char in (\"'\", '\"', \"\\`\"):\n quote = char\n output.append(\" \")\n index += 1\n continue\n if char == \"#\":\n while index < len(command) and command[index] != \"\\\\n\":\n output.append(\" \")\n index += 1\n output.append(\"\\\\n\")\n index += 1\n continue\n output.append(char)\n index += 1\n return \"\".join(output)\n\ndef _validate_bash_command(command, args=None):\n errors = []\n normalized = _strip_quoted_content(command)\n if command.strip() == \"\":\n errors.append(\"Command is empty.\")\n if \"\\\\0\" in command:\n errors.append(\"Command contains a NUL byte.\")\n if not ALLOW_DANGEROUS_COMMANDS:\n if any(pattern.search(normalized) for pattern in DANGEROUS_COMMAND_PATTERNS):\n errors.append(\"Command matches a destructive command pattern.\")\n elif any(pattern.search(command) for pattern in QUOTED_DESTRUCTIVE_PATTERNS):\n errors.append(\"Command matches a destructive command pattern (quoted target).\")\n elif any(pattern.search(command) for pattern in NESTED_SHELL_DESTRUCTIVE_PATTERNS):\n errors.append(\"Command matches a destructive command pattern (nested shell payload).\")\n elif args and DESTRUCTIVE_OP_IN_COMMAND_RE.search(command):\n offending = next((str(arg) for arg in args if PROTECTED_TARGET_ARG_RE.search(str(arg))), None)\n if offending is not None:\n errors.append(f\"Command matches a destructive command pattern (protected target \\\\\"{offending}\\\\\" passed via positional arg).\")\n if READ_ONLY and MUTATING_COMMAND_PATTERN.search(normalized):\n errors.append(\"Command appears to mutate files or repository state in read-only Cloudflare sandbox mode.\")\n if errors:\n raise ValueError(\"\\\\n\".join(errors))\n\ndef _line_window(content, offset=None, limit=None):\n start = max((offset or 1) - 1, 0)\n lines = content.split(\"\\\\n\")\n selected = lines[start:] if not limit or limit <= 0 else lines[start:start + limit]\n return \"\\\\n\".join(f\"{start + idx + 1:6d}\\\\t{line}\" for idx, line in enumerate(selected))\n\ndef _run(command, timeout=None, args=None):\n _validate_bash_command(command, args=args)\n completed = subprocess.run(\n [SHELL, \"-lc\", command, \"--\"] + [str(arg) for arg in (args or [])],\n cwd=WORKSPACE,\n capture_output=True,\n text=True,\n timeout=(timeout / 1000 if timeout else None),\n )\n return {\n \"stdout\": completed.stdout,\n \"stderr\": completed.stderr,\n \"exit_code\": completed.returncode,\n }\n\ndef _format_run(result):\n text = \"\"\n if result.get(\"stdout\"):\n text += f\"stdout:\\\\n{result['stdout']}\\\\n\"\n else:\n text += \"stdout: Empty. Ensure you're writing output explicitly.\\\\n\"\n if result.get(\"stderr\"):\n text += f\"stderr:\\\\n{result['stderr']}\\\\n\"\n if result.get(\"exit_code\") not in (None, 0):\n text += f\"exit_code: {result['exit_code']}\\\\n\"\n text += f\"working_directory: {WORKSPACE}\"\n return text.strip()\n\ndef _detect_compile_command():\n if os.path.exists(os.path.join(WORKSPACE, \"tsconfig.json\")):\n return \"typescript\", \"npx --no-install tsc --noEmit\", \"tsconfig.json present\"\n package_json = os.path.join(WORKSPACE, \"package.json\")\n if os.path.exists(package_json):\n try:\n if '\"typescript\"' in open(package_json, encoding=\"utf-8\").read():\n return \"typescript\", \"npx --no-install tsc --noEmit\", \"package.json declares typescript\"\n except Exception:\n pass\n if os.path.exists(os.path.join(WORKSPACE, \"Cargo.toml\")):\n return \"rust\", \"cargo check --message-format=short\", \"Cargo.toml present\"\n if os.path.exists(os.path.join(WORKSPACE, \"go.mod\")):\n return \"go\", \"go vet ./...\", \"go.mod present\"\n if any(os.path.exists(os.path.join(WORKSPACE, name)) for name in [\"pyproject.toml\", \"setup.py\", \"setup.cfg\"]):\n return \"python-compile\", \"python3 -m py_compile $(find . -name '*.py' -not -path './.venv/*' -not -path './node_modules/*')\", \"Python project\"\n return \"unknown\", \"\", \"no recognised project marker\"\n\nasync def bash_tool(command, args=None):\n return _format_run(_run(command, args=args))\n\nasync def execute_code(lang, code, args=None):\n args = args or []\n temp_dir = tempfile.mkdtemp(prefix=\"lc-ptc-\", dir=WORKSPACE)\n try:\n def q(value):\n import shlex\n return shlex.quote(str(value))\n arg_text = \" \".join(q(arg) for arg in args)\n if lang in (\"py\", \"python\"):\n file_path = os.path.join(temp_dir, \"main.py\")\n open(file_path, \"w\", encoding=\"utf-8\").write(code)\n return _format_run(_run(f\"python3 {q(file_path)} {arg_text}\"))\n if lang in (\"js\", \"javascript\"):\n file_path = os.path.join(temp_dir, \"main.js\")\n open(file_path, \"w\", encoding=\"utf-8\").write(code)\n return _format_run(_run(f\"node {q(file_path)} {arg_text}\"))\n if lang in (\"ts\", \"typescript\"):\n file_path = os.path.join(temp_dir, \"main.ts\")\n open(file_path, \"w\", encoding=\"utf-8\").write(code)\n return _format_run(_run(f\"npx --no-install tsx {q(file_path)} {arg_text}\"))\n if lang == \"php\":\n file_path = os.path.join(temp_dir, \"main.php\")\n open(file_path, \"w\", encoding=\"utf-8\").write(code)\n return _format_run(_run(f\"php {q(file_path)} {arg_text}\"))\n if lang == \"go\":\n file_path = os.path.join(temp_dir, \"main.go\")\n open(file_path, \"w\", encoding=\"utf-8\").write(code)\n return _format_run(_run(f\"go run {q(file_path)} {arg_text}\"))\n if lang == \"rs\":\n file_path = os.path.join(temp_dir, \"main.rs\")\n open(file_path, \"w\", encoding=\"utf-8\").write(code)\n binary = os.path.join(temp_dir, \"main-rs\")\n return _format_run(_run(f\"rustc {q(file_path)} -o {q(binary)} && {q(binary)} {arg_text}\"))\n if lang == \"c\":\n file_path = os.path.join(temp_dir, \"main.c\")\n open(file_path, \"w\", encoding=\"utf-8\").write(code)\n binary = os.path.join(temp_dir, \"main-c\")\n return _format_run(_run(f\"cc {q(file_path)} -o {q(binary)} && {q(binary)} {arg_text}\"))\n if lang == \"cpp\":\n file_path = os.path.join(temp_dir, \"main.cpp\")\n open(file_path, \"w\", encoding=\"utf-8\").write(code)\n binary = os.path.join(temp_dir, \"main-cpp\")\n return _format_run(_run(f\"c++ {q(file_path)} -o {q(binary)} && {q(binary)} {arg_text}\"))\n if lang == \"java\":\n file_path = os.path.join(temp_dir, \"Main.java\")\n open(file_path, \"w\", encoding=\"utf-8\").write(code)\n return _format_run(_run(f\"javac {q(file_path)} && java -cp {q(temp_dir)} Main {arg_text}\"))\n if lang == \"r\":\n file_path = os.path.join(temp_dir, \"main.R\")\n open(file_path, \"w\", encoding=\"utf-8\").write(code)\n return _format_run(_run(f\"Rscript {q(file_path)} {arg_text}\"))\n if lang == \"d\":\n file_path = os.path.join(temp_dir, \"main.d\")\n open(file_path, \"w\", encoding=\"utf-8\").write(code)\n binary = os.path.join(temp_dir, \"main-d\")\n return _format_run(_run(f\"dmd {q(file_path)} -of={q(binary)} && {q(binary)} {arg_text}\"))\n if lang == \"f90\":\n file_path = os.path.join(temp_dir, \"main.f90\")\n open(file_path, \"w\", encoding=\"utf-8\").write(code)\n binary = os.path.join(temp_dir, \"main-f90\")\n return _format_run(_run(f\"gfortran {q(file_path)} -o {q(binary)} && {q(binary)} {arg_text}\"))\n if lang in (\"bash\", \"sh\"):\n return _format_run(_run(code, args=args))\n raise ValueError(f\"Unsupported Cloudflare sandbox runtime: {lang}\")\n finally:\n shutil.rmtree(temp_dir, ignore_errors=True)\n\nasync def read_file(path, offset=None, limit=None):\n resolved = _resolve(path)\n with open(resolved, encoding=\"utf-8\") as handle:\n return _line_window(handle.read(), offset, limit)\n\nasync def write_file(path, content):\n _assert_writable(\"write_file\")\n resolved = _resolve(path)\n os.makedirs(os.path.dirname(resolved), exist_ok=True)\n existed = os.path.exists(resolved)\n with open(resolved, \"w\", encoding=\"utf-8\") as handle:\n handle.write(content)\n return f\"{'Overwrote' if existed else 'Created'} {resolved} ({len(content)} chars).\"\n\nasync def edit_file(path, old_text=None, new_text=None, edits=None):\n _assert_writable(\"edit_file\")\n resolved = _resolve(path)\n edits = edits or [{\"old_text\": old_text, \"new_text\": new_text}]\n content = open(resolved, encoding=\"utf-8\").read()\n for edit in edits:\n old = edit.get(\"old_text\") or \"\"\n new = edit.get(\"new_text\") or \"\"\n if content.count(old) != 1:\n raise ValueError(f\"Could not locate old_text exactly once in {path}\")\n content = content.replace(old, new, 1)\n open(resolved, \"w\", encoding=\"utf-8\").write(content)\n return f\"Applied {len(edits)} edit(s) to {resolved}.\"\n\nasync def list_directory(path=\".\"):\n resolved = _resolve(path)\n entries = []\n for name in sorted(os.listdir(resolved)):\n full = os.path.join(resolved, name)\n entries.append((\"dir \" if os.path.isdir(full) else \"file\") + \"\\\\t\" + name)\n return \"\\\\n\".join(entries) or \"Directory is empty.\"\n\nasync def grep_search(pattern, path=\".\", glob=None, max_results=200):\n root = _resolve(path)\n regex = re.compile(pattern)\n out = []\n for current, dirs, files in os.walk(root):\n dirs[:] = [d for d in dirs if d not in {\".git\", \"node_modules\", \".venv\", \"dist\", \"build\"}]\n for name in files:\n rel = os.path.relpath(os.path.join(current, name), root)\n if glob and not fnmatch.fnmatch(rel, glob):\n continue\n try:\n for line_no, line in enumerate(open(os.path.join(current, name), encoding=\"utf-8\", errors=\"ignore\"), 1):\n if regex.search(line):\n out.append(f\"{os.path.join(current, name)}:{line_no}:{line.rstrip()}\")\n if len(out) >= max_results:\n return \"\\\\n\".join(out)\n except Exception:\n pass\n return \"\\\\n\".join(out) if out else \"No matches found.\"\n\nasync def glob_search(pattern, path=\".\", max_results=200):\n root = _resolve(path)\n target = pattern if os.path.isabs(pattern) else os.path.join(root, pattern)\n matches = []\n for match in glob_module.glob(target, recursive=True):\n resolved = os.path.abspath(match)\n if _is_within_workspace(resolved):\n matches.append(resolved)\n if len(matches) >= max_results:\n break\n return \"\\\\n\".join(matches) if matches else \"No files found.\"\n\nasync def compile_check(command=None, timeout_ms=None):\n kind, detected, reason = _detect_compile_command()\n command = command or detected\n if not command:\n return f\"compile_check: {reason}. Pass an explicit command to override.\"\n result = _run(command, timeout_ms)\n status = \"PASSED\" if result[\"exit_code\"] == 0 else \"FAILED\"\n return f\"compile_check ({kind}) {status} via {command}\\\\n\\\\nstdout:\\\\n{result['stdout']}\\\\nstderr:\\\\n{result['stderr']}\\\\nworking_directory: {WORKSPACE}\\\\nreason: {reason}\"\n\n# Avoid shadowing the glob_search function argument named \"glob\".\nglob_module = glob\n`.trim();\n}\n\nfunction createNodeNativeToolSource(\n config: t.CloudflareSandboxExecutionConfig,\n workspaceRoot: string\n): string {\n return `\nconst fs = require(\"fs\");\nconst fsp = fs.promises;\nconst path = require(\"path\");\nconst cp = require(\"child_process\");\n\nconst WORKSPACE = ${JSON.stringify(workspaceRoot)};\nconst SHELL = ${JSON.stringify(config.shell ?? 'bash')};\nconst READ_ONLY = ${JSON.stringify(config.readOnly === true)};\nconst ALLOW_DANGEROUS_COMMANDS = ${JSON.stringify(config.allowDangerousCommands === true)};\nconst DESTRUCTIVE_TARGET = \"(?:\\\\\\\\/|~|\\\\\\\\$\\\\\\\\{?HOME\\\\\\\\}?|\\\\\\\\.)(?:\\\\\\\\/?\\\\\\\\.?\\\\\\\\*|\\\\\\\\/)?\";\nconst DANGEROUS_COMMAND_PATTERNS = [\n new RegExp(\"\\\\\\\\brm\\\\\\\\s+(?:-[^\\\\\\\\s]*[rf][^\\\\\\\\s]*\\\\\\\\s+|-[^\\\\\\\\s]*[r][^\\\\\\\\s]*\\\\\\\\s+-[^\\\\\\\\s]*[f][^\\\\\\\\s]*\\\\\\\\s+)(?:--\\\\\\\\s+)?\" + DESTRUCTIVE_TARGET + \"\\\\\\\\s*(?:$|[;&|])\"),\n /\\\\b(?:mkfs|mkswap|fdisk|parted|diskutil)\\\\b/,\n /\\\\bdd\\\\s+[^;&|]*\\\\bof=\\\\/dev\\\\//,\n new RegExp(\"\\\\\\\\bchmod\\\\\\\\s+-R\\\\\\\\s+(?:777|a\\\\\\\\+w)\\\\\\\\s+(?:--\\\\\\\\s+)?\" + DESTRUCTIVE_TARGET + \"(?:$|\\\\\\\\s|[;&|])\"),\n new RegExp(\"\\\\\\\\bchown\\\\\\\\s+-R\\\\\\\\s+[^;&|]+\\\\\\\\s+(?:--\\\\\\\\s+)?\" + DESTRUCTIVE_TARGET + \"(?:$|\\\\\\\\s|[;&|])\"),\n /:\\\\s*\\\\(\\\\s*\\\\)\\\\s*\\\\{\\\\s*:\\\\s*\\\\|\\\\s*:\\\\s*&\\\\s*\\\\}\\\\s*;\\\\s*:/,\n];\nconst QUOTED_DESTRUCTIVE_PATTERNS = [\n new RegExp(\"\\\\\\\\brm\\\\\\\\s+(?:-[^\\\\\\\\s]*[rf][^\\\\\\\\s]*\\\\\\\\s+){1,3}(?:--\\\\\\\\s+)?[\\\\\\\"']\" + DESTRUCTIVE_TARGET + \"[\\\\\\\"']\"),\n new RegExp(\"\\\\\\\\bchmod\\\\\\\\s+-R\\\\\\\\s+(?:777|a\\\\\\\\+w)\\\\\\\\s+(?:--\\\\\\\\s+)?[\\\\\\\"']\" + DESTRUCTIVE_TARGET + \"[\\\\\\\"']\"),\n new RegExp(\"\\\\\\\\bchown\\\\\\\\s+-R\\\\\\\\s+[^;&|]+\\\\\\\\s+(?:--\\\\\\\\s+)?[\\\\\\\"']\" + DESTRUCTIVE_TARGET + \"[\\\\\\\"']\"),\n];\nconst NESTED_SHELL_PREFIX = \"(?:(?:ba|z|da|k)?sh|eval)\\\\\\\\s+(?:-l?c\\\\\\\\s+)?\";\nconst NESTED_SHELL_DESTRUCTIVE_PATTERNS = [\n new RegExp(NESTED_SHELL_PREFIX + \"[\\\\\\\"'][^\\\\\\\"']*\\\\\\\\brm\\\\\\\\s+-[^\\\\\\\\s\\\\\\\"']*[rf][^\\\\\\\\s\\\\\\\"']*\\\\\\\\s+(?:--\\\\\\\\s+)?(?:\\\\\\\\/|~|\\\\\\\\$\\\\\\\\{?HOME\\\\\\\\}?|\\\\\\\\.)\"),\n new RegExp(NESTED_SHELL_PREFIX + \"[\\\\\\\"'][^\\\\\\\"']*\\\\\\\\bchmod\\\\\\\\s+-R\\\\\\\\s+(?:777|a\\\\\\\\+w)\\\\\\\\s+(?:--\\\\\\\\s+)?(?:\\\\\\\\/|~|\\\\\\\\$\\\\\\\\{?HOME\\\\\\\\}?|\\\\\\\\.)\"),\n new RegExp(NESTED_SHELL_PREFIX + \"[\\\\\\\"'][^\\\\\\\"']*\\\\\\\\bchown\\\\\\\\s+-R\\\\\\\\s+[^;&|]+\\\\\\\\s+(?:--\\\\\\\\s+)?(?:\\\\\\\\/|~|\\\\\\\\$\\\\\\\\{?HOME\\\\\\\\}?|\\\\\\\\.)\"),\n];\nconst MUTATING_COMMAND_PATTERN = /\\\\b(?:rm|mv|cp|touch|mkdir|rmdir|ln|truncate|tee|sed\\\\s+-i|perl\\\\s+-pi|python(?:3)?\\\\s+-c|node\\\\s+-e|npm\\\\s+(?:install|ci|update|publish)|pnpm\\\\s+(?:install|update|publish)|yarn\\\\s+(?:install|add|publish)|git\\\\s+(?:add|commit|checkout|switch|reset|clean|rebase|merge|push|pull|stash|tag|branch)|chmod|chown)\\\\b|(?:^|[^<])>\\\\s*[^&]|\\\\bcat\\\\s+[^|;&]*>\\\\s*/;\nconst PROTECTED_TARGET_ARG_RE = /^(?:\\\\/|~|\\\\$\\\\{?HOME\\\\}?|\\\\.)(?:\\\\/?\\\\.?\\\\*|\\\\/)?$/;\nconst DESTRUCTIVE_OP_IN_COMMAND_RE = /\\\\b(?:rm\\\\s+-[^\\\\s]*[rf]|chmod\\\\s+-R|chown\\\\s+-R)\\\\b/;\n\nfunction resolvePath(filePath) {\n const raw = filePath || \".\";\n const candidate = path.isAbsolute(raw) ? raw : path.join(WORKSPACE, raw);\n const resolved = path.resolve(candidate);\n const root = path.resolve(WORKSPACE);\n const relative = path.relative(root, resolved);\n if (relative && (relative.startsWith(\"..\") || path.isAbsolute(relative))) {\n throw new Error(\"Path is outside the Cloudflare sandbox workspace: \" + filePath);\n }\n return resolved;\n}\n\nfunction assertWritable(toolName) {\n if (READ_ONLY) {\n throw new Error(toolName + \" is blocked in read-only Cloudflare sandbox mode.\");\n }\n}\n\nfunction stripQuotedContent(command) {\n let output = \"\";\n let quote;\n let escaped = false;\n for (let index = 0; index < command.length; index++) {\n const char = command[index];\n if (escaped) {\n escaped = false;\n output += \" \";\n continue;\n }\n if (char === \"\\\\\\\\\") {\n escaped = true;\n output += \" \";\n continue;\n }\n if (quote != null) {\n if (char === quote) quote = undefined;\n output += \" \";\n continue;\n }\n if (char === \"\\\\\\\"\" || char === \"'\" || char === \"\\`\") {\n quote = char;\n output += \" \";\n continue;\n }\n if (char === \"#\") {\n while (index < command.length && command[index] !== \"\\\\n\") {\n output += \" \";\n index += 1;\n }\n output += \"\\\\n\";\n continue;\n }\n output += char;\n }\n return output;\n}\n\nfunction validateBashCommand(command, args) {\n const errors = [];\n const normalized = stripQuotedContent(command);\n if (command.trim() === \"\") {\n errors.push(\"Command is empty.\");\n }\n if (command.includes(\"\\\\0\")) {\n errors.push(\"Command contains a NUL byte.\");\n }\n if (!ALLOW_DANGEROUS_COMMANDS) {\n if (DANGEROUS_COMMAND_PATTERNS.some((pattern) => pattern.test(normalized))) {\n errors.push(\"Command matches a destructive command pattern.\");\n } else if (QUOTED_DESTRUCTIVE_PATTERNS.some((pattern) => pattern.test(command))) {\n errors.push(\"Command matches a destructive command pattern (quoted target).\");\n } else if (NESTED_SHELL_DESTRUCTIVE_PATTERNS.some((pattern) => pattern.test(command))) {\n errors.push(\"Command matches a destructive command pattern (nested shell payload).\");\n } else if ((args || []).length > 0 && DESTRUCTIVE_OP_IN_COMMAND_RE.test(command)) {\n const offending = (args || []).map(String).find((arg) => PROTECTED_TARGET_ARG_RE.test(arg));\n if (offending !== undefined) {\n errors.push(\"Command matches a destructive command pattern (protected target \\\\\"\" + offending + \"\\\\\" passed via positional arg).\");\n }\n }\n }\n if (READ_ONLY && MUTATING_COMMAND_PATTERN.test(normalized)) {\n errors.push(\"Command appears to mutate files or repository state in read-only Cloudflare sandbox mode.\");\n }\n if (errors.length > 0) {\n throw new Error(errors.join(\"\\\\n\"));\n }\n}\n\nfunction lineWindow(content, offset, limit) {\n const start = Math.max((offset || 1) - 1, 0);\n const lines = content.split(\"\\\\n\");\n const selected = !limit || limit <= 0 ? lines.slice(start) : lines.slice(start, start + limit);\n return selected.map((line, index) => String(start + index + 1).padStart(6, \" \") + \"\\\\t\" + line).join(\"\\\\n\");\n}\n\nfunction quote(value) {\n const text = String(value);\n if (text === \"\") return \"''\";\n if (/^[A-Za-z0-9_/:=.,@%+-]+$/.test(text)) return text;\n return \"'\" + text.replace(/'/g, \"'\\\\\\\\''\") + \"'\";\n}\n\nfunction run(command, timeoutMs, args) {\n validateBashCommand(command, args);\n return new Promise((resolve) => {\n const child = cp.spawn(SHELL, [\"-lc\", command, \"--\", ...((args || []).map(String))], {\n cwd: WORKSPACE,\n env: process.env,\n });\n let stdout = \"\";\n let stderr = \"\";\n let timedOut = false;\n const timer = timeoutMs\n ? setTimeout(() => {\n timedOut = true;\n child.kill(\"SIGTERM\");\n }, timeoutMs)\n : null;\n\n child.stdout.on(\"data\", (chunk) => {\n stdout += chunk.toString();\n });\n child.stderr.on(\"data\", (chunk) => {\n stderr += chunk.toString();\n });\n child.on(\"error\", (error) => {\n if (timer) clearTimeout(timer);\n resolve({ stdout, stderr: stderr + error.message, exit_code: 1, timed_out: timedOut });\n });\n child.on(\"close\", (code) => {\n if (timer) clearTimeout(timer);\n resolve({ stdout, stderr, exit_code: timedOut ? null : code, timed_out: timedOut });\n });\n });\n}\n\nfunction formatRun(result) {\n let text = \"\";\n if (result.stdout) {\n text += \"stdout:\\\\n\" + result.stdout + \"\\\\n\";\n } else {\n text += \"stdout: Empty. Ensure you're writing output explicitly.\\\\n\";\n }\n if (result.stderr) {\n text += \"stderr:\\\\n\" + result.stderr + \"\\\\n\";\n }\n if (result.timed_out) {\n text += \"timed_out: true\\\\n\";\n }\n if (result.exit_code !== null && result.exit_code !== undefined && result.exit_code !== 0) {\n text += \"exit_code: \" + result.exit_code + \"\\\\n\";\n }\n text += \"working_directory: \" + WORKSPACE;\n return text.trim();\n}\n\nasync function detectCompileCommand() {\n async function exists(name) {\n try {\n await fsp.access(path.join(WORKSPACE, name));\n return true;\n } catch {\n return false;\n }\n }\n if (await exists(\"tsconfig.json\")) {\n return [\"typescript\", \"npx --no-install tsc --noEmit\", \"tsconfig.json present\"];\n }\n if (await exists(\"package.json\")) {\n try {\n if ((await fsp.readFile(path.join(WORKSPACE, \"package.json\"), \"utf8\")).includes('\"typescript\"')) {\n return [\"typescript\", \"npx --no-install tsc --noEmit\", \"package.json declares typescript\"];\n }\n } catch {}\n }\n if (await exists(\"Cargo.toml\")) return [\"rust\", \"cargo check --message-format=short\", \"Cargo.toml present\"];\n if (await exists(\"go.mod\")) return [\"go\", \"go vet ./...\", \"go.mod present\"];\n if (await exists(\"pyproject.toml\") || await exists(\"setup.py\") || await exists(\"setup.cfg\")) {\n return [\"python-compile\", \"python3 -m py_compile $(find . -name '*.py' -not -path './.venv/*' -not -path './node_modules/*')\", \"Python project\"];\n }\n return [\"unknown\", \"\", \"no recognised project marker\"];\n}\n\nfunction globToRegExp(pattern) {\n const escaped = pattern.replace(/[|\\\\\\\\{}()[\\\\]^$+*?.]/g, \"\\\\\\\\$&\");\n return new RegExp(\"^\" + escaped.replace(/\\\\\\\\\\\\*\\\\\\\\\\\\*/g, \".*\").replace(/\\\\\\\\\\\\*/g, \"[^/]*\") + \"$\");\n}\n\nfunction globMatch(relativePath, pattern) {\n const matcher = globToRegExp(pattern);\n return matcher.test(relativePath) || matcher.test(path.basename(relativePath));\n}\n\nasync function walkFiles(root, visit) {\n const entries = await fsp.readdir(root, { withFileTypes: true });\n for (const entry of entries) {\n const full = path.join(root, entry.name);\n if (entry.isDirectory()) {\n if ([\".git\", \"node_modules\", \".venv\", \"dist\", \"build\"].includes(entry.name)) continue;\n await walkFiles(full, visit);\n } else if (entry.isFile()) {\n await visit(full);\n }\n }\n}\n\nasync function bash_tool(payload) {\n return formatRun(await run(payload.command, undefined, payload.args));\n}\n\nasync function execute_code(payload) {\n const lang = payload.lang;\n const code = payload.code;\n const args = payload.args || [];\n const tempDir = await fsp.mkdtemp(path.join(WORKSPACE, \"lc-ptc-\"));\n try {\n const argText = args.map(quote).join(\" \");\n async function writeAndRun(fileName, command) {\n const filePath = path.join(tempDir, fileName);\n await fsp.writeFile(filePath, code, \"utf8\");\n return formatRun(await run(command(filePath, argText), undefined, []));\n }\n if (lang === \"py\" || lang === \"python\") {\n return writeAndRun(\"main.py\", (filePath, argText) => \"python3 \" + quote(filePath) + \" \" + argText);\n }\n if (lang === \"js\" || lang === \"javascript\") {\n return writeAndRun(\"main.js\", (filePath, argText) => \"node \" + quote(filePath) + \" \" + argText);\n }\n if (lang === \"ts\" || lang === \"typescript\") {\n return writeAndRun(\"main.ts\", (filePath, argText) => \"npx --no-install tsx \" + quote(filePath) + \" \" + argText);\n }\n if (lang === \"php\") {\n return writeAndRun(\"main.php\", (filePath, argText) => \"php \" + quote(filePath) + \" \" + argText);\n }\n if (lang === \"go\") {\n return writeAndRun(\"main.go\", (filePath, argText) => \"go run \" + quote(filePath) + \" \" + argText);\n }\n if (lang === \"rs\") {\n return writeAndRun(\"main.rs\", (filePath, argText) => {\n const binary = path.join(tempDir, \"main-rs\");\n return \"rustc \" + quote(filePath) + \" -o \" + quote(binary) + \" && \" + quote(binary) + \" \" + argText;\n });\n }\n if (lang === \"c\") {\n return writeAndRun(\"main.c\", (filePath, argText) => {\n const binary = path.join(tempDir, \"main-c\");\n return \"cc \" + quote(filePath) + \" -o \" + quote(binary) + \" && \" + quote(binary) + \" \" + argText;\n });\n }\n if (lang === \"cpp\") {\n return writeAndRun(\"main.cpp\", (filePath, argText) => {\n const binary = path.join(tempDir, \"main-cpp\");\n return \"c++ \" + quote(filePath) + \" -o \" + quote(binary) + \" && \" + quote(binary) + \" \" + argText;\n });\n }\n if (lang === \"java\") {\n return writeAndRun(\"Main.java\", (filePath, argText) => \"javac \" + quote(filePath) + \" && java -cp \" + quote(tempDir) + \" Main \" + argText);\n }\n if (lang === \"r\") {\n return writeAndRun(\"main.R\", (filePath, argText) => \"Rscript \" + quote(filePath) + \" \" + argText);\n }\n if (lang === \"d\") {\n return writeAndRun(\"main.d\", (filePath, argText) => {\n const binary = path.join(tempDir, \"main-d\");\n return \"dmd \" + quote(filePath) + \" -of=\" + quote(binary) + \" && \" + quote(binary) + \" \" + argText;\n });\n }\n if (lang === \"f90\") {\n return writeAndRun(\"main.f90\", (filePath, argText) => {\n const binary = path.join(tempDir, \"main-f90\");\n return \"gfortran \" + quote(filePath) + \" -o \" + quote(binary) + \" && \" + quote(binary) + \" \" + argText;\n });\n }\n if (lang === \"bash\" || lang === \"sh\") {\n return formatRun(await run(code, undefined, args));\n }\n throw new Error(\"Unsupported Cloudflare sandbox runtime: \" + lang);\n } finally {\n await fsp.rm(tempDir, { recursive: true, force: true });\n }\n}\n\nasync function read_file(payload) {\n const resolved = resolvePath(payload.path);\n return lineWindow(await fsp.readFile(resolved, \"utf8\"), payload.offset, payload.limit);\n}\n\nasync function write_file(payload) {\n assertWritable(\"write_file\");\n const resolved = resolvePath(payload.path);\n await fsp.mkdir(path.dirname(resolved), { recursive: true });\n const existed = fs.existsSync(resolved);\n await fsp.writeFile(resolved, payload.content, \"utf8\");\n return (existed ? \"Overwrote \" : \"Created \") + resolved + \" (\" + payload.content.length + \" chars).\";\n}\n\nasync function edit_file(payload) {\n assertWritable(\"edit_file\");\n const resolved = resolvePath(payload.path);\n const edits = payload.edits || [{ old_text: payload.old_text, new_text: payload.new_text }];\n let content = await fsp.readFile(resolved, \"utf8\");\n for (const edit of edits) {\n const oldText = edit.old_text || \"\";\n const newText = edit.new_text || \"\";\n if (oldText === \"\" || content.split(oldText).length - 1 !== 1) {\n throw new Error(\"Could not locate old_text exactly once in \" + payload.path);\n }\n content = content.replace(oldText, newText);\n }\n await fsp.writeFile(resolved, content, \"utf8\");\n return \"Applied \" + edits.length + \" edit(s) to \" + resolved + \".\";\n}\n\nasync function list_directory(payload) {\n const resolved = resolvePath(payload.path || \".\");\n const entries = await fsp.readdir(resolved, { withFileTypes: true });\n const lines = entries\n .sort((a, b) => a.name.localeCompare(b.name))\n .map((entry) => (entry.isDirectory() ? \"dir\" : \"file\") + \"\\\\t\" + entry.name);\n return lines.join(\"\\\\n\") || \"Directory is empty.\";\n}\n\nasync function grep_search(payload) {\n const root = resolvePath(payload.path || \".\");\n const regex = new RegExp(payload.pattern);\n const maxResults = payload.max_results || 200;\n const out = [];\n await walkFiles(root, async (filePath) => {\n if (out.length >= maxResults) return;\n const relative = path.relative(root, filePath);\n if (payload.glob && !globMatch(relative, payload.glob)) return;\n let text = \"\";\n try {\n text = await fsp.readFile(filePath, \"utf8\");\n } catch {\n return;\n }\n text.split(\"\\\\n\").forEach((line, index) => {\n if (out.length < maxResults && regex.test(line)) {\n out.push(filePath + \":\" + (index + 1) + \":\" + line);\n }\n });\n });\n return out.join(\"\\\\n\") || \"No matches found.\";\n}\n\nasync function glob_search(payload) {\n const root = resolvePath(payload.path || \".\");\n const maxResults = payload.max_results || 200;\n const out = [];\n await walkFiles(root, async (filePath) => {\n if (out.length >= maxResults) return;\n const relative = path.relative(root, filePath);\n if (globMatch(relative, payload.pattern)) out.push(filePath);\n });\n return out.join(\"\\\\n\") || \"No files found.\";\n}\n\nasync function compile_check(payload) {\n const [kind, detected, reason] = await detectCompileCommand();\n const command = payload.command || detected;\n if (!command) {\n return \"compile_check: \" + reason + \". Pass an explicit command to override.\";\n }\n const result = await run(command, payload.timeout_ms);\n const status = result.exit_code === 0 ? \"PASSED\" : \"FAILED\";\n return \"compile_check (\" + kind + \") \" + status + \" via \" + command + \"\\\\n\\\\nstdout:\\\\n\" + result.stdout + \"\\\\nstderr:\\\\n\" + result.stderr + \"\\\\nworking_directory: \" + WORKSPACE + \"\\\\nreason: \" + reason;\n}\n\nconst TOOLS = {\n bash_tool,\n execute_code,\n read_file,\n write_file,\n edit_file,\n list_directory,\n grep_search,\n glob_search,\n compile_check,\n};\n\nasync function main() {\n const name = process.argv[2];\n const payload = JSON.parse(process.argv[3] || \"{}\");\n if (!TOOLS[name]) throw new Error(\"Unknown tool: \" + name);\n const result = await TOOLS[name](payload);\n process.stdout.write(typeof result === \"string\" ? result : JSON.stringify(result));\n}\n\nmain().catch((error) => {\n console.error(error && error.stack ? error.stack : String(error));\n process.exit(1);\n});\n`.trim();\n}\n\nfunction createPythonProgram(\n userCode: string,\n toolDefs: t.LCTool[],\n config: t.CloudflareSandboxExecutionConfig,\n workspaceRoot: string\n): string {\n const aliases = toolDefs\n .map((def) => {\n const pythonName = normalizeToPythonIdentifier(def.name);\n return NATIVE_TOOL_NAMES.has(def.name) && pythonName !== def.name\n ? `${pythonName} = globals()[${JSON.stringify(def.name)}]`\n : '';\n })\n .filter(Boolean)\n .join('\\n');\n return `${createPythonNativeToolSource(config, workspaceRoot)}\n${aliases}\n\nasync def __lc_user_main__():\n${indent(userCode)}\n\nasyncio.run(__lc_user_main__())\n`;\n}\n\nfunction createBashProgram(\n userCode: string,\n toolDefs: t.LCTool[],\n config: t.CloudflareSandboxExecutionConfig,\n workspaceRoot: string\n): string {\n const helper = createNodeNativeToolSource(config, workspaceRoot);\n const functions = toolDefs\n .map((def) => {\n const bashName = normalizeToBashIdentifier(def.name);\n if (!NATIVE_TOOL_NAMES.has(def.name)) {\n return '';\n }\n return `${bashName}() { node \"$__LC_TOOL_HELPER\" ${JSON.stringify(def.name)} \"$1\"; }`;\n })\n .filter(Boolean)\n .join('\\n');\n return `\nset -euo pipefail\ncommand -v node >/dev/null 2>&1 || { echo \"Cloudflare programmatic tool calling requires node in the sandbox image.\" >&2; exit 127; }\n__LC_TOOL_HELPER=\"$(mktemp /tmp/lc-tools.XXXXXX.js)\"\ncat > \"$__LC_TOOL_HELPER\" <<'JS'\n${helper}\nJS\ntrap 'rm -f \"$__LC_TOOL_HELPER\"' EXIT\n${functions}\n${userCode}\n`.trim();\n}\n\nasync function runProgrammatic(args: {\n params: ProgrammaticParams;\n config?: { toolCall?: unknown };\n cloudflareConfig: t.CloudflareSandboxExecutionConfig;\n runtime: 'python' | 'bash';\n}): Promise<[string, t.ProgrammaticExecutionArtifact]> {\n const toolCall = (args.config?.toolCall ??\n {}) as Partial<t.ProgrammaticCache>;\n const toolDefs = toolCall.toolDefs ?? [];\n const effectiveTools = filterNativeTools(\n toolDefs,\n args.params.code,\n args.runtime\n );\n const timeoutMs = clampExecutionTimeout(\n args.params.timeout,\n args.cloudflareConfig.timeoutMs\n );\n const workspaceRoot = getCloudflareWorkspaceRoot(args.cloudflareConfig);\n let result: Awaited<ReturnType<typeof executeCloudflareCode>>;\n\n if (args.runtime === 'bash') {\n await validateCloudflareBashCommand(args.params.code, [], {\n ...args.cloudflareConfig,\n timeoutMs,\n });\n result = await executeGeneratedCloudflareBash(\n createBashProgram(\n args.params.code,\n effectiveTools,\n args.cloudflareConfig,\n workspaceRoot\n ),\n { ...args.cloudflareConfig, timeoutMs }\n );\n } else {\n result = await executeCloudflareCode(\n {\n lang: 'py',\n code: createPythonProgram(\n args.params.code,\n effectiveTools,\n args.cloudflareConfig,\n workspaceRoot\n ),\n },\n { ...args.cloudflareConfig, timeoutMs }\n );\n }\n\n if (result.exitCode !== 0 || result.timedOut) {\n throw new Error(\n result.stderr !== ''\n ? result.stderr\n : `Cloudflare ${args.runtime} programmatic execution exited with code ${result.exitCode ?? 'unknown'}`\n );\n }\n\n return formatCompletedResponse({\n status: 'completed',\n session_id: 'cloudflare-sandbox',\n stdout: result.stdout,\n stderr: result.stderr,\n files: [],\n });\n}\n\nexport function createCloudflareProgrammaticToolCallingTool(\n cloudflareConfig: t.CloudflareSandboxExecutionConfig\n): DynamicStructuredTool {\n return tool(\n async (rawParams, config) => {\n const params = rawParams as ProgrammaticParams;\n return runProgrammatic({\n params,\n config,\n cloudflareConfig,\n runtime: resolveRuntime(params),\n });\n },\n {\n name: ProgrammaticToolCallingName,\n description: `${ProgrammaticToolCallingDescription}\\n\\nCloudflare Sandbox engine: exposes the built-in coding tools inside the sandbox process. Non-coding host tools are not callable from this in-sandbox programmatic runner.`,\n schema: createCloudflareProgrammaticToolCallingSchema(cloudflareConfig),\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n\nexport function createCloudflareBashProgrammaticToolCallingTool(\n cloudflareConfig: t.CloudflareSandboxExecutionConfig\n): DynamicStructuredTool {\n return tool(\n async (rawParams, config) => {\n const params = rawParams as ProgrammaticParams;\n return runProgrammatic({\n params,\n config,\n cloudflareConfig,\n runtime: 'bash',\n });\n },\n {\n name: Constants.BASH_PROGRAMMATIC_TOOL_CALLING,\n description: `${BashProgrammaticToolCallingDescription}\\n\\nCloudflare Sandbox engine: exposes the built-in coding tools as bash functions inside the sandbox process. Non-coding host tools are not callable from this in-sandbox programmatic runner.`,\n schema:\n createCloudflareBashProgrammaticToolCallingSchema(cloudflareConfig),\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n"],"mappings":";;;;;;;AAmCA,MAAM,kBAAkB;AACxB,MAAM,cAAc;AACpB,MAAM,cAAc;AACpB,MAAM,2BAA2B;AAgCjC,MAAM,oBAAoB,IAAI,IAAY;;;;;;;;;;AAU1C,CAAC;AAED,SAAS,iBAAiB,WAAuC;CAC/D,IAAI,aAAa,QAAQ,CAAC,OAAO,SAAS,SAAS,GACjD,OAAO;CAET,OAAO,KAAK,I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AAiB,SACxB;CACA,MAAM,gBAAgB,2BAA2B,KAAK,gBAAgB;CACtE,IAAI;CAEJ,IAAI,KAAK,YAAY,QAAQ;EAC3B,MAAM,8BAA8B,KAAK,OAAO,MAAM,CAAC,GAAG;GACxD,GAAG,KAAK;GACR;EACF,CAAC;EACD,SAAS,MAAM,+BACb,kBACE,KAAK,OAAO,MACZ,gBACA,KAAK,kBACL,aACF,GACA;GAAE,GAAG,KAAK;GAAkB;EAAU,CACxC;CACF,OACE,SAAS,MAAM,sBACb;EACE,MAAM;EACN,MAAM,oBACJ,KAAK,OAAO,MACZ,gBACA,KAAK,kBACL,aACF;CACF,GACA;EAAE,GAAG,KAAK;EAAkB;CAAU,CACxC;CAGF,IAAI,OAAO,aAAa,KAAK,OAAO,UAClC,MAAM,IAAI,MACR,OAAO,WAAW,KACd,OAAO,SACP,cAAc,KAAK,QAAQ,2CAA2C,OAAO,YAAY,WAC/F;CAGF,OAAO,wBAAwB;EAC7B,QAAQ;EACR,YAAY;EACZ,QAAQ,OAAO;EACf,QAAQ,OAAO;EACf,OAAO,CAAC;CACV,CAAC;AACH;AAEA,SAAgB,4CACd,kBACuB;CACvB,OAAO,KACL,OAAO,WAAW,WAAW;EAC3B,MAAM,SAAS;EACf,OAAO,gBAAgB;GACrB;GACA;GACA;GACA,SAAS,eAAe,MAAM;EAChC,CAAC;CACH,GACA;EACE,MAAM;EACN,aAAa,GAAG,mCAAmC;EACnD,QAAQ,8CAA8C,gBAAgB;EACtE,gBAAA;CACF,CACF;AACF;AAEA,SAAgB,gDACd,kBACuB;CACvB,OAAO,KACL,OAAO,WAAW,WAAW;EAE3B,OAAO,gBAAgB;GACrB,QAAA;GACA;GACA;GACA,SAAS;EACX,CAAC;CACH,GACA;EACE,MAAA;EACA,aAAa,GAAG,uCAAuC;EACvD,QACE,kDAAkD,gBAAgB;EACpE,gBAAA;CACF,CACF;AACF"}
1
+ {"version":3,"file":"CloudflareProgrammaticToolCalling.mjs","names":[],"sources":["../../../../src/tools/cloudflare/CloudflareProgrammaticToolCalling.ts"],"sourcesContent":["import { tool } from '@langchain/core/tools';\nimport type { DynamicStructuredTool } from '@langchain/core/tools';\nimport type * as t from '@/types';\n\n/* eslint-disable no-useless-escape -- generated sandbox helper source needs escapes for emitted JS/Python string literals. */\nimport {\n formatCompletedResponse,\n normalizeToPythonIdentifier,\n ProgrammaticToolCallingDescription,\n ProgrammaticToolCallingName,\n ProgrammaticToolCallingSchema,\n filterToolsByUsage,\n} from '@/tools/ProgrammaticToolCalling';\nimport {\n BashProgrammaticToolCallingDescription,\n BashProgrammaticToolCallingSchema,\n filterBashToolsByUsage,\n normalizeToBashIdentifier,\n} from '@/tools/BashProgrammaticToolCalling';\nimport { Constants } from '@/common';\nimport {\n clientExecTimeoutMs,\n execWithClientTimeout,\n executeCloudflareCode,\n getCloudflareWorkspaceRoot,\n resolveCloudflareSandbox,\n validateCloudflareBashCommand,\n} from './CloudflareSandboxExecutionEngine';\n\ntype ProgrammaticParams = {\n code: string;\n timeout?: number;\n lang?: string;\n runtime?: string;\n language?: string;\n};\n\nconst DEFAULT_TIMEOUT = 60000;\nconst MIN_TIMEOUT = 1000;\nconst MAX_TIMEOUT = 300000;\nconst DEFAULT_MAX_OUTPUT_CHARS = 200000;\n\ntype TimeoutSchema = {\n type: 'integer';\n minimum: number;\n maximum: number;\n default: number;\n description: string;\n};\n\ntype CloudflareProgrammaticToolCallingJsonSchema = {\n type: 'object';\n properties: typeof ProgrammaticToolCallingSchema.properties & {\n timeout: TimeoutSchema;\n lang: {\n type: 'string';\n enum: readonly ['py', 'python', 'bash', 'sh'];\n default: 'bash';\n description: string;\n };\n };\n required: readonly ['code'];\n};\n\ntype CloudflareBashProgrammaticToolCallingJsonSchema = {\n type: 'object';\n properties: typeof BashProgrammaticToolCallingSchema.properties & {\n timeout: TimeoutSchema;\n };\n required: readonly ['code'];\n};\n\nconst NATIVE_TOOL_NAMES = new Set<string>([\n Constants.READ_FILE,\n Constants.WRITE_FILE,\n Constants.EDIT_FILE,\n Constants.GREP_SEARCH,\n Constants.GLOB_SEARCH,\n Constants.LIST_DIRECTORY,\n Constants.COMPILE_CHECK,\n Constants.BASH_TOOL,\n Constants.EXECUTE_CODE,\n]);\n\nfunction normalizeTimeout(timeoutMs: number | undefined): number {\n if (timeoutMs == null || !Number.isFinite(timeoutMs)) {\n return DEFAULT_TIMEOUT;\n }\n return Math.max(MIN_TIMEOUT, Math.floor(timeoutMs));\n}\n\nfunction formatTimeout(timeoutMs: number): string {\n return timeoutMs % 1000 === 0\n ? `${timeoutMs / 1000} seconds`\n : `${timeoutMs} milliseconds`;\n}\n\nfunction createTimeoutSchema(timeoutMs?: number): TimeoutSchema {\n const defaultTimeout = normalizeTimeout(timeoutMs);\n const maxTimeout = Math.max(MAX_TIMEOUT, defaultTimeout);\n return {\n type: 'integer',\n minimum: MIN_TIMEOUT,\n maximum: maxTimeout,\n default: defaultTimeout,\n description:\n 'Maximum Cloudflare Sandbox execution time in milliseconds. ' +\n `Default: ${formatTimeout(defaultTimeout)}. Max: ${formatTimeout(maxTimeout)}.`,\n };\n}\n\nfunction clampExecutionTimeout(\n requestedTimeoutMs: number | undefined,\n configuredTimeoutMs: number | undefined\n): number {\n const defaultTimeout = normalizeTimeout(configuredTimeoutMs);\n const maxTimeout = Math.max(MAX_TIMEOUT, defaultTimeout);\n if (requestedTimeoutMs == null || !Number.isFinite(requestedTimeoutMs)) {\n return defaultTimeout;\n }\n return Math.min(\n Math.max(MIN_TIMEOUT, Math.floor(requestedTimeoutMs)),\n maxTimeout\n );\n}\n\nfunction quoteShell(value: string): string {\n if (/^[A-Za-z0-9_/:=.,@%+-]+$/.test(value)) {\n return value;\n }\n const escapedQuote = String.raw`'\\''`;\n return `'${value.replace(/'/g, escapedQuote)}'`;\n}\n\nfunction truncateOutput(\n value: string,\n maxChars = DEFAULT_MAX_OUTPUT_CHARS\n): string {\n if (value.length <= maxChars) {\n return value;\n }\n const head = Math.floor(maxChars * 0.6);\n const tail = maxChars - head;\n const omitted = value.length - maxChars;\n return `${value.slice(0, head)}\\n\\n[... ${omitted} characters truncated ...]\\n\\n${value.slice(\n value.length - tail\n )}`;\n}\n\nfunction withInSandboxTimeout(command: string, timeoutMs: number): string {\n const timeoutSeconds = Math.max(1, Math.ceil(timeoutMs / 1000));\n return `timeout -k 2s ${timeoutSeconds}s ${command}`;\n}\n\nfunction outerTimeoutMs(timeoutMs: number): number {\n return timeoutMs + 5000;\n}\n\nfunction isInSandboxTimeoutExit(exitCode: number | null): boolean {\n return exitCode === 124 || exitCode === 137;\n}\n\nasync function executeGeneratedCloudflareBash(\n command: string,\n config: t.CloudflareSandboxExecutionConfig\n): ReturnType<typeof executeCloudflareCode> {\n const sandbox = await resolveCloudflareSandbox(config);\n const workspaceRoot = getCloudflareWorkspaceRoot(config);\n const shell = config.shell ?? 'bash';\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT;\n const result = await execWithClientTimeout(\n sandbox,\n withInSandboxTimeout(`${shell} -lc ${quoteShell(command)}`, timeoutMs),\n {\n cwd: workspaceRoot,\n env: config.env,\n timeout: outerTimeoutMs(timeoutMs),\n },\n clientExecTimeoutMs(timeoutMs),\n 'cloudflare bash programmatic exec'\n );\n const maxOutputChars = config.maxOutputChars ?? DEFAULT_MAX_OUTPUT_CHARS;\n return {\n stdout: truncateOutput(result.stdout, maxOutputChars),\n stderr: truncateOutput(result.stderr, maxOutputChars),\n exitCode: result.exitCode,\n timedOut: isInSandboxTimeoutExit(result.exitCode),\n };\n}\n\nfunction createCloudflareProgrammaticToolCallingSchema(\n config: t.CloudflareSandboxExecutionConfig\n): CloudflareProgrammaticToolCallingJsonSchema {\n return {\n ...ProgrammaticToolCallingSchema,\n properties: {\n ...ProgrammaticToolCallingSchema.properties,\n timeout: createTimeoutSchema(config.timeoutMs),\n lang: {\n type: 'string',\n enum: ['py', 'python', 'bash', 'sh'],\n default: 'bash',\n description:\n 'Cloudflare Sandbox runtime for orchestration code. Defaults to bash; use py/python for Python orchestration.',\n },\n },\n } as const;\n}\n\nfunction createCloudflareBashProgrammaticToolCallingSchema(\n config: t.CloudflareSandboxExecutionConfig\n): CloudflareBashProgrammaticToolCallingJsonSchema {\n return {\n ...BashProgrammaticToolCallingSchema,\n properties: {\n ...BashProgrammaticToolCallingSchema.properties,\n timeout: createTimeoutSchema(config.timeoutMs),\n },\n } as const;\n}\n\nfunction resolveRuntime(params: ProgrammaticParams): 'python' | 'bash' {\n const raw = params.lang ?? params.runtime ?? params.language ?? 'bash';\n return raw === 'py' || raw === 'python' ? 'python' : 'bash';\n}\n\nfunction filterNativeTools(\n toolDefs: t.LCTool[],\n code: string,\n runtime: 'python' | 'bash'\n): t.LCTool[] {\n const nativeDefs = toolDefs.filter((def) => NATIVE_TOOL_NAMES.has(def.name));\n const filter =\n runtime === 'bash' ? filterBashToolsByUsage : filterToolsByUsage;\n return filter(nativeDefs, code);\n}\n\nfunction indent(code: string, spaces = 4): string {\n const prefix = ' '.repeat(spaces);\n return code\n .split('\\n')\n .map((line) => (line === '' ? line : prefix + line))\n .join('\\n');\n}\n\nfunction pythonBoolean(value: boolean | undefined): 'True' | 'False' {\n return value === true ? 'True' : 'False';\n}\n\nfunction createPythonNativeToolSource(\n config: t.CloudflareSandboxExecutionConfig,\n workspaceRoot: string\n): string {\n return `\nimport asyncio, fnmatch, glob, json, os, pathlib, re, shlex, shutil, subprocess, sys, tempfile\n\nWORKSPACE = ${JSON.stringify(workspaceRoot)}\nSHELL = ${JSON.stringify(config.shell ?? 'bash')}\nREAD_ONLY = ${pythonBoolean(config.readOnly)}\nALLOW_DANGEROUS_COMMANDS = ${pythonBoolean(config.allowDangerousCommands)}\nDESTRUCTIVE_TARGET = r\"(?:/|~|\\\\$\\\\{?HOME\\\\}?|\\\\.)(?:/?\\\\.?\\\\*|/)?\"\nDANGEROUS_COMMAND_PATTERNS = [\n re.compile(r\"\\\\brm\\\\s+(?:-[^\\\\s]*[rf][^\\\\s]*\\\\s+|-[^\\\\s]*[r][^\\\\s]*\\\\s+-[^\\\\s]*[f][^\\\\s]*\\\\s+)(?:--\\\\s+)?\" + DESTRUCTIVE_TARGET + r\"\\\\s*(?:$|[;&|])\"),\n re.compile(r\"\\\\b(?:mkfs|mkswap|fdisk|parted|diskutil)\\\\b\"),\n re.compile(r\"\\\\bdd\\\\s+[^;&|]*\\\\bof=/dev/\"),\n re.compile(r\"\\\\bchmod\\\\s+-R\\\\s+(?:777|a\\\\+w)\\\\s+(?:--\\\\s+)?\" + DESTRUCTIVE_TARGET + r\"(?:$|\\\\s|[;&|])\"),\n re.compile(r\"\\\\bchown\\\\s+-R\\\\s+[^;&|]+\\\\s+(?:--\\\\s+)?\" + DESTRUCTIVE_TARGET + r\"(?:$|\\\\s|[;&|])\"),\n re.compile(r\":\\\\s*\\\\(\\\\s*\\\\)\\\\s*\\\\{\\\\s*:\\\\s*\\\\|\\\\s*:\\\\s*&\\\\s*\\\\}\\\\s*;\\\\s*:\"),\n]\nQUOTED_DESTRUCTIVE_PATTERNS = [\n re.compile(r\"\\\\brm\\\\s+(?:-[^\\\\s]*[rf][^\\\\s]*\\\\s+){1,3}(?:--\\\\s+)?[\\\\\"']\" + DESTRUCTIVE_TARGET + r\"[\\\\\"']\"),\n re.compile(r\"\\\\bchmod\\\\s+-R\\\\s+(?:777|a\\\\+w)\\\\s+(?:--\\\\s+)?[\\\\\"']\" + DESTRUCTIVE_TARGET + r\"[\\\\\"']\"),\n re.compile(r\"\\\\bchown\\\\s+-R\\\\s+[^;&|]+\\\\s+(?:--\\\\s+)?[\\\\\"']\" + DESTRUCTIVE_TARGET + r\"[\\\\\"']\"),\n]\nNESTED_SHELL_PREFIX = r\"(?:(?:ba|z|da|k)?sh|eval)\\\\s+(?:-l?c\\\\s+)?\"\nNESTED_SHELL_DESTRUCTIVE_PATTERNS = [\n re.compile(NESTED_SHELL_PREFIX + r\"[\\\\\"'][^\\\\\"']*\\\\brm\\\\s+-[^\\\\s\\\\\"']*[rf][^\\\\s\\\\\"']*\\\\s+(?:--\\\\s+)?(?:/|~|\\\\$\\\\{?HOME\\\\}?|\\\\.)\"),\n re.compile(NESTED_SHELL_PREFIX + r\"[\\\\\"'][^\\\\\"']*\\\\bchmod\\\\s+-R\\\\s+(?:777|a\\\\+w)\\\\s+(?:--\\\\s+)?(?:/|~|\\\\$\\\\{?HOME\\\\}?|\\\\.)\"),\n re.compile(NESTED_SHELL_PREFIX + r\"[\\\\\"'][^\\\\\"']*\\\\bchown\\\\s+-R\\\\s+[^;&|]+\\\\s+(?:--\\\\s+)?(?:/|~|\\\\$\\\\{?HOME\\\\}?|\\\\.)\"),\n]\nMUTATING_COMMAND_PATTERN = re.compile(r\"\\\\b(?:rm|mv|cp|touch|mkdir|rmdir|ln|truncate|tee|sed\\\\s+-i|perl\\\\s+-pi|python(?:3)?\\\\s+-c|node\\\\s+-e|npm\\\\s+(?:install|ci|update|publish)|pnpm\\\\s+(?:install|update|publish)|yarn\\\\s+(?:install|add|publish)|git\\\\s+(?:add|commit|checkout|switch|reset|clean|rebase|merge|push|pull|stash|tag|branch)|chmod|chown)\\\\b|(?:^|[^<])>\\\\s*[^&]|\\\\bcat\\\\s+[^|;&]*>\\\\s*\")\nPROTECTED_TARGET_ARG_RE = re.compile(r\"^(?:/|~|\\\\$\\\\{?HOME\\\\}?|\\\\.)(?:/?\\\\.?\\\\*|/)?$\")\nDESTRUCTIVE_OP_IN_COMMAND_RE = re.compile(r\"\\\\b(?:rm\\\\s+-[^\\\\s]*[rf]|chmod\\\\s+-R|chown\\\\s+-R)\\\\b\")\n\ndef _is_within_workspace(file_path):\n resolved = os.path.abspath(file_path)\n root = os.path.abspath(WORKSPACE)\n return os.path.commonpath([root, resolved]) == root\n\ndef _resolve(file_path=\".\"):\n raw = file_path or \".\"\n candidate = raw if os.path.isabs(raw) else os.path.join(WORKSPACE, raw)\n resolved = os.path.abspath(candidate)\n if not _is_within_workspace(resolved):\n raise ValueError(f\"Path is outside the Cloudflare sandbox workspace: {file_path}\")\n return resolved\n\ndef _assert_writable(tool_name):\n if READ_ONLY:\n raise PermissionError(f\"{tool_name} is blocked in read-only Cloudflare sandbox mode.\")\n\ndef _strip_quoted_content(command):\n output = []\n quote = None\n escaped = False\n index = 0\n while index < len(command):\n char = command[index]\n if escaped:\n escaped = False\n output.append(\" \")\n index += 1\n continue\n if char == \"\\\\\\\\\":\n escaped = True\n output.append(\" \")\n index += 1\n continue\n if quote is not None:\n if char == quote:\n quote = None\n output.append(\" \")\n index += 1\n continue\n if char in (\"'\", '\"', \"\\`\"):\n quote = char\n output.append(\" \")\n index += 1\n continue\n if char == \"#\":\n while index < len(command) and command[index] != \"\\\\n\":\n output.append(\" \")\n index += 1\n output.append(\"\\\\n\")\n index += 1\n continue\n output.append(char)\n index += 1\n return \"\".join(output)\n\ndef _validate_bash_command(command, args=None):\n errors = []\n normalized = _strip_quoted_content(command)\n if command.strip() == \"\":\n errors.append(\"Command is empty.\")\n if \"\\\\0\" in command:\n errors.append(\"Command contains a NUL byte.\")\n if not ALLOW_DANGEROUS_COMMANDS:\n if any(pattern.search(normalized) for pattern in DANGEROUS_COMMAND_PATTERNS):\n errors.append(\"Command matches a destructive command pattern.\")\n elif any(pattern.search(command) for pattern in QUOTED_DESTRUCTIVE_PATTERNS):\n errors.append(\"Command matches a destructive command pattern (quoted target).\")\n elif any(pattern.search(command) for pattern in NESTED_SHELL_DESTRUCTIVE_PATTERNS):\n errors.append(\"Command matches a destructive command pattern (nested shell payload).\")\n elif args and DESTRUCTIVE_OP_IN_COMMAND_RE.search(command):\n offending = next((str(arg) for arg in args if PROTECTED_TARGET_ARG_RE.search(str(arg))), None)\n if offending is not None:\n errors.append(f\"Command matches a destructive command pattern (protected target \\\\\"{offending}\\\\\" passed via positional arg).\")\n if READ_ONLY and MUTATING_COMMAND_PATTERN.search(normalized):\n errors.append(\"Command appears to mutate files or repository state in read-only Cloudflare sandbox mode.\")\n if errors:\n raise ValueError(\"\\\\n\".join(errors))\n\ndef _line_window(content, offset=None, limit=None):\n start = max((offset or 1) - 1, 0)\n lines = content.split(\"\\\\n\")\n selected = lines[start:] if not limit or limit <= 0 else lines[start:start + limit]\n return \"\\\\n\".join(f\"{start + idx + 1:6d}\\\\t{line}\" for idx, line in enumerate(selected))\n\ndef _run(command, timeout=None, args=None):\n _validate_bash_command(command, args=args)\n completed = subprocess.run(\n [SHELL, \"-lc\", command, \"--\"] + [str(arg) for arg in (args or [])],\n cwd=WORKSPACE,\n capture_output=True,\n text=True,\n timeout=(timeout / 1000 if timeout else None),\n )\n return {\n \"stdout\": completed.stdout,\n \"stderr\": completed.stderr,\n \"exit_code\": completed.returncode,\n }\n\ndef _format_run(result):\n text = \"\"\n if result.get(\"stdout\"):\n text += f\"stdout:\\\\n{result['stdout']}\\\\n\"\n else:\n text += \"stdout: Empty. Ensure you're writing output explicitly.\\\\n\"\n if result.get(\"stderr\"):\n text += f\"stderr:\\\\n{result['stderr']}\\\\n\"\n if result.get(\"exit_code\") not in (None, 0):\n text += f\"exit_code: {result['exit_code']}\\\\n\"\n text += f\"working_directory: {WORKSPACE}\"\n return text.strip()\n\ndef _detect_compile_command():\n if os.path.exists(os.path.join(WORKSPACE, \"tsconfig.json\")):\n return \"typescript\", \"npx --no-install tsc --noEmit\", \"tsconfig.json present\"\n package_json = os.path.join(WORKSPACE, \"package.json\")\n if os.path.exists(package_json):\n try:\n if '\"typescript\"' in open(package_json, encoding=\"utf-8\").read():\n return \"typescript\", \"npx --no-install tsc --noEmit\", \"package.json declares typescript\"\n except Exception:\n pass\n if os.path.exists(os.path.join(WORKSPACE, \"Cargo.toml\")):\n return \"rust\", \"cargo check --message-format=short\", \"Cargo.toml present\"\n if os.path.exists(os.path.join(WORKSPACE, \"go.mod\")):\n return \"go\", \"go vet ./...\", \"go.mod present\"\n if any(os.path.exists(os.path.join(WORKSPACE, name)) for name in [\"pyproject.toml\", \"setup.py\", \"setup.cfg\"]):\n return \"python-compile\", \"python3 -m py_compile $(find . -name '*.py' -not -path './.venv/*' -not -path './node_modules/*')\", \"Python project\"\n return \"unknown\", \"\", \"no recognised project marker\"\n\nasync def bash_tool(command, args=None):\n return _format_run(_run(command, args=args))\n\nasync def execute_code(lang, code, args=None):\n args = args or []\n temp_dir = tempfile.mkdtemp(prefix=\"lc-ptc-\", dir=WORKSPACE)\n try:\n def q(value):\n import shlex\n return shlex.quote(str(value))\n arg_text = \" \".join(q(arg) for arg in args)\n if lang in (\"py\", \"python\"):\n file_path = os.path.join(temp_dir, \"main.py\")\n open(file_path, \"w\", encoding=\"utf-8\").write(code)\n return _format_run(_run(f\"python3 {q(file_path)} {arg_text}\"))\n if lang in (\"js\", \"javascript\"):\n file_path = os.path.join(temp_dir, \"main.js\")\n open(file_path, \"w\", encoding=\"utf-8\").write(code)\n return _format_run(_run(f\"node {q(file_path)} {arg_text}\"))\n if lang in (\"ts\", \"typescript\"):\n file_path = os.path.join(temp_dir, \"main.ts\")\n open(file_path, \"w\", encoding=\"utf-8\").write(code)\n return _format_run(_run(f\"npx --no-install tsx {q(file_path)} {arg_text}\"))\n if lang == \"php\":\n file_path = os.path.join(temp_dir, \"main.php\")\n open(file_path, \"w\", encoding=\"utf-8\").write(code)\n return _format_run(_run(f\"php {q(file_path)} {arg_text}\"))\n if lang == \"go\":\n file_path = os.path.join(temp_dir, \"main.go\")\n open(file_path, \"w\", encoding=\"utf-8\").write(code)\n return _format_run(_run(f\"go run {q(file_path)} {arg_text}\"))\n if lang == \"rs\":\n file_path = os.path.join(temp_dir, \"main.rs\")\n open(file_path, \"w\", encoding=\"utf-8\").write(code)\n binary = os.path.join(temp_dir, \"main-rs\")\n return _format_run(_run(f\"rustc {q(file_path)} -o {q(binary)} && {q(binary)} {arg_text}\"))\n if lang == \"c\":\n file_path = os.path.join(temp_dir, \"main.c\")\n open(file_path, \"w\", encoding=\"utf-8\").write(code)\n binary = os.path.join(temp_dir, \"main-c\")\n return _format_run(_run(f\"cc {q(file_path)} -o {q(binary)} && {q(binary)} {arg_text}\"))\n if lang == \"cpp\":\n file_path = os.path.join(temp_dir, \"main.cpp\")\n open(file_path, \"w\", encoding=\"utf-8\").write(code)\n binary = os.path.join(temp_dir, \"main-cpp\")\n return _format_run(_run(f\"c++ {q(file_path)} -o {q(binary)} && {q(binary)} {arg_text}\"))\n if lang == \"java\":\n file_path = os.path.join(temp_dir, \"Main.java\")\n open(file_path, \"w\", encoding=\"utf-8\").write(code)\n return _format_run(_run(f\"javac {q(file_path)} && java -cp {q(temp_dir)} Main {arg_text}\"))\n if lang == \"r\":\n file_path = os.path.join(temp_dir, \"main.R\")\n open(file_path, \"w\", encoding=\"utf-8\").write(code)\n return _format_run(_run(f\"Rscript {q(file_path)} {arg_text}\"))\n if lang == \"d\":\n file_path = os.path.join(temp_dir, \"main.d\")\n open(file_path, \"w\", encoding=\"utf-8\").write(code)\n binary = os.path.join(temp_dir, \"main-d\")\n return _format_run(_run(f\"dmd {q(file_path)} -of={q(binary)} && {q(binary)} {arg_text}\"))\n if lang == \"f90\":\n file_path = os.path.join(temp_dir, \"main.f90\")\n open(file_path, \"w\", encoding=\"utf-8\").write(code)\n binary = os.path.join(temp_dir, \"main-f90\")\n return _format_run(_run(f\"gfortran {q(file_path)} -o {q(binary)} && {q(binary)} {arg_text}\"))\n if lang in (\"bash\", \"sh\"):\n return _format_run(_run(code, args=args))\n raise ValueError(f\"Unsupported Cloudflare sandbox runtime: {lang}\")\n finally:\n shutil.rmtree(temp_dir, ignore_errors=True)\n\nasync def read_file(path, offset=None, limit=None):\n resolved = _resolve(path)\n with open(resolved, encoding=\"utf-8\") as handle:\n return _line_window(handle.read(), offset, limit)\n\nasync def write_file(path, content):\n _assert_writable(\"write_file\")\n resolved = _resolve(path)\n os.makedirs(os.path.dirname(resolved), exist_ok=True)\n existed = os.path.exists(resolved)\n with open(resolved, \"w\", encoding=\"utf-8\") as handle:\n handle.write(content)\n return f\"{'Overwrote' if existed else 'Created'} {resolved} ({len(content)} chars).\"\n\nasync def edit_file(path, old_text=None, new_text=None, edits=None):\n _assert_writable(\"edit_file\")\n resolved = _resolve(path)\n edits = edits or [{\"old_text\": old_text, \"new_text\": new_text}]\n content = open(resolved, encoding=\"utf-8\").read()\n for edit in edits:\n old = edit.get(\"old_text\") or \"\"\n new = edit.get(\"new_text\") or \"\"\n if content.count(old) != 1:\n raise ValueError(f\"Could not locate old_text exactly once in {path}\")\n content = content.replace(old, new, 1)\n open(resolved, \"w\", encoding=\"utf-8\").write(content)\n return f\"Applied {len(edits)} edit(s) to {resolved}.\"\n\nasync def list_directory(path=\".\"):\n resolved = _resolve(path)\n entries = []\n for name in sorted(os.listdir(resolved)):\n full = os.path.join(resolved, name)\n entries.append((\"dir \" if os.path.isdir(full) else \"file\") + \"\\\\t\" + name)\n return \"\\\\n\".join(entries) or \"Directory is empty.\"\n\nasync def grep_search(pattern, path=\".\", glob=None, max_results=200):\n root = _resolve(path)\n regex = re.compile(pattern)\n out = []\n for current, dirs, files in os.walk(root):\n dirs[:] = [d for d in dirs if d not in {\".git\", \"node_modules\", \".venv\", \"dist\", \"build\"}]\n for name in files:\n rel = os.path.relpath(os.path.join(current, name), root)\n if glob and not fnmatch.fnmatch(rel, glob):\n continue\n try:\n for line_no, line in enumerate(open(os.path.join(current, name), encoding=\"utf-8\", errors=\"ignore\"), 1):\n if regex.search(line):\n out.append(f\"{os.path.join(current, name)}:{line_no}:{line.rstrip()}\")\n if len(out) >= max_results:\n return \"\\\\n\".join(out)\n except Exception:\n pass\n return \"\\\\n\".join(out) if out else \"No matches found.\"\n\nasync def glob_search(pattern, path=\".\", max_results=200):\n root = _resolve(path)\n target = pattern if os.path.isabs(pattern) else os.path.join(root, pattern)\n matches = []\n for match in glob_module.glob(target, recursive=True):\n resolved = os.path.abspath(match)\n if _is_within_workspace(resolved):\n matches.append(resolved)\n if len(matches) >= max_results:\n break\n return \"\\\\n\".join(matches) if matches else \"No files found.\"\n\nasync def compile_check(command=None, timeout_ms=None):\n kind, detected, reason = _detect_compile_command()\n command = command or detected\n if not command:\n return f\"compile_check: {reason}. Pass an explicit command to override.\"\n result = _run(command, timeout_ms)\n status = \"PASSED\" if result[\"exit_code\"] == 0 else \"FAILED\"\n return f\"compile_check ({kind}) {status} via {command}\\\\n\\\\nstdout:\\\\n{result['stdout']}\\\\nstderr:\\\\n{result['stderr']}\\\\nworking_directory: {WORKSPACE}\\\\nreason: {reason}\"\n\n# Avoid shadowing the glob_search function argument named \"glob\".\nglob_module = glob\n`.trim();\n}\n\nfunction createNodeNativeToolSource(\n config: t.CloudflareSandboxExecutionConfig,\n workspaceRoot: string\n): string {\n return `\nconst fs = require(\"fs\");\nconst fsp = fs.promises;\nconst path = require(\"path\");\nconst cp = require(\"child_process\");\n\nconst WORKSPACE = ${JSON.stringify(workspaceRoot)};\nconst SHELL = ${JSON.stringify(config.shell ?? 'bash')};\nconst READ_ONLY = ${JSON.stringify(config.readOnly === true)};\nconst ALLOW_DANGEROUS_COMMANDS = ${JSON.stringify(config.allowDangerousCommands === true)};\nconst DESTRUCTIVE_TARGET = \"(?:\\\\\\\\/|~|\\\\\\\\$\\\\\\\\{?HOME\\\\\\\\}?|\\\\\\\\.)(?:\\\\\\\\/?\\\\\\\\.?\\\\\\\\*|\\\\\\\\/)?\";\nconst DANGEROUS_COMMAND_PATTERNS = [\n new RegExp(\"\\\\\\\\brm\\\\\\\\s+(?:-[^\\\\\\\\s]*[rf][^\\\\\\\\s]*\\\\\\\\s+|-[^\\\\\\\\s]*[r][^\\\\\\\\s]*\\\\\\\\s+-[^\\\\\\\\s]*[f][^\\\\\\\\s]*\\\\\\\\s+)(?:--\\\\\\\\s+)?\" + DESTRUCTIVE_TARGET + \"\\\\\\\\s*(?:$|[;&|])\"),\n /\\\\b(?:mkfs|mkswap|fdisk|parted|diskutil)\\\\b/,\n /\\\\bdd\\\\s+[^;&|]*\\\\bof=\\\\/dev\\\\//,\n new RegExp(\"\\\\\\\\bchmod\\\\\\\\s+-R\\\\\\\\s+(?:777|a\\\\\\\\+w)\\\\\\\\s+(?:--\\\\\\\\s+)?\" + DESTRUCTIVE_TARGET + \"(?:$|\\\\\\\\s|[;&|])\"),\n new RegExp(\"\\\\\\\\bchown\\\\\\\\s+-R\\\\\\\\s+[^;&|]+\\\\\\\\s+(?:--\\\\\\\\s+)?\" + DESTRUCTIVE_TARGET + \"(?:$|\\\\\\\\s|[;&|])\"),\n /:\\\\s*\\\\(\\\\s*\\\\)\\\\s*\\\\{\\\\s*:\\\\s*\\\\|\\\\s*:\\\\s*&\\\\s*\\\\}\\\\s*;\\\\s*:/,\n];\nconst QUOTED_DESTRUCTIVE_PATTERNS = [\n new RegExp(\"\\\\\\\\brm\\\\\\\\s+(?:-[^\\\\\\\\s]*[rf][^\\\\\\\\s]*\\\\\\\\s+){1,3}(?:--\\\\\\\\s+)?[\\\\\\\"']\" + DESTRUCTIVE_TARGET + \"[\\\\\\\"']\"),\n new RegExp(\"\\\\\\\\bchmod\\\\\\\\s+-R\\\\\\\\s+(?:777|a\\\\\\\\+w)\\\\\\\\s+(?:--\\\\\\\\s+)?[\\\\\\\"']\" + DESTRUCTIVE_TARGET + \"[\\\\\\\"']\"),\n new RegExp(\"\\\\\\\\bchown\\\\\\\\s+-R\\\\\\\\s+[^;&|]+\\\\\\\\s+(?:--\\\\\\\\s+)?[\\\\\\\"']\" + DESTRUCTIVE_TARGET + \"[\\\\\\\"']\"),\n];\nconst NESTED_SHELL_PREFIX = \"(?:(?:ba|z|da|k)?sh|eval)\\\\\\\\s+(?:-l?c\\\\\\\\s+)?\";\nconst NESTED_SHELL_DESTRUCTIVE_PATTERNS = [\n new RegExp(NESTED_SHELL_PREFIX + \"[\\\\\\\"'][^\\\\\\\"']*\\\\\\\\brm\\\\\\\\s+-[^\\\\\\\\s\\\\\\\"']*[rf][^\\\\\\\\s\\\\\\\"']*\\\\\\\\s+(?:--\\\\\\\\s+)?(?:\\\\\\\\/|~|\\\\\\\\$\\\\\\\\{?HOME\\\\\\\\}?|\\\\\\\\.)\"),\n new RegExp(NESTED_SHELL_PREFIX + \"[\\\\\\\"'][^\\\\\\\"']*\\\\\\\\bchmod\\\\\\\\s+-R\\\\\\\\s+(?:777|a\\\\\\\\+w)\\\\\\\\s+(?:--\\\\\\\\s+)?(?:\\\\\\\\/|~|\\\\\\\\$\\\\\\\\{?HOME\\\\\\\\}?|\\\\\\\\.)\"),\n new RegExp(NESTED_SHELL_PREFIX + \"[\\\\\\\"'][^\\\\\\\"']*\\\\\\\\bchown\\\\\\\\s+-R\\\\\\\\s+[^;&|]+\\\\\\\\s+(?:--\\\\\\\\s+)?(?:\\\\\\\\/|~|\\\\\\\\$\\\\\\\\{?HOME\\\\\\\\}?|\\\\\\\\.)\"),\n];\nconst MUTATING_COMMAND_PATTERN = /\\\\b(?:rm|mv|cp|touch|mkdir|rmdir|ln|truncate|tee|sed\\\\s+-i|perl\\\\s+-pi|python(?:3)?\\\\s+-c|node\\\\s+-e|npm\\\\s+(?:install|ci|update|publish)|pnpm\\\\s+(?:install|update|publish)|yarn\\\\s+(?:install|add|publish)|git\\\\s+(?:add|commit|checkout|switch|reset|clean|rebase|merge|push|pull|stash|tag|branch)|chmod|chown)\\\\b|(?:^|[^<])>\\\\s*[^&]|\\\\bcat\\\\s+[^|;&]*>\\\\s*/;\nconst PROTECTED_TARGET_ARG_RE = /^(?:\\\\/|~|\\\\$\\\\{?HOME\\\\}?|\\\\.)(?:\\\\/?\\\\.?\\\\*|\\\\/)?$/;\nconst DESTRUCTIVE_OP_IN_COMMAND_RE = /\\\\b(?:rm\\\\s+-[^\\\\s]*[rf]|chmod\\\\s+-R|chown\\\\s+-R)\\\\b/;\n\nfunction resolvePath(filePath) {\n const raw = filePath || \".\";\n const candidate = path.isAbsolute(raw) ? raw : path.join(WORKSPACE, raw);\n const resolved = path.resolve(candidate);\n const root = path.resolve(WORKSPACE);\n const relative = path.relative(root, resolved);\n if (relative && (relative.startsWith(\"..\") || path.isAbsolute(relative))) {\n throw new Error(\"Path is outside the Cloudflare sandbox workspace: \" + filePath);\n }\n return resolved;\n}\n\nfunction assertWritable(toolName) {\n if (READ_ONLY) {\n throw new Error(toolName + \" is blocked in read-only Cloudflare sandbox mode.\");\n }\n}\n\nfunction stripQuotedContent(command) {\n let output = \"\";\n let quote;\n let escaped = false;\n for (let index = 0; index < command.length; index++) {\n const char = command[index];\n if (escaped) {\n escaped = false;\n output += \" \";\n continue;\n }\n if (char === \"\\\\\\\\\") {\n escaped = true;\n output += \" \";\n continue;\n }\n if (quote != null) {\n if (char === quote) quote = undefined;\n output += \" \";\n continue;\n }\n if (char === \"\\\\\\\"\" || char === \"'\" || char === \"\\`\") {\n quote = char;\n output += \" \";\n continue;\n }\n if (char === \"#\") {\n while (index < command.length && command[index] !== \"\\\\n\") {\n output += \" \";\n index += 1;\n }\n output += \"\\\\n\";\n continue;\n }\n output += char;\n }\n return output;\n}\n\nfunction validateBashCommand(command, args) {\n const errors = [];\n const normalized = stripQuotedContent(command);\n if (command.trim() === \"\") {\n errors.push(\"Command is empty.\");\n }\n if (command.includes(\"\\\\0\")) {\n errors.push(\"Command contains a NUL byte.\");\n }\n if (!ALLOW_DANGEROUS_COMMANDS) {\n if (DANGEROUS_COMMAND_PATTERNS.some((pattern) => pattern.test(normalized))) {\n errors.push(\"Command matches a destructive command pattern.\");\n } else if (QUOTED_DESTRUCTIVE_PATTERNS.some((pattern) => pattern.test(command))) {\n errors.push(\"Command matches a destructive command pattern (quoted target).\");\n } else if (NESTED_SHELL_DESTRUCTIVE_PATTERNS.some((pattern) => pattern.test(command))) {\n errors.push(\"Command matches a destructive command pattern (nested shell payload).\");\n } else if ((args || []).length > 0 && DESTRUCTIVE_OP_IN_COMMAND_RE.test(command)) {\n const offending = (args || []).map(String).find((arg) => PROTECTED_TARGET_ARG_RE.test(arg));\n if (offending !== undefined) {\n errors.push(\"Command matches a destructive command pattern (protected target \\\\\"\" + offending + \"\\\\\" passed via positional arg).\");\n }\n }\n }\n if (READ_ONLY && MUTATING_COMMAND_PATTERN.test(normalized)) {\n errors.push(\"Command appears to mutate files or repository state in read-only Cloudflare sandbox mode.\");\n }\n if (errors.length > 0) {\n throw new Error(errors.join(\"\\\\n\"));\n }\n}\n\nfunction lineWindow(content, offset, limit) {\n const start = Math.max((offset || 1) - 1, 0);\n const lines = content.split(\"\\\\n\");\n const selected = !limit || limit <= 0 ? lines.slice(start) : lines.slice(start, start + limit);\n return selected.map((line, index) => String(start + index + 1).padStart(6, \" \") + \"\\\\t\" + line).join(\"\\\\n\");\n}\n\nfunction quote(value) {\n const text = String(value);\n if (text === \"\") return \"''\";\n if (/^[A-Za-z0-9_/:=.,@%+-]+$/.test(text)) return text;\n return \"'\" + text.replace(/'/g, \"'\\\\\\\\''\") + \"'\";\n}\n\nfunction run(command, timeoutMs, args) {\n validateBashCommand(command, args);\n return new Promise((resolve) => {\n const child = cp.spawn(SHELL, [\"-lc\", command, \"--\", ...((args || []).map(String))], {\n cwd: WORKSPACE,\n env: process.env,\n });\n let stdout = \"\";\n let stderr = \"\";\n let timedOut = false;\n const timer = timeoutMs\n ? setTimeout(() => {\n timedOut = true;\n child.kill(\"SIGTERM\");\n }, timeoutMs)\n : null;\n\n child.stdout.on(\"data\", (chunk) => {\n stdout += chunk.toString();\n });\n child.stderr.on(\"data\", (chunk) => {\n stderr += chunk.toString();\n });\n child.on(\"error\", (error) => {\n if (timer) clearTimeout(timer);\n resolve({ stdout, stderr: stderr + error.message, exit_code: 1, timed_out: timedOut });\n });\n child.on(\"close\", (code) => {\n if (timer) clearTimeout(timer);\n resolve({ stdout, stderr, exit_code: timedOut ? null : code, timed_out: timedOut });\n });\n });\n}\n\nfunction formatRun(result) {\n let text = \"\";\n if (result.stdout) {\n text += \"stdout:\\\\n\" + result.stdout + \"\\\\n\";\n } else {\n text += \"stdout: Empty. Ensure you're writing output explicitly.\\\\n\";\n }\n if (result.stderr) {\n text += \"stderr:\\\\n\" + result.stderr + \"\\\\n\";\n }\n if (result.timed_out) {\n text += \"timed_out: true\\\\n\";\n }\n if (result.exit_code !== null && result.exit_code !== undefined && result.exit_code !== 0) {\n text += \"exit_code: \" + result.exit_code + \"\\\\n\";\n }\n text += \"working_directory: \" + WORKSPACE;\n return text.trim();\n}\n\nasync function detectCompileCommand() {\n async function exists(name) {\n try {\n await fsp.access(path.join(WORKSPACE, name));\n return true;\n } catch {\n return false;\n }\n }\n if (await exists(\"tsconfig.json\")) {\n return [\"typescript\", \"npx --no-install tsc --noEmit\", \"tsconfig.json present\"];\n }\n if (await exists(\"package.json\")) {\n try {\n if ((await fsp.readFile(path.join(WORKSPACE, \"package.json\"), \"utf8\")).includes('\"typescript\"')) {\n return [\"typescript\", \"npx --no-install tsc --noEmit\", \"package.json declares typescript\"];\n }\n } catch {}\n }\n if (await exists(\"Cargo.toml\")) return [\"rust\", \"cargo check --message-format=short\", \"Cargo.toml present\"];\n if (await exists(\"go.mod\")) return [\"go\", \"go vet ./...\", \"go.mod present\"];\n if (await exists(\"pyproject.toml\") || await exists(\"setup.py\") || await exists(\"setup.cfg\")) {\n return [\"python-compile\", \"python3 -m py_compile $(find . -name '*.py' -not -path './.venv/*' -not -path './node_modules/*')\", \"Python project\"];\n }\n return [\"unknown\", \"\", \"no recognised project marker\"];\n}\n\nfunction globToRegExp(pattern) {\n const escaped = pattern.replace(/[|\\\\\\\\{}()[\\\\]^$+*?.]/g, \"\\\\\\\\$&\");\n return new RegExp(\"^\" + escaped.replace(/\\\\\\\\\\\\*\\\\\\\\\\\\*/g, \".*\").replace(/\\\\\\\\\\\\*/g, \"[^/]*\") + \"$\");\n}\n\nfunction globMatch(relativePath, pattern) {\n const matcher = globToRegExp(pattern);\n return matcher.test(relativePath) || matcher.test(path.basename(relativePath));\n}\n\nasync function walkFiles(root, visit) {\n const entries = await fsp.readdir(root, { withFileTypes: true });\n for (const entry of entries) {\n const full = path.join(root, entry.name);\n if (entry.isDirectory()) {\n if ([\".git\", \"node_modules\", \".venv\", \"dist\", \"build\"].includes(entry.name)) continue;\n await walkFiles(full, visit);\n } else if (entry.isFile()) {\n await visit(full);\n }\n }\n}\n\nasync function bash_tool(payload) {\n return formatRun(await run(payload.command, undefined, payload.args));\n}\n\nasync function execute_code(payload) {\n const lang = payload.lang;\n const code = payload.code;\n const args = payload.args || [];\n const tempDir = await fsp.mkdtemp(path.join(WORKSPACE, \"lc-ptc-\"));\n try {\n const argText = args.map(quote).join(\" \");\n async function writeAndRun(fileName, command) {\n const filePath = path.join(tempDir, fileName);\n await fsp.writeFile(filePath, code, \"utf8\");\n return formatRun(await run(command(filePath, argText), undefined, []));\n }\n if (lang === \"py\" || lang === \"python\") {\n return writeAndRun(\"main.py\", (filePath, argText) => \"python3 \" + quote(filePath) + \" \" + argText);\n }\n if (lang === \"js\" || lang === \"javascript\") {\n return writeAndRun(\"main.js\", (filePath, argText) => \"node \" + quote(filePath) + \" \" + argText);\n }\n if (lang === \"ts\" || lang === \"typescript\") {\n return writeAndRun(\"main.ts\", (filePath, argText) => \"npx --no-install tsx \" + quote(filePath) + \" \" + argText);\n }\n if (lang === \"php\") {\n return writeAndRun(\"main.php\", (filePath, argText) => \"php \" + quote(filePath) + \" \" + argText);\n }\n if (lang === \"go\") {\n return writeAndRun(\"main.go\", (filePath, argText) => \"go run \" + quote(filePath) + \" \" + argText);\n }\n if (lang === \"rs\") {\n return writeAndRun(\"main.rs\", (filePath, argText) => {\n const binary = path.join(tempDir, \"main-rs\");\n return \"rustc \" + quote(filePath) + \" -o \" + quote(binary) + \" && \" + quote(binary) + \" \" + argText;\n });\n }\n if (lang === \"c\") {\n return writeAndRun(\"main.c\", (filePath, argText) => {\n const binary = path.join(tempDir, \"main-c\");\n return \"cc \" + quote(filePath) + \" -o \" + quote(binary) + \" && \" + quote(binary) + \" \" + argText;\n });\n }\n if (lang === \"cpp\") {\n return writeAndRun(\"main.cpp\", (filePath, argText) => {\n const binary = path.join(tempDir, \"main-cpp\");\n return \"c++ \" + quote(filePath) + \" -o \" + quote(binary) + \" && \" + quote(binary) + \" \" + argText;\n });\n }\n if (lang === \"java\") {\n return writeAndRun(\"Main.java\", (filePath, argText) => \"javac \" + quote(filePath) + \" && java -cp \" + quote(tempDir) + \" Main \" + argText);\n }\n if (lang === \"r\") {\n return writeAndRun(\"main.R\", (filePath, argText) => \"Rscript \" + quote(filePath) + \" \" + argText);\n }\n if (lang === \"d\") {\n return writeAndRun(\"main.d\", (filePath, argText) => {\n const binary = path.join(tempDir, \"main-d\");\n return \"dmd \" + quote(filePath) + \" -of=\" + quote(binary) + \" && \" + quote(binary) + \" \" + argText;\n });\n }\n if (lang === \"f90\") {\n return writeAndRun(\"main.f90\", (filePath, argText) => {\n const binary = path.join(tempDir, \"main-f90\");\n return \"gfortran \" + quote(filePath) + \" -o \" + quote(binary) + \" && \" + quote(binary) + \" \" + argText;\n });\n }\n if (lang === \"bash\" || lang === \"sh\") {\n return formatRun(await run(code, undefined, args));\n }\n throw new Error(\"Unsupported Cloudflare sandbox runtime: \" + lang);\n } finally {\n await fsp.rm(tempDir, { recursive: true, force: true });\n }\n}\n\nasync function read_file(payload) {\n const resolved = resolvePath(payload.path);\n return lineWindow(await fsp.readFile(resolved, \"utf8\"), payload.offset, payload.limit);\n}\n\nasync function write_file(payload) {\n assertWritable(\"write_file\");\n const resolved = resolvePath(payload.path);\n await fsp.mkdir(path.dirname(resolved), { recursive: true });\n const existed = fs.existsSync(resolved);\n await fsp.writeFile(resolved, payload.content, \"utf8\");\n return (existed ? \"Overwrote \" : \"Created \") + resolved + \" (\" + payload.content.length + \" chars).\";\n}\n\nasync function edit_file(payload) {\n assertWritable(\"edit_file\");\n const resolved = resolvePath(payload.path);\n const edits = payload.edits || [{ old_text: payload.old_text, new_text: payload.new_text }];\n let content = await fsp.readFile(resolved, \"utf8\");\n for (const edit of edits) {\n const oldText = edit.old_text || \"\";\n const newText = edit.new_text || \"\";\n if (oldText === \"\" || content.split(oldText).length - 1 !== 1) {\n throw new Error(\"Could not locate old_text exactly once in \" + payload.path);\n }\n content = content.replace(oldText, newText);\n }\n await fsp.writeFile(resolved, content, \"utf8\");\n return \"Applied \" + edits.length + \" edit(s) to \" + resolved + \".\";\n}\n\nasync function list_directory(payload) {\n const resolved = resolvePath(payload.path || \".\");\n const entries = await fsp.readdir(resolved, { withFileTypes: true });\n const lines = entries\n .sort((a, b) => a.name.localeCompare(b.name))\n .map((entry) => (entry.isDirectory() ? \"dir\" : \"file\") + \"\\\\t\" + entry.name);\n return lines.join(\"\\\\n\") || \"Directory is empty.\";\n}\n\nasync function grep_search(payload) {\n const root = resolvePath(payload.path || \".\");\n const regex = new RegExp(payload.pattern);\n const maxResults = payload.max_results || 200;\n const out = [];\n await walkFiles(root, async (filePath) => {\n if (out.length >= maxResults) return;\n const relative = path.relative(root, filePath);\n if (payload.glob && !globMatch(relative, payload.glob)) return;\n let text = \"\";\n try {\n text = await fsp.readFile(filePath, \"utf8\");\n } catch {\n return;\n }\n text.split(\"\\\\n\").forEach((line, index) => {\n if (out.length < maxResults && regex.test(line)) {\n out.push(filePath + \":\" + (index + 1) + \":\" + line);\n }\n });\n });\n return out.join(\"\\\\n\") || \"No matches found.\";\n}\n\nasync function glob_search(payload) {\n const root = resolvePath(payload.path || \".\");\n const maxResults = payload.max_results || 200;\n const out = [];\n await walkFiles(root, async (filePath) => {\n if (out.length >= maxResults) return;\n const relative = path.relative(root, filePath);\n if (globMatch(relative, payload.pattern)) out.push(filePath);\n });\n return out.join(\"\\\\n\") || \"No files found.\";\n}\n\nasync function compile_check(payload) {\n const [kind, detected, reason] = await detectCompileCommand();\n const command = payload.command || detected;\n if (!command) {\n return \"compile_check: \" + reason + \". Pass an explicit command to override.\";\n }\n const result = await run(command, payload.timeout_ms);\n const status = result.exit_code === 0 ? \"PASSED\" : \"FAILED\";\n return \"compile_check (\" + kind + \") \" + status + \" via \" + command + \"\\\\n\\\\nstdout:\\\\n\" + result.stdout + \"\\\\nstderr:\\\\n\" + result.stderr + \"\\\\nworking_directory: \" + WORKSPACE + \"\\\\nreason: \" + reason;\n}\n\nconst TOOLS = {\n bash_tool,\n execute_code,\n read_file,\n write_file,\n edit_file,\n list_directory,\n grep_search,\n glob_search,\n compile_check,\n};\n\nasync function main() {\n const name = process.argv[2];\n const payload = JSON.parse(process.argv[3] || \"{}\");\n if (!TOOLS[name]) throw new Error(\"Unknown tool: \" + name);\n const result = await TOOLS[name](payload);\n process.stdout.write(typeof result === \"string\" ? result : JSON.stringify(result));\n}\n\nmain().catch((error) => {\n console.error(error && error.stack ? error.stack : String(error));\n process.exit(1);\n});\n`.trim();\n}\n\nfunction createPythonProgram(\n userCode: string,\n toolDefs: t.LCTool[],\n config: t.CloudflareSandboxExecutionConfig,\n workspaceRoot: string\n): string {\n const aliases = toolDefs\n .map((def) => {\n const pythonName = normalizeToPythonIdentifier(def.name);\n return NATIVE_TOOL_NAMES.has(def.name) && pythonName !== def.name\n ? `${pythonName} = globals()[${JSON.stringify(def.name)}]`\n : '';\n })\n .filter(Boolean)\n .join('\\n');\n return `${createPythonNativeToolSource(config, workspaceRoot)}\n${aliases}\n\nasync def __lc_user_main__():\n${indent(userCode)}\n\nasyncio.run(__lc_user_main__())\n`;\n}\n\nfunction createBashProgram(\n userCode: string,\n toolDefs: t.LCTool[],\n config: t.CloudflareSandboxExecutionConfig,\n workspaceRoot: string\n): string {\n const helper = createNodeNativeToolSource(config, workspaceRoot);\n const functions = toolDefs\n .map((def) => {\n const bashName = normalizeToBashIdentifier(def.name);\n if (!NATIVE_TOOL_NAMES.has(def.name)) {\n return '';\n }\n return `${bashName}() { node \"$__LC_TOOL_HELPER\" ${JSON.stringify(def.name)} \"$1\"; }`;\n })\n .filter(Boolean)\n .join('\\n');\n return `\nset -euo pipefail\ncommand -v node >/dev/null 2>&1 || { echo \"Cloudflare programmatic tool calling requires node in the sandbox image.\" >&2; exit 127; }\n__LC_TOOL_HELPER=\"$(mktemp /tmp/lc-tools.XXXXXX.js)\"\ncat > \"$__LC_TOOL_HELPER\" <<'JS'\n${helper}\nJS\ntrap 'rm -f \"$__LC_TOOL_HELPER\"' EXIT\n${functions}\n${userCode}\n`.trim();\n}\n\nasync function runProgrammatic(args: {\n params: ProgrammaticParams;\n config?: { toolCall?: unknown };\n cloudflareConfig: t.CloudflareSandboxExecutionConfig;\n runtime: 'python' | 'bash';\n}): Promise<[string, t.ProgrammaticExecutionArtifact]> {\n const toolCall = (args.config?.toolCall ??\n {}) as Partial<t.ProgrammaticCache>;\n const toolDefs = toolCall.toolDefs ?? [];\n const effectiveTools = filterNativeTools(\n toolDefs,\n args.params.code,\n args.runtime\n );\n const timeoutMs = clampExecutionTimeout(\n args.params.timeout,\n args.cloudflareConfig.timeoutMs\n );\n const workspaceRoot = getCloudflareWorkspaceRoot(args.cloudflareConfig);\n let result: Awaited<ReturnType<typeof executeCloudflareCode>>;\n\n if (args.runtime === 'bash') {\n await validateCloudflareBashCommand(args.params.code, [], {\n ...args.cloudflareConfig,\n timeoutMs,\n });\n result = await executeGeneratedCloudflareBash(\n createBashProgram(\n args.params.code,\n effectiveTools,\n args.cloudflareConfig,\n workspaceRoot\n ),\n { ...args.cloudflareConfig, timeoutMs }\n );\n } else {\n result = await executeCloudflareCode(\n {\n lang: 'py',\n code: createPythonProgram(\n args.params.code,\n effectiveTools,\n args.cloudflareConfig,\n workspaceRoot\n ),\n },\n { ...args.cloudflareConfig, timeoutMs }\n );\n }\n\n if (result.exitCode !== 0 || result.timedOut) {\n throw new Error(\n result.stderr !== ''\n ? result.stderr\n : `Cloudflare ${args.runtime} programmatic execution exited with code ${result.exitCode ?? 'unknown'}`\n );\n }\n\n return formatCompletedResponse({\n status: 'completed',\n session_id: 'cloudflare-sandbox',\n stdout: result.stdout,\n stderr: result.stderr,\n files: [],\n });\n}\n\nexport function createCloudflareProgrammaticToolCallingTool(\n cloudflareConfig: t.CloudflareSandboxExecutionConfig\n): DynamicStructuredTool {\n return tool(\n async (rawParams, config) => {\n const params = rawParams as ProgrammaticParams;\n return runProgrammatic({\n params,\n config,\n cloudflareConfig,\n runtime: resolveRuntime(params),\n });\n },\n {\n name: ProgrammaticToolCallingName,\n description: `${ProgrammaticToolCallingDescription}\\n\\nCloudflare Sandbox engine: exposes the built-in coding tools inside the sandbox process. Non-coding host tools are not callable from this in-sandbox programmatic runner.`,\n schema: createCloudflareProgrammaticToolCallingSchema(cloudflareConfig),\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n\nexport function createCloudflareBashProgrammaticToolCallingTool(\n cloudflareConfig: t.CloudflareSandboxExecutionConfig\n): DynamicStructuredTool {\n return tool(\n async (rawParams, config) => {\n const params = rawParams as ProgrammaticParams;\n return runProgrammatic({\n params,\n config,\n cloudflareConfig,\n runtime: 'bash',\n });\n },\n {\n name: Constants.BASH_PROGRAMMATIC_TOOL_CALLING,\n description: `${BashProgrammaticToolCallingDescription}\\n\\nCloudflare Sandbox engine: exposes the built-in coding tools as bash functions inside the sandbox process. Non-coding host tools are not callable from this in-sandbox programmatic runner.`,\n schema:\n createCloudflareBashProgrammaticToolCallingSchema(cloudflareConfig),\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n"],"mappings":";;;;;;;AAqCA,MAAM,kBAAkB;AACxB,MAAM,cAAc;AACpB,MAAM,cAAc;AACpB,MAAM,2BAA2B;AAgCjC,MAAM,oBAAoB,IAAI,IAAY;;;;;;;;;;AAU1C,CAAC;AAED,SAAS,iBAAiB,WAAuC;CAC/D,IAAI,aAAa,QAAQ,CAAC,OAAO,SAAS,SAAS,GACjD,OAAO;CAET,OAAO,KAAK,IAAI,aAAa,KAAK,MAAM,SAAS,CAAC;AACpD;AAEA,SAAS,cAAc,WAA2B;CAChD,OAAO,YAAY,QAAS,IACxB,GAAG,YAAY,IAAK,YACpB,GAAG,UAAU;AACnB;AAEA,SAAS,oBAAoB,WAAmC;CAC9D,MAAM,iBAAiB,iBAAiB,SAAS;CACjD,MAAM,aAAa,KAAK,IAAI,aAAa,cAAc;CACvD,OAAO;EACL,MAAM;EACN,SAAS;EACT,SAAS;EACT,SAAS;EACT,aACE,uEACY,cAAc,cAAc,EAAE,SAAS,cAAc,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ACb;EACE,MAAM;EACN,MAAM,oBACJ,KAAK,OAAO,MACZ,gBACA,KAAK,kBACL,aACF;CACF,GACA;EAAE,GAAG,KAAK;EAAkB;CAAU,CACxC;CAGF,IAAI,OAAO,aAAa,KAAK,OAAO,UAClC,MAAM,IAAI,MACR,OAAO,WAAW,KACd,OAAO,SACP,cAAc,KAAK,QAAQ,2CAA2C,OAAO,YAAY,WAC/F;CAGF,OAAO,wBAAwB;EAC7B,QAAQ;EACR,YAAY;EACZ,QAAQ,OAAO;EACf,QAAQ,OAAO;EACf,OAAO,CAAC;CACV,CAAC;AACH;AAEA,SAAgB,4CACd,kBACuB;CACvB,OAAO,KACL,OAAO,WAAW,WAAW;EAC3B,MAAM,SAAS;EACf,OAAO,gBAAgB;GACrB;GACA;GACA;GACA,SAAS,eAAe,MAAM;EAChC,CAAC;CACH,GACA;EACE,MAAM;EACN,aAAa,GAAG,mCAAmC;EACnD,QAAQ,8CAA8C,gBAAgB;EACtE,gBAAA;CACF,CACF;AACF;AAEA,SAAgB,gDACd,kBACuB;CACvB,OAAO,KACL,OAAO,WAAW,WAAW;EAE3B,OAAO,gBAAgB;GACrB,QAAA;GACA;GACA;GACA,SAAS;EACX,CAAC;CACH,GACA;EACE,MAAA;EACA,aAAa,GAAG,uCAAuC;EACvD,QACE,kDAAkD,gBAAgB;EACpE,gBAAA;CACF,CACF;AACF"}
@@ -61,6 +61,76 @@ function outerTimeoutMs(timeoutMs) {
61
61
  function isInSandboxTimeoutExit(exitCode) {
62
62
  return exitCode === 124 || exitCode === 137;
63
63
  }
64
+ /**
65
+ * Client-side backstop timeout for a `sandbox.exec()` await: a few seconds beyond
66
+ * the exec's own `timeout` option, so a stalled exec that never honors `timeout`
67
+ * still can't outlast this.
68
+ */
69
+ function clientExecTimeoutMs(timeoutMs) {
70
+ return outerTimeoutMs(timeoutMs) + 5e3;
71
+ }
72
+ /**
73
+ * Bound a `sandbox.exec()` await with a CLIENT-SIDE timeout.
74
+ *
75
+ * The native Cloudflare Sandbox Durable Object `exec()` is effectively
76
+ * uncancellable from the host: `ExecOptions` has no `signal` (so
77
+ * `supportsExecSignal` is false for the native transport), and its `timeout`
78
+ * option is not reliably enforced when the container/RPC itself stalls — while
79
+ * the in-sandbox `timeout(1)` wrapper only bounds a command that is actually
80
+ * running. So a stalled exec (an unresponsive/cold container) otherwise hangs
81
+ * until the host's run-level abort, burning the whole run budget on one tool
82
+ * call. This race guarantees the host await settles within `timeoutMs`
83
+ * regardless of the transport.
84
+ *
85
+ * On timeout the underlying `exec` promise may keep running in the DO (a
86
+ * native-DO exec cannot be truly cancelled), so its late settlement is swallowed
87
+ * to avoid an unhandled rejection.
88
+ */
89
+ async function withClientTimeout(exec, timeoutMs, label, options = {}) {
90
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) return exec;
91
+ exec.catch(() => void 0);
92
+ let timer;
93
+ try {
94
+ return await Promise.race([exec, new Promise((_resolve, reject) => {
95
+ timer = setTimeout(() => {
96
+ reject(/* @__PURE__ */ new Error(`${label} exceeded ${timeoutMs}ms client-side timeout (sandbox exec did not return)`));
97
+ options.onTimeout?.();
98
+ }, timeoutMs);
99
+ if (options.unref === true) timer?.unref?.();
100
+ })]);
101
+ } finally {
102
+ if (timer !== void 0) clearTimeout(timer);
103
+ }
104
+ }
105
+ /**
106
+ * Run `sandbox.exec()` bounded by a client-side timeout, and — for signal-aware
107
+ * transports (e.g. the HTTP bridge, `supportsExecSignal === true`) — abort the
108
+ * underlying exec when the timeout fires instead of merely abandoning it. The
109
+ * native DO transport ignores `signal`, so it only gets the timeout. Leaves the
110
+ * backstop timer ref'd (this is an awaited direct-exec path).
111
+ */
112
+ async function execWithClientTimeout(sandbox, command, options, timeoutMs, label, runOptions = {}) {
113
+ const controller = new AbortController();
114
+ const execOptions = { ...options };
115
+ const callerSignal = options.signal;
116
+ let onCallerAbort;
117
+ if (sandbox.supportsExecSignal === true) {
118
+ if (callerSignal != null) if (callerSignal.aborted) controller.abort();
119
+ else {
120
+ onCallerAbort = () => controller.abort();
121
+ callerSignal.addEventListener("abort", onCallerAbort, { once: true });
122
+ }
123
+ execOptions.signal = controller.signal;
124
+ } else if ("signal" in execOptions) delete execOptions.signal;
125
+ try {
126
+ return await withClientTimeout(sandbox.exec(command, execOptions), timeoutMs, label, {
127
+ unref: runOptions.unref,
128
+ onTimeout: () => controller.abort()
129
+ });
130
+ } finally {
131
+ if (onCallerAbort != null && callerSignal != null) callerSignal.removeEventListener("abort", onCallerAbort);
132
+ }
133
+ }
64
134
  function truncateOutput(value, maxChars) {
65
135
  if (maxChars <= 0 || value.length <= maxChars) return value;
66
136
  const head = Math.max(Math.floor(maxChars / 2), 0);
@@ -298,7 +368,10 @@ function createCloudflareSpawn(config) {
298
368
  };
299
369
  if (ctx.sandbox.supportsExecSignal === true) execOptions.signal = abortController.signal;
300
370
  try {
301
- const result = await ctx.sandbox.exec(timedCommand, execOptions);
371
+ const result = await withClientTimeout(ctx.sandbox.exec(timedCommand, execOptions), clientExecTimeoutMs(timeoutMs), "cloudflare sandbox exec", {
372
+ unref: true,
373
+ onTimeout: () => abortController.abort()
374
+ });
302
375
  if (isClosed()) return;
303
376
  if (result.stdout) stdout.write(result.stdout);
304
377
  if (result.stderr) stderr.write(result.stderr);
@@ -350,11 +423,11 @@ async function executeCloudflareBash(command, config, args = []) {
350
423
  await validateCloudflareBashCommand(command, args, config);
351
424
  const ctx = await getRuntimeContext(config);
352
425
  const shellCommand = args.length > 0 ? `${ctx.shell} -lc ${quote(command)} -- ${args.map(quote).join(" ")}` : `${ctx.shell} -lc ${quote(command)}`;
353
- const result = await ctx.sandbox.exec(withInSandboxTimeout(shellCommand, ctx.timeoutMs), {
426
+ const result = await execWithClientTimeout(ctx.sandbox, withInSandboxTimeout(shellCommand, ctx.timeoutMs), {
354
427
  cwd: ctx.workspaceRoot,
355
428
  env: ctx.env,
356
429
  timeout: outerTimeoutMs(ctx.timeoutMs)
357
- });
430
+ }, clientExecTimeoutMs(ctx.timeoutMs), "cloudflare sandbox bash exec");
358
431
  return {
359
432
  stdout: truncateOutput(result.stdout, ctx.maxOutputChars),
360
433
  stderr: truncateOutput(result.stderr, ctx.maxOutputChars),
@@ -446,12 +519,14 @@ async function executeCloudflareCode(input, config) {
446
519
  const runtime = runtimeForCode(input.lang, tempDir, input.code, input.args, ctx.shell);
447
520
  await ctx.sandbox.mkdir(tempDir, { recursive: true });
448
521
  if (runtime.source != null) await ctx.sandbox.writeFile(posix.join(tempDir, runtime.fileName), runtime.source, { encoding: "utf8" });
522
+ let execSucceeded = false;
449
523
  try {
450
- const result = await ctx.sandbox.exec(withInSandboxTimeout(runtime.command, ctx.timeoutMs), {
524
+ const result = await execWithClientTimeout(ctx.sandbox, withInSandboxTimeout(runtime.command, ctx.timeoutMs), {
451
525
  cwd: ctx.workspaceRoot,
452
526
  env: ctx.env,
453
527
  timeout: outerTimeoutMs(ctx.timeoutMs)
454
- });
528
+ }, clientExecTimeoutMs(ctx.timeoutMs), "cloudflare sandbox code-exec");
529
+ execSucceeded = true;
455
530
  return {
456
531
  stdout: truncateOutput(result.stdout, ctx.maxOutputChars),
457
532
  stderr: truncateOutput(result.stderr, ctx.maxOutputChars),
@@ -459,11 +534,13 @@ async function executeCloudflareCode(input, config) {
459
534
  timedOut: isInSandboxTimeoutExit(result.exitCode)
460
535
  };
461
536
  } finally {
462
- await ctx.sandbox.exec(`rm -rf ${quote(tempDir)}`, {
537
+ const detach = !execSucceeded;
538
+ const cleanup = execWithClientTimeout(ctx.sandbox, `rm -rf ${quote(tempDir)}`, {
463
539
  cwd: ctx.workspaceRoot,
464
540
  env: ctx.env,
465
541
  timeout: 1e4
466
- }).catch(() => void 0);
542
+ }, clientExecTimeoutMs(1e4), "cloudflare sandbox cleanup", { unref: detach }).catch(() => void 0);
543
+ if (!detach) await cleanup;
467
544
  }
468
545
  }
469
546
  function formatCloudflareOutput(result, cwd) {
@@ -477,6 +554,6 @@ function formatCloudflareOutput(result, cwd) {
477
554
  return formatted.trim();
478
555
  }
479
556
  //#endregion
480
- export { createCloudflareLocalExecutionConfig, createCloudflareWorkspaceFS, executeCloudflareBash, executeCloudflareCode, formatCloudflareOutput, getCloudflareWorkspaceRoot, resolveCloudflareSandbox, validateCloudflareBashCommand };
557
+ export { clientExecTimeoutMs, createCloudflareLocalExecutionConfig, createCloudflareWorkspaceFS, execWithClientTimeout, executeCloudflareBash, executeCloudflareCode, formatCloudflareOutput, getCloudflareWorkspaceRoot, resolveCloudflareSandbox, validateCloudflareBashCommand, withClientTimeout };
481
558
 
482
559
  //# sourceMappingURL=CloudflareSandboxExecutionEngine.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"CloudflareSandboxExecutionEngine.mjs","names":["path"],"sources":["../../../../src/tools/cloudflare/CloudflareSandboxExecutionEngine.ts"],"sourcesContent":["import { PassThrough } from 'stream';\nimport { posix as path } from 'path';\nimport { EventEmitter } from 'events';\nimport type { WriteFileOptions, MakeDirectoryOptions, Stats } from 'fs';\nimport type { ChildProcessWithoutNullStreams } from 'child_process';\nimport type { FileHandle } from 'fs/promises';\nimport type { WorkspaceFS, ReaddirEntry } from '@/tools/local/workspaceFS';\nimport type * as t from '@/types';\nimport {\n LOCAL_SPAWN_TIMEOUT_MS,\n validateBashCommand,\n} from '@/tools/local/LocalExecutionEngine';\n\nconst DEFAULT_WORKSPACE_ROOT = '/workspace';\nconst DEFAULT_TIMEOUT_MS = 60000;\nconst DEFAULT_MAX_OUTPUT_CHARS = 200000;\nconst PROTECTED_TARGET_ARG_RE = /^(?:\\/|~|\\$\\{?HOME\\}?|\\.)(?:\\/?\\.?\\*|\\/)?$/;\nconst DESTRUCTIVE_OP_IN_COMMAND_RE =\n /\\b(?:rm\\s+-[^\\s]*[rf]|chmod\\s+-R|chown\\s+-R)\\b/;\n\ntype SpawnResult = {\n stdout: string;\n stderr: string;\n exitCode: number | null;\n timedOut: boolean;\n};\n\ntype RuntimeCommand = {\n fileName: string;\n source?: string;\n command: string;\n};\n\ntype SandboxRuntimeContext = {\n sandbox: t.CloudflareSandboxRuntime;\n workspaceRoot: string;\n env?: Record<string, string | undefined>;\n timeoutMs: number;\n maxOutputChars: number;\n shell: string;\n};\n\nconst sandboxFactoryCache = new WeakMap<\n t.CloudflareSandboxExecutionConfig,\n Promise<t.CloudflareSandboxRuntime>\n>();\n\nfunction normalizeWorkspaceRoot(workspaceRoot: string): string {\n const normalized = path.normalize(workspaceRoot);\n return normalized === '/' ? normalized : normalized.replace(/\\/+$/, '');\n}\n\nexport function getCloudflareWorkspaceRoot(\n config?: t.CloudflareSandboxExecutionConfig\n): string {\n return normalizeWorkspaceRoot(\n config?.workspaceRoot ?? DEFAULT_WORKSPACE_ROOT\n );\n}\n\nexport async function resolveCloudflareSandbox(\n config: t.CloudflareSandboxExecutionConfig\n): Promise<t.CloudflareSandboxRuntime> {\n const sandbox = config.sandbox;\n if (typeof sandbox !== 'function') {\n return sandbox;\n }\n let cached = sandboxFactoryCache.get(config);\n if (cached == null) {\n cached = Promise.resolve()\n .then(() => sandbox())\n .catch((error: unknown) => {\n sandboxFactoryCache.delete(config);\n throw error;\n });\n sandboxFactoryCache.set(config, cached);\n }\n return cached;\n}\n\nasync function getRuntimeContext(\n config: t.CloudflareSandboxExecutionConfig\n): Promise<SandboxRuntimeContext> {\n return {\n sandbox: await resolveCloudflareSandbox(config),\n workspaceRoot: getCloudflareWorkspaceRoot(config),\n env: config.env,\n timeoutMs: config.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n maxOutputChars: config.maxOutputChars ?? DEFAULT_MAX_OUTPUT_CHARS,\n shell: config.shell ?? 'bash',\n };\n}\n\nfunction toSandboxPath(filePath: string, workspaceRoot: string): string {\n const raw = filePath === '' ? '.' : filePath;\n const root = normalizeWorkspaceRoot(workspaceRoot);\n const resolved = raw.startsWith('/')\n ? path.normalize(raw)\n : path.resolve(root, raw);\n if (root === '/') {\n return resolved;\n }\n if (resolved === root || resolved.startsWith(`${root}/`)) {\n return resolved;\n }\n throw new Error(\n `Path is outside the Cloudflare sandbox workspace: ${filePath}`\n );\n}\n\nfunction quote(value: string): string {\n if (value === '') {\n return '\\'\\'';\n }\n if (/^[A-Za-z0-9_/:=.,@%+-]+$/.test(value)) {\n return value;\n }\n return `'${value.replace(/'/g, '\\'\\\\\\'\\'')}'`;\n}\n\nfunction withInSandboxTimeout(command: string, timeoutMs: number): string {\n const timeoutSeconds = Math.max(1, Math.ceil(timeoutMs / 1000));\n return `timeout -k 2s ${timeoutSeconds}s ${command}`;\n}\n\nfunction outerTimeoutMs(timeoutMs: number): number {\n return timeoutMs + 5000;\n}\n\nfunction isInSandboxTimeoutExit(exitCode: number | null): boolean {\n return exitCode === 124 || exitCode === 137;\n}\n\nfunction truncateOutput(value: string, maxChars: number): string {\n if (maxChars <= 0 || value.length <= maxChars) {\n return value;\n }\n const head = Math.max(Math.floor(maxChars / 2), 0);\n const tail = Math.max(maxChars - head, 0);\n return `${value.slice(0, head)}\\n...[truncated ${value.length - maxChars} chars]...\\n${value.slice(value.length - tail)}`;\n}\n\nasync function readStream(stream: ReadableStream<Uint8Array>): Promise<Buffer> {\n const reader = stream.getReader();\n const chunks: Uint8Array[] = [];\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n chunks.push(value);\n }\n } finally {\n reader.releaseLock();\n }\n return Buffer.concat(chunks.map((chunk) => Buffer.from(chunk)));\n}\n\nasync function normalizeReadFileContent(\n result: t.CloudflareSandboxReadFileResult\n): Promise<Buffer> {\n if (typeof result === 'string') {\n return Buffer.from(result, 'utf8');\n }\n if (Buffer.isBuffer(result)) {\n return result;\n }\n if (result instanceof Uint8Array) {\n return Buffer.from(result);\n }\n const content = result.content;\n if (typeof content === 'string') {\n if (result.encoding === 'base64') {\n return Buffer.from(content, 'base64');\n }\n return Buffer.from(content, 'utf8');\n }\n if (Buffer.isBuffer(content)) {\n return content;\n }\n if (content instanceof Uint8Array) {\n return Buffer.from(content);\n }\n return readStream(content);\n}\n\nfunction bytesToStream(bytes: Uint8Array): ReadableStream<Uint8Array> {\n return new ReadableStream<Uint8Array>({\n start(controller): void {\n controller.enqueue(bytes);\n controller.close();\n },\n });\n}\n\nfunction normalizeWriteFileContent(content: string | Buffer | Uint8Array): {\n content: string | ReadableStream<Uint8Array>;\n options?: { encoding?: string };\n} {\n if (typeof content === 'string') {\n return { content, options: { encoding: 'utf8' } };\n }\n return { content: bytesToStream(content) };\n}\n\nfunction createStats(info: {\n size?: number;\n type?: t.CloudflareSandboxFileInfo['type'];\n}): Stats {\n const type = info.type ?? 'file';\n const now = new Date();\n return {\n size: info.size ?? 0,\n isFile: () => type === 'file',\n isDirectory: () => type === 'directory',\n isSymbolicLink: () => type === 'symlink',\n isBlockDevice: () => false,\n isCharacterDevice: () => false,\n isFIFO: () => false,\n isSocket: () => false,\n dev: 0,\n ino: 0,\n mode: 0,\n nlink: 1,\n uid: 0,\n gid: 0,\n rdev: 0,\n blksize: 0,\n blocks: 0,\n atimeMs: now.getTime(),\n mtimeMs: now.getTime(),\n ctimeMs: now.getTime(),\n birthtimeMs: now.getTime(),\n atime: now,\n mtime: now,\n ctime: now,\n birthtime: now,\n } as Stats;\n}\n\nfunction normalizeFileList(\n result: t.CloudflareSandboxListFilesResult\n): t.CloudflareSandboxFileInfo[] {\n return Array.isArray(result) ? result : result.files;\n}\n\nfunction entryNameFor(\n info: t.CloudflareSandboxFileInfo,\n parentPath: string\n): string {\n if (info.name !== '') {\n return info.name.includes('/') ? path.basename(info.name) : info.name;\n }\n if (info.absolutePath != null && info.absolutePath !== '') {\n return path.basename(info.absolutePath);\n }\n if (info.relativePath != null && info.relativePath !== '') {\n return path.basename(info.relativePath);\n }\n return path.basename(parentPath);\n}\n\nfunction entryAbsolutePath(\n info: t.CloudflareSandboxFileInfo,\n parentPath: string\n): string {\n if (info.absolutePath != null && info.absolutePath !== '') {\n return path.normalize(info.absolutePath);\n }\n if (info.relativePath != null && info.relativePath !== '') {\n return path.resolve(parentPath, info.relativePath);\n }\n return path.resolve(parentPath, info.name);\n}\n\nfunction createDirent(info: t.CloudflareSandboxFileInfo): ReaddirEntry {\n return {\n name: entryNameFor(info, ''),\n isFile: () => (info.type ?? 'file') === 'file',\n isDirectory: () => info.type === 'directory',\n isSymbolicLink: () => info.type === 'symlink',\n };\n}\n\nasync function findChildInfo(\n sandbox: t.CloudflareSandboxRuntime,\n filePath: string\n): Promise<t.CloudflareSandboxFileInfo | undefined> {\n const parent = path.dirname(filePath);\n const basename = path.basename(filePath);\n const entries = normalizeFileList(\n await sandbox.listFiles(parent, { includeHidden: true })\n );\n return entries.find((entry) => {\n const absolute = entryAbsolutePath(entry, parent);\n return absolute === filePath || entryNameFor(entry, parent) === basename;\n });\n}\n\nexport function createCloudflareWorkspaceFS(\n config: t.CloudflareSandboxExecutionConfig\n): WorkspaceFS {\n const workspaceRoot = getCloudflareWorkspaceRoot(config);\n\n const fs: WorkspaceFS = {\n readFile: (async (filePath: string, encoding?: 'utf8') => {\n const sandbox = await resolveCloudflareSandbox(config);\n const resolved = toSandboxPath(filePath, workspaceRoot);\n const buffer = await normalizeReadFileContent(\n await sandbox.readFile(resolved, encoding ? { encoding } : undefined)\n );\n return encoding != null ? buffer.toString(encoding) : buffer;\n }) as WorkspaceFS['readFile'],\n writeFile: async (\n filePath: string,\n content: string | Buffer,\n _options?: WriteFileOptions\n ) => {\n const sandbox = await resolveCloudflareSandbox(config);\n const resolved = toSandboxPath(filePath, workspaceRoot);\n const normalized = normalizeWriteFileContent(content);\n await sandbox.writeFile(resolved, normalized.content, normalized.options);\n },\n stat: async (filePath: string) => {\n const sandbox = await resolveCloudflareSandbox(config);\n const resolved = toSandboxPath(filePath, workspaceRoot);\n if (resolved === workspaceRoot) {\n const entries = normalizeFileList(\n await sandbox.listFiles(resolved, { includeHidden: true })\n );\n return createStats({ size: entries.length, type: 'directory' });\n }\n const info = await findChildInfo(sandbox, resolved);\n if (info != null) {\n return createStats({ size: info.size, type: info.type });\n }\n try {\n const entries = normalizeFileList(\n await sandbox.listFiles(resolved, { includeHidden: true })\n );\n return createStats({ size: entries.length, type: 'directory' });\n } catch {\n const buffer = await normalizeReadFileContent(\n await sandbox.readFile(resolved)\n );\n return createStats({ size: buffer.length, type: 'file' });\n }\n },\n readdir: (async (filePath: string, options?: { withFileTypes: true }) => {\n const sandbox = await resolveCloudflareSandbox(config);\n const resolved = toSandboxPath(filePath, workspaceRoot);\n const entries = normalizeFileList(\n await sandbox.listFiles(resolved, { includeHidden: true })\n );\n if (options?.withFileTypes === true) {\n return entries.map(createDirent);\n }\n return entries.map((entry) => entryNameFor(entry, resolved));\n }) as WorkspaceFS['readdir'],\n mkdir: async (filePath: string, options?: MakeDirectoryOptions) => {\n const sandbox = await resolveCloudflareSandbox(config);\n await sandbox.mkdir(toSandboxPath(filePath, workspaceRoot), {\n recursive: options?.recursive,\n });\n },\n realpath: async (filePath: string) =>\n toSandboxPath(filePath, workspaceRoot),\n unlink: async (filePath: string) => {\n const sandbox = await resolveCloudflareSandbox(config);\n await sandbox.deleteFile(toSandboxPath(filePath, workspaceRoot));\n },\n open: async (filePath: string, _flags: 'r') => {\n const sandbox = await resolveCloudflareSandbox(config);\n const resolved = toSandboxPath(filePath, workspaceRoot);\n const buffer = await normalizeReadFileContent(\n await sandbox.readFile(resolved)\n );\n return {\n read: async (\n target: Buffer,\n offset: number,\n length: number,\n position: number\n ) => {\n const start = Math.max(position, 0);\n const slice = buffer.subarray(start, start + length);\n slice.copy(target, offset);\n return { bytesRead: slice.length, buffer: target };\n },\n close: async () => undefined,\n } as unknown as FileHandle;\n },\n };\n\n return fs;\n}\n\nfunction createCloudflareSpawn(\n config: t.CloudflareSandboxExecutionConfig\n): t.LocalSpawn {\n return (command, args, options) => {\n const stdout = new PassThrough();\n const stderr = new PassThrough();\n const child = new EventEmitter() as ChildProcessWithoutNullStreams;\n const abortController = new AbortController();\n const state = { closed: false };\n /** Read through a function so concurrent `closeOnce` mutation (via\n * `kill()`/abort during an `await`) isn't statically narrowed away. */\n const isClosed = (): boolean => state.closed;\n const closeOnce = (\n exitCode: number | null,\n signal: NodeJS.Signals | null\n ): void => {\n if (state.closed) {\n return;\n }\n state.closed = true;\n stdout.end();\n stderr.end();\n Object.assign(child, {\n exitCode,\n signalCode: signal,\n });\n child.emit('close', exitCode, signal);\n };\n Object.assign(child, {\n stdout,\n stderr,\n stdin: new PassThrough(),\n stdio: [null, stdout, stderr],\n killed: false,\n exitCode: null,\n signalCode: null,\n pid: undefined,\n kill: (signal: NodeJS.Signals = 'SIGTERM') => {\n Object.assign(child, { killed: true, signalCode: signal });\n abortController.abort();\n closeOnce(null, signal);\n return true;\n },\n });\n\n void (async (): Promise<void> => {\n const ctx = await getRuntimeContext(config);\n const rendered = [command, ...args].map(quote).join(' ');\n const spawnTimeoutMs = (\n options as {\n [LOCAL_SPAWN_TIMEOUT_MS]?: number;\n }\n )[LOCAL_SPAWN_TIMEOUT_MS];\n const timeoutMs =\n typeof spawnTimeoutMs === 'number' && Number.isFinite(spawnTimeoutMs)\n ? spawnTimeoutMs\n : ctx.timeoutMs;\n const timedCommand = withInSandboxTimeout(rendered, timeoutMs);\n const cwd =\n options.cwd == null ? ctx.workspaceRoot : options.cwd.toString();\n if (isClosed()) {\n return;\n }\n const execOptions: t.CloudflareSandboxExecOptions = {\n cwd,\n env: ctx.env,\n timeout: outerTimeoutMs(timeoutMs),\n };\n if (ctx.sandbox.supportsExecSignal === true) {\n execOptions.signal = abortController.signal;\n }\n try {\n const result = await ctx.sandbox.exec(timedCommand, execOptions);\n if (isClosed()) {\n return;\n }\n if (result.stdout) stdout.write(result.stdout);\n if (result.stderr) stderr.write(result.stderr);\n closeOnce(result.exitCode, null);\n } catch (error) {\n if (isClosed()) {\n return;\n }\n stderr.write((error as Error).message);\n closeOnce(1, null);\n }\n })();\n\n return child;\n };\n}\n\nexport function createCloudflareLocalExecutionConfig(\n config: t.CloudflareSandboxExecutionConfig\n): t.LocalExecutionConfig {\n const workspaceRoot = getCloudflareWorkspaceRoot(config);\n return {\n cwd: workspaceRoot,\n workspace: { root: workspaceRoot },\n exec: {\n spawn: createCloudflareSpawn(config),\n fs: createCloudflareWorkspaceFS(config),\n sandboxed: true,\n },\n shell: config.shell ?? 'bash',\n timeoutMs: config.timeoutMs,\n maxOutputChars: config.maxOutputChars,\n env: config.env,\n includeCodingTools: config.includeCodingTools,\n compileCheck: config.compileCheck,\n readOnly: config.readOnly,\n allowDangerousCommands: config.allowDangerousCommands,\n bashAst: config.bashAst,\n fileCheckpointing: config.fileCheckpointing,\n maxReadBytes: config.maxReadBytes,\n attachReadAttachments: config.attachReadAttachments,\n maxAttachmentBytes: config.maxAttachmentBytes,\n postEditSyntaxCheck: config.postEditSyntaxCheck,\n };\n}\n\nexport async function validateCloudflareBashCommand(\n command: string,\n args: readonly string[],\n config: t.CloudflareSandboxExecutionConfig\n): Promise<void> {\n const localConfig = createCloudflareLocalExecutionConfig(config);\n const validation = await validateBashCommand(command, localConfig);\n if (!validation.valid) {\n throw new Error(validation.errors.join('\\n'));\n }\n\n if (\n args.length > 0 &&\n config.allowDangerousCommands !== true &&\n DESTRUCTIVE_OP_IN_COMMAND_RE.test(command)\n ) {\n const offending = args.find((arg) => PROTECTED_TARGET_ARG_RE.test(arg));\n if (offending !== undefined) {\n throw new Error(\n `Command matches a destructive command pattern (protected target \"${offending}\" passed via positional arg).`\n );\n }\n }\n}\n\nexport async function executeCloudflareBash(\n command: string,\n config: t.CloudflareSandboxExecutionConfig,\n args: readonly string[] = []\n): Promise<SpawnResult> {\n await validateCloudflareBashCommand(command, args, config);\n const ctx = await getRuntimeContext(config);\n const shellCommand =\n args.length > 0\n ? `${ctx.shell} -lc ${quote(command)} -- ${args.map(quote).join(' ')}`\n : `${ctx.shell} -lc ${quote(command)}`;\n const result = await ctx.sandbox.exec(\n withInSandboxTimeout(shellCommand, ctx.timeoutMs),\n {\n cwd: ctx.workspaceRoot,\n env: ctx.env,\n timeout: outerTimeoutMs(ctx.timeoutMs),\n }\n );\n return {\n stdout: truncateOutput(result.stdout, ctx.maxOutputChars),\n stderr: truncateOutput(result.stderr, ctx.maxOutputChars),\n exitCode: result.exitCode,\n timedOut: isInSandboxTimeoutExit(result.exitCode),\n };\n}\n\nfunction runtimeForCode(\n lang: string,\n tempDir: string,\n code: string,\n args: string[] = [],\n shell = 'bash'\n): RuntimeCommand {\n const fileFor = (name: string): string => path.join(tempDir, name);\n const argText = args.map(quote).join(' ');\n switch (lang) {\n case 'py':\n case 'python':\n return {\n fileName: 'main.py',\n source: code,\n command: `python3 ${quote(fileFor('main.py'))} ${argText}`,\n };\n case 'js':\n case 'javascript':\n return {\n fileName: 'main.js',\n source: code,\n command: `node ${quote(fileFor('main.js'))} ${argText}`,\n };\n case 'ts':\n case 'typescript':\n return {\n fileName: 'main.ts',\n source: code,\n command: `npx --no-install tsx ${quote(fileFor('main.ts'))} ${argText}`,\n };\n case 'php':\n return {\n fileName: 'main.php',\n source: code,\n command: `php ${quote(fileFor('main.php'))} ${argText}`,\n };\n case 'go':\n return {\n fileName: 'main.go',\n source: code,\n command: `go run ${quote(fileFor('main.go'))} ${argText}`,\n };\n case 'rs':\n return {\n fileName: 'main.rs',\n source: code,\n command: `${shell} -lc ${quote(\n `rustc ${quote(fileFor('main.rs'))} -o ${quote(fileFor('main-rs'))} && ${quote(fileFor('main-rs'))} ${argText}`\n )}`,\n };\n case 'c':\n return {\n fileName: 'main.c',\n source: code,\n command: `${shell} -lc ${quote(\n `cc ${quote(fileFor('main.c'))} -o ${quote(fileFor('main-c'))} && ${quote(fileFor('main-c'))} ${argText}`\n )}`,\n };\n case 'cpp':\n return {\n fileName: 'main.cpp',\n source: code,\n command: `${shell} -lc ${quote(\n `c++ ${quote(fileFor('main.cpp'))} -o ${quote(fileFor('main-cpp'))} && ${quote(fileFor('main-cpp'))} ${argText}`\n )}`,\n };\n case 'java':\n return {\n fileName: 'Main.java',\n source: code,\n command: `${shell} -lc ${quote(\n `javac ${quote(fileFor('Main.java'))} && java -cp ${quote(tempDir)} Main ${argText}`\n )}`,\n };\n case 'r':\n return {\n fileName: 'main.R',\n source: code,\n command: `Rscript ${quote(fileFor('main.R'))} ${argText}`,\n };\n case 'd':\n return {\n fileName: 'main.d',\n source: code,\n command: `${shell} -lc ${quote(\n `dmd ${quote(fileFor('main.d'))} -of=${quote(fileFor('main-d'))} && ${quote(fileFor('main-d'))} ${argText}`\n )}`,\n };\n case 'f90':\n return {\n fileName: 'main.f90',\n source: code,\n command: `${shell} -lc ${quote(\n `gfortran ${quote(fileFor('main.f90'))} -o ${quote(fileFor('main-f90'))} && ${quote(fileFor('main-f90'))} ${argText}`\n )}`,\n };\n case 'bash':\n case 'sh':\n return {\n fileName: 'main.sh',\n source: code,\n command: `${shell} -lc ${quote(code)} -- ${argText}`,\n };\n default:\n throw new Error(`Unsupported Cloudflare sandbox runtime: ${lang}`);\n }\n}\n\nexport async function executeCloudflareCode(\n input: { lang: string; code: string; args?: string[] },\n config: t.CloudflareSandboxExecutionConfig\n): Promise<SpawnResult> {\n if (input.lang === 'bash' || input.lang === 'sh') {\n return executeCloudflareBash(input.code, config, input.args ?? []);\n }\n const ctx = await getRuntimeContext(config);\n const id = globalThis.crypto.randomUUID();\n const tempDir = path.join(ctx.workspaceRoot, '.lc-exec', id);\n const runtime = runtimeForCode(\n input.lang,\n tempDir,\n input.code,\n input.args,\n ctx.shell\n );\n await ctx.sandbox.mkdir(tempDir, { recursive: true });\n if (runtime.source != null) {\n await ctx.sandbox.writeFile(\n path.join(tempDir, runtime.fileName),\n runtime.source,\n {\n encoding: 'utf8',\n }\n );\n }\n try {\n const result = await ctx.sandbox.exec(\n withInSandboxTimeout(runtime.command, ctx.timeoutMs),\n {\n cwd: ctx.workspaceRoot,\n env: ctx.env,\n timeout: outerTimeoutMs(ctx.timeoutMs),\n }\n );\n return {\n stdout: truncateOutput(result.stdout, ctx.maxOutputChars),\n stderr: truncateOutput(result.stderr, ctx.maxOutputChars),\n exitCode: result.exitCode,\n timedOut: isInSandboxTimeoutExit(result.exitCode),\n };\n } finally {\n await ctx.sandbox\n .exec(`rm -rf ${quote(tempDir)}`, {\n cwd: ctx.workspaceRoot,\n env: ctx.env,\n timeout: 10000,\n })\n .catch(() => undefined);\n }\n}\n\nexport function formatCloudflareOutput(\n result: SpawnResult,\n cwd: string\n): string {\n let formatted = '';\n if (result.stdout !== '') {\n formatted += `stdout:\\n${result.stdout}\\n`;\n } else {\n formatted += 'stdout: Empty. Ensure you\\'re writing output explicitly.\\n';\n }\n if (result.stderr !== '') {\n formatted += `stderr:\\n${result.stderr}\\n`;\n }\n if (result.exitCode != null && result.exitCode !== 0) {\n formatted += `exit_code: ${result.exitCode}\\n`;\n }\n if (result.timedOut) {\n formatted += 'timed_out: true\\n';\n }\n formatted += `working_directory: ${cwd}`;\n return formatted.trim();\n}\n"],"mappings":";;;;;AAaA,MAAM,yBAAyB;AAC/B,MAAM,qBAAqB;AAC3B,MAAM,2BAA2B;AACjC,MAAM,0BAA0B;AAChC,MAAM,+BACJ;AAwBF,MAAM,sCAAsB,IAAI,QAG9B;AAEF,SAAS,uBAAuB,eAA+B;CAC7D,MAAM,aAAaA,MAAK,UAAU,aAAa;CAC/C,OAAO,eAAe,MAAM,aAAa,WAAW,QAAQ,QAAQ,EAAE;AACxE;AAEA,SAAgB,2BACd,QACQ;CACR,OAAO,uBACL,QAAQ,iBAAiB,sBAC3B;AACF;AAEA,eAAsB,yBACpB,QACqC;CACrC,MAAM,UAAU,OAAO;CACvB,IAAI,OAAO,YAAY,YACrB,OAAO;CAET,IAAI,SAAS,oBAAoB,IAAI,MAAM;CAC3C,IAAI,UAAU,MAAM;EAClB,SAAS,QAAQ,QAAQ,CAAC,CACvB,WAAW,QAAQ,CAAC,CAAC,CACrB,OAAO,UAAmB;GACzB,oBAAoB,OAAO,MAAM;GACjC,MAAM;EACR,CAAC;EACH,oBAAoB,IAAI,QAAQ,MAAM;CACxC;CACA,OAAO;AACT;AAEA,eAAe,kBACb,QACgC;CAChC,OAAO;EACL,SAAS,MAAM,yBAAyB,MAAM;EAC9C,eA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UAAU,MAAM,OAAO,KAAK;GAChC,KAAK,IAAI;GACT,KAAK,IAAI;GACT,SAAS;EACX,CAAC,CAAC,CACD,YAAY,KAAA,CAAS;CAC1B;AACF;AAEA,SAAgB,uBACd,QACA,KACQ;CACR,IAAI,YAAY;CAChB,IAAI,OAAO,WAAW,IACpB,aAAa,YAAY,OAAO,OAAO;MAEvC,aAAa;CAEf,IAAI,OAAO,WAAW,IACpB,aAAa,YAAY,OAAO,OAAO;CAEzC,IAAI,OAAO,YAAY,QAAQ,OAAO,aAAa,GACjD,aAAa,cAAc,OAAO,SAAS;CAE7C,IAAI,OAAO,UACT,aAAa;CAEf,aAAa,sBAAsB;CACnC,OAAO,UAAU,KAAK;AACxB"}
1
+ {"version":3,"file":"CloudflareSandboxExecutionEngine.mjs","names":["path"],"sources":["../../../../src/tools/cloudflare/CloudflareSandboxExecutionEngine.ts"],"sourcesContent":["import { PassThrough } from 'stream';\nimport { posix as path } from 'path';\nimport { EventEmitter } from 'events';\nimport type { WriteFileOptions, MakeDirectoryOptions, Stats } from 'fs';\nimport type { ChildProcessWithoutNullStreams } from 'child_process';\nimport type { FileHandle } from 'fs/promises';\nimport type { WorkspaceFS, ReaddirEntry } from '@/tools/local/workspaceFS';\nimport type * as t from '@/types';\nimport {\n LOCAL_SPAWN_TIMEOUT_MS,\n validateBashCommand,\n} from '@/tools/local/LocalExecutionEngine';\n\nconst DEFAULT_WORKSPACE_ROOT = '/workspace';\nconst DEFAULT_TIMEOUT_MS = 60000;\nconst DEFAULT_MAX_OUTPUT_CHARS = 200000;\nconst PROTECTED_TARGET_ARG_RE = /^(?:\\/|~|\\$\\{?HOME\\}?|\\.)(?:\\/?\\.?\\*|\\/)?$/;\nconst DESTRUCTIVE_OP_IN_COMMAND_RE =\n /\\b(?:rm\\s+-[^\\s]*[rf]|chmod\\s+-R|chown\\s+-R)\\b/;\n\ntype SpawnResult = {\n stdout: string;\n stderr: string;\n exitCode: number | null;\n timedOut: boolean;\n};\n\ntype RuntimeCommand = {\n fileName: string;\n source?: string;\n command: string;\n};\n\ntype SandboxRuntimeContext = {\n sandbox: t.CloudflareSandboxRuntime;\n workspaceRoot: string;\n env?: Record<string, string | undefined>;\n timeoutMs: number;\n maxOutputChars: number;\n shell: string;\n};\n\nconst sandboxFactoryCache = new WeakMap<\n t.CloudflareSandboxExecutionConfig,\n Promise<t.CloudflareSandboxRuntime>\n>();\n\nfunction normalizeWorkspaceRoot(workspaceRoot: string): string {\n const normalized = path.normalize(workspaceRoot);\n return normalized === '/' ? normalized : normalized.replace(/\\/+$/, '');\n}\n\nexport function getCloudflareWorkspaceRoot(\n config?: t.CloudflareSandboxExecutionConfig\n): string {\n return normalizeWorkspaceRoot(\n config?.workspaceRoot ?? DEFAULT_WORKSPACE_ROOT\n );\n}\n\nexport async function resolveCloudflareSandbox(\n config: t.CloudflareSandboxExecutionConfig\n): Promise<t.CloudflareSandboxRuntime> {\n const sandbox = config.sandbox;\n if (typeof sandbox !== 'function') {\n return sandbox;\n }\n let cached = sandboxFactoryCache.get(config);\n if (cached == null) {\n cached = Promise.resolve()\n .then(() => sandbox())\n .catch((error: unknown) => {\n sandboxFactoryCache.delete(config);\n throw error;\n });\n sandboxFactoryCache.set(config, cached);\n }\n return cached;\n}\n\nasync function getRuntimeContext(\n config: t.CloudflareSandboxExecutionConfig\n): Promise<SandboxRuntimeContext> {\n return {\n sandbox: await resolveCloudflareSandbox(config),\n workspaceRoot: getCloudflareWorkspaceRoot(config),\n env: config.env,\n timeoutMs: config.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n maxOutputChars: config.maxOutputChars ?? DEFAULT_MAX_OUTPUT_CHARS,\n shell: config.shell ?? 'bash',\n };\n}\n\nfunction toSandboxPath(filePath: string, workspaceRoot: string): string {\n const raw = filePath === '' ? '.' : filePath;\n const root = normalizeWorkspaceRoot(workspaceRoot);\n const resolved = raw.startsWith('/')\n ? path.normalize(raw)\n : path.resolve(root, raw);\n if (root === '/') {\n return resolved;\n }\n if (resolved === root || resolved.startsWith(`${root}/`)) {\n return resolved;\n }\n throw new Error(\n `Path is outside the Cloudflare sandbox workspace: ${filePath}`\n );\n}\n\nfunction quote(value: string): string {\n if (value === '') {\n return '\\'\\'';\n }\n if (/^[A-Za-z0-9_/:=.,@%+-]+$/.test(value)) {\n return value;\n }\n return `'${value.replace(/'/g, '\\'\\\\\\'\\'')}'`;\n}\n\nfunction withInSandboxTimeout(command: string, timeoutMs: number): string {\n const timeoutSeconds = Math.max(1, Math.ceil(timeoutMs / 1000));\n return `timeout -k 2s ${timeoutSeconds}s ${command}`;\n}\n\nfunction outerTimeoutMs(timeoutMs: number): number {\n return timeoutMs + 5000;\n}\n\nfunction isInSandboxTimeoutExit(exitCode: number | null): boolean {\n return exitCode === 124 || exitCode === 137;\n}\n\n/**\n * Client-side backstop timeout for a `sandbox.exec()` await: a few seconds beyond\n * the exec's own `timeout` option, so a stalled exec that never honors `timeout`\n * still can't outlast this.\n */\nexport function clientExecTimeoutMs(timeoutMs: number): number {\n return outerTimeoutMs(timeoutMs) + 5000;\n}\n\n/**\n * Bound a `sandbox.exec()` await with a CLIENT-SIDE timeout.\n *\n * The native Cloudflare Sandbox Durable Object `exec()` is effectively\n * uncancellable from the host: `ExecOptions` has no `signal` (so\n * `supportsExecSignal` is false for the native transport), and its `timeout`\n * option is not reliably enforced when the container/RPC itself stalls — while\n * the in-sandbox `timeout(1)` wrapper only bounds a command that is actually\n * running. So a stalled exec (an unresponsive/cold container) otherwise hangs\n * until the host's run-level abort, burning the whole run budget on one tool\n * call. This race guarantees the host await settles within `timeoutMs`\n * regardless of the transport.\n *\n * On timeout the underlying `exec` promise may keep running in the DO (a\n * native-DO exec cannot be truly cancelled), so its late settlement is swallowed\n * to avoid an unhandled rejection.\n */\nexport async function withClientTimeout<T>(\n exec: Promise<T>,\n timeoutMs: number,\n label: string,\n options: {\n /**\n * Detach the backstop timer from the event loop. Use ONLY when something else\n * already settles the caller (e.g. the spawn path, where spawnLocalProcess's\n * own timer resolves the child). The awaited direct-exec paths must leave it\n * REF'd so the timeout is guaranteed to fire even if nothing else is pending.\n */\n unref?: boolean;\n /** Invoked when the client timeout fires — e.g. abort a signal-aware exec. */\n onTimeout?: () => void;\n } = {}\n): Promise<T> {\n if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {\n return exec;\n }\n // Swallow a late rejection from the losing promise after the race settles.\n exec.catch(() => undefined);\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n exec,\n new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => {\n // Reject FIRST so this client-timeout message reliably wins the race;\n // only then abort a signal-aware exec, whose resulting AbortError must\n // not surface to the caller instead of the timeout.\n reject(\n new Error(\n `${label} exceeded ${timeoutMs}ms client-side timeout (sandbox exec did not return)`\n )\n );\n options.onTimeout?.();\n }, timeoutMs);\n if (options.unref === true) {\n (timer as { unref?: () => void } | undefined)?.unref?.();\n }\n }),\n ]);\n } finally {\n if (timer !== undefined) {\n clearTimeout(timer);\n }\n }\n}\n\n/**\n * Run `sandbox.exec()` bounded by a client-side timeout, and — for signal-aware\n * transports (e.g. the HTTP bridge, `supportsExecSignal === true`) — abort the\n * underlying exec when the timeout fires instead of merely abandoning it. The\n * native DO transport ignores `signal`, so it only gets the timeout. Leaves the\n * backstop timer ref'd (this is an awaited direct-exec path).\n */\nexport async function execWithClientTimeout(\n sandbox: t.CloudflareSandboxRuntime,\n command: string,\n options: t.CloudflareSandboxExecOptions,\n timeoutMs: number,\n label: string,\n runOptions: { unref?: boolean } = {}\n): Promise<t.CloudflareSandboxExecResult> {\n const controller = new AbortController();\n const execOptions: t.CloudflareSandboxExecOptions = { ...options };\n const callerSignal = options.signal;\n let onCallerAbort: (() => void) | undefined;\n if (sandbox.supportsExecSignal === true) {\n // Compose the caller's signal (e.g. run/user cancellation) with our timeout\n // controller so EITHER source cancels the exec — don't clobber the caller's.\n if (callerSignal != null) {\n if (callerSignal.aborted) {\n controller.abort();\n } else {\n onCallerAbort = (): void => controller.abort();\n callerSignal.addEventListener('abort', onCallerAbort, { once: true });\n }\n }\n execOptions.signal = controller.signal;\n } else if ('signal' in execOptions) {\n // Native DO RPC cannot consume an AbortSignal (and would fail to clone it).\n // Strip any caller-provided one so the spread above can't reintroduce it.\n delete execOptions.signal;\n }\n try {\n return await withClientTimeout(\n sandbox.exec(command, execOptions),\n timeoutMs,\n label,\n {\n unref: runOptions.unref,\n onTimeout: () => controller.abort(),\n }\n );\n } finally {\n // Don't leave a listener attached to a long-lived/shared caller signal.\n if (onCallerAbort != null && callerSignal != null) {\n callerSignal.removeEventListener('abort', onCallerAbort);\n }\n }\n}\n\nfunction truncateOutput(value: string, maxChars: number): string {\n if (maxChars <= 0 || value.length <= maxChars) {\n return value;\n }\n const head = Math.max(Math.floor(maxChars / 2), 0);\n const tail = Math.max(maxChars - head, 0);\n return `${value.slice(0, head)}\\n...[truncated ${value.length - maxChars} chars]...\\n${value.slice(value.length - tail)}`;\n}\n\nasync function readStream(stream: ReadableStream<Uint8Array>): Promise<Buffer> {\n const reader = stream.getReader();\n const chunks: Uint8Array[] = [];\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n chunks.push(value);\n }\n } finally {\n reader.releaseLock();\n }\n return Buffer.concat(chunks.map((chunk) => Buffer.from(chunk)));\n}\n\nasync function normalizeReadFileContent(\n result: t.CloudflareSandboxReadFileResult\n): Promise<Buffer> {\n if (typeof result === 'string') {\n return Buffer.from(result, 'utf8');\n }\n if (Buffer.isBuffer(result)) {\n return result;\n }\n if (result instanceof Uint8Array) {\n return Buffer.from(result);\n }\n const content = result.content;\n if (typeof content === 'string') {\n if (result.encoding === 'base64') {\n return Buffer.from(content, 'base64');\n }\n return Buffer.from(content, 'utf8');\n }\n if (Buffer.isBuffer(content)) {\n return content;\n }\n if (content instanceof Uint8Array) {\n return Buffer.from(content);\n }\n return readStream(content);\n}\n\nfunction bytesToStream(bytes: Uint8Array): ReadableStream<Uint8Array> {\n return new ReadableStream<Uint8Array>({\n start(controller): void {\n controller.enqueue(bytes);\n controller.close();\n },\n });\n}\n\nfunction normalizeWriteFileContent(content: string | Buffer | Uint8Array): {\n content: string | ReadableStream<Uint8Array>;\n options?: { encoding?: string };\n} {\n if (typeof content === 'string') {\n return { content, options: { encoding: 'utf8' } };\n }\n return { content: bytesToStream(content) };\n}\n\nfunction createStats(info: {\n size?: number;\n type?: t.CloudflareSandboxFileInfo['type'];\n}): Stats {\n const type = info.type ?? 'file';\n const now = new Date();\n return {\n size: info.size ?? 0,\n isFile: () => type === 'file',\n isDirectory: () => type === 'directory',\n isSymbolicLink: () => type === 'symlink',\n isBlockDevice: () => false,\n isCharacterDevice: () => false,\n isFIFO: () => false,\n isSocket: () => false,\n dev: 0,\n ino: 0,\n mode: 0,\n nlink: 1,\n uid: 0,\n gid: 0,\n rdev: 0,\n blksize: 0,\n blocks: 0,\n atimeMs: now.getTime(),\n mtimeMs: now.getTime(),\n ctimeMs: now.getTime(),\n birthtimeMs: now.getTime(),\n atime: now,\n mtime: now,\n ctime: now,\n birthtime: now,\n } as Stats;\n}\n\nfunction normalizeFileList(\n result: t.CloudflareSandboxListFilesResult\n): t.CloudflareSandboxFileInfo[] {\n return Array.isArray(result) ? result : result.files;\n}\n\nfunction entryNameFor(\n info: t.CloudflareSandboxFileInfo,\n parentPath: string\n): string {\n if (info.name !== '') {\n return info.name.includes('/') ? path.basename(info.name) : info.name;\n }\n if (info.absolutePath != null && info.absolutePath !== '') {\n return path.basename(info.absolutePath);\n }\n if (info.relativePath != null && info.relativePath !== '') {\n return path.basename(info.relativePath);\n }\n return path.basename(parentPath);\n}\n\nfunction entryAbsolutePath(\n info: t.CloudflareSandboxFileInfo,\n parentPath: string\n): string {\n if (info.absolutePath != null && info.absolutePath !== '') {\n return path.normalize(info.absolutePath);\n }\n if (info.relativePath != null && info.relativePath !== '') {\n return path.resolve(parentPath, info.relativePath);\n }\n return path.resolve(parentPath, info.name);\n}\n\nfunction createDirent(info: t.CloudflareSandboxFileInfo): ReaddirEntry {\n return {\n name: entryNameFor(info, ''),\n isFile: () => (info.type ?? 'file') === 'file',\n isDirectory: () => info.type === 'directory',\n isSymbolicLink: () => info.type === 'symlink',\n };\n}\n\nasync function findChildInfo(\n sandbox: t.CloudflareSandboxRuntime,\n filePath: string\n): Promise<t.CloudflareSandboxFileInfo | undefined> {\n const parent = path.dirname(filePath);\n const basename = path.basename(filePath);\n const entries = normalizeFileList(\n await sandbox.listFiles(parent, { includeHidden: true })\n );\n return entries.find((entry) => {\n const absolute = entryAbsolutePath(entry, parent);\n return absolute === filePath || entryNameFor(entry, parent) === basename;\n });\n}\n\nexport function createCloudflareWorkspaceFS(\n config: t.CloudflareSandboxExecutionConfig\n): WorkspaceFS {\n const workspaceRoot = getCloudflareWorkspaceRoot(config);\n\n const fs: WorkspaceFS = {\n readFile: (async (filePath: string, encoding?: 'utf8') => {\n const sandbox = await resolveCloudflareSandbox(config);\n const resolved = toSandboxPath(filePath, workspaceRoot);\n const buffer = await normalizeReadFileContent(\n await sandbox.readFile(resolved, encoding ? { encoding } : undefined)\n );\n return encoding != null ? buffer.toString(encoding) : buffer;\n }) as WorkspaceFS['readFile'],\n writeFile: async (\n filePath: string,\n content: string | Buffer,\n _options?: WriteFileOptions\n ) => {\n const sandbox = await resolveCloudflareSandbox(config);\n const resolved = toSandboxPath(filePath, workspaceRoot);\n const normalized = normalizeWriteFileContent(content);\n await sandbox.writeFile(resolved, normalized.content, normalized.options);\n },\n stat: async (filePath: string) => {\n const sandbox = await resolveCloudflareSandbox(config);\n const resolved = toSandboxPath(filePath, workspaceRoot);\n if (resolved === workspaceRoot) {\n const entries = normalizeFileList(\n await sandbox.listFiles(resolved, { includeHidden: true })\n );\n return createStats({ size: entries.length, type: 'directory' });\n }\n const info = await findChildInfo(sandbox, resolved);\n if (info != null) {\n return createStats({ size: info.size, type: info.type });\n }\n try {\n const entries = normalizeFileList(\n await sandbox.listFiles(resolved, { includeHidden: true })\n );\n return createStats({ size: entries.length, type: 'directory' });\n } catch {\n const buffer = await normalizeReadFileContent(\n await sandbox.readFile(resolved)\n );\n return createStats({ size: buffer.length, type: 'file' });\n }\n },\n readdir: (async (filePath: string, options?: { withFileTypes: true }) => {\n const sandbox = await resolveCloudflareSandbox(config);\n const resolved = toSandboxPath(filePath, workspaceRoot);\n const entries = normalizeFileList(\n await sandbox.listFiles(resolved, { includeHidden: true })\n );\n if (options?.withFileTypes === true) {\n return entries.map(createDirent);\n }\n return entries.map((entry) => entryNameFor(entry, resolved));\n }) as WorkspaceFS['readdir'],\n mkdir: async (filePath: string, options?: MakeDirectoryOptions) => {\n const sandbox = await resolveCloudflareSandbox(config);\n await sandbox.mkdir(toSandboxPath(filePath, workspaceRoot), {\n recursive: options?.recursive,\n });\n },\n realpath: async (filePath: string) =>\n toSandboxPath(filePath, workspaceRoot),\n unlink: async (filePath: string) => {\n const sandbox = await resolveCloudflareSandbox(config);\n await sandbox.deleteFile(toSandboxPath(filePath, workspaceRoot));\n },\n open: async (filePath: string, _flags: 'r') => {\n const sandbox = await resolveCloudflareSandbox(config);\n const resolved = toSandboxPath(filePath, workspaceRoot);\n const buffer = await normalizeReadFileContent(\n await sandbox.readFile(resolved)\n );\n return {\n read: async (\n target: Buffer,\n offset: number,\n length: number,\n position: number\n ) => {\n const start = Math.max(position, 0);\n const slice = buffer.subarray(start, start + length);\n slice.copy(target, offset);\n return { bytesRead: slice.length, buffer: target };\n },\n close: async () => undefined,\n } as unknown as FileHandle;\n },\n };\n\n return fs;\n}\n\nfunction createCloudflareSpawn(\n config: t.CloudflareSandboxExecutionConfig\n): t.LocalSpawn {\n return (command, args, options) => {\n const stdout = new PassThrough();\n const stderr = new PassThrough();\n const child = new EventEmitter() as ChildProcessWithoutNullStreams;\n const abortController = new AbortController();\n const state = { closed: false };\n /** Read through a function so concurrent `closeOnce` mutation (via\n * `kill()`/abort during an `await`) isn't statically narrowed away. */\n const isClosed = (): boolean => state.closed;\n const closeOnce = (\n exitCode: number | null,\n signal: NodeJS.Signals | null\n ): void => {\n if (state.closed) {\n return;\n }\n state.closed = true;\n stdout.end();\n stderr.end();\n Object.assign(child, {\n exitCode,\n signalCode: signal,\n });\n child.emit('close', exitCode, signal);\n };\n Object.assign(child, {\n stdout,\n stderr,\n stdin: new PassThrough(),\n stdio: [null, stdout, stderr],\n killed: false,\n exitCode: null,\n signalCode: null,\n pid: undefined,\n kill: (signal: NodeJS.Signals = 'SIGTERM') => {\n Object.assign(child, { killed: true, signalCode: signal });\n abortController.abort();\n closeOnce(null, signal);\n return true;\n },\n });\n\n void (async (): Promise<void> => {\n const ctx = await getRuntimeContext(config);\n const rendered = [command, ...args].map(quote).join(' ');\n const spawnTimeoutMs = (\n options as {\n [LOCAL_SPAWN_TIMEOUT_MS]?: number;\n }\n )[LOCAL_SPAWN_TIMEOUT_MS];\n const timeoutMs =\n typeof spawnTimeoutMs === 'number' && Number.isFinite(spawnTimeoutMs)\n ? spawnTimeoutMs\n : ctx.timeoutMs;\n const timedCommand = withInSandboxTimeout(rendered, timeoutMs);\n const cwd =\n options.cwd == null ? ctx.workspaceRoot : options.cwd.toString();\n if (isClosed()) {\n return;\n }\n const execOptions: t.CloudflareSandboxExecOptions = {\n cwd,\n env: ctx.env,\n timeout: outerTimeoutMs(timeoutMs),\n };\n if (ctx.sandbox.supportsExecSignal === true) {\n execOptions.signal = abortController.signal;\n }\n try {\n const result = await withClientTimeout(\n ctx.sandbox.exec(timedCommand, execOptions),\n clientExecTimeoutMs(timeoutMs),\n 'cloudflare sandbox exec',\n // spawnLocalProcess's own timer already resolves the child, so this\n // backstop may safely detach; abort the (signal-aware) exec on timeout.\n { unref: true, onTimeout: () => abortController.abort() }\n );\n if (isClosed()) {\n return;\n }\n if (result.stdout) stdout.write(result.stdout);\n if (result.stderr) stderr.write(result.stderr);\n closeOnce(result.exitCode, null);\n } catch (error) {\n if (isClosed()) {\n return;\n }\n stderr.write((error as Error).message);\n closeOnce(1, null);\n }\n })();\n\n return child;\n };\n}\n\nexport function createCloudflareLocalExecutionConfig(\n config: t.CloudflareSandboxExecutionConfig\n): t.LocalExecutionConfig {\n const workspaceRoot = getCloudflareWorkspaceRoot(config);\n return {\n cwd: workspaceRoot,\n workspace: { root: workspaceRoot },\n exec: {\n spawn: createCloudflareSpawn(config),\n fs: createCloudflareWorkspaceFS(config),\n sandboxed: true,\n },\n shell: config.shell ?? 'bash',\n timeoutMs: config.timeoutMs,\n maxOutputChars: config.maxOutputChars,\n env: config.env,\n includeCodingTools: config.includeCodingTools,\n compileCheck: config.compileCheck,\n readOnly: config.readOnly,\n allowDangerousCommands: config.allowDangerousCommands,\n bashAst: config.bashAst,\n fileCheckpointing: config.fileCheckpointing,\n maxReadBytes: config.maxReadBytes,\n attachReadAttachments: config.attachReadAttachments,\n maxAttachmentBytes: config.maxAttachmentBytes,\n postEditSyntaxCheck: config.postEditSyntaxCheck,\n };\n}\n\nexport async function validateCloudflareBashCommand(\n command: string,\n args: readonly string[],\n config: t.CloudflareSandboxExecutionConfig\n): Promise<void> {\n const localConfig = createCloudflareLocalExecutionConfig(config);\n const validation = await validateBashCommand(command, localConfig);\n if (!validation.valid) {\n throw new Error(validation.errors.join('\\n'));\n }\n\n if (\n args.length > 0 &&\n config.allowDangerousCommands !== true &&\n DESTRUCTIVE_OP_IN_COMMAND_RE.test(command)\n ) {\n const offending = args.find((arg) => PROTECTED_TARGET_ARG_RE.test(arg));\n if (offending !== undefined) {\n throw new Error(\n `Command matches a destructive command pattern (protected target \"${offending}\" passed via positional arg).`\n );\n }\n }\n}\n\nexport async function executeCloudflareBash(\n command: string,\n config: t.CloudflareSandboxExecutionConfig,\n args: readonly string[] = []\n): Promise<SpawnResult> {\n await validateCloudflareBashCommand(command, args, config);\n const ctx = await getRuntimeContext(config);\n const shellCommand =\n args.length > 0\n ? `${ctx.shell} -lc ${quote(command)} -- ${args.map(quote).join(' ')}`\n : `${ctx.shell} -lc ${quote(command)}`;\n const result = await execWithClientTimeout(\n ctx.sandbox,\n withInSandboxTimeout(shellCommand, ctx.timeoutMs),\n {\n cwd: ctx.workspaceRoot,\n env: ctx.env,\n timeout: outerTimeoutMs(ctx.timeoutMs),\n },\n clientExecTimeoutMs(ctx.timeoutMs),\n 'cloudflare sandbox bash exec'\n );\n return {\n stdout: truncateOutput(result.stdout, ctx.maxOutputChars),\n stderr: truncateOutput(result.stderr, ctx.maxOutputChars),\n exitCode: result.exitCode,\n timedOut: isInSandboxTimeoutExit(result.exitCode),\n };\n}\n\nfunction runtimeForCode(\n lang: string,\n tempDir: string,\n code: string,\n args: string[] = [],\n shell = 'bash'\n): RuntimeCommand {\n const fileFor = (name: string): string => path.join(tempDir, name);\n const argText = args.map(quote).join(' ');\n switch (lang) {\n case 'py':\n case 'python':\n return {\n fileName: 'main.py',\n source: code,\n command: `python3 ${quote(fileFor('main.py'))} ${argText}`,\n };\n case 'js':\n case 'javascript':\n return {\n fileName: 'main.js',\n source: code,\n command: `node ${quote(fileFor('main.js'))} ${argText}`,\n };\n case 'ts':\n case 'typescript':\n return {\n fileName: 'main.ts',\n source: code,\n command: `npx --no-install tsx ${quote(fileFor('main.ts'))} ${argText}`,\n };\n case 'php':\n return {\n fileName: 'main.php',\n source: code,\n command: `php ${quote(fileFor('main.php'))} ${argText}`,\n };\n case 'go':\n return {\n fileName: 'main.go',\n source: code,\n command: `go run ${quote(fileFor('main.go'))} ${argText}`,\n };\n case 'rs':\n return {\n fileName: 'main.rs',\n source: code,\n command: `${shell} -lc ${quote(\n `rustc ${quote(fileFor('main.rs'))} -o ${quote(fileFor('main-rs'))} && ${quote(fileFor('main-rs'))} ${argText}`\n )}`,\n };\n case 'c':\n return {\n fileName: 'main.c',\n source: code,\n command: `${shell} -lc ${quote(\n `cc ${quote(fileFor('main.c'))} -o ${quote(fileFor('main-c'))} && ${quote(fileFor('main-c'))} ${argText}`\n )}`,\n };\n case 'cpp':\n return {\n fileName: 'main.cpp',\n source: code,\n command: `${shell} -lc ${quote(\n `c++ ${quote(fileFor('main.cpp'))} -o ${quote(fileFor('main-cpp'))} && ${quote(fileFor('main-cpp'))} ${argText}`\n )}`,\n };\n case 'java':\n return {\n fileName: 'Main.java',\n source: code,\n command: `${shell} -lc ${quote(\n `javac ${quote(fileFor('Main.java'))} && java -cp ${quote(tempDir)} Main ${argText}`\n )}`,\n };\n case 'r':\n return {\n fileName: 'main.R',\n source: code,\n command: `Rscript ${quote(fileFor('main.R'))} ${argText}`,\n };\n case 'd':\n return {\n fileName: 'main.d',\n source: code,\n command: `${shell} -lc ${quote(\n `dmd ${quote(fileFor('main.d'))} -of=${quote(fileFor('main-d'))} && ${quote(fileFor('main-d'))} ${argText}`\n )}`,\n };\n case 'f90':\n return {\n fileName: 'main.f90',\n source: code,\n command: `${shell} -lc ${quote(\n `gfortran ${quote(fileFor('main.f90'))} -o ${quote(fileFor('main-f90'))} && ${quote(fileFor('main-f90'))} ${argText}`\n )}`,\n };\n case 'bash':\n case 'sh':\n return {\n fileName: 'main.sh',\n source: code,\n command: `${shell} -lc ${quote(code)} -- ${argText}`,\n };\n default:\n throw new Error(`Unsupported Cloudflare sandbox runtime: ${lang}`);\n }\n}\n\nexport async function executeCloudflareCode(\n input: { lang: string; code: string; args?: string[] },\n config: t.CloudflareSandboxExecutionConfig\n): Promise<SpawnResult> {\n if (input.lang === 'bash' || input.lang === 'sh') {\n return executeCloudflareBash(input.code, config, input.args ?? []);\n }\n const ctx = await getRuntimeContext(config);\n const id = globalThis.crypto.randomUUID();\n const tempDir = path.join(ctx.workspaceRoot, '.lc-exec', id);\n const runtime = runtimeForCode(\n input.lang,\n tempDir,\n input.code,\n input.args,\n ctx.shell\n );\n await ctx.sandbox.mkdir(tempDir, { recursive: true });\n if (runtime.source != null) {\n await ctx.sandbox.writeFile(\n path.join(tempDir, runtime.fileName),\n runtime.source,\n {\n encoding: 'utf8',\n }\n );\n }\n let execSucceeded = false;\n try {\n const result = await execWithClientTimeout(\n ctx.sandbox,\n withInSandboxTimeout(runtime.command, ctx.timeoutMs),\n {\n cwd: ctx.workspaceRoot,\n env: ctx.env,\n timeout: outerTimeoutMs(ctx.timeoutMs),\n },\n clientExecTimeoutMs(ctx.timeoutMs),\n 'cloudflare sandbox code-exec'\n );\n execSucceeded = true;\n return {\n stdout: truncateOutput(result.stdout, ctx.maxOutputChars),\n stderr: truncateOutput(result.stderr, ctx.maxOutputChars),\n exitCode: result.exitCode,\n timedOut: isInSandboxTimeoutExit(result.exitCode),\n };\n } finally {\n // After a normal run, AWAIT cleanup so the temp dir is gone before returning.\n // After a stalled/failed run, detach it (unref'd) so we don't pile a second\n // client timeout onto the caller's latency; cleanup still runs best-effort.\n const detach = !execSucceeded;\n const cleanup = execWithClientTimeout(\n ctx.sandbox,\n `rm -rf ${quote(tempDir)}`,\n {\n cwd: ctx.workspaceRoot,\n env: ctx.env,\n timeout: 10000,\n },\n clientExecTimeoutMs(10000),\n 'cloudflare sandbox cleanup',\n { unref: detach }\n ).catch(() => undefined);\n if (!detach) {\n await cleanup;\n }\n }\n}\n\nexport function formatCloudflareOutput(\n result: SpawnResult,\n cwd: string\n): string {\n let formatted = '';\n if (result.stdout !== '') {\n formatted += `stdout:\\n${result.stdout}\\n`;\n } else {\n formatted += 'stdout: Empty. Ensure you\\'re writing output explicitly.\\n';\n }\n if (result.stderr !== '') {\n formatted += `stderr:\\n${result.stderr}\\n`;\n }\n if (result.exitCode != null && result.exitCode !== 0) {\n formatted += `exit_code: ${result.exitCode}\\n`;\n }\n if (result.timedOut) {\n formatted += 'timed_out: true\\n';\n }\n formatted += `working_directory: ${cwd}`;\n return formatted.trim();\n}\n"],"mappings":";;;;;AAaA,MAAM,yBAAyB;AAC/B,MAAM,qBAAqB;AAC3B,MAAM,2BAA2B;AACjC,MAAM,0BAA0B;AAChC,MAAM,+BACJ;AAwBF,MAAM,sCAAsB,IAAI,QAG9B;AAEF,SAAS,uBAAuB,eAA+B;CAC7D,MAAM,aAAaA,MAAK,UAAU,aAAa;CAC/C,OAAO,eAAe,MAAM,aAAa,WAAW,QAAQ,QAAQ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