@trenchwork/erosolar 1.1.40

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