### Environment Setup Scenarios Source: https://github.com/revenium/revenium-claude-code-sdk/blob/main/examples/README.md Specific CLI configurations for different organizational tiers and development environments. These commands set the API key, email, and tier/endpoint requirements. ```bash # Personal Developer Setup revenium-metering setup --api-key hak_your_api_key --email developer@company.com --tier pro # Team Setup revenium-metering setup --api-key hak_team_key --email team@company.com --tier team_premium # Enterprise Setup revenium-metering setup --api-key hak_enterprise_key --email admin@enterprise.com --tier enterprise # Local Development/Testing revenium-metering setup --api-key hak_dev_key --endpoint http://localhost:8082 --tier api ``` -------------------------------- ### Development Setup and Commands (Bash) Source: https://github.com/revenium/revenium-claude-code-sdk/blob/main/CONTRIBUTING.md This snippet provides essential bash commands for setting up the development environment for the revenium-claude-code-sdk. It includes cloning the repository, installing dependencies, running the project in development mode, executing tests, building for production, and testing the CLI locally. ```bash # Clone your fork git clone https://github.com/YOUR-USERNAME/revenium-claude-code-sdk.git cd revenium-claude-code-sdk # Install dependencies npm install # Run in development mode npm run dev # Run tests npm test # Build for production npm run build # Test CLI locally npm run cli -- setup --help ``` -------------------------------- ### Configure Revenium Metering via CLI Source: https://github.com/revenium/revenium-claude-code-sdk/blob/main/examples/README.md Commands to initialize the Revenium metering service. Supports interactive wizards for personal use or non-interactive flags for CI/CD environments. ```bash revenium-metering setup revenium-metering setup --api-key hak_... --tier pro ``` -------------------------------- ### Setup Revenium Metering for Local Development Testing Source: https://github.com/revenium/revenium-claude-code-sdk/blob/main/README.md Configure the `revenium-metering` CLI for local development testing by specifying a test API key, a local endpoint, and a tier. This requires a local metering service running on port 8082 with Kafka connectivity. ```bash revenium-metering setup \ --api-key hak_your_test_key \ --endpoint http://localhost:8082 \ --tier pro ``` -------------------------------- ### Verify Metering Configuration Source: https://github.com/revenium/revenium-claude-code-sdk/blob/main/examples/README.md Commands to validate that the Revenium environment variables are correctly loaded and the service is communicating with the backend. ```bash cat ~/.claude/revenium.env source ~/.claude/revenium.env echo $OTEL_METRICS_EXPORTER revenium-metering status revenium-metering test --verbose ``` -------------------------------- ### Verify Telemetry Configuration and Send Test Metric Source: https://github.com/revenium/revenium-claude-code-sdk/blob/main/README.md Use `revenium-metering` commands to check the status of your telemetry configuration, verify that environment variables are loaded correctly, and send a test metric to ensure the setup is working. ```bash revenium-metering status echo $OTEL_LOGS_EXPORTER echo $CLAUDE_CODE_ENABLE_TELEMETRY revenium-metering test --verbose ``` -------------------------------- ### Override Cost Multiplier Source: https://github.com/revenium/revenium-claude-code-sdk/blob/main/examples/README.md Instructions for modifying the cost multiplier by updating the environment configuration file and reloading the session. ```bash export OTEL_RESOURCE_ATTRIBUTES="cost_multiplier=0.12" source ~/.claude/revenium.env ``` -------------------------------- ### Configure Claude Code Telemetry via CLI Source: https://context7.com/revenium/revenium-claude-code-sdk/llms.txt The setup command initializes the telemetry configuration by validating API keys and updating shell profiles. It supports both interactive and non-interactive modes with various configuration flags. ```bash # Interactive setup npx @revenium/claude-code-metering setup # Non-interactive setup with all options npx @revenium/claude-code-metering setup \ --api-key hak_your_key_here \ --email developer@company.com \ --tier max_20x \ --organization engineering \ --product backend-api # Setup with custom endpoint (for development/testing) npx @revenium/claude-code-metering setup \ --api-key hak_test_key \ --endpoint http://localhost:8082 \ --tier pro # Skip automatic shell profile update npx @revenium/claude-code-metering setup \ --api-key hak_your_key \ --skip-shell-update ``` -------------------------------- ### Manage Configuration Programmatically Source: https://context7.com/revenium/revenium-claude-code-sdk/llms.txt The TypeScript SDK allows developers to load, validate, and write configuration files programmatically. This is useful for custom tool integrations or automated environment setup. ```typescript import { loadConfig, configExists, isEnvLoaded, getConfigPath, writeConfig, } from "@revenium/claude-code-metering"; // Check if configuration exists if (configExists()) { console.log(`Config found at: ${getConfigPath()}`); } // Load existing configuration const config = await loadConfig(); if (config) { console.log(`API Key: ${config.apiKey}`); console.log(`Endpoint: ${config.endpoint}`); console.log(`Email: ${config.email}`); console.log(`Tier: ${config.subscriptionTier}`); console.log(`Organization: ${config.organizationName}`); console.log(`Product: ${config.productName}`); } // Check if environment variables are loaded in current shell if (isEnvLoaded()) { console.log("Telemetry environment is active"); } // Write new configuration const configPath = await writeConfig({ apiKey: "hak_tenant_secretkey123", endpoint: "https://api.revenium.ai", email: "developer@company.com", subscriptionTier: "max_20x", organizationName: "engineering", productName: "backend-api", }); console.log(`Configuration written to: ${configPath}`); ``` -------------------------------- ### Detect Shell and Manage Profiles Source: https://context7.com/revenium/revenium-claude-code-sdk/llms.txt Provides helper functions to identify the current shell environment and retrieve the corresponding profile configuration path. Useful for automated setup scripts. ```typescript import { detectShell, getProfilePath, } from "@revenium/claude-code-metering"; // Detect current shell type const shellType = detectShell(); // Returns: 'bash' | 'zsh' | 'fish' | 'unknown' console.log(`Detected shell: ${shellType}`); // Get shell profile path const profilePath = getProfilePath(shellType); console.log(`Profile path: ${profilePath}`); ``` -------------------------------- ### Example settings.json Telemetry Configuration Source: https://github.com/revenium/revenium-claude-code-sdk/blob/main/docs/research/settings-json-telemetry-findings.md Demonstrates the expected structure for configuring environment variables, including telemetry settings, within Claude Code's settings.json file. This configuration is intended to be applied to all Claude Code interfaces. ```json { "env": { "CLAUDE_CODE_ENABLE_TELEMETRY": "1", "OTEL_EXPORTER_OTLP_ENDPOINT": "https://api.example.com/meter/v2/otlp", "OTEL_EXPORTER_OTLP_HEADERS": "x-api-key=hak_xxx" } } ``` -------------------------------- ### Run Project Tests Source: https://github.com/revenium/revenium-claude-code-sdk/blob/main/README.md Execute the project's test suite using npm. Includes commands for running all tests and for running tests with coverage reporting enabled. ```bash npm test npm test -- --coverage ``` -------------------------------- ### Configure Revenium Claude Code CLI Flags Source: https://github.com/revenium/revenium-claude-code-sdk/blob/main/README.md Sets up Revenium metering with API key, subscription tier, organization, and product. This is the recommended method for attribution. ```bash revenium-metering setup \ --api-key hak_your_key \ --tier max_20x \ --organization engineering \ --product backend-api ``` -------------------------------- ### Configure Revenium Claude Code Environment Variables Source: https://github.com/revenium/revenium-claude-code-sdk/blob/main/README.md Updates the OTEL_RESOURCE_ATTRIBUTES environment variable to include organization and product names for cost attribution. Requires reloading the environment file. ```bash # Before: export OTEL_RESOURCE_ATTRIBUTES="CLAUDE_CODE_SUBSCRIPTION_TIER=max_20x,user.email=dev@company.com" # After: export OTEL_RESOURCE_ATTRIBUTES="organization.name=engineering,product.name=backend-api,CLAUDE_CODE_SUBSCRIPTION_TIER=max_20x,user.email=dev@company.com" # Then reload: source ~/.claude/revenium.env ``` -------------------------------- ### Verifying Environment Variables in Claude Code (Bash) Source: https://github.com/revenium/revenium-claude-code-sdk/blob/main/docs/research/settings-json-telemetry-findings.md Illustrates how to verify if environment variables, specifically those related to OpenTelemetry (OTEL), are correctly set within a Claude Code session. This involves using the 'env' command prefixed with '!' to execute a shell command. ```bash # INSIDE Claude Code (! prefix runs shell command): ! env | grep OTEL # Shows all OTEL vars correctly ✓ # OUTSIDE Claude Code (after exiting): env | grep OTEL # Shows NOTHING - vars not in shell ✗ ``` -------------------------------- ### Verify Integration with Test Metrics Source: https://context7.com/revenium/revenium-claude-code-sdk/llms.txt The test command sends a sample metric to the Revenium backend to ensure that the telemetry pipeline is correctly configured and operational. ```bash # Send a test metric npx @revenium/claude-code-metering test # Show detailed payload information npx @revenium/claude-code-metering test --verbose ``` -------------------------------- ### Configure VS Code Environment Variables for Telemetry Source: https://github.com/revenium/revenium-claude-code-sdk/blob/main/README.md Add specific environment variables to VS Code's `settings.json` to enable and configure telemetry for Claude Code. This includes setting the endpoint, API key, and resource attributes for cost attribution. ```json { "terminal.integrated.env.osx": { "CLAUDE_CODE_ENABLE_TELEMETRY": "1", "OTEL_LOGS_EXPORTER": "otlp", "OTEL_EXPORTER_OTLP_ENDPOINT": "https://api.revenium.ai/meter/v2/otlp", "OTEL_EXPORTER_OTLP_HEADERS": "x-api-key=hak_YOUR_API_KEY_HERE", "OTEL_EXPORTER_OTLP_PROTOCOL": "http/json", "OTEL_RESOURCE_ATTRIBUTES": "organization.name=my-org,product.name=my-product,CLAUDE_CODE_SUBSCRIPTION_TIER=max_20x,user.email=dev@company.com" } } ``` -------------------------------- ### Backfill Historical Usage Data Source: https://context7.com/revenium/revenium-claude-code-sdk/llms.txt The backfill command processes local Claude Code session files to import historical usage data into the Revenium metering system. It supports dry runs, date filtering, and batch processing controls. ```bash # Preview what would be sent (recommended first step) npx @revenium/claude-code-metering backfill --dry-run # Backfill only the last 30 days npx @revenium/claude-code-metering backfill --since 30d # Backfill since a specific date with verbose output npx @revenium/claude-code-metering backfill --since 2024-12-01 --verbose # Full backfill with custom batch settings npx @revenium/claude-code-metering backfill \ --batch-size 50 \ --delay 200 ``` -------------------------------- ### Perform API Client Operations with TypeScript Source: https://context7.com/revenium/revenium-claude-code-sdk/llms.txt Demonstrates how to verify API keys, perform endpoint health checks, and send OTLP logs to the Revenium endpoint. These functions require a valid API key and endpoint URL to communicate with the service. ```typescript import { sendOtlpLogs, checkEndpointHealth, verifyApiKey, createTestPayload, generateTestSessionId, } from "@revenium/claude-code-metering"; // Verify an API key is valid const isValid = await verifyApiKey( "https://api.revenium.ai", "hak_tenant_secretkey123" ); console.log(`API key valid: ${isValid}`); // Perform endpoint health check const health = await checkEndpointHealth( "https://api.revenium.ai", "hak_tenant_secretkey123", { email: "developer@company.com", organizationName: "engineering", productName: "backend-api", } ); if (health.healthy) { console.log(`Endpoint healthy (${health.latencyMs}ms)`); } else { console.error(`Endpoint error: ${health.message}`); } // Send custom OTLP logs payload const sessionId = generateTestSessionId(); const payload = createTestPayload(sessionId, { email: "developer@company.com", organizationName: "engineering", }); const response = await sendOtlpLogs( "https://api.revenium.ai", "hak_tenant_secretkey123", payload ); console.log(`Processed ${response.processedEvents} events`); console.log(`Response ID: ${response.id}`); ``` -------------------------------- ### Access Configuration Constants and Subscription Types Source: https://context7.com/revenium/revenium-claude-code-sdk/llms.txt Exposes core constants such as API endpoints, environment variable keys, and subscription tier definitions. These constants help maintain consistency across the application when configuring telemetry and metering settings. ```typescript import { DEFAULT_REVENIUM_URL, OTLP_PATH, API_KEY_PREFIX, SUBSCRIPTION_TIER_CONFIG, SUBSCRIPTION_TIERS, ENV_VARS } from "@revenium/claude-code-metering"; console.log(DEFAULT_REVENIUM_URL); console.log(OTLP_PATH); console.log(API_KEY_PREFIX); for (const tier of SUBSCRIPTION_TIERS) { const config = SUBSCRIPTION_TIER_CONFIG[tier]; console.log(`${tier}: ${config.name}`); } console.log(ENV_VARS.TELEMETRY_ENABLED); console.log(ENV_VARS.OTLP_ENDPOINT); ``` -------------------------------- ### Implement Tool Metering and Telemetry Source: https://context7.com/revenium/revenium-claude-code-sdk/llms.txt Provides methods to wrap tool executions for automatic timing, error tracking, and metadata collection. Supports both global and scoped context management for complex tool call workflows. ```typescript import { meterTool, reportToolCall, setToolContext, getToolContext, clearToolContext, runWithToolContext, } from "@revenium/claude-code-metering"; // Set global context for all tool calls setToolContext({ sessionId: "session-abc123", userId: "user-456", organizationName: "engineering", productName: "backend-api", apiKey: "hak_tenant_secretkey123", endpoint: "https://api.revenium.ai", }); // Meter a simple async function const result = await meterTool("weather-api", async () => { const response = await fetch("https://api.example.com/weather?city=NYC"); return response.json(); }); // Meter with metadata and auto-extract fields from result const weatherData = await meterTool( "weather-api", async () => { const res = await fetch("https://api.example.com/weather?city=NYC"); return res.json(); }, { description: "Fetch weather forecast", category: "external-api", version: "1.0.0", tags: ["weather", "forecast"], outputFields: ["temperature", "humidity", "conditions"], usageMetadata: { city: "NYC", units: "metric", }, } ); // Report a tool call that was already executed reportToolCall("database-query", { success: true, durationMs: 45, metadata: { description: "User lookup query", category: "database", usageMetadata: { rowsReturned: 1, queryType: "SELECT", }, }, }); // Report a failed tool call reportToolCall("payment-api", { success: false, durationMs: 1500, errorMessage: "Connection timeout", metadata: { description: "Process payment", category: "external-api", }, }); // Run function with scoped context (isolated from global context) const resultWithContext = await runWithToolContext( { sessionId: "isolated-session", userId: "special-user", organizationName: "special-org", }, async () => { return await meterTool("isolated-tool", async () => { return { status: "ok" }; }); } ); // Get and clear context const currentContext = getToolContext(); console.log(`Current session: ${currentContext.sessionId}`); clearToolContext(); ``` -------------------------------- ### Meter Custom Tool Execution in TypeScript Source: https://github.com/revenium/revenium-claude-code-sdk/blob/main/README.md Wraps a function with automatic metering using the `meterTool` function from the `@revenium/claude-code-metering` package. It captures duration, success/failure, and errors, and can extract specific output fields. ```typescript import { meterTool, setToolContext } from "@revenium/claude-code-metering"; // Set context once (propagates to all tool calls) setToolContext({ sessionId: "session-123", userId: "user-456" }); // Wrap tool execution const result = await meterTool("weather-api", async () => { return await fetch("https://api.example.com/weather"); }, { description: "Fetch weather forecast", category: "external-api", outputFields: ["temperature", "humidity"] }); // Automatically extracts temperature & humidity from result ``` -------------------------------- ### Validate Configuration Parameters Source: https://context7.com/revenium/revenium-claude-code-sdk/llms.txt Utilities for validating the format of API keys, email addresses, and endpoint URLs. Returns a validation object containing a boolean status and a list of errors if validation fails. ```typescript import { validateApiKey, validateEmail, validateEndpointUrl, } from "@revenium/claude-code-metering"; // Validate API key format const apiKeyResult = validateApiKey("hak_tenant_secretkey123"); if (apiKeyResult.valid) { console.log("API key format is valid"); } else { console.error("API key errors:", apiKeyResult.errors); } // Validate email format const emailResult = validateEmail("developer@company.com"); if (emailResult.valid) { console.log("Email format is valid"); } else { console.error("Email errors:", emailResult.errors); } // Validate endpoint URL const urlResult = validateEndpointUrl("https://api.revenium.ai"); if (urlResult.valid) { console.log("Endpoint URL is valid"); } else { console.error("URL errors:", urlResult.errors); } ``` -------------------------------- ### Source Revenium Environment Variables in Shell Profiles Source: https://github.com/revenium/revenium-claude-code-sdk/blob/main/README.md Manually add a line to your shell profile to source the Revenium environment variables. This ensures that the Claude Code CLI can access necessary configurations, especially if automatic updates fail. ```bash [ -f ~/.claude/revenium.env ] && source ~/.claude/revenium.env ``` ```zsh [ -f ~/.claude/revenium.env ] && source ~/.claude/revenium.env ``` ```fish if test -f ~/.claude/revenium.env source ~/.claude/revenium.env end ``` -------------------------------- ### Check Telemetry Status via CLI Source: https://context7.com/revenium/revenium-claude-code-sdk/llms.txt The status command verifies the current configuration, environment state, and performs a health check against the configured telemetry endpoint. ```bash npx @revenium/claude-code-metering status ``` -------------------------------- ### Utilize Data Masking and Transaction ID Generation Source: https://context7.com/revenium/revenium-claude-code-sdk/llms.txt Provides helper functions to mask sensitive information like API keys and email addresses for secure logging. Also includes a utility to generate unique transaction IDs based on session and token usage metadata. ```typescript import { maskApiKey, maskEmail, generateTransactionId, } from "@revenium/claude-code-metering"; const maskedKey = maskApiKey("hak_tenant_secretkey123"); console.log(maskedKey); const maskedEmail = maskEmail("developer@company.com"); console.log(maskedEmail); const transactionId = generateTransactionId({ sessionId: "session-123", timestamp: "2024-01-15T10:30:00Z", model: "claude-sonnet-4", inputTokens: 1000, outputTokens: 500, cacheReadTokens: 200, cacheCreationTokens: 0, }); console.log(transactionId); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.