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,1201 +0,0 @@
|
|
|
1
|
-
import { createReadStream, existsSync } from "node:fs";
|
|
2
|
-
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
3
|
-
import { extname, join, resolve } from "node:path";
|
|
4
|
-
import { type AgentSession, SessionManager } from "@earendil-works/pi-coding-agent";
|
|
5
|
-
import { buildDoctorReport } from "../../src/doctor/report.js";
|
|
6
|
-
import { MarketStateService } from "../../src/market-state/service.js";
|
|
7
|
-
import {
|
|
8
|
-
formatLatestReportSummary,
|
|
9
|
-
formatPortfolioSummary,
|
|
10
|
-
formatWatchlistSummary,
|
|
11
|
-
} from "../../src/market-state/summaries.js";
|
|
12
|
-
import { initDefaultDatabase } from "../../src/memory/sqlite.js";
|
|
13
|
-
import { probeProviderStatus } from "../../src/onboarding/provider-status.js";
|
|
14
|
-
import {
|
|
15
|
-
clearPendingSessionAction,
|
|
16
|
-
hasAcceptedSessionAction,
|
|
17
|
-
hasPendingSessionAction,
|
|
18
|
-
recordAcceptedSessionAction,
|
|
19
|
-
recordPendingSessionAction,
|
|
20
|
-
} from "../../src/pi/session-action-dedupe.js";
|
|
21
|
-
import type { ChatEvent } from "../shared/chat-events.js";
|
|
22
|
-
import { sessionEntriesToChatEvents } from "./chat-event-adapter.js";
|
|
23
|
-
import type { ToolInvokeController } from "./invoke-tool.js";
|
|
24
|
-
import { createLiveChatEventAdapter } from "./live-chat-event-adapter.js";
|
|
25
|
-
import type {
|
|
26
|
-
LocalSessionCoordinator,
|
|
27
|
-
SessionActionEnvelope,
|
|
28
|
-
SessionActionResult,
|
|
29
|
-
} from "./local-session-coordinator.js";
|
|
30
|
-
import {
|
|
31
|
-
buildMarketStateSnapshot,
|
|
32
|
-
getSavedMarketStateSymbols,
|
|
33
|
-
searchInstrumentCandidates,
|
|
34
|
-
} from "./market-state-api.js";
|
|
35
|
-
import { buildModelSetupState, type ModelSetupController } from "./model-setup.js";
|
|
36
|
-
import { isTrustedPrivateApiRequest, privateApiCookieHeader } from "./private-api-access.js";
|
|
37
|
-
import { projectDashboard } from "./projector.js";
|
|
38
|
-
import { createPromptObservation, observePromptEvent } from "./prompt-observation.js";
|
|
39
|
-
import type { QuoteSnapshotStore } from "./quote-snapshot-store.js";
|
|
40
|
-
import { promptAndSettle, type SessionActionsController } from "./session-actions.js";
|
|
41
|
-
import { waitForNewEntryId } from "./session-entry-wait.js";
|
|
42
|
-
import { buildCatalog } from "./tool-metadata.js";
|
|
43
|
-
import {
|
|
44
|
-
acquireWriterLock,
|
|
45
|
-
isCoordinatorOwnerAlive,
|
|
46
|
-
readWriterLock,
|
|
47
|
-
refreshWriterLock,
|
|
48
|
-
releaseWriterLock,
|
|
49
|
-
shouldBlockFailedCoordinatorAction as shouldBlockFailedCoordinatorLockAction,
|
|
50
|
-
writerLockScopeForSession,
|
|
51
|
-
} from "./writer-lock.js";
|
|
52
|
-
import type { WsHub } from "./ws-hub.js";
|
|
53
|
-
|
|
54
|
-
interface GuiHttpRouteOptions {
|
|
55
|
-
host: string;
|
|
56
|
-
port: number;
|
|
57
|
-
webDist: string;
|
|
58
|
-
role: string;
|
|
59
|
-
cwd: string;
|
|
60
|
-
agentDir: string;
|
|
61
|
-
sessionDir: string;
|
|
62
|
-
privateApiSessionToken: string;
|
|
63
|
-
localCoordinatorEndpoint: string;
|
|
64
|
-
localCoordinatorSecret: string;
|
|
65
|
-
allowRemotePrivateApi: boolean;
|
|
66
|
-
syncCurrentWriterLockScope?: () => void;
|
|
67
|
-
getSession: () => AgentSession;
|
|
68
|
-
getSessionManager: () => SessionManager;
|
|
69
|
-
createSessionForManager: (sessionManager: SessionManager) => Promise<{ session: AgentSession }>;
|
|
70
|
-
wsHub: WsHub;
|
|
71
|
-
modelSetupController: ModelSetupController;
|
|
72
|
-
sessionActionsController: SessionActionsController;
|
|
73
|
-
toolInvokeController: ToolInvokeController;
|
|
74
|
-
quoteSnapshotStore: QuoteSnapshotStore;
|
|
75
|
-
localSessionCoordinator?: LocalSessionCoordinator;
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
export interface ChatRunImageInput {
|
|
79
|
-
data: string;
|
|
80
|
-
mimeType: string;
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
export type ChatRunAttachmentInput =
|
|
84
|
-
| { kind: "portfolio"; id?: string }
|
|
85
|
-
| { kind: "watchlist"; id: string }
|
|
86
|
-
| { kind: "report"; id: string };
|
|
87
|
-
|
|
88
|
-
export interface ParsedChatRunBody {
|
|
89
|
-
prompt: string;
|
|
90
|
-
images: ChatRunImageInput[];
|
|
91
|
-
attachments: ChatRunAttachmentInput[];
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
type ChatRunParseResult = { ok: true; value: ParsedChatRunBody } | { ok: false; error: string };
|
|
95
|
-
|
|
96
|
-
const CHAT_RUN_IMAGE_MIME_TYPES = new Set(["image/png", "image/jpeg", "image/webp"]);
|
|
97
|
-
const CHAT_RUN_MAX_IMAGE_COUNT = 4;
|
|
98
|
-
const CHAT_RUN_MAX_IMAGE_BYTES = 5 * 1024 * 1024;
|
|
99
|
-
|
|
100
|
-
export function createHttpRequestHandler(options: GuiHttpRouteOptions) {
|
|
101
|
-
const activeRunSessionIds = new Set<string>();
|
|
102
|
-
|
|
103
|
-
return async function handleHttpRequest(
|
|
104
|
-
req: IncomingMessage,
|
|
105
|
-
res: ServerResponse,
|
|
106
|
-
): Promise<void> {
|
|
107
|
-
const url = new URL(req.url ?? "/", `http://${options.host}:${options.port}`);
|
|
108
|
-
if (url.pathname === "/health") {
|
|
109
|
-
writeJson(res, { ok: true, role: options.role });
|
|
110
|
-
return;
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
if (url.pathname === "/api/bootstrap" && req.method === "GET") {
|
|
114
|
-
if (!allowTrustedGuiRequest(req, res, "Bootstrap API", options)) return;
|
|
115
|
-
writeJson(res, await options.wsHub.buildBootstrapPayload());
|
|
116
|
-
return;
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
if (url.pathname === "/api/session/new" && req.method === "POST") {
|
|
120
|
-
if (!allowTrustedGuiRequest(req, res, "Session API", options)) return;
|
|
121
|
-
if (options.role !== "writer") {
|
|
122
|
-
writeJson(
|
|
123
|
-
res,
|
|
124
|
-
{ error: "OpenCandle is reconnecting to this session.", code: "syncing" },
|
|
125
|
-
409,
|
|
126
|
-
);
|
|
127
|
-
return;
|
|
128
|
-
}
|
|
129
|
-
await options.sessionActionsController.handleNewSession();
|
|
130
|
-
options.wsHub.broadcastState();
|
|
131
|
-
options.wsHub.broadcastSessions();
|
|
132
|
-
writeJson(res, await options.wsHub.buildBootstrapPayload());
|
|
133
|
-
return;
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
if (url.pathname === "/api/sessions" && req.method === "GET") {
|
|
137
|
-
if (!allowTrustedGuiRequest(req, res, "Session API", options)) return;
|
|
138
|
-
writeJson(res, {
|
|
139
|
-
currentSessionId: options.getSessionManager().getSessionId(),
|
|
140
|
-
role: options.role,
|
|
141
|
-
sessions: await SessionManager.list(options.cwd, options.sessionDir),
|
|
142
|
-
});
|
|
143
|
-
return;
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
const sessionBootstrapId = sessionIdFromRoute(url.pathname, "bootstrap");
|
|
147
|
-
if (sessionBootstrapId && req.method === "GET") {
|
|
148
|
-
if (!allowTrustedGuiRequest(req, res, "Session API", options)) return;
|
|
149
|
-
const sessionManager = await resolveSessionManagerById(options, sessionBootstrapId);
|
|
150
|
-
if (!sessionManager) {
|
|
151
|
-
writeJson(res, { error: "Unknown saved session" }, 404);
|
|
152
|
-
return;
|
|
153
|
-
}
|
|
154
|
-
writeJson(res, await buildSessionBootstrapPayload(options, sessionManager));
|
|
155
|
-
return;
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
if (url.pathname === "/api/session/events" && req.method === "GET") {
|
|
159
|
-
if (!allowTrustedGuiRequest(req, res, "Session API", options)) return;
|
|
160
|
-
writeJson(res, {
|
|
161
|
-
sessionId: options.getSessionManager().getSessionId(),
|
|
162
|
-
role: options.role,
|
|
163
|
-
events: options.wsHub.currentChatEvents(),
|
|
164
|
-
});
|
|
165
|
-
return;
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
if (url.pathname === "/api/model-setup/refresh" && req.method === "POST") {
|
|
169
|
-
if (!allowTrustedGuiRequest(req, res, "Model setup API", options)) return;
|
|
170
|
-
options.getSession().modelRegistry.refresh();
|
|
171
|
-
options.wsHub.broadcastModelSetup();
|
|
172
|
-
writeJson(res, await options.wsHub.buildBootstrapPayload());
|
|
173
|
-
return;
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
if (url.pathname === "/api/model-setup/api-key" && req.method === "POST") {
|
|
177
|
-
if (!allowTrustedGuiRequest(req, res, "Model setup API", options)) return;
|
|
178
|
-
await handleTrustedGuiMutation(req, res, options, async (body) => {
|
|
179
|
-
await options.modelSetupController.handleSaveModelApiKey(
|
|
180
|
-
String(body.provider ?? ""),
|
|
181
|
-
String(body.apiKey ?? ""),
|
|
182
|
-
);
|
|
183
|
-
options.wsHub.broadcastModelSetup();
|
|
184
|
-
});
|
|
185
|
-
return;
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
if (url.pathname === "/api/model-setup/model" && req.method === "POST") {
|
|
189
|
-
if (!allowTrustedGuiRequest(req, res, "Model setup API", options)) return;
|
|
190
|
-
await handleTrustedGuiMutation(req, res, options, async (body) => {
|
|
191
|
-
await options.modelSetupController.handleSelectModel(
|
|
192
|
-
String(body.provider ?? ""),
|
|
193
|
-
String(body.modelId ?? ""),
|
|
194
|
-
);
|
|
195
|
-
options.wsHub.broadcastModelSetup();
|
|
196
|
-
});
|
|
197
|
-
return;
|
|
198
|
-
}
|
|
199
|
-
|
|
200
|
-
if (url.pathname === "/api/provider-setup/api-key" && req.method === "POST") {
|
|
201
|
-
if (!allowTrustedGuiRequest(req, res, "Provider setup API", options)) return;
|
|
202
|
-
await handleTrustedGuiMutation(req, res, options, async (body) => {
|
|
203
|
-
await options.modelSetupController.handleSaveProviderApiKey(
|
|
204
|
-
String(body.providerId ?? ""),
|
|
205
|
-
String(body.apiKey ?? ""),
|
|
206
|
-
);
|
|
207
|
-
options.wsHub.broadcast({ type: "catalog", catalog: buildCatalog() });
|
|
208
|
-
});
|
|
209
|
-
return;
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
if (url.pathname === "/api/market-state" && req.method === "GET") {
|
|
213
|
-
if (!allowTrustedGuiRequest(req, res, "Market-state API", options)) return;
|
|
214
|
-
writeJson(res, buildMarketStateSnapshot());
|
|
215
|
-
return;
|
|
216
|
-
}
|
|
217
|
-
|
|
218
|
-
if (url.pathname === "/api/market-state/quotes" && req.method === "GET") {
|
|
219
|
-
if (!allowTrustedGuiRequest(req, res, "Market-state API", options)) return;
|
|
220
|
-
writeJson(res, await options.quoteSnapshotStore.get());
|
|
221
|
-
return;
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
if (url.pathname === "/api/doctor" && req.method === "GET") {
|
|
225
|
-
if (!allowTrustedGuiRequest(req, res, "Diagnostics API", options)) return;
|
|
226
|
-
const session = options.getSession();
|
|
227
|
-
writeJson(
|
|
228
|
-
res,
|
|
229
|
-
await buildDoctorReport({
|
|
230
|
-
cwd: options.cwd,
|
|
231
|
-
agentDir: options.agentDir,
|
|
232
|
-
includeSessions: url.searchParams.get("sessions") === "1",
|
|
233
|
-
gui: {
|
|
234
|
-
host: options.host,
|
|
235
|
-
port: options.port,
|
|
236
|
-
role: options.role,
|
|
237
|
-
reachable: true,
|
|
238
|
-
healthEndpoint: `http://${options.host}:${options.port}/health`,
|
|
239
|
-
},
|
|
240
|
-
modelSetup: buildModelSetupState(session.modelRegistry, session.model),
|
|
241
|
-
}),
|
|
242
|
-
);
|
|
243
|
-
return;
|
|
244
|
-
}
|
|
245
|
-
|
|
246
|
-
if (url.pathname === "/api/instruments/search" && req.method === "GET") {
|
|
247
|
-
if (!allowTrustedGuiRequest(req, res, "Market-state API", options)) return;
|
|
248
|
-
writeJson(res, await searchInstrumentCandidates(url.searchParams.get("q") ?? ""));
|
|
249
|
-
return;
|
|
250
|
-
}
|
|
251
|
-
|
|
252
|
-
if (url.pathname === "/api/diagnostics/twitter-cli" && req.method === "GET") {
|
|
253
|
-
if (!allowTrustedGuiRequest(req, res, "Diagnostics API", options)) return;
|
|
254
|
-
const mode = url.searchParams.get("mode") === "session" ? "session" : "install";
|
|
255
|
-
const force = url.searchParams.get("force") === "1";
|
|
256
|
-
writeJson(res, await probeProviderStatus("twitter", { mode, force }));
|
|
257
|
-
return;
|
|
258
|
-
}
|
|
259
|
-
|
|
260
|
-
if (url.pathname === "/api/diagnostics/reddit-cli" && req.method === "GET") {
|
|
261
|
-
if (!allowTrustedGuiRequest(req, res, "Diagnostics API", options)) return;
|
|
262
|
-
const mode = url.searchParams.get("mode") === "session" ? "session" : "install";
|
|
263
|
-
const force = url.searchParams.get("force") === "1";
|
|
264
|
-
writeJson(res, await probeProviderStatus("reddit", { mode, force }));
|
|
265
|
-
return;
|
|
266
|
-
}
|
|
267
|
-
|
|
268
|
-
if (url.pathname === "/api/chat/run" && req.method === "POST") {
|
|
269
|
-
if (!allowTrustedGuiRequest(req, res, "Chat run API", options)) return;
|
|
270
|
-
writeJson(
|
|
271
|
-
res,
|
|
272
|
-
{
|
|
273
|
-
error: "Legacy active-session chat runs are no longer supported.",
|
|
274
|
-
code: "legacy_route_removed",
|
|
275
|
-
},
|
|
276
|
-
410,
|
|
277
|
-
);
|
|
278
|
-
return;
|
|
279
|
-
}
|
|
280
|
-
|
|
281
|
-
if (url.pathname === "/api/local-coordinator/chat-run" && req.method === "POST") {
|
|
282
|
-
if (!allowLocalCoordinatorRequest(req, res, options)) return;
|
|
283
|
-
const body = asRecord(await readJsonBody(req));
|
|
284
|
-
if (!requireSessionActionFields(res, body)) return;
|
|
285
|
-
const sessionManager = await resolveSessionManagerById(options, String(body.sessionId));
|
|
286
|
-
if (!sessionManager) {
|
|
287
|
-
writeJson(res, { error: "Unknown saved session" }, 404);
|
|
288
|
-
return;
|
|
289
|
-
}
|
|
290
|
-
// allowProxy: false — this endpoint is the proxy target; re-proxying loops.
|
|
291
|
-
await handleSseChatRun(req, res, options, activeRunSessionIds, sessionManager, body, false);
|
|
292
|
-
return;
|
|
293
|
-
}
|
|
294
|
-
|
|
295
|
-
if (url.pathname === "/api/local-coordinator/tool-invoke" && req.method === "POST") {
|
|
296
|
-
if (!allowLocalCoordinatorRequest(req, res, options)) return;
|
|
297
|
-
const body = asRecord(await readJsonBody(req));
|
|
298
|
-
if (!requireSessionActionFields(res, body)) return;
|
|
299
|
-
let ack: unknown;
|
|
300
|
-
await options.toolInvokeController.handleToolInvokeMessage(
|
|
301
|
-
{ send: (message) => (ack = message) },
|
|
302
|
-
{
|
|
303
|
-
requestId: "local-coordinator-tool",
|
|
304
|
-
actionId: String(body.actionId ?? ""),
|
|
305
|
-
sessionId: String(body.sessionId ?? ""),
|
|
306
|
-
toolName: String(body.toolName ?? ""),
|
|
307
|
-
args: asRecord(body.args),
|
|
308
|
-
allowProxy: false,
|
|
309
|
-
},
|
|
310
|
-
);
|
|
311
|
-
const message = asRecord(ack);
|
|
312
|
-
const result = asRecord(message.result);
|
|
313
|
-
if (result.toolCallId) {
|
|
314
|
-
writeJson(res, { result });
|
|
315
|
-
} else {
|
|
316
|
-
writeJson(
|
|
317
|
-
res,
|
|
318
|
-
{ error: String(asRecord(message.error).message ?? "Tool invocation failed") },
|
|
319
|
-
409,
|
|
320
|
-
);
|
|
321
|
-
}
|
|
322
|
-
return;
|
|
323
|
-
}
|
|
324
|
-
|
|
325
|
-
if (url.pathname === "/api/local-coordinator/ask-user" && req.method === "POST") {
|
|
326
|
-
if (!allowLocalCoordinatorRequest(req, res, options)) return;
|
|
327
|
-
const body = asRecord(await readJsonBody(req));
|
|
328
|
-
if (!requireSessionActionFields(res, body)) return;
|
|
329
|
-
const payload = asRecord(body.payload);
|
|
330
|
-
try {
|
|
331
|
-
const action = {
|
|
332
|
-
actionId: String(body.actionId ?? ""),
|
|
333
|
-
sessionId: String(body.sessionId ?? ""),
|
|
334
|
-
source: "browser" as const,
|
|
335
|
-
allowProxy: false,
|
|
336
|
-
};
|
|
337
|
-
if (body.actionType === "ask_user.answer") {
|
|
338
|
-
await options.sessionActionsController.handleAskUserAnswer(
|
|
339
|
-
String(payload.id ?? ""),
|
|
340
|
-
payload.answer,
|
|
341
|
-
action,
|
|
342
|
-
);
|
|
343
|
-
} else if (body.actionType === "ask_user.cancel") {
|
|
344
|
-
await options.sessionActionsController.handleAskUserCancel(
|
|
345
|
-
String(payload.id ?? ""),
|
|
346
|
-
action,
|
|
347
|
-
);
|
|
348
|
-
} else {
|
|
349
|
-
writeJson(res, { error: "Unknown ask_user action" }, 400);
|
|
350
|
-
return;
|
|
351
|
-
}
|
|
352
|
-
writeJson(res, { ok: true });
|
|
353
|
-
} catch (error) {
|
|
354
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
355
|
-
writeJson(res, { error: message }, 409);
|
|
356
|
-
}
|
|
357
|
-
return;
|
|
358
|
-
}
|
|
359
|
-
|
|
360
|
-
const runSessionId = sessionIdFromRoute(url.pathname, "runs");
|
|
361
|
-
if (runSessionId && req.method === "POST") {
|
|
362
|
-
if (!allowTrustedGuiRequest(req, res, "Chat run API", options)) return;
|
|
363
|
-
const body = asRecord(await readJsonBody(req));
|
|
364
|
-
if (!requireSessionActionFields(res, { ...body, sessionId: runSessionId }, false)) return;
|
|
365
|
-
const sessionManager = await resolveSessionManagerById(options, runSessionId);
|
|
366
|
-
if (!sessionManager) {
|
|
367
|
-
writeJson(res, { error: "Unknown saved session" }, 404);
|
|
368
|
-
return;
|
|
369
|
-
}
|
|
370
|
-
// allowProxy: true — forward to a live coordinator owned by another
|
|
371
|
-
// process (0.11.0 authenticated local forwarding).
|
|
372
|
-
await handleSseChatRun(req, res, options, activeRunSessionIds, sessionManager, body, true);
|
|
373
|
-
return;
|
|
374
|
-
}
|
|
375
|
-
|
|
376
|
-
serveStaticAsset(url.pathname, res, options);
|
|
377
|
-
};
|
|
378
|
-
}
|
|
379
|
-
|
|
380
|
-
async function handleSseChatRun(
|
|
381
|
-
req: IncomingMessage,
|
|
382
|
-
res: ServerResponse,
|
|
383
|
-
options: GuiHttpRouteOptions,
|
|
384
|
-
activeRunSessionIds: Set<string>,
|
|
385
|
-
targetSessionManager: SessionManager | undefined,
|
|
386
|
-
bodyOverride: Record<string, unknown> | undefined,
|
|
387
|
-
// Explicit because both remaining callers pass a body: the browser-facing
|
|
388
|
-
// runs route must forward to a live coordinator owned by another process,
|
|
389
|
-
// while the local-coordinator endpoint IS the proxy target and re-proxying
|
|
390
|
-
// there would loop.
|
|
391
|
-
allowProxy: boolean,
|
|
392
|
-
): Promise<void> {
|
|
393
|
-
const body = bodyOverride ?? asRecord(await readJsonBody(req));
|
|
394
|
-
const parsed = parseChatRunBody(body);
|
|
395
|
-
if (!parsed.ok) {
|
|
396
|
-
writeJson(res, { error: parsed.error }, 400);
|
|
397
|
-
return;
|
|
398
|
-
}
|
|
399
|
-
const currentSessionManager = options.getSessionManager();
|
|
400
|
-
const bodyRecord = asRecord(body);
|
|
401
|
-
const requestedSessionId = String(bodyRecord.sessionId ?? "").trim();
|
|
402
|
-
const runSessionManager = targetSessionManager ?? currentSessionManager;
|
|
403
|
-
const sessionId = runSessionManager.getSessionId();
|
|
404
|
-
if (requestedSessionId && requestedSessionId !== sessionId) {
|
|
405
|
-
writeJson(
|
|
406
|
-
res,
|
|
407
|
-
{ error: "Session route and request body disagree", code: "session_changed" },
|
|
408
|
-
409,
|
|
409
|
-
);
|
|
410
|
-
return;
|
|
411
|
-
}
|
|
412
|
-
|
|
413
|
-
const actionId = String(bodyRecord.actionId ?? "").trim();
|
|
414
|
-
const shouldProxyChatRun = allowProxy && canProxyChatRunToCoordinator(runSessionManager);
|
|
415
|
-
if (shouldProxyChatRun) {
|
|
416
|
-
if (await proxyChatRunToCoordinator(res, runSessionManager, bodyRecord)) {
|
|
417
|
-
const useCurrentSession =
|
|
418
|
-
!targetSessionManager ||
|
|
419
|
-
currentSessionManager.getSessionFile() === runSessionManager.getSessionFile();
|
|
420
|
-
await broadcastFreshRunSessionSnapshot(options, runSessionManager, useCurrentSession);
|
|
421
|
-
return;
|
|
422
|
-
}
|
|
423
|
-
if (actionId && hasAcceptedSessionAction(runSessionManager, actionId)) {
|
|
424
|
-
writeJson(res, { ok: true, duplicate: true });
|
|
425
|
-
return;
|
|
426
|
-
}
|
|
427
|
-
if (actionId && hasPendingSessionAction(runSessionManager, actionId)) {
|
|
428
|
-
writeJson(
|
|
429
|
-
res,
|
|
430
|
-
{ error: "OpenCandle is reconnecting to this session.", code: "syncing" },
|
|
431
|
-
409,
|
|
432
|
-
);
|
|
433
|
-
return;
|
|
434
|
-
}
|
|
435
|
-
if (shouldBlockFailedCoordinatorAction(runSessionManager, bodyRecord)) {
|
|
436
|
-
writeJson(
|
|
437
|
-
res,
|
|
438
|
-
{ error: "OpenCandle is reconnecting to this session.", code: "syncing" },
|
|
439
|
-
409,
|
|
440
|
-
);
|
|
441
|
-
return;
|
|
442
|
-
}
|
|
443
|
-
}
|
|
444
|
-
if (actionId && hasAcceptedSessionAction(runSessionManager, actionId)) {
|
|
445
|
-
writeJson(res, { ok: true, duplicate: true });
|
|
446
|
-
return;
|
|
447
|
-
}
|
|
448
|
-
if (actionId && hasPendingSessionAction(runSessionManager, actionId)) {
|
|
449
|
-
writeJson(res, { error: "OpenCandle is reconnecting to this session.", code: "syncing" }, 409);
|
|
450
|
-
return;
|
|
451
|
-
}
|
|
452
|
-
|
|
453
|
-
if (options.localSessionCoordinator) {
|
|
454
|
-
const action = buildChatRunActionEnvelope(bodyRecord, sessionId);
|
|
455
|
-
let result: SessionActionResult<{ streamed: boolean }>;
|
|
456
|
-
try {
|
|
457
|
-
result = await options.localSessionCoordinator.runSessionAction(action, async () => {
|
|
458
|
-
const admitted = await streamAcceptedSseChatRun({
|
|
459
|
-
res,
|
|
460
|
-
options,
|
|
461
|
-
activeRunSessionIds,
|
|
462
|
-
targetSessionManager,
|
|
463
|
-
currentSessionManager,
|
|
464
|
-
runSessionManager,
|
|
465
|
-
sessionId,
|
|
466
|
-
parsedRun: parsed.value,
|
|
467
|
-
actionId: action.actionId,
|
|
468
|
-
});
|
|
469
|
-
if (!admitted) throw new SessionActionNotAdmitted();
|
|
470
|
-
return { streamed: true };
|
|
471
|
-
});
|
|
472
|
-
} catch (error) {
|
|
473
|
-
if (error instanceof SessionActionNotAdmitted) return;
|
|
474
|
-
throw error;
|
|
475
|
-
}
|
|
476
|
-
if (!result.ok) {
|
|
477
|
-
writeJson(res, { error: result.message, code: result.code }, 409);
|
|
478
|
-
return;
|
|
479
|
-
}
|
|
480
|
-
if (result.duplicate && !res.headersSent) {
|
|
481
|
-
writeJson(res, { ok: true, duplicate: true });
|
|
482
|
-
}
|
|
483
|
-
return;
|
|
484
|
-
}
|
|
485
|
-
|
|
486
|
-
await streamAcceptedSseChatRun({
|
|
487
|
-
res,
|
|
488
|
-
options,
|
|
489
|
-
activeRunSessionIds,
|
|
490
|
-
targetSessionManager,
|
|
491
|
-
currentSessionManager,
|
|
492
|
-
runSessionManager,
|
|
493
|
-
sessionId,
|
|
494
|
-
parsedRun: parsed.value,
|
|
495
|
-
actionId,
|
|
496
|
-
});
|
|
497
|
-
}
|
|
498
|
-
|
|
499
|
-
export function canProxyChatRunToCoordinator(runSessionManager: SessionManager): boolean {
|
|
500
|
-
const lock = readWriterLock(writerLockScopeForSession(runSessionManager));
|
|
501
|
-
return hasLiveCoordinatorLock(lock);
|
|
502
|
-
}
|
|
503
|
-
|
|
504
|
-
async function proxyChatRunToCoordinator(
|
|
505
|
-
res: ServerResponse,
|
|
506
|
-
runSessionManager: SessionManager,
|
|
507
|
-
body: Record<string, unknown>,
|
|
508
|
-
): Promise<boolean> {
|
|
509
|
-
const lock = readWriterLock(writerLockScopeForSession(runSessionManager));
|
|
510
|
-
if (!hasLiveCoordinatorLock(lock)) return false;
|
|
511
|
-
const endpoint = new URL("/api/local-coordinator/chat-run", lock.coordinatorEndpoint);
|
|
512
|
-
let response: Response;
|
|
513
|
-
try {
|
|
514
|
-
response = await fetch(endpoint, {
|
|
515
|
-
method: "POST",
|
|
516
|
-
headers: {
|
|
517
|
-
"content-type": "application/json",
|
|
518
|
-
"x-opencandle-coordinator-secret": lock.coordinatorSecret,
|
|
519
|
-
},
|
|
520
|
-
body: JSON.stringify({ ...body, sessionId: runSessionManager.getSessionId() }),
|
|
521
|
-
});
|
|
522
|
-
} catch {
|
|
523
|
-
return false;
|
|
524
|
-
}
|
|
525
|
-
res.writeHead(response.status, Object.fromEntries(response.headers));
|
|
526
|
-
if (response.body) {
|
|
527
|
-
for await (const chunk of response.body) {
|
|
528
|
-
res.write(chunk);
|
|
529
|
-
}
|
|
530
|
-
}
|
|
531
|
-
res.end();
|
|
532
|
-
return true;
|
|
533
|
-
}
|
|
534
|
-
|
|
535
|
-
function hasLiveCoordinatorLock(
|
|
536
|
-
lock: ReturnType<typeof readWriterLock>,
|
|
537
|
-
staleGraceMs = 15_000,
|
|
538
|
-
): lock is NonNullable<ReturnType<typeof readWriterLock>> & {
|
|
539
|
-
coordinatorEndpoint: string;
|
|
540
|
-
coordinatorSecret: string;
|
|
541
|
-
} {
|
|
542
|
-
if (!lock?.coordinatorEndpoint || !lock.coordinatorSecret || lock.pid === process.pid) {
|
|
543
|
-
return false;
|
|
544
|
-
}
|
|
545
|
-
const heartbeat = Date.parse(lock.lastHeartbeat);
|
|
546
|
-
const hasFreshHeartbeat = Number.isFinite(heartbeat) && Date.now() - heartbeat <= staleGraceMs;
|
|
547
|
-
return hasFreshHeartbeat && isCoordinatorOwnerAlive(lock.pid);
|
|
548
|
-
}
|
|
549
|
-
|
|
550
|
-
async function streamAcceptedSseChatRun({
|
|
551
|
-
res,
|
|
552
|
-
options,
|
|
553
|
-
activeRunSessionIds,
|
|
554
|
-
targetSessionManager,
|
|
555
|
-
currentSessionManager,
|
|
556
|
-
runSessionManager,
|
|
557
|
-
sessionId,
|
|
558
|
-
parsedRun,
|
|
559
|
-
actionId,
|
|
560
|
-
}: {
|
|
561
|
-
res: ServerResponse;
|
|
562
|
-
options: GuiHttpRouteOptions;
|
|
563
|
-
activeRunSessionIds: Set<string>;
|
|
564
|
-
targetSessionManager?: SessionManager;
|
|
565
|
-
currentSessionManager: SessionManager;
|
|
566
|
-
runSessionManager: SessionManager;
|
|
567
|
-
sessionId: string;
|
|
568
|
-
parsedRun: ParsedChatRunBody;
|
|
569
|
-
actionId: string;
|
|
570
|
-
}): Promise<boolean> {
|
|
571
|
-
const prompt = parsedRun.prompt;
|
|
572
|
-
if (activeRunSessionIds.has(sessionId)) {
|
|
573
|
-
writeJson(res, { error: "Session already has an active run", code: "session_busy" }, 409);
|
|
574
|
-
return false;
|
|
575
|
-
}
|
|
576
|
-
let dispatchedPrompt: string;
|
|
577
|
-
try {
|
|
578
|
-
dispatchedPrompt = await buildDispatchedPrompt(parsedRun);
|
|
579
|
-
} catch (error) {
|
|
580
|
-
writeJson(res, { error: error instanceof Error ? error.message : String(error) }, 400);
|
|
581
|
-
return false;
|
|
582
|
-
}
|
|
583
|
-
const promptImages = parsedRun.images.map((image) => ({
|
|
584
|
-
type: "image" as const,
|
|
585
|
-
data: image.data,
|
|
586
|
-
mimeType: image.mimeType,
|
|
587
|
-
}));
|
|
588
|
-
const attachmentLabels = parsedRun.attachments.map((attachment) => ({
|
|
589
|
-
kind: attachment.kind,
|
|
590
|
-
label: attachmentLabel(attachment),
|
|
591
|
-
}));
|
|
592
|
-
const inputAttachmentLabels = [
|
|
593
|
-
...promptImages.map((image, index) => ({
|
|
594
|
-
kind: "image",
|
|
595
|
-
label: `${image.mimeType || "image"} #${index + 1}`,
|
|
596
|
-
})),
|
|
597
|
-
...attachmentLabels,
|
|
598
|
-
];
|
|
599
|
-
|
|
600
|
-
const currentSessionFile = currentSessionManager.getSessionFile();
|
|
601
|
-
const targetSessionFile = runSessionManager.getSessionFile();
|
|
602
|
-
const useCurrentSession = !targetSessionManager || currentSessionFile === targetSessionFile;
|
|
603
|
-
let acquiredLockScope = "";
|
|
604
|
-
let lockHeartbeat: ReturnType<typeof setInterval> | undefined;
|
|
605
|
-
const needsWriterLock = !useCurrentSession || options.role !== "writer";
|
|
606
|
-
if (needsWriterLock) {
|
|
607
|
-
const lockScope = writerLockScopeForSession(runSessionManager);
|
|
608
|
-
const lockResult = await acquireWriterLock(lockScope, "gui", {
|
|
609
|
-
coordinatorEndpoint: options.localCoordinatorEndpoint,
|
|
610
|
-
coordinatorSecret: options.localCoordinatorSecret,
|
|
611
|
-
});
|
|
612
|
-
if (lockResult.role !== "writer") {
|
|
613
|
-
writeJson(
|
|
614
|
-
res,
|
|
615
|
-
{ error: "OpenCandle is reconnecting to this session.", code: "syncing" },
|
|
616
|
-
409,
|
|
617
|
-
);
|
|
618
|
-
return false;
|
|
619
|
-
}
|
|
620
|
-
acquiredLockScope = lockScope;
|
|
621
|
-
lockHeartbeat = setInterval(() => refreshWriterLock(lockScope), 5000);
|
|
622
|
-
}
|
|
623
|
-
|
|
624
|
-
activeRunSessionIds.add(sessionId);
|
|
625
|
-
let createdSession: { session: AgentSession } | null = null;
|
|
626
|
-
try {
|
|
627
|
-
createdSession = useCurrentSession
|
|
628
|
-
? null
|
|
629
|
-
: await options.createSessionForManager(runSessionManager);
|
|
630
|
-
} catch (error) {
|
|
631
|
-
activeRunSessionIds.delete(sessionId);
|
|
632
|
-
if (lockHeartbeat) clearInterval(lockHeartbeat);
|
|
633
|
-
if (acquiredLockScope) releaseWriterLock(acquiredLockScope);
|
|
634
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
635
|
-
writeJson(res, { error: message }, 500);
|
|
636
|
-
return false;
|
|
637
|
-
}
|
|
638
|
-
|
|
639
|
-
res.writeHead(200, {
|
|
640
|
-
"content-type": "text/event-stream; charset=utf-8",
|
|
641
|
-
"cache-control": "no-cache, no-transform",
|
|
642
|
-
connection: "keep-alive",
|
|
643
|
-
});
|
|
644
|
-
|
|
645
|
-
let seq = 1;
|
|
646
|
-
const runId = `gui-run-${Date.now()}`;
|
|
647
|
-
const runSession = createdSession?.session ?? options.getSession();
|
|
648
|
-
if (!prompt.startsWith("/") && !runSessionManager.getSessionName()) {
|
|
649
|
-
runSessionManager.appendSessionInfo(prompt.length > 80 ? `${prompt.slice(0, 77)}...` : prompt);
|
|
650
|
-
}
|
|
651
|
-
const beforeEntries = runSessionManager.getEntries();
|
|
652
|
-
const beforeCount = beforeEntries.length;
|
|
653
|
-
const beforeIds = new Set(beforeEntries.map((entry) => entry.id));
|
|
654
|
-
writeSse(res, { type: "run.started", runId, sessionId, seq: seq++ });
|
|
655
|
-
res.flushHeaders?.();
|
|
656
|
-
const liveStartSeq = seq;
|
|
657
|
-
const liveAdapter = createLiveChatEventAdapter({
|
|
658
|
-
runId,
|
|
659
|
-
sessionId,
|
|
660
|
-
startSeq: seq,
|
|
661
|
-
emit: (event) => writeSse(res, event),
|
|
662
|
-
originalPrompt: prompt,
|
|
663
|
-
originalAttachments: inputAttachmentLabels,
|
|
664
|
-
});
|
|
665
|
-
const observation = createPromptObservation();
|
|
666
|
-
let originalInputMarkerAppended = false;
|
|
667
|
-
const appendOriginalInputMarker = () => {
|
|
668
|
-
if (inputAttachmentLabels.length === 0 || originalInputMarkerAppended) return;
|
|
669
|
-
runSessionManager.appendCustomEntry("opencandle-user-input", {
|
|
670
|
-
original: prompt,
|
|
671
|
-
attachments: inputAttachmentLabels,
|
|
672
|
-
});
|
|
673
|
-
originalInputMarkerAppended = true;
|
|
674
|
-
};
|
|
675
|
-
let actionAccepted = false;
|
|
676
|
-
const recordAcceptedAction = () => {
|
|
677
|
-
if (actionAccepted) return;
|
|
678
|
-
appendOriginalInputMarker();
|
|
679
|
-
recordAcceptedSessionAction(runSessionManager, actionId);
|
|
680
|
-
if (useCurrentSession) options.syncCurrentWriterLockScope?.();
|
|
681
|
-
actionAccepted = true;
|
|
682
|
-
};
|
|
683
|
-
|
|
684
|
-
const unsubscribeLive = runSession.subscribe((event) => {
|
|
685
|
-
liveAdapter.handle(event);
|
|
686
|
-
observePromptEvent(observation, event);
|
|
687
|
-
if (
|
|
688
|
-
!prompt.startsWith("/") &&
|
|
689
|
-
!actionAccepted &&
|
|
690
|
-
observation.userTexts.some((text) => text.trim() === dispatchedPrompt.trim())
|
|
691
|
-
) {
|
|
692
|
-
recordAcceptedAction();
|
|
693
|
-
}
|
|
694
|
-
});
|
|
695
|
-
|
|
696
|
-
try {
|
|
697
|
-
recordPendingSessionAction(runSessionManager, actionId);
|
|
698
|
-
const modelSetup = buildModelSetupState(runSession.modelRegistry, runSession.model);
|
|
699
|
-
if (!prompt.startsWith("/") && modelSetup.requirement !== "ready") {
|
|
700
|
-
runSessionManager.appendMessage({ role: "user", content: prompt, timestamp: Date.now() });
|
|
701
|
-
recordAcceptedAction();
|
|
702
|
-
const message =
|
|
703
|
-
modelSetup.requirement === "select_model"
|
|
704
|
-
? "Choose an available model before chat can run. OpenCandle found configured credentials but no active model."
|
|
705
|
-
: "Connect an AI model before chat can run. Paste a Google Gemini, OpenAI, or Anthropic API key in the setup panel.";
|
|
706
|
-
runSessionManager.appendCustomMessageEntry("opencandle-model-setup", message, true, {
|
|
707
|
-
source: "gui",
|
|
708
|
-
requirement: modelSetup.requirement,
|
|
709
|
-
});
|
|
710
|
-
await broadcastRunSessionSnapshot(options, runSessionManager, useCurrentSession);
|
|
711
|
-
} else {
|
|
712
|
-
await promptAndSettle(
|
|
713
|
-
runSession,
|
|
714
|
-
dispatchedPrompt,
|
|
715
|
-
beforeIds,
|
|
716
|
-
observation,
|
|
717
|
-
promptImages.length > 0 ? { images: promptImages } : undefined,
|
|
718
|
-
);
|
|
719
|
-
recordAcceptedAction();
|
|
720
|
-
await broadcastRunSessionSnapshot(options, runSessionManager, useCurrentSession);
|
|
721
|
-
}
|
|
722
|
-
seq = liveAdapter.nextSeq();
|
|
723
|
-
if (seq === liveStartSeq) {
|
|
724
|
-
await waitForNewEntryId(
|
|
725
|
-
() => runSessionManager.getEntries().map((entry) => entry.id),
|
|
726
|
-
beforeIds,
|
|
727
|
-
);
|
|
728
|
-
const newEntries = runSessionManager
|
|
729
|
-
.getEntries()
|
|
730
|
-
.slice(beforeCount)
|
|
731
|
-
.filter((entry) => !beforeIds.has(entry.id));
|
|
732
|
-
const events = sessionEntriesToChatEvents(newEntries, {
|
|
733
|
-
sessionId,
|
|
734
|
-
updatedAt: new Date().toISOString(),
|
|
735
|
-
startSeq: seq,
|
|
736
|
-
});
|
|
737
|
-
for (const event of events) {
|
|
738
|
-
writeSse(res, event);
|
|
739
|
-
seq = event.seq + 1;
|
|
740
|
-
}
|
|
741
|
-
}
|
|
742
|
-
writeSse(res, { type: "run.completed", runId, sessionId, seq });
|
|
743
|
-
} catch (error) {
|
|
744
|
-
if (!actionAccepted) clearPendingSessionAction(runSessionManager, actionId);
|
|
745
|
-
seq = liveAdapter.nextSeq();
|
|
746
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
747
|
-
writeSse(res, { type: "run.failed", runId, sessionId, error: { message }, seq });
|
|
748
|
-
} finally {
|
|
749
|
-
activeRunSessionIds.delete(sessionId);
|
|
750
|
-
unsubscribeLive();
|
|
751
|
-
createdSession?.session.dispose();
|
|
752
|
-
if (lockHeartbeat) clearInterval(lockHeartbeat);
|
|
753
|
-
if (acquiredLockScope) releaseWriterLock(acquiredLockScope);
|
|
754
|
-
res.end();
|
|
755
|
-
}
|
|
756
|
-
return actionAccepted;
|
|
757
|
-
}
|
|
758
|
-
|
|
759
|
-
class SessionActionNotAdmitted extends Error {}
|
|
760
|
-
|
|
761
|
-
async function broadcastRunSessionSnapshot(
|
|
762
|
-
options: GuiHttpRouteOptions,
|
|
763
|
-
sessionManager: SessionManager,
|
|
764
|
-
useCurrentSession: boolean,
|
|
765
|
-
): Promise<void> {
|
|
766
|
-
if (useCurrentSession) {
|
|
767
|
-
options.syncCurrentWriterLockScope?.();
|
|
768
|
-
options.wsHub.broadcastState();
|
|
769
|
-
} else {
|
|
770
|
-
options.wsHub.broadcastSessionSnapshot(sessionManager);
|
|
771
|
-
options.wsHub.broadcastSessions();
|
|
772
|
-
}
|
|
773
|
-
}
|
|
774
|
-
|
|
775
|
-
async function broadcastFreshRunSessionSnapshot(
|
|
776
|
-
options: GuiHttpRouteOptions,
|
|
777
|
-
sessionManager: SessionManager,
|
|
778
|
-
useCurrentSession: boolean,
|
|
779
|
-
): Promise<void> {
|
|
780
|
-
const freshSessionManager = await reloadSessionManager(sessionManager, options);
|
|
781
|
-
if (useCurrentSession) {
|
|
782
|
-
options.syncCurrentWriterLockScope?.();
|
|
783
|
-
options.wsHub.broadcast({
|
|
784
|
-
type: "state.snapshot",
|
|
785
|
-
...buildSnapshotPayload(freshSessionManager),
|
|
786
|
-
});
|
|
787
|
-
} else {
|
|
788
|
-
options.wsHub.broadcast({
|
|
789
|
-
type: "session.snapshot",
|
|
790
|
-
...buildSnapshotPayload(freshSessionManager),
|
|
791
|
-
});
|
|
792
|
-
options.wsHub.broadcastSessions();
|
|
793
|
-
}
|
|
794
|
-
}
|
|
795
|
-
|
|
796
|
-
async function reloadSessionManager(
|
|
797
|
-
sessionManager: SessionManager,
|
|
798
|
-
options: Pick<GuiHttpRouteOptions, "sessionDir" | "cwd">,
|
|
799
|
-
): Promise<SessionManager> {
|
|
800
|
-
const sessionFile = sessionManager.getSessionFile();
|
|
801
|
-
return sessionFile
|
|
802
|
-
? SessionManager.open(sessionFile, options.sessionDir, options.cwd)
|
|
803
|
-
: sessionManager;
|
|
804
|
-
}
|
|
805
|
-
|
|
806
|
-
function buildSnapshotPayload(sessionManager: SessionManager): Record<string, unknown> {
|
|
807
|
-
const sessionId = sessionManager.getSessionId();
|
|
808
|
-
const entries = sessionManager.getEntries();
|
|
809
|
-
return {
|
|
810
|
-
sessionId,
|
|
811
|
-
state: projectDashboard(entries, sessionId, getSavedMarketStateSymbols()),
|
|
812
|
-
entries,
|
|
813
|
-
events: sessionEntriesToChatEvents(entries, {
|
|
814
|
-
sessionId,
|
|
815
|
-
title: sessionManager.getSessionName(),
|
|
816
|
-
}),
|
|
817
|
-
};
|
|
818
|
-
}
|
|
819
|
-
|
|
820
|
-
export async function buildSessionBootstrapPayload(
|
|
821
|
-
options: Pick<
|
|
822
|
-
GuiHttpRouteOptions,
|
|
823
|
-
"cwd" | "sessionDir" | "role" | "modelSetupController" | "getSessionManager" | "wsHub"
|
|
824
|
-
>,
|
|
825
|
-
sessionManager: SessionManager,
|
|
826
|
-
): Promise<Record<string, unknown>> {
|
|
827
|
-
const sessionId = sessionManager.getSessionId();
|
|
828
|
-
const entries = sessionManager.getEntries();
|
|
829
|
-
const bootstrap = await options.wsHub.buildBootstrapPayload();
|
|
830
|
-
return {
|
|
831
|
-
role: roleForSessionBootstrap(options, sessionManager),
|
|
832
|
-
sessionId,
|
|
833
|
-
coordination: {
|
|
834
|
-
sessionId,
|
|
835
|
-
status: roleForSessionBootstrap(options, sessionManager) === "writer" ? "ready" : "syncing",
|
|
836
|
-
ownerKind: ownerKindForSessionBootstrap(options, sessionManager),
|
|
837
|
-
},
|
|
838
|
-
catalog: buildCatalog(),
|
|
839
|
-
modelSetup: options.modelSetupController.buildCurrentModelSetupState(),
|
|
840
|
-
askUserPrompts: Array.isArray(bootstrap.askUserPrompts) ? bootstrap.askUserPrompts : [],
|
|
841
|
-
sessions: await SessionManager.list(options.cwd, options.sessionDir),
|
|
842
|
-
snapshot: {
|
|
843
|
-
sessionId,
|
|
844
|
-
state: projectDashboard(entries, sessionId, getSavedMarketStateSymbols()),
|
|
845
|
-
entries,
|
|
846
|
-
events: sessionEntriesToChatEvents(entries, {
|
|
847
|
-
sessionId,
|
|
848
|
-
title: sessionManager.getSessionName(),
|
|
849
|
-
}),
|
|
850
|
-
},
|
|
851
|
-
};
|
|
852
|
-
}
|
|
853
|
-
|
|
854
|
-
function ownerKindForSessionBootstrap(
|
|
855
|
-
options: Pick<GuiHttpRouteOptions, "getSessionManager" | "role">,
|
|
856
|
-
sessionManager: SessionManager,
|
|
857
|
-
): string | undefined {
|
|
858
|
-
if (roleForSessionBootstrap(options, sessionManager) === "writer") return "gui";
|
|
859
|
-
return readWriterLock(writerLockScopeForSession(sessionManager))?.processKind;
|
|
860
|
-
}
|
|
861
|
-
|
|
862
|
-
function roleForSessionBootstrap(
|
|
863
|
-
options: Pick<GuiHttpRouteOptions, "role" | "getSessionManager">,
|
|
864
|
-
sessionManager: SessionManager,
|
|
865
|
-
): string {
|
|
866
|
-
if (options.role !== "writer") return options.role;
|
|
867
|
-
const currentSessionManager = options.getSessionManager();
|
|
868
|
-
if (currentSessionManager.getSessionFile() === sessionManager.getSessionFile()) return "writer";
|
|
869
|
-
const lock = readWriterLock(writerLockScopeForSession(sessionManager));
|
|
870
|
-
return lock && lock.pid !== process.pid ? "follower" : "writer";
|
|
871
|
-
}
|
|
872
|
-
|
|
873
|
-
export async function resolveSessionManagerById(
|
|
874
|
-
options: Pick<GuiHttpRouteOptions, "cwd" | "sessionDir" | "getSessionManager">,
|
|
875
|
-
sessionId: string,
|
|
876
|
-
): Promise<SessionManager | null> {
|
|
877
|
-
const currentSessionManager = options.getSessionManager();
|
|
878
|
-
if (currentSessionManager.getSessionId() === sessionId) return currentSessionManager;
|
|
879
|
-
const sessions = await SessionManager.list(options.cwd, options.sessionDir);
|
|
880
|
-
const match = sessions.find((candidate) => candidate.id === sessionId);
|
|
881
|
-
return match ? SessionManager.open(match.path, options.sessionDir, options.cwd) : null;
|
|
882
|
-
}
|
|
883
|
-
|
|
884
|
-
export function sessionIdFromRoute(pathname: string, action: "bootstrap" | "runs"): string {
|
|
885
|
-
const match = pathname.match(new RegExp(`^/api/sessions/([^/]+)/${action}$`));
|
|
886
|
-
if (!match) return "";
|
|
887
|
-
try {
|
|
888
|
-
return decodeURIComponent(match[1] ?? "");
|
|
889
|
-
} catch {
|
|
890
|
-
return "";
|
|
891
|
-
}
|
|
892
|
-
}
|
|
893
|
-
|
|
894
|
-
export function buildChatRunActionEnvelope(
|
|
895
|
-
body: Record<string, unknown>,
|
|
896
|
-
sessionId: string,
|
|
897
|
-
): SessionActionEnvelope {
|
|
898
|
-
const actionId = String(body.actionId ?? "").trim();
|
|
899
|
-
const parsed = parseChatRunBody(body);
|
|
900
|
-
const attachments = parsed.ok ? parsed.value.attachments : [];
|
|
901
|
-
const images = parsed.ok ? parsed.value.images : [];
|
|
902
|
-
return {
|
|
903
|
-
sessionId,
|
|
904
|
-
actionId,
|
|
905
|
-
actionType: "chat.prompt",
|
|
906
|
-
payload: {
|
|
907
|
-
prompt: String(body.prompt ?? ""),
|
|
908
|
-
...(images.length > 0 ? { imageCount: images.length } : {}),
|
|
909
|
-
...(attachments.length > 0
|
|
910
|
-
? { attachments: attachments.map((attachment) => ({ kind: attachment.kind })) }
|
|
911
|
-
: {}),
|
|
912
|
-
},
|
|
913
|
-
source: "browser",
|
|
914
|
-
};
|
|
915
|
-
}
|
|
916
|
-
|
|
917
|
-
export function parseChatRunBody(body: unknown): ChatRunParseResult {
|
|
918
|
-
const record = asRecord(body);
|
|
919
|
-
const prompt = String(record.prompt ?? "").trim();
|
|
920
|
-
if (!prompt) return { ok: false, error: "prompt is required" };
|
|
921
|
-
|
|
922
|
-
const rawImages = record.images;
|
|
923
|
-
const images: ChatRunImageInput[] = [];
|
|
924
|
-
if (rawImages !== undefined) {
|
|
925
|
-
if (!Array.isArray(rawImages)) return { ok: false, error: "images must be an array" };
|
|
926
|
-
if (rawImages.length > CHAT_RUN_MAX_IMAGE_COUNT) {
|
|
927
|
-
return { ok: false, error: "Attach up to 4 images" };
|
|
928
|
-
}
|
|
929
|
-
for (const rawImage of rawImages) {
|
|
930
|
-
const image = asRecord(rawImage);
|
|
931
|
-
const mimeType = String(image.mimeType ?? "");
|
|
932
|
-
const data = String(image.data ?? "");
|
|
933
|
-
if (!CHAT_RUN_IMAGE_MIME_TYPES.has(mimeType)) {
|
|
934
|
-
return { ok: false, error: "Unsupported image mime type" };
|
|
935
|
-
}
|
|
936
|
-
if (data.length > Math.ceil(CHAT_RUN_MAX_IMAGE_BYTES / 3) * 4) {
|
|
937
|
-
return { ok: false, error: "Image attachment must be 5 MB or smaller" };
|
|
938
|
-
}
|
|
939
|
-
const decoded = decodeStrictBase64(data);
|
|
940
|
-
if (!decoded) {
|
|
941
|
-
return { ok: false, error: "Image attachment data must be valid base64" };
|
|
942
|
-
}
|
|
943
|
-
if (decoded.byteLength > CHAT_RUN_MAX_IMAGE_BYTES) {
|
|
944
|
-
return { ok: false, error: "Image attachment must be 5 MB or smaller" };
|
|
945
|
-
}
|
|
946
|
-
images.push({ data, mimeType });
|
|
947
|
-
}
|
|
948
|
-
}
|
|
949
|
-
|
|
950
|
-
const rawAttachments = record.attachments;
|
|
951
|
-
const attachments: ChatRunAttachmentInput[] = [];
|
|
952
|
-
if (rawAttachments !== undefined) {
|
|
953
|
-
if (!Array.isArray(rawAttachments)) {
|
|
954
|
-
return { ok: false, error: "attachments must be an array" };
|
|
955
|
-
}
|
|
956
|
-
for (const rawAttachment of rawAttachments) {
|
|
957
|
-
const attachment = asRecord(rawAttachment);
|
|
958
|
-
const kind = String(attachment.kind ?? "");
|
|
959
|
-
const id = typeof attachment.id === "string" ? attachment.id.trim() : "";
|
|
960
|
-
if (kind === "portfolio") {
|
|
961
|
-
attachments.push(id ? { kind, id } : { kind });
|
|
962
|
-
} else if (kind === "watchlist" || kind === "report") {
|
|
963
|
-
if (!id) return { ok: false, error: `${kind} attachment id is required` };
|
|
964
|
-
attachments.push({ kind, id });
|
|
965
|
-
} else {
|
|
966
|
-
return { ok: false, error: "Unsupported attachment kind" };
|
|
967
|
-
}
|
|
968
|
-
}
|
|
969
|
-
}
|
|
970
|
-
|
|
971
|
-
if (prompt.startsWith("/") && (images.length > 0 || attachments.length > 0)) {
|
|
972
|
-
return { ok: false, error: "Attachments are not supported for slash commands" };
|
|
973
|
-
}
|
|
974
|
-
|
|
975
|
-
return { ok: true, value: { prompt, images, attachments } };
|
|
976
|
-
}
|
|
977
|
-
|
|
978
|
-
function decodeStrictBase64(data: string): Buffer | null {
|
|
979
|
-
if (!data || data.trim() !== data) return null;
|
|
980
|
-
if (data.length % 4 !== 0) return null;
|
|
981
|
-
if (/[^A-Za-z0-9+/=]/.test(data)) return null;
|
|
982
|
-
const firstPadding = data.indexOf("=");
|
|
983
|
-
if (firstPadding !== -1) {
|
|
984
|
-
const padding = data.slice(firstPadding);
|
|
985
|
-
if (!/^={1,2}$/.test(padding)) return null;
|
|
986
|
-
}
|
|
987
|
-
const decoded = Buffer.from(data, "base64");
|
|
988
|
-
if (decoded.byteLength === 0) return null;
|
|
989
|
-
return decoded.toString("base64") === data ? decoded : null;
|
|
990
|
-
}
|
|
991
|
-
|
|
992
|
-
export async function buildDispatchedPrompt(parsed: ParsedChatRunBody): Promise<string> {
|
|
993
|
-
if (parsed.prompt.startsWith("/")) return parsed.prompt;
|
|
994
|
-
if (parsed.attachments.length === 0) return parsed.prompt;
|
|
995
|
-
const db = initDefaultDatabase();
|
|
996
|
-
try {
|
|
997
|
-
const service = new MarketStateService(db);
|
|
998
|
-
const blocks = parsed.attachments.map((attachment) => {
|
|
999
|
-
const lines = attachmentSummaryLines(service, attachment);
|
|
1000
|
-
if (lines.length === 0) throw new Error(`${attachment.kind} attachment was empty`);
|
|
1001
|
-
return `[Attached by user — ${attachment.kind}]\n${lines.join("\n")}`;
|
|
1002
|
-
});
|
|
1003
|
-
return [parsed.prompt, ...blocks].join("\n\n");
|
|
1004
|
-
} finally {
|
|
1005
|
-
db.close();
|
|
1006
|
-
}
|
|
1007
|
-
}
|
|
1008
|
-
|
|
1009
|
-
function attachmentSummaryLines(
|
|
1010
|
-
service: MarketStateService,
|
|
1011
|
-
attachment: ChatRunAttachmentInput,
|
|
1012
|
-
): string[] {
|
|
1013
|
-
if (attachment.kind === "portfolio") {
|
|
1014
|
-
const portfolioId = attachment.id ? Number(attachment.id) : undefined;
|
|
1015
|
-
if (attachment.id && !Number.isFinite(portfolioId)) {
|
|
1016
|
-
throw new Error("Unknown portfolio attachment");
|
|
1017
|
-
}
|
|
1018
|
-
return formatPortfolioSummary(service.listPortfolioLots(portfolioId));
|
|
1019
|
-
}
|
|
1020
|
-
if (attachment.kind === "watchlist") {
|
|
1021
|
-
const watchlistId =
|
|
1022
|
-
attachment.id === "default" ? service.getDefaultWatchlist().id : Number(attachment.id);
|
|
1023
|
-
if (!Number.isFinite(watchlistId)) throw new Error("Unknown watchlist attachment");
|
|
1024
|
-
return formatWatchlistSummary(service.listWatchlistItems(watchlistId));
|
|
1025
|
-
}
|
|
1026
|
-
const reports = service.listReportRuns();
|
|
1027
|
-
const report =
|
|
1028
|
-
attachment.id === "latest"
|
|
1029
|
-
? reports[0]
|
|
1030
|
-
: reports.find((candidate) => candidate.id === Number(attachment.id));
|
|
1031
|
-
if (!report) throw new Error("Unknown report attachment");
|
|
1032
|
-
return formatLatestReportSummary(report);
|
|
1033
|
-
}
|
|
1034
|
-
|
|
1035
|
-
function attachmentLabel(attachment: ChatRunAttachmentInput): string {
|
|
1036
|
-
if (attachment.kind === "portfolio") return "Portfolio";
|
|
1037
|
-
if (attachment.kind === "watchlist") return "Watchlist";
|
|
1038
|
-
return "Latest report";
|
|
1039
|
-
}
|
|
1040
|
-
|
|
1041
|
-
function hasClientActionId(body: Record<string, unknown>): boolean {
|
|
1042
|
-
return typeof body.actionId === "string" && body.actionId.trim().length > 0;
|
|
1043
|
-
}
|
|
1044
|
-
|
|
1045
|
-
function requireSessionActionFields(
|
|
1046
|
-
res: ServerResponse,
|
|
1047
|
-
body: Record<string, unknown>,
|
|
1048
|
-
requireSessionId = true,
|
|
1049
|
-
): boolean {
|
|
1050
|
-
if (requireSessionId && !String(body.sessionId ?? "").trim()) {
|
|
1051
|
-
writeJson(res, { error: "sessionId is required" }, 400);
|
|
1052
|
-
return false;
|
|
1053
|
-
}
|
|
1054
|
-
if (!String(body.actionId ?? "").trim()) {
|
|
1055
|
-
writeJson(res, { error: "actionId is required" }, 400);
|
|
1056
|
-
return false;
|
|
1057
|
-
}
|
|
1058
|
-
return true;
|
|
1059
|
-
}
|
|
1060
|
-
|
|
1061
|
-
function shouldBlockFailedCoordinatorAction(
|
|
1062
|
-
runSessionManager: SessionManager,
|
|
1063
|
-
body: Record<string, unknown>,
|
|
1064
|
-
): boolean {
|
|
1065
|
-
return hasClientActionId(body) && shouldBlockFailedCoordinatorLockAction(runSessionManager);
|
|
1066
|
-
}
|
|
1067
|
-
|
|
1068
|
-
async function handleTrustedGuiMutation(
|
|
1069
|
-
req: IncomingMessage,
|
|
1070
|
-
res: ServerResponse,
|
|
1071
|
-
options: GuiHttpRouteOptions,
|
|
1072
|
-
action: (body: Record<string, unknown>) => Promise<void>,
|
|
1073
|
-
): Promise<void> {
|
|
1074
|
-
try {
|
|
1075
|
-
await action(asRecord(await readJsonBody(req)));
|
|
1076
|
-
writeJson(res, await options.wsHub.buildBootstrapPayload());
|
|
1077
|
-
} catch (error) {
|
|
1078
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
1079
|
-
const coordinationError = message === "Read-only follower mode";
|
|
1080
|
-
writeJson(
|
|
1081
|
-
res,
|
|
1082
|
-
{
|
|
1083
|
-
error: coordinationError ? "OpenCandle is reconnecting to this session." : message,
|
|
1084
|
-
...(coordinationError ? { code: "syncing" } : {}),
|
|
1085
|
-
},
|
|
1086
|
-
coordinationError ? 409 : 400,
|
|
1087
|
-
);
|
|
1088
|
-
}
|
|
1089
|
-
}
|
|
1090
|
-
|
|
1091
|
-
function serveStaticAsset(
|
|
1092
|
-
pathname: string,
|
|
1093
|
-
res: ServerResponse,
|
|
1094
|
-
options: GuiHttpRouteOptions,
|
|
1095
|
-
): void {
|
|
1096
|
-
const requested = pathname === "/" ? "/index.html" : pathname;
|
|
1097
|
-
const path = resolve(join(options.webDist, requested));
|
|
1098
|
-
if (!path.startsWith(options.webDist) || !existsSync(path)) {
|
|
1099
|
-
const fallback = resolve(join(options.webDist, "index.html"));
|
|
1100
|
-
if (!extname(requested) && fallback.startsWith(options.webDist) && existsSync(fallback)) {
|
|
1101
|
-
res.writeHead(200, privateGuiHeaders("text/html; charset=utf-8", options));
|
|
1102
|
-
createReadStream(fallback).pipe(res);
|
|
1103
|
-
return;
|
|
1104
|
-
}
|
|
1105
|
-
res.writeHead(404).end("Not found");
|
|
1106
|
-
return;
|
|
1107
|
-
}
|
|
1108
|
-
|
|
1109
|
-
const type = contentType(path);
|
|
1110
|
-
res.writeHead(200, privateGuiHeaders(type, options));
|
|
1111
|
-
createReadStream(path).pipe(res);
|
|
1112
|
-
}
|
|
1113
|
-
|
|
1114
|
-
function writeJson(res: ServerResponse, value: unknown, status = 200): void {
|
|
1115
|
-
res.writeHead(status, { "content-type": "application/json" });
|
|
1116
|
-
res.end(JSON.stringify(value));
|
|
1117
|
-
}
|
|
1118
|
-
|
|
1119
|
-
function allowTrustedGuiRequest(
|
|
1120
|
-
req: IncomingMessage,
|
|
1121
|
-
res: ServerResponse,
|
|
1122
|
-
label: string,
|
|
1123
|
-
options: GuiHttpRouteOptions,
|
|
1124
|
-
): boolean {
|
|
1125
|
-
if (
|
|
1126
|
-
isTrustedPrivateApiRequest(
|
|
1127
|
-
req.headers,
|
|
1128
|
-
options.privateApiSessionToken,
|
|
1129
|
-
req.socket.remoteAddress,
|
|
1130
|
-
{
|
|
1131
|
-
allowRemote: options.allowRemotePrivateApi,
|
|
1132
|
-
},
|
|
1133
|
-
)
|
|
1134
|
-
)
|
|
1135
|
-
return true;
|
|
1136
|
-
res.writeHead(403, { "content-type": "application/json" });
|
|
1137
|
-
res.end(
|
|
1138
|
-
JSON.stringify({
|
|
1139
|
-
error: `${label} is only available to trusted GUI browser sessions.`,
|
|
1140
|
-
}),
|
|
1141
|
-
);
|
|
1142
|
-
return false;
|
|
1143
|
-
}
|
|
1144
|
-
|
|
1145
|
-
function allowLocalCoordinatorRequest(
|
|
1146
|
-
req: IncomingMessage,
|
|
1147
|
-
res: ServerResponse,
|
|
1148
|
-
options: GuiHttpRouteOptions,
|
|
1149
|
-
): boolean {
|
|
1150
|
-
if (req.headers["x-opencandle-coordinator-secret"] === options.localCoordinatorSecret) {
|
|
1151
|
-
return true;
|
|
1152
|
-
}
|
|
1153
|
-
res.writeHead(403, { "content-type": "application/json" });
|
|
1154
|
-
res.end(JSON.stringify({ error: "Local coordinator request was not authorized." }));
|
|
1155
|
-
return false;
|
|
1156
|
-
}
|
|
1157
|
-
|
|
1158
|
-
function privateGuiHeaders(
|
|
1159
|
-
contentTypeValue: string,
|
|
1160
|
-
options: GuiHttpRouteOptions,
|
|
1161
|
-
): Record<string, string> {
|
|
1162
|
-
const headers: Record<string, string> = { "content-type": contentTypeValue };
|
|
1163
|
-
if (contentTypeValue.startsWith("text/html")) {
|
|
1164
|
-
headers["set-cookie"] = privateApiCookieHeader(options.privateApiSessionToken);
|
|
1165
|
-
}
|
|
1166
|
-
return headers;
|
|
1167
|
-
}
|
|
1168
|
-
|
|
1169
|
-
function writeSse(res: ServerResponse, event: ChatEvent): void {
|
|
1170
|
-
res.write(`data: ${JSON.stringify(event)}\n\n`);
|
|
1171
|
-
}
|
|
1172
|
-
|
|
1173
|
-
async function readJsonBody(req: IncomingMessage): Promise<unknown> {
|
|
1174
|
-
const chunks: Buffer[] = [];
|
|
1175
|
-
for await (const chunk of req) {
|
|
1176
|
-
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
|
1177
|
-
}
|
|
1178
|
-
if (chunks.length === 0) return {};
|
|
1179
|
-
return JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
1180
|
-
}
|
|
1181
|
-
|
|
1182
|
-
function contentType(path: string): string {
|
|
1183
|
-
switch (extname(path)) {
|
|
1184
|
-
case ".html":
|
|
1185
|
-
return "text/html; charset=utf-8";
|
|
1186
|
-
case ".css":
|
|
1187
|
-
return "text/css; charset=utf-8";
|
|
1188
|
-
case ".js":
|
|
1189
|
-
return "text/javascript; charset=utf-8";
|
|
1190
|
-
case ".svg":
|
|
1191
|
-
return "image/svg+xml";
|
|
1192
|
-
default:
|
|
1193
|
-
return "application/octet-stream";
|
|
1194
|
-
}
|
|
1195
|
-
}
|
|
1196
|
-
|
|
1197
|
-
function asRecord(value: unknown): Record<string, unknown> {
|
|
1198
|
-
return typeof value === "object" && value !== null && !Array.isArray(value)
|
|
1199
|
-
? (value as Record<string, unknown>)
|
|
1200
|
-
: {};
|
|
1201
|
-
}
|