@trenchwork/erosolar 1.1.16

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