### Get CLI Location Example Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/api-reference/dependencies.md Demonstrates how to retrieve the full path to the WakaTime CLI binary. It checks global installations first, then falls back to a local installation path. ```typescript const cliPath = dependencies.getCliLocation(); // Linux: /home/user/.wakatime/wakatime-cli-linux-amd64 // macOS: /Users/user/.wakatime/wakatime-cli-darwin-amd64 // Windows: C:\Users\user\.wakatime\wakatime-cli-windows-amd64.exe // Global: /usr/local/bin/wakatime-cli (if found) ``` -------------------------------- ### Wakatime CLI Installation Logs Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/configuration.md Example log messages indicating the status of wakatime-cli installation and update checks performed by the plugin. ```log [INFO] wakatime-cli not found, downloading... [INFO] wakatime-cli installed successfully [DEBUG] Checking for wakatime-cli updates... [INFO] Updating wakatime-cli to v1.76.0... ``` -------------------------------- ### Install Plugin from Source Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/configuration.md Install the opencode-wakatime plugin by cloning the repository, installing dependencies, building the project, and then running the install script. ```bash git clone https://github.com/angristan/opencode-wakatime cd opencode-wakatime npm install && npm run build node bin/cli.js --install ``` -------------------------------- ### Using the Shared Dependencies Instance Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/api-reference/dependencies.md Demonstrates how to import and use the shared singleton instance of the dependencies module to check CLI installation, install it if necessary, and get its location. ```typescript import { dependencies } from "./dependencies.js"; const installed = dependencies.isCliInstalled(); await dependencies.checkAndInstallCli(); const location = dependencies.getCliLocation(); ``` -------------------------------- ### Install opencode-wakatime from Source Source: https://github.com/angristan/opencode-wakatime/blob/master/README.md Clone the repository, install dependencies, build the project, and then run the install command. This method is useful for development or if you want to contribute. ```bash git clone https://github.com/angristan/opencode-wakatime cd opencode-wakatime npm install && npm run build node bin/cli.js --install ``` -------------------------------- ### Example Log File Cleanup Script Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/configuration.md This bash command demonstrates how to back up the current log file and start a fresh one. This is useful for manual log rotation. ```bash # Backup old logs and start fresh mv ~/.wakatime/opencode.log ~/.wakatime/opencode.log.bak ``` -------------------------------- ### Plugin Initialization Example Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/api-reference/plugin-entry-point.md Example of how the plugin is configured in opencode.json. No direct usage is required as the framework loads it. ```json { "plugin": ["opencode-wakatime"] } ``` -------------------------------- ### Check CLI Installation Path Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/errors.md Lists files in the WakaTime directory that match the CLI installation pattern. Helps verify the CLI is installed. ```bash # Check if CLI exists ls -la ~/.wakatime/wakatime-cli-* ``` -------------------------------- ### Install opencode-wakatime via npm Source: https://github.com/angristan/opencode-wakatime/blob/master/README.md Install the plugin globally using npm and then run the install command. This method places the plugin in ~/.config/opencode/plugin/wakatime.js. ```bash npm i -g opencode-wakatime opencode-wakatime --install ``` -------------------------------- ### Install Dependencies, Type Check, and Build Project Source: https://github.com/angristan/opencode-wakatime/blob/master/README.md Standard development commands for installing dependencies, performing type checking, and building the project. Run these in your project's root directory. ```bash npm install ``` ```bash npm run typecheck ``` ```bash npm run build ``` -------------------------------- ### WakaTime Configuration File Example Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/configuration.md This is an example of the main WakaTime configuration file, typically located at ~/.wakatime.cfg. It includes essential settings like the API key and debug mode. ```ini [settings] api_key = waka_1234567890abcdef1234567890abcdef debug = false ``` -------------------------------- ### Install Plugin Globally Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/configuration.md Install the opencode-wakatime plugin globally using npm. This command also prepares the plugin for use. ```bash npm i -g opencode-wakatime opencode-wakatime --install ``` -------------------------------- ### Check and Install CLI Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/INDEX.md Checks if the Wakatime CLI is installed and installs it if necessary. ```typescript checkAndInstallCli() ``` -------------------------------- ### Install OpenCode Wakatime Plugin Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/README.md Install the plugin globally using npm. Alternatively, add it to your OpenCode configuration file. ```bash npm i -g opencode-wakatime opencode-wakatime --install ``` ```json { "plugin": ["opencode-wakatime"] } ``` -------------------------------- ### ensureCliInstalled() Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/api-reference/wakatime-client.md Ensures the WakaTime CLI is available. Downloads and installs if missing, checks for updates if installed locally. Returns true if the CLI is available (either found or successfully installed), false if installation failed. ```APIDOC ## ensureCliInstalled() ### Description Ensures the WakaTime CLI is available. Downloads and installs if missing, checks for updates if installed locally. ### Returns `boolean` — True if CLI is available (either found or successfully installed), false if installation failed. ### Example ```typescript const installed = await ensureCliInstalled(); if (!installed) { console.warn("WakaTime CLI not available. Install manually: https://wakatime.com/terminal"); } ``` ``` -------------------------------- ### Ensure CLI Installation and Updates Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/api-reference/dependencies.md Ensures wakatime-cli is installed and up-to-date. Downloads and installs if missing, or checks for updates if already installed. Errors during installation are logged but do not throw. ```typescript async checkAndInstallCli(): Promise ``` ```typescript // At plugin initialization const installed = await ensureCliInstalled(); if (!installed) { logger.warn("WakaTime CLI unavailable. Install manually: https://wakatime.com/terminal"); } ``` -------------------------------- ### Install Wakatime CLI on macOS Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/configuration.md Install the wakatime-cli using Homebrew on macOS. This is a manual installation option. ```bash brew install wakatime-cli ``` -------------------------------- ### checkAndInstallCli Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/api-reference/dependencies.md Ensures wakatime-cli is installed and up-to-date. Downloads and installs if missing, or checks for updates if already installed. The promise always resolves, errors are logged but not thrown. ```APIDOC ## checkAndInstallCli() ### Description Ensures wakatime-cli is installed and up-to-date. Downloads and installs if missing, checks for updates if already installed. ### Returns `Promise` — Resolves when check is complete. ### Behavior 1. If global CLI found, skip installation check entirely 2. If CLI not installed, download and install immediately 3. If installed: - Check if update check interval has passed (4 hours) - Fetch latest version from GitHub releases API - If new version available, download and install - Update version tracking state file ### Update Check Interval 4 hours (14,400,000 ms). After 4 hours, the next call to `checkAndInstallCli()` will check GitHub for updates. ### Errors Errors during installation are logged but not thrown. The promise always resolves. ### Example ```typescript // At plugin initialization const installed = await ensureCliInstalled(); if (!installed) { logger.warn("WakaTime CLI unavailable. Install manually: https://wakatime.com/terminal"); } ``` ``` -------------------------------- ### Example Heartbeat from Desktop Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/configuration.md Illustrates the format of a WakaTime heartbeat sent from the desktop application client. ```bash # From Desktop opencode-desktop/1.1.53 opencode-wakatime/1.3.8 ``` -------------------------------- ### Verify OpenCode Wakatime Installation Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/README.md Verify that the plugin is installed, the WakaTime CLI is available, and the configuration is correctly set. ```bash # Check plugin is installed ls ~/.config/opencode/plugin/wakatime.js # Check CLI is available wakatime-cli --version # Check config cat ~/.wakatime.cfg | grep api_key ``` -------------------------------- ### Install WakaTime CLI (macOS) Source: https://github.com/angristan/opencode-wakatime/blob/master/README.md Install the WakaTime CLI using Homebrew on macOS. This is an optional step as the plugin can download it automatically. ```bash brew install wakatime-cli ``` -------------------------------- ### Get Plugin Version Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/errors.md Displays the installed version of the opencode-wakatime plugin using npm. Useful for debugging plugin-specific issues. ```bash npm list -g opencode-wakatime ``` -------------------------------- ### Example Heartbeat from CLI Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/configuration.md Illustrates the format of a WakaTime heartbeat sent from the command-line interface client. ```bash # From CLI opencode-cli/1.0.0 opencode-wakatime/1.3.8 ``` -------------------------------- ### Ensure WakaTime CLI is Installed Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/api-reference/wakatime-client.md Checks if the WakaTime CLI is installed. If not, it attempts to download and install it. Returns true if the CLI is available, false otherwise. Catches and logs any installation errors. ```typescript export async function ensureCliInstalled(): Promise ``` ```typescript const installed = await ensureCliInstalled(); if (!installed) { console.warn("WakaTime CLI not available. Install manually: https://wakatime.com/terminal"); } ``` -------------------------------- ### Check Plugin Installation Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/configuration.md Verify if the WakaTime plugin is installed in the OpenCode configuration directory. ```bash ls ~/.config/opencode/plugin/wakatime.js ``` -------------------------------- ### Get Global CLI Location Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/api-reference/dependencies.md Attempts to find a globally installed wakatime-cli in the system PATH. Returns the full path if found, otherwise undefined. ```typescript getCliLocationGlobal(): string | undefined ``` ```typescript const globalPath = dependencies.getCliLocationGlobal(); if (globalPath) { console.log(`Found global CLI: ${globalPath}`); // /usr/local/bin/wakatime-cli // or C:\Program Files\wakatime\wakatime-cli.exe } ``` -------------------------------- ### Verify Global Wakatime CLI Installation Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/configuration.md Check if the wakatime-cli is installed globally and accessible in the system's PATH. This command shows the installation location. ```bash which wakatime-cli # Found: /usr/local/bin/wakatime-cli ``` -------------------------------- ### Example Log File Entries Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/api-reference/logger.md Illustrates the format of log entries, including timestamps, log levels, and messages. ```log [2024-01-12T15:30:45.123Z][INFO] OpenCode WakaTime plugin initialized for project: myapp [2024-01-12T15:30:45.456Z][DEBUG] Chat message received [2024-01-12T15:30:45.789Z][DEBUG] Tool executed: edit - src/main.ts [2024-01-12T15:30:45.890Z][WARN] Could not fetch OpenCode version: Network error [2024-01-12T15:31:02.456Z][DEBUG] Sent heartbeat for src/main.ts: +10/-5 lines ``` -------------------------------- ### Check Global CLI Installation Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/errors.md Verifies if the WakaTime CLI is installed globally on your system using the 'which' command. ```bash # Check if globally installed which wakatime-cli ``` -------------------------------- ### Example Debug Log Output Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/configuration.md Illustrative example of the debug log output when the 'debug' option is enabled. It shows various plugin activities, events, and WakaTime CLI interactions. ```log [2024-01-12T15:30:45.123Z][INFO] OpenCode WakaTime plugin initialized for project: myapp [2024-01-12T15:30:45.456Z][DEBUG] OpenCode client: desktop, version: 1.1.53 [2024-01-12T15:30:45.789Z][DEBUG] Chat message received [2024-01-12T15:30:46.012Z][DEBUG] Tool executed: edit - src/main.ts [2024-01-12T15:30:46.134Z][DEBUG] Tracked: src/main.ts (+10/-5) [2024-01-12T15:30:46.245Z][DEBUG] Sent heartbeat: wakatime-cli --entity src/main.ts ... [2024-01-12T15:30:46.356Z][DEBUG] Skipping heartbeat (rate limited) ``` -------------------------------- ### Path Resolution Examples on Linux Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/api-reference/wakatime-paths.md Demonstrates WakaTime path resolution on Linux when WAKATIME_HOME is not set. Shows the expected output for home directory, resources directory, and configuration file path. ```typescript // Environment: // - User: alice // - WAKATIME_HOME: (not set) getWakatimeHomeDir() // /home/alice getWakatimeResourcesDir() // /home/alice/.wakatime getWakatimeConfigFilePath() // /home/alice/.wakatime.cfg ``` -------------------------------- ### Check WakaTime CLI Version Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/configuration.md Verify that the WakaTime CLI is installed and accessible. ```bash wakatime-cli --version ``` -------------------------------- ### WakaTime Path Normalization Examples Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/api-reference/wakatime-paths.md Illustrates how WakaTime handles path normalization, including tilde expansion for home directories and handling of absolute and relative paths. ```typescript // Input: WAKATIME_HOME=~/my-wakatime // Output: /home/user/my-wakatime // Input: WAKATIME_HOME=~/Documents/wakatime // Output: /home/user/Documents/wakatime // Input: WAKATIME_HOME=/absolute/path // Output: /absolute/path (unchanged) // Input: WAKATIME_HOME=relative/path // Output: relative/path (unchanged — treated as relative) ``` -------------------------------- ### Example Heartbeat from Web App Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/configuration.md Illustrates the format of a WakaTime heartbeat sent from the web application client, showing the mapping from 'app' to 'web'. ```bash # From Web App (mapped from "app") opencode-web/1.1.0 opencode-wakatime/1.3.8 ``` -------------------------------- ### Example WakaTime Heartbeat Identifiers Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/api-reference/wakatime-client.md Provides concrete examples of plugin identifier strings for different WakaTime client types (desktop, CLI, web). ```text opencode-desktop/1.1.53 opencode-wakatime/1.3.8 ``` ```text opencode-cli/1.0.0 opencode-wakatime/1.3.8 ``` ```text opencode-web/1.1.0 opencode-wakatime/1.3.8 ``` -------------------------------- ### Logger Usage Example Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/api-reference/logger.md Demonstrates how to import the logger and LogLevel, set the log level to DEBUG, and log messages at various severity levels. ```typescript import { logger, LogLevel } from "opencode-wakatime"; // Enable debug logging logger.setLevel(LogLevel.DEBUG); // Log at different levels logger.debug("Detailed trace information"); logger.info("Plugin initialized"); logger.warn("Configuration not found, using defaults"); logger.error("Failed to send heartbeat"); ``` -------------------------------- ### TypeScript CLI Installation Method Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/api-reference/dependencies.md The private `installCli` method orchestrates the download, extraction, and permission setting for the WakaTime CLI. It includes fallback mechanisms for extraction and ensures cleanup. ```typescript private async installCli(): Promise ``` -------------------------------- ### Dependency Management Module Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/INDEX.md Manages the installation and availability of the Wakatime CLI. ```typescript src/dependencies.ts (dependency management) ├─ exports: dependencies, Dependencies ├─ imports: logger, wakatime-paths └─ 384 lines ``` -------------------------------- ### Path Resolution Examples on Windows Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/api-reference/wakatime-paths.md Shows WakaTime path resolution on Windows using an absolute path for WAKATIME_HOME. Details the resulting home directory, resources directory, and configuration file path. ```typescript // Environment: // - User: charlie // - WAKATIME_HOME: D:\sync\wakatime getWakatimeHomeDir() // D:\sync\wakatime getWakatimeResourcesDir() // D:\sync\wakatime getWakatimeConfigFilePath() // D:\sync\wakatime\.wakatime.cfg ``` -------------------------------- ### Send Heartbeat with Details Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/README.md Example of sending a heartbeat to WakaTime with detailed entity and plugin information. Use `--write` for new file creations. ```bash wakatime-cli \ --entity /path/to/file.ts \ --entity-type file \ --category "ai coding" \ --plugin "opencode-{client}/{version} opencode-wakatime/{pluginVersion}" \ --project-folder /path/to/project \ --ai-line-changes 10 \ [--write] # if new file creation ``` -------------------------------- ### Example HeartbeatParams Usage Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/types.md Demonstrates how to construct and use HeartbeatParams for sending a heartbeat to WakaTime. ```typescript const params: HeartbeatParams = { entity: "/workspace/myapp/src/main.ts", projectFolder: "/workspace/myapp", lineChanges: 5, category: "ai coding", isWrite: false, opencodeVersion: "1.1.53", opencodeClient: "desktop", }; await sendHeartbeat(params); ``` -------------------------------- ### Dependencies Class Methods Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/api-reference/dependencies.md Provides methods to manage the WakaTime CLI lifecycle, including checking its availability, installation status, and location. ```APIDOC ## getCliLocation() ### Description Returns the full path to the wakatime-cli binary. It first checks for global installations and then falls back to a local installation path. ### Method `getCliLocation(): string` ### Parameters None ### Returns `string` - The full path to the CLI binary. ### Behavior 1. Returns cached location if already resolved. 2. Checks for global installation using `which`/`where` command. 3. Falls back to local installation path: `~/.wakatime/wakatime-cli-{os}-{arch}`. 4. Caches the result for subsequent calls. ### Platforms - Linux x64: `wakatime-cli-linux-amd64` - macOS ARM: `wakatime-cli-darwin-arm64` - macOS Intel: `wakatime-cli-darwin-amd64` - Windows x64: `wakatime-cli-windows-amd64.exe` - Other architectures: Automatically detected (386, arm, arm64, etc.) ### Example ```typescript const cliPath = dependencies.getCliLocation(); // Linux: /home/user/.wakatime/wakatime-cli-linux-amd64 // macOS: /Users/user/.wakatime/wakatime-cli-darwin-amd64 // Windows: C:\Users\user\.wakatime\wakatime-cli-windows-amd64.exe // Global: /usr/local/bin/wakatime-cli (if found) ``` ``` -------------------------------- ### Get OS and Architecture Info Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/errors.md Provides system information including kernel version, OS, and architecture. Useful for reporting environment details. ```bash uname -a ``` -------------------------------- ### isCliAvailable() Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/api-reference/wakatime-client.md Synchronously checks if WakaTime CLI is available (either locally installed or globally in PATH). Returns true if the CLI is present, false otherwise. ```APIDOC ## isCliAvailable() ### Description Synchronously checks if WakaTime CLI is available (either locally installed or globally in PATH). ### Returns `boolean` — True if CLI is present, false otherwise. ### Example ```typescript if (!isCliAvailable()) { // Warn user or skip heartbeat sending } ``` ``` -------------------------------- ### Example WakaTime CLI State File Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/api-reference/dependencies.md Illustrates the JSON format of the local state file used for version tracking. It shows the `lastChecked` timestamp and the `version` string. ```json { "lastChecked": 1704067200000, "version": "v1.76.0" } ``` -------------------------------- ### Configure Plugin in opencode.json Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/configuration.md Add the opencode-wakatime plugin to your OpenCode configuration file. The plugin is automatically loaded when OpenCode starts. ```json { "$schema": "https://opencode.ai/config.json", "plugin": ["opencode-wakatime"] } ``` -------------------------------- ### WakaTime Client Module Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/START_HERE.md Handles communication with the WakaTime API, including sending heartbeats and managing CLI installation. ```APIDOC ## Module: wakatime-client ### Description This module is responsible for interacting with the WakaTime API, including sending heartbeat data and ensuring the WakaTime CLI is installed and available. ### Functions - **sendHeartbeat(params: HeartbeatParams)**: (Type: Any) - Sends a heartbeat to WakaTime. - **ensureCliInstalled()**: (Type: Any) - Ensures the WakaTime CLI is installed. - **isCliAvailable()**: (Type: Boolean) - Checks if the WakaTime CLI is available. ### Types - **HeartbeatParams**: Parameters required for sending a heartbeat. ``` -------------------------------- ### Check WakaTime CLI Version Source: https://github.com/angristan/opencode-wakatime/blob/master/README.md Verify if the wakatime-cli is installed and working correctly by checking its version. This is a troubleshooting step for heartbeats not sending. ```bash wakatime-cli --version ``` -------------------------------- ### Path Resolution Examples on macOS Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/api-reference/wakatime-paths.md Illustrates WakaTime path resolution on macOS with a custom WAKATIME_HOME directory set to a user's Documents folder. Includes expected paths for home, resources, and configuration files. ```typescript // Environment: // - User: bob // - WAKATIME_HOME: ~/Documents/WakaTime getWakatimeHomeDir() // /Users/bob/Documents/WakaTime getWakatimeResourcesDir() // /Users/bob/Documents/WakaTime getWakatimeConfigFilePath() // /Users/bob/Documents/WakaTime/.wakatime.cfg ``` -------------------------------- ### Get OpenCode Version Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/errors.md Retrieves the version of the OpenCode application. This is useful when reporting issues. ```bash opencode --version ``` -------------------------------- ### Update API Key Configuration Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/errors.md Example of how to update the WakaTime API key in the configuration file. This is necessary after an authentication failure. ```properties api_key = waka_new_key_here ``` -------------------------------- ### Example Usage of processHeartbeat Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/api-reference/plugin-entry-point.md Demonstrates how to manually call `processHeartbeat` to force sending heartbeats, typically used during session shutdown to ensure all pending data is sent. ```typescript // Called automatically by event hooks, but can be forced on shutdown await processHeartbeat( "/workspace/myproject", "1.1.53", "desktop", true // Force send even if rate limited ); ``` -------------------------------- ### Send Heartbeat for New File Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/api-reference/wakatime-client.md Example of sending a heartbeat for a newly created file, setting `isWrite` to true. Includes entity, project folder, and category. ```typescript await sendHeartbeat({ entity: "/workspace/myapp/src/new-feature.ts", projectFolder: "/workspace/myapp", lineChanges: 0, isWrite: true, // New file created category: "ai coding", }); ``` -------------------------------- ### Set WAKATIME_HOME to Cloud Sync Directory Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/configuration.md Customize the directory where WakaTime files are stored by setting the WAKATIME_HOME environment variable. This example shows setting it to a cloud sync directory. ```bash # Linux/macOS — use cloud sync directory export WAKATIME_HOME=~/Dropbox/wakatime ``` -------------------------------- ### Get WakaTime Config File Path Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/api-reference/wakatime-paths.md Returns the full path to the WakaTime configuration file, respecting the WAKATIME_HOME environment variable. The configuration file is expected to be in INI format and contains settings like API key and debug mode. ```typescript export function getWakatimeConfigFilePath(): string ``` ```typescript // Without WAKATIME_HOME: const cfgPath = getWakatimeConfigFilePath(); // Returns: /home/user/.wakatime.cfg // With WAKATIME_HOME=/custom/path: const cfgPath = getWakatimeConfigFilePath(); // Returns: /custom/path/.wakatime.cfg ``` ```ini [settings] api_key = waka_your_api_key_here debug = true ``` -------------------------------- ### Get WakaTime Home Directory Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/api-reference/wakatime-paths.md Retrieves the WakaTime home directory. It prioritizes the WAKATIME_HOME environment variable, expanding '~' if present. If WAKATIME_HOME is not set, it defaults to the user's home directory. ```typescript export function getWakatimeHomeDir(): string ``` ```typescript // Without WAKATIME_HOME: const dir = getWakatimeHomeDir(); // Returns: /home/user or /Users/user or C:\Users\user // With WAKATIME_HOME=/custom/path: const dir = getWakatimeHomeDir(); // Returns: /custom/path // With WAKATIME_HOME=~/my-wakatime: const dir = getWakatimeHomeDir(); // Returns: /home/user/my-wakatime ``` -------------------------------- ### Create WakaTime Config File Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/errors.md Use this command to create the WakaTime configuration file if it does not exist. ```bash touch ~/".wakatime.cfg" ``` -------------------------------- ### Show All Version Information Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/configuration.md Display versions for OpenCode WakaTime plugin, WakaTime CLI, and cached OpenCode version. ```bash opencode-wakatime --version wakatime-cli --version cat ~/.wakatime/opencode-version-cache.json | jq .version ``` -------------------------------- ### Get Current Unix Timestamp Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/api-reference/state-management.md Gets the current Unix timestamp in seconds. Useful for calculating time differences, such as for rate limiting. ```typescript export function timestamp(): number ``` ```typescript const now = timestamp(); // Returns: 1704067200 (for example) const lastHeartbeat = 1704067140; const secondsAgo = now - lastHeartbeat; // 60 seconds ``` -------------------------------- ### Test CLI Functionality Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/errors.md Runs the WakaTime CLI with the '--help' flag to test its basic functionality and display available commands. ```bash # Test CLI wakatime-cli --help ``` -------------------------------- ### timestamp() Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/api-reference/state-management.md Gets the current Unix timestamp in seconds. ```APIDOC ## timestamp() ### Description Gets the current Unix timestamp in seconds. ### Returns `number` — `Math.floor(Date.now() / 1000)` — current time in seconds since epoch. ### Example ```typescript const now = timestamp(); // Returns: 1704067200 (for example) const lastHeartbeat = 1704067140; const secondsAgo = now - lastHeartbeat; // 60 seconds ``` ``` -------------------------------- ### initState() Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/api-reference/state-management.md Initializes the state management system for a specific project. This function must be called once per plugin instance before using other state functions. It creates a project-specific state file based on the project folder's path. ```APIDOC ## initState(projectFolder: string) ### Description Initializes the state management system for a specific project. Must be called once per plugin instance before using state functions. ### Method `initState` ### Parameters #### Path Parameters - **projectFolder** (string) - Required - Absolute path to the project directory ### Behavior 1. Hashes the project folder path using MD5 2. Takes first 8 characters of hash 3. Derives state file path: `~/.wakatime/opencode-{hash}.json` 4. Sets internal `stateFile` variable used by all subsequent state operations ### Example ```typescript import { initState } from "opencode-wakatime"; // Called at plugin initialization const projectFolder = "/workspace/my-project"; initState(projectFolder); // Creates state file: ~/.wakatime/opencode-abc12345.json ``` ``` -------------------------------- ### Wakatime Path Exports Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/INDEX.md Exports functions for getting Wakatime configuration and resource paths. ```typescript getWakatimeConfigFilePath() ``` ```typescript getWakatimeHomeDir() ``` ```typescript getWakatimeResourcesDir() ``` -------------------------------- ### WakaTime CLI Directory Structure Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/api-reference/wakatime-paths.md Illustrates the standard file and directory layout for the WakaTime CLI configuration and operational files. ```text ~/.wakatime/ (or $WAKATIME_HOME/) ├── .wakatime.cfg (config — user-created) ├── opencode.log (debug log) ├── opencode-cli-state.json (CLI version tracking) ├── opencode-version-cache.json (cached OpenCode server version) ├── opencode-abc12345.json (project 1 rate-limit state) ├── opencode-def67890.json (project 2 rate-limit state) ├── wakatime-cli-linux-amd64 (downloaded CLI binary) └── wakatime-cli-*.zip (temporary download files) ``` -------------------------------- ### getCliLocationGlobal Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/api-reference/dependencies.md Attempts to find a globally installed wakatime-cli in the system PATH. Returns the full path if found, otherwise undefined. ```APIDOC ## getCliLocationGlobal() ### Description Attempts to find a globally installed wakatime-cli in the system PATH. ### Returns `string | undefined` — Full path to global CLI if found, undefined otherwise. ### Behavior 1. Constructs binary name for the platform 2. Executes `which wakatime-cli` (Unix) or `where wakatime-cli` (Windows) 3. Returns first result if found 4. Silently returns undefined if not found ### Example ```typescript const globalPath = dependencies.getCliLocationGlobal(); if (globalPath) { console.log(`Found global CLI: ${globalPath}`); // /usr/local/bin/wakatime-cli // or C:\Program Files\wakatime\wakatime-cli.exe } ``` ``` -------------------------------- ### Plugin Entry Point Module Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/START_HERE.md Provides the main entry point for the plugin and functions to extract file changes. ```APIDOC ## Module: plugin-entry-point ### Description This module serves as the main entry point for the WakaTime plugin and includes utilities for extracting file change information. ### Functions - **plugin()**: (Type: Any) - Main plugin function. - **extractFileChanges(changes: FileChangeInfo)**: (Type: Any) - Extracts file changes. ### Types - **FileChangeInfo**: Represents information about file changes. ``` -------------------------------- ### Get System Architecture Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/api-reference/dependencies.md Determines the system architecture and maps Node.js architecture values to artifact names (e.g., 'x64' to 'amd64'). ```typescript private getArchitecture(): string ``` -------------------------------- ### Diagnose CLI Not Found Errors Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/errors.md Use these commands to diagnose network connectivity, disk space, and file permissions when the WakaTime CLI cannot be installed. ```bash # Check network curl -s https://api.github.com/repos/wakatime/wakatime-cli/releases/latest | head ``` ```bash # Check disk space df ~/.wakatime/ ``` ```bash # Check permissions touch ~/.wakatime/test && rm ~/.wakatime/test ``` ```bash # Check log for details tail -f ~/.wakatime/opencode.log ``` -------------------------------- ### View WakaTime Configuration Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/errors.md Displays the content of the WakaTime configuration file. Use this to review your settings. ```bash # View WakaTime config cat ~/.wakatime.cfg ``` -------------------------------- ### buildExecOptions() Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/api-reference/wakatime-client.md Builds execution options for the CLI subprocess on the current platform. Returns an `ExecFileOptions` object with `windowsHide: true` (hides command window on Windows) and `env` with `WAKATIME_HOME` fallback (Unix-only, if HOME not set). ```APIDOC ## buildExecOptions() ### Description Builds execution options for the CLI subprocess on the current platform. ### Returns `ExecFileOptions` object with: - `windowsHide: true` (hides command window on Windows) - `env` with `WAKATIME_HOME` fallback (Unix-only, if HOME not set) ### Example ```typescript const options = buildExecOptions(); execFile("wakatime-cli", args, options, callback); ``` ``` -------------------------------- ### Enable Full Debug Logging Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/errors.md Appends 'debug = true' to the WakaTime configuration file and restarts OpenCode to enable verbose logging. Then, tail the logs to observe detailed output. ```bash # Edit config echo "debug = true" >> ~/.wakatime.cfg # Restart OpenCode # Logs are now verbose # Check logs tail -f ~/.wakatime/opencode.log ``` -------------------------------- ### Set WAKATIME_HOME on Linux/macOS Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/configuration.md Customize the directory where WakaTime files are stored by setting the WAKATIME_HOME environment variable. This example shows setting it to a custom directory. ```bash # Linux/macOS — use custom directory export WAKATIME_HOME=~/Documents/wakatime ``` -------------------------------- ### Build CLI Execution Options Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/api-reference/wakatime-client.md Constructs the necessary execution options for running the WakaTime CLI as a subprocess. Includes platform-specific settings like hiding the console window on Windows and setting the WAKATIME_HOME environment variable. ```typescript export function buildExecOptions(): ExecFileOptions ``` ```typescript const options = buildExecOptions(); execFile("wakatime-cli", args, options, callback); ``` -------------------------------- ### Get Operating System Name Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/api-reference/dependencies.md Determines the operating system name and maps Node.js platform values to artifact names (e.g., 'win32' to 'windows'). ```typescript private getOsName(): string ``` -------------------------------- ### Get WakaTime Resources Directory Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/api-reference/wakatime-paths.md Retrieves the directory for WakaTime plugin resources. If WAKATIME_HOME is set, it's used directly. Otherwise, it defaults to '~/.wakatime'. ```typescript export function getWakatimeResourcesDir(): string ``` ```typescript // Without WAKATIME_HOME: const dir = getWakatimeResourcesDir(); // Returns: /home/user/.wakatime // With WAKATIME_HOME=/custom/wakatime: const dir = getWakatimeResourcesDir(); // Returns: /custom/wakatime // Files stored here: // - opencode.log (debug log) // - opencode-{hash}.json (per-project state) // - opencode-cli-state.json (CLI version tracking) // - opencode-version-cache.json (cached OpenCode version) // - wakatime-cli-* (downloaded CLI binary) ``` -------------------------------- ### Follow Live Logs Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/errors.md Continuously streams new log entries as they are written to the file. Ideal for monitoring activity in real-time. ```bash # Follow live logs tail -f ~/.wakatime/opencode.log ``` -------------------------------- ### Dependencies Class Definition Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/api-reference/dependencies.md Defines the Dependencies class responsible for managing the WakaTime CLI. It includes methods for CLI detection, installation, updates, and version management. ```typescript export class Dependencies { constructor() // CLI Detection getCliLocation(): string getCliLocationGlobal(): string | undefined isCliInstalled(): boolean isCliAvailable(): boolean // Installation & Updates checkAndInstallCli(): Promise // Version Management getLatestVersion(): Promise (private) // Utilities getOsName(): string (private) getArchitecture(): string (private) getCliBinaryName(): string (private) getCliDownloadUrl(): string (private) downloadFile(url: string, dest: string): Promise (private) extractZip(zipFile: string, destDir: string): Promise (private) } export const dependencies = new Dependencies() ``` -------------------------------- ### Set WAKATIME_HOME on Windows PowerShell Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/configuration.md Customize the directory where WakaTime files are stored by setting the WAKATIME_HOME environment variable. This example shows setting it for Windows PowerShell. ```powershell # Windows PowerShell $env:WAKATIME_HOME = "C:\Users\alice\Documents\wakatime" ``` -------------------------------- ### Manually Extract Downloaded CLI Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/errors.md Steps to manually extract the WakaTime CLI from a downloaded ZIP archive and make it executable. ```bash chmod +x ~/.wakatime/wakatime-cli-linux-amd64 ``` -------------------------------- ### Check WakaTime CLI Write Permissions Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/configuration.md Test write permissions in the WakaTime configuration directory. ```bash touch ~/.wakatime/test && rm $_ ``` -------------------------------- ### WakaTime Configuration for Debug Logging Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/api-reference/logger.md Shows how to enable debug logging by setting 'debug = true' in the WakaTime configuration file. ```ini [settings] api_key = waka_your_api_key debug = true ``` -------------------------------- ### Plugin Entry Point Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/INDEX.md The main entry point for the plugin, handling exports, imports, and core logic. ```typescript src/index.ts (plugin entry point) │ ├─ exports: plugin, extractFileChanges, FileChangeInfo │ ├─ imports: logger, state, wakatime, wakatime-paths │ └─ 484 lines ``` -------------------------------- ### Fetch OpenCode Version Health Check Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/README.md Demonstrates how the OpenCode Wakatime plugin retrieves the OpenCode client version by making a GET request to the /global/health endpoint. ```typescript GET /global/health → { version: "1.1.53", ... } ``` -------------------------------- ### List State Files Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/errors.md Lists all files in the WakaTime directory that match the state file pattern. Useful for identifying available state data. ```bash # List all state files ls -la ~/.wakatime/opencode-*.json ``` -------------------------------- ### Check CLI Installation Status Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/api-reference/dependencies.md Checks if the wakatime-cli binary exists at its expected location using fs.existsSync(). Returns true if the binary file exists, false otherwise. ```typescript isCliInstalled(): boolean ``` ```typescript if (!dependencies.isCliInstalled()) { console.log("CLI not found, downloading..."); await dependencies.checkAndInstallCli(); } ``` -------------------------------- ### Example Rate Limiting State File Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/configuration.md This JSON structure represents the state file used for rate limiting heartbeats. It stores the timestamp of the last heartbeat sent. ```json { "lastHeartbeatAt": 1704067200 } ``` -------------------------------- ### Configure opencode.json for Plugin Source: https://github.com/angristan/opencode-wakatime/blob/master/README.md Add 'opencode-wakatime' to the 'plugin' array in your opencode.json configuration file. This is the recommended way to enable the plugin. ```json { "$schema": "https://opencode.ai/config.json", "plugin": ["opencode-wakatime"] } ``` -------------------------------- ### Define LogLevel Enum Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/types.md An enum for filtering log messages. Only messages at or above the current level are written to the log file. Usage examples show how to set the logging level. ```typescript export enum LogLevel { DEBUG = 0 INFO = 1 WARN = 2 ERROR = 3 } ``` ```typescript import { LogLevel, logger } from "opencode-wakatime"; logger.setLevel(LogLevel.DEBUG); // Show all logger.setLevel(LogLevel.INFO); // Hide DEBUG logger.setLevel(LogLevel.ERROR); // Show only errors ``` -------------------------------- ### Reinstall CLI Command Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/errors.md Commands to reinstall the WakaTime CLI. Use this if the CLI binary is not found or is not executable. ```bash npm i -g opencode-wakatime && opencode-wakatime --install ``` ```bash brew install wakatime-cli ``` -------------------------------- ### Send Heartbeat for Edited File Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/api-reference/wakatime-client.md Example of sending a heartbeat for an edited file, including entity, project folder, and line changes. Requires importing the `sendHeartbeat` function. ```typescript import { sendHeartbeat } from "opencode-wakatime"; await sendHeartbeat({ entity: "/workspace/myapp/src/main.ts", projectFolder: "/workspace/myapp", lineChanges: 10 - 5, // 5 net lines added category: "ai coding", opencodeVersion: "1.1.53", opencodeClient: "desktop", }); ``` -------------------------------- ### View CLI State File Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/errors.md Displays the content of the WakaTime CLI state file. This file contains information about the CLI's current status. ```bash # Check CLI state cat ~/.wakatime/opencode-cli-state.json ``` -------------------------------- ### Get WakaTime Client Version Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/api-reference/wakatime-client.md Retrieves the WakaTime client version, prioritizing a build-time constant and falling back to package.json in development. Defaults to 'unknown' if neither is available. ```typescript declare const __VERSION__: string | undefined function getVersion(): string { // 1. Check for build-time __VERSION__ constant // 2. Fall back to package.json if in development // 3. Default to "unknown" } const VERSION = getVersion() ``` -------------------------------- ### Define CliState Interface Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/types.md Tracks the state of the wakatime-cli binary, including the last time an update was checked and the latest known version. Persisted at `~/.wakatime/opencode-cli-state.json`. ```typescript interface CliState { lastChecked?: number version?: string } ``` -------------------------------- ### Check Log File Existence Source: https://github.com/angristan/opencode-wakatime/blob/master/_autodocs/configuration.md Verify that the WakaTime plugin log file exists. ```bash ls -la ~/.wakatime/opencode.log ```