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,574 @@
1
+ import { normalize } from "node:path";
2
+ import { z } from "zod";
3
+ import { isAbortError } from "../../loop/errors.js";
4
+ import { defineTool } from "../define.js";
5
+ import { isSensitiveFile, SENSITIVE_DOT_VARIANT_SUFFIXES } from "../policies/sensitive.js";
6
+ import { resolveRgCommand, rgUnavailableMessage } from "../support/rg-locator.js";
7
+ import { runRipgrep, stillRunningNote } from "../support/ripgrep-run.js";
8
+ import { ToolResultBuilder } from "../support/result-builder.js";
9
+ import { globApproval, resolveToolPath, SEARCH_ACCESS_POLICY } from "../support/tool-path.js";
10
+ const NUL = "\u0000";
11
+ const GrepInput = z.object({
12
+ pattern: z.string().describe("Regular expression to search for."),
13
+ path: z
14
+ .string()
15
+ .optional()
16
+ .describe("File or directory to search. Accepts an absolute path, or a path relative to the current working directory. Omit to search the current working directory. Use Read instead when you already know a concrete file path and need its contents."),
17
+ glob: z.string().optional().describe("Optional glob filter passed to ripgrep."),
18
+ type: z
19
+ .string()
20
+ .optional()
21
+ .describe("Optional ripgrep file type filter, such as ts or py. Prefer this over `glob` when filtering by language or file kind: it is more efficient and less error-prone than an equivalent glob pattern."),
22
+ output_mode: z
23
+ .enum(["content", "files_with_matches", "count_matches"])
24
+ .optional()
25
+ .describe("Shape of the result. `content` shows matching lines (honors `-A`, `-B`, `-C`, `-n`, and `head_limit`); `files_with_matches` shows only the paths of files that contain a match (honors `head_limit`); `count_matches` shows the total number of matches. Defaults to `files_with_matches`."),
26
+ "-i": z.boolean().optional().describe("Perform a case-insensitive search. Defaults to false."),
27
+ "-n": z
28
+ .boolean()
29
+ .optional()
30
+ .describe("Prefix each matching line with its line number. Applies only when `output_mode` is `content`. Defaults to true."),
31
+ "-A": z
32
+ .number()
33
+ .int()
34
+ .nonnegative()
35
+ .optional()
36
+ .describe("Number of lines to show after each match. Applies only when `output_mode` is `content`."),
37
+ "-B": z
38
+ .number()
39
+ .int()
40
+ .nonnegative()
41
+ .optional()
42
+ .describe("Number of lines to show before each match. Applies only when `output_mode` is `content`."),
43
+ "-C": z
44
+ .number()
45
+ .int()
46
+ .nonnegative()
47
+ .optional()
48
+ .describe("Number of lines to show before and after each match. Applies only when `output_mode` is `content`; takes precedence over `-A` and `-B`."),
49
+ head_limit: z
50
+ .number()
51
+ .int()
52
+ .nonnegative()
53
+ .optional()
54
+ .describe("Limit output to the first N lines/entries after offset. Defaults to 250. Pass 0 for unlimited."),
55
+ offset: z
56
+ .number()
57
+ .int()
58
+ .nonnegative()
59
+ .optional()
60
+ .describe("Number of leading lines/entries to skip before applying `head_limit`. Use it together with `head_limit` to page through large result sets. Defaults to 0."),
61
+ multiline: z
62
+ .boolean()
63
+ .optional()
64
+ .describe("Enable multiline matching, where the pattern can span line boundaries and `.` also matches newlines. Defaults to false."),
65
+ include_ignored: z
66
+ .boolean()
67
+ .optional()
68
+ .describe("Also search files excluded by ignore files such as `.gitignore`, `.ignore`, and `.rgignore` (for example `node_modules` or build outputs). Sensitive files (such as `.env`) remain filtered out for safety. Defaults to false."),
69
+ });
70
+ const DEFAULT_TIMEOUT_MS = 20_000;
71
+ const MAX_OUTPUT_BYTES = 10 * 1024 * 1024;
72
+ const RG_MAX_COLUMNS = 500;
73
+ const DEFAULT_HEAD_LIMIT = 250;
74
+ const MTIME_STAT_CONCURRENCY = 32;
75
+ const VCS_DIRECTORIES_TO_EXCLUDE = [".git", ".svn", ".hg", ".bzr", ".jj", ".sl"];
76
+ const SENSITIVE_KEY_BASENAMES = ["id_rsa", "id_ed25519", "id_ecdsa"];
77
+ const SENSITIVE_KEY_GLOBS_TO_EXCLUDE = SENSITIVE_KEY_BASENAMES.flatMap((name) => [
78
+ `**/${name}`,
79
+ `**/${name}[-_]*`,
80
+ ...SENSITIVE_DOT_VARIANT_SUFFIXES.map((suffix) => `**/${name}${suffix}`),
81
+ ]);
82
+ const SENSITIVE_GLOBS_TO_EXCLUDE = [
83
+ "**/.env",
84
+ ...SENSITIVE_KEY_GLOBS_TO_EXCLUDE,
85
+ "**/.aws/credentials",
86
+ "**/.aws/credentials/**",
87
+ "**/.gcp/credentials",
88
+ "**/.gcp/credentials/**",
89
+ ];
90
+ const CONTENT_LINE_RE = /^(.*?)([:-])(\d+)\2/;
91
+ const GREP_DESCRIPTION = [
92
+ "Search file contents using regular expressions (powered by ripgrep).",
93
+ "",
94
+ "Use Grep when the task is to find unknown content or unknown file locations. Do not use shell `grep` or `rg` directly; this tool applies workspace path policy, output limits, and sensitive-file filtering.",
95
+ "ALWAYS use Grep tool instead of running `grep` or `rg` from a shell — direct shell calls bypass workspace policy, output limits, and sensitive-file filtering.",
96
+ "If you already know a concrete file path and need to inspect its contents, use Read directly instead.",
97
+ "",
98
+ "Write patterns in ripgrep regex syntax, which differs from POSIX `grep` syntax. For example, braces are special, so escape them as `\\{` to match a literal `{`.",
99
+ "",
100
+ "Hidden files (dotfiles such as `.gitlab-ci.yml` or `.eslintrc.json`) are searched by default. To also search files excluded by `.gitignore` (such as `node_modules` or build outputs), set `include_ignored` to `true`. Sensitive files (such as `.env`) are always skipped for safety, even when `include_ignored` is `true`.",
101
+ ].join("\n");
102
+ export const grepTool = defineTool({
103
+ name: "Grep",
104
+ description: GREP_DESCRIPTION,
105
+ params: GrepInput,
106
+ async resolve(args, ctx) {
107
+ const searchPath = args.path !== undefined
108
+ ? await resolveToolPath(args.path, ctx.machine, "search", SEARCH_ACCESS_POLICY)
109
+ : ctx.machine.getcwd();
110
+ return {
111
+ display: { title: `Searching for '${args.pattern}' in ${args.path ?? "."}` },
112
+ ...globApproval("Grep", args.pattern),
113
+ run: (runCtx) => execution(args, runCtx.signal, [searchPath], runCtx.machine),
114
+ };
115
+ },
116
+ });
117
+ class GrepAbortedError extends Error {
118
+ constructor() {
119
+ super("Grep aborted");
120
+ this.name = "GrepAbortedError";
121
+ }
122
+ }
123
+ function errResult(text) {
124
+ return { content: [{ type: "text", text }], isError: true };
125
+ }
126
+ async function execution(args, signal, searchPaths, machine) {
127
+ if (signal.aborted)
128
+ return errResult("Aborted before search started");
129
+ const pathClass = machine.pathClass();
130
+ const workspaceDir = machine.getcwd();
131
+ let rgPath;
132
+ try {
133
+ rgPath = await resolveRgCommand(machine, { signal });
134
+ }
135
+ catch (error) {
136
+ if (isAbortError(error))
137
+ return errResult("Grep aborted");
138
+ return errResult(rgUnavailableMessage(error));
139
+ }
140
+ const runOptions = { timeoutMs: DEFAULT_TIMEOUT_MS, maxOutputBytes: MAX_OUTPUT_BYTES };
141
+ let outcome = await runRipgrep(machine, buildRgArgs(rgPath, args, searchPaths), signal, runOptions);
142
+ const earlyExit = mapNonResult(outcome);
143
+ if (earlyExit)
144
+ return earlyExit;
145
+ let runResult = outcome.result;
146
+ if (shouldRetryRipgrepEagain(runResult)) {
147
+ outcome = await runRipgrep(machine, buildRgArgs(rgPath, args, searchPaths, true), signal, runOptions);
148
+ const retryExit = mapNonResult(outcome);
149
+ if (retryExit)
150
+ return retryExit;
151
+ runResult = outcome.result;
152
+ }
153
+ const { exitCode, stderrText, truncated, timedOut, terminated } = runResult;
154
+ let { stdoutText } = runResult;
155
+ // An `undefined` code is not a failure — it means the run was cut short (timeout kill, or
156
+ // a backend that cannot confirm completion), and the partial output is still usable.
157
+ if (exitCode !== undefined && exitCode !== 0 && exitCode !== 1 && !timedOut) {
158
+ return errResult(formatRipgrepError(exitCode, stderrText, truncated));
159
+ }
160
+ const mode = args.output_mode ?? "files_with_matches";
161
+ if (truncated || timedOut)
162
+ stdoutText = omitIncompleteTrailingRecord(stdoutText, mode);
163
+ if (timedOut && stdoutText.trim() === "") {
164
+ return errResult(`Grep timed out after ${String(DEFAULT_TIMEOUT_MS / 1000)}s${stillRunningNote(terminated)}. ` +
165
+ `Try a more specific path or pattern.`);
166
+ }
167
+ if (signal.aborted)
168
+ return errResult("Grep aborted");
169
+ const rawLines = parseRipgrepOutput(stdoutText, mode);
170
+ const filteredSensitive = new Set();
171
+ const keptLines = filterSensitiveLines(rawLines, mode, filteredSensitive, pathClass);
172
+ let orderedLines;
173
+ try {
174
+ orderedLines =
175
+ mode === "files_with_matches" && !timedOut
176
+ ? await sortFilesWithMatchesByMtime(keptLines, machine, signal)
177
+ : keptLines;
178
+ }
179
+ catch (error) {
180
+ if (error instanceof GrepAbortedError)
181
+ return errResult("Grep aborted");
182
+ throw error;
183
+ }
184
+ const offset = args.offset ?? 0;
185
+ const headLimit = args.head_limit ?? DEFAULT_HEAD_LIMIT;
186
+ const afterOffset = offset > 0 ? orderedLines.slice(offset) : orderedLines;
187
+ const limitActive = headLimit > 0;
188
+ const limited = limitActive ? afterOffset.slice(0, headLimit) : afterOffset;
189
+ const paginationTruncated = limitActive && afterOffset.length > headLimit;
190
+ const messages = [];
191
+ const sideChannelMessages = [];
192
+ if (filteredSensitive.size > 0) {
193
+ const displayedFilteredPaths = [...filteredSensitive].map((p) => relativizeIfUnder(p, workspaceDir, pathClass));
194
+ messages.push(`Filtered ${String(filteredSensitive.size)} sensitive file(s): ${displayedFilteredPaths.join(", ")}`);
195
+ }
196
+ if (mode === "count_matches" && orderedLines.length > 0) {
197
+ sideChannelMessages.push(formatCountSummary(orderedLines, filteredSensitive.size > 0));
198
+ }
199
+ if (paginationTruncated) {
200
+ const total = afterOffset.length + offset;
201
+ const nextOffset = offset + headLimit;
202
+ const paginationNotice = `Results truncated to ${String(headLimit)} lines (total: ${String(total)}). Use offset=${String(nextOffset)} to see more.`;
203
+ if (mode === "count_matches")
204
+ sideChannelMessages.push(paginationNotice);
205
+ else
206
+ messages.push(paginationNotice);
207
+ }
208
+ if (truncated) {
209
+ messages.push(`[output truncated at ${String(MAX_OUTPUT_BYTES)} bytes; incomplete trailing line omitted]`);
210
+ }
211
+ if (timedOut) {
212
+ messages.push(`Grep timed out after ${String(DEFAULT_TIMEOUT_MS / 1000)}s${stillRunningNote(terminated)}; ` +
213
+ `partial results returned`);
214
+ }
215
+ const contentIncludesLineNumbers = mode === "content" && args["-n"] !== false;
216
+ const displayedLines = limited.map((line) => formatDisplayLine(line, mode, workspaceDir, pathClass, contentIncludesLineNumbers));
217
+ const contentBody = displayedLines.join("\n");
218
+ const visibleBody = orderedLines.length === 0 && filteredSensitive.size > 0 ? "No non-sensitive matches found" : contentBody;
219
+ const emptyResultMessage = "No non-sensitive matches found";
220
+ const combined = visibleBody === "" && messages.length === 0
221
+ ? emptyResultMessage
222
+ : messages.length > 0
223
+ ? visibleBody === ""
224
+ ? messages.join("\n")
225
+ : `${visibleBody}\n${messages.join("\n")}`
226
+ : visibleBody;
227
+ const builder = new ToolResultBuilder();
228
+ builder.write(combined);
229
+ return builder.ok(sideChannelMessages.join("\n"));
230
+ }
231
+ /** Map an aborted/exec-error outcome to a tool result, or null when ripgrep ran. */
232
+ function mapNonResult(outcome) {
233
+ if (outcome.kind === "aborted")
234
+ return errResult("Grep aborted");
235
+ if (outcome.kind === "exec-error") {
236
+ return errResult(outcome.isEnoent
237
+ ? rgUnavailableMessage(outcome.error)
238
+ : outcome.error instanceof Error
239
+ ? outcome.error.message
240
+ : String(outcome.error));
241
+ }
242
+ return null;
243
+ }
244
+ function shouldRetryRipgrepEagain(result) {
245
+ // No exit code means the run was cut short, not that rg failed to spawn threads — a
246
+ // retry would just hit the same timeout.
247
+ if (result.exitCode === undefined)
248
+ return false;
249
+ return result.exitCode !== 0 && result.exitCode !== 1 && !result.timedOut && isEagainRipgrepError(result.stderrText);
250
+ }
251
+ function isEagainRipgrepError(stderr) {
252
+ return stderr.includes("os error 11") || stderr.includes("Resource temporarily unavailable");
253
+ }
254
+ async function sortFilesWithMatchesByMtime(lines, machine, signal) {
255
+ const entries = await mapWithConcurrency(lines, MTIME_STAT_CONCURRENCY, signal, async (line, index) => {
256
+ const path = line.kind === "record" ? line.filePath : line.kind === "legacy" ? line.text : undefined;
257
+ let mtime = 0;
258
+ if (path !== undefined) {
259
+ try {
260
+ mtime = (await machine.fileInfo(path)).mtimeMs ?? 0;
261
+ }
262
+ catch {
263
+ /* mtime=0 → sort after known files */
264
+ }
265
+ }
266
+ return { line, mtime, index };
267
+ });
268
+ entries.sort((a, b) => b.mtime - a.mtime || a.index - b.index);
269
+ return entries.map((entry) => entry.line);
270
+ }
271
+ async function mapWithConcurrency(items, concurrency, signal, mapper) {
272
+ if (signal.aborted)
273
+ throw new GrepAbortedError();
274
+ if (items.length === 0)
275
+ return [];
276
+ const results = [];
277
+ results.length = items.length;
278
+ let nextIndex = 0;
279
+ const workerCount = Math.min(Math.max(1, concurrency), items.length);
280
+ await Promise.all(Array.from({ length: workerCount }, async () => {
281
+ while (true) {
282
+ if (signal.aborted)
283
+ return;
284
+ const index = nextIndex;
285
+ nextIndex += 1;
286
+ if (index >= items.length)
287
+ return;
288
+ results[index] = await mapper(items[index], index);
289
+ }
290
+ }));
291
+ if (signal.aborted)
292
+ throw new GrepAbortedError();
293
+ return results;
294
+ }
295
+ function buildRgArgs(rgPath, args, searchPaths, singleThreaded = false) {
296
+ const cmd = [rgPath];
297
+ if (singleThreaded)
298
+ cmd.push("-j", "1");
299
+ cmd.push("--hidden");
300
+ const mode = args.output_mode ?? "files_with_matches";
301
+ // Only `content` prints file lines, so only it can print a 200 KB minified one. Capping at
302
+ // the ripgrep end matters most on remote backends: the cap decides how many bytes cross the
303
+ // wire, whereas the result builder's per-line limit only trims them after they arrive.
304
+ if (mode === "content")
305
+ cmd.push("--max-columns", String(RG_MAX_COLUMNS), "--max-columns-preview");
306
+ cmd.push("--null");
307
+ for (const dir of VCS_DIRECTORIES_TO_EXCLUDE)
308
+ cmd.push("--glob", `!${dir}`);
309
+ if (mode === "files_with_matches")
310
+ cmd.push("-l");
311
+ else if (mode === "count_matches")
312
+ cmd.push("--count-matches", "--with-filename");
313
+ if (args["-i"])
314
+ cmd.push("-i");
315
+ if (mode === "content") {
316
+ cmd.push("--with-filename");
317
+ if (args["-n"] !== false)
318
+ cmd.push("-n");
319
+ else
320
+ cmd.push("--field-context-separator", ":");
321
+ if (args["-C"] !== undefined) {
322
+ cmd.push("-C", String(args["-C"]));
323
+ }
324
+ else {
325
+ if (args["-A"] !== undefined)
326
+ cmd.push("-A", String(args["-A"]));
327
+ if (args["-B"] !== undefined)
328
+ cmd.push("-B", String(args["-B"]));
329
+ }
330
+ }
331
+ if (args.glob !== undefined)
332
+ cmd.push("--glob", args.glob);
333
+ if (args.type !== undefined)
334
+ cmd.push("--type", args.type);
335
+ if (args.multiline)
336
+ cmd.push("-U", "--multiline-dotall");
337
+ if (args.include_ignored)
338
+ cmd.push("--no-ignore");
339
+ for (const glob of SENSITIVE_GLOBS_TO_EXCLUDE)
340
+ cmd.push("--glob", `!${glob}`);
341
+ cmd.push("--", args.pattern, ...searchPaths);
342
+ return cmd;
343
+ }
344
+ function splitRgLines(text) {
345
+ if (text === "")
346
+ return [];
347
+ const lines = text.split("\n");
348
+ while (lines.length > 0 && lines.at(-1) === "")
349
+ lines.pop();
350
+ return lines.map((line) => stripTrailingCarriageReturn(line));
351
+ }
352
+ function parseRipgrepOutput(text, mode) {
353
+ if (text === "")
354
+ return [];
355
+ if (!text.includes(NUL)) {
356
+ return splitRgLines(text).map((line) => mode === "content" && line === "--" ? { kind: "separator" } : { kind: "legacy", text: line });
357
+ }
358
+ if (mode === "files_with_matches") {
359
+ return text
360
+ .split(NUL)
361
+ .map((filePath) => stripTrailingCarriageReturn(filePath))
362
+ .filter((filePath) => filePath !== "")
363
+ .map((filePath) => ({ kind: "record", filePath, payload: "" }));
364
+ }
365
+ const records = [];
366
+ let cursor = 0;
367
+ while (cursor < text.length) {
368
+ if (text[cursor] === "\n") {
369
+ cursor += 1;
370
+ continue;
371
+ }
372
+ if (text.startsWith("--\r\n", cursor)) {
373
+ records.push({ kind: "separator" });
374
+ cursor += 4;
375
+ continue;
376
+ }
377
+ if (text.startsWith("--\n", cursor)) {
378
+ records.push({ kind: "separator" });
379
+ cursor += 3;
380
+ continue;
381
+ }
382
+ const nulIndex = text.indexOf(NUL, cursor);
383
+ if (nulIndex < 0) {
384
+ const tail = stripTrailingCarriageReturn(text.slice(cursor));
385
+ if (tail !== "")
386
+ records.push({ kind: "legacy", text: tail });
387
+ break;
388
+ }
389
+ const lineEnd = text.indexOf("\n", nulIndex + 1);
390
+ const payloadEnd = lineEnd >= 0 ? lineEnd : text.length;
391
+ const filePath = text.slice(cursor, nulIndex);
392
+ const payload = stripTrailingCarriageReturn(text.slice(nulIndex + 1, payloadEnd));
393
+ records.push({ kind: "record", filePath, payload });
394
+ cursor = lineEnd >= 0 ? lineEnd + 1 : text.length;
395
+ }
396
+ return records;
397
+ }
398
+ function formatDisplayLine(line, mode, workspaceDir, pathClass, contentIncludesLineNumbers) {
399
+ if (line.kind === "separator")
400
+ return "--";
401
+ if (line.kind === "record") {
402
+ const displayPath = relativizeIfUnder(line.filePath, workspaceDir, pathClass);
403
+ if (mode === "files_with_matches")
404
+ return displayPath;
405
+ if (mode === "count_matches")
406
+ return `${displayPath}:${line.payload}`;
407
+ const separator = contentIncludesLineNumbers ? contentPayloadPathSeparator(line.payload) : ":";
408
+ return `${displayPath}${separator}${line.payload}`;
409
+ }
410
+ const text = line.text;
411
+ if (mode === "files_with_matches")
412
+ return relativizeIfUnder(text, workspaceDir, pathClass);
413
+ if (mode === "count_matches") {
414
+ const idx = text.lastIndexOf(":");
415
+ if (idx <= 0)
416
+ return text;
417
+ return relativizeIfUnder(text.slice(0, idx), workspaceDir, pathClass) + text.slice(idx);
418
+ }
419
+ const filePath = extractContentFilePath(text, pathClass);
420
+ if (filePath !== undefined)
421
+ return relativizeIfUnder(filePath, workspaceDir, pathClass) + text.slice(filePath.length);
422
+ return text;
423
+ }
424
+ function relativizeIfUnder(candidate, base, pathClass) {
425
+ const normCandidate = normalize(candidate);
426
+ const normBase = normalize(base);
427
+ const comparableCandidate = pathClass === "win32" ? normCandidate.toLowerCase() : normCandidate;
428
+ const comparableBase = pathClass === "win32" ? normBase.toLowerCase() : normBase;
429
+ if (comparableCandidate === comparableBase)
430
+ return ".";
431
+ const prefix = comparableBase.endsWith("/") ? comparableBase : comparableBase + "/";
432
+ if (comparableCandidate.startsWith(prefix))
433
+ return normCandidate.slice(prefix.length);
434
+ return normCandidate;
435
+ }
436
+ function omitIncompleteTrailingRecord(text, mode) {
437
+ if (!text.includes(NUL))
438
+ return omitIncompleteTrailingLine(text);
439
+ if (mode === "files_with_matches") {
440
+ const lastNul = text.lastIndexOf(NUL);
441
+ return lastNul >= 0 ? text.slice(0, lastNul + 1) : "";
442
+ }
443
+ let cursor = 0;
444
+ let lastCompleteEnd = 0;
445
+ while (cursor < text.length) {
446
+ if (text[cursor] === "\n") {
447
+ cursor += 1;
448
+ lastCompleteEnd = cursor;
449
+ continue;
450
+ }
451
+ if (text.startsWith("--\r\n", cursor)) {
452
+ cursor += 4;
453
+ lastCompleteEnd = cursor;
454
+ continue;
455
+ }
456
+ if (text.startsWith("--\n", cursor)) {
457
+ cursor += 3;
458
+ lastCompleteEnd = cursor;
459
+ continue;
460
+ }
461
+ const nulIndex = text.indexOf(NUL, cursor);
462
+ if (nulIndex < 0)
463
+ break;
464
+ const lineEnd = text.indexOf("\n", nulIndex + 1);
465
+ if (lineEnd < 0)
466
+ break;
467
+ cursor = lineEnd + 1;
468
+ lastCompleteEnd = cursor;
469
+ }
470
+ return text.slice(0, lastCompleteEnd);
471
+ }
472
+ function omitIncompleteTrailingLine(text) {
473
+ const lastNewline = text.lastIndexOf("\n");
474
+ return lastNewline >= 0 ? text.slice(0, lastNewline) : "";
475
+ }
476
+ function formatRipgrepError(exitCode, stderrText, truncated) {
477
+ const stderr = stderrText.trim();
478
+ if (stderr.length === 0)
479
+ return `Failed to grep: ripgrep exited with code ${String(exitCode)}`;
480
+ const summary = summarizeRipgrepStderr(stderr);
481
+ const lines = [`Failed to grep: ${summary}`, "", "ripgrep stderr:", stderr];
482
+ if (truncated)
483
+ lines.push(`[output truncated at ${String(MAX_OUTPUT_BYTES)} bytes]`);
484
+ return lines.join("\n");
485
+ }
486
+ function summarizeRipgrepStderr(stderr) {
487
+ const lines = splitRgLines(stderr)
488
+ .map((line) => line.trim())
489
+ .filter((line) => line.length > 0);
490
+ const errorLine = lines.findLast((line) => line.toLowerCase().startsWith("error:"));
491
+ return errorLine ?? lines.at(-1) ?? "ripgrep error";
492
+ }
493
+ function filterSensitiveLines(lines, mode, filteredPaths, pathClass) {
494
+ const kept = [];
495
+ for (const line of lines) {
496
+ if (line.kind === "separator") {
497
+ kept.push(line);
498
+ continue;
499
+ }
500
+ const filePath = parsedFilePath(line, mode, pathClass);
501
+ if (filePath !== undefined && isSensitiveFile(filePath)) {
502
+ filteredPaths.add(filePath);
503
+ continue;
504
+ }
505
+ kept.push(line);
506
+ }
507
+ return mode === "content" ? normalizeContextSeparators(kept) : kept;
508
+ }
509
+ function normalizeContextSeparators(lines) {
510
+ const normalized = [];
511
+ for (const line of lines) {
512
+ if (line.kind === "separator" && (normalized.length === 0 || normalized.at(-1)?.kind === "separator"))
513
+ continue;
514
+ normalized.push(line);
515
+ }
516
+ while (normalized.length > 0 && normalized.at(-1)?.kind === "separator")
517
+ normalized.pop();
518
+ return normalized;
519
+ }
520
+ function parsedFilePath(line, mode, pathClass) {
521
+ if (line.kind === "record")
522
+ return normalize(line.filePath);
523
+ if (line.kind === "separator")
524
+ return undefined;
525
+ const text = line.text;
526
+ if (mode === "files_with_matches")
527
+ return normalize(text);
528
+ if (mode === "count_matches") {
529
+ const idx = text.lastIndexOf(":");
530
+ return idx > 0 ? normalize(text.slice(0, idx)) : normalize(text);
531
+ }
532
+ return extractContentFilePath(text, pathClass);
533
+ }
534
+ function extractContentFilePath(line, pathClass) {
535
+ const m = CONTENT_LINE_RE.exec(line);
536
+ if (m?.[1] !== undefined)
537
+ return normalize(m[1]);
538
+ const separatorIndex = noLineNumberContentSeparatorIndex(line, pathClass);
539
+ return separatorIndex > 0 ? normalize(line.slice(0, separatorIndex)) : undefined;
540
+ }
541
+ function noLineNumberContentSeparatorIndex(line, pathClass) {
542
+ const searchFrom = pathClass === "win32" && /^[A-Za-z]:/.test(line) ? 2 : 0;
543
+ return line.indexOf(":", searchFrom);
544
+ }
545
+ function contentPayloadPathSeparator(payload) {
546
+ const m = /^(\d+)([:-])/.exec(payload);
547
+ return m?.[2] === "-" ? "-" : ":";
548
+ }
549
+ function stripTrailingCarriageReturn(value) {
550
+ return value.endsWith("\r") ? value.slice(0, -1) : value;
551
+ }
552
+ function formatCountSummary(lines, redactedSensitive) {
553
+ let totalMatches = 0;
554
+ let totalFiles = 0;
555
+ for (const line of lines) {
556
+ const rawCount = line.kind === "record" ? line.payload : line.kind === "legacy" ? countPayloadFromLegacyLine(line.text) : undefined;
557
+ if (rawCount === undefined)
558
+ continue;
559
+ const count = Number(rawCount);
560
+ if (!Number.isSafeInteger(count) || count < 0)
561
+ continue;
562
+ totalMatches += count;
563
+ totalFiles++;
564
+ }
565
+ const occurrenceWord = totalMatches === 1 ? "occurrence" : "occurrences";
566
+ const fileWord = totalFiles === 1 ? "file" : "files";
567
+ const scope = redactedSensitive ? "total non-sensitive" : "total";
568
+ return `Found ${String(totalMatches)} ${scope} ${occurrenceWord} across ${String(totalFiles)} ${fileWord}.`;
569
+ }
570
+ function countPayloadFromLegacyLine(line) {
571
+ const idx = line.lastIndexOf(":");
572
+ return idx > 0 ? line.slice(idx + 1) : undefined;
573
+ }
574
+ //# sourceMappingURL=grep.js.map
@@ -0,0 +1,10 @@
1
+ export type LineEndingStyle = "lf" | "crlf" | "mixed";
2
+ export interface ModelTextView {
3
+ text: string;
4
+ lineEndingStyle: LineEndingStyle;
5
+ }
6
+ export declare function detectLineEndingStyle(text: string): LineEndingStyle;
7
+ export declare function toModelTextView(raw: string): ModelTextView;
8
+ export declare function materializeModelText(text: string, lineEndingStyle: LineEndingStyle): string;
9
+ export declare function makeCarriageReturnsVisible(text: string): string;
10
+ //# sourceMappingURL=line-endings.d.ts.map
@@ -0,0 +1,41 @@
1
+ export function detectLineEndingStyle(text) {
2
+ let hasCrLf = false;
3
+ let hasLf = false;
4
+ let hasLoneCr = false;
5
+ for (let i = 0; i < text.length; i++) {
6
+ const code = text.codePointAt(i);
7
+ if (code === 13) {
8
+ if (text.codePointAt(i + 1) === 10) {
9
+ hasCrLf = true;
10
+ i++;
11
+ }
12
+ else {
13
+ hasLoneCr = true;
14
+ }
15
+ }
16
+ else if (code === 10) {
17
+ hasLf = true;
18
+ }
19
+ }
20
+ if (hasLoneCr || (hasCrLf && hasLf))
21
+ return "mixed";
22
+ if (hasCrLf)
23
+ return "crlf";
24
+ return "lf";
25
+ }
26
+ export function toModelTextView(raw) {
27
+ const lineEndingStyle = detectLineEndingStyle(raw);
28
+ if (lineEndingStyle !== "crlf") {
29
+ return { text: raw, lineEndingStyle };
30
+ }
31
+ return { text: raw.replaceAll("\r\n", "\n"), lineEndingStyle };
32
+ }
33
+ export function materializeModelText(text, lineEndingStyle) {
34
+ if (lineEndingStyle !== "crlf")
35
+ return text;
36
+ return text.replaceAll("\r\n", "\n").replaceAll("\n", "\r\n");
37
+ }
38
+ export function makeCarriageReturnsVisible(text) {
39
+ return text.replaceAll("\r", "\\r");
40
+ }
41
+ //# sourceMappingURL=line-endings.js.map
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Ceiling on an EXPLICIT line request (`n_lines`, or a negative `line_offset`). Not a default
3
+ * truncation: an unpaged read returns the whole file, bounded by the two limits below.
4
+ *
5
+ * A default that quietly served the first N lines was the worst of both worlds — the caller
6
+ * asked for a file and got a prefix, and the ledger recorded a partial view, which is exactly
7
+ * what disables the content-comparison fallback that the mtime-coarse backends depend on.
8
+ */
9
+ export declare const MAX_LINES = 2000;
10
+ export declare const MAX_LINE_LENGTH = 2000;
11
+ /** Rendered-output ceiling. Past it the read is refused, never silently cut short. */
12
+ export declare const MAX_BYTES: number;
13
+ /**
14
+ * Whole-file ceiling for an UNPAGED read (no `line_offset`/`n_lines`): past this the read is
15
+ * refused instead of served truncated.
16
+ *
17
+ * Truncation is not the problem — the `<system>` footer says plainly how much was cut. The
18
+ * cost is: a multi-megabyte file answers with `MAX_BYTES` of its opening, which is rarely
19
+ * what the caller wanted and never cheap. Refusing costs a two-line error and leaves the
20
+ * caller to page in, grep, or give up, all of which beat paying for a prefix nobody asked for.
21
+ *
22
+ * Only unpaged reads are gated. A caller that passed a range already said what it wants, and
23
+ * gating that on the file's TOTAL size would refuse exactly the paging that is the way
24
+ * out of this error.
25
+ */
26
+ export declare const MAX_UNPAGED_FILE_BYTES: number;
27
+ export declare const readTool: import("../types.ts").Tool;
28
+ //# sourceMappingURL=read.d.ts.map