@bastani/atomic 0.9.13-alpha.2 → 0.9.13-alpha.4

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 (317) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/README.md +1 -1
  3. package/dist/builtin/i-have-adhd/package.json +1 -1
  4. package/dist/builtin/intercom/CHANGELOG.md +14 -0
  5. package/dist/builtin/intercom/README.md +12 -12
  6. package/dist/builtin/intercom/incoming-message-delivery.ts +1 -1
  7. package/dist/builtin/intercom/index.ts +1 -1
  8. package/dist/builtin/intercom/intercom-tool.ts +1 -1
  9. package/dist/builtin/intercom/intercom-utils.ts +3 -6
  10. package/dist/builtin/intercom/package.json +1 -1
  11. package/dist/builtin/intercom/result-renderers.ts +1 -1
  12. package/dist/builtin/intercom/session-target.ts +1 -15
  13. package/dist/builtin/intercom/skills/intercom/SKILL.md +6 -6
  14. package/dist/builtin/intercom/terminal-ordering-barrier.ts +2 -2
  15. package/dist/builtin/intercom/ui/inline-message.ts +7 -5
  16. package/dist/builtin/intercom/ui/session-list.ts +23 -10
  17. package/dist/builtin/mcp/package.json +1 -1
  18. package/dist/builtin/subagents/CHANGELOG.md +19 -0
  19. package/dist/builtin/subagents/README.md +29 -73
  20. package/dist/builtin/subagents/package.json +2 -2
  21. package/dist/builtin/subagents/prompts/parallel-cleanup.md +1 -1
  22. package/dist/builtin/subagents/prompts/parallel-review.md +1 -1
  23. package/dist/builtin/subagents/prompts/review-loop.md +2 -2
  24. package/dist/builtin/subagents/skills/subagent/SKILL.md +23 -59
  25. package/dist/builtin/subagents/skills/tmux/SKILL.md +1 -1
  26. package/dist/builtin/subagents/src/extension/control-notices.ts +2 -3
  27. package/dist/builtin/subagents/src/extension/doctor.ts +2 -14
  28. package/dist/builtin/subagents/src/extension/fanout-child.ts +1 -17
  29. package/dist/builtin/subagents/src/extension/index.ts +9 -70
  30. package/dist/builtin/subagents/src/extension/notification-content.ts +1 -1
  31. package/dist/builtin/subagents/src/extension/prompt-guidance.ts +2 -2
  32. package/dist/builtin/subagents/src/extension/schemas.ts +2 -8
  33. package/dist/builtin/subagents/src/extension/tool-description.ts +2 -3
  34. package/dist/builtin/subagents/src/intercom/intercom-bridge.ts +1 -1
  35. package/dist/builtin/subagents/src/intercom/result-intercom.ts +5 -46
  36. package/dist/builtin/subagents/src/runs/{background → foreground}/completion-notification.ts +2 -2
  37. package/dist/builtin/subagents/src/runs/foreground/inprocess-run-sync.ts +25 -88
  38. package/dist/builtin/subagents/src/runs/{background → foreground}/notify.ts +5 -5
  39. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-context.ts +11 -28
  40. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-parallel-task.ts +3 -0
  41. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-parallel.ts +2 -0
  42. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-runtime.ts +0 -5
  43. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-single.ts +30 -20
  44. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-status.ts +4 -4
  45. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-types.ts +0 -13
  46. package/dist/builtin/subagents/src/runs/foreground/subagent-executor.ts +104 -48
  47. package/dist/builtin/subagents/src/runs/inprocess/index.ts +1 -1
  48. package/dist/builtin/subagents/src/runs/inprocess/runner.ts +5 -5
  49. package/dist/builtin/subagents/src/runs/inprocess/runtime-support/nested-api.ts +0 -7
  50. package/dist/builtin/subagents/src/runs/inprocess/runtime-support/nested-core.ts +0 -10
  51. package/dist/builtin/subagents/src/runs/inprocess/runtime-support/nested-projection.ts +3 -108
  52. package/dist/builtin/subagents/src/runs/inprocess/runtime-support/nested-sanitize.ts +0 -4
  53. package/dist/builtin/subagents/src/runs/shared/subagent-control.ts +1 -1
  54. package/dist/builtin/subagents/src/shared/formatters.ts +3 -5
  55. package/dist/builtin/subagents/src/shared/model-resolution.ts +78 -0
  56. package/dist/builtin/subagents/src/shared/status-format.ts +4 -11
  57. package/dist/builtin/subagents/src/shared/types-config.ts +10 -9
  58. package/dist/builtin/subagents/src/shared/types-nested.ts +127 -0
  59. package/dist/builtin/subagents/src/shared/types-results.ts +2 -8
  60. package/dist/builtin/subagents/src/shared/types-runtime.ts +0 -9
  61. package/dist/builtin/subagents/src/shared/types.ts +1 -1
  62. package/dist/builtin/subagents/src/shared/utils.ts +1 -109
  63. package/dist/builtin/subagents/src/slash/slash-commands.ts +7 -17
  64. package/dist/builtin/subagents/src/tui/render-event-formatting.ts +2 -252
  65. package/dist/builtin/subagents/src/tui/render-layout.ts +4 -4
  66. package/dist/builtin/subagents/src/tui/render-result.ts +0 -9
  67. package/dist/builtin/subagents/src/tui/render-stable-output.ts +1 -34
  68. package/dist/builtin/subagents/src/tui/render.ts +0 -2
  69. package/dist/builtin/web-access/package.json +1 -1
  70. package/dist/builtin/workflows/CHANGELOG.md +23 -0
  71. package/dist/builtin/workflows/README.md +3 -3
  72. package/dist/builtin/workflows/package.json +1 -1
  73. package/dist/builtin/workflows/src/durable/backend.ts +11 -0
  74. package/dist/builtin/workflows/src/durable/completed-catalog-stage-groups.ts +63 -25
  75. package/dist/builtin/workflows/src/durable/completed-catalog.ts +166 -25
  76. package/dist/builtin/workflows/src/durable/dbos-backend.ts +42 -24
  77. package/dist/builtin/workflows/src/durable/dbos-envelope.ts +2 -1
  78. package/dist/builtin/workflows/src/durable/run-timing.ts +28 -7
  79. package/dist/builtin/workflows/src/durable/scoped-backend.ts +4 -0
  80. package/dist/builtin/workflows/src/durable/targeted-inspection.ts +110 -0
  81. package/dist/builtin/workflows/src/engine/run-durable-stage-session.ts +2 -2
  82. package/dist/builtin/workflows/src/engine/runtime.ts +19 -2
  83. package/dist/builtin/workflows/src/extension/extension-runtime-state.ts +3 -0
  84. package/dist/builtin/workflows/src/extension/index.bundle.mjs +750 -168
  85. package/dist/builtin/workflows/src/extension/runtime-durable-resume.ts +6 -0
  86. package/dist/builtin/workflows/src/extension/ui-surface.ts +4 -0
  87. package/dist/builtin/workflows/src/extension/workflow-command-registration.ts +6 -1
  88. package/dist/builtin/workflows/src/extension/workflow-targets.ts +18 -10
  89. package/dist/builtin/workflows/src/extension/workflow-tool-inspection.ts +31 -16
  90. package/dist/builtin/workflows/src/extension/workflow-tool-send.ts +75 -3
  91. package/dist/builtin/workflows/src/extension/workflow-tool.ts +53 -6
  92. package/dist/builtin/workflows/src/runs/background/run-inspect.ts +5 -1
  93. package/dist/builtin/workflows/src/runs/foreground/executor-stage-call.ts +94 -60
  94. package/dist/builtin/workflows/src/runs/foreground/executor-stage-context.ts +1 -1
  95. package/dist/builtin/workflows/src/runs/foreground/executor-stage-control.ts +7 -7
  96. package/dist/builtin/workflows/src/runs/foreground/executor-stage-factory.ts +25 -4
  97. package/dist/builtin/workflows/src/runs/foreground/executor-stage-types.ts +4 -1
  98. package/dist/builtin/workflows/src/runs/foreground/executor-types.ts +2 -0
  99. package/dist/builtin/workflows/src/runs/foreground/stage-runner-controller.ts +142 -4
  100. package/dist/builtin/workflows/src/runs/foreground/stage-runner-types.ts +2 -0
  101. package/dist/builtin/workflows/src/runs/foreground/stage-session-heartbeat.ts +88 -0
  102. package/dist/builtin/workflows/src/tui/keybindings-adapter.ts +1 -0
  103. package/dist/builtin/workflows/src/tui/overlay-adapter.ts +1 -0
  104. package/dist/builtin/workflows/src/tui/run-detail.ts +25 -12
  105. package/dist/builtin/workflows/src/tui/stage-chat-view-archive-history.ts +27 -8
  106. package/dist/builtin/workflows/src/tui/stage-chat-view-input.ts +17 -1
  107. package/dist/builtin/workflows/src/tui/stage-chat-view.ts +20 -3
  108. package/dist/builtin/workflows/src/tui/workflow-attach-pane.ts +10 -1
  109. package/dist/builtin/workflows/src/tui/workflow-resume-selector.ts +1 -0
  110. package/dist/core/agent-session-events.d.ts.map +1 -1
  111. package/dist/core/agent-session-events.js +22 -5
  112. package/dist/core/agent-session-events.js.map +1 -1
  113. package/dist/core/agent-session-export.d.ts.map +1 -1
  114. package/dist/core/agent-session-export.js +2 -1
  115. package/dist/core/agent-session-export.js.map +1 -1
  116. package/dist/core/agent-session-methods.d.ts +10 -4
  117. package/dist/core/agent-session-methods.d.ts.map +1 -1
  118. package/dist/core/agent-session-methods.js.map +1 -1
  119. package/dist/core/agent-session-prompt.d.ts.map +1 -1
  120. package/dist/core/agent-session-prompt.js +68 -0
  121. package/dist/core/agent-session-prompt.js.map +1 -1
  122. package/dist/core/agent-session-queue-pause.d.ts.map +1 -1
  123. package/dist/core/agent-session-queue-pause.js +6 -0
  124. package/dist/core/agent-session-queue-pause.js.map +1 -1
  125. package/dist/core/agent-session-summary.d.ts +21 -0
  126. package/dist/core/agent-session-summary.d.ts.map +1 -0
  127. package/dist/core/agent-session-summary.js +156 -0
  128. package/dist/core/agent-session-summary.js.map +1 -0
  129. package/dist/core/agent-session-tool-registry.d.ts.map +1 -1
  130. package/dist/core/agent-session-tool-registry.js +0 -4
  131. package/dist/core/agent-session-tool-registry.js.map +1 -1
  132. package/dist/core/agent-session-transfer.d.ts.map +1 -1
  133. package/dist/core/agent-session-transfer.js +0 -2
  134. package/dist/core/agent-session-transfer.js.map +1 -1
  135. package/dist/core/agent-session-tree.d.ts.map +1 -1
  136. package/dist/core/agent-session-tree.js +6 -0
  137. package/dist/core/agent-session-tree.js.map +1 -1
  138. package/dist/core/agent-session.d.ts +21 -3
  139. package/dist/core/agent-session.d.ts.map +1 -1
  140. package/dist/core/agent-session.js +22 -5
  141. package/dist/core/agent-session.js.map +1 -1
  142. package/dist/core/atomic-guide-command.js +2 -2
  143. package/dist/core/atomic-guide-command.js.map +1 -1
  144. package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
  145. package/dist/core/compaction/branch-summarization.js +1 -0
  146. package/dist/core/compaction/branch-summarization.js.map +1 -1
  147. package/dist/core/compaction/index.d.ts +1 -0
  148. package/dist/core/compaction/index.d.ts.map +1 -1
  149. package/dist/core/compaction/index.js +1 -0
  150. package/dist/core/compaction/index.js.map +1 -1
  151. package/dist/core/compaction/session-summarization.d.ts +41 -0
  152. package/dist/core/compaction/session-summarization.d.ts.map +1 -0
  153. package/dist/core/compaction/session-summarization.js +97 -0
  154. package/dist/core/compaction/session-summarization.js.map +1 -0
  155. package/dist/core/extensions/ui-types.d.ts +4 -0
  156. package/dist/core/extensions/ui-types.d.ts.map +1 -1
  157. package/dist/core/extensions/ui-types.js.map +1 -1
  158. package/dist/core/keybindings.d.ts +0 -5
  159. package/dist/core/keybindings.d.ts.map +1 -1
  160. package/dist/core/keybindings.js +0 -2
  161. package/dist/core/keybindings.js.map +1 -1
  162. package/dist/core/session-manager-core.d.ts +3 -1
  163. package/dist/core/session-manager-core.d.ts.map +1 -1
  164. package/dist/core/session-manager-core.js +9 -1
  165. package/dist/core/session-manager-core.js.map +1 -1
  166. package/dist/core/session-manager-entries.d.ts +24 -1
  167. package/dist/core/session-manager-entries.d.ts.map +1 -1
  168. package/dist/core/session-manager-entries.js +48 -0
  169. package/dist/core/session-manager-entries.js.map +1 -1
  170. package/dist/core/session-manager-list.d.ts.map +1 -1
  171. package/dist/core/session-manager-list.js +10 -0
  172. package/dist/core/session-manager-list.js.map +1 -1
  173. package/dist/core/session-manager-types.d.ts +10 -1
  174. package/dist/core/session-manager-types.d.ts.map +1 -1
  175. package/dist/core/session-manager-types.js.map +1 -1
  176. package/dist/core/settings-manager-basic-accessors.d.ts +3 -0
  177. package/dist/core/settings-manager-basic-accessors.d.ts.map +1 -1
  178. package/dist/core/settings-manager-basic-accessors.js +5 -0
  179. package/dist/core/settings-manager-basic-accessors.js.map +1 -1
  180. package/dist/core/settings-manager.d.ts +1 -1
  181. package/dist/core/settings-manager.d.ts.map +1 -1
  182. package/dist/core/settings-manager.js.map +1 -1
  183. package/dist/core/settings-types.d.ts +4 -0
  184. package/dist/core/settings-types.d.ts.map +1 -1
  185. package/dist/core/settings-types.js.map +1 -1
  186. package/dist/core/slash-commands.js +2 -2
  187. package/dist/core/slash-commands.js.map +1 -1
  188. package/dist/core/tools/bash.d.ts +0 -15
  189. package/dist/core/tools/bash.d.ts.map +1 -1
  190. package/dist/core/tools/bash.js +3 -81
  191. package/dist/core/tools/bash.js.map +1 -1
  192. package/dist/core/tools/fetch-url.d.ts +12 -0
  193. package/dist/core/tools/fetch-url.d.ts.map +1 -1
  194. package/dist/core/tools/fetch-url.js +76 -10
  195. package/dist/core/tools/fetch-url.js.map +1 -1
  196. package/dist/core/tools/index.js +4 -4
  197. package/dist/core/tools/index.js.map +1 -1
  198. package/dist/core/tools/session-temp-dir.d.ts +2 -2
  199. package/dist/core/tools/session-temp-dir.d.ts.map +1 -1
  200. package/dist/core/tools/session-temp-dir.js +6 -7
  201. package/dist/core/tools/session-temp-dir.js.map +1 -1
  202. package/dist/core/usage-totals.js +1 -1
  203. package/dist/core/usage-totals.js.map +1 -1
  204. package/dist/index.d.ts +1 -1
  205. package/dist/index.d.ts.map +1 -1
  206. package/dist/index.js +1 -1
  207. package/dist/index.js.map +1 -1
  208. package/dist/modes/interactive/components/footer.js +1 -1
  209. package/dist/modes/interactive/components/footer.js.map +1 -1
  210. package/dist/modes/interactive/components/host-session-picker.d.ts.map +1 -1
  211. package/dist/modes/interactive/components/host-session-picker.js +1 -0
  212. package/dist/modes/interactive/components/host-session-picker.js.map +1 -1
  213. package/dist/modes/interactive/components/index.d.ts +1 -0
  214. package/dist/modes/interactive/components/index.d.ts.map +1 -1
  215. package/dist/modes/interactive/components/index.js +1 -0
  216. package/dist/modes/interactive/components/index.js.map +1 -1
  217. package/dist/modes/interactive/components/session-selector-list.d.ts.map +1 -1
  218. package/dist/modes/interactive/components/session-selector-list.js +29 -4
  219. package/dist/modes/interactive/components/session-selector-list.js.map +1 -1
  220. package/dist/modes/interactive/components/session-selector-search.js +1 -1
  221. package/dist/modes/interactive/components/session-selector-search.js.map +1 -1
  222. package/dist/modes/interactive/components/transcript-follow-indicator.d.ts +14 -0
  223. package/dist/modes/interactive/components/transcript-follow-indicator.d.ts.map +1 -0
  224. package/dist/modes/interactive/components/transcript-follow-indicator.js +36 -0
  225. package/dist/modes/interactive/components/transcript-follow-indicator.js.map +1 -0
  226. package/dist/modes/interactive/components/tree-selector-content.d.ts.map +1 -1
  227. package/dist/modes/interactive/components/tree-selector-content.js +6 -0
  228. package/dist/modes/interactive/components/tree-selector-content.js.map +1 -1
  229. package/dist/modes/interactive/interactive-extension-custom-ui.js +3 -0
  230. package/dist/modes/interactive/interactive-extension-custom-ui.js.map +1 -1
  231. package/dist/modes/interactive/interactive-input-handling.js +0 -3
  232. package/dist/modes/interactive/interactive-input-handling.js.map +1 -1
  233. package/dist/modes/interactive/interactive-mode-base.d.ts +1 -0
  234. package/dist/modes/interactive/interactive-mode-base.d.ts.map +1 -1
  235. package/dist/modes/interactive/interactive-mode-base.js +7 -1
  236. package/dist/modes/interactive/interactive-mode-base.js.map +1 -1
  237. package/dist/modes/interactive/interactive-mode-surface.d.ts +3 -3
  238. package/dist/modes/interactive/interactive-mode-surface.d.ts.map +1 -1
  239. package/dist/modes/interactive/interactive-mode-surface.js.map +1 -1
  240. package/dist/modes/interactive/interactive-mode.d.ts +1 -0
  241. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  242. package/dist/modes/interactive/interactive-mode.js +1 -0
  243. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  244. package/dist/modes/interactive/interactive-slash-commands.js +2 -5
  245. package/dist/modes/interactive/interactive-slash-commands.js.map +1 -1
  246. package/dist/modes/interactive/interactive-startup.d.ts.map +1 -1
  247. package/dist/modes/interactive/interactive-startup.js +6 -0
  248. package/dist/modes/interactive/interactive-startup.js.map +1 -1
  249. package/dist/modes/interactive/interactive-transcript-follow.d.ts +2 -0
  250. package/dist/modes/interactive/interactive-transcript-follow.d.ts.map +1 -0
  251. package/dist/modes/interactive/interactive-transcript-follow.js +6 -0
  252. package/dist/modes/interactive/interactive-transcript-follow.js.map +1 -0
  253. package/dist/modes/interactive/interactive-tui.d.ts +13 -1
  254. package/dist/modes/interactive/interactive-tui.d.ts.map +1 -1
  255. package/dist/modes/interactive/interactive-tui.js +59 -1
  256. package/dist/modes/interactive/interactive-tui.js.map +1 -1
  257. package/dist/modes/interactive-engine/engine-custom-ui.d.ts +2 -0
  258. package/dist/modes/interactive-engine/engine-custom-ui.d.ts.map +1 -1
  259. package/dist/modes/interactive-engine/engine-custom-ui.js +1 -0
  260. package/dist/modes/interactive-engine/engine-custom-ui.js.map +1 -1
  261. package/dist/modes/interactive-engine/protocol.d.ts +1 -0
  262. package/dist/modes/interactive-engine/protocol.d.ts.map +1 -1
  263. package/dist/modes/interactive-engine/protocol.js +5 -1
  264. package/dist/modes/interactive-engine/protocol.js.map +1 -1
  265. package/dist/modes/interactive-engine/remote-component.d.ts.map +1 -1
  266. package/dist/modes/interactive-engine/remote-component.js +21 -9
  267. package/dist/modes/interactive-engine/remote-component.js.map +1 -1
  268. package/docs/environment-variables.md +1 -1
  269. package/docs/intercom.md +20 -21
  270. package/docs/keybindings.md +2 -5
  271. package/docs/quickstart.md +5 -1
  272. package/docs/sdk.md +1 -1
  273. package/docs/session-format.md +15 -0
  274. package/docs/sessions.md +8 -0
  275. package/docs/settings.md +6 -0
  276. package/docs/subagents.md +19 -31
  277. package/docs/tools.md +3 -5
  278. package/docs/usage.md +3 -1
  279. package/docs/windows.md +1 -1
  280. package/docs/workflows.md +60 -32
  281. package/npm-shrinkwrap.json +29 -29
  282. package/package.json +2 -2
  283. package/dist/builtin/subagents/src/runs/background/async-job-tracker.ts +0 -331
  284. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-async.ts +0 -161
  285. package/dist/builtin/subagents/src/runs/inprocess/background-single.ts +0 -195
  286. package/dist/builtin/subagents/src/runs/inprocess/background.ts +0 -90
  287. package/dist/builtin/subagents/src/shared/types-async.ts +0 -247
  288. package/dist/builtin/subagents/src/tui/render-widget-graph.ts +0 -217
  289. package/dist/builtin/subagents/src/tui/render-widget.ts +0 -366
  290. package/dist/core/async/format.d.ts +0 -3
  291. package/dist/core/async/format.d.ts.map +0 -1
  292. package/dist/core/async/format.js +0 -52
  293. package/dist/core/async/format.js.map +0 -1
  294. package/dist/core/async/job-manager.d.ts +0 -40
  295. package/dist/core/async/job-manager.d.ts.map +0 -1
  296. package/dist/core/async/job-manager.js +0 -293
  297. package/dist/core/async/job-manager.js.map +0 -1
  298. package/dist/core/async/session-manager.d.ts +0 -16
  299. package/dist/core/async/session-manager.d.ts.map +0 -1
  300. package/dist/core/async/session-manager.js +0 -34
  301. package/dist/core/async/session-manager.js.map +0 -1
  302. package/dist/core/async/types.d.ts +0 -23
  303. package/dist/core/async/types.d.ts.map +0 -1
  304. package/dist/core/async/types.js +0 -2
  305. package/dist/core/async/types.js.map +0 -1
  306. package/dist/core/tools/bash-async-execution.d.ts +0 -27
  307. package/dist/core/tools/bash-async-execution.d.ts.map +0 -1
  308. package/dist/core/tools/bash-async-execution.js +0 -81
  309. package/dist/core/tools/bash-async-execution.js.map +0 -1
  310. package/dist/core/tools/bash-async-jobs.d.ts +0 -30
  311. package/dist/core/tools/bash-async-jobs.d.ts.map +0 -1
  312. package/dist/core/tools/bash-async-jobs.js +0 -87
  313. package/dist/core/tools/bash-async-jobs.js.map +0 -1
  314. package/dist/core/tools/bash-async-output.d.ts +0 -13
  315. package/dist/core/tools/bash-async-output.d.ts.map +0 -1
  316. package/dist/core/tools/bash-async-output.js +0 -122
  317. package/dist/core/tools/bash-async-output.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"fetch-url.js","sourceRoot":"","sources":["../../../src/core/tools/fetch-url.ts"],"names":[],"mappings":"AAAA,kDAAkD;AAClD;;;;;;;;;;;;;;GAcG;AACH,OAAO,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAC3C,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AACrC,OAAO,eAAe,MAAM,UAAU,CAAC;AACvC,OAAO,EAAE,KAAK,EAAmB,OAAO,IAAI,aAAa,EAAE,MAAM,QAAQ,CAAC;AAC1E,OAAO,EAAE,kBAAkB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ache / artifact / markdown-discovery pipeline, mirrored from\n * oh-my-pi's `packages/coding-agent/src/tools/fetch.ts` at 15b5c1397fc.\n *\n * Responsibilities:\n * - parseReadUrlTarget: URL + line selectors (:raw, :N, :A-B, :A+B, :A-B,C-D),\n * collapsed-scheme repair, host-port protection.\n * - session-scoped LRU cache keyed by `<scope>::<raw|rendered>::<normalizedUrl>`,\n * cached under both requested and final (redirected) URLs.\n * - renderUrl: markdown discovery (alternate <link>, .md suffix, content\n * negotiation, llms.txt/llms.md endpoints) + native HTML-to-markdown, with\n * quality gating.\n * - artifact persistence of the rendered output, with artifactId surfaced in\n * truncation metadata when the visible output is head-truncated.\n */\nimport { lookup } from \"node:dns/promises\";\nimport { LRUCache } from \"lru-cache\";\nimport TurndownService from \"turndown\";\nimport { Agent, type Dispatcher, request as undiciRequest } from \"undici\";\nimport { getArtifactManager } from \"./artifacts.ts\";\nimport { extractDocumentMarkdown, isDocumentPath } from \"./read-document-extract.ts\";\nimport type { TruncationResult } from \"./truncate.ts\";\nimport { ipFamily, isPrivateIpAddress, normalizeIpLiteralHost } from \"./url-ip-guards.ts\";\n\nexport const FETCH_DEFAULT_MAX_LINES = 300;\nexport const READ_URL_CACHE_MAX_ENTRIES = 100;\nconst REMOTE_FETCH_TIMEOUT_MS = 10_000;\nconst MAX_URL_REDIRECTS = 5;\nconst MAX_URL_RESPONSE_BYTES = 10 * 1024 * 1024;\nconst MIN_CONTENT_LENGTH = 100;\n\nexport interface LineRange {\n\tstart: number;\n\tend?: number;\n}\n\nexport interface ParsedReadUrlTarget {\n\turl: string;\n\traw: boolean;\n\toffset?: number;\n\tlimit?: number;\n\tranges?: readonly LineRange[];\n}\n\nexport interface ReadUrlToolDetails {\n\turl: string;\n\tfinalUrl: string;\n\tcontentType: string;\n\tmethod: string;\n\ttruncated: boolean;\n\tnotes: string[];\n\tmeta?: { artifactId?: string; truncation?: TruncationResult };\n}\n\ninterface ReadUrlCacheEntry {\n\tartifactId?: string;\n\tdetails: ReadUrlToolDetails;\n\toutput: string;\n}\n\nexport interface LoadedPage {\n\tok: boolean;\n\tstatus: number;\n\tcontent: string;\n\tcontentType: string;\n\tfinalUrl: string;\n}\n\nconst readUrlCache = new LRUCache<string, ReadUrlCacheEntry>({ max: READ_URL_CACHE_MAX_ENTRIES });\nlet turndown: TurndownService | undefined;\nfunction getTurndown(): TurndownService {\n\tif (!turndown)\n\t\tturndown = new TurndownService({ headingStyle: \"atx\", codeBlockStyle: \"fenced\", bulletListMarker: \"-\" });\n\treturn turndown;\n}\n\nexport function repairCollapsedScheme(url: string): string {\n\treturn url.replace(/^(https?):\\/([^/])/i, \"$1://$2\");\n}\n\nexport function isReadableUrlPath(readPath: string): boolean {\n\tconst repaired = repairCollapsedScheme(readPath);\n\treturn /^https?:\\/\\//i.test(repaired) || /^www\\./i.test(readPath);\n}\n\nfunction normalizeUrlForCache(url: string): string {\n\tconst repaired = repairCollapsedScheme(url);\n\tif (/^[a-z][a-z0-9+.-]*:\\/\\//i.test(repaired)) return repaired;\n\treturn /^https?:\\/\\//i.test(repaired) ? repaired : `https://${repaired}`;\n}\nconst RANGE_TOKEN_RE = /^(raw|\\d+(?:\\+(?:\\d+)|(?:-|\\.\\.)\\d+)?)$/i;\nconst MULTI_RANGE_RE = /^\\d+(?:(?:-|\\.\\.|,|\\+)\\d+)*$/;\n\nfunction isUrlSelectorToken(token: string): boolean {\n\treturn /^raw$/i.test(token) || RANGE_TOKEN_RE.test(token) || MULTI_RANGE_RE.test(token);\n}\n\nfunction parseSingleRange(token: string): LineRange | undefined {\n\tconst plus = token.match(/^(\\d+)\\+(\\d+)$/);\n\tif (plus) {\n\t\tconst start = Number.parseInt(plus[1]!, 10),\n\t\t\tcount = Number.parseInt(plus[2]!, 10);\n\t\treturn start < 1 || count < 1 ? undefined : { start, end: start + count - 1 };\n\t}\n\tconst range = token.match(/^(\\d+)(?:-|\\.\\.)(\\d+)$/);\n\tif (range) {\n\t\tconst start = Number.parseInt(range[1]!, 10);\n\t\tconst end = Number.parseInt(range[2]!, 10);\n\t\treturn start < 1 || end < start ? undefined : { start, end };\n\t}\n\tconst single = token.match(/^(\\d+)$/);\n\tif (single) {\n\t\tconst start = Number.parseInt(single[1]!, 10);\n\t\treturn start < 1 ? undefined : { start };\n\t}\n\treturn undefined;\n}\n\nfunction parseRangeGroup(token: string): LineRange[] | undefined {\n\tconst groups = token.split(\",\");\n\tconst ranges: LineRange[] = [];\n\tfor (const group of groups) {\n\t\tconst r = parseSingleRange(group);\n\t\tif (!r) return undefined;\n\t\tranges.push(r);\n\t}\n\treturn ranges;\n}\n\nfunction tryExtractEmbeddedUrlSelector(readPath: string): { path: string; sels: string[] } | null {\n\tlet basePath = readPath;\n\tconst sels: string[] = [];\n\tfor (;;) {\n\t\tconst lastColonIndex = basePath.lastIndexOf(\":\");\n\t\tif (lastColonIndex <= 0) break;\n\t\tconst candidate = basePath.slice(lastColonIndex + 1);\n\t\tconst remainder = basePath.slice(0, lastColonIndex);\n\t\tif (!isReadableUrlPath(remainder) || !isUrlSelectorToken(candidate)) break;\n\t\ttry {\n\t\t\tnew URL(\n\t\t\t\tremainder.startsWith(\"http://\") || remainder.startsWith(\"https://\") ? remainder : `https://${remainder}`,\n\t\t\t);\n\t\t} catch {\n\t\t\tbreak;\n\t\t}\n\t\tsels.unshift(candidate);\n\t\tbasePath = remainder;\n\t}\n\treturn sels.length === 0 ? null : { path: basePath, sels };\n}\n\nexport function parseReadUrlTarget(readPath: string): ParsedReadUrlTarget | null {\n\tconst repaired = repairCollapsedScheme(readPath);\n\tconst embedded = tryExtractEmbeddedUrlSelector(repaired);\n\tconst urlPath = embedded?.path ?? repaired;\n\tif (!isReadableUrlPath(urlPath)) return null;\n\tlet raw = false;\n\tlet ranges: LineRange[] | undefined;\n\tfor (const sel of embedded?.sels ?? []) {\n\t\tif (/^raw$/i.test(sel)) {\n\t\t\traw = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ranges !== undefined)\n\t\t\tthrow new Error(\"URL selector has multiple range groups; combine them with commas (e.g. `:5-10,20-30`).\");\n\t\tconst parsed = parseRangeGroup(sel);\n\t\tif (!parsed) throw new Error(`Invalid URL line selector: ${sel}`);\n\t\tranges = parsed;\n\t}\n\tif (!ranges || ranges.length === 0) return { url: urlPath, raw };\n\tif (ranges.length === 1) {\n\t\tconst r = ranges[0]!;\n\t\treturn { url: urlPath, raw, offset: r.start, limit: r.end !== undefined ? r.end - r.start + 1 : undefined };\n\t}\n\treturn { url: urlPath, raw, ranges };\n}\n\nexport function getReadUrlCacheKey(scope: string, requestedUrl: string, raw: boolean): string {\n\treturn `${scope}::${raw ? \"raw\" : \"rendered\"}::${normalizeUrlForCache(requestedUrl)}`;\n}\n\nfunction looksLikeHtml(text: string): boolean {\n\treturn /<html[\\s>]/i.test(text) || (/<head[\\s>]/i.test(text) && /<body[\\s>]/i.test(text));\n}\n\nfunction documentExtensionFromContentType(contentType: string): string | undefined {\n\tif (/pdf/i.test(contentType)) return \".pdf\";\n\tif (/msword/i.test(contentType)) return \".doc\";\n\tif (/wordprocessingml|officedocument\\.word/i.test(contentType)) return \".docx\";\n\tif (/presentationml|officedocument\\.presentation/i.test(contentType)) return \".pptx\";\n\tif (/ms-powerpoint|vnd\\.ms-powerpoint/i.test(contentType)) return \".ppt\";\n\tif (/spreadsheetml|officedocument\\.spreadsheet/i.test(contentType)) return \".xlsx\";\n\tif (/ms-excel|vnd\\.ms-excel/i.test(contentType)) return \".xls\";\n\tif (/epub/i.test(contentType)) return \".epub\";\n\tif (/\\bjson\\b|ipynb|jupyter/i.test(contentType)) return \".ipynb\";\n\tif (/rtf/i.test(contentType)) return \".rtf\";\n\treturn undefined;\n}\n\ninterface SafeFetchAddress {\n\taddress: string;\n\tfamily:\n\t\t| 4\n\t\t| 6 /** True only when the address came from DNS resolution and must be pinned to prevent rebinding at connect time. */;\n\tpinned: boolean;\n}\ntype LookupCallback = (\n\terror: NodeJS.ErrnoException | null,\n\taddress: string | SafeFetchAddress[],\n\tfamily?: number,\n) => void;\n\nfunction createPinnedDispatcher(pinned: SafeFetchAddress): Agent {\n\treturn new Agent({\n\t\tconnect: {\n\t\t\tlookup: (_hostname: string, options: { all?: boolean }, callback: LookupCallback) => {\n\t\t\t\tif (options.all) callback(null, [pinned]);\n\t\t\t\telse callback(null, pinned.address, pinned.family);\n\t\t\t},\n\t\t},\n\t});\n}\n\nasync function closePinnedDispatcher(dispatcher: Agent | undefined): Promise<void> {\n\tconst close = (dispatcher as { close?: () => Promise<void> | void } | undefined)?.close;\n\tif (typeof close === \"function\") await close.call(dispatcher);\n}\n/**\n * Fetch a URL through undici with the pinned dispatcher so the validated\n * address is the one actually connected to. Unlike `globalThis.fetch`, which\n * silently ignores the undici `dispatcher` option under Bun's compiled binary\n * (reopening a DNS-rebinding TOCTOU window for hostname targets), undici's own\n * client honors the dispatcher's custom `lookup` regardless of host runtime.\n * Adapts the undici response to the WHATWG-Response shape loadPage consumes.\n */\nasync function pinnedFetch(\n\turl: string,\n\tdispatcher: Dispatcher,\n\toptions: { signal: AbortSignal; headers?: Record<string, string> },\n): Promise<Response> {\n\tconst result = await undiciRequest(url, {\n\t\tmethod: \"GET\",\n\t\tdispatcher,\n\t\tsignal: options.signal,\n\t\theaders: options.headers,\n\t});\n\tconst body = result.body;\n\tconst status = result.statusCode;\n\tconst headers = new Headers();\n\tfor (const [key, value] of Object.entries(result.headers as Record<string, string | string[] | undefined>)) {\n\t\tif (value === undefined) continue;\n\t\tconst values = Array.isArray(value) ? value : [value];\n\t\tfor (const entry of values) headers.append(key, entry);\n\t}\n\tconst stream = new ReadableStream({\n\t\tstart(controller) {\n\t\t\tbody.on(\"data\", (chunk: Buffer) => controller.enqueue(new Uint8Array(chunk)));\n\t\t\tbody.on(\"end\", () => controller.close());\n\t\t\tbody.on(\"error\", (error: unknown) => controller.error(error));\n\t\t},\n\t\tcancel() {\n\t\t\tbody.destroy();\n\t\t},\n\t});\n\treturn new Response(stream, { status, headers });\n}\n\nasync function assertSafeFetchUrl(url: string): Promise<SafeFetchAddress | undefined> {\n\tconst parsed = new URL(url);\n\tif (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\")\n\t\tthrow new Error(`Unsupported URL protocol: ${parsed.protocol}`);\n\tif (process.env.ATOMIC_ALLOW_PRIVATE_URL_READS === \"1\") return undefined;\n\tconst hostname = parsed.hostname\n\t\t.replace(/^\\[|\\]$/g, \"\")\n\t\t.replace(/\\.$/, \"\")\n\t\t.toLowerCase();\n\tif (hostname === \"localhost\" || hostname.endsWith(\".localhost\") || hostname === \"metadata.google.internal\")\n\t\tthrow new Error(`Refusing to fetch private or metadata URL: ${url}`);\n\tconst literalAddress = normalizeIpLiteralHost(hostname);\n\tif (literalAddress) {\n\t\tif (isPrivateIpAddress(literalAddress)) throw new Error(`Refusing to fetch private or metadata URL: ${url}`);\n\t\treturn { address: literalAddress, family: ipFamily(literalAddress), pinned: false };\n\t}\n\tconst addresses = await lookup(hostname, { all: true }).catch((error: unknown) => {\n\t\tthrow new Error(\n\t\t\t`Could not resolve URL host ${hostname}: ${error instanceof Error ? error.message : String(error)}`,\n\t\t);\n\t});\n\tif (addresses.length === 0) throw new Error(`Could not resolve URL host ${hostname}: no addresses returned`);\n\tfor (const address of addresses)\n\t\tif (isPrivateIpAddress(address.address)) throw new Error(`Refusing to fetch private or metadata URL: ${url}`);\n\tconst first = addresses[0]!;\n\treturn { address: first.address, family: first.family === 6 ? 6 : 4, pinned: true };\n}\n\nasync function readResponseTextWithLimit(response: Response): Promise<string> {\n\tif (!response.body) {\n\t\tconst buffer = Buffer.from(await response.arrayBuffer());\n\t\tif (buffer.length > MAX_URL_RESPONSE_BYTES)\n\t\t\tthrow new Error(`URL response exceeds ${MAX_URL_RESPONSE_BYTES} byte limit`);\n\t\treturn buffer.toString(\"utf8\");\n\t}\n\tconst reader = response.body.getReader();\n\tconst decoder = new TextDecoder();\n\tconst chunks: string[] = [];\n\tlet totalBytes = 0;\n\tfor (;;) {\n\t\tconst { done, value } = await reader.read();\n\t\tif (done) break;\n\t\ttotalBytes += value.byteLength;\n\t\tif (totalBytes > MAX_URL_RESPONSE_BYTES) {\n\t\t\tawait reader.cancel();\n\t\t\tthrow new Error(`URL response exceeds ${MAX_URL_RESPONSE_BYTES} byte limit`);\n\t\t}\n\t\tchunks.push(decoder.decode(value, { stream: true }));\n\t}\n\tchunks.push(decoder.decode());\n\treturn chunks.join(\"\");\n}\nexport async function loadPage(\n\turl: string,\n\ttimeoutMs: number,\n\tsignal?: AbortSignal,\n\taccept?: string,\n): Promise<LoadedPage> {\n\turl = normalizeUrlForCache(url);\n\tconst controller = new AbortController();\n\tconst timer = setTimeout(() => controller.abort(), Math.min(timeoutMs, REMOTE_FETCH_TIMEOUT_MS));\n\tconst onParentAbort = () => controller.abort();\n\tsignal?.addEventListener(\"abort\", onParentAbort, { once: true });\n\ttry {\n\t\tlet currentUrl = url;\n\t\tfor (let redirects = 0; redirects <= MAX_URL_REDIRECTS; redirects++) {\n\t\t\tconst pinned = await assertSafeFetchUrl(currentUrl);\n\t\t\t// Only a DNS-resolved hostname needs pinning: a literal-IP host is\n\t\t\t// validated directly and cannot be re-resolved at connect time, so\n\t\t\t// global fetch is sufficient and stays redirect/mock-friendly.\n\t\t\tconst dispatcher = pinned?.pinned ? createPinnedDispatcher(pinned) : undefined;\n\t\t\ttry {\n\t\t\t\tconst headers = accept ? { Accept: accept } : undefined;\n\t\t\t\t// Route pinned (hostname) fetches through undici directly so the\n\t\t\t\t// dispatcher's custom lookup is honored even under Bun's compiled\n\t\t\t\t// fetch, which silently ignores the `dispatcher` option.\n\t\t\t\tconst response = dispatcher\n\t\t\t\t\t? await pinnedFetch(currentUrl, dispatcher, { signal: controller.signal, headers })\n\t\t\t\t\t: await fetch(currentUrl, { signal: controller.signal, headers, redirect: \"manual\" });\n\t\t\t\tif (response.status >= 300 && response.status < 400 && response.headers.get(\"location\")) {\n\t\t\t\t\tawait response.body?.cancel().catch(() => {});\n\t\t\t\t\tcurrentUrl = new URL(response.headers.get(\"location\")!, currentUrl).href;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst contentLength = Number.parseInt(response.headers.get(\"content-length\") ?? \"0\", 10);\n\t\t\t\tif (contentLength > MAX_URL_RESPONSE_BYTES)\n\t\t\t\t\tthrow new Error(`URL response exceeds ${MAX_URL_RESPONSE_BYTES} byte limit: ${currentUrl}`);\n\t\t\t\tconst contentType = response.headers.get(\"content-type\") ?? \"\";\n\t\t\t\tconst content = await readResponseTextWithLimit(response);\n\t\t\t\treturn {\n\t\t\t\t\tok: response.ok,\n\t\t\t\t\tstatus: response.status,\n\t\t\t\t\tcontent,\n\t\t\t\t\tcontentType,\n\t\t\t\t\tfinalUrl: response.url || currentUrl,\n\t\t\t\t};\n\t\t\t} finally {\n\t\t\t\tawait closePinnedDispatcher(dispatcher).catch(() => undefined);\n\t\t\t}\n\t\t}\n\t\tthrow new Error(`Too many redirects while fetching URL: ${url}`);\n\t} finally {\n\t\tclearTimeout(timer);\n\t\tsignal?.removeEventListener(\"abort\", onParentAbort);\n\t}\n}\n\nfunction isLowQuality(content: string): boolean {\n\tconst lower = content.toLowerCase();\n\tif (\n\t\t/(enable javascript|javascript required|turn on javascript|please enable javascript|browser not supported)/.test(\n\t\t\tlower,\n\t\t) &&\n\t\tcontent.trim().length < 2000\n\t)\n\t\treturn true;\n\tconst nonblank = content.split(\"\\n\").filter((line) => line.trim().length > 0);\n\tif (nonblank.length > 10 && nonblank.filter((line) => line.trim().length < 40).length / nonblank.length > 0.7)\n\t\treturn true;\n\treturn false;\n}\n\nfunction buildLlmEndpointCandidates(url: string): string[] {\n\tconst parsed = (() => {\n\t\ttry {\n\t\t\treturn new URL(url);\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t})();\n\tif (!parsed) return [];\n\tconst origin = parsed.origin;\n\tif (parsed.pathname === \"/\" || parsed.pathname === \"\")\n\t\treturn [`${origin}/.well-known/llms.txt`, `${origin}/llms.txt`, `${origin}/llms.md`];\n\tconst trimmed = parsed.pathname.replace(/\\/+$/, \"\");\n\tconst segments = trimmed.split(\"/\").filter(Boolean);\n\tconst candidates: string[] = [];\n\tconst depth = parsed.pathname.endsWith(\"/\") ? segments.length : Math.max(segments.length - 1, 1);\n\tfor (let scope = Math.min(depth, segments.length); scope >= 1; scope--) {\n\t\tconst base = `${origin}/${segments.slice(0, scope).join(\"/\")}`;\n\t\tcandidates.push(`${base}/llms.txt`, `${base}/llms.md`);\n\t}\n\tcandidates.push(`${origin}/llms.txt`, `${origin}/llms.md`);\n\treturn [...new Set(candidates)];\n}\n\nasync function tryLlmEndpoints(\n\turl: string,\n\tsignal?: AbortSignal,\n): Promise<{ content: string; endpoint: string } | null> {\n\tfor (const endpoint of buildLlmEndpointCandidates(url)) {\n\t\ttry {\n\t\t\tconst page = await loadPage(endpoint, 5000, signal);\n\t\t\tif (page.ok && page.content.trim().length > MIN_CONTENT_LENGTH && !looksLikeHtml(page.content))\n\t\t\t\treturn { content: page.content, endpoint };\n\t\t} catch {}\n\t}\n\treturn null;\n}\n\nfunction parseAlternateMarkdownLink(html: string, pageUrl: string): string | undefined {\n\tconst headEnd = html.toLowerCase().indexOf(\"</head>\");\n\tconst head = html.slice(0, headEnd >= 0 ? headEnd + 7 : html.length);\n\tconst links = [...head.matchAll(/<link\\b[^>]*>/gi)].map((m) => m[0] ?? \"\");\n\tfor (const tag of links) {\n\t\tconst rel = /rel=[\"']?([^\"'>]+)[\"']?/i.exec(tag)?.[1] ?? \"\";\n\t\tconst type = /type=[\"']?([^\"'>]+)[\"']?/i.exec(tag)?.[1] ?? \"\";\n\t\tconst href = /href=[\"']?([^\"'>]+)[\"']?/i.exec(tag)?.[1] ?? \"\";\n\t\tif (!/alternate/i.test(rel) || !href) continue;\n\t\tif (/RecentChanges|Special:|\\/feed\\/|action=feed/i.test(href)) continue;\n\t\tif (type.includes(\"markdown\") || href.endsWith(\".md\")) {\n\t\t\ttry {\n\t\t\t\treturn new URL(href, pageUrl).href;\n\t\t\t} catch {}\n\t\t}\n\t}\n\treturn undefined;\n}\n\nasync function tryMdSuffix(url: string, signal?: AbortSignal): Promise<string | null> {\n\tconst candidates: string[] = [];\n\tif (/\\/$/.test(url)) candidates.push(`${url}index.html.md`);\n\telse if (/\\.\\w+\\/?$/.test(url)) candidates.push(`${url}.md`);\n\telse candidates.push(`${url}.md`, `${url}/index.html.md`);\n\tfor (const candidate of candidates) {\n\t\ttry {\n\t\t\tconst page = await loadPage(candidate, 5000, signal);\n\t\t\tif (page.ok && page.content.trim().length > MIN_CONTENT_LENGTH && !looksLikeHtml(page.content))\n\t\t\t\treturn page.content;\n\t\t} catch {}\n\t}\n\treturn null;\n}\n\nasync function tryContentNegotiation(url: string, signal?: AbortSignal): Promise<string | null> {\n\ttry {\n\t\tconst page = await loadPage(url, 5000, signal, \"text/markdown, text/plain;q=0.9, text/html;q=0.8\");\n\t\tconst mime = page.contentType.toLowerCase();\n\t\tif (\n\t\t\tpage.ok &&\n\t\t\tpage.content.trim().length > MIN_CONTENT_LENGTH &&\n\t\t\t!looksLikeHtml(page.content) &&\n\t\t\t(mime.includes(\"markdown\") || mime.includes(\"text/plain\"))\n\t\t)\n\t\t\treturn page.content;\n\t} catch {}\n\treturn null;\n}\n\nexport interface RenderedUrl {\n\tcontent: string;\n\tfinalUrl: string;\n\tcontentType: string;\n\tmethod: string;\n\tnotes: string[];\n\ttruncated: boolean;\n}\n\nexport async function renderUrl(url: string, raw: boolean, signal?: AbortSignal): Promise<RenderedUrl> {\n\tconst notes: string[] = [];\n\tlet method = \"text\";\n\tlet contentType = \"\";\n\tlet finalUrl: string;\n\tlet body = \"\";\n\tconst page = await loadPage(url, REMOTE_FETCH_TIMEOUT_MS, signal);\n\tfinalUrl = page.finalUrl;\n\tcontentType = page.contentType;\n\tif (!page.ok)\n\t\treturn {\n\t\t\tcontent: page.content || `(request failed with status ${page.status})`,\n\t\t\tfinalUrl,\n\t\t\tcontentType,\n\t\t\tmethod: \"failed\",\n\t\t\tnotes,\n\t\t\ttruncated: false,\n\t\t};\n\tif (raw) return { content: page.content, finalUrl, contentType, method: \"raw\", notes, truncated: false };\n\tconst buffer = Buffer.from(page.content, \"utf8\");\n\tconst docExt =\n\t\tdocumentExtensionFromContentType(contentType) ??\n\t\t(isDocumentPath(finalUrl) ? (finalUrl.match(/\\.\\w+(?:$|[?#])/)?.[0] ?? \"\") : \"\");\n\tif (docExt) {\n\t\ttry {\n\t\t\tbody = await extractDocumentMarkdown(buffer, `${finalUrl}${docExt}`);\n\t\t\tmethod = \"document\";\n\t\t} catch (error) {\n\t\t\tbody = `[Cannot read ${docExt} file: ${error instanceof Error ? error.message : \"conversion failed\"}]`;\n\t\t\tmethod = \"document-error\";\n\t\t}\n\t\treturn { content: body, finalUrl, contentType, method, notes, truncated: false };\n\t}\n\tconst isHtml = /html/i.test(contentType) || looksLikeHtml(page.content);\n\tif (isHtml) {\n\t\tconst altMd = parseAlternateMarkdownLink(page.content, finalUrl);\n\t\tif (altMd) {\n\t\t\ttry {\n\t\t\t\tconst alt = await loadPage(altMd, 5000, signal);\n\t\t\t\tif (alt.ok && alt.content.trim().length > MIN_CONTENT_LENGTH && !looksLikeHtml(alt.content)) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: alt.content,\n\t\t\t\t\t\tfinalUrl: alt.finalUrl,\n\t\t\t\t\t\tcontentType: alt.contentType,\n\t\t\t\t\t\tmethod: \"alternate-markdown\",\n\t\t\t\t\t\tnotes,\n\t\t\t\t\t\ttruncated: false,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t} catch {}\n\t\t\tnotes.push(\"alternate markdown link unusable\");\n\t\t}\n\t\tconst md = await tryMdSuffix(finalUrl, signal);\n\t\tif (md)\n\t\t\treturn { content: md, finalUrl, contentType: \"text/markdown\", method: \"md-suffix\", notes, truncated: false };\n\t\tconst neg = await tryContentNegotiation(finalUrl, signal);\n\t\tif (neg)\n\t\t\treturn {\n\t\t\t\tcontent: neg,\n\t\t\t\tfinalUrl,\n\t\t\t\tcontentType: \"text/markdown\",\n\t\t\t\tmethod: \"content-negotiation\",\n\t\t\t\tnotes,\n\t\t\t\ttruncated: false,\n\t\t\t};\n\t\tconst rendered = getTurndown().turndown(page.content).trim();\n\t\tmethod = \"native\";\n\t\tif (rendered.length <= MIN_CONTENT_LENGTH || isLowQuality(rendered)) {\n\t\t\tconst llms = await tryLlmEndpoints(finalUrl, signal);\n\t\t\tif (llms) {\n\t\t\t\treturn {\n\t\t\t\t\tcontent: llms.content,\n\t\t\t\t\tfinalUrl,\n\t\t\t\t\tcontentType: \"text/plain\",\n\t\t\t\t\tmethod: `llms-txt (${llms.endpoint})`,\n\t\t\t\t\tnotes,\n\t\t\t\t\ttruncated: false,\n\t\t\t\t};\n\t\t\t}\n\t\t\tnotes.push(\"rendered content low quality; no markdown source discovered\");\n\t\t}\n\t\tbody = rendered;\n\t} else {\n\t\tbody = page.content;\n\t}\n\treturn { content: body, finalUrl, contentType, method, notes, truncated: false };\n}\n\nexport function buildUrlReadOutput(result: RenderedUrl): string {\n\tconst header = [\n\t\t`URL: ${result.finalUrl}`,\n\t\t`Content-Type: ${result.contentType}`,\n\t\t`Method: ${result.method}`,\n\t\t...(result.notes.length ? [`Notes: ${result.notes.join(\"; \")}`] : []),\n\t].join(\"\\n\");\n\treturn `${header}\\n\\n---\\n\\n${result.content}`;\n}\n\nfunction persistReadUrlArtifact(artifactsDir: string | undefined, output: string): string | undefined {\n\tif (!artifactsDir) return undefined;\n\treturn getArtifactManager(artifactsDir).save(output, \"read\");\n}\n\nexport interface ExecuteReadUrlResult {\n\tcontent: string;\n\tdetails: ReadUrlToolDetails;\n\tartifactId?: string;\n}\n\nexport interface LoadedReadUrl {\n\toutput: string;\n\tdetails: ReadUrlToolDetails;\n\tartifactId?: string;\n\traw: boolean;\n}\n\n/**\n * Resolve a URL to its full rendered (or raw) output, using the session-scoped\n * cache and persisting the rendered body as a `read` artifact. Returns the\n * complete untruncated output so callers can apply their own line selection.\n */\nexport async function loadReadUrlOutput(\n\tscope: string,\n\tparams: { path: string; raw?: boolean },\n\tartifactsDir: string | undefined,\n\tsignal?: AbortSignal,\n): Promise<LoadedReadUrl> {\n\tconst parsed = parseReadUrlTarget(params.path);\n\tif (!parsed) throw new Error(`Not a readable URL: ${params.path}`);\n\tconst raw = params.raw ?? parsed.raw;\n\tconst key = getReadUrlCacheKey(scope, parsed.url, raw);\n\tlet entry = readUrlCache.get(key);\n\tif (!entry) {\n\t\tconst rendered = await renderUrl(parsed.url, raw, signal);\n\t\tconst output = raw ? rendered.content : buildUrlReadOutput(rendered);\n\t\tconst artifactId = persistReadUrlArtifact(artifactsDir, output);\n\t\tconst details: ReadUrlToolDetails = {\n\t\t\turl: parsed.url,\n\t\t\tfinalUrl: rendered.finalUrl,\n\t\t\tcontentType: rendered.contentType,\n\t\t\tmethod: rendered.method,\n\t\t\ttruncated: rendered.truncated,\n\t\t\tnotes: rendered.notes,\n\t\t\tmeta: artifactId ? { artifactId } : undefined,\n\t\t};\n\t\tentry = { artifactId, details, output };\n\t\treadUrlCache.set(key, entry);\n\t\treadUrlCache.set(getReadUrlCacheKey(scope, rendered.finalUrl, raw), entry);\n\t}\n\treturn { output: entry.output, details: entry.details, artifactId: entry.artifactId, raw };\n}\n\nexport async function executeReadUrl(\n\tscope: string,\n\tparams: { path: string; raw?: boolean },\n\tartifactsDir: string | undefined,\n\tsignal?: AbortSignal,\n): Promise<ExecuteReadUrlResult> {\n\tconst loaded = await loadReadUrlOutput(scope, params, artifactsDir, signal);\n\tconst entry = { output: loaded.output, details: loaded.details, artifactId: loaded.artifactId };\n\tconst fetchDefaultBytes = 50 * 1024;\n\tconst lines = entry.output.split(\"\\n\");\n\tconst visibleLines = lines.slice(0, FETCH_DEFAULT_MAX_LINES);\n\tlet content = visibleLines.join(\"\\n\");\n\tconst bytesBeforeByteClamp = Buffer.byteLength(content, \"utf8\");\n\tconst byteTruncated = bytesBeforeByteClamp > fetchDefaultBytes;\n\tconst lineTruncated = lines.length > FETCH_DEFAULT_MAX_LINES;\n\tif (byteTruncated) content = content.slice(0, fetchDefaultBytes);\n\tconst truncated = lineTruncated || byteTruncated;\n\tlet artifactId = entry.artifactId;\n\tif (truncated && !artifactId) artifactId = persistReadUrlArtifact(artifactsDir, entry.output);\n\tconst outputLines = content.length === 0 ? 0 : content.split(\"\\n\").length;\n\tconst truncation: TruncationResult | undefined = truncated\n\t\t? {\n\t\t\t\tcontent,\n\t\t\t\ttruncated: true,\n\t\t\t\ttruncatedBy: byteTruncated ? \"bytes\" : \"lines\",\n\t\t\t\ttotalLines: lines.length,\n\t\t\t\ttotalBytes: Buffer.byteLength(entry.output, \"utf8\"),\n\t\t\t\toutputLines,\n\t\t\t\toutputBytes: Buffer.byteLength(content, \"utf8\"),\n\t\t\t\tlastLinePartial: byteTruncated,\n\t\t\t\tfirstLineExceedsLimit: false,\n\t\t\t\tmaxLines: FETCH_DEFAULT_MAX_LINES,\n\t\t\t\tmaxBytes: fetchDefaultBytes,\n\t\t\t}\n\t\t: undefined;\n\tconst details: ReadUrlToolDetails = {\n\t\t...entry.details,\n\t\ttruncated,\n\t\tmeta: {\n\t\t\t...(entry.details.meta ?? {}),\n\t\t\t...(artifactId ? { artifactId } : {}),\n\t\t\t...(truncation ? { truncation } : {}),\n\t\t},\n\t};\n\tif (truncated)\n\t\tcontent += `\\n\\n[Showing first ${visibleLines.length} of ${lines.length} lines.${artifactId ? ` Full output: artifact://${artifactId}` : \"\"}]`;\n\treturn { content, details, artifactId };\n}\n\nexport function resetReadUrlCache(): void {\n\treadUrlCache.clear();\n}\n"]}
1
+ {"version":3,"file":"fetch-url.js","sourceRoot":"","sources":["../../../src/core/tools/fetch-url.ts"],"names":[],"mappings":"AAAA,kDAAkD;AAClD;;;;;;;;;;;;;;GAcG;AACH,OAAO,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAC3C,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AACrC,OAAO,eAAe,MAAM,UAAU,CAAC;AACvC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AAuB;YACjC,QAAQ,EAAE,iBAAiB;SAC3B;QACF,CAAC,CAAC,SAAS,CAAC;IACb,MAAM,OAAO,GAAuB;QACnC,GAAG,KAAK,CAAC,OAAO;QAChB,SAAS;QACT,IAAI,EAAE;YACL,GAAG,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,IAAI,EAAE,CAAC;YAC7B,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,EAAE,UAAU,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;YACrC,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,EAAE,UAAU,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SACrC;KACD,CAAC;IACF,IAAI,SAAS;QACZ,OAAO,IAAI,sBAAsB,YAAY,CAAC,MAAM,OAAO,KAAK,CAAC,MAAM,UAAU,UAAU,CAAC,CAAC,CAAC,4BAA4B,UAAU,EAAE,CAAC,CAAC,CAAC,EAAE,GAAG,CAAC;IAChJ,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,CAAC;AACzC,CAAC;AAED,MAAM,UAAU,iBAAiB;IAChC,YAAY,CAAC,KAAK,EAAE,CAAC;AACtB,CAAC","sourcesContent":["/// <reference path=\"../../utils/turndown.d.ts\" />\n/**\n * URL fetch / cache / artifact / markdown-discovery pipeline, mirrored from\n * oh-my-pi's `packages/coding-agent/src/tools/fetch.ts` at 15b5c1397fc.\n *\n * Responsibilities:\n * - parseReadUrlTarget: URL + line selectors (:raw, :N, :A-B, :A+B, :A-B,C-D),\n * collapsed-scheme repair, host-port protection.\n * - session-scoped LRU cache keyed by `<scope>::<raw|rendered>::<normalizedUrl>`,\n * cached under both requested and final (redirected) URLs.\n * - renderUrl: markdown discovery (alternate <link>, .md suffix, content\n * negotiation, llms.txt/llms.md endpoints) + native HTML-to-markdown, with\n * quality gating.\n * - artifact persistence of the rendered output, with artifactId surfaced in\n * truncation metadata when the visible output is head-truncated.\n */\nimport { lookup } from \"node:dns/promises\";\nimport { LRUCache } from \"lru-cache\";\nimport TurndownService from \"turndown\";\nimport { Agent, type Dispatcher, request as undiciRequest } from \"undici\";\nimport { getArtifactManager } from \"./artifacts.ts\";\nimport { extractDocumentMarkdown, isDocumentPath } from \"./read-document-extract.ts\";\nimport type { TruncationResult } from \"./truncate.ts\";\nimport { ipFamily, isPrivateIpAddress, normalizeIpLiteralHost } from \"./url-ip-guards.ts\";\n\nexport const FETCH_DEFAULT_MAX_LINES = 300;\nexport const READ_URL_CACHE_MAX_ENTRIES = 100;\nconst REMOTE_FETCH_TIMEOUT_MS = 10_000;\nconst MAX_URL_REDIRECTS = 5;\nconst MAX_URL_RESPONSE_BYTES = 10 * 1024 * 1024;\nconst MIN_CONTENT_LENGTH = 100;\n\nexport interface LineRange {\n\tstart: number;\n\tend?: number;\n}\n\nexport interface ParsedReadUrlTarget {\n\turl: string;\n\traw: boolean;\n\toffset?: number;\n\tlimit?: number;\n\tranges?: readonly LineRange[];\n}\n\nexport interface ReadUrlToolDetails {\n\turl: string;\n\tfinalUrl: string;\n\tcontentType: string;\n\tmethod: string;\n\ttruncated: boolean;\n\tnotes: string[];\n\tmeta?: { artifactId?: string; truncation?: TruncationResult };\n}\n\ninterface ReadUrlCacheEntry {\n\tartifactId?: string;\n\tdetails: ReadUrlToolDetails;\n\toutput: string;\n}\n\nexport interface LoadedPage {\n\tok: boolean;\n\tstatus: number;\n\tcontent: string;\n\tcontentType: string;\n\tfinalUrl: string;\n}\n\nconst readUrlCache = new LRUCache<string, ReadUrlCacheEntry>({ max: READ_URL_CACHE_MAX_ENTRIES });\nlet turndown: TurndownService | undefined;\nfunction getTurndown(): TurndownService {\n\tif (!turndown)\n\t\tturndown = new TurndownService({ headingStyle: \"atx\", codeBlockStyle: \"fenced\", bulletListMarker: \"-\" });\n\treturn turndown;\n}\n\nexport function repairCollapsedScheme(url: string): string {\n\treturn url.replace(/^(https?):\\/([^/])/i, \"$1://$2\");\n}\n\nexport function isReadableUrlPath(readPath: string): boolean {\n\tconst repaired = repairCollapsedScheme(readPath);\n\treturn /^https?:\\/\\//i.test(repaired) || /^www\\./i.test(readPath);\n}\n\nfunction normalizeUrlForCache(url: string): string {\n\tconst repaired = repairCollapsedScheme(url);\n\tif (/^[a-z][a-z0-9+.-]*:\\/\\//i.test(repaired)) return repaired;\n\treturn /^https?:\\/\\//i.test(repaired) ? repaired : `https://${repaired}`;\n}\nconst RANGE_TOKEN_RE = /^(raw|\\d+(?:\\+(?:\\d+)|(?:-|\\.\\.)\\d+)?)$/i;\nconst MULTI_RANGE_RE = /^\\d+(?:(?:-|\\.\\.|,|\\+)\\d+)*$/;\n\nfunction isUrlSelectorToken(token: string): boolean {\n\treturn /^raw$/i.test(token) || RANGE_TOKEN_RE.test(token) || MULTI_RANGE_RE.test(token);\n}\n\nfunction parseSingleRange(token: string): LineRange | undefined {\n\tconst plus = token.match(/^(\\d+)\\+(\\d+)$/);\n\tif (plus) {\n\t\tconst start = Number.parseInt(plus[1]!, 10),\n\t\t\tcount = Number.parseInt(plus[2]!, 10);\n\t\treturn start < 1 || count < 1 ? undefined : { start, end: start + count - 1 };\n\t}\n\tconst range = token.match(/^(\\d+)(?:-|\\.\\.)(\\d+)$/);\n\tif (range) {\n\t\tconst start = Number.parseInt(range[1]!, 10);\n\t\tconst end = Number.parseInt(range[2]!, 10);\n\t\treturn start < 1 || end < start ? undefined : { start, end };\n\t}\n\tconst single = token.match(/^(\\d+)$/);\n\tif (single) {\n\t\tconst start = Number.parseInt(single[1]!, 10);\n\t\treturn start < 1 ? undefined : { start };\n\t}\n\treturn undefined;\n}\n\nfunction parseRangeGroup(token: string): LineRange[] | undefined {\n\tconst groups = token.split(\",\");\n\tconst ranges: LineRange[] = [];\n\tfor (const group of groups) {\n\t\tconst r = parseSingleRange(group);\n\t\tif (!r) return undefined;\n\t\tranges.push(r);\n\t}\n\treturn ranges;\n}\n\nfunction tryExtractEmbeddedUrlSelector(readPath: string): { path: string; sels: string[] } | null {\n\tlet basePath = readPath;\n\tconst sels: string[] = [];\n\tfor (;;) {\n\t\tconst lastColonIndex = basePath.lastIndexOf(\":\");\n\t\tif (lastColonIndex <= 0) break;\n\t\tconst candidate = basePath.slice(lastColonIndex + 1);\n\t\tconst remainder = basePath.slice(0, lastColonIndex);\n\t\tif (!isReadableUrlPath(remainder) || !isUrlSelectorToken(candidate)) break;\n\t\ttry {\n\t\t\tnew URL(\n\t\t\t\tremainder.startsWith(\"http://\") || remainder.startsWith(\"https://\") ? remainder : `https://${remainder}`,\n\t\t\t);\n\t\t} catch {\n\t\t\tbreak;\n\t\t}\n\t\tsels.unshift(candidate);\n\t\tbasePath = remainder;\n\t}\n\treturn sels.length === 0 ? null : { path: basePath, sels };\n}\n\nexport function parseReadUrlTarget(readPath: string): ParsedReadUrlTarget | null {\n\tconst repaired = repairCollapsedScheme(readPath);\n\tconst embedded = tryExtractEmbeddedUrlSelector(repaired);\n\tconst urlPath = embedded?.path ?? repaired;\n\tif (!isReadableUrlPath(urlPath)) return null;\n\tlet raw = false;\n\tlet ranges: LineRange[] | undefined;\n\tfor (const sel of embedded?.sels ?? []) {\n\t\tif (/^raw$/i.test(sel)) {\n\t\t\traw = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ranges !== undefined)\n\t\t\tthrow new Error(\"URL selector has multiple range groups; combine them with commas (e.g. `:5-10,20-30`).\");\n\t\tconst parsed = parseRangeGroup(sel);\n\t\tif (!parsed) throw new Error(`Invalid URL line selector: ${sel}`);\n\t\tranges = parsed;\n\t}\n\tif (!ranges || ranges.length === 0) return { url: urlPath, raw };\n\tif (ranges.length === 1) {\n\t\tconst r = ranges[0]!;\n\t\treturn { url: urlPath, raw, offset: r.start, limit: r.end !== undefined ? r.end - r.start + 1 : undefined };\n\t}\n\treturn { url: urlPath, raw, ranges };\n}\n\nexport function getReadUrlCacheKey(scope: string, requestedUrl: string, raw: boolean): string {\n\treturn `${scope}::${raw ? \"raw\" : \"rendered\"}::${normalizeUrlForCache(requestedUrl)}`;\n}\n\nfunction looksLikeHtml(text: string): boolean {\n\treturn /<html[\\s>]/i.test(text) || (/<head[\\s>]/i.test(text) && /<body[\\s>]/i.test(text));\n}\n\nfunction documentExtensionFromContentType(contentType: string): string | undefined {\n\tif (/pdf/i.test(contentType)) return \".pdf\";\n\tif (/msword/i.test(contentType)) return \".doc\";\n\tif (/wordprocessingml|officedocument\\.word/i.test(contentType)) return \".docx\";\n\tif (/presentationml|officedocument\\.presentation/i.test(contentType)) return \".pptx\";\n\tif (/ms-powerpoint|vnd\\.ms-powerpoint/i.test(contentType)) return \".ppt\";\n\tif (/spreadsheetml|officedocument\\.spreadsheet/i.test(contentType)) return \".xlsx\";\n\tif (/ms-excel|vnd\\.ms-excel/i.test(contentType)) return \".xls\";\n\tif (/epub/i.test(contentType)) return \".epub\";\n\tif (/\\bjson\\b|ipynb|jupyter/i.test(contentType)) return \".ipynb\";\n\tif (/rtf/i.test(contentType)) return \".rtf\";\n\treturn undefined;\n}\n\ninterface SafeFetchAddress {\n\taddress: string;\n\tfamily:\n\t\t| 4\n\t\t| 6 /** True only when the address came from DNS resolution and must be pinned to prevent rebinding at connect time. */;\n\tpinned: boolean;\n}\ntype LookupCallback = (\n\terror: NodeJS.ErrnoException | null,\n\taddress: string | SafeFetchAddress[],\n\tfamily?: number,\n) => void;\n\nfunction createPinnedDispatcher(pinned: SafeFetchAddress): Agent {\n\treturn new Agent({\n\t\tconnect: {\n\t\t\tlookup: (_hostname: string, options: { all?: boolean }, callback: LookupCallback) => {\n\t\t\t\tif (options.all) callback(null, [pinned]);\n\t\t\t\telse callback(null, pinned.address, pinned.family);\n\t\t\t},\n\t\t},\n\t});\n}\n\ninterface ResponseBodyStream extends NodeJS.ReadableStream {\n\ton(event: \"data\", listener: (chunk: Buffer) => void): this;\n\ton(event: \"end\" | \"close\", listener: () => void): this;\n\ton(event: \"error\", listener: (error: unknown) => void): this;\n\tremoveListener(event: \"data\", listener: (chunk: Buffer) => void): this;\n\tremoveListener(event: \"end\" | \"close\", listener: () => void): this;\n\tremoveListener(event: \"error\", listener: (error: unknown) => void): this;\n\tdestroy(error?: Error): this;\n\tpause(): this;\n}\n\nfunction toReadableStreamError(error: unknown): Error {\n\treturn error instanceof Error ? error : new Error(String(error));\n}\n\nexport function createPinnedResponseBodyStream(body: ResponseBodyStream): ReadableStream<Uint8Array> {\n\tlet controller: ReadableStreamDefaultController<Uint8Array> | undefined;\n\tlet terminal = false;\n\tlet ended = false;\n\tlet cleanedUp = false;\n\n\tconst detachDataListeners = () => {\n\t\tbody.removeListener(\"data\", onData);\n\t\tbody.removeListener(\"end\", onEnd);\n\t};\n\tconst cleanup = () => {\n\t\tif (cleanedUp) return;\n\t\tcleanedUp = true;\n\t\tdetachDataListeners();\n\t\tbody.removeListener(\"error\", onError);\n\t\tbody.removeListener(\"close\", onClose);\n\t};\n\tconst closeStream = () => {\n\t\tif (terminal) return;\n\t\tterminal = true;\n\t\tdetachDataListeners();\n\t\tcontroller?.close();\n\t};\n\tconst onData = (chunk: Buffer) => {\n\t\tif (terminal) return;\n\t\tcontroller?.enqueue(new Uint8Array(chunk));\n\t};\n\tconst onEnd = () => {\n\t\tended = true;\n\t\tcloseStream();\n\t};\n\tconst onError = (error: unknown) => {\n\t\tif (terminal) return;\n\t\tterminal = true;\n\t\tdetachDataListeners();\n\t\tcontroller?.error(toReadableStreamError(error));\n\t};\n\tconst onClose = () => {\n\t\t// `close` without a preceding `end` is a premature termination (reset,\n\t\t// abort, truncation). Reporting it as a clean EOF would hand partial\n\t\t// response content to the consumer as a successful read.\n\t\tif (!terminal && !ended) {\n\t\t\tterminal = true;\n\t\t\tdetachDataListeners();\n\t\t\tcontroller?.error(new Error(\"response body closed before the stream ended\"));\n\t\t} else {\n\t\t\tcloseStream();\n\t\t}\n\t\tcleanup();\n\t};\n\treturn new ReadableStream<Uint8Array>({\n\t\tstart(streamController) {\n\t\t\tcontroller = streamController;\n\t\t\tbody.on(\"data\", onData);\n\t\t\tbody.on(\"end\", onEnd);\n\t\t\tbody.on(\"error\", onError);\n\t\t\tbody.on(\"close\", onClose);\n\t\t},\n\t\tcancel() {\n\t\t\tif (terminal) return;\n\t\t\tterminal = true;\n\t\t\tdetachDataListeners();\n\t\t\tbody.pause?.();\n\t\t\tbody.destroy();\n\t\t},\n\t});\n}\n\nasync function closePinnedDispatcher(dispatcher: Agent | undefined): Promise<void> {\n\tconst close = (dispatcher as { close?: () => Promise<void> | void } | undefined)?.close;\n\tif (typeof close === \"function\") await close.call(dispatcher);\n}\n/**\n * Fetch a URL through undici with the pinned dispatcher so the validated\n * address is the one actually connected to. Unlike `globalThis.fetch`, which\n * silently ignores the undici `dispatcher` option under Bun's compiled binary\n * (reopening a DNS-rebinding TOCTOU window for hostname targets), undici's own\n * client honors the dispatcher's custom `lookup` regardless of host runtime.\n * Adapts the undici response to the WHATWG-Response shape loadPage consumes.\n */\nasync function pinnedFetch(\n\turl: string,\n\tdispatcher: Dispatcher,\n\toptions: { signal: AbortSignal; headers?: Record<string, string> },\n): Promise<Response> {\n\tconst result = await undiciRequest(url, {\n\t\tmethod: \"GET\",\n\t\tdispatcher,\n\t\tsignal: options.signal,\n\t\theaders: options.headers,\n\t});\n\tconst body = result.body;\n\tconst status = result.statusCode;\n\tconst headers = new Headers();\n\tfor (const [key, value] of Object.entries(result.headers as Record<string, string | string[] | undefined>)) {\n\t\tif (value === undefined) continue;\n\t\tconst values = Array.isArray(value) ? value : [value];\n\t\tfor (const entry of values) headers.append(key, entry);\n\t}\n\tconst stream = createPinnedResponseBodyStream(body);\n\treturn new Response(stream, { status, headers });\n}\n\nasync function assertSafeFetchUrl(url: string): Promise<SafeFetchAddress | undefined> {\n\tconst parsed = new URL(url);\n\tif (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\")\n\t\tthrow new Error(`Unsupported URL protocol: ${parsed.protocol}`);\n\tif (process.env.ATOMIC_ALLOW_PRIVATE_URL_READS === \"1\") return undefined;\n\tconst hostname = parsed.hostname\n\t\t.replace(/^\\[|\\]$/g, \"\")\n\t\t.replace(/\\.$/, \"\")\n\t\t.toLowerCase();\n\tif (hostname === \"localhost\" || hostname.endsWith(\".localhost\") || hostname === \"metadata.google.internal\")\n\t\tthrow new Error(`Refusing to fetch private or metadata URL: ${url}`);\n\tconst literalAddress = normalizeIpLiteralHost(hostname);\n\tif (literalAddress) {\n\t\tif (isPrivateIpAddress(literalAddress)) throw new Error(`Refusing to fetch private or metadata URL: ${url}`);\n\t\treturn { address: literalAddress, family: ipFamily(literalAddress), pinned: false };\n\t}\n\tconst addresses = await lookup(hostname, { all: true }).catch((error: unknown) => {\n\t\tthrow new Error(\n\t\t\t`Could not resolve URL host ${hostname}: ${error instanceof Error ? error.message : String(error)}`,\n\t\t);\n\t});\n\tif (addresses.length === 0) throw new Error(`Could not resolve URL host ${hostname}: no addresses returned`);\n\tfor (const address of addresses)\n\t\tif (isPrivateIpAddress(address.address)) throw new Error(`Refusing to fetch private or metadata URL: ${url}`);\n\tconst first = addresses[0]!;\n\treturn { address: first.address, family: first.family === 6 ? 6 : 4, pinned: true };\n}\n\nasync function readResponseTextWithLimit(response: Response): Promise<string> {\n\tif (!response.body) {\n\t\tconst buffer = Buffer.from(await response.arrayBuffer());\n\t\tif (buffer.length > MAX_URL_RESPONSE_BYTES)\n\t\t\tthrow new Error(`URL response exceeds ${MAX_URL_RESPONSE_BYTES} byte limit`);\n\t\treturn buffer.toString(\"utf8\");\n\t}\n\tconst reader = response.body.getReader();\n\tconst decoder = new TextDecoder();\n\tconst chunks: string[] = [];\n\tlet totalBytes = 0;\n\tfor (;;) {\n\t\tconst { done, value } = await reader.read();\n\t\tif (done) break;\n\t\ttotalBytes += value.byteLength;\n\t\tif (totalBytes > MAX_URL_RESPONSE_BYTES) {\n\t\t\tawait reader.cancel();\n\t\t\tthrow new Error(`URL response exceeds ${MAX_URL_RESPONSE_BYTES} byte limit`);\n\t\t}\n\t\tchunks.push(decoder.decode(value, { stream: true }));\n\t}\n\tchunks.push(decoder.decode());\n\treturn chunks.join(\"\");\n}\nexport async function loadPage(\n\turl: string,\n\ttimeoutMs: number,\n\tsignal?: AbortSignal,\n\taccept?: string,\n): Promise<LoadedPage> {\n\turl = normalizeUrlForCache(url);\n\tconst controller = new AbortController();\n\tconst timer = setTimeout(() => controller.abort(), Math.min(timeoutMs, REMOTE_FETCH_TIMEOUT_MS));\n\tconst onParentAbort = () => controller.abort();\n\tsignal?.addEventListener(\"abort\", onParentAbort, { once: true });\n\ttry {\n\t\tlet currentUrl = url;\n\t\tfor (let redirects = 0; redirects <= MAX_URL_REDIRECTS; redirects++) {\n\t\t\tconst pinned = await assertSafeFetchUrl(currentUrl);\n\t\t\t// Only a DNS-resolved hostname needs pinning: a literal-IP host is\n\t\t\t// validated directly and cannot be re-resolved at connect time, so\n\t\t\t// global fetch is sufficient and stays redirect/mock-friendly.\n\t\t\tconst dispatcher = pinned?.pinned ? createPinnedDispatcher(pinned) : undefined;\n\t\t\ttry {\n\t\t\t\tconst headers = accept ? { Accept: accept } : undefined;\n\t\t\t\t// Route pinned (hostname) fetches through undici directly so the\n\t\t\t\t// dispatcher's custom lookup is honored even under Bun's compiled\n\t\t\t\t// fetch, which silently ignores the `dispatcher` option.\n\t\t\t\tconst response = dispatcher\n\t\t\t\t\t? await pinnedFetch(currentUrl, dispatcher, { signal: controller.signal, headers })\n\t\t\t\t\t: await fetch(currentUrl, { signal: controller.signal, headers, redirect: \"manual\" });\n\t\t\t\tif (response.status >= 300 && response.status < 400 && response.headers.get(\"location\")) {\n\t\t\t\t\tawait response.body?.cancel().catch(() => {});\n\t\t\t\t\tcurrentUrl = new URL(response.headers.get(\"location\")!, currentUrl).href;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst contentLength = Number.parseInt(response.headers.get(\"content-length\") ?? \"0\", 10);\n\t\t\t\tif (contentLength > MAX_URL_RESPONSE_BYTES)\n\t\t\t\t\tthrow new Error(`URL response exceeds ${MAX_URL_RESPONSE_BYTES} byte limit: ${currentUrl}`);\n\t\t\t\tconst contentType = response.headers.get(\"content-type\") ?? \"\";\n\t\t\t\tconst content = await readResponseTextWithLimit(response);\n\t\t\t\treturn {\n\t\t\t\t\tok: response.ok,\n\t\t\t\t\tstatus: response.status,\n\t\t\t\t\tcontent,\n\t\t\t\t\tcontentType,\n\t\t\t\t\tfinalUrl: response.url || currentUrl,\n\t\t\t\t};\n\t\t\t} finally {\n\t\t\t\tawait closePinnedDispatcher(dispatcher).catch(() => undefined);\n\t\t\t}\n\t\t}\n\t\tthrow new Error(`Too many redirects while fetching URL: ${url}`);\n\t} finally {\n\t\tclearTimeout(timer);\n\t\tsignal?.removeEventListener(\"abort\", onParentAbort);\n\t}\n}\n\nfunction isLowQuality(content: string): boolean {\n\tconst lower = content.toLowerCase();\n\tif (\n\t\t/(enable javascript|javascript required|turn on javascript|please enable javascript|browser not supported)/.test(\n\t\t\tlower,\n\t\t) &&\n\t\tcontent.trim().length < 2000\n\t)\n\t\treturn true;\n\tconst nonblank = content.split(\"\\n\").filter((line) => line.trim().length > 0);\n\tif (nonblank.length > 10 && nonblank.filter((line) => line.trim().length < 40).length / nonblank.length > 0.7)\n\t\treturn true;\n\treturn false;\n}\n\nfunction buildLlmEndpointCandidates(url: string): string[] {\n\tconst parsed = (() => {\n\t\ttry {\n\t\t\treturn new URL(url);\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t})();\n\tif (!parsed) return [];\n\tconst origin = parsed.origin;\n\tif (parsed.pathname === \"/\" || parsed.pathname === \"\")\n\t\treturn [`${origin}/.well-known/llms.txt`, `${origin}/llms.txt`, `${origin}/llms.md`];\n\tconst trimmed = parsed.pathname.replace(/\\/+$/, \"\");\n\tconst segments = trimmed.split(\"/\").filter(Boolean);\n\tconst candidates: string[] = [];\n\tconst depth = parsed.pathname.endsWith(\"/\") ? segments.length : Math.max(segments.length - 1, 1);\n\tfor (let scope = Math.min(depth, segments.length); scope >= 1; scope--) {\n\t\tconst base = `${origin}/${segments.slice(0, scope).join(\"/\")}`;\n\t\tcandidates.push(`${base}/llms.txt`, `${base}/llms.md`);\n\t}\n\tcandidates.push(`${origin}/llms.txt`, `${origin}/llms.md`);\n\treturn [...new Set(candidates)];\n}\n\nasync function tryLlmEndpoints(\n\turl: string,\n\tsignal?: AbortSignal,\n): Promise<{ content: string; endpoint: string } | null> {\n\tfor (const endpoint of buildLlmEndpointCandidates(url)) {\n\t\ttry {\n\t\t\tconst page = await loadPage(endpoint, 5000, signal);\n\t\t\tif (page.ok && page.content.trim().length > MIN_CONTENT_LENGTH && !looksLikeHtml(page.content))\n\t\t\t\treturn { content: page.content, endpoint };\n\t\t} catch {}\n\t}\n\treturn null;\n}\n\nfunction parseAlternateMarkdownLink(html: string, pageUrl: string): string | undefined {\n\tconst headEnd = html.toLowerCase().indexOf(\"</head>\");\n\tconst head = html.slice(0, headEnd >= 0 ? headEnd + 7 : html.length);\n\tconst links = [...head.matchAll(/<link\\b[^>]*>/gi)].map((m) => m[0] ?? \"\");\n\tfor (const tag of links) {\n\t\tconst rel = /rel=[\"']?([^\"'>]+)[\"']?/i.exec(tag)?.[1] ?? \"\";\n\t\tconst type = /type=[\"']?([^\"'>]+)[\"']?/i.exec(tag)?.[1] ?? \"\";\n\t\tconst href = /href=[\"']?([^\"'>]+)[\"']?/i.exec(tag)?.[1] ?? \"\";\n\t\tif (!/alternate/i.test(rel) || !href) continue;\n\t\tif (/RecentChanges|Special:|\\/feed\\/|action=feed/i.test(href)) continue;\n\t\tif (type.includes(\"markdown\") || href.endsWith(\".md\")) {\n\t\t\ttry {\n\t\t\t\treturn new URL(href, pageUrl).href;\n\t\t\t} catch {}\n\t\t}\n\t}\n\treturn undefined;\n}\n\nasync function tryMdSuffix(url: string, signal?: AbortSignal): Promise<string | null> {\n\tconst candidates: string[] = [];\n\tif (/\\/$/.test(url)) candidates.push(`${url}index.html.md`);\n\telse if (/\\.\\w+\\/?$/.test(url)) candidates.push(`${url}.md`);\n\telse candidates.push(`${url}.md`, `${url}/index.html.md`);\n\tfor (const candidate of candidates) {\n\t\ttry {\n\t\t\tconst page = await loadPage(candidate, 5000, signal);\n\t\t\tif (page.ok && page.content.trim().length > MIN_CONTENT_LENGTH && !looksLikeHtml(page.content))\n\t\t\t\treturn page.content;\n\t\t} catch {}\n\t}\n\treturn null;\n}\n\nasync function tryContentNegotiation(url: string, signal?: AbortSignal): Promise<string | null> {\n\ttry {\n\t\tconst page = await loadPage(url, 5000, signal, \"text/markdown, text/plain;q=0.9, text/html;q=0.8\");\n\t\tconst mime = page.contentType.toLowerCase();\n\t\tif (\n\t\t\tpage.ok &&\n\t\t\tpage.content.trim().length > MIN_CONTENT_LENGTH &&\n\t\t\t!looksLikeHtml(page.content) &&\n\t\t\t(mime.includes(\"markdown\") || mime.includes(\"text/plain\"))\n\t\t)\n\t\t\treturn page.content;\n\t} catch {}\n\treturn null;\n}\n\nexport interface RenderedUrl {\n\tcontent: string;\n\tfinalUrl: string;\n\tcontentType: string;\n\tmethod: string;\n\tnotes: string[];\n\ttruncated: boolean;\n}\n\nexport async function renderUrl(url: string, raw: boolean, signal?: AbortSignal): Promise<RenderedUrl> {\n\tconst notes: string[] = [];\n\tlet method = \"text\";\n\tlet contentType = \"\";\n\tlet finalUrl: string;\n\tlet body = \"\";\n\tconst page = await loadPage(url, REMOTE_FETCH_TIMEOUT_MS, signal);\n\tfinalUrl = page.finalUrl;\n\tcontentType = page.contentType;\n\tif (!page.ok)\n\t\treturn {\n\t\t\tcontent: page.content || `(request failed with status ${page.status})`,\n\t\t\tfinalUrl,\n\t\t\tcontentType,\n\t\t\tmethod: \"failed\",\n\t\t\tnotes,\n\t\t\ttruncated: false,\n\t\t};\n\tif (raw) return { content: page.content, finalUrl, contentType, method: \"raw\", notes, truncated: false };\n\tconst buffer = Buffer.from(page.content, \"utf8\");\n\tconst docExt =\n\t\tdocumentExtensionFromContentType(contentType) ??\n\t\t(isDocumentPath(finalUrl) ? (finalUrl.match(/\\.\\w+(?:$|[?#])/)?.[0] ?? \"\") : \"\");\n\tif (docExt) {\n\t\ttry {\n\t\t\tbody = await extractDocumentMarkdown(buffer, `${finalUrl}${docExt}`);\n\t\t\tmethod = \"document\";\n\t\t} catch (error) {\n\t\t\tbody = `[Cannot read ${docExt} file: ${error instanceof Error ? error.message : \"conversion failed\"}]`;\n\t\t\tmethod = \"document-error\";\n\t\t}\n\t\treturn { content: body, finalUrl, contentType, method, notes, truncated: false };\n\t}\n\tconst isHtml = /html/i.test(contentType) || looksLikeHtml(page.content);\n\tif (isHtml) {\n\t\tconst altMd = parseAlternateMarkdownLink(page.content, finalUrl);\n\t\tif (altMd) {\n\t\t\ttry {\n\t\t\t\tconst alt = await loadPage(altMd, 5000, signal);\n\t\t\t\tif (alt.ok && alt.content.trim().length > MIN_CONTENT_LENGTH && !looksLikeHtml(alt.content)) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: alt.content,\n\t\t\t\t\t\tfinalUrl: alt.finalUrl,\n\t\t\t\t\t\tcontentType: alt.contentType,\n\t\t\t\t\t\tmethod: \"alternate-markdown\",\n\t\t\t\t\t\tnotes,\n\t\t\t\t\t\ttruncated: false,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t} catch {}\n\t\t\tnotes.push(\"alternate markdown link unusable\");\n\t\t}\n\t\tconst md = await tryMdSuffix(finalUrl, signal);\n\t\tif (md)\n\t\t\treturn { content: md, finalUrl, contentType: \"text/markdown\", method: \"md-suffix\", notes, truncated: false };\n\t\tconst neg = await tryContentNegotiation(finalUrl, signal);\n\t\tif (neg)\n\t\t\treturn {\n\t\t\t\tcontent: neg,\n\t\t\t\tfinalUrl,\n\t\t\t\tcontentType: \"text/markdown\",\n\t\t\t\tmethod: \"content-negotiation\",\n\t\t\t\tnotes,\n\t\t\t\ttruncated: false,\n\t\t\t};\n\t\tconst rendered = getTurndown().turndown(page.content).trim();\n\t\tmethod = \"native\";\n\t\tif (rendered.length <= MIN_CONTENT_LENGTH || isLowQuality(rendered)) {\n\t\t\tconst llms = await tryLlmEndpoints(finalUrl, signal);\n\t\t\tif (llms) {\n\t\t\t\treturn {\n\t\t\t\t\tcontent: llms.content,\n\t\t\t\t\tfinalUrl,\n\t\t\t\t\tcontentType: \"text/plain\",\n\t\t\t\t\tmethod: `llms-txt (${llms.endpoint})`,\n\t\t\t\t\tnotes,\n\t\t\t\t\ttruncated: false,\n\t\t\t\t};\n\t\t\t}\n\t\t\tnotes.push(\"rendered content low quality; no markdown source discovered\");\n\t\t}\n\t\tbody = rendered;\n\t} else {\n\t\tbody = page.content;\n\t}\n\treturn { content: body, finalUrl, contentType, method, notes, truncated: false };\n}\n\nexport function buildUrlReadOutput(result: RenderedUrl): string {\n\tconst header = [\n\t\t`URL: ${result.finalUrl}`,\n\t\t`Content-Type: ${result.contentType}`,\n\t\t`Method: ${result.method}`,\n\t\t...(result.notes.length ? [`Notes: ${result.notes.join(\"; \")}`] : []),\n\t].join(\"\\n\");\n\treturn `${header}\\n\\n---\\n\\n${result.content}`;\n}\n\nfunction persistReadUrlArtifact(artifactsDir: string | undefined, output: string): string | undefined {\n\tif (!artifactsDir) return undefined;\n\treturn getArtifactManager(artifactsDir).save(output, \"read\");\n}\n\nexport interface ExecuteReadUrlResult {\n\tcontent: string;\n\tdetails: ReadUrlToolDetails;\n\tartifactId?: string;\n}\n\nexport interface LoadedReadUrl {\n\toutput: string;\n\tdetails: ReadUrlToolDetails;\n\tartifactId?: string;\n\traw: boolean;\n}\n\n/**\n * Resolve a URL to its full rendered (or raw) output, using the session-scoped\n * cache and persisting the rendered body as a `read` artifact. Returns the\n * complete untruncated output so callers can apply their own line selection.\n */\nexport async function loadReadUrlOutput(\n\tscope: string,\n\tparams: { path: string; raw?: boolean },\n\tartifactsDir: string | undefined,\n\tsignal?: AbortSignal,\n): Promise<LoadedReadUrl> {\n\tconst parsed = parseReadUrlTarget(params.path);\n\tif (!parsed) throw new Error(`Not a readable URL: ${params.path}`);\n\tconst raw = params.raw ?? parsed.raw;\n\tconst key = getReadUrlCacheKey(scope, parsed.url, raw);\n\tlet entry = readUrlCache.get(key);\n\tif (!entry) {\n\t\tconst rendered = await renderUrl(parsed.url, raw, signal);\n\t\tconst output = raw ? rendered.content : buildUrlReadOutput(rendered);\n\t\tconst artifactId = persistReadUrlArtifact(artifactsDir, output);\n\t\tconst details: ReadUrlToolDetails = {\n\t\t\turl: parsed.url,\n\t\t\tfinalUrl: rendered.finalUrl,\n\t\t\tcontentType: rendered.contentType,\n\t\t\tmethod: rendered.method,\n\t\t\ttruncated: rendered.truncated,\n\t\t\tnotes: rendered.notes,\n\t\t\tmeta: artifactId ? { artifactId } : undefined,\n\t\t};\n\t\tentry = { artifactId, details, output };\n\t\treadUrlCache.set(key, entry);\n\t\treadUrlCache.set(getReadUrlCacheKey(scope, rendered.finalUrl, raw), entry);\n\t}\n\treturn { output: entry.output, details: entry.details, artifactId: entry.artifactId, raw };\n}\n\nexport async function executeReadUrl(\n\tscope: string,\n\tparams: { path: string; raw?: boolean },\n\tartifactsDir: string | undefined,\n\tsignal?: AbortSignal,\n): Promise<ExecuteReadUrlResult> {\n\tconst loaded = await loadReadUrlOutput(scope, params, artifactsDir, signal);\n\tconst entry = { output: loaded.output, details: loaded.details, artifactId: loaded.artifactId };\n\tconst fetchDefaultBytes = 50 * 1024;\n\tconst lines = entry.output.split(\"\\n\");\n\tconst visibleLines = lines.slice(0, FETCH_DEFAULT_MAX_LINES);\n\tlet content = visibleLines.join(\"\\n\");\n\tconst bytesBeforeByteClamp = Buffer.byteLength(content, \"utf8\");\n\tconst byteTruncated = bytesBeforeByteClamp > fetchDefaultBytes;\n\tconst lineTruncated = lines.length > FETCH_DEFAULT_MAX_LINES;\n\tif (byteTruncated) content = content.slice(0, fetchDefaultBytes);\n\tconst truncated = lineTruncated || byteTruncated;\n\tlet artifactId = entry.artifactId;\n\tif (truncated && !artifactId) artifactId = persistReadUrlArtifact(artifactsDir, entry.output);\n\tconst outputLines = content.length === 0 ? 0 : content.split(\"\\n\").length;\n\tconst truncation: TruncationResult | undefined = truncated\n\t\t? {\n\t\t\t\tcontent,\n\t\t\t\ttruncated: true,\n\t\t\t\ttruncatedBy: byteTruncated ? \"bytes\" : \"lines\",\n\t\t\t\ttotalLines: lines.length,\n\t\t\t\ttotalBytes: Buffer.byteLength(entry.output, \"utf8\"),\n\t\t\t\toutputLines,\n\t\t\t\toutputBytes: Buffer.byteLength(content, \"utf8\"),\n\t\t\t\tlastLinePartial: byteTruncated,\n\t\t\t\tfirstLineExceedsLimit: false,\n\t\t\t\tmaxLines: FETCH_DEFAULT_MAX_LINES,\n\t\t\t\tmaxBytes: fetchDefaultBytes,\n\t\t\t}\n\t\t: undefined;\n\tconst details: ReadUrlToolDetails = {\n\t\t...entry.details,\n\t\ttruncated,\n\t\tmeta: {\n\t\t\t...(entry.details.meta ?? {}),\n\t\t\t...(artifactId ? { artifactId } : {}),\n\t\t\t...(truncation ? { truncation } : {}),\n\t\t},\n\t};\n\tif (truncated)\n\t\tcontent += `\\n\\n[Showing first ${visibleLines.length} of ${lines.length} lines.${artifactId ? ` Full output: artifact://${artifactId}` : \"\"}]`;\n\treturn { content, details, artifactId };\n}\n\nexport function resetReadUrlCache(): void {\n\treadUrlCache.clear();\n}\n"]}
@@ -98,7 +98,7 @@ export function createCodingToolDefinitions(cwd, options) {
98
98
  const hashlineStore = options?.hashlineStore ?? createHashlineSnapshotStore();
99
99
  return [
100
100
  createReadToolDefinition(cwd, { ...options?.read, hashlineStore }),
101
- createBashToolDefinition(cwd, { asyncEnabled: true, ...options?.bash }),
101
+ createBashToolDefinition(cwd, options?.bash),
102
102
  createEditToolDefinition(cwd, { ...options?.edit, hashlineStore }),
103
103
  createWriteToolDefinition(cwd, { ...options?.write, hashlineStore }),
104
104
  createFindToolDefinition(cwd, options?.find),
@@ -118,7 +118,7 @@ export function createAllToolDefinitions(cwd, options) {
118
118
  const hashlineStore = options?.hashlineStore ?? createHashlineSnapshotStore();
119
119
  return {
120
120
  read: createReadToolDefinition(cwd, { ...options?.read, hashlineStore }),
121
- bash: createBashToolDefinition(cwd, { asyncEnabled: true, ...options?.bash }),
121
+ bash: createBashToolDefinition(cwd, options?.bash),
122
122
  edit: createEditToolDefinition(cwd, { ...options?.edit, hashlineStore }),
123
123
  write: createWriteToolDefinition(cwd, { ...options?.write, hashlineStore }),
124
124
  find: createFindToolDefinition(cwd, options?.find),
@@ -132,7 +132,7 @@ export function createCodingTools(cwd, options) {
132
132
  const hashlineStore = options?.hashlineStore ?? createHashlineSnapshotStore();
133
133
  return [
134
134
  createReadTool(cwd, { ...options?.read, hashlineStore }),
135
- createBashTool(cwd, { asyncEnabled: true, ...options?.bash }),
135
+ createBashTool(cwd, options?.bash),
136
136
  createEditTool(cwd, { ...options?.edit, hashlineStore }),
137
137
  createWriteTool(cwd, { ...options?.write, hashlineStore }),
138
138
  createFindTool(cwd, options?.find),
@@ -152,7 +152,7 @@ export function createAllTools(cwd, options) {
152
152
  const hashlineStore = options?.hashlineStore ?? createHashlineSnapshotStore();
153
153
  return {
154
154
  read: createReadTool(cwd, { ...options?.read, hashlineStore }),
155
- bash: createBashTool(cwd, { asyncEnabled: true, ...options?.bash }),
155
+ bash: createBashTool(cwd, options?.bash),
156
156
  edit: createEditTool(cwd, { ...options?.edit, hashlineStore }),
157
157
  write: createWriteTool(cwd, { ...options?.write, hashlineStore }),
158
158
  find: createFindTool(cwd, options?.find),
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/core/tools/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mCAAmC,EAAE,MAAM,8BAA8B,CAAC;AACnF,OAAO,EAON,gCAAgC,EAChC,cAAc,EACd,wBAAwB,EACxB,yBAAyB,GACzB,MAAM,WAAW,CAAC;AACnB,OAAO,EACN,cAAc,EACd,wBAAwB,EAKxB,gCAAgC,GAChC,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,qBAAqB,EAAE,MAAM,0BAA0B,CAAC;AACjE,OAAO,EACN,cAAc,EACd,wBAAwB,EAKxB,gCAAgC,GAChC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AE,CAAC;QACjE,IAAI,EAAE,cAAc,CAAC,GAAG,EAAE,OAAO,EAAE,IAAI,CAAC;QACxC,MAAM,EAAE,gBAAgB,CAAC,GAAG,EAAE,EAAE,GAAG,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,CAAC;QACpE,EAAE,EAAE,YAAY,CAAC,GAAG,EAAE,OAAO,EAAE,EAAE,CAAC;QAClC,iBAAiB,EAAE,kBAAkB,CAAC,mCAAmC,EAAE,CAAC;QAC5E,IAAI,EAAE,kBAAkB,CAAC,wBAAwB,CAAC,GAAG,CAAC,CAAC;KACvD,CAAC;AACH,CAAC","sourcesContent":["export { createAskUserQuestionToolDefinition } from \"./ask-user-question/index.ts\";\nexport {\n\ttype BashOperations,\n\ttype BashSpawnContext,\n\ttype BashSpawnHook,\n\ttype BashToolDetails,\n\ttype BashToolInput,\n\ttype BashToolOptions,\n\tbashToolSystemPromptContribution,\n\tcreateBashTool,\n\tcreateBashToolDefinition,\n\tcreateLocalBashOperations,\n} from \"./bash.ts\";\nexport {\n\tcreateEditTool,\n\tcreateEditToolDefinition,\n\ttype EditOperations,\n\ttype EditToolDetails,\n\ttype EditToolInput,\n\ttype EditToolOptions,\n\teditToolSystemPromptContribution,\n} from \"./edit.ts\";\nexport { withFileMutationQueue } from \"./file-mutation-queue.ts\";\nexport {\n\tcreateFindTool,\n\tcreateFindToolDefinition,\n\ttype FindOperations,\n\ttype FindToolDetails,\n\ttype FindToolInput,\n\ttype FindToolOptions,\n\tfindToolSystemPromptContribution,\n} from \"./find.ts\";\nexport {\n\tcreateLsTool,\n\tcreateLsToolDefinition,\n\ttype LsOperations,\n\ttype LsToolDetails,\n\ttype LsToolInput,\n\ttype LsToolOptions,\n\tlsToolSystemPromptContribution,\n} from \"./ls.ts\";\nexport {\n\tcreateReadTool,\n\tcreateReadToolDefinition,\n\ttype ReadOperations,\n\ttype ReadToolDetails,\n\ttype ReadToolInput,\n\ttype ReadToolOptions,\n\treadToolSystemPromptContribution,\n} from \"./read.ts\";\nexport {\n\tcreateSearchTool,\n\tcreateSearchToolDefinition,\n\ttype SearchToolDetails,\n\ttype SearchToolInput,\n\ttype SearchToolOptions,\n\tsearchToolSystemPromptContribution,\n} from \"./search.ts\";\nexport {\n\tcreateStructuredOutputCapture,\n\tcreateStructuredOutputTool,\n\ttype JsonObject,\n\ttype JsonPrimitive,\n\ttype JsonValue,\n\tSTRUCTURED_OUTPUT_TOOL_NAME,\n\ttype StructuredOutputCapture,\n\ttype StructuredOutputFileCapture,\n\ttype StructuredOutputToolOptions,\n} from \"./structured-output.ts\";\nexport { createTodoToolDefinition } from \"./todos.ts\";\nexport {\n\tDEFAULT_MAX_BYTES,\n\tDEFAULT_MAX_LINES,\n\tformatSize,\n\ttype TruncationOptions,\n\ttype TruncationResult,\n\ttruncateHead,\n\ttruncateLine,\n\ttruncateTail,\n} from \"./truncate.ts\";\nexport {\n\tcreateWriteTool,\n\tcreateWriteToolDefinition,\n\ttype WriteOperations,\n\ttype WriteToolInput,\n\ttype WriteToolOptions,\n\twriteToolSystemPromptContribution,\n} from \"./write.ts\";\n\nimport type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport type { TSchema } from \"typebox\";\nimport type { ToolDefinition } from \"../extensions/types.ts\";\nimport { createAskUserQuestionToolDefinition } from \"./ask-user-question/index.ts\";\nimport { type BashToolOptions, createBashTool, createBashToolDefinition } from \"./bash.ts\";\nimport { createEditTool, createEditToolDefinition, type EditToolOptions } from \"./edit.ts\";\nimport { createFindTool, createFindToolDefinition, type FindToolOptions } from \"./find.ts\";\nimport { createHashlineSnapshotStore, type HashlineSnapshotStore } from \"./hashline.ts\";\nimport { createLsTool, createLsToolDefinition, type LsToolOptions } from \"./ls.ts\";\nimport { createReadTool, createReadToolDefinition, type ReadToolOptions } from \"./read.ts\";\nimport { createSearchTool, createSearchToolDefinition, type SearchToolOptions } from \"./search.ts\";\nimport { createTodoToolDefinition } from \"./todos.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\nimport { createWriteTool, createWriteToolDefinition, type WriteToolOptions } from \"./write.ts\";\n\nexport type Tool = AgentTool<TSchema, unknown>;\nexport type ToolDef = ToolDefinition<TSchema, unknown>;\nexport type ToolName = \"read\" | \"bash\" | \"edit\" | \"write\" | \"find\" | \"search\" | \"ls\" | \"ask_user_question\" | \"todo\";\nexport const allToolNames: Set<ToolName> = new Set([\n\t\"read\",\n\t\"bash\",\n\t\"edit\",\n\t\"write\",\n\t\"find\",\n\t\"search\",\n\t\"ls\",\n\t\"ask_user_question\",\n\t\"todo\",\n]);\n\nexport const defaultToolNames: readonly ToolName[] = [\n\t\"read\",\n\t\"bash\",\n\t\"edit\",\n\t\"write\",\n\t\"find\",\n\t\"search\",\n\t\"ask_user_question\",\n\t\"todo\",\n];\n\nexport interface ToolsOptions {\n\tread?: ReadToolOptions;\n\tbash?: BashToolOptions;\n\twrite?: WriteToolOptions;\n\tedit?: EditToolOptions;\n\tfind?: FindToolOptions;\n\tsearch?: SearchToolOptions;\n\tls?: LsToolOptions;\n\thashlineStore?: HashlineSnapshotStore;\n}\n\nexport function createToolDefinition(toolName: ToolName, cwd: string, options?: ToolsOptions): ToolDef {\n\t// Default a shared store so the singular factories don't hand read/edit/\n\t// write/search isolated stores (which silently degrades drift recovery).\n\tconst hashlineStore = options?.hashlineStore ?? createHashlineSnapshotStore();\n\tswitch (toolName) {\n\t\tcase \"read\":\n\t\t\treturn createReadToolDefinition(cwd, { ...options?.read, hashlineStore });\n\t\tcase \"bash\":\n\t\t\treturn createBashToolDefinition(cwd, options?.bash);\n\t\tcase \"edit\":\n\t\t\treturn createEditToolDefinition(cwd, { ...options?.edit, hashlineStore });\n\t\tcase \"write\":\n\t\t\treturn createWriteToolDefinition(cwd, { ...options?.write, hashlineStore });\n\t\tcase \"find\":\n\t\t\treturn createFindToolDefinition(cwd, options?.find);\n\t\tcase \"search\":\n\t\t\treturn createSearchToolDefinition(cwd, { ...options?.search, hashlineStore });\n\t\tcase \"ls\":\n\t\t\treturn createLsToolDefinition(cwd, options?.ls);\n\t\tcase \"ask_user_question\":\n\t\t\treturn createAskUserQuestionToolDefinition();\n\t\tcase \"todo\":\n\t\t\treturn createTodoToolDefinition(cwd);\n\t\tdefault:\n\t\t\tthrow new Error(`Unknown tool name: ${toolName}`);\n\t}\n}\n\nexport function createTool(toolName: ToolName, cwd: string, options?: ToolsOptions): Tool {\n\tconst hashlineStore = options?.hashlineStore ?? createHashlineSnapshotStore();\n\tswitch (toolName) {\n\t\tcase \"read\":\n\t\t\treturn createReadTool(cwd, { ...options?.read, hashlineStore });\n\t\tcase \"bash\":\n\t\t\treturn createBashTool(cwd, options?.bash);\n\t\tcase \"edit\":\n\t\t\treturn createEditTool(cwd, { ...options?.edit, hashlineStore });\n\t\tcase \"write\":\n\t\t\treturn createWriteTool(cwd, { ...options?.write, hashlineStore });\n\t\tcase \"find\":\n\t\t\treturn createFindTool(cwd, options?.find);\n\t\tcase \"search\":\n\t\t\treturn createSearchTool(cwd, { ...options?.search, hashlineStore });\n\t\tcase \"ls\":\n\t\t\treturn createLsTool(cwd, options?.ls);\n\t\tcase \"ask_user_question\":\n\t\t\treturn wrapToolDefinition(createAskUserQuestionToolDefinition());\n\t\tcase \"todo\":\n\t\t\treturn wrapToolDefinition(createTodoToolDefinition(cwd));\n\t\tdefault:\n\t\t\tthrow new Error(`Unknown tool name: ${toolName}`);\n\t}\n}\n\nexport function createCodingToolDefinitions(cwd: string, options?: ToolsOptions): ToolDef[] {\n\tconst hashlineStore = options?.hashlineStore ?? createHashlineSnapshotStore();\n\treturn [\n\t\tcreateReadToolDefinition(cwd, { ...options?.read, hashlineStore }),\n\t\tcreateBashToolDefinition(cwd, { asyncEnabled: true, ...options?.bash }),\n\t\tcreateEditToolDefinition(cwd, { ...options?.edit, hashlineStore }),\n\t\tcreateWriteToolDefinition(cwd, { ...options?.write, hashlineStore }),\n\t\tcreateFindToolDefinition(cwd, options?.find),\n\t\tcreateSearchToolDefinition(cwd, { ...options?.search, hashlineStore }),\n\t];\n}\n\nexport function createReadOnlyToolDefinitions(cwd: string, options?: ToolsOptions): ToolDef[] {\n\tconst hashlineStore = options?.hashlineStore ?? createHashlineSnapshotStore();\n\treturn [\n\t\tcreateReadToolDefinition(cwd, { ...options?.read, hashlineStore }),\n\t\tcreateFindToolDefinition(cwd, options?.find),\n\t\tcreateSearchToolDefinition(cwd, { ...options?.search, hashlineStore }),\n\t\tcreateLsToolDefinition(cwd, options?.ls),\n\t];\n}\n\nexport function createAllToolDefinitions(cwd: string, options?: ToolsOptions): Record<ToolName, ToolDef> {\n\tconst hashlineStore = options?.hashlineStore ?? createHashlineSnapshotStore();\n\treturn {\n\t\tread: createReadToolDefinition(cwd, { ...options?.read, hashlineStore }),\n\t\tbash: createBashToolDefinition(cwd, { asyncEnabled: true, ...options?.bash }),\n\t\tedit: createEditToolDefinition(cwd, { ...options?.edit, hashlineStore }),\n\t\twrite: createWriteToolDefinition(cwd, { ...options?.write, hashlineStore }),\n\t\tfind: createFindToolDefinition(cwd, options?.find),\n\t\tsearch: createSearchToolDefinition(cwd, { ...options?.search, hashlineStore }),\n\t\tls: createLsToolDefinition(cwd, options?.ls),\n\t\task_user_question: createAskUserQuestionToolDefinition(),\n\t\ttodo: createTodoToolDefinition(cwd),\n\t};\n}\n\nexport function createCodingTools(cwd: string, options?: ToolsOptions): Tool[] {\n\tconst hashlineStore = options?.hashlineStore ?? createHashlineSnapshotStore();\n\treturn [\n\t\tcreateReadTool(cwd, { ...options?.read, hashlineStore }),\n\t\tcreateBashTool(cwd, { asyncEnabled: true, ...options?.bash }),\n\t\tcreateEditTool(cwd, { ...options?.edit, hashlineStore }),\n\t\tcreateWriteTool(cwd, { ...options?.write, hashlineStore }),\n\t\tcreateFindTool(cwd, options?.find),\n\t\tcreateSearchTool(cwd, { ...options?.search, hashlineStore }),\n\t];\n}\n\nexport function createReadOnlyTools(cwd: string, options?: ToolsOptions): Tool[] {\n\tconst hashlineStore = options?.hashlineStore ?? createHashlineSnapshotStore();\n\treturn [\n\t\tcreateReadTool(cwd, { ...options?.read, hashlineStore }),\n\t\tcreateFindTool(cwd, options?.find),\n\t\tcreateSearchTool(cwd, { ...options?.search, hashlineStore }),\n\t\tcreateLsTool(cwd, options?.ls),\n\t];\n}\n\nexport function createAllTools(cwd: string, options?: ToolsOptions): Record<ToolName, Tool> {\n\tconst hashlineStore = options?.hashlineStore ?? createHashlineSnapshotStore();\n\treturn {\n\t\tread: createReadTool(cwd, { ...options?.read, hashlineStore }),\n\t\tbash: createBashTool(cwd, { asyncEnabled: true, ...options?.bash }),\n\t\tedit: createEditTool(cwd, { ...options?.edit, hashlineStore }),\n\t\twrite: createWriteTool(cwd, { ...options?.write, hashlineStore }),\n\t\tfind: createFindTool(cwd, options?.find),\n\t\tsearch: createSearchTool(cwd, { ...options?.search, hashlineStore }),\n\t\tls: createLsTool(cwd, options?.ls),\n\t\task_user_question: wrapToolDefinition(createAskUserQuestionToolDefinition()),\n\t\ttodo: wrapToolDefinition(createTodoToolDefinition(cwd)),\n\t};\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/core/tools/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mCAAmC,EAAE,MAAM,8BAA8B,CAAC;AACnF,OAAO,EAON,gCAAgC,EAChC,cAAc,EACd,wBAAwB,EACxB,yBAAyB,GACzB,MAAM,WAAW,CAAC;AACnB,OAAO,EACN,cAAc,EACd,wBAAwB,EAKxB,gCAAgC,GAChC,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,qBAAqB,EAAE,MAAM,0BAA0B,CAAC;AACjE,OAAO,EACN,cAAc,EACd,wBAAwB,EAKxB,gCAAgC,GAChC,MAAM,WAAW,CAAC;AACnB,OAAO,EACN,YAAY,EACZ,sBAAsB,EAKtB,8BAA8B,GAC9B,MAAM,SAAS,CAAC;AACjB,OAAO,EACN,cAAc,EACd,wBAAwB,EAKxB,gCAAgC,GAChC,MAAM,WAAW,CAAC;AACnB,OA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AAC,CAAC;KACvD,CAAC;AACH,CAAC","sourcesContent":["export { createAskUserQuestionToolDefinition } from \"./ask-user-question/index.ts\";\nexport {\n\ttype BashOperations,\n\ttype BashSpawnContext,\n\ttype BashSpawnHook,\n\ttype BashToolDetails,\n\ttype BashToolInput,\n\ttype BashToolOptions,\n\tbashToolSystemPromptContribution,\n\tcreateBashTool,\n\tcreateBashToolDefinition,\n\tcreateLocalBashOperations,\n} from \"./bash.ts\";\nexport {\n\tcreateEditTool,\n\tcreateEditToolDefinition,\n\ttype EditOperations,\n\ttype EditToolDetails,\n\ttype EditToolInput,\n\ttype EditToolOptions,\n\teditToolSystemPromptContribution,\n} from \"./edit.ts\";\nexport { withFileMutationQueue } from \"./file-mutation-queue.ts\";\nexport {\n\tcreateFindTool,\n\tcreateFindToolDefinition,\n\ttype FindOperations,\n\ttype FindToolDetails,\n\ttype FindToolInput,\n\ttype FindToolOptions,\n\tfindToolSystemPromptContribution,\n} from \"./find.ts\";\nexport {\n\tcreateLsTool,\n\tcreateLsToolDefinition,\n\ttype LsOperations,\n\ttype LsToolDetails,\n\ttype LsToolInput,\n\ttype LsToolOptions,\n\tlsToolSystemPromptContribution,\n} from \"./ls.ts\";\nexport {\n\tcreateReadTool,\n\tcreateReadToolDefinition,\n\ttype ReadOperations,\n\ttype ReadToolDetails,\n\ttype ReadToolInput,\n\ttype ReadToolOptions,\n\treadToolSystemPromptContribution,\n} from \"./read.ts\";\nexport {\n\tcreateSearchTool,\n\tcreateSearchToolDefinition,\n\ttype SearchToolDetails,\n\ttype SearchToolInput,\n\ttype SearchToolOptions,\n\tsearchToolSystemPromptContribution,\n} from \"./search.ts\";\nexport {\n\tcreateStructuredOutputCapture,\n\tcreateStructuredOutputTool,\n\ttype JsonObject,\n\ttype JsonPrimitive,\n\ttype JsonValue,\n\tSTRUCTURED_OUTPUT_TOOL_NAME,\n\ttype StructuredOutputCapture,\n\ttype StructuredOutputFileCapture,\n\ttype StructuredOutputToolOptions,\n} from \"./structured-output.ts\";\nexport { createTodoToolDefinition } from \"./todos.ts\";\nexport {\n\tDEFAULT_MAX_BYTES,\n\tDEFAULT_MAX_LINES,\n\tformatSize,\n\ttype TruncationOptions,\n\ttype TruncationResult,\n\ttruncateHead,\n\ttruncateLine,\n\ttruncateTail,\n} from \"./truncate.ts\";\nexport {\n\tcreateWriteTool,\n\tcreateWriteToolDefinition,\n\ttype WriteOperations,\n\ttype WriteToolInput,\n\ttype WriteToolOptions,\n\twriteToolSystemPromptContribution,\n} from \"./write.ts\";\n\nimport type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport type { TSchema } from \"typebox\";\nimport type { ToolDefinition } from \"../extensions/types.ts\";\nimport { createAskUserQuestionToolDefinition } from \"./ask-user-question/index.ts\";\nimport { type BashToolOptions, createBashTool, createBashToolDefinition } from \"./bash.ts\";\nimport { createEditTool, createEditToolDefinition, type EditToolOptions } from \"./edit.ts\";\nimport { createFindTool, createFindToolDefinition, type FindToolOptions } from \"./find.ts\";\nimport { createHashlineSnapshotStore, type HashlineSnapshotStore } from \"./hashline.ts\";\nimport { createLsTool, createLsToolDefinition, type LsToolOptions } from \"./ls.ts\";\nimport { createReadTool, createReadToolDefinition, type ReadToolOptions } from \"./read.ts\";\nimport { createSearchTool, createSearchToolDefinition, type SearchToolOptions } from \"./search.ts\";\nimport { createTodoToolDefinition } from \"./todos.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\nimport { createWriteTool, createWriteToolDefinition, type WriteToolOptions } from \"./write.ts\";\n\nexport type Tool = AgentTool<TSchema, unknown>;\nexport type ToolDef = ToolDefinition<TSchema, unknown>;\nexport type ToolName = \"read\" | \"bash\" | \"edit\" | \"write\" | \"find\" | \"search\" | \"ls\" | \"ask_user_question\" | \"todo\";\nexport const allToolNames: Set<ToolName> = new Set([\n\t\"read\",\n\t\"bash\",\n\t\"edit\",\n\t\"write\",\n\t\"find\",\n\t\"search\",\n\t\"ls\",\n\t\"ask_user_question\",\n\t\"todo\",\n]);\n\nexport const defaultToolNames: readonly ToolName[] = [\n\t\"read\",\n\t\"bash\",\n\t\"edit\",\n\t\"write\",\n\t\"find\",\n\t\"search\",\n\t\"ask_user_question\",\n\t\"todo\",\n];\n\nexport interface ToolsOptions {\n\tread?: ReadToolOptions;\n\tbash?: BashToolOptions;\n\twrite?: WriteToolOptions;\n\tedit?: EditToolOptions;\n\tfind?: FindToolOptions;\n\tsearch?: SearchToolOptions;\n\tls?: LsToolOptions;\n\thashlineStore?: HashlineSnapshotStore;\n}\n\nexport function createToolDefinition(toolName: ToolName, cwd: string, options?: ToolsOptions): ToolDef {\n\t// Default a shared store so the singular factories don't hand read/edit/\n\t// write/search isolated stores (which silently degrades drift recovery).\n\tconst hashlineStore = options?.hashlineStore ?? createHashlineSnapshotStore();\n\tswitch (toolName) {\n\t\tcase \"read\":\n\t\t\treturn createReadToolDefinition(cwd, { ...options?.read, hashlineStore });\n\t\tcase \"bash\":\n\t\t\treturn createBashToolDefinition(cwd, options?.bash);\n\t\tcase \"edit\":\n\t\t\treturn createEditToolDefinition(cwd, { ...options?.edit, hashlineStore });\n\t\tcase \"write\":\n\t\t\treturn createWriteToolDefinition(cwd, { ...options?.write, hashlineStore });\n\t\tcase \"find\":\n\t\t\treturn createFindToolDefinition(cwd, options?.find);\n\t\tcase \"search\":\n\t\t\treturn createSearchToolDefinition(cwd, { ...options?.search, hashlineStore });\n\t\tcase \"ls\":\n\t\t\treturn createLsToolDefinition(cwd, options?.ls);\n\t\tcase \"ask_user_question\":\n\t\t\treturn createAskUserQuestionToolDefinition();\n\t\tcase \"todo\":\n\t\t\treturn createTodoToolDefinition(cwd);\n\t\tdefault:\n\t\t\tthrow new Error(`Unknown tool name: ${toolName}`);\n\t}\n}\n\nexport function createTool(toolName: ToolName, cwd: string, options?: ToolsOptions): Tool {\n\tconst hashlineStore = options?.hashlineStore ?? createHashlineSnapshotStore();\n\tswitch (toolName) {\n\t\tcase \"read\":\n\t\t\treturn createReadTool(cwd, { ...options?.read, hashlineStore });\n\t\tcase \"bash\":\n\t\t\treturn createBashTool(cwd, options?.bash);\n\t\tcase \"edit\":\n\t\t\treturn createEditTool(cwd, { ...options?.edit, hashlineStore });\n\t\tcase \"write\":\n\t\t\treturn createWriteTool(cwd, { ...options?.write, hashlineStore });\n\t\tcase \"find\":\n\t\t\treturn createFindTool(cwd, options?.find);\n\t\tcase \"search\":\n\t\t\treturn createSearchTool(cwd, { ...options?.search, hashlineStore });\n\t\tcase \"ls\":\n\t\t\treturn createLsTool(cwd, options?.ls);\n\t\tcase \"ask_user_question\":\n\t\t\treturn wrapToolDefinition(createAskUserQuestionToolDefinition());\n\t\tcase \"todo\":\n\t\t\treturn wrapToolDefinition(createTodoToolDefinition(cwd));\n\t\tdefault:\n\t\t\tthrow new Error(`Unknown tool name: ${toolName}`);\n\t}\n}\n\nexport function createCodingToolDefinitions(cwd: string, options?: ToolsOptions): ToolDef[] {\n\tconst hashlineStore = options?.hashlineStore ?? createHashlineSnapshotStore();\n\treturn [\n\t\tcreateReadToolDefinition(cwd, { ...options?.read, hashlineStore }),\n\t\tcreateBashToolDefinition(cwd, options?.bash),\n\t\tcreateEditToolDefinition(cwd, { ...options?.edit, hashlineStore }),\n\t\tcreateWriteToolDefinition(cwd, { ...options?.write, hashlineStore }),\n\t\tcreateFindToolDefinition(cwd, options?.find),\n\t\tcreateSearchToolDefinition(cwd, { ...options?.search, hashlineStore }),\n\t];\n}\n\nexport function createReadOnlyToolDefinitions(cwd: string, options?: ToolsOptions): ToolDef[] {\n\tconst hashlineStore = options?.hashlineStore ?? createHashlineSnapshotStore();\n\treturn [\n\t\tcreateReadToolDefinition(cwd, { ...options?.read, hashlineStore }),\n\t\tcreateFindToolDefinition(cwd, options?.find),\n\t\tcreateSearchToolDefinition(cwd, { ...options?.search, hashlineStore }),\n\t\tcreateLsToolDefinition(cwd, options?.ls),\n\t];\n}\n\nexport function createAllToolDefinitions(cwd: string, options?: ToolsOptions): Record<ToolName, ToolDef> {\n\tconst hashlineStore = options?.hashlineStore ?? createHashlineSnapshotStore();\n\treturn {\n\t\tread: createReadToolDefinition(cwd, { ...options?.read, hashlineStore }),\n\t\tbash: createBashToolDefinition(cwd, options?.bash),\n\t\tedit: createEditToolDefinition(cwd, { ...options?.edit, hashlineStore }),\n\t\twrite: createWriteToolDefinition(cwd, { ...options?.write, hashlineStore }),\n\t\tfind: createFindToolDefinition(cwd, options?.find),\n\t\tsearch: createSearchToolDefinition(cwd, { ...options?.search, hashlineStore }),\n\t\tls: createLsToolDefinition(cwd, options?.ls),\n\t\task_user_question: createAskUserQuestionToolDefinition(),\n\t\ttodo: createTodoToolDefinition(cwd),\n\t};\n}\n\nexport function createCodingTools(cwd: string, options?: ToolsOptions): Tool[] {\n\tconst hashlineStore = options?.hashlineStore ?? createHashlineSnapshotStore();\n\treturn [\n\t\tcreateReadTool(cwd, { ...options?.read, hashlineStore }),\n\t\tcreateBashTool(cwd, options?.bash),\n\t\tcreateEditTool(cwd, { ...options?.edit, hashlineStore }),\n\t\tcreateWriteTool(cwd, { ...options?.write, hashlineStore }),\n\t\tcreateFindTool(cwd, options?.find),\n\t\tcreateSearchTool(cwd, { ...options?.search, hashlineStore }),\n\t];\n}\n\nexport function createReadOnlyTools(cwd: string, options?: ToolsOptions): Tool[] {\n\tconst hashlineStore = options?.hashlineStore ?? createHashlineSnapshotStore();\n\treturn [\n\t\tcreateReadTool(cwd, { ...options?.read, hashlineStore }),\n\t\tcreateFindTool(cwd, options?.find),\n\t\tcreateSearchTool(cwd, { ...options?.search, hashlineStore }),\n\t\tcreateLsTool(cwd, options?.ls),\n\t];\n}\n\nexport function createAllTools(cwd: string, options?: ToolsOptions): Record<ToolName, Tool> {\n\tconst hashlineStore = options?.hashlineStore ?? createHashlineSnapshotStore();\n\treturn {\n\t\tread: createReadTool(cwd, { ...options?.read, hashlineStore }),\n\t\tbash: createBashTool(cwd, options?.bash),\n\t\tedit: createEditTool(cwd, { ...options?.edit, hashlineStore }),\n\t\twrite: createWriteTool(cwd, { ...options?.write, hashlineStore }),\n\t\tfind: createFindTool(cwd, options?.find),\n\t\tsearch: createSearchTool(cwd, { ...options?.search, hashlineStore }),\n\t\tls: createLsTool(cwd, options?.ls),\n\t\task_user_question: wrapToolDefinition(createAskUserQuestionToolDefinition()),\n\t\ttodo: wrapToolDefinition(createTodoToolDefinition(cwd)),\n\t};\n}\n"]}
@@ -2,8 +2,8 @@
2
2
  * Owner- and session-scoped temp storage for tool output files.
3
3
  *
4
4
  * Every file a tool spills to the system temp directory (bash overflow logs,
5
- * async bash logs, `OutputAccumulator` spill files, and the in-memory-session
6
- * tool-result fallback) lands under:
5
+ * `OutputAccumulator` spill files, and the in-memory-session tool-result fallback)
6
+ * lands under:
7
7
  *
8
8
  * ```text
9
9
  * <tmpdir>/<APP_NAME>-<owner>/<sanitized-session-id>/
@@ -1 +1 @@
1
- {"version":3,"file":"session-temp-dir.d.ts","sourceRoot":"","sources":["../../../src/core/tools/session-temp-dir.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAaH,2EAA2E;AAC3E,eAAO,MAAM,qBAAqB,MAAQ,CAAC;AAE3C,8DAA8D;AAC9D,eAAO,MAAM,sBAAsB,MAAQ,CAAC;AAQ5C;;;;;;;;GAQG;AACH,wBAAgB,yBAAyB,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAYjF;AAID;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,oBAAoB,CAAC,WAAW,EAAE,MAAM,GAAG,MAAM,CAUhE;AAED;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,CAQjE;AAwDD,oFAAoF;AACpF,wBAAgB,cAAc,IAAI,MAAM,CAGvC;AAED;;;;;;GAMG;AACH,wBAAgB,yBAAyB,CAAC,SAAS,CAAC,EAAE,MAAM,GAAG,MAAM,CAGpE;AAcD,mGAAmG;AACnG,qBAA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AI,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,CAQjE;AAwDD,oFAAoF;AACpF,wBAAgB,cAAc,IAAI,MAAM,CAGvC;AAED;;;;;;GAMG;AACH,wBAAgB,yBAAyB,CAAC,SAAS,CAAC,EAAE,MAAM,GAAG,MAAM,CAGpE;AAcD,mGAAmG;AACnG,qBAAa,mBAAoB,SAAQ,KAAK;IAC7C,YAAY,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAGvC;CACD;AA+GD;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,aAAa,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAyBjD;AAED;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAAC,SAAS,CAAC,EAAE,MAAM,GAAG,MAAM,CAE5D;AAED,yFAAyF;AACzF,wBAAgB,oBAAoB,CAAC,WAAW,CAAC,EAAE,MAAM,GAAG,MAAM,CAEjE;AAeD,wEAAwE;AACxE,MAAM,WAAW,kBAAkB;IAClC,OAAO,IAAI,IAAI,CAAC;CAChB;AAED,4DAA4D;AAC5D,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,SAAS,MAAM,EAAE,GAAG,kBAAkB,CAsBlF;AAED;;;;;;GAMG;AACH,wBAAgB,sBAAsB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAGhE;AAED,wFAAwF;AACxF,wBAAgB,2BAA2B,IAAI,WAAW,CAAC,MAAM,CAAC,CAEjE;AAED,0EAA0E;AAC1E,wBAAgB,kCAAkC,IAAI,IAAI,CAOzD"}
@@ -2,8 +2,8 @@
2
2
  * Owner- and session-scoped temp storage for tool output files.
3
3
  *
4
4
  * Every file a tool spills to the system temp directory (bash overflow logs,
5
- * async bash logs, `OutputAccumulator` spill files, and the in-memory-session
6
- * tool-result fallback) lands under:
5
+ * `OutputAccumulator` spill files, and the in-memory-session tool-result fallback)
6
+ * lands under:
7
7
  *
8
8
  * ```text
9
9
  * <tmpdir>/<APP_NAME>-<owner>/<sanitized-session-id>/
@@ -350,11 +350,10 @@ let activeSessionId;
350
350
  * Refcounted protection for directories the sweeper must not reap.
351
351
  *
352
352
  * A count rather than a set, because protection has more than one holder and
353
- * more than one lifetime: a session protects its own tree, an async spill writer
354
- * outlives the session object it started under, and one session can be replaced
355
- * by another wrapping the same paths. Releasing one holder must not unprotect a
356
- * directory another is still writing to, and a session that is gone must stop
357
- * protecting a tree the startup sweep exists to collect.
353
+ * more than one lifetime: a session protects its own tree, and one session can
354
+ * be replaced by another wrapping the same paths. Releasing one holder must not
355
+ * unprotect a directory another is still using, and a session that is gone must
356
+ * stop protecting a tree the startup sweep exists to collect.
358
357
  */
359
358
  const protectedPathCounts = new Map();
360
359
  /** Protect `paths` until the returned lease is released. */
@@ -1 +1 @@
1
- {"version":3,"file":"session-temp-dir.js","sourceRoot":"","sources":["../../../src/core/tools/session-temp-dir.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,EAAc,MAAM,SAAS,CAAC;AAC5F,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAC3C,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AAC/C,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAC1C,OAAO,EACN,4CAA4C,EAC5C,8BAA8B,GAC9B,MAAM,iCAAiC,CAAC;AAEzC,2EAA2E;AAC3E,MAAM,CAAC,MAAM,qBAAqB,GAAG,KAAK,CAAC;AAE3C,8DAA8D;AAC9D,MAAM,CAAC,MAAM,sBAAsB,GAAG,KAAK,CAAC;AAE5C,0EAA0E;AAC1E,MAAM,yBAAyB,GAAG,EAAE,CAAC;AAEr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K,EAAE,CAAC;IACpB,oBAAoB,GAAG,SAAS,CAAC;IACjC,kBAAkB,GAAG,SAAS,CAAC;IAC/B,4CAA4C,EAAE,CAAC;AAChD,CAAC","sourcesContent":["/**\n * Owner- and session-scoped temp storage for tool output files.\n *\n * Every file a tool spills to the system temp directory (bash overflow logs,\n * async bash logs, `OutputAccumulator` spill files, and the in-memory-session\n * tool-result fallback) lands under:\n *\n * ```text\n * <tmpdir>/<APP_NAME>-<owner>/<sanitized-session-id>/\n * ```\n *\n * The owner segment mirrors the upstream Claude Code `claude-{uid}` convention\n * (mehmoodosman/claude-code): a shared multi-user temp directory must never let\n * one account write into (or read) another account's tree. The session segment\n * makes the tree reapable as a unit by the age-based sweeper in\n * `session-temp-cleanup.ts` once the session is long gone.\n */\n\nimport { createHash } from \"node:crypto\";\nimport { chmodSync, lstatSync, mkdirSync, realpathSync, rmSync, type Stats } from \"node:fs\";\nimport { tmpdir, userInfo } from \"node:os\";\nimport { dirname, join, sep } from \"node:path\";\nimport { APP_NAME } from \"../../config.ts\";\nimport { getErrnoCode } from \"./errno.ts\";\nimport {\n\tresetWindowsDirectorySecurityStateForTesting,\n\tverifyWindowsDirectorySecurity,\n} from \"./windows-directory-security.ts\";\n\n/** Directory mode for every directory this module creates (owner-only). */\nexport const SESSION_TEMP_DIR_MODE = 0o700;\n\n/** File mode for persisted tool-output files (owner-only). */\nexport const SESSION_TEMP_FILE_MODE = 0o600;\n\n/** Longest path component this module will emit for a sanitized value. */\nconst MAX_PATH_COMPONENT_LENGTH = 64;\n\nconst FALLBACK_SESSION_COMPONENT = \"session\";\nconst FALLBACK_OWNER_COMPONENT = \"user\";\n\n/**\n * Reduce a value to a single safe path component.\n *\n * Disallowed characters collapse to `_`; leading `.`/`_` and trailing `.`/`_`\n * are stripped so the result can never be `.`, `..`, a hidden sweeper marker\n * file name, or anything that escapes the parent directory. Trimming uses a\n * linear scan rather than a `/^[._]+|[._]+$/` regex to avoid polynomial-time\n * backtracking on adversarial ids (CodeQL js/polynomial-redos).\n */\nexport function sanitizeTempPathComponent(value: string, fallback: string): string {\n\tconst collapsed = value.replace(/[^a-zA-Z0-9._-]+/g, \"_\");\n\tlet start = 0;\n\tlet end = collapsed.length;\n\twhile (start < end && (collapsed[start] === \"_\" || collapsed[start] === \".\")) {\n\t\tstart++;\n\t}\n\twhile (end > start && (collapsed[end - 1] === \"_\" || collapsed[end - 1] === \".\")) {\n\t\tend--;\n\t}\n\tconst sanitized = collapsed.slice(start, end).slice(0, MAX_PATH_COMPONENT_LENGTH);\n\treturn sanitized.length > 0 ? sanitized : fallback;\n}\n\nlet cachedOwnerComponent: string | undefined;\n\n/**\n * Derive the owner component for a named (non-uid) account.\n *\n * Sanitizing a name to a safe path component is lossy, and two distinct\n * accounts can reduce to the same component (`aliceé` and `aliceø` both yield\n * `alice_`). Where the system temp directory is machine-wide and\n * shared-accessible, that would put two accounts in one tree. Appending a short\n * digest of the raw identity keeps distinct accounts on distinct roots, with\n * the readable component in front so the directory stays recognizable.\n *\n * This prevents collision; it is not owner verification. Ownership is proven\n * separately by `verifyOwnedDirectory` — a uid check on POSIX, an owner-SID\n * and DACL check on Windows.\n *\n * Exported as a pure function so the collision property can be tested directly:\n * its only caller reaches this branch on Windows, which a POSIX test host\n * cannot enter.\n */\nexport function deriveOwnerComponent(rawIdentity: string): string {\n\t// Windows account names are case-insensitive, so `Alice` and `alice` are one\n\t// account and must resolve to one root. Normalize before both the readable\n\t// component and the digest: normalizing only the digest would still emit two\n\t// spellings of one directory, which NTFS then treats as the same path while\n\t// the sweeper's bookkeeping sees two.\n\tconst normalized = rawIdentity.toLowerCase();\n\tconst readable = sanitizeTempPathComponent(normalized, FALLBACK_OWNER_COMPONENT);\n\tconst digest = createHash(\"sha256\").update(normalized).digest(\"hex\").slice(0, 8);\n\treturn `${readable}-${digest}`;\n}\n\n/**\n * Assemble the account identity used where there is no uid.\n *\n * `userInfo().username` returns the bare account name, so `CONTOSO\\Alice` and\n * `FABRIKAM\\Alice` would otherwise be one identity and share a tree. Exported\n * for tests: its caller only reaches this branch on Windows.\n */\nexport function windowsPrincipal(name: string | undefined): string {\n\tconst account = name || process.env.USERNAME || process.env.USER || \"\";\n\t// USERDOMAIN is the NetBIOS domain and is set for both domain and local\n\t// accounts; USERDNSDOMAIN appears only on domain-joined hosts and\n\t// distinguishes two forests that share a NetBIOS name. Neither is\n\t// authoritative on its own, so both take part in the identity.\n\tconst domain = process.env.USERDNSDOMAIN || process.env.USERDOMAIN || \"\";\n\treturn domain ? `${domain}\\\\${account}` : account;\n}\n\n/**\n * Identify the account that owns the temp tree.\n *\n * POSIX uses the numeric uid, which is already collision-free. Windows has no\n * `process.getuid`, so the domain-qualified principal stands in.\n */\nfunction ownerComponent(): string {\n\tif (cachedOwnerComponent !== undefined) {\n\t\treturn cachedOwnerComponent;\n\t}\n\tconst uid = typeof process.getuid === \"function\" ? process.getuid() : undefined;\n\tif (typeof uid === \"number\" && Number.isFinite(uid)) {\n\t\tcachedOwnerComponent = String(uid);\n\t\treturn cachedOwnerComponent;\n\t}\n\tlet name: string | undefined;\n\ttry {\n\t\tname = userInfo().username;\n\t} catch {\n\t\t// A container without a passwd entry cannot name the account; the env\n\t\t// fallback inside windowsPrincipal still separates the common case.\n\t\tname = undefined;\n\t}\n\tcachedOwnerComponent = deriveOwnerComponent(windowsPrincipal(name));\n\treturn cachedOwnerComponent;\n}\n\ninterface BaseTempDirs {\n\traw: string;\n\tcanonical: string;\n}\n\nlet cachedBaseTempDirs: BaseTempDirs | undefined;\n\n/**\n * Preserve the OS-provided temp spelling for returned paths while caching a\n * canonical form for internal component checks (macOS `/var` → `/private/var`,\n * for example). Nothing below the base is resolved through `realpath`.\n */\nfunction baseTempDirs(): BaseTempDirs {\n\tconst raw = tmpdir();\n\tif (cachedBaseTempDirs?.raw === raw) {\n\t\treturn cachedBaseTempDirs;\n\t}\n\tlet canonical = raw;\n\ttry {\n\t\tcanonical = realpathSync(raw);\n\t} catch {\n\t\t// An unresolvable temp directory is checked as given.\n\t}\n\tcachedBaseTempDirs = { raw, canonical };\n\treturn cachedBaseTempDirs;\n}\n\n/** `<tmpdir>/<APP_NAME>-<owner>` — the root every session temp tree lives under. */\nexport function getTempRootDir(): string {\n\tconst app = sanitizeTempPathComponent(APP_NAME, \"atomic\");\n\treturn join(baseTempDirs().raw, `${app}-${ownerComponent()}`);\n}\n\n/**\n * The temp directory path for a session, without creating it.\n *\n * Falls back to the process-scoped component when no session id is available,\n * so a tool running outside a transcript session still writes inside the\n * owner-scoped root instead of directly into the system temp directory.\n */\nexport function resolveSessionTempDirPath(sessionId?: string): string {\n\tconst id = sessionId ?? activeSessionId ?? `pid-${process.pid}`;\n\treturn join(getTempRootDir(), sanitizeTempPathComponent(id, FALLBACK_SESSION_COMPONENT));\n}\n\nconst ensuredDirs = new Set<string>();\n\n/** An existing real directory — not a symlink, not a file, not missing. */\nfunction isRealDirectory(path: string): boolean {\n\ttry {\n\t\tconst stat = lstatSync(path);\n\t\treturn stat.isDirectory() && !stat.isSymbolicLink();\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/** Raised when a temp directory cannot be created or trusted; callers degrade to no spill file. */\nexport class TempDirRefusedError extends Error {\n\tconstructor(path: string, reason: string) {\n\t\tsuper(`Refusing to use temp directory ${path}: ${reason}`);\n\t\tthis.name = \"TempDirRefusedError\";\n\t}\n}\n\n/**\n * Confirm one existing component is a directory this account owns, at mode 0700.\n *\n * A looser mode is tightened and re-checked; a component owned by another\n * account, or one whose mode cannot be tightened, is refused rather than used.\n *\n * Windows has no uid or POSIX mode, so the proof comes from the security\n * descriptor instead: the owner SID must be a trusted principal and the DACL\n * must grant access to trusted principals only\n * (see `windows-directory-security.ts`). Node exposes neither — `lstatSync`\n * reports uid/gid 0 on Windows — so the read goes through a PowerShell\n * `Get-Acl` subprocess. Successful verifications are cached per path per\n * process, keyed to the directory's metadata identity so a swapped directory\n * or an in-place DACL edit forces a fresh read. Domain-qualifying the\n * principal (see `windowsPrincipal`) stops two accounts *colliding* by\n * accident, which is a different problem and is not a substitute for this\n * verification.\n */\nfunction verifyOwnedDirectory(path: string, known?: Stats): void {\n\tlet stat = known ?? lstatSync(path);\n\tif (stat.isSymbolicLink()) {\n\t\tthrow new TempDirRefusedError(path, \"it is a symbolic link\");\n\t}\n\tif (!stat.isDirectory()) {\n\t\tthrow new TempDirRefusedError(path, \"it is not a directory\");\n\t}\n\tif (process.platform === \"win32\") {\n\t\tconst refusal = verifyWindowsDirectorySecurity(path);\n\t\tif (refusal !== undefined) {\n\t\t\tthrow new TempDirRefusedError(path, refusal);\n\t\t}\n\t\treturn;\n\t}\n\tconst uid = typeof process.getuid === \"function\" ? process.getuid() : undefined;\n\tif (typeof uid === \"number\" && stat.uid !== uid) {\n\t\tthrow new TempDirRefusedError(path, \"it is owned by another account\");\n\t}\n\tif ((stat.mode & 0o777) === SESSION_TEMP_DIR_MODE) {\n\t\treturn;\n\t}\n\ttry {\n\t\tchmodSync(path, SESSION_TEMP_DIR_MODE);\n\t\tstat = lstatSync(path);\n\t} catch {\n\t\tthrow new TempDirRefusedError(path, \"its permissions could not be tightened\");\n\t}\n\tif ((stat.mode & 0o777) !== SESSION_TEMP_DIR_MODE) {\n\t\tthrow new TempDirRefusedError(path, \"its permissions could not be tightened\");\n\t}\n}\n\n/**\n * Create or adopt one path component, never following a link to get there.\n *\n * Creation is non-recursive on purpose: `mkdir -p` resolves an existing symlink\n * on the way down, which is how a link planted at the predictable owner root\n * redirects every later write outside the tree.\n */\nfunction ensureOwnedDirectory(path: string): void {\n\tlet stat: Stats | undefined;\n\ttry {\n\t\tstat = lstatSync(path);\n\t} catch {\n\t\tstat = undefined;\n\t}\n\tif (stat === undefined) {\n\t\ttry {\n\t\t\tmkdirSync(path, { recursive: false, mode: SESSION_TEMP_DIR_MODE });\n\t\t} catch (error) {\n\t\t\t// A concurrent creator winning the race is fine; anything else is not.\n\t\t\tif (getErrnoCode(error) !== \"EEXIST\") {\n\t\t\t\tthrow new TempDirRefusedError(path, \"it could not be created\");\n\t\t\t}\n\t\t}\n\t\tverifyOwnedDirectory(path);\n\t\treturn;\n\t}\n\tverifyOwnedDirectory(path, stat);\n}\n\n/**\n * Adopt the final component, replacing something that is not a directory.\n *\n * Only the leaf gets this treatment: a stale file or link left where a session\n * directory belongs is ours to clear, and removing a symlink removes the link\n * alone. A parent — above all the owner root — is refused instead, because\n * deleting it would be acting on a directory this process does not own.\n */\nfunction ensureLeafDirectory(dir: string): void {\n\ttry {\n\t\tif (!lstatSync(dir).isDirectory()) {\n\t\t\trmSync(dir, { force: true });\n\t\t}\n\t} catch {\n\t\t// Nothing at the path yet, or it cannot be inspected; creation decides.\n\t}\n\tensureOwnedDirectory(dir);\n}\n\n/** Map a lexical temp child to the same path below the canonical temp base. */\nfunction canonicalTempChild(dir: string, base: BaseTempDirs): string | undefined {\n\tfor (const candidate of [base.raw, base.canonical]) {\n\t\tconst prefix = `${candidate}${sep}`;\n\t\tif (dir.startsWith(prefix)) {\n\t\t\treturn join(base.canonical, dir.slice(prefix.length));\n\t\t}\n\t}\n\treturn undefined;\n}\n/**\n * Create `dir` with owner-only permissions, validating every component below the\n * system temp directory.\n *\n * Temp children always revalidate the canonical owner root and every later\n * component, even after a cache hit. A system temp reaper can delete a session\n * tree, and an attacker must not turn a memoized path into a symlink bypass.\n * Caller-owned paths outside the temp base may use the memo after confirming\n * the leaf is still a real directory.\n *\n * Throws {@link TempDirRefusedError} when a component cannot be trusted. Every\n * caller treats that as \"no spill file\", never as a fatal error: failing closed\n * loses a convenience artifact, while failing open writes tool output into a\n * directory someone else controls.\n */\nexport function ensureTempDir(dir: string): string {\n\tconst base = baseTempDirs();\n\tconst checkedDir = canonicalTempChild(dir, base);\n\tif (checkedDir !== undefined) {\n\t\tconst prefix = `${base.canonical}${sep}`;\n\t\tconst parts = checkedDir\n\t\t\t.slice(prefix.length)\n\t\t\t.split(sep)\n\t\t\t.filter((part) => part.length > 0);\n\t\tlet current = base.canonical;\n\t\tfor (const part of parts.slice(0, -1)) {\n\t\t\tcurrent = join(current, part);\n\t\t\tensureOwnedDirectory(current);\n\t\t}\n\t\tensureLeafDirectory(checkedDir);\n\t} else {\n\t\t// A caller-supplied directory outside the system temp base (a session\n\t\t// directory, for instance) is the caller's to own; only the leaf is ours.\n\t\tif (!(ensuredDirs.has(dir) && isRealDirectory(dir))) {\n\t\t\tmkdirSync(dirname(dir), { recursive: true, mode: SESSION_TEMP_DIR_MODE });\n\t\t\tensureLeafDirectory(dir);\n\t\t}\n\t}\n\tensuredDirs.add(dir);\n\treturn dir;\n}\n\n/**\n * Resolve and create the temp directory for a session.\n *\n * Pass an already-resolved directory to reuse a caller-provided path (still\n * created lazily with the same mode).\n */\nexport function getSessionTempDir(sessionId?: string): string {\n\treturn ensureTempDir(resolveSessionTempDirPath(sessionId));\n}\n\n/** Create `explicitDir` when supplied, otherwise the active session's temp directory. */\nexport function ensureSessionTempDir(explicitDir?: string): string {\n\treturn ensureTempDir(explicitDir ?? resolveSessionTempDirPath());\n}\n\nlet activeSessionId: string | undefined;\n\n/**\n * Refcounted protection for directories the sweeper must not reap.\n *\n * A count rather than a set, because protection has more than one holder and\n * more than one lifetime: a session protects its own tree, an async spill writer\n * outlives the session object it started under, and one session can be replaced\n * by another wrapping the same paths. Releasing one holder must not unprotect a\n * directory another is still writing to, and a session that is gone must stop\n * protecting a tree the startup sweep exists to collect.\n */\nconst protectedPathCounts = new Map<string, number>();\n\n/** A protection claim held by one owner; releasing twice is a no-op. */\nexport interface ProtectedPathLease {\n\trelease(): void;\n}\n\n/** Protect `paths` until the returned lease is released. */\nexport function acquireProtectedPaths(paths: readonly string[]): ProtectedPathLease {\n\tconst claimed = paths.filter((path) => path.length > 0);\n\tfor (const path of claimed) {\n\t\tprotectedPathCounts.set(path, (protectedPathCounts.get(path) ?? 0) + 1);\n\t}\n\tlet released = false;\n\treturn {\n\t\trelease() {\n\t\t\tif (released) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\treleased = true;\n\t\t\tfor (const path of claimed) {\n\t\t\t\tconst remaining = (protectedPathCounts.get(path) ?? 0) - 1;\n\t\t\t\tif (remaining > 0) {\n\t\t\t\t\tprotectedPathCounts.set(path, remaining);\n\t\t\t\t} else {\n\t\t\t\t\tprotectedPathCounts.delete(path);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t};\n}\n\n/**\n * Make `sessionId` the default target for writers without a session handle.\n *\n * Deliberately separate from protection: a disposed session must stop protecting\n * its tree, but whichever session ran last still names where an unattached\n * writer spills.\n */\nexport function setActiveSessionTempId(sessionId: string): string {\n\tactiveSessionId = sessionId;\n\treturn resolveSessionTempDirPath(sessionId);\n}\n\n/** Directories this process must not reap: session temp trees and live tool-results. */\nexport function getProtectedSessionTempDirs(): ReadonlySet<string> {\n\treturn new Set(protectedPathCounts.keys());\n}\n\n/** Test seam: forget the process-level active/protected session state. */\nexport function resetSessionTempDirStateForTesting(): void {\n\tactiveSessionId = undefined;\n\tprotectedPathCounts.clear();\n\tensuredDirs.clear();\n\tcachedOwnerComponent = undefined;\n\tcachedBaseTempDirs = undefined;\n\tresetWindowsDirectorySecurityStateForTesting();\n}\n"]}
1
+ {"version":3,"file":"session-temp-dir.js","sourceRoot":"","sources":["../../../src/core/tools/session-temp-dir.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,EAAc,MAAM,SAAS,CAAC;AAC5F,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAC3C,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AAC/C,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAC1C,OAAO,EACN,4CAA4C,EAC5C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UAAU,2BAA2B;IAC1C,OAAO,IAAI,GAAG,CAAC,mBAAmB,CAAC,IAAI,EAAE,CAAC,CAAC;AAC5C,CAAC;AAED,0EAA0E;AAC1E,MAAM,UAAU,kCAAkC;IACjD,eAAe,GAAG,SAAS,CAAC;IAC5B,mBAAmB,CAAC,KAAK,EAAE,CAAC;IAC5B,WAAW,CAAC,KAAK,EAAE,CAAC;IACpB,oBAAoB,GAAG,SAAS,CAAC;IACjC,kBAAkB,GAAG,SAAS,CAAC;IAC/B,4CAA4C,EAAE,CAAC;AAChD,CAAC","sourcesContent":["/**\n * Owner- and session-scoped temp storage for tool output files.\n *\n * Every file a tool spills to the system temp directory (bash overflow logs,\n * `OutputAccumulator` spill files, and the in-memory-session tool-result fallback)\n * lands under:\n *\n * ```text\n * <tmpdir>/<APP_NAME>-<owner>/<sanitized-session-id>/\n * ```\n *\n * The owner segment mirrors the upstream Claude Code `claude-{uid}` convention\n * (mehmoodosman/claude-code): a shared multi-user temp directory must never let\n * one account write into (or read) another account's tree. The session segment\n * makes the tree reapable as a unit by the age-based sweeper in\n * `session-temp-cleanup.ts` once the session is long gone.\n */\n\nimport { createHash } from \"node:crypto\";\nimport { chmodSync, lstatSync, mkdirSync, realpathSync, rmSync, type Stats } from \"node:fs\";\nimport { tmpdir, userInfo } from \"node:os\";\nimport { dirname, join, sep } from \"node:path\";\nimport { APP_NAME } from \"../../config.ts\";\nimport { getErrnoCode } from \"./errno.ts\";\nimport {\n\tresetWindowsDirectorySecurityStateForTesting,\n\tverifyWindowsDirectorySecurity,\n} from \"./windows-directory-security.ts\";\n\n/** Directory mode for every directory this module creates (owner-only). */\nexport const SESSION_TEMP_DIR_MODE = 0o700;\n\n/** File mode for persisted tool-output files (owner-only). */\nexport const SESSION_TEMP_FILE_MODE = 0o600;\n\n/** Longest path component this module will emit for a sanitized value. */\nconst MAX_PATH_COMPONENT_LENGTH = 64;\n\nconst FALLBACK_SESSION_COMPONENT = \"session\";\nconst FALLBACK_OWNER_COMPONENT = \"user\";\n\n/**\n * Reduce a value to a single safe path component.\n *\n * Disallowed characters collapse to `_`; leading `.`/`_` and trailing `.`/`_`\n * are stripped so the result can never be `.`, `..`, a hidden sweeper marker\n * file name, or anything that escapes the parent directory. Trimming uses a\n * linear scan rather than a `/^[._]+|[._]+$/` regex to avoid polynomial-time\n * backtracking on adversarial ids (CodeQL js/polynomial-redos).\n */\nexport function sanitizeTempPathComponent(value: string, fallback: string): string {\n\tconst collapsed = value.replace(/[^a-zA-Z0-9._-]+/g, \"_\");\n\tlet start = 0;\n\tlet end = collapsed.length;\n\twhile (start < end && (collapsed[start] === \"_\" || collapsed[start] === \".\")) {\n\t\tstart++;\n\t}\n\twhile (end > start && (collapsed[end - 1] === \"_\" || collapsed[end - 1] === \".\")) {\n\t\tend--;\n\t}\n\tconst sanitized = collapsed.slice(start, end).slice(0, MAX_PATH_COMPONENT_LENGTH);\n\treturn sanitized.length > 0 ? sanitized : fallback;\n}\n\nlet cachedOwnerComponent: string | undefined;\n\n/**\n * Derive the owner component for a named (non-uid) account.\n *\n * Sanitizing a name to a safe path component is lossy, and two distinct\n * accounts can reduce to the same component (`aliceé` and `aliceø` both yield\n * `alice_`). Where the system temp directory is machine-wide and\n * shared-accessible, that would put two accounts in one tree. Appending a short\n * digest of the raw identity keeps distinct accounts on distinct roots, with\n * the readable component in front so the directory stays recognizable.\n *\n * This prevents collision; it is not owner verification. Ownership is proven\n * separately by `verifyOwnedDirectory` — a uid check on POSIX, an owner-SID\n * and DACL check on Windows.\n *\n * Exported as a pure function so the collision property can be tested directly:\n * its only caller reaches this branch on Windows, which a POSIX test host\n * cannot enter.\n */\nexport function deriveOwnerComponent(rawIdentity: string): string {\n\t// Windows account names are case-insensitive, so `Alice` and `alice` are one\n\t// account and must resolve to one root. Normalize before both the readable\n\t// component and the digest: normalizing only the digest would still emit two\n\t// spellings of one directory, which NTFS then treats as the same path while\n\t// the sweeper's bookkeeping sees two.\n\tconst normalized = rawIdentity.toLowerCase();\n\tconst readable = sanitizeTempPathComponent(normalized, FALLBACK_OWNER_COMPONENT);\n\tconst digest = createHash(\"sha256\").update(normalized).digest(\"hex\").slice(0, 8);\n\treturn `${readable}-${digest}`;\n}\n\n/**\n * Assemble the account identity used where there is no uid.\n *\n * `userInfo().username` returns the bare account name, so `CONTOSO\\Alice` and\n * `FABRIKAM\\Alice` would otherwise be one identity and share a tree. Exported\n * for tests: its caller only reaches this branch on Windows.\n */\nexport function windowsPrincipal(name: string | undefined): string {\n\tconst account = name || process.env.USERNAME || process.env.USER || \"\";\n\t// USERDOMAIN is the NetBIOS domain and is set for both domain and local\n\t// accounts; USERDNSDOMAIN appears only on domain-joined hosts and\n\t// distinguishes two forests that share a NetBIOS name. Neither is\n\t// authoritative on its own, so both take part in the identity.\n\tconst domain = process.env.USERDNSDOMAIN || process.env.USERDOMAIN || \"\";\n\treturn domain ? `${domain}\\\\${account}` : account;\n}\n\n/**\n * Identify the account that owns the temp tree.\n *\n * POSIX uses the numeric uid, which is already collision-free. Windows has no\n * `process.getuid`, so the domain-qualified principal stands in.\n */\nfunction ownerComponent(): string {\n\tif (cachedOwnerComponent !== undefined) {\n\t\treturn cachedOwnerComponent;\n\t}\n\tconst uid = typeof process.getuid === \"function\" ? process.getuid() : undefined;\n\tif (typeof uid === \"number\" && Number.isFinite(uid)) {\n\t\tcachedOwnerComponent = String(uid);\n\t\treturn cachedOwnerComponent;\n\t}\n\tlet name: string | undefined;\n\ttry {\n\t\tname = userInfo().username;\n\t} catch {\n\t\t// A container without a passwd entry cannot name the account; the env\n\t\t// fallback inside windowsPrincipal still separates the common case.\n\t\tname = undefined;\n\t}\n\tcachedOwnerComponent = deriveOwnerComponent(windowsPrincipal(name));\n\treturn cachedOwnerComponent;\n}\n\ninterface BaseTempDirs {\n\traw: string;\n\tcanonical: string;\n}\n\nlet cachedBaseTempDirs: BaseTempDirs | undefined;\n\n/**\n * Preserve the OS-provided temp spelling for returned paths while caching a\n * canonical form for internal component checks (macOS `/var` → `/private/var`,\n * for example). Nothing below the base is resolved through `realpath`.\n */\nfunction baseTempDirs(): BaseTempDirs {\n\tconst raw = tmpdir();\n\tif (cachedBaseTempDirs?.raw === raw) {\n\t\treturn cachedBaseTempDirs;\n\t}\n\tlet canonical = raw;\n\ttry {\n\t\tcanonical = realpathSync(raw);\n\t} catch {\n\t\t// An unresolvable temp directory is checked as given.\n\t}\n\tcachedBaseTempDirs = { raw, canonical };\n\treturn cachedBaseTempDirs;\n}\n\n/** `<tmpdir>/<APP_NAME>-<owner>` — the root every session temp tree lives under. */\nexport function getTempRootDir(): string {\n\tconst app = sanitizeTempPathComponent(APP_NAME, \"atomic\");\n\treturn join(baseTempDirs().raw, `${app}-${ownerComponent()}`);\n}\n\n/**\n * The temp directory path for a session, without creating it.\n *\n * Falls back to the process-scoped component when no session id is available,\n * so a tool running outside a transcript session still writes inside the\n * owner-scoped root instead of directly into the system temp directory.\n */\nexport function resolveSessionTempDirPath(sessionId?: string): string {\n\tconst id = sessionId ?? activeSessionId ?? `pid-${process.pid}`;\n\treturn join(getTempRootDir(), sanitizeTempPathComponent(id, FALLBACK_SESSION_COMPONENT));\n}\n\nconst ensuredDirs = new Set<string>();\n\n/** An existing real directory — not a symlink, not a file, not missing. */\nfunction isRealDirectory(path: string): boolean {\n\ttry {\n\t\tconst stat = lstatSync(path);\n\t\treturn stat.isDirectory() && !stat.isSymbolicLink();\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/** Raised when a temp directory cannot be created or trusted; callers degrade to no spill file. */\nexport class TempDirRefusedError extends Error {\n\tconstructor(path: string, reason: string) {\n\t\tsuper(`Refusing to use temp directory ${path}: ${reason}`);\n\t\tthis.name = \"TempDirRefusedError\";\n\t}\n}\n\n/**\n * Confirm one existing component is a directory this account owns, at mode 0700.\n *\n * A looser mode is tightened and re-checked; a component owned by another\n * account, or one whose mode cannot be tightened, is refused rather than used.\n *\n * Windows has no uid or POSIX mode, so the proof comes from the security\n * descriptor instead: the owner SID must be a trusted principal and the DACL\n * must grant access to trusted principals only\n * (see `windows-directory-security.ts`). Node exposes neither — `lstatSync`\n * reports uid/gid 0 on Windows — so the read goes through a PowerShell\n * `Get-Acl` subprocess. Successful verifications are cached per path per\n * process, keyed to the directory's metadata identity so a swapped directory\n * or an in-place DACL edit forces a fresh read. Domain-qualifying the\n * principal (see `windowsPrincipal`) stops two accounts *colliding* by\n * accident, which is a different problem and is not a substitute for this\n * verification.\n */\nfunction verifyOwnedDirectory(path: string, known?: Stats): void {\n\tlet stat = known ?? lstatSync(path);\n\tif (stat.isSymbolicLink()) {\n\t\tthrow new TempDirRefusedError(path, \"it is a symbolic link\");\n\t}\n\tif (!stat.isDirectory()) {\n\t\tthrow new TempDirRefusedError(path, \"it is not a directory\");\n\t}\n\tif (process.platform === \"win32\") {\n\t\tconst refusal = verifyWindowsDirectorySecurity(path);\n\t\tif (refusal !== undefined) {\n\t\t\tthrow new TempDirRefusedError(path, refusal);\n\t\t}\n\t\treturn;\n\t}\n\tconst uid = typeof process.getuid === \"function\" ? process.getuid() : undefined;\n\tif (typeof uid === \"number\" && stat.uid !== uid) {\n\t\tthrow new TempDirRefusedError(path, \"it is owned by another account\");\n\t}\n\tif ((stat.mode & 0o777) === SESSION_TEMP_DIR_MODE) {\n\t\treturn;\n\t}\n\ttry {\n\t\tchmodSync(path, SESSION_TEMP_DIR_MODE);\n\t\tstat = lstatSync(path);\n\t} catch {\n\t\tthrow new TempDirRefusedError(path, \"its permissions could not be tightened\");\n\t}\n\tif ((stat.mode & 0o777) !== SESSION_TEMP_DIR_MODE) {\n\t\tthrow new TempDirRefusedError(path, \"its permissions could not be tightened\");\n\t}\n}\n\n/**\n * Create or adopt one path component, never following a link to get there.\n *\n * Creation is non-recursive on purpose: `mkdir -p` resolves an existing symlink\n * on the way down, which is how a link planted at the predictable owner root\n * redirects every later write outside the tree.\n */\nfunction ensureOwnedDirectory(path: string): void {\n\tlet stat: Stats | undefined;\n\ttry {\n\t\tstat = lstatSync(path);\n\t} catch {\n\t\tstat = undefined;\n\t}\n\tif (stat === undefined) {\n\t\ttry {\n\t\t\tmkdirSync(path, { recursive: false, mode: SESSION_TEMP_DIR_MODE });\n\t\t} catch (error) {\n\t\t\t// A concurrent creator winning the race is fine; anything else is not.\n\t\t\tif (getErrnoCode(error) !== \"EEXIST\") {\n\t\t\t\tthrow new TempDirRefusedError(path, \"it could not be created\");\n\t\t\t}\n\t\t}\n\t\tverifyOwnedDirectory(path);\n\t\treturn;\n\t}\n\tverifyOwnedDirectory(path, stat);\n}\n\n/**\n * Adopt the final component, replacing something that is not a directory.\n *\n * Only the leaf gets this treatment: a stale file or link left where a session\n * directory belongs is ours to clear, and removing a symlink removes the link\n * alone. A parent — above all the owner root — is refused instead, because\n * deleting it would be acting on a directory this process does not own.\n */\nfunction ensureLeafDirectory(dir: string): void {\n\ttry {\n\t\tif (!lstatSync(dir).isDirectory()) {\n\t\t\trmSync(dir, { force: true });\n\t\t}\n\t} catch {\n\t\t// Nothing at the path yet, or it cannot be inspected; creation decides.\n\t}\n\tensureOwnedDirectory(dir);\n}\n\n/** Map a lexical temp child to the same path below the canonical temp base. */\nfunction canonicalTempChild(dir: string, base: BaseTempDirs): string | undefined {\n\tfor (const candidate of [base.raw, base.canonical]) {\n\t\tconst prefix = `${candidate}${sep}`;\n\t\tif (dir.startsWith(prefix)) {\n\t\t\treturn join(base.canonical, dir.slice(prefix.length));\n\t\t}\n\t}\n\treturn undefined;\n}\n/**\n * Create `dir` with owner-only permissions, validating every component below the\n * system temp directory.\n *\n * Temp children always revalidate the canonical owner root and every later\n * component, even after a cache hit. A system temp reaper can delete a session\n * tree, and an attacker must not turn a memoized path into a symlink bypass.\n * Caller-owned paths outside the temp base may use the memo after confirming\n * the leaf is still a real directory.\n *\n * Throws {@link TempDirRefusedError} when a component cannot be trusted. Every\n * caller treats that as \"no spill file\", never as a fatal error: failing closed\n * loses a convenience artifact, while failing open writes tool output into a\n * directory someone else controls.\n */\nexport function ensureTempDir(dir: string): string {\n\tconst base = baseTempDirs();\n\tconst checkedDir = canonicalTempChild(dir, base);\n\tif (checkedDir !== undefined) {\n\t\tconst prefix = `${base.canonical}${sep}`;\n\t\tconst parts = checkedDir\n\t\t\t.slice(prefix.length)\n\t\t\t.split(sep)\n\t\t\t.filter((part) => part.length > 0);\n\t\tlet current = base.canonical;\n\t\tfor (const part of parts.slice(0, -1)) {\n\t\t\tcurrent = join(current, part);\n\t\t\tensureOwnedDirectory(current);\n\t\t}\n\t\tensureLeafDirectory(checkedDir);\n\t} else {\n\t\t// A caller-supplied directory outside the system temp base (a session\n\t\t// directory, for instance) is the caller's to own; only the leaf is ours.\n\t\tif (!(ensuredDirs.has(dir) && isRealDirectory(dir))) {\n\t\t\tmkdirSync(dirname(dir), { recursive: true, mode: SESSION_TEMP_DIR_MODE });\n\t\t\tensureLeafDirectory(dir);\n\t\t}\n\t}\n\tensuredDirs.add(dir);\n\treturn dir;\n}\n\n/**\n * Resolve and create the temp directory for a session.\n *\n * Pass an already-resolved directory to reuse a caller-provided path (still\n * created lazily with the same mode).\n */\nexport function getSessionTempDir(sessionId?: string): string {\n\treturn ensureTempDir(resolveSessionTempDirPath(sessionId));\n}\n\n/** Create `explicitDir` when supplied, otherwise the active session's temp directory. */\nexport function ensureSessionTempDir(explicitDir?: string): string {\n\treturn ensureTempDir(explicitDir ?? resolveSessionTempDirPath());\n}\n\nlet activeSessionId: string | undefined;\n\n/**\n * Refcounted protection for directories the sweeper must not reap.\n *\n * A count rather than a set, because protection has more than one holder and\n * more than one lifetime: a session protects its own tree, and one session can\n * be replaced by another wrapping the same paths. Releasing one holder must not\n * unprotect a directory another is still using, and a session that is gone must\n * stop protecting a tree the startup sweep exists to collect.\n */\nconst protectedPathCounts = new Map<string, number>();\n\n/** A protection claim held by one owner; releasing twice is a no-op. */\nexport interface ProtectedPathLease {\n\trelease(): void;\n}\n\n/** Protect `paths` until the returned lease is released. */\nexport function acquireProtectedPaths(paths: readonly string[]): ProtectedPathLease {\n\tconst claimed = paths.filter((path) => path.length > 0);\n\tfor (const path of claimed) {\n\t\tprotectedPathCounts.set(path, (protectedPathCounts.get(path) ?? 0) + 1);\n\t}\n\tlet released = false;\n\treturn {\n\t\trelease() {\n\t\t\tif (released) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\treleased = true;\n\t\t\tfor (const path of claimed) {\n\t\t\t\tconst remaining = (protectedPathCounts.get(path) ?? 0) - 1;\n\t\t\t\tif (remaining > 0) {\n\t\t\t\t\tprotectedPathCounts.set(path, remaining);\n\t\t\t\t} else {\n\t\t\t\t\tprotectedPathCounts.delete(path);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t};\n}\n\n/**\n * Make `sessionId` the default target for writers without a session handle.\n *\n * Deliberately separate from protection: a disposed session must stop protecting\n * its tree, but whichever session ran last still names where an unattached\n * writer spills.\n */\nexport function setActiveSessionTempId(sessionId: string): string {\n\tactiveSessionId = sessionId;\n\treturn resolveSessionTempDirPath(sessionId);\n}\n\n/** Directories this process must not reap: session temp trees and live tool-results. */\nexport function getProtectedSessionTempDirs(): ReadonlySet<string> {\n\treturn new Set(protectedPathCounts.keys());\n}\n\n/** Test seam: forget the process-level active/protected session state. */\nexport function resetSessionTempDirStateForTesting(): void {\n\tactiveSessionId = undefined;\n\tprotectedPathCounts.clear();\n\tensuredDirs.clear();\n\tcachedOwnerComponent = undefined;\n\tcachedBaseTempDirs = undefined;\n\tresetWindowsDirectorySecurityStateForTesting();\n}\n"]}
@@ -21,7 +21,7 @@ export function getUsageCostBreakdown(entries) {
21
21
  usage = entry.message.usage;
22
22
  key = usage ? "Tools/summaries" : undefined;
23
23
  }
24
- else if (entry.type === "branch_summary" && entry.usage) {
24
+ else if ((entry.type === "branch_summary" || entry.type === "session_summary") && entry.usage) {
25
25
  key = "Tools/summaries";
26
26
  usage = entry.usage;
27
27
  }
@@ -1 +1 @@
1
- {"version":3,"file":"usage-totals.js","sourceRoot":"","sources":["../../src/core/usage-totals.ts"],"names":[],"mappings":"AAWA,MAAM,U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C,CAAC,CAAC,SAAS,CAAC;QAC7C,CAAC;aAAM,IAAI,KAAK,CAAC,IAAI,KAAK,gBAAgB,IAAI,KAAK,CAAC,KAAK,EAAE,CAAC;YAC3D,GAAG,GAAG,iBAAiB,CAAC;YACxB,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC;QACrB,CAAC;QACD,IAAI,CAAC,GAAG,IAAI,CAAC,KAAK;YAAE,SAAS;QAC7B,MAAM,MAAM,GAAG,WAAW,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,iBAAiB,EAAE,CAAC;QAC3D,gBAAgB,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;QAChC,WAAW,CAAC,GAAG,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;IAC9B,CAAC;IACD,OAAO,CAAC,GAAG,WAAW,CAAC;SACrB,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,MAAM,CAAC,EAAE,EAAE,CAAC,CAAC;QACxB,GAAG;QACH,IAAI,EAAE,MAAM,CAAC,IAAI;QACjB,MAAM,EAAE,MAAM,CAAC,KAAK,GAAG,MAAM,CAAC,MAAM,GAAG,MAAM,CAAC,SAAS,GAAG,MAAM,CAAC,UAAU;KAC3E,CAAC,CAAC;SACF,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,GAAG,CAAC,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC;SACrD,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC;AACnC,CAAC","sourcesContent":["import type { Usage } from \"@earendil-works/pi-ai/compat\";\nimport type { SessionEntry } from \"./session-manager.ts\";\n\nexport interface UsageTotals {\n\tinput: number;\n\toutput: number;\n\tcacheRead: number;\n\tcacheWrite: number;\n\tcost: number;\n}\n\nexport function createUsageTotals(): UsageTotals {\n\treturn { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 };\n}\n\nexport function addUsageToTotals(totals: UsageTotals, usage: Usage): void {\n\ttotals.input += usage.input;\n\ttotals.output += usage.output;\n\ttotals.cacheRead += usage.cacheRead;\n\ttotals.cacheWrite += usage.cacheWrite;\n\ttotals.cost += usage.cost.total;\n}\n\nexport interface UsageCostBreakdownEntry {\n\tkey: string;\n\tcost: number;\n\ttokens: number;\n}\n\ntype MessageWithUsage = { role: \"toolResult\"; usage?: Usage };\n\nexport function getUsageCostBreakdown(entries: SessionEntry[]): UsageCostBreakdownEntry[] {\n\tconst totalsByKey = new Map<string, UsageTotals>();\n\tfor (const entry of entries) {\n\t\tlet key: string | undefined;\n\t\tlet usage: Usage | undefined;\n\t\tif (entry.type === \"message\" && entry.message.role === \"assistant\") {\n\t\t\tkey = `${entry.message.provider}/${entry.message.responseModel ?? entry.message.model}`;\n\t\t\tusage = entry.message.usage;\n\t\t} else if (entry.type === \"message\" && entry.message.role === \"toolResult\") {\n\t\t\tusage = (entry.message as MessageWithUsage).usage;\n\t\t\tkey = usage ? \"Tools/summaries\" : undefined;\n\t\t} else if (entry.type === \"branch_summary\" && entry.usage) {\n\t\t\tkey = \"Tools/summaries\";\n\t\t\tusage = entry.usage;\n\t\t}\n\t\tif (!key || !usage) continue;\n\t\tconst totals = totalsByKey.get(key) ?? createUsageTotals();\n\t\taddUsageToTotals(totals, usage);\n\t\ttotalsByKey.set(key, totals);\n\t}\n\treturn [...totalsByKey]\n\t\t.map(([key, totals]) => ({\n\t\t\tkey,\n\t\t\tcost: totals.cost,\n\t\t\ttokens: totals.input + totals.output + totals.cacheRead + totals.cacheWrite,\n\t\t}))\n\t\t.filter((entry) => entry.cost > 0 || entry.tokens > 0)\n\t\t.sort((a, b) => b.cost - a.cost);\n}\n"]}
1
+ {"version":3,"file":"usage-totals.js","sourceRoot":"","sources":["../../src/core/usage-totals.ts"],"names":[],"mappings":"AAWA,MAAM,UAAU,iBAAiB;IAChC,OAAO,EAAE,KAAK,EAAE,CAAC,E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,CAAC,KAAK,CAAC,IAAI,KAAK,gBAAgB,IAAI,KAAK,CAAC,IAAI,KAAK,iBAAiB,CAAC,IAAI,KAAK,CAAC,KAAK,EAAE,CAAC;YACjG,GAAG,GAAG,iBAAiB,CAAC;YACxB,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC;QACrB,CAAC;QACD,IAAI,CAAC,GAAG,IAAI,CAAC,KAAK;YAAE,SAAS;QAC7B,MAAM,MAAM,GAAG,WAAW,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,iBAAiB,EAAE,CAAC;QAC3D,gBAAgB,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;QAChC,WAAW,CAAC,GAAG,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;IAC9B,CAAC;IACD,OAAO,CAAC,GAAG,WAAW,CAAC;SACrB,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,MAAM,CAAC,EAAE,EAAE,CAAC,CAAC;QACxB,GAAG;QACH,IAAI,EAAE,MAAM,CAAC,IAAI;QACjB,MAAM,EAAE,MAAM,CAAC,KAAK,GAAG,MAAM,CAAC,MAAM,GAAG,MAAM,CAAC,SAAS,GAAG,MAAM,CAAC,UAAU;KAC3E,CAAC,CAAC;SACF,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,GAAG,CAAC,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC;SACrD,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC;AACnC,CAAC","sourcesContent":["import type { Usage } from \"@earendil-works/pi-ai/compat\";\nimport type { SessionEntry } from \"./session-manager.ts\";\n\nexport interface UsageTotals {\n\tinput: number;\n\toutput: number;\n\tcacheRead: number;\n\tcacheWrite: number;\n\tcost: number;\n}\n\nexport function createUsageTotals(): UsageTotals {\n\treturn { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 };\n}\n\nexport function addUsageToTotals(totals: UsageTotals, usage: Usage): void {\n\ttotals.input += usage.input;\n\ttotals.output += usage.output;\n\ttotals.cacheRead += usage.cacheRead;\n\ttotals.cacheWrite += usage.cacheWrite;\n\ttotals.cost += usage.cost.total;\n}\n\nexport interface UsageCostBreakdownEntry {\n\tkey: string;\n\tcost: number;\n\ttokens: number;\n}\n\ntype MessageWithUsage = { role: \"toolResult\"; usage?: Usage };\n\nexport function getUsageCostBreakdown(entries: SessionEntry[]): UsageCostBreakdownEntry[] {\n\tconst totalsByKey = new Map<string, UsageTotals>();\n\tfor (const entry of entries) {\n\t\tlet key: string | undefined;\n\t\tlet usage: Usage | undefined;\n\t\tif (entry.type === \"message\" && entry.message.role === \"assistant\") {\n\t\t\tkey = `${entry.message.provider}/${entry.message.responseModel ?? entry.message.model}`;\n\t\t\tusage = entry.message.usage;\n\t\t} else if (entry.type === \"message\" && entry.message.role === \"toolResult\") {\n\t\t\tusage = (entry.message as MessageWithUsage).usage;\n\t\t\tkey = usage ? \"Tools/summaries\" : undefined;\n\t\t} else if ((entry.type === \"branch_summary\" || entry.type === \"session_summary\") && entry.usage) {\n\t\t\tkey = \"Tools/summaries\";\n\t\t\tusage = entry.usage;\n\t\t}\n\t\tif (!key || !usage) continue;\n\t\tconst totals = totalsByKey.get(key) ?? createUsageTotals();\n\t\taddUsageToTotals(totals, usage);\n\t\ttotalsByKey.set(key, totals);\n\t}\n\treturn [...totalsByKey]\n\t\t.map(([key, totals]) => ({\n\t\t\tkey,\n\t\t\tcost: totals.cost,\n\t\t\ttokens: totals.input + totals.output + totals.cacheRead + totals.cacheWrite,\n\t\t}))\n\t\t.filter((entry) => entry.cost > 0 || entry.tokens > 0)\n\t\t.sort((a, b) => b.cost - a.cost);\n}\n"]}