import { randomUUID } from "node:crypto"; import { tool } from "@opencode-ai/plugin"; import { createDelegationContext } from "../lib/delegation-context.js"; import { createRuntimeHost, createRuntimeLocation } from "../lib/host-contract.js"; import { convertObjectShape } from "../lib/memory-tool-schema.js"; import { formatMemoryToolOutcome, isMemoryToolId, memoryToolId } from "../lib/memory-tools.js"; import { __testUtils, buildInjectionToastMessage, createCodememRuntime, } from "../lib/runtime.js"; const extractV1SessionID = (event) => { if (!event || typeof event !== "object") return null; const properties = event.properties; if (!properties || typeof properties !== "object") return null; if (typeof properties.sessionID === "string") return properties.sessionID; if (typeof properties.info?.sessionID === "string") return properties.info.sessionID; if (typeof properties.part?.sessionID === "string") return properties.part.sessionID; if ( ["session.created", "session.updated", "session.deleted"].includes(event.type) && typeof properties.info?.id === "string" ) { return properties.info.id; } return null; }; const extractV1HookSessionID = (input) => { if (!input || typeof input !== "object") return null; return input.sessionID || input.sessionId || input.session?.id || input.session?.sessionID || input.properties?.sessionID || null; }; const translateV1Event = (event) => ({ type: event?.type || "unknown", sessionID: extractV1SessionID(event), messageInfo: event?.properties?.info || null, part: event?.properties?.part || null, usage: event?.properties?.usage || event?.usage || null, raw: event, }); const translateV1PromptInput = (input) => ({ sessionID: input.sessionID, }); const translateV1ToolResult = (input, output) => ({ input: { sessionID: input.sessionID, tool: input.tool, args: input.args, }, output: { output: output.output, }, }); const createV1Tool = (definition) => { const args = {}; for (const [name, argument] of Object.entries(definition.args)) { if (argument.type !== "number") { throw new Error(`Unsupported OpenCode 1 tool argument: ${name}:${argument.type}`); } const schema = tool.schema.number(); args[name] = argument.optional ? schema.optional() : schema; } return tool({ description: definition.description, args, execute: definition.execute, }); }; // OpenCode 1 tools return plain text and have no error flag, so a failed call // returns the same error payload text the MCP server would send. const createV1MemoryTool = (contract, execute) => tool({ description: contract.description, args: convertObjectShape(tool.schema, contract.input, contract.name), execute: async (args, context) => { const outcome = await execute(contract.name, args, { directory: context?.directory, sessionID: context?.sessionID, // OpenCode 1 supplies no call ID. One per execution lets the viewer and a // CLI retry of this same call share a retrieval-ledger identity. callID: randomUUID(), signal: context?.abort, }); const { text, note } = formatMemoryToolOutcome(outcome); return note ? `${text}\n${note}` : text; }, }); const createV1MemoryTools = (memoryTools) => { if (!memoryTools) return {}; return Object.fromEntries( memoryTools.contracts.map((contract) => [ memoryToolId(contract.name), createV1MemoryTool(contract, memoryTools.execute), ]), ); }; const isV1CodememMcpConfigured = async (client) => { const response = await client.config.get(); if (!response?.data) throw new Error("OpenCode config unavailable"); const server = response.data.mcp?.codemem; return Boolean(server) && server.enabled !== false; }; /** Native memory tools to register, or null when off or a codemem MCP server already serves them. */ const resolveV1MemoryTools = async (client, memoryTools) => { if (!memoryTools) return null; const register = await memoryTools.shouldRegister({ isCodememMcpConfigured: typeof client.config?.get === "function" ? () => isV1CodememMcpConfigured(client) : null, }); return register ? memoryTools : null; }; const dispatchV1Event = async (delegation, runtime, event) => { const translated = translateV1Event(event); if (event?.type === "session.deleted") { try { for (const childSessionID of delegation.boundChildren(translated.sessionID)) { await runtime.capturePendingPrompts({ sessionID: childSessionID }); } return await runtime.handleEvent(translated); } finally { delegation.observe(event); } } const part = event?.properties?.part; const terminalTaskUpdate = event?.type === "message.part.updated" && part?.type === "tool" && part.tool === "task" && ["completed", "error"].includes(part.state?.status); const boundChildSessionID = terminalTaskUpdate ? delegation.boundChild(part.sessionID, part.callID) : null; if (boundChildSessionID) { try { await runtime.capturePendingPrompts({ sessionID: boundChildSessionID }); return await runtime.handleEvent(translated); } finally { delegation.observe(event); } } delegation.observe(event); return runtime.handleEvent(translated); }; const createOpenCodeV1Adapter = async ({ project, client, directory, worktree }) => { const delegation = createDelegationContext({ requirePromptSnapshot: true, readSession: client.session?.get ? async (id, signal) => (await client.session.get({ path: { id }, signal })).data : null, readMessage: client.session?.message ? async (id, messageID, signal) => (await client.session.message({ path: { id, messageID }, signal })).data : null, }); const runtime = await createCodememRuntime({ location: createRuntimeLocation({ project, directory, worktree }), host: createRuntimeHost({ log: (entry) => client.app.log({ body: entry }), resolveCaptureContext: delegation.resolve, notify: client.tui?.showToast ? (notice) => client.tui.showToast({ body: notice }) : null, }), }); if (!runtime) return {}; const memoryTools = { ...Object.fromEntries( Object.entries(runtime.tools).map(([name, definition]) => [name, createV1Tool(definition)]), ), ...createV1MemoryTools(await resolveV1MemoryTools(client, runtime.memoryTools)), }; return { dispose: async () => { try { await runtime.dispose(); } finally { delegation.dispose(); } }, "chat.message": async (input, output) => { delegation.observePrompt(input, output); }, "experimental.session.compacting": (input) => runtime.handleCompacting({ sessionID: extractV1HookSessionID(input), }), "experimental.chat.messages.transform": (input, output) => runtime.transformMessages( translateV1PromptInput(input), output, ), "experimental.chat.system.transform": (input, output) => runtime.transformSystem( translateV1PromptInput(input), output, ), event: ({ event }) => dispatchV1Event(delegation, runtime, event), "tool.execute.after": (input, output) => { // Native memory tool output is retrieved memory; capturing it would distill it into new // memories. With the flag off, MCP-provided codemem tools keep their existing capture path. if (runtime.memoryTools && isMemoryToolId(input?.tool)) return; const translated = translateV1ToolResult(input, output); return runtime.handleToolResult(translated.input, translated.output); }, tool: memoryTools, }; }; export const CodememPlugin = createOpenCodeV1Adapter; export default CodememPlugin; /** * @deprecated Use CodememPlugin. * Keep this reference-identical: OpenCode deduplicates plugin exports by identity. */ export const OpencodeMemPlugin = CodememPlugin; export { __testUtils, buildInjectionToastMessage }; export const __v1AdapterTestUtils = { createV1MemoryTools, createV1Tool, dispatchV1Event, extractV1HookSessionID, extractV1SessionID, translateV1Event, translateV1ToolResult, };