import type { Plugin } from "@opencode-ai/plugin" import { createHash } from "crypto" import { tmpdir } from "os" import path from "path" import { promises as fs } from "fs" const TMP_DIR = path.join(tmpdir(), "opencode-vision") // Map from content hash → global image sequence number, ensuring each unique // image gets a stable seq across the session. const imageRegistry = new Map() // Reverse map: seq → hash, used to clean imageRegistry when LRU evicts a dir. const reverseRegistry = new Map() let nextImageSeq = 1 // LRU eviction: when this many images are stored, oldest image* dir gets deleted // Default 200 images (~200MB cap); adjustable via VISION_MAX_IMAGES env var const MAX_IMAGES = Number(process.env["VISION_MAX_IMAGES"] || 200) const LRU_QUEUE: string[] = [] // image{N} dir paths in access order (deduplicated) // Shared prefix for all plugin-injected hint text parts. Used by both hint // generation and isPluginInjectedText() cleanup to stay in sync. const HINT_PREFIX = "[opencode-vision:" /** * Record access for LRU eviction. Deduplicates the queue so the same seqDir * is never counted twice — prevents queue bloat and accidental eviction of * in-use directories when the same image is referenced multiple times. */ function touchLRU(seqDir: string) { // Step 1: remove old occurrence to "move to back" (O(n) but n ≤ MAX_IMAGES) const idx = LRU_QUEUE.indexOf(seqDir) if (idx !== -1) LRU_QUEUE.splice(idx, 1) LRU_QUEUE.push(seqDir) // Step 2: evict oldest entries when over the cap while (LRU_QUEUE.length > MAX_IMAGES) { const oldest = LRU_QUEUE.shift() if (!oldest) break // Extract seq number from dir name (e.g. "image42" → 42) to clean registries const seqMatch = oldest.match(/image(\d+)$/) if (seqMatch) { const evictedSeq = Number(seqMatch[1]) const evictedHash = reverseRegistry.get(evictedSeq) if (evictedHash) { imageRegistry.delete(evictedHash) reverseRegistry.delete(evictedSeq) } } // Asynchronously delete the oldest image dir fs.rm(oldest, { recursive: true, force: true }).catch(() => {}) } } // Identifies text parts that THIS plugin injected into a user message during a // previous transform run. The transform hook re-runs for every message sent to // the LLM (including after a /model switch), so we must clear these stale // injections on every pass — otherwise native-vision models would see the // "[vision: imageN/hash.ext]" placeholder text and incorrectly call the vision // tool to "read" it, instead of viewing the original image part natively. // // Mirrored in tests/transform-cleanup.test.ts — keep in sync. function isPluginInjectedText(text: string): boolean { if (!text) return false // Primary check: all hints generated by this plugin share HINT_PREFIX. // Legacy patterns kept for backward compat with messages created before // the prefix was introduced. return ( text.startsWith(HINT_PREFIX) || /^\[Image #\d+ auto-saved to /.test(text) || /^\[Image #\d+ \w+\.\w+ auto-saved to /.test(text) || /^\[Images auto-saved to:/.test(text) || /^\[Images \(\d+\) auto-saved to:/.test(text) || /^\[vision: image\d+\/[\w-]+\.[\w]+]$/.test(text) ) } // ── Delegation mode ── // // VISION_MODE controls how non-vision models obtain image descriptions: // "api" (default, original) — the vision tool calls an external VLM // API (VISION_API_KEY + VISION_API_URL). This is the upstream // behaviour and is left untouched. // "subagent" — the plugin instructs the LLM to delegate image analysis to // the @image-reader subagent via the Task tool. No external API // key is required; the subagent runs on whatever vision-capable // model is configured in opencode (e.g. opencode-go/minimax-m3). // // Auto-fallback: when VISION_MODE is unset, the plugin uses "api" mode if // VISION_API_KEY is present, otherwise it falls back to "subagent" mode so // the plugin works out-of-the-box without any external credentials. // // VISION_SUBAGENT_NAME overrides the subagent identifier injected into the // system prompt and path hint (default: "image-reader"). const VISION_MODE_RAW = (process.env["VISION_MODE"] || "").toLowerCase() const VISION_SUBAGENT_NAME = process.env["VISION_SUBAGENT_NAME"] || "image-reader" const hasApiKey = !!process.env["VISION_API_KEY"] const VISION_MODE: "api" | "subagent" = VISION_MODE_RAW === "subagent" ? "subagent" : VISION_MODE_RAW === "api" ? "api" : hasApiKey ? "api" : "subagent" /** * Hook runs just before messages are sent to the model. For every user message * with attached images: * 1. Skips compaction messages (summary messages are already text) * 2. Cleans up any text parts this plugin injected in a previous transform * run (prevents hint/placeholder accumulation across model switches) * 3. Saves each image to a temp dir so the vision tool can read it * 4. Pushes a path-hint text part telling the LLM where the image was saved * * We deliberately do NOT replace the original file parts and do NOT decide * whether the current model is multimodal — OpenCode already handles both via * ProviderTransform.unsupportedParts (checks model.capabilities.input). For * native-vision models, the original image part reaches the LLM and it views * the image directly; for non-vision models, OpenCode replaces the image part * with an ERROR text and the LLM uses the hint to call the vision tool. This * plugin stays out of OpenCode's capability decision and only manages the * side-channel (temp file + hint), so the plugin's behavior stays consistent * with OpenCode's internal mechanism regardless of modelID. * * To steer native-vision LLMs away from the lossy vision tool (which returns * a textual description instead of the image itself), the plugin also * registers a tool.definition hook that overrides the vision tool's * description, recommending the built-in read tool as the primary path. * * Additionally, the system.transform hook injects a capability declaration * into the system prompt when the current model supports native image input. * This prevents path-dependency when switching from a non-vision model (which * used the vision tool) to a native-vision model — without this hint, the * new model would see historical vision tool calls and incorrectly mimic that * behavior instead of directly analyzing images. * * Images are assigned global sequence numbers in paste order: * 1st image → image1/xxx.png * 2nd image → image2/yyy.png * 3rd image → image3/zzz.png * * Deduplication uses MD5 of the full base64 (not just the first 1024 chars) to * avoid hash collisions for visually similar images. */ let currentModelSupportsImage = false const sessionImageSupport = new Map() function modelSupportsImage(sessionID?: string): boolean { return sessionID ? (sessionImageSupport.get(sessionID) ?? currentModelSupportsImage) : currentModelSupportsImage } function nativeVisionBlockArgs() { return { paths: [], __nativeVisionBlocked: true, } } export default (async () => { // Ensure the temp root dir exists at plugin startup await fs.mkdir(TMP_DIR, { recursive: true }).catch(() => {}) return { "tool.definition": async (input, output) => { if (input.toolID === "vision") { output.description = modelSupportsImage() ? [ "DISABLED for the current model: this model has native image input.", "Do NOT call this tool for user-attached images. Analyze the image directly from the message, or use the built-in `read` tool for local image files.", "This external VLM fallback exists only for text-only models that cannot parse image attachments.", ].join("\n") : [ "Reads one or more image files via an external VLM API and returns a textual description.", "Use ONLY for text-only models that cannot parse image attachments. Native-vision models should analyze user-attached images directly or use the built-in `read` tool for local image files.", ].join("\n") } // In subagent mode, the vision tool is typically absent (no VISION_API_KEY). // OpenCode silently ignores tool.definition calls for tools that don't // exist, so this hook is a no-op in that case — no extra guard needed. }, "tool.execute.before": async (input, output) => { if (input.tool === "vision" && modelSupportsImage(input.sessionID)) { output.args = nativeVisionBlockArgs() } }, "experimental.chat.system.transform": async (input, output) => { const model = input.model as unknown as { id?: string capabilities?: { input?: { image?: boolean } } modalities?: { input?: string[] } } // Check both formats: capabilities.input.image (boolean) AND // modalities.input includes "image" (string array). The opencode model // config exclusively uses the modalities format, while the capabilities // format may come from provider-level normalization. const hasImage = !!model?.capabilities?.input?.image || (Array.isArray(model?.modalities?.input) && model.modalities.input.includes("image")) currentModelSupportsImage = hasImage if (input.sessionID) sessionImageSupport.set(input.sessionID, hasImage) let instruction: string | undefined if (hasImage) { instruction = "You have native image input capabilities. You can directly view and analyze images attached to user messages. Do NOT call the `vision` tool to read images sent by the user — analyze them natively instead." } else if (VISION_MODE === "subagent") { instruction = `IMPORTANT: This model does NOT support image input. When a user attaches an image or screenshot, OpenCode will save it to a temp directory and inject a path hint like '[Image #N auto-saved to /tmp/opencode-vision/imageN/hash.png]'. You MUST delegate image analysis to the @${VISION_SUBAGENT_NAME} subagent via the Task tool (subagent_type="${VISION_SUBAGENT_NAME}", prompt="Read and describe the image at "). The @${VISION_SUBAGENT_NAME} subagent runs on a multimodal model (e.g. opencode-go/minimax-m3) that can read images. Never attempt to read images directly with the \`read\` tool — it will fail with 'model does not support image input'.` } if (instruction) { output.system.splice(0, output.system.length, [...output.system, instruction].join("\n")) } }, "experimental.chat.messages.transform": async (_input, output) => { for (const msg of output.messages) { if (msg.info.role !== "user") continue // P0-2: Skip compaction messages (they are already summarized text) // OpenCode's MessageInfo exposes a `summary` field for compacted msgs const info = msg.info as unknown as { role: string; summary?: boolean } if (info.summary) continue // Clean up any text parts this plugin injected in a previous transform // run. Covers both image hints AND [vision: imageN/hash.ext] placeholders // so re-processing a user message (e.g. after a /model switch) does // not leak stale injections into the prompt. for (let i = msg.parts.length - 1; i >= 0; i--) { const p = msg.parts[i] as unknown as { type?: string; text?: string } if (p.type === "text" && typeof p.text === "string" && isPluginInjectedText(p.text)) { msg.parts.splice(i, 1) } } if (modelSupportsImage()) continue const saved: { name: string; seq: number }[] = [] for (let i = 0; i < msg.parts.length; i++) { const part = msg.parts[i] if (part.type !== "file" || typeof part.mime !== "string" || !part.mime.startsWith("image/")) continue const colon = part.url.indexOf(";base64,") if (colon === -1) continue const base64 = part.url.slice(colon + ";base64,".length) if (!base64) continue // P1-1: MD5 over the FULL base64 (not just first 1024 chars) to avoid collisions // for visually similar images. 16 hex chars (64 bits) — birthday-paradox // collision threshold ~5 billion images, safe for any practical session. const hash = createHash("md5").update(base64).digest("hex").slice(0, 16) let seq = imageRegistry.get(hash) if (!seq) { seq = nextImageSeq++ imageRegistry.set(hash, seq) reverseRegistry.set(seq, hash) } const ext = part.mime.split("/")[1] || "png" const name = `${hash}.${ext}` const seqDir = path.join(TMP_DIR, `image${seq}`) const filePath = path.join(seqDir, name) // P1-3: write failures degrade to a skip (don't throw, don't break the turn) if (!(await Bun.file(filePath).exists())) { try { // H2 fix: ensure seqDir exists before writing — Bun.write may not // auto-create intermediate directories depending on version. await fs.mkdir(seqDir, { recursive: true }).catch(() => {}) await Bun.write(filePath, Buffer.from(base64, "base64")) } catch (err) { console.error(`[vision-helper] Failed to write ${filePath}:`, err) continue } } // P0-5: record access for LRU eviction touchLRU(seqDir) saved.push({ name, seq }) } if (saved.length === 0) continue // Build path hint(s). The hint records where the temp copy lives so // any model that needs it can find it. In "api" mode the hint is // neutral (the vision tool's own description handles routing); in // "subagent" mode the hint explicitly names the @image-reader // subagent so the LLM knows to delegate via the Task tool. // M4 fix: all hints start with HINT_PREFIX so isPluginInjectedText() // can detect them with a single startsWith() check. const hintSuffix = VISION_MODE === "subagent" ? ` — use @${VISION_SUBAGENT_NAME} subagent via Task tool to analyze it if you cannot view images natively]` : `]` const hints = saved.length === 1 ? `${HINT_PREFIX} Image #${saved[0].seq} ${saved[0].name} auto-saved to ${path.join(TMP_DIR, `image${saved[0].seq}`, saved[0].name)}${hintSuffix}` : `${HINT_PREFIX} Images (${saved.length}) auto-saved to:\n${saved.map((s) => ` ${path.join(TMP_DIR, `image${s.seq}`, s.name)}`).join("\n")}${hintSuffix}` msg.parts.push({ type: "text", text: hints, }) } }, } }) satisfies Plugin