@trenchwork/erosolar 1.1.30 → 1.1.31

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.

Potentially problematic release.


This version of @trenchwork/erosolar might be problematic. Click here for more details.

Files changed (799) hide show
  1. package/README.md +6 -6
  2. package/SECURITY.md +4 -4
  3. package/dist/bin/cliMode.d.ts +8 -0
  4. package/dist/bin/cliMode.d.ts.map +1 -0
  5. package/dist/bin/cliMode.js +20 -0
  6. package/dist/bin/cliMode.js.map +1 -0
  7. package/dist/bin/deepseek.d.ts +3 -0
  8. package/dist/bin/deepseek.d.ts.map +1 -0
  9. package/dist/bin/deepseek.js +332 -0
  10. package/dist/bin/deepseek.js.map +1 -0
  11. package/dist/bin/erosolar.d.ts +7 -0
  12. package/dist/bin/erosolar.d.ts.map +1 -0
  13. package/dist/bin/erosolar.js +7 -0
  14. package/dist/bin/erosolar.js.map +1 -0
  15. package/dist/bin/selfTest.d.ts +14 -0
  16. package/dist/bin/selfTest.d.ts.map +1 -0
  17. package/dist/bin/selfTest.js +298 -0
  18. package/dist/bin/selfTest.js.map +1 -0
  19. package/dist/capabilities/_processRunner.d.ts +17 -0
  20. package/dist/capabilities/_processRunner.d.ts.map +1 -0
  21. package/dist/capabilities/_processRunner.js +74 -0
  22. package/dist/capabilities/_processRunner.js.map +1 -0
  23. package/dist/capabilities/aflppCapability.d.ts +7 -0
  24. package/dist/capabilities/aflppCapability.d.ts.map +1 -0
  25. package/dist/capabilities/aflppCapability.js +301 -0
  26. package/dist/capabilities/aflppCapability.js.map +1 -0
  27. package/dist/capabilities/baseCapability.d.ts +72 -0
  28. package/dist/capabilities/baseCapability.d.ts.map +1 -0
  29. package/dist/capabilities/baseCapability.js +183 -0
  30. package/dist/capabilities/baseCapability.js.map +1 -0
  31. package/dist/capabilities/bashCapability.d.ts +13 -0
  32. package/dist/capabilities/bashCapability.d.ts.map +1 -0
  33. package/dist/capabilities/bashCapability.js +24 -0
  34. package/dist/capabilities/bashCapability.js.map +1 -0
  35. package/dist/capabilities/binaryAnalysisCapability.d.ts +7 -0
  36. package/dist/capabilities/binaryAnalysisCapability.d.ts.map +1 -0
  37. package/dist/capabilities/binaryAnalysisCapability.js +201 -0
  38. package/dist/capabilities/binaryAnalysisCapability.js.map +1 -0
  39. package/dist/capabilities/editCapability.d.ts +17 -0
  40. package/dist/capabilities/editCapability.d.ts.map +1 -0
  41. package/dist/capabilities/editCapability.js +27 -0
  42. package/dist/capabilities/editCapability.js.map +1 -0
  43. package/dist/capabilities/engagementCapability.d.ts +15 -0
  44. package/dist/capabilities/engagementCapability.d.ts.map +1 -0
  45. package/dist/capabilities/engagementCapability.js +29 -0
  46. package/dist/capabilities/engagementCapability.js.map +1 -0
  47. package/dist/capabilities/enhancedGitCapability.d.ts +7 -0
  48. package/dist/capabilities/enhancedGitCapability.d.ts.map +1 -0
  49. package/dist/capabilities/enhancedGitCapability.js +220 -0
  50. package/dist/capabilities/enhancedGitCapability.js.map +1 -0
  51. package/dist/capabilities/filesystemCapability.d.ts +13 -0
  52. package/dist/capabilities/filesystemCapability.d.ts.map +1 -0
  53. package/dist/capabilities/filesystemCapability.js +24 -0
  54. package/dist/capabilities/filesystemCapability.js.map +1 -0
  55. package/dist/capabilities/gdbCapability.d.ts +7 -0
  56. package/dist/capabilities/gdbCapability.d.ts.map +1 -0
  57. package/dist/capabilities/gdbCapability.js +125 -0
  58. package/dist/capabilities/gdbCapability.js.map +1 -0
  59. package/dist/capabilities/ghidraHeadlessCapability.d.ts +25 -0
  60. package/dist/capabilities/ghidraHeadlessCapability.d.ts.map +1 -0
  61. package/dist/capabilities/ghidraHeadlessCapability.js +593 -0
  62. package/dist/capabilities/ghidraHeadlessCapability.js.map +1 -0
  63. package/dist/capabilities/gitHistoryCapability.d.ts +6 -0
  64. package/dist/capabilities/gitHistoryCapability.d.ts.map +1 -0
  65. package/dist/capabilities/gitHistoryCapability.js +184 -0
  66. package/dist/capabilities/gitHistoryCapability.js.map +1 -0
  67. package/dist/capabilities/hitlCapability.d.ts +18 -0
  68. package/dist/capabilities/hitlCapability.d.ts.map +1 -0
  69. package/dist/capabilities/hitlCapability.js +29 -0
  70. package/dist/capabilities/hitlCapability.js.map +1 -0
  71. package/dist/capabilities/index.d.ts +25 -0
  72. package/dist/capabilities/index.d.ts.map +1 -0
  73. package/dist/capabilities/index.js +30 -0
  74. package/dist/capabilities/index.js.map +1 -0
  75. package/dist/capabilities/interactionCapability.d.ts +6 -0
  76. package/dist/capabilities/interactionCapability.d.ts.map +1 -0
  77. package/dist/capabilities/interactionCapability.js +17 -0
  78. package/dist/capabilities/interactionCapability.js.map +1 -0
  79. package/dist/capabilities/kaliCapability.d.ts +14 -0
  80. package/dist/capabilities/kaliCapability.d.ts.map +1 -0
  81. package/dist/capabilities/kaliCapability.js +478 -0
  82. package/dist/capabilities/kaliCapability.js.map +1 -0
  83. package/dist/capabilities/mcpCapability.d.ts +7 -0
  84. package/dist/capabilities/mcpCapability.d.ts.map +1 -0
  85. package/dist/capabilities/mcpCapability.js +82 -0
  86. package/dist/capabilities/mcpCapability.js.map +1 -0
  87. package/dist/capabilities/memoryCapability.d.ts +10 -0
  88. package/dist/capabilities/memoryCapability.d.ts.map +1 -0
  89. package/dist/capabilities/memoryCapability.js +22 -0
  90. package/dist/capabilities/memoryCapability.js.map +1 -0
  91. package/dist/capabilities/monitorCapability.d.ts +6 -0
  92. package/dist/capabilities/monitorCapability.d.ts.map +1 -0
  93. package/dist/capabilities/monitorCapability.js +19 -0
  94. package/dist/capabilities/monitorCapability.js.map +1 -0
  95. package/dist/capabilities/notebookCapability.d.ts +6 -0
  96. package/dist/capabilities/notebookCapability.d.ts.map +1 -0
  97. package/dist/capabilities/notebookCapability.js +17 -0
  98. package/dist/capabilities/notebookCapability.js.map +1 -0
  99. package/dist/capabilities/planModeCapability.d.ts +6 -0
  100. package/dist/capabilities/planModeCapability.d.ts.map +1 -0
  101. package/dist/capabilities/planModeCapability.js +16 -0
  102. package/dist/capabilities/planModeCapability.js.map +1 -0
  103. package/dist/capabilities/pwntoolsCapability.d.ts +7 -0
  104. package/dist/capabilities/pwntoolsCapability.d.ts.map +1 -0
  105. package/dist/capabilities/pwntoolsCapability.js +109 -0
  106. package/dist/capabilities/pwntoolsCapability.js.map +1 -0
  107. package/dist/capabilities/scheduleCapability.d.ts +6 -0
  108. package/dist/capabilities/scheduleCapability.d.ts.map +1 -0
  109. package/dist/capabilities/scheduleCapability.js +16 -0
  110. package/dist/capabilities/scheduleCapability.js.map +1 -0
  111. package/dist/capabilities/searchCapability.d.ts +19 -0
  112. package/dist/capabilities/searchCapability.d.ts.map +1 -0
  113. package/dist/capabilities/searchCapability.js +29 -0
  114. package/dist/capabilities/searchCapability.js.map +1 -0
  115. package/dist/capabilities/skillCapability.d.ts +6 -0
  116. package/dist/capabilities/skillCapability.d.ts.map +1 -0
  117. package/dist/capabilities/skillCapability.js +17 -0
  118. package/dist/capabilities/skillCapability.js.map +1 -0
  119. package/dist/capabilities/todoCapability.d.ts +11 -0
  120. package/dist/capabilities/todoCapability.d.ts.map +1 -0
  121. package/dist/capabilities/todoCapability.js +22 -0
  122. package/dist/capabilities/todoCapability.js.map +1 -0
  123. package/dist/capabilities/toolManifest.d.ts +3 -0
  124. package/dist/capabilities/toolManifest.d.ts.map +1 -0
  125. package/dist/capabilities/toolManifest.js +163 -0
  126. package/dist/capabilities/toolManifest.js.map +1 -0
  127. package/dist/capabilities/toolRegistry.d.ts +25 -0
  128. package/dist/capabilities/toolRegistry.d.ts.map +1 -0
  129. package/dist/capabilities/toolRegistry.js +150 -0
  130. package/dist/capabilities/toolRegistry.js.map +1 -0
  131. package/dist/capabilities/triggerCapability.d.ts +6 -0
  132. package/dist/capabilities/triggerCapability.d.ts.map +1 -0
  133. package/dist/capabilities/triggerCapability.js +16 -0
  134. package/dist/capabilities/triggerCapability.js.map +1 -0
  135. package/dist/capabilities/unifiedCodingCapability.d.ts +62 -0
  136. package/dist/capabilities/unifiedCodingCapability.d.ts.map +1 -0
  137. package/dist/capabilities/unifiedCodingCapability.js +788 -0
  138. package/dist/capabilities/unifiedCodingCapability.js.map +1 -0
  139. package/dist/capabilities/webCapability.d.ts +23 -0
  140. package/dist/capabilities/webCapability.d.ts.map +1 -0
  141. package/dist/capabilities/webCapability.js +33 -0
  142. package/dist/capabilities/webCapability.js.map +1 -0
  143. package/dist/capabilities/worktreeCapability.d.ts +6 -0
  144. package/dist/capabilities/worktreeCapability.d.ts.map +1 -0
  145. package/dist/capabilities/worktreeCapability.js +16 -0
  146. package/dist/capabilities/worktreeCapability.js.map +1 -0
  147. package/dist/config.d.ts +25 -0
  148. package/dist/config.d.ts.map +1 -0
  149. package/dist/config.js +155 -0
  150. package/dist/config.js.map +1 -0
  151. package/dist/contracts/v1/agent.d.ts +179 -0
  152. package/dist/contracts/v1/agent.d.ts.map +1 -0
  153. package/dist/contracts/v1/agent.js +8 -0
  154. package/dist/contracts/v1/agent.js.map +1 -0
  155. package/dist/contracts/v1/agentProfileManifest.d.ts +60 -0
  156. package/dist/contracts/v1/agentProfileManifest.d.ts.map +1 -0
  157. package/dist/contracts/v1/agentProfileManifest.js +9 -0
  158. package/dist/contracts/v1/agentProfileManifest.js.map +1 -0
  159. package/dist/contracts/v1/agentRules.d.ts +60 -0
  160. package/dist/contracts/v1/agentRules.d.ts.map +1 -0
  161. package/dist/contracts/v1/agentRules.js +10 -0
  162. package/dist/contracts/v1/agentRules.js.map +1 -0
  163. package/dist/contracts/v1/provider.d.ts +149 -0
  164. package/dist/contracts/v1/provider.d.ts.map +1 -0
  165. package/dist/contracts/v1/provider.js +7 -0
  166. package/dist/contracts/v1/provider.js.map +1 -0
  167. package/dist/contracts/v1/tool.d.ts +136 -0
  168. package/dist/contracts/v1/tool.d.ts.map +1 -0
  169. package/dist/contracts/v1/tool.js +7 -0
  170. package/dist/contracts/v1/tool.js.map +1 -0
  171. package/dist/contracts/v1/toolAccess.d.ts +43 -0
  172. package/dist/contracts/v1/toolAccess.d.ts.map +1 -0
  173. package/dist/contracts/v1/toolAccess.js +9 -0
  174. package/dist/contracts/v1/toolAccess.js.map +1 -0
  175. package/dist/core/agent.d.ts +320 -0
  176. package/dist/core/agent.d.ts.map +1 -0
  177. package/dist/core/agent.js +1627 -0
  178. package/dist/core/agent.js.map +1 -0
  179. package/dist/core/agentProfileManifest.d.ts +3 -0
  180. package/dist/core/agentProfileManifest.d.ts.map +1 -0
  181. package/dist/core/agentProfileManifest.js +188 -0
  182. package/dist/core/agentProfileManifest.js.map +1 -0
  183. package/dist/core/agentProfiles.d.ts +22 -0
  184. package/dist/core/agentProfiles.d.ts.map +1 -0
  185. package/dist/core/agentProfiles.js +35 -0
  186. package/dist/core/agentProfiles.js.map +1 -0
  187. package/dist/core/agentRegistry.d.ts +111 -0
  188. package/dist/core/agentRegistry.d.ts.map +1 -0
  189. package/dist/core/agentRegistry.js +229 -0
  190. package/dist/core/agentRegistry.js.map +1 -0
  191. package/dist/core/agentRulebook.d.ts +11 -0
  192. package/dist/core/agentRulebook.d.ts.map +1 -0
  193. package/dist/core/agentRulebook.js +136 -0
  194. package/dist/core/agentRulebook.js.map +1 -0
  195. package/dist/core/agentSchemaLoader.d.ts +131 -0
  196. package/dist/core/agentSchemaLoader.d.ts.map +1 -0
  197. package/dist/core/agentSchemaLoader.js +235 -0
  198. package/dist/core/agentSchemaLoader.js.map +1 -0
  199. package/dist/core/aiErrorFixer.d.ts +57 -0
  200. package/dist/core/aiErrorFixer.d.ts.map +1 -0
  201. package/dist/core/aiErrorFixer.js +214 -0
  202. package/dist/core/aiErrorFixer.js.map +1 -0
  203. package/dist/core/artifactStore.d.ts +35 -0
  204. package/dist/core/artifactStore.d.ts.map +1 -0
  205. package/dist/core/artifactStore.js +105 -0
  206. package/dist/core/artifactStore.js.map +1 -0
  207. package/dist/core/auth.d.ts +15 -0
  208. package/dist/core/auth.d.ts.map +1 -0
  209. package/dist/core/auth.js +345 -0
  210. package/dist/core/auth.js.map +1 -0
  211. package/dist/core/bashCommandGuidance.d.ts +16 -0
  212. package/dist/core/bashCommandGuidance.d.ts.map +1 -0
  213. package/dist/core/bashCommandGuidance.js +40 -0
  214. package/dist/core/bashCommandGuidance.js.map +1 -0
  215. package/dist/core/constants.d.ts +31 -0
  216. package/dist/core/constants.d.ts.map +1 -0
  217. package/dist/core/constants.js +62 -0
  218. package/dist/core/constants.js.map +1 -0
  219. package/dist/core/contextManager.d.ts +271 -0
  220. package/dist/core/contextManager.d.ts.map +1 -0
  221. package/dist/core/contextManager.js +1073 -0
  222. package/dist/core/contextManager.js.map +1 -0
  223. package/dist/core/contextWindow.d.ts +42 -0
  224. package/dist/core/contextWindow.d.ts.map +1 -0
  225. package/dist/core/contextWindow.js +123 -0
  226. package/dist/core/contextWindow.js.map +1 -0
  227. package/dist/core/customCommands.d.ts +19 -0
  228. package/dist/core/customCommands.d.ts.map +1 -0
  229. package/dist/core/customCommands.js +85 -0
  230. package/dist/core/customCommands.js.map +1 -0
  231. package/dist/core/errors/apiKeyErrors.d.ts +11 -0
  232. package/dist/core/errors/apiKeyErrors.d.ts.map +1 -0
  233. package/dist/core/errors/apiKeyErrors.js +159 -0
  234. package/dist/core/errors/apiKeyErrors.js.map +1 -0
  235. package/dist/core/errors/errorTypes.d.ts +111 -0
  236. package/dist/core/errors/errorTypes.d.ts.map +1 -0
  237. package/dist/core/errors/errorTypes.js +345 -0
  238. package/dist/core/errors/errorTypes.js.map +1 -0
  239. package/dist/core/errors/index.d.ts +50 -0
  240. package/dist/core/errors/index.d.ts.map +1 -0
  241. package/dist/core/errors/index.js +156 -0
  242. package/dist/core/errors/index.js.map +1 -0
  243. package/dist/core/errors/networkErrors.d.ts +14 -0
  244. package/dist/core/errors/networkErrors.d.ts.map +1 -0
  245. package/dist/core/errors/networkErrors.js +53 -0
  246. package/dist/core/errors/networkErrors.js.map +1 -0
  247. package/dist/core/errors/safetyValidator.d.ts +109 -0
  248. package/dist/core/errors/safetyValidator.d.ts.map +1 -0
  249. package/dist/core/errors/safetyValidator.js +271 -0
  250. package/dist/core/errors/safetyValidator.js.map +1 -0
  251. package/dist/core/errors.d.ts +4 -0
  252. package/dist/core/errors.d.ts.map +1 -0
  253. package/dist/core/errors.js +33 -0
  254. package/dist/core/errors.js.map +1 -0
  255. package/dist/core/finalResponseFormatter.d.ts +10 -0
  256. package/dist/core/finalResponseFormatter.d.ts.map +1 -0
  257. package/dist/core/finalResponseFormatter.js +14 -0
  258. package/dist/core/finalResponseFormatter.js.map +1 -0
  259. package/dist/core/guardrails.d.ts +146 -0
  260. package/dist/core/guardrails.d.ts.map +1 -0
  261. package/dist/core/guardrails.js +361 -0
  262. package/dist/core/guardrails.js.map +1 -0
  263. package/dist/core/hitl.d.ts +119 -0
  264. package/dist/core/hitl.d.ts.map +1 -0
  265. package/dist/core/hitl.js +387 -0
  266. package/dist/core/hitl.js.map +1 -0
  267. package/dist/core/hooks.d.ts +95 -0
  268. package/dist/core/hooks.d.ts.map +1 -0
  269. package/dist/core/hooks.js +239 -0
  270. package/dist/core/hooks.js.map +1 -0
  271. package/dist/core/index.d.ts +7 -0
  272. package/dist/core/index.d.ts.map +1 -0
  273. package/dist/core/index.js +7 -0
  274. package/dist/core/index.js.map +1 -0
  275. package/dist/core/inputProtection.d.ts +122 -0
  276. package/dist/core/inputProtection.d.ts.map +1 -0
  277. package/dist/core/inputProtection.js +422 -0
  278. package/dist/core/inputProtection.js.map +1 -0
  279. package/dist/core/modelDiscovery.d.ts +105 -0
  280. package/dist/core/modelDiscovery.d.ts.map +1 -0
  281. package/dist/core/modelDiscovery.js +768 -0
  282. package/dist/core/modelDiscovery.js.map +1 -0
  283. package/dist/core/multilinePasteHandler.d.ts +35 -0
  284. package/dist/core/multilinePasteHandler.d.ts.map +1 -0
  285. package/dist/core/multilinePasteHandler.js +81 -0
  286. package/dist/core/multilinePasteHandler.js.map +1 -0
  287. package/dist/core/preferences.d.ts +65 -0
  288. package/dist/core/preferences.d.ts.map +1 -0
  289. package/dist/core/preferences.js +305 -0
  290. package/dist/core/preferences.js.map +1 -0
  291. package/dist/core/projectTracker.d.ts +96 -0
  292. package/dist/core/projectTracker.d.ts.map +1 -0
  293. package/dist/core/projectTracker.js +275 -0
  294. package/dist/core/projectTracker.js.map +1 -0
  295. package/dist/core/providerKeys.d.ts +20 -0
  296. package/dist/core/providerKeys.d.ts.map +1 -0
  297. package/dist/core/providerKeys.js +40 -0
  298. package/dist/core/providerKeys.js.map +1 -0
  299. package/dist/core/refusalDetection.d.ts +2 -0
  300. package/dist/core/refusalDetection.d.ts.map +1 -0
  301. package/dist/core/refusalDetection.js +51 -0
  302. package/dist/core/refusalDetection.js.map +1 -0
  303. package/dist/core/resultVerification.d.ts +47 -0
  304. package/dist/core/resultVerification.d.ts.map +1 -0
  305. package/dist/core/resultVerification.js +126 -0
  306. package/dist/core/resultVerification.js.map +1 -0
  307. package/dist/core/reviewerGuard.d.ts +37 -0
  308. package/dist/core/reviewerGuard.d.ts.map +1 -0
  309. package/dist/core/reviewerGuard.js +188 -0
  310. package/dist/core/reviewerGuard.js.map +1 -0
  311. package/dist/core/schemaValidator.d.ts +49 -0
  312. package/dist/core/schemaValidator.d.ts.map +1 -0
  313. package/dist/core/schemaValidator.js +234 -0
  314. package/dist/core/schemaValidator.js.map +1 -0
  315. package/dist/core/secretStore.d.ts +48 -0
  316. package/dist/core/secretStore.d.ts.map +1 -0
  317. package/dist/core/secretStore.js +259 -0
  318. package/dist/core/secretStore.js.map +1 -0
  319. package/dist/core/sessionStorage.d.ts +10 -0
  320. package/dist/core/sessionStorage.d.ts.map +1 -0
  321. package/dist/core/sessionStorage.js +46 -0
  322. package/dist/core/sessionStorage.js.map +1 -0
  323. package/dist/core/sessionStore.d.ts +35 -0
  324. package/dist/core/sessionStore.d.ts.map +1 -0
  325. package/dist/core/sessionStore.js +191 -0
  326. package/dist/core/sessionStore.js.map +1 -0
  327. package/dist/core/sharedSecrets.d.ts +60 -0
  328. package/dist/core/sharedSecrets.d.ts.map +1 -0
  329. package/dist/core/sharedSecrets.js +111 -0
  330. package/dist/core/sharedSecrets.js.map +1 -0
  331. package/dist/core/shutdown.d.ts +34 -0
  332. package/dist/core/shutdown.d.ts.map +1 -0
  333. package/dist/core/shutdown.js +186 -0
  334. package/dist/core/shutdown.js.map +1 -0
  335. package/dist/core/sudoPasswordManager.d.ts +52 -0
  336. package/dist/core/sudoPasswordManager.d.ts.map +1 -0
  337. package/dist/core/sudoPasswordManager.js +115 -0
  338. package/dist/core/sudoPasswordManager.js.map +1 -0
  339. package/dist/core/taskCompletionDetector.d.ts +117 -0
  340. package/dist/core/taskCompletionDetector.d.ts.map +1 -0
  341. package/dist/core/taskCompletionDetector.js +532 -0
  342. package/dist/core/taskCompletionDetector.js.map +1 -0
  343. package/dist/core/testFailureMonitor.d.ts +67 -0
  344. package/dist/core/testFailureMonitor.d.ts.map +1 -0
  345. package/dist/core/testFailureMonitor.js +262 -0
  346. package/dist/core/testFailureMonitor.js.map +1 -0
  347. package/dist/core/toolPreconditions.d.ts +34 -0
  348. package/dist/core/toolPreconditions.d.ts.map +1 -0
  349. package/dist/core/toolPreconditions.js +242 -0
  350. package/dist/core/toolPreconditions.js.map +1 -0
  351. package/dist/core/toolRuntime.d.ts +192 -0
  352. package/dist/core/toolRuntime.d.ts.map +1 -0
  353. package/dist/core/toolRuntime.js +511 -0
  354. package/dist/core/toolRuntime.js.map +1 -0
  355. package/dist/core/types/utilityTypes.d.ts +183 -0
  356. package/dist/core/types/utilityTypes.d.ts.map +1 -0
  357. package/dist/core/types/utilityTypes.js +273 -0
  358. package/dist/core/types/utilityTypes.js.map +1 -0
  359. package/dist/core/types.d.ts +334 -0
  360. package/dist/core/types.d.ts.map +1 -0
  361. package/dist/core/types.js +76 -0
  362. package/dist/core/types.js.map +1 -0
  363. package/dist/core/updateChecker.d.ts +148 -0
  364. package/dist/core/updateChecker.d.ts.map +1 -0
  365. package/dist/core/updateChecker.js +599 -0
  366. package/dist/core/updateChecker.js.map +1 -0
  367. package/dist/core/usageTracker.d.ts +11 -0
  368. package/dist/core/usageTracker.d.ts.map +1 -0
  369. package/dist/core/usageTracker.js +128 -0
  370. package/dist/core/usageTracker.js.map +1 -0
  371. package/dist/core/userApproval.d.ts +95 -0
  372. package/dist/core/userApproval.d.ts.map +1 -0
  373. package/dist/core/userApproval.js +239 -0
  374. package/dist/core/userApproval.js.map +1 -0
  375. package/dist/headless/interactiveShell.d.ts +22 -0
  376. package/dist/headless/interactiveShell.d.ts.map +1 -0
  377. package/dist/headless/interactiveShell.js +2156 -0
  378. package/dist/headless/interactiveShell.js.map +1 -0
  379. package/dist/leanAgent.d.ts +73 -0
  380. package/dist/leanAgent.d.ts.map +1 -0
  381. package/dist/leanAgent.js +177 -0
  382. package/dist/leanAgent.js.map +1 -0
  383. package/dist/plugins/index.d.ts +49 -0
  384. package/dist/plugins/index.d.ts.map +1 -0
  385. package/dist/plugins/index.js +104 -0
  386. package/dist/plugins/index.js.map +1 -0
  387. package/dist/plugins/providers/anthropic/index.d.ts +9 -0
  388. package/dist/plugins/providers/anthropic/index.d.ts.map +1 -0
  389. package/dist/plugins/providers/anthropic/index.js +48 -0
  390. package/dist/plugins/providers/anthropic/index.js.map +1 -0
  391. package/dist/plugins/providers/deepseek/index.d.ts +11 -0
  392. package/dist/plugins/providers/deepseek/index.d.ts.map +1 -0
  393. package/dist/plugins/providers/deepseek/index.js +54 -0
  394. package/dist/plugins/providers/deepseek/index.js.map +1 -0
  395. package/dist/plugins/providers/index.d.ts +2 -0
  396. package/dist/plugins/providers/index.d.ts.map +1 -0
  397. package/dist/plugins/providers/index.js +17 -0
  398. package/dist/plugins/providers/index.js.map +1 -0
  399. package/dist/plugins/providers/openai/index.d.ts +10 -0
  400. package/dist/plugins/providers/openai/index.d.ts.map +1 -0
  401. package/dist/plugins/providers/openai/index.js +47 -0
  402. package/dist/plugins/providers/openai/index.js.map +1 -0
  403. package/dist/plugins/providers/xai/index.d.ts +10 -0
  404. package/dist/plugins/providers/xai/index.d.ts.map +1 -0
  405. package/dist/plugins/providers/xai/index.js +47 -0
  406. package/dist/plugins/providers/xai/index.js.map +1 -0
  407. package/dist/plugins/tools/agentSpawning/agentSpawningPlugin.d.ts +10 -0
  408. package/dist/plugins/tools/agentSpawning/agentSpawningPlugin.d.ts.map +1 -0
  409. package/dist/plugins/tools/agentSpawning/agentSpawningPlugin.js +110 -0
  410. package/dist/plugins/tools/agentSpawning/agentSpawningPlugin.js.map +1 -0
  411. package/dist/plugins/tools/bash/localBashPlugin.d.ts +3 -0
  412. package/dist/plugins/tools/bash/localBashPlugin.d.ts.map +1 -0
  413. package/dist/plugins/tools/bash/localBashPlugin.js +14 -0
  414. package/dist/plugins/tools/bash/localBashPlugin.js.map +1 -0
  415. package/dist/plugins/tools/edit/editPlugin.d.ts +9 -0
  416. package/dist/plugins/tools/edit/editPlugin.d.ts.map +1 -0
  417. package/dist/plugins/tools/edit/editPlugin.js +15 -0
  418. package/dist/plugins/tools/edit/editPlugin.js.map +1 -0
  419. package/dist/plugins/tools/enhancedGit/enhancedGitPlugin.d.ts +3 -0
  420. package/dist/plugins/tools/enhancedGit/enhancedGitPlugin.d.ts.map +1 -0
  421. package/dist/plugins/tools/enhancedGit/enhancedGitPlugin.js +9 -0
  422. package/dist/plugins/tools/enhancedGit/enhancedGitPlugin.js.map +1 -0
  423. package/dist/plugins/tools/filesystem/localFilesystemPlugin.d.ts +3 -0
  424. package/dist/plugins/tools/filesystem/localFilesystemPlugin.d.ts.map +1 -0
  425. package/dist/plugins/tools/filesystem/localFilesystemPlugin.js +14 -0
  426. package/dist/plugins/tools/filesystem/localFilesystemPlugin.js.map +1 -0
  427. package/dist/plugins/tools/gitHistory/gitHistoryPlugin.d.ts +3 -0
  428. package/dist/plugins/tools/gitHistory/gitHistoryPlugin.d.ts.map +1 -0
  429. package/dist/plugins/tools/gitHistory/gitHistoryPlugin.js +9 -0
  430. package/dist/plugins/tools/gitHistory/gitHistoryPlugin.js.map +1 -0
  431. package/dist/plugins/tools/index.d.ts +3 -0
  432. package/dist/plugins/tools/index.d.ts.map +1 -0
  433. package/dist/plugins/tools/index.js +3 -0
  434. package/dist/plugins/tools/index.js.map +1 -0
  435. package/dist/plugins/tools/integrity/integrityPlugin.d.ts +3 -0
  436. package/dist/plugins/tools/integrity/integrityPlugin.d.ts.map +1 -0
  437. package/dist/plugins/tools/integrity/integrityPlugin.js +31 -0
  438. package/dist/plugins/tools/integrity/integrityPlugin.js.map +1 -0
  439. package/dist/plugins/tools/kali/kaliPlugin.d.ts +3 -0
  440. package/dist/plugins/tools/kali/kaliPlugin.d.ts.map +1 -0
  441. package/dist/plugins/tools/kali/kaliPlugin.js +10 -0
  442. package/dist/plugins/tools/kali/kaliPlugin.js.map +1 -0
  443. package/dist/plugins/tools/mcp/mcpClient.d.ts +59 -0
  444. package/dist/plugins/tools/mcp/mcpClient.d.ts.map +1 -0
  445. package/dist/plugins/tools/mcp/mcpClient.js +118 -0
  446. package/dist/plugins/tools/mcp/mcpClient.js.map +1 -0
  447. package/dist/plugins/tools/mcp/mcpPlugin.d.ts +3 -0
  448. package/dist/plugins/tools/mcp/mcpPlugin.d.ts.map +1 -0
  449. package/dist/plugins/tools/mcp/mcpPlugin.js +10 -0
  450. package/dist/plugins/tools/mcp/mcpPlugin.js.map +1 -0
  451. package/dist/plugins/tools/nodeDefaults.d.ts +13 -0
  452. package/dist/plugins/tools/nodeDefaults.d.ts.map +1 -0
  453. package/dist/plugins/tools/nodeDefaults.js +37 -0
  454. package/dist/plugins/tools/nodeDefaults.js.map +1 -0
  455. package/dist/plugins/tools/orchestration/orchestrationPlugin.d.ts +3 -0
  456. package/dist/plugins/tools/orchestration/orchestrationPlugin.d.ts.map +1 -0
  457. package/dist/plugins/tools/orchestration/orchestrationPlugin.js +340 -0
  458. package/dist/plugins/tools/orchestration/orchestrationPlugin.js.map +1 -0
  459. package/dist/plugins/tools/registry.d.ts +22 -0
  460. package/dist/plugins/tools/registry.d.ts.map +1 -0
  461. package/dist/plugins/tools/registry.js +58 -0
  462. package/dist/plugins/tools/registry.js.map +1 -0
  463. package/dist/plugins/tools/search/localSearchPlugin.d.ts +3 -0
  464. package/dist/plugins/tools/search/localSearchPlugin.d.ts.map +1 -0
  465. package/dist/plugins/tools/search/localSearchPlugin.js +14 -0
  466. package/dist/plugins/tools/search/localSearchPlugin.js.map +1 -0
  467. package/dist/plugins/tools/skills/skillPlugin.d.ts +3 -0
  468. package/dist/plugins/tools/skills/skillPlugin.d.ts.map +1 -0
  469. package/dist/plugins/tools/skills/skillPlugin.js +27 -0
  470. package/dist/plugins/tools/skills/skillPlugin.js.map +1 -0
  471. package/dist/plugins/tools/todo/todoPlugin.d.ts +3 -0
  472. package/dist/plugins/tools/todo/todoPlugin.d.ts.map +1 -0
  473. package/dist/plugins/tools/todo/todoPlugin.js +10 -0
  474. package/dist/plugins/tools/todo/todoPlugin.js.map +1 -0
  475. package/dist/providers/baseProvider.d.ts +148 -0
  476. package/dist/providers/baseProvider.d.ts.map +1 -0
  477. package/dist/providers/baseProvider.js +284 -0
  478. package/dist/providers/baseProvider.js.map +1 -0
  479. package/dist/providers/openaiChatCompletionsProvider.d.ts +64 -0
  480. package/dist/providers/openaiChatCompletionsProvider.d.ts.map +1 -0
  481. package/dist/providers/openaiChatCompletionsProvider.js +1018 -0
  482. package/dist/providers/openaiChatCompletionsProvider.js.map +1 -0
  483. package/dist/providers/providerFactory.d.ts +22 -0
  484. package/dist/providers/providerFactory.d.ts.map +1 -0
  485. package/dist/providers/providerFactory.js +25 -0
  486. package/dist/providers/providerFactory.js.map +1 -0
  487. package/dist/providers/resilientProvider.d.ts +103 -0
  488. package/dist/providers/resilientProvider.d.ts.map +1 -0
  489. package/dist/providers/resilientProvider.js +468 -0
  490. package/dist/providers/resilientProvider.js.map +1 -0
  491. package/dist/runtime/agentController.d.ts +121 -0
  492. package/dist/runtime/agentController.d.ts.map +1 -0
  493. package/dist/runtime/agentController.js +739 -0
  494. package/dist/runtime/agentController.js.map +1 -0
  495. package/dist/runtime/agentHost.d.ts +61 -0
  496. package/dist/runtime/agentHost.d.ts.map +1 -0
  497. package/dist/runtime/agentHost.js +158 -0
  498. package/dist/runtime/agentHost.js.map +1 -0
  499. package/dist/runtime/agentSession.d.ts +49 -0
  500. package/dist/runtime/agentSession.d.ts.map +1 -0
  501. package/dist/runtime/agentSession.js +218 -0
  502. package/dist/runtime/agentSession.js.map +1 -0
  503. package/dist/runtime/agentSpawningWiring.d.ts +23 -0
  504. package/dist/runtime/agentSpawningWiring.d.ts.map +1 -0
  505. package/dist/runtime/agentSpawningWiring.js +119 -0
  506. package/dist/runtime/agentSpawningWiring.js.map +1 -0
  507. package/dist/runtime/agentWorkerPool.d.ts +167 -0
  508. package/dist/runtime/agentWorkerPool.d.ts.map +1 -0
  509. package/dist/runtime/agentWorkerPool.js +435 -0
  510. package/dist/runtime/agentWorkerPool.js.map +1 -0
  511. package/dist/runtime/node.d.ts +9 -0
  512. package/dist/runtime/node.d.ts.map +1 -0
  513. package/dist/runtime/node.js +56 -0
  514. package/dist/runtime/node.js.map +1 -0
  515. package/dist/runtime/profileGates.d.ts +19 -0
  516. package/dist/runtime/profileGates.d.ts.map +1 -0
  517. package/dist/runtime/profileGates.js +23 -0
  518. package/dist/runtime/profileGates.js.map +1 -0
  519. package/dist/runtime/universal.d.ts +18 -0
  520. package/dist/runtime/universal.d.ts.map +1 -0
  521. package/dist/runtime/universal.js +31 -0
  522. package/dist/runtime/universal.js.map +1 -0
  523. package/dist/shell/autoExecutor.d.ts +70 -0
  524. package/dist/shell/autoExecutor.d.ts.map +1 -0
  525. package/dist/shell/autoExecutor.js +320 -0
  526. package/dist/shell/autoExecutor.js.map +1 -0
  527. package/dist/shell/commandRegistry.d.ts +122 -0
  528. package/dist/shell/commandRegistry.d.ts.map +1 -0
  529. package/dist/shell/commandRegistry.js +355 -0
  530. package/dist/shell/commandRegistry.js.map +1 -0
  531. package/dist/shell/composableMessage.d.ts +178 -0
  532. package/dist/shell/composableMessage.d.ts.map +1 -0
  533. package/dist/shell/composableMessage.js +384 -0
  534. package/dist/shell/composableMessage.js.map +1 -0
  535. package/dist/shell/liveStatus.d.ts +27 -0
  536. package/dist/shell/liveStatus.d.ts.map +1 -0
  537. package/dist/shell/liveStatus.js +53 -0
  538. package/dist/shell/liveStatus.js.map +1 -0
  539. package/dist/shell/systemPrompt.d.ts +12 -0
  540. package/dist/shell/systemPrompt.d.ts.map +1 -0
  541. package/dist/shell/systemPrompt.js +16 -0
  542. package/dist/shell/systemPrompt.js.map +1 -0
  543. package/dist/shell/vimMode.d.ts +66 -0
  544. package/dist/shell/vimMode.d.ts.map +1 -0
  545. package/dist/shell/vimMode.js +435 -0
  546. package/dist/shell/vimMode.js.map +1 -0
  547. package/dist/tools/bashTools.d.ts +11 -0
  548. package/dist/tools/bashTools.d.ts.map +1 -0
  549. package/dist/tools/bashTools.js +779 -0
  550. package/dist/tools/bashTools.js.map +1 -0
  551. package/dist/tools/diffUtils.d.ts +43 -0
  552. package/dist/tools/diffUtils.d.ts.map +1 -0
  553. package/dist/tools/diffUtils.js +607 -0
  554. package/dist/tools/diffUtils.js.map +1 -0
  555. package/dist/tools/editTools.d.ts +29 -0
  556. package/dist/tools/editTools.d.ts.map +1 -0
  557. package/dist/tools/editTools.js +792 -0
  558. package/dist/tools/editTools.js.map +1 -0
  559. package/dist/tools/engagementTools.d.ts +22 -0
  560. package/dist/tools/engagementTools.d.ts.map +1 -0
  561. package/dist/tools/engagementTools.js +339 -0
  562. package/dist/tools/engagementTools.js.map +1 -0
  563. package/dist/tools/fileChangeTracker.d.ts +47 -0
  564. package/dist/tools/fileChangeTracker.d.ts.map +1 -0
  565. package/dist/tools/fileChangeTracker.js +154 -0
  566. package/dist/tools/fileChangeTracker.js.map +1 -0
  567. package/dist/tools/fileReadTracker.d.ts +69 -0
  568. package/dist/tools/fileReadTracker.d.ts.map +1 -0
  569. package/dist/tools/fileReadTracker.js +213 -0
  570. package/dist/tools/fileReadTracker.js.map +1 -0
  571. package/dist/tools/fileTools.d.ts +3 -0
  572. package/dist/tools/fileTools.d.ts.map +1 -0
  573. package/dist/tools/fileTools.js +389 -0
  574. package/dist/tools/fileTools.js.map +1 -0
  575. package/dist/tools/grepTools.d.ts +3 -0
  576. package/dist/tools/grepTools.d.ts.map +1 -0
  577. package/dist/tools/grepTools.js +128 -0
  578. package/dist/tools/grepTools.js.map +1 -0
  579. package/dist/tools/heliaControl.d.ts +51 -0
  580. package/dist/tools/heliaControl.d.ts.map +1 -0
  581. package/dist/tools/heliaControl.js +93 -0
  582. package/dist/tools/heliaControl.js.map +1 -0
  583. package/dist/tools/hitlTools.d.ts +7 -0
  584. package/dist/tools/hitlTools.d.ts.map +1 -0
  585. package/dist/tools/hitlTools.js +185 -0
  586. package/dist/tools/hitlTools.js.map +1 -0
  587. package/dist/tools/interactionTools.d.ts +16 -0
  588. package/dist/tools/interactionTools.d.ts.map +1 -0
  589. package/dist/tools/interactionTools.js +207 -0
  590. package/dist/tools/interactionTools.js.map +1 -0
  591. package/dist/tools/localExplore.d.ts +38 -0
  592. package/dist/tools/localExplore.d.ts.map +1 -0
  593. package/dist/tools/localExplore.js +30 -0
  594. package/dist/tools/localExplore.js.map +1 -0
  595. package/dist/tools/memoryTools.d.ts +20 -0
  596. package/dist/tools/memoryTools.d.ts.map +1 -0
  597. package/dist/tools/memoryTools.js +180 -0
  598. package/dist/tools/memoryTools.js.map +1 -0
  599. package/dist/tools/monitorTools.d.ts +16 -0
  600. package/dist/tools/monitorTools.d.ts.map +1 -0
  601. package/dist/tools/monitorTools.js +178 -0
  602. package/dist/tools/monitorTools.js.map +1 -0
  603. package/dist/tools/notebookTools.d.ts +20 -0
  604. package/dist/tools/notebookTools.d.ts.map +1 -0
  605. package/dist/tools/notebookTools.js +140 -0
  606. package/dist/tools/notebookTools.js.map +1 -0
  607. package/dist/tools/planModeTools.d.ts +32 -0
  608. package/dist/tools/planModeTools.d.ts.map +1 -0
  609. package/dist/tools/planModeTools.js +200 -0
  610. package/dist/tools/planModeTools.js.map +1 -0
  611. package/dist/tools/scheduleTools.d.ts +39 -0
  612. package/dist/tools/scheduleTools.d.ts.map +1 -0
  613. package/dist/tools/scheduleTools.js +182 -0
  614. package/dist/tools/scheduleTools.js.map +1 -0
  615. package/dist/tools/searchTools.d.ts +12 -0
  616. package/dist/tools/searchTools.d.ts.map +1 -0
  617. package/dist/tools/searchTools.js +413 -0
  618. package/dist/tools/searchTools.js.map +1 -0
  619. package/dist/tools/skillTools.d.ts +24 -0
  620. package/dist/tools/skillTools.d.ts.map +1 -0
  621. package/dist/tools/skillTools.js +140 -0
  622. package/dist/tools/skillTools.js.map +1 -0
  623. package/dist/tools/todoTools.d.ts +24 -0
  624. package/dist/tools/todoTools.d.ts.map +1 -0
  625. package/dist/tools/todoTools.js +115 -0
  626. package/dist/tools/todoTools.js.map +1 -0
  627. package/dist/tools/triggerTools.d.ts +28 -0
  628. package/dist/tools/triggerTools.d.ts.map +1 -0
  629. package/dist/tools/triggerTools.js +210 -0
  630. package/dist/tools/triggerTools.js.map +1 -0
  631. package/dist/tools/webTools.d.ts +26 -0
  632. package/dist/tools/webTools.d.ts.map +1 -0
  633. package/dist/tools/webTools.js +332 -0
  634. package/dist/tools/webTools.js.map +1 -0
  635. package/dist/tools/worktreeTools.d.ts +21 -0
  636. package/dist/tools/worktreeTools.d.ts.map +1 -0
  637. package/dist/tools/worktreeTools.js +158 -0
  638. package/dist/tools/worktreeTools.js.map +1 -0
  639. package/dist/ui/RenderGate.d.ts +83 -0
  640. package/dist/ui/RenderGate.d.ts.map +1 -0
  641. package/dist/ui/RenderGate.js +138 -0
  642. package/dist/ui/RenderGate.js.map +1 -0
  643. package/dist/ui/animatedStatus.d.ts +140 -0
  644. package/dist/ui/animatedStatus.d.ts.map +1 -0
  645. package/dist/ui/animatedStatus.js +480 -0
  646. package/dist/ui/animatedStatus.js.map +1 -0
  647. package/dist/ui/animation/AnimationScheduler.d.ts +197 -0
  648. package/dist/ui/animation/AnimationScheduler.d.ts.map +1 -0
  649. package/dist/ui/animation/AnimationScheduler.js +440 -0
  650. package/dist/ui/animation/AnimationScheduler.js.map +1 -0
  651. package/dist/ui/codeHighlighter.d.ts +6 -0
  652. package/dist/ui/codeHighlighter.d.ts.map +1 -0
  653. package/dist/ui/codeHighlighter.js +855 -0
  654. package/dist/ui/codeHighlighter.js.map +1 -0
  655. package/dist/ui/designSystem.d.ts +26 -0
  656. package/dist/ui/designSystem.d.ts.map +1 -0
  657. package/dist/ui/designSystem.js +114 -0
  658. package/dist/ui/designSystem.js.map +1 -0
  659. package/dist/ui/errorFormatter.d.ts +64 -0
  660. package/dist/ui/errorFormatter.d.ts.map +1 -0
  661. package/dist/ui/errorFormatter.js +316 -0
  662. package/dist/ui/errorFormatter.js.map +1 -0
  663. package/dist/ui/globalWriteLock.d.ts +63 -0
  664. package/dist/ui/globalWriteLock.d.ts.map +1 -0
  665. package/dist/ui/globalWriteLock.js +173 -0
  666. package/dist/ui/globalWriteLock.js.map +1 -0
  667. package/dist/ui/index.d.ts +31 -0
  668. package/dist/ui/index.d.ts.map +1 -0
  669. package/dist/ui/index.js +49 -0
  670. package/dist/ui/index.js.map +1 -0
  671. package/dist/ui/ink/App.d.ts +39 -0
  672. package/dist/ui/ink/App.d.ts.map +1 -0
  673. package/dist/ui/ink/App.js +19 -0
  674. package/dist/ui/ink/App.js.map +1 -0
  675. package/dist/ui/ink/ChatStatic.d.ts +29 -0
  676. package/dist/ui/ink/ChatStatic.d.ts.map +1 -0
  677. package/dist/ui/ink/ChatStatic.js +31 -0
  678. package/dist/ui/ink/ChatStatic.js.map +1 -0
  679. package/dist/ui/ink/InkPromptController.d.ts +286 -0
  680. package/dist/ui/ink/InkPromptController.d.ts.map +1 -0
  681. package/dist/ui/ink/InkPromptController.js +558 -0
  682. package/dist/ui/ink/InkPromptController.js.map +1 -0
  683. package/dist/ui/ink/Prompt.d.ts +36 -0
  684. package/dist/ui/ink/Prompt.d.ts.map +1 -0
  685. package/dist/ui/ink/Prompt.js +296 -0
  686. package/dist/ui/ink/Prompt.js.map +1 -0
  687. package/dist/ui/ink/StatusLine.d.ts +25 -0
  688. package/dist/ui/ink/StatusLine.d.ts.map +1 -0
  689. package/dist/ui/ink/StatusLine.js +12 -0
  690. package/dist/ui/ink/StatusLine.js.map +1 -0
  691. package/dist/ui/ink/adapter.d.ts +58 -0
  692. package/dist/ui/ink/adapter.d.ts.map +1 -0
  693. package/dist/ui/ink/adapter.js +113 -0
  694. package/dist/ui/ink/adapter.js.map +1 -0
  695. package/dist/ui/interrupts/InterruptManager.d.ts +157 -0
  696. package/dist/ui/interrupts/InterruptManager.d.ts.map +1 -0
  697. package/dist/ui/interrupts/InterruptManager.js +501 -0
  698. package/dist/ui/interrupts/InterruptManager.js.map +1 -0
  699. package/dist/ui/layout.d.ts +27 -0
  700. package/dist/ui/layout.d.ts.map +1 -0
  701. package/dist/ui/layout.js +184 -0
  702. package/dist/ui/layout.js.map +1 -0
  703. package/dist/ui/outputMode.d.ts +58 -0
  704. package/dist/ui/outputMode.d.ts.map +1 -0
  705. package/dist/ui/outputMode.js +179 -0
  706. package/dist/ui/outputMode.js.map +1 -0
  707. package/dist/ui/overlay/OverlayManager.d.ts +105 -0
  708. package/dist/ui/overlay/OverlayManager.d.ts.map +1 -0
  709. package/dist/ui/overlay/OverlayManager.js +304 -0
  710. package/dist/ui/overlay/OverlayManager.js.map +1 -0
  711. package/dist/ui/premiumComponents.d.ts +54 -0
  712. package/dist/ui/premiumComponents.d.ts.map +1 -0
  713. package/dist/ui/premiumComponents.js +241 -0
  714. package/dist/ui/premiumComponents.js.map +1 -0
  715. package/dist/ui/richText.d.ts +13 -0
  716. package/dist/ui/richText.d.ts.map +1 -0
  717. package/dist/ui/richText.js +444 -0
  718. package/dist/ui/richText.js.map +1 -0
  719. package/dist/ui/telemetry/ResponseTracker.d.ts +22 -0
  720. package/dist/ui/telemetry/ResponseTracker.d.ts.map +1 -0
  721. package/dist/ui/telemetry/ResponseTracker.js +60 -0
  722. package/dist/ui/telemetry/ResponseTracker.js.map +1 -0
  723. package/dist/ui/telemetry/UITelemetry.d.ts +181 -0
  724. package/dist/ui/telemetry/UITelemetry.d.ts.map +1 -0
  725. package/dist/ui/telemetry/UITelemetry.js +446 -0
  726. package/dist/ui/telemetry/UITelemetry.js.map +1 -0
  727. package/dist/ui/textHighlighter.d.ts +83 -0
  728. package/dist/ui/textHighlighter.d.ts.map +1 -0
  729. package/dist/ui/textHighlighter.js +267 -0
  730. package/dist/ui/textHighlighter.js.map +1 -0
  731. package/dist/ui/theme.d.ts +351 -0
  732. package/dist/ui/theme.d.ts.map +1 -0
  733. package/dist/ui/theme.js +436 -0
  734. package/dist/ui/theme.js.map +1 -0
  735. package/dist/ui/toolDisplay.d.ts +221 -0
  736. package/dist/ui/toolDisplay.d.ts.map +1 -0
  737. package/dist/ui/toolDisplay.js +1654 -0
  738. package/dist/ui/toolDisplay.js.map +1 -0
  739. package/dist/ui/uiConstants.d.ts +253 -0
  740. package/dist/ui/uiConstants.d.ts.map +1 -0
  741. package/dist/ui/uiConstants.js +437 -0
  742. package/dist/ui/uiConstants.js.map +1 -0
  743. package/dist/utils/analytics.d.ts +2 -0
  744. package/dist/utils/analytics.d.ts.map +1 -0
  745. package/dist/utils/analytics.js +51 -0
  746. package/dist/utils/analytics.js.map +1 -0
  747. package/dist/utils/askUserPrompt.d.ts +21 -0
  748. package/dist/utils/askUserPrompt.d.ts.map +1 -0
  749. package/dist/utils/askUserPrompt.js +87 -0
  750. package/dist/utils/askUserPrompt.js.map +1 -0
  751. package/dist/utils/asyncUtils.d.ts +95 -0
  752. package/dist/utils/asyncUtils.d.ts.map +1 -0
  753. package/dist/utils/asyncUtils.js +286 -0
  754. package/dist/utils/asyncUtils.js.map +1 -0
  755. package/dist/utils/debugLogger.d.ts +6 -0
  756. package/dist/utils/debugLogger.d.ts.map +1 -0
  757. package/dist/utils/debugLogger.js +39 -0
  758. package/dist/utils/debugLogger.js.map +1 -0
  759. package/dist/utils/errorUtils.d.ts +12 -0
  760. package/dist/utils/errorUtils.d.ts.map +1 -0
  761. package/dist/utils/errorUtils.js +83 -0
  762. package/dist/utils/errorUtils.js.map +1 -0
  763. package/dist/utils/frontmatter.d.ts +10 -0
  764. package/dist/utils/frontmatter.d.ts.map +1 -0
  765. package/dist/utils/frontmatter.js +78 -0
  766. package/dist/utils/frontmatter.js.map +1 -0
  767. package/dist/utils/lambdaClient.d.ts +35 -0
  768. package/dist/utils/lambdaClient.d.ts.map +1 -0
  769. package/dist/utils/lambdaClient.js +81 -0
  770. package/dist/utils/lambdaClient.js.map +1 -0
  771. package/dist/utils/packageInfo.d.ts +14 -0
  772. package/dist/utils/packageInfo.d.ts.map +1 -0
  773. package/dist/utils/packageInfo.js +45 -0
  774. package/dist/utils/packageInfo.js.map +1 -0
  775. package/dist/utils/planFormatter.d.ts +34 -0
  776. package/dist/utils/planFormatter.d.ts.map +1 -0
  777. package/dist/utils/planFormatter.js +141 -0
  778. package/dist/utils/planFormatter.js.map +1 -0
  779. package/dist/utils/projectRegistration.d.ts +61 -0
  780. package/dist/utils/projectRegistration.d.ts.map +1 -0
  781. package/dist/utils/projectRegistration.js +212 -0
  782. package/dist/utils/projectRegistration.js.map +1 -0
  783. package/dist/utils/securityUtils.d.ts +145 -0
  784. package/dist/utils/securityUtils.d.ts.map +1 -0
  785. package/dist/utils/securityUtils.js +507 -0
  786. package/dist/utils/securityUtils.js.map +1 -0
  787. package/dist/utils/statusReporter.d.ts +6 -0
  788. package/dist/utils/statusReporter.d.ts.map +1 -0
  789. package/dist/utils/statusReporter.js +26 -0
  790. package/dist/utils/statusReporter.js.map +1 -0
  791. package/dist/workspace.d.ts +8 -0
  792. package/dist/workspace.d.ts.map +1 -0
  793. package/dist/workspace.js +135 -0
  794. package/dist/workspace.js.map +1 -0
  795. package/dist/workspace.validator.d.ts +49 -0
  796. package/dist/workspace.validator.d.ts.map +1 -0
  797. package/dist/workspace.validator.js +215 -0
  798. package/dist/workspace.validator.js.map +1 -0
  799. package/package.json +1 -1
@@ -0,0 +1,2156 @@
1
+ /**
2
+ * Interactive Shell - Full interactive CLI experience with rich UI.
3
+ *
4
+ * Usage:
5
+ * agi # Start interactive shell
6
+ * agi "initial prompt" # Start with initial prompt
7
+ *
8
+ * Features:
9
+ * - Rich terminal UI with status bar
10
+ * - Command history
11
+ * - Streaming responses
12
+ * - Tool execution display
13
+ * - Ctrl+C to interrupt
14
+ */
15
+ import { stdin, stdout, exit } from 'node:process';
16
+ import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';
17
+ import { resolve, dirname, join } from 'node:path';
18
+ import { homedir } from 'node:os';
19
+ import { fileURLToPath } from 'node:url';
20
+ import { exec as childExec } from 'node:child_process';
21
+ import { promisify } from 'node:util';
22
+ import chalk from 'chalk';
23
+ import gradientString from 'gradient-string';
24
+ import { getHITL, hitlEvents } from '../core/hitl.js';
25
+ import { reportUsageToFirebase, fetchUserBalanceMicrodollars } from '../core/usageTracker.js';
26
+ import { getAuthStatus } from '../core/auth.js';
27
+ // Connector imports removed — CLI is local-only, no GitHub gate.
28
+ // Stub functions (antiTermination removed)
29
+ const initializeProtection = (_config) => { };
30
+ const enterCriticalSection = (_name) => { };
31
+ const exitCriticalSection = (_name) => { };
32
+ // Import real shutdown handler for reliable Ctrl+C handling
33
+ import { authorizedShutdown, installSignalHandlers, onShutdown } from '../core/shutdown.js';
34
+ import { resolveProfileConfig } from '../config.js';
35
+ import { hasAgentProfile } from '../core/agentProfiles.js';
36
+ import { createAgentController } from '../runtime/agentController.js';
37
+ import { resolveWorkspaceCaptureOptions, buildWorkspaceContext } from '../workspace.js';
38
+ import { loadAllSecrets, listSecretDefinitions, setSecretValue, getSecretValue } from '../core/secretStore.js';
39
+ import { getConfiguredProviders, getProvidersStatus, quickCheckProviders, getCachedDiscoveredModels, sortModelsByPriority } from '../core/modelDiscovery.js';
40
+ import { saveModelPreference } from '../core/preferences.js';
41
+ import { setDebugMode, debugSnippet } from '../utils/debugLogger.js';
42
+ const exec = promisify(childExec);
43
+ import { ensureNextSteps } from '../core/finalResponseFormatter.js';
44
+ import { getTaskCompletionDetector, detectFailingTestOrBuild } from '../core/taskCompletionDetector.js';
45
+ import { checkForUpdates, performBackgroundUpdate } from '../core/updateChecker.js';
46
+ import { startNewRun } from '../tools/fileChangeTracker.js';
47
+ import { onSudoPasswordNeeded, offSudoPasswordNeeded, provideSudoPassword } from '../core/sudoPasswordManager.js';
48
+ import { reportStatus, setStatusSink } from '../utils/statusReporter.js';
49
+ import { isSafetyRefusal } from '../core/refusalDetection.js';
50
+ import { getSharedMcpManager } from '../plugins/tools/mcp/mcpClient.js';
51
+ // Timeout constants for regular prompt processing (reasoning models like DeepSeek)
52
+ const PROMPT_REASONING_TIMEOUT_MS = 60 * 1000; // 60 seconds max for reasoning-only without action
53
+ // Per-step timeout: how long we'll wait for the *next* event before
54
+ // declaring the stream stuck and bailing out. Set generously (10 min) so
55
+ // long-running tool calls (a build, a slow `npm install`, etc.) don't
56
+ // trip it, but short enough that a dead provider / network drop doesn't
57
+ // leave the user staring at a forever-spinner with Ctrl+C as their only
58
+ // escape. iterateWithTimeout resets this per-event, so it only fires on
59
+ // genuine inactivity. Override with EROSOLAR_STEP_TIMEOUT_MS for tests.
60
+ const PROMPT_STEP_TIMEOUT_MS = (() => {
61
+ const env = process.env['EROSOLAR_STEP_TIMEOUT_MS'];
62
+ const parsed = env ? Number(env) : NaN;
63
+ if (Number.isFinite(parsed) && parsed > 0)
64
+ return parsed;
65
+ return 10 * 60 * 1000;
66
+ })();
67
+ const HITL_TOOL_PREFIX = 'HITL_';
68
+ const isHitlToolName = (toolName) => toolName.startsWith(HITL_TOOL_PREFIX);
69
+ /**
70
+ * Iterate over an async iterator with a timeout per iteration.
71
+ * If no event is received within the timeout, yields a special timeout marker.
72
+ * Emits timeout markers without aborting the underlying iterator.
73
+ * Pass Infinity to disable timeouts entirely.
74
+ */
75
+ async function* iterateWithTimeout(iterator, timeoutMs, onTimeout) {
76
+ const asyncIterator = iterator[Symbol.asyncIterator]();
77
+ let pending = null;
78
+ let done = false;
79
+ // If timeout is Infinity or not a positive finite number, disable timeout entirely
80
+ const timeoutDisabled = !Number.isFinite(timeoutMs) || timeoutMs <= 0;
81
+ try {
82
+ while (true) {
83
+ if (!pending) {
84
+ pending = asyncIterator.next();
85
+ }
86
+ let result;
87
+ if (timeoutDisabled) {
88
+ // No timeout - just wait for the next value
89
+ result = await pending;
90
+ }
91
+ else {
92
+ // Race between pending result and timeout
93
+ const timeoutPromise = new Promise((resolve) => setTimeout(() => resolve({ __timeout: true }), timeoutMs));
94
+ result = await Promise.race([pending, timeoutPromise]);
95
+ }
96
+ if ('__timeout' in result) {
97
+ onTimeout?.();
98
+ yield result;
99
+ continue;
100
+ }
101
+ pending = null;
102
+ if (result.done) {
103
+ done = true;
104
+ return;
105
+ }
106
+ yield result.value;
107
+ }
108
+ }
109
+ finally {
110
+ if (!done && typeof asyncIterator.return === 'function') {
111
+ try {
112
+ await asyncIterator.return(undefined);
113
+ }
114
+ catch {
115
+ // Ignore return errors
116
+ }
117
+ }
118
+ }
119
+ }
120
+ let cachedVersion = null;
121
+ // Get version from package.json
122
+ function getVersion() {
123
+ if (cachedVersion)
124
+ return cachedVersion;
125
+ try {
126
+ const __filename = fileURLToPath(import.meta.url);
127
+ const pkgPath = resolve(dirname(__filename), '../../package.json');
128
+ const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8'));
129
+ cachedVersion = pkg.version || '0.0.0';
130
+ return cachedVersion;
131
+ }
132
+ catch {
133
+ return '0.0.0';
134
+ }
135
+ }
136
+ // Clean minimal banner
137
+ const BANNER_GRADIENT = gradientString(['#0EA5E9', '#6366F1', '#EC4899']);
138
+ const EROSOLAR_BANNER_RENDERED = BANNER_GRADIENT(' ◈ Trenchwork — a freedom coding CLI powered by DeepSeek');
139
+ /**
140
+ * Run the fully interactive shell with rich UI.
141
+ */
142
+ export async function runInteractiveShell(options) {
143
+ // Install signal handlers FIRST for reliable Ctrl+C handling
144
+ installSignalHandlers();
145
+ // Initialize protection systems
146
+ initializeProtection({
147
+ interceptSignals: true,
148
+ monitorResources: true,
149
+ armorExceptions: true,
150
+ enableWatchdog: true,
151
+ verbose: process.env['EROSOLAR_DEBUG'] === '1',
152
+ });
153
+ // The CLI is interactive-only. There is no piped / one-shot / headless
154
+ // mode — every session runs through the Ink renderer against a live
155
+ // terminal. If stdin or stdout isn't a TTY, fail fast with a clear
156
+ // message rather than emitting unrenderable escape sequences into a
157
+ // pipe.
158
+ if (!stdin.isTTY || !stdout.isTTY) {
159
+ reportStatus('erosolar requires an interactive terminal. Run it directly in a TTY (no pipes, no shell redirection).');
160
+ exit(1);
161
+ }
162
+ loadAllSecrets();
163
+ const parsed = parseArgs(options.argv);
164
+ const profile = resolveProfile();
165
+ const workingDir = process.cwd();
166
+ const workspaceOptions = resolveWorkspaceCaptureOptions(process.env);
167
+ const workspaceContext = buildWorkspaceContext(workingDir, workspaceOptions);
168
+ // Resolve profile config for model info
169
+ const profileConfig = resolveProfileConfig(profile, workspaceContext);
170
+ // Create agent controller
171
+ const controller = await createAgentController({
172
+ profile,
173
+ workingDir,
174
+ workspaceContext,
175
+ env: process.env,
176
+ });
177
+ // Create the interactive shell instance
178
+ const shell = new InteractiveShell(controller, profile, profileConfig, workingDir);
179
+ // Handle initial prompt if provided
180
+ if (parsed.initialPrompt) {
181
+ shell.queuePrompt(parsed.initialPrompt);
182
+ }
183
+ await shell.run();
184
+ }
185
+ class InteractiveShell {
186
+ controller;
187
+ profile;
188
+ profileConfig;
189
+ workingDir;
190
+ // The shell holds an `IPromptController`-shaped value so the same
191
+ // call sites work whether we picked the legacy renderer or the Ink
192
+ // adapter (selected by EROSOLAR_INK=1, see createPromptController).
193
+ // Using `any` here keeps existing call signatures unchanged — the
194
+ // interface declares the same surface but TS would otherwise insist
195
+ // we touch every call site to declare nullability.
196
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
197
+ promptController = null;
198
+ isProcessing = false;
199
+ shouldExit = false;
200
+ pendingPrompts = [];
201
+ debugEnabled = false;
202
+ ctrlCCount = 0;
203
+ lastCtrlCTime = 0;
204
+ // Set when the user Ctrl+C interrupts a run; suppresses the auto-continue
205
+ // re-launch in the finally block of processPrompt so the agent doesn't
206
+ // immediately resume the work the user just cancelled. Cleared when the
207
+ // user submits a fresh prompt.
208
+ userInterruptedRun = false;
209
+ // Session-level aggregates rolled up across every processPrompt call
210
+ // and flushed to Firestore on shutdown. Bounded by the writeSessionEnd
211
+ // slicer (top 100 of each).
212
+ sessionToolsUsed = new Set();
213
+ sessionFilesModified = new Set();
214
+ sessionTokensIn = 0;
215
+ sessionTokensOut = 0;
216
+ cachedProviders = null;
217
+ secretInputMode = {
218
+ active: false,
219
+ secretId: null,
220
+ queue: [],
221
+ };
222
+ pendingModelSwitch = null;
223
+ currentResponseBuffer = '';
224
+ // Store original prompt for auto-continuation
225
+ originalPromptForAutoContinue = null;
226
+ // (Pinned prompt removed per request — field intentionally absent.)
227
+ constructor(controller, profile, profileConfig, workingDir) {
228
+ this.controller = controller;
229
+ this.profile = profile;
230
+ this.profileConfig = profileConfig;
231
+ this.workingDir = workingDir;
232
+ // Pre-fetch provider status in background
233
+ void this.fetchProviders();
234
+ }
235
+ async fetchProviders() {
236
+ try {
237
+ this.cachedProviders = await quickCheckProviders();
238
+ }
239
+ catch {
240
+ this.cachedProviders = [];
241
+ }
242
+ }
243
+ validateRequiredApiKeys() {
244
+ const missingKeys = [];
245
+ // Check DeepSeek API key (required)
246
+ if (!getSecretValue('DEEPSEEK_API_KEY')) {
247
+ missingKeys.push('DEEPSEEK_API_KEY');
248
+ }
249
+ // Prompt for missing keys directly without showing warning
250
+ if (missingKeys.length > 0 && this.promptController) {
251
+ // Queue all missing keys for input
252
+ this.secretInputMode.queue = missingKeys.slice(1); // Rest of the keys
253
+ const first = missingKeys[0];
254
+ if (first) {
255
+ // Set secret mode immediately to mask input
256
+ this.secretInputMode.active = true;
257
+ this.secretInputMode.secretId = first;
258
+ this.promptController.setSecretMode(true);
259
+ // Show the inline panel with instructions
260
+ const secrets = listSecretDefinitions();
261
+ const secret = secrets.find(s => s.id === first);
262
+ if (secret && this.promptController.supportsInlinePanel()) {
263
+ const lines = [
264
+ chalk.bold.hex('#6366F1')(`Set ${secret.label}`),
265
+ chalk.dim(secret.description),
266
+ '',
267
+ chalk.dim('Enter value (or press Enter to skip)'),
268
+ ];
269
+ this.promptController.setInlinePanel(lines);
270
+ this.promptController.setStatusMessage(`Enter ${secret.label}...`);
271
+ }
272
+ }
273
+ }
274
+ }
275
+ queuePrompt(prompt) {
276
+ this.pendingPrompts.push(prompt);
277
+ }
278
+ async run() {
279
+ // Factory-driven construction: `EROSOLAR_INK=1` picks the Ink-backed
280
+ // controller (src/ui/ink/InkPromptController.ts), otherwise the
281
+ // legacy PromptController. Both implement the same surface so
282
+ // every call site below is unchanged. Dynamic import keeps the
283
+ // legacy path's cold-start free of the React/Ink parse cost when
284
+ // the env flag is unset.
285
+ const { createPromptController } = await import('../ui/ink/InkPromptController.js');
286
+ this.promptController = await createPromptController(stdin, stdout, {
287
+ onSubmit: (text) => this.handleSubmit(text),
288
+ onQueue: (text) => this.queuePrompt(text),
289
+ onInterrupt: () => this.handleInterrupt(),
290
+ onExit: () => this.handleExit(),
291
+ onCtrlC: (info) => this.handleCtrlC(info),
292
+ onToggleAutoContinue: () => this.handleAutoContinueToggle(),
293
+ onToggleHITL: () => this.handleHITLToggle(),
294
+ });
295
+ // Register cleanup callback for graceful shutdown
296
+ onShutdown(() => {
297
+ this.shouldExit = true;
298
+ this.promptController?.stop();
299
+ setStatusSink(null);
300
+ });
301
+ // Session-end Firestore write — transitions the session row from
302
+ // `in_progress` to `completed` and rolls up the project's
303
+ // totalTokens. Best-effort: a kill -9 leaves the row stale at
304
+ // `in_progress`, which the audit portal can highlight.
305
+ onShutdown(async () => {
306
+ const sessionId = process.env['EROSOLAR_SESSION_ID'];
307
+ const projectId = process.env['EROSOLAR_PROJECT_ID'];
308
+ if (!sessionId || !projectId)
309
+ return;
310
+ try {
311
+ const { writeSessionEnd } = await import('../core/projectTracker.js');
312
+ await writeSessionEnd({
313
+ sessionId,
314
+ projectId,
315
+ outcome: this.userInterruptedRun ? 'cancelled' : 'completed',
316
+ filesModified: Array.from(this.sessionFilesModified).slice(0, 100),
317
+ toolsUsed: Array.from(this.sessionToolsUsed).slice(0, 100),
318
+ tokensIn: this.sessionTokensIn,
319
+ tokensOut: this.sessionTokensOut,
320
+ });
321
+ }
322
+ catch { /* best-effort */ }
323
+ });
324
+ setStatusSink((message) => this.promptController?.setStatusMessage(message));
325
+ // Hand the terminal off to the HITL prompt while it's open: suspend
326
+ // prompt rendering and detach our keypress handler so arrow keys aren't
327
+ // double-consumed. Restore both when the prompt closes so the next turn's
328
+ // input works correctly.
329
+ const onHitlOpen = () => {
330
+ const r = this.promptController?.getRenderer();
331
+ if (!r)
332
+ return;
333
+ try {
334
+ r.suspendPromptRendering();
335
+ }
336
+ catch { /* ignore */ }
337
+ try {
338
+ r.suspendInputCapture();
339
+ }
340
+ catch { /* ignore */ }
341
+ };
342
+ const onHitlClose = () => {
343
+ const r = this.promptController?.getRenderer();
344
+ if (!r)
345
+ return;
346
+ try {
347
+ r.resumeInputCapture();
348
+ }
349
+ catch { /* ignore */ }
350
+ try {
351
+ r.resumePromptRendering(true);
352
+ }
353
+ catch { /* ignore */ }
354
+ };
355
+ hitlEvents.on('prompt-open', onHitlOpen);
356
+ hitlEvents.on('prompt-close', onHitlClose);
357
+ onShutdown(() => {
358
+ hitlEvents.removeListener('prompt-open', onHitlOpen);
359
+ hitlEvents.removeListener('prompt-close', onHitlClose);
360
+ });
361
+ // Start the UI
362
+ this.promptController.start();
363
+ this.applyDebugState(this.debugEnabled);
364
+ // Set up sudo password prompt handler
365
+ this.setupSudoPasswordHandler();
366
+ // Set initial status
367
+ this.promptController.setChromeMeta({
368
+ directory: this.workingDir,
369
+ });
370
+ // Show welcome message
371
+ await this.showWelcome();
372
+ // Pinned prompt loading removed — feature stripped per request.
373
+ // Process any queued prompts
374
+ if (this.pendingPrompts.length > 0) {
375
+ const prompts = this.pendingPrompts.splice(0);
376
+ for (const prompt of prompts) {
377
+ await this.processPrompt(prompt);
378
+ }
379
+ }
380
+ // Keep running until exit
381
+ await this.waitForExit();
382
+ }
383
+ async showWelcome() {
384
+ const renderer = this.promptController?.getRenderer();
385
+ if (!renderer)
386
+ return;
387
+ const version = getVersion();
388
+ // Append to existing terminal history — do not clear scrollback.
389
+ // Check if DeepSeek API key is set
390
+ const apiKey = process.env.DEEPSEEK_API_KEY?.trim() || '';
391
+ const hasApiKey = apiKey.length > 0;
392
+ // Mask API key: show first 4 and last 4 chars
393
+ const maskApiKey = (key) => {
394
+ if (key.length <= 12)
395
+ return key.slice(0, 3) + '...' + key.slice(-3);
396
+ return key.slice(0, 6) + '...' + key.slice(-4);
397
+ };
398
+ // Account state for the welcome banner
399
+ const auth = getAuthStatus();
400
+ const accountLine = auth.authenticated && auth.email
401
+ ? chalk.dim(' Signed in as ') + chalk.green(auth.email) + chalk.dim(' · /logout')
402
+ : chalk.dim(' ') + chalk.yellow('Not signed in') + chalk.dim(' · /login to sync usage & credits');
403
+ // Pull account balance + connector status for signed-in users. Tight
404
+ // timeouts so slow networks can't hang launch — skip lines on miss.
405
+ // Update check runs in parallel for everyone (no auth required), with a
406
+ // hard race-timeout so a slow registry never delays the banner.
407
+ let balanceLine = null;
408
+ const updateLines = [];
409
+ const updatePromise = Promise.race([
410
+ checkForUpdates(version).catch(() => null),
411
+ new Promise((resolve) => setTimeout(() => resolve(null), 2000)),
412
+ ]);
413
+ if (auth.authenticated) {
414
+ // CLI is local-only — no GitHub connector required. Skip the
415
+ // connector lookup entirely (was a wasted Firestore round-trip
416
+ // on every launch, plus a nag prompting users to set up an
417
+ // unused connection).
418
+ const micro = await fetchUserBalanceMicrodollars(800);
419
+ if (typeof micro === 'number') {
420
+ const dollars = Math.max(0, micro) / 1_000_000;
421
+ const fmt = '$' + dollars.toFixed(4);
422
+ const exhausted = micro <= 0;
423
+ const lowish = !exhausted && micro < 100_000; // < $0.10
424
+ const colored = exhausted ? chalk.red(fmt) : (lowish ? chalk.yellow(fmt) : chalk.green(fmt));
425
+ const topup = chalk.cyan('https://trenchwork.org/portal');
426
+ balanceLine = chalk.dim(' Balance: ') + colored + chalk.dim(' · Top up at ') + topup;
427
+ }
428
+ }
429
+ // Resolve the update check BEFORE composing the welcome lines — the
430
+ // previous order built welcomeLines with `...updateLines` (the array
431
+ // was empty at that point) and only populated updateLines afterwards,
432
+ // so the upgrade banner literally never rendered. Bug shipped before
433
+ // the scoped-package rename made the check return wrong data anyway.
434
+ const updateInfo = await updatePromise;
435
+ if (updateInfo?.updateAvailable) {
436
+ updateLines.push(chalk.cyan(' ⬆ ') +
437
+ chalk.dim('Update available: ') +
438
+ chalk.yellow(`v${updateInfo.current}`) +
439
+ chalk.dim(' → ') +
440
+ chalk.green(`v${updateInfo.latest}`) +
441
+ chalk.dim(' · installing in background…'));
442
+ this.runBackgroundUpdate(updateInfo);
443
+ }
444
+ // Clean, minimal welcome - just the essentials
445
+ const welcomeLines = [
446
+ '',
447
+ EROSOLAR_BANNER_RENDERED + chalk.dim(` v${version}`),
448
+ chalk.dim(' ') + chalk.cyan('https://trenchwork.org') + chalk.dim(' · ') + chalk.cyan('https://www.npmjs.com/package/@trenchwork/erosolar'),
449
+ accountLine,
450
+ ...(balanceLine ? [balanceLine] : []),
451
+ ...updateLines,
452
+ '',
453
+ ];
454
+ if (!hasApiKey) {
455
+ // Show API key setup instructions
456
+ welcomeLines.push(chalk.yellow(' ⚠ No API key configured'), '', chalk.dim(' Get your key: ') + chalk.cyan('https://platform.deepseek.com/'), chalk.dim(' Set your key: ') + chalk.hex('#FBBF24')('/key YOUR_API_KEY'), '');
457
+ }
458
+ else {
459
+ const maskedKey = maskApiKey(apiKey);
460
+ welcomeLines.push(chalk.dim(` ${this.profileConfig.model} · ${this.profileConfig.provider}`), chalk.dim(' Key: ') + chalk.green(maskedKey) + chalk.dim(' · /help for commands'), '');
461
+ }
462
+ const welcomeContent = welcomeLines.join('\n');
463
+ // Use renderer event system instead of direct stdout writes
464
+ renderer.addEvent('banner', welcomeContent);
465
+ // Update renderer meta with model info
466
+ this.promptController?.setModelContext({
467
+ model: this.profileConfig.model,
468
+ provider: this.profileConfig.provider,
469
+ });
470
+ }
471
+ /**
472
+ * Kick off `npm install -g <pkg>@latest` in a background process. When it
473
+ * completes, surface a renderer event so the user sees the result without
474
+ * any blocking. The running CLI keeps the old code — the new version is
475
+ * picked up on next launch.
476
+ */
477
+ runBackgroundUpdate(info) {
478
+ const renderer = this.promptController?.getRenderer();
479
+ void performBackgroundUpdate(info, (msg) => {
480
+ try {
481
+ renderer?.addEvent('system', msg);
482
+ }
483
+ catch { /* ignore */ }
484
+ }).then((res) => {
485
+ if (!res.started)
486
+ return;
487
+ try {
488
+ renderer?.addEvent('system', chalk.green(`✓ Update installer launched for v${info.latest}. `) +
489
+ chalk.dim('Exit and reopen the CLI to use the new version.'));
490
+ }
491
+ catch { /* ignore */ }
492
+ }).catch(() => { });
493
+ }
494
+ /**
495
+ * Set up handler for sudo password prompts from bash tool execution.
496
+ * When a sudo command needs a password, this prompts the user securely.
497
+ */
498
+ sudoPasswordHandler = null;
499
+ setupSudoPasswordHandler() {
500
+ this.sudoPasswordHandler = async () => {
501
+ const renderer = this.promptController?.getRenderer();
502
+ if (!renderer) {
503
+ provideSudoPassword(null);
504
+ return;
505
+ }
506
+ try {
507
+ // Show password prompt
508
+ renderer.addEvent('system', chalk.yellow('🔐 Sudo password required'));
509
+ renderer.setSecretMode(true);
510
+ renderer.clearBuffer();
511
+ // Capture password input
512
+ const password = await renderer.captureInput({ allowEmpty: false, trim: true, resetBuffer: true });
513
+ // Hide password mode
514
+ renderer.setSecretMode(false);
515
+ if (password) {
516
+ provideSudoPassword(password);
517
+ renderer.addEvent('system', chalk.green('✓ Password provided'));
518
+ }
519
+ else {
520
+ provideSudoPassword(null);
521
+ renderer.addEvent('system', chalk.yellow('Sudo cancelled'));
522
+ }
523
+ }
524
+ catch (error) {
525
+ renderer.setSecretMode(false);
526
+ provideSudoPassword(null);
527
+ reportStatus('Password prompt cancelled');
528
+ }
529
+ };
530
+ onSudoPasswordNeeded(this.sudoPasswordHandler);
531
+ }
532
+ cleanupSudoPasswordHandler() {
533
+ if (this.sudoPasswordHandler) {
534
+ offSudoPasswordNeeded(this.sudoPasswordHandler);
535
+ this.sudoPasswordHandler = null;
536
+ }
537
+ }
538
+ applyDebugState(enabled, statusMessage) {
539
+ this.debugEnabled = enabled;
540
+ setDebugMode(enabled);
541
+ this.promptController?.setDebugMode(enabled);
542
+ // Show transient status message instead of chat banner
543
+ if (statusMessage) {
544
+ this.promptController?.setStatusMessage(statusMessage);
545
+ setTimeout(() => this.promptController?.setStatusMessage(null), 2000);
546
+ }
547
+ }
548
+ describeEventForDebug(event) {
549
+ switch (event.type) {
550
+ case 'message.start':
551
+ return 'message.start';
552
+ case 'message.delta': {
553
+ const snippet = debugSnippet(event.content);
554
+ return snippet ? `message.delta → ${snippet}` : 'message.delta (empty)';
555
+ }
556
+ case 'message.complete': {
557
+ const snippet = debugSnippet(event.content);
558
+ return snippet
559
+ ? `message.complete → ${snippet} (${event.elapsedMs}ms)`
560
+ : `message.complete (${event.elapsedMs}ms)`;
561
+ }
562
+ case 'tool.start':
563
+ return `tool.start ${event.toolName}`;
564
+ case 'tool.complete': {
565
+ const snippet = debugSnippet(event.result);
566
+ return snippet
567
+ ? `tool.complete ${event.toolName} → ${snippet}`
568
+ : `tool.complete ${event.toolName}`;
569
+ }
570
+ case 'tool.error':
571
+ return `tool.error ${event.toolName} → ${event.error}`;
572
+ case 'edit.explanation': {
573
+ const snippet = debugSnippet(event.content);
574
+ return snippet ? `edit.explanation → ${snippet}` : 'edit.explanation';
575
+ }
576
+ case 'error':
577
+ return `error → ${event.error}`;
578
+ case 'usage': {
579
+ const parts = [];
580
+ if (event.inputTokens != null)
581
+ parts.push(`in:${event.inputTokens}`);
582
+ if (event.outputTokens != null)
583
+ parts.push(`out:${event.outputTokens}`);
584
+ if (event.totalTokens != null)
585
+ parts.push(`total:${event.totalTokens}`);
586
+ return `usage ${parts.length ? parts.join(', ') : '(no tokens)'}`;
587
+ }
588
+ default:
589
+ return event.type;
590
+ }
591
+ }
592
+ handleDebugCommand(arg) {
593
+ const normalized = arg?.toLowerCase();
594
+ // /debug alone - toggle
595
+ if (!normalized) {
596
+ const targetState = !this.debugEnabled;
597
+ this.applyDebugState(targetState, `Debug ${targetState ? 'on' : 'off'}`);
598
+ return true;
599
+ }
600
+ // /debug status - show current state
601
+ if (normalized === 'status') {
602
+ this.promptController?.setStatusMessage(`Debug is ${this.debugEnabled ? 'on' : 'off'}`);
603
+ setTimeout(() => this.promptController?.setStatusMessage(null), 2000);
604
+ return true;
605
+ }
606
+ // /debug on|enable
607
+ if (normalized === 'on' || normalized === 'enable') {
608
+ if (this.debugEnabled) {
609
+ this.promptController?.setStatusMessage('Debug already on');
610
+ setTimeout(() => this.promptController?.setStatusMessage(null), 2000);
611
+ return true;
612
+ }
613
+ this.applyDebugState(true, 'Debug on');
614
+ return true;
615
+ }
616
+ // /debug off|disable
617
+ if (normalized === 'off' || normalized === 'disable') {
618
+ if (!this.debugEnabled) {
619
+ this.promptController?.setStatusMessage('Debug already off');
620
+ setTimeout(() => this.promptController?.setStatusMessage(null), 2000);
621
+ return true;
622
+ }
623
+ this.applyDebugState(false, 'Debug off');
624
+ return true;
625
+ }
626
+ // Invalid argument
627
+ this.promptController?.setStatusMessage(`Invalid: /debug ${arg}. Use on|off|status`);
628
+ setTimeout(() => this.promptController?.setStatusMessage(null), 2500);
629
+ return true;
630
+ }
631
+ /**
632
+ * Synthesize a user-facing response from reasoning content when the model
633
+ * provides reasoning but no actual response (common with deepseek-v4-pro).
634
+ * Extracts key conclusions and formats them as a concise response.
635
+ */
636
+ synthesizeFromReasoning(reasoning) {
637
+ if (!reasoning || reasoning.trim().length < 50) {
638
+ return null;
639
+ }
640
+ // Filter out internal meta-reasoning patterns that shouldn't be shown to user
641
+ const metaPatterns = [
642
+ /according to the rules?:?/gi,
643
+ /let me (?:use|search|look|check|find|think|analyze)/gi,
644
+ /I (?:should|need to|will|can|must) (?:use|search|look|check|find)/gi,
645
+ /⚡\s*Executing\.*/gi,
646
+ /use web\s?search/gi,
647
+ /for (?:non-)?coding (?:questions|tasks)/gi,
648
+ /answer (?:directly )?from knowledge/gi,
649
+ /this is a (?:general knowledge|coding|security)/gi,
650
+ /the user (?:is asking|wants|might be)/gi,
651
+ /however,? (?:the user|I|we)/gi,
652
+ /(?:first|next),? (?:I should|let me|I need)/gi,
653
+ ];
654
+ let filtered = reasoning;
655
+ for (const pattern of metaPatterns) {
656
+ filtered = filtered.replace(pattern, '');
657
+ }
658
+ // Split into sentences
659
+ const sentences = filtered
660
+ .split(/[.!?\n]+/)
661
+ .map(s => s.trim())
662
+ .filter(s => s.length > 20 && !/^[•\-–—*]/.test(s)); // Skip bullets and short fragments
663
+ if (sentences.length === 0) {
664
+ return null;
665
+ }
666
+ // Look for actual content (not process descriptions)
667
+ const contentPatterns = [
668
+ /(?:refers? to|involves?|relates? to|is about|concerns?)/i,
669
+ /(?:scandal|deal|agreement|proposal|plan|policy)/i,
670
+ /(?:Trump|Biden|Ukraine|Russia|president|congress)/i,
671
+ /(?:the (?:main|key|primary)|importantly)/i,
672
+ ];
673
+ const contentSentences = [];
674
+ for (const sentence of sentences) {
675
+ // Skip sentences that are clearly meta-reasoning
676
+ if (/^(?:so|therefore|thus|hence|accordingly)/i.test(sentence))
677
+ continue;
678
+ if (/(?:I should|let me|I will|I need|I can)/i.test(sentence))
679
+ continue;
680
+ for (const pattern of contentPatterns) {
681
+ if (pattern.test(sentence)) {
682
+ contentSentences.push(sentence);
683
+ break;
684
+ }
685
+ }
686
+ }
687
+ // Use content sentences if found, otherwise take last few sentences (often conclusions)
688
+ const useSentences = contentSentences.length > 0
689
+ ? contentSentences.slice(0, 3)
690
+ : sentences.slice(-3);
691
+ if (useSentences.length === 0) {
692
+ return null;
693
+ }
694
+ const response = useSentences.join('. ').replace(/\.{2,}/g, '.').trim();
695
+ // Don't prefix with "Based on my analysis" - just return clean content
696
+ return response.endsWith('.') ? response : response + '.';
697
+ }
698
+ async runLocalCommand(command) {
699
+ const renderer = this.promptController?.getRenderer();
700
+ if (!command) {
701
+ this.promptController?.setStatusMessage('Usage: /bash <command>');
702
+ setTimeout(() => this.promptController?.setStatusMessage(null), 2500);
703
+ return;
704
+ }
705
+ this.promptController?.setStatusMessage(`bash: ${command}`);
706
+ try {
707
+ const { stdout: out, stderr } = await exec(command, {
708
+ cwd: this.workingDir,
709
+ maxBuffer: 4 * 1024 * 1024,
710
+ });
711
+ const output = [out, stderr].filter(Boolean).join('').trim() || '(no output)';
712
+ renderer?.addEvent('tool', `$ ${command}\n${output}`);
713
+ }
714
+ catch (error) {
715
+ const err = error;
716
+ const output = [err.stdout, err.stderr, err.message].filter(Boolean).join('\n').trim();
717
+ renderer?.addEvent('error', `$ ${command}\n${output || 'command failed'}`);
718
+ }
719
+ finally {
720
+ this.promptController?.setStatusMessage(null);
721
+ }
722
+ }
723
+ handleSlashCommand(command) {
724
+ const trimmed = command.trim();
725
+ const lower = trimmed.toLowerCase();
726
+ // Handle /model with arguments - silent model switch
727
+ if (lower.startsWith('/model ') || lower.startsWith('/m ')) {
728
+ const arg = trimmed.slice(trimmed.indexOf(' ') + 1).trim();
729
+ if (arg) {
730
+ void this.switchModel(arg);
731
+ return true;
732
+ }
733
+ }
734
+ // Handle /model or /m alone - show interactive model picker menu
735
+ if (lower === '/model' || lower === '/m') {
736
+ this.showModelMenu();
737
+ return true;
738
+ }
739
+ // Handle /secrets with subcommands
740
+ if (lower.startsWith('/secrets') || lower.startsWith('/s ') || lower === '/s') {
741
+ const parts = trimmed.split(/\s+/);
742
+ const subCmd = parts[1]?.toLowerCase();
743
+ if (subCmd === 'set') {
744
+ const secretArg = parts[2];
745
+ void this.startSecretInput(secretArg);
746
+ return true;
747
+ }
748
+ // /secrets or /s alone - show status
749
+ this.showSecrets();
750
+ return true;
751
+ }
752
+ // Handle /key - shortcut to set DEEPSEEK_API_KEY
753
+ if (lower === '/key' || lower.startsWith('/key ')) {
754
+ const parts = trimmed.split(/\s+/);
755
+ const keyValue = parts[1];
756
+ const renderer = this.promptController?.getRenderer();
757
+ if (keyValue) {
758
+ // Direct file write - most reliable method
759
+ try {
760
+ const secretDir = join(homedir(), '.erosolar');
761
+ const secretFile = join(secretDir, 'secrets.json');
762
+ mkdirSync(secretDir, { recursive: true });
763
+ const existing = existsSync(secretFile)
764
+ ? JSON.parse(readFileSync(secretFile, 'utf-8'))
765
+ : {};
766
+ existing['DEEPSEEK_API_KEY'] = keyValue;
767
+ writeFileSync(secretFile, JSON.stringify(existing, null, 2) + '\n');
768
+ // Also set in process.env for immediate use
769
+ process.env['DEEPSEEK_API_KEY'] = keyValue;
770
+ // Show confirmation via renderer
771
+ renderer?.addEvent('system', chalk.green('✓ DEEPSEEK_API_KEY saved'));
772
+ }
773
+ catch (error) {
774
+ const msg = error instanceof Error ? error.message : String(error);
775
+ renderer?.addEvent('system', chalk.red(`✗ Failed: ${msg}`));
776
+ }
777
+ }
778
+ else {
779
+ // Show usage hint
780
+ renderer?.addEvent('system', chalk.yellow('Usage: /key YOUR_API_KEY'));
781
+ }
782
+ return true;
783
+ }
784
+ if (lower === '/help' || lower === '/h' || lower === '/?') {
785
+ this.showHelp();
786
+ return true;
787
+ }
788
+ if (lower === '/clear' || lower === '/c') {
789
+ stdout.write('\x1b[2J\x1b[H');
790
+ void this.showWelcome();
791
+ return true;
792
+ }
793
+ if (lower.startsWith('/bash') || lower.startsWith('/sh ')) {
794
+ const cmd = trimmed.replace(/^\/(bash|sh)\s*/i, '').trim();
795
+ void this.runLocalCommand(cmd);
796
+ return true;
797
+ }
798
+ // Pin/unpin slash commands removed. The pinned prompt UI was
799
+ // pulled per request; commands now silently no-op so existing
800
+ // bindings don't error.
801
+ if (lower.startsWith('/pin ') || lower === '/unpin' || lower === '/clearpin') {
802
+ return true;
803
+ }
804
+ // Toggle auto mode: off → on → dual → off
805
+ if (lower === '/auto' || lower === '/continue' || lower === '/loop' || lower === '/dual') {
806
+ this.promptController?.toggleAutoContinue();
807
+ const mode = this.promptController?.getAutoMode() ?? 'off';
808
+ this.promptController?.setStatusMessage(`Auto: ${mode}`);
809
+ setTimeout(() => this.promptController?.setStatusMessage(null), 1500);
810
+ return true;
811
+ }
812
+ if (lower === '/exit' || lower === '/quit' || lower === '/q') {
813
+ this.handleExit();
814
+ return true;
815
+ }
816
+ if (lower.startsWith('/debug')) {
817
+ const parts = trimmed.split(/\s+/);
818
+ this.handleDebugCommand(parts[1]);
819
+ return true;
820
+ }
821
+ // Keyboard shortcuts help
822
+ if (lower === '/keys' || lower === '/shortcuts' || lower === '/kb') {
823
+ this.showKeyboardShortcuts();
824
+ return true;
825
+ }
826
+ // /email and /mail are intentionally unimplemented in the CLI.
827
+ // All transactional email is handled by Cloud Functions (site/functions/index.js).
828
+ if (lower.startsWith('/email') || lower.startsWith('/mail')) {
829
+ const renderer = this.promptController?.getRenderer();
830
+ const msg = 'Email sending is handled by the Cloud Functions backend, not the CLI. See site/functions/index.js (sendProtonEmail, requestHuman, onUserCreate, maybeNotifyBalance).';
831
+ if (renderer) {
832
+ renderer.addEvent('response', msg);
833
+ }
834
+ else {
835
+ console.log(msg);
836
+ }
837
+ return true;
838
+ }
839
+ // Session stats
840
+ if (lower === '/stats' || lower === '/status') {
841
+ this.showSessionStats();
842
+ return true;
843
+ }
844
+ return false;
845
+ }
846
+ /**
847
+ * Switch model silently without writing to chat.
848
+ * Accepts formats: "provider", "provider model", "provider/model", or "model"
849
+ * Updates status bar to show new model.
850
+ */
851
+ async switchModel(arg) {
852
+ // Ensure we have provider info
853
+ if (!this.cachedProviders) {
854
+ await this.fetchProviders();
855
+ }
856
+ const providers = this.cachedProviders || [];
857
+ const configuredProviders = getConfiguredProviders();
858
+ let targetProvider = null;
859
+ let targetModel = null;
860
+ // Parse argument: could be "provider model", "provider/model", "provider", or just "model"
861
+ // Check for space-separated format first: "openai o1-pro"
862
+ const parts = arg.split(/[\s/]+/);
863
+ if (parts.length >= 2) {
864
+ // Try first part as provider
865
+ const providerMatch = this.matchProvider(parts[0] || '');
866
+ if (providerMatch) {
867
+ targetProvider = providerMatch;
868
+ targetModel = parts.slice(1).join('/'); // Rest is model (handle models with slashes)
869
+ }
870
+ else {
871
+ // First part isn't a provider, treat whole arg as model name
872
+ const inferredProvider = this.inferProviderFromModel(arg.replace(/\s+/g, '-'));
873
+ if (inferredProvider) {
874
+ targetProvider = inferredProvider;
875
+ targetModel = arg.replace(/\s+/g, '-');
876
+ }
877
+ }
878
+ }
879
+ else {
880
+ // Single token - could be provider or model
881
+ const matched = this.matchProvider(arg);
882
+ if (matched) {
883
+ targetProvider = matched;
884
+ // Use provider's best model
885
+ const providerStatus = providers.find(p => p.provider === targetProvider);
886
+ targetModel = providerStatus?.latestModel || null;
887
+ }
888
+ else {
889
+ // Assume it's a model name - try to infer provider from model prefix
890
+ const inferredProvider = this.inferProviderFromModel(arg);
891
+ if (inferredProvider) {
892
+ targetProvider = inferredProvider;
893
+ targetModel = arg;
894
+ }
895
+ }
896
+ }
897
+ // Validate we have a valid provider
898
+ if (!targetProvider) {
899
+ // Silent error - just flash status briefly
900
+ this.promptController?.setStatusMessage(`Unknown: ${arg}`);
901
+ setTimeout(() => this.promptController?.setStatusMessage(null), 2000);
902
+ return;
903
+ }
904
+ // Check provider is configured
905
+ const providerInfo = configuredProviders.find(p => p.id === targetProvider);
906
+ if (!providerInfo) {
907
+ // Provider not configured - offer to set up API key
908
+ const secretMap = {
909
+ 'deepseek': 'DEEPSEEK_API_KEY',
910
+ };
911
+ const secretId = secretMap[targetProvider];
912
+ if (secretId) {
913
+ this.promptController?.setStatusMessage(`${targetProvider} needs API key - setting up...`);
914
+ // Store the pending model switch to complete after secret is set
915
+ this.pendingModelSwitch = { provider: targetProvider, model: targetModel };
916
+ setTimeout(() => this.promptForSecret(secretId), 500);
917
+ return;
918
+ }
919
+ // Provider not supported
920
+ this.promptController?.setStatusMessage(`${targetProvider} not available - only DeepSeek is supported`);
921
+ setTimeout(() => this.promptController?.setStatusMessage(null), 2000);
922
+ return;
923
+ }
924
+ // Get model if not specified
925
+ if (!targetModel) {
926
+ const providerStatus = providers.find(p => p.provider === targetProvider);
927
+ targetModel = providerStatus?.latestModel || providerInfo.latestModel;
928
+ }
929
+ // Save preference and update config
930
+ saveModelPreference(this.profile, {
931
+ provider: targetProvider,
932
+ model: targetModel,
933
+ });
934
+ // Update local config
935
+ this.profileConfig = {
936
+ ...this.profileConfig,
937
+ provider: targetProvider,
938
+ model: targetModel,
939
+ };
940
+ // Update controller's model
941
+ await this.controller.switchModel({
942
+ provider: targetProvider,
943
+ model: targetModel,
944
+ });
945
+ // Update status bar - this displays the model below the chat box
946
+ this.promptController?.setModelContext({
947
+ model: targetModel,
948
+ provider: targetProvider,
949
+ });
950
+ // Silent success - no chat output, just status bar update
951
+ }
952
+ /**
953
+ * Match user input to a provider ID (fuzzy matching)
954
+ */
955
+ matchProvider(input) {
956
+ const lower = input.toLowerCase();
957
+ const providers = getConfiguredProviders();
958
+ // Exact match
959
+ const exact = providers.find(p => p.id === lower || p.name.toLowerCase() === lower);
960
+ if (exact)
961
+ return exact.id;
962
+ // Prefix match
963
+ const prefix = providers.find(p => p.id.startsWith(lower) || p.name.toLowerCase().startsWith(lower));
964
+ if (prefix)
965
+ return prefix.id;
966
+ // Alias matching
967
+ const aliases = {
968
+ 'claude': 'anthropic',
969
+ 'ant': 'anthropic',
970
+ 'gpt': 'openai',
971
+ 'oai': 'openai',
972
+ 'gemini': 'google',
973
+ 'gem': 'google',
974
+ 'ds': 'deepseek',
975
+ 'deep': 'deepseek',
976
+ 'grok': 'xai',
977
+ 'x': 'xai',
978
+ 'local': 'ollama',
979
+ 'llama': 'ollama',
980
+ };
981
+ if (aliases[lower]) {
982
+ const aliased = providers.find(p => p.id === aliases[lower]);
983
+ if (aliased)
984
+ return aliased.id;
985
+ }
986
+ return null;
987
+ }
988
+ /**
989
+ * Infer provider from model name
990
+ */
991
+ inferProviderFromModel(model) {
992
+ const lower = model.toLowerCase();
993
+ if (lower.startsWith('claude') || lower.startsWith('opus') || lower.startsWith('sonnet') || lower.startsWith('haiku')) {
994
+ return 'anthropic';
995
+ }
996
+ if (lower.startsWith('gpt') || lower.startsWith('o1') || lower.startsWith('o3') || lower.startsWith('codex')) {
997
+ return 'openai';
998
+ }
999
+ if (lower.startsWith('gemini')) {
1000
+ return 'google';
1001
+ }
1002
+ if (lower.startsWith('deepseek')) {
1003
+ return 'deepseek';
1004
+ }
1005
+ if (lower.startsWith('grok')) {
1006
+ return 'xai';
1007
+ }
1008
+ if (lower.startsWith('llama') || lower.startsWith('mistral') || lower.startsWith('qwen')) {
1009
+ return 'ollama';
1010
+ }
1011
+ return null;
1012
+ }
1013
+ /**
1014
+ * Show interactive model picker menu (Claude Code style).
1015
+ * Auto-discovers latest models from each provider's API.
1016
+ * Uses arrow key navigation with inline panel display.
1017
+ */
1018
+ showModelMenu() {
1019
+ if (!this.promptController?.supportsInlinePanel()) {
1020
+ this.promptController?.setStatusMessage('Use /model <provider> <model> to switch');
1021
+ setTimeout(() => this.promptController?.setStatusMessage(null), 3000);
1022
+ return;
1023
+ }
1024
+ // Show loading indicator
1025
+ this.promptController?.setStatusMessage('Discovering models...');
1026
+ // Fetch latest models from APIs
1027
+ void this.fetchAndShowModelMenu();
1028
+ }
1029
+ /**
1030
+ * Fetch models from provider APIs and show the interactive menu.
1031
+ */
1032
+ async fetchAndShowModelMenu() {
1033
+ try {
1034
+ // Get provider status and cached models
1035
+ const allProviders = getProvidersStatus();
1036
+ const cachedModels = getCachedDiscoveredModels();
1037
+ const currentModel = this.profileConfig.model;
1038
+ const currentProvider = this.profileConfig.provider;
1039
+ // Try to get fresh models from configured providers (with short timeout)
1040
+ let freshStatus = [];
1041
+ try {
1042
+ freshStatus = await Promise.race([
1043
+ quickCheckProviders(),
1044
+ new Promise((resolve) => setTimeout(() => resolve([]), 3000))
1045
+ ]);
1046
+ }
1047
+ catch {
1048
+ // Use cached data on error
1049
+ }
1050
+ // Build menu items - group by provider, show models
1051
+ const menuItems = [];
1052
+ for (const provider of allProviders) {
1053
+ // Get models for this provider
1054
+ const providerCachedModels = cachedModels.filter(m => m.provider === provider.id);
1055
+ const freshProvider = freshStatus.find(s => s.provider === provider.id);
1056
+ // Collect model IDs
1057
+ let modelIds = [];
1058
+ // Add fresh latest model if available
1059
+ if (freshProvider?.available && freshProvider.latestModel) {
1060
+ modelIds.push(freshProvider.latestModel);
1061
+ }
1062
+ // Add cached models
1063
+ modelIds.push(...providerCachedModels.map(m => m.id));
1064
+ // Add provider's default model
1065
+ if (provider.latestModel && !modelIds.includes(provider.latestModel)) {
1066
+ modelIds.push(provider.latestModel);
1067
+ }
1068
+ // Remove duplicates and sort by priority (best first)
1069
+ modelIds = [...new Set(modelIds)];
1070
+ modelIds = sortModelsByPriority(provider.id, modelIds);
1071
+ // Limit to top 3 models per provider
1072
+ const topModels = modelIds.slice(0, 3);
1073
+ if (!provider.configured) {
1074
+ // Show unconfigured provider as single disabled item
1075
+ menuItems.push({
1076
+ id: `${provider.id}:setup`,
1077
+ label: `${provider.name}`,
1078
+ description: `(${provider.envVar} not set - select to configure)`,
1079
+ category: provider.id,
1080
+ isActive: false,
1081
+ disabled: false, // Allow selection to configure
1082
+ });
1083
+ }
1084
+ else if (topModels.length === 0) {
1085
+ // No models found - show provider with default
1086
+ menuItems.push({
1087
+ id: `${provider.id}:${provider.latestModel}`,
1088
+ label: `${provider.name} › ${provider.latestModel}`,
1089
+ description: 'default',
1090
+ category: provider.id,
1091
+ isActive: provider.id === currentProvider && provider.latestModel === currentModel,
1092
+ disabled: false,
1093
+ });
1094
+ }
1095
+ else {
1096
+ // Show each model as selectable item
1097
+ for (const modelId of topModels) {
1098
+ const isCurrentModel = provider.id === currentProvider && modelId === currentModel;
1099
+ const modelLabel = this.formatModelLabel(modelId);
1100
+ menuItems.push({
1101
+ id: `${provider.id}:${modelId}`,
1102
+ label: `${provider.name} › ${modelLabel}`,
1103
+ description: isCurrentModel ? '(current)' : '',
1104
+ category: provider.id,
1105
+ isActive: isCurrentModel,
1106
+ disabled: false,
1107
+ });
1108
+ }
1109
+ }
1110
+ }
1111
+ // Clear loading message
1112
+ this.promptController?.setStatusMessage(null);
1113
+ // Show the interactive menu
1114
+ this.promptController?.setMenu(menuItems, { title: '🤖 Select Model' }, (selected) => {
1115
+ if (selected) {
1116
+ // Parse provider:model format
1117
+ const [providerId, ...modelParts] = selected.id.split(':');
1118
+ const modelId = modelParts.join(':');
1119
+ if (modelId === 'setup') {
1120
+ // Configure provider API key
1121
+ const secretMap = {
1122
+ 'deepseek': 'DEEPSEEK_API_KEY',
1123
+ };
1124
+ const secretId = secretMap[providerId ?? ''];
1125
+ if (secretId) {
1126
+ this.promptForSecret(secretId);
1127
+ }
1128
+ }
1129
+ else {
1130
+ // Switch to selected model
1131
+ void this.switchModel(`${providerId} ${modelId}`);
1132
+ }
1133
+ }
1134
+ });
1135
+ }
1136
+ catch (error) {
1137
+ this.promptController?.setStatusMessage('Failed to load models');
1138
+ setTimeout(() => this.promptController?.setStatusMessage(null), 2000);
1139
+ }
1140
+ }
1141
+ /**
1142
+ * Format model ID for display (shorten long IDs).
1143
+ */
1144
+ formatModelLabel(modelId) {
1145
+ // Shorten common prefixes
1146
+ let label = modelId
1147
+ .replace(/^claude-/, '')
1148
+ .replace(/^gpt-/, 'GPT-')
1149
+ .replace(/^gemini-/, 'Gemini ')
1150
+ .replace(/^deepseek-/, 'DeepSeek ')
1151
+ .replace(/^grok-/, 'Grok ')
1152
+ .replace(/^llama/, 'Llama ')
1153
+ .replace(/^qwen-/, 'Qwen ');
1154
+ // Truncate if too long
1155
+ if (label.length > 30) {
1156
+ label = label.slice(0, 27) + '...';
1157
+ }
1158
+ return label;
1159
+ }
1160
+ showSecrets() {
1161
+ const secrets = listSecretDefinitions();
1162
+ if (!this.promptController?.supportsInlinePanel()) {
1163
+ // Fallback for non-TTY - use status message
1164
+ const setCount = secrets.filter(s => !!process.env[s.envVar]).length;
1165
+ this.promptController?.setStatusMessage(`API Keys: ${setCount}/${secrets.length} configured`);
1166
+ setTimeout(() => this.promptController?.setStatusMessage(null), 3000);
1167
+ return;
1168
+ }
1169
+ // Build interactive menu items
1170
+ const menuItems = secrets.map(secret => {
1171
+ const isSet = !!process.env[secret.envVar];
1172
+ const statusIcon = isSet ? '✓' : '✗';
1173
+ const providers = secret.providers?.length ? ` (${secret.providers.join(', ')})` : '';
1174
+ return {
1175
+ id: secret.id,
1176
+ label: `${statusIcon} ${secret.envVar}`,
1177
+ description: isSet ? 'configured' + providers : 'not set' + providers,
1178
+ isActive: isSet,
1179
+ disabled: false,
1180
+ };
1181
+ });
1182
+ // Show the interactive menu
1183
+ this.promptController.setMenu(menuItems, { title: '🔑 API Keys - Select to Configure' }, (selected) => {
1184
+ if (selected) {
1185
+ // Start secret input for selected key
1186
+ this.promptForSecret(selected.id);
1187
+ }
1188
+ });
1189
+ }
1190
+ /**
1191
+ * Start interactive secret input flow.
1192
+ * If secretArg is provided, set only that secret.
1193
+ * Otherwise, prompt for all unset secrets.
1194
+ */
1195
+ async startSecretInput(secretArg) {
1196
+ const secrets = listSecretDefinitions();
1197
+ if (secretArg) {
1198
+ // Set a specific secret
1199
+ const upper = secretArg.toUpperCase();
1200
+ const secret = secrets.find(s => s.id === upper || s.envVar === upper);
1201
+ if (!secret) {
1202
+ this.promptController?.setStatusMessage(`Unknown secret: ${secretArg}`);
1203
+ setTimeout(() => this.promptController?.setStatusMessage(null), 2000);
1204
+ return;
1205
+ }
1206
+ this.promptForSecret(secret.id);
1207
+ return;
1208
+ }
1209
+ // Queue all unset secrets for input
1210
+ const unsetSecrets = secrets.filter(s => !getSecretValue(s.id));
1211
+ if (unsetSecrets.length === 0) {
1212
+ this.promptController?.setStatusMessage('All secrets configured');
1213
+ setTimeout(() => this.promptController?.setStatusMessage(null), 2000);
1214
+ return;
1215
+ }
1216
+ // Queue all unset secrets and start with the first one
1217
+ this.secretInputMode.queue = unsetSecrets.map(s => s.id);
1218
+ const first = this.secretInputMode.queue.shift();
1219
+ if (first) {
1220
+ this.promptForSecret(first);
1221
+ }
1222
+ }
1223
+ /**
1224
+ * Show prompt for a specific secret and enable secret input mode.
1225
+ */
1226
+ promptForSecret(secretId) {
1227
+ const secrets = listSecretDefinitions();
1228
+ const secret = secrets.find(s => s.id === secretId);
1229
+ if (!secret)
1230
+ return;
1231
+ // Show in inline panel (no chat output)
1232
+ if (this.promptController?.supportsInlinePanel()) {
1233
+ const lines = [
1234
+ chalk.bold.hex('#6366F1')(`Set ${secret.label}`),
1235
+ chalk.dim(secret.description),
1236
+ '',
1237
+ chalk.dim('Enter value (or press Enter to skip)'),
1238
+ ];
1239
+ this.promptController.setInlinePanel(lines);
1240
+ }
1241
+ // Enable secret input mode
1242
+ this.secretInputMode.active = true;
1243
+ this.secretInputMode.secretId = secretId;
1244
+ this.promptController?.setSecretMode(true);
1245
+ this.promptController?.setStatusMessage(`Enter ${secret.label}...`);
1246
+ }
1247
+ /**
1248
+ * Handle secret value submission.
1249
+ */
1250
+ handleSecretValue(value) {
1251
+ const secretId = this.secretInputMode.secretId;
1252
+ if (!secretId)
1253
+ return;
1254
+ // Disable secret mode and clear inline panel
1255
+ this.promptController?.setSecretMode(false);
1256
+ this.promptController?.clearInlinePanel();
1257
+ this.secretInputMode.active = false;
1258
+ this.secretInputMode.secretId = null;
1259
+ let savedSuccessfully = false;
1260
+ if (value.trim()) {
1261
+ try {
1262
+ setSecretValue(secretId, value.trim());
1263
+ this.promptController?.setStatusMessage(`${secretId} saved`);
1264
+ savedSuccessfully = true;
1265
+ }
1266
+ catch (error) {
1267
+ const msg = error instanceof Error ? error.message : 'Failed to save';
1268
+ this.promptController?.setStatusMessage(msg);
1269
+ }
1270
+ }
1271
+ else {
1272
+ this.promptController?.setStatusMessage(`Skipped ${secretId}`);
1273
+ }
1274
+ // Clear status after a moment
1275
+ setTimeout(() => this.promptController?.setStatusMessage(null), 1500);
1276
+ // Process next secret in queue if any
1277
+ if (this.secretInputMode.queue.length > 0) {
1278
+ const next = this.secretInputMode.queue.shift();
1279
+ if (next) {
1280
+ setTimeout(() => this.promptForSecret(next), 500);
1281
+ }
1282
+ return;
1283
+ }
1284
+ // Complete pending model switch if secret was saved successfully
1285
+ if (savedSuccessfully && this.pendingModelSwitch) {
1286
+ const { provider, model } = this.pendingModelSwitch;
1287
+ this.pendingModelSwitch = null;
1288
+ // Refresh provider cache and complete the switch
1289
+ setTimeout(async () => {
1290
+ await this.fetchProviders();
1291
+ await this.switchModel(model ? `${provider} ${model}` : provider);
1292
+ }, 500);
1293
+ }
1294
+ }
1295
+ showHelp() {
1296
+ if (!this.promptController?.supportsInlinePanel()) {
1297
+ this.promptController?.setStatusMessage('Help: /model /secrets /auto /stats /keys /clear /exit');
1298
+ setTimeout(() => this.promptController?.setStatusMessage(null), 3000);
1299
+ return;
1300
+ }
1301
+ const heading = (s) => chalk.bold.hex('#8B5CF6')(s);
1302
+ const cmd = (s) => chalk.hex('#FBBF24')(s);
1303
+ const dim = (s) => chalk.dim(s);
1304
+ const lines = [
1305
+ chalk.bold.hex('#6366F1')('Trenchwork Help') + dim(' (press any key to dismiss)'),
1306
+ '',
1307
+ heading('Slash commands'),
1308
+ cmd('/model') + dim(' Cycle provider, or /model <name> to switch'),
1309
+ cmd('/key') + dim(' Set DeepSeek API key for this machine'),
1310
+ cmd('/secrets') + dim(' Show or set provider keys'),
1311
+ cmd('/auto') + dim(' Toggle auto-continue (off → on → dual → off)'),
1312
+ cmd('/bash <cmd>') + dim(' Run a one-shot local shell command'),
1313
+ cmd('/debug') + dim(' Toggle debug mode'),
1314
+ cmd('/stats') + dim(' Show session token + cost stats'),
1315
+ cmd('/keys') + dim(' Show keyboard shortcuts'),
1316
+ cmd('/clear') + dim(' Clear the screen'),
1317
+ cmd('/exit') + dim(' Quit'),
1318
+ '',
1319
+ heading('Quick start'),
1320
+ dim(' 1. /key sk-… (or set ANTHROPIC_API_KEY / OPENAI_API_KEY)'),
1321
+ dim(' 2. Type any prompt; the agent reads files, edits, runs commands'),
1322
+ dim(' 3. Ctrl+C interrupts an in-flight run'),
1323
+ '',
1324
+ heading('Companion surface'),
1325
+ dim(' Helia — Electron browser at https://trenchwork.org/helia'),
1326
+ dim(' Same Firebase account, same balance, browser-side agent.'),
1327
+ '',
1328
+ dim('Launch: erosolar (interactive)'),
1329
+ dim(' erosolar "task" (interactive, pre-filled with the prompt)'),
1330
+ dim('Docs: https://trenchwork.org/docs | README.md'),
1331
+ ];
1332
+ this.promptController.setInlinePanel(lines);
1333
+ this.scheduleInlinePanelDismiss();
1334
+ }
1335
+ showKeyboardShortcuts() {
1336
+ if (!this.promptController?.supportsInlinePanel()) {
1337
+ this.promptController?.setStatusMessage('Use /keys in interactive mode');
1338
+ setTimeout(() => this.promptController?.setStatusMessage(null), 3000);
1339
+ return;
1340
+ }
1341
+ const kb = (key) => chalk.hex('#FBBF24')(key);
1342
+ const desc = (text) => chalk.dim(text);
1343
+ const lines = [
1344
+ chalk.bold.hex('#6366F1')('Keyboard Shortcuts') + chalk.dim(' (press any key to dismiss)'),
1345
+ '',
1346
+ chalk.hex('#22D3EE')('Navigation'),
1347
+ ` ${kb('Ctrl+A')} / ${kb('Home')} ${desc('Move to start of line')}`,
1348
+ ` ${kb('Ctrl+E')} / ${kb('End')} ${desc('Move to end of line')}`,
1349
+ ` ${kb('Alt+←')} / ${kb('Alt+→')} ${desc('Move word by word')}`,
1350
+ '',
1351
+ chalk.hex('#22D3EE')('Editing'),
1352
+ ` ${kb('Ctrl+U')} ${desc('Clear entire line')}`,
1353
+ ` ${kb('Ctrl+W')} / ${kb('Alt+⌫')} ${desc('Delete word backward')}`,
1354
+ ` ${kb('Ctrl+K')} ${desc('Delete to end of line')}`,
1355
+ '',
1356
+ chalk.hex('#22D3EE')('Display'),
1357
+ ` ${kb('Ctrl+L')} ${desc('Clear screen')}`,
1358
+ ` ${kb('Ctrl+O')} ${desc('Expand last tool result')}`,
1359
+ '',
1360
+ chalk.hex('#22D3EE')('Control'),
1361
+ ` ${kb('Ctrl+C')} ${desc('Cancel input / interrupt')}`,
1362
+ ` ${kb('Ctrl+D')} ${desc('Exit (when empty)')}`,
1363
+ ` ${kb('Esc')} ${desc('Interrupt AI response')}`,
1364
+ ];
1365
+ this.promptController.setInlinePanel(lines);
1366
+ this.scheduleInlinePanelDismiss();
1367
+ }
1368
+ showSessionStats() {
1369
+ if (!this.promptController?.supportsInlinePanel()) {
1370
+ this.promptController?.setStatusMessage('Use /stats in interactive mode');
1371
+ setTimeout(() => this.promptController?.setStatusMessage(null), 3000);
1372
+ return;
1373
+ }
1374
+ const history = this.controller.getHistory();
1375
+ const messageCount = history.length;
1376
+ const userMessages = history.filter(m => m.role === 'user').length;
1377
+ const assistantMessages = history.filter(m => m.role === 'assistant').length;
1378
+ // Calculate approximate token usage from history
1379
+ let totalChars = 0;
1380
+ for (const msg of history) {
1381
+ if (typeof msg.content === 'string') {
1382
+ totalChars += msg.content.length;
1383
+ }
1384
+ }
1385
+ const approxTokens = Math.round(totalChars / 4); // Rough estimate
1386
+ const collapsedCount = this.promptController?.getRenderer?.()?.getCollapsedResultCount?.() ?? 0;
1387
+ const lines = [
1388
+ chalk.bold.hex('#6366F1')('Session Stats') + chalk.dim(' (press any key to dismiss)'),
1389
+ '',
1390
+ chalk.hex('#22D3EE')('Conversation'),
1391
+ ` ${chalk.white(messageCount.toString())} messages (${userMessages} user, ${assistantMessages} assistant)`,
1392
+ ` ${chalk.dim('~')}${chalk.white(approxTokens.toLocaleString())} ${chalk.dim('tokens (estimate)')}`,
1393
+ '',
1394
+ chalk.hex('#22D3EE')('Model'),
1395
+ ` ${chalk.white(this.profileConfig.model)} ${chalk.dim('on')} ${chalk.hex('#A855F7')(this.profileConfig.provider)}`,
1396
+ collapsedCount > 0 ? ` ${chalk.white(collapsedCount.toString())} collapsed results` : '',
1397
+ '',
1398
+ chalk.hex('#22D3EE')('Settings'),
1399
+ ` Debug: ${this.debugEnabled ? chalk.green('on') : chalk.dim('off')}`,
1400
+ ].filter(line => line !== '');
1401
+ this.promptController.setInlinePanel(lines);
1402
+ this.scheduleInlinePanelDismiss();
1403
+ }
1404
+ async showMcpStatus() {
1405
+ const manager = getSharedMcpManager(this.workingDir);
1406
+ await manager.init();
1407
+ const entries = manager.getEntries();
1408
+ if (!this.promptController?.supportsInlinePanel()) {
1409
+ const summary = entries.length === 0
1410
+ ? 'No MCP servers configured (.erosolar/mcp.json)'
1411
+ : entries.map(e => e.status === 'connected'
1412
+ ? `${e.name}: ${e.tools.length} tools`
1413
+ : `${e.name}: ERROR (${e.error})`).join(' · ');
1414
+ this.promptController?.setStatusMessage(summary);
1415
+ setTimeout(() => this.promptController?.setStatusMessage(null), 4000);
1416
+ return;
1417
+ }
1418
+ const lines = [
1419
+ chalk.bold.hex('#6366F1')('MCP Servers') + chalk.dim(' (.erosolar/mcp.json)'),
1420
+ '',
1421
+ ];
1422
+ if (entries.length === 0) {
1423
+ lines.push(chalk.dim(' No servers configured.'));
1424
+ lines.push(chalk.dim(' Add entries to ~/.erosolar/mcp.json or <project>/.erosolar/mcp.json.'));
1425
+ }
1426
+ else {
1427
+ for (const entry of entries) {
1428
+ if (entry.status === 'connected') {
1429
+ lines.push(` ${chalk.green('●')} ${chalk.white(entry.name)} ` +
1430
+ chalk.dim(`${entry.spec.command}${entry.spec.args?.length ? ' ' + entry.spec.args.join(' ') : ''}`));
1431
+ lines.push(` ${chalk.dim('tools: ')}${chalk.hex('#22D3EE')(String(entry.tools.length))}`);
1432
+ for (const t of entry.tools.slice(0, 8)) {
1433
+ lines.push(` ${chalk.dim('·')} ${chalk.white(t.name)}`);
1434
+ }
1435
+ if (entry.tools.length > 8) {
1436
+ lines.push(` ${chalk.dim(`… +${entry.tools.length - 8} more`)}`);
1437
+ }
1438
+ }
1439
+ else {
1440
+ lines.push(` ${chalk.red('●')} ${chalk.white(entry.name)} ${chalk.red('error')}`);
1441
+ lines.push(` ${chalk.dim(entry.error)}`);
1442
+ }
1443
+ }
1444
+ }
1445
+ this.promptController.setInlinePanel(lines);
1446
+ this.scheduleInlinePanelDismiss();
1447
+ }
1448
+ /**
1449
+ * Auto-dismiss inline panel after timeout or on next input.
1450
+ */
1451
+ inlinePanelDismissTimer = null;
1452
+ scheduleInlinePanelDismiss() {
1453
+ // Clear any existing timer
1454
+ if (this.inlinePanelDismissTimer) {
1455
+ clearTimeout(this.inlinePanelDismissTimer);
1456
+ }
1457
+ // Auto-dismiss after 8 seconds
1458
+ this.inlinePanelDismissTimer = setTimeout(() => {
1459
+ this.promptController?.clearInlinePanel();
1460
+ this.inlinePanelDismissTimer = null;
1461
+ }, 8000);
1462
+ }
1463
+ dismissInlinePanel() {
1464
+ if (this.inlinePanelDismissTimer) {
1465
+ clearTimeout(this.inlinePanelDismissTimer);
1466
+ this.inlinePanelDismissTimer = null;
1467
+ }
1468
+ this.promptController?.clearInlinePanel();
1469
+ }
1470
+ handleSubmit(text) {
1471
+ const trimmed = text.trim();
1472
+ // Handle secret input mode - capture the API key value
1473
+ if (this.secretInputMode.active && this.secretInputMode.secretId) {
1474
+ this.handleSecretValue(trimmed);
1475
+ return;
1476
+ }
1477
+ if (!trimmed) {
1478
+ return;
1479
+ }
1480
+ // Handle slash commands first - these don't go to the AI
1481
+ if (trimmed.startsWith('/')) {
1482
+ if (this.handleSlashCommand(trimmed)) {
1483
+ return;
1484
+ }
1485
+ // Unknown slash command - silent status flash, dismiss inline panel
1486
+ this.dismissInlinePanel();
1487
+ this.promptController?.setStatusMessage(`Unknown: ${trimmed.slice(0, 30)}`);
1488
+ setTimeout(() => this.promptController?.setStatusMessage(null), 2000);
1489
+ return;
1490
+ }
1491
+ // Dismiss inline panel for regular user prompts
1492
+ this.dismissInlinePanel();
1493
+ if (this.isProcessing) {
1494
+ this.pendingPrompts.push(trimmed);
1495
+ return;
1496
+ }
1497
+ void this.processPrompt(trimmed);
1498
+ }
1499
+ async processPrompt(prompt) {
1500
+ if (this.isProcessing) {
1501
+ return;
1502
+ }
1503
+ // Start new run for file change tracking (enables /revert)
1504
+ startNewRun();
1505
+ const sanitizedPrompt = prompt;
1506
+ // Store original prompt for auto-continuation (if not a continuation or auto-generated prompt)
1507
+ if (prompt !== 'continue' && !prompt.startsWith('IMPORTANT:')) {
1508
+ this.originalPromptForAutoContinue = prompt;
1509
+ // A fresh user prompt clears any prior interrupt state — this is new
1510
+ // work the user actually wants done.
1511
+ this.userInterruptedRun = false;
1512
+ // Pinned-prompt persistence removed per request — no longer
1513
+ // displayed above the chat box.
1514
+ }
1515
+ enterCriticalSection();
1516
+ this.isProcessing = true;
1517
+ this.currentResponseBuffer = '';
1518
+ this.promptController?.setStreaming(true);
1519
+ this.promptController?.setStatusMessage('🔄 Analyzing request...');
1520
+ const renderer = this.promptController?.getRenderer();
1521
+ let episodeSuccess = false;
1522
+ const toolsUsed = [];
1523
+ const filesModified = [];
1524
+ // Track reasoning content for fallback when response is empty
1525
+ let reasoningBuffer = '';
1526
+ // Track reasoning-only time to prevent models from reasoning forever without action
1527
+ let reasoningOnlyStartTime = null;
1528
+ let reasoningTimedOut = false;
1529
+ let stepTimedOut = false;
1530
+ let hitlDepth = 0;
1531
+ // Track total prompt processing time to prevent infinite loops
1532
+ const promptStartTime = Date.now();
1533
+ const TOTAL_PROMPT_TIMEOUT_MS = 24 * 60 * 60 * 1000; // 24 hours max for entire prompt without meaningful content
1534
+ let hasReceivedMeaningfulContent = false;
1535
+ // Track response content separately - tool calls don't count for reasoning timeout
1536
+ let hasReceivedResponseContent = false;
1537
+ try {
1538
+ // Use timeout-wrapped iterator to prevent hanging on slow/stuck models
1539
+ for await (const eventOrTimeout of iterateWithTimeout(this.controller.send(sanitizedPrompt), PROMPT_STEP_TIMEOUT_MS)) {
1540
+ // Check for timeout marker
1541
+ if (eventOrTimeout && typeof eventOrTimeout === 'object' && '__timeout' in eventOrTimeout) {
1542
+ if (hitlDepth > 0) {
1543
+ this.promptController?.setStatusMessage('⏱ Waiting for human decision...');
1544
+ continue;
1545
+ }
1546
+ stepTimedOut = true;
1547
+ this.promptController?.setStatusMessage(`⏱ Step timeout (${PROMPT_STEP_TIMEOUT_MS / 1000}s) - completing response`);
1548
+ // Cancel the controller so the underlying agent stops generating
1549
+ // events that would never be consumed. Without this the spinner
1550
+ // can keep ticking against a "ghost" run after the for-await
1551
+ // loop exits, and any in-flight tool keeps doing work the user
1552
+ // can't see or stop.
1553
+ try {
1554
+ this.controller.cancel('step timeout');
1555
+ }
1556
+ catch { /* best-effort */ }
1557
+ break;
1558
+ }
1559
+ // Check total elapsed time - bail out if too long without meaningful content
1560
+ const totalElapsed = Date.now() - promptStartTime;
1561
+ if (!hasReceivedMeaningfulContent && totalElapsed > TOTAL_PROMPT_TIMEOUT_MS) {
1562
+ if (renderer) {
1563
+ renderer.addEvent('response', chalk.yellow(`\n⏱ Response timeout (${Math.round(totalElapsed / 1000)}s) - completing\n`));
1564
+ }
1565
+ reasoningTimedOut = true;
1566
+ try {
1567
+ this.controller.cancel('response timeout');
1568
+ }
1569
+ catch { /* best-effort */ }
1570
+ break;
1571
+ }
1572
+ const event = eventOrTimeout;
1573
+ if (this.shouldExit) {
1574
+ break;
1575
+ }
1576
+ switch (event.type) {
1577
+ case 'message.start':
1578
+ // AI has started processing - update status to show activity
1579
+ this.currentResponseBuffer = '';
1580
+ reasoningBuffer = '';
1581
+ reasoningOnlyStartTime = null; // Reset on new message
1582
+ this.promptController?.setStatusMessage('Thinking...');
1583
+ break;
1584
+ case 'message.delta':
1585
+ // Stream content as it arrives
1586
+ this.currentResponseBuffer += event.content ?? '';
1587
+ if (renderer) {
1588
+ renderer.addEvent('stream', event.content);
1589
+ }
1590
+ // Reset reasoning timer only when we get actual non-empty content
1591
+ if (event.content && event.content.trim()) {
1592
+ reasoningOnlyStartTime = null;
1593
+ hasReceivedMeaningfulContent = true;
1594
+ hasReceivedResponseContent = true; // Track actual response content
1595
+ }
1596
+ break;
1597
+ case 'reasoning':
1598
+ // Accumulate reasoning for potential fallback synthesis
1599
+ reasoningBuffer += event.content ?? '';
1600
+ // Update status to show reasoning is actively streaming
1601
+ this.promptController?.setActivityMessage('Thinking');
1602
+ // Start the reasoning timer on first reasoning event
1603
+ if (!reasoningOnlyStartTime) {
1604
+ reasoningOnlyStartTime = Date.now();
1605
+ }
1606
+ // Display useful reasoning as 'thought' events BEFORE the response
1607
+ // The renderer's curateReasoningContent and shouldRenderThought will filter
1608
+ // to show only actionable/structured thoughts
1609
+ if (renderer && event.content?.trim()) {
1610
+ renderer.addEvent('thought', event.content);
1611
+ }
1612
+ break;
1613
+ case 'message.complete':
1614
+ // Response complete — clear thinking AND reasoning indicators
1615
+ // both. statusMessage clears 'Thinking...' (set on message.start
1616
+ // and after each tool); activityMessage clears the reasoning
1617
+ // chip (set on every 'reasoning' event but never reset until
1618
+ // the post-loop finally). Without clearing activityMessage
1619
+ // here, the spinner kept ticking between message-end and the
1620
+ // next event because composedStatus falls through to the still-
1621
+ // set 'Thinking' activity label.
1622
+ this.promptController?.setStatusMessage(null);
1623
+ this.promptController?.setActivityMessage(null);
1624
+ // Response complete - ensure final output includes required "Next steps"
1625
+ if (renderer) {
1626
+ // Use the appended field from ensureNextSteps to avoid re-rendering the entire response
1627
+ const base = (event.content ?? '').trimEnd();
1628
+ let sourceText = base || this.currentResponseBuffer;
1629
+ // If content came via message.complete but NOT via deltas, render it now as a proper response
1630
+ // This handles models that don't stream deltas (e.g., deepseek-v4-pro)
1631
+ // IMPORTANT: Do NOT re-emit content that was already streamed via 'message.delta' events
1632
+ // to prevent duplicate display of the same response
1633
+ if (base && !this.currentResponseBuffer.trim()) {
1634
+ renderer.addEvent('response', base);
1635
+ }
1636
+ // Note: We intentionally DO NOT re-emit currentResponseBuffer as a 'response' event
1637
+ // because it was already displayed via 'stream' events during message.delta handling
1638
+ // Fallback: If response is empty but we have reasoning, synthesize a response
1639
+ if (!sourceText.trim() && reasoningBuffer.trim()) {
1640
+ // Extract key conclusions from reasoning for display
1641
+ const synthesized = this.synthesizeFromReasoning(reasoningBuffer);
1642
+ if (synthesized) {
1643
+ renderer.addEvent('response', synthesized);
1644
+ sourceText = synthesized;
1645
+ }
1646
+ }
1647
+ episodeSuccess = true; // Mark episode as successful only after we have content
1648
+ // Only add "Next steps" if tools were actually used (real work done)
1649
+ // This prevents showing "Next steps" after reasoning-only responses
1650
+ if (toolsUsed.length > 0) {
1651
+ const { appended } = ensureNextSteps(sourceText);
1652
+ // Only stream the newly appended content (e.g., "Next steps:")
1653
+ // The main response was already added as a response event above
1654
+ if (appended && appended.trim()) {
1655
+ renderer.addEvent('response', appended);
1656
+ }
1657
+ }
1658
+ renderer.addEvent('response', '\n');
1659
+ }
1660
+ this.currentResponseBuffer = '';
1661
+ break;
1662
+ case 'tool.start': {
1663
+ const toolName = event.toolName;
1664
+ const args = event.parameters;
1665
+ // Default format: `ToolName(arg)` — Claude Code's idiom.
1666
+ // ChatStatic prefixes a `⏺ ` glyph for kind='tool', so this
1667
+ // string is what reads after the bullet. Shorter and more
1668
+ // scannable than `[ToolName] arg`.
1669
+ let toolDisplay = toolName;
1670
+ if (isHitlToolName(toolName)) {
1671
+ hitlDepth += 1;
1672
+ }
1673
+ // Reset reasoning timer when tools are being called (model is taking action)
1674
+ reasoningOnlyStartTime = null;
1675
+ hasReceivedMeaningfulContent = true;
1676
+ if (!toolsUsed.includes(toolName)) {
1677
+ toolsUsed.push(toolName);
1678
+ }
1679
+ this.sessionToolsUsed.add(toolName);
1680
+ const filePath = args?.['file_path'];
1681
+ if (filePath && (toolName === 'Write' || toolName === 'Edit')) {
1682
+ if (!filesModified.includes(filePath)) {
1683
+ filesModified.push(filePath);
1684
+ }
1685
+ this.sessionFilesModified.add(filePath);
1686
+ }
1687
+ if (toolName === 'Bash' && args?.['command']) {
1688
+ toolDisplay = `Bash(${String(args['command']).slice(0, 120)})`;
1689
+ }
1690
+ else if (toolName === 'Read' && args?.['file_path']) {
1691
+ toolDisplay = `Read(${args['file_path']})`;
1692
+ }
1693
+ else if (toolName === 'Write' && args?.['file_path']) {
1694
+ toolDisplay = `Write(${args['file_path']})`;
1695
+ }
1696
+ else if (toolName === 'Edit' && args?.['file_path']) {
1697
+ toolDisplay = `Edit(${args['file_path']})`;
1698
+ }
1699
+ else if (toolName === 'Search' && args?.['pattern']) {
1700
+ toolDisplay = `Search(${args['pattern']})`;
1701
+ }
1702
+ else if (toolName === 'Grep' && args?.['pattern']) {
1703
+ toolDisplay = `Grep(${args['pattern']})`;
1704
+ }
1705
+ else if (toolName === 'WebSearch' && args?.['query']) {
1706
+ toolDisplay = `WebSearch("${String(args['query']).slice(0, 80)}")`;
1707
+ }
1708
+ else if (toolName === 'WebExtract') {
1709
+ const urlsArg = args?.['urls'];
1710
+ const urls = Array.isArray(urlsArg)
1711
+ ? urlsArg.filter((u) => typeof u === 'string')
1712
+ : typeof args?.['url'] === 'string'
1713
+ ? [args['url']]
1714
+ : [];
1715
+ const display = urls.length > 0
1716
+ ? urls.length === 1 ? urls[0] : `${urls[0]} (+${urls.length - 1} more)`
1717
+ : '...';
1718
+ toolDisplay = `WebExtract(${display})`;
1719
+ }
1720
+ if (renderer) {
1721
+ renderer.addEvent('tool', toolDisplay);
1722
+ }
1723
+ // Provide explanatory status messages for different tool types
1724
+ let statusMsg = '';
1725
+ if (toolName === 'Bash') {
1726
+ statusMsg = `Running: ${args?.['command'] ? String(args['command']).slice(0, 40) : '...'}`;
1727
+ }
1728
+ else if (toolName === 'Edit' || toolName === 'Write') {
1729
+ statusMsg = `📝 Editing file: ${args?.['file_path'] || '...'}`;
1730
+ }
1731
+ else if (toolName === 'Read') {
1732
+ statusMsg = `📖 Reading file: ${args?.['file_path'] || '...'}`;
1733
+ }
1734
+ else if (toolName === 'Search' || toolName === 'Grep') {
1735
+ statusMsg = `🔍 Searching: ${args?.['pattern'] ? String(args['pattern']).slice(0, 30) : '...'}`;
1736
+ }
1737
+ else if (toolName === 'WebSearch') {
1738
+ statusMsg = `🌐 Searching web: ${args?.['query'] ? String(args['query']).slice(0, 40) : '...'}`;
1739
+ }
1740
+ else if (toolName === 'WebExtract') {
1741
+ const urlsArg = args?.['urls'];
1742
+ const firstUrl = Array.isArray(urlsArg)
1743
+ ? urlsArg.find((u) => typeof u === 'string')
1744
+ : typeof args?.['url'] === 'string' ? args['url'] : '...';
1745
+ statusMsg = `🌐 Extracting: ${String(firstUrl ?? '...').slice(0, 50)}`;
1746
+ }
1747
+ else {
1748
+ statusMsg = `🔧 Running ${toolName}...`;
1749
+ }
1750
+ this.promptController?.setStatusMessage(statusMsg);
1751
+ break;
1752
+ }
1753
+ case 'tool.complete': {
1754
+ if (isHitlToolName(event.toolName)) {
1755
+ hitlDepth = Math.max(0, hitlDepth - 1);
1756
+ }
1757
+ // Clear the "Running X..." status since tool is complete
1758
+ this.promptController?.setStatusMessage('Thinking...');
1759
+ // Reset reasoning timer after tool completes
1760
+ reasoningOnlyStartTime = null;
1761
+ // The legacy "Done:" header for Bash was redundant — the
1762
+ // tool-result item now renders with its own ` ↳ ` indent
1763
+ // so the call→result pairing is visually obvious without
1764
+ // a separate header line.
1765
+ // Pass full result to renderer - it handles display truncation
1766
+ // and stores full content for Ctrl+O expansion
1767
+ if (event.result && typeof event.result === 'string' && event.result.trim() && renderer) {
1768
+ renderer.addEvent('tool-result', event.result);
1769
+ }
1770
+ break;
1771
+ }
1772
+ case 'tool.error':
1773
+ if (isHitlToolName(event.toolName)) {
1774
+ hitlDepth = Math.max(0, hitlDepth - 1);
1775
+ }
1776
+ // Clear the "Running X..." status since tool errored
1777
+ this.promptController?.setStatusMessage('Thinking...');
1778
+ if (renderer) {
1779
+ renderer.addEvent('error', event.error);
1780
+ }
1781
+ break;
1782
+ case 'error':
1783
+ if (renderer) {
1784
+ renderer.addEvent('error', event.error);
1785
+ }
1786
+ break;
1787
+ case 'usage':
1788
+ reportUsageToFirebase(event.inputTokens || 0, event.outputTokens || 0).catch(() => { });
1789
+ this.promptController?.setMetaStatus({
1790
+ tokensUsed: event.totalTokens,
1791
+ tokenLimit: 200000, // Approximate limit
1792
+ });
1793
+ // Roll up to session totals for the session-end Firestore write.
1794
+ this.sessionTokensIn += event.inputTokens || 0;
1795
+ this.sessionTokensOut += event.outputTokens || 0;
1796
+ break;
1797
+ case 'provider.fallback': {
1798
+ // Display fallback notification
1799
+ if (renderer) {
1800
+ const fallbackMsg = chalk.yellow('⚠ ') +
1801
+ chalk.dim(`${event.fromProvider}/${event.fromModel} failed: `) +
1802
+ chalk.hex('#EF4444')(event.reason) +
1803
+ chalk.dim(' → switching to ') +
1804
+ chalk.hex('#34D399')(`${event.toProvider}/${event.toModel}`);
1805
+ renderer.addEvent('banner', fallbackMsg);
1806
+ }
1807
+ // Update the model context to reflect the new provider/model
1808
+ this.profileConfig = {
1809
+ ...this.profileConfig,
1810
+ provider: event.toProvider,
1811
+ model: event.toModel,
1812
+ };
1813
+ this.promptController?.setModelContext({
1814
+ model: event.toModel,
1815
+ provider: event.toProvider,
1816
+ });
1817
+ break;
1818
+ }
1819
+ case 'edit.explanation':
1820
+ // Show explanation for edits made
1821
+ if (event.content && renderer) {
1822
+ const filesInfo = event.files?.length ? ` (${event.files.join(', ')})` : '';
1823
+ renderer.addEvent('response', `${event.content}${filesInfo}`);
1824
+ }
1825
+ break;
1826
+ }
1827
+ // Check reasoning timeout on EVERY iteration (not just when reasoning events arrive)
1828
+ // This ensures we bail out even if events are sparse
1829
+ // Use hasReceivedResponseContent (not hasReceivedMeaningfulContent) so timeout
1830
+ // still triggers after tool calls if model just reasons without responding
1831
+ if (reasoningOnlyStartTime && !hasReceivedResponseContent) {
1832
+ const reasoningElapsed = Date.now() - reasoningOnlyStartTime;
1833
+ if (reasoningElapsed > PROMPT_REASONING_TIMEOUT_MS) {
1834
+ if (renderer) {
1835
+ renderer.addEvent('response', chalk.yellow(`\n⏱ Reasoning timeout (${Math.round(reasoningElapsed / 1000)}s)\n`));
1836
+ }
1837
+ reasoningTimedOut = true;
1838
+ }
1839
+ }
1840
+ // Check if reasoning timeout was triggered - break out of event loop
1841
+ if (reasoningTimedOut) {
1842
+ // Cancel the controller too; otherwise the for-await drain
1843
+ // exits but the agent keeps producing events and side-effects
1844
+ // for the next 30+ seconds with no UI to consume them.
1845
+ try {
1846
+ this.controller.cancel('reasoning timeout');
1847
+ }
1848
+ catch { /* best-effort */ }
1849
+ break;
1850
+ }
1851
+ }
1852
+ // After loop: synthesize from reasoning if no response was generated or timed out
1853
+ // This handles models like deepseek-v4-pro that output thinking but empty response
1854
+ // Also handles step timeouts where the model was stuck
1855
+ // IMPORTANT: Don't add "Next steps" when only reasoning occurred - only after real work
1856
+ if ((!episodeSuccess || reasoningTimedOut || stepTimedOut) && reasoningBuffer.trim() && !this.currentResponseBuffer.trim()) {
1857
+ const synthesized = this.synthesizeFromReasoning(reasoningBuffer);
1858
+ if (synthesized && renderer) {
1859
+ renderer.addEvent('stream', '\n' + synthesized);
1860
+ // Only add "Next steps" if tools were actually used (real work done)
1861
+ if (toolsUsed.length > 0) {
1862
+ const { appended } = ensureNextSteps(synthesized);
1863
+ if (appended?.trim()) {
1864
+ renderer.addEvent('stream', appended);
1865
+ }
1866
+ }
1867
+ renderer.addEvent('response', '\n');
1868
+ episodeSuccess = true;
1869
+ }
1870
+ }
1871
+ }
1872
+ catch (error) {
1873
+ const message = error instanceof Error ? error.message : String(error);
1874
+ if (renderer) {
1875
+ renderer.addEvent('error', message);
1876
+ }
1877
+ // Fallback: If we have reasoning content but no response was generated, synthesize one
1878
+ if (!episodeSuccess && reasoningBuffer.trim() && !this.currentResponseBuffer.trim()) {
1879
+ const synthesized = this.synthesizeFromReasoning(reasoningBuffer);
1880
+ if (synthesized && renderer) {
1881
+ renderer.addEvent('stream', '\n' + synthesized);
1882
+ renderer.addEvent('response', '\n');
1883
+ episodeSuccess = true; // Mark as partial success
1884
+ }
1885
+ }
1886
+ }
1887
+ finally {
1888
+ // Exit critical section - allow termination again
1889
+ exitCriticalSection();
1890
+ // Final fallback: If stream ended without message.complete but we have reasoning
1891
+ if (!episodeSuccess && reasoningBuffer.trim() && !this.currentResponseBuffer.trim()) {
1892
+ const synthesized = this.synthesizeFromReasoning(reasoningBuffer);
1893
+ if (synthesized && renderer) {
1894
+ renderer.addEvent('stream', '\n' + synthesized);
1895
+ // Only add "Next steps" if tools were actually used (real work done)
1896
+ if (toolsUsed.length > 0) {
1897
+ const { appended } = ensureNextSteps(synthesized);
1898
+ if (appended?.trim()) {
1899
+ renderer.addEvent('stream', appended);
1900
+ }
1901
+ }
1902
+ renderer.addEvent('response', '\n');
1903
+ episodeSuccess = true;
1904
+ }
1905
+ }
1906
+ // Detect a model safety refusal in the just-finished turn. When the
1907
+ // model declines the request, the request is *done* — auto-continue
1908
+ // would just resubmit "continue" and start a new spinner cycle, which
1909
+ // is what produced the stuck "Thinking… (4m N s)" timer the user saw.
1910
+ const refusedTurn = isSafetyRefusal(this.currentResponseBuffer);
1911
+ this.isProcessing = false;
1912
+ this.promptController?.setStreaming(false);
1913
+ this.promptController?.setStatusMessage(null);
1914
+ // Belt-and-suspenders: explicitly clear the activity message so the
1915
+ // "Thinking… (esc to interrupt · Ns)" line doesn't linger after the
1916
+ // final reply if setMode→stopSpinnerAnimation races with another
1917
+ // renderPrompt tick.
1918
+ this.promptController?.setActivityMessage(null);
1919
+ // Force an idle re-render so the spinner area is repainted without
1920
+ // the streaming activity line. setStreaming(false) → setMode('idle')
1921
+ // already calls renderPrompt(), but a coalesced spinner tick that
1922
+ // races with the transition can leave the last "Thinking… (Ns)"
1923
+ // frame on screen until the next event. forceRender squashes it.
1924
+ this.promptController?.forceRender();
1925
+ this.currentResponseBuffer = '';
1926
+ // Process any queued prompts
1927
+ if (this.pendingPrompts.length > 0 && !this.shouldExit) {
1928
+ const next = this.pendingPrompts.shift();
1929
+ if (next) {
1930
+ await this.processPrompt(next);
1931
+ }
1932
+ }
1933
+ else if (refusedTurn) {
1934
+ // Refusal terminates the turn. Don't re-prompt the model — the
1935
+ // user's request is finished from the agent's side. Clear the
1936
+ // stored "original prompt" so a stray Alt+G later doesn't pick
1937
+ // up where this turn left off.
1938
+ this.originalPromptForAutoContinue = null;
1939
+ }
1940
+ else if (!this.shouldExit && !this.userInterruptedRun) {
1941
+ // Auto mode: keep running until user's prompt is fully completed.
1942
+ // Skipped after a Ctrl+C interrupt so we don't immediately resume
1943
+ // the work the user just cancelled.
1944
+ const autoMode = this.promptController?.getAutoMode() ?? 'off';
1945
+ if (autoMode !== 'off') {
1946
+ // Check if original user prompt is fully completed
1947
+ const detector = getTaskCompletionDetector();
1948
+ const analysis = detector.analyzeCompletion(this.currentResponseBuffer, toolsUsed);
1949
+ // Continue until task is complete
1950
+ if (!analysis.isComplete) {
1951
+ this.promptController?.setStatusMessage('Continuing...');
1952
+ await new Promise(resolve => setTimeout(resolve, 500));
1953
+ // Generate auto-continue prompt using stored original prompt
1954
+ const autoPrompt = this.generateAutoContinuePrompt(this.originalPromptForAutoContinue || '', this.currentResponseBuffer, toolsUsed);
1955
+ if (autoPrompt) {
1956
+ await this.processPrompt(autoPrompt);
1957
+ }
1958
+ else {
1959
+ // Default continue if no specific auto-prompt generated
1960
+ await this.processPrompt('continue');
1961
+ }
1962
+ }
1963
+ else {
1964
+ this.promptController?.setStatusMessage('Task complete');
1965
+ setTimeout(() => this.promptController?.setStatusMessage(null), 2000);
1966
+ }
1967
+ }
1968
+ else if (episodeSuccess && !stepTimedOut && !reasoningTimedOut) {
1969
+ // Manual mode (autoMode === 'off') — show a brief end-of-turn
1970
+ // signal so the user knows the agent is idle again. Without
1971
+ // this the spinner just vanishes silently, which on slow
1972
+ // terminals reads as "still thinking" or "hung". Skipped on
1973
+ // errors / timeouts because those already render their own
1974
+ // explanatory bubble.
1975
+ this.promptController?.setStatusMessage('✓ Done');
1976
+ setTimeout(() => this.promptController?.setStatusMessage(null), 2000);
1977
+ }
1978
+ }
1979
+ }
1980
+ }
1981
+ generateAutoContinuePrompt(originalPrompt, response, toolsUsed) {
1982
+ // Highest-priority signal: a test or build is currently failing
1983
+ // in the visible output. Override every other heuristic and force
1984
+ // a sharp, focused next-action prompt — the agent must drill into
1985
+ // the FIRST failure rather than declaring victory.
1986
+ const failingSignal = detectFailingTestOrBuild(response);
1987
+ if (failingSignal) {
1988
+ const noDocsInstruction = `IMPORTANT: Do NOT create markdown files, documentation, summaries, or reports.`;
1989
+ return `${noDocsInstruction} The output above shows a failing test/build (${failingSignal}). Read the FIRST failure carefully, identify the root cause, edit exactly the file(s) needed, then re-run the same test/build command to confirm. Do not stop until that command exits cleanly.`;
1990
+ }
1991
+ // Only auto-continue for certain types of work
1992
+ const hasFileOperations = toolsUsed.some(t => ['Read', 'Write', 'Edit', 'Search', 'Grep'].includes(t));
1993
+ const hasBashOperations = toolsUsed.includes('Bash');
1994
+ if (!hasFileOperations && !hasBashOperations) {
1995
+ return null; // No meaningful work to continue
1996
+ }
1997
+ // Analyze response to determine what to do next
1998
+ const lowercaseResponse = response.toLowerCase();
1999
+ // Check for common patterns that indicate more work is needed
2000
+ if (lowercaseResponse.includes('next steps') ||
2001
+ lowercaseResponse.includes('further') ||
2002
+ lowercaseResponse.includes('additional') ||
2003
+ lowercaseResponse.includes('implement') ||
2004
+ lowercaseResponse.includes('complete') ||
2005
+ lowercaseResponse.includes('finish')) {
2006
+ // Core instruction to prevent documentation spam
2007
+ const noDocsInstruction = `IMPORTANT: Do NOT create markdown files, documentation, summaries, or reports. Focus only on the actual code/implementation work. Perform the next concrete action in the codebase.`;
2008
+ // Generate a follow-up prompt based on the original task
2009
+ if (originalPrompt.includes('fix') || originalPrompt.includes('bug')) {
2010
+ return `${noDocsInstruction} Continue fixing - edit the next file that needs changes.`;
2011
+ }
2012
+ else if (originalPrompt.includes('implement') || originalPrompt.includes('add')) {
2013
+ return `${noDocsInstruction} Continue implementing - write or edit the next piece of code.`;
2014
+ }
2015
+ else if (originalPrompt.includes('refactor') || originalPrompt.includes('clean')) {
2016
+ return `${noDocsInstruction} Continue refactoring - apply changes to the next file.`;
2017
+ }
2018
+ else if (originalPrompt.includes('test')) {
2019
+ return `${noDocsInstruction} Continue with tests - run or fix the next test.`;
2020
+ }
2021
+ else if (originalPrompt.includes('build') || originalPrompt.includes('deploy') || originalPrompt.includes('publish')) {
2022
+ return `${noDocsInstruction} Continue the build/deploy process - execute the next command.`;
2023
+ }
2024
+ else {
2025
+ return `${noDocsInstruction} Continue with the original task "${originalPrompt.slice(0, 100)}..." - perform the next action.`;
2026
+ }
2027
+ }
2028
+ return null;
2029
+ }
2030
+ handleInterrupt() {
2031
+ if (!this.isProcessing) {
2032
+ return;
2033
+ }
2034
+ const renderer = this.promptController?.getRenderer();
2035
+ if (renderer) {
2036
+ renderer.addEvent('banner', chalk.yellow('Interrupted'));
2037
+ }
2038
+ // Actually cancel the in-flight controller run. Without this the
2039
+ // for-await loop in processPrompt keeps consuming events, the spinner
2040
+ // stays up, and the agent grinds through the rest of its tool loop
2041
+ // while the user sees only a "Interrupted" banner. cancel() is a no-op
2042
+ // when there's no active sink, so this is safe to call unconditionally.
2043
+ try {
2044
+ this.controller.cancel('user interrupt via Ctrl+C');
2045
+ }
2046
+ catch {
2047
+ // Best-effort; if the controller is already torn down the next
2048
+ // Ctrl+C will fall through to authorizedShutdown.
2049
+ }
2050
+ // Suppress the auto-continue re-launch in processPrompt's finally
2051
+ // block. Otherwise the agent immediately starts a fresh "continue"
2052
+ // cycle 500ms later and the user has to keep mashing Ctrl+C to keep
2053
+ // up. Cleared when the user submits a new prompt.
2054
+ this.userInterruptedRun = true;
2055
+ }
2056
+ handleAutoContinueToggle() {
2057
+ const autoMode = this.promptController?.getAutoMode() ?? 'off';
2058
+ this.promptController?.setStatusMessage(`Auto: ${autoMode}`);
2059
+ setTimeout(() => this.promptController?.setStatusMessage(null), 1500);
2060
+ // Reset task completion detector when entering any auto mode
2061
+ if (autoMode !== 'off') {
2062
+ const detector = getTaskCompletionDetector();
2063
+ detector.reset();
2064
+ // Clear any stored original prompt
2065
+ this.originalPromptForAutoContinue = null;
2066
+ }
2067
+ }
2068
+ handleHITLToggle() {
2069
+ const mode = this.promptController?.getModeToggleState().hitlMode ?? 'off';
2070
+ getHITL().updateConfig({ autoPause: mode === 'on' });
2071
+ this.promptController?.setStatusMessage(`HITL: ${mode}`);
2072
+ setTimeout(() => this.promptController?.setStatusMessage(null), 1500);
2073
+ }
2074
+ handleCtrlC(info) {
2075
+ const now = Date.now();
2076
+ // Reset count if more than 2 seconds since last Ctrl+C
2077
+ if (now - this.lastCtrlCTime > 2000) {
2078
+ this.ctrlCCount = 0;
2079
+ }
2080
+ this.lastCtrlCTime = now;
2081
+ this.ctrlCCount++;
2082
+ if (info.hadBuffer) {
2083
+ // Clear buffer, reset count
2084
+ this.ctrlCCount = 0;
2085
+ return;
2086
+ }
2087
+ // Always allow double Ctrl+C to exit, even while processing
2088
+ if (this.ctrlCCount >= 2) {
2089
+ // Use authorized shutdown to bypass anti-termination guard
2090
+ void authorizedShutdown(0);
2091
+ this.shouldExit = true;
2092
+ this.ctrlCCount = 0;
2093
+ return;
2094
+ }
2095
+ if (this.isProcessing) {
2096
+ // Interrupt processing on first Ctrl+C, then allow next Ctrl+C to exit
2097
+ this.handleInterrupt();
2098
+ const renderer = this.promptController?.getRenderer();
2099
+ if (renderer) {
2100
+ renderer.addEvent('banner', chalk.dim('Press Ctrl+C again to exit'));
2101
+ }
2102
+ return;
2103
+ }
2104
+ // First Ctrl+C when idle: show hint
2105
+ const renderer = this.promptController?.getRenderer();
2106
+ if (renderer) {
2107
+ renderer.addEvent('banner', chalk.dim('Press Ctrl+C again to exit'));
2108
+ }
2109
+ }
2110
+ handleExit() {
2111
+ this.shouldExit = true;
2112
+ this.cleanupSudoPasswordHandler();
2113
+ this.promptController?.stop();
2114
+ void authorizedShutdown(0);
2115
+ }
2116
+ waitForExit() {
2117
+ return new Promise((resolve) => {
2118
+ const check = () => {
2119
+ if (this.shouldExit) {
2120
+ resolve();
2121
+ }
2122
+ else {
2123
+ setTimeout(check, 100);
2124
+ }
2125
+ };
2126
+ check();
2127
+ });
2128
+ }
2129
+ }
2130
+ function parseArgs(argv) {
2131
+ const promptTokens = [];
2132
+ for (let index = 0; index < argv.length; index += 1) {
2133
+ const token = argv[index];
2134
+ if (!token) {
2135
+ continue;
2136
+ }
2137
+ // Skip known flags
2138
+ if (token.startsWith('--') || token.startsWith('-')) {
2139
+ continue;
2140
+ }
2141
+ promptTokens.push(token);
2142
+ }
2143
+ return {
2144
+ initialPrompt: promptTokens.length ? promptTokens.join(' ').trim() : null,
2145
+ };
2146
+ }
2147
+ // Default profile is erosolar-code; opt-in offsec / engagement profiles
2148
+ // activate via EROSOLAR_PROFILE env var so the default tool inventory
2149
+ // stays clean for ordinary coding sessions.
2150
+ function resolveProfile() {
2151
+ const env = process.env.EROSOLAR_PROFILE?.trim();
2152
+ if (env && hasAgentProfile(env))
2153
+ return env;
2154
+ return 'erosolar-code';
2155
+ }
2156
+ //# sourceMappingURL=interactiveShell.js.map