From 9584584765699b88580d94c65807ff95975d836d Mon Sep 17 00:00:00 2001 From: famewolf Date: Sun, 27 Sep 2026 11:30:12 -0400 Subject: [PATCH 1/3] feat: add OpenCode v2 plugin API entry (src/index.v2.ts) --- README.md | 5 ++ src/index.v2.ts | 125 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 130 insertions(+) create mode 100644 src/index.v2.ts diff --git a/README.md b/README.md index 61c9e31..e17db0e 100644 --- a/README.md +++ b/README.md @@ -209,3 +209,8 @@ They can be installed side by side. When both are present, the token optimizer's ## License MIT + +## OpenCode 2.x + +- `src/index.v2.ts` — v2 plugin API entry (`{ id, setup }`): registers `track_task` / `check_duplicate` / `validate_task_scope` via `ctx.tool.transform` and pre-computes guidance into the context (`ctx.session.hook('context')`). +- Compiles to `dist/index.v2.js` (no `package.json` change; `tsconfig` already includes `src/**`). diff --git a/src/index.v2.ts b/src/index.v2.ts new file mode 100644 index 0000000..791fd92 --- /dev/null +++ b/src/index.v2.ts @@ -0,0 +1,125 @@ +// opencode-token-optimizer v2 — port of the v1 plugin (src/index.ts) to the OpenCode 2.x plugin API. +// Default entry stays src/index.ts (v1); this entry builds to dist/index.v2.js. +// Verified on OpenCode 2.0.16. On pre-2.0 hosts the guards skip registration (no crash). + +const taskRegistry = new Map(); +const STOP_WORDS = new Set(["the", "a", "an", "in", "to", "for", "of", "and", "or", "is", "are"]); + +function getSignificantWords(text: string): string[] { + return text.toLowerCase().split(/[\s,.;:!?()]+/).filter((w) => w.length > 0 && !STOP_WORDS.has(w)); +} + +function calculateOverlap(qw: string[], dw: string[]): number { + if (qw.length === 0) return 0; + const common = qw.filter((w) => dw.includes(w)).length; + return common / qw.length; +} + +const CONCERN_DELIMITER = new RegExp("(?:\\n\\n|\\n(?=[A-Z][a-z]+)|(?:^|(?<=\\.))\\s+(?=[A-Z][a-z]+\\s))", "g"); +const FILE_PATH_PATTERN = /(?:[\w-]+\.[\w-]+(?:\/[\w-]+)*|[\/][\w\-./]+)/g; + +function summarizeConcern(text: string): string { + const paths = text.match(FILE_PATH_PATTERN); + if (paths && paths.length) return paths.join(", "); + const funcs = text.match(/\b[a-zA-Z_]\w+(?=\s*\()/g); + if (funcs && funcs.length) return funcs.slice(0, 3).join(", "); + const cleaned = text.replace(/[,;.].*$/, "").trim(); + return cleaned.length > 60 ? cleaned.substring(0, 57) + "..." : cleaned; +} + +function extractConcerns(prompt: string): string[] { + const segs = prompt.split(CONCERN_DELIMITER).map((s) => s.trim()).filter((s) => s.length > 0); + if (segs.length <= 1) return []; + return segs.map(summarizeConcern); +} + +function trackTask(args: { taskId: string; description: string }): { duplicate: boolean; existingTask?: string } { + if (taskRegistry.has(args.taskId)) + return { duplicate: true, existingTask: taskRegistry.get(args.taskId)!.description }; + taskRegistry.set(args.taskId, { description: args.description }); + return { duplicate: false }; +} + +function checkDuplicate(args: { query: string }): { isDuplicate: boolean; matchedTask?: string } { + const qw = getSignificantWords(args.query); + if (qw.length === 0) return { isDuplicate: false }; + for (const [, e] of taskRegistry) { + const dw = getSignificantWords(e.description); + if (dw.length === 0) continue; + if (calculateOverlap(qw, dw) > 0.5) return { isDuplicate: true, matchedTask: e.description }; + } + return { isDuplicate: false }; +} + +function validateTaskScope(args: { + prompt?: string; + maxConcerns?: number; +}): { valid: boolean; concerns: string[]; suggestion: string } { + try { + const { prompt, maxConcerns = 1 } = args; + if (!prompt || !prompt.trim()) return { valid: true, concerns: [], suggestion: "" }; + const concerns = extractConcerns(prompt); + if (concerns.length > maxConcerns) + return { + valid: false, + concerns, + suggestion: `Split into ${concerns.length} separate tasks. Each task should focus on one concern.`, + }; + return { valid: true, concerns: [], suggestion: "" }; + } catch (e) { + console.warn("[token-optimizer-v2] validateTaskScope failed:", e); + return { valid: true, concerns: [], suggestion: "" }; + } +} + +const PRE_COMPUTE_GUIDANCE = ` +## Pre-computation guidance +Before calling tools, verify: +1. Have you already read this file in this session? (check conversation) +2. Is this file likely to exist? (check known paths from prior tool results) +3. Can you combine this with another call? (batch independent reads) +If you already have the info, use it directly instead of re-reading.`; + +export const TokenOptimizerV2Plugin = { + id: "token-optimizer-v2", + setup: async (ctx: any) => { + if (ctx?.tool && typeof ctx.tool.transform === "function") { + ctx.tool.transform((editor: any) => { + editor.add({ + name: "track_task", + description: "Register a task to prevent duplicate delegation", + input: { + taskId: { type: "string", description: "Unique identifier for this task" }, + description: { type: "string", description: "What this task will do" }, + }, + execute: async (a: any) => JSON.stringify(trackTask(a)), + }); + editor.add({ + name: "check_duplicate", + description: "Check if work has already been delegated", + input: { + query: { type: "string", description: "Description of work about to do" }, + }, + execute: async (a: any) => JSON.stringify(checkDuplicate(a)), + }); + editor.add({ + name: "validate_task_scope", + description: + "Validate that a task prompt focuses on ONE concern (not multiple). Returns detected concerns so the orchestrator can split into separate tasks.", + input: { + prompt: { type: "string", description: "The task prompt to validate for single-concern focus" }, + maxConcerns: { type: "number", description: "Maximum number of concerns to allow (default: 1)", default: 1 }, + }, + execute: async (a: any) => JSON.stringify(validateTaskScope(a), null, 2), + }); + }); + } + if (ctx?.session && typeof ctx.session.hook === "function") { + ctx.session.hook("context", async (event: any) => { + if (event?.system && Array.isArray(event.system)) event.system.push(PRE_COMPUTE_GUIDANCE); + }); + } + }, +}; + +export default TokenOptimizerV2Plugin; From a5b337b11f40e21403ec843494077d7c9914b2ad Mon Sep 17 00:00:00 2001 From: famewolf Date: Tue, 29 Sep 2026 10:20:15 -0400 Subject: [PATCH 2/3] fix(v2): push a SystemPart, not a bare string, into event.system OpenCode v2 validates the context event's `system` array against LLM.SystemPart, which is { type: "text", text: string }. This pushed the PRE_COMPUTE_GUIDANCE template literal directly, which fails schema validation. Once such an entry lands at system[4] or later, every request from the session fails, so the failure looks like a dead session rather than a bad plugin. Refs anomalyco/opencode#51269 --- src/index.v2.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/index.v2.ts b/src/index.v2.ts index 791fd92..e07ecd4 100644 --- a/src/index.v2.ts +++ b/src/index.v2.ts @@ -116,7 +116,13 @@ export const TokenOptimizerV2Plugin = { } if (ctx?.session && typeof ctx.session.hook === "function") { ctx.session.hook("context", async (event: any) => { - if (event?.system && Array.isArray(event.system)) event.system.push(PRE_COMPUTE_GUIDANCE); + if (event?.system && Array.isArray(event.system)) { + // OpenCode v2 validates `system` against LLM.SystemPart, which is + // { type: "text", text: string }. Pushing a bare string fails schema + // validation; once it lands at system[4] or later the whole request + // fails, which breaks every turn from this session including subagents. + event.system.push({ type: "text", text: PRE_COMPUTE_GUIDANCE }); + } }); } }, From 101a062f36863dbe5122b3b65e7ab4eebaf44067 Mon Sep 17 00:00:00 2001 From: famewolf Date: Tue, 29 Sep 2026 10:22:53 -0400 Subject: [PATCH 3/3] test(v2): cover the SystemPart shape in the pre-compute guidance The v2 entry had no test coverage at all, which is how the bare-string push reached main. These four cases drive setup() with a mock context and assert that the "context" hook appends a SystemPart rather than a string, that the guidance text survives, that existing entries are left alone, and that an event without a system array is not mutated. Verified to fail against the pre-fix code (Expected "object", Received "string") and pass after it. --- src/__tests__/v2-system-part.test.ts | 59 ++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 src/__tests__/v2-system-part.test.ts diff --git a/src/__tests__/v2-system-part.test.ts b/src/__tests__/v2-system-part.test.ts new file mode 100644 index 0000000..de74743 --- /dev/null +++ b/src/__tests__/v2-system-part.test.ts @@ -0,0 +1,59 @@ +import { describe, expect, test } from "bun:test"; +import TokenOptimizerV2Plugin from "../index.v2.js"; + +/** + * Drive the v2 plugin's setup() and return the `system` array after its + * "context" hook has run. + */ +async function runContextHook(event: any): Promise { + const hooks: Array<(e: any) => Promise | void> = []; + const ctx = { + tool: { transform: (fn: any) => fn({ add: () => {} }) }, + session: { + hook: (name: string, cb: any) => { + if (name === "context") hooks.push(cb); + }, + }, + }; + await TokenOptimizerV2Plugin.setup(ctx); + expect(hooks).toHaveLength(1); + await hooks[0](event); + return event.system; +} + +describe("v2 pre-compute guidance", () => { + // Regression: anomalyco/opencode#51269. The context event's `system` array is + // validated against LLM.SystemPart, which is { type: "text", text: string }. + // Pushing a bare string fails schema validation, and once such an entry lands + // at system[4] or later the entire request fails, so the session looks alive + // but can never complete a turn. + test("appends a SystemPart, never a bare string", async () => { + const system = await runContextHook({ system: [] }); + expect(system).toHaveLength(1); + expect(typeof system[0]).toBe("object"); + expect(system[0]).not.toBeNull(); + expect(Array.isArray(system[0])).toBe(false); + expect(system[0].type).toBe("text"); + expect(typeof system[0].text).toBe("string"); + }); + + test("carries the guidance text, not an empty shell", async () => { + const system = await runContextHook({ system: [] }); + expect(system[0].text).toContain("Pre-computation guidance"); + }); + + test("appends without disturbing entries already in the array", async () => { + const existing = { type: "text", text: "a prior system part" }; + const system = await runContextHook({ system: [existing] }); + expect(system).toHaveLength(2); + expect(system[0]).toBe(existing); + expect(system[1].type).toBe("text"); + expect(typeof system[1].text).toBe("string"); + }); + + test("leaves an event that carries no system array alone", async () => { + const event: any = {}; + await runContextHook(event); + expect(event.system).toBeUndefined(); + }); +});