@trenchwork/coder 1.3.0

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 (560) hide show
  1. package/LICENSE +16 -0
  2. package/README.md +173 -0
  3. package/agents/trenchwork-code.rules.json +199 -0
  4. package/dist/bin/deepseek.d.ts +3 -0
  5. package/dist/bin/deepseek.d.ts.map +1 -0
  6. package/dist/bin/deepseek.js +23 -0
  7. package/dist/bin/deepseek.js.map +1 -0
  8. package/dist/capabilities/baseCapability.d.ts +72 -0
  9. package/dist/capabilities/baseCapability.d.ts.map +1 -0
  10. package/dist/capabilities/baseCapability.js +183 -0
  11. package/dist/capabilities/baseCapability.js.map +1 -0
  12. package/dist/capabilities/bashCapability.d.ts +13 -0
  13. package/dist/capabilities/bashCapability.d.ts.map +1 -0
  14. package/dist/capabilities/bashCapability.js +24 -0
  15. package/dist/capabilities/bashCapability.js.map +1 -0
  16. package/dist/capabilities/editCapability.d.ts +17 -0
  17. package/dist/capabilities/editCapability.d.ts.map +1 -0
  18. package/dist/capabilities/editCapability.js +27 -0
  19. package/dist/capabilities/editCapability.js.map +1 -0
  20. package/dist/capabilities/enhancedGitCapability.d.ts +7 -0
  21. package/dist/capabilities/enhancedGitCapability.d.ts.map +1 -0
  22. package/dist/capabilities/enhancedGitCapability.js +220 -0
  23. package/dist/capabilities/enhancedGitCapability.js.map +1 -0
  24. package/dist/capabilities/filesystemCapability.d.ts +13 -0
  25. package/dist/capabilities/filesystemCapability.d.ts.map +1 -0
  26. package/dist/capabilities/filesystemCapability.js +24 -0
  27. package/dist/capabilities/filesystemCapability.js.map +1 -0
  28. package/dist/capabilities/gitHistoryCapability.d.ts +6 -0
  29. package/dist/capabilities/gitHistoryCapability.d.ts.map +1 -0
  30. package/dist/capabilities/gitHistoryCapability.js +184 -0
  31. package/dist/capabilities/gitHistoryCapability.js.map +1 -0
  32. package/dist/capabilities/hitlCapability.d.ts +18 -0
  33. package/dist/capabilities/hitlCapability.d.ts.map +1 -0
  34. package/dist/capabilities/hitlCapability.js +29 -0
  35. package/dist/capabilities/hitlCapability.js.map +1 -0
  36. package/dist/capabilities/index.d.ts +11 -0
  37. package/dist/capabilities/index.d.ts.map +1 -0
  38. package/dist/capabilities/index.js +16 -0
  39. package/dist/capabilities/index.js.map +1 -0
  40. package/dist/capabilities/memoryCapability.d.ts +10 -0
  41. package/dist/capabilities/memoryCapability.d.ts.map +1 -0
  42. package/dist/capabilities/memoryCapability.js +22 -0
  43. package/dist/capabilities/memoryCapability.js.map +1 -0
  44. package/dist/capabilities/notebookCapability.d.ts +6 -0
  45. package/dist/capabilities/notebookCapability.d.ts.map +1 -0
  46. package/dist/capabilities/notebookCapability.js +17 -0
  47. package/dist/capabilities/notebookCapability.js.map +1 -0
  48. package/dist/capabilities/searchCapability.d.ts +19 -0
  49. package/dist/capabilities/searchCapability.d.ts.map +1 -0
  50. package/dist/capabilities/searchCapability.js +29 -0
  51. package/dist/capabilities/searchCapability.js.map +1 -0
  52. package/dist/capabilities/skillCapability.d.ts +6 -0
  53. package/dist/capabilities/skillCapability.d.ts.map +1 -0
  54. package/dist/capabilities/skillCapability.js +17 -0
  55. package/dist/capabilities/skillCapability.js.map +1 -0
  56. package/dist/capabilities/todoCapability.d.ts +11 -0
  57. package/dist/capabilities/todoCapability.d.ts.map +1 -0
  58. package/dist/capabilities/todoCapability.js +22 -0
  59. package/dist/capabilities/todoCapability.js.map +1 -0
  60. package/dist/capabilities/toolManifest.d.ts +3 -0
  61. package/dist/capabilities/toolManifest.d.ts.map +1 -0
  62. package/dist/capabilities/toolManifest.js +163 -0
  63. package/dist/capabilities/toolManifest.js.map +1 -0
  64. package/dist/capabilities/toolRegistry.d.ts +25 -0
  65. package/dist/capabilities/toolRegistry.d.ts.map +1 -0
  66. package/dist/capabilities/toolRegistry.js +150 -0
  67. package/dist/capabilities/toolRegistry.js.map +1 -0
  68. package/dist/capabilities/unifiedCodingCapability.d.ts +62 -0
  69. package/dist/capabilities/unifiedCodingCapability.d.ts.map +1 -0
  70. package/dist/capabilities/unifiedCodingCapability.js +790 -0
  71. package/dist/capabilities/unifiedCodingCapability.js.map +1 -0
  72. package/dist/capabilities/webCapability.d.ts +23 -0
  73. package/dist/capabilities/webCapability.d.ts.map +1 -0
  74. package/dist/capabilities/webCapability.js +33 -0
  75. package/dist/capabilities/webCapability.js.map +1 -0
  76. package/dist/config.d.ts +25 -0
  77. package/dist/config.d.ts.map +1 -0
  78. package/dist/config.js +181 -0
  79. package/dist/config.js.map +1 -0
  80. package/dist/contracts/agent-profiles.schema.json +25 -0
  81. package/dist/contracts/agent-schemas.json +158 -0
  82. package/dist/contracts/models.schema.json +9 -0
  83. package/dist/contracts/module-schema.json +367 -0
  84. package/dist/contracts/schemas/agent-profile.schema.json +157 -0
  85. package/dist/contracts/schemas/agent-rules.schema.json +238 -0
  86. package/dist/contracts/schemas/agent-schemas.schema.json +528 -0
  87. package/dist/contracts/schemas/agent.schema.json +90 -0
  88. package/dist/contracts/schemas/tool-selection.schema.json +174 -0
  89. package/dist/contracts/tools.schema.json +42 -0
  90. package/dist/contracts/unified-schema.json +40 -0
  91. package/dist/contracts/v1/agent.d.ts +225 -0
  92. package/dist/contracts/v1/agent.d.ts.map +1 -0
  93. package/dist/contracts/v1/agent.js +8 -0
  94. package/dist/contracts/v1/agent.js.map +1 -0
  95. package/dist/contracts/v1/agentProfileManifest.d.ts +60 -0
  96. package/dist/contracts/v1/agentProfileManifest.d.ts.map +1 -0
  97. package/dist/contracts/v1/agentProfileManifest.js +9 -0
  98. package/dist/contracts/v1/agentProfileManifest.js.map +1 -0
  99. package/dist/contracts/v1/agentRules.d.ts +60 -0
  100. package/dist/contracts/v1/agentRules.d.ts.map +1 -0
  101. package/dist/contracts/v1/agentRules.js +10 -0
  102. package/dist/contracts/v1/agentRules.js.map +1 -0
  103. package/dist/contracts/v1/provider.d.ts +149 -0
  104. package/dist/contracts/v1/provider.d.ts.map +1 -0
  105. package/dist/contracts/v1/provider.js +7 -0
  106. package/dist/contracts/v1/provider.js.map +1 -0
  107. package/dist/contracts/v1/tool.d.ts +136 -0
  108. package/dist/contracts/v1/tool.d.ts.map +1 -0
  109. package/dist/contracts/v1/tool.js +7 -0
  110. package/dist/contracts/v1/tool.js.map +1 -0
  111. package/dist/contracts/v1/toolAccess.d.ts +43 -0
  112. package/dist/contracts/v1/toolAccess.d.ts.map +1 -0
  113. package/dist/contracts/v1/toolAccess.js +9 -0
  114. package/dist/contracts/v1/toolAccess.js.map +1 -0
  115. package/dist/core/adversarial.d.ts +38 -0
  116. package/dist/core/adversarial.d.ts.map +1 -0
  117. package/dist/core/adversarial.js +106 -0
  118. package/dist/core/adversarial.js.map +1 -0
  119. package/dist/core/adversarialCorrection.d.ts +22 -0
  120. package/dist/core/adversarialCorrection.d.ts.map +1 -0
  121. package/dist/core/adversarialCorrection.js +25 -0
  122. package/dist/core/adversarialCorrection.js.map +1 -0
  123. package/dist/core/agent.d.ts +331 -0
  124. package/dist/core/agent.d.ts.map +1 -0
  125. package/dist/core/agent.js +1637 -0
  126. package/dist/core/agent.js.map +1 -0
  127. package/dist/core/agentProfileManifest.d.ts +3 -0
  128. package/dist/core/agentProfileManifest.d.ts.map +1 -0
  129. package/dist/core/agentProfileManifest.js +188 -0
  130. package/dist/core/agentProfileManifest.js.map +1 -0
  131. package/dist/core/agentProfiles.d.ts +22 -0
  132. package/dist/core/agentProfiles.d.ts.map +1 -0
  133. package/dist/core/agentProfiles.js +35 -0
  134. package/dist/core/agentProfiles.js.map +1 -0
  135. package/dist/core/agentRegistry.d.ts +111 -0
  136. package/dist/core/agentRegistry.d.ts.map +1 -0
  137. package/dist/core/agentRegistry.js +229 -0
  138. package/dist/core/agentRegistry.js.map +1 -0
  139. package/dist/core/agentRulebook.d.ts +11 -0
  140. package/dist/core/agentRulebook.d.ts.map +1 -0
  141. package/dist/core/agentRulebook.js +136 -0
  142. package/dist/core/agentRulebook.js.map +1 -0
  143. package/dist/core/agentSchemaLoader.d.ts +131 -0
  144. package/dist/core/agentSchemaLoader.d.ts.map +1 -0
  145. package/dist/core/agentSchemaLoader.js +235 -0
  146. package/dist/core/agentSchemaLoader.js.map +1 -0
  147. package/dist/core/aiErrorFixer.d.ts +57 -0
  148. package/dist/core/aiErrorFixer.d.ts.map +1 -0
  149. package/dist/core/aiErrorFixer.js +214 -0
  150. package/dist/core/aiErrorFixer.js.map +1 -0
  151. package/dist/core/bashCommandGuidance.d.ts +16 -0
  152. package/dist/core/bashCommandGuidance.d.ts.map +1 -0
  153. package/dist/core/bashCommandGuidance.js +40 -0
  154. package/dist/core/bashCommandGuidance.js.map +1 -0
  155. package/dist/core/compactionNote.d.ts +13 -0
  156. package/dist/core/compactionNote.d.ts.map +1 -0
  157. package/dist/core/compactionNote.js +13 -0
  158. package/dist/core/compactionNote.js.map +1 -0
  159. package/dist/core/constants.d.ts +31 -0
  160. package/dist/core/constants.d.ts.map +1 -0
  161. package/dist/core/constants.js +62 -0
  162. package/dist/core/constants.js.map +1 -0
  163. package/dist/core/contextManager.d.ts +271 -0
  164. package/dist/core/contextManager.d.ts.map +1 -0
  165. package/dist/core/contextManager.js +1076 -0
  166. package/dist/core/contextManager.js.map +1 -0
  167. package/dist/core/contextUsage.d.ts +28 -0
  168. package/dist/core/contextUsage.d.ts.map +1 -0
  169. package/dist/core/contextUsage.js +62 -0
  170. package/dist/core/contextUsage.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 +127 -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/diffPanel.d.ts +30 -0
  180. package/dist/core/diffPanel.d.ts.map +1 -0
  181. package/dist/core/diffPanel.js +48 -0
  182. package/dist/core/diffPanel.js.map +1 -0
  183. package/dist/core/errorClassification.d.ts +44 -0
  184. package/dist/core/errorClassification.d.ts.map +1 -0
  185. package/dist/core/errorClassification.js +333 -0
  186. package/dist/core/errorClassification.js.map +1 -0
  187. package/dist/core/errors/apiKeyErrors.d.ts +11 -0
  188. package/dist/core/errors/apiKeyErrors.d.ts.map +1 -0
  189. package/dist/core/errors/apiKeyErrors.js +159 -0
  190. package/dist/core/errors/apiKeyErrors.js.map +1 -0
  191. package/dist/core/errors/errorTypes.d.ts +111 -0
  192. package/dist/core/errors/errorTypes.d.ts.map +1 -0
  193. package/dist/core/errors/errorTypes.js +345 -0
  194. package/dist/core/errors/errorTypes.js.map +1 -0
  195. package/dist/core/errors/index.d.ts +50 -0
  196. package/dist/core/errors/index.d.ts.map +1 -0
  197. package/dist/core/errors/index.js +156 -0
  198. package/dist/core/errors/index.js.map +1 -0
  199. package/dist/core/errors/networkErrors.d.ts +14 -0
  200. package/dist/core/errors/networkErrors.d.ts.map +1 -0
  201. package/dist/core/errors/networkErrors.js +53 -0
  202. package/dist/core/errors/networkErrors.js.map +1 -0
  203. package/dist/core/errors/safetyValidator.d.ts +109 -0
  204. package/dist/core/errors/safetyValidator.d.ts.map +1 -0
  205. package/dist/core/errors/safetyValidator.js +272 -0
  206. package/dist/core/errors/safetyValidator.js.map +1 -0
  207. package/dist/core/errors.d.ts +4 -0
  208. package/dist/core/errors.d.ts.map +1 -0
  209. package/dist/core/errors.js +33 -0
  210. package/dist/core/errors.js.map +1 -0
  211. package/dist/core/failureRegistry.d.ts +30 -0
  212. package/dist/core/failureRegistry.d.ts.map +1 -0
  213. package/dist/core/failureRegistry.js +74 -0
  214. package/dist/core/failureRegistry.js.map +1 -0
  215. package/dist/core/fileMentions.d.ts +40 -0
  216. package/dist/core/fileMentions.d.ts.map +1 -0
  217. package/dist/core/fileMentions.js +136 -0
  218. package/dist/core/fileMentions.js.map +1 -0
  219. package/dist/core/finalResponseFormatter.d.ts +10 -0
  220. package/dist/core/finalResponseFormatter.d.ts.map +1 -0
  221. package/dist/core/finalResponseFormatter.js +14 -0
  222. package/dist/core/finalResponseFormatter.js.map +1 -0
  223. package/dist/core/guardrails.d.ts +146 -0
  224. package/dist/core/guardrails.d.ts.map +1 -0
  225. package/dist/core/guardrails.js +361 -0
  226. package/dist/core/guardrails.js.map +1 -0
  227. package/dist/core/hitl.d.ts +119 -0
  228. package/dist/core/hitl.d.ts.map +1 -0
  229. package/dist/core/hitl.js +396 -0
  230. package/dist/core/hitl.js.map +1 -0
  231. package/dist/core/hooks.d.ts +95 -0
  232. package/dist/core/hooks.d.ts.map +1 -0
  233. package/dist/core/hooks.js +236 -0
  234. package/dist/core/hooks.js.map +1 -0
  235. package/dist/core/hostedAuth.d.ts +88 -0
  236. package/dist/core/hostedAuth.d.ts.map +1 -0
  237. package/dist/core/hostedAuth.js +219 -0
  238. package/dist/core/hostedAuth.js.map +1 -0
  239. package/dist/core/inputProtection.d.ts +122 -0
  240. package/dist/core/inputProtection.d.ts.map +1 -0
  241. package/dist/core/inputProtection.js +422 -0
  242. package/dist/core/inputProtection.js.map +1 -0
  243. package/dist/core/modelDiscovery.d.ts +102 -0
  244. package/dist/core/modelDiscovery.d.ts.map +1 -0
  245. package/dist/core/modelDiscovery.js +416 -0
  246. package/dist/core/modelDiscovery.js.map +1 -0
  247. package/dist/core/multilinePasteHandler.d.ts +35 -0
  248. package/dist/core/multilinePasteHandler.d.ts.map +1 -0
  249. package/dist/core/multilinePasteHandler.js +81 -0
  250. package/dist/core/multilinePasteHandler.js.map +1 -0
  251. package/dist/core/permissionMode.d.ts +40 -0
  252. package/dist/core/permissionMode.d.ts.map +1 -0
  253. package/dist/core/permissionMode.js +86 -0
  254. package/dist/core/permissionMode.js.map +1 -0
  255. package/dist/core/postWriteDiagnostics.d.ts +32 -0
  256. package/dist/core/postWriteDiagnostics.d.ts.map +1 -0
  257. package/dist/core/postWriteDiagnostics.js +127 -0
  258. package/dist/core/postWriteDiagnostics.js.map +1 -0
  259. package/dist/core/preferences.d.ts +66 -0
  260. package/dist/core/preferences.d.ts.map +1 -0
  261. package/dist/core/preferences.js +310 -0
  262. package/dist/core/preferences.js.map +1 -0
  263. package/dist/core/quota.d.ts +61 -0
  264. package/dist/core/quota.d.ts.map +1 -0
  265. package/dist/core/quota.js +104 -0
  266. package/dist/core/quota.js.map +1 -0
  267. package/dist/core/quotaErrors.d.ts +42 -0
  268. package/dist/core/quotaErrors.d.ts.map +1 -0
  269. package/dist/core/quotaErrors.js +86 -0
  270. package/dist/core/quotaErrors.js.map +1 -0
  271. package/dist/core/refusalDetection.d.ts +2 -0
  272. package/dist/core/refusalDetection.d.ts.map +1 -0
  273. package/dist/core/refusalDetection.js +51 -0
  274. package/dist/core/refusalDetection.js.map +1 -0
  275. package/dist/core/relativeTime.d.ts +8 -0
  276. package/dist/core/relativeTime.d.ts.map +1 -0
  277. package/dist/core/relativeTime.js +29 -0
  278. package/dist/core/relativeTime.js.map +1 -0
  279. package/dist/core/resultVerification.d.ts +48 -0
  280. package/dist/core/resultVerification.d.ts.map +1 -0
  281. package/dist/core/resultVerification.js +127 -0
  282. package/dist/core/resultVerification.js.map +1 -0
  283. package/dist/core/rewind.d.ts +14 -0
  284. package/dist/core/rewind.d.ts.map +1 -0
  285. package/dist/core/rewind.js +25 -0
  286. package/dist/core/rewind.js.map +1 -0
  287. package/dist/core/schemaValidator.d.ts +49 -0
  288. package/dist/core/schemaValidator.d.ts.map +1 -0
  289. package/dist/core/schemaValidator.js +234 -0
  290. package/dist/core/schemaValidator.js.map +1 -0
  291. package/dist/core/secretStore.d.ts +59 -0
  292. package/dist/core/secretStore.d.ts.map +1 -0
  293. package/dist/core/secretStore.js +278 -0
  294. package/dist/core/secretStore.js.map +1 -0
  295. package/dist/core/sessionStorage.d.ts +10 -0
  296. package/dist/core/sessionStorage.d.ts.map +1 -0
  297. package/dist/core/sessionStorage.js +46 -0
  298. package/dist/core/sessionStorage.js.map +1 -0
  299. package/dist/core/sessionStore.d.ts +35 -0
  300. package/dist/core/sessionStore.d.ts.map +1 -0
  301. package/dist/core/sessionStore.js +190 -0
  302. package/dist/core/sessionStore.js.map +1 -0
  303. package/dist/core/shutdown.d.ts +34 -0
  304. package/dist/core/shutdown.d.ts.map +1 -0
  305. package/dist/core/shutdown.js +186 -0
  306. package/dist/core/shutdown.js.map +1 -0
  307. package/dist/core/slashCommands.d.ts +38 -0
  308. package/dist/core/slashCommands.d.ts.map +1 -0
  309. package/dist/core/slashCommands.js +72 -0
  310. package/dist/core/slashCommands.js.map +1 -0
  311. package/dist/core/subAgentNote.d.ts +15 -0
  312. package/dist/core/subAgentNote.d.ts.map +1 -0
  313. package/dist/core/subAgentNote.js +16 -0
  314. package/dist/core/subAgentNote.js.map +1 -0
  315. package/dist/core/sudoPasswordManager.d.ts +52 -0
  316. package/dist/core/sudoPasswordManager.d.ts.map +1 -0
  317. package/dist/core/sudoPasswordManager.js +115 -0
  318. package/dist/core/sudoPasswordManager.js.map +1 -0
  319. package/dist/core/taskCompletionDetector.d.ts +117 -0
  320. package/dist/core/taskCompletionDetector.d.ts.map +1 -0
  321. package/dist/core/taskCompletionDetector.js +532 -0
  322. package/dist/core/taskCompletionDetector.js.map +1 -0
  323. package/dist/core/testFailureMonitor.d.ts +67 -0
  324. package/dist/core/testFailureMonitor.d.ts.map +1 -0
  325. package/dist/core/testFailureMonitor.js +262 -0
  326. package/dist/core/testFailureMonitor.js.map +1 -0
  327. package/dist/core/thinkingVerbs.d.ts +31 -0
  328. package/dist/core/thinkingVerbs.d.ts.map +1 -0
  329. package/dist/core/thinkingVerbs.js +58 -0
  330. package/dist/core/thinkingVerbs.js.map +1 -0
  331. package/dist/core/toolPreconditions.d.ts +34 -0
  332. package/dist/core/toolPreconditions.d.ts.map +1 -0
  333. package/dist/core/toolPreconditions.js +242 -0
  334. package/dist/core/toolPreconditions.js.map +1 -0
  335. package/dist/core/toolRuntime.d.ts +193 -0
  336. package/dist/core/toolRuntime.d.ts.map +1 -0
  337. package/dist/core/toolRuntime.js +526 -0
  338. package/dist/core/toolRuntime.js.map +1 -0
  339. package/dist/core/turnGovernor.d.ts +63 -0
  340. package/dist/core/turnGovernor.d.ts.map +1 -0
  341. package/dist/core/turnGovernor.js +94 -0
  342. package/dist/core/turnGovernor.js.map +1 -0
  343. package/dist/core/types/utilityTypes.d.ts +183 -0
  344. package/dist/core/types/utilityTypes.d.ts.map +1 -0
  345. package/dist/core/types/utilityTypes.js +273 -0
  346. package/dist/core/types/utilityTypes.js.map +1 -0
  347. package/dist/core/types.d.ts +334 -0
  348. package/dist/core/types.d.ts.map +1 -0
  349. package/dist/core/types.js +76 -0
  350. package/dist/core/types.js.map +1 -0
  351. package/dist/core/updateChecker.d.ts +148 -0
  352. package/dist/core/updateChecker.d.ts.map +1 -0
  353. package/dist/core/updateChecker.js +605 -0
  354. package/dist/core/updateChecker.js.map +1 -0
  355. package/dist/core/usage.d.ts +28 -0
  356. package/dist/core/usage.d.ts.map +1 -0
  357. package/dist/core/usage.js +77 -0
  358. package/dist/core/usage.js.map +1 -0
  359. package/dist/headless/interactiveShell.d.ts +47 -0
  360. package/dist/headless/interactiveShell.d.ts.map +1 -0
  361. package/dist/headless/interactiveShell.js +2495 -0
  362. package/dist/headless/interactiveShell.js.map +1 -0
  363. package/dist/leanAgent.d.ts +73 -0
  364. package/dist/leanAgent.d.ts.map +1 -0
  365. package/dist/leanAgent.js +177 -0
  366. package/dist/leanAgent.js.map +1 -0
  367. package/dist/plugins/providers/deepseek/index.d.ts +12 -0
  368. package/dist/plugins/providers/deepseek/index.d.ts.map +1 -0
  369. package/dist/plugins/providers/deepseek/index.js +123 -0
  370. package/dist/plugins/providers/deepseek/index.js.map +1 -0
  371. package/dist/plugins/providers/index.d.ts +2 -0
  372. package/dist/plugins/providers/index.d.ts.map +1 -0
  373. package/dist/plugins/providers/index.js +10 -0
  374. package/dist/plugins/providers/index.js.map +1 -0
  375. package/dist/providers/baseProvider.d.ts +140 -0
  376. package/dist/providers/baseProvider.d.ts.map +1 -0
  377. package/dist/providers/baseProvider.js +230 -0
  378. package/dist/providers/baseProvider.js.map +1 -0
  379. package/dist/providers/openaiChatCompletionsProvider.d.ts +70 -0
  380. package/dist/providers/openaiChatCompletionsProvider.d.ts.map +1 -0
  381. package/dist/providers/openaiChatCompletionsProvider.js +971 -0
  382. package/dist/providers/openaiChatCompletionsProvider.js.map +1 -0
  383. package/dist/providers/providerFactory.d.ts +22 -0
  384. package/dist/providers/providerFactory.d.ts.map +1 -0
  385. package/dist/providers/providerFactory.js +25 -0
  386. package/dist/providers/providerFactory.js.map +1 -0
  387. package/dist/providers/resilientProvider.d.ts +96 -0
  388. package/dist/providers/resilientProvider.d.ts.map +1 -0
  389. package/dist/providers/resilientProvider.js +251 -0
  390. package/dist/providers/resilientProvider.js.map +1 -0
  391. package/dist/runtime/agentController.d.ts +137 -0
  392. package/dist/runtime/agentController.d.ts.map +1 -0
  393. package/dist/runtime/agentController.js +784 -0
  394. package/dist/runtime/agentController.js.map +1 -0
  395. package/dist/runtime/agentHost.d.ts +61 -0
  396. package/dist/runtime/agentHost.d.ts.map +1 -0
  397. package/dist/runtime/agentHost.js +158 -0
  398. package/dist/runtime/agentHost.js.map +1 -0
  399. package/dist/runtime/agentSession.d.ts +49 -0
  400. package/dist/runtime/agentSession.d.ts.map +1 -0
  401. package/dist/runtime/agentSession.js +218 -0
  402. package/dist/runtime/agentSession.js.map +1 -0
  403. package/dist/runtime/agentSpawningWiring.d.ts +32 -0
  404. package/dist/runtime/agentSpawningWiring.d.ts.map +1 -0
  405. package/dist/runtime/agentSpawningWiring.js +114 -0
  406. package/dist/runtime/agentSpawningWiring.js.map +1 -0
  407. package/dist/runtime/node.d.ts +7 -0
  408. package/dist/runtime/node.d.ts.map +1 -0
  409. package/dist/runtime/node.js +50 -0
  410. package/dist/runtime/node.js.map +1 -0
  411. package/dist/runtime/universal.d.ts +18 -0
  412. package/dist/runtime/universal.d.ts.map +1 -0
  413. package/dist/runtime/universal.js +21 -0
  414. package/dist/runtime/universal.js.map +1 -0
  415. package/dist/shell/liveStatus.d.ts +27 -0
  416. package/dist/shell/liveStatus.d.ts.map +1 -0
  417. package/dist/shell/liveStatus.js +53 -0
  418. package/dist/shell/liveStatus.js.map +1 -0
  419. package/dist/shell/systemPrompt.d.ts +12 -0
  420. package/dist/shell/systemPrompt.d.ts.map +1 -0
  421. package/dist/shell/systemPrompt.js +16 -0
  422. package/dist/shell/systemPrompt.js.map +1 -0
  423. package/dist/shell/toolPresentation.d.ts +54 -0
  424. package/dist/shell/toolPresentation.d.ts.map +1 -0
  425. package/dist/shell/toolPresentation.js +334 -0
  426. package/dist/shell/toolPresentation.js.map +1 -0
  427. package/dist/tools/bashTools.d.ts +11 -0
  428. package/dist/tools/bashTools.d.ts.map +1 -0
  429. package/dist/tools/bashTools.js +785 -0
  430. package/dist/tools/bashTools.js.map +1 -0
  431. package/dist/tools/diffUtils.d.ts +43 -0
  432. package/dist/tools/diffUtils.d.ts.map +1 -0
  433. package/dist/tools/diffUtils.js +607 -0
  434. package/dist/tools/diffUtils.js.map +1 -0
  435. package/dist/tools/editTools.d.ts +29 -0
  436. package/dist/tools/editTools.d.ts.map +1 -0
  437. package/dist/tools/editTools.js +792 -0
  438. package/dist/tools/editTools.js.map +1 -0
  439. package/dist/tools/fileChangeTracker.d.ts +47 -0
  440. package/dist/tools/fileChangeTracker.d.ts.map +1 -0
  441. package/dist/tools/fileChangeTracker.js +154 -0
  442. package/dist/tools/fileChangeTracker.js.map +1 -0
  443. package/dist/tools/fileReadTracker.d.ts +69 -0
  444. package/dist/tools/fileReadTracker.d.ts.map +1 -0
  445. package/dist/tools/fileReadTracker.js +213 -0
  446. package/dist/tools/fileReadTracker.js.map +1 -0
  447. package/dist/tools/fileTools.d.ts +3 -0
  448. package/dist/tools/fileTools.d.ts.map +1 -0
  449. package/dist/tools/fileTools.js +389 -0
  450. package/dist/tools/fileTools.js.map +1 -0
  451. package/dist/tools/grepTools.d.ts +3 -0
  452. package/dist/tools/grepTools.d.ts.map +1 -0
  453. package/dist/tools/grepTools.js +137 -0
  454. package/dist/tools/grepTools.js.map +1 -0
  455. package/dist/tools/hitlTools.d.ts +7 -0
  456. package/dist/tools/hitlTools.d.ts.map +1 -0
  457. package/dist/tools/hitlTools.js +185 -0
  458. package/dist/tools/hitlTools.js.map +1 -0
  459. package/dist/tools/memoryTools.d.ts +27 -0
  460. package/dist/tools/memoryTools.d.ts.map +1 -0
  461. package/dist/tools/memoryTools.js +197 -0
  462. package/dist/tools/memoryTools.js.map +1 -0
  463. package/dist/tools/notebookTools.d.ts +20 -0
  464. package/dist/tools/notebookTools.d.ts.map +1 -0
  465. package/dist/tools/notebookTools.js +140 -0
  466. package/dist/tools/notebookTools.js.map +1 -0
  467. package/dist/tools/searchTools.d.ts +12 -0
  468. package/dist/tools/searchTools.d.ts.map +1 -0
  469. package/dist/tools/searchTools.js +414 -0
  470. package/dist/tools/searchTools.js.map +1 -0
  471. package/dist/tools/skillTools.d.ts +24 -0
  472. package/dist/tools/skillTools.d.ts.map +1 -0
  473. package/dist/tools/skillTools.js +140 -0
  474. package/dist/tools/skillTools.js.map +1 -0
  475. package/dist/tools/todoTools.d.ts +23 -0
  476. package/dist/tools/todoTools.d.ts.map +1 -0
  477. package/dist/tools/todoTools.js +120 -0
  478. package/dist/tools/todoTools.js.map +1 -0
  479. package/dist/tools/webTools.d.ts +26 -0
  480. package/dist/tools/webTools.d.ts.map +1 -0
  481. package/dist/tools/webTools.js +467 -0
  482. package/dist/tools/webTools.js.map +1 -0
  483. package/dist/ui/ink/App.d.ts +53 -0
  484. package/dist/ui/ink/App.d.ts.map +1 -0
  485. package/dist/ui/ink/App.js +13 -0
  486. package/dist/ui/ink/App.js.map +1 -0
  487. package/dist/ui/ink/ChatStatic.d.ts +30 -0
  488. package/dist/ui/ink/ChatStatic.d.ts.map +1 -0
  489. package/dist/ui/ink/ChatStatic.js +83 -0
  490. package/dist/ui/ink/ChatStatic.js.map +1 -0
  491. package/dist/ui/ink/InkPromptController.d.ts +321 -0
  492. package/dist/ui/ink/InkPromptController.d.ts.map +1 -0
  493. package/dist/ui/ink/InkPromptController.js +667 -0
  494. package/dist/ui/ink/InkPromptController.js.map +1 -0
  495. package/dist/ui/ink/Menu.d.ts +21 -0
  496. package/dist/ui/ink/Menu.d.ts.map +1 -0
  497. package/dist/ui/ink/Menu.js +61 -0
  498. package/dist/ui/ink/Menu.js.map +1 -0
  499. package/dist/ui/ink/Prompt.d.ts +47 -0
  500. package/dist/ui/ink/Prompt.d.ts.map +1 -0
  501. package/dist/ui/ink/Prompt.js +571 -0
  502. package/dist/ui/ink/Prompt.js.map +1 -0
  503. package/dist/ui/ink/StatusLine.d.ts +35 -0
  504. package/dist/ui/ink/StatusLine.d.ts.map +1 -0
  505. package/dist/ui/ink/StatusLine.js +66 -0
  506. package/dist/ui/ink/StatusLine.js.map +1 -0
  507. package/dist/ui/ink/pasteBuffer.d.ts +44 -0
  508. package/dist/ui/ink/pasteBuffer.d.ts.map +1 -0
  509. package/dist/ui/ink/pasteBuffer.js +73 -0
  510. package/dist/ui/ink/pasteBuffer.js.map +1 -0
  511. package/dist/ui/theme.d.ts +351 -0
  512. package/dist/ui/theme.d.ts.map +1 -0
  513. package/dist/ui/theme.js +435 -0
  514. package/dist/ui/theme.js.map +1 -0
  515. package/dist/utils/analytics.d.ts +2 -0
  516. package/dist/utils/analytics.d.ts.map +1 -0
  517. package/dist/utils/analytics.js +51 -0
  518. package/dist/utils/analytics.js.map +1 -0
  519. package/dist/utils/asyncUtils.d.ts +95 -0
  520. package/dist/utils/asyncUtils.d.ts.map +1 -0
  521. package/dist/utils/asyncUtils.js +286 -0
  522. package/dist/utils/asyncUtils.js.map +1 -0
  523. package/dist/utils/debugLogger.d.ts +6 -0
  524. package/dist/utils/debugLogger.d.ts.map +1 -0
  525. package/dist/utils/debugLogger.js +39 -0
  526. package/dist/utils/debugLogger.js.map +1 -0
  527. package/dist/utils/errorUtils.d.ts +12 -0
  528. package/dist/utils/errorUtils.d.ts.map +1 -0
  529. package/dist/utils/errorUtils.js +83 -0
  530. package/dist/utils/errorUtils.js.map +1 -0
  531. package/dist/utils/frontmatter.d.ts +10 -0
  532. package/dist/utils/frontmatter.d.ts.map +1 -0
  533. package/dist/utils/frontmatter.js +78 -0
  534. package/dist/utils/frontmatter.js.map +1 -0
  535. package/dist/utils/packageInfo.d.ts +14 -0
  536. package/dist/utils/packageInfo.d.ts.map +1 -0
  537. package/dist/utils/packageInfo.js +45 -0
  538. package/dist/utils/packageInfo.js.map +1 -0
  539. package/dist/utils/planFormatter.d.ts +34 -0
  540. package/dist/utils/planFormatter.d.ts.map +1 -0
  541. package/dist/utils/planFormatter.js +141 -0
  542. package/dist/utils/planFormatter.js.map +1 -0
  543. package/dist/utils/securityUtils.d.ts +132 -0
  544. package/dist/utils/securityUtils.d.ts.map +1 -0
  545. package/dist/utils/securityUtils.js +324 -0
  546. package/dist/utils/securityUtils.js.map +1 -0
  547. package/dist/utils/statusReporter.d.ts +6 -0
  548. package/dist/utils/statusReporter.d.ts.map +1 -0
  549. package/dist/utils/statusReporter.js +26 -0
  550. package/dist/utils/statusReporter.js.map +1 -0
  551. package/dist/workspace.d.ts +8 -0
  552. package/dist/workspace.d.ts.map +1 -0
  553. package/dist/workspace.js +135 -0
  554. package/dist/workspace.js.map +1 -0
  555. package/dist/workspace.validator.d.ts +49 -0
  556. package/dist/workspace.validator.d.ts.map +1 -0
  557. package/dist/workspace.validator.js +215 -0
  558. package/dist/workspace.validator.js.map +1 -0
  559. package/package.json +116 -0
  560. package/scripts/postinstall.cjs +56 -0
@@ -0,0 +1,784 @@
1
+ import { createNodeRuntime } from './node.js';
2
+ import { AGENT_CONTRACT_VERSION } from '../contracts/v1/agent.js';
3
+ import { logDebug } from '../utils/debugLogger.js';
4
+ import { isFallbackEligibleError, getFallbackReason } from '../providers/resilientProvider.js';
5
+ import { getConfiguredProviders, getLatestModelForProvider } from '../core/modelDiscovery.js';
6
+ import { hitlEvents } from '../core/hitl.js';
7
+ class EventStream {
8
+ queue = [];
9
+ pending = null;
10
+ closed = false;
11
+ failure = null;
12
+ push(value) {
13
+ if (this.closed || this.failure) {
14
+ return;
15
+ }
16
+ if (this.pending) {
17
+ this.pending.resolve({ value, done: false });
18
+ this.pending = null;
19
+ return;
20
+ }
21
+ this.queue.push(value);
22
+ }
23
+ close() {
24
+ if (this.closed || this.failure) {
25
+ return;
26
+ }
27
+ this.closed = true;
28
+ if (this.pending) {
29
+ this.pending.resolve({ value: undefined, done: true });
30
+ this.pending = null;
31
+ }
32
+ }
33
+ fail(error) {
34
+ if (this.closed || this.failure) {
35
+ return;
36
+ }
37
+ this.failure = error;
38
+ this.closed = true; // Mark as closed to prevent new pending promises
39
+ if (this.pending) {
40
+ this.pending.reject(error);
41
+ this.pending = null;
42
+ }
43
+ }
44
+ next() {
45
+ if (this.queue.length) {
46
+ const value = this.queue.shift();
47
+ return Promise.resolve({ value, done: false });
48
+ }
49
+ if (this.failure) {
50
+ const error = this.failure;
51
+ this.failure = null;
52
+ return Promise.reject(error);
53
+ }
54
+ if (this.closed) {
55
+ return Promise.resolve({ value: undefined, done: true });
56
+ }
57
+ return new Promise((resolve, reject) => {
58
+ this.pending = { resolve, reject };
59
+ });
60
+ }
61
+ return() {
62
+ this.close();
63
+ return Promise.resolve({ value: undefined, done: true });
64
+ }
65
+ throw(error) {
66
+ const err = error instanceof Error ? error : new Error(String(error));
67
+ this.fail(err);
68
+ return Promise.reject(err);
69
+ }
70
+ [Symbol.asyncIterator]() {
71
+ return this;
72
+ }
73
+ }
74
+ function mergeToolObservers(primary, secondary) {
75
+ if (!secondary) {
76
+ return primary;
77
+ }
78
+ return {
79
+ onToolStart(call) {
80
+ primary.onToolStart?.(call);
81
+ secondary.onToolStart?.(call);
82
+ },
83
+ onToolResult(call, output) {
84
+ primary.onToolResult?.(call, output);
85
+ secondary.onToolResult?.(call, output);
86
+ },
87
+ onToolProgress(call, progress) {
88
+ primary.onToolProgress?.(call, progress);
89
+ secondary.onToolProgress?.(call, progress);
90
+ },
91
+ onToolError(call, error) {
92
+ primary.onToolError?.(call, error);
93
+ secondary.onToolError?.(call, error);
94
+ },
95
+ onCacheHit(call) {
96
+ primary.onCacheHit?.(call);
97
+ secondary.onCacheHit?.(call);
98
+ },
99
+ onToolWarning(call, warning) {
100
+ primary.onToolWarning?.(call, warning);
101
+ secondary.onToolWarning?.(call, warning);
102
+ },
103
+ };
104
+ }
105
+ function createControllerToolObserver(ref) {
106
+ const emit = (event) => {
107
+ ref.current?.push(event);
108
+ };
109
+ const timestamp = () => Date.now();
110
+ return {
111
+ onToolStart(call) {
112
+ emit({
113
+ type: 'tool.start',
114
+ timestamp: timestamp(),
115
+ toolName: call.name,
116
+ toolCallId: call.id,
117
+ parameters: { ...call.arguments },
118
+ });
119
+ },
120
+ onToolResult(call, output) {
121
+ emit({
122
+ type: 'tool.complete',
123
+ timestamp: timestamp(),
124
+ toolName: call.name,
125
+ toolCallId: call.id,
126
+ result: output,
127
+ parameters: { ...call.arguments },
128
+ });
129
+ },
130
+ onToolError(call, error) {
131
+ emit({
132
+ type: 'tool.error',
133
+ timestamp: timestamp(),
134
+ toolName: call.name,
135
+ toolCallId: call.id,
136
+ error,
137
+ });
138
+ },
139
+ };
140
+ }
141
+ export async function createAgentController(options, additionalObserver) {
142
+ const sinkRef = { current: null };
143
+ const observer = createControllerToolObserver(sinkRef);
144
+ const runtime = await createNodeRuntime({
145
+ profile: options.profile,
146
+ workspaceContext: options.workspaceContext,
147
+ workingDir: options.workingDir,
148
+ env: options.env,
149
+ toolObserver: mergeToolObservers(observer, additionalObserver),
150
+ additionalModules: options.modules,
151
+ });
152
+ const controller = new AgentController({ runtime, sinkRef, externalCallbacks: options.callbacks });
153
+ // Register the parallel-sub-agent tool now that the controller
154
+ // exists — the tool handler resolves the provider lazily via the
155
+ // controller's current selection, so it stays in sync with model
156
+ // switches the user makes mid-session.
157
+ try {
158
+ const { wireAgentSpawning } = await import('./agentSpawningWiring.js');
159
+ wireAgentSpawning({
160
+ session: runtime.session,
161
+ workingDir: options.workingDir,
162
+ getSelection: () => controller.getSelection(),
163
+ notifySubAgent: (e) => controller.emitSubAgentEvent(e),
164
+ });
165
+ }
166
+ catch (err) {
167
+ // Non-fatal: spawning is an optional capability. Surface the
168
+ // failure for diagnostics but don't block CLI startup.
169
+ logDebug?.('agent-spawning wiring failed: ' + (err instanceof Error ? err.message : String(err)));
170
+ }
171
+ return controller;
172
+ }
173
+ export class AgentController {
174
+ session;
175
+ sinkRef;
176
+ externalCallbacks;
177
+ activeSink = null;
178
+ agent = null;
179
+ cachedHistory = [];
180
+ selection;
181
+ /** Set of providers that have failed with non-retryable errors in this session */
182
+ failedProviders = new Set();
183
+ /** Maximum fallback attempts per send() call */
184
+ static MAX_FALLBACK_ATTEMPTS = 3;
185
+ activeTimeout = null;
186
+ inflightReject = null;
187
+ constructor(dependencies) {
188
+ this.session = dependencies.runtime.session;
189
+ this.sinkRef = dependencies.sinkRef;
190
+ this.externalCallbacks = dependencies.externalCallbacks;
191
+ this.selection = this.buildInitialSelection();
192
+ }
193
+ buildInitialSelection() {
194
+ const config = this.session.profileConfig;
195
+ return {
196
+ provider: config.provider,
197
+ model: config.model,
198
+ temperature: config.temperature,
199
+ maxTokens: config.maxTokens,
200
+ systemPrompt: config.systemPrompt,
201
+ };
202
+ }
203
+ /**
204
+ * Live read of the current model selection. Used by the
205
+ * agent-spawning wiring so sub-agents inherit whatever model the
206
+ * user has currently chosen, even if they switched mid-session.
207
+ */
208
+ getSelection() {
209
+ return this.selection;
210
+ }
211
+ ensureAgent() {
212
+ if (this.agent) {
213
+ return this.agent;
214
+ }
215
+ const agent = this.session.createAgent(this.selection, this.createAgentCallbacks(), undefined, {
216
+ explainEdits: true,
217
+ });
218
+ if (this.cachedHistory.length) {
219
+ agent.loadHistory(this.cachedHistory);
220
+ }
221
+ this.agent = agent;
222
+ return agent;
223
+ }
224
+ createAgentCallbacks() {
225
+ return {
226
+ onRequestReceived: (requestPreview) => {
227
+ // Signal to UI that request was received - let model handle natural acknowledgment
228
+ // Don't emit verbatim echo - it's redundant and the model's response should acknowledge contextually
229
+ this.externalCallbacks?.onRequestReceived?.(requestPreview);
230
+ },
231
+ onAssistantMessage: (content, metadata) => {
232
+ this.handleAssistantMessage(content, metadata);
233
+ this.externalCallbacks?.onAssistantMessage?.(content, metadata);
234
+ },
235
+ onStreamChunk: (chunk, type) => {
236
+ if (type === 'content') {
237
+ // Content chunks go to message.delta for streaming display
238
+ this.emitDelta(chunk, false);
239
+ }
240
+ else if (type === 'reasoning') {
241
+ // Reasoning chunks go to reasoning event for thought display
242
+ this.emitReasoning(chunk);
243
+ }
244
+ // Pass all chunks to external callbacks
245
+ this.externalCallbacks?.onStreamChunk?.(chunk, type);
246
+ },
247
+ onUsage: (usage) => {
248
+ this.emitUsage(usage);
249
+ this.externalCallbacks?.onUsage?.(usage);
250
+ },
251
+ onContextPruned: (removedCount, stats) => {
252
+ // Surface auto-compaction to the UI as a transcript event.
253
+ this.activeSink?.push({
254
+ type: 'context.compacted',
255
+ timestamp: Date.now(),
256
+ removed: removedCount,
257
+ freedTokens: typeof stats['freedTokens'] === 'number' ? stats['freedTokens'] : 0,
258
+ summarized: stats['summarized'] === true,
259
+ percentage: typeof stats['percentage'] === 'number' ? stats['percentage'] : 0,
260
+ });
261
+ this.externalCallbacks?.onContextPruned?.(removedCount, stats);
262
+ },
263
+ onAdversarialFindings: (findings) => {
264
+ // The reviewer refuted the draft — surface it so the shell can run a
265
+ // bounded auto-correction (re-fix), not just show the caveat.
266
+ this.activeSink?.push({ type: 'adversarial.findings', timestamp: Date.now(), findings });
267
+ this.externalCallbacks?.onAdversarialFindings?.(findings);
268
+ },
269
+ onContextSquishing: (message) => {
270
+ this.externalCallbacks?.onContextSquishing?.(message);
271
+ },
272
+ onContextRecovery: (attempt, maxAttempts, message) => {
273
+ this.externalCallbacks?.onContextRecovery?.(attempt, maxAttempts, message);
274
+ },
275
+ onContinueAfterRecovery: () => {
276
+ this.externalCallbacks?.onContinueAfterRecovery?.();
277
+ },
278
+ onMultilinePaste: (summary, metadata) => {
279
+ this.externalCallbacks?.onMultilinePaste?.(summary, metadata);
280
+ },
281
+ onEditExplanation: (payload) => {
282
+ this.handleEditExplanation(payload);
283
+ this.externalCallbacks?.onEditExplanation?.(payload);
284
+ },
285
+ onRetrying: (attempt, maxAttempts, error) => {
286
+ // Emit delta event to show retry status
287
+ this.emitDelta(`[Retrying ${attempt}/${maxAttempts}: ${error.message}]`, false);
288
+ this.externalCallbacks?.onRetrying?.(attempt, maxAttempts, error);
289
+ },
290
+ // onBeforeFirstToolCall not needed - model's reasoning is now emitted as thought events
291
+ };
292
+ }
293
+ /**
294
+ * Check if content looks like garbage/leaked reasoning fragments.
295
+ * Returns true if the content should be filtered out.
296
+ * NOTE: Keep this minimal to avoid suppressing legitimate short responses.
297
+ */
298
+ isGarbageContent(content) {
299
+ const trimmed = content.trim();
300
+ if (!trimmed)
301
+ return true;
302
+ // Only filter pure punctuation/markdown artifacts
303
+ if (/^[)\]}>*`'".:,!?|│┃─━═\s]+$/.test(trimmed))
304
+ return true;
305
+ // Just newlines or whitespace
306
+ if (/^[\s\n\r]+$/.test(trimmed))
307
+ return true;
308
+ // Removed aggressive short fragment filtering - was suppressing legitimate content
309
+ return false;
310
+ }
311
+ emitDelta(content, isFinal) {
312
+ if (!content?.trim()) {
313
+ return;
314
+ }
315
+ // Filter out garbage/leaked reasoning fragments
316
+ if (this.isGarbageContent(content)) {
317
+ return;
318
+ }
319
+ this.activeSink?.push({
320
+ type: 'message.delta',
321
+ timestamp: Date.now(),
322
+ content,
323
+ isFinal,
324
+ });
325
+ }
326
+ emitError(message) {
327
+ this.activeSink?.push({
328
+ type: 'error',
329
+ timestamp: Date.now(),
330
+ error: message,
331
+ });
332
+ }
333
+ emitReasoning(content) {
334
+ if (!content?.trim()) {
335
+ return;
336
+ }
337
+ // Filter out garbage/leaked formatting fragments in reasoning too
338
+ if (this.isGarbageContent(content)) {
339
+ return;
340
+ }
341
+ this.activeSink?.push({
342
+ type: 'reasoning',
343
+ timestamp: Date.now(),
344
+ content,
345
+ });
346
+ }
347
+ emitUsage(usage) {
348
+ if (!usage) {
349
+ return;
350
+ }
351
+ this.activeSink?.push({
352
+ type: 'usage',
353
+ timestamp: Date.now(),
354
+ inputTokens: usage.inputTokens,
355
+ outputTokens: usage.outputTokens,
356
+ totalTokens: usage.totalTokens,
357
+ });
358
+ }
359
+ /** Surface a parallel sub-agent's lifecycle to the UI (Task notes). */
360
+ emitSubAgentEvent(e) {
361
+ if (e.phase === 'start') {
362
+ this.activeSink?.push({ type: 'subagent.start', timestamp: Date.now(), id: e.id, description: e.description });
363
+ }
364
+ else {
365
+ this.activeSink?.push({
366
+ type: 'subagent.complete',
367
+ timestamp: Date.now(),
368
+ id: e.id,
369
+ description: e.description,
370
+ success: e.success ?? true,
371
+ elapsedMs: e.elapsedMs ?? 0,
372
+ });
373
+ }
374
+ }
375
+ handleEditExplanation(payload) {
376
+ if (!this.activeSink) {
377
+ return;
378
+ }
379
+ if (!payload.explanation?.trim()) {
380
+ return;
381
+ }
382
+ this.activeSink.push({
383
+ type: 'edit.explanation',
384
+ timestamp: Date.now(),
385
+ content: payload.explanation,
386
+ files: payload.files,
387
+ toolName: payload.toolName,
388
+ toolCallId: payload.toolCallId,
389
+ });
390
+ }
391
+ handleAssistantMessage(content, metadata) {
392
+ if (!this.activeSink) {
393
+ return;
394
+ }
395
+ if (!content.trim()) {
396
+ return;
397
+ }
398
+ if (metadata.suppressDisplay) {
399
+ return;
400
+ }
401
+ if (!metadata.isFinal) {
402
+ this.emitDelta(content, false);
403
+ return;
404
+ }
405
+ const elapsedMs = metadata.elapsedMs ?? 0;
406
+ this.activeSink.push({
407
+ type: 'message.complete',
408
+ timestamp: Date.now(),
409
+ content,
410
+ elapsedMs,
411
+ });
412
+ this.emitUsage(metadata.usage ?? null);
413
+ }
414
+ updateCachedHistory() {
415
+ if (this.agent) {
416
+ this.cachedHistory = this.agent.getHistory();
417
+ }
418
+ }
419
+ cancel(reason) {
420
+ if (!this.activeSink) {
421
+ return;
422
+ }
423
+ const error = new Error(reason ?? 'Run cancelled');
424
+ try {
425
+ this.agent?.cancel?.(reason);
426
+ }
427
+ catch {
428
+ // ignore cancellation errors
429
+ }
430
+ this.rejectInflight(error);
431
+ this.activeSink.fail(error);
432
+ this.activeSink = null;
433
+ this.sinkRef.current = null;
434
+ this.clearActiveTimeout();
435
+ }
436
+ clearActiveTimeout() {
437
+ if (this.activeTimeout) {
438
+ clearTimeout(this.activeTimeout);
439
+ this.activeTimeout = null;
440
+ }
441
+ }
442
+ rejectInflight(error) {
443
+ if (this.inflightReject) {
444
+ this.inflightReject(error);
445
+ this.inflightReject = null;
446
+ }
447
+ }
448
+ async *send(message) {
449
+ if (this.activeSink) {
450
+ throw new Error('Agent runtime is already processing a message. Please wait for the current run to finish.');
451
+ }
452
+ // Reset failed providers at the start of each new message
453
+ // (providers might have recovered, quotas might have reset, etc.)
454
+ this.failedProviders.clear();
455
+ let fallbackAttempts = 0;
456
+ // Retry loop for fallback handling
457
+ while (fallbackAttempts < AgentController.MAX_FALLBACK_ATTEMPTS) {
458
+ const agent = this.ensureAgent();
459
+ const sink = new EventStream();
460
+ this.activeSink = sink;
461
+ this.sinkRef.current = sink;
462
+ sink.push({ type: 'message.start', timestamp: Date.now() });
463
+ const timeoutMsRaw = process.env['TRENCHWORK_AGENT_RUN_TIMEOUT_MS'];
464
+ const parsed = timeoutMsRaw ? Number(timeoutMsRaw) : NaN;
465
+ const effectiveTimeoutMs = !Number.isNaN(parsed) && parsed > 0 && parsed < 24 * 60 * 60 * 1000
466
+ ? parsed
467
+ : 24 * 60 * 60 * 1000;
468
+ // The run-timeout must NOT count user think-time at HITL prompts.
469
+ // We track when a HITL prompt is open, freeze the deadline while open,
470
+ // and reschedule from the remaining-budget when it closes. This way a
471
+ // configured run-timeout (e.g. TRENCHWORK_AGENT_RUN_TIMEOUT_MS=120000)
472
+ // still bounds model+tool work, but a slow human never aborts the run.
473
+ let remainingMs = effectiveTimeoutMs;
474
+ let armedAt = null;
475
+ const fireTimeout = () => {
476
+ const err = new Error(`Run timed out after ${effectiveTimeoutMs}ms`);
477
+ this.rejectInflight(err);
478
+ sink.fail(err);
479
+ try {
480
+ this.agent?.cancel?.('timeout');
481
+ }
482
+ catch {
483
+ // ignore
484
+ }
485
+ };
486
+ const arm = () => {
487
+ if (this.activeTimeout || remainingMs <= 0)
488
+ return;
489
+ armedAt = Date.now();
490
+ this.activeTimeout = setTimeout(fireTimeout, remainingMs);
491
+ };
492
+ const disarm = () => {
493
+ if (!this.activeTimeout)
494
+ return;
495
+ clearTimeout(this.activeTimeout);
496
+ this.activeTimeout = null;
497
+ if (armedAt !== null) {
498
+ remainingMs = Math.max(0, remainingMs - (Date.now() - armedAt));
499
+ armedAt = null;
500
+ }
501
+ };
502
+ const onPromptOpen = () => disarm();
503
+ const onPromptClose = () => arm();
504
+ hitlEvents.on('prompt-open', onPromptOpen);
505
+ hitlEvents.on('prompt-close', onPromptClose);
506
+ const detachHitlListeners = () => {
507
+ hitlEvents.removeListener('prompt-open', onPromptOpen);
508
+ hitlEvents.removeListener('prompt-close', onPromptClose);
509
+ };
510
+ arm();
511
+ let caughtError = null;
512
+ let fallbackSucceeded = false;
513
+ let cancelRun = null;
514
+ const cancelPromise = new Promise((_, reject) => {
515
+ cancelRun = reject;
516
+ });
517
+ this.inflightReject = (error) => {
518
+ cancelRun?.(error);
519
+ };
520
+ const run = Promise.race([
521
+ agent.send(message, true),
522
+ cancelPromise,
523
+ ])
524
+ .then(() => {
525
+ this.updateCachedHistory();
526
+ this.clearActiveTimeout();
527
+ sink.close();
528
+ })
529
+ .catch(async (error) => {
530
+ const errorObj = error instanceof Error ? error : new Error(String(error));
531
+ caughtError = errorObj;
532
+ this.clearActiveTimeout();
533
+ const cancelled = /cancel/i.test(errorObj.message);
534
+ const timedOut = /timed out/i.test(errorObj.message);
535
+ if (cancelled || timedOut) {
536
+ this.emitError(errorObj.message);
537
+ sink.fail(errorObj);
538
+ return;
539
+ }
540
+ // Check if this error is eligible for fallback
541
+ if (isFallbackEligibleError(error) && fallbackAttempts < AgentController.MAX_FALLBACK_ATTEMPTS - 1) {
542
+ logDebug(`[AgentController] Fallback-eligible error detected: ${errorObj.message}`);
543
+ fallbackSucceeded = await this.attemptFallback(errorObj);
544
+ if (fallbackSucceeded) {
545
+ // Close this sink without error - we'll retry with new provider
546
+ sink.close();
547
+ return;
548
+ }
549
+ }
550
+ // Not fallback-eligible or no fallback available - emit error and fail
551
+ this.emitError(errorObj.message);
552
+ sink.fail(errorObj);
553
+ })
554
+ .finally(() => {
555
+ this.clearActiveTimeout();
556
+ detachHitlListeners();
557
+ this.inflightReject = null;
558
+ if (this.activeSink === sink) {
559
+ this.activeSink = null;
560
+ this.sinkRef.current = null;
561
+ }
562
+ });
563
+ try {
564
+ for await (const event of sink) {
565
+ yield event;
566
+ }
567
+ }
568
+ finally {
569
+ await run;
570
+ }
571
+ // If we successfully fell back, increment counter and continue loop
572
+ if (fallbackSucceeded && caughtError) {
573
+ fallbackAttempts++;
574
+ logDebug(`[AgentController] Retrying with fallback provider (attempt ${fallbackAttempts}/${AgentController.MAX_FALLBACK_ATTEMPTS})`);
575
+ continue;
576
+ }
577
+ // No fallback happened or it failed - exit loop
578
+ break;
579
+ }
580
+ }
581
+ async switchModel(config) {
582
+ this.updateCachedHistory();
583
+ this.agent = null;
584
+ this.selection = {
585
+ provider: config.provider,
586
+ model: config.model,
587
+ temperature: config.temperature,
588
+ maxTokens: config.maxTokens,
589
+ systemPrompt: this.selection.systemPrompt,
590
+ };
591
+ this.session.updateToolContext(this.selection);
592
+ }
593
+ getCapabilities() {
594
+ const tools = this.session.toolRuntime.listProviderTools();
595
+ const manifestTools = tools.map((tool) => ({
596
+ name: tool.name,
597
+ description: tool.description,
598
+ category: 'general',
599
+ }));
600
+ return {
601
+ contractVersion: AGENT_CONTRACT_VERSION,
602
+ profile: this.session.profile,
603
+ model: this.toModelConfig(this.selection),
604
+ tools: manifestTools,
605
+ features: ['streaming', 'tool-calls'],
606
+ };
607
+ }
608
+ registerToolSuite(suiteId, suite) {
609
+ this.session.toolRuntime.registerSuite({ ...suite, id: suiteId });
610
+ }
611
+ unregisterToolSuite(suiteId) {
612
+ this.session.toolRuntime.unregisterSuite(suiteId);
613
+ }
614
+ getHistory() {
615
+ if (this.agent) {
616
+ return this.agent.getHistory();
617
+ }
618
+ return [...this.cachedHistory];
619
+ }
620
+ clearHistory() {
621
+ this.cachedHistory = [];
622
+ this.agent?.clearHistory();
623
+ }
624
+ /**
625
+ * Restore a prior conversation into context (used by /resume). Sets the
626
+ * cached history and, if an agent is already live, loads it directly;
627
+ * otherwise ensureAgent() picks up cachedHistory on next send(). Runs
628
+ * sanitizeHistory() because a saved session may have been snapshotted
629
+ * mid-tool-execution, leaving orphaned tool calls the provider rejects.
630
+ */
631
+ loadHistory(history) {
632
+ this.cachedHistory = Array.isArray(history) ? history.map((m) => ({ ...m })) : [];
633
+ this.agent?.loadHistory(this.cachedHistory);
634
+ this.sanitizeHistory();
635
+ }
636
+ /**
637
+ * Check if the controller is currently processing a message.
638
+ */
639
+ isProcessing() {
640
+ return this.activeSink !== null;
641
+ }
642
+ /**
643
+ * Force-clear any lingering active state. Use this before starting a new
644
+ * operation (like a complex reasoning task) to ensure clean state.
645
+ * This will close any active sink without waiting for completion.
646
+ */
647
+ forceReset() {
648
+ if (this.activeSink) {
649
+ try {
650
+ this.activeSink.close();
651
+ }
652
+ catch {
653
+ // Ignore errors - sink may already be closed
654
+ }
655
+ this.activeSink = null;
656
+ this.sinkRef.current = null;
657
+ }
658
+ }
659
+ /**
660
+ * Sanitize history by fixing orphaned tool calls (tool_calls without corresponding tool results).
661
+ * This can happen when a run is interrupted mid-tool-execution.
662
+ * We add placeholder error results for any orphaned tool calls to keep history valid.
663
+ */
664
+ sanitizeHistory() {
665
+ const history = this.getHistory();
666
+ if (history.length === 0)
667
+ return;
668
+ const sanitized = [];
669
+ for (let i = 0; i < history.length; i++) {
670
+ const msg = history[i];
671
+ sanitized.push(msg);
672
+ // Check if this is an assistant message with tool_calls
673
+ if (msg.role === 'assistant' && msg.toolCalls?.length) {
674
+ // Look ahead for tool results
675
+ const toolCallIds = new Set(msg.toolCalls.map(tc => tc.id));
676
+ let nextIdx = i + 1;
677
+ // Consume any following tool messages
678
+ while (nextIdx < history.length && history[nextIdx].role === 'tool') {
679
+ const toolMsg = history[nextIdx];
680
+ if (toolMsg.toolCallId) {
681
+ toolCallIds.delete(toolMsg.toolCallId);
682
+ }
683
+ sanitized.push(history[nextIdx]);
684
+ nextIdx++;
685
+ }
686
+ // Add placeholder results for any orphaned tool calls
687
+ for (const orphanedId of toolCallIds) {
688
+ const orphanedCall = msg.toolCalls.find(tc => tc.id === orphanedId);
689
+ const toolName = orphanedCall?.name ?? 'unknown';
690
+ sanitized.push({
691
+ role: 'tool',
692
+ name: toolName,
693
+ toolCallId: orphanedId,
694
+ content: `[Interrupted: ${toolName} execution was cancelled]`,
695
+ });
696
+ }
697
+ // Skip the tool messages we already processed
698
+ i = nextIdx - 1;
699
+ }
700
+ }
701
+ // Update both cached history and agent history
702
+ this.cachedHistory = sanitized;
703
+ if (this.agent) {
704
+ this.agent.loadHistory(sanitized);
705
+ }
706
+ }
707
+ toModelConfig(selection) {
708
+ return {
709
+ provider: selection.provider,
710
+ model: selection.model,
711
+ temperature: selection.temperature,
712
+ maxTokens: selection.maxTokens,
713
+ };
714
+ }
715
+ /**
716
+ * Find the next available provider for fallback.
717
+ * Excludes providers that have already failed in this session.
718
+ */
719
+ findFallbackProvider() {
720
+ const configured = getConfiguredProviders();
721
+ const currentProvider = this.selection.provider;
722
+ // Provider preference order (excluding current and failed)
723
+ // deepseek-v4-pro is default, grok (xai) is backup
724
+ const preferenceOrder = ['deepseek', 'xai'];
725
+ for (const providerId of preferenceOrder) {
726
+ // Skip current provider and already failed providers
727
+ if (providerId === currentProvider || this.failedProviders.has(providerId)) {
728
+ continue;
729
+ }
730
+ // Check if this provider is configured
731
+ const provider = configured.find(p => p.id === providerId);
732
+ if (provider) {
733
+ const model = getLatestModelForProvider(providerId);
734
+ if (model) {
735
+ return { provider: providerId, model };
736
+ }
737
+ }
738
+ }
739
+ return null;
740
+ }
741
+ /**
742
+ * Emit a provider fallback event
743
+ */
744
+ emitFallbackEvent(fromProvider, fromModel, toProvider, toModel, reason, error) {
745
+ this.activeSink?.push({
746
+ type: 'provider.fallback',
747
+ timestamp: Date.now(),
748
+ fromProvider,
749
+ fromModel,
750
+ toProvider,
751
+ toModel,
752
+ reason,
753
+ error,
754
+ });
755
+ }
756
+ /**
757
+ * Attempt to switch to a fallback provider
758
+ */
759
+ async attemptFallback(error) {
760
+ const fallback = this.findFallbackProvider();
761
+ if (!fallback) {
762
+ logDebug('[AgentController] No fallback provider available');
763
+ return false;
764
+ }
765
+ const reason = getFallbackReason(error);
766
+ const fromProvider = this.selection.provider;
767
+ const fromModel = this.selection.model;
768
+ // Mark current provider as failed
769
+ this.failedProviders.add(fromProvider);
770
+ // Emit fallback event
771
+ this.emitFallbackEvent(fromProvider, fromModel, fallback.provider, fallback.model, reason, error.message);
772
+ logDebug(`[AgentController] Falling back from ${fromProvider}/${fromModel} to ${fallback.provider}/${fallback.model}: ${reason}`);
773
+ // Switch to fallback provider
774
+ await this.switchModel({
775
+ provider: fallback.provider,
776
+ model: fallback.model,
777
+ });
778
+ return true;
779
+ }
780
+ getToolSuites() {
781
+ return this.session.toolSuites;
782
+ }
783
+ }
784
+ //# sourceMappingURL=agentController.js.map