Repository navigation
feat(opencode): serve both V1 and V2 plugin APIs #508
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
114 changes: 114 additions & 0 deletions
114
integrations/opencode/legacy/.opencode/plugins/token-optimizer.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,114 @@ | ||
| // GENERATED from integrations/opencode/.opencode/plugins/token-optimizer.js by | ||
| // scripts/generate-opencode-legacy-plugin.mjs -- edit that file, then run | ||
| // `npm run sync:hooks`. For OpenCode 1.3.3 and earlier only: it exports the | ||
| // V1 plugin function and nothing else, because those releases call every | ||
| // export as a plugin. Install this file OR the current one, never both. | ||
| import { spawnSync } from 'node:child_process'; | ||
| import { basename, join } from 'node:path'; | ||
|
|
||
| /** | ||
| * Runtime used to execute the generated hook entries. The hooks target Node, | ||
| * and OpenCode 1.x ran plugins inside a Node server, so process.execPath used | ||
| * to be node. OpenCode 2.x is a compiled binary: spawning it with a .mjs path | ||
| * makes the CLI treat the script as a project directory (ENOTDIR) instead of | ||
| * executing it, and enforcement silently no-ops. Keep process.execPath when it | ||
| * is Node and fall back to node on PATH otherwise. | ||
| */ | ||
| const HOOK_RUNTIME = /^node/i.test(basename(process.execPath)) | ||
| ? process.execPath | ||
| : 'node'; | ||
|
|
||
| const compactionGuidance = ` | ||
| ## Token Optimizer state | ||
|
|
||
| Preserve which large files and bulky outputs have already been processed. After | ||
| compaction, continue using token-optimizer smart_read for large or repeated | ||
| files, smart_glob/smart_grep for noisy searches, optimize_text for bulky output, | ||
| and get_optimization_report when savings are requested. | ||
| `; | ||
|
|
||
| /** | ||
| * Spawn one generated shared hook entry over the stdin/stdout JSON contract. | ||
| * Shared by both plugin APIs below so V1 and V2 hosts enforce identically. | ||
| */ | ||
| const createInvoke = (directory) => { | ||
| const hooks = join(directory, '.opencode', 'hooks', 'token-optimizer'); | ||
| return (entry, payload) => { | ||
| try { | ||
| const result = spawnSync( | ||
| HOOK_RUNTIME, | ||
| [join(hooks, `${entry}.mjs`)], | ||
| { | ||
| input: JSON.stringify(payload), | ||
| encoding: 'utf8', | ||
| // Preserve the live enforcement/capability contract for the generated | ||
| // child hook. Making this explicit also keeps test hosts and embedders | ||
| // from spawning with an implementation-defined environment snapshot. | ||
| env: { ...process.env }, | ||
| timeout: 5_000, | ||
| maxBuffer: 64 * 1024, | ||
| } | ||
| ); | ||
| return result.status === 0 && result.stdout.trim() | ||
| ? JSON.parse(result.stdout) | ||
| : null; | ||
| } catch { | ||
| return null; | ||
| } | ||
| }; | ||
| }; | ||
|
|
||
| /** | ||
| * OpenCode V1 entrypoint: the V1 hook-name map. OpenCode 2.x rejects this shape | ||
| * outright ("Plugin must export a default definition with an id and an effect | ||
| * or setup function"), so 2.x is served by a separate `setup` instead. | ||
| */ | ||
| export const TokenOptimizerPlugin = async ({ directory }) => { | ||
| const invoke = createInvoke(directory); | ||
| const pending = new Map(); | ||
| const keyFor = (input) => input.callID || `${input.sessionID}:${input.tool}`; | ||
| const payloadFor = (input, args) => ({ | ||
| session_id: input.sessionID || 'default', | ||
| cwd: directory, | ||
| tool_name: input.tool, | ||
| tool_input: args || {}, | ||
| }); | ||
|
|
||
| return { | ||
| 'experimental.chat.system.transform': async (_input, output) => { | ||
| const result = invoke('session-start', {}); | ||
| const policy = result?.hookSpecificOutput?.additionalContext; | ||
| if (policy) output.system.push(policy); | ||
| }, | ||
| 'tool.execute.before': async (input, output) => { | ||
| const shared = invoke('pre-tool', payloadFor(input, output.args)); | ||
| const hook = shared?.hookSpecificOutput; | ||
| if (hook?.permissionDecision === 'deny') { | ||
| throw new Error(hook.permissionDecisionReason); | ||
| } | ||
| pending.set(keyFor(input), { | ||
| context: hook?.additionalContext || '', | ||
| args: output.args, | ||
| }); | ||
| }, | ||
| 'tool.execute.after': async (input, output) => { | ||
| const parts = []; | ||
| const prior = pending.get(keyFor(input)); | ||
| pending.delete(keyFor(input)); | ||
| if (prior?.context) parts.push(prior.context); | ||
|
|
||
| if (/^(?:edit|write|apply_patch|replace)$/i.test(input.tool)) { | ||
| const result = invoke('post-tool', payloadFor(input, prior?.args)); | ||
| const context = result?.hookSpecificOutput?.additionalContext; | ||
| if (context) parts.push(context); | ||
| } | ||
| if (parts.length) { | ||
| output.output = | ||
| `${output.output || ''}\n\n[Token Optimizer graph]\n${parts.join('\n\n')}`.trim(); | ||
| } | ||
| }, | ||
| 'experimental.session.compacting': async (_input, output) => { | ||
| output.context.push(compactionGuidance); | ||
| }, | ||
| }; | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,52 @@ | ||
| #!/usr/bin/env node | ||
| /** | ||
| * Generates the OpenCode plugin for OpenCode 1.3.3 and earlier. | ||
| * | ||
| * Those releases call every export of a plugin file as a plugin function | ||
| * (packages/opencode/src/plugin/index.ts up to v1.3.3), and the current | ||
| * plugin's default export is the object OpenCode 2.x requires, so a release | ||
| * that old fails to load the whole file. No one module satisfies both loaders. | ||
| * The legacy build is the current plugin cut at its LEGACY CUT marker, so the | ||
| * two can never disagree about a hook. | ||
| */ | ||
|
|
||
| import { readFileSync } from 'node:fs'; | ||
| import { join, dirname } from 'node:path'; | ||
| import { fileURLToPath } from 'node:url'; | ||
| import { | ||
| contentMatches, | ||
| normalizeEol, | ||
| readIfExists, | ||
| writeIfChanged, | ||
| } from './lib/text.mjs'; | ||
|
|
||
| const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..'); | ||
| const SOURCE = 'integrations/opencode/.opencode/plugins/token-optimizer.js'; | ||
| const LEGACY = 'integrations/opencode/legacy/.opencode/plugins/token-optimizer.js'; | ||
| const check = process.argv.includes('--check'); | ||
|
|
||
| const text = normalizeEol(readFileSync(join(ROOT, SOURCE), 'utf8')); | ||
| const cut = text.indexOf('\n// LEGACY CUT.'); | ||
| if (cut < 0) { | ||
| console.error(`${SOURCE} has no LEGACY CUT marker`); | ||
| process.exit(1); | ||
| } | ||
| const contents = `// GENERATED from ${SOURCE} by | ||
| // scripts/generate-opencode-legacy-plugin.mjs -- edit that file, then run | ||
| // \`npm run sync:hooks\`. For OpenCode 1.3.3 and earlier only: it exports the | ||
| // V1 plugin function and nothing else, because those releases call every | ||
| // export as a plugin. Install this file OR the current one, never both. | ||
| ${text.slice(0, cut).trimEnd()} | ||
| `; | ||
|
|
||
| const destination = join(ROOT, LEGACY); | ||
| if (check) { | ||
| if (!contentMatches(readIfExists(destination), contents)) { | ||
| console.error(`DRIFT: ${LEGACY}\nRun: npm run sync:hooks`); | ||
| process.exit(1); | ||
| } | ||
| console.log('opencode legacy plugin in sync'); | ||
| } else { | ||
| writeIfChanged(destination, contents); | ||
| console.log(`generated ${LEGACY}`); | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.