@gokulvenkatareddy/cortex 0.1.7
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 +1295 -0
- package/apps/octogent/.github/workflows/ci.yml +40 -0
- package/apps/octogent/.shims/claude +4 -0
- package/apps/octogent/AGENTS.md +71 -0
- package/apps/octogent/CONTRIBUTING.md +72 -0
- package/apps/octogent/LICENSE +21 -0
- package/apps/octogent/README.md +184 -0
- package/apps/octogent/apps/api/AGENTS.md +32 -0
- package/apps/octogent/apps/api/package.json +19 -0
- package/apps/octogent/apps/api/src/agentStateDetection.ts +181 -0
- package/apps/octogent/apps/api/src/claudeSessionScanner.ts +235 -0
- package/apps/octogent/apps/api/src/claudeSkills.ts +182 -0
- package/apps/octogent/apps/api/src/claudeUsage.ts +922 -0
- package/apps/octogent/apps/api/src/cli.ts +595 -0
- package/apps/octogent/apps/api/src/codeIntelStore.ts +46 -0
- package/apps/octogent/apps/api/src/codexUsage.ts +278 -0
- package/apps/octogent/apps/api/src/createApiServer/codeIntelRoutes.ts +60 -0
- package/apps/octogent/apps/api/src/createApiServer/conversationRoutes.ts +128 -0
- package/apps/octogent/apps/api/src/createApiServer/deckRoutes.ts +873 -0
- package/apps/octogent/apps/api/src/createApiServer/gitParsers.ts +140 -0
- package/apps/octogent/apps/api/src/createApiServer/gitRoutes.ts +214 -0
- package/apps/octogent/apps/api/src/createApiServer/miscRoutes.ts +316 -0
- package/apps/octogent/apps/api/src/createApiServer/monitorParsers.ts +137 -0
- package/apps/octogent/apps/api/src/createApiServer/monitorRoutes.ts +95 -0
- package/apps/octogent/apps/api/src/createApiServer/requestHandler.ts +311 -0
- package/apps/octogent/apps/api/src/createApiServer/requestParsers.ts +25 -0
- package/apps/octogent/apps/api/src/createApiServer/routeHelpers.ts +97 -0
- package/apps/octogent/apps/api/src/createApiServer/security.ts +70 -0
- package/apps/octogent/apps/api/src/createApiServer/terminalParsers.ts +167 -0
- package/apps/octogent/apps/api/src/createApiServer/terminalRoutes.ts +315 -0
- package/apps/octogent/apps/api/src/createApiServer/types.ts +24 -0
- package/apps/octogent/apps/api/src/createApiServer/uiStateParsers.ts +255 -0
- package/apps/octogent/apps/api/src/createApiServer/upgradeHandler.ts +38 -0
- package/apps/octogent/apps/api/src/createApiServer/usageRoutes.ts +84 -0
- package/apps/octogent/apps/api/src/createApiServer.ts +176 -0
- package/apps/octogent/apps/api/src/deck/readDeckTentacles.ts +595 -0
- package/apps/octogent/apps/api/src/githubRepoSummary.ts +397 -0
- package/apps/octogent/apps/api/src/logging.ts +9 -0
- package/apps/octogent/apps/api/src/monitor/defaults.ts +3 -0
- package/apps/octogent/apps/api/src/monitor/index.ts +8 -0
- package/apps/octogent/apps/api/src/monitor/repository.ts +303 -0
- package/apps/octogent/apps/api/src/monitor/service.ts +349 -0
- package/apps/octogent/apps/api/src/monitor/types.ts +120 -0
- package/apps/octogent/apps/api/src/monitor/xProvider.ts +587 -0
- package/apps/octogent/apps/api/src/projectPersistence.ts +377 -0
- package/apps/octogent/apps/api/src/prompts/index.ts +10 -0
- package/apps/octogent/apps/api/src/prompts/promptResolver.ts +145 -0
- package/apps/octogent/apps/api/src/runtimeMetadata.ts +69 -0
- package/apps/octogent/apps/api/src/server.ts +80 -0
- package/apps/octogent/apps/api/src/setupState.ts +80 -0
- package/apps/octogent/apps/api/src/setupStatus.ts +174 -0
- package/apps/octogent/apps/api/src/startupPrerequisites.ts +146 -0
- package/apps/octogent/apps/api/src/terminalRuntime/channelMessaging.ts +87 -0
- package/apps/octogent/apps/api/src/terminalRuntime/claudeTranscript.ts +279 -0
- package/apps/octogent/apps/api/src/terminalRuntime/constants.ts +15 -0
- package/apps/octogent/apps/api/src/terminalRuntime/conversations.ts +492 -0
- package/apps/octogent/apps/api/src/terminalRuntime/gitOperations.ts +341 -0
- package/apps/octogent/apps/api/src/terminalRuntime/hookProcessor.ts +405 -0
- package/apps/octogent/apps/api/src/terminalRuntime/protocol.ts +46 -0
- package/apps/octogent/apps/api/src/terminalRuntime/ptyEnvironment.ts +50 -0
- package/apps/octogent/apps/api/src/terminalRuntime/registry.ts +423 -0
- package/apps/octogent/apps/api/src/terminalRuntime/sessionRuntime.ts +671 -0
- package/apps/octogent/apps/api/src/terminalRuntime/systemClients.ts +432 -0
- package/apps/octogent/apps/api/src/terminalRuntime/types.ts +157 -0
- package/apps/octogent/apps/api/src/terminalRuntime/worktreeManager.ts +135 -0
- package/apps/octogent/apps/api/src/terminalRuntime.ts +567 -0
- package/apps/octogent/apps/api/src/usageUtils.ts +16 -0
- package/apps/octogent/apps/api/src/ws-shim.d.ts +28 -0
- package/apps/octogent/apps/api/tests/agentStateDetection.test.ts +67 -0
- package/apps/octogent/apps/api/tests/claudeUsage.test.ts +583 -0
- package/apps/octogent/apps/api/tests/codexUsage.test.ts +107 -0
- package/apps/octogent/apps/api/tests/createApiServer.test.ts +3207 -0
- package/apps/octogent/apps/api/tests/githubRepoSummary.test.ts +100 -0
- package/apps/octogent/apps/api/tests/logging.test.ts +33 -0
- package/apps/octogent/apps/api/tests/monitorApi.test.ts +467 -0
- package/apps/octogent/apps/api/tests/monitorCore.test.ts +104 -0
- package/apps/octogent/apps/api/tests/promptResolver.test.ts +109 -0
- package/apps/octogent/apps/api/tests/protocol.test.ts +14 -0
- package/apps/octogent/apps/api/tests/sessionRuntime.test.ts +608 -0
- package/apps/octogent/apps/api/tests/startupPrerequisites.test.ts +70 -0
- package/apps/octogent/apps/api/tests/upgradeHandler.test.ts +40 -0
- package/apps/octogent/apps/api/tests/xMonitorProvider.test.ts +109 -0
- package/apps/octogent/apps/api/tsconfig.json +7 -0
- package/apps/octogent/apps/api/vitest.config.ts +7 -0
- package/apps/octogent/apps/web/AGENTS.md +38 -0
- package/apps/octogent/apps/web/index.html +13 -0
- package/apps/octogent/apps/web/package.json +32 -0
- package/apps/octogent/apps/web/public/octopus-favicon.svg +26 -0
- package/apps/octogent/apps/web/src/App.tsx +646 -0
- package/apps/octogent/apps/web/src/app/canvas/types.ts +34 -0
- package/apps/octogent/apps/web/src/app/codeIntelAggregation.ts +278 -0
- package/apps/octogent/apps/web/src/app/constants.ts +28 -0
- package/apps/octogent/apps/web/src/app/conversationNormalizers.ts +135 -0
- package/apps/octogent/apps/web/src/app/formatTimestamp.ts +18 -0
- package/apps/octogent/apps/web/src/app/githubMetrics.ts +76 -0
- package/apps/octogent/apps/web/src/app/githubNormalizers.ts +91 -0
- package/apps/octogent/apps/web/src/app/hooks/useAgentRuntimeStates.ts +18 -0
- package/apps/octogent/apps/web/src/app/hooks/useBackendLivenessPolling.ts +53 -0
- package/apps/octogent/apps/web/src/app/hooks/useCanvasGraphData.ts +449 -0
- package/apps/octogent/apps/web/src/app/hooks/useCanvasTransform.ts +260 -0
- package/apps/octogent/apps/web/src/app/hooks/useClaudeUsagePolling.ts +40 -0
- package/apps/octogent/apps/web/src/app/hooks/useClickOutside.ts +30 -0
- package/apps/octogent/apps/web/src/app/hooks/useCodeIntelRuntime.ts +83 -0
- package/apps/octogent/apps/web/src/app/hooks/useCodexUsagePolling.ts +35 -0
- package/apps/octogent/apps/web/src/app/hooks/useConsoleKeyboardShortcuts.ts +31 -0
- package/apps/octogent/apps/web/src/app/hooks/useConversationsRuntime.ts +377 -0
- package/apps/octogent/apps/web/src/app/hooks/useForceSimulation.ts +319 -0
- package/apps/octogent/apps/web/src/app/hooks/useGitHubPrimaryViewModel.ts +143 -0
- package/apps/octogent/apps/web/src/app/hooks/useGithubSummaryPolling.ts +28 -0
- package/apps/octogent/apps/web/src/app/hooks/useInitialColumnsHydration.ts +64 -0
- package/apps/octogent/apps/web/src/app/hooks/useMonitorRuntime.ts +220 -0
- package/apps/octogent/apps/web/src/app/hooks/usePersistedUiState.ts +536 -0
- package/apps/octogent/apps/web/src/app/hooks/usePollingData.ts +79 -0
- package/apps/octogent/apps/web/src/app/hooks/usePromptLibrary.ts +185 -0
- package/apps/octogent/apps/web/src/app/hooks/useTentacleGitLifecycle.ts +530 -0
- package/apps/octogent/apps/web/src/app/hooks/useTerminalCompletionNotification.ts +94 -0
- package/apps/octogent/apps/web/src/app/hooks/useTerminalMutations.ts +266 -0
- package/apps/octogent/apps/web/src/app/hooks/useTerminalStateReconciliation.ts +23 -0
- package/apps/octogent/apps/web/src/app/hooks/useUsageHeatmapPolling.ts +43 -0
- package/apps/octogent/apps/web/src/app/hooks/useWorkspaceSetup.ts +80 -0
- package/apps/octogent/apps/web/src/app/hotkeys.ts +31 -0
- package/apps/octogent/apps/web/src/app/monitorNormalizers.ts +145 -0
- package/apps/octogent/apps/web/src/app/notificationSounds.ts +164 -0
- package/apps/octogent/apps/web/src/app/terminalRuntimeStateStore.ts +261 -0
- package/apps/octogent/apps/web/src/app/terminalState.ts +21 -0
- package/apps/octogent/apps/web/src/app/types.ts +42 -0
- package/apps/octogent/apps/web/src/app/uiStateNormalizers.ts +113 -0
- package/apps/octogent/apps/web/src/app/usageNormalizers.ts +58 -0
- package/apps/octogent/apps/web/src/components/ActiveAgentsSidebar.tsx +60 -0
- package/apps/octogent/apps/web/src/components/ActivityPrimaryView.tsx +21 -0
- package/apps/octogent/apps/web/src/components/AgentStateBadge.tsx +47 -0
- package/apps/octogent/apps/web/src/components/CanvasPrimaryView.tsx +1532 -0
- package/apps/octogent/apps/web/src/components/ClearAllConversationsDialog.tsx +33 -0
- package/apps/octogent/apps/web/src/components/CodeIntelArcDiagram.tsx +245 -0
- package/apps/octogent/apps/web/src/components/CodeIntelPrimaryView.tsx +104 -0
- package/apps/octogent/apps/web/src/components/CodeIntelTreemap.tsx +138 -0
- package/apps/octogent/apps/web/src/components/ConsolePrimaryNav.tsx +31 -0
- package/apps/octogent/apps/web/src/components/ConversationsPrimaryView.tsx +243 -0
- package/apps/octogent/apps/web/src/components/DeckPrimaryView.tsx +613 -0
- package/apps/octogent/apps/web/src/components/DeleteTentacleDialog.tsx +91 -0
- package/apps/octogent/apps/web/src/components/EmptyOctopus.tsx +715 -0
- package/apps/octogent/apps/web/src/components/GitHubPrimaryView.tsx +494 -0
- package/apps/octogent/apps/web/src/components/MonitorPrimaryView.tsx +475 -0
- package/apps/octogent/apps/web/src/components/PrimaryViewRouter.tsx +99 -0
- package/apps/octogent/apps/web/src/components/PromptsPrimaryView.tsx +243 -0
- package/apps/octogent/apps/web/src/components/RuntimeStatusStrip.tsx +273 -0
- package/apps/octogent/apps/web/src/components/SettingsPrimaryView.tsx +92 -0
- package/apps/octogent/apps/web/src/components/SidebarActionPanel.tsx +124 -0
- package/apps/octogent/apps/web/src/components/SidebarConversationsList.tsx +279 -0
- package/apps/octogent/apps/web/src/components/SidebarPromptsList.tsx +116 -0
- package/apps/octogent/apps/web/src/components/TelemetryTape.tsx +106 -0
- package/apps/octogent/apps/web/src/components/TentacleGitActionsDialog.tsx +341 -0
- package/apps/octogent/apps/web/src/components/Terminal.tsx +524 -0
- package/apps/octogent/apps/web/src/components/TerminalPromptPicker.tsx +140 -0
- package/apps/octogent/apps/web/src/components/UsageHeatmap.tsx +702 -0
- package/apps/octogent/apps/web/src/components/canvas/CanvasTentaclePanel.tsx +485 -0
- package/apps/octogent/apps/web/src/components/canvas/CanvasTerminalColumn.tsx +89 -0
- package/apps/octogent/apps/web/src/components/canvas/DeleteAllTerminalsDialog.tsx +221 -0
- package/apps/octogent/apps/web/src/components/canvas/OctopusNode.tsx +307 -0
- package/apps/octogent/apps/web/src/components/canvas/SessionNode.tsx +185 -0
- package/apps/octogent/apps/web/src/components/deck/ActionCards.tsx +118 -0
- package/apps/octogent/apps/web/src/components/deck/AddTentacleForm.tsx +269 -0
- package/apps/octogent/apps/web/src/components/deck/DeckBottomActions.tsx +56 -0
- package/apps/octogent/apps/web/src/components/deck/TentaclePod.tsx +334 -0
- package/apps/octogent/apps/web/src/components/deck/WorkspaceSetupCard.tsx +105 -0
- package/apps/octogent/apps/web/src/components/deck/octopusVisuals.ts +72 -0
- package/apps/octogent/apps/web/src/components/terminalReplay.ts +62 -0
- package/apps/octogent/apps/web/src/components/terminalWheel.ts +54 -0
- package/apps/octogent/apps/web/src/components/ui/ActionButton.tsx +34 -0
- package/apps/octogent/apps/web/src/components/ui/ConfirmationDialog.tsx +86 -0
- package/apps/octogent/apps/web/src/components/ui/MarkdownContent.tsx +43 -0
- package/apps/octogent/apps/web/src/components/ui/SettingsToggle.tsx +34 -0
- package/apps/octogent/apps/web/src/components/ui/StatusBadge.tsx +24 -0
- package/apps/octogent/apps/web/src/main.tsx +17 -0
- package/apps/octogent/apps/web/src/runtime/HttpTerminalSnapshotReader.ts +87 -0
- package/apps/octogent/apps/web/src/runtime/runtimeEndpoints.ts +412 -0
- package/apps/octogent/apps/web/src/styles/chrome-and-buttons.css +272 -0
- package/apps/octogent/apps/web/src/styles/console-canvas-activity.css +358 -0
- package/apps/octogent/apps/web/src/styles/console-canvas-canvas.css +1843 -0
- package/apps/octogent/apps/web/src/styles/console-canvas-code-intel.css +227 -0
- package/apps/octogent/apps/web/src/styles/console-canvas-conversations.css +705 -0
- package/apps/octogent/apps/web/src/styles/console-canvas-deck.css +1524 -0
- package/apps/octogent/apps/web/src/styles/console-canvas-github.css +541 -0
- package/apps/octogent/apps/web/src/styles/console-canvas-monitor.css +595 -0
- package/apps/octogent/apps/web/src/styles/console-canvas-pixpack.css +81 -0
- package/apps/octogent/apps/web/src/styles/console-canvas-prompts.css +474 -0
- package/apps/octogent/apps/web/src/styles/console-canvas-settings.css +207 -0
- package/apps/octogent/apps/web/src/styles/console-chrome-status-nav.css +441 -0
- package/apps/octogent/apps/web/src/styles/console-overrides-telemetry.css +320 -0
- package/apps/octogent/apps/web/src/styles/console-theme-tokens.css +25 -0
- package/apps/octogent/apps/web/src/styles/cortex-theme.css +412 -0
- package/apps/octogent/apps/web/src/styles/foundation.css +100 -0
- package/apps/octogent/apps/web/src/styles/sidebar-and-scrollbars.css +447 -0
- package/apps/octogent/apps/web/src/styles/terminal-and-status.css +356 -0
- package/apps/octogent/apps/web/src/styles.css +25 -0
- package/apps/octogent/apps/web/src/types/ws.d.ts +23 -0
- package/apps/octogent/apps/web/tests/CanvasPrimaryView.test.tsx +347 -0
- package/apps/octogent/apps/web/tests/HttpTerminalSnapshotReader.test.tsx +54 -0
- package/apps/octogent/apps/web/tests/RuntimeStatusStrip.test.tsx +70 -0
- package/apps/octogent/apps/web/tests/Terminal.test.tsx +87 -0
- package/apps/octogent/apps/web/tests/add-tentacle-form.test.tsx +48 -0
- package/apps/octogent/apps/web/tests/app-github-runtime.test.tsx +162 -0
- package/apps/octogent/apps/web/tests/app-monitor-runtime.test.tsx +657 -0
- package/apps/octogent/apps/web/tests/app-shell-navigation.test.tsx +109 -0
- package/apps/octogent/apps/web/tests/app-swarm-refresh.test.tsx +268 -0
- package/apps/octogent/apps/web/tests/app-ui-state-persistence.test.tsx +116 -0
- package/apps/octogent/apps/web/tests/app-workspace-setup.test.tsx +217 -0
- package/apps/octogent/apps/web/tests/canvas-tentacle-panel.test.tsx +195 -0
- package/apps/octogent/apps/web/tests/delete-all-terminals-dialog.test.tsx +76 -0
- package/apps/octogent/apps/web/tests/githubMetrics.test.tsx +52 -0
- package/apps/octogent/apps/web/tests/hotkeys.test.tsx +44 -0
- package/apps/octogent/apps/web/tests/runtimeEndpoints.test.tsx +240 -0
- package/apps/octogent/apps/web/tests/setup.ts +39 -0
- package/apps/octogent/apps/web/tests/tentacle-pod.test.tsx +62 -0
- package/apps/octogent/apps/web/tests/terminalReplay.test.ts +71 -0
- package/apps/octogent/apps/web/tests/terminalState.test.tsx +49 -0
- package/apps/octogent/apps/web/tests/terminalWheel.test.tsx +51 -0
- package/apps/octogent/apps/web/tests/test-utils/appTestHarness.ts +48 -0
- package/apps/octogent/apps/web/tests/uiPrimitives.test.tsx +31 -0
- package/apps/octogent/apps/web/tests/useAgentRuntimeStates.test.tsx +47 -0
- package/apps/octogent/apps/web/tsconfig.json +8 -0
- package/apps/octogent/apps/web/vite.api.bundle.config.mts +32 -0
- package/apps/octogent/apps/web/vite.config.ts +22 -0
- package/apps/octogent/bin/octogent +3 -0
- package/apps/octogent/biome.json +21 -0
- package/apps/octogent/docs/concepts/mental-model.md +79 -0
- package/apps/octogent/docs/concepts/runtime-and-api.md +60 -0
- package/apps/octogent/docs/concepts/tentacles.md +85 -0
- package/apps/octogent/docs/getting-started/installation.md +54 -0
- package/apps/octogent/docs/getting-started/quickstart.md +79 -0
- package/apps/octogent/docs/guides/inter-agent-messaging.md +43 -0
- package/apps/octogent/docs/guides/orchestrating-child-agents.md +49 -0
- package/apps/octogent/docs/guides/working-with-todos.md +56 -0
- package/apps/octogent/docs/index.md +40 -0
- package/apps/octogent/docs/reference/api.md +103 -0
- package/apps/octogent/docs/reference/cli.md +71 -0
- package/apps/octogent/docs/reference/experimental-features.md +28 -0
- package/apps/octogent/docs/reference/filesystem-layout.md +62 -0
- package/apps/octogent/docs/reference/troubleshooting.md +49 -0
- package/apps/octogent/package.json +35 -0
- package/apps/octogent/packages/core/AGENTS.md +31 -0
- package/apps/octogent/packages/core/package.json +12 -0
- package/apps/octogent/packages/core/src/adapters/InMemoryTerminalSnapshotReader.ts +10 -0
- package/apps/octogent/packages/core/src/application/buildTerminalList.ts +13 -0
- package/apps/octogent/packages/core/src/domain/agentRuntime.ts +18 -0
- package/apps/octogent/packages/core/src/domain/channel.ts +8 -0
- package/apps/octogent/packages/core/src/domain/completionSound.ts +14 -0
- package/apps/octogent/packages/core/src/domain/conversation.ts +48 -0
- package/apps/octogent/packages/core/src/domain/deck.ts +33 -0
- package/apps/octogent/packages/core/src/domain/git.ts +32 -0
- package/apps/octogent/packages/core/src/domain/monitor.ts +62 -0
- package/apps/octogent/packages/core/src/domain/setup.ts +27 -0
- package/apps/octogent/packages/core/src/domain/terminal.ts +17 -0
- package/apps/octogent/packages/core/src/domain/uiState.ts +22 -0
- package/apps/octogent/packages/core/src/domain/usage.ts +60 -0
- package/apps/octogent/packages/core/src/index.ts +15 -0
- package/apps/octogent/packages/core/src/ports/TerminalSnapshotReader.ts +5 -0
- package/apps/octogent/packages/core/src/util/typeCoercion.ts +20 -0
- package/apps/octogent/packages/core/tests/buildTerminalList.test.ts +75 -0
- package/apps/octogent/packages/core/tsconfig.json +7 -0
- package/apps/octogent/packages/core/tsconfig.tsbuildinfo +1 -0
- package/apps/octogent/packages/core/vitest.config.ts +7 -0
- package/apps/octogent/pnpm-lock.yaml +3212 -0
- package/apps/octogent/pnpm-workspace.yaml +3 -0
- package/apps/octogent/prompts/meta-prompt-generator.md +223 -0
- package/apps/octogent/prompts/octoboss-clean-contexts.md +30 -0
- package/apps/octogent/prompts/octoboss-reorganize-tentacles.md +29 -0
- package/apps/octogent/prompts/octoboss-reorganize-todos.md +27 -0
- package/apps/octogent/prompts/sandbox-init.md +3 -0
- package/apps/octogent/prompts/swarm-parent.md +83 -0
- package/apps/octogent/prompts/swarm-worker.md +50 -0
- package/apps/octogent/prompts/tentacle-context-init.md +1 -0
- package/apps/octogent/prompts/tentacle-planner.md +110 -0
- package/apps/octogent/prompts/tentacle-reorganize-todos.md +20 -0
- package/apps/octogent/prompts/tentacle-update-tentacle.md +18 -0
- package/apps/octogent/scripts/build-package.mjs +23 -0
- package/apps/octogent/scripts/dev.mjs +158 -0
- package/apps/octogent/scripts/smoke-public-install.mjs +271 -0
- package/apps/octogent/static/images/octogent-header.png +0 -0
- package/apps/octogent/static/images/preview_1.jpg +0 -0
- package/apps/octogent/static/images/preview_2.jpg +0 -0
- package/apps/octogent/static/images/preview_3.jpg +0 -0
- package/apps/octogent/static/images/preview_4.jpg +0 -0
- package/apps/octogent/static/images/preview_5.jpg +0 -0
- package/apps/octogent/static/images/preview_6.jpg +0 -0
- package/apps/octogent/tsconfig.base.json +16 -0
- package/bin/AGI +3 -0
- package/bin/AGI-install-app +71 -0
- package/bin/AGI-ui +16 -0
- package/bin/AGI-voice +15 -0
- package/bin/AGI-web +16 -0
- package/bin/cortex +109 -0
- package/bin/cortex-octogent +99 -0
- package/bin/import-specifier.mjs +13 -0
- package/bin/import-specifier.test.mjs +13 -0
- package/bin/octo +150 -0
- package/dist/cli.mjs +555650 -0
- package/package.json +157 -0
- package/scripts/setup-wizard.ts +390 -0
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
MonitorCredentialSummary,
|
|
3
|
+
MonitorFeedSnapshot,
|
|
4
|
+
MonitorPost,
|
|
5
|
+
MonitorUsageSnapshot,
|
|
6
|
+
} from "@octogent/core";
|
|
7
|
+
|
|
8
|
+
export type {
|
|
9
|
+
MonitorCredentialSummary,
|
|
10
|
+
MonitorFeedSnapshot,
|
|
11
|
+
MonitorPost,
|
|
12
|
+
MonitorUsageSnapshot,
|
|
13
|
+
} from "@octogent/core";
|
|
14
|
+
|
|
15
|
+
export type MonitorProviderId = "x";
|
|
16
|
+
|
|
17
|
+
export type XMonitorCredentials = {
|
|
18
|
+
bearerToken: string;
|
|
19
|
+
apiKey: string | null;
|
|
20
|
+
apiSecret: string | null;
|
|
21
|
+
accessToken: string | null;
|
|
22
|
+
accessTokenSecret: string | null;
|
|
23
|
+
updatedAt: string;
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
export type MonitorSearchWindowDays = 1 | 3 | 7;
|
|
27
|
+
|
|
28
|
+
export type MonitorRefreshPolicy = {
|
|
29
|
+
maxCacheAgeMs: number;
|
|
30
|
+
maxPosts: number;
|
|
31
|
+
searchWindowDays: MonitorSearchWindowDays;
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
export type PersistedMonitorConfig = {
|
|
35
|
+
version: 1;
|
|
36
|
+
providerId: MonitorProviderId;
|
|
37
|
+
queryTerms: string[];
|
|
38
|
+
refreshPolicy: MonitorRefreshPolicy;
|
|
39
|
+
providers: {
|
|
40
|
+
x: {
|
|
41
|
+
credentials: XMonitorCredentials | null;
|
|
42
|
+
};
|
|
43
|
+
};
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
export type PersistedMonitorCache = {
|
|
47
|
+
version: 1;
|
|
48
|
+
providerId: MonitorProviderId;
|
|
49
|
+
queryTerms: string[];
|
|
50
|
+
fetchedAt: string | null;
|
|
51
|
+
lastError: string | null;
|
|
52
|
+
posts: MonitorPost[];
|
|
53
|
+
usage: MonitorUsageSnapshot | null;
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
export type SanitizedMonitorConfig = {
|
|
57
|
+
providerId: MonitorProviderId;
|
|
58
|
+
queryTerms: string[];
|
|
59
|
+
refreshPolicy: MonitorRefreshPolicy;
|
|
60
|
+
providers: {
|
|
61
|
+
x: {
|
|
62
|
+
credentials: MonitorCredentialSummary;
|
|
63
|
+
};
|
|
64
|
+
};
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
export type MonitorConfigPatchInput = {
|
|
68
|
+
providerId?: MonitorProviderId;
|
|
69
|
+
queryTerms?: string[];
|
|
70
|
+
refreshPolicy?: {
|
|
71
|
+
maxCacheAgeMs?: number;
|
|
72
|
+
maxPosts?: number;
|
|
73
|
+
searchWindowDays?: MonitorSearchWindowDays;
|
|
74
|
+
};
|
|
75
|
+
credentials?: unknown;
|
|
76
|
+
validateCredentials?: boolean;
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
export type MonitorReadFeedOptions = {
|
|
80
|
+
forceRefresh?: boolean;
|
|
81
|
+
refreshIfStale?: boolean;
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
export type MonitorCredentialsSaveResult = {
|
|
85
|
+
credentials: unknown;
|
|
86
|
+
summary: MonitorCredentialSummary;
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
export type MonitorProviderValidationResult = {
|
|
90
|
+
ok: boolean;
|
|
91
|
+
error?: string;
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
export type MonitorProviderAdapter = {
|
|
95
|
+
providerId: MonitorProviderId;
|
|
96
|
+
saveCredentials: (input: unknown, now: Date) => MonitorCredentialsSaveResult;
|
|
97
|
+
summarizeCredentials: (credentials: unknown) => MonitorCredentialSummary;
|
|
98
|
+
validateCredentials: (credentials: unknown) => Promise<MonitorProviderValidationResult>;
|
|
99
|
+
fetchRecentPosts: (args: {
|
|
100
|
+
credentials: unknown;
|
|
101
|
+
queryTerms: string[];
|
|
102
|
+
postLimit: number;
|
|
103
|
+
searchWindowDays: MonitorSearchWindowDays;
|
|
104
|
+
now: Date;
|
|
105
|
+
}) => Promise<MonitorPost[]>;
|
|
106
|
+
fetchUsage: (args: { credentials: unknown; now: Date }) => Promise<MonitorUsageSnapshot>;
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
export type MonitorRepository = {
|
|
110
|
+
readConfig: () => PersistedMonitorConfig;
|
|
111
|
+
writeConfig: (config: PersistedMonitorConfig) => void;
|
|
112
|
+
readCache: () => PersistedMonitorCache;
|
|
113
|
+
writeCache: (cache: PersistedMonitorCache) => void;
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
export type MonitorService = {
|
|
117
|
+
readConfig: () => Promise<SanitizedMonitorConfig>;
|
|
118
|
+
patchConfig: (patch: MonitorConfigPatchInput) => Promise<SanitizedMonitorConfig>;
|
|
119
|
+
readFeed: (options?: MonitorReadFeedOptions) => Promise<MonitorFeedSnapshot>;
|
|
120
|
+
};
|
|
@@ -0,0 +1,587 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
MonitorCredentialSummary,
|
|
3
|
+
MonitorCredentialsSaveResult,
|
|
4
|
+
MonitorPost,
|
|
5
|
+
MonitorProviderAdapter,
|
|
6
|
+
MonitorProviderValidationResult,
|
|
7
|
+
MonitorSearchWindowDays,
|
|
8
|
+
MonitorUsageSnapshot,
|
|
9
|
+
XMonitorCredentials,
|
|
10
|
+
} from "./types";
|
|
11
|
+
|
|
12
|
+
const DEFAULT_X_API_BASE_URL = "https://api.x.com";
|
|
13
|
+
const DEFAULT_X_USAGE_ENDPOINT_PATH = "/2/usage/tweets";
|
|
14
|
+
const VALIDATION_QUERY = "lang:en -is:retweet";
|
|
15
|
+
const MAX_RECENT_SEARCH_PAGES_PER_TERM = 5;
|
|
16
|
+
|
|
17
|
+
const asRecord = (value: unknown): Record<string, unknown> | null =>
|
|
18
|
+
value !== null && typeof value === "object" && !Array.isArray(value)
|
|
19
|
+
? (value as Record<string, unknown>)
|
|
20
|
+
: null;
|
|
21
|
+
|
|
22
|
+
const asString = (value: unknown): string | null => (typeof value === "string" ? value : null);
|
|
23
|
+
|
|
24
|
+
const asNumber = (value: unknown): number | null => {
|
|
25
|
+
if (typeof value === "number" && Number.isFinite(value)) {
|
|
26
|
+
return value;
|
|
27
|
+
}
|
|
28
|
+
if (typeof value === "string") {
|
|
29
|
+
const parsed = Number.parseFloat(value);
|
|
30
|
+
return Number.isFinite(parsed) ? parsed : null;
|
|
31
|
+
}
|
|
32
|
+
return null;
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
const normalizeOptionalSecret = (value: unknown): string | null => {
|
|
36
|
+
if (typeof value !== "string") {
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const trimmed = value.trim();
|
|
41
|
+
return trimmed.length > 0 ? trimmed : null;
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
const maskSecret = (value: string | null): string | null => {
|
|
45
|
+
if (!value || value.length === 0) {
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
if (value.length <= 4) {
|
|
50
|
+
return "*".repeat(value.length);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
return `${"*".repeat(value.length - 4)}${value.slice(-4)}`;
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
const toXCredentials = (value: unknown): XMonitorCredentials | null => {
|
|
57
|
+
const record = asRecord(value);
|
|
58
|
+
if (!record) {
|
|
59
|
+
return null;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const bearerToken = asString(record.bearerToken)?.trim();
|
|
63
|
+
if (!bearerToken) {
|
|
64
|
+
return null;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
return {
|
|
68
|
+
bearerToken,
|
|
69
|
+
apiKey: normalizeOptionalSecret(record.apiKey),
|
|
70
|
+
apiSecret: normalizeOptionalSecret(record.apiSecret),
|
|
71
|
+
accessToken: normalizeOptionalSecret(record.accessToken),
|
|
72
|
+
accessTokenSecret: normalizeOptionalSecret(record.accessTokenSecret),
|
|
73
|
+
updatedAt: asString(record.updatedAt) ?? new Date().toISOString(),
|
|
74
|
+
};
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
const summarizeXCredentials = (credentials: unknown): MonitorCredentialSummary => {
|
|
78
|
+
const parsed = toXCredentials(credentials);
|
|
79
|
+
if (!parsed) {
|
|
80
|
+
return {
|
|
81
|
+
isConfigured: false,
|
|
82
|
+
bearerTokenHint: null,
|
|
83
|
+
apiKeyHint: null,
|
|
84
|
+
hasApiSecret: false,
|
|
85
|
+
hasAccessToken: false,
|
|
86
|
+
hasAccessTokenSecret: false,
|
|
87
|
+
updatedAt: null,
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
return {
|
|
92
|
+
isConfigured: true,
|
|
93
|
+
bearerTokenHint: maskSecret(parsed.bearerToken),
|
|
94
|
+
apiKeyHint: maskSecret(parsed.apiKey),
|
|
95
|
+
hasApiSecret: Boolean(parsed.apiSecret),
|
|
96
|
+
hasAccessToken: Boolean(parsed.accessToken),
|
|
97
|
+
hasAccessTokenSecret: Boolean(parsed.accessTokenSecret),
|
|
98
|
+
updatedAt: parsed.updatedAt,
|
|
99
|
+
};
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
const quoteQueryTerm = (term: string): string => {
|
|
103
|
+
const trimmed = term.trim();
|
|
104
|
+
return `"${trimmed.replaceAll('"', "")}"`;
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
const normalizeQueryTerms = (queryTerms: string[]): string[] => {
|
|
108
|
+
const normalized = queryTerms
|
|
109
|
+
.map((term) => term.trim())
|
|
110
|
+
.filter((term) => term.length > 0)
|
|
111
|
+
.map((term) => quoteQueryTerm(term));
|
|
112
|
+
|
|
113
|
+
return [...new Set(normalized)];
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
export const buildXRecentSearchQuery = (queryTerms: string[]): string => {
|
|
117
|
+
const terms = normalizeQueryTerms(queryTerms);
|
|
118
|
+
if (terms.length === 0) {
|
|
119
|
+
throw new Error("At least one X query term is required.");
|
|
120
|
+
}
|
|
121
|
+
return `(${terms.join(" OR ")}) lang:en -is:retweet`;
|
|
122
|
+
};
|
|
123
|
+
|
|
124
|
+
const buildXApiUrl = (
|
|
125
|
+
baseUrl: string,
|
|
126
|
+
pathname: string,
|
|
127
|
+
searchParams?: URLSearchParams,
|
|
128
|
+
): string => {
|
|
129
|
+
const url = new URL(pathname, baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`);
|
|
130
|
+
if (searchParams) {
|
|
131
|
+
url.search = searchParams.toString();
|
|
132
|
+
}
|
|
133
|
+
return url.toString();
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
const asErrorMessage = (value: unknown): string => {
|
|
137
|
+
if (value instanceof Error) {
|
|
138
|
+
return value.message;
|
|
139
|
+
}
|
|
140
|
+
return typeof value === "string" ? value : "Unknown error";
|
|
141
|
+
};
|
|
142
|
+
|
|
143
|
+
const truncateText = (value: string, maxLength = 220): string =>
|
|
144
|
+
value.length > maxLength ? `${value.slice(0, maxLength)}...` : value;
|
|
145
|
+
|
|
146
|
+
const readResponseErrorDetail = async (response: Response): Promise<string | null> => {
|
|
147
|
+
try {
|
|
148
|
+
const payload = (await response.clone().json()) as unknown;
|
|
149
|
+
const record = asRecord(payload);
|
|
150
|
+
if (record) {
|
|
151
|
+
const detail = asString(record.detail);
|
|
152
|
+
if (detail) {
|
|
153
|
+
return truncateText(detail);
|
|
154
|
+
}
|
|
155
|
+
const message = asString(record.message);
|
|
156
|
+
if (message) {
|
|
157
|
+
return truncateText(message);
|
|
158
|
+
}
|
|
159
|
+
const title = asString(record.title);
|
|
160
|
+
if (title) {
|
|
161
|
+
return truncateText(title);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const errors = Array.isArray(record.errors) ? record.errors : null;
|
|
165
|
+
if (errors) {
|
|
166
|
+
const first = asRecord(errors[0]);
|
|
167
|
+
const firstMessage = first ? asString(first.message) : null;
|
|
168
|
+
if (firstMessage) {
|
|
169
|
+
return truncateText(firstMessage);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
} catch {
|
|
174
|
+
// fall through to text body parsing
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
try {
|
|
178
|
+
const text = (await response.clone().text()).trim();
|
|
179
|
+
if (text.length > 0) {
|
|
180
|
+
return truncateText(text);
|
|
181
|
+
}
|
|
182
|
+
} catch {
|
|
183
|
+
// noop
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
return null;
|
|
187
|
+
};
|
|
188
|
+
|
|
189
|
+
const assertXCredentials = (credentials: unknown): XMonitorCredentials => {
|
|
190
|
+
const parsed = toXCredentials(credentials);
|
|
191
|
+
if (!parsed) {
|
|
192
|
+
throw new Error("Invalid X credentials: bearerToken is required.");
|
|
193
|
+
}
|
|
194
|
+
return parsed;
|
|
195
|
+
};
|
|
196
|
+
|
|
197
|
+
const parseRecentSearchPayload = (payload: unknown, matchedQueryTerm: string): MonitorPost[] => {
|
|
198
|
+
const record = asRecord(payload);
|
|
199
|
+
if (!record) {
|
|
200
|
+
return [];
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
const includesRecord = asRecord(record.includes);
|
|
204
|
+
const users = Array.isArray(includesRecord?.users) ? includesRecord.users : [];
|
|
205
|
+
const usersById = new Map<string, { username: string; displayName: string }>();
|
|
206
|
+
|
|
207
|
+
for (const user of users) {
|
|
208
|
+
const userRecord = asRecord(user);
|
|
209
|
+
if (!userRecord) {
|
|
210
|
+
continue;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
const id = asString(userRecord.id);
|
|
214
|
+
const username = asString(userRecord.username);
|
|
215
|
+
const displayName = asString(userRecord.name);
|
|
216
|
+
if (!id || !username) {
|
|
217
|
+
continue;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
usersById.set(id, {
|
|
221
|
+
username,
|
|
222
|
+
displayName: displayName ?? username,
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
const tweets = Array.isArray(record.data) ? record.data : [];
|
|
227
|
+
const normalized: MonitorPost[] = [];
|
|
228
|
+
|
|
229
|
+
for (const tweet of tweets) {
|
|
230
|
+
const tweetRecord = asRecord(tweet);
|
|
231
|
+
if (!tweetRecord) {
|
|
232
|
+
continue;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
const id = asString(tweetRecord.id);
|
|
236
|
+
const text = asString(tweetRecord.text);
|
|
237
|
+
const createdAt = asString(tweetRecord.created_at);
|
|
238
|
+
const authorId = asString(tweetRecord.author_id);
|
|
239
|
+
const metrics = asRecord(tweetRecord.public_metrics);
|
|
240
|
+
const likeCountRaw = asNumber(metrics?.like_count);
|
|
241
|
+
|
|
242
|
+
if (!id || !text || !createdAt || !authorId || likeCountRaw === null) {
|
|
243
|
+
continue;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
const authorInfo = usersById.get(authorId);
|
|
247
|
+
const author = authorInfo?.username ?? authorId;
|
|
248
|
+
const permalink = authorInfo
|
|
249
|
+
? `https://x.com/${authorInfo.username}/status/${id}`
|
|
250
|
+
: `https://x.com/i/web/status/${id}`;
|
|
251
|
+
|
|
252
|
+
normalized.push({
|
|
253
|
+
source: "x",
|
|
254
|
+
id,
|
|
255
|
+
text,
|
|
256
|
+
author,
|
|
257
|
+
createdAt,
|
|
258
|
+
likeCount: Math.max(0, Math.floor(likeCountRaw)),
|
|
259
|
+
permalink,
|
|
260
|
+
matchedQueryTerm,
|
|
261
|
+
});
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
return normalized;
|
|
265
|
+
};
|
|
266
|
+
|
|
267
|
+
const parseNextToken = (payload: unknown): string | null => {
|
|
268
|
+
const record = asRecord(payload);
|
|
269
|
+
const meta = record ? asRecord(record.meta) : null;
|
|
270
|
+
const nextToken = meta ? asString(meta.next_token) : null;
|
|
271
|
+
return nextToken ?? null;
|
|
272
|
+
};
|
|
273
|
+
|
|
274
|
+
const extractUsageBudget = (
|
|
275
|
+
value: unknown,
|
|
276
|
+
): { cap: number; used: number; remaining: number; resetAt: string | null } | null => {
|
|
277
|
+
const record = asRecord(value);
|
|
278
|
+
if (!record) {
|
|
279
|
+
if (Array.isArray(value)) {
|
|
280
|
+
for (const item of value) {
|
|
281
|
+
const extracted = extractUsageBudget(item);
|
|
282
|
+
if (extracted) {
|
|
283
|
+
return extracted;
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
return null;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
const cap = asNumber(record.cap);
|
|
291
|
+
const used = asNumber(record.used) ?? asNumber(record.usage);
|
|
292
|
+
if (cap !== null && used !== null) {
|
|
293
|
+
const normalizedCap = Math.max(0, Math.floor(cap));
|
|
294
|
+
const normalizedUsed = Math.max(0, Math.floor(used));
|
|
295
|
+
const remaining = Math.max(0, normalizedCap - normalizedUsed);
|
|
296
|
+
return {
|
|
297
|
+
cap: normalizedCap,
|
|
298
|
+
used: normalizedUsed,
|
|
299
|
+
remaining,
|
|
300
|
+
resetAt: asString(record.reset_at) ?? asString(record.resetAt) ?? null,
|
|
301
|
+
};
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
for (const childValue of Object.values(record)) {
|
|
305
|
+
const extracted = extractUsageBudget(childValue);
|
|
306
|
+
if (extracted) {
|
|
307
|
+
return extracted;
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
return null;
|
|
312
|
+
};
|
|
313
|
+
|
|
314
|
+
const fetchRecentSearchPage = async ({
|
|
315
|
+
fetchFn,
|
|
316
|
+
baseUrl,
|
|
317
|
+
credentials,
|
|
318
|
+
query,
|
|
319
|
+
startTime,
|
|
320
|
+
nextToken,
|
|
321
|
+
}: {
|
|
322
|
+
fetchFn: typeof fetch;
|
|
323
|
+
baseUrl: string;
|
|
324
|
+
credentials: XMonitorCredentials;
|
|
325
|
+
query: string;
|
|
326
|
+
startTime: string;
|
|
327
|
+
nextToken?: string | null;
|
|
328
|
+
}) => {
|
|
329
|
+
const searchParams = new URLSearchParams({
|
|
330
|
+
query,
|
|
331
|
+
"tweet.fields": "id,text,created_at,public_metrics,author_id,lang",
|
|
332
|
+
expansions: "author_id",
|
|
333
|
+
"user.fields": "id,name,username",
|
|
334
|
+
max_results: "100",
|
|
335
|
+
start_time: startTime,
|
|
336
|
+
});
|
|
337
|
+
|
|
338
|
+
if (nextToken) {
|
|
339
|
+
searchParams.set("next_token", nextToken);
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
const url = buildXApiUrl(baseUrl, "/2/tweets/search/recent", searchParams);
|
|
343
|
+
const response = await fetchFn(url, {
|
|
344
|
+
method: "GET",
|
|
345
|
+
headers: {
|
|
346
|
+
Accept: "application/json",
|
|
347
|
+
Authorization: `Bearer ${credentials.bearerToken}`,
|
|
348
|
+
},
|
|
349
|
+
});
|
|
350
|
+
|
|
351
|
+
if (!response.ok) {
|
|
352
|
+
const detail = await readResponseErrorDetail(response);
|
|
353
|
+
throw new Error(
|
|
354
|
+
detail
|
|
355
|
+
? `X recent search failed (${response.status}): ${detail}`
|
|
356
|
+
: `X recent search failed (${response.status}).`,
|
|
357
|
+
);
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
return response.json();
|
|
361
|
+
};
|
|
362
|
+
|
|
363
|
+
const validateXCredentials = async ({
|
|
364
|
+
fetchFn,
|
|
365
|
+
baseUrl,
|
|
366
|
+
credentials,
|
|
367
|
+
}: {
|
|
368
|
+
fetchFn: typeof fetch;
|
|
369
|
+
baseUrl: string;
|
|
370
|
+
credentials: XMonitorCredentials;
|
|
371
|
+
}): Promise<MonitorProviderValidationResult> => {
|
|
372
|
+
try {
|
|
373
|
+
const now = new Date();
|
|
374
|
+
const startTime = new Date(now.getTime() - 60 * 60 * 1000).toISOString();
|
|
375
|
+
await fetchRecentSearchPage({
|
|
376
|
+
fetchFn,
|
|
377
|
+
baseUrl,
|
|
378
|
+
credentials,
|
|
379
|
+
query: VALIDATION_QUERY,
|
|
380
|
+
startTime,
|
|
381
|
+
});
|
|
382
|
+
return { ok: true };
|
|
383
|
+
} catch (error) {
|
|
384
|
+
return {
|
|
385
|
+
ok: false,
|
|
386
|
+
error: `X credential validation failed: ${asErrorMessage(error)}`,
|
|
387
|
+
};
|
|
388
|
+
}
|
|
389
|
+
};
|
|
390
|
+
|
|
391
|
+
const fetchXRecentPosts = async ({
|
|
392
|
+
fetchFn,
|
|
393
|
+
baseUrl,
|
|
394
|
+
credentials,
|
|
395
|
+
queryTerms,
|
|
396
|
+
postLimit,
|
|
397
|
+
searchWindowDays,
|
|
398
|
+
now,
|
|
399
|
+
}: {
|
|
400
|
+
fetchFn: typeof fetch;
|
|
401
|
+
baseUrl: string;
|
|
402
|
+
credentials: XMonitorCredentials;
|
|
403
|
+
queryTerms: string[];
|
|
404
|
+
postLimit: number;
|
|
405
|
+
searchWindowDays: MonitorSearchWindowDays;
|
|
406
|
+
now: Date;
|
|
407
|
+
}): Promise<MonitorPost[]> => {
|
|
408
|
+
const startTime = new Date(now.getTime() - searchWindowDays * 24 * 60 * 60 * 1000).toISOString();
|
|
409
|
+
const normalizedTerms = [
|
|
410
|
+
...new Set(queryTerms.map((term) => term.trim()).filter((term) => term.length > 0)),
|
|
411
|
+
];
|
|
412
|
+
if (normalizedTerms.length === 0) {
|
|
413
|
+
throw new Error("At least one X query term is required.");
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
const normalizedPostLimit = Math.max(1, Math.floor(postLimit));
|
|
417
|
+
const perTermLimit = Math.max(1, Math.ceil(normalizedPostLimit / normalizedTerms.length));
|
|
418
|
+
const posts: MonitorPost[] = [];
|
|
419
|
+
|
|
420
|
+
for (const term of normalizedTerms) {
|
|
421
|
+
let nextToken: string | null = null;
|
|
422
|
+
let pageCount = 0;
|
|
423
|
+
let termPostCount = 0;
|
|
424
|
+
const query = buildXRecentSearchQuery([term]);
|
|
425
|
+
|
|
426
|
+
while (pageCount < MAX_RECENT_SEARCH_PAGES_PER_TERM && termPostCount < perTermLimit) {
|
|
427
|
+
const payload = await fetchRecentSearchPage({
|
|
428
|
+
fetchFn,
|
|
429
|
+
baseUrl,
|
|
430
|
+
credentials,
|
|
431
|
+
query,
|
|
432
|
+
startTime,
|
|
433
|
+
nextToken,
|
|
434
|
+
});
|
|
435
|
+
|
|
436
|
+
const parsedPosts = parseRecentSearchPayload(payload, term);
|
|
437
|
+
posts.push(...parsedPosts);
|
|
438
|
+
termPostCount += parsedPosts.length;
|
|
439
|
+
nextToken = parseNextToken(payload);
|
|
440
|
+
pageCount += 1;
|
|
441
|
+
|
|
442
|
+
if (!nextToken) {
|
|
443
|
+
break;
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
return posts;
|
|
449
|
+
};
|
|
450
|
+
|
|
451
|
+
const fetchXUsage = async ({
|
|
452
|
+
fetchFn,
|
|
453
|
+
baseUrl,
|
|
454
|
+
usagePath,
|
|
455
|
+
credentials,
|
|
456
|
+
now,
|
|
457
|
+
}: {
|
|
458
|
+
fetchFn: typeof fetch;
|
|
459
|
+
baseUrl: string;
|
|
460
|
+
usagePath: string;
|
|
461
|
+
credentials: XMonitorCredentials;
|
|
462
|
+
now: Date;
|
|
463
|
+
}): Promise<MonitorUsageSnapshot> => {
|
|
464
|
+
try {
|
|
465
|
+
const url = buildXApiUrl(baseUrl, usagePath);
|
|
466
|
+
const response = await fetchFn(url, {
|
|
467
|
+
method: "GET",
|
|
468
|
+
headers: {
|
|
469
|
+
Accept: "application/json",
|
|
470
|
+
Authorization: `Bearer ${credentials.bearerToken}`,
|
|
471
|
+
},
|
|
472
|
+
});
|
|
473
|
+
|
|
474
|
+
if (!response.ok) {
|
|
475
|
+
const detail = await readResponseErrorDetail(response);
|
|
476
|
+
return {
|
|
477
|
+
status: "error",
|
|
478
|
+
source: "x-api",
|
|
479
|
+
fetchedAt: now.toISOString(),
|
|
480
|
+
message: detail
|
|
481
|
+
? `X usage request failed (${response.status}): ${detail}`
|
|
482
|
+
: `X usage request failed (${response.status}).`,
|
|
483
|
+
};
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
const payload = await response.json();
|
|
487
|
+
const budget = extractUsageBudget(payload);
|
|
488
|
+
if (!budget) {
|
|
489
|
+
return {
|
|
490
|
+
status: "unavailable",
|
|
491
|
+
source: "x-api",
|
|
492
|
+
fetchedAt: now.toISOString(),
|
|
493
|
+
message: "X usage response did not include cap and usage values.",
|
|
494
|
+
};
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
return {
|
|
498
|
+
status: "ok",
|
|
499
|
+
source: "x-api",
|
|
500
|
+
fetchedAt: now.toISOString(),
|
|
501
|
+
cap: budget.cap,
|
|
502
|
+
used: budget.used,
|
|
503
|
+
remaining: budget.remaining,
|
|
504
|
+
resetAt: budget.resetAt,
|
|
505
|
+
message: null,
|
|
506
|
+
};
|
|
507
|
+
} catch (error) {
|
|
508
|
+
return {
|
|
509
|
+
status: "error",
|
|
510
|
+
source: "x-api",
|
|
511
|
+
fetchedAt: now.toISOString(),
|
|
512
|
+
message: `Unable to read X usage: ${asErrorMessage(error)}`,
|
|
513
|
+
};
|
|
514
|
+
}
|
|
515
|
+
};
|
|
516
|
+
|
|
517
|
+
export const createXMonitorProvider = ({
|
|
518
|
+
fetchFn = globalThis.fetch,
|
|
519
|
+
apiBaseUrl = process.env.OCTOGENT_X_API_BASE_URL ?? DEFAULT_X_API_BASE_URL,
|
|
520
|
+
usageEndpointPath = process.env.OCTOGENT_X_USAGE_ENDPOINT_PATH ?? DEFAULT_X_USAGE_ENDPOINT_PATH,
|
|
521
|
+
}: {
|
|
522
|
+
fetchFn?: typeof fetch;
|
|
523
|
+
apiBaseUrl?: string;
|
|
524
|
+
usageEndpointPath?: string;
|
|
525
|
+
} = {}): MonitorProviderAdapter => ({
|
|
526
|
+
providerId: "x",
|
|
527
|
+
|
|
528
|
+
saveCredentials(input, now): MonitorCredentialsSaveResult {
|
|
529
|
+
const record = asRecord(input);
|
|
530
|
+
if (!record) {
|
|
531
|
+
throw new Error("Expected credentials to be a JSON object.");
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
const bearerToken = asString(record.bearerToken)?.trim();
|
|
535
|
+
if (!bearerToken) {
|
|
536
|
+
throw new Error("X bearerToken is required.");
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
const credentials: XMonitorCredentials = {
|
|
540
|
+
bearerToken,
|
|
541
|
+
apiKey: normalizeOptionalSecret(record.apiKey),
|
|
542
|
+
apiSecret: normalizeOptionalSecret(record.apiSecret),
|
|
543
|
+
accessToken: normalizeOptionalSecret(record.accessToken),
|
|
544
|
+
accessTokenSecret: normalizeOptionalSecret(record.accessTokenSecret),
|
|
545
|
+
updatedAt: now.toISOString(),
|
|
546
|
+
};
|
|
547
|
+
|
|
548
|
+
return {
|
|
549
|
+
credentials,
|
|
550
|
+
summary: summarizeXCredentials(credentials),
|
|
551
|
+
};
|
|
552
|
+
},
|
|
553
|
+
|
|
554
|
+
summarizeCredentials(credentials) {
|
|
555
|
+
return summarizeXCredentials(credentials);
|
|
556
|
+
},
|
|
557
|
+
|
|
558
|
+
validateCredentials(credentials) {
|
|
559
|
+
return validateXCredentials({
|
|
560
|
+
fetchFn,
|
|
561
|
+
baseUrl: apiBaseUrl,
|
|
562
|
+
credentials: assertXCredentials(credentials),
|
|
563
|
+
});
|
|
564
|
+
},
|
|
565
|
+
|
|
566
|
+
fetchRecentPosts({ credentials, queryTerms, postLimit, searchWindowDays, now }) {
|
|
567
|
+
return fetchXRecentPosts({
|
|
568
|
+
fetchFn,
|
|
569
|
+
baseUrl: apiBaseUrl,
|
|
570
|
+
credentials: assertXCredentials(credentials),
|
|
571
|
+
queryTerms,
|
|
572
|
+
postLimit,
|
|
573
|
+
searchWindowDays,
|
|
574
|
+
now,
|
|
575
|
+
});
|
|
576
|
+
},
|
|
577
|
+
|
|
578
|
+
fetchUsage({ credentials, now }) {
|
|
579
|
+
return fetchXUsage({
|
|
580
|
+
fetchFn,
|
|
581
|
+
baseUrl: apiBaseUrl,
|
|
582
|
+
usagePath: usageEndpointPath,
|
|
583
|
+
credentials: assertXCredentials(credentials),
|
|
584
|
+
now,
|
|
585
|
+
});
|
|
586
|
+
},
|
|
587
|
+
});
|