@trenchwork/erosolar 1.1.30 → 1.1.32

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