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