// Chat Relay - Dynamic Multi-Agent Chat Extension import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; import { execSync } from "node:child_process"; import { writeFileSync } from "node:fs"; import { randomUUID } from "node:crypto"; const LOG = "/tmp/chat-relay.log"; function log(msg: string) { writeFileSync(LOG, msg + "\n", { flag: "a" }); } function clearLog() { writeFileSync(LOG, ""); } // State management for conversation flow interface RelayState { waitingForResponse: boolean; currentTarget: string; responseTarget: string; } function runHerdr(args: string[]): { stdout: string; stderr: string } { try { const result = execSync(`herdr ${args.join(' ')}`, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 5000 }); return { stdout: result, stderr: '' }; } catch (e: any) { return { stdout: '', stderr: e.message }; } } // Find pane by workspace directory name function findPaneByWorkspace(workspaceName: string): string | null { const result = runHerdr(["agent", "list"]); try { const data = JSON.parse(result.stdout); for (const agent of data?.result?.agents || []) { if (agent.cwd?.includes(workspaceName)) { return agent.pane_id; } } } catch (e) { log(`Failed to find pane: ${e}`); } return null; } function sendToPane(paneId: string, text: string): void { const escaped = text.replace(/'/g, "'\"'\"'"); try { execSync(`herdr pane send-text '${paneId}' '${escaped}'`, { encoding: 'utf8', stdio: 'ignore' }); execSync(`herdr pane send-keys '${paneId}' enter`, { encoding: 'utf8', stdio: 'ignore' }); } catch (e: any) { log(`Send failed: ${e.message}`); } } // Detect identity from cwd (workspace name = agent name = display name) function getIdentity(): { displayName: string; workspaceName: string } { const cwd = process.cwd(); const workspaceName = cwd.split('/').pop() || ""; return { displayName: workspaceName, workspaceName }; } // Parse incoming message function parseIncomingMessage(text: string): { sender: string; message: string; responseTo: string } | null { text = text.trim(); // Handle GOT INPUT wrapper const gotInputMatch = text.match(/^GOT INPUT:\s*(.+?)\s*─+$/s); if (gotInputMatch) { text = gotInputMatch[1].trim(); } if (text.startsWith('GOT INPUT:')) { const lines = text.split('\n'); text = lines.slice(1, -1).join('\n').trim(); } // Handle JSON format if (text.startsWith('{')) { try { const json = JSON.parse(text); const message = json.DELEGATE?.MESSAGE || json.FROM_PARTNER?.message; const sender = json.DELEGATE?.ORIGIN || json.FROM_PARTNER?.sender; const responseTo = json.DELEGATE?.RESPONSE_TO || sender; if (message && sender) { return { sender, message, responseTo }; } } catch (e) {} } // Handle "Sender: message" format // Strip "From-" prefix if present (explicit relay format) if (text.startsWith('From-')) { text = text.substring(5); } const colonIndex = text.indexOf(':'); if (colonIndex > 0 && colonIndex < 50) { const sender = text.substring(0, colonIndex); const message = text.substring(colonIndex + 1).trim(); if (sender.length > 0 && message.length > 0) { if (['Skills', 'Extensions', 'Reloaded', 'Chat relay'].includes(sender)) { return null; } return { sender, message, responseTo: sender }; } } return null; } export default function (pi: ExtensionAPI) { const identity = getIdentity(); const displayName = identity.displayName; const state: RelayState = { waitingForResponse: false, currentTarget: "", responseTarget: "" }; clearLog(); log(`Chat relay loaded for ${displayName}`); // Register /chat command pi.registerCommand("chat", { description: "Start a chat relay with another agent: /chat : ", handler: async (args, ctx) => { // Parse /chat : const match = args.match(/^([\w-]+):\s*(.+)$/); if (!match) { ctx.ui.notify("Usage: /chat : ", "error"); ctx.ui.notify("Example: /chat kat: Let's debate pizza toppings", "info"); return; } const targetAgent = match[1]; const topic = match[2].trim(); // Agent name IS the workspace name - no lookup needed const targetWorkspace = targetAgent; if (targetWorkspace === identity.workspaceName) { ctx.ui.notify("Cannot chat with yourself!", "error"); return; } // Find target pane const targetPane = findPaneByWorkspace(targetWorkspace); if (!targetPane) { ctx.ui.notify(`Agent ${targetAgent} not found`, "error"); return; } // Construct initial message // responseTo tells the target who to send responses back to const taskId = randomUUID(); const msg = JSON.stringify({ DELEGATE: { ORIGIN: displayName, RESPONSE_TO: displayName, // Send responses back to me TYPE: "text", TASK_ID: taskId, MESSAGE: topic } }); log(`Starting chat with ${targetAgent} about: ${topic.substring(0, 30)}...`); ctx.ui.notify(`Starting chat with ${targetAgent}...`, "info"); // Send to target sendToPane(targetPane, msg); log(`Sent initial message to ${targetAgent}`); // Set state to wait for response from THIS target state.waitingForResponse = true; state.currentTarget = targetWorkspace; state.responseTarget = displayName; ctx.ui.notify("Chat initiated! Responses will be relayed automatically.", "info"); } }); // Handle input events pi.on("input", async (event) => { const rawText = event.text || ""; const text = rawText.trim(); log(`INPUT: ${text.substring(0, 80)}`); // Skip commands (already handled by registerCommand) if (text.startsWith('/')) { return { action: "continue" }; } // Parse incoming relay message const parsed = parseIncomingMessage(text); if (parsed) { log(`Relay message from ${parsed.sender}: ${parsed.message.substring(0, 40)}`); // Skip self-echo if (parsed.sender === displayName) { log(`SKIP: self-echo`); return { action: "continue" }; } // Set up response routing state.waitingForResponse = true; state.currentTarget = parsed.sender; state.responseTarget = parsed.responseTo; // Transform for LLM - use "From-" prefix to clearly mark as relay message const transformed = `From-${parsed.sender}: ${parsed.message}`; log(`Transforming: ${transformed.substring(0, 40)}`); return { action: "transform", text: transformed }; } // Skip if waiting for response (don't process user input) if (state.waitingForResponse) { log(`SKIP: waiting for response`); return { action: "continue" }; } return { action: "continue" }; }); // Relay LLM response back pi.on("agent_end", async (event, ctx) => { if (!state.waitingForResponse) { return; } log(`agent_end: extracting response`); state.waitingForResponse = false; // Find last assistant message const entries = ctx.sessionManager.getEntries(); let lastAssistant: any = null; for (let i = entries.length - 1; i >= 0; i--) { const entry = entries[i] as any; if (entry.role === "assistant") { lastAssistant = entry; break; } if (entry.type === "message" && entry.message?.role === "assistant") { lastAssistant = entry.message; break; } } if (!lastAssistant) { log(`No assistant message found`); return; } // Extract content let message = ""; const content = lastAssistant.content; if (content) { for (const block of content) { if (block.type === "text") { message += block.text; } } } if (!message.trim()) { log(`Empty response, skipping`); return; } log(`Response: ${message.trim().substring(0, 50)}...`); // No AGENT_MAP - agent name IS the workspace name const targetWorkspace = state.responseTarget; const targetPane = findPaneByWorkspace(targetWorkspace); if (!targetPane) { log(`Target pane not found: ${state.responseTarget}`); return; } // Send response const msg = JSON.stringify({ FROM_PARTNER: { sender: displayName, message: message.trim() } }); sendToPane(targetPane, msg); log(`Sent response to ${state.responseTarget}`); // Continue waiting for their response state.waitingForResponse = true; state.currentTarget = state.responseTarget; }); log(`Chat relay ready. Use /chat : to start.`); }