@librechat/agents 3.1.90 → 3.1.92

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 (94) hide show
  1. package/dist/cjs/agents/AgentContext.cjs +9 -5
  2. package/dist/cjs/agents/AgentContext.cjs.map +1 -1
  3. package/dist/cjs/graphs/Graph.cjs +48 -14
  4. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  5. package/dist/cjs/instrumentation.cjs +2 -7
  6. package/dist/cjs/instrumentation.cjs.map +1 -1
  7. package/dist/cjs/langfuse.cjs +285 -0
  8. package/dist/cjs/langfuse.cjs.map +1 -0
  9. package/dist/cjs/main.cjs +25 -0
  10. package/dist/cjs/main.cjs.map +1 -1
  11. package/dist/cjs/run.cjs +75 -44
  12. package/dist/cjs/run.cjs.map +1 -1
  13. package/dist/cjs/stream.cjs +10 -3
  14. package/dist/cjs/stream.cjs.map +1 -1
  15. package/dist/cjs/tools/cloudflare/CloudflareBridgeRuntime.cjs +380 -0
  16. package/dist/cjs/tools/cloudflare/CloudflareBridgeRuntime.cjs.map +1 -0
  17. package/dist/cjs/tools/cloudflare/CloudflareProgrammaticToolCalling.cjs +997 -0
  18. package/dist/cjs/tools/cloudflare/CloudflareProgrammaticToolCalling.cjs.map +1 -0
  19. package/dist/cjs/tools/cloudflare/CloudflareSandboxExecutionEngine.cjs +575 -0
  20. package/dist/cjs/tools/cloudflare/CloudflareSandboxExecutionEngine.cjs.map +1 -0
  21. package/dist/cjs/tools/cloudflare/CloudflareSandboxTools.cjs +165 -0
  22. package/dist/cjs/tools/cloudflare/CloudflareSandboxTools.cjs.map +1 -0
  23. package/dist/cjs/tools/local/LocalExecutionEngine.cjs +17 -5
  24. package/dist/cjs/tools/local/LocalExecutionEngine.cjs.map +1 -1
  25. package/dist/cjs/tools/local/resolveLocalExecutionTools.cjs +110 -6
  26. package/dist/cjs/tools/local/resolveLocalExecutionTools.cjs.map +1 -1
  27. package/dist/cjs/utils/callbacks.cjs +27 -0
  28. package/dist/cjs/utils/callbacks.cjs.map +1 -0
  29. package/dist/esm/agents/AgentContext.mjs +9 -5
  30. package/dist/esm/agents/AgentContext.mjs.map +1 -1
  31. package/dist/esm/graphs/Graph.mjs +48 -14
  32. package/dist/esm/graphs/Graph.mjs.map +1 -1
  33. package/dist/esm/instrumentation.mjs +2 -7
  34. package/dist/esm/instrumentation.mjs.map +1 -1
  35. package/dist/esm/langfuse.mjs +275 -0
  36. package/dist/esm/langfuse.mjs.map +1 -0
  37. package/dist/esm/main.mjs +5 -1
  38. package/dist/esm/main.mjs.map +1 -1
  39. package/dist/esm/run.mjs +75 -44
  40. package/dist/esm/run.mjs.map +1 -1
  41. package/dist/esm/stream.mjs +10 -3
  42. package/dist/esm/stream.mjs.map +1 -1
  43. package/dist/esm/tools/cloudflare/CloudflareBridgeRuntime.mjs +378 -0
  44. package/dist/esm/tools/cloudflare/CloudflareBridgeRuntime.mjs.map +1 -0
  45. package/dist/esm/tools/cloudflare/CloudflareProgrammaticToolCalling.mjs +994 -0
  46. package/dist/esm/tools/cloudflare/CloudflareProgrammaticToolCalling.mjs.map +1 -0
  47. package/dist/esm/tools/cloudflare/CloudflareSandboxExecutionEngine.mjs +566 -0
  48. package/dist/esm/tools/cloudflare/CloudflareSandboxExecutionEngine.mjs.map +1 -0
  49. package/dist/esm/tools/cloudflare/CloudflareSandboxTools.mjs +155 -0
  50. package/dist/esm/tools/cloudflare/CloudflareSandboxTools.mjs.map +1 -0
  51. package/dist/esm/tools/local/LocalExecutionEngine.mjs +17 -6
  52. package/dist/esm/tools/local/LocalExecutionEngine.mjs.map +1 -1
  53. package/dist/esm/tools/local/resolveLocalExecutionTools.mjs +111 -7
  54. package/dist/esm/tools/local/resolveLocalExecutionTools.mjs.map +1 -1
  55. package/dist/esm/utils/callbacks.mjs +24 -0
  56. package/dist/esm/utils/callbacks.mjs.map +1 -0
  57. package/dist/types/agents/AgentContext.d.ts +4 -1
  58. package/dist/types/graphs/Graph.d.ts +6 -5
  59. package/dist/types/index.d.ts +1 -0
  60. package/dist/types/langfuse.d.ts +57 -0
  61. package/dist/types/tools/cloudflare/CloudflareBridgeRuntime.d.ts +23 -0
  62. package/dist/types/tools/cloudflare/CloudflareProgrammaticToolCalling.d.ts +4 -0
  63. package/dist/types/tools/cloudflare/CloudflareSandboxExecutionEngine.d.ts +21 -0
  64. package/dist/types/tools/cloudflare/CloudflareSandboxTools.d.ts +22 -0
  65. package/dist/types/tools/cloudflare/index.d.ts +4 -0
  66. package/dist/types/tools/local/LocalExecutionEngine.d.ts +1 -0
  67. package/dist/types/types/graph.d.ts +8 -0
  68. package/dist/types/types/run.d.ts +2 -2
  69. package/dist/types/types/tools.d.ts +118 -2
  70. package/dist/types/utils/callbacks.d.ts +5 -0
  71. package/package.json +4 -4
  72. package/src/__tests__/stream.eagerEventExecution.test.ts +66 -0
  73. package/src/agents/AgentContext.ts +13 -3
  74. package/src/graphs/Graph.ts +57 -16
  75. package/src/index.ts +1 -0
  76. package/src/instrumentation.ts +2 -7
  77. package/src/langfuse.ts +441 -0
  78. package/src/run.ts +105 -59
  79. package/src/specs/langfuse-callbacks.test.ts +75 -0
  80. package/src/specs/langfuse-config.test.ts +114 -0
  81. package/src/specs/langfuse-metadata.test.ts +19 -1
  82. package/src/stream.ts +13 -3
  83. package/src/tools/__tests__/CloudflareSandboxExecution.test.ts +537 -0
  84. package/src/tools/cloudflare/CloudflareBridgeRuntime.ts +480 -0
  85. package/src/tools/cloudflare/CloudflareProgrammaticToolCalling.ts +1162 -0
  86. package/src/tools/cloudflare/CloudflareSandboxExecutionEngine.ts +744 -0
  87. package/src/tools/cloudflare/CloudflareSandboxTools.ts +225 -0
  88. package/src/tools/cloudflare/index.ts +4 -0
  89. package/src/tools/local/LocalExecutionEngine.ts +20 -4
  90. package/src/tools/local/resolveLocalExecutionTools.ts +169 -7
  91. package/src/types/graph.ts +9 -0
  92. package/src/types/run.ts +2 -7
  93. package/src/types/tools.ts +141 -2
  94. package/src/utils/callbacks.ts +39 -0
@@ -0,0 +1,155 @@
1
+ import { tool } from '@langchain/core/tools';
2
+ import { CodeExecutionToolSchema, CodeExecutionToolName } from '../CodeExecutor.mjs';
3
+ import { BashExecutionToolSchema, BashToolOutputReferencesGuide, BashExecutionToolName } from '../BashExecutor.mjs';
4
+ import { createLocalReadFileTool, createLocalWriteFileTool, createLocalEditFileTool, createLocalGrepSearchTool, createLocalGlobSearchTool, createLocalListDirectoryTool } from '../local/LocalCodingTools.mjs';
5
+ import { createLocalFileCheckpointer } from '../local/FileCheckpointer.mjs';
6
+ import { createCompileCheckTool } from '../local/CompileCheckTool.mjs';
7
+ import { Constants } from '../../common/enum.mjs';
8
+ import { getCloudflareWorkspaceRoot, executeCloudflareBash, formatCloudflareOutput, executeCloudflareCode, createCloudflareWorkspaceFS, createCloudflareLocalExecutionConfig } from './CloudflareSandboxExecutionEngine.mjs';
9
+ import { createCloudflareProgrammaticToolCallingTool, createCloudflareBashProgrammaticToolCallingTool } from './CloudflareProgrammaticToolCalling.mjs';
10
+
11
+ const CLOUDFLARE_CODING_TOOL_NAMES = [
12
+ Constants.READ_FILE,
13
+ Constants.WRITE_FILE,
14
+ Constants.EDIT_FILE,
15
+ Constants.GREP_SEARCH,
16
+ Constants.GLOB_SEARCH,
17
+ Constants.LIST_DIRECTORY,
18
+ Constants.COMPILE_CHECK,
19
+ Constants.BASH_TOOL,
20
+ Constants.EXECUTE_CODE,
21
+ Constants.PROGRAMMATIC_TOOL_CALLING,
22
+ Constants.BASH_PROGRAMMATIC_TOOL_CALLING,
23
+ ];
24
+ const CLOUDFLARE_BASH_CODING_TOOL_NAMES = [
25
+ Constants.READ_FILE,
26
+ Constants.WRITE_FILE,
27
+ Constants.EDIT_FILE,
28
+ Constants.GREP_SEARCH,
29
+ Constants.GLOB_SEARCH,
30
+ Constants.LIST_DIRECTORY,
31
+ Constants.COMPILE_CHECK,
32
+ Constants.BASH_TOOL,
33
+ Constants.BASH_PROGRAMMATIC_TOOL_CALLING,
34
+ ];
35
+ const CloudflareCodeExecutionToolDescription = `
36
+ Runs code inside the configured Cloudflare Sandbox workspace. The sandbox can see files and installed runtimes available inside the Cloudflare Sandbox container.
37
+
38
+ Usage:
39
+ - Commands execute in the Cloudflare Sandbox workspace and may modify sandbox files.
40
+ - Input code is already displayed to the user, so do not repeat it unless asked.
41
+ - Output is not displayed unless you print it explicitly.
42
+ `.trim();
43
+ const CloudflareBashExecutionToolDescription = `
44
+ Runs bash commands inside the configured Cloudflare Sandbox workspace.
45
+
46
+ Usage:
47
+ - Commands execute in the Cloudflare Sandbox workspace and may modify sandbox files.
48
+ - Output is not displayed unless you print it explicitly.
49
+ - Prefer project-native commands and inspect files before changing them.
50
+ `.trim();
51
+ function createCloudflareCodeExecutionTool(config) {
52
+ return tool(async (rawInput) => {
53
+ const input = rawInput;
54
+ const cwd = getCloudflareWorkspaceRoot(config);
55
+ const result = await executeCloudflareCode(input, config);
56
+ return [
57
+ formatCloudflareOutput(result, cwd),
58
+ {
59
+ session_id: 'cloudflare-sandbox',
60
+ files: [],
61
+ },
62
+ ];
63
+ }, {
64
+ name: CodeExecutionToolName,
65
+ description: CloudflareCodeExecutionToolDescription,
66
+ schema: CodeExecutionToolSchema,
67
+ responseFormat: Constants.CONTENT_AND_ARTIFACT,
68
+ });
69
+ }
70
+ function createCloudflareBashExecutionTool(options) {
71
+ const { config } = options;
72
+ return tool(async (rawInput) => {
73
+ const input = rawInput;
74
+ const cwd = getCloudflareWorkspaceRoot(config);
75
+ const result = await executeCloudflareBash(input.command, config, input.args ?? []);
76
+ return [
77
+ formatCloudflareOutput(result, cwd),
78
+ {
79
+ session_id: 'cloudflare-sandbox',
80
+ files: [],
81
+ },
82
+ ];
83
+ }, {
84
+ name: BashExecutionToolName,
85
+ description: options.enableToolOutputReferences === true
86
+ ? `${CloudflareBashExecutionToolDescription}\n\n${BashToolOutputReferencesGuide}`
87
+ : CloudflareBashExecutionToolDescription,
88
+ schema: BashExecutionToolSchema,
89
+ responseFormat: Constants.CONTENT_AND_ARTIFACT,
90
+ });
91
+ }
92
+ function getSelectedCodingToolNames(config) {
93
+ return new Set(config.codingToolNames ?? CLOUDFLARE_CODING_TOOL_NAMES);
94
+ }
95
+ function createCloudflareCodingTools(config, options = {}) {
96
+ const localConfig = createCloudflareLocalExecutionConfig(config);
97
+ const checkpointer = options.checkpointer ??
98
+ (config.fileCheckpointing === true
99
+ ? createLocalFileCheckpointer({
100
+ fs: createCloudflareWorkspaceFS(config),
101
+ })
102
+ : undefined);
103
+ const tools = [
104
+ [Constants.READ_FILE, createLocalReadFileTool(localConfig)],
105
+ [Constants.WRITE_FILE, createLocalWriteFileTool(localConfig, checkpointer)],
106
+ [Constants.EDIT_FILE, createLocalEditFileTool(localConfig, checkpointer)],
107
+ [Constants.GREP_SEARCH, createLocalGrepSearchTool(localConfig)],
108
+ [Constants.GLOB_SEARCH, createLocalGlobSearchTool(localConfig)],
109
+ [Constants.LIST_DIRECTORY, createLocalListDirectoryTool(localConfig)],
110
+ [Constants.COMPILE_CHECK, createCompileCheckTool(localConfig)],
111
+ [Constants.BASH_TOOL, createCloudflareBashExecutionTool({ config })],
112
+ [Constants.EXECUTE_CODE, createCloudflareCodeExecutionTool(config)],
113
+ [
114
+ Constants.PROGRAMMATIC_TOOL_CALLING,
115
+ createCloudflareProgrammaticToolCallingTool(config),
116
+ ],
117
+ [
118
+ Constants.BASH_PROGRAMMATIC_TOOL_CALLING,
119
+ createCloudflareBashProgrammaticToolCallingTool(config),
120
+ ],
121
+ ];
122
+ const selectedNames = getSelectedCodingToolNames(config);
123
+ return tools
124
+ .filter(([name]) => selectedNames.has(name))
125
+ .map(([, selectedTool]) => selectedTool);
126
+ }
127
+ function createCloudflareCodingToolBundle(config, options = {}) {
128
+ const checkpointer = options.checkpointer ??
129
+ (config.fileCheckpointing === true
130
+ ? createLocalFileCheckpointer({
131
+ fs: createCloudflareWorkspaceFS(config),
132
+ })
133
+ : undefined);
134
+ return {
135
+ tools: createCloudflareCodingTools(config, { checkpointer }),
136
+ checkpointer,
137
+ };
138
+ }
139
+ function createCloudflareExecutionTool(name, config) {
140
+ switch (name) {
141
+ case Constants.EXECUTE_CODE:
142
+ return createCloudflareCodeExecutionTool(config);
143
+ case Constants.BASH_TOOL:
144
+ return createCloudflareBashExecutionTool({ config });
145
+ case Constants.PROGRAMMATIC_TOOL_CALLING:
146
+ return createCloudflareProgrammaticToolCallingTool(config);
147
+ case Constants.BASH_PROGRAMMATIC_TOOL_CALLING:
148
+ return createCloudflareBashProgrammaticToolCallingTool(config);
149
+ default:
150
+ return undefined;
151
+ }
152
+ }
153
+
154
+ export { CLOUDFLARE_BASH_CODING_TOOL_NAMES, CLOUDFLARE_CODING_TOOL_NAMES, CloudflareBashExecutionToolDescription, CloudflareCodeExecutionToolDescription, createCloudflareBashExecutionTool, createCloudflareCodeExecutionTool, createCloudflareCodingToolBundle, createCloudflareCodingTools, createCloudflareExecutionTool };
155
+ //# sourceMappingURL=CloudflareSandboxTools.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"CloudflareSandboxTools.mjs","sources":["../../../../src/tools/cloudflare/CloudflareSandboxTools.ts"],"sourcesContent":["import { tool } from '@langchain/core/tools';\nimport type { DynamicStructuredTool } from '@langchain/core/tools';\nimport type * as t from '@/types';\nimport {\n CodeExecutionToolName,\n CodeExecutionToolSchema,\n} from '@/tools/CodeExecutor';\nimport {\n BashExecutionToolName,\n BashExecutionToolSchema,\n BashToolOutputReferencesGuide,\n} from '@/tools/BashExecutor';\nimport {\n createLocalReadFileTool,\n createLocalWriteFileTool,\n createLocalEditFileTool,\n createLocalGrepSearchTool,\n createLocalGlobSearchTool,\n createLocalListDirectoryTool,\n} from '@/tools/local/LocalCodingTools';\nimport { createLocalFileCheckpointer } from '@/tools/local/FileCheckpointer';\nimport { createCompileCheckTool } from '@/tools/local/CompileCheckTool';\nimport { Constants } from '@/common';\nimport {\n createCloudflareLocalExecutionConfig,\n createCloudflareWorkspaceFS,\n executeCloudflareBash,\n executeCloudflareCode,\n formatCloudflareOutput,\n getCloudflareWorkspaceRoot,\n} from './CloudflareSandboxExecutionEngine';\nimport {\n createCloudflareBashProgrammaticToolCallingTool,\n createCloudflareProgrammaticToolCallingTool,\n} from './CloudflareProgrammaticToolCalling';\n\nexport const CLOUDFLARE_CODING_TOOL_NAMES: readonly 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 Constants.PROGRAMMATIC_TOOL_CALLING,\n Constants.BASH_PROGRAMMATIC_TOOL_CALLING,\n];\n\nexport const CLOUDFLARE_BASH_CODING_TOOL_NAMES: readonly 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.BASH_PROGRAMMATIC_TOOL_CALLING,\n];\n\nexport const CloudflareCodeExecutionToolDescription = `\nRuns code inside the configured Cloudflare Sandbox workspace. The sandbox can see files and installed runtimes available inside the Cloudflare Sandbox container.\n\nUsage:\n- Commands execute in the Cloudflare Sandbox workspace and may modify sandbox files.\n- Input code is already displayed to the user, so do not repeat it unless asked.\n- Output is not displayed unless you print it explicitly.\n`.trim();\n\nexport const CloudflareBashExecutionToolDescription = `\nRuns bash commands inside the configured Cloudflare Sandbox workspace.\n\nUsage:\n- Commands execute in the Cloudflare Sandbox workspace and may modify sandbox files.\n- Output is not displayed unless you print it explicitly.\n- Prefer project-native commands and inspect files before changing them.\n`.trim();\n\nexport function createCloudflareCodeExecutionTool(\n config: t.CloudflareSandboxExecutionConfig\n): DynamicStructuredTool {\n return tool(\n async (rawInput) => {\n const input = rawInput as {\n lang: string;\n code: string;\n args?: string[];\n };\n const cwd = getCloudflareWorkspaceRoot(config);\n const result = await executeCloudflareCode(input, config);\n return [\n formatCloudflareOutput(result, cwd),\n {\n session_id: 'cloudflare-sandbox',\n files: [],\n } satisfies t.CodeExecutionArtifact,\n ];\n },\n {\n name: CodeExecutionToolName,\n description: CloudflareCodeExecutionToolDescription,\n schema: CodeExecutionToolSchema,\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n\nexport function createCloudflareBashExecutionTool(options: {\n config: t.CloudflareSandboxExecutionConfig;\n enableToolOutputReferences?: boolean;\n}): DynamicStructuredTool {\n const { config } = options;\n return tool(\n async (rawInput) => {\n const input = rawInput as { command: string; args?: string[] };\n const cwd = getCloudflareWorkspaceRoot(config);\n const result = await executeCloudflareBash(\n input.command,\n config,\n input.args ?? []\n );\n return [\n formatCloudflareOutput(result, cwd),\n {\n session_id: 'cloudflare-sandbox',\n files: [],\n } satisfies t.CodeExecutionArtifact,\n ];\n },\n {\n name: BashExecutionToolName,\n description:\n options.enableToolOutputReferences === true\n ? `${CloudflareBashExecutionToolDescription}\\n\\n${BashToolOutputReferencesGuide}`\n : CloudflareBashExecutionToolDescription,\n schema: BashExecutionToolSchema,\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n\nexport type CloudflareCodingToolBundle = {\n tools: DynamicStructuredTool[];\n checkpointer?: t.LocalFileCheckpointer;\n};\n\nfunction getSelectedCodingToolNames(\n config: t.CloudflareSandboxExecutionConfig\n): Set<string> {\n return new Set(config.codingToolNames ?? CLOUDFLARE_CODING_TOOL_NAMES);\n}\n\nexport function createCloudflareCodingTools(\n config: t.CloudflareSandboxExecutionConfig,\n options: { checkpointer?: t.LocalFileCheckpointer } = {}\n): DynamicStructuredTool[] {\n const localConfig = createCloudflareLocalExecutionConfig(config);\n const checkpointer =\n options.checkpointer ??\n (config.fileCheckpointing === true\n ? createLocalFileCheckpointer({\n fs: createCloudflareWorkspaceFS(config),\n })\n : undefined);\n const tools = [\n [Constants.READ_FILE, createLocalReadFileTool(localConfig)],\n [Constants.WRITE_FILE, createLocalWriteFileTool(localConfig, checkpointer)],\n [Constants.EDIT_FILE, createLocalEditFileTool(localConfig, checkpointer)],\n [Constants.GREP_SEARCH, createLocalGrepSearchTool(localConfig)],\n [Constants.GLOB_SEARCH, createLocalGlobSearchTool(localConfig)],\n [Constants.LIST_DIRECTORY, createLocalListDirectoryTool(localConfig)],\n [Constants.COMPILE_CHECK, createCompileCheckTool(localConfig)],\n [Constants.BASH_TOOL, createCloudflareBashExecutionTool({ config })],\n [Constants.EXECUTE_CODE, createCloudflareCodeExecutionTool(config)],\n [\n Constants.PROGRAMMATIC_TOOL_CALLING,\n createCloudflareProgrammaticToolCallingTool(config),\n ],\n [\n Constants.BASH_PROGRAMMATIC_TOOL_CALLING,\n createCloudflareBashProgrammaticToolCallingTool(config),\n ],\n ] satisfies Array<[string, DynamicStructuredTool]>;\n const selectedNames = getSelectedCodingToolNames(config);\n return tools\n .filter(([name]) => selectedNames.has(name))\n .map(([, selectedTool]) => selectedTool);\n}\n\nexport function createCloudflareCodingToolBundle(\n config: t.CloudflareSandboxExecutionConfig,\n options: { checkpointer?: t.LocalFileCheckpointer } = {}\n): CloudflareCodingToolBundle {\n const checkpointer =\n options.checkpointer ??\n (config.fileCheckpointing === true\n ? createLocalFileCheckpointer({\n fs: createCloudflareWorkspaceFS(config),\n })\n : undefined);\n return {\n tools: createCloudflareCodingTools(config, { checkpointer }),\n checkpointer,\n };\n}\n\nexport function createCloudflareExecutionTool(\n name: string,\n config: t.CloudflareSandboxExecutionConfig\n): t.GenericTool | undefined {\n switch (name) {\n case Constants.EXECUTE_CODE:\n return createCloudflareCodeExecutionTool(config);\n case Constants.BASH_TOOL:\n return createCloudflareBashExecutionTool({ config });\n case Constants.PROGRAMMATIC_TOOL_CALLING:\n return createCloudflareProgrammaticToolCallingTool(config);\n case Constants.BASH_PROGRAMMATIC_TOOL_CALLING:\n return createCloudflareBashProgrammaticToolCallingTool(config);\n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CAAC;AAC5C;SAEgB,gCAAgC,CAC9C,MAA0C,EAC1C,UAAsD,EAAE,EAAA;AAExD,IAAA,MAAM,YAAY,GAChB,OAAO,CAAC,YAAY;AACpB,SAAC,MAAM,CAAC,iBAAiB,KAAK;cAC1B,2BAA2B,CAAC;AAC5B,gBAAA,EAAE,EAAE,2BAA2B,CAAC,MAAM,CAAC;aACxC;cACC,SAAS,CAAC;IAChB,OAAO;QACL,KAAK,EAAE,2BAA2B,CAAC,MAAM,EAAE,EAAE,YAAY,EAAE,CAAC;QAC5D,YAAY;KACb;AACH;AAEM,SAAU,6BAA6B,CAC3C,IAAY,EACZ,MAA0C,EAAA;IAE1C,QAAQ,IAAI;QACZ,KAAK,SAAS,CAAC,YAAY;AACzB,YAAA,OAAO,iCAAiC,CAAC,MAAM,CAAC;QAClD,KAAK,SAAS,CAAC,SAAS;AACtB,YAAA,OAAO,iCAAiC,CAAC,EAAE,MAAM,EAAE,CAAC;QACtD,KAAK,SAAS,CAAC,yBAAyB;AACtC,YAAA,OAAO,2CAA2C,CAAC,MAAM,CAAC;QAC5D,KAAK,SAAS,CAAC,8BAA8B;AAC3C,YAAA,OAAO,+CAA+C,CAAC,MAAM,CAAC;AAChE,QAAA;AACE,YAAA,OAAO,SAAS;;AAEpB;;;;"}
@@ -243,7 +243,9 @@ function shouldUseLocalSandbox(config) {
243
243
  }
244
244
  let sandboxOffWarned = false;
245
245
  function maybeWarnSandboxOff(config) {
246
- if (sandboxOffWarned || shouldUseLocalSandbox(config)) {
246
+ if (sandboxOffWarned ||
247
+ shouldUseLocalSandbox(config) ||
248
+ config.exec?.sandboxed === true) {
247
249
  return;
248
250
  }
249
251
  sandboxOffWarned = true;
@@ -479,6 +481,7 @@ function buildSandboxRuntimeConfig(config, cwd, getDefaultWritePaths) {
479
481
  },
480
482
  };
481
483
  }
484
+ const LOCAL_SPAWN_TIMEOUT_MS = Symbol('librechat.localSpawn.timeoutMs');
482
485
  async function spawnLocalProcess(command, args, config = {}, options) {
483
486
  const cwd = getLocalCwd(config);
484
487
  const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
@@ -514,12 +517,16 @@ async function spawnLocalProcess(command, args, config = {}, options) {
514
517
  }
515
518
  const launcher = getSpawn(config);
516
519
  return new Promise((resolveResult, reject) => {
517
- const child = launcher(spawnCommand, spawnArgs, {
520
+ const spawnOptions = {
518
521
  cwd,
519
522
  detached: process.platform !== 'win32',
520
523
  env: { ...process.env, ...(config.env ?? {}) },
521
524
  stdio: ['ignore', 'pipe', 'pipe'],
525
+ };
526
+ Object.defineProperty(spawnOptions, LOCAL_SPAWN_TIMEOUT_MS, {
527
+ value: timeoutMs,
522
528
  });
529
+ const child = launcher(spawnCommand, spawnArgs, spawnOptions);
523
530
  let stdout = '';
524
531
  let stderr = '';
525
532
  let totalSpawnedBytes = 0;
@@ -874,8 +881,10 @@ function configShell() {
874
881
  */
875
882
  const SIGKILL_ESCALATION_MS = 2000;
876
883
  function sigterm(child) {
877
- if (child.pid == null)
884
+ if (child.pid == null) {
885
+ child.kill('SIGTERM');
878
886
  return;
887
+ }
879
888
  try {
880
889
  if (process.platform === 'win32') {
881
890
  child.kill('SIGTERM');
@@ -888,10 +897,12 @@ function sigterm(child) {
888
897
  }
889
898
  }
890
899
  function sigkill(child) {
891
- if (child.pid == null)
892
- return;
893
900
  if (child.exitCode != null || child.signalCode != null)
894
901
  return;
902
+ if (child.pid == null) {
903
+ child.kill('SIGKILL');
904
+ return;
905
+ }
895
906
  try {
896
907
  if (process.platform === 'win32') {
897
908
  child.kill('SIGKILL');
@@ -1016,5 +1027,5 @@ async function resolveWorkspacePathSafe(filePath, config = {}, intent = 'write')
1016
1027
  throw new Error(`Path is outside the local workspace (symlink escape): ${filePath}`);
1017
1028
  }
1018
1029
 
1019
- export { _resetLocalEngineWarningsForTests, buildSandboxRuntimeConfig, executeLocalBash, executeLocalBashWithArgs, executeLocalCode, getLocalCwd, getLocalSessionId, getReadRoots, getSpawn, getWorkspaceFS, getWorkspaceRoots, getWriteRoots, resolveLocalExecutionConfig, resolveWorkspacePath, resolveWorkspacePathSafe, shellQuote, spawnLocalProcess, truncateLocalOutput, validateBashCommand };
1030
+ export { LOCAL_SPAWN_TIMEOUT_MS, _resetLocalEngineWarningsForTests, buildSandboxRuntimeConfig, executeLocalBash, executeLocalBashWithArgs, executeLocalCode, getLocalCwd, getLocalSessionId, getReadRoots, getSpawn, getWorkspaceFS, getWorkspaceRoots, getWriteRoots, resolveLocalExecutionConfig, resolveWorkspacePath, resolveWorkspacePathSafe, shellQuote, spawnLocalProcess, truncateLocalOutput, validateBashCommand };
1020
1031
  //# sourceMappingURL=LocalExecutionEngine.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"LocalExecutionEngine.mjs","sources":["../../../../src/tools/local/LocalExecutionEngine.ts"],"sourcesContent":["import { tmpdir } from 'os';\nimport { isAbsolute, relative, resolve } from 'path';\nimport { createHash, randomUUID } from 'crypto';\nimport { mkdir, realpath, rm, writeFile } from 'fs/promises';\nimport { createWriteStream } from 'fs';\nimport { spawn } from 'child_process';\nimport type { ChildProcess } from 'child_process';\nimport { runBashAstChecks, bashAstFindingsToErrors } from './bashAst';\nimport { nodeWorkspaceFS } from './workspaceFS';\nimport type { WorkspaceFS } from './workspaceFS';\nimport type * as t from '@/types';\n\nconst DEFAULT_TIMEOUT_MS = 60000;\nconst DEFAULT_MAX_OUTPUT_CHARS = 200000;\n/**\n * Hard cap on total stdout+stderr bytes a child process can stream\n * before we kill its process tree. Independent from `maxOutputChars`\n * (which only affects what the *model* sees) — this is the OOM\n * backstop. Configurable via `local.maxSpawnedBytes`.\n */\nconst DEFAULT_MAX_SPAWNED_BYTES = 50 * 1024 * 1024;\nconst DEFAULT_LOCAL_SESSION_ID = 'local';\nconst DEFAULT_SHELL = process.platform === 'win32' ? 'bash.exe' : 'bash';\n\n// `(?:--\\s+)?` before each destructive-target alternation: GNU/BSD\n// utilities accept `--` as an end-of-options marker, so `rm -rf -- /`\n// is identical in effect to `rm -rf /` but pre-fix it slipped past\n// the guard because the regex required the path to follow option\n// flags directly. Codex P1 #20.\n// `DESTRUCTIVE_TARGET` is the canonical \"protected location\" pattern:\n// matches `/`, `~`, `$HOME`, `${HOME}`, `.`, each optionally followed\n// by a trailing-slash and/or wildcard glob suffix. The suffix matrix:\n// '' — `$HOME` (round 14)\n// '/' — `$HOME/` (round 14, Codex P1 [37])\n// '*' — `$HOME*` (round 15, Codex P1 [42])\n// '/*' — `$HOME/*` (round 15, Codex P1 [42])\n// '.*' — `$HOME.*` (round 17, Codex P1 [47])\n// '/.*' — `$HOME/.*` (round 17, Codex P1 [47]) — the\n// dot-glob form deletes all dotfiles under the protected\n// root, just as destructive as `/*` but the prior matrix\n// missed it.\n// Suffix expression: `(?:\\/?\\.?\\*|\\/)?` — one of:\n// `\\/?\\.?\\*` → `*`, `.*`, `/*`, `/.*`\n// `\\/` → `/`\n// (empty) → bare base\nconst DESTRUCTIVE_TARGET = '(?:\\\\/|~|\\\\$\\\\{?HOME\\\\}?|\\\\.)(?:\\\\/?\\\\.?\\\\*|\\\\/)?';\n\nconst dangerousCommandPatterns: ReadonlyArray<RegExp> = [\n new RegExp(\n `\\\\brm\\\\s+(?:-[^\\\\s]*[rf][^\\\\s]*\\\\s+|-[^\\\\s]*[r][^\\\\s]*\\\\s+-[^\\\\s]*[f][^\\\\s]*\\\\s+)(?:--\\\\s+)?${DESTRUCTIVE_TARGET}\\\\s*(?:$|[;&|])`\n ),\n /\\b(?:mkfs|mkswap|fdisk|parted|diskutil)\\b/,\n /\\bdd\\s+[^;&|]*\\bof=\\/dev\\//,\n new RegExp(\n `\\\\bchmod\\\\s+-R\\\\s+(?:777|a\\\\+w)\\\\s+(?:--\\\\s+)?${DESTRUCTIVE_TARGET}(?:$|\\\\s|[;&|])`\n ),\n new RegExp(\n `\\\\bchown\\\\s+-R\\\\s+[^;&|]+\\\\s+(?:--\\\\s+)?${DESTRUCTIVE_TARGET}(?:$|\\\\s|[;&|])`\n ),\n /:\\s*\\(\\s*\\)\\s*\\{\\s*:\\s*\\|\\s*:\\s*&\\s*\\}\\s*;\\s*:/,\n];\n\n/**\n * Companion patterns that look for destructive targets *inside*\n * matching quote pairs. These are checked against the ORIGINAL\n * command (not the post-quote-strip `normalized` form), because\n * `stripQuotedContent` blanks the contents of quoted spans —\n * which would otherwise let `rm -rf \"/\"` and friends slip past\n * `dangerousCommandPatterns`.\n *\n * Kept as a separate list so we don't pay false-positive cost on\n * benign uses like `echo \"rm -rf /\"` (the print case): each pattern\n * here REQUIRES a quote *around the destructive path argument*, not\n * just a quote *somewhere* in the command. `echo \"rm -rf /\"` has\n * `/` outside of any quote-pair-around-the-path (the quotes wrap\n * the whole `rm -rf /` text), so it doesn't match here either.\n */\n// Quoted variant uses the same DESTRUCTIVE_TARGET (which accepts an\n// optional trailing slash) so `rm -rf \"$HOME/\"` and `rm -rf \"~/\"`\n// don't slip past. Codex P1 #37.\nconst quotedDestructivePatterns: ReadonlyArray<RegExp> = [\n new RegExp(\n `\\\\brm\\\\s+(?:-[^\\\\s]*[rf][^\\\\s]*\\\\s+){1,3}(?:--\\\\s+)?[\"']${DESTRUCTIVE_TARGET}[\"']`\n ),\n new RegExp(\n `\\\\bchmod\\\\s+-R\\\\s+(?:777|a\\\\+w)\\\\s+(?:--\\\\s+)?[\"']${DESTRUCTIVE_TARGET}[\"']`\n ),\n new RegExp(\n `\\\\bchown\\\\s+-R\\\\s+[^;&|]+\\\\s+(?:--\\\\s+)?[\"']${DESTRUCTIVE_TARGET}[\"']`\n ),\n];\n\n/**\n * Catches destructive operations smuggled inside a nested shell or\n * `eval` call, e.g. `bash -lc \"rm -rf $HOME\"` — the outer command\n * looks benign (`bash -lc \"...\"`) and the destructive `rm` lives\n * inside the quoted payload that `stripQuotedContent` blanks out.\n * Comprehensive review (manual finding C) flagged this as a real\n * bypass of the otherwise-correct quote-strip-then-match approach.\n *\n * Run against the ORIGINAL command (quotes intact) so the inside of\n * the nested-shell payload is visible. Conservative: matches only\n * the same operation set as `dangerousCommandPatterns` (rm -rf,\n * chmod -R 777, chown -R) when they appear inside a `<shell> -[l]?c\n * \"...\"` or `eval \"...\"` payload.\n */\nconst NESTED_SHELL_PREFIX = '(?:(?:ba|z|da|k)?sh|eval)\\\\s+(?:-l?c\\\\s+)?';\nconst nestedShellDestructivePatterns: ReadonlyArray<RegExp> = [\n new RegExp(\n NESTED_SHELL_PREFIX +\n '[\"\\'][^\"\\']*\\\\brm\\\\s+-[^\\\\s\"\\']*[rf][^\\\\s\"\\']*\\\\s+(?:--\\\\s+)?(?:\\\\/|~|\\\\$\\\\{?HOME\\\\}?|\\\\.)'\n ),\n new RegExp(\n NESTED_SHELL_PREFIX +\n '[\"\\'][^\"\\']*\\\\bchmod\\\\s+-R\\\\s+(?:777|a\\\\+w)\\\\s+(?:--\\\\s+)?(?:\\\\/|~|\\\\$\\\\{?HOME\\\\}?|\\\\.)'\n ),\n new RegExp(\n NESTED_SHELL_PREFIX +\n '[\"\\'][^\"\\']*\\\\bchown\\\\s+-R\\\\s+[^;&|]+\\\\s+(?:--\\\\s+)?(?:\\\\/|~|\\\\$\\\\{?HOME\\\\}?|\\\\.)'\n ),\n];\n\nconst mutatingCommandPattern =\n /\\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*/;\n\ntype SpawnResult = {\n stdout: string;\n stderr: string;\n exitCode: number | null;\n timedOut: boolean;\n /**\n * True when the process was force-killed because total streamed bytes\n * exceeded `maxSpawnedBytes`. Distinct from `timedOut`. Without this\n * flag, callers (`bash_tool`, `execute_code`, etc.) would see a\n * SIGKILL'd process with `exitCode: null` and treat it as success\n * (Codex P1 — runaway commands like `yes` or noisy builds silently\n * looked successful even though their output was truncated).\n */\n overflowKilled?: boolean;\n /**\n * Signal name (e.g. `'SIGKILL'`, `'SIGSEGV'`) when the process was\n * terminated by a signal. Distinct from the overflow-kill path:\n * this captures `kill -9 $$` from inside the script, native crashes,\n * OS OOM killer, etc. Without this, signal-killed processes\n * reported `exitCode: null` and looked like clean runs (Codex P2 —\n * generalization of the overflow-kill fix). When present, the\n * exitCode field is also synthesized to `128 + signum` per the\n * POSIX convention so non-null-exit-code consumers see a failure.\n */\n signal?: string;\n /** Path to the full untruncated stdout/stderr when output exceeded `maxOutputChars`. */\n fullOutputPath?: string;\n};\n\n/**\n * POSIX convention: `128 + signum` when a process is killed by a\n * signal. Maps the common signals; unknown ones default to 1 so the\n * caller still sees a non-zero (failed) exit. Only used when Node's\n * `close` event reports `exitCode === null` (true signal kill).\n */\nconst SIGNAL_TO_EXIT_CODE: Record<string, number> = {\n SIGHUP: 129,\n SIGINT: 130,\n SIGQUIT: 131,\n SIGILL: 132,\n SIGTRAP: 133,\n SIGABRT: 134,\n SIGBUS: 135,\n SIGFPE: 136,\n SIGKILL: 137,\n SIGUSR1: 138,\n SIGSEGV: 139,\n SIGUSR2: 140,\n SIGPIPE: 141,\n SIGALRM: 142,\n SIGTERM: 143,\n};\nfunction exitCodeForSignal(signal: string | null): number {\n if (signal == null) return 1;\n return SIGNAL_TO_EXIT_CODE[signal] ?? 1;\n}\n\ntype RuntimeCommand = {\n command: string;\n args: string[];\n fileName: string;\n source?: string;\n};\n\ntype SandboxManagerType = {\n checkDependencies(): { errors: string[] };\n initialize(config: BuiltSandboxRuntimeConfig): Promise<void>;\n reset(): Promise<void>;\n wrapWithSandbox(command: string): Promise<string>;\n};\n\ntype SandboxRuntimeModule = {\n getDefaultWritePaths(): string[];\n SandboxManager: SandboxManagerType;\n};\n\nlet sandboxConfigKey: string | undefined;\nlet sandboxInitialized = false;\nlet sandboxRuntimePromise: Promise<SandboxRuntimeModule> | undefined;\n\nexport type BashValidationResult = {\n valid: boolean;\n errors: string[];\n warnings: string[];\n};\n\nfunction isToolExecutionConfig(\n config: t.ToolExecutionConfig | t.LocalExecutionConfig\n): config is t.ToolExecutionConfig {\n return 'engine' in config || 'local' in config;\n}\n\nexport function resolveLocalExecutionConfig(\n config?: t.ToolExecutionConfig | t.LocalExecutionConfig\n): t.LocalExecutionConfig {\n if (config != null && isToolExecutionConfig(config)) {\n return config.local ?? {};\n }\n return config ?? {};\n}\n\nexport function getLocalCwd(config?: t.LocalExecutionConfig): string {\n return resolve(config?.workspace?.root ?? config?.cwd ?? process.cwd());\n}\n\n/**\n * Resolves the effective workspace boundary: a list of absolute roots\n * that file operations are allowed to touch. The first entry is always\n * the canonical root (`getLocalCwd`); subsequent entries come from\n * `workspace.additionalRoots` when provided.\n *\n * Returns plain absolute paths — callers symlink-resolve when they\n * need realpath equality (see `resolveWorkspacePathSafe`).\n */\nexport function getWorkspaceRoots(config?: t.LocalExecutionConfig): string[] {\n const root = getLocalCwd(config);\n const extras = config?.workspace?.additionalRoots ?? [];\n if (extras.length === 0) return [root];\n const seen = new Set<string>([root]);\n const out: string[] = [root];\n for (const extra of extras) {\n // Relative `additionalRoots` entries are anchored to the\n // workspace root (so monorepo configs like\n // `additionalRoots: ['../shared']` resolve to a sibling of\n // `root` rather than to `process.cwd()/../shared`, which would\n // mean something completely different on a server with a\n // different cwd).\n const abs = isAbsolute(extra) ? resolve(extra) : resolve(root, extra);\n if (!seen.has(abs)) {\n seen.add(abs);\n out.push(abs);\n }\n }\n return out;\n}\n\n/**\n * Pluggable spawn resolver. Honours `local.exec.spawn` first, falls\n * back to the legacy top-level `local.spawn`, then to Node's\n * `child_process.spawn`. Centralised so engine swapping is one knob.\n */\nexport function getSpawn(config?: t.LocalExecutionConfig): t.LocalSpawn {\n return (config?.exec?.spawn ?? config?.spawn ?? spawn) as t.LocalSpawn;\n}\n\n/**\n * Pluggable filesystem resolver. Honours `local.exec.fs`, falls back\n * to the Node-host implementation. A future remote engine supplies\n * its own implementation here and inherits every file-touching tool.\n */\nexport function getWorkspaceFS(config?: t.LocalExecutionConfig): WorkspaceFS {\n return config?.exec?.fs ?? nodeWorkspaceFS;\n}\n\n/**\n * Resolves the workspace boundary for *write* operations. Honours\n * `workspace.allowWriteOutside` (and the deprecated\n * `allowOutsideWorkspace`) by returning `null`, which the path-safety\n * helpers interpret as \"skip the write clamp\".\n */\nexport function getWriteRoots(\n config: t.LocalExecutionConfig = {}\n): string[] | null {\n // Granular flag wins over the legacy one when explicitly set\n // (true OR false) — otherwise a host tightening access during\n // migration (`allowOutsideWorkspace: true, workspace.\n // allowWriteOutside: false`) would still get the loose behavior\n // because the legacy flag short-circuited the OR. Codex P1 #36.\n const granular = config.workspace?.allowWriteOutside;\n if (granular === true) return null;\n if (granular === false) return getWorkspaceRoots(config);\n if (config.allowOutsideWorkspace === true) return null;\n return getWorkspaceRoots(config);\n}\n\n/**\n * Resolves the workspace boundary for *read* operations. Honours\n * `workspace.allowReadOutside` (and the deprecated\n * `allowOutsideWorkspace`) by returning `null`.\n */\nexport function getReadRoots(\n config: t.LocalExecutionConfig = {}\n): string[] | null {\n // Same precedence as getWriteRoots: granular flag is authoritative\n // when set, legacy flag is the fallback. Codex P1 #36.\n const granular = config.workspace?.allowReadOutside;\n if (granular === true) return null;\n if (granular === false) return getWorkspaceRoots(config);\n if (config.allowOutsideWorkspace === true) return null;\n return getWorkspaceRoots(config);\n}\n\nexport function getLocalSessionId(config?: t.LocalExecutionConfig): string {\n const cwd = getLocalCwd(config);\n const digest = createHash('sha1').update(cwd).digest('hex').slice(0, 12);\n return `${DEFAULT_LOCAL_SESSION_ID}:${digest}`;\n}\n\nconst missingSandboxRuntimeMessage = [\n 'Local sandbox is enabled, but @anthropic-ai/sandbox-runtime is not installed.',\n 'Install it with `npm install @anthropic-ai/sandbox-runtime`, or disable local sandboxing with `local.sandbox.enabled: false`.',\n].join(' ');\nconst sandboxRuntimePackage = '@anthropic-ai/sandbox-runtime';\n\n/** Lazy-loads the ESM-only sandbox runtime only when sandboxing is enabled. */\nfunction loadSandboxRuntime(): Promise<SandboxRuntimeModule> {\n sandboxRuntimePromise ??= import(\n sandboxRuntimePackage\n ) as Promise<SandboxRuntimeModule>;\n return sandboxRuntimePromise;\n}\n\nfunction shouldUseLocalSandbox(config: t.LocalExecutionConfig): boolean {\n return config.sandbox?.enabled === true;\n}\n\nlet sandboxOffWarned = false;\n\nfunction maybeWarnSandboxOff(config: t.LocalExecutionConfig): void {\n if (sandboxOffWarned || shouldUseLocalSandbox(config)) {\n return;\n }\n sandboxOffWarned = true;\n // eslint-disable-next-line no-console\n console.warn(\n '[@librechat/agents] Local execution engine is running without ' +\n '@anthropic-ai/sandbox-runtime wrapping. The agent has full access to ' +\n 'the host filesystem and network. Set toolExecution.local.sandbox.enabled ' +\n '= true to opt into process sandboxing.'\n );\n}\n\n/**\n * Test-only reset hook for the sandbox-off warning latch.\n *\n * @internal Not part of the public SDK surface.\n */\nexport function _resetLocalEngineWarningsForTests(): void {\n sandboxOffWarned = false;\n}\n\nexport function truncateLocalOutput(\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 stripQuotedContent(command: string): string {\n let output = '';\n let quote: '\"' | '\\'' | '`' | undefined;\n let escaped = false;\n\n for (let i = 0; i < command.length; i++) {\n const char = command[i];\n\n if (escaped) {\n escaped = false;\n output += ' ';\n continue;\n }\n\n if (char === '\\\\') {\n escaped = true;\n output += ' ';\n continue;\n }\n\n if (quote != null) {\n if (char === quote) {\n quote = undefined;\n }\n output += ' ';\n continue;\n }\n\n if (char === '\"' || char === '\\'' || char === '`') {\n quote = char;\n output += ' ';\n continue;\n }\n\n if (char === '#') {\n while (i < command.length && command[i] !== '\\n') {\n output += ' ';\n i++;\n }\n output += '\\n';\n continue;\n }\n\n output += char;\n }\n\n return output;\n}\n\nexport async function validateBashCommand(\n command: string,\n config: t.LocalExecutionConfig = {}\n): Promise<BashValidationResult> {\n const errors: string[] = [];\n const warnings: string[] = [];\n const normalized = stripQuotedContent(command);\n\n if (command.trim() === '') {\n errors.push('Command is empty.');\n }\n\n if (command.includes('\\0')) {\n errors.push('Command contains a NUL byte.');\n }\n\n if (config.allowDangerousCommands !== true) {\n let blocked = false;\n // Strip-then-match for the bare-form patterns (avoids false\n // positives where the destructive text is buried inside a\n // string the user is just printing).\n for (const pattern of dangerousCommandPatterns) {\n if (pattern.test(normalized)) {\n errors.push('Command matches a destructive command pattern.');\n blocked = true;\n break;\n }\n }\n // Original-form pass for patterns that REQUIRE matching quote\n // pairs around a destructive path. Without this, `rm -rf \"/\"`\n // and `chmod -R 777 \"/\"` slip past the strip-then-match pass\n // because their destructive target is inside quotes.\n if (!blocked) {\n for (const pattern of quotedDestructivePatterns) {\n if (pattern.test(command)) {\n errors.push(\n 'Command matches a destructive command pattern (quoted target).'\n );\n blocked = true;\n break;\n }\n }\n }\n if (!blocked) {\n for (const pattern of nestedShellDestructivePatterns) {\n if (pattern.test(command)) {\n errors.push(\n 'Command matches a destructive command pattern (nested shell payload).'\n );\n break;\n }\n }\n }\n }\n\n const bashAstMode = config.bashAst ?? 'off';\n if (bashAstMode !== 'off' && config.allowDangerousCommands !== true) {\n const findings = runBashAstChecks(normalized, bashAstMode);\n const split = bashAstFindingsToErrors(findings);\n errors.push(...split.errors);\n warnings.push(...split.warnings);\n }\n\n if (config.readOnly === true && mutatingCommandPattern.test(normalized)) {\n errors.push(\n 'Command appears to mutate files or repository state in read-only local mode.'\n );\n }\n\n // Use the same shell the actual execution path will use. Hard-coding\n // DEFAULT_SHELL here would reject perfectly valid commands when the\n // host configures `local.shell` to a non-bash binary (or when the\n // runtime doesn't have bash installed at all but does have e.g. zsh).\n const syntaxShell = config.shell ?? DEFAULT_SHELL;\n const syntax = await spawnLocalProcess(\n syntaxShell,\n ['-n', '-c', command],\n {\n ...config,\n timeoutMs: Math.min(config.timeoutMs ?? DEFAULT_TIMEOUT_MS, 5000),\n sandbox: { enabled: false },\n },\n { internal: true }\n ).catch(\n (error: Error): SpawnResult => ({\n stdout: '',\n stderr: error.message,\n exitCode: 1,\n timedOut: false,\n })\n );\n\n if (syntax.exitCode !== 0) {\n errors.push(\n syntax.stderr.trim() === ''\n ? 'Command failed shell syntax validation.'\n : `Command failed shell syntax validation: ${syntax.stderr.trim()}`\n );\n }\n\n if (/\\bsudo\\b/.test(normalized)) {\n warnings.push('Command requests elevated privileges with sudo.');\n }\n\n return {\n valid: errors.length === 0,\n errors,\n warnings,\n };\n}\n\nasync function ensureSandbox(\n config: t.LocalExecutionConfig,\n cwd: string\n): Promise<SandboxManagerType | undefined> {\n if (!shouldUseLocalSandbox(config)) {\n return undefined;\n }\n\n const runtime = await loadSandboxRuntime().catch((error: Error) => {\n throw new Error(`${missingSandboxRuntimeMessage} Cause: ${error.message}`);\n });\n\n const runtimeConfig = buildSandboxRuntimeConfig(\n config,\n cwd,\n runtime.getDefaultWritePaths\n );\n const nextKey = JSON.stringify(runtimeConfig);\n\n if (sandboxInitialized && sandboxConfigKey === nextKey) {\n return runtime.SandboxManager;\n }\n\n const dependencyCheck = runtime.SandboxManager.checkDependencies();\n if (dependencyCheck.errors.length > 0) {\n if (config.sandbox?.failIfUnavailable === true) {\n throw new Error(\n `Local sandbox requested but unavailable: ${dependencyCheck.errors.join('; ')}`\n );\n }\n return undefined;\n }\n\n if (sandboxInitialized) {\n await runtime.SandboxManager.reset();\n }\n\n await runtime.SandboxManager.initialize(runtimeConfig);\n sandboxInitialized = true;\n sandboxConfigKey = nextKey;\n return runtime.SandboxManager;\n}\n\n/**\n * Loopback addresses the in-process programmatic-tool bridge listens\n * on (`LocalProgrammaticToolCalling.ts` binds 127.0.0.1). Sandboxed\n * code launched by `run_tools_with_code` / `run_tools_with_bash` HTTPs\n * back to that address — without the entries below, the bridge is\n * silently blocked under sandbox.\n */\nconst BRIDGE_LOOPBACK_HOSTS = ['127.0.0.1', 'localhost', '::1'] as const;\n\n/**\n * Structural shape of the sandbox-runtime config we hand to\n * `SandboxManager.initialize()`. Intentionally NOT typed as the peer\n * `SandboxRuntimeConfig` from `@anthropic-ai/sandbox-runtime`: that\n * package is an OPTIONAL peer dep, and exporting a function whose\n * return type references it would make our generated `.d.ts` import\n * a module the consumer may not have installed (Codex P1 #22 — type-\n * checking would fail with `Cannot find module\n * '@anthropic-ai/sandbox-runtime'` for any host that doesn't enable\n * local sandboxing). The shape here is a structural subset; assignable\n * to the real `SandboxRuntimeConfig` at the one runtime call site.\n *\n * @internal\n */\nexport interface BuiltSandboxRuntimeConfig {\n network: {\n allowedDomains: string[];\n deniedDomains: string[];\n allowUnixSockets?: string[];\n allowAllUnixSockets?: boolean;\n allowLocalBinding?: boolean;\n allowMachLookup?: string[];\n };\n filesystem: {\n denyRead: string[];\n allowRead?: string[];\n allowWrite: string[];\n denyWrite: string[];\n allowGitConfig?: boolean;\n };\n}\n\nexport function buildSandboxRuntimeConfig(\n config: t.LocalExecutionConfig,\n cwd: string,\n getDefaultWritePaths: () => string[]\n): BuiltSandboxRuntimeConfig {\n const sandbox = config.sandbox;\n // Seed allowedDomains with loopback so the programmatic-tool bridge\n // works under sandbox. If the host explicitly denied a loopback\n // entry via `deniedDomains`, respect that and skip seeding it.\n const userAllowed = sandbox?.network?.allowedDomains ?? [];\n const denied = new Set(sandbox?.network?.deniedDomains ?? []);\n const seededLoopback = BRIDGE_LOOPBACK_HOSTS.filter(\n (host) => !denied.has(host) && !userAllowed.includes(host)\n );\n const allowedDomains = [...seededLoopback, ...userAllowed];\n // Mirror the file-tools workspace boundary: anything in\n // `additionalRoots` counts as in-workspace, so sandboxed shell/code\n // can write there too. Without this, file_tools can resolve a\n // sibling-root path but `bash`/`execute_code` is denied write\n // access — confusing divergence flagged in Codex P2 #15.\n const workspaceWriteRoots =\n config.workspace?.additionalRoots != null\n ? getWorkspaceRoots(config)\n : [cwd];\n return {\n network: {\n allowedDomains,\n deniedDomains: sandbox?.network?.deniedDomains ?? [],\n ...(sandbox?.network?.allowUnixSockets != null && {\n allowUnixSockets: sandbox.network.allowUnixSockets,\n }),\n ...(sandbox?.network?.allowAllUnixSockets != null && {\n allowAllUnixSockets: sandbox.network.allowAllUnixSockets,\n }),\n ...(sandbox?.network?.allowLocalBinding != null && {\n allowLocalBinding: sandbox.network.allowLocalBinding,\n }),\n ...(sandbox?.network?.allowMachLookup != null && {\n allowMachLookup: sandbox.network.allowMachLookup,\n }),\n },\n filesystem: {\n denyRead: sandbox?.filesystem?.denyRead ?? [],\n allowRead: sandbox?.filesystem?.allowRead,\n allowWrite: sandbox?.filesystem?.allowWrite ?? [\n ...workspaceWriteRoots,\n ...getDefaultWritePaths(),\n ],\n denyWrite: sandbox?.filesystem?.denyWrite ?? [\n '.env',\n '.env.*',\n '.git/config',\n '.git/hooks/**',\n ],\n allowGitConfig: sandbox?.filesystem?.allowGitConfig,\n },\n };\n}\n\n/**\n * Internal options for {@link spawnLocalProcess} that we don't want\n * exposed on the public `LocalExecutionConfig` type.\n *\n * @internal\n */\nexport interface SpawnLocalProcessOptions {\n /**\n * When true, suppress the \"sandbox is off\" warning AND its latch\n * for this spawn. Use for SDK-internal probes (`bash -n` syntax\n * preflight, `rg --version`, etc.) that intentionally run with\n * the sandbox forced off — the warning is noise for those, and\n * letting the latch flip would hide the warning when a *real*\n * unsandboxed execution happens later in the same process.\n */\n internal?: boolean;\n}\n\nexport async function spawnLocalProcess(\n command: string,\n args: string[],\n config: t.LocalExecutionConfig = {},\n options?: SpawnLocalProcessOptions\n): Promise<SpawnResult> {\n const cwd = getLocalCwd(config);\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const maxOutputChars = config.maxOutputChars ?? DEFAULT_MAX_OUTPUT_CHARS;\n // Streaming caps. Local tools execute arbitrary shell/code, so a noisy\n // command (`yes`, `cat /dev/urandom | base64`, a verbose build) could\n // accumulate gigabytes in memory before hitting the post-close cap.\n // We bound in-memory per-stream and spill the rest to disk; we also\n // hard-kill the child once total streamed bytes pass `maxSpawnedBytes`\n // so a process producing unbounded output gets stopped instead of\n // letting the host OOM.\n const inMemoryCapBytes = maxOutputChars * 2;\n const hardKillBytes = config.maxSpawnedBytes ?? DEFAULT_MAX_SPAWNED_BYTES;\n const sandboxManager = await ensureSandbox(config, cwd);\n // Internal probes (validateBashCommand syntax preflight,\n // isRipgrepAvailable, syntax-check probe cache priming) pass\n // `internal: true` so they don't emit a misleading \"sandbox is\n // off\" warning AND don't flip `sandboxOffWarned = true`. Without\n // this Codex P2 path: a run with `sandbox.enabled: true` would\n // see a false warning from the syntax preflight, and the latch\n // flip would suppress the warning in a *later* truly-unsandboxed\n // run — exactly the scenario operators need to see.\n if (sandboxManager == null && options?.internal !== true) {\n maybeWarnSandboxOff(config);\n }\n let spawnCommand = command;\n let spawnArgs = args;\n\n if (sandboxManager != null) {\n const rendered = [command, ...args.map(shellQuote)].join(' ');\n const sandboxed = await sandboxManager.wrapWithSandbox(rendered);\n spawnCommand = config.shell ?? DEFAULT_SHELL;\n spawnArgs = ['-lc', sandboxed];\n }\n\n const launcher = getSpawn(config);\n return new Promise<SpawnResult>((resolveResult, reject) => {\n const child = launcher(spawnCommand, spawnArgs, {\n cwd,\n detached: process.platform !== 'win32',\n env: { ...process.env, ...(config.env ?? {}) },\n stdio: ['ignore', 'pipe', 'pipe'],\n });\n\n let stdout = '';\n let stderr = '';\n let totalSpawnedBytes = 0;\n let overflowKilled = false;\n let spillStream: import('fs').WriteStream | undefined;\n let spillPath: string | undefined;\n let settled = false;\n let timedOut = false;\n let timeout: NodeJS.Timeout | undefined;\n\n const ensureSpill = (): void => {\n if (spillStream != null) return;\n // Lazy-open the temp file the first time a stream's in-memory\n // buffer overflows. Seed it with everything we've buffered so\n // the file holds the FULL output (not just the post-cap tail).\n // Uses the static `createWriteStream` import — `require('fs')`\n // would throw `ReferenceError: require is not defined` in ESM\n // consumers (this package ships both `dist/cjs` and `dist/esm`).\n spillPath = resolve(tmpdir(), `lc-local-output-${randomUUID()}.txt`);\n spillStream = createWriteStream(spillPath);\n spillStream.write('===== stdout =====\\n');\n spillStream.write(stdout);\n spillStream.write('\\n===== stderr =====\\n');\n spillStream.write(stderr);\n spillStream.write('\\n===== overflow stream begins here =====\\n');\n };\n\n const handleChunk = (buf: Buffer, kind: 'stdout' | 'stderr'): void => {\n totalSpawnedBytes += buf.length;\n // hardKillBytes <= 0 means \"no cap\" per the public config contract\n // (see LocalExecutionConfig.maxSpawnedBytes). Skip the kill check\n // entirely in that case so a single byte doesn't terminate the run.\n if (\n hardKillBytes > 0 &&\n totalSpawnedBytes > hardKillBytes &&\n !overflowKilled\n ) {\n overflowKilled = true;\n killProcessTree(child);\n return;\n }\n const current = kind === 'stdout' ? stdout : stderr;\n if (current.length < inMemoryCapBytes) {\n const text = buf.toString('utf8');\n if (kind === 'stdout') stdout += text;\n else stderr += text;\n if (current.length + text.length >= inMemoryCapBytes) {\n ensureSpill();\n }\n } else {\n ensureSpill();\n spillStream!.write(`[${kind}] `);\n spillStream!.write(buf);\n }\n };\n\n const finish = (result: SpawnResult): void => {\n if (settled) {\n return;\n }\n settled = true;\n if (timeout != null) {\n clearTimeout(timeout);\n }\n const finalize = (): void => {\n const truncated = {\n stdout: truncateLocalOutput(result.stdout, maxOutputChars),\n stderr: truncateLocalOutput(result.stderr, maxOutputChars),\n };\n resolveResult({\n ...result,\n ...truncated,\n ...(spillPath != null ? { fullOutputPath: spillPath } : {}),\n });\n };\n if (spillStream == null) {\n finalize();\n return;\n }\n // Wait for the temp file to flush before reporting the path.\n // Otherwise the model sees `full_output_path: …` for a file\n // that's still being written.\n spillStream.end(() => finalize());\n };\n\n const fail = (error: Error): void => {\n if (settled) {\n return;\n }\n settled = true;\n if (timeout != null) {\n clearTimeout(timeout);\n }\n if (spillStream != null) {\n spillStream.end();\n }\n reject(error);\n };\n\n if (timeoutMs > 0) {\n timeout = setTimeout(() => {\n timedOut = true;\n killProcessTree(child);\n }, timeoutMs);\n }\n\n child.stdout.on('data', (chunk: Buffer) => {\n handleChunk(chunk, 'stdout');\n });\n\n child.stderr.on('data', (chunk: Buffer) => {\n handleChunk(chunk, 'stderr');\n });\n\n child.on('error', fail);\n\n child.on('close', (exitCode, signal) => {\n // Synthesize a non-zero exit code whenever the process exited\n // by signal — Node reports `exitCode: null` in that case and\n // the formatter only prints non-null exit codes, so signal\n // kills (overflow guard, `kill -9 $$` from inside the script,\n // native crashes, OS OOM killer, …) would otherwise look like\n // successful runs (Codex P1 + Codex P2). Overflow path keeps\n // its 137 (SIGKILL) for compatibility; other signals map per\n // POSIX `128 + signum`.\n let finalExit: number | null = exitCode;\n if (finalExit == null) {\n if (overflowKilled) {\n finalExit = 137;\n } else if (signal != null) {\n finalExit = exitCodeForSignal(signal);\n }\n }\n finish({\n stdout,\n stderr,\n exitCode: finalExit,\n timedOut,\n ...(overflowKilled ? { overflowKilled: true } : {}),\n ...(signal != null ? { signal } : {}),\n });\n });\n });\n}\n\nexport async function executeLocalBash(\n command: string,\n config: t.LocalExecutionConfig = {}\n): Promise<SpawnResult> {\n const validation = await validateBashCommand(command, config);\n if (!validation.valid) {\n throw new Error(validation.errors.join('\\n'));\n }\n const shell = config.shell ?? DEFAULT_SHELL;\n return spawnLocalProcess(shell, ['-lc', command], config);\n}\n\n/**\n * Variant of `executeLocalBash` that exposes `args` as positional\n * shell parameters (`$1`, `$2`, …). Mirrors what the other runtimes\n * do in `getRuntimeCommand`. Uses the standard `bash -c <code> --\n * arg0 arg1 …` form: the `--` becomes `$0`, then `args[0]` is `$1`\n * and so on. Same AST validation as the no-args path.\n *\n * Used by both the `execute_code`/`lang:'bash'` path AND the\n * `bash_tool` factory so the schema's `args` contract works\n * identically in both surfaces.\n */\n/**\n * Matches a single arg that, on its own, references a protected\n * location (`/`, `~`, `$HOME`, `${HOME}`, `.`, with optional trailing\n * slash, wildcard, or dot-glob suffix). Used to spot the\n * `command: 'rm -rf \"$1\"', args: ['/']` shape where the destructive\n * target is moved into a positional arg to evade the command regex.\n * Codex P1 [45], extended for dot-glob in Codex P1 [47] (mirrors the\n * `DESTRUCTIVE_TARGET` suffix matrix exactly).\n */\nconst PROTECTED_TARGET_ARG_RE = /^(?:\\/|~|\\$\\{?HOME\\}?|\\.)(?:\\/?\\.?\\*|\\/)?$/;\n\n/**\n * Mutating-op recognizer for the args check. Conservative: only the\n * three operations the destructive-command guard already covers\n * directly (`rm -rf …`, `chmod -R …`, `chown -R …`). Other shell\n * builtins might mutate state (`mv`, `cp` over an existing file,\n * etc.) but the destructive guard doesn't try to catch those today,\n * so we don't widen here either.\n */\nconst DESTRUCTIVE_OP_IN_COMMAND_RE =\n /\\b(?:rm\\s+-[^\\s]*[rf]|chmod\\s+-R|chown\\s+-R)\\b/;\n\nexport async function executeLocalBashWithArgs(\n command: string,\n args: readonly string[],\n config: t.LocalExecutionConfig = {}\n): Promise<SpawnResult> {\n const validation = await validateBashCommand(command, config);\n if (!validation.valid) {\n throw new Error(validation.errors.join('\\n'));\n }\n // Per-arg protected-target check (Codex P1 [45]). The command\n // regex can't see `$1`/`$@` substitutions at runtime — `command:\n // 'rm -rf \"$1\"', args: ['/']` would expand to `rm -rf '/'` inside\n // bash but the validator only saw `rm -rf \"$1\"` (no destructive\n // target). Block when (a) the command contains a destructive op\n // AND (b) at least one arg matches the protected-target shape.\n // Skipped when allowDangerousCommands is true (host-opted-in).\n if (\n args.length > 0 &&\n config.allowDangerousCommands !== true &&\n DESTRUCTIVE_OP_IN_COMMAND_RE.test(command)\n ) {\n const offending = args.find((a) => PROTECTED_TARGET_ARG_RE.test(a));\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 const shell = config.shell ?? DEFAULT_SHELL;\n return spawnLocalProcess(shell, ['-lc', command, '--', ...args], config);\n}\n\nexport async function executeLocalCode(\n input: {\n lang: string;\n code: string;\n args?: string[];\n },\n config: t.LocalExecutionConfig = {}\n): Promise<SpawnResult> {\n if (input.lang === 'bash') {\n // Append `args` as positional parameters via the standard\n // `bash -c <code> -- <args...>` form so `$1`, `$2`, … inside\n // `code` resolve correctly. Honours the same args contract the\n // other runtimes (py, js, …) already support.\n if (input.args != null && input.args.length > 0) {\n return executeLocalBashWithArgs(input.code, input.args, config);\n }\n return executeLocalBash(input.code, config);\n }\n\n const tempDir = resolve(tmpdir(), `lc-local-${randomUUID()}`);\n await mkdir(tempDir, { recursive: true });\n\n try {\n const runtime = getRuntimeCommand(\n input.lang,\n tempDir,\n input.code,\n input.args,\n config.shell\n );\n if (runtime.source != null) {\n await writeFile(\n resolve(tempDir, runtime.fileName),\n runtime.source,\n 'utf8'\n );\n }\n return await spawnLocalProcess(runtime.command, runtime.args, config);\n } finally {\n await rm(tempDir, { recursive: true, force: true });\n }\n}\n\nfunction getRuntimeCommand(\n lang: string,\n tempDir: string,\n code: string,\n args: string[] = [],\n // Override for the shell used by compile-style runtimes (`rs`,\n // `c`, `cpp`, `java`, `d`, `f90`). Threads `local.shell` so a host\n // that doesn't have bash (or wants `/bin/sh` / zsh) can still\n // execute these languages — Codex P2 #29: the bare-bash hardcode\n // mirrored the same gap that Codex P1 #6 fixed for the syntax\n // preflight, but had been missed for these runtime invocations.\n shellOverride?: string\n): RuntimeCommand {\n const fileFor = (name: string): string => resolve(tempDir, name);\n const shell = shellOverride ?? configShell();\n\n switch (lang) {\n case 'py':\n return {\n command: 'python3',\n args: [fileFor('main.py'), ...args],\n fileName: 'main.py',\n source: code,\n };\n case 'js':\n return {\n command: 'node',\n args: [fileFor('main.js'), ...args],\n fileName: 'main.js',\n source: code,\n };\n case 'ts':\n return {\n command: 'npx',\n args: ['--no-install', 'tsx', fileFor('main.ts'), ...args],\n fileName: 'main.ts',\n source: code,\n };\n case 'php':\n return {\n command: 'php',\n args: [fileFor('main.php'), ...args],\n fileName: 'main.php',\n source: code,\n };\n case 'go':\n return {\n command: 'go',\n args: ['run', fileFor('main.go'), ...args],\n fileName: 'main.go',\n source: code,\n };\n case 'rs':\n return {\n command: shell,\n args: [\n '-lc',\n `rustc ${shellQuote(fileFor('main.rs'))} -o ${shellQuote(\n fileFor('main-rs')\n )} && ${shellQuote(fileFor('main-rs'))} ${args.map(shellQuote).join(' ')}`,\n ],\n fileName: 'main.rs',\n source: code,\n };\n case 'c':\n return {\n command: shell,\n args: [\n '-lc',\n `cc ${shellQuote(fileFor('main.c'))} -o ${shellQuote(\n fileFor('main-c')\n )} && ${shellQuote(fileFor('main-c'))} ${args.map(shellQuote).join(' ')}`,\n ],\n fileName: 'main.c',\n source: code,\n };\n case 'cpp':\n return {\n command: shell,\n args: [\n '-lc',\n `c++ ${shellQuote(fileFor('main.cpp'))} -o ${shellQuote(\n fileFor('main-cpp')\n )} && ${shellQuote(fileFor('main-cpp'))} ${args.map(shellQuote).join(' ')}`,\n ],\n fileName: 'main.cpp',\n source: code,\n };\n case 'java':\n return {\n command: shell,\n args: [\n '-lc',\n `javac ${shellQuote(fileFor('Main.java'))} && java -cp ${shellQuote(\n tempDir\n )} Main ${args.map(shellQuote).join(' ')}`,\n ],\n fileName: 'Main.java',\n source: code,\n };\n case 'r':\n return {\n command: 'Rscript',\n args: [fileFor('main.R'), ...args],\n fileName: 'main.R',\n source: code,\n };\n case 'd':\n return {\n command: shell,\n args: [\n '-lc',\n `dmd ${shellQuote(fileFor('main.d'))} -of=${shellQuote(\n fileFor('main-d')\n )} && ${shellQuote(fileFor('main-d'))} ${args.map(shellQuote).join(' ')}`,\n ],\n fileName: 'main.d',\n source: code,\n };\n case 'f90':\n return {\n command: shell,\n args: [\n '-lc',\n `gfortran ${shellQuote(fileFor('main.f90'))} -o ${shellQuote(\n fileFor('main-f90')\n )} && ${shellQuote(fileFor('main-f90'))} ${args.map(shellQuote).join(' ')}`,\n ],\n fileName: 'main.f90',\n source: code,\n };\n default:\n throw new Error(`Unsupported local runtime: ${lang}`);\n }\n}\n\nfunction configShell(): string {\n return process.platform === 'win32' ? 'bash.exe' : 'bash';\n}\n\n/**\n * How long after SIGTERM we wait before escalating to SIGKILL. A\n * cooperative process gets a graceful chance to flush + clean up;\n * a process that ignores or traps SIGTERM (`trap '' TERM`) gets\n * killed unconditionally so timeoutMs / maxSpawnedBytes can't be\n * defeated by a hostile script. Codex P1 #28 — pre-fix the spawn\n * promise would never resolve in that case and the entire tool run\n * would hang past the advertised timeout.\n */\nconst SIGKILL_ESCALATION_MS = 2000;\n\nfunction sigterm(child: ChildProcess): void {\n if (child.pid == null) return;\n try {\n if (process.platform === 'win32') {\n child.kill('SIGTERM');\n return;\n }\n process.kill(-child.pid, 'SIGTERM');\n } catch {\n child.kill('SIGTERM');\n }\n}\n\nfunction sigkill(child: ChildProcess): void {\n if (child.pid == null) return;\n if (child.exitCode != null || child.signalCode != null) return;\n try {\n if (process.platform === 'win32') {\n child.kill('SIGKILL');\n return;\n }\n process.kill(-child.pid, 'SIGKILL');\n } catch {\n try {\n child.kill('SIGKILL');\n } catch {\n /* already dead */\n }\n }\n}\n\nfunction killProcessTree(child: ChildProcess): void {\n sigterm(child);\n // Escalate to SIGKILL if the child is still alive after the grace\n // window. Use unref() so the timer doesn't keep the Node process\n // alive past the parent's natural exit.\n const escalation = setTimeout(() => sigkill(child), SIGKILL_ESCALATION_MS);\n escalation.unref();\n child.once('close', () => clearTimeout(escalation));\n}\n\nexport function shellQuote(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\nexport function resolveWorkspacePath(\n filePath: string,\n config: t.LocalExecutionConfig = {},\n intent: 'read' | 'write' = 'write'\n): string {\n const cwd = getLocalCwd(config);\n const absolutePath = isAbsolute(filePath)\n ? resolve(filePath)\n : resolve(cwd, filePath);\n\n const roots =\n intent === 'write' ? getWriteRoots(config) : getReadRoots(config);\n if (roots == null) return absolutePath; // explicit allow-outside\n\n if (absolutePath === cwd || isInsideAnyRoot(absolutePath, roots)) {\n return absolutePath;\n }\n throw new Error(`Path is outside the local workspace: ${filePath}`);\n}\n\nfunction isInsideAnyRoot(absolutePath: string, roots: string[]): boolean {\n for (const root of roots) {\n if (absolutePath === root) return true;\n const rel = relative(root, absolutePath);\n if (!rel.startsWith('..') && !isAbsolute(rel)) return true;\n }\n return false;\n}\n\ntype RealpathFn = (p: string) => Promise<string>;\n\nasync function realpathOrSelf(\n absolutePath: string,\n realpathImpl: RealpathFn = realpath\n): Promise<string> {\n try {\n return await realpathImpl(absolutePath);\n } catch {\n return absolutePath;\n }\n}\n\n/**\n * Resolves the realpath of `absolutePath`, falling back to the nearest\n * existing ancestor when the target itself does not yet exist (so the\n * containment check still works for `write_file` to a brand-new path).\n *\n * Codex P2 #38: takes the realpath impl as a parameter so callers\n * can route through `WorkspaceFS.realpath` when a custom engine is\n * configured. Pre-fix, host `fs/promises.realpath` would fail on a\n * remote/in-memory FS path and silently fall back to lexical\n * containment, leaving the symlink-escape clamp ineffective on\n * non-default engines.\n */\nasync function realpathOfPathOrAncestor(\n absolutePath: string,\n realpathImpl: RealpathFn = realpath\n): Promise<string> {\n let current = absolutePath;\n let suffix = '';\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n while (true) {\n try {\n const real = await realpathImpl(current);\n return suffix === '' ? real : resolve(real, suffix);\n } catch {\n const parent = resolve(current, '..');\n if (parent === current) {\n return absolutePath;\n }\n const base = current.slice(parent.length + 1);\n suffix = suffix === '' ? base : `${base}/${suffix}`;\n current = parent;\n }\n }\n}\n\n/**\n * Resolves a workspace path AND follows any symlinks before checking\n * containment, so a symlink inside the workspace pointing outside is\n * rejected even though the lexical path looks safe. Handles paths that\n * don't yet exist (e.g. write_file targets) by realpath-resolving the\n * nearest existing ancestor and re-attaching the unresolved suffix.\n */\nexport async function resolveWorkspacePathSafe(\n filePath: string,\n config: t.LocalExecutionConfig = {},\n intent: 'read' | 'write' = 'write'\n): Promise<string> {\n const lexical = resolveWorkspacePath(filePath, config, intent);\n const roots =\n intent === 'write' ? getWriteRoots(config) : getReadRoots(config);\n if (roots == null) {\n return lexical;\n }\n // Route realpath through the configured WorkspaceFS so a custom\n // engine (in-memory, remote) gets the same symlink-escape clamp\n // the host-fs path gets. Codex P2 #38: pre-fix the host realpath\n // would fail on a non-default FS path and silently fall back to\n // lexical containment, leaving the clamp ineffective.\n const fsRealpath: RealpathFn = (p) => getWorkspaceFS(config).realpath(p);\n const realRoots = await Promise.all(\n roots.map((r) => realpathOrSelf(r, fsRealpath))\n );\n const realPath = await realpathOfPathOrAncestor(lexical, fsRealpath);\n if (isInsideAnyRoot(realPath, realRoots)) {\n return lexical;\n }\n throw new Error(\n `Path is outside the local workspace (symlink escape): ${filePath}`\n );\n}\n"],"names":[],"mappings":";;;;;;;;;AAYA,MAAM,kBAAkB,GAAG,KAAK;AAChC,MAAM,wBAAwB,GAAG,MAAM;AACvC;;;;;AAKG;AACH,MAAM,yBAAyB,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI;AAClD,MAAM,wBAAwB,GAAG,OAAO;AACxC,MAAM,aAAa,GAAG,OAAO,CAAC,QAAQ,KAAK,OAAO,GAAG,UAAU,GAAG,MAAM;AAExE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,kBAAkB,GAAG,mDAAmD;AAE9E,MAAM,wBAAwB,GAA0B;AACtD,IAAA,IAAI,MAAM,CACR,CAAA,4FAAA,EAA+F,kBAAkB,iBAAiB,CACnI;IACD,2CAA2C;IAC3C,4BAA4B;AAC5B,IAAA,IAAI,MAAM,CACR,CAAA,8CAAA,EAAiD,kBAAkB,iBAAiB,CACrF;AACD,IAAA,IAAI,MAAM,CACR,C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C,KAAK,cAAc,CAAC,CAAC,EAAE,UAAU,CAAC,CAAC,CAChD;IACD,MAAM,QAAQ,GAAG,MAAM,wBAAwB,CAAC,OAAO,EAAE,UAAU,CAAC;AACpE,IAAA,IAAI,eAAe,CAAC,QAAQ,EAAE,SAAS,CAAC,EAAE;AACxC,QAAA,OAAO,OAAO;IAChB;AACA,IAAA,MAAM,IAAI,KAAK,CACb,yDAAyD,QAAQ,CAAA,CAAE,CACpE;AACH;;;;"}
1
+ {"version":3,"file":"LocalExecutionEngine.mjs","sources":["../../../../src/tools/local/LocalExecutionEngine.ts"],"sourcesContent":["import { tmpdir } from 'os';\nimport { isAbsolute, relative, resolve } from 'path';\nimport { createHash, randomUUID } from 'crypto';\nimport { mkdir, realpath, rm, writeFile } from 'fs/promises';\nimport { createWriteStream } from 'fs';\nimport { spawn } from 'child_process';\nimport type { ChildProcess } from 'child_process';\nimport { runBashAstChecks, bashAstFindingsToErrors } from './bashAst';\nimport { nodeWorkspaceFS } from './workspaceFS';\nimport type { WorkspaceFS } from './workspaceFS';\nimport type * as t from '@/types';\n\nconst DEFAULT_TIMEOUT_MS = 60000;\nconst DEFAULT_MAX_OUTPUT_CHARS = 200000;\n/**\n * Hard cap on total stdout+stderr bytes a child process can stream\n * before we kill its process tree. Independent from `maxOutputChars`\n * (which only affects what the *model* sees) — this is the OOM\n * backstop. Configurable via `local.maxSpawnedBytes`.\n */\nconst DEFAULT_MAX_SPAWNED_BYTES = 50 * 1024 * 1024;\nconst DEFAULT_LOCAL_SESSION_ID = 'local';\nconst DEFAULT_SHELL = process.platform === 'win32' ? 'bash.exe' : 'bash';\n\n// `(?:--\\s+)?` before each destructive-target alternation: GNU/BSD\n// utilities accept `--` as an end-of-options marker, so `rm -rf -- /`\n// is identical in effect to `rm -rf /` but pre-fix it slipped past\n// the guard because the regex required the path to follow option\n// flags directly. Codex P1 #20.\n// `DESTRUCTIVE_TARGET` is the canonical \"protected location\" pattern:\n// matches `/`, `~`, `$HOME`, `${HOME}`, `.`, each optionally followed\n// by a trailing-slash and/or wildcard glob suffix. The suffix matrix:\n// '' — `$HOME` (round 14)\n// '/' — `$HOME/` (round 14, Codex P1 [37])\n// '*' — `$HOME*` (round 15, Codex P1 [42])\n// '/*' — `$HOME/*` (round 15, Codex P1 [42])\n// '.*' — `$HOME.*` (round 17, Codex P1 [47])\n// '/.*' — `$HOME/.*` (round 17, Codex P1 [47]) — the\n// dot-glob form deletes all dotfiles under the protected\n// root, just as destructive as `/*` but the prior matrix\n// missed it.\n// Suffix expression: `(?:\\/?\\.?\\*|\\/)?` — one of:\n// `\\/?\\.?\\*` → `*`, `.*`, `/*`, `/.*`\n// `\\/` → `/`\n// (empty) → bare base\nconst DESTRUCTIVE_TARGET = '(?:\\\\/|~|\\\\$\\\\{?HOME\\\\}?|\\\\.)(?:\\\\/?\\\\.?\\\\*|\\\\/)?';\n\nconst dangerousCommandPatterns: ReadonlyArray<RegExp> = [\n new RegExp(\n `\\\\brm\\\\s+(?:-[^\\\\s]*[rf][^\\\\s]*\\\\s+|-[^\\\\s]*[r][^\\\\s]*\\\\s+-[^\\\\s]*[f][^\\\\s]*\\\\s+)(?:--\\\\s+)?${DESTRUCTIVE_TARGET}\\\\s*(?:$|[;&|])`\n ),\n /\\b(?:mkfs|mkswap|fdisk|parted|diskutil)\\b/,\n /\\bdd\\s+[^;&|]*\\bof=\\/dev\\//,\n new RegExp(\n `\\\\bchmod\\\\s+-R\\\\s+(?:777|a\\\\+w)\\\\s+(?:--\\\\s+)?${DESTRUCTIVE_TARGET}(?:$|\\\\s|[;&|])`\n ),\n new RegExp(\n `\\\\bchown\\\\s+-R\\\\s+[^;&|]+\\\\s+(?:--\\\\s+)?${DESTRUCTIVE_TARGET}(?:$|\\\\s|[;&|])`\n ),\n /:\\s*\\(\\s*\\)\\s*\\{\\s*:\\s*\\|\\s*:\\s*&\\s*\\}\\s*;\\s*:/,\n];\n\n/**\n * Companion patterns that look for destructive targets *inside*\n * matching quote pairs. These are checked against the ORIGINAL\n * command (not the post-quote-strip `normalized` form), because\n * `stripQuotedContent` blanks the contents of quoted spans —\n * which would otherwise let `rm -rf \"/\"` and friends slip past\n * `dangerousCommandPatterns`.\n *\n * Kept as a separate list so we don't pay false-positive cost on\n * benign uses like `echo \"rm -rf /\"` (the print case): each pattern\n * here REQUIRES a quote *around the destructive path argument*, not\n * just a quote *somewhere* in the command. `echo \"rm -rf /\"` has\n * `/` outside of any quote-pair-around-the-path (the quotes wrap\n * the whole `rm -rf /` text), so it doesn't match here either.\n */\n// Quoted variant uses the same DESTRUCTIVE_TARGET (which accepts an\n// optional trailing slash) so `rm -rf \"$HOME/\"` and `rm -rf \"~/\"`\n// don't slip past. Codex P1 #37.\nconst quotedDestructivePatterns: ReadonlyArray<RegExp> = [\n new RegExp(\n `\\\\brm\\\\s+(?:-[^\\\\s]*[rf][^\\\\s]*\\\\s+){1,3}(?:--\\\\s+)?[\"']${DESTRUCTIVE_TARGET}[\"']`\n ),\n new RegExp(\n `\\\\bchmod\\\\s+-R\\\\s+(?:777|a\\\\+w)\\\\s+(?:--\\\\s+)?[\"']${DESTRUCTIVE_TARGET}[\"']`\n ),\n new RegExp(\n `\\\\bchown\\\\s+-R\\\\s+[^;&|]+\\\\s+(?:--\\\\s+)?[\"']${DESTRUCTIVE_TARGET}[\"']`\n ),\n];\n\n/**\n * Catches destructive operations smuggled inside a nested shell or\n * `eval` call, e.g. `bash -lc \"rm -rf $HOME\"` — the outer command\n * looks benign (`bash -lc \"...\"`) and the destructive `rm` lives\n * inside the quoted payload that `stripQuotedContent` blanks out.\n * Comprehensive review (manual finding C) flagged this as a real\n * bypass of the otherwise-correct quote-strip-then-match approach.\n *\n * Run against the ORIGINAL command (quotes intact) so the inside of\n * the nested-shell payload is visible. Conservative: matches only\n * the same operation set as `dangerousCommandPatterns` (rm -rf,\n * chmod -R 777, chown -R) when they appear inside a `<shell> -[l]?c\n * \"...\"` or `eval \"...\"` payload.\n */\nconst NESTED_SHELL_PREFIX = '(?:(?:ba|z|da|k)?sh|eval)\\\\s+(?:-l?c\\\\s+)?';\nconst nestedShellDestructivePatterns: ReadonlyArray<RegExp> = [\n new RegExp(\n NESTED_SHELL_PREFIX +\n '[\"\\'][^\"\\']*\\\\brm\\\\s+-[^\\\\s\"\\']*[rf][^\\\\s\"\\']*\\\\s+(?:--\\\\s+)?(?:\\\\/|~|\\\\$\\\\{?HOME\\\\}?|\\\\.)'\n ),\n new RegExp(\n NESTED_SHELL_PREFIX +\n '[\"\\'][^\"\\']*\\\\bchmod\\\\s+-R\\\\s+(?:777|a\\\\+w)\\\\s+(?:--\\\\s+)?(?:\\\\/|~|\\\\$\\\\{?HOME\\\\}?|\\\\.)'\n ),\n new RegExp(\n NESTED_SHELL_PREFIX +\n '[\"\\'][^\"\\']*\\\\bchown\\\\s+-R\\\\s+[^;&|]+\\\\s+(?:--\\\\s+)?(?:\\\\/|~|\\\\$\\\\{?HOME\\\\}?|\\\\.)'\n ),\n];\n\nconst mutatingCommandPattern =\n /\\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*/;\n\ntype SpawnResult = {\n stdout: string;\n stderr: string;\n exitCode: number | null;\n timedOut: boolean;\n /**\n * True when the process was force-killed because total streamed bytes\n * exceeded `maxSpawnedBytes`. Distinct from `timedOut`. Without this\n * flag, callers (`bash_tool`, `execute_code`, etc.) would see a\n * SIGKILL'd process with `exitCode: null` and treat it as success\n * (Codex P1 — runaway commands like `yes` or noisy builds silently\n * looked successful even though their output was truncated).\n */\n overflowKilled?: boolean;\n /**\n * Signal name (e.g. `'SIGKILL'`, `'SIGSEGV'`) when the process was\n * terminated by a signal. Distinct from the overflow-kill path:\n * this captures `kill -9 $$` from inside the script, native crashes,\n * OS OOM killer, etc. Without this, signal-killed processes\n * reported `exitCode: null` and looked like clean runs (Codex P2 —\n * generalization of the overflow-kill fix). When present, the\n * exitCode field is also synthesized to `128 + signum` per the\n * POSIX convention so non-null-exit-code consumers see a failure.\n */\n signal?: string;\n /** Path to the full untruncated stdout/stderr when output exceeded `maxOutputChars`. */\n fullOutputPath?: string;\n};\n\n/**\n * POSIX convention: `128 + signum` when a process is killed by a\n * signal. Maps the common signals; unknown ones default to 1 so the\n * caller still sees a non-zero (failed) exit. Only used when Node's\n * `close` event reports `exitCode === null` (true signal kill).\n */\nconst SIGNAL_TO_EXIT_CODE: Record<string, number> = {\n SIGHUP: 129,\n SIGINT: 130,\n SIGQUIT: 131,\n SIGILL: 132,\n SIGTRAP: 133,\n SIGABRT: 134,\n SIGBUS: 135,\n SIGFPE: 136,\n SIGKILL: 137,\n SIGUSR1: 138,\n SIGSEGV: 139,\n SIGUSR2: 140,\n SIGPIPE: 141,\n SIGALRM: 142,\n SIGTERM: 143,\n};\nfunction exitCodeForSignal(signal: string | null): number {\n if (signal == null) return 1;\n return SIGNAL_TO_EXIT_CODE[signal] ?? 1;\n}\n\ntype RuntimeCommand = {\n command: string;\n args: string[];\n fileName: string;\n source?: string;\n};\n\ntype SandboxManagerType = {\n checkDependencies(): { errors: string[] };\n initialize(config: BuiltSandboxRuntimeConfig): Promise<void>;\n reset(): Promise<void>;\n wrapWithSandbox(command: string): Promise<string>;\n};\n\ntype SandboxRuntimeModule = {\n getDefaultWritePaths(): string[];\n SandboxManager: SandboxManagerType;\n};\n\nlet sandboxConfigKey: string | undefined;\nlet sandboxInitialized = false;\nlet sandboxRuntimePromise: Promise<SandboxRuntimeModule> | undefined;\n\nexport type BashValidationResult = {\n valid: boolean;\n errors: string[];\n warnings: string[];\n};\n\nfunction isToolExecutionConfig(\n config: t.ToolExecutionConfig | t.LocalExecutionConfig\n): config is t.ToolExecutionConfig {\n return 'engine' in config || 'local' in config;\n}\n\nexport function resolveLocalExecutionConfig(\n config?: t.ToolExecutionConfig | t.LocalExecutionConfig\n): t.LocalExecutionConfig {\n if (config != null && isToolExecutionConfig(config)) {\n return config.local ?? {};\n }\n return config ?? {};\n}\n\nexport function getLocalCwd(config?: t.LocalExecutionConfig): string {\n return resolve(config?.workspace?.root ?? config?.cwd ?? process.cwd());\n}\n\n/**\n * Resolves the effective workspace boundary: a list of absolute roots\n * that file operations are allowed to touch. The first entry is always\n * the canonical root (`getLocalCwd`); subsequent entries come from\n * `workspace.additionalRoots` when provided.\n *\n * Returns plain absolute paths — callers symlink-resolve when they\n * need realpath equality (see `resolveWorkspacePathSafe`).\n */\nexport function getWorkspaceRoots(config?: t.LocalExecutionConfig): string[] {\n const root = getLocalCwd(config);\n const extras = config?.workspace?.additionalRoots ?? [];\n if (extras.length === 0) return [root];\n const seen = new Set<string>([root]);\n const out: string[] = [root];\n for (const extra of extras) {\n // Relative `additionalRoots` entries are anchored to the\n // workspace root (so monorepo configs like\n // `additionalRoots: ['../shared']` resolve to a sibling of\n // `root` rather than to `process.cwd()/../shared`, which would\n // mean something completely different on a server with a\n // different cwd).\n const abs = isAbsolute(extra) ? resolve(extra) : resolve(root, extra);\n if (!seen.has(abs)) {\n seen.add(abs);\n out.push(abs);\n }\n }\n return out;\n}\n\n/**\n * Pluggable spawn resolver. Honours `local.exec.spawn` first, falls\n * back to the legacy top-level `local.spawn`, then to Node's\n * `child_process.spawn`. Centralised so engine swapping is one knob.\n */\nexport function getSpawn(config?: t.LocalExecutionConfig): t.LocalSpawn {\n return (config?.exec?.spawn ?? config?.spawn ?? spawn) as t.LocalSpawn;\n}\n\n/**\n * Pluggable filesystem resolver. Honours `local.exec.fs`, falls back\n * to the Node-host implementation. A future remote engine supplies\n * its own implementation here and inherits every file-touching tool.\n */\nexport function getWorkspaceFS(config?: t.LocalExecutionConfig): WorkspaceFS {\n return config?.exec?.fs ?? nodeWorkspaceFS;\n}\n\n/**\n * Resolves the workspace boundary for *write* operations. Honours\n * `workspace.allowWriteOutside` (and the deprecated\n * `allowOutsideWorkspace`) by returning `null`, which the path-safety\n * helpers interpret as \"skip the write clamp\".\n */\nexport function getWriteRoots(\n config: t.LocalExecutionConfig = {}\n): string[] | null {\n // Granular flag wins over the legacy one when explicitly set\n // (true OR false) — otherwise a host tightening access during\n // migration (`allowOutsideWorkspace: true, workspace.\n // allowWriteOutside: false`) would still get the loose behavior\n // because the legacy flag short-circuited the OR. Codex P1 #36.\n const granular = config.workspace?.allowWriteOutside;\n if (granular === true) return null;\n if (granular === false) return getWorkspaceRoots(config);\n if (config.allowOutsideWorkspace === true) return null;\n return getWorkspaceRoots(config);\n}\n\n/**\n * Resolves the workspace boundary for *read* operations. Honours\n * `workspace.allowReadOutside` (and the deprecated\n * `allowOutsideWorkspace`) by returning `null`.\n */\nexport function getReadRoots(\n config: t.LocalExecutionConfig = {}\n): string[] | null {\n // Same precedence as getWriteRoots: granular flag is authoritative\n // when set, legacy flag is the fallback. Codex P1 #36.\n const granular = config.workspace?.allowReadOutside;\n if (granular === true) return null;\n if (granular === false) return getWorkspaceRoots(config);\n if (config.allowOutsideWorkspace === true) return null;\n return getWorkspaceRoots(config);\n}\n\nexport function getLocalSessionId(config?: t.LocalExecutionConfig): string {\n const cwd = getLocalCwd(config);\n const digest = createHash('sha1').update(cwd).digest('hex').slice(0, 12);\n return `${DEFAULT_LOCAL_SESSION_ID}:${digest}`;\n}\n\nconst missingSandboxRuntimeMessage = [\n 'Local sandbox is enabled, but @anthropic-ai/sandbox-runtime is not installed.',\n 'Install it with `npm install @anthropic-ai/sandbox-runtime`, or disable local sandboxing with `local.sandbox.enabled: false`.',\n].join(' ');\nconst sandboxRuntimePackage = '@anthropic-ai/sandbox-runtime';\n\n/** Lazy-loads the ESM-only sandbox runtime only when sandboxing is enabled. */\nfunction loadSandboxRuntime(): Promise<SandboxRuntimeModule> {\n sandboxRuntimePromise ??= import(\n sandboxRuntimePackage\n ) as Promise<SandboxRuntimeModule>;\n return sandboxRuntimePromise;\n}\n\nfunction shouldUseLocalSandbox(config: t.LocalExecutionConfig): boolean {\n return config.sandbox?.enabled === true;\n}\n\nlet sandboxOffWarned = false;\n\nfunction maybeWarnSandboxOff(config: t.LocalExecutionConfig): void {\n if (\n sandboxOffWarned ||\n shouldUseLocalSandbox(config) ||\n config.exec?.sandboxed === true\n ) {\n return;\n }\n sandboxOffWarned = true;\n // eslint-disable-next-line no-console\n console.warn(\n '[@librechat/agents] Local execution engine is running without ' +\n '@anthropic-ai/sandbox-runtime wrapping. The agent has full access to ' +\n 'the host filesystem and network. Set toolExecution.local.sandbox.enabled ' +\n '= true to opt into process sandboxing.'\n );\n}\n\n/**\n * Test-only reset hook for the sandbox-off warning latch.\n *\n * @internal Not part of the public SDK surface.\n */\nexport function _resetLocalEngineWarningsForTests(): void {\n sandboxOffWarned = false;\n}\n\nexport function truncateLocalOutput(\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 stripQuotedContent(command: string): string {\n let output = '';\n let quote: '\"' | '\\'' | '`' | undefined;\n let escaped = false;\n\n for (let i = 0; i < command.length; i++) {\n const char = command[i];\n\n if (escaped) {\n escaped = false;\n output += ' ';\n continue;\n }\n\n if (char === '\\\\') {\n escaped = true;\n output += ' ';\n continue;\n }\n\n if (quote != null) {\n if (char === quote) {\n quote = undefined;\n }\n output += ' ';\n continue;\n }\n\n if (char === '\"' || char === '\\'' || char === '`') {\n quote = char;\n output += ' ';\n continue;\n }\n\n if (char === '#') {\n while (i < command.length && command[i] !== '\\n') {\n output += ' ';\n i++;\n }\n output += '\\n';\n continue;\n }\n\n output += char;\n }\n\n return output;\n}\n\nexport async function validateBashCommand(\n command: string,\n config: t.LocalExecutionConfig = {}\n): Promise<BashValidationResult> {\n const errors: string[] = [];\n const warnings: string[] = [];\n const normalized = stripQuotedContent(command);\n\n if (command.trim() === '') {\n errors.push('Command is empty.');\n }\n\n if (command.includes('\\0')) {\n errors.push('Command contains a NUL byte.');\n }\n\n if (config.allowDangerousCommands !== true) {\n let blocked = false;\n // Strip-then-match for the bare-form patterns (avoids false\n // positives where the destructive text is buried inside a\n // string the user is just printing).\n for (const pattern of dangerousCommandPatterns) {\n if (pattern.test(normalized)) {\n errors.push('Command matches a destructive command pattern.');\n blocked = true;\n break;\n }\n }\n // Original-form pass for patterns that REQUIRE matching quote\n // pairs around a destructive path. Without this, `rm -rf \"/\"`\n // and `chmod -R 777 \"/\"` slip past the strip-then-match pass\n // because their destructive target is inside quotes.\n if (!blocked) {\n for (const pattern of quotedDestructivePatterns) {\n if (pattern.test(command)) {\n errors.push(\n 'Command matches a destructive command pattern (quoted target).'\n );\n blocked = true;\n break;\n }\n }\n }\n if (!blocked) {\n for (const pattern of nestedShellDestructivePatterns) {\n if (pattern.test(command)) {\n errors.push(\n 'Command matches a destructive command pattern (nested shell payload).'\n );\n break;\n }\n }\n }\n }\n\n const bashAstMode = config.bashAst ?? 'off';\n if (bashAstMode !== 'off' && config.allowDangerousCommands !== true) {\n const findings = runBashAstChecks(normalized, bashAstMode);\n const split = bashAstFindingsToErrors(findings);\n errors.push(...split.errors);\n warnings.push(...split.warnings);\n }\n\n if (config.readOnly === true && mutatingCommandPattern.test(normalized)) {\n errors.push(\n 'Command appears to mutate files or repository state in read-only local mode.'\n );\n }\n\n // Use the same shell the actual execution path will use. Hard-coding\n // DEFAULT_SHELL here would reject perfectly valid commands when the\n // host configures `local.shell` to a non-bash binary (or when the\n // runtime doesn't have bash installed at all but does have e.g. zsh).\n const syntaxShell = config.shell ?? DEFAULT_SHELL;\n const syntax = await spawnLocalProcess(\n syntaxShell,\n ['-n', '-c', command],\n {\n ...config,\n timeoutMs: Math.min(config.timeoutMs ?? DEFAULT_TIMEOUT_MS, 5000),\n sandbox: { enabled: false },\n },\n { internal: true }\n ).catch(\n (error: Error): SpawnResult => ({\n stdout: '',\n stderr: error.message,\n exitCode: 1,\n timedOut: false,\n })\n );\n\n if (syntax.exitCode !== 0) {\n errors.push(\n syntax.stderr.trim() === ''\n ? 'Command failed shell syntax validation.'\n : `Command failed shell syntax validation: ${syntax.stderr.trim()}`\n );\n }\n\n if (/\\bsudo\\b/.test(normalized)) {\n warnings.push('Command requests elevated privileges with sudo.');\n }\n\n return {\n valid: errors.length === 0,\n errors,\n warnings,\n };\n}\n\nasync function ensureSandbox(\n config: t.LocalExecutionConfig,\n cwd: string\n): Promise<SandboxManagerType | undefined> {\n if (!shouldUseLocalSandbox(config)) {\n return undefined;\n }\n\n const runtime = await loadSandboxRuntime().catch((error: Error) => {\n throw new Error(`${missingSandboxRuntimeMessage} Cause: ${error.message}`);\n });\n\n const runtimeConfig = buildSandboxRuntimeConfig(\n config,\n cwd,\n runtime.getDefaultWritePaths\n );\n const nextKey = JSON.stringify(runtimeConfig);\n\n if (sandboxInitialized && sandboxConfigKey === nextKey) {\n return runtime.SandboxManager;\n }\n\n const dependencyCheck = runtime.SandboxManager.checkDependencies();\n if (dependencyCheck.errors.length > 0) {\n if (config.sandbox?.failIfUnavailable === true) {\n throw new Error(\n `Local sandbox requested but unavailable: ${dependencyCheck.errors.join('; ')}`\n );\n }\n return undefined;\n }\n\n if (sandboxInitialized) {\n await runtime.SandboxManager.reset();\n }\n\n await runtime.SandboxManager.initialize(runtimeConfig);\n sandboxInitialized = true;\n sandboxConfigKey = nextKey;\n return runtime.SandboxManager;\n}\n\n/**\n * Loopback addresses the in-process programmatic-tool bridge listens\n * on (`LocalProgrammaticToolCalling.ts` binds 127.0.0.1). Sandboxed\n * code launched by `run_tools_with_code` / `run_tools_with_bash` HTTPs\n * back to that address — without the entries below, the bridge is\n * silently blocked under sandbox.\n */\nconst BRIDGE_LOOPBACK_HOSTS = ['127.0.0.1', 'localhost', '::1'] as const;\n\n/**\n * Structural shape of the sandbox-runtime config we hand to\n * `SandboxManager.initialize()`. Intentionally NOT typed as the peer\n * `SandboxRuntimeConfig` from `@anthropic-ai/sandbox-runtime`: that\n * package is an OPTIONAL peer dep, and exporting a function whose\n * return type references it would make our generated `.d.ts` import\n * a module the consumer may not have installed (Codex P1 #22 — type-\n * checking would fail with `Cannot find module\n * '@anthropic-ai/sandbox-runtime'` for any host that doesn't enable\n * local sandboxing). The shape here is a structural subset; assignable\n * to the real `SandboxRuntimeConfig` at the one runtime call site.\n *\n * @internal\n */\nexport interface BuiltSandboxRuntimeConfig {\n network: {\n allowedDomains: string[];\n deniedDomains: string[];\n allowUnixSockets?: string[];\n allowAllUnixSockets?: boolean;\n allowLocalBinding?: boolean;\n allowMachLookup?: string[];\n };\n filesystem: {\n denyRead: string[];\n allowRead?: string[];\n allowWrite: string[];\n denyWrite: string[];\n allowGitConfig?: boolean;\n };\n}\n\nexport function buildSandboxRuntimeConfig(\n config: t.LocalExecutionConfig,\n cwd: string,\n getDefaultWritePaths: () => string[]\n): BuiltSandboxRuntimeConfig {\n const sandbox = config.sandbox;\n // Seed allowedDomains with loopback so the programmatic-tool bridge\n // works under sandbox. If the host explicitly denied a loopback\n // entry via `deniedDomains`, respect that and skip seeding it.\n const userAllowed = sandbox?.network?.allowedDomains ?? [];\n const denied = new Set(sandbox?.network?.deniedDomains ?? []);\n const seededLoopback = BRIDGE_LOOPBACK_HOSTS.filter(\n (host) => !denied.has(host) && !userAllowed.includes(host)\n );\n const allowedDomains = [...seededLoopback, ...userAllowed];\n // Mirror the file-tools workspace boundary: anything in\n // `additionalRoots` counts as in-workspace, so sandboxed shell/code\n // can write there too. Without this, file_tools can resolve a\n // sibling-root path but `bash`/`execute_code` is denied write\n // access — confusing divergence flagged in Codex P2 #15.\n const workspaceWriteRoots =\n config.workspace?.additionalRoots != null\n ? getWorkspaceRoots(config)\n : [cwd];\n return {\n network: {\n allowedDomains,\n deniedDomains: sandbox?.network?.deniedDomains ?? [],\n ...(sandbox?.network?.allowUnixSockets != null && {\n allowUnixSockets: sandbox.network.allowUnixSockets,\n }),\n ...(sandbox?.network?.allowAllUnixSockets != null && {\n allowAllUnixSockets: sandbox.network.allowAllUnixSockets,\n }),\n ...(sandbox?.network?.allowLocalBinding != null && {\n allowLocalBinding: sandbox.network.allowLocalBinding,\n }),\n ...(sandbox?.network?.allowMachLookup != null && {\n allowMachLookup: sandbox.network.allowMachLookup,\n }),\n },\n filesystem: {\n denyRead: sandbox?.filesystem?.denyRead ?? [],\n allowRead: sandbox?.filesystem?.allowRead,\n allowWrite: sandbox?.filesystem?.allowWrite ?? [\n ...workspaceWriteRoots,\n ...getDefaultWritePaths(),\n ],\n denyWrite: sandbox?.filesystem?.denyWrite ?? [\n '.env',\n '.env.*',\n '.git/config',\n '.git/hooks/**',\n ],\n allowGitConfig: sandbox?.filesystem?.allowGitConfig,\n },\n };\n}\n\n/**\n * Internal options for {@link spawnLocalProcess} that we don't want\n * exposed on the public `LocalExecutionConfig` type.\n *\n * @internal\n */\nexport interface SpawnLocalProcessOptions {\n /**\n * When true, suppress the \"sandbox is off\" warning AND its latch\n * for this spawn. Use for SDK-internal probes (`bash -n` syntax\n * preflight, `rg --version`, etc.) that intentionally run with\n * the sandbox forced off — the warning is noise for those, and\n * letting the latch flip would hide the warning when a *real*\n * unsandboxed execution happens later in the same process.\n */\n internal?: boolean;\n}\n\nexport const LOCAL_SPAWN_TIMEOUT_MS = Symbol('librechat.localSpawn.timeoutMs');\n\nexport async function spawnLocalProcess(\n command: string,\n args: string[],\n config: t.LocalExecutionConfig = {},\n options?: SpawnLocalProcessOptions\n): Promise<SpawnResult> {\n const cwd = getLocalCwd(config);\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const maxOutputChars = config.maxOutputChars ?? DEFAULT_MAX_OUTPUT_CHARS;\n // Streaming caps. Local tools execute arbitrary shell/code, so a noisy\n // command (`yes`, `cat /dev/urandom | base64`, a verbose build) could\n // accumulate gigabytes in memory before hitting the post-close cap.\n // We bound in-memory per-stream and spill the rest to disk; we also\n // hard-kill the child once total streamed bytes pass `maxSpawnedBytes`\n // so a process producing unbounded output gets stopped instead of\n // letting the host OOM.\n const inMemoryCapBytes = maxOutputChars * 2;\n const hardKillBytes = config.maxSpawnedBytes ?? DEFAULT_MAX_SPAWNED_BYTES;\n const sandboxManager = await ensureSandbox(config, cwd);\n // Internal probes (validateBashCommand syntax preflight,\n // isRipgrepAvailable, syntax-check probe cache priming) pass\n // `internal: true` so they don't emit a misleading \"sandbox is\n // off\" warning AND don't flip `sandboxOffWarned = true`. Without\n // this Codex P2 path: a run with `sandbox.enabled: true` would\n // see a false warning from the syntax preflight, and the latch\n // flip would suppress the warning in a *later* truly-unsandboxed\n // run — exactly the scenario operators need to see.\n if (sandboxManager == null && options?.internal !== true) {\n maybeWarnSandboxOff(config);\n }\n let spawnCommand = command;\n let spawnArgs = args;\n\n if (sandboxManager != null) {\n const rendered = [command, ...args.map(shellQuote)].join(' ');\n const sandboxed = await sandboxManager.wrapWithSandbox(rendered);\n spawnCommand = config.shell ?? DEFAULT_SHELL;\n spawnArgs = ['-lc', sandboxed];\n }\n\n const launcher = getSpawn(config);\n return new Promise<SpawnResult>((resolveResult, reject) => {\n const spawnOptions: import('child_process').SpawnOptions = {\n cwd,\n detached: process.platform !== 'win32',\n env: { ...process.env, ...(config.env ?? {}) },\n stdio: ['ignore', 'pipe', 'pipe'],\n };\n Object.defineProperty(spawnOptions, LOCAL_SPAWN_TIMEOUT_MS, {\n value: timeoutMs,\n });\n const child = launcher(spawnCommand, spawnArgs, spawnOptions);\n\n let stdout = '';\n let stderr = '';\n let totalSpawnedBytes = 0;\n let overflowKilled = false;\n let spillStream: import('fs').WriteStream | undefined;\n let spillPath: string | undefined;\n let settled = false;\n let timedOut = false;\n let timeout: NodeJS.Timeout | undefined;\n\n const ensureSpill = (): void => {\n if (spillStream != null) return;\n // Lazy-open the temp file the first time a stream's in-memory\n // buffer overflows. Seed it with everything we've buffered so\n // the file holds the FULL output (not just the post-cap tail).\n // Uses the static `createWriteStream` import — `require('fs')`\n // would throw `ReferenceError: require is not defined` in ESM\n // consumers (this package ships both `dist/cjs` and `dist/esm`).\n spillPath = resolve(tmpdir(), `lc-local-output-${randomUUID()}.txt`);\n spillStream = createWriteStream(spillPath);\n spillStream.write('===== stdout =====\\n');\n spillStream.write(stdout);\n spillStream.write('\\n===== stderr =====\\n');\n spillStream.write(stderr);\n spillStream.write('\\n===== overflow stream begins here =====\\n');\n };\n\n const handleChunk = (buf: Buffer, kind: 'stdout' | 'stderr'): void => {\n totalSpawnedBytes += buf.length;\n // hardKillBytes <= 0 means \"no cap\" per the public config contract\n // (see LocalExecutionConfig.maxSpawnedBytes). Skip the kill check\n // entirely in that case so a single byte doesn't terminate the run.\n if (\n hardKillBytes > 0 &&\n totalSpawnedBytes > hardKillBytes &&\n !overflowKilled\n ) {\n overflowKilled = true;\n killProcessTree(child);\n return;\n }\n const current = kind === 'stdout' ? stdout : stderr;\n if (current.length < inMemoryCapBytes) {\n const text = buf.toString('utf8');\n if (kind === 'stdout') stdout += text;\n else stderr += text;\n if (current.length + text.length >= inMemoryCapBytes) {\n ensureSpill();\n }\n } else {\n ensureSpill();\n spillStream!.write(`[${kind}] `);\n spillStream!.write(buf);\n }\n };\n\n const finish = (result: SpawnResult): void => {\n if (settled) {\n return;\n }\n settled = true;\n if (timeout != null) {\n clearTimeout(timeout);\n }\n const finalize = (): void => {\n const truncated = {\n stdout: truncateLocalOutput(result.stdout, maxOutputChars),\n stderr: truncateLocalOutput(result.stderr, maxOutputChars),\n };\n resolveResult({\n ...result,\n ...truncated,\n ...(spillPath != null ? { fullOutputPath: spillPath } : {}),\n });\n };\n if (spillStream == null) {\n finalize();\n return;\n }\n // Wait for the temp file to flush before reporting the path.\n // Otherwise the model sees `full_output_path: …` for a file\n // that's still being written.\n spillStream.end(() => finalize());\n };\n\n const fail = (error: Error): void => {\n if (settled) {\n return;\n }\n settled = true;\n if (timeout != null) {\n clearTimeout(timeout);\n }\n if (spillStream != null) {\n spillStream.end();\n }\n reject(error);\n };\n\n if (timeoutMs > 0) {\n timeout = setTimeout(() => {\n timedOut = true;\n killProcessTree(child);\n }, timeoutMs);\n }\n\n child.stdout.on('data', (chunk: Buffer) => {\n handleChunk(chunk, 'stdout');\n });\n\n child.stderr.on('data', (chunk: Buffer) => {\n handleChunk(chunk, 'stderr');\n });\n\n child.on('error', fail);\n\n child.on('close', (exitCode, signal) => {\n // Synthesize a non-zero exit code whenever the process exited\n // by signal — Node reports `exitCode: null` in that case and\n // the formatter only prints non-null exit codes, so signal\n // kills (overflow guard, `kill -9 $$` from inside the script,\n // native crashes, OS OOM killer, …) would otherwise look like\n // successful runs (Codex P1 + Codex P2). Overflow path keeps\n // its 137 (SIGKILL) for compatibility; other signals map per\n // POSIX `128 + signum`.\n let finalExit: number | null = exitCode;\n if (finalExit == null) {\n if (overflowKilled) {\n finalExit = 137;\n } else if (signal != null) {\n finalExit = exitCodeForSignal(signal);\n }\n }\n finish({\n stdout,\n stderr,\n exitCode: finalExit,\n timedOut,\n ...(overflowKilled ? { overflowKilled: true } : {}),\n ...(signal != null ? { signal } : {}),\n });\n });\n });\n}\n\nexport async function executeLocalBash(\n command: string,\n config: t.LocalExecutionConfig = {}\n): Promise<SpawnResult> {\n const validation = await validateBashCommand(command, config);\n if (!validation.valid) {\n throw new Error(validation.errors.join('\\n'));\n }\n const shell = config.shell ?? DEFAULT_SHELL;\n return spawnLocalProcess(shell, ['-lc', command], config);\n}\n\n/**\n * Variant of `executeLocalBash` that exposes `args` as positional\n * shell parameters (`$1`, `$2`, …). Mirrors what the other runtimes\n * do in `getRuntimeCommand`. Uses the standard `bash -c <code> --\n * arg0 arg1 …` form: the `--` becomes `$0`, then `args[0]` is `$1`\n * and so on. Same AST validation as the no-args path.\n *\n * Used by both the `execute_code`/`lang:'bash'` path AND the\n * `bash_tool` factory so the schema's `args` contract works\n * identically in both surfaces.\n */\n/**\n * Matches a single arg that, on its own, references a protected\n * location (`/`, `~`, `$HOME`, `${HOME}`, `.`, with optional trailing\n * slash, wildcard, or dot-glob suffix). Used to spot the\n * `command: 'rm -rf \"$1\"', args: ['/']` shape where the destructive\n * target is moved into a positional arg to evade the command regex.\n * Codex P1 [45], extended for dot-glob in Codex P1 [47] (mirrors the\n * `DESTRUCTIVE_TARGET` suffix matrix exactly).\n */\nconst PROTECTED_TARGET_ARG_RE = /^(?:\\/|~|\\$\\{?HOME\\}?|\\.)(?:\\/?\\.?\\*|\\/)?$/;\n\n/**\n * Mutating-op recognizer for the args check. Conservative: only the\n * three operations the destructive-command guard already covers\n * directly (`rm -rf …`, `chmod -R …`, `chown -R …`). Other shell\n * builtins might mutate state (`mv`, `cp` over an existing file,\n * etc.) but the destructive guard doesn't try to catch those today,\n * so we don't widen here either.\n */\nconst DESTRUCTIVE_OP_IN_COMMAND_RE =\n /\\b(?:rm\\s+-[^\\s]*[rf]|chmod\\s+-R|chown\\s+-R)\\b/;\n\nexport async function executeLocalBashWithArgs(\n command: string,\n args: readonly string[],\n config: t.LocalExecutionConfig = {}\n): Promise<SpawnResult> {\n const validation = await validateBashCommand(command, config);\n if (!validation.valid) {\n throw new Error(validation.errors.join('\\n'));\n }\n // Per-arg protected-target check (Codex P1 [45]). The command\n // regex can't see `$1`/`$@` substitutions at runtime — `command:\n // 'rm -rf \"$1\"', args: ['/']` would expand to `rm -rf '/'` inside\n // bash but the validator only saw `rm -rf \"$1\"` (no destructive\n // target). Block when (a) the command contains a destructive op\n // AND (b) at least one arg matches the protected-target shape.\n // Skipped when allowDangerousCommands is true (host-opted-in).\n if (\n args.length > 0 &&\n config.allowDangerousCommands !== true &&\n DESTRUCTIVE_OP_IN_COMMAND_RE.test(command)\n ) {\n const offending = args.find((a) => PROTECTED_TARGET_ARG_RE.test(a));\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 const shell = config.shell ?? DEFAULT_SHELL;\n return spawnLocalProcess(shell, ['-lc', command, '--', ...args], config);\n}\n\nexport async function executeLocalCode(\n input: {\n lang: string;\n code: string;\n args?: string[];\n },\n config: t.LocalExecutionConfig = {}\n): Promise<SpawnResult> {\n if (input.lang === 'bash') {\n // Append `args` as positional parameters via the standard\n // `bash -c <code> -- <args...>` form so `$1`, `$2`, … inside\n // `code` resolve correctly. Honours the same args contract the\n // other runtimes (py, js, …) already support.\n if (input.args != null && input.args.length > 0) {\n return executeLocalBashWithArgs(input.code, input.args, config);\n }\n return executeLocalBash(input.code, config);\n }\n\n const tempDir = resolve(tmpdir(), `lc-local-${randomUUID()}`);\n await mkdir(tempDir, { recursive: true });\n\n try {\n const runtime = getRuntimeCommand(\n input.lang,\n tempDir,\n input.code,\n input.args,\n config.shell\n );\n if (runtime.source != null) {\n await writeFile(\n resolve(tempDir, runtime.fileName),\n runtime.source,\n 'utf8'\n );\n }\n return await spawnLocalProcess(runtime.command, runtime.args, config);\n } finally {\n await rm(tempDir, { recursive: true, force: true });\n }\n}\n\nfunction getRuntimeCommand(\n lang: string,\n tempDir: string,\n code: string,\n args: string[] = [],\n // Override for the shell used by compile-style runtimes (`rs`,\n // `c`, `cpp`, `java`, `d`, `f90`). Threads `local.shell` so a host\n // that doesn't have bash (or wants `/bin/sh` / zsh) can still\n // execute these languages — Codex P2 #29: the bare-bash hardcode\n // mirrored the same gap that Codex P1 #6 fixed for the syntax\n // preflight, but had been missed for these runtime invocations.\n shellOverride?: string\n): RuntimeCommand {\n const fileFor = (name: string): string => resolve(tempDir, name);\n const shell = shellOverride ?? configShell();\n\n switch (lang) {\n case 'py':\n return {\n command: 'python3',\n args: [fileFor('main.py'), ...args],\n fileName: 'main.py',\n source: code,\n };\n case 'js':\n return {\n command: 'node',\n args: [fileFor('main.js'), ...args],\n fileName: 'main.js',\n source: code,\n };\n case 'ts':\n return {\n command: 'npx',\n args: ['--no-install', 'tsx', fileFor('main.ts'), ...args],\n fileName: 'main.ts',\n source: code,\n };\n case 'php':\n return {\n command: 'php',\n args: [fileFor('main.php'), ...args],\n fileName: 'main.php',\n source: code,\n };\n case 'go':\n return {\n command: 'go',\n args: ['run', fileFor('main.go'), ...args],\n fileName: 'main.go',\n source: code,\n };\n case 'rs':\n return {\n command: shell,\n args: [\n '-lc',\n `rustc ${shellQuote(fileFor('main.rs'))} -o ${shellQuote(\n fileFor('main-rs')\n )} && ${shellQuote(fileFor('main-rs'))} ${args.map(shellQuote).join(' ')}`,\n ],\n fileName: 'main.rs',\n source: code,\n };\n case 'c':\n return {\n command: shell,\n args: [\n '-lc',\n `cc ${shellQuote(fileFor('main.c'))} -o ${shellQuote(\n fileFor('main-c')\n )} && ${shellQuote(fileFor('main-c'))} ${args.map(shellQuote).join(' ')}`,\n ],\n fileName: 'main.c',\n source: code,\n };\n case 'cpp':\n return {\n command: shell,\n args: [\n '-lc',\n `c++ ${shellQuote(fileFor('main.cpp'))} -o ${shellQuote(\n fileFor('main-cpp')\n )} && ${shellQuote(fileFor('main-cpp'))} ${args.map(shellQuote).join(' ')}`,\n ],\n fileName: 'main.cpp',\n source: code,\n };\n case 'java':\n return {\n command: shell,\n args: [\n '-lc',\n `javac ${shellQuote(fileFor('Main.java'))} && java -cp ${shellQuote(\n tempDir\n )} Main ${args.map(shellQuote).join(' ')}`,\n ],\n fileName: 'Main.java',\n source: code,\n };\n case 'r':\n return {\n command: 'Rscript',\n args: [fileFor('main.R'), ...args],\n fileName: 'main.R',\n source: code,\n };\n case 'd':\n return {\n command: shell,\n args: [\n '-lc',\n `dmd ${shellQuote(fileFor('main.d'))} -of=${shellQuote(\n fileFor('main-d')\n )} && ${shellQuote(fileFor('main-d'))} ${args.map(shellQuote).join(' ')}`,\n ],\n fileName: 'main.d',\n source: code,\n };\n case 'f90':\n return {\n command: shell,\n args: [\n '-lc',\n `gfortran ${shellQuote(fileFor('main.f90'))} -o ${shellQuote(\n fileFor('main-f90')\n )} && ${shellQuote(fileFor('main-f90'))} ${args.map(shellQuote).join(' ')}`,\n ],\n fileName: 'main.f90',\n source: code,\n };\n default:\n throw new Error(`Unsupported local runtime: ${lang}`);\n }\n}\n\nfunction configShell(): string {\n return process.platform === 'win32' ? 'bash.exe' : 'bash';\n}\n\n/**\n * How long after SIGTERM we wait before escalating to SIGKILL. A\n * cooperative process gets a graceful chance to flush + clean up;\n * a process that ignores or traps SIGTERM (`trap '' TERM`) gets\n * killed unconditionally so timeoutMs / maxSpawnedBytes can't be\n * defeated by a hostile script. Codex P1 #28 — pre-fix the spawn\n * promise would never resolve in that case and the entire tool run\n * would hang past the advertised timeout.\n */\nconst SIGKILL_ESCALATION_MS = 2000;\n\nfunction sigterm(child: ChildProcess): void {\n if (child.pid == null) {\n child.kill('SIGTERM');\n return;\n }\n try {\n if (process.platform === 'win32') {\n child.kill('SIGTERM');\n return;\n }\n process.kill(-child.pid, 'SIGTERM');\n } catch {\n child.kill('SIGTERM');\n }\n}\n\nfunction sigkill(child: ChildProcess): void {\n if (child.exitCode != null || child.signalCode != null) return;\n if (child.pid == null) {\n child.kill('SIGKILL');\n return;\n }\n try {\n if (process.platform === 'win32') {\n child.kill('SIGKILL');\n return;\n }\n process.kill(-child.pid, 'SIGKILL');\n } catch {\n try {\n child.kill('SIGKILL');\n } catch {\n /* already dead */\n }\n }\n}\n\nfunction killProcessTree(child: ChildProcess): void {\n sigterm(child);\n // Escalate to SIGKILL if the child is still alive after the grace\n // window. Use unref() so the timer doesn't keep the Node process\n // alive past the parent's natural exit.\n const escalation = setTimeout(() => sigkill(child), SIGKILL_ESCALATION_MS);\n escalation.unref();\n child.once('close', () => clearTimeout(escalation));\n}\n\nexport function shellQuote(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\nexport function resolveWorkspacePath(\n filePath: string,\n config: t.LocalExecutionConfig = {},\n intent: 'read' | 'write' = 'write'\n): string {\n const cwd = getLocalCwd(config);\n const absolutePath = isAbsolute(filePath)\n ? resolve(filePath)\n : resolve(cwd, filePath);\n\n const roots =\n intent === 'write' ? getWriteRoots(config) : getReadRoots(config);\n if (roots == null) return absolutePath; // explicit allow-outside\n\n if (absolutePath === cwd || isInsideAnyRoot(absolutePath, roots)) {\n return absolutePath;\n }\n throw new Error(`Path is outside the local workspace: ${filePath}`);\n}\n\nfunction isInsideAnyRoot(absolutePath: string, roots: string[]): boolean {\n for (const root of roots) {\n if (absolutePath === root) return true;\n const rel = relative(root, absolutePath);\n if (!rel.startsWith('..') && !isAbsolute(rel)) return true;\n }\n return false;\n}\n\ntype RealpathFn = (p: string) => Promise<string>;\n\nasync function realpathOrSelf(\n absolutePath: string,\n realpathImpl: RealpathFn = realpath\n): Promise<string> {\n try {\n return await realpathImpl(absolutePath);\n } catch {\n return absolutePath;\n }\n}\n\n/**\n * Resolves the realpath of `absolutePath`, falling back to the nearest\n * existing ancestor when the target itself does not yet exist (so the\n * containment check still works for `write_file` to a brand-new path).\n *\n * Codex P2 #38: takes the realpath impl as a parameter so callers\n * can route through `WorkspaceFS.realpath` when a custom engine is\n * configured. Pre-fix, host `fs/promises.realpath` would fail on a\n * remote/in-memory FS path and silently fall back to lexical\n * containment, leaving the symlink-escape clamp ineffective on\n * non-default engines.\n */\nasync function realpathOfPathOrAncestor(\n absolutePath: string,\n realpathImpl: RealpathFn = realpath\n): Promise<string> {\n let current = absolutePath;\n let suffix = '';\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n while (true) {\n try {\n const real = await realpathImpl(current);\n return suffix === '' ? real : resolve(real, suffix);\n } catch {\n const parent = resolve(current, '..');\n if (parent === current) {\n return absolutePath;\n }\n const base = current.slice(parent.length + 1);\n suffix = suffix === '' ? base : `${base}/${suffix}`;\n current = parent;\n }\n }\n}\n\n/**\n * Resolves a workspace path AND follows any symlinks before checking\n * containment, so a symlink inside the workspace pointing outside is\n * rejected even though the lexical path looks safe. Handles paths that\n * don't yet exist (e.g. write_file targets) by realpath-resolving the\n * nearest existing ancestor and re-attaching the unresolved suffix.\n */\nexport async function resolveWorkspacePathSafe(\n filePath: string,\n config: t.LocalExecutionConfig = {},\n intent: 'read' | 'write' = 'write'\n): Promise<string> {\n const lexical = resolveWorkspacePath(filePath, config, intent);\n const roots =\n intent === 'write' ? getWriteRoots(config) : getReadRoots(config);\n if (roots == null) {\n return lexical;\n }\n // Route realpath through the configured WorkspaceFS so a custom\n // engine (in-memory, remote) gets the same symlink-escape clamp\n // the host-fs path gets. Codex P2 #38: pre-fix the host realpath\n // would fail on a non-default FS path and silently fall back to\n // lexical containment, leaving the clamp ineffective.\n const fsRealpath: RealpathFn = (p) => getWorkspaceFS(config).realpath(p);\n const realRoots = await Promise.all(\n roots.map((r) => realpathOrSelf(r, fsRealpath))\n );\n const realPath = await realpathOfPathOrAncestor(lexical, fsRealpath);\n if (isInsideAnyRoot(realPath, realRoots)) {\n return lexical;\n }\n throw new Error(\n `Path is outside the local workspace (symlink escape): ${filePath}`\n );\n}\n"],"names":[],"mappings":";;;;;;;;;AAYA,MAAM,kBAAkB,GAAG,KAAK;AAChC,MAAM,wBAAwB,GAAG,MAAM;AACvC;;;;;AAKG;AACH,MAAM,yBAAyB,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI;AAClD,MAAM,wBAAwB,GAAG,OAAO;AACxC,MAAM,aAAa,GAAG,OAAO,CAAC,QAAQ,KAAK,OAAO,GAAG,UAAU,GAAG,MAAM;AAExE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,kBAAkB,GAAG,mDAAmD;AAE9E,MAAM,wBAAwB,GAA0B;AACtD,IAAA,IAAI,MAAM,CACR,CAAA,4FAAA,EAA+F,kBAAkB,iBAAiB,CACnI;IACD,2CAA2C;IAC3C,4BAA4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