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.
- package/README.md +20 -24
- package/dist/analysts/contracts.js +0 -1
- package/dist/analysts/orchestrator.js +0 -1
- package/dist/cli-main.js +13 -7
- package/dist/cli-options.d.ts +4 -0
- package/dist/cli-options.js +33 -0
- package/dist/cli.js +8 -3
- package/dist/config.js +0 -1
- package/dist/doctor/cli-command.js +2 -1
- package/dist/doctor/render.js +0 -1
- package/dist/doctor/report.js +40 -11
- package/dist/gui/server/ask-user-bridge.d.ts +19 -0
- package/dist/gui/server/ask-user-bridge.js +55 -0
- package/dist/gui/server/automation-heartbeat.d.ts +25 -0
- package/dist/gui/server/automation-heartbeat.js +61 -0
- package/dist/gui/server/background-quotes.d.ts +39 -0
- package/dist/gui/server/background-quotes.js +71 -0
- package/dist/gui/server/chat-event-adapter.d.ts +16 -0
- package/dist/gui/server/chat-event-adapter.js +263 -0
- package/dist/gui/server/gui-session-manager.d.ts +2 -0
- package/dist/gui/server/gui-session-manager.js +4 -0
- package/dist/gui/server/http-routes.d.ts +69 -0
- package/dist/gui/server/http-routes.js +1008 -0
- package/dist/gui/server/invoke-tool.d.ts +47 -0
- package/dist/gui/server/invoke-tool.js +373 -0
- package/dist/gui/server/live-chat-event-adapter.d.ts +19 -0
- package/dist/gui/server/live-chat-event-adapter.js +206 -0
- package/dist/gui/server/local-session-coordinator.d.ts +26 -0
- package/dist/gui/server/local-session-coordinator.js +53 -0
- package/dist/gui/server/market-state-api.d.ts +138 -0
- package/dist/gui/server/market-state-api.js +355 -0
- package/dist/gui/server/model-setup.d.ts +64 -0
- package/dist/gui/server/model-setup.js +150 -0
- package/dist/gui/server/private-api-access.d.ts +6 -0
- package/dist/gui/server/private-api-access.js +53 -0
- package/dist/gui/server/projector.d.ts +49 -0
- package/dist/gui/server/projector.js +296 -0
- package/dist/gui/server/prompt-observation.d.ts +8 -0
- package/dist/gui/server/prompt-observation.js +43 -0
- package/dist/gui/server/quote-snapshot-store.d.ts +14 -0
- package/dist/gui/server/quote-snapshot-store.js +49 -0
- package/dist/gui/server/server.d.ts +1 -0
- package/dist/gui/server/server.js +259 -0
- package/dist/gui/server/session-actions.d.ts +60 -0
- package/dist/gui/server/session-actions.js +218 -0
- package/dist/gui/server/session-entry-wait.d.ts +27 -0
- package/dist/gui/server/session-entry-wait.js +129 -0
- package/dist/gui/server/session-list.d.ts +2 -0
- package/dist/gui/server/session-list.js +11 -0
- package/dist/gui/server/shutdown.d.ts +10 -0
- package/dist/gui/server/shutdown.js +29 -0
- package/dist/gui/server/tool-invoke-ack.d.ts +17 -0
- package/dist/gui/server/tool-invoke-ack.js +26 -0
- package/dist/gui/server/tool-metadata.d.ts +93 -0
- package/dist/gui/server/tool-metadata.js +148 -0
- package/dist/gui/server/websocket.d.ts +9 -0
- package/dist/gui/server/websocket.js +124 -0
- package/dist/gui/server/writer-lock.d.ts +1 -0
- package/dist/gui/server/writer-lock.js +1 -0
- package/dist/gui/server/ws-hub.d.ts +50 -0
- package/dist/gui/server/ws-hub.js +284 -0
- package/dist/gui/shared/chat-events.d.ts +174 -0
- package/dist/gui/shared/chat-events.js +13 -0
- package/dist/gui/shared/event-reducer.d.ts +3 -0
- package/dist/gui/shared/event-reducer.js +187 -0
- package/dist/index.js +0 -1
- package/dist/infra/cache.js +0 -1
- package/dist/infra/freshness.js +0 -1
- package/dist/infra/http-client.js +1 -2
- package/dist/infra/index.js +0 -1
- package/dist/infra/market-calendar.js +0 -1
- package/dist/infra/native-dependencies.js +0 -1
- package/dist/infra/node-version.js +0 -1
- package/dist/infra/open-url.js +0 -1
- package/dist/infra/opencandle-paths.js +0 -1
- package/dist/infra/rate-limiter.js +0 -1
- package/dist/market-state/alert-conditions.js +0 -1
- package/dist/market-state/alert-runner.d.ts +1 -0
- package/dist/market-state/alert-runner.js +5 -4
- package/dist/market-state/daily-report.js +0 -1
- package/dist/market-state/local-automation-service.js +0 -1
- package/dist/market-state/notification-delivery.js +0 -1
- package/dist/market-state/resolve-for-mutation.js +0 -1
- package/dist/market-state/resolve.js +0 -1
- package/dist/market-state/service.d.ts +26 -21
- package/dist/market-state/service.js +175 -36
- package/dist/market-state/summaries.js +1 -13
- package/dist/memory/index.js +0 -1
- package/dist/memory/manager.js +0 -1
- package/dist/memory/preference-extractor.js +0 -1
- package/dist/memory/retrieval.js +0 -1
- package/dist/memory/sqlite.js +60 -11
- package/dist/memory/storage.js +0 -1
- package/dist/memory/tool-defaults.js +0 -1
- package/dist/memory/types.js +0 -1
- package/dist/monitor.js +0 -1
- package/dist/onboarding/connect.js +0 -1
- package/dist/onboarding/credential-interceptor.js +0 -1
- package/dist/onboarding/degradation-accumulator.js +0 -1
- package/dist/onboarding/prompt-user.d.ts +1 -1
- package/dist/onboarding/prompt-user.js +0 -1
- package/dist/onboarding/provider-status.js +0 -1
- package/dist/onboarding/providers.js +0 -1
- package/dist/onboarding/state.js +0 -1
- package/dist/onboarding/tool-helpers.js +0 -1
- package/dist/onboarding/tool-tags.js +0 -1
- package/dist/onboarding/validate-model-key.d.ts +17 -0
- package/dist/onboarding/validate-model-key.js +54 -0
- package/dist/onboarding/validation.js +0 -1
- package/dist/pi/opencandle-extension.js +2 -2
- package/dist/pi/session-action-dedupe.js +0 -1
- package/dist/pi/session-storage.js +0 -1
- package/dist/pi/session-writer-lock.js +0 -1
- package/dist/pi/session.js +0 -1
- package/dist/pi/setup.d.ts +2 -0
- package/dist/pi/setup.js +10 -3
- package/dist/pi/tool-adapter.js +0 -1
- package/dist/pi/tui-session-coordinator.js +0 -1
- package/dist/prompts/context-builder.js +1 -2
- package/dist/prompts/disclaimer.js +0 -1
- package/dist/prompts/policy-cards.js +0 -1
- package/dist/prompts/sections.js +0 -1
- package/dist/prompts/symbol-preflight.js +0 -1
- package/dist/prompts/workflow-prompts.js +0 -1
- package/dist/providers/alpha-vantage.js +2 -3
- package/dist/providers/coingecko.js +0 -1
- package/dist/providers/errors.js +0 -1
- package/dist/providers/exa-search.js +11 -10
- package/dist/providers/external-tool-command.js +0 -1
- package/dist/providers/external-tool-error.js +0 -1
- package/dist/providers/fear-greed.js +0 -1
- package/dist/providers/finnhub.js +0 -1
- package/dist/providers/fred.js +0 -1
- package/dist/providers/index.js +0 -1
- package/dist/providers/polymarket.js +0 -1
- package/dist/providers/provider-credential-error.js +0 -1
- package/dist/providers/reddit-cli.js +0 -1
- package/dist/providers/reddit.js +0 -1
- package/dist/providers/sec-edgar.js +0 -1
- package/dist/providers/tradingview.js +1 -2
- package/dist/providers/twitter-cli.js +0 -1
- package/dist/providers/twitter.js +0 -1
- package/dist/providers/web-search.js +15 -12
- package/dist/providers/with-fallback.js +0 -1
- package/dist/providers/wrap-provider.js +0 -1
- package/dist/providers/yahoo-finance.js +67 -4
- package/dist/routing/classify-intent.js +0 -1
- package/dist/routing/defaults.js +0 -1
- package/dist/routing/entity-extractor.js +2 -3
- package/dist/routing/fund-symbols.js +0 -1
- package/dist/routing/horizon.js +0 -1
- package/dist/routing/index.js +0 -1
- package/dist/routing/legacy-rule-router.js +0 -1
- package/dist/routing/planning.js +0 -1
- package/dist/routing/route-manifest.js +0 -1
- package/dist/routing/router-llm-client.d.ts +2 -2
- package/dist/routing/router-llm-client.js +0 -1
- package/dist/routing/router-prompt.js +0 -1
- package/dist/routing/router-types.js +0 -1
- package/dist/routing/router.js +1 -2
- package/dist/routing/slot-resolver.js +0 -1
- package/dist/routing/symbol-disambiguator.js +0 -1
- package/dist/routing/turn-context.js +0 -1
- package/dist/routing/types.js +0 -1
- package/dist/runtime/answer-contracts.js +0 -1
- package/dist/runtime/artifact-contracts.js +0 -1
- package/dist/runtime/evidence.js +0 -1
- package/dist/runtime/numeric-claims.js +0 -1
- package/dist/runtime/planning-evidence.js +0 -1
- package/dist/runtime/prompt-step.js +0 -1
- package/dist/runtime/provider-tracker.js +0 -1
- package/dist/runtime/run-context.js +0 -1
- package/dist/runtime/session-coordinator.js +0 -1
- package/dist/runtime/session-title.js +0 -1
- package/dist/runtime/tool-defaults-wrapper.js +0 -1
- package/dist/runtime/validation.js +0 -1
- package/dist/runtime/workflow-events.js +0 -1
- package/dist/runtime/workflow-runner.d.ts +1 -0
- package/dist/runtime/workflow-runner.js +8 -3
- package/dist/runtime/workflow-types.js +0 -1
- package/dist/sentiment/adapters/finnhub.js +0 -1
- package/dist/sentiment/adapters/reddit.js +0 -1
- package/dist/sentiment/adapters/twitter.js +0 -1
- package/dist/sentiment/adapters/web.js +0 -1
- package/dist/sentiment/index.js +4 -2
- package/dist/sentiment/insights.js +0 -1
- package/dist/sentiment/keywords.js +0 -1
- package/dist/sentiment/pipeline.js +0 -1
- package/dist/sentiment/scorer.js +0 -1
- package/dist/sentiment/store.js +0 -1
- package/dist/sentiment/trends.js +0 -1
- package/dist/sentiment/types.js +0 -1
- package/dist/system-prompt.js +0 -1
- package/dist/tool-kit.js +0 -1
- package/dist/tools/fundamentals/company-overview.d.ts +1 -1
- package/dist/tools/fundamentals/company-overview.js +2 -1
- package/dist/tools/fundamentals/comps.js +6 -4
- package/dist/tools/fundamentals/dcf.js +0 -1
- package/dist/tools/fundamentals/earnings.d.ts +1 -1
- package/dist/tools/fundamentals/earnings.js +2 -1
- package/dist/tools/fundamentals/financials.js +2 -1
- package/dist/tools/fundamentals/sec-filings.js +0 -1
- package/dist/tools/index.d.ts +116 -2
- package/dist/tools/index.js +0 -1
- package/dist/tools/interaction/ask-user.js +11 -1
- package/dist/tools/macro/event-probabilities.js +0 -1
- package/dist/tools/macro/fear-greed.d.ts +1 -1
- package/dist/tools/macro/fear-greed.js +0 -1
- package/dist/tools/macro/fred-data.d.ts +1 -1
- package/dist/tools/macro/fred-data.js +2 -1
- package/dist/tools/market/crypto-history.js +0 -1
- package/dist/tools/market/crypto-price.d.ts +2 -2
- package/dist/tools/market/crypto-price.js +0 -1
- package/dist/tools/market/screen-stocks.js +0 -1
- package/dist/tools/market/search-ticker.js +1 -2
- package/dist/tools/market/stock-history.js +0 -1
- package/dist/tools/market/stock-quote.d.ts +2 -2
- package/dist/tools/market/stock-quote.js +0 -1
- package/dist/tools/options/greeks.js +0 -1
- package/dist/tools/options/option-chain.d.ts +2 -2
- package/dist/tools/options/option-chain.js +0 -1
- package/dist/tools/portfolio/alerts.d.ts +2 -1
- package/dist/tools/portfolio/alerts.js +228 -2
- package/dist/tools/portfolio/correlation.js +23 -5
- package/dist/tools/portfolio/daily-report.js +0 -1
- package/dist/tools/portfolio/holdings-overlap.js +0 -1
- package/dist/tools/portfolio/notifications.js +0 -1
- package/dist/tools/portfolio/risk-analysis.d.ts +1 -1
- package/dist/tools/portfolio/risk-analysis.js +0 -1
- package/dist/tools/portfolio/tracker.d.ts +3 -1
- package/dist/tools/portfolio/tracker.js +57 -10
- package/dist/tools/portfolio/watchlist.d.ts +3 -6
- package/dist/tools/portfolio/watchlist.js +101 -110
- package/dist/tools/sentiment/insight-format.js +0 -1
- package/dist/tools/sentiment/query-match.js +0 -1
- package/dist/tools/sentiment/reddit-sentiment.js +0 -1
- package/dist/tools/sentiment/sentiment-summary.js +8 -4
- package/dist/tools/sentiment/sentiment-trend.d.ts +5 -1
- package/dist/tools/sentiment/sentiment-trend.js +6 -2
- package/dist/tools/sentiment/twitter-sentiment.js +0 -1
- package/dist/tools/sentiment/untrusted-text.js +0 -1
- package/dist/tools/sentiment/web-search.d.ts +1 -1
- package/dist/tools/sentiment/web-search.js +0 -1
- package/dist/tools/sentiment/web-sentiment.js +0 -1
- package/dist/tools/technical/backtest.js +0 -1
- package/dist/tools/technical/indicators.js +0 -1
- package/dist/types/fundamentals.js +0 -1
- package/dist/types/index.js +0 -1
- package/dist/types/macro.js +0 -1
- package/dist/types/market.d.ts +6 -0
- package/dist/types/market.js +0 -1
- package/dist/types/options.js +0 -1
- package/dist/types/portfolio.js +0 -1
- package/dist/types/prediction-markets.js +0 -1
- package/dist/types/sentiment.js +0 -1
- package/dist/workflows/compare-assets.js +0 -1
- package/dist/workflows/index.js +0 -1
- package/dist/workflows/options-screener.js +0 -1
- package/dist/workflows/portfolio-builder.js +0 -1
- package/gui/web/dist/assets/CatalogOverlay-CAc7e3Pf.js +1 -0
- package/gui/web/dist/assets/index-BOEKd9wT.css +2 -0
- package/gui/web/dist/assets/index-C-H05cQ2.js +65 -0
- package/gui/web/dist/index.html +2 -2
- package/package.json +11 -12
- package/dist/analysts/contracts.js.map +0 -1
- package/dist/analysts/orchestrator.js.map +0 -1
- package/dist/cli-main.js.map +0 -1
- package/dist/cli.js.map +0 -1
- package/dist/config.js.map +0 -1
- package/dist/doctor/cli-command.js.map +0 -1
- package/dist/doctor/render.js.map +0 -1
- package/dist/doctor/report.js.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/infra/cache.js.map +0 -1
- package/dist/infra/freshness.js.map +0 -1
- package/dist/infra/http-client.js.map +0 -1
- package/dist/infra/index.js.map +0 -1
- package/dist/infra/market-calendar.js.map +0 -1
- package/dist/infra/native-dependencies.js.map +0 -1
- package/dist/infra/node-version.js.map +0 -1
- package/dist/infra/open-url.js.map +0 -1
- package/dist/infra/opencandle-paths.js.map +0 -1
- package/dist/infra/rate-limiter.js.map +0 -1
- package/dist/market-state/alert-conditions.js.map +0 -1
- package/dist/market-state/alert-runner.js.map +0 -1
- package/dist/market-state/daily-report.js.map +0 -1
- package/dist/market-state/local-automation-service.js.map +0 -1
- package/dist/market-state/notification-delivery.js.map +0 -1
- package/dist/market-state/resolve-for-mutation.js.map +0 -1
- package/dist/market-state/resolve.js.map +0 -1
- package/dist/market-state/service.js.map +0 -1
- package/dist/market-state/summaries.js.map +0 -1
- package/dist/memory/index.js.map +0 -1
- package/dist/memory/manager.js.map +0 -1
- package/dist/memory/preference-extractor.js.map +0 -1
- package/dist/memory/retrieval.js.map +0 -1
- package/dist/memory/sqlite.js.map +0 -1
- package/dist/memory/storage.js.map +0 -1
- package/dist/memory/tool-defaults.js.map +0 -1
- package/dist/memory/types.js.map +0 -1
- package/dist/monitor.js.map +0 -1
- package/dist/onboarding/connect.js.map +0 -1
- package/dist/onboarding/credential-interceptor.js.map +0 -1
- package/dist/onboarding/degradation-accumulator.js.map +0 -1
- package/dist/onboarding/prompt-user.js.map +0 -1
- package/dist/onboarding/provider-status.js.map +0 -1
- package/dist/onboarding/providers.js.map +0 -1
- package/dist/onboarding/state.js.map +0 -1
- package/dist/onboarding/tool-helpers.js.map +0 -1
- package/dist/onboarding/tool-tags.js.map +0 -1
- package/dist/onboarding/validation.js.map +0 -1
- package/dist/pi/opencandle-extension.js.map +0 -1
- package/dist/pi/session-action-dedupe.js.map +0 -1
- package/dist/pi/session-storage.js.map +0 -1
- package/dist/pi/session-writer-lock.js.map +0 -1
- package/dist/pi/session.js.map +0 -1
- package/dist/pi/setup.js.map +0 -1
- package/dist/pi/tool-adapter.js.map +0 -1
- package/dist/pi/tui-session-coordinator.js.map +0 -1
- package/dist/prompts/context-builder.js.map +0 -1
- package/dist/prompts/disclaimer.js.map +0 -1
- package/dist/prompts/policy-cards.js.map +0 -1
- package/dist/prompts/sections.js.map +0 -1
- package/dist/prompts/symbol-preflight.js.map +0 -1
- package/dist/prompts/workflow-prompts.js.map +0 -1
- package/dist/providers/alpha-vantage.js.map +0 -1
- package/dist/providers/coingecko.js.map +0 -1
- package/dist/providers/errors.js.map +0 -1
- package/dist/providers/exa-search.js.map +0 -1
- package/dist/providers/external-tool-command.js.map +0 -1
- package/dist/providers/external-tool-error.js.map +0 -1
- package/dist/providers/fear-greed.js.map +0 -1
- package/dist/providers/finnhub.js.map +0 -1
- package/dist/providers/fred.js.map +0 -1
- package/dist/providers/index.js.map +0 -1
- package/dist/providers/polymarket.js.map +0 -1
- package/dist/providers/provider-credential-error.js.map +0 -1
- package/dist/providers/reddit-cli.js.map +0 -1
- package/dist/providers/reddit.js.map +0 -1
- package/dist/providers/sec-edgar.js.map +0 -1
- package/dist/providers/tradingview.js.map +0 -1
- package/dist/providers/twitter-cli.js.map +0 -1
- package/dist/providers/twitter.js.map +0 -1
- package/dist/providers/web-search.js.map +0 -1
- package/dist/providers/with-fallback.js.map +0 -1
- package/dist/providers/wrap-provider.js.map +0 -1
- package/dist/providers/yahoo-finance.js.map +0 -1
- package/dist/routing/classify-intent.js.map +0 -1
- package/dist/routing/defaults.js.map +0 -1
- package/dist/routing/entity-extractor.js.map +0 -1
- package/dist/routing/fund-symbols.js.map +0 -1
- package/dist/routing/horizon.js.map +0 -1
- package/dist/routing/index.js.map +0 -1
- package/dist/routing/legacy-rule-router.js.map +0 -1
- package/dist/routing/planning.js.map +0 -1
- package/dist/routing/route-manifest.js.map +0 -1
- package/dist/routing/router-llm-client.js.map +0 -1
- package/dist/routing/router-prompt.js.map +0 -1
- package/dist/routing/router-types.js.map +0 -1
- package/dist/routing/router.js.map +0 -1
- package/dist/routing/slot-resolver.js.map +0 -1
- package/dist/routing/symbol-disambiguator.js.map +0 -1
- package/dist/routing/turn-context.js.map +0 -1
- package/dist/routing/types.js.map +0 -1
- package/dist/runtime/answer-contracts.js.map +0 -1
- package/dist/runtime/artifact-contracts.js.map +0 -1
- package/dist/runtime/evidence.js.map +0 -1
- package/dist/runtime/numeric-claims.js.map +0 -1
- package/dist/runtime/planning-evidence.js.map +0 -1
- package/dist/runtime/prompt-step.js.map +0 -1
- package/dist/runtime/provider-tracker.js.map +0 -1
- package/dist/runtime/run-context.js.map +0 -1
- package/dist/runtime/session-coordinator.js.map +0 -1
- package/dist/runtime/session-title.js.map +0 -1
- package/dist/runtime/tool-defaults-wrapper.js.map +0 -1
- package/dist/runtime/validation.js.map +0 -1
- package/dist/runtime/workflow-events.js.map +0 -1
- package/dist/runtime/workflow-runner.js.map +0 -1
- package/dist/runtime/workflow-types.js.map +0 -1
- package/dist/sentiment/adapters/finnhub.js.map +0 -1
- package/dist/sentiment/adapters/reddit.js.map +0 -1
- package/dist/sentiment/adapters/twitter.js.map +0 -1
- package/dist/sentiment/adapters/web.js.map +0 -1
- package/dist/sentiment/index.js.map +0 -1
- package/dist/sentiment/insights.js.map +0 -1
- package/dist/sentiment/keywords.js.map +0 -1
- package/dist/sentiment/pipeline.js.map +0 -1
- package/dist/sentiment/scorer.js.map +0 -1
- package/dist/sentiment/store.js.map +0 -1
- package/dist/sentiment/trends.js.map +0 -1
- package/dist/sentiment/types.js.map +0 -1
- package/dist/system-prompt.js.map +0 -1
- package/dist/tool-kit.js.map +0 -1
- package/dist/tools/fundamentals/company-overview.js.map +0 -1
- package/dist/tools/fundamentals/comps.js.map +0 -1
- package/dist/tools/fundamentals/dcf.js.map +0 -1
- package/dist/tools/fundamentals/earnings.js.map +0 -1
- package/dist/tools/fundamentals/financials.js.map +0 -1
- package/dist/tools/fundamentals/sec-filings.js.map +0 -1
- package/dist/tools/index.js.map +0 -1
- package/dist/tools/interaction/ask-user.js.map +0 -1
- package/dist/tools/macro/event-probabilities.js.map +0 -1
- package/dist/tools/macro/fear-greed.js.map +0 -1
- package/dist/tools/macro/fred-data.js.map +0 -1
- package/dist/tools/market/crypto-history.js.map +0 -1
- package/dist/tools/market/crypto-price.js.map +0 -1
- package/dist/tools/market/screen-stocks.js.map +0 -1
- package/dist/tools/market/search-ticker.js.map +0 -1
- package/dist/tools/market/stock-history.js.map +0 -1
- package/dist/tools/market/stock-quote.js.map +0 -1
- package/dist/tools/options/greeks.js.map +0 -1
- package/dist/tools/options/option-chain.js.map +0 -1
- package/dist/tools/portfolio/alerts.js.map +0 -1
- package/dist/tools/portfolio/correlation.js.map +0 -1
- package/dist/tools/portfolio/daily-report.js.map +0 -1
- package/dist/tools/portfolio/holdings-overlap.js.map +0 -1
- package/dist/tools/portfolio/notifications.js.map +0 -1
- package/dist/tools/portfolio/risk-analysis.js.map +0 -1
- package/dist/tools/portfolio/tracker.js.map +0 -1
- package/dist/tools/portfolio/watchlist.js.map +0 -1
- package/dist/tools/sentiment/insight-format.js.map +0 -1
- package/dist/tools/sentiment/query-match.js.map +0 -1
- package/dist/tools/sentiment/reddit-sentiment.js.map +0 -1
- package/dist/tools/sentiment/sentiment-summary.js.map +0 -1
- package/dist/tools/sentiment/sentiment-trend.js.map +0 -1
- package/dist/tools/sentiment/twitter-sentiment.js.map +0 -1
- package/dist/tools/sentiment/untrusted-text.js.map +0 -1
- package/dist/tools/sentiment/web-search.js.map +0 -1
- package/dist/tools/sentiment/web-sentiment.js.map +0 -1
- package/dist/tools/technical/backtest.js.map +0 -1
- package/dist/tools/technical/indicators.js.map +0 -1
- package/dist/types/fundamentals.js.map +0 -1
- package/dist/types/index.js.map +0 -1
- package/dist/types/macro.js.map +0 -1
- package/dist/types/market.js.map +0 -1
- package/dist/types/options.js.map +0 -1
- package/dist/types/portfolio.js.map +0 -1
- package/dist/types/prediction-markets.js.map +0 -1
- package/dist/types/sentiment.js.map +0 -1
- package/dist/workflows/compare-assets.js.map +0 -1
- package/dist/workflows/index.js.map +0 -1
- package/dist/workflows/options-screener.js.map +0 -1
- package/dist/workflows/portfolio-builder.js.map +0 -1
- package/gui/server/ask-user-bridge.ts +0 -89
- package/gui/server/automation-heartbeat.ts +0 -97
- package/gui/server/background-quotes.ts +0 -127
- package/gui/server/chat-event-adapter.ts +0 -294
- package/gui/server/gui-session-manager.ts +0 -5
- package/gui/server/http-routes.ts +0 -1201
- package/gui/server/invoke-tool.ts +0 -490
- package/gui/server/live-chat-event-adapter.ts +0 -243
- package/gui/server/local-session-coordinator.ts +0 -97
- package/gui/server/market-state-api.ts +0 -331
- package/gui/server/model-setup.ts +0 -254
- package/gui/server/package.json +0 -5
- package/gui/server/private-api-access.ts +0 -62
- package/gui/server/projector.ts +0 -392
- package/gui/server/prompt-observation.ts +0 -58
- package/gui/server/quote-snapshot-store.ts +0 -50
- package/gui/server/server.ts +0 -289
- package/gui/server/session-actions.ts +0 -323
- package/gui/server/session-entry-wait.ts +0 -179
- package/gui/server/shutdown.ts +0 -47
- package/gui/server/tool-invoke-ack.ts +0 -49
- package/gui/server/tool-metadata.ts +0 -167
- package/gui/server/websocket.ts +0 -138
- package/gui/server/writer-lock.ts +0 -1
- package/gui/server/ws-hub.ts +0 -403
- package/gui/shared/chat-events.ts +0 -165
- package/gui/shared/event-reducer.ts +0 -220
- package/gui/web/dist/assets/CatalogOverlay-DZ1niyQm.js +0 -1
- package/gui/web/dist/assets/index-D4F9AJnn.css +0 -2
- package/gui/web/dist/assets/index-DtqMMBTr.js +0 -65
- package/src/analysts/contracts.ts +0 -176
- package/src/analysts/orchestrator.ts +0 -244
- package/src/cli-main.ts +0 -510
- package/src/cli.ts +0 -17
- package/src/config.ts +0 -272
- package/src/doctor/cli-command.ts +0 -83
- package/src/doctor/render.ts +0 -37
- package/src/doctor/report.ts +0 -638
- package/src/index.ts +0 -5
- package/src/infra/cache.ts +0 -127
- package/src/infra/freshness.ts +0 -165
- package/src/infra/http-client.ts +0 -134
- package/src/infra/index.ts +0 -14
- package/src/infra/market-calendar.ts +0 -193
- package/src/infra/native-dependencies.ts +0 -84
- package/src/infra/node-version.ts +0 -23
- package/src/infra/open-url.ts +0 -28
- package/src/infra/opencandle-paths.ts +0 -53
- package/src/infra/rate-limiter.ts +0 -77
- package/src/market-state/alert-conditions.ts +0 -82
- package/src/market-state/alert-runner.ts +0 -863
- package/src/market-state/daily-report.ts +0 -237
- package/src/market-state/local-automation-service.ts +0 -162
- package/src/market-state/notification-delivery.ts +0 -158
- package/src/market-state/resolve-for-mutation.ts +0 -24
- package/src/market-state/resolve.ts +0 -112
- package/src/market-state/service.ts +0 -2208
- package/src/market-state/summaries.ts +0 -75
- package/src/memory/index.ts +0 -10
- package/src/memory/manager.ts +0 -190
- package/src/memory/preference-extractor.ts +0 -106
- package/src/memory/retrieval.ts +0 -71
- package/src/memory/sqlite.ts +0 -577
- package/src/memory/storage.ts +0 -195
- package/src/memory/tool-defaults.ts +0 -108
- package/src/memory/types.ts +0 -71
- package/src/monitor.ts +0 -123
- package/src/onboarding/connect.ts +0 -177
- package/src/onboarding/credential-interceptor.ts +0 -122
- package/src/onboarding/degradation-accumulator.ts +0 -77
- package/src/onboarding/prompt-user.ts +0 -85
- package/src/onboarding/provider-status.ts +0 -382
- package/src/onboarding/providers.ts +0 -442
- package/src/onboarding/state.ts +0 -216
- package/src/onboarding/tool-helpers.ts +0 -104
- package/src/onboarding/tool-tags.ts +0 -244
- package/src/onboarding/validation.ts +0 -152
- package/src/pi/opencandle-extension.ts +0 -1294
- package/src/pi/session-action-dedupe.ts +0 -155
- package/src/pi/session-storage.ts +0 -5
- package/src/pi/session-writer-lock.ts +0 -426
- package/src/pi/session.ts +0 -84
- package/src/pi/setup.ts +0 -399
- package/src/pi/tool-adapter.ts +0 -49
- package/src/pi/tui-session-coordinator.ts +0 -351
- package/src/prompts/context-builder.ts +0 -326
- package/src/prompts/disclaimer.ts +0 -9
- package/src/prompts/policy-cards.ts +0 -228
- package/src/prompts/sections.ts +0 -46
- package/src/prompts/symbol-preflight.ts +0 -80
- package/src/prompts/workflow-prompts.ts +0 -504
- package/src/providers/alpha-vantage.ts +0 -340
- package/src/providers/coingecko.ts +0 -95
- package/src/providers/errors.ts +0 -9
- package/src/providers/exa-search.ts +0 -375
- package/src/providers/external-tool-command.ts +0 -164
- package/src/providers/external-tool-error.ts +0 -20
- package/src/providers/fear-greed.ts +0 -45
- package/src/providers/finnhub.ts +0 -125
- package/src/providers/fred.ts +0 -83
- package/src/providers/index.ts +0 -17
- package/src/providers/polymarket.ts +0 -214
- package/src/providers/provider-credential-error.ts +0 -23
- package/src/providers/reddit-cli.ts +0 -286
- package/src/providers/reddit.ts +0 -106
- package/src/providers/sec-edgar.ts +0 -326
- package/src/providers/tradingview.ts +0 -399
- package/src/providers/twitter-cli.ts +0 -202
- package/src/providers/twitter.ts +0 -102
- package/src/providers/web-search.ts +0 -303
- package/src/providers/with-fallback.ts +0 -42
- package/src/providers/wrap-provider.ts +0 -105
- package/src/providers/yahoo-finance.ts +0 -984
- package/src/routing/classify-intent.ts +0 -380
- package/src/routing/defaults.ts +0 -29
- package/src/routing/entity-extractor.ts +0 -557
- package/src/routing/fund-symbols.ts +0 -58
- package/src/routing/horizon.ts +0 -7
- package/src/routing/index.ts +0 -70
- package/src/routing/legacy-rule-router.ts +0 -13
- package/src/routing/planning.ts +0 -829
- package/src/routing/route-manifest.ts +0 -308
- package/src/routing/router-llm-client.ts +0 -64
- package/src/routing/router-prompt.ts +0 -159
- package/src/routing/router-types.ts +0 -84
- package/src/routing/router.ts +0 -1332
- package/src/routing/slot-resolver.ts +0 -213
- package/src/routing/symbol-disambiguator.ts +0 -72
- package/src/routing/turn-context.ts +0 -108
- package/src/routing/types.ts +0 -77
- package/src/runtime/answer-contracts.ts +0 -693
- package/src/runtime/artifact-contracts.ts +0 -77
- package/src/runtime/evidence.ts +0 -78
- package/src/runtime/numeric-claims.ts +0 -108
- package/src/runtime/planning-evidence.ts +0 -597
- package/src/runtime/prompt-step.ts +0 -185
- package/src/runtime/provider-tracker.ts +0 -40
- package/src/runtime/run-context.ts +0 -32
- package/src/runtime/session-coordinator.ts +0 -1037
- package/src/runtime/session-title.ts +0 -60
- package/src/runtime/tool-defaults-wrapper.ts +0 -43
- package/src/runtime/validation.ts +0 -211
- package/src/runtime/workflow-events.ts +0 -77
- package/src/runtime/workflow-runner.ts +0 -182
- package/src/runtime/workflow-types.ts +0 -105
- package/src/sentiment/adapters/finnhub.ts +0 -49
- package/src/sentiment/adapters/reddit.ts +0 -65
- package/src/sentiment/adapters/twitter.ts +0 -36
- package/src/sentiment/adapters/web.ts +0 -44
- package/src/sentiment/index.ts +0 -49
- package/src/sentiment/insights.ts +0 -269
- package/src/sentiment/keywords.ts +0 -31
- package/src/sentiment/pipeline.ts +0 -91
- package/src/sentiment/scorer.ts +0 -89
- package/src/sentiment/store.ts +0 -260
- package/src/sentiment/trends.ts +0 -96
- package/src/sentiment/types.ts +0 -112
- package/src/system-prompt.ts +0 -115
- package/src/tool-kit.ts +0 -69
- package/src/tools/AGENTS.md +0 -36
- package/src/tools/fundamentals/company-overview.ts +0 -64
- package/src/tools/fundamentals/comps.ts +0 -180
- package/src/tools/fundamentals/dcf.ts +0 -447
- package/src/tools/fundamentals/earnings.ts +0 -57
- package/src/tools/fundamentals/financials.ts +0 -63
- package/src/tools/fundamentals/sec-filings.ts +0 -105
- package/src/tools/index.ts +0 -104
- package/src/tools/interaction/ask-user.ts +0 -93
- package/src/tools/macro/event-probabilities.ts +0 -141
- package/src/tools/macro/fear-greed.ts +0 -41
- package/src/tools/macro/fred-data.ts +0 -92
- package/src/tools/market/crypto-history.ts +0 -72
- package/src/tools/market/crypto-price.ts +0 -65
- package/src/tools/market/screen-stocks.ts +0 -290
- package/src/tools/market/search-ticker.ts +0 -254
- package/src/tools/market/stock-history.ts +0 -104
- package/src/tools/market/stock-quote.ts +0 -73
- package/src/tools/options/greeks.ts +0 -81
- package/src/tools/options/option-chain.ts +0 -134
- package/src/tools/portfolio/alerts.ts +0 -457
- package/src/tools/portfolio/correlation.ts +0 -189
- package/src/tools/portfolio/daily-report.ts +0 -107
- package/src/tools/portfolio/holdings-overlap.ts +0 -139
- package/src/tools/portfolio/notifications.ts +0 -45
- package/src/tools/portfolio/risk-analysis.ts +0 -173
- package/src/tools/portfolio/tracker.ts +0 -308
- package/src/tools/portfolio/watchlist.ts +0 -288
- package/src/tools/sentiment/insight-format.ts +0 -50
- package/src/tools/sentiment/query-match.ts +0 -117
- package/src/tools/sentiment/reddit-sentiment.ts +0 -403
- package/src/tools/sentiment/sentiment-summary.ts +0 -383
- package/src/tools/sentiment/sentiment-trend.ts +0 -75
- package/src/tools/sentiment/twitter-sentiment.ts +0 -287
- package/src/tools/sentiment/untrusted-text.ts +0 -21
- package/src/tools/sentiment/web-search.ts +0 -186
- package/src/tools/sentiment/web-sentiment.ts +0 -96
- package/src/tools/technical/backtest.ts +0 -336
- package/src/tools/technical/indicators.ts +0 -281
- package/src/types/fundamentals.ts +0 -47
- package/src/types/index.ts +0 -26
- package/src/types/macro.ts +0 -27
- package/src/types/market.ts +0 -46
- package/src/types/options.ts +0 -53
- package/src/types/portfolio.ts +0 -83
- package/src/types/prediction-markets.ts +0 -13
- package/src/types/sentiment.ts +0 -129
- package/src/workflows/compare-assets.ts +0 -89
- package/src/workflows/index.ts +0 -3
- package/src/workflows/options-screener.ts +0 -125
- 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
|
-
}
|