@librechat/agents 3.1.77 → 3.1.78-dev.0

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 (181) hide show
  1. package/dist/cjs/common/enum.cjs +54 -0
  2. package/dist/cjs/common/enum.cjs.map +1 -1
  3. package/dist/cjs/graphs/Graph.cjs +148 -4
  4. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  5. package/dist/cjs/hooks/createWorkspacePolicyHook.cjs +291 -0
  6. package/dist/cjs/hooks/createWorkspacePolicyHook.cjs.map +1 -0
  7. package/dist/cjs/main.cjs +90 -0
  8. package/dist/cjs/main.cjs.map +1 -1
  9. package/dist/cjs/messages/anthropicToolCache.cjs +102 -0
  10. package/dist/cjs/messages/anthropicToolCache.cjs.map +1 -0
  11. package/dist/cjs/messages/prune.cjs +27 -0
  12. package/dist/cjs/messages/prune.cjs.map +1 -1
  13. package/dist/cjs/messages/recency.cjs +99 -0
  14. package/dist/cjs/messages/recency.cjs.map +1 -0
  15. package/dist/cjs/run.cjs +30 -0
  16. package/dist/cjs/run.cjs.map +1 -1
  17. package/dist/cjs/summarization/node.cjs +100 -6
  18. package/dist/cjs/summarization/node.cjs.map +1 -1
  19. package/dist/cjs/tools/ToolNode.cjs +635 -23
  20. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  21. package/dist/cjs/tools/local/CompileCheckTool.cjs +227 -0
  22. package/dist/cjs/tools/local/CompileCheckTool.cjs.map +1 -0
  23. package/dist/cjs/tools/local/FileCheckpointer.cjs +90 -0
  24. package/dist/cjs/tools/local/FileCheckpointer.cjs.map +1 -0
  25. package/dist/cjs/tools/local/LocalCodingTools.cjs +1098 -0
  26. package/dist/cjs/tools/local/LocalCodingTools.cjs.map +1 -0
  27. package/dist/cjs/tools/local/LocalExecutionEngine.cjs +1042 -0
  28. package/dist/cjs/tools/local/LocalExecutionEngine.cjs.map +1 -0
  29. package/dist/cjs/tools/local/LocalExecutionTools.cjs +122 -0
  30. package/dist/cjs/tools/local/LocalExecutionTools.cjs.map +1 -0
  31. package/dist/cjs/tools/local/LocalProgrammaticToolCalling.cjs +453 -0
  32. package/dist/cjs/tools/local/LocalProgrammaticToolCalling.cjs.map +1 -0
  33. package/dist/cjs/tools/local/attachments.cjs +183 -0
  34. package/dist/cjs/tools/local/attachments.cjs.map +1 -0
  35. package/dist/cjs/tools/local/bashAst.cjs +129 -0
  36. package/dist/cjs/tools/local/bashAst.cjs.map +1 -0
  37. package/dist/cjs/tools/local/editStrategies.cjs +188 -0
  38. package/dist/cjs/tools/local/editStrategies.cjs.map +1 -0
  39. package/dist/cjs/tools/local/resolveLocalExecutionTools.cjs +141 -0
  40. package/dist/cjs/tools/local/resolveLocalExecutionTools.cjs.map +1 -0
  41. package/dist/cjs/tools/local/syntaxCheck.cjs +182 -0
  42. package/dist/cjs/tools/local/syntaxCheck.cjs.map +1 -0
  43. package/dist/cjs/tools/local/textEncoding.cjs +30 -0
  44. package/dist/cjs/tools/local/textEncoding.cjs.map +1 -0
  45. package/dist/cjs/tools/local/workspaceFS.cjs +51 -0
  46. package/dist/cjs/tools/local/workspaceFS.cjs.map +1 -0
  47. package/dist/cjs/tools/subagent/SubagentExecutor.cjs +1 -0
  48. package/dist/cjs/tools/subagent/SubagentExecutor.cjs.map +1 -1
  49. package/dist/esm/common/enum.mjs +53 -1
  50. package/dist/esm/common/enum.mjs.map +1 -1
  51. package/dist/esm/graphs/Graph.mjs +149 -5
  52. package/dist/esm/graphs/Graph.mjs.map +1 -1
  53. package/dist/esm/hooks/createWorkspacePolicyHook.mjs +289 -0
  54. package/dist/esm/hooks/createWorkspacePolicyHook.mjs.map +1 -0
  55. package/dist/esm/main.mjs +17 -2
  56. package/dist/esm/main.mjs.map +1 -1
  57. package/dist/esm/messages/anthropicToolCache.mjs +99 -0
  58. package/dist/esm/messages/anthropicToolCache.mjs.map +1 -0
  59. package/dist/esm/messages/prune.mjs +26 -1
  60. package/dist/esm/messages/prune.mjs.map +1 -1
  61. package/dist/esm/messages/recency.mjs +97 -0
  62. package/dist/esm/messages/recency.mjs.map +1 -0
  63. package/dist/esm/run.mjs +30 -0
  64. package/dist/esm/run.mjs.map +1 -1
  65. package/dist/esm/summarization/node.mjs +100 -6
  66. package/dist/esm/summarization/node.mjs.map +1 -1
  67. package/dist/esm/tools/ToolNode.mjs +635 -23
  68. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  69. package/dist/esm/tools/local/CompileCheckTool.mjs +223 -0
  70. package/dist/esm/tools/local/CompileCheckTool.mjs.map +1 -0
  71. package/dist/esm/tools/local/FileCheckpointer.mjs +87 -0
  72. package/dist/esm/tools/local/FileCheckpointer.mjs.map +1 -0
  73. package/dist/esm/tools/local/LocalCodingTools.mjs +1075 -0
  74. package/dist/esm/tools/local/LocalCodingTools.mjs.map +1 -0
  75. package/dist/esm/tools/local/LocalExecutionEngine.mjs +1022 -0
  76. package/dist/esm/tools/local/LocalExecutionEngine.mjs.map +1 -0
  77. package/dist/esm/tools/local/LocalExecutionTools.mjs +117 -0
  78. package/dist/esm/tools/local/LocalExecutionTools.mjs.map +1 -0
  79. package/dist/esm/tools/local/LocalProgrammaticToolCalling.mjs +448 -0
  80. package/dist/esm/tools/local/LocalProgrammaticToolCalling.mjs.map +1 -0
  81. package/dist/esm/tools/local/attachments.mjs +180 -0
  82. package/dist/esm/tools/local/attachments.mjs.map +1 -0
  83. package/dist/esm/tools/local/bashAst.mjs +126 -0
  84. package/dist/esm/tools/local/bashAst.mjs.map +1 -0
  85. package/dist/esm/tools/local/editStrategies.mjs +185 -0
  86. package/dist/esm/tools/local/editStrategies.mjs.map +1 -0
  87. package/dist/esm/tools/local/resolveLocalExecutionTools.mjs +137 -0
  88. package/dist/esm/tools/local/resolveLocalExecutionTools.mjs.map +1 -0
  89. package/dist/esm/tools/local/syntaxCheck.mjs +179 -0
  90. package/dist/esm/tools/local/syntaxCheck.mjs.map +1 -0
  91. package/dist/esm/tools/local/textEncoding.mjs +27 -0
  92. package/dist/esm/tools/local/textEncoding.mjs.map +1 -0
  93. package/dist/esm/tools/local/workspaceFS.mjs +49 -0
  94. package/dist/esm/tools/local/workspaceFS.mjs.map +1 -0
  95. package/dist/esm/tools/subagent/SubagentExecutor.mjs +1 -0
  96. package/dist/esm/tools/subagent/SubagentExecutor.mjs.map +1 -1
  97. package/dist/types/common/enum.d.ts +39 -1
  98. package/dist/types/graphs/Graph.d.ts +34 -0
  99. package/dist/types/hooks/createWorkspacePolicyHook.d.ts +95 -0
  100. package/dist/types/hooks/index.d.ts +2 -0
  101. package/dist/types/index.d.ts +1 -0
  102. package/dist/types/messages/anthropicToolCache.d.ts +51 -0
  103. package/dist/types/messages/index.d.ts +2 -0
  104. package/dist/types/messages/prune.d.ts +11 -0
  105. package/dist/types/messages/recency.d.ts +64 -0
  106. package/dist/types/run.d.ts +21 -0
  107. package/dist/types/tools/ToolNode.d.ts +145 -2
  108. package/dist/types/tools/local/CompileCheckTool.d.ts +31 -0
  109. package/dist/types/tools/local/FileCheckpointer.d.ts +39 -0
  110. package/dist/types/tools/local/LocalCodingTools.d.ts +57 -0
  111. package/dist/types/tools/local/LocalExecutionEngine.d.ts +149 -0
  112. package/dist/types/tools/local/LocalExecutionTools.d.ts +9 -0
  113. package/dist/types/tools/local/LocalProgrammaticToolCalling.d.ts +21 -0
  114. package/dist/types/tools/local/attachments.d.ts +84 -0
  115. package/dist/types/tools/local/bashAst.d.ts +11 -0
  116. package/dist/types/tools/local/editStrategies.d.ts +28 -0
  117. package/dist/types/tools/local/index.d.ts +12 -0
  118. package/dist/types/tools/local/resolveLocalExecutionTools.d.ts +38 -0
  119. package/dist/types/tools/local/syntaxCheck.d.ts +42 -0
  120. package/dist/types/tools/local/textEncoding.d.ts +21 -0
  121. package/dist/types/tools/local/workspaceFS.d.ts +49 -0
  122. package/dist/types/types/hitl.d.ts +56 -27
  123. package/dist/types/types/run.d.ts +8 -1
  124. package/dist/types/types/summarize.d.ts +30 -0
  125. package/dist/types/types/tools.d.ts +341 -6
  126. package/package.json +21 -2
  127. package/src/common/enum.ts +54 -0
  128. package/src/graphs/Graph.ts +164 -6
  129. package/src/hooks/__tests__/compactHooks.test.ts +38 -2
  130. package/src/hooks/__tests__/createWorkspacePolicyHook.test.ts +393 -0
  131. package/src/hooks/createWorkspacePolicyHook.ts +355 -0
  132. package/src/hooks/index.ts +6 -0
  133. package/src/index.ts +1 -0
  134. package/src/messages/__tests__/anthropicToolCache.test.ts +125 -0
  135. package/src/messages/__tests__/recency.test.ts +267 -0
  136. package/src/messages/anthropicToolCache.ts +116 -0
  137. package/src/messages/index.ts +2 -0
  138. package/src/messages/prune.ts +27 -1
  139. package/src/messages/recency.ts +155 -0
  140. package/src/run.ts +31 -0
  141. package/src/scripts/compare_pi_vs_ours.ts +840 -0
  142. package/src/scripts/local_engine.ts +166 -0
  143. package/src/scripts/local_engine_checkpointer.ts +205 -0
  144. package/src/scripts/local_engine_compile.ts +263 -0
  145. package/src/scripts/local_engine_hooks.ts +226 -0
  146. package/src/scripts/local_engine_image.ts +201 -0
  147. package/src/scripts/local_engine_ptc.ts +151 -0
  148. package/src/scripts/local_engine_workspace.ts +258 -0
  149. package/src/scripts/summarization-recency.ts +462 -0
  150. package/src/specs/prune.test.ts +39 -0
  151. package/src/summarization/__tests__/node.test.ts +499 -3
  152. package/src/summarization/node.ts +124 -7
  153. package/src/tools/ToolNode.ts +769 -20
  154. package/src/tools/__tests__/LocalExecutionTools.test.ts +2647 -0
  155. package/src/tools/__tests__/ProgrammaticToolCalling.test.ts +175 -0
  156. package/src/tools/__tests__/ToolNode.outputReferences.test.ts +114 -0
  157. package/src/tools/__tests__/ToolNode.session.test.ts +84 -0
  158. package/src/tools/__tests__/directToolHITLResumeScope.test.ts +467 -0
  159. package/src/tools/__tests__/directToolHooks.test.ts +411 -0
  160. package/src/tools/__tests__/localToolNames.test.ts +73 -0
  161. package/src/tools/__tests__/workspaceSeam.test.ts +134 -0
  162. package/src/tools/local/CompileCheckTool.ts +278 -0
  163. package/src/tools/local/FileCheckpointer.ts +93 -0
  164. package/src/tools/local/LocalCodingTools.ts +1342 -0
  165. package/src/tools/local/LocalExecutionEngine.ts +1329 -0
  166. package/src/tools/local/LocalExecutionTools.ts +167 -0
  167. package/src/tools/local/LocalProgrammaticToolCalling.ts +594 -0
  168. package/src/tools/local/__tests__/FileCheckpointer.test.ts +120 -0
  169. package/src/tools/local/__tests__/editStrategies.test.ts +134 -0
  170. package/src/tools/local/attachments.ts +251 -0
  171. package/src/tools/local/bashAst.ts +151 -0
  172. package/src/tools/local/editStrategies.ts +188 -0
  173. package/src/tools/local/index.ts +12 -0
  174. package/src/tools/local/resolveLocalExecutionTools.ts +208 -0
  175. package/src/tools/local/syntaxCheck.ts +243 -0
  176. package/src/tools/local/textEncoding.ts +37 -0
  177. package/src/tools/local/workspaceFS.ts +89 -0
  178. package/src/types/hitl.ts +56 -27
  179. package/src/types/run.ts +12 -1
  180. package/src/types/summarize.ts +31 -0
  181. package/src/types/tools.ts +359 -7
@@ -0,0 +1,1042 @@
1
+ 'use strict';
2
+
3
+ var os = require('os');
4
+ var path = require('path');
5
+ var crypto = require('crypto');
6
+ var promises = require('fs/promises');
7
+ var fs = require('fs');
8
+ var child_process = require('child_process');
9
+ var bashAst = require('./bashAst.cjs');
10
+ var workspaceFS = require('./workspaceFS.cjs');
11
+
12
+ const DEFAULT_TIMEOUT_MS = 60000;
13
+ const DEFAULT_MAX_OUTPUT_CHARS = 200000;
14
+ /**
15
+ * Hard cap on total stdout+stderr bytes a child process can stream
16
+ * before we kill its process tree. Independent from `maxOutputChars`
17
+ * (which only affects what the *model* sees) — this is the OOM
18
+ * backstop. Configurable via `local.maxSpawnedBytes`.
19
+ */
20
+ const DEFAULT_MAX_SPAWNED_BYTES = 50 * 1024 * 1024;
21
+ const DEFAULT_LOCAL_SESSION_ID = 'local';
22
+ const DEFAULT_SHELL = process.platform === 'win32' ? 'bash.exe' : 'bash';
23
+ // `(?:--\s+)?` before each destructive-target alternation: GNU/BSD
24
+ // utilities accept `--` as an end-of-options marker, so `rm -rf -- /`
25
+ // is identical in effect to `rm -rf /` but pre-fix it slipped past
26
+ // the guard because the regex required the path to follow option
27
+ // flags directly. Codex P1 #20.
28
+ // `DESTRUCTIVE_TARGET` is the canonical "protected location" pattern:
29
+ // matches `/`, `~`, `$HOME`, `${HOME}`, `.`, each optionally followed
30
+ // by a trailing-slash and/or wildcard glob suffix. The suffix matrix:
31
+ // '' — `$HOME` (round 14)
32
+ // '/' — `$HOME/` (round 14, Codex P1 [37])
33
+ // '*' — `$HOME*` (round 15, Codex P1 [42])
34
+ // '/*' — `$HOME/*` (round 15, Codex P1 [42])
35
+ // '.*' — `$HOME.*` (round 17, Codex P1 [47])
36
+ // '/.*' — `$HOME/.*` (round 17, Codex P1 [47]) — the
37
+ // dot-glob form deletes all dotfiles under the protected
38
+ // root, just as destructive as `/*` but the prior matrix
39
+ // missed it.
40
+ // Suffix expression: `(?:\/?\.?\*|\/)?` — one of:
41
+ // `\/?\.?\*` → `*`, `.*`, `/*`, `/.*`
42
+ // `\/` → `/`
43
+ // (empty) → bare base
44
+ const DESTRUCTIVE_TARGET = '(?:\\/|~|\\$\\{?HOME\\}?|\\.)(?:\\/?\\.?\\*|\\/)?';
45
+ const dangerousCommandPatterns = [
46
+ new RegExp(`\\brm\\s+(?:-[^\\s]*[rf][^\\s]*\\s+|-[^\\s]*[r][^\\s]*\\s+-[^\\s]*[f][^\\s]*\\s+)(?:--\\s+)?${DESTRUCTIVE_TARGET}\\s*(?:$|[;&|])`),
47
+ /\b(?:mkfs|mkswap|fdisk|parted|diskutil)\b/,
48
+ /\bdd\s+[^;&|]*\bof=\/dev\//,
49
+ new RegExp(`\\bchmod\\s+-R\\s+(?:777|a\\+w)\\s+(?:--\\s+)?${DESTRUCTIVE_TARGET}(?:$|\\s|[;&|])`),
50
+ new RegExp(`\\bchown\\s+-R\\s+[^;&|]+\\s+(?:--\\s+)?${DESTRUCTIVE_TARGET}(?:$|\\s|[;&|])`),
51
+ /:\s*\(\s*\)\s*\{\s*:\s*\|\s*:\s*&\s*\}\s*;\s*:/,
52
+ ];
53
+ /**
54
+ * Companion patterns that look for destructive targets *inside*
55
+ * matching quote pairs. These are checked against the ORIGINAL
56
+ * command (not the post-quote-strip `normalized` form), because
57
+ * `stripQuotedContent` blanks the contents of quoted spans —
58
+ * which would otherwise let `rm -rf "/"` and friends slip past
59
+ * `dangerousCommandPatterns`.
60
+ *
61
+ * Kept as a separate list so we don't pay false-positive cost on
62
+ * benign uses like `echo "rm -rf /"` (the print case): each pattern
63
+ * here REQUIRES a quote *around the destructive path argument*, not
64
+ * just a quote *somewhere* in the command. `echo "rm -rf /"` has
65
+ * `/` outside of any quote-pair-around-the-path (the quotes wrap
66
+ * the whole `rm -rf /` text), so it doesn't match here either.
67
+ */
68
+ // Quoted variant uses the same DESTRUCTIVE_TARGET (which accepts an
69
+ // optional trailing slash) so `rm -rf "$HOME/"` and `rm -rf "~/"`
70
+ // don't slip past. Codex P1 #37.
71
+ const quotedDestructivePatterns = [
72
+ new RegExp(`\\brm\\s+(?:-[^\\s]*[rf][^\\s]*\\s+){1,3}(?:--\\s+)?["']${DESTRUCTIVE_TARGET}["']`),
73
+ new RegExp(`\\bchmod\\s+-R\\s+(?:777|a\\+w)\\s+(?:--\\s+)?["']${DESTRUCTIVE_TARGET}["']`),
74
+ new RegExp(`\\bchown\\s+-R\\s+[^;&|]+\\s+(?:--\\s+)?["']${DESTRUCTIVE_TARGET}["']`),
75
+ ];
76
+ /**
77
+ * Catches destructive operations smuggled inside a nested shell or
78
+ * `eval` call, e.g. `bash -lc "rm -rf $HOME"` — the outer command
79
+ * looks benign (`bash -lc "..."`) and the destructive `rm` lives
80
+ * inside the quoted payload that `stripQuotedContent` blanks out.
81
+ * Comprehensive review (manual finding C) flagged this as a real
82
+ * bypass of the otherwise-correct quote-strip-then-match approach.
83
+ *
84
+ * Run against the ORIGINAL command (quotes intact) so the inside of
85
+ * the nested-shell payload is visible. Conservative: matches only
86
+ * the same operation set as `dangerousCommandPatterns` (rm -rf,
87
+ * chmod -R 777, chown -R) when they appear inside a `<shell> -[l]?c
88
+ * "..."` or `eval "..."` payload.
89
+ */
90
+ const NESTED_SHELL_PREFIX = '(?:(?:ba|z|da|k)?sh|eval)\\s+(?:-l?c\\s+)?';
91
+ const nestedShellDestructivePatterns = [
92
+ new RegExp(NESTED_SHELL_PREFIX +
93
+ '["\'][^"\']*\\brm\\s+-[^\\s"\']*[rf][^\\s"\']*\\s+(?:--\\s+)?(?:\\/|~|\\$\\{?HOME\\}?|\\.)'),
94
+ new RegExp(NESTED_SHELL_PREFIX +
95
+ '["\'][^"\']*\\bchmod\\s+-R\\s+(?:777|a\\+w)\\s+(?:--\\s+)?(?:\\/|~|\\$\\{?HOME\\}?|\\.)'),
96
+ new RegExp(NESTED_SHELL_PREFIX +
97
+ '["\'][^"\']*\\bchown\\s+-R\\s+[^;&|]+\\s+(?:--\\s+)?(?:\\/|~|\\$\\{?HOME\\}?|\\.)'),
98
+ ];
99
+ const mutatingCommandPattern = /\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*/;
100
+ /**
101
+ * POSIX convention: `128 + signum` when a process is killed by a
102
+ * signal. Maps the common signals; unknown ones default to 1 so the
103
+ * caller still sees a non-zero (failed) exit. Only used when Node's
104
+ * `close` event reports `exitCode === null` (true signal kill).
105
+ */
106
+ const SIGNAL_TO_EXIT_CODE = {
107
+ SIGHUP: 129,
108
+ SIGINT: 130,
109
+ SIGQUIT: 131,
110
+ SIGILL: 132,
111
+ SIGTRAP: 133,
112
+ SIGABRT: 134,
113
+ SIGBUS: 135,
114
+ SIGFPE: 136,
115
+ SIGKILL: 137,
116
+ SIGUSR1: 138,
117
+ SIGSEGV: 139,
118
+ SIGUSR2: 140,
119
+ SIGPIPE: 141,
120
+ SIGALRM: 142,
121
+ SIGTERM: 143,
122
+ };
123
+ function exitCodeForSignal(signal) {
124
+ if (signal == null)
125
+ return 1;
126
+ return SIGNAL_TO_EXIT_CODE[signal] ?? 1;
127
+ }
128
+ let sandboxConfigKey;
129
+ let sandboxInitialized = false;
130
+ let sandboxRuntimePromise;
131
+ function isToolExecutionConfig(config) {
132
+ return 'engine' in config || 'local' in config;
133
+ }
134
+ function resolveLocalExecutionConfig(config) {
135
+ if (config != null && isToolExecutionConfig(config)) {
136
+ return config.local ?? {};
137
+ }
138
+ return config ?? {};
139
+ }
140
+ function getLocalCwd(config) {
141
+ return path.resolve(config?.workspace?.root ?? config?.cwd ?? process.cwd());
142
+ }
143
+ /**
144
+ * Resolves the effective workspace boundary: a list of absolute roots
145
+ * that file operations are allowed to touch. The first entry is always
146
+ * the canonical root (`getLocalCwd`); subsequent entries come from
147
+ * `workspace.additionalRoots` when provided.
148
+ *
149
+ * Returns plain absolute paths — callers symlink-resolve when they
150
+ * need realpath equality (see `resolveWorkspacePathSafe`).
151
+ */
152
+ function getWorkspaceRoots(config) {
153
+ const root = getLocalCwd(config);
154
+ const extras = config?.workspace?.additionalRoots ?? [];
155
+ if (extras.length === 0)
156
+ return [root];
157
+ const seen = new Set([root]);
158
+ const out = [root];
159
+ for (const extra of extras) {
160
+ // Relative `additionalRoots` entries are anchored to the
161
+ // workspace root (so monorepo configs like
162
+ // `additionalRoots: ['../shared']` resolve to a sibling of
163
+ // `root` rather than to `process.cwd()/../shared`, which would
164
+ // mean something completely different on a server with a
165
+ // different cwd).
166
+ const abs = path.isAbsolute(extra) ? path.resolve(extra) : path.resolve(root, extra);
167
+ if (!seen.has(abs)) {
168
+ seen.add(abs);
169
+ out.push(abs);
170
+ }
171
+ }
172
+ return out;
173
+ }
174
+ /**
175
+ * Pluggable spawn resolver. Honours `local.exec.spawn` first, falls
176
+ * back to the legacy top-level `local.spawn`, then to Node's
177
+ * `child_process.spawn`. Centralised so engine swapping is one knob.
178
+ */
179
+ function getSpawn(config) {
180
+ return (config?.exec?.spawn ?? config?.spawn ?? child_process.spawn);
181
+ }
182
+ /**
183
+ * Pluggable filesystem resolver. Honours `local.exec.fs`, falls back
184
+ * to the Node-host implementation. A future remote engine supplies
185
+ * its own implementation here and inherits every file-touching tool.
186
+ */
187
+ function getWorkspaceFS(config) {
188
+ return config?.exec?.fs ?? workspaceFS.nodeWorkspaceFS;
189
+ }
190
+ /**
191
+ * Resolves the workspace boundary for *write* operations. Honours
192
+ * `workspace.allowWriteOutside` (and the deprecated
193
+ * `allowOutsideWorkspace`) by returning `null`, which the path-safety
194
+ * helpers interpret as "skip the write clamp".
195
+ */
196
+ function getWriteRoots(config) {
197
+ // Granular flag wins over the legacy one when explicitly set
198
+ // (true OR false) — otherwise a host tightening access during
199
+ // migration (`allowOutsideWorkspace: true, workspace.
200
+ // allowWriteOutside: false`) would still get the loose behavior
201
+ // because the legacy flag short-circuited the OR. Codex P1 #36.
202
+ const granular = config?.workspace?.allowWriteOutside;
203
+ if (granular === true)
204
+ return null;
205
+ if (granular === false)
206
+ return getWorkspaceRoots(config);
207
+ if (config?.allowOutsideWorkspace === true)
208
+ return null;
209
+ return getWorkspaceRoots(config);
210
+ }
211
+ /**
212
+ * Resolves the workspace boundary for *read* operations. Honours
213
+ * `workspace.allowReadOutside` (and the deprecated
214
+ * `allowOutsideWorkspace`) by returning `null`.
215
+ */
216
+ function getReadRoots(config) {
217
+ // Same precedence as getWriteRoots: granular flag is authoritative
218
+ // when set, legacy flag is the fallback. Codex P1 #36.
219
+ const granular = config?.workspace?.allowReadOutside;
220
+ if (granular === true)
221
+ return null;
222
+ if (granular === false)
223
+ return getWorkspaceRoots(config);
224
+ if (config?.allowOutsideWorkspace === true)
225
+ return null;
226
+ return getWorkspaceRoots(config);
227
+ }
228
+ function getLocalSessionId(config) {
229
+ const cwd = getLocalCwd(config);
230
+ const digest = crypto.createHash('sha1').update(cwd).digest('hex').slice(0, 12);
231
+ return `${DEFAULT_LOCAL_SESSION_ID}:${digest}`;
232
+ }
233
+ const missingSandboxRuntimeMessage = [
234
+ 'Local sandbox is enabled, but @anthropic-ai/sandbox-runtime is not installed.',
235
+ 'Install it with `npm install @anthropic-ai/sandbox-runtime`, or disable local sandboxing with `local.sandbox.enabled: false`.',
236
+ ].join(' ');
237
+ /** Lazy-loads the ESM-only sandbox runtime only when sandboxing is enabled. */
238
+ function loadSandboxRuntime() {
239
+ sandboxRuntimePromise ??= import('@anthropic-ai/sandbox-runtime');
240
+ return sandboxRuntimePromise;
241
+ }
242
+ function shouldUseLocalSandbox(config) {
243
+ return config.sandbox?.enabled === true;
244
+ }
245
+ let sandboxOffWarned = false;
246
+ function maybeWarnSandboxOff(config) {
247
+ if (sandboxOffWarned || shouldUseLocalSandbox(config)) {
248
+ return;
249
+ }
250
+ sandboxOffWarned = true;
251
+ // eslint-disable-next-line no-console
252
+ console.warn('[@librechat/agents] Local execution engine is running without ' +
253
+ '@anthropic-ai/sandbox-runtime wrapping. The agent has full access to ' +
254
+ 'the host filesystem and network. Set toolExecution.local.sandbox.enabled ' +
255
+ '= true to opt into process sandboxing.');
256
+ }
257
+ /**
258
+ * Test-only reset hook for the sandbox-off warning latch.
259
+ *
260
+ * @internal Not part of the public SDK surface.
261
+ */
262
+ function _resetLocalEngineWarningsForTests() {
263
+ sandboxOffWarned = false;
264
+ }
265
+ function truncateLocalOutput(value, maxChars = DEFAULT_MAX_OUTPUT_CHARS) {
266
+ if (value.length <= maxChars) {
267
+ return value;
268
+ }
269
+ const head = Math.floor(maxChars * 0.6);
270
+ const tail = maxChars - head;
271
+ const omitted = value.length - maxChars;
272
+ return `${value.slice(0, head)}\n\n[... ${omitted} characters truncated ...]\n\n${value.slice(value.length - tail)}`;
273
+ }
274
+ function stripQuotedContent(command) {
275
+ let output = '';
276
+ let quote;
277
+ let escaped = false;
278
+ for (let i = 0; i < command.length; i++) {
279
+ const char = command[i];
280
+ if (escaped) {
281
+ escaped = false;
282
+ output += ' ';
283
+ continue;
284
+ }
285
+ if (char === '\\') {
286
+ escaped = true;
287
+ output += ' ';
288
+ continue;
289
+ }
290
+ if (quote != null) {
291
+ if (char === quote) {
292
+ quote = undefined;
293
+ }
294
+ output += ' ';
295
+ continue;
296
+ }
297
+ if (char === '"' || char === '\'' || char === '`') {
298
+ quote = char;
299
+ output += ' ';
300
+ continue;
301
+ }
302
+ if (char === '#') {
303
+ while (i < command.length && command[i] !== '\n') {
304
+ output += ' ';
305
+ i++;
306
+ }
307
+ output += '\n';
308
+ continue;
309
+ }
310
+ output += char;
311
+ }
312
+ return output;
313
+ }
314
+ async function validateBashCommand(command, config = {}) {
315
+ const errors = [];
316
+ const warnings = [];
317
+ const normalized = stripQuotedContent(command);
318
+ if (command.trim() === '') {
319
+ errors.push('Command is empty.');
320
+ }
321
+ if (command.includes('\0')) {
322
+ errors.push('Command contains a NUL byte.');
323
+ }
324
+ if (config.allowDangerousCommands !== true) {
325
+ let blocked = false;
326
+ // Strip-then-match for the bare-form patterns (avoids false
327
+ // positives where the destructive text is buried inside a
328
+ // string the user is just printing).
329
+ for (const pattern of dangerousCommandPatterns) {
330
+ if (pattern.test(normalized)) {
331
+ errors.push('Command matches a destructive command pattern.');
332
+ blocked = true;
333
+ break;
334
+ }
335
+ }
336
+ // Original-form pass for patterns that REQUIRE matching quote
337
+ // pairs around a destructive path. Without this, `rm -rf "/"`
338
+ // and `chmod -R 777 "/"` slip past the strip-then-match pass
339
+ // because their destructive target is inside quotes.
340
+ if (!blocked) {
341
+ for (const pattern of quotedDestructivePatterns) {
342
+ if (pattern.test(command)) {
343
+ errors.push('Command matches a destructive command pattern (quoted target).');
344
+ blocked = true;
345
+ break;
346
+ }
347
+ }
348
+ }
349
+ if (!blocked) {
350
+ for (const pattern of nestedShellDestructivePatterns) {
351
+ if (pattern.test(command)) {
352
+ errors.push('Command matches a destructive command pattern (nested shell payload).');
353
+ break;
354
+ }
355
+ }
356
+ }
357
+ }
358
+ const bashAstMode = config.bashAst ?? 'off';
359
+ if (bashAstMode !== 'off' && config.allowDangerousCommands !== true) {
360
+ const findings = bashAst.runBashAstChecks(normalized, bashAstMode);
361
+ const split = bashAst.bashAstFindingsToErrors(findings);
362
+ errors.push(...split.errors);
363
+ warnings.push(...split.warnings);
364
+ }
365
+ if (config.readOnly === true && mutatingCommandPattern.test(normalized)) {
366
+ errors.push('Command appears to mutate files or repository state in read-only local mode.');
367
+ }
368
+ // Use the same shell the actual execution path will use. Hard-coding
369
+ // DEFAULT_SHELL here would reject perfectly valid commands when the
370
+ // host configures `local.shell` to a non-bash binary (or when the
371
+ // runtime doesn't have bash installed at all but does have e.g. zsh).
372
+ const syntaxShell = config.shell ?? DEFAULT_SHELL;
373
+ const syntax = await spawnLocalProcess(syntaxShell, ['-n', '-c', command], {
374
+ ...config,
375
+ timeoutMs: Math.min(config.timeoutMs ?? DEFAULT_TIMEOUT_MS, 5000),
376
+ sandbox: { enabled: false },
377
+ }, { internal: true }).catch((error) => ({
378
+ stdout: '',
379
+ stderr: error.message,
380
+ exitCode: 1,
381
+ timedOut: false,
382
+ }));
383
+ if (syntax.exitCode !== 0) {
384
+ errors.push(syntax.stderr.trim() === ''
385
+ ? 'Command failed shell syntax validation.'
386
+ : `Command failed shell syntax validation: ${syntax.stderr.trim()}`);
387
+ }
388
+ if (/\bsudo\b/.test(normalized)) {
389
+ warnings.push('Command requests elevated privileges with sudo.');
390
+ }
391
+ return {
392
+ valid: errors.length === 0,
393
+ errors,
394
+ warnings,
395
+ };
396
+ }
397
+ async function ensureSandbox(config, cwd) {
398
+ if (!shouldUseLocalSandbox(config)) {
399
+ return undefined;
400
+ }
401
+ const runtime = await loadSandboxRuntime().catch((error) => {
402
+ throw new Error(`${missingSandboxRuntimeMessage} Cause: ${error.message}`);
403
+ });
404
+ const runtimeConfig = buildSandboxRuntimeConfig(config, cwd, runtime.getDefaultWritePaths);
405
+ const nextKey = JSON.stringify(runtimeConfig);
406
+ if (sandboxInitialized && sandboxConfigKey === nextKey) {
407
+ return runtime.SandboxManager;
408
+ }
409
+ const dependencyCheck = runtime.SandboxManager.checkDependencies();
410
+ if (dependencyCheck.errors.length > 0) {
411
+ if (config.sandbox?.failIfUnavailable === true) {
412
+ throw new Error(`Local sandbox requested but unavailable: ${dependencyCheck.errors.join('; ')}`);
413
+ }
414
+ return undefined;
415
+ }
416
+ if (sandboxInitialized) {
417
+ await runtime.SandboxManager.reset();
418
+ }
419
+ // Cast at the runtime boundary — our public `BuiltSandboxRuntimeConfig`
420
+ // is intentionally structural to keep the optional peer dep out of
421
+ // generated `.d.ts` (Codex P1 #22). It's a structural subset of the
422
+ // peer's `SandboxRuntimeConfig`, so the assignment is sound at the
423
+ // one site where the peer is actually loaded.
424
+ await runtime.SandboxManager.initialize(runtimeConfig);
425
+ sandboxInitialized = true;
426
+ sandboxConfigKey = nextKey;
427
+ return runtime.SandboxManager;
428
+ }
429
+ /**
430
+ * Loopback addresses the in-process programmatic-tool bridge listens
431
+ * on (`LocalProgrammaticToolCalling.ts` binds 127.0.0.1). Sandboxed
432
+ * code launched by `run_tools_with_code` / `run_tools_with_bash` HTTPs
433
+ * back to that address — without the entries below, the bridge is
434
+ * silently blocked under sandbox.
435
+ */
436
+ const BRIDGE_LOOPBACK_HOSTS = ['127.0.0.1', 'localhost', '::1'];
437
+ function buildSandboxRuntimeConfig(config, cwd, getDefaultWritePaths) {
438
+ const sandbox = config.sandbox;
439
+ // Seed allowedDomains with loopback so the programmatic-tool bridge
440
+ // works under sandbox. If the host explicitly denied a loopback
441
+ // entry via `deniedDomains`, respect that and skip seeding it.
442
+ const userAllowed = sandbox?.network?.allowedDomains ?? [];
443
+ const denied = new Set(sandbox?.network?.deniedDomains ?? []);
444
+ const seededLoopback = BRIDGE_LOOPBACK_HOSTS.filter((host) => !denied.has(host) && !userAllowed.includes(host));
445
+ const allowedDomains = [...seededLoopback, ...userAllowed];
446
+ // Mirror the file-tools workspace boundary: anything in
447
+ // `additionalRoots` counts as in-workspace, so sandboxed shell/code
448
+ // can write there too. Without this, file_tools can resolve a
449
+ // sibling-root path but `bash`/`execute_code` is denied write
450
+ // access — confusing divergence flagged in Codex P2 #15.
451
+ const workspaceWriteRoots = config.workspace?.additionalRoots != null
452
+ ? getWorkspaceRoots(config)
453
+ : [cwd];
454
+ return {
455
+ network: {
456
+ allowedDomains,
457
+ deniedDomains: sandbox?.network?.deniedDomains ?? [],
458
+ ...(sandbox?.network?.allowUnixSockets != null && {
459
+ allowUnixSockets: sandbox.network.allowUnixSockets,
460
+ }),
461
+ ...(sandbox?.network?.allowAllUnixSockets != null && {
462
+ allowAllUnixSockets: sandbox.network.allowAllUnixSockets,
463
+ }),
464
+ ...(sandbox?.network?.allowLocalBinding != null && {
465
+ allowLocalBinding: sandbox.network.allowLocalBinding,
466
+ }),
467
+ ...(sandbox?.network?.allowMachLookup != null && {
468
+ allowMachLookup: sandbox.network.allowMachLookup,
469
+ }),
470
+ },
471
+ filesystem: {
472
+ denyRead: sandbox?.filesystem?.denyRead ?? [],
473
+ allowRead: sandbox?.filesystem?.allowRead,
474
+ allowWrite: sandbox?.filesystem?.allowWrite ?? [
475
+ ...workspaceWriteRoots,
476
+ ...getDefaultWritePaths(),
477
+ ],
478
+ denyWrite: sandbox?.filesystem?.denyWrite ?? [
479
+ '.env',
480
+ '.env.*',
481
+ '.git/config',
482
+ '.git/hooks/**',
483
+ ],
484
+ allowGitConfig: sandbox?.filesystem?.allowGitConfig,
485
+ },
486
+ };
487
+ }
488
+ async function spawnLocalProcess(command, args, config = {}, options) {
489
+ const cwd = getLocalCwd(config);
490
+ const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
491
+ const maxOutputChars = config.maxOutputChars ?? DEFAULT_MAX_OUTPUT_CHARS;
492
+ // Streaming caps. Local tools execute arbitrary shell/code, so a noisy
493
+ // command (`yes`, `cat /dev/urandom | base64`, a verbose build) could
494
+ // accumulate gigabytes in memory before hitting the post-close cap.
495
+ // We bound in-memory per-stream and spill the rest to disk; we also
496
+ // hard-kill the child once total streamed bytes pass `maxSpawnedBytes`
497
+ // so a process producing unbounded output gets stopped instead of
498
+ // letting the host OOM.
499
+ const inMemoryCapBytes = maxOutputChars * 2;
500
+ const hardKillBytes = config.maxSpawnedBytes ?? DEFAULT_MAX_SPAWNED_BYTES;
501
+ const sandboxManager = await ensureSandbox(config, cwd);
502
+ // Internal probes (validateBashCommand syntax preflight,
503
+ // isRipgrepAvailable, syntax-check probe cache priming) pass
504
+ // `internal: true` so they don't emit a misleading "sandbox is
505
+ // off" warning AND don't flip `sandboxOffWarned = true`. Without
506
+ // this Codex P2 path: a run with `sandbox.enabled: true` would
507
+ // see a false warning from the syntax preflight, and the latch
508
+ // flip would suppress the warning in a *later* truly-unsandboxed
509
+ // run — exactly the scenario operators need to see.
510
+ if (sandboxManager == null && options?.internal !== true) {
511
+ maybeWarnSandboxOff(config);
512
+ }
513
+ let spawnCommand = command;
514
+ let spawnArgs = args;
515
+ if (sandboxManager != null) {
516
+ const rendered = [command, ...args.map(shellQuote)].join(' ');
517
+ const sandboxed = await sandboxManager.wrapWithSandbox(rendered);
518
+ spawnCommand = config.shell ?? DEFAULT_SHELL;
519
+ spawnArgs = ['-lc', sandboxed];
520
+ }
521
+ const launcher = getSpawn(config);
522
+ return new Promise((resolveResult, reject) => {
523
+ const child = launcher(spawnCommand, spawnArgs, {
524
+ cwd,
525
+ detached: process.platform !== 'win32',
526
+ env: { ...process.env, ...(config.env ?? {}) },
527
+ stdio: ['ignore', 'pipe', 'pipe'],
528
+ });
529
+ let stdout = '';
530
+ let stderr = '';
531
+ let totalSpawnedBytes = 0;
532
+ let overflowKilled = false;
533
+ let spillStream;
534
+ let spillPath;
535
+ let settled = false;
536
+ let timedOut = false;
537
+ let timeout;
538
+ const ensureSpill = () => {
539
+ if (spillStream != null)
540
+ return;
541
+ // Lazy-open the temp file the first time a stream's in-memory
542
+ // buffer overflows. Seed it with everything we've buffered so
543
+ // the file holds the FULL output (not just the post-cap tail).
544
+ // Uses the static `createWriteStream` import — `require('fs')`
545
+ // would throw `ReferenceError: require is not defined` in ESM
546
+ // consumers (this package ships both `dist/cjs` and `dist/esm`).
547
+ spillPath = path.resolve(os.tmpdir(), `lc-local-output-${crypto.randomUUID()}.txt`);
548
+ spillStream = fs.createWriteStream(spillPath);
549
+ spillStream.write('===== stdout =====\n');
550
+ spillStream.write(stdout);
551
+ spillStream.write('\n===== stderr =====\n');
552
+ spillStream.write(stderr);
553
+ spillStream.write('\n===== overflow stream begins here =====\n');
554
+ };
555
+ const handleChunk = (buf, kind) => {
556
+ totalSpawnedBytes += buf.length;
557
+ // hardKillBytes <= 0 means "no cap" per the public config contract
558
+ // (see LocalExecutionConfig.maxSpawnedBytes). Skip the kill check
559
+ // entirely in that case so a single byte doesn't terminate the run.
560
+ if (hardKillBytes > 0 &&
561
+ totalSpawnedBytes > hardKillBytes &&
562
+ !overflowKilled) {
563
+ overflowKilled = true;
564
+ killProcessTree(child);
565
+ return;
566
+ }
567
+ const current = kind === 'stdout' ? stdout : stderr;
568
+ if (current.length < inMemoryCapBytes) {
569
+ const text = buf.toString('utf8');
570
+ if (kind === 'stdout')
571
+ stdout += text;
572
+ else
573
+ stderr += text;
574
+ if (current.length + text.length >= inMemoryCapBytes) {
575
+ ensureSpill();
576
+ }
577
+ }
578
+ else {
579
+ ensureSpill();
580
+ spillStream.write(`[${kind}] `);
581
+ spillStream.write(buf);
582
+ }
583
+ };
584
+ const finish = (result) => {
585
+ if (settled) {
586
+ return;
587
+ }
588
+ settled = true;
589
+ if (timeout != null) {
590
+ clearTimeout(timeout);
591
+ }
592
+ const finalize = () => {
593
+ const truncated = {
594
+ stdout: truncateLocalOutput(result.stdout, maxOutputChars),
595
+ stderr: truncateLocalOutput(result.stderr, maxOutputChars),
596
+ };
597
+ resolveResult({
598
+ ...result,
599
+ ...truncated,
600
+ ...(spillPath != null ? { fullOutputPath: spillPath } : {}),
601
+ });
602
+ };
603
+ if (spillStream == null) {
604
+ finalize();
605
+ return;
606
+ }
607
+ // Wait for the temp file to flush before reporting the path.
608
+ // Otherwise the model sees `full_output_path: …` for a file
609
+ // that's still being written.
610
+ spillStream.end(() => finalize());
611
+ };
612
+ const fail = (error) => {
613
+ if (settled) {
614
+ return;
615
+ }
616
+ settled = true;
617
+ if (timeout != null) {
618
+ clearTimeout(timeout);
619
+ }
620
+ if (spillStream != null) {
621
+ spillStream.end();
622
+ }
623
+ reject(error);
624
+ };
625
+ if (timeoutMs > 0) {
626
+ timeout = setTimeout(() => {
627
+ timedOut = true;
628
+ killProcessTree(child);
629
+ }, timeoutMs);
630
+ }
631
+ child.stdout?.on('data', (chunk) => {
632
+ handleChunk(chunk, 'stdout');
633
+ });
634
+ child.stderr?.on('data', (chunk) => {
635
+ handleChunk(chunk, 'stderr');
636
+ });
637
+ child.on('error', fail);
638
+ child.on('close', (exitCode, signal) => {
639
+ // Synthesize a non-zero exit code whenever the process exited
640
+ // by signal — Node reports `exitCode: null` in that case and
641
+ // the formatter only prints non-null exit codes, so signal
642
+ // kills (overflow guard, `kill -9 $$` from inside the script,
643
+ // native crashes, OS OOM killer, …) would otherwise look like
644
+ // successful runs (Codex P1 + Codex P2). Overflow path keeps
645
+ // its 137 (SIGKILL) for compatibility; other signals map per
646
+ // POSIX `128 + signum`.
647
+ let finalExit = exitCode;
648
+ if (finalExit == null) {
649
+ if (overflowKilled) {
650
+ finalExit = 137;
651
+ }
652
+ else if (signal != null) {
653
+ finalExit = exitCodeForSignal(signal);
654
+ }
655
+ }
656
+ finish({
657
+ stdout,
658
+ stderr,
659
+ exitCode: finalExit,
660
+ timedOut,
661
+ ...(overflowKilled ? { overflowKilled: true } : {}),
662
+ ...(signal != null ? { signal } : {}),
663
+ });
664
+ });
665
+ });
666
+ }
667
+ async function executeLocalBash(command, config = {}) {
668
+ const validation = await validateBashCommand(command, config);
669
+ if (!validation.valid) {
670
+ throw new Error(validation.errors.join('\n'));
671
+ }
672
+ const shell = config.shell ?? DEFAULT_SHELL;
673
+ return spawnLocalProcess(shell, ['-lc', command], config);
674
+ }
675
+ /**
676
+ * Variant of `executeLocalBash` that exposes `args` as positional
677
+ * shell parameters (`$1`, `$2`, …). Mirrors what the other runtimes
678
+ * do in `getRuntimeCommand`. Uses the standard `bash -c <code> --
679
+ * arg0 arg1 …` form: the `--` becomes `$0`, then `args[0]` is `$1`
680
+ * and so on. Same AST validation as the no-args path.
681
+ *
682
+ * Used by both the `execute_code`/`lang:'bash'` path AND the
683
+ * `bash_tool` factory so the schema's `args` contract works
684
+ * identically in both surfaces.
685
+ */
686
+ /**
687
+ * Matches a single arg that, on its own, references a protected
688
+ * location (`/`, `~`, `$HOME`, `${HOME}`, `.`, with optional trailing
689
+ * slash, wildcard, or dot-glob suffix). Used to spot the
690
+ * `command: 'rm -rf "$1"', args: ['/']` shape where the destructive
691
+ * target is moved into a positional arg to evade the command regex.
692
+ * Codex P1 [45], extended for dot-glob in Codex P1 [47] (mirrors the
693
+ * `DESTRUCTIVE_TARGET` suffix matrix exactly).
694
+ */
695
+ const PROTECTED_TARGET_ARG_RE = /^(?:\/|~|\$\{?HOME\}?|\.)(?:\/?\.?\*|\/)?$/;
696
+ /**
697
+ * Mutating-op recognizer for the args check. Conservative: only the
698
+ * three operations the destructive-command guard already covers
699
+ * directly (`rm -rf …`, `chmod -R …`, `chown -R …`). Other shell
700
+ * builtins might mutate state (`mv`, `cp` over an existing file,
701
+ * etc.) but the destructive guard doesn't try to catch those today,
702
+ * so we don't widen here either.
703
+ */
704
+ const DESTRUCTIVE_OP_IN_COMMAND_RE = /\b(?:rm\s+-[^\s]*[rf]|chmod\s+-R|chown\s+-R)\b/;
705
+ async function executeLocalBashWithArgs(command, args, config = {}) {
706
+ const validation = await validateBashCommand(command, config);
707
+ if (!validation.valid) {
708
+ throw new Error(validation.errors.join('\n'));
709
+ }
710
+ // Per-arg protected-target check (Codex P1 [45]). The command
711
+ // regex can't see `$1`/`$@` substitutions at runtime — `command:
712
+ // 'rm -rf "$1"', args: ['/']` would expand to `rm -rf '/'` inside
713
+ // bash but the validator only saw `rm -rf "$1"` (no destructive
714
+ // target). Block when (a) the command contains a destructive op
715
+ // AND (b) at least one arg matches the protected-target shape.
716
+ // Skipped when allowDangerousCommands is true (host-opted-in).
717
+ if (args.length > 0 &&
718
+ config.allowDangerousCommands !== true &&
719
+ DESTRUCTIVE_OP_IN_COMMAND_RE.test(command)) {
720
+ const offending = args.find((a) => PROTECTED_TARGET_ARG_RE.test(a));
721
+ if (offending !== undefined) {
722
+ throw new Error(`Command matches a destructive command pattern (protected target "${offending}" passed via positional arg).`);
723
+ }
724
+ }
725
+ const shell = config.shell ?? DEFAULT_SHELL;
726
+ return spawnLocalProcess(shell, ['-lc', command, '--', ...args], config);
727
+ }
728
+ async function executeLocalCode(input, config = {}) {
729
+ if (input.lang === 'bash') {
730
+ // Append `args` as positional parameters via the standard
731
+ // `bash -c <code> -- <args...>` form so `$1`, `$2`, … inside
732
+ // `code` resolve correctly. Honours the same args contract the
733
+ // other runtimes (py, js, …) already support.
734
+ if (input.args != null && input.args.length > 0) {
735
+ return executeLocalBashWithArgs(input.code, input.args, config);
736
+ }
737
+ return executeLocalBash(input.code, config);
738
+ }
739
+ const tempDir = path.resolve(os.tmpdir(), `lc-local-${crypto.randomUUID()}`);
740
+ await promises.mkdir(tempDir, { recursive: true });
741
+ try {
742
+ const runtime = getRuntimeCommand(input.lang, tempDir, input.code, input.args, config.shell);
743
+ if (runtime.source != null) {
744
+ await promises.writeFile(path.resolve(tempDir, runtime.fileName), runtime.source, 'utf8');
745
+ }
746
+ return await spawnLocalProcess(runtime.command, runtime.args, config);
747
+ }
748
+ finally {
749
+ await promises.rm(tempDir, { recursive: true, force: true });
750
+ }
751
+ }
752
+ function getRuntimeCommand(lang, tempDir, code, args = [],
753
+ // Override for the shell used by compile-style runtimes (`rs`,
754
+ // `c`, `cpp`, `java`, `d`, `f90`). Threads `local.shell` so a host
755
+ // that doesn't have bash (or wants `/bin/sh` / zsh) can still
756
+ // execute these languages — Codex P2 #29: the bare-bash hardcode
757
+ // mirrored the same gap that Codex P1 #6 fixed for the syntax
758
+ // preflight, but had been missed for these runtime invocations.
759
+ shellOverride) {
760
+ const fileFor = (name) => path.resolve(tempDir, name);
761
+ const shell = shellOverride ?? configShell();
762
+ switch (lang) {
763
+ case 'py':
764
+ return {
765
+ command: 'python3',
766
+ args: [fileFor('main.py'), ...args],
767
+ fileName: 'main.py',
768
+ source: code,
769
+ };
770
+ case 'js':
771
+ return {
772
+ command: 'node',
773
+ args: [fileFor('main.js'), ...args],
774
+ fileName: 'main.js',
775
+ source: code,
776
+ };
777
+ case 'ts':
778
+ return {
779
+ command: 'npx',
780
+ args: ['--no-install', 'tsx', fileFor('main.ts'), ...args],
781
+ fileName: 'main.ts',
782
+ source: code,
783
+ };
784
+ case 'php':
785
+ return {
786
+ command: 'php',
787
+ args: [fileFor('main.php'), ...args],
788
+ fileName: 'main.php',
789
+ source: code,
790
+ };
791
+ case 'go':
792
+ return {
793
+ command: 'go',
794
+ args: ['run', fileFor('main.go'), ...args],
795
+ fileName: 'main.go',
796
+ source: code,
797
+ };
798
+ case 'rs':
799
+ return {
800
+ command: shell,
801
+ args: [
802
+ '-lc',
803
+ `rustc ${shellQuote(fileFor('main.rs'))} -o ${shellQuote(fileFor('main-rs'))} && ${shellQuote(fileFor('main-rs'))} ${args.map(shellQuote).join(' ')}`,
804
+ ],
805
+ fileName: 'main.rs',
806
+ source: code,
807
+ };
808
+ case 'c':
809
+ return {
810
+ command: shell,
811
+ args: [
812
+ '-lc',
813
+ `cc ${shellQuote(fileFor('main.c'))} -o ${shellQuote(fileFor('main-c'))} && ${shellQuote(fileFor('main-c'))} ${args.map(shellQuote).join(' ')}`,
814
+ ],
815
+ fileName: 'main.c',
816
+ source: code,
817
+ };
818
+ case 'cpp':
819
+ return {
820
+ command: shell,
821
+ args: [
822
+ '-lc',
823
+ `c++ ${shellQuote(fileFor('main.cpp'))} -o ${shellQuote(fileFor('main-cpp'))} && ${shellQuote(fileFor('main-cpp'))} ${args.map(shellQuote).join(' ')}`,
824
+ ],
825
+ fileName: 'main.cpp',
826
+ source: code,
827
+ };
828
+ case 'java':
829
+ return {
830
+ command: shell,
831
+ args: [
832
+ '-lc',
833
+ `javac ${shellQuote(fileFor('Main.java'))} && java -cp ${shellQuote(tempDir)} Main ${args.map(shellQuote).join(' ')}`,
834
+ ],
835
+ fileName: 'Main.java',
836
+ source: code,
837
+ };
838
+ case 'r':
839
+ return {
840
+ command: 'Rscript',
841
+ args: [fileFor('main.R'), ...args],
842
+ fileName: 'main.R',
843
+ source: code,
844
+ };
845
+ case 'd':
846
+ return {
847
+ command: shell,
848
+ args: [
849
+ '-lc',
850
+ `dmd ${shellQuote(fileFor('main.d'))} -of=${shellQuote(fileFor('main-d'))} && ${shellQuote(fileFor('main-d'))} ${args.map(shellQuote).join(' ')}`,
851
+ ],
852
+ fileName: 'main.d',
853
+ source: code,
854
+ };
855
+ case 'f90':
856
+ return {
857
+ command: shell,
858
+ args: [
859
+ '-lc',
860
+ `gfortran ${shellQuote(fileFor('main.f90'))} -o ${shellQuote(fileFor('main-f90'))} && ${shellQuote(fileFor('main-f90'))} ${args.map(shellQuote).join(' ')}`,
861
+ ],
862
+ fileName: 'main.f90',
863
+ source: code,
864
+ };
865
+ default:
866
+ throw new Error(`Unsupported local runtime: ${lang}`);
867
+ }
868
+ }
869
+ function configShell() {
870
+ return process.platform === 'win32' ? 'bash.exe' : 'bash';
871
+ }
872
+ /**
873
+ * How long after SIGTERM we wait before escalating to SIGKILL. A
874
+ * cooperative process gets a graceful chance to flush + clean up;
875
+ * a process that ignores or traps SIGTERM (`trap '' TERM`) gets
876
+ * killed unconditionally so timeoutMs / maxSpawnedBytes can't be
877
+ * defeated by a hostile script. Codex P1 #28 — pre-fix the spawn
878
+ * promise would never resolve in that case and the entire tool run
879
+ * would hang past the advertised timeout.
880
+ */
881
+ const SIGKILL_ESCALATION_MS = 2000;
882
+ function sigterm(child) {
883
+ if (child.pid == null)
884
+ return;
885
+ try {
886
+ if (process.platform === 'win32') {
887
+ child.kill('SIGTERM');
888
+ return;
889
+ }
890
+ process.kill(-child.pid, 'SIGTERM');
891
+ }
892
+ catch {
893
+ child.kill('SIGTERM');
894
+ }
895
+ }
896
+ function sigkill(child) {
897
+ if (child.pid == null)
898
+ return;
899
+ if (child.exitCode != null || child.signalCode != null)
900
+ return;
901
+ try {
902
+ if (process.platform === 'win32') {
903
+ child.kill('SIGKILL');
904
+ return;
905
+ }
906
+ process.kill(-child.pid, 'SIGKILL');
907
+ }
908
+ catch {
909
+ try {
910
+ child.kill('SIGKILL');
911
+ }
912
+ catch {
913
+ /* already dead */
914
+ }
915
+ }
916
+ }
917
+ function killProcessTree(child) {
918
+ sigterm(child);
919
+ // Escalate to SIGKILL if the child is still alive after the grace
920
+ // window. Use unref() so the timer doesn't keep the Node process
921
+ // alive past the parent's natural exit.
922
+ const escalation = setTimeout(() => sigkill(child), SIGKILL_ESCALATION_MS);
923
+ escalation.unref?.();
924
+ child.once('close', () => clearTimeout(escalation));
925
+ }
926
+ function shellQuote(value) {
927
+ if (value === '') {
928
+ return '\'\'';
929
+ }
930
+ if (/^[A-Za-z0-9_/:=.,@%+-]+$/.test(value)) {
931
+ return value;
932
+ }
933
+ return `'${value.replace(/'/g, '\'\\\'\'')}'`;
934
+ }
935
+ function resolveWorkspacePath(filePath, config = {}, intent = 'write') {
936
+ const cwd = getLocalCwd(config);
937
+ const absolutePath = path.isAbsolute(filePath) ? path.resolve(filePath) : path.resolve(cwd, filePath);
938
+ const roots = intent === 'write' ? getWriteRoots(config) : getReadRoots(config);
939
+ if (roots == null)
940
+ return absolutePath; // explicit allow-outside
941
+ if (absolutePath === cwd || isInsideAnyRoot(absolutePath, roots)) {
942
+ return absolutePath;
943
+ }
944
+ throw new Error(`Path is outside the local workspace: ${filePath}`);
945
+ }
946
+ function isInsideAnyRoot(absolutePath, roots) {
947
+ for (const root of roots) {
948
+ if (absolutePath === root)
949
+ return true;
950
+ const rel = path.relative(root, absolutePath);
951
+ if (!rel.startsWith('..') && !path.isAbsolute(rel))
952
+ return true;
953
+ }
954
+ return false;
955
+ }
956
+ async function realpathOrSelf(absolutePath, realpathImpl = promises.realpath) {
957
+ try {
958
+ return await realpathImpl(absolutePath);
959
+ }
960
+ catch {
961
+ return absolutePath;
962
+ }
963
+ }
964
+ /**
965
+ * Resolves the realpath of `absolutePath`, falling back to the nearest
966
+ * existing ancestor when the target itself does not yet exist (so the
967
+ * containment check still works for `write_file` to a brand-new path).
968
+ *
969
+ * Codex P2 #38: takes the realpath impl as a parameter so callers
970
+ * can route through `WorkspaceFS.realpath` when a custom engine is
971
+ * configured. Pre-fix, host `fs/promises.realpath` would fail on a
972
+ * remote/in-memory FS path and silently fall back to lexical
973
+ * containment, leaving the symlink-escape clamp ineffective on
974
+ * non-default engines.
975
+ */
976
+ async function realpathOfPathOrAncestor(absolutePath, realpathImpl = promises.realpath) {
977
+ let current = absolutePath;
978
+ let suffix = '';
979
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
980
+ while (true) {
981
+ try {
982
+ const real = await realpathImpl(current);
983
+ return suffix === '' ? real : path.resolve(real, suffix);
984
+ }
985
+ catch {
986
+ const parent = path.resolve(current, '..');
987
+ if (parent === current) {
988
+ return absolutePath;
989
+ }
990
+ const base = current.slice(parent.length + 1);
991
+ suffix = suffix === '' ? base : `${base}/${suffix}`;
992
+ current = parent;
993
+ }
994
+ }
995
+ }
996
+ /**
997
+ * Resolves a workspace path AND follows any symlinks before checking
998
+ * containment, so a symlink inside the workspace pointing outside is
999
+ * rejected even though the lexical path looks safe. Handles paths that
1000
+ * don't yet exist (e.g. write_file targets) by realpath-resolving the
1001
+ * nearest existing ancestor and re-attaching the unresolved suffix.
1002
+ */
1003
+ async function resolveWorkspacePathSafe(filePath, config = {}, intent = 'write') {
1004
+ const lexical = resolveWorkspacePath(filePath, config, intent);
1005
+ const roots = intent === 'write' ? getWriteRoots(config) : getReadRoots(config);
1006
+ if (roots == null) {
1007
+ return lexical;
1008
+ }
1009
+ // Route realpath through the configured WorkspaceFS so a custom
1010
+ // engine (in-memory, remote) gets the same symlink-escape clamp
1011
+ // the host-fs path gets. Codex P2 #38: pre-fix the host realpath
1012
+ // would fail on a non-default FS path and silently fall back to
1013
+ // lexical containment, leaving the clamp ineffective.
1014
+ const fsRealpath = (p) => getWorkspaceFS(config).realpath(p);
1015
+ const realRoots = await Promise.all(roots.map((r) => realpathOrSelf(r, fsRealpath)));
1016
+ const realPath = await realpathOfPathOrAncestor(lexical, fsRealpath);
1017
+ if (isInsideAnyRoot(realPath, realRoots)) {
1018
+ return lexical;
1019
+ }
1020
+ throw new Error(`Path is outside the local workspace (symlink escape): ${filePath}`);
1021
+ }
1022
+
1023
+ exports._resetLocalEngineWarningsForTests = _resetLocalEngineWarningsForTests;
1024
+ exports.buildSandboxRuntimeConfig = buildSandboxRuntimeConfig;
1025
+ exports.executeLocalBash = executeLocalBash;
1026
+ exports.executeLocalBashWithArgs = executeLocalBashWithArgs;
1027
+ exports.executeLocalCode = executeLocalCode;
1028
+ exports.getLocalCwd = getLocalCwd;
1029
+ exports.getLocalSessionId = getLocalSessionId;
1030
+ exports.getReadRoots = getReadRoots;
1031
+ exports.getSpawn = getSpawn;
1032
+ exports.getWorkspaceFS = getWorkspaceFS;
1033
+ exports.getWorkspaceRoots = getWorkspaceRoots;
1034
+ exports.getWriteRoots = getWriteRoots;
1035
+ exports.resolveLocalExecutionConfig = resolveLocalExecutionConfig;
1036
+ exports.resolveWorkspacePath = resolveWorkspacePath;
1037
+ exports.resolveWorkspacePathSafe = resolveWorkspacePathSafe;
1038
+ exports.shellQuote = shellQuote;
1039
+ exports.spawnLocalProcess = spawnLocalProcess;
1040
+ exports.truncateLocalOutput = truncateLocalOutput;
1041
+ exports.validateBashCommand = validateBashCommand;
1042
+ //# sourceMappingURL=LocalExecutionEngine.cjs.map