opencandle 0.11.1 → 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 (653) hide show
  1. package/README.md +20 -24
  2. package/dist/analysts/contracts.js +0 -1
  3. package/dist/analysts/orchestrator.js +0 -1
  4. package/dist/cli-main.js +13 -7
  5. package/dist/cli-options.d.ts +4 -0
  6. package/dist/cli-options.js +33 -0
  7. package/dist/cli.js +8 -3
  8. package/dist/config.js +0 -1
  9. package/dist/doctor/cli-command.js +2 -1
  10. package/dist/doctor/render.js +0 -1
  11. package/dist/doctor/report.js +40 -11
  12. package/dist/gui/server/ask-user-bridge.d.ts +19 -0
  13. package/dist/gui/server/ask-user-bridge.js +55 -0
  14. package/dist/gui/server/automation-heartbeat.d.ts +25 -0
  15. package/dist/gui/server/automation-heartbeat.js +61 -0
  16. package/dist/gui/server/background-quotes.d.ts +39 -0
  17. package/dist/gui/server/background-quotes.js +71 -0
  18. package/dist/gui/server/chat-event-adapter.d.ts +16 -0
  19. package/dist/gui/server/chat-event-adapter.js +263 -0
  20. package/dist/gui/server/gui-session-manager.d.ts +2 -0
  21. package/dist/gui/server/gui-session-manager.js +4 -0
  22. package/dist/gui/server/http-routes.d.ts +69 -0
  23. package/dist/gui/server/http-routes.js +1008 -0
  24. package/dist/gui/server/invoke-tool.d.ts +47 -0
  25. package/dist/gui/server/invoke-tool.js +373 -0
  26. package/dist/gui/server/live-chat-event-adapter.d.ts +19 -0
  27. package/dist/gui/server/live-chat-event-adapter.js +206 -0
  28. package/dist/gui/server/local-session-coordinator.d.ts +26 -0
  29. package/dist/gui/server/local-session-coordinator.js +53 -0
  30. package/dist/gui/server/market-state-api.d.ts +138 -0
  31. package/dist/gui/server/market-state-api.js +355 -0
  32. package/dist/gui/server/model-setup.d.ts +64 -0
  33. package/dist/gui/server/model-setup.js +150 -0
  34. package/dist/gui/server/private-api-access.d.ts +6 -0
  35. package/dist/gui/server/private-api-access.js +53 -0
  36. package/dist/gui/server/projector.d.ts +49 -0
  37. package/dist/gui/server/projector.js +296 -0
  38. package/dist/gui/server/prompt-observation.d.ts +8 -0
  39. package/dist/gui/server/prompt-observation.js +43 -0
  40. package/dist/gui/server/quote-snapshot-store.d.ts +14 -0
  41. package/dist/gui/server/quote-snapshot-store.js +49 -0
  42. package/dist/gui/server/server.d.ts +1 -0
  43. package/dist/gui/server/server.js +259 -0
  44. package/dist/gui/server/session-actions.d.ts +60 -0
  45. package/dist/gui/server/session-actions.js +218 -0
  46. package/dist/gui/server/session-entry-wait.d.ts +27 -0
  47. package/dist/gui/server/session-entry-wait.js +129 -0
  48. package/dist/gui/server/session-list.d.ts +2 -0
  49. package/dist/gui/server/session-list.js +11 -0
  50. package/dist/gui/server/shutdown.d.ts +10 -0
  51. package/dist/gui/server/shutdown.js +29 -0
  52. package/dist/gui/server/tool-invoke-ack.d.ts +17 -0
  53. package/dist/gui/server/tool-invoke-ack.js +26 -0
  54. package/dist/gui/server/tool-metadata.d.ts +93 -0
  55. package/dist/gui/server/tool-metadata.js +148 -0
  56. package/dist/gui/server/websocket.d.ts +9 -0
  57. package/dist/gui/server/websocket.js +124 -0
  58. package/dist/gui/server/writer-lock.d.ts +1 -0
  59. package/dist/gui/server/writer-lock.js +1 -0
  60. package/dist/gui/server/ws-hub.d.ts +50 -0
  61. package/dist/gui/server/ws-hub.js +284 -0
  62. package/dist/gui/shared/chat-events.d.ts +174 -0
  63. package/dist/gui/shared/chat-events.js +13 -0
  64. package/dist/gui/shared/event-reducer.d.ts +3 -0
  65. package/dist/gui/shared/event-reducer.js +187 -0
  66. package/dist/index.js +0 -1
  67. package/dist/infra/cache.js +0 -1
  68. package/dist/infra/freshness.js +0 -1
  69. package/dist/infra/http-client.js +1 -2
  70. package/dist/infra/index.js +0 -1
  71. package/dist/infra/market-calendar.js +0 -1
  72. package/dist/infra/native-dependencies.js +0 -1
  73. package/dist/infra/node-version.js +0 -1
  74. package/dist/infra/open-url.js +0 -1
  75. package/dist/infra/opencandle-paths.js +0 -1
  76. package/dist/infra/rate-limiter.js +0 -1
  77. package/dist/market-state/alert-conditions.js +0 -1
  78. package/dist/market-state/alert-runner.d.ts +1 -0
  79. package/dist/market-state/alert-runner.js +5 -4
  80. package/dist/market-state/daily-report.js +0 -1
  81. package/dist/market-state/local-automation-service.js +0 -1
  82. package/dist/market-state/notification-delivery.js +0 -1
  83. package/dist/market-state/resolve-for-mutation.js +0 -1
  84. package/dist/market-state/resolve.js +0 -1
  85. package/dist/market-state/service.d.ts +26 -21
  86. package/dist/market-state/service.js +175 -36
  87. package/dist/market-state/summaries.js +1 -13
  88. package/dist/memory/index.js +0 -1
  89. package/dist/memory/manager.js +0 -1
  90. package/dist/memory/preference-extractor.js +0 -1
  91. package/dist/memory/retrieval.js +0 -1
  92. package/dist/memory/sqlite.js +60 -11
  93. package/dist/memory/storage.js +0 -1
  94. package/dist/memory/tool-defaults.js +0 -1
  95. package/dist/memory/types.js +0 -1
  96. package/dist/monitor.js +0 -1
  97. package/dist/onboarding/connect.js +0 -1
  98. package/dist/onboarding/credential-interceptor.js +0 -1
  99. package/dist/onboarding/degradation-accumulator.js +0 -1
  100. package/dist/onboarding/prompt-user.d.ts +1 -1
  101. package/dist/onboarding/prompt-user.js +0 -1
  102. package/dist/onboarding/provider-status.js +0 -1
  103. package/dist/onboarding/providers.js +0 -1
  104. package/dist/onboarding/state.js +0 -1
  105. package/dist/onboarding/tool-helpers.js +0 -1
  106. package/dist/onboarding/tool-tags.js +0 -1
  107. package/dist/onboarding/validate-model-key.d.ts +17 -0
  108. package/dist/onboarding/validate-model-key.js +54 -0
  109. package/dist/onboarding/validation.js +0 -1
  110. package/dist/pi/opencandle-extension.js +2 -2
  111. package/dist/pi/session-action-dedupe.js +0 -1
  112. package/dist/pi/session-storage.js +0 -1
  113. package/dist/pi/session-writer-lock.js +0 -1
  114. package/dist/pi/session.js +0 -1
  115. package/dist/pi/setup.d.ts +2 -0
  116. package/dist/pi/setup.js +10 -3
  117. package/dist/pi/tool-adapter.js +0 -1
  118. package/dist/pi/tui-session-coordinator.js +0 -1
  119. package/dist/prompts/context-builder.js +1 -2
  120. package/dist/prompts/disclaimer.js +0 -1
  121. package/dist/prompts/policy-cards.js +0 -1
  122. package/dist/prompts/sections.js +0 -1
  123. package/dist/prompts/symbol-preflight.js +0 -1
  124. package/dist/prompts/workflow-prompts.js +0 -1
  125. package/dist/providers/alpha-vantage.js +2 -3
  126. package/dist/providers/coingecko.js +0 -1
  127. package/dist/providers/errors.js +0 -1
  128. package/dist/providers/exa-search.js +11 -10
  129. package/dist/providers/external-tool-command.js +0 -1
  130. package/dist/providers/external-tool-error.js +0 -1
  131. package/dist/providers/fear-greed.js +0 -1
  132. package/dist/providers/finnhub.js +0 -1
  133. package/dist/providers/fred.js +0 -1
  134. package/dist/providers/index.js +0 -1
  135. package/dist/providers/polymarket.js +0 -1
  136. package/dist/providers/provider-credential-error.js +0 -1
  137. package/dist/providers/reddit-cli.js +0 -1
  138. package/dist/providers/reddit.js +0 -1
  139. package/dist/providers/sec-edgar.js +0 -1
  140. package/dist/providers/tradingview.js +1 -2
  141. package/dist/providers/twitter-cli.js +0 -1
  142. package/dist/providers/twitter.js +0 -1
  143. package/dist/providers/web-search.js +15 -12
  144. package/dist/providers/with-fallback.js +0 -1
  145. package/dist/providers/wrap-provider.js +0 -1
  146. package/dist/providers/yahoo-finance.js +67 -4
  147. package/dist/routing/classify-intent.js +0 -1
  148. package/dist/routing/defaults.js +0 -1
  149. package/dist/routing/entity-extractor.js +2 -3
  150. package/dist/routing/fund-symbols.js +0 -1
  151. package/dist/routing/horizon.js +0 -1
  152. package/dist/routing/index.js +0 -1
  153. package/dist/routing/legacy-rule-router.js +0 -1
  154. package/dist/routing/planning.js +0 -1
  155. package/dist/routing/route-manifest.js +0 -1
  156. package/dist/routing/router-llm-client.d.ts +2 -2
  157. package/dist/routing/router-llm-client.js +0 -1
  158. package/dist/routing/router-prompt.js +0 -1
  159. package/dist/routing/router-types.js +0 -1
  160. package/dist/routing/router.js +1 -2
  161. package/dist/routing/slot-resolver.js +0 -1
  162. package/dist/routing/symbol-disambiguator.js +0 -1
  163. package/dist/routing/turn-context.js +0 -1
  164. package/dist/routing/types.js +0 -1
  165. package/dist/runtime/answer-contracts.js +0 -1
  166. package/dist/runtime/artifact-contracts.js +0 -1
  167. package/dist/runtime/evidence.js +0 -1
  168. package/dist/runtime/numeric-claims.js +0 -1
  169. package/dist/runtime/planning-evidence.js +0 -1
  170. package/dist/runtime/prompt-step.js +0 -1
  171. package/dist/runtime/provider-tracker.js +0 -1
  172. package/dist/runtime/run-context.js +0 -1
  173. package/dist/runtime/session-coordinator.js +0 -1
  174. package/dist/runtime/session-title.js +0 -1
  175. package/dist/runtime/tool-defaults-wrapper.js +0 -1
  176. package/dist/runtime/validation.js +0 -1
  177. package/dist/runtime/workflow-events.js +0 -1
  178. package/dist/runtime/workflow-runner.d.ts +1 -0
  179. package/dist/runtime/workflow-runner.js +8 -3
  180. package/dist/runtime/workflow-types.js +0 -1
  181. package/dist/sentiment/adapters/finnhub.js +0 -1
  182. package/dist/sentiment/adapters/reddit.js +0 -1
  183. package/dist/sentiment/adapters/twitter.js +0 -1
  184. package/dist/sentiment/adapters/web.js +0 -1
  185. package/dist/sentiment/index.js +4 -2
  186. package/dist/sentiment/insights.js +0 -1
  187. package/dist/sentiment/keywords.js +0 -1
  188. package/dist/sentiment/pipeline.js +0 -1
  189. package/dist/sentiment/scorer.js +0 -1
  190. package/dist/sentiment/store.js +0 -1
  191. package/dist/sentiment/trends.js +0 -1
  192. package/dist/sentiment/types.js +0 -1
  193. package/dist/system-prompt.js +0 -1
  194. package/dist/tool-kit.js +0 -1
  195. package/dist/tools/fundamentals/company-overview.d.ts +1 -1
  196. package/dist/tools/fundamentals/company-overview.js +2 -1
  197. package/dist/tools/fundamentals/comps.js +6 -4
  198. package/dist/tools/fundamentals/dcf.js +0 -1
  199. package/dist/tools/fundamentals/earnings.d.ts +1 -1
  200. package/dist/tools/fundamentals/earnings.js +2 -1
  201. package/dist/tools/fundamentals/financials.js +2 -1
  202. package/dist/tools/fundamentals/sec-filings.js +0 -1
  203. package/dist/tools/index.d.ts +116 -2
  204. package/dist/tools/index.js +0 -1
  205. package/dist/tools/interaction/ask-user.js +11 -1
  206. package/dist/tools/macro/event-probabilities.js +0 -1
  207. package/dist/tools/macro/fear-greed.d.ts +1 -1
  208. package/dist/tools/macro/fear-greed.js +0 -1
  209. package/dist/tools/macro/fred-data.d.ts +1 -1
  210. package/dist/tools/macro/fred-data.js +2 -1
  211. package/dist/tools/market/crypto-history.js +0 -1
  212. package/dist/tools/market/crypto-price.d.ts +2 -2
  213. package/dist/tools/market/crypto-price.js +0 -1
  214. package/dist/tools/market/screen-stocks.js +0 -1
  215. package/dist/tools/market/search-ticker.js +1 -2
  216. package/dist/tools/market/stock-history.js +0 -1
  217. package/dist/tools/market/stock-quote.d.ts +2 -2
  218. package/dist/tools/market/stock-quote.js +0 -1
  219. package/dist/tools/options/greeks.js +0 -1
  220. package/dist/tools/options/option-chain.d.ts +2 -2
  221. package/dist/tools/options/option-chain.js +0 -1
  222. package/dist/tools/portfolio/alerts.d.ts +2 -1
  223. package/dist/tools/portfolio/alerts.js +228 -2
  224. package/dist/tools/portfolio/correlation.js +23 -5
  225. package/dist/tools/portfolio/daily-report.js +0 -1
  226. package/dist/tools/portfolio/holdings-overlap.js +0 -1
  227. package/dist/tools/portfolio/notifications.js +0 -1
  228. package/dist/tools/portfolio/risk-analysis.d.ts +1 -1
  229. package/dist/tools/portfolio/risk-analysis.js +0 -1
  230. package/dist/tools/portfolio/tracker.d.ts +3 -1
  231. package/dist/tools/portfolio/tracker.js +57 -10
  232. package/dist/tools/portfolio/watchlist.d.ts +3 -6
  233. package/dist/tools/portfolio/watchlist.js +101 -110
  234. package/dist/tools/sentiment/insight-format.js +0 -1
  235. package/dist/tools/sentiment/query-match.js +0 -1
  236. package/dist/tools/sentiment/reddit-sentiment.js +0 -1
  237. package/dist/tools/sentiment/sentiment-summary.js +8 -4
  238. package/dist/tools/sentiment/sentiment-trend.d.ts +5 -1
  239. package/dist/tools/sentiment/sentiment-trend.js +6 -2
  240. package/dist/tools/sentiment/twitter-sentiment.js +0 -1
  241. package/dist/tools/sentiment/untrusted-text.js +0 -1
  242. package/dist/tools/sentiment/web-search.d.ts +1 -1
  243. package/dist/tools/sentiment/web-search.js +0 -1
  244. package/dist/tools/sentiment/web-sentiment.js +0 -1
  245. package/dist/tools/technical/backtest.js +0 -1
  246. package/dist/tools/technical/indicators.js +0 -1
  247. package/dist/types/fundamentals.js +0 -1
  248. package/dist/types/index.js +0 -1
  249. package/dist/types/macro.js +0 -1
  250. package/dist/types/market.d.ts +6 -0
  251. package/dist/types/market.js +0 -1
  252. package/dist/types/options.js +0 -1
  253. package/dist/types/portfolio.js +0 -1
  254. package/dist/types/prediction-markets.js +0 -1
  255. package/dist/types/sentiment.js +0 -1
  256. package/dist/workflows/compare-assets.js +0 -1
  257. package/dist/workflows/index.js +0 -1
  258. package/dist/workflows/options-screener.js +0 -1
  259. package/dist/workflows/portfolio-builder.js +0 -1
  260. package/gui/web/dist/assets/CatalogOverlay-CAc7e3Pf.js +1 -0
  261. package/gui/web/dist/assets/index-BOEKd9wT.css +2 -0
  262. package/gui/web/dist/assets/index-C-H05cQ2.js +65 -0
  263. package/gui/web/dist/index.html +2 -2
  264. package/package.json +11 -12
  265. package/dist/analysts/contracts.js.map +0 -1
  266. package/dist/analysts/orchestrator.js.map +0 -1
  267. package/dist/cli-main.js.map +0 -1
  268. package/dist/cli.js.map +0 -1
  269. package/dist/config.js.map +0 -1
  270. package/dist/doctor/cli-command.js.map +0 -1
  271. package/dist/doctor/render.js.map +0 -1
  272. package/dist/doctor/report.js.map +0 -1
  273. package/dist/index.js.map +0 -1
  274. package/dist/infra/cache.js.map +0 -1
  275. package/dist/infra/freshness.js.map +0 -1
  276. package/dist/infra/http-client.js.map +0 -1
  277. package/dist/infra/index.js.map +0 -1
  278. package/dist/infra/market-calendar.js.map +0 -1
  279. package/dist/infra/native-dependencies.js.map +0 -1
  280. package/dist/infra/node-version.js.map +0 -1
  281. package/dist/infra/open-url.js.map +0 -1
  282. package/dist/infra/opencandle-paths.js.map +0 -1
  283. package/dist/infra/rate-limiter.js.map +0 -1
  284. package/dist/market-state/alert-conditions.js.map +0 -1
  285. package/dist/market-state/alert-runner.js.map +0 -1
  286. package/dist/market-state/daily-report.js.map +0 -1
  287. package/dist/market-state/local-automation-service.js.map +0 -1
  288. package/dist/market-state/notification-delivery.js.map +0 -1
  289. package/dist/market-state/resolve-for-mutation.js.map +0 -1
  290. package/dist/market-state/resolve.js.map +0 -1
  291. package/dist/market-state/service.js.map +0 -1
  292. package/dist/market-state/summaries.js.map +0 -1
  293. package/dist/memory/index.js.map +0 -1
  294. package/dist/memory/manager.js.map +0 -1
  295. package/dist/memory/preference-extractor.js.map +0 -1
  296. package/dist/memory/retrieval.js.map +0 -1
  297. package/dist/memory/sqlite.js.map +0 -1
  298. package/dist/memory/storage.js.map +0 -1
  299. package/dist/memory/tool-defaults.js.map +0 -1
  300. package/dist/memory/types.js.map +0 -1
  301. package/dist/monitor.js.map +0 -1
  302. package/dist/onboarding/connect.js.map +0 -1
  303. package/dist/onboarding/credential-interceptor.js.map +0 -1
  304. package/dist/onboarding/degradation-accumulator.js.map +0 -1
  305. package/dist/onboarding/prompt-user.js.map +0 -1
  306. package/dist/onboarding/provider-status.js.map +0 -1
  307. package/dist/onboarding/providers.js.map +0 -1
  308. package/dist/onboarding/state.js.map +0 -1
  309. package/dist/onboarding/tool-helpers.js.map +0 -1
  310. package/dist/onboarding/tool-tags.js.map +0 -1
  311. package/dist/onboarding/validation.js.map +0 -1
  312. package/dist/pi/opencandle-extension.js.map +0 -1
  313. package/dist/pi/session-action-dedupe.js.map +0 -1
  314. package/dist/pi/session-storage.js.map +0 -1
  315. package/dist/pi/session-writer-lock.js.map +0 -1
  316. package/dist/pi/session.js.map +0 -1
  317. package/dist/pi/setup.js.map +0 -1
  318. package/dist/pi/tool-adapter.js.map +0 -1
  319. package/dist/pi/tui-session-coordinator.js.map +0 -1
  320. package/dist/prompts/context-builder.js.map +0 -1
  321. package/dist/prompts/disclaimer.js.map +0 -1
  322. package/dist/prompts/policy-cards.js.map +0 -1
  323. package/dist/prompts/sections.js.map +0 -1
  324. package/dist/prompts/symbol-preflight.js.map +0 -1
  325. package/dist/prompts/workflow-prompts.js.map +0 -1
  326. package/dist/providers/alpha-vantage.js.map +0 -1
  327. package/dist/providers/coingecko.js.map +0 -1
  328. package/dist/providers/errors.js.map +0 -1
  329. package/dist/providers/exa-search.js.map +0 -1
  330. package/dist/providers/external-tool-command.js.map +0 -1
  331. package/dist/providers/external-tool-error.js.map +0 -1
  332. package/dist/providers/fear-greed.js.map +0 -1
  333. package/dist/providers/finnhub.js.map +0 -1
  334. package/dist/providers/fred.js.map +0 -1
  335. package/dist/providers/index.js.map +0 -1
  336. package/dist/providers/polymarket.js.map +0 -1
  337. package/dist/providers/provider-credential-error.js.map +0 -1
  338. package/dist/providers/reddit-cli.js.map +0 -1
  339. package/dist/providers/reddit.js.map +0 -1
  340. package/dist/providers/sec-edgar.js.map +0 -1
  341. package/dist/providers/tradingview.js.map +0 -1
  342. package/dist/providers/twitter-cli.js.map +0 -1
  343. package/dist/providers/twitter.js.map +0 -1
  344. package/dist/providers/web-search.js.map +0 -1
  345. package/dist/providers/with-fallback.js.map +0 -1
  346. package/dist/providers/wrap-provider.js.map +0 -1
  347. package/dist/providers/yahoo-finance.js.map +0 -1
  348. package/dist/routing/classify-intent.js.map +0 -1
  349. package/dist/routing/defaults.js.map +0 -1
  350. package/dist/routing/entity-extractor.js.map +0 -1
  351. package/dist/routing/fund-symbols.js.map +0 -1
  352. package/dist/routing/horizon.js.map +0 -1
  353. package/dist/routing/index.js.map +0 -1
  354. package/dist/routing/legacy-rule-router.js.map +0 -1
  355. package/dist/routing/planning.js.map +0 -1
  356. package/dist/routing/route-manifest.js.map +0 -1
  357. package/dist/routing/router-llm-client.js.map +0 -1
  358. package/dist/routing/router-prompt.js.map +0 -1
  359. package/dist/routing/router-types.js.map +0 -1
  360. package/dist/routing/router.js.map +0 -1
  361. package/dist/routing/slot-resolver.js.map +0 -1
  362. package/dist/routing/symbol-disambiguator.js.map +0 -1
  363. package/dist/routing/turn-context.js.map +0 -1
  364. package/dist/routing/types.js.map +0 -1
  365. package/dist/runtime/answer-contracts.js.map +0 -1
  366. package/dist/runtime/artifact-contracts.js.map +0 -1
  367. package/dist/runtime/evidence.js.map +0 -1
  368. package/dist/runtime/numeric-claims.js.map +0 -1
  369. package/dist/runtime/planning-evidence.js.map +0 -1
  370. package/dist/runtime/prompt-step.js.map +0 -1
  371. package/dist/runtime/provider-tracker.js.map +0 -1
  372. package/dist/runtime/run-context.js.map +0 -1
  373. package/dist/runtime/session-coordinator.js.map +0 -1
  374. package/dist/runtime/session-title.js.map +0 -1
  375. package/dist/runtime/tool-defaults-wrapper.js.map +0 -1
  376. package/dist/runtime/validation.js.map +0 -1
  377. package/dist/runtime/workflow-events.js.map +0 -1
  378. package/dist/runtime/workflow-runner.js.map +0 -1
  379. package/dist/runtime/workflow-types.js.map +0 -1
  380. package/dist/sentiment/adapters/finnhub.js.map +0 -1
  381. package/dist/sentiment/adapters/reddit.js.map +0 -1
  382. package/dist/sentiment/adapters/twitter.js.map +0 -1
  383. package/dist/sentiment/adapters/web.js.map +0 -1
  384. package/dist/sentiment/index.js.map +0 -1
  385. package/dist/sentiment/insights.js.map +0 -1
  386. package/dist/sentiment/keywords.js.map +0 -1
  387. package/dist/sentiment/pipeline.js.map +0 -1
  388. package/dist/sentiment/scorer.js.map +0 -1
  389. package/dist/sentiment/store.js.map +0 -1
  390. package/dist/sentiment/trends.js.map +0 -1
  391. package/dist/sentiment/types.js.map +0 -1
  392. package/dist/system-prompt.js.map +0 -1
  393. package/dist/tool-kit.js.map +0 -1
  394. package/dist/tools/fundamentals/company-overview.js.map +0 -1
  395. package/dist/tools/fundamentals/comps.js.map +0 -1
  396. package/dist/tools/fundamentals/dcf.js.map +0 -1
  397. package/dist/tools/fundamentals/earnings.js.map +0 -1
  398. package/dist/tools/fundamentals/financials.js.map +0 -1
  399. package/dist/tools/fundamentals/sec-filings.js.map +0 -1
  400. package/dist/tools/index.js.map +0 -1
  401. package/dist/tools/interaction/ask-user.js.map +0 -1
  402. package/dist/tools/macro/event-probabilities.js.map +0 -1
  403. package/dist/tools/macro/fear-greed.js.map +0 -1
  404. package/dist/tools/macro/fred-data.js.map +0 -1
  405. package/dist/tools/market/crypto-history.js.map +0 -1
  406. package/dist/tools/market/crypto-price.js.map +0 -1
  407. package/dist/tools/market/screen-stocks.js.map +0 -1
  408. package/dist/tools/market/search-ticker.js.map +0 -1
  409. package/dist/tools/market/stock-history.js.map +0 -1
  410. package/dist/tools/market/stock-quote.js.map +0 -1
  411. package/dist/tools/options/greeks.js.map +0 -1
  412. package/dist/tools/options/option-chain.js.map +0 -1
  413. package/dist/tools/portfolio/alerts.js.map +0 -1
  414. package/dist/tools/portfolio/correlation.js.map +0 -1
  415. package/dist/tools/portfolio/daily-report.js.map +0 -1
  416. package/dist/tools/portfolio/holdings-overlap.js.map +0 -1
  417. package/dist/tools/portfolio/notifications.js.map +0 -1
  418. package/dist/tools/portfolio/risk-analysis.js.map +0 -1
  419. package/dist/tools/portfolio/tracker.js.map +0 -1
  420. package/dist/tools/portfolio/watchlist.js.map +0 -1
  421. package/dist/tools/sentiment/insight-format.js.map +0 -1
  422. package/dist/tools/sentiment/query-match.js.map +0 -1
  423. package/dist/tools/sentiment/reddit-sentiment.js.map +0 -1
  424. package/dist/tools/sentiment/sentiment-summary.js.map +0 -1
  425. package/dist/tools/sentiment/sentiment-trend.js.map +0 -1
  426. package/dist/tools/sentiment/twitter-sentiment.js.map +0 -1
  427. package/dist/tools/sentiment/untrusted-text.js.map +0 -1
  428. package/dist/tools/sentiment/web-search.js.map +0 -1
  429. package/dist/tools/sentiment/web-sentiment.js.map +0 -1
  430. package/dist/tools/technical/backtest.js.map +0 -1
  431. package/dist/tools/technical/indicators.js.map +0 -1
  432. package/dist/types/fundamentals.js.map +0 -1
  433. package/dist/types/index.js.map +0 -1
  434. package/dist/types/macro.js.map +0 -1
  435. package/dist/types/market.js.map +0 -1
  436. package/dist/types/options.js.map +0 -1
  437. package/dist/types/portfolio.js.map +0 -1
  438. package/dist/types/prediction-markets.js.map +0 -1
  439. package/dist/types/sentiment.js.map +0 -1
  440. package/dist/workflows/compare-assets.js.map +0 -1
  441. package/dist/workflows/index.js.map +0 -1
  442. package/dist/workflows/options-screener.js.map +0 -1
  443. package/dist/workflows/portfolio-builder.js.map +0 -1
  444. package/gui/server/ask-user-bridge.ts +0 -89
  445. package/gui/server/automation-heartbeat.ts +0 -97
  446. package/gui/server/background-quotes.ts +0 -127
  447. package/gui/server/chat-event-adapter.ts +0 -294
  448. package/gui/server/gui-session-manager.ts +0 -5
  449. package/gui/server/http-routes.ts +0 -1201
  450. package/gui/server/invoke-tool.ts +0 -490
  451. package/gui/server/live-chat-event-adapter.ts +0 -243
  452. package/gui/server/local-session-coordinator.ts +0 -97
  453. package/gui/server/market-state-api.ts +0 -331
  454. package/gui/server/model-setup.ts +0 -254
  455. package/gui/server/package.json +0 -5
  456. package/gui/server/private-api-access.ts +0 -62
  457. package/gui/server/projector.ts +0 -392
  458. package/gui/server/prompt-observation.ts +0 -58
  459. package/gui/server/quote-snapshot-store.ts +0 -50
  460. package/gui/server/server.ts +0 -289
  461. package/gui/server/session-actions.ts +0 -323
  462. package/gui/server/session-entry-wait.ts +0 -179
  463. package/gui/server/shutdown.ts +0 -47
  464. package/gui/server/tool-invoke-ack.ts +0 -49
  465. package/gui/server/tool-metadata.ts +0 -167
  466. package/gui/server/websocket.ts +0 -138
  467. package/gui/server/writer-lock.ts +0 -1
  468. package/gui/server/ws-hub.ts +0 -403
  469. package/gui/shared/chat-events.ts +0 -165
  470. package/gui/shared/event-reducer.ts +0 -220
  471. package/gui/web/dist/assets/CatalogOverlay-DZ1niyQm.js +0 -1
  472. package/gui/web/dist/assets/index-D4F9AJnn.css +0 -2
  473. package/gui/web/dist/assets/index-DtqMMBTr.js +0 -65
  474. package/src/analysts/contracts.ts +0 -176
  475. package/src/analysts/orchestrator.ts +0 -244
  476. package/src/cli-main.ts +0 -510
  477. package/src/cli.ts +0 -17
  478. package/src/config.ts +0 -272
  479. package/src/doctor/cli-command.ts +0 -83
  480. package/src/doctor/render.ts +0 -37
  481. package/src/doctor/report.ts +0 -638
  482. package/src/index.ts +0 -5
  483. package/src/infra/cache.ts +0 -127
  484. package/src/infra/freshness.ts +0 -165
  485. package/src/infra/http-client.ts +0 -134
  486. package/src/infra/index.ts +0 -14
  487. package/src/infra/market-calendar.ts +0 -193
  488. package/src/infra/native-dependencies.ts +0 -84
  489. package/src/infra/node-version.ts +0 -23
  490. package/src/infra/open-url.ts +0 -28
  491. package/src/infra/opencandle-paths.ts +0 -53
  492. package/src/infra/rate-limiter.ts +0 -77
  493. package/src/market-state/alert-conditions.ts +0 -82
  494. package/src/market-state/alert-runner.ts +0 -863
  495. package/src/market-state/daily-report.ts +0 -237
  496. package/src/market-state/local-automation-service.ts +0 -162
  497. package/src/market-state/notification-delivery.ts +0 -158
  498. package/src/market-state/resolve-for-mutation.ts +0 -24
  499. package/src/market-state/resolve.ts +0 -112
  500. package/src/market-state/service.ts +0 -2208
  501. package/src/market-state/summaries.ts +0 -75
  502. package/src/memory/index.ts +0 -10
  503. package/src/memory/manager.ts +0 -190
  504. package/src/memory/preference-extractor.ts +0 -106
  505. package/src/memory/retrieval.ts +0 -71
  506. package/src/memory/sqlite.ts +0 -577
  507. package/src/memory/storage.ts +0 -195
  508. package/src/memory/tool-defaults.ts +0 -108
  509. package/src/memory/types.ts +0 -71
  510. package/src/monitor.ts +0 -123
  511. package/src/onboarding/connect.ts +0 -177
  512. package/src/onboarding/credential-interceptor.ts +0 -122
  513. package/src/onboarding/degradation-accumulator.ts +0 -77
  514. package/src/onboarding/prompt-user.ts +0 -85
  515. package/src/onboarding/provider-status.ts +0 -382
  516. package/src/onboarding/providers.ts +0 -442
  517. package/src/onboarding/state.ts +0 -216
  518. package/src/onboarding/tool-helpers.ts +0 -104
  519. package/src/onboarding/tool-tags.ts +0 -244
  520. package/src/onboarding/validation.ts +0 -152
  521. package/src/pi/opencandle-extension.ts +0 -1294
  522. package/src/pi/session-action-dedupe.ts +0 -155
  523. package/src/pi/session-storage.ts +0 -5
  524. package/src/pi/session-writer-lock.ts +0 -426
  525. package/src/pi/session.ts +0 -84
  526. package/src/pi/setup.ts +0 -399
  527. package/src/pi/tool-adapter.ts +0 -49
  528. package/src/pi/tui-session-coordinator.ts +0 -351
  529. package/src/prompts/context-builder.ts +0 -326
  530. package/src/prompts/disclaimer.ts +0 -9
  531. package/src/prompts/policy-cards.ts +0 -228
  532. package/src/prompts/sections.ts +0 -46
  533. package/src/prompts/symbol-preflight.ts +0 -80
  534. package/src/prompts/workflow-prompts.ts +0 -504
  535. package/src/providers/alpha-vantage.ts +0 -340
  536. package/src/providers/coingecko.ts +0 -95
  537. package/src/providers/errors.ts +0 -9
  538. package/src/providers/exa-search.ts +0 -375
  539. package/src/providers/external-tool-command.ts +0 -164
  540. package/src/providers/external-tool-error.ts +0 -20
  541. package/src/providers/fear-greed.ts +0 -45
  542. package/src/providers/finnhub.ts +0 -125
  543. package/src/providers/fred.ts +0 -83
  544. package/src/providers/index.ts +0 -17
  545. package/src/providers/polymarket.ts +0 -214
  546. package/src/providers/provider-credential-error.ts +0 -23
  547. package/src/providers/reddit-cli.ts +0 -286
  548. package/src/providers/reddit.ts +0 -106
  549. package/src/providers/sec-edgar.ts +0 -326
  550. package/src/providers/tradingview.ts +0 -399
  551. package/src/providers/twitter-cli.ts +0 -202
  552. package/src/providers/twitter.ts +0 -102
  553. package/src/providers/web-search.ts +0 -303
  554. package/src/providers/with-fallback.ts +0 -42
  555. package/src/providers/wrap-provider.ts +0 -105
  556. package/src/providers/yahoo-finance.ts +0 -984
  557. package/src/routing/classify-intent.ts +0 -380
  558. package/src/routing/defaults.ts +0 -29
  559. package/src/routing/entity-extractor.ts +0 -557
  560. package/src/routing/fund-symbols.ts +0 -58
  561. package/src/routing/horizon.ts +0 -7
  562. package/src/routing/index.ts +0 -70
  563. package/src/routing/legacy-rule-router.ts +0 -13
  564. package/src/routing/planning.ts +0 -829
  565. package/src/routing/route-manifest.ts +0 -308
  566. package/src/routing/router-llm-client.ts +0 -64
  567. package/src/routing/router-prompt.ts +0 -159
  568. package/src/routing/router-types.ts +0 -84
  569. package/src/routing/router.ts +0 -1332
  570. package/src/routing/slot-resolver.ts +0 -213
  571. package/src/routing/symbol-disambiguator.ts +0 -72
  572. package/src/routing/turn-context.ts +0 -108
  573. package/src/routing/types.ts +0 -77
  574. package/src/runtime/answer-contracts.ts +0 -693
  575. package/src/runtime/artifact-contracts.ts +0 -77
  576. package/src/runtime/evidence.ts +0 -78
  577. package/src/runtime/numeric-claims.ts +0 -108
  578. package/src/runtime/planning-evidence.ts +0 -597
  579. package/src/runtime/prompt-step.ts +0 -185
  580. package/src/runtime/provider-tracker.ts +0 -40
  581. package/src/runtime/run-context.ts +0 -32
  582. package/src/runtime/session-coordinator.ts +0 -1037
  583. package/src/runtime/session-title.ts +0 -60
  584. package/src/runtime/tool-defaults-wrapper.ts +0 -43
  585. package/src/runtime/validation.ts +0 -211
  586. package/src/runtime/workflow-events.ts +0 -77
  587. package/src/runtime/workflow-runner.ts +0 -182
  588. package/src/runtime/workflow-types.ts +0 -105
  589. package/src/sentiment/adapters/finnhub.ts +0 -49
  590. package/src/sentiment/adapters/reddit.ts +0 -65
  591. package/src/sentiment/adapters/twitter.ts +0 -36
  592. package/src/sentiment/adapters/web.ts +0 -44
  593. package/src/sentiment/index.ts +0 -49
  594. package/src/sentiment/insights.ts +0 -269
  595. package/src/sentiment/keywords.ts +0 -31
  596. package/src/sentiment/pipeline.ts +0 -91
  597. package/src/sentiment/scorer.ts +0 -89
  598. package/src/sentiment/store.ts +0 -260
  599. package/src/sentiment/trends.ts +0 -96
  600. package/src/sentiment/types.ts +0 -112
  601. package/src/system-prompt.ts +0 -115
  602. package/src/tool-kit.ts +0 -69
  603. package/src/tools/AGENTS.md +0 -36
  604. package/src/tools/fundamentals/company-overview.ts +0 -64
  605. package/src/tools/fundamentals/comps.ts +0 -180
  606. package/src/tools/fundamentals/dcf.ts +0 -447
  607. package/src/tools/fundamentals/earnings.ts +0 -57
  608. package/src/tools/fundamentals/financials.ts +0 -63
  609. package/src/tools/fundamentals/sec-filings.ts +0 -105
  610. package/src/tools/index.ts +0 -104
  611. package/src/tools/interaction/ask-user.ts +0 -93
  612. package/src/tools/macro/event-probabilities.ts +0 -141
  613. package/src/tools/macro/fear-greed.ts +0 -41
  614. package/src/tools/macro/fred-data.ts +0 -92
  615. package/src/tools/market/crypto-history.ts +0 -72
  616. package/src/tools/market/crypto-price.ts +0 -65
  617. package/src/tools/market/screen-stocks.ts +0 -290
  618. package/src/tools/market/search-ticker.ts +0 -254
  619. package/src/tools/market/stock-history.ts +0 -104
  620. package/src/tools/market/stock-quote.ts +0 -73
  621. package/src/tools/options/greeks.ts +0 -81
  622. package/src/tools/options/option-chain.ts +0 -134
  623. package/src/tools/portfolio/alerts.ts +0 -457
  624. package/src/tools/portfolio/correlation.ts +0 -189
  625. package/src/tools/portfolio/daily-report.ts +0 -107
  626. package/src/tools/portfolio/holdings-overlap.ts +0 -139
  627. package/src/tools/portfolio/notifications.ts +0 -45
  628. package/src/tools/portfolio/risk-analysis.ts +0 -173
  629. package/src/tools/portfolio/tracker.ts +0 -308
  630. package/src/tools/portfolio/watchlist.ts +0 -288
  631. package/src/tools/sentiment/insight-format.ts +0 -50
  632. package/src/tools/sentiment/query-match.ts +0 -117
  633. package/src/tools/sentiment/reddit-sentiment.ts +0 -403
  634. package/src/tools/sentiment/sentiment-summary.ts +0 -383
  635. package/src/tools/sentiment/sentiment-trend.ts +0 -75
  636. package/src/tools/sentiment/twitter-sentiment.ts +0 -287
  637. package/src/tools/sentiment/untrusted-text.ts +0 -21
  638. package/src/tools/sentiment/web-search.ts +0 -186
  639. package/src/tools/sentiment/web-sentiment.ts +0 -96
  640. package/src/tools/technical/backtest.ts +0 -336
  641. package/src/tools/technical/indicators.ts +0 -281
  642. package/src/types/fundamentals.ts +0 -47
  643. package/src/types/index.ts +0 -26
  644. package/src/types/macro.ts +0 -27
  645. package/src/types/market.ts +0 -46
  646. package/src/types/options.ts +0 -53
  647. package/src/types/portfolio.ts +0 -83
  648. package/src/types/prediction-markets.ts +0 -13
  649. package/src/types/sentiment.ts +0 -129
  650. package/src/workflows/compare-assets.ts +0 -89
  651. package/src/workflows/index.ts +0 -3
  652. package/src/workflows/options-screener.ts +0 -125
  653. package/src/workflows/portfolio-builder.ts +0 -63
@@ -1,1332 +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 { mapDteHintToTarget } from "./slot-resolver.js";
30
- import { disambiguateSymbols } from "./symbol-disambiguator.js";
31
- import type { ExtractedEntities, WorkflowType } from "./types.js";
32
-
33
- const VALID_ROUTES: readonly RouterRoute[] = ["workflow", "fallback"];
34
- const VALID_WORKFLOWS: ReadonlyArray<Exclude<WorkflowType, "unclassified">> = [
35
- "portfolio_builder",
36
- "options_screener",
37
- "compare_assets",
38
- "single_asset_analysis",
39
- "watchlist_or_tracking",
40
- "general_finance_qa",
41
- ];
42
- const VALID_SOURCES = new Set(["user", "preference", "default", "prior_context", "memory"]);
43
- const VALID_CONFIDENCE = new Set(["high", "medium", "low"]);
44
-
45
- /**
46
- * Run the LLM router against the given input context. Retries once on
47
- * validation failure with a corrective message. Falls back to a minimal
48
- * `route: "fallback"` output on persistent failure.
49
- *
50
- * The LLM client is injected so unit tests can supply deterministic responses.
51
- */
52
- export async function route(
53
- input: RouterInputContext,
54
- client: RouterLlmClient,
55
- ): Promise<RouterOutput> {
56
- const prompt = buildRouterPrompt(input);
57
-
58
- let firstError: string | undefined;
59
- try {
60
- const raw = await client.complete(prompt);
61
- return postProcessRouterOutput(input.text, validateRouterOutput(raw), input);
62
- } catch (err) {
63
- firstError = err instanceof Error ? err.message : String(err);
64
- }
65
-
66
- // Retry once with error feedback.
67
- try {
68
- const retryPrompt = `${prompt}\n\n(Your previous response failed validation: ${firstError}. Return a valid JSON object conforming to RouterOutput. Nothing else.)`;
69
- const raw = await client.complete(retryPrompt);
70
- return postProcessRouterOutput(input.text, validateRouterOutput(raw), input);
71
- } catch {
72
- // Persistent failure — return a minimal fallback with regex-extracted symbols.
73
- return postProcessRouterOutput(input.text, minimalFallback(input.text), input);
74
- }
75
- }
76
-
77
- export function validateRouterOutput(raw: string): RouterOutput {
78
- const parsed = parseJsonPayload(raw);
79
-
80
- if (!parsed || typeof parsed !== "object") {
81
- throw new Error("router output was not a JSON object");
82
- }
83
- const obj = parsed as Record<string, unknown>;
84
-
85
- const rawMissingRequired = validateStringArray(obj.missing_required, "missing_required");
86
-
87
- const explicitRouteKind = obj.routeKind;
88
- if (
89
- explicitRouteKind !== undefined &&
90
- (typeof explicitRouteKind !== "string" || !isRouteKind(explicitRouteKind))
91
- ) {
92
- throw new Error(`invalid routeKind: ${JSON.stringify(explicitRouteKind)}`);
93
- }
94
-
95
- const rawRoute = obj.route;
96
- let route: RouterRoute;
97
- if (typeof rawRoute === "string") {
98
- if (!VALID_ROUTES.includes(rawRoute as RouterRoute)) {
99
- throw new Error(`invalid route: ${JSON.stringify(rawRoute)}`);
100
- }
101
- route = rawRoute as RouterRoute;
102
- } else if (typeof explicitRouteKind === "string" && isRouteKind(explicitRouteKind)) {
103
- route = legacyRouteForRouteKind(explicitRouteKind);
104
- } else {
105
- throw new Error(`invalid route: ${JSON.stringify(rawRoute)}`);
106
- }
107
-
108
- let workflow: RouterOutput["workflow"];
109
- const routeKind: RouterRouteKind =
110
- typeof explicitRouteKind === "string" && isRouteKind(explicitRouteKind)
111
- ? explicitRouteKind
112
- : routeKindFromLegacyRoute(route, rawMissingRequired);
113
-
114
- if (route === "workflow" || routeKind === "workflow_dispatch") {
115
- if (
116
- typeof obj.workflow !== "string" ||
117
- !VALID_WORKFLOWS.includes(obj.workflow as Exclude<WorkflowType, "unclassified">)
118
- ) {
119
- throw new Error(
120
- `workflow route requires a valid workflow; got ${JSON.stringify(obj.workflow)}`,
121
- );
122
- }
123
- workflow = obj.workflow as Exclude<WorkflowType, "unclassified">;
124
- } else if (
125
- typeof obj.workflow === "string" &&
126
- VALID_WORKFLOWS.includes(obj.workflow as Exclude<WorkflowType, "unclassified">)
127
- ) {
128
- workflow = obj.workflow as Exclude<WorkflowType, "unclassified">;
129
- }
130
-
131
- const entities = validateEntities(obj.entities);
132
- const slots = canonicalizeSymbolSlots(workflow, validateSlots(obj.slots));
133
- const preference_updates = validatePreferenceUpdates(obj.preference_updates);
134
- const missing_required = rawMissingRequired;
135
- const tool_bundles = validateToolBundles(obj.tool_bundles);
136
- const diagnostics = validateDiagnostics(obj.diagnostics);
137
- const reasoning = typeof obj.reasoning === "string" ? obj.reasoning : "";
138
-
139
- return {
140
- routeKind,
141
- route: legacyRouteForRouteKind(routeKind),
142
- workflow,
143
- entities,
144
- slots,
145
- preference_updates,
146
- missing_required,
147
- tool_bundles,
148
- diagnostics,
149
- reasoning,
150
- };
151
- }
152
-
153
- function parseJsonPayload(raw: string): unknown {
154
- const trimmed = raw.trim();
155
- // Tolerate ```json ... ``` fences even though the prompt forbids them.
156
- const stripped = trimmed
157
- .replace(/^```(?:json)?\s*/i, "")
158
- .replace(/\s*```$/i, "")
159
- .trim();
160
- try {
161
- return JSON.parse(stripped);
162
- } catch (err) {
163
- const msg = err instanceof Error ? err.message : String(err);
164
- throw new Error(`router output was not valid JSON: ${msg}`);
165
- }
166
- }
167
-
168
- function validateEntities(raw: unknown): ExtractedEntities {
169
- if (!raw || typeof raw !== "object") {
170
- throw new Error("entities must be an object");
171
- }
172
- const e = raw as Record<string, unknown>;
173
- const symbols = validateStringArray(e.symbols, "entities.symbols").map((s) => s.toUpperCase());
174
-
175
- const out: ExtractedEntities = { symbols };
176
- if (typeof e.budget === "number") out.budget = e.budget;
177
- if (typeof e.maxPremium === "number") out.maxPremium = e.maxPremium;
178
- if (typeof e.costBasis === "number") out.costBasis = e.costBasis;
179
- if (typeof e.shareQuantity === "number") out.shareQuantity = e.shareQuantity;
180
- if (typeof e.timeHorizon === "string") out.timeHorizon = e.timeHorizon;
181
- if (typeof e.riskProfile === "string") out.riskProfile = e.riskProfile;
182
- if (e.direction === "bullish" || e.direction === "bearish") out.direction = e.direction;
183
- if (typeof e.dteHint === "string") out.dteHint = e.dteHint;
184
- if (e.optionStrategy === "covered_call" || e.optionStrategy === "protective_put")
185
- out.optionStrategy = e.optionStrategy;
186
- if (typeof e.heldSymbol === "string") out.heldSymbol = e.heldSymbol.toUpperCase();
187
- const catalystSymbols = validateStringArray(e.catalystSymbols, "entities.catalystSymbols").map(
188
- (s) => s.toUpperCase(),
189
- );
190
- if (catalystSymbols.length > 0) out.catalystSymbols = catalystSymbols;
191
- const compareMetrics = validateStringArray(e.compareMetrics, "entities.compareMetrics");
192
- if (compareMetrics.length > 0) out.compareMetrics = compareMetrics;
193
- return out;
194
- }
195
-
196
- export function postProcessRouterOutput(
197
- text: string,
198
- output: RouterOutput,
199
- inputContext?: Pick<RouterInputContext, "priorTurns" | "profileSnapshot">,
200
- ): RouterOutput {
201
- const extracted = extractEntities(text);
202
- const deterministic = classifyWithLegacyRules(text);
203
- let diagnostics: RouterDiagnostic[] = [...output.diagnostics];
204
- const symbolsAfterAmbiguousFilter = output.entities.symbols.filter(
205
- (symbol) => !isAmbiguousConceptUsage(text, symbol),
206
- );
207
- const droppedAmbiguousSymbols = output.entities.symbols.filter(
208
- (symbol) => !symbolsAfterAmbiguousFilter.includes(symbol),
209
- );
210
- let next: RouterOutput = {
211
- ...output,
212
- entities: {
213
- ...output.entities,
214
- symbols: symbolsAfterAmbiguousFilter,
215
- budget: output.entities.budget ?? extracted.budget,
216
- maxPremium: output.entities.maxPremium ?? extracted.maxPremium,
217
- timeHorizon: output.entities.timeHorizon ?? extracted.timeHorizon,
218
- riskProfile: output.entities.riskProfile ?? extracted.riskProfile,
219
- assetScope: output.entities.assetScope ?? extracted.assetScope,
220
- compareMetrics: mergeStringArrays(output.entities.compareMetrics, extracted.compareMetrics),
221
- direction: output.entities.direction ?? extracted.direction,
222
- optionStrategy: output.entities.optionStrategy ?? extracted.optionStrategy,
223
- costBasis: output.entities.costBasis ?? extracted.costBasis,
224
- shareQuantity: output.entities.shareQuantity ?? extracted.shareQuantity,
225
- heldSymbol: output.entities.heldSymbol ?? extracted.heldSymbol,
226
- catalystSymbols: output.entities.catalystSymbols ?? extracted.catalystSymbols,
227
- dteHint:
228
- output.entities.dteHint ??
229
- (output.workflow === "options_screener" ? extracted.dteHint : undefined),
230
- },
231
- diagnostics,
232
- };
233
-
234
- if (next.workflow === "compare_assets") {
235
- const restorableExtractedSymbols = extracted.symbols.filter(
236
- (symbol) => disambiguateSymbols([symbol], text).kept.length > 0,
237
- );
238
- const orderedSymbols = orderSymbolsByText(
239
- text,
240
- mergeSymbols(next.entities.symbols, restorableExtractedSymbols),
241
- );
242
- if (!sameStringArray(orderedSymbols, next.entities.symbols)) {
243
- diagnostics.push({
244
- code: "compare_symbols_canonicalized",
245
- message: "compare symbols restored from deterministic extraction and ordered by user text",
246
- });
247
- next = {
248
- ...next,
249
- entities: {
250
- ...next.entities,
251
- symbols: orderedSymbols,
252
- },
253
- slots: syncSymbolListSlot(next.slots, orderedSymbols),
254
- diagnostics,
255
- };
256
- }
257
-
258
- // Prior-turn symbols merged into the slot (by the model or by the sync
259
- // above) must not claim user provenance: the user typed only what is in
260
- // this turn's text, and the Assumptions block renders slot sources.
261
- // preference/memory/default sources legitimately reference out-of-text
262
- // symbols and are left alone.
263
- if (symbolsSlotClaimsPriorTurnUserProvenance(next.slots, text, inputContext?.priorTurns)) {
264
- diagnostics.push({
265
- code: "symbols_slot_provenance_prior_context",
266
- message:
267
- "compare symbols slot includes symbols absent from the user text; source downgraded from user to prior_context",
268
- });
269
- next = {
270
- ...next,
271
- slots: {
272
- ...next.slots,
273
- symbols: {
274
- ...next.slots.symbols,
275
- source: "prior_context",
276
- },
277
- },
278
- diagnostics,
279
- };
280
- }
281
- }
282
-
283
- // The DTE horizon is a named historical loss class; when the model drops
284
- // the slot on an options dispatch, the deterministic extraction preserves
285
- // the user's stated range (mirrors the profile risk-slot fill below).
286
- const dteHint = next.entities.dteHint ?? extracted.dteHint;
287
- if (next.workflow === "options_screener" && !next.slots.dte_target && dteHint) {
288
- const dteTarget = mapDteHintToTarget(dteHint);
289
- if (dteTarget) {
290
- diagnostics.push({
291
- code: "dte_slot_filled_from_extraction",
292
- message: "dte_target slot filled from deterministic horizon extraction",
293
- });
294
- next = {
295
- ...next,
296
- slots: {
297
- ...next.slots,
298
- dte_target: {
299
- value: dteTarget,
300
- source: "user",
301
- confidence: "high",
302
- },
303
- },
304
- diagnostics,
305
- };
306
- }
307
- }
308
-
309
- // Model-vocabulary synonyms for the canonical asset_scope value
310
- // ("etf_only" for "etf_focused") drift saved preferences and slot
311
- // consumers onto private vocabularies; canonicalize before the echo
312
- // suppression below so restatements still match the profile.
313
- next = canonicalizeAssetScopeVocabulary(next);
314
-
315
- // A preference update that restates the saved profile value is an echo,
316
- // not a change; writing it pollutes preference provenance (the
317
- // preference-ECHO contract, fixture 029).
318
- const echoedUpdates = next.preference_updates.filter(
319
- (update) => readProfileString(inputContext?.profileSnapshot, update.key) === update.value,
320
- );
321
- if (echoedUpdates.length > 0) {
322
- diagnostics.push({
323
- code: "preference_echo_suppressed",
324
- message: `dropped preference update(s) restating the saved profile: ${echoedUpdates
325
- .map((update) => update.key)
326
- .join(", ")}`,
327
- });
328
- next = {
329
- ...next,
330
- preference_updates: next.preference_updates.filter(
331
- (update) => !echoedUpdates.includes(update),
332
- ),
333
- diagnostics,
334
- };
335
- }
336
-
337
- const profileRiskProfile = readProfileString(inputContext?.profileSnapshot, "risk_profile");
338
- if (
339
- next.workflow === "portfolio_builder" &&
340
- profileRiskProfile &&
341
- !next.slots.risk_profile &&
342
- !next.entities.riskProfile
343
- ) {
344
- diagnostics.push({
345
- code: "profile_risk_slot_filled",
346
- message: "risk_profile slot filled from investor profile snapshot",
347
- });
348
- next = {
349
- ...next,
350
- slots: {
351
- ...next.slots,
352
- risk_profile: {
353
- value: profileRiskProfile,
354
- source: "preference",
355
- confidence: "high",
356
- },
357
- },
358
- diagnostics,
359
- };
360
- }
361
-
362
- if (
363
- next.routeKind === "pass_through" &&
364
- extracted.riskProfile &&
365
- isConversationalRiskPreferenceUpdate(text, inputContext)
366
- ) {
367
- diagnostics.push({
368
- code: "conversational_risk_preference_recovered",
369
- message: "risk preference update recovered from profile/prior-turn context",
370
- });
371
- next = {
372
- ...next,
373
- routeKind: "agent_task",
374
- route: "fallback",
375
- entities: {
376
- ...next.entities,
377
- riskProfile: extracted.riskProfile,
378
- },
379
- slots: {
380
- ...next.slots,
381
- risk_profile: {
382
- value: extracted.riskProfile,
383
- source: "user",
384
- confidence: "high",
385
- },
386
- },
387
- preference_updates: ensurePreferenceUpdate(next.preference_updates, {
388
- key: "risk_profile",
389
- value: extracted.riskProfile,
390
- confidence: "high",
391
- source: "inferred",
392
- }),
393
- diagnostics,
394
- };
395
- }
396
-
397
- if (
398
- next.workflow === "options_screener" &&
399
- isExistingPositionOptionRequest(text, extracted) &&
400
- extracted.heldSymbol
401
- ) {
402
- const reorderedSymbols = [
403
- extracted.heldSymbol,
404
- ...mergeSymbols(next.entities.symbols, extracted.symbols).filter(
405
- (symbol) => symbol !== extracted.heldSymbol,
406
- ),
407
- ];
408
- if (next.entities.symbols[0] !== extracted.heldSymbol) {
409
- diagnostics.push({
410
- code:
411
- extracted.optionStrategy === "protective_put"
412
- ? "existing_position_underlying_corrected"
413
- : "covered_call_underlying_corrected",
414
- message: `using owned position ${extracted.heldSymbol} as the option-chain underlying`,
415
- });
416
- }
417
- next = {
418
- ...next,
419
- entities: {
420
- ...next.entities,
421
- symbols: reorderedSymbols,
422
- optionStrategy: extracted.optionStrategy ?? next.entities.optionStrategy,
423
- direction: extracted.direction ?? next.entities.direction,
424
- heldSymbol: extracted.heldSymbol,
425
- catalystSymbols: reorderedSymbols.filter((symbol) => symbol !== extracted.heldSymbol),
426
- costBasis: extracted.costBasis ?? next.entities.costBasis,
427
- shareQuantity: extracted.shareQuantity ?? next.entities.shareQuantity,
428
- dteHint: extracted.dteHint ?? next.entities.dteHint,
429
- },
430
- diagnostics,
431
- };
432
- }
433
-
434
- if (
435
- next.workflow === "options_screener" &&
436
- isOptionsEducationOrSuitabilityRequest(text) &&
437
- !isSpecificOptionContractSelectionRequest(text)
438
- ) {
439
- diagnostics.push({
440
- code: "options_workflow_corrected_to_policy_task",
441
- message:
442
- "options education or suitability prompt should use policy-card synthesis, not contract-screen workflow dispatch",
443
- });
444
- next = {
445
- ...next,
446
- routeKind: "agent_task",
447
- route: "fallback",
448
- workflow: "general_finance_qa",
449
- missing_required: [],
450
- diagnostics,
451
- };
452
- }
453
-
454
- if (
455
- next.workflow === "options_screener" &&
456
- next.entities.symbols.length >= 2 &&
457
- isPlainMultiAssetComparisonRequest(text)
458
- ) {
459
- diagnostics.push({
460
- code: "options_comparison_corrected_to_compare_assets",
461
- message:
462
- "explicit multi-asset comparison without option contract language should use compare_assets",
463
- });
464
- next = {
465
- ...next,
466
- routeKind: "workflow_dispatch",
467
- route: "workflow",
468
- workflow: "compare_assets",
469
- missing_required: [],
470
- entities: {
471
- ...next.entities,
472
- direction: undefined,
473
- dteHint: undefined,
474
- optionStrategy: undefined,
475
- },
476
- diagnostics,
477
- };
478
- }
479
-
480
- // Legacy rules may recover a primary route only when the LLM router path has
481
- // already failed validation. Otherwise they are limited to enrichment and
482
- // narrow corrections below.
483
- if (
484
- next.diagnostics.some((d) => d.code === "router_validation_failed") &&
485
- deterministic.workflow !== "unclassified"
486
- ) {
487
- next = {
488
- ...next,
489
- routeKind: isDispatchableWorkflow(deterministic.workflow)
490
- ? "workflow_dispatch"
491
- : "agent_task",
492
- route: isDispatchableWorkflow(deterministic.workflow) ? "workflow" : "fallback",
493
- workflow: deterministic.workflow,
494
- entities: {
495
- ...deterministic.entities,
496
- budget: deterministic.entities.budget ?? extracted.budget,
497
- maxPremium: deterministic.entities.maxPremium ?? extracted.maxPremium,
498
- timeHorizon: deterministic.entities.timeHorizon ?? extracted.timeHorizon,
499
- riskProfile: deterministic.entities.riskProfile ?? extracted.riskProfile,
500
- assetScope: deterministic.entities.assetScope ?? extracted.assetScope,
501
- compareMetrics: mergeStringArrays(
502
- deterministic.entities.compareMetrics,
503
- extracted.compareMetrics,
504
- ),
505
- direction: deterministic.entities.direction ?? extracted.direction,
506
- costBasis: deterministic.entities.costBasis ?? extracted.costBasis,
507
- shareQuantity: deterministic.entities.shareQuantity ?? extracted.shareQuantity,
508
- heldSymbol: deterministic.entities.heldSymbol ?? extracted.heldSymbol,
509
- catalystSymbols: deterministic.entities.catalystSymbols ?? extracted.catalystSymbols,
510
- },
511
- diagnostics: [
512
- ...diagnostics,
513
- {
514
- code: "deterministic_failure_recovery",
515
- message: `deterministic classifier selected ${deterministic.workflow} after router validation failure`,
516
- },
517
- ],
518
- reasoning: next.reasoning
519
- ? `${next.reasoning}; deterministic classifier selected ${deterministic.workflow}`
520
- : `deterministic classifier selected ${deterministic.workflow}`,
521
- };
522
- diagnostics = next.diagnostics;
523
- }
524
-
525
- if (next.routeKind === "workflow_dispatch" && !isDispatchableWorkflow(next.workflow)) {
526
- diagnostics.push({
527
- code: "route_kind_corrected_to_agent_task",
528
- message: next.workflow
529
- ? `${next.workflow} is not a dispatchable workflow`
530
- : "workflow_dispatch requires a dispatchable workflow",
531
- });
532
- next = {
533
- ...next,
534
- routeKind: "agent_task",
535
- route: "fallback",
536
- diagnostics,
537
- };
538
- }
539
-
540
- if (
541
- (next.workflow === "compare_assets" || next.workflow === "portfolio_builder") &&
542
- isStatefulTrackingRequest(text)
543
- ) {
544
- diagnostics.push({
545
- code: "stateful_tracking_corrected_to_agent_task",
546
- message:
547
- "portfolio/watchlist tracking mutation should use stateful tracking tools, not compare or construction workflow dispatch",
548
- });
549
- next = {
550
- ...next,
551
- routeKind: "agent_task",
552
- route: "fallback",
553
- workflow: "watchlist_or_tracking",
554
- missing_required: [],
555
- entities: {
556
- ...next.entities,
557
- symbols: filterCurrencyUnitSymbols(text, next.entities.symbols),
558
- },
559
- slots: removeCurrencyUnitSymbolSlots(text, next.slots),
560
- diagnostics,
561
- };
562
- }
563
-
564
- if (next.routeKind === "agent_task" && isDispatchableWorkflow(next.workflow)) {
565
- diagnostics.push({
566
- code: "dispatchable_workflow_corrected_to_workflow_dispatch",
567
- message: `${next.workflow} is a dispatchable workflow`,
568
- });
569
- next = {
570
- ...next,
571
- routeKind: "workflow_dispatch",
572
- route: "workflow",
573
- diagnostics,
574
- };
575
- }
576
-
577
- if (
578
- next.workflow === "compare_assets" &&
579
- next.entities.symbols.length === 0 &&
580
- isExplicitMacroDataRequest(text)
581
- ) {
582
- diagnostics.push({
583
- code: "compare_route_corrected_to_macro_task",
584
- message: "macro/source acronyms were not explicit tickers",
585
- });
586
- next = {
587
- ...next,
588
- routeKind: "agent_task",
589
- route: "fallback",
590
- workflow: "general_finance_qa",
591
- missing_required: [],
592
- diagnostics,
593
- };
594
- }
595
-
596
- if (next.workflow === "compare_assets" && isPortfolioEvaluationRequest(text)) {
597
- diagnostics.push({
598
- code: "portfolio_evaluation_corrected_to_agent_task",
599
- message:
600
- "existing portfolio/allocation risk review should not be reduced to asset comparison",
601
- });
602
- next = {
603
- ...next,
604
- routeKind: "agent_task",
605
- route: "fallback",
606
- workflow: "general_finance_qa",
607
- missing_required: [],
608
- diagnostics,
609
- };
610
- }
611
-
612
- if (
613
- next.routeKind === "agent_task" &&
614
- !next.workflow &&
615
- next.entities.symbols.length === 0 &&
616
- isExplicitMacroDataRequest(text)
617
- ) {
618
- diagnostics.push({
619
- code: "macro_task_inferred_from_prompt",
620
- message: "macro data terms were present without explicit tickers",
621
- });
622
- next = {
623
- ...next,
624
- workflow: "general_finance_qa",
625
- diagnostics,
626
- };
627
- }
628
-
629
- if (next.workflow === "portfolio_builder" && isCryptoSizingRequest(text)) {
630
- diagnostics.push({
631
- code: "crypto_sizing_corrected_to_agent_task",
632
- message:
633
- "crypto allocation-range and drawdown questions are advisory tradeoffs, not portfolio construction",
634
- });
635
- next = {
636
- ...next,
637
- routeKind: "agent_task",
638
- route: "fallback",
639
- workflow: "general_finance_qa",
640
- missing_required: [],
641
- diagnostics,
642
- };
643
- }
644
-
645
- if (next.workflow === "portfolio_builder" && isPortfolioEvaluationRequest(text)) {
646
- diagnostics.push({
647
- code: "portfolio_evaluation_corrected_to_agent_task",
648
- message:
649
- "existing portfolio/allocation evaluation does not require portfolio-construction budget",
650
- });
651
- next = {
652
- ...next,
653
- routeKind: "agent_task",
654
- route: "fallback",
655
- workflow: "general_finance_qa",
656
- missing_required: [],
657
- diagnostics,
658
- };
659
- }
660
-
661
- if (
662
- next.workflow === "portfolio_builder" &&
663
- next.entities.symbols.length >= 2 &&
664
- isPortfolioTradeoffComparisonRequest(text)
665
- ) {
666
- diagnostics.push({
667
- code: "portfolio_tradeoff_corrected_to_compare_assets",
668
- message:
669
- "explicit multi-asset tradeoff question should compare the requested assets before constructing a portfolio",
670
- });
671
- next = {
672
- ...next,
673
- routeKind: "workflow_dispatch",
674
- route: "workflow",
675
- workflow: "compare_assets",
676
- missing_required: [],
677
- diagnostics,
678
- };
679
- }
680
-
681
- if (next.workflow === "single_asset_analysis" && isSpecializedSingleAssetPolicyRequest(text)) {
682
- diagnostics.push({
683
- code: "single_asset_workflow_corrected_to_general_policy_task",
684
- message: "prompt asks for policy-card planning outside a single-asset buy/sell analysis",
685
- });
686
- next = {
687
- ...next,
688
- workflow: "general_finance_qa",
689
- diagnostics,
690
- };
691
- }
692
-
693
- const disambiguated = disambiguateSymbols(next.entities.symbols, text);
694
- if (disambiguated.dropped.length > 0) {
695
- for (const drop of disambiguated.dropped) {
696
- diagnostics.push({
697
- code: "symbol_dropped",
698
- message: `${drop.token} dropped: ${drop.reason}`,
699
- details: {
700
- token: drop.token,
701
- reason: drop.reason,
702
- signalsChecked: drop.signalsChecked,
703
- source: "llm",
704
- },
705
- });
706
- }
707
- next = {
708
- ...next,
709
- entities: {
710
- ...next.entities,
711
- symbols: disambiguated.kept,
712
- },
713
- slots: removeDroppedSymbolSlots(
714
- next.slots,
715
- disambiguated.dropped.map((drop) => drop.token),
716
- ),
717
- diagnostics,
718
- };
719
- }
720
-
721
- if (
722
- next.workflow === "compare_assets" &&
723
- (disambiguated.dropped.length > 0 || droppedAmbiguousSymbols.length > 0) &&
724
- next.entities.symbols.length < 2 &&
725
- isExplicitMacroDataRequest(text)
726
- ) {
727
- diagnostics.push({
728
- code: "compare_route_corrected_to_macro_task",
729
- message: "macro/source acronyms were not explicit tickers",
730
- });
731
- next = {
732
- ...next,
733
- routeKind: "agent_task",
734
- route: "fallback",
735
- workflow: "general_finance_qa",
736
- missing_required: [],
737
- slots: removeSymbolSlots(next.slots),
738
- diagnostics,
739
- };
740
- }
741
-
742
- const missingRequired = computeMissingRequiredSlots(
743
- next.workflow,
744
- next.entities,
745
- next.slots,
746
- next.missing_required,
747
- );
748
- if (missingRequired.length > 0 && next.routeKind !== "pass_through") {
749
- if (next.routeKind !== "clarification") {
750
- diagnostics.push({
751
- code: "route_kind_corrected_to_clarification",
752
- message: `missing required slots: ${missingRequired.join(", ")}`,
753
- });
754
- }
755
- next = {
756
- ...next,
757
- routeKind: "clarification",
758
- route: "fallback",
759
- missing_required: missingRequired,
760
- diagnostics,
761
- };
762
- }
763
-
764
- const selectedToolBundles = isConceptualEducationRequest(text, next)
765
- ? []
766
- : selectToolBundles(next);
767
- if (selectedToolBundles.length === 0 && isConceptualEducationRequest(text, next)) {
768
- diagnostics.push({
769
- code: "conceptual_education_no_tools",
770
- message: "conceptual education prompt does not need live finance tools",
771
- });
772
- }
773
- const emittedUnsupported = next.tool_bundles.filter(
774
- (bundle) => !selectedToolBundles.includes(bundle),
775
- );
776
- if (emittedUnsupported.length > 0) {
777
- diagnostics.push({
778
- code: "tool_bundles_corrected",
779
- message: `unsupported emitted bundles dropped: ${emittedUnsupported.join(", ")}`,
780
- });
781
- }
782
-
783
- return omitUndefined({
784
- ...next,
785
- route: legacyRouteForRouteKind(next.routeKind),
786
- tool_bundles: selectedToolBundles,
787
- diagnostics,
788
- });
789
- }
790
-
791
- function isExplicitMacroDataRequest(text: string): boolean {
792
- return /\b(?:get_economic_data|fred|cpi|inflation|fed\s+funds?|unemployment|gdp|macro)\b/i.test(
793
- text,
794
- );
795
- }
796
-
797
- function isConceptualEducationRequest(text: string, output: RouterOutput): boolean {
798
- if (output.routeKind !== "agent_task") return false;
799
- if (output.entities.symbols.length > 0) return false;
800
- if (isForwardLookingMacroContextRequest(text)) return false;
801
- if (
802
- /\b(?:current|recent|today|right now|latest|news|sentiment|build|portfolio|buy|sell|allocate|compare)\b/i.test(
803
- text,
804
- )
805
- ) {
806
- return false;
807
- }
808
- return /\b(?:explain|what is|define|how (?:do|should|to)|teach me|help me understand)\b/i.test(
809
- text,
810
- );
811
- }
812
-
813
- function isForwardLookingMacroContextRequest(text: string): boolean {
814
- return (
815
- /\b(?:rates?|rate\s*cuts?|fed|inflation|macro)\b/i.test(text) &&
816
- /\b(?:next\s+(?:year|12\s*months?)|over\s+the\s+next|outlook|affect|impact|falling|rising)\b/i.test(
817
- text,
818
- )
819
- );
820
- }
821
-
822
- function isCoveredCallRequest(text: string): boolean {
823
- return /\bcovered\s+calls?\b/i.test(text);
824
- }
825
-
826
- function isPortfolioEvaluationRequest(text: string): boolean {
827
- const lower = text.toLowerCase();
828
- const hasEvaluationIntent =
829
- /\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(
830
- lower,
831
- );
832
- const hasExplicitPortfolioSubject =
833
- /\b(?:portfolio|allocation|asset\s+allocation|60\/40|holdings?|positions?)\b/.test(lower);
834
- const hasOwnedAssetMix =
835
- /\b(?:my|current|have|holding|hold|own|invested|positions?|\d+(?:\.\d+)?%)\b/.test(lower) &&
836
- /\b(?:equity|fixed\s+income|bonds?|cash|stocks?|etfs?|funds?)\b/.test(lower);
837
- const hasConstructionIntent =
838
- /\b(?:build|create|construct|put\s+together|invest|allocate)\b/.test(lower) &&
839
- /\$\s*\d|\b\d+(?:\.\d+)?\s*k\b|\bbudget\b|\bcapital\b/.test(lower);
840
- return (
841
- hasEvaluationIntent &&
842
- (hasExplicitPortfolioSubject || hasOwnedAssetMix) &&
843
- !hasConstructionIntent
844
- );
845
- }
846
-
847
- function isStatefulTrackingRequest(text: string): boolean {
848
- const lower = text.toLowerCase();
849
- const hasPortfolioConstructionIntent =
850
- /\b(?:build|create|construct|put\s+together)\b/.test(lower) &&
851
- /\bportfolio\b/.test(lower) &&
852
- /\$\s*\d|\b\d+(?:\.\d+)?\s*k\b|\bbudget\b|\bcapital\b/.test(lower);
853
- const hasStateVerb =
854
- /\b(?:add|remove|update|record|track|create|configure|check|show|list|view|cancel)\b/.test(
855
- lower,
856
- );
857
- const hasStateObject =
858
- /\b(?:watchlist|portfolio|holding|holdings|position|positions|alert|alerts|daily\s+report|watchlist\s+report|report\s+history)\b/.test(
859
- lower,
860
- );
861
- const hasPortfolioLotShape =
862
- /\b(?:add|record|track)\b/.test(lower) &&
863
- /\b\d+(?:\.\d+)?\s+shares?\b/.test(lower) &&
864
- /\b(?:portfolio|holding|holdings|position|positions)\b/.test(lower);
865
- if (hasPortfolioConstructionIntent) return false;
866
- return (hasStateVerb && hasStateObject) || hasPortfolioLotShape;
867
- }
868
-
869
- function filterCurrencyUnitSymbols(text: string, symbols: string[]): string[] {
870
- return symbols.filter((symbol) => !isCurrencyCodeUsage(text, symbol));
871
- }
872
-
873
- function removeCurrencyUnitSymbolSlots(
874
- text: string,
875
- slots: Record<string, RouterSlot>,
876
- ): Record<string, RouterSlot> {
877
- const next = { ...slots };
878
- for (const key of ["symbol", "symbols"]) {
879
- const slot = next[key];
880
- if (!slot) continue;
881
- if (Array.isArray(slot.value)) {
882
- const value = slot.value.filter(
883
- (item) => typeof item !== "string" || !isCurrencyCodeUsage(text, item.toUpperCase()),
884
- );
885
- if (value.length === 0) delete next[key];
886
- else next[key] = { ...slot, value };
887
- continue;
888
- }
889
- if (typeof slot.value === "string" && isCurrencyCodeUsage(text, slot.value.toUpperCase())) {
890
- delete next[key];
891
- }
892
- }
893
- return next;
894
- }
895
-
896
- function isPortfolioTradeoffComparisonRequest(text: string): boolean {
897
- const lower = text.toLowerCase();
898
- return (
899
- /\b(?:prioritize|tradeoffs?|growth[-\s]?oriented|dividend|income|which\s+(?:one|is)\s+better|should\s+i)\b/.test(
900
- lower,
901
- ) && /\b(?:or|vs\.?|versus|compare)\b/.test(lower)
902
- );
903
- }
904
-
905
- function isCryptoSizingRequest(text: string): boolean {
906
- const lower = text.toLowerCase();
907
- const hasPortfolioConstructionIntent =
908
- /\b(?:build|create|construct|put\s+together)\b/.test(lower) &&
909
- /\b(?:portfolio|allocation)\b/.test(lower);
910
- if (hasPortfolioConstructionIntent) return false;
911
- return (
912
- /\b(?:btc|bitcoin|crypto)\b/.test(lower) &&
913
- /\b(?:allocation|range|position\s+size|sizing|exposure|drawdown)\b/.test(lower)
914
- );
915
- }
916
-
917
- function isSpecializedSingleAssetPolicyRequest(text: string): boolean {
918
- const lower = text.toLowerCase();
919
- return (
920
- /\b(?:ticker|symbol|formerly|old ticker|earnings are|earnings tonight)\b/.test(lower) ||
921
- /\b(?:today|right now|this morning|after close|moved|catalyst)\b/.test(lower) ||
922
- /\b(?:sentiment|mood|reddit|twitter|x\/twitter)\b/.test(lower) ||
923
- /\b(?:filing|10-k|10-q|8-k|sec)\b/.test(lower)
924
- );
925
- }
926
-
927
- function isExistingPositionOptionRequest(text: string, extracted: ExtractedEntities): boolean {
928
- return isCoveredCallRequest(text) || extracted.optionStrategy === "protective_put";
929
- }
930
-
931
- function isOptionsEducationOrSuitabilityRequest(text: string): boolean {
932
- const lower = text.toLowerCase();
933
- return (
934
- /\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(
935
- lower,
936
- ) &&
937
- /\b(?:covered\s+calls?|protective\s+puts?|options?|selling\s+calls?|option\s+income)\b/.test(
938
- lower,
939
- )
940
- );
941
- }
942
-
943
- function isPlainMultiAssetComparisonRequest(text: string): boolean {
944
- const lower = text.toLowerCase();
945
- const hasCompareIntent =
946
- /\bcompare\b/.test(lower) ||
947
- /\bvs\.?\b/.test(lower) ||
948
- /\bversus\b/.test(lower) ||
949
- /\bwhich\s+is\s+better\b/.test(lower);
950
- return hasCompareIntent && !hasExplicitOptionContractLanguage(lower);
951
- }
952
-
953
- function hasExplicitOptionContractLanguage(lower: string): boolean {
954
- return (
955
- /\bcalls?\b(?!\s+out\b)/.test(lower) ||
956
- /\bputs?\b/.test(lower) ||
957
- /\boption(?:s)?\s*chain\b/.test(lower) ||
958
- /\boptions?\b/.test(lower) ||
959
- /\b(?:strike|expiration|dte|premium|delta|theta|greeks?|contract)\b/.test(lower)
960
- );
961
- }
962
-
963
- function isSpecificOptionContractSelectionRequest(text: string): boolean {
964
- const lower = text.toLowerCase();
965
- return (
966
- /\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(
967
- lower,
968
- ) && /\b(?:sell|buy|trade|contract|strike|expiration|premium|call|put)\b/.test(lower)
969
- );
970
- }
971
-
972
- function mergeSymbols(primary: string[], secondary: string[]): string[] {
973
- const merged: string[] = [];
974
- for (const symbol of [...primary, ...secondary]) {
975
- if (!merged.includes(symbol)) merged.push(symbol);
976
- }
977
- return merged;
978
- }
979
-
980
- function mergeStringArrays(primary?: string[], secondary?: string[]): string[] | undefined {
981
- const merged: string[] = [];
982
- for (const value of [...(primary ?? []), ...(secondary ?? [])]) {
983
- if (!merged.includes(value)) merged.push(value);
984
- }
985
- return merged.length > 0 ? merged : undefined;
986
- }
987
-
988
- function omitUndefined<T>(value: T): T {
989
- if (Array.isArray(value)) return value.map(omitUndefined) as T;
990
- if (!value || typeof value !== "object") return value;
991
- const out: Record<string, unknown> = {};
992
- for (const [key, entry] of Object.entries(value)) {
993
- if (entry !== undefined) out[key] = omitUndefined(entry);
994
- }
995
- return out as T;
996
- }
997
-
998
- function validateSlots(raw: unknown): Record<string, RouterSlot> {
999
- if (raw === undefined || raw === null) return {};
1000
- if (typeof raw !== "object") {
1001
- throw new Error("slots must be an object");
1002
- }
1003
- const out: Record<string, RouterSlot> = {};
1004
- for (const [key, val] of Object.entries(raw as Record<string, unknown>)) {
1005
- if (!val || typeof val !== "object") {
1006
- throw new Error(`slot ${key} must be an object`);
1007
- }
1008
- const s = val as Record<string, unknown>;
1009
- if (!VALID_SOURCES.has(s.source as string)) {
1010
- throw new Error(`slot ${key} has invalid source: ${JSON.stringify(s.source)}`);
1011
- }
1012
- if (!VALID_CONFIDENCE.has(s.confidence as string)) {
1013
- throw new Error(`slot ${key} has invalid confidence: ${JSON.stringify(s.confidence)}`);
1014
- }
1015
- const canonicalKey = canonicalSlotKey(key);
1016
- out[canonicalKey] = {
1017
- value: s.value,
1018
- source: s.source as RouterSlot["source"],
1019
- confidence: s.confidence as RouterSlot["confidence"],
1020
- };
1021
- }
1022
- return out;
1023
- }
1024
-
1025
- // The slot contract uses snake_case keys; non-Claude router models sometimes
1026
- // emit camelCase (timeHorizon, riskProfile). Canonicalize deterministically so
1027
- // downstream slot resolution and missing-required checks match.
1028
- function canonicalSlotKey(key: string): string {
1029
- return key.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
1030
- }
1031
-
1032
- // Models also drift between scalar `symbol` and one-element `symbols` slot
1033
- // shapes. Canonicalize toward the workflow's manifest-declared required slot
1034
- // name when the conversion is unambiguous.
1035
- function canonicalizeSymbolSlots(
1036
- workflow: RouterOutput["workflow"],
1037
- slots: Record<string, RouterSlot>,
1038
- ): Record<string, RouterSlot> {
1039
- if (!workflow) return slots;
1040
- const required = workflowRequiredSlots(workflow);
1041
- const next = { ...slots };
1042
- if (required.includes("symbol") && next.symbol == null && next.symbols != null) {
1043
- const value = next.symbols.value;
1044
- if (Array.isArray(value) && value.length === 1) {
1045
- next.symbol = { ...next.symbols, value: value[0] };
1046
- delete next.symbols;
1047
- }
1048
- }
1049
- if (required.includes("symbols") && next.symbols == null && next.symbol != null) {
1050
- const value = next.symbol.value;
1051
- if (typeof value === "string" && value.length > 0) {
1052
- next.symbols = { ...next.symbol, value: [value] };
1053
- delete next.symbol;
1054
- }
1055
- }
1056
- return next;
1057
- }
1058
-
1059
- function syncSymbolListSlot(
1060
- slots: Record<string, RouterSlot>,
1061
- symbols: string[],
1062
- ): Record<string, RouterSlot> {
1063
- if (!slots.symbols || symbols.length === 0) return slots;
1064
- return {
1065
- ...slots,
1066
- symbols: {
1067
- ...slots.symbols,
1068
- value: symbols,
1069
- },
1070
- };
1071
- }
1072
-
1073
- const ASSET_SCOPE_SYNONYMS: Record<string, string> = {
1074
- etf_only: "etf_focused",
1075
- etfs_only: "etf_focused",
1076
- only_etfs: "etf_focused",
1077
- etf: "etf_focused",
1078
- etfs: "etf_focused",
1079
- };
1080
-
1081
- function canonicalAssetScope(value: unknown): string | undefined {
1082
- if (typeof value !== "string") return undefined;
1083
- return ASSET_SCOPE_SYNONYMS[value.toLowerCase()];
1084
- }
1085
-
1086
- function canonicalizeAssetScopeVocabulary(output: RouterOutput): RouterOutput {
1087
- let next = output;
1088
- const slotCanonical = canonicalAssetScope(next.slots.asset_scope?.value);
1089
- if (slotCanonical) {
1090
- next = {
1091
- ...next,
1092
- slots: {
1093
- ...next.slots,
1094
- asset_scope: { ...next.slots.asset_scope, value: slotCanonical },
1095
- },
1096
- };
1097
- }
1098
- const entityCanonical = canonicalAssetScope(next.entities.assetScope);
1099
- if (entityCanonical) {
1100
- next = {
1101
- ...next,
1102
- entities: { ...next.entities, assetScope: entityCanonical },
1103
- };
1104
- }
1105
- if (
1106
- next.preference_updates.some(
1107
- (update) => update.key === "asset_scope" && canonicalAssetScope(update.value),
1108
- )
1109
- ) {
1110
- next = {
1111
- ...next,
1112
- preference_updates: next.preference_updates.map((update) =>
1113
- update.key === "asset_scope"
1114
- ? { ...update, value: canonicalAssetScope(update.value) ?? update.value }
1115
- : update,
1116
- ),
1117
- };
1118
- }
1119
- return next;
1120
- }
1121
-
1122
- function symbolsSlotClaimsPriorTurnUserProvenance(
1123
- slots: Record<string, RouterSlot>,
1124
- text: string,
1125
- priorTurns: RouterInputContext["priorTurns"] | undefined,
1126
- ): boolean {
1127
- const slot = slots.symbols;
1128
- if (!slot || slot.source !== "user" || !Array.isArray(slot.value)) return false;
1129
- if (!priorTurns || priorTurns.length === 0) return false;
1130
- const priorText = priorTurns.map((turn) => turn.text).join("\n");
1131
- // A symbol absent from this turn's text but present in prior turns is a
1132
- // carryover, not a user-typed value. Symbols absent from both (e.g. tickers
1133
- // resolved from company names in the current text) are left alone.
1134
- return slot.value.some(
1135
- (symbol) =>
1136
- typeof symbol === "string" &&
1137
- symbolPosition(text, symbol) === Number.MAX_SAFE_INTEGER &&
1138
- symbolPosition(priorText, symbol) !== Number.MAX_SAFE_INTEGER,
1139
- );
1140
- }
1141
-
1142
- function removeSymbolSlots(slots: Record<string, RouterSlot>): Record<string, RouterSlot> {
1143
- const next = { ...slots };
1144
- delete next.symbol;
1145
- delete next.symbols;
1146
- return next;
1147
- }
1148
-
1149
- function orderSymbolsByText(text: string, symbols: string[]): string[] {
1150
- return [...symbols].sort((a, b) => symbolPosition(text, a) - symbolPosition(text, b));
1151
- }
1152
-
1153
- function symbolPosition(text: string, symbol: string): number {
1154
- const escaped = escapeRegExp(symbol);
1155
- const match = new RegExp(`\\$?${escaped}\\b`, "i").exec(text);
1156
- return match?.index ?? Number.MAX_SAFE_INTEGER;
1157
- }
1158
-
1159
- function sameStringArray(left: string[], right: string[]): boolean {
1160
- return left.length === right.length && left.every((value, index) => value === right[index]);
1161
- }
1162
-
1163
- function readProfileString(
1164
- profileSnapshot: RouterInputContext["profileSnapshot"] | undefined,
1165
- key: string,
1166
- ): string | undefined {
1167
- const value = profileSnapshot?.[key];
1168
- return typeof value === "string" && value.length > 0 ? value : undefined;
1169
- }
1170
-
1171
- function isConversationalRiskPreferenceUpdate(
1172
- text: string,
1173
- inputContext: Pick<RouterInputContext, "priorTurns" | "profileSnapshot"> | undefined,
1174
- ): boolean {
1175
- if (!/\b(?:now|lately|getting|becoming|thinking|feel|feeling|prefer|preference)\b/i.test(text)) {
1176
- return false;
1177
- }
1178
- // Finance context must come from the conversation itself — a saved
1179
- // risk_profile alone must not convert non-finance chat ("more aggressive
1180
- // on the tennis court lately") into a routed preference write.
1181
- const priorText = inputContext?.priorTurns.map((turn) => turn.text).join(" ") ?? "";
1182
- return /\b(?:profile|risk|portfolio|position|invest|sizing)\b/i.test(`${text} ${priorText}`);
1183
- }
1184
-
1185
- function ensurePreferenceUpdate(
1186
- updates: RouterPreferenceUpdate[],
1187
- update: RouterPreferenceUpdate,
1188
- ): RouterPreferenceUpdate[] {
1189
- if (updates.some((item) => item.key === update.key && item.value === update.value)) {
1190
- return updates;
1191
- }
1192
- return [...updates, update];
1193
- }
1194
-
1195
- function escapeRegExp(value: string): string {
1196
- return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1197
- }
1198
-
1199
- function validatePreferenceUpdates(raw: unknown): RouterPreferenceUpdate[] {
1200
- if (raw === undefined || raw === null) return [];
1201
- if (!Array.isArray(raw)) {
1202
- throw new Error("preference_updates must be an array");
1203
- }
1204
- return raw.map((item, idx) => {
1205
- if (!item || typeof item !== "object") {
1206
- throw new Error(`preference_updates[${idx}] must be an object`);
1207
- }
1208
- const p = item as Record<string, unknown>;
1209
- if (typeof p.key !== "string" || p.key.length === 0) {
1210
- throw new Error(`preference_updates[${idx}].key must be a non-empty string`);
1211
- }
1212
- if (typeof p.value !== "string") {
1213
- throw new Error(`preference_updates[${idx}].value must be a string`);
1214
- }
1215
- if (!VALID_CONFIDENCE.has(p.confidence as string)) {
1216
- throw new Error(`preference_updates[${idx}].confidence is invalid`);
1217
- }
1218
- // Router-emitted preferences are always inferred — absent is accepted
1219
- // (normalized), but any explicit non-"inferred" value is an invariant
1220
- // violation the caller should see rather than silently lose.
1221
- if (p.source !== undefined && p.source !== "inferred") {
1222
- throw new Error(
1223
- `preference_updates[${idx}].source must be "inferred" (got ${JSON.stringify(p.source)})`,
1224
- );
1225
- }
1226
- return {
1227
- key: p.key,
1228
- value: p.value,
1229
- confidence: p.confidence as RouterPreferenceUpdate["confidence"],
1230
- source: "inferred",
1231
- };
1232
- });
1233
- }
1234
-
1235
- function validateToolBundles(raw: unknown): ToolBundleName[] {
1236
- const bundles = validateStringArray(raw, "tool_bundles");
1237
- return bundles.filter(isToolBundleName);
1238
- }
1239
-
1240
- function removeDroppedSymbolSlots(
1241
- slots: Record<string, RouterSlot>,
1242
- droppedTokens: string[],
1243
- ): Record<string, RouterSlot> {
1244
- if (droppedTokens.length === 0) return slots;
1245
- const dropped = new Set(droppedTokens.map((token) => token.toUpperCase()));
1246
- const next = { ...slots };
1247
-
1248
- for (const key of ["symbol", "symbols"]) {
1249
- const slot = next[key];
1250
- if (!slot) continue;
1251
- if (Array.isArray(slot.value)) {
1252
- const value = slot.value.filter(
1253
- (item) => typeof item !== "string" || !dropped.has(item.toUpperCase()),
1254
- );
1255
- if (value.length === 0) {
1256
- delete next[key];
1257
- } else {
1258
- next[key] = { ...slot, value };
1259
- }
1260
- continue;
1261
- }
1262
- if (typeof slot.value === "string" && dropped.has(slot.value.toUpperCase())) {
1263
- delete next[key];
1264
- }
1265
- }
1266
-
1267
- return next;
1268
- }
1269
-
1270
- function validateDiagnostics(raw: unknown): RouterDiagnostic[] {
1271
- if (raw === undefined || raw === null) return [];
1272
- if (!Array.isArray(raw)) {
1273
- throw new Error("diagnostics must be an array");
1274
- }
1275
- return raw.map((item, idx) => {
1276
- if (!item || typeof item !== "object") {
1277
- throw new Error(`diagnostics[${idx}] must be an object`);
1278
- }
1279
- const diagnostic = item as Record<string, unknown>;
1280
- if (typeof diagnostic.code !== "string" || diagnostic.code.length === 0) {
1281
- throw new Error(`diagnostics[${idx}].code must be a non-empty string`);
1282
- }
1283
- if (typeof diagnostic.message !== "string") {
1284
- throw new Error(`diagnostics[${idx}].message must be a string`);
1285
- }
1286
- const out: RouterDiagnostic = {
1287
- code: diagnostic.code,
1288
- message: diagnostic.message,
1289
- };
1290
- if (
1291
- diagnostic.details &&
1292
- typeof diagnostic.details === "object" &&
1293
- !Array.isArray(diagnostic.details)
1294
- ) {
1295
- out.details = diagnostic.details as Record<string, unknown>;
1296
- }
1297
- return out;
1298
- });
1299
- }
1300
-
1301
- function validateStringArray(raw: unknown, field: string): string[] {
1302
- if (raw === undefined || raw === null) return [];
1303
- if (!Array.isArray(raw)) {
1304
- throw new Error(`${field} must be an array`);
1305
- }
1306
- return raw.map((item, idx) => {
1307
- if (typeof item !== "string") {
1308
- throw new Error(`${field}[${idx}] must be a string`);
1309
- }
1310
- return item;
1311
- });
1312
- }
1313
-
1314
- function minimalFallback(text: string): RouterOutput {
1315
- const entities = extractEntities(text);
1316
- return {
1317
- routeKind: "agent_task",
1318
- route: "fallback",
1319
- entities,
1320
- slots: {},
1321
- preference_updates: [],
1322
- missing_required: [],
1323
- tool_bundles: [],
1324
- diagnostics: [
1325
- {
1326
- code: "router_validation_failed",
1327
- message: "router validation failed persistently; emitted minimal fallback",
1328
- },
1329
- ],
1330
- reasoning: "router validation failed; emitted minimal fallback",
1331
- };
1332
- }