@librechat/agents 3.1.77 → 3.1.78

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