### Multi-Agent Communication Workflow Example in TypeScript Source: https://context7.com/spoons-and-mirrors/pocket-universe/llms.txt This TypeScript example illustrates a multi-agent workflow where two agents, AgentA (frontend) and AgentB (backend), communicate using the broadcast tool. It shows agents announcing their presence, AgentA querying AgentB, AgentB responding using `reply_to`, and AgentA acknowledging the response. ```typescript // Parent session spawns two agents // Agent A: Frontend development // Agent B: Backend API development // === AgentA starts and announces === broadcast(message="Building user dashboard components") // Result: You are: agentA // No other agents available yet. // === AgentB starts and announces === broadcast(message="Implementing REST API endpoints") // Result: You are: agentB // Available agents: // - agentA: Building user dashboard components // === AgentA discovers AgentB and asks a question === broadcast(send_to="agentB", message="What's the endpoint for fetching user profiles?") // Result: You are: agentA // Available agents: // - agentB: Implementing REST API endpoints // Message sent to: agentB // === AgentB receives message in synthetic injection === // Synthetic tool result appears: // { // "agents": [{ "name": "agentA", "status": "Building user dashboard components" }], // "messages": [{ "id": 1, "from": "agentA", "content": "What's the endpoint for fetching user profiles?" }] // } // === AgentB replies using reply_to === broadcast(reply_to=1, message="GET /api/v1/users/:id - returns { id, name, email, avatar }") // Result: You are: agentB // Available agents: // - agentA: Building user dashboard components // Replied to #1 from agentA: // "What's the endpoint for fetching user profiles?" // === AgentA receives response and acknowledges === broadcast(reply_to=1, message="Perfect, implementing the fetch now. Thanks!") // Message automatically sent to agentB ``` -------------------------------- ### Install IAM Plugin for OpenCode Source: https://github.com/spoons-and-mirrors/pocket-universe/blob/main/README.md To enable parallel agent communication using the IAM plugin, add the specified configuration to your OpenCode settings. This is a one-time setup for the project. ```json "plugin": ["@spoons-and-mirrors/iam@latest"] ``` -------------------------------- ### Install IAM Plugin Source: https://context7.com/spoons-and-mirrors/pocket-universe/llms.txt Configure IAM as an OpenCode plugin by adding its package to your project's configuration file. This enables the inter-agent messaging capabilities. ```json { "plugin": ["@spoons-and-mirrors/iam@latest"] } ``` -------------------------------- ### Example Workflow Source: https://github.com/spoons-and-mirrors/pocket-universe/blob/main/README.md Illustrates a typical workflow where agents communicate to coordinate tasks, such as one agent requesting an API schema from another. ```APIDOC ## Example Workflow ``` # Parent spawns two agents to work on different parts of a feature AgentA (working on frontend): -> broadcast(message="Starting frontend work") # Tool result shows: "Available agents: agentB" -> ... does work ... -> broadcast(send_to="agentB", message="Need the API schema") AgentB (working on backend): -> broadcast(message="Starting backend work") # Tool result shows: "Available agents: agentA" -> ... sees AgentA's question in inbox ... -> broadcast(reply_to=1, message="Here's the schema: {...}") # Tool result shows: Marked as handled: #1 from agentA # Recipient auto-wired to agentA AgentA: -> ... sees AgentB's response in inbox ... -> broadcast(reply_to=1, message="Got it, thanks!") # Recipient auto-wired to agentB ``` ``` -------------------------------- ### Enabling and Understanding Debug Logs in Bash and TypeScript Source: https://context7.com/spoons-and-mirrors/pocket-universe/llms.txt This section shows how to enable debug logging for IAM by setting the OPENCODE_IAM_DEBUG_LOGS environment variable in bash. It also provides a TypeScript example demonstrating how to use the logger with different log levels and categories, and how to flush logs before exiting. ```bash # Enable debug logging export OPENCODE_IAM_DEBUG_LOGS=1 # Log output format # [2024-01-15T10:30:00.000Z] [INFO] [SESSION] Session registered | {"sessionId":"abc123","alias":"agentA","totalSessions":2} # [2024-01-15T10:30:01.000Z] [INFO] [MESSAGE] Message sent | {"id":"xy7k2m","msgIndex":1,"from":"agentA","to":"agentB","bodyLength":45} # [2024-01-15T10:30:02.000Z] [INFO] [INJECT] Injecting synthetic broadcast | {"sessionId":"def456","alias":"agentB","agentCount":1,"messageCount":1} ``` ```typescript import { log, LOG } from "./logger"; // Available log categories log.debug(LOG.TOOL, "broadcast called", { alias: "agentA", send_to: "agentB" }); log.info(LOG.MESSAGE, "Message sent", { from: "agentA", to: "agentB" }); log.warn(LOG.SESSION, "Session lookup failed", { sessionId: "abc123" }); log.error(LOG.HOOK, "Hook execution failed", { error: "Connection timeout" }); // Force flush before process exit await log.flush(); ``` -------------------------------- ### IAM Plugin Installation Source: https://github.com/spoons-and-mirrors/pocket-universe/blob/main/README.md Add the IAM plugin to your OpenCode configuration to enable inter-agent messaging. ```APIDOC ## Installation Add to your OpenCode config: ```json "plugin": ["@spoons-and-mirrors/iam@latest"] ``` ``` -------------------------------- ### Registering Broadcast Tool and System Hooks in TypeScript Source: https://context7.com/spoons-and-mirrors/pocket-universe/llms.txt This TypeScript code defines a plugin that registers a 'broadcast' tool for inter-agent communication and injects system prompts and pending messages into child sessions using experimental hooks. It also modifies configuration to include 'broadcast' in subagent tools. ```typescript import type { Plugin } from "@opencode-ai/plugin"; import { tool } from "@opencode-ai/plugin"; const plugin: Plugin = async (ctx) => { const client = ctx.client; return { // Register the broadcast tool tool: { broadcast: tool({ description: "Communicate with other parallel agents", args: { send_to: tool.schema.string().optional().describe("Target agent"), message: tool.schema.string().describe("Your message"), reply_to: tool.schema.number().optional().describe("Message ID to reply to"), }, async execute(args, context) { // Handle messaging logic const sessionId = context.sessionID; // ... send/receive messages }, }), }, // Inject system prompt for child sessions "experimental.chat.system.transform": async (input, output) => { const sessionId = input.sessionID; // Register session and inject IAM instructions output.system.push(SYSTEM_PROMPT); }, // Inject pending messages into conversation "experimental.chat.messages.transform": async (input, output) => { // Append synthetic broadcast result with inbox contents const inboxMsg = createInboxMessage(sessionId, unhandledMessages, parallelAgents); output.messages.push(inboxMsg); }, // Add broadcast to subagent tools "experimental.config.transform": async (input, output) => { output.experimental = { ...output.experimental, subagent_tools: [...(output.experimental?.subagent_tools ?? []), "broadcast"], }; }, }; }; export default plugin; ``` -------------------------------- ### Use broadcast Tool for Agent Communication Source: https://context7.com/spoons-and-mirrors/pocket-universe/llms.txt The `broadcast` tool is the primary interface for agents to communicate. It allows agents to announce their status, send messages to all other agents, target specific agents, and reply to messages, automatically handling recipient resolution. ```typescript // Announce yourself (first call sets your status visible to other agents) broadcast(message="Working on frontend components") // Returns: You are: agentA // No other agents available yet. // Send message to all known agents broadcast(message="Does anyone have the API schema?") // Returns: You are: agentA // Available agents: // - agentB: Working on backend API // Message sent to: agentB // Send to specific agent broadcast(send_to="agentB", message="Need the user authentication endpoint details") // Returns: You are: agentA // Available agents: // - agentB: Working on backend API // Message sent to: agentB // Reply to a specific message (auto-wires recipient to original sender) broadcast(reply_to=1, message="Here's the schema: { users: [...] }") // Returns: You are: agentB // Available agents: // - agentA: Working on frontend components // Replied to #1 from agentA: // "Need the user authentication endpoint details" ``` -------------------------------- ### The `broadcast` Tool Source: https://github.com/spoons-and-mirrors/pocket-universe/blob/main/README.md Use the `broadcast` tool to send messages between agents. You can send to all agents, a specific agent, or reply to a previous message. ```APIDOC ## The `broadcast` Tool ``` broadcast(message="...") # Send to all agents broadcast(send_to="agentB", message="...") # Send to specific agent broadcast(reply_to=1, message="...") # Reply to message #1 (auto-wires recipient) ``` ### Parameters | Parameter | Required | Description | | ---------- | -------- | --------------------------------------------------------------- | | `message` | Yes | Your message content | | `send_to` | No | Target agent (single agent only) | | `reply_to` | No | Message ID to reply to - auto-wires recipient to message sender | ``` -------------------------------- ### IAM Synthetic Message Injection Format Source: https://context7.com/spoons-and-mirrors/pocket-universe/llms.txt Incoming messages and agent discovery information are delivered to agents via synthetic `broadcast` tool results. This JSON structure details the tool's state, including agent statuses and pending messages. ```json { "tool": "broadcast", "state": { "status": "completed", "input": { "synthetic": true }, "output": { "hint": "ACTION REQUIRED: Announce yourself to other agents by calling broadcast(message=\"what you're working on\")", "agents": [ { "name": "agentA", "status": "Working on frontend components" }, { "name": "agentC", "status": "Running integration tests" } ], "messages": [ { "id": 1, "from": "agentA", "content": "What's the status on the API?" }, { "id": 2, "from": "agentA", "content": "Also, can you check the tests?" } ] }, "title": "2 agent(s), 2 message(s)", "metadata": { "incoming_message": true, "message_count": 2, "agent_count": 2 } } } ``` -------------------------------- ### IAM Broadcast Tool Usage Source: https://github.com/spoons-and-mirrors/pocket-universe/blob/main/README.md The `broadcast` tool is central to IAM, allowing agents to send messages. It supports broadcasting to all agents, specific agents by name, or replying to a previous message using its ID. ```python broadcast(message="...") # Send to all agents broadcast(send_to="agentB", message="...") # Send to specific agent broadcast(reply_to=1, message="...") # Reply to message #1 (auto-wires recipient) ``` -------------------------------- ### IAM Message Structure Source: https://github.com/spoons-and-mirrors/pocket-universe/blob/main/README.md Incoming messages are presented as a synthetic `broadcast` tool result within the agent's environment. This JSON structure details the message's origin, content, and associated metadata, including other active agents. ```json { "tool": "broadcast", "state": { "status": "completed", "input": { "synthetic": true }, "output": { "hint": "ACTION REQUIRED: Announce yourself...", "agents": [ { "name": "agentA", "status": "Working on frontend components" } ], "messages": [ { "id": 1, "from": "agentA", "content": "What's the status on the API?" }, { "id": 2, "from": "agentA", "content": "Also, can you check the tests?" } ] }, "title": "1 agent(s), 2 message(s)" } } ``` -------------------------------- ### Receiving Messages Source: https://github.com/spoons-and-mirrors/pocket-universe/blob/main/README.md Messages from other agents are injected as a synthetic `broadcast` tool result. This structure includes sender information, message content, and other agents' statuses. ```APIDOC ## Receiving Messages Messages are injected as a synthetic `broadcast` tool result. Here's the complete structure: ```json { "tool": "broadcast", "state": { "status": "completed", "input": { "synthetic": true }, "output": { "hint": "ACTION REQUIRED: Announce yourself...", "agents": [ { "name": "agentA", "status": "Working on frontend components" } ], "messages": [ { "id": 1, "from": "agentA", "content": "What's the status on the API?" }, { "id": 2, "from": "agentA", "content": "Also, can you check the tests?" } ] }, "title": "1 agent(s), 2 message(s)" } } ``` - **`input.synthetic`**: Indicates this was injected by IAM, not a real agent call - **`output.hint`**: Shown only if agent hasn't announced yet (disappears after first broadcast) - **`output.agents`**: Other agents and their status (not replyable) - **`output.messages`**: Messages you can reply to using `reply_to` Messages persist in the inbox until the agent marks them as handled using `reply_to`. **Discovery:** Agents discover each other through synthetic injection. The first `broadcast` call sets the agent's status, which other agents see in the `agents` array. ``` -------------------------------- ### Attention Layer Source: https://github.com/spoons-and-mirrors/pocket-universe/blob/main/README.md Pending inbox messages are injected as a synthetic `broadcast` tool result at the end of the message chain during every LLM fetch. ```APIDOC ## Attention Layer On every LLM fetch, pending inbox messages are injected as a synthetic `broadcast` tool result at the end of the message chain. The synthetic call has `input: { synthetic: true }` to indicate it was injected by IAM, not a real agent call. After injection, the message chain looks like: 1. system prompt 2. user message 3. assistant response 4. tool calls... 5. user message 6. **`[broadcast]` 1 agent(s), 2 message(s)** ← injected at end ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.