### Start Sonde Services with Docker Compose (Bash) Source: https://github.com/compiuta-origin/sonde-analytics/blob/main/README.md This command starts all the services defined in the Docker Compose file in detached mode. Ensure you are in the 'docker/' directory before running this command. It makes Sonde and its dependencies available. ```bash docker compose up -d ``` -------------------------------- ### Create Environment File (Bash) Source: https://github.com/compiuta-origin/sonde-analytics/blob/main/README.md This command copies the example environment file to '.env', which will be used to configure Sonde's settings, including API keys and database credentials. Ensure you create this file before modifying it. ```bash cp .env.example .env ``` -------------------------------- ### Verify Docker and Docker Compose Versions (Bash) Source: https://github.com/compiuta-origin/sonde-analytics/blob/main/README.md This command verifies that Docker and Docker Compose are installed and accessible on your system. It's a prerequisite for running Sonde via Docker Compose. ```bash docker --version docker compose version ``` -------------------------------- ### Clone Sonde Repository and Navigate to Docker Directory (Bash) Source: https://github.com/compiuta-origin/sonde-analytics/blob/main/README.md These commands clone the Sonde repository from GitHub and change the current directory to the 'docker' folder, where Docker Compose files are located. This is the first step in the local setup process. ```bash git clone https://github.com/compiuta-origin/sonde.git cd sonde/docker ``` -------------------------------- ### SQL Query to Store Service Role Key (SQL) Source: https://github.com/compiuta-origin/sonde-analytics/blob/main/README.md This SQL query, executed within Supabase Studio, securely stores your service role key in the vault. This is a crucial step for secure authentication and authorization after initial setup. ```sql SELECT vault.create_secret('your-service-role-key-value','service_role_key') ``` -------------------------------- ### Enable UFW Firewall (Bash) Source: https://github.com/compiuta-origin/sonde-analytics/blob/main/README.md This command enables the UFW firewall, applying the configured rules. Ensure SSH is allowed before enabling to avoid being locked out. ```bash sudo ufw enable ``` -------------------------------- ### POST /functions/v1/create-portal-session Source: https://context7.com/compiuta-origin/sonde-analytics/llms.txt Generates a Stripe customer portal session for billing and subscription management. ```APIDOC ## POST /functions/v1/create-portal-session ### Description Generates a Stripe customer portal session for managing subscriptions and billing. ### Method POST ### Endpoint /functions/v1/create-portal-session ### Response #### Success Response (200) - **url** (string) - The URL of the Stripe customer portal. #### Response Example { "url": "https://billing.stripe.com/session/..." } ``` -------------------------------- ### POST /functions/v1/executor Source: https://context7.com/compiuta-origin/sonde-analytics/llms.txt Internal background engine for prompt execution and credit management. ```APIDOC ## POST /functions/v1/executor ### Description Core background execution engine that runs prompts across multiple AI models with credit management. Requires service-role authentication. ### Method POST ### Endpoint /functions/v1/executor ### Parameters #### Request Body - **prompt_id** (string) - Required - The unique identifier of the prompt to process. ### Request Example { "prompt_id": "uuid-of-prompt" } ### Response #### Success Response (200) - **status** (string) - Execution process initiation status. ``` -------------------------------- ### Allow Required Ports with UFW (Bash) Source: https://github.com/compiuta-origin/sonde-analytics/blob/main/README.md These commands configure the Uncomplicated Firewall (UFW) on Ubuntu to allow incoming connections on SSH, HTTP (port 80), and HTTPS (port 443). This is essential for network security. ```bash sudo ufw allow OpenSSH sudo ufw allow 80/tcp sudo ufw allow 443/tcp ``` -------------------------------- ### Interact with AI Models using OpenRouter Client Source: https://context7.com/compiuta-origin/sonde-analytics/llms.txt The OpenRouter Client provides a unified interface for executing prompts and evaluations across various AI models through the OpenRouter API. It supports prompt execution with optional web search and judging AI responses based on predefined rules. The client returns response content, token usage, and evaluation results. ```typescript import { OpenRouterClient } from './openrouter-client.ts'; // Execute a prompt with optional web search const client = new OpenRouterClient(apiKey); const result = await client.executePrompt( 'What are the best project management tools in 2026?', 'anthropic/claude-sonnet-4.6', true, // enable web search 'high' // search context size: low, medium, or high ); console.log(result.response); // "Based on current market data, the leading project management tools include..." console.log(result.tokenUsage); // { input: 1523, output: 842 } // Judge an AI response against a rule const evaluation = await client.judge( result.response, 'Check if "Asana" is mentioned', 'binary' ); console.log(evaluation); // { score: 1, reasoning: "Asana is mentioned in the list of top tools" } // Evaluation types: // - binary: 0 (not mentioned) or 1 (mentioned) // - ranking: position number (1, 2, 3...) or 0 if not found // - sentiment: -1.0 (negative) to 1.0 (positive) ``` -------------------------------- ### POST /api/execute Source: https://context7.com/compiuta-origin/sonde-analytics/llms.txt Triggers the execution of a defined prompt across configured AI models for an authenticated user. ```APIDOC ## POST /api/execute ### Description Triggers execution of a prompt across configured AI models with authentication and ownership validation. ### Method POST ### Endpoint /api/execute ### Parameters #### Request Body - **prompt_id** (string) - Required - The unique identifier of the prompt to execute. ### Request Example { "prompt_id": "uuid-of-prompt" } ### Response #### Success Response (200) - **success** (boolean) - Indicates if execution started successfully. - **message** (string) - Status message. #### Response Example { "success": true, "message": "Execution started" } ``` -------------------------------- ### POST /functions/v1/create-checkout-session Source: https://context7.com/compiuta-origin/sonde-analytics/llms.txt Generates a Stripe checkout session for subscription upgrades. ```APIDOC ## POST /functions/v1/create-checkout-session ### Description Generates a Stripe checkout session for subscription upgrades with automatic customer creation. ### Method POST ### Endpoint /functions/v1/create-checkout-session ### Parameters #### Request Body - **lookupKey** (string) - Required - Stripe product lookup key (e.g., 'pro_monthly'). - **currency** (string) - Required - ISO currency code (e.g., 'USD'). ### Request Example { "lookupKey": "pro_monthly", "currency": "USD" } ### Response #### Success Response (200) - **sessionId** (string) - The generated Stripe checkout session ID. - **url** (string) - The checkout URL to redirect the user to. #### Response Example { "sessionId": "cs_test_...", "url": "https://checkout.stripe.com/..." } ``` -------------------------------- ### Check UFW Firewall Status (Bash) Source: https://github.com/compiuta-origin/sonde-analytics/blob/main/README.md This command displays the current status of the UFW firewall, showing which ports are allowed and if the firewall is active. It's used to verify the configuration. ```bash sudo ufw status ``` -------------------------------- ### Configure AI Model Tier Access Source: https://context7.com/compiuta-origin/sonde-analytics/llms.txt Utilities to map user subscription plans to authorized AI models and verify tier-based permissions. It ensures that users can only access models mapped to their specific subscription level. ```typescript import { getModelForTier, MODEL_FAMILIES_CONFIG } from './model-config.ts'; const model = getModelForTier('anthropic', 'pro'); function isModelAllowedForTier(modelId: string, tier: string): boolean { const tierHierarchy = ['free', 'pro', 'enterprise']; const tierIndex = tierHierarchy.indexOf(tier); const allowedTiers = tierIndex === -1 ? ['free'] : tierHierarchy.slice(0, tierIndex + 1); for (const family of MODEL_FAMILIES_CONFIG) { for (const allowedTier of allowedTiers) { if (getModelForTier(family.id, allowedTier).id === modelId) return true; } } return false; } ``` -------------------------------- ### Execute Prompt API Endpoint Source: https://context7.com/compiuta-origin/sonde-analytics/llms.txt Triggers the execution of a user-defined prompt across configured AI models. Requires authentication and ownership validation. Returns a success message or an error indicating unauthorized access, prompt not found, or insufficient credits. ```typescript // POST /api/execute const response = await fetch('http://app.localhost/api/execute', { method: 'POST', headers: { 'Authorization': `Bearer ${accessToken}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ prompt_id: 'uuid-of-prompt' }) }); const result = await response.json(); // Expected response: // { "success": true, "message": "Execution started" } // Error cases: // { "error": "Unauthorized" } (401) // { "error": "Prompt not found" } (404) // { "error": "Insufficient credits..." } (400) ``` -------------------------------- ### Manage Subscription Access Source: https://context7.com/compiuta-origin/sonde-analytics/llms.txt Client-side utilities to fetch current subscription status, determine effective access levels, and resolve the correct subscription record from a list of history. ```typescript import { getCurrentSubscription, hasProAccess, getResolvedPlan, pickCurrentSubscription } from './subscription'; const subscription = await getCurrentSubscription(); if (hasProAccess(subscription)) { console.log('User has pro or enterprise access'); } const plan = getResolvedPlan(subscription); const current = pickCurrentSubscription(subscriptions); ``` -------------------------------- ### Update Sonde Application (Bash) Source: https://github.com/compiuta-origin/sonde-analytics/blob/main/README.md These commands update the Sonde application by pulling the latest changes from the Git repository, updating Docker images, and restarting the services with a build. This ensures you are running the most recent version. ```bash cd sonde git pull cd docker docker compose pull docker compose up -d --build ``` -------------------------------- ### Create Stripe Portal Session API Endpoint Source: https://context7.com/compiuta-origin/sonde-analytics/llms.txt Generates a Stripe customer portal session, allowing users to manage their subscriptions, payment methods, and billing history. Requires user authentication. ```typescript // POST /functions/v1/create-portal-session const response = await fetch('http://api.localhost/functions/v1/create-portal-session', { method: 'POST', headers: { 'Authorization': `Bearer ${userJwt}`, 'Content-Type': 'application/json' } }); const { url } = await response.json(); // Response: { "url": "https://billing.stripe.com/session/..." } // User can manage subscriptions, payment methods, and billing history ``` -------------------------------- ### POST /functions/v1/stripe-webhook Source: https://context7.com/compiuta-origin/sonde-analytics/llms.txt Endpoint for Stripe to push event notifications for subscription lifecycle management. ```APIDOC ## POST /functions/v1/stripe-webhook ### Description Handles Stripe webhook events to synchronize subscription statuses (active, trialing, canceled, past_due) within the local database. ### Method POST ### Endpoint /functions/v1/stripe-webhook ### Request Body - Payload varies per Stripe event type (e.g., checkout.session.completed, customer.subscription.updated). ### Response #### Success Response (200) - Acknowledge receipt of the webhook event. ``` -------------------------------- ### POST /functions/v1/scheduler Source: https://context7.com/compiuta-origin/sonde-analytics/llms.txt Triggered by cron jobs to execute scheduled tasks, featuring exponential backoff logic for failed jobs. ```APIDOC ## POST /functions/v1/scheduler ### Description Automated cron-based job scheduler that processes pending tasks and applies exponential backoff for failed executions. ### Method POST ### Endpoint /functions/v1/scheduler ### Request Body - None ### Request Example {} ### Response #### Success Response (200) - **success** (boolean) - Execution status. - **processed** (array) - List of objects detailing job IDs, their new status, and the next run time. #### Response Example { "success": true, "processed": [ { "id": "uuid", "status": "scheduled", "next_run": "2026-03-30T10:00:00Z" }, { "id": "uuid", "status": "backoff", "next_run": "2026-03-30T10:04:00Z", "failed_attempts": 2 } ] } ``` -------------------------------- ### Calculate Exponential Backoff Source: https://context7.com/compiuta-origin/sonde-analytics/llms.txt Implements an exponential delay algorithm for task retries. It calculates a progressively increasing wait time, capped at 24 hours, to handle failed executions. ```typescript function calculateExponentialBackoff(failedAttempts: number): number { const backoffMinutes = Math.min(Math.pow(2, failedAttempts) * 1, 24 * 60); return backoffMinutes; } // Usage in scheduler: const backoffMinutes = calculateExponentialBackoff(failedAttempts); const retryTime = new Date(lastFailureAt.getTime() + backoffMinutes * 60000); ``` -------------------------------- ### Create Stripe Checkout Session API Endpoint Source: https://context7.com/compiuta-origin/sonde-analytics/llms.txt Generates a Stripe checkout session for users to upgrade their subscriptions. It handles automatic customer creation and returns a session ID and URL for redirection. Supports specified currency. ```typescript // POST /functions/v1/create-checkout-session const response = await fetch('http://api.localhost/functions/v1/create-checkout-session', { method: 'POST', headers: { 'Authorization': `Bearer ${userJwt}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ lookupKey: 'pro_monthly', currency: 'USD' }) }); const { sessionId, url } = await response.json(); // Response: { "sessionId": "cs_test_...", "url": "https://checkout.stripe.com/..." } // Redirects to: http://app.localhost/dashboard?success=true (success) // Or: http://app.localhost/upgrade?canceled=true (cancel) ``` -------------------------------- ### POST /functions/v1/judge Source: https://context7.com/compiuta-origin/sonde-analytics/llms.txt Evaluates AI-generated responses against user-defined rules. Supports binary, ranking, and sentiment analysis scoring. ```APIDOC ## POST /functions/v1/judge ### Description Evaluates AI responses against user-defined rules for visibility, ranking, and sentiment analysis. ### Method POST ### Endpoint /functions/v1/judge ### Request Body - **run_id** (string) - Required - The unique identifier of the AI execution run to be evaluated. ### Request Example { "run_id": "uuid-of-run" } ### Response #### Success Response (200) - **run_id** (string) - The ID of the evaluated run. - **rule_id** (string) - The ID of the rule applied. - **score** (number) - The calculated score based on the evaluation type. - **reasoning** (string) - Qualitative explanation of the score. #### Response Example { "run_id": "uuid", "rule_id": "uuid", "score": 1, "reasoning": "Brand mentioned in first paragraph as industry leader" } ``` -------------------------------- ### Generate Secure Secrets (Bash) Source: https://github.com/compiuta-origin/sonde-analytics/blob/main/README.md This script generates secure random keys for various services used by Sonde, such as JWT secrets and database passwords. It overwrites the corresponding values in the '.env' file. ```bash ./utils/generate-keys.sh ``` -------------------------------- ### Stop and Remove Sonde Volumes (Bash) Source: https://github.com/compiuta-origin/sonde-analytics/blob/main/README.md This command stops the Sonde services and removes the associated Docker volumes. Use this with caution as it will destroy all database data. ```bash docker compose down -v ``` -------------------------------- ### SQL Query to View Decrypted Secrets (SQL) Source: https://github.com/compiuta-origin/sonde-analytics/blob/main/README.md This query allows you to view all currently stored secrets in the vault, including the service role key. Use this for verification purposes after storing secrets. ```sql SELECT * from vault.decrypted_secrets ``` -------------------------------- ### Handle Stripe Subscriptions with Webhook Handler Source: https://context7.com/compiuta-origin/sonde-analytics/llms.txt The Stripe Webhook Handler processes Stripe events to manage the subscription lifecycle. It automatically handles events like checkout completion, subscription updates, and deletions, updating the subscriptions table accordingly. Signature verification is a mandatory security step. ```typescript // POST /functions/v1/stripe-webhook // Automatically called by Stripe (no manual invocation needed) // Handled events: // - checkout.session.completed: Creates/updates subscription record // - customer.subscription.updated: Updates status, plan, and period // - customer.subscription.deleted: Marks subscription as canceled // Webhook signature verification required // Updates subscriptions table with status: active, trialing, canceled, past_due ``` -------------------------------- ### Internal Executor Function Logic Source: https://context7.com/compiuta-origin/sonde-analytics/llms.txt The core background service responsible for executing prompts across multiple AI models. It manages credit deduction, execution locking, tier validation, calls to OpenRouter, response evaluation, and implements exponential backoff for failed executions. ```typescript // POST /functions/v1/executor (internal, service-role auth required) const response = await fetch('http://api.localhost/functions/v1/executor', { method: 'POST', headers: { 'Authorization': `Bearer ${serviceRoleKey}`, 'Content-Type': 'application/json', 'apikey': serviceRoleKey }, body: JSON.stringify({ prompt_id: 'uuid-of-prompt' }) }); // Process: // 1. Validates credits_balance > 0 // 2. Acquires execution lock (prevents duplicate runs) // 3. Resolves user tier (free/pro/enterprise) from subscriptions // 4. Executes prompt across target_config models // 5. Validates each model is allowed for user's tier // 6. Calls OpenRouter with optional web search // 7. Saves runs to database with token usage // 8. Triggers judge function for each successful run // 9. Deducts 1 credit if all models succeed // 10. Implements exponential backoff for failures ``` -------------------------------- ### Automate Jobs with Scheduler Function Source: https://context7.com/compiuta-origin/sonde-analytics/llms.txt The Scheduler function is an automated cron-based job scheduler that includes exponential backoff for failed executions. It requires service-role authentication and is called by cron. The function returns processing status and next run times, with backoff delays increasing for subsequent failures. ```typescript // POST /functions/v1/scheduler (called by cron, service-role auth required) const response = await fetch('http://api.localhost/functions/v1/scheduler', { method: 'POST', headers: { 'Authorization': `Bearer ${serviceRoleKey}`, 'Content-Type': 'application/json' } }); // Backoff calculation: // failed_attempts=0: immediate execution // failed_attempts=1: 2 minutes delay // failed_attempts=2: 4 minutes delay // failed_attempts=3+: falls back to regular cron schedule // Maximum backoff: 24 hours // Response example: // { // "success": true, // "processed": [ // { "id": "uuid", "status": "scheduled", "next_run": "2026-03-30T10:00:00Z" }, // { "id": "uuid", "status": "backoff", "next_run": "2026-03-30T10:04:00Z", "failed_attempts": 2 } // ] // } ``` -------------------------------- ### Stop Sonde Services with Docker Compose (Bash) Source: https://github.com/compiuta-origin/sonde-analytics/blob/main/README.md This command stops the running Sonde services. It gracefully shuts down the containers managed by Docker Compose. ```bash docker compose down ``` -------------------------------- ### Atomic Credit Deduction Source: https://context7.com/compiuta-origin/sonde-analytics/llms.txt Server-side database function for atomic credit decrements with validation. Provides a thread-safe check-and-deduct mechanism via Supabase RPC. ```sql SELECT * FROM decrement_profile_credits_if_available( p_profile_id := 'user-uuid', p_amount := 1 ); ``` ```typescript const { data: creditData, error } = await supabase.rpc( 'decrement_profile_credits_if_available', { p_profile_id: profileId, p_amount: 1 } ); ``` -------------------------------- ### Recover Stale Execution Locks in TypeScript Source: https://context7.com/compiuta-origin/sonde-analytics/llms.txt Implements an automatic lock recovery mechanism for execution tasks that exceed the defined timeout threshold. It checks for stale run states and uses optimistic locking via Supabase to safely reset execution status. ```typescript import { getStaleLockTimeoutMinutes } from './_shared/stale-lock.ts'; const staleLockTimeoutMinutes = getStaleLockTimeoutMinutes(); const staleLockCutoff = new Date(Date.now() - staleLockTimeoutMinutes * 60000); const runStartedAt = prompt.run_started_at ? new Date(prompt.run_started_at) : null; const hasStaleLock = prompt.is_running && (!runStartedAt || runStartedAt <= staleLockCutoff); if (hasStaleLock) { console.log('Lock is stale, attempting recovery'); const { data } = await supabase .from('prompts') .update({ is_running: true, run_started_at: new Date().toISOString() }) .eq('id', promptId) .eq('is_running', true) .eq('run_started_at', prompt.run_started_at) .select() .single(); if (data) { console.log('Successfully recovered stale lock'); } } ``` -------------------------------- ### Evaluate AI Responses with Judge Function Source: https://context7.com/compiuta-origin/sonde-analytics/llms.txt The Judge function evaluates AI responses against user-defined rules for visibility, ranking, and sentiment analysis. It requires service-role authentication and accepts a run ID. The function returns a score and reasoning for the evaluation. ```typescript // POST /functions/v1/judge (internal, service-role auth required) const response = await fetch('http://api.localhost/functions/v1/judge', { method: 'POST', headers: { 'Authorization': `Bearer ${serviceRoleKey}`, 'Content-Type': 'application/json', 'apikey': serviceRoleKey }, body: JSON.stringify({ run_id: 'uuid-of-run' }) }); // Evaluation types: // - binary: score 0 or 1 (mentioned/not mentioned) // - ranking: score is position number (1=first, 0=not found) // - sentiment: score -1 to 1 (negative to positive) // Example evaluation stored in database: // { // "run_id": "uuid", // "rule_id": "uuid", // "score": 1, // "reasoning": "Brand mentioned in first paragraph as industry leader" // } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.