opencandle 0.11.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (663) hide show
  1. package/README.md +25 -28
  2. package/dist/analysts/contracts.js +0 -1
  3. package/dist/analysts/orchestrator.d.ts +2 -0
  4. package/dist/analysts/orchestrator.js +19 -1
  5. package/dist/cli-main.js +13 -7
  6. package/dist/cli-options.d.ts +4 -0
  7. package/dist/cli-options.js +33 -0
  8. package/dist/cli.js +8 -3
  9. package/dist/config.js +0 -1
  10. package/dist/doctor/cli-command.js +2 -1
  11. package/dist/doctor/render.js +0 -1
  12. package/dist/doctor/report.js +41 -12
  13. package/dist/gui/server/ask-user-bridge.d.ts +19 -0
  14. package/dist/gui/server/ask-user-bridge.js +55 -0
  15. package/dist/gui/server/automation-heartbeat.d.ts +25 -0
  16. package/dist/gui/server/automation-heartbeat.js +61 -0
  17. package/dist/gui/server/background-quotes.d.ts +39 -0
  18. package/dist/gui/server/background-quotes.js +71 -0
  19. package/dist/gui/server/chat-event-adapter.d.ts +16 -0
  20. package/dist/gui/server/chat-event-adapter.js +263 -0
  21. package/dist/gui/server/gui-session-manager.d.ts +2 -0
  22. package/dist/gui/server/gui-session-manager.js +4 -0
  23. package/dist/gui/server/http-routes.d.ts +69 -0
  24. package/dist/gui/server/http-routes.js +1008 -0
  25. package/dist/gui/server/invoke-tool.d.ts +47 -0
  26. package/dist/gui/server/invoke-tool.js +373 -0
  27. package/dist/gui/server/live-chat-event-adapter.d.ts +19 -0
  28. package/dist/gui/server/live-chat-event-adapter.js +206 -0
  29. package/dist/gui/server/local-session-coordinator.d.ts +26 -0
  30. package/dist/gui/server/local-session-coordinator.js +53 -0
  31. package/dist/gui/server/market-state-api.d.ts +138 -0
  32. package/dist/gui/server/market-state-api.js +355 -0
  33. package/dist/gui/server/model-setup.d.ts +64 -0
  34. package/dist/gui/server/model-setup.js +150 -0
  35. package/dist/gui/server/private-api-access.d.ts +6 -0
  36. package/dist/gui/server/private-api-access.js +53 -0
  37. package/dist/gui/server/projector.d.ts +49 -0
  38. package/dist/gui/server/projector.js +296 -0
  39. package/dist/gui/server/prompt-observation.d.ts +8 -0
  40. package/dist/gui/server/prompt-observation.js +43 -0
  41. package/dist/gui/server/quote-snapshot-store.d.ts +14 -0
  42. package/dist/gui/server/quote-snapshot-store.js +49 -0
  43. package/dist/gui/server/server.d.ts +1 -0
  44. package/dist/gui/server/server.js +259 -0
  45. package/dist/gui/server/session-actions.d.ts +60 -0
  46. package/dist/gui/server/session-actions.js +218 -0
  47. package/dist/gui/server/session-entry-wait.d.ts +27 -0
  48. package/dist/gui/server/session-entry-wait.js +129 -0
  49. package/dist/gui/server/session-list.d.ts +2 -0
  50. package/dist/gui/server/session-list.js +11 -0
  51. package/dist/gui/server/shutdown.d.ts +10 -0
  52. package/dist/gui/server/shutdown.js +29 -0
  53. package/dist/gui/server/tool-invoke-ack.d.ts +17 -0
  54. package/dist/gui/server/tool-invoke-ack.js +26 -0
  55. package/dist/gui/server/tool-metadata.d.ts +93 -0
  56. package/dist/gui/server/tool-metadata.js +148 -0
  57. package/dist/gui/server/websocket.d.ts +9 -0
  58. package/dist/gui/server/websocket.js +124 -0
  59. package/dist/gui/server/writer-lock.d.ts +1 -0
  60. package/dist/gui/server/writer-lock.js +1 -0
  61. package/dist/gui/server/ws-hub.d.ts +50 -0
  62. package/dist/gui/server/ws-hub.js +284 -0
  63. package/dist/gui/shared/chat-events.d.ts +174 -0
  64. package/dist/gui/shared/chat-events.js +13 -0
  65. package/dist/gui/shared/event-reducer.d.ts +3 -0
  66. package/dist/gui/shared/event-reducer.js +187 -0
  67. package/dist/index.js +0 -1
  68. package/dist/infra/cache.d.ts +6 -0
  69. package/dist/infra/cache.js +16 -7
  70. package/dist/infra/freshness.d.ts +21 -0
  71. package/dist/infra/freshness.js +118 -0
  72. package/dist/infra/http-client.js +1 -2
  73. package/dist/infra/index.js +0 -1
  74. package/dist/infra/market-calendar.d.ts +14 -0
  75. package/dist/infra/market-calendar.js +136 -0
  76. package/dist/infra/native-dependencies.js +0 -1
  77. package/dist/infra/node-version.js +0 -1
  78. package/dist/infra/open-url.js +0 -1
  79. package/dist/infra/opencandle-paths.js +0 -1
  80. package/dist/infra/rate-limiter.js +1 -1
  81. package/dist/market-state/alert-conditions.js +0 -1
  82. package/dist/market-state/alert-runner.d.ts +1 -0
  83. package/dist/market-state/alert-runner.js +5 -4
  84. package/dist/market-state/daily-report.js +0 -1
  85. package/dist/market-state/local-automation-service.js +0 -1
  86. package/dist/market-state/notification-delivery.js +0 -1
  87. package/dist/market-state/resolve-for-mutation.js +0 -1
  88. package/dist/market-state/resolve.js +0 -1
  89. package/dist/market-state/service.d.ts +26 -21
  90. package/dist/market-state/service.js +175 -36
  91. package/dist/market-state/summaries.d.ts +8 -0
  92. package/dist/market-state/summaries.js +58 -0
  93. package/dist/memory/index.js +0 -1
  94. package/dist/memory/manager.js +0 -1
  95. package/dist/memory/preference-extractor.js +0 -1
  96. package/dist/memory/retrieval.js +0 -1
  97. package/dist/memory/sqlite.js +60 -11
  98. package/dist/memory/storage.js +0 -1
  99. package/dist/memory/tool-defaults.js +0 -1
  100. package/dist/memory/types.js +0 -1
  101. package/dist/monitor.js +0 -1
  102. package/dist/onboarding/connect.js +0 -1
  103. package/dist/onboarding/credential-interceptor.js +0 -1
  104. package/dist/onboarding/degradation-accumulator.js +0 -1
  105. package/dist/onboarding/prompt-user.d.ts +1 -1
  106. package/dist/onboarding/prompt-user.js +0 -1
  107. package/dist/onboarding/provider-status.js +0 -1
  108. package/dist/onboarding/providers.d.ts +25 -1
  109. package/dist/onboarding/providers.js +26 -1
  110. package/dist/onboarding/state.js +0 -1
  111. package/dist/onboarding/tool-helpers.js +0 -1
  112. package/dist/onboarding/tool-tags.js +0 -1
  113. package/dist/onboarding/validate-model-key.d.ts +17 -0
  114. package/dist/onboarding/validate-model-key.js +54 -0
  115. package/dist/onboarding/validation.js +0 -1
  116. package/dist/pi/opencandle-extension.js +46 -7
  117. package/dist/pi/session-action-dedupe.js +0 -1
  118. package/dist/pi/session-storage.js +0 -1
  119. package/dist/pi/session-writer-lock.js +0 -1
  120. package/dist/pi/session.js +0 -1
  121. package/dist/pi/setup.d.ts +2 -0
  122. package/dist/pi/setup.js +10 -3
  123. package/dist/pi/tool-adapter.js +0 -1
  124. package/dist/pi/tui-session-coordinator.js +0 -1
  125. package/dist/prompts/context-builder.js +1 -2
  126. package/dist/prompts/disclaimer.js +0 -1
  127. package/dist/prompts/policy-cards.js +0 -1
  128. package/dist/prompts/sections.js +0 -1
  129. package/dist/prompts/symbol-preflight.js +0 -1
  130. package/dist/prompts/workflow-prompts.js +0 -1
  131. package/dist/providers/alpha-vantage.js +8 -3
  132. package/dist/providers/coingecko.js +1 -1
  133. package/dist/providers/errors.js +0 -1
  134. package/dist/providers/exa-search.js +11 -10
  135. package/dist/providers/external-tool-command.js +0 -1
  136. package/dist/providers/external-tool-error.js +0 -1
  137. package/dist/providers/fear-greed.js +0 -1
  138. package/dist/providers/finnhub.js +0 -1
  139. package/dist/providers/fred.js +0 -1
  140. package/dist/providers/index.js +0 -1
  141. package/dist/providers/polymarket.d.ts +2 -0
  142. package/dist/providers/polymarket.js +162 -0
  143. package/dist/providers/provider-credential-error.js +0 -1
  144. package/dist/providers/reddit-cli.js +0 -1
  145. package/dist/providers/reddit.js +0 -1
  146. package/dist/providers/sec-edgar.js +0 -1
  147. package/dist/providers/tradingview.js +1 -2
  148. package/dist/providers/twitter-cli.js +0 -1
  149. package/dist/providers/twitter.js +0 -1
  150. package/dist/providers/web-search.js +15 -12
  151. package/dist/providers/with-fallback.js +0 -1
  152. package/dist/providers/wrap-provider.js +5 -4
  153. package/dist/providers/yahoo-finance.d.ts +3 -0
  154. package/dist/providers/yahoo-finance.js +272 -13
  155. package/dist/routing/classify-intent.js +0 -1
  156. package/dist/routing/defaults.js +0 -1
  157. package/dist/routing/entity-extractor.js +18 -3
  158. package/dist/routing/fund-symbols.js +0 -1
  159. package/dist/routing/horizon.js +0 -1
  160. package/dist/routing/index.js +0 -1
  161. package/dist/routing/legacy-rule-router.js +0 -1
  162. package/dist/routing/planning.js +0 -1
  163. package/dist/routing/route-manifest.js +1 -2
  164. package/dist/routing/router-llm-client.d.ts +2 -2
  165. package/dist/routing/router-llm-client.js +18 -4
  166. package/dist/routing/router-prompt.js +0 -1
  167. package/dist/routing/router-types.js +0 -1
  168. package/dist/routing/router.d.ts +1 -1
  169. package/dist/routing/router.js +274 -6
  170. package/dist/routing/slot-resolver.d.ts +1 -0
  171. package/dist/routing/slot-resolver.js +1 -2
  172. package/dist/routing/symbol-disambiguator.js +0 -1
  173. package/dist/routing/turn-context.js +0 -1
  174. package/dist/routing/types.js +0 -1
  175. package/dist/runtime/answer-contracts.js +0 -1
  176. package/dist/runtime/artifact-contracts.js +0 -1
  177. package/dist/runtime/evidence.d.ts +1 -0
  178. package/dist/runtime/evidence.js +0 -1
  179. package/dist/runtime/numeric-claims.d.ts +23 -0
  180. package/dist/runtime/numeric-claims.js +99 -0
  181. package/dist/runtime/planning-evidence.js +1 -77
  182. package/dist/runtime/prompt-step.d.ts +10 -1
  183. package/dist/runtime/prompt-step.js +116 -3
  184. package/dist/runtime/provider-tracker.js +0 -1
  185. package/dist/runtime/run-context.js +0 -1
  186. package/dist/runtime/session-coordinator.d.ts +11 -1
  187. package/dist/runtime/session-coordinator.js +352 -50
  188. package/dist/runtime/session-title.js +0 -1
  189. package/dist/runtime/tool-defaults-wrapper.js +0 -1
  190. package/dist/runtime/validation.d.ts +3 -1
  191. package/dist/runtime/validation.js +0 -1
  192. package/dist/runtime/workflow-events.d.ts +1 -1
  193. package/dist/runtime/workflow-events.js +0 -1
  194. package/dist/runtime/workflow-runner.d.ts +1 -0
  195. package/dist/runtime/workflow-runner.js +8 -3
  196. package/dist/runtime/workflow-types.d.ts +3 -0
  197. package/dist/runtime/workflow-types.js +0 -1
  198. package/dist/sentiment/adapters/finnhub.js +0 -1
  199. package/dist/sentiment/adapters/reddit.js +0 -1
  200. package/dist/sentiment/adapters/twitter.js +0 -1
  201. package/dist/sentiment/adapters/web.js +0 -1
  202. package/dist/sentiment/index.js +4 -2
  203. package/dist/sentiment/insights.js +0 -1
  204. package/dist/sentiment/keywords.js +0 -1
  205. package/dist/sentiment/pipeline.js +0 -1
  206. package/dist/sentiment/scorer.js +0 -1
  207. package/dist/sentiment/store.js +0 -1
  208. package/dist/sentiment/trends.js +0 -1
  209. package/dist/sentiment/types.js +0 -1
  210. package/dist/system-prompt.js +0 -1
  211. package/dist/tool-kit.js +0 -1
  212. package/dist/tools/fundamentals/company-overview.d.ts +1 -1
  213. package/dist/tools/fundamentals/company-overview.js +2 -1
  214. package/dist/tools/fundamentals/comps.d.ts +1 -0
  215. package/dist/tools/fundamentals/comps.js +25 -12
  216. package/dist/tools/fundamentals/dcf.js +183 -113
  217. package/dist/tools/fundamentals/earnings.d.ts +1 -1
  218. package/dist/tools/fundamentals/earnings.js +2 -1
  219. package/dist/tools/fundamentals/financials.js +2 -1
  220. package/dist/tools/fundamentals/sec-filings.js +0 -1
  221. package/dist/tools/index.d.ts +117 -2
  222. package/dist/tools/index.js +3 -1
  223. package/dist/tools/interaction/ask-user.js +11 -1
  224. package/dist/tools/macro/event-probabilities.d.ts +8 -0
  225. package/dist/tools/macro/event-probabilities.js +120 -0
  226. package/dist/tools/macro/fear-greed.d.ts +1 -1
  227. package/dist/tools/macro/fear-greed.js +0 -1
  228. package/dist/tools/macro/fred-data.d.ts +1 -1
  229. package/dist/tools/macro/fred-data.js +2 -1
  230. package/dist/tools/market/crypto-history.js +0 -1
  231. package/dist/tools/market/crypto-price.d.ts +4 -1
  232. package/dist/tools/market/crypto-price.js +10 -2
  233. package/dist/tools/market/screen-stocks.js +14 -4
  234. package/dist/tools/market/search-ticker.js +1 -2
  235. package/dist/tools/market/stock-history.js +0 -1
  236. package/dist/tools/market/stock-quote.d.ts +4 -1
  237. package/dist/tools/market/stock-quote.js +9 -5
  238. package/dist/tools/options/greeks.js +0 -1
  239. package/dist/tools/options/option-chain.d.ts +4 -1
  240. package/dist/tools/options/option-chain.js +12 -2
  241. package/dist/tools/portfolio/alerts.d.ts +2 -1
  242. package/dist/tools/portfolio/alerts.js +228 -2
  243. package/dist/tools/portfolio/correlation.js +23 -5
  244. package/dist/tools/portfolio/daily-report.js +0 -1
  245. package/dist/tools/portfolio/holdings-overlap.js +0 -1
  246. package/dist/tools/portfolio/notifications.js +0 -1
  247. package/dist/tools/portfolio/risk-analysis.d.ts +1 -1
  248. package/dist/tools/portfolio/risk-analysis.js +1 -2
  249. package/dist/tools/portfolio/tracker.d.ts +3 -1
  250. package/dist/tools/portfolio/tracker.js +57 -10
  251. package/dist/tools/portfolio/watchlist.d.ts +3 -6
  252. package/dist/tools/portfolio/watchlist.js +101 -110
  253. package/dist/tools/sentiment/insight-format.js +0 -1
  254. package/dist/tools/sentiment/query-match.js +0 -1
  255. package/dist/tools/sentiment/reddit-sentiment.js +0 -1
  256. package/dist/tools/sentiment/sentiment-summary.js +8 -4
  257. package/dist/tools/sentiment/sentiment-trend.d.ts +5 -1
  258. package/dist/tools/sentiment/sentiment-trend.js +6 -2
  259. package/dist/tools/sentiment/twitter-sentiment.js +0 -1
  260. package/dist/tools/sentiment/untrusted-text.js +0 -1
  261. package/dist/tools/sentiment/web-search.d.ts +1 -1
  262. package/dist/tools/sentiment/web-search.js +0 -1
  263. package/dist/tools/sentiment/web-sentiment.js +0 -1
  264. package/dist/tools/technical/backtest.js +0 -1
  265. package/dist/tools/technical/indicators.js +1 -2
  266. package/dist/types/fundamentals.d.ts +1 -0
  267. package/dist/types/fundamentals.js +0 -1
  268. package/dist/types/index.d.ts +1 -0
  269. package/dist/types/index.js +0 -1
  270. package/dist/types/macro.js +0 -1
  271. package/dist/types/market.d.ts +8 -0
  272. package/dist/types/market.js +0 -1
  273. package/dist/types/options.d.ts +1 -0
  274. package/dist/types/options.js +0 -1
  275. package/dist/types/portfolio.js +0 -1
  276. package/dist/types/prediction-markets.d.ts +13 -0
  277. package/dist/types/prediction-markets.js +1 -0
  278. package/dist/types/sentiment.js +0 -1
  279. package/dist/workflows/compare-assets.js +0 -1
  280. package/dist/workflows/index.js +0 -1
  281. package/dist/workflows/options-screener.js +0 -1
  282. package/dist/workflows/portfolio-builder.js +0 -1
  283. package/gui/web/dist/assets/CatalogOverlay-CAc7e3Pf.js +1 -0
  284. package/gui/web/dist/assets/index-BOEKd9wT.css +2 -0
  285. package/gui/web/dist/assets/index-C-H05cQ2.js +65 -0
  286. package/gui/web/dist/index.html +2 -2
  287. package/package.json +16 -22
  288. package/dist/analysts/contracts.js.map +0 -1
  289. package/dist/analysts/orchestrator.js.map +0 -1
  290. package/dist/cli-main.js.map +0 -1
  291. package/dist/cli.js.map +0 -1
  292. package/dist/config.js.map +0 -1
  293. package/dist/doctor/cli-command.js.map +0 -1
  294. package/dist/doctor/render.js.map +0 -1
  295. package/dist/doctor/report.js.map +0 -1
  296. package/dist/index.js.map +0 -1
  297. package/dist/infra/cache.js.map +0 -1
  298. package/dist/infra/http-client.js.map +0 -1
  299. package/dist/infra/index.js.map +0 -1
  300. package/dist/infra/native-dependencies.js.map +0 -1
  301. package/dist/infra/node-version.js.map +0 -1
  302. package/dist/infra/open-url.js.map +0 -1
  303. package/dist/infra/opencandle-paths.js.map +0 -1
  304. package/dist/infra/rate-limiter.js.map +0 -1
  305. package/dist/market-state/alert-conditions.js.map +0 -1
  306. package/dist/market-state/alert-runner.js.map +0 -1
  307. package/dist/market-state/daily-report.js.map +0 -1
  308. package/dist/market-state/local-automation-service.js.map +0 -1
  309. package/dist/market-state/notification-delivery.js.map +0 -1
  310. package/dist/market-state/resolve-for-mutation.js.map +0 -1
  311. package/dist/market-state/resolve.js.map +0 -1
  312. package/dist/market-state/service.js.map +0 -1
  313. package/dist/memory/index.js.map +0 -1
  314. package/dist/memory/manager.js.map +0 -1
  315. package/dist/memory/preference-extractor.js.map +0 -1
  316. package/dist/memory/retrieval.js.map +0 -1
  317. package/dist/memory/sqlite.js.map +0 -1
  318. package/dist/memory/storage.js.map +0 -1
  319. package/dist/memory/tool-defaults.js.map +0 -1
  320. package/dist/memory/types.js.map +0 -1
  321. package/dist/monitor.js.map +0 -1
  322. package/dist/onboarding/connect.js.map +0 -1
  323. package/dist/onboarding/credential-interceptor.js.map +0 -1
  324. package/dist/onboarding/degradation-accumulator.js.map +0 -1
  325. package/dist/onboarding/prompt-user.js.map +0 -1
  326. package/dist/onboarding/provider-status.js.map +0 -1
  327. package/dist/onboarding/providers.js.map +0 -1
  328. package/dist/onboarding/state.js.map +0 -1
  329. package/dist/onboarding/tool-helpers.js.map +0 -1
  330. package/dist/onboarding/tool-tags.js.map +0 -1
  331. package/dist/onboarding/validation.js.map +0 -1
  332. package/dist/pi/opencandle-extension.js.map +0 -1
  333. package/dist/pi/session-action-dedupe.js.map +0 -1
  334. package/dist/pi/session-storage.js.map +0 -1
  335. package/dist/pi/session-writer-lock.js.map +0 -1
  336. package/dist/pi/session.js.map +0 -1
  337. package/dist/pi/setup.js.map +0 -1
  338. package/dist/pi/tool-adapter.js.map +0 -1
  339. package/dist/pi/tui-session-coordinator.js.map +0 -1
  340. package/dist/prompts/context-builder.js.map +0 -1
  341. package/dist/prompts/disclaimer.js.map +0 -1
  342. package/dist/prompts/policy-cards.js.map +0 -1
  343. package/dist/prompts/sections.js.map +0 -1
  344. package/dist/prompts/symbol-preflight.js.map +0 -1
  345. package/dist/prompts/workflow-prompts.js.map +0 -1
  346. package/dist/providers/alpha-vantage.js.map +0 -1
  347. package/dist/providers/coingecko.js.map +0 -1
  348. package/dist/providers/errors.js.map +0 -1
  349. package/dist/providers/exa-search.js.map +0 -1
  350. package/dist/providers/external-tool-command.js.map +0 -1
  351. package/dist/providers/external-tool-error.js.map +0 -1
  352. package/dist/providers/fear-greed.js.map +0 -1
  353. package/dist/providers/finnhub.js.map +0 -1
  354. package/dist/providers/fred.js.map +0 -1
  355. package/dist/providers/index.js.map +0 -1
  356. package/dist/providers/provider-credential-error.js.map +0 -1
  357. package/dist/providers/reddit-cli.js.map +0 -1
  358. package/dist/providers/reddit.js.map +0 -1
  359. package/dist/providers/sec-edgar.js.map +0 -1
  360. package/dist/providers/tradingview.js.map +0 -1
  361. package/dist/providers/twitter-cli.js.map +0 -1
  362. package/dist/providers/twitter.js.map +0 -1
  363. package/dist/providers/web-search.js.map +0 -1
  364. package/dist/providers/with-fallback.js.map +0 -1
  365. package/dist/providers/wrap-provider.js.map +0 -1
  366. package/dist/providers/yahoo-finance.js.map +0 -1
  367. package/dist/routing/classify-intent.js.map +0 -1
  368. package/dist/routing/defaults.js.map +0 -1
  369. package/dist/routing/entity-extractor.js.map +0 -1
  370. package/dist/routing/fund-symbols.js.map +0 -1
  371. package/dist/routing/horizon.js.map +0 -1
  372. package/dist/routing/index.js.map +0 -1
  373. package/dist/routing/legacy-rule-router.js.map +0 -1
  374. package/dist/routing/planning.js.map +0 -1
  375. package/dist/routing/route-manifest.js.map +0 -1
  376. package/dist/routing/router-llm-client.js.map +0 -1
  377. package/dist/routing/router-prompt.js.map +0 -1
  378. package/dist/routing/router-types.js.map +0 -1
  379. package/dist/routing/router.js.map +0 -1
  380. package/dist/routing/slot-resolver.js.map +0 -1
  381. package/dist/routing/symbol-disambiguator.js.map +0 -1
  382. package/dist/routing/turn-context.js.map +0 -1
  383. package/dist/routing/types.js.map +0 -1
  384. package/dist/runtime/answer-contracts.js.map +0 -1
  385. package/dist/runtime/artifact-contracts.js.map +0 -1
  386. package/dist/runtime/evidence.js.map +0 -1
  387. package/dist/runtime/planning-evidence.js.map +0 -1
  388. package/dist/runtime/prompt-step.js.map +0 -1
  389. package/dist/runtime/provider-tracker.js.map +0 -1
  390. package/dist/runtime/run-context.js.map +0 -1
  391. package/dist/runtime/session-coordinator.js.map +0 -1
  392. package/dist/runtime/session-title.js.map +0 -1
  393. package/dist/runtime/tool-defaults-wrapper.js.map +0 -1
  394. package/dist/runtime/validation.js.map +0 -1
  395. package/dist/runtime/workflow-events.js.map +0 -1
  396. package/dist/runtime/workflow-runner.js.map +0 -1
  397. package/dist/runtime/workflow-types.js.map +0 -1
  398. package/dist/sentiment/adapters/finnhub.js.map +0 -1
  399. package/dist/sentiment/adapters/reddit.js.map +0 -1
  400. package/dist/sentiment/adapters/twitter.js.map +0 -1
  401. package/dist/sentiment/adapters/web.js.map +0 -1
  402. package/dist/sentiment/index.js.map +0 -1
  403. package/dist/sentiment/insights.js.map +0 -1
  404. package/dist/sentiment/keywords.js.map +0 -1
  405. package/dist/sentiment/pipeline.js.map +0 -1
  406. package/dist/sentiment/scorer.js.map +0 -1
  407. package/dist/sentiment/store.js.map +0 -1
  408. package/dist/sentiment/trends.js.map +0 -1
  409. package/dist/sentiment/types.js.map +0 -1
  410. package/dist/system-prompt.js.map +0 -1
  411. package/dist/tool-kit.js.map +0 -1
  412. package/dist/tools/fundamentals/company-overview.js.map +0 -1
  413. package/dist/tools/fundamentals/comps.js.map +0 -1
  414. package/dist/tools/fundamentals/dcf.js.map +0 -1
  415. package/dist/tools/fundamentals/earnings.js.map +0 -1
  416. package/dist/tools/fundamentals/financials.js.map +0 -1
  417. package/dist/tools/fundamentals/sec-filings.js.map +0 -1
  418. package/dist/tools/index.js.map +0 -1
  419. package/dist/tools/interaction/ask-user.js.map +0 -1
  420. package/dist/tools/macro/fear-greed.js.map +0 -1
  421. package/dist/tools/macro/fred-data.js.map +0 -1
  422. package/dist/tools/market/crypto-history.js.map +0 -1
  423. package/dist/tools/market/crypto-price.js.map +0 -1
  424. package/dist/tools/market/screen-stocks.js.map +0 -1
  425. package/dist/tools/market/search-ticker.js.map +0 -1
  426. package/dist/tools/market/stock-history.js.map +0 -1
  427. package/dist/tools/market/stock-quote.js.map +0 -1
  428. package/dist/tools/options/greeks.js.map +0 -1
  429. package/dist/tools/options/option-chain.js.map +0 -1
  430. package/dist/tools/portfolio/alerts.js.map +0 -1
  431. package/dist/tools/portfolio/correlation.js.map +0 -1
  432. package/dist/tools/portfolio/daily-report.js.map +0 -1
  433. package/dist/tools/portfolio/holdings-overlap.js.map +0 -1
  434. package/dist/tools/portfolio/notifications.js.map +0 -1
  435. package/dist/tools/portfolio/risk-analysis.js.map +0 -1
  436. package/dist/tools/portfolio/tracker.js.map +0 -1
  437. package/dist/tools/portfolio/watchlist.js.map +0 -1
  438. package/dist/tools/sentiment/insight-format.js.map +0 -1
  439. package/dist/tools/sentiment/query-match.js.map +0 -1
  440. package/dist/tools/sentiment/reddit-sentiment.js.map +0 -1
  441. package/dist/tools/sentiment/sentiment-summary.js.map +0 -1
  442. package/dist/tools/sentiment/sentiment-trend.js.map +0 -1
  443. package/dist/tools/sentiment/twitter-sentiment.js.map +0 -1
  444. package/dist/tools/sentiment/untrusted-text.js.map +0 -1
  445. package/dist/tools/sentiment/web-search.js.map +0 -1
  446. package/dist/tools/sentiment/web-sentiment.js.map +0 -1
  447. package/dist/tools/technical/backtest.js.map +0 -1
  448. package/dist/tools/technical/indicators.js.map +0 -1
  449. package/dist/types/fundamentals.js.map +0 -1
  450. package/dist/types/index.js.map +0 -1
  451. package/dist/types/macro.js.map +0 -1
  452. package/dist/types/market.js.map +0 -1
  453. package/dist/types/options.js.map +0 -1
  454. package/dist/types/portfolio.js.map +0 -1
  455. package/dist/types/sentiment.js.map +0 -1
  456. package/dist/workflows/compare-assets.js.map +0 -1
  457. package/dist/workflows/index.js.map +0 -1
  458. package/dist/workflows/options-screener.js.map +0 -1
  459. package/dist/workflows/portfolio-builder.js.map +0 -1
  460. package/gui/server/ask-user-bridge.ts +0 -89
  461. package/gui/server/automation-heartbeat.ts +0 -97
  462. package/gui/server/background-quotes.ts +0 -127
  463. package/gui/server/chat-event-adapter.ts +0 -210
  464. package/gui/server/chat-run-session.ts +0 -16
  465. package/gui/server/gui-session-manager.ts +0 -5
  466. package/gui/server/http-routes.ts +0 -953
  467. package/gui/server/invoke-tool.ts +0 -489
  468. package/gui/server/live-chat-event-adapter.ts +0 -208
  469. package/gui/server/local-session-coordinator.ts +0 -97
  470. package/gui/server/market-state-api.ts +0 -273
  471. package/gui/server/model-setup.ts +0 -254
  472. package/gui/server/package.json +0 -5
  473. package/gui/server/private-api-access.ts +0 -62
  474. package/gui/server/projector.ts +0 -263
  475. package/gui/server/prompt-observation.ts +0 -58
  476. package/gui/server/quote-snapshot-store.ts +0 -50
  477. package/gui/server/server.ts +0 -289
  478. package/gui/server/session-actions.ts +0 -331
  479. package/gui/server/session-entry-wait.ts +0 -160
  480. package/gui/server/shutdown.ts +0 -47
  481. package/gui/server/tool-invoke-ack.ts +0 -49
  482. package/gui/server/tool-metadata.ts +0 -167
  483. package/gui/server/websocket.ts +0 -138
  484. package/gui/server/writer-lock.ts +0 -1
  485. package/gui/server/ws-hub.ts +0 -391
  486. package/gui/shared/chat-events.ts +0 -156
  487. package/gui/shared/event-reducer.ts +0 -219
  488. package/gui/web/dist/assets/CatalogOverlay-ChRTKNlf.js +0 -1
  489. package/gui/web/dist/assets/index-BzyqyVnd.css +0 -2
  490. package/gui/web/dist/assets/index-DvMjkOP9.js +0 -65
  491. package/src/analysts/contracts.ts +0 -176
  492. package/src/analysts/orchestrator.ts +0 -224
  493. package/src/cli-main.ts +0 -510
  494. package/src/cli.ts +0 -17
  495. package/src/config.ts +0 -272
  496. package/src/doctor/cli-command.ts +0 -83
  497. package/src/doctor/render.ts +0 -37
  498. package/src/doctor/report.ts +0 -638
  499. package/src/index.ts +0 -5
  500. package/src/infra/cache.ts +0 -114
  501. package/src/infra/http-client.ts +0 -134
  502. package/src/infra/index.ts +0 -14
  503. package/src/infra/native-dependencies.ts +0 -84
  504. package/src/infra/node-version.ts +0 -23
  505. package/src/infra/open-url.ts +0 -28
  506. package/src/infra/opencandle-paths.ts +0 -53
  507. package/src/infra/rate-limiter.ts +0 -76
  508. package/src/market-state/alert-conditions.ts +0 -82
  509. package/src/market-state/alert-runner.ts +0 -863
  510. package/src/market-state/daily-report.ts +0 -237
  511. package/src/market-state/local-automation-service.ts +0 -162
  512. package/src/market-state/notification-delivery.ts +0 -158
  513. package/src/market-state/resolve-for-mutation.ts +0 -24
  514. package/src/market-state/resolve.ts +0 -112
  515. package/src/market-state/service.ts +0 -2208
  516. package/src/memory/index.ts +0 -10
  517. package/src/memory/manager.ts +0 -190
  518. package/src/memory/preference-extractor.ts +0 -106
  519. package/src/memory/retrieval.ts +0 -71
  520. package/src/memory/sqlite.ts +0 -577
  521. package/src/memory/storage.ts +0 -195
  522. package/src/memory/tool-defaults.ts +0 -108
  523. package/src/memory/types.ts +0 -71
  524. package/src/monitor.ts +0 -123
  525. package/src/onboarding/connect.ts +0 -177
  526. package/src/onboarding/credential-interceptor.ts +0 -122
  527. package/src/onboarding/degradation-accumulator.ts +0 -77
  528. package/src/onboarding/prompt-user.ts +0 -85
  529. package/src/onboarding/provider-status.ts +0 -382
  530. package/src/onboarding/providers.ts +0 -414
  531. package/src/onboarding/state.ts +0 -216
  532. package/src/onboarding/tool-helpers.ts +0 -104
  533. package/src/onboarding/tool-tags.ts +0 -244
  534. package/src/onboarding/validation.ts +0 -152
  535. package/src/pi/opencandle-extension.ts +0 -1244
  536. package/src/pi/session-action-dedupe.ts +0 -155
  537. package/src/pi/session-storage.ts +0 -5
  538. package/src/pi/session-writer-lock.ts +0 -426
  539. package/src/pi/session.ts +0 -84
  540. package/src/pi/setup.ts +0 -399
  541. package/src/pi/tool-adapter.ts +0 -49
  542. package/src/pi/tui-session-coordinator.ts +0 -351
  543. package/src/prompts/context-builder.ts +0 -326
  544. package/src/prompts/disclaimer.ts +0 -9
  545. package/src/prompts/policy-cards.ts +0 -228
  546. package/src/prompts/sections.ts +0 -46
  547. package/src/prompts/symbol-preflight.ts +0 -80
  548. package/src/prompts/workflow-prompts.ts +0 -504
  549. package/src/providers/alpha-vantage.ts +0 -334
  550. package/src/providers/coingecko.ts +0 -93
  551. package/src/providers/errors.ts +0 -9
  552. package/src/providers/exa-search.ts +0 -375
  553. package/src/providers/external-tool-command.ts +0 -164
  554. package/src/providers/external-tool-error.ts +0 -20
  555. package/src/providers/fear-greed.ts +0 -45
  556. package/src/providers/finnhub.ts +0 -125
  557. package/src/providers/fred.ts +0 -83
  558. package/src/providers/index.ts +0 -17
  559. package/src/providers/provider-credential-error.ts +0 -23
  560. package/src/providers/reddit-cli.ts +0 -286
  561. package/src/providers/reddit.ts +0 -106
  562. package/src/providers/sec-edgar.ts +0 -326
  563. package/src/providers/tradingview.ts +0 -399
  564. package/src/providers/twitter-cli.ts +0 -202
  565. package/src/providers/twitter.ts +0 -102
  566. package/src/providers/web-search.ts +0 -303
  567. package/src/providers/with-fallback.ts +0 -42
  568. package/src/providers/wrap-provider.ts +0 -103
  569. package/src/providers/yahoo-finance.ts +0 -672
  570. package/src/routing/classify-intent.ts +0 -380
  571. package/src/routing/defaults.ts +0 -29
  572. package/src/routing/entity-extractor.ts +0 -540
  573. package/src/routing/fund-symbols.ts +0 -58
  574. package/src/routing/horizon.ts +0 -7
  575. package/src/routing/index.ts +0 -70
  576. package/src/routing/legacy-rule-router.ts +0 -13
  577. package/src/routing/planning.ts +0 -829
  578. package/src/routing/route-manifest.ts +0 -308
  579. package/src/routing/router-llm-client.ts +0 -52
  580. package/src/routing/router-prompt.ts +0 -159
  581. package/src/routing/router-types.ts +0 -84
  582. package/src/routing/router.ts +0 -997
  583. package/src/routing/slot-resolver.ts +0 -213
  584. package/src/routing/symbol-disambiguator.ts +0 -72
  585. package/src/routing/turn-context.ts +0 -108
  586. package/src/routing/types.ts +0 -77
  587. package/src/runtime/answer-contracts.ts +0 -693
  588. package/src/runtime/artifact-contracts.ts +0 -77
  589. package/src/runtime/evidence.ts +0 -77
  590. package/src/runtime/planning-evidence.ts +0 -682
  591. package/src/runtime/prompt-step.ts +0 -60
  592. package/src/runtime/provider-tracker.ts +0 -40
  593. package/src/runtime/run-context.ts +0 -32
  594. package/src/runtime/session-coordinator.ts +0 -632
  595. package/src/runtime/session-title.ts +0 -60
  596. package/src/runtime/tool-defaults-wrapper.ts +0 -43
  597. package/src/runtime/validation.ts +0 -211
  598. package/src/runtime/workflow-events.ts +0 -75
  599. package/src/runtime/workflow-runner.ts +0 -182
  600. package/src/runtime/workflow-types.ts +0 -102
  601. package/src/sentiment/adapters/finnhub.ts +0 -49
  602. package/src/sentiment/adapters/reddit.ts +0 -65
  603. package/src/sentiment/adapters/twitter.ts +0 -36
  604. package/src/sentiment/adapters/web.ts +0 -44
  605. package/src/sentiment/index.ts +0 -49
  606. package/src/sentiment/insights.ts +0 -269
  607. package/src/sentiment/keywords.ts +0 -31
  608. package/src/sentiment/pipeline.ts +0 -91
  609. package/src/sentiment/scorer.ts +0 -89
  610. package/src/sentiment/store.ts +0 -260
  611. package/src/sentiment/trends.ts +0 -96
  612. package/src/sentiment/types.ts +0 -112
  613. package/src/system-prompt.ts +0 -115
  614. package/src/tool-kit.ts +0 -69
  615. package/src/tools/AGENTS.md +0 -36
  616. package/src/tools/fundamentals/company-overview.ts +0 -64
  617. package/src/tools/fundamentals/comps.ts +0 -169
  618. package/src/tools/fundamentals/dcf.ts +0 -367
  619. package/src/tools/fundamentals/earnings.ts +0 -57
  620. package/src/tools/fundamentals/financials.ts +0 -63
  621. package/src/tools/fundamentals/sec-filings.ts +0 -105
  622. package/src/tools/index.ts +0 -101
  623. package/src/tools/interaction/ask-user.ts +0 -93
  624. package/src/tools/macro/fear-greed.ts +0 -41
  625. package/src/tools/macro/fred-data.ts +0 -92
  626. package/src/tools/market/crypto-history.ts +0 -72
  627. package/src/tools/market/crypto-price.ts +0 -53
  628. package/src/tools/market/screen-stocks.ts +0 -279
  629. package/src/tools/market/search-ticker.ts +0 -254
  630. package/src/tools/market/stock-history.ts +0 -104
  631. package/src/tools/market/stock-quote.ts +0 -67
  632. package/src/tools/options/greeks.ts +0 -81
  633. package/src/tools/options/option-chain.ts +0 -120
  634. package/src/tools/portfolio/alerts.ts +0 -457
  635. package/src/tools/portfolio/correlation.ts +0 -189
  636. package/src/tools/portfolio/daily-report.ts +0 -107
  637. package/src/tools/portfolio/holdings-overlap.ts +0 -139
  638. package/src/tools/portfolio/notifications.ts +0 -45
  639. package/src/tools/portfolio/risk-analysis.ts +0 -173
  640. package/src/tools/portfolio/tracker.ts +0 -308
  641. package/src/tools/portfolio/watchlist.ts +0 -288
  642. package/src/tools/sentiment/insight-format.ts +0 -50
  643. package/src/tools/sentiment/query-match.ts +0 -117
  644. package/src/tools/sentiment/reddit-sentiment.ts +0 -403
  645. package/src/tools/sentiment/sentiment-summary.ts +0 -383
  646. package/src/tools/sentiment/sentiment-trend.ts +0 -75
  647. package/src/tools/sentiment/twitter-sentiment.ts +0 -287
  648. package/src/tools/sentiment/untrusted-text.ts +0 -21
  649. package/src/tools/sentiment/web-search.ts +0 -186
  650. package/src/tools/sentiment/web-sentiment.ts +0 -96
  651. package/src/tools/technical/backtest.ts +0 -336
  652. package/src/tools/technical/indicators.ts +0 -281
  653. package/src/types/fundamentals.ts +0 -46
  654. package/src/types/index.ts +0 -25
  655. package/src/types/macro.ts +0 -27
  656. package/src/types/market.ts +0 -44
  657. package/src/types/options.ts +0 -52
  658. package/src/types/portfolio.ts +0 -83
  659. package/src/types/sentiment.ts +0 -129
  660. package/src/workflows/compare-assets.ts +0 -89
  661. package/src/workflows/index.ts +0 -3
  662. package/src/workflows/options-screener.ts +0 -125
  663. package/src/workflows/portfolio-builder.ts +0 -63
@@ -1,997 +0,0 @@
1
- import {
2
- extractEntities,
3
- isAmbiguousConceptUsage,
4
- isCurrencyCodeUsage,
5
- } from "./entity-extractor.js";
6
- import { classifyWithLegacyRules } from "./legacy-rule-router.js";
7
- import {
8
- computeMissingRequiredSlots,
9
- isDispatchableWorkflow,
10
- isRouteKind,
11
- isToolBundleName,
12
- legacyRouteForRouteKind,
13
- routeKindFromLegacyRoute,
14
- selectToolBundles,
15
- workflowRequiredSlots,
16
- } from "./route-manifest.js";
17
- import { buildRouterPrompt } from "./router-prompt.js";
18
- import type {
19
- RouterDiagnostic,
20
- RouterInputContext,
21
- RouterLlmClient,
22
- RouterOutput,
23
- RouterPreferenceUpdate,
24
- RouterRoute,
25
- RouterRouteKind,
26
- RouterSlot,
27
- ToolBundleName,
28
- } from "./router-types.js";
29
- import { disambiguateSymbols } from "./symbol-disambiguator.js";
30
- import type { ExtractedEntities, WorkflowType } from "./types.js";
31
-
32
- const VALID_ROUTES: readonly RouterRoute[] = ["workflow", "fallback"];
33
- const VALID_WORKFLOWS: ReadonlyArray<Exclude<WorkflowType, "unclassified">> = [
34
- "portfolio_builder",
35
- "options_screener",
36
- "compare_assets",
37
- "single_asset_analysis",
38
- "watchlist_or_tracking",
39
- "general_finance_qa",
40
- ];
41
- const VALID_SOURCES = new Set(["user", "preference", "default", "prior_context", "memory"]);
42
- const VALID_CONFIDENCE = new Set(["high", "medium", "low"]);
43
-
44
- /**
45
- * Run the LLM router against the given input context. Retries once on
46
- * validation failure with a corrective message. Falls back to a minimal
47
- * `route: "fallback"` output on persistent failure.
48
- *
49
- * The LLM client is injected so unit tests can supply deterministic responses.
50
- */
51
- export async function route(
52
- input: RouterInputContext,
53
- client: RouterLlmClient,
54
- ): Promise<RouterOutput> {
55
- const prompt = buildRouterPrompt(input);
56
-
57
- let firstError: string | undefined;
58
- try {
59
- const raw = await client.complete(prompt);
60
- return postProcessRouterOutput(input.text, validateRouterOutput(raw));
61
- } catch (err) {
62
- firstError = err instanceof Error ? err.message : String(err);
63
- }
64
-
65
- // Retry once with error feedback.
66
- try {
67
- const retryPrompt = `${prompt}\n\n(Your previous response failed validation: ${firstError}. Return a valid JSON object conforming to RouterOutput. Nothing else.)`;
68
- const raw = await client.complete(retryPrompt);
69
- return postProcessRouterOutput(input.text, validateRouterOutput(raw));
70
- } catch {
71
- // Persistent failure — return a minimal fallback with regex-extracted symbols.
72
- return postProcessRouterOutput(input.text, minimalFallback(input.text));
73
- }
74
- }
75
-
76
- export function validateRouterOutput(raw: string): RouterOutput {
77
- const parsed = parseJsonPayload(raw);
78
-
79
- if (!parsed || typeof parsed !== "object") {
80
- throw new Error("router output was not a JSON object");
81
- }
82
- const obj = parsed as Record<string, unknown>;
83
-
84
- const rawMissingRequired = validateStringArray(obj.missing_required, "missing_required");
85
-
86
- const explicitRouteKind = obj.routeKind;
87
- if (
88
- explicitRouteKind !== undefined &&
89
- (typeof explicitRouteKind !== "string" || !isRouteKind(explicitRouteKind))
90
- ) {
91
- throw new Error(`invalid routeKind: ${JSON.stringify(explicitRouteKind)}`);
92
- }
93
-
94
- const rawRoute = obj.route;
95
- let route: RouterRoute;
96
- if (typeof rawRoute === "string") {
97
- if (!VALID_ROUTES.includes(rawRoute as RouterRoute)) {
98
- throw new Error(`invalid route: ${JSON.stringify(rawRoute)}`);
99
- }
100
- route = rawRoute as RouterRoute;
101
- } else if (typeof explicitRouteKind === "string" && isRouteKind(explicitRouteKind)) {
102
- route = legacyRouteForRouteKind(explicitRouteKind);
103
- } else {
104
- throw new Error(`invalid route: ${JSON.stringify(rawRoute)}`);
105
- }
106
-
107
- let workflow: RouterOutput["workflow"];
108
- const routeKind: RouterRouteKind =
109
- typeof explicitRouteKind === "string" && isRouteKind(explicitRouteKind)
110
- ? explicitRouteKind
111
- : routeKindFromLegacyRoute(route, rawMissingRequired);
112
-
113
- if (route === "workflow" || routeKind === "workflow_dispatch") {
114
- if (
115
- typeof obj.workflow !== "string" ||
116
- !VALID_WORKFLOWS.includes(obj.workflow as Exclude<WorkflowType, "unclassified">)
117
- ) {
118
- throw new Error(
119
- `workflow route requires a valid workflow; got ${JSON.stringify(obj.workflow)}`,
120
- );
121
- }
122
- workflow = obj.workflow as Exclude<WorkflowType, "unclassified">;
123
- } else if (
124
- typeof obj.workflow === "string" &&
125
- VALID_WORKFLOWS.includes(obj.workflow as Exclude<WorkflowType, "unclassified">)
126
- ) {
127
- workflow = obj.workflow as Exclude<WorkflowType, "unclassified">;
128
- }
129
-
130
- const entities = validateEntities(obj.entities);
131
- const slots = canonicalizeSymbolSlots(workflow, validateSlots(obj.slots));
132
- const preference_updates = validatePreferenceUpdates(obj.preference_updates);
133
- const missing_required = rawMissingRequired;
134
- const tool_bundles = validateToolBundles(obj.tool_bundles);
135
- const diagnostics = validateDiagnostics(obj.diagnostics);
136
- const reasoning = typeof obj.reasoning === "string" ? obj.reasoning : "";
137
-
138
- return {
139
- routeKind,
140
- route: legacyRouteForRouteKind(routeKind),
141
- workflow,
142
- entities,
143
- slots,
144
- preference_updates,
145
- missing_required,
146
- tool_bundles,
147
- diagnostics,
148
- reasoning,
149
- };
150
- }
151
-
152
- function parseJsonPayload(raw: string): unknown {
153
- const trimmed = raw.trim();
154
- // Tolerate ```json ... ``` fences even though the prompt forbids them.
155
- const stripped = trimmed
156
- .replace(/^```(?:json)?\s*/i, "")
157
- .replace(/\s*```$/i, "")
158
- .trim();
159
- try {
160
- return JSON.parse(stripped);
161
- } catch (err) {
162
- const msg = err instanceof Error ? err.message : String(err);
163
- throw new Error(`router output was not valid JSON: ${msg}`);
164
- }
165
- }
166
-
167
- function validateEntities(raw: unknown): ExtractedEntities {
168
- if (!raw || typeof raw !== "object") {
169
- throw new Error("entities must be an object");
170
- }
171
- const e = raw as Record<string, unknown>;
172
- const symbols = validateStringArray(e.symbols, "entities.symbols").map((s) => s.toUpperCase());
173
-
174
- const out: ExtractedEntities = { symbols };
175
- if (typeof e.budget === "number") out.budget = e.budget;
176
- if (typeof e.maxPremium === "number") out.maxPremium = e.maxPremium;
177
- if (typeof e.costBasis === "number") out.costBasis = e.costBasis;
178
- if (typeof e.shareQuantity === "number") out.shareQuantity = e.shareQuantity;
179
- if (typeof e.timeHorizon === "string") out.timeHorizon = e.timeHorizon;
180
- if (typeof e.riskProfile === "string") out.riskProfile = e.riskProfile;
181
- if (e.direction === "bullish" || e.direction === "bearish") out.direction = e.direction;
182
- if (typeof e.dteHint === "string") out.dteHint = e.dteHint;
183
- if (e.optionStrategy === "covered_call" || e.optionStrategy === "protective_put")
184
- out.optionStrategy = e.optionStrategy;
185
- if (typeof e.heldSymbol === "string") out.heldSymbol = e.heldSymbol.toUpperCase();
186
- const catalystSymbols = validateStringArray(e.catalystSymbols, "entities.catalystSymbols").map(
187
- (s) => s.toUpperCase(),
188
- );
189
- if (catalystSymbols.length > 0) out.catalystSymbols = catalystSymbols;
190
- const compareMetrics = validateStringArray(e.compareMetrics, "entities.compareMetrics");
191
- if (compareMetrics.length > 0) out.compareMetrics = compareMetrics;
192
- return out;
193
- }
194
-
195
- export function postProcessRouterOutput(text: string, output: RouterOutput): RouterOutput {
196
- const extracted = extractEntities(text);
197
- const deterministic = classifyWithLegacyRules(text);
198
- let diagnostics: RouterDiagnostic[] = [...output.diagnostics];
199
- let next: RouterOutput = {
200
- ...output,
201
- entities: {
202
- ...output.entities,
203
- symbols: output.entities.symbols.filter((symbol) => !isAmbiguousConceptUsage(text, symbol)),
204
- budget: output.entities.budget ?? extracted.budget,
205
- maxPremium: output.entities.maxPremium ?? extracted.maxPremium,
206
- timeHorizon: output.entities.timeHorizon ?? extracted.timeHorizon,
207
- riskProfile: output.entities.riskProfile ?? extracted.riskProfile,
208
- assetScope: output.entities.assetScope ?? extracted.assetScope,
209
- compareMetrics: mergeStringArrays(output.entities.compareMetrics, extracted.compareMetrics),
210
- direction: output.entities.direction ?? extracted.direction,
211
- optionStrategy: output.entities.optionStrategy ?? extracted.optionStrategy,
212
- costBasis: output.entities.costBasis ?? extracted.costBasis,
213
- shareQuantity: output.entities.shareQuantity ?? extracted.shareQuantity,
214
- heldSymbol: output.entities.heldSymbol ?? extracted.heldSymbol,
215
- catalystSymbols: output.entities.catalystSymbols ?? extracted.catalystSymbols,
216
- dteHint:
217
- output.entities.dteHint ??
218
- (output.workflow === "options_screener" ? extracted.dteHint : undefined),
219
- },
220
- diagnostics,
221
- };
222
-
223
- if (
224
- next.workflow === "options_screener" &&
225
- isExistingPositionOptionRequest(text, extracted) &&
226
- extracted.heldSymbol
227
- ) {
228
- const reorderedSymbols = [
229
- extracted.heldSymbol,
230
- ...mergeSymbols(next.entities.symbols, extracted.symbols).filter(
231
- (symbol) => symbol !== extracted.heldSymbol,
232
- ),
233
- ];
234
- if (next.entities.symbols[0] !== extracted.heldSymbol) {
235
- diagnostics.push({
236
- code:
237
- extracted.optionStrategy === "protective_put"
238
- ? "existing_position_underlying_corrected"
239
- : "covered_call_underlying_corrected",
240
- message: `using owned position ${extracted.heldSymbol} as the option-chain underlying`,
241
- });
242
- }
243
- next = {
244
- ...next,
245
- entities: {
246
- ...next.entities,
247
- symbols: reorderedSymbols,
248
- optionStrategy: extracted.optionStrategy ?? next.entities.optionStrategy,
249
- direction: extracted.direction ?? next.entities.direction,
250
- heldSymbol: extracted.heldSymbol,
251
- catalystSymbols: reorderedSymbols.filter((symbol) => symbol !== extracted.heldSymbol),
252
- costBasis: extracted.costBasis ?? next.entities.costBasis,
253
- shareQuantity: extracted.shareQuantity ?? next.entities.shareQuantity,
254
- dteHint: extracted.dteHint ?? next.entities.dteHint,
255
- },
256
- diagnostics,
257
- };
258
- }
259
-
260
- if (
261
- next.workflow === "options_screener" &&
262
- isOptionsEducationOrSuitabilityRequest(text) &&
263
- !isSpecificOptionContractSelectionRequest(text)
264
- ) {
265
- diagnostics.push({
266
- code: "options_workflow_corrected_to_policy_task",
267
- message:
268
- "options education or suitability prompt should use policy-card synthesis, not contract-screen workflow dispatch",
269
- });
270
- next = {
271
- ...next,
272
- routeKind: "agent_task",
273
- route: "fallback",
274
- workflow: "general_finance_qa",
275
- missing_required: [],
276
- diagnostics,
277
- };
278
- }
279
-
280
- if (
281
- next.workflow === "options_screener" &&
282
- next.entities.symbols.length >= 2 &&
283
- isPlainMultiAssetComparisonRequest(text)
284
- ) {
285
- diagnostics.push({
286
- code: "options_comparison_corrected_to_compare_assets",
287
- message:
288
- "explicit multi-asset comparison without option contract language should use compare_assets",
289
- });
290
- next = {
291
- ...next,
292
- routeKind: "workflow_dispatch",
293
- route: "workflow",
294
- workflow: "compare_assets",
295
- missing_required: [],
296
- entities: {
297
- ...next.entities,
298
- direction: undefined,
299
- dteHint: undefined,
300
- optionStrategy: undefined,
301
- },
302
- diagnostics,
303
- };
304
- }
305
-
306
- // Legacy rules may recover a primary route only when the LLM router path has
307
- // already failed validation. Otherwise they are limited to enrichment and
308
- // narrow corrections below.
309
- if (
310
- next.diagnostics.some((d) => d.code === "router_validation_failed") &&
311
- deterministic.workflow !== "unclassified"
312
- ) {
313
- next = {
314
- ...next,
315
- routeKind: isDispatchableWorkflow(deterministic.workflow)
316
- ? "workflow_dispatch"
317
- : "agent_task",
318
- route: isDispatchableWorkflow(deterministic.workflow) ? "workflow" : "fallback",
319
- workflow: deterministic.workflow,
320
- entities: {
321
- ...deterministic.entities,
322
- budget: deterministic.entities.budget ?? extracted.budget,
323
- maxPremium: deterministic.entities.maxPremium ?? extracted.maxPremium,
324
- timeHorizon: deterministic.entities.timeHorizon ?? extracted.timeHorizon,
325
- riskProfile: deterministic.entities.riskProfile ?? extracted.riskProfile,
326
- assetScope: deterministic.entities.assetScope ?? extracted.assetScope,
327
- compareMetrics: mergeStringArrays(
328
- deterministic.entities.compareMetrics,
329
- extracted.compareMetrics,
330
- ),
331
- direction: deterministic.entities.direction ?? extracted.direction,
332
- costBasis: deterministic.entities.costBasis ?? extracted.costBasis,
333
- shareQuantity: deterministic.entities.shareQuantity ?? extracted.shareQuantity,
334
- heldSymbol: deterministic.entities.heldSymbol ?? extracted.heldSymbol,
335
- catalystSymbols: deterministic.entities.catalystSymbols ?? extracted.catalystSymbols,
336
- },
337
- diagnostics: [
338
- ...diagnostics,
339
- {
340
- code: "deterministic_failure_recovery",
341
- message: `deterministic classifier selected ${deterministic.workflow} after router validation failure`,
342
- },
343
- ],
344
- reasoning: next.reasoning
345
- ? `${next.reasoning}; deterministic classifier selected ${deterministic.workflow}`
346
- : `deterministic classifier selected ${deterministic.workflow}`,
347
- };
348
- diagnostics = next.diagnostics;
349
- }
350
-
351
- if (next.routeKind === "workflow_dispatch" && !isDispatchableWorkflow(next.workflow)) {
352
- diagnostics.push({
353
- code: "route_kind_corrected_to_agent_task",
354
- message: next.workflow
355
- ? `${next.workflow} is not a dispatchable workflow`
356
- : "workflow_dispatch requires a dispatchable workflow",
357
- });
358
- next = {
359
- ...next,
360
- routeKind: "agent_task",
361
- route: "fallback",
362
- diagnostics,
363
- };
364
- }
365
-
366
- if (
367
- (next.workflow === "compare_assets" || next.workflow === "portfolio_builder") &&
368
- isStatefulTrackingRequest(text)
369
- ) {
370
- diagnostics.push({
371
- code: "stateful_tracking_corrected_to_agent_task",
372
- message:
373
- "portfolio/watchlist tracking mutation should use stateful tracking tools, not compare or construction workflow dispatch",
374
- });
375
- next = {
376
- ...next,
377
- routeKind: "agent_task",
378
- route: "fallback",
379
- workflow: "watchlist_or_tracking",
380
- missing_required: [],
381
- entities: {
382
- ...next.entities,
383
- symbols: filterCurrencyUnitSymbols(text, next.entities.symbols),
384
- },
385
- slots: removeCurrencyUnitSymbolSlots(text, next.slots),
386
- diagnostics,
387
- };
388
- }
389
-
390
- if (next.routeKind === "agent_task" && isDispatchableWorkflow(next.workflow)) {
391
- diagnostics.push({
392
- code: "dispatchable_workflow_corrected_to_workflow_dispatch",
393
- message: `${next.workflow} is a dispatchable workflow`,
394
- });
395
- next = {
396
- ...next,
397
- routeKind: "workflow_dispatch",
398
- route: "workflow",
399
- diagnostics,
400
- };
401
- }
402
-
403
- if (
404
- next.workflow === "compare_assets" &&
405
- next.entities.symbols.length === 0 &&
406
- isExplicitMacroDataRequest(text)
407
- ) {
408
- diagnostics.push({
409
- code: "compare_route_corrected_to_macro_task",
410
- message: "macro/source acronyms were not explicit tickers",
411
- });
412
- next = {
413
- ...next,
414
- routeKind: "agent_task",
415
- route: "fallback",
416
- workflow: "general_finance_qa",
417
- missing_required: [],
418
- diagnostics,
419
- };
420
- }
421
-
422
- if (next.workflow === "compare_assets" && isPortfolioEvaluationRequest(text)) {
423
- diagnostics.push({
424
- code: "portfolio_evaluation_corrected_to_agent_task",
425
- message:
426
- "existing portfolio/allocation risk review should not be reduced to asset comparison",
427
- });
428
- next = {
429
- ...next,
430
- routeKind: "agent_task",
431
- route: "fallback",
432
- workflow: "general_finance_qa",
433
- missing_required: [],
434
- diagnostics,
435
- };
436
- }
437
-
438
- if (
439
- next.routeKind === "agent_task" &&
440
- !next.workflow &&
441
- next.entities.symbols.length === 0 &&
442
- isExplicitMacroDataRequest(text)
443
- ) {
444
- diagnostics.push({
445
- code: "macro_task_inferred_from_prompt",
446
- message: "macro data terms were present without explicit tickers",
447
- });
448
- next = {
449
- ...next,
450
- workflow: "general_finance_qa",
451
- diagnostics,
452
- };
453
- }
454
-
455
- if (next.workflow === "portfolio_builder" && isCryptoSizingRequest(text)) {
456
- diagnostics.push({
457
- code: "crypto_sizing_corrected_to_agent_task",
458
- message:
459
- "crypto allocation-range and drawdown questions are advisory tradeoffs, not portfolio construction",
460
- });
461
- next = {
462
- ...next,
463
- routeKind: "agent_task",
464
- route: "fallback",
465
- workflow: "general_finance_qa",
466
- missing_required: [],
467
- diagnostics,
468
- };
469
- }
470
-
471
- if (next.workflow === "portfolio_builder" && isPortfolioEvaluationRequest(text)) {
472
- diagnostics.push({
473
- code: "portfolio_evaluation_corrected_to_agent_task",
474
- message:
475
- "existing portfolio/allocation evaluation does not require portfolio-construction budget",
476
- });
477
- next = {
478
- ...next,
479
- routeKind: "agent_task",
480
- route: "fallback",
481
- workflow: "general_finance_qa",
482
- missing_required: [],
483
- diagnostics,
484
- };
485
- }
486
-
487
- if (
488
- next.workflow === "portfolio_builder" &&
489
- next.entities.symbols.length >= 2 &&
490
- isPortfolioTradeoffComparisonRequest(text)
491
- ) {
492
- diagnostics.push({
493
- code: "portfolio_tradeoff_corrected_to_compare_assets",
494
- message:
495
- "explicit multi-asset tradeoff question should compare the requested assets before constructing a portfolio",
496
- });
497
- next = {
498
- ...next,
499
- routeKind: "workflow_dispatch",
500
- route: "workflow",
501
- workflow: "compare_assets",
502
- missing_required: [],
503
- diagnostics,
504
- };
505
- }
506
-
507
- if (next.workflow === "single_asset_analysis" && isSpecializedSingleAssetPolicyRequest(text)) {
508
- diagnostics.push({
509
- code: "single_asset_workflow_corrected_to_general_policy_task",
510
- message: "prompt asks for policy-card planning outside a single-asset buy/sell analysis",
511
- });
512
- next = {
513
- ...next,
514
- workflow: "general_finance_qa",
515
- diagnostics,
516
- };
517
- }
518
-
519
- const disambiguated = disambiguateSymbols(next.entities.symbols, text);
520
- if (disambiguated.dropped.length > 0) {
521
- for (const drop of disambiguated.dropped) {
522
- diagnostics.push({
523
- code: "symbol_dropped",
524
- message: `${drop.token} dropped: ${drop.reason}`,
525
- details: {
526
- token: drop.token,
527
- reason: drop.reason,
528
- signalsChecked: drop.signalsChecked,
529
- source: "llm",
530
- },
531
- });
532
- }
533
- next = {
534
- ...next,
535
- entities: {
536
- ...next.entities,
537
- symbols: disambiguated.kept,
538
- },
539
- slots: removeDroppedSymbolSlots(
540
- next.slots,
541
- disambiguated.dropped.map((drop) => drop.token),
542
- ),
543
- diagnostics,
544
- };
545
- }
546
-
547
- const missingRequired = computeMissingRequiredSlots(
548
- next.workflow,
549
- next.entities,
550
- next.slots,
551
- next.missing_required,
552
- );
553
- if (missingRequired.length > 0 && next.routeKind !== "pass_through") {
554
- if (next.routeKind !== "clarification") {
555
- diagnostics.push({
556
- code: "route_kind_corrected_to_clarification",
557
- message: `missing required slots: ${missingRequired.join(", ")}`,
558
- });
559
- }
560
- next = {
561
- ...next,
562
- routeKind: "clarification",
563
- route: "fallback",
564
- missing_required: missingRequired,
565
- diagnostics,
566
- };
567
- }
568
-
569
- const selectedToolBundles = isConceptualEducationRequest(text, next)
570
- ? []
571
- : selectToolBundles(next);
572
- if (selectedToolBundles.length === 0 && isConceptualEducationRequest(text, next)) {
573
- diagnostics.push({
574
- code: "conceptual_education_no_tools",
575
- message: "conceptual education prompt does not need live finance tools",
576
- });
577
- }
578
- const emittedUnsupported = next.tool_bundles.filter(
579
- (bundle) => !selectedToolBundles.includes(bundle),
580
- );
581
- if (emittedUnsupported.length > 0) {
582
- diagnostics.push({
583
- code: "tool_bundles_corrected",
584
- message: `unsupported emitted bundles dropped: ${emittedUnsupported.join(", ")}`,
585
- });
586
- }
587
-
588
- return omitUndefined({
589
- ...next,
590
- route: legacyRouteForRouteKind(next.routeKind),
591
- tool_bundles: selectedToolBundles,
592
- diagnostics,
593
- });
594
- }
595
-
596
- function isExplicitMacroDataRequest(text: string): boolean {
597
- return /\b(?:get_economic_data|fred|cpi|inflation|fed\s+funds?|unemployment|gdp|macro)\b/i.test(
598
- text,
599
- );
600
- }
601
-
602
- function isConceptualEducationRequest(text: string, output: RouterOutput): boolean {
603
- if (output.routeKind !== "agent_task") return false;
604
- if (output.entities.symbols.length > 0) return false;
605
- if (isForwardLookingMacroContextRequest(text)) return false;
606
- if (
607
- /\b(?:current|recent|today|right now|latest|news|sentiment|build|portfolio|buy|sell|allocate|compare)\b/i.test(
608
- text,
609
- )
610
- ) {
611
- return false;
612
- }
613
- return /\b(?:explain|what is|define|how (?:do|should|to)|teach me|help me understand)\b/i.test(
614
- text,
615
- );
616
- }
617
-
618
- function isForwardLookingMacroContextRequest(text: string): boolean {
619
- return (
620
- /\b(?:rates?|rate\s*cuts?|fed|inflation|macro)\b/i.test(text) &&
621
- /\b(?:next\s+(?:year|12\s*months?)|over\s+the\s+next|outlook|affect|impact|falling|rising)\b/i.test(
622
- text,
623
- )
624
- );
625
- }
626
-
627
- function isCoveredCallRequest(text: string): boolean {
628
- return /\bcovered\s+calls?\b/i.test(text);
629
- }
630
-
631
- function isPortfolioEvaluationRequest(text: string): boolean {
632
- const lower = text.toLowerCase();
633
- const hasEvaluationIntent =
634
- /\b(?:evaluat(?:e|ion)|review|assess|analy[sz]e|prospects?|risks?|risky|opportunities?|mitigat(?:e|ion)|adjust(?:ment)?|change|rebalance|diversify|concentration|overweight|underweight|expos(?:ed|ure)|target\s+bands?|drift|worried|crash|protect|protection|missing\s+out\s+on\s+growth)\b/.test(
635
- lower,
636
- );
637
- const hasExplicitPortfolioSubject =
638
- /\b(?:portfolio|allocation|asset\s+allocation|60\/40|holdings?|positions?)\b/.test(lower);
639
- const hasOwnedAssetMix =
640
- /\b(?:my|current|have|holding|hold|own|invested|positions?|\d+(?:\.\d+)?%)\b/.test(lower) &&
641
- /\b(?:equity|fixed\s+income|bonds?|cash|stocks?|etfs?|funds?)\b/.test(lower);
642
- const hasConstructionIntent =
643
- /\b(?:build|create|construct|put\s+together|invest|allocate)\b/.test(lower) &&
644
- /\$\s*\d|\b\d+(?:\.\d+)?\s*k\b|\bbudget\b|\bcapital\b/.test(lower);
645
- return (
646
- hasEvaluationIntent &&
647
- (hasExplicitPortfolioSubject || hasOwnedAssetMix) &&
648
- !hasConstructionIntent
649
- );
650
- }
651
-
652
- function isStatefulTrackingRequest(text: string): boolean {
653
- const lower = text.toLowerCase();
654
- const hasPortfolioConstructionIntent =
655
- /\b(?:build|create|construct|put\s+together)\b/.test(lower) &&
656
- /\bportfolio\b/.test(lower) &&
657
- /\$\s*\d|\b\d+(?:\.\d+)?\s*k\b|\bbudget\b|\bcapital\b/.test(lower);
658
- const hasStateVerb =
659
- /\b(?:add|remove|update|record|track|create|configure|check|show|list|view|cancel)\b/.test(
660
- lower,
661
- );
662
- const hasStateObject =
663
- /\b(?:watchlist|portfolio|holding|holdings|position|positions|alert|alerts|daily\s+report|watchlist\s+report|report\s+history)\b/.test(
664
- lower,
665
- );
666
- const hasPortfolioLotShape =
667
- /\b(?:add|record|track)\b/.test(lower) &&
668
- /\b\d+(?:\.\d+)?\s+shares?\b/.test(lower) &&
669
- /\b(?:portfolio|holding|holdings|position|positions)\b/.test(lower);
670
- if (hasPortfolioConstructionIntent) return false;
671
- return (hasStateVerb && hasStateObject) || hasPortfolioLotShape;
672
- }
673
-
674
- function filterCurrencyUnitSymbols(text: string, symbols: string[]): string[] {
675
- return symbols.filter((symbol) => !isCurrencyCodeUsage(text, symbol));
676
- }
677
-
678
- function removeCurrencyUnitSymbolSlots(
679
- text: string,
680
- slots: Record<string, RouterSlot>,
681
- ): Record<string, RouterSlot> {
682
- const next = { ...slots };
683
- for (const key of ["symbol", "symbols"]) {
684
- const slot = next[key];
685
- if (!slot) continue;
686
- if (Array.isArray(slot.value)) {
687
- const value = slot.value.filter(
688
- (item) => typeof item !== "string" || !isCurrencyCodeUsage(text, item.toUpperCase()),
689
- );
690
- if (value.length === 0) delete next[key];
691
- else next[key] = { ...slot, value };
692
- continue;
693
- }
694
- if (typeof slot.value === "string" && isCurrencyCodeUsage(text, slot.value.toUpperCase())) {
695
- delete next[key];
696
- }
697
- }
698
- return next;
699
- }
700
-
701
- function isPortfolioTradeoffComparisonRequest(text: string): boolean {
702
- const lower = text.toLowerCase();
703
- return (
704
- /\b(?:prioritize|tradeoffs?|growth[-\s]?oriented|dividend|income|which\s+(?:one|is)\s+better|should\s+i)\b/.test(
705
- lower,
706
- ) && /\b(?:or|vs\.?|versus|compare)\b/.test(lower)
707
- );
708
- }
709
-
710
- function isCryptoSizingRequest(text: string): boolean {
711
- const lower = text.toLowerCase();
712
- const hasPortfolioConstructionIntent =
713
- /\b(?:build|create|construct|put\s+together)\b/.test(lower) &&
714
- /\b(?:portfolio|allocation)\b/.test(lower);
715
- if (hasPortfolioConstructionIntent) return false;
716
- return (
717
- /\b(?:btc|bitcoin|crypto)\b/.test(lower) &&
718
- /\b(?:allocation|range|position\s+size|sizing|exposure|drawdown)\b/.test(lower)
719
- );
720
- }
721
-
722
- function isSpecializedSingleAssetPolicyRequest(text: string): boolean {
723
- const lower = text.toLowerCase();
724
- return (
725
- /\b(?:ticker|symbol|formerly|old ticker|earnings are|earnings tonight)\b/.test(lower) ||
726
- /\b(?:today|right now|this morning|after close|moved|catalyst)\b/.test(lower) ||
727
- /\b(?:sentiment|mood|reddit|twitter|x\/twitter)\b/.test(lower) ||
728
- /\b(?:filing|10-k|10-q|8-k|sec)\b/.test(lower)
729
- );
730
- }
731
-
732
- function isExistingPositionOptionRequest(text: string, extracted: ExtractedEntities): boolean {
733
- return isCoveredCallRequest(text) || extracted.optionStrategy === "protective_put";
734
- }
735
-
736
- function isOptionsEducationOrSuitabilityRequest(text: string): boolean {
737
- const lower = text.toLowerCase();
738
- return (
739
- /\b(?:how\s+does|how\s+do|explain|what\s+is|good\s+idea|make\s+sense|suitable|suitability|is\s+it\s+(?:good|worth|smart))\b/.test(
740
- lower,
741
- ) &&
742
- /\b(?:covered\s+calls?|protective\s+puts?|options?|selling\s+calls?|option\s+income)\b/.test(
743
- lower,
744
- )
745
- );
746
- }
747
-
748
- function isPlainMultiAssetComparisonRequest(text: string): boolean {
749
- const lower = text.toLowerCase();
750
- const hasCompareIntent =
751
- /\bcompare\b/.test(lower) ||
752
- /\bvs\.?\b/.test(lower) ||
753
- /\bversus\b/.test(lower) ||
754
- /\bwhich\s+is\s+better\b/.test(lower);
755
- return hasCompareIntent && !hasExplicitOptionContractLanguage(lower);
756
- }
757
-
758
- function hasExplicitOptionContractLanguage(lower: string): boolean {
759
- return (
760
- /\bcalls?\b(?!\s+out\b)/.test(lower) ||
761
- /\bputs?\b/.test(lower) ||
762
- /\boption(?:s)?\s*chain\b/.test(lower) ||
763
- /\boptions?\b/.test(lower) ||
764
- /\b(?:strike|expiration|dte|premium|delta|theta|greeks?|contract)\b/.test(lower)
765
- );
766
- }
767
-
768
- function isSpecificOptionContractSelectionRequest(text: string): boolean {
769
- const lower = text.toLowerCase();
770
- return (
771
- /\b(?:best|which|what\s+(?:strike|contract|option)|rank|screen|specific|right\s+now|today|around\s+earnings|expiration|dte|premium\s+under)\b/.test(
772
- lower,
773
- ) && /\b(?:sell|buy|trade|contract|strike|expiration|premium|call|put)\b/.test(lower)
774
- );
775
- }
776
-
777
- function mergeSymbols(primary: string[], secondary: string[]): string[] {
778
- const merged: string[] = [];
779
- for (const symbol of [...primary, ...secondary]) {
780
- if (!merged.includes(symbol)) merged.push(symbol);
781
- }
782
- return merged;
783
- }
784
-
785
- function mergeStringArrays(primary?: string[], secondary?: string[]): string[] | undefined {
786
- const merged: string[] = [];
787
- for (const value of [...(primary ?? []), ...(secondary ?? [])]) {
788
- if (!merged.includes(value)) merged.push(value);
789
- }
790
- return merged.length > 0 ? merged : undefined;
791
- }
792
-
793
- function omitUndefined<T>(value: T): T {
794
- if (Array.isArray(value)) return value.map(omitUndefined) as T;
795
- if (!value || typeof value !== "object") return value;
796
- const out: Record<string, unknown> = {};
797
- for (const [key, entry] of Object.entries(value)) {
798
- if (entry !== undefined) out[key] = omitUndefined(entry);
799
- }
800
- return out as T;
801
- }
802
-
803
- function validateSlots(raw: unknown): Record<string, RouterSlot> {
804
- if (raw === undefined || raw === null) return {};
805
- if (typeof raw !== "object") {
806
- throw new Error("slots must be an object");
807
- }
808
- const out: Record<string, RouterSlot> = {};
809
- for (const [key, val] of Object.entries(raw as Record<string, unknown>)) {
810
- if (!val || typeof val !== "object") {
811
- throw new Error(`slot ${key} must be an object`);
812
- }
813
- const s = val as Record<string, unknown>;
814
- if (!VALID_SOURCES.has(s.source as string)) {
815
- throw new Error(`slot ${key} has invalid source: ${JSON.stringify(s.source)}`);
816
- }
817
- if (!VALID_CONFIDENCE.has(s.confidence as string)) {
818
- throw new Error(`slot ${key} has invalid confidence: ${JSON.stringify(s.confidence)}`);
819
- }
820
- const canonicalKey = canonicalSlotKey(key);
821
- out[canonicalKey] = {
822
- value: s.value,
823
- source: s.source as RouterSlot["source"],
824
- confidence: s.confidence as RouterSlot["confidence"],
825
- };
826
- }
827
- return out;
828
- }
829
-
830
- // The slot contract uses snake_case keys; non-Claude router models sometimes
831
- // emit camelCase (timeHorizon, riskProfile). Canonicalize deterministically so
832
- // downstream slot resolution and missing-required checks match.
833
- function canonicalSlotKey(key: string): string {
834
- return key.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
835
- }
836
-
837
- // Models also drift between scalar `symbol` and one-element `symbols` slot
838
- // shapes. Canonicalize toward the workflow's manifest-declared required slot
839
- // name when the conversion is unambiguous.
840
- function canonicalizeSymbolSlots(
841
- workflow: RouterOutput["workflow"],
842
- slots: Record<string, RouterSlot>,
843
- ): Record<string, RouterSlot> {
844
- if (!workflow) return slots;
845
- const required = workflowRequiredSlots(workflow);
846
- const next = { ...slots };
847
- if (required.includes("symbol") && next.symbol == null && next.symbols != null) {
848
- const value = next.symbols.value;
849
- if (Array.isArray(value) && value.length === 1) {
850
- next.symbol = { ...next.symbols, value: value[0] };
851
- delete next.symbols;
852
- }
853
- }
854
- if (required.includes("symbols") && next.symbols == null && next.symbol != null) {
855
- const value = next.symbol.value;
856
- if (typeof value === "string" && value.length > 0) {
857
- next.symbols = { ...next.symbol, value: [value] };
858
- delete next.symbol;
859
- }
860
- }
861
- return next;
862
- }
863
-
864
- function validatePreferenceUpdates(raw: unknown): RouterPreferenceUpdate[] {
865
- if (raw === undefined || raw === null) return [];
866
- if (!Array.isArray(raw)) {
867
- throw new Error("preference_updates must be an array");
868
- }
869
- return raw.map((item, idx) => {
870
- if (!item || typeof item !== "object") {
871
- throw new Error(`preference_updates[${idx}] must be an object`);
872
- }
873
- const p = item as Record<string, unknown>;
874
- if (typeof p.key !== "string" || p.key.length === 0) {
875
- throw new Error(`preference_updates[${idx}].key must be a non-empty string`);
876
- }
877
- if (typeof p.value !== "string") {
878
- throw new Error(`preference_updates[${idx}].value must be a string`);
879
- }
880
- if (!VALID_CONFIDENCE.has(p.confidence as string)) {
881
- throw new Error(`preference_updates[${idx}].confidence is invalid`);
882
- }
883
- // Router-emitted preferences are always inferred — absent is accepted
884
- // (normalized), but any explicit non-"inferred" value is an invariant
885
- // violation the caller should see rather than silently lose.
886
- if (p.source !== undefined && p.source !== "inferred") {
887
- throw new Error(
888
- `preference_updates[${idx}].source must be "inferred" (got ${JSON.stringify(p.source)})`,
889
- );
890
- }
891
- return {
892
- key: p.key,
893
- value: p.value,
894
- confidence: p.confidence as RouterPreferenceUpdate["confidence"],
895
- source: "inferred",
896
- };
897
- });
898
- }
899
-
900
- function validateToolBundles(raw: unknown): ToolBundleName[] {
901
- const bundles = validateStringArray(raw, "tool_bundles");
902
- return bundles.filter(isToolBundleName);
903
- }
904
-
905
- function removeDroppedSymbolSlots(
906
- slots: Record<string, RouterSlot>,
907
- droppedTokens: string[],
908
- ): Record<string, RouterSlot> {
909
- if (droppedTokens.length === 0) return slots;
910
- const dropped = new Set(droppedTokens.map((token) => token.toUpperCase()));
911
- const next = { ...slots };
912
-
913
- for (const key of ["symbol", "symbols"]) {
914
- const slot = next[key];
915
- if (!slot) continue;
916
- if (Array.isArray(slot.value)) {
917
- const value = slot.value.filter(
918
- (item) => typeof item !== "string" || !dropped.has(item.toUpperCase()),
919
- );
920
- if (value.length === 0) {
921
- delete next[key];
922
- } else {
923
- next[key] = { ...slot, value };
924
- }
925
- continue;
926
- }
927
- if (typeof slot.value === "string" && dropped.has(slot.value.toUpperCase())) {
928
- delete next[key];
929
- }
930
- }
931
-
932
- return next;
933
- }
934
-
935
- function validateDiagnostics(raw: unknown): RouterDiagnostic[] {
936
- if (raw === undefined || raw === null) return [];
937
- if (!Array.isArray(raw)) {
938
- throw new Error("diagnostics must be an array");
939
- }
940
- return raw.map((item, idx) => {
941
- if (!item || typeof item !== "object") {
942
- throw new Error(`diagnostics[${idx}] must be an object`);
943
- }
944
- const diagnostic = item as Record<string, unknown>;
945
- if (typeof diagnostic.code !== "string" || diagnostic.code.length === 0) {
946
- throw new Error(`diagnostics[${idx}].code must be a non-empty string`);
947
- }
948
- if (typeof diagnostic.message !== "string") {
949
- throw new Error(`diagnostics[${idx}].message must be a string`);
950
- }
951
- const out: RouterDiagnostic = {
952
- code: diagnostic.code,
953
- message: diagnostic.message,
954
- };
955
- if (
956
- diagnostic.details &&
957
- typeof diagnostic.details === "object" &&
958
- !Array.isArray(diagnostic.details)
959
- ) {
960
- out.details = diagnostic.details as Record<string, unknown>;
961
- }
962
- return out;
963
- });
964
- }
965
-
966
- function validateStringArray(raw: unknown, field: string): string[] {
967
- if (raw === undefined || raw === null) return [];
968
- if (!Array.isArray(raw)) {
969
- throw new Error(`${field} must be an array`);
970
- }
971
- return raw.map((item, idx) => {
972
- if (typeof item !== "string") {
973
- throw new Error(`${field}[${idx}] must be a string`);
974
- }
975
- return item;
976
- });
977
- }
978
-
979
- function minimalFallback(text: string): RouterOutput {
980
- const entities = extractEntities(text);
981
- return {
982
- routeKind: "agent_task",
983
- route: "fallback",
984
- entities,
985
- slots: {},
986
- preference_updates: [],
987
- missing_required: [],
988
- tool_bundles: [],
989
- diagnostics: [
990
- {
991
- code: "router_validation_failed",
992
- message: "router validation failed persistently; emitted minimal fallback",
993
- },
994
- ],
995
- reasoning: "router validation failed; emitted minimal fallback",
996
- };
997
- }