A skill to stop your coding agent from burying the answer. ADHD-friendly output.
opencode: migrate plugin to the V2 plugin API
opencode-agent582ade6655e5
diff --git a/.opencode/plugins/i-have-adhd.mjs b/.opencode/plugins/i-have-adhd.mjsindex 310b263..b409e58 100644--- a/.opencode/plugins/i-have-adhd.mjs+++ b/.opencode/plugins/i-have-adhd.mjs@@ -1,19 +1,31 @@-// i-have-adhd — OpenCode plugin.+// i-have-adhd — OpenCode V2 plugin.//// Mirrors the Claude Code / Codex behaviour for OpenCode: the skill in// `skills/i-have-adhd/SKILL.md` is the single source of truth for the ruleset.//-// • On demand — registers the skills directory and a `/i-have-adhd`-// command so the ruleset applies for the rest of the session.-// • Always-on — when the opt-in flag file exists, the full ruleset is+// • On demand → registers the skill plus a `/i-have-adhd` command so the+// ruleset applies for the rest of the session.+// • Always-on → when the opt-in flag file exists, the full ruleset is// appended to the system prompt every turn (the OpenCode// equivalent of the SessionStart hook in hooks/always-on.sh).//+// V2 migration notes:+// • The default export must be a definition object with an `id` and an+// `effect`/`setup` function. The V1 shape, a bare+// `export default async () => ({...})`, is rejected at load time with+// "Plugin must export a default definition with an id and an effect or+// setup function".+// • The V1 `config` mutation hook is gone. Skills and commands register+// through `ctx.skill.transform` and `ctx.command.transform`.+// • `experimental.chat.system.transform` is gone. System-prompt edits go+// through `ctx.session.hook("context", ...)`.+//// Opt in to always-on: touch ~/.config/opencode/.i-have-adhd-always// Opt back out: rm ~/.config/opencode/.i-have-adhd-always//-// Install — add to opencode.json:-// { "plugin": ["./.opencode/plugins/i-have-adhd.mjs"] }+// Install — add to opencode.json(c). V2 requires a directory, and the field+// is plural:+// { "plugins": ["/absolute/path/to/i-have-adhd"] }import fs from 'fs';import os from 'os';@@ -25,13 +37,18 @@ const skillsDir = path.resolve(__dirname, '../../skills');const skillPath = path.join(skillsDir, 'i-have-adhd', 'SKILL.md');const commandPath = path.join(__dirname, '..', 'command', 'i-have-adhd.md');-// JSON is valid YAML frontmatter; share native command metadata without a YAML dependency.-async function commandDefinition() {- const raw = await fs.promises.readFile(commandPath, 'utf8');- const match = raw.match(/^---[^\S\r\n]*\r?\n([\s\S]*?)\r?\n---[^\S\r\n]*(?:\r?\n|$)([\s\S]*)$/);- if (!match) throw new Error('Missing command frontmatter');- return { ...JSON.parse(match[1]), template: match[2].trim() };-}+const SKILL_ID = 'i-have-adhd';+const FALLBACK_DESCRIPTION =+ 'Shape output for a reader with ADHD: lead with the next action, number ' ++ 'multi-step work, restate state across turns, suppress tangents, give ' ++ 'specific time estimates, make wins visible.';++const FALLBACK_PROMPT =+ 'Use the `i-have-adhd` skill and apply its ruleset to every response for the ' ++ 'rest of this session: lead with the next action, number multi-step work, ' ++ 'restate state across turns, suppress tangents, give concrete time estimates, ' ++ 'and make wins visible. These rules persist until I say "stop adhd mode" or ' ++ '"normal mode".';// Always-on opt-in flag, mirroring Claude Code's ~/.claude/.i-have-adhd-always// but under OpenCode's config dir so the two tools stay independent.@@ -41,6 +58,14 @@ const flagPath = path.join('.i-have-adhd-always',);+// JSON is valid YAML frontmatter; share native command metadata without a YAML dependency.+async function commandDefinition() {+ const raw = await fs.promises.readFile(commandPath, 'utf8');+ const match = raw.match(/^---[^\S\r\n]*\r?\n([\s\S]*?)\r?\n---[^\S\r\n]*(?:\r?\n|$)([\s\S]*)$/);+ if (!match) throw new Error('Missing command frontmatter');+ return { description: JSON.parse(match[1]).description, template: match[2].trim() };+}+// Read SKILL.md and strip a leading YAML frontmatter block (--- ... ---).// Regex and trailing-newline trim match hooks/always-on.mjs so always-on// injections behave identically across harnesses (see tests/test_always_on_hooks.py).@@ -51,49 +76,78 @@ function rulesetBody() {.replace(/(?:\r?\n)+$/, '');}-export default async () => {- return {- // Make the skill discoverable (so the `skill` tool and the /i-have-adhd- // command can load it).- config: async (config) => {- config.skills = config.skills || {};- config.skills.paths = config.skills.paths || [];- if (!config.skills.paths.includes(skillsDir)) config.skills.paths.push(skillsDir);+export default {+ id: SKILL_ID,- // Global installs need a command entry; preserve native or user-defined commands.- try {- config.command = config.command || {};- if (!config.command['i-have-adhd']) {- config.command['i-have-adhd'] = await commandDefinition();- }- } catch (e) {- // Missing or malformed command files must not break skill discovery.- }- },+ async setup(ctx) {+ // Make the skill discoverable, so the `skill` tool and the /i-have-adhd+ // command can both load it.+ try {+ const content = rulesetBody();+ await ctx.skill.transform((editor) => {+ if (editor.get(SKILL_ID)) return;+ editor.add({+ id: SKILL_ID,+ name: SKILL_ID,+ description: FALLBACK_DESCRIPTION,+ path: skillPath,+ content,+ });+ });+ } catch (e) {+ // Missing or malformed SKILL.md must not break command registration.+ }++ // Register /i-have-adhd. A global install loads the plugin from a path with+ // no project-scope `.opencode/command/` directory, so the plugin has to+ // supply the command itself (see #140).+ try {+ const command = await commandDefinition();+ await ctx.command.transform((editor) => {+ editor.add({+ name: SKILL_ID,+ description: command.description || FALLBACK_DESCRIPTION,+ execute: async ({ sessionID, prompt, delivery }) => {+ await ctx.session.prompt({+ ...prompt,+ sessionID,+ text: prompt.text ? `${command.template}\n\n${prompt.text}` : command.template,+ delivery,+ });+ },+ });+ });+ } catch (e) {+ // Missing or malformed command files must not break skill discovery.+ }// Always-on: append the ruleset to the system prompt every turn while the// flag file exists. "stop adhd mode" turns it off for the session (the// model honours the skill's own Persistence rules); deleting the flag// turns always-on off for good.- 'experimental.chat.system.transform': async (_input, output) => {- let on = false;- try { on = fs.existsSync(flagPath); } catch (e) {}- if (!on) return;+ try {+ await ctx.session.hook('context', (event) => {+ let on = false;+ try {+ on = fs.existsSync(flagPath);+ } catch (e) {}+ if (!on) return;- let body;- try { body = rulesetBody(); } catch (e) { return; }-- const header =- 'ADHD MODE ACTIVE (always-on). The ruleset below applies to every ' +- 'response. "stop adhd mode" or "normal mode" turns it off for this ' +- 'session; delete ' + flagPath + ' to turn always-on off for good.';- const injected = header + '\n\n' + body;+ let body;+ try {+ body = rulesetBody();+ } catch (e) {+ return;+ }- if (output.system.length > 0) {- output.system[output.system.length - 1] += '\n\n' + injected;- } else {- output.system.push(injected);- }- },- };+ const header =+ 'ADHD MODE ACTIVE (always-on). The ruleset below applies to every ' ++ 'response. "stop adhd mode" or "normal mode" turns it off for this ' ++ 'session; delete ' + flagPath + ' to turn always-on off for good.';+ event.system.push({ type: 'text', text: header + '\n\n' + body });+ });+ } catch (e) {+ // Always-on injection is optional; never break plugin load.+ }+ },};diff --git a/INSTALL.md b/INSTALL.mdindex f39b274..87e37eb 100644--- a/INSTALL.md+++ b/INSTALL.md@@ -508,62 +508,99 @@ Use slash command `/skill:i-have-adhd` to invoke the skill explicitly.<details><summary><strong>OpenCode</strong></summary>-OpenCode loads this repository as a server plugin: `.opencode/plugins/i-have-adhd.mjs` registers the `skills/` entry point and the `/i-have-adhd` command, and injects the ruleset when always-on is enabled. OpenCode also reads `skills/` natively, so the skill still works even without the plugin — the plugin adds the `/i-have-adhd` command and the always-on flag.+# OpenCode-### Install+OpenCode reads `skills/i-have-adhd/SKILL.md` natively, so the ruleset is available+to the `skill` tool with no plugin at all. The plugin adds two things on top: the+`/i-have-adhd` slash command for a global install, and the always-on flag.++## Install++### Skill only (no plugin)-Clone the repo and point OpenCode at the plugin. An absolute path shares one checkout across every project:+Copy the skill into your global skills directory. OpenCode discovers+`~/.config/opencode/skills/` and every project already gets the ruleset through the+`skill` tool. Ask for it in plain words ("use the i-have-adhd skill").```bash-git clone https://github.com/ayghri/i-have-adhd ~/.config/opencode/vendor/i-have-adhd+mkdir -p ~/.config/opencode/skills/i-have-adhd+cp skills/i-have-adhd/SKILL.md ~/.config/opencode/skills/i-have-adhd/SKILL.md```-Add to your `opencode.json` (global: `~/.config/opencode/opencode.json`):+### Skill and `/i-have-adhd` command (no plugin)-```json-{ "plugin": ["/absolute/path/to/i-have-adhd/.opencode/plugins/i-have-adhd.mjs"] }+Also copy the command file. A global install has no project-scope+`.opencode/commands/` directory, so `/i-have-adhd` is otherwise missing from the+`/` menu (see #140).++```bash+mkdir -p ~/.config/opencode/commands+cp .opencode/command/i-have-adhd.md ~/.config/opencode/commands/i-have-adhd.md```-Or run OpenCode from the checkout — it ships a root `opencode.json` with the plugin already wired up.+This is the recommended global install: two files, no plugin, no build step.-Start a new session and turn on ADHD-friendly output for the session:+### Plugin (adds always-on)-```text-/i-have-adhd+The plugin registers the skill and the command itself and adds the always-on+flag. OpenCode V2 loads a plugin that sits in a discovered `.opencode/plugins/`+directory, so expose the vendored checkout with a one-line loader:++```bash+git clone https://github.com/ayghri/i-have-adhd ~/.config/opencode/vendor/i-have-adhd+mkdir -p ~/.config/opencode/plugins+cat > ~/.config/opencode/plugins/i-have-adhd.js <<'EOF'+export { default } from "file://$HOME/.config/opencode/vendor/i-have-adhd/.opencode/plugins/i-have-adhd.mjs";+EOF```-Rules stay on until `stop adhd mode` or `normal mode`.+The loader re-exports the vendored module so its `__dirname` — and therefore its+`../../skills` and `../command/i-have-adhd.md` lookups — stay inside the checkout.+Replace `file://$HOME/...` with an absolute `file:///` URL; a loader is used+because OpenCode 2.0.18 rejects file paths in `plugins`+(`configured plugin path must be a directory`) and ignores configured directory+paths.-### Verify+To run OpenCode from a checkout instead, use the root `opencode.json`, which wires+the plugin for that directory.++## VerifyStart OpenCode, type `/`, and confirm `i-have-adhd` appears in the command list.-### Update+## Update```bashgit -C ~/.config/opencode/vendor/i-have-adhd pull```-### Uninstall+If you used the copy-based install, re-copy `SKILL.md` and+`.opencode/command/i-have-adhd.md` after pulling.-Remove the `plugin` entry from `opencode.json`.+## Uninstall-### Always-on (optional)+Remove `~/.config/opencode/plugins/i-have-adhd.js`, and whichever of+`~/.config/opencode/skills/i-have-adhd/` and+`~/.config/opencode/commands/i-have-adhd.md` you created.++## Always-on (optional)++Requires the plugin.```bashtouch ~/.config/opencode/.i-have-adhd-always```-While the flag exists, the plugin appends the full ruleset to the system prompt every turn — the OpenCode equivalent of the Claude Code `SessionStart` hook. `stop adhd mode` or `normal mode` disables it for the current session; delete the flag to turn always-on off for good:+While the flag exists, the plugin appends the full ruleset to the system prompt+every turn — the OpenCode equivalent of the Claude Code `SessionStart` hook.+`stop adhd mode` or `normal mode` disables it for the current session; delete the+flag to turn always-on off for good:```bashrm ~/.config/opencode/.i-have-adhd-always```-</details>--<details><summary><strong>Pi</strong></summary>Pi discovers this repository as a native package: `extensions/` provides the session-persistent mode and `skills/` keeps the Agent Skills entry point available.diff --git a/opencode.json b/opencode.jsonindex cf7824a..da310cf 100644--- a/opencode.json+++ b/opencode.json@@ -1,4 +1,4 @@{"$schema": "https://opencode.ai/config.json",- "plugin": ["./.opencode/plugins/i-have-adhd.mjs"]+ "plugins": ["."]}diff --git a/tests/opencode_plugin_driver.mjs b/tests/opencode_plugin_driver.mjsindex 70421d1..fcc09c6 100644--- a/tests/opencode_plugin_driver.mjs+++ b/tests/opencode_plugin_driver.mjs@@ -1,27 +1,77 @@-// Test driver for the OpenCode plugin. Imports the plugin at argv[2] and runs-// one of its hooks depending on argv[3]:+// Test driver for the OpenCode plugin. Imports the plugin at argv[2], calls its+// V2 `setup` with a recording context, and runs one of the registered handlers+// depending on argv[3]://-// (default) runs `experimental.chat.system.transform` against an empty-// system prompt and prints the resulting system text so tests-// can assert on the injected banner. Nothing is printed when the-// hook injects nothing (always-on flag absent).-// config runs the `config` hook twice, seeded by optional JSON at argv[4],-// and prints the resulting config to check registration, overrides,-// and idempotency without a running OpenCode server.+// (default) fires the `context` session hook against an empty system prompt+// and prints the resulting system text so tests can assert on the+// injected banner. Nothing is printed when the hook injects+// nothing (always-on flag absent).+// skill prints the registered skills as JSON.+// command prints the registered commands as JSON, with `template` holding+// the prompt the command would submit.+//+// V2 note: the plugin default-exports a definition object, so the driver awaits+// `setup(ctx)` instead of calling a bare function.import { pathToFileURL } from 'node:url';const pluginPath = process.argv[2];const mode = process.argv[3];-const { default: init } = await import(pathToFileURL(pluginPath).href);-const hooks = await init();+const { default: definition } = await import(pathToFileURL(pluginPath).href);++const skills = new Map();+const commands = new Map();+const hooks = new Map();+const prompts = [];++const editorFor = (store) => ({+ list: () => [...store.values()],+ get: (id) => store.get(id),+ add: (entry) => store.set(entry.id ?? entry.name, entry),+});++const ctx = {+ skill: {+ transform: async (cb) => {+ cb(editorFor(skills));+ return { dispose: async () => {} };+ },+ },+ command: {+ transform: async (cb) => {+ cb(editorFor(commands));+ return { dispose: async () => {} };+ },+ },+ session: {+ hook: async (name, handler) => {+ hooks.set(name, handler);+ return { dispose: async () => {} };+ },+ prompt: async (input) => {+ prompts.push(input);+ },+ },+};++await definition.setup(ctx);-if (mode === 'config') {- const config = JSON.parse(process.argv[4] || "{}");- await hooks.config(config);- await hooks.config(config);- process.stdout.write(JSON.stringify(config));+if (mode === 'skill') {+ process.stdout.write(JSON.stringify([...skills.values()]));+} else if (mode === 'command') {+ const out = [...commands.values()].map((command) => ({+ name: command.name,+ description: command.description,+ }));+ const entry = [...commands.values()][0];+ if (entry) {+ await entry.execute({ sessionID: "ses_test", prompt: { text: "" }, delivery: "steer" });+ out[0].template = prompts[prompts.length - 1]?.text;+ }+ process.stdout.write(JSON.stringify(out));} else {- const output = { system: [] };- await hooks['experimental.chat.system.transform']({}, output);- process.stdout.write(output.system.join('\n---SEP---\n'));+ const handler = hooks.get('context');+ if (!handler) process.exit(0);+ const event = { system: [] };+ await handler(event);+ process.stdout.write(event.system.map((part) => part.text ?? String(part)).join('\n---SEP---\n'));}diff --git a/tests/test_opencode_plugin.py b/tests/test_opencode_plugin.pyindex 816ba47..272b6e9 100644--- a/tests/test_opencode_plugin.py+++ b/tests/test_opencode_plugin.py@@ -13,7 +13,10 @@ ROOT = Path(__file__).resolve().parents[1]@unittest.skipUnless(shutil.which("node"), "node is required for the OpenCode plugin")class OpenCodePluginTest(unittest.TestCase):"""Mirror tests/test_always_on_hooks.py for the OpenCode server plugin: the- always-on flag gates injection, and frontmatter stripping matches the hooks."""+ always-on flag gates injection, and frontmatter stripping matches the hooks.++ OpenCode V2 replaced the V1 `config` mutation hook with `ctx.skill.transform`+ and `ctx.command.transform`, so registration is asserted through those."""def setUp(self):self.temp_dir = tempfile.TemporaryDirectory()@@ -25,7 +28,7 @@ class OpenCodePluginTest(unittest.TestCase):self.config_dir = Path(self.temp_dir.name) / "config"(self.config_dir / "opencode").mkdir(parents=True)- def run_plugin(self, mode=None, config=None):+ def run_plugin(self, mode=None):env = os.environ.copy()env["XDG_CONFIG_HOME"] = str(self.config_dir)args = [@@ -35,8 +38,6 @@ class OpenCodePluginTest(unittest.TestCase):]if mode:args.append(mode)- if config is not None:- args.append(json.dumps(config))return subprocess.run(args,check=False,@@ -71,64 +72,49 @@ class OpenCodePluginTest(unittest.TestCase):self.assertEqual(0, result.returncode, result.stderr)self.assertIn("Fixture body, fence never closed.", result.stdout)- def test_config_hook_registers_the_slash_command(self):+ def test_setup_registers_the_slash_command(self):# Regression test for #140: a global install (plugin loaded from a# path outside any checkout, no project-scope .opencode/command/# directory in play) must still get /i-have-adhd, because OpenCode's# skill-sourced commands are not surfaced in the TUI's `/` menu.- result = self.run_plugin(mode="config")+ result = self.run_plugin(mode="command")self.assertEqual(0, result.returncode, result.stderr)- config = json.loads(result.stdout)- command = config["command"]["i-have-adhd"]+ command = json.loads(result.stdout)[0]+ self.assertEqual("i-have-adhd", command["name"])self.assertIn("ADHD", command["description"])self.assertIn("stop adhd mode", command["template"])- def test_config_hook_still_registers_the_skills_path(self):- result = self.run_plugin(mode="config")- self.assertEqual(0, result.returncode, result.stderr)- config = json.loads(result.stdout)- self.assertIn(str(self.plugin_root / "skills"), config["skills"]["paths"])-- def test_config_preserves_existing_command(self):- custom = {"description": "User command", "template": "Keep this", "agent": "plan"}- result = self.run_plugin("config", {"command": {"i-have-adhd": custom}})+ def test_setup_registers_the_skill(self):+ result = self.run_plugin(mode="skill")self.assertEqual(0, result.returncode, result.stderr)- self.assertEqual(custom, json.loads(result.stdout)["command"]["i-have-adhd"])-- def test_repeated_config_does_not_duplicate_skill_paths(self):- result = self.run_plugin("config")- self.assertEqual(0, result.returncode, result.stderr)- self.assertEqual([str(self.plugin_root / "skills")], json.loads(result.stdout)["skills"]["paths"])-- def test_command_preserves_metadata_and_trims_template(self):- metadata = {"description": 'ADHD: "focus"\nnext line', "agent": "plan",- "model": "fixture/model", "subtask": True}- command = self.plugin_root / ".opencode/command/i-have-adhd.md"- command.write_bytes(("--- \r\n" + json.dumps(metadata) +- "\r\n--- \t\r\n\r\nUse the skill.\r\n\r\n").encode())- result = self.run_plugin("config")- self.assertEqual(0, result.returncode, result.stderr)- self.assertEqual({**metadata, "template": "Use the skill."},- json.loads(result.stdout)["command"]["i-have-adhd"])+ skill = json.loads(result.stdout)[0]+ self.assertEqual("i-have-adhd", skill["id"])+ self.assertEqual(+ str(self.plugin_root / "skills" / "i-have-adhd" / "SKILL.md"), skill["path"]+ )+ self.assertIn("ADHD", skill["description"])+ self.assertNotIn("---", skill["content"])- def test_missing_command_keeps_skill_discovery(self):+ def test_missing_command_keeps_skill_registration(self):(self.plugin_root / ".opencode/command/i-have-adhd.md").unlink()- result = self.run_plugin("config")+ result = self.run_plugin(mode="command")self.assertEqual(0, result.returncode, result.stderr)- config = json.loads(result.stdout)- self.assertNotIn("i-have-adhd", config["command"])- self.assertEqual([str(self.plugin_root / "skills")], config["skills"]["paths"])+ self.assertEqual([], json.loads(result.stdout))+ result = self.run_plugin(mode="skill")+ self.assertEqual(0, result.returncode, result.stderr)+ self.assertEqual("i-have-adhd", json.loads(result.stdout)[0]["id"])- def test_malformed_command_does_not_leak_frontmatter_into_prompt(self):+ def test_malformed_command_keeps_skill_registration(self):command = self.plugin_root / ".opencode/command/i-have-adhd.md"for text in ["---\n{broken}\n---\nBody", '---\n{"description":"unclosed"}\nBody']:with self.subTest(text=text):command.write_text(text)- result = self.run_plugin("config")+ result = self.run_plugin(mode="command")+ self.assertEqual(0, result.returncode, result.stderr)+ self.assertEqual([], json.loads(result.stdout))+ result = self.run_plugin(mode="skill")self.assertEqual(0, result.returncode, result.stderr)- config = json.loads(result.stdout)- self.assertNotIn("i-have-adhd", config["command"])- self.assertEqual([str(self.plugin_root / "skills")], config["skills"]["paths"])+ self.assertEqual("i-have-adhd", json.loads(result.stdout)[0]["id"])if __name__ == "__main__":