/** * PAL plugin for opencode — thin adapter over shared hooks/lib/ modules. * * All business logic lives in hooks/lib/ so it stays in sync with Claude Code hooks. * This plugin just wires opencode's hook API to those shared functions. */ import { spawnSync } from "node:child_process"; import { resolve } from "node:path"; import type { Hooks, Plugin, PluginInput } from "@opencode-ai/plugin"; const PAL_DIR = process.env.PAL_DIR || resolve(import.meta.dir, "../../.."); // Force-override (= not ??=): a PAL_AGENT inherited from the parent shell, as when // opencode starts from a Claude Code terminal, would route inference to that CLI. process.env.PAL_AGENT = "opencode"; async function lib(mod: string): Promise { return await import(resolve(PAL_DIR, "src", "hooks", "lib", mod)); } type TranscriptMessage = { role: string; content: string; id?: string }; function isSessionEvent(type: string): boolean { return type.startsWith("session."); } type OpencodeEvent = Parameters>[0]["event"]; const PALPlugin: Plugin = async ({ directory, client }: PluginInput) => { const { buildSystemReminder } = await lib("context.ts"); const { checkBashCommand, checkFilePath } = await lib("security.ts"); const { findBinaryOnPath } = await lib("which.ts"); // `rtk hook check ` prints the rewritten command (exit 0), or nothing // (exit 1) when a command isn't worth wrapping. const rtkBin = findBinaryOnPath("rtk"); const rtkRewrite = (cmd: string): string | null => { if (!rtkBin || !cmd) return null; try { const r = spawnSync(rtkBin, ["hook", "check", cmd], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], }); const out = r.status === 0 ? (r.stdout ?? "").trim() : ""; return out && out !== cmd ? out : null; } catch { return null; } }; const { logDebug, logError, logPromptSnapshot } = await lib("log.ts"); const { runStopHandlers } = await lib("stop.ts"); const { logToolCall } = await lib("tool-events.ts"); const { recordSlurpCheck } = await lib("slurp-check.ts"); const { attachProgressFromToolCall } = await lib< typeof import("../../hooks/lib/progress-tree-tool") >("progress-tree-tool.ts"); const { logAttention } = await lib("attention-events.ts"); const { logOpencodeCompaction, logOpencodePermissionReply, logOpencodeSessionCreated, logOpencodeToolFailure, rememberAskedTool, } = await lib("opencode-events.ts"); const { captureSessionName } = await lib< typeof import("../../hooks/handlers/session-name") >("../handlers/session-name.ts"); const { captureRating } = await lib( "../handlers/rating.ts" ); const { getPromptContext } = await lib< typeof import("../../hooks/handlers/inject-retrieval") >("../handlers/inject-retrieval.ts"); function partsToText(parts: Array>): string { return parts .filter((p) => p?.type === "text" && !p.ignored && !p.synthetic) .map((p) => (typeof p.text === "string" ? p.text : "")) .join(" ") .trim(); } async function buildSessionTranscript(sessionID: string): Promise { const result = await client.session.messages({ path: { id: sessionID }, query: { directory }, }); if (result.error || !result.data) { logDebug( "opencode:session.messages", `Failed to fetch messages (error=${Boolean(result.error)})` ); return []; } const rows = result.data as Array<{ info: { role?: string; id?: string }; parts: Array>; }>; return rows .map((row) => { const role = row?.info?.role ?? "unknown"; const content = partsToText(row?.parts ?? []); return { role, content, id: row?.info?.id }; }) .filter((m) => m.content.length > 0); } async function runStopHandlersOnIdle(event: unknown): Promise { const sessionID = (event as { properties?: { sessionID?: string } })?.properties ?.sessionID; if (!sessionID) { logDebug("opencode:event", "Skipping stop handlers: missing sessionID"); return; } const messages = await buildSessionTranscript(sessionID); logDebug("opencode:event", `Got ${messages.length} transcript messages`); if (messages.length < 2) return; // Last assistant message feeds response caching (parity with Claude Code). const lastAssistant = messages .filter((m: TranscriptMessage) => m.role === "assistant") .pop(); await runStopHandlers(messages, { sessionId: sessionID, lastAssistantMessage: lastAssistant?.content, }); logDebug("opencode:event", "Stop handlers complete"); } function guardShellCall(output: { args: Record | string }): void { const cmd = typeof output.args === "string" ? output.args : ((output.args?.command as string) ?? ""); const reason = checkBashCommand(cmd); if (reason) { throw new Error(`PAL Security: Blocked — ${reason}`); } const rewritten = rtkRewrite(cmd); if (!rewritten) return; if (typeof output.args === "string") output.args = rewritten; else (output.args as Record).command = rewritten; } function guardFileWrite(args: Record): void { const filePath = args?.file_path ?? args?.filePath ?? args?.path ?? ""; const fileReason = checkFilePath(filePath); if (fileReason) { throw new Error(`PAL Security: ${fileReason}`); } } const { isPalSpawnedInference } = await lib("spawn-guard.ts"); const { commitApplied, ledgeredTarget, snapshotCall } = await lib("ledger-hook.ts"); function logEventDetails(event: OpencodeEvent): void { if (event.type === "session.created") logOpencodeSessionCreated(event.properties.info); if (event.type === "session.compacted") logOpencodeCompaction(event.properties.sessionID); if (event.type === "permission.replied") logOpencodePermissionReply(event.properties); if (event.type === "message.part.updated") logOpencodeToolFailure(event.properties.part); } async function onSessionOpenedOrUpdated(event: OpencodeEvent): Promise { if (event.type === "session.created") { const { heartbeatOnStart } = await lib("telemetry.ts"); heartbeatOnStart(); } if (event.type === "session.created" || event.type === "session.updated") { const { regenerateIfNeeded } = await lib("claude-md.ts"); regenerateIfNeeded(); } } const ledgeredOpencodeCall = (tool: string, callID: string, args: unknown) => { const target = ledgeredTarget(tool, (args ?? {}) as Record); return target ? { toolUseId: callID, tool, target } : null; }; return { "experimental.chat.system.transform": async (input, output) => { if (isPalSpawnedInference()) return; const reminder = buildSystemReminder({ agent: "opencode", sessionId: input.sessionID, }); if (reminder) output.system.push(reminder); }, event: async ({ event }) => { if (isPalSpawnedInference()) return; if (isSessionEvent(event.type)) logDebug("opencode:event", `Event: ${event.type}`); if (event.type === "server.instance.disposed") { const { autoUpdateOnClose } = await lib("auto-update.ts"); autoUpdateOnClose(); } logEventDetails(event); await onSessionOpenedOrUpdated(event); if (event.type === "session.idle") { logDebug("opencode:event", "Running stop handlers..."); try { await runStopHandlersOnIdle(event); } catch (err) { logError("opencode:session.stop", err); } } }, "chat.message": async (input, output) => { if (isPalSpawnedInference()) return; const text = partsToText(output.parts ?? []); if (!text.trim()) return; const sentAt = new Date(); const injectedText = (await getPromptContext(text, input.sessionID)) ?? ""; logPromptSnapshot(text, injectedText || null); await Promise.allSettled([ captureRating(text, input.sessionID, sentAt), captureSessionName(text, input.sessionID), ]); if (injectedText) { const injected = { id: `pal-promptctx-${Date.now()}`, sessionID: input.sessionID, messageID: input.messageID ?? `pal-msg-${Date.now()}`, type: "text" as const, text: injectedText, synthetic: true, }; output.parts = [injected, ...(output.parts ?? [])]; } }, "tool.execute.before": async ( _input: { tool: string; sessionID: string; callID: string }, output: { args: Record | string } ) => { const toolName = _input.tool; if (toolName === "shell" || toolName === "bash") guardShellCall(output); if (toolName === "write" || toolName === "edit" || toolName === "patch") { guardFileWrite(output.args as Record); } const call = ledgeredOpencodeCall(toolName, _input.callID, output.args); if (call) snapshotCall(call); }, "permission.ask": async (input: { id: string; type: string; sessionID: string }) => { rememberAskedTool(input); logAttention({ hook_event_name: "PermissionRequest", session_id: input.sessionID, tool_name: input.type, }); }, "tool.execute.after": async ( input: { tool: string; sessionID: string; callID: string; args: unknown }, output: { title: string; output: string; metadata: unknown } ) => { logToolCall({ tool_name: input.tool, tool_input: input.args, session_id: input.sessionID, tool_response: output?.output, }); recordSlurpCheck( { tool_name: input.tool, tool_input: input.args, session_id: input.sessionID, tool_response: output?.output, exit_code: (output?.metadata as { exit?: unknown } | undefined)?.exit, }, directory ); attachProgressFromToolCall( { tool_name: input.tool, tool_input: input.args, session_id: input.sessionID, tool_response: output?.output, exit_code: (output?.metadata as { exit?: unknown } | undefined)?.exit, }, directory ); const call = ledgeredOpencodeCall(input.tool, input.callID, input.args); if (!call) return; const entry = commitApplied(call); if (entry) logDebug("opencode:ledger", `recorded ${entry.id} ${entry.target}`); }, "shell.env": async ( input: { cwd: string; sessionID?: string; callID?: string }, output: { env: Record } ) => { output.env.PAL_DIR = PAL_DIR; if (input.sessionID) output.env.PAL_OPENCODE_SESSION_ID = input.sessionID; }, }; }; export default PALPlugin;