opencandle 0.11.1 → 0.13.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 (678) hide show
  1. package/README.md +50 -186
  2. package/dist/analysts/contracts.js +0 -1
  3. package/dist/analysts/orchestrator.js +0 -1
  4. package/dist/cli-main.js +22 -15
  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.d.ts +4 -0
  9. package/dist/config.js +1 -1
  10. package/dist/doctor/cli-command.js +9 -5
  11. package/dist/doctor/render.js +0 -1
  12. package/dist/doctor/report.js +53 -11
  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 +388 -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/history-snapshot-store.d.ts +8 -0
  24. package/dist/gui/server/history-snapshot-store.js +43 -0
  25. package/dist/gui/server/http-routes.d.ts +71 -0
  26. package/dist/gui/server/http-routes.js +1033 -0
  27. package/dist/gui/server/invoke-tool.d.ts +47 -0
  28. package/dist/gui/server/invoke-tool.js +373 -0
  29. package/dist/gui/server/live-chat-event-adapter.d.ts +21 -0
  30. package/dist/gui/server/live-chat-event-adapter.js +224 -0
  31. package/dist/gui/server/local-session-coordinator.d.ts +26 -0
  32. package/dist/gui/server/local-session-coordinator.js +53 -0
  33. package/dist/gui/server/market-indices-api.d.ts +21 -0
  34. package/dist/gui/server/market-indices-api.js +26 -0
  35. package/dist/gui/server/market-indices-snapshot-store.d.ts +12 -0
  36. package/dist/gui/server/market-indices-snapshot-store.js +56 -0
  37. package/dist/gui/server/market-state-api.d.ts +250 -0
  38. package/dist/gui/server/market-state-api.js +597 -0
  39. package/dist/gui/server/model-setup.d.ts +55 -0
  40. package/dist/gui/server/model-setup.js +154 -0
  41. package/dist/gui/server/private-api-access.d.ts +6 -0
  42. package/dist/gui/server/private-api-access.js +53 -0
  43. package/dist/gui/server/projector.d.ts +49 -0
  44. package/dist/gui/server/projector.js +296 -0
  45. package/dist/gui/server/prompt-observation.d.ts +8 -0
  46. package/dist/gui/server/prompt-observation.js +43 -0
  47. package/dist/gui/server/quote-snapshot-store.d.ts +14 -0
  48. package/dist/gui/server/quote-snapshot-store.js +49 -0
  49. package/dist/gui/server/server.d.ts +1 -0
  50. package/dist/gui/server/server.js +262 -0
  51. package/dist/gui/server/session-actions.d.ts +60 -0
  52. package/dist/gui/server/session-actions.js +218 -0
  53. package/dist/gui/server/session-entry-wait.d.ts +27 -0
  54. package/dist/gui/server/session-entry-wait.js +129 -0
  55. package/dist/gui/server/session-list.d.ts +2 -0
  56. package/dist/gui/server/session-list.js +11 -0
  57. package/dist/gui/server/shutdown.d.ts +10 -0
  58. package/dist/gui/server/shutdown.js +29 -0
  59. package/dist/gui/server/tool-invoke-ack.d.ts +17 -0
  60. package/dist/gui/server/tool-invoke-ack.js +26 -0
  61. package/dist/gui/server/tool-metadata.d.ts +93 -0
  62. package/dist/gui/server/tool-metadata.js +148 -0
  63. package/dist/gui/server/websocket.d.ts +9 -0
  64. package/dist/gui/server/websocket.js +124 -0
  65. package/dist/gui/server/writer-lock.d.ts +1 -0
  66. package/dist/gui/server/writer-lock.js +1 -0
  67. package/dist/gui/server/ws-hub.d.ts +50 -0
  68. package/dist/gui/server/ws-hub.js +284 -0
  69. package/dist/gui/shared/chat-events.d.ts +174 -0
  70. package/dist/gui/shared/chat-events.js +13 -0
  71. package/dist/gui/shared/event-reducer.d.ts +3 -0
  72. package/dist/gui/shared/event-reducer.js +187 -0
  73. package/dist/index.js +0 -1
  74. package/dist/infra/cache.d.ts +4 -0
  75. package/dist/infra/cache.js +4 -1
  76. package/dist/infra/freshness.js +0 -1
  77. package/dist/infra/http-client.js +1 -2
  78. package/dist/infra/index.js +0 -1
  79. package/dist/infra/lse-byte-budget.d.ts +10 -0
  80. package/dist/infra/lse-byte-budget.js +47 -0
  81. package/dist/infra/market-calendar.js +0 -1
  82. package/dist/infra/native-dependencies.js +0 -1
  83. package/dist/infra/node-version.js +0 -1
  84. package/dist/infra/open-url.js +0 -1
  85. package/dist/infra/opencandle-paths.js +0 -1
  86. package/dist/infra/rate-limiter.js +1 -1
  87. package/dist/market-state/alert-conditions.js +0 -1
  88. package/dist/market-state/alert-runner.d.ts +1 -0
  89. package/dist/market-state/alert-runner.js +5 -4
  90. package/dist/market-state/daily-report.js +0 -1
  91. package/dist/market-state/local-automation-service.js +0 -1
  92. package/dist/market-state/notification-delivery.js +0 -1
  93. package/dist/market-state/resolve-for-mutation.js +0 -1
  94. package/dist/market-state/resolve.js +0 -1
  95. package/dist/market-state/service.d.ts +26 -21
  96. package/dist/market-state/service.js +175 -36
  97. package/dist/market-state/summaries.js +1 -13
  98. package/dist/memory/index.js +0 -1
  99. package/dist/memory/manager.js +0 -1
  100. package/dist/memory/preference-extractor.js +0 -1
  101. package/dist/memory/retrieval.js +0 -1
  102. package/dist/memory/sqlite.js +60 -11
  103. package/dist/memory/storage.js +0 -1
  104. package/dist/memory/tool-defaults.js +0 -1
  105. package/dist/memory/types.js +0 -1
  106. package/dist/monitor.js +0 -1
  107. package/dist/onboarding/connect.js +0 -1
  108. package/dist/onboarding/credential-interceptor.js +0 -1
  109. package/dist/onboarding/degradation-accumulator.js +0 -1
  110. package/dist/onboarding/prompt-user.d.ts +1 -1
  111. package/dist/onboarding/prompt-user.js +0 -1
  112. package/dist/onboarding/provider-status.js +0 -1
  113. package/dist/onboarding/providers.d.ts +16 -1
  114. package/dist/onboarding/providers.js +20 -1
  115. package/dist/onboarding/state.js +0 -1
  116. package/dist/onboarding/tool-helpers.js +0 -1
  117. package/dist/onboarding/tool-tags.js +0 -1
  118. package/dist/onboarding/validate-model-key.d.ts +17 -0
  119. package/dist/onboarding/validate-model-key.js +86 -0
  120. package/dist/onboarding/validation.js +8 -1
  121. package/dist/pi/opencandle-extension.d.ts +2 -1
  122. package/dist/pi/opencandle-extension.js +4 -4
  123. package/dist/pi/session-action-dedupe.js +0 -1
  124. package/dist/pi/session-storage.js +0 -1
  125. package/dist/pi/session-writer-lock.js +0 -1
  126. package/dist/pi/session.d.ts +2 -3
  127. package/dist/pi/session.js +7 -6
  128. package/dist/pi/setup.d.ts +4 -2
  129. package/dist/pi/setup.js +60 -61
  130. package/dist/pi/tool-adapter.js +0 -1
  131. package/dist/pi/tui-session-coordinator.js +0 -1
  132. package/dist/prompts/context-builder.js +1 -2
  133. package/dist/prompts/disclaimer.js +0 -1
  134. package/dist/prompts/policy-cards.js +0 -1
  135. package/dist/prompts/sections.js +0 -1
  136. package/dist/prompts/symbol-preflight.js +0 -1
  137. package/dist/prompts/workflow-prompts.js +16 -15
  138. package/dist/providers/alpha-vantage.js +2 -3
  139. package/dist/providers/coingecko.js +0 -1
  140. package/dist/providers/errors.js +0 -1
  141. package/dist/providers/exa-search.js +11 -10
  142. package/dist/providers/external-tool-command.js +0 -1
  143. package/dist/providers/external-tool-error.js +0 -1
  144. package/dist/providers/fear-greed.js +0 -1
  145. package/dist/providers/finnhub.js +0 -1
  146. package/dist/providers/fred.js +0 -1
  147. package/dist/providers/index.d.ts +1 -0
  148. package/dist/providers/index.js +1 -1
  149. package/dist/providers/lse.d.ts +35 -0
  150. package/dist/providers/lse.js +284 -0
  151. package/dist/providers/polymarket.js +22 -6
  152. package/dist/providers/provider-credential-error.js +0 -1
  153. package/dist/providers/reddit-cli.js +0 -1
  154. package/dist/providers/reddit.js +0 -1
  155. package/dist/providers/sec-edgar.js +0 -1
  156. package/dist/providers/tradingview.js +1 -2
  157. package/dist/providers/twitter-cli.js +0 -1
  158. package/dist/providers/twitter.js +0 -1
  159. package/dist/providers/web-search.js +15 -12
  160. package/dist/providers/with-fallback.js +0 -1
  161. package/dist/providers/wrap-provider.js +1 -1
  162. package/dist/providers/yahoo-finance.js +68 -4
  163. package/dist/routing/classify-intent.js +0 -1
  164. package/dist/routing/defaults.js +0 -1
  165. package/dist/routing/entity-extractor.js +2 -3
  166. package/dist/routing/fund-symbols.js +0 -1
  167. package/dist/routing/horizon.js +0 -1
  168. package/dist/routing/index.js +0 -1
  169. package/dist/routing/legacy-rule-router.js +0 -1
  170. package/dist/routing/planning.js +0 -1
  171. package/dist/routing/route-manifest.js +1 -1
  172. package/dist/routing/router-llm-client.d.ts +2 -2
  173. package/dist/routing/router-llm-client.js +0 -1
  174. package/dist/routing/router-prompt.js +0 -1
  175. package/dist/routing/router-types.js +0 -1
  176. package/dist/routing/router.js +9 -3
  177. package/dist/routing/slot-resolver.js +0 -1
  178. package/dist/routing/symbol-disambiguator.js +0 -1
  179. package/dist/routing/turn-context.js +0 -1
  180. package/dist/routing/types.js +0 -1
  181. package/dist/runtime/answer-contracts.js +0 -1
  182. package/dist/runtime/artifact-contracts.js +0 -1
  183. package/dist/runtime/evidence.d.ts +1 -0
  184. package/dist/runtime/evidence.js +1 -2
  185. package/dist/runtime/numeric-claims.js +0 -1
  186. package/dist/runtime/planning-evidence.js +0 -1
  187. package/dist/runtime/prompt-step.js +0 -1
  188. package/dist/runtime/provider-tracker.js +0 -1
  189. package/dist/runtime/run-context.js +0 -1
  190. package/dist/runtime/session-coordinator.d.ts +2 -2
  191. package/dist/runtime/session-coordinator.js +2 -3
  192. package/dist/runtime/session-title.js +0 -1
  193. package/dist/runtime/tool-defaults-wrapper.js +0 -1
  194. package/dist/runtime/validation.js +0 -1
  195. package/dist/runtime/workflow-events.js +0 -1
  196. package/dist/runtime/workflow-runner.d.ts +1 -0
  197. package/dist/runtime/workflow-runner.js +8 -3
  198. package/dist/runtime/workflow-types.js +0 -1
  199. package/dist/sentiment/adapters/finnhub.js +0 -1
  200. package/dist/sentiment/adapters/reddit.js +0 -1
  201. package/dist/sentiment/adapters/twitter.js +0 -1
  202. package/dist/sentiment/adapters/web.js +0 -1
  203. package/dist/sentiment/index.js +4 -2
  204. package/dist/sentiment/insights.js +0 -1
  205. package/dist/sentiment/keywords.js +0 -1
  206. package/dist/sentiment/pipeline.js +0 -1
  207. package/dist/sentiment/scorer.js +0 -1
  208. package/dist/sentiment/store.js +0 -1
  209. package/dist/sentiment/trends.js +0 -1
  210. package/dist/sentiment/types.js +0 -1
  211. package/dist/system-prompt.js +0 -1
  212. package/dist/tool-kit.js +0 -1
  213. package/dist/tools/fundamentals/company-overview.d.ts +1 -1
  214. package/dist/tools/fundamentals/company-overview.js +2 -1
  215. package/dist/tools/fundamentals/comps.js +6 -4
  216. package/dist/tools/fundamentals/dcf.js +37 -9
  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 +88 -9
  220. package/dist/tools/fundamentals/sec-filings.js +0 -1
  221. package/dist/tools/index.d.ts +121 -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.js +0 -1
  225. package/dist/tools/macro/fear-greed.d.ts +1 -1
  226. package/dist/tools/macro/fear-greed.js +0 -1
  227. package/dist/tools/macro/fred-data.d.ts +1 -1
  228. package/dist/tools/macro/fred-data.js +2 -1
  229. package/dist/tools/market/crypto-history.js +0 -1
  230. package/dist/tools/market/crypto-price.d.ts +2 -2
  231. package/dist/tools/market/crypto-price.js +0 -1
  232. package/dist/tools/market/price-comparison.d.ts +30 -0
  233. package/dist/tools/market/price-comparison.js +202 -0
  234. package/dist/tools/market/screen-stocks.js +0 -1
  235. package/dist/tools/market/search-ticker.js +1 -2
  236. package/dist/tools/market/stock-history.d.ts +18 -3
  237. package/dist/tools/market/stock-history.js +132 -18
  238. package/dist/tools/market/stock-quote.d.ts +2 -2
  239. package/dist/tools/market/stock-quote.js +0 -1
  240. package/dist/tools/options/greeks.js +0 -1
  241. package/dist/tools/options/option-chain.d.ts +2 -2
  242. package/dist/tools/options/option-chain.js +0 -1
  243. package/dist/tools/portfolio/alerts.d.ts +2 -1
  244. package/dist/tools/portfolio/alerts.js +228 -2
  245. package/dist/tools/portfolio/correlation.d.ts +1 -1
  246. package/dist/tools/portfolio/correlation.js +23 -5
  247. package/dist/tools/portfolio/daily-report.js +0 -1
  248. package/dist/tools/portfolio/holdings-overlap.js +0 -1
  249. package/dist/tools/portfolio/notifications.js +0 -1
  250. package/dist/tools/portfolio/risk-analysis.d.ts +2 -2
  251. package/dist/tools/portfolio/risk-analysis.js +0 -1
  252. package/dist/tools/portfolio/tracker.d.ts +3 -1
  253. package/dist/tools/portfolio/tracker.js +57 -10
  254. package/dist/tools/portfolio/watchlist.d.ts +3 -6
  255. package/dist/tools/portfolio/watchlist.js +101 -110
  256. package/dist/tools/sentiment/insight-format.js +0 -1
  257. package/dist/tools/sentiment/query-match.js +0 -1
  258. package/dist/tools/sentiment/reddit-sentiment.js +0 -1
  259. package/dist/tools/sentiment/sentiment-summary.js +8 -4
  260. package/dist/tools/sentiment/sentiment-trend.d.ts +5 -1
  261. package/dist/tools/sentiment/sentiment-trend.js +6 -2
  262. package/dist/tools/sentiment/twitter-sentiment.js +0 -1
  263. package/dist/tools/sentiment/untrusted-text.js +0 -1
  264. package/dist/tools/sentiment/web-search.d.ts +1 -1
  265. package/dist/tools/sentiment/web-search.js +0 -1
  266. package/dist/tools/sentiment/web-sentiment.js +0 -1
  267. package/dist/tools/technical/backtest.js +0 -1
  268. package/dist/tools/technical/indicators.js +0 -1
  269. package/dist/types/fundamentals.js +0 -1
  270. package/dist/types/index.js +0 -1
  271. package/dist/types/macro.js +0 -1
  272. package/dist/types/market.d.ts +8 -0
  273. package/dist/types/market.js +0 -1
  274. package/dist/types/options.js +0 -1
  275. package/dist/types/portfolio.js +0 -1
  276. package/dist/types/prediction-markets.js +0 -1
  277. package/dist/types/sentiment.js +0 -1
  278. package/dist/workflows/compare-assets.js +0 -1
  279. package/dist/workflows/index.js +0 -1
  280. package/dist/workflows/options-screener.js +0 -1
  281. package/dist/workflows/portfolio-builder.js +0 -1
  282. package/gui/web/dist/assets/CatalogOverlay-Cy8Fq0fn.js +1 -0
  283. package/gui/web/dist/assets/allocation-donut-DgBRIKCk.js +52 -0
  284. package/gui/web/dist/assets/index-DIlFyIOO.js +66 -0
  285. package/gui/web/dist/assets/index-DS4jESOB.css +2 -0
  286. package/gui/web/dist/assets/market-chart-DammaCjH.js +1 -0
  287. package/gui/web/dist/assets/utils-CnADgYgh.js +1 -0
  288. package/gui/web/dist/index.html +3 -2
  289. package/package.json +23 -26
  290. package/dist/analysts/contracts.js.map +0 -1
  291. package/dist/analysts/orchestrator.js.map +0 -1
  292. package/dist/cli-main.js.map +0 -1
  293. package/dist/cli.js.map +0 -1
  294. package/dist/config.js.map +0 -1
  295. package/dist/doctor/cli-command.js.map +0 -1
  296. package/dist/doctor/render.js.map +0 -1
  297. package/dist/doctor/report.js.map +0 -1
  298. package/dist/index.js.map +0 -1
  299. package/dist/infra/cache.js.map +0 -1
  300. package/dist/infra/freshness.js.map +0 -1
  301. package/dist/infra/http-client.js.map +0 -1
  302. package/dist/infra/index.js.map +0 -1
  303. package/dist/infra/market-calendar.js.map +0 -1
  304. package/dist/infra/native-dependencies.js.map +0 -1
  305. package/dist/infra/node-version.js.map +0 -1
  306. package/dist/infra/open-url.js.map +0 -1
  307. package/dist/infra/opencandle-paths.js.map +0 -1
  308. package/dist/infra/rate-limiter.js.map +0 -1
  309. package/dist/market-state/alert-conditions.js.map +0 -1
  310. package/dist/market-state/alert-runner.js.map +0 -1
  311. package/dist/market-state/daily-report.js.map +0 -1
  312. package/dist/market-state/local-automation-service.js.map +0 -1
  313. package/dist/market-state/notification-delivery.js.map +0 -1
  314. package/dist/market-state/resolve-for-mutation.js.map +0 -1
  315. package/dist/market-state/resolve.js.map +0 -1
  316. package/dist/market-state/service.js.map +0 -1
  317. package/dist/market-state/summaries.js.map +0 -1
  318. package/dist/memory/index.js.map +0 -1
  319. package/dist/memory/manager.js.map +0 -1
  320. package/dist/memory/preference-extractor.js.map +0 -1
  321. package/dist/memory/retrieval.js.map +0 -1
  322. package/dist/memory/sqlite.js.map +0 -1
  323. package/dist/memory/storage.js.map +0 -1
  324. package/dist/memory/tool-defaults.js.map +0 -1
  325. package/dist/memory/types.js.map +0 -1
  326. package/dist/monitor.js.map +0 -1
  327. package/dist/onboarding/connect.js.map +0 -1
  328. package/dist/onboarding/credential-interceptor.js.map +0 -1
  329. package/dist/onboarding/degradation-accumulator.js.map +0 -1
  330. package/dist/onboarding/prompt-user.js.map +0 -1
  331. package/dist/onboarding/provider-status.js.map +0 -1
  332. package/dist/onboarding/providers.js.map +0 -1
  333. package/dist/onboarding/state.js.map +0 -1
  334. package/dist/onboarding/tool-helpers.js.map +0 -1
  335. package/dist/onboarding/tool-tags.js.map +0 -1
  336. package/dist/onboarding/validation.js.map +0 -1
  337. package/dist/pi/opencandle-extension.js.map +0 -1
  338. package/dist/pi/session-action-dedupe.js.map +0 -1
  339. package/dist/pi/session-storage.js.map +0 -1
  340. package/dist/pi/session-writer-lock.js.map +0 -1
  341. package/dist/pi/session.js.map +0 -1
  342. package/dist/pi/setup.js.map +0 -1
  343. package/dist/pi/tool-adapter.js.map +0 -1
  344. package/dist/pi/tui-session-coordinator.js.map +0 -1
  345. package/dist/prompts/context-builder.js.map +0 -1
  346. package/dist/prompts/disclaimer.js.map +0 -1
  347. package/dist/prompts/policy-cards.js.map +0 -1
  348. package/dist/prompts/sections.js.map +0 -1
  349. package/dist/prompts/symbol-preflight.js.map +0 -1
  350. package/dist/prompts/workflow-prompts.js.map +0 -1
  351. package/dist/providers/alpha-vantage.js.map +0 -1
  352. package/dist/providers/coingecko.js.map +0 -1
  353. package/dist/providers/errors.js.map +0 -1
  354. package/dist/providers/exa-search.js.map +0 -1
  355. package/dist/providers/external-tool-command.js.map +0 -1
  356. package/dist/providers/external-tool-error.js.map +0 -1
  357. package/dist/providers/fear-greed.js.map +0 -1
  358. package/dist/providers/finnhub.js.map +0 -1
  359. package/dist/providers/fred.js.map +0 -1
  360. package/dist/providers/index.js.map +0 -1
  361. package/dist/providers/polymarket.js.map +0 -1
  362. package/dist/providers/provider-credential-error.js.map +0 -1
  363. package/dist/providers/reddit-cli.js.map +0 -1
  364. package/dist/providers/reddit.js.map +0 -1
  365. package/dist/providers/sec-edgar.js.map +0 -1
  366. package/dist/providers/tradingview.js.map +0 -1
  367. package/dist/providers/twitter-cli.js.map +0 -1
  368. package/dist/providers/twitter.js.map +0 -1
  369. package/dist/providers/web-search.js.map +0 -1
  370. package/dist/providers/with-fallback.js.map +0 -1
  371. package/dist/providers/wrap-provider.js.map +0 -1
  372. package/dist/providers/yahoo-finance.js.map +0 -1
  373. package/dist/routing/classify-intent.js.map +0 -1
  374. package/dist/routing/defaults.js.map +0 -1
  375. package/dist/routing/entity-extractor.js.map +0 -1
  376. package/dist/routing/fund-symbols.js.map +0 -1
  377. package/dist/routing/horizon.js.map +0 -1
  378. package/dist/routing/index.js.map +0 -1
  379. package/dist/routing/legacy-rule-router.js.map +0 -1
  380. package/dist/routing/planning.js.map +0 -1
  381. package/dist/routing/route-manifest.js.map +0 -1
  382. package/dist/routing/router-llm-client.js.map +0 -1
  383. package/dist/routing/router-prompt.js.map +0 -1
  384. package/dist/routing/router-types.js.map +0 -1
  385. package/dist/routing/router.js.map +0 -1
  386. package/dist/routing/slot-resolver.js.map +0 -1
  387. package/dist/routing/symbol-disambiguator.js.map +0 -1
  388. package/dist/routing/turn-context.js.map +0 -1
  389. package/dist/routing/types.js.map +0 -1
  390. package/dist/runtime/answer-contracts.js.map +0 -1
  391. package/dist/runtime/artifact-contracts.js.map +0 -1
  392. package/dist/runtime/evidence.js.map +0 -1
  393. package/dist/runtime/numeric-claims.js.map +0 -1
  394. package/dist/runtime/planning-evidence.js.map +0 -1
  395. package/dist/runtime/prompt-step.js.map +0 -1
  396. package/dist/runtime/provider-tracker.js.map +0 -1
  397. package/dist/runtime/run-context.js.map +0 -1
  398. package/dist/runtime/session-coordinator.js.map +0 -1
  399. package/dist/runtime/session-title.js.map +0 -1
  400. package/dist/runtime/tool-defaults-wrapper.js.map +0 -1
  401. package/dist/runtime/validation.js.map +0 -1
  402. package/dist/runtime/workflow-events.js.map +0 -1
  403. package/dist/runtime/workflow-runner.js.map +0 -1
  404. package/dist/runtime/workflow-types.js.map +0 -1
  405. package/dist/sentiment/adapters/finnhub.js.map +0 -1
  406. package/dist/sentiment/adapters/reddit.js.map +0 -1
  407. package/dist/sentiment/adapters/twitter.js.map +0 -1
  408. package/dist/sentiment/adapters/web.js.map +0 -1
  409. package/dist/sentiment/index.js.map +0 -1
  410. package/dist/sentiment/insights.js.map +0 -1
  411. package/dist/sentiment/keywords.js.map +0 -1
  412. package/dist/sentiment/pipeline.js.map +0 -1
  413. package/dist/sentiment/scorer.js.map +0 -1
  414. package/dist/sentiment/store.js.map +0 -1
  415. package/dist/sentiment/trends.js.map +0 -1
  416. package/dist/sentiment/types.js.map +0 -1
  417. package/dist/system-prompt.js.map +0 -1
  418. package/dist/tool-kit.js.map +0 -1
  419. package/dist/tools/fundamentals/company-overview.js.map +0 -1
  420. package/dist/tools/fundamentals/comps.js.map +0 -1
  421. package/dist/tools/fundamentals/dcf.js.map +0 -1
  422. package/dist/tools/fundamentals/earnings.js.map +0 -1
  423. package/dist/tools/fundamentals/financials.js.map +0 -1
  424. package/dist/tools/fundamentals/sec-filings.js.map +0 -1
  425. package/dist/tools/index.js.map +0 -1
  426. package/dist/tools/interaction/ask-user.js.map +0 -1
  427. package/dist/tools/macro/event-probabilities.js.map +0 -1
  428. package/dist/tools/macro/fear-greed.js.map +0 -1
  429. package/dist/tools/macro/fred-data.js.map +0 -1
  430. package/dist/tools/market/crypto-history.js.map +0 -1
  431. package/dist/tools/market/crypto-price.js.map +0 -1
  432. package/dist/tools/market/screen-stocks.js.map +0 -1
  433. package/dist/tools/market/search-ticker.js.map +0 -1
  434. package/dist/tools/market/stock-history.js.map +0 -1
  435. package/dist/tools/market/stock-quote.js.map +0 -1
  436. package/dist/tools/options/greeks.js.map +0 -1
  437. package/dist/tools/options/option-chain.js.map +0 -1
  438. package/dist/tools/portfolio/alerts.js.map +0 -1
  439. package/dist/tools/portfolio/correlation.js.map +0 -1
  440. package/dist/tools/portfolio/daily-report.js.map +0 -1
  441. package/dist/tools/portfolio/holdings-overlap.js.map +0 -1
  442. package/dist/tools/portfolio/notifications.js.map +0 -1
  443. package/dist/tools/portfolio/risk-analysis.js.map +0 -1
  444. package/dist/tools/portfolio/tracker.js.map +0 -1
  445. package/dist/tools/portfolio/watchlist.js.map +0 -1
  446. package/dist/tools/sentiment/insight-format.js.map +0 -1
  447. package/dist/tools/sentiment/query-match.js.map +0 -1
  448. package/dist/tools/sentiment/reddit-sentiment.js.map +0 -1
  449. package/dist/tools/sentiment/sentiment-summary.js.map +0 -1
  450. package/dist/tools/sentiment/sentiment-trend.js.map +0 -1
  451. package/dist/tools/sentiment/twitter-sentiment.js.map +0 -1
  452. package/dist/tools/sentiment/untrusted-text.js.map +0 -1
  453. package/dist/tools/sentiment/web-search.js.map +0 -1
  454. package/dist/tools/sentiment/web-sentiment.js.map +0 -1
  455. package/dist/tools/technical/backtest.js.map +0 -1
  456. package/dist/tools/technical/indicators.js.map +0 -1
  457. package/dist/types/fundamentals.js.map +0 -1
  458. package/dist/types/index.js.map +0 -1
  459. package/dist/types/macro.js.map +0 -1
  460. package/dist/types/market.js.map +0 -1
  461. package/dist/types/options.js.map +0 -1
  462. package/dist/types/portfolio.js.map +0 -1
  463. package/dist/types/prediction-markets.js.map +0 -1
  464. package/dist/types/sentiment.js.map +0 -1
  465. package/dist/workflows/compare-assets.js.map +0 -1
  466. package/dist/workflows/index.js.map +0 -1
  467. package/dist/workflows/options-screener.js.map +0 -1
  468. package/dist/workflows/portfolio-builder.js.map +0 -1
  469. package/gui/server/ask-user-bridge.ts +0 -89
  470. package/gui/server/automation-heartbeat.ts +0 -97
  471. package/gui/server/background-quotes.ts +0 -127
  472. package/gui/server/chat-event-adapter.ts +0 -294
  473. package/gui/server/gui-session-manager.ts +0 -5
  474. package/gui/server/http-routes.ts +0 -1201
  475. package/gui/server/invoke-tool.ts +0 -490
  476. package/gui/server/live-chat-event-adapter.ts +0 -243
  477. package/gui/server/local-session-coordinator.ts +0 -97
  478. package/gui/server/market-state-api.ts +0 -331
  479. package/gui/server/model-setup.ts +0 -254
  480. package/gui/server/package.json +0 -5
  481. package/gui/server/private-api-access.ts +0 -62
  482. package/gui/server/projector.ts +0 -392
  483. package/gui/server/prompt-observation.ts +0 -58
  484. package/gui/server/quote-snapshot-store.ts +0 -50
  485. package/gui/server/server.ts +0 -289
  486. package/gui/server/session-actions.ts +0 -323
  487. package/gui/server/session-entry-wait.ts +0 -179
  488. package/gui/server/shutdown.ts +0 -47
  489. package/gui/server/tool-invoke-ack.ts +0 -49
  490. package/gui/server/tool-metadata.ts +0 -167
  491. package/gui/server/websocket.ts +0 -138
  492. package/gui/server/writer-lock.ts +0 -1
  493. package/gui/server/ws-hub.ts +0 -403
  494. package/gui/shared/chat-events.ts +0 -165
  495. package/gui/shared/event-reducer.ts +0 -220
  496. package/gui/web/dist/assets/CatalogOverlay-DZ1niyQm.js +0 -1
  497. package/gui/web/dist/assets/index-D4F9AJnn.css +0 -2
  498. package/gui/web/dist/assets/index-DtqMMBTr.js +0 -65
  499. package/src/analysts/contracts.ts +0 -176
  500. package/src/analysts/orchestrator.ts +0 -244
  501. package/src/cli-main.ts +0 -510
  502. package/src/cli.ts +0 -17
  503. package/src/config.ts +0 -272
  504. package/src/doctor/cli-command.ts +0 -83
  505. package/src/doctor/render.ts +0 -37
  506. package/src/doctor/report.ts +0 -638
  507. package/src/index.ts +0 -5
  508. package/src/infra/cache.ts +0 -127
  509. package/src/infra/freshness.ts +0 -165
  510. package/src/infra/http-client.ts +0 -134
  511. package/src/infra/index.ts +0 -14
  512. package/src/infra/market-calendar.ts +0 -193
  513. package/src/infra/native-dependencies.ts +0 -84
  514. package/src/infra/node-version.ts +0 -23
  515. package/src/infra/open-url.ts +0 -28
  516. package/src/infra/opencandle-paths.ts +0 -53
  517. package/src/infra/rate-limiter.ts +0 -77
  518. package/src/market-state/alert-conditions.ts +0 -82
  519. package/src/market-state/alert-runner.ts +0 -863
  520. package/src/market-state/daily-report.ts +0 -237
  521. package/src/market-state/local-automation-service.ts +0 -162
  522. package/src/market-state/notification-delivery.ts +0 -158
  523. package/src/market-state/resolve-for-mutation.ts +0 -24
  524. package/src/market-state/resolve.ts +0 -112
  525. package/src/market-state/service.ts +0 -2208
  526. package/src/market-state/summaries.ts +0 -75
  527. package/src/memory/index.ts +0 -10
  528. package/src/memory/manager.ts +0 -190
  529. package/src/memory/preference-extractor.ts +0 -106
  530. package/src/memory/retrieval.ts +0 -71
  531. package/src/memory/sqlite.ts +0 -577
  532. package/src/memory/storage.ts +0 -195
  533. package/src/memory/tool-defaults.ts +0 -108
  534. package/src/memory/types.ts +0 -71
  535. package/src/monitor.ts +0 -123
  536. package/src/onboarding/connect.ts +0 -177
  537. package/src/onboarding/credential-interceptor.ts +0 -122
  538. package/src/onboarding/degradation-accumulator.ts +0 -77
  539. package/src/onboarding/prompt-user.ts +0 -85
  540. package/src/onboarding/provider-status.ts +0 -382
  541. package/src/onboarding/providers.ts +0 -442
  542. package/src/onboarding/state.ts +0 -216
  543. package/src/onboarding/tool-helpers.ts +0 -104
  544. package/src/onboarding/tool-tags.ts +0 -244
  545. package/src/onboarding/validation.ts +0 -152
  546. package/src/pi/opencandle-extension.ts +0 -1294
  547. package/src/pi/session-action-dedupe.ts +0 -155
  548. package/src/pi/session-storage.ts +0 -5
  549. package/src/pi/session-writer-lock.ts +0 -426
  550. package/src/pi/session.ts +0 -84
  551. package/src/pi/setup.ts +0 -399
  552. package/src/pi/tool-adapter.ts +0 -49
  553. package/src/pi/tui-session-coordinator.ts +0 -351
  554. package/src/prompts/context-builder.ts +0 -326
  555. package/src/prompts/disclaimer.ts +0 -9
  556. package/src/prompts/policy-cards.ts +0 -228
  557. package/src/prompts/sections.ts +0 -46
  558. package/src/prompts/symbol-preflight.ts +0 -80
  559. package/src/prompts/workflow-prompts.ts +0 -504
  560. package/src/providers/alpha-vantage.ts +0 -340
  561. package/src/providers/coingecko.ts +0 -95
  562. package/src/providers/errors.ts +0 -9
  563. package/src/providers/exa-search.ts +0 -375
  564. package/src/providers/external-tool-command.ts +0 -164
  565. package/src/providers/external-tool-error.ts +0 -20
  566. package/src/providers/fear-greed.ts +0 -45
  567. package/src/providers/finnhub.ts +0 -125
  568. package/src/providers/fred.ts +0 -83
  569. package/src/providers/index.ts +0 -17
  570. package/src/providers/polymarket.ts +0 -214
  571. package/src/providers/provider-credential-error.ts +0 -23
  572. package/src/providers/reddit-cli.ts +0 -286
  573. package/src/providers/reddit.ts +0 -106
  574. package/src/providers/sec-edgar.ts +0 -326
  575. package/src/providers/tradingview.ts +0 -399
  576. package/src/providers/twitter-cli.ts +0 -202
  577. package/src/providers/twitter.ts +0 -102
  578. package/src/providers/web-search.ts +0 -303
  579. package/src/providers/with-fallback.ts +0 -42
  580. package/src/providers/wrap-provider.ts +0 -105
  581. package/src/providers/yahoo-finance.ts +0 -984
  582. package/src/routing/classify-intent.ts +0 -380
  583. package/src/routing/defaults.ts +0 -29
  584. package/src/routing/entity-extractor.ts +0 -557
  585. package/src/routing/fund-symbols.ts +0 -58
  586. package/src/routing/horizon.ts +0 -7
  587. package/src/routing/index.ts +0 -70
  588. package/src/routing/legacy-rule-router.ts +0 -13
  589. package/src/routing/planning.ts +0 -829
  590. package/src/routing/route-manifest.ts +0 -308
  591. package/src/routing/router-llm-client.ts +0 -64
  592. package/src/routing/router-prompt.ts +0 -159
  593. package/src/routing/router-types.ts +0 -84
  594. package/src/routing/router.ts +0 -1332
  595. package/src/routing/slot-resolver.ts +0 -213
  596. package/src/routing/symbol-disambiguator.ts +0 -72
  597. package/src/routing/turn-context.ts +0 -108
  598. package/src/routing/types.ts +0 -77
  599. package/src/runtime/answer-contracts.ts +0 -693
  600. package/src/runtime/artifact-contracts.ts +0 -77
  601. package/src/runtime/evidence.ts +0 -78
  602. package/src/runtime/numeric-claims.ts +0 -108
  603. package/src/runtime/planning-evidence.ts +0 -597
  604. package/src/runtime/prompt-step.ts +0 -185
  605. package/src/runtime/provider-tracker.ts +0 -40
  606. package/src/runtime/run-context.ts +0 -32
  607. package/src/runtime/session-coordinator.ts +0 -1037
  608. package/src/runtime/session-title.ts +0 -60
  609. package/src/runtime/tool-defaults-wrapper.ts +0 -43
  610. package/src/runtime/validation.ts +0 -211
  611. package/src/runtime/workflow-events.ts +0 -77
  612. package/src/runtime/workflow-runner.ts +0 -182
  613. package/src/runtime/workflow-types.ts +0 -105
  614. package/src/sentiment/adapters/finnhub.ts +0 -49
  615. package/src/sentiment/adapters/reddit.ts +0 -65
  616. package/src/sentiment/adapters/twitter.ts +0 -36
  617. package/src/sentiment/adapters/web.ts +0 -44
  618. package/src/sentiment/index.ts +0 -49
  619. package/src/sentiment/insights.ts +0 -269
  620. package/src/sentiment/keywords.ts +0 -31
  621. package/src/sentiment/pipeline.ts +0 -91
  622. package/src/sentiment/scorer.ts +0 -89
  623. package/src/sentiment/store.ts +0 -260
  624. package/src/sentiment/trends.ts +0 -96
  625. package/src/sentiment/types.ts +0 -112
  626. package/src/system-prompt.ts +0 -115
  627. package/src/tool-kit.ts +0 -69
  628. package/src/tools/AGENTS.md +0 -36
  629. package/src/tools/fundamentals/company-overview.ts +0 -64
  630. package/src/tools/fundamentals/comps.ts +0 -180
  631. package/src/tools/fundamentals/dcf.ts +0 -447
  632. package/src/tools/fundamentals/earnings.ts +0 -57
  633. package/src/tools/fundamentals/financials.ts +0 -63
  634. package/src/tools/fundamentals/sec-filings.ts +0 -105
  635. package/src/tools/index.ts +0 -104
  636. package/src/tools/interaction/ask-user.ts +0 -93
  637. package/src/tools/macro/event-probabilities.ts +0 -141
  638. package/src/tools/macro/fear-greed.ts +0 -41
  639. package/src/tools/macro/fred-data.ts +0 -92
  640. package/src/tools/market/crypto-history.ts +0 -72
  641. package/src/tools/market/crypto-price.ts +0 -65
  642. package/src/tools/market/screen-stocks.ts +0 -290
  643. package/src/tools/market/search-ticker.ts +0 -254
  644. package/src/tools/market/stock-history.ts +0 -104
  645. package/src/tools/market/stock-quote.ts +0 -73
  646. package/src/tools/options/greeks.ts +0 -81
  647. package/src/tools/options/option-chain.ts +0 -134
  648. package/src/tools/portfolio/alerts.ts +0 -457
  649. package/src/tools/portfolio/correlation.ts +0 -189
  650. package/src/tools/portfolio/daily-report.ts +0 -107
  651. package/src/tools/portfolio/holdings-overlap.ts +0 -139
  652. package/src/tools/portfolio/notifications.ts +0 -45
  653. package/src/tools/portfolio/risk-analysis.ts +0 -173
  654. package/src/tools/portfolio/tracker.ts +0 -308
  655. package/src/tools/portfolio/watchlist.ts +0 -288
  656. package/src/tools/sentiment/insight-format.ts +0 -50
  657. package/src/tools/sentiment/query-match.ts +0 -117
  658. package/src/tools/sentiment/reddit-sentiment.ts +0 -403
  659. package/src/tools/sentiment/sentiment-summary.ts +0 -383
  660. package/src/tools/sentiment/sentiment-trend.ts +0 -75
  661. package/src/tools/sentiment/twitter-sentiment.ts +0 -287
  662. package/src/tools/sentiment/untrusted-text.ts +0 -21
  663. package/src/tools/sentiment/web-search.ts +0 -186
  664. package/src/tools/sentiment/web-sentiment.ts +0 -96
  665. package/src/tools/technical/backtest.ts +0 -336
  666. package/src/tools/technical/indicators.ts +0 -281
  667. package/src/types/fundamentals.ts +0 -47
  668. package/src/types/index.ts +0 -26
  669. package/src/types/macro.ts +0 -27
  670. package/src/types/market.ts +0 -46
  671. package/src/types/options.ts +0 -53
  672. package/src/types/portfolio.ts +0 -83
  673. package/src/types/prediction-markets.ts +0 -13
  674. package/src/types/sentiment.ts +0 -129
  675. package/src/workflows/compare-assets.ts +0 -89
  676. package/src/workflows/index.ts +0 -3
  677. package/src/workflows/options-screener.ts +0 -125
  678. package/src/workflows/portfolio-builder.ts +0 -63
@@ -1,1037 +0,0 @@
1
- import type {
2
- ExtensionAPI,
3
- ExtensionCommandContext,
4
- ExtensionContext,
5
- SessionEntry,
6
- } from "@earendil-works/pi-coding-agent";
7
- import { isAnalystSplit, parseAnalystOutput, parseDebateOutput } from "../analysts/contracts.js";
8
- import { buildAnalystVoteTallyBlock } from "../analysts/orchestrator.js";
9
- import type { FreshnessStamp } from "../infra/freshness.js";
10
- import { MarketStateService } from "../market-state/service.js";
11
- import {
12
- formatJsonSummary,
13
- formatLatestReportSummary,
14
- formatPortfolioSummary,
15
- formatWatchlistSummary,
16
- } from "../market-state/summaries.js";
17
- import { getAllDefaults, initDefaultDatabase, MemoryStorage } from "../memory/index.js";
18
-
19
- /**
20
- * Alias for the session-manager handle extensions receive via
21
- * `ExtensionContext`. `ReadonlySessionManager` is defined inside pi-coding-
22
- * agent but is not re-exported from the package's `.` entry, so we derive
23
- * the shape we need from the public `ExtensionContext` type.
24
- */
25
- type ReadonlySessionManager = ExtensionContext["sessionManager"];
26
-
27
- import type Database from "better-sqlite3";
28
- import type { FilteredMemoryEntry } from "../memory/manager.js";
29
- import { MemoryManager } from "../memory/manager.js";
30
- import { extractPreferences } from "../memory/preference-extractor.js";
31
- import type { MemoryEntry } from "../memory/types.js";
32
- import { runOpenCandleSetup } from "../pi/setup.js";
33
- import { type FallbackContext, PromptContextBuilder } from "../prompts/context-builder.js";
34
- import type { SymbolValidationCache } from "../prompts/symbol-preflight.js";
35
- import type { RouterRouteKind } from "../routing/router-types.js";
36
- import type { ResolvedTurnContext } from "../routing/turn-context.js";
37
- import { getAddonToolDescriptions } from "../tool-kit.js";
38
- import type { EvidenceRecord } from "./evidence.js";
39
- import { collectToolNumbers, extractNumericClaims } from "./numeric-claims.js";
40
- import type { WorkflowDefinition } from "./prompt-step.js";
41
- import {
42
- captureToolEvidence,
43
- extractAssistantText,
44
- promptStepOutput,
45
- toStepDefinitions,
46
- } from "./prompt-step.js";
47
- import { ProviderTracker } from "./provider-tracker.js";
48
- import { clearRunContext, type RunContextToken, setRunContext } from "./run-context.js";
49
- import { checkNumberMatch } from "./validation.js";
50
- import { WorkflowEventLogger } from "./workflow-events.js";
51
- import { WorkflowRunner } from "./workflow-runner.js";
52
- import type { AnalystOutput, StepOutput, WorkflowRun } from "./workflow-types.js";
53
-
54
- const PROMPT_SETTLE_POLL_MS = 25;
55
- const IMMEDIATE_IDLE_GRACE_MS = 100;
56
-
57
- interface ActiveWorkflowRunRef {
58
- active: boolean;
59
- contextToken: RunContextToken;
60
- }
61
-
62
- interface ActiveStepCapture {
63
- evidence: EvidenceRecord[];
64
- pendingTools: Map<string, { tool: string; args: unknown; startedAt: string }>;
65
- rawText: string;
66
- }
67
-
68
- function parseMaybeJson(raw: unknown): Record<string, unknown> | undefined {
69
- if (typeof raw !== "string" || raw.length === 0) return undefined;
70
- try {
71
- const parsed = JSON.parse(raw);
72
- return parsed && typeof parsed === "object" && !Array.isArray(parsed)
73
- ? (parsed as Record<string, unknown>)
74
- : undefined;
75
- } catch {
76
- return undefined;
77
- }
78
- }
79
-
80
- type QueueContext =
81
- | ExtensionCommandContext
82
- | {
83
- isIdle(): boolean;
84
- hasPendingMessages?(): boolean;
85
- ui?: { notify(message: string, level?: string): void };
86
- sessionManager?: { getEntries(): SessionEntry[] };
87
- };
88
-
89
- function hasPendingMessages(ctx: QueueContext): boolean {
90
- return ctx.hasPendingMessages?.() ?? false;
91
- }
92
-
93
- function isReadyForNextPrompt(ctx: QueueContext): boolean {
94
- return ctx.isIdle() && !hasPendingMessages(ctx);
95
- }
96
-
97
- function readSessionEntries(ctx: QueueContext): SessionEntry[] {
98
- const manager = "sessionManager" in ctx ? ctx.sessionManager : undefined;
99
- return manager?.getEntries?.() ?? [];
100
- }
101
-
102
- function sleep(ms: number): Promise<void> {
103
- return new Promise((resolve) => setTimeout(resolve, ms));
104
- }
105
-
106
- async function waitForPromptSettlement(
107
- ctx: QueueContext,
108
- isCurrentRun: () => boolean,
109
- options: { requireActivity?: boolean } = {},
110
- ): Promise<boolean> {
111
- let sawBusyOrPending = !isReadyForNextPrompt(ctx);
112
- const startedAt = Date.now();
113
-
114
- while (isCurrentRun()) {
115
- const ready = isReadyForNextPrompt(ctx);
116
- if (!ready) {
117
- sawBusyOrPending = true;
118
- }
119
-
120
- if (sawBusyOrPending && ready) {
121
- return true;
122
- }
123
-
124
- if (
125
- !options.requireActivity &&
126
- !sawBusyOrPending &&
127
- ready &&
128
- Date.now() - startedAt >= IMMEDIATE_IDLE_GRACE_MS
129
- ) {
130
- return true;
131
- }
132
-
133
- await sleep(PROMPT_SETTLE_POLL_MS);
134
- }
135
-
136
- return false;
137
- }
138
-
139
- /**
140
- * Coordinates session lifecycle, memory, workflow execution,
141
- * and prompt assembly. The extension delegates to this.
142
- */
143
- export class SessionCoordinator {
144
- private db: Database.Database | null = null;
145
- private storage: MemoryStorage | null = null;
146
- private memoryManager: MemoryManager | null = null;
147
- private eventLogger: WorkflowEventLogger | null = null;
148
- private runner: WorkflowRunner;
149
- private providerTracker: ProviderTracker;
150
- private activeWorkflowRunRef: ActiveWorkflowRunRef | null = null;
151
- private activeWorkflowType: string | undefined;
152
- private activeStepCapture: ActiveStepCapture | null = null;
153
- private workflowEventCaptureInstalled = false;
154
- private tickerValidationCache: SymbolValidationCache = new Map();
155
- private sessionId = "unknown";
156
-
157
- constructor() {
158
- // Runner is always available — event logger is optional and added after session init
159
- this.providerTracker = new ProviderTracker();
160
- this.runner = new WorkflowRunner({ providerTracker: this.providerTracker });
161
- }
162
-
163
- getStorage(): MemoryStorage | null {
164
- return this.storage;
165
- }
166
-
167
- getRunner(): WorkflowRunner {
168
- return this.runner;
169
- }
170
-
171
- getTickerValidationCache(): SymbolValidationCache {
172
- return this.tickerValidationCache;
173
- }
174
-
175
- clearTickerValidationCache(): void {
176
- this.tickerValidationCache.clear();
177
- }
178
-
179
- /** Initialize session: database, memory, event logger, workflow runner. */
180
- initSession(sessionId: string): void {
181
- this.db = initDefaultDatabase();
182
- this.storage = new MemoryStorage(this.db);
183
- this.memoryManager = new MemoryManager(this.storage);
184
- this.eventLogger = new WorkflowEventLogger(this.db);
185
- this.providerTracker = new ProviderTracker();
186
- this.runner = new WorkflowRunner({
187
- eventLogger: this.eventLogger,
188
- providerTracker: this.providerTracker,
189
- });
190
- this.sessionId = sessionId;
191
- }
192
-
193
- /** Run setup flow. */
194
- async runSetup(
195
- pi: ExtensionAPI,
196
- ctx: ExtensionContext | ExtensionCommandContext,
197
- options: { mode: "startup" | "manual" },
198
- ): Promise<"ready" | "shutdown" | "cancelled"> {
199
- return runOpenCandleSetup(pi, ctx, options);
200
- }
201
-
202
- /** Extract and persist user preferences from natural language. */
203
- extractAndStorePreferences(text: string): void {
204
- if (!this.storage) return;
205
- for (const pref of extractPreferences(text)) {
206
- this.storage.upsertPreference({
207
- key: pref.key,
208
- valueJson: JSON.stringify(pref.value),
209
- confidence: pref.confidence,
210
- source: "inferred",
211
- });
212
- }
213
- }
214
-
215
- /** Record a workflow run in storage. */
216
- recordWorkflowRun(
217
- workflowType: string,
218
- entities: object,
219
- resolved: object,
220
- defaultsUsed: unknown[],
221
- turnType = "workflow",
222
- ): void {
223
- this.storage?.insertWorkflowRun({
224
- sessionId: this.sessionId,
225
- workflowType,
226
- inputSlotsJson: JSON.stringify(entities),
227
- resolvedSlotsJson: JSON.stringify(resolved),
228
- defaultsUsedJson: JSON.stringify(defaultsUsed),
229
- turnType,
230
- });
231
- }
232
-
233
- /**
234
- * Extract the last `max` user/assistant turns from the session branch as
235
- * `{role, text}` pairs, oldest→newest. Walks `sessionManager.getBranch()`
236
- * (root→leaf order) and filters per the intent-routing spec:
237
- *
238
- * - Keep only `type === "message"` entries whose `message.role` is
239
- * `"user"` or `"assistant"`. Compaction, branch_summary, custom, label,
240
- * thinking_level_change, model_change, and session_info entries are
241
- * skipped. Tool-result messages (`role === "toolResult"`) are skipped.
242
- * - Extract concatenated text-block content. User `content` may be a
243
- * plain string; assistant `content` is always an array of blocks, from
244
- * which only `type === "text"` blocks contribute.
245
- * - Drop entries whose resulting text is empty or whitespace-only
246
- * (handles aborted assistant turns and tool-only assistant turns).
247
- * - Slice to the last `max` qualifying entries.
248
- *
249
- * Privacy note: conversational text in priorTurns is NOT filtered by
250
- * `NEVER_TRUST_FROM_MEMORY` (which governs structured memory keys). A
251
- * future `/forget` command is the designated scrubbing primitive — see
252
- * `openspec/changes/router-context-and-observability/` for the follow-up.
253
- */
254
- buildPriorTurns(
255
- sessionManager: ReadonlySessionManager,
256
- max = 5,
257
- ): Array<{ role: "user" | "assistant"; text: string }> {
258
- const branch = sessionManager.getBranch();
259
- const turns: Array<{ role: "user" | "assistant"; text: string }> = [];
260
-
261
- for (const entry of branch) {
262
- if (entry.type !== "message") continue;
263
- const msg = (entry as SessionEntry & { type: "message" }).message;
264
- if (!msg || typeof msg !== "object") continue;
265
- const role = (msg as { role?: unknown }).role;
266
- if (role !== "user" && role !== "assistant") continue;
267
-
268
- const rawContent = (msg as { content?: unknown }).content;
269
- let text = "";
270
- if (typeof rawContent === "string") {
271
- text = rawContent;
272
- } else if (Array.isArray(rawContent)) {
273
- for (const block of rawContent) {
274
- if (
275
- block &&
276
- typeof block === "object" &&
277
- (block as { type?: unknown }).type === "text" &&
278
- typeof (block as { text?: unknown }).text === "string"
279
- ) {
280
- text += (block as { text: string }).text;
281
- }
282
- }
283
- }
284
-
285
- if (text.trim().length === 0) continue;
286
- turns.push({ role, text });
287
- }
288
-
289
- return turns.slice(-max);
290
- }
291
-
292
- /**
293
- * Expose prior turns + recent runs + profile snapshot for the router
294
- * input context. Fixed-window per design.md §7 (last 5 turns, 3 runs).
295
- * `priorTurns` is derived from the session branch at call time; see
296
- * `buildPriorTurns` for the filter rules.
297
- */
298
- buildRouterContextBase(sessionManager: ReadonlySessionManager): {
299
- profileSnapshot: Record<string, unknown>;
300
- recentWorkflowRuns: Array<{
301
- workflowType: string;
302
- turnType: string;
303
- resolvedSlots?: Record<string, unknown>;
304
- createdAt: string;
305
- }>;
306
- priorTurns: Array<{ role: "user" | "assistant"; text: string }>;
307
- } {
308
- const priorTurns = this.buildPriorTurns(sessionManager);
309
- if (!this.storage) {
310
- return { profileSnapshot: {}, recentWorkflowRuns: [], priorTurns };
311
- }
312
- const prefs = this.storage.getPreferencesByNamespace("global");
313
- const profileSnapshot: Record<string, unknown> = {};
314
- for (const p of prefs) {
315
- const key = String(p.key);
316
- const rawValue = p.value_json;
317
- if (typeof rawValue === "string") {
318
- try {
319
- profileSnapshot[key] = JSON.parse(rawValue);
320
- } catch {
321
- profileSnapshot[key] = rawValue;
322
- }
323
- }
324
- }
325
- const runs = this.storage.getRecentWorkflowRuns(3).map((r) => ({
326
- workflowType: String(r.workflow_type ?? ""),
327
- turnType: String(r.turn_type ?? "workflow"),
328
- resolvedSlots: parseMaybeJson(r.resolved_slots_json),
329
- createdAt: String(r.created_at ?? ""),
330
- }));
331
- return { profileSnapshot, recentWorkflowRuns: runs, priorTurns };
332
- }
333
-
334
- retrieveMemoryForRoute(
335
- routeKind: RouterRouteKind,
336
- workflowType?: string,
337
- overriddenSlots?: string[],
338
- ): { entries: MemoryEntry[]; filtered: FilteredMemoryEntry[] } {
339
- if (!this.memoryManager) return { entries: [], filtered: [] };
340
- return this.memoryManager.retrieveDetailed(workflowType ?? routeKind, overriddenSlots);
341
- }
342
-
343
- /** Build system prompt using composable sections. */
344
- buildSystemPrompt(
345
- basePrompt: string,
346
- workflowType?: string,
347
- fallbackContext?: FallbackContext,
348
- resolvedTurnContext?: ResolvedTurnContext,
349
- ): string {
350
- const builder = new PromptContextBuilder();
351
-
352
- const addonTools = getAddonToolDescriptions();
353
- const addonDescriptions =
354
- addonTools.length > 0 ? addonTools.map((t) => `${t.name}: ${t.description}`) : undefined;
355
-
356
- const memoryContext = this.memoryManager
357
- ? this.memoryManager.buildContext(
358
- resolvedTurnContext?.workflow ??
359
- workflowType ??
360
- resolvedTurnContext?.routeKind ??
361
- "unclassified",
362
- )
363
- : undefined;
364
- const savedMarketStateContext =
365
- this.db &&
366
- shouldIncludeSavedMarketStateContext(workflowType, resolvedTurnContext, fallbackContext)
367
- ? buildSavedMarketStateContext(this.db)
368
- : "";
369
- const combinedMemoryContext = [savedMarketStateContext, memoryContext]
370
- .filter((part) => part && part.trim().length > 0)
371
- .join("\n\n");
372
-
373
- builder.populateFromOptions({
374
- workflowType,
375
- memoryContext: combinedMemoryContext || undefined,
376
- addonToolDescriptions: addonDescriptions,
377
- fallbackContext,
378
- resolvedTurnContext,
379
- });
380
-
381
- const toolDefaults = formatToolDefaultsForPrompt();
382
- const defaultsSection =
383
- toolDefaults.length > 0 ? `\n\n## User Tool Defaults\n${toolDefaults.join("\n")}` : "";
384
-
385
- return `${basePrompt}\n\n${builder.build()}${defaultsSection}`;
386
- }
387
-
388
- /**
389
- * Stash a pending fallback context so the very next `before_agent_start`
390
- * hook can slot it into the system prompt. Cleared after consumption so
391
- * subsequent turns do not inherit stale fallback directives.
392
- */
393
- private pendingFallbackContext: FallbackContext | null = null;
394
- private pendingResolvedTurnContext: ResolvedTurnContext | null = null;
395
-
396
- setPendingFallbackContext(ctx: FallbackContext | null): void {
397
- this.pendingFallbackContext = ctx;
398
- }
399
-
400
- setPendingResolvedTurnContext(ctx: ResolvedTurnContext | null): void {
401
- this.pendingResolvedTurnContext = ctx;
402
- }
403
-
404
- consumePendingFallbackContext(): FallbackContext | null {
405
- const ctx = this.pendingFallbackContext;
406
- this.pendingFallbackContext = null;
407
- return ctx;
408
- }
409
-
410
- consumePendingResolvedTurnContext(): ResolvedTurnContext | null {
411
- const ctx = this.pendingResolvedTurnContext;
412
- this.pendingResolvedTurnContext = null;
413
- return ctx;
414
- }
415
-
416
- /**
417
- * Execute a workflow definition through the WorkflowRunner,
418
- * sending prompts via Pi with settlement-based sequencing.
419
- */
420
- executeWorkflow(pi: ExtensionAPI, definition: WorkflowDefinition, ctx: QueueContext): void {
421
- this.startWorkflowRun(pi, definition, ctx, "send");
422
- }
423
-
424
- /**
425
- * Start workflow tracking for an input handler that will return a Pi
426
- * transform result. The current prompt becomes the first workflow prompt;
427
- * only later steps are sent through Pi.
428
- */
429
- /** Workflow type of the in-flight run, for prompt context on workflow turns. */
430
- getActiveWorkflowType(): string | undefined {
431
- return this.activeWorkflowRunRef?.active ? this.activeWorkflowType : undefined;
432
- }
433
-
434
- transformWorkflowInput(
435
- pi: ExtensionAPI,
436
- definition: WorkflowDefinition,
437
- ctx: QueueContext,
438
- ): string | undefined {
439
- if (definition.steps.length === 0) return undefined;
440
- this.startWorkflowRun(pi, definition, ctx, "transform");
441
- return definition.steps[0].prompt;
442
- }
443
-
444
- private startWorkflowRun(
445
- pi: ExtensionAPI,
446
- definition: WorkflowDefinition,
447
- ctx: QueueContext,
448
- firstPromptMode: "send" | "transform",
449
- ): void {
450
- if (definition.steps.length === 0) return;
451
- this.installWorkflowEventCapture(pi);
452
-
453
- const runner = this.runner;
454
- if (this.activeWorkflowRunRef) {
455
- this.activeWorkflowRunRef.active = false;
456
- }
457
- runner.cancel();
458
- this.activeWorkflowType = definition.workflowType;
459
-
460
- const [firstStep] = definition.steps;
461
-
462
- if (firstPromptMode === "send") {
463
- const startedBusy = !isReadyForNextPrompt(ctx);
464
- if (startedBusy) {
465
- pi.sendUserMessage(firstStep.prompt, { deliverAs: "followUp" });
466
- ctx.ui?.notify?.("Analysis queued as follow-up.", "info");
467
- } else {
468
- pi.sendUserMessage(firstStep.prompt);
469
- }
470
- }
471
-
472
- // Make the run's ProviderTracker accessible to tools during execution
473
- const contextToken = setRunContext({ providerTracker: this.providerTracker });
474
- const runRef: ActiveWorkflowRunRef = { active: true, contextToken };
475
- this.activeWorkflowRunRef = runRef;
476
-
477
- // Start the runner in the background for state tracking
478
- const stepDefs = toStepDefinitions(definition.steps);
479
- void runner
480
- .start(
481
- definition.workflowType,
482
- stepDefs,
483
- async (step, stepIndex, _priorEvidence, context) => {
484
- let entriesBeforeStep = readSessionEntries(ctx).length;
485
- const eventCapture = this.startStepCapture();
486
-
487
- // First step was already sent above — later steps are sent here.
488
- if (stepIndex > 0) {
489
- const settled = await waitForPromptSettlement(ctx, () => runRef.active);
490
- if (!settled || !runRef.active) {
491
- throw new Error("run_cancelled");
492
- }
493
- if (shouldSkipRebuttal(runner.getActiveRun(), step.stepType)) {
494
- this.appendWorkflowEvent(pi, "step_skipped", {
495
- stepType: step.stepType,
496
- reason: "analyst_consensus",
497
- });
498
- throw new Error("analyst_consensus");
499
- }
500
- entriesBeforeStep = readSessionEntries(ctx).length;
501
- const prompt = this.prepareWorkflowPrompt(
502
- pi,
503
- definition.steps[stepIndex].prompt,
504
- step.stepType,
505
- runner.getActiveRun(),
506
- );
507
- pi.sendUserMessage(prompt);
508
- }
509
-
510
- const settled = await waitForPromptSettlement(ctx, () => runRef.active, {
511
- requireActivity: stepIndex === 0 && firstPromptMode === "transform",
512
- });
513
- if (!settled || !runRef.active) {
514
- throw new Error("run_cancelled");
515
- }
516
-
517
- let stepEntries = readSessionEntries(ctx).slice(entriesBeforeStep);
518
- let rawText = capturedText(eventCapture, stepEntries);
519
- let output = promptStepOutput(stepIndex, step.stepType, {
520
- evidence: capturedEvidence(eventCapture, stepEntries),
521
- rawText,
522
- });
523
-
524
- if (
525
- isStructuredAnalystStep(step.stepType) &&
526
- !hasStructuredContract(step.stepType, rawText)
527
- ) {
528
- pi.sendUserMessage(
529
- "Please revise your previous response to include the exact required final output format from the stage prompt. Do not add new tool calls.",
530
- );
531
- const retrySettled = await waitForPromptSettlement(ctx, () => runRef.active);
532
- if (!retrySettled || !runRef.active) {
533
- throw new Error("run_cancelled");
534
- }
535
- stepEntries = readSessionEntries(ctx).slice(entriesBeforeStep);
536
- rawText = capturedText(eventCapture, stepEntries);
537
- output = promptStepOutput(stepIndex, step.stepType, {
538
- evidence: capturedEvidence(eventCapture, stepEntries),
539
- rawText,
540
- });
541
- }
542
-
543
- for (const record of output.evidence) {
544
- const value = isPlainObject(record.value) ? record.value : {};
545
- this.eventLogger?.log(context.runId, stepIndex, "tool_called", {
546
- stepType: step.stepType,
547
- tool: value.tool,
548
- args: value.args,
549
- resultDigest: value.resultDigest,
550
- });
551
- }
552
-
553
- if (this.activeStepCapture === eventCapture) {
554
- this.activeStepCapture = null;
555
- }
556
-
557
- const structuredOutput = attachStructuredOutput(pi, output);
558
- if (step.stepType === "synthesis") {
559
- this.emitSynthesisValidation(
560
- pi,
561
- context.runId,
562
- stepIndex,
563
- runner.getActiveRun(),
564
- structuredOutput,
565
- );
566
- }
567
-
568
- return structuredOutput;
569
- },
570
- )
571
- .finally(() => {
572
- if (this.activeWorkflowRunRef === runRef) {
573
- this.activeStepCapture = null;
574
- }
575
- clearRunContext(runRef.contextToken);
576
- if (this.activeWorkflowRunRef === runRef) {
577
- this.activeWorkflowRunRef = null;
578
- }
579
- });
580
- }
581
-
582
- /** Cancel any active workflow. */
583
- cancelActiveWorkflow(): void {
584
- const activeRef = this.activeWorkflowRunRef;
585
- if (activeRef) {
586
- activeRef.active = false;
587
- clearRunContext(activeRef.contextToken);
588
- this.activeWorkflowRunRef = null;
589
- }
590
- this.activeStepCapture = null;
591
- this.runner?.cancel();
592
- }
593
-
594
- private startStepCapture(): ActiveStepCapture {
595
- const capture: ActiveStepCapture = {
596
- evidence: [],
597
- pendingTools: new Map(),
598
- rawText: "",
599
- };
600
- this.activeStepCapture = capture;
601
- return capture;
602
- }
603
-
604
- private installWorkflowEventCapture(pi: ExtensionAPI): void {
605
- const on = (pi as { on?: unknown }).on;
606
- if (this.workflowEventCaptureInstalled || typeof on !== "function") return;
607
- this.workflowEventCaptureInstalled = true;
608
-
609
- pi.on("message_update", (event) => {
610
- const capture = this.activeStepCapture;
611
- if (!capture || event.assistantMessageEvent.type !== "text_delta") return;
612
- capture.rawText += event.assistantMessageEvent.delta;
613
- });
614
-
615
- pi.on("tool_execution_start", (event) => {
616
- const capture = this.activeStepCapture;
617
- if (!capture) return;
618
- capture.pendingTools.set(event.toolCallId, {
619
- tool: event.toolName,
620
- args: event.args ?? {},
621
- startedAt: new Date().toISOString(),
622
- });
623
- });
624
-
625
- pi.on("tool_execution_end", (event) => {
626
- const capture = this.activeStepCapture;
627
- if (!capture) return;
628
- const completedAt = new Date().toISOString();
629
- const pending = capture.pendingTools.get(event.toolCallId);
630
- capture.pendingTools.delete(event.toolCallId);
631
- const tool = pending?.tool ?? event.toolName;
632
- if (!tool) return;
633
- capture.evidence.push(
634
- toolEvidenceRecord({
635
- tool,
636
- args: pending?.args ?? {},
637
- result: event.result,
638
- startedAt: pending?.startedAt ?? completedAt,
639
- completedAt,
640
- isError: event.isError === true,
641
- }),
642
- );
643
- });
644
- }
645
-
646
- private prepareWorkflowPrompt(
647
- pi: ExtensionAPI,
648
- prompt: string,
649
- stepType: string,
650
- run: WorkflowRun | null,
651
- ): string {
652
- if (stepType !== "synthesis") return prompt;
653
- const parsedAnalysts = collectParsedAnalystOutputs(run);
654
- const tallyBlock = buildAnalystVoteTallyBlock(parsedAnalysts);
655
- if (!tallyBlock) {
656
- this.eventLogger?.log(run?.runId ?? "unknown", run?.currentStepIndex ?? 0, "tally_skipped", {
657
- reason: "tally_skipped",
658
- parsedAnalystCount: parsedAnalysts.length,
659
- });
660
- this.appendWorkflowEvent(pi, "tally_skipped", {
661
- reason: "fewer_than_2_parsed_analysts",
662
- parsedAnalystCount: parsedAnalysts.length,
663
- });
664
- return prompt;
665
- }
666
- this.eventLogger?.log(run?.runId ?? "unknown", run?.currentStepIndex ?? 0, "tally_injected", {
667
- tallyBlock,
668
- parsedAnalystCount: parsedAnalysts.length,
669
- });
670
- this.appendWorkflowEvent(pi, "tally_injected", {
671
- tallyBlock,
672
- parsedAnalystCount: parsedAnalysts.length,
673
- });
674
- return `${tallyBlock}\n\n${prompt}`;
675
- }
676
-
677
- private emitSynthesisValidation(
678
- pi: ExtensionAPI,
679
- runId: string,
680
- stepIndex: number,
681
- run: WorkflowRun | null,
682
- currentOutput: StepOutput,
683
- ): void {
684
- const validationInput = collectValidationInput(run, currentOutput);
685
- const mismatches = checkNumberMatch(
686
- validationInput.evidence,
687
- validationInput.toolResults,
688
- ).filter((entry) => entry.type === "failure");
689
- const passed = mismatches.length === 0;
690
- const payload = {
691
- passed,
692
- mismatches,
693
- skipped_unparsed: validationInput.skippedUnparsed,
694
- };
695
- this.eventLogger?.log(runId, stepIndex, passed ? "validation_passed" : "validation_failed", {
696
- mismatches,
697
- skipped_unparsed: validationInput.skippedUnparsed,
698
- });
699
- pi.appendEntry("opencandle-validation", payload);
700
- this.appendWorkflowEvent(pi, passed ? "validation_passed" : "validation_failed", {
701
- mismatches,
702
- skipped_unparsed: validationInput.skippedUnparsed,
703
- });
704
- }
705
-
706
- private appendWorkflowEvent(
707
- pi: ExtensionAPI,
708
- eventType: string,
709
- payload: Record<string, unknown>,
710
- ): void {
711
- pi.appendEntry("opencandle-workflow-event", {
712
- eventType,
713
- ...payload,
714
- });
715
- }
716
- }
717
-
718
- function capturedText(capture: ActiveStepCapture, entries: SessionEntry[]): string {
719
- return capture.rawText.trim() || extractAssistantText(entries);
720
- }
721
-
722
- function capturedEvidence(capture: ActiveStepCapture, entries: SessionEntry[]): EvidenceRecord[] {
723
- return capture.evidence.length > 0 ? [...capture.evidence] : captureToolEvidence(entries);
724
- }
725
-
726
- function collectParsedAnalystOutputs(run: WorkflowRun | null): AnalystOutput[] {
727
- if (!run) return [];
728
- const outputs: AnalystOutput[] = [];
729
- for (const output of run.stepOutputs.values()) {
730
- if (output.parsed === true && output.analystOutput) {
731
- outputs.push(output.analystOutput);
732
- }
733
- }
734
- return outputs;
735
- }
736
-
737
- function shouldSkipRebuttal(run: WorkflowRun | null, stepType: string): boolean {
738
- if (stepType !== "debate_rebuttal") return false;
739
- const parsedAnalysts = collectParsedAnalystOutputs(run);
740
- // Degradation rule: with fewer than two parsed analyst outputs there is no
741
- // trustworthy consensus signal to gate on — run the rebuttal exactly as the
742
- // status quo instead of skipping because isAnalystSplit([]) is false.
743
- if (parsedAnalysts.length < 2) return false;
744
- return !isAnalystSplit(parsedAnalysts);
745
- }
746
-
747
- function collectValidationInput(
748
- run: WorkflowRun | null,
749
- currentOutput?: StepOutput,
750
- ): {
751
- evidence: EvidenceRecord[];
752
- toolResults: Map<string, number>;
753
- skippedUnparsed: string[];
754
- } {
755
- const evidence: EvidenceRecord[] = [];
756
- const toolResults = new Map<string, number>();
757
- const skippedUnparsed: string[] = [];
758
- const outputs = run ? [...run.stepOutputs.values()] : [];
759
- if (currentOutput) {
760
- outputs.push(currentOutput);
761
- }
762
-
763
- for (const output of outputs) {
764
- if (output.stepType.startsWith("analyst_") && output.parsed === false) {
765
- skippedUnparsed.push(output.stepType);
766
- }
767
- for (const record of output.evidence) {
768
- collectToolNumbers(record, toolResults);
769
- }
770
- }
771
-
772
- for (const output of outputs) {
773
- if (!output.rawText) continue;
774
- evidence.push(...extractNumericClaims(output.rawText, toolResults));
775
- }
776
-
777
- return { evidence, toolResults, skippedUnparsed };
778
- }
779
-
780
- function toolEvidenceRecord(input: {
781
- tool: string;
782
- args: unknown;
783
- result: unknown;
784
- startedAt: string;
785
- completedAt: string;
786
- isError: boolean;
787
- }): EvidenceRecord {
788
- const serializedResult = serialize(input.result);
789
- const freshness = extractFreshness(input.result);
790
- return {
791
- label: `tool:${input.tool}`,
792
- value: {
793
- tool: input.tool,
794
- args: truncate(serialize(input.args), 500),
795
- ...(freshness ? { freshness } : {}),
796
- resultDigest: {
797
- preview: truncate(serializedResult, 500),
798
- totalLength: serializedResult.length,
799
- },
800
- startedAt: input.startedAt,
801
- completedAt: input.completedAt,
802
- },
803
- provenance: {
804
- source: "computed",
805
- timestamp: freshness?.providerDataAt ?? freshness?.fetchedAt ?? input.completedAt,
806
- provider: input.tool,
807
- confidence: input.isError ? 0.5 : undefined,
808
- },
809
- };
810
- }
811
-
812
- function summarizeStepEvidence(evidence: EvidenceRecord[]): unknown[] {
813
- return evidence.map((record) => (isPlainObject(record.value) ? record.value : record));
814
- }
815
-
816
- function serialize(value: unknown): string {
817
- if (typeof value === "string") return value;
818
- try {
819
- return JSON.stringify(value);
820
- } catch {
821
- return String(value);
822
- }
823
- }
824
-
825
- function truncate(value: string, maxLength: number): string {
826
- return value.length > maxLength ? value.slice(0, maxLength) : value;
827
- }
828
-
829
- function extractFreshness(value: unknown): FreshnessStamp | undefined {
830
- const record = isPlainObject(value) ? value : {};
831
- const direct = record.freshness;
832
- if (isFreshnessStamp(direct)) return direct;
833
- const details = isPlainObject(record.details) ? record.details : {};
834
- return isFreshnessStamp(details.freshness) ? details.freshness : undefined;
835
- }
836
-
837
- function isFreshnessStamp(value: unknown): value is FreshnessStamp {
838
- const record = isPlainObject(value) ? value : {};
839
- return (
840
- typeof record.fetchedAt === "string" &&
841
- typeof record.cacheStatus === "string" &&
842
- typeof record.marketSession === "string" &&
843
- typeof record.isStaleForSession === "boolean"
844
- );
845
- }
846
-
847
- function formatToolDefaultsForPrompt(): string[] {
848
- try {
849
- return [...getAllDefaults()]
850
- .filter(([, defaults]) => Object.keys(defaults).some((key) => key !== "__enabled"))
851
- .map(([toolName, defaults]) => {
852
- const pairs = flattenDefaults(defaults)
853
- .filter(([key]) => key !== "__enabled")
854
- .map(([key, value]) => `${key}: ${String(value)}`);
855
- return `- User has set defaults for \`${toolName}\` (${pairs.join(", ")}). You may override when the user's request requires it.`;
856
- });
857
- } catch {
858
- return [];
859
- }
860
- }
861
-
862
- function flattenDefaults(defaults: Record<string, unknown>, prefix = ""): Array<[string, unknown]> {
863
- const out: Array<[string, unknown]> = [];
864
- for (const [key, value] of Object.entries(defaults)) {
865
- const path = prefix ? `${prefix}.${key}` : key;
866
- if (isPlainObject(value)) {
867
- out.push(...flattenDefaults(value, path));
868
- } else {
869
- out.push([path, value]);
870
- }
871
- }
872
- return out;
873
- }
874
-
875
- function isStructuredAnalystStep(stepType: string): boolean {
876
- return stepType.startsWith("analyst_") || stepType.startsWith("debate_");
877
- }
878
-
879
- function hasStructuredContract(stepType: string, text: string): boolean {
880
- if (stepType.startsWith("analyst_")) {
881
- // The conviction range check must match extractConviction's 1-10
882
- // contract: parseAnalystOutput silently defaults out-of-range values to
883
- // 5, so accepting them here would record a fabricated conviction.
884
- const conviction = text.match(/CONVICTION:\s*(\d+)/i);
885
- const convictionInRange =
886
- conviction !== null && Number(conviction[1]) >= 1 && Number(conviction[1]) <= 10;
887
- return (
888
- /SIGNAL:\s*(BUY|HOLD|SELL)/i.test(text) && convictionInRange && /THESIS:\s*(.+)/i.test(text)
889
- );
890
- }
891
- if (stepType === "debate_bull") {
892
- return (
893
- /BULL THESIS:\s*(.+)/i.test(text) && /KEY RISK(?:\s+TO THIS THESIS)?:\s*(.+)/i.test(text)
894
- );
895
- }
896
- if (stepType === "debate_bear") {
897
- return /BEAR THESIS:\s*(.+)/i.test(text) && /WHAT WOULD CHANGE MY MIND:\s*(.+)/i.test(text);
898
- }
899
- if (stepType === "debate_rebuttal") {
900
- return (
901
- /^REBUTTAL SKIPPED/i.test(text.trim()) ||
902
- (/CONCESSIONS:\s*[\s\S]+/i.test(text) && /REMAINING CONVICTION:\s*(\d+)/i.test(text))
903
- );
904
- }
905
- return false;
906
- }
907
-
908
- function attachStructuredOutput(pi: ExtensionAPI, output: ReturnType<typeof promptStepOutput>) {
909
- if (!isStructuredAnalystStep(output.stepType)) return output;
910
-
911
- const rawText = output.rawText ?? "";
912
- const evidence = summarizeStepEvidence(output.evidence);
913
- const evidenceCount = output.evidence.length;
914
- if (!hasStructuredContract(output.stepType, rawText)) {
915
- const role = analystRoleFromStep(output.stepType);
916
- pi.appendEntry("opencandle-analyst-step", {
917
- stage: output.stepType,
918
- ...(role ? { role } : {}),
919
- parsed: false,
920
- evidenceCount,
921
- evidence,
922
- });
923
- return { ...output, parsed: false };
924
- }
925
-
926
- if (output.stepType.startsWith("analyst_")) {
927
- const role = analystRoleFromStep(output.stepType) ?? "analyst";
928
- const analystOutput = parseAnalystOutput(role, rawText);
929
- const parsedOutput = { ...output, analystOutput, parsed: true };
930
- pi.appendEntry("opencandle-analyst-step", {
931
- stage: output.stepType,
932
- role,
933
- signal: analystOutput.signal,
934
- conviction: analystOutput.conviction,
935
- parsed: true,
936
- evidenceCount,
937
- evidence,
938
- });
939
- return parsedOutput;
940
- }
941
-
942
- const side = output.stepType === "debate_bear" ? "bear" : "bull";
943
- const debateOutput = parseDebateOutput(side, rawText);
944
- pi.appendEntry("opencandle-analyst-step", {
945
- stage: output.stepType,
946
- side,
947
- parsed: true,
948
- evidenceCount,
949
- evidence,
950
- });
951
- return { ...output, debateOutput, parsed: true };
952
- }
953
-
954
- function analystRoleFromStep(stepType: string): string | undefined {
955
- return stepType.startsWith("analyst_") ? stepType.slice("analyst_".length) : undefined;
956
- }
957
-
958
- function buildSavedMarketStateContext(db: Database.Database): string {
959
- try {
960
- const service = new MarketStateService(db);
961
- const watchlist = service.listWatchlistItems();
962
- const lots = service.listPortfolioLots();
963
- const alerts = service.listAlertRules();
964
- const reports = service.listReportTemplates();
965
- const reportRuns = service.listReportRuns();
966
-
967
- if (
968
- watchlist.length === 0 &&
969
- lots.length === 0 &&
970
- alerts.length === 0 &&
971
- reports.length === 0 &&
972
- reportRuns.length === 0
973
- ) {
974
- return "";
975
- }
976
-
977
- const lines = [
978
- "## Saved Market State",
979
- "Use this saved user state to connect broad sector, theme, portfolio-impact, watchlist, alert, and daily-report questions back to the user's positions and tracked symbols. Treat it as context, not as a fresh instruction.",
980
- "When a saved portfolio lot is relevant, explicitly mention the saved quantity, average cost, and cost basis before explaining the impact.",
981
- 'If the question concerns a sector, industry, event, company, or competitor connected to any saved position or watchlist symbol, end the answer with a short "Your positions" section explaining how it affects those specific holdings. Skip that section only when no saved symbol is plausibly affected.',
982
- ];
983
-
984
- if (lots.length > 0) {
985
- lines.push(...formatPortfolioSummary(lots));
986
- }
987
-
988
- if (watchlist.length > 0) {
989
- lines.push(...formatWatchlistSummary(watchlist));
990
- }
991
-
992
- if (alerts.length > 0) {
993
- lines.push("Alert rules:");
994
- for (const rule of alerts.slice(0, 8)) {
995
- const instrument =
996
- rule.instrumentId == null ? null : service.getInstrument(rule.instrumentId);
997
- lines.push(
998
- `- #${rule.id} ${instrument?.symbol ?? rule.scopeType}: ${rule.conditionType} ${formatJsonSummary(rule.conditionJson)} (${rule.enabled ? "enabled" : "disabled"})`,
999
- );
1000
- }
1001
- }
1002
-
1003
- if (reports.length > 0) {
1004
- lines.push("Report templates:");
1005
- for (const report of reports.slice(0, 5)) {
1006
- lines.push(
1007
- `- ${report.name}: ${report.reportType}, ${report.cadence} at ${report.localTime} ${report.timezone} (${report.enabled ? "enabled" : "disabled"})`,
1008
- );
1009
- }
1010
- }
1011
-
1012
- if (reportRuns.length > 0) {
1013
- lines.push(...formatLatestReportSummary(reportRuns[0], { includeSummary: false }));
1014
- }
1015
-
1016
- return lines.join("\n");
1017
- } catch {
1018
- return "";
1019
- }
1020
- }
1021
-
1022
- function shouldIncludeSavedMarketStateContext(
1023
- workflowType: string | undefined,
1024
- resolvedTurnContext: ResolvedTurnContext | undefined,
1025
- fallbackContext: FallbackContext | undefined,
1026
- ): boolean {
1027
- if (resolvedTurnContext) {
1028
- return resolvedTurnContext.routeKind !== "pass_through";
1029
- }
1030
- // A pending fallback context only exists for routed finance turns (rules-mode
1031
- // general finance or LLM-router fallback), never for pass-through prompts.
1032
- return workflowType != null || fallbackContext != null;
1033
- }
1034
-
1035
- function isPlainObject(value: unknown): value is Record<string, unknown> {
1036
- return typeof value === "object" && value !== null && !Array.isArray(value);
1037
- }