operon-agents-core 0.1.0-alpha.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 (511) hide show
  1. package/LICENSE +55 -0
  2. package/README.md +7 -0
  3. package/dist/agent/agent.d.ts +65 -0
  4. package/dist/agent/agent.js +39 -0
  5. package/dist/agent/compose-hooks.d.ts +13 -0
  6. package/dist/agent/compose-hooks.js +197 -0
  7. package/dist/agent/concurrency.d.ts +22 -0
  8. package/dist/agent/concurrency.js +70 -0
  9. package/dist/agent/context-report.d.ts +60 -0
  10. package/dist/agent/context-report.js +45 -0
  11. package/dist/agent/graph.d.ts +48 -0
  12. package/dist/agent/graph.js +129 -0
  13. package/dist/agent/guardrail.d.ts +105 -0
  14. package/dist/agent/guardrail.js +314 -0
  15. package/dist/agent/handoff-executor.d.ts +21 -0
  16. package/dist/agent/handoff-executor.js +95 -0
  17. package/dist/agent/handoff.d.ts +42 -0
  18. package/dist/agent/handoff.js +70 -0
  19. package/dist/agent/index.d.ts +25 -0
  20. package/dist/agent/index.js +19 -0
  21. package/dist/agent/instruction-context.d.ts +33 -0
  22. package/dist/agent/instruction-context.js +100 -0
  23. package/dist/agent/pause.d.ts +12 -0
  24. package/dist/agent/pause.js +82 -0
  25. package/dist/agent/profile-builtins.d.ts +8 -0
  26. package/dist/agent/profile-builtins.js +130 -0
  27. package/dist/agent/profiles.d.ts +94 -0
  28. package/dist/agent/profiles.js +264 -0
  29. package/dist/agent/recovery.d.ts +10 -0
  30. package/dist/agent/recovery.js +151 -0
  31. package/dist/agent/run-support.d.ts +79 -0
  32. package/dist/agent/run-support.js +211 -0
  33. package/dist/agent/runner.d.ts +246 -0
  34. package/dist/agent/runner.js +786 -0
  35. package/dist/agent/session.d.ts +363 -0
  36. package/dist/agent/session.js +937 -0
  37. package/dist/agent/subagent-tools.d.ts +18 -0
  38. package/dist/agent/subagent-tools.js +650 -0
  39. package/dist/agent/subagent.d.ts +56 -0
  40. package/dist/agent/subagent.js +50 -0
  41. package/dist/agent/toolset.d.ts +24 -0
  42. package/dist/agent/toolset.js +112 -0
  43. package/dist/agent/workflow/index.d.ts +9 -0
  44. package/dist/agent/workflow/index.js +8 -0
  45. package/dist/agent/workflow/journal.d.ts +180 -0
  46. package/dist/agent/workflow/journal.js +224 -0
  47. package/dist/agent/workflow/manager.d.ts +27 -0
  48. package/dist/agent/workflow/manager.js +33 -0
  49. package/dist/agent/workflow/parse.d.ts +17 -0
  50. package/dist/agent/workflow/parse.js +174 -0
  51. package/dist/agent/workflow/prompt.d.ts +8 -0
  52. package/dist/agent/workflow/prompt.js +84 -0
  53. package/dist/agent/workflow/runtime.d.ts +64 -0
  54. package/dist/agent/workflow/runtime.js +380 -0
  55. package/dist/agent/workflow/sandbox.d.ts +35 -0
  56. package/dist/agent/workflow/sandbox.js +90 -0
  57. package/dist/agent/workflow/snapshot.d.ts +36 -0
  58. package/dist/agent/workflow/snapshot.js +9 -0
  59. package/dist/agent/workflow/structured.d.ts +35 -0
  60. package/dist/agent/workflow/structured.js +79 -0
  61. package/dist/agent/workflow/tool.d.ts +14 -0
  62. package/dist/agent/workflow/tool.js +569 -0
  63. package/dist/agent/workflow/types.d.ts +100 -0
  64. package/dist/agent/workflow/types.js +17 -0
  65. package/dist/agent/worktree.d.ts +38 -0
  66. package/dist/agent/worktree.js +56 -0
  67. package/dist/capabilities/assembler.d.ts +39 -0
  68. package/dist/capabilities/assembler.js +171 -0
  69. package/dist/capabilities/background/agent-task.d.ts +51 -0
  70. package/dist/capabilities/background/agent-task.js +101 -0
  71. package/dist/capabilities/background/command-task.d.ts +43 -0
  72. package/dist/capabilities/background/command-task.js +86 -0
  73. package/dist/capabilities/background/index.d.ts +20 -0
  74. package/dist/capabilities/background/index.js +57 -0
  75. package/dist/capabilities/background/manager.d.ts +194 -0
  76. package/dist/capabilities/background/manager.js +1131 -0
  77. package/dist/capabilities/background/persist-disk.d.ts +17 -0
  78. package/dist/capabilities/background/persist-disk.js +66 -0
  79. package/dist/capabilities/background/persist.d.ts +61 -0
  80. package/dist/capabilities/background/persist.js +117 -0
  81. package/dist/capabilities/background/question-task.d.ts +32 -0
  82. package/dist/capabilities/background/question-task.js +56 -0
  83. package/dist/capabilities/background/registrar.d.ts +12 -0
  84. package/dist/capabilities/background/registrar.js +9 -0
  85. package/dist/capabilities/background/swappable-sink.d.ts +20 -0
  86. package/dist/capabilities/background/swappable-sink.js +20 -0
  87. package/dist/capabilities/background/task.d.ts +114 -0
  88. package/dist/capabilities/background/task.js +20 -0
  89. package/dist/capabilities/background/tools.d.ts +6 -0
  90. package/dist/capabilities/background/tools.js +190 -0
  91. package/dist/capabilities/background/workflow-task.d.ts +48 -0
  92. package/dist/capabilities/background/workflow-task.js +91 -0
  93. package/dist/capabilities/capability-state.d.ts +13 -0
  94. package/dist/capabilities/capability-state.js +37 -0
  95. package/dist/capabilities/capability.d.ts +145 -0
  96. package/dist/capabilities/capability.js +2 -0
  97. package/dist/capabilities/compaction/full.d.ts +27 -0
  98. package/dist/capabilities/compaction/full.js +155 -0
  99. package/dist/capabilities/compaction/index.d.ts +17 -0
  100. package/dist/capabilities/compaction/index.js +145 -0
  101. package/dist/capabilities/compaction/instruction.d.ts +2 -0
  102. package/dist/capabilities/compaction/instruction.js +31 -0
  103. package/dist/capabilities/compaction/micro.d.ts +17 -0
  104. package/dist/capabilities/compaction/micro.js +57 -0
  105. package/dist/capabilities/compaction/service.d.ts +28 -0
  106. package/dist/capabilities/compaction/service.js +52 -0
  107. package/dist/capabilities/compaction/strategy.d.ts +43 -0
  108. package/dist/capabilities/compaction/strategy.js +116 -0
  109. package/dist/capabilities/compaction/tokens.d.ts +5 -0
  110. package/dist/capabilities/compaction/tokens.js +28 -0
  111. package/dist/capabilities/goal/goal-store.d.ts +69 -0
  112. package/dist/capabilities/goal/goal-store.js +172 -0
  113. package/dist/capabilities/goal/index.d.ts +6 -0
  114. package/dist/capabilities/goal/index.js +31 -0
  115. package/dist/capabilities/goal/injector.d.ts +9 -0
  116. package/dist/capabilities/goal/injector.js +79 -0
  117. package/dist/capabilities/goal/tools.d.ts +6 -0
  118. package/dist/capabilities/goal/tools.js +86 -0
  119. package/dist/capabilities/index.d.ts +25 -0
  120. package/dist/capabilities/index.js +22 -0
  121. package/dist/capabilities/injection.d.ts +44 -0
  122. package/dist/capabilities/injection.js +112 -0
  123. package/dist/capabilities/plan/index.d.ts +6 -0
  124. package/dist/capabilities/plan/index.js +25 -0
  125. package/dist/capabilities/plan/injector.d.ts +13 -0
  126. package/dist/capabilities/plan/injector.js +83 -0
  127. package/dist/capabilities/plan/plan-mode.d.ts +38 -0
  128. package/dist/capabilities/plan/plan-mode.js +113 -0
  129. package/dist/capabilities/plan/policies.d.ts +6 -0
  130. package/dist/capabilities/plan/policies.js +89 -0
  131. package/dist/capabilities/plan/tools.d.ts +15 -0
  132. package/dist/capabilities/plan/tools.js +87 -0
  133. package/dist/capabilities/skills/flow-provider.d.ts +6 -0
  134. package/dist/capabilities/skills/flow-provider.js +50 -0
  135. package/dist/capabilities/skills/index.d.ts +43 -0
  136. package/dist/capabilities/skills/index.js +48 -0
  137. package/dist/capabilities/skills/injector.d.ts +11 -0
  138. package/dist/capabilities/skills/injector.js +27 -0
  139. package/dist/capabilities/skills/parser.d.ts +36 -0
  140. package/dist/capabilities/skills/parser.js +334 -0
  141. package/dist/capabilities/skills/registry.d.ts +33 -0
  142. package/dist/capabilities/skills/registry.js +118 -0
  143. package/dist/capabilities/skills/scanner.d.ts +26 -0
  144. package/dist/capabilities/skills/scanner.js +154 -0
  145. package/dist/capabilities/skills/service.d.ts +39 -0
  146. package/dist/capabilities/skills/service.js +68 -0
  147. package/dist/capabilities/skills/skill-tool.d.ts +13 -0
  148. package/dist/capabilities/skills/skill-tool.js +72 -0
  149. package/dist/capabilities/skills/types.d.ts +62 -0
  150. package/dist/capabilities/skills/types.js +26 -0
  151. package/dist/capabilities/task/index.d.ts +23 -0
  152. package/dist/capabilities/task/index.js +38 -0
  153. package/dist/capabilities/task/injector.d.ts +9 -0
  154. package/dist/capabilities/task/injector.js +62 -0
  155. package/dist/capabilities/task/persist-disk.d.ts +19 -0
  156. package/dist/capabilities/task/persist-disk.js +84 -0
  157. package/dist/capabilities/task/persist.d.ts +52 -0
  158. package/dist/capabilities/task/persist.js +84 -0
  159. package/dist/capabilities/task/task-store.d.ts +44 -0
  160. package/dist/capabilities/task/task-store.js +106 -0
  161. package/dist/capabilities/task/tools.d.ts +12 -0
  162. package/dist/capabilities/task/tools.js +164 -0
  163. package/dist/capabilities/todo/index.d.ts +8 -0
  164. package/dist/capabilities/todo/index.js +21 -0
  165. package/dist/capabilities/todo/injector.d.ts +9 -0
  166. package/dist/capabilities/todo/injector.js +68 -0
  167. package/dist/capabilities/todo/todo-store.d.ts +19 -0
  168. package/dist/capabilities/todo/todo-store.js +36 -0
  169. package/dist/capabilities/todo/tools.d.ts +6 -0
  170. package/dist/capabilities/todo/tools.js +70 -0
  171. package/dist/capabilities/tool-provider.d.ts +12 -0
  172. package/dist/capabilities/tool-provider.js +20 -0
  173. package/dist/capabilities/user-hooks/engine.d.ts +22 -0
  174. package/dist/capabilities/user-hooks/engine.js +105 -0
  175. package/dist/capabilities/user-hooks/index.d.ts +13 -0
  176. package/dist/capabilities/user-hooks/index.js +126 -0
  177. package/dist/capabilities/user-hooks/types.d.ts +26 -0
  178. package/dist/capabilities/user-hooks/types.js +19 -0
  179. package/dist/capabilities/workflow/index.d.ts +16 -0
  180. package/dist/capabilities/workflow/index.js +15 -0
  181. package/dist/commands/index.d.ts +31 -0
  182. package/dist/commands/index.js +318 -0
  183. package/dist/config/config-store.d.ts +29 -0
  184. package/dist/config/config-store.js +103 -0
  185. package/dist/config/file-source.d.ts +40 -0
  186. package/dist/config/file-source.js +78 -0
  187. package/dist/config/flags.d.ts +13 -0
  188. package/dist/config/flags.js +25 -0
  189. package/dist/config/index.d.ts +17 -0
  190. package/dist/config/index.js +10 -0
  191. package/dist/config/merge.d.ts +5 -0
  192. package/dist/config/merge.js +57 -0
  193. package/dist/config/model-catalog.d.ts +17 -0
  194. package/dist/config/model-catalog.js +37 -0
  195. package/dist/config/paths.d.ts +31 -0
  196. package/dist/config/paths.js +28 -0
  197. package/dist/config/provider-manager.d.ts +57 -0
  198. package/dist/config/provider-manager.js +344 -0
  199. package/dist/config/resolver.d.ts +40 -0
  200. package/dist/config/resolver.js +52 -0
  201. package/dist/config/schema.d.ts +389 -0
  202. package/dist/config/schema.js +132 -0
  203. package/dist/events/events.d.ts +348 -0
  204. package/dist/events/events.js +146 -0
  205. package/dist/events/index.d.ts +10 -0
  206. package/dist/events/index.js +5 -0
  207. package/dist/events/projection.d.ts +207 -0
  208. package/dist/events/projection.js +438 -0
  209. package/dist/events/publisher.d.ts +48 -0
  210. package/dist/events/publisher.js +404 -0
  211. package/dist/events/redacting-sink.d.ts +11 -0
  212. package/dist/events/redacting-sink.js +31 -0
  213. package/dist/home.d.ts +16 -0
  214. package/dist/home.js +20 -0
  215. package/dist/index.d.ts +22 -0
  216. package/dist/index.js +22 -0
  217. package/dist/internal.d.ts +33 -0
  218. package/dist/internal.js +29 -0
  219. package/dist/llm/auth.d.ts +22 -0
  220. package/dist/llm/auth.js +112 -0
  221. package/dist/llm/capability.d.ts +13 -0
  222. package/dist/llm/capability.js +45 -0
  223. package/dist/llm/define-model.d.ts +110 -0
  224. package/dist/llm/define-model.js +252 -0
  225. package/dist/llm/errors.d.ts +33 -0
  226. package/dist/llm/errors.js +154 -0
  227. package/dist/llm/index.d.ts +14 -0
  228. package/dist/llm/index.js +8 -0
  229. package/dist/llm/model.d.ts +43 -0
  230. package/dist/llm/model.js +9 -0
  231. package/dist/llm/retry.d.ts +35 -0
  232. package/dist/llm/retry.js +160 -0
  233. package/dist/llm/runtime.d.ts +25 -0
  234. package/dist/llm/runtime.js +38 -0
  235. package/dist/logging/diagnostics.d.ts +21 -0
  236. package/dist/logging/diagnostics.js +46 -0
  237. package/dist/logging/index.d.ts +11 -0
  238. package/dist/logging/index.js +7 -0
  239. package/dist/logging/logger.d.ts +25 -0
  240. package/dist/logging/logger.js +54 -0
  241. package/dist/logging/paths.d.ts +11 -0
  242. package/dist/logging/paths.js +20 -0
  243. package/dist/logging/policy.d.ts +5 -0
  244. package/dist/logging/policy.js +19 -0
  245. package/dist/logging/redact.d.ts +10 -0
  246. package/dist/logging/redact.js +95 -0
  247. package/dist/logging/sinks.d.ts +67 -0
  248. package/dist/logging/sinks.js +117 -0
  249. package/dist/loop/context.d.ts +69 -0
  250. package/dist/loop/context.js +129 -0
  251. package/dist/loop/errors.d.ts +8 -0
  252. package/dist/loop/errors.js +27 -0
  253. package/dist/loop/events.d.ts +14 -0
  254. package/dist/loop/events.js +2 -0
  255. package/dist/loop/index.d.ts +10 -0
  256. package/dist/loop/index.js +7 -0
  257. package/dist/loop/interruption.d.ts +118 -0
  258. package/dist/loop/interruption.js +191 -0
  259. package/dist/loop/run-turn.d.ts +54 -0
  260. package/dist/loop/run-turn.js +203 -0
  261. package/dist/loop/scheduler.d.ts +18 -0
  262. package/dist/loop/scheduler.js +71 -0
  263. package/dist/loop/steer.d.ts +122 -0
  264. package/dist/loop/steer.js +209 -0
  265. package/dist/loop/tool-call.d.ts +41 -0
  266. package/dist/loop/tool-call.js +326 -0
  267. package/dist/loop/turn-step.d.ts +57 -0
  268. package/dist/loop/turn-step.js +298 -0
  269. package/dist/loop/types.d.ts +217 -0
  270. package/dist/loop/types.js +2 -0
  271. package/dist/loop/usage.d.ts +6 -0
  272. package/dist/loop/usage.js +44 -0
  273. package/dist/mcp/auth-tool.d.ts +12 -0
  274. package/dist/mcp/auth-tool.js +92 -0
  275. package/dist/mcp/capability.d.ts +7 -0
  276. package/dist/mcp/capability.js +91 -0
  277. package/dist/mcp/config-loader.d.ts +28 -0
  278. package/dist/mcp/config-loader.js +115 -0
  279. package/dist/mcp/filter.d.ts +18 -0
  280. package/dist/mcp/filter.js +35 -0
  281. package/dist/mcp/index.d.ts +23 -0
  282. package/dist/mcp/index.js +13 -0
  283. package/dist/mcp/manager.d.ts +51 -0
  284. package/dist/mcp/manager.js +412 -0
  285. package/dist/mcp/mock-transport.d.ts +40 -0
  286. package/dist/mcp/mock-transport.js +68 -0
  287. package/dist/mcp/oauth/callback-server.d.ts +14 -0
  288. package/dist/mcp/oauth/callback-server.js +122 -0
  289. package/dist/mcp/oauth/index.d.ts +9 -0
  290. package/dist/mcp/oauth/index.js +5 -0
  291. package/dist/mcp/oauth/provider.d.ts +39 -0
  292. package/dist/mcp/oauth/provider.js +121 -0
  293. package/dist/mcp/oauth/service.d.ts +34 -0
  294. package/dist/mcp/oauth/service.js +130 -0
  295. package/dist/mcp/oauth/store.d.ts +40 -0
  296. package/dist/mcp/oauth/store.js +134 -0
  297. package/dist/mcp/output.d.ts +12 -0
  298. package/dist/mcp/output.js +110 -0
  299. package/dist/mcp/provider.d.ts +7 -0
  300. package/dist/mcp/provider.js +56 -0
  301. package/dist/mcp/sdk-transport.d.ts +25 -0
  302. package/dist/mcp/sdk-transport.js +228 -0
  303. package/dist/mcp/server.d.ts +77 -0
  304. package/dist/mcp/server.js +120 -0
  305. package/dist/mcp/tool-naming.d.ts +4 -0
  306. package/dist/mcp/tool-naming.js +26 -0
  307. package/dist/mcp/types.d.ts +75 -0
  308. package/dist/mcp/types.js +2 -0
  309. package/dist/net/index.d.ts +3 -0
  310. package/dist/net/index.js +2 -0
  311. package/dist/net/proxy.d.ts +16 -0
  312. package/dist/net/proxy.js +42 -0
  313. package/dist/permission/auto-approver/index.d.ts +3 -0
  314. package/dist/permission/auto-approver/index.js +3 -0
  315. package/dist/permission/auto-approver/llm-auto-approver.d.ts +53 -0
  316. package/dist/permission/auto-approver/llm-auto-approver.js +122 -0
  317. package/dist/permission/auto-approver/prompts-data.d.ts +9 -0
  318. package/dist/permission/auto-approver/prompts-data.js +155 -0
  319. package/dist/permission/auto-approver/prompts.d.ts +18 -0
  320. package/dist/permission/auto-approver/prompts.js +40 -0
  321. package/dist/permission/auto-approver/transcript.d.ts +22 -0
  322. package/dist/permission/auto-approver/transcript.js +75 -0
  323. package/dist/permission/auto-approver/xml.d.ts +5 -0
  324. package/dist/permission/auto-approver/xml.js +25 -0
  325. package/dist/permission/index.d.ts +7 -0
  326. package/dist/permission/index.js +5 -0
  327. package/dist/permission/manager.d.ts +74 -0
  328. package/dist/permission/manager.js +162 -0
  329. package/dist/permission/matches-rule.d.ts +27 -0
  330. package/dist/permission/matches-rule.js +54 -0
  331. package/dist/permission/policies.d.ts +14 -0
  332. package/dist/permission/policies.js +233 -0
  333. package/dist/permission/types.d.ts +84 -0
  334. package/dist/permission/types.js +2 -0
  335. package/dist/plugins/archive.d.ts +3 -0
  336. package/dist/plugins/archive.js +58 -0
  337. package/dist/plugins/github-resolver.d.ts +13 -0
  338. package/dist/plugins/github-resolver.js +20 -0
  339. package/dist/plugins/hooks.d.ts +28 -0
  340. package/dist/plugins/hooks.js +296 -0
  341. package/dist/plugins/index.d.ts +23 -0
  342. package/dist/plugins/index.js +23 -0
  343. package/dist/plugins/injector.d.ts +11 -0
  344. package/dist/plugins/injector.js +32 -0
  345. package/dist/plugins/manager.d.ts +37 -0
  346. package/dist/plugins/manager.js +330 -0
  347. package/dist/plugins/manifest.d.ts +9 -0
  348. package/dist/plugins/manifest.js +234 -0
  349. package/dist/plugins/marketplace.d.ts +85 -0
  350. package/dist/plugins/marketplace.js +205 -0
  351. package/dist/plugins/source.d.ts +23 -0
  352. package/dist/plugins/source.js +87 -0
  353. package/dist/plugins/store.d.ts +20 -0
  354. package/dist/plugins/store.js +30 -0
  355. package/dist/plugins/types.d.ts +118 -0
  356. package/dist/plugins/types.js +5 -0
  357. package/dist/protocol/index.d.ts +4 -0
  358. package/dist/protocol/index.js +2 -0
  359. package/dist/protocol/tool-schema.d.ts +6 -0
  360. package/dist/protocol/tool-schema.js +2 -0
  361. package/dist/store/blob-store.d.ts +45 -0
  362. package/dist/store/blob-store.js +120 -0
  363. package/dist/store/catalog-store.d.ts +32 -0
  364. package/dist/store/catalog-store.js +73 -0
  365. package/dist/store/disk-store.d.ts +58 -0
  366. package/dist/store/disk-store.js +369 -0
  367. package/dist/store/index.d.ts +23 -0
  368. package/dist/store/index.js +15 -0
  369. package/dist/store/lock.d.ts +86 -0
  370. package/dist/store/lock.js +104 -0
  371. package/dist/store/log-store.d.ts +89 -0
  372. package/dist/store/log-store.js +296 -0
  373. package/dist/store/migrate.d.ts +26 -0
  374. package/dist/store/migrate.js +32 -0
  375. package/dist/store/origin.d.ts +89 -0
  376. package/dist/store/origin.js +16 -0
  377. package/dist/store/pg.d.ts +90 -0
  378. package/dist/store/pg.js +344 -0
  379. package/dist/store/redacting-store.d.ts +21 -0
  380. package/dist/store/redacting-store.js +46 -0
  381. package/dist/store/redis.d.ts +89 -0
  382. package/dist/store/redis.js +370 -0
  383. package/dist/store/repository.d.ts +150 -0
  384. package/dist/store/repository.js +508 -0
  385. package/dist/store/session-catalog.d.ts +32 -0
  386. package/dist/store/session-catalog.js +117 -0
  387. package/dist/store/storage.d.ts +27 -0
  388. package/dist/store/storage.js +54 -0
  389. package/dist/store/store.d.ts +262 -0
  390. package/dist/store/store.js +129 -0
  391. package/dist/store/workdir-key.d.ts +4 -0
  392. package/dist/store/workdir-key.js +28 -0
  393. package/dist/tool/access.d.ts +37 -0
  394. package/dist/tool/access.js +79 -0
  395. package/dist/tool/ask.d.ts +22 -0
  396. package/dist/tool/ask.js +38 -0
  397. package/dist/tool/background.d.ts +109 -0
  398. package/dist/tool/background.js +39 -0
  399. package/dist/tool/builtin/ask-user-question.d.ts +2 -0
  400. package/dist/tool/builtin/ask-user-question.js +175 -0
  401. package/dist/tool/builtin/bash.d.ts +2 -0
  402. package/dist/tool/builtin/bash.js +407 -0
  403. package/dist/tool/builtin/edit.d.ts +2 -0
  404. package/dist/tool/builtin/edit.js +202 -0
  405. package/dist/tool/builtin/glob.d.ts +3 -0
  406. package/dist/tool/builtin/glob.js +260 -0
  407. package/dist/tool/builtin/grep.d.ts +2 -0
  408. package/dist/tool/builtin/grep.js +574 -0
  409. package/dist/tool/builtin/line-endings.d.ts +10 -0
  410. package/dist/tool/builtin/line-endings.js +41 -0
  411. package/dist/tool/builtin/read.d.ts +28 -0
  412. package/dist/tool/builtin/read.js +498 -0
  413. package/dist/tool/builtin/write.d.ts +2 -0
  414. package/dist/tool/builtin/write.js +179 -0
  415. package/dist/tool/define.d.ts +46 -0
  416. package/dist/tool/define.js +45 -0
  417. package/dist/tool/file-freshness.d.ts +81 -0
  418. package/dist/tool/file-freshness.js +67 -0
  419. package/dist/tool/filesystem-tools.d.ts +16 -0
  420. package/dist/tool/filesystem-tools.js +19 -0
  421. package/dist/tool/git-context.d.ts +20 -0
  422. package/dist/tool/git-context.js +114 -0
  423. package/dist/tool/index.d.ts +37 -0
  424. package/dist/tool/index.js +34 -0
  425. package/dist/tool/machine-base.d.ts +138 -0
  426. package/dist/tool/machine-base.js +388 -0
  427. package/dist/tool/machine-local.d.ts +35 -0
  428. package/dist/tool/machine-local.js +316 -0
  429. package/dist/tool/machine-null.d.ts +36 -0
  430. package/dist/tool/machine-null.js +64 -0
  431. package/dist/tool/machine-ssh.d.ts +86 -0
  432. package/dist/tool/machine-ssh.js +576 -0
  433. package/dist/tool/machine.d.ts +333 -0
  434. package/dist/tool/machine.js +15 -0
  435. package/dist/tool/policies/path-access.d.ts +48 -0
  436. package/dist/tool/policies/path-access.js +186 -0
  437. package/dist/tool/policies/sensitive.d.ts +3 -0
  438. package/dist/tool/policies/sensitive.js +60 -0
  439. package/dist/tool/questions.d.ts +40 -0
  440. package/dist/tool/questions.js +8 -0
  441. package/dist/tool/search/activation.d.ts +13 -0
  442. package/dist/tool/search/activation.js +31 -0
  443. package/dist/tool/search/deferral.d.ts +37 -0
  444. package/dist/tool/search/deferral.js +128 -0
  445. package/dist/tool/search/search-tool.d.ts +9 -0
  446. package/dist/tool/search/search-tool.js +62 -0
  447. package/dist/tool/shell-env.d.ts +9 -0
  448. package/dist/tool/shell-env.js +34 -0
  449. package/dist/tool/support/bash-destructive.d.ts +24 -0
  450. package/dist/tool/support/bash-destructive.js +63 -0
  451. package/dist/tool/support/bash-paths.d.ts +7 -0
  452. package/dist/tool/support/bash-paths.js +247 -0
  453. package/dist/tool/support/bash-read-only.d.ts +8 -0
  454. package/dist/tool/support/bash-read-only.js +165 -0
  455. package/dist/tool/support/bash-rule-match.d.ts +20 -0
  456. package/dist/tool/support/bash-rule-match.js +191 -0
  457. package/dist/tool/support/file-type.d.ts +10 -0
  458. package/dist/tool/support/file-type.js +149 -0
  459. package/dist/tool/support/git-worktree.d.ts +10 -0
  460. package/dist/tool/support/git-worktree.js +63 -0
  461. package/dist/tool/support/image-compress.d.ts +69 -0
  462. package/dist/tool/support/image-compress.js +265 -0
  463. package/dist/tool/support/machine-ops.d.ts +34 -0
  464. package/dist/tool/support/machine-ops.js +34 -0
  465. package/dist/tool/support/path-glob-match.d.ts +12 -0
  466. package/dist/tool/support/path-glob-match.js +84 -0
  467. package/dist/tool/support/result-builder.d.ts +27 -0
  468. package/dist/tool/support/result-builder.js +108 -0
  469. package/dist/tool/support/rg-locator.d.ts +20 -0
  470. package/dist/tool/support/rg-locator.js +42 -0
  471. package/dist/tool/support/ripgrep-run.d.ts +65 -0
  472. package/dist/tool/support/ripgrep-run.js +40 -0
  473. package/dist/tool/support/rule-match.d.ts +6 -0
  474. package/dist/tool/support/rule-match.js +23 -0
  475. package/dist/tool/support/tool-path.d.ts +8 -0
  476. package/dist/tool/support/tool-path.js +28 -0
  477. package/dist/tool/support/workspace.d.ts +5 -0
  478. package/dist/tool/support/workspace.js +2 -0
  479. package/dist/tool/types.d.ts +131 -0
  480. package/dist/tool/types.js +2 -0
  481. package/dist/tool/web/fetch-url.d.ts +4 -0
  482. package/dist/tool/web/fetch-url.js +61 -0
  483. package/dist/tool/web/index.d.ts +11 -0
  484. package/dist/tool/web/index.js +7 -0
  485. package/dist/tool/web/providers/direct-fetch.d.ts +33 -0
  486. package/dist/tool/web/providers/direct-fetch.js +198 -0
  487. package/dist/tool/web/providers/firecrawl.d.ts +16 -0
  488. package/dist/tool/web/providers/firecrawl.js +59 -0
  489. package/dist/tool/web/providers/tavily.d.ts +14 -0
  490. package/dist/tool/web/providers/tavily.js +43 -0
  491. package/dist/tool/web/types.d.ts +41 -0
  492. package/dist/tool/web/types.js +7 -0
  493. package/dist/tool/web/web-search.d.ts +4 -0
  494. package/dist/tool/web/web-search.js +68 -0
  495. package/dist/tool/workspace-spec.d.ts +74 -0
  496. package/dist/tool/workspace-spec.js +177 -0
  497. package/dist/tracing/bridge.d.ts +7 -0
  498. package/dist/tracing/bridge.js +171 -0
  499. package/dist/tracing/index.d.ts +9 -0
  500. package/dist/tracing/index.js +5 -0
  501. package/dist/tracing/otel.d.ts +38 -0
  502. package/dist/tracing/otel.js +221 -0
  503. package/dist/tracing/processor.d.ts +47 -0
  504. package/dist/tracing/processor.js +94 -0
  505. package/dist/tracing/spans.d.ts +94 -0
  506. package/dist/tracing/spans.js +56 -0
  507. package/dist/ui/ai-sdk.d.ts +114 -0
  508. package/dist/ui/ai-sdk.js +175 -0
  509. package/dist/ui/index.d.ts +2 -0
  510. package/dist/ui/index.js +2 -0
  511. package/package.json +101 -0
@@ -0,0 +1,407 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { posix, win32 } from "node:path";
3
+ import { z } from "zod";
4
+ import { defineTool } from "../define.js";
5
+ import { ToolAccesses } from "../access.js";
6
+ import { ToolResultBuilder } from "../support/result-builder.js";
7
+ import { matchesBashRule } from "../support/bash-rule-match.js";
8
+ import { extractBashPaths } from "../support/bash-paths.js";
9
+ import { destructiveWarning } from "../support/bash-destructive.js";
10
+ import { escapeRuleSubjectLiteral } from "../support/rule-match.js";
11
+ import { nonInteractiveShellEnv } from "../shell-env.js";
12
+ import { runCommandInline } from "../background.js";
13
+ import { OPERON_HOME_DIRNAME } from "../../home.js";
14
+ import { isWithinDirectory } from "../policies/path-access.js";
15
+ const MS_PER_SECOND = 1000;
16
+ // 60s was short enough that builds and test suites routinely needed an explicit
17
+ // `timeout`, and each guess that came in low cost a full re-run.
18
+ const DEFAULT_TIMEOUT_S = 120;
19
+ const MAX_TIMEOUT_S = 10 * 60;
20
+ const BashInput = z.object({
21
+ command: z.string().min(1, "Command cannot be empty.").describe("The command to execute."),
22
+ cwd: z
23
+ .string()
24
+ .optional()
25
+ .describe("The working directory in which to run the command. When omitted, the command runs in the session's working directory."),
26
+ timeout: z
27
+ .number()
28
+ .int()
29
+ .positive()
30
+ .max(MAX_TIMEOUT_S)
31
+ .optional()
32
+ .describe(`Optional timeout in seconds for the command to execute. Default ${String(DEFAULT_TIMEOUT_S)}s, max ${String(MAX_TIMEOUT_S)}s.`),
33
+ run_in_background: z.boolean().optional().describe("Whether to run the command as a background task."),
34
+ });
35
+ const BASH_DESCRIPTION = [
36
+ "Execute a shell command. Use this for shell semantics — pipes, env, processes, git, package managers, build/test runners, anything genuinely shell-specific or multi-step.",
37
+ "",
38
+ "**Translate these to a dedicated tool instead:**",
39
+ "- `cat` / `head` / `tail` (known path) -> `Read`",
40
+ "- `sed` / `awk` (in-place edit) -> `Edit`",
41
+ "- `echo > file` / `cat <<EOF` -> `Write`",
42
+ "- `find` / recursive `ls` to locate files by name pattern -> `Glob` (plain `ls <known-directory>` is fine for listing a directory)",
43
+ "- `grep` / `rg` (search file contents) -> `Grep`",
44
+ "- `echo` / `printf` (talk to the user) -> just output text directly",
45
+ "",
46
+ "The dedicated tools render in the per-tool permission UI and keep raw stdout out of the conversation; that is why they are worth reaching for whenever one fits.",
47
+ "",
48
+ "**Output:**",
49
+ "The stdout and stderr will be combined and returned as a string. The output may be truncated if it is too long. If the command failed, the output will end with a `Command failed with exit code: N` line stating the non-zero exit code.",
50
+ "",
51
+ "If `run_in_background=true`, the command will be started as a background task and this tool will return a task ID instead of waiting for command completion. You will be automatically notified when the task completes. Use BackgroundOutput(task_id) for a non-blocking status/output snapshot, and BackgroundStop(task_id) only if the task must be cancelled. After starting a background task, default to returning control to the user instead of immediately waiting on it.",
52
+ "",
53
+ "**Guidelines for safety and security:**",
54
+ "- Each shell tool call will be executed in a fresh shell environment. The shell variables, current working directory changes, and the shell history is not preserved between calls.",
55
+ `- The tool call will return after the command is finished. You shall not use this tool to execute an interactive command or a command that may run forever. For possibly long-running foreground commands, set the \`timeout\` argument in seconds. Foreground commands default to ${String(DEFAULT_TIMEOUT_S)}s and allow up to ${String(MAX_TIMEOUT_S)}s.`,
56
+ "- Avoid using `..` to access files or directories outside of the working directory.",
57
+ "- Avoid modifying files outside of the working directory unless explicitly instructed to do so.",
58
+ "- Never run commands that require superuser privileges unless explicitly instructed to do so.",
59
+ "",
60
+ "**Guidelines for efficiency:**",
61
+ "- For multiple related commands, use `&&` to chain them in a single call, e.g. `cd /path && ls -la`",
62
+ "- Use `;` to run commands sequentially regardless of success/failure",
63
+ "- Use `||` for conditional execution (run second command only if first fails)",
64
+ "- Use pipe operations (`|`) and redirections (`>`, `>>`) to chain input and output between commands",
65
+ "- Always quote file paths containing spaces with double quotes (e.g., cd \"/path with spaces/\")",
66
+ "- Compose multi-step logic in a single call with `if` / `case` / `for` / `while` control flows.",
67
+ "- Prefer `run_in_background=true` for long-running builds, tests, watchers, or servers when you need the conversation to continue before the command finishes.",
68
+ "",
69
+ "**Commands available:**",
70
+ "The following common command categories are usually available. Availability still depends on the host, so when in doubt run `which <command>` first to confirm a command exists before relying on it.",
71
+ "- Navigation and inspection: `ls`, `pwd`, `cd`, `stat`, `file`, `du`, `df`, `tree`",
72
+ "- File and directory management: `cp`, `mv`, `rm`, `mkdir`, `touch`, `ln`, `chmod`, `chown`",
73
+ "- Text and data processing: `wc`, `sort`, `uniq`, `cut`, `tr`, `diff`, `xargs`",
74
+ "- Archives and compression: `tar`, `gzip`, `gunzip`, `zip`, `unzip`",
75
+ "- Networking and transfer: `curl`, `wget`, `ping`, `ssh`, `scp`",
76
+ "- Version control: `git`",
77
+ "- Process and system: `ps`, `kill`, `top`, `env`, `date`, `uname`, `whoami`",
78
+ "- Language and package toolchains: `node`, `npm`, `pnpm`, `yarn`, `python`, `pip` (use whichever the project actually relies on)",
79
+ ].join("\n");
80
+ function normalizeTimeoutMs(timeout) {
81
+ return Math.min(timeout ?? DEFAULT_TIMEOUT_S, MAX_TIMEOUT_S) * MS_PER_SECOND;
82
+ }
83
+ export const bashTool = defineTool({
84
+ name: "Bash",
85
+ description: BASH_DESCRIPTION,
86
+ params: BashInput,
87
+ // The command is the only security-relevant field; cwd/timeout/background don't change
88
+ // what the action does — so the projection is just `input.command`.
89
+ toAutoApprovalInput: (args) => args.command,
90
+ resolve(args, ctx) {
91
+ const preview = args.command.length > 50 ? `${args.command.slice(0, 50)}…` : args.command;
92
+ return {
93
+ // What the command is read to touch. Best-effort by nature (see bash-paths.ts): this is
94
+ // what lets the sensitive-file / git-control-path / write-outside-cwd policies see a Bash
95
+ // call at all, which they otherwise skip entirely for want of anything to inspect.
96
+ accesses: commandAccesses(args, ctx.machine),
97
+ // `warning` is advisory only — nothing branches on it. It rides on the plan so whatever
98
+ // renders the approval can show the caller why this command deserves a second look.
99
+ display: {
100
+ title: `Running: ${preview}`,
101
+ command: args.command,
102
+ ...(destructiveWarning(args.command) !== undefined ? { warning: destructiveWarning(args.command) } : {}),
103
+ },
104
+ approvalRule: `Bash(${escapeRuleSubjectLiteral(args.command)})`,
105
+ matchesRule: (ruleArgs) => matchesBashRule(ruleArgs, args.command),
106
+ run: (runCtx) => execute(args, runCtx.machine, runCtx.signal, runCtx.background, runCtx.onUpdate, runCtx.detachSignal, runCtx.address, runCtx.toolCallId),
107
+ };
108
+ },
109
+ });
110
+ /**
111
+ * File accesses the command is read to perform, as absolute paths.
112
+ *
113
+ * Absolute matters: the policies compare against cwd with `isWithinDirectory`, and a bare
114
+ * `notes.txt` would compare false and be reported as an out-of-workspace write. `~` is expanded
115
+ * for the same reason. Anything that cannot be resolved is dropped rather than guessed at —
116
+ * see bash-paths.ts on why silence is the correct failure mode here.
117
+ */
118
+ function commandAccesses(args, machine) {
119
+ const found = extractBashPaths(args.command);
120
+ if (found.length === 0)
121
+ return ToolAccesses.none();
122
+ const pathClass = machine.pathClass();
123
+ const base = args.cwd ?? machine.getcwd();
124
+ let home;
125
+ try {
126
+ home = machine.gethome();
127
+ }
128
+ catch {
129
+ home = undefined;
130
+ }
131
+ const accesses = [];
132
+ const seen = new Set();
133
+ for (const entry of found) {
134
+ const absolute = toAbsolute(entry.path, base, home, pathClass);
135
+ if (absolute === undefined)
136
+ continue;
137
+ const key = `${entry.operation}:${absolute}`;
138
+ if (seen.has(key))
139
+ continue;
140
+ seen.add(key);
141
+ accesses.push({ kind: "file", operation: entry.operation, path: absolute });
142
+ }
143
+ return accesses;
144
+ }
145
+ function toAbsolute(path, base, home, pathClass) {
146
+ const p = pathClass === "win32" ? win32 : posix;
147
+ let value = path;
148
+ if (value === "~" || value.startsWith("~/")) {
149
+ if (home === undefined || home.length === 0)
150
+ return undefined;
151
+ value = value === "~" ? home : p.join(home, value.slice(2));
152
+ }
153
+ // A `~user` form names someone else's home, which we cannot resolve without the passwd db.
154
+ if (value.startsWith("~"))
155
+ return undefined;
156
+ if (p.isAbsolute(value))
157
+ return p.normalize(value);
158
+ if (!p.isAbsolute(base))
159
+ return undefined;
160
+ return p.normalize(p.join(base, value));
161
+ }
162
+ /** The argv + env overrides every bash invocation shares, whichever path ends up running it. */
163
+ function shellInvocation(machine, effectiveCwd, command) {
164
+ const isWindowsBash = machine.osEnv.osKind === "Windows";
165
+ const shellCwd = isWindowsBash ? windowsPathToPosixPath(effectiveCwd) : effectiveCwd;
166
+ return {
167
+ argv: [machine.osEnv.shellPath, "-c", `cd ${shellQuote(shellCwd)} && ${command}`],
168
+ // Non-interactive overrides only; the machine layers these over its ambient env (PATH +
169
+ // proxy vars ride through), so we don't ship the whole process environment downstream.
170
+ env: nonInteractiveShellEnv({ shellPath: machine.osEnv.shellPath }),
171
+ };
172
+ }
173
+ /** The same invocation, packaged for a spawner that owns the run's lifecycle (background,
174
+ * or foreground-attached-then-detachable). No timeout: those runs are bounded by the
175
+ * spawner's own foreground timer, or not at all once detached. */
176
+ function commandStarter(machine, effectiveCwd, command) {
177
+ const { argv, env } = shellInvocation(machine, effectiveCwd, command);
178
+ return ({ signal, onOutput }) => machine.run(argv, {
179
+ env,
180
+ signal,
181
+ ...(onOutput !== undefined ? { onOutput: (chunk) => onOutput(chunk.data) } : {}),
182
+ });
183
+ }
184
+ async function execute(args, machine, signal, background, onUpdate, detachSignal, parentAddress, toolCallId) {
185
+ if (signal.aborted)
186
+ return errorResult("Aborted before command started");
187
+ if (args.command.length === 0)
188
+ return errorResult("Command cannot be empty.");
189
+ const isWindowsBash = machine.osEnv.osKind === "Windows";
190
+ const command = isWindowsBash ? rewriteWindowsNullRedirect(args.command) : args.command;
191
+ if (args.run_in_background) {
192
+ if (background === undefined) {
193
+ return errorResult("Background execution is not available for this agent (Task tools not enabled).");
194
+ }
195
+ // Redirect output to a Machine log file: the OS captures the stream (survives this
196
+ // process; detached commands keep logging), and the file — not process memory — is
197
+ // the output's home. The ack carries the path so it stays readable across restarts.
198
+ let logPath;
199
+ try {
200
+ logPath = await prepareBackgroundLog(machine);
201
+ }
202
+ catch (error) {
203
+ return errorResult(error instanceof Error ? error.message : String(error));
204
+ }
205
+ const wrapped = `{ ${command}\n} > ${shellQuote(logPath)} 2>&1`;
206
+ const preview = args.command.length > 50 ? `${args.command.slice(0, 50)}…` : args.command;
207
+ const taskId = background.spawnCommand(commandStarter(machine, args.cwd ?? machine.getcwd(), wrapped), args.command, `bash: ${preview}`, {
208
+ logPath,
209
+ machine,
210
+ ...(parentAddress !== undefined ? { parentAddress } : {}),
211
+ ...(toolCallId !== undefined ? { toolCallId } : {}),
212
+ });
213
+ return {
214
+ content: [
215
+ {
216
+ type: "text",
217
+ text: `Started background task ${taskId}.\n` +
218
+ `output_log: ${logPath}\n` +
219
+ "Use BackgroundOutput(task_id) to read its output and BackgroundStop(task_id) to stop it." +
220
+ " The output log file stays readable (e.g. with Read) even after this session's process exits.",
221
+ },
222
+ ],
223
+ };
224
+ }
225
+ const timeoutMs = normalizeTimeoutMs(args.timeout);
226
+ // ONE foreground path. Which driver runs it is a detail of what this deployment has: the
227
+ // background capability's, which can hand a still-running command over to a task mid-flight,
228
+ // or the inline default, which cannot. Branching in the TOOL instead — as this used to —
229
+ // means two implementations of "run a command in the foreground", and they drift.
230
+ const attachedDriver = background?.runCommandAttached?.bind(background);
231
+ const usesAttachedDriver = attachedDriver !== undefined;
232
+ // Every command owned by an attached/background driver is file-backed from its first byte,
233
+ // regardless of backend. The standard loop also supplies detachSignal, but storage does not
234
+ // depend on that routing seam: passing BackgroundManager alone is enough to select one
235
+ // canonical durable output path.
236
+ // Local machines can do this cheaply, and sandbox/remote machines redirect inside their own
237
+ // shell then expose the growing file through Machine.readBytes. Detach consequently changes
238
+ // lifecycle ownership only; it never has to migrate an already-running pipe into memory.
239
+ let logPath;
240
+ if (usesAttachedDriver) {
241
+ try {
242
+ logPath = await prepareBackgroundLog(machine);
243
+ }
244
+ catch {
245
+ // The manager's attached driver refuses pipe-only commands (assertDurableOutput), so a
246
+ // machine that cannot host the log (unwritable home, quota) degrades to the inline pipe
247
+ // driver below: the command still runs, it just cannot be detached into a task.
248
+ logPath = undefined;
249
+ }
250
+ }
251
+ const drive = attachedDriver !== undefined && logPath !== undefined
252
+ ? attachedDriver
253
+ : (start, _c, _d, opts) => runCommandInline(start, opts);
254
+ const fgCommand = logPath === undefined
255
+ ? command
256
+ : `{ ${command}\n} > ${shellQuote(logPath)} 2>&1`;
257
+ const preview = args.command.length > 50 ? `${args.command.slice(0, 50)}…` : args.command;
258
+ const builder = new ToolResultBuilder();
259
+ const start = commandStarter(machine, args.cwd ?? machine.getcwd(), fgCommand);
260
+ let outcome;
261
+ try {
262
+ outcome = await drive(start, args.command, `bash: ${preview}`, {
263
+ foregroundSignal: signal,
264
+ ...(detachSignal !== undefined ? { detachSignal } : {}),
265
+ foregroundTimeoutMs: timeoutMs,
266
+ // Attached mode passes logPath+machine so the driver knows WHERE this command's output
267
+ // lives; with the live tap below it tails that file while we stay attached, and stops
268
+ // the moment we detach. The no-manager inline path omits them and receives the pipe.
269
+ ...(logPath !== undefined ? { logPath, machine } : {}),
270
+ ...(parentAddress !== undefined ? { parentAddress } : {}),
271
+ ...(toolCallId !== undefined ? { toolCallId } : {}),
272
+ onLive: (chunk) => {
273
+ builder.write(chunk);
274
+ onUpdate?.({ kind: "stdout", text: chunk });
275
+ },
276
+ // Fired by the driver once the run has lasted long enough to be worth offering — not at
277
+ // start, so a command that returns in milliseconds never flashes the offer.
278
+ onDetachable: () => onUpdate?.({ kind: "custom", customKind: "detachable" }),
279
+ });
280
+ }
281
+ catch (error) {
282
+ return errorResult(error instanceof Error ? error.message : String(error));
283
+ }
284
+ if (outcome.kind === "detached") {
285
+ // Correlation link: the UI re-subscribes this card from tool.progress to BackgroundOutput.
286
+ onUpdate?.({ kind: "custom", customKind: "detached", customData: { taskId: outcome.taskId } });
287
+ return {
288
+ content: [
289
+ {
290
+ type: "text",
291
+ text: `Moved to background task ${outcome.taskId}.\n` +
292
+ (logPath !== undefined ? `output_log: ${logPath}\n` : "") +
293
+ "Use BackgroundOutput(task_id) to read its output and BackgroundStop(task_id) to stop it." +
294
+ (logPath !== undefined ? " The output log file stays readable (e.g. with Read) even after this session's process exits." : ""),
295
+ },
296
+ ],
297
+ details: { movedToBackground: true, backgroundTaskId: outcome.taskId },
298
+ };
299
+ }
300
+ const label = timeoutMs % 1000 === 0 ? `${String(timeoutMs / 1000)}s` : `${String(timeoutMs)}ms`;
301
+ // In file mode the whole output was ALSO written to a log file. When the result had to drop
302
+ // some of it, say where the rest is — the bytes exist and are readable, and a bare "output is
303
+ // truncated" would strand the model one step from the answer. Only on truncation: naming the
304
+ // file every time would push the model to Read what it was already handed in full.
305
+ // The path must not be the last thing in the sentence: `ok()` appends a full stop to a
306
+ // message that lacks one, and it would land on the filename.
307
+ const overflow = logPath !== undefined && builder.truncated
308
+ ? `\nThe untruncated output was also written to ${logPath} — Read that file to see what was dropped.`
309
+ : "";
310
+ switch (outcome.status) {
311
+ case "completed":
312
+ return builder.ok(`Command executed successfully.${overflow}`);
313
+ case "timed_out":
314
+ return builder.error(`Command killed by timeout (${label})${overflow}`, { brief: `Killed by timeout (${label})` });
315
+ case "killed":
316
+ return builder.error(`Interrupted by user${overflow}`, { brief: "Interrupted by user" });
317
+ case "failed": {
318
+ const code = outcome.exitCode === null ? "unknown" : String(outcome.exitCode);
319
+ if (builder.nChars === 0)
320
+ builder.write(`Process exited with code ${code}`);
321
+ return builder.error(`Command failed with exit code: ${code}.${overflow}`, { brief: `Failed with exit code: ${code}` });
322
+ }
323
+ }
324
+ }
325
+ function shellQuote(s) {
326
+ return `'${s.replaceAll("'", "'\\''")}'`;
327
+ }
328
+ /** `<dir>/bash-<random>.log`; undefined = nowhere safe to put durable background output. */
329
+ function backgroundLogPath(machine) {
330
+ const dir = backgroundLogDir(machine);
331
+ // Compose with '/' — both posix hosts and win32 Git-bash shells accept it.
332
+ return dir === undefined ? undefined : `${dir}/bash-${randomBytes(4).toString("hex")}.log`;
333
+ }
334
+ /** Allocate the canonical command log before the user's process starts. The shell only owns
335
+ * appending command output; directory/file setup failures therefore fail the tool cleanly
336
+ * instead of escaping through an uncaptured outer stderr stream. */
337
+ async function prepareBackgroundLog(machine) {
338
+ const logPath = backgroundLogPath(machine);
339
+ if (logPath === undefined) {
340
+ throw new Error("Background Bash execution requires a durable output log, but this machine has no safe task-log directory.");
341
+ }
342
+ await machine.mkdir(posixDirname(logPath), { parents: true });
343
+ await machine.writeText(logPath, "");
344
+ return logPath;
345
+ }
346
+ /**
347
+ * Where task logs go: `<home>/.operon/tasks`, unless that would land inside the workspace.
348
+ *
349
+ * The rule being enforced is "framework bookkeeping must not appear in the user's project",
350
+ * and the test for that is containment in the WORK DIRECTORY — not `home !== cwd`, which gets
351
+ * it wrong in both directions. Every sandbox backend returns the same path for both (E2B
352
+ * `/home/user`, Cloudflare `/workspace`), so a home-only rule silently drops task logs into
353
+ * the very tree the agent is editing, where Glob/Grep surface them and git offers to commit
354
+ * them. Conversely `cwd=/workspace/proj` with `home=/workspace` is perfectly fine, and a
355
+ * `home !== cwd` test would needlessly relocate it.
356
+ *
357
+ * The fallback is `/tmp`: still on the machine (so `Read` reaches it, sandbox included),
358
+ * outside the workspace, and alive for as long as the machine is. On win32 there is no
359
+ * equivalent worth guessing at, and a Windows home is never the workspace in practice, so it
360
+ * keeps the home path.
361
+ */
362
+ function backgroundLogDir(machine) {
363
+ let home;
364
+ try {
365
+ home = machine.gethome();
366
+ }
367
+ catch {
368
+ return undefined;
369
+ }
370
+ if (home.length === 0)
371
+ return undefined;
372
+ const candidate = `${home.replaceAll("\\", "/").replace(/\/+$/, "")}/${OPERON_HOME_DIRNAME}/tasks`;
373
+ let cwd;
374
+ try {
375
+ cwd = machine.getcwd();
376
+ }
377
+ catch {
378
+ return candidate;
379
+ }
380
+ const pathClass = machine.pathClass();
381
+ if (cwd.length === 0 || !isWithinDirectory(candidate, cwd.replaceAll("\\", "/"), pathClass))
382
+ return candidate;
383
+ return pathClass === "win32" ? candidate : `/tmp/${OPERON_HOME_DIRNAME}/tasks`;
384
+ }
385
+ function posixDirname(path) {
386
+ const idx = path.lastIndexOf("/");
387
+ return idx <= 0 ? "/" : path.slice(0, idx);
388
+ }
389
+ function windowsPathToPosixPath(path) {
390
+ if (path.startsWith("\\\\"))
391
+ return path.replaceAll("\\", "/");
392
+ const driveMatch = /^([A-Za-z]):(?:[\\/]|$)/.exec(path);
393
+ if (driveMatch !== null) {
394
+ const drive = driveMatch[1].toLowerCase();
395
+ const rest = path.slice(2).replaceAll("\\", "/");
396
+ return `/${drive}${rest.startsWith("/") ? rest : `/${rest}`}`;
397
+ }
398
+ return path.replaceAll("\\", "/");
399
+ }
400
+ const WINDOWS_NUL_REDIRECT = /(\d?&?>+\s*)[Nn][Uu][Ll](?=\s|$|[|&;)\n])/g;
401
+ function rewriteWindowsNullRedirect(command) {
402
+ return command.replace(WINDOWS_NUL_REDIRECT, "$1/dev/null");
403
+ }
404
+ function errorResult(text) {
405
+ return { content: [{ type: "text", text }], isError: true };
406
+ }
407
+ //# sourceMappingURL=bash.js.map
@@ -0,0 +1,2 @@
1
+ export declare const editTool: import("../types.ts").Tool;
2
+ //# sourceMappingURL=edit.d.ts.map
@@ -0,0 +1,202 @@
1
+ import { z } from "zod";
2
+ import { ToolAccesses } from "../access.js";
3
+ import { defineTool } from "../define.js";
4
+ import { StaleFileError } from "../machine.js";
5
+ import { checkFreshness, FILE_MODIFIED_MESSAGE, FILE_NOT_READ_MESSAGE } from "../file-freshness.js";
6
+ import { fileVersionFromInfo, normalizeForCompare, readTextFile } from "../support/machine-ops.js";
7
+ import { pathApproval, resolveToolPath } from "../support/tool-path.js";
8
+ import { materializeModelText, toModelTextView } from "./line-endings.js";
9
+ // `old_string` must be non-empty: the non-replace_all branch walks occurrences with
10
+ // indexOf, which would loop forever on an empty search string.
11
+ const EditInput = z.object({
12
+ path: z
13
+ .string()
14
+ .describe("Path to the text file to edit. Relative paths resolve against the working directory; a path outside the working directory must be absolute."),
15
+ old_string: z
16
+ .string()
17
+ .min(1)
18
+ .describe("Exact content to replace from the Read output view, without the line-number prefix. Use LF for pure CRLF files; use actual \\r escapes where Read shows \\r."),
19
+ new_string: z
20
+ .string()
21
+ .describe("Replacement text in the same Read output view. LF is written back as CRLF only for pure CRLF files."),
22
+ replace_all: z
23
+ .boolean()
24
+ .optional()
25
+ .describe("Set true only when every occurrence of old_string should be replaced."),
26
+ });
27
+ const EDIT_DESCRIPTION = [
28
+ "Perform exact string replacements against the text view returned by Read.",
29
+ "",
30
+ "- When copying from Read output, omit the line-number prefix and tab; match only the file content.",
31
+ "- By default, old_string must occur exactly once. If it matches multiple locations, add surrounding context or set replace_all when every occurrence should change.",
32
+ "- Prefer Edit for targeted changes to existing files; use Write only for new files or complete overwrites.",
33
+ "- To modify a file, always use Edit; do not run a Bash `sed` command for edits.",
34
+ "- Read the file first so Edit can use the latest text view and verify the file has not changed before writing.",
35
+ "- When making several independent changes, issue multiple Edit calls in parallel within a single response; edits to the same file are serialized automatically by a write lock.",
36
+ "- When several parallel Edit calls target the same file, a write lock serializes them; they apply in the order the calls appear in your response. An edit fails with `old_string not found` if its old_string was taken from text an earlier edit already replaced — base every old_string on the latest Read view and order dependent edits accordingly.",
37
+ "- For pure CRLF files, Read shows LF and Edit.old_string/new_string should use LF; Edit writes the file back with CRLF preserved.",
38
+ "- For mixed line endings or lone carriage returns, Read displays carriage returns as \\r; include actual \\r escapes in old_string/new_string for those positions.",
39
+ ].join("\n");
40
+ function replaceOnceLiteral(content, oldString, newString) {
41
+ const index = content.indexOf(oldString);
42
+ if (index === -1)
43
+ return content;
44
+ return content.slice(0, index) + newString + content.slice(index + oldString.length);
45
+ }
46
+ export const editTool = defineTool({
47
+ name: "Edit",
48
+ description: EDIT_DESCRIPTION,
49
+ params: EditInput,
50
+ // The replacement text is what lands in the file — that's the security-relevant part.
51
+ toAutoApprovalInput: (args) => `${args.path}: ${args.new_string}`,
52
+ async resolve(args, ctx) {
53
+ const path = await resolveToolPath(args.path, ctx.machine, "write");
54
+ return {
55
+ accesses: ToolAccesses.readWriteFile(path),
56
+ display: { title: `Editing ${args.path}`, before: args.old_string, after: args.new_string },
57
+ ...pathApproval("Edit", ctx.machine, path),
58
+ run: (runCtx) => execute(args, path, runCtx),
59
+ };
60
+ },
61
+ });
62
+ async function execute(args, safePath, ctx) {
63
+ const machine = ctx.machine;
64
+ if (args.old_string === args.new_string) {
65
+ return errorResult("No changes to make: old_string and new_string are exactly the same.");
66
+ }
67
+ try {
68
+ await validateEdit(args, safePath, ctx);
69
+ const raw = await readTextFile(machine, safePath);
70
+ const modelView = toModelTextView(raw);
71
+ const content = modelView.text;
72
+ const replaceAll = args.replace_all ?? false;
73
+ if (!replaceAll) {
74
+ let count = 0;
75
+ let pos = 0;
76
+ while (pos < content.length) {
77
+ const idx = content.indexOf(args.old_string, pos);
78
+ if (idx === -1)
79
+ break;
80
+ count++;
81
+ pos = idx + args.old_string.length;
82
+ }
83
+ if (count === 0) {
84
+ return errorResult(`old_string not found in ${args.path}, the file contents may be out of date. Please use the Read Tool to reload the content.\n`);
85
+ }
86
+ if (count > 1) {
87
+ return errorResult(`old_string is not unique in ${args.path} (found ${String(count)} occurrences). ` +
88
+ "To replace every occurrence, set replace_all=true. To replace only one occurrence, include more surrounding context in old_string.");
89
+ }
90
+ const newContent = replaceOnceLiteral(content, args.old_string, args.new_string);
91
+ await writeFreshText(ctx, safePath, materializeModelText(newContent, modelView.lineEndingStyle), modelView.lineEndingStyle);
92
+ return textResult(`Replaced 1 occurrence in ${args.path}`);
93
+ }
94
+ const parts = content.split(args.old_string);
95
+ const replacementCount = parts.length - 1;
96
+ if (replacementCount === 0) {
97
+ return errorResult(`old_string not found in ${args.path}, the file contents may be out of date. Please use the Read Tool to reload the content.\n`);
98
+ }
99
+ const newContent = parts.join(args.new_string);
100
+ await writeFreshText(ctx, safePath, materializeModelText(newContent, modelView.lineEndingStyle), modelView.lineEndingStyle);
101
+ return textResult(`Replaced ${String(replacementCount)} occurrences in ${args.path}`);
102
+ }
103
+ catch (error) {
104
+ if (error instanceof StaleFileError)
105
+ return errorResult(FILE_MODIFIED_MESSAGE);
106
+ const code = error?.code;
107
+ if (code === "EISDIR") {
108
+ return errorResult(`${args.path} is not a file.`);
109
+ }
110
+ return errorResult(error instanceof Error ? error.message : String(error));
111
+ }
112
+ }
113
+ function requireLedger(ctx) {
114
+ if (ctx.fileLedger === undefined) {
115
+ throw new Error("File freshness tracking unavailable - cannot verify read-before-write safety for this session.");
116
+ }
117
+ return ctx.fileLedger;
118
+ }
119
+ async function validateEdit(args, path, ctx) {
120
+ if (args.old_string === args.new_string) {
121
+ throw new Error("No changes to make: old_string and new_string are exactly the same.");
122
+ }
123
+ const ledger = requireLedger(ctx);
124
+ // Read-before-write asks "has this agent seen the file", which any ledger record
125
+ // answers. NOT `fullRead` — that says whether the RETAINED CONTENT is the whole
126
+ // file, and gating on it locked Edit out of every file over the Read tool's line
127
+ // or byte cap, with no way back in (a paged re-read is not a full read either).
128
+ // Partial reads stay safe further down: the uniqueness check below runs against
129
+ // the WHOLE file, so an old_string guessed from unseen text fails to match or
130
+ // fails to be unique.
131
+ const record = ledger.get(path);
132
+ if (record === undefined)
133
+ throw new Error(FILE_NOT_READ_MESSAGE);
134
+ const raw = await readTextFile(ctx.machine, path);
135
+ const info = await ctx.machine.fileInfo(path);
136
+ const verdict = await checkFreshness({
137
+ ledger,
138
+ path,
139
+ current: fileVersionFromInfo(info),
140
+ currentContent: () => Promise.resolve(normalizeForCompare(raw)),
141
+ });
142
+ if (verdict.kind === "not-read")
143
+ throw new Error(FILE_NOT_READ_MESSAGE);
144
+ if (verdict.kind === "stale")
145
+ throw new Error(FILE_MODIFIED_MESSAGE);
146
+ const content = toModelTextView(raw).text;
147
+ const replaceAll = args.replace_all ?? false;
148
+ if (!replaceAll) {
149
+ let count = 0;
150
+ let pos = 0;
151
+ while (pos < content.length) {
152
+ const idx = content.indexOf(args.old_string, pos);
153
+ if (idx === -1)
154
+ break;
155
+ count++;
156
+ pos = idx + args.old_string.length;
157
+ }
158
+ if (count === 0) {
159
+ throw new Error(`old_string not found in ${args.path}, the file contents may be out of date. Please use the Read Tool to reload the content.\n`);
160
+ }
161
+ if (count > 1) {
162
+ throw new Error(`old_string is not unique in ${args.path} (found ${String(count)} occurrences). ` +
163
+ "To replace every occurrence, set replace_all=true. To replace only one occurrence, include more surrounding context in old_string.");
164
+ }
165
+ return;
166
+ }
167
+ if (!content.includes(args.old_string)) {
168
+ throw new Error(`old_string not found in ${args.path}, the file contents may be out of date. Please use the Read Tool to reload the content.\n`);
169
+ }
170
+ }
171
+ async function writeFreshText(ctx, path, materializedContent, lineEndingStyle) {
172
+ const ledger = requireLedger(ctx);
173
+ const record = ledger.get(path);
174
+ if (record === undefined)
175
+ throw new Error(FILE_NOT_READ_MESSAGE);
176
+ // `expectedContent` only rides along when the ledger kept the whole file — on a
177
+ // partial read the CAS has the mtime and nothing else, so a moved mtime is a
178
+ // conflict with no content review to overturn it.
179
+ const result = await ctx.machine.writeTextIfUnchanged(path, materializedContent, {
180
+ expected: record.version,
181
+ ...(record.fullRead && record.content !== undefined ? { expectedContent: record.content } : {}),
182
+ });
183
+ ledger.recordWrite(path, result.version, {
184
+ content: normalizeForCompare(materializedContent),
185
+ lineEndings: toLedgerLineEndings(lineEndingStyle),
186
+ encoding: "utf8",
187
+ });
188
+ }
189
+ function toLedgerLineEndings(style) {
190
+ if (style === "crlf")
191
+ return "CRLF";
192
+ if (style === "mixed")
193
+ return "mixed";
194
+ return "LF";
195
+ }
196
+ function errorResult(text) {
197
+ return { content: [{ type: "text", text }], isError: true };
198
+ }
199
+ function textResult(text) {
200
+ return { content: [{ type: "text", text }] };
201
+ }
202
+ //# sourceMappingURL=edit.js.map
@@ -0,0 +1,3 @@
1
+ export declare const MAX_MATCHES = 100;
2
+ export declare const globTool: import("../types.ts").Tool;
3
+ //# sourceMappingURL=glob.d.ts.map