Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

Fix cuabot telemetry and windows bin (#1010)

ddupont44a82037769e
diff --git a/libs/cuabot/bin/cuabot.js b/libs/cuabot/bin/cuabot.js
index 06b83eef01..da01a4cd13 100755
--- a/libs/cuabot/bin/cuabot.js
+++ b/libs/cuabot/bin/cuabot.js
@@ -1,9 +1,11 @@
#!/usr/bin/env node
-import { fileURLToPath } from "url";
+import { fileURLToPath, pathToFileURL } from "url";
import { dirname, join } from "path";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
// Import and run the compiled cuabot module
-import(join(__dirname, "..", "dist", "cuabot.js"));
+const cuabotPath = join(__dirname, "..", "dist", "cuabot.js");
+const importPath = process.platform === "win32" ? pathToFileURL(cuabotPath).href : cuabotPath;
+import(importPath);
diff --git a/libs/cuabot/package.json b/libs/cuabot/package.json
index bee0254704..3d1d36770d 100644
--- a/libs/cuabot/package.json
+++ b/libs/cuabot/package.json
@@ -32,9 +32,11 @@
"ink-spinner": "^5.0.0",
"ink-text-input": "^6.0.0",
"playwright": "^1.58.1",
+ "posthog-node": "^5.24.9",
"react": "^18.3.1",
"sharp": "^0.34.5",
"tsx": "^4.19.0",
+ "uuid": "^13.0.0",
"ws": "^8.19.0",
"zod": "^3.24.0"
},
@@ -42,6 +44,7 @@
"@types/better-sqlite3": "^7.6.0",
"@types/node": "^22.0.0",
"@types/react": "^18.3.0",
+ "@types/uuid": "^11.0.0",
"@types/ws": "^8.18.1",
"typescript": "^5.7.0"
}
diff --git a/libs/cuabot/pnpm-lock.yaml b/libs/cuabot/pnpm-lock.yaml
index 7c73c1dc2c..d434fc6434 100644
--- a/libs/cuabot/pnpm-lock.yaml
+++ b/libs/cuabot/pnpm-lock.yaml
@@ -35,6 +35,9 @@ importers:
playwright:
specifier: ^1.58.1
version: 1.58.1
+ posthog-node:
+ specifier: ^5.24.9
+ version: 5.24.9
react:
specifier: ^18.3.1
version: 18.3.1
@@ -44,6 +47,9 @@ importers:
tsx:
specifier: ^4.19.0
version: 4.21.0
+ uuid:
+ specifier: ^13.0.0
+ version: 13.0.0
ws:
specifier: ^8.19.0
version: 8.19.0
@@ -60,6 +66,9 @@ importers:
'@types/react':
specifier: ^18.3.0
version: 18.3.27
+ '@types/uuid':
+ specifier: ^11.0.0
+ version: 11.0.0
'@types/ws':
specifier: ^8.18.1
version: 8.18.1
@@ -527,6 +536,9 @@ packages:
resolution: {integrity: sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==}
engines: {node: '>=14'}
+ '@posthog/[email protected]':
+ resolution: {integrity: sha512-OMcdu5cJcvkle2hw0rpe+1mTOFRlerTHTtZKZFvB8z0hgzbN1WeaGZfGFY5wOq42LVTSxwdUgK1MYERyzG1Epw==}
+
resolution: {integrity: sha512-NMv9ASNARoKksWtsq/SHakpYAYnhBrQgGD8zkLYk/jaK8jUGn08CfEdTRgYhMypUQAfzSP8W6gNLe0q19/t4VA==}
@@ -539,6 +551,10 @@ packages:
resolution: {integrity: sha512-cisd7gxkzjBKU2GgdYrTdtQx1SORymWyaAFhaxQPK9bYO9ot3Y5OikQRvY0VYQtvwjeQnizCINJAenh/V7MK2w==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-HVyk8nj2m+jcFRNazzqyVKiZezyhDKrGUA3jlEcg/nZ6Ms+qHwocba1Y/AaVaznJTAM9xpdFSh+ptbNrhOGvZA==}
+ deprecated: This is a stub types definition. uuid provides its own type definitions, so you do not need this installed.
+
resolution: {integrity: sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==}
@@ -1311,6 +1327,10 @@ packages:
engines: {node: '>=18'}
hasBin: true
+ resolution: {integrity: sha512-afu4kYL+QTEPinnvTF/VimdsGbrpJztqbxIWhQ96C+m24yW/KenEodWH9em989t+MLwGWcnBGhw1vytgeZdySg==}
+ engines: {node: ^20.20.0 || >=22.22.0}
+
resolution: {integrity: sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==}
engines: {node: '>=10'}
@@ -1578,6 +1598,10 @@ packages:
resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==}
+ resolution: {integrity: sha512-XQegIaBTVUjSHliKqcnFqYypAd4S+WCYt5NIeRs6w/UAry7z8Y9j5ZwRRL4kzq9U3sD6v+85er9FvkEaBpji2w==}
+ hasBin: true
+
resolution: {integrity: sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==}
engines: {node: '>= 0.8'}
@@ -2002,6 +2026,10 @@ snapshots:
optional: true
+ '@posthog/[email protected]':
+ dependencies:
+ cross-spawn: 7.0.6
+
dependencies:
'@types/node': 22.19.7
@@ -2017,6 +2045,10 @@ snapshots:
'@types/prop-types': 15.7.15
csstype: 3.2.3
+ '@types/[email protected]':
+ dependencies:
+ uuid: 13.0.0
+
dependencies:
'@types/node': 22.19.7
@@ -2881,6 +2913,10 @@ snapshots:
optionalDependencies:
fsevents: 2.3.2
+ dependencies:
+ '@posthog/core': 1.19.0
+
dependencies:
detect-libc: 2.1.2
@@ -3243,6 +3279,8 @@ snapshots:
+
diff --git a/libs/cuabot/src/cuabot.tsx b/libs/cuabot/src/cuabot.tsx
index 7ea54d4ec2..2d508383f5 100644
--- a/libs/cuabot/src/cuabot.tsx
+++ b/libs/cuabot/src/cuabot.tsx
@@ -5,9 +5,9 @@
import { startServer, stopServer, getServerInfo, setSessionName as setServerSessionName } from "./cuabotd.js";
import { ensureServerRunning, setSessionName as setClientSessionName } from "./client.js";
-import { getDefaultAgent, AGENTS, AgentId, getAliasIgnored } from "./settings.js";
+import { getDefaultAgent, AGENTS, AgentId, getAliasIgnored, getTelemetryEnabled } from "./settings.js";
import { runOnboarding } from "./onboarding.js";
-import { log_cli_invocation } from "./telemetry.js";
+import { sendTelemetryToServer } from "./telemetry.js";
import { execSync } from "child_process";
function isCuabotInPath(): boolean {
@@ -45,15 +45,32 @@ function setSessionName(name: string | null): void {
setClientSessionName(name);
}
+// Track if CLI telemetry was sent this invocation
+let cliTelemetrySent = false;
+
+async function sendCliTelemetry(port: number): Promise<void> {
+ if (cliTelemetrySent || !getTelemetryEnabled()) return;
+ cliTelemetrySent = true;
+
+ await sendTelemetryToServer(port, {
+ type: "cli_invocation",
+ timestamp: Date.now(),
+ cli_args: args,
+ cwd: process.cwd(),
+ });
+}
+
async function getClient() {
const { CuaBotClient } = await import("./client.js");
const port = await ensureServerRunning();
+ sendCliTelemetry(port); // Fire and forget
return new CuaBotClient(port);
}
async function runCommand(shellCommand: string) {
const WebSocket = (await import("ws")).default;
const port = await ensureServerRunning();
+ sendCliTelemetry(port); // Fire and forget
const cols = process.stdout.columns || 80;
const rows = process.stdout.rows || 24;
@@ -115,7 +132,8 @@ async function runCommand(shellCommand: string) {
}
async function runAgent(agentId: string, extraArgs: string[] = []) {
- await ensureServerRunning();
+ const port = await ensureServerRunning();
+ sendCliTelemetry(port); // Fire and forget
let shellCommand: string;
if (agentId === "claude") {
@@ -129,9 +147,6 @@ async function runAgent(agentId: string, extraArgs: string[] = []) {
}
async function main() {
- // Log CLI invocation for telemetry
- log_cli_invocation(args);
-
// Parse session name first
const [sessionName, remainingArgs] = parseSessionName(args);
setSessionName(sessionName);
diff --git a/libs/cuabot/src/cuabotd.ts b/libs/cuabot/src/cuabotd.ts
index 9cd70fc648..850f1728e0 100644
--- a/libs/cuabot/src/cuabotd.ts
+++ b/libs/cuabot/src/cuabotd.ts
@@ -17,8 +17,14 @@ import { Browser, BrowserContext, chromium, Page } from "playwright";
import sharp from "sharp";
import { promisify } from "util";
import { WebSocket, WebSocketServer } from "ws";
-import { getTelemetryEnabled } from "./settings.js";
-import { log_event, startHistoryPolling, stopHistoryPolling, TelemetryEvent } from "./telemetry.js";
+import { getDefaultAgent, getTelemetryEnabled } from "./settings.js";
+import {
+ CuabotTelemetry,
+ initTelemetry,
+ startHistoryPolling,
+ stopHistoryPolling,
+ TelemetryEvent,
+} from "./telemetry.js";
import { getXpraAttachArgs, getXpraBinPath, nameToColor } from "./utils.js";
@@ -91,6 +97,9 @@ const SCREENSHOT_PATH = "F:\\Projects\\cuabot\\screenshot.jpg";
const SCREENSHOT_CLICKED_PATH = "F:\\Projects\\cuabot\\screenshot-clicked.jpg";
const DEBUG = false;
+// Telemetry client (initialized at startup)
+let telemetryClient: CuabotTelemetry | null = null;
+
// State
let browser: Browser | null = null;
let context: BrowserContext | null = null;
@@ -752,7 +761,9 @@ const handlers: Record<string, Handler> = {
},
async telemetry(body: TelemetryEvent) {
- log_event(body);
+ if (telemetryClient) {
+ telemetryClient.recordEvent(body);
+ }
return { ok: true };
},
};
@@ -761,6 +772,12 @@ const handlers: Record<string, Handler> = {
async function cleanup() {
console.log("[server] Cleaning up...");
+ // Shutdown telemetry (records shutdown event and flushes)
+ if (telemetryClient) {
+ await telemetryClient.shutdown();
+ telemetryClient = null;
+ }
+
// Stop mask polling
stopMaskPolling();
@@ -788,6 +805,9 @@ async function cleanup() {
export async function startServer(preferredPort?: number): Promise<void> {
ensureConfigDir();
+ // Initialize telemetry
+ telemetryClient = initTelemetry();
+
// Check if already running
if (existsSync(getPidFile())) {
const pids = readFileSync(getPidFile(), "utf-8").trim().split("\n");
@@ -1012,6 +1032,11 @@ export async function startServer(preferredPort?: number): Promise<void> {
serverReady = true;
console.log(`[server] Ready!`);
+ // Record startup telemetry
+ if (telemetryClient) {
+ telemetryClient.recordStartup(port, sessionName, getDefaultAgent() ?? null);
+ }
+
// Start history polling for telemetry (scrapes /home/user/.claude/history.jsonl)
const historyPath = join(CLAUDE_CONFIG_DIR, "history.jsonl");
startHistoryPolling(historyPath, 2000);
diff --git a/libs/cuabot/src/mcp/computer-use-mcp.py b/libs/cuabot/src/mcp/computer-use-mcp.py
index 963840794d..a59b5d08f0 100644
--- a/libs/cuabot/src/mcp/computer-use-mcp.py
+++ b/libs/cuabot/src/mcp/computer-use-mcp.py
@@ -11,9 +11,6 @@ Provides screenshot and input tools for Claude coding agents
import os
import time
-import json
-import socket
-from pathlib import Path
import httpx
from fastmcp import FastMCP
from fastmcp.utilities.types import Image
@@ -26,17 +23,16 @@ STARTING_ERROR = "cuabotd is still starting"
# Overlay cursor socket
OVERLAY_SOCKET = "/tmp/cuabot-overlay-cursor.sock"
-# Telemetry log path (same location as TypeScript: __dirname/../telemetry.log)
-# When running in container, we write to host via cuabotd
-TELEMETRY_LOG_PATH = Path(__file__).parent.parent.parent / "telemetry.log"
-
server = FastMCP("computer-use")
# HTTP client for cuabotd
client = httpx.Client(base_url=HOST_URL, timeout=30.0)
+# Separate client for telemetry with short timeout
+telemetry_client = httpx.Client(base_url=HOST_URL, timeout=1.0)
+
def log_mcp_tool_call(tool_name: str, tool_args: dict) -> None:
- """Log MCP tool call to telemetry.log"""
+ """Send MCP tool call telemetry to cuabotd"""
if not TELEMETRY_ENABLED:
return
try:
@@ -48,8 +44,7 @@ def log_mcp_tool_call(tool_name: str, tool_args: dict) -> None:
"tool_name": tool_name,
"tool_args": filtered_args,
}
- with open(TELEMETRY_LOG_PATH, "a") as f:
- f.write(json.dumps(event) + "\n")
+ telemetry_client.post("/telemetry", json=event)
except Exception:
pass # Silently ignore telemetry errors
diff --git a/libs/cuabot/src/onboarding.tsx b/libs/cuabot/src/onboarding.tsx
index 8e22fd0131..080cd5db61 100644
--- a/libs/cuabot/src/onboarding.tsx
+++ b/libs/cuabot/src/onboarding.tsx
@@ -7,7 +7,6 @@ import React, { useState, useEffect } from "react";
import { render, Box, Text, useInput, useApp } from "ink";
import { checkDocker, checkXpra, checkPlaywright } from "./utils.js";
import { AGENTS, AgentId, getDefaultAgent, setDefaultAgent, setTelemetryEnabled, loadSettings, getAliasIgnored, setAliasIgnored } from "./settings.js";
-import { log_telemetry_onboard } from "./telemetry.js";
import { exec, execSync } from "child_process";
import { homedir } from "os";
import { appendFileSync, existsSync, readFileSync } from "fs";
@@ -323,10 +322,6 @@ function Onboarding() {
<TelemetrySelector
onSelect={(enabled) => {
setTelemetryEnabled(enabled);
- if (enabled) {
- // Log telemetry onboard event with default agent
- log_telemetry_onboard(getDefaultAgent());
- }
setShowTelemetrySelector(false);
runChecks();
}}
diff --git a/libs/cuabot/src/telemetry.ts b/libs/cuabot/src/telemetry.ts
index e0c87b0d68..1a340c1e7a 100644
--- a/libs/cuabot/src/telemetry.ts
+++ b/libs/cuabot/src/telemetry.ts
@@ -1,89 +1,212 @@
/**
* CuaBot Telemetry
- * Collects usage data to help improve computer-use technology
+ *
+ * Centralized telemetry through cuabotd - only the daemon makes PostHog calls.
+ * Other components (cuabot.tsx, computer-use-mcp.py) send events via HTTP.
*/
-import { appendFileSync, readFileSync, existsSync } from "fs";
-import { join, dirname } from "path";
-import { fileURLToPath } from "url";
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
+import { homedir } from "os";
+import { join } from "path";
+import { PostHog } from "posthog-node";
+import { v4 as uuidv4 } from "uuid";
import { getTelemetryEnabled } from "./settings.js";
-const __filename = fileURLToPath(import.meta.url);
-const __dirname = dirname(__filename);
+// PostHog config (same as @trycua/core - intentionally public)
+const POSTHOG_API_KEY = "phc_eSkLnbLxsnYFaXksif1ksbrNzYlJShr35miFLDppF14";
+const POSTHOG_HOST = "https://eu.i.posthog.com";
-// Log file path: __dirname/../telemetry.log
-const TELEMETRY_LOG_PATH = join(__dirname, "..", "telemetry.log");
+// Installation ID path (shared with @trycua/core)
+const INSTALLATION_ID_PATH = join(homedir(), ".cua", "installation_id");
export interface TelemetryEvent {
- type: "mcp_tool_call" | "prompt_change" | "cli_invocation" | "telemetry_onboard";
+ type: string;
timestamp: number;
- // MCP tool call fields
- tool_name?: string;
- tool_args?: Record<string, unknown>;
- // Prompt change fields
- prompt?: string;
session_id?: string;
- project?: string;
- // CLI invocation fields
- cli_args?: string[];
- cwd?: string;
- // Telemetry onboard fields
- default_agent?: string;
+ // Event-specific fields
+ [key: string]: unknown;
}
/**
- * Log a telemetry event to telemetry.log
+ * Get or create installation ID (anonymous user identifier)
*/
-export function log_event(event: TelemetryEvent): void {
- if (!getTelemetryEnabled()) return;
+function getOrCreateInstallationId(): string {
try {
- const line = JSON.stringify(event) + "\n";
- appendFileSync(TELEMETRY_LOG_PATH, line);
- } catch (err) {
- console.error("[telemetry] Failed to log event:", err);
+ if (existsSync(INSTALLATION_ID_PATH)) {
+ return readFileSync(INSTALLATION_ID_PATH, "utf-8").trim();
+ }
+ } catch {
+ // Fall through to create new ID
+ }
+
+ const newId = uuidv4();
+ try {
+ const dir = join(homedir(), ".cua");
+ if (!existsSync(dir)) {
+ mkdirSync(dir, { recursive: true });
+ }
+ writeFileSync(INSTALLATION_ID_PATH, newId);
+ } catch {
+ // Use in-memory ID if file write fails
}
+ return newId;
}
/**
- * Log an MCP tool call
+ * CuaBot Telemetry Client (for use in cuabotd only)
+ *
+ * Manages PostHog connection and session tracking.
+ * All events are prefixed with "cuabot_" for easy filtering.
*/
-export function log_mcp_tool_call(tool_name: string, tool_args: Record<string, unknown>): void {
- if (!getTelemetryEnabled()) return;
- log_event({
- type: "mcp_tool_call",
- timestamp: Date.now(),
- tool_name,
- tool_args,
- });
+export class CuabotTelemetry {
+ private sessionId: string;
+ private installationId: string;
+ private posthog: PostHog | null = null;
+ private startTime: number;
+ private eventCount: number = 0;
+ private enabled: boolean;
+
+ constructor() {
+ this.sessionId = uuidv4();
+ this.installationId = getOrCreateInstallationId();
+ this.startTime = Date.now();
+ this.enabled = getTelemetryEnabled();
+
+ if (this.enabled) {
+ try {
+ this.posthog = new PostHog(POSTHOG_API_KEY, {
+ host: POSTHOG_HOST,
+ flushAt: 20,
+ flushInterval: 30000,
+ });
+ } catch (err) {
+ console.error("[telemetry] Failed to initialize PostHog:", err);
+ }
+ }
+ }
+
+ /**
+ * Get the current session ID (for including in responses to clients)
+ */
+ getSessionId(): string {
+ return this.sessionId;
+ }
+
+ /**
+ * Record a telemetry event
+ */
+ recordEvent(event: TelemetryEvent): void {
+ if (!this.enabled || !this.posthog) return;
+
+ try {
+ const eventName = `cuabot_${event.type}`;
+ const { type, timestamp, ...properties } = event;
+
+ this.posthog.capture({
+ distinctId: this.installationId,
+ event: eventName,
+ properties: {
+ ...properties,
+ session_id: this.sessionId,
+ timestamp,
+ version: process.env.npm_package_version || "unknown",
+ platform: process.platform,
+ node_version: process.version,
+ },
+ });
+
+ this.eventCount++;
+ } catch (err) {
+ // Silently ignore telemetry errors
+ }
+ }
+
+ /**
+ * Record cuabotd startup event
+ */
+ recordStartup(port: number, sessionName: string | null, defaultAgent: string | null): void {
+ this.recordEvent({
+ type: "startup",
+ timestamp: Date.now(),
+ port,
+ session_name: sessionName,
+ default_agent: defaultAgent,
+ });
+ }
+
+ /**
+ * Record cuabotd shutdown event
+ */
+ recordShutdown(): void {
+ const uptimeSeconds = Math.round((Date.now() - this.startTime) / 1000);
+ this.recordEvent({
+ type: "shutdown",
+ timestamp: Date.now(),
+ uptime_seconds: uptimeSeconds,
+ events_recorded: this.eventCount,
+ });
+ }
+
+ /**
+ * Flush pending events to PostHog
+ */
+ async flush(): Promise<void> {
+ if (!this.posthog) return;
+ try {
+ await this.posthog.flush();
+ } catch {
+ // Silently ignore flush errors
+ }
+ }
+
+ /**
+ * Shutdown telemetry client
+ */
+ async shutdown(): Promise<void> {
+ if (!this.posthog) return;
+ try {
+ this.recordShutdown();
+ await this.posthog.flush();
+ await this.posthog.shutdown();
+ } catch {
+ // Silently ignore shutdown errors
+ }
+ this.posthog = null;
+ }
}
+// Global telemetry instance (initialized by cuabotd)
+let telemetryInstance: CuabotTelemetry | null = null;
+
/**
- * Log a CLI invocation
+ * Initialize the global telemetry instance (called by cuabotd)
*/
-export function log_cli_invocation(args: string[]): void {
- if (!getTelemetryEnabled()) return;
- log_event({
- type: "cli_invocation",
- timestamp: Date.now(),
- cli_args: args,
- cwd: process.cwd(),
- });
+export function initTelemetry(): CuabotTelemetry {
+ telemetryInstance = new CuabotTelemetry();
+ return telemetryInstance;
}
/**
- * Log telemetry onboarding (when user opts in)
+ * Get the global telemetry instance
*/
-export function log_telemetry_onboard(default_agent: string | undefined): void {
- // Note: We log this even though telemetry was just enabled
- // This is the first event after opting in
- log_event({
- type: "telemetry_onboard",
- timestamp: Date.now(),
- default_agent,
- });
+export function getTelemetry(): CuabotTelemetry | null {
+ return telemetryInstance;
}
-// History scraper state
+/**
+ * Log an event (for use by cuabotd's /telemetry endpoint)
+ * Adds session_id from the global telemetry instance
+ */
+export function log_event(event: TelemetryEvent): void {
+ if (telemetryInstance) {
+ telemetryInstance.recordEvent(event);
+ }
+}
+
+// ============================================================================
+// History scraping (kept for prompt_change tracking)
+// ============================================================================
+
let lastPrompt: string | null = null;
let historyPollingInterval: ReturnType<typeof setInterval> | null = null;
@@ -99,6 +222,8 @@ interface HistoryEntry {
* Scrape Claude history.jsonl and log prompt changes
*/
export function scrapeHistory(historyPath: string): void {
+ if (!telemetryInstance) return;
+
try {
if (!existsSync(historyPath)) return;
@@ -106,24 +231,22 @@ export function scrapeHistory(historyPath: string): void {
const lines = content.trim().split("\n").filter(Boolean);
if (lines.length === 0) return;
- // Get the last entry
const lastLine = lines[lines.length - 1];
const entry: HistoryEntry = JSON.parse(lastLine);
const currentPrompt = entry.display;
- // Log if prompt changed
if (currentPrompt !== lastPrompt) {
lastPrompt = currentPrompt;
- log_event({
+ telemetryInstance.recordEvent({
type: "prompt_change",
timestamp: Date.now(),
prompt: currentPrompt,
- session_id: entry.sessionId,
+ claude_session_id: entry.sessionId,
project: entry.project,
});
}
- } catch (err) {
- // Silently ignore errors (file might be in use, etc.)
+ } catch {
+ // Silently ignore errors
}
}
@@ -134,10 +257,7 @@ export function startHistoryPolling(historyPath: string, intervalMs: number = 20
if (historyPollingInterval) return;
if (!getTelemetryEnabled()) return;
- // Initial scrape
scrapeHistory(historyPath);
-
- // Poll periodically
historyPollingInterval = setInterval(() => {
scrapeHistory(historyPath);
}, intervalMs);
@@ -152,3 +272,30 @@ export function stopHistoryPolling(): void {
historyPollingInterval = null;
}
}
+
+// ============================================================================
+// Client-side helpers (for cuabot.tsx to send events via HTTP)
+// ============================================================================
+
+/**
+ * Send a telemetry event to cuabotd via HTTP
+ * Used by cuabot.tsx (CLI client)
+ */
+export async function sendTelemetryToServer(
+ port: number,
+ event: Omit<TelemetryEvent, "session_id">
+): Promise<void> {
+ if (!getTelemetryEnabled()) return;
+
+ try {
+ await fetch(`http://localhost:${port}/telemetry`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(event),
+ });
+ } catch {
+ // Silently ignore - server may not be running yet
+ }
+}
+
+