Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .claude-plugin/plugin.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "agentsmd",
"version": "17.4.9",
"version": "17.5.0",
"description": "Portable agent rules, Project Direction, Delivery System profiles, owned workflow Skills, and deterministic version control.",
"author": {
"name": "lukaszmaj"
Expand Down
2 changes: 1 addition & 1 deletion .codex-plugin/plugin.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "agentsmd",
"version": "17.4.9",
"version": "17.5.0",
"description": "Portable agent rules, Project Direction, Delivery System profiles, owned workflow Skills, and deterministic version control.",
"author": {
"name": "lukaszmaj",
Expand Down
2 changes: 1 addition & 1 deletion .grok-plugin/plugin.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "agentsmd",
"version": "17.4.9",
"version": "17.5.0",
"description": "Portable agent rules, Project Direction, Delivery System profiles, owned workflow Skills, and deterministic version control.",
"author": {
"name": "lukaszmaj"
Expand Down
2 changes: 1 addition & 1 deletion .muse-plugin/plugin.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"schemaVersion": 1,
"name": "agentsmd",
"displayName": "AgentsMD",
"version": "17.4.9",
"version": "17.5.0",
"description": "Portable agent rules, Project Direction, Delivery System profiles, owned workflow Skills, and deterministic version control.",
"compat": {
"source": "native",
Expand Down
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,12 @@
All completed repository versions are recorded here. Release entries follow
SemVer and identify one user-consumable repository state.

## [17.5.0] - 2026-11-18

### Added

- OpenCode plugin supports the OpenCode 2.x plugin API and keeps 1.x working (#271)

## [17.4.9] - 2026-11-15

### Changed
Expand Down
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ Do not link the Skills into `~/.agents/skills` or `~/.claude/skills`; Codex and
Grok Build scan those directories too, so a harness that already has the plugin
would list every Skill twice as a duplicate. The second command links the
AgentsMD OpenCode plugin into the same directory's `plugins` folder. The plugin
targets OpenCode **1.18.32**. [OpenCode details](docs/opencode.md) covers its
works on OpenCode **1.18.32**, **1.19.6** and **2.3.2**. [OpenCode details](docs/opencode.md) covers its
status, update and uninstall commands.

**Muse Code 1.4.9:**
Expand Down Expand Up @@ -276,7 +276,7 @@ healthy and carries your private preferences.
| Codex | `SessionStart`, `UserPromptSubmit`, `SubagentStart` | The loader emits nothing on `PreToolUse`; it runs only the Elon gate | Plugin hook (`hooks/hooks.json`) | Explicit reading after a subagent's private compaction |
| Claude Code | `SessionStart`, `UserPromptSubmit`, `SubagentStart` | The loader emits nothing on `PreToolUse`; it runs only the Elon gate | Plugin hook (`hooks/hooks.json`), plus the `operations` pointer from `hooks/claude.json` at `SessionStart` | Explicit reading when the hook reports a problem; `UserPromptSubmit` and `SubagentStart` delivery was not separately exercised live |
| Grok Build | `PreToolUse`, on the first tool call of a session | `SessionStart`, `UserPromptSubmit`, `SubagentStart`: Grok discards their output | Owned global hook file from `bin/agentsmd-grok-hook` | Explicit reading for the first response, before the first tool call |
| OpenCode | Every session, appended to the system prompt | OpenCode has no such lifecycle events | Plugin `experimental.chat.system.transform`, which also appends the `operations` pointer; `tool.execute.before` runs the Elon gate | Explicit reading when the plugin reports a problem |
| OpenCode | Every session, appended to the system prompt | OpenCode has no such lifecycle events | Plugin `experimental.chat.system.transform` (1.x) or `session.hook("context")` (2.x), which also appends the `operations` pointer; `tool.execute.before` (1.x) or `tool.hook("execute.before")` (2.x) runs the Elon gate | Explicit reading when the plugin reports a problem |
| Muse | `SessionStart`, `UserPromptSubmit`, `SubagentStart` | `PreToolUse` runs only the Elon gate | Native plugin wrappers, plus the operations pointer at `SessionStart` | PostCompact re-delivery unproven; live tool-call blocking pending Live Verification |

`SessionStart` loads at startup, resume, clear, and compact on Codex and Claude
Expand All @@ -300,7 +300,7 @@ through the hook that already runs there:
| --- | --- |
| Claude Code, Codex | `UserPromptSubmit` from `hooks/hooks.json` |
| Muse | The `UserPromptSubmit` wrapper |
| OpenCode | `experimental.chat.system.transform`, as the last line of the loader context on every request |
| OpenCode | `experimental.chat.system.transform` (1.x) or `session.hook("context")` (2.x), as the last line of the loader context on every request |
| Grok Build | Not supported. Grok discards the output of an allowing `UserPromptSubmit` hook, and `PreToolUse` fires on every tool call, which would repeat the reminder many times per turn |

No hook checks the reply itself (#201).
Expand Down
2 changes: 1 addition & 1 deletion VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
17.4.9
17.5.0
28 changes: 22 additions & 6 deletions docs/opencode.md
Original file line number Diff line number Diff line change
Expand Up @@ -152,11 +152,26 @@ verdicts. Any loader failure leaves the system prompt unchanged and logs one
`agentsmd-project-direction:` line to stderr. Start a fresh OpenCode session
after install; a running session keeps its loaded plugins.

The plugin uses `experimental.chat.system.transform`, which is experimental in
OpenCode **1.18.32**, the version the bounded run adapter pins. The plugin
context exposes no harness version, so the pin is documented, not enforced at
runtime. Treat a different OpenCode version as unproved until the seam is
rechecked.
One module serves both OpenCode plugin APIs. Its default export is
`{id, server, setup}`: OpenCode 1.x calls `server`, and OpenCode 2.x calls
`setup` and ignores `server`. OpenCode 1.x also calls `setup`, with a context
that has no session or tool hooks; `setup` then registers nothing.

| Purpose | OpenCode 1.x | OpenCode 2.x |
| --- | --- | --- |
| Load the module | default `{id, server}`, `server(context)` returns hooks | default `{id, setup}`, `setup(context)` registers hooks |
| Working directory | `context.directory`, else `context.worktree` | `context.location.directory` |
| Append to the system prompt | `experimental.chat.system.transform`: push strings onto `output.system` | `context.session.hook("context", …)`: push `{type: "text", text}` onto `input.system` |
| Elon gate before a tool runs | `tool.execute.before`: read `input.tool` and `output.args`; throw to block | `context.tool.hook("execute.before", …)`: read `input.tool` and `input.input`; throw to block |

In 2.x a throw from `execute.before` fails the call with that message before the
tool runs, as in 1.x. The 2.x shell tool is named `shell`, which the loader
already treats as a shell. The 1.x system transform is experimental.

The plugin was proved on OpenCode **1.18.32**, which the bounded run adapter
pins, **1.19.6** and **2.3.2**. The plugin context exposes no harness version, so
this list is documented, not enforced at runtime. Treat another OpenCode version
as unproved until the seam is rechecked.

The entry reports the Skill links' ownership states: `missing`, `owned-link`,
`divergent-link`, `regular-file`, `other-path` and `broken-link`. Install
Expand Down Expand Up @@ -219,7 +234,8 @@ install, repeat install, preserved user entries, uninstall and rejected shared
directories, explicit CLI arguments, stale-head refusal, malformed events,
errors and timeout. It uses a
fake CLI and spends no model quota. `python3 -m unittest tests.test_opencode_plugin -v`
runs the plugin module under Node against a fixture repository and asserts that
runs the plugin module under Node through both the 1.x `server` and the 2.x
`setup` hooks against a fixture repository and asserts that
the appended system entry equals the loader payload byte for byte, that an
installed link resolves the canonical loader, and that an unreachable or failing
loader leaves the system prompt unchanged. It skips when `node` is absent. The full repository and versionctl suites
Expand Down
90 changes: 71 additions & 19 deletions opencode/agentsmd-project-direction.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,22 @@
* prompt. Any failure leaves the system prompt unchanged and logs one line.
* It also appends the pointer to the operations Skill from
* `bin/operations-routing`, because OpenCode does not always load it on its own.
*
* One default export serves both plugin APIs. OpenCode 1.x loads `{id, server}`
* and calls `server`; OpenCode 2.x loads `{id, setup}`, calls `setup` and
* ignores `server`.
*/

import { spawnSync } from "node:child_process";
import { realpathSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";

// `experimental.chat.system.transform` is experimental in this OpenCode
// version, which the bounded run adapter pins as well. The plugin context
// exposes no harness version, so the pin is documentation, not a runtime gate.
// OpenCode treats every export of a plugin module as a plugin function, so the
// pin stays a module constant and a property of the exported function.
const SUPPORTED_OPENCODE_VERSION = "1.18.32";
// The OpenCode versions this plugin was proved on. The 1.x hooks are
// experimental and the bounded run adapter pins 1.18.32. The plugin context
// exposes no harness version, so the list is documentation, not a runtime gate.
const SUPPORTED_OPENCODE_VERSIONS = Object.freeze(["1.18.32", "1.19.6", "2.3.2"]);
const PLUGIN_ID = "agentsmd-project-direction";

const LOG_PREFIX = "agentsmd-project-direction:";
const LOADER = ["bin", "project-direction"];
Expand Down Expand Up @@ -70,8 +73,7 @@ function loadRouting() {
return routing;
}

function sessionKey(input, directory) {
const given = input && input.sessionID;
function sessionKey(given, directory) {
return typeof given === "string" && given.trim()
? given
: `agentsmd-opencode:${directory}`;
Expand Down Expand Up @@ -153,29 +155,36 @@ function elonGate(directory, sessionID, tool, args) {
return null;
}

agentsmdProjectDirection.supportedOpenCodeVersion = SUPPORTED_OPENCODE_VERSION;
function systemEntries(directory, sessionID) {
const entries = [];
const loaded = loadContext(directory, sessionID);
if (loaded) {
entries.push(loaded);
}
const table = loadRouting();
if (table) {
entries.push(table);
}
return entries;
}

export default async function agentsmdProjectDirection(context) {
// OpenCode 1.x: hooks returned from `server`.
async function server(context) {
const directory =
(context && (context.directory || context.worktree)) || process.cwd();
return {
"experimental.chat.system.transform": async (input, output) => {
if (!output || !Array.isArray(output.system)) {
return;
}
const loaded = loadContext(directory, sessionKey(input, directory));
if (loaded) {
output.system.push(loaded);
}
const table = loadRouting();
if (table) {
output.system.push(table);
}
output.system.push(
...systemEntries(directory, sessionKey(input && input.sessionID, directory)),
);
},
"tool.execute.before": async (input, output) => {
const blocked = elonGate(
directory,
sessionKey(input, directory),
sessionKey(input && input.sessionID, directory),
input && input.tool,
output && output.args,
);
Expand All @@ -185,3 +194,46 @@ export default async function agentsmdProjectDirection(context) {
},
};
}

// OpenCode 2.x: hooks registered from `setup`. The `context` hook edits each
// primary model request; a throw in `execute.before` fails the tool call
// before it runs. OpenCode 1.x also calls `setup`, with a context that has no
// session or tool hooks; `server` already covers 1.x, so setup does nothing.
async function setup(context) {
const session = context && context.session;
const tool = context && context.tool;
if (
!session || typeof session.hook !== "function" ||
!tool || typeof tool.hook !== "function"
) {
return;
}
const location = context.location;
const directory = (location && location.directory) || process.cwd();
await session.hook("context", (input) => {
if (!input || !Array.isArray(input.system)) {
return;
}
for (const text of systemEntries(directory, sessionKey(input.sessionID, directory))) {
input.system.push({ type: "text", text });
}
});
await tool.hook("execute.before", (input) => {
const blocked = elonGate(
directory,
sessionKey(input && input.sessionID, directory),
input && input.tool,
input && input.input,
);
if (blocked) {
throw new Error(blocked);
}
});
}

export default {
id: PLUGIN_ID,
server,
setup,
supportedOpenCodeVersions: SUPPORTED_OPENCODE_VERSIONS,
};
75 changes: 42 additions & 33 deletions tests/test_elon_gate.py
Original file line number Diff line number Diff line change
Expand Up @@ -1221,47 +1221,56 @@ def test_read_only_gh_api_and_status_posts_pass(self) -> None:
with self.subTest(command=command):
self.assertEqual(self.hook({"command": command}, tool_name="Bash").returncode, 0)

# Calls the plugin's pre-tool hook through OpenCode 1.x `server` or the 2.x
# `setup` registration, printing `allowed` or `blocked:<message>`.
OPENCODE_GATE_DRIVER = (
"import { pathToFileURL } from 'node:url';\n"
"const [modulePath, directory, command, api] = process.argv.slice(2);\n"
"const plugin = (await import(pathToFileURL(modulePath).href)).default;\n"
"let before;\n"
"if (api === 'v2') {\n"
" const hooks = {};\n"
" const hook = (domain) => async (name, callback) => {\n"
" hooks[`${domain}.${name}`] = callback;\n"
" return { dispose: async () => {} };\n"
" };\n"
" await plugin.setup({ location: { directory }, session: { hook: hook('session') }, tool: { hook: hook('tool') } });\n"
" before = () => hooks['tool.execute.before']({ tool: 'shell', sessionID: 's', input: { command } });\n"
"} else {\n"
" const hooks = await plugin.server({ directory });\n"
" before = () => hooks['tool.execute.before']({ tool: 'bash', sessionID: 's' }, { args: { command } });\n"
"}\n"
"try { await before(); process.stdout.write('allowed'); }\n"
"catch (error) { process.stdout.write('blocked:' + error.message); }\n"
)

def opencode_gate(self, module: Path, command: str, api: str) -> str:
driver = self.cwd / "opencode-gate.mjs"
driver.write_text(self.OPENCODE_GATE_DRIVER, encoding="utf-8")
return subprocess.run([NODE, str(driver), str(module), str(self.cwd), command, api],
capture_output=True, text=True, env=self.env, check=True).stdout

@unittest.skipIf(NODE is None, "node is not on PATH")
def test_opencode_plugin_fails_closed_without_loader(self) -> None:
plugin_dir = self.cwd / "orphan/opencode"
plugin_dir.mkdir(parents=True)
shutil.copy(PLUGIN, plugin_dir / PLUGIN.name)
driver = self.cwd / "orphan.mjs"
driver.write_text(
"import { pathToFileURL } from 'node:url';\n"
"const [modulePath, directory] = process.argv.slice(2);\n"
"const hooks = await (await import(pathToFileURL(modulePath).href)).default({ directory });\n"
"try { await hooks['tool.execute.before']({ tool: 'bash' }, { args: { command: 'gh issue create --body hi' } });\n"
" process.stdout.write('allowed'); } catch (e) { process.stdout.write('blocked:' + e.message); }\n",
encoding="utf-8",
)
out = subprocess.run([NODE, str(driver), str(plugin_dir / PLUGIN.name), str(self.cwd)],
capture_output=True, text=True, env=self.env, check=True).stdout
self.assertTrue(out.startswith("blocked:AgentsMD could not run its Elon check"), out)
for api in ("v1", "v2"):
with self.subTest(api=api):
out = self.opencode_gate(plugin_dir / PLUGIN.name, "gh issue create --body hi", api)
self.assertTrue(out.startswith("blocked:AgentsMD could not run its Elon check"), out)

@unittest.skipIf(NODE is None, "node is not on PATH")
def test_opencode_plugin_throws_on_blocked_call(self) -> None:
driver = self.cwd / "driver.mjs"
driver.write_text(
"import { pathToFileURL } from 'node:url';\n"
"const [modulePath, directory, command] = process.argv.slice(2);\n"
"const hooks = await (await import(pathToFileURL(modulePath).href)).default({ directory });\n"
"try {\n"
" await hooks['tool.execute.before']({ tool: 'bash', sessionID: 's' }, { args: { command } });\n"
" process.stdout.write('allowed');\n"
"} catch (error) { process.stdout.write('blocked:' + error.message); }\n",
encoding="utf-8",
)

def run(command: str) -> str:
return subprocess.run([NODE, str(driver), str(PLUGIN), str(self.cwd), command],
capture_output=True, text=True, env=self.env, check=True).stdout

self.assertTrue(run("gh issue create --body hi").startswith("blocked:AgentsMD blocked"))
self.assertEqual(run("gh issue create --body " + shlex.quote(RECORD)), "allowed")
self.assertEqual(run("ls"), "allowed")
self.assertTrue(run("gh api repos/o/r/issues -f title=x").startswith("blocked:AgentsMD blocked"))

for api in ("v1", "v2"):
with self.subTest(api=api):
def run(command: str) -> str:
return self.opencode_gate(PLUGIN, command, api)

self.assertTrue(run("gh issue create --body hi").startswith("blocked:AgentsMD blocked"))
self.assertEqual(run("gh issue create --body " + shlex.quote(RECORD)), "allowed")
self.assertEqual(run("ls"), "allowed")
self.assertTrue(run("gh api repos/o/r/issues -f title=x").startswith("blocked:AgentsMD blocked"))


class ElonContractTests(unittest.TestCase):
Expand Down
Loading
Loading