@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,1043 @@
1
+ import OpenAI from 'openai';
2
+ import { sanitizeErrorMessage, safeErrorMessage } from '../core/secretStore.js';
3
+ import { logDebug } from '../utils/debugLogger.js';
4
+ import { securityLogger, globalRateLimiter } from '../utils/securityUtils.js';
5
+ /**
6
+ * Security utility for safe JSON parsing with protection against prototype pollution
7
+ */
8
+ export function safeJSONParse(json, options) {
9
+ const maxDepth = options?.maxDepth ?? 20;
10
+ const maxProperties = options?.maxProperties ?? 1000;
11
+ if (!json || typeof json !== 'string') {
12
+ throw new Error('JSON must be a non-empty string');
13
+ }
14
+ // Check for prototype pollution patterns
15
+ if (json.includes('__proto__') || json.includes('constructor') || json.includes('prototype')) {
16
+ logDebug('[SECURITY] Prototype pollution attempt detected in JSON');
17
+ // Clean the JSON by removing dangerous patterns
18
+ json = json.replace(/["']?__proto__["']?\s*:/g, '"__safe_proto__":')
19
+ .replace(/["']?constructor["']?\s*:/g, '"__safe_constructor__":')
20
+ .replace(/["']?prototype["']?\s*:/g, '"__safe_prototype__":');
21
+ }
22
+ // Parse with depth and property limits
23
+ const parsed = JSON.parse(json, (key, value) => {
24
+ // Depth tracking - prevent circular references and deep nesting
25
+ const depth = this?.__depth ?? 0;
26
+ if (depth > maxDepth) {
27
+ throw new Error(`JSON depth ${depth} exceeds maximum allowed depth ${maxDepth}`);
28
+ }
29
+ // Property count tracking
30
+ const propertyCount = this?.__propertyCount ?? 0;
31
+ if (propertyCount > maxProperties) {
32
+ throw new Error(`JSON property count ${propertyCount} exceeds maximum ${maxProperties}`);
33
+ }
34
+ return value;
35
+ });
36
+ return parsed;
37
+ }
38
+ /**
39
+ * Validate and sanitize URL for OpenAI baseURL
40
+ */
41
+ function validateOpenAIBaseURL(url) {
42
+ if (!url || typeof url !== 'string') {
43
+ throw new Error('Base URL must be a non-empty string');
44
+ }
45
+ url = url.trim();
46
+ // Must start with http:// or https://
47
+ if (!url.startsWith('http://') && !url.startsWith('https://')) {
48
+ throw new Error(`Invalid baseURL format: ${url}. Must start with http:// or https://`);
49
+ }
50
+ // Parse URL to validate format
51
+ let parsedUrl;
52
+ try {
53
+ parsedUrl = new URL(url);
54
+ }
55
+ catch (error) {
56
+ throw new Error(`Invalid URL format: ${url}`);
57
+ }
58
+ // Security: Restrict to OpenAI domains and known safe proxies
59
+ const allowedDomains = [
60
+ 'api.openai.com',
61
+ 'api.deepseek.com',
62
+ 'api.anthropic.com',
63
+ 'api.x.ai',
64
+ 'openrouter.ai',
65
+ 'api.groq.com',
66
+ 'dashscope.aliyuncs.com',
67
+ // Add other allowed domains as needed
68
+ ];
69
+ const hostname = parsedUrl.hostname;
70
+ const isAllowed = allowedDomains.some(domain => hostname === domain || hostname.endsWith(`.${domain}`));
71
+ if (!isAllowed) {
72
+ console.warn(`SECURITY: Using non-standard OpenAI baseURL: ${hostname}. This could be a security risk.`);
73
+ // Allow but log warning for custom deployments, Azure, etc.
74
+ }
75
+ // Enforce HTTPS for production-like domains
76
+ if (hostname.includes('openai.com') && parsedUrl.protocol !== 'https:') {
77
+ throw new Error(`OpenAI API requires HTTPS for domain ${hostname}`);
78
+ }
79
+ return url;
80
+ }
81
+ const REQUEST_CHAR_LIMIT = 800_000; // Hard cap to avoid provider 413 errors
82
+ // ============================================================================
83
+ // Stream/Fetch Error Types for Detection
84
+ // ============================================================================
85
+ /**
86
+ * Error types that indicate stream or network failures that should be retried
87
+ */
88
+ const RECOVERABLE_ERROR_PATTERNS = [
89
+ 'premature close',
90
+ 'premature end',
91
+ 'unexpected end',
92
+ 'aborted',
93
+ 'fetcherror',
94
+ 'invalid response body',
95
+ 'gunzip',
96
+ 'decompress',
97
+ 'econnreset',
98
+ 'econnrefused',
99
+ 'epipe',
100
+ 'socket hang up',
101
+ 'network',
102
+ 'timeout',
103
+ ];
104
+ /**
105
+ * Custom error class for provider-specific failures
106
+ */
107
+ export class ProviderStreamError extends Error {
108
+ isRetryable;
109
+ originalError;
110
+ providerId;
111
+ constructor(message, providerId, originalError, isRetryable = true) {
112
+ // SECURITY: Sanitize the error message to prevent token leakage
113
+ super(sanitizeErrorMessage(message));
114
+ this.name = 'ProviderStreamError';
115
+ this.providerId = providerId;
116
+ this.originalError = originalError;
117
+ this.isRetryable = isRetryable;
118
+ // SECURITY: Sanitize stack trace to prevent token leakage
119
+ if (originalError?.stack) {
120
+ this.stack = `${this.stack}\nCaused by: ${sanitizeErrorMessage(originalError.stack)}`;
121
+ }
122
+ }
123
+ }
124
+ /**
125
+ * Basic API key validation for non-OpenAI providers (DeepSeek, xAI, etc.)
126
+ * Only checks that a key exists and has reasonable format - no OpenAI-specific validation
127
+ */
128
+ function validateGenericApiKey(apiKey) {
129
+ if (!apiKey || typeof apiKey !== 'string') {
130
+ throw new Error('API key is required and must be a string');
131
+ }
132
+ const trimmed = apiKey.trim();
133
+ if (trimmed.length < 10) {
134
+ throw new Error('API key is too short');
135
+ }
136
+ // Just log that we're using a custom provider key
137
+ const redactedKey = trimmed.length > 8 ? `${trimmed.substring(0, 4)}...${trimmed.substring(trimmed.length - 4)}` : '[REDACTED]';
138
+ logDebug(`[SECURITY] Using custom provider API key (redacted: ${redactedKey})`);
139
+ return trimmed;
140
+ }
141
+ /**
142
+ * Security audit: OpenAI API key validation and protection
143
+ * Enhanced with comprehensive validation and security controls
144
+ */
145
+ function validateAndProtectApiKey(apiKey) {
146
+ if (!apiKey || typeof apiKey !== 'string') {
147
+ throw new Error('OpenAI API key is required and must be a string');
148
+ }
149
+ // Remove whitespace
150
+ apiKey = apiKey.trim();
151
+ // Comprehensive format validation
152
+ const validation = validateOpenAIKeyFormat(apiKey);
153
+ if (!validation.isValid) {
154
+ throw new Error(`Invalid OpenAI API key: ${validation.reason}`);
155
+ }
156
+ // Security logging (redacted)
157
+ const redactedKey = apiKey.length > 8 ? `${apiKey.substring(0, 8)}...${apiKey.substring(apiKey.length - 4)}` : '[REDACTED]';
158
+ logDebug(`[SECURITY] Using OpenAI API key (type: ${validation.keyType}, redacted: ${redactedKey})`);
159
+ // Check for known revoked/compromised key patterns
160
+ if (isPotentiallyCompromisedKey(apiKey)) {
161
+ console.warn('SECURITY WARNING: API key matches patterns associated with compromised keys. Rotate immediately.');
162
+ }
163
+ return apiKey;
164
+ }
165
+ /**
166
+ * Comprehensive OpenAI key format validation
167
+ */
168
+ function validateOpenAIKeyFormat(apiKey) {
169
+ // Length validation
170
+ if (apiKey.length < 40 || apiKey.length > 200) {
171
+ return { isValid: false, reason: `Invalid key length: ${apiKey.length} chars (expected 40-200)`, keyType: 'unknown' };
172
+ }
173
+ // Character validation (alphanumeric, dashes, underscores only)
174
+ const validChars = /^[a-zA-Z0-9\-_]+$/;
175
+ if (!validChars.test(apiKey)) {
176
+ return { isValid: false, reason: 'Key contains invalid characters', keyType: 'unknown' };
177
+ }
178
+ // OpenAI key format patterns
179
+ if (apiKey.startsWith('sk-proj-')) {
180
+ // Project key format: sk-proj-xxxxxxxxxxxxxxxxxxxxxxxx
181
+ if (apiKey.length !== 51) {
182
+ return { isValid: false, reason: `Project key should be 51 chars, got ${apiKey.length}`, keyType: 'project' };
183
+ }
184
+ return { isValid: true, keyType: 'project' };
185
+ }
186
+ if (apiKey.startsWith('sk-')) {
187
+ // Standard key format: sk-xxxxxxxxxxxxxxxxxxxxxxxx
188
+ if (apiKey.length !== 51) {
189
+ return { isValid: false, reason: `Standard key should be 51 chars, got ${apiKey.length}`, keyType: 'standard' };
190
+ }
191
+ return { isValid: true, keyType: 'standard' };
192
+ }
193
+ if (apiKey.startsWith('org-')) {
194
+ // Organization key format: org-xxxxxxxxxxxxxxxxxxxxxxxx
195
+ if (apiKey.length < 40 || apiKey.length > 100) {
196
+ return { isValid: false, reason: `Organization key length ${apiKey.length} outside expected range`, keyType: 'organization' };
197
+ }
198
+ return { isValid: true, keyType: 'organization' };
199
+ }
200
+ // Unknown format but might be valid (custom deployments, Azure, etc.)
201
+ console.warn(`Unrecognized OpenAI API key format: ${apiKey.substring(0, 12)}...`);
202
+ return { isValid: true, keyType: 'unknown' };
203
+ }
204
+ /**
205
+ * Check for patterns associated with compromised keys
206
+ * This checks for known patterns from public leaks and security advisories
207
+ */
208
+ function isPotentiallyCompromisedKey(apiKey) {
209
+ // Check for patterns from known public leaks
210
+ // These are example patterns - in production, these should come from a threat intelligence feed
211
+ // Example: Keys starting with certain compromised prefixes
212
+ const compromisedPrefixes = [
213
+ 'sk-live-', // Example compromised pattern
214
+ 'sk-test-', // Test keys that shouldn't be in production
215
+ ];
216
+ for (const prefix of compromisedPrefixes) {
217
+ if (apiKey.startsWith(prefix)) {
218
+ return true;
219
+ }
220
+ }
221
+ // Check for sequential or repeating patterns that might indicate generated/test keys
222
+ const sequentialPattern = /(\d{3,})/;
223
+ const match = sequentialPattern.exec(apiKey);
224
+ if (match) {
225
+ const sequence = match[1];
226
+ // Check if digits are sequential (like 123, 456, etc.)
227
+ if (isSequentialDigits(sequence)) {
228
+ return true;
229
+ }
230
+ }
231
+ return false;
232
+ }
233
+ /**
234
+ * Check if a string of digits is sequential (ascending or descending)
235
+ */
236
+ function isSequentialDigits(str) {
237
+ if (str.length < 3)
238
+ return false;
239
+ // Check ascending
240
+ let ascending = true;
241
+ for (let i = 1; i < str.length; i++) {
242
+ if (parseInt(str[i]) !== parseInt(str[i - 1]) + 1) {
243
+ ascending = false;
244
+ break;
245
+ }
246
+ }
247
+ if (ascending)
248
+ return true;
249
+ // Check descending
250
+ let descending = true;
251
+ for (let i = 1; i < str.length; i++) {
252
+ if (parseInt(str[i]) !== parseInt(str[i - 1]) - 1) {
253
+ descending = false;
254
+ break;
255
+ }
256
+ }
257
+ return descending;
258
+ }
259
+ /**
260
+ * Check if an error is recoverable (should be retried)
261
+ */
262
+ function isRecoverableError(error) {
263
+ if (!(error instanceof Error))
264
+ return false;
265
+ const message = error.message.toLowerCase();
266
+ const errorName = error.name?.toLowerCase() ?? '';
267
+ const errorCode = error.code?.toLowerCase() ?? '';
268
+ // Check all sources for recoverable patterns
269
+ const allText = `${message} ${errorName} ${errorCode}`;
270
+ return RECOVERABLE_ERROR_PATTERNS.some(pattern => allText.includes(pattern));
271
+ }
272
+ export class OpenAIChatCompletionsProvider {
273
+ id;
274
+ model;
275
+ client;
276
+ maxRetries;
277
+ temperature;
278
+ maxTokens;
279
+ disableStreaming;
280
+ requestCount = 0;
281
+ lastRequestTime = Date.now();
282
+ constructor(options) {
283
+ // SECURITY: Validate API key - skip OpenAI-specific format checks for custom providers
284
+ const isCustomProvider = !!options.baseURL;
285
+ const validatedApiKey = isCustomProvider
286
+ ? validateGenericApiKey(options.apiKey)
287
+ : validateAndProtectApiKey(options.apiKey);
288
+ // SECURITY: Rate limiting check
289
+ if (!globalRateLimiter.isAllowed('openai-provider')) {
290
+ throw new Error('Rate limit exceeded for OpenAI provider. Please wait before making more requests.');
291
+ }
292
+ // SECURITY: Log security event
293
+ securityLogger.logSecurityEvent({
294
+ type: 'openai_provider_initialized',
295
+ command: 'constructor',
296
+ success: true,
297
+ timestamp: new Date(),
298
+ details: {
299
+ model: options.model,
300
+ providerId: options.providerId,
301
+ hasBaseURL: !!options.baseURL
302
+ }
303
+ });
304
+ const clientConfig = {
305
+ apiKey: validatedApiKey,
306
+ timeout: options.timeout ?? 120000,
307
+ maxRetries: 0, // We handle retries ourselves for better control
308
+ };
309
+ if (options.fetchImpl) {
310
+ // Lets a proxy inject a dynamic Authorization header per request.
311
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
312
+ clientConfig.fetch = options.fetchImpl;
313
+ }
314
+ if (options.baseURL) {
315
+ // SECURITY: Enhanced URL validation with domain restrictions
316
+ try {
317
+ clientConfig.baseURL = validateOpenAIBaseURL(options.baseURL);
318
+ logDebug(`[SECURITY] Using validated baseURL: ${clientConfig.baseURL}`);
319
+ }
320
+ catch (error) {
321
+ securityLogger.logSecurityEvent({
322
+ type: 'invalid_baseurl',
323
+ command: 'constructor',
324
+ success: false,
325
+ timestamp: new Date(),
326
+ details: { error: error instanceof Error ? error.message : String(error) }
327
+ });
328
+ throw new Error(`Invalid baseURL: ${error instanceof Error ? error.message : String(error)}`);
329
+ }
330
+ }
331
+ this.client = new OpenAI(clientConfig);
332
+ this.id = options.providerId ?? 'openai';
333
+ this.model = options.model;
334
+ this.maxRetries = options.maxRetries ?? 3;
335
+ this.temperature = typeof options.temperature === 'number' ? options.temperature : undefined;
336
+ this.maxTokens = Math.max(1, options.maxTokens ?? 4096);
337
+ this.disableStreaming = options.disableStreaming ?? false;
338
+ }
339
+ /**
340
+ * Sleep for a given number of milliseconds
341
+ */
342
+ sleep(ms) {
343
+ return new Promise(resolve => setTimeout(resolve, ms));
344
+ }
345
+ /**
346
+ * Calculate exponential backoff delay
347
+ */
348
+ getBackoffDelay(attempt, baseDelay = 1000, maxDelay = 30000) {
349
+ const delay = Math.min(baseDelay * Math.pow(2, attempt), maxDelay);
350
+ // Add jitter to prevent thundering herd
351
+ return delay + Math.random() * delay * 0.1;
352
+ }
353
+ /**
354
+ * Execute request with retry logic for transient errors
355
+ */
356
+ async executeWithRetry(operation, operationName) {
357
+ let lastError;
358
+ for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
359
+ try {
360
+ return await operation();
361
+ }
362
+ catch (error) {
363
+ lastError = error instanceof Error ? error : new Error(String(error));
364
+ // Check if this is a recoverable error
365
+ if (isRecoverableError(error) && attempt < this.maxRetries) {
366
+ const delay = this.getBackoffDelay(attempt);
367
+ // SECURITY: Sanitize error message to prevent token leakage
368
+ logDebug(`[${this.id}] ${operationName} failed (attempt ${attempt + 1}/${this.maxRetries + 1}): ` +
369
+ `${safeErrorMessage(lastError)}. Retrying in ${Math.round(delay)}ms...`);
370
+ await this.sleep(delay);
371
+ continue;
372
+ }
373
+ // Non-recoverable error or out of retries
374
+ throw new ProviderStreamError(`${operationName} failed after ${attempt + 1} attempts: ${lastError.message}`, this.id, lastError, isRecoverableError(error));
375
+ }
376
+ }
377
+ // Should not reach here, but TypeScript needs this
378
+ throw lastError;
379
+ }
380
+ async generate(messages, tools) {
381
+ const { messages: boundedMessages } = enforceRequestSizeLimit(messages);
382
+ return this.executeWithRetry(async () => {
383
+ const extraBody = deepseekExtraBody(this.model);
384
+ const request = {
385
+ model: this.model,
386
+ messages: mapMessages(boundedMessages, this.model),
387
+ tools: tools.length ? tools.map(mapTool) : undefined,
388
+ // Force tool usage when tools are available - prevents text-only rambling
389
+ tool_choice: tools.length ? 'auto' : undefined,
390
+ // Enable multiple tool calls in a single response
391
+ parallel_tool_calls: tools.length ? true : undefined,
392
+ stream: false,
393
+ // Guardrails: enforce temperature and output cap to prevent runaway responses
394
+ temperature: this.temperature,
395
+ max_tokens: this.maxTokens,
396
+ ...(extraBody ?? {}),
397
+ };
398
+ let completion;
399
+ try {
400
+ const result = await this.client.chat.completions.create(request);
401
+ assertHasChoices(result);
402
+ completion = result;
403
+ }
404
+ catch (error) {
405
+ // Wrap and rethrow with more context
406
+ if (error instanceof Error) {
407
+ // Check for specific API error types
408
+ const apiError = error;
409
+ if (apiError.status === 401) {
410
+ throw new ProviderStreamError(`Authentication failed for ${this.id}. Check your API key.`, this.id, error, false // Not retryable
411
+ );
412
+ }
413
+ if (apiError.status === 403) {
414
+ throw new ProviderStreamError(`Access forbidden for ${this.id}. Check your permissions.`, this.id, error, false // Not retryable
415
+ );
416
+ }
417
+ // Let recoverable errors propagate for retry
418
+ if (isRecoverableError(error)) {
419
+ throw error;
420
+ }
421
+ // Wrap other errors
422
+ throw new ProviderStreamError(`API request failed: ${error.message}`, this.id, error, false);
423
+ }
424
+ throw error;
425
+ }
426
+ const choice = completion.choices[0];
427
+ const usage = mapUsage(completion.usage);
428
+ if (!choice) {
429
+ return {
430
+ type: 'message',
431
+ content: '',
432
+ usage,
433
+ };
434
+ }
435
+ // Safely extract tool calls with error recovery
436
+ let toolCalls = [];
437
+ try {
438
+ toolCalls = (choice.message.tool_calls ?? []).map(mapToolCall);
439
+ }
440
+ catch (parseError) {
441
+ // SECURITY: Sanitize error message to prevent token leakage
442
+ logDebug(`[${this.id}] Failed to parse tool calls, recovering: ` +
443
+ `${safeErrorMessage(parseError)}`);
444
+ // Continue with empty tool calls rather than failing
445
+ }
446
+ const content = extractMessageContent(choice);
447
+ if (toolCalls.length > 0) {
448
+ return {
449
+ type: 'tool_calls',
450
+ toolCalls,
451
+ content,
452
+ usage,
453
+ };
454
+ }
455
+ return {
456
+ type: 'message',
457
+ content,
458
+ usage,
459
+ };
460
+ }, 'generate');
461
+ }
462
+ async *generateStream(messages, tools) {
463
+ // Non-streaming proxy mode: the Erosolar Lambda proxy rejects stream:true,
464
+ // so satisfy the streaming interface by running one non-streaming
465
+ // generate() and emitting its result as chunks.
466
+ if (this.disableStreaming) {
467
+ const result = await this.generate(messages, tools);
468
+ if (result.content)
469
+ yield { type: 'content', content: result.content };
470
+ if (result.type === 'tool_calls') {
471
+ for (const toolCall of result.toolCalls)
472
+ yield { type: 'tool_call', toolCall };
473
+ }
474
+ if (result.usage)
475
+ yield { type: 'usage', usage: result.usage };
476
+ yield result.type === 'message' && result.stopReason
477
+ ? { type: 'done', stopReason: result.stopReason }
478
+ : { type: 'done' };
479
+ return;
480
+ }
481
+ const { messages: boundedMessages } = enforceRequestSizeLimit(messages);
482
+ const extraBody = deepseekExtraBody(this.model);
483
+ const request = {
484
+ model: this.model,
485
+ messages: mapMessages(boundedMessages, this.model),
486
+ tools: tools.length ? tools.map(mapTool) : undefined,
487
+ // Force tool usage when tools are available - prevents text-only rambling
488
+ tool_choice: tools.length ? 'auto' : undefined,
489
+ // Enable multiple tool calls in a single response
490
+ parallel_tool_calls: tools.length ? true : undefined,
491
+ stream: true,
492
+ // Guardrails: enforce temperature and output cap to prevent runaway responses
493
+ temperature: this.temperature,
494
+ max_tokens: this.maxTokens,
495
+ ...(extraBody ?? {}),
496
+ };
497
+ const response = await this.client.chat.completions.create(request);
498
+ // TypeScript needs help knowing this is a stream when stream: true
499
+ if (!Symbol.asyncIterator || !(response[Symbol.asyncIterator])) {
500
+ throw new Error('Expected streaming response but got non-streaming');
501
+ }
502
+ const stream = response;
503
+ // Track tool calls being built (by index)
504
+ const pendingToolCalls = new Map();
505
+ for await (const chunk of stream) {
506
+ const choice = chunk.choices[0];
507
+ if (!choice)
508
+ continue;
509
+ const delta = choice.delta;
510
+ // Stream reasoning_content for models like deepseek-v4-pro so users see progress
511
+ const reasoning = extractTextContent(delta['reasoning_content']);
512
+ if (reasoning) {
513
+ yield { type: 'reasoning', content: reasoning };
514
+ }
515
+ // Handle content chunks (support both string and array formats)
516
+ const content = extractTextContent(delta['content']);
517
+ if (content) {
518
+ yield { type: 'content', content };
519
+ }
520
+ // Handle tool call deltas
521
+ const toolCalls = delta['tool_calls'];
522
+ if (toolCalls) {
523
+ for (const toolCallDelta of toolCalls) {
524
+ const idx = toolCallDelta.index;
525
+ if (!pendingToolCalls.has(idx)) {
526
+ pendingToolCalls.set(idx, {
527
+ id: toolCallDelta.id ?? `call_${idx}`,
528
+ name: toolCallDelta.function?.name ?? '',
529
+ arguments: '',
530
+ });
531
+ }
532
+ const pending = pendingToolCalls.get(idx);
533
+ // Accumulate function name if provided
534
+ if (toolCallDelta.function?.name) {
535
+ pending.name = toolCallDelta.function.name;
536
+ }
537
+ // Accumulate arguments with size limit
538
+ if (toolCallDelta.function?.arguments) {
539
+ // SECURITY: Limit accumulated arguments size to prevent memory DoS
540
+ if (pending.arguments.length + toolCallDelta.function.arguments.length > 100000) {
541
+ throw new Error(`Tool call arguments too large (${pending.arguments.length + toolCallDelta.function.arguments.length} bytes), maximum is 100KB`);
542
+ }
543
+ pending.arguments += toolCallDelta.function.arguments;
544
+ }
545
+ }
546
+ }
547
+ // Check if stream is done
548
+ if (choice.finish_reason) {
549
+ // Emit all accumulated tool calls
550
+ for (const [, toolCall] of pendingToolCalls) {
551
+ let parsed = {};
552
+ try {
553
+ // SECURITY: Use safe JSON parsing with prototype pollution protection
554
+ parsed = safeJSONParse(toolCall.arguments || '{}', {
555
+ maxDepth: 10,
556
+ maxProperties: 100
557
+ });
558
+ }
559
+ catch (parseError) {
560
+ // Try recovery for malformed JSON
561
+ const recovered = tryRecoverMalformedJson(toolCall.arguments);
562
+ if (recovered) {
563
+ parsed = recovered;
564
+ }
565
+ else {
566
+ logDebug(`[SECURITY] Failed to parse tool call arguments: ${safeErrorMessage(parseError)}`);
567
+ }
568
+ }
569
+ yield {
570
+ type: 'tool_call',
571
+ toolCall: {
572
+ id: toolCall.id,
573
+ name: toolCall.name,
574
+ arguments: parsed,
575
+ },
576
+ };
577
+ }
578
+ // Emit usage if available
579
+ if ('usage' in chunk && chunk.usage) {
580
+ const usage = chunk.usage;
581
+ yield {
582
+ type: 'usage',
583
+ usage: {
584
+ inputTokens: usage.prompt_tokens,
585
+ outputTokens: usage.completion_tokens,
586
+ totalTokens: usage.total_tokens,
587
+ },
588
+ };
589
+ }
590
+ yield { type: 'done' };
591
+ }
592
+ }
593
+ }
594
+ cachedModelInfo = null;
595
+ /**
596
+ * Fetch model info from OpenAI API
597
+ * Returns context window and token limits from the real API
598
+ */
599
+ async getModelInfo() {
600
+ if (this.cachedModelInfo) {
601
+ return this.cachedModelInfo;
602
+ }
603
+ try {
604
+ // Use the OpenAI models API to get real model info
605
+ const modelInfo = await this.client.models.retrieve(this.model);
606
+ if (modelInfo) {
607
+ // OpenAI models API returns context_length or similar field
608
+ // The exact field name may vary by model
609
+ const rawInfo = modelInfo;
610
+ const contextWindow = rawInfo['context_length'] ??
611
+ rawInfo['context_window'] ??
612
+ rawInfo['max_context_length'];
613
+ const maxOutputTokens = rawInfo['max_output_tokens'] ??
614
+ rawInfo['output_token_limit'];
615
+ if (contextWindow) {
616
+ this.cachedModelInfo = {
617
+ id: this.model,
618
+ contextWindow,
619
+ maxOutputTokens,
620
+ inputTokenLimit: contextWindow,
621
+ outputTokenLimit: maxOutputTokens,
622
+ };
623
+ return this.cachedModelInfo;
624
+ }
625
+ }
626
+ }
627
+ catch (error) {
628
+ // Models API may not be available for all models
629
+ // Fall through to return null
630
+ const message = error instanceof Error ? error.message : String(error);
631
+ if (!message.includes('404') && !message.includes('not found')) {
632
+ // Log unexpected errors but don't fail
633
+ logDebug(`Failed to fetch model info for ${this.model}:`, message);
634
+ }
635
+ }
636
+ return null;
637
+ }
638
+ }
639
+ function isDeepSeekModel(model) {
640
+ if (!model)
641
+ return false;
642
+ const normalized = model.toLowerCase();
643
+ return normalized.includes('deepseek');
644
+ }
645
+ /**
646
+ * DeepSeek V4 (deepseek-v4-pro / deepseek-v4-flash and legacy aliases that
647
+ * forward to V4) accepts a per-request `thinking` toggle. We always force
648
+ * thinking on — the API has no useful non-thinking mode for an agent loop.
649
+ * Sent via extra_body so the OpenAI SDK passes it through unchanged.
650
+ */
651
+ function deepseekExtraBody(model) {
652
+ if (!isDeepSeekModel(model))
653
+ return undefined;
654
+ return { thinking: { type: 'enabled' } };
655
+ }
656
+ /**
657
+ * Check if a model is a Grok model that may output reasoning content
658
+ * Grok 3+, Grok 4, and variants with "think" or "reasoning" support chain-of-thought
659
+ */
660
+ function isGrokModel(model) {
661
+ if (!model)
662
+ return false;
663
+ const normalized = model.toLowerCase();
664
+ return (normalized.includes('grok') &&
665
+ (normalized.includes('think') ||
666
+ normalized.includes('reason') ||
667
+ normalized.includes('grok-3') ||
668
+ normalized.includes('grok-4')));
669
+ }
670
+ /**
671
+ * Check if a model is a local reasoning model (via Ollama)
672
+ * QwQ, Qwen reasoning, Llama reasoning variants, etc.
673
+ */
674
+ function isLocalReasoningModel(model) {
675
+ if (!model)
676
+ return false;
677
+ const normalized = model.toLowerCase();
678
+ return (
679
+ // QwQ is Alibaba's reasoning model
680
+ normalized.includes('qwq') ||
681
+ // Qwen with reasoning
682
+ (normalized.includes('qwen') && normalized.includes('reason')) ||
683
+ // Llama reasoning variants
684
+ (normalized.includes('llama') && normalized.includes('reason')) ||
685
+ // Mistral reasoning
686
+ (normalized.includes('mistral') && normalized.includes('reason')) ||
687
+ // Generic reasoning model indicators
688
+ normalized.includes('-r1') ||
689
+ normalized.includes('think') ||
690
+ normalized.includes('cot'));
691
+ }
692
+ /**
693
+ * Check if a model supports reasoning/thinking content in responses
694
+ */
695
+ function supportsReasoningContent(model) {
696
+ return isDeepSeekModel(model) || isGrokModel(model) || isLocalReasoningModel(model);
697
+ }
698
+ /**
699
+ * Validate and sanitize message sequence to ensure tool messages have preceding tool_calls.
700
+ * OpenAI/DeepSeek APIs require: "Messages with role 'tool' must be a response to a preceding message with 'tool_calls'"
701
+ */
702
+ function sanitizeMessageSequence(messages) {
703
+ const sanitized = [];
704
+ const pendingToolCallIds = new Set();
705
+ for (const message of messages) {
706
+ if (message.role === 'assistant' && message.toolCalls?.length) {
707
+ // Track tool call IDs that need responses
708
+ for (const tc of message.toolCalls) {
709
+ if (tc.id)
710
+ pendingToolCallIds.add(tc.id);
711
+ }
712
+ sanitized.push(message);
713
+ }
714
+ else if (message.role === 'tool') {
715
+ // Only include tool messages if we have a pending tool call for them
716
+ const toolCallId = message.toolCallId;
717
+ if (toolCallId && pendingToolCallIds.has(toolCallId)) {
718
+ pendingToolCallIds.delete(toolCallId);
719
+ sanitized.push(message);
720
+ }
721
+ else {
722
+ // ORPHANED TOOL MESSAGE - skip it to prevent API error
723
+ // This can happen after context compaction or message pruning
724
+ logDebug(`[mapMessages] Skipping orphaned tool message (no preceding tool_call): ${toolCallId?.slice(0, 20) || 'no-id'}`);
725
+ }
726
+ }
727
+ else {
728
+ // system, user, assistant without tool_calls - pass through
729
+ // Clear pending tool calls when we hit a user message (new turn)
730
+ if (message.role === 'user') {
731
+ pendingToolCallIds.clear();
732
+ }
733
+ sanitized.push(message);
734
+ }
735
+ }
736
+ return sanitized;
737
+ }
738
+ function mapMessages(messages, model) {
739
+ // CRITICAL: Sanitize message sequence to prevent "tool must follow tool_calls" errors
740
+ const sanitizedMessages = sanitizeMessageSequence(messages);
741
+ const params = [];
742
+ const includeReasoningContent = supportsReasoningContent(model);
743
+ for (const message of sanitizedMessages) {
744
+ switch (message.role) {
745
+ case 'system':
746
+ case 'user': {
747
+ params.push({
748
+ role: message.role,
749
+ content: message.content,
750
+ });
751
+ break;
752
+ }
753
+ case 'assistant': {
754
+ const assistantMessage = {
755
+ role: 'assistant',
756
+ content: message.content,
757
+ tool_calls: message.toolCalls?.map((call, index) => ({
758
+ id: call.id || `call_${index}`,
759
+ type: 'function',
760
+ function: {
761
+ name: call.name,
762
+ arguments: JSON.stringify(call.arguments ?? {}),
763
+ },
764
+ })),
765
+ };
766
+ if (includeReasoningContent) {
767
+ assistantMessage.reasoning_content = message.content ?? '';
768
+ }
769
+ params.push(assistantMessage);
770
+ break;
771
+ }
772
+ case 'tool': {
773
+ params.push({
774
+ role: 'tool',
775
+ content: message.content,
776
+ tool_call_id: message.toolCallId,
777
+ });
778
+ break;
779
+ }
780
+ default:
781
+ break;
782
+ }
783
+ }
784
+ return params;
785
+ }
786
+ function mapTool(definition) {
787
+ const parameters = (definition.parameters ?? {
788
+ type: 'object',
789
+ properties: {},
790
+ });
791
+ return {
792
+ type: 'function',
793
+ function: {
794
+ name: definition.name,
795
+ description: definition.description,
796
+ parameters,
797
+ // Enable strict schema validation for more reliable tool calls
798
+ strict: false, // Set to false to allow flexible schemas; true requires additionalProperties: false
799
+ },
800
+ };
801
+ }
802
+ /**
803
+ * Enforce a hard request size limit to prevent provider 413 errors.
804
+ * Drops the oldest non-system messages until the serialized size is under limit.
805
+ */
806
+ function enforceRequestSizeLimit(messages) {
807
+ let truncated = false;
808
+ const trimmed = [...messages];
809
+ let size = estimateMessageChars(trimmed);
810
+ while (size > REQUEST_CHAR_LIMIT && trimmed.length > 1) {
811
+ // Remove the oldest non-system message; if only systems remain, drop the second message
812
+ const removeIdx = trimmed.findIndex(msg => msg.role !== 'system');
813
+ const idx = removeIdx === -1 ? 1 : removeIdx;
814
+ trimmed.splice(idx, 1);
815
+ truncated = true;
816
+ size = estimateMessageChars(trimmed);
817
+ }
818
+ if (truncated) {
819
+ trimmed.unshift({
820
+ role: 'system',
821
+ content: '[Context trimmed to fit request size limit. Earlier turns were dropped to avoid provider rejection.]',
822
+ });
823
+ }
824
+ return { messages: trimmed, truncated };
825
+ }
826
+ function estimateMessageChars(messages) {
827
+ let total = 0;
828
+ for (const msg of messages) {
829
+ if (typeof msg.content === 'string') {
830
+ total += msg.content.length;
831
+ }
832
+ else if (Array.isArray(msg.content)) {
833
+ for (const part of msg.content) {
834
+ if (typeof part === 'string') {
835
+ total += part.length;
836
+ }
837
+ else if (part && typeof part === 'object' && 'text' in part) {
838
+ const text = part.text ?? '';
839
+ total += typeof text === 'string' ? text.length : String(text).length;
840
+ }
841
+ else {
842
+ total += JSON.stringify(part ?? '').length;
843
+ }
844
+ }
845
+ }
846
+ else if (msg.content != null) {
847
+ total += JSON.stringify(msg.content).length;
848
+ }
849
+ const toolCalls = msg.toolCalls;
850
+ if (Array.isArray(toolCalls)) {
851
+ for (const call of toolCalls) {
852
+ total += (call.name?.length ?? 0);
853
+ try {
854
+ total += JSON.stringify(call.arguments ?? {}).length;
855
+ }
856
+ catch {
857
+ total += 100; // Fallback small cost
858
+ }
859
+ }
860
+ }
861
+ }
862
+ return total;
863
+ }
864
+ function extractMessageContent(choice) {
865
+ const message = choice.message;
866
+ const content = extractTextContent(message?.content);
867
+ if (content.trim()) {
868
+ return content.trim();
869
+ }
870
+ const reasoning = extractTextContent(message?.reasoning_content);
871
+ if (reasoning.trim()) {
872
+ return reasoning.trim();
873
+ }
874
+ const refusal = message?.refusal;
875
+ if (typeof refusal === 'string' && refusal.trim()) {
876
+ return refusal.trim();
877
+ }
878
+ return '';
879
+ }
880
+ function isFunctionToolCall(call) {
881
+ return call.type === 'function';
882
+ }
883
+ function isCustomToolCall(call) {
884
+ return call.type === 'custom';
885
+ }
886
+ function mapToolCall(call) {
887
+ let parsed = {};
888
+ let rawArgs;
889
+ let funcName;
890
+ // Handle both standard function calls and custom tool calls
891
+ if (isFunctionToolCall(call)) {
892
+ rawArgs = call.function.arguments ?? '{}';
893
+ funcName = call.function.name ?? call.id ?? 'unknown';
894
+ }
895
+ else if (isCustomToolCall(call)) {
896
+ rawArgs = call.custom.input ?? '{}';
897
+ funcName = call.custom.name ?? call.id ?? 'unknown';
898
+ }
899
+ else {
900
+ // Fallback for any future tool call types
901
+ rawArgs = '{}';
902
+ funcName = call.id ?? 'unknown';
903
+ }
904
+ try {
905
+ // SECURITY: Validate JSON size before parsing to prevent DoS anomalys
906
+ if (rawArgs.length > 100000) {
907
+ throw new Error(`JSON too large (${rawArgs.length} bytes), maximum is 100KB`);
908
+ }
909
+ // SECURITY: Check for potential malicious patterns before parsing
910
+ if (rawArgs.includes('__proto__') || rawArgs.includes('constructor') || rawArgs.includes('prototype')) {
911
+ logDebug(`[security] Suspicious pattern detected in tool call arguments for ${funcName}`);
912
+ }
913
+ // SECURITY: Use safe JSON parsing instead of plain JSON.parse
914
+ parsed = safeJSONParse(rawArgs, {
915
+ maxDepth: 15,
916
+ maxProperties: 500
917
+ });
918
+ }
919
+ catch (error) {
920
+ // Try to recover malformed JSON (common with some models)
921
+ const recovered = tryRecoverMalformedJson(rawArgs);
922
+ if (recovered) {
923
+ parsed = recovered;
924
+ }
925
+ else {
926
+ // SECURITY: Sanitize raw args to prevent token leakage (they could contain API keys in malformed requests)
927
+ const sanitizedArgs = sanitizeErrorMessage(rawArgs.slice(0, 100));
928
+ logDebug(`[tool-call] Failed to parse arguments for ${funcName}: ${sanitizedArgs}...`);
929
+ }
930
+ }
931
+ return {
932
+ id: call.id ?? funcName,
933
+ name: funcName,
934
+ arguments: parsed,
935
+ };
936
+ }
937
+ /**
938
+ * Try to recover malformed JSON from tool call arguments.
939
+ * Some models return truncated or malformed JSON that can be fixed.
940
+ */
941
+ function tryRecoverMalformedJson(raw) {
942
+ if (!raw || !raw.trim()) {
943
+ return null;
944
+ }
945
+ const attempts = [
946
+ // Try adding missing closing braces/quotes
947
+ `${raw}"}`,
948
+ `${raw}}`,
949
+ `${raw}"` + `}`,
950
+ `${raw}"}}`,
951
+ `${raw}}}`,
952
+ ];
953
+ for (const attempt of attempts) {
954
+ try {
955
+ const parsed = JSON.parse(attempt);
956
+ if (typeof parsed === 'object' && parsed !== null) {
957
+ return parsed;
958
+ }
959
+ }
960
+ catch {
961
+ // Continue to next attempt
962
+ }
963
+ }
964
+ // Try regex extraction as last resort
965
+ try {
966
+ const pairs = raw.matchAll(/"([^"]+)":\s*(?:"([^"]*)"?|(\d+(?:\.\d+)?)|(\btrue\b|\bfalse\b|\bnull\b))/g);
967
+ const result = {};
968
+ for (const match of pairs) {
969
+ const [, key, strVal, numVal, boolVal] = match;
970
+ if (key) {
971
+ if (strVal !== undefined) {
972
+ result[key] = strVal;
973
+ }
974
+ else if (numVal) {
975
+ result[key] = numVal.includes('.') ? parseFloat(numVal) : parseInt(numVal, 10);
976
+ }
977
+ else if (boolVal) {
978
+ result[key] = boolVal === 'true' ? true : boolVal === 'false' ? false : null;
979
+ }
980
+ }
981
+ }
982
+ if (Object.keys(result).length > 0) {
983
+ return result;
984
+ }
985
+ }
986
+ catch {
987
+ // Regex extraction failed
988
+ }
989
+ return null;
990
+ }
991
+ /**
992
+ * Normalize OpenAI content parts into plain text.
993
+ * Supports both legacy string content and the newer array-of-parts format.
994
+ */
995
+ function extractTextContent(content) {
996
+ if (!content) {
997
+ return '';
998
+ }
999
+ if (typeof content === 'string') {
1000
+ return content;
1001
+ }
1002
+ if (Array.isArray(content)) {
1003
+ return content
1004
+ .map((part) => {
1005
+ if (typeof part === 'string') {
1006
+ return part;
1007
+ }
1008
+ if (part && typeof part === 'object') {
1009
+ const { text, content: nestedContent } = part;
1010
+ if (typeof text === 'string')
1011
+ return text;
1012
+ if (typeof nestedContent === 'string')
1013
+ return nestedContent;
1014
+ }
1015
+ return '';
1016
+ })
1017
+ .join('');
1018
+ }
1019
+ if (content && typeof content === 'object') {
1020
+ const { text, content: nestedContent } = content;
1021
+ if (typeof text === 'string')
1022
+ return text;
1023
+ if (typeof nestedContent === 'string')
1024
+ return nestedContent;
1025
+ }
1026
+ return '';
1027
+ }
1028
+ function mapUsage(usage) {
1029
+ if (!usage) {
1030
+ return null;
1031
+ }
1032
+ return {
1033
+ inputTokens: usage.prompt_tokens,
1034
+ outputTokens: usage.completion_tokens,
1035
+ totalTokens: usage.total_tokens,
1036
+ };
1037
+ }
1038
+ function assertHasChoices(result) {
1039
+ if (!('choices' in result)) {
1040
+ throw new Error('Streaming responses are not supported in this runtime.');
1041
+ }
1042
+ }
1043
+ //# sourceMappingURL=openaiChatCompletionsProvider.js.map