@draht/coding-agent 2026.11.5 → 2026.11.14

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 (306) hide show
  1. package/CHANGELOG.md +66 -0
  2. package/dist/bundle/chunks/anthropic-messages-FKSSTO6N.js +6 -0
  3. package/dist/bundle/chunks/{azure-openai-responses-5YLWRJ4E.js → azure-openai-responses-AHIW4IRP.js} +1 -1
  4. package/dist/bundle/chunks/bedrock-converse-stream.js +2 -2
  5. package/dist/bundle/chunks/chunk-2CHTECAU.js +2 -0
  6. package/dist/bundle/chunks/{chunk-SPVE2GM7.js → chunk-46NQOOTO.js} +1 -1
  7. package/dist/bundle/chunks/{chunk-MKVW4KK2.js → chunk-4ALYWMDD.js} +1 -1
  8. package/dist/bundle/chunks/{chunk-EXZUXBS5.js → chunk-5K3TBDND.js} +12 -15
  9. package/dist/bundle/chunks/{chunk-PRT3JHOZ.js → chunk-DFFQ5ETM.js} +1 -1
  10. package/dist/bundle/chunks/chunk-EBTEI43G.js +20 -0
  11. package/dist/bundle/chunks/{chunk-LJ3SEGWI.js → chunk-G7DJ6PIU.js} +5 -1
  12. package/dist/bundle/chunks/{chunk-3LFBXSCO.js → chunk-GR3JEDCL.js} +1 -1
  13. package/dist/bundle/chunks/{chunk-JAT7HEFU.js → chunk-HIL6BIBX.js} +2 -2
  14. package/dist/bundle/chunks/{chunk-PZKD35UB.js → chunk-MXA4WY3C.js} +1 -1
  15. package/dist/bundle/chunks/chunk-NJDELBDB.js +82 -0
  16. package/dist/bundle/chunks/{chunk-CLNF6E5P.js → chunk-NLVN7RG3.js} +1 -1
  17. package/dist/bundle/chunks/chunk-NLYBRJ3F.js +9 -0
  18. package/dist/bundle/chunks/{chunk-UQSONZLL.js → chunk-OPLOTJXH.js} +3 -1
  19. package/dist/bundle/chunks/{chunk-YUBUKEPQ.js → chunk-PPJRJAR3.js} +169 -130
  20. package/dist/bundle/chunks/chunk-RIPTEKPX.js +44 -0
  21. package/dist/bundle/chunks/chunk-ROB5AWV5.js +30 -0
  22. package/dist/bundle/chunks/chunk-WNZ64GW3.js +2 -0
  23. package/dist/bundle/chunks/{chunk-ABW2JATG.js → chunk-XEVRP72T.js} +1 -1
  24. package/dist/bundle/chunks/{chunk-SKQFE2GA.js → chunk-XY64T2H6.js} +1 -1
  25. package/dist/bundle/chunks/chunk-ZZAOELWU.js +2 -0
  26. package/dist/bundle/chunks/{cli-7AMCJ2UG.js → cli-JDGPEN7N.js} +3 -3
  27. package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-QBCV2OWJ.js → cloudflare-workers-ai-system-one-ZPDQKK4H.js} +1 -1
  28. package/dist/bundle/chunks/codemode-worker.js +2 -0
  29. package/dist/bundle/chunks/{execute-VOIPQMCI.js → execute-YOMYOVUT.js} +2 -2
  30. package/dist/bundle/chunks/github-copilot.js +1 -1
  31. package/dist/bundle/chunks/google-generative-ai-EEDLVZAQ.js +2 -0
  32. package/dist/bundle/chunks/google-vertex-YQDP6U25.js +2 -0
  33. package/dist/bundle/chunks/{llama-cpp-classify-WGVYEPG2.js → llama-cpp-classify-SRUYBPZS.js} +1 -1
  34. package/dist/bundle/chunks/{mistral-conversations-PV6RDK65.js → mistral-conversations-QKVAIF57.js} +1 -1
  35. package/dist/bundle/chunks/{openai-codex-responses-SEOL3EDF.js → openai-codex-responses-2FIT2Z3L.js} +1 -1
  36. package/dist/bundle/chunks/{openai-completions-U32QPS37.js → openai-completions-42OND4EW.js} +3 -3
  37. package/dist/bundle/chunks/{openai-decisions-ULSYFV2A.js → openai-decisions-FAP6LRGH.js} +1 -1
  38. package/dist/bundle/chunks/{openai-responses-5MYZJYPK.js → openai-responses-BGC7WCIQ.js} +1 -1
  39. package/dist/bundle/chunks/{openrouter-images-SGOP5SDW.js → openrouter-images-EAWW57ZG.js} +1 -1
  40. package/dist/bundle/chunks/{pi-messages-QALFE2BD.js → pi-messages-JM6JDMH5.js} +1 -1
  41. package/dist/bundle/chunks/{runtime-GDH3ZURV.js → runtime-F63NCS5Y.js} +1 -1
  42. package/dist/bundle/chunks/{runtime-Z74VFUDD.js → runtime-S5WBSLTE.js} +1 -1
  43. package/dist/bundle/chunks/{settings-manager-T6UJFO2F.js → settings-manager-H3QEOPQ3.js} +1 -1
  44. package/dist/bundle/chunks/{typesafe-system-one-GTGS5MG6.js → typesafe-system-one-QOA2PTJR.js} +1 -1
  45. package/dist/bundle/chunks/virtual-modules-2BURZRW7.js +2 -0
  46. package/dist/bundle/cli-runtime.js +1 -1
  47. package/dist/bundle/index.js +1 -1
  48. package/dist/bundle/rpc-entry.js +1 -1
  49. package/dist/cli/args.d.ts.map +1 -1
  50. package/dist/cli/args.js +5 -3
  51. package/dist/cli/args.js.map +1 -1
  52. package/dist/cli/auth-command.d.ts.map +1 -1
  53. package/dist/cli/auth-command.js +30 -6
  54. package/dist/cli/auth-command.js.map +1 -1
  55. package/dist/cli/auth-login.d.ts +15 -0
  56. package/dist/cli/auth-login.d.ts.map +1 -0
  57. package/dist/cli/auth-login.js +232 -0
  58. package/dist/cli/auth-login.js.map +1 -0
  59. package/dist/cli/auth-logout.d.ts +14 -0
  60. package/dist/cli/auth-logout.d.ts.map +1 -0
  61. package/dist/cli/auth-logout.js +57 -0
  62. package/dist/cli/auth-logout.js.map +1 -0
  63. package/dist/cli/auth-terminal.d.ts +17 -0
  64. package/dist/cli/auth-terminal.d.ts.map +1 -0
  65. package/dist/cli/auth-terminal.js +63 -0
  66. package/dist/cli/auth-terminal.js.map +1 -0
  67. package/dist/core/agent-session-runtime.d.ts +5 -0
  68. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  69. package/dist/core/agent-session-runtime.js +16 -2
  70. package/dist/core/agent-session-runtime.js.map +1 -1
  71. package/dist/core/agent-session.d.ts +20 -9
  72. package/dist/core/agent-session.d.ts.map +1 -1
  73. package/dist/core/agent-session.js +71 -29
  74. package/dist/core/agent-session.js.map +1 -1
  75. package/dist/core/ai-schemas.d.ts +1 -0
  76. package/dist/core/ai-schemas.d.ts.map +1 -1
  77. package/dist/core/builtins/budgets.d.ts.map +1 -1
  78. package/dist/core/builtins/budgets.js +6 -3
  79. package/dist/core/builtins/budgets.js.map +1 -1
  80. package/dist/core/cache-warmer.d.ts +4 -37
  81. package/dist/core/cache-warmer.d.ts.map +1 -1
  82. package/dist/core/cache-warmer.js +11 -91
  83. package/dist/core/cache-warmer.js.map +1 -1
  84. package/dist/core/compaction/utils.d.ts.map +1 -1
  85. package/dist/core/compaction/utils.js +2 -1
  86. package/dist/core/compaction/utils.js.map +1 -1
  87. package/dist/core/exec.d.ts +1 -0
  88. package/dist/core/exec.d.ts.map +1 -1
  89. package/dist/core/exec.js +4 -1
  90. package/dist/core/exec.js.map +1 -1
  91. package/dist/core/export-html/ansi-to-html.d.ts +5 -0
  92. package/dist/core/export-html/ansi-to-html.d.ts.map +1 -1
  93. package/dist/core/export-html/ansi-to-html.js +57 -20
  94. package/dist/core/export-html/ansi-to-html.js.map +1 -1
  95. package/dist/core/export-html/template.js +1 -1
  96. package/dist/core/export-html/tool-renderer.d.ts.map +1 -1
  97. package/dist/core/export-html/tool-renderer.js +2 -3
  98. package/dist/core/export-html/tool-renderer.js.map +1 -1
  99. package/dist/core/extensions/types.d.ts +3 -2
  100. package/dist/core/extensions/types.d.ts.map +1 -1
  101. package/dist/core/extensions/types.js.map +1 -1
  102. package/dist/core/model-config.d.ts +13 -0
  103. package/dist/core/model-config.d.ts.map +1 -1
  104. package/dist/core/model-resolver.d.ts +0 -1
  105. package/dist/core/model-resolver.d.ts.map +1 -1
  106. package/dist/core/model-resolver.js +17 -24
  107. package/dist/core/model-resolver.js.map +1 -1
  108. package/dist/core/model-runtime.d.ts +5 -0
  109. package/dist/core/model-runtime.d.ts.map +1 -1
  110. package/dist/core/model-runtime.js +7 -0
  111. package/dist/core/model-runtime.js.map +1 -1
  112. package/dist/core/polyphase/render/format.d.ts +2 -0
  113. package/dist/core/polyphase/render/format.d.ts.map +1 -1
  114. package/dist/core/polyphase/render/format.js +6 -0
  115. package/dist/core/polyphase/render/format.js.map +1 -1
  116. package/dist/core/polyphase/render/run-block.d.ts +4 -0
  117. package/dist/core/polyphase/render/run-block.d.ts.map +1 -1
  118. package/dist/core/polyphase/render/run-block.js +71 -12
  119. package/dist/core/polyphase/render/run-block.js.map +1 -1
  120. package/dist/core/polyphase/render/snapshot.d.ts +1 -1
  121. package/dist/core/polyphase/render/snapshot.d.ts.map +1 -1
  122. package/dist/core/polyphase/render/snapshot.js +22 -7
  123. package/dist/core/polyphase/render/snapshot.js.map +1 -1
  124. package/dist/core/polyphase/ui/dock.d.ts.map +1 -1
  125. package/dist/core/polyphase/ui/dock.js +34 -2
  126. package/dist/core/polyphase/ui/dock.js.map +1 -1
  127. package/dist/core/polyphase/ui/inspector.d.ts +18 -6
  128. package/dist/core/polyphase/ui/inspector.d.ts.map +1 -1
  129. package/dist/core/polyphase/ui/inspector.js +125 -44
  130. package/dist/core/polyphase/ui/inspector.js.map +1 -1
  131. package/dist/core/polyphase/ui/transcript-layout.d.ts.map +1 -1
  132. package/dist/core/polyphase/ui/transcript-layout.js +5 -1
  133. package/dist/core/polyphase/ui/transcript-layout.js.map +1 -1
  134. package/dist/core/preferred-providers.d.ts +17 -0
  135. package/dist/core/preferred-providers.d.ts.map +1 -0
  136. package/dist/core/preferred-providers.js +24 -0
  137. package/dist/core/preferred-providers.js.map +1 -0
  138. package/dist/core/prompt-templates.d.ts.map +1 -1
  139. package/dist/core/prompt-templates.js +18 -2
  140. package/dist/core/prompt-templates.js.map +1 -1
  141. package/dist/core/provider-composer.d.ts.map +1 -1
  142. package/dist/core/provider-composer.js +2 -0
  143. package/dist/core/provider-composer.js.map +1 -1
  144. package/dist/core/provider-matching.d.ts +6 -0
  145. package/dist/core/provider-matching.d.ts.map +1 -0
  146. package/dist/core/provider-matching.js +8 -0
  147. package/dist/core/provider-matching.js.map +1 -0
  148. package/dist/core/radius-mcp.d.ts +13 -0
  149. package/dist/core/radius-mcp.d.ts.map +1 -0
  150. package/dist/core/radius-mcp.js +29 -0
  151. package/dist/core/radius-mcp.js.map +1 -0
  152. package/dist/core/remote-catalog-provider.d.ts.map +1 -1
  153. package/dist/core/remote-catalog-provider.js +2 -0
  154. package/dist/core/remote-catalog-provider.js.map +1 -1
  155. package/dist/core/runtime-credentials.d.ts +8 -0
  156. package/dist/core/runtime-credentials.d.ts.map +1 -1
  157. package/dist/core/runtime-credentials.js +15 -1
  158. package/dist/core/runtime-credentials.js.map +1 -1
  159. package/dist/core/session-cwd.d.ts +7 -0
  160. package/dist/core/session-cwd.d.ts.map +1 -1
  161. package/dist/core/session-cwd.js +9 -1
  162. package/dist/core/session-cwd.js.map +1 -1
  163. package/dist/core/session-manager.d.ts.map +1 -1
  164. package/dist/core/session-manager.js +45 -36
  165. package/dist/core/session-manager.js.map +1 -1
  166. package/dist/core/settings-defaults.d.ts +1 -1
  167. package/dist/core/settings-defaults.d.ts.map +1 -1
  168. package/dist/core/settings-defaults.js +1 -1
  169. package/dist/core/settings-defaults.js.map +1 -1
  170. package/dist/core/tools/bash.d.ts.map +1 -1
  171. package/dist/core/tools/bash.js +35 -5
  172. package/dist/core/tools/bash.js.map +1 -1
  173. package/dist/core/tools/edit-diff.d.ts +23 -14
  174. package/dist/core/tools/edit-diff.d.ts.map +1 -1
  175. package/dist/core/tools/edit-diff.js +182 -41
  176. package/dist/core/tools/edit-diff.js.map +1 -1
  177. package/dist/core/tools/edit.d.ts.map +1 -1
  178. package/dist/core/tools/edit.js +8 -7
  179. package/dist/core/tools/edit.js.map +1 -1
  180. package/dist/core/tools/find.d.ts.map +1 -1
  181. package/dist/core/tools/find.js +57 -16
  182. package/dist/core/tools/find.js.map +1 -1
  183. package/dist/core/tools/grep.d.ts +4 -0
  184. package/dist/core/tools/grep.d.ts.map +1 -1
  185. package/dist/core/tools/grep.js +20 -8
  186. package/dist/core/tools/grep.js.map +1 -1
  187. package/dist/core/tools/output-accumulator.d.ts.map +1 -1
  188. package/dist/core/tools/output-accumulator.js +4 -1
  189. package/dist/core/tools/output-accumulator.js.map +1 -1
  190. package/dist/core/tools/powershell.d.ts.map +1 -1
  191. package/dist/core/tools/powershell.js +15 -2
  192. package/dist/core/tools/powershell.js.map +1 -1
  193. package/dist/core/tools/read.d.ts +13 -0
  194. package/dist/core/tools/read.d.ts.map +1 -1
  195. package/dist/core/tools/read.js +146 -35
  196. package/dist/core/tools/read.js.map +1 -1
  197. package/dist/core/tools/renderers/read.d.ts.map +1 -1
  198. package/dist/core/tools/renderers/read.js +6 -2
  199. package/dist/core/tools/renderers/read.js.map +1 -1
  200. package/dist/core/tools/truncate.d.ts +4 -0
  201. package/dist/core/tools/truncate.d.ts.map +1 -1
  202. package/dist/core/tools/truncate.js +24 -1
  203. package/dist/core/tools/truncate.js.map +1 -1
  204. package/dist/extensions/codemode/execute.js +4 -4
  205. package/dist/extensions/codemode/execute.js.map +1 -1
  206. package/dist/extensions/codemode/tool.d.ts.map +1 -1
  207. package/dist/extensions/codemode/tool.js +34 -12
  208. package/dist/extensions/codemode/tool.js.map +1 -1
  209. package/dist/extensions/llama/provider.d.ts +1 -1
  210. package/dist/extensions/llama/provider.js +1 -1
  211. package/dist/extensions/llama/provider.js.map +1 -1
  212. package/dist/extensions/llama/ui.d.ts.map +1 -1
  213. package/dist/extensions/llama/ui.js +15 -3
  214. package/dist/extensions/llama/ui.js.map +1 -1
  215. package/dist/extensions/mcp/cli.js +5 -8
  216. package/dist/extensions/mcp/cli.js.map +1 -1
  217. package/dist/extensions/mcp/index.d.ts.map +1 -1
  218. package/dist/extensions/mcp/index.js +2 -1
  219. package/dist/extensions/mcp/index.js.map +1 -1
  220. package/dist/extensions/mcp/runtime.d.ts.map +1 -1
  221. package/dist/extensions/mcp/runtime.js +3 -2
  222. package/dist/extensions/mcp/runtime.js.map +1 -1
  223. package/dist/extensions/tool-search/tool.d.ts.map +1 -1
  224. package/dist/extensions/tool-search/tool.js +18 -6
  225. package/dist/extensions/tool-search/tool.js.map +1 -1
  226. package/dist/main.d.ts.map +1 -1
  227. package/dist/main.js +67 -15
  228. package/dist/main.js.map +1 -1
  229. package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -1
  230. package/dist/modes/interactive/components/login-dialog.js +2 -19
  231. package/dist/modes/interactive/components/login-dialog.js.map +1 -1
  232. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
  233. package/dist/modes/interactive/components/model-selector.js +14 -6
  234. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  235. package/dist/modes/interactive/components/oauth-selector.d.ts +10 -3
  236. package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -1
  237. package/dist/modes/interactive/components/oauth-selector.js +32 -5
  238. package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
  239. package/dist/modes/interactive/components/provider-brand.d.ts +14 -0
  240. package/dist/modes/interactive/components/provider-brand.d.ts.map +1 -0
  241. package/dist/modes/interactive/components/provider-brand.js +66 -0
  242. package/dist/modes/interactive/components/provider-brand.js.map +1 -0
  243. package/dist/modes/interactive/components/radius-login-selector.d.ts +1 -2
  244. package/dist/modes/interactive/components/radius-login-selector.d.ts.map +1 -1
  245. package/dist/modes/interactive/components/radius-login-selector.js +6 -37
  246. package/dist/modes/interactive/components/radius-login-selector.js.map +1 -1
  247. package/dist/modes/interactive/components/session-selector.d.ts +6 -1
  248. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
  249. package/dist/modes/interactive/components/session-selector.js +23 -5
  250. package/dist/modes/interactive/components/session-selector.js.map +1 -1
  251. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  252. package/dist/modes/interactive/components/tool-execution.js +3 -1
  253. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  254. package/dist/modes/interactive/interactive-mode.d.ts +11 -1
  255. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  256. package/dist/modes/interactive/interactive-mode.js +133 -78
  257. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  258. package/dist/modes/interactive/session-share.js +2 -0
  259. package/dist/modes/interactive/session-share.js.map +1 -1
  260. package/dist/package-manager-cli.d.ts.map +1 -1
  261. package/dist/package-manager-cli.js +27 -4
  262. package/dist/package-manager-cli.js.map +1 -1
  263. package/dist/prompts/commands/test-audit.md +84 -0
  264. package/dist/utils/image-resize.d.ts.map +1 -1
  265. package/dist/utils/image-resize.js +3 -1
  266. package/dist/utils/image-resize.js.map +1 -1
  267. package/dist/utils/terminal-question.d.ts +8 -0
  268. package/dist/utils/terminal-question.d.ts.map +1 -0
  269. package/dist/utils/terminal-question.js +24 -0
  270. package/dist/utils/terminal-question.js.map +1 -0
  271. package/dist/utils/web-url.d.ts +12 -0
  272. package/dist/utils/web-url.d.ts.map +1 -0
  273. package/dist/utils/web-url.js +20 -0
  274. package/dist/utils/web-url.js.map +1 -0
  275. package/docs/cli.md +14 -1
  276. package/docs/extensions.md +6 -4
  277. package/docs/llama-cpp.md +5 -5
  278. package/docs/models-configuration.md +2 -1
  279. package/docs/nvidia-rtx-llama-cpp.md +5 -5
  280. package/docs/polyphase.md +13 -1
  281. package/docs/prompt-templates.md +1 -1
  282. package/docs/providers.md +4 -2
  283. package/docs/quickstart.md +1 -1
  284. package/docs/rpc-commands.md +1 -1
  285. package/docs/rpc.md +1 -1
  286. package/docs/sessions.md +7 -1
  287. package/docs/settings.md +1 -1
  288. package/docs/tui.md +1 -1
  289. package/examples/extensions/gondolin/index.ts +4 -7
  290. package/examples/extensions/subagent/index.ts +5 -1
  291. package/package.json +10 -10
  292. package/prompts/commands/test-audit.md +84 -0
  293. package/schemas/models.schema.json +5 -1
  294. package/schemas/settings.schema.json +1 -1
  295. package/dist/bundle/chunks/anthropic-messages-TXQXPH4S.js +0 -6
  296. package/dist/bundle/chunks/chunk-AOCWORXE.js +0 -2
  297. package/dist/bundle/chunks/chunk-DQ4G4IS4.js +0 -20
  298. package/dist/bundle/chunks/chunk-J7QTCDIN.js +0 -2
  299. package/dist/bundle/chunks/chunk-NNYZSIKR.js +0 -9
  300. package/dist/bundle/chunks/chunk-SUVMF4W5.js +0 -2
  301. package/dist/bundle/chunks/chunk-THDNEOXP.js +0 -44
  302. package/dist/bundle/chunks/chunk-TK3LS5QZ.js +0 -82
  303. package/dist/bundle/chunks/chunk-TYAEYYRA.js +0 -30
  304. package/dist/bundle/chunks/google-generative-ai-NC5KHHW3.js +0 -2
  305. package/dist/bundle/chunks/google-vertex-GAPUJEF7.js +0 -2
  306. package/dist/bundle/chunks/virtual-modules-ZUI2T3XR.js +0 -2
@@ -1,15 +1,28 @@
1
+ import { win32 } from "node:path";
1
2
  import { getPowerShellConfig } from "../../utils/shell.js";
2
3
  import { createLocalShellOperations, createShellToolDefinition, } from "./bash.js";
3
4
  import { wrapToolDefinition } from "./tool-definition-wrapper.js";
4
5
  const UTF8_OUTPUT_PREFIX = "try { [Console]::OutputEncoding=[System.Text.Encoding]::UTF8 } catch {}\n";
6
+ // Windows PowerShell 5.1 turns redirected native stderr into error records and sets $? to false, so
7
+ // `git push 2>&1 | Select-Object -Last 3` exits 1 although git exited 0 (#8842). PowerShell 7 does not.
8
+ // Exit 0 when the last failure is only such a record and the native command exited 0; otherwise keep the
9
+ // -Command rule: 0 when the last statement succeeded, 1 when it failed. The lone `;` keeps an unfinished last
10
+ // statement, such as `Get-ChildItem |`, a parse error instead of continuing into the suffix and running.
11
+ const WINDOWS_POWERSHELL_EXIT_SUFFIX = '\n;\nif ($?) { exit 0 }\nif (($LASTEXITCODE -eq 0) -and ("$($Error[0].FullyQualifiedErrorId)" -like "NativeCommandError*")) { exit 0 }\nexit 1';
5
12
  export const powershellToolSystemPromptContribution = {
6
13
  snippet: "Execute PowerShell commands",
7
14
  guidelines: ["You can inspect DRAHT_* environment variables for current model and session details."],
8
15
  };
9
16
  export function createLocalPowerShellOperations() {
10
- const operations = createLocalShellOperations("PowerShell", getPowerShellConfig);
11
17
  return {
12
- exec: (command, cwd, options) => operations.exec(`${UTF8_OUTPUT_PREFIX}${command}`, cwd, options),
18
+ exec: async (command, cwd, options) => {
19
+ const shellConfig = getPowerShellConfig();
20
+ // A final backtick would continue the user's last line into the suffix, so leave such commands unchanged.
21
+ const suffix = win32.basename(shellConfig.shell).toLowerCase() === "powershell.exe" && !command.endsWith("`")
22
+ ? WINDOWS_POWERSHELL_EXIT_SUFFIX
23
+ : "";
24
+ return createLocalShellOperations("PowerShell", () => shellConfig).exec(`${UTF8_OUTPUT_PREFIX}${command}${suffix}`, cwd, options);
25
+ },
13
26
  };
14
27
  }
15
28
  const powershellToolConfig = {
@@ -1 +1 @@
1
- {"version":3,"file":"powershell.js","sourceRoot":"","sources":["../../../src/core/tools/powershell.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AAC3D,OAAO,EAQN,0BAA0B,EAC1B,yBAAyB,GAEzB,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAElE,MAAM,kBAAkB,GAAG,2EAA2E,CAAC;AAEvG,MAAM,CAAC,MAAM,sCAAsC,GAAG;IACrD,OAAO,EAAE,6BAA6B;IACtC,UAAU,EAAE,CAAC,sFAAsF,CAAC;CAC3F,CAAC;AAWX,MAAM,UAAU,+BAA+B;IAC9C,MAAM,UAAU,GAAG,0BAA0B,CAAC,YAAY,EAAE,mBAAmB,CAAC,CAAC;IACjF,OAAO;QACN,IAAI,EAAE,CAAC,OAAO,EAAE,GAAG,EAAE,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,GAAG,kBAAkB,GAAG,OAAO,EAAE,EAAE,GAAG,EAAE,OAAO,CAAC;KACjG,CAAC;AACH,CAAC;AAED,MAAM,oBAAoB,GAAoB;IAC7C,IAAI,EAAE,YAAY;IAClB,KAAK,EAAE,YAAY;IACnB,SAAS,EAAE,YAAY;IACvB,MAAM,EAAE,KAAK;IACb,aAAa,EAAE,sCAAsC,CAAC,OAAO;IAC7D,gBAAgB,EAAE,sCAAsC,CAAC,UAAU;IACnE,cAAc,EAAE,eAAe;CAC/B,CAAC;AAEF,MAAM,UAAU,8BAA8B,CAC7C,GAAW,EACX,OAA+B;IAE/B,OAAO,yBAAyB,CAAC,GAAG,EAAE,oBAAoB,EAAE;QAC3D,GAAG,OAAO;QACV,UAAU,EAAE,OAAO,EAAE,UAAU,IAAI,+BAA+B,EAAE;KACpE,CAAC,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,oBAAoB,CAAC,GAAW,EAAE,OAA+B;IAChF,MAAM,UAAU,GAAG,8BAA8B,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;IAChE,MAAM,IAAI,GAAG,kBAAkB,CAAC,UAAU,CAAC,CAAC;IAC5C,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE;QACnB,aAAa,EAAE,UAAU,CAAC,aAAa;QACvC,gBAAgB,EAAE,UAAU,CAAC,gBAAgB;KAC7C,CAAC,CAAC;IACH,OAAO,IAAI,CAAC;AACb,CAAC","sourcesContent":["import { getPowerShellConfig } from \"../../utils/shell.ts\";\nimport {\n\ttype BashOperations,\n\ttype BashSpawnContext,\n\ttype BashSpawnHook,\n\ttype BashToolDetails,\n\ttype BashToolInput,\n\ttype BashToolOptions,\n\ttype createBashTool,\n\tcreateLocalShellOperations,\n\tcreateShellToolDefinition,\n\ttype ShellToolConfig,\n} from \"./bash.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\n\nconst UTF8_OUTPUT_PREFIX = \"try { [Console]::OutputEncoding=[System.Text.Encoding]::UTF8 } catch {}\\n\";\n\nexport const powershellToolSystemPromptContribution = {\n\tsnippet: \"Execute PowerShell commands\",\n\tguidelines: [\"You can inspect DRAHT_* environment variables for current model and session details.\"],\n} as const;\n\nexport type PowerShellOperations = BashOperations;\nexport type PowerShellSpawnContext = BashSpawnContext;\nexport type PowerShellSpawnHook = BashSpawnHook;\nexport type PowerShellToolDetails = BashToolDetails;\nexport type PowerShellToolInput = BashToolInput;\n\nexport interface PowerShellToolOptions\n\textends Pick<BashToolOptions, \"operations\" | \"exposeSessionEnvironment\" | \"spawnHook\"> {}\n\nexport function createLocalPowerShellOperations(): PowerShellOperations {\n\tconst operations = createLocalShellOperations(\"PowerShell\", getPowerShellConfig);\n\treturn {\n\t\texec: (command, cwd, options) => operations.exec(`${UTF8_OUTPUT_PREFIX}${command}`, cwd, options),\n\t};\n}\n\nconst powershellToolConfig: ShellToolConfig = {\n\tname: \"powershell\",\n\tlabel: \"powershell\",\n\tshellName: \"PowerShell\",\n\tprompt: \"PS>\",\n\tpromptSnippet: powershellToolSystemPromptContribution.snippet,\n\tpromptGuidelines: powershellToolSystemPromptContribution.guidelines,\n\ttempFilePrefix: \"pi-powershell\",\n};\n\nexport function createPowerShellToolDefinition(\n\tcwd: string,\n\toptions?: PowerShellToolOptions,\n): ReturnType<typeof createShellToolDefinition> {\n\treturn createShellToolDefinition(cwd, powershellToolConfig, {\n\t\t...options,\n\t\toperations: options?.operations ?? createLocalPowerShellOperations(),\n\t});\n}\n\nexport function createPowerShellTool(cwd: string, options?: PowerShellToolOptions): ReturnType<typeof createBashTool> {\n\tconst definition = createPowerShellToolDefinition(cwd, options);\n\tconst tool = wrapToolDefinition(definition);\n\tObject.assign(tool, {\n\t\tpromptSnippet: definition.promptSnippet,\n\t\tpromptGuidelines: definition.promptGuidelines,\n\t});\n\treturn tool;\n}\n"]}
1
+ {"version":3,"file":"powershell.js","sourceRoot":"","sources":["../../../src/core/tools/powershell.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,WAAW,CAAC;AAClC,OAAO,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AAC3D,OAAO,EAQN,0BAA0B,EAC1B,yBAAyB,GAEzB,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAElE,MAAM,kBAAkB,GAAG,2EAA2E,CAAC;AAEvG,oGAAoG;AACpG,wGAAwG;AACxG,yGAAyG;AACzG,8G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,oBAAoB,CAAC,GAAW,EAAE,OAA+B;IAChF,MAAM,UAAU,GAAG,8BAA8B,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;IAChE,MAAM,IAAI,GAAG,kBAAkB,CAAC,UAAU,CAAC,CAAC;IAC5C,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE;QACnB,aAAa,EAAE,UAAU,CAAC,aAAa;QACvC,gBAAgB,EAAE,UAAU,CAAC,gBAAgB;KAC7C,CAAC,CAAC;IACH,OAAO,IAAI,CAAC;AACb,CAAC","sourcesContent":["import { win32 } from \"node:path\";\nimport { getPowerShellConfig } from \"../../utils/shell.ts\";\nimport {\n\ttype BashOperations,\n\ttype BashSpawnContext,\n\ttype BashSpawnHook,\n\ttype BashToolDetails,\n\ttype BashToolInput,\n\ttype BashToolOptions,\n\ttype createBashTool,\n\tcreateLocalShellOperations,\n\tcreateShellToolDefinition,\n\ttype ShellToolConfig,\n} from \"./bash.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\n\nconst UTF8_OUTPUT_PREFIX = \"try { [Console]::OutputEncoding=[System.Text.Encoding]::UTF8 } catch {}\\n\";\n\n// Windows PowerShell 5.1 turns redirected native stderr into error records and sets $? to false, so\n// `git push 2>&1 | Select-Object -Last 3` exits 1 although git exited 0 (#8842). PowerShell 7 does not.\n// Exit 0 when the last failure is only such a record and the native command exited 0; otherwise keep the\n// -Command rule: 0 when the last statement succeeded, 1 when it failed. The lone `;` keeps an unfinished last\n// statement, such as `Get-ChildItem |`, a parse error instead of continuing into the suffix and running.\nconst WINDOWS_POWERSHELL_EXIT_SUFFIX =\n\t'\\n;\\nif ($?) { exit 0 }\\nif (($LASTEXITCODE -eq 0) -and (\"$($Error[0].FullyQualifiedErrorId)\" -like \"NativeCommandError*\")) { exit 0 }\\nexit 1';\n\nexport const powershellToolSystemPromptContribution = {\n\tsnippet: \"Execute PowerShell commands\",\n\tguidelines: [\"You can inspect DRAHT_* environment variables for current model and session details.\"],\n} as const;\n\nexport type PowerShellOperations = BashOperations;\nexport type PowerShellSpawnContext = BashSpawnContext;\nexport type PowerShellSpawnHook = BashSpawnHook;\nexport type PowerShellToolDetails = BashToolDetails;\nexport type PowerShellToolInput = BashToolInput;\n\nexport interface PowerShellToolOptions\n\textends Pick<BashToolOptions, \"operations\" | \"exposeSessionEnvironment\" | \"spawnHook\"> {}\n\nexport function createLocalPowerShellOperations(): PowerShellOperations {\n\treturn {\n\t\texec: async (command, cwd, options) => {\n\t\t\tconst shellConfig = getPowerShellConfig();\n\t\t\t// A final backtick would continue the user's last line into the suffix, so leave such commands unchanged.\n\t\t\tconst suffix =\n\t\t\t\twin32.basename(shellConfig.shell).toLowerCase() === \"powershell.exe\" && !command.endsWith(\"`\")\n\t\t\t\t\t? WINDOWS_POWERSHELL_EXIT_SUFFIX\n\t\t\t\t\t: \"\";\n\t\t\treturn createLocalShellOperations(\"PowerShell\", () => shellConfig).exec(\n\t\t\t\t`${UTF8_OUTPUT_PREFIX}${command}${suffix}`,\n\t\t\t\tcwd,\n\t\t\t\toptions,\n\t\t\t);\n\t\t},\n\t};\n}\n\nconst powershellToolConfig: ShellToolConfig = {\n\tname: \"powershell\",\n\tlabel: \"powershell\",\n\tshellName: \"PowerShell\",\n\tprompt: \"PS>\",\n\tpromptSnippet: powershellToolSystemPromptContribution.snippet,\n\tpromptGuidelines: powershellToolSystemPromptContribution.guidelines,\n\ttempFilePrefix: \"pi-powershell\",\n};\n\nexport function createPowerShellToolDefinition(\n\tcwd: string,\n\toptions?: PowerShellToolOptions,\n): ReturnType<typeof createShellToolDefinition> {\n\treturn createShellToolDefinition(cwd, powershellToolConfig, {\n\t\t...options,\n\t\toperations: options?.operations ?? createLocalPowerShellOperations(),\n\t});\n}\n\nexport function createPowerShellTool(cwd: string, options?: PowerShellToolOptions): ReturnType<typeof createBashTool> {\n\tconst definition = createPowerShellToolDefinition(cwd, options);\n\tconst tool = wrapToolDefinition(definition);\n\tObject.assign(tool, {\n\t\tpromptSnippet: definition.promptSnippet,\n\t\tpromptGuidelines: definition.promptGuidelines,\n\t});\n\treturn tool;\n}\n"]}
@@ -28,6 +28,11 @@ declare const readOutputSchema: Type.TUnion<[Type.TString, Type.TObject<{
28
28
  export type ReadToolOutput = Static<typeof readOutputSchema>;
29
29
  export interface ReadToolDetails {
30
30
  truncation?: TruncationResult;
31
+ /**
32
+ * Id of the model that was selected when the image was read, if it has no image input. Shown to the user only:
33
+ * the model gets @draht/ai's placeholder per request, so the stored result stays right after a model switch.
34
+ */
35
+ imageUnsupportedByModel?: string;
31
36
  }
32
37
  /**
33
38
  * Pluggable operations for the read tool.
@@ -40,6 +45,14 @@ export interface ReadOperations {
40
45
  access: (absolutePath: string) => Promise<void>;
41
46
  /** Detect image MIME type, return null or undefined for non-images */
42
47
  detectImageMimeType?: (absolutePath: string) => Promise<string | null | undefined>;
48
+ /**
49
+ * Stream file contents in chunks. When present, text files are read through it and only the lines
50
+ * that will be shown are kept in memory; otherwise readFile loads the whole file. Stop reading when
51
+ * the signal aborts; the read tool also stops consuming the stream then.
52
+ */
53
+ createReadStream?: (absolutePath: string, options: {
54
+ signal?: AbortSignal;
55
+ }) => AsyncIterable<Uint8Array>;
43
56
  }
44
57
  export interface ReadToolOptions {
45
58
  /** Whether to auto-resize images. Default: true */
@@ -1 +1 @@
1
- {"version":3,"file":"read.d.ts","sourceRoot":"","sources":["../../../src/core/tools/read.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAA4B,uBAAuB,EAAe,MAAM,WAAW,CAAC;AAGhG,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAG5C,OAAO,KAAK,EAAoB,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAG/E,OAAO,EAAE,KAAK,gBAAgB,EAAsB,MAAM,8BAA8B,CAAC;AACzF,OAAO,EAAoD,KAAK,gBAAgB,EAAgB,MAAM,eAAe,CAAC;AAEtH,QAAA,MAAM,UAAU;;;;EAId,CAAC;AAE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W,CAAA;KAAE,KAAK,aAAa,CAAC,UAAU,CAAC,CAAC;CAC1G;AA4BD,MAAM,WAAW,eAAe;IAC/B,mDAAmD;IACnD,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B,gFAAgF;IAChF,aAAa,CAAC,EAAE,uBAAuB,CAAC;IACxC,oEAAoE;IACpE,UAAU,CAAC,EAAE,cAAc,CAAC;CAC5B;AAgID,wBAAgB,wBAAwB,CACvC,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE,eAAe,GACvB,cAAc,CAAC,OAAO,UAAU,EAAE,eAAe,GAAG,SAAS,CAAC,CA2IhE;AAED,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,eAAe,GAAG,gBAAgB,CAAC,OAAO,UAAU,CAAC,CAE1G"}
@@ -1,6 +1,7 @@
1
1
  import { constants } from "fs";
2
- import { access as fsAccess, readFile as fsReadFile } from "fs/promises";
2
+ import { access as fsAccess, open as fsOpen, readFile as fsReadFile } from "fs/promises";
3
3
  import { Type } from "typebox";
4
+ import { TextDecoder } from "util";
4
5
  import { processImage } from "../../utils/image-process.js";
5
6
  import { detectSupportedImageMimeTypeFromFile } from "../../utils/mime.js";
6
7
  import { resolveReadPathAsync } from "./path-utils.js";
@@ -28,20 +29,143 @@ const readOutputSchema = Type.Union([
28
29
  ]);
29
30
  const defaultReadOperations = {
30
31
  readFile: (path) => fsReadFile(path),
32
+ createReadStream: readLocalFileChunks,
31
33
  access: (path) => fsAccess(path, constants.R_OK),
32
34
  detectImageMimeType: detectSupportedImageMimeTypeFromFile,
33
35
  };
36
+ /**
37
+ * Stream a local file the way fs.readFile reads it: a regular file up to its size when opened, so text
38
+ * appended during the read is not counted and a growing file still ends; a file reporting size 0 (such
39
+ * as /proc files) and other file types until EOF. Abort is left to the read tool, which stops consuming
40
+ * the stream when its signal aborts; leaving its loop closes the stream.
41
+ */
42
+ async function* readLocalFileChunks(path) {
43
+ const handle = await fsOpen(path, "r");
44
+ try {
45
+ const stats = await handle.stat();
46
+ const end = stats.isFile() && stats.size > 0 ? stats.size - 1 : undefined;
47
+ // No signal for the stream: one that aborts before the stream's iterator attaches makes the stream
48
+ // emit an 'error' no listener handles, which crashes the process (#11956).
49
+ yield* handle.createReadStream({ end, autoClose: false });
50
+ }
51
+ finally {
52
+ await handle.close();
53
+ }
54
+ }
34
55
  /** The image block and its note, or the text for text files and images that could not be processed. */
35
56
  function toReadOutput(content) {
36
57
  const text = content.find((block) => block.type === "text")?.text ?? "";
37
58
  const image = content.find((block) => block.type === "image");
38
59
  return image ? { type: "image", data: image.data, mimeType: image.mimeType, note: text } : text;
39
60
  }
40
- function getNonVisionImageNote(model) {
41
- if (!model || model.input.includes("image")) {
42
- return undefined;
61
+ /**
62
+ * Whether a range can be streamed. Other values (fractional, negative limit) keep the whole-file path,
63
+ * whose array slicing defines what they select, for example limit -1 as all lines but the last.
64
+ */
65
+ function isStreamableRange(offset, limit) {
66
+ return ((offset === undefined || Number.isInteger(offset)) &&
67
+ (limit === undefined || (Number.isInteger(limit) && limit >= 0)));
68
+ }
69
+ /** Select lines from a whole file in memory: for operations without createReadStream and unusual ranges. */
70
+ function selectLinesFromBuffer(buffer, startLine, limit) {
71
+ const allLines = buffer.toString("utf-8").split("\n");
72
+ const endLine = limit === undefined ? undefined : Math.min(startLine + limit, allLines.length);
73
+ const truncation = truncateHead(allLines.slice(startLine, endLine).join("\n"));
74
+ const firstLineBytes = truncation.firstLineExceedsLimit ? Buffer.byteLength(allLines[startLine], "utf-8") : 0;
75
+ return { totalFileLines: allLines.length, truncation, firstLineBytes };
76
+ }
77
+ /**
78
+ * Select lines from a file read in chunks. Only lines truncateHead can show are stored; the rest are
79
+ * counted, so memory does not grow with the file. Stops reading when the signal aborts.
80
+ */
81
+ async function selectLinesFromStream(chunks, startLine, limit, signal) {
82
+ const endLine = limit === undefined ? Number.POSITIVE_INFINITY : startLine + limit;
83
+ // Non-fatal UTF-8 that keeps a byte order mark decodes like Buffer.toString("utf-8").
84
+ const decoder = new TextDecoder("utf-8", { ignoreBOM: true });
85
+ const storedLines = [];
86
+ let storedBytes = 0;
87
+ let storedPastCaps = false;
88
+ let line = 0;
89
+ let selectedLines = 0;
90
+ let selectedBytes = 0;
91
+ let firstLineBytes = 0;
92
+ let lastLineEmpty = true;
93
+ // The selected line being read: its text, while it is stored, and its size.
94
+ let pieces = [];
95
+ let lineBytes = 0;
96
+ let lineHasText = false;
97
+ const appendToLine = (text, start, end) => {
98
+ lineHasText = true;
99
+ if (!pieces)
100
+ return;
101
+ const piece = text.slice(start, end);
102
+ // A line over the byte cap is never shown, and a first line over it is only measured: never store
103
+ // all of a 1 GB line.
104
+ if (lineBytes <= DEFAULT_MAX_BYTES)
105
+ pieces.push(piece);
106
+ lineBytes += Buffer.byteLength(piece, "utf-8");
107
+ };
108
+ const finishLine = () => {
109
+ if (pieces) {
110
+ if (selectedLines === 0)
111
+ firstLineBytes = lineBytes;
112
+ // Storing continues one line past the caps: truncateHead ignores a trailing empty line, so the
113
+ // line after the cap must be there for it to decide truncation as for the full text.
114
+ if (storedLines.length > DEFAULT_MAX_LINES || storedBytes > DEFAULT_MAX_BYTES)
115
+ storedPastCaps = true;
116
+ const text = pieces.join("");
117
+ storedBytes += Buffer.byteLength(text, "utf-8") + (storedLines.length > 0 ? 1 : 0);
118
+ storedLines.push(text);
119
+ }
120
+ selectedLines++;
121
+ lastLineEmpty = !lineHasText;
122
+ pieces = storedPastCaps ? undefined : [];
123
+ lineBytes = 0;
124
+ lineHasText = false;
125
+ };
126
+ const select = (text) => {
127
+ let position = 0;
128
+ // Start of the selected text in this piece, measured as a whole: the joined lines' size.
129
+ let selectionStart = -1;
130
+ while (true) {
131
+ const selected = line >= startLine && line < endLine;
132
+ if (selected && selectionStart === -1)
133
+ selectionStart = position;
134
+ const newline = text.indexOf("\n", position);
135
+ const end = newline === -1 ? text.length : newline;
136
+ if (selected && end > position)
137
+ appendToLine(text, position, end);
138
+ if (newline === -1)
139
+ break;
140
+ if (selected) {
141
+ finishLine();
142
+ if (line + 1 === endLine) {
143
+ selectedBytes += Buffer.byteLength(text.slice(selectionStart, newline), "utf-8");
144
+ selectionStart = -1;
145
+ }
146
+ }
147
+ line++;
148
+ position = newline + 1;
149
+ }
150
+ if (selectionStart !== -1)
151
+ selectedBytes += Buffer.byteLength(text.slice(selectionStart), "utf-8");
152
+ };
153
+ for await (const chunk of chunks) {
154
+ // Leaving the loop closes the stream.
155
+ if (signal?.aborted)
156
+ throw new Error("Operation aborted");
157
+ select(decoder.decode(chunk, { stream: true }));
43
158
  }
44
- return "[Current model does not support images. The image will be omitted from this request.]";
159
+ select(decoder.decode());
160
+ if (line >= startLine && line < endLine)
161
+ finishLine();
162
+ const truncation = {
163
+ ...truncateHead(storedLines.join("\n")),
164
+ // truncateHead's counts for the joined selected lines, which drop a trailing empty line.
165
+ totalLines: selectedBytes === 0 ? 0 : selectedLines - (lastLineEmpty ? 1 : 0),
166
+ totalBytes: selectedBytes,
167
+ };
168
+ return { totalFileLines: line + 1, truncation, firstLineBytes };
45
169
  }
46
170
  export function createReadToolDefinition(cwd, options) {
47
171
  const autoResizeImages = options?.autoResizeImages ?? true;
@@ -93,7 +217,6 @@ export function createReadToolDefinition(cwd, options) {
93
217
  const mimeType = ops.detectImageMimeType ? await ops.detectImageMimeType(absolutePath) : undefined;
94
218
  let content;
95
219
  let details;
96
- const nonVisionImageNote = getNonVisionImageNote(ctx?.model);
97
220
  if (mimeType) {
98
221
  // Read image as binary.
99
222
  const buffer = await ops.readFile(absolutePath);
@@ -102,53 +225,41 @@ export function createReadToolDefinition(cwd, options) {
102
225
  resizeOptions: ctx?.model?.inputLimits?.images?.resize ?? fallbackResizeOptions,
103
226
  });
104
227
  if (!processed.ok) {
105
- let textNote = `Read image file [${mimeType}]\n${processed.message}`;
106
- if (nonVisionImageNote)
107
- textNote += `\n${nonVisionImageNote}`;
228
+ const textNote = `Read image file [${mimeType}]\n${processed.message}`;
108
229
  content = [{ type: "text", text: textNote }];
109
230
  }
110
231
  else {
111
232
  let textNote = `Read image file [${processed.mimeType}]`;
112
233
  if (processed.hints.length > 0)
113
234
  textNote += `\n${processed.hints.join("\n")}`;
114
- if (nonVisionImageNote)
115
- textNote += `\n${nonVisionImageNote}`;
116
235
  content = [
117
236
  { type: "text", text: textNote },
118
237
  { type: "image", data: processed.data, mimeType: processed.mimeType },
119
238
  ];
239
+ if (ctx?.model && !ctx.model.input.includes("image")) {
240
+ details = { imageUnsupportedByModel: ctx.model.id };
241
+ }
120
242
  }
121
243
  }
122
244
  else {
123
- // Read text content.
124
- const buffer = await ops.readFile(absolutePath);
125
- const textContent = buffer.toString("utf-8");
126
- const allLines = textContent.split("\n");
127
- const totalFileLines = allLines.length;
128
- // Apply offset if specified. Convert from 1-indexed input to 0-indexed array access.
245
+ // Read text content. Convert offset from 1-indexed input to 0-indexed line access.
129
246
  const startLine = offset ? Math.max(0, offset - 1) : 0;
130
247
  const startLineDisplay = startLine + 1;
248
+ const { totalFileLines, truncation, firstLineBytes } = ops.createReadStream && isStreamableRange(offset, limit)
249
+ ? await selectLinesFromStream(ops.createReadStream(absolutePath, { signal }), startLine, limit, signal)
250
+ : selectLinesFromBuffer(await ops.readFile(absolutePath), startLine, limit);
251
+ if (aborted)
252
+ return;
131
253
  // Check if offset is out of bounds.
132
- if (startLine >= allLines.length) {
133
- throw new Error(`Offset ${offset} is beyond end of file (${allLines.length} lines total)`);
134
- }
135
- let selectedContent;
136
- let userLimitedLines;
137
- // If limit is specified by the user, honor it first. Otherwise truncateHead decides.
138
- if (limit !== undefined) {
139
- const endLine = Math.min(startLine + limit, allLines.length);
140
- selectedContent = allLines.slice(startLine, endLine).join("\n");
141
- userLimitedLines = endLine - startLine;
142
- }
143
- else {
144
- selectedContent = allLines.slice(startLine).join("\n");
254
+ if (startLine >= totalFileLines) {
255
+ throw new Error(`Offset ${offset} is beyond end of file (${totalFileLines} lines total)`);
145
256
  }
146
- // Apply truncation, respecting both line and byte limits.
147
- const truncation = truncateHead(selectedContent);
257
+ // A user-specified limit is honored before truncation.
258
+ const userLimitedLines = limit === undefined ? undefined : Math.min(startLine + limit, totalFileLines) - startLine;
148
259
  let outputText;
149
260
  if (truncation.firstLineExceedsLimit) {
150
261
  // First line alone exceeds the byte limit. Point the model at a bash fallback.
151
- const firstLineSize = formatSize(Buffer.byteLength(allLines[startLine], "utf-8"));
262
+ const firstLineSize = formatSize(firstLineBytes);
152
263
  outputText = `[Line ${startLineDisplay} is ${firstLineSize}, exceeds ${formatSize(DEFAULT_MAX_BYTES)} limit. Use bash: sed -n '${startLineDisplay}p' ${path} | head -c ${DEFAULT_MAX_BYTES}]`;
153
264
  details = { truncation };
154
265
  }
@@ -165,9 +276,9 @@ export function createReadToolDefinition(cwd, options) {
165
276
  }
166
277
  details = { truncation };
167
278
  }
168
- else if (userLimitedLines !== undefined && startLine + userLimitedLines < allLines.length) {
279
+ else if (userLimitedLines !== undefined && startLine + userLimitedLines < totalFileLines) {
169
280
  // User-specified limit stopped early, but the file still has more content.
170
- const remaining = allLines.length - (startLine + userLimitedLines);
281
+ const remaining = totalFileLines - (startLine + userLimitedLines);
171
282
  const nextOffset = startLine + userLimitedLines + 1;
172
283
  outputText = `${truncation.content}\n\n[${remaining} more lines in file. Use offset=${nextOffset} to continue.]`;
173
284
  }
@@ -1 +1 @@
1
- {"version":3,"file":"read.js","sourceRoot":"","sources":["../../../src/core/tools/read.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,MAAM,IAAI,CAAC;AAC/B,OAAO,EAAE,MAAM,IAAI,QAAQ,EAAE,QAAQ,IAAI,UAAU,EAAE,MAAM,aAAa,CAAC;AACzE,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AAC5D,OAAO,EAAE,oCAAoC,EAAE,MAAM,qBAAqB,CAAC;AAE3E,OAAO,EAAE,oBAAoB,EAAE,MAAM,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CAAC,GAAW,EAAE,OAAyB;IACpE,OAAO,kBAAkB,CAAC,wBAAwB,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC,CAAC;AACnE,CAAC","sourcesContent":["import type { Api, ImageContent, Model, ModelImageResizeOptions, TextContent } from \"@draht/ai\";\nimport { constants } from \"fs\";\nimport { access as fsAccess, readFile as fsReadFile } from \"fs/promises\";\nimport { type Static, Type } from \"typebox\";\nimport { processImage } from \"../../utils/image-process.ts\";\nimport { detectSupportedImageMimeTypeFromFile } from \"../../utils/mime.ts\";\nimport type { ExtensionContext, ToolDefinition } from \"../extensions/types.ts\";\nimport { resolveReadPathAsync } from \"./path-utils.ts\";\nimport { readRenderers } from \"./renderers/read.ts\";\nimport { type TypeBoxAgentTool, wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\nimport { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, type TruncationResult, truncateHead } from \"./truncate.ts\";\n\nconst readSchema = Type.Object({\n\tpath: Type.String({ description: \"Path to the file to read (relative or absolute)\" }),\n\toffset: Type.Optional(Type.Number({ description: \"Line number to start reading from (1-indexed)\" })),\n\tlimit: Type.Optional(Type.Number({ description: \"Maximum number of lines to read\" })),\n});\n\nexport const readToolSystemPromptContribution = {\n\tsnippet: \"Read file contents\",\n\tguidelines: [\"Use read to examine files instead of cat or sed.\"],\n} as const;\n\nexport type ReadToolInput = Static<typeof readSchema>;\n\n/**\n * Result for programmatic callers such as codemode scripts: the text for text files, and an image\n * block for images that codemode's `image()` accepts. `note` is the text that goes with the image,\n * such as resize hints. Property descriptions are left out so the type stays on one line in tool\n * descriptions.\n */\nconst readOutputSchema = Type.Union([\n\tType.String(),\n\tType.Object({ type: Type.Literal(\"image\"), data: Type.String(), mimeType: Type.String(), note: Type.String() }),\n]);\n\nexport type ReadToolOutput = Static<typeof readOutputSchema>;\n\nexport interface ReadToolDetails {\n\ttruncation?: TruncationResult;\n}\n\n/**\n * Pluggable operations for the read tool.\n * Override these to delegate file reading to remote systems (for example SSH).\n */\nexport interface ReadOperations {\n\t/** Read file contents as a Buffer */\n\treadFile: (absolutePath: string) => Promise<Buffer>;\n\t/** Check if file is readable (throw if not) */\n\taccess: (absolutePath: string) => Promise<void>;\n\t/** Detect image MIME type, return null or undefined for non-images */\n\tdetectImageMimeType?: (absolutePath: string) => Promise<string | null | undefined>;\n}\n\nconst defaultReadOperations: ReadOperations = {\n\treadFile: (path) => fsReadFile(path),\n\taccess: (path) => fsAccess(path, constants.R_OK),\n\tdetectImageMimeType: detectSupportedImageMimeTypeFromFile,\n};\n\nexport interface ReadToolOptions {\n\t/** Whether to auto-resize images. Default: true */\n\tautoResizeImages?: boolean;\n\t/** Fallback resize profile when the execution context has no model metadata. */\n\tresizeOptions?: ModelImageResizeOptions;\n\t/** Custom operations for file reading. Default: local filesystem */\n\toperations?: ReadOperations;\n}\n\n/** The image block and its note, or the text for text files and images that could not be processed. */\nfunction toReadOutput(content: (TextContent | ImageContent)[]): ReadToolOutput {\n\tconst text = content.find((block) => block.type === \"text\")?.text ?? \"\";\n\tconst image = content.find((block) => block.type === \"image\");\n\treturn image ? { type: \"image\", data: image.data, mimeType: image.mimeType, note: text } : text;\n}\n\nfunction getNonVisionImageNote(model: Model<Api> | undefined): string | undefined {\n\tif (!model || model.input.includes(\"image\")) {\n\t\treturn undefined;\n\t}\n\treturn \"[Current model does not support images. The image will be omitted from this request.]\";\n}\n\nexport function createReadToolDefinition(\n\tcwd: string,\n\toptions?: ReadToolOptions,\n): ToolDefinition<typeof readSchema, ReadToolDetails | undefined> {\n\tconst autoResizeImages = options?.autoResizeImages ?? true;\n\tconst fallbackResizeOptions = options?.resizeOptions;\n\tconst ops = options?.operations ?? defaultReadOperations;\n\t// Remote or confined backends own normalization probes as well as content\n\t// reads. Probing the local host first can leak or select unrelated files.\n\tconst exists = options?.operations\n\t\t? async (path: string) => {\n\t\t\t\ttry {\n\t\t\t\t\tawait ops.access(path);\n\t\t\t\t\treturn true;\n\t\t\t\t} catch {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t: undefined;\n\treturn {\n\t\tname: \"read\",\n\t\tlabel: \"read\",\n\t\tdescription: `Read the contents of a file. Supports text files and images (jpg, png, gif, webp, bmp). Images are sent as attachments. For text files, output is truncated to ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). Use offset/limit for large files. When you need the full file, continue with offset until complete.`,\n\t\tpromptSnippet: readToolSystemPromptContribution.snippet,\n\t\tpromptGuidelines: [...readToolSystemPromptContribution.guidelines],\n\t\tparameters: readSchema,\n\t\toutputSchema: readOutputSchema,\n\t\tconstrainedSampling: { type: \"json_schema\", strict: \"prefer\" },\n\t\tasync execute(\n\t\t\t_toolCallId,\n\t\t\t{ path, offset, limit }: { path: string; offset?: number; limit?: number },\n\t\t\tsignal?: AbortSignal,\n\t\t\t_onUpdate?,\n\t\t\tctx?: ExtensionContext,\n\t\t) {\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\n\t\t\t\t\t(async () => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst absolutePath = await resolveReadPathAsync(path, ctx?.cwd || cwd, exists);\n\t\t\t\t\t\t\tif (aborted) return;\n\t\t\t\t\t\t\t// Check if file exists and is readable.\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\tconst mimeType = ops.detectImageMimeType ? await ops.detectImageMimeType(absolutePath) : undefined;\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\tconst nonVisionImageNote = getNonVisionImageNote(ctx?.model);\n\t\t\t\t\t\t\tif (mimeType) {\n\t\t\t\t\t\t\t\t// Read image as binary.\n\t\t\t\t\t\t\t\tconst buffer = await ops.readFile(absolutePath);\n\t\t\t\t\t\t\t\tconst processed = await processImage(buffer, mimeType, {\n\t\t\t\t\t\t\t\t\tautoResizeImages,\n\t\t\t\t\t\t\t\t\tresizeOptions: ctx?.model?.inputLimits?.images?.resize ?? fallbackResizeOptions,\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tif (!processed.ok) {\n\t\t\t\t\t\t\t\t\tlet textNote = `Read image file [${mimeType}]\\n${processed.message}`;\n\t\t\t\t\t\t\t\t\tif (nonVisionImageNote) textNote += `\\n${nonVisionImageNote}`;\n\t\t\t\t\t\t\t\t\tcontent = [{ type: \"text\", text: textNote }];\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tlet textNote = `Read image file [${processed.mimeType}]`;\n\t\t\t\t\t\t\t\t\tif (processed.hints.length > 0) textNote += `\\n${processed.hints.join(\"\\n\")}`;\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: processed.data, mimeType: processed.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\t// Read text content.\n\t\t\t\t\t\t\t\tconst buffer = await ops.readFile(absolutePath);\n\t\t\t\t\t\t\t\tconst textContent = buffer.toString(\"utf-8\");\n\t\t\t\t\t\t\t\tconst allLines = textContent.split(\"\\n\");\n\t\t\t\t\t\t\t\tconst totalFileLines = allLines.length;\n\t\t\t\t\t\t\t\t// Apply offset if specified. Convert from 1-indexed input to 0-indexed array access.\n\t\t\t\t\t\t\t\tconst startLine = offset ? Math.max(0, offset - 1) : 0;\n\t\t\t\t\t\t\t\tconst startLineDisplay = startLine + 1;\n\t\t\t\t\t\t\t\t// Check if offset is out of bounds.\n\t\t\t\t\t\t\t\tif (startLine >= allLines.length) {\n\t\t\t\t\t\t\t\t\tthrow new Error(`Offset ${offset} is beyond end of file (${allLines.length} lines total)`);\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 userLimitedLines: number | undefined;\n\t\t\t\t\t\t\t\t// If limit is specified by the user, honor it first. Otherwise truncateHead decides.\n\t\t\t\t\t\t\t\tif (limit !== undefined) {\n\t\t\t\t\t\t\t\t\tconst endLine = Math.min(startLine + limit, allLines.length);\n\t\t\t\t\t\t\t\t\tselectedContent = allLines.slice(startLine, endLine).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\tselectedContent = allLines.slice(startLine).join(\"\\n\");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t// Apply truncation, respecting both line and byte limits.\n\t\t\t\t\t\t\t\tconst truncation = truncateHead(selectedContent);\n\t\t\t\t\t\t\t\tlet outputText: string;\n\t\t\t\t\t\t\t\tif (truncation.firstLineExceedsLimit) {\n\t\t\t\t\t\t\t\t\t// First line alone exceeds the byte limit. Point the model at a bash fallback.\n\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\toutputText = `[Line ${startLineDisplay} is ${firstLineSize}, exceeds ${formatSize(DEFAULT_MAX_BYTES)} limit. Use bash: sed -n '${startLineDisplay}p' ${path} | head -c ${DEFAULT_MAX_BYTES}]`;\n\t\t\t\t\t\t\t\t\tdetails = { truncation };\n\t\t\t\t\t\t\t\t} else if (truncation.truncated) {\n\t\t\t\t\t\t\t\t\t// Truncation occurred. Build an actionable continuation notice.\n\t\t\t\t\t\t\t\t\tconst endLineDisplay = startLineDisplay + truncation.outputLines - 1;\n\t\t\t\t\t\t\t\t\tconst nextOffset = endLineDisplay + 1;\n\t\t\t\t\t\t\t\t\toutputText = truncation.content;\n\t\t\t\t\t\t\t\t\tif (truncation.truncatedBy === \"lines\") {\n\t\t\t\t\t\t\t\t\t\toutputText += `\\n\\n[Showing lines ${startLineDisplay}-${endLineDisplay} of ${totalFileLines}. Use offset=${nextOffset} to continue.]`;\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\toutputText += `\\n\\n[Showing lines ${startLineDisplay}-${endLineDisplay} of ${totalFileLines} (${formatSize(DEFAULT_MAX_BYTES)} limit). Use offset=${nextOffset} to continue.]`;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tdetails = { truncation };\n\t\t\t\t\t\t\t\t} else if (userLimitedLines !== undefined && startLine + userLimitedLines < allLines.length) {\n\t\t\t\t\t\t\t\t\t// User-specified limit stopped early, but the file still has more content.\n\t\t\t\t\t\t\t\t\tconst remaining = allLines.length - (startLine + userLimitedLines);\n\t\t\t\t\t\t\t\t\tconst nextOffset = startLine + userLimitedLines + 1;\n\t\t\t\t\t\t\t\t\toutputText = `${truncation.content}\\n\\n[${remaining} more lines in file. Use offset=${nextOffset} to continue.]`;\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t// No truncation and no remaining user-limited content.\n\t\t\t\t\t\t\t\t\toutputText = truncation.content;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcontent = [{ type: \"text\", text: outputText }];\n\t\t\t\t\t\t\t}\n\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\t\tresolve({ content, details });\n\t\t\t\t\t\t} catch (error: any) {\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).then((result) => ({ ...result, structuredContent: toReadOutput(result.content) }));\n\t\t},\n\t\t...readRenderers,\n\t};\n}\n\nexport function createReadTool(cwd: string, options?: ReadToolOptions): TypeBoxAgentTool<typeof readSchema> {\n\treturn wrapToolDefinition(createReadToolDefinition(cwd, options));\n}\n"]}
1
+ {"version":3,"file":"read.js","sourceRoot":"","sources":["../../../src/core/tools/read.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,MAAM,IAAI,CAAC;AAC/B,OAAO,EAAE,MAAM,IAAI,QAAQ,EAAE,IAAI,IAAI,MAAM,EAAE,QAAQ,IAAI,UAAU,EAAE,MAAM,aAAa,CAAC;AACzF,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,EAAE,WAAW,EAAE,MAAM,MAAM,CAAC;AACnC,OAAO,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AAC5D,OAAO,EAAE,oCAAoC,EAAE,MAAM,qBAAqB,CAAC;AAE3E,OAAO,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAC;AACvD,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAyB,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AACzF,OAAO,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,UAAU,EAAyB,YAAY,EAAE,MAAM,eAAe,CAAC;AAEtH,MAAM,UAAU,GAAG,IAAI,CAAC,MAAM,CAAC;IAC9B,IAAI,EAAE,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,iDAAiD,EAAE,CAAC;IACrF,MAAM,EAAE,IAAI,CAAC,QAAQ,CAA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AAG,CAAC,CAAC;gCACpD,UAAU,GAAG,GAAG,UAAU,CAAC,OAAO,QAAQ,SAAS,mCAAmC,UAAU,gBAAgB,CAAC;4BAClH,CAAC;iCAAM,CAAC;gCACP,uDAAuD;gCACvD,UAAU,GAAG,UAAU,CAAC,OAAO,CAAC;4BACjC,CAAC;4BACD,OAAO,GAAG,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,UAAU,EAAE,CAAC,CAAC;wBAChD,CAAC;wBAED,IAAI,OAAO;4BAAE,OAAO;wBACpB,MAAM,EAAE,mBAAmB,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;wBAC9C,OAAO,CAAC,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC,CAAC;oBAC/B,CAAC;oBAAC,OAAO,KAAU,EAAE,CAAC;wBACrB,MAAM,EAAE,mBAAmB,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;wBAC9C,IAAI,CAAC,OAAO;4BAAE,MAAM,CAAC,KAAK,CAAC,CAAC;oBAC7B,CAAC;gBACF,CAAC,CAAC,EAAE,CAAC;YACN,CAAC,CACD,CAAC,IAAI,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,EAAE,GAAG,MAAM,EAAE,iBAAiB,EAAE,YAAY,CAAC,MAAM,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,CAAC;QACtF,CAAC;QACD,GAAG,aAAa;KAChB,CAAC;AACH,CAAC;AAED,MAAM,UAAU,cAAc,CAAC,GAAW,EAAE,OAAyB;IACpE,OAAO,kBAAkB,CAAC,wBAAwB,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC,CAAC;AACnE,CAAC","sourcesContent":["import type { ImageContent, ModelImageResizeOptions, TextContent } from \"@draht/ai\";\nimport { constants } from \"fs\";\nimport { access as fsAccess, open as fsOpen, readFile as fsReadFile } from \"fs/promises\";\nimport { type Static, Type } from \"typebox\";\nimport { TextDecoder } from \"util\";\nimport { processImage } from \"../../utils/image-process.ts\";\nimport { detectSupportedImageMimeTypeFromFile } from \"../../utils/mime.ts\";\nimport type { ExtensionContext, ToolDefinition } from \"../extensions/types.ts\";\nimport { resolveReadPathAsync } from \"./path-utils.ts\";\nimport { readRenderers } from \"./renderers/read.ts\";\nimport { type TypeBoxAgentTool, wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\nimport { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, type TruncationResult, truncateHead } from \"./truncate.ts\";\n\nconst readSchema = Type.Object({\n\tpath: Type.String({ description: \"Path to the file to read (relative or absolute)\" }),\n\toffset: Type.Optional(Type.Number({ description: \"Line number to start reading from (1-indexed)\" })),\n\tlimit: Type.Optional(Type.Number({ description: \"Maximum number of lines to read\" })),\n});\n\nexport const readToolSystemPromptContribution = {\n\tsnippet: \"Read file contents\",\n\tguidelines: [\"Use read to examine files instead of cat or sed.\"],\n} as const;\n\nexport type ReadToolInput = Static<typeof readSchema>;\n\n/**\n * Result for programmatic callers such as codemode scripts: the text for text files, and an image\n * block for images that codemode's `image()` accepts. `note` is the text that goes with the image,\n * such as resize hints. Property descriptions are left out so the type stays on one line in tool\n * descriptions.\n */\nconst readOutputSchema = Type.Union([\n\tType.String(),\n\tType.Object({ type: Type.Literal(\"image\"), data: Type.String(), mimeType: Type.String(), note: Type.String() }),\n]);\n\nexport type ReadToolOutput = Static<typeof readOutputSchema>;\n\nexport interface ReadToolDetails {\n\ttruncation?: TruncationResult;\n\t/**\n\t * Id of the model that was selected when the image was read, if it has no image input. Shown to the user only:\n\t * the model gets @draht/ai's placeholder per request, so the stored result stays right after a model switch.\n\t */\n\timageUnsupportedByModel?: string;\n}\n\n/**\n * Pluggable operations for the read tool.\n * Override these to delegate file reading to remote systems (for example SSH).\n */\nexport interface ReadOperations {\n\t/** Read file contents as a Buffer */\n\treadFile: (absolutePath: string) => Promise<Buffer>;\n\t/** Check if file is readable (throw if not) */\n\taccess: (absolutePath: string) => Promise<void>;\n\t/** Detect image MIME type, return null or undefined for non-images */\n\tdetectImageMimeType?: (absolutePath: string) => Promise<string | null | undefined>;\n\t/**\n\t * Stream file contents in chunks. When present, text files are read through it and only the lines\n\t * that will be shown are kept in memory; otherwise readFile loads the whole file. Stop reading when\n\t * the signal aborts; the read tool also stops consuming the stream then.\n\t */\n\tcreateReadStream?: (absolutePath: string, options: { signal?: AbortSignal }) => AsyncIterable<Uint8Array>;\n}\n\nconst defaultReadOperations: ReadOperations = {\n\treadFile: (path) => fsReadFile(path),\n\tcreateReadStream: readLocalFileChunks,\n\taccess: (path) => fsAccess(path, constants.R_OK),\n\tdetectImageMimeType: detectSupportedImageMimeTypeFromFile,\n};\n\n/**\n * Stream a local file the way fs.readFile reads it: a regular file up to its size when opened, so text\n * appended during the read is not counted and a growing file still ends; a file reporting size 0 (such\n * as /proc files) and other file types until EOF. Abort is left to the read tool, which stops consuming\n * the stream when its signal aborts; leaving its loop closes the stream.\n */\nasync function* readLocalFileChunks(path: string): AsyncIterable<Uint8Array> {\n\tconst handle = await fsOpen(path, \"r\");\n\ttry {\n\t\tconst stats = await handle.stat();\n\t\tconst end = stats.isFile() && stats.size > 0 ? stats.size - 1 : undefined;\n\t\t// No signal for the stream: one that aborts before the stream's iterator attaches makes the stream\n\t\t// emit an 'error' no listener handles, which crashes the process (#11956).\n\t\tyield* handle.createReadStream({ end, autoClose: false });\n\t} finally {\n\t\tawait handle.close();\n\t}\n}\n\nexport interface ReadToolOptions {\n\t/** Whether to auto-resize images. Default: true */\n\tautoResizeImages?: boolean;\n\t/** Fallback resize profile when the execution context has no model metadata. */\n\tresizeOptions?: ModelImageResizeOptions;\n\t/** Custom operations for file reading. Default: local filesystem */\n\toperations?: ReadOperations;\n}\n\n/** The image block and its note, or the text for text files and images that could not be processed. */\nfunction toReadOutput(content: (TextContent | ImageContent)[]): ReadToolOutput {\n\tconst text = content.find((block) => block.type === \"text\")?.text ?? \"\";\n\tconst image = content.find((block) => block.type === \"image\");\n\treturn image ? { type: \"image\", data: image.data, mimeType: image.mimeType, note: text } : text;\n}\n\n/** The lines a read shows, with the file's line count; line counts follow `text.split(\"\\n\")`. */\ninterface SelectedLines {\n\ttotalFileLines: number;\n\ttruncation: TruncationResult;\n\t/** Bytes of the first selected line, for the notice when it alone exceeds the byte limit. */\n\tfirstLineBytes: number;\n}\n\n/**\n * Whether a range can be streamed. Other values (fractional, negative limit) keep the whole-file path,\n * whose array slicing defines what they select, for example limit -1 as all lines but the last.\n */\nfunction isStreamableRange(offset: number | undefined, limit: number | undefined): boolean {\n\treturn (\n\t\t(offset === undefined || Number.isInteger(offset)) &&\n\t\t(limit === undefined || (Number.isInteger(limit) && limit >= 0))\n\t);\n}\n\n/** Select lines from a whole file in memory: for operations without createReadStream and unusual ranges. */\nfunction selectLinesFromBuffer(buffer: Buffer, startLine: number, limit: number | undefined): SelectedLines {\n\tconst allLines = buffer.toString(\"utf-8\").split(\"\\n\");\n\tconst endLine = limit === undefined ? undefined : Math.min(startLine + limit, allLines.length);\n\tconst truncation = truncateHead(allLines.slice(startLine, endLine).join(\"\\n\"));\n\tconst firstLineBytes = truncation.firstLineExceedsLimit ? Buffer.byteLength(allLines[startLine], \"utf-8\") : 0;\n\treturn { totalFileLines: allLines.length, truncation, firstLineBytes };\n}\n\n/**\n * Select lines from a file read in chunks. Only lines truncateHead can show are stored; the rest are\n * counted, so memory does not grow with the file. Stops reading when the signal aborts.\n */\nasync function selectLinesFromStream(\n\tchunks: AsyncIterable<Uint8Array>,\n\tstartLine: number,\n\tlimit: number | undefined,\n\tsignal: AbortSignal | undefined,\n): Promise<SelectedLines> {\n\tconst endLine = limit === undefined ? Number.POSITIVE_INFINITY : startLine + limit;\n\t// Non-fatal UTF-8 that keeps a byte order mark decodes like Buffer.toString(\"utf-8\").\n\tconst decoder = new TextDecoder(\"utf-8\", { ignoreBOM: true });\n\tconst storedLines: string[] = [];\n\tlet storedBytes = 0;\n\tlet storedPastCaps = false;\n\tlet line = 0;\n\tlet selectedLines = 0;\n\tlet selectedBytes = 0;\n\tlet firstLineBytes = 0;\n\tlet lastLineEmpty = true;\n\t// The selected line being read: its text, while it is stored, and its size.\n\tlet pieces: string[] | undefined = [];\n\tlet lineBytes = 0;\n\tlet lineHasText = false;\n\n\tconst appendToLine = (text: string, start: number, end: number) => {\n\t\tlineHasText = true;\n\t\tif (!pieces) return;\n\t\tconst piece = text.slice(start, end);\n\t\t// A line over the byte cap is never shown, and a first line over it is only measured: never store\n\t\t// all of a 1 GB line.\n\t\tif (lineBytes <= DEFAULT_MAX_BYTES) pieces.push(piece);\n\t\tlineBytes += Buffer.byteLength(piece, \"utf-8\");\n\t};\n\tconst finishLine = () => {\n\t\tif (pieces) {\n\t\t\tif (selectedLines === 0) firstLineBytes = lineBytes;\n\t\t\t// Storing continues one line past the caps: truncateHead ignores a trailing empty line, so the\n\t\t\t// line after the cap must be there for it to decide truncation as for the full text.\n\t\t\tif (storedLines.length > DEFAULT_MAX_LINES || storedBytes > DEFAULT_MAX_BYTES) storedPastCaps = true;\n\t\t\tconst text = pieces.join(\"\");\n\t\t\tstoredBytes += Buffer.byteLength(text, \"utf-8\") + (storedLines.length > 0 ? 1 : 0);\n\t\t\tstoredLines.push(text);\n\t\t}\n\t\tselectedLines++;\n\t\tlastLineEmpty = !lineHasText;\n\t\tpieces = storedPastCaps ? undefined : [];\n\t\tlineBytes = 0;\n\t\tlineHasText = false;\n\t};\n\tconst select = (text: string) => {\n\t\tlet position = 0;\n\t\t// Start of the selected text in this piece, measured as a whole: the joined lines' size.\n\t\tlet selectionStart = -1;\n\t\twhile (true) {\n\t\t\tconst selected = line >= startLine && line < endLine;\n\t\t\tif (selected && selectionStart === -1) selectionStart = position;\n\t\t\tconst newline = text.indexOf(\"\\n\", position);\n\t\t\tconst end = newline === -1 ? text.length : newline;\n\t\t\tif (selected && end > position) appendToLine(text, position, end);\n\t\t\tif (newline === -1) break;\n\t\t\tif (selected) {\n\t\t\t\tfinishLine();\n\t\t\t\tif (line + 1 === endLine) {\n\t\t\t\t\tselectedBytes += Buffer.byteLength(text.slice(selectionStart, newline), \"utf-8\");\n\t\t\t\t\tselectionStart = -1;\n\t\t\t\t}\n\t\t\t}\n\t\t\tline++;\n\t\t\tposition = newline + 1;\n\t\t}\n\t\tif (selectionStart !== -1) selectedBytes += Buffer.byteLength(text.slice(selectionStart), \"utf-8\");\n\t};\n\n\tfor await (const chunk of chunks) {\n\t\t// Leaving the loop closes the stream.\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tselect(decoder.decode(chunk, { stream: true }));\n\t}\n\tselect(decoder.decode());\n\tif (line >= startLine && line < endLine) finishLine();\n\tconst truncation: TruncationResult = {\n\t\t...truncateHead(storedLines.join(\"\\n\")),\n\t\t// truncateHead's counts for the joined selected lines, which drop a trailing empty line.\n\t\ttotalLines: selectedBytes === 0 ? 0 : selectedLines - (lastLineEmpty ? 1 : 0),\n\t\ttotalBytes: selectedBytes,\n\t};\n\treturn { totalFileLines: line + 1, truncation, firstLineBytes };\n}\n\nexport function createReadToolDefinition(\n\tcwd: string,\n\toptions?: ReadToolOptions,\n): ToolDefinition<typeof readSchema, ReadToolDetails | undefined> {\n\tconst autoResizeImages = options?.autoResizeImages ?? true;\n\tconst fallbackResizeOptions = options?.resizeOptions;\n\tconst ops = options?.operations ?? defaultReadOperations;\n\t// Remote or confined backends own normalization probes as well as content\n\t// reads. Probing the local host first can leak or select unrelated files.\n\tconst exists = options?.operations\n\t\t? async (path: string) => {\n\t\t\t\ttry {\n\t\t\t\t\tawait ops.access(path);\n\t\t\t\t\treturn true;\n\t\t\t\t} catch {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t: undefined;\n\treturn {\n\t\tname: \"read\",\n\t\tlabel: \"read\",\n\t\tdescription: `Read the contents of a file. Supports text files and images (jpg, png, gif, webp, bmp). Images are sent as attachments. For text files, output is truncated to ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). Use offset/limit for large files. When you need the full file, continue with offset until complete.`,\n\t\tpromptSnippet: readToolSystemPromptContribution.snippet,\n\t\tpromptGuidelines: [...readToolSystemPromptContribution.guidelines],\n\t\tparameters: readSchema,\n\t\toutputSchema: readOutputSchema,\n\t\tconstrainedSampling: { type: \"json_schema\", strict: \"prefer\" },\n\t\tasync execute(\n\t\t\t_toolCallId,\n\t\t\t{ path, offset, limit }: { path: string; offset?: number; limit?: number },\n\t\t\tsignal?: AbortSignal,\n\t\t\t_onUpdate?,\n\t\t\tctx?: ExtensionContext,\n\t\t) {\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\n\t\t\t\t\t(async () => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst absolutePath = await resolveReadPathAsync(path, ctx?.cwd || cwd, exists);\n\t\t\t\t\t\t\tif (aborted) return;\n\t\t\t\t\t\t\t// Check if file exists and is readable.\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\tconst mimeType = ops.detectImageMimeType ? await ops.detectImageMimeType(absolutePath) : undefined;\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\tif (mimeType) {\n\t\t\t\t\t\t\t\t// Read image as binary.\n\t\t\t\t\t\t\t\tconst buffer = await ops.readFile(absolutePath);\n\t\t\t\t\t\t\t\tconst processed = await processImage(buffer, mimeType, {\n\t\t\t\t\t\t\t\t\tautoResizeImages,\n\t\t\t\t\t\t\t\t\tresizeOptions: ctx?.model?.inputLimits?.images?.resize ?? fallbackResizeOptions,\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tif (!processed.ok) {\n\t\t\t\t\t\t\t\t\tconst textNote = `Read image file [${mimeType}]\\n${processed.message}`;\n\t\t\t\t\t\t\t\t\tcontent = [{ type: \"text\", text: textNote }];\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tlet textNote = `Read image file [${processed.mimeType}]`;\n\t\t\t\t\t\t\t\t\tif (processed.hints.length > 0) textNote += `\\n${processed.hints.join(\"\\n\")}`;\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: processed.data, mimeType: processed.mimeType },\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\t\t\tif (ctx?.model && !ctx.model.input.includes(\"image\")) {\n\t\t\t\t\t\t\t\t\t\tdetails = { imageUnsupportedByModel: ctx.model.id };\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\t// Read text content. Convert offset from 1-indexed input to 0-indexed line access.\n\t\t\t\t\t\t\t\tconst startLine = offset ? Math.max(0, offset - 1) : 0;\n\t\t\t\t\t\t\t\tconst startLineDisplay = startLine + 1;\n\t\t\t\t\t\t\t\tconst { totalFileLines, truncation, firstLineBytes } =\n\t\t\t\t\t\t\t\t\tops.createReadStream && isStreamableRange(offset, limit)\n\t\t\t\t\t\t\t\t\t\t? await selectLinesFromStream(\n\t\t\t\t\t\t\t\t\t\t\t\tops.createReadStream(absolutePath, { signal }),\n\t\t\t\t\t\t\t\t\t\t\t\tstartLine,\n\t\t\t\t\t\t\t\t\t\t\t\tlimit,\n\t\t\t\t\t\t\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t: selectLinesFromBuffer(await ops.readFile(absolutePath), startLine, limit);\n\t\t\t\t\t\t\t\tif (aborted) return;\n\t\t\t\t\t\t\t\t// Check if offset is out of bounds.\n\t\t\t\t\t\t\t\tif (startLine >= totalFileLines) {\n\t\t\t\t\t\t\t\t\tthrow new Error(`Offset ${offset} is beyond end of file (${totalFileLines} lines total)`);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t// A user-specified limit is honored before truncation.\n\t\t\t\t\t\t\t\tconst userLimitedLines =\n\t\t\t\t\t\t\t\t\tlimit === undefined ? undefined : Math.min(startLine + limit, totalFileLines) - startLine;\n\t\t\t\t\t\t\t\tlet outputText: string;\n\t\t\t\t\t\t\t\tif (truncation.firstLineExceedsLimit) {\n\t\t\t\t\t\t\t\t\t// First line alone exceeds the byte limit. Point the model at a bash fallback.\n\t\t\t\t\t\t\t\t\tconst firstLineSize = formatSize(firstLineBytes);\n\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' ${path} | head -c ${DEFAULT_MAX_BYTES}]`;\n\t\t\t\t\t\t\t\t\tdetails = { truncation };\n\t\t\t\t\t\t\t\t} else if (truncation.truncated) {\n\t\t\t\t\t\t\t\t\t// Truncation occurred. Build an actionable continuation notice.\n\t\t\t\t\t\t\t\t\tconst endLineDisplay = startLineDisplay + truncation.outputLines - 1;\n\t\t\t\t\t\t\t\t\tconst nextOffset = endLineDisplay + 1;\n\t\t\t\t\t\t\t\t\toutputText = truncation.content;\n\t\t\t\t\t\t\t\t\tif (truncation.truncatedBy === \"lines\") {\n\t\t\t\t\t\t\t\t\t\toutputText += `\\n\\n[Showing lines ${startLineDisplay}-${endLineDisplay} of ${totalFileLines}. Use offset=${nextOffset} to continue.]`;\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\toutputText += `\\n\\n[Showing lines ${startLineDisplay}-${endLineDisplay} of ${totalFileLines} (${formatSize(DEFAULT_MAX_BYTES)} limit). Use offset=${nextOffset} to continue.]`;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tdetails = { truncation };\n\t\t\t\t\t\t\t\t} else if (userLimitedLines !== undefined && startLine + userLimitedLines < totalFileLines) {\n\t\t\t\t\t\t\t\t\t// User-specified limit stopped early, but the file still has more content.\n\t\t\t\t\t\t\t\t\tconst remaining = totalFileLines - (startLine + userLimitedLines);\n\t\t\t\t\t\t\t\t\tconst nextOffset = startLine + userLimitedLines + 1;\n\t\t\t\t\t\t\t\t\toutputText = `${truncation.content}\\n\\n[${remaining} more lines in file. Use offset=${nextOffset} to continue.]`;\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t// No truncation and no remaining user-limited content.\n\t\t\t\t\t\t\t\t\toutputText = truncation.content;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcontent = [{ type: \"text\", text: outputText }];\n\t\t\t\t\t\t\t}\n\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\t\tresolve({ content, details });\n\t\t\t\t\t\t} catch (error: any) {\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).then((result) => ({ ...result, structuredContent: toReadOutput(result.content) }));\n\t\t},\n\t\t...readRenderers,\n\t};\n}\n\nexport function createReadTool(cwd: string, options?: ReadToolOptions): TypeBoxAgentTool<typeof readSchema> {\n\treturn wrapToolDefinition(createReadToolDefinition(cwd, options));\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"read.d.ts","sourceRoot":"","sources":["../../../../src/core/tools/renderers/read.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AASH,OAAO,KAAK,EAAE,cAAc,EAA2B,MAAM,2BAA2B,CAAC;AAEzF,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAkIlD,eAAO,MAAM,aAAa,EAAE,IAAI,CAAC,cAAc,CAAC,GAAG,EAAE,eAAe,GAAG,SAAS,CAAC,EAAE,YAAY,GAAG,cAAc,CAyB/G,CAAC"}
1
+ {"version":3,"file":"read.d.ts","sourceRoot":"","sources":["../../../../src/core/tools/renderers/read.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AASH,OAAO,KAAK,EAAE,cAAc,EAA2B,MAAM,2BAA2B,CAAC;AAEzF,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAsIlD,eAAO,MAAM,aAAa,EAAE,IAAI,CAAC,cAAc,CAAC,GAAG,EAAE,eAAe,GAAG,SAAS,CAAC,EAAE,YAAY,GAAG,cAAc,CAyB/G,CAAC"}
@@ -80,8 +80,12 @@ function formatCompactReadCall(classification, args, theme) {
80
80
  expandHint);
81
81
  }
82
82
  function formatReadResult(args, result, options, theme, showImages, _cwd, isError) {
83
+ const unsupportedBy = result.details?.imageUnsupportedByModel;
84
+ const imageWarning = unsupportedBy
85
+ ? `\n${theme.fg("warning", `[${unsupportedBy} does not support images; it saw a placeholder instead]`)}`
86
+ : "";
83
87
  if (!options.expanded && !isError) {
84
- return "";
88
+ return imageWarning;
85
89
  }
86
90
  const rawPath = str(args?.file_path ?? args?.path);
87
91
  const output = getTextOutput(result, showImages);
@@ -107,7 +111,7 @@ function formatReadResult(args, result, options, theme, showImages, _cwd, isErro
107
111
  text += `\n${theme.fg("warning", `[Truncated: ${truncation.outputLines} lines shown (${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit)]`)}`;
108
112
  }
109
113
  }
110
- return text;
114
+ return text + imageWarning;
111
115
  }
112
116
  export const readRenderers = {
113
117
  renderCall(rawArgs, theme, context) {
@@ -1 +1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cesContent":["/**\n * Presentation for the read tool.\n *\n * Renderers live apart from the implementation so a process that only displays tool output does not\n * load the execution path or its typebox parameter schema. `read.ts` spreads these into its\n * definition, so the tool's public shape is unchanged.\n */\n\nimport { basename, dirname, isAbsolute, relative, resolve as resolvePath, sep } from \"node:path\";\nimport type { ImageContent, TextContent } from \"@draht/ai\";\nimport { Text } from \"@draht/tui\";\nimport { getReadmePath } from \"../../../config.ts\";\nimport { keyHint, keyText } from \"../../../modes/interactive/components/keybinding-hints.ts\";\nimport { getLanguageFromPath, highlightCode, type Theme } from \"../../../modes/interactive/theme/theme.ts\";\nimport { formatPathRelativeToCwdOrAbsolute } from \"../../../utils/paths.ts\";\nimport type { ToolDefinition, ToolRenderResultOptions } from \"../../extensions/types.ts\";\nimport { resolveToCwd } from \"../path-utils.ts\";\nimport type { ReadToolDetails } from \"../read.ts\";\nimport { formatReadLineRange, getTextOutput, renderToolPath, replaceTabs, str } from \"../render-utils.ts\";\nimport { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize } from \"../truncate.ts\";\n\ninterface CompactReadClassification {\n\tkind: \"docs\" | \"resource\" | \"skill\";\n\tlabel: string;\n}\nconst COMPACT_RESOURCE_FILE_NAMES = new Set([\"AGENTS.override.md\", \"AGENTS.md\", \"AGENTS.MD\", \"CLAUDE.md\", \"CLAUDE.MD\"]);\ntype ReadRenderArgs = { path?: string; file_path?: string; offset?: unknown; limit?: unknown };\nfunction styledReadLineRange(args: ReadRenderArgs | undefined, theme: Theme): string {\n\tconst range = formatReadLineRange(args?.offset, args?.limit);\n\treturn range ? theme.fg(\"warning\", range) : \"\";\n}\nfunction formatReadCall(args: ReadRenderArgs | undefined, theme: Theme, cwd: string): string {\n\tconst pathDisplay = renderToolPath(str(args?.file_path ?? args?.path), theme, cwd);\n\treturn `${theme.fg(\"toolTitle\", theme.bold(\"read\"))} ${pathDisplay}${styledReadLineRange(args, theme)}`;\n}\nfunction trimTrailingEmptyLines(lines: string[]): string[] {\n\tlet end = lines.length;\n\twhile (end > 0 && lines[end - 1] === \"\") {\n\t\tend--;\n\t}\n\treturn lines.slice(0, end);\n}\nfunction toPosixPath(filePath: string): string {\n\treturn filePath.split(sep).join(\"/\");\n}\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\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?.file_path ?? args?.path);\n\tif (!rawPath) return undefined;\n\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\n\tconst docsClassification = getPiDocsClassification(absolutePath);\n\tif (docsClassification) return docsClassification;\n\n\tif (COMPACT_RESOURCE_FILE_NAMES.has(fileName)) {\n\t\treturn { kind: \"resource\", label: formatPathRelativeToCwdOrAbsolute(absolutePath, cwd) };\n\t}\n\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\")} to 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\tstyledReadLineRange(args, theme) +\n\t\t\texpandHint\n\t\t);\n\t}\n\n\treturn (\n\t\ttheme.fg(\"toolTitle\", theme.bold(`read ${classification.kind}`)) +\n\t\t\" \" +\n\t\ttheme.fg(\"accent\", classification.label) +\n\t\tstyledReadLineRange(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\tif (!options.expanded && !isError) {\n\t\treturn \"\";\n\t}\n\n\tconst rawPath = str(args?.file_path ?? args?.path);\n\tconst output = getTextOutput(result, showImages);\n\tconst lang = !isError && rawPath ? 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\", \"to expand\")}${theme.fg(\"muted\", \")\")}`;\n\t}\n\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}\n\nexport const readRenderers: Pick<ToolDefinition<any, ReadToolDetails | undefined>, \"renderCall\" | \"renderResult\"> = {\n\trenderCall(rawArgs, theme, context) {\n\t\tconst args = rawArgs as ReadRenderArgs | undefined;\n\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\tconst classification = !context.expanded ? getCompactReadClassification(args, context.cwd) : undefined;\n\t\ttext.setText(\n\t\t\tclassification ? formatCompactReadCall(classification, args, theme) : formatReadCall(args, theme, context.cwd),\n\t\t);\n\t\treturn text;\n\t},\n\trenderResult(result, options, theme, context) {\n\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\ttext.setText(\n\t\t\tformatReadResult(\n\t\t\t\tcontext.args as ReadRenderArgs | undefined,\n\t\t\t\tresult,\n\t\t\t\toptions,\n\t\t\t\ttheme,\n\t\t\t\tcontext.showImages,\n\t\t\t\tcontext.cwd,\n\t\t\t\tcontext.isError,\n\t\t\t),\n\t\t);\n\t\treturn text;\n\t},\n};\n"]}
1
+ {"version":3,"file":"read.js","sourceRoot":"","sources":["../../../../src/core/tools/renderers/read.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,OAAO,IAAI,WAAW,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AAEjG,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAClC,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,2DAA2D,CAAC;AAC7F,OAAO,EAAE,mBAAmB,EAAE,aAAa,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,GAAG,YAAY,CAAC;AAC5B,CAAC;AAED,MAAM,CAAC,MAAM,aAAa,GAA0F;IACnH,UAAU,CAAC,OAAO,EAAE,KAAK,EAAE,OAAO;QACjC,MAAM,IAAI,GAAG,OAAqC,CAAC;QACnD,MAAM,IAAI,GAAI,OAAO,CAAC,aAAkC,IAAI,IAAI,IAAI,CAAC,EAAE,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;QAC/E,MAAM,cAAc,GAAG,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC,4BAA4B,CAAC,IAAI,EAAE,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;QACvG,IAAI,CAAC,OAAO,CACX,cAAc,CAAC,CAAC,CAAC,qBAAqB,CAAC,cAAc,EAAE,IAAI,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,cAAc,CAAC,IAAI,EAAE,KAAK,EAAE,OAAO,CAAC,GAAG,CAAC,CAC9G,CAAC;QACF,OAAO,IAAI,CAAC;IACb,CAAC;IACD,YAAY,CAAC,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO;QAC3C,MAAM,IAAI,GAAI,OAAO,CAAC,aAAkC,IAAI,IAAI,IAAI,CAAC,EAAE,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;QAC/E,IAAI,CAAC,OAAO,CACX,gBAAgB,CACf,OAAO,CAAC,IAAkC,EAC1C,MAAM,EACN,OAAO,EACP,KAAK,EACL,OAAO,CAAC,UAAU,EAClB,OAAO,CAAC,GAAG,EACX,OAAO,CAAC,OAAO,CACf,CACD,CAAC;QACF,OAAO,IAAI,CAAC;IACb,CAAC;CACD,CAAC","sourcesContent":["/**\n * Presentation for the read tool.\n *\n * Renderers live apart from the implementation so a process that only displays tool output does not\n * load the execution path or its typebox parameter schema. `read.ts` spreads these into its\n * definition, so the tool's public shape is unchanged.\n */\n\nimport { basename, dirname, isAbsolute, relative, resolve as resolvePath, sep } from \"node:path\";\nimport type { ImageContent, TextContent } from \"@draht/ai\";\nimport { Text } from \"@draht/tui\";\nimport { getReadmePath } from \"../../../config.ts\";\nimport { keyHint, keyText } from \"../../../modes/interactive/components/keybinding-hints.ts\";\nimport { getLanguageFromPath, highlightCode, type Theme } from \"../../../modes/interactive/theme/theme.ts\";\nimport { formatPathRelativeToCwdOrAbsolute } from \"../../../utils/paths.ts\";\nimport type { ToolDefinition, ToolRenderResultOptions } from \"../../extensions/types.ts\";\nimport { resolveToCwd } from \"../path-utils.ts\";\nimport type { ReadToolDetails } from \"../read.ts\";\nimport { formatReadLineRange, getTextOutput, renderToolPath, replaceTabs, str } from \"../render-utils.ts\";\nimport { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize } from \"../truncate.ts\";\n\ninterface CompactReadClassification {\n\tkind: \"docs\" | \"resource\" | \"skill\";\n\tlabel: string;\n}\nconst COMPACT_RESOURCE_FILE_NAMES = new Set([\"AGENTS.override.md\", \"AGENTS.md\", \"AGENTS.MD\", \"CLAUDE.md\", \"CLAUDE.MD\"]);\ntype ReadRenderArgs = { path?: string; file_path?: string; offset?: unknown; limit?: unknown };\nfunction styledReadLineRange(args: ReadRenderArgs | undefined, theme: Theme): string {\n\tconst range = formatReadLineRange(args?.offset, args?.limit);\n\treturn range ? theme.fg(\"warning\", range) : \"\";\n}\nfunction formatReadCall(args: ReadRenderArgs | undefined, theme: Theme, cwd: string): string {\n\tconst pathDisplay = renderToolPath(str(args?.file_path ?? args?.path), theme, cwd);\n\treturn `${theme.fg(\"toolTitle\", theme.bold(\"read\"))} ${pathDisplay}${styledReadLineRange(args, theme)}`;\n}\nfunction trimTrailingEmptyLines(lines: string[]): string[] {\n\tlet end = lines.length;\n\twhile (end > 0 && lines[end - 1] === \"\") {\n\t\tend--;\n\t}\n\treturn lines.slice(0, end);\n}\nfunction toPosixPath(filePath: string): string {\n\treturn filePath.split(sep).join(\"/\");\n}\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\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?.file_path ?? args?.path);\n\tif (!rawPath) return undefined;\n\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\n\tconst docsClassification = getPiDocsClassification(absolutePath);\n\tif (docsClassification) return docsClassification;\n\n\tif (COMPACT_RESOURCE_FILE_NAMES.has(fileName)) {\n\t\treturn { kind: \"resource\", label: formatPathRelativeToCwdOrAbsolute(absolutePath, cwd) };\n\t}\n\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\")} to 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\tstyledReadLineRange(args, theme) +\n\t\t\texpandHint\n\t\t);\n\t}\n\n\treturn (\n\t\ttheme.fg(\"toolTitle\", theme.bold(`read ${classification.kind}`)) +\n\t\t\" \" +\n\t\ttheme.fg(\"accent\", classification.label) +\n\t\tstyledReadLineRange(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 unsupportedBy = result.details?.imageUnsupportedByModel;\n\tconst imageWarning = unsupportedBy\n\t\t? `\\n${theme.fg(\"warning\", `[${unsupportedBy} does not support images; it saw a placeholder instead]`)}`\n\t\t: \"\";\n\tif (!options.expanded && !isError) {\n\t\treturn imageWarning;\n\t}\n\n\tconst rawPath = str(args?.file_path ?? args?.path);\n\tconst output = getTextOutput(result, showImages);\n\tconst lang = !isError && rawPath ? 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\", \"to expand\")}${theme.fg(\"muted\", \")\")}`;\n\t}\n\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 + imageWarning;\n}\n\nexport const readRenderers: Pick<ToolDefinition<any, ReadToolDetails | undefined>, \"renderCall\" | \"renderResult\"> = {\n\trenderCall(rawArgs, theme, context) {\n\t\tconst args = rawArgs as ReadRenderArgs | undefined;\n\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\tconst classification = !context.expanded ? getCompactReadClassification(args, context.cwd) : undefined;\n\t\ttext.setText(\n\t\t\tclassification ? formatCompactReadCall(classification, args, theme) : formatReadCall(args, theme, context.cwd),\n\t\t);\n\t\treturn text;\n\t},\n\trenderResult(result, options, theme, context) {\n\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\ttext.setText(\n\t\t\tformatReadResult(\n\t\t\t\tcontext.args as ReadRenderArgs | undefined,\n\t\t\t\tresult,\n\t\t\t\toptions,\n\t\t\t\ttheme,\n\t\t\t\tcontext.showImages,\n\t\t\t\tcontext.cwd,\n\t\t\t\tcontext.isError,\n\t\t\t),\n\t\t);\n\t\treturn text;\n\t},\n};\n"]}
@@ -67,4 +67,8 @@ export declare function truncateLine(line: string, maxChars?: number): {
67
67
  text: string;
68
68
  wasTruncated: boolean;
69
69
  };
70
+ /** Returns at most the first `maxUnits` UTF-16 code units of `text`, without splitting a surrogate pair. */
71
+ export declare function sliceHead(text: string, maxUnits: number): string;
72
+ /** Returns at most the last `maxUnits` UTF-16 code units of `text`, without splitting a surrogate pair. */
73
+ export declare function sliceTail(text: string, maxUnits: number): string;
70
74
  //# sourceMappingURL=truncate.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"truncate.d.ts","sourceRoot":"","sources":["../../../src/core/tools/truncate.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,eAAO,MAAM,iBAAiB,OAAO,CAAC;AACtC,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AAY,CAC3B,IAAI,EAAE,MAAM,EACZ,QAAQ,GAAE,MAA6B,GACrC;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,YAAY,EAAE,OAAO,CAAA;CAAE,CAKzC;AAED,4GAA4G;AAC5G,wBAAgB,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAMhE;AAED,2GAA2G;AAC3G,wBAAgB,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAMhE"}
@@ -210,6 +210,29 @@ export function truncateLine(line, maxChars = GREP_MAX_LINE_LENGTH) {
210
210
  if (line.length <= maxChars) {
211
211
  return { text: line, wasTruncated: false };
212
212
  }
213
- return { text: `${line.slice(0, maxChars)}... [truncated]`, wasTruncated: true };
213
+ return { text: `${sliceHead(line, maxChars)}... [truncated]`, wasTruncated: true };
214
+ }
215
+ /** Returns at most the first `maxUnits` UTF-16 code units of `text`, without splitting a surrogate pair. */
216
+ export function sliceHead(text, maxUnits) {
217
+ const end = Math.max(0, maxUnits);
218
+ // A lone high surrogate before the cut would be invalid UTF-16; keep the whole character out instead.
219
+ return isHighSurrogate(text.charCodeAt(end - 1)) && isLowSurrogate(text.charCodeAt(end))
220
+ ? text.slice(0, end - 1)
221
+ : text.slice(0, end);
222
+ }
223
+ /** Returns at most the last `maxUnits` UTF-16 code units of `text`, without splitting a surrogate pair. */
224
+ export function sliceTail(text, maxUnits) {
225
+ if (maxUnits <= 0)
226
+ return "";
227
+ const start = Math.max(0, text.length - maxUnits);
228
+ return isLowSurrogate(text.charCodeAt(start)) && isHighSurrogate(text.charCodeAt(start - 1))
229
+ ? text.slice(start + 1)
230
+ : text.slice(start);
231
+ }
232
+ function isHighSurrogate(code) {
233
+ return code >= 0xd800 && code <= 0xdbff;
234
+ }
235
+ function isLowSurrogate(code) {
236
+ return code >= 0xdc00 && code <= 0xdfff;
214
237
  }
215
238
  //# sourceMappingURL=truncate.js.map