whale-code 6.5.4 → 6.5.6

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 (853) hide show
  1. package/README.md +39 -31
  2. package/bin/{swagmanager-mcp.js → whale-code.js} +17 -2
  3. package/dist/cli/app.js +148 -72
  4. package/dist/cli/app.js.map +1 -0
  5. package/dist/cli/chat/AgentSelector.js +105 -10
  6. package/dist/cli/chat/AgentSelector.js.map +1 -0
  7. package/dist/cli/chat/ChatApp.d.ts +31 -0
  8. package/dist/cli/chat/ChatApp.js +539 -286
  9. package/dist/cli/chat/ChatApp.js.map +1 -0
  10. package/dist/cli/chat/ChatInput.js +1088 -770
  11. package/dist/cli/chat/ChatInput.js.map +1 -0
  12. package/dist/cli/chat/MarkdownText.js +39 -14
  13. package/dist/cli/chat/MarkdownText.js.map +1 -0
  14. package/dist/cli/chat/MemoryManager.js +181 -46
  15. package/dist/cli/chat/MemoryManager.js.map +1 -0
  16. package/dist/cli/chat/MessageList.d.ts +2 -3
  17. package/dist/cli/chat/MessageList.js +186 -45
  18. package/dist/cli/chat/MessageList.js.map +1 -0
  19. package/dist/cli/chat/ModelSelector.js +282 -63
  20. package/dist/cli/chat/ModelSelector.js.map +1 -0
  21. package/dist/cli/chat/NodeManager.js +165 -75
  22. package/dist/cli/chat/NodeManager.js.map +1 -0
  23. package/dist/cli/chat/NodeSelector.js +171 -30
  24. package/dist/cli/chat/NodeSelector.js.map +1 -0
  25. package/dist/cli/chat/PlanApproval.js +281 -57
  26. package/dist/cli/chat/PlanApproval.js.map +1 -0
  27. package/dist/cli/chat/RewindViewer.js +559 -144
  28. package/dist/cli/chat/RewindViewer.js.map +1 -0
  29. package/dist/cli/chat/SessionManager.js +137 -30
  30. package/dist/cli/chat/SessionManager.js.map +1 -0
  31. package/dist/cli/chat/SlashMenu.js +293 -164
  32. package/dist/cli/chat/SlashMenu.js.map +1 -0
  33. package/dist/cli/chat/StatusBar.js +172 -9
  34. package/dist/cli/chat/StatusBar.js.map +1 -0
  35. package/dist/cli/chat/StoreSelector.js +147 -18
  36. package/dist/cli/chat/StoreSelector.js.map +1 -0
  37. package/dist/cli/chat/StreamingText.d.ts +1 -5
  38. package/dist/cli/chat/StreamingText.js +22 -7
  39. package/dist/cli/chat/StreamingText.js.map +1 -0
  40. package/dist/cli/chat/SubagentPanel.d.ts +1 -2
  41. package/dist/cli/chat/SubagentPanel.js +612 -72
  42. package/dist/cli/chat/SubagentPanel.js.map +1 -0
  43. package/dist/cli/chat/TeamPanel.d.ts +1 -0
  44. package/dist/cli/chat/TeamPanel.js +230 -30
  45. package/dist/cli/chat/TeamPanel.js.map +1 -0
  46. package/dist/cli/chat/ThemeSelector.js +84 -24
  47. package/dist/cli/chat/ThemeSelector.js.map +1 -0
  48. package/dist/cli/chat/ToolIndicator.js +1476 -371
  49. package/dist/cli/chat/ToolIndicator.js.map +1 -0
  50. package/dist/cli/chat/hooks/useAgentLoop.d.ts +1 -0
  51. package/dist/cli/chat/hooks/useAgentLoop.js +481 -367
  52. package/dist/cli/chat/hooks/useAgentLoop.js.map +1 -0
  53. package/dist/cli/chat/hooks/useSlashCommands.d.ts +3 -14
  54. package/dist/cli/chat/hooks/useSlashCommands.js +744 -572
  55. package/dist/cli/chat/hooks/useSlashCommands.js.map +1 -0
  56. package/dist/cli/commands/config-cmd.js +56 -57
  57. package/dist/cli/commands/config-cmd.js.map +1 -0
  58. package/dist/cli/commands/db.js +184 -169
  59. package/dist/cli/commands/db.js.map +1 -0
  60. package/dist/cli/commands/doctor.js +212 -122
  61. package/dist/cli/commands/doctor.js.map +1 -0
  62. package/dist/cli/commands/init.js +211 -244
  63. package/dist/cli/commands/init.js.map +1 -0
  64. package/dist/cli/commands/mcp.js +127 -122
  65. package/dist/cli/commands/mcp.js.map +1 -0
  66. package/dist/cli/login/LoginApp.js +355 -141
  67. package/dist/cli/login/LoginApp.js.map +1 -0
  68. package/dist/cli/print-mode.js +196 -177
  69. package/dist/cli/print-mode.js.map +1 -0
  70. package/dist/cli/serve-mode.js +615 -530
  71. package/dist/cli/serve-mode.js.map +1 -0
  72. package/dist/cli/services/agent-config.d.ts +29 -0
  73. package/dist/cli/services/agent-config.js +91 -0
  74. package/dist/cli/services/agent-config.js.map +1 -0
  75. package/dist/cli/services/agent-definitions.d.ts +4 -1
  76. package/dist/cli/services/agent-definitions.js +97 -56
  77. package/dist/cli/services/agent-definitions.js.map +1 -0
  78. package/dist/cli/services/agent-events.js +225 -162
  79. package/dist/cli/services/agent-events.js.map +1 -0
  80. package/dist/cli/services/agent-loop.js +978 -669
  81. package/dist/cli/services/agent-loop.js.map +1 -0
  82. package/dist/cli/services/agent-worker-base.d.ts +35 -5
  83. package/dist/cli/services/agent-worker-base.js +337 -153
  84. package/dist/cli/services/agent-worker-base.js.map +1 -0
  85. package/dist/cli/services/api-retry.js +69 -64
  86. package/dist/cli/services/api-retry.js.map +1 -0
  87. package/dist/cli/services/auth-service.d.ts +3 -3
  88. package/dist/cli/services/auth-service.js +209 -132
  89. package/dist/cli/services/auth-service.js.map +1 -0
  90. package/dist/cli/services/background-processes.js +343 -267
  91. package/dist/cli/services/background-processes.js.map +1 -0
  92. package/dist/cli/services/browser-auth.d.ts +2 -2
  93. package/dist/cli/services/browser-auth.js +159 -118
  94. package/dist/cli/services/browser-auth.js.map +1 -0
  95. package/dist/cli/services/claude-md-loader.js +40 -36
  96. package/dist/cli/services/claude-md-loader.js.map +1 -0
  97. package/dist/cli/services/config-store.d.ts +9 -4
  98. package/dist/cli/services/config-store.js +164 -117
  99. package/dist/cli/services/config-store.js.map +1 -0
  100. package/dist/cli/services/debug-log.d.ts +1 -1
  101. package/dist/cli/services/debug-log.js +34 -35
  102. package/dist/cli/services/debug-log.js.map +1 -0
  103. package/dist/cli/services/env-detect.d.ts +7 -0
  104. package/dist/cli/services/env-detect.js +9 -0
  105. package/dist/cli/services/env-detect.js.map +1 -0
  106. package/dist/cli/services/error-logger.d.ts +2 -3
  107. package/dist/cli/services/error-logger.js +189 -180
  108. package/dist/cli/services/error-logger.js.map +1 -0
  109. package/dist/cli/services/file-history.d.ts +1 -1
  110. package/dist/cli/services/file-history.js +50 -54
  111. package/dist/cli/services/file-history.js.map +1 -0
  112. package/dist/cli/services/format-server-response.js +332 -372
  113. package/dist/cli/services/format-server-response.js.map +1 -0
  114. package/dist/cli/services/git-context.js +61 -45
  115. package/dist/cli/services/git-context.js.map +1 -0
  116. package/dist/cli/services/hooks.d.ts +2 -2
  117. package/dist/cli/services/hooks.js +195 -180
  118. package/dist/cli/services/hooks.js.map +1 -0
  119. package/dist/cli/services/ink-incremental.d.ts +19 -0
  120. package/dist/cli/services/ink-incremental.js +59 -0
  121. package/dist/cli/services/ink-incremental.js.map +1 -0
  122. package/dist/cli/services/ink-resize-fix.js +54 -44
  123. package/dist/cli/services/ink-resize-fix.js.map +1 -0
  124. package/dist/cli/services/ink-sync-output.d.ts +12 -0
  125. package/dist/cli/services/ink-sync-output.js +16 -0
  126. package/dist/cli/services/ink-sync-output.js.map +1 -0
  127. package/dist/cli/services/interactive-tools.js +268 -212
  128. package/dist/cli/services/interactive-tools.js.map +1 -0
  129. package/dist/cli/services/keybinding-manager.d.ts +11 -1
  130. package/dist/cli/services/keybinding-manager.js +126 -63
  131. package/dist/cli/services/keybinding-manager.js.map +1 -0
  132. package/dist/cli/services/local-tools.d.ts +1 -1
  133. package/dist/cli/services/local-tools.js +939 -656
  134. package/dist/cli/services/local-tools.js.map +1 -0
  135. package/dist/cli/services/lsp-manager.js +757 -594
  136. package/dist/cli/services/lsp-manager.js.map +1 -0
  137. package/dist/cli/services/mcp-client.d.ts +1 -1
  138. package/dist/cli/services/mcp-client.js +173 -134
  139. package/dist/cli/services/mcp-client.js.map +1 -0
  140. package/dist/cli/services/memory-manager.js +53 -40
  141. package/dist/cli/services/memory-manager.js.map +1 -0
  142. package/dist/cli/services/model-manager.js +55 -40
  143. package/dist/cli/services/model-manager.js.map +1 -0
  144. package/dist/cli/services/model-router.js +115 -85
  145. package/dist/cli/services/model-router.js.map +1 -0
  146. package/dist/cli/services/paths.d.ts +30 -0
  147. package/dist/cli/services/paths.js +81 -0
  148. package/dist/cli/services/paths.js.map +1 -0
  149. package/dist/cli/services/permission-modes.js +32 -25
  150. package/dist/cli/services/permission-modes.js.map +1 -0
  151. package/dist/cli/services/rewind.js +182 -168
  152. package/dist/cli/services/rewind.js.map +1 -0
  153. package/dist/cli/services/ripgrep.js +115 -115
  154. package/dist/cli/services/ripgrep.js.map +1 -0
  155. package/dist/cli/services/sandbox.d.ts +1 -1
  156. package/dist/cli/services/sandbox.js +58 -37
  157. package/dist/cli/services/sandbox.js.map +1 -0
  158. package/dist/cli/services/server-tools.js +738 -565
  159. package/dist/cli/services/server-tools.js.map +1 -0
  160. package/dist/cli/services/session-persistence.js +69 -74
  161. package/dist/cli/services/session-persistence.js.map +1 -0
  162. package/dist/cli/services/subagent-worker.js +42 -27
  163. package/dist/cli/services/subagent-worker.js.map +1 -0
  164. package/dist/cli/services/subagent.d.ts +2 -0
  165. package/dist/cli/services/subagent.js +606 -430
  166. package/dist/cli/services/subagent.js.map +1 -0
  167. package/dist/cli/services/system-prompt.js +86 -78
  168. package/dist/cli/services/system-prompt.js.map +1 -0
  169. package/dist/cli/services/task-decomposer.d.ts +1 -1
  170. package/dist/cli/services/task-decomposer.js +172 -139
  171. package/dist/cli/services/task-decomposer.js.map +1 -0
  172. package/dist/cli/services/team-lead.d.ts +2 -2
  173. package/dist/cli/services/team-lead.js +727 -529
  174. package/dist/cli/services/team-lead.js.map +1 -0
  175. package/dist/cli/services/team-state.js +319 -319
  176. package/dist/cli/services/team-state.js.map +1 -0
  177. package/dist/cli/services/teammate.d.ts +8 -2
  178. package/dist/cli/services/teammate.js +862 -560
  179. package/dist/cli/services/teammate.js.map +1 -0
  180. package/dist/cli/services/telemetry.d.ts +6 -1
  181. package/dist/cli/services/telemetry.js +180 -157
  182. package/dist/cli/services/telemetry.js.map +1 -0
  183. package/dist/cli/services/tools/agent-tools.d.ts +3 -3
  184. package/dist/cli/services/tools/agent-tools.js +480 -322
  185. package/dist/cli/services/tools/agent-tools.js.map +1 -0
  186. package/dist/cli/services/tools/file-ops.js +563 -450
  187. package/dist/cli/services/tools/file-ops.js.map +1 -0
  188. package/dist/cli/services/tools/search-tools.js +231 -162
  189. package/dist/cli/services/tools/search-tools.js.map +1 -0
  190. package/dist/cli/services/tools/shell-exec.js +197 -151
  191. package/dist/cli/services/tools/shell-exec.js.map +1 -0
  192. package/dist/cli/services/tools/task-manager.js +206 -173
  193. package/dist/cli/services/tools/task-manager.js.map +1 -0
  194. package/dist/cli/services/tools/web-tools.js +388 -341
  195. package/dist/cli/services/tools/web-tools.js.map +1 -0
  196. package/dist/cli/setup/SetupApp.d.ts +2 -2
  197. package/dist/cli/setup/SetupApp.js +608 -160
  198. package/dist/cli/setup/SetupApp.js.map +1 -0
  199. package/dist/cli/shared/ErrorBoundary.d.ts +22 -0
  200. package/dist/cli/shared/ErrorBoundary.js +73 -0
  201. package/dist/cli/shared/ErrorBoundary.js.map +1 -0
  202. package/dist/cli/shared/MatrixIntro.js +66 -69
  203. package/dist/cli/shared/MatrixIntro.js.map +1 -0
  204. package/dist/cli/shared/SpinnerSlot.d.ts +14 -0
  205. package/dist/cli/shared/SpinnerSlot.js +63 -0
  206. package/dist/cli/shared/SpinnerSlot.js.map +1 -0
  207. package/dist/cli/shared/Theme.d.ts +1 -1
  208. package/dist/cli/shared/Theme.js +136 -92
  209. package/dist/cli/shared/Theme.js.map +1 -0
  210. package/dist/cli/shared/WhaleBanner.js +99 -11
  211. package/dist/cli/shared/WhaleBanner.js.map +1 -0
  212. package/dist/cli/shared/markdown.d.ts +3 -1
  213. package/dist/cli/shared/markdown.js +736 -674
  214. package/dist/cli/shared/markdown.js.map +1 -0
  215. package/dist/cli/shared/marked-terminal.d.js +2 -0
  216. package/dist/cli/shared/marked-terminal.d.js.map +1 -0
  217. package/dist/cli/shared/theme-manager.js +99 -90
  218. package/dist/cli/shared/theme-manager.js.map +1 -0
  219. package/dist/cli/shared/theme-presets.js +256 -254
  220. package/dist/cli/shared/theme-presets.js.map +1 -0
  221. package/dist/cli/status/StatusApp.js +235 -86
  222. package/dist/cli/status/StatusApp.js.map +1 -0
  223. package/dist/cli/stores/StoreApp.js +275 -65
  224. package/dist/cli/stores/StoreApp.js.map +1 -0
  225. package/dist/index.d.ts +2 -2
  226. package/dist/index.js +509 -396
  227. package/dist/index.js.map +1 -0
  228. package/dist/local-agent/connection.d.ts +2 -2
  229. package/dist/local-agent/connection.js +352 -293
  230. package/dist/local-agent/connection.js.map +1 -0
  231. package/dist/local-agent/discovery.js +259 -122
  232. package/dist/local-agent/discovery.js.map +1 -0
  233. package/dist/local-agent/executor.js +216 -193
  234. package/dist/local-agent/executor.js.map +1 -0
  235. package/dist/local-agent/index.d.ts +2 -2
  236. package/dist/local-agent/index.js +156 -156
  237. package/dist/local-agent/index.js.map +1 -0
  238. package/dist/node/adapters/base.js +18 -8
  239. package/dist/node/adapters/base.js.map +1 -0
  240. package/dist/node/adapters/discord.js +286 -275
  241. package/dist/node/adapters/discord.js.map +1 -0
  242. package/dist/node/adapters/email.js +189 -202
  243. package/dist/node/adapters/email.js.map +1 -0
  244. package/dist/node/adapters/imessage.js +145 -142
  245. package/dist/node/adapters/imessage.js.map +1 -0
  246. package/dist/node/adapters/slack.js +237 -236
  247. package/dist/node/adapters/slack.js.map +1 -0
  248. package/dist/node/adapters/sms.js +149 -151
  249. package/dist/node/adapters/sms.js.map +1 -0
  250. package/dist/node/adapters/telegram.js +88 -92
  251. package/dist/node/adapters/telegram.js.map +1 -0
  252. package/dist/node/adapters/webchat.js +160 -136
  253. package/dist/node/adapters/webchat.js.map +1 -0
  254. package/dist/node/adapters/whatsapp.js +212 -215
  255. package/dist/node/adapters/whatsapp.js.map +1 -0
  256. package/dist/node/cli.js +884 -653
  257. package/dist/node/cli.js.map +1 -0
  258. package/dist/node/config.js +20 -18
  259. package/dist/node/config.js.map +1 -0
  260. package/dist/node/gateway-client.js +191 -181
  261. package/dist/node/gateway-client.js.map +1 -0
  262. package/dist/node/portal/clipboard.js +161 -130
  263. package/dist/node/portal/clipboard.js.map +1 -0
  264. package/dist/node/portal/discovery.js +51 -45
  265. package/dist/node/portal/discovery.js.map +1 -0
  266. package/dist/node/portal/forward.js +64 -58
  267. package/dist/node/portal/forward.js.map +1 -0
  268. package/dist/node/portal/index.js +246 -221
  269. package/dist/node/portal/index.js.map +1 -0
  270. package/dist/node/portal/multiplexer.js +192 -182
  271. package/dist/node/portal/multiplexer.js.map +1 -0
  272. package/dist/node/portal/permissions.js +102 -70
  273. package/dist/node/portal/permissions.js.map +1 -0
  274. package/dist/node/portal/protocol.js +153 -116
  275. package/dist/node/portal/protocol.js.map +1 -0
  276. package/dist/node/portal/screen.js +80 -69
  277. package/dist/node/portal/screen.js.map +1 -0
  278. package/dist/node/portal/session.js +124 -117
  279. package/dist/node/portal/session.js.map +1 -0
  280. package/dist/node/portal/shell.js +140 -113
  281. package/dist/node/portal/shell.js.map +1 -0
  282. package/dist/node/portal/stream.js +77 -75
  283. package/dist/node/portal/stream.js.map +1 -0
  284. package/dist/node/portal/transfer.js +190 -167
  285. package/dist/node/portal/transfer.js.map +1 -0
  286. package/dist/node/portal/ui.js +124 -99
  287. package/dist/node/portal/ui.js.map +1 -0
  288. package/dist/node/remote-desktop/compile-helper.js +50 -45
  289. package/dist/node/remote-desktop/compile-helper.js.map +1 -0
  290. package/dist/node/remote-desktop/index.js +215 -187
  291. package/dist/node/remote-desktop/index.js.map +1 -0
  292. package/dist/node/remote-desktop/protocol.js +45 -29
  293. package/dist/node/remote-desktop/protocol.js.map +1 -0
  294. package/dist/node/runtime.js +493 -410
  295. package/dist/node/runtime.js.map +1 -0
  296. package/dist/server/handlers/__test-utils__/test-db.js +39 -89
  297. package/dist/server/handlers/__test-utils__/test-db.js.map +1 -0
  298. package/dist/server/handlers/analytics.js +467 -261
  299. package/dist/server/handlers/analytics.js.map +1 -0
  300. package/dist/server/handlers/api-docs.d.ts +6 -0
  301. package/dist/server/handlers/api-docs.js +1613 -0
  302. package/dist/server/handlers/api-docs.js.map +1 -0
  303. package/dist/server/handlers/api-keys.js +295 -232
  304. package/dist/server/handlers/api-keys.js.map +1 -0
  305. package/dist/server/handlers/billing.js +330 -239
  306. package/dist/server/handlers/billing.js.map +1 -0
  307. package/dist/server/handlers/browser.js +468 -395
  308. package/dist/server/handlers/browser.js.map +1 -0
  309. package/dist/server/handlers/catalog.js +1377 -978
  310. package/dist/server/handlers/catalog.js.map +1 -0
  311. package/dist/server/handlers/clickhouse.js +157 -109
  312. package/dist/server/handlers/clickhouse.js.map +1 -0
  313. package/dist/server/handlers/comms.d.ts +0 -53
  314. package/dist/server/handlers/comms.js +1443 -970
  315. package/dist/server/handlers/comms.js.map +1 -0
  316. package/dist/server/handlers/creations.js +461 -394
  317. package/dist/server/handlers/creations.js.map +1 -0
  318. package/dist/server/handlers/crm.js +1082 -791
  319. package/dist/server/handlers/crm.js.map +1 -0
  320. package/dist/server/handlers/discovery.js +251 -232
  321. package/dist/server/handlers/discovery.js.map +1 -0
  322. package/dist/server/handlers/embeddings.js +241 -164
  323. package/dist/server/handlers/embeddings.js.map +1 -0
  324. package/dist/server/handlers/enrichment.js +887 -718
  325. package/dist/server/handlers/enrichment.js.map +1 -0
  326. package/dist/server/handlers/image-gen.js +467 -376
  327. package/dist/server/handlers/image-gen.js.map +1 -0
  328. package/dist/server/handlers/inventory.js +797 -424
  329. package/dist/server/handlers/inventory.js.map +1 -0
  330. package/dist/server/handlers/kali.js +272 -230
  331. package/dist/server/handlers/kali.js.map +1 -0
  332. package/dist/server/handlers/llm-providers.js +803 -580
  333. package/dist/server/handlers/llm-providers.js.map +1 -0
  334. package/dist/server/handlers/local-agent.js +133 -105
  335. package/dist/server/handlers/local-agent.js.map +1 -0
  336. package/dist/server/handlers/media.js +1179 -857
  337. package/dist/server/handlers/media.js.map +1 -0
  338. package/dist/server/handlers/meta-ads.js +2669 -2093
  339. package/dist/server/handlers/meta-ads.js.map +1 -0
  340. package/dist/server/handlers/nodes.js +1321 -913
  341. package/dist/server/handlers/nodes.js.map +1 -0
  342. package/dist/server/handlers/operations.js +183 -157
  343. package/dist/server/handlers/operations.js.map +1 -0
  344. package/dist/server/handlers/platform.js +346 -210
  345. package/dist/server/handlers/platform.js.map +1 -0
  346. package/dist/server/handlers/remove-bg.js +118 -86
  347. package/dist/server/handlers/remove-bg.js.map +1 -0
  348. package/dist/server/handlers/storefront.js +586 -446
  349. package/dist/server/handlers/storefront.js.map +1 -0
  350. package/dist/server/handlers/supply-chain.js +546 -326
  351. package/dist/server/handlers/supply-chain.js.map +1 -0
  352. package/dist/server/handlers/transcription.js +106 -97
  353. package/dist/server/handlers/transcription.js.map +1 -0
  354. package/dist/server/handlers/video-gen.js +593 -424
  355. package/dist/server/handlers/video-gen.js.map +1 -0
  356. package/dist/server/handlers/voice.js +1458 -1017
  357. package/dist/server/handlers/voice.js.map +1 -0
  358. package/dist/server/handlers/workflow-steps.js +2837 -2116
  359. package/dist/server/handlers/workflow-steps.js.map +1 -0
  360. package/dist/server/handlers/workflows.js +1630 -933
  361. package/dist/server/handlers/workflows.js.map +1 -0
  362. package/dist/server/index.js +3166 -2390
  363. package/dist/server/index.js.map +1 -0
  364. package/dist/server/lib/batch-client.js +471 -409
  365. package/dist/server/lib/batch-client.js.map +1 -0
  366. package/dist/server/lib/clickhouse-buffer.js +118 -104
  367. package/dist/server/lib/clickhouse-buffer.js.map +1 -0
  368. package/dist/server/lib/clickhouse-client.js +107 -107
  369. package/dist/server/lib/clickhouse-client.js.map +1 -0
  370. package/dist/server/lib/coa-renderer.js +1786 -356
  371. package/dist/server/lib/coa-renderer.js.map +1 -0
  372. package/dist/server/lib/code-worker-pool.js +227 -177
  373. package/dist/server/lib/code-worker-pool.js.map +1 -0
  374. package/dist/server/lib/code-worker.js +174 -164
  375. package/dist/server/lib/code-worker.js.map +1 -0
  376. package/dist/server/lib/compaction-service.d.ts +2 -12
  377. package/dist/server/lib/compaction-service.js +74 -184
  378. package/dist/server/lib/compaction-service.js.map +1 -0
  379. package/dist/server/lib/logger.js +36 -24
  380. package/dist/server/lib/logger.js.map +1 -0
  381. package/dist/server/lib/otel.js +101 -80
  382. package/dist/server/lib/otel.js.map +1 -0
  383. package/dist/server/lib/pdf-renderer.d.ts +1 -1
  384. package/dist/server/lib/pdf-renderer.js +954 -776
  385. package/dist/server/lib/pdf-renderer.js.map +1 -0
  386. package/dist/server/lib/prompt-sanitizer.js +188 -108
  387. package/dist/server/lib/prompt-sanitizer.js.map +1 -0
  388. package/dist/server/lib/provider-capabilities.js +136 -138
  389. package/dist/server/lib/provider-capabilities.js.map +1 -0
  390. package/dist/server/lib/provider-failover.js +190 -168
  391. package/dist/server/lib/provider-failover.js.map +1 -0
  392. package/dist/server/lib/rate-limiter.js +186 -117
  393. package/dist/server/lib/rate-limiter.js.map +1 -0
  394. package/dist/server/lib/react-pdf-layout.js +551 -382
  395. package/dist/server/lib/react-pdf-layout.js.map +1 -0
  396. package/dist/server/lib/server-agent-loop.d.ts +9 -0
  397. package/dist/server/lib/server-agent-loop.js +906 -624
  398. package/dist/server/lib/server-agent-loop.js.map +1 -0
  399. package/dist/server/lib/server-subagent.d.ts +2 -0
  400. package/dist/server/lib/server-subagent.js +260 -162
  401. package/dist/server/lib/server-subagent.js.map +1 -0
  402. package/dist/server/lib/session-checkpoint.js +105 -96
  403. package/dist/server/lib/session-checkpoint.js.map +1 -0
  404. package/dist/server/lib/ssrf-guard.js +193 -184
  405. package/dist/server/lib/ssrf-guard.js.map +1 -0
  406. package/dist/server/lib/supabase-client.js +94 -82
  407. package/dist/server/lib/supabase-client.js.map +1 -0
  408. package/dist/server/lib/template-resolver.js +154 -176
  409. package/dist/server/lib/template-resolver.js.map +1 -0
  410. package/dist/server/lib/utils.js +242 -133
  411. package/dist/server/lib/utils.js.map +1 -0
  412. package/dist/server/local-agent-gateway.d.ts +2 -2
  413. package/dist/server/local-agent-gateway.js +785 -627
  414. package/dist/server/local-agent-gateway.js.map +1 -0
  415. package/dist/server/providers/anthropic.js +254 -176
  416. package/dist/server/providers/anthropic.js.map +1 -0
  417. package/dist/server/providers/bedrock.js +221 -162
  418. package/dist/server/providers/bedrock.js.map +1 -0
  419. package/dist/server/providers/gemini.js +548 -418
  420. package/dist/server/providers/gemini.js.map +1 -0
  421. package/dist/server/providers/openai.js +571 -437
  422. package/dist/server/providers/openai.js.map +1 -0
  423. package/dist/server/providers/registry.js +23 -18
  424. package/dist/server/providers/registry.js.map +1 -0
  425. package/dist/server/providers/shared.js +123 -95
  426. package/dist/server/providers/shared.js.map +1 -0
  427. package/dist/server/providers/types.js +1 -11
  428. package/dist/server/providers/types.js.map +1 -0
  429. package/dist/server/proxy-handlers.js +209 -165
  430. package/dist/server/proxy-handlers.js.map +1 -0
  431. package/dist/server/tool-router.d.ts +13 -0
  432. package/dist/server/tool-router.js +960 -598
  433. package/dist/server/tool-router.js.map +1 -0
  434. package/dist/server/validation.js +248 -188
  435. package/dist/server/validation.js.map +1 -0
  436. package/dist/server/worker.js +202 -133
  437. package/dist/server/worker.js.map +1 -0
  438. package/dist/setup.d.ts +2 -2
  439. package/dist/setup.js +151 -147
  440. package/dist/setup.js.map +1 -0
  441. package/dist/shared/agent-core.d.ts +191 -24
  442. package/dist/shared/agent-core.js +971 -462
  443. package/dist/shared/agent-core.js.map +1 -0
  444. package/dist/shared/anthropic-types.js +1 -6
  445. package/dist/shared/anthropic-types.js.map +1 -0
  446. package/dist/shared/api-client.d.ts +17 -9
  447. package/dist/shared/api-client.js +419 -327
  448. package/dist/shared/api-client.js.map +1 -0
  449. package/dist/shared/compaction.d.ts +36 -0
  450. package/dist/shared/compaction.js +138 -0
  451. package/dist/shared/compaction.js.map +1 -0
  452. package/dist/shared/constants.js +67 -64
  453. package/dist/shared/constants.js.map +1 -0
  454. package/dist/shared/sse-parser.js +221 -219
  455. package/dist/shared/sse-parser.js.map +1 -0
  456. package/dist/shared/tool-dispatch.d.ts +4 -2
  457. package/dist/shared/tool-dispatch.js +226 -165
  458. package/dist/shared/tool-dispatch.js.map +1 -0
  459. package/dist/shared/types.js +1 -6
  460. package/dist/shared/types.js.map +1 -0
  461. package/dist/types/cli-highlight.d.js +2 -0
  462. package/dist/types/cli-highlight.d.js.map +1 -0
  463. package/dist/types/diff.d.js +2 -0
  464. package/dist/types/diff.d.js.map +1 -0
  465. package/dist/types/pdf-parse.d.js +2 -0
  466. package/dist/types/pdf-parse.d.js.map +1 -0
  467. package/dist/updater.d.ts +1 -1
  468. package/dist/updater.js +118 -92
  469. package/dist/updater.js.map +1 -0
  470. package/dist/webchat/widget.js +227 -380
  471. package/dist/webchat/widget.js.map +1 -0
  472. package/package.json +22 -10
  473. package/vendor/ink/build/ansi-tokenizer.d.ts +38 -0
  474. package/vendor/ink/build/ansi-tokenizer.js +316 -0
  475. package/vendor/ink/build/ansi-tokenizer.js.map +1 -0
  476. package/vendor/ink/build/apply-styles.js +175 -0
  477. package/vendor/ink/build/build-layout.js +77 -0
  478. package/vendor/ink/build/calculate-wrapped-text.js +53 -0
  479. package/vendor/ink/build/colorize.d.ts +3 -0
  480. package/vendor/ink/build/colorize.js +48 -0
  481. package/vendor/ink/build/colorize.js.map +1 -0
  482. package/vendor/ink/build/components/AccessibilityContext.d.ts +3 -0
  483. package/vendor/ink/build/components/AccessibilityContext.js +5 -0
  484. package/vendor/ink/build/components/AccessibilityContext.js.map +1 -0
  485. package/vendor/ink/build/components/App.d.ts +18 -0
  486. package/vendor/ink/build/components/App.js +351 -0
  487. package/vendor/ink/build/components/App.js.map +1 -0
  488. package/vendor/ink/build/components/AppContext.d.ts +15 -0
  489. package/vendor/ink/build/components/AppContext.js +11 -0
  490. package/vendor/ink/build/components/AppContext.js.map +1 -0
  491. package/vendor/ink/build/components/BackgroundContext.d.ts +4 -0
  492. package/vendor/ink/build/components/BackgroundContext.js +3 -0
  493. package/vendor/ink/build/components/BackgroundContext.js.map +1 -0
  494. package/vendor/ink/build/components/Box.d.ts +117 -0
  495. package/vendor/ink/build/components/Box.js +34 -0
  496. package/vendor/ink/build/components/Box.js.map +1 -0
  497. package/vendor/ink/build/components/Color.js +62 -0
  498. package/vendor/ink/build/components/Cursor.d.ts +83 -0
  499. package/vendor/ink/build/components/Cursor.js +53 -0
  500. package/vendor/ink/build/components/Cursor.js.map +1 -0
  501. package/vendor/ink/build/components/CursorContext.d.ts +11 -0
  502. package/vendor/ink/build/components/CursorContext.js +8 -0
  503. package/vendor/ink/build/components/CursorContext.js.map +1 -0
  504. package/vendor/ink/build/components/ErrorBoundary.d.ts +18 -0
  505. package/vendor/ink/build/components/ErrorBoundary.js +23 -0
  506. package/vendor/ink/build/components/ErrorBoundary.js.map +1 -0
  507. package/vendor/ink/build/components/ErrorOverview.d.ts +6 -0
  508. package/vendor/ink/build/components/ErrorOverview.js +84 -0
  509. package/vendor/ink/build/components/ErrorOverview.js.map +1 -0
  510. package/vendor/ink/build/components/FocusContext.d.ts +16 -0
  511. package/vendor/ink/build/components/FocusContext.js +17 -0
  512. package/vendor/ink/build/components/FocusContext.js.map +1 -0
  513. package/vendor/ink/build/components/Newline.d.ts +13 -0
  514. package/vendor/ink/build/components/Newline.js +8 -0
  515. package/vendor/ink/build/components/Newline.js.map +1 -0
  516. package/vendor/ink/build/components/Spacer.d.ts +7 -0
  517. package/vendor/ink/build/components/Spacer.js +11 -0
  518. package/vendor/ink/build/components/Spacer.js.map +1 -0
  519. package/vendor/ink/build/components/Static.d.ts +24 -0
  520. package/vendor/ink/build/components/Static.js +28 -0
  521. package/vendor/ink/build/components/Static.js.map +1 -0
  522. package/vendor/ink/build/components/StderrContext.d.ts +15 -0
  523. package/vendor/ink/build/components/StderrContext.js +13 -0
  524. package/vendor/ink/build/components/StderrContext.js.map +1 -0
  525. package/vendor/ink/build/components/StdinContext.d.ts +22 -0
  526. package/vendor/ink/build/components/StdinContext.js +19 -0
  527. package/vendor/ink/build/components/StdinContext.js.map +1 -0
  528. package/vendor/ink/build/components/StdoutContext.d.ts +15 -0
  529. package/vendor/ink/build/components/StdoutContext.js +13 -0
  530. package/vendor/ink/build/components/StdoutContext.js.map +1 -0
  531. package/vendor/ink/build/components/Text.d.ts +55 -0
  532. package/vendor/ink/build/components/Text.js +50 -0
  533. package/vendor/ink/build/components/Text.js.map +1 -0
  534. package/vendor/ink/build/components/Transform.d.ts +16 -0
  535. package/vendor/ink/build/components/Transform.js +15 -0
  536. package/vendor/ink/build/components/Transform.js.map +1 -0
  537. package/vendor/ink/build/cursor-helpers.d.ts +38 -0
  538. package/vendor/ink/build/cursor-helpers.js +56 -0
  539. package/vendor/ink/build/cursor-helpers.js.map +1 -0
  540. package/vendor/ink/build/devtools-window-polyfill.d.ts +1 -0
  541. package/vendor/ink/build/devtools-window-polyfill.js +65 -0
  542. package/vendor/ink/build/devtools-window-polyfill.js.map +1 -0
  543. package/vendor/ink/build/devtools.d.ts +1 -0
  544. package/vendor/ink/build/devtools.js +11 -0
  545. package/vendor/ink/build/devtools.js.map +1 -0
  546. package/vendor/ink/build/dom.d.ts +56 -0
  547. package/vendor/ink/build/dom.js +124 -0
  548. package/vendor/ink/build/dom.js.map +1 -0
  549. package/vendor/ink/build/experimental/apply-style.js +140 -0
  550. package/vendor/ink/build/experimental/dom.js +123 -0
  551. package/vendor/ink/build/experimental/output.js +91 -0
  552. package/vendor/ink/build/experimental/reconciler.js +141 -0
  553. package/vendor/ink/build/experimental/renderer.js +81 -0
  554. package/vendor/ink/build/get-max-width.d.ts +3 -0
  555. package/vendor/ink/build/get-max-width.js +10 -0
  556. package/vendor/ink/build/get-max-width.js.map +1 -0
  557. package/vendor/ink/build/hooks/use-app.d.ts +5 -0
  558. package/vendor/ink/build/hooks/use-app.js +8 -0
  559. package/vendor/ink/build/hooks/use-app.js.map +1 -0
  560. package/vendor/ink/build/hooks/use-cursor.d.ts +12 -0
  561. package/vendor/ink/build/hooks/use-cursor.js +29 -0
  562. package/vendor/ink/build/hooks/use-cursor.js.map +1 -0
  563. package/vendor/ink/build/hooks/use-focus-manager.d.ts +28 -0
  564. package/vendor/ink/build/hooks/use-focus-manager.js +17 -0
  565. package/vendor/ink/build/hooks/use-focus-manager.js.map +1 -0
  566. package/vendor/ink/build/hooks/use-focus.d.ts +29 -0
  567. package/vendor/ink/build/hooks/use-focus.js +42 -0
  568. package/vendor/ink/build/hooks/use-focus.js.map +1 -0
  569. package/vendor/ink/build/hooks/use-input.d.ts +131 -0
  570. package/vendor/ink/build/hooks/use-input.js +124 -0
  571. package/vendor/ink/build/hooks/use-input.js.map +1 -0
  572. package/vendor/ink/build/hooks/use-is-screen-reader-enabled.d.ts +5 -0
  573. package/vendor/ink/build/hooks/use-is-screen-reader-enabled.js +11 -0
  574. package/vendor/ink/build/hooks/use-is-screen-reader-enabled.js.map +1 -0
  575. package/vendor/ink/build/hooks/use-stderr.d.ts +5 -0
  576. package/vendor/ink/build/hooks/use-stderr.js +8 -0
  577. package/vendor/ink/build/hooks/use-stderr.js.map +1 -0
  578. package/vendor/ink/build/hooks/use-stdin.d.ts +5 -0
  579. package/vendor/ink/build/hooks/use-stdin.js +8 -0
  580. package/vendor/ink/build/hooks/use-stdin.js.map +1 -0
  581. package/vendor/ink/build/hooks/use-stdout.d.ts +5 -0
  582. package/vendor/ink/build/hooks/use-stdout.js +8 -0
  583. package/vendor/ink/build/hooks/use-stdout.js.map +1 -0
  584. package/vendor/ink/build/hooks/useInput.js +38 -0
  585. package/vendor/ink/build/index.d.ts +34 -0
  586. package/vendor/ink/build/index.js +20 -0
  587. package/vendor/ink/build/index.js.map +1 -0
  588. package/vendor/ink/build/ink.d.ts +90 -0
  589. package/vendor/ink/build/ink.js +654 -0
  590. package/vendor/ink/build/ink.js.map +1 -0
  591. package/vendor/ink/build/input-parser.d.ts +7 -0
  592. package/vendor/ink/build/input-parser.js +154 -0
  593. package/vendor/ink/build/input-parser.js.map +1 -0
  594. package/vendor/ink/build/instance.js +205 -0
  595. package/vendor/ink/build/instances.d.ts +3 -0
  596. package/vendor/ink/build/instances.js +8 -0
  597. package/vendor/ink/build/instances.js.map +1 -0
  598. package/vendor/ink/build/kitty-keyboard.d.ts +23 -0
  599. package/vendor/ink/build/kitty-keyboard.js +32 -0
  600. package/vendor/ink/build/kitty-keyboard.js.map +1 -0
  601. package/vendor/ink/build/layout.d.ts +7 -0
  602. package/vendor/ink/build/layout.js +33 -0
  603. package/vendor/ink/build/layout.js.map +1 -0
  604. package/vendor/ink/build/log-update.d.ts +19 -0
  605. package/vendor/ink/build/log-update.js +243 -0
  606. package/vendor/ink/build/log-update.js.map +1 -0
  607. package/vendor/ink/build/measure-element.d.ts +16 -0
  608. package/vendor/ink/build/measure-element.js +9 -0
  609. package/vendor/ink/build/measure-element.js.map +1 -0
  610. package/vendor/ink/build/measure-text.d.ts +6 -0
  611. package/vendor/ink/build/measure-text.js +21 -0
  612. package/vendor/ink/build/measure-text.js.map +1 -0
  613. package/vendor/ink/build/options.d.ts +52 -0
  614. package/vendor/ink/build/options.js +2 -0
  615. package/vendor/ink/build/options.js.map +1 -0
  616. package/vendor/ink/build/output.d.ts +35 -0
  617. package/vendor/ink/build/output.js +183 -0
  618. package/vendor/ink/build/output.js.map +1 -0
  619. package/vendor/ink/build/parse-keypress.d.ts +22 -0
  620. package/vendor/ink/build/parse-keypress.js +493 -0
  621. package/vendor/ink/build/parse-keypress.js.map +1 -0
  622. package/vendor/ink/build/reconciler.d.ts +4 -0
  623. package/vendor/ink/build/reconciler.js +274 -0
  624. package/vendor/ink/build/reconciler.js.map +1 -0
  625. package/vendor/ink/build/render-background.d.ts +4 -0
  626. package/vendor/ink/build/render-background.js +25 -0
  627. package/vendor/ink/build/render-background.js.map +1 -0
  628. package/vendor/ink/build/render-border.d.ts +4 -0
  629. package/vendor/ink/build/render-border.js +73 -0
  630. package/vendor/ink/build/render-border.js.map +1 -0
  631. package/vendor/ink/build/render-node-to-output.d.ts +14 -0
  632. package/vendor/ink/build/render-node-to-output.js +147 -0
  633. package/vendor/ink/build/render-node-to-output.js.map +1 -0
  634. package/vendor/ink/build/render-to-string.d.ts +38 -0
  635. package/vendor/ink/build/render-to-string.js +115 -0
  636. package/vendor/ink/build/render-to-string.js.map +1 -0
  637. package/vendor/ink/build/render.d.ts +121 -0
  638. package/vendor/ink/build/render.js +55 -0
  639. package/vendor/ink/build/render.js.map +1 -0
  640. package/vendor/ink/build/renderer.d.ts +8 -0
  641. package/vendor/ink/build/renderer.js +55 -0
  642. package/vendor/ink/build/renderer.js.map +1 -0
  643. package/vendor/ink/build/sanitize-ansi.d.ts +2 -0
  644. package/vendor/ink/build/sanitize-ansi.js +27 -0
  645. package/vendor/ink/build/sanitize-ansi.js.map +1 -0
  646. package/vendor/ink/build/screen-reader-update.d.ts +13 -0
  647. package/vendor/ink/build/screen-reader-update.js +38 -0
  648. package/vendor/ink/build/screen-reader-update.js.map +1 -0
  649. package/vendor/ink/build/squash-text-nodes.d.ts +3 -0
  650. package/vendor/ink/build/squash-text-nodes.js +36 -0
  651. package/vendor/ink/build/squash-text-nodes.js.map +1 -0
  652. package/vendor/ink/build/styles.d.ts +240 -0
  653. package/vendor/ink/build/styles.js +232 -0
  654. package/vendor/ink/build/styles.js.map +1 -0
  655. package/vendor/ink/build/utils.d.ts +2 -0
  656. package/vendor/ink/build/utils.js +4 -0
  657. package/vendor/ink/build/utils.js.map +1 -0
  658. package/vendor/ink/build/wrap-text.d.ts +3 -0
  659. package/vendor/ink/build/wrap-text.js +31 -0
  660. package/vendor/ink/build/wrap-text.js.map +1 -0
  661. package/vendor/ink/build/write-synchronized.d.ts +4 -0
  662. package/vendor/ink/build/write-synchronized.js +7 -0
  663. package/vendor/ink/build/write-synchronized.js.map +1 -0
  664. package/vendor/ink/license +10 -0
  665. package/vendor/ink/node_modules/@types/node/LICENSE +21 -0
  666. package/vendor/ink/node_modules/@types/node/README.md +15 -0
  667. package/vendor/ink/node_modules/@types/node/assert/strict.d.ts +105 -0
  668. package/vendor/ink/node_modules/@types/node/assert.d.ts +955 -0
  669. package/vendor/ink/node_modules/@types/node/async_hooks.d.ts +623 -0
  670. package/vendor/ink/node_modules/@types/node/buffer.buffer.d.ts +466 -0
  671. package/vendor/ink/node_modules/@types/node/buffer.d.ts +1810 -0
  672. package/vendor/ink/node_modules/@types/node/child_process.d.ts +1428 -0
  673. package/vendor/ink/node_modules/@types/node/cluster.d.ts +486 -0
  674. package/vendor/ink/node_modules/@types/node/compatibility/iterators.d.ts +21 -0
  675. package/vendor/ink/node_modules/@types/node/console.d.ts +151 -0
  676. package/vendor/ink/node_modules/@types/node/constants.d.ts +20 -0
  677. package/vendor/ink/node_modules/@types/node/crypto.d.ts +4065 -0
  678. package/vendor/ink/node_modules/@types/node/dgram.d.ts +564 -0
  679. package/vendor/ink/node_modules/@types/node/diagnostics_channel.d.ts +576 -0
  680. package/vendor/ink/node_modules/@types/node/dns/promises.d.ts +503 -0
  681. package/vendor/ink/node_modules/@types/node/dns.d.ts +922 -0
  682. package/vendor/ink/node_modules/@types/node/domain.d.ts +166 -0
  683. package/vendor/ink/node_modules/@types/node/events.d.ts +1054 -0
  684. package/vendor/ink/node_modules/@types/node/fs/promises.d.ts +1329 -0
  685. package/vendor/ink/node_modules/@types/node/fs.d.ts +4676 -0
  686. package/vendor/ink/node_modules/@types/node/globals.d.ts +150 -0
  687. package/vendor/ink/node_modules/@types/node/globals.typedarray.d.ts +101 -0
  688. package/vendor/ink/node_modules/@types/node/http.d.ts +2167 -0
  689. package/vendor/ink/node_modules/@types/node/http2.d.ts +2480 -0
  690. package/vendor/ink/node_modules/@types/node/https.d.ts +405 -0
  691. package/vendor/ink/node_modules/@types/node/index.d.ts +115 -0
  692. package/vendor/ink/node_modules/@types/node/inspector/promises.d.ts +41 -0
  693. package/vendor/ink/node_modules/@types/node/inspector.d.ts +224 -0
  694. package/vendor/ink/node_modules/@types/node/inspector.generated.d.ts +4226 -0
  695. package/vendor/ink/node_modules/@types/node/module.d.ts +819 -0
  696. package/vendor/ink/node_modules/@types/node/net.d.ts +933 -0
  697. package/vendor/ink/node_modules/@types/node/os.d.ts +507 -0
  698. package/vendor/ink/node_modules/@types/node/package.json +155 -0
  699. package/vendor/ink/node_modules/@types/node/path/posix.d.ts +8 -0
  700. package/vendor/ink/node_modules/@types/node/path/win32.d.ts +8 -0
  701. package/vendor/ink/node_modules/@types/node/path.d.ts +187 -0
  702. package/vendor/ink/node_modules/@types/node/perf_hooks.d.ts +643 -0
  703. package/vendor/ink/node_modules/@types/node/process.d.ts +2156 -0
  704. package/vendor/ink/node_modules/@types/node/punycode.d.ts +117 -0
  705. package/vendor/ink/node_modules/@types/node/querystring.d.ts +152 -0
  706. package/vendor/ink/node_modules/@types/node/quic.d.ts +910 -0
  707. package/vendor/ink/node_modules/@types/node/readline/promises.d.ts +161 -0
  708. package/vendor/ink/node_modules/@types/node/readline.d.ts +541 -0
  709. package/vendor/ink/node_modules/@types/node/repl.d.ts +415 -0
  710. package/vendor/ink/node_modules/@types/node/sea.d.ts +162 -0
  711. package/vendor/ink/node_modules/@types/node/sqlite.d.ts +955 -0
  712. package/vendor/ink/node_modules/@types/node/stream/consumers.d.ts +38 -0
  713. package/vendor/ink/node_modules/@types/node/stream/promises.d.ts +211 -0
  714. package/vendor/ink/node_modules/@types/node/stream/web.d.ts +296 -0
  715. package/vendor/ink/node_modules/@types/node/stream.d.ts +1760 -0
  716. package/vendor/ink/node_modules/@types/node/string_decoder.d.ts +67 -0
  717. package/vendor/ink/node_modules/@types/node/test/reporters.d.ts +96 -0
  718. package/vendor/ink/node_modules/@types/node/test.d.ts +2240 -0
  719. package/vendor/ink/node_modules/@types/node/timers/promises.d.ts +108 -0
  720. package/vendor/ink/node_modules/@types/node/timers.d.ts +159 -0
  721. package/vendor/ink/node_modules/@types/node/tls.d.ts +1198 -0
  722. package/vendor/ink/node_modules/@types/node/trace_events.d.ts +197 -0
  723. package/vendor/ink/node_modules/@types/node/ts5.6/buffer.buffer.d.ts +462 -0
  724. package/vendor/ink/node_modules/@types/node/ts5.6/compatibility/float16array.d.ts +71 -0
  725. package/vendor/ink/node_modules/@types/node/ts5.6/globals.typedarray.d.ts +36 -0
  726. package/vendor/ink/node_modules/@types/node/ts5.6/index.d.ts +117 -0
  727. package/vendor/ink/node_modules/@types/node/ts5.7/compatibility/float16array.d.ts +72 -0
  728. package/vendor/ink/node_modules/@types/node/ts5.7/index.d.ts +117 -0
  729. package/vendor/ink/node_modules/@types/node/tty.d.ts +250 -0
  730. package/vendor/ink/node_modules/@types/node/url.d.ts +519 -0
  731. package/vendor/ink/node_modules/@types/node/util/types.d.ts +558 -0
  732. package/vendor/ink/node_modules/@types/node/util.d.ts +1662 -0
  733. package/vendor/ink/node_modules/@types/node/v8.d.ts +983 -0
  734. package/vendor/ink/node_modules/@types/node/vm.d.ts +1208 -0
  735. package/vendor/ink/node_modules/@types/node/wasi.d.ts +202 -0
  736. package/vendor/ink/node_modules/@types/node/web-globals/abortcontroller.d.ts +59 -0
  737. package/vendor/ink/node_modules/@types/node/web-globals/blob.d.ts +23 -0
  738. package/vendor/ink/node_modules/@types/node/web-globals/console.d.ts +9 -0
  739. package/vendor/ink/node_modules/@types/node/web-globals/crypto.d.ts +39 -0
  740. package/vendor/ink/node_modules/@types/node/web-globals/domexception.d.ts +68 -0
  741. package/vendor/ink/node_modules/@types/node/web-globals/encoding.d.ts +11 -0
  742. package/vendor/ink/node_modules/@types/node/web-globals/events.d.ts +106 -0
  743. package/vendor/ink/node_modules/@types/node/web-globals/fetch.d.ts +69 -0
  744. package/vendor/ink/node_modules/@types/node/web-globals/importmeta.d.ts +13 -0
  745. package/vendor/ink/node_modules/@types/node/web-globals/messaging.d.ts +23 -0
  746. package/vendor/ink/node_modules/@types/node/web-globals/navigator.d.ts +25 -0
  747. package/vendor/ink/node_modules/@types/node/web-globals/performance.d.ts +45 -0
  748. package/vendor/ink/node_modules/@types/node/web-globals/storage.d.ts +24 -0
  749. package/vendor/ink/node_modules/@types/node/web-globals/streams.d.ts +115 -0
  750. package/vendor/ink/node_modules/@types/node/web-globals/timers.d.ts +44 -0
  751. package/vendor/ink/node_modules/@types/node/web-globals/url.d.ts +24 -0
  752. package/vendor/ink/node_modules/@types/node/worker_threads.d.ts +717 -0
  753. package/vendor/ink/node_modules/@types/node/zlib.d.ts +618 -0
  754. package/vendor/ink/node_modules/node-pty/LICENSE +69 -0
  755. package/vendor/ink/node_modules/node-pty/README.md +164 -0
  756. package/vendor/ink/node_modules/node-pty/binding.gyp +150 -0
  757. package/vendor/ink/node_modules/node-pty/lib/conpty_console_list_agent.js +25 -0
  758. package/vendor/ink/node_modules/node-pty/lib/eventEmitter2.js +47 -0
  759. package/vendor/ink/node_modules/node-pty/lib/index.js +52 -0
  760. package/vendor/ink/node_modules/node-pty/lib/interfaces.js +7 -0
  761. package/vendor/ink/node_modules/node-pty/lib/shared/conout.js +11 -0
  762. package/vendor/ink/node_modules/node-pty/lib/terminal.js +190 -0
  763. package/vendor/ink/node_modules/node-pty/lib/types.js +7 -0
  764. package/vendor/ink/node_modules/node-pty/lib/unixTerminal.js +349 -0
  765. package/vendor/ink/node_modules/node-pty/lib/utils.js +39 -0
  766. package/vendor/ink/node_modules/node-pty/lib/windowsConoutConnection.js +125 -0
  767. package/vendor/ink/node_modules/node-pty/lib/windowsPtyAgent.js +287 -0
  768. package/vendor/ink/node_modules/node-pty/lib/windowsTerminal.js +201 -0
  769. package/vendor/ink/node_modules/node-pty/lib/worker/conoutSocketWorker.js +22 -0
  770. package/vendor/ink/node_modules/node-pty/package.json +65 -0
  771. package/vendor/ink/node_modules/node-pty/prebuilds/darwin-arm64/pty.node +0 -0
  772. package/vendor/ink/node_modules/node-pty/prebuilds/darwin-arm64/spawn-helper +0 -0
  773. package/vendor/ink/node_modules/node-pty/prebuilds/darwin-x64/pty.node +0 -0
  774. package/vendor/ink/node_modules/node-pty/prebuilds/darwin-x64/spawn-helper +0 -0
  775. package/vendor/ink/node_modules/node-pty/prebuilds/linux-arm64/pty.node +0 -0
  776. package/vendor/ink/node_modules/node-pty/prebuilds/linux-x64/pty.node +0 -0
  777. package/vendor/ink/node_modules/node-pty/prebuilds/win32-arm64/conpty/OpenConsole.exe +0 -0
  778. package/vendor/ink/node_modules/node-pty/prebuilds/win32-arm64/conpty/conpty.dll +0 -0
  779. package/vendor/ink/node_modules/node-pty/prebuilds/win32-arm64/conpty.node +0 -0
  780. package/vendor/ink/node_modules/node-pty/prebuilds/win32-arm64/conpty.pdb +0 -0
  781. package/vendor/ink/node_modules/node-pty/prebuilds/win32-arm64/conpty_console_list.node +0 -0
  782. package/vendor/ink/node_modules/node-pty/prebuilds/win32-arm64/conpty_console_list.pdb +0 -0
  783. package/vendor/ink/node_modules/node-pty/prebuilds/win32-x64/conpty/OpenConsole.exe +0 -0
  784. package/vendor/ink/node_modules/node-pty/prebuilds/win32-x64/conpty/conpty.dll +0 -0
  785. package/vendor/ink/node_modules/node-pty/prebuilds/win32-x64/conpty.node +0 -0
  786. package/vendor/ink/node_modules/node-pty/prebuilds/win32-x64/conpty.pdb +0 -0
  787. package/vendor/ink/node_modules/node-pty/prebuilds/win32-x64/conpty_console_list.node +0 -0
  788. package/vendor/ink/node_modules/node-pty/prebuilds/win32-x64/conpty_console_list.pdb +0 -0
  789. package/vendor/ink/node_modules/node-pty/scripts/post-install.js +76 -0
  790. package/vendor/ink/node_modules/node-pty/scripts/prebuild.js +34 -0
  791. package/vendor/ink/node_modules/node-pty/src/unix/pty.cc +875 -0
  792. package/vendor/ink/node_modules/node-pty/src/unix/spawn-helper.cc +23 -0
  793. package/vendor/ink/node_modules/node-pty/src/win/conpty.cc +582 -0
  794. package/vendor/ink/node_modules/node-pty/src/win/conpty.h +41 -0
  795. package/vendor/ink/node_modules/node-pty/src/win/conpty_console_list.cc +44 -0
  796. package/vendor/ink/node_modules/node-pty/src/win/path_util.cc +95 -0
  797. package/vendor/ink/node_modules/node-pty/src/win/path_util.h +26 -0
  798. package/vendor/ink/node_modules/node-pty/third_party/conpty/1.23.251008001/win10-arm64/OpenConsole.exe +0 -0
  799. package/vendor/ink/node_modules/node-pty/third_party/conpty/1.23.251008001/win10-arm64/conpty.dll +0 -0
  800. package/vendor/ink/node_modules/node-pty/third_party/conpty/1.23.251008001/win10-x64/OpenConsole.exe +0 -0
  801. package/vendor/ink/node_modules/node-pty/third_party/conpty/1.23.251008001/win10-x64/conpty.dll +0 -0
  802. package/vendor/ink/node_modules/node-pty/typings/node-pty.d.ts +215 -0
  803. package/vendor/ink/node_modules/undici-types/LICENSE +21 -0
  804. package/vendor/ink/node_modules/undici-types/README.md +6 -0
  805. package/vendor/ink/node_modules/undici-types/agent.d.ts +32 -0
  806. package/vendor/ink/node_modules/undici-types/api.d.ts +43 -0
  807. package/vendor/ink/node_modules/undici-types/balanced-pool.d.ts +30 -0
  808. package/vendor/ink/node_modules/undici-types/cache-interceptor.d.ts +173 -0
  809. package/vendor/ink/node_modules/undici-types/cache.d.ts +36 -0
  810. package/vendor/ink/node_modules/undici-types/client-stats.d.ts +15 -0
  811. package/vendor/ink/node_modules/undici-types/client.d.ts +108 -0
  812. package/vendor/ink/node_modules/undici-types/connector.d.ts +34 -0
  813. package/vendor/ink/node_modules/undici-types/content-type.d.ts +21 -0
  814. package/vendor/ink/node_modules/undici-types/cookies.d.ts +30 -0
  815. package/vendor/ink/node_modules/undici-types/diagnostics-channel.d.ts +74 -0
  816. package/vendor/ink/node_modules/undici-types/dispatcher.d.ts +276 -0
  817. package/vendor/ink/node_modules/undici-types/env-http-proxy-agent.d.ts +22 -0
  818. package/vendor/ink/node_modules/undici-types/errors.d.ts +161 -0
  819. package/vendor/ink/node_modules/undici-types/eventsource.d.ts +66 -0
  820. package/vendor/ink/node_modules/undici-types/fetch.d.ts +211 -0
  821. package/vendor/ink/node_modules/undici-types/formdata.d.ts +108 -0
  822. package/vendor/ink/node_modules/undici-types/global-dispatcher.d.ts +9 -0
  823. package/vendor/ink/node_modules/undici-types/global-origin.d.ts +7 -0
  824. package/vendor/ink/node_modules/undici-types/h2c-client.d.ts +73 -0
  825. package/vendor/ink/node_modules/undici-types/handlers.d.ts +15 -0
  826. package/vendor/ink/node_modules/undici-types/header.d.ts +160 -0
  827. package/vendor/ink/node_modules/undici-types/index.d.ts +88 -0
  828. package/vendor/ink/node_modules/undici-types/interceptors.d.ts +73 -0
  829. package/vendor/ink/node_modules/undici-types/mock-agent.d.ts +68 -0
  830. package/vendor/ink/node_modules/undici-types/mock-call-history.d.ts +111 -0
  831. package/vendor/ink/node_modules/undici-types/mock-client.d.ts +27 -0
  832. package/vendor/ink/node_modules/undici-types/mock-errors.d.ts +12 -0
  833. package/vendor/ink/node_modules/undici-types/mock-interceptor.d.ts +94 -0
  834. package/vendor/ink/node_modules/undici-types/mock-pool.d.ts +27 -0
  835. package/vendor/ink/node_modules/undici-types/package.json +55 -0
  836. package/vendor/ink/node_modules/undici-types/patch.d.ts +29 -0
  837. package/vendor/ink/node_modules/undici-types/pool-stats.d.ts +19 -0
  838. package/vendor/ink/node_modules/undici-types/pool.d.ts +41 -0
  839. package/vendor/ink/node_modules/undici-types/proxy-agent.d.ts +29 -0
  840. package/vendor/ink/node_modules/undici-types/readable.d.ts +68 -0
  841. package/vendor/ink/node_modules/undici-types/retry-agent.d.ts +8 -0
  842. package/vendor/ink/node_modules/undici-types/retry-handler.d.ts +125 -0
  843. package/vendor/ink/node_modules/undici-types/round-robin-pool.d.ts +41 -0
  844. package/vendor/ink/node_modules/undici-types/snapshot-agent.d.ts +109 -0
  845. package/vendor/ink/node_modules/undici-types/util.d.ts +18 -0
  846. package/vendor/ink/node_modules/undici-types/utility.d.ts +7 -0
  847. package/vendor/ink/node_modules/undici-types/webidl.d.ts +341 -0
  848. package/vendor/ink/node_modules/undici-types/websocket.d.ts +186 -0
  849. package/vendor/ink/package.json +201 -0
  850. package/vendor/ink/readme.md +2636 -0
  851. package/bin/swag-agent.js +0 -9
  852. package/dist/server/lib/pg-rate-limiter.d.ts +0 -21
  853. package/dist/server/lib/pg-rate-limiter.js +0 -86
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent-core.js","names":["getProvider","resolveToolChoice","opts","toolChoice","undefined","recentToolUses","length","last3","slice","last6","isRepeatingPair","turnCount","userMessage","availableToolNames","msgLower","toLowerCase","toolName","includes","type","name","COMPACTION_TRIGGER_TOKENS","COMPACTION_TOTAL_BUDGET","DEFAULT_SESSION_COST_BUDGET_USD","getCompactionConfig","model","provider","triggerTokens","totalBudget","isNative","getContextManagement","overrides","betas","config","edits","clearThinkingKeep","clear_thinking_keep","push","keep","value","supportsCompaction","compactionTrigger","compaction_trigger_tokens","AGENT_DEFAULTS","compactionTriggerTokens","trigger","pause_after_compaction","instructions","clearToolUsesTrigger","clear_tool_uses_trigger","clearToolUsesKeep","clear_tool_uses_keep","DEFAULT_OUTPUT_TOKENS","MODEL_MAX_OUTPUT_TOKENS","getMaxOutputTokens","agentMax","modelMax","Math","min","addPromptCaching","tools","messages","cachedTools","cache_control","cachedMessages","idx","msg","content","text","Array","isArray","blocks","djb2Hash","str","hash","i","charCodeAt","toString","LoopDetector","history","consecutiveErrors","Map","turnErrors","turnHadErrors","sessionErrors","failedStrategies","Set","consecutiveFailedTurns","totalSessionErrors","fileReadCounts","constructor","identicalCallLimit","loopIdenticalCallLimit","consecutiveErrorLimit","loopConsecutiveErrorLimit","turnErrorLimit","loopTurnErrorLimit","window","loopWindow","sessionToolErrorLimit","loopSessionToolErrorLimit","consecutiveFailedTurnLimit","loopConsecutiveFailedTurnLimit","fileReadLimit","loopFileReadLimit","fromResolved","resolved","errorKey","input","action","recordCall","inputHash","JSON","stringify","eKey","has","blocked","reason","sessionErrorCount","get","errorCount","windowSlice","identicalCount","filter","h","trackRead","path","readCount","set","recordResult","success","transient","delete","current","sessionCount","add","size","arr","from","endTurn","clear","key","count","decayed","floor","shouldBail","message","resetTurn","reset","getSessionStats","totalErrors","getThinkingConfig","enabled","thinking","beta","isReasoning","test","budget_tokens","MODEL_PRICING","inputPer1M","outputPer1M","thinkingPer1M","emitCostWarningIfNeeded","sessionCostUsd","maxCostUsd","costWarningsEmitted","onText","isFinite","pct","toFixed","estimateCostUsd","inputTokens","outputTokens","thinkingTokens","cacheReadTokens","cacheCreationTokens","pricing","Object","keys","find","k","startsWith","thinkingRate","inputRate","cost","routeModel","requestedModel","forceModel","estimatedTokens","ceil","simplePatterns","complexPatterns","categorizeError","err","e","status","statusCode","String","category","retryable","isRetryableError","demoteSubagentModel","requested","agentType","maxTurns","temperature","maxConcurrentTools","enableDelegation","maxDurationMs","maxDurationMsWorkflow","enableModelRouting","subagentMaxTokens","subagentMaxTurns","subagentTemperature","subagentMaxRetries","maxContinuations","subagentMaxContinuations","maxMessageChars","maxHistoryChars","maxToolResultChars","compactionTotalBudget","sessionCostBudgetUsd","teammateMaxTotalTurns","teamTimeoutMs","workerStallMs","teamReviewMaxTokens","apiTimeoutMs","toolTimeoutMs","toolResultTruncateChars","loopBatchErrorLimit","resolveAgentLoopConfig","agent","callPath","workflowMaxTurns","cc","context_config","defaultsUsed","resolve","dbValue","defaultValue","agentMaxTurns","max_tool_calls","maxTokens","max_tokens","durationDefault","max_concurrent_tools","enable_delegation","max_duration_ms","enable_model_routing","max_message_chars","max_history_chars","contextOverrides","compaction_total_budget","session_cost_budget_usd","subagent_max_tokens","subagent_max_turns","subagent_temperature","max_continuations","subagent_max_continuations","subagent_max_retries","max_tool_result_chars","teammate_max_total_turns","team_timeout_ms","worker_stall_ms","team_review_max_tokens","api_timeout_ms","tool_timeout_ms","tool_result_truncate_chars","loop_identical_call_limit","loop_consecutive_error_limit","loop_turn_error_limit","loop_window","loop_session_tool_error_limit","loop_consecutive_failed_turn_limit","loop_file_read_limit","loop_batch_error_limit","sanitizeError","replace","substring"],"sources":["../../src/shared/agent-core.ts"],"sourcesContent":["/**\n * Shared Agent Core — single source of truth for CLI + server agent\n *\n * Pure TypeScript, no runtime-specific APIs (no Deno.env, no process.env, no fs).\n * Both the CLI (Node.js) and server (Fly container) import from here.\n */\n\nimport { getProvider } from \"./constants.js\";\nimport type { CompactableMessage } from \"./compaction.js\";\n\n// ============================================================================\n// TYPES\n// ============================================================================\n\nexport interface LoopCheckResult {\n blocked: boolean;\n reason?: string;\n}\n\nexport interface BailCheckResult {\n shouldBail: boolean;\n message?: string;\n}\n\nexport interface CostInfo {\n inputTokens: number;\n outputTokens: number;\n costUsd: number;\n cacheCreation: number;\n cacheRead: number;\n}\n\n// ============================================================================\n// TOOL CHOICE\n// ============================================================================\n\n/**\n * Controls which tools the model can/must use:\n * - \"auto\": Model decides whether to use tools (default)\n * - \"any\": Model must use at least one tool\n * - \"none\": Model must not use any tools (text-only response)\n * - { type: \"tool\", name: string }: Model must use the specified tool\n */\nexport type ToolChoice = \"auto\" | \"any\" | \"none\" | { type: \"tool\"; name: string };\n\n/**\n * Resolve the effective tool_choice for a given turn.\n *\n * Priority:\n * 1. Explicit override from caller (toolChoice option)\n * 2. Loop detection: if last 3 turns all used the same tool, force \"none\"\n * 3. Keyword detection: if user message mentions a tool name, force that tool\n * 4. Default: \"auto\"\n */\nexport function resolveToolChoice(\n opts: {\n toolChoice?: ToolChoice;\n turnCount: number;\n recentToolUses: string[];\n availableToolNames: string[];\n userMessage: string;\n },\n): ToolChoice {\n // 1. Explicit override always wins\n if (opts.toolChoice !== undefined) return opts.toolChoice;\n\n // 2. Loop detection: if last 3+ turns all used the exact same tool, force text\n if (opts.recentToolUses.length >= 3) {\n const last3 = opts.recentToolUses.slice(-3);\n if (last3[0] === last3[1] && last3[1] === last3[2]) {\n return \"none\";\n }\n }\n\n // 2b. Alternating pattern detection: catch A→B→A→B→A→B death spirals (e.g. read→edit→read→edit)\n if (opts.recentToolUses.length >= 6) {\n const last6 = opts.recentToolUses.slice(-6);\n const isRepeatingPair =\n last6[2] === last6[0] && last6[3] === last6[1] &&\n last6[4] === last6[0] && last6[5] === last6[1];\n if (isRepeatingPair) return \"none\";\n }\n\n // 3. Keyword matching: check if the user message mentions a specific tool name\n // Only on the first turn (avoids false positives on multi-turn conversations)\n if (opts.turnCount === 1 && opts.userMessage && opts.availableToolNames.length > 0) {\n const msgLower = opts.userMessage.toLowerCase();\n for (const toolName of opts.availableToolNames) {\n // Match tool name as a whole word (e.g. \"blender_do\" not \"do\")\n // Only consider tool names >= 4 chars to avoid false positives\n if (toolName.length >= 4 && msgLower.includes(toolName.toLowerCase())) {\n return { type: \"tool\", name: toolName };\n }\n }\n }\n\n // 4. Default\n return \"auto\";\n}\n\nexport interface ContextManagementConfig {\n betas: string[];\n config: { edits: Array<Record<string, unknown>> };\n}\n\n/** Overrides from ai_agent_config.context_config JSONB — all optional, falls back to defaults */\nexport interface ContextManagementOverrides {\n compaction_trigger_tokens?: number;\n compaction_total_budget?: number;\n clear_thinking_keep?: number;\n clear_tool_uses_trigger?: number;\n clear_tool_uses_keep?: number;\n session_cost_budget_usd?: number;\n}\n\n// ============================================================================\n// MODEL-AWARE CONTEXT MANAGEMENT\n// ============================================================================\n\n// These re-export from AGENT_DEFAULTS so there's exactly one place to change.\n// DB context_config always overrides these via resolveAgentLoopConfig().\n\n/** Legacy compaction trigger — used by getCompactionConfig() for non-Anthropic providers. */\nexport const COMPACTION_TRIGGER_TOKENS = 167_000;\n/** Max cumulative tokens before forcing wrap-up */\nexport const COMPACTION_TOTAL_BUDGET = 2_000_000;\n/** Session cost safety cap — DB context_config.session_cost_budget_usd overrides */\nexport const DEFAULT_SESSION_COST_BUDGET_USD = 25.00;\n\n/**\n * Provider-aware compaction configuration.\n * - Anthropic/Bedrock: native server-side compaction via compact_20260112\n * - OpenAI/Gemini: Haiku-based summarization (same instructions, same format)\n */\nexport interface CompactionConfig {\n triggerTokens: number; // When to trigger compaction\n totalBudget: number; // Max cumulative tokens before forced wrap-up\n isNative: boolean; // true = Anthropic handles it server-side, false = we call Haiku\n}\n\nexport function getCompactionConfig(model: string): CompactionConfig {\n const provider = getProvider(model);\n\n switch (provider) {\n case \"gemini\":\n return { triggerTokens: 700_000, totalBudget: 4_000_000, isNative: false };\n case \"openai\":\n return { triggerTokens: 120_000, totalBudget: 2_000_000, isNative: false };\n case \"bedrock\":\n case \"anthropic\":\n default:\n return { triggerTokens: COMPACTION_TRIGGER_TOKENS, totalBudget: COMPACTION_TOTAL_BUDGET, isNative: true };\n }\n}\n\n/**\n * Returns Anthropic beta flags and context_management config for the given model.\n * - Opus 4.6 / Sonnet 4.6: compact at 120K (pause after) + clear thinking + clear tools at 80K/keep 3\n * - All other Claude models: clear thinking + clear tools at 80K/keep 3\n * - Non-Anthropic models (Gemini, OpenAI): no betas, no context management\n */\nexport function getContextManagement(model: string, overrides?: ContextManagementOverrides): ContextManagementConfig {\n // Non-Anthropic models don't use Anthropic betas or context management\n const provider = getProvider(model);\n if (provider === \"gemini\" || provider === \"openai\") {\n return { betas: [], config: { edits: [] } };\n }\n\n const edits: Array<Record<string, unknown>> = [];\n const betas: string[] = [\"context-management-2025-06-27\"];\n\n // Thinking block clearing — must come FIRST in edits array (API requirement).\n // Default: keep 1 thinking turn (matches Claude Code / Anthropic API defaults).\n const clearThinkingKeep = overrides?.clear_thinking_keep ?? 1;\n edits.push({\n type: \"clear_thinking_20251015\",\n keep: { type: \"thinking_turns\", value: clearThinkingKeep },\n });\n\n // Server-side compaction for models that support compact_20260112.\n // Default trigger: 150K tokens (matches Anthropic API default).\n // pause_after_compaction: true enables the loop to preserve recent messages\n // and track compaction count for budget enforcement.\n const supportsCompaction = model.includes(\"opus-4-6\") || model.includes(\"sonnet-4-6\");\n const compactionTrigger = overrides?.compaction_trigger_tokens ?? AGENT_DEFAULTS.compactionTriggerTokens;\n if (supportsCompaction) {\n edits.push({\n type: \"compact_20260112\",\n trigger: { type: \"input_tokens\", value: compactionTrigger },\n pause_after_compaction: true,\n instructions: \"Summarize the conversation preserving: (1) task goals and constraints, (2) files created/modified with paths, (3) decisions made and rationale, (4) errors encountered and resolutions, (5) exact next steps. Be concise but preserve all state needed to continue work without repeating mistakes.\",\n });\n betas.push(\"compact-2026-01-12\");\n }\n\n // Clear tool uses — default: trigger at 100K, keep 3 (matches Anthropic API defaults).\n const clearToolUsesTrigger = overrides?.clear_tool_uses_trigger ?? 100_000;\n const clearToolUsesKeep = overrides?.clear_tool_uses_keep ?? 3;\n edits.push({\n type: \"clear_tool_uses_20250919\",\n trigger: { type: \"input_tokens\", value: clearToolUsesTrigger },\n keep: { type: \"tool_uses\", value: clearToolUsesKeep },\n });\n\n return { betas, config: { edits } };\n}\n\n/**\n * Model-aware max output tokens.\n * Agent config max_tokens takes priority but is capped at model maximum.\n *\n * DEFAULT_OUTPUT_TOKENS is the sensible per-response cap (like Claude Code's ~16K).\n * The full MODEL_MAX is only used when explicitly requested via agentMax.\n */\n// Fallback only when DB agent.max_tokens is null/0. DB value (ai_agent_config.max_tokens) takes priority.\nconst DEFAULT_OUTPUT_TOKENS = 32000;\n\nconst MODEL_MAX_OUTPUT_TOKENS: Record<string, number> = {\n // Anthropic — current models (actual API-enforced limits)\n \"claude-opus-4-6\": 128000, // 128K\n \"claude-sonnet-4-6\": 64000, // 64K (API enforces 64000, not 65536)\n \"claude-haiku-4-5-20251001\": 64000, // 64K\n // Anthropic — legacy models\n \"claude-sonnet-4-5-20250929\": 64000, // 64K (API enforces 64000)\n \"claude-opus-4-5-20251101\": 64000, // 64K\n \"claude-opus-4-1-20250805\": 32768, // 32K\n \"claude-sonnet-4-20250514\": 64000, // 64K\n \"claude-opus-4-20250514\": 32768, // 32K\n \"claude-3-7-sonnet-20250219\": 64000, // 64K\n \"claude-3-haiku-20240307\": 4096, // 4K\n // Bedrock — same limits as direct API\n \"anthropic.claude-sonnet-4-6\": 64000,\n \"us.anthropic.claude-sonnet-4-20250514-v1:0\": 64000,\n \"us.anthropic.claude-sonnet-4-5-20250929-v1:0\": 64000,\n \"us.anthropic.claude-haiku-4-5-20251001-v1:0\": 64000,\n // Google Gemini\n \"gemini-3-pro-preview\": 65536,\n \"gemini-3-flash-preview\": 65536,\n \"gemini-2.5-pro\": 65536,\n \"gemini-2.5-flash\": 65536,\n \"gemini-2.5-flash-lite\": 65536,\n // OpenAI — GPT-5 family: 128K max output, o-series: 100K\n \"gpt-5\": 128000,\n \"gpt-5-mini\": 128000,\n \"gpt-5-nano\": 128000,\n \"o3\": 100000,\n \"o4-mini\": 100000,\n \"gpt-4o\": 16384,\n};\n\nexport function getMaxOutputTokens(model: string, agentMax?: number): number {\n const modelMax = MODEL_MAX_OUTPUT_TOKENS[model] ?? DEFAULT_OUTPUT_TOKENS;\n // If caller explicitly sets agentMax, respect it (capped at model max).\n // Otherwise use sane default — never auto-request 128K output.\n if (agentMax) return Math.min(agentMax, modelMax);\n return Math.min(DEFAULT_OUTPUT_TOKENS, modelMax);\n}\n\n// ============================================================================\n// MULTI-BREAKPOINT PROMPT CACHING\n// ============================================================================\n\n/**\n * Add prompt cache breakpoints to tools and messages.\n * Uses 2 of 4 allowed breakpoints:\n * - Last tool definition\n * - Turn boundary (second-to-last message)\n * System prompt caching is handled by the caller.\n */\nexport function addPromptCaching<\n T extends object = Record<string, unknown>,\n M extends CompactableMessage = CompactableMessage,\n>(\n tools: T[],\n messages: M[]\n): { tools: T[]; messages: M[] } {\n const cachedTools =\n tools.length > 0\n ? [...tools.slice(0, -1), { ...tools[tools.length - 1], cache_control: { type: \"ephemeral\" } } as T]\n : [...tools];\n\n const cachedMessages = [...messages];\n if (cachedMessages.length >= 2) {\n const idx = cachedMessages.length - 2;\n const msg = cachedMessages[idx] as any;\n if (typeof msg.content === \"string\") {\n cachedMessages[idx] = {\n ...msg,\n content: [{ type: \"text\", text: msg.content, cache_control: { type: \"ephemeral\" } }],\n };\n } else if (Array.isArray(msg.content)) {\n const blocks = [...msg.content];\n blocks[blocks.length - 1] = { ...blocks[blocks.length - 1], cache_control: { type: \"ephemeral\" } };\n cachedMessages[idx] = { ...msg, content: blocks };\n }\n }\n\n return { tools: cachedTools, messages: cachedMessages };\n}\n\n// ============================================================================\n// LOOP DETECTION\n// ============================================================================\n\n/** djb2 string hash — fast, deterministic, no dependencies */\nexport function djb2Hash(str: string): string {\n let hash = 5381;\n for (let i = 0; i < str.length; i++) {\n hash = ((hash << 5) + hash + str.charCodeAt(i)) & 0xffffffff;\n }\n return hash.toString(36);\n}\n\nexport interface LoopDetectorConfig {\n identicalCallLimit: number;\n consecutiveErrorLimit: number;\n turnErrorLimit: number;\n window: number;\n sessionToolErrorLimit: number;\n consecutiveFailedTurnLimit: number;\n fileReadLimit: number;\n}\n\nexport class LoopDetector {\n private history: { name: string; inputHash: string }[] = [];\n private consecutiveErrors = new Map<string, number>();\n private turnErrors = 0;\n private turnHadErrors = false;\n\n private sessionErrors = new Map<string, number>();\n private failedStrategies = new Set<string>();\n private consecutiveFailedTurns = 0;\n private totalSessionErrors = 0;\n\n /** Tracks how many times the same file path has been read this session */\n private fileReadCounts = new Map<string, number>();\n\n /** Resolved config — accepts DB overrides, falls back to AGENT_DEFAULTS */\n readonly config: LoopDetectorConfig;\n\n constructor(config?: Partial<LoopDetectorConfig>) {\n this.config = {\n identicalCallLimit: config?.identicalCallLimit ?? AGENT_DEFAULTS.loopIdenticalCallLimit,\n consecutiveErrorLimit: config?.consecutiveErrorLimit ?? AGENT_DEFAULTS.loopConsecutiveErrorLimit,\n turnErrorLimit: config?.turnErrorLimit ?? AGENT_DEFAULTS.loopTurnErrorLimit,\n window: config?.window ?? AGENT_DEFAULTS.loopWindow,\n sessionToolErrorLimit: config?.sessionToolErrorLimit ?? AGENT_DEFAULTS.loopSessionToolErrorLimit,\n consecutiveFailedTurnLimit: config?.consecutiveFailedTurnLimit ?? AGENT_DEFAULTS.loopConsecutiveFailedTurnLimit,\n fileReadLimit: config?.fileReadLimit ?? AGENT_DEFAULTS.loopFileReadLimit,\n };\n }\n\n /** Create a LoopDetector from a ResolvedAgentLoopConfig */\n static fromResolved(resolved: ResolvedAgentLoopConfig): LoopDetector {\n return new LoopDetector({\n identicalCallLimit: resolved.loopIdenticalCallLimit,\n consecutiveErrorLimit: resolved.loopConsecutiveErrorLimit,\n turnErrorLimit: resolved.loopTurnErrorLimit,\n window: resolved.loopWindow,\n sessionToolErrorLimit: resolved.loopSessionToolErrorLimit,\n consecutiveFailedTurnLimit: resolved.loopConsecutiveFailedTurnLimit,\n fileReadLimit: resolved.loopFileReadLimit,\n });\n }\n\n /** Get the error-tracking key for a tool call. Tools with an `action` param\n * are tracked per-action so e.g. voice/speak failing won't block voice/music_compose. */\n private errorKey(name: string, input?: Record<string, unknown>): string {\n if (input && typeof input.action === \"string\") return `${name}:${input.action}`;\n return name;\n }\n\n recordCall(name: string, input: Record<string, unknown>): LoopCheckResult {\n const inputHash = djb2Hash(JSON.stringify({ name, ...input }));\n const eKey = this.errorKey(name, input);\n\n if (this.failedStrategies.has(inputHash)) {\n return {\n blocked: true,\n reason: `Blocked: this exact \"${name}\" call failed in a previous turn. Try a fundamentally different approach.`,\n };\n }\n\n const sessionErrorCount = this.sessionErrors.get(eKey) || 0;\n if (sessionErrorCount >= this.config.sessionToolErrorLimit) {\n return {\n blocked: true,\n reason: `Tool \"${name}\" (action: ${input.action || \"default\"}) has failed ${sessionErrorCount} times this session. Stop using this tool and try a different approach.`,\n };\n }\n\n if (this.turnErrors >= this.config.turnErrorLimit) {\n return {\n blocked: true,\n reason: `${this.turnErrors} errors this turn. Stop and re-assess your approach.`,\n };\n }\n\n const errorCount = this.consecutiveErrors.get(eKey) || 0;\n if (errorCount >= this.config.consecutiveErrorLimit) {\n return {\n blocked: true,\n reason: `Tool \"${name}\" (action: ${input.action || \"default\"}) blocked: failed ${errorCount} times consecutively. Try a different approach or action.`,\n };\n }\n\n const windowSlice = this.history.slice(-this.config.window);\n const identicalCount = windowSlice.filter((h) => h.inputHash === inputHash).length;\n if (identicalCount >= this.config.identicalCallLimit) {\n return {\n blocked: true,\n reason: `Tool \"${name}\" blocked: identical call made ${identicalCount} times. Try different parameters.`,\n };\n }\n\n this.history.push({ name, inputHash });\n if (this.history.length > this.config.window * 2) {\n this.history = this.history.slice(-this.config.window);\n }\n\n return { blocked: false };\n }\n\n /**\n * Track file read frequency — call when the tool is known to be a file read.\n * Blocks re-reading the same path more than FILE_READ_LIMIT times per session.\n */\n trackRead(path: string): LoopCheckResult {\n const readCount = (this.fileReadCounts.get(path) || 0) + 1;\n this.fileReadCounts.set(path, readCount);\n if (readCount > this.config.fileReadLimit) {\n return {\n blocked: true,\n reason: `File \"${path}\" already read ${readCount - 1} times this session. Use the content from a previous read instead of re-reading.`,\n };\n }\n return { blocked: false };\n }\n\n /**\n * Record a tool execution result.\n * @param transient - If true, the failure is transient (timeout, rate limit)\n * and should NOT be added to failedStrategies. Transient failures are\n * retryable with the exact same inputs — e.g., a task_output poll that\n * timed out because the task is still running.\n */\n recordResult(name: string, success: boolean, input?: Record<string, unknown>, transient?: boolean): void {\n const eKey = this.errorKey(name, input);\n if (success) {\n this.consecutiveErrors.delete(eKey);\n } else {\n const current = this.consecutiveErrors.get(eKey) || 0;\n this.consecutiveErrors.set(eKey, current + 1);\n this.turnErrors++;\n this.turnHadErrors = true;\n\n const sessionCount = this.sessionErrors.get(eKey) || 0;\n this.sessionErrors.set(eKey, sessionCount + 1);\n this.totalSessionErrors++;\n\n // Only add to failedStrategies for non-transient errors.\n // Transient errors (timeouts, rate limits) should be retryable with\n // the exact same inputs — blocking them creates a deadlock for polling\n // tools like task_output where the input (task_id) never changes.\n if (input && !transient) {\n const inputHash = djb2Hash(JSON.stringify({ name, ...input }));\n this.failedStrategies.add(inputHash);\n if (this.failedStrategies.size > 200) {\n const arr = Array.from(this.failedStrategies);\n this.failedStrategies = new Set(arr.slice(-100));\n }\n }\n }\n }\n\n endTurn(): BailCheckResult {\n if (this.turnHadErrors) {\n this.consecutiveFailedTurns++;\n } else {\n this.consecutiveFailedTurns = 0;\n // A clean turn means the agent has recovered — unblock previously failed strategies\n // so it can retry calls that failed due to bad params (e.g., wrong UUID format)\n this.failedStrategies.clear();\n // Decay session error counts on clean turns so tools aren't permanently blocked.\n // Each clean turn halves all session error counts, allowing recovery from\n // transient issues while still blocking persistently broken tools.\n if (this.sessionErrors.size > 0) {\n for (const [key, count] of this.sessionErrors) {\n const decayed = Math.floor(count / 2);\n if (decayed <= 0) {\n this.sessionErrors.delete(key);\n } else {\n this.sessionErrors.set(key, decayed);\n }\n }\n }\n }\n\n // Cap consecutiveErrors so a single bad batch (parallel Promise.all) can't\n // permanently brick a tool. Without this, N parallel failures push\n // consecutiveErrors to N, which exceeds consecutiveErrorLimit and creates\n // a deadlock: the tool is blocked because it failed, but can't succeed to\n // unblock itself because it's blocked. Capping to (limit - 1) gives the\n // tool one retry on the next turn. Only permanently block after multiple\n // consecutive failed turns (handled by the bail-out check below).\n if (this.consecutiveFailedTurns < this.config.consecutiveFailedTurnLimit) {\n for (const [key, count] of this.consecutiveErrors) {\n if (count >= this.config.consecutiveErrorLimit) {\n this.consecutiveErrors.set(key, this.config.consecutiveErrorLimit - 1);\n }\n }\n }\n\n // Reset turn-level counters so the NEXT dispatch batch starts fresh.\n // Session-level counters (sessionErrors, consecutiveFailedTurns) persist.\n this.turnErrors = 0;\n this.turnHadErrors = false;\n\n if (this.consecutiveFailedTurns >= this.config.consecutiveFailedTurnLimit) {\n return {\n shouldBail: true,\n message: `You have had errors in ${this.consecutiveFailedTurns} consecutive turns (${this.totalSessionErrors} total errors). Your approach is not working. STOP and explain to the user what's failing.`,\n };\n }\n\n return { shouldBail: false };\n }\n\n resetTurn(): void {\n // Only reset per-turn counters — history and consecutiveErrors persist\n // for cross-turn detection. The full reset() clears everything for new sessions.\n this.turnErrors = 0;\n this.turnHadErrors = false;\n }\n\n reset(): void {\n this.resetTurn();\n this.history = [];\n this.consecutiveErrors.clear();\n this.sessionErrors.clear();\n this.failedStrategies.clear();\n this.fileReadCounts.clear();\n this.consecutiveFailedTurns = 0;\n this.totalSessionErrors = 0;\n }\n\n getSessionStats(): { totalErrors: number; failedStrategies: number; consecutiveFailedTurns: number } {\n return {\n totalErrors: this.totalSessionErrors,\n failedStrategies: this.failedStrategies.size,\n consecutiveFailedTurns: this.consecutiveFailedTurns,\n };\n }\n}\n\n// ============================================================================\n// EXTENDED THINKING\n// ============================================================================\n\nexport interface ThinkingConfig {\n type: \"enabled\" | \"disabled\" | \"adaptive\";\n budget_tokens?: number;\n}\n\n/**\n * Returns the thinking configuration and required beta string for the given model.\n * - Opus 4.6: adaptive thinking (no budget needed)\n * - Sonnet/Haiku: enabled with 10000 token budget\n * - budget_tokens must be strictly < max_tokens\n */\nexport function getThinkingConfig(model: string, enabled: boolean): {\n thinking: ThinkingConfig;\n beta: string;\n} {\n if (!enabled) {\n return { thinking: { type: \"disabled\" }, beta: \"\" };\n }\n\n const provider = getProvider(model);\n\n // Gemini models: thinking is always-on for 2.5+/3.x — signal pass-through\n if (provider === \"gemini\") {\n return { thinking: { type: \"enabled\" }, beta: \"\" };\n }\n\n // OpenAI models: reasoning models (o-series) have built-in reasoning, GPT models don't support thinking\n if (provider === \"openai\") {\n const isReasoning = /^o\\d/.test(model);\n return { thinking: { type: isReasoning ? \"enabled\" : \"disabled\" }, beta: \"\" };\n }\n\n if (model.includes(\"opus-4-6\") || model.includes(\"sonnet-4-6\")) {\n return {\n thinking: { type: \"adaptive\" },\n beta: \"adaptive-thinking-2026-01-28\",\n };\n }\n\n // Sonnet 4.5/4.0 / Haiku: fixed budget (matches Claude Code's 31,999 default)\n return {\n thinking: { type: \"enabled\", budget_tokens: 31_999 },\n beta: \"interleaved-thinking-2025-05-14\",\n };\n}\n\n// ============================================================================\n// COST TRACKING\n// ============================================================================\n\nexport const MODEL_PRICING: Record<string, { inputPer1M: number; outputPer1M: number; thinkingPer1M?: number }> = {\n // Anthropic direct — Claude 4.x\n \"claude-sonnet-4-6\": { inputPer1M: 3.0, outputPer1M: 15.0, thinkingPer1M: 15.0 },\n \"claude-sonnet-4-20250514\": { inputPer1M: 3.0, outputPer1M: 15.0, thinkingPer1M: 15.0 },\n \"claude-sonnet-4-5-20250929\": { inputPer1M: 3.0, outputPer1M: 15.0, thinkingPer1M: 15.0 },\n \"claude-opus-4-6\": { inputPer1M: 5.0, outputPer1M: 25.0, thinkingPer1M: 25.0 },\n \"claude-opus-4-20250514\": { inputPer1M: 5.0, outputPer1M: 25.0, thinkingPer1M: 25.0 },\n \"claude-opus-4-5-20251101\": { inputPer1M: 5.0, outputPer1M: 25.0, thinkingPer1M: 25.0 },\n \"claude-haiku-4-20250514\": { inputPer1M: 1.0, outputPer1M: 5.0, thinkingPer1M: 5.0 },\n \"claude-haiku-4-5-20251001\": { inputPer1M: 1.0, outputPer1M: 5.0, thinkingPer1M: 5.0 },\n // Anthropic direct — Claude 3.5\n \"claude-3-5-sonnet-20241022\": { inputPer1M: 3.0, outputPer1M: 15.0 },\n \"claude-3-5-haiku-20241022\": { inputPer1M: 0.80, outputPer1M: 4.0 },\n // Bedrock — Claude 4.x\n \"anthropic.claude-sonnet-4-6\": { inputPer1M: 3.0, outputPer1M: 15.0, thinkingPer1M: 15.0 },\n \"us.anthropic.claude-sonnet-4-20250514-v1:0\": { inputPer1M: 3.0, outputPer1M: 15.0, thinkingPer1M: 15.0 },\n \"us.anthropic.claude-sonnet-4-5-20250929-v1:0\": { inputPer1M: 3.0, outputPer1M: 15.0, thinkingPer1M: 15.0 },\n \"us.anthropic.claude-haiku-4-5-20251001-v1:0\": { inputPer1M: 1.0, outputPer1M: 5.0, thinkingPer1M: 5.0 },\n // Bedrock — Claude 3.5\n \"us.anthropic.claude-3-5-haiku-20241022-v1:0\": { inputPer1M: 0.80, outputPer1M: 4.0 },\n // Bedrock — Llama & Nova\n \"us.meta.llama3-1-70b-instruct-v1:0\": { inputPer1M: 0.72, outputPer1M: 0.72 },\n \"us.amazon.nova-pro-v1:0\": { inputPer1M: 0.80, outputPer1M: 3.20 },\n // Gemini (thinking tokens are cheaper than output)\n \"gemini-3-pro-preview\": { inputPer1M: 1.25, outputPer1M: 10.0, thinkingPer1M: 2.50 },\n \"gemini-3-flash-preview\": { inputPer1M: 0.15, outputPer1M: 0.60, thinkingPer1M: 0.15 },\n \"gemini-2.5-pro\": { inputPer1M: 1.25, outputPer1M: 10.0, thinkingPer1M: 2.50 },\n \"gemini-2.5-flash\": { inputPer1M: 0.15, outputPer1M: 0.60, thinkingPer1M: 0.15 },\n \"gemini-2.5-flash-lite\": { inputPer1M: 0.075, outputPer1M: 0.30, thinkingPer1M: 0.075 },\n \"gemini-2.0-flash\": { inputPer1M: 0.10, outputPer1M: 0.40 },\n \"gemini-2.0-flash-lite\": { inputPer1M: 0.075, outputPer1M: 0.30 },\n // OpenAI — GPT\n \"gpt-5\": { inputPer1M: 1.25, outputPer1M: 10.0 },\n \"gpt-5-mini\": { inputPer1M: 0.25, outputPer1M: 2.0 },\n \"gpt-5-nano\": { inputPer1M: 0.05, outputPer1M: 0.40 },\n \"gpt-4o\": { inputPer1M: 2.50, outputPer1M: 10.0 },\n \"gpt-4o-mini\": { inputPer1M: 0.15, outputPer1M: 0.60 },\n \"gpt-4-turbo\": { inputPer1M: 10.0, outputPer1M: 30.0 },\n // OpenAI — reasoning models\n \"o1\": { inputPer1M: 15.0, outputPer1M: 60.0, thinkingPer1M: 60.0 },\n \"o1-mini\": { inputPer1M: 3.0, outputPer1M: 12.0, thinkingPer1M: 12.0 },\n \"o3\": { inputPer1M: 2.0, outputPer1M: 8.0, thinkingPer1M: 8.0 },\n \"o3-mini\": { inputPer1M: 1.10, outputPer1M: 4.40, thinkingPer1M: 4.40 },\n \"o4-mini\": { inputPer1M: 1.10, outputPer1M: 4.40, thinkingPer1M: 4.40 },\n};\n\n/**\n * Emit graduated cost warnings at 25%, 50%, 75% thresholds.\n * Single source of truth — replaces copy-pasted blocks in server + CLI.\n */\nexport function emitCostWarningIfNeeded(\n sessionCostUsd: number,\n maxCostUsd: number,\n costWarningsEmitted: Set<number>,\n onText?: (text: string) => void,\n): void {\n if (!isFinite(maxCostUsd) || !onText) return;\n for (const pct of [25, 50, 75]) {\n if (!costWarningsEmitted.has(pct) && sessionCostUsd >= maxCostUsd * (pct / 100)) {\n costWarningsEmitted.add(pct);\n onText(`\\n[Cost warning: ${pct}% of budget used ($${sessionCostUsd.toFixed(2)}/$${maxCostUsd.toFixed(2)}).${pct >= 75 ? \" Wrap up soon.\" : \"\"}]`);\n }\n }\n}\n\nexport function estimateCostUsd(\n inputTokens: number,\n outputTokens: number,\n model: string,\n thinkingTokens = 0,\n cacheReadTokens = 0,\n cacheCreationTokens = 0,\n): number {\n // Exact match first, then find a pricing key that is a prefix of the model ID\n const pricing = MODEL_PRICING[model]\n || MODEL_PRICING[Object.keys(MODEL_PRICING).find((k) => model.startsWith(k)) ?? \"\"]\n || MODEL_PRICING[\"claude-sonnet-4-6\"];\n const thinkingRate = pricing.thinkingPer1M || pricing.outputPer1M;\n const inputRate = pricing.inputPer1M;\n\n // Base cost\n let cost = (inputTokens / 1_000_000) * inputRate\n + (outputTokens / 1_000_000) * pricing.outputPer1M\n + (thinkingTokens / 1_000_000) * thinkingRate;\n\n // Cache pricing — subtract savings for cached tokens\n // Anthropic/Bedrock: cache reads 90% cheaper, cache creation 25% surcharge\n // OpenAI: cache reads 50% cheaper, no creation surcharge\n // Gemini: cache reads 75% cheaper\n if (cacheReadTokens > 0 || cacheCreationTokens > 0) {\n const provider = getProvider(model);\n if (provider === \"anthropic\" || provider === \"bedrock\") {\n cost -= (cacheReadTokens / 1_000_000) * inputRate * 0.9;\n cost += (cacheCreationTokens / 1_000_000) * inputRate * 0.25;\n } else if (provider === \"openai\") {\n cost -= (cacheReadTokens / 1_000_000) * inputRate * 0.5;\n } else if (provider === \"gemini\") {\n cost -= (cacheReadTokens / 1_000_000) * inputRate * 0.75;\n }\n }\n\n return cost;\n}\n\n// ============================================================================\n// MODEL ROUTING BY TASK COMPLEXITY\n// ============================================================================\n\n/**\n * Route to cheaper model when the task is simple enough.\n * Returns the model to actually use.\n */\nexport function routeModel(message: string, requestedModel: string, forceModel?: boolean): string {\n // If user explicitly picked a model, respect it\n if (forceModel) return requestedModel;\n\n // Estimate token count (rough: 1 token ~= 4 chars)\n const estimatedTokens = Math.ceil(message.length / 4);\n\n // Simple queries → Haiku (30x cheaper than Opus)\n const simplePatterns = /^(what|who|when|where|show|list|get|find|look ?up|check)\\b/i;\n const complexPatterns = /\\b(analyze|implement|refactor|design|architect|debug|explain why|compare|evaluate|write|create|build|fix)\\b/i;\n\n if (estimatedTokens < 50 && simplePatterns.test(message) && !complexPatterns.test(message)) {\n return \"claude-haiku-4-5-20251001\";\n }\n\n // Medium queries → Sonnet\n if (estimatedTokens < 200 && !complexPatterns.test(message)) {\n return \"claude-sonnet-4-5-20250929\";\n }\n\n // Complex → honor requested model\n return requestedModel;\n}\n\n// ============================================================================\n// ERROR CATEGORIZATION\n// ============================================================================\n\nexport type ErrorCategory =\n | \"RATE_LIMIT\"\n | \"TIMEOUT\"\n | \"AUTH\"\n | \"MALFORMED\"\n | \"PROVIDER_DOWN\"\n | \"NETWORK\"\n | \"UNKNOWN\";\n\nexport function categorizeError(err: unknown): { category: ErrorCategory; retryable: boolean } {\n const e = err as any;\n const status = e?.status || e?.statusCode;\n const msg = String(e?.message || \"\").toLowerCase();\n\n if (status === 429 || msg.includes(\"rate limit\")) {\n return { category: \"RATE_LIMIT\", retryable: true };\n }\n if (status === 401 || status === 403 || msg.includes(\"unauthorized\") || msg.includes(\"forbidden\") || msg.includes(\"invalid api key\")) {\n return { category: \"AUTH\", retryable: false };\n }\n if (status === 400 || msg.includes(\"malformed\") || msg.includes(\"invalid\") || msg.includes(\"validation\")) {\n return { category: \"MALFORMED\", retryable: false };\n }\n if (status === 500 || status === 502 || status === 503 || status === 529 || msg.includes(\"overloaded\") || msg.includes(\"internal server error\")) {\n return { category: \"PROVIDER_DOWN\", retryable: true };\n }\n if (msg.includes(\"timeout\") || msg.includes(\"timed out\") || msg.includes(\"deadline\") || msg.includes(\"econnreset\") || msg.includes(\"stream stalled\")) {\n return { category: \"TIMEOUT\", retryable: true };\n }\n if (msg.includes(\"econnrefused\") || msg.includes(\"enetunreach\") || msg.includes(\"enotfound\") || msg.includes(\"fetch failed\") || msg.includes(\"network\")) {\n return { category: \"NETWORK\", retryable: true };\n }\n return { category: \"UNKNOWN\", retryable: false };\n}\n\n// ============================================================================\n// RETRY LOGIC\n// ============================================================================\n\nexport function isRetryableError(err: unknown): boolean {\n return categorizeError(err).retryable;\n}\n\n// ============================================================================\n// UTILITY — model demotion, sanitize errors\n// ============================================================================\n\n/**\n * Demote subagent model requests — single source of truth for server + CLI.\n * - explore/research: always haiku\n * - opus: demoted to sonnet\n * - sonnet: kept for plan, demoted to haiku for others\n * - default/undefined: haiku\n */\n/**\n * Resolve subagent model based on agent type and request.\n *\n * Claude Code behavior: general-purpose and plan subagents inherit the parent\n * model (they do real work / need full reasoning). Only explore and research\n * are demoted to haiku (fast, focused tasks).\n */\nexport function demoteSubagentModel(\n requested: string | undefined,\n agentType?: string,\n): \"haiku\" | \"sonnet\" | \"opus\" {\n // Fast, focused agent types always use haiku regardless of request\n if (agentType === \"explore\" || agentType === \"research\") return \"haiku\";\n\n // General-purpose and plan inherit the requested model (Claude Code parity)\n if (agentType === \"general-purpose\" || agentType === \"plan\") {\n if (requested === \"opus\") return \"opus\";\n if (requested === \"sonnet\") return \"sonnet\";\n return \"sonnet\"; // default to sonnet if no model specified\n }\n\n // Unknown/custom agent types — default to haiku for safety\n if (!requested) return \"haiku\";\n return requested === \"opus\" ? \"sonnet\" : requested === \"sonnet\" ? \"sonnet\" : \"haiku\";\n}\n\n// ============================================================================\n// AGENT LOOP CONFIG RESOLVER — single source of truth for all call paths\n// ============================================================================\n\nexport type CallPath = \"sse\" | \"workflow\" | \"channel\";\n\n/**\n * EMERGENCY FALLBACK DEFAULTS — used ONLY when ai_agent_config DB is unreachable.\n *\n * The SINGLE SOURCE OF TRUTH is the ai_agent_config table (Supabase), specifically\n * the row for Whale Code (id: 72d7aaa8-2e8b-48a0-a38d-f332f69600bb).\n * All behavioral knobs are stored in `context_config` JSONB.\n *\n * These values MUST mirror what's in the DB. If you change a value, update the DB\n * first (via Supabase dashboard or migration), then mirror it here.\n *\n * DB → resolveAgentLoopConfig() → code reads resolved values.\n * AGENT_DEFAULTS → code reads ONLY if DB fetch returns null.\n */\nexport const AGENT_DEFAULTS = {\n // Mirrors ai_agent_config.max_tool_calls / temperature\n maxTurns: 0, // 0 = no limit (agent self-regulates via end_turn, Claude Code parity)\n temperature: 1.0,\n // Mirrors ai_agent_config.context_config JSONB fields\n maxConcurrentTools: 7,\n enableDelegation: true,\n maxDurationMs: 900_000,\n maxDurationMsWorkflow: 120_000,\n enableModelRouting: true,\n subagentMaxTokens: 32000,\n subagentMaxTurns: 0, // 0 = no limit (agent self-regulates via end_turn, Claude Code parity)\n subagentTemperature: 1.0,\n subagentMaxRetries: 2, // 1 retry (2 total attempts) — proxy already handles auth refresh, avoid double backoff\n maxContinuations: 10,\n subagentMaxContinuations: 5,\n maxMessageChars: 100_000,\n maxHistoryChars: 400_000,\n maxToolResultChars: 2048,\n compactionTriggerTokens: 167_000,\n compactionTotalBudget: 2_000_000,\n sessionCostBudgetUsd: 25.00,\n // Team / teammate behavioral defaults\n teammateMaxTotalTurns: 0, // 0 = no limit (teammate self-regulates, Claude Code parity)\n teamTimeoutMs: 600_000, // 10 min global safety cap — prevents runaway team runs (DB overridable)\n workerStallMs: 90_000, // 90s no-message stall detection (API timeout is 90s, so 90s silence = truly stalled)\n teamReviewMaxTokens: 1024, // Max tokens for team review synthesis\n // Infrastructure timeouts for teammates (DB overridable, not hardcoded)\n apiTimeoutMs: 90_000, // 90s timeout on proxy/API fetch calls\n toolTimeoutMs: 60_000, // 60s timeout on individual tool execution\n // Per-tool-result truncation cap (different from maxToolResultChars which is for preCompact)\n toolResultTruncateChars: 30_000, // Match SAFETY_MAX_CHARS from tool-dispatch.ts — 500K was blowing context windows\n // Loop detector thresholds (DB overridable via context_config)\n loopIdenticalCallLimit: 4,\n loopConsecutiveErrorLimit: 3,\n loopTurnErrorLimit: 5,\n loopWindow: 20,\n loopSessionToolErrorLimit: 10,\n loopConsecutiveFailedTurnLimit: 3,\n loopFileReadLimit: 3,\n loopBatchErrorLimit: 3, // Max errors from single parallel batch before abort\n} as const;\n\n/** Context config shape from ai_agent_config.context_config JSONB */\nexport interface AgentContextConfig {\n includeLocations?: boolean;\n locationIds?: string[];\n includeCustomers?: boolean;\n customerSegments?: string[];\n max_history_chars?: number;\n max_tool_result_chars?: number;\n max_message_chars?: number;\n compaction_trigger_tokens?: number;\n compaction_total_budget?: number;\n clear_thinking_keep?: number;\n clear_tool_uses_trigger?: number;\n clear_tool_uses_keep?: number;\n session_cost_budget_usd?: number;\n max_concurrent_tools?: number;\n enable_delegation?: boolean;\n max_duration_ms?: number;\n enable_model_routing?: boolean;\n subagent_max_tokens?: number;\n subagent_max_turns?: number;\n subagent_temperature?: number;\n subagent_max_retries?: number;\n max_continuations?: number;\n subagent_max_continuations?: number;\n // Team / teammate\n teammate_max_total_turns?: number;\n team_timeout_ms?: number;\n worker_stall_ms?: number;\n team_review_max_tokens?: number;\n // Infrastructure timeouts for teammates\n api_timeout_ms?: number;\n tool_timeout_ms?: number;\n // Per-tool-result truncation cap\n tool_result_truncate_chars?: number;\n // Loop detector thresholds\n loop_identical_call_limit?: number;\n loop_consecutive_error_limit?: number;\n loop_turn_error_limit?: number;\n loop_window?: number;\n loop_session_tool_error_limit?: number;\n loop_consecutive_failed_turn_limit?: number;\n loop_file_read_limit?: number;\n loop_batch_error_limit?: number;\n}\n\nexport interface ResolvedAgentLoopConfig {\n maxTurns: number;\n temperature: number;\n maxTokens: number;\n maxConcurrentTools: number;\n enableDelegation: boolean;\n maxDurationMs: number;\n enableModelRouting: boolean;\n maxMessageChars: number;\n maxHistoryChars: number;\n contextOverrides: ContextManagementOverrides;\n subagentMaxTokens: number;\n subagentMaxTurns: number;\n subagentTemperature: number;\n maxContinuations: number;\n subagentMaxContinuations: number;\n subagentMaxRetries: number;\n maxToolResultChars: number;\n // Team / teammate\n teammateMaxTotalTurns: number;\n teamTimeoutMs: number;\n workerStallMs: number;\n teamReviewMaxTokens: number;\n // Infrastructure timeouts for teammates\n apiTimeoutMs: number;\n toolTimeoutMs: number;\n // Per-tool-result truncation cap\n toolResultTruncateChars: number;\n // Loop detector thresholds\n loopIdenticalCallLimit: number;\n loopConsecutiveErrorLimit: number;\n loopTurnErrorLimit: number;\n loopWindow: number;\n loopSessionToolErrorLimit: number;\n loopConsecutiveFailedTurnLimit: number;\n loopFileReadLimit: number;\n loopBatchErrorLimit: number;\n /** Which fields fell back to AGENT_DEFAULTS (transparency for logging) */\n defaultsUsed: string[];\n}\n\n/**\n * Resolve all agent loop behavioral knobs from DB config.\n * All 3 call paths MUST use this — structurally prevents hardcoded constants.\n *\n * @param agent - Agent config (DB row or subset)\n * @param callPath - Which call path is invoking (\"sse\" | \"workflow\" | \"channel\")\n * @param workflowMaxTurns - Optional cap from workflow step config (workflow path only)\n */\nexport function resolveAgentLoopConfig(\n agent: {\n max_tool_calls: number;\n temperature: number;\n max_tokens: number;\n model: string;\n context_config: AgentContextConfig | null;\n },\n callPath: CallPath,\n workflowMaxTurns?: number,\n): ResolvedAgentLoopConfig {\n const cc = agent.context_config;\n const defaultsUsed: string[] = [];\n\n function resolve<T>(dbValue: T | undefined | null, defaultValue: T, name: string): T {\n if (dbValue != null) return dbValue;\n defaultsUsed.push(name);\n return defaultValue;\n }\n\n // Core agent behavior\n const agentMaxTurns = agent.max_tool_calls || AGENT_DEFAULTS.maxTurns;\n if (!agent.max_tool_calls) defaultsUsed.push(\"maxTurns\");\n const temperature = agent.temperature ?? AGENT_DEFAULTS.temperature;\n if (agent.temperature == null) defaultsUsed.push(\"temperature\");\n const maxTokens = getMaxOutputTokens(agent.model || \"claude-sonnet-4-6\", agent.max_tokens);\n if (!agent.max_tokens) defaultsUsed.push(\"maxTokens\");\n\n // Call-path-specific duration defaults\n const durationDefault = callPath === \"sse\"\n ? AGENT_DEFAULTS.maxDurationMs\n : AGENT_DEFAULTS.maxDurationMsWorkflow;\n\n // Call-path-specific turn caps (0 = no limit, Claude Code parity)\n let maxTurns = agentMaxTurns;\n if (maxTurns > 0) {\n if (callPath === \"channel\") maxTurns = Math.min(agentMaxTurns, 15);\n if (callPath === \"workflow\" && workflowMaxTurns != null) {\n maxTurns = Math.min(agentMaxTurns, workflowMaxTurns);\n }\n }\n\n return {\n maxTurns,\n temperature,\n maxTokens,\n maxConcurrentTools: resolve(cc?.max_concurrent_tools, AGENT_DEFAULTS.maxConcurrentTools, \"maxConcurrentTools\"),\n enableDelegation: resolve(cc?.enable_delegation, AGENT_DEFAULTS.enableDelegation, \"enableDelegation\"),\n maxDurationMs: resolve(cc?.max_duration_ms, durationDefault, \"maxDurationMs\"),\n enableModelRouting: resolve(cc?.enable_model_routing, AGENT_DEFAULTS.enableModelRouting, \"enableModelRouting\"),\n maxMessageChars: resolve(cc?.max_message_chars, AGENT_DEFAULTS.maxMessageChars, \"maxMessageChars\"),\n maxHistoryChars: resolve(cc?.max_history_chars, AGENT_DEFAULTS.maxHistoryChars, \"maxHistoryChars\"),\n contextOverrides: {\n compaction_trigger_tokens: cc?.compaction_trigger_tokens ?? undefined,\n compaction_total_budget: cc?.compaction_total_budget ?? undefined,\n clear_thinking_keep: cc?.clear_thinking_keep ?? undefined,\n clear_tool_uses_trigger: cc?.clear_tool_uses_trigger ?? undefined,\n clear_tool_uses_keep: cc?.clear_tool_uses_keep ?? undefined,\n session_cost_budget_usd: cc?.session_cost_budget_usd ?? undefined,\n },\n subagentMaxTokens: resolve(cc?.subagent_max_tokens, AGENT_DEFAULTS.subagentMaxTokens, \"subagentMaxTokens\"),\n subagentMaxTurns: resolve(cc?.subagent_max_turns, AGENT_DEFAULTS.subagentMaxTurns, \"subagentMaxTurns\"),\n subagentTemperature: resolve(cc?.subagent_temperature, AGENT_DEFAULTS.subagentTemperature, \"subagentTemperature\"),\n maxContinuations: resolve(cc?.max_continuations, AGENT_DEFAULTS.maxContinuations, \"maxContinuations\"),\n subagentMaxContinuations: resolve(cc?.subagent_max_continuations, AGENT_DEFAULTS.subagentMaxContinuations, \"subagentMaxContinuations\"),\n subagentMaxRetries: resolve(cc?.subagent_max_retries, AGENT_DEFAULTS.subagentMaxRetries, \"subagentMaxRetries\"),\n maxToolResultChars: resolve(cc?.max_tool_result_chars, AGENT_DEFAULTS.maxToolResultChars, \"maxToolResultChars\"),\n teammateMaxTotalTurns: resolve(cc?.teammate_max_total_turns, AGENT_DEFAULTS.teammateMaxTotalTurns, \"teammateMaxTotalTurns\"),\n teamTimeoutMs: resolve(cc?.team_timeout_ms, AGENT_DEFAULTS.teamTimeoutMs, \"teamTimeoutMs\"),\n workerStallMs: resolve(cc?.worker_stall_ms, AGENT_DEFAULTS.workerStallMs, \"workerStallMs\"),\n teamReviewMaxTokens: resolve(cc?.team_review_max_tokens, AGENT_DEFAULTS.teamReviewMaxTokens, \"teamReviewMaxTokens\"),\n apiTimeoutMs: resolve(cc?.api_timeout_ms, AGENT_DEFAULTS.apiTimeoutMs, \"apiTimeoutMs\"),\n toolTimeoutMs: resolve(cc?.tool_timeout_ms, AGENT_DEFAULTS.toolTimeoutMs, \"toolTimeoutMs\"),\n toolResultTruncateChars: resolve(cc?.tool_result_truncate_chars, AGENT_DEFAULTS.toolResultTruncateChars, \"toolResultTruncateChars\"),\n // Loop detector thresholds\n loopIdenticalCallLimit: resolve(cc?.loop_identical_call_limit, AGENT_DEFAULTS.loopIdenticalCallLimit, \"loopIdenticalCallLimit\"),\n loopConsecutiveErrorLimit: resolve(cc?.loop_consecutive_error_limit, AGENT_DEFAULTS.loopConsecutiveErrorLimit, \"loopConsecutiveErrorLimit\"),\n loopTurnErrorLimit: resolve(cc?.loop_turn_error_limit, AGENT_DEFAULTS.loopTurnErrorLimit, \"loopTurnErrorLimit\"),\n loopWindow: resolve(cc?.loop_window, AGENT_DEFAULTS.loopWindow, \"loopWindow\"),\n loopSessionToolErrorLimit: resolve(cc?.loop_session_tool_error_limit, AGENT_DEFAULTS.loopSessionToolErrorLimit, \"loopSessionToolErrorLimit\"),\n loopConsecutiveFailedTurnLimit: resolve(cc?.loop_consecutive_failed_turn_limit, AGENT_DEFAULTS.loopConsecutiveFailedTurnLimit, \"loopConsecutiveFailedTurnLimit\"),\n loopFileReadLimit: resolve(cc?.loop_file_read_limit, AGENT_DEFAULTS.loopFileReadLimit, \"loopFileReadLimit\"),\n loopBatchErrorLimit: resolve(cc?.loop_batch_error_limit, AGENT_DEFAULTS.loopBatchErrorLimit, \"loopBatchErrorLimit\"),\n defaultsUsed,\n };\n}\n\nexport function sanitizeError(err: unknown): string {\n const msg = String(err);\n return msg\n .replace(/sk-[a-zA-Z0-9_-]+/g, \"sk-***\")\n .replace(/AIzaSy[a-zA-Z0-9_-]+/g, \"AIzaSy***\")\n .replace(/AKIA[A-Z0-9]{16}/g, \"AKIA***\")\n .replace(/key[=:]\\s*[\"']?[a-zA-Z0-9_-]{20,}[\"']?/gi, \"key=***\")\n .replace(/password[=:]\\s*[\"']?[^\\s\"']+[\"']?/gi, \"password=***\")\n .replace(/\\n\\s+at\\s+.*/g, \"\")\n .substring(0, 500);\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAASA,WAAW,QAAQ,gBAAgB;;AAG5C;AACA;AACA;;AAoBA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,iBAAiBA,CAC/BC,IAMC,EACW;EACZ;EACA,IAAIA,IAAI,CAACC,UAAU,KAAKC,SAAS,EAAE,OAAOF,IAAI,CAACC,UAAU;;EAEzD;EACA,IAAID,IAAI,CAACG,cAAc,CAACC,MAAM,IAAI,CAAC,EAAE;IACnC,MAAMC,KAAK,GAAGL,IAAI,CAACG,cAAc,CAACG,KAAK,CAAC,CAAC,CAAC,CAAC;IAC3C,IAAID,KAAK,CAAC,CAAC,CAAC,KAAKA,KAAK,CAAC,CAAC,CAAC,IAAIA,KAAK,CAAC,CAAC,CAAC,KAAKA,KAAK,CAAC,CAAC,CAAC,EAAE;MAClD,OAAO,MAAM;IACf;EACF;;EAEA;EACA,IAAIL,IAAI,CAACG,cAAc,CAACC,MAAM,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,SAAS,CAAC,CAAC,EAAE,GAAG,CAAC;AACtB","ignoreList":[]}
@@ -1,7 +1,2 @@
1
- /**
2
- * Typed Anthropic SSE Events — replaces `as any` casts in stream processing.
3
- *
4
- * Based on Anthropic API streaming specification.
5
- * Pure TypeScript, no runtime dependencies.
6
- */
7
1
  export {};
2
+ //# sourceMappingURL=anthropic-types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"anthropic-types.js","names":[],"sources":["../../src/shared/anthropic-types.ts"],"sourcesContent":["/**\n * Typed Anthropic SSE Events — replaces `as any` casts in stream processing.\n *\n * Based on Anthropic API streaming specification.\n * Pure TypeScript, no runtime dependencies.\n */\n\n// ============================================================================\n// CONTENT BLOCK TYPES\n// ============================================================================\n\nexport interface TextContentBlock {\n type: \"text\";\n text: string;\n}\n\nexport interface ToolUseContentBlock {\n type: \"tool_use\";\n id: string;\n name: string;\n}\n\nexport interface ThinkingContentBlock {\n type: \"thinking\";\n}\n\nexport interface CompactionContentBlock {\n type: \"compaction\";\n}\n\nexport interface CiteContentBlock {\n type: \"cite\";\n cited_text: string;\n document_index: number;\n document_title?: string;\n start_char_index: number;\n end_char_index: number;\n}\n\nexport type ContentBlock =\n | TextContentBlock\n | ToolUseContentBlock\n | ThinkingContentBlock\n | CompactionContentBlock\n | CiteContentBlock;\n\n// ============================================================================\n// DELTA TYPES\n// ============================================================================\n\nexport interface TextDelta {\n type: \"text_delta\";\n text: string;\n}\n\nexport interface InputJsonDelta {\n type: \"input_json_delta\";\n partial_json: string;\n}\n\nexport interface ThinkingDelta {\n type: \"thinking_delta\";\n thinking: string;\n}\n\nexport interface SignatureDelta {\n type: \"signature_delta\";\n signature: string;\n}\n\nexport interface CompactionDelta {\n type: \"compaction_delta\";\n content: string;\n}\n\nexport interface CiteDelta {\n type: \"cite_delta\";\n cited_text?: string;\n document_index?: number;\n document_title?: string;\n start_char_index?: number;\n end_char_index?: number;\n}\n\nexport type ContentBlockDelta =\n | TextDelta\n | InputJsonDelta\n | ThinkingDelta\n | SignatureDelta\n | CompactionDelta\n | CiteDelta;\n\n// ============================================================================\n// USAGE TYPES\n// ============================================================================\n\nexport interface BetaUsage {\n input_tokens: number;\n output_tokens: number;\n cache_creation_input_tokens?: number;\n cache_read_input_tokens?: number;\n}\n\n// ============================================================================\n// STREAM EVENT TYPES — discriminated union\n// ============================================================================\n\nexport interface MessageStartEvent {\n type: \"message_start\";\n message: {\n usage: BetaUsage;\n };\n}\n\nexport interface ContentBlockStartEvent {\n type: \"content_block_start\";\n index: number;\n content_block: ContentBlock;\n}\n\nexport interface ContentBlockDeltaEvent {\n type: \"content_block_delta\";\n index: number;\n delta: ContentBlockDelta;\n}\n\nexport interface ContentBlockStopEvent {\n type: \"content_block_stop\";\n index: number;\n}\n\nexport interface MessageDeltaEvent {\n type: \"message_delta\";\n delta: {\n stop_reason?: string;\n context_management?: {\n applied_edits?: Array<Record<string, unknown>>;\n };\n };\n usage: {\n output_tokens: number;\n // Non-Anthropic providers (Gemini, OpenAI) emit these in message_delta, not message_start\n input_tokens?: number;\n cache_read_input_tokens?: number;\n thinking_tokens?: number;\n };\n}\n\nexport interface StreamErrorEvent {\n type: \"error\";\n error: string | Record<string, unknown>;\n}\n\nexport type BetaStreamEvent =\n | MessageStartEvent\n | ContentBlockStartEvent\n | ContentBlockDeltaEvent\n | ContentBlockStopEvent\n | MessageDeltaEvent\n | StreamErrorEvent;\n"],"mappings":"","ignoreList":[]}
@@ -4,6 +4,7 @@
4
4
  * Replaces proxy+direct call paths in agent-loop, subagent, teammate.
5
5
  * CLI-only: always calls through server proxy (no direct Anthropic SDK usage).
6
6
  */
7
+ import type { CompactableMessage } from "./compaction.js";
7
8
  import type { ContextProfile, APIRequestConfig } from "./types.js";
8
9
  /**
9
10
  * Build all Anthropic API config from a simple profile.
@@ -18,14 +19,15 @@ export declare function buildAPIRequest(opts: {
18
19
  contextProfile: ContextProfile;
19
20
  thinkingEnabled?: boolean;
20
21
  maxOutputTokens?: number;
22
+ contextOverrides?: import("./agent-core.js").ContextManagementOverrides;
21
23
  }): APIRequestConfig;
22
24
  export interface CallServerProxyConfig {
23
25
  proxyUrl: string;
24
26
  token: string;
25
27
  model: string;
26
- system: Array<Record<string, unknown>>;
27
- messages: Array<Record<string, unknown>>;
28
- tools: Array<Record<string, unknown>>;
28
+ system: object[];
29
+ messages: object[];
30
+ tools: object[];
29
31
  apiConfig: APIRequestConfig;
30
32
  signal?: AbortSignal;
31
33
  timeoutMs?: number;
@@ -50,16 +52,22 @@ export declare function buildSystemBlocks(systemPrompt: string, costContext?: st
50
52
  * Prepare messages and tools with prompt caching.
51
53
  * Skips cache_control injection for Gemini (uses implicit caching).
52
54
  */
53
- export declare function prepareWithCaching(tools: Array<Record<string, unknown>>, messages: Array<Record<string, unknown>>, model?: string): {
54
- tools: Array<Record<string, unknown>>;
55
- messages: Array<Record<string, unknown>>;
55
+ export declare function prepareWithCaching<T extends object = object, M extends {
56
+ role: string;
57
+ content: unknown;
58
+ } = {
59
+ role: string;
60
+ content: unknown;
61
+ }>(tools: T[], messages: M[], model?: string): {
62
+ tools: T[];
63
+ messages: M[];
56
64
  };
57
65
  /**
58
66
  * Client-side context trimming for Gemini (no server-side context management).
59
67
  * When estimated input tokens exceed threshold, replaces old tool result contents
60
68
  * with "[trimmed]" to stay within Gemini's 1M context window.
61
69
  */
62
- export declare function trimGeminiContext(messages: Array<Record<string, unknown>>, estimatedTokens: number, threshold?: number, keepRecent?: number): Array<Record<string, unknown>>;
70
+ export declare function trimGeminiContext<T extends CompactableMessage>(messages: T[], estimatedTokens: number, threshold?: number, keepRecent?: number): T[];
63
71
  /**
64
72
  * Client-side context trimming for OpenAI (no server-side context management).
65
73
  * When estimated input tokens exceed threshold, replaces old tool result contents
@@ -76,7 +84,7 @@ export declare function callTranscribe(opts: {
76
84
  audioBase64: string;
77
85
  mediaType: string;
78
86
  }): Promise<string>;
79
- export declare function trimOpenAIContext(messages: Array<Record<string, unknown>>, estimatedTokens: number, threshold?: number, keepRecent?: number): Array<Record<string, unknown>>;
87
+ export declare function trimOpenAIContext<T extends CompactableMessage>(messages: T[], estimatedTokens: number, threshold?: number, keepRecent?: number): T[];
80
88
  /**
81
89
  * Request conversation compaction from the server (Haiku summarization).
82
90
  * Used by non-Anthropic providers (OpenAI, Gemini) that lack native compaction.
@@ -85,6 +93,6 @@ export declare function trimOpenAIContext(messages: Array<Record<string, unknown
85
93
  export declare function requestProviderCompaction(opts: {
86
94
  proxyUrl: string;
87
95
  token: string;
88
- messages: Array<Record<string, unknown>>;
96
+ messages: object[];
89
97
  systemPrompt: string;
90
98
  }): Promise<string | null>;