### Delegate Method Example Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/api-reference.md An internal example demonstrating how to use the `delegate` method to start a new delegation. It logs the ID and creation timestamp of the initiated delegation. ```typescript const delegation = await manager.delegate({ parentSessionID: "session-123", parentMessageID: "msg-456", parentAgent: "main", prompt: "Research TypeScript generics", agent: "researcher" }) console.log(`Delegation ${delegation.id} started at ${delegation.createdAt}`) ``` -------------------------------- ### ListDelegations Method Example Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/api-reference.md An example demonstrating how to list all delegations visible to a session and log their ID, title, and status. ```typescript const list = await manager.listDelegations("session-123") list.forEach(d => console.log(`${d.id}: ${d.title} [${d.status}]`)) ``` -------------------------------- ### Delegation Storage Format Example Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/configuration.md Delegations are persisted as markdown files. This example shows the structure, including metadata and the start of the full delegation output. ```markdown # OAuth2 PKCE Best Practices Comprehensive research on secure OAuth2 flows and implementations. **ID:** elegant-blue-tiger **Agent:** researcher **Status:** complete **Session:** session-abc123 **Started:** 2025-02-14T10:15:30.000Z **Completed:** 2025-02-14T10:20:45.000Z --- [Full delegation output follows] ``` -------------------------------- ### Install Workspace Plugin Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/README.md Optional: Install the workspace plugin for a comprehensive experience, including background agents, specialist agents, and planning tools. ```bash ocx add kdco/workspace --from https://registry.kdco.dev ``` -------------------------------- ### ReadOutput Method Example Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/api-reference.md An internal example showing how to retrieve the output of a specific delegation using its session ID and delegation ID. ```typescript const output = await manager.readOutput("session-123", "elegant-blue-tiger") console.log(output) ``` -------------------------------- ### Mark Delegation as Started Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/lifecycle.md Transitions a delegation's status to 'running' and records the timestamp when it officially started. This is a synchronous operation. ```typescript this.markStarted(delegation.id) ``` -------------------------------- ### Install Background Agents Plugin Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/README.md Use this command to add the background agents plugin to your OpenCode environment. Ensure OCX is installed first. ```bash ocx add kdco/background-agents --from https://registry.kdco.dev ``` -------------------------------- ### Install Background Agents Plugin Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/README.md Use this command to add the background agents plugin to your OpenCode environment. ```bash ocx add kdco/background-agents --from https://registry.kdco.dev ``` -------------------------------- ### DelegationManager.delegate Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/exported-api.md Creates and starts a new delegation. This is the primary method for initiating a delegation process. ```APIDOC ## delegate() ### Description Create and start delegation. ### Method POST (Assumed, as it creates a resource) ### Endpoint /delegations (Assumed) ### Parameters #### Request Body - **input** (DelegateInput) - Required - Input parameters for the delegation. ### Response #### Success Response (200) - **DelegationRecord** - The record of the created and started delegation. ``` -------------------------------- ### Plugin Installation and Loading Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/exported-api.md This snippet shows how to import the Background Agents plugin. The plugin is automatically loaded by OpenCode, making its tools available. ```typescript import BackgroundAgentsPlugin from './background-agents.ts' // Plugin is loaded by OpenCode // Tools become available automatically ``` -------------------------------- ### Background Agents Plugin Initialization Example Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/api-reference.md Illustrates how the Background Agents Plugin is imported and automatically loaded by the OpenCode registry system. It highlights the availability of delegate(), delegation_read(), and delegation_list() tools after loading. ```typescript import BackgroundAgentsPlugin from './background-agents.ts' // Plugin is automatically loaded by OpenCode registry system // Three tools become available: delegate(), delegation_read(), delegation_list() ``` -------------------------------- ### DelegationManager delegate() Method Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/exported-api.md Creates and starts a new delegation. Returns a promise that resolves with the DelegationRecord. ```typescript (input: DelegateInput) => Promise ``` -------------------------------- ### Example Injected Chat Message Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/hooks.md This is an example of the XML-like structure that might be injected as a notification within a chat message. It includes task status, summary, and artifact details. ```xml elegant-blue-tiger complete Background agent complete: OAuth2 PKCE Best Practices OAuth2 PKCE Best Practices Comprehensive research on secure OAuth2 flows... /home/user/.local/share/opencode/delegations/abc123/elegant-blue-tiger.md Use delegation_read("elegant-blue-tiger") for full output. 0 [model's actual response continues here] ``` -------------------------------- ### Mutex Example: Serializing Database Operations Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/primitives.md Shows how Mutex can be used to serialize database operations, ensuring that concurrent updates to the same record are handled sequentially. ```typescript // Serialize database operations const dbMutex = new Mutex() await dbMutex.runExclusive(async () => { await db.update(record) }) ``` -------------------------------- ### Tool Execution Guard: Agent Not Found Error Message Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/hooks.md Example error message displayed when an agent specified in a tool call is not found. ```text ❌ Agent "unknown-agent" not found. Available agents: • researcher - Research assistant • explore - Code exploration ``` -------------------------------- ### All-Complete Session Notification Example Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/configuration.md This XML structure is sent when all delegations for a parent session have reached their terminal status. ```xml all-complete completed All delegations complete. session-123 1 session-123:1 ``` -------------------------------- ### Event Loop Flow Example Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/architecture.md Illustrates the sequence of events and function calls within the single-threaded event loop for session management and notifications. This flow helps understand how operations are processed sequentially without race conditions. ```plaintext Event 1: session.message.updated for delegation session → handleMessageEvent() updates progress in memory ↓ Event 2: session.idle for delegation session → handleSessionIdle() initiates finalization → persistOutput() writes to disk → notifyParent() sends notification ↓ Event 3: session.message for parent session → chat.message hook injects queued notifications ↓ Event 4: delegation_read() call from parent → readOutput() returns artifact ``` -------------------------------- ### Stream Long Tasks Without Blocking Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/usage-patterns.md This example shows how to initiate a long-running task and monitor its progress without blocking the main thread. It's ideal for tasks like processing large datasets or generating reports. ```typescript console.log("Starting data processing...") const id = await delegate( "Process 1 million records and generate report", "data_processor" ) // Delegate returns immediately console.log(`Processing started: ${id}`) // Continue with other work await doOtherWork() // Check status occasionally (use list, don't call read) let lastList = await delegation_list() let processingTask = lastList.find(t => t.id === id) if (processingTask?.status === "running") { console.log("Still processing...") // Don't call delegation_read() while running, just check list } // When notified or user asks for results: console.log("Fetching results...") const result = await delegation_read(id) console.log(result) ``` -------------------------------- ### List all delegations Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/api-reference.md Lists all delegations within the current session, providing their titles and summaries. Use this to get an overview of ongoing or completed background tasks. ```typescript async function delegation_list(): Promise ``` ```typescript const list = await delegation_list() // Output: // ## Delegations // // - **elegant-blue-tiger** | OAuth2 PKCE Best Practices [complete] // → Comprehensive research on secure OAuth2 flows and implementations // - **bright-orange-penguin** | TypeScript Generics [running] [unread] // → (running) ``` -------------------------------- ### Get Configuration for Small Model Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/configuration.md Retrieve the client configuration to access settings like the 'small_model' used for metadata generation. Handles cases where 'small_model' might be unavailable. ```typescript const config = await client.config.get() const configData = config.data as { small_model?: string } ``` -------------------------------- ### Silent Failure Suppression Example Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/primitives.md Shows how non-critical failures, such as cache writes, are silently ignored using `.catch(() => {})`. ```typescript cache.write().catch(() => {}) ``` -------------------------------- ### Mutex Example: Serializing Tmux Commands Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/primitives.md Illustrates using Mutex to serialize asynchronous operations, specifically to prevent race conditions when executing multiple tmux commands. ```typescript const tmuxMutex = new Mutex() // Serialize tmux commands to prevent socket races const windows = await tmuxMutex.runExclusive(async () => { return await execTmuxCommand(["list-windows"]) }) ``` -------------------------------- ### Tool Execution Guard: Read-Only Agent Error Message Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/hooks.md Example error message displayed when a read-only agent attempts to use the 'task' tool, advising the use of 'delegate'. ```text ❌ Agent 'researcher' is read-only and should use the delegate tool for async background execution. Read-only agents have: edit="deny", write="deny", bash={"*":"deny"} Use delegate for read-only sub-agents. Use task for write-capable sub-agents. ``` -------------------------------- ### Delegate a Task and Read Results Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/INDEX.md Use this pattern to start a long-running background task and later retrieve its results. The `delegate` function returns an ID immediately, and `delegation_read` fetches the artifact once the task is complete. ```typescript // Start task const id = await delegate("Research topic", "researcher") // Continue working // ... you'll be notified automatically ... // Retrieve results const result = await delegation_read(id) ``` -------------------------------- ### Nested Timeouts with withTimeout Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/primitives.md Demonstrates how to apply `withTimeout` to an already wrapped promise, creating nested timeouts. This example shows an `innerPromise` with a 5000ms timeout, which is itself wrapped by an outer timeout of 10000ms. ```typescript // Nested timeouts const result = await withTimeout( withTimeout(innerPromise(), 5000), 10000 ) ``` -------------------------------- ### Get Real Temporary Directory Path Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/primitives.md Resolves symlinks to get the actual temporary directory path. Essential for tools like VS Code and Bun that require the resolved path for file watching. ```typescript function getTempDir(): string ``` ```typescript const tempDir = getTempDir() // macOS: "/private/var/folders/xx/xxxxx/T" // Linux: "/tmp" // Windows: "C:\\Users\\name\\AppData\\Local\\Temp" // Use for creating temp files const tempFile = path.join(getTempDir(), `script-${Date.now()}.sh`) await fs.writeFile(tempFile, scriptContent) ``` -------------------------------- ### Background Agents Plugin Component Architecture Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/architecture.md Illustrates the main entry point, key managers, tool creators, hook handlers, state tracking, and client APIs within the background agents plugin system. ```text ┌─────────────────────────────────────────────────────────────┐ │ OpenCode Plugin System │ └─────────────────────────────────────────────────────────────┘ ↓ ┌─────────────────────────────────────────────────────────────┐ │ BackgroundAgentsPlugin (main entry point) │ │ src/plugin/background-agents.ts │ └─────────────────────────────────────────────────────────────┘ ↓ ↓ ↓ ┌─────────────┐ ┌──────────────┐ ┌──────────────┐ │DelegationMgr│ │ Tool Creators│ │Hook Handlers │ │ (line 400) │ │ (line 1578-1678) │ (line 1853-1973) │ │ │ │ │ │ - delegate()│ │ - createDelegate() │ - tool.execute │ │ - readOutput│ │ - createRead() │ - system.trans │ │ - listDelegations │ - createList() │ - chat.message │ │ - findBySession │ │ - compacting │ │ - handleSessionIdle │ │ - event │ │ - handleMessageEvent │ │ │ │ - registerDelegation │ │ │ │ - finalizeDelegation │ │ │ │ - persistOutput │ │ │ │ - notifyParent │ │ │ └─────────────┘ └──────────────────────┴──────────────┘ ↓ ┌─────────────────────────────────────┐ │ In-Memory State Tracking │ │ │ │ - delegations Map │ │ - delegationsBySession Map │ │ - terminalWaiters Map │ │ - timeoutTimers Map │ │ - pendingByParent Map │ │ - parentNotificationState Map │ │ - pendingNotifications Map │ └─────────────────────────────────────┘ ↓ ┌─────────────────────────────────────┐ │ OpenCode Client APIs │ │ │ │ - session.create() │ │ - session.delete() │ │ - session.prompt() │ │ - session.promptAsync() │ │ - session.messages() │ │ - config.get() │ │ - app.agents() │ │ - app.log() │ └─────────────────────────────────────┘ ``` -------------------------------- ### Check 1: Immediate Disk Read Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/lifecycle.md Fast path: If the artifact exists on disk, return it immediately. Marks the delegation as retrieved. ```typescript const immediateRead = await this.readPersistedArtifact(immediateArtifactPath) if (immediateRead !== null) { this.markRetrieved(delegation.id, sessionID) return immediateRead } ``` -------------------------------- ### DelegationManager.readOutput Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/exported-api.md Retrieves the output of a specific delegation session. Useful for getting the results after a delegation has completed. ```APIDOC ## readOutput(sessionID, id) ### Description Read delegation output. ### Method GET (Assumed, as it retrieves data) ### Endpoint /sessions/{sessionID}/delegations/{id}/output (Assumed) ### Parameters #### Path Parameters - **sessionID** (string) - Required - The ID of the session. - **id** (string) - Required - The ID of the delegation. ### Response #### Success Response (200) - **string** - The output of the delegation. ``` -------------------------------- ### Running Delegations Context Format Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/hooks.md Markdown format for displaying running delegations. This section is included only if running delegations exist. ```markdown ## Running Delegations ### `elegant-blue-tiger` (researcher) **Started:** 2025-02-14T10:15:30.000Z **Last heartbeat:** 2025-02-14T10:16:40.000Z **Prompt:** Research OAuth2 PKCE security best practices... > **Note:** You WILL be notified via `` when delegations complete. > Do NOT poll `delegation_list` - continue productive work. ``` -------------------------------- ### experimental.chat.system.transform Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/api-reference.md This hook injects `DELEGATION_RULES` into the system prompt, educating the agent about delegation routing. ```APIDOC ## HOOK experimental.chat.system.transform ### Description Injects `DELEGATION_RULES` into system prompt, educating the agent about delegation routing. ### Signature ```typescript "experimental.chat.system.transform": (input: { agent?: string; sessionID?: string }, output: { system: string[] }) => Promise ``` ``` -------------------------------- ### Disk Persistence Directory Structure Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/architecture.md Illustrates the directory structure for on-disk persistence of delegation artifacts and logs. Project IDs are used to organize data across different projects. ```text ~/.local/share/opencode/delegations/ ├─ {projectId}/ (stable across worktrees) │ ├─ elegant-blue-tiger.md (artifact) │ ├─ bright-orange-penguin.md (artifact) │ ├─ rapid-green-fox.md (artifact) │ └─ background-agents-debug.log (debug log) └─ {projectId2}/ └─ ... ``` -------------------------------- ### DelegationManager getPendingCount() Method Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/exported-api.md Gets the count of active delegations for a given parent session ID. Returns a number. ```typescript (parentSessionID: string) => number ``` -------------------------------- ### Terminal Task Notification Example Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/configuration.md This XML structure represents a single terminal notification sent when a delegation reaches its final status. ```xml elegant-blue-tiger complete Background agent complete: OAuth2 PKCE Best Practices OAuth2 PKCE Best Practices Comprehensive research on OAuth2 flows... /path/to/delegation.md Use delegation_read("elegant-blue-tiger") for full output. 2 ``` -------------------------------- ### Tool Input Validation Steps Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/architecture.md Outlines the validation checks performed on tool inputs before session creation. Failures at this layer result in immediate exceptions returned to the user. ```plaintext delegate(prompt, agent) ├─ prompt is string ✓ ├─ agent is string ✓ ├─ agent exists ✓ ├─ agent is read-only ✓ └─ Create session ``` -------------------------------- ### Get Result for Timeout Delegations Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/lifecycle.md Retrieves partial results for a timed-out delegation and appends a timeout marker. This is used by the `resolveDelegationResult` function. ```typescript if (delegation.status === "timeout") { const partial = await this.getResult(delegation) return `${partial}\n\n[TIMEOUT REACHED]` } ``` -------------------------------- ### experimental.session.compacting Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/api-reference.md This hook injects running and unread completed delegations into compaction context so the agent remembers them across context windows. ```APIDOC ## HOOK experimental.session.compacting ### Description Injects running and unread completed delegations into compaction context so the agent remembers them across context windows. ### Signature ```typescript "experimental.session.compacting": (input: { sessionID: string }, output: { context: string[]; prompt?: string }) => Promise ``` ``` -------------------------------- ### Delegate a Research Task Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/README.md Example of delegating a research task asynchronously and retrieving its results later. This is suitable for tasks that do not require immediate output. ```typescript // Delegate a research task const researchId = await delegate( "Research OAuth2 PKCE security best practices", "researcher" ) // Continue working - you'll be notified when complete // ... // Later, retrieve the results const result = await delegation_read(researchId) console.log(result) ``` -------------------------------- ### logWarn(client, service, message): void Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/primitives.md Logs a warning message. It can either use an OpenCode client for UI integration or fall back to `console.warn` if no client is provided. Logging failures are silently ignored. ```APIDOC ## logWarn(client, service, message): void ### Description Log a warning message via OpenCode client or console fallback. Silently ignores logging failures. ### Method ```typescript function logWarn( client: OpencodeClient | undefined, service: string, message: string ): void ``` ### Parameters #### Parameters - **client** (OpencodeClient | undefined) - Yes - Client for logging (or undefined) - **service** (string) - Yes - Service name for categorization - **message** (string) - Yes - Warning message ### Behavior - With client: Uses OpenCode logging API (integrates with UI) - Without client: Falls back to console.warn ### Example ```typescript // With client - logs to OpenCode UI logWarn(client, "delegation", "Task timed out after 30s") // Without client - logs to console logWarn(undefined, "delegation", "Task timed out after 30s") // Output: [delegation] Task timed out after 30s // In error handlers try { await getProjectId(projectRoot, client) } catch (error) { logWarn(client, "project-id", `Failed: ${error}`) } ``` ``` -------------------------------- ### Fire-and-Forget Async Agent Prompt Execution Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/architecture.md Demonstrates how agent prompt execution is handled asynchronously without awaiting the result, ensuring the main `delegate()` function returns immediately. Errors are caught and used to finalize the delegation. ```typescript this.client.session.prompt({ ... }) .then(() => this.finalizeDelegation(...)) .catch((error) => this.finalizeDelegation(..., error.message)) ``` -------------------------------- ### Get Root Commit SHA for Git Repository Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/configuration.md This command retrieves the SHA of the root commit for a Git repository, used for project identification. ```bash git rev-list --max-parents=0 --all ``` -------------------------------- ### Delegate a Background Task Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/README.md Launches a background task with the specified prompt and agent. This tool is intended for read-only sub-agents only. ```python delegate(prompt, agent) ``` -------------------------------- ### Delegation Workflow Hook Execution Order Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/hooks.md Illustrates the sequence of operations and hook invocations during a delegation workflow, from tool invocation to context compaction. ```text 1. Tool invocation: user calls delegate() ↓ 2. system.transform: Inject delegation rules into system prompt ↓ 3. delegate() executes, creates delegation, fires agent ↓ 4. message.updated events: Agent produces messages → event hook: handleMessageEvent() updates progress ↓ 5. session.idle event: Agent finishes → event hook: handleSessionIdle() finalizes delegation ↓ 6. Parent notification sent (async) ↓ 7. chat.message hook (on parent's next turn): → If notification delivery timed out, inject queued notification ↓ 8. delegation_read() called by parent → Returns persisted artifact ↓ 9. Context compaction (if triggered) → compacting hook: Inject running/unread delegations into context ``` -------------------------------- ### Get Pending Delegation Count Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/api-reference.md Retrieves the count of active delegations for a given parent session. This count includes delegations in 'registered' or 'running' status. ```typescript getPendingCount(parentSessionID: string): number ``` ```typescript const active = manager.getPendingCount("session-123") console.log(`${active} delegations still running`) ``` -------------------------------- ### Delegation Retrieval Instructions Format Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/hooks.md Markdown format providing instructions on how to retrieve delegation output using `delegation_read()` and emphasizing reliance on task notifications over polling. ```markdown ## Retrieval Use `delegation_read("id")` to access full delegation output. Do not poll delegation_list for completion; rely on task notifications. ``` -------------------------------- ### DelegationManager Constructor Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/exported-api.md Initializes a new instance of the DelegationManager. Requires an OpencodeClient, base directory, logger, and optional options. ```typescript constructor( client: OpencodeClient, baseDir: string, log: Logger, options?: DelegationManagerOptions ) ``` -------------------------------- ### Correct Approach: Wait for Notification Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/usage-patterns.md Illustrates the correct method of delegating a task and waiting for an automatic notification before retrieving results. This is efficient and recommended. ```typescript // RIGHT: Wait for notification, then retrieve const id = await delegate("Research topic", "researcher") // Continue working immediately console.log("Delegation started: " + id) // Notification will arrive automatically // Then call delegation_read() at that point ``` -------------------------------- ### System Prompt Injection for Delegation Rules Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/configuration.md This configuration is injected into the system prompt to educate the agent on when to use 'delegate' versus 'task' for background operations. ```xml ## Async Delegation You have tools for parallel background work: - `delegate(prompt, agent)` - Launch task, returns ID immediately - `delegation_read(id)` - Retrieve completed result - `delegation_list()` - List delegations (use sparingly) ## Delegation Routing Agents route based on their permissions: | Agent Type | Tool | Why | |------------|------|-----| | Read-only sub-agents (edit/write/bash denied) | `delegate` | Background session, async | | Write-capable sub-agents (any write permission) | `task` | Native task, preserves undo/branching | [... additional rules ...] ``` -------------------------------- ### Get Root Session ID for Isolation Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/hooks.md Retrieves the root session ID to ensure that only delegations visible to the compacting session's root are included, enforcing session isolation. ```typescript const rootSessionID = await manager.getRootSessionID(input.sessionID) const running = manager.getRunningDelegations(rootSessionID) ``` -------------------------------- ### Get Root Session ID Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/api-reference.md Resolves the root session ID by traversing the parent chain. Useful for identifying the top-level session in a delegation tree. Maximum depth is 10 levels. ```typescript async getRootSessionID(sessionID: string): Promise ``` ```typescript const rootId = await manager.getRootSessionID("sub-sub-session-id") // Returns the topmost session ID in the delegation tree ``` -------------------------------- ### BackgroundAgentsPlugin Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/api-reference.md Initializes the background agents plugin, registering delegation tools and hooks for OpenCode integration. ```APIDOC ## BackgroundAgentsPlugin ### Description Initializes the delegation system for OpenCode, providing tools for asynchronous task execution and persistent output storage. ### Method `async function` ### Signature `BackgroundAgentsPlugin(ctx: PluginContext): Promise` ### Parameters #### Path Parameters - **ctx** (`PluginContext`) - Yes - OpenCode plugin context containing client and directory ### Returns `PluginInterface` with the following properties: - **tool** (`object`) - Three delegation tools: `delegate`, `delegation_read`, `delegation_list` - **tool.execute.before** (`Hook`) - Prevents read-only agents from using native task tool - **experimental.chat.system.transform** (`Hook`) - Injects delegation rules into system prompt - **chat.message** (`Hook`) - Delivers queued notifications on user turns - **experimental.session.compacting** (`Hook`) - Injects delegation context during compaction - **event** (`Hook`) - Handles session idle and message events ### Example ```typescript import BackgroundAgentsPlugin from './background-agents.ts' // Plugin is automatically loaded by OpenCode registry system // Three tools become available: delegate(), delegation_read(), delegation_list() ``` ``` -------------------------------- ### Read delegation results Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/api-reference.md Retrieves the output of a completed delegation by its ID. This function blocks until the delegation is in a terminal state or a timeout occurs. Use this to get the final result of a delegated task. ```typescript async function delegation_read(id: string): Promise ``` ```typescript // Read a delegation result const result = await delegation_read("elegant-blue-tiger") console.log(result) // Output includes header: // # OAuth2 PKCE Best Practices // // Comprehensive research on secure OAuth2 flows... // **ID:** elegant-blue-tiger // **Agent:** researcher // **Status:** complete // **Started:** 2025-02-14T10:15:30.000Z // **Completed:** 2025-02-14T10:20:45.000Z // // --- // [full delegation output follows] ``` -------------------------------- ### Helper Functions Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/exported-api.md Provides utility functions for parsing agent modes and capabilities, and checking permissions. ```APIDOC ### Helper Functions - **parseAgentMode(client, agentName, log)**: `(client, agentName, log) => Promise<{ isSubAgent: boolean }>` - Parses the mode of an agent. - **parseAgentWriteCapability(client, agentName, log)**: `(client, agentName, log) => Promise<{ isReadOnly: boolean }>` - Parses the write capability of an agent. - **isPermissionDenied(entry)**: `(entry: PermissionEntry | undefined) => boolean` - Checks if a permission entry indicates a denied permission. ``` -------------------------------- ### List all delegations Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/exported-api.md Obtain a list of all existing delegations, including their titles and summaries. The output is formatted as a Markdown string. ```typescript async function delegation_list(): Promise ``` -------------------------------- ### Get Project ID (TypeScript) Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/primitives.md Generates a stable project identifier using git history or a path hash. Caches results in .git/opencode. Use for cross-worktree storage and stable project identity. ```typescript async function getProjectId( projectRoot: string, client?: OpencodeClient ): Promise ``` ```typescript // Git repository const projectId = await getProjectId("/home/user/my-repo") // Returns: "abc123def456..." (40-char git root SHA) // Non-git directory const projectId = await getProjectId("/home/user/notes") // Returns: "def456..." (16-char path hash) // Git worktree (shares ID with main repo) const projectId = await getProjectId("/home/user/my-repo/.git/worktrees/feature") // Returns: "abc123def456..." (same 40-char SHA as main repo) ``` -------------------------------- ### Project ID Generation Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/architecture.md Explains the two methods for generating project IDs used in disk persistence: a 40-character hex commit SHA for Git repositories and a 16-character hex hash for non-Git repositories. ```text **Project ID:** - 40-char hex: Git root commit SHA (stable across worktrees) - 16-char hex: Path hash (non-git repos) ``` -------------------------------- ### delegate Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/api-reference.md Creates a new delegation and initiates the associated agent process. This method is intended for internal use by the `delegate()` tool. ```APIDOC ## POST /delegate ### Description Creates a delegation and starts the agent. This method is called internally by the `delegate()` tool. ### Method POST ### Endpoint /delegate ### Parameters #### Request Body - **parentSessionID** (string) - Yes - Session ID of the delegating agent - **parentMessageID** (string) - Yes - Message ID where delegation was triggered - **parentAgent** (string) - Yes - Name of the delegating agent - **prompt** (string) - Yes - Full task prompt for the sub-agent - **agent** (string) - Yes - Name of the sub-agent to delegate to ### Response #### Success Response (200) - **id** (string) - Human-readable delegation ID - **status** (string) - "registered" (just created) - **sessionID** (string) - Isolated session ID for the delegation - **createdAt** (timestamp) - Timestamp of creation - **timeoutAt** (timestamp) - Deadline for completion ### Request Example ```json { "parentSessionID": "session-123", "parentMessageID": "msg-456", "parentAgent": "main", "prompt": "Research TypeScript generics", "agent": "researcher" } ``` ### Response Example ```json { "id": "elegant-blue-tiger", "status": "registered", "sessionID": "delegation-session-xyz", "createdAt": "2023-10-27T10:00:00Z", "timeoutAt": "2023-10-27T10:15:00Z" } ``` ``` -------------------------------- ### Delegate Method Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/api-reference.md Creates a new delegation and initiates the associated agent. This method is called internally by the `delegate()` tool. It performs validation checks and sets up an isolated session. ```typescript async delegate(input: { parentSessionID: string parentMessageID: string parentAgent: string prompt: string agent: string }): Promise ``` -------------------------------- ### Manage Multiple Parallel Tasks and Check Status Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/INDEX.md This pattern demonstrates how to initiate multiple background tasks concurrently using `Promise.all` and how to check the status of all delegations using `delegations_list`. It also shows how to retrieve results from all initiated tasks. ```typescript // Multiple tasks in parallel const ids = await Promise.all([ delegate("Task A", "agent1"), delegate("Task B", "agent2") ]) // Check status const list = await delegation_list() // Read all results const results = await Promise.all( ids.map(id => delegation_read(id)) ) ``` -------------------------------- ### delegate Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/exported-api.md Delegates a task to an agent with a given prompt. This is a user-facing tool. ```APIDOC ## delegate(prompt, agent) ### Description Delegates a task to an agent with a given prompt. This is a user-facing tool. ### Method Tool ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "prompt": "string", "agent": "string" } ``` ### Response #### Success Response (200) - **result** (any) - The result of the delegation. #### Response Example ```json { "result": "any" } ``` ``` -------------------------------- ### List All Delegations Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/README.md Retrieves a list of all background delegations, including their titles and summaries. This allows the AI to scan past research for relevant information. ```python delegation_list() ``` -------------------------------- ### Configure Write Permissions for task() Agents Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/configuration.md This JSON configuration grants write permissions, specifically allowing bash access, for an agent named 'executor'. Use this when an agent needs to perform write operations or execute commands via the `task` tool. ```json { "agent": { "executor": { "permission": { "bash": { "*": "allow" } } } } } ``` -------------------------------- ### generateMetadata Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/api-reference.md Generates title and description from delegation result using a small model. ```APIDOC ## INTERNAL UTILITY generateMetadata ### Description Generate title and description from delegation result using small model. ### Signature ```typescript async function generateMetadata( client: OpencodeClient, resultContent: string, parentID: string, debugLog: (msg: string) => Promise ): Promise ``` ### Returns Object with `title` (max 30 chars) and `description` (max 150 chars). ### Fallback If small model unavailable, truncates first line/paragraph. ``` -------------------------------- ### ListDelegations Method Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/api-reference.md Lists all delegations visible to a given session, including those persisted to the filesystem. It prioritizes in-memory delegations over persisted ones in case of duplicates. ```typescript async listDelegations(sessionID: string): Promise ``` -------------------------------- ### event Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/api-reference.md Handles various events to manage delegations and track progress. ```APIDOC ## EVENT HANDLER event ### Description Handles various events to manage delegations and track progress. ### Signature ```typescript event: (props: { event: Event }) => Promise ``` ### Handles - `session.idle` / `session.status` (type: "idle"): Finalize delegation when session becomes idle - `message.updated`: Track progress for running delegations ``` -------------------------------- ### Injected Delegation Rules and Routing Guidance Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/hooks.md The XML content injected into the system prompt by the hook. It provides instructions for async delegation and agent routing based on permissions. ```xml ## Async Delegation You have tools for parallel background work: - `delegate(prompt, agent)` - Launch task, returns ID immediately - `delegation_read(id)` - Retrieve completed result - `delegation_list()` - List delegations (use sparingly) ## Delegation Routing Agents route based on their permissions: | Agent Type | Tool | Why | |------------|------|-----| | Read-only sub-agents (edit/write/bash denied) | `delegate` | Background session, async | | Write-capable sub-agents (any write permission) | `task` | Native task, preserves undo/branching | **Read-only sub-agents** have edit="deny", write="deny", bash={"*":"deny"}. **Write-capable sub-agents** have any write tool enabled. ## How It Works 1. For read-only sub-agents: Call `delegate` with detailed prompt 2. For write-capable sub-agents: Call `task` with detailed prompt 3. Continue productive work while it runs 4. Receive notification when complete 5. Call `delegation_read(id)` to retrieve results ## Critical Constraints **NEVER poll `delegation_list` to check completion.** You WILL be notified via ``. Polling wastes tokens. **NEVER wait idle.** Always have productive work while delegations run. **Using wrong tool will fail fast with guidance.** ``` -------------------------------- ### tool.execute.before Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/api-reference.md This hook prevents read-only sub-agents from using the native `task` tool, enforcing the use of `delegate` instead. ```APIDOC ## HOOK tool.execute.before ### Description Prevents read-only sub-agents from using the native `task` tool, enforcing use of `delegate` instead. ### Signature ```typescript "tool.execute.before": (input: { tool: string }, output: { args?: { subagent_type?: string } }) => Promise ``` ``` -------------------------------- ### Import OpenCode Primitives Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/README.md Imports various utility functions and types from the OpenCode primitives module, such as project ID retrieval, timeout handling, mutex, escaping utilities, temporary directory access, logging, and tmux detection. ```typescript import { getProjectId, withTimeout, TimeoutError, Mutex, escapeApache, escapeBash, escapeBatch, getTempDir, logWarn, isInsideTmux, type OpencodeClient } from './src/plugin/kdco-primitives' ``` -------------------------------- ### delegate(prompt: string, agent: string): Promise Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/exported-api.md Fire off a background task and return immediately with a readable ID. This function is used to delegate a task to a specific agent and returns a unique identifier for the delegation. ```APIDOC ## delegate(prompt: string, agent: string): Promise ### Description Fire off a background task and return immediately with a readable ID. This function is used to delegate a task to a specific agent and returns a unique identifier for the delegation. ### Method POST ### Endpoint /delegate ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **prompt** (string) - Required - Task prompt in English - **agent** (string) - Required - Read-only sub-agent name ### Request Example ```json { "prompt": "Write a summary of the latest news.", "agent": "news-summarizer" } ``` ### Response #### Success Response (200) - **delegation_id** (string) - Human-readable delegation ID (e.g., "elegant-blue-tiger") #### Response Example ```json { "delegation_id": "elegant-blue-tiger" } ``` ### Errors - `Error` if agent not found - `Error` if agent is write-capable ``` -------------------------------- ### Session Creation Failure Error Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/lifecycle.md This error is thrown when the client fails to create a delegation session. The delegation is not registered. ```text Error: Failed to create delegation session ``` -------------------------------- ### listDelegations Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/api-reference.md Lists all delegations visible to a given session, including those persisted on disk. Deduplicates entries, prioritizing in-memory delegations. ```APIDOC ## GET /sessions/{sessionID}/delegations ### Description List all delegations visible to a session, including persisted ones from disk. ### Method GET ### Endpoint /sessions/{sessionID}/delegations ### Parameters #### Path Parameters - **sessionID** (string) - Yes - Session ID for visibility scoping ### Response #### Success Response (200) - **delegations** (array) - Array of `DelegationListItem` objects. - **id** (string) - Delegation ID - **status** (string) - Current status: "registered" | "running" | "complete" | "error" | "cancelled" | "timeout" - **title** (string) - Optional title of the delegation - **description** (string) - Optional description of the delegation - **agent** (string) - Optional name of the agent that performed the delegation - **unread** (boolean) - Optional flag indicating if there are unread updates ### Response Example ```json [ { "id": "elegant-blue-tiger", "status": "complete", "title": "Research TypeScript Generics", "agent": "researcher" }, { "id": "swift-red-fox", "status": "running", "unread": true } ] ``` ``` -------------------------------- ### Write-Capable Executor Agent Configuration Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/usage-patterns.md Configure an agent to be write-capable by allowing bash execution. This is necessary for agents that need to perform actions or modify files. ```json { "agent": { "executor": { "permission": { "bash": { "run": "allow" } } } } } ``` -------------------------------- ### delegation_list Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/exported-api.md Lists all available delegations. This is a user-facing tool. ```APIDOC ## delegation_list() ### Description Lists all available delegations. This is a user-facing tool. ### Method Tool ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json {} ``` ### Response #### Success Response (200) - **delegations** (array) - An array of delegation records. #### Response Example ```json { "delegations": [ { "id": "string", "status": "DelegationStatus", "result": "any" } ] } ``` ``` -------------------------------- ### Early Exit Design Principle Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/primitives.md Illustrates the early exit pattern, returning or throwing immediately on success or error to avoid nested conditionals. ```plaintext if (!value) return fallback ``` -------------------------------- ### delegation_list(): Promise Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/exported-api.md List all delegations with titles and summaries. This function provides a markdown-formatted list of all available delegations. ```APIDOC ## delegation_list(): Promise ### Description List all delegations with titles and summaries. This function provides a markdown-formatted list of all available delegations. ### Method GET ### Endpoint /delegations ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json {} ``` ### Response #### Success Response (200) - **delegation_list** (string) - Markdown-formatted delegation list #### Response Example ```json { "delegation_list": "- **elegant-blue-tiger**: Write a summary of the latest news." } ``` ``` -------------------------------- ### Import Main Background Agents Plugin Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/README.md Imports the main BackgroundAgentsPlugin. This plugin automatically exports several delegation-related tools and hooks for system integration. ```typescript import BackgroundAgentsPlugin from './src/plugin/background-agents.ts' // Plugin automatically exports: // - tool.delegate // - tool.delegation_read // - tool.delegation_list // - Hooks for system integration // - testInternals (for testing) ``` -------------------------------- ### Session and Execution Error Handling Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/architecture.md Details the error handling process during session creation and execution, including result collection, metadata generation, artifact persistence, and parent notification. Failures are logged, and fallback mechanisms are employed. ```plaintext Session creation ├─ Session created ✓ ├─ Agent fires ✓ └─ Finalization pipeline ├─ Result collection ├─ Metadata generation (timeout graceful) ├─ Artifact persistence (fallback to deterministic) └─ Parent notification (queued on failure) ``` -------------------------------- ### Export all kdco-primitives Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/primitives.md Centralized export of all utility functions from the kdco-primitives module. Import specific functions as needed. ```typescript export { getProjectId } from "./get-project-id" export { logWarn } from "./log-warn" export { Mutex } from "./mutex" export { assertShellSafe, escapeBash, escapeAppleScript, escapeBatch } from "./shell" export { getTempDir } from "./temp" export { isInsideTmux } from "./terminal-detect" export type { OpencodeClient } from "./types" export { TimeoutError, withTimeout } from "./with-timeout" ``` ```typescript import { getProjectId, withTimeout, Mutex, getTempDir, escapeBash, isInsideTmux, logWarn, type OpencodeClient } from "./kdco-primitives" ``` -------------------------------- ### Using a Write-Capable Agent Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/usage-patterns.md Use the `task` function to interact with a write-capable agent. The `delegate` function will throw an error if used with a write-capable agent. ```typescript // Must use task, not delegate // delegate() will throw error directing to task await task("Run build script", "executor") ``` -------------------------------- ### DelegationRecord Interface Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/types.md Represents a complete snapshot of the state for a single background agent delegation. Includes all details from creation to completion or failure. ```typescript interface DelegationRecord { id: string rootSessionID: string sessionID: string parentSessionID: string parentMessageID: string parentAgent: string prompt: string agent: string notificationCycle: number notificationCycleToken: string status: DelegationStatus createdAt: Date startedAt?: Date completedAt?: Date updatedAt: Date timeoutAt: Date progress: DelegationProgress notification: DelegationNotificationState retrieval: DelegationRetrievalState artifact: DelegationArtifactState error?: string title?: string description?: string result?: string } ``` -------------------------------- ### Run Multiple Tasks in Parallel Source: https://github.com/kdcokenny/opencode-background-agents/blob/main/_autodocs/README.md Use Promise.all to execute multiple delegation tasks concurrently. This is useful when you need to perform several independent operations simultaneously. ```typescript const [r1, r2, r3] = await Promise.all([ delegate("Research topic A", "researcher"), delegate("Research topic B", "researcher"), delegate("Explore codebase", "explore") ]) // All run concurrently in background ```