### Define Plugin Dependencies in package.json Source: https://opencode.ai/docs/plugins This JSON file defines the npm dependencies required for local plugins. OpenCode will automatically run 'bun install' to install these dependencies at startup. ```json { "dependencies": { "shescape": "^2.1.0" } } ``` -------------------------------- ### Customize Session Compaction Source: https://opencode.ai/docs/plugins These plugins hook into the session compaction process. One example injects additional context into the compaction prompt, while the other completely replaces the default prompt with a custom one. ```typescript import type { Plugin } from "@opencode-ai/plugin" export const CompactionPlugin: Plugin = async (ctx) => { return { "experimental.session.compacting": async (input, output) => { output.context.push(` ## Custom Context Include any state that should persist across compaction: - Current task status - Important decisions made - Files being actively worked on `) }, } } ``` ```typescript import type { Plugin } from "@opencode-ai/plugin" export const CustomCompactionPlugin: Plugin = async (ctx) => { return { "experimental.session.compacting": async (input, output) => { output.prompt = ` You are generating a continuation prompt for a multi-agent swarm session. Summarize: 1. The current task and its status 2. Which files are being modified and by whom 3. Any blockers or dependencies between agents 4. The next steps to complete the work Format as a structured prompt that a new agent can use to resume work. ` }, } } ``` -------------------------------- ### TypeScript Plugin with Type Imports Source: https://opencode.ai/docs/plugins This TypeScript example shows how to import types from the '@opencode-ai/plugin' package for type-safe plugin development. It defines the plugin function with explicit types. ```typescript import type { Plugin } from "@opencode-ai/plugin" export const MyPlugin: Plugin = async ({ project, client, $, directory, worktree }) => { return { // Type-safe hook implementations } } ``` -------------------------------- ### Create a Local Plugin with Dependency Usage (TypeScript) Source: https://opencode.ai/docs/plugins An example of a local TypeScript plugin that utilizes an external npm package ('shescape'). It hooks into the 'tool.execute.before' event to escape commands for the 'bash' tool. ```typescript import { escape } from "shescape" export const MyPlugin = async (ctx) => { return { "tool.execute.before": async (input, output) => { if (input.tool === "bash") { output.args.command = escape(output.args.command) } }, } } ``` -------------------------------- ### Basic Plugin Structure (JavaScript) Source: https://opencode.ai/docs/plugins This JavaScript code demonstrates the basic structure of an OpenCode plugin. It exports an async function that receives a context object and returns an object of hook implementations. ```javascript export const MyPlugin = async ({ project, client, $, directory, worktree }) => { console.log("Plugin initialized!") return { // Hook implementations go here } } ``` -------------------------------- ### Structured Application Logging Source: https://opencode.ai/docs/plugins This plugin demonstrates how to use the client.app.log method for structured logging within the OpenCode environment. It supports multiple log levels including debug, info, warn, and error. ```typescript export const MyPlugin = async ({ client }) => { await client.app.log({ body: { service: "my-plugin", level: "info", message: "Plugin initialized", extra: { foo: "bar" }, }, }) } ``` -------------------------------- ### Configure npm Plugins in opencode.json Source: https://opencode.ai/docs/plugins This JSON configuration specifies which npm packages to load as plugins for OpenCode. It supports both regular and scoped npm packages. ```json { "$schema": "https://opencode.ai/config.json", "plugin": ["opencode-helicone-session", "opencode-wakatime", "@my-org/custom-plugin"] } ``` -------------------------------- ### Compaction Hooks Source: https://opencode.ai/docs/plugins Allows customization of the context included when a session is compacted, or replacement of the entire compaction prompt. ```APIDOC ## Compaction Hooks ### Description Provides hooks to customize the context or the entire prompt used during session compaction, enabling more domain-specific state persistence. ### Method `experimental.session.compacting` Hook ### Endpoint N/A (Internal session management hook) ### Parameters #### Hook Parameters - **input** (object) - Required - Input object containing session data. - **output** (object) - Required - Output object that can be modified. - **context** (array of strings) - Optional - An array to which custom context strings can be pushed. - **prompt** (string) - Optional - A string to completely replace the default compaction prompt. ### Request Example (Adding Context) ```typescript import type { Plugin } from "@opencode-ai/plugin" export const CompactionPlugin: Plugin = async (ctx) => { return { "experimental.session.compacting": async (input, output) => { output.context.push(` ## Custom Context Include any state that should persist across compaction: - Current task status - Important decisions made - Files being actively worked on `) }, } } ``` ### Request Example (Replacing Prompt) ```typescript import type { Plugin } from "@opencode-ai/plugin" export const CustomCompactionPlugin: Plugin = async (ctx) => { return { "experimental.session.compacting": async (input, output) => { output.prompt = ` You are generating a continuation prompt for a multi-agent swarm session. Summarize: 1. The current task and its status 2. Which files are being modified and by whom 3. Any blockers or dependencies between agents 4. The next steps to complete the work Format as a structured prompt that a new agent can use to resume work. ` }, } } ``` ### Response #### Success Response N/A (Compaction process is customized) #### Response Example N/A ``` -------------------------------- ### Logging Plugin Source: https://opencode.ai/docs/plugins Provides a structured way to log information within plugins using `client.app.log()` instead of `console.log`. ```APIDOC ## Logging ### Description Utilizes `client.app.log()` for structured logging within plugins, offering different levels and additional metadata. ### Method `client.app.log()` ### Endpoint N/A (Internal logging mechanism) ### Parameters #### Log Parameters - **body** (object) - Required - The log message payload. - **service** (string) - Required - The name of the service or plugin logging the message. - **level** (string) - Required - The log level (e.g., `debug`, `info`, `warn`, `error`). - **message** (string) - Required - The main log message. - **extra** (object) - Optional - Additional key-value pairs for context. ### Request Example ```typescript export const MyPlugin = async ({ client }) => { await client.app.log({ body: { service: "my-plugin", level: "info", message: "Plugin initialized", extra: { foo: "bar" }, }, }) } ``` ### Response #### Success Response N/A (Logs are recorded internally) #### Response Example N/A ``` -------------------------------- ### Custom Tools Plugin Source: https://opencode.ai/docs/plugins Allows developers to define and add custom tools that can be called by OpenCode AI. ```APIDOC ## Custom Tools ### Description Enables the creation of custom tools that extend OpenCode's capabilities. These tools can be invoked by the AI alongside built-in tools. ### Method Plugin Definition ### Endpoint N/A (Defines tools available within the OpenCode environment) ### Parameters #### Tool Definition Parameters - **description** (string) - Required - A description of what the custom tool does. - **args** (object) - Required - A Zod schema defining the arguments the tool accepts. - **execute** (function) - Required - The function that executes when the tool is called. It receives arguments and context. ### Request Example ```typescript import { type Plugin, tool } from "@opencode-ai/plugin" export const CustomToolsPlugin: Plugin = async (ctx) => { return { tool: { mytool: tool({ description: "This is a custom tool", args: { foo: tool.schema.string(), }, async execute(args, context) { const { directory, worktree } = context return `Hello ${args.foo} from ${directory} (worktree: ${worktree})` }, }), }, } } ``` ### Response #### Success Response N/A (Tools are registered and available for use) #### Response Example N/A ``` -------------------------------- ### Notification Plugin Source: https://opencode.ai/docs/plugins This plugin sends system notifications on specific events, such as session completion, using AppleScript on macOS. ```APIDOC ## Send Notifications ### Description Sends system notifications when certain events occur, like session completion. ### Method Event Hook ### Endpoint N/A (Internal event handling) ### Parameters #### Event Hook Parameters - **event** (object) - Required - An object containing event details. The plugin specifically checks for `event.type === "session.idle"`. ### Request Example N/A (Triggered by internal events) ### Response #### Success Response N/A (Side effect: displays a system notification) #### Response Example N/A ``` -------------------------------- ### Define Custom AI Tools Source: https://opencode.ai/docs/plugins This plugin registers a custom tool within OpenCode, providing a Zod-based schema for arguments and an execution function. Custom tools take precedence over built-in tools if naming conflicts occur. ```typescript import { type Plugin, tool } from "@opencode-ai/plugin" export const CustomToolsPlugin: Plugin = async (ctx) => { return { tool: { mytool: tool({ description: "This is a custom tool", args: { foo: tool.schema.string(), }, async execute(args, context) { const { directory, worktree } = context return `Hello ${args.foo} from ${directory} (worktree: ${worktree})` }, }), }, } } ``` -------------------------------- ### Environment Variable Protection Plugin Source: https://opencode.ai/docs/plugins This plugin prevents OpenCode from reading sensitive .env files by intercepting tool execution. ```APIDOC ## .env Protection ### Description Prevents OpenCode from accessing or reading `.env` files by throwing an error if a read operation targets such a file. ### Method `tool.execute.before` Hook ### Endpoint N/A (Internal tool execution interception) ### Parameters #### Hook Parameters - **input** (object) - Required - The input to the tool execution. - **output** (object) - Required - The output or arguments of the tool execution. The plugin checks `output.args.filePath`. ### Request Example N/A (Intercepts tool calls) ### Response #### Success Response N/A (Allows tool execution if not reading .env files) #### Error Response (400) - **Error** (string) - Throws an error: "Do not read .env files" if a `.env` file is targeted for reading. #### Response Example N/A ``` -------------------------------- ### Restrict File Access for Security Source: https://opencode.ai/docs/plugins This plugin intercepts tool execution requests to prevent the AI from reading sensitive .env files. It throws an error if a read operation targets a file containing .env in its path. ```javascript export const EnvProtection = async ({ project, client, $, directory, worktree }) => { return { "tool.execute.before": async (input, output) => { if (input.tool === "read" && output.args.filePath.includes(".env")) { throw new Error("Do not read .env files") } }, } } ``` -------------------------------- ### Inject Environment Variables Plugin Source: https://opencode.ai/docs/plugins This plugin injects custom environment variables into all shell executions, including AI tools and user terminals. ```APIDOC ## Inject Environment Variables ### Description Injects specified environment variables into the environment for all shell executions initiated by OpenCode. ### Method `shell.env` Hook ### Endpoint N/A (Modifies shell environment) ### Parameters #### Hook Parameters - **input** (object) - Required - Input object containing context like the current working directory (`cwd`). - **output** (object) - Required - Output object where environment variables can be added. The plugin modifies `output.env`. ### Request Example N/A (Modifies environment) ### Response #### Success Response N/A (Environment variables are added to the shell process) #### Response Example ```json { "env": { "MY_API_KEY": "secret", "PROJECT_ROOT": "/path/to/project" } } ``` ``` -------------------------------- ### Inject Environment Variables into Shell Source: https://opencode.ai/docs/plugins This plugin modifies the environment variables available to shell execution tools and user terminals. It allows for dynamic injection of API keys or project-specific paths. ```javascript export const InjectEnvPlugin = async () => { return { "shell.env": async (input, output) => { output.env.MY_API_KEY = "secret" output.env.PROJECT_ROOT = input.cwd }, } } ``` -------------------------------- ### Send System Notifications via AppleScript Source: https://opencode.ai/docs/plugins This plugin triggers a macOS system notification when a session becomes idle. It utilizes the osascript command to interface with the macOS notification center. ```javascript export const NotificationPlugin = async ({ project, client, $, directory, worktree }) => { return { event: async ({ event }) => { if (event.type === "session.idle") { await $`osascript -e 'display notification "Session completed!" with title "opencode"'` } }, } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.