@caupulican/pi-adaptative 0.81.32 → 0.81.35

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 (237) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/dist/bundled-resources/extensions/tmux-agent-manager/README.md +69 -0
  3. package/dist/bundled-resources/extensions/tmux-agent-manager/index.d.ts +53 -0
  4. package/dist/bundled-resources/extensions/tmux-agent-manager/index.d.ts.map +1 -0
  5. package/dist/bundled-resources/extensions/tmux-agent-manager/index.js +1282 -0
  6. package/dist/bundled-resources/extensions/tmux-agent-manager/index.js.map +1 -0
  7. package/dist/bundled-resources/extensions/tmux-agent-manager/index.ts +1453 -0
  8. package/dist/bundled-resources/extensions/tmux-agent-manager/templates/builder-validator.json +14 -0
  9. package/dist/bundled-resources/extensions/tmux-agent-manager/templates/claude-trio.json +32 -0
  10. package/dist/bundled-resources/extensions/tmux-agent-manager/templates/full-provider-review.json +15 -0
  11. package/dist/bundled-resources/extensions/tmux-agent-manager/templates/provider-prompt-smoke.json +14 -0
  12. package/dist/bundled-resources/prompts/extensionify.md +5 -4
  13. package/dist/bundled-resources/prompts/skillify.md +5 -5
  14. package/dist/bundled-resources/skills/pi-harness-learning/SKILL.md +6 -3
  15. package/dist/config.d.ts +5 -1
  16. package/dist/config.d.ts.map +1 -1
  17. package/dist/config.js +10 -2
  18. package/dist/config.js.map +1 -1
  19. package/dist/core/agent-session.d.ts +7 -0
  20. package/dist/core/agent-session.d.ts.map +1 -1
  21. package/dist/core/agent-session.js +25 -2
  22. package/dist/core/agent-session.js.map +1 -1
  23. package/dist/core/background-lane-controller.d.ts +12 -3
  24. package/dist/core/background-lane-controller.d.ts.map +1 -1
  25. package/dist/core/background-lane-controller.js +67 -26
  26. package/dist/core/background-lane-controller.js.map +1 -1
  27. package/dist/core/bash-executor.d.ts.map +1 -1
  28. package/dist/core/bash-executor.js +7 -3
  29. package/dist/core/bash-executor.js.map +1 -1
  30. package/dist/core/context/context-store-retention.d.ts +4 -1
  31. package/dist/core/context/context-store-retention.d.ts.map +1 -1
  32. package/dist/core/context/context-store-retention.js +42 -151
  33. package/dist/core/context/context-store-retention.js.map +1 -1
  34. package/dist/core/context-pipeline.d.ts.map +1 -1
  35. package/dist/core/context-pipeline.js +6 -6
  36. package/dist/core/context-pipeline.js.map +1 -1
  37. package/dist/core/exec.d.ts.map +1 -1
  38. package/dist/core/exec.js +25 -39
  39. package/dist/core/exec.js.map +1 -1
  40. package/dist/core/extensions/loader.d.ts +9 -2
  41. package/dist/core/extensions/loader.d.ts.map +1 -1
  42. package/dist/core/extensions/loader.js +105 -21
  43. package/dist/core/extensions/loader.js.map +1 -1
  44. package/dist/core/footer-data-provider.d.ts.map +1 -1
  45. package/dist/core/footer-data-provider.js +2 -0
  46. package/dist/core/footer-data-provider.js.map +1 -1
  47. package/dist/core/goals/goal-state.d.ts +10 -0
  48. package/dist/core/goals/goal-state.d.ts.map +1 -1
  49. package/dist/core/goals/goal-state.js +37 -0
  50. package/dist/core/goals/goal-state.js.map +1 -1
  51. package/dist/core/goals/goal-tool-core.d.ts +11 -0
  52. package/dist/core/goals/goal-tool-core.d.ts.map +1 -1
  53. package/dist/core/goals/goal-tool-core.js +51 -1
  54. package/dist/core/goals/goal-tool-core.js.map +1 -1
  55. package/dist/core/improvement-loop.d.ts.map +1 -1
  56. package/dist/core/improvement-loop.js +26 -5
  57. package/dist/core/improvement-loop.js.map +1 -1
  58. package/dist/core/models/fitness-store.d.ts.map +1 -1
  59. package/dist/core/models/fitness-store.js +1 -1
  60. package/dist/core/models/fitness-store.js.map +1 -1
  61. package/dist/core/models/local-runtime.d.ts +6 -4
  62. package/dist/core/models/local-runtime.d.ts.map +1 -1
  63. package/dist/core/models/local-runtime.js +108 -36
  64. package/dist/core/models/local-runtime.js.map +1 -1
  65. package/dist/core/output-guard.d.ts.map +1 -1
  66. package/dist/core/output-guard.js +23 -8
  67. package/dist/core/output-guard.js.map +1 -1
  68. package/dist/core/package-manager.d.ts.map +1 -1
  69. package/dist/core/package-manager.js +44 -59
  70. package/dist/core/package-manager.js.map +1 -1
  71. package/dist/core/profile-resource-selection.d.ts +16 -0
  72. package/dist/core/profile-resource-selection.d.ts.map +1 -1
  73. package/dist/core/profile-resource-selection.js +41 -0
  74. package/dist/core/profile-resource-selection.js.map +1 -1
  75. package/dist/core/reflection-controller.d.ts.map +1 -1
  76. package/dist/core/reflection-controller.js +18 -1
  77. package/dist/core/reflection-controller.js.map +1 -1
  78. package/dist/core/reload-blockers.d.ts +1 -0
  79. package/dist/core/reload-blockers.d.ts.map +1 -1
  80. package/dist/core/reload-blockers.js +6 -2
  81. package/dist/core/reload-blockers.js.map +1 -1
  82. package/dist/core/resource-loader.d.ts +2 -0
  83. package/dist/core/resource-loader.d.ts.map +1 -1
  84. package/dist/core/resource-loader.js +50 -28
  85. package/dist/core/resource-loader.js.map +1 -1
  86. package/dist/core/settings-manager.d.ts.map +1 -1
  87. package/dist/core/settings-manager.js +1 -1
  88. package/dist/core/settings-manager.js.map +1 -1
  89. package/dist/core/slash-commands.d.ts.map +1 -1
  90. package/dist/core/slash-commands.js +1 -1
  91. package/dist/core/slash-commands.js.map +1 -1
  92. package/dist/core/toolkit/script-runner.d.ts.map +1 -1
  93. package/dist/core/toolkit/script-runner.js +58 -24
  94. package/dist/core/toolkit/script-runner.js.map +1 -1
  95. package/dist/core/tools/bash.d.ts.map +1 -1
  96. package/dist/core/tools/bash.js +13 -26
  97. package/dist/core/tools/bash.js.map +1 -1
  98. package/dist/core/tools/extensionify.d.ts +2 -1
  99. package/dist/core/tools/extensionify.d.ts.map +1 -1
  100. package/dist/core/tools/extensionify.js +11 -8
  101. package/dist/core/tools/extensionify.js.map +1 -1
  102. package/dist/core/tools/find.d.ts.map +1 -1
  103. package/dist/core/tools/find.js +54 -48
  104. package/dist/core/tools/find.js.map +1 -1
  105. package/dist/core/tools/git-filter.d.ts.map +1 -1
  106. package/dist/core/tools/git-filter.js +20 -32
  107. package/dist/core/tools/git-filter.js.map +1 -1
  108. package/dist/core/tools/goal.d.ts +1 -1
  109. package/dist/core/tools/goal.d.ts.map +1 -1
  110. package/dist/core/tools/goal.js +10 -3
  111. package/dist/core/tools/goal.js.map +1 -1
  112. package/dist/core/tools/grep.d.ts.map +1 -1
  113. package/dist/core/tools/grep.js +89 -80
  114. package/dist/core/tools/grep.js.map +1 -1
  115. package/dist/core/tools/output-accumulator.d.ts +2 -0
  116. package/dist/core/tools/output-accumulator.d.ts.map +1 -1
  117. package/dist/core/tools/output-accumulator.js +7 -4
  118. package/dist/core/tools/output-accumulator.js.map +1 -1
  119. package/dist/core/tools/read.d.ts.map +1 -1
  120. package/dist/core/tools/read.js +4 -3
  121. package/dist/core/tools/read.js.map +1 -1
  122. package/dist/index.d.ts +2 -1
  123. package/dist/index.d.ts.map +1 -1
  124. package/dist/index.js +2 -1
  125. package/dist/index.js.map +1 -1
  126. package/dist/main.d.ts +2 -0
  127. package/dist/main.d.ts.map +1 -1
  128. package/dist/main.js +23 -4
  129. package/dist/main.js.map +1 -1
  130. package/dist/migrations.d.ts.map +1 -1
  131. package/dist/migrations.js +18 -4
  132. package/dist/migrations.js.map +1 -1
  133. package/dist/modes/interactive/auth-dialogs-controller.d.ts +10 -0
  134. package/dist/modes/interactive/auth-dialogs-controller.d.ts.map +1 -1
  135. package/dist/modes/interactive/auth-dialogs-controller.js +94 -27
  136. package/dist/modes/interactive/auth-dialogs-controller.js.map +1 -1
  137. package/dist/modes/interactive/auto-learn-controller.d.ts.map +1 -1
  138. package/dist/modes/interactive/auto-learn-controller.js +2 -1
  139. package/dist/modes/interactive/auto-learn-controller.js.map +1 -1
  140. package/dist/modes/interactive/components/bordered-loader.d.ts +1 -0
  141. package/dist/modes/interactive/components/bordered-loader.d.ts.map +1 -1
  142. package/dist/modes/interactive/components/bordered-loader.js +8 -0
  143. package/dist/modes/interactive/components/bordered-loader.js.map +1 -1
  144. package/dist/modes/interactive/components/extension-editor.d.ts.map +1 -1
  145. package/dist/modes/interactive/components/extension-editor.js +6 -15
  146. package/dist/modes/interactive/components/extension-editor.js.map +1 -1
  147. package/dist/modes/interactive/components/login-dialog.d.ts +3 -1
  148. package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -1
  149. package/dist/modes/interactive/components/login-dialog.js +20 -8
  150. package/dist/modes/interactive/components/login-dialog.js.map +1 -1
  151. package/dist/modes/interactive/components/profile-resource-editor.d.ts +4 -1
  152. package/dist/modes/interactive/components/profile-resource-editor.d.ts.map +1 -1
  153. package/dist/modes/interactive/components/profile-resource-editor.js +22 -39
  154. package/dist/modes/interactive/components/profile-resource-editor.js.map +1 -1
  155. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
  156. package/dist/modes/interactive/components/session-selector.js +1 -1
  157. package/dist/modes/interactive/components/session-selector.js.map +1 -1
  158. package/dist/modes/interactive/config-backup.d.ts +1 -0
  159. package/dist/modes/interactive/config-backup.d.ts.map +1 -1
  160. package/dist/modes/interactive/config-backup.js +14 -3
  161. package/dist/modes/interactive/config-backup.js.map +1 -1
  162. package/dist/modes/interactive/editor-overlay-host.d.ts +12 -0
  163. package/dist/modes/interactive/editor-overlay-host.d.ts.map +1 -1
  164. package/dist/modes/interactive/editor-overlay-host.js +55 -0
  165. package/dist/modes/interactive/editor-overlay-host.js.map +1 -1
  166. package/dist/modes/interactive/extension-ui-host.d.ts +2 -1
  167. package/dist/modes/interactive/extension-ui-host.d.ts.map +1 -1
  168. package/dist/modes/interactive/extension-ui-host.js +161 -96
  169. package/dist/modes/interactive/extension-ui-host.js.map +1 -1
  170. package/dist/modes/interactive/external-editor.d.ts.map +1 -1
  171. package/dist/modes/interactive/external-editor.js +23 -28
  172. package/dist/modes/interactive/external-editor.js.map +1 -1
  173. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  174. package/dist/modes/interactive/interactive-mode.js +14 -8
  175. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  176. package/dist/modes/interactive/profile-menu-controller.d.ts +5 -1
  177. package/dist/modes/interactive/profile-menu-controller.d.ts.map +1 -1
  178. package/dist/modes/interactive/profile-menu-controller.js +118 -24
  179. package/dist/modes/interactive/profile-menu-controller.js.map +1 -1
  180. package/dist/modes/interactive/resource-shell-commands.d.ts +1 -0
  181. package/dist/modes/interactive/resource-shell-commands.d.ts.map +1 -1
  182. package/dist/modes/interactive/resource-shell-commands.js +5 -1
  183. package/dist/modes/interactive/resource-shell-commands.js.map +1 -1
  184. package/dist/modes/interactive/session-flow-commands.d.ts.map +1 -1
  185. package/dist/modes/interactive/session-flow-commands.js +100 -7
  186. package/dist/modes/interactive/session-flow-commands.js.map +1 -1
  187. package/dist/modes/interactive/session-io-commands.d.ts.map +1 -1
  188. package/dist/modes/interactive/session-io-commands.js +80 -50
  189. package/dist/modes/interactive/session-io-commands.js.map +1 -1
  190. package/dist/modes/interactive/startup-checks.d.ts.map +1 -1
  191. package/dist/modes/interactive/startup-checks.js +14 -17
  192. package/dist/modes/interactive/startup-checks.js.map +1 -1
  193. package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
  194. package/dist/modes/rpc/rpc-client.js +20 -19
  195. package/dist/modes/rpc/rpc-client.js.map +1 -1
  196. package/dist/package-manager-cli.d.ts.map +1 -1
  197. package/dist/package-manager-cli.js +10 -19
  198. package/dist/package-manager-cli.js.map +1 -1
  199. package/dist/utils/child-process.d.ts +13 -7
  200. package/dist/utils/child-process.d.ts.map +1 -1
  201. package/dist/utils/child-process.js +56 -3
  202. package/dist/utils/child-process.js.map +1 -1
  203. package/dist/utils/clipboard-image.d.ts.map +1 -1
  204. package/dist/utils/clipboard-image.js +3 -2
  205. package/dist/utils/clipboard-image.js.map +1 -1
  206. package/dist/utils/clipboard.d.ts.map +1 -1
  207. package/dist/utils/clipboard.js +17 -10
  208. package/dist/utils/clipboard.js.map +1 -1
  209. package/dist/utils/external-editor-command.d.ts +8 -0
  210. package/dist/utils/external-editor-command.d.ts.map +1 -0
  211. package/dist/utils/external-editor-command.js +60 -0
  212. package/dist/utils/external-editor-command.js.map +1 -0
  213. package/dist/utils/paths.d.ts.map +1 -1
  214. package/dist/utils/paths.js +10 -2
  215. package/dist/utils/paths.js.map +1 -1
  216. package/dist/utils/tools-manager.d.ts.map +1 -1
  217. package/dist/utils/tools-manager.js +23 -10
  218. package/dist/utils/tools-manager.js.map +1 -1
  219. package/dist/utils/work-directory.d.ts +36 -0
  220. package/dist/utils/work-directory.d.ts.map +1 -0
  221. package/dist/utils/work-directory.js +462 -0
  222. package/dist/utils/work-directory.js.map +1 -0
  223. package/docs/index.md +2 -0
  224. package/docs/resources.md +2 -2
  225. package/docs/rpc.md +1 -1
  226. package/docs/tmux-agent-manager.md +48 -0
  227. package/docs/windows.md +100 -7
  228. package/docs/work-directory.md +41 -0
  229. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  230. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  231. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  232. package/examples/extensions/sandbox/package-lock.json +2 -2
  233. package/examples/extensions/sandbox/package.json +1 -1
  234. package/examples/extensions/with-deps/package-lock.json +2 -2
  235. package/examples/extensions/with-deps/package.json +1 -1
  236. package/npm-shrinkwrap.json +12 -12
  237. package/package.json +4 -4
@@ -5,6 +5,7 @@ import { spawn } from "child_process";
5
5
  import path from "path";
6
6
  import { Type } from "typebox";
7
7
  import { keyHint } from "../../modes/interactive/components/keybinding-hints.js";
8
+ import { waitForChildProcessWithTermination } from "../../utils/child-process.js";
8
9
  import { ensureTool } from "../../utils/tools-manager.js";
9
10
  import { broadQueryInvalidationNote, formatArtifactNotice, normalizeBroadQueryKey, packToolOutput, } from "../context/tool-output-packer.js";
10
11
  import { defaultFffSearchBackend, hasGitignoreInTree, relativePathInside, safeGetFinder, } from "./fff-search-backend.js";
@@ -24,6 +25,8 @@ const findSchema = Type.Object({
24
25
  ignoreCase: Type.Optional(Type.Boolean({ description: "Case-insensitive matching (default: false)" })),
25
26
  });
26
27
  const DEFAULT_LIMIT = 1000;
28
+ const FIND_PROCESS_TIMEOUT_MS = 5 * 60_000;
29
+ const FIND_PROCESS_KILL_GRACE_MS = 1_000;
27
30
  const defaultFindOperations = {
28
31
  exists: pathExists,
29
32
  // This is a placeholder. Actual fd execution happens in execute() when no custom glob is provided.
@@ -410,15 +413,15 @@ export function createFindToolDefinition(cwd, options) {
410
413
  }
411
414
  }
412
415
  args.push("--", finalPattern, searchPath);
413
- const child = spawn(fdPath, args, { stdio: ["ignore", "pipe", "pipe"] });
416
+ const child = spawn(fdPath, args, {
417
+ detached: process.platform !== "win32",
418
+ stdio: ["ignore", "pipe", "pipe"],
419
+ });
414
420
  const rl = createInterface({ input: child.stdout });
415
421
  let stderr = "";
416
422
  const lines = [];
417
- stopChild = () => {
418
- if (!child.killed) {
419
- child.kill();
420
- }
421
- };
423
+ const terminationController = new AbortController();
424
+ stopChild = () => terminationController.abort();
422
425
  const cleanup = () => {
423
426
  rl.close();
424
427
  };
@@ -428,53 +431,56 @@ export function createFindToolDefinition(cwd, options) {
428
431
  rl.on("line", (line) => {
429
432
  lines.push(line);
430
433
  });
431
- child.on("error", (error) => {
432
- cleanup();
433
- settle(() => reject(new Error(`Failed to run fd: ${error.message}`)));
434
- });
435
- child.on("close", (code) => {
436
- cleanup();
437
- if (signal?.aborted) {
438
- settle(() => reject(new Error("Operation aborted")));
434
+ const terminal = await waitForChildProcessWithTermination(child, {
435
+ signal: terminationController.signal,
436
+ timeoutMs: FIND_PROCESS_TIMEOUT_MS,
437
+ killGraceMs: FIND_PROCESS_KILL_GRACE_MS,
438
+ }).finally(cleanup);
439
+ const code = terminal.code;
440
+ if (terminal.reason === "timeout") {
441
+ settle(() => reject(new Error(`fd timed out after ${FIND_PROCESS_TIMEOUT_MS}ms`)));
442
+ return;
443
+ }
444
+ if (signal?.aborted) {
445
+ settle(() => reject(new Error("Operation aborted")));
446
+ return;
447
+ }
448
+ const output = lines.join("\n");
449
+ if (code !== 0) {
450
+ const errorMsg = stderr.trim() || `fd exited with code ${code}`;
451
+ if (!output) {
452
+ settle(() => reject(new Error(errorMsg)));
439
453
  return;
440
454
  }
441
- const output = lines.join("\n");
442
- if (code !== 0) {
443
- const errorMsg = stderr.trim() || `fd exited with code ${code}`;
444
- if (!output) {
445
- settle(() => reject(new Error(errorMsg)));
446
- return;
447
- }
455
+ }
456
+ const relativized = [];
457
+ for (const rawLine of lines) {
458
+ const line = rawLine.replace(/\r$/, "").trim();
459
+ if (!line)
460
+ continue;
461
+ const hadTrailingSlash = line.endsWith("/") || line.endsWith("\\");
462
+ let relativePath = line;
463
+ if (line.startsWith(searchPath)) {
464
+ relativePath = line.slice(searchPath.length + 1);
448
465
  }
449
- const relativized = [];
450
- for (const rawLine of lines) {
451
- const line = rawLine.replace(/\r$/, "").trim();
452
- if (!line)
453
- continue;
454
- const hadTrailingSlash = line.endsWith("/") || line.endsWith("\\");
455
- let relativePath = line;
456
- if (line.startsWith(searchPath)) {
457
- relativePath = line.slice(searchPath.length + 1);
458
- }
459
- else {
460
- relativePath = path.relative(searchPath, line);
461
- }
462
- if (hadTrailingSlash && !relativePath.endsWith("/"))
463
- relativePath += "/";
464
- relativized.push(toPosixPath(relativePath));
466
+ else {
467
+ relativePath = path.relative(searchPath, line);
465
468
  }
466
- const formatted = formatFindResults(relativized, effectiveLimit, {
467
- toolCallId,
468
- artifactStore,
469
- broadQueryTracker,
470
- pattern: effectivePattern,
471
- rawPath: searchDir,
472
- });
473
- settle(() => resolve({
474
- content: [{ type: "text", text: formatted.text }],
475
- details: Object.keys(formatted.details).length > 0 ? formatted.details : undefined,
476
- }));
469
+ if (hadTrailingSlash && !relativePath.endsWith("/"))
470
+ relativePath += "/";
471
+ relativized.push(toPosixPath(relativePath));
472
+ }
473
+ const formatted = formatFindResults(relativized, effectiveLimit, {
474
+ toolCallId,
475
+ artifactStore,
476
+ broadQueryTracker,
477
+ pattern: effectivePattern,
478
+ rawPath: searchDir,
477
479
  });
480
+ settle(() => resolve({
481
+ content: [{ type: "text", text: formatted.text }],
482
+ details: Object.keys(formatted.details).length > 0 ? formatted.details : undefined,
483
+ }));
478
484
  }
479
485
  catch (e) {
480
486
  if (signal?.aborted) {
@@ -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;AAEhD,OAAO,EAAE,iBAAiB,EAAE,UAAU,EAAyB,MAAM,gCAAgC,CAAC;AACtG,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAC1C,OAAO,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AACtC,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,EAAE,OAAO,EAAE,MAAM,wDAAwD,CAAC;AAEjF,OAAO,EAAE,UAAU,EAAE,MAAM,8BAA8B,CAAC;AAE1D,OAAO,EAEN,0BAA0B,EAC1B,oBAAoB,EACpB,sBAAsB,EACtB,cAAc,GACd,MAAM,kCAAkC,CAAC;AAE1C,OAAO,EACN,uBAAuB,EAGvB,kBAAkB,EAClB,kBAAkB,EAClB,aAAa,GACb,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAC3D,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,WAAW,EAAE,GAAG,EAAE,MAAM,mBAAmB,CAAC;AACpF,OAAO,EAAE,mBAAmB,EAAqB,MAAM,oBAAoB,CAAC;AAC5E,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAElE,SAAS,WAAW,CAAC,KAAa,EAAU;IAC3C,OAAO,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAAA,CACvC;AAED,MAAM,UAAU,GAAG,IAAI,CAAC,MAAM,C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AClE","sourcesContent":["import { createInterface } from \"node:readline\";\nimport type { AgentTool } from \"@caupulican/pi-agent-core\";\nimport { DEFAULT_MAX_BYTES, formatSize, type TruncationResult } from \"@caupulican/pi-agent-core/node\";\nimport { Text } from \"@caupulican/pi-tui\";\nimport { spawn } from \"child_process\";\nimport path from \"path\";\nimport { type Static, Type } from \"typebox\";\nimport { keyHint } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport type { Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport { ensureTool } from \"../../utils/tools-manager.ts\";\nimport type { ArtifactStore } from \"../context/context-artifacts.ts\";\nimport {\n\ttype BroadQueryTracker,\n\tbroadQueryInvalidationNote,\n\tformatArtifactNotice,\n\tnormalizeBroadQueryKey,\n\tpackToolOutput,\n} from \"../context/tool-output-packer.ts\";\nimport type { ToolDefinition, ToolRenderResultOptions } from \"../extensions/types.ts\";\nimport {\n\tdefaultFffSearchBackend,\n\ttype FffSearchBackend,\n\ttype FffSearchResult,\n\thasGitignoreInTree,\n\trelativePathInside,\n\tsafeGetFinder,\n} from \"./fff-search-backend.ts\";\nimport { pathExists, resolveToCwd } from \"./path-utils.ts\";\nimport { getTextOutput, invalidArgText, shortenPath, str } from \"./render-utils.ts\";\nimport { defaultSearchRouter, type SearchRouter } from \"./search-router.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\n\nfunction toPosixPath(value: string): string {\n\treturn value.split(path.sep).join(\"/\");\n}\n\nconst findSchema = Type.Object({\n\tpattern: Type.String({\n\t\tdescription:\n\t\t\t\"Glob pattern to match files, e.g. '*.ts', '**/*.json', or 'src/**/*.spec.ts'. Use '.' to match all files.\",\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\tignoreCase: Type.Optional(Type.Boolean({ description: \"Case-insensitive matching (default: false)\" })),\n});\n\nexport type FindToolInput = Static<typeof findSchema>;\n\nconst DEFAULT_LIMIT = 1000;\n\nexport interface FindToolDetails {\n\ttruncation?: TruncationResult;\n\tresultLimitReached?: number;\n\t/** Set only when output was packed to an artifact; see tool-output-packer.ts. */\n\tartifactId?: string;\n\t/** Set when this exact query has repeatedly produced broad/truncated results. */\n\tinvalidationCandidate?: boolean;\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 routed FFF/fd search */\n\toperations?: FindOperations;\n\t/** FFF backend for resident indexed search. Set false to force fd fallback. */\n\tfff?: FffSearchBackend | false;\n\t/** Pure router that selects FFF or fd from request filters and environment facts. */\n\tsearchRouter?: SearchRouter;\n\t/**\n\t * Opt-in artifact store for first-capture-then-bound output packing (Phase 3). When\n\t * omitted (the default), behavior is byte-for-byte unchanged from before this option\n\t * existed: output is truncated the same way, just never artifact-backed.\n\t */\n\tartifactStore?: ArtifactStore;\n\t/** Opt-in tracker for repeated-broad-query \"do not repeat\" signals. Also default-off. */\n\tbroadQueryTracker?: BroadQueryTracker;\n}\n\nfunction formatFindCall(\n\targs: { pattern: string; path?: string; limit?: number } | undefined,\n\ttheme: Theme,\n\tcwd: string,\n): string {\n\tconst pattern = str(args?.pattern);\n\tconst rawPath = str(args?.path);\n\tconst path = rawPath !== null ? shortenPath(rawPath || \".\", cwd) : null;\n\tconst limit = args?.limit;\n\tconst invalidArg = invalidArgText(theme);\n\tlet text =\n\t\ttheme.fg(\"toolTitle\", theme.bold(\"find\")) +\n\t\t\" \" +\n\t\t(pattern === null ? invalidArg : theme.fg(\"accent\", pattern || \"\")) +\n\t\ttheme.fg(\"toolOutput\", ` in ${path === null ? invalidArg : path}`);\n\tif (limit !== undefined) {\n\t\ttext += theme.fg(\"toolOutput\", ` (limit ${limit})`);\n\t}\n\treturn text;\n}\n\nfunction formatFindResult(\n\tresult: {\n\t\tcontent: Array<{ type: string; text?: string; data?: string; mimeType?: string }>;\n\t\tdetails?: FindToolDetails;\n\t},\n\toptions: ToolRenderResultOptions,\n\ttheme: Theme,\n\tshowImages: boolean,\n): string {\n\tconst output = getTextOutput(result, showImages).trim();\n\tlet text = \"\";\n\tif (output) {\n\t\tconst lines = output.split(\"\\n\");\n\t\tconst maxLines = options.expanded ? lines.length : 20;\n\t\tconst displayLines = lines.slice(0, maxLines);\n\t\tconst remaining = lines.length - maxLines;\n\t\ttext += `\\n${displayLines.map((line) => theme.fg(\"toolOutput\", line)).join(\"\\n\")}`;\n\t\tif (remaining > 0) {\n\t\t\ttext += `${theme.fg(\"muted\", `\\n... (${remaining} more lines,`)} ${keyHint(\"app.tools.expand\", \"to expand\")})`;\n\t\t}\n\t}\n\n\tconst resultLimit = result.details?.resultLimitReached;\n\tconst truncation = result.details?.truncation;\n\tif (resultLimit || truncation?.truncated) {\n\t\tconst warnings: string[] = [];\n\t\tif (resultLimit) warnings.push(`${resultLimit} results limit`);\n\t\tif (truncation?.truncated) warnings.push(`${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit`);\n\t\ttext += `\\n${theme.fg(\"warning\", `[Truncated: ${warnings.join(\", \")}]`)}`;\n\t}\n\treturn text;\n}\n\nfunction hasGlobSyntax(pattern: string): boolean {\n\treturn pattern === \".\" || /[*?[{]/.test(pattern);\n}\n\nfunction fffQueryParts(parts: string[]): string {\n\treturn parts.filter(Boolean).join(\" \");\n}\n\nfunction toSearchRelative(repoRelativePath: string, searchPathRelativeToCwd: string): string | undefined {\n\tif (!searchPathRelativeToCwd) return repoRelativePath;\n\tconst prefix = `${searchPathRelativeToCwd}/`;\n\tif (!repoRelativePath.startsWith(prefix)) return undefined;\n\treturn repoRelativePath.slice(prefix.length);\n}\n\nfunction fffGlobPattern(pattern: string, searchPathRelativeToCwd: string): string {\n\tconst effectivePattern = pattern === \".\" ? \"**/*\" : pattern;\n\tif (!searchPathRelativeToCwd) {\n\t\tif (effectivePattern.includes(\"/\") || effectivePattern.startsWith(\"**/\")) return effectivePattern;\n\t\treturn `**/${effectivePattern}`;\n\t}\n\tif (effectivePattern === \"**\" || effectivePattern === \"**/*\") return `${searchPathRelativeToCwd}/**/*`;\n\tif (effectivePattern.includes(\"/\")) return `${searchPathRelativeToCwd}/${effectivePattern}`;\n\treturn `${searchPathRelativeToCwd}/**/${effectivePattern}`;\n}\n\ninterface FindPackingOptions {\n\ttoolCallId: string;\n\tartifactStore?: ArtifactStore;\n\tbroadQueryTracker?: BroadQueryTracker;\n\tpattern: string;\n\trawPath?: string;\n}\n\nfunction fffSearchOutput(\n\tresult: FffSearchResult,\n\tsearchPathRelativeToCwd: string,\n\teffectiveLimit: number,\n\tpacking: FindPackingOptions,\n) {\n\tconst relativized = result.items\n\t\t.map((item) => toSearchRelative(item.relativePath, searchPathRelativeToCwd))\n\t\t.filter((item): item is string => Boolean(item));\n\treturn formatFindResults(relativized, effectiveLimit, packing);\n}\n\nexport async function tryFffFind(options: {\n\tbackend: FffSearchBackend;\n\trouter: SearchRouter;\n\tcwd: string;\n\tsearchPath: string;\n\tpattern: string;\n\tignoreCase?: boolean;\n\teffectiveLimit: number;\n\ttoolCallId: string;\n\tartifactStore?: ArtifactStore;\n\tbroadQueryTracker?: BroadQueryTracker;\n\trawPath?: string;\n}): Promise<{ text: string; details: FindToolDetails } | undefined> {\n\tif (!(await pathExists(options.searchPath))) return undefined;\n\n\t// Kick off the FFF finder -- and, on a machine where fff-node isn't provisioned\n\t// yet, its lazy managed install -- unconditionally and as early as possible.\n\t// Routing below can still send THIS call to the fd fallback for reasons that\n\t// have nothing to do with tool availability (most commonly: the default result\n\t// limit is well above the FFF top-N threshold, see search-router.ts). That\n\t// outcome must not gate the install itself, or a machine that only ever issues\n\t// default-limit searches would never provision fff-node at all. getFinder() is\n\t// cached per basePath, so this costs nothing beyond the first call for a given\n\t// cwd -- the `await` further down, when this call does want FFF, reuses this\n\t// same in-flight/resolved promise instead of triggering the work twice.\n\t// safeGetFinder() guarantees this can never reject (a non-conforming custom\n\t// backend that throws synchronously still degrades to \"unavailable\"), so it\n\t// can neither produce an unhandled rejection nor fail this tool call outright.\n\tconst finderPromise = safeGetFinder(options.backend, options.cwd);\n\n\tconst searchPathRelativeToCwd = relativePathInside(options.cwd, options.searchPath);\n\tconst glob = hasGlobSyntax(options.pattern);\n\tconst baseRoute = options.router.route({\n\t\ttool: \"find\",\n\t\tglob,\n\t\tignoreCase: Boolean(options.ignoreCase),\n\t\tlimit: options.effectiveLimit,\n\t\tfinderAvailable: true,\n\t\tpathResolvable: searchPathRelativeToCwd !== undefined,\n\t\tgitignoreInTree: false,\n\t});\n\tif (baseRoute.backend !== \"fff\") return undefined;\n\tif (searchPathRelativeToCwd === undefined) return undefined;\n\n\tconst gitignoreInTree = await hasGitignoreInTree(options.searchPath);\n\tconst semanticRoute = options.router.route({\n\t\ttool: \"find\",\n\t\tglob,\n\t\tignoreCase: Boolean(options.ignoreCase),\n\t\tlimit: options.effectiveLimit,\n\t\tfinderAvailable: true,\n\t\tpathResolvable: true,\n\t\tgitignoreInTree,\n\t});\n\tif (semanticRoute.backend !== \"fff\") return undefined;\n\n\tconst finder = await finderPromise;\n\tconst finderRoute = options.router.route({\n\t\ttool: \"find\",\n\t\tglob,\n\t\tignoreCase: Boolean(options.ignoreCase),\n\t\tlimit: options.effectiveLimit,\n\t\tfinderAvailable: Boolean(finder),\n\t\tpathResolvable: true,\n\t\tgitignoreInTree: false,\n\t});\n\tif (!finder || finderRoute.backend !== \"fff\") return undefined;\n\n\tconst packing: FindPackingOptions = {\n\t\ttoolCallId: options.toolCallId,\n\t\tartifactStore: options.artifactStore,\n\t\tbroadQueryTracker: options.broadQueryTracker,\n\t\tpattern: options.pattern,\n\t\trawPath: options.rawPath,\n\t};\n\n\tconst probeLimit = options.effectiveLimit + 1;\n\tif (glob) {\n\t\tconst result = finder.glob(fffGlobPattern(options.pattern, searchPathRelativeToCwd), {\n\t\t\tpageSize: probeLimit,\n\t\t});\n\t\treturn result.ok\n\t\t\t? fffSearchOutput(result.value, searchPathRelativeToCwd, options.effectiveLimit, packing)\n\t\t\t: undefined;\n\t}\n\n\tconst pathConstraint = searchPathRelativeToCwd ? `${searchPathRelativeToCwd}/` : \"\";\n\tconst result = finder.fileSearch(fffQueryParts([pathConstraint, options.pattern]), {\n\t\tpageSize: probeLimit,\n\t});\n\treturn result.ok\n\t\t? fffSearchOutput(result.value, searchPathRelativeToCwd, options.effectiveLimit, packing)\n\t\t: undefined;\n}\n\nfunction formatFindResults(\n\trelativized: string[],\n\teffectiveLimit: number,\n\tpacking: FindPackingOptions,\n): { text: string; details: FindToolDetails } {\n\tif (relativized.length === 0) {\n\t\treturn { text: \"No files found matching pattern\", details: {} };\n\t}\n\n\tconst resultLimitReached = relativized.length > effectiveLimit;\n\tconst displayedResults = resultLimitReached ? relativized.slice(0, effectiveLimit) : relativized;\n\tconst dirGroups = new Map<string, string[]>();\n\tconst extCounts = new Map<string, number>();\n\n\tfor (const p of displayedResults) {\n\t\tconst dir = path.dirname(p);\n\t\tconst base = path.basename(p);\n\t\tconst dirKey = dir === \".\" ? \"./\" : `${dir}/`;\n\t\tif (!dirGroups.has(dirKey)) {\n\t\t\tdirGroups.set(dirKey, []);\n\t\t}\n\t\tdirGroups.get(dirKey)!.push(base);\n\n\t\tconst ext = path.extname(p).toLowerCase() || \"(no extension)\";\n\t\textCounts.set(ext, (extCounts.get(ext) || 0) + 1);\n\t}\n\n\tconst sortedDirs = Array.from(dirGroups.keys()).sort((a, b) => a.localeCompare(b));\n\tconst formattedLines: string[] = [];\n\tfor (const dir of sortedDirs) {\n\t\tformattedLines.push(dir);\n\t\tconst files = dirGroups.get(dir)!;\n\t\tfiles.sort((a, b) => a.localeCompare(b));\n\t\tfor (const file of files) {\n\t\t\tformattedLines.push(` ${file}`);\n\t\t}\n\t}\n\n\tconst extSummaryParts = Array.from(extCounts.entries())\n\t\t.sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))\n\t\t.map(([ext, count]) => `${ext}: ${count}`);\n\tconst extSummary = `Extensions: ${extSummaryParts.join(\", \")}`;\n\n\tconst rawOutput = formattedLines.join(\"\\n\");\n\t// Measure -> pack (artifact-backed if oversized and a store was provided) -> notices.\n\tconst packed = packToolOutput(\n\t\t{\n\t\t\ttoolName: \"find\",\n\t\t\tpath: packing.rawPath,\n\t\t\trawContent: rawOutput,\n\t\t\t// No line limit here because the result limit already caps rows; only the byte\n\t\t\t// cap should apply, matching the pre-Slice-B truncateHead call exactly.\n\t\t\ttruncation: { maxLines: Number.MAX_SAFE_INTEGER },\n\t\t},\n\t\tpacking.artifactStore,\n\t\tpacking.toolCallId,\n\t);\n\tlet resultOutput = packed.content;\n\tconst details: FindToolDetails = {};\n\tconst notices: string[] = [];\n\tif (packed.artifactId) {\n\t\tnotices.push(formatArtifactNotice(packed.artifactId));\n\t\tdetails.artifactId = packed.artifactId;\n\t}\n\tif (resultLimitReached) {\n\t\tnotices.push(\n\t\t\t`${effectiveLimit} results limit reached. Use limit=${effectiveLimit * 2} for more, or narrow path/pattern`,\n\t\t);\n\t\tdetails.resultLimitReached = effectiveLimit;\n\t}\n\tif (packed.truncation.truncated) {\n\t\tnotices.push(`${formatSize(DEFAULT_MAX_BYTES)} limit reached`);\n\t\t// Drop the duplicated bounded-preview text: it's already in the message's own\n\t\t// content, and re-including it here can push `details` past\n\t\t// MAX_RETAINED_TOOL_RESULT_DETAILS_BYTES (message-retention.ts), which replaces\n\t\t// the *entire* details object with a stub -- silently losing artifactId and every\n\t\t// other field alongside it. This is load-bearing beyond just the retention budget:\n\t\t// agent-session.ts's _releaseGcPackedArtifactReferences() reads artifactId back off\n\t\t// this same canonical message at eviction time (potentially many turns later), so\n\t\t// keeping `details` small here is what keeps that release path working at all. If\n\t\t// this field ever grows a large addition again, add a regression proving artifactId\n\t\t// survives compactToolResultDetailsForRetention (see\n\t\t// test/suite/agent-session-artifact-lifecycle.test.ts), not just a details-size check.\n\t\tdetails.truncation = { ...packed.truncation, content: \"\" };\n\t}\n\tif (resultLimitReached || packed.truncation.truncated) {\n\t\tconst note = broadQueryInvalidationNote(\n\t\t\tpacking.broadQueryTracker,\n\t\t\tnormalizeBroadQueryKey({ toolName: \"find\", pattern: packing.pattern, path: packing.rawPath }),\n\t\t\t`find \"${packing.pattern}\" in ${packing.rawPath ?? \".\"}`,\n\t\t);\n\t\tif (note) {\n\t\t\tnotices.push(note);\n\t\t\tdetails.invalidationCandidate = true;\n\t\t}\n\t}\n\tif (displayedResults.length > 0) {\n\t\tresultOutput += `\\n\\n[Summary - ${extSummary}]`;\n\t}\n\tif (notices.length > 0) {\n\t\tresultOutput += `\\n\\n[${notices.join(\". \")}]`;\n\t}\n\treturn { text: resultOutput, details };\n}\n\nexport function createFindToolDefinition(\n\tcwd: string,\n\toptions?: FindToolOptions,\n): ToolDefinition<typeof findSchema, FindToolDetails | undefined> {\n\tconst customOps = options?.operations;\n\tconst fffBackend = options?.fff === false ? undefined : (options?.fff ?? defaultFffSearchBackend);\n\tconst searchRouter = options?.searchRouter ?? defaultSearchRouter;\n\tconst artifactStore = options?.artifactStore;\n\tconst broadQueryTracker = options?.broadQueryTracker;\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: \"Find files by glob pattern (respects .gitignore)\",\n\t\tparameters: findSchema,\n\t\ttoolGroup: \"explore\",\n\t\tasync execute(\n\t\t\ttoolCallId,\n\t\t\t{\n\t\t\t\tpattern,\n\t\t\t\tpath: searchDir,\n\t\t\t\tlimit,\n\t\t\t\tignoreCase,\n\t\t\t}: { pattern: string; path?: string; limit?: number; ignoreCase?: boolean },\n\t\t\tsignal?: AbortSignal,\n\t\t\t_onUpdate?,\n\t\t\t_ctx?,\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 || \".\", cwd);\n\t\t\t\t\t\tconst effectiveLimit = limit ?? DEFAULT_LIMIT;\n\t\t\t\t\t\tconst probeLimit = effectiveLimit + 1;\n\t\t\t\t\t\tconst ops = customOps ?? defaultFindOperations;\n\n\t\t\t\t\t\tlet effectivePattern = pattern;\n\t\t\t\t\t\tif (pattern === \".\") {\n\t\t\t\t\t\t\teffectivePattern = \"**/*\";\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (!customOps && fffBackend) {\n\t\t\t\t\t\t\tconst fffResult = await tryFffFind({\n\t\t\t\t\t\t\t\tbackend: fffBackend,\n\t\t\t\t\t\t\t\trouter: searchRouter,\n\t\t\t\t\t\t\t\tcwd,\n\t\t\t\t\t\t\t\tsearchPath,\n\t\t\t\t\t\t\t\tpattern: effectivePattern,\n\t\t\t\t\t\t\t\tignoreCase,\n\t\t\t\t\t\t\t\teffectiveLimit,\n\t\t\t\t\t\t\t\ttoolCallId,\n\t\t\t\t\t\t\t\tartifactStore,\n\t\t\t\t\t\t\t\tbroadQueryTracker,\n\t\t\t\t\t\t\t\trawPath: searchDir,\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 (fffResult) {\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: fffResult.text }],\n\t\t\t\t\t\t\t\t\t\tdetails: Object.keys(fffResult.details).length > 0 ? fffResult.details : 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\t\t\t\t\t\t}\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\tconst results = await ops.glob(effectivePattern, searchPath, {\n\t\t\t\t\t\t\t\tignore: [\"**/node_modules/**\", \"**/.git/**\"],\n\t\t\t\t\t\t\t\tlimit: probeLimit,\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\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.map((p) => {\n\t\t\t\t\t\t\t\tif (p.startsWith(searchPath)) return toPosixPath(p.slice(searchPath.length + 1));\n\t\t\t\t\t\t\t\treturn toPosixPath(path.relative(searchPath, p));\n\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\tconst formatted = formatFindResults(relativized, effectiveLimit, {\n\t\t\t\t\t\t\t\ttoolCallId,\n\t\t\t\t\t\t\t\tartifactStore,\n\t\t\t\t\t\t\t\tbroadQueryTracker,\n\t\t\t\t\t\t\t\tpattern: effectivePattern,\n\t\t\t\t\t\t\t\trawPath: searchDir,\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: formatted.text }],\n\t\t\t\t\t\t\t\t\tdetails: Object.keys(formatted.details).length > 0 ? formatted.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\", true);\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\t// Build fd arguments. --no-require-git makes fd apply hierarchical .gitignore\n\t\t\t\t\t\t// semantics whether or not the search path is inside a git repository, without\n\t\t\t\t\t\t// leaking sibling-directory rules the way --ignore-file (a global source) would.\n\t\t\t\t\t\tconst args: string[] = [\n\t\t\t\t\t\t\t\"--glob\",\n\t\t\t\t\t\t\t\"--color=never\",\n\t\t\t\t\t\t\t\"--hidden\",\n\t\t\t\t\t\t\t\"--no-require-git\",\n\t\t\t\t\t\t\t\"--max-results\",\n\t\t\t\t\t\t\tString(probeLimit),\n\t\t\t\t\t\t];\n\t\t\t\t\t\tif (ignoreCase) {\n\t\t\t\t\t\t\targs.push(\"--ignore-case\");\n\t\t\t\t\t\t}\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\tlet finalPattern = effectivePattern;\n\t\t\t\t\t\tif (effectivePattern.includes(\"/\")) {\n\t\t\t\t\t\t\targs.push(\"--full-path\");\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t!effectivePattern.startsWith(\"/\") &&\n\t\t\t\t\t\t\t\t!effectivePattern.startsWith(\"**/\") &&\n\t\t\t\t\t\t\t\teffectivePattern !== \"**\"\n\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\tfinalPattern = `**/${effectivePattern}`;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\targs.push(\"--\", finalPattern, searchPath);\n\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\tconst lines: string[] = [];\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\", (line) => {\n\t\t\t\t\t\t\tlines.push(line);\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\tconst output = lines.join(\"\\n\");\n\t\t\t\t\t\t\tif (code !== 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\tif (!output) {\n\t\t\t\t\t\t\t\t\tsettle(() => reject(new Error(errorMsg)));\n\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tconst relativized: string[] = [];\n\t\t\t\t\t\t\tfor (const rawLine of lines) {\n\t\t\t\t\t\t\t\tconst line = rawLine.replace(/\\r$/, \"\").trim();\n\t\t\t\t\t\t\t\tif (!line) continue;\n\t\t\t\t\t\t\t\tconst hadTrailingSlash = line.endsWith(\"/\") || line.endsWith(\"\\\\\");\n\t\t\t\t\t\t\t\tlet relativePath = line;\n\t\t\t\t\t\t\t\tif (line.startsWith(searchPath)) {\n\t\t\t\t\t\t\t\t\trelativePath = line.slice(searchPath.length + 1);\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\trelativePath = path.relative(searchPath, line);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (hadTrailingSlash && !relativePath.endsWith(\"/\")) relativePath += \"/\";\n\t\t\t\t\t\t\t\trelativized.push(toPosixPath(relativePath));\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tconst formatted = formatFindResults(relativized, effectiveLimit, {\n\t\t\t\t\t\t\t\ttoolCallId,\n\t\t\t\t\t\t\t\tartifactStore,\n\t\t\t\t\t\t\t\tbroadQueryTracker,\n\t\t\t\t\t\t\t\tpattern: effectivePattern,\n\t\t\t\t\t\t\t\trawPath: searchDir,\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: formatted.text }],\n\t\t\t\t\t\t\t\t\tdetails: Object.keys(formatted.details).length > 0 ? formatted.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\trenderCall(args, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatFindCall(args, theme, context.cwd));\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatFindResult(result as any, options, theme, context.showImages));\n\t\t\treturn text;\n\t\t},\n\t};\n}\n\nexport function createFindTool(cwd: string, options?: FindToolOptions): AgentTool<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;AAEhD,OAAO,EAAE,iBAAiB,EAAE,UAAU,EAAyB,MAAM,gCAAgC,CAAC;AACtG,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAC1C,OAAO,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AACtC,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,EAAE,OAAO,EAAE,MAAM,wDAAwD,CAAC;AAEjF,OAAO,EAAE,kCAAkC,EAAE,MAAM,8BAA8B,CAAC;AAClF,OAAO,EAAE,UAAU,EAAE,MAAM,8BAA8B,CAAC;AAE1D,OAAO,EAEN,0BAA0B,EAC1B,oBAAoB,EACpB,sBAAsB,EACtB,cAAc,GACd,MAAM,kCAAkC,CAAC;AAE1C,OAAO,EACN,uBAAuB,EAGvB,kBAAkB,EAClB,kBAAkB,EAClB,aAAa,GACb,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAC3D,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,WAAW,EAAE,GAAG,EAAE,MAAM,mBAAmB,CAAC;AACpF,OAAO,EAAE,mBAAmB,EAAqB,MAAM,oBAAoB,CAAC;AAC5E,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAElE,SAAS,WAAW,CAAC,KAAa,EAAU;IAC3C,OAAO,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAAA,CACvC;AAED,MAAM,UAAU,GAAG,IAAI,CAAC,MAAM,CAAC;IAC9B,OAAO,EAAE,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,CACZ;KACD,CAAC;AAAA,CACF;AAED,MAAM,UAAU,cAAc,CAAC,GAAW,EAAE,OAAyB,EAAgC;IACpG,OAAO,kBAAkB,CAAC,wBAAwB,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC,CAAC;AAAA,CAClE","sourcesContent":["import { createInterface } from \"node:readline\";\nimport type { AgentTool } from \"@caupulican/pi-agent-core\";\nimport { DEFAULT_MAX_BYTES, formatSize, type TruncationResult } from \"@caupulican/pi-agent-core/node\";\nimport { Text } from \"@caupulican/pi-tui\";\nimport { spawn } from \"child_process\";\nimport path from \"path\";\nimport { type Static, Type } from \"typebox\";\nimport { keyHint } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport type { Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport { waitForChildProcessWithTermination } from \"../../utils/child-process.ts\";\nimport { ensureTool } from \"../../utils/tools-manager.ts\";\nimport type { ArtifactStore } from \"../context/context-artifacts.ts\";\nimport {\n\ttype BroadQueryTracker,\n\tbroadQueryInvalidationNote,\n\tformatArtifactNotice,\n\tnormalizeBroadQueryKey,\n\tpackToolOutput,\n} from \"../context/tool-output-packer.ts\";\nimport type { ToolDefinition, ToolRenderResultOptions } from \"../extensions/types.ts\";\nimport {\n\tdefaultFffSearchBackend,\n\ttype FffSearchBackend,\n\ttype FffSearchResult,\n\thasGitignoreInTree,\n\trelativePathInside,\n\tsafeGetFinder,\n} from \"./fff-search-backend.ts\";\nimport { pathExists, resolveToCwd } from \"./path-utils.ts\";\nimport { getTextOutput, invalidArgText, shortenPath, str } from \"./render-utils.ts\";\nimport { defaultSearchRouter, type SearchRouter } from \"./search-router.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\n\nfunction toPosixPath(value: string): string {\n\treturn value.split(path.sep).join(\"/\");\n}\n\nconst findSchema = Type.Object({\n\tpattern: Type.String({\n\t\tdescription:\n\t\t\t\"Glob pattern to match files, e.g. '*.ts', '**/*.json', or 'src/**/*.spec.ts'. Use '.' to match all files.\",\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\tignoreCase: Type.Optional(Type.Boolean({ description: \"Case-insensitive matching (default: false)\" })),\n});\n\nexport type FindToolInput = Static<typeof findSchema>;\n\nconst DEFAULT_LIMIT = 1000;\nconst FIND_PROCESS_TIMEOUT_MS = 5 * 60_000;\nconst FIND_PROCESS_KILL_GRACE_MS = 1_000;\n\nexport interface FindToolDetails {\n\ttruncation?: TruncationResult;\n\tresultLimitReached?: number;\n\t/** Set only when output was packed to an artifact; see tool-output-packer.ts. */\n\tartifactId?: string;\n\t/** Set when this exact query has repeatedly produced broad/truncated results. */\n\tinvalidationCandidate?: boolean;\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 routed FFF/fd search */\n\toperations?: FindOperations;\n\t/** FFF backend for resident indexed search. Set false to force fd fallback. */\n\tfff?: FffSearchBackend | false;\n\t/** Pure router that selects FFF or fd from request filters and environment facts. */\n\tsearchRouter?: SearchRouter;\n\t/**\n\t * Opt-in artifact store for first-capture-then-bound output packing (Phase 3). When\n\t * omitted (the default), behavior is byte-for-byte unchanged from before this option\n\t * existed: output is truncated the same way, just never artifact-backed.\n\t */\n\tartifactStore?: ArtifactStore;\n\t/** Opt-in tracker for repeated-broad-query \"do not repeat\" signals. Also default-off. */\n\tbroadQueryTracker?: BroadQueryTracker;\n}\n\nfunction formatFindCall(\n\targs: { pattern: string; path?: string; limit?: number } | undefined,\n\ttheme: Theme,\n\tcwd: string,\n): string {\n\tconst pattern = str(args?.pattern);\n\tconst rawPath = str(args?.path);\n\tconst path = rawPath !== null ? shortenPath(rawPath || \".\", cwd) : null;\n\tconst limit = args?.limit;\n\tconst invalidArg = invalidArgText(theme);\n\tlet text =\n\t\ttheme.fg(\"toolTitle\", theme.bold(\"find\")) +\n\t\t\" \" +\n\t\t(pattern === null ? invalidArg : theme.fg(\"accent\", pattern || \"\")) +\n\t\ttheme.fg(\"toolOutput\", ` in ${path === null ? invalidArg : path}`);\n\tif (limit !== undefined) {\n\t\ttext += theme.fg(\"toolOutput\", ` (limit ${limit})`);\n\t}\n\treturn text;\n}\n\nfunction formatFindResult(\n\tresult: {\n\t\tcontent: Array<{ type: string; text?: string; data?: string; mimeType?: string }>;\n\t\tdetails?: FindToolDetails;\n\t},\n\toptions: ToolRenderResultOptions,\n\ttheme: Theme,\n\tshowImages: boolean,\n): string {\n\tconst output = getTextOutput(result, showImages).trim();\n\tlet text = \"\";\n\tif (output) {\n\t\tconst lines = output.split(\"\\n\");\n\t\tconst maxLines = options.expanded ? lines.length : 20;\n\t\tconst displayLines = lines.slice(0, maxLines);\n\t\tconst remaining = lines.length - maxLines;\n\t\ttext += `\\n${displayLines.map((line) => theme.fg(\"toolOutput\", line)).join(\"\\n\")}`;\n\t\tif (remaining > 0) {\n\t\t\ttext += `${theme.fg(\"muted\", `\\n... (${remaining} more lines,`)} ${keyHint(\"app.tools.expand\", \"to expand\")})`;\n\t\t}\n\t}\n\n\tconst resultLimit = result.details?.resultLimitReached;\n\tconst truncation = result.details?.truncation;\n\tif (resultLimit || truncation?.truncated) {\n\t\tconst warnings: string[] = [];\n\t\tif (resultLimit) warnings.push(`${resultLimit} results limit`);\n\t\tif (truncation?.truncated) warnings.push(`${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit`);\n\t\ttext += `\\n${theme.fg(\"warning\", `[Truncated: ${warnings.join(\", \")}]`)}`;\n\t}\n\treturn text;\n}\n\nfunction hasGlobSyntax(pattern: string): boolean {\n\treturn pattern === \".\" || /[*?[{]/.test(pattern);\n}\n\nfunction fffQueryParts(parts: string[]): string {\n\treturn parts.filter(Boolean).join(\" \");\n}\n\nfunction toSearchRelative(repoRelativePath: string, searchPathRelativeToCwd: string): string | undefined {\n\tif (!searchPathRelativeToCwd) return repoRelativePath;\n\tconst prefix = `${searchPathRelativeToCwd}/`;\n\tif (!repoRelativePath.startsWith(prefix)) return undefined;\n\treturn repoRelativePath.slice(prefix.length);\n}\n\nfunction fffGlobPattern(pattern: string, searchPathRelativeToCwd: string): string {\n\tconst effectivePattern = pattern === \".\" ? \"**/*\" : pattern;\n\tif (!searchPathRelativeToCwd) {\n\t\tif (effectivePattern.includes(\"/\") || effectivePattern.startsWith(\"**/\")) return effectivePattern;\n\t\treturn `**/${effectivePattern}`;\n\t}\n\tif (effectivePattern === \"**\" || effectivePattern === \"**/*\") return `${searchPathRelativeToCwd}/**/*`;\n\tif (effectivePattern.includes(\"/\")) return `${searchPathRelativeToCwd}/${effectivePattern}`;\n\treturn `${searchPathRelativeToCwd}/**/${effectivePattern}`;\n}\n\ninterface FindPackingOptions {\n\ttoolCallId: string;\n\tartifactStore?: ArtifactStore;\n\tbroadQueryTracker?: BroadQueryTracker;\n\tpattern: string;\n\trawPath?: string;\n}\n\nfunction fffSearchOutput(\n\tresult: FffSearchResult,\n\tsearchPathRelativeToCwd: string,\n\teffectiveLimit: number,\n\tpacking: FindPackingOptions,\n) {\n\tconst relativized = result.items\n\t\t.map((item) => toSearchRelative(item.relativePath, searchPathRelativeToCwd))\n\t\t.filter((item): item is string => Boolean(item));\n\treturn formatFindResults(relativized, effectiveLimit, packing);\n}\n\nexport async function tryFffFind(options: {\n\tbackend: FffSearchBackend;\n\trouter: SearchRouter;\n\tcwd: string;\n\tsearchPath: string;\n\tpattern: string;\n\tignoreCase?: boolean;\n\teffectiveLimit: number;\n\ttoolCallId: string;\n\tartifactStore?: ArtifactStore;\n\tbroadQueryTracker?: BroadQueryTracker;\n\trawPath?: string;\n}): Promise<{ text: string; details: FindToolDetails } | undefined> {\n\tif (!(await pathExists(options.searchPath))) return undefined;\n\n\t// Kick off the FFF finder -- and, on a machine where fff-node isn't provisioned\n\t// yet, its lazy managed install -- unconditionally and as early as possible.\n\t// Routing below can still send THIS call to the fd fallback for reasons that\n\t// have nothing to do with tool availability (most commonly: the default result\n\t// limit is well above the FFF top-N threshold, see search-router.ts). That\n\t// outcome must not gate the install itself, or a machine that only ever issues\n\t// default-limit searches would never provision fff-node at all. getFinder() is\n\t// cached per basePath, so this costs nothing beyond the first call for a given\n\t// cwd -- the `await` further down, when this call does want FFF, reuses this\n\t// same in-flight/resolved promise instead of triggering the work twice.\n\t// safeGetFinder() guarantees this can never reject (a non-conforming custom\n\t// backend that throws synchronously still degrades to \"unavailable\"), so it\n\t// can neither produce an unhandled rejection nor fail this tool call outright.\n\tconst finderPromise = safeGetFinder(options.backend, options.cwd);\n\n\tconst searchPathRelativeToCwd = relativePathInside(options.cwd, options.searchPath);\n\tconst glob = hasGlobSyntax(options.pattern);\n\tconst baseRoute = options.router.route({\n\t\ttool: \"find\",\n\t\tglob,\n\t\tignoreCase: Boolean(options.ignoreCase),\n\t\tlimit: options.effectiveLimit,\n\t\tfinderAvailable: true,\n\t\tpathResolvable: searchPathRelativeToCwd !== undefined,\n\t\tgitignoreInTree: false,\n\t});\n\tif (baseRoute.backend !== \"fff\") return undefined;\n\tif (searchPathRelativeToCwd === undefined) return undefined;\n\n\tconst gitignoreInTree = await hasGitignoreInTree(options.searchPath);\n\tconst semanticRoute = options.router.route({\n\t\ttool: \"find\",\n\t\tglob,\n\t\tignoreCase: Boolean(options.ignoreCase),\n\t\tlimit: options.effectiveLimit,\n\t\tfinderAvailable: true,\n\t\tpathResolvable: true,\n\t\tgitignoreInTree,\n\t});\n\tif (semanticRoute.backend !== \"fff\") return undefined;\n\n\tconst finder = await finderPromise;\n\tconst finderRoute = options.router.route({\n\t\ttool: \"find\",\n\t\tglob,\n\t\tignoreCase: Boolean(options.ignoreCase),\n\t\tlimit: options.effectiveLimit,\n\t\tfinderAvailable: Boolean(finder),\n\t\tpathResolvable: true,\n\t\tgitignoreInTree: false,\n\t});\n\tif (!finder || finderRoute.backend !== \"fff\") return undefined;\n\n\tconst packing: FindPackingOptions = {\n\t\ttoolCallId: options.toolCallId,\n\t\tartifactStore: options.artifactStore,\n\t\tbroadQueryTracker: options.broadQueryTracker,\n\t\tpattern: options.pattern,\n\t\trawPath: options.rawPath,\n\t};\n\n\tconst probeLimit = options.effectiveLimit + 1;\n\tif (glob) {\n\t\tconst result = finder.glob(fffGlobPattern(options.pattern, searchPathRelativeToCwd), {\n\t\t\tpageSize: probeLimit,\n\t\t});\n\t\treturn result.ok\n\t\t\t? fffSearchOutput(result.value, searchPathRelativeToCwd, options.effectiveLimit, packing)\n\t\t\t: undefined;\n\t}\n\n\tconst pathConstraint = searchPathRelativeToCwd ? `${searchPathRelativeToCwd}/` : \"\";\n\tconst result = finder.fileSearch(fffQueryParts([pathConstraint, options.pattern]), {\n\t\tpageSize: probeLimit,\n\t});\n\treturn result.ok\n\t\t? fffSearchOutput(result.value, searchPathRelativeToCwd, options.effectiveLimit, packing)\n\t\t: undefined;\n}\n\nfunction formatFindResults(\n\trelativized: string[],\n\teffectiveLimit: number,\n\tpacking: FindPackingOptions,\n): { text: string; details: FindToolDetails } {\n\tif (relativized.length === 0) {\n\t\treturn { text: \"No files found matching pattern\", details: {} };\n\t}\n\n\tconst resultLimitReached = relativized.length > effectiveLimit;\n\tconst displayedResults = resultLimitReached ? relativized.slice(0, effectiveLimit) : relativized;\n\tconst dirGroups = new Map<string, string[]>();\n\tconst extCounts = new Map<string, number>();\n\n\tfor (const p of displayedResults) {\n\t\tconst dir = path.dirname(p);\n\t\tconst base = path.basename(p);\n\t\tconst dirKey = dir === \".\" ? \"./\" : `${dir}/`;\n\t\tif (!dirGroups.has(dirKey)) {\n\t\t\tdirGroups.set(dirKey, []);\n\t\t}\n\t\tdirGroups.get(dirKey)!.push(base);\n\n\t\tconst ext = path.extname(p).toLowerCase() || \"(no extension)\";\n\t\textCounts.set(ext, (extCounts.get(ext) || 0) + 1);\n\t}\n\n\tconst sortedDirs = Array.from(dirGroups.keys()).sort((a, b) => a.localeCompare(b));\n\tconst formattedLines: string[] = [];\n\tfor (const dir of sortedDirs) {\n\t\tformattedLines.push(dir);\n\t\tconst files = dirGroups.get(dir)!;\n\t\tfiles.sort((a, b) => a.localeCompare(b));\n\t\tfor (const file of files) {\n\t\t\tformattedLines.push(` ${file}`);\n\t\t}\n\t}\n\n\tconst extSummaryParts = Array.from(extCounts.entries())\n\t\t.sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))\n\t\t.map(([ext, count]) => `${ext}: ${count}`);\n\tconst extSummary = `Extensions: ${extSummaryParts.join(\", \")}`;\n\n\tconst rawOutput = formattedLines.join(\"\\n\");\n\t// Measure -> pack (artifact-backed if oversized and a store was provided) -> notices.\n\tconst packed = packToolOutput(\n\t\t{\n\t\t\ttoolName: \"find\",\n\t\t\tpath: packing.rawPath,\n\t\t\trawContent: rawOutput,\n\t\t\t// No line limit here because the result limit already caps rows; only the byte\n\t\t\t// cap should apply, matching the pre-Slice-B truncateHead call exactly.\n\t\t\ttruncation: { maxLines: Number.MAX_SAFE_INTEGER },\n\t\t},\n\t\tpacking.artifactStore,\n\t\tpacking.toolCallId,\n\t);\n\tlet resultOutput = packed.content;\n\tconst details: FindToolDetails = {};\n\tconst notices: string[] = [];\n\tif (packed.artifactId) {\n\t\tnotices.push(formatArtifactNotice(packed.artifactId));\n\t\tdetails.artifactId = packed.artifactId;\n\t}\n\tif (resultLimitReached) {\n\t\tnotices.push(\n\t\t\t`${effectiveLimit} results limit reached. Use limit=${effectiveLimit * 2} for more, or narrow path/pattern`,\n\t\t);\n\t\tdetails.resultLimitReached = effectiveLimit;\n\t}\n\tif (packed.truncation.truncated) {\n\t\tnotices.push(`${formatSize(DEFAULT_MAX_BYTES)} limit reached`);\n\t\t// Drop the duplicated bounded-preview text: it's already in the message's own\n\t\t// content, and re-including it here can push `details` past\n\t\t// MAX_RETAINED_TOOL_RESULT_DETAILS_BYTES (message-retention.ts), which replaces\n\t\t// the *entire* details object with a stub -- silently losing artifactId and every\n\t\t// other field alongside it. This is load-bearing beyond just the retention budget:\n\t\t// agent-session.ts's _releaseGcPackedArtifactReferences() reads artifactId back off\n\t\t// this same canonical message at eviction time (potentially many turns later), so\n\t\t// keeping `details` small here is what keeps that release path working at all. If\n\t\t// this field ever grows a large addition again, add a regression proving artifactId\n\t\t// survives compactToolResultDetailsForRetention (see\n\t\t// test/suite/agent-session-artifact-lifecycle.test.ts), not just a details-size check.\n\t\tdetails.truncation = { ...packed.truncation, content: \"\" };\n\t}\n\tif (resultLimitReached || packed.truncation.truncated) {\n\t\tconst note = broadQueryInvalidationNote(\n\t\t\tpacking.broadQueryTracker,\n\t\t\tnormalizeBroadQueryKey({ toolName: \"find\", pattern: packing.pattern, path: packing.rawPath }),\n\t\t\t`find \"${packing.pattern}\" in ${packing.rawPath ?? \".\"}`,\n\t\t);\n\t\tif (note) {\n\t\t\tnotices.push(note);\n\t\t\tdetails.invalidationCandidate = true;\n\t\t}\n\t}\n\tif (displayedResults.length > 0) {\n\t\tresultOutput += `\\n\\n[Summary - ${extSummary}]`;\n\t}\n\tif (notices.length > 0) {\n\t\tresultOutput += `\\n\\n[${notices.join(\". \")}]`;\n\t}\n\treturn { text: resultOutput, details };\n}\n\nexport function createFindToolDefinition(\n\tcwd: string,\n\toptions?: FindToolOptions,\n): ToolDefinition<typeof findSchema, FindToolDetails | undefined> {\n\tconst customOps = options?.operations;\n\tconst fffBackend = options?.fff === false ? undefined : (options?.fff ?? defaultFffSearchBackend);\n\tconst searchRouter = options?.searchRouter ?? defaultSearchRouter;\n\tconst artifactStore = options?.artifactStore;\n\tconst broadQueryTracker = options?.broadQueryTracker;\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: \"Find files by glob pattern (respects .gitignore)\",\n\t\tparameters: findSchema,\n\t\ttoolGroup: \"explore\",\n\t\tasync execute(\n\t\t\ttoolCallId,\n\t\t\t{\n\t\t\t\tpattern,\n\t\t\t\tpath: searchDir,\n\t\t\t\tlimit,\n\t\t\t\tignoreCase,\n\t\t\t}: { pattern: string; path?: string; limit?: number; ignoreCase?: boolean },\n\t\t\tsignal?: AbortSignal,\n\t\t\t_onUpdate?,\n\t\t\t_ctx?,\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 || \".\", cwd);\n\t\t\t\t\t\tconst effectiveLimit = limit ?? DEFAULT_LIMIT;\n\t\t\t\t\t\tconst probeLimit = effectiveLimit + 1;\n\t\t\t\t\t\tconst ops = customOps ?? defaultFindOperations;\n\n\t\t\t\t\t\tlet effectivePattern = pattern;\n\t\t\t\t\t\tif (pattern === \".\") {\n\t\t\t\t\t\t\teffectivePattern = \"**/*\";\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (!customOps && fffBackend) {\n\t\t\t\t\t\t\tconst fffResult = await tryFffFind({\n\t\t\t\t\t\t\t\tbackend: fffBackend,\n\t\t\t\t\t\t\t\trouter: searchRouter,\n\t\t\t\t\t\t\t\tcwd,\n\t\t\t\t\t\t\t\tsearchPath,\n\t\t\t\t\t\t\t\tpattern: effectivePattern,\n\t\t\t\t\t\t\t\tignoreCase,\n\t\t\t\t\t\t\t\teffectiveLimit,\n\t\t\t\t\t\t\t\ttoolCallId,\n\t\t\t\t\t\t\t\tartifactStore,\n\t\t\t\t\t\t\t\tbroadQueryTracker,\n\t\t\t\t\t\t\t\trawPath: searchDir,\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 (fffResult) {\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: fffResult.text }],\n\t\t\t\t\t\t\t\t\t\tdetails: Object.keys(fffResult.details).length > 0 ? fffResult.details : 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\t\t\t\t\t\t}\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\tconst results = await ops.glob(effectivePattern, searchPath, {\n\t\t\t\t\t\t\t\tignore: [\"**/node_modules/**\", \"**/.git/**\"],\n\t\t\t\t\t\t\t\tlimit: probeLimit,\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\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.map((p) => {\n\t\t\t\t\t\t\t\tif (p.startsWith(searchPath)) return toPosixPath(p.slice(searchPath.length + 1));\n\t\t\t\t\t\t\t\treturn toPosixPath(path.relative(searchPath, p));\n\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\tconst formatted = formatFindResults(relativized, effectiveLimit, {\n\t\t\t\t\t\t\t\ttoolCallId,\n\t\t\t\t\t\t\t\tartifactStore,\n\t\t\t\t\t\t\t\tbroadQueryTracker,\n\t\t\t\t\t\t\t\tpattern: effectivePattern,\n\t\t\t\t\t\t\t\trawPath: searchDir,\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: formatted.text }],\n\t\t\t\t\t\t\t\t\tdetails: Object.keys(formatted.details).length > 0 ? formatted.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\", true);\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\t// Build fd arguments. --no-require-git makes fd apply hierarchical .gitignore\n\t\t\t\t\t\t// semantics whether or not the search path is inside a git repository, without\n\t\t\t\t\t\t// leaking sibling-directory rules the way --ignore-file (a global source) would.\n\t\t\t\t\t\tconst args: string[] = [\n\t\t\t\t\t\t\t\"--glob\",\n\t\t\t\t\t\t\t\"--color=never\",\n\t\t\t\t\t\t\t\"--hidden\",\n\t\t\t\t\t\t\t\"--no-require-git\",\n\t\t\t\t\t\t\t\"--max-results\",\n\t\t\t\t\t\t\tString(probeLimit),\n\t\t\t\t\t\t];\n\t\t\t\t\t\tif (ignoreCase) {\n\t\t\t\t\t\t\targs.push(\"--ignore-case\");\n\t\t\t\t\t\t}\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\tlet finalPattern = effectivePattern;\n\t\t\t\t\t\tif (effectivePattern.includes(\"/\")) {\n\t\t\t\t\t\t\targs.push(\"--full-path\");\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t!effectivePattern.startsWith(\"/\") &&\n\t\t\t\t\t\t\t\t!effectivePattern.startsWith(\"**/\") &&\n\t\t\t\t\t\t\t\teffectivePattern !== \"**\"\n\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\tfinalPattern = `**/${effectivePattern}`;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\targs.push(\"--\", finalPattern, searchPath);\n\n\t\t\t\t\t\tconst child = spawn(fdPath, args, {\n\t\t\t\t\t\t\tdetached: process.platform !== \"win32\",\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\tconst lines: string[] = [];\n\t\t\t\t\t\tconst terminationController = new AbortController();\n\n\t\t\t\t\t\tstopChild = () => terminationController.abort();\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\", (line) => {\n\t\t\t\t\t\t\tlines.push(line);\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\tconst terminal = await waitForChildProcessWithTermination(child, {\n\t\t\t\t\t\t\tsignal: terminationController.signal,\n\t\t\t\t\t\t\ttimeoutMs: FIND_PROCESS_TIMEOUT_MS,\n\t\t\t\t\t\t\tkillGraceMs: FIND_PROCESS_KILL_GRACE_MS,\n\t\t\t\t\t\t}).finally(cleanup);\n\t\t\t\t\t\tconst code = terminal.code;\n\t\t\t\t\t\tif (terminal.reason === \"timeout\") {\n\t\t\t\t\t\t\tsettle(() => reject(new Error(`fd timed out after ${FIND_PROCESS_TIMEOUT_MS}ms`)));\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\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 output = lines.join(\"\\n\");\n\t\t\t\t\t\tif (code !== 0) {\n\t\t\t\t\t\t\tconst errorMsg = stderr.trim() || `fd exited with code ${code}`;\n\t\t\t\t\t\t\tif (!output) {\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}\n\n\t\t\t\t\t\tconst relativized: string[] = [];\n\t\t\t\t\t\tfor (const rawLine of lines) {\n\t\t\t\t\t\t\tconst line = rawLine.replace(/\\r$/, \"\").trim();\n\t\t\t\t\t\t\tif (!line) continue;\n\t\t\t\t\t\t\tconst hadTrailingSlash = line.endsWith(\"/\") || line.endsWith(\"\\\\\");\n\t\t\t\t\t\t\tlet relativePath = line;\n\t\t\t\t\t\t\tif (line.startsWith(searchPath)) {\n\t\t\t\t\t\t\t\trelativePath = line.slice(searchPath.length + 1);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\trelativePath = path.relative(searchPath, line);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (hadTrailingSlash && !relativePath.endsWith(\"/\")) relativePath += \"/\";\n\t\t\t\t\t\t\trelativized.push(toPosixPath(relativePath));\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst formatted = formatFindResults(relativized, effectiveLimit, {\n\t\t\t\t\t\t\ttoolCallId,\n\t\t\t\t\t\t\tartifactStore,\n\t\t\t\t\t\t\tbroadQueryTracker,\n\t\t\t\t\t\t\tpattern: effectivePattern,\n\t\t\t\t\t\t\trawPath: searchDir,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tsettle(() =>\n\t\t\t\t\t\t\tresolve({\n\t\t\t\t\t\t\t\tcontent: [{ type: \"text\", text: formatted.text }],\n\t\t\t\t\t\t\t\tdetails: Object.keys(formatted.details).length > 0 ? formatted.details : undefined,\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\trenderCall(args, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatFindCall(args, theme, context.cwd));\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatFindResult(result as any, options, theme, context.showImages));\n\t\t\treturn text;\n\t\t},\n\t};\n}\n\nexport function createFindTool(cwd: string, options?: FindToolOptions): AgentTool<typeof findSchema> {\n\treturn wrapToolDefinition(createFindToolDefinition(cwd, options));\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"git-filter.d.ts","sourceRoot":"","sources":["../../../src/core/tools/git-filter.ts"],"names":[],"mappings":"AAyCA,MAAM,WAAW,YAAY;IAC5B,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,mGAAmG;IACnG,cAAc,CAAC,EAAE,MAAM,CAAC;CACxB;AAED,UAAU,cAAc;IACvB,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IACtB,mFAAmF;IACnF,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,oFAAoF;IACpF,QAAQ,CAAC,EAAE;QAAE,cAAc,EAAE,MAAM,CAAC;QAAC,UAAU,EAAE,MAAM,CAAA;KAAE,CAAC;CAC1D;AAED,UAAU,gBAAgB;IACzB,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,OAAO,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,MAAM,CAItE;AAED,wBAAgB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CAAC,YAAY,CAAC,CA6BvB;AAED,wBAAgB,wBAAwB,CAAC,aAAa,EAAE,MAAM,EAAE,EAAE,UAAU,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,GAAG,MAAM,CAE5G","sourcesContent":["import { spawn } from \"node:child_process\";\nimport { randomBytes } from \"node:crypto\";\nimport { existsSync, type WriteStream } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join, resolve } from \"node:path\";\nimport { waitForChildProcess } from \"../../utils/child-process.ts\";\nimport { createSafeWriteStream } from \"../../utils/safe-write-stream.ts\";\nimport { killProcessTree, trackDetachedChildPid, untrackDetachedChildPid } from \"../../utils/shell.ts\";\n\n/**\n * Retention budget for git output held in memory while filtering. Output beyond\n * the budget is spilled to a temp file so a giant `git log -p`/`git diff` cannot\n * exhaust the V8 heap. Override with PI_GIT_FILTER_MAX_RETAINED_BYTES.\n */\nconst DEFAULT_MAX_RETAINED_GIT_OUTPUT_BYTES = 48 * 1024 * 1024;\nconst MAX_RETAINED_GIT_STDERR_BYTES = 8 * 1024 * 1024;\n\nfunction maxRetainedGitOutputBytes(): number {\n\tconst raw = process.env.PI_GIT_FILTER_MAX_RETAINED_BYTES;\n\tif (raw !== undefined) {\n\t\tconst parsed = Number.parseInt(raw, 10);\n\t\tif (Number.isFinite(parsed) && parsed > 0) return parsed;\n\t}\n\treturn DEFAULT_MAX_RETAINED_GIT_OUTPUT_BYTES;\n}\n\nconst SUPPORTED_SUBCOMMANDS = new Set([\n\t\"status\",\n\t\"log\",\n\t\"diff\",\n\t\"show\",\n\t\"add\",\n\t\"commit\",\n\t\"push\",\n\t\"pull\",\n\t\"branch\",\n\t\"fetch\",\n\t\"stash\",\n\t\"worktree\",\n]);\n\nexport interface FilterResult {\n\toutput: string;\n\texitCode: number;\n\trawOut: string;\n\trawBytes?: Buffer;\n\t/** Set when git output exceeded the in-memory retention budget; the file holds the full output. */\n\tfullOutputPath?: string;\n}\n\ninterface GitQueryResult {\n\tstdout: string;\n\tstderr: string;\n\tstatus: number | null;\n\t/** Full raw output (stderr then stdout). Absent when output overflowed to disk. */\n\trawBytes?: Buffer;\n\t/** Set when stdout exceeded the retention budget and was spilled to a temp file. */\n\toverflow?: { fullOutputPath: string; totalBytes: number };\n}\n\ninterface GitFilterOptions {\n\tsignal?: AbortSignal;\n\ttimeout?: number;\n}\n\nexport function unicodeTruncate(str: string, maxLength: number): string {\n\tconst chars = Array.from(str);\n\tif (chars.length <= maxLength) return str;\n\treturn `${chars.slice(0, maxLength).join(\"\")}...`;\n}\n\nexport function tokenizeCommand(command: string): string[] | null {\n\tconst args: string[] = [];\n\tlet current = \"\";\n\tlet inDoubleQuotes = false;\n\tlet inSingleQuotes = false;\n\tlet escapeNext = false;\n\n\tfor (let i = 0; i < command.length; i++) {\n\t\tconst char = command[i];\n\t\tif (escapeNext) {\n\t\t\tcurrent += char;\n\t\t\tescapeNext = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (char === \"\\\\\" && !inSingleQuotes) {\n\t\t\tescapeNext = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (char === '\"' && !inSingleQuotes) {\n\t\t\tinDoubleQuotes = !inDoubleQuotes;\n\t\t} else if (char === \"'\" && !inDoubleQuotes) {\n\t\t\tinSingleQuotes = !inSingleQuotes;\n\t\t} else if (/\\s/.test(char) && !inDoubleQuotes && !inSingleQuotes) {\n\t\t\tif (current) {\n\t\t\t\targs.push(current);\n\t\t\t\tcurrent = \"\";\n\t\t\t}\n\t\t} else {\n\t\t\tcurrent += char;\n\t\t}\n\t}\n\tif (inDoubleQuotes || inSingleQuotes || escapeNext) return null;\n\tif (current) args.push(current);\n\treturn args;\n}\n\nexport interface ParsedCommand {\n\tenvVars: Record<string, string>;\n\tcoreCommandTokens: string[];\n}\n\nexport function parseCommandPrefixes(command: string): ParsedCommand | null {\n\tconst tokens = tokenizeCommand(command);\n\tif (!tokens || tokens.length === 0) return null;\n\n\tconst envVars: Record<string, string> = {};\n\tlet i = 0;\n\tconst envPattern = /^([a-zA-Z_][a-zA-Z0-9_]*)=(.*)$/;\n\n\twhile (i < tokens.length) {\n\t\tconst token = tokens[i];\n\t\tconst match = token.match(envPattern);\n\t\tif (!match) break;\n\t\tlet value = match[2];\n\t\tif ((value.startsWith('\"') && value.endsWith('\"')) || (value.startsWith(\"'\") && value.endsWith(\"'\"))) {\n\t\t\tvalue = value.slice(1, -1);\n\t\t}\n\t\tenvVars[match[1]] = value;\n\t\ti++;\n\t}\n\n\treturn { envVars, coreCommandTokens: tokens.slice(i) };\n}\n\nexport function isComplexShellCommand(command: string): boolean {\n\treturn /[|><&;\\n\\r$`()*?[\\]#]/.test(command);\n}\n\nfunction quoteForShell(arg: string): string {\n\tif (/^[A-Za-z0-9_./:=+-]+$/.test(arg)) return arg;\n\treturn `'${arg.replace(/'/g, `'\"'\"'`)}'`;\n}\n\nfunction gitCommand(globalOptions: string[], args: string[]): string {\n\treturn [\"git\", ...globalOptions, ...args].map(quoteForShell).join(\" \");\n}\n\nfunction rawText(res: GitQueryResult, combine = false): string {\n\tif (combine) return `${res.stderr}${res.stderr && res.stdout ? \"\\n\" : \"\"}${res.stdout}`;\n\treturn res.stderr || res.stdout;\n}\n\nfunction applyOverflowDisclosure(res: GitQueryResult, result: FilterResult): FilterResult {\n\tif (!res.overflow) return result;\n\tconst totalMb = (res.overflow.totalBytes / (1024 * 1024)).toFixed(1);\n\treturn {\n\t\t...result,\n\t\toutput: `${result.output}\\n\\n[git output was ${totalMb}MB; filtered view computed from the retained head. Full output: ${res.overflow.fullOutputPath}]`,\n\t\tfullOutputPath: res.overflow.fullOutputPath,\n\t};\n}\n\nfunction resultFromQuery(res: GitQueryResult, output: string, exitCode = res.status ?? 0): FilterResult {\n\treturn applyOverflowDisclosure(res, { output, exitCode, rawOut: rawText(res), rawBytes: res.rawBytes });\n}\n\nexport async function runGitQuery(\n\tcwd: string,\n\tglobalOptions: string[],\n\targs: string[],\n\toptions?: GitFilterOptions,\n): Promise<GitQueryResult> {\n\tif (options?.signal?.aborted) throw new Error(\"aborted\");\n\n\tconst child = spawn(\"git\", [...globalOptions, ...args], {\n\t\tcwd,\n\t\tdetached: process.platform !== \"win32\",\n\t\tenv: { ...process.env, LC_ALL: \"C\" },\n\t\tstdio: [\"ignore\", \"pipe\", \"pipe\"],\n\t\twindowsHide: true,\n\t});\n\tif (child.pid) trackDetachedChildPid(child.pid);\n\n\tconst stdoutChunks: Buffer[] = [];\n\tconst stderrChunks: Buffer[] = [];\n\tconst maxRetainedBytes = maxRetainedGitOutputBytes();\n\tlet retainedStdoutBytes = 0;\n\tlet totalStdoutBytes = 0;\n\tlet retainedStderrBytes = 0;\n\tlet overflowPath: string | undefined;\n\tlet overflowStream: WriteStream | undefined;\n\tlet overflowStreamEnded = false;\n\tlet overflowWriteError: Error | undefined;\n\tlet timedOut = false;\n\tconst timeoutSeconds = options?.timeout;\n\tlet timeoutHandle: NodeJS.Timeout | undefined;\n\tconst killChild = () => {\n\t\tif (child.pid) killProcessTree(child.pid);\n\t};\n\n\ttry {\n\t\tif (timeoutSeconds !== undefined && timeoutSeconds > 0) {\n\t\t\ttimeoutHandle = setTimeout(() => {\n\t\t\t\ttimedOut = true;\n\t\t\t\tkillChild();\n\t\t\t}, timeoutSeconds * 1000);\n\t\t}\n\t\tif (options?.signal) {\n\t\t\tif (options.signal.aborted) killChild();\n\t\t\telse options.signal.addEventListener(\"abort\", killChild, { once: true });\n\t\t}\n\n\t\tchild.stdout?.on(\"data\", (chunk: Buffer) => {\n\t\t\ttotalStdoutBytes += chunk.length;\n\t\t\tif (overflowStream) {\n\t\t\t\toverflowStream.write(chunk);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tstdoutChunks.push(chunk);\n\t\t\tretainedStdoutBytes += chunk.length;\n\t\t\tif (retainedStdoutBytes > maxRetainedBytes) {\n\t\t\t\toverflowPath = join(tmpdir(), `pi-git-${randomBytes(8).toString(\"hex\")}.log`);\n\t\t\t\toverflowStream = createSafeWriteStream(overflowPath, (error) => {\n\t\t\t\t\toverflowWriteError = error;\n\t\t\t\t});\n\t\t\t\tfor (const retained of stdoutChunks) overflowStream.write(retained);\n\t\t\t}\n\t\t});\n\t\tchild.stderr?.on(\"data\", (chunk: Buffer) => {\n\t\t\tstderrChunks.push(chunk);\n\t\t\tretainedStderrBytes += chunk.length;\n\t\t\twhile (retainedStderrBytes > MAX_RETAINED_GIT_STDERR_BYTES && stderrChunks.length > 1) {\n\t\t\t\tretainedStderrBytes -= stderrChunks.shift()?.length ?? 0;\n\t\t\t}\n\t\t});\n\t\tconst status = await waitForChildProcess(child);\n\t\tif (options?.signal?.aborted) throw new Error(\"aborted\");\n\t\tif (timedOut) throw new Error(`timeout:${timeoutSeconds}`);\n\t\tconst stdoutBuffer = Buffer.concat(stdoutChunks);\n\t\tconst stderrBuffer = Buffer.concat(stderrChunks);\n\t\tif (overflowStream !== undefined && overflowPath !== undefined) {\n\t\t\tif (stderrBuffer.length > 0 && !overflowStream.writableEnded) {\n\t\t\t\toverflowStream.write(\"\\n--- stderr ---\\n\");\n\t\t\t\toverflowStream.write(stderrBuffer);\n\t\t\t}\n\t\t\tconst stream = overflowStream;\n\t\t\tawait new Promise<void>((resolveEnd) => {\n\t\t\t\tstream.end(() => resolveEnd());\n\t\t\t});\n\t\t\toverflowStreamEnded = true;\n\t\t\tif (overflowWriteError !== undefined) {\n\t\t\t\t// Spill failed (e.g. disk full): disclose the loss instead of pointing\n\t\t\t\t// consumers at a broken artifact, and keep the retained head usable.\n\t\t\t\treturn {\n\t\t\t\t\tstdout: stdoutBuffer.toString(\"utf-8\"),\n\t\t\t\t\tstderr: `${stderrBuffer.toString(\"utf-8\")}\\n[git output overflow spill failed: ${overflowWriteError.message}; output beyond the retained head was lost]`,\n\t\t\t\t\tstatus,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tstdout: stdoutBuffer.toString(\"utf-8\"),\n\t\t\t\tstderr: stderrBuffer.toString(\"utf-8\"),\n\t\t\t\tstatus,\n\t\t\t\toverflow: { fullOutputPath: overflowPath, totalBytes: totalStdoutBytes },\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\tstdout: stdoutBuffer.toString(\"utf-8\"),\n\t\t\tstderr: stderrBuffer.toString(\"utf-8\"),\n\t\t\tstatus,\n\t\t\trawBytes: Buffer.concat([stderrBuffer, stdoutBuffer]),\n\t\t};\n\t} finally {\n\t\tif (child.pid) untrackDetachedChildPid(child.pid);\n\t\tif (timeoutHandle) clearTimeout(timeoutHandle);\n\t\tif (options?.signal) options.signal.removeEventListener(\"abort\", killChild);\n\t\tif (overflowStream !== undefined && !overflowStreamEnded) overflowStream.end();\n\t}\n}\n\nexport function classifyGitCommand(\n\tcommand: string,\n\tparentEnv?: NodeJS.ProcessEnv,\n): {\n\teligible: boolean;\n\tsubcommand?: string;\n\tglobalOptions?: string[];\n\tsubcommandArgs?: string[];\n\tlocalEnv?: Record<string, string>;\n} {\n\tif (isComplexShellCommand(command)) return { eligible: false };\n\n\tconst parsed = parseCommandPrefixes(command);\n\tif (!parsed || parsed.coreCommandTokens.length === 0) return { eligible: false };\n\n\tconst { envVars, coreCommandTokens } = parsed;\n\tconst toolFilterDisabled =\n\t\tprocess.env.PI_TOOL_FILTER_DISABLED === \"1\" ||\n\t\tparentEnv?.PI_TOOL_FILTER_DISABLED === \"1\" ||\n\t\tenvVars.PI_TOOL_FILTER_DISABLED === \"1\";\n\tconst gitFilterDisabled =\n\t\tprocess.env.PI_GIT_FILTER_DISABLED === \"1\" ||\n\t\tparentEnv?.PI_GIT_FILTER_DISABLED === \"1\" ||\n\t\tenvVars.PI_GIT_FILTER_DISABLED === \"1\";\n\tif (toolFilterDisabled || gitFilterDisabled) return { eligible: false };\n\n\tconst envKeys = Object.keys(envVars).filter(\n\t\t(key) => key !== \"PI_TOOL_FILTER_DISABLED\" && key !== \"PI_GIT_FILTER_DISABLED\",\n\t);\n\tif (envKeys.length > 0) return { eligible: false };\n\n\tconst cmdName = coreCommandTokens[0];\n\tif (cmdName !== \"git\" && cmdName !== \"yadm\") return { eligible: false };\n\n\tlet idx = 1;\n\tconst globalOptions: string[] = [];\n\twhile (idx < coreCommandTokens.length) {\n\t\tconst token = coreCommandTokens[idx];\n\t\tif (token === \"-C\" || token === \"-c\" || token === \"--git-dir\" || token === \"--work-tree\") {\n\t\t\tif (idx + 1 >= coreCommandTokens.length) return { eligible: false };\n\t\t\tglobalOptions.push(token, coreCommandTokens[idx + 1]);\n\t\t\tidx += 2;\n\t\t} else if (token.startsWith(\"--git-dir=\") || token.startsWith(\"--work-tree=\")) {\n\t\t\tglobalOptions.push(token);\n\t\t\tidx++;\n\t\t} else if (\n\t\t\ttoken === \"--no-pager\" ||\n\t\t\ttoken === \"--no-optional-locks\" ||\n\t\t\ttoken === \"--bare\" ||\n\t\t\ttoken === \"--literal-pathspecs\"\n\t\t) {\n\t\t\tglobalOptions.push(token);\n\t\t\tidx++;\n\t\t} else {\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (idx === coreCommandTokens.length) return { eligible: false };\n\tconst subcommand = coreCommandTokens[idx];\n\tif (!SUPPORTED_SUBCOMMANDS.has(subcommand)) return { eligible: false };\n\n\treturn {\n\t\teligible: true,\n\t\tsubcommand,\n\t\tglobalOptions,\n\t\tsubcommandArgs: coreCommandTokens.slice(idx + 1),\n\t\tlocalEnv: envVars,\n\t};\n}\n\nexport function detectGitState(gitDir: string): string[] {\n\tconst states: string[] = [];\n\tif (!gitDir) return states;\n\tif (existsSync(join(gitDir, \"rebase-merge\")) || existsSync(join(gitDir, \"rebase-apply\"))) {\n\t\tstates.push(\"rebase in progress\");\n\t}\n\tif (existsSync(join(gitDir, \"MERGE_HEAD\"))) states.push(\"merge in progress\");\n\tif (existsSync(join(gitDir, \"CHERRY_PICK_HEAD\"))) states.push(\"cherry-pick in progress\");\n\tif (existsSync(join(gitDir, \"REVERT_HEAD\"))) states.push(\"revert in progress\");\n\tif (existsSync(join(gitDir, \"BISECT_LOG\"))) states.push(\"bisect in progress\");\n\tif (existsSync(join(gitDir, \"applying\"))) states.push(\"am in progress\");\n\treturn states;\n}\n\nasync function handleStatus(\n\tcwd: string,\n\tglobalOptions: string[],\n\targs: string[],\n\toptions?: GitFilterOptions,\n): Promise<FilterResult> {\n\tconst isSimple =\n\t\targs.length === 0 || args.every((arg) => arg === \"-s\" || arg === \"--short\" || arg === \"-b\" || arg === \"--branch\");\n\n\tif (!isSimple) {\n\t\tconst res = await runGitQuery(cwd, globalOptions, [\"status\", ...args], options);\n\t\tconst rawOut = rawText(res);\n\t\tif (res.status !== 0) return { output: rawOut, exitCode: res.status ?? 1, rawOut, rawBytes: res.rawBytes };\n\t\tconst cleanedLines = res.stdout\n\t\t\t.split(\"\\n\")\n\t\t\t.map((line) => line.trimEnd())\n\t\t\t.filter((line) => line.length > 0 && !line.trim().startsWith(\"(use \"));\n\t\tconst output = cleanedLines.join(\"\\n\");\n\t\treturn resultFromQuery(res, output || \"success\", 0);\n\t}\n\n\tconst res = await runGitQuery(cwd, globalOptions, [\"status\", \"--porcelain=v1\", \"-b\"], options);\n\tlet rawOut = rawText(res);\n\tif (res.status !== 0) {\n\t\tif (rawOut.includes(\"not a git repository\")) rawOut = \"fatal: not a git repository\";\n\t\treturn { output: rawOut.trim(), exitCode: res.status ?? 1, rawOut, rawBytes: res.rawBytes };\n\t}\n\n\tconst lines = res.stdout.split(\"\\n\").filter((line) => line.trim().length > 0);\n\tlet branchLine = \"\";\n\tconst fileLines: string[] = [];\n\tfor (const line of lines) {\n\t\tif (line.startsWith(\"##\")) branchLine = line;\n\t\telse fileLines.push(line);\n\t}\n\n\tlet statePrefix = \"\";\n\tconst gitDirRes = await runGitQuery(cwd, globalOptions, [\"rev-parse\", \"--git-dir\"], options);\n\tif (gitDirRes.status === 0) {\n\t\tconst gitDir = resolve(cwd, gitDirRes.stdout.trim());\n\t\tconst states = detectGitState(gitDir);\n\t\tif (states.length > 0) statePrefix = `[${states.join(\", \")}]\\n`;\n\t}\n\n\tif (branchLine.includes(\"HEAD (no branch)\")) {\n\t\tconst headHashRes = await runGitQuery(cwd, globalOptions, [\"rev-parse\", \"--short\", \"HEAD\"], options);\n\t\tconst hash = headHashRes.status === 0 ? headHashRes.stdout.trim() : \"unknown\";\n\t\tbranchLine = `## HEAD (detached at ${hash})`;\n\t}\n\n\tif (fileLines.length === 0) {\n\t\treturn resultFromQuery(res, `${statePrefix}${branchLine}\\nnothing to commit, working tree clean`, 0);\n\t}\n\treturn resultFromQuery(res, `${statePrefix}${branchLine}\\n${fileLines.join(\"\\n\")}`, 0);\n}\n\nasync function handleLog(\n\tcwd: string,\n\tglobalOptions: string[],\n\targs: string[],\n\toptions?: GitFilterOptions,\n): Promise<FilterResult> {\n\tconst hasLimit = args.some(\n\t\t(arg) => /^-n\\d+$/.test(arg) || arg === \"-n\" || /^-?\\d+$/.test(arg) || arg.startsWith(\"--max-count\"),\n\t);\n\tconst hasPretty = args.some(\n\t\t(arg) => arg.startsWith(\"--pretty\") || arg.startsWith(\"--format\") || arg === \"--oneline\",\n\t);\n\n\tconst logArgs = hasLimit ? [\"log\", ...args] : [\"log\", \"-n\", \"10\", \"--no-merges\", ...args];\n\tconst res = await runGitQuery(cwd, globalOptions, logArgs, options);\n\tif (hasPretty) return resultFromQuery(res, rawText(res), res.status ?? 0);\n\n\tconst rawOut = rawText(res);\n\tif (res.status !== 0) return { output: rawOut, exitCode: res.status ?? 1, rawOut, rawBytes: res.rawBytes };\n\n\tconst commits = res.stdout.split(/(?=^commit [0-9a-f]{7,40})/m).filter((commit) => commit.trim().length > 0);\n\tconst compactedCommits: string[] = [];\n\tconst trailerPrefixes = [\n\t\t\"Signed-off-by:\",\n\t\t\"Co-authored-by:\",\n\t\t\"Reported-by:\",\n\t\t\"Reviewed-by:\",\n\t\t\"Tested-by:\",\n\t\t\"Suggested-by:\",\n\t\t\"CC:\",\n\t];\n\n\tfor (const commit of commits) {\n\t\tconst lines = commit.split(\"\\n\");\n\t\tconst commitLine = lines[0];\n\t\tif (!commitLine) continue;\n\t\tconst shortCommitLine = commitLine.replace(/^commit ([0-9a-f]{7})[0-9a-f]+/, \"commit $1\");\n\t\tconst bodyLines: string[] = [];\n\t\tfor (let i = 1; i < lines.length; i++) {\n\t\t\tconst line = lines[i];\n\t\t\tconst trimmed = line.trim();\n\t\t\tif (!trimmed) continue;\n\t\t\tif (line.startsWith(\"Author:\") || line.startsWith(\"Date:\") || line.startsWith(\"Merge:\")) continue;\n\t\t\tif (trailerPrefixes.some((prefix) => trimmed.startsWith(prefix))) continue;\n\t\t\tbodyLines.push(line);\n\t\t}\n\t\tconst displayBody = bodyLines.slice(0, 3).map((line) => unicodeTruncate(line, 160));\n\t\tconst omitted = bodyLines.length - displayBody.length;\n\t\tif (omitted > 0) displayBody.push(` ... (${omitted} lines omitted)`);\n\t\tcompactedCommits.push(`${shortCommitLine}\\n${displayBody.join(\"\\n\")}`);\n\t}\n\n\treturn resultFromQuery(res, compactedCommits.join(\"\\n\\n\"), 0);\n}\n\nexport function compactDiff(diffOutput: string, maxLines = 150): { compacted: string; truncated: boolean } {\n\tconst lines = diffOutput.split(\"\\n\");\n\tconst output: string[] = [];\n\tlet linesCount = 0;\n\tlet truncated = false;\n\tlet contextBuffer: string[] = [];\n\tlet trailingContextRemaining = 0;\n\n\tfor (const line of lines) {\n\t\tif (linesCount >= maxLines) {\n\t\t\ttruncated = true;\n\t\t\tbreak;\n\t\t}\n\t\tif (\n\t\t\tline.startsWith(\"diff --git\") ||\n\t\t\tline.startsWith(\"--- \") ||\n\t\t\tline.startsWith(\"+++ \") ||\n\t\t\tline.startsWith(\"index \")\n\t\t) {\n\t\t\tcontextBuffer = [];\n\t\t\ttrailingContextRemaining = 0;\n\t\t\toutput.push(line);\n\t\t\tlinesCount++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (line.startsWith(\"@@ \")) {\n\t\t\tcontextBuffer = [];\n\t\t\ttrailingContextRemaining = 0;\n\t\t\toutput.push(line);\n\t\t\tlinesCount++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (line.startsWith(\"+\") || line.startsWith(\"-\")) {\n\t\t\tfor (const ctx of contextBuffer) {\n\t\t\t\tif (linesCount >= maxLines) {\n\t\t\t\t\ttruncated = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\toutput.push(ctx);\n\t\t\t\tlinesCount++;\n\t\t\t}\n\t\t\tcontextBuffer = [];\n\t\t\tif (truncated) break;\n\t\t\toutput.push(line);\n\t\t\tlinesCount++;\n\t\t\ttrailingContextRemaining = 3;\n\t\t\tcontinue;\n\t\t}\n\t\tif (line.startsWith(\" \")) {\n\t\t\tif (trailingContextRemaining > 0) {\n\t\t\t\toutput.push(line);\n\t\t\t\tlinesCount++;\n\t\t\t\ttrailingContextRemaining--;\n\t\t\t} else {\n\t\t\t\tcontextBuffer.push(line);\n\t\t\t\tif (contextBuffer.length > 3) contextBuffer.shift();\n\t\t\t}\n\t\t} else {\n\t\t\toutput.push(line);\n\t\t\tlinesCount++;\n\t\t}\n\t}\n\n\treturn { compacted: output.join(\"\\n\"), truncated };\n}\n\nasync function handleDiff(\n\tcwd: string,\n\tglobalOptions: string[],\n\targs: string[],\n\toptions?: GitFilterOptions,\n): Promise<FilterResult> {\n\tconst cleanArgs = [...args];\n\tconst noCompactIndex = cleanArgs.indexOf(\"--no-compact\");\n\tconst optOut = noCompactIndex !== -1;\n\tif (optOut) cleanArgs.splice(noCompactIndex, 1);\n\n\tconst statFlags = [\"--stat\", \"--numstat\", \"--shortstat\", \"--summary\", \"--name-only\", \"--name-status\", \"--check\"];\n\tconst isStatOnly = cleanArgs.some((arg) => statFlags.includes(arg));\n\tif (optOut || isStatOnly) {\n\t\tconst res = await runGitQuery(cwd, globalOptions, [\"diff\", ...cleanArgs], options);\n\t\treturn resultFromQuery(res, rawText(res), res.status ?? 0);\n\t}\n\n\tconst hasDoubleDash = cleanArgs.includes(\"--\");\n\tif (!hasDoubleDash) {\n\t\tconst pathIdx = cleanArgs.findIndex((arg) => {\n\t\t\tif (arg.startsWith(\"-\")) return false;\n\t\t\tif (!(arg.includes(\"/\") || arg.includes(\".\") || existsSync(join(cwd, arg)))) return false;\n\t\t\treturn existsSync(resolve(cwd, arg));\n\t\t});\n\t\tif (pathIdx !== -1) cleanArgs.splice(pathIdx, 0, \"--\");\n\t}\n\n\tconst statRes = await runGitQuery(cwd, globalOptions, [\"diff\", \"--stat\", ...cleanArgs], options);\n\tif (statRes.status !== 0) return resultFromQuery(statRes, rawText(statRes), statRes.status ?? 1);\n\tconst diffRes = await runGitQuery(cwd, globalOptions, [\"diff\", ...cleanArgs], options);\n\tif (diffRes.status !== 0) return resultFromQuery(diffRes, rawText(diffRes), diffRes.status ?? 1);\n\n\tconst { compacted, truncated } = compactDiff(diffRes.stdout);\n\tlet output = `${statRes.stdout.trimEnd()}\\n\\n${compacted}`.trim();\n\tif (truncated) output += \"\\n\\n[Diff truncated. Re-run with: git diff --no-compact]\";\n\treturn applyOverflowDisclosure(diffRes, { output, exitCode: 0, rawOut: diffRes.stdout, rawBytes: diffRes.rawBytes });\n}\n\nasync function handleShow(\n\tcwd: string,\n\tglobalOptions: string[],\n\targs: string[],\n\toptions?: GitFilterOptions,\n): Promise<FilterResult> {\n\tconst statFlags = [\"--stat\", \"--numstat\", \"--shortstat\", \"--summary\", \"--name-only\", \"--name-status\", \"--check\"];\n\tconst hasStatOnly = args.some((arg) => statFlags.includes(arg));\n\tconst hasPretty = args.some(\n\t\t(arg) => arg.startsWith(\"--pretty\") || arg.startsWith(\"--format\") || arg === \"--oneline\",\n\t);\n\tconst hasBlob = args.some((arg) => !arg.startsWith(\"-\") && arg.includes(\":\"));\n\tif (hasStatOnly || hasPretty || hasBlob) {\n\t\tconst res = await runGitQuery(cwd, globalOptions, [\"show\", ...args], options);\n\t\treturn resultFromQuery(res, rawText(res), res.status ?? 0);\n\t}\n\n\tconst showRes = await runGitQuery(cwd, globalOptions, [\"show\", ...args], options);\n\tconst rawOut = rawText(showRes);\n\tif (showRes.status !== 0)\n\t\treturn { output: rawOut, exitCode: showRes.status ?? 1, rawOut, rawBytes: showRes.rawBytes };\n\n\tconst lines = showRes.stdout.split(\"\\n\");\n\tconst diffStart = lines.findIndex((line) => line.startsWith(\"diff --git\"));\n\tconst headerLines = diffStart === -1 ? lines : lines.slice(0, diffStart);\n\tconst diffLines = diffStart === -1 ? [] : lines.slice(diffStart);\n\tconst summaryLines = headerLines.filter((line) => {\n\t\tconst trimmed = line.trim();\n\t\tif (!trimmed) return false;\n\t\tif (line.startsWith(\"Author:\") || line.startsWith(\"Date:\") || line.startsWith(\"Merge:\")) return false;\n\t\treturn true;\n\t});\n\tconst shortSummary = summaryLines\n\t\t.slice(0, 4)\n\t\t.map((line) => unicodeTruncate(line.replace(/^commit ([0-9a-f]{7})[0-9a-f]+/, \"commit $1\"), 160));\n\tconst { compacted, truncated } = compactDiff(diffLines.join(\"\\n\"));\n\tlet output = shortSummary.join(\"\\n\");\n\tif (compacted.trim()) output += `\\n\\n${compacted}`;\n\tif (truncated) output += \"\\n\\n[Diff truncated.]\";\n\treturn resultFromQuery(showRes, output.trim(), 0);\n}\n\nasync function handlePassthroughGit(\n\tcwd: string,\n\tglobalOptions: string[],\n\targs: string[],\n\toptions?: GitFilterOptions,\n): Promise<FilterResult> {\n\tconst res = await runGitQuery(cwd, globalOptions, args, options);\n\treturn resultFromQuery(res, rawText(res, true).trim(), res.status ?? 0);\n}\n\nasync function handleAdd(\n\tcwd: string,\n\tglobalOptions: string[],\n\targs: string[],\n\toptions?: GitFilterOptions,\n): Promise<FilterResult> {\n\tif (args.length === 0) return handlePassthroughGit(cwd, globalOptions, [\"add\"], options);\n\tconst addRes = await runGitQuery(cwd, globalOptions, [\"add\", ...args], options);\n\tconst rawOut = rawText(addRes);\n\tif (addRes.status !== 0) return { output: rawOut, exitCode: addRes.status ?? 1, rawOut, rawBytes: addRes.rawBytes };\n\tconst statRes = await runGitQuery(cwd, globalOptions, [\"diff\", \"--cached\", \"--stat\"], options);\n\tif (statRes.status === 0 && statRes.stdout.trim().length > 0) {\n\t\treturn { output: `Staged changes:\\n${statRes.stdout.trim()}`, exitCode: 0, rawOut, rawBytes: addRes.rawBytes };\n\t}\n\treturn { output: rawOut.trim() || \"Successfully staged.\", exitCode: 0, rawOut, rawBytes: addRes.rawBytes };\n}\n\nasync function handleCommit(\n\tcwd: string,\n\tglobalOptions: string[],\n\targs: string[],\n\toptions?: GitFilterOptions,\n): Promise<FilterResult> {\n\tconst hasMsg = args.some(\n\t\t(arg) => arg === \"-m\" || arg === \"-F\" || arg.startsWith(\"--message\") || arg.startsWith(\"--file\"),\n\t);\n\tif (!hasMsg) return { output: \"\", exitCode: -100, rawOut: \"\" };\n\tconst res = await runGitQuery(cwd, globalOptions, [\"commit\", ...args], options);\n\tconst rawOut = rawText(res, true);\n\tif (res.status !== 0) return { output: rawOut, exitCode: res.status ?? 1, rawOut, rawBytes: res.rawBytes };\n\tif (rawOut.includes(\"nothing to commit\") || rawOut.includes(\"working tree clean\")) {\n\t\treturn { output: \"nothing to commit, working tree clean\", exitCode: 0, rawOut, rawBytes: res.rawBytes };\n\t}\n\tconst firstLine = rawOut\n\t\t.split(\"\\n\")\n\t\t.find((line) => line.trim().length > 0)\n\t\t?.trim();\n\treturn { output: firstLine || \"Committed successfully.\", exitCode: 0, rawOut, rawBytes: res.rawBytes };\n}\n\nasync function handlePush(\n\tcwd: string,\n\tglobalOptions: string[],\n\targs: string[],\n\toptions?: GitFilterOptions,\n): Promise<FilterResult> {\n\tconst res = await runGitQuery(cwd, globalOptions, [\"push\", ...args], options);\n\tconst rawOut = rawText(res, true);\n\tconst outputLines = rawOut\n\t\t.split(\"\\n\")\n\t\t.map((line) => line.trimEnd())\n\t\t.filter((line) => {\n\t\t\tconst trimmed = line.trim();\n\t\t\tif (!trimmed) return false;\n\t\t\treturn ![\"Writing objects:\", \"Counting objects:\", \"Delta compression\", \"Compressing objects:\", \"Total \"].some(\n\t\t\t\t(prefix) => trimmed.startsWith(prefix),\n\t\t\t);\n\t\t});\n\tif (res.status !== 0)\n\t\treturn { output: outputLines.join(\"\\n\"), exitCode: res.status ?? 1, rawOut, rawBytes: res.rawBytes };\n\tif (outputLines.some((line) => line.includes(\"Everything up-to-date\"))) {\n\t\treturn { output: \"Everything up-to-date.\", exitCode: 0, rawOut, rawBytes: res.rawBytes };\n\t}\n\tconst remoteMessages = outputLines.filter((line) => line.trim().startsWith(\"remote:\"));\n\tconst pushDetail = outputLines.find((line) => line.includes(\"->\"));\n\tconst summary = pushDetail ? `Pushed: ${pushDetail.trim()}` : \"Push successful.\";\n\treturn { output: [...remoteMessages, summary].join(\"\\n\"), exitCode: 0, rawOut, rawBytes: res.rawBytes };\n}\n\nasync function handlePull(\n\tcwd: string,\n\tglobalOptions: string[],\n\targs: string[],\n\toptions?: GitFilterOptions,\n): Promise<FilterResult> {\n\tconst res = await runGitQuery(cwd, globalOptions, [\"pull\", ...args], options);\n\tconst rawOut = rawText(res, true);\n\tif (res.status !== 0) return { output: rawOut, exitCode: res.status ?? 1, rawOut, rawBytes: res.rawBytes };\n\tif (rawOut.includes(\"Already up to date.\"))\n\t\treturn { output: \"Already up to date.\", exitCode: 0, rawOut, rawBytes: res.rawBytes };\n\tconst lines = rawOut.split(\"\\n\");\n\tconst summary = lines.filter(\n\t\t(line) => line.includes(\"Fast-forward\") || line.includes(\"file changed\") || line.includes(\"files changed\"),\n\t);\n\treturn { output: summary.join(\"\\n\") || \"Pull successful.\", exitCode: 0, rawOut, rawBytes: res.rawBytes };\n}\n\nasync function handleFetch(\n\tcwd: string,\n\tglobalOptions: string[],\n\targs: string[],\n\toptions?: GitFilterOptions,\n): Promise<FilterResult> {\n\tconst res = await runGitQuery(cwd, globalOptions, [\"fetch\", ...args], options);\n\tconst rawOut = rawText(res, true);\n\tif (res.status !== 0) return { output: rawOut, exitCode: res.status ?? 1, rawOut, rawBytes: res.rawBytes };\n\tconst refs = rawOut\n\t\t.split(\"\\n\")\n\t\t.filter((line) => line.includes(\"[new branch]\") || line.includes(\"[new tag]\") || line.includes(\"->\"));\n\treturn {\n\t\toutput: refs.length\n\t\t\t? `Fetched:\\n${refs.map((line) => line.trim()).join(\"\\n\")}`\n\t\t\t: \"Fetch successful (no new refs).\",\n\t\texitCode: 0,\n\t\trawOut,\n\t\trawBytes: res.rawBytes,\n\t};\n}\n\nasync function handleBranch(\n\tcwd: string,\n\tglobalOptions: string[],\n\targs: string[],\n\toptions?: GitFilterOptions,\n): Promise<FilterResult> {\n\tif (args.includes(\"--show-current\")) {\n\t\tconst res = await runGitQuery(cwd, globalOptions, [\"branch\", \"--show-current\"], options);\n\t\treturn { output: res.stdout.trim(), exitCode: res.status ?? 0, rawOut: rawText(res), rawBytes: res.rawBytes };\n\t}\n\tconst isWrite = args.some(\n\t\t(arg) =>\n\t\t\targ === \"-d\" || arg === \"-D\" || arg === \"-m\" || arg === \"-M\" || (!arg.startsWith(\"-\") && args.length === 1),\n\t);\n\tif (isWrite) {\n\t\tconst res = await runGitQuery(cwd, globalOptions, [\"branch\", ...args], options);\n\t\tconst rawOut = rawText(res);\n\t\tif (res.status !== 0) return { output: rawOut, exitCode: res.status ?? 1, rawOut, rawBytes: res.rawBytes };\n\t\treturn { output: rawOut.trim() || \"Branch updated successfully.\", exitCode: 0, rawOut, rawBytes: res.rawBytes };\n\t}\n\tconst res = await runGitQuery(cwd, globalOptions, [\"branch\", \"--no-color\", ...args], options);\n\tconst rawOut = rawText(res);\n\tif (res.status !== 0) return { output: rawOut, exitCode: res.status ?? 1, rawOut, rawBytes: res.rawBytes };\n\tconst lines = res.stdout.split(\"\\n\").filter((line) => line.trim().length > 0);\n\tconst remoteBranches = lines.filter((line) => line.includes(\"remotes/\"));\n\tconst localBranches = lines.filter((line) => !line.includes(\"remotes/\"));\n\tconst remoteDisplay = remoteBranches.slice(0, 5);\n\tconst omitted = remoteBranches.length - remoteDisplay.length;\n\tif (omitted > 0) remoteDisplay.push(` remotes/... (${omitted} more remote branches)`);\n\treturn { output: [...localBranches, ...remoteDisplay].join(\"\\n\"), exitCode: 0, rawOut, rawBytes: res.rawBytes };\n}\n\nasync function handleStash(\n\tcwd: string,\n\tglobalOptions: string[],\n\targs: string[],\n\toptions?: GitFilterOptions,\n): Promise<FilterResult> {\n\tconst sub = args[0] || \"push\";\n\tconst res = await runGitQuery(cwd, globalOptions, [\"stash\", ...args], options);\n\tconst rawOut = rawText(res);\n\tif (res.status !== 0) return { output: rawOut, exitCode: res.status ?? 1, rawOut, rawBytes: res.rawBytes };\n\tif (sub === \"list\")\n\t\treturn { output: res.stdout.trim() || \"No stashes found.\", exitCode: 0, rawOut, rawBytes: res.rawBytes };\n\tif (sub === \"show\") {\n\t\tconst { compacted, truncated } = compactDiff(res.stdout);\n\t\treturn applyOverflowDisclosure(res, {\n\t\t\toutput: `${compacted.trim()}${truncated ? \"\\n\\n[Diff truncated.]\" : \"\"}`,\n\t\t\texitCode: 0,\n\t\t\trawOut,\n\t\t\trawBytes: res.rawBytes,\n\t\t});\n\t}\n\tif (res.stdout.includes(\"No local changes to save\"))\n\t\treturn { output: \"No local changes to save.\", exitCode: 0, rawOut, rawBytes: res.rawBytes };\n\tconst firstLine = res.stdout\n\t\t.split(\"\\n\")\n\t\t.find((line) => line.trim().length > 0)\n\t\t?.trim();\n\treturn { output: firstLine || \"Stash successful.\", exitCode: 0, rawOut, rawBytes: res.rawBytes };\n}\n\nasync function handleWorktree(\n\tcwd: string,\n\tglobalOptions: string[],\n\targs: string[],\n\toptions?: GitFilterOptions,\n): Promise<FilterResult> {\n\tconst sub = args[0] || \"list\";\n\tconst res = await runGitQuery(cwd, globalOptions, [\"worktree\", ...(sub === \"list\" ? [\"list\"] : args)], options);\n\tconst rawOut = rawText(res, true);\n\tif (res.status !== 0) return { output: rawOut, exitCode: res.status ?? 1, rawOut, rawBytes: res.rawBytes };\n\tif (sub !== \"list\") return { output: rawOut.trim(), exitCode: 0, rawOut, rawBytes: res.rawBytes };\n\tconst home = process.env.HOME || \"\";\n\tconst output = res.stdout\n\t\t.split(\"\\n\")\n\t\t.map((line) => (home && line.startsWith(home) ? `~${line.slice(home.length)}` : line))\n\t\t.join(\"\\n\")\n\t\t.trim();\n\treturn { output, exitCode: 0, rawOut, rawBytes: res.rawBytes };\n}\n\nexport async function executeFilteredGit(\n\tcwd: string,\n\tsubcommand: string,\n\tglobalOptions: string[],\n\tsubcommandArgs: string[],\n\toptions?: GitFilterOptions,\n): Promise<FilterResult> {\n\tswitch (subcommand) {\n\t\tcase \"status\":\n\t\t\treturn handleStatus(cwd, globalOptions, subcommandArgs, options);\n\t\tcase \"log\":\n\t\t\treturn handleLog(cwd, globalOptions, subcommandArgs, options);\n\t\tcase \"diff\":\n\t\t\treturn handleDiff(cwd, globalOptions, subcommandArgs, options);\n\t\tcase \"show\":\n\t\t\treturn handleShow(cwd, globalOptions, subcommandArgs, options);\n\t\tcase \"add\":\n\t\t\treturn handleAdd(cwd, globalOptions, subcommandArgs, options);\n\t\tcase \"commit\":\n\t\t\treturn handleCommit(cwd, globalOptions, subcommandArgs, options);\n\t\tcase \"push\":\n\t\t\treturn handlePush(cwd, globalOptions, subcommandArgs, options);\n\t\tcase \"pull\":\n\t\t\treturn handlePull(cwd, globalOptions, subcommandArgs, options);\n\t\tcase \"branch\":\n\t\t\treturn handleBranch(cwd, globalOptions, subcommandArgs, options);\n\t\tcase \"fetch\":\n\t\t\treturn handleFetch(cwd, globalOptions, subcommandArgs, options);\n\t\tcase \"stash\":\n\t\t\treturn handleStash(cwd, globalOptions, subcommandArgs, options);\n\t\tcase \"worktree\":\n\t\t\treturn handleWorktree(cwd, globalOptions, subcommandArgs, options);\n\t\tdefault:\n\t\t\treturn { output: \"\", exitCode: -100, rawOut: \"\" };\n\t}\n}\n\nexport function makeGitCommandForDisplay(globalOptions: string[], subcommand: string, args: string[]): string {\n\treturn gitCommand(globalOptions, [subcommand, ...args]);\n}\n"]}
1
+ {"version":3,"file":"git-filter.d.ts","sourceRoot":"","sources":["../../../src/core/tools/git-filter.ts"],"names":[],"mapp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,CACjC,OAAO,EAAE,MAAM,EACf,SAAS,CAAC,EAAE,MAAM,CAAC,UAAU,GAC3B;IACF,QAAQ,EAAE,OAAO,CAAC;IAClB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,aAAa,CAAC,EAAE,MAAM,EAAE,CAAC;IACzB,cAAc,CAAC,EAAE,MAAM,EAAE,CAAC;IAC1B,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CAClC,CA4DA;AAED,wBAAgB,cAAc,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,CAYvD;AAoHD,wBAAgB,WAAW,CAAC,UAAU,EAAE,MAAM,EAAE,QAAQ,SAAM,GAAG;IAAE,SAAS,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,OAAO,CAAA;CAAE,CAgEzG;AA4RD,wBAAsB,kBAAkB,CACvC,GAAG,EAAE,MAAM,EACX,UAAU,EAAE,MAAM,EAClB,aAAa,EAAE,MAAM,EAAE,EACvB,cAAc,EAAE,MAAM,EAAE,EACxB,OAAO,CAAC,EAAE,gBAAgB,GACxB,OAAO,CAAC,YAAY,CAAC,CA6BvB;AAED,wBAAgB,wBAAwB,CAAC,aAAa,EAAE,MAAM,EAAE,EAAE,UAAU,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,GAAG,MAAM,CAE5G","sourcesContent":["import { spawn } from \"node:child_process\";\nimport { randomBytes } from \"node:crypto\";\nimport { existsSync, type WriteStream } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\nimport { getAgentDir } from \"../../config.ts\";\nimport { waitForChildProcessWithTermination } from \"../../utils/child-process.ts\";\nimport { createSafeWriteStream } from \"../../utils/safe-write-stream.ts\";\nimport { trackDetachedChildPid, untrackDetachedChildPid } from \"../../utils/shell.ts\";\nimport { getProcessWorkRun } from \"../../utils/work-directory.ts\";\n\n/**\n * Retention budget for git output held in memory while filtering. Output beyond\n * the budget is spilled to a temp file so a giant `git log -p`/`git diff` cannot\n * exhaust the V8 heap. Override with PI_GIT_FILTER_MAX_RETAINED_BYTES.\n */\nconst DEFAULT_MAX_RETAINED_GIT_OUTPUT_BYTES = 48 * 1024 * 1024;\nconst MAX_RETAINED_GIT_STDERR_BYTES = 8 * 1024 * 1024;\nconst DEFAULT_GIT_FILTER_TIMEOUT_SECONDS = 10 * 60;\nconst GIT_FILTER_KILL_GRACE_MS = 2_000;\n\nfunction maxRetainedGitOutputBytes(): number {\n\tconst raw = process.env.PI_GIT_FILTER_MAX_RETAINED_BYTES;\n\tif (raw !== undefined) {\n\t\tconst parsed = Number.parseInt(raw, 10);\n\t\tif (Number.isFinite(parsed) && parsed > 0) return parsed;\n\t}\n\treturn DEFAULT_MAX_RETAINED_GIT_OUTPUT_BYTES;\n}\n\nconst SUPPORTED_SUBCOMMANDS = new Set([\n\t\"status\",\n\t\"log\",\n\t\"diff\",\n\t\"show\",\n\t\"add\",\n\t\"commit\",\n\t\"push\",\n\t\"pull\",\n\t\"branch\",\n\t\"fetch\",\n\t\"stash\",\n\t\"worktree\",\n]);\n\nexport interface FilterResult {\n\toutput: string;\n\texitCode: number;\n\trawOut: string;\n\trawBytes?: Buffer;\n\t/** Set when git output exceeded the in-memory retention budget; the file holds the full output. */\n\tfullOutputPath?: string;\n}\n\ninterface GitQueryResult {\n\tstdout: string;\n\tstderr: string;\n\tstatus: number | null;\n\t/** Full raw output (stderr then stdout). Absent when output overflowed to disk. */\n\trawBytes?: Buffer;\n\t/** Set when stdout exceeded the retention budget and was spilled to a temp file. */\n\toverflow?: { fullOutputPath: string; totalBytes: number };\n}\n\ninterface GitFilterOptions {\n\tsignal?: AbortSignal;\n\ttimeout?: number;\n}\n\nexport function unicodeTruncate(str: string, maxLength: number): string {\n\tconst chars = Array.from(str);\n\tif (chars.length <= maxLength) return str;\n\treturn `${chars.slice(0, maxLength).join(\"\")}...`;\n}\n\nexport function tokenizeCommand(command: string): string[] | null {\n\tconst args: string[] = [];\n\tlet current = \"\";\n\tlet inDoubleQuotes = false;\n\tlet inSingleQuotes = false;\n\tlet escapeNext = false;\n\n\tfor (let i = 0; i < command.length; i++) {\n\t\tconst char = command[i];\n\t\tif (escapeNext) {\n\t\t\tcurrent += char;\n\t\t\tescapeNext = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (char === \"\\\\\" && !inSingleQuotes) {\n\t\t\tescapeNext = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (char === '\"' && !inSingleQuotes) {\n\t\t\tinDoubleQuotes = !inDoubleQuotes;\n\t\t} else if (char === \"'\" && !inDoubleQuotes) {\n\t\t\tinSingleQuotes = !inSingleQuotes;\n\t\t} else if (/\\s/.test(char) && !inDoubleQuotes && !inSingleQuotes) {\n\t\t\tif (current) {\n\t\t\t\targs.push(current);\n\t\t\t\tcurrent = \"\";\n\t\t\t}\n\t\t} else {\n\t\t\tcurrent += char;\n\t\t}\n\t}\n\tif (inDoubleQuotes || inSingleQuotes || escapeNext) return null;\n\tif (current) args.push(current);\n\treturn args;\n}\n\nexport interface ParsedCommand {\n\tenvVars: Record<string, string>;\n\tcoreCommandTokens: string[];\n}\n\nexport function parseCommandPrefixes(command: string): ParsedCommand | null {\n\tconst tokens = tokenizeCommand(command);\n\tif (!tokens || tokens.length === 0) return null;\n\n\tconst envVars: Record<string, string> = {};\n\tlet i = 0;\n\tconst envPattern = /^([a-zA-Z_][a-zA-Z0-9_]*)=(.*)$/;\n\n\twhile (i < tokens.length) {\n\t\tconst token = tokens[i];\n\t\tconst match = token.match(envPattern);\n\t\tif (!match) break;\n\t\tlet value = match[2];\n\t\tif ((value.startsWith('\"') && value.endsWith('\"')) || (value.startsWith(\"'\") && value.endsWith(\"'\"))) {\n\t\t\tvalue = value.slice(1, -1);\n\t\t}\n\t\tenvVars[match[1]] = value;\n\t\ti++;\n\t}\n\n\treturn { envVars, coreCommandTokens: tokens.slice(i) };\n}\n\nexport function isComplexShellCommand(command: string): boolean {\n\treturn /[|><&;\\n\\r$`()*?[\\]#]/.test(command);\n}\n\nfunction quoteForShell(arg: string): string {\n\tif (/^[A-Za-z0-9_./:=+-]+$/.test(arg)) return arg;\n\treturn `'${arg.replace(/'/g, `'\"'\"'`)}'`;\n}\n\nfunction gitCommand(globalOptions: string[], args: string[]): string {\n\treturn [\"git\", ...globalOptions, ...args].map(quoteForShell).join(\" \");\n}\n\nfunction rawText(res: GitQueryResult, combine = false): string {\n\tif (combine) return `${res.stderr}${res.stderr && res.stdout ? \"\\n\" : \"\"}${res.stdout}`;\n\treturn res.stderr || res.stdout;\n}\n\nfunction applyOverflowDisclosure(res: GitQueryResult, result: FilterResult): FilterResult {\n\tif (!res.overflow) return result;\n\tconst totalMb = (res.overflow.totalBytes / (1024 * 1024)).toFixed(1);\n\treturn {\n\t\t...result,\n\t\toutput: `${result.output}\\n\\n[git output was ${totalMb}MB; filtered view computed from the retained head. Full output: ${res.overflow.fullOutputPath}]`,\n\t\tfullOutputPath: res.overflow.fullOutputPath,\n\t};\n}\n\nfunction resultFromQuery(res: GitQueryResult, output: string, exitCode = res.status ?? 0): FilterResult {\n\treturn applyOverflowDisclosure(res, { output, exitCode, rawOut: rawText(res), rawBytes: res.rawBytes });\n}\n\nexport async function runGitQuery(\n\tcwd: string,\n\tglobalOptions: string[],\n\targs: string[],\n\toptions?: GitFilterOptions,\n): Promise<GitQueryResult> {\n\tif (options?.signal?.aborted) throw new Error(\"aborted\");\n\n\tconst child = spawn(\"git\", [...globalOptions, ...args], {\n\t\tcwd,\n\t\tdetached: process.platform !== \"win32\",\n\t\tenv: { ...process.env, LC_ALL: \"C\" },\n\t\tstdio: [\"ignore\", \"pipe\", \"pipe\"],\n\t\twindowsHide: true,\n\t});\n\tif (child.pid) trackDetachedChildPid(child.pid);\n\n\tconst stdoutChunks: Buffer[] = [];\n\tconst stderrChunks: Buffer[] = [];\n\tconst maxRetainedBytes = maxRetainedGitOutputBytes();\n\tlet retainedStdoutBytes = 0;\n\tlet totalStdoutBytes = 0;\n\tlet retainedStderrBytes = 0;\n\tlet overflowPath: string | undefined;\n\tlet overflowStream: WriteStream | undefined;\n\tlet overflowStreamEnded = false;\n\tlet overflowWriteError: Error | undefined;\n\tconst timeoutSeconds =\n\t\toptions?.timeout && options.timeout > 0 ? options.timeout : DEFAULT_GIT_FILTER_TIMEOUT_SECONDS;\n\n\ttry {\n\t\tchild.stdout?.on(\"data\", (chunk: Buffer) => {\n\t\t\ttotalStdoutBytes += chunk.length;\n\t\t\tif (overflowStream) {\n\t\t\t\toverflowStream.write(chunk);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tstdoutChunks.push(chunk);\n\t\t\tretainedStdoutBytes += chunk.length;\n\t\t\tif (retainedStdoutBytes > maxRetainedBytes) {\n\t\t\t\toverflowPath = join(\n\t\t\t\t\tgetProcessWorkRun(getAgentDir(), \"outputs\", \"git\").path,\n\t\t\t\t\t`pi-git-${randomBytes(8).toString(\"hex\")}.log`,\n\t\t\t\t);\n\t\t\t\toverflowStream = createSafeWriteStream(overflowPath, (error) => {\n\t\t\t\t\toverflowWriteError = error;\n\t\t\t\t});\n\t\t\t\tfor (const retained of stdoutChunks) overflowStream.write(retained);\n\t\t\t}\n\t\t});\n\t\tchild.stderr?.on(\"data\", (chunk: Buffer) => {\n\t\t\tstderrChunks.push(chunk);\n\t\t\tretainedStderrBytes += chunk.length;\n\t\t\twhile (retainedStderrBytes > MAX_RETAINED_GIT_STDERR_BYTES && stderrChunks.length > 1) {\n\t\t\t\tretainedStderrBytes -= stderrChunks.shift()?.length ?? 0;\n\t\t\t}\n\t\t});\n\t\tconst terminal = await waitForChildProcessWithTermination(child, {\n\t\t\tsignal: options?.signal,\n\t\t\ttimeoutMs: timeoutSeconds * 1000,\n\t\t\tkillGraceMs: GIT_FILTER_KILL_GRACE_MS,\n\t\t});\n\t\tif (terminal.reason === \"aborted\") throw new Error(\"aborted\");\n\t\tif (terminal.reason === \"timeout\") throw new Error(`timeout:${timeoutSeconds}`);\n\t\tconst status = terminal.code;\n\t\tconst stdoutBuffer = Buffer.concat(stdoutChunks);\n\t\tconst stderrBuffer = Buffer.concat(stderrChunks);\n\t\tif (overflowStream !== undefined && overflowPath !== undefined) {\n\t\t\tif (stderrBuffer.length > 0 && !overflowStream.writableEnded) {\n\t\t\t\toverflowStream.write(\"\\n--- stderr ---\\n\");\n\t\t\t\toverflowStream.write(stderrBuffer);\n\t\t\t}\n\t\t\tconst stream = overflowStream;\n\t\t\tawait new Promise<void>((resolveEnd) => {\n\t\t\t\tstream.end(() => resolveEnd());\n\t\t\t});\n\t\t\toverflowStreamEnded = true;\n\t\t\tif (overflowWriteError !== undefined) {\n\t\t\t\t// Spill failed (e.g. disk full): disclose the loss instead of pointing\n\t\t\t\t// consumers at a broken artifact, and keep the retained head usable.\n\t\t\t\treturn {\n\t\t\t\t\tstdout: stdoutBuffer.toString(\"utf-8\"),\n\t\t\t\t\tstderr: `${stderrBuffer.toString(\"utf-8\")}\\n[git output overflow spill failed: ${overflowWriteError.message}; output beyond the retained head was lost]`,\n\t\t\t\t\tstatus,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tstdout: stdoutBuffer.toString(\"utf-8\"),\n\t\t\t\tstderr: stderrBuffer.toString(\"utf-8\"),\n\t\t\t\tstatus,\n\t\t\t\toverflow: { fullOutputPath: overflowPath, totalBytes: totalStdoutBytes },\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\tstdout: stdoutBuffer.toString(\"utf-8\"),\n\t\t\tstderr: stderrBuffer.toString(\"utf-8\"),\n\t\t\tstatus,\n\t\t\trawBytes: Buffer.concat([stderrBuffer, stdoutBuffer]),\n\t\t};\n\t} finally {\n\t\tif (child.pid) untrackDetachedChildPid(child.pid);\n\t\tif (overflowStream !== undefined && !overflowStreamEnded) overflowStream.end();\n\t}\n}\n\nexport function classifyGitCommand(\n\tcommand: string,\n\tparentEnv?: NodeJS.ProcessEnv,\n): {\n\teligible: boolean;\n\tsubcommand?: string;\n\tglobalOptions?: string[];\n\tsubcommandArgs?: string[];\n\tlocalEnv?: Record<string, string>;\n} {\n\tif (isComplexShellCommand(command)) return { eligible: false };\n\n\tconst parsed = parseCommandPrefixes(command);\n\tif (!parsed || parsed.coreCommandTokens.length === 0) return { eligible: false };\n\n\tconst { envVars, coreCommandTokens } = parsed;\n\tconst toolFilterDisabled =\n\t\tprocess.env.PI_TOOL_FILTER_DISABLED === \"1\" ||\n\t\tparentEnv?.PI_TOOL_FILTER_DISABLED === \"1\" ||\n\t\tenvVars.PI_TOOL_FILTER_DISABLED === \"1\";\n\tconst gitFilterDisabled =\n\t\tprocess.env.PI_GIT_FILTER_DISABLED === \"1\" ||\n\t\tparentEnv?.PI_GIT_FILTER_DISABLED === \"1\" ||\n\t\tenvVars.PI_GIT_FILTER_DISABLED === \"1\";\n\tif (toolFilterDisabled || gitFilterDisabled) return { eligible: false };\n\n\tconst envKeys = Object.keys(envVars).filter(\n\t\t(key) => key !== \"PI_TOOL_FILTER_DISABLED\" && key !== \"PI_GIT_FILTER_DISABLED\",\n\t);\n\tif (envKeys.length > 0) return { eligible: false };\n\n\tconst cmdName = coreCommandTokens[0];\n\tif (cmdName !== \"git\" && cmdName !== \"yadm\") return { eligible: false };\n\n\tlet idx = 1;\n\tconst globalOptions: string[] = [];\n\twhile (idx < coreCommandTokens.length) {\n\t\tconst token = coreCommandTokens[idx];\n\t\tif (token === \"-C\" || token === \"-c\" || token === \"--git-dir\" || token === \"--work-tree\") {\n\t\t\tif (idx + 1 >= coreCommandTokens.length) return { eligible: false };\n\t\t\tglobalOptions.push(token, coreCommandTokens[idx + 1]);\n\t\t\tidx += 2;\n\t\t} else if (token.startsWith(\"--git-dir=\") || token.startsWith(\"--work-tree=\")) {\n\t\t\tglobalOptions.push(token);\n\t\t\tidx++;\n\t\t} else if (\n\t\t\ttoken === \"--no-pager\" ||\n\t\t\ttoken === \"--no-optional-locks\" ||\n\t\t\ttoken === \"--bare\" ||\n\t\t\ttoken === \"--literal-pathspecs\"\n\t\t) {\n\t\t\tglobalOptions.push(token);\n\t\t\tidx++;\n\t\t} else {\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (idx === coreCommandTokens.length) return { eligible: false };\n\tconst subcommand = coreCommandTokens[idx];\n\tif (!SUPPORTED_SUBCOMMANDS.has(subcommand)) return { eligible: false };\n\n\treturn {\n\t\teligible: true,\n\t\tsubcommand,\n\t\tglobalOptions,\n\t\tsubcommandArgs: coreCommandTokens.slice(idx + 1),\n\t\tlocalEnv: envVars,\n\t};\n}\n\nexport function detectGitState(gitDir: string): string[] {\n\tconst states: string[] = [];\n\tif (!gitDir) return states;\n\tif (existsSync(join(gitDir, \"rebase-merge\")) || existsSync(join(gitDir, \"rebase-apply\"))) {\n\t\tstates.push(\"rebase in progress\");\n\t}\n\tif (existsSync(join(gitDir, \"MERGE_HEAD\"))) states.push(\"merge in progress\");\n\tif (existsSync(join(gitDir, \"CHERRY_PICK_HEAD\"))) states.push(\"cherry-pick in progress\");\n\tif (existsSync(join(gitDir, \"REVERT_HEAD\"))) states.push(\"revert in progress\");\n\tif (existsSync(join(gitDir, \"BISECT_LOG\"))) states.push(\"bisect in progress\");\n\tif (existsSync(join(gitDir, \"applying\"))) states.push(\"am in progress\");\n\treturn states;\n}\n\nasync function handleStatus(\n\tcwd: string,\n\tglobalOptions: string[],\n\targs: string[],\n\toptions?: GitFilterOptions,\n): Promise<FilterResult> {\n\tconst isSimple =\n\t\targs.length === 0 || args.every((arg) => arg === \"-s\" || arg === \"--short\" || arg === \"-b\" || arg === \"--branch\");\n\n\tif (!isSimple) {\n\t\tconst res = await runGitQuery(cwd, globalOptions, [\"status\", ...args], options);\n\t\tconst rawOut = rawText(res);\n\t\tif (res.status !== 0) return { output: rawOut, exitCode: res.status ?? 1, rawOut, rawBytes: res.rawBytes };\n\t\tconst cleanedLines = res.stdout\n\t\t\t.split(\"\\n\")\n\t\t\t.map((line) => line.trimEnd())\n\t\t\t.filter((line) => line.length > 0 && !line.trim().startsWith(\"(use \"));\n\t\tconst output = cleanedLines.join(\"\\n\");\n\t\treturn resultFromQuery(res, output || \"success\", 0);\n\t}\n\n\tconst res = await runGitQuery(cwd, globalOptions, [\"status\", \"--porcelain=v1\", \"-b\"], options);\n\tlet rawOut = rawText(res);\n\tif (res.status !== 0) {\n\t\tif (rawOut.includes(\"not a git repository\")) rawOut = \"fatal: not a git repository\";\n\t\treturn { output: rawOut.trim(), exitCode: res.status ?? 1, rawOut, rawBytes: res.rawBytes };\n\t}\n\n\tconst lines = res.stdout.split(\"\\n\").filter((line) => line.trim().length > 0);\n\tlet branchLine = \"\";\n\tconst fileLines: string[] = [];\n\tfor (const line of lines) {\n\t\tif (line.startsWith(\"##\")) {\n\t\t\tbranchLine = line;\n\t\t} else {\n\t\t\tfileLines.push(line);\n\t\t}\n\t}\n\n\tlet statePrefix = \"\";\n\tconst gitDirRes = await runGitQuery(cwd, globalOptions, [\"rev-parse\", \"--git-dir\"], options);\n\tif (gitDirRes.status === 0) {\n\t\tconst gitDir = resolve(cwd, gitDirRes.stdout.trim());\n\t\tconst states = detectGitState(gitDir);\n\t\tif (states.length > 0) statePrefix = `[${states.join(\", \")}]\\n`;\n\t}\n\n\tif (branchLine.includes(\"HEAD (no branch)\")) {\n\t\tconst headHashRes = await runGitQuery(cwd, globalOptions, [\"rev-parse\", \"--short\", \"HEAD\"], options);\n\t\tconst hash = headHashRes.status === 0 ? headHashRes.stdout.trim() : \"unknown\";\n\t\tbranchLine = `## HEAD (detached at ${hash})`;\n\t}\n\n\tif (fileLines.length === 0) {\n\t\treturn resultFromQuery(res, `${statePrefix}${branchLine}\\nnothing to commit, working tree clean`, 0);\n\t}\n\treturn resultFromQuery(res, `${statePrefix}${branchLine}\\n${fileLines.join(\"\\n\")}`, 0);\n}\n\nasync function handleLog(\n\tcwd: string,\n\tglobalOptions: string[],\n\targs: string[],\n\toptions?: GitFilterOptions,\n): Promise<FilterResult> {\n\tconst hasLimit = args.some(\n\t\t(arg) => /^-n\\d+$/.test(arg) || arg === \"-n\" || /^-?\\d+$/.test(arg) || arg.startsWith(\"--max-count\"),\n\t);\n\tconst hasPretty = args.some(\n\t\t(arg) => arg.startsWith(\"--pretty\") || arg.startsWith(\"--format\") || arg === \"--oneline\",\n\t);\n\n\tconst logArgs = hasLimit ? [\"log\", ...args] : [\"log\", \"-n\", \"10\", \"--no-merges\", ...args];\n\tconst res = await runGitQuery(cwd, globalOptions, logArgs, options);\n\tif (hasPretty) return resultFromQuery(res, rawText(res), res.status ?? 0);\n\n\tconst rawOut = rawText(res);\n\tif (res.status !== 0) return { output: rawOut, exitCode: res.status ?? 1, rawOut, rawBytes: res.rawBytes };\n\n\tconst commits = res.stdout.split(/(?=^commit [0-9a-f]{7,40})/m).filter((commit) => commit.trim().length > 0);\n\tconst compactedCommits: string[] = [];\n\tconst trailerPrefixes = [\n\t\t\"Signed-off-by:\",\n\t\t\"Co-authored-by:\",\n\t\t\"Reported-by:\",\n\t\t\"Reviewed-by:\",\n\t\t\"Tested-by:\",\n\t\t\"Suggested-by:\",\n\t\t\"CC:\",\n\t];\n\n\tfor (const commit of commits) {\n\t\tconst lines = commit.split(\"\\n\");\n\t\tconst commitLine = lines[0];\n\t\tif (!commitLine) continue;\n\t\tconst shortCommitLine = commitLine.replace(/^commit ([0-9a-f]{7})[0-9a-f]+/, \"commit $1\");\n\t\tconst bodyLines: string[] = [];\n\t\tfor (let i = 1; i < lines.length; i++) {\n\t\t\tconst line = lines[i];\n\t\t\tconst trimmed = line.trim();\n\t\t\tif (!trimmed) continue;\n\t\t\tif (line.startsWith(\"Author:\") || line.startsWith(\"Date:\") || line.startsWith(\"Merge:\")) continue;\n\t\t\tif (trailerPrefixes.some((prefix) => trimmed.startsWith(prefix))) continue;\n\t\t\tbodyLines.push(line);\n\t\t}\n\t\tconst displayBody = bodyLines.slice(0, 3).map((line) => unicodeTruncate(line, 160));\n\t\tconst omitted = bodyLines.length - displayBody.length;\n\t\tif (omitted > 0) displayBody.push(` ... (${omitted} lines omitted)`);\n\t\tcompactedCommits.push(`${shortCommitLine}\\n${displayBody.join(\"\\n\")}`);\n\t}\n\n\treturn resultFromQuery(res, compactedCommits.join(\"\\n\\n\"), 0);\n}\n\nexport function compactDiff(diffOutput: string, maxLines = 150): { compacted: string; truncated: boolean } {\n\tconst lines = diffOutput.split(\"\\n\");\n\tconst output: string[] = [];\n\tlet linesCount = 0;\n\tlet truncated = false;\n\tlet contextBuffer: string[] = [];\n\tlet trailingContextRemaining = 0;\n\n\tfor (const line of lines) {\n\t\tif (linesCount >= maxLines) {\n\t\t\ttruncated = true;\n\t\t\tbreak;\n\t\t}\n\t\tif (\n\t\t\tline.startsWith(\"diff --git\") ||\n\t\t\tline.startsWith(\"--- \") ||\n\t\t\tline.startsWith(\"+++ \") ||\n\t\t\tline.startsWith(\"index \")\n\t\t) {\n\t\t\tcontextBuffer = [];\n\t\t\ttrailingContextRemaining = 0;\n\t\t\toutput.push(line);\n\t\t\tlinesCount++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (line.startsWith(\"@@ \")) {\n\t\t\tcontextBuffer = [];\n\t\t\ttrailingContextRemaining = 0;\n\t\t\toutput.push(line);\n\t\t\tlinesCount++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (line.startsWith(\"+\") || line.startsWith(\"-\")) {\n\t\t\tfor (const ctx of contextBuffer) {\n\t\t\t\tif (linesCount >= maxLines) {\n\t\t\t\t\ttruncated = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\toutput.push(ctx);\n\t\t\t\tlinesCount++;\n\t\t\t}\n\t\t\tcontextBuffer = [];\n\t\t\tif (truncated) break;\n\t\t\toutput.push(line);\n\t\t\tlinesCount++;\n\t\t\ttrailingContextRemaining = 3;\n\t\t\tcontinue;\n\t\t}\n\t\tif (line.startsWith(\" \")) {\n\t\t\tif (trailingContextRemaining > 0) {\n\t\t\t\toutput.push(line);\n\t\t\t\tlinesCount++;\n\t\t\t\ttrailingContextRemaining--;\n\t\t\t} else {\n\t\t\t\tcontextBuffer.push(line);\n\t\t\t\tif (contextBuffer.length > 3) contextBuffer.shift();\n\t\t\t}\n\t\t} else {\n\t\t\toutput.push(line);\n\t\t\tlinesCount++;\n\t\t}\n\t}\n\n\treturn { compacted: output.join(\"\\n\"), truncated };\n}\n\nasync function handleDiff(\n\tcwd: string,\n\tglobalOptions: string[],\n\targs: string[],\n\toptions?: GitFilterOptions,\n): Promise<FilterResult> {\n\tconst cleanArgs = [...args];\n\tconst noCompactIndex = cleanArgs.indexOf(\"--no-compact\");\n\tconst optOut = noCompactIndex !== -1;\n\tif (optOut) cleanArgs.splice(noCompactIndex, 1);\n\n\tconst statFlags = [\"--stat\", \"--numstat\", \"--shortstat\", \"--summary\", \"--name-only\", \"--name-status\", \"--check\"];\n\tconst isStatOnly = cleanArgs.some((arg) => statFlags.includes(arg));\n\tif (optOut || isStatOnly) {\n\t\tconst res = await runGitQuery(cwd, globalOptions, [\"diff\", ...cleanArgs], options);\n\t\treturn resultFromQuery(res, rawText(res), res.status ?? 0);\n\t}\n\n\tconst hasDoubleDash = cleanArgs.includes(\"--\");\n\tif (!hasDoubleDash) {\n\t\tconst pathIdx = cleanArgs.findIndex((arg) => {\n\t\t\tif (arg.startsWith(\"-\")) return false;\n\t\t\tif (!(arg.includes(\"/\") || arg.includes(\".\") || existsSync(join(cwd, arg)))) return false;\n\t\t\treturn existsSync(resolve(cwd, arg));\n\t\t});\n\t\tif (pathIdx !== -1) cleanArgs.splice(pathIdx, 0, \"--\");\n\t}\n\n\tconst statRes = await runGitQuery(cwd, globalOptions, [\"diff\", \"--stat\", ...cleanArgs], options);\n\tif (statRes.status !== 0) return resultFromQuery(statRes, rawText(statRes), statRes.status ?? 1);\n\tconst diffRes = await runGitQuery(cwd, globalOptions, [\"diff\", ...cleanArgs], options);\n\tif (diffRes.status !== 0) return resultFromQuery(diffRes, rawText(diffRes), diffRes.status ?? 1);\n\n\tconst { compacted, truncated } = compactDiff(diffRes.stdout);\n\tlet output = `${statRes.stdout.trimEnd()}\\n\\n${compacted}`.trim();\n\tif (truncated) output += \"\\n\\n[Diff truncated. Re-run with: git diff --no-compact]\";\n\treturn applyOverflowDisclosure(diffRes, { output, exitCode: 0, rawOut: diffRes.stdout, rawBytes: diffRes.rawBytes });\n}\n\nasync function handleShow(\n\tcwd: string,\n\tglobalOptions: string[],\n\targs: string[],\n\toptions?: GitFilterOptions,\n): Promise<FilterResult> {\n\tconst statFlags = [\"--stat\", \"--numstat\", \"--shortstat\", \"--summary\", \"--name-only\", \"--name-status\", \"--check\"];\n\tconst hasStatOnly = args.some((arg) => statFlags.includes(arg));\n\tconst hasPretty = args.some(\n\t\t(arg) => arg.startsWith(\"--pretty\") || arg.startsWith(\"--format\") || arg === \"--oneline\",\n\t);\n\tconst hasBlob = args.some((arg) => !arg.startsWith(\"-\") && arg.includes(\":\"));\n\tif (hasStatOnly || hasPretty || hasBlob) {\n\t\tconst res = await runGitQuery(cwd, globalOptions, [\"show\", ...args], options);\n\t\treturn resultFromQuery(res, rawText(res), res.status ?? 0);\n\t}\n\n\tconst showRes = await runGitQuery(cwd, globalOptions, [\"show\", ...args], options);\n\tconst rawOut = rawText(showRes);\n\tif (showRes.status !== 0)\n\t\treturn { output: rawOut, exitCode: showRes.status ?? 1, rawOut, rawBytes: showRes.rawBytes };\n\n\tconst lines = showRes.stdout.split(\"\\n\");\n\tconst diffStart = lines.findIndex((line) => line.startsWith(\"diff --git\"));\n\tconst headerLines = diffStart === -1 ? lines : lines.slice(0, diffStart);\n\tconst diffLines = diffStart === -1 ? [] : lines.slice(diffStart);\n\tconst summaryLines = headerLines.filter((line) => {\n\t\tconst trimmed = line.trim();\n\t\tif (!trimmed) return false;\n\t\tif (line.startsWith(\"Author:\") || line.startsWith(\"Date:\") || line.startsWith(\"Merge:\")) return false;\n\t\treturn true;\n\t});\n\tconst shortSummary = summaryLines\n\t\t.slice(0, 4)\n\t\t.map((line) => unicodeTruncate(line.replace(/^commit ([0-9a-f]{7})[0-9a-f]+/, \"commit $1\"), 160));\n\tconst { compacted, truncated } = compactDiff(diffLines.join(\"\\n\"));\n\tlet output = shortSummary.join(\"\\n\");\n\tif (compacted.trim()) output += `\\n\\n${compacted}`;\n\tif (truncated) output += \"\\n\\n[Diff truncated.]\";\n\treturn resultFromQuery(showRes, output.trim(), 0);\n}\n\nasync function handlePassthroughGit(\n\tcwd: string,\n\tglobalOptions: string[],\n\targs: string[],\n\toptions?: GitFilterOptions,\n): Promise<FilterResult> {\n\tconst res = await runGitQuery(cwd, globalOptions, args, options);\n\treturn resultFromQuery(res, rawText(res, true).trim(), res.status ?? 0);\n}\n\nasync function handleAdd(\n\tcwd: string,\n\tglobalOptions: string[],\n\targs: string[],\n\toptions?: GitFilterOptions,\n): Promise<FilterResult> {\n\tif (args.length === 0) return handlePassthroughGit(cwd, globalOptions, [\"add\"], options);\n\tconst addRes = await runGitQuery(cwd, globalOptions, [\"add\", ...args], options);\n\tconst rawOut = rawText(addRes);\n\tif (addRes.status !== 0) return { output: rawOut, exitCode: addRes.status ?? 1, rawOut, rawBytes: addRes.rawBytes };\n\tconst statRes = await runGitQuery(cwd, globalOptions, [\"diff\", \"--cached\", \"--stat\"], options);\n\tif (statRes.status === 0 && statRes.stdout.trim().length > 0) {\n\t\treturn { output: `Staged changes:\\n${statRes.stdout.trim()}`, exitCode: 0, rawOut, rawBytes: addRes.rawBytes };\n\t}\n\treturn { output: rawOut.trim() || \"Successfully staged.\", exitCode: 0, rawOut, rawBytes: addRes.rawBytes };\n}\n\nasync function handleCommit(\n\tcwd: string,\n\tglobalOptions: string[],\n\targs: string[],\n\toptions?: GitFilterOptions,\n): Promise<FilterResult> {\n\tconst hasMsg = args.some(\n\t\t(arg) => arg === \"-m\" || arg === \"-F\" || arg.startsWith(\"--message\") || arg.startsWith(\"--file\"),\n\t);\n\tif (!hasMsg) return { output: \"\", exitCode: -100, rawOut: \"\" };\n\tconst res = await runGitQuery(cwd, globalOptions, [\"commit\", ...args], options);\n\tconst rawOut = rawText(res, true);\n\tif (res.status !== 0) return { output: rawOut, exitCode: res.status ?? 1, rawOut, rawBytes: res.rawBytes };\n\tif (rawOut.includes(\"nothing to commit\") || rawOut.includes(\"working tree clean\")) {\n\t\treturn { output: \"nothing to commit, working tree clean\", exitCode: 0, rawOut, rawBytes: res.rawBytes };\n\t}\n\tconst firstLine = rawOut\n\t\t.split(\"\\n\")\n\t\t.find((line) => line.trim().length > 0)\n\t\t?.trim();\n\treturn { output: firstLine || \"Committed successfully.\", exitCode: 0, rawOut, rawBytes: res.rawBytes };\n}\n\nasync function handlePush(\n\tcwd: string,\n\tglobalOptions: string[],\n\targs: string[],\n\toptions?: GitFilterOptions,\n): Promise<FilterResult> {\n\tconst res = await runGitQuery(cwd, globalOptions, [\"push\", ...args], options);\n\tconst rawOut = rawText(res, true);\n\tconst outputLines = rawOut\n\t\t.split(\"\\n\")\n\t\t.map((line) => line.trimEnd())\n\t\t.filter((line) => {\n\t\t\tconst trimmed = line.trim();\n\t\t\tif (!trimmed) return false;\n\t\t\treturn ![\"Writing objects:\", \"Counting objects:\", \"Delta compression\", \"Compressing objects:\", \"Total \"].some(\n\t\t\t\t(prefix) => trimmed.startsWith(prefix),\n\t\t\t);\n\t\t});\n\tif (res.status !== 0)\n\t\treturn { output: outputLines.join(\"\\n\"), exitCode: res.status ?? 1, rawOut, rawBytes: res.rawBytes };\n\tif (outputLines.some((line) => line.includes(\"Everything up-to-date\"))) {\n\t\treturn { output: \"Everything up-to-date.\", exitCode: 0, rawOut, rawBytes: res.rawBytes };\n\t}\n\tconst remoteMessages = outputLines.filter((line) => line.trim().startsWith(\"remote:\"));\n\tconst pushDetail = outputLines.find((line) => line.includes(\"->\"));\n\tconst summary = pushDetail ? `Pushed: ${pushDetail.trim()}` : \"Push successful.\";\n\treturn { output: [...remoteMessages, summary].join(\"\\n\"), exitCode: 0, rawOut, rawBytes: res.rawBytes };\n}\n\nasync function handlePull(\n\tcwd: string,\n\tglobalOptions: string[],\n\targs: string[],\n\toptions?: GitFilterOptions,\n): Promise<FilterResult> {\n\tconst res = await runGitQuery(cwd, globalOptions, [\"pull\", ...args], options);\n\tconst rawOut = rawText(res, true);\n\tif (res.status !== 0) return { output: rawOut, exitCode: res.status ?? 1, rawOut, rawBytes: res.rawBytes };\n\tif (rawOut.includes(\"Already up to date.\"))\n\t\treturn { output: \"Already up to date.\", exitCode: 0, rawOut, rawBytes: res.rawBytes };\n\tconst lines = rawOut.split(\"\\n\");\n\tconst summary = lines.filter(\n\t\t(line) => line.includes(\"Fast-forward\") || line.includes(\"file changed\") || line.includes(\"files changed\"),\n\t);\n\treturn { output: summary.join(\"\\n\") || \"Pull successful.\", exitCode: 0, rawOut, rawBytes: res.rawBytes };\n}\n\nasync function handleFetch(\n\tcwd: string,\n\tglobalOptions: string[],\n\targs: string[],\n\toptions?: GitFilterOptions,\n): Promise<FilterResult> {\n\tconst res = await runGitQuery(cwd, globalOptions, [\"fetch\", ...args], options);\n\tconst rawOut = rawText(res, true);\n\tif (res.status !== 0) return { output: rawOut, exitCode: res.status ?? 1, rawOut, rawBytes: res.rawBytes };\n\tconst refs = rawOut\n\t\t.split(\"\\n\")\n\t\t.filter((line) => line.includes(\"[new branch]\") || line.includes(\"[new tag]\") || line.includes(\"->\"));\n\treturn {\n\t\toutput: refs.length\n\t\t\t? `Fetched:\\n${refs.map((line) => line.trim()).join(\"\\n\")}`\n\t\t\t: \"Fetch successful (no new refs).\",\n\t\texitCode: 0,\n\t\trawOut,\n\t\trawBytes: res.rawBytes,\n\t};\n}\n\nasync function handleBranch(\n\tcwd: string,\n\tglobalOptions: string[],\n\targs: string[],\n\toptions?: GitFilterOptions,\n): Promise<FilterResult> {\n\tif (args.includes(\"--show-current\")) {\n\t\tconst res = await runGitQuery(cwd, globalOptions, [\"branch\", \"--show-current\"], options);\n\t\treturn { output: res.stdout.trim(), exitCode: res.status ?? 0, rawOut: rawText(res), rawBytes: res.rawBytes };\n\t}\n\tconst isWrite = args.some(\n\t\t(arg) =>\n\t\t\targ === \"-d\" || arg === \"-D\" || arg === \"-m\" || arg === \"-M\" || (!arg.startsWith(\"-\") && args.length === 1),\n\t);\n\tif (isWrite) {\n\t\tconst res = await runGitQuery(cwd, globalOptions, [\"branch\", ...args], options);\n\t\tconst rawOut = rawText(res);\n\t\tif (res.status !== 0) return { output: rawOut, exitCode: res.status ?? 1, rawOut, rawBytes: res.rawBytes };\n\t\treturn { output: rawOut.trim() || \"Branch updated successfully.\", exitCode: 0, rawOut, rawBytes: res.rawBytes };\n\t}\n\tconst res = await runGitQuery(cwd, globalOptions, [\"branch\", \"--no-color\", ...args], options);\n\tconst rawOut = rawText(res);\n\tif (res.status !== 0) return { output: rawOut, exitCode: res.status ?? 1, rawOut, rawBytes: res.rawBytes };\n\tconst lines = res.stdout.split(\"\\n\").filter((line) => line.trim().length > 0);\n\tconst remoteBranches = lines.filter((line) => line.includes(\"remotes/\"));\n\tconst localBranches = lines.filter((line) => !line.includes(\"remotes/\"));\n\tconst remoteDisplay = remoteBranches.slice(0, 5);\n\tconst omitted = remoteBranches.length - remoteDisplay.length;\n\tif (omitted > 0) remoteDisplay.push(` remotes/... (${omitted} more remote branches)`);\n\treturn { output: [...localBranches, ...remoteDisplay].join(\"\\n\"), exitCode: 0, rawOut, rawBytes: res.rawBytes };\n}\n\nasync function handleStash(\n\tcwd: string,\n\tglobalOptions: string[],\n\targs: string[],\n\toptions?: GitFilterOptions,\n): Promise<FilterResult> {\n\tconst sub = args[0] || \"push\";\n\tconst res = await runGitQuery(cwd, globalOptions, [\"stash\", ...args], options);\n\tconst rawOut = rawText(res);\n\tif (res.status !== 0) return { output: rawOut, exitCode: res.status ?? 1, rawOut, rawBytes: res.rawBytes };\n\tif (sub === \"list\")\n\t\treturn { output: res.stdout.trim() || \"No stashes found.\", exitCode: 0, rawOut, rawBytes: res.rawBytes };\n\tif (sub === \"show\") {\n\t\tconst { compacted, truncated } = compactDiff(res.stdout);\n\t\treturn applyOverflowDisclosure(res, {\n\t\t\toutput: `${compacted.trim()}${truncated ? \"\\n\\n[Diff truncated.]\" : \"\"}`,\n\t\t\texitCode: 0,\n\t\t\trawOut,\n\t\t\trawBytes: res.rawBytes,\n\t\t});\n\t}\n\tif (res.stdout.includes(\"No local changes to save\"))\n\t\treturn { output: \"No local changes to save.\", exitCode: 0, rawOut, rawBytes: res.rawBytes };\n\tconst firstLine = res.stdout\n\t\t.split(\"\\n\")\n\t\t.find((line) => line.trim().length > 0)\n\t\t?.trim();\n\treturn { output: firstLine || \"Stash successful.\", exitCode: 0, rawOut, rawBytes: res.rawBytes };\n}\n\nasync function handleWorktree(\n\tcwd: string,\n\tglobalOptions: string[],\n\targs: string[],\n\toptions?: GitFilterOptions,\n): Promise<FilterResult> {\n\tconst sub = args[0] || \"list\";\n\tconst res = await runGitQuery(cwd, globalOptions, [\"worktree\", ...(sub === \"list\" ? [\"list\"] : args)], options);\n\tconst rawOut = rawText(res, true);\n\tif (res.status !== 0) return { output: rawOut, exitCode: res.status ?? 1, rawOut, rawBytes: res.rawBytes };\n\tif (sub !== \"list\") return { output: rawOut.trim(), exitCode: 0, rawOut, rawBytes: res.rawBytes };\n\tconst home = process.env.HOME || \"\";\n\tconst output = res.stdout\n\t\t.split(\"\\n\")\n\t\t.map((line) => (home && line.startsWith(home) ? `~${line.slice(home.length)}` : line))\n\t\t.join(\"\\n\")\n\t\t.trim();\n\treturn { output, exitCode: 0, rawOut, rawBytes: res.rawBytes };\n}\n\nexport async function executeFilteredGit(\n\tcwd: string,\n\tsubcommand: string,\n\tglobalOptions: string[],\n\tsubcommandArgs: string[],\n\toptions?: GitFilterOptions,\n): Promise<FilterResult> {\n\tswitch (subcommand) {\n\t\tcase \"status\":\n\t\t\treturn handleStatus(cwd, globalOptions, subcommandArgs, options);\n\t\tcase \"log\":\n\t\t\treturn handleLog(cwd, globalOptions, subcommandArgs, options);\n\t\tcase \"diff\":\n\t\t\treturn handleDiff(cwd, globalOptions, subcommandArgs, options);\n\t\tcase \"show\":\n\t\t\treturn handleShow(cwd, globalOptions, subcommandArgs, options);\n\t\tcase \"add\":\n\t\t\treturn handleAdd(cwd, globalOptions, subcommandArgs, options);\n\t\tcase \"commit\":\n\t\t\treturn handleCommit(cwd, globalOptions, subcommandArgs, options);\n\t\tcase \"push\":\n\t\t\treturn handlePush(cwd, globalOptions, subcommandArgs, options);\n\t\tcase \"pull\":\n\t\t\treturn handlePull(cwd, globalOptions, subcommandArgs, options);\n\t\tcase \"branch\":\n\t\t\treturn handleBranch(cwd, globalOptions, subcommandArgs, options);\n\t\tcase \"fetch\":\n\t\t\treturn handleFetch(cwd, globalOptions, subcommandArgs, options);\n\t\tcase \"stash\":\n\t\t\treturn handleStash(cwd, globalOptions, subcommandArgs, options);\n\t\tcase \"worktree\":\n\t\t\treturn handleWorktree(cwd, globalOptions, subcommandArgs, options);\n\t\tdefault:\n\t\t\treturn { output: \"\", exitCode: -100, rawOut: \"\" };\n\t}\n}\n\nexport function makeGitCommandForDisplay(globalOptions: string[], subcommand: string, args: string[]): string {\n\treturn gitCommand(globalOptions, [subcommand, ...args]);\n}\n"]}