@caupulican/pi-adaptative 0.84.1 → 0.85.0

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 (145) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/dist/bundled-resources/extensions/tmux-agent-manager/index.d.ts.map +1 -1
  3. package/dist/bundled-resources/extensions/tmux-agent-manager/index.js +14 -8
  4. package/dist/bundled-resources/extensions/tmux-agent-manager/index.js.map +1 -1
  5. package/dist/bundled-resources/extensions/tmux-agent-manager/index.ts +14 -8
  6. package/dist/bundled-resources/skills/deduplicate-by-evidence/SKILL.md +7 -5
  7. package/dist/bundled-resources/skills/worker-profile-writer/SKILL.md +63 -0
  8. package/dist/core/autonomy/lane-tool-surface.d.ts.map +1 -1
  9. package/dist/core/autonomy/lane-tool-surface.js +4 -2
  10. package/dist/core/autonomy/lane-tool-surface.js.map +1 -1
  11. package/dist/core/background-lane-controller.d.ts +3 -0
  12. package/dist/core/background-lane-controller.d.ts.map +1 -1
  13. package/dist/core/background-lane-controller.js +6 -0
  14. package/dist/core/background-lane-controller.js.map +1 -1
  15. package/dist/core/default-tool-surface.d.ts.map +1 -1
  16. package/dist/core/default-tool-surface.js +1 -0
  17. package/dist/core/default-tool-surface.js.map +1 -1
  18. package/dist/core/delegation/worker-delegation-controller.d.ts +7 -0
  19. package/dist/core/delegation/worker-delegation-controller.d.ts.map +1 -1
  20. package/dist/core/delegation/worker-delegation-controller.js +28 -0
  21. package/dist/core/delegation/worker-delegation-controller.js.map +1 -1
  22. package/dist/core/delegation/worker-profile-resolver.d.ts +2 -0
  23. package/dist/core/delegation/worker-profile-resolver.d.ts.map +1 -1
  24. package/dist/core/delegation/worker-profile-resolver.js +46 -11
  25. package/dist/core/delegation/worker-profile-resolver.js.map +1 -1
  26. package/dist/core/doctor.d.ts +1 -1
  27. package/dist/core/doctor.d.ts.map +1 -1
  28. package/dist/core/doctor.js +5 -4
  29. package/dist/core/doctor.js.map +1 -1
  30. package/dist/core/model-capability.d.ts.map +1 -1
  31. package/dist/core/model-capability.js +1 -0
  32. package/dist/core/model-capability.js.map +1 -1
  33. package/dist/core/orchestration/lane-tool-manifests.d.ts +1 -1
  34. package/dist/core/orchestration/lane-tool-manifests.d.ts.map +1 -1
  35. package/dist/core/orchestration/lane-tool-manifests.js +6 -1
  36. package/dist/core/orchestration/lane-tool-manifests.js.map +1 -1
  37. package/dist/core/orchestration/session-task-profile-store.d.ts +31 -0
  38. package/dist/core/orchestration/session-task-profile-store.d.ts.map +1 -0
  39. package/dist/core/orchestration/session-task-profile-store.js +138 -0
  40. package/dist/core/orchestration/session-task-profile-store.js.map +1 -0
  41. package/dist/core/orchestration/task-profile-writer.d.ts +58 -0
  42. package/dist/core/orchestration/task-profile-writer.d.ts.map +1 -0
  43. package/dist/core/orchestration/task-profile-writer.js +165 -0
  44. package/dist/core/orchestration/task-profile-writer.js.map +1 -0
  45. package/dist/core/runtime-builder.d.ts +3 -1
  46. package/dist/core/runtime-builder.d.ts.map +1 -1
  47. package/dist/core/runtime-builder.js +14 -0
  48. package/dist/core/runtime-builder.js.map +1 -1
  49. package/dist/core/security/untrusted-boundary.d.ts.map +1 -1
  50. package/dist/core/security/untrusted-boundary.js +4 -6
  51. package/dist/core/security/untrusted-boundary.js.map +1 -1
  52. package/dist/core/session-role.d.ts.map +1 -1
  53. package/dist/core/session-role.js +1 -0
  54. package/dist/core/session-role.js.map +1 -1
  55. package/dist/core/system-prompt.d.ts.map +1 -1
  56. package/dist/core/system-prompt.js +21 -23
  57. package/dist/core/system-prompt.js.map +1 -1
  58. package/dist/core/tool-capability-policy.js +1 -1
  59. package/dist/core/tool-capability-policy.js.map +1 -1
  60. package/dist/core/tools/bash.d.ts +1 -6
  61. package/dist/core/tools/bash.d.ts.map +1 -1
  62. package/dist/core/tools/bash.js +2 -26
  63. package/dist/core/tools/bash.js.map +1 -1
  64. package/dist/core/tools/delegate.js +4 -4
  65. package/dist/core/tools/delegate.js.map +1 -1
  66. package/dist/core/tools/edit-diff.d.ts +32 -5
  67. package/dist/core/tools/edit-diff.d.ts.map +1 -1
  68. package/dist/core/tools/edit-diff.js +137 -69
  69. package/dist/core/tools/edit-diff.js.map +1 -1
  70. package/dist/core/tools/edit.d.ts +22 -7
  71. package/dist/core/tools/edit.d.ts.map +1 -1
  72. package/dist/core/tools/edit.js +128 -55
  73. package/dist/core/tools/edit.js.map +1 -1
  74. package/dist/core/tools/file-mutation-intent.d.ts +70 -0
  75. package/dist/core/tools/file-mutation-intent.d.ts.map +1 -0
  76. package/dist/core/tools/file-mutation-intent.js +325 -0
  77. package/dist/core/tools/file-mutation-intent.js.map +1 -0
  78. package/dist/core/tools/goal.d.ts.map +1 -1
  79. package/dist/core/tools/goal.js +41 -18
  80. package/dist/core/tools/goal.js.map +1 -1
  81. package/dist/core/tools/index.d.ts +3 -1
  82. package/dist/core/tools/index.d.ts.map +1 -1
  83. package/dist/core/tools/index.js +31 -8
  84. package/dist/core/tools/index.js.map +1 -1
  85. package/dist/core/tools/profile-writer.d.ts +33 -0
  86. package/dist/core/tools/profile-writer.d.ts.map +1 -0
  87. package/dist/core/tools/profile-writer.js +67 -0
  88. package/dist/core/tools/profile-writer.js.map +1 -0
  89. package/dist/core/tools/task-steps.d.ts.map +1 -1
  90. package/dist/core/tools/task-steps.js +6 -11
  91. package/dist/core/tools/task-steps.js.map +1 -1
  92. package/dist/core/tools/tmux-dispatch.d.ts +2 -0
  93. package/dist/core/tools/tmux-dispatch.d.ts.map +1 -1
  94. package/dist/core/tools/tmux-dispatch.js +16 -2
  95. package/dist/core/tools/tmux-dispatch.js.map +1 -1
  96. package/dist/core/tools/write.d.ts +24 -7
  97. package/dist/core/tools/write.d.ts.map +1 -1
  98. package/dist/core/tools/write.js +182 -107
  99. package/dist/core/tools/write.js.map +1 -1
  100. package/dist/index.d.ts +1 -1
  101. package/dist/index.d.ts.map +1 -1
  102. package/dist/index.js +1 -1
  103. package/dist/index.js.map +1 -1
  104. package/dist/jscpd-cli.d.ts +3 -0
  105. package/dist/jscpd-cli.d.ts.map +1 -0
  106. package/dist/jscpd-cli.js +22 -0
  107. package/dist/jscpd-cli.js.map +1 -0
  108. package/dist/modes/interactive/components/profile-resource-editor.js +2 -2
  109. package/dist/modes/interactive/components/profile-resource-editor.js.map +1 -1
  110. package/dist/modes/interactive/components/tool-execution.d.ts +1 -0
  111. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  112. package/dist/modes/interactive/components/tool-execution.js +85 -3
  113. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  114. package/dist/modes/interactive/interactive-mode.js +1 -1
  115. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  116. package/dist/utils/bundled-jscpd.d.ts +20 -0
  117. package/dist/utils/bundled-jscpd.d.ts.map +1 -0
  118. package/dist/utils/bundled-jscpd.js +154 -0
  119. package/dist/utils/bundled-jscpd.js.map +1 -0
  120. package/dist/utils/shell.d.ts.map +1 -1
  121. package/dist/utils/shell.js +11 -0
  122. package/dist/utils/shell.js.map +1 -1
  123. package/dist/utils/tools-manager.d.ts +1 -1
  124. package/dist/utils/tools-manager.d.ts.map +1 -1
  125. package/dist/utils/tools-manager.js +22 -0
  126. package/dist/utils/tools-manager.js.map +1 -1
  127. package/docs/index.md +3 -0
  128. package/docs/managed-data-tools.md +15 -0
  129. package/docs/quickstart.md +2 -2
  130. package/docs/tool-boundary-performance-roadmap-2026-08-02.md +166 -0
  131. package/docs/tool-repair.md +1 -1
  132. package/docs/worker-profiles.md +16 -0
  133. package/examples/extensions/built-in-tool-renderer.ts +12 -5
  134. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  135. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  136. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  137. package/examples/extensions/minimal-mode.ts +8 -7
  138. package/examples/extensions/prompt-customizer.ts +4 -2
  139. package/examples/extensions/sandbox/package-lock.json +2 -2
  140. package/examples/extensions/sandbox/package.json +1 -1
  141. package/examples/extensions/ssh.ts +113 -24
  142. package/examples/extensions/with-deps/package-lock.json +2 -2
  143. package/examples/extensions/with-deps/package.json +1 -1
  144. package/npm-shrinkwrap.json +112 -12
  145. package/package.json +7 -5
@@ -1 +1 @@
1
- {"version":3,"file":"tools-manager.js","sourceRoot":"","sources":["../../src/utils/tools-manager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAyB,SAAS,EAAE,MAAM,eAAe,CAAC;AACjE,OAAO,EACN,UAAU,EACV,SAAS,EACT,gBAAgB,EAChB,iBAAiB,EACjB,UAAU,EACV,SAAS,IAAI,WAAW,EACxB,SAAS,EACT,WAAW,EACX,YAAY,EACZ,UAAU,EACV,MAAM,EACN,QAAQ,EACR,aAAa,GACb,MAAM,IAAI,CAAC;AACZ,OAAO,EAAE,aAAa,EAAE,MAAM,QAAQ,CAAC;AACvC,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,IAAI,CAAC;AACpC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AACrC,OAAO,EAAE,QAAQ,EAAE,MAAM,QAAQ,CAAC;AAClC,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,aAAa,EAAE,MAAM,KAAK,CAAC;AACpC,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAChE,OAAO,EAAE,QAAQ,IAAI,aAAa,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AAC9E,OAAO,EAAE,YAAY,EAAE,kCAAkC,EAAE,MAAM,oBAAoB,CAAC;AACtF,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAExD,MAAM,SAAS,GAAG,SAAS,EAAE,CAAC;AAC9B,MAAM,kBAAkB,GAAG,MAAM,C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O,SAAS,CAAC;QAClB,CAAC;IACF,CAAC;IAED,+BAA+B;IAC/B,IAAI,CAAC,MAAM,EAAE,CAAC;QACb,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,MAAM,CAAC,IAAI,4BAA4B,CAAC,CAAC,CAAC;IACpE,CAAC;IAED,IAAI,CAAC;QACJ,MAAM,IAAI,GAAG,MAAM,wBAAwB,CAAC,IAAI,EAAE,GAAG,EAAE,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC;QAC5E,IAAI,CAAC,MAAM,EAAE,CAAC;YACb,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,MAAM,CAAC,IAAI,iBAAiB,IAAI,EAAE,CAAC,CAAC,CAAC;QAC/D,CAAC;QACD,OAAO,IAAI,CAAC;IACb,CAAC;IAAC,OAAO,CAAC,EAAE,CAAC;QACZ,IAAI,CAAC,MAAM,EAAE,CAAC;YACb,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,MAAM,CAAC,sBAAsB,MAAM,CAAC,IAAI,KAAK,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;QACvG,CAAC;QACD,OAAO,SAAS,CAAC;IAClB,CAAC;AACF,CAAC","sourcesContent":["import { createHash } from \"node:crypto\";\nimport chalk from \"chalk\";\nimport { type SpawnSyncReturns, spawnSync } from \"child_process\";\nimport {\n\taccessSync,\n\tchmodSync,\n\tcreateReadStream,\n\tcreateWriteStream,\n\texistsSync,\n\tconstants as fsConstants,\n\tmkdirSync,\n\treaddirSync,\n\treadFileSync,\n\trenameSync,\n\trmSync,\n\tstatSync,\n\twriteFileSync,\n} from \"fs\";\nimport { createRequire } from \"module\";\nimport { arch, platform } from \"os\";\nimport { dirname, join } from \"path\";\nimport { Readable } from \"stream\";\nimport { pipeline } from \"stream/promises\";\nimport { pathToFileURL } from \"url\";\nimport { APP_NAME, getAgentDir, getBinDir } from \"../config.ts\";\nimport { cacheDir as agentCacheDir, cacheFile } from \"../core/agent-paths.ts\";\nimport { spawnProcess, waitForChildProcessWithTermination } from \"./child-process.ts\";\nimport { getProcessWorkRun } from \"./work-directory.ts\";\n\nconst TOOLS_DIR = getBinDir();\nconst NETWORK_TIMEOUT_MS = 10_000;\nconst DOWNLOAD_TIMEOUT_MS = 120_000;\nconst COMMAND_PROBE_TIMEOUT_MS = 5_000;\nconst ARCHIVE_EXTRACTION_TIMEOUT_MS = 5 * 60_000;\nconst FFF_NODE_VERSION = \"0.9.6\";\nexport const RG_VERSION = \"15.2.0\";\nexport const JQ_VERSION = \"1.8.2\";\nexport const UV_VERSION = \"0.11.28\";\nconst FFF_MANAGED_DIR = join(TOOLS_DIR, \"fff-node\");\nconst FFF_MANAGED_PACKAGE_JSON = join(FFF_MANAGED_DIR, \"package.json\");\n\ntype ModuleRequire = ((id: string) => unknown) & { resolve?: (id: string) => string };\n\nconst moduleRequire = createRequire(import.meta.url);\nconst executableDirRequire = createRequire(pathToFileURL(join(dirname(process.execPath), \"package.json\")).href);\n\nfunction isOfflineModeEnabled(): boolean {\n\tconst value = process.env.PI_OFFLINE;\n\tif (!value) return false;\n\treturn value === \"1\" || value.toLowerCase() === \"true\" || value.toLowerCase() === \"yes\";\n}\n\ninterface ToolConfig {\n\tname: string;\n\trepo: string; // GitHub repo (e.g., \"sharkdp/fd\")\n\tbinaryName: string; // Name of the binary inside the archive\n\tsystemBinaryNames?: string[]; // Alternative system command names to try before downloading\n\ttagPrefix: string; // Prefix for tags (e.g., \"v\" for v1.0.0, \"\" for 1.0.0)\n\tgetAssetName: (version: string, plat: string, architecture: string) => string | null;\n\tdownloadKind?: \"archive\" | \"binary\";\n\tpinnedVersion?: string;\n\tsha256ByAsset?: Readonly<Record<string, string>>;\n}\n\nconst TOOLS: Record<\"fd\" | \"jq\" | \"rg\" | \"uv\", ToolConfig> = {\n\tfd: {\n\t\tname: \"fd\",\n\t\trepo: \"sharkdp/fd\",\n\t\tbinaryName: \"fd\",\n\t\tsystemBinaryNames: [\"fd\", \"fdfind\"],\n\t\ttagPrefix: \"v\",\n\t\tgetAssetName: (version, plat, architecture) => {\n\t\t\tif (plat === \"darwin\") {\n\t\t\t\tconst archStr = architecture === \"arm64\" ? \"aarch64\" : \"x86_64\";\n\t\t\t\treturn `fd-v${version}-${archStr}-apple-darwin.tar.gz`;\n\t\t\t} else if (plat === \"linux\") {\n\t\t\t\tconst archStr = architecture === \"arm64\" ? \"aarch64\" : \"x86_64\";\n\t\t\t\treturn `fd-v${version}-${archStr}-unknown-linux-gnu.tar.gz`;\n\t\t\t} else if (plat === \"win32\") {\n\t\t\t\tconst archStr = architecture === \"arm64\" ? \"aarch64\" : \"x86_64\";\n\t\t\t\treturn `fd-v${version}-${archStr}-pc-windows-msvc.zip`;\n\t\t\t}\n\t\t\treturn null;\n\t\t},\n\t},\n\trg: {\n\t\tname: \"ripgrep\",\n\t\trepo: \"BurntSushi/ripgrep\",\n\t\tbinaryName: \"rg\",\n\t\ttagPrefix: \"\",\n\t\tpinnedVersion: RG_VERSION,\n\t\tgetAssetName: (version, plat, architecture) => {\n\t\t\tif (plat === \"darwin\") {\n\t\t\t\tconst archStr = architecture === \"arm64\" ? \"aarch64\" : \"x86_64\";\n\t\t\t\treturn `ripgrep-${version}-${archStr}-apple-darwin.tar.gz`;\n\t\t\t} else if (plat === \"linux\") {\n\t\t\t\tif (architecture === \"arm64\") {\n\t\t\t\t\treturn `ripgrep-${version}-aarch64-unknown-linux-gnu.tar.gz`;\n\t\t\t\t}\n\t\t\t\treturn `ripgrep-${version}-x86_64-unknown-linux-musl.tar.gz`;\n\t\t\t} else if (plat === \"win32\") {\n\t\t\t\tconst archStr = architecture === \"arm64\" ? \"aarch64\" : \"x86_64\";\n\t\t\t\treturn `ripgrep-${version}-${archStr}-pc-windows-msvc.zip`;\n\t\t\t}\n\t\t\treturn null;\n\t\t},\n\t\tsha256ByAsset: {\n\t\t\t\"ripgrep-15.2.0-aarch64-apple-darwin.tar.gz\":\n\t\t\t\t\"3750b2e93f37e0c692657da574d7019a101c0084da05a790c83fd335bad973e4\",\n\t\t\t\"ripgrep-15.2.0-aarch64-pc-windows-msvc.zip\":\n\t\t\t\t\"e4abca10c3a64ebea742667dd7009449d49403db5460dd6873e389fa2945360f\",\n\t\t\t\"ripgrep-15.2.0-aarch64-unknown-linux-gnu.tar.gz\":\n\t\t\t\t\"a740b91c82eaf9914cfedd353572f2791cbe0162c84101ee0951058f4dcbc90d\",\n\t\t\t\"ripgrep-15.2.0-x86_64-apple-darwin.tar.gz\":\n\t\t\t\t\"af7825fcc69a2afc7a7aea55fc9af90e26421d8f20fe59df32e233c0b8a231c1\",\n\t\t\t\"ripgrep-15.2.0-x86_64-pc-windows-msvc.zip\":\n\t\t\t\t\"71b2fef860abe467217a538ff31de02f5258807c0129f771846f87bd029aafc5\",\n\t\t\t\"ripgrep-15.2.0-x86_64-unknown-linux-musl.tar.gz\":\n\t\t\t\t\"33e15bcf1624b25cdd2a55813a47a2f95dbe126268203e76aa6a585d1e7b149c\",\n\t\t},\n\t},\n\tjq: {\n\t\tname: \"jq\",\n\t\trepo: \"jqlang/jq\",\n\t\tbinaryName: \"jq\",\n\t\tsystemBinaryNames: [\"jq\"],\n\t\ttagPrefix: \"jq-\",\n\t\tdownloadKind: \"binary\",\n\t\tpinnedVersion: JQ_VERSION,\n\t\tgetAssetName: (_version, plat, architecture) => {\n\t\t\tif (architecture !== \"arm64\" && architecture !== \"x64\") return null;\n\t\t\tconst archStr = architecture === \"arm64\" ? \"arm64\" : \"amd64\";\n\t\t\tif (plat === \"darwin\") return `jq-macos-${archStr}`;\n\t\t\tif (plat === \"linux\") return `jq-linux-${archStr}`;\n\t\t\tif (plat === \"win32\") return `jq-windows-${archStr}.exe`;\n\t\t\treturn null;\n\t\t},\n\t\tsha256ByAsset: {\n\t\t\t\"jq-linux-amd64\": \"b1c22172dd303f3be49e935aa56aa48a8b7a46e0bc838b4997d3bb451495870f\",\n\t\t\t\"jq-linux-arm64\": \"8b85c817833814ddca00a144c33705546355afccf0cf39b188f3cdb48b852309\",\n\t\t\t\"jq-macos-amd64\": \"e94b266e3c26690550006abe63152b782280f4e14374accdf04cbde844f00bc0\",\n\t\t\t\"jq-macos-arm64\": \"2d75340ba57a4b4b4c8708a21c2dc8e958a48aaa8bba13b27f77f6e4c0eca07e\",\n\t\t\t\"jq-windows-amd64.exe\": \"a6fc67fedaf9128a3309a1e2ebb8b986aeccf70122ee46d2cb4849e423f0c627\",\n\t\t\t\"jq-windows-arm64.exe\": \"083b5377392bc57cf27052b6d20a2d927770683bca844632901ff38b4b7b0ac7\",\n\t\t},\n\t},\n\tuv: {\n\t\tname: \"uv\",\n\t\trepo: \"astral-sh/uv\",\n\t\tbinaryName: \"uv\",\n\t\tsystemBinaryNames: [\"uv\"],\n\t\ttagPrefix: \"\",\n\t\tpinnedVersion: UV_VERSION,\n\t\tgetAssetName: (_version, plat, architecture) => {\n\t\t\tif (architecture !== \"arm64\" && architecture !== \"x64\") return null;\n\t\t\tconst archStr = architecture === \"arm64\" ? \"aarch64\" : \"x86_64\";\n\t\t\tif (plat === \"darwin\") return `uv-${archStr}-apple-darwin.tar.gz`;\n\t\t\tif (plat === \"linux\") return `uv-${archStr}-unknown-linux-musl.tar.gz`;\n\t\t\tif (plat === \"win32\") return `uv-${archStr}-pc-windows-msvc.zip`;\n\t\t\treturn null;\n\t\t},\n\t\tsha256ByAsset: {\n\t\t\t\"uv-aarch64-apple-darwin.tar.gz\": \"33540eb7c883ab857eff79bd5ac2aa31fe27b595abecb4a9c003a2c998447232\",\n\t\t\t\"uv-aarch64-pc-windows-msvc.zip\": \"3248109afad3ec59baad299d324ff53de17e2d9a3b3e21580ffd26744b11e036\",\n\t\t\t\"uv-aarch64-unknown-linux-musl.tar.gz\": \"da10cdfa7d92212b7acb62021a0fd61bcf8580c58c3632ec915d10c3a1a7906b\",\n\t\t\t\"uv-x86_64-apple-darwin.tar.gz\": \"2ad79983127ffca7d77b77ce6a24278d7e4f7b817a1acf72fea5f8124b4aac5e\",\n\t\t\t\"uv-x86_64-pc-windows-msvc.zip\": \"0a23463216d09c6a72ff80ef5dc5a795f07dc1575cb84d24596c2f124a441b7b\",\n\t\t\t\"uv-x86_64-unknown-linux-musl.tar.gz\": \"f02146b371c35c287d860f003ece7345c86e358a3fd70a9b63700cd141ee7fb4\",\n\t\t},\n\t},\n};\n\nexport type ManagedToolName = keyof typeof TOOLS;\n\nexport interface PinnedToolAsset {\n\tversion: string;\n\tassetName: string;\n\texpectedSha256: string;\n}\n\nexport function getPinnedToolAsset(\n\ttool: ManagedToolName,\n\ttargetPlatform: string = platform(),\n\ttargetArchitecture: string = arch(),\n): PinnedToolAsset | null {\n\tconst config: ToolConfig = TOOLS[tool];\n\tif (!config.pinnedVersion || !config.sha256ByAsset) return null;\n\tconst assetName = config.getAssetName(config.pinnedVersion, targetPlatform, targetArchitecture);\n\tif (!assetName) return null;\n\tconst expectedSha256 = config.sha256ByAsset[assetName];\n\treturn expectedSha256 ? { version: config.pinnedVersion, assetName, expectedSha256 } : null;\n}\n\n// Check if a command exists in PATH by trying to run it\nfunction commandExists(cmd: string): boolean {\n\ttry {\n\t\tconst result = spawnSync(cmd, [\"--version\"], { stdio: \"pipe\", timeout: COMMAND_PROBE_TIMEOUT_MS });\n\t\t// Check for ENOENT error (command not found)\n\t\treturn result.error === undefined || result.error === null;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\ninterface CachedToolPath {\n\tpath: string;\n\tmtimeMs: number;\n}\n\nfunction isCachedToolPath(value: unknown): value is CachedToolPath {\n\tif (typeof value !== \"object\" || value === null) return false;\n\tconst candidate = value as Record<string, unknown>;\n\treturn typeof candidate.path === \"string\" && typeof candidate.mtimeMs === \"number\";\n}\n\nfunction getToolPathCacheFile(): string {\n\treturn cacheFile(getAgentDir(), \"tool-paths.json\");\n}\n\n/** Read the persisted cross-run tool-path cache. Missing/corrupt/foreign entries are dropped silently -- a cold cache just means the next resolve re-probes and repopulates it. */\nfunction readToolPathCache(): Partial<Record<ManagedToolName, CachedToolPath>> {\n\ttry {\n\t\tconst raw = readFileSync(getToolPathCacheFile(), \"utf-8\");\n\t\tconst parsed = JSON.parse(raw) as Record<string, unknown>;\n\t\tconst cache: Partial<Record<ManagedToolName, CachedToolPath>> = {};\n\t\tfor (const tool of Object.keys(TOOLS) as ManagedToolName[]) {\n\t\t\tconst entry = parsed[tool];\n\t\t\tif (isCachedToolPath(entry)) cache[tool] = entry;\n\t\t}\n\t\treturn cache;\n\t} catch {\n\t\treturn {};\n\t}\n}\n\nfunction writeToolPathCacheEntry(tool: ManagedToolName, entry: CachedToolPath): void {\n\ttry {\n\t\tconst cacheDir = agentCacheDir(getAgentDir());\n\t\tmkdirSync(cacheDir, { recursive: true });\n\t\tconst cache = readToolPathCache();\n\t\tcache[tool] = entry;\n\t\twriteFileSync(join(cacheDir, \"tool-paths.json\"), JSON.stringify(cache));\n\t} catch {\n\t\t// Best-effort: a failed cache write only costs the next run its probe, same as a cold cache.\n\t}\n}\n\n/** A cached entry is fresh only while its file still exists at the same path with the same mtime -- a deleted/moved/replaced binary invalidates it and forces a re-probe below. */\nfunction isCachedToolPathFresh(entry: CachedToolPath): boolean {\n\ttry {\n\t\treturn statSync(entry.path).mtimeMs === entry.mtimeMs;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction getPathExtensionCandidates(): readonly string[] {\n\tif (platform() !== \"win32\") return [\"\"];\n\tconst pathExt = process.env.PATHEXT || \".COM;.EXE;.BAT;.CMD\";\n\treturn [\"\", ...pathExt.split(\";\").filter(Boolean)];\n}\n\n/**\n * Manually walk PATH to turn a bare command name that commandExists() already confirmed is\n * runnable into an absolute, stat-checkable path. This never decides presence itself (that stays\n * commandExists's job via spawnSync, unchanged) -- it only supplies the path the cross-run cache\n * needs for its mtime staleness check, using stat calls instead of another spawn.\n */\nfunction resolveOnSystemPath(binaryName: string): string | null {\n\tconst pathEnv = process.env.PATH ?? \"\";\n\tconst dirs = pathEnv.split(platform() === \"win32\" ? \";\" : \":\").filter(Boolean);\n\tfor (const dir of dirs) {\n\t\tfor (const ext of getPathExtensionCandidates()) {\n\t\t\tconst candidate = join(dir, binaryName + ext);\n\t\t\tif (!existsSync(candidate)) continue;\n\t\t\ttry {\n\t\t\t\tif (statSync(candidate).isDirectory()) continue;\n\t\t\t\tif (platform() !== \"win32\") accessSync(candidate, fsConstants.X_OK);\n\t\t\t} catch {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\treturn candidate;\n\t\t}\n\t}\n\treturn null;\n}\n\nfunction cacheResolvedSystemPath(tool: ManagedToolName, resolvedPath: string): void {\n\ttry {\n\t\twriteToolPathCacheEntry(tool, { path: resolvedPath, mtimeMs: statSync(resolvedPath).mtimeMs });\n\t} catch {\n\t\t// Stat raced with a delete between resolve and here: nothing to cache, still return the path below.\n\t}\n}\n\n// Get the path to a tool (system-wide or in our tools dir)\nexport function getToolPath(tool: ManagedToolName): string | null {\n\tconst config = TOOLS[tool];\n\tif (!config) return null;\n\n\t// Check our tools directory first\n\tconst localPath = join(TOOLS_DIR, config.binaryName + (platform() === \"win32\" ? \".exe\" : \"\"));\n\tif (existsSync(localPath)) {\n\t\treturn localPath;\n\t}\n\n\t// Check system PATH - if found, just return the command name (it's in PATH)\n\tconst systemBinaryNames = config.systemBinaryNames ?? [config.binaryName];\n\n\t// A system-PATH resolution normally requires commandExists's synchronous\n\t// spawnSync(`<name> --version`) probe below, which is expensive to pay on every process\n\t// startup (this runs once per tool at interactive-mode init, plus again on the first\n\t// find/grep tool call). Persist the resolved absolute path + mtime across runs\n\t// (<agentDir>/cache/tool-paths.json) so a warm run can skip the probe entirely and just\n\t// stat the cached path instead. KNOWN LIMITATION: if a *different* binary of the same name\n\t// starts shadowing the cached one earlier on PATH (e.g. a new install) while the\n\t// originally-cached file itself is untouched, this cache keeps returning the old path until\n\t// that file is deleted/modified -- an intentional narrow staleness window (the returned tool\n\t// still exists and runs; it just isn't the newly-shadowing one), not a correctness bug.\n\tconst cached = readToolPathCache()[tool];\n\tif (cached && isCachedToolPathFresh(cached)) {\n\t\treturn cached.path;\n\t}\n\n\tfor (const systemBinaryName of systemBinaryNames) {\n\t\tif (commandExists(systemBinaryName)) {\n\t\t\tconst resolved = resolveOnSystemPath(systemBinaryName);\n\t\t\tif (resolved) {\n\t\t\t\tcacheResolvedSystemPath(tool, resolved);\n\t\t\t\treturn resolved;\n\t\t\t}\n\t\t\t// Could not resolve an absolute path to cache (e.g. PATH env raced between the two\n\t\t\t// lookups); still return the bare name so the caller keeps working, uncached.\n\t\t\treturn systemBinaryName;\n\t\t}\n\t}\n\n\treturn null;\n}\n\n/** Presence check for a SYSTEM tool the doctor only ever reports on -- never installs. */\nexport interface SystemToolStatus {\n\tpresent: boolean;\n\tcommand?: string;\n\tversion?: string;\n}\n\nconst PYTHON_COMMANDS = [\"python3\", \"python\"];\n\n/**\n * Detect a usable Python interpreter. SYSTEM tool (see src/core/doctor.ts):\n * the doctor reports presence/version, it never installs this itself.\n *\n * @param commands Override the candidate command names, for tests.\n */\nexport function detectPython(commands: readonly string[] = PYTHON_COMMANDS): SystemToolStatus {\n\tfor (const command of commands) {\n\t\ttry {\n\t\t\tconst result = spawnSync(command, [\"--version\"], { encoding: \"utf-8\", stdio: \"pipe\", timeout: 5_000 });\n\t\t\tif (result.error) continue;\n\t\t\t// Python 2 prints its version to stderr; Python 3 prints to stdout. Some\n\t\t\t// platforms' `python` alias is one or the other, so check both.\n\t\t\tconst version = `${result.stdout ?? \"\"}${result.stderr ?? \"\"}`.trim() || undefined;\n\t\t\tif (result.status !== 0 && !version) continue;\n\t\t\treturn { present: true, command, version };\n\t\t} catch {\n\t\t\t// Try the next candidate.\n\t\t}\n\t}\n\treturn { present: false };\n}\n\n/**\n * Runs `<command> --version` (or `versionArgs`) and returns its trimmed\n * combined stdout+stderr, or undefined if the command can't be run. Used by\n * the doctor (src/core/doctor.ts) to show a version alongside a tool it has\n * already located by some other means (e.g. getToolPath(\"rg\"), or the binary\n * path OllamaRuntime.detect() reports) -- callers that only need a yes/no\n * presence check should use commandExists/getToolPath/detectPython instead.\n */\nexport function probeVersion(command: string, versionArgs: readonly string[] = [\"--version\"]): string | undefined {\n\ttry {\n\t\tconst result = spawnSync(command, versionArgs, { encoding: \"utf-8\", stdio: \"pipe\", timeout: 5_000 });\n\t\tif (result.error) return undefined;\n\t\tconst output = `${result.stdout ?? \"\"}${result.stderr ?? \"\"}`.trim();\n\t\treturn output || undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n// Fetch latest release version from GitHub\nasync function getLatestVersion(repo: string): Promise<string> {\n\tconst response = await fetch(`https://api.github.com/repos/${repo}/releases/latest`, {\n\t\theaders: { \"User-Agent\": `${APP_NAME}-coding-agent` },\n\t\tsignal: AbortSignal.timeout(NETWORK_TIMEOUT_MS),\n\t});\n\n\tif (!response.ok) {\n\t\tthrow new Error(`GitHub API error: ${response.status}`);\n\t}\n\n\tconst data = (await response.json()) as { tag_name: string };\n\treturn data.tag_name.replace(/^v/, \"\");\n}\n\n// Download a file from URL\nasync function downloadFile(url: string, dest: string): Promise<void> {\n\tconst response = await fetch(url, {\n\t\tsignal: AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS),\n\t});\n\n\tif (!response.ok) {\n\t\tthrow new Error(`Failed to download: ${response.status}`);\n\t}\n\n\tif (!response.body) {\n\t\tthrow new Error(\"No response body\");\n\t}\n\n\tconst fileStream = createWriteStream(dest);\n\tawait pipeline(Readable.fromWeb(response.body as any), fileStream);\n}\n\nexport async function verifyFileSha256(filePath: string, expectedSha256: string): Promise<boolean> {\n\tconst hash = createHash(\"sha256\");\n\tawait new Promise<void>((resolve, reject) => {\n\t\tconst stream = createReadStream(filePath);\n\t\tstream.on(\"data\", (chunk) => hash.update(chunk));\n\t\tstream.once(\"error\", reject);\n\t\tstream.once(\"end\", resolve);\n\t});\n\treturn hash.digest(\"hex\") === expectedSha256.toLowerCase();\n}\n\nfunction findBinaryRecursively(rootDir: string, binaryFileName: string): string | null {\n\tconst stack: string[] = [rootDir];\n\n\twhile (stack.length > 0) {\n\t\tconst currentDir = stack.pop();\n\t\tif (!currentDir) continue;\n\n\t\tconst entries = readdirSync(currentDir, { withFileTypes: true });\n\t\tfor (const entry of entries) {\n\t\t\tconst fullPath = join(currentDir, entry.name);\n\t\t\tif (entry.isFile() && entry.name === binaryFileName) {\n\t\t\t\treturn fullPath;\n\t\t\t}\n\t\t\tif (entry.isDirectory()) {\n\t\t\t\tstack.push(fullPath);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn null;\n}\n\nfunction formatSpawnFailure(result: SpawnSyncReturns<Buffer>): string {\n\tif (result.error?.message) {\n\t\treturn result.error.message;\n\t}\n\tconst stderr = result.stderr?.toString().trim();\n\tif (stderr) {\n\t\treturn stderr;\n\t}\n\tconst stdout = result.stdout?.toString().trim();\n\tif (stdout) {\n\t\treturn stdout;\n\t}\n\treturn `exit status ${result.status ?? \"unknown\"}`;\n}\n\nfunction runExtractionCommand(command: string, args: string[]): string | null {\n\tconst result = spawnSync(command, args, { stdio: \"pipe\", timeout: ARCHIVE_EXTRACTION_TIMEOUT_MS });\n\tif (!result.error && result.status === 0) {\n\t\treturn null;\n\t}\n\treturn `${command}: ${formatSpawnFailure(result)}`;\n}\n\nfunction extractTarGzArchive(archivePath: string, extractDir: string, assetName: string): void {\n\tconst failure = runExtractionCommand(\"tar\", [\"xzf\", archivePath, \"-C\", extractDir]);\n\tif (failure) {\n\t\tthrow new Error(`Failed to extract ${assetName}: ${failure}`);\n\t}\n}\n\nfunction getWindowsTarCommand(): string {\n\tconst systemRoot = process.env.SystemRoot ?? process.env.WINDIR;\n\tif (systemRoot) {\n\t\tconst systemTar = join(systemRoot, \"System32\", \"tar.exe\");\n\t\tif (existsSync(systemTar)) {\n\t\t\treturn systemTar;\n\t\t}\n\t}\n\treturn \"tar.exe\";\n}\n\nfunction extractZipArchive(archivePath: string, extractDir: string, assetName: string): void {\n\tconst failures: string[] = [];\n\n\tif (platform() === \"win32\") {\n\t\t// Windows ships bsdtar as tar.exe, which supports zip files. Prefer the\n\t\t// System32 binary over Git Bash's GNU tar, which does not handle zip archives.\n\t\tconst tarFailure = runExtractionCommand(getWindowsTarCommand(), [\"xf\", archivePath, \"-C\", extractDir]);\n\t\tif (!tarFailure) return;\n\t\tfailures.push(tarFailure);\n\n\t\tconst script =\n\t\t\t\"& { param($archive, $destination) $ErrorActionPreference = 'Stop'; Expand-Archive -LiteralPath $archive -DestinationPath $destination -Force }\";\n\t\tconst powershellFailure = runExtractionCommand(\"powershell.exe\", [\n\t\t\t\"-NoLogo\",\n\t\t\t\"-NoProfile\",\n\t\t\t\"-NonInteractive\",\n\t\t\t\"-ExecutionPolicy\",\n\t\t\t\"Bypass\",\n\t\t\t\"-Command\",\n\t\t\tscript,\n\t\t\tarchivePath,\n\t\t\textractDir,\n\t\t]);\n\t\tif (!powershellFailure) return;\n\t\tfailures.push(powershellFailure);\n\t} else {\n\t\tconst unzipFailure = runExtractionCommand(\"unzip\", [\"-q\", archivePath, \"-d\", extractDir]);\n\t\tif (!unzipFailure) return;\n\t\tfailures.push(unzipFailure);\n\n\t\tconst tarFailure = runExtractionCommand(\"tar\", [\"xf\", archivePath, \"-C\", extractDir]);\n\t\tif (!tarFailure) return;\n\t\tfailures.push(tarFailure);\n\t}\n\n\tthrow new Error(`Failed to extract ${assetName}: ${failures.join(\"; \")}`);\n}\n\n/** Move a verified upstream standalone executable into Pi's managed bin directory. */\nexport function installStandaloneBinaryAsset(\n\tdownloadedPath: string,\n\tbinaryPath: string,\n\ttargetPlatform: string = platform(),\n): void {\n\tmkdirSync(dirname(binaryPath), { recursive: true });\n\trenameSync(downloadedPath, binaryPath);\n\tif (targetPlatform !== \"win32\") chmodSync(binaryPath, 0o755);\n}\n\n// Download and install a tool\nconst toolDownloadPromises = new Map<ManagedToolName, Promise<string | undefined>>();\n\nexport function runExclusiveToolDownload(\n\ttool: ManagedToolName,\n\tinstaller: () => Promise<string | undefined>,\n): Promise<string | undefined> {\n\tconst existing = toolDownloadPromises.get(tool);\n\tif (existing) return existing;\n\tconst promise = installer().finally(() => {\n\t\tif (toolDownloadPromises.get(tool) === promise) {\n\t\t\ttoolDownloadPromises.delete(tool);\n\t\t}\n\t});\n\ttoolDownloadPromises.set(tool, promise);\n\treturn promise;\n}\n\nasync function downloadTool(tool: ManagedToolName): Promise<string> {\n\tconst config: ToolConfig = TOOLS[tool];\n\tif (!config) throw new Error(`Unknown tool: ${tool}`);\n\n\tconst plat = platform();\n\tconst architecture = arch();\n\n\t// Pinned tools are reproducible and verified before installation.\n\tlet version = config.pinnedVersion ?? (await getLatestVersion(config.repo));\n\tif (tool === \"fd\" && plat === \"darwin\" && architecture === \"x64\") {\n\t\tversion = \"10.3.0\";\n\t}\n\n\t// Get asset name for this platform\n\tconst assetName = config.getAssetName(version, plat, architecture);\n\tif (!assetName) {\n\t\tthrow new Error(`Unsupported platform: ${plat}/${architecture}`);\n\t}\n\n\t// Create tools directory\n\tmkdirSync(TOOLS_DIR, { recursive: true });\n\n\tconst downloadUrl = `https://github.com/${config.repo}/releases/download/${config.tagPrefix}${version}/${assetName}`;\n\tconst downloadWorkDir = getProcessWorkRun(getAgentDir(), \"downloads\", \"tools\").path;\n\tconst archivePath = join(downloadWorkDir, assetName);\n\tconst binaryExt = plat === \"win32\" ? \".exe\" : \"\";\n\tconst binaryPath = join(TOOLS_DIR, config.binaryName + binaryExt);\n\n\t// Download and verify pinned artifacts before extraction.\n\tawait downloadFile(downloadUrl, archivePath);\n\tconst expectedSha256 = config.sha256ByAsset?.[assetName];\n\tif (config.sha256ByAsset && !expectedSha256) {\n\t\tthrow new Error(`No pinned SHA-256 is registered for ${assetName}`);\n\t}\n\tif (expectedSha256 && !(await verifyFileSha256(archivePath, expectedSha256))) {\n\t\tthrow new Error(`SHA-256 verification failed for ${assetName}`);\n\t}\n\n\tif (config.downloadKind === \"binary\") {\n\t\ttry {\n\t\t\tinstallStandaloneBinaryAsset(archivePath, binaryPath, plat);\n\t\t} finally {\n\t\t\trmSync(archivePath, { force: true });\n\t\t}\n\t\treturn binaryPath;\n\t}\n\n\t// Extract into a unique temp directory. Tool downloads can run concurrently\n\t// during startup, so sharing a fixed directory causes races.\n\tconst extractDir = join(\n\t\tdownloadWorkDir,\n\t\t`extract-${config.binaryName}-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`,\n\t);\n\tmkdirSync(extractDir, { recursive: true });\n\n\ttry {\n\t\tif (assetName.endsWith(\".tar.gz\")) {\n\t\t\textractTarGzArchive(archivePath, extractDir, assetName);\n\t\t} else if (assetName.endsWith(\".zip\")) {\n\t\t\textractZipArchive(archivePath, extractDir, assetName);\n\t\t} else {\n\t\t\tthrow new Error(`Unsupported archive format: ${assetName}`);\n\t\t}\n\n\t\t// Find the binary in extracted files. Some archives contain files directly\n\t\t// at root, others nest under a versioned subdirectory.\n\t\tconst binaryFileName = config.binaryName + binaryExt;\n\t\tconst extractedDir = join(extractDir, assetName.replace(/\\.(tar\\.gz|zip)$/, \"\"));\n\t\tconst extractedBinaryCandidates = [join(extractedDir, binaryFileName), join(extractDir, binaryFileName)];\n\t\tlet extractedBinary = extractedBinaryCandidates.find((candidate) => existsSync(candidate));\n\n\t\tif (!extractedBinary) {\n\t\t\textractedBinary = findBinaryRecursively(extractDir, binaryFileName) ?? undefined;\n\t\t}\n\n\t\tif (extractedBinary) {\n\t\t\trenameSync(extractedBinary, binaryPath);\n\t\t} else {\n\t\t\tthrow new Error(`Binary not found in archive: expected ${binaryFileName} under ${extractDir}`);\n\t\t}\n\n\t\t// Make executable (Unix only)\n\t\tif (plat !== \"win32\") {\n\t\t\tchmodSync(binaryPath, 0o755);\n\t\t}\n\t} finally {\n\t\t// Cleanup\n\t\trmSync(archivePath, { force: true });\n\t\trmSync(extractDir, { recursive: true, force: true });\n\t}\n\n\treturn binaryPath;\n}\n\n// Termux package names for tools\nconst TERMUX_PACKAGES: Record<ManagedToolName, string> = {\n\tfd: \"fd\",\n\tjq: \"jq\",\n\trg: \"ripgrep\",\n\tuv: \"uv\",\n};\n\nconst FFF_PLATFORM_PACKAGES: Record<string, string> = {\n\t\"darwin/arm64\": \"@ff-labs/fff-bin-darwin-arm64\",\n\t\"darwin/x64\": \"@ff-labs/fff-bin-darwin-x64\",\n\t\"linux/arm64/glibc\": \"@ff-labs/fff-bin-linux-arm64-gnu\",\n\t\"linux/arm64/musl\": \"@ff-labs/fff-bin-linux-arm64-musl\",\n\t\"linux/x64/glibc\": \"@ff-labs/fff-bin-linux-x64-gnu\",\n\t\"linux/x64/musl\": \"@ff-labs/fff-bin-linux-x64-musl\",\n\t\"win32/arm64\": \"@ff-labs/fff-bin-win32-arm64\",\n\t\"win32/x64\": \"@ff-labs/fff-bin-win32-x64\",\n};\n\nlet fffNodeInstallPromise: Promise<unknown | undefined> | undefined;\n\nfunction detectLinuxLibc(): \"glibc\" | \"musl\" {\n\tlet output = \"\";\n\ttry {\n\t\tconst result = spawnSync(\"ldd\", [\"--version\"], { encoding: \"utf-8\", stdio: \"pipe\", timeout: 5000 });\n\t\toutput = `${result.stdout ?? \"\"}${result.stderr ?? \"\"}`;\n\t} catch (e: unknown) {\n\t\tconst err = e as { stdout?: string | Buffer; stderr?: string | Buffer };\n\t\toutput = `${String(err.stdout ?? \"\")}${String(err.stderr ?? \"\")}`;\n\t}\n\treturn output.toLowerCase().includes(\"musl\") ? \"musl\" : \"glibc\";\n}\n\nfunction getFffPlatformPackageName(): string | undefined {\n\tconst plat = platform();\n\tconst architecture = arch();\n\tif (plat === \"linux\") {\n\t\treturn FFF_PLATFORM_PACKAGES[`${plat}/${architecture}/${detectLinuxLibc()}`];\n\t}\n\treturn FFF_PLATFORM_PACKAGES[`${plat}/${architecture}`];\n}\n\nfunction createManagedFffRequire(): ModuleRequire | undefined {\n\tif (!existsSync(FFF_MANAGED_PACKAGE_JSON)) return undefined;\n\treturn createRequire(pathToFileURL(FFF_MANAGED_PACKAGE_JSON).href);\n}\n\nfunction findFffNodeDistEntry(startPath: string): string | undefined {\n\tlet currentDir = dirname(startPath);\n\twhile (currentDir !== dirname(currentDir)) {\n\t\tconst candidate = join(currentDir, \"node_modules\", \"@ff-labs\", \"fff-node\", \"dist\", \"src\", \"index.js\");\n\t\tif (existsSync(candidate)) return candidate;\n\t\tcurrentDir = dirname(currentDir);\n\t}\n\treturn undefined;\n}\n\nfunction loadFffNodeDistEntry(requireFff: ModuleRequire): unknown | undefined {\n\tif (!requireFff.resolve) return undefined;\n\ttry {\n\t\tconst ffiPath = requireFff.resolve(\"ffi-rs\");\n\t\tconst fffEntry = findFffNodeDistEntry(ffiPath);\n\t\treturn fffEntry ? requireFff(fffEntry) : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction loadFffNodeWith(requireFff: ModuleRequire): unknown | undefined {\n\ttry {\n\t\treturn requireFff(\"@ff-labs/fff-node\");\n\t} catch {\n\t\treturn loadFffNodeDistEntry(requireFff);\n\t}\n}\n\n/**\n * @param requires Override the resolution candidates, for tests (mirrors\n * fff-search-backend.ts's loadFffModule(requires?)). Whether this resolves\n * depends on the ambient environment -- @ff-labs/fff-node is a real npm\n * dependency (package.json), so moduleRequire succeeds wherever a normal\n * `npm install`/`npm ci` provisioned it (e.g. CI) even though it fails on a\n * dev checkout that never ran that install here (this repo resolves fff-node\n * via the separate managed-dir path instead). A test asserting \"nothing is\n * available\" must pass `[]` here rather than relying on that being true.\n */\nexport function loadAvailableFffNodePackage(requires?: readonly ModuleRequire[]): unknown | undefined {\n\tconst candidates =\n\t\trequires ??\n\t\t[moduleRequire, executableDirRequire, createManagedFffRequire()].filter((candidate): candidate is ModuleRequire =>\n\t\t\tBoolean(candidate),\n\t\t);\n\tfor (const requireFff of candidates) {\n\t\tconst loaded = loadFffNodeWith(requireFff);\n\t\tif (loaded) return loaded;\n\t}\n\treturn undefined;\n}\n\nasync function runNpmInstall(args: string[]): Promise<{ code: number | null; stderr: string }> {\n\ttry {\n\t\tconst child = spawnProcess(\"npm\", args, {\n\t\t\tdetached: process.platform !== \"win32\",\n\t\t\tstdio: [\"ignore\", \"pipe\", \"pipe\"],\n\t\t});\n\t\tlet stderr = \"\";\n\t\tchild.stderr?.on(\"data\", (chunk) => {\n\t\t\tstderr = `${stderr}${chunk.toString()}`.slice(-64 * 1024);\n\t\t});\n\t\tconst terminal = await waitForChildProcessWithTermination(child, {\n\t\t\ttimeoutMs: ARCHIVE_EXTRACTION_TIMEOUT_MS,\n\t\t\tkillGraceMs: 2_000,\n\t\t});\n\t\tif (terminal.reason === \"timeout\") {\n\t\t\tstderr = `${stderr}\\nnpm install timed out after ${ARCHIVE_EXTRACTION_TIMEOUT_MS}ms`.trim();\n\t\t}\n\t\treturn { code: terminal.code, stderr };\n\t} catch (error) {\n\t\treturn { code: 1, stderr: error instanceof Error ? error.message : String(error) };\n\t}\n}\n\n/**\n * Outcome of the most recent {@link ensureFffNodePackage} call, kept for\n * observability (e.g. a future `doctor` check) since the function itself\n * only ever returns the loaded module or `undefined` either way.\n *\n * `install-failed` is distinguished from `offline`/`unsupported-platform`\n * because it is the only one worth *retrying*: offline mode and an\n * unsupported platform are stable for the life of the process, but a real\n * install attempt can fail on a transient issue (registry hiccup, timeout)\n * that may no longer apply on the next search. See\n * DefaultFffSearchBackend.getFinder in fff-search-backend.ts, which uses\n * this distinction to decide whether a failed finder is retryable.\n */\nexport type FffInstallOutcome =\n\t| { status: \"already-available\" }\n\t| { status: \"offline\" }\n\t| { status: \"unsupported-platform\" }\n\t| { status: \"installed\" }\n\t| { status: \"install-failed\"; reason: string };\n\n/**\n * How long a genuine install failure gates out a NEW npm spawn. An agent turn\n * can fire several find/grep calls in quick succession, and each one now\n * primes the finder in the background (see tryFffFind/tryFffGrep) -- without\n * this, a persistently-failing install (registry down, disk full, ...) would\n * re-spawn npm on every single one of those calls instead of once.\n *\n * This gates the SPAWN inside ensureFffNodePackage, not whether a failed\n * finder is retryable (see isFffInstallRetryable): DefaultFffSearchBackend\n * always evicts a failed finder so the next search re-enters this function,\n * and it is THIS cooldown check -- evaluated fresh, at call time -- that\n * decides whether that re-entry is a real attempt or a fast, spawn-free bail.\n * (An earlier version conflated the two: it gated eviction itself on the\n * cooldown, which is checked once, immediately after the failure it's timing\n * -- i.e. always still within the window -- so the failed finder was never\n * evicted and the retry never got a chance to happen at all.)\n */\nexport const FFF_INSTALL_RETRY_COOLDOWN_MS = 30_000;\n\nlet lastFffInstallOutcome: FffInstallOutcome | undefined;\nlet lastFffInstallFailureAt: number | undefined;\n\n/** The outcome of the last {@link ensureFffNodePackage} call, if any. */\nexport function getLastFffInstallOutcome(): FffInstallOutcome | undefined {\n\treturn lastFffInstallOutcome;\n}\n\n/** Whether the last install outcome was a genuine failure worth retrying (as opposed to a stable \"not applicable\" result). Cooldown-independent by design -- see FFF_INSTALL_RETRY_COOLDOWN_MS. */\nexport function isFffInstallRetryable(): boolean {\n\treturn lastFffInstallOutcome?.status === \"install-failed\";\n}\n\n/**\n * Pure decision logic behind {@link isFffInstallCoolingDown}, exposed directly\n * so tests can assert the cooldown boundary without faking the system clock.\n */\nexport function computeIsFffInstallCoolingDown(\n\toutcome: FffInstallOutcome | undefined,\n\tfailedAt: number | undefined,\n\tnow: number,\n): boolean {\n\tif (outcome?.status !== \"install-failed\") return false;\n\tif (failedAt === undefined) return false;\n\treturn now - failedAt < FFF_INSTALL_RETRY_COOLDOWN_MS;\n}\n\n/** Whether a real install attempt happened too recently to try again right now. */\nfunction isFffInstallCoolingDown(): boolean {\n\treturn computeIsFffInstallCoolingDown(lastFffInstallOutcome, lastFffInstallFailureAt, Date.now());\n}\n\n/** Records a genuine install failure and stamps when it happened, so the cooldown above has a start time to measure from. */\nfunction recordFffInstallFailure(reason: string): void {\n\tlastFffInstallOutcome = { status: \"install-failed\", reason };\n\tlastFffInstallFailureAt = Date.now();\n}\n\nasync function installManagedFffNodePackage(platformPackage: string, silent: boolean): Promise<unknown | undefined> {\n\ttry {\n\t\tmkdirSync(FFF_MANAGED_DIR, { recursive: true });\n\t\tif (!existsSync(FFF_MANAGED_PACKAGE_JSON)) {\n\t\t\twriteFileSync(FFF_MANAGED_PACKAGE_JSON, '{\"name\":\"pi-managed-fff-node\",\"private\":true,\"version\":\"0.0.0\"}\\n');\n\t\t}\n\n\t\tif (!silent) {\n\t\t\tconsole.log(chalk.dim(\"FFF native search not found. Installing managed FFF package...\"));\n\t\t}\n\n\t\tconst args = [\n\t\t\t\"install\",\n\t\t\t\"--ignore-scripts\",\n\t\t\t\"--omit=dev\",\n\t\t\t\"--include=optional\",\n\t\t\t\"--no-audit\",\n\t\t\t\"--no-fund\",\n\t\t\t\"--package-lock=false\",\n\t\t\t\"--prefix\",\n\t\t\tFFF_MANAGED_DIR,\n\t\t\t`@ff-labs/fff-node@${FFF_NODE_VERSION}`,\n\t\t\t`${platformPackage}@${FFF_NODE_VERSION}`,\n\t\t];\n\t\tconst result = await runNpmInstall(args);\n\t\tif (result.code !== 0) {\n\t\t\tconst reason = result.stderr.trim() || `npm exited with code ${result.code}`;\n\t\t\tif (!silent) {\n\t\t\t\tconsole.log(chalk.yellow(`Failed to install FFF native search: ${reason}`));\n\t\t\t}\n\t\t\trecordFffInstallFailure(reason);\n\t\t\treturn undefined;\n\t\t}\n\t\tconst loaded = loadFffNodeWith(createRequire(pathToFileURL(FFF_MANAGED_PACKAGE_JSON).href));\n\t\tif (!loaded) {\n\t\t\tconst reason = \"Managed FFF install completed but @ff-labs/fff-node could not be loaded.\";\n\t\t\tif (!silent) {\n\t\t\t\tconsole.log(chalk.yellow(reason));\n\t\t\t}\n\t\t\trecordFffInstallFailure(reason);\n\t\t\treturn undefined;\n\t\t}\n\t\tlastFffInstallOutcome = { status: \"installed\" };\n\t\treturn loaded;\n\t} catch (error) {\n\t\t// Never let a filesystem/spawn surprise (e.g. a read-only home directory)\n\t\t// crash the caller: fall back like any other install failure, but keep\n\t\t// the reason observable.\n\t\tconst reason = error instanceof Error ? error.message : String(error);\n\t\tif (!silent) {\n\t\t\tconsole.log(chalk.yellow(`Failed to install FFF native search: ${reason}`));\n\t\t}\n\t\trecordFffInstallFailure(reason);\n\t\treturn undefined;\n\t}\n}\n\nexport async function ensureFffNodePackage(\n\tsilent: boolean = false,\n\tforceManagedInstall: boolean = false,\n\t/** Override the \"is it already available\" resolution candidates, for tests. See loadAvailableFffNodePackage's doc. */\n\trequires?: readonly ModuleRequire[],\n): Promise<unknown | undefined> {\n\tconst existing = forceManagedInstall ? undefined : loadAvailableFffNodePackage(requires);\n\tif (existing) {\n\t\tlastFffInstallOutcome = { status: \"already-available\" };\n\t\treturn existing;\n\t}\n\n\tif (isOfflineModeEnabled()) {\n\t\tif (!silent) {\n\t\t\tconsole.log(chalk.yellow(\"FFF native search not found. Offline mode enabled, skipping install.\"));\n\t\t}\n\t\tlastFffInstallOutcome = { status: \"offline\" };\n\t\treturn undefined;\n\t}\n\n\t// A prior attempt failed too recently to try again: bail out fast (no npm\n\t// spawn, no platform/libc probing) rather than repeating a doomed attempt.\n\t// Leaves lastFffInstallOutcome/lastFffInstallFailureAt untouched -- this\n\t// isn't a new attempt, so there's nothing new to record.\n\tif (isFffInstallCoolingDown()) {\n\t\treturn undefined;\n\t}\n\n\tconst platformPackage = getFffPlatformPackageName();\n\tif (!platformPackage) {\n\t\tif (!silent) {\n\t\t\tconsole.log(chalk.yellow(`FFF native search is not available for ${platform()}/${arch()}.`));\n\t\t}\n\t\tlastFffInstallOutcome = { status: \"unsupported-platform\" };\n\t\treturn undefined;\n\t}\n\n\tfffNodeInstallPromise ??= installManagedFffNodePackage(platformPackage, silent).finally(() => {\n\t\tfffNodeInstallPromise = undefined;\n\t});\n\treturn fffNodeInstallPromise;\n}\n\nasync function installTermuxManagedTool(tool: ManagedToolName, silent: boolean): Promise<string | undefined> {\n\tconst packageName = TERMUX_PACKAGES[tool];\n\tif (!silent) console.log(chalk.dim(`${TOOLS[tool].name} not found. Installing with Termux pkg...`));\n\tconst child = spawnProcess(\"pkg\", [\"install\", \"-y\", packageName], {\n\t\tenv: process.env,\n\t\tstdio: silent ? \"ignore\" : \"inherit\",\n\t});\n\tconst terminal = await waitForChildProcessWithTermination(child, { timeoutMs: 300_000, killGraceMs: 5_000 });\n\tif (terminal.reason !== \"exited\" || terminal.code !== 0) {\n\t\tthrow new Error(\n\t\t\t`pkg install ${packageName} ${terminal.reason === \"timeout\" ? \"timed out\" : `exited with code ${terminal.code ?? 1}`}`,\n\t\t);\n\t}\n\treturn getToolPath(tool) ?? undefined;\n}\n\n// Ensure a tool is available, downloading if necessary\n// Returns the path to the tool, or undefined if unavailable\nexport async function ensureTool(tool: ManagedToolName, silent: boolean = false): Promise<string | undefined> {\n\tconst existingPath = getToolPath(tool);\n\tif (existingPath) {\n\t\treturn existingPath;\n\t}\n\n\tconst config = TOOLS[tool];\n\tif (!config) return undefined;\n\n\tif (isOfflineModeEnabled()) {\n\t\tif (!silent) {\n\t\t\tconsole.log(chalk.yellow(`${config.name} not found. Offline mode enabled, skipping download.`));\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t// On Android/Termux, upstream Linux archives target glibc/musl rather than Bionic.\n\t// uv is a required managed runtime and the user explicitly authorized provisioning it;\n\t// preserve guide-only behavior for optional search tools.\n\tif (platform() === \"android\") {\n\t\tif (tool !== \"uv\") {\n\t\t\tconst packageName = TERMUX_PACKAGES[tool];\n\t\t\tif (!silent) console.log(chalk.yellow(`${config.name} not found. Install with: pkg install ${packageName}`));\n\t\t\treturn undefined;\n\t\t}\n\t\ttry {\n\t\t\treturn await runExclusiveToolDownload(tool, () => installTermuxManagedTool(tool, silent));\n\t\t} catch (error) {\n\t\t\tif (!silent) {\n\t\t\t\tconsole.log(\n\t\t\t\t\tchalk.yellow(`Failed to install ${config.name}: ${error instanceof Error ? error.message : error}`),\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn undefined;\n\t\t}\n\t}\n\n\t// Tool not found - download it\n\tif (!silent) {\n\t\tconsole.log(chalk.dim(`${config.name} not found. Downloading...`));\n\t}\n\n\ttry {\n\t\tconst path = await runExclusiveToolDownload(tool, () => downloadTool(tool));\n\t\tif (!silent) {\n\t\t\tconsole.log(chalk.dim(`${config.name} installed to ${path}`));\n\t\t}\n\t\treturn path;\n\t} catch (e) {\n\t\tif (!silent) {\n\t\t\tconsole.log(chalk.yellow(`Failed to download ${config.name}: ${e instanceof Error ? e.message : e}`));\n\t\t}\n\t\treturn undefined;\n\t}\n}\n"]}
1
+ {"version":3,"file":"tools-manager.js","sourceRoot":"","sources":["../../src/utils/tools-manager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAyB,SAAS,EAAE,MAAM,eAAe,CAAC;AACjE,OAAO,EACN,UAAU,EACV,SAAS,EACT,gBAAgB,EAChB,iBAAiB,EACjB,UAAU,EACV,SAAS,IAAI,WAAW,EACxB,SAAS,EACT,WAAW,EACX,YAAY,EACZ,UAAU,EACV,MAAM,EACN,QAAQ,EACR,aAAa,GACb,MAAM,IAAI,CAAC;AACZ,OAAO,EAAE,aAAa,EAAE,MAAM,QAAQ,CAAC;AACvC,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,IAAI,CAAC;AACpC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AACrC,OAAO,EAAE,QAAQ,EAAE,MAAM,QAAQ,CAAC;AAClC,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,aAAa,EAAE,MAAM,KAAK,CAAC;AACpC,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAChE,OAAO,EAAE,QAAQ,IAAI,aAAa,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AAC9E,OAAO,EAAE,kBAAkB,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;A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,CAAC,GAAG,MAAM,CAAC,IAAI,iBAAiB,IAAI,EAAE,CAAC,CAAC,CAAC;QAC/D,CAAC;QACD,OAAO,IAAI,CAAC;IACb,CAAC;IAAC,OAAO,CAAC,EAAE,CAAC;QACZ,IAAI,CAAC,MAAM,EAAE,CAAC;YACb,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,MAAM,CAAC,sBAAsB,MAAM,CAAC,IAAI,KAAK,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;QACvG,CAAC;QACD,OAAO,SAAS,CAAC;IAClB,CAAC;AACF,CAAC","sourcesContent":["import { createHash } from \"node:crypto\";\nimport chalk from \"chalk\";\nimport { type SpawnSyncReturns, spawnSync } from \"child_process\";\nimport {\n\taccessSync,\n\tchmodSync,\n\tcreateReadStream,\n\tcreateWriteStream,\n\texistsSync,\n\tconstants as fsConstants,\n\tmkdirSync,\n\treaddirSync,\n\treadFileSync,\n\trenameSync,\n\trmSync,\n\tstatSync,\n\twriteFileSync,\n} from \"fs\";\nimport { createRequire } from \"module\";\nimport { arch, platform } from \"os\";\nimport { dirname, join } from \"path\";\nimport { Readable } from \"stream\";\nimport { pipeline } from \"stream/promises\";\nimport { pathToFileURL } from \"url\";\nimport { APP_NAME, getAgentDir, getBinDir } from \"../config.ts\";\nimport { cacheDir as agentCacheDir, cacheFile } from \"../core/agent-paths.ts\";\nimport { ensureManagedJscpd, JSCPD_VERSION } from \"./bundled-jscpd.ts\";\nimport { spawnProcess, waitForChildProcessWithTermination } from \"./child-process.ts\";\nimport { getProcessWorkRun } from \"./work-directory.ts\";\n\nconst TOOLS_DIR = getBinDir();\nconst NETWORK_TIMEOUT_MS = 10_000;\nconst DOWNLOAD_TIMEOUT_MS = 120_000;\nconst COMMAND_PROBE_TIMEOUT_MS = 5_000;\nconst ARCHIVE_EXTRACTION_TIMEOUT_MS = 5 * 60_000;\nconst FFF_NODE_VERSION = \"0.9.6\";\nexport const RG_VERSION = \"15.2.0\";\nexport const JQ_VERSION = \"1.8.2\";\nexport const UV_VERSION = \"0.11.28\";\nconst FFF_MANAGED_DIR = join(TOOLS_DIR, \"fff-node\");\nconst FFF_MANAGED_PACKAGE_JSON = join(FFF_MANAGED_DIR, \"package.json\");\n\ntype ModuleRequire = ((id: string) => unknown) & { resolve?: (id: string) => string };\n\nconst moduleRequire = createRequire(import.meta.url);\nconst executableDirRequire = createRequire(pathToFileURL(join(dirname(process.execPath), \"package.json\")).href);\n\nfunction isOfflineModeEnabled(): boolean {\n\tconst value = process.env.PI_OFFLINE;\n\tif (!value) return false;\n\treturn value === \"1\" || value.toLowerCase() === \"true\" || value.toLowerCase() === \"yes\";\n}\n\ninterface ToolConfig {\n\tname: string;\n\trepo: string; // GitHub repo (e.g., \"sharkdp/fd\")\n\tbinaryName: string; // Name of the binary inside the archive\n\tsystemBinaryNames?: string[]; // Alternative system command names to try before downloading\n\ttagPrefix: string; // Prefix for tags (e.g., \"v\" for v1.0.0, \"\" for 1.0.0)\n\tgetAssetName: (version: string, plat: string, architecture: string) => string | null;\n\tdownloadKind?: \"archive\" | \"binary\";\n\tpinnedVersion?: string;\n\tsha256ByAsset?: Readonly<Record<string, string>>;\n}\n\nconst TOOLS: Record<\"fd\" | \"jq\" | \"jscpd\" | \"rg\" | \"uv\", ToolConfig> = {\n\tfd: {\n\t\tname: \"fd\",\n\t\trepo: \"sharkdp/fd\",\n\t\tbinaryName: \"fd\",\n\t\tsystemBinaryNames: [\"fd\", \"fdfind\"],\n\t\ttagPrefix: \"v\",\n\t\tgetAssetName: (version, plat, architecture) => {\n\t\t\tif (plat === \"darwin\") {\n\t\t\t\tconst archStr = architecture === \"arm64\" ? \"aarch64\" : \"x86_64\";\n\t\t\t\treturn `fd-v${version}-${archStr}-apple-darwin.tar.gz`;\n\t\t\t} else if (plat === \"linux\") {\n\t\t\t\tconst archStr = architecture === \"arm64\" ? \"aarch64\" : \"x86_64\";\n\t\t\t\treturn `fd-v${version}-${archStr}-unknown-linux-gnu.tar.gz`;\n\t\t\t} else if (plat === \"win32\") {\n\t\t\t\tconst archStr = architecture === \"arm64\" ? \"aarch64\" : \"x86_64\";\n\t\t\t\treturn `fd-v${version}-${archStr}-pc-windows-msvc.zip`;\n\t\t\t}\n\t\t\treturn null;\n\t\t},\n\t},\n\trg: {\n\t\tname: \"ripgrep\",\n\t\trepo: \"BurntSushi/ripgrep\",\n\t\tbinaryName: \"rg\",\n\t\ttagPrefix: \"\",\n\t\tpinnedVersion: RG_VERSION,\n\t\tgetAssetName: (version, plat, architecture) => {\n\t\t\tif (plat === \"darwin\") {\n\t\t\t\tconst archStr = architecture === \"arm64\" ? \"aarch64\" : \"x86_64\";\n\t\t\t\treturn `ripgrep-${version}-${archStr}-apple-darwin.tar.gz`;\n\t\t\t} else if (plat === \"linux\") {\n\t\t\t\tif (architecture === \"arm64\") {\n\t\t\t\t\treturn `ripgrep-${version}-aarch64-unknown-linux-gnu.tar.gz`;\n\t\t\t\t}\n\t\t\t\treturn `ripgrep-${version}-x86_64-unknown-linux-musl.tar.gz`;\n\t\t\t} else if (plat === \"win32\") {\n\t\t\t\tconst archStr = architecture === \"arm64\" ? \"aarch64\" : \"x86_64\";\n\t\t\t\treturn `ripgrep-${version}-${archStr}-pc-windows-msvc.zip`;\n\t\t\t}\n\t\t\treturn null;\n\t\t},\n\t\tsha256ByAsset: {\n\t\t\t\"ripgrep-15.2.0-aarch64-apple-darwin.tar.gz\":\n\t\t\t\t\"3750b2e93f37e0c692657da574d7019a101c0084da05a790c83fd335bad973e4\",\n\t\t\t\"ripgrep-15.2.0-aarch64-pc-windows-msvc.zip\":\n\t\t\t\t\"e4abca10c3a64ebea742667dd7009449d49403db5460dd6873e389fa2945360f\",\n\t\t\t\"ripgrep-15.2.0-aarch64-unknown-linux-gnu.tar.gz\":\n\t\t\t\t\"a740b91c82eaf9914cfedd353572f2791cbe0162c84101ee0951058f4dcbc90d\",\n\t\t\t\"ripgrep-15.2.0-x86_64-apple-darwin.tar.gz\":\n\t\t\t\t\"af7825fcc69a2afc7a7aea55fc9af90e26421d8f20fe59df32e233c0b8a231c1\",\n\t\t\t\"ripgrep-15.2.0-x86_64-pc-windows-msvc.zip\":\n\t\t\t\t\"71b2fef860abe467217a538ff31de02f5258807c0129f771846f87bd029aafc5\",\n\t\t\t\"ripgrep-15.2.0-x86_64-unknown-linux-musl.tar.gz\":\n\t\t\t\t\"33e15bcf1624b25cdd2a55813a47a2f95dbe126268203e76aa6a585d1e7b149c\",\n\t\t},\n\t},\n\tjq: {\n\t\tname: \"jq\",\n\t\trepo: \"jqlang/jq\",\n\t\tbinaryName: \"jq\",\n\t\tsystemBinaryNames: [\"jq\"],\n\t\ttagPrefix: \"jq-\",\n\t\tdownloadKind: \"binary\",\n\t\tpinnedVersion: JQ_VERSION,\n\t\tgetAssetName: (_version, plat, architecture) => {\n\t\t\tif (architecture !== \"arm64\" && architecture !== \"x64\") return null;\n\t\t\tconst archStr = architecture === \"arm64\" ? \"arm64\" : \"amd64\";\n\t\t\tif (plat === \"darwin\") return `jq-macos-${archStr}`;\n\t\t\tif (plat === \"linux\") return `jq-linux-${archStr}`;\n\t\t\tif (plat === \"win32\") return `jq-windows-${archStr}.exe`;\n\t\t\treturn null;\n\t\t},\n\t\tsha256ByAsset: {\n\t\t\t\"jq-linux-amd64\": \"b1c22172dd303f3be49e935aa56aa48a8b7a46e0bc838b4997d3bb451495870f\",\n\t\t\t\"jq-linux-arm64\": \"8b85c817833814ddca00a144c33705546355afccf0cf39b188f3cdb48b852309\",\n\t\t\t\"jq-macos-amd64\": \"e94b266e3c26690550006abe63152b782280f4e14374accdf04cbde844f00bc0\",\n\t\t\t\"jq-macos-arm64\": \"2d75340ba57a4b4b4c8708a21c2dc8e958a48aaa8bba13b27f77f6e4c0eca07e\",\n\t\t\t\"jq-windows-amd64.exe\": \"a6fc67fedaf9128a3309a1e2ebb8b986aeccf70122ee46d2cb4849e423f0c627\",\n\t\t\t\"jq-windows-arm64.exe\": \"083b5377392bc57cf27052b6d20a2d927770683bca844632901ff38b4b7b0ac7\",\n\t\t},\n\t},\n\tjscpd: {\n\t\tname: \"jscpd\",\n\t\trepo: \"\",\n\t\tbinaryName: \"jscpd\",\n\t\tsystemBinaryNames: [],\n\t\ttagPrefix: \"\",\n\t\tpinnedVersion: JSCPD_VERSION,\n\t\tgetAssetName: () => null,\n\t},\n\tuv: {\n\t\tname: \"uv\",\n\t\trepo: \"astral-sh/uv\",\n\t\tbinaryName: \"uv\",\n\t\tsystemBinaryNames: [\"uv\"],\n\t\ttagPrefix: \"\",\n\t\tpinnedVersion: UV_VERSION,\n\t\tgetAssetName: (_version, plat, architecture) => {\n\t\t\tif (architecture !== \"arm64\" && architecture !== \"x64\") return null;\n\t\t\tconst archStr = architecture === \"arm64\" ? \"aarch64\" : \"x86_64\";\n\t\t\tif (plat === \"darwin\") return `uv-${archStr}-apple-darwin.tar.gz`;\n\t\t\tif (plat === \"linux\") return `uv-${archStr}-unknown-linux-musl.tar.gz`;\n\t\t\tif (plat === \"win32\") return `uv-${archStr}-pc-windows-msvc.zip`;\n\t\t\treturn null;\n\t\t},\n\t\tsha256ByAsset: {\n\t\t\t\"uv-aarch64-apple-darwin.tar.gz\": \"33540eb7c883ab857eff79bd5ac2aa31fe27b595abecb4a9c003a2c998447232\",\n\t\t\t\"uv-aarch64-pc-windows-msvc.zip\": \"3248109afad3ec59baad299d324ff53de17e2d9a3b3e21580ffd26744b11e036\",\n\t\t\t\"uv-aarch64-unknown-linux-musl.tar.gz\": \"da10cdfa7d92212b7acb62021a0fd61bcf8580c58c3632ec915d10c3a1a7906b\",\n\t\t\t\"uv-x86_64-apple-darwin.tar.gz\": \"2ad79983127ffca7d77b77ce6a24278d7e4f7b817a1acf72fea5f8124b4aac5e\",\n\t\t\t\"uv-x86_64-pc-windows-msvc.zip\": \"0a23463216d09c6a72ff80ef5dc5a795f07dc1575cb84d24596c2f124a441b7b\",\n\t\t\t\"uv-x86_64-unknown-linux-musl.tar.gz\": \"f02146b371c35c287d860f003ece7345c86e358a3fd70a9b63700cd141ee7fb4\",\n\t\t},\n\t},\n};\n\nexport type ManagedToolName = keyof typeof TOOLS;\n\nexport interface PinnedToolAsset {\n\tversion: string;\n\tassetName: string;\n\texpectedSha256: string;\n}\n\nexport function getPinnedToolAsset(\n\ttool: ManagedToolName,\n\ttargetPlatform: string = platform(),\n\ttargetArchitecture: string = arch(),\n): PinnedToolAsset | null {\n\tconst config: ToolConfig = TOOLS[tool];\n\tif (!config.pinnedVersion || !config.sha256ByAsset) return null;\n\tconst assetName = config.getAssetName(config.pinnedVersion, targetPlatform, targetArchitecture);\n\tif (!assetName) return null;\n\tconst expectedSha256 = config.sha256ByAsset[assetName];\n\treturn expectedSha256 ? { version: config.pinnedVersion, assetName, expectedSha256 } : null;\n}\n\n// Check if a command exists in PATH by trying to run it\nfunction commandExists(cmd: string): boolean {\n\ttry {\n\t\tconst result = spawnSync(cmd, [\"--version\"], { stdio: \"pipe\", timeout: COMMAND_PROBE_TIMEOUT_MS });\n\t\t// Check for ENOENT error (command not found)\n\t\treturn result.error === undefined || result.error === null;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\ninterface CachedToolPath {\n\tpath: string;\n\tmtimeMs: number;\n}\n\nfunction isCachedToolPath(value: unknown): value is CachedToolPath {\n\tif (typeof value !== \"object\" || value === null) return false;\n\tconst candidate = value as Record<string, unknown>;\n\treturn typeof candidate.path === \"string\" && typeof candidate.mtimeMs === \"number\";\n}\n\nfunction getToolPathCacheFile(): string {\n\treturn cacheFile(getAgentDir(), \"tool-paths.json\");\n}\n\n/** Read the persisted cross-run tool-path cache. Missing/corrupt/foreign entries are dropped silently -- a cold cache just means the next resolve re-probes and repopulates it. */\nfunction readToolPathCache(): Partial<Record<ManagedToolName, CachedToolPath>> {\n\ttry {\n\t\tconst raw = readFileSync(getToolPathCacheFile(), \"utf-8\");\n\t\tconst parsed = JSON.parse(raw) as Record<string, unknown>;\n\t\tconst cache: Partial<Record<ManagedToolName, CachedToolPath>> = {};\n\t\tfor (const tool of Object.keys(TOOLS) as ManagedToolName[]) {\n\t\t\tconst entry = parsed[tool];\n\t\t\tif (isCachedToolPath(entry)) cache[tool] = entry;\n\t\t}\n\t\treturn cache;\n\t} catch {\n\t\treturn {};\n\t}\n}\n\nfunction writeToolPathCacheEntry(tool: ManagedToolName, entry: CachedToolPath): void {\n\ttry {\n\t\tconst cacheDir = agentCacheDir(getAgentDir());\n\t\tmkdirSync(cacheDir, { recursive: true });\n\t\tconst cache = readToolPathCache();\n\t\tcache[tool] = entry;\n\t\twriteFileSync(join(cacheDir, \"tool-paths.json\"), JSON.stringify(cache));\n\t} catch {\n\t\t// Best-effort: a failed cache write only costs the next run its probe, same as a cold cache.\n\t}\n}\n\n/** A cached entry is fresh only while its file still exists at the same path with the same mtime -- a deleted/moved/replaced binary invalidates it and forces a re-probe below. */\nfunction isCachedToolPathFresh(entry: CachedToolPath): boolean {\n\ttry {\n\t\treturn statSync(entry.path).mtimeMs === entry.mtimeMs;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction getPathExtensionCandidates(): readonly string[] {\n\tif (platform() !== \"win32\") return [\"\"];\n\tconst pathExt = process.env.PATHEXT || \".COM;.EXE;.BAT;.CMD\";\n\treturn [\"\", ...pathExt.split(\";\").filter(Boolean)];\n}\n\n/**\n * Manually walk PATH to turn a bare command name that commandExists() already confirmed is\n * runnable into an absolute, stat-checkable path. This never decides presence itself (that stays\n * commandExists's job via spawnSync, unchanged) -- it only supplies the path the cross-run cache\n * needs for its mtime staleness check, using stat calls instead of another spawn.\n */\nfunction resolveOnSystemPath(binaryName: string): string | null {\n\tconst pathEnv = process.env.PATH ?? \"\";\n\tconst dirs = pathEnv.split(platform() === \"win32\" ? \";\" : \":\").filter(Boolean);\n\tfor (const dir of dirs) {\n\t\tfor (const ext of getPathExtensionCandidates()) {\n\t\t\tconst candidate = join(dir, binaryName + ext);\n\t\t\tif (!existsSync(candidate)) continue;\n\t\t\ttry {\n\t\t\t\tif (statSync(candidate).isDirectory()) continue;\n\t\t\t\tif (platform() !== \"win32\") accessSync(candidate, fsConstants.X_OK);\n\t\t\t} catch {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\treturn candidate;\n\t\t}\n\t}\n\treturn null;\n}\n\nfunction cacheResolvedSystemPath(tool: ManagedToolName, resolvedPath: string): void {\n\ttry {\n\t\twriteToolPathCacheEntry(tool, { path: resolvedPath, mtimeMs: statSync(resolvedPath).mtimeMs });\n\t} catch {\n\t\t// Stat raced with a delete between resolve and here: nothing to cache, still return the path below.\n\t}\n}\n\n// Get the path to a tool (system-wide or in our tools dir)\nexport function getToolPath(tool: ManagedToolName): string | null {\n\tconst config = TOOLS[tool];\n\tif (!config) return null;\n\n\t// Check our tools directory first\n\tconst localPath = join(TOOLS_DIR, config.binaryName + (platform() === \"win32\" ? \".exe\" : \"\"));\n\tif (existsSync(localPath)) {\n\t\treturn localPath;\n\t}\n\n\t// Check system PATH - if found, just return the command name (it's in PATH)\n\tconst systemBinaryNames = config.systemBinaryNames ?? [config.binaryName];\n\n\t// A system-PATH resolution normally requires commandExists's synchronous\n\t// spawnSync(`<name> --version`) probe below, which is expensive to pay on every process\n\t// startup (this runs once per tool at interactive-mode init, plus again on the first\n\t// find/grep tool call). Persist the resolved absolute path + mtime across runs\n\t// (<agentDir>/cache/tool-paths.json) so a warm run can skip the probe entirely and just\n\t// stat the cached path instead. KNOWN LIMITATION: if a *different* binary of the same name\n\t// starts shadowing the cached one earlier on PATH (e.g. a new install) while the\n\t// originally-cached file itself is untouched, this cache keeps returning the old path until\n\t// that file is deleted/modified -- an intentional narrow staleness window (the returned tool\n\t// still exists and runs; it just isn't the newly-shadowing one), not a correctness bug.\n\tconst cached = readToolPathCache()[tool];\n\tif (cached && isCachedToolPathFresh(cached)) {\n\t\treturn cached.path;\n\t}\n\n\tfor (const systemBinaryName of systemBinaryNames) {\n\t\tif (commandExists(systemBinaryName)) {\n\t\t\tconst resolved = resolveOnSystemPath(systemBinaryName);\n\t\t\tif (resolved) {\n\t\t\t\tcacheResolvedSystemPath(tool, resolved);\n\t\t\t\treturn resolved;\n\t\t\t}\n\t\t\t// Could not resolve an absolute path to cache (e.g. PATH env raced between the two\n\t\t\t// lookups); still return the bare name so the caller keeps working, uncached.\n\t\t\treturn systemBinaryName;\n\t\t}\n\t}\n\n\treturn null;\n}\n\n/** Presence check for a SYSTEM tool the doctor only ever reports on -- never installs. */\nexport interface SystemToolStatus {\n\tpresent: boolean;\n\tcommand?: string;\n\tversion?: string;\n}\n\nconst PYTHON_COMMANDS = [\"python3\", \"python\"];\n\n/**\n * Detect a usable Python interpreter. SYSTEM tool (see src/core/doctor.ts):\n * the doctor reports presence/version, it never installs this itself.\n *\n * @param commands Override the candidate command names, for tests.\n */\nexport function detectPython(commands: readonly string[] = PYTHON_COMMANDS): SystemToolStatus {\n\tfor (const command of commands) {\n\t\ttry {\n\t\t\tconst result = spawnSync(command, [\"--version\"], { encoding: \"utf-8\", stdio: \"pipe\", timeout: 5_000 });\n\t\t\tif (result.error) continue;\n\t\t\t// Python 2 prints its version to stderr; Python 3 prints to stdout. Some\n\t\t\t// platforms' `python` alias is one or the other, so check both.\n\t\t\tconst version = `${result.stdout ?? \"\"}${result.stderr ?? \"\"}`.trim() || undefined;\n\t\t\tif (result.status !== 0 && !version) continue;\n\t\t\treturn { present: true, command, version };\n\t\t} catch {\n\t\t\t// Try the next candidate.\n\t\t}\n\t}\n\treturn { present: false };\n}\n\n/**\n * Runs `<command> --version` (or `versionArgs`) and returns its trimmed\n * combined stdout+stderr, or undefined if the command can't be run. Used by\n * the doctor (src/core/doctor.ts) to show a version alongside a tool it has\n * already located by some other means (e.g. getToolPath(\"rg\"), or the binary\n * path OllamaRuntime.detect() reports) -- callers that only need a yes/no\n * presence check should use commandExists/getToolPath/detectPython instead.\n */\nexport function probeVersion(command: string, versionArgs: readonly string[] = [\"--version\"]): string | undefined {\n\ttry {\n\t\tconst result = spawnSync(command, versionArgs, { encoding: \"utf-8\", stdio: \"pipe\", timeout: 5_000 });\n\t\tif (result.error) return undefined;\n\t\tconst output = `${result.stdout ?? \"\"}${result.stderr ?? \"\"}`.trim();\n\t\treturn output || undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n// Fetch latest release version from GitHub\nasync function getLatestVersion(repo: string): Promise<string> {\n\tconst response = await fetch(`https://api.github.com/repos/${repo}/releases/latest`, {\n\t\theaders: { \"User-Agent\": `${APP_NAME}-coding-agent` },\n\t\tsignal: AbortSignal.timeout(NETWORK_TIMEOUT_MS),\n\t});\n\n\tif (!response.ok) {\n\t\tthrow new Error(`GitHub API error: ${response.status}`);\n\t}\n\n\tconst data = (await response.json()) as { tag_name: string };\n\treturn data.tag_name.replace(/^v/, \"\");\n}\n\n// Download a file from URL\nasync function downloadFile(url: string, dest: string): Promise<void> {\n\tconst response = await fetch(url, {\n\t\tsignal: AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS),\n\t});\n\n\tif (!response.ok) {\n\t\tthrow new Error(`Failed to download: ${response.status}`);\n\t}\n\n\tif (!response.body) {\n\t\tthrow new Error(\"No response body\");\n\t}\n\n\tconst fileStream = createWriteStream(dest);\n\tawait pipeline(Readable.fromWeb(response.body as any), fileStream);\n}\n\nexport async function verifyFileSha256(filePath: string, expectedSha256: string): Promise<boolean> {\n\tconst hash = createHash(\"sha256\");\n\tawait new Promise<void>((resolve, reject) => {\n\t\tconst stream = createReadStream(filePath);\n\t\tstream.on(\"data\", (chunk) => hash.update(chunk));\n\t\tstream.once(\"error\", reject);\n\t\tstream.once(\"end\", resolve);\n\t});\n\treturn hash.digest(\"hex\") === expectedSha256.toLowerCase();\n}\n\nfunction findBinaryRecursively(rootDir: string, binaryFileName: string): string | null {\n\tconst stack: string[] = [rootDir];\n\n\twhile (stack.length > 0) {\n\t\tconst currentDir = stack.pop();\n\t\tif (!currentDir) continue;\n\n\t\tconst entries = readdirSync(currentDir, { withFileTypes: true });\n\t\tfor (const entry of entries) {\n\t\t\tconst fullPath = join(currentDir, entry.name);\n\t\t\tif (entry.isFile() && entry.name === binaryFileName) {\n\t\t\t\treturn fullPath;\n\t\t\t}\n\t\t\tif (entry.isDirectory()) {\n\t\t\t\tstack.push(fullPath);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn null;\n}\n\nfunction formatSpawnFailure(result: SpawnSyncReturns<Buffer>): string {\n\tif (result.error?.message) {\n\t\treturn result.error.message;\n\t}\n\tconst stderr = result.stderr?.toString().trim();\n\tif (stderr) {\n\t\treturn stderr;\n\t}\n\tconst stdout = result.stdout?.toString().trim();\n\tif (stdout) {\n\t\treturn stdout;\n\t}\n\treturn `exit status ${result.status ?? \"unknown\"}`;\n}\n\nfunction runExtractionCommand(command: string, args: string[]): string | null {\n\tconst result = spawnSync(command, args, { stdio: \"pipe\", timeout: ARCHIVE_EXTRACTION_TIMEOUT_MS });\n\tif (!result.error && result.status === 0) {\n\t\treturn null;\n\t}\n\treturn `${command}: ${formatSpawnFailure(result)}`;\n}\n\nfunction extractTarGzArchive(archivePath: string, extractDir: string, assetName: string): void {\n\tconst failure = runExtractionCommand(\"tar\", [\"xzf\", archivePath, \"-C\", extractDir]);\n\tif (failure) {\n\t\tthrow new Error(`Failed to extract ${assetName}: ${failure}`);\n\t}\n}\n\nfunction getWindowsTarCommand(): string {\n\tconst systemRoot = process.env.SystemRoot ?? process.env.WINDIR;\n\tif (systemRoot) {\n\t\tconst systemTar = join(systemRoot, \"System32\", \"tar.exe\");\n\t\tif (existsSync(systemTar)) {\n\t\t\treturn systemTar;\n\t\t}\n\t}\n\treturn \"tar.exe\";\n}\n\nfunction extractZipArchive(archivePath: string, extractDir: string, assetName: string): void {\n\tconst failures: string[] = [];\n\n\tif (platform() === \"win32\") {\n\t\t// Windows ships bsdtar as tar.exe, which supports zip files. Prefer the\n\t\t// System32 binary over Git Bash's GNU tar, which does not handle zip archives.\n\t\tconst tarFailure = runExtractionCommand(getWindowsTarCommand(), [\"xf\", archivePath, \"-C\", extractDir]);\n\t\tif (!tarFailure) return;\n\t\tfailures.push(tarFailure);\n\n\t\tconst script =\n\t\t\t\"& { param($archive, $destination) $ErrorActionPreference = 'Stop'; Expand-Archive -LiteralPath $archive -DestinationPath $destination -Force }\";\n\t\tconst powershellFailure = runExtractionCommand(\"powershell.exe\", [\n\t\t\t\"-NoLogo\",\n\t\t\t\"-NoProfile\",\n\t\t\t\"-NonInteractive\",\n\t\t\t\"-ExecutionPolicy\",\n\t\t\t\"Bypass\",\n\t\t\t\"-Command\",\n\t\t\tscript,\n\t\t\tarchivePath,\n\t\t\textractDir,\n\t\t]);\n\t\tif (!powershellFailure) return;\n\t\tfailures.push(powershellFailure);\n\t} else {\n\t\tconst unzipFailure = runExtractionCommand(\"unzip\", [\"-q\", archivePath, \"-d\", extractDir]);\n\t\tif (!unzipFailure) return;\n\t\tfailures.push(unzipFailure);\n\n\t\tconst tarFailure = runExtractionCommand(\"tar\", [\"xf\", archivePath, \"-C\", extractDir]);\n\t\tif (!tarFailure) return;\n\t\tfailures.push(tarFailure);\n\t}\n\n\tthrow new Error(`Failed to extract ${assetName}: ${failures.join(\"; \")}`);\n}\n\n/** Move a verified upstream standalone executable into Pi's managed bin directory. */\nexport function installStandaloneBinaryAsset(\n\tdownloadedPath: string,\n\tbinaryPath: string,\n\ttargetPlatform: string = platform(),\n): void {\n\tmkdirSync(dirname(binaryPath), { recursive: true });\n\trenameSync(downloadedPath, binaryPath);\n\tif (targetPlatform !== \"win32\") chmodSync(binaryPath, 0o755);\n}\n\n// Download and install a tool\nconst toolDownloadPromises = new Map<ManagedToolName, Promise<string | undefined>>();\n\nexport function runExclusiveToolDownload(\n\ttool: ManagedToolName,\n\tinstaller: () => Promise<string | undefined>,\n): Promise<string | undefined> {\n\tconst existing = toolDownloadPromises.get(tool);\n\tif (existing) return existing;\n\tconst promise = installer().finally(() => {\n\t\tif (toolDownloadPromises.get(tool) === promise) {\n\t\t\ttoolDownloadPromises.delete(tool);\n\t\t}\n\t});\n\ttoolDownloadPromises.set(tool, promise);\n\treturn promise;\n}\n\nasync function downloadTool(tool: ManagedToolName): Promise<string> {\n\tconst config: ToolConfig = TOOLS[tool];\n\tif (!config) throw new Error(`Unknown tool: ${tool}`);\n\n\tconst plat = platform();\n\tconst architecture = arch();\n\n\t// Pinned tools are reproducible and verified before installation.\n\tlet version = config.pinnedVersion ?? (await getLatestVersion(config.repo));\n\tif (tool === \"fd\" && plat === \"darwin\" && architecture === \"x64\") {\n\t\tversion = \"10.3.0\";\n\t}\n\n\t// Get asset name for this platform\n\tconst assetName = config.getAssetName(version, plat, architecture);\n\tif (!assetName) {\n\t\tthrow new Error(`Unsupported platform: ${plat}/${architecture}`);\n\t}\n\n\t// Create tools directory\n\tmkdirSync(TOOLS_DIR, { recursive: true });\n\n\tconst downloadUrl = `https://github.com/${config.repo}/releases/download/${config.tagPrefix}${version}/${assetName}`;\n\tconst downloadWorkDir = getProcessWorkRun(getAgentDir(), \"downloads\", \"tools\").path;\n\tconst archivePath = join(downloadWorkDir, assetName);\n\tconst binaryExt = plat === \"win32\" ? \".exe\" : \"\";\n\tconst binaryPath = join(TOOLS_DIR, config.binaryName + binaryExt);\n\n\t// Download and verify pinned artifacts before extraction.\n\tawait downloadFile(downloadUrl, archivePath);\n\tconst expectedSha256 = config.sha256ByAsset?.[assetName];\n\tif (config.sha256ByAsset && !expectedSha256) {\n\t\tthrow new Error(`No pinned SHA-256 is registered for ${assetName}`);\n\t}\n\tif (expectedSha256 && !(await verifyFileSha256(archivePath, expectedSha256))) {\n\t\tthrow new Error(`SHA-256 verification failed for ${assetName}`);\n\t}\n\n\tif (config.downloadKind === \"binary\") {\n\t\ttry {\n\t\t\tinstallStandaloneBinaryAsset(archivePath, binaryPath, plat);\n\t\t} finally {\n\t\t\trmSync(archivePath, { force: true });\n\t\t}\n\t\treturn binaryPath;\n\t}\n\n\t// Extract into a unique temp directory. Tool downloads can run concurrently\n\t// during startup, so sharing a fixed directory causes races.\n\tconst extractDir = join(\n\t\tdownloadWorkDir,\n\t\t`extract-${config.binaryName}-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`,\n\t);\n\tmkdirSync(extractDir, { recursive: true });\n\n\ttry {\n\t\tif (assetName.endsWith(\".tar.gz\")) {\n\t\t\textractTarGzArchive(archivePath, extractDir, assetName);\n\t\t} else if (assetName.endsWith(\".zip\")) {\n\t\t\textractZipArchive(archivePath, extractDir, assetName);\n\t\t} else {\n\t\t\tthrow new Error(`Unsupported archive format: ${assetName}`);\n\t\t}\n\n\t\t// Find the binary in extracted files. Some archives contain files directly\n\t\t// at root, others nest under a versioned subdirectory.\n\t\tconst binaryFileName = config.binaryName + binaryExt;\n\t\tconst extractedDir = join(extractDir, assetName.replace(/\\.(tar\\.gz|zip)$/, \"\"));\n\t\tconst extractedBinaryCandidates = [join(extractedDir, binaryFileName), join(extractDir, binaryFileName)];\n\t\tlet extractedBinary = extractedBinaryCandidates.find((candidate) => existsSync(candidate));\n\n\t\tif (!extractedBinary) {\n\t\t\textractedBinary = findBinaryRecursively(extractDir, binaryFileName) ?? undefined;\n\t\t}\n\n\t\tif (extractedBinary) {\n\t\t\trenameSync(extractedBinary, binaryPath);\n\t\t} else {\n\t\t\tthrow new Error(`Binary not found in archive: expected ${binaryFileName} under ${extractDir}`);\n\t\t}\n\n\t\t// Make executable (Unix only)\n\t\tif (plat !== \"win32\") {\n\t\t\tchmodSync(binaryPath, 0o755);\n\t\t}\n\t} finally {\n\t\t// Cleanup\n\t\trmSync(archivePath, { force: true });\n\t\trmSync(extractDir, { recursive: true, force: true });\n\t}\n\n\treturn binaryPath;\n}\n\n// Termux package names for tools\nconst TERMUX_PACKAGES: Record<ManagedToolName, string> = {\n\tfd: \"fd\",\n\tjscpd: \"jscpd\",\n\tjq: \"jq\",\n\trg: \"ripgrep\",\n\tuv: \"uv\",\n};\n\nconst FFF_PLATFORM_PACKAGES: Record<string, string> = {\n\t\"darwin/arm64\": \"@ff-labs/fff-bin-darwin-arm64\",\n\t\"darwin/x64\": \"@ff-labs/fff-bin-darwin-x64\",\n\t\"linux/arm64/glibc\": \"@ff-labs/fff-bin-linux-arm64-gnu\",\n\t\"linux/arm64/musl\": \"@ff-labs/fff-bin-linux-arm64-musl\",\n\t\"linux/x64/glibc\": \"@ff-labs/fff-bin-linux-x64-gnu\",\n\t\"linux/x64/musl\": \"@ff-labs/fff-bin-linux-x64-musl\",\n\t\"win32/arm64\": \"@ff-labs/fff-bin-win32-arm64\",\n\t\"win32/x64\": \"@ff-labs/fff-bin-win32-x64\",\n};\n\nlet fffNodeInstallPromise: Promise<unknown | undefined> | undefined;\n\nfunction detectLinuxLibc(): \"glibc\" | \"musl\" {\n\tlet output = \"\";\n\ttry {\n\t\tconst result = spawnSync(\"ldd\", [\"--version\"], { encoding: \"utf-8\", stdio: \"pipe\", timeout: 5000 });\n\t\toutput = `${result.stdout ?? \"\"}${result.stderr ?? \"\"}`;\n\t} catch (e: unknown) {\n\t\tconst err = e as { stdout?: string | Buffer; stderr?: string | Buffer };\n\t\toutput = `${String(err.stdout ?? \"\")}${String(err.stderr ?? \"\")}`;\n\t}\n\treturn output.toLowerCase().includes(\"musl\") ? \"musl\" : \"glibc\";\n}\n\nfunction getFffPlatformPackageName(): string | undefined {\n\tconst plat = platform();\n\tconst architecture = arch();\n\tif (plat === \"linux\") {\n\t\treturn FFF_PLATFORM_PACKAGES[`${plat}/${architecture}/${detectLinuxLibc()}`];\n\t}\n\treturn FFF_PLATFORM_PACKAGES[`${plat}/${architecture}`];\n}\n\nfunction createManagedFffRequire(): ModuleRequire | undefined {\n\tif (!existsSync(FFF_MANAGED_PACKAGE_JSON)) return undefined;\n\treturn createRequire(pathToFileURL(FFF_MANAGED_PACKAGE_JSON).href);\n}\n\nfunction findFffNodeDistEntry(startPath: string): string | undefined {\n\tlet currentDir = dirname(startPath);\n\twhile (currentDir !== dirname(currentDir)) {\n\t\tconst candidate = join(currentDir, \"node_modules\", \"@ff-labs\", \"fff-node\", \"dist\", \"src\", \"index.js\");\n\t\tif (existsSync(candidate)) return candidate;\n\t\tcurrentDir = dirname(currentDir);\n\t}\n\treturn undefined;\n}\n\nfunction loadFffNodeDistEntry(requireFff: ModuleRequire): unknown | undefined {\n\tif (!requireFff.resolve) return undefined;\n\ttry {\n\t\tconst ffiPath = requireFff.resolve(\"ffi-rs\");\n\t\tconst fffEntry = findFffNodeDistEntry(ffiPath);\n\t\treturn fffEntry ? requireFff(fffEntry) : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction loadFffNodeWith(requireFff: ModuleRequire): unknown | undefined {\n\ttry {\n\t\treturn requireFff(\"@ff-labs/fff-node\");\n\t} catch {\n\t\treturn loadFffNodeDistEntry(requireFff);\n\t}\n}\n\n/**\n * @param requires Override the resolution candidates, for tests (mirrors\n * fff-search-backend.ts's loadFffModule(requires?)). Whether this resolves\n * depends on the ambient environment -- @ff-labs/fff-node is a real npm\n * dependency (package.json), so moduleRequire succeeds wherever a normal\n * `npm install`/`npm ci` provisioned it (e.g. CI) even though it fails on a\n * dev checkout that never ran that install here (this repo resolves fff-node\n * via the separate managed-dir path instead). A test asserting \"nothing is\n * available\" must pass `[]` here rather than relying on that being true.\n */\nexport function loadAvailableFffNodePackage(requires?: readonly ModuleRequire[]): unknown | undefined {\n\tconst candidates =\n\t\trequires ??\n\t\t[moduleRequire, executableDirRequire, createManagedFffRequire()].filter((candidate): candidate is ModuleRequire =>\n\t\t\tBoolean(candidate),\n\t\t);\n\tfor (const requireFff of candidates) {\n\t\tconst loaded = loadFffNodeWith(requireFff);\n\t\tif (loaded) return loaded;\n\t}\n\treturn undefined;\n}\n\nasync function runNpmInstall(args: string[]): Promise<{ code: number | null; stderr: string }> {\n\ttry {\n\t\tconst child = spawnProcess(\"npm\", args, {\n\t\t\tdetached: process.platform !== \"win32\",\n\t\t\tstdio: [\"ignore\", \"pipe\", \"pipe\"],\n\t\t});\n\t\tlet stderr = \"\";\n\t\tchild.stderr?.on(\"data\", (chunk) => {\n\t\t\tstderr = `${stderr}${chunk.toString()}`.slice(-64 * 1024);\n\t\t});\n\t\tconst terminal = await waitForChildProcessWithTermination(child, {\n\t\t\ttimeoutMs: ARCHIVE_EXTRACTION_TIMEOUT_MS,\n\t\t\tkillGraceMs: 2_000,\n\t\t});\n\t\tif (terminal.reason === \"timeout\") {\n\t\t\tstderr = `${stderr}\\nnpm install timed out after ${ARCHIVE_EXTRACTION_TIMEOUT_MS}ms`.trim();\n\t\t}\n\t\treturn { code: terminal.code, stderr };\n\t} catch (error) {\n\t\treturn { code: 1, stderr: error instanceof Error ? error.message : String(error) };\n\t}\n}\n\n/**\n * Outcome of the most recent {@link ensureFffNodePackage} call, kept for\n * observability (e.g. a future `doctor` check) since the function itself\n * only ever returns the loaded module or `undefined` either way.\n *\n * `install-failed` is distinguished from `offline`/`unsupported-platform`\n * because it is the only one worth *retrying*: offline mode and an\n * unsupported platform are stable for the life of the process, but a real\n * install attempt can fail on a transient issue (registry hiccup, timeout)\n * that may no longer apply on the next search. See\n * DefaultFffSearchBackend.getFinder in fff-search-backend.ts, which uses\n * this distinction to decide whether a failed finder is retryable.\n */\nexport type FffInstallOutcome =\n\t| { status: \"already-available\" }\n\t| { status: \"offline\" }\n\t| { status: \"unsupported-platform\" }\n\t| { status: \"installed\" }\n\t| { status: \"install-failed\"; reason: string };\n\n/**\n * How long a genuine install failure gates out a NEW npm spawn. An agent turn\n * can fire several find/grep calls in quick succession, and each one now\n * primes the finder in the background (see tryFffFind/tryFffGrep) -- without\n * this, a persistently-failing install (registry down, disk full, ...) would\n * re-spawn npm on every single one of those calls instead of once.\n *\n * This gates the SPAWN inside ensureFffNodePackage, not whether a failed\n * finder is retryable (see isFffInstallRetryable): DefaultFffSearchBackend\n * always evicts a failed finder so the next search re-enters this function,\n * and it is THIS cooldown check -- evaluated fresh, at call time -- that\n * decides whether that re-entry is a real attempt or a fast, spawn-free bail.\n * (An earlier version conflated the two: it gated eviction itself on the\n * cooldown, which is checked once, immediately after the failure it's timing\n * -- i.e. always still within the window -- so the failed finder was never\n * evicted and the retry never got a chance to happen at all.)\n */\nexport const FFF_INSTALL_RETRY_COOLDOWN_MS = 30_000;\n\nlet lastFffInstallOutcome: FffInstallOutcome | undefined;\nlet lastFffInstallFailureAt: number | undefined;\n\n/** The outcome of the last {@link ensureFffNodePackage} call, if any. */\nexport function getLastFffInstallOutcome(): FffInstallOutcome | undefined {\n\treturn lastFffInstallOutcome;\n}\n\n/** Whether the last install outcome was a genuine failure worth retrying (as opposed to a stable \"not applicable\" result). Cooldown-independent by design -- see FFF_INSTALL_RETRY_COOLDOWN_MS. */\nexport function isFffInstallRetryable(): boolean {\n\treturn lastFffInstallOutcome?.status === \"install-failed\";\n}\n\n/**\n * Pure decision logic behind {@link isFffInstallCoolingDown}, exposed directly\n * so tests can assert the cooldown boundary without faking the system clock.\n */\nexport function computeIsFffInstallCoolingDown(\n\toutcome: FffInstallOutcome | undefined,\n\tfailedAt: number | undefined,\n\tnow: number,\n): boolean {\n\tif (outcome?.status !== \"install-failed\") return false;\n\tif (failedAt === undefined) return false;\n\treturn now - failedAt < FFF_INSTALL_RETRY_COOLDOWN_MS;\n}\n\n/** Whether a real install attempt happened too recently to try again right now. */\nfunction isFffInstallCoolingDown(): boolean {\n\treturn computeIsFffInstallCoolingDown(lastFffInstallOutcome, lastFffInstallFailureAt, Date.now());\n}\n\n/** Records a genuine install failure and stamps when it happened, so the cooldown above has a start time to measure from. */\nfunction recordFffInstallFailure(reason: string): void {\n\tlastFffInstallOutcome = { status: \"install-failed\", reason };\n\tlastFffInstallFailureAt = Date.now();\n}\n\nasync function installManagedFffNodePackage(platformPackage: string, silent: boolean): Promise<unknown | undefined> {\n\ttry {\n\t\tmkdirSync(FFF_MANAGED_DIR, { recursive: true });\n\t\tif (!existsSync(FFF_MANAGED_PACKAGE_JSON)) {\n\t\t\twriteFileSync(FFF_MANAGED_PACKAGE_JSON, '{\"name\":\"pi-managed-fff-node\",\"private\":true,\"version\":\"0.0.0\"}\\n');\n\t\t}\n\n\t\tif (!silent) {\n\t\t\tconsole.log(chalk.dim(\"FFF native search not found. Installing managed FFF package...\"));\n\t\t}\n\n\t\tconst args = [\n\t\t\t\"install\",\n\t\t\t\"--ignore-scripts\",\n\t\t\t\"--omit=dev\",\n\t\t\t\"--include=optional\",\n\t\t\t\"--no-audit\",\n\t\t\t\"--no-fund\",\n\t\t\t\"--package-lock=false\",\n\t\t\t\"--prefix\",\n\t\t\tFFF_MANAGED_DIR,\n\t\t\t`@ff-labs/fff-node@${FFF_NODE_VERSION}`,\n\t\t\t`${platformPackage}@${FFF_NODE_VERSION}`,\n\t\t];\n\t\tconst result = await runNpmInstall(args);\n\t\tif (result.code !== 0) {\n\t\t\tconst reason = result.stderr.trim() || `npm exited with code ${result.code}`;\n\t\t\tif (!silent) {\n\t\t\t\tconsole.log(chalk.yellow(`Failed to install FFF native search: ${reason}`));\n\t\t\t}\n\t\t\trecordFffInstallFailure(reason);\n\t\t\treturn undefined;\n\t\t}\n\t\tconst loaded = loadFffNodeWith(createRequire(pathToFileURL(FFF_MANAGED_PACKAGE_JSON).href));\n\t\tif (!loaded) {\n\t\t\tconst reason = \"Managed FFF install completed but @ff-labs/fff-node could not be loaded.\";\n\t\t\tif (!silent) {\n\t\t\t\tconsole.log(chalk.yellow(reason));\n\t\t\t}\n\t\t\trecordFffInstallFailure(reason);\n\t\t\treturn undefined;\n\t\t}\n\t\tlastFffInstallOutcome = { status: \"installed\" };\n\t\treturn loaded;\n\t} catch (error) {\n\t\t// Never let a filesystem/spawn surprise (e.g. a read-only home directory)\n\t\t// crash the caller: fall back like any other install failure, but keep\n\t\t// the reason observable.\n\t\tconst reason = error instanceof Error ? error.message : String(error);\n\t\tif (!silent) {\n\t\t\tconsole.log(chalk.yellow(`Failed to install FFF native search: ${reason}`));\n\t\t}\n\t\trecordFffInstallFailure(reason);\n\t\treturn undefined;\n\t}\n}\n\nexport async function ensureFffNodePackage(\n\tsilent: boolean = false,\n\tforceManagedInstall: boolean = false,\n\t/** Override the \"is it already available\" resolution candidates, for tests. See loadAvailableFffNodePackage's doc. */\n\trequires?: readonly ModuleRequire[],\n): Promise<unknown | undefined> {\n\tconst existing = forceManagedInstall ? undefined : loadAvailableFffNodePackage(requires);\n\tif (existing) {\n\t\tlastFffInstallOutcome = { status: \"already-available\" };\n\t\treturn existing;\n\t}\n\n\tif (isOfflineModeEnabled()) {\n\t\tif (!silent) {\n\t\t\tconsole.log(chalk.yellow(\"FFF native search not found. Offline mode enabled, skipping install.\"));\n\t\t}\n\t\tlastFffInstallOutcome = { status: \"offline\" };\n\t\treturn undefined;\n\t}\n\n\t// A prior attempt failed too recently to try again: bail out fast (no npm\n\t// spawn, no platform/libc probing) rather than repeating a doomed attempt.\n\t// Leaves lastFffInstallOutcome/lastFffInstallFailureAt untouched -- this\n\t// isn't a new attempt, so there's nothing new to record.\n\tif (isFffInstallCoolingDown()) {\n\t\treturn undefined;\n\t}\n\n\tconst platformPackage = getFffPlatformPackageName();\n\tif (!platformPackage) {\n\t\tif (!silent) {\n\t\t\tconsole.log(chalk.yellow(`FFF native search is not available for ${platform()}/${arch()}.`));\n\t\t}\n\t\tlastFffInstallOutcome = { status: \"unsupported-platform\" };\n\t\treturn undefined;\n\t}\n\n\tfffNodeInstallPromise ??= installManagedFffNodePackage(platformPackage, silent).finally(() => {\n\t\tfffNodeInstallPromise = undefined;\n\t});\n\treturn fffNodeInstallPromise;\n}\n\nasync function installTermuxManagedTool(tool: ManagedToolName, silent: boolean): Promise<string | undefined> {\n\tconst packageName = TERMUX_PACKAGES[tool];\n\tif (!silent) console.log(chalk.dim(`${TOOLS[tool].name} not found. Installing with Termux pkg...`));\n\tconst child = spawnProcess(\"pkg\", [\"install\", \"-y\", packageName], {\n\t\tenv: process.env,\n\t\tstdio: silent ? \"ignore\" : \"inherit\",\n\t});\n\tconst terminal = await waitForChildProcessWithTermination(child, { timeoutMs: 300_000, killGraceMs: 5_000 });\n\tif (terminal.reason !== \"exited\" || terminal.code !== 0) {\n\t\tthrow new Error(\n\t\t\t`pkg install ${packageName} ${terminal.reason === \"timeout\" ? \"timed out\" : `exited with code ${terminal.code ?? 1}`}`,\n\t\t);\n\t}\n\treturn getToolPath(tool) ?? undefined;\n}\n\n// Ensure a tool is available, downloading if necessary\n// Returns the path to the tool, or undefined if unavailable\nexport async function ensureTool(tool: ManagedToolName, silent: boolean = false): Promise<string | undefined> {\n\tif (tool === \"jscpd\") {\n\t\ttry {\n\t\t\treturn ensureManagedJscpd();\n\t\t} catch (error) {\n\t\t\tif (!silent) {\n\t\t\t\tconsole.log(chalk.yellow(`Failed to provision jscpd: ${error instanceof Error ? error.message : error}`));\n\t\t\t}\n\t\t\treturn undefined;\n\t\t}\n\t}\n\tconst existingPath = getToolPath(tool);\n\tif (existingPath) {\n\t\treturn existingPath;\n\t}\n\n\tconst config = TOOLS[tool];\n\tif (!config) return undefined;\n\n\tif (isOfflineModeEnabled()) {\n\t\tif (!silent) {\n\t\t\tconsole.log(chalk.yellow(`${config.name} not found. Offline mode enabled, skipping download.`));\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t// On Android/Termux, upstream Linux archives target glibc/musl rather than Bionic.\n\t// uv is a required managed runtime and the user explicitly authorized provisioning it;\n\t// preserve guide-only behavior for optional search tools.\n\tif (platform() === \"android\") {\n\t\tif (tool !== \"uv\") {\n\t\t\tconst packageName = TERMUX_PACKAGES[tool];\n\t\t\tif (!silent) console.log(chalk.yellow(`${config.name} not found. Install with: pkg install ${packageName}`));\n\t\t\treturn undefined;\n\t\t}\n\t\ttry {\n\t\t\treturn await runExclusiveToolDownload(tool, () => installTermuxManagedTool(tool, silent));\n\t\t} catch (error) {\n\t\t\tif (!silent) {\n\t\t\t\tconsole.log(\n\t\t\t\t\tchalk.yellow(`Failed to install ${config.name}: ${error instanceof Error ? error.message : error}`),\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn undefined;\n\t\t}\n\t}\n\n\t// Tool not found - download it\n\tif (!silent) {\n\t\tconsole.log(chalk.dim(`${config.name} not found. Downloading...`));\n\t}\n\n\ttry {\n\t\tconst path = await runExclusiveToolDownload(tool, () => downloadTool(tool));\n\t\tif (!silent) {\n\t\t\tconsole.log(chalk.dim(`${config.name} installed to ${path}`));\n\t\t}\n\t\treturn path;\n\t} catch (e) {\n\t\tif (!silent) {\n\t\t\tconsole.log(chalk.yellow(`Failed to download ${config.name}: ${e instanceof Error ? e.message : e}`));\n\t\t}\n\t\treturn undefined;\n\t}\n}\n"]}
package/docs/index.md CHANGED
@@ -49,11 +49,13 @@ For the full first-run flow, see [Quickstart](quickstart.md).
49
49
  - [Tool repair](tool-repair.md) - repaired tool-call arguments, health diagnostics, kill switches, and replay workflow.
50
50
  - [Task steps](task-steps.md) - native session checklist, slash commands, persistence, and delegation migration.
51
51
  - [Native Python](python.md) - uv-managed bounded Python execution, provisioning, output limits, and cross-platform file guidance.
52
+ - [Managed data tools](managed-data-tools.md) - pinned rg, jq, and Rust jscpd provisioning without project files.
52
53
 
53
54
  ## Customization
54
55
 
55
56
  - [Extensions](extensions.md) - TypeScript modules for tools, commands, events, and custom UI.
56
57
  - [tmux agent manager](tmux-agent-manager.md) - bundled event-driven external-provider teams with parent wake handoffs.
58
+ - [Task worker profiles](worker-profiles.md) - immutable session-scoped worker profiles with bounded model and tool authority.
57
59
  - [Skills](skills.md) - Agent Skills for reusable on-demand capabilities.
58
60
  - [Resource profiles & library](resources.md) - curate extensions, skills, and agents per project or situation; share a catalog; install and back up.
59
61
  - [Self-adaptation](self-adaptation.md) - draft live skills/extensions and run evidence-backed Pi harness improvement loops.
@@ -86,3 +88,4 @@ For the full first-run flow, see [Quickstart](quickstart.md).
86
88
  ## Development
87
89
 
88
90
  - [Development](development.md) - local setup, project structure, and debugging.
91
+ - [Tool boundary performance roadmap](tool-boundary-performance-roadmap-2026-08-02.md) - evidence ledger for preflight, payload ownership, Python coordination, and remaining latency/memory work.
@@ -0,0 +1,15 @@
1
+ # Managed data tools
2
+
3
+ Pi keeps source filtering and structured-data projection outside the JavaScript heap with managed native tools:
4
+
5
+ - `rg` for bounded text and file candidate searches.
6
+ - `jq` for selecting only the JSON records and fields needed by the agent.
7
+ - Rust `jscpd` 5.0.14 for production clone evidence.
8
+
9
+ Pi provisions these binaries under its managed agent `bin` directory and places that directory first on the tool environment `PATH`. Provisioning never runs a project package manager and never writes dependencies, configuration, reports, or caches into the current repository.
10
+
11
+ The npm package includes the exact jscpd v5 platform package. Standalone releases carry the native binary beside Pi. The first Pi startup, `pi doctor`, or direct `jscpd` wrapper invocation installs the verified binary into managed storage. Concurrent sessions converge on the same exact version; different agent directories remain isolated.
12
+
13
+ Use `pi doctor` to verify availability. If a managed binary cannot be verified, treat the scan as incomplete and change approach; do not install a fallback into the project.
14
+
15
+ Ad hoc scanner reports and configuration belong in the OS or Pi transient work directory. A green clone report is evidence only when its production coverage and detection thresholds are also verified.
@@ -77,8 +77,8 @@ Summarize this repository and tell me how to run its checks.
77
77
  By default, pi gives the model four tools:
78
78
 
79
79
  - `read` - read files
80
- - `write` - create or overwrite files
81
- - `edit` - patch files
80
+ - `write` - preflight and create new files without overwriting existing paths
81
+ - `edit` - preflight and patch existing files with stale-target checks
82
82
  - `bash` - run shell commands
83
83
 
84
84
  Additional built-in read-only tools (`grep`, `find`, `ls`) are available through tool options. Pi runs in your current working directory and can modify files there. Use git or another checkpointing workflow if you want easy rollback.
@@ -0,0 +1,166 @@
1
+ # Tool Boundary Performance Roadmap — 2026-08-02
2
+
3
+ This is the evidence ledger for avoiding wasted model output, repeated large-string work, foreground stalls,
4
+ and cross-session contention at tool boundaries. Findings are classified as fixed, open, rejected, or
5
+ incomplete. A green process exit is not evidence when a relevant payload, race, platform, or memory probe was
6
+ not exercised.
7
+
8
+ ## Required invariants
9
+
10
+ 1. Validate cheap authority, path, identity, availability, and collision facts before asking the model for a
11
+ large payload.
12
+ 2. Keep coordinators, payload handles, mutable queues, and retry state session-owned unless cross-session
13
+ coordination is the explicit invariant.
14
+ 3. Store large bytes once, outside the JavaScript heap where practical. Context and telemetry retain bounded
15
+ metadata and opaque handles, not duplicate payloads.
16
+ 4. Never flatten accumulated text repeatedly. Rendering, loop detection, failure handling, and telemetry use
17
+ incremental processing or constant-size fingerprints.
18
+ 5. A failure that requires a different approach discards its operation arguments. It may expose one bounded
19
+ reason/directive for the next model turn, then expires.
20
+ 6. Every visible tool operation reports elapsed time through the shared TUI timing owner.
21
+
22
+ ## Confirmed and fixed in this cycle
23
+
24
+ | Boundary | Root cause | Fix | Evidence gate |
25
+ | --- | --- | --- | --- |
26
+ | Write collision | `write` accepted the full content before discovering an occupied destination and could overwrite it. | Two-phase `prepare`/`commit`, path-only collision and parent checks, single-use session intent, and final `wx` no-clobber create. | `test/file-mutation-preflight.test.ts`; `test/file-encoding-policy.test.ts` |
27
+ | Missing/stale edit | `edit` accepted replacement payloads before existence checks and could apply a plan prepared against older bytes. | Path-only preparation records file identity; commit consumes the intent and rejects a missing or changed target. | `test/file-mutation-preflight.test.ts`; `test/file-mutation-queue.test.ts` |
28
+ | Repeated exact content | Copying identical generated content to another destination required retransmitting it. | Successful writes/edits return a session-local `contentRef`; the bounded controller hashes the source and performs exclusive verified copies without retaining bytes on the JS heap. | `test/file-mutation-preflight.test.ts` |
29
+ | Encoding corruption | An unsafe text edit could be remembered as a retryable operation and teach repair/re-read loops. | The central execution-error catalogue classifies `PI_FILE_ENCODING_CORRUPTION` as change-approach, consumes the edit intent, retains no operation arguments, exposes one bounded directive, and expires it after the next assistant response. | `packages/ai/test/tool-execution-error-catalogue.test.ts`; `packages/agent/test/tool-failure-memory.test.ts` |
30
+ | Edit preview flattening | Preview rendering used `JSON.stringify({ path, edits })` during render and result settlement, copying the complete edit payload. | Constant-size request generations fence asynchronous previews; partial renders do not scan accumulated edits. | `test/edit-tool-no-full-redraw.test.ts` |
31
+ | Write preview flattening | Collapsed streamed previews compared the complete prior content prefix, split and highlighted complete snapshots, and retained duplicate full line arrays. | Collapsed rendering inspects at most 8,192 characters, caches by argument-generation identity, and performs one allocation-free final line count; complete text is materialized only on explicit expansion. | `test/tool-execution-component.test.ts` |
32
+ | Loop/failure payload retention | Stall and failure signatures serialized complete tool arguments and stored the normalized string in the loop window. | A streaming structural fingerprint returns 32 hex characters; failure display keeps a bounded structural preview and never serializes the original payload. | `packages/agent/test/tool-failure-memory.test.ts` |
33
+ | Tool timing gaps | Only selected tool implementations exposed duration, so reads and Python appeared to have no timing. | One monotonic component displays live `Elapsed` and terminal `Took` timing for every tool surface, including failures, replayed panels, built-ins, and extensions. | `test/tool-execution-component.test.ts` |
34
+
35
+ All fixed paths must retain the zero-clone production gate and the focused regression named above.
36
+
37
+ ## P0 — confirmed open work
38
+
39
+ ### P0.1 Persistent Python coordinator per session
40
+
41
+ Evidence:
42
+
43
+ - `src/core/tools/python.ts` creates `createLocalPythonOperations()` per tool definition and calls
44
+ `spawnProcess()` for every execution.
45
+ - `src/core/python-runtime.ts` caches interpreter discovery process-wide, but it is not a command coordinator.
46
+ - `src/core/tools/python.ts` wraps every job in `withExclusiveMutationBarrier()`.
47
+ - `src/core/tools/file-mutation-queue.ts` owns one module-global writer queue, so a long Python job can block
48
+ unrelated sessions and workspaces.
49
+
50
+ Required design:
51
+
52
+ - RuntimeBuilder owns one `PythonCommandCoordinator` per agent session. Never share the command process across
53
+ sessions or tenants.
54
+ - Start the interpreter/worker once on first use, use framed requests and terminal acknowledgements, and reset
55
+ the owned process after protocol corruption, timeout, abort, or crash.
56
+ - Completion is event-driven and emits the normal terminal tool signal. Jobs handed to the existing background
57
+ lane after 15 seconds keep the same session coordinator and notify their owning session only.
58
+ - Replace the process-global exclusive writer with an explicit session/workspace mutation port. Same-file
59
+ operations remain serialized; unrelated sessions are not globally stopped.
60
+
61
+ Acceptance evidence:
62
+
63
+ - Cold start and first dispatch measured separately from warm dispatch on Linux and Windows.
64
+ - Warm no-op harness overhead target: p95 <= 25 ms, excluding Python code runtime.
65
+ - Two concurrent sessions prove distinct worker PIDs/state and no cross-session variables.
66
+ - A 20-second Python job does not delay a read-only call or a mutation in another isolated workspace.
67
+ - Timeout, abort, malformed frame, worker exit, and session disposal each produce one terminal event and bounded
68
+ handoff.
69
+
70
+ ### P0.2 Python path/runtime preflight before inline code
71
+
72
+ Evidence: `python` receives up to 200,000 characters of inline code before it checks `cwd`, `scriptPath`, uv, or
73
+ the interpreter. An invalid working directory can therefore waste the entire generated program.
74
+
75
+ Required design:
76
+
77
+ - Add a path-only/runtime-only prepare action for inline-code mode and a path/runtime prepare action for script
78
+ mode.
79
+ - Commit consumes a single-use session intent. Runtime failure or coordinator reset invalidates the intent; the
80
+ code is not stored as retry memory.
81
+ - Do not add a legacy one-phase fallback.
82
+
83
+ Acceptance evidence: invalid cwd/runtime tests prove that no `code` field was accepted; stale and cross-session
84
+ intents fail; successful warm preparation meets the same p95 budget as P0.1.
85
+
86
+ ### P0.3 Process-isolate extension smoke tests
87
+
88
+ Evidence: `src/core/tools/extensionify.ts` writes the complete draft and calls `loadExtension()` in the live Pi
89
+ process. The “isolated runtime” isolates registration state, not CPU, environment, memory, filesystem, or process
90
+ lifetime. A draft can block the event loop or inspect live process state.
91
+
92
+ Required design:
93
+
94
+ - Validate name, proposed destination, package JSON shape, size bounds, and policy before accepting factory code.
95
+ - Run the draft in a disposable child process with a bounded environment, output, time, memory, and capability
96
+ surface. Send back registration metadata only.
97
+ - The child emits one terminal result; cleanup is lease-owned and event-driven.
98
+ - Do not repeat `code`/`packageJson` in tool result details.
99
+
100
+ Acceptance evidence: infinite loop, allocation bomb, environment read, process exit, malformed package JSON,
101
+ path traversal, and cleanup-failure probes; parent session remains responsive and bounded.
102
+
103
+ ### P0.4 Close edit's external-writer race
104
+
105
+ Evidence: edit commit verifies identity before `readFile()` and later overwrites by path. A non-Pi writer can
106
+ replace the file after the identity check but before the final write.
107
+
108
+ Required design: bind read/compare/commit to a file handle or an adapter-owned compare-and-replace primitive;
109
+ fail closed when identity changes. Define Windows replace/share semantics explicitly and preserve BOM/newlines.
110
+
111
+ Acceptance evidence: deterministic interleavings at every stat/read/write boundary, symlink swaps, same-size
112
+ same-timestamp replacement, Windows sharing violations, abort, and cleanup failure.
113
+
114
+ ## P1 — confirmed, bounded, or dependent work
115
+
116
+ 1. **General payload leases for `skillify`/`extensionify`.** Both tools repeat full draft bodies in result
117
+ details, while their name/description checks happen only after the payload exists. Introduce a session-owned,
118
+ disk-backed, byte/count/age-bounded payload store and return opaque handles. Keep security-sensitive payload
119
+ classes separate even if they share a storage port.
120
+ 2. **Streaming skill audit.** `skill-audit.ts` lowercases, regex-replaces, splits, and de-duplicates the complete
121
+ draft body, then performs pairwise Jaccard comparisons. Add bounded streaming tokenization and an inverted
122
+ candidate index before exact scoring. Preserve evidence that distinct trust/workflow semantics are not merged.
123
+ 3. **Verify custom write adapters before issuing reusable content handles.** Local `wx` writes are authoritative;
124
+ remote/custom adapters need an adapter-owned verified-create contract so a handle is not returned for altered
125
+ bytes.
126
+ 4. **Reduce bounded toolkit-output copies.** Script capture is capped at 512 KiB per stream, but result assembly
127
+ trims and joins both strings before artifact packing. Stream directly into the existing output/artifact owner.
128
+ This is not an OOM path under the present cap, so it follows the unbounded P0 items.
129
+ 5. **Bound metadata schemas.** Add evidence-derived character/item limits to `extensionify`, `skillify`, and
130
+ toolkit identifiers/arguments. Limits must be measured and must not truncate source or reduce correctness.
131
+ 6. **Bound renderer-less tool arguments.** `ToolExecutionComponent.formatToolExecution()` currently
132
+ `JSON.stringify()`s complete arguments for tools without a renderer, and the scrollback component retains
133
+ that argument object after settlement. Use the shared bounded structural projection for display and release
134
+ the UI-owned payload after the session transcript has accepted the authoritative call. Preserve explicit
135
+ expansion through a disk-backed/session-owned handle instead of another heap copy.
136
+
137
+ ## Rejected or low-benefit candidates
138
+
139
+ - **Ropes/piece tables for provider payloads:** rejected at the network boundary. Providers still require a
140
+ contiguous JSON/body representation; chunked message ownership, pruning before formatting, and one terminal
141
+ serialization are the useful controls.
142
+ - **Two-phase preflight for `read`, `grep`, `find`, `ls`, and artifact retrieval:** rejected unless new evidence
143
+ shows large arguments. Their requests are small, outputs are bounded or artifact-backed, and an extra model
144
+ round trip would cost more than the local validation.
145
+ - **Replacing native JSON globally:** rejected without per-boundary benchmarks. Several provider transports
146
+ require JSON text; changing parsers cannot remove serialization and may add copies. Optimize duplicate
147
+ serialization and retained ownership first.
148
+ - **Raising output/context limits:** rejected as a performance fix. It moves the failure boundary and increases
149
+ heap exposure without removing repeated work.
150
+
151
+ ## Incomplete probes
152
+
153
+ - Windows timing distributions for local and SSH-backed prepare/commit.
154
+ - Heap/GC profiles for multi-megabyte skill drafts and extension smoke tests.
155
+ - External-writer race reproduction on NTFS with antivirus/indexer sharing behavior.
156
+ - Provider-specific cost of the extra prepare turn versus rejected-payload tokens across native and text tool
157
+ protocols.
158
+ - Persistent Python protocol throughput and reset cost; no implementation exists yet, so prior process-spawn
159
+ timings are not acceptance evidence.
160
+
161
+ ## Release gate for roadmap items
162
+
163
+ For each item: Detect -> deterministic failing regression and negative control -> fix at the named owner -> run
164
+ the smallest package test -> run adjacent package tests -> `npm run check` -> production clone audit. Run the full
165
+ non-e2e suite only at the pre-release gate. Report fixed findings, rejected candidates, incomplete probes, and
166
+ remaining platform risks separately.
@@ -2,7 +2,7 @@
2
2
 
3
3
  Pi validates every model-emitted tool call against its TypeBox schema before execution. Valid calls run unchanged. Invalid calls either pass through a named deterministic repair and then execute with the repaired arguments, or they bounce with schema feedback when no safe repair applies.
4
4
 
5
- Execution failures are not argument repairs. Pi removes their potentially large failed protocol turns from provider context and retains one bounded failure record: stable operation identity, occurrence count, failure code, a cause-bearing diagnostic when available, and `next_action`. A matching successful retry clears the record. Pi uses `repair` only for argument/protocol rejections with a concrete call correction; policy, preflight, abort, and execution failures use `next_action`. It never invents a deterministic repair from an unknown nonzero exit.
5
+ Execution failures are not argument repairs. Pi removes their potentially large failed protocol turns from provider context and normally retains one bounded failure record: constant-size operation fingerprint, bounded operation preview, occurrence count, failure code, a cause-bearing diagnostic when available, and `next_action`. A matching successful retry clears the record. Change-approach classes such as non-UTF-8 text edits are different: Pi discards the complete attempted operation, exposes one bounded reason/directive for the next assistant response, then expires it. Pi uses `repair` only for argument/protocol rejections with a concrete call correction; policy, preflight, abort, and execution failures use `next_action`. It never invents a deterministic repair from an unknown nonzero exit.
6
6
 
7
7
  ## Runtime behavior
8
8
 
@@ -0,0 +1,16 @@
1
+ # Task worker profiles
2
+
3
+ `profile_writer` lets the foreground orchestrator create the smallest worker profile needed for one bounded task. It does not edit user or project profile files.
4
+
5
+ Task profiles are:
6
+
7
+ - Derived only from an owner-authorized base profile.
8
+ - Immutable and assigned a `task-...` ID by Pi.
9
+ - Stored on the owning session branch, never shared across independent sessions.
10
+ - Limited to 32 profiles per session.
11
+ - Unable to add tools, resources, or budget beyond the base profile.
12
+ - Limited to configured, authenticated, non-exhausted models and a thinking level that model supports.
13
+
14
+ Use `profile_writer { action: "inspect" }` when the authorized bases or model combinations are unknown. Then call `create` with a concise task and only the fields that need narrowing. Pass the returned profile ID unchanged to `delegate`; never invent one.
15
+
16
+ Workers cannot invoke `profile_writer`, recursively delegate, or expand their admitted contract. A resumed worker retains the exact profile, model, resources, and transcript admitted for that task.