Skip to content

feat(opencode): sync built-in and agent hooks as an OpenCode plugin - #326

Merged
jeff-r2026 merged 3 commits into
Tencent:mainfrom
jeff-r2026:feat/opencode-hooks
Aug 26, 2026
Merged

jeff-r2026 merged 3 commits into
Tencent:mainfrom
jeff-r2026:feat/opencode-hooks

Conversation

@jeff-r2026

Copy link
Copy Markdown
Collaborator

What

Implements the final remaining piece of #303: OpenCode hooks. PR #306 shipped OpenCode skills/rules/subagents/MCP but explicitly deferred hooks (SessionStart, etc.) to a follow-up — this is that follow-up.

Why it's different from every other agent

OpenCode has no settings.json hook list. It auto-loads JS/TS plugins — the config loader scans {plugin,plugins}/*.{ts,js} under .opencode/ (project) and ~/.config/opencode/ (user). So teamai generates a teamai-hooks.ts plugin that subscribes to OpenCode's own events and shells out to the same teamai hook-dispatch entry point every other tool uses. Like the Hermes/OpenClaw adapters it is fire-and-forget — OpenCode has no channel to inject a hook's stdout back into the session, so hooks run for their side effects (status report / sync / update) and never block the agent.

Event mapping (mirrors the Claude built-in set)

Claude event teamai dispatch OpenCode hook
SessionStart session-start session.created
Stop stop session.idle
UserPromptSubmit prompt-submit chat.message
PostToolUse post-tool-use tool.execute.after (Skill/TodoWrite matchers forwarded)

Changes

  • src/opencode-hooks.ts (new): plugin generator + inject/remove + agent-hook apply/remove pair; project vs user scope resolution.
  • hooks.ts: route opencode through the plugin adapter in reconcileHooksToAllTools / injectHooksToAllTools (like Hermes), threading a scope param so the plugin lands in the right config dir.
  • hooks-cmd.ts: pass scope on hooks inject/remove — baseDir is HOME, so these install to the global ~/.config/opencode/plugin (covers every project, matching how settings.json hooks live in HOME).
  • local-agent.ts: dispatch HTTP-source agent hooks (feat(http): support install_hooks / uninstall_hooks sync commands #238) to the opencode backend (4 sites) instead of erroring on the missing settings path.
  • uninstall.ts: discover and remove opencode plugin files (main hook + leftover agent-hook plugins).
  • pull.ts: thread scope through hook auto-migration.
  • Docs: README (both languages) feature-matrix hooks column —→✓; usage-guide (both languages) OpenCode section gains a Hooks bullet.

Test Plan

All executed and passing:

  • npx tsc --noEmit — clean
  • npx vitest run — 2209 passing (added 22 cases in opencode-hooks.test.ts, incl. generated-plugin JS syntax validity across quote/backtick/hyphen-slug edge cases; updated 4 hooks-cmd assertions for the new scope arg)
  • npm run build — success
  • Packaged E2E — npm pack → npm install the tarball into a clean project → drive the real installed teamai binary against a local git team repo:
    • teamai pull (project scope) → plugin written to <root>/.opencode/plugin/teamai-hooks.ts, all 4 event mappings present
    • teamai hooks inject (global) → plugin written to ~/.config/opencode/plugin/teamai-hooks.ts
    • node --check on the generated plugin → valid JS
    • teamai hooks remove → both plugins removed
    • teamai uninstall --agent opencode → project plugin cleaned up

Closes #303

OpenCode has no settings.json hook list; it auto-loads JS/TS plugins from
.opencode/plugin (project) or ~/.config/opencode/plugin (user). Generate a
teamai-hooks.ts plugin there that subscribes to OpenCode's own events and
shells out to the same `teamai hook-dispatch` entry point every other tool
uses. Fire-and-forget (OpenCode cannot inject a hook's stdout back into the
session), matching the Hermes/OpenClaw adapters.

Event mapping mirrors the Claude built-in set:
  session.created    -> session-start
  session.idle       -> stop
  chat.message       -> prompt-submit
  tool.execute.after -> post-tool-use (Skill/TodoWrite matchers forwarded)

- new src/opencode-hooks.ts: plugin generator + inject/remove + agent-hook pair
- hooks.ts: route opencode through the plugin adapter in reconcile/inject-all,
  threading scope so project vs user lands in the right config dir
- hooks-cmd.ts: pass scope on inject/remove (global ~/.config/opencode/plugin)
- local-agent.ts: dispatch HTTP-source agent hooks to the opencode backend
- uninstall.ts: discover and remove opencode plugin files (main + agent hooks)
- pull.ts: thread scope through hook auto-migration
- docs: README (both langs) feature matrix hooks column, usage-guide OpenCode section

Closes Tencent#303 (final remaining piece: OpenCode hooks).
…ize agent hooks

The OpenCode plugin adapter had four defects, all verified against a real
OpenCode 1.15.13 runtime (tool ids come back lowercase; named hooks are awaited):

1. Matcher casing: the plugin tested `tool === 'Skill' || 'TodoWrite'`, but
   OpenCode passes lowercase ids (`skill`/`todowrite`), so the Skill-usage and
   TodoWrite-hint handlers never fired. Map the id back to the PascalCase
   matcher the handler registry keys on.

2. Empty STDIN: the plugin shelled out with no payload, so track/track-slash/
   todowrite-hint (which read tool_name/tool_input/prompt) no-op'd, and the
   provider-config gate fell back to the user config because cwd was undefined.
   Forward a JSON payload on STDIN (cwd from the plugin ctx + per-event fields)
   via a Response (Bun shell can't redirect a bare string).

3. Agent-hook matcher ignored: applyOpencodeAgentHook dropped matcher/timeout,
   so a tool-scoped enterprise hook ran after every tool call. Thread matcher
   through and gate tool.execute.after on the (case-insensitive) tool id.

4. Slug path traversal: the agent-hook filename was built from an unsanitized
   backend slug, so `../../evil` wrote outside the plugin dir. Add assertSafeSlug.

Docs (both languages) corrected: OpenCode awaits its named hooks, so the
dispatch is not truly non-blocking for chat.message/tool.execute.after.
@jeff-r2026

Copy link
Copy Markdown
Collaborator Author

Pushed a fix commit (513f3a3) addressing four defects found in code review, all verified against a real OpenCode 1.15.13 runtime (not just static analysis).

Fixes

  1. Matcher casing — OpenCode passes lowercase tool ids (skill/todowrite), but the plugin tested tool === 'Skill' || 'TodoWrite', so the Skill-usage and TodoWrite-hint handlers were dead for every OpenCode user. Now maps the id back to the PascalCase matcher the handler registry keys on.
  2. Empty STDIN / missing cwd — the plugin shelled out with no payload, so track/track-slash/todowrite-hint (which read tool_name/tool_input/prompt) no-op'd, and the provider-config gate fell back to the user config because cwd was undefined. Now forwards a JSON payload on STDIN (cwd from the plugin ctx + per-event fields) via a Response (Bun shell can't redirect a bare string).
  3. Agent-hook matcher ignored — applyOpencodeAgentHook dropped matcher, so a tool-scoped enterprise hook ran after every tool call. Now threads matcher through and gates tool.execute.after on the (case-insensitive) tool id.
  4. Slug path traversal — the agent-hook filename was built from an unsanitized backend slug (../../evil escaped the plugin dir). Added assertSafeSlug.

Docs (both languages) corrected: OpenCode awaits its named hooks, so the dispatch is not truly non-blocking for chat.message/tool.execute.after.

Verification (real OpenCode 1.15.13)

  • Tool ids are lowercase: GET /experimental/tool/ids on a headless server returns ["...","skill",...,"todowrite",...]; source confirms Tool.define("skill") / Tool.define("todowrite") and the tool.execute.after trigger passes { tool: item.id }.
  • STDIN before/after: with a fake teamai binary intercepting real plugin calls — before: STDIN: empty on every event; after: {"cwd":".../proj"} on session-start and {"cwd":"...","prompt":"/deploy hello world"} on prompt-submit.
  • Tool-id mapping: feeding the fixed plugin lowercase skill/todowrite/bash produces --matcher Skill / --matcher TodoWrite / (no matcher), with correct tool_name/tool_input on STDIN.
  • Full chain: piping the plugin's payload into the real hook-dispatch records the usage event (1 row) where the old code recorded 0.

All 2214 unit tests pass; opencode-hooks.test.ts updated with coverage for the mapping, STDIN payload, matcher gating, and slug rejection.

OpenCode auto-loads plugins from both ~/.config/opencode/plugin and
<project>/.opencode/plugin. pull/init wrote the plugin at the active
teamai scope while `hooks inject` and agent hooks always wrote the user
dir, so a project-scope setup ended up with two identical plugins loaded
in the same workspace — every event dispatched twice (sync, dashboard,
session-start pull).

Route every path through one reconciler that writes only the user plugin
dir and deletes a project-scope copy from the earlier layout, and drop
the now-unused scope plumbing. Uninstall inspects both locations, and its
agent-hook sweep joins the plugin dir onto the relative paths
listFilesRecursive returns instead of deleting cwd-relative ones.

Also make every user-facing uninstall string English, per the repo's
output-language rule.

Co-authored-by: Cursor <[email protected]>
@jeff-r2026
jeff-r2026 merged commit d004fcb into Tencent:main Aug 26, 2026
7 checks passed
@jeff-r2026
jeff-r2026 deleted the feat/opencode-hooks branch August 26, 2026 06:30
jeff-r2026 added a commit that referenced this pull request Aug 26, 2026
#326 translated the uninstall command's user-facing output to English, but
two e2e assertions still expected the old Chinese strings, so CI on main
went red:

  e2e.test.ts               '卸载完成'                    -> 'teamai uninstalled'
  scope-isolation-e2e.test.ts '正在卸载 project scope(项目级)' -> 'Uninstalling project scope'

The English output is the intended behavior (CLI output must be English);
only the stale assertions needed updating.

These never failed on #326's own runs because its PR-level e2e job was
queued behind the e2e-fixture-repo concurrency lock and got dropped on
merge, and its post-merge run on main was cancelled by the next push.

Co-authored-by: Cursor <[email protected]>
Walternater pushed a commit to Walternater/teamai-cli that referenced this pull request Nov 2, 2026
…encent#326)

* feat(opencode): sync built-in and agent hooks as an OpenCode plugin

OpenCode has no settings.json hook list; it auto-loads JS/TS plugins from
.opencode/plugin (project) or ~/.config/opencode/plugin (user). Generate a
teamai-hooks.ts plugin there that subscribes to OpenCode's own events and
shells out to the same `teamai hook-dispatch` entry point every other tool
uses. Fire-and-forget (OpenCode cannot inject a hook's stdout back into the
session), matching the Hermes/OpenClaw adapters.

Event mapping mirrors the Claude built-in set:
  session.created    -> session-start
  session.idle       -> stop
  chat.message       -> prompt-submit
  tool.execute.after -> post-tool-use (Skill/TodoWrite matchers forwarded)

- new src/opencode-hooks.ts: plugin generator + inject/remove + agent-hook pair
- hooks.ts: route opencode through the plugin adapter in reconcile/inject-all,
  threading scope so project vs user lands in the right config dir
- hooks-cmd.ts: pass scope on inject/remove (global ~/.config/opencode/plugin)
- local-agent.ts: dispatch HTTP-source agent hooks to the opencode backend
- uninstall.ts: discover and remove opencode plugin files (main + agent hooks)
- pull.ts: thread scope through hook auto-migration
- docs: README (both langs) feature matrix hooks column, usage-guide OpenCode section

Closes Tencent#303 (final remaining piece: OpenCode hooks).

* fix(opencode): forward hook STDIN payload, map tool ids, gate & sanitize agent hooks

The OpenCode plugin adapter had four defects, all verified against a real
OpenCode 1.15.13 runtime (tool ids come back lowercase; named hooks are awaited):

1. Matcher casing: the plugin tested `tool === 'Skill' || 'TodoWrite'`, but
   OpenCode passes lowercase ids (`skill`/`todowrite`), so the Skill-usage and
   TodoWrite-hint handlers never fired. Map the id back to the PascalCase
   matcher the handler registry keys on.

2. Empty STDIN: the plugin shelled out with no payload, so track/track-slash/
   todowrite-hint (which read tool_name/tool_input/prompt) no-op'd, and the
   provider-config gate fell back to the user config because cwd was undefined.
   Forward a JSON payload on STDIN (cwd from the plugin ctx + per-event fields)
   via a Response (Bun shell can't redirect a bare string).

3. Agent-hook matcher ignored: applyOpencodeAgentHook dropped matcher/timeout,
   so a tool-scoped enterprise hook ran after every tool call. Thread matcher
   through and gate tool.execute.after on the (case-insensitive) tool id.

4. Slug path traversal: the agent-hook filename was built from an unsanitized
   backend slug, so `../../evil` wrote outside the plugin dir. Add assertSafeSlug.

Docs (both languages) corrected: OpenCode awaits its named hooks, so the
dispatch is not truly non-blocking for chat.message/tool.execute.after.

* fix(opencode): keep one plugin copy and fix uninstall sweep path

OpenCode auto-loads plugins from both ~/.config/opencode/plugin and
<project>/.opencode/plugin. pull/init wrote the plugin at the active
teamai scope while `hooks inject` and agent hooks always wrote the user
dir, so a project-scope setup ended up with two identical plugins loaded
in the same workspace — every event dispatched twice (sync, dashboard,
session-start pull).

Route every path through one reconciler that writes only the user plugin
dir and deletes a project-scope copy from the earlier layout, and drop
the now-unused scope plumbing. Uninstall inspects both locations, and its
agent-hook sweep joins the plugin dir onto the relative paths
listFilesRecursive returns instead of deleting cwd-relative ones.

Also make every user-facing uninstall string English, per the repo's
output-language rule.

Co-authored-by: Cursor <[email protected]>

---------

Co-authored-by: Cursor <[email protected]>
Walternater pushed a commit to Walternater/teamai-cli that referenced this pull request Nov 2, 2026
)

Tencent#326 translated the uninstall command's user-facing output to English, but
two e2e assertions still expected the old Chinese strings, so CI on main
went red:

  e2e.test.ts               '卸载完成'                    -> 'teamai uninstalled'
  scope-isolation-e2e.test.ts '正在卸载 project scope(项目级)' -> 'Uninstalling project scope'

The English output is the intended behavior (CLI output must be English);
only the stale assertions needed updating.

These never failed on Tencent#326's own runs because its PR-level e2e job was
queued behind the e2e-fixture-repo concurrency lock and got dropped on
merge, and its post-merge run on main was cancelled by the next push.

Co-authored-by: Cursor <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[feat] Support OpenCode agent and GitLab as git provider

1 participant