@leanandmean/coding-agent 0.74.1-scramjet.7 → 0.74.1-scramjet.70

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 (225) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/LICENSE +202 -0
  3. package/README.md +23 -9
  4. package/dist/cli/args.d.ts.map +1 -1
  5. package/dist/cli/args.js +1 -1
  6. package/dist/cli/args.js.map +1 -1
  7. package/dist/cli/initial-message.d.ts +1 -0
  8. package/dist/cli/initial-message.d.ts.map +1 -1
  9. package/dist/cli/initial-message.js +3 -0
  10. package/dist/cli/initial-message.js.map +1 -1
  11. package/dist/cli/list-models.d.ts +2 -0
  12. package/dist/cli/list-models.d.ts.map +1 -1
  13. package/dist/cli/list-models.js +4 -1
  14. package/dist/cli/list-models.js.map +1 -1
  15. package/dist/config.d.ts +9 -2
  16. package/dist/config.d.ts.map +1 -1
  17. package/dist/config.js +33 -22
  18. package/dist/config.js.map +1 -1
  19. package/dist/core/agent-session-runtime.d.ts +12 -3
  20. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  21. package/dist/core/agent-session-runtime.js +64 -38
  22. package/dist/core/agent-session-runtime.js.map +1 -1
  23. package/dist/core/agent-session-services.d.ts +1 -0
  24. package/dist/core/agent-session-services.d.ts.map +1 -1
  25. package/dist/core/agent-session-services.js +2 -0
  26. package/dist/core/agent-session-services.js.map +1 -1
  27. package/dist/core/agent-session.d.ts +78 -15
  28. package/dist/core/agent-session.d.ts.map +1 -1
  29. package/dist/core/agent-session.js +1059 -203
  30. package/dist/core/agent-session.js.map +1 -1
  31. package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
  32. package/dist/core/compaction/branch-summarization.js +21 -17
  33. package/dist/core/compaction/branch-summarization.js.map +1 -1
  34. package/dist/core/compaction/compaction.d.ts +3 -5
  35. package/dist/core/compaction/compaction.d.ts.map +1 -1
  36. package/dist/core/compaction/compaction.js +43 -10
  37. package/dist/core/compaction/compaction.js.map +1 -1
  38. package/dist/core/exec.d.ts +12 -0
  39. package/dist/core/exec.d.ts.map +1 -1
  40. package/dist/core/exec.js +74 -28
  41. package/dist/core/exec.js.map +1 -1
  42. package/dist/core/export-html/template.js +4 -0
  43. package/dist/core/extensions/index.d.ts +1 -1
  44. package/dist/core/extensions/index.d.ts.map +1 -1
  45. package/dist/core/extensions/index.js.map +1 -1
  46. package/dist/core/extensions/runner.d.ts +9 -5
  47. package/dist/core/extensions/runner.d.ts.map +1 -1
  48. package/dist/core/extensions/runner.js +160 -3
  49. package/dist/core/extensions/runner.js.map +1 -1
  50. package/dist/core/extensions/types.d.ts +85 -8
  51. package/dist/core/extensions/types.d.ts.map +1 -1
  52. package/dist/core/extensions/types.js.map +1 -1
  53. package/dist/core/keybindings.d.ts +8 -0
  54. package/dist/core/keybindings.d.ts.map +1 -1
  55. package/dist/core/model-registry.d.ts +4 -0
  56. package/dist/core/model-registry.d.ts.map +1 -1
  57. package/dist/core/model-registry.js +179 -28
  58. package/dist/core/model-registry.js.map +1 -1
  59. package/dist/core/model-resolver.d.ts.map +1 -1
  60. package/dist/core/model-resolver.js +24 -6
  61. package/dist/core/model-resolver.js.map +1 -1
  62. package/dist/core/output-throughput-history.d.ts +25 -0
  63. package/dist/core/output-throughput-history.d.ts.map +1 -0
  64. package/dist/core/output-throughput-history.js +240 -0
  65. package/dist/core/output-throughput-history.js.map +1 -0
  66. package/dist/core/output-throughput.d.ts +43 -0
  67. package/dist/core/output-throughput.d.ts.map +1 -0
  68. package/dist/core/output-throughput.js +161 -0
  69. package/dist/core/output-throughput.js.map +1 -0
  70. package/dist/core/resource-loader.d.ts +6 -0
  71. package/dist/core/resource-loader.d.ts.map +1 -1
  72. package/dist/core/resource-loader.js +76 -21
  73. package/dist/core/resource-loader.js.map +1 -1
  74. package/dist/core/scramjet-command-parser.d.ts +4 -0
  75. package/dist/core/scramjet-command-parser.d.ts.map +1 -1
  76. package/dist/core/scramjet-command-parser.js +72 -1
  77. package/dist/core/scramjet-command-parser.js.map +1 -1
  78. package/dist/core/sdk.d.ts +2 -0
  79. package/dist/core/sdk.d.ts.map +1 -1
  80. package/dist/core/sdk.js +61 -10
  81. package/dist/core/sdk.js.map +1 -1
  82. package/dist/core/session-manager.d.ts +11 -3
  83. package/dist/core/session-manager.d.ts.map +1 -1
  84. package/dist/core/session-manager.js +46 -11
  85. package/dist/core/session-manager.js.map +1 -1
  86. package/dist/core/settings-manager.d.ts +19 -6
  87. package/dist/core/settings-manager.d.ts.map +1 -1
  88. package/dist/core/settings-manager.js +131 -17
  89. package/dist/core/settings-manager.js.map +1 -1
  90. package/dist/core/skills.d.ts.map +1 -1
  91. package/dist/core/skills.js +6 -2
  92. package/dist/core/skills.js.map +1 -1
  93. package/dist/core/system-prompt.d.ts +2 -0
  94. package/dist/core/system-prompt.d.ts.map +1 -1
  95. package/dist/core/system-prompt.js +5 -2
  96. package/dist/core/system-prompt.js.map +1 -1
  97. package/dist/core/tools/bash.d.ts.map +1 -1
  98. package/dist/core/tools/bash.js +4 -3
  99. package/dist/core/tools/bash.js.map +1 -1
  100. package/dist/index.d.ts +4 -3
  101. package/dist/index.d.ts.map +1 -1
  102. package/dist/index.js +3 -2
  103. package/dist/index.js.map +1 -1
  104. package/dist/main.d.ts +16 -0
  105. package/dist/main.d.ts.map +1 -1
  106. package/dist/main.js +38 -10
  107. package/dist/main.js.map +1 -1
  108. package/dist/modes/interactive/components/armin.d.ts +4 -2
  109. package/dist/modes/interactive/components/armin.d.ts.map +1 -1
  110. package/dist/modes/interactive/components/armin.js +14 -8
  111. package/dist/modes/interactive/components/armin.js.map +1 -1
  112. package/dist/modes/interactive/components/assistant-message.d.ts +3 -1
  113. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
  114. package/dist/modes/interactive/components/assistant-message.js +19 -8
  115. package/dist/modes/interactive/components/assistant-message.js.map +1 -1
  116. package/dist/modes/interactive/components/daxnuts.d.ts +4 -1
  117. package/dist/modes/interactive/components/daxnuts.d.ts.map +1 -1
  118. package/dist/modes/interactive/components/daxnuts.js +14 -6
  119. package/dist/modes/interactive/components/daxnuts.js.map +1 -1
  120. package/dist/modes/interactive/components/extension-editor.d.ts.map +1 -1
  121. package/dist/modes/interactive/components/extension-editor.js +5 -3
  122. package/dist/modes/interactive/components/extension-editor.js.map +1 -1
  123. package/dist/modes/interactive/components/extension-selector.d.ts.map +1 -1
  124. package/dist/modes/interactive/components/extension-selector.js +4 -3
  125. package/dist/modes/interactive/components/extension-selector.js.map +1 -1
  126. package/dist/modes/interactive/components/footer.d.ts +4 -0
  127. package/dist/modes/interactive/components/footer.d.ts.map +1 -1
  128. package/dist/modes/interactive/components/footer.js +24 -20
  129. package/dist/modes/interactive/components/footer.js.map +1 -1
  130. package/dist/modes/interactive/components/model-selector.d.ts +3 -1
  131. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
  132. package/dist/modes/interactive/components/model-selector.js +9 -3
  133. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  134. package/dist/modes/interactive/components/scoped-models-selector.d.ts +3 -1
  135. package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -1
  136. package/dist/modes/interactive/components/scoped-models-selector.js +8 -2
  137. package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -1
  138. package/dist/modes/interactive/components/settings-selector.d.ts +17 -3
  139. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  140. package/dist/modes/interactive/components/settings-selector.js +87 -16
  141. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  142. package/dist/modes/interactive/components/thinking-selector.d.ts.map +1 -1
  143. package/dist/modes/interactive/components/thinking-selector.js +2 -1
  144. package/dist/modes/interactive/components/thinking-selector.js.map +1 -1
  145. package/dist/modes/interactive/components/tool-execution.d.ts +19 -1
  146. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  147. package/dist/modes/interactive/components/tool-execution.js +129 -36
  148. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  149. package/dist/modes/interactive/components/user-message.d.ts.map +1 -1
  150. package/dist/modes/interactive/components/user-message.js +3 -2
  151. package/dist/modes/interactive/components/user-message.js.map +1 -1
  152. package/dist/modes/interactive/components/visual-truncate.d.ts.map +1 -1
  153. package/dist/modes/interactive/components/visual-truncate.js +2 -2
  154. package/dist/modes/interactive/components/visual-truncate.js.map +1 -1
  155. package/dist/modes/interactive/interactive-mode.d.ts +37 -1
  156. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  157. package/dist/modes/interactive/interactive-mode.js +901 -176
  158. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  159. package/dist/modes/interactive/spellcheck.d.ts +26 -0
  160. package/dist/modes/interactive/spellcheck.d.ts.map +1 -0
  161. package/dist/modes/interactive/spellcheck.js +144 -0
  162. package/dist/modes/interactive/spellcheck.js.map +1 -0
  163. package/dist/modes/interactive/theme/{dark.json → pi-dark.json} +3 -2
  164. package/dist/modes/interactive/theme/{light.json → pi-light.json} +27 -26
  165. package/dist/modes/interactive/theme/theme-schema.json +6 -1
  166. package/dist/modes/interactive/theme/theme.d.ts +24 -4
  167. package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
  168. package/dist/modes/interactive/theme/theme.js +123 -22
  169. package/dist/modes/interactive/theme/theme.js.map +1 -1
  170. package/dist/modes/print-mode.d.ts.map +1 -1
  171. package/dist/modes/print-mode.js +5 -0
  172. package/dist/modes/print-mode.js.map +1 -1
  173. package/dist/modes/rpc/rpc-client.d.ts +3 -1
  174. package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
  175. package/dist/modes/rpc/rpc-client.js.map +1 -1
  176. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  177. package/dist/modes/rpc/rpc-mode.js +6 -1
  178. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  179. package/dist/package-manager-cli.d.ts.map +1 -1
  180. package/dist/package-manager-cli.js +33 -14
  181. package/dist/package-manager-cli.js.map +1 -1
  182. package/dist/utils/clipboard-native.d.ts +1 -0
  183. package/dist/utils/clipboard-native.d.ts.map +1 -1
  184. package/dist/utils/clipboard-native.js.map +1 -1
  185. package/dist/utils/clipboard.d.ts +6 -0
  186. package/dist/utils/clipboard.d.ts.map +1 -1
  187. package/dist/utils/clipboard.js +278 -10
  188. package/dist/utils/clipboard.js.map +1 -1
  189. package/dist/utils/tools-manager.d.ts +1 -1
  190. package/dist/utils/tools-manager.d.ts.map +1 -1
  191. package/dist/utils/tools-manager.js +7 -6
  192. package/dist/utils/tools-manager.js.map +1 -1
  193. package/dist/utils/version-check.d.ts +17 -5
  194. package/dist/utils/version-check.d.ts.map +1 -1
  195. package/dist/utils/version-check.js +88 -21
  196. package/dist/utils/version-check.js.map +1 -1
  197. package/docs/compaction.md +21 -3
  198. package/docs/custom-provider.md +33 -4
  199. package/docs/extensions.md +150 -24
  200. package/docs/json.md +2 -0
  201. package/docs/keybindings.md +25 -1
  202. package/docs/models.md +34 -2
  203. package/docs/packages.md +2 -0
  204. package/docs/prompt-templates.md +2 -0
  205. package/docs/quickstart.md +1 -4
  206. package/docs/rpc.md +8 -6
  207. package/docs/sdk.md +31 -3
  208. package/docs/session-format.md +5 -1
  209. package/docs/settings.md +19 -5
  210. package/docs/skills.md +7 -5
  211. package/docs/terminal-setup.md +79 -2
  212. package/docs/terminal-verification.md +71 -0
  213. package/docs/themes.md +63 -10
  214. package/docs/tui.md +120 -25
  215. package/docs/usage.md +6 -4
  216. package/examples/extensions/border-status-editor.ts +2 -3
  217. package/examples/extensions/doom-overlay/doom-component.ts +3 -3
  218. package/examples/extensions/mac-system-theme.ts +3 -2
  219. package/examples/extensions/modal-editor.ts +13 -8
  220. package/examples/extensions/overlay-qa-tests.ts +22 -9
  221. package/examples/extensions/overlay-test.ts +5 -3
  222. package/examples/extensions/snake.ts +3 -1
  223. package/examples/extensions/space-invaders.ts +6 -3
  224. package/examples/extensions/subagent/index.ts +20 -17
  225. package/package.json +69 -58
@@ -1 +1 @@
1
- {"version":3,"file":"tools-manager.js","sourceRoot":"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ACD,OAAO,SAAS,CAAC;IAClB,CAAC;IAED,mFAAmF;IACnF,8BAA8B;IAC9B,IAAI,QAAQ,EAAE,KAAK,SAAS,EAAE,CAAC;QAC9B,MAAM,OAAO,GAAG,eAAe,CAAC,IAAI,CAAC,IAAI,IAAI,CAAC;QAC9C,IAAI,CAAC,MAAM,EAAE,CAAC;YACb,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,MAAM,CAAC,GAAG,MAAM,CAAC,IAAI,yCAAyC,OAAO,EAAE,CAAC,CAAC,CAAC;QAC7F,CAAC;QACD,OAAO,SAAS,CAAC;IAClB,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,YAAY,CAAC,IAAI,CAAC,CAAC;QACtC,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;AAAA,CACD","sourcesContent":["import chalk from \"chalk\";\nimport { type SpawnSyncReturns, spawnSync } from \"child_process\";\nimport { chmodSync, createWriteStream, existsSync, mkdirSync, readdirSync, renameSync, rmSync } from \"fs\";\nimport { arch, platform } from \"os\";\nimport { join } from \"path\";\nimport { Readable } from \"stream\";\nimport { pipeline } from \"stream/promises\";\nimport { APP_NAME, getBinDir } from \"../config.js\";\n\nconst TOOLS_DIR = getBinDir();\nconst NETWORK_TIMEOUT_MS = 10_000;\nconst DOWNLOAD_TIMEOUT_MS = 120_000;\n\n// SCRAMJET-DIVERGENCE: prefer SCRAMJET_OFFLINE, fall back to PI_OFFLINE.\nfunction isOfflineModeEnabled(): boolean {\n\tconst value = process.env.SCRAMJET_OFFLINE || 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}\n\nconst TOOLS: Record<string, 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\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},\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\" });\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\n// Get the path to a tool (system-wide or in our tools dir)\nexport function getToolPath(tool: \"fd\" | \"rg\"): 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\tfor (const systemBinaryName of systemBinaryNames) {\n\t\tif (commandExists(systemBinaryName)) {\n\t\t\treturn systemBinaryName;\n\t\t}\n\t}\n\n\treturn null;\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\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\" });\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// Download and install a tool\nasync function downloadTool(tool: \"fd\" | \"rg\"): Promise<string> {\n\tconst config = TOOLS[tool];\n\tif (!config) throw new Error(`Unknown tool: ${tool}`);\n\n\tconst plat = platform();\n\tconst architecture = arch();\n\n\t// Get latest version\n\tlet version = 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 archivePath = join(TOOLS_DIR, assetName);\n\tconst binaryExt = plat === \"win32\" ? \".exe\" : \"\";\n\tconst binaryPath = join(TOOLS_DIR, config.binaryName + binaryExt);\n\n\t// Download\n\tawait downloadFile(downloadUrl, archivePath);\n\n\t// Extract into a unique temp directory. fd and rg downloads can run concurrently\n\t// during startup, so sharing a fixed directory causes races.\n\tconst extractDir = join(\n\t\tTOOLS_DIR,\n\t\t`extract_tmp_${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<string, string> = {\n\tfd: \"fd\",\n\trg: \"ripgrep\",\n};\n\n// Ensure a tool is available, downloading if necessary\n// Returns the path to the tool, or null if unavailable\nexport async function ensureTool(tool: \"fd\" | \"rg\", 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, Linux binaries don't work due to Bionic libc incompatibility.\n\t// Users must install via pkg.\n\tif (platform() === \"android\") {\n\t\tconst pkgName = TERMUX_PACKAGES[tool] ?? tool;\n\t\tif (!silent) {\n\t\t\tconsole.log(chalk.yellow(`${config.name} not found. Install with: pkg install ${pkgName}`));\n\t\t}\n\t\treturn undefined;\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 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,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAyB,SAAS,EAAE,MAAM,eAAe,CAAC;AACjE,OAAO,EAAE,SAAS,EAAE,iBAAiB,EAAE,UAAU,EAAE,SAAS,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,IAAI,CAAC;AAC1G,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,IAAI,CAAC;AACpC,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC5B,OAAO,EAAE,QAAQ,EAAE,MAAM,QAAQ,CAAC;AAClC,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEnD,MAAM,SAAS,GAAG,SAAS,EAAE,CAAC;AAC9B,MAAM,kBAAkB,GAAG,MAAM,CAAC;AAClC,MAAM,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AC,IAAI,CAAC,CAAC;QACtC,IAAI,CAAC,MAAM,EAAE,CAAC;YACb,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,MAAM,CAAC,IAAI,iBAAiB,IAAI,EAAE,CAAC,CAAC,CAAC;QAC1D,CAAC;QACD,OAAO,IAAI,CAAC;IACb,CAAC;IAAC,OAAO,CAAC,EAAE,CAAC;QACZ,IAAI,CAAC,MAAM,EAAE,CAAC;YACb,MAAM,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;QAClG,CAAC;QACD,OAAO,SAAS,CAAC;IAClB,CAAC;AAAA,CACD","sourcesContent":["import chalk from \"chalk\";\nimport { type SpawnSyncReturns, spawnSync } from \"child_process\";\nimport { chmodSync, createWriteStream, existsSync, mkdirSync, readdirSync, renameSync, rmSync } from \"fs\";\nimport { arch, platform } from \"os\";\nimport { join } from \"path\";\nimport { Readable } from \"stream\";\nimport { pipeline } from \"stream/promises\";\nimport { APP_NAME, getBinDir } from \"../config.js\";\n\nconst TOOLS_DIR = getBinDir();\nconst NETWORK_TIMEOUT_MS = 10_000;\nconst DOWNLOAD_TIMEOUT_MS = 120_000;\n\n// SCRAMJET-DIVERGENCE: prefer SCRAMJET_OFFLINE, fall back to PI_OFFLINE.\nfunction isOfflineModeEnabled(): boolean {\n\tconst value = process.env.SCRAMJET_OFFLINE || 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}\n\nconst TOOLS: Record<string, 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\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},\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\" });\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\n// Get the path to a tool (system-wide or in our tools dir)\nexport function getToolPath(tool: \"fd\" | \"rg\"): 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\tfor (const systemBinaryName of systemBinaryNames) {\n\t\tif (commandExists(systemBinaryName)) {\n\t\t\treturn systemBinaryName;\n\t\t}\n\t}\n\n\treturn null;\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\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\" });\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// Download and install a tool\nasync function downloadTool(tool: \"fd\" | \"rg\"): Promise<string> {\n\tconst config = TOOLS[tool];\n\tif (!config) throw new Error(`Unknown tool: ${tool}`);\n\n\tconst plat = platform();\n\tconst architecture = arch();\n\n\t// Get latest version\n\tlet version = 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 archivePath = join(TOOLS_DIR, assetName);\n\tconst binaryExt = plat === \"win32\" ? \".exe\" : \"\";\n\tconst binaryPath = join(TOOLS_DIR, config.binaryName + binaryExt);\n\n\t// Download\n\tawait downloadFile(downloadUrl, archivePath);\n\n\t// Extract into a unique temp directory. fd and rg downloads can run concurrently\n\t// during startup, so sharing a fixed directory causes races.\n\tconst extractDir = join(\n\t\tTOOLS_DIR,\n\t\t`extract_tmp_${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<string, string> = {\n\tfd: \"fd\",\n\trg: \"ripgrep\",\n};\n\n// Ensure a tool is available, downloading if necessary\n// Returns the path to the tool, or null if unavailable\n// SCRAMJET-DIVERGENCE: interactive startup owns presentation of provisioning diagnostics.\nexport async function ensureTool(\n\ttool: \"fd\" | \"rg\",\n\tsilent: boolean = false,\n\treport: (message: string) => void = console.log,\n): 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\treport(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, Linux binaries don't work due to Bionic libc incompatibility.\n\t// Users must install via pkg.\n\tif (platform() === \"android\") {\n\t\tconst pkgName = TERMUX_PACKAGES[tool] ?? tool;\n\t\tif (!silent) {\n\t\t\treport(chalk.yellow(`${config.name} not found. Install with: pkg install ${pkgName}`));\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t// Tool not found - download it\n\tif (!silent) {\n\t\treport(chalk.dim(`${config.name} not found. Downloading...`));\n\t}\n\n\ttry {\n\t\tconst path = await downloadTool(tool);\n\t\tif (!silent) {\n\t\t\treport(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\treport(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,9 +1,21 @@
1
- export interface LatestRelease {
1
+ import { type ExecError } from "../core/exec.js";
2
+ export interface CurrentRelease {
3
+ packageName: string;
2
4
  version: string;
3
- packageName?: string;
4
5
  }
6
+ export interface CurrentReleaseExecution {
7
+ stdout: string;
8
+ stderr: string;
9
+ code: number;
10
+ killed: boolean;
11
+ stdoutError?: ExecError;
12
+ stderrError?: ExecError;
13
+ }
14
+ export type CurrentReleaseExecutor = (command: string, args: string[], options: {
15
+ timeout: number;
16
+ }) => Promise<CurrentReleaseExecution>;
17
+ export declare const CURRENT_RELEASE_TIMEOUT_MS = 5000;
5
18
  export declare function isNewerPackageVersion(candidateVersion: string, currentVersion: string): boolean;
6
- export declare function getLatestRelease(_currentVersion: string, _options?: {
7
- timeoutMs?: number;
8
- }): Promise<LatestRelease | undefined>;
19
+ export declare const executeCurrentReleaseLookup: CurrentReleaseExecutor;
20
+ export declare function resolveCurrentRelease(packageName: string, executor?: CurrentReleaseExecutor, timeoutMs?: number, commandPrefix?: string[]): Promise<CurrentRelease>;
9
21
  //# sourceMappingURL=version-check.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"version-check.d.ts","sourceRoot":"","sources":["../../src/utils/version-check.ts"],"names":[],"mappings":"AAGA,MAAM,WAAW,aAAa;IAC7B,OAAO,EAAE,MAAM,CAAC;IAChB,WAAW,CAAC,EAAE,MAAM,CAAC;CACrB;AAsCD,wBAAgB,qBAAqB,CAAC,gBAAgB,EAAE,MAAM,EAAE,cAAc,EAAE,MAAM,GAAG,OAAO,CAM/F;AAED,wBAAsB,gBAAgB,CACrC,eAAe,EAAE,MAAM,EACvB,QAAQ,GAAE;IAAE,SAAS,CAAC,EAAE,MAAM,CAAA;CAAO,GACnC,OAAO,CAAC,aAAa,GAAG,SAAS,CAAC,CAEpC","sourcesContent":["// SCRAMJET-DIVERGENCE: Removed pi.dev network code (LATEST_VERSION_URL, fetch calls);\n// renamed Pi-prefixed identifiers; network functions gutted to return undefined.\n\nexport interface LatestRelease {\n\tversion: string;\n\tpackageName?: string;\n}\n\ninterface ParsedVersion {\n\tmajor: number;\n\tminor: number;\n\tpatch: number;\n\tprerelease?: string;\n}\n\nfunction parsePackageVersion(version: string): ParsedVersion | undefined {\n\tconst match = version.trim().match(/^v?(\\d+)\\.(\\d+)\\.(\\d+)(?:-([0-9A-Za-z.-]+))?(?:\\+.*)?$/);\n\tif (!match) {\n\t\treturn undefined;\n\t}\n\treturn {\n\t\tmajor: Number.parseInt(match[1], 10),\n\t\tminor: Number.parseInt(match[2], 10),\n\t\tpatch: Number.parseInt(match[3], 10),\n\t\tprerelease: match[4],\n\t};\n}\n\nfunction comparePackageVersions(leftVersion: string, rightVersion: string): number | undefined {\n\tconst left = parsePackageVersion(leftVersion);\n\tconst right = parsePackageVersion(rightVersion);\n\tif (!left || !right) {\n\t\treturn undefined;\n\t}\n\n\tif (left.major !== right.major) return left.major - right.major;\n\tif (left.minor !== right.minor) return left.minor - right.minor;\n\tif (left.patch !== right.patch) return left.patch - right.patch;\n\tif (left.prerelease === right.prerelease) return 0;\n\tif (!left.prerelease) return 1;\n\tif (!right.prerelease) return -1;\n\treturn left.prerelease.localeCompare(right.prerelease);\n}\n\nexport function isNewerPackageVersion(candidateVersion: string, currentVersion: string): boolean {\n\tconst comparison = comparePackageVersions(candidateVersion, currentVersion);\n\tif (comparison !== undefined) {\n\t\treturn comparison > 0;\n\t}\n\treturn candidateVersion.trim() !== currentVersion.trim();\n}\n\nexport async function getLatestRelease(\n\t_currentVersion: string,\n\t_options: { timeoutMs?: number } = {},\n): Promise<LatestRelease | undefined> {\n\treturn undefined;\n}\n"]}
1
+ {"version":3,"file":"version-check.d.ts","sourceRoot":"","sources":["../../src/utils/version-check.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,KAAK,SAAS,EAAe,MAAM,iBAAiB,CAAC;AAG9D,MAAM,WAAW,cAAc;IAC9B,WAAW,EAAE,MAAM,CAAC;IACpB,OAAO,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,uBAAuB;IACvC,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,OAAO,CAAC;IAChB,WAAW,CAAC,EAAE,SAAS,CAAC;IACxB,WAAW,CAAC,EAAE,SAAS,CAAC;CACxB;AAED,MAAM,MAAM,sBAAsB,GAAG,CACpC,OAAO,EAAE,MAAM,EACf,IAAI,EAAE,MAAM,EAAE,EACd,OAAO,EAAE;IAAE,OAAO,EAAE,MAAM,CAAA;CAAE,KACxB,OAAO,CAAC,uBAAuB,CAAC,CAAC;AAEtC,eAAO,MAAM,0BAA0B,OAAO,CAAC;AAiE/C,wBAAgB,qBAAqB,CAAC,gBAAgB,EAAE,MAAM,EAAE,cAAc,EAAE,MAAM,GAAG,OAAO,CAE/F;AAED,eAAO,MAAM,2BAA2B,EAAE,sBAazC,CAAC;AAEF,wBAAsB,qBAAqB,CAC1C,WAAW,EAAE,MAAM,EACnB,QAAQ,GAAE,sBAAoD,EAC9D,SAAS,SAA6B,EACtC,aAAa,GAAE,MAAM,EAAY,GAC/B,OAAO,CAAC,cAAc,CAAC,CAwBzB","sourcesContent":["// SCRAMJET-DIVERGENCE: Replaced pi.dev release lookup with validated npm package resolution.\n\nimport { type ExecError, execCommand } from \"../core/exec.js\";\nimport { shouldUseWindowsShell } from \"./child-process.js\";\n\nexport interface CurrentRelease {\n\tpackageName: string;\n\tversion: string;\n}\n\nexport interface CurrentReleaseExecution {\n\tstdout: string;\n\tstderr: string;\n\tcode: number;\n\tkilled: boolean;\n\tstdoutError?: ExecError;\n\tstderrError?: ExecError;\n}\n\nexport type CurrentReleaseExecutor = (\n\tcommand: string,\n\targs: string[],\n\toptions: { timeout: number },\n) => Promise<CurrentReleaseExecution>;\n\nexport const CURRENT_RELEASE_TIMEOUT_MS = 5000;\n\ninterface ParsedVersion {\n\tmajor: string;\n\tminor: string;\n\tpatch: string;\n\tprerelease?: string;\n}\n\nfunction parsePackageVersion(version: string): ParsedVersion | undefined {\n\tconst match = version\n\t\t.trim()\n\t\t.match(\n\t\t\t/^v?(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-([0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*))?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$/,\n\t\t);\n\tif (!match || match[4]?.split(\".\").some((identifier) => /^0\\d+$/.test(identifier))) {\n\t\treturn undefined;\n\t}\n\treturn {\n\t\tmajor: match[1],\n\t\tminor: match[2],\n\t\tpatch: match[3],\n\t\tprerelease: match[4],\n\t};\n}\n\nfunction comparePackageVersions(leftVersion: string, rightVersion: string): number | undefined {\n\tconst left = parsePackageVersion(leftVersion);\n\tconst right = parsePackageVersion(rightVersion);\n\tif (!left || !right) {\n\t\treturn undefined;\n\t}\n\n\tfor (const component of [\"major\", \"minor\", \"patch\"] as const) {\n\t\tif (left[component] === right[component]) continue;\n\t\tif (left[component].length !== right[component].length) {\n\t\t\treturn left[component].length - right[component].length;\n\t\t}\n\t\treturn left[component].localeCompare(right[component]);\n\t}\n\tif (left.prerelease === right.prerelease) return 0;\n\tif (!left.prerelease) return 1;\n\tif (!right.prerelease) return -1;\n\tconst leftIdentifiers = left.prerelease.split(\".\");\n\tconst rightIdentifiers = right.prerelease.split(\".\");\n\tfor (let index = 0; index < Math.max(leftIdentifiers.length, rightIdentifiers.length); index++) {\n\t\tconst leftIdentifier = leftIdentifiers[index];\n\t\tconst rightIdentifier = rightIdentifiers[index];\n\t\tif (leftIdentifier === undefined) return -1;\n\t\tif (rightIdentifier === undefined) return 1;\n\t\tif (leftIdentifier === rightIdentifier) continue;\n\t\tconst leftNumeric = /^\\d+$/.test(leftIdentifier);\n\t\tconst rightNumeric = /^\\d+$/.test(rightIdentifier);\n\t\tif (leftNumeric && rightNumeric) {\n\t\t\tif (leftIdentifier.length !== rightIdentifier.length) return leftIdentifier.length - rightIdentifier.length;\n\t\t\treturn leftIdentifier.localeCompare(rightIdentifier);\n\t\t}\n\t\tif (leftNumeric) return -1;\n\t\tif (rightNumeric) return 1;\n\t\treturn leftIdentifier.localeCompare(rightIdentifier);\n\t}\n\treturn 0;\n}\n\n// SCRAMJET-DIVERGENCE: malformed package versions fail closed for passive update notifications (#432).\nexport function isNewerPackageVersion(candidateVersion: string, currentVersion: string): boolean {\n\treturn (comparePackageVersions(candidateVersion, currentVersion) ?? 0) > 0;\n}\n\nexport const executeCurrentReleaseLookup: CurrentReleaseExecutor = async (command, args, options) => {\n\tconst result = await execCommand(command, args, process.cwd(), {\n\t\ttimeout: options.timeout,\n\t\tshell: shouldUseWindowsShell(command),\n\t});\n\treturn {\n\t\tstdout: result.stdout,\n\t\tstderr: result.stderr || result.spawnError?.message || \"\",\n\t\tcode: result.code,\n\t\tkilled: result.killed,\n\t\tstdoutError: result.stdoutError,\n\t\tstderrError: result.stderrError,\n\t};\n};\n\nexport async function resolveCurrentRelease(\n\tpackageName: string,\n\texecutor: CurrentReleaseExecutor = executeCurrentReleaseLookup,\n\ttimeoutMs = CURRENT_RELEASE_TIMEOUT_MS,\n\tcommandPrefix: string[] = [\"npm\"],\n): Promise<CurrentRelease> {\n\tconst [command, ...prefixArgs] = commandPrefix;\n\tif (!command) throw new Error(\"npm release lookup requires a command\");\n\tconst result = await executor(command, [...prefixArgs, \"view\", packageName, \"version\", \"--json\"], {\n\t\ttimeout: timeoutMs,\n\t});\n\tif (result.stdoutError) throw new Error(`npm release lookup stdout failed: ${result.stdoutError.message}`);\n\tif (result.stderrError) throw new Error(`npm release lookup stderr failed: ${result.stderrError.message}`);\n\tif (result.killed) throw new Error(`npm release lookup timed out after ${timeoutMs}ms`);\n\tif (result.code !== 0) {\n\t\tconst detail = result.stderr.trim();\n\t\tthrow new Error(`npm release lookup failed with exit code ${result.code}${detail ? `: ${detail}` : \"\"}`);\n\t}\n\n\tlet version: unknown;\n\ttry {\n\t\tversion = JSON.parse(result.stdout);\n\t} catch {\n\t\tthrow new Error(\"npm release lookup returned malformed JSON\");\n\t}\n\tif (typeof version !== \"string\" || !parsePackageVersion(version)) {\n\t\tthrow new Error(\"npm release lookup returned an invalid package version\");\n\t}\n\treturn { packageName, version };\n}\n"]}
@@ -1,14 +1,18 @@
1
- // SCRAMJET-DIVERGENCE: Removed pi.dev network code (LATEST_VERSION_URL, fetch calls);
2
- // renamed Pi-prefixed identifiers; network functions gutted to return undefined.
1
+ // SCRAMJET-DIVERGENCE: Replaced pi.dev release lookup with validated npm package resolution.
2
+ import { execCommand } from "../core/exec.js";
3
+ import { shouldUseWindowsShell } from "./child-process.js";
4
+ export const CURRENT_RELEASE_TIMEOUT_MS = 5000;
3
5
  function parsePackageVersion(version) {
4
- const match = version.trim().match(/^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+.*)?$/);
5
- if (!match) {
6
+ const match = version
7
+ .trim()
8
+ .match(/^v?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/);
9
+ if (!match || match[4]?.split(".").some((identifier) => /^0\d+$/.test(identifier))) {
6
10
  return undefined;
7
11
  }
8
12
  return {
9
- major: Number.parseInt(match[1], 10),
10
- minor: Number.parseInt(match[2], 10),
11
- patch: Number.parseInt(match[3], 10),
13
+ major: match[1],
14
+ minor: match[2],
15
+ patch: match[3],
12
16
  prerelease: match[4],
13
17
  };
14
18
  }
@@ -18,28 +22,91 @@ function comparePackageVersions(leftVersion, rightVersion) {
18
22
  if (!left || !right) {
19
23
  return undefined;
20
24
  }
21
- if (left.major !== right.major)
22
- return left.major - right.major;
23
- if (left.minor !== right.minor)
24
- return left.minor - right.minor;
25
- if (left.patch !== right.patch)
26
- return left.patch - right.patch;
25
+ for (const component of ["major", "minor", "patch"]) {
26
+ if (left[component] === right[component])
27
+ continue;
28
+ if (left[component].length !== right[component].length) {
29
+ return left[component].length - right[component].length;
30
+ }
31
+ return left[component].localeCompare(right[component]);
32
+ }
27
33
  if (left.prerelease === right.prerelease)
28
34
  return 0;
29
35
  if (!left.prerelease)
30
36
  return 1;
31
37
  if (!right.prerelease)
32
38
  return -1;
33
- return left.prerelease.localeCompare(right.prerelease);
39
+ const leftIdentifiers = left.prerelease.split(".");
40
+ const rightIdentifiers = right.prerelease.split(".");
41
+ for (let index = 0; index < Math.max(leftIdentifiers.length, rightIdentifiers.length); index++) {
42
+ const leftIdentifier = leftIdentifiers[index];
43
+ const rightIdentifier = rightIdentifiers[index];
44
+ if (leftIdentifier === undefined)
45
+ return -1;
46
+ if (rightIdentifier === undefined)
47
+ return 1;
48
+ if (leftIdentifier === rightIdentifier)
49
+ continue;
50
+ const leftNumeric = /^\d+$/.test(leftIdentifier);
51
+ const rightNumeric = /^\d+$/.test(rightIdentifier);
52
+ if (leftNumeric && rightNumeric) {
53
+ if (leftIdentifier.length !== rightIdentifier.length)
54
+ return leftIdentifier.length - rightIdentifier.length;
55
+ return leftIdentifier.localeCompare(rightIdentifier);
56
+ }
57
+ if (leftNumeric)
58
+ return -1;
59
+ if (rightNumeric)
60
+ return 1;
61
+ return leftIdentifier.localeCompare(rightIdentifier);
62
+ }
63
+ return 0;
34
64
  }
65
+ // SCRAMJET-DIVERGENCE: malformed package versions fail closed for passive update notifications (#432).
35
66
  export function isNewerPackageVersion(candidateVersion, currentVersion) {
36
- const comparison = comparePackageVersions(candidateVersion, currentVersion);
37
- if (comparison !== undefined) {
38
- return comparison > 0;
39
- }
40
- return candidateVersion.trim() !== currentVersion.trim();
67
+ return (comparePackageVersions(candidateVersion, currentVersion) ?? 0) > 0;
41
68
  }
42
- export async function getLatestRelease(_currentVersion, _options = {}) {
43
- return undefined;
69
+ export const executeCurrentReleaseLookup = async (command, args, options) => {
70
+ const result = await execCommand(command, args, process.cwd(), {
71
+ timeout: options.timeout,
72
+ shell: shouldUseWindowsShell(command),
73
+ });
74
+ return {
75
+ stdout: result.stdout,
76
+ stderr: result.stderr || result.spawnError?.message || "",
77
+ code: result.code,
78
+ killed: result.killed,
79
+ stdoutError: result.stdoutError,
80
+ stderrError: result.stderrError,
81
+ };
82
+ };
83
+ export async function resolveCurrentRelease(packageName, executor = executeCurrentReleaseLookup, timeoutMs = CURRENT_RELEASE_TIMEOUT_MS, commandPrefix = ["npm"]) {
84
+ const [command, ...prefixArgs] = commandPrefix;
85
+ if (!command)
86
+ throw new Error("npm release lookup requires a command");
87
+ const result = await executor(command, [...prefixArgs, "view", packageName, "version", "--json"], {
88
+ timeout: timeoutMs,
89
+ });
90
+ if (result.stdoutError)
91
+ throw new Error(`npm release lookup stdout failed: ${result.stdoutError.message}`);
92
+ if (result.stderrError)
93
+ throw new Error(`npm release lookup stderr failed: ${result.stderrError.message}`);
94
+ if (result.killed)
95
+ throw new Error(`npm release lookup timed out after ${timeoutMs}ms`);
96
+ if (result.code !== 0) {
97
+ const detail = result.stderr.trim();
98
+ throw new Error(`npm release lookup failed with exit code ${result.code}${detail ? `: ${detail}` : ""}`);
99
+ }
100
+ let version;
101
+ try {
102
+ version = JSON.parse(result.stdout);
103
+ }
104
+ catch {
105
+ throw new Error("npm release lookup returned malformed JSON");
106
+ }
107
+ if (typeof version !== "string" || !parsePackageVersion(version)) {
108
+ throw new Error("npm release lookup returned an invalid package version");
109
+ }
110
+ return { packageName, version };
44
111
  }
45
112
  //# sourceMappingURL=version-check.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"version-check.js","sourceRoot":"","sources":["../../src/utils/version-check.ts"],"names":[],"mappings":"AAAA,sFAAsF;AACtF,iFAAiF;AAcjF,SAAS,mBAAmB,CAAC,OAAe,EAA6B;IACxE,MAAM,KAAK,GAAG,OAAO,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,wDAAwD,CAAC,CAAC;IAC7F,IAAI,CAAC,KAAK,EAAE,CAAC;QACZ,OAAO,SAAS,CAAC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A,CACvD;AAED,MAAM,UAAU,qBAAqB,CAAC,gBAAwB,EAAE,cAAsB,EAAW;IAChG,MAAM,UAAU,GAAG,sBAAsB,CAAC,gBAAgB,EAAE,cAAc,CAAC,CAAC;IAC5E,IAAI,UAAU,KAAK,SAAS,EAAE,CAAC;QAC9B,OAAO,UAAU,GAAG,CAAC,CAAC;IACvB,CAAC;IACD,OAAO,gBAAgB,CAAC,IAAI,EAAE,KAAK,cAAc,CAAC,IAAI,EAAE,CAAC;AAAA,CACzD;AAED,MAAM,CAAC,KAAK,UAAU,gBAAgB,CACrC,eAAuB,EACvB,QAAQ,GAA2B,EAAE,EACA;IACrC,OAAO,SAAS,CAAC;AAAA,CACjB","sourcesContent":["// SCRAMJET-DIVERGENCE: Removed pi.dev network code (LATEST_VERSION_URL, fetch calls);\n// renamed Pi-prefixed identifiers; network functions gutted to return undefined.\n\nexport interface LatestRelease {\n\tversion: string;\n\tpackageName?: string;\n}\n\ninterface ParsedVersion {\n\tmajor: number;\n\tminor: number;\n\tpatch: number;\n\tprerelease?: string;\n}\n\nfunction parsePackageVersion(version: string): ParsedVersion | undefined {\n\tconst match = version.trim().match(/^v?(\\d+)\\.(\\d+)\\.(\\d+)(?:-([0-9A-Za-z.-]+))?(?:\\+.*)?$/);\n\tif (!match) {\n\t\treturn undefined;\n\t}\n\treturn {\n\t\tmajor: Number.parseInt(match[1], 10),\n\t\tminor: Number.parseInt(match[2], 10),\n\t\tpatch: Number.parseInt(match[3], 10),\n\t\tprerelease: match[4],\n\t};\n}\n\nfunction comparePackageVersions(leftVersion: string, rightVersion: string): number | undefined {\n\tconst left = parsePackageVersion(leftVersion);\n\tconst right = parsePackageVersion(rightVersion);\n\tif (!left || !right) {\n\t\treturn undefined;\n\t}\n\n\tif (left.major !== right.major) return left.major - right.major;\n\tif (left.minor !== right.minor) return left.minor - right.minor;\n\tif (left.patch !== right.patch) return left.patch - right.patch;\n\tif (left.prerelease === right.prerelease) return 0;\n\tif (!left.prerelease) return 1;\n\tif (!right.prerelease) return -1;\n\treturn left.prerelease.localeCompare(right.prerelease);\n}\n\nexport function isNewerPackageVersion(candidateVersion: string, currentVersion: string): boolean {\n\tconst comparison = comparePackageVersions(candidateVersion, currentVersion);\n\tif (comparison !== undefined) {\n\t\treturn comparison > 0;\n\t}\n\treturn candidateVersion.trim() !== currentVersion.trim();\n}\n\nexport async function getLatestRelease(\n\t_currentVersion: string,\n\t_options: { timeoutMs?: number } = {},\n): Promise<LatestRelease | undefined> {\n\treturn undefined;\n}\n"]}
1
+ {"version":3,"file":"version-check.js","sourceRoot":"","sources":["../../src/utils/version-check.ts"],"names":[],"mappings":"AAAA,6FAA6F;AAE7F,OAAO,EAAkB,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAC9D,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAsB3D,MAAM,CAAC,MAAM,0BAA0B,GAAG,IAAI,CAAC;AAS/C,SAAS,mBAAmB,CAAC,OAAe,EAA6B;IACxE,MAAM,KAAK,GAAG,OAAO;SACnB,IAAI,EAAE;SACN,KAAK,CACL,+HAA+H,CAC/H,CAAC;IACH,IAAI,CAAC,KAAK,IAAI,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC,UAAU,EAAE,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,EAAE,CAAC;QACpF,OAAO,SAAS,CAAC;IAClB,CAAC;IACD,OAAO;QACN,KAAK,EAAE,KAAK,CAAC,CAAC,CAAC;QACf,KAAK,EAAE,KAAK,CAAC,CAAC,CAAC;QACf,KAAK,EAAE,KAAK,CAAC,CAAC,CAAC;QACf,UAAU,EAAE,KAAK,CAAC,CAAC,CAAC;KACpB,CAAC;AAAA,CACF;AAED,SAAS,sBAAsB,CAAC,WAAmB,EAAE,YAAoB,EAAsB;IAC9F,MAAM,IAAI,GAAG,mBAAmB,CAAC,WAAW,CAAC,CAAC;IAC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C,MAAM,CAAC,IAAI,GAAG,MAAM,CAAC,CAAC,CAAC,KAAK,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;IAC1G,CAAC;IAED,IAAI,OAAgB,CAAC;IACrB,IAAI,CAAC;QACJ,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;IACrC,CAAC;IAAC,MAAM,CAAC;QACR,MAAM,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAC;IAC/D,CAAC;IACD,IAAI,OAAO,OAAO,KAAK,QAAQ,IAAI,CAAC,mBAAmB,CAAC,OAAO,CAAC,EAAE,CAAC;QAClE,MAAM,IAAI,KAAK,CAAC,wDAAwD,CAAC,CAAC;IAC3E,CAAC;IACD,OAAO,EAAE,WAAW,EAAE,OAAO,EAAE,CAAC;AAAA,CAChC","sourcesContent":["// SCRAMJET-DIVERGENCE: Replaced pi.dev release lookup with validated npm package resolution.\n\nimport { type ExecError, execCommand } from \"../core/exec.js\";\nimport { shouldUseWindowsShell } from \"./child-process.js\";\n\nexport interface CurrentRelease {\n\tpackageName: string;\n\tversion: string;\n}\n\nexport interface CurrentReleaseExecution {\n\tstdout: string;\n\tstderr: string;\n\tcode: number;\n\tkilled: boolean;\n\tstdoutError?: ExecError;\n\tstderrError?: ExecError;\n}\n\nexport type CurrentReleaseExecutor = (\n\tcommand: string,\n\targs: string[],\n\toptions: { timeout: number },\n) => Promise<CurrentReleaseExecution>;\n\nexport const CURRENT_RELEASE_TIMEOUT_MS = 5000;\n\ninterface ParsedVersion {\n\tmajor: string;\n\tminor: string;\n\tpatch: string;\n\tprerelease?: string;\n}\n\nfunction parsePackageVersion(version: string): ParsedVersion | undefined {\n\tconst match = version\n\t\t.trim()\n\t\t.match(\n\t\t\t/^v?(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-([0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*))?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$/,\n\t\t);\n\tif (!match || match[4]?.split(\".\").some((identifier) => /^0\\d+$/.test(identifier))) {\n\t\treturn undefined;\n\t}\n\treturn {\n\t\tmajor: match[1],\n\t\tminor: match[2],\n\t\tpatch: match[3],\n\t\tprerelease: match[4],\n\t};\n}\n\nfunction comparePackageVersions(leftVersion: string, rightVersion: string): number | undefined {\n\tconst left = parsePackageVersion(leftVersion);\n\tconst right = parsePackageVersion(rightVersion);\n\tif (!left || !right) {\n\t\treturn undefined;\n\t}\n\n\tfor (const component of [\"major\", \"minor\", \"patch\"] as const) {\n\t\tif (left[component] === right[component]) continue;\n\t\tif (left[component].length !== right[component].length) {\n\t\t\treturn left[component].length - right[component].length;\n\t\t}\n\t\treturn left[component].localeCompare(right[component]);\n\t}\n\tif (left.prerelease === right.prerelease) return 0;\n\tif (!left.prerelease) return 1;\n\tif (!right.prerelease) return -1;\n\tconst leftIdentifiers = left.prerelease.split(\".\");\n\tconst rightIdentifiers = right.prerelease.split(\".\");\n\tfor (let index = 0; index < Math.max(leftIdentifiers.length, rightIdentifiers.length); index++) {\n\t\tconst leftIdentifier = leftIdentifiers[index];\n\t\tconst rightIdentifier = rightIdentifiers[index];\n\t\tif (leftIdentifier === undefined) return -1;\n\t\tif (rightIdentifier === undefined) return 1;\n\t\tif (leftIdentifier === rightIdentifier) continue;\n\t\tconst leftNumeric = /^\\d+$/.test(leftIdentifier);\n\t\tconst rightNumeric = /^\\d+$/.test(rightIdentifier);\n\t\tif (leftNumeric && rightNumeric) {\n\t\t\tif (leftIdentifier.length !== rightIdentifier.length) return leftIdentifier.length - rightIdentifier.length;\n\t\t\treturn leftIdentifier.localeCompare(rightIdentifier);\n\t\t}\n\t\tif (leftNumeric) return -1;\n\t\tif (rightNumeric) return 1;\n\t\treturn leftIdentifier.localeCompare(rightIdentifier);\n\t}\n\treturn 0;\n}\n\n// SCRAMJET-DIVERGENCE: malformed package versions fail closed for passive update notifications (#432).\nexport function isNewerPackageVersion(candidateVersion: string, currentVersion: string): boolean {\n\treturn (comparePackageVersions(candidateVersion, currentVersion) ?? 0) > 0;\n}\n\nexport const executeCurrentReleaseLookup: CurrentReleaseExecutor = async (command, args, options) => {\n\tconst result = await execCommand(command, args, process.cwd(), {\n\t\ttimeout: options.timeout,\n\t\tshell: shouldUseWindowsShell(command),\n\t});\n\treturn {\n\t\tstdout: result.stdout,\n\t\tstderr: result.stderr || result.spawnError?.message || \"\",\n\t\tcode: result.code,\n\t\tkilled: result.killed,\n\t\tstdoutError: result.stdoutError,\n\t\tstderrError: result.stderrError,\n\t};\n};\n\nexport async function resolveCurrentRelease(\n\tpackageName: string,\n\texecutor: CurrentReleaseExecutor = executeCurrentReleaseLookup,\n\ttimeoutMs = CURRENT_RELEASE_TIMEOUT_MS,\n\tcommandPrefix: string[] = [\"npm\"],\n): Promise<CurrentRelease> {\n\tconst [command, ...prefixArgs] = commandPrefix;\n\tif (!command) throw new Error(\"npm release lookup requires a command\");\n\tconst result = await executor(command, [...prefixArgs, \"view\", packageName, \"version\", \"--json\"], {\n\t\ttimeout: timeoutMs,\n\t});\n\tif (result.stdoutError) throw new Error(`npm release lookup stdout failed: ${result.stdoutError.message}`);\n\tif (result.stderrError) throw new Error(`npm release lookup stderr failed: ${result.stderrError.message}`);\n\tif (result.killed) throw new Error(`npm release lookup timed out after ${timeoutMs}ms`);\n\tif (result.code !== 0) {\n\t\tconst detail = result.stderr.trim();\n\t\tthrow new Error(`npm release lookup failed with exit code ${result.code}${detail ? `: ${detail}` : \"\"}`);\n\t}\n\n\tlet version: unknown;\n\ttry {\n\t\tversion = JSON.parse(result.stdout);\n\t} catch {\n\t\tthrow new Error(\"npm release lookup returned malformed JSON\");\n\t}\n\tif (typeof version !== \"string\" || !parsePackageVersion(version)) {\n\t\tthrow new Error(\"npm release lookup returned an invalid package version\");\n\t}\n\treturn { packageName, version };\n}\n"]}
@@ -32,10 +32,28 @@ Auto-compaction triggers when:
32
32
  contextTokens > contextWindow - reserveTokens
33
33
  ```
34
34
 
35
- By default, `reserveTokens` is 16384 tokens (configurable in `~/.scramjet/agent/settings.json` or `<project-dir>/.scramjet/settings.json`). This leaves room for the LLM's response.
35
+ `contextWindow` is the selected provider/model's maximum supported total context, also used by the footer and usage percentages. The default `reserveTokens` is 16384 (configurable in `~/.scramjet/agent/settings.json` or `<project-dir>/.scramjet/settings.json`). With 1,050,000 total context, 1,033,616 tokens does not trigger threshold compaction; 1,033,617 does. There is no lower pricing or quality budget and no global subtraction of maximum output. Auto-compaction remains disabled when the reserve consumes the whole context; reduce the reserve rather than inventing a larger model maximum.
36
+
37
+ An applicable `maxInputTokens` is checked separately, without subtracting output reserve from that input-only limit. Request allocation and both built-in summarizers use approximate message/system/tool estimates, aided by same-model usage when available, to reject estimated input breaches and limit requested output to remaining total space. Reserve is not subtracted again. Estimates are not exact tokenization or an upper bound, and later payload replacements can invalidate them; real provider overflow handling remains necessary.
38
+
39
+ Explicit output limits include thinking in the Anthropic and Bedrock simple adapters. Too little space for minimum token-based thinking produces an actionable error, not silent reasoning disablement. Codex does not serialize an output limit, so its output allocation is not wire-enforced. OpenRouter ordinary requests omit an implicit aggregate output maximum to avoid excluding long-context routes; explicit summary limits remain bounded. When provider-evidenced `requestLimits` are present, both allocation implementations keep each endpoint's total/input/output constraints together and require tool support for requests containing tools. Explicit output is capped by the largest compatible endpoint allowance, including Vercel's required output field; no compatible entry produces an actionable error. Scalar context/output maxima and reserve accounting remain unchanged. See [models.md](models.md#joint-endpoint-constraints) for metadata validation and the remaining custom-routing, capability, and account qualifications.
40
+
41
+ Validated provider overflow and typed local context-allocation overflow retain bounded one-attempt recovery. Arbitrary harness, callback, local-configuration, aborted, invalid-evidence, retry-suppressed, and explicitly unknown/provider-error/malformed-event failures do not initiate automatic recovery or failure-triggered threshold compaction. When authoritative evidence is absent, legacy provider overflow recognition remains supported.
42
+
43
+ A new user prompt independently checks threshold maintenance using trustworthy successful usage for the current model after the latest compaction boundary, plus trailing-message estimates. It does not revive the previous error as another overflow-recovery request. Manual compaction is unchanged. This does not fix the separate continuous-tool-run compaction/recovery work in [#526](https://github.com/LeanAndMean/scramjet/issues/526).
36
44
 
37
45
  You can also trigger manually with `/compact [instructions]`, where optional instructions focus the summary.
38
46
 
47
+ ### Manual admission and terminal drain
48
+
49
+ Manual compaction has one owner. It rejects while manual/automatic compaction or branch summarization is in progress, or while an idle-origin harness tool is still executing. Refusal leaves execution, abort signals, accounting, subscriptions, and context untouched. Await the conflicting operation's persisted settlement before deliberately retrying; requests are not queued.
50
+
51
+ An admitted request cancels the active Agent run and drains prior and terminal message processing before preparing the summary. Final `message_end` hooks, message replacement, subscriber notification, persistence, and cost handoff still run. Internal prompt/retry and already-admitted harness obligations settle, but queued/new run/turn lifecycle hooks and subscribers, retries, continuations, and automatic compaction are suppressed during the drain. Tool-result execution hooks are not replayed. New session `invokeHarnessTool()` admissions reject throughout manual ownership; this is not a lock on direct underlying Agent calls.
52
+
53
+ Abort/drain/persistence failure rejects compaction without appending its entry or reconstructing context from an incomplete journal. Recorded in-memory costs remain included; no automatic persistence retry or durability guarantee is added. Normal event subscription is restored on success/failure unless the session was disposed.
54
+
55
+ These rules apply to SDK `session.compact()`, interactive `/compact`, RPC `compact` (failure response), and extension `ctx.compact()` (`onError`). A refused contender does not emit the owner's completion or cancel it. Message hooks should use the fire-and-forget `ctx.compact()` callbacks, not await compaction from work the drain needs to finish.
56
+
39
57
  ### How It Works
40
58
 
41
59
  1. **Find cut point**: Walk backwards from newest message, accumulating token estimates until `keepRecentTokens` (default 20k, configurable in `~/.scramjet/agent/settings.json` or `<project-dir>/.scramjet/settings.json`) is reached
@@ -154,8 +172,8 @@ When you use `/tree` to navigate to a different branch, Scramjet offers to summa
154
172
 
155
173
  1. **Find common ancestor**: Deepest node shared by old and new positions
156
174
  2. **Collect entries**: Walk from old leaf back to common ancestor
157
- 3. **Prepare with budget**: Include messages up to token budget (newest first)
158
- 4. **Generate summary**: Call LLM with structured format
175
+ 3. **Prepare content**: Include entries within `contextWindow - reserveTokens` (newest first), additionally bounded by any input constraint minus estimated fixed prompt overhead; retain the existing minimum-one-token selection clamp
176
+ 4. **Generate summary**: Check the constructed prompt (including instructions and previous summaries), then allocate output from remaining total context; an oversized request fails without silently truncating history
159
177
  5. **Append entry**: Save `BranchSummaryEntry` at navigation point
160
178
 
161
179
  ```
@@ -62,6 +62,10 @@ export default function (pi: ExtensionAPI) {
62
62
 
63
63
  The extension factory can also be `async`. For dynamic model discovery, fetch and register models in the factory instead of `session_start`. Scramjet waits for the factory before startup continues, so the provider is available during interactive startup and to `scramjet --list-models`.
64
64
 
65
+ Set `contextWindow` to the maximum supported total context for this provider/model. A genuine independently evidenced input constraint may use `maxInputTokens`; never use it for price, quality, or speculative headroom. Final context and input values must be positive finite numbers. `contextWindowBudget` is rejected with an actionable provider/model diagnostic, not silently ignored or copied. See [models.md](models.md#breaking-migration-from-context-budgets) for migration and preserved configuration/OAuth fallback semantics.
66
+
67
+ Coding-agent sessions check estimated request input and allocate output from remaining total context before dispatch, additionally honoring provider-declared joint `requestLimits` when present (see [models.md](models.md#joint-endpoint-constraints)). Custom transports, direct AI callers, and payload-replacement hooks remain responsible for their actual request constraints. Explicit `SimpleStreamOptions.maxTokens` now bounds combined output including token-based thinking in Anthropic/Bedrock adapters. The estimates are not a tokenizer or proof of provider acceptance; see [compaction.md](compaction.md).
68
+
65
69
  ## Override Existing Provider
66
70
 
67
71
  The simplest use case: redirect an existing provider through a proxy.
@@ -511,6 +515,26 @@ output.usage.totalTokens = output.usage.input + output.usage.output +
511
515
  calculateCost(model, output.usage);
512
516
  ```
513
517
 
518
+ ### Failure Evidence
519
+
520
+ `@leanandmean/ai` exports `RequestFailureV1`, `RetrySuppressionV1`, `appendRequestFailure`, `validateRequestFailure`, and `inspectFailureEvidence`. Optional diagnostics persist in the existing assistant message envelope. A `request_failure` diagnostic has `details.schemaVersion: 1` and exactly one closed branch:
521
+
522
+ - `kind: "http"`, numeric integer `status` from 400 through 599, and `reason: "status"` or a recognized semantic rejection.
523
+ - `kind: "provider"` and a closed semantic `category` (for example `rate_limit`, `quota_exhausted`, or `context_overflow`).
524
+ - `kind: "stream"` and `reason: "missing_body"`, `"missing_terminal_event"`, `"transport"`, `"timeout"`, or `"malformed_event"`.
525
+ - `kind: "callback"` and `callback: "onPayload"` or `"onResponse"`.
526
+ - `kind: "local"` and `reason: "request_preparation"`, `"request_validation"`, `"configuration"`, or `"context_overflow"`. The last is reserved for witnessed local context allocation failure, not arbitrary error prose.
527
+
528
+ Use the exported TypeScript union as the complete vocabulary. AI's neutral evidence utility validates both primary families; the Responses validator remains available from its existing public subpath. Unknown keys, invalid values, duplicate recognized diagnostics, and simultaneous `request_failure` and Responses `provider_failure` evidence fail closed. HTTP 401/403/404 cannot authorize overflow or override their terminal status category; explicit HTTP overflow evidence is compatible only with 400/413/422. Previously accepted contradictory version-1 records remain readable in sessions but no longer validate for recovery; no journal migration is required. Do not emit two primary failure families for one failure. Valid evidence takes precedence over retry and overflow prose; absent evidence preserves legacy custom-provider behavior. Stream completeness failures may be retried within configured limits without asserting their cause was transient. The existing Responses EOF diagnostic remains `unknown`; session policy explicitly admits its canonical category.
529
+
530
+ Separate `retry_suppression` evidence vetoes retries without changing the provider cause. Version 1 accepts `server_delay_exceeds_limit` with finite safe `requestedDelayMs > maxDelayMs > 0`, or `invalid_server_delay` with no raw value. It must accompany one valid transient primary failure. Orphaned, malformed, duplicate or inconsistent suppression blocks automatic recovery. These records are evidence, not durable retry queues; reopening a session does not restart retries.
531
+
532
+ Built-in failure catches preserve an existing primary diagnosis, classify witnessed failures at their source, and emit explicit unknown evidence when available facts do not establish a category. Unknown, provider-error, and malformed-event evidence blocks both retry and failure-triggered compaction, even when preceding usage is high. This is not a universal enforcement guarantee for future adapters or trusted extension replacements. Independent new-prompt maintenance and evidence-absent legacy custom providers retain their existing behavior.
533
+
534
+ Callback failures must never be inferred from provider prose or persist original callback exception details. Message origin describes who produced the message, not which operation failed. Retain partial provider output and mark the callback failure separately.
535
+
536
+ Completeness coverage is route-qualified: shared Responses, Chat's existing finish-reason check, and started Anthropic streams detect missing terminals. Additional mandatory markers for Google/Vertex, Mistral, Bedrock and startless Anthropic SSE were not established from installed SDK contracts and are not enforced. In particular, Google prompt-feedback blocking can occur without a candidate finish reason; parser acceptance alone does not establish valid backend completion. The installed Google SDK exposes bodyless generation failures as plain errors without a supported raw-response hook; Google/Vertex therefore retain an explicit unknown diagnosis rather than inferring body absence from the error message. Chat and Mistral classify body absence from their available response objects. Responses and default Chat/Anthropic clients distinguish local SDK preparation from dispatch at the invocation-local fetch boundary, not from observational SDK-attempt diagnostics or a generic `TypeError`.
537
+
514
538
  ### Context Overflow Errors
515
539
 
516
540
  When a request exceeds the model's context window, scramjet can recover automatically by compacting the conversation and retrying. This recovery only kicks in if scramjet recognizes the failure as an overflow.
@@ -518,9 +542,9 @@ When a request exceeds the model's context window, scramjet can recover automati
518
542
  Detection runs on the finalized assistant message:
519
543
 
520
544
  - `stopReason === "error"`
521
- - `errorMessage` matches one of scramjet's known overflow patterns (see [`packages/ai/src/utils/overflow.ts`](https://github.com/earendil-works/pi-mono/blob/main/packages/ai/src/utils/overflow.ts))
545
+ - Without authoritative failure evidence, `errorMessage` matches one of scramjet's known overflow patterns (see [`packages/ai/src/utils/overflow.ts`](https://github.com/earendil-works/pi-mono/blob/main/packages/ai/src/utils/overflow.ts)). With recognized failure evidence, its validated category determines overflow instead of message text.
522
546
 
523
- If your provider returns overflow errors with a message scramjet does not recognize, normalize the error from the same extension that registers the provider. Use a `message_end` handler to rewrite the assistant message so its `errorMessage` starts with a phrase scramjet recognizes. The generic fallback `context_length_exceeded` is the safest choice.
547
+ If your provider returns overflow errors without any authoritative failure evidence and with a message scramjet does not recognize, normalize the error from the same extension that registers the provider. Use a `message_end` handler to rewrite the assistant message so its `errorMessage` starts with a phrase scramjet recognizes. The generic fallback `context_length_exceeded` is the safest choice. For a provider that emits `request_failure` or Responses `provider_failure` diagnostics, classify overflow at the provider-error source; rewriting `errorMessage` alone cannot override present evidence. Shared Responses adapters can also record a bounded local snapshot of unfamiliar error fields separately from the readable `errorMessage`; this snapshot is display-only and never grants retry or compaction.
524
548
 
525
549
  ```typescript
526
550
  const MY_PROVIDER_OVERFLOW_PATTERN = /your provider's overflow phrase/i;
@@ -552,7 +576,7 @@ export default function (pi: ExtensionAPI) {
552
576
  }
553
577
  ```
554
578
 
555
- `message_end` runs before scramjet tracks the assistant message for auto-compaction, so the rewritten `errorMessage` is what scramjet checks. With this in place, scramjet will:
579
+ `message_end` runs before scramjet tracks the assistant message for auto-compaction. When there is no authoritative failure diagnostic, the rewritten `errorMessage` is what scramjet checks. With this in place, scramjet will:
556
580
 
557
581
  1. Detect the overflow from `errorMessage`.
558
582
  2. Drop the failed assistant message from live context.
@@ -675,9 +699,14 @@ interface ProviderModelConfig {
675
699
  cacheWrite: number;
676
700
  };
677
701
 
678
- /** Maximum context window size in tokens. */
702
+ /** Maximum supported total context in tokens. */
679
703
  contextWindow: number;
680
704
 
705
+ /** Genuine independently evidenced provider input limit. */
706
+ maxInputTokens?: number;
707
+
708
+ requestLimits?: Model<Api>["requestLimits"];
709
+
681
710
  /** Maximum output tokens. */
682
711
  maxTokens: number;
683
712