@bastani/atomic 0.9.3-alpha.3 → 0.9.3-alpha.5

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 (332) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/dist/builtin/cursor/CHANGELOG.md +19 -0
  3. package/dist/builtin/cursor/README.md +2 -1
  4. package/dist/builtin/cursor/package.json +4 -3
  5. package/dist/builtin/cursor/src/auth.ts +1 -1
  6. package/dist/builtin/cursor/src/config.ts +1 -1
  7. package/dist/builtin/cursor/src/cursor-models-raw.json +82 -246
  8. package/dist/builtin/cursor/src/model-mapper.ts +97 -12
  9. package/dist/builtin/cursor/src/model-reference.ts +282 -0
  10. package/dist/builtin/cursor/src/proto/README.md +2 -2
  11. package/dist/builtin/cursor/src/proto/protobuf-codec-request.ts +1 -1
  12. package/dist/builtin/cursor/src/provider.ts +1 -1
  13. package/dist/builtin/cursor/src/stream.ts +1 -1
  14. package/dist/builtin/cursor/src/transport-types.ts +1 -1
  15. package/dist/builtin/intercom/CHANGELOG.md +12 -0
  16. package/dist/builtin/intercom/package.json +2 -2
  17. package/dist/builtin/mcp/CHANGELOG.md +12 -0
  18. package/dist/builtin/mcp/package.json +3 -3
  19. package/dist/builtin/mcp/sampling-handler.ts +1 -1
  20. package/dist/builtin/mcp/types.ts +1 -1
  21. package/dist/builtin/subagents/CHANGELOG.md +12 -0
  22. package/dist/builtin/subagents/package.json +4 -4
  23. package/dist/builtin/subagents/src/runs/background/subagent-runner-streaming.ts +1 -1
  24. package/dist/builtin/subagents/src/runs/background/subagent-runner-types.ts +1 -1
  25. package/dist/builtin/subagents/src/runs/foreground/execution-attempt.ts +1 -1
  26. package/dist/builtin/subagents/src/runs/shared/structured-output.ts +1 -1
  27. package/dist/builtin/subagents/src/shared/types-results.ts +1 -1
  28. package/dist/builtin/subagents/src/shared/utils.ts +1 -1
  29. package/dist/builtin/subagents/src/slash/slash-live-state.ts +1 -1
  30. package/dist/builtin/web-access/CHANGELOG.md +12 -0
  31. package/dist/builtin/web-access/package.json +2 -2
  32. package/dist/builtin/web-access/summary-review.ts +1 -1
  33. package/dist/builtin/web-access/web-search-summary.ts +1 -1
  34. package/dist/builtin/web-access/web-search-tool.ts +1 -1
  35. package/dist/builtin/workflows/CHANGELOG.md +12 -0
  36. package/dist/builtin/workflows/README.md +2 -0
  37. package/dist/builtin/workflows/package.json +2 -2
  38. package/dist/builtin/workflows/src/extension/workflow-prompts.ts +6 -3
  39. package/dist/bun/register-bedrock.d.ts.map +1 -1
  40. package/dist/bun/register-bedrock.js +1 -1
  41. package/dist/bun/register-bedrock.js.map +1 -1
  42. package/dist/cli/file-processor.d.ts +1 -1
  43. package/dist/cli/file-processor.d.ts.map +1 -1
  44. package/dist/cli/file-processor.js.map +1 -1
  45. package/dist/cli/initial-message.d.ts +1 -1
  46. package/dist/cli/initial-message.d.ts.map +1 -1
  47. package/dist/cli/initial-message.js.map +1 -1
  48. package/dist/cli/list-models.d.ts.map +1 -1
  49. package/dist/cli/list-models.js.map +1 -1
  50. package/dist/core/agent-session-auto-compaction.d.ts +1 -1
  51. package/dist/core/agent-session-auto-compaction.d.ts.map +1 -1
  52. package/dist/core/agent-session-auto-compaction.js +1 -1
  53. package/dist/core/agent-session-auto-compaction.js.map +1 -1
  54. package/dist/core/agent-session-events.d.ts +1 -1
  55. package/dist/core/agent-session-events.d.ts.map +1 -1
  56. package/dist/core/agent-session-events.js +1 -1
  57. package/dist/core/agent-session-events.js.map +1 -1
  58. package/dist/core/agent-session-export.d.ts.map +1 -1
  59. package/dist/core/agent-session-export.js.map +1 -1
  60. package/dist/core/agent-session-extension-bindings.d.ts.map +1 -1
  61. package/dist/core/agent-session-extension-bindings.js +1 -1
  62. package/dist/core/agent-session-extension-bindings.js.map +1 -1
  63. package/dist/core/agent-session-message-queue.d.ts +1 -1
  64. package/dist/core/agent-session-message-queue.d.ts.map +1 -1
  65. package/dist/core/agent-session-message-queue.js.map +1 -1
  66. package/dist/core/agent-session-methods.d.ts +1 -1
  67. package/dist/core/agent-session-methods.d.ts.map +1 -1
  68. package/dist/core/agent-session-methods.js.map +1 -1
  69. package/dist/core/agent-session-models.d.ts +1 -1
  70. package/dist/core/agent-session-models.d.ts.map +1 -1
  71. package/dist/core/agent-session-models.js +1 -1
  72. package/dist/core/agent-session-models.js.map +1 -1
  73. package/dist/core/agent-session-prompt.d.ts +1 -1
  74. package/dist/core/agent-session-prompt.d.ts.map +1 -1
  75. package/dist/core/agent-session-prompt.js.map +1 -1
  76. package/dist/core/agent-session-retry.d.ts +1 -1
  77. package/dist/core/agent-session-retry.d.ts.map +1 -1
  78. package/dist/core/agent-session-retry.js +1 -1
  79. package/dist/core/agent-session-retry.js.map +1 -1
  80. package/dist/core/agent-session-services.d.ts +1 -1
  81. package/dist/core/agent-session-services.d.ts.map +1 -1
  82. package/dist/core/agent-session-services.js.map +1 -1
  83. package/dist/core/agent-session-state.d.ts +1 -1
  84. package/dist/core/agent-session-state.d.ts.map +1 -1
  85. package/dist/core/agent-session-state.js.map +1 -1
  86. package/dist/core/agent-session-types.d.ts +1 -1
  87. package/dist/core/agent-session-types.d.ts.map +1 -1
  88. package/dist/core/agent-session-types.js.map +1 -1
  89. package/dist/core/agent-session.d.ts +1 -1
  90. package/dist/core/agent-session.d.ts.map +1 -1
  91. package/dist/core/agent-session.js.map +1 -1
  92. package/dist/core/anthropic-thinking-guard.d.ts +1 -1
  93. package/dist/core/anthropic-thinking-guard.d.ts.map +1 -1
  94. package/dist/core/anthropic-thinking-guard.js.map +1 -1
  95. package/dist/core/atomic-guide-command.d.ts.map +1 -1
  96. package/dist/core/atomic-guide-command.js +15 -11
  97. package/dist/core/atomic-guide-command.js.map +1 -1
  98. package/dist/core/auth-storage.d.ts +2 -2
  99. package/dist/core/auth-storage.d.ts.map +1 -1
  100. package/dist/core/auth-storage.js +1 -1
  101. package/dist/core/auth-storage.js.map +1 -1
  102. package/dist/core/codex-fast-mode.d.ts +1 -1
  103. package/dist/core/codex-fast-mode.d.ts.map +1 -1
  104. package/dist/core/codex-fast-mode.js +1 -1
  105. package/dist/core/codex-fast-mode.js.map +1 -1
  106. package/dist/core/compaction/branch-summarization.d.ts +1 -1
  107. package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
  108. package/dist/core/compaction/branch-summarization.js +1 -1
  109. package/dist/core/compaction/branch-summarization.js.map +1 -1
  110. package/dist/core/compaction/compaction.d.ts +1 -1
  111. package/dist/core/compaction/compaction.d.ts.map +1 -1
  112. package/dist/core/compaction/compaction.js.map +1 -1
  113. package/dist/core/compaction/context-compaction-runner.d.ts +1 -1
  114. package/dist/core/compaction/context-compaction-runner.d.ts.map +1 -1
  115. package/dist/core/compaction/context-compaction-runner.js +1 -1
  116. package/dist/core/compaction/context-compaction-runner.js.map +1 -1
  117. package/dist/core/compaction/context-deletion-tool-definitions.d.ts.map +1 -1
  118. package/dist/core/compaction/context-deletion-tool-definitions.js +1 -1
  119. package/dist/core/compaction/context-deletion-tool-definitions.js.map +1 -1
  120. package/dist/core/compaction/context-transcript-analysis.d.ts.map +1 -1
  121. package/dist/core/compaction/context-transcript-analysis.js.map +1 -1
  122. package/dist/core/compaction/utils.d.ts +1 -1
  123. package/dist/core/compaction/utils.d.ts.map +1 -1
  124. package/dist/core/compaction/utils.js.map +1 -1
  125. package/dist/core/context-window.d.ts +2 -2
  126. package/dist/core/context-window.d.ts.map +1 -1
  127. package/dist/core/context-window.js.map +1 -1
  128. package/dist/core/copilot-gemini-payload-sanitizer.d.ts +1 -1
  129. package/dist/core/copilot-gemini-payload-sanitizer.d.ts.map +1 -1
  130. package/dist/core/copilot-gemini-payload-sanitizer.js.map +1 -1
  131. package/dist/core/copilot-gemini-reasoning.d.ts +1 -1
  132. package/dist/core/copilot-gemini-reasoning.d.ts.map +1 -1
  133. package/dist/core/copilot-gemini-reasoning.js.map +1 -1
  134. package/dist/core/copilot-gemini-tool-arguments.d.ts +1 -1
  135. package/dist/core/copilot-gemini-tool-arguments.d.ts.map +1 -1
  136. package/dist/core/copilot-gemini-tool-arguments.js.map +1 -1
  137. package/dist/core/export-html/tool-renderer.d.ts.map +1 -1
  138. package/dist/core/export-html/tool-renderer.js.map +1 -1
  139. package/dist/core/extensions/agent-events.d.ts +1 -1
  140. package/dist/core/extensions/agent-events.d.ts.map +1 -1
  141. package/dist/core/extensions/agent-events.js.map +1 -1
  142. package/dist/core/extensions/api-types.d.ts +1 -1
  143. package/dist/core/extensions/api-types.d.ts.map +1 -1
  144. package/dist/core/extensions/api-types.js.map +1 -1
  145. package/dist/core/extensions/context-types.d.ts +1 -1
  146. package/dist/core/extensions/context-types.d.ts.map +1 -1
  147. package/dist/core/extensions/context-types.js.map +1 -1
  148. package/dist/core/extensions/event-results.d.ts +1 -1
  149. package/dist/core/extensions/event-results.d.ts.map +1 -1
  150. package/dist/core/extensions/event-results.js.map +1 -1
  151. package/dist/core/extensions/loader-virtual-modules.d.ts +12 -0
  152. package/dist/core/extensions/loader-virtual-modules.d.ts.map +1 -1
  153. package/dist/core/extensions/loader-virtual-modules.js +18 -2
  154. package/dist/core/extensions/loader-virtual-modules.js.map +1 -1
  155. package/dist/core/extensions/provider-types.d.ts +1 -1
  156. package/dist/core/extensions/provider-types.d.ts.map +1 -1
  157. package/dist/core/extensions/provider-types.js.map +1 -1
  158. package/dist/core/extensions/runner-context.d.ts +1 -1
  159. package/dist/core/extensions/runner-context.d.ts.map +1 -1
  160. package/dist/core/extensions/runner-context.js.map +1 -1
  161. package/dist/core/extensions/runner-events.d.ts +1 -1
  162. package/dist/core/extensions/runner-events.d.ts.map +1 -1
  163. package/dist/core/extensions/runner-events.js.map +1 -1
  164. package/dist/core/extensions/runner.d.ts +1 -1
  165. package/dist/core/extensions/runner.d.ts.map +1 -1
  166. package/dist/core/extensions/runner.js.map +1 -1
  167. package/dist/core/extensions/runtime-types.d.ts +1 -1
  168. package/dist/core/extensions/runtime-types.d.ts.map +1 -1
  169. package/dist/core/extensions/runtime-types.js.map +1 -1
  170. package/dist/core/extensions/tool-events.d.ts +1 -1
  171. package/dist/core/extensions/tool-events.d.ts.map +1 -1
  172. package/dist/core/extensions/tool-events.js.map +1 -1
  173. package/dist/core/footer-data-provider.d.ts +5 -0
  174. package/dist/core/footer-data-provider.d.ts.map +1 -1
  175. package/dist/core/footer-data-provider.js +46 -12
  176. package/dist/core/footer-data-provider.js.map +1 -1
  177. package/dist/core/http-dispatcher.d.ts +3 -1
  178. package/dist/core/http-dispatcher.d.ts.map +1 -1
  179. package/dist/core/http-dispatcher.js +4 -1
  180. package/dist/core/http-dispatcher.js.map +1 -1
  181. package/dist/core/keybindings.d.ts +1 -1
  182. package/dist/core/messages.d.ts +1 -1
  183. package/dist/core/messages.d.ts.map +1 -1
  184. package/dist/core/messages.js.map +1 -1
  185. package/dist/core/model-registry-auth.d.ts +1 -1
  186. package/dist/core/model-registry-auth.d.ts.map +1 -1
  187. package/dist/core/model-registry-auth.js.map +1 -1
  188. package/dist/core/model-registry-builtins.d.ts +1 -1
  189. package/dist/core/model-registry-builtins.d.ts.map +1 -1
  190. package/dist/core/model-registry-builtins.js +1 -1
  191. package/dist/core/model-registry-builtins.js.map +1 -1
  192. package/dist/core/model-registry-custom-loader.d.ts.map +1 -1
  193. package/dist/core/model-registry-custom-loader.js +1 -1
  194. package/dist/core/model-registry-custom-loader.js.map +1 -1
  195. package/dist/core/model-registry-dynamic.d.ts +1 -1
  196. package/dist/core/model-registry-dynamic.d.ts.map +1 -1
  197. package/dist/core/model-registry-dynamic.js +1 -1
  198. package/dist/core/model-registry-dynamic.js.map +1 -1
  199. package/dist/core/model-registry-loader.d.ts.map +1 -1
  200. package/dist/core/model-registry-loader.js.map +1 -1
  201. package/dist/core/model-registry-types.d.ts +1 -1
  202. package/dist/core/model-registry-types.d.ts.map +1 -1
  203. package/dist/core/model-registry-types.js.map +1 -1
  204. package/dist/core/model-registry.d.ts +1 -1
  205. package/dist/core/model-registry.d.ts.map +1 -1
  206. package/dist/core/model-registry.js +1 -1
  207. package/dist/core/model-registry.js.map +1 -1
  208. package/dist/core/model-resolver-cli.d.ts.map +1 -1
  209. package/dist/core/model-resolver-cli.js.map +1 -1
  210. package/dist/core/model-resolver-defaults.d.ts +1 -1
  211. package/dist/core/model-resolver-defaults.d.ts.map +1 -1
  212. package/dist/core/model-resolver-defaults.js.map +1 -1
  213. package/dist/core/model-resolver-initial.d.ts +1 -1
  214. package/dist/core/model-resolver-initial.d.ts.map +1 -1
  215. package/dist/core/model-resolver-initial.js.map +1 -1
  216. package/dist/core/model-resolver-patterns.d.ts +1 -1
  217. package/dist/core/model-resolver-patterns.d.ts.map +1 -1
  218. package/dist/core/model-resolver-patterns.js.map +1 -1
  219. package/dist/core/model-resolver-scope.d.ts.map +1 -1
  220. package/dist/core/model-resolver-scope.js +1 -1
  221. package/dist/core/model-resolver-scope.js.map +1 -1
  222. package/dist/core/model-resolver-types.d.ts +1 -1
  223. package/dist/core/model-resolver-types.d.ts.map +1 -1
  224. package/dist/core/model-resolver-types.js.map +1 -1
  225. package/dist/core/provider-attribution.d.ts +2 -2
  226. package/dist/core/provider-attribution.d.ts.map +1 -1
  227. package/dist/core/provider-attribution.js +4 -0
  228. package/dist/core/provider-attribution.js.map +1 -1
  229. package/dist/core/sdk-types.d.ts +1 -1
  230. package/dist/core/sdk-types.d.ts.map +1 -1
  231. package/dist/core/sdk-types.js.map +1 -1
  232. package/dist/core/sdk.d.ts +1 -1
  233. package/dist/core/sdk.d.ts.map +1 -1
  234. package/dist/core/sdk.js +2 -2
  235. package/dist/core/sdk.js.map +1 -1
  236. package/dist/core/session-manager-core.d.ts +1 -1
  237. package/dist/core/session-manager-core.d.ts.map +1 -1
  238. package/dist/core/session-manager-core.js.map +1 -1
  239. package/dist/core/session-manager-entries.d.ts +1 -1
  240. package/dist/core/session-manager-entries.d.ts.map +1 -1
  241. package/dist/core/session-manager-entries.js.map +1 -1
  242. package/dist/core/session-manager-list.d.ts.map +1 -1
  243. package/dist/core/session-manager-list.js.map +1 -1
  244. package/dist/core/session-manager-types.d.ts +1 -1
  245. package/dist/core/session-manager-types.d.ts.map +1 -1
  246. package/dist/core/session-manager-types.js.map +1 -1
  247. package/dist/core/settings-types.d.ts +1 -1
  248. package/dist/core/settings-types.d.ts.map +1 -1
  249. package/dist/core/settings-types.js.map +1 -1
  250. package/dist/core/tools/oversized-tool-result.d.ts +1 -1
  251. package/dist/core/tools/oversized-tool-result.d.ts.map +1 -1
  252. package/dist/core/tools/oversized-tool-result.js.map +1 -1
  253. package/dist/core/tools/read-url.d.ts +1 -1
  254. package/dist/core/tools/read-url.d.ts.map +1 -1
  255. package/dist/core/tools/read-url.js.map +1 -1
  256. package/dist/core/tools/read.d.ts.map +1 -1
  257. package/dist/core/tools/read.js.map +1 -1
  258. package/dist/core/tools/render-utils.d.ts +1 -1
  259. package/dist/core/tools/render-utils.d.ts.map +1 -1
  260. package/dist/core/tools/render-utils.js.map +1 -1
  261. package/dist/core/tools/todos-types.d.ts.map +1 -1
  262. package/dist/core/tools/todos-types.js +1 -1
  263. package/dist/core/tools/todos-types.js.map +1 -1
  264. package/dist/main-app-mode.d.ts +1 -1
  265. package/dist/main-app-mode.d.ts.map +1 -1
  266. package/dist/main-app-mode.js.map +1 -1
  267. package/dist/main-session-options.d.ts.map +1 -1
  268. package/dist/main-session-options.js +1 -1
  269. package/dist/main-session-options.js.map +1 -1
  270. package/dist/modes/interactive/components/assistant-message.d.ts +1 -1
  271. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
  272. package/dist/modes/interactive/components/assistant-message.js.map +1 -1
  273. package/dist/modes/interactive/components/chat-message-renderer.d.ts +1 -1
  274. package/dist/modes/interactive/components/chat-message-renderer.d.ts.map +1 -1
  275. package/dist/modes/interactive/components/chat-message-renderer.js.map +1 -1
  276. package/dist/modes/interactive/components/custom-message.d.ts.map +1 -1
  277. package/dist/modes/interactive/components/custom-message.js.map +1 -1
  278. package/dist/modes/interactive/components/model-selector.d.ts +1 -1
  279. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
  280. package/dist/modes/interactive/components/model-selector.js +1 -1
  281. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  282. package/dist/modes/interactive/components/scoped-models-selector.d.ts +1 -1
  283. package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -1
  284. package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -1
  285. package/dist/modes/interactive/components/settings-selector-handlers.d.ts.map +1 -1
  286. package/dist/modes/interactive/components/settings-selector-handlers.js +2 -2
  287. package/dist/modes/interactive/components/settings-selector-handlers.js.map +1 -1
  288. package/dist/modes/interactive/components/settings-selector-types.d.ts +1 -1
  289. package/dist/modes/interactive/components/settings-selector-types.d.ts.map +1 -1
  290. package/dist/modes/interactive/components/settings-selector-types.js.map +1 -1
  291. package/dist/modes/interactive/interactive-mode-deps.d.ts +1 -1
  292. package/dist/modes/interactive/interactive-mode-deps.d.ts.map +1 -1
  293. package/dist/modes/interactive/interactive-mode-deps.js +1 -1
  294. package/dist/modes/interactive/interactive-mode-deps.js.map +1 -1
  295. package/dist/modes/print-mode.d.ts +1 -1
  296. package/dist/modes/print-mode.d.ts.map +1 -1
  297. package/dist/modes/print-mode.js.map +1 -1
  298. package/dist/modes/rpc/rpc-client.d.ts +1 -1
  299. package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
  300. package/dist/modes/rpc/rpc-client.js.map +1 -1
  301. package/dist/modes/rpc/rpc-types.d.ts +1 -1
  302. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  303. package/dist/modes/rpc/rpc-types.js.map +1 -1
  304. package/docs/changelog.mdx +15 -0
  305. package/docs/custom-provider.md +2 -1
  306. package/docs/models.md +2 -0
  307. package/docs/providers.md +3 -1
  308. package/docs/quickstart.md +6 -4
  309. package/docs/sdk.md +2 -2
  310. package/docs/settings.md +4 -4
  311. package/docs/workflows.md +11 -6
  312. package/examples/extensions/custom-footer.ts +1 -1
  313. package/examples/extensions/custom-provider-anthropic/index.ts +1 -1
  314. package/examples/extensions/custom-provider-gitlab-duo/index.ts +1 -1
  315. package/examples/extensions/custom-provider-gitlab-duo/test.ts +1 -1
  316. package/examples/extensions/handoff.ts +1 -1
  317. package/examples/extensions/hello.ts +1 -1
  318. package/examples/extensions/plan-mode/index.ts +1 -1
  319. package/examples/extensions/preset.ts +1 -1
  320. package/examples/extensions/qna.ts +1 -1
  321. package/examples/extensions/subagent/display.ts +1 -1
  322. package/examples/extensions/subagent/runner.ts +1 -1
  323. package/examples/extensions/subagent/schemas.ts +1 -1
  324. package/examples/extensions/subagent/types.ts +1 -1
  325. package/examples/extensions/summarize.ts +1 -1
  326. package/examples/extensions/tic-tac-toe.ts +1 -1
  327. package/examples/extensions/todo.ts +1 -1
  328. package/examples/extensions/tool-override.ts +1 -1
  329. package/examples/sdk/02-custom-model.ts +1 -1
  330. package/examples/sdk/12-full-control.ts +1 -1
  331. package/examples/sdk/README.md +1 -1
  332. package/package.json +5 -5
@@ -1 +1 @@
1
- {"version":3,"file":"oversized-tool-result.js","sourceRoot":"","sources":["../../../src/core/tools/oversized-tool-result.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AACpD,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAGjC,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EACN,6BAA6B,EAC7B,4BAA4B,EAC5B,oBAAoB,EACpB,kBAAkB,EAClB,mBAAmB,GACnB,MAAM,kBAAkB,CAAC;AAE1B;;;;;;;GAOG;AACH,MAAM,UAAU,uBAAuB,CAAC,0BAAmC;IAC1E,IAAI,0BAA0B,KAAK,SAAS,EAAE,CAAC;QAC9C,OAAO,6BAA6B,CAAC;IACtC,CAAC;IACD,IAAI,CAAC,MAAM,CAAC,QAAQ,CA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AAM,OAAO,GAAG,2BAA2B,CAAC;QAC3C,iBAAiB,EAAE,MAAM,CAAC,UAAU,CAAC,IAAI,EAAE,MAAM,CAAC;QAClD,QAAQ;QACR,OAAO;QACP,OAAO;KACP,CAAC,CAAC;IAEH,OAAO;QACN,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC;QAC1C,+EAA+E;QAC/E,kEAAkE;QAClE,OAAO,EAAE,KAAK,CAAC,MAAM,CAAC,OAAO;QAC7B,OAAO,EAAE,KAAK,CAAC,OAAO;KACtB,CAAC;AACH,CAAC","sourcesContent":["import { Buffer } from \"node:buffer\";\nimport { mkdir, writeFile } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport type { AgentToolResult } from \"@earendil-works/pi-agent-core\";\nimport type { ImageContent, TextContent } from \"@earendil-works/pi-ai\";\nimport { APP_NAME } from \"../../config.js\";\nimport {\n\tDEFAULT_MAX_RESULT_SIZE_CHARS,\n\tPERSISTED_OUTPUT_CLOSING_TAG,\n\tPERSISTED_OUTPUT_TAG,\n\tPREVIEW_SIZE_BYTES,\n\tTOOL_RESULTS_SUBDIR,\n} from \"./tool-limits.js\";\n\n/**\n * Resolve the effective persistence threshold (in characters) for a tool.\n *\n * Mirrors the upstream `getPersistenceThreshold` convention: a tool may declare a\n * lower per-tool cap, but the global {@link DEFAULT_MAX_RESULT_SIZE_CHARS} acts as\n * a system-wide ceiling. `Infinity` is a hard opt-out for self-bounded tools whose\n * output is already a file the model reads back, where persisting would be circular.\n */\nexport function getPersistenceThreshold(declaredMaxResultSizeChars?: number): number {\n\tif (declaredMaxResultSizeChars === undefined) {\n\t\treturn DEFAULT_MAX_RESULT_SIZE_CHARS;\n\t}\n\tif (!Number.isFinite(declaredMaxResultSizeChars)) {\n\t\treturn declaredMaxResultSizeChars;\n\t}\n\treturn Math.min(declaredMaxResultSizeChars, DEFAULT_MAX_RESULT_SIZE_CHARS);\n}\n\nexport interface RedirectOversizedToolResultInput<TDetails = unknown> {\n\ttoolName: string;\n\ttoolCallId: string;\n\tresult: Pick<AgentToolResult<TDetails>, \"content\" | \"details\">;\n\tisError: boolean;\n\tsessionId: string;\n\tsessionDir?: string;\n\t/** Optional per-tool character cap; clamped by {@link DEFAULT_MAX_RESULT_SIZE_CHARS}. */\n\tmaxResultSizeChars?: number;\n}\n\nexport interface OversizedToolResultReplacement {\n\tcontent: TextContent[];\n\tdetails: unknown;\n\tisError: boolean;\n}\n\n/**\n * Human-readable byte size, e.g. `1536` → \"1.5KB\". Intentionally mirrors\n * upstream Claude Code `formatFileSize` wording instead of using tools/truncate.ts.\n */\nexport function formatFileSize(sizeInBytes: number): string {\n\tconst kb = sizeInBytes / 1024;\n\tif (kb < 1) {\n\t\treturn `${sizeInBytes} bytes`;\n\t}\n\tif (kb < 1024) {\n\t\treturn `${kb.toFixed(1).replace(/\\.0$/, \"\")}KB`;\n\t}\n\tconst mb = kb / 1024;\n\tif (mb < 1024) {\n\t\treturn `${mb.toFixed(1).replace(/\\.0$/, \"\")}MB`;\n\t}\n\tconst gb = mb / 1024;\n\treturn `${gb.toFixed(1).replace(/\\.0$/, \"\")}GB`;\n}\n\nfunction hasImageBlock(content: readonly (TextContent | ImageContent)[]): boolean {\n\treturn content.some((block) => block.type === \"image\");\n}\n\n/** Concatenate the text blocks of a tool result into a single string. */\nfunction collectText(content: readonly (TextContent | ImageContent)[]): string {\n\treturn content\n\t\t.filter((block): block is TextContent => block.type === \"text\")\n\t\t.map((block) => block.text)\n\t\t.join(\"\");\n}\n\n/**\n * Generate a preview of content, truncating at a newline boundary when possible.\n * Ported from the reference `generatePreview`.\n */\nexport function generatePreview(content: string, maxBytes: number): { preview: string; hasMore: boolean } {\n\tif (Buffer.byteLength(content, \"utf8\") <= maxBytes) {\n\t\treturn { preview: content, hasMore: false };\n\t}\n\n\tlet bytes = 0;\n\tlet hardCutIndex = 0;\n\tlet lastNewlineIndex = -1;\n\tlet lastNewlineBytes = 0;\n\n\tfor (const character of content) {\n\t\tconst characterBytes = Buffer.byteLength(character, \"utf8\");\n\t\tif (bytes + characterBytes > maxBytes) {\n\t\t\tbreak;\n\t\t}\n\t\tconst characterStartIndex = hardCutIndex;\n\t\tbytes += characterBytes;\n\t\thardCutIndex += character.length;\n\t\tif (character === \"\\n\") {\n\t\t\tlastNewlineIndex = characterStartIndex;\n\t\t\tlastNewlineBytes = bytes - characterBytes;\n\t\t}\n\t}\n\n\t// Find the last newline within the byte limit to avoid cutting mid-line;\n\t// fall back to the hard byte limit when the newline is too close to the start.\n\tconst cutPoint = lastNewlineBytes > maxBytes * 0.5 ? lastNewlineIndex : hardCutIndex;\n\treturn { preview: content.slice(0, cutPoint), hasMore: true };\n}\n\n/**\n * Build the `<persisted-output>` preview message shown to the model in place of\n * the oversized content. Ported from the reference `buildLargeToolResultMessage`.\n */\nfunction buildPersistedOutputMessage(input: {\n\toriginalSizeBytes: number;\n\tfilepath: string;\n\tpreview: string;\n\thasMore: boolean;\n}): string {\n\tlet message = `${PERSISTED_OUTPUT_TAG}\\n`;\n\tmessage += `Output too large (${formatFileSize(input.originalSizeBytes)}). Full output saved to: ${input.filepath}\\n\\n`;\n\tmessage += `Preview (first ${formatFileSize(PREVIEW_SIZE_BYTES)}):\\n`;\n\tmessage += input.preview;\n\tmessage += input.hasMore ? \"\\n...\\n\" : \"\\n\";\n\tmessage += PERSISTED_OUTPUT_CLOSING_TAG;\n\treturn message;\n}\n\n/** Strip leading/trailing underscores with a linear scan (no backtracking regex). */\nfunction trimUnderscores(value: string): string {\n\tlet start = 0;\n\tlet end = value.length;\n\twhile (start < end && value[start] === \"_\") {\n\t\tstart++;\n\t}\n\twhile (end > start && value[end - 1] === \"_\") {\n\t\tend--;\n\t}\n\treturn value.slice(start, end);\n}\n\nfunction sanitizePathComponent(value: string, fallback: string): string {\n\t// Collapse disallowed characters to \"_\", then strip leading/trailing \"_\". The trim uses\n\t// a manual linear scan instead of a /^_+|_+$/ regex to avoid a polynomial-time ReDoS on\n\t// tool-call ids containing long runs of underscores (CodeQL js/polynomial-redos).\n\tconst sanitized = trimUnderscores(value.replace(/[^a-zA-Z0-9._-]+/g, \"_\")).slice(0, 64);\n\treturn sanitized.length > 0 ? sanitized : fallback;\n}\n\n/** Session-scoped directory for persisted tool results: `<sessionDir>/tool-results`. */\nfunction getToolResultsDir(input: { sessionDir?: string; sessionId: string }): string {\n\tif (input.sessionDir?.trim()) {\n\t\treturn join(input.sessionDir, TOOL_RESULTS_SUBDIR);\n\t}\n\t// Fall back to a stable session-scoped temp directory for in-memory sessions.\n\tconst safeApp = sanitizePathComponent(APP_NAME || \"atomic\", \"atomic\");\n\tconst safeSessionId = sanitizePathComponent(input.sessionId || \"session\", \"session\");\n\treturn join(tmpdir(), `${safeApp}-${TOOL_RESULTS_SUBDIR}`, safeSessionId);\n}\n\nfunction getErrnoCode(error: unknown): string | undefined {\n\tif (error && typeof error === \"object\" && \"code\" in error) {\n\t\tconst code = (error as { code?: unknown }).code;\n\t\treturn typeof code === \"string\" ? code : undefined;\n\t}\n\treturn undefined;\n}\n\n/**\n * Persist the full tool output to a session-scoped file and return its path.\n *\n * The tool_use_id is unique per invocation and the content is deterministic for a\n * given id, so we write with the `wx` flag and treat `EEXIST` as success — this\n * makes repeated calls (e.g. replay/compaction) idempotent without rewriting.\n * Returns `undefined` on any other write failure so the caller can fall back to\n * returning the original result unchanged.\n */\nasync function persistToolOutput(input: {\n\ttext: string;\n\tsessionDir?: string;\n\tsessionId: string;\n\ttoolCallId: string;\n}): Promise<string | undefined> {\n\tconst dir = getToolResultsDir({ sessionDir: input.sessionDir, sessionId: input.sessionId });\n\tconst fileName = `${sanitizePathComponent(input.toolCallId, \"tool-result\")}.txt`;\n\tconst filepath = join(dir, fileName);\n\ttry {\n\t\tawait mkdir(dir, { recursive: true, mode: 0o700 });\n\t\tawait writeFile(filepath, input.text, { encoding: \"utf8\", mode: 0o600, flag: \"wx\" });\n\t} catch (error) {\n\t\tif (getErrnoCode(error) === \"EEXIST\") {\n\t\t\t// Already persisted on a prior turn — reuse the existing file.\n\t\t\treturn filepath;\n\t\t}\n\t\treturn undefined;\n\t}\n\treturn filepath;\n}\n\n/**\n * When a tool result's text content exceeds the persistence threshold (default\n * 50,000 chars — {@link DEFAULT_MAX_RESULT_SIZE_CHARS}), persist the full output\n * to a session-scoped file and replace the model-visible content with a\n * `<persisted-output>` preview that references the saved file.\n *\n * Returns `undefined` (leave the result untouched) when the result is within the\n * threshold, contains image blocks, or cannot be persisted to disk.\n *\n * Convention ported from the upstream `maybePersistLargeToolResult`\n * (mehmoodosman/claude-code, `src/utils/toolResultStorage.ts`).\n */\nexport async function redirectOversizedToolResult<TDetails = unknown>(\n\tinput: RedirectOversizedToolResultInput<TDetails>,\n): Promise<OversizedToolResultReplacement | undefined> {\n\tconst content = input.result.content;\n\n\t// Image content must be sent to the model as-is; never persist.\n\tif (hasImageBlock(content)) {\n\t\treturn undefined;\n\t}\n\n\tconst text = collectText(content);\n\tconst threshold = getPersistenceThreshold(input.maxResultSizeChars);\n\tif (text.length <= threshold) {\n\t\treturn undefined;\n\t}\n\n\tconst filepath = await persistToolOutput({\n\t\ttext,\n\t\tsessionDir: input.sessionDir,\n\t\tsessionId: input.sessionId,\n\t\ttoolCallId: input.toolCallId,\n\t});\n\t// Graceful degradation: if persistence failed, leave the original result unchanged.\n\tif (filepath === undefined) {\n\t\treturn undefined;\n\t}\n\n\tconst { preview, hasMore } = generatePreview(text, PREVIEW_SIZE_BYTES);\n\tconst message = buildPersistedOutputMessage({\n\t\toriginalSizeBytes: Buffer.byteLength(text, \"utf8\"),\n\t\tfilepath,\n\t\tpreview,\n\t\thasMore,\n\t});\n\n\treturn {\n\t\tcontent: [{ type: \"text\", text: message }],\n\t\t// Details (tool metadata) are passed through untouched, matching the reference\n\t\t// convention which only replaces the model-visible content block.\n\t\tdetails: input.result.details,\n\t\tisError: input.isError,\n\t};\n}\n"]}
1
+ {"version":3,"file":"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B,OAAO,SAAS,CAAC;IAClB,CAAC;IAED,MAAM,IAAI,GAAG,WAAW,CAAC,OAAO,CAAC,CAAC;IAClC,MAAM,SAAS,GAAG,uBAAuB,CAAC,KAAK,CAAC,kBAAkB,CAAC,CAAC;IACpE,IAAI,IAAI,CAAC,MAAM,IAAI,SAAS,EAAE,CAAC;QAC9B,OAAO,SAAS,CAAC;IAClB,CAAC;IAED,MAAM,QAAQ,GAAG,MAAM,iBAAiB,CAAC;QACxC,IAAI;QACJ,UAAU,EAAE,KAAK,CAAC,UAAU;QAC5B,SAAS,EAAE,KAAK,CAAC,SAAS;QAC1B,UAAU,EAAE,KAAK,CAAC,UAAU;KAC5B,CAAC,CAAC;IACH,oFAAoF;IACpF,IAAI,QAAQ,KAAK,SAAS,EAAE,CAAC;QAC5B,OAAO,SAAS,CAAC;IAClB,CAAC;IAED,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,GAAG,eAAe,CAAC,IAAI,EAAE,kBAAkB,CAAC,CAAC;IACvE,MAAM,OAAO,GAAG,2BAA2B,CAAC;QAC3C,iBAAiB,EAAE,MAAM,CAAC,UAAU,CAAC,IAAI,EAAE,MAAM,CAAC;QAClD,QAAQ;QACR,OAAO;QACP,OAAO;KACP,CAAC,CAAC;IAEH,OAAO;QACN,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC;QAC1C,+EAA+E;QAC/E,kEAAkE;QAClE,OAAO,EAAE,KAAK,CAAC,MAAM,CAAC,OAAO;QAC7B,OAAO,EAAE,KAAK,CAAC,OAAO;KACtB,CAAC;AACH,CAAC","sourcesContent":["import { Buffer } from \"node:buffer\";\nimport { mkdir, writeFile } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport type { AgentToolResult } from \"@earendil-works/pi-agent-core\";\nimport type { ImageContent, TextContent } from \"@earendil-works/pi-ai/compat\";\nimport { APP_NAME } from \"../../config.js\";\nimport {\n\tDEFAULT_MAX_RESULT_SIZE_CHARS,\n\tPERSISTED_OUTPUT_CLOSING_TAG,\n\tPERSISTED_OUTPUT_TAG,\n\tPREVIEW_SIZE_BYTES,\n\tTOOL_RESULTS_SUBDIR,\n} from \"./tool-limits.js\";\n\n/**\n * Resolve the effective persistence threshold (in characters) for a tool.\n *\n * Mirrors the upstream `getPersistenceThreshold` convention: a tool may declare a\n * lower per-tool cap, but the global {@link DEFAULT_MAX_RESULT_SIZE_CHARS} acts as\n * a system-wide ceiling. `Infinity` is a hard opt-out for self-bounded tools whose\n * output is already a file the model reads back, where persisting would be circular.\n */\nexport function getPersistenceThreshold(declaredMaxResultSizeChars?: number): number {\n\tif (declaredMaxResultSizeChars === undefined) {\n\t\treturn DEFAULT_MAX_RESULT_SIZE_CHARS;\n\t}\n\tif (!Number.isFinite(declaredMaxResultSizeChars)) {\n\t\treturn declaredMaxResultSizeChars;\n\t}\n\treturn Math.min(declaredMaxResultSizeChars, DEFAULT_MAX_RESULT_SIZE_CHARS);\n}\n\nexport interface RedirectOversizedToolResultInput<TDetails = unknown> {\n\ttoolName: string;\n\ttoolCallId: string;\n\tresult: Pick<AgentToolResult<TDetails>, \"content\" | \"details\">;\n\tisError: boolean;\n\tsessionId: string;\n\tsessionDir?: string;\n\t/** Optional per-tool character cap; clamped by {@link DEFAULT_MAX_RESULT_SIZE_CHARS}. */\n\tmaxResultSizeChars?: number;\n}\n\nexport interface OversizedToolResultReplacement {\n\tcontent: TextContent[];\n\tdetails: unknown;\n\tisError: boolean;\n}\n\n/**\n * Human-readable byte size, e.g. `1536` → \"1.5KB\". Intentionally mirrors\n * upstream Claude Code `formatFileSize` wording instead of using tools/truncate.ts.\n */\nexport function formatFileSize(sizeInBytes: number): string {\n\tconst kb = sizeInBytes / 1024;\n\tif (kb < 1) {\n\t\treturn `${sizeInBytes} bytes`;\n\t}\n\tif (kb < 1024) {\n\t\treturn `${kb.toFixed(1).replace(/\\.0$/, \"\")}KB`;\n\t}\n\tconst mb = kb / 1024;\n\tif (mb < 1024) {\n\t\treturn `${mb.toFixed(1).replace(/\\.0$/, \"\")}MB`;\n\t}\n\tconst gb = mb / 1024;\n\treturn `${gb.toFixed(1).replace(/\\.0$/, \"\")}GB`;\n}\n\nfunction hasImageBlock(content: readonly (TextContent | ImageContent)[]): boolean {\n\treturn content.some((block) => block.type === \"image\");\n}\n\n/** Concatenate the text blocks of a tool result into a single string. */\nfunction collectText(content: readonly (TextContent | ImageContent)[]): string {\n\treturn content\n\t\t.filter((block): block is TextContent => block.type === \"text\")\n\t\t.map((block) => block.text)\n\t\t.join(\"\");\n}\n\n/**\n * Generate a preview of content, truncating at a newline boundary when possible.\n * Ported from the reference `generatePreview`.\n */\nexport function generatePreview(content: string, maxBytes: number): { preview: string; hasMore: boolean } {\n\tif (Buffer.byteLength(content, \"utf8\") <= maxBytes) {\n\t\treturn { preview: content, hasMore: false };\n\t}\n\n\tlet bytes = 0;\n\tlet hardCutIndex = 0;\n\tlet lastNewlineIndex = -1;\n\tlet lastNewlineBytes = 0;\n\n\tfor (const character of content) {\n\t\tconst characterBytes = Buffer.byteLength(character, \"utf8\");\n\t\tif (bytes + characterBytes > maxBytes) {\n\t\t\tbreak;\n\t\t}\n\t\tconst characterStartIndex = hardCutIndex;\n\t\tbytes += characterBytes;\n\t\thardCutIndex += character.length;\n\t\tif (character === \"\\n\") {\n\t\t\tlastNewlineIndex = characterStartIndex;\n\t\t\tlastNewlineBytes = bytes - characterBytes;\n\t\t}\n\t}\n\n\t// Find the last newline within the byte limit to avoid cutting mid-line;\n\t// fall back to the hard byte limit when the newline is too close to the start.\n\tconst cutPoint = lastNewlineBytes > maxBytes * 0.5 ? lastNewlineIndex : hardCutIndex;\n\treturn { preview: content.slice(0, cutPoint), hasMore: true };\n}\n\n/**\n * Build the `<persisted-output>` preview message shown to the model in place of\n * the oversized content. Ported from the reference `buildLargeToolResultMessage`.\n */\nfunction buildPersistedOutputMessage(input: {\n\toriginalSizeBytes: number;\n\tfilepath: string;\n\tpreview: string;\n\thasMore: boolean;\n}): string {\n\tlet message = `${PERSISTED_OUTPUT_TAG}\\n`;\n\tmessage += `Output too large (${formatFileSize(input.originalSizeBytes)}). Full output saved to: ${input.filepath}\\n\\n`;\n\tmessage += `Preview (first ${formatFileSize(PREVIEW_SIZE_BYTES)}):\\n`;\n\tmessage += input.preview;\n\tmessage += input.hasMore ? \"\\n...\\n\" : \"\\n\";\n\tmessage += PERSISTED_OUTPUT_CLOSING_TAG;\n\treturn message;\n}\n\n/** Strip leading/trailing underscores with a linear scan (no backtracking regex). */\nfunction trimUnderscores(value: string): string {\n\tlet start = 0;\n\tlet end = value.length;\n\twhile (start < end && value[start] === \"_\") {\n\t\tstart++;\n\t}\n\twhile (end > start && value[end - 1] === \"_\") {\n\t\tend--;\n\t}\n\treturn value.slice(start, end);\n}\n\nfunction sanitizePathComponent(value: string, fallback: string): string {\n\t// Collapse disallowed characters to \"_\", then strip leading/trailing \"_\". The trim uses\n\t// a manual linear scan instead of a /^_+|_+$/ regex to avoid a polynomial-time ReDoS on\n\t// tool-call ids containing long runs of underscores (CodeQL js/polynomial-redos).\n\tconst sanitized = trimUnderscores(value.replace(/[^a-zA-Z0-9._-]+/g, \"_\")).slice(0, 64);\n\treturn sanitized.length > 0 ? sanitized : fallback;\n}\n\n/** Session-scoped directory for persisted tool results: `<sessionDir>/tool-results`. */\nfunction getToolResultsDir(input: { sessionDir?: string; sessionId: string }): string {\n\tif (input.sessionDir?.trim()) {\n\t\treturn join(input.sessionDir, TOOL_RESULTS_SUBDIR);\n\t}\n\t// Fall back to a stable session-scoped temp directory for in-memory sessions.\n\tconst safeApp = sanitizePathComponent(APP_NAME || \"atomic\", \"atomic\");\n\tconst safeSessionId = sanitizePathComponent(input.sessionId || \"session\", \"session\");\n\treturn join(tmpdir(), `${safeApp}-${TOOL_RESULTS_SUBDIR}`, safeSessionId);\n}\n\nfunction getErrnoCode(error: unknown): string | undefined {\n\tif (error && typeof error === \"object\" && \"code\" in error) {\n\t\tconst code = (error as { code?: unknown }).code;\n\t\treturn typeof code === \"string\" ? code : undefined;\n\t}\n\treturn undefined;\n}\n\n/**\n * Persist the full tool output to a session-scoped file and return its path.\n *\n * The tool_use_id is unique per invocation and the content is deterministic for a\n * given id, so we write with the `wx` flag and treat `EEXIST` as success — this\n * makes repeated calls (e.g. replay/compaction) idempotent without rewriting.\n * Returns `undefined` on any other write failure so the caller can fall back to\n * returning the original result unchanged.\n */\nasync function persistToolOutput(input: {\n\ttext: string;\n\tsessionDir?: string;\n\tsessionId: string;\n\ttoolCallId: string;\n}): Promise<string | undefined> {\n\tconst dir = getToolResultsDir({ sessionDir: input.sessionDir, sessionId: input.sessionId });\n\tconst fileName = `${sanitizePathComponent(input.toolCallId, \"tool-result\")}.txt`;\n\tconst filepath = join(dir, fileName);\n\ttry {\n\t\tawait mkdir(dir, { recursive: true, mode: 0o700 });\n\t\tawait writeFile(filepath, input.text, { encoding: \"utf8\", mode: 0o600, flag: \"wx\" });\n\t} catch (error) {\n\t\tif (getErrnoCode(error) === \"EEXIST\") {\n\t\t\t// Already persisted on a prior turn — reuse the existing file.\n\t\t\treturn filepath;\n\t\t}\n\t\treturn undefined;\n\t}\n\treturn filepath;\n}\n\n/**\n * When a tool result's text content exceeds the persistence threshold (default\n * 50,000 chars — {@link DEFAULT_MAX_RESULT_SIZE_CHARS}), persist the full output\n * to a session-scoped file and replace the model-visible content with a\n * `<persisted-output>` preview that references the saved file.\n *\n * Returns `undefined` (leave the result untouched) when the result is within the\n * threshold, contains image blocks, or cannot be persisted to disk.\n *\n * Convention ported from the upstream `maybePersistLargeToolResult`\n * (mehmoodosman/claude-code, `src/utils/toolResultStorage.ts`).\n */\nexport async function redirectOversizedToolResult<TDetails = unknown>(\n\tinput: RedirectOversizedToolResultInput<TDetails>,\n): Promise<OversizedToolResultReplacement | undefined> {\n\tconst content = input.result.content;\n\n\t// Image content must be sent to the model as-is; never persist.\n\tif (hasImageBlock(content)) {\n\t\treturn undefined;\n\t}\n\n\tconst text = collectText(content);\n\tconst threshold = getPersistenceThreshold(input.maxResultSizeChars);\n\tif (text.length <= threshold) {\n\t\treturn undefined;\n\t}\n\n\tconst filepath = await persistToolOutput({\n\t\ttext,\n\t\tsessionDir: input.sessionDir,\n\t\tsessionId: input.sessionId,\n\t\ttoolCallId: input.toolCallId,\n\t});\n\t// Graceful degradation: if persistence failed, leave the original result unchanged.\n\tif (filepath === undefined) {\n\t\treturn undefined;\n\t}\n\n\tconst { preview, hasMore } = generatePreview(text, PREVIEW_SIZE_BYTES);\n\tconst message = buildPersistedOutputMessage({\n\t\toriginalSizeBytes: Buffer.byteLength(text, \"utf8\"),\n\t\tfilepath,\n\t\tpreview,\n\t\thasMore,\n\t});\n\n\treturn {\n\t\tcontent: [{ type: \"text\", text: message }],\n\t\t// Details (tool metadata) are passed through untouched, matching the reference\n\t\t// convention which only replaces the model-visible content block.\n\t\tdetails: input.result.details,\n\t\tisError: input.isError,\n\t};\n}\n"]}
@@ -1,4 +1,4 @@
1
- import type { TextContent } from "@earendil-works/pi-ai";
1
+ import type { TextContent } from "@earendil-works/pi-ai/compat";
2
2
  import type { ReadToolDetails } from "./read.ts";
3
3
  export interface ReadUrlBranchArgs {
4
4
  effectivePath: string;
@@ -1 +1 @@
1
- {"version":3,"file":"read-url.d.ts","sourceRoot":"","sources":["../../../src/core/tools/read-url.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AACzD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,WAAW,CAAC;AAIjD,MAAM,WAAW,iBAAiB;IACjC,aAAa,EAAE,MAAM,CAAC;IACtB,SAAS,EAAE,OAAO,CAAC;IACnB,eAAe,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,GAAG,CAAC,EAAE,MAAM,CAAA;KAAE,EAAE,GAAG,SAAS,CAAC;IAC/D,eAAe,EAAE,MAAM,GAAG,SAAS,CAAC;IACpC,cAAc,EAAE,MAAM,GAAG,SAAS,CAAC;IACnC,GAAG,EAAE,MAAM,CAAC;IACZ,GAAG,EAAE,OAAO,CAAC;IACb,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,CAAC,OAAO,EAAE;QAAE,OAAO,EAAE,IAAI,CAAC;QAAC,IAAI,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAC;QAAC,QAAQ,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,MAAM,CAAC;QAAC,cAAc,EAAE,MAAM,CAAC;QAAC,cAAc,EAAE,MAAM,CAAC;QAAC,YAAY,EAAE,OAAO,CAAA;KAAE,KAAK;QAAE,OAAO,EAAE,WAAW,EAAE,CAAC;QAAC,OAAO,EAAE,eAAe,CAAA;KAAE,CAAC;IACzO,UAAU,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,eAAe,CAAC;CAChD;AAED,MAAM,MAAM,mBAAmB,GAAG;IAAE,OAAO,EAAE,WAAW,EAAE,CAAC;IAAC,OAAO,EAAE,eAAe,GAAG,SAAS,CAAA;CAAE,CAAC;AAEnG,wBAAsB,aAAa,CAAC,IAAI,EAAE,iBAAiB,GAAG,OAAO,CAAC,mBAAmB,CAAC,CA6BzF","sourcesContent":["/**\n * URL branch of the `read` tool: routes plain URL reads through the\n * cache/artifact/llms.txt fetch pipeline ({@link executeReadUrl}); explicit\n * URL line selectors reuse the same safe rendering path before slicing lines.\n */\nimport { resolve as resolvePath } from \"node:path\";\nimport type { TextContent } from \"@earendil-works/pi-ai\";\nimport type { ReadToolDetails } from \"./read.ts\";\nimport { applyReadLineSelection, decodeReadableUrl } from \"./read-document-extract.ts\";\nimport { executeReadUrl, loadPage } from \"./fetch-url.ts\";\n\nexport interface ReadUrlBranchArgs {\n\teffectivePath: string;\n\trawOutput: boolean;\n\teffectiveRanges: { start: number; end?: number }[] | undefined;\n\teffectiveOffset: number | undefined;\n\teffectiveLimit: number | undefined;\n\tcwd: string;\n\tctx: unknown;\n\tsignal?: AbortSignal;\n\tmaxChars: number;\n\tmaxBytes: number;\n\toversized: (details: { blocked: true; path: string; chars: number; maxChars: number; startLine: number; totalFileLines: number; firstLineBytes: number; byteGuidance: boolean }) => { content: TextContent[]; details: ReadToolDetails };\n\tsourceMeta: (source: string) => ReadToolDetails;\n}\n\nexport type ReadUrlBranchResult = { content: TextContent[]; details: ReadToolDetails | undefined };\n\nexport async function readUrlBranch(args: ReadUrlBranchArgs): Promise<ReadUrlBranchResult> {\n\tconst { effectivePath, rawOutput, effectiveRanges, effectiveOffset, effectiveLimit, cwd, ctx, signal, maxChars, maxBytes, oversized, sourceMeta } = args;\n\tconst session = (ctx as { sessionManager?: { getSessionDir?: () => string | undefined; getSessionId?: () => string | undefined } } | undefined)?.sessionManager;\n\tconst sessionDir = session?.getSessionDir?.();\n\tconst scope = session?.getSessionId?.() ?? cwd;\n\tconst artifactsDir = sessionDir ? resolvePath(sessionDir, \"artifacts\") : undefined;\n\tif (!effectiveRanges && !effectiveOffset && effectiveLimit === undefined) {\n\t\tconst result = await executeReadUrl(scope, { path: effectivePath, raw: rawOutput }, artifactsDir, signal);\n\t\tconst artifactId = result.artifactId ?? result.details.meta?.artifactId;\n\t\tconst truncation = result.details.meta?.truncation;\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text: result.content }],\n\t\t\tdetails: {\n\t\t\t\t...(truncation ? { truncation } : {}),\n\t\t\t\tmeta: { ...(result.details.meta ?? {}), source: effectivePath, sourcePath: effectivePath, ...(artifactId ? { artifactId } : {}) },\n\t\t\t},\n\t\t};\n\t}\n\tconst page = await loadPage(effectivePath, 10_000, signal);\n\tconst textContent = rawOutput ? page.content : await decodeReadableUrl(new Response(page.content, { headers: { \"content-type\": page.contentType } }), page.finalUrl || effectivePath);\n\tconst selection = applyReadLineSelection(textContent.split(\"\\n\"), effectiveRanges, effectiveOffset, effectiveLimit, rawOutput), selectedText = selection.lines.join(\"\\n\");\n\tif ((effectiveRanges || effectiveOffset) && selection.lines.length === 0) {\n\t\tconst requested = effectiveRanges?.[0]?.start ?? effectiveOffset ?? 1;\n\t\treturn { content: [{ type: \"text\", text: `Requested line ${requested} is beyond end of resource (${textContent.split(\"\\n\").length} lines total).` }], details: undefined };\n\t}\n\tif (selectedText.length > maxChars || Buffer.byteLength(selectedText, \"utf8\") > maxBytes) {\n\t\treturn oversized({ blocked: true, path: effectivePath, chars: selectedText.length, maxChars, startLine: selection.firstLine, totalFileLines: textContent.split(\"\\n\").length, firstLineBytes: Buffer.byteLength(selection.lines[0] ?? \"\", \"utf8\"), byteGuidance: false });\n\t}\n\treturn { content: [{ type: \"text\", text: rawOutput ? selectedText : `URL: ${effectivePath}\\nStatus: ${page.status}\\nContent-Type: ${page.contentType || \"unknown\"}\\n\\n${selectedText}` }], details: sourceMeta(effectivePath) };\n}\n"]}
1
+ {"version":3,"file":"read-url.d.ts","sourceRoot":"","sources":["../../../src/core/tools/read-url.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAAC;AAChE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,WAAW,CAAC;AAIjD,MAAM,WAAW,iBAAiB;IACjC,aAAa,EAAE,MAAM,CAAC;IACtB,SAAS,EAAE,OAAO,CAAC;IACnB,eAAe,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,GAAG,CAAC,EAAE,MAAM,CAAA;KAAE,EAAE,GAAG,SAAS,CAAC;IAC/D,eAAe,EAAE,MAAM,GAAG,SAAS,CAAC;IACpC,cAAc,EAAE,MAAM,GAAG,SAAS,CAAC;IACnC,GAAG,EAAE,MAAM,CAAC;IACZ,GAAG,EAAE,OAAO,CAAC;IACb,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,CAAC,OAAO,EAAE;QAAE,OAAO,EAAE,IAAI,CAAC;QAAC,IAAI,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAC;QAAC,QAAQ,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,MAAM,CAAC;QAAC,cAAc,EAAE,MAAM,CAAC;QAAC,cAAc,EAAE,MAAM,CAAC;QAAC,YAAY,EAAE,OAAO,CAAA;KAAE,KAAK;QAAE,OAAO,EAAE,WAAW,EAAE,CAAC;QAAC,OAAO,EAAE,eAAe,CAAA;KAAE,CAAC;IACzO,UAAU,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,eAAe,CAAC;CAChD;AAED,MAAM,MAAM,mBAAmB,GAAG;IAAE,OAAO,EAAE,WAAW,EAAE,CAAC;IAAC,OAAO,EAAE,eAAe,GAAG,SAAS,CAAA;CAAE,CAAC;AAEnG,wBAAsB,aAAa,CAAC,IAAI,EAAE,iBAAiB,GAAG,OAAO,CAAC,mBAAmB,CAAC,CA6BzF","sourcesContent":["/**\n * URL branch of the `read` tool: routes plain URL reads through the\n * cache/artifact/llms.txt fetch pipeline ({@link executeReadUrl}); explicit\n * URL line selectors reuse the same safe rendering path before slicing lines.\n */\nimport { resolve as resolvePath } from \"node:path\";\nimport type { TextContent } from \"@earendil-works/pi-ai/compat\";\nimport type { ReadToolDetails } from \"./read.ts\";\nimport { applyReadLineSelection, decodeReadableUrl } from \"./read-document-extract.ts\";\nimport { executeReadUrl, loadPage } from \"./fetch-url.ts\";\n\nexport interface ReadUrlBranchArgs {\n\teffectivePath: string;\n\trawOutput: boolean;\n\teffectiveRanges: { start: number; end?: number }[] | undefined;\n\teffectiveOffset: number | undefined;\n\teffectiveLimit: number | undefined;\n\tcwd: string;\n\tctx: unknown;\n\tsignal?: AbortSignal;\n\tmaxChars: number;\n\tmaxBytes: number;\n\toversized: (details: { blocked: true; path: string; chars: number; maxChars: number; startLine: number; totalFileLines: number; firstLineBytes: number; byteGuidance: boolean }) => { content: TextContent[]; details: ReadToolDetails };\n\tsourceMeta: (source: string) => ReadToolDetails;\n}\n\nexport type ReadUrlBranchResult = { content: TextContent[]; details: ReadToolDetails | undefined };\n\nexport async function readUrlBranch(args: ReadUrlBranchArgs): Promise<ReadUrlBranchResult> {\n\tconst { effectivePath, rawOutput, effectiveRanges, effectiveOffset, effectiveLimit, cwd, ctx, signal, maxChars, maxBytes, oversized, sourceMeta } = args;\n\tconst session = (ctx as { sessionManager?: { getSessionDir?: () => string | undefined; getSessionId?: () => string | undefined } } | undefined)?.sessionManager;\n\tconst sessionDir = session?.getSessionDir?.();\n\tconst scope = session?.getSessionId?.() ?? cwd;\n\tconst artifactsDir = sessionDir ? resolvePath(sessionDir, \"artifacts\") : undefined;\n\tif (!effectiveRanges && !effectiveOffset && effectiveLimit === undefined) {\n\t\tconst result = await executeReadUrl(scope, { path: effectivePath, raw: rawOutput }, artifactsDir, signal);\n\t\tconst artifactId = result.artifactId ?? result.details.meta?.artifactId;\n\t\tconst truncation = result.details.meta?.truncation;\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text: result.content }],\n\t\t\tdetails: {\n\t\t\t\t...(truncation ? { truncation } : {}),\n\t\t\t\tmeta: { ...(result.details.meta ?? {}), source: effectivePath, sourcePath: effectivePath, ...(artifactId ? { artifactId } : {}) },\n\t\t\t},\n\t\t};\n\t}\n\tconst page = await loadPage(effectivePath, 10_000, signal);\n\tconst textContent = rawOutput ? page.content : await decodeReadableUrl(new Response(page.content, { headers: { \"content-type\": page.contentType } }), page.finalUrl || effectivePath);\n\tconst selection = applyReadLineSelection(textContent.split(\"\\n\"), effectiveRanges, effectiveOffset, effectiveLimit, rawOutput), selectedText = selection.lines.join(\"\\n\");\n\tif ((effectiveRanges || effectiveOffset) && selection.lines.length === 0) {\n\t\tconst requested = effectiveRanges?.[0]?.start ?? effectiveOffset ?? 1;\n\t\treturn { content: [{ type: \"text\", text: `Requested line ${requested} is beyond end of resource (${textContent.split(\"\\n\").length} lines total).` }], details: undefined };\n\t}\n\tif (selectedText.length > maxChars || Buffer.byteLength(selectedText, \"utf8\") > maxBytes) {\n\t\treturn oversized({ blocked: true, path: effectivePath, chars: selectedText.length, maxChars, startLine: selection.firstLine, totalFileLines: textContent.split(\"\\n\").length, firstLineBytes: Buffer.byteLength(selection.lines[0] ?? \"\", \"utf8\"), byteGuidance: false });\n\t}\n\treturn { content: [{ type: \"text\", text: rawOutput ? selectedText : `URL: ${effectivePath}\\nStatus: ${page.status}\\nContent-Type: ${page.contentType || \"unknown\"}\\n\\n${selectedText}` }], details: sourceMeta(effectivePath) };\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"read-url.js","sourceRoot":"","sources":["../../../src/core/tools/read-url.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,OAAO,IAAI,WAAW,EAAE,MAAM,WAAW,CAAC;AAGnD,OAAO,EAAE,sBAAsB,EAAE,iBAAiB,EAAE,MAAM,4BAA4B,CAAC;AACvF,OAAO,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAmB1D,MAAM,CAAC,KAAK,UAAU,aAAa,CAAC,IAAuB;IAC1D,MAAM,EAAE,aAAa,EAAE,SAAS,EAAE,eAAe,EAAE,eAAe,EAAE,cAAc,EAAE,GAAG,EAAE,GAAG,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,EAAE,SAAS,EAAE,UAAU,EAAE,GAAG,IAAI,CAAC;IACzJ,MAAM,OAAO,GAAI,GAA8H,EAAE,cAAc,CAAC;IAChK,MAAM,UAAU,GAAG,OAAO,EAAE,aAAa,EAAE,EAAE,CAAC;IAC9C,MAAM,KAAK,GAAG,OAAO,EAAE,YAAY,EAAE,EAAE,IAAI,GAAG,CAAC;IAC/C,MAAM,YAAY,GAAG,UAAU,CAAC,CAAC,CAAC,WAAW,CAAC,UAAU,EAAE,WAAW,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IACnF,IAAI,CAAC,eAAe,IA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,aAAa,IAAI,CAAC,MAAM,mBAAmB,IAAI,CAAC,WAAW,IAAI,SAAS,OAAO,YAAY,EAAE,EAAE,CAAC,EAAE,OAAO,EAAE,UAAU,CAAC,aAAa,CAAC,EAAE,CAAC;AACjO,CAAC","sourcesContent":["/**\n * URL branch of the `read` tool: routes plain URL reads through the\n * cache/artifact/llms.txt fetch pipeline ({@link executeReadUrl}); explicit\n * URL line selectors reuse the same safe rendering path before slicing lines.\n */\nimport { resolve as resolvePath } from \"node:path\";\nimport type { TextContent } from \"@earendil-works/pi-ai\";\nimport type { ReadToolDetails } from \"./read.ts\";\nimport { applyReadLineSelection, decodeReadableUrl } from \"./read-document-extract.ts\";\nimport { executeReadUrl, loadPage } from \"./fetch-url.ts\";\n\nexport interface ReadUrlBranchArgs {\n\teffectivePath: string;\n\trawOutput: boolean;\n\teffectiveRanges: { start: number; end?: number }[] | undefined;\n\teffectiveOffset: number | undefined;\n\teffectiveLimit: number | undefined;\n\tcwd: string;\n\tctx: unknown;\n\tsignal?: AbortSignal;\n\tmaxChars: number;\n\tmaxBytes: number;\n\toversized: (details: { blocked: true; path: string; chars: number; maxChars: number; startLine: number; totalFileLines: number; firstLineBytes: number; byteGuidance: boolean }) => { content: TextContent[]; details: ReadToolDetails };\n\tsourceMeta: (source: string) => ReadToolDetails;\n}\n\nexport type ReadUrlBranchResult = { content: TextContent[]; details: ReadToolDetails | undefined };\n\nexport async function readUrlBranch(args: ReadUrlBranchArgs): Promise<ReadUrlBranchResult> {\n\tconst { effectivePath, rawOutput, effectiveRanges, effectiveOffset, effectiveLimit, cwd, ctx, signal, maxChars, maxBytes, oversized, sourceMeta } = args;\n\tconst session = (ctx as { sessionManager?: { getSessionDir?: () => string | undefined; getSessionId?: () => string | undefined } } | undefined)?.sessionManager;\n\tconst sessionDir = session?.getSessionDir?.();\n\tconst scope = session?.getSessionId?.() ?? cwd;\n\tconst artifactsDir = sessionDir ? resolvePath(sessionDir, \"artifacts\") : undefined;\n\tif (!effectiveRanges && !effectiveOffset && effectiveLimit === undefined) {\n\t\tconst result = await executeReadUrl(scope, { path: effectivePath, raw: rawOutput }, artifactsDir, signal);\n\t\tconst artifactId = result.artifactId ?? result.details.meta?.artifactId;\n\t\tconst truncation = result.details.meta?.truncation;\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text: result.content }],\n\t\t\tdetails: {\n\t\t\t\t...(truncation ? { truncation } : {}),\n\t\t\t\tmeta: { ...(result.details.meta ?? {}), source: effectivePath, sourcePath: effectivePath, ...(artifactId ? { artifactId } : {}) },\n\t\t\t},\n\t\t};\n\t}\n\tconst page = await loadPage(effectivePath, 10_000, signal);\n\tconst textContent = rawOutput ? page.content : await decodeReadableUrl(new Response(page.content, { headers: { \"content-type\": page.contentType } }), page.finalUrl || effectivePath);\n\tconst selection = applyReadLineSelection(textContent.split(\"\\n\"), effectiveRanges, effectiveOffset, effectiveLimit, rawOutput), selectedText = selection.lines.join(\"\\n\");\n\tif ((effectiveRanges || effectiveOffset) && selection.lines.length === 0) {\n\t\tconst requested = effectiveRanges?.[0]?.start ?? effectiveOffset ?? 1;\n\t\treturn { content: [{ type: \"text\", text: `Requested line ${requested} is beyond end of resource (${textContent.split(\"\\n\").length} lines total).` }], details: undefined };\n\t}\n\tif (selectedText.length > maxChars || Buffer.byteLength(selectedText, \"utf8\") > maxBytes) {\n\t\treturn oversized({ blocked: true, path: effectivePath, chars: selectedText.length, maxChars, startLine: selection.firstLine, totalFileLines: textContent.split(\"\\n\").length, firstLineBytes: Buffer.byteLength(selection.lines[0] ?? \"\", \"utf8\"), byteGuidance: false });\n\t}\n\treturn { content: [{ type: \"text\", text: rawOutput ? selectedText : `URL: ${effectivePath}\\nStatus: ${page.status}\\nContent-Type: ${page.contentType || \"unknown\"}\\n\\n${selectedText}` }], details: sourceMeta(effectivePath) };\n}\n"]}
1
+ {"version":3,"file":"read-url.js","sourceRoot":"","sources":["../../../src/core/tools/read-url.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,O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AAC,IAAI,CAAC,CAAC,MAAM,gBAAgB,EAAE,CAAC,EAAE,OAAO,EAAE,SAAS,EAAE,CAAC;IAC5K,CAAC;IACD,IAAI,YAAY,CAAC,MAAM,GAAG,QAAQ,IAAI,MAAM,CAAC,UAAU,CAAC,YAAY,EAAE,MAAM,CAAC,GAAG,QAAQ,EAAE,CAAC;QAC1F,OAAO,SAAS,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,aAAa,EAAE,KAAK,EAAE,YAAY,CAAC,MAAM,EAAE,QAAQ,EAAE,SAAS,EAAE,SAAS,CAAC,SAAS,EAAE,cAAc,EAAE,WAAW,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,MAAM,EAAE,cAAc,EAAE,MAAM,CAAC,UAAU,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,EAAE,MAAM,CAAC,EAAE,YAAY,EAAE,KAAK,EAAE,CAAC,CAAC;IAC1Q,CAAC;IACD,OAAO,EAAE,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,SAAS,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,QAAQ,aAAa,aAAa,IAAI,CAAC,MAAM,mBAAmB,IAAI,CAAC,WAAW,IAAI,SAAS,OAAO,YAAY,EAAE,EAAE,CAAC,EAAE,OAAO,EAAE,UAAU,CAAC,aAAa,CAAC,EAAE,CAAC;AACjO,CAAC","sourcesContent":["/**\n * URL branch of the `read` tool: routes plain URL reads through the\n * cache/artifact/llms.txt fetch pipeline ({@link executeReadUrl}); explicit\n * URL line selectors reuse the same safe rendering path before slicing lines.\n */\nimport { resolve as resolvePath } from \"node:path\";\nimport type { TextContent } from \"@earendil-works/pi-ai/compat\";\nimport type { ReadToolDetails } from \"./read.ts\";\nimport { applyReadLineSelection, decodeReadableUrl } from \"./read-document-extract.ts\";\nimport { executeReadUrl, loadPage } from \"./fetch-url.ts\";\n\nexport interface ReadUrlBranchArgs {\n\teffectivePath: string;\n\trawOutput: boolean;\n\teffectiveRanges: { start: number; end?: number }[] | undefined;\n\teffectiveOffset: number | undefined;\n\teffectiveLimit: number | undefined;\n\tcwd: string;\n\tctx: unknown;\n\tsignal?: AbortSignal;\n\tmaxChars: number;\n\tmaxBytes: number;\n\toversized: (details: { blocked: true; path: string; chars: number; maxChars: number; startLine: number; totalFileLines: number; firstLineBytes: number; byteGuidance: boolean }) => { content: TextContent[]; details: ReadToolDetails };\n\tsourceMeta: (source: string) => ReadToolDetails;\n}\n\nexport type ReadUrlBranchResult = { content: TextContent[]; details: ReadToolDetails | undefined };\n\nexport async function readUrlBranch(args: ReadUrlBranchArgs): Promise<ReadUrlBranchResult> {\n\tconst { effectivePath, rawOutput, effectiveRanges, effectiveOffset, effectiveLimit, cwd, ctx, signal, maxChars, maxBytes, oversized, sourceMeta } = args;\n\tconst session = (ctx as { sessionManager?: { getSessionDir?: () => string | undefined; getSessionId?: () => string | undefined } } | undefined)?.sessionManager;\n\tconst sessionDir = session?.getSessionDir?.();\n\tconst scope = session?.getSessionId?.() ?? cwd;\n\tconst artifactsDir = sessionDir ? resolvePath(sessionDir, \"artifacts\") : undefined;\n\tif (!effectiveRanges && !effectiveOffset && effectiveLimit === undefined) {\n\t\tconst result = await executeReadUrl(scope, { path: effectivePath, raw: rawOutput }, artifactsDir, signal);\n\t\tconst artifactId = result.artifactId ?? result.details.meta?.artifactId;\n\t\tconst truncation = result.details.meta?.truncation;\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text: result.content }],\n\t\t\tdetails: {\n\t\t\t\t...(truncation ? { truncation } : {}),\n\t\t\t\tmeta: { ...(result.details.meta ?? {}), source: effectivePath, sourcePath: effectivePath, ...(artifactId ? { artifactId } : {}) },\n\t\t\t},\n\t\t};\n\t}\n\tconst page = await loadPage(effectivePath, 10_000, signal);\n\tconst textContent = rawOutput ? page.content : await decodeReadableUrl(new Response(page.content, { headers: { \"content-type\": page.contentType } }), page.finalUrl || effectivePath);\n\tconst selection = applyReadLineSelection(textContent.split(\"\\n\"), effectiveRanges, effectiveOffset, effectiveLimit, rawOutput), selectedText = selection.lines.join(\"\\n\");\n\tif ((effectiveRanges || effectiveOffset) && selection.lines.length === 0) {\n\t\tconst requested = effectiveRanges?.[0]?.start ?? effectiveOffset ?? 1;\n\t\treturn { content: [{ type: \"text\", text: `Requested line ${requested} is beyond end of resource (${textContent.split(\"\\n\").length} lines total).` }], details: undefined };\n\t}\n\tif (selectedText.length > maxChars || Buffer.byteLength(selectedText, \"utf8\") > maxBytes) {\n\t\treturn oversized({ blocked: true, path: effectivePath, chars: selectedText.length, maxChars, startLine: selection.firstLine, totalFileLines: textContent.split(\"\\n\").length, firstLineBytes: Buffer.byteLength(selection.lines[0] ?? \"\", \"utf8\"), byteGuidance: false });\n\t}\n\treturn { content: [{ type: \"text\", text: rawOutput ? selectedText : `URL: ${effectivePath}\\nStatus: ${page.status}\\nContent-Type: ${page.contentType || \"unknown\"}\\n\\n${selectedText}` }], details: sourceMeta(effectivePath) };\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"read.d.ts","sourceRoot":"","sources":["../../../src/core/tools/read.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,+BAA+B,CAAC;AAK/D,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAa5C,OAAO,KAAK,EAAE,cAAc,EAA2B,MAAM,wBAAwB,CAAC;AACtF,OAAO,EAA8E,KAAK,qBAAqB,EAAE,MAAM,eAAe,CAAC;AAMvI,OAAO,EAAoD,KAAK,gBAAgB,EAAgB,MAAM,eAAe,CAAC;AACtH,QAAA,MAAM,UAAU;;EAEmB,CAAC;AACpC,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,OAAO,UAAU,CAAC,CAAC;AAEtD,MAAM,WAAW,oBAAoB;IACpC,OAAO,EAAE,IAAI,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;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AC,CA+P/I;AACD,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,eAAe,GAAG,SAAS,CAAC,OAAO,UAAU,CAAC,CAEnG","sourcesContent":["import { basename, dirname, isAbsolute, relative, resolve as resolvePath, sep } from \"node:path\";\nimport type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport type { Api, ImageContent, Model, TextContent } from \"@earendil-works/pi-ai\";\nimport { Text } from \"@earendil-works/pi-tui\";\nimport { constants } from \"fs\";\nimport { access as fsAccess, readFile as fsReadFile, stat as fsStat } from \"fs/promises\";\nimport { type Static, Type } from \"typebox\";\nimport { getReadmePath } from \"../../config.ts\";\nimport { keyHint, keyText } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport { parseConflictBlocks, registerConflictBlocks } from \"./conflict-registry.ts\";\nimport { getLanguageFromPath, highlightCode, type Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport { formatDimensionNote, resizeImage } from \"../../utils/image-resize.ts\";\nimport { detectSupportedImageMimeTypeFromFile } from \"../../utils/mime.ts\";\nimport { formatPathRelativeToCwdOrAbsolute } from \"../../utils/paths.ts\";\nimport { buildDirectoryTree } from \"./directory-tree.ts\";\nimport { applyReadLineSelection, extractDocumentMarkdown, isDocumentPath } from \"./read-document-extract.ts\";\nimport { isReadableUrlPath } from \"./fetch-url.ts\";\nimport { readUrlBranch } from \"./read-url.ts\";\nimport { isNotebookPath, readEditableNotebookText } from \"./notebook.ts\";\nimport type { ToolDefinition, ToolRenderResultOptions } from \"../extensions/types.ts\";\nimport { createHashlineSnapshotStore, formatHashlineContent, recordHashlineSnapshot, type HashlineSnapshotStore } from \"./hashline.ts\";\nimport { resolveReadPathAsync, resolveToCwd } from \"./path-utils.ts\";\nimport { getTextOutput, invalidArgText, replaceTabs, shortenPath, str } from \"./render-utils.ts\";\nimport { formatHashlineSelectedLines, isReadResourceSelector, selectExactReadRanges, selectReadRanges, splitReadLineSelector, type ReadLineSelector } from \"./read-selectors.ts\";\nimport { parseArchiveSelector, readArchiveSelector, readInternalSelector, readSqliteSelector, resolveArchiveSelector, resolveInternalSelector, sqliteSelectorForPath, type InternalResourceContext } from \"./resource-selectors.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\nimport { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, type TruncationResult, truncateHead } from \"./truncate.ts\";\nconst readSchema = Type.Object({\n\tpath: Type.String({ description: \"File, directory, archive member, SQLite selector, internal resource, image, document, or URL to read. Append selectors such as :raw, :conflicts, :N, :A-B, :A+C, or :A-B,C-D to scope output.\" }),\n}, { additionalProperties: false });\nexport type ReadToolInput = Static<typeof readSchema>;\nconst READ_TOOL_MAX_RESULT_CHARS = 50_000;\nexport interface OversizedReadDetails {\n\tblocked: true;\n\tpath: string;\n\tchars: number;\n\tmaxChars: number;\n\tstartLine: number;\n\trequestedLimit?: number;\n\ttotalFileLines: number;\n\tfirstLineBytes: number;\n\tbyteGuidance: boolean;\n}\nexport interface ReadToolDetails {\n\tisDirectory?: boolean;\n\tresolvedPath?: string;\n\ttruncation?: TruncationResult;\n\toversizedRead?: OversizedReadDetails;\n\tmeta?: { source?: string; sourcePath?: string; artifactId?: string; truncation?: TruncationResult; limits?: Record<string, number> };\n}\ninterface CompactReadClassification {\n\tkind: \"docs\" | \"resource\" | \"skill\";\n\tlabel: string;\n}\nconst COMPACT_RESOURCE_FILE_NAMES = new Set([\"AGENTS.md\", \"AGENTS.MD\", \"CLAUDE.md\", \"CLAUDE.MD\"]);\nexport interface ReadOperations {\n\treadFile: (absolutePath: string) => Promise<Buffer>;\n\taccess: (absolutePath: string) => Promise<void>;\n\tdetectImageMimeType?: (absolutePath: string) => Promise<string | null | undefined>;\n}\nconst defaultReadOperations: ReadOperations = {\n\treadFile: (path) => fsReadFile(path),\n\taccess: (path) => fsAccess(path, constants.R_OK),\n\tdetectImageMimeType: detectSupportedImageMimeTypeFromFile,\n};\nexport interface ReadToolOptions {\n\tautoResizeImages?: boolean;\n\toperations?: ReadOperations;\n\thashlineStore?: HashlineSnapshotStore;\n}\ntype ReadRenderArgs = { path?: string };\nfunction formatReadLineRange(_args: ReadRenderArgs | undefined, _theme: Theme): string {\n\treturn \"\";\n}\nfunction formatReadCall(args: ReadRenderArgs | undefined, theme: Theme): string {\n\tconst rawPath = str(args?.path);\n\tconst path = rawPath !== null ? shortenPath(rawPath) : null;\n\tconst invalidArg = invalidArgText(theme);\n\tconst pathDisplay = path === null ? invalidArg : path ? theme.fg(\"accent\", path) : theme.fg(\"toolOutput\", \"...\");\n\treturn `${theme.fg(\"toolTitle\", theme.bold(\"read\"))} ${pathDisplay}${formatReadLineRange(args, theme)}`;\n}\nfunction trimTrailingEmptyLines(lines: string[]): string[] { let end = lines.length; while (end > 0 && lines[end - 1] === \"\") end--; return lines.slice(0, end); }\nfunction getNonVisionImageNote(model: Model<Api> | undefined): string | undefined { return !model || model.input.includes(\"image\") ? undefined : \"[Current model does not support images. The image will be omitted from this request.]\"; }\nfunction toPosixPath(filePath: string): string { return filePath.split(sep).join(\"/\"); }\nfunction formatCount(count: number): string { return count.toLocaleString(\"en-US\"); }\nfunction shellQuote(value: string): string {\n\treturn `'${value.replace(/'/g, `'\\\\''`)}'`;\n}\nfunction buildOversizedReadMessage(details: OversizedReadDetails): string {\n\tconst pathForExample = JSON.stringify(details.path);\n\tconst rangePathForExample = JSON.stringify(`${details.path}:${details.startLine}+200`);\n\tconst shellPathForExample = shellQuote(details.path);\n\tconst requestedLimitLine =\n\t\tdetails.requestedLimit !== undefined ? [`Requested line limit: ${formatCount(details.requestedLimit)}`] : [];\n\tif (details.byteGuidance) {\n\t\treturn [\n\t\t\t`File read blocked: requested selected range is too large (${formatCount(details.chars)} chars; threshold: ${formatCount(details.maxChars)} chars).`,\n\t\t\t`Path: ${details.path}`,\n\t\t\t...requestedLimitLine,\n\t\t\t\"\",\n\t\t\t\"The selected content starts with a single oversized line, so line pagination is not useful. Read byte slices instead. Examples:\",\n\t\t\t`- Inspect the start of line ${details.startLine}: sed -n '${details.startLine}p' ${shellPathForExample} | head -c ${DEFAULT_MAX_BYTES}`,\n\t\t\t`- Inspect a later byte window: sed -n '${details.startLine}p' ${shellPathForExample} | tail -c +${DEFAULT_MAX_BYTES + 1} | head -c ${DEFAULT_MAX_BYTES}`,\n\t\t\t`- Search for relevant text first: search({ \"pattern\": \"functionName\", \"paths\": ${pathForExample} })`,\n\t\t].join(\"\\n\");\n\t}\n\tconst targetedSnippetOffset = Math.max(details.startLine, 120);\n\tconst snippetPathForExample = JSON.stringify(`${details.path}:${targetedSnippetOffset}+80`);\n\treturn [\n\t\t`File read blocked: requested selected range is too large (${formatCount(details.chars)} chars; threshold: ${formatCount(details.maxChars)} chars).`,\n\t\t`Path: ${details.path}`,\n\t\t...requestedLimitLine,\n\t\t\"\",\n\t\t\"Read only the needed context incrementally. Examples:\",\n\t\t`- Search for relevant symbols first: search({ \"pattern\": \"functionName\", \"paths\": ${pathForExample} })`,\n\t\t`- Read a smaller line range: read({ \"path\": ${rangePathForExample} })`,\n\t\t`- Read a targeted snippet around a match: read({ \"path\": ${snippetPathForExample} })`,\n\t].join(\"\\n\");\n}\nfunction readSourceMeta(source: string): ReadToolDetails { return { meta: { source, sourcePath: source } }; }\nfunction oversizedReadResult(details: OversizedReadDetails): { content: TextContent[]; details: ReadToolDetails } { return { content: [{ type: \"text\", text: buildOversizedReadMessage(details) }], details: { oversizedRead: details, meta: { source: details.path, sourcePath: details.path, limits: { maxChars: details.maxChars }, } } }; }\nfunction getPiDocsClassification(absolutePath: string): CompactReadClassification | undefined {\n\tconst packageRoot = dirname(getReadmePath());\n\tconst relativePath = relative(resolvePath(packageRoot), resolvePath(absolutePath));\n\tif (\n\t\trelativePath === \"\" ||\n\t\trelativePath === \"..\" ||\n\t\trelativePath.startsWith(`..${sep}`) ||\n\t\tisAbsolute(relativePath)\n\t) {\n\t\treturn undefined;\n\t}\n\tconst label = toPosixPath(relativePath);\n\tif (label === \"README.md\" || label.startsWith(\"docs/\") || label.startsWith(\"examples/\")) {\n\t\treturn { kind: \"docs\", label };\n\t}\n\treturn undefined;\n}\nfunction getCompactReadClassification(\n\targs: ReadRenderArgs | undefined,\n\tcwd: string,\n): CompactReadClassification | undefined {\n\tconst rawPath = str(args?.path);\n\tif (!rawPath) return undefined;\n\tconst absolutePath = resolveToCwd(rawPath, cwd);\n\tconst fileName = basename(absolutePath);\n\tif (fileName === \"SKILL.md\") {\n\t\treturn { kind: \"skill\", label: basename(dirname(absolutePath)) || fileName };\n\t}\n\tconst docsClassification = getPiDocsClassification(absolutePath);\n\tif (docsClassification) return docsClassification;\n\tif (COMPACT_RESOURCE_FILE_NAMES.has(fileName)) {\n\t\treturn { kind: \"resource\", label: formatPathRelativeToCwdOrAbsolute(absolutePath, cwd) };\n\t}\n\treturn undefined;\n}\nfunction formatCompactReadCall(\n\tclassification: CompactReadClassification,\n\targs: ReadRenderArgs | undefined,\n\ttheme: Theme,\n): string {\n\tconst expandHint = theme.fg(\"dim\", ` (${keyText(\"app.tools.expand\")} Expand)`);\n\tif (classification.kind === \"skill\") {\n\t\treturn (\n\t\t\ttheme.fg(\"customMessageLabel\", `\\x1b[1m[skill]\\x1b[22m `) +\n\t\t\ttheme.fg(\"customMessageText\", classification.label) +\n\t\t\tformatReadLineRange(args, theme) +\n\t\t\texpandHint\n\t\t);\n\t}\n\treturn (\n\t\ttheme.fg(\"toolTitle\", theme.bold(`read ${classification.kind}`)) +\n\t\t\" \" +\n\t\ttheme.fg(\"accent\", classification.label) +\n\t\tformatReadLineRange(args, theme) +\n\t\texpandHint\n\t);\n}\nfunction formatReadResult(\n\targs: ReadRenderArgs | undefined,\n\tresult: { content: (TextContent | ImageContent)[]; details?: ReadToolDetails },\n\toptions: ToolRenderResultOptions,\n\ttheme: Theme,\n\tshowImages: boolean,\n\t_cwd: string,\n\tisError: boolean,\n): string {\n\tconst oversizedRead = result.details?.oversizedRead;\n\tconst oversizedReadBlocked = oversizedRead?.blocked === true;\n\tif (!options.expanded && !isError && !oversizedReadBlocked) {\n\t\treturn \"\";\n\t}\n\tconst rawPath = str(args?.path);\n\tconst output = oversizedRead ? buildOversizedReadMessage(oversizedRead) : getTextOutput(result, showImages);\n\tconst lang = rawPath && !oversizedReadBlocked ? getLanguageFromPath(rawPath) : undefined;\n\tconst renderedLines = lang ? highlightCode(replaceTabs(output), lang) : output.split(\"\\n\");\n\tconst lines = trimTrailingEmptyLines(renderedLines);\n\tconst maxLines = options.expanded ? lines.length : 10;\n\tconst displayLines = lines.slice(0, maxLines);\n\tconst remaining = lines.length - maxLines;\n\tlet text = `\\n${displayLines.map((line) => (lang ? replaceTabs(line) : theme.fg(\"toolOutput\", replaceTabs(line)))).join(\"\\n\")}`;\n\tif (remaining > 0) {\n\t\ttext += `${theme.fg(\"muted\", `\\n... (${remaining} more lines,`)} ${keyHint(\"app.tools.expand\", \"Expand\")}${theme.fg(\"muted\", \")\")}`;\n\t}\n\tconst truncation = result.details?.truncation;\n\tif (truncation?.truncated) {\n\t\tif (truncation.firstLineExceedsLimit) {\n\t\t\ttext += `\\n${theme.fg(\"warning\", `[First line exceeds ${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit]`)}`;\n\t\t} else if (truncation.truncatedBy === \"lines\") {\n\t\t\ttext += `\\n${theme.fg(\"warning\", `[Truncated: showing ${truncation.outputLines} of ${truncation.totalLines} lines (${truncation.maxLines ?? DEFAULT_MAX_LINES} line limit)]`)}`;\n\t\t} else {\n\t\t\ttext += `\\n${theme.fg(\"warning\", `[Truncated: ${truncation.outputLines} lines shown (${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit)]`)}`;\n\t\t}\n\t}\n\treturn text;\n}\nfunction archiveSelectorMemberExists(pathValue: string, cwd: string): boolean { const archive = parseArchiveSelector(pathValue); if (!archive || !archive.memberPath) return false; try { readArchiveSelector(resolveArchiveSelector(archive, cwd)); return true; } catch { return false; } }\nfunction appendReadSelectors(pathValue: string, selector: ReadLineSelector): string {\n\tconst range = selector.ranges?.map((item) => item.end === undefined ? `${item.start}` : `${item.start}-${item.end}`).join(\",\") ?? (selector.offset ? `${selector.offset}` : \"\");\n\treturn `${pathValue}${range ? `:${range}` : \"\"}${selector.conflicts ? \":conflicts\" : \"\"}${selector.raw ? \":raw\" : \"\"}`;\n}\nexport function createReadToolDefinition(cwd: string, options?: ReadToolOptions): ToolDefinition<typeof readSchema, ReadToolDetails | undefined> {\n\tconst autoResizeImages = options?.autoResizeImages ?? true;\n\tconst ops = options?.operations ?? defaultReadOperations;\n\tconst hashlineStore = options?.hashlineStore ?? createHashlineSnapshotStore();\n\treturn {\n\t\tname: \"read\",\n\t\tlabel: \"read\",\n\t\tdescription: \"Read files, directories, archives, SQLite databases, internal resources, images, documents, and URLs through one path string.\",\n\t\tpromptSnippet: \"Read a path selector.\",\n\t\tpromptGuidelines: [\"Use read to inspect file and resource contents; use path selectors for line ranges, raw output, and conflict views.\"],\n\t\tparameters: readSchema,\n\t\tmaxResultSizeChars: Infinity,\n\t\tasync execute(\n\t\t\t_toolCallId,\n\t\t\t{ path }: ReadToolInput,\n\t\t\tsignal?: AbortSignal,\n\t\t\t_onUpdate?,\n\t\t\tctx?,\n\t\t) {\n\t\t\tconst resourceCtx = ctx as InternalResourceContext | undefined;\n\t\t\tconst splitSelector = splitReadLineSelector(path), markerless = path.replace(/:raw(?=(:|$))/g, \"\").replace(/:conflicts(?=(:|$))/g, \"\"), sqliteOriginal = sqliteSelectorForPath(markerless, cwd), sqliteDirect = sqliteSelectorForPath(path, cwd);\n\t\t\tconst selector = archiveSelectorMemberExists(path, cwd) ? { path } : sqliteDirect && (sqliteDirect.table === \"raw\" || sqliteDirect.table === \"conflicts\") ? { path } : sqliteOriginal?.rowId && splitSelector.path !== markerless ? { path: markerless, raw: splitSelector.raw, conflicts: splitSelector.conflicts } : sqliteOriginal && splitSelector.path === markerless && markerless !== path ? { path: markerless, raw: splitSelector.raw, conflicts: splitSelector.conflicts } : splitSelector.path === path && sqliteDirect ? { path } : splitSelector;\n\t\t\tconst effectivePath = selector.path;\n\t\t\tconst effectiveOffset = selector.offset;\n\t\t\tconst effectiveLimit = selector.limit;\n\t\t\tconst effectiveRanges = selector.ranges;\n\t\t\tconst rawOutput = selector.raw;\n\t\t\tconst conflictsOnly = selector.conflicts;\n\t\t\treturn new Promise<{ content: (TextContent | ImageContent)[]; details: ReadToolDetails | undefined }>(\n\t\t\t\t(resolve, reject) => {\n\t\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\t\treject(new Error(\"Operation aborted\"));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tlet aborted = false;\n\t\t\t\t\tconst onAbort = () => {\n\t\t\t\t\t\taborted = true;\n\t\t\t\t\t\treject(new Error(\"Operation aborted\"));\n\t\t\t\t\t};\n\t\t\t\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\t\t\t(async () => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst archive = parseArchiveSelector(effectivePath);\n\t\t\t\t\t\t\tconst sqlite = sqliteSelectorForPath(effectivePath, cwd);\n\t\t\t\t\t\t\tif (isReadableUrlPath(effectivePath)) {\n\t\t\t\t\t\t\t\tresolve(await readUrlBranch({ effectivePath, rawOutput: rawOutput === true, effectiveRanges, effectiveOffset, effectiveLimit, cwd, ctx, signal, maxChars: READ_TOOL_MAX_RESULT_CHARS, maxBytes: DEFAULT_MAX_BYTES, oversized: oversizedReadResult, sourceMeta: readSourceMeta }));\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (sqlite) {\n\t\t\t\t\t\t\t\tconst textContent = readSqliteSelector(sqlite), selection = applyReadLineSelection(textContent.split(\"\\n\"), effectiveRanges, effectiveOffset, effectiveLimit, rawOutput), selectedText = selection.lines.join(\"\\n\");\n\t\t\t\t\t\t\t\tif ((effectiveRanges || effectiveOffset) && selection.lines.length === 0) { const requested = effectiveRanges?.[0]?.start ?? effectiveOffset ?? 1; resolve({ content: [{ type: \"text\", text: `Requested line ${requested} is beyond end of resource (${textContent.split(\"\\n\").length} lines total).` }], details: undefined }); return; }\n\t\t\t\t\t\t\t\tif (selectedText.length > READ_TOOL_MAX_RESULT_CHARS || Buffer.byteLength(selectedText, \"utf8\") > DEFAULT_MAX_BYTES) { resolve(oversizedReadResult({ blocked: true, path: effectivePath, chars: selectedText.length, maxChars: READ_TOOL_MAX_RESULT_CHARS, startLine: selection.firstLine, totalFileLines: textContent.split(\"\\n\").length, firstLineBytes: Buffer.byteLength(selection.lines[0] ?? \"\", \"utf8\"), byteGuidance: false })); return; }\n\t\t\t\t\t\t\tresolve({ content: [{ type: \"text\", text: selectedText }], details: readSourceMeta(effectivePath) }); return;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (archive) {\n\t\t\t\t\t\t\t\tconst resolvedArchive = resolveArchiveSelector(archive, cwd);\n\t\t\t\t\t\t\t\tconst textContent = readArchiveSelector(resolvedArchive);\n\t\t\t\t\t\t\t\tlet allLines = textContent.split(\"\\n\");\n\t\t\t\t\t\t\t\tif (conflictsOnly) {\n\t\t\t\t\t\t\t\t\tlet inConflict = false;\n\t\t\t\t\t\t\t\t\tconst conflictLines = allLines.filter((line) => { if (line.startsWith(\"<<<<<<<\")) inConflict = true; const keep = inConflict; if (line.startsWith(\">>>>>>>\")) inConflict = false; return keep; });\n\t\t\t\t\t\t\t\t\tif (conflictLines.length === 0) { resolve({ content: [{ type: \"text\", text: \"No conflict markers found\" }], details: undefined }); return; }\n\t\t\t\t\t\t\t\t\tallLines = conflictLines;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tconst rangeSelection = (rawOutput ? selectExactReadRanges : selectReadRanges)(allLines, effectiveRanges);\n\t\t\t\t\t\t\t\tconst startLine = rangeSelection ? rangeSelection.firstLine - 1 : effectiveOffset ? Math.max(0, effectiveOffset - 1) : 0;\n\t\t\t\t\t\t\t\tif (startLine >= allLines.length || (effectiveRanges && rangeSelection?.selectedLines.length === 0)) {\n\t\t\t\t\t\t\t\t\tresolve({ content: [{ type: \"text\", text: `Requested line ${startLine + 1} is beyond end of resource (${allLines.length} lines total).` }], details: undefined });\n\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tconst endLine = effectiveLimit !== undefined ? Math.min(startLine + effectiveLimit, allLines.length) : allLines.length;\n\t\t\t\t\t\t\t\tconst selectedLines = rangeSelection?.selectedLines ?? allLines.slice(startLine, endLine);\n\t\t\t\t\t\t\t\tconst selectedText = selectedLines.join(\"\\n\");\n\t\t\t\t\t\t\t\tif (selectedText.length > READ_TOOL_MAX_RESULT_CHARS || Buffer.byteLength(selectedText, \"utf8\") > DEFAULT_MAX_BYTES) { resolve(oversizedReadResult({ blocked: true, path: `${resolvedArchive.archivePath}:${resolvedArchive.memberPath}`, chars: selectedText.length, maxChars: READ_TOOL_MAX_RESULT_CHARS, startLine: startLine + 1, totalFileLines: allLines.length, firstLineBytes: Buffer.byteLength(selectedLines[0] ?? \"\", \"utf8\"), byteGuidance: false })); return; }\n\t\t\t\t\t\t\tresolve({ content: [{ type: \"text\", text: selectedText }], details: readSourceMeta(`${resolvedArchive.archivePath}:${resolvedArchive.memberPath}`) });\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (/^(?:skill|agent|artifact|history|issue|local|memory|pr|conflict|omp|rule|mcp|vault):\\/\\//.test(effectivePath)) {\n\t\t\t\t\t\t\t\tconst sourcePath = effectivePath.startsWith(\"local://\") ? resolveInternalSelector(effectivePath, cwd) : undefined;\n\t\t\t\t\t\t\t\tif (sourcePath) { resolve(await createReadToolDefinition(cwd, options).execute(_toolCallId, { path: appendReadSelectors(sourcePath, selector) }, signal, _onUpdate, ctx as never)); return; }\n\t\t\t\t\t\t\t\tconst allLines = (await readInternalSelector(effectivePath, cwd, resourceCtx)).split(\"\\n\");\n\t\t\t\t\t\t\t\tconst rangeSelection = (rawOutput ? selectExactReadRanges : selectReadRanges)(allLines, effectiveRanges);\n\t\t\t\t\t\t\t\tconst startLine = rangeSelection ? rangeSelection.firstLine - 1 : effectiveOffset ? Math.max(0, effectiveOffset - 1) : 0;\n\t\t\t\t\t\t\t\tif (startLine >= allLines.length || (effectiveRanges && rangeSelection?.selectedLines.length === 0)) {\n\t\t\t\t\t\t\t\t\tresolve({ content: [{ type: \"text\", text: `Requested line ${startLine + 1} is beyond end of resource (${allLines.length} lines total).` }], details: undefined });\n\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tconst endLine = effectiveLimit !== undefined ? Math.min(startLine + effectiveLimit, allLines.length) : allLines.length;\n\t\t\t\t\t\t\t\tconst selectedLines = rangeSelection?.selectedLines ?? allLines.slice(startLine, endLine);\n\t\t\t\t\t\t\t\tconst selectedText = selectedLines.join(\"\\n\");\n\t\t\t\t\t\t\t\tif (selectedText.length > READ_TOOL_MAX_RESULT_CHARS || Buffer.byteLength(selectedText, \"utf8\") > DEFAULT_MAX_BYTES) { resolve(oversizedReadResult({ blocked: true, path: effectivePath, chars: selectedText.length, maxChars: READ_TOOL_MAX_RESULT_CHARS, startLine: startLine + 1, totalFileLines: allLines.length, firstLineBytes: Buffer.byteLength(selectedLines[0] ?? \"\", \"utf8\"), byteGuidance: false })); return; }\n\t\t\t\t\t\t\tresolve({ content: [{ type: \"text\", text: selectedText }], details: readSourceMeta(effectivePath) });\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (isReadResourceSelector(effectivePath)) throw new Error(`Read resource selectors are not supported by this filesystem backend: ${path}`);\n\t\t\t\t\t\t\tconst absolutePath = await resolveReadPathAsync(effectivePath, cwd);\n\t\t\t\t\t\t\tif (aborted) return;\n\t\t\t\t\t\t\tlet content: (TextContent | ImageContent)[];\n\t\t\t\t\t\t\tlet details: ReadToolDetails | undefined;\n\t\t\t\t\t\t\tawait ops.access(absolutePath);\n\t\t\t\t\t\t\tif (aborted) return;\n\t\t\t\t\t\t\tif (isDocumentPath(absolutePath) && !rawOutput && !isNotebookPath(absolutePath)) {\n\t\t\t\t\t\t\t\tconst buffer = await ops.readFile(absolutePath);\n\t\t\t\t\t\t\t\tconst textContent = await extractDocumentMarkdown(buffer, absolutePath);\n\t\t\t\t\t\t\t\tconst selection = applyReadLineSelection(textContent.split(\"\\n\"), effectiveRanges, effectiveOffset, effectiveLimit, rawOutput);\n\t\t\t\t\t\t\t\tif (selection.lines.length === 0) { resolve({ content: [{ type: \"text\", text: `Requested line ${selection.firstLine} is beyond end of document (${textContent.split(\"\\n\").length} lines total).` }], details: undefined }); return; }\n\t\t\t\t\t\t\t\tconst selectedText = selection.lines.join(\"\\n\");\n\t\t\t\t\t\t\tif (selectedText.length > READ_TOOL_MAX_RESULT_CHARS || Buffer.byteLength(selectedText, \"utf8\") > DEFAULT_MAX_BYTES) { resolve(oversizedReadResult({ blocked: true, path: absolutePath, chars: selectedText.length, maxChars: READ_TOOL_MAX_RESULT_CHARS, startLine: selection.firstLine, totalFileLines: textContent.split(\"\\n\").length, firstLineBytes: Buffer.byteLength(selection.lines[0] ?? \"\", \"utf8\"), byteGuidance: false })); return; }\n\t\t\t\t\t\t\tcontent = [{ type: \"text\", text: selectedText }]; resolve({ content, details: readSourceMeta(absolutePath) }); return;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (!options?.operations && (await fsStat(absolutePath)).isDirectory()) {\n\t\t\t\t\t\t\t\tconst tree = await buildDirectoryTree(absolutePath, { maxDepth: 2, perDirLimit: 12, rootLimit: null });\n\t\t\t\t\t\t\t\tconst allLines = tree.rendered.split(\"\\n\"), rangeSelection = (rawOutput ? selectExactReadRanges : selectReadRanges)(allLines, effectiveRanges), startLine = rangeSelection ? rangeSelection.firstLine - 1 : effectiveOffset ? Math.max(0, effectiveOffset - 1) : 0;\n\t\t\t\t\t\t\t\tif (startLine >= allLines.length || (effectiveRanges && rangeSelection?.selectedLines.length === 0)) { resolve({ content: [{ type: \"text\", text: `Requested line ${startLine + 1} is beyond end of directory (${allLines.length} lines total).` }], details: undefined }); return; }\n\t\t\t\t\t\t\t\tconst endLine = effectiveLimit !== undefined ? Math.min(startLine + effectiveLimit, allLines.length) : allLines.length, selectedLines = rangeSelection?.selectedLines ?? allLines.slice(startLine, endLine);\n\t\t\t\t\t\t\t\tcontent = [{ type: \"text\", text: selectedLines.join(\"\\n\") }];\n\t\t\t\t\t\t\t\tconst meta = { ...readSourceMeta(absolutePath).meta, ...(tree.truncated ? { limits: { perDirLimit: 12, totalLines: tree.totalLines } } : {}) };\n\t\t\t\t\t\t\t\tresolve({ content, details: { isDirectory: true, resolvedPath: absolutePath, meta } });\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst mimeType = ops.detectImageMimeType ? await ops.detectImageMimeType(absolutePath) : undefined;\n\t\t\t\t\t\t\tconst nonVisionImageNote = getNonVisionImageNote(ctx?.model);\n\t\t\t\t\t\t\tif (mimeType) {\n\t\t\t\t\t\t\t\tconst buffer = await ops.readFile(absolutePath);\n\t\t\t\t\t\t\t\tif (autoResizeImages) {\n\t\t\t\t\t\t\t\t\tconst resized = await resizeImage(buffer, mimeType);\n\t\t\t\t\t\t\t\t\tif (!resized) {\n\t\t\t\t\t\t\t\t\t\tlet textNote = `Read image file [${mimeType}]\\n[Image omitted: could not be resized below the inline image size limit.]`;\n\t\t\t\t\t\t\t\t\t\tif (nonVisionImageNote) textNote += `\\n${nonVisionImageNote}`;\n\t\t\t\t\t\t\t\t\t\tcontent = [{ type: \"text\", text: textNote }];\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\tconst dimensionNote = formatDimensionNote(resized);\n\t\t\t\t\t\t\t\t\t\tlet textNote = `Read image file [${resized.mimeType}]`;\n\t\t\t\t\t\t\t\t\t\tif (dimensionNote) textNote += `\\n${dimensionNote}`;\n\t\t\t\t\t\t\t\t\t\tif (nonVisionImageNote) textNote += `\\n${nonVisionImageNote}`;\n\t\t\t\t\t\t\t\t\t\tcontent = [\n\t\t\t\t\t\t\t\t\t\t\t{ type: \"text\", text: textNote },\n\t\t\t\t\t\t\t\t\t\t\t{ type: \"image\", data: resized.data, mimeType: resized.mimeType },\n\t\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tlet textNote = `Read image file [${mimeType}]`;\n\t\t\t\t\t\t\t\t\tif (nonVisionImageNote) textNote += `\\n${nonVisionImageNote}`;\n\t\t\t\t\t\t\t\t\tcontent = [\n\t\t\t\t\t\t\t\t\t\t{ type: \"text\", text: textNote },\n\t\t\t\t\t\t\t\t\t\t{ type: \"image\", data: buffer.toString(\"base64\"), mimeType },\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tconst buffer = await ops.readFile(absolutePath);\n\t\t\t\t\t\t\t\tconst textContent = (isNotebookPath(absolutePath) && !rawOutput) ? readEditableNotebookText(absolutePath, effectivePath) : buffer.toString(\"utf-8\");\n\t\t\t\t\t\t\t\tlet allLines = textContent.split(\"\\n\");\n\t\t\t\t\t\t\t\tlet conflictLineNumbers: number[] | undefined;\n\t\t\t\t\t\t\t\tif (conflictsOnly) {\n\t\t\t\t\t\t\t\t\tregisterConflictBlocks(cwd, parseConflictBlocks(absolutePath, textContent));\n\t\t\t\t\t\t\t\t\tconst conflictLines: string[] = [];\n\t\t\t\t\t\t\t\t\tconflictLineNumbers = [];\n\t\t\t\t\t\t\t\t\tlet inConflict = false;\n\t\t\t\t\t\t\t\t\tallLines.forEach((line, index) => {\n\t\t\t\t\t\t\t\t\t\tif (line.startsWith(\"<<<<<<<\")) inConflict = true;\n\t\t\t\t\t\t\t\t\t\tif (inConflict) { conflictLines.push(line); conflictLineNumbers!.push(index + 1); }\n\t\t\t\t\t\t\t\t\t\tif (line.startsWith(\">>>>>>>\")) inConflict = false;\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\tif (conflictLines.length > 0) allLines = conflictLines;\n\t\t\t\t\t\t\t\t\telse { signal?.removeEventListener(\"abort\", onAbort); resolve({ content: [{ type: \"text\", text: \"No conflict markers found\" }], details: undefined }); return; }\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tconst totalFileLines = allLines.length;\n\t\t\t\t\t\t\t\tconst rangeSelection = (rawOutput ? selectExactReadRanges : selectReadRanges)(allLines, effectiveRanges);\n\t\t\t\t\t\t\t\tconst startLine = rangeSelection ? rangeSelection.firstLine - 1 : effectiveOffset ? Math.max(0, effectiveOffset - 1) : 0;\n\t\t\t\t\t\t\t\tconst startLineDisplay = startLine + 1;\n\t\t\t\t\t\t\t\tif (startLine >= allLines.length || (effectiveRanges && rangeSelection?.selectedLines.length === 0)) {\n\t\t\t\t\t\t\t\t\tconst requested = effectiveRanges?.[0]?.start ?? startLineDisplay;\n\t\t\t\t\t\t\t\t\tresolve({ content: [{ type: \"text\", text: `Requested line ${requested} is beyond end of file (${allLines.length} lines total). Use ${effectivePath}:${Math.max(1, allLines.length)} to read the final line.` }], details: undefined });\n\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tlet selectedContent: string;\n\t\t\t\t\t\t\t\tlet selectedLines: string[];\n\t\t\t\t\t\t\t\tlet userLimitedLines: number | undefined;\n\t\t\t\t\t\t\t\tif (rangeSelection) {\n\t\t\t\t\t\t\t\t\tselectedLines = rangeSelection.selectedLines;\n\t\t\t\t\t\t\t\t\tselectedContent = rangeSelection.selectedContent;\n\t\t\t\t\t\t\t\t\tuserLimitedLines = rangeSelection.userLimitedLines;\n\t\t\t\t\t\t\t\t} else if (effectiveLimit !== undefined) {\n\t\t\t\t\t\t\t\t\tconst endLine = Math.min(startLine + effectiveLimit, allLines.length);\n\t\t\t\t\t\t\t\t\tselectedLines = allLines.slice(startLine, endLine);\n\t\t\t\t\t\t\t\t\tselectedContent = selectedLines.join(\"\\n\");\n\t\t\t\t\t\t\t\t\tuserLimitedLines = endLine - startLine;\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tselectedLines = allLines.slice(startLine);\n\t\t\t\t\t\t\t\t\tselectedContent = selectedLines.join(\"\\n\");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (selectedContent.length > READ_TOOL_MAX_RESULT_CHARS) {\n\t\t\t\t\t\t\t\t\tconst firstSelectedLine = allLines[startLine] ?? \"\";\n\t\t\t\t\t\t\t\t\tconst firstLineBytes = Buffer.byteLength(firstSelectedLine, \"utf-8\");\n\t\t\t\t\t\t\t\t\tconst selectedLineCount = trimTrailingEmptyLines(selectedLines).length;\n\t\t\t\t\t\t\t\t\tconst byteGuidance = selectedLineCount <= 1 || firstLineBytes > DEFAULT_MAX_BYTES;\n\t\t\t\t\t\t\t\t\tconst oversizedRead: OversizedReadDetails = { blocked: true, path: absolutePath, chars: selectedContent.length, maxChars: READ_TOOL_MAX_RESULT_CHARS, startLine: startLineDisplay, ...(effectiveLimit !== undefined ? { requestedLimit: effectiveLimit } : {}), totalFileLines, firstLineBytes, byteGuidance };\n\t\t\t\t\t\t\t\tdetails = { oversizedRead, meta: readSourceMeta(absolutePath).meta };\n\t\t\t\t\t\t\t\t\tcontent = [{ type: \"text\", text: buildOversizedReadMessage(oversizedRead) }];\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tconst truncation = truncateHead(selectedContent);\n\t\t\t\t\t\t\t\t\tlet outputText = truncation.content;\n\t\t\t\t\t\t\t\t\tif (truncation.firstLineExceedsLimit) {\n\t\t\t\t\t\t\t\t\t\tconst firstLineSize = formatSize(Buffer.byteLength(allLines[startLine], \"utf-8\"));\n\t\t\t\t\t\t\t\t\t\toutputText = `[Line ${startLineDisplay} is ${firstLineSize}, exceeds ${formatSize(DEFAULT_MAX_BYTES)} limit. Use bash: sed -n '${startLineDisplay}p' ${effectivePath} | head -c ${DEFAULT_MAX_BYTES}]`;\n\t\t\t\t\t\tdetails = { truncation, meta: { source: absolutePath, sourcePath: absolutePath, truncation } };\n\t\t\t\t\t\t\t\t\t} else if (truncation.truncated) {\n\t\t\t\t\t\t\t\t\t\tconst endLineDisplay = startLineDisplay + truncation.outputLines - 1;\n\t\t\t\t\t\t\t\t\t\tconst nextOffset = endLineDisplay + 1;\n\t\t\t\t\t\t\t\t\t\toutputText += truncation.truncatedBy === \"lines\" ? `\\n\\n[Showing lines ${startLineDisplay}-${endLineDisplay} of ${totalFileLines}. Continue with path selector :${nextOffset}.]` : `\\n\\n[Showing lines ${startLineDisplay}-${endLineDisplay} of ${totalFileLines} (${formatSize(DEFAULT_MAX_BYTES)} limit). Continue with path selector :${nextOffset}.]`;\n\t\t\t\t\t\tdetails = { truncation, meta: { source: absolutePath, sourcePath: absolutePath, truncation } };\n\t\t\t\t\t\t\t\t\t} else if (!rawOutput && userLimitedLines !== undefined && startLine + userLimitedLines < allLines.length) {\n\t\t\t\t\t\t\t\t\t\tconst remaining = allLines.length - (startLine + userLimitedLines);\n\t\t\t\t\t\t\t\t\t\tconst nextOffset = startLine + userLimitedLines + 1;\n\t\t\t\t\t\t\t\t\t\toutputText = `${truncation.content}\\n\\n[${remaining} more lines in file. Continue with path selector :${nextOffset}.]`;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tif (truncation.firstLineExceedsLimit) content = [{ type: \"text\", text: outputText }];\n\t\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\t\tconst snapshot = recordHashlineSnapshot(absolutePath, cwd, textContent, hashlineStore);\n\t\t\t\t\t\t\t\t\t\tconst visibleContent = truncation.truncated ? truncation.content : selectedContent;\n\t\t\t\t\t\t\t\t\t\tconst header = `[${snapshot.displayPath}#${snapshot.tag}]`;\n\t\t\t\t\t\t\t\t\t\tconst selectedConflictLineNumbers = conflictLineNumbers && rangeSelection?.lineNumbers ? rangeSelection.lineNumbers.map((line) => conflictLineNumbers![line - 1]).filter((line): line is number => typeof line === \"number\") : conflictLineNumbers ? conflictLineNumbers.slice(startLine, startLine + selectedLines.length) : undefined;\n\t\t\t\t\t\t\t\t\t\tlet hashlineOutput = rawOutput ? visibleContent : selectedConflictLineNumbers && visibleContent === selectedContent ? formatHashlineSelectedLines(header, selectedLines, selectedConflictLineNumbers) : rangeSelection && visibleContent === selectedContent ? formatHashlineSelectedLines(header, selectedLines, rangeSelection.lineNumbers) : formatHashlineContent(snapshot, visibleContent, startLineDisplay);\n\t\t\t\t\t\t\t\t\t\tif (outputText.startsWith(truncation.content) && outputText.length > truncation.content.length) hashlineOutput += outputText.slice(truncation.content.length);\n\t\t\t\t\t\t\t\t\t\tcontent = [{ type: \"text\", text: hashlineOutput }];\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (aborted) return;\n\t\t\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\t\tresolve({ content, details: details ?? readSourceMeta(absolutePath) });\n\t\t\t\t\t\t} catch (error: unknown) {\n\t\t\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\t\t\tif (!aborted) reject(error);\n\t\t\t\t\t\t}\n\t\t\t\t\t})();\n\t\t\t\t},\n\t\t\t);\n\t\t},\n\t\trenderCall(args, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\tconst classification = !context.expanded ? getCompactReadClassification(args, context.cwd) : undefined;\n\t\t\ttext.setText(\n\t\t\t\tclassification ? formatCompactReadCall(classification, args, theme) : formatReadCall(args, theme),\n\t\t\t);\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(\n\t\t\t\tformatReadResult(context.args, result, options, theme, context.showImages, context.cwd, context.isError),\n\t\t\t);\n\t\t\treturn text;\n\t\t},\n\t};\n}\nexport function createReadTool(cwd: string, options?: ReadToolOptions): AgentTool<typeof readSchema> {\n\treturn wrapToolDefinition(createReadToolDefinition(cwd, options));\n}\n"]}
1
+ {"version":3,"file":"read.d.ts","sourceRoot":"","sources":["../../../src/core/tools/read.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,+BAA+B,CAAC;AAK/D,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAa5C,OAAO,KAAK,EAAE,cAAc,EAA2B,MAAM,wBAAwB,CAAC;AACtF,OAAO,EAA8E,KAAK,qBAAqB,EAAE,MAAM,eAAe,CAAC;AAMvI,OAAO,EAAoD,KAAK,gBAAgB,EAAgB,MAAM,eAAe,CAAC;AACtH,QAAA,MAAM,UAAU;;EAEmB,CAAC;AACpC,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,OAAO,UAAU,CAAC,CAAC;AAEtD,MAAM,WAAW,oBAAoB;IACpC,OAAO,EAAE,IAAI,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;IAClB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,cAAc,EAAE,MAAM,CAAC;IACvB,cAAc,EAAE,MAAM,CAAC;IACvB,YAAY,EAAE,OAAO,CAAC;CACtB;AACD,MAAM,WAAW,eAAe;IAC/B,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,UAAU,CAAC,EAAE,gBAAgB,CAAC;IAC9B,aAAa,CAAC,EAAE,oBAAoB,CAAC;IACrC,IAAI,CAAC,EAAE;QAAE,MAAM,CAAC,EAAE,MAAM,CAAC;QAAC,UAAU,CAAC,EAAE,MAAM,CAAC;QAAC,UAAU,CAAC,EAAE,MAAM,CAAC;QAAC,UAAU,CAAC,EAAE,gBAAgB,CAAC;QAAC,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;KAAE,CAAC;CACrI;AAMD,MAAM,WAAW,cAAc;IAC9B,QAAQ,EAAE,CAAC,YAAY,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,CAAC,CAAC;IACpD,MAAM,EAAE,CAAC,YAAY,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAChD,mBAAmB,CAAC,EAAE,CAAC,YAAY,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC,CAAC;CACnF;AAMD,MAAM,WAAW,eAAe;IAC/B,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B,UAAU,CAAC,EAAE,cAAc,CAAC;IAC5B,aAAa,CAAC,EAAE,qBAAqB,CAAC;CACtC;AAwJD,wBAAgB,wBAAwB,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,eAAe,GAAG,cAAc,CAAC,OAAO,UAAU,EAAE,eAAe,GAAG,SAAS,CAAC,CA+P/I;AACD,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,eAAe,GAAG,SAAS,CAAC,OAAO,UAAU,CAAC,CAEnG","sourcesContent":["import { basename, dirname, isAbsolute, relative, resolve as resolvePath, sep } from \"node:path\";\nimport type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport type { Api, ImageContent, Model, TextContent } from \"@earendil-works/pi-ai/compat\";\nimport { Text } from \"@earendil-works/pi-tui\";\nimport { constants } from \"fs\";\nimport { access as fsAccess, readFile as fsReadFile, stat as fsStat } from \"fs/promises\";\nimport { type Static, Type } from \"typebox\";\nimport { getReadmePath } from \"../../config.ts\";\nimport { keyHint, keyText } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport { parseConflictBlocks, registerConflictBlocks } from \"./conflict-registry.ts\";\nimport { getLanguageFromPath, highlightCode, type Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport { formatDimensionNote, resizeImage } from \"../../utils/image-resize.ts\";\nimport { detectSupportedImageMimeTypeFromFile } from \"../../utils/mime.ts\";\nimport { formatPathRelativeToCwdOrAbsolute } from \"../../utils/paths.ts\";\nimport { buildDirectoryTree } from \"./directory-tree.ts\";\nimport { applyReadLineSelection, extractDocumentMarkdown, isDocumentPath } from \"./read-document-extract.ts\";\nimport { isReadableUrlPath } from \"./fetch-url.ts\";\nimport { readUrlBranch } from \"./read-url.ts\";\nimport { isNotebookPath, readEditableNotebookText } from \"./notebook.ts\";\nimport type { ToolDefinition, ToolRenderResultOptions } from \"../extensions/types.ts\";\nimport { createHashlineSnapshotStore, formatHashlineContent, recordHashlineSnapshot, type HashlineSnapshotStore } from \"./hashline.ts\";\nimport { resolveReadPathAsync, resolveToCwd } from \"./path-utils.ts\";\nimport { getTextOutput, invalidArgText, replaceTabs, shortenPath, str } from \"./render-utils.ts\";\nimport { formatHashlineSelectedLines, isReadResourceSelector, selectExactReadRanges, selectReadRanges, splitReadLineSelector, type ReadLineSelector } from \"./read-selectors.ts\";\nimport { parseArchiveSelector, readArchiveSelector, readInternalSelector, readSqliteSelector, resolveArchiveSelector, resolveInternalSelector, sqliteSelectorForPath, type InternalResourceContext } from \"./resource-selectors.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\nimport { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, type TruncationResult, truncateHead } from \"./truncate.ts\";\nconst readSchema = Type.Object({\n\tpath: Type.String({ description: \"File, directory, archive member, SQLite selector, internal resource, image, document, or URL to read. Append selectors such as :raw, :conflicts, :N, :A-B, :A+C, or :A-B,C-D to scope output.\" }),\n}, { additionalProperties: false });\nexport type ReadToolInput = Static<typeof readSchema>;\nconst READ_TOOL_MAX_RESULT_CHARS = 50_000;\nexport interface OversizedReadDetails {\n\tblocked: true;\n\tpath: string;\n\tchars: number;\n\tmaxChars: number;\n\tstartLine: number;\n\trequestedLimit?: number;\n\ttotalFileLines: number;\n\tfirstLineBytes: number;\n\tbyteGuidance: boolean;\n}\nexport interface ReadToolDetails {\n\tisDirectory?: boolean;\n\tresolvedPath?: string;\n\ttruncation?: TruncationResult;\n\toversizedRead?: OversizedReadDetails;\n\tmeta?: { source?: string; sourcePath?: string; artifactId?: string; truncation?: TruncationResult; limits?: Record<string, number> };\n}\ninterface CompactReadClassification {\n\tkind: \"docs\" | \"resource\" | \"skill\";\n\tlabel: string;\n}\nconst COMPACT_RESOURCE_FILE_NAMES = new Set([\"AGENTS.md\", \"AGENTS.MD\", \"CLAUDE.md\", \"CLAUDE.MD\"]);\nexport interface ReadOperations {\n\treadFile: (absolutePath: string) => Promise<Buffer>;\n\taccess: (absolutePath: string) => Promise<void>;\n\tdetectImageMimeType?: (absolutePath: string) => Promise<string | null | undefined>;\n}\nconst defaultReadOperations: ReadOperations = {\n\treadFile: (path) => fsReadFile(path),\n\taccess: (path) => fsAccess(path, constants.R_OK),\n\tdetectImageMimeType: detectSupportedImageMimeTypeFromFile,\n};\nexport interface ReadToolOptions {\n\tautoResizeImages?: boolean;\n\toperations?: ReadOperations;\n\thashlineStore?: HashlineSnapshotStore;\n}\ntype ReadRenderArgs = { path?: string };\nfunction formatReadLineRange(_args: ReadRenderArgs | undefined, _theme: Theme): string {\n\treturn \"\";\n}\nfunction formatReadCall(args: ReadRenderArgs | undefined, theme: Theme): string {\n\tconst rawPath = str(args?.path);\n\tconst path = rawPath !== null ? shortenPath(rawPath) : null;\n\tconst invalidArg = invalidArgText(theme);\n\tconst pathDisplay = path === null ? invalidArg : path ? theme.fg(\"accent\", path) : theme.fg(\"toolOutput\", \"...\");\n\treturn `${theme.fg(\"toolTitle\", theme.bold(\"read\"))} ${pathDisplay}${formatReadLineRange(args, theme)}`;\n}\nfunction trimTrailingEmptyLines(lines: string[]): string[] { let end = lines.length; while (end > 0 && lines[end - 1] === \"\") end--; return lines.slice(0, end); }\nfunction getNonVisionImageNote(model: Model<Api> | undefined): string | undefined { return !model || model.input.includes(\"image\") ? undefined : \"[Current model does not support images. The image will be omitted from this request.]\"; }\nfunction toPosixPath(filePath: string): string { return filePath.split(sep).join(\"/\"); }\nfunction formatCount(count: number): string { return count.toLocaleString(\"en-US\"); }\nfunction shellQuote(value: string): string {\n\treturn `'${value.replace(/'/g, `'\\\\''`)}'`;\n}\nfunction buildOversizedReadMessage(details: OversizedReadDetails): string {\n\tconst pathForExample = JSON.stringify(details.path);\n\tconst rangePathForExample = JSON.stringify(`${details.path}:${details.startLine}+200`);\n\tconst shellPathForExample = shellQuote(details.path);\n\tconst requestedLimitLine =\n\t\tdetails.requestedLimit !== undefined ? [`Requested line limit: ${formatCount(details.requestedLimit)}`] : [];\n\tif (details.byteGuidance) {\n\t\treturn [\n\t\t\t`File read blocked: requested selected range is too large (${formatCount(details.chars)} chars; threshold: ${formatCount(details.maxChars)} chars).`,\n\t\t\t`Path: ${details.path}`,\n\t\t\t...requestedLimitLine,\n\t\t\t\"\",\n\t\t\t\"The selected content starts with a single oversized line, so line pagination is not useful. Read byte slices instead. Examples:\",\n\t\t\t`- Inspect the start of line ${details.startLine}: sed -n '${details.startLine}p' ${shellPathForExample} | head -c ${DEFAULT_MAX_BYTES}`,\n\t\t\t`- Inspect a later byte window: sed -n '${details.startLine}p' ${shellPathForExample} | tail -c +${DEFAULT_MAX_BYTES + 1} | head -c ${DEFAULT_MAX_BYTES}`,\n\t\t\t`- Search for relevant text first: search({ \"pattern\": \"functionName\", \"paths\": ${pathForExample} })`,\n\t\t].join(\"\\n\");\n\t}\n\tconst targetedSnippetOffset = Math.max(details.startLine, 120);\n\tconst snippetPathForExample = JSON.stringify(`${details.path}:${targetedSnippetOffset}+80`);\n\treturn [\n\t\t`File read blocked: requested selected range is too large (${formatCount(details.chars)} chars; threshold: ${formatCount(details.maxChars)} chars).`,\n\t\t`Path: ${details.path}`,\n\t\t...requestedLimitLine,\n\t\t\"\",\n\t\t\"Read only the needed context incrementally. Examples:\",\n\t\t`- Search for relevant symbols first: search({ \"pattern\": \"functionName\", \"paths\": ${pathForExample} })`,\n\t\t`- Read a smaller line range: read({ \"path\": ${rangePathForExample} })`,\n\t\t`- Read a targeted snippet around a match: read({ \"path\": ${snippetPathForExample} })`,\n\t].join(\"\\n\");\n}\nfunction readSourceMeta(source: string): ReadToolDetails { return { meta: { source, sourcePath: source } }; }\nfunction oversizedReadResult(details: OversizedReadDetails): { content: TextContent[]; details: ReadToolDetails } { return { content: [{ type: \"text\", text: buildOversizedReadMessage(details) }], details: { oversizedRead: details, meta: { source: details.path, sourcePath: details.path, limits: { maxChars: details.maxChars }, } } }; }\nfunction getPiDocsClassification(absolutePath: string): CompactReadClassification | undefined {\n\tconst packageRoot = dirname(getReadmePath());\n\tconst relativePath = relative(resolvePath(packageRoot), resolvePath(absolutePath));\n\tif (\n\t\trelativePath === \"\" ||\n\t\trelativePath === \"..\" ||\n\t\trelativePath.startsWith(`..${sep}`) ||\n\t\tisAbsolute(relativePath)\n\t) {\n\t\treturn undefined;\n\t}\n\tconst label = toPosixPath(relativePath);\n\tif (label === \"README.md\" || label.startsWith(\"docs/\") || label.startsWith(\"examples/\")) {\n\t\treturn { kind: \"docs\", label };\n\t}\n\treturn undefined;\n}\nfunction getCompactReadClassification(\n\targs: ReadRenderArgs | undefined,\n\tcwd: string,\n): CompactReadClassification | undefined {\n\tconst rawPath = str(args?.path);\n\tif (!rawPath) return undefined;\n\tconst absolutePath = resolveToCwd(rawPath, cwd);\n\tconst fileName = basename(absolutePath);\n\tif (fileName === \"SKILL.md\") {\n\t\treturn { kind: \"skill\", label: basename(dirname(absolutePath)) || fileName };\n\t}\n\tconst docsClassification = getPiDocsClassification(absolutePath);\n\tif (docsClassification) return docsClassification;\n\tif (COMPACT_RESOURCE_FILE_NAMES.has(fileName)) {\n\t\treturn { kind: \"resource\", label: formatPathRelativeToCwdOrAbsolute(absolutePath, cwd) };\n\t}\n\treturn undefined;\n}\nfunction formatCompactReadCall(\n\tclassification: CompactReadClassification,\n\targs: ReadRenderArgs | undefined,\n\ttheme: Theme,\n): string {\n\tconst expandHint = theme.fg(\"dim\", ` (${keyText(\"app.tools.expand\")} Expand)`);\n\tif (classification.kind === \"skill\") {\n\t\treturn (\n\t\t\ttheme.fg(\"customMessageLabel\", `\\x1b[1m[skill]\\x1b[22m `) +\n\t\t\ttheme.fg(\"customMessageText\", classification.label) +\n\t\t\tformatReadLineRange(args, theme) +\n\t\t\texpandHint\n\t\t);\n\t}\n\treturn (\n\t\ttheme.fg(\"toolTitle\", theme.bold(`read ${classification.kind}`)) +\n\t\t\" \" +\n\t\ttheme.fg(\"accent\", classification.label) +\n\t\tformatReadLineRange(args, theme) +\n\t\texpandHint\n\t);\n}\nfunction formatReadResult(\n\targs: ReadRenderArgs | undefined,\n\tresult: { content: (TextContent | ImageContent)[]; details?: ReadToolDetails },\n\toptions: ToolRenderResultOptions,\n\ttheme: Theme,\n\tshowImages: boolean,\n\t_cwd: string,\n\tisError: boolean,\n): string {\n\tconst oversizedRead = result.details?.oversizedRead;\n\tconst oversizedReadBlocked = oversizedRead?.blocked === true;\n\tif (!options.expanded && !isError && !oversizedReadBlocked) {\n\t\treturn \"\";\n\t}\n\tconst rawPath = str(args?.path);\n\tconst output = oversizedRead ? buildOversizedReadMessage(oversizedRead) : getTextOutput(result, showImages);\n\tconst lang = rawPath && !oversizedReadBlocked ? getLanguageFromPath(rawPath) : undefined;\n\tconst renderedLines = lang ? highlightCode(replaceTabs(output), lang) : output.split(\"\\n\");\n\tconst lines = trimTrailingEmptyLines(renderedLines);\n\tconst maxLines = options.expanded ? lines.length : 10;\n\tconst displayLines = lines.slice(0, maxLines);\n\tconst remaining = lines.length - maxLines;\n\tlet text = `\\n${displayLines.map((line) => (lang ? replaceTabs(line) : theme.fg(\"toolOutput\", replaceTabs(line)))).join(\"\\n\")}`;\n\tif (remaining > 0) {\n\t\ttext += `${theme.fg(\"muted\", `\\n... (${remaining} more lines,`)} ${keyHint(\"app.tools.expand\", \"Expand\")}${theme.fg(\"muted\", \")\")}`;\n\t}\n\tconst truncation = result.details?.truncation;\n\tif (truncation?.truncated) {\n\t\tif (truncation.firstLineExceedsLimit) {\n\t\t\ttext += `\\n${theme.fg(\"warning\", `[First line exceeds ${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit]`)}`;\n\t\t} else if (truncation.truncatedBy === \"lines\") {\n\t\t\ttext += `\\n${theme.fg(\"warning\", `[Truncated: showing ${truncation.outputLines} of ${truncation.totalLines} lines (${truncation.maxLines ?? DEFAULT_MAX_LINES} line limit)]`)}`;\n\t\t} else {\n\t\t\ttext += `\\n${theme.fg(\"warning\", `[Truncated: ${truncation.outputLines} lines shown (${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit)]`)}`;\n\t\t}\n\t}\n\treturn text;\n}\nfunction archiveSelectorMemberExists(pathValue: string, cwd: string): boolean { const archive = parseArchiveSelector(pathValue); if (!archive || !archive.memberPath) return false; try { readArchiveSelector(resolveArchiveSelector(archive, cwd)); return true; } catch { return false; } }\nfunction appendReadSelectors(pathValue: string, selector: ReadLineSelector): string {\n\tconst range = selector.ranges?.map((item) => item.end === undefined ? `${item.start}` : `${item.start}-${item.end}`).join(\",\") ?? (selector.offset ? `${selector.offset}` : \"\");\n\treturn `${pathValue}${range ? `:${range}` : \"\"}${selector.conflicts ? \":conflicts\" : \"\"}${selector.raw ? \":raw\" : \"\"}`;\n}\nexport function createReadToolDefinition(cwd: string, options?: ReadToolOptions): ToolDefinition<typeof readSchema, ReadToolDetails | undefined> {\n\tconst autoResizeImages = options?.autoResizeImages ?? true;\n\tconst ops = options?.operations ?? defaultReadOperations;\n\tconst hashlineStore = options?.hashlineStore ?? createHashlineSnapshotStore();\n\treturn {\n\t\tname: \"read\",\n\t\tlabel: \"read\",\n\t\tdescription: \"Read files, directories, archives, SQLite databases, internal resources, images, documents, and URLs through one path string.\",\n\t\tpromptSnippet: \"Read a path selector.\",\n\t\tpromptGuidelines: [\"Use read to inspect file and resource contents; use path selectors for line ranges, raw output, and conflict views.\"],\n\t\tparameters: readSchema,\n\t\tmaxResultSizeChars: Infinity,\n\t\tasync execute(\n\t\t\t_toolCallId,\n\t\t\t{ path }: ReadToolInput,\n\t\t\tsignal?: AbortSignal,\n\t\t\t_onUpdate?,\n\t\t\tctx?,\n\t\t) {\n\t\t\tconst resourceCtx = ctx as InternalResourceContext | undefined;\n\t\t\tconst splitSelector = splitReadLineSelector(path), markerless = path.replace(/:raw(?=(:|$))/g, \"\").replace(/:conflicts(?=(:|$))/g, \"\"), sqliteOriginal = sqliteSelectorForPath(markerless, cwd), sqliteDirect = sqliteSelectorForPath(path, cwd);\n\t\t\tconst selector = archiveSelectorMemberExists(path, cwd) ? { path } : sqliteDirect && (sqliteDirect.table === \"raw\" || sqliteDirect.table === \"conflicts\") ? { path } : sqliteOriginal?.rowId && splitSelector.path !== markerless ? { path: markerless, raw: splitSelector.raw, conflicts: splitSelector.conflicts } : sqliteOriginal && splitSelector.path === markerless && markerless !== path ? { path: markerless, raw: splitSelector.raw, conflicts: splitSelector.conflicts } : splitSelector.path === path && sqliteDirect ? { path } : splitSelector;\n\t\t\tconst effectivePath = selector.path;\n\t\t\tconst effectiveOffset = selector.offset;\n\t\t\tconst effectiveLimit = selector.limit;\n\t\t\tconst effectiveRanges = selector.ranges;\n\t\t\tconst rawOutput = selector.raw;\n\t\t\tconst conflictsOnly = selector.conflicts;\n\t\t\treturn new Promise<{ content: (TextContent | ImageContent)[]; details: ReadToolDetails | undefined }>(\n\t\t\t\t(resolve, reject) => {\n\t\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\t\treject(new Error(\"Operation aborted\"));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tlet aborted = false;\n\t\t\t\t\tconst onAbort = () => {\n\t\t\t\t\t\taborted = true;\n\t\t\t\t\t\treject(new Error(\"Operation aborted\"));\n\t\t\t\t\t};\n\t\t\t\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\t\t\t(async () => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst archive = parseArchiveSelector(effectivePath);\n\t\t\t\t\t\t\tconst sqlite = sqliteSelectorForPath(effectivePath, cwd);\n\t\t\t\t\t\t\tif (isReadableUrlPath(effectivePath)) {\n\t\t\t\t\t\t\t\tresolve(await readUrlBranch({ effectivePath, rawOutput: rawOutput === true, effectiveRanges, effectiveOffset, effectiveLimit, cwd, ctx, signal, maxChars: READ_TOOL_MAX_RESULT_CHARS, maxBytes: DEFAULT_MAX_BYTES, oversized: oversizedReadResult, sourceMeta: readSourceMeta }));\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (sqlite) {\n\t\t\t\t\t\t\t\tconst textContent = readSqliteSelector(sqlite), selection = applyReadLineSelection(textContent.split(\"\\n\"), effectiveRanges, effectiveOffset, effectiveLimit, rawOutput), selectedText = selection.lines.join(\"\\n\");\n\t\t\t\t\t\t\t\tif ((effectiveRanges || effectiveOffset) && selection.lines.length === 0) { const requested = effectiveRanges?.[0]?.start ?? effectiveOffset ?? 1; resolve({ content: [{ type: \"text\", text: `Requested line ${requested} is beyond end of resource (${textContent.split(\"\\n\").length} lines total).` }], details: undefined }); return; }\n\t\t\t\t\t\t\t\tif (selectedText.length > READ_TOOL_MAX_RESULT_CHARS || Buffer.byteLength(selectedText, \"utf8\") > DEFAULT_MAX_BYTES) { resolve(oversizedReadResult({ blocked: true, path: effectivePath, chars: selectedText.length, maxChars: READ_TOOL_MAX_RESULT_CHARS, startLine: selection.firstLine, totalFileLines: textContent.split(\"\\n\").length, firstLineBytes: Buffer.byteLength(selection.lines[0] ?? \"\", \"utf8\"), byteGuidance: false })); return; }\n\t\t\t\t\t\t\tresolve({ content: [{ type: \"text\", text: selectedText }], details: readSourceMeta(effectivePath) }); return;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (archive) {\n\t\t\t\t\t\t\t\tconst resolvedArchive = resolveArchiveSelector(archive, cwd);\n\t\t\t\t\t\t\t\tconst textContent = readArchiveSelector(resolvedArchive);\n\t\t\t\t\t\t\t\tlet allLines = textContent.split(\"\\n\");\n\t\t\t\t\t\t\t\tif (conflictsOnly) {\n\t\t\t\t\t\t\t\t\tlet inConflict = false;\n\t\t\t\t\t\t\t\t\tconst conflictLines = allLines.filter((line) => { if (line.startsWith(\"<<<<<<<\")) inConflict = true; const keep = inConflict; if (line.startsWith(\">>>>>>>\")) inConflict = false; return keep; });\n\t\t\t\t\t\t\t\t\tif (conflictLines.length === 0) { resolve({ content: [{ type: \"text\", text: \"No conflict markers found\" }], details: undefined }); return; }\n\t\t\t\t\t\t\t\t\tallLines = conflictLines;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tconst rangeSelection = (rawOutput ? selectExactReadRanges : selectReadRanges)(allLines, effectiveRanges);\n\t\t\t\t\t\t\t\tconst startLine = rangeSelection ? rangeSelection.firstLine - 1 : effectiveOffset ? Math.max(0, effectiveOffset - 1) : 0;\n\t\t\t\t\t\t\t\tif (startLine >= allLines.length || (effectiveRanges && rangeSelection?.selectedLines.length === 0)) {\n\t\t\t\t\t\t\t\t\tresolve({ content: [{ type: \"text\", text: `Requested line ${startLine + 1} is beyond end of resource (${allLines.length} lines total).` }], details: undefined });\n\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tconst endLine = effectiveLimit !== undefined ? Math.min(startLine + effectiveLimit, allLines.length) : allLines.length;\n\t\t\t\t\t\t\t\tconst selectedLines = rangeSelection?.selectedLines ?? allLines.slice(startLine, endLine);\n\t\t\t\t\t\t\t\tconst selectedText = selectedLines.join(\"\\n\");\n\t\t\t\t\t\t\t\tif (selectedText.length > READ_TOOL_MAX_RESULT_CHARS || Buffer.byteLength(selectedText, \"utf8\") > DEFAULT_MAX_BYTES) { resolve(oversizedReadResult({ blocked: true, path: `${resolvedArchive.archivePath}:${resolvedArchive.memberPath}`, chars: selectedText.length, maxChars: READ_TOOL_MAX_RESULT_CHARS, startLine: startLine + 1, totalFileLines: allLines.length, firstLineBytes: Buffer.byteLength(selectedLines[0] ?? \"\", \"utf8\"), byteGuidance: false })); return; }\n\t\t\t\t\t\t\tresolve({ content: [{ type: \"text\", text: selectedText }], details: readSourceMeta(`${resolvedArchive.archivePath}:${resolvedArchive.memberPath}`) });\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (/^(?:skill|agent|artifact|history|issue|local|memory|pr|conflict|omp|rule|mcp|vault):\\/\\//.test(effectivePath)) {\n\t\t\t\t\t\t\t\tconst sourcePath = effectivePath.startsWith(\"local://\") ? resolveInternalSelector(effectivePath, cwd) : undefined;\n\t\t\t\t\t\t\t\tif (sourcePath) { resolve(await createReadToolDefinition(cwd, options).execute(_toolCallId, { path: appendReadSelectors(sourcePath, selector) }, signal, _onUpdate, ctx as never)); return; }\n\t\t\t\t\t\t\t\tconst allLines = (await readInternalSelector(effectivePath, cwd, resourceCtx)).split(\"\\n\");\n\t\t\t\t\t\t\t\tconst rangeSelection = (rawOutput ? selectExactReadRanges : selectReadRanges)(allLines, effectiveRanges);\n\t\t\t\t\t\t\t\tconst startLine = rangeSelection ? rangeSelection.firstLine - 1 : effectiveOffset ? Math.max(0, effectiveOffset - 1) : 0;\n\t\t\t\t\t\t\t\tif (startLine >= allLines.length || (effectiveRanges && rangeSelection?.selectedLines.length === 0)) {\n\t\t\t\t\t\t\t\t\tresolve({ content: [{ type: \"text\", text: `Requested line ${startLine + 1} is beyond end of resource (${allLines.length} lines total).` }], details: undefined });\n\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tconst endLine = effectiveLimit !== undefined ? Math.min(startLine + effectiveLimit, allLines.length) : allLines.length;\n\t\t\t\t\t\t\t\tconst selectedLines = rangeSelection?.selectedLines ?? allLines.slice(startLine, endLine);\n\t\t\t\t\t\t\t\tconst selectedText = selectedLines.join(\"\\n\");\n\t\t\t\t\t\t\t\tif (selectedText.length > READ_TOOL_MAX_RESULT_CHARS || Buffer.byteLength(selectedText, \"utf8\") > DEFAULT_MAX_BYTES) { resolve(oversizedReadResult({ blocked: true, path: effectivePath, chars: selectedText.length, maxChars: READ_TOOL_MAX_RESULT_CHARS, startLine: startLine + 1, totalFileLines: allLines.length, firstLineBytes: Buffer.byteLength(selectedLines[0] ?? \"\", \"utf8\"), byteGuidance: false })); return; }\n\t\t\t\t\t\t\tresolve({ content: [{ type: \"text\", text: selectedText }], details: readSourceMeta(effectivePath) });\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (isReadResourceSelector(effectivePath)) throw new Error(`Read resource selectors are not supported by this filesystem backend: ${path}`);\n\t\t\t\t\t\t\tconst absolutePath = await resolveReadPathAsync(effectivePath, cwd);\n\t\t\t\t\t\t\tif (aborted) return;\n\t\t\t\t\t\t\tlet content: (TextContent | ImageContent)[];\n\t\t\t\t\t\t\tlet details: ReadToolDetails | undefined;\n\t\t\t\t\t\t\tawait ops.access(absolutePath);\n\t\t\t\t\t\t\tif (aborted) return;\n\t\t\t\t\t\t\tif (isDocumentPath(absolutePath) && !rawOutput && !isNotebookPath(absolutePath)) {\n\t\t\t\t\t\t\t\tconst buffer = await ops.readFile(absolutePath);\n\t\t\t\t\t\t\t\tconst textContent = await extractDocumentMarkdown(buffer, absolutePath);\n\t\t\t\t\t\t\t\tconst selection = applyReadLineSelection(textContent.split(\"\\n\"), effectiveRanges, effectiveOffset, effectiveLimit, rawOutput);\n\t\t\t\t\t\t\t\tif (selection.lines.length === 0) { resolve({ content: [{ type: \"text\", text: `Requested line ${selection.firstLine} is beyond end of document (${textContent.split(\"\\n\").length} lines total).` }], details: undefined }); return; }\n\t\t\t\t\t\t\t\tconst selectedText = selection.lines.join(\"\\n\");\n\t\t\t\t\t\t\tif (selectedText.length > READ_TOOL_MAX_RESULT_CHARS || Buffer.byteLength(selectedText, \"utf8\") > DEFAULT_MAX_BYTES) { resolve(oversizedReadResult({ blocked: true, path: absolutePath, chars: selectedText.length, maxChars: READ_TOOL_MAX_RESULT_CHARS, startLine: selection.firstLine, totalFileLines: textContent.split(\"\\n\").length, firstLineBytes: Buffer.byteLength(selection.lines[0] ?? \"\", \"utf8\"), byteGuidance: false })); return; }\n\t\t\t\t\t\t\tcontent = [{ type: \"text\", text: selectedText }]; resolve({ content, details: readSourceMeta(absolutePath) }); return;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (!options?.operations && (await fsStat(absolutePath)).isDirectory()) {\n\t\t\t\t\t\t\t\tconst tree = await buildDirectoryTree(absolutePath, { maxDepth: 2, perDirLimit: 12, rootLimit: null });\n\t\t\t\t\t\t\t\tconst allLines = tree.rendered.split(\"\\n\"), rangeSelection = (rawOutput ? selectExactReadRanges : selectReadRanges)(allLines, effectiveRanges), startLine = rangeSelection ? rangeSelection.firstLine - 1 : effectiveOffset ? Math.max(0, effectiveOffset - 1) : 0;\n\t\t\t\t\t\t\t\tif (startLine >= allLines.length || (effectiveRanges && rangeSelection?.selectedLines.length === 0)) { resolve({ content: [{ type: \"text\", text: `Requested line ${startLine + 1} is beyond end of directory (${allLines.length} lines total).` }], details: undefined }); return; }\n\t\t\t\t\t\t\t\tconst endLine = effectiveLimit !== undefined ? Math.min(startLine + effectiveLimit, allLines.length) : allLines.length, selectedLines = rangeSelection?.selectedLines ?? allLines.slice(startLine, endLine);\n\t\t\t\t\t\t\t\tcontent = [{ type: \"text\", text: selectedLines.join(\"\\n\") }];\n\t\t\t\t\t\t\t\tconst meta = { ...readSourceMeta(absolutePath).meta, ...(tree.truncated ? { limits: { perDirLimit: 12, totalLines: tree.totalLines } } : {}) };\n\t\t\t\t\t\t\t\tresolve({ content, details: { isDirectory: true, resolvedPath: absolutePath, meta } });\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst mimeType = ops.detectImageMimeType ? await ops.detectImageMimeType(absolutePath) : undefined;\n\t\t\t\t\t\t\tconst nonVisionImageNote = getNonVisionImageNote(ctx?.model);\n\t\t\t\t\t\t\tif (mimeType) {\n\t\t\t\t\t\t\t\tconst buffer = await ops.readFile(absolutePath);\n\t\t\t\t\t\t\t\tif (autoResizeImages) {\n\t\t\t\t\t\t\t\t\tconst resized = await resizeImage(buffer, mimeType);\n\t\t\t\t\t\t\t\t\tif (!resized) {\n\t\t\t\t\t\t\t\t\t\tlet textNote = `Read image file [${mimeType}]\\n[Image omitted: could not be resized below the inline image size limit.]`;\n\t\t\t\t\t\t\t\t\t\tif (nonVisionImageNote) textNote += `\\n${nonVisionImageNote}`;\n\t\t\t\t\t\t\t\t\t\tcontent = [{ type: \"text\", text: textNote }];\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\tconst dimensionNote = formatDimensionNote(resized);\n\t\t\t\t\t\t\t\t\t\tlet textNote = `Read image file [${resized.mimeType}]`;\n\t\t\t\t\t\t\t\t\t\tif (dimensionNote) textNote += `\\n${dimensionNote}`;\n\t\t\t\t\t\t\t\t\t\tif (nonVisionImageNote) textNote += `\\n${nonVisionImageNote}`;\n\t\t\t\t\t\t\t\t\t\tcontent = [\n\t\t\t\t\t\t\t\t\t\t\t{ type: \"text\", text: textNote },\n\t\t\t\t\t\t\t\t\t\t\t{ type: \"image\", data: resized.data, mimeType: resized.mimeType },\n\t\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tlet textNote = `Read image file [${mimeType}]`;\n\t\t\t\t\t\t\t\t\tif (nonVisionImageNote) textNote += `\\n${nonVisionImageNote}`;\n\t\t\t\t\t\t\t\t\tcontent = [\n\t\t\t\t\t\t\t\t\t\t{ type: \"text\", text: textNote },\n\t\t\t\t\t\t\t\t\t\t{ type: \"image\", data: buffer.toString(\"base64\"), mimeType },\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tconst buffer = await ops.readFile(absolutePath);\n\t\t\t\t\t\t\t\tconst textContent = (isNotebookPath(absolutePath) && !rawOutput) ? readEditableNotebookText(absolutePath, effectivePath) : buffer.toString(\"utf-8\");\n\t\t\t\t\t\t\t\tlet allLines = textContent.split(\"\\n\");\n\t\t\t\t\t\t\t\tlet conflictLineNumbers: number[] | undefined;\n\t\t\t\t\t\t\t\tif (conflictsOnly) {\n\t\t\t\t\t\t\t\t\tregisterConflictBlocks(cwd, parseConflictBlocks(absolutePath, textContent));\n\t\t\t\t\t\t\t\t\tconst conflictLines: string[] = [];\n\t\t\t\t\t\t\t\t\tconflictLineNumbers = [];\n\t\t\t\t\t\t\t\t\tlet inConflict = false;\n\t\t\t\t\t\t\t\t\tallLines.forEach((line, index) => {\n\t\t\t\t\t\t\t\t\t\tif (line.startsWith(\"<<<<<<<\")) inConflict = true;\n\t\t\t\t\t\t\t\t\t\tif (inConflict) { conflictLines.push(line); conflictLineNumbers!.push(index + 1); }\n\t\t\t\t\t\t\t\t\t\tif (line.startsWith(\">>>>>>>\")) inConflict = false;\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\tif (conflictLines.length > 0) allLines = conflictLines;\n\t\t\t\t\t\t\t\t\telse { signal?.removeEventListener(\"abort\", onAbort); resolve({ content: [{ type: \"text\", text: \"No conflict markers found\" }], details: undefined }); return; }\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tconst totalFileLines = allLines.length;\n\t\t\t\t\t\t\t\tconst rangeSelection = (rawOutput ? selectExactReadRanges : selectReadRanges)(allLines, effectiveRanges);\n\t\t\t\t\t\t\t\tconst startLine = rangeSelection ? rangeSelection.firstLine - 1 : effectiveOffset ? Math.max(0, effectiveOffset - 1) : 0;\n\t\t\t\t\t\t\t\tconst startLineDisplay = startLine + 1;\n\t\t\t\t\t\t\t\tif (startLine >= allLines.length || (effectiveRanges && rangeSelection?.selectedLines.length === 0)) {\n\t\t\t\t\t\t\t\t\tconst requested = effectiveRanges?.[0]?.start ?? startLineDisplay;\n\t\t\t\t\t\t\t\t\tresolve({ content: [{ type: \"text\", text: `Requested line ${requested} is beyond end of file (${allLines.length} lines total). Use ${effectivePath}:${Math.max(1, allLines.length)} to read the final line.` }], details: undefined });\n\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tlet selectedContent: string;\n\t\t\t\t\t\t\t\tlet selectedLines: string[];\n\t\t\t\t\t\t\t\tlet userLimitedLines: number | undefined;\n\t\t\t\t\t\t\t\tif (rangeSelection) {\n\t\t\t\t\t\t\t\t\tselectedLines = rangeSelection.selectedLines;\n\t\t\t\t\t\t\t\t\tselectedContent = rangeSelection.selectedContent;\n\t\t\t\t\t\t\t\t\tuserLimitedLines = rangeSelection.userLimitedLines;\n\t\t\t\t\t\t\t\t} else if (effectiveLimit !== undefined) {\n\t\t\t\t\t\t\t\t\tconst endLine = Math.min(startLine + effectiveLimit, allLines.length);\n\t\t\t\t\t\t\t\t\tselectedLines = allLines.slice(startLine, endLine);\n\t\t\t\t\t\t\t\t\tselectedContent = selectedLines.join(\"\\n\");\n\t\t\t\t\t\t\t\t\tuserLimitedLines = endLine - startLine;\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tselectedLines = allLines.slice(startLine);\n\t\t\t\t\t\t\t\t\tselectedContent = selectedLines.join(\"\\n\");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (selectedContent.length > READ_TOOL_MAX_RESULT_CHARS) {\n\t\t\t\t\t\t\t\t\tconst firstSelectedLine = allLines[startLine] ?? \"\";\n\t\t\t\t\t\t\t\t\tconst firstLineBytes = Buffer.byteLength(firstSelectedLine, \"utf-8\");\n\t\t\t\t\t\t\t\t\tconst selectedLineCount = trimTrailingEmptyLines(selectedLines).length;\n\t\t\t\t\t\t\t\t\tconst byteGuidance = selectedLineCount <= 1 || firstLineBytes > DEFAULT_MAX_BYTES;\n\t\t\t\t\t\t\t\t\tconst oversizedRead: OversizedReadDetails = { blocked: true, path: absolutePath, chars: selectedContent.length, maxChars: READ_TOOL_MAX_RESULT_CHARS, startLine: startLineDisplay, ...(effectiveLimit !== undefined ? { requestedLimit: effectiveLimit } : {}), totalFileLines, firstLineBytes, byteGuidance };\n\t\t\t\t\t\t\t\tdetails = { oversizedRead, meta: readSourceMeta(absolutePath).meta };\n\t\t\t\t\t\t\t\t\tcontent = [{ type: \"text\", text: buildOversizedReadMessage(oversizedRead) }];\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tconst truncation = truncateHead(selectedContent);\n\t\t\t\t\t\t\t\t\tlet outputText = truncation.content;\n\t\t\t\t\t\t\t\t\tif (truncation.firstLineExceedsLimit) {\n\t\t\t\t\t\t\t\t\t\tconst firstLineSize = formatSize(Buffer.byteLength(allLines[startLine], \"utf-8\"));\n\t\t\t\t\t\t\t\t\t\toutputText = `[Line ${startLineDisplay} is ${firstLineSize}, exceeds ${formatSize(DEFAULT_MAX_BYTES)} limit. Use bash: sed -n '${startLineDisplay}p' ${effectivePath} | head -c ${DEFAULT_MAX_BYTES}]`;\n\t\t\t\t\t\tdetails = { truncation, meta: { source: absolutePath, sourcePath: absolutePath, truncation } };\n\t\t\t\t\t\t\t\t\t} else if (truncation.truncated) {\n\t\t\t\t\t\t\t\t\t\tconst endLineDisplay = startLineDisplay + truncation.outputLines - 1;\n\t\t\t\t\t\t\t\t\t\tconst nextOffset = endLineDisplay + 1;\n\t\t\t\t\t\t\t\t\t\toutputText += truncation.truncatedBy === \"lines\" ? `\\n\\n[Showing lines ${startLineDisplay}-${endLineDisplay} of ${totalFileLines}. Continue with path selector :${nextOffset}.]` : `\\n\\n[Showing lines ${startLineDisplay}-${endLineDisplay} of ${totalFileLines} (${formatSize(DEFAULT_MAX_BYTES)} limit). Continue with path selector :${nextOffset}.]`;\n\t\t\t\t\t\tdetails = { truncation, meta: { source: absolutePath, sourcePath: absolutePath, truncation } };\n\t\t\t\t\t\t\t\t\t} else if (!rawOutput && userLimitedLines !== undefined && startLine + userLimitedLines < allLines.length) {\n\t\t\t\t\t\t\t\t\t\tconst remaining = allLines.length - (startLine + userLimitedLines);\n\t\t\t\t\t\t\t\t\t\tconst nextOffset = startLine + userLimitedLines + 1;\n\t\t\t\t\t\t\t\t\t\toutputText = `${truncation.content}\\n\\n[${remaining} more lines in file. Continue with path selector :${nextOffset}.]`;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tif (truncation.firstLineExceedsLimit) content = [{ type: \"text\", text: outputText }];\n\t\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\t\tconst snapshot = recordHashlineSnapshot(absolutePath, cwd, textContent, hashlineStore);\n\t\t\t\t\t\t\t\t\t\tconst visibleContent = truncation.truncated ? truncation.content : selectedContent;\n\t\t\t\t\t\t\t\t\t\tconst header = `[${snapshot.displayPath}#${snapshot.tag}]`;\n\t\t\t\t\t\t\t\t\t\tconst selectedConflictLineNumbers = conflictLineNumbers && rangeSelection?.lineNumbers ? rangeSelection.lineNumbers.map((line) => conflictLineNumbers![line - 1]).filter((line): line is number => typeof line === \"number\") : conflictLineNumbers ? conflictLineNumbers.slice(startLine, startLine + selectedLines.length) : undefined;\n\t\t\t\t\t\t\t\t\t\tlet hashlineOutput = rawOutput ? visibleContent : selectedConflictLineNumbers && visibleContent === selectedContent ? formatHashlineSelectedLines(header, selectedLines, selectedConflictLineNumbers) : rangeSelection && visibleContent === selectedContent ? formatHashlineSelectedLines(header, selectedLines, rangeSelection.lineNumbers) : formatHashlineContent(snapshot, visibleContent, startLineDisplay);\n\t\t\t\t\t\t\t\t\t\tif (outputText.startsWith(truncation.content) && outputText.length > truncation.content.length) hashlineOutput += outputText.slice(truncation.content.length);\n\t\t\t\t\t\t\t\t\t\tcontent = [{ type: \"text\", text: hashlineOutput }];\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (aborted) return;\n\t\t\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\t\tresolve({ content, details: details ?? readSourceMeta(absolutePath) });\n\t\t\t\t\t\t} catch (error: unknown) {\n\t\t\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\t\t\tif (!aborted) reject(error);\n\t\t\t\t\t\t}\n\t\t\t\t\t})();\n\t\t\t\t},\n\t\t\t);\n\t\t},\n\t\trenderCall(args, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\tconst classification = !context.expanded ? getCompactReadClassification(args, context.cwd) : undefined;\n\t\t\ttext.setText(\n\t\t\t\tclassification ? formatCompactReadCall(classification, args, theme) : formatReadCall(args, theme),\n\t\t\t);\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(\n\t\t\t\tformatReadResult(context.args, result, options, theme, context.showImages, context.cwd, context.isError),\n\t\t\t);\n\t\t\treturn text;\n\t\t},\n\t};\n}\nexport function createReadTool(cwd: string, options?: ReadToolOptions): AgentTool<typeof readSchema> {\n\treturn wrapToolDefinition(createReadToolDefinition(cwd, options));\n}\n"]}