Skip to content

Commit 8604a6d

Browse files
committed
Fix v2 adapter defects found in review
Ten fixes from review of the v2 adapter, each verified against the installed @opencode/plugin and @opencode/client dists: - isolation: move buildCoreContext/trimHostContext out of tools.ts (a runtime import of the v1 SDK) into tool-defs.ts, so loading the v2 adapter no longer evaluates @opencode-ai/plugin - absent on v2 user installs, which would kill the whole plugin load - generate hook: inject nudges into the wire Message's content array (there is no parts field; the stray property was silently dropped, muting all per-message nudges on v2) - session.get input is {sessionID}, not {id}; the adapter decodes input before the host call, so the old shape always rejected - extraction children: forward their events by ID - they are created in the project directory, which the directory filter drops whenever opencode is launched below the project root - event pump: per-event try/catch so one handler throw cannot end the loop for the process lifetime - wrap-up commands: substitute the invocation prompt text for ARGUMENTS (v2 does no template expansion; typed args were dropped) - session messages: read via session.context (no message accessor on the promise domain), restoring the wrap-up greenlight on v2 - compaction trigger: session.compact is not in the SessionDomain Pick; degrade to a logged no-op instead of throwing - tool buffering: flatten Tool.Result content arrays (text parts joined; typed output is not a title - the buffer's deriveTitle synthesizes) - stale wrap-up command files from v1 runs are removed on v2, since syncCommandFiles never deletes and a file collides with the code-registered command
1 parent 93306c8 commit 8604a6d

9 files changed

Lines changed: 381 additions & 119 deletions

File tree

‎docs/dev/features/opencode-plugin.md‎

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -57,20 +57,22 @@ the shared runtime needs. It is the lifecycle-level sibling of `CoreContext`
5757

5858
| Capability | v1 source | v2 source | v2 strategy |
5959
|---|---|---|---|
60-
| bus events | `event` hook | `event.subscribe` (raw SSE) | client-side location filter; location-less events drop (mirrors v1's server-side filter) |
61-
| incoming message | `chat.message` hook | `session.hook("prompt")` | the hook awaits the runtime; injections append to `prompt.text` (v2 has no synthetic parts) |
60+
| bus events | `event` hook | `event.subscribe` (raw SSE) | client-side location filter; location-less events resolve via `session.get` (`{sessionID}` input) and drop unresolvable (mirrors v1's server-side filter); events for plugin-created extraction children pass by ID (they live in the project directory, which differs from the instance directory on below-root launches) |
61+
| incoming message | `chat.message` hook | `session.hook("prompt")` | the hook awaits the runtime; nudge injections append to the OUTBOUND request's last user message in the generate hook (v2 wire `Message` carries parts in `content`, not `parts`) |
6262
| system prompt | `experimental.chat.system.transform` | `session.hook("context")` | mutates the request's system array; the runtime pushes a raw string where v2 types SystemPart (smoke-test-gated) |
6363
| compaction | `experimental.session.compacting` + `.autocontinue` + `session.compacted` | `session.hook("compaction")` | flag lands; context-injection surface unverified |
64-
| wrap-up commands | `command.execute.before` + command files | `command.transform` + `CommandEditor.add` | registered in code: `execute` arms the greenlight check (`armWrapUp`) and delivers the same prompt body the v1 file carries; the runtime installs only ACTION command files on v2 (a file and a registered command with the same name would collide) |
65-
| tools | `hooks.tool` map via `tool()` | `tool.transform` + `ToolEditor.add` | zod shapes pass as Standard Schema; results wrap as `{ content }` |
66-
| tool buffering | `tool.execute.after` hook | `tool.hook("execute.after")` | wired: feeds the same extraction buffer; result shape smoke-test-gated |
64+
| wrap-up commands | `command.execute.before` + command files | `command.transform` + `CommandEditor.add` | registered in code: `execute` arms the greenlight check (`armWrapUp`) and delivers the same prompt body the v1 file carries, substituting the invocation's prompt text for `$ARGUMENTS` (v2's `session.prompt` does no template expansion); the runtime installs only ACTION command files on v2 and REMOVES stale wrap-up files from earlier v1 runs (a file and a registered command with the same name would collide) |
65+
| tools | `hooks.tool` map via `tool()` | `tool.transform` + `ToolEditor.add` | zod shapes pre-converted to JSON Schema with our own zod (v2's `instanceof $ZodType` detection fails for ours and drops the schema); results wrap as `{ content }` |
66+
| tool buffering | `tool.execute.after` hook | `tool.hook("execute.after")` | wired: feeds the same extraction buffer; `Tool.Result.content` is flattened (string passes through, content-part arrays contribute their text parts), title is left empty (the buffer's `deriveTitle` synthesizes one) |
6767
| noReply deliveries | `promptAsync` with `noReply` | none | gated off via `HostCapabilities.noReplyDelivery` -- chat echoes and the session-start reminder are skipped on v2 (delivering them would start real model turns: a feedback loop) |
6868
| synthetic wake deliveries | `promptAsync` with `synthetic` parts | `session.synthetic` endpoint | watcher + chat wake nudges route to v2's synthetic endpoint (TUI-hidden), matching v1 |
69-
| child sessions | `client.session.create/promptAsync/prompt/delete` | `session.create/prompt` | create+prompt supported (shapes smoke-test-gated; a missing id throws into the extraction fallback); delete degrades (extraction children are not cleaned up on v2) |
69+
| child sessions | `client.session.create/promptAsync/prompt/delete` | `session.create/prompt` | create+prompt supported (a missing id throws into the extraction fallback); delete degrades (extraction children are not cleaned up on v2 -- the session picker accumulates one `thatch-extraction` entry per extraction, and `-c` "continue last session" logic that picks the newest top-level session will land in an extraction child after any session that triggered extraction) |
7070
| session status | `client.session.status` | none | returns `{}`; the wake gate treats unknown as idle and the event-fed status map does the gating |
71-
| session list/messages | `client.session.list/messages` | none | degrade (`-c` resume listing + wrap-up greenlight lose their data source) |
71+
| session messages | `client.session.messages` | `session.context` | mapped into the v1 `{info: {role}, parts}` shape, so the wrap-up greenlight check works (the promise domain has no `message` accessor) |
72+
| session list | `client.session.list` | none | degrade (`-c` resume listing loses its data source) |
73+
| compaction trigger | `client.tui.executeCommand("session_compact")` | none | degrade (the promise domain's SessionDomain Pick has no `session.compact`; the wrap-up checklist and flush still run, only the automatic compaction is skipped) |
7274
| toasts | `client.tui.showToast` | none reachable | degrade (the `tui.toast.show` event has no producer surface from the promise context) |
73-
| TUI actions | `client.tui.executeCommand/publish` | none | degrade |
75+
| TUI actions | `client.tui.executeCommand/publish` | none | degrade (except the compaction trigger, handled above) |
7476
| dispose | `dispose` hook | cleanup returned from `setup` | must be idempotent: v2 auto-reloads plugins on file change, and a non-idempotent cleanup doubles pollers/pumps/nudges |
7577

7678
## Smoke-test-gated unknowns

‎src/commands.ts‎

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
1+
import { mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
22
import { join } from "node:path";
33
import {
44
defragCore,
@@ -229,6 +229,26 @@ export function installOpencodeCommands(configHome: string, defs: CommandDef[] =
229229
return syncCommandFiles(join(configHome, "opencode", "command", "thatch"), defs);
230230
}
231231

232+
/**
233+
* Removes wrap-up command files left in the opencode command dir. Hosts
234+
* that register wrap-up commands in code (v2) pass the action-only set to
235+
* installOpencodeCommands, but files written by earlier v1 runs persist -
236+
* syncCommandFiles never removes - and a stale file collides with the
237+
* registered command (both versions share the config dir). Call this
238+
* before installing on such hosts. Idempotent: missing files are fine.
239+
*/
240+
export function removeWrapUpCommandFiles(configHome: string): void {
241+
const dir = join(configHome, "opencode", "command", "thatch");
242+
for (const kind of ["compact", "exit"] as const) {
243+
try {
244+
unlinkSync(join(dir, `${kind}.md`));
245+
} catch {
246+
// ENOENT is the expected steady state; anything else is equally
247+
// harmless for a best-effort cleanup.
248+
}
249+
}
250+
}
251+
232252
/** Sync Claude Code's commands into <claudeDir>/commands/thatch/ (claudeDir is ~/.claude or <project>/.claude). */
233253
export function installClaudeCommands(claudeDir: string): string[] {
234254
return syncCommandFiles(join(claudeDir, "commands", "thatch"), claudeCommandDefs());

0 commit comments

Comments
 (0)