@maxmo74/pi-coding-agent 1.5.2-max.15 → 1.6.0-max.16

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 (228) hide show
  1. package/CHANGELOG.md +82 -0
  2. package/README.md +1 -1
  3. package/dist/bundle/chunks/{anthropic-messages-CA3HHOL3.js → anthropic-messages-WAFIHSF7.js} +3 -3
  4. package/dist/bundle/chunks/{azure-openai-responses-76TWS6DT.js → azure-openai-responses-EB4MRIM4.js} +1 -1
  5. package/dist/bundle/chunks/bedrock-converse-stream.js +2 -2
  6. package/dist/bundle/chunks/{chunk-FMPAMX2W.js → chunk-E6LJTZYC.js} +1 -1
  7. package/dist/bundle/chunks/chunk-EEBRZED2.js +44 -0
  8. package/dist/bundle/chunks/chunk-EVSO24NP.js +2 -0
  9. package/dist/bundle/chunks/{chunk-M6TSYZBS.js → chunk-EXXWEFU5.js} +67 -64
  10. package/dist/bundle/chunks/{chunk-ZBIZYD6W.js → chunk-F7LEMV2T.js} +1 -1
  11. package/dist/bundle/chunks/{chunk-VKJQ6CME.js → chunk-I6HYYNH6.js} +1 -1
  12. package/dist/bundle/chunks/{chunk-BAC3QPNW.js → chunk-ILDLA2JW.js} +1 -1
  13. package/dist/bundle/chunks/chunk-INODY4DR.js +2 -0
  14. package/dist/bundle/chunks/{chunk-COKMCNCW.js → chunk-KREOSXD7.js} +1 -1
  15. package/dist/bundle/chunks/chunk-LWG2CUTI.js +31 -0
  16. package/dist/bundle/chunks/{chunk-WL4TUXY7.js → chunk-NRLRGOCX.js} +1 -1
  17. package/dist/bundle/chunks/{chunk-AUUCDC7R.js → chunk-NRY4NBZW.js} +1 -1
  18. package/dist/bundle/chunks/{chunk-4KSTFUIK.js → chunk-NV3NPOPF.js} +3 -2
  19. package/dist/bundle/chunks/{chunk-IQUU5XIT.js → chunk-RCNEHRMW.js} +1 -1
  20. package/dist/bundle/chunks/{chunk-FF6XOTWB.js → chunk-X26YOAEH.js} +11 -10
  21. package/dist/bundle/chunks/chunk-X6RQRO3L.js +16 -0
  22. package/dist/bundle/chunks/{chunk-4UNPP53I.js → chunk-XGGZYFNG.js} +2 -2
  23. package/dist/bundle/chunks/chunk-XJ2YV77J.js +30 -0
  24. package/dist/bundle/chunks/{chunk-RKNK4Y6L.js → chunk-YOWSKVK7.js} +1 -1
  25. package/dist/bundle/chunks/{cli-2MK3TR7P.js → cli-QMJEURSM.js} +1 -1
  26. package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-U4J7D646.js → cloudflare-workers-ai-system-one-AMCR7QEI.js} +1 -1
  27. package/dist/bundle/chunks/{easter-egg-3d-GEVPKQF6.js → easter-egg-3d-7CBVPJQ3.js} +1 -1
  28. package/dist/bundle/chunks/{execute-L2EEDV3L.js → execute-XDNPBEMU.js} +1 -1
  29. package/dist/bundle/chunks/github-copilot.js +1 -1
  30. package/dist/bundle/chunks/google-generative-ai-43M4N5LK.js +2 -0
  31. package/dist/bundle/chunks/google-vertex-2B3PASK2.js +2 -0
  32. package/dist/bundle/chunks/{llama-cpp-classify-EJXCQRUQ.js → llama-cpp-classify-XXZYF3RR.js} +1 -1
  33. package/dist/bundle/chunks/{mistral-conversations-S277EKLB.js → mistral-conversations-E3D5ZQKB.js} +2 -2
  34. package/dist/bundle/chunks/openai-codex-responses-MSQDSDUR.js +10 -0
  35. package/dist/bundle/chunks/{openai-completions-HRZOSLBO.js → openai-completions-4IC6AGTR.js} +2 -2
  36. package/dist/bundle/chunks/{openai-decisions-F66BDLOM.js → openai-decisions-LZ2RLVRX.js} +1 -1
  37. package/dist/bundle/chunks/{openai-responses-BAKFWTGE.js → openai-responses-MCO3BHCC.js} +1 -1
  38. package/dist/bundle/chunks/{openrouter-images-VXF5TVIK.js → openrouter-images-SHUJ3VSG.js} +1 -1
  39. package/dist/bundle/chunks/{pi-messages-UBJKNDRN.js → pi-messages-NIKOQ4O7.js} +1 -1
  40. package/dist/bundle/chunks/{runtime-J5ZSBGTX.js → runtime-F3SXQONS.js} +1 -1
  41. package/dist/bundle/chunks/{typesafe-system-one-56TEMIHL.js → typesafe-system-one-R2CDUWNO.js} +1 -1
  42. package/dist/bundle/chunks/{virtual-modules-MRQHQVIQ.js → virtual-modules-2WYTGPJ3.js} +1 -1
  43. package/dist/bundle/cli-runtime.js +1 -1
  44. package/dist/bundle/index.js +1 -1
  45. package/dist/bundle/rpc-entry.js +1 -1
  46. package/dist/cli/args.d.ts.map +1 -1
  47. package/dist/cli/args.js +4 -2
  48. package/dist/cli/args.js.map +1 -1
  49. package/dist/cli/config-selector.d.ts.map +1 -1
  50. package/dist/cli/config-selector.js +9 -6
  51. package/dist/cli/config-selector.js.map +1 -1
  52. package/dist/cli/session-picker.d.ts.map +1 -1
  53. package/dist/cli/session-picker.js +9 -6
  54. package/dist/cli/session-picker.js.map +1 -1
  55. package/dist/cli/startup-ui.d.ts.map +1 -1
  56. package/dist/cli/startup-ui.js +4 -0
  57. package/dist/cli/startup-ui.js.map +1 -1
  58. package/dist/core/agent-session-runtime.d.ts +11 -0
  59. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  60. package/dist/core/agent-session-runtime.js +19 -0
  61. package/dist/core/agent-session-runtime.js.map +1 -1
  62. package/dist/core/agent-session.d.ts +6 -3
  63. package/dist/core/agent-session.d.ts.map +1 -1
  64. package/dist/core/agent-session.js +21 -13
  65. package/dist/core/agent-session.js.map +1 -1
  66. package/dist/core/exec.d.ts +1 -0
  67. package/dist/core/exec.d.ts.map +1 -1
  68. package/dist/core/exec.js +4 -1
  69. package/dist/core/exec.js.map +1 -1
  70. package/dist/core/export-html/ansi-to-html.d.ts +6 -1
  71. package/dist/core/export-html/ansi-to-html.d.ts.map +1 -1
  72. package/dist/core/export-html/ansi-to-html.js +57 -20
  73. package/dist/core/export-html/ansi-to-html.js.map +1 -1
  74. package/dist/core/export-html/template.js +1 -1
  75. package/dist/core/export-html/tool-renderer.d.ts.map +1 -1
  76. package/dist/core/export-html/tool-renderer.js +2 -3
  77. package/dist/core/export-html/tool-renderer.js.map +1 -1
  78. package/dist/core/extensions/loader.d.ts.map +1 -1
  79. package/dist/core/extensions/loader.js +18 -1
  80. package/dist/core/extensions/loader.js.map +1 -1
  81. package/dist/core/extensions/runner.d.ts.map +1 -1
  82. package/dist/core/extensions/runner.js +5 -0
  83. package/dist/core/extensions/runner.js.map +1 -1
  84. package/dist/core/extensions/types.d.ts +5 -0
  85. package/dist/core/extensions/types.d.ts.map +1 -1
  86. package/dist/core/extensions/types.js.map +1 -1
  87. package/dist/core/model-resolver.d.ts +0 -8
  88. package/dist/core/model-resolver.d.ts.map +1 -1
  89. package/dist/core/model-resolver.js +3 -67
  90. package/dist/core/model-resolver.js.map +1 -1
  91. package/dist/core/package-manager.d.ts +16 -0
  92. package/dist/core/package-manager.d.ts.map +1 -1
  93. package/dist/core/package-manager.js +45 -2
  94. package/dist/core/package-manager.js.map +1 -1
  95. package/dist/core/remote-catalog-provider.d.ts.map +1 -1
  96. package/dist/core/remote-catalog-provider.js +7 -0
  97. package/dist/core/remote-catalog-provider.js.map +1 -1
  98. package/dist/core/resource-loader.d.ts +5 -1
  99. package/dist/core/resource-loader.d.ts.map +1 -1
  100. package/dist/core/resource-loader.js +2 -0
  101. package/dist/core/resource-loader.js.map +1 -1
  102. package/dist/core/session-manager.d.ts.map +1 -1
  103. package/dist/core/session-manager.js +45 -36
  104. package/dist/core/session-manager.js.map +1 -1
  105. package/dist/core/session-ownership.js +15 -1
  106. package/dist/core/session-ownership.js.map +1 -1
  107. package/dist/core/tools/find.d.ts.map +1 -1
  108. package/dist/core/tools/find.js +27 -16
  109. package/dist/core/tools/find.js.map +1 -1
  110. package/dist/core/tools/grep.js +1 -1
  111. package/dist/core/tools/grep.js.map +1 -1
  112. package/dist/core/tools/output-accumulator.d.ts.map +1 -1
  113. package/dist/core/tools/output-accumulator.js +4 -1
  114. package/dist/core/tools/output-accumulator.js.map +1 -1
  115. package/dist/core/tools/read.d.ts +5 -0
  116. package/dist/core/tools/read.d.ts.map +1 -1
  117. package/dist/core/tools/read.js +10 -15
  118. package/dist/core/tools/read.js.map +1 -1
  119. package/dist/core/tools/renderers/read.d.ts.map +1 -1
  120. package/dist/core/tools/renderers/read.js +6 -2
  121. package/dist/core/tools/renderers/read.js.map +1 -1
  122. package/dist/extensions/llama/provider.d.ts +1 -1
  123. package/dist/extensions/llama/provider.d.ts.map +1 -1
  124. package/dist/extensions/llama/provider.js +6 -4
  125. package/dist/extensions/llama/provider.js.map +1 -1
  126. package/dist/extensions/mcp/index.d.ts.map +1 -1
  127. package/dist/extensions/mcp/index.js +4 -7
  128. package/dist/extensions/mcp/index.js.map +1 -1
  129. package/dist/main.d.ts.map +1 -1
  130. package/dist/main.js +39 -16
  131. package/dist/main.js.map +1 -1
  132. package/dist/modes/diagnostics-stderr.d.ts +4 -0
  133. package/dist/modes/diagnostics-stderr.d.ts.map +1 -0
  134. package/dist/modes/diagnostics-stderr.js +11 -0
  135. package/dist/modes/diagnostics-stderr.js.map +1 -0
  136. package/dist/modes/interactive/components/assistant-message.d.ts +2 -1
  137. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
  138. package/dist/modes/interactive/components/assistant-message.js +9 -3
  139. package/dist/modes/interactive/components/assistant-message.js.map +1 -1
  140. package/dist/modes/interactive/components/bash-execution.js.map +1 -1
  141. package/dist/modes/interactive/components/config-selector.d.ts.map +1 -1
  142. package/dist/modes/interactive/components/config-selector.js +5 -2
  143. package/dist/modes/interactive/components/config-selector.js.map +1 -1
  144. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
  145. package/dist/modes/interactive/components/model-selector.js +5 -2
  146. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  147. package/dist/modes/interactive/components/oauth-selector.d.ts +1 -1
  148. package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -1
  149. package/dist/modes/interactive/components/oauth-selector.js +7 -3
  150. package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
  151. package/dist/modes/interactive/components/radius-login-selector.d.ts.map +1 -1
  152. package/dist/modes/interactive/components/radius-login-selector.js +2 -1
  153. package/dist/modes/interactive/components/radius-login-selector.js.map +1 -1
  154. package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -1
  155. package/dist/modes/interactive/components/scoped-models-selector.js +9 -1
  156. package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -1
  157. package/dist/modes/interactive/components/session-selector.d.ts +8 -1
  158. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
  159. package/dist/modes/interactive/components/session-selector.js +41 -9
  160. package/dist/modes/interactive/components/session-selector.js.map +1 -1
  161. package/dist/modes/interactive/components/settings-submenu.d.ts +1 -1
  162. package/dist/modes/interactive/components/settings-submenu.d.ts.map +1 -1
  163. package/dist/modes/interactive/components/settings-submenu.js +5 -1
  164. package/dist/modes/interactive/components/settings-submenu.js.map +1 -1
  165. package/dist/modes/interactive/components/themed-text.d.ts +1 -1
  166. package/dist/modes/interactive/components/themed-text.d.ts.map +1 -1
  167. package/dist/modes/interactive/components/themed-text.js.map +1 -1
  168. package/dist/modes/interactive/components/thinking-selector.d.ts.map +1 -1
  169. package/dist/modes/interactive/components/thinking-selector.js +5 -1
  170. package/dist/modes/interactive/components/thinking-selector.js.map +1 -1
  171. package/dist/modes/interactive/components/tool-execution.d.ts +1 -1
  172. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  173. package/dist/modes/interactive/components/tool-execution.js +3 -1
  174. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  175. package/dist/modes/interactive/components/user-message.d.ts +2 -1
  176. package/dist/modes/interactive/components/user-message.d.ts.map +1 -1
  177. package/dist/modes/interactive/components/user-message.js +9 -3
  178. package/dist/modes/interactive/components/user-message.js.map +1 -1
  179. package/dist/modes/interactive/components/visual-truncate.d.ts +2 -2
  180. package/dist/modes/interactive/components/visual-truncate.d.ts.map +1 -1
  181. package/dist/modes/interactive/components/visual-truncate.js.map +1 -1
  182. package/dist/modes/interactive/interactive-mode.d.ts +1 -1
  183. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  184. package/dist/modes/interactive/interactive-mode.js +71 -36
  185. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  186. package/dist/modes/interactive/session-share.js +2 -0
  187. package/dist/modes/interactive/session-share.js.map +1 -1
  188. package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
  189. package/dist/modes/interactive/theme/theme.js +1 -0
  190. package/dist/modes/interactive/theme/theme.js.map +1 -1
  191. package/dist/modes/print-mode.d.ts.map +1 -1
  192. package/dist/modes/print-mode.js +16 -13
  193. package/dist/modes/print-mode.js.map +1 -1
  194. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  195. package/dist/modes/rpc/rpc-mode.js +15 -23
  196. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  197. package/dist/package-manager-cli.d.ts.map +1 -1
  198. package/dist/package-manager-cli.js +14 -1
  199. package/dist/package-manager-cli.js.map +1 -1
  200. package/dist/utils/changelog.d.ts.map +1 -1
  201. package/dist/utils/changelog.js +3 -2
  202. package/dist/utils/changelog.js.map +1 -1
  203. package/dist/utils/flush-stdout.d.ts +8 -0
  204. package/dist/utils/flush-stdout.d.ts.map +1 -0
  205. package/dist/utils/flush-stdout.js +23 -0
  206. package/dist/utils/flush-stdout.js.map +1 -0
  207. package/docs/extensions.md +4 -4
  208. package/docs/models-configuration.md +4 -3
  209. package/docs/nvidia-rtx-llama-cpp.md +5 -5
  210. package/docs/providers.md +4 -2
  211. package/docs/rpc-commands.md +1 -1
  212. package/docs/tui.md +2 -0
  213. package/examples/extensions/gondolin/index.ts +4 -7
  214. package/package.json +10 -10
  215. package/schemas/models.schema.json +2 -2
  216. package/dist/bundle/chunks/chunk-CF5GWZHW.js +0 -31
  217. package/dist/bundle/chunks/chunk-GFUN2N5K.js +0 -2
  218. package/dist/bundle/chunks/chunk-QN4TOIZN.js +0 -16
  219. package/dist/bundle/chunks/chunk-V7SLUK6A.js +0 -44
  220. package/dist/bundle/chunks/chunk-YTPJCXUB.js +0 -30
  221. package/dist/bundle/chunks/chunk-ZGYS4UTC.js +0 -2
  222. package/dist/bundle/chunks/google-generative-ai-D5B6W47J.js +0 -2
  223. package/dist/bundle/chunks/google-vertex-U4H5YDEW.js +0 -2
  224. package/dist/bundle/chunks/openai-codex-responses-TEQRB65N.js +0 -10
  225. package/dist/utils/deprecation.d.ts +0 -4
  226. package/dist/utils/deprecation.d.ts.map +0 -1
  227. package/dist/utils/deprecation.js +0 -13
  228. package/dist/utils/deprecation.js.map +0 -1
@@ -240,7 +240,21 @@ function collectLiveOwners() {
240
240
  removeStaleRecord(join(root, file));
241
241
  continue;
242
242
  }
243
- const record = JSON.parse(readFileSync(join(root, file), "utf8"));
243
+ let raw;
244
+ try {
245
+ raw = readFileSync(join(root, file), "utf8");
246
+ }
247
+ catch (error) {
248
+ // The owner removed its record after readdir listed it, which means it exited: the same
249
+ // conclusion the missing-process check above reaches. Concurrent scanners hit this routinely,
250
+ // and without it the scan throws, so every gate that asks who holds a session fails with a
251
+ // filesystem error instead of an answer.
252
+ if (error.code !== "ENOENT")
253
+ throw error;
254
+ removeStaleRecord(join(root, file));
255
+ continue;
256
+ }
257
+ const record = JSON.parse(raw);
244
258
  if (!record ||
245
259
  typeof record !== "object" ||
246
260
  !("start" in record) ||
@@ -1 +1 @@
1
- {"version":3,"file":"session-ownership.js","sourceRoot":"","sources":["../../src/core/session-ownership.ts"],"names":[],"mappings":"AAAA,yEAAyE;AAEzE,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EACN,UAAU,EACV,SAAS,EACT,SAAS,EACT,WAAW,EACX,YAAY,EACZ,UAAU,EACV,SAAS,EACT,UAAU,EACV,aAAa,GACb,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,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AAI,CAAC,CAAC,CAAC;YACpC,SAAS;QACV,CAAC;QACD,MAAM,MAAM,GAAY,IAAI,CAAC,KAAK,CAAC,YAAY,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;QAC3E,IACC,CAAC,MAAM;YACP,OAAO,MAAM,KAAK,QAAQ;YAC1B,CAAC,CAAC,OAAO,IAAI,MAAM,CAAC;YACpB,CAAC,CAAC,UAAU,IAAI,MAAM,CAAC;YACvB,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,EAC9B,CAAC;YACF,MAAM,IAAI,KAAK,CAAC,qCAAqC,IAAI,EAAE,CAAC,CAAC;QAC9D,CAAC;QACD,IAAI,MAAM,CAAC,KAAK,KAAK,IAAI,EAAE,CAAC;YAC3B,yFAAyF;YACzF,mCAAmC;YACnC,IAAI,KAAK,KAAK,SAAS,IAAI,MAAM,CAAC,KAAK,KAAK,KAAK,EAAE,CAAC;gBACnD,iBAAiB,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC;gBACpC,SAAS;YACV,CAAC;QACF,CAAC;aAAM,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,EAAE,CAAC;YAChC,wFAAwF;YACxF,iBAAiB,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC;YACpC,SAAS;QACV,CAAC;QACD,MAAM,CAAC,IAAI,CAAC,EAAE,GAAG,EAAE,QAAQ,EAAE,MAAM,CAAC,QAAQ,EAAE,CAAC,CAAC;IACjD,CAAC;IACD,OAAO,MAAM,CAAC;AACf,CAAC","sourcesContent":["// Coordinate session users and relocation within one local user account.\n\nimport { execFileSync } from \"node:child_process\";\nimport { createHash } from \"node:crypto\";\nimport {\n\texistsSync,\n\tlstatSync,\n\tmkdirSync,\n\treaddirSync,\n\treadFileSync,\n\trenameSync,\n\trmdirSync,\n\tunlinkSync,\n\twriteFileSync,\n} from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { basename, dirname, join, resolve } from \"node:path\";\nimport { canonicalizePath } from \"../utils/paths.ts\";\n\nconst root = join(tmpdir(), `pi-session-owners-${process.getuid?.() ?? \"user\"}`);\nconst sessions = new Map<string, number>();\nconst gateWait = new Int32Array(new SharedArrayBuffer(4));\nconst gateTimeoutMs = 2000;\nlet holdingGate = false;\n\n/** Serialize registration and moves; an abandoned gate fails closed rather than guessing. */\nexport function withSessionOwnershipGate<T>(operation: () => T): T {\n\tif (holdingGate) throw new Error(\"Session ownership operations cannot acquire the gate recursively.\");\n\tmkdirSync(root, { recursive: true, mode: 0o700 });\n\t// POSIX mode bits are only meaningful where they are reported. On Windows the per-user\n\t// temporary directory is the isolation boundary and lstat reports a fixed mode.\n\tconst info = lstatSync(root);\n\tconst uid = process.getuid?.();\n\tif (!info.isDirectory() || (uid !== undefined && (info.uid !== uid || (info.mode & 0o077) !== 0))) {\n\t\tthrow new Error(`Unsafe session ownership directory: ${root}`);\n\t}\n\tconst gate = join(root, \"gate\");\n\tconst deadline = performance.now() + gateTimeoutMs;\n\tfor (;;) {\n\t\ttry {\n\t\t\tmkdirSync(gate, { mode: 0o700 });\n\t\t\tbreak;\n\t\t} catch (error) {\n\t\t\tif ((error as NodeJS.ErrnoException).code !== \"EEXIST\") throw error;\n\t\t\tconst remaining = deadline - performance.now();\n\t\t\tif (remaining <= 0) {\n\t\t\t\tthrow new Error(`Session ownership is busy. Retry later. If a process crashed, inspect ${gate}.`);\n\t\t\t}\n\t\t\t// SessionManager's API is synchronous. Wait only for other processes, never for work on this event loop.\n\t\t\tAtomics.wait(gateWait, 0, 0, Math.min(25, remaining));\n\t\t}\n\t}\n\tholdingGate = true;\n\ttry {\n\t\treturn operation();\n\t} finally {\n\t\tholdingGate = false;\n\t\trmdirSync(gate);\n\t}\n}\n\n/** Register a manager's session before reading it, releasing its previous registration. */\nexport function changeSessionOwnership(previous: string | undefined, next: string | undefined): void {\n\tif (previous === next) return;\n\twithSessionOwnershipGate(() => {\n\t\tif (next && !existsSync(next) && existsSync(movedMarker(next)))\n\t\t\tthrow new Error(\"This session has moved. Refresh the session picker.\");\n\t\tconst updated = new Map(sessions);\n\t\tif (previous) {\n\t\t\tconst path = canonicalSessionPath(previous);\n\t\t\tconst count = updated.get(path) ?? 0;\n\t\t\tif (count <= 1) updated.delete(path);\n\t\t\telse updated.set(path, count - 1);\n\t\t}\n\t\tif (next) {\n\t\t\tconst path = canonicalSessionPath(next);\n\t\t\tupdated.set(path, (updated.get(path) ?? 0) + 1);\n\t\t}\n\t\t// A null start means the platform cannot distinguish a PID from a later process that reused it.\n\t\tconst temporary = join(root, `${process.pid}.tmp`);\n\t\twriteFileSync(\n\t\t\ttemporary,\n\t\t\tJSON.stringify({ start: processIdentity(process.pid) ?? null, sessions: [...updated.keys()] }),\n\t\t\t{ mode: 0o600 },\n\t\t);\n\t\trenameSync(temporary, join(root, `${process.pid}.json`));\n\t\tsessions.clear();\n\t\tfor (const [path, count] of updated) sessions.set(path, count);\n\t});\n}\n\n/** Hold a counted session reference during a synchronous read/copy/mutation operation. */\nexport function withSessionFileUsage<T>(path: string, operation: () => T): T {\n\tchangeSessionOwnership(undefined, path);\n\ttry {\n\t\treturn operation();\n\t} finally {\n\t\tchangeSessionOwnership(path, undefined);\n\t}\n}\n\nfunction canonicalSessionPath(path: string): string {\n\tconst absolute = resolve(path);\n\treturn canonicalizePath(join(canonicalizePath(dirname(absolute)), basename(absolute)));\n}\n\nfunction movedMarker(path: string): string {\n\treturn join(root, `${createHash(\"sha256\").update(canonicalSessionPath(path)).digest(\"hex\")}.moved`);\n}\n\n/** Prevent a concurrent opener from recreating the old path after relocation. */\nexport function markSessionMoved(path: string, destination: string): void {\n\twriteFileSync(movedMarker(path), destination, { mode: 0o600 });\n}\n\n/** Roll back a relocation marker when the source was not removed. */\nexport function unmarkSessionMoved(path: string): void {\n\tunlinkSync(movedMarker(path));\n}\n\n// Linux only: stat field 22 distinguishes a PID from a later process that reused it.\n// comm can contain spaces and parentheses, so fields are read after the last ')'.\nfunction linuxProcessStart(pid: number): string {\n\tconst stat = readFileSync(`/proc/${pid}/stat`, \"utf8\");\n\treturn stat.slice(stat.lastIndexOf(\")\") + 2).split(\" \")[19];\n}\n\nconst processIdentity = process.platform === \"linux\" ? linuxProcessStart : () => undefined;\n\n/**\n * Drop a record whose owner is provably gone. This is cleanup only: a failed removal must never\n * affect the safety decision, because Windows can report EPERM or EBUSY for a file another\n * process still has open.\n */\nfunction removeStaleRecord(path: string): void {\n\ttry {\n\t\tunlinkSync(path);\n\t} catch {\n\t\t// The next move retries the cleanup. A surviving stale record only ever causes a refusal.\n\t}\n}\n\n/**\n * Report whether a recorded owner process is still running. Anything other than a confirmed\n * absence counts as running, including a permission error, so an uncertain check never allows\n * the operation. On non-Linux platforms a reused PID is indistinguishable and also counts as\n * running, which can refuse an operation that would have been safe.\n */\nfunction processIsLive(pid: number): boolean {\n\ttry {\n\t\tprocess.kill(pid, 0);\n\t\treturn true;\n\t} catch (error) {\n\t\treturn (error as NodeJS.ErrnoException).code !== \"ESRCH\";\n\t}\n}\n\n/** Refuse live users of this file and, on Linux, untracked Pi processes. Caller must hold the ownership gate. */\nexport function assertSessionUnused(path: string): void {\n\tconst canonical = canonicalSessionPath(path);\n\tconst owners = collectLiveOwners();\n\trefuseWhileOpen(owners, canonical, \"moving\");\n\t// Relocation splits a session across two paths if any process keeps the old one open, including\n\t// a process that cannot be inspected, so an untracked Pi blocks a move with no override.\n\t// Detecting Pi processes that predate ownership requires scanning the process table, and the\n\t// portable process list is not reliable enough to do so outside Linux. Those platforms only\n\t// enforce ownership registered by cooperating Pi instances.\n\tconst untracked = findUntrackedPiPid(owners);\n\tif (untracked !== undefined)\n\t\tthrow new Error(\n\t\t\t`Pi process ${untracked} does not report session ownership. Close older Pi instances before moving.`,\n\t\t);\n}\n\n/**\n * Refuse a delete where the harm is proven, and allow an override where it is only possible. A live\n * process that registered this file always blocks it, with or without the override: deleting a session\n * out from under its writer is the same loss as forking its history. An untracked Pi cannot be\n * inspected at all, so it blocks too, but `PI_ALLOW_SHARED_SESSION` clears that case. Without the\n * override, one unrelated official Pi on Linux would make session cleanup impossible, and the worst\n * outcome it prevents is a process writing to a removed file rather than lost conversation.\n * Caller must hold the ownership gate.\n */\nexport function assertSessionDeletable(path: string): void {\n\tconst canonical = canonicalSessionPath(path);\n\tconst owners = collectLiveOwners();\n\trefuseWhileOpen(owners, canonical, \"deleting\");\n\tif (process.env.PI_ALLOW_SHARED_SESSION) return;\n\tconst untracked = findUntrackedPiPid(owners);\n\tif (untracked !== undefined)\n\t\tthrow new Error(\n\t\t\t`Pi process ${untracked} does not report session ownership, so it may hold this session. Close it, or set PI_ALLOW_SHARED_SESSION to delete anyway.`,\n\t\t);\n}\n\nfunction refuseWhileOpen(owners: LiveOwner[], canonical: string, purpose: string): void {\n\tfor (const owner of owners) {\n\t\tif (owner.sessions.includes(canonical))\n\t\t\tthrow new Error(`Session is open in process ${owner.pid}. Close it before ${purpose}.`);\n\t}\n}\n\n/** First Pi process of this user that runs without an ownership record, if any. Linux only. */\nfunction findUntrackedPiPid(owners: LiveOwner[]): number | undefined {\n\tif (process.platform !== \"linux\") return undefined;\n\tconst registered = new Set(owners.map((owner) => owner.pid));\n\tconst processes = execFileSync(\"ps\", [\"-u\", String(process.getuid!()), \"-o\", \"pid=,comm=,args=\"], {\n\t\tencoding: \"utf8\",\n\t});\n\tfor (const line of processes.split(\"\\n\")) {\n\t\tconst match = line.trim().match(/^(\\d+)\\s+(\\S+)\\s+(.*)$/);\n\t\tif (!match) continue;\n\t\tconst pid = Number(match[1]);\n\t\tif (pid === process.pid || registered.has(pid)) continue;\n\t\tconst isPi =\n\t\t\tmatch[2] === \"pi\" ||\n\t\t\t/(?:^|\\s)\\S*(?:pi-coding-agent\\/(?:dist|src)\\/cli\\.(?:js|ts)|\\/pi\\/packages\\/coding-agent\\/src\\/cli\\.ts)(?:\\s|$)/.test(\n\t\t\t\tmatch[3],\n\t\t\t);\n\t\tif (isPi) return pid;\n\t}\n\treturn undefined;\n}\n\n/**\n * Refuse resuming a session a live Pi already holds. Appends carry the writer's own leaf, so two\n * writers on one file fork its history and a later read follows the branch that appended last,\n * hiding the other one without warning. This process's own registrations never refuse, so\n * re-selecting the current session stays a no-op and unrelated sessions are unaffected. Returns\n * the message instead of throwing so the interactive picker can refuse without ending its session.\n * Set PI_ALLOW_SHARED_SESSION to resume anyway.\n */\nexport function getSessionOpenRefusal(path: string): string | undefined {\n\tif (process.env.PI_ALLOW_SHARED_SESSION) return undefined;\n\tconst canonical = canonicalSessionPath(path);\n\tfor (const owner of collectLiveOwners()) {\n\t\tif (owner.pid === process.pid) continue;\n\t\tif (owner.sessions.includes(canonical))\n\t\t\treturn `This session is open in process ${owner.pid}. Close that Pi first, or set PI_ALLOW_SHARED_SESSION to resume anyway. Two writers on one session fork its history: only the branch written last stays visible.`;\n\t}\n\treturn undefined;\n}\n\ninterface LiveOwner {\n\tpid: number;\n\tsessions: unknown[];\n}\n\n/**\n * Owners that a record claims are running, after records proven stale are dropped. Removal is\n * idempotent and its failure is ignored, so this is safe with and without the ownership gate.\n * Records are written only by Pi in a directory only this user can read.\n */\nfunction collectLiveOwners(): LiveOwner[] {\n\tconst owners: LiveOwner[] = [];\n\tfor (const file of readdirSync(root)) {\n\t\tif (!/^\\d+\\.json$/.test(file)) continue;\n\t\tconst pid = Number(file.split(\".\")[0]);\n\t\tlet start: string | undefined;\n\t\ttry {\n\t\t\tstart = processIdentity(pid);\n\t\t} catch (error) {\n\t\t\tif ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n\t\t\tremoveStaleRecord(join(root, file));\n\t\t\tcontinue;\n\t\t}\n\t\tconst record: unknown = JSON.parse(readFileSync(join(root, file), \"utf8\"));\n\t\tif (\n\t\t\t!record ||\n\t\t\ttypeof record !== \"object\" ||\n\t\t\t!(\"start\" in record) ||\n\t\t\t!(\"sessions\" in record) ||\n\t\t\t!Array.isArray(record.sessions)\n\t\t) {\n\t\t\tthrow new Error(`Invalid session ownership record: ${file}`);\n\t\t}\n\t\tif (record.start !== null) {\n\t\t\t// Linux records carry a start identity. A mismatch means another process reused the PID,\n\t\t\t// so the record is provably stale.\n\t\t\tif (start === undefined || record.start !== start) {\n\t\t\t\tremoveStaleRecord(join(root, file));\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t} else if (!processIsLive(pid)) {\n\t\t\t// Without a start identity, only a PID the OS confirms is gone proves the owner exited.\n\t\t\tremoveStaleRecord(join(root, file));\n\t\t\tcontinue;\n\t\t}\n\t\towners.push({ pid, sessions: record.sessions });\n\t}\n\treturn owners;\n}\n"]}
1
+ {"version":3,"file":"session-ownership.js","sourceRoot":"","sources":["../../src/core/session-ownership.ts"],"names":[],"mappings":"AAAA,yEAAyE;AAEzE,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EACN,UAAU,EACV,SAAS,EACT,SAAS,EACT,WAAW,EACX,YAAY,EACZ,UAAU,EACV,SAAS,EACT,UAAU,EACV,aAAa,GACb,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC7D,OAAO,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAErD,MAAM,IAAI,GAAG,IAAI,CAAC,MAAM,EAAE,EAAE,qBAAqB,OAAO,CAAC,MAAM,EAAE,EAAE,IAAI,MAAM,EAAE,CAAC,CAAC;AACjF,MAAM,QAAQ,GAAG,IAAI,GAAG,EAAkB,CAAC;AAC3C,MAAM,QAAQ,GAAG,IAAI,UAAU,CAAC,IAAI,iBAAiB,CAAC,CAAC,CAAC,CAAC,CAAC;AAC1D,MAAM,aAAa,GAAG,IAAI,CAAC;AAC3B,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AC,CAAC,CAAC;YACpC,SAAS;QACV,CAAC;QACD,MAAM,MAAM,GAAY,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;QACxC,IACC,CAAC,MAAM;YACP,OAAO,MAAM,KAAK,QAAQ;YAC1B,CAAC,CAAC,OAAO,IAAI,MAAM,CAAC;YACpB,CAAC,CAAC,UAAU,IAAI,MAAM,CAAC;YACvB,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,EAC9B,CAAC;YACF,MAAM,IAAI,KAAK,CAAC,qCAAqC,IAAI,EAAE,CAAC,CAAC;QAC9D,CAAC;QACD,IAAI,MAAM,CAAC,KAAK,KAAK,IAAI,EAAE,CAAC;YAC3B,yFAAyF;YACzF,mCAAmC;YACnC,IAAI,KAAK,KAAK,SAAS,IAAI,MAAM,CAAC,KAAK,KAAK,KAAK,EAAE,CAAC;gBACnD,iBAAiB,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC;gBACpC,SAAS;YACV,CAAC;QACF,CAAC;aAAM,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,EAAE,CAAC;YAChC,wFAAwF;YACxF,iBAAiB,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC;YACpC,SAAS;QACV,CAAC;QACD,MAAM,CAAC,IAAI,CAAC,EAAE,GAAG,EAAE,QAAQ,EAAE,MAAM,CAAC,QAAQ,EAAE,CAAC,CAAC;IACjD,CAAC;IACD,OAAO,MAAM,CAAC;AACf,CAAC","sourcesContent":["// Coordinate session users and relocation within one local user account.\n\nimport { execFileSync } from \"node:child_process\";\nimport { createHash } from \"node:crypto\";\nimport {\n\texistsSync,\n\tlstatSync,\n\tmkdirSync,\n\treaddirSync,\n\treadFileSync,\n\trenameSync,\n\trmdirSync,\n\tunlinkSync,\n\twriteFileSync,\n} from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { basename, dirname, join, resolve } from \"node:path\";\nimport { canonicalizePath } from \"../utils/paths.ts\";\n\nconst root = join(tmpdir(), `pi-session-owners-${process.getuid?.() ?? \"user\"}`);\nconst sessions = new Map<string, number>();\nconst gateWait = new Int32Array(new SharedArrayBuffer(4));\nconst gateTimeoutMs = 2000;\nlet holdingGate = false;\n\n/** Serialize registration and moves; an abandoned gate fails closed rather than guessing. */\nexport function withSessionOwnershipGate<T>(operation: () => T): T {\n\tif (holdingGate) throw new Error(\"Session ownership operations cannot acquire the gate recursively.\");\n\tmkdirSync(root, { recursive: true, mode: 0o700 });\n\t// POSIX mode bits are only meaningful where they are reported. On Windows the per-user\n\t// temporary directory is the isolation boundary and lstat reports a fixed mode.\n\tconst info = lstatSync(root);\n\tconst uid = process.getuid?.();\n\tif (!info.isDirectory() || (uid !== undefined && (info.uid !== uid || (info.mode & 0o077) !== 0))) {\n\t\tthrow new Error(`Unsafe session ownership directory: ${root}`);\n\t}\n\tconst gate = join(root, \"gate\");\n\tconst deadline = performance.now() + gateTimeoutMs;\n\tfor (;;) {\n\t\ttry {\n\t\t\tmkdirSync(gate, { mode: 0o700 });\n\t\t\tbreak;\n\t\t} catch (error) {\n\t\t\tif ((error as NodeJS.ErrnoException).code !== \"EEXIST\") throw error;\n\t\t\tconst remaining = deadline - performance.now();\n\t\t\tif (remaining <= 0) {\n\t\t\t\tthrow new Error(`Session ownership is busy. Retry later. If a process crashed, inspect ${gate}.`);\n\t\t\t}\n\t\t\t// SessionManager's API is synchronous. Wait only for other processes, never for work on this event loop.\n\t\t\tAtomics.wait(gateWait, 0, 0, Math.min(25, remaining));\n\t\t}\n\t}\n\tholdingGate = true;\n\ttry {\n\t\treturn operation();\n\t} finally {\n\t\tholdingGate = false;\n\t\trmdirSync(gate);\n\t}\n}\n\n/** Register a manager's session before reading it, releasing its previous registration. */\nexport function changeSessionOwnership(previous: string | undefined, next: string | undefined): void {\n\tif (previous === next) return;\n\twithSessionOwnershipGate(() => {\n\t\tif (next && !existsSync(next) && existsSync(movedMarker(next)))\n\t\t\tthrow new Error(\"This session has moved. Refresh the session picker.\");\n\t\tconst updated = new Map(sessions);\n\t\tif (previous) {\n\t\t\tconst path = canonicalSessionPath(previous);\n\t\t\tconst count = updated.get(path) ?? 0;\n\t\t\tif (count <= 1) updated.delete(path);\n\t\t\telse updated.set(path, count - 1);\n\t\t}\n\t\tif (next) {\n\t\t\tconst path = canonicalSessionPath(next);\n\t\t\tupdated.set(path, (updated.get(path) ?? 0) + 1);\n\t\t}\n\t\t// A null start means the platform cannot distinguish a PID from a later process that reused it.\n\t\tconst temporary = join(root, `${process.pid}.tmp`);\n\t\twriteFileSync(\n\t\t\ttemporary,\n\t\t\tJSON.stringify({ start: processIdentity(process.pid) ?? null, sessions: [...updated.keys()] }),\n\t\t\t{ mode: 0o600 },\n\t\t);\n\t\trenameSync(temporary, join(root, `${process.pid}.json`));\n\t\tsessions.clear();\n\t\tfor (const [path, count] of updated) sessions.set(path, count);\n\t});\n}\n\n/** Hold a counted session reference during a synchronous read/copy/mutation operation. */\nexport function withSessionFileUsage<T>(path: string, operation: () => T): T {\n\tchangeSessionOwnership(undefined, path);\n\ttry {\n\t\treturn operation();\n\t} finally {\n\t\tchangeSessionOwnership(path, undefined);\n\t}\n}\n\nfunction canonicalSessionPath(path: string): string {\n\tconst absolute = resolve(path);\n\treturn canonicalizePath(join(canonicalizePath(dirname(absolute)), basename(absolute)));\n}\n\nfunction movedMarker(path: string): string {\n\treturn join(root, `${createHash(\"sha256\").update(canonicalSessionPath(path)).digest(\"hex\")}.moved`);\n}\n\n/** Prevent a concurrent opener from recreating the old path after relocation. */\nexport function markSessionMoved(path: string, destination: string): void {\n\twriteFileSync(movedMarker(path), destination, { mode: 0o600 });\n}\n\n/** Roll back a relocation marker when the source was not removed. */\nexport function unmarkSessionMoved(path: string): void {\n\tunlinkSync(movedMarker(path));\n}\n\n// Linux only: stat field 22 distinguishes a PID from a later process that reused it.\n// comm can contain spaces and parentheses, so fields are read after the last ')'.\nfunction linuxProcessStart(pid: number): string {\n\tconst stat = readFileSync(`/proc/${pid}/stat`, \"utf8\");\n\treturn stat.slice(stat.lastIndexOf(\")\") + 2).split(\" \")[19];\n}\n\nconst processIdentity = process.platform === \"linux\" ? linuxProcessStart : () => undefined;\n\n/**\n * Drop a record whose owner is provably gone. This is cleanup only: a failed removal must never\n * affect the safety decision, because Windows can report EPERM or EBUSY for a file another\n * process still has open.\n */\nfunction removeStaleRecord(path: string): void {\n\ttry {\n\t\tunlinkSync(path);\n\t} catch {\n\t\t// The next move retries the cleanup. A surviving stale record only ever causes a refusal.\n\t}\n}\n\n/**\n * Report whether a recorded owner process is still running. Anything other than a confirmed\n * absence counts as running, including a permission error, so an uncertain check never allows\n * the operation. On non-Linux platforms a reused PID is indistinguishable and also counts as\n * running, which can refuse an operation that would have been safe.\n */\nfunction processIsLive(pid: number): boolean {\n\ttry {\n\t\tprocess.kill(pid, 0);\n\t\treturn true;\n\t} catch (error) {\n\t\treturn (error as NodeJS.ErrnoException).code !== \"ESRCH\";\n\t}\n}\n\n/** Refuse live users of this file and, on Linux, untracked Pi processes. Caller must hold the ownership gate. */\nexport function assertSessionUnused(path: string): void {\n\tconst canonical = canonicalSessionPath(path);\n\tconst owners = collectLiveOwners();\n\trefuseWhileOpen(owners, canonical, \"moving\");\n\t// Relocation splits a session across two paths if any process keeps the old one open, including\n\t// a process that cannot be inspected, so an untracked Pi blocks a move with no override.\n\t// Detecting Pi processes that predate ownership requires scanning the process table, and the\n\t// portable process list is not reliable enough to do so outside Linux. Those platforms only\n\t// enforce ownership registered by cooperating Pi instances.\n\tconst untracked = findUntrackedPiPid(owners);\n\tif (untracked !== undefined)\n\t\tthrow new Error(\n\t\t\t`Pi process ${untracked} does not report session ownership. Close older Pi instances before moving.`,\n\t\t);\n}\n\n/**\n * Refuse a delete where the harm is proven, and allow an override where it is only possible. A live\n * process that registered this file always blocks it, with or without the override: deleting a session\n * out from under its writer is the same loss as forking its history. An untracked Pi cannot be\n * inspected at all, so it blocks too, but `PI_ALLOW_SHARED_SESSION` clears that case. Without the\n * override, one unrelated official Pi on Linux would make session cleanup impossible, and the worst\n * outcome it prevents is a process writing to a removed file rather than lost conversation.\n * Caller must hold the ownership gate.\n */\nexport function assertSessionDeletable(path: string): void {\n\tconst canonical = canonicalSessionPath(path);\n\tconst owners = collectLiveOwners();\n\trefuseWhileOpen(owners, canonical, \"deleting\");\n\tif (process.env.PI_ALLOW_SHARED_SESSION) return;\n\tconst untracked = findUntrackedPiPid(owners);\n\tif (untracked !== undefined)\n\t\tthrow new Error(\n\t\t\t`Pi process ${untracked} does not report session ownership, so it may hold this session. Close it, or set PI_ALLOW_SHARED_SESSION to delete anyway.`,\n\t\t);\n}\n\nfunction refuseWhileOpen(owners: LiveOwner[], canonical: string, purpose: string): void {\n\tfor (const owner of owners) {\n\t\tif (owner.sessions.includes(canonical))\n\t\t\tthrow new Error(`Session is open in process ${owner.pid}. Close it before ${purpose}.`);\n\t}\n}\n\n/** First Pi process of this user that runs without an ownership record, if any. Linux only. */\nfunction findUntrackedPiPid(owners: LiveOwner[]): number | undefined {\n\tif (process.platform !== \"linux\") return undefined;\n\tconst registered = new Set(owners.map((owner) => owner.pid));\n\tconst processes = execFileSync(\"ps\", [\"-u\", String(process.getuid!()), \"-o\", \"pid=,comm=,args=\"], {\n\t\tencoding: \"utf8\",\n\t});\n\tfor (const line of processes.split(\"\\n\")) {\n\t\tconst match = line.trim().match(/^(\\d+)\\s+(\\S+)\\s+(.*)$/);\n\t\tif (!match) continue;\n\t\tconst pid = Number(match[1]);\n\t\tif (pid === process.pid || registered.has(pid)) continue;\n\t\tconst isPi =\n\t\t\tmatch[2] === \"pi\" ||\n\t\t\t/(?:^|\\s)\\S*(?:pi-coding-agent\\/(?:dist|src)\\/cli\\.(?:js|ts)|\\/pi\\/packages\\/coding-agent\\/src\\/cli\\.ts)(?:\\s|$)/.test(\n\t\t\t\tmatch[3],\n\t\t\t);\n\t\tif (isPi) return pid;\n\t}\n\treturn undefined;\n}\n\n/**\n * Refuse resuming a session a live Pi already holds. Appends carry the writer's own leaf, so two\n * writers on one file fork its history and a later read follows the branch that appended last,\n * hiding the other one without warning. This process's own registrations never refuse, so\n * re-selecting the current session stays a no-op and unrelated sessions are unaffected. Returns\n * the message instead of throwing so the interactive picker can refuse without ending its session.\n * Set PI_ALLOW_SHARED_SESSION to resume anyway.\n */\nexport function getSessionOpenRefusal(path: string): string | undefined {\n\tif (process.env.PI_ALLOW_SHARED_SESSION) return undefined;\n\tconst canonical = canonicalSessionPath(path);\n\tfor (const owner of collectLiveOwners()) {\n\t\tif (owner.pid === process.pid) continue;\n\t\tif (owner.sessions.includes(canonical))\n\t\t\treturn `This session is open in process ${owner.pid}. Close that Pi first, or set PI_ALLOW_SHARED_SESSION to resume anyway. Two writers on one session fork its history: only the branch written last stays visible.`;\n\t}\n\treturn undefined;\n}\n\ninterface LiveOwner {\n\tpid: number;\n\tsessions: unknown[];\n}\n\n/**\n * Owners that a record claims are running, after records proven stale are dropped. Removal is\n * idempotent and its failure is ignored, so this is safe with and without the ownership gate.\n * Records are written only by Pi in a directory only this user can read.\n */\nfunction collectLiveOwners(): LiveOwner[] {\n\tconst owners: LiveOwner[] = [];\n\tfor (const file of readdirSync(root)) {\n\t\tif (!/^\\d+\\.json$/.test(file)) continue;\n\t\tconst pid = Number(file.split(\".\")[0]);\n\t\tlet start: string | undefined;\n\t\ttry {\n\t\t\tstart = processIdentity(pid);\n\t\t} catch (error) {\n\t\t\tif ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n\t\t\tremoveStaleRecord(join(root, file));\n\t\t\tcontinue;\n\t\t}\n\t\tlet raw: string;\n\t\ttry {\n\t\t\traw = readFileSync(join(root, file), \"utf8\");\n\t\t} catch (error) {\n\t\t\t// The owner removed its record after readdir listed it, which means it exited: the same\n\t\t\t// conclusion the missing-process check above reaches. Concurrent scanners hit this routinely,\n\t\t\t// and without it the scan throws, so every gate that asks who holds a session fails with a\n\t\t\t// filesystem error instead of an answer.\n\t\t\tif ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n\t\t\tremoveStaleRecord(join(root, file));\n\t\t\tcontinue;\n\t\t}\n\t\tconst record: unknown = JSON.parse(raw);\n\t\tif (\n\t\t\t!record ||\n\t\t\ttypeof record !== \"object\" ||\n\t\t\t!(\"start\" in record) ||\n\t\t\t!(\"sessions\" in record) ||\n\t\t\t!Array.isArray(record.sessions)\n\t\t) {\n\t\t\tthrow new Error(`Invalid session ownership record: ${file}`);\n\t\t}\n\t\tif (record.start !== null) {\n\t\t\t// Linux records carry a start identity. A mismatch means another process reused the PID,\n\t\t\t// so the record is provably stale.\n\t\t\tif (start === undefined || record.start !== start) {\n\t\t\t\tremoveStaleRecord(join(root, file));\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t} else if (!processIsLive(pid)) {\n\t\t\t// Without a start identity, only a PID the OS confirms is gone proves the owner exited.\n\t\t\tremoveStaleRecord(join(root, file));\n\t\t\tcontinue;\n\t\t}\n\t\towners.push({ pid, sessions: record.sessions });\n\t}\n\treturn owners;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"find.d.ts","sourceRoot":"","sources":["../../../src/core/tools/find.ts"],"names":[],"mappings":"AAGA,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAE5C,OAAO,KAAK,EAAoB,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAG/E,OAAO,EAAE,KAAK,gBAAgB,EAAsB,MAAM,8BAA8B,CAAC;AACzF,OAAO,EAAiC,KAAK,gBAAgB,EAAgB,MAAM,eAAe,CAAC;AAEnG,6FAA6F;AAC7F,wBAAgB,wBAAwB,CACvC,UAAU,EAAE,MAAM,EAClB,UAAU,EAAE,MAAM,EAClB,UAAU,GAAE,IAAI,CAAC,YAAmB,GAClC,MAAM,CAMR;AAED,QAAA,MAAM,UAAU;;;;EAMd,CAAC;AAEH,eAAO,MAAM,gCAAg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U,CAAC,CAE1G"}
@@ -17,7 +17,7 @@ export function relativizeFindResultPath(resultPath, searchPath, pathModule = pa
17
17
  }
18
18
  const findSchema = Type.Object({
19
19
  pattern: Type.String({
20
- description: "Glob pattern to match files, e.g. '*.ts', '**/*.json', or 'src/**/*.spec.ts'",
20
+ description: "Glob pattern relative to the search directory, e.g. 'src/**/*.ts'. Without '/', e.g. '*.ts', it matches file names at any depth",
21
21
  }),
22
22
  path: Type.Optional(Type.String({ description: "Directory to search in (default: current directory)" })),
23
23
  limit: Type.Optional(Type.Number({ description: "Maximum number of results (default: 1000)" })),
@@ -149,29 +149,31 @@ export function createFindToolDefinition(cwd, options) {
149
149
  if (!insideGitRepo)
150
150
  args.push("--no-require-git");
151
151
  // fd --glob matches against the basename unless --full-path is set; in --full-path
152
- // mode it matches against the absolute candidate path, so a path-containing
153
- // pattern like 'src/**/*.spec.ts' needs a leading '**/' to match anything.
152
+ // mode it matches against the absolute candidate path.
154
153
  // On Windows `\` is a path separator, so native patterns like 'src\**\*.ts' are
155
154
  // normalized to '/' (#9262). On POSIX `\` stays a glob escape character.
156
155
  let effectivePattern = process.platform === "win32" ? pattern.replaceAll("\\", "/") : pattern;
156
+ // fd's full paths never contain "/./", so "./src/*.ts" would find nothing; drop the "./".
157
+ effectivePattern = effectivePattern.replace(/^(?:\.\/)+/, "");
157
158
  const isPathPattern = effectivePattern.includes("/");
158
- if (isPathPattern &&
159
- !effectivePattern.startsWith("/") &&
160
- !effectivePattern.startsWith("**/") &&
161
- effectivePattern !== "**") {
162
- effectivePattern = `**/${effectivePattern}`;
163
- }
159
+ // fd's smart case: an all-lowercase pattern matches case-insensitively.
160
+ const ignoreCase = effectivePattern === effectivePattern.toLowerCase();
161
+ // A relative path pattern is anchored at the search path, like grep's glob (#12066):
162
+ // 'src/*.ts' finds 'src/a.ts' but not 'pkg/src/b.ts'; '**/src/*.ts' finds both.
163
+ // Absolute patterns are matched as given.
164
+ const isRelativePathPattern = isPathPattern && !path.isAbsolute(effectivePattern);
164
165
  // fd before 10.5.1 never matches --full-path globs on Windows, and workarounds for that
165
166
  // break on fd 10.5.1 (sharkdp/fd#2067). pi cannot rely on either fd version, so on
166
- // Windows fd lists every entry and minimatch matches path patterns. The options keep
167
- // fd's glob behavior: `*` matches dotfiles, `+(a|b)` is literal, and an all-lowercase
168
- // pattern matches case-insensitively (smart case). A trailing '/**' becomes '/**/*'
169
- // because minimatch's 'src/**' also matches 'src' itself and fd's does not.
167
+ // Windows fd lists every entry and minimatch matches path patterns against the path
168
+ // relative to the search path, or the absolute path for absolute patterns. The options
169
+ // keep fd's glob behavior: `*` matches dotfiles, `+(a|b)` is literal, and smart case.
170
+ // A trailing '/**' becomes '/**/*' because minimatch's 'src/**' also matches 'src'
171
+ // itself and fd's does not.
170
172
  const windowsPathMatcher = process.platform === "win32" && isPathPattern
171
173
  ? new Minimatch(effectivePattern.replace(/\/\*\*$/, "/**/*"), {
172
174
  dot: true,
173
175
  noext: true,
174
- nocase: effectivePattern === effectivePattern.toLowerCase(),
176
+ nocase: ignoreCase,
175
177
  })
176
178
  : undefined;
177
179
  if (windowsPathMatcher) {
@@ -182,6 +184,15 @@ export function createFindToolDefinition(cwd, options) {
182
184
  args.push("--glob", "--max-results", String(effectiveLimit + 1));
183
185
  if (isPathPattern)
184
186
  args.push("--full-path");
187
+ if (isRelativePathPattern) {
188
+ // fd matches the absolute path, so the pattern is prefixed with the glob-escaped
189
+ // search path. Smart case is decided by the user's pattern, not by the search
190
+ // path's letters, so it is set explicitly.
191
+ const escapedRoot = searchPath.replace(/\/+$/, "").replace(/[\\*?[\]{}]/g, "\\$&");
192
+ effectivePattern = `${escapedRoot}/${effectivePattern}`;
193
+ if (ignoreCase)
194
+ args.push("--ignore-case");
195
+ }
185
196
  args.push("--", effectivePattern, searchPath);
186
197
  }
187
198
  // An abort during the .git lookup above already rejected the call, but there was no
@@ -213,7 +224,8 @@ export function createFindToolDefinition(cwd, options) {
213
224
  const line = rawLine.replace(/\r$/, "").trim();
214
225
  if (!line)
215
226
  return;
216
- if (windowsPathMatcher && !windowsPathMatcher.match(line))
227
+ const result = relativizeFindResultPath(line, searchPath);
228
+ if (windowsPathMatcher && !windowsPathMatcher.match(isRelativePathPattern ? result : line))
217
229
  return;
218
230
  if (resultCount === effectiveLimit) {
219
231
  resultLimitReached = true;
@@ -222,7 +234,6 @@ export function createFindToolDefinition(cwd, options) {
222
234
  stopChild?.();
223
235
  return;
224
236
  }
225
- const result = relativizeFindResultPath(line, searchPath);
226
237
  resultCount++;
227
238
  if (outputBytes - 1 <= DEFAULT_MAX_BYTES)
228
239
  storedResults.push(result);
@@ -1 +1 @@
1
- {"version":3,"file":"find.js","sourceRoot":"","sources":["../../../src/core/tools/find.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAChD,OAAO,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AACtC,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AACtC,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,EAAE,UAAU,EAAE,MAAM,8BAA8B,CAAC;AAE1D,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAC3D,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAyB,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AACzF,OAAO,EAAE,iBAAiB,EAAE,UAAU,EAAyB,YAAY,EAAE,MAAM,eAAe,CAAC;AAEnG,6FAA6F;AAC7F,MAAM,UAAU,wBAAwB,CACvC,UAAkB,EAClB,UAAkB,EAClB,UAAU,GAAsB,IAAI;IAEpC,MAAM,oBAAoB,GACzB,UAAU,CAAC,QAAQ,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,UAAU,CAAC,GAAG,KAAK,IAAI,IAAI,UAAU,CAAC,QAAQ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,CACX,OAAO,CAAC;gCACP,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,YAAY,EAAE,CAAC;gCAC/C,OAAO,EAAE,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS;6BAC9D,CAAC,CACF,CAAC;wBACH,CAAC,CAAC,CAAC;oBACJ,CAAC;oBAAC,OAAO,CAAC,EAAE,CAAC;wBACZ,IAAI,MAAM,EAAE,OAAO,EAAE,CAAC;4BACrB,MAAM,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,mBAAmB,CAAC,CAAC,CAAC,CAAC;4BACrD,OAAO;wBACR,CAAC;wBACD,MAAM,KAAK,GAAG,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;wBAC5D,MAAM,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;oBAC7B,CAAC;gBACF,CAAC,CAAC,EAAE,CAAC;YACN,CAAC,CAAC,CAAC;QACJ,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 { createInterface } from \"node:readline\";\nimport { spawn } from \"child_process\";\nimport { Minimatch } from \"minimatch\";\nimport path from \"path\";\nimport { type Static, Type } from \"typebox\";\nimport { ensureTool } from \"../../utils/tools-manager.ts\";\nimport type { ExtensionContext, ToolDefinition } from \"../extensions/types.ts\";\nimport { pathExists, resolveToCwd } from \"./path-utils.ts\";\nimport { findRenderers } from \"./renderers/find.ts\";\nimport { type TypeBoxAgentTool, wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\nimport { DEFAULT_MAX_BYTES, formatSize, type TruncationResult, truncateHead } from \"./truncate.ts\";\n\n/** Relativize a find result against the search root and normalize it to posix separators. */\nexport function relativizeFindResultPath(\n\tresultPath: string,\n\tsearchPath: string,\n\tpathModule: path.PlatformPath = path,\n): string {\n\tconst hadTrailingSeparator =\n\t\tresultPath.endsWith(pathModule.sep) || (pathModule.sep === \"\\\\\" && resultPath.endsWith(\"/\"));\n\tconst relativePath = pathModule.isAbsolute(resultPath) ? pathModule.relative(searchPath, resultPath) : resultPath;\n\tconst posixPath = relativePath.split(pathModule.sep).join(\"/\");\n\treturn hadTrailingSeparator && !posixPath.endsWith(\"/\") ? `${posixPath}/` : posixPath;\n}\n\nconst findSchema = Type.Object({\n\tpattern: Type.String({\n\t\tdescription: \"Glob pattern to match files, e.g. '*.ts', '**/*.json', or 'src/**/*.spec.ts'\",\n\t}),\n\tpath: Type.Optional(Type.String({ description: \"Directory to search in (default: current directory)\" })),\n\tlimit: Type.Optional(Type.Number({ description: \"Maximum number of results (default: 1000)\" })),\n});\n\nexport const findToolSystemPromptContribution = {\n\tsnippet: \"Find files by glob pattern (respects .gitignore)\",\n\tguidelines: [],\n} as const;\n\nexport type FindToolInput = Static<typeof findSchema>;\n\nconst DEFAULT_LIMIT = 1000;\n\nexport interface FindToolDetails {\n\ttruncation?: TruncationResult;\n\tresultLimitReached?: number;\n}\n\n/**\n * Pluggable operations for the find tool.\n * Override these to delegate file search to remote systems (for example SSH).\n */\nexport interface FindOperations {\n\t/** Check if path exists */\n\texists: (absolutePath: string) => Promise<boolean> | boolean;\n\t/** Find files matching glob pattern. Returns relative or absolute paths. */\n\tglob: (pattern: string, cwd: string, options: { ignore: string[]; limit: number }) => Promise<string[]> | string[];\n}\n\nconst defaultFindOperations: FindOperations = {\n\texists: pathExists,\n\t// This is a placeholder. Actual fd execution happens in execute() when no custom glob is provided.\n\tglob: () => [],\n};\n\nexport interface FindToolOptions {\n\t/** Custom operations for find. Default: local filesystem plus fd */\n\toperations?: FindOperations;\n}\n\nexport function createFindToolDefinition(\n\tcwd: string,\n\toptions?: FindToolOptions,\n): ToolDefinition<typeof findSchema, FindToolDetails | undefined> {\n\tconst customOps = options?.operations;\n\treturn {\n\t\tname: \"find\",\n\t\tlabel: \"find\",\n\t\tdescription: `Search for files by glob pattern. Returns matching file paths relative to the search directory. Respects .gitignore. Output is truncated to ${DEFAULT_LIMIT} results or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first).`,\n\t\tpromptSnippet: findToolSystemPromptContribution.snippet,\n\t\tparameters: findSchema,\n\t\tasync execute(\n\t\t\t_toolCallId,\n\t\t\t{ pattern, path: searchDir, limit }: { pattern: string; path?: string; 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((resolve, reject) => {\n\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\treject(new Error(\"Operation aborted\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tlet settled = false;\n\t\t\t\tlet stopChild: (() => void) | undefined;\n\t\t\t\tconst settle = (fn: () => void) => {\n\t\t\t\t\tif (settled) return;\n\t\t\t\t\tsettled = true;\n\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\tstopChild = undefined;\n\t\t\t\t\tfn();\n\t\t\t\t};\n\t\t\t\tconst onAbort = () => {\n\t\t\t\t\tstopChild?.();\n\t\t\t\t\tsettle(() => reject(new Error(\"Operation aborted\")));\n\t\t\t\t};\n\t\t\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\n\t\t\t\t(async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst searchPath = resolveToCwd(searchDir || \".\", ctx?.cwd || cwd);\n\t\t\t\t\t\t// fd treats --max-results 0 as unlimited, so a limit below 1 means 1.\n\t\t\t\t\t\tconst effectiveLimit = Math.max(1, Math.floor(limit ?? DEFAULT_LIMIT));\n\t\t\t\t\t\tconst ops = customOps ?? defaultFindOperations;\n\n\t\t\t\t\t\t// If custom operations provide glob(), use that instead of fd.\n\t\t\t\t\t\tif (customOps?.glob) {\n\t\t\t\t\t\t\tif (!(await ops.exists(searchPath))) {\n\t\t\t\t\t\t\t\tsettle(() => reject(new Error(`Path not found: ${searchPath}`)));\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\t\t\t\tsettle(() => reject(new Error(\"Operation aborted\")));\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t// One result past the limit tells \"exactly N matches\" apart from \"more than N\".\n\t\t\t\t\t\t\tconst results = await ops.glob(pattern, searchPath, {\n\t\t\t\t\t\t\t\tignore: [\"**/node_modules/**\", \"**/.git/**\"],\n\t\t\t\t\t\t\t\tlimit: effectiveLimit + 1,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\t\t\t\tsettle(() => reject(new Error(\"Operation aborted\")));\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (results.length === 0) {\n\t\t\t\t\t\t\t\tsettle(() =>\n\t\t\t\t\t\t\t\t\tresolve({\n\t\t\t\t\t\t\t\t\t\tcontent: [{ type: \"text\", text: \"No files found matching pattern\" }],\n\t\t\t\t\t\t\t\t\t\tdetails: undefined,\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\treturn;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tconst resultLimitReached = results.length > effectiveLimit;\n\t\t\t\t\t\t\t// Relativize paths against the search root for stable output.\n\t\t\t\t\t\t\tconst relativized = results\n\t\t\t\t\t\t\t\t.slice(0, effectiveLimit)\n\t\t\t\t\t\t\t\t.map((p) => relativizeFindResultPath(p, searchPath));\n\t\t\t\t\t\t\tconst rawOutput = relativized.join(\"\\n\");\n\t\t\t\t\t\t\tconst truncation = truncateHead(rawOutput, { maxLines: Number.MAX_SAFE_INTEGER });\n\t\t\t\t\t\t\tlet resultOutput = truncation.content;\n\t\t\t\t\t\t\tconst details: FindToolDetails = {};\n\t\t\t\t\t\t\tconst notices: string[] = [];\n\t\t\t\t\t\t\tif (resultLimitReached) {\n\t\t\t\t\t\t\t\tnotices.push(`${effectiveLimit} results limit reached`);\n\t\t\t\t\t\t\t\tdetails.resultLimitReached = effectiveLimit;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (truncation.truncated) {\n\t\t\t\t\t\t\t\tnotices.push(`${formatSize(DEFAULT_MAX_BYTES)} limit reached`);\n\t\t\t\t\t\t\t\tdetails.truncation = truncation;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (notices.length > 0) {\n\t\t\t\t\t\t\t\tresultOutput += `\\n\\n[${notices.join(\". \")}]`;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tsettle(() =>\n\t\t\t\t\t\t\t\tresolve({\n\t\t\t\t\t\t\t\t\tcontent: [{ type: \"text\", text: resultOutput }],\n\t\t\t\t\t\t\t\t\tdetails: Object.keys(details).length > 0 ? details : undefined,\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Default implementation uses fd.\n\t\t\t\t\t\tconst fdPath = await ensureTool(\"fd\");\n\t\t\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\t\t\tsettle(() => reject(new Error(\"Operation aborted\")));\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!fdPath) {\n\t\t\t\t\t\t\tsettle(() => reject(new Error(\"fd is not available and could not be downloaded\")));\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst args: string[] = [\"--color=never\", \"--hidden\"];\n\n\t\t\t\t\t\t// fd normally ignores .gitignore outside git repos, so keep --no-require-git\n\t\t\t\t\t\t// there. Inside repos, use fd's default git-aware behavior so parent\n\t\t\t\t\t\t// .gitignore rules stop at nested repo boundaries:\n\t\t\t\t\t\t// https://github.com/earendil-works/pi/issues/5960\n\t\t\t\t\t\tlet insideGitRepo = false;\n\t\t\t\t\t\tfor (let current = searchPath; ; ) {\n\t\t\t\t\t\t\tif (await pathExists(path.join(current, \".git\"))) {\n\t\t\t\t\t\t\t\tinsideGitRepo = true;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst parent = path.dirname(current);\n\t\t\t\t\t\t\tif (parent === current) break;\n\t\t\t\t\t\t\tcurrent = parent;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!insideGitRepo) args.push(\"--no-require-git\");\n\n\t\t\t\t\t\t// fd --glob matches against the basename unless --full-path is set; in --full-path\n\t\t\t\t\t\t// mode it matches against the absolute candidate path, so a path-containing\n\t\t\t\t\t\t// pattern like 'src/**/*.spec.ts' needs a leading '**/' to match anything.\n\t\t\t\t\t\t// On Windows `\\` is a path separator, so native patterns like 'src\\**\\*.ts' are\n\t\t\t\t\t\t// normalized to '/' (#9262). On POSIX `\\` stays a glob escape character.\n\t\t\t\t\t\tlet effectivePattern = process.platform === \"win32\" ? pattern.replaceAll(\"\\\\\", \"/\") : pattern;\n\t\t\t\t\t\tconst isPathPattern = effectivePattern.includes(\"/\");\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tisPathPattern &&\n\t\t\t\t\t\t\t!effectivePattern.startsWith(\"/\") &&\n\t\t\t\t\t\t\t!effectivePattern.startsWith(\"**/\") &&\n\t\t\t\t\t\t\teffectivePattern !== \"**\"\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\teffectivePattern = `**/${effectivePattern}`;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// fd before 10.5.1 never matches --full-path globs on Windows, and workarounds for that\n\t\t\t\t\t\t// break on fd 10.5.1 (sharkdp/fd#2067). pi cannot rely on either fd version, so on\n\t\t\t\t\t\t// Windows fd lists every entry and minimatch matches path patterns. The options keep\n\t\t\t\t\t\t// fd's glob behavior: `*` matches dotfiles, `+(a|b)` is literal, and an all-lowercase\n\t\t\t\t\t\t// pattern matches case-insensitively (smart case). A trailing '/**' becomes '/**/*'\n\t\t\t\t\t\t// because minimatch's 'src/**' also matches 'src' itself and fd's does not.\n\t\t\t\t\t\tconst windowsPathMatcher =\n\t\t\t\t\t\t\tprocess.platform === \"win32\" && isPathPattern\n\t\t\t\t\t\t\t\t? new Minimatch(effectivePattern.replace(/\\/\\*\\*$/, \"/**/*\"), {\n\t\t\t\t\t\t\t\t\t\tdot: true,\n\t\t\t\t\t\t\t\t\t\tnoext: true,\n\t\t\t\t\t\t\t\t\t\tnocase: effectivePattern === effectivePattern.toLowerCase(),\n\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t: undefined;\n\t\t\t\t\t\tif (windowsPathMatcher) {\n\t\t\t\t\t\t\targs.push(\"--\", \"\", searchPath);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// One result past the limit tells \"exactly N matches\" apart from \"more than N\" (#7121).\n\t\t\t\t\t\t\targs.push(\"--glob\", \"--max-results\", String(effectiveLimit + 1));\n\t\t\t\t\t\t\tif (isPathPattern) args.push(\"--full-path\");\n\t\t\t\t\t\t\targs.push(\"--\", effectivePattern, searchPath);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// An abort during the .git lookup above already rejected the call, but there was no\n\t\t\t\t\t\t// child to stop yet. Do not start fd.\n\t\t\t\t\t\tif (signal?.aborted) return;\n\t\t\t\t\t\tconst child = spawn(fdPath, args, { stdio: [\"ignore\", \"pipe\", \"pipe\"] });\n\t\t\t\t\t\tconst rl = createInterface({ input: child.stdout });\n\t\t\t\t\t\tlet stderr = \"\";\n\t\t\t\t\t\t// Results within the limit, stored only up to the first one past the byte cap:\n\t\t\t\t\t\t// truncateHead drops the rest anyway, so they are counted but not kept.\n\t\t\t\t\t\tconst storedResults: string[] = [];\n\t\t\t\t\t\tlet resultCount = 0;\n\t\t\t\t\t\t// Byte size of all results within the limit, each counted with a trailing newline.\n\t\t\t\t\t\tlet outputBytes = 0;\n\t\t\t\t\t\tlet resultLimitReached = false;\n\n\t\t\t\t\t\tstopChild = () => {\n\t\t\t\t\t\t\tif (!child.killed) {\n\t\t\t\t\t\t\t\tchild.kill();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tconst cleanup = () => {\n\t\t\t\t\t\t\trl.close();\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tchild.stderr?.on(\"data\", (chunk) => {\n\t\t\t\t\t\t\tstderr += chunk.toString();\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\trl.on(\"line\", (rawLine) => {\n\t\t\t\t\t\t\tconst line = rawLine.replace(/\\r$/, \"\").trim();\n\t\t\t\t\t\t\tif (!line) return;\n\t\t\t\t\t\t\tif (windowsPathMatcher && !windowsPathMatcher.match(line)) return;\n\t\t\t\t\t\t\tif (resultCount === effectiveLimit) {\n\t\t\t\t\t\t\t\tresultLimitReached = true;\n\t\t\t\t\t\t\t\t// Without --max-results, fd keeps listing after the limit.\n\t\t\t\t\t\t\t\tif (windowsPathMatcher) stopChild?.();\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst result = relativizeFindResultPath(line, searchPath);\n\t\t\t\t\t\t\tresultCount++;\n\t\t\t\t\t\t\tif (outputBytes - 1 <= DEFAULT_MAX_BYTES) storedResults.push(result);\n\t\t\t\t\t\t\toutputBytes += Buffer.byteLength(result, \"utf-8\") + 1;\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\tchild.on(\"error\", (error) => {\n\t\t\t\t\t\t\tcleanup();\n\t\t\t\t\t\t\tsettle(() => reject(new Error(`Failed to run fd: ${error.message}`)));\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\tchild.on(\"close\", (code) => {\n\t\t\t\t\t\t\tcleanup();\n\t\t\t\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\t\t\t\tsettle(() => reject(new Error(\"Operation aborted\")));\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (code !== 0 && resultCount === 0) {\n\t\t\t\t\t\t\t\tconst errorMsg = stderr.trim() || `fd exited with code ${code}`;\n\t\t\t\t\t\t\t\tsettle(() => reject(new Error(errorMsg)));\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (resultCount === 0) {\n\t\t\t\t\t\t\t\tsettle(() =>\n\t\t\t\t\t\t\t\t\tresolve({\n\t\t\t\t\t\t\t\t\t\tcontent: [{ type: \"text\", text: \"No files found matching pattern\" }],\n\t\t\t\t\t\t\t\t\t\tdetails: undefined,\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\treturn;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// Stored results extend past the byte cap when more exist, so truncateHead decides\n\t\t\t\t\t\t\t// truncation as for the full output; only the totals need the unstored rest.\n\t\t\t\t\t\t\tconst truncation = {\n\t\t\t\t\t\t\t\t...truncateHead(storedResults.join(\"\\n\"), { maxLines: Number.MAX_SAFE_INTEGER }),\n\t\t\t\t\t\t\t\ttotalLines: resultCount,\n\t\t\t\t\t\t\t\ttotalBytes: outputBytes - 1,\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\tlet resultOutput = truncation.content;\n\t\t\t\t\t\t\tconst details: FindToolDetails = {};\n\t\t\t\t\t\t\tconst notices: string[] = [];\n\t\t\t\t\t\t\tif (resultLimitReached) {\n\t\t\t\t\t\t\t\tnotices.push(\n\t\t\t\t\t\t\t\t\t`${effectiveLimit} results limit reached. Use limit=${effectiveLimit * 2} for more, or refine pattern`,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tdetails.resultLimitReached = effectiveLimit;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (truncation.truncated) {\n\t\t\t\t\t\t\t\tnotices.push(`${formatSize(DEFAULT_MAX_BYTES)} limit reached`);\n\t\t\t\t\t\t\t\tdetails.truncation = truncation;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (notices.length > 0) {\n\t\t\t\t\t\t\t\tresultOutput += `\\n\\n[${notices.join(\". \")}]`;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tsettle(() =>\n\t\t\t\t\t\t\t\tresolve({\n\t\t\t\t\t\t\t\t\tcontent: [{ type: \"text\", text: resultOutput }],\n\t\t\t\t\t\t\t\t\tdetails: Object.keys(details).length > 0 ? details : undefined,\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t});\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\t\t\tsettle(() => reject(new Error(\"Operation aborted\")));\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst error = e instanceof Error ? e : new Error(String(e));\n\t\t\t\t\t\tsettle(() => reject(error));\n\t\t\t\t\t}\n\t\t\t\t})();\n\t\t\t});\n\t\t},\n\t\t...findRenderers,\n\t};\n}\n\nexport function createFindTool(cwd: string, options?: FindToolOptions): TypeBoxAgentTool<typeof findSchema> {\n\treturn wrapToolDefinition(createFindToolDefinition(cwd, options));\n}\n"]}
1
+ {"version":3,"file":"find.js","sourceRoot":"","sources":["../../../src/core/tools/find.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAChD,OAAO,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AACtC,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AACtC,OAAO,IAAI,MAAM,MAAM,C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AAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS;6BAC9D,CAAC,CACF,CAAC;wBACH,CAAC,CAAC,CAAC;oBACJ,CAAC;oBAAC,OAAO,CAAC,EAAE,CAAC;wBACZ,IAAI,MAAM,EAAE,OAAO,EAAE,CAAC;4BACrB,MAAM,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,mBAAmB,CAAC,CAAC,CAAC,CAAC;4BACrD,OAAO;wBACR,CAAC;wBACD,MAAM,KAAK,GAAG,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;wBAC5D,MAAM,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;oBAC7B,CAAC;gBACF,CAAC,CAAC,EAAE,CAAC;YACN,CAAC,CAAC,CAAC;QACJ,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 { createInterface } from \"node:readline\";\nimport { spawn } from \"child_process\";\nimport { Minimatch } from \"minimatch\";\nimport path from \"path\";\nimport { type Static, Type } from \"typebox\";\nimport { ensureTool } from \"../../utils/tools-manager.ts\";\nimport type { ExtensionContext, ToolDefinition } from \"../extensions/types.ts\";\nimport { pathExists, resolveToCwd } from \"./path-utils.ts\";\nimport { findRenderers } from \"./renderers/find.ts\";\nimport { type TypeBoxAgentTool, wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\nimport { DEFAULT_MAX_BYTES, formatSize, type TruncationResult, truncateHead } from \"./truncate.ts\";\n\n/** Relativize a find result against the search root and normalize it to posix separators. */\nexport function relativizeFindResultPath(\n\tresultPath: string,\n\tsearchPath: string,\n\tpathModule: path.PlatformPath = path,\n): string {\n\tconst hadTrailingSeparator =\n\t\tresultPath.endsWith(pathModule.sep) || (pathModule.sep === \"\\\\\" && resultPath.endsWith(\"/\"));\n\tconst relativePath = pathModule.isAbsolute(resultPath) ? pathModule.relative(searchPath, resultPath) : resultPath;\n\tconst posixPath = relativePath.split(pathModule.sep).join(\"/\");\n\treturn hadTrailingSeparator && !posixPath.endsWith(\"/\") ? `${posixPath}/` : posixPath;\n}\n\nconst findSchema = Type.Object({\n\tpattern: Type.String({\n\t\tdescription:\n\t\t\t\"Glob pattern relative to the search directory, e.g. 'src/**/*.ts'. Without '/', e.g. '*.ts', it matches file names at any depth\",\n\t}),\n\tpath: Type.Optional(Type.String({ description: \"Directory to search in (default: current directory)\" })),\n\tlimit: Type.Optional(Type.Number({ description: \"Maximum number of results (default: 1000)\" })),\n});\n\nexport const findToolSystemPromptContribution = {\n\tsnippet: \"Find files by glob pattern (respects .gitignore)\",\n\tguidelines: [],\n} as const;\n\nexport type FindToolInput = Static<typeof findSchema>;\n\nconst DEFAULT_LIMIT = 1000;\n\nexport interface FindToolDetails {\n\ttruncation?: TruncationResult;\n\tresultLimitReached?: number;\n}\n\n/**\n * Pluggable operations for the find tool.\n * Override these to delegate file search to remote systems (for example SSH).\n */\nexport interface FindOperations {\n\t/** Check if path exists */\n\texists: (absolutePath: string) => Promise<boolean> | boolean;\n\t/** Find files matching glob pattern. Returns relative or absolute paths. */\n\tglob: (pattern: string, cwd: string, options: { ignore: string[]; limit: number }) => Promise<string[]> | string[];\n}\n\nconst defaultFindOperations: FindOperations = {\n\texists: pathExists,\n\t// This is a placeholder. Actual fd execution happens in execute() when no custom glob is provided.\n\tglob: () => [],\n};\n\nexport interface FindToolOptions {\n\t/** Custom operations for find. Default: local filesystem plus fd */\n\toperations?: FindOperations;\n}\n\nexport function createFindToolDefinition(\n\tcwd: string,\n\toptions?: FindToolOptions,\n): ToolDefinition<typeof findSchema, FindToolDetails | undefined> {\n\tconst customOps = options?.operations;\n\treturn {\n\t\tname: \"find\",\n\t\tlabel: \"find\",\n\t\tdescription: `Search for files by glob pattern. Returns matching file paths relative to the search directory. Respects .gitignore. Output is truncated to ${DEFAULT_LIMIT} results or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first).`,\n\t\tpromptSnippet: findToolSystemPromptContribution.snippet,\n\t\tparameters: findSchema,\n\t\tasync execute(\n\t\t\t_toolCallId,\n\t\t\t{ pattern, path: searchDir, limit }: { pattern: string; path?: string; 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((resolve, reject) => {\n\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\treject(new Error(\"Operation aborted\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tlet settled = false;\n\t\t\t\tlet stopChild: (() => void) | undefined;\n\t\t\t\tconst settle = (fn: () => void) => {\n\t\t\t\t\tif (settled) return;\n\t\t\t\t\tsettled = true;\n\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\tstopChild = undefined;\n\t\t\t\t\tfn();\n\t\t\t\t};\n\t\t\t\tconst onAbort = () => {\n\t\t\t\t\tstopChild?.();\n\t\t\t\t\tsettle(() => reject(new Error(\"Operation aborted\")));\n\t\t\t\t};\n\t\t\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\n\t\t\t\t(async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst searchPath = resolveToCwd(searchDir || \".\", ctx?.cwd || cwd);\n\t\t\t\t\t\t// fd treats --max-results 0 as unlimited, so a limit below 1 means 1.\n\t\t\t\t\t\tconst effectiveLimit = Math.max(1, Math.floor(limit ?? DEFAULT_LIMIT));\n\t\t\t\t\t\tconst ops = customOps ?? defaultFindOperations;\n\n\t\t\t\t\t\t// If custom operations provide glob(), use that instead of fd.\n\t\t\t\t\t\tif (customOps?.glob) {\n\t\t\t\t\t\t\tif (!(await ops.exists(searchPath))) {\n\t\t\t\t\t\t\t\tsettle(() => reject(new Error(`Path not found: ${searchPath}`)));\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\t\t\t\tsettle(() => reject(new Error(\"Operation aborted\")));\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t// One result past the limit tells \"exactly N matches\" apart from \"more than N\".\n\t\t\t\t\t\t\tconst results = await ops.glob(pattern, searchPath, {\n\t\t\t\t\t\t\t\tignore: [\"**/node_modules/**\", \"**/.git/**\"],\n\t\t\t\t\t\t\t\tlimit: effectiveLimit + 1,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\t\t\t\tsettle(() => reject(new Error(\"Operation aborted\")));\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (results.length === 0) {\n\t\t\t\t\t\t\t\tsettle(() =>\n\t\t\t\t\t\t\t\t\tresolve({\n\t\t\t\t\t\t\t\t\t\tcontent: [{ type: \"text\", text: \"No files found matching pattern\" }],\n\t\t\t\t\t\t\t\t\t\tdetails: undefined,\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\treturn;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tconst resultLimitReached = results.length > effectiveLimit;\n\t\t\t\t\t\t\t// Relativize paths against the search root for stable output.\n\t\t\t\t\t\t\tconst relativized = results\n\t\t\t\t\t\t\t\t.slice(0, effectiveLimit)\n\t\t\t\t\t\t\t\t.map((p) => relativizeFindResultPath(p, searchPath));\n\t\t\t\t\t\t\tconst rawOutput = relativized.join(\"\\n\");\n\t\t\t\t\t\t\tconst truncation = truncateHead(rawOutput, { maxLines: Number.MAX_SAFE_INTEGER });\n\t\t\t\t\t\t\tlet resultOutput = truncation.content;\n\t\t\t\t\t\t\tconst details: FindToolDetails = {};\n\t\t\t\t\t\t\tconst notices: string[] = [];\n\t\t\t\t\t\t\tif (resultLimitReached) {\n\t\t\t\t\t\t\t\tnotices.push(`${effectiveLimit} results limit reached`);\n\t\t\t\t\t\t\t\tdetails.resultLimitReached = effectiveLimit;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (truncation.truncated) {\n\t\t\t\t\t\t\t\tnotices.push(`${formatSize(DEFAULT_MAX_BYTES)} limit reached`);\n\t\t\t\t\t\t\t\tdetails.truncation = truncation;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (notices.length > 0) {\n\t\t\t\t\t\t\t\tresultOutput += `\\n\\n[${notices.join(\". \")}]`;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tsettle(() =>\n\t\t\t\t\t\t\t\tresolve({\n\t\t\t\t\t\t\t\t\tcontent: [{ type: \"text\", text: resultOutput }],\n\t\t\t\t\t\t\t\t\tdetails: Object.keys(details).length > 0 ? details : undefined,\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Default implementation uses fd.\n\t\t\t\t\t\tconst fdPath = await ensureTool(\"fd\");\n\t\t\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\t\t\tsettle(() => reject(new Error(\"Operation aborted\")));\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!fdPath) {\n\t\t\t\t\t\t\tsettle(() => reject(new Error(\"fd is not available and could not be downloaded\")));\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst args: string[] = [\"--color=never\", \"--hidden\"];\n\n\t\t\t\t\t\t// fd normally ignores .gitignore outside git repos, so keep --no-require-git\n\t\t\t\t\t\t// there. Inside repos, use fd's default git-aware behavior so parent\n\t\t\t\t\t\t// .gitignore rules stop at nested repo boundaries:\n\t\t\t\t\t\t// https://github.com/earendil-works/pi/issues/5960\n\t\t\t\t\t\tlet insideGitRepo = false;\n\t\t\t\t\t\tfor (let current = searchPath; ; ) {\n\t\t\t\t\t\t\tif (await pathExists(path.join(current, \".git\"))) {\n\t\t\t\t\t\t\t\tinsideGitRepo = true;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst parent = path.dirname(current);\n\t\t\t\t\t\t\tif (parent === current) break;\n\t\t\t\t\t\t\tcurrent = parent;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!insideGitRepo) args.push(\"--no-require-git\");\n\n\t\t\t\t\t\t// fd --glob matches against the basename unless --full-path is set; in --full-path\n\t\t\t\t\t\t// mode it matches against the absolute candidate path.\n\t\t\t\t\t\t// On Windows `\\` is a path separator, so native patterns like 'src\\**\\*.ts' are\n\t\t\t\t\t\t// normalized to '/' (#9262). On POSIX `\\` stays a glob escape character.\n\t\t\t\t\t\tlet effectivePattern = process.platform === \"win32\" ? pattern.replaceAll(\"\\\\\", \"/\") : pattern;\n\t\t\t\t\t\t// fd's full paths never contain \"/./\", so \"./src/*.ts\" would find nothing; drop the \"./\".\n\t\t\t\t\t\teffectivePattern = effectivePattern.replace(/^(?:\\.\\/)+/, \"\");\n\t\t\t\t\t\tconst isPathPattern = effectivePattern.includes(\"/\");\n\t\t\t\t\t\t// fd's smart case: an all-lowercase pattern matches case-insensitively.\n\t\t\t\t\t\tconst ignoreCase = effectivePattern === effectivePattern.toLowerCase();\n\t\t\t\t\t\t// A relative path pattern is anchored at the search path, like grep's glob (#12066):\n\t\t\t\t\t\t// 'src/*.ts' finds 'src/a.ts' but not 'pkg/src/b.ts'; '**/src/*.ts' finds both.\n\t\t\t\t\t\t// Absolute patterns are matched as given.\n\t\t\t\t\t\tconst isRelativePathPattern = isPathPattern && !path.isAbsolute(effectivePattern);\n\t\t\t\t\t\t// fd before 10.5.1 never matches --full-path globs on Windows, and workarounds for that\n\t\t\t\t\t\t// break on fd 10.5.1 (sharkdp/fd#2067). pi cannot rely on either fd version, so on\n\t\t\t\t\t\t// Windows fd lists every entry and minimatch matches path patterns against the path\n\t\t\t\t\t\t// relative to the search path, or the absolute path for absolute patterns. The options\n\t\t\t\t\t\t// keep fd's glob behavior: `*` matches dotfiles, `+(a|b)` is literal, and smart case.\n\t\t\t\t\t\t// A trailing '/**' becomes '/**/*' because minimatch's 'src/**' also matches 'src'\n\t\t\t\t\t\t// itself and fd's does not.\n\t\t\t\t\t\tconst windowsPathMatcher =\n\t\t\t\t\t\t\tprocess.platform === \"win32\" && isPathPattern\n\t\t\t\t\t\t\t\t? new Minimatch(effectivePattern.replace(/\\/\\*\\*$/, \"/**/*\"), {\n\t\t\t\t\t\t\t\t\t\tdot: true,\n\t\t\t\t\t\t\t\t\t\tnoext: true,\n\t\t\t\t\t\t\t\t\t\tnocase: ignoreCase,\n\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t: undefined;\n\t\t\t\t\t\tif (windowsPathMatcher) {\n\t\t\t\t\t\t\targs.push(\"--\", \"\", searchPath);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// One result past the limit tells \"exactly N matches\" apart from \"more than N\" (#7121).\n\t\t\t\t\t\t\targs.push(\"--glob\", \"--max-results\", String(effectiveLimit + 1));\n\t\t\t\t\t\t\tif (isPathPattern) args.push(\"--full-path\");\n\t\t\t\t\t\t\tif (isRelativePathPattern) {\n\t\t\t\t\t\t\t\t// fd matches the absolute path, so the pattern is prefixed with the glob-escaped\n\t\t\t\t\t\t\t\t// search path. Smart case is decided by the user's pattern, not by the search\n\t\t\t\t\t\t\t\t// path's letters, so it is set explicitly.\n\t\t\t\t\t\t\t\tconst escapedRoot = searchPath.replace(/\\/+$/, \"\").replace(/[\\\\*?[\\]{}]/g, \"\\\\$&\");\n\t\t\t\t\t\t\t\teffectivePattern = `${escapedRoot}/${effectivePattern}`;\n\t\t\t\t\t\t\t\tif (ignoreCase) args.push(\"--ignore-case\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\targs.push(\"--\", effectivePattern, searchPath);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// An abort during the .git lookup above already rejected the call, but there was no\n\t\t\t\t\t\t// child to stop yet. Do not start fd.\n\t\t\t\t\t\tif (signal?.aborted) return;\n\t\t\t\t\t\tconst child = spawn(fdPath, args, { stdio: [\"ignore\", \"pipe\", \"pipe\"] });\n\t\t\t\t\t\tconst rl = createInterface({ input: child.stdout });\n\t\t\t\t\t\tlet stderr = \"\";\n\t\t\t\t\t\t// Results within the limit, stored only up to the first one past the byte cap:\n\t\t\t\t\t\t// truncateHead drops the rest anyway, so they are counted but not kept.\n\t\t\t\t\t\tconst storedResults: string[] = [];\n\t\t\t\t\t\tlet resultCount = 0;\n\t\t\t\t\t\t// Byte size of all results within the limit, each counted with a trailing newline.\n\t\t\t\t\t\tlet outputBytes = 0;\n\t\t\t\t\t\tlet resultLimitReached = false;\n\n\t\t\t\t\t\tstopChild = () => {\n\t\t\t\t\t\t\tif (!child.killed) {\n\t\t\t\t\t\t\t\tchild.kill();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tconst cleanup = () => {\n\t\t\t\t\t\t\trl.close();\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tchild.stderr?.on(\"data\", (chunk) => {\n\t\t\t\t\t\t\tstderr += chunk.toString();\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\trl.on(\"line\", (rawLine) => {\n\t\t\t\t\t\t\tconst line = rawLine.replace(/\\r$/, \"\").trim();\n\t\t\t\t\t\t\tif (!line) return;\n\t\t\t\t\t\t\tconst result = relativizeFindResultPath(line, searchPath);\n\t\t\t\t\t\t\tif (windowsPathMatcher && !windowsPathMatcher.match(isRelativePathPattern ? result : line)) return;\n\t\t\t\t\t\t\tif (resultCount === effectiveLimit) {\n\t\t\t\t\t\t\t\tresultLimitReached = true;\n\t\t\t\t\t\t\t\t// Without --max-results, fd keeps listing after the limit.\n\t\t\t\t\t\t\t\tif (windowsPathMatcher) stopChild?.();\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tresultCount++;\n\t\t\t\t\t\t\tif (outputBytes - 1 <= DEFAULT_MAX_BYTES) storedResults.push(result);\n\t\t\t\t\t\t\toutputBytes += Buffer.byteLength(result, \"utf-8\") + 1;\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\tchild.on(\"error\", (error) => {\n\t\t\t\t\t\t\tcleanup();\n\t\t\t\t\t\t\tsettle(() => reject(new Error(`Failed to run fd: ${error.message}`)));\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\tchild.on(\"close\", (code) => {\n\t\t\t\t\t\t\tcleanup();\n\t\t\t\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\t\t\t\tsettle(() => reject(new Error(\"Operation aborted\")));\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (code !== 0 && resultCount === 0) {\n\t\t\t\t\t\t\t\tconst errorMsg = stderr.trim() || `fd exited with code ${code}`;\n\t\t\t\t\t\t\t\tsettle(() => reject(new Error(errorMsg)));\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (resultCount === 0) {\n\t\t\t\t\t\t\t\tsettle(() =>\n\t\t\t\t\t\t\t\t\tresolve({\n\t\t\t\t\t\t\t\t\t\tcontent: [{ type: \"text\", text: \"No files found matching pattern\" }],\n\t\t\t\t\t\t\t\t\t\tdetails: undefined,\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\treturn;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// Stored results extend past the byte cap when more exist, so truncateHead decides\n\t\t\t\t\t\t\t// truncation as for the full output; only the totals need the unstored rest.\n\t\t\t\t\t\t\tconst truncation = {\n\t\t\t\t\t\t\t\t...truncateHead(storedResults.join(\"\\n\"), { maxLines: Number.MAX_SAFE_INTEGER }),\n\t\t\t\t\t\t\t\ttotalLines: resultCount,\n\t\t\t\t\t\t\t\ttotalBytes: outputBytes - 1,\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\tlet resultOutput = truncation.content;\n\t\t\t\t\t\t\tconst details: FindToolDetails = {};\n\t\t\t\t\t\t\tconst notices: string[] = [];\n\t\t\t\t\t\t\tif (resultLimitReached) {\n\t\t\t\t\t\t\t\tnotices.push(\n\t\t\t\t\t\t\t\t\t`${effectiveLimit} results limit reached. Use limit=${effectiveLimit * 2} for more, or refine pattern`,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tdetails.resultLimitReached = effectiveLimit;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (truncation.truncated) {\n\t\t\t\t\t\t\t\tnotices.push(`${formatSize(DEFAULT_MAX_BYTES)} limit reached`);\n\t\t\t\t\t\t\t\tdetails.truncation = truncation;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (notices.length > 0) {\n\t\t\t\t\t\t\t\tresultOutput += `\\n\\n[${notices.join(\". \")}]`;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tsettle(() =>\n\t\t\t\t\t\t\t\tresolve({\n\t\t\t\t\t\t\t\t\tcontent: [{ type: \"text\", text: resultOutput }],\n\t\t\t\t\t\t\t\t\tdetails: Object.keys(details).length > 0 ? details : undefined,\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t});\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\t\t\tsettle(() => reject(new Error(\"Operation aborted\")));\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst error = e instanceof Error ? e : new Error(String(e));\n\t\t\t\t\t\tsettle(() => reject(error));\n\t\t\t\t\t}\n\t\t\t\t})();\n\t\t\t});\n\t\t},\n\t\t...findRenderers,\n\t};\n}\n\nexport function createFindTool(cwd: string, options?: FindToolOptions): TypeBoxAgentTool<typeof findSchema> {\n\treturn wrapToolDefinition(createFindToolDefinition(cwd, options));\n}\n"]}
@@ -12,7 +12,7 @@ const grepSchema = Type.Object({
12
12
  pattern: Type.String({ description: "Search pattern (regex or literal string)" }),
13
13
  path: Type.Optional(Type.String({ description: "Directory or file to search (default: current directory)" })),
14
14
  glob: Type.Optional(Type.String({
15
- description: "Filter files by glob pattern, relative to path, e.g. '*.ts', 'src/**/*.ts' or '**/*.spec.ts'. A pattern without '/' matches file names at any depth",
15
+ description: "Filter files by glob pattern relative to path, e.g. 'src/**/*.ts'. Without '/', e.g. '*.ts', it matches file names at any depth",
16
16
  })),
17
17
  ignoreCase: Type.Optional(Type.Boolean({ description: "Case-insensitive search (default: false)" })),
18
18
  literal: Type.Optional(Type.Boolean({ description: "Treat pattern as literal string instead of regex (default: false)" })),
@@ -1 +1 @@
1
- {"version":3,"file":"grep.js","sourceRoot":"","sources":["../../../src/core/tools/grep.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,IAAI,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAChD,OAAO,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AACtC,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,EAAE,UAAU,EAAE,MAAM,8BAA8B,CAAC;AAE1D,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAC/C,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAyB,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AACzF,OAAO,EACN,iBAAiB,EACjB,UAAU,EACV,oBAAoB,EAEpB,YAAY,EACZ,YAAY,GACZ,MAAM,eAAe,CA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,CAAC;gBACF,CAAC,CAAC,EAAE,CAAC;YACN,CAAC,CAAC,CAAC;QACJ,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 { stat as fsStat } from \"node:fs/promises\";\nimport { createInterface } from \"node:readline\";\nimport { spawn } from \"child_process\";\nimport path from \"path\";\nimport { type Static, Type } from \"typebox\";\nimport { ensureTool } from \"../../utils/tools-manager.ts\";\nimport type { ExtensionContext, ToolDefinition } from \"../extensions/types.ts\";\nimport { resolveToCwd } from \"./path-utils.ts\";\nimport { grepRenderers } from \"./renderers/grep.ts\";\nimport { type TypeBoxAgentTool, wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\nimport {\n\tDEFAULT_MAX_BYTES,\n\tformatSize,\n\tGREP_MAX_LINE_LENGTH,\n\ttype TruncationResult,\n\ttruncateHead,\n\ttruncateLine,\n} from \"./truncate.ts\";\n\nconst grepSchema = Type.Object({\n\tpattern: Type.String({ description: \"Search pattern (regex or literal string)\" }),\n\tpath: Type.Optional(Type.String({ description: \"Directory or file to search (default: current directory)\" })),\n\tglob: Type.Optional(\n\t\tType.String({\n\t\t\tdescription:\n\t\t\t\t\"Filter files by glob pattern, relative to path, e.g. '*.ts', 'src/**/*.ts' or '**/*.spec.ts'. A pattern without '/' matches file names at any depth\",\n\t\t}),\n\t),\n\tignoreCase: Type.Optional(Type.Boolean({ description: \"Case-insensitive search (default: false)\" })),\n\tliteral: Type.Optional(\n\t\tType.Boolean({ description: \"Treat pattern as literal string instead of regex (default: false)\" }),\n\t),\n\tcontext: Type.Optional(\n\t\tType.Number({ description: \"Number of lines to show before and after each match (default: 0)\" }),\n\t),\n\tlimit: Type.Optional(Type.Number({ description: \"Maximum number of matches to return (default: 100)\" })),\n});\n\nexport const grepToolSystemPromptContribution = {\n\tsnippet: \"Search file contents for patterns (respects .gitignore)\",\n\tguidelines: [],\n} as const;\n\nexport type GrepToolInput = Static<typeof grepSchema>;\nconst DEFAULT_LIMIT = 100;\n\nexport interface GrepToolDetails {\n\ttruncation?: TruncationResult;\n\tmatchLimitReached?: number;\n\tlinesTruncated?: boolean;\n}\n\n/**\n * Pluggable operations for the grep tool.\n * The search itself always runs the local ripgrep; to search a remote system, override the tool's execute().\n */\nexport interface GrepOperations {\n\t/** Check if path is a directory. Throws if path does not exist. */\n\tisDirectory: (absolutePath: string) => Promise<boolean> | boolean;\n\t/**\n\t * @deprecated Ignored. Context lines come directly from ripgrep. Override the tool's execute() for remote search.\n\t */\n\treadFile?: (absolutePath: string) => Promise<string> | string;\n}\n\nconst defaultGrepOperations: GrepOperations = {\n\tisDirectory: async (p) => (await fsStat(p)).isDirectory(),\n};\n\n/** Decode a ripgrep JSON text field (path or line). Non-UTF-8 data arrives base64-encoded in `bytes`. */\nfunction decodeRgText(data: { text?: string; bytes?: string } | undefined): string {\n\tif (typeof data?.text === \"string\") return data.text;\n\tif (typeof data?.bytes === \"string\") return Buffer.from(data.bytes, \"base64\").toString(\"utf-8\");\n\treturn \"\";\n}\n\nexport interface GrepToolOptions {\n\t/** Custom operations for grep. Default: local filesystem plus ripgrep */\n\toperations?: GrepOperations;\n}\n\nexport function createGrepToolDefinition(\n\tcwd: string,\n\toptions?: GrepToolOptions,\n): ToolDefinition<typeof grepSchema, GrepToolDetails | undefined> {\n\tconst customOps = options?.operations;\n\treturn {\n\t\tname: \"grep\",\n\t\tlabel: \"grep\",\n\t\tdescription: `Search file contents for a pattern. Returns matching lines with file paths and line numbers. Respects .gitignore. Output is truncated to ${DEFAULT_LIMIT} matches or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). Long lines are truncated to ${GREP_MAX_LINE_LENGTH} chars.`,\n\t\tpromptSnippet: grepToolSystemPromptContribution.snippet,\n\t\tparameters: grepSchema,\n\t\tasync execute(\n\t\t\t_toolCallId,\n\t\t\t{\n\t\t\t\tpattern,\n\t\t\t\tpath: searchDir,\n\t\t\t\tglob,\n\t\t\t\tignoreCase,\n\t\t\t\tliteral,\n\t\t\t\tcontext,\n\t\t\t\tlimit,\n\t\t\t}: {\n\t\t\t\tpattern: string;\n\t\t\t\tpath?: string;\n\t\t\t\tglob?: string;\n\t\t\t\tignoreCase?: boolean;\n\t\t\t\tliteral?: boolean;\n\t\t\t\tcontext?: number;\n\t\t\t\tlimit?: number;\n\t\t\t},\n\t\t\tsignal?: AbortSignal,\n\t\t\t_onUpdate?,\n\t\t\tctx?: ExtensionContext,\n\t\t) {\n\t\t\treturn new Promise((resolve, reject) => {\n\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\treject(new Error(\"Operation aborted\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tlet settled = false;\n\t\t\t\tconst settle = (fn: () => void) => {\n\t\t\t\t\tif (!settled) {\n\t\t\t\t\t\tsettled = true;\n\t\t\t\t\t\tfn();\n\t\t\t\t\t}\n\t\t\t\t};\n\n\t\t\t\t(async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst rgPath = await ensureTool(\"rg\");\n\t\t\t\t\t\tif (!rgPath) {\n\t\t\t\t\t\t\tsettle(() => reject(new Error(\"ripgrep (rg) is not available and could not be downloaded\")));\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst searchPath = resolveToCwd(searchDir || \".\", ctx?.cwd || cwd);\n\t\t\t\t\t\tconst ops = customOps ?? defaultGrepOperations;\n\t\t\t\t\t\tlet isDirectory: boolean;\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tisDirectory = await ops.isDirectory(searchPath);\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\tsettle(() => reject(new Error(`Path not found: ${searchPath}`)));\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Clamp so String() never yields exponent notation, which rg rejects.\n\t\t\t\t\t\tconst contextValue =\n\t\t\t\t\t\t\tcontext && context > 0 ? Math.min(Math.floor(context), Number.MAX_SAFE_INTEGER) : 0;\n\t\t\t\t\t\tconst effectiveLimit = Math.max(1, Math.floor(limit ?? DEFAULT_LIMIT));\n\t\t\t\t\t\tconst formatPath = (filePath: string): string => {\n\t\t\t\t\t\t\tif (isDirectory) {\n\t\t\t\t\t\t\t\tconst relative = path.relative(searchPath, path.resolve(searchPath, filePath));\n\t\t\t\t\t\t\t\tif (relative && !relative.startsWith(\"..\")) {\n\t\t\t\t\t\t\t\t\treturn relative.replace(/\\\\/g, \"/\");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn path.basename(filePath);\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\t// --no-config: the tool contract (literal, glob, limit, ...) must not depend on\n\t\t\t\t\t\t// ambient user config like RIPGREP_CONFIG_PATH. Users can customize via bash or extensions.\n\t\t\t\t\t\tconst args: string[] = [\"--no-config\", \"--json\", \"--line-number\", \"--color=never\", \"--hidden\"];\n\t\t\t\t\t\tif (ignoreCase) args.push(\"--ignore-case\");\n\t\t\t\t\t\tif (literal) args.push(\"--fixed-strings\");\n\t\t\t\t\t\t// rg never matches a leading \"./\" (\"./src/*.ts\" finds nothing), so drop it; \"!\" negates.\n\t\t\t\t\t\tif (glob) args.push(\"--glob\", glob.replace(/^(!?)(?:\\.\\/)+/, \"$1\"));\n\t\t\t\t\t\t// rg emits the surrounding lines as `context` events, so no matched file is ever read here (#9276).\n\t\t\t\t\t\tif (contextValue > 0) args.push(\"--context\", String(contextValue));\n\t\t\t\t\t\t// rg roots --glob at its own cwd, so a directory search runs inside searchPath (#11807).\n\t\t\t\t\t\t// It searches \".\" because rg canonicalizes its cwd: with an absolute path, a symlinked\n\t\t\t\t\t\t// searchPath (macOS /tmp) would no longer lie under the glob root.\n\t\t\t\t\t\targs.push(\"--\", pattern, isDirectory ? \".\" : searchPath);\n\n\t\t\t\t\t\tconst child = spawn(rgPath, args, {\n\t\t\t\t\t\t\tcwd: isDirectory ? searchPath : undefined,\n\t\t\t\t\t\t\tstdio: [\"ignore\", \"pipe\", \"pipe\"],\n\t\t\t\t\t\t});\n\t\t\t\t\t\tconst rl = createInterface({ input: child.stdout });\n\t\t\t\t\t\tlet stderr = \"\";\n\t\t\t\t\t\tlet matchCount = 0;\n\t\t\t\t\t\tlet matchLimitReached = false;\n\t\t\t\t\t\tlet linesTruncated = false;\n\t\t\t\t\t\tlet aborted = false;\n\t\t\t\t\t\tlet killedDueToLimit = false;\n\t\t\t\t\t\tconst outputLines: string[] = [];\n\n\t\t\t\t\t\tconst cleanup = () => {\n\t\t\t\t\t\t\trl.close();\n\t\t\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconst stopChild = (dueToLimit = false) => {\n\t\t\t\t\t\t\tif (!child.killed) {\n\t\t\t\t\t\t\t\tkilledDueToLimit = dueToLimit;\n\t\t\t\t\t\t\t\tchild.kill();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconst onAbort = () => {\n\t\t\t\t\t\t\taborted = true;\n\t\t\t\t\t\t\tstopChild();\n\t\t\t\t\t\t};\n\t\t\t\t\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\t\t\t\tchild.stderr?.on(\"data\", (chunk) => {\n\t\t\t\t\t\t\tstderr += chunk.toString();\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\t// Size of the full output, including lines past the byte cap that are counted but not stored.\n\t\t\t\t\t\tlet outputBytes = 0;\n\t\t\t\t\t\tlet outputLineCount = 0;\n\t\t\t\t\t\tlet lastFile: string | undefined;\n\t\t\t\t\t\t// Set at the last allowed match. rg still sends that match's trailing context, kept up to\n\t\t\t\t\t\t// trailingContextEnd, and the limit notice waits for proof of one more match.\n\t\t\t\t\t\tlet limitHit = false;\n\t\t\t\t\t\tlet trailingContextEnd = 0;\n\t\t\t\t\t\tlet done = false;\n\t\t\t\t\t\tconst finish = () => {\n\t\t\t\t\t\t\tdone = true;\n\t\t\t\t\t\t\tstopChild(true);\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconst pushLine = (filePath: string, lineNumber: number, lineText: string, isMatch: boolean) => {\n\t\t\t\t\t\t\tlastFile = filePath;\n\t\t\t\t\t\t\tconst relativePath = formatPath(filePath);\n\t\t\t\t\t\t\t// Strip only the line terminator: a lone CR inside a line is content, as in the read tool.\n\t\t\t\t\t\t\tconst sanitized = lineText.replace(/\\r?\\n?$/, \"\");\n\t\t\t\t\t\t\t// Truncate long lines so grep output stays compact.\n\t\t\t\t\t\t\tconst { text: truncatedText, wasTruncated } = truncateLine(sanitized);\n\t\t\t\t\t\t\tif (wasTruncated) linesTruncated = true;\n\t\t\t\t\t\t\tconst line = isMatch\n\t\t\t\t\t\t\t\t? `${relativePath}:${lineNumber}: ${truncatedText}`\n\t\t\t\t\t\t\t\t: `${relativePath}-${lineNumber}- ${truncatedText}`;\n\t\t\t\t\t\t\t// Byte truncation below drops everything past the cap, so keep counting but stop storing (#9276).\n\t\t\t\t\t\t\t// outputBytes counts a newline after every line; the joined output has one fewer.\n\t\t\t\t\t\t\tif (outputBytes - 1 <= DEFAULT_MAX_BYTES) outputLines.push(line);\n\t\t\t\t\t\t\toutputBytes += Buffer.byteLength(line, \"utf-8\") + 1;\n\t\t\t\t\t\t\toutputLineCount++;\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\trl.on(\"line\", (line) => {\n\t\t\t\t\t\t\tif (done || !line.trim()) return;\n\t\t\t\t\t\t\tlet event: any;\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tevent = JSON.parse(line);\n\t\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst isMatch = event.type === \"match\";\n\t\t\t\t\t\t\tif (!isMatch && event.type !== \"context\") return;\n\t\t\t\t\t\t\tconst filePath = decodeRgText(event.data?.path);\n\t\t\t\t\t\t\tconst lineNumber = event.data?.line_number;\n\t\t\t\t\t\t\tif (!filePath || typeof lineNumber !== \"number\") return;\n\t\t\t\t\t\t\tconst lineText = decodeRgText(event.data?.lines);\n\t\t\t\t\t\t\tif (!limitHit) {\n\t\t\t\t\t\t\t\tpushLine(filePath, lineNumber, lineText, isMatch);\n\t\t\t\t\t\t\t\tif (!isMatch) return;\n\t\t\t\t\t\t\t\tmatchCount++;\n\t\t\t\t\t\t\t\tif (matchCount >= effectiveLimit) {\n\t\t\t\t\t\t\t\t\tlimitHit = true;\n\t\t\t\t\t\t\t\t\ttrailingContextEnd = lineNumber + contextValue;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst inWindow = filePath === lastFile && lineNumber <= trailingContextEnd;\n\t\t\t\t\t\t\t// A match inside the last match's trailing context is shown as context.\n\t\t\t\t\t\t\tif (inWindow) pushLine(filePath, lineNumber, lineText, false);\n\t\t\t\t\t\t\t// Only another match proves that the limit cut results off.\n\t\t\t\t\t\t\tif (isMatch) matchLimitReached = true;\n\t\t\t\t\t\t\tif (matchLimitReached && !(inWindow && lineNumber < trailingContextEnd)) finish();\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\tchild.on(\"error\", (error) => {\n\t\t\t\t\t\t\tcleanup();\n\t\t\t\t\t\t\tsettle(() => reject(new Error(`Failed to run ripgrep: ${error.message}`)));\n\t\t\t\t\t\t});\n\t\t\t\t\t\tchild.on(\"close\", (code) => {\n\t\t\t\t\t\t\tcleanup();\n\t\t\t\t\t\t\tif (aborted) {\n\t\t\t\t\t\t\t\tsettle(() => reject(new Error(\"Operation aborted\")));\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (!killedDueToLimit && code !== 0 && code !== 1) {\n\t\t\t\t\t\t\t\tconst errorMsg = stderr.trim() || `ripgrep exited with code ${code}`;\n\t\t\t\t\t\t\t\tsettle(() => reject(new Error(errorMsg)));\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (matchCount === 0) {\n\t\t\t\t\t\t\t\tsettle(() =>\n\t\t\t\t\t\t\t\t\tresolve({ content: [{ type: \"text\", text: \"No matches found\" }], details: undefined }),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tconst rawOutput = outputLines.join(\"\\n\");\n\t\t\t\t\t\t\t// Apply byte truncation. There is no line limit here because the match limit already capped rows.\n\t\t\t\t\t\t\tconst truncation = truncateHead(rawOutput, { maxLines: Number.MAX_SAFE_INTEGER });\n\t\t\t\t\t\t\ttruncation.totalLines = outputLineCount;\n\t\t\t\t\t\t\ttruncation.totalBytes = outputBytes - 1;\n\t\t\t\t\t\t\tlet output = truncation.content;\n\t\t\t\t\t\t\tconst details: GrepToolDetails = {};\n\t\t\t\t\t\t\t// Build actionable notices for truncation and match limits.\n\t\t\t\t\t\t\tconst notices: string[] = [];\n\t\t\t\t\t\t\tif (matchLimitReached) {\n\t\t\t\t\t\t\t\tnotices.push(\n\t\t\t\t\t\t\t\t\t`${effectiveLimit} matches limit reached. Use limit=${effectiveLimit * 2} for more, or refine pattern`,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tdetails.matchLimitReached = effectiveLimit;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (truncation.truncated) {\n\t\t\t\t\t\t\t\tnotices.push(`${formatSize(DEFAULT_MAX_BYTES)} limit reached`);\n\t\t\t\t\t\t\t\tdetails.truncation = truncation;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (linesTruncated) {\n\t\t\t\t\t\t\t\tnotices.push(\n\t\t\t\t\t\t\t\t\t`Some lines truncated to ${GREP_MAX_LINE_LENGTH} chars. Use read tool to see full lines`,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tdetails.linesTruncated = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (notices.length > 0) output += `\\n\\n[${notices.join(\". \")}]`;\n\t\t\t\t\t\t\tsettle(() =>\n\t\t\t\t\t\t\t\tresolve({\n\t\t\t\t\t\t\t\t\tcontent: [{ type: \"text\", text: output }],\n\t\t\t\t\t\t\t\t\tdetails: Object.keys(details).length > 0 ? details : undefined,\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t});\n\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\tsettle(() => reject(err as Error));\n\t\t\t\t\t}\n\t\t\t\t})();\n\t\t\t});\n\t\t},\n\t\t...grepRenderers,\n\t};\n}\n\nexport function createGrepTool(cwd: string, options?: GrepToolOptions): TypeBoxAgentTool<typeof grepSchema> {\n\treturn wrapToolDefinition(createGrepToolDefinition(cwd, options));\n}\n"]}
1
+ {"version":3,"file":"grep.js","sourceRoot":"","sources":["../../../src/core/tools/grep.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,IAAI,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAChD,OAAO,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AACtC,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,EAAE,UAAU,EAAE,MAAM,8BAA8B,CAAC;AAE1D,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAC/C,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAyB,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AACzF,OAAO,EACN,iBAAiB,EACjB,UAAU,EACV,oBAAoB,EAEpB,YAAY,EACZ,YAAY,GACZ,MAAM,e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BACpC,CAAC;gBACF,CAAC,CAAC,EAAE,CAAC;YACN,CAAC,CAAC,CAAC;QACJ,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 { stat as fsStat } from \"node:fs/promises\";\nimport { createInterface } from \"node:readline\";\nimport { spawn } from \"child_process\";\nimport path from \"path\";\nimport { type Static, Type } from \"typebox\";\nimport { ensureTool } from \"../../utils/tools-manager.ts\";\nimport type { ExtensionContext, ToolDefinition } from \"../extensions/types.ts\";\nimport { resolveToCwd } from \"./path-utils.ts\";\nimport { grepRenderers } from \"./renderers/grep.ts\";\nimport { type TypeBoxAgentTool, wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\nimport {\n\tDEFAULT_MAX_BYTES,\n\tformatSize,\n\tGREP_MAX_LINE_LENGTH,\n\ttype TruncationResult,\n\ttruncateHead,\n\ttruncateLine,\n} from \"./truncate.ts\";\n\nconst grepSchema = Type.Object({\n\tpattern: Type.String({ description: \"Search pattern (regex or literal string)\" }),\n\tpath: Type.Optional(Type.String({ description: \"Directory or file to search (default: current directory)\" })),\n\tglob: Type.Optional(\n\t\tType.String({\n\t\t\tdescription:\n\t\t\t\t\"Filter files by glob pattern relative to path, e.g. 'src/**/*.ts'. Without '/', e.g. '*.ts', it matches file names at any depth\",\n\t\t}),\n\t),\n\tignoreCase: Type.Optional(Type.Boolean({ description: \"Case-insensitive search (default: false)\" })),\n\tliteral: Type.Optional(\n\t\tType.Boolean({ description: \"Treat pattern as literal string instead of regex (default: false)\" }),\n\t),\n\tcontext: Type.Optional(\n\t\tType.Number({ description: \"Number of lines to show before and after each match (default: 0)\" }),\n\t),\n\tlimit: Type.Optional(Type.Number({ description: \"Maximum number of matches to return (default: 100)\" })),\n});\n\nexport const grepToolSystemPromptContribution = {\n\tsnippet: \"Search file contents for patterns (respects .gitignore)\",\n\tguidelines: [],\n} as const;\n\nexport type GrepToolInput = Static<typeof grepSchema>;\nconst DEFAULT_LIMIT = 100;\n\nexport interface GrepToolDetails {\n\ttruncation?: TruncationResult;\n\tmatchLimitReached?: number;\n\tlinesTruncated?: boolean;\n}\n\n/**\n * Pluggable operations for the grep tool.\n * The search itself always runs the local ripgrep; to search a remote system, override the tool's execute().\n */\nexport interface GrepOperations {\n\t/** Check if path is a directory. Throws if path does not exist. */\n\tisDirectory: (absolutePath: string) => Promise<boolean> | boolean;\n\t/**\n\t * @deprecated Ignored. Context lines come directly from ripgrep. Override the tool's execute() for remote search.\n\t */\n\treadFile?: (absolutePath: string) => Promise<string> | string;\n}\n\nconst defaultGrepOperations: GrepOperations = {\n\tisDirectory: async (p) => (await fsStat(p)).isDirectory(),\n};\n\n/** Decode a ripgrep JSON text field (path or line). Non-UTF-8 data arrives base64-encoded in `bytes`. */\nfunction decodeRgText(data: { text?: string; bytes?: string } | undefined): string {\n\tif (typeof data?.text === \"string\") return data.text;\n\tif (typeof data?.bytes === \"string\") return Buffer.from(data.bytes, \"base64\").toString(\"utf-8\");\n\treturn \"\";\n}\n\nexport interface GrepToolOptions {\n\t/** Custom operations for grep. Default: local filesystem plus ripgrep */\n\toperations?: GrepOperations;\n}\n\nexport function createGrepToolDefinition(\n\tcwd: string,\n\toptions?: GrepToolOptions,\n): ToolDefinition<typeof grepSchema, GrepToolDetails | undefined> {\n\tconst customOps = options?.operations;\n\treturn {\n\t\tname: \"grep\",\n\t\tlabel: \"grep\",\n\t\tdescription: `Search file contents for a pattern. Returns matching lines with file paths and line numbers. Respects .gitignore. Output is truncated to ${DEFAULT_LIMIT} matches or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). Long lines are truncated to ${GREP_MAX_LINE_LENGTH} chars.`,\n\t\tpromptSnippet: grepToolSystemPromptContribution.snippet,\n\t\tparameters: grepSchema,\n\t\tasync execute(\n\t\t\t_toolCallId,\n\t\t\t{\n\t\t\t\tpattern,\n\t\t\t\tpath: searchDir,\n\t\t\t\tglob,\n\t\t\t\tignoreCase,\n\t\t\t\tliteral,\n\t\t\t\tcontext,\n\t\t\t\tlimit,\n\t\t\t}: {\n\t\t\t\tpattern: string;\n\t\t\t\tpath?: string;\n\t\t\t\tglob?: string;\n\t\t\t\tignoreCase?: boolean;\n\t\t\t\tliteral?: boolean;\n\t\t\t\tcontext?: number;\n\t\t\t\tlimit?: number;\n\t\t\t},\n\t\t\tsignal?: AbortSignal,\n\t\t\t_onUpdate?,\n\t\t\tctx?: ExtensionContext,\n\t\t) {\n\t\t\treturn new Promise((resolve, reject) => {\n\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\treject(new Error(\"Operation aborted\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tlet settled = false;\n\t\t\t\tconst settle = (fn: () => void) => {\n\t\t\t\t\tif (!settled) {\n\t\t\t\t\t\tsettled = true;\n\t\t\t\t\t\tfn();\n\t\t\t\t\t}\n\t\t\t\t};\n\n\t\t\t\t(async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst rgPath = await ensureTool(\"rg\");\n\t\t\t\t\t\tif (!rgPath) {\n\t\t\t\t\t\t\tsettle(() => reject(new Error(\"ripgrep (rg) is not available and could not be downloaded\")));\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst searchPath = resolveToCwd(searchDir || \".\", ctx?.cwd || cwd);\n\t\t\t\t\t\tconst ops = customOps ?? defaultGrepOperations;\n\t\t\t\t\t\tlet isDirectory: boolean;\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tisDirectory = await ops.isDirectory(searchPath);\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\tsettle(() => reject(new Error(`Path not found: ${searchPath}`)));\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Clamp so String() never yields exponent notation, which rg rejects.\n\t\t\t\t\t\tconst contextValue =\n\t\t\t\t\t\t\tcontext && context > 0 ? Math.min(Math.floor(context), Number.MAX_SAFE_INTEGER) : 0;\n\t\t\t\t\t\tconst effectiveLimit = Math.max(1, Math.floor(limit ?? DEFAULT_LIMIT));\n\t\t\t\t\t\tconst formatPath = (filePath: string): string => {\n\t\t\t\t\t\t\tif (isDirectory) {\n\t\t\t\t\t\t\t\tconst relative = path.relative(searchPath, path.resolve(searchPath, filePath));\n\t\t\t\t\t\t\t\tif (relative && !relative.startsWith(\"..\")) {\n\t\t\t\t\t\t\t\t\treturn relative.replace(/\\\\/g, \"/\");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn path.basename(filePath);\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\t// --no-config: the tool contract (literal, glob, limit, ...) must not depend on\n\t\t\t\t\t\t// ambient user config like RIPGREP_CONFIG_PATH. Users can customize via bash or extensions.\n\t\t\t\t\t\tconst args: string[] = [\"--no-config\", \"--json\", \"--line-number\", \"--color=never\", \"--hidden\"];\n\t\t\t\t\t\tif (ignoreCase) args.push(\"--ignore-case\");\n\t\t\t\t\t\tif (literal) args.push(\"--fixed-strings\");\n\t\t\t\t\t\t// rg never matches a leading \"./\" (\"./src/*.ts\" finds nothing), so drop it; \"!\" negates.\n\t\t\t\t\t\tif (glob) args.push(\"--glob\", glob.replace(/^(!?)(?:\\.\\/)+/, \"$1\"));\n\t\t\t\t\t\t// rg emits the surrounding lines as `context` events, so no matched file is ever read here (#9276).\n\t\t\t\t\t\tif (contextValue > 0) args.push(\"--context\", String(contextValue));\n\t\t\t\t\t\t// rg roots --glob at its own cwd, so a directory search runs inside searchPath (#11807).\n\t\t\t\t\t\t// It searches \".\" because rg canonicalizes its cwd: with an absolute path, a symlinked\n\t\t\t\t\t\t// searchPath (macOS /tmp) would no longer lie under the glob root.\n\t\t\t\t\t\targs.push(\"--\", pattern, isDirectory ? \".\" : searchPath);\n\n\t\t\t\t\t\tconst child = spawn(rgPath, args, {\n\t\t\t\t\t\t\tcwd: isDirectory ? searchPath : undefined,\n\t\t\t\t\t\t\tstdio: [\"ignore\", \"pipe\", \"pipe\"],\n\t\t\t\t\t\t});\n\t\t\t\t\t\tconst rl = createInterface({ input: child.stdout });\n\t\t\t\t\t\tlet stderr = \"\";\n\t\t\t\t\t\tlet matchCount = 0;\n\t\t\t\t\t\tlet matchLimitReached = false;\n\t\t\t\t\t\tlet linesTruncated = false;\n\t\t\t\t\t\tlet aborted = false;\n\t\t\t\t\t\tlet killedDueToLimit = false;\n\t\t\t\t\t\tconst outputLines: string[] = [];\n\n\t\t\t\t\t\tconst cleanup = () => {\n\t\t\t\t\t\t\trl.close();\n\t\t\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconst stopChild = (dueToLimit = false) => {\n\t\t\t\t\t\t\tif (!child.killed) {\n\t\t\t\t\t\t\t\tkilledDueToLimit = dueToLimit;\n\t\t\t\t\t\t\t\tchild.kill();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconst onAbort = () => {\n\t\t\t\t\t\t\taborted = true;\n\t\t\t\t\t\t\tstopChild();\n\t\t\t\t\t\t};\n\t\t\t\t\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\t\t\t\tchild.stderr?.on(\"data\", (chunk) => {\n\t\t\t\t\t\t\tstderr += chunk.toString();\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\t// Size of the full output, including lines past the byte cap that are counted but not stored.\n\t\t\t\t\t\tlet outputBytes = 0;\n\t\t\t\t\t\tlet outputLineCount = 0;\n\t\t\t\t\t\tlet lastFile: string | undefined;\n\t\t\t\t\t\t// Set at the last allowed match. rg still sends that match's trailing context, kept up to\n\t\t\t\t\t\t// trailingContextEnd, and the limit notice waits for proof of one more match.\n\t\t\t\t\t\tlet limitHit = false;\n\t\t\t\t\t\tlet trailingContextEnd = 0;\n\t\t\t\t\t\tlet done = false;\n\t\t\t\t\t\tconst finish = () => {\n\t\t\t\t\t\t\tdone = true;\n\t\t\t\t\t\t\tstopChild(true);\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconst pushLine = (filePath: string, lineNumber: number, lineText: string, isMatch: boolean) => {\n\t\t\t\t\t\t\tlastFile = filePath;\n\t\t\t\t\t\t\tconst relativePath = formatPath(filePath);\n\t\t\t\t\t\t\t// Strip only the line terminator: a lone CR inside a line is content, as in the read tool.\n\t\t\t\t\t\t\tconst sanitized = lineText.replace(/\\r?\\n?$/, \"\");\n\t\t\t\t\t\t\t// Truncate long lines so grep output stays compact.\n\t\t\t\t\t\t\tconst { text: truncatedText, wasTruncated } = truncateLine(sanitized);\n\t\t\t\t\t\t\tif (wasTruncated) linesTruncated = true;\n\t\t\t\t\t\t\tconst line = isMatch\n\t\t\t\t\t\t\t\t? `${relativePath}:${lineNumber}: ${truncatedText}`\n\t\t\t\t\t\t\t\t: `${relativePath}-${lineNumber}- ${truncatedText}`;\n\t\t\t\t\t\t\t// Byte truncation below drops everything past the cap, so keep counting but stop storing (#9276).\n\t\t\t\t\t\t\t// outputBytes counts a newline after every line; the joined output has one fewer.\n\t\t\t\t\t\t\tif (outputBytes - 1 <= DEFAULT_MAX_BYTES) outputLines.push(line);\n\t\t\t\t\t\t\toutputBytes += Buffer.byteLength(line, \"utf-8\") + 1;\n\t\t\t\t\t\t\toutputLineCount++;\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\trl.on(\"line\", (line) => {\n\t\t\t\t\t\t\tif (done || !line.trim()) return;\n\t\t\t\t\t\t\tlet event: any;\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tevent = JSON.parse(line);\n\t\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst isMatch = event.type === \"match\";\n\t\t\t\t\t\t\tif (!isMatch && event.type !== \"context\") return;\n\t\t\t\t\t\t\tconst filePath = decodeRgText(event.data?.path);\n\t\t\t\t\t\t\tconst lineNumber = event.data?.line_number;\n\t\t\t\t\t\t\tif (!filePath || typeof lineNumber !== \"number\") return;\n\t\t\t\t\t\t\tconst lineText = decodeRgText(event.data?.lines);\n\t\t\t\t\t\t\tif (!limitHit) {\n\t\t\t\t\t\t\t\tpushLine(filePath, lineNumber, lineText, isMatch);\n\t\t\t\t\t\t\t\tif (!isMatch) return;\n\t\t\t\t\t\t\t\tmatchCount++;\n\t\t\t\t\t\t\t\tif (matchCount >= effectiveLimit) {\n\t\t\t\t\t\t\t\t\tlimitHit = true;\n\t\t\t\t\t\t\t\t\ttrailingContextEnd = lineNumber + contextValue;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst inWindow = filePath === lastFile && lineNumber <= trailingContextEnd;\n\t\t\t\t\t\t\t// A match inside the last match's trailing context is shown as context.\n\t\t\t\t\t\t\tif (inWindow) pushLine(filePath, lineNumber, lineText, false);\n\t\t\t\t\t\t\t// Only another match proves that the limit cut results off.\n\t\t\t\t\t\t\tif (isMatch) matchLimitReached = true;\n\t\t\t\t\t\t\tif (matchLimitReached && !(inWindow && lineNumber < trailingContextEnd)) finish();\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\tchild.on(\"error\", (error) => {\n\t\t\t\t\t\t\tcleanup();\n\t\t\t\t\t\t\tsettle(() => reject(new Error(`Failed to run ripgrep: ${error.message}`)));\n\t\t\t\t\t\t});\n\t\t\t\t\t\tchild.on(\"close\", (code) => {\n\t\t\t\t\t\t\tcleanup();\n\t\t\t\t\t\t\tif (aborted) {\n\t\t\t\t\t\t\t\tsettle(() => reject(new Error(\"Operation aborted\")));\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (!killedDueToLimit && code !== 0 && code !== 1) {\n\t\t\t\t\t\t\t\tconst errorMsg = stderr.trim() || `ripgrep exited with code ${code}`;\n\t\t\t\t\t\t\t\tsettle(() => reject(new Error(errorMsg)));\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (matchCount === 0) {\n\t\t\t\t\t\t\t\tsettle(() =>\n\t\t\t\t\t\t\t\t\tresolve({ content: [{ type: \"text\", text: \"No matches found\" }], details: undefined }),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tconst rawOutput = outputLines.join(\"\\n\");\n\t\t\t\t\t\t\t// Apply byte truncation. There is no line limit here because the match limit already capped rows.\n\t\t\t\t\t\t\tconst truncation = truncateHead(rawOutput, { maxLines: Number.MAX_SAFE_INTEGER });\n\t\t\t\t\t\t\ttruncation.totalLines = outputLineCount;\n\t\t\t\t\t\t\ttruncation.totalBytes = outputBytes - 1;\n\t\t\t\t\t\t\tlet output = truncation.content;\n\t\t\t\t\t\t\tconst details: GrepToolDetails = {};\n\t\t\t\t\t\t\t// Build actionable notices for truncation and match limits.\n\t\t\t\t\t\t\tconst notices: string[] = [];\n\t\t\t\t\t\t\tif (matchLimitReached) {\n\t\t\t\t\t\t\t\tnotices.push(\n\t\t\t\t\t\t\t\t\t`${effectiveLimit} matches limit reached. Use limit=${effectiveLimit * 2} for more, or refine pattern`,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tdetails.matchLimitReached = effectiveLimit;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (truncation.truncated) {\n\t\t\t\t\t\t\t\tnotices.push(`${formatSize(DEFAULT_MAX_BYTES)} limit reached`);\n\t\t\t\t\t\t\t\tdetails.truncation = truncation;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (linesTruncated) {\n\t\t\t\t\t\t\t\tnotices.push(\n\t\t\t\t\t\t\t\t\t`Some lines truncated to ${GREP_MAX_LINE_LENGTH} chars. Use read tool to see full lines`,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tdetails.linesTruncated = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (notices.length > 0) output += `\\n\\n[${notices.join(\". \")}]`;\n\t\t\t\t\t\t\tsettle(() =>\n\t\t\t\t\t\t\t\tresolve({\n\t\t\t\t\t\t\t\t\tcontent: [{ type: \"text\", text: output }],\n\t\t\t\t\t\t\t\t\tdetails: Object.keys(details).length > 0 ? details : undefined,\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t});\n\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\tsettle(() => reject(err as Error));\n\t\t\t\t\t}\n\t\t\t\t})();\n\t\t\t});\n\t\t},\n\t\t...grepRenderers,\n\t};\n}\n\nexport function createGrepTool(cwd: string, options?: GrepToolOptions): TypeBoxAgentTool<typeof grepSchema> {\n\treturn wrapToolDefinition(createGrepToolDefinition(cwd, options));\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"output-accumulator.d.ts","sourceRoot":"","sources":["../../../src/core/tools/output-accumulator.ts"],"names":[],"mappings":"AAGA,OAAO,EAAwC,KAAK,gBAAgB,EAAgB,MAAM,eAAe,CAAC;AAE1G,MAAM,WAAW,wBAAwB;IACxC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,cAAc,CAAC,EAAE,MAAM,CAAC;CACxB;AAED,MAAM,WAAW,cAAc;IAC9B,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,gBAAgB,CAAC;IAC7B,cAAc,CAAC,EAAE,MAAM,CAAC;CACxB;AAED,MAAM,WAAW,UAAU;IAC1B,OAAO,EAAE,MAAM,CAAC;IAChB,kDAAkD;IAClD,SAAS,EAAE,OAAO,CAAC;CACnB;AAMD;;;;;;GAMG;AACH,qBAAa,iBAAiB;IAC7B,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAS;I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E;QAAE,kBAAkB,CAAC,EAAE,OAAO,CAAA;KAAO,GAAG,cAAc,CA+BvE;IAEK,aAAa,IAAI,OAAO,CAAC,IAAI,CAAC,CAqBnC;IAED;;;;OAIG;IACG,cAAc,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,CAAC,CA2B1D;IAED,gBAAgB,IAAI,MAAM,CAEzB;IAED,OAAO,CAAC,iBAAiB;IA+BzB,OAAO,CAAC,QAAQ;IAiBhB,OAAO,CAAC,eAAe;IASvB,OAAO,CAAC,iBAAiB;IAMzB,OAAO,CAAC,cAAc;CAYtB"}
@@ -61,7 +61,10 @@ export class OutputAccumulator {
61
61
  }
62
62
  }
63
63
  snapshot(options = {}) {
64
- const tailTruncation = truncateTail(this.getSnapshotText(), {
64
+ // Clipping drops the partial first line of the retained tail. When the tail is only the end of
65
+ // one over-long line, that is everything, so show the end of that line instead.
66
+ const snapshotText = this.getSnapshotText() || this.tailText;
67
+ const tailTruncation = truncateTail(snapshotText, {
65
68
  maxLines: this.maxLines,
66
69
  maxBytes: this.maxBytes,
67
70
  });