YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
fix(ci): publish release on workflow_dispatch - bump to v2.0.10
Louis Beaumontbf3f8fdd5380
diff --git a/.github/workflows/release-app.yml b/.github/workflows/release-app.ymlindex 81a4c6aa3..ed314410e 100644--- a/.github/workflows/release-app.yml+++ b/.github/workflows/release-app.yml@@ -654,7 +654,7 @@ jobs:publish-release:needs: [check_commit, publish-tauri]- if: needs.check_commit.outputs.should_publish == 'true' && (needs.publish-tauri.result == 'success' || needs.retry-win.result == 'success')+ if: (github.event_name == 'workflow_dispatch' || needs.check_commit.outputs.should_publish == 'true') && (needs.publish-tauri.result == 'success' || needs.retry-win.result == 'success')runs-on: ubuntu-lateststeps:- uses: actions/checkout@v4diff --git a/screenpipe-app-tauri/src-tauri/Cargo.lock b/screenpipe-app-tauri/src-tauri/Cargo.lockindex f9a31291c..134427fc7 100755--- a/screenpipe-app-tauri/src-tauri/Cargo.lock+++ b/screenpipe-app-tauri/src-tauri/Cargo.lock@@ -5629,7 +5629,7 @@ checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"[[package]]name = "screenpipe-app"-version = "2.0.8"+version = "2.0.9"dependencies = ["anyhow","async-stream",diff --git a/screenpipe-app-tauri/src-tauri/Cargo.toml b/screenpipe-app-tauri/src-tauri/Cargo.tomlindex ab16f5d52..e04dd3bc3 100644--- a/screenpipe-app-tauri/src-tauri/Cargo.toml+++ b/screenpipe-app-tauri/src-tauri/Cargo.toml@@ -1,6 +1,6 @@[package]name = "screenpipe-app"-version = "2.0.9"+version = "2.0.10"description = "24/7 memory for your desktop. 100% local."authors = ["you"]license = ""diff --git a/screenpipe-app-tauri/src-tauri/src/sidecar.rs b/screenpipe-app-tauri/src-tauri/src/sidecar.rsindex 9af1f1aa3..5725be283 100644--- a/screenpipe-app-tauri/src-tauri/src/sidecar.rs+++ b/screenpipe-app-tauri/src-tauri/src/sidecar.rs@@ -308,6 +308,8 @@ async fn spawn_sidecar(app: &tauri::AppHandle, override_args: Option<Vec<String>let _use_all_monitors = store.use_all_monitors;+ let analytics_id = store.analytics_id.clone();+let user = User::from_store(&store);println!("user: {:?}", user);@@ -486,6 +488,7 @@ async fn spawn_sidecar(app: &tauri::AppHandle, override_args: Option<Vec<String>}c = c.env("SENTRY_RELEASE_NAME_APPEND", "tauri");+ c = c.env("SCREENPIPE_ANALYTICS_ID", &analytics_id);// only supports --enable-realtime-vision for now, avoid adding if already presentif !args.contains(&"--enable-realtime-vision") && override_args_as_vec.contains(&"--enable-realtime-vision".to_string()) {@@ -526,6 +529,7 @@ async fn spawn_sidecar(app: &tauri::AppHandle, override_args: Option<Vec<String>}c = c.env("SENTRY_RELEASE_NAME_APPEND", "tauri");+ c = c.env("SCREENPIPE_ANALYTICS_ID", &analytics_id);// only supports --enable-realtime-vision for now, avoid adding if already presentif !args.contains(&"--enable-realtime-vision") && override_args_as_vec.contains(&"--enable-realtime-vision".to_string()) {diff --git a/screenpipe-js/ai-proxy/.dev.vars.example b/screenpipe-js/ai-proxy/.dev.vars.examplenew file mode 100644index 000000000..c037609a7--- /dev/null+++ b/screenpipe-js/ai-proxy/.dev.vars.example@@ -0,0 +1,33 @@+# Copy this file to .dev.vars and fill in your values+# These are used for local development with `wrangler dev`++# Existing API keys+OPENAI_API_KEY=sk-...+ANTHROPIC_API_KEY=sk-ant-...+GEMINI_API_KEY=...+DEEPGRAM_API_KEY=...++# Analytics+LANGFUSE_PUBLIC_KEY=...+LANGFUSE_SECRET_KEY=...++# Auth+CLERK_SECRET_KEY=...++# Supabase+SUPABASE_URL=...+SUPABASE_ANON_KEY=...++# ===== Vertex AI Proxy for Agent SDK =====+# These enable the /v1/messages endpoint to proxy to Vertex AI++# Your GCP project ID+VERTEX_PROJECT_ID=your-gcp-project-id++# Region where Claude models are available (us-east5 recommended)+VERTEX_REGION=us-east5++# Service account JSON credentials (paste the entire JSON on one line)+# Create a service account with "Vertex AI User" role+# Generate a JSON key and paste it here (escape quotes if needed)+VERTEX_SERVICE_ACCOUNT_JSON={"type":"service_account","project_id":"...","private_key_id":"...","private_key":"-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n","client_email":"...","client_id":"...","auth_uri":"https://accounts.google.com/o/oauth2/auth","token_uri":"https://oauth2.googleapis.com/token","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs","client_x509_cert_url":"..."}diff --git a/screenpipe-js/ai-proxy/VERTEX_PROXY_README.md b/screenpipe-js/ai-proxy/VERTEX_PROXY_README.mdnew file mode 100644index 000000000..3522d307c--- /dev/null+++ b/screenpipe-js/ai-proxy/VERTEX_PROXY_README.md@@ -0,0 +1,115 @@+# Vertex AI Proxy for Claude Agent SDK++This proxy allows the Claude Agent SDK to use Vertex AI without requiring users to set up GCP credentials. Users just log in to Screenpipe, and the proxy handles authentication with Vertex AI using Screenpipe's service account.++## How It Works++1. User logs in to Screenpipe desktop app+2. Desktop app configures Agent SDK with environment variables:+ - `CLAUDE_CODE_USE_VERTEX=1`+ - `ANTHROPIC_VERTEX_BASE_URL=https://ai-proxy.i-f9f.workers.dev` (or your worker URL)+ - `CLAUDE_CODE_SKIP_VERTEX_AUTH=1`+3. Agent SDK sends requests to the proxy+4. Proxy validates user's auth token (via Clerk)+5. Proxy authenticates with Vertex AI using service account+6. Proxy forwards request and returns response++## Setup (Worker)++### 1. Create GCP Service Account++1. Go to [GCP Console](https://console.cloud.google.com/)+2. Create a new service account or use existing+3. Grant "Vertex AI User" role+4. Create and download JSON key++### 2. Configure Worker Secrets++```bash+cd screenpipe-js/ai-proxy++# Set the service account JSON (paste entire JSON, escape quotes)+wrangler secret put VERTEX_SERVICE_ACCOUNT_JSON++# Set project ID+wrangler secret put VERTEX_PROJECT_ID+```++### 3. Deploy++```bash+wrangler deploy+```++## Local Development++1. Copy `.dev.vars.example` to `.dev.vars`+2. Fill in your credentials+3. Run `npm run dev`+4. Test with `./test-vertex-local.sh`++## Desktop App Integration++In your Tauri app, when spawning the Agent SDK:++```typescript+// Set environment variables for Agent SDK+const env = {+ CLAUDE_CODE_USE_VERTEX: '1',+ ANTHROPIC_VERTEX_BASE_URL: 'https://ai-proxy.i-f9f.workers.dev',+ CLAUDE_CODE_SKIP_VERTEX_AUTH: '1',+ // User's auth token for the proxy+ SCREENPIPE_AUTH_TOKEN: userAuthToken,+};++// The Agent SDK will use these env vars automatically+```++## API Endpoints++### POST /v1/messages++Proxies Anthropic Messages API requests to Vertex AI.++**Headers:**+- `Authorization: Bearer <user-token>` - User's Screenpipe auth token+- `Content-Type: application/json`++**Body:** Standard Anthropic Messages API format++**Example:**+```bash+curl -X POST https://ai-proxy.i-f9f.workers.dev/v1/messages \+ -H "Authorization: Bearer $USER_TOKEN" \+ -H "Content-Type: application/json" \+ -d '{+ "model": "claude-3-5-sonnet-v2@20241022",+ "max_tokens": 1024,+ "messages": [{"role": "user", "content": "Hello"}]+ }'+```++## Supported Models++- `claude-3-5-sonnet-v2@20241022` (recommended)+- `claude-3-5-haiku@20241022`+- `claude-3-opus@20240229`+- `claude-3-sonnet@20240229`+- `claude-3-haiku@20240307`+- `claude-sonnet-4@20250514`+- `claude-opus-4@20250514`++## Troubleshooting++### "Vertex AI service account not configured"+- Ensure `VERTEX_SERVICE_ACCOUNT_JSON` secret is set in the worker++### "Failed to get access token"+- Check service account JSON is valid+- Ensure service account has "Vertex AI User" role+- Check region is correct (us-east5 is recommended)++### "Vertex AI error: 403"+- Service account doesn't have permission+- Project doesn't have Vertex AI API enabled+- Quota exceededdiff --git a/screenpipe-js/ai-proxy/src/handlers/vertex-proxy.ts b/screenpipe-js/ai-proxy/src/handlers/vertex-proxy.tsnew file mode 100644index 000000000..f0e0def12--- /dev/null+++ b/screenpipe-js/ai-proxy/src/handlers/vertex-proxy.ts@@ -0,0 +1,112 @@+/**+ * Vertex AI Proxy Handler for Claude Agent SDK+ *+ * This handler proxies Anthropic Messages API requests to Vertex AI,+ * allowing users to use the Agent SDK without setting up GCP credentials.+ *+ * The Agent SDK sends requests to:+ * ANTHROPIC_VERTEX_BASE_URL/v1/messages+ *+ * This handler receives those requests and forwards them to Vertex AI+ * with proper authentication using the service account.+ */++import { Env } from '../types';+import { proxyToVertex } from '../providers/vertex';+import { addCorsHeaders } from '../utils/cors';++/**+ * Handle Vertex AI proxy requests for the Agent SDK+ */+export async function handleVertexProxy(request: Request, env: Env): Promise<Response> {+ // Validate required env vars+ if (!env.VERTEX_SERVICE_ACCOUNT_JSON) {+ return new Response(JSON.stringify({ error: 'Vertex AI service account not configured' }), {+ status: 500,+ headers: { 'Content-Type': 'application/json' },+ });+ }++ if (!env.VERTEX_PROJECT_ID) {+ return new Response(JSON.stringify({ error: 'Vertex AI project ID not configured' }), {+ status: 500,+ headers: { 'Content-Type': 'application/json' },+ });+ }++ const region = env.VERTEX_REGION || 'us-east5';++ try {+ const response = await proxyToVertex(request, env.VERTEX_SERVICE_ACCOUNT_JSON, env.VERTEX_PROJECT_ID, region);++ return addCorsHeaders(response);+ } catch (error: any) {+ console.error('Vertex proxy error:', error);+ return new Response(JSON.stringify({ error: error.message }), {+ status: 500,+ headers: { 'Content-Type': 'application/json' },+ });+ }+}++/**+ * Handle Vertex AI model listing+ */+export async function handleVertexModels(env: Env): Promise<Response> {+ const models = [+ {+ id: 'claude-3-5-sonnet-v2@20241022',+ object: 'model',+ created: 1729555200,+ owned_by: 'anthropic',+ },+ {+ id: 'claude-3-5-haiku@20241022',+ object: 'model',+ created: 1729555200,+ owned_by: 'anthropic',+ },+ {+ id: 'claude-3-opus@20240229',+ object: 'model',+ created: 1709164800,+ owned_by: 'anthropic',+ },+ {+ id: 'claude-3-sonnet@20240229',+ object: 'model',+ created: 1709164800,+ owned_by: 'anthropic',+ },+ {+ id: 'claude-3-haiku@20240307',+ object: 'model',+ created: 1709769600,+ owned_by: 'anthropic',+ },+ {+ id: 'claude-sonnet-4@20250514',+ object: 'model',+ created: 1747180800,+ owned_by: 'anthropic',+ },+ {+ id: 'claude-opus-4@20250514',+ object: 'model',+ created: 1747180800,+ owned_by: 'anthropic',+ },+ ];++ return addCorsHeaders(+ new Response(+ JSON.stringify({+ object: 'list',+ data: models,+ }),+ {+ headers: { 'Content-Type': 'application/json' },+ }+ )+ );+}diff --git a/screenpipe-js/ai-proxy/src/index.ts b/screenpipe-js/ai-proxy/src/index.tsindex b21033d58..29db533dc 100644--- a/screenpipe-js/ai-proxy/src/index.ts+++ b/screenpipe-js/ai-proxy/src/index.ts@@ -8,6 +8,7 @@ import { handleChatCompletions } from './handlers/chat';import { handleModelListing } from './handlers/models';import { handleFileTranscription, handleWebSocketUpgrade } from './handlers/transcription';import { handleVoiceTranscription, handleVoiceQuery, handleTextToSpeech, handleVoiceChat } from './handlers/voice';+import { handleVertexProxy, handleVertexModels } from './handlers/vertex-proxy';// import { handleTTSWebSocketUpgrade } from './handlers/voice-ws';export { RateLimiter };@@ -98,6 +99,13 @@ export default Sentry.withSentry(// return await handleTTSWebSocketUpgrade(request, env);// }+ // Vertex AI proxy for Agent SDK+ // The Agent SDK sends requests to ANTHROPIC_VERTEX_BASE_URL/v1/messages+ if (path === '/v1/messages' && request.method === 'POST') {+ console.log('Vertex AI proxy request to /v1/messages');+ return await handleVertexProxy(request, env);+ }+return createErrorResponse(404, 'not found');} catch (error) {console.error('error in fetch:', error);diff --git a/screenpipe-js/ai-proxy/src/providers/vertex.ts b/screenpipe-js/ai-proxy/src/providers/vertex.tsnew file mode 100644index 000000000..46da27c1b--- /dev/null+++ b/screenpipe-js/ai-proxy/src/providers/vertex.ts@@ -0,0 +1,476 @@+/**+ * Vertex AI Provider for proxying Claude requests to Google Cloud Vertex AI+ *+ * This provider allows the Agent SDK to use Vertex AI Claude models without+ * requiring users to set up GCP credentials themselves.+ */++import { AIProvider } from './base';+import { RequestBody } from '../types';++// Service account credentials structure+interface ServiceAccountCredentials {+ type: string;+ project_id: string;+ private_key_id: string;+ private_key: string;+ client_email: string;+ client_id: string;+ auth_uri: string;+ token_uri: string;+ auth_provider_x509_cert_url: string;+ client_x509_cert_url: string;+}++// Cache for access tokens+interface TokenCache {+ accessToken: string;+ expiresAt: number;+}++let tokenCache: TokenCache | null = null;++export class VertexAIProvider implements AIProvider {+ supportsTools = true;+ supportsVision = true;+ supportsJson = true;++ private credentials: ServiceAccountCredentials;+ private projectId: string;+ private region: string;++ constructor(serviceAccountJson: string, projectId: string, region: string = 'us-east5') {+ this.credentials = JSON.parse(serviceAccountJson);+ this.projectId = projectId || this.credentials.project_id;+ this.region = region;+ }++ /**+ * Generate a JWT for service account authentication+ */+ private async generateJWT(): Promise<string> {+ const header = {+ alg: 'RS256',+ typ: 'JWT',+ };++ const now = Math.floor(Date.now() / 1000);+ const payload = {+ iss: this.credentials.client_email,+ sub: this.credentials.client_email,+ aud: 'https://oauth2.googleapis.com/token',+ iat: now,+ exp: now + 3600, // 1 hour+ scope: 'https://www.googleapis.com/auth/cloud-platform',+ };++ const encodedHeader = this.base64urlEncode(JSON.stringify(header));+ const encodedPayload = this.base64urlEncode(JSON.stringify(payload));+ const signatureInput = `${encodedHeader}.${encodedPayload}`;++ const signature = await this.signWithRSA(signatureInput, this.credentials.private_key);+ return `${signatureInput}.${signature}`;+ }++ /**+ * Base64URL encode a string+ */+ private base64urlEncode(str: string): string {+ const base64 = btoa(str);+ return base64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');+ }++ /**+ * Sign data with RSA-SHA256 using the service account private key+ */+ private async signWithRSA(data: string, privateKeyPem: string): Promise<string> {+ // Import the private key+ const pemContents = privateKeyPem+ .replace('-----BEGIN PRIVATE KEY-----', '')+ .replace('-----END PRIVATE KEY-----', '')+ .replace(/\n/g, '');++ const binaryKey = Uint8Array.from(atob(pemContents), (c) => c.charCodeAt(0));++ const cryptoKey = await crypto.subtle.importKey(+ 'pkcs8',+ binaryKey,+ {+ name: 'RSASSA-PKCS1-v1_5',+ hash: 'SHA-256',+ },+ false,+ ['sign']+ );++ // Sign the data+ const encoder = new TextEncoder();+ const signature = await crypto.subtle.sign('RSASSA-PKCS1-v1_5', cryptoKey, encoder.encode(data));++ // Base64URL encode the signature+ const signatureArray = new Uint8Array(signature);+ const signatureBase64 = btoa(String.fromCharCode(...signatureArray));+ return signatureBase64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');+ }++ /**+ * Get an access token, using cache if valid+ */+ private async getAccessToken(): Promise<string> {+ // Check cache+ if (tokenCache && tokenCache.expiresAt > Date.now() + 60000) {+ return tokenCache.accessToken;+ }++ // Generate new token+ const jwt = await this.generateJWT();++ const response = await fetch('https://oauth2.googleapis.com/token', {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/x-www-form-urlencoded',+ },+ body: new URLSearchParams({+ grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',+ assertion: jwt,+ }),+ });++ if (!response.ok) {+ const error = await response.text();+ throw new Error(`Failed to get access token: ${error}`);+ }++ const data = (await response.json()) as { access_token: string; expires_in: number };++ // Cache the token+ tokenCache = {+ accessToken: data.access_token,+ expiresAt: Date.now() + data.expires_in * 1000,+ };++ return data.access_token;+ }++ /**+ * Get the Vertex AI endpoint URL for a model+ */+ private getEndpointUrl(model: string, streaming: boolean = false): string {+ // Map common model names to Vertex AI model IDs+ const modelMapping: Record<string, string> = {+ 'claude-3-opus': 'claude-3-opus@20240229',+ 'claude-3-sonnet': 'claude-3-sonnet@20240229',+ 'claude-3-haiku': 'claude-3-haiku@20240307',+ 'claude-3-5-sonnet': 'claude-3-5-sonnet@20240620',+ 'claude-3-5-sonnet-20240620': 'claude-3-5-sonnet@20240620',+ 'claude-3-5-sonnet-20241022': 'claude-3-5-sonnet-v2@20241022',+ 'claude-3-5-sonnet-v2': 'claude-3-5-sonnet-v2@20241022',+ 'claude-3-5-haiku': 'claude-3-5-haiku@20241022',+ 'claude-sonnet-4-20250514': 'claude-sonnet-4@20250514',+ 'claude-opus-4-20250514': 'claude-opus-4@20250514',+ };++ const vertexModel = modelMapping[model] || model;+ const method = streaming ? 'streamRawPredict' : 'rawPredict';++ return `https://${this.region}-aiplatform.googleapis.com/v1/projects/${this.projectId}/locations/${this.region}/publishers/anthropic/models/${vertexModel}:${method}`;+ }++ /**+ * Create a non-streaming completion+ */+ async createCompletion(body: RequestBody): Promise<Response> {+ const accessToken = await this.getAccessToken();+ const url = this.getEndpointUrl(body.model, false);++ // Convert to Anthropic Messages API format+ const anthropicBody = this.convertToAnthropicFormat(body);++ const response = await fetch(url, {+ method: 'POST',+ headers: {+ Authorization: `Bearer ${accessToken}`,+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify(anthropicBody),+ });++ if (!response.ok) {+ const error = await response.text();+ console.error('Vertex AI error:', error);+ throw new Error(`Vertex AI request failed: ${response.status} ${error}`);+ }++ const result = await response.json();++ // Convert Anthropic response to OpenAI format for compatibility+ return new Response(JSON.stringify(this.formatResponse(result as any)), {+ headers: { 'Content-Type': 'application/json' },+ });+ }++ /**+ * Create a streaming completion+ */+ async createStreamingCompletion(body: RequestBody): Promise<ReadableStream> {+ const accessToken = await this.getAccessToken();+ const url = this.getEndpointUrl(body.model, true);++ // Convert to Anthropic Messages API format+ const anthropicBody = this.convertToAnthropicFormat(body);+ anthropicBody.stream = true;++ const response = await fetch(url, {+ method: 'POST',+ headers: {+ Authorization: `Bearer ${accessToken}`,+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify(anthropicBody),+ });++ if (!response.ok) {+ const error = await response.text();+ console.error('Vertex AI streaming error:', error);+ throw new Error(`Vertex AI streaming request failed: ${response.status} ${error}`);+ }++ const reader = response.body!.getReader();+ const decoder = new TextDecoder();++ return new ReadableStream({+ async pull(controller) {+ const { done, value } = await reader.read();+ if (done) {+ controller.enqueue(new TextEncoder().encode('data: [DONE]\n\n'));+ controller.close();+ return;+ }++ const chunk = decoder.decode(value, { stream: true });+ const lines = chunk.split('\n');++ for (const line of lines) {+ if (line.startsWith('data: ')) {+ try {+ const data = JSON.parse(line.slice(6));+ if (data.type === 'content_block_delta' && data.delta?.type === 'text_delta') {+ controller.enqueue(+ new TextEncoder().encode(+ `data: ${JSON.stringify({+ choices: [{ delta: { content: data.delta.text } }],+ })}\n\n`+ )+ );+ }+ } catch (e) {+ // Skip invalid JSON+ }+ }+ }+ },+ });+ }++ /**+ * Convert OpenAI-style request to Anthropic Messages API format+ */+ private convertToAnthropicFormat(body: RequestBody): any {+ const systemMessage = body.messages.find((m) => m.role === 'system');+ const otherMessages = body.messages.filter((m) => m.role !== 'system');++ return {+ anthropic_version: 'vertex-2023-10-16',+ max_tokens: 4096,+ messages: otherMessages.map((m) => ({+ role: m.role === 'assistant' ? 'assistant' : 'user',+ content: typeof m.content === 'string' ? m.content : m.content,+ })),+ ...(systemMessage && { system: typeof systemMessage.content === 'string' ? systemMessage.content : '' }),+ ...(body.temperature !== undefined && { temperature: body.temperature }),+ ...(body.tools && { tools: this.formatTools(body.tools) }),+ };+ }++ /**+ * Format tools for Anthropic API+ */+ private formatTools(tools: any[]): any[] {+ return tools.map((tool) => ({+ name: tool.function?.name || tool.name,+ description: tool.function?.description || tool.description,+ input_schema: tool.function?.parameters || tool.input_schema,+ }));+ }++ /**+ * Format messages (required by AIProvider interface)+ */+ formatMessages(messages: any[]): any[] {+ return messages.map((m) => ({+ role: m.role === 'assistant' ? 'assistant' : 'user',+ content: typeof m.content === 'string' ? m.content : m.content,+ }));+ }++ /**+ * Format Anthropic response to OpenAI format+ */+ formatResponse(response: any): any {+ const textContent = response.content?.find((block: any) => block.type === 'text')?.text || '';++ return {+ choices: [+ {+ message: {+ content: textContent,+ role: 'assistant',+ tool_calls: response.content+ ?.filter((block: any) => block.type === 'tool_use')+ .map((block: any) => ({+ type: 'tool_use',+ function: {+ name: block.name,+ arguments: JSON.stringify(block.input),+ },+ })),+ },+ },+ ],+ };+ }++ /**+ * List available models+ */+ async listModels(): Promise<{ id: string; name: string; provider: string }[]> {+ return [+ { id: 'claude-3-5-sonnet-v2', name: 'Claude 3.5 Sonnet v2', provider: 'vertex-anthropic' },+ { id: 'claude-3-5-haiku', name: 'Claude 3.5 Haiku', provider: 'vertex-anthropic' },+ { id: 'claude-3-opus', name: 'Claude 3 Opus', provider: 'vertex-anthropic' },+ { id: 'claude-3-sonnet', name: 'Claude 3 Sonnet', provider: 'vertex-anthropic' },+ { id: 'claude-3-haiku', name: 'Claude 3 Haiku', provider: 'vertex-anthropic' },+ { id: 'claude-sonnet-4-20250514', name: 'Claude Sonnet 4', provider: 'vertex-anthropic' },+ { id: 'claude-opus-4-20250514', name: 'Claude Opus 4', provider: 'vertex-anthropic' },+ ];+ }+}++/**+ * Create a passthrough proxy for raw Anthropic API requests to Vertex AI+ * This is what the Agent SDK needs - it sends Anthropic-format requests+ * and expects Anthropic-format responses+ */+export async function proxyToVertex(+ request: Request,+ serviceAccountJson: string,+ projectId: string,+ region: string = 'us-east5'+): Promise<Response> {+ const provider = new VertexAIProvider(serviceAccountJson, projectId, region);++ // Parse the request path to get the model+ const url = new URL(request.url);+ const pathMatch = url.pathname.match(/\/v1\/messages/);++ if (!pathMatch) {+ return new Response(JSON.stringify({ error: 'Invalid endpoint' }), {+ status: 400,+ headers: { 'Content-Type': 'application/json' },+ });+ }++ try {+ const body = (await request.json()) as {+ model?: string;+ stream?: boolean;+ max_tokens?: number;+ messages?: any[];+ system?: string;+ temperature?: number;+ [key: string]: any;+ };+ const isStreaming = body.stream === true;++ // Get access token+ const accessToken = await (provider as any).getAccessToken();++ // Map model to Vertex format+ const model = body.model || 'claude-3-5-sonnet-v2@20241022';+ const vertexModel = mapModelToVertex(model);+ const method = isStreaming ? 'streamRawPredict' : 'rawPredict';+ const vertexUrl = `https://${region}-aiplatform.googleapis.com/v1/projects/${projectId}/locations/${region}/publishers/anthropic/models/${vertexModel}:${method}`;++ // Prepare the body for Vertex AI+ const vertexBody = {+ ...body,+ anthropic_version: 'vertex-2023-10-16',+ };+ delete vertexBody.model; // Vertex doesn't use model in body++ console.log('Proxying to Vertex AI:', vertexUrl);++ const response = await fetch(vertexUrl, {+ method: 'POST',+ headers: {+ Authorization: `Bearer ${accessToken}`,+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify(vertexBody),+ });++ if (!response.ok) {+ const error = await response.text();+ console.error('Vertex AI error:', error);+ return new Response(JSON.stringify({ error: `Vertex AI error: ${error}` }), {+ status: response.status,+ headers: { 'Content-Type': 'application/json' },+ });+ }++ // For streaming, return the response as-is+ if (isStreaming) {+ return new Response(response.body, {+ headers: {+ 'Content-Type': 'text/event-stream',+ 'Cache-Control': 'no-cache',+ Connection: 'keep-alive',+ },+ });+ }++ // For non-streaming, return JSON+ const result = await response.json();+ return new Response(JSON.stringify(result), {+ headers: { 'Content-Type': 'application/json' },+ });+ } catch (error: any) {+ console.error('Proxy error:', error);+ return new Response(JSON.stringify({ error: error.message }), {+ status: 500,+ headers: { 'Content-Type': 'application/json' },+ });+ }+}++function mapModelToVertex(model: string): string {+ const mapping: Record<string, string> = {+ 'claude-3-opus-20240229': 'claude-3-opus@20240229',+ 'claude-3-sonnet-20240229': 'claude-3-sonnet@20240229',+ 'claude-3-haiku-20240307': 'claude-3-haiku@20240307',+ 'claude-3-5-sonnet-20240620': 'claude-3-5-sonnet@20240620',+ 'claude-3-5-sonnet-20241022': 'claude-3-5-sonnet-v2@20241022',+ 'claude-3-5-haiku-20241022': 'claude-3-5-haiku@20241022',+ 'claude-sonnet-4-20250514': 'claude-sonnet-4@20250514',+ 'claude-opus-4-20250514': 'claude-opus-4@20250514',+ 'claude-opus-4-5-20251101': 'claude-opus-4-5@20251101',+ // Short names+ 'claude-3-opus': 'claude-3-opus@20240229',+ 'claude-3-sonnet': 'claude-3-sonnet@20240229',+ 'claude-3-haiku': 'claude-3-haiku@20240307',+ 'claude-3-5-sonnet': 'claude-3-5-sonnet-v2@20241022',+ 'claude-3-5-haiku': 'claude-3-5-haiku@20241022',+ };++ return mapping[model] || model;+}diff --git a/screenpipe-js/ai-proxy/src/test/vertex-proxy.test.ts b/screenpipe-js/ai-proxy/src/test/vertex-proxy.test.tsnew file mode 100644index 000000000..7d5510045--- /dev/null+++ b/screenpipe-js/ai-proxy/src/test/vertex-proxy.test.ts@@ -0,0 +1,152 @@+/**+ * Tests for Vertex AI proxy+ *+ * To run these tests locally:+ * 1. Set up your service account JSON in .dev.vars:+ * VERTEX_SERVICE_ACCOUNT_JSON='{"type":"service_account",...}'+ * VERTEX_PROJECT_ID='your-project-id'+ * VERTEX_REGION='us-east5'+ *+ * 2. Start the worker: npm run dev+ *+ * 3. Run tests: npx bun test src/test/vertex-proxy.test.ts+ * Or manually with curl (see examples below)+ */++import { describe, it, expect, beforeAll } from 'bun:test';++const HOST = process.env.TEST_HOST || 'http://localhost:8787';++describe('Vertex AI Proxy', () => {+ // Skip tests if no service account is configured+ const hasCredentials = process.env.VERTEX_SERVICE_ACCOUNT_JSON || process.env.SKIP_CREDENTIAL_CHECK;++ it('should return health check', async () => {+ const response = await fetch(`${HOST}/test`);+ expect(response.status).toBe(200);+ const text = await response.text();+ expect(text).toContain('ai proxy is working');+ });++ it('should handle /v1/messages endpoint', async () => {+ if (!hasCredentials) {+ console.log('Skipping test - no credentials configured');+ return;+ }++ const response = await fetch(`${HOST}/v1/messages`, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ Authorization: 'Bearer test-token',+ },+ body: JSON.stringify({+ model: 'claude-3-5-sonnet-v2@20241022',+ max_tokens: 100,+ messages: [+ {+ role: 'user',+ content: 'Say "hello" and nothing else.',+ },+ ],+ }),+ });++ console.log('Response status:', response.status);+ const data = await response.json();+ console.log('Response data:', JSON.stringify(data, null, 2));++ // If credentials are invalid, we'll get a 500 with error message+ // If valid, we should get 200 with response+ expect([200, 500]).toContain(response.status);+ });++ it('should handle streaming requests', async () => {+ if (!hasCredentials) {+ console.log('Skipping test - no credentials configured');+ return;+ }++ const response = await fetch(`${HOST}/v1/messages`, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ Authorization: 'Bearer test-token',+ },+ body: JSON.stringify({+ model: 'claude-3-5-sonnet-v2@20241022',+ max_tokens: 100,+ stream: true,+ messages: [+ {+ role: 'user',+ content: 'Count from 1 to 3.',+ },+ ],+ }),+ });++ console.log('Streaming response status:', response.status);+ expect([200, 500]).toContain(response.status);++ if (response.status === 200) {+ const reader = response.body?.getReader();+ if (reader) {+ const chunks: string[] = [];+ const decoder = new TextDecoder();++ while (true) {+ const { done, value } = await reader.read();+ if (done) break;+ chunks.push(decoder.decode(value, { stream: true }));+ }++ console.log('Received chunks:', chunks.length);+ expect(chunks.length).toBeGreaterThan(0);+ }+ }+ });+});++/*+Manual test commands:++# Start the worker+cd screenpipe-js/ai-proxy+npm run dev++# Test health check+curl http://localhost:8787/test++# Test /v1/messages (non-streaming)+curl -X POST http://localhost:8787/v1/messages \+ -H "Content-Type: application/json" \+ -H "Authorization: Bearer test-token" \+ -d '{+ "model": "claude-3-5-sonnet-v2@20241022",+ "max_tokens": 100,+ "messages": [+ {"role": "user", "content": "Say hello"}+ ]+ }'++# Test /v1/messages (streaming)+curl -X POST http://localhost:8787/v1/messages \+ -H "Content-Type: application/json" \+ -H "Authorization: Bearer test-token" \+ -d '{+ "model": "claude-3-5-sonnet-v2@20241022",+ "max_tokens": 100,+ "stream": true,+ "messages": [+ {"role": "user", "content": "Count from 1 to 5"}+ ]+ }'++# Test with Agent SDK (in your app)+export CLAUDE_CODE_USE_VERTEX=1+export ANTHROPIC_VERTEX_BASE_URL=http://localhost:8787+export CLAUDE_CODE_SKIP_VERTEX_AUTH=1++# Then run your Agent SDK code+*/diff --git a/screenpipe-js/ai-proxy/src/types.ts b/screenpipe-js/ai-proxy/src/types.tsindex 2addcfeb0..f3835d1a8 100644--- a/screenpipe-js/ai-proxy/src/types.ts+++ b/screenpipe-js/ai-proxy/src/types.ts@@ -124,6 +124,10 @@ export interface Env {SUPABASE_URL: string;SUPABASE_ANON_KEY: string;NODE_ENV: string;+ // Vertex AI credentials for Agent SDK proxy+ VERTEX_SERVICE_ACCOUNT_JSON: string;+ VERTEX_PROJECT_ID: string;+ VERTEX_REGION: string;}export interface ResponseUtils {diff --git a/screenpipe-js/ai-proxy/src/utils/auth.ts b/screenpipe-js/ai-proxy/src/utils/auth.tsindex 4acf21880..e6c906d93 100644--- a/screenpipe-js/ai-proxy/src/utils/auth.ts+++ b/screenpipe-js/ai-proxy/src/utils/auth.ts@@ -29,12 +29,19 @@ export async function verifyClerkToken(env: Env, token: string): Promise<boolean*/export async function validateAuth(request: Request, env: Env): Promise<{ isValid: boolean; error?: string }> {const authHeader = request.headers.get('Authorization');-+if (!authHeader || !(authHeader.startsWith('Bearer ') || authHeader.startsWith('Token '))) {return { isValid: false, error: 'unauthorized' };}const token = authHeader.split(' ')[1];++ // Allow test token in development mode+ if (env.NODE_ENV === 'development' && token === 'test-token') {+ console.log('using test token in development mode');+ return { isValid: true };+ }+let isValid = await validateSubscription(env, token);// If not valid, try to verify as a clerk tokendiff --git a/screenpipe-js/ai-proxy/test-vertex-local.sh b/screenpipe-js/ai-proxy/test-vertex-local.shnew file mode 100755index 000000000..5eeefdfc7--- /dev/null+++ b/screenpipe-js/ai-proxy/test-vertex-local.sh@@ -0,0 +1,52 @@+#!/bin/bash+# Local test script for Vertex AI proxy+#+# Usage:+# 1. Create .dev.vars with your credentials (see .dev.vars.example)+# 2. Start the worker: npm run dev (in another terminal)+# 3. Run this script: ./test-vertex-local.sh++HOST=${HOST:-http://localhost:8787}+TOKEN=${TOKEN:-test-token}++echo "Testing against: $HOST"+echo ""++# Test 1: Health check+echo "=== Test 1: Health check ==="+curl -s "$HOST/test"+echo ""+echo ""++# Test 2: Non-streaming request to /v1/messages+echo "=== Test 2: Non-streaming /v1/messages ==="+curl -s -X POST "$HOST/v1/messages" \+ -H "Content-Type: application/json" \+ -H "Authorization: Bearer $TOKEN" \+ -d '{+ "model": "claude-3-5-sonnet-v2@20241022",+ "max_tokens": 100,+ "messages": [+ {"role": "user", "content": "Say hello in exactly 3 words."}+ ]+ }' | jq .+echo ""++# Test 3: Streaming request to /v1/messages+echo "=== Test 3: Streaming /v1/messages ==="+curl -s -X POST "$HOST/v1/messages" \+ -H "Content-Type: application/json" \+ -H "Authorization: Bearer $TOKEN" \+ -d '{+ "model": "claude-3-5-sonnet-v2@20241022",+ "max_tokens": 100,+ "stream": true,+ "messages": [+ {"role": "user", "content": "Count from 1 to 3."}+ ]+ }' | while read -r line; do+ echo "$line"+done+echo ""++echo "=== Done ==="diff --git a/screenpipe-js/ai-proxy/wrangler.toml b/screenpipe-js/ai-proxy/wrangler.tomlindex 91cee9176..79680a069 100644--- a/screenpipe-js/ai-proxy/wrangler.toml+++ b/screenpipe-js/ai-proxy/wrangler.toml@@ -27,6 +27,12 @@ enabled = true# - https://developers.cloudflare.com/workers/configuration/secrets/[vars]# add any non-secret environment variables here+# Default Vertex AI region+VERTEX_REGION = "us-east5"++# Secrets (set via `wrangler secret put <NAME>`):+# - VERTEX_SERVICE_ACCOUNT_JSON: GCP service account JSON for Vertex AI+# - VERTEX_PROJECT_ID: Your GCP project ID# Bind the Workers AI model catalog. Run machine learning models, powered by serverless GPUs, on Cloudflare's global network# Docs: https://developers.cloudflare.com/workers/wrangler/configuration/#workers-aidiff --git a/screenpipe-server/src/analytics.rs b/screenpipe-server/src/analytics.rsnew file mode 100644index 000000000..97a868c93--- /dev/null+++ b/screenpipe-server/src/analytics.rs@@ -0,0 +1,98 @@+use once_cell::sync::Lazy;+use reqwest::Client;+use serde_json::{json, Value};+use std::env;+use std::sync::atomic::{AtomicBool, Ordering};+use tracing::{debug, error, trace};++const POSTHOG_API_KEY: &str = "phc_Bt8GoTBPgkCpDrbaIZzJIEYt0CrJjhBiuLaBck1clce";+const POSTHOG_HOST: &str = "https://eu.i.posthog.com";++static TELEMETRY_ENABLED: AtomicBool = AtomicBool::new(false);++static ANALYTICS: Lazy<Analytics> = Lazy::new(Analytics::new);++pub struct Analytics {+ client: Client,+ distinct_id: String,+}++impl Analytics {+ fn new() -> Self {+ // Try to get analytics ID from env var (passed from Tauri app)+ // Fall back to random UUID for standalone CLI usage+ let distinct_id = env::var("SCREENPIPE_ANALYTICS_ID")+ .unwrap_or_else(|_| uuid::Uuid::new_v4().to_string());++ debug!("Analytics initialized with distinct_id: {}", distinct_id);++ Self {+ client: Client::new(),+ distinct_id,+ }+ }++ pub fn distinct_id(&self) -> &str {+ &self.distinct_id+ }+}++/// Initialize analytics with telemetry enabled/disabled+pub fn init(telemetry_enabled: bool) {+ TELEMETRY_ENABLED.store(telemetry_enabled, Ordering::SeqCst);+ // Force lazy initialization+ let _ = &*ANALYTICS;+ debug!(+ "Analytics initialized, telemetry_enabled: {}",+ telemetry_enabled+ );+}++/// Get the current distinct_id+pub fn get_distinct_id() -> &'static str {+ ANALYTICS.distinct_id()+}++/// Capture an analytics event+pub async fn capture_event(event: &str, properties: Value) {+ if !TELEMETRY_ENABLED.load(Ordering::SeqCst) {+ return;+ }++ let mut props = properties;+ if let Some(obj) = props.as_object_mut() {+ obj.insert("distinct_id".to_string(), json!(ANALYTICS.distinct_id));+ obj.insert("$lib".to_string(), json!("screenpipe-server"));+ obj.insert("release".to_string(), json!(env!("CARGO_PKG_VERSION")));+ }++ let payload = json!({+ "api_key": POSTHOG_API_KEY,+ "event": event,+ "properties": props,+ });++ trace!(target: "analytics", "Capturing event: {} {:?}", event, payload);++ let client = &ANALYTICS.client;+ if let Err(e) = client+ .post(format!("{}/capture/", POSTHOG_HOST))+ .json(&payload)+ .timeout(std::time::Duration::from_secs(5))+ .send()+ .await+ {+ error!("Failed to send analytics event: {}", e);+ }+}++/// Capture event without blocking (fire and forget)+pub fn capture_event_nonblocking(event: &'static str, properties: Value) {+ if !TELEMETRY_ENABLED.load(Ordering::SeqCst) {+ return;+ }++ tokio::spawn(async move {+ capture_event(event, properties).await;+ });+}diff --git a/screenpipe-server/src/bin/screenpipe-server.rs b/screenpipe-server/src/bin/screenpipe-server.rsindex b1ff8b2a6..206cd9167 100644--- a/screenpipe-server/src/bin/screenpipe-server.rs+++ b/screenpipe-server/src/bin/screenpipe-server.rs@@ -17,6 +17,7 @@ use screenpipe_db::{create_migration_worker, DatabaseManager, MigrationCommand, MigrationConfig, MigrationStatus,};use screenpipe_server::{+ analytics,cli::{AudioCommand, Cli, CliAudioTranscriptionEngine, CliOcrEngine, Command, McpCommand,MigrationSubCommand, OutputFormat, PipeCommand, VisionCommand,@@ -630,6 +631,9 @@ async fn main() -> anyhow::Result<()> {let resource_monitor = ResourceMonitor::new(!cli.disable_telemetry);resource_monitor.start_monitoring(Duration::from_secs(30), Some(Duration::from_secs(60)));+ // Initialize analytics for API tracking+ analytics::init(!cli.disable_telemetry);+let db = Arc::new(DatabaseManager::new(&format!("{}/db.sqlite", local_data_dir.to_string_lossy())).awaitdiff --git a/screenpipe-server/src/lib.rs b/screenpipe-server/src/lib.rsindex 98060f250..fb75338a4 100644--- a/screenpipe-server/src/lib.rs+++ b/screenpipe-server/src/lib.rs@@ -1,4 +1,5 @@mod add;+pub mod analytics;mod auto_destruct;pub mod chunking;pub mod cli;diff --git a/screenpipe-server/src/resource_monitor.rs b/screenpipe-server/src/resource_monitor.rsindex 94f96e7b5..be146f6ba 100644--- a/screenpipe-server/src/resource_monitor.rs+++ b/screenpipe-server/src/resource_monitor.rs@@ -58,8 +58,9 @@ impl ResourceMonitor {debug!("Telemetry disabled, will not send performance data to PostHog");}- // Generate a unique ID for this installation- let distinct_id = uuid::Uuid::new_v4().to_string();+ // Use analytics ID from env var (passed from Tauri app) or generate random UUID+ let distinct_id = env::var("SCREENPIPE_ANALYTICS_ID")+ .unwrap_or_else(|_| uuid::Uuid::new_v4().to_string());Arc::new(Self {start_time: Instant::now(),diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rsindex c934d9d2b..34a6b2780 100644--- a/screenpipe-server/src/server.rs+++ b/screenpipe-server/src/server.rs@@ -31,6 +31,7 @@ use image::{GenericImageView, ImageFormat};use screenpipe_events::{send_event, subscribe_to_all_events, Event as ScreenpipeEvent};use crate::{+ analytics,embedding::embedding_endpoint::create_embeddings,video::{finish_ffmpeg_process, start_ffmpeg_process, write_frame_to_ffmpeg, MAX_FPS},video_cache::{AudioEntry, DeviceFrame, FrameCache, FrameMetadata, TimeSeriesFrame},@@ -445,6 +446,21 @@ pub(crate) async fn search(}info!("search completed: found {} results", total);++ // Track search analytics+ analytics::capture_event_nonblocking(+ "search_performed",+ serde_json::json!({+ "query_length": query.q.as_ref().map(|q| q.len()).unwrap_or(0),+ "content_type": format!("{:?}", query.content_type),+ "has_date_filter": query.start_time.is_some() || query.end_time.is_some(),+ "has_app_filter": query.app_name.is_some(),+ "result_count": total,+ "limit": query.pagination.limit,+ "offset": query.pagination.offset,+ }),+ );+Ok(JsonResponse(SearchResponse {data: content_items,pagination: PaginationInfo {