Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(opencode): load the status plugin on OpenCode 2.x without breaking 1.x (#1239)
eneskirca0df678d3fc54
diff --git a/CLAUDE.md b/CLAUDE.mdindex fa457cb60..3594d6d7d 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -3133,6 +3133,29 @@ else, and its context links must keep classifying across restarts).installer needs is why events are typed `ManagedHookEvent` (`string | {event, matcher}`): grok'stool matcher is a REGEX and must be `.*` — a bare `*` is invalid and silently stops tool eventsfiring. Plain-string events keep their byte-identical output for every other agent.+ **opencode gets TWO plugin files, because no single module loads on both of its generations**+ (issue #1136, `hooks/opencode.ts`, measured 2026-10-16 on @opencode/cli 2.0.30 and opencode-ai+ 1.1.4 / 1.2.10 / 1.18.28 / 1.18.33). 2.x accepts only a default export OBJECT `{ id, setup }` (a+ function default is refused) and loads `plugins/*.js` and plugin DIRECTORIES; 1.x loads only+ `{plugin,plugins}/*.{ts,js}` files, and up to **1.2.10 calls every export as a function** — an+ object default there throws and kills every opencode command on the machine, inside nodeterm or+ not (bisected: 1.2.10 crashes, 1.2.11 does not). So `plugins/nodeterm-status.js` keeps ONLY the+ named 1.x export (2.x logs a harmless "failed to load plugin" WARN for it at every start) and 2.x+ gets `plugins/nodeterm-status-v2/index.js`, a directory no 1.x glob matches. **Never add a default+ export to the 1.x file**, and never "simplify" the pair back into one dual-shape file. A+ process-wide latch (`Symbol.for('nodeterm.opencode.status.api')`, keyed by API, not by call)+ keeps a process that runs both from posting twice. The 2.x plugin translates its event stream to+ the 1.x wire names (`session.execution.started` → user `message.updated`, `…succeeded|interrupted`+ → `session.idle`, `…failed` → `session.error`, `form.*` → `question.*`), so `normalizeOpencode` has+ one dialect, and it drops a subagent child session's turn events (forwarding its permission/form+ under the root session). **It refuses to run inside 2.x's shared background server**+ (`serve --service`, argv): by default every 2.x CLI talks to ONE server that keeps the env of+ whichever pane started it and outlives it — measured, a second pane's events carried the first+ pane's `NODETERM_NODE_ID` — so posting from it would paint one node's status on another (the+ codex `--no-daemon` problem). Only a `--standalone` server (the pane's own `serve --stdio` child)+ reports, so **2.x status needs `opencode --standalone`**; nodeterm does not pass it yet (1.x exits+ on the unknown flag, so it needs a codex-style `--help` probe — follow-up), and until then the+ Launch commands override (`opencode --standalone`) is the user's switch.**Codex is the one agent whose hook command is NOT a POSIX one-liner on Windows** (issue #567):it builds the command as `cmd.exe /C <string>` (`codex-rs/hooks/src/engine/command_runner.rs`,rust-v0.151.0) unless the session has a shell configured, which a default Windows install hasdiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 9c016d12b..823f732c8 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -1249,6 +1249,13 @@ silently enabled every agent on a fresh install's second boot (#1149). Only a no`~/.nodeterm/agent-hooks/` counts, and only on an install's first boot (the fresh-install marker). Do not merge text into `AGENTS.md` / `GEMINI.md` — agents get skills (progressive disclosure)instead; the old blocks crowded codex's 32 KiB instruction budget.+**opencode has two managed plugins and they must stay two** (issue #1136): the 1.x file+`plugins/nodeterm-status.js` exports ONLY the named function — opencode <= 1.2.10 calls every export+as a function and dies on a default object, for every command on the machine — and 2.x gets the+directory `plugins/nodeterm-status-v2/`, which no 1.x loads. The 2.x plugin stays silent inside the+shared `serve --service` server (its env belongs to another pane); see CLAUDE.md for the+measurements.+Claude/Gemini settings must go through the guarded transactions in`src/core/agents/hooks/{settings-file,remote-settings-file}.ts`. Confirmed absence or a successfully read empty/whitespace file may start from `{}`;malformed, non-object and unreadable files must survive unchanged.diff --git a/src/core/agents/hooks/opencode.test.ts b/src/core/agents/hooks/opencode.test.tsindex cf8b3dc34..d46d5df06 100644--- a/src/core/agents/hooks/opencode.test.ts+++ b/src/core/agents/hooks/opencode.test.ts@@ -5,14 +5,23 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import {PLUGIN_MARKER,buildOpencodePlugin,+ buildOpencodeV2Plugin,installOpencodeHooks,opencodeConfigDir,pluginPath,- removeOpencodeHooks+ removeOpencodeHooks,+ v2PluginPath} from './opencode'+import { normalizeOpencode } from '../../../shared/agents/normalize'++// Both generated plugins share one process-wide latch (which plugin API armed first). Every test+// loads fresh module copies into the SAME process, so the latch is reset before each one.+const LATCH = Symbol.for('nodeterm.opencode.status.api')+const g = globalThis as unknown as Record<symbol, unknown>let tmp: stringbeforeEach(() => {+ delete g[LATCH]tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-oc-'))vi.spyOn(os, 'homedir').mockReturnValue(tmp)// CI runners export XDG_CONFIG_HOME (GitHub Actions: /home/runner/.config), which wins@@ -467,3 +476,338 @@ describe('opencodeConfigDir honors XDG_CONFIG_HOME', () => {}})})++// Issue #1136. OpenCode 2.x needs a default export object `{ id, setup }`; OpenCode <= 1.2.10+// calls every export as a function and dies on an object (bisected on real builds). So there are+// TWO plugins: the 1.x file (named export only) and a 2.x DIRECTORY no 1.x glob matches.+const planted2 = () => path.join(tmp, '.config', 'opencode', 'plugins', 'nodeterm-status-v2', 'index.js')++describe('opencode plugin install — the 2.x directory plugin', () => {+ it('plants both plugins, each marker-bearing, at the paths each opencode generation loads', () => {+ installOpencodeHooks()+ expect(v2PluginPath()).toBe(planted2())+ expect(fs.readFileSync(planted(), 'utf8')).toBe(buildOpencodePlugin())+ expect(fs.readFileSync(planted2(), 'utf8')).toBe(buildOpencodeV2Plugin())+ expect(fs.readFileSync(planted2(), 'utf8').startsWith(PLUGIN_MARKER)).toBe(true)+ })+ it('refreshes a stale managed copy (an older build\'s body) but never a user file', () => {+ fs.mkdirSync(path.dirname(planted2()), { recursive: true })+ fs.writeFileSync(planted2(), PLUGIN_MARKER + '\n// old body\n')+ installOpencodeHooks()+ expect(fs.readFileSync(planted2(), 'utf8')).toBe(buildOpencodeV2Plugin())+ fs.writeFileSync(planted2(), '// my own v2 plugin\n')+ installOpencodeHooks()+ expect(fs.readFileSync(planted2(), 'utf8')).toBe('// my own v2 plugin\n')+ })+ it('does not rewrite an up-to-date file (opencode 2.x watches plugin files and reloads on change)', () => {+ installOpencodeHooks()+ const past = Math.floor(Date.now() / 1000) - 60 // whole seconds: mtimeMs is a float+ fs.utimesSync(planted2(), past, past)+ installOpencodeHooks()+ expect(Math.round(fs.statSync(planted2()).mtimeMs / 1000)).toBe(past)+ })+ it('remove deletes both managed plugins and the now-empty directory, but keeps anything else', () => {+ installOpencodeHooks()+ removeOpencodeHooks()+ expect(fs.existsSync(planted())).toBe(false)+ expect(fs.existsSync(path.dirname(planted2()))).toBe(false)+ installOpencodeHooks()+ fs.writeFileSync(path.join(path.dirname(planted2()), 'notes.txt'), 'mine')+ removeOpencodeHooks()+ expect(fs.existsSync(planted2())).toBe(false)+ expect(fs.readFileSync(path.join(path.dirname(planted2()), 'notes.txt'), 'utf8')).toBe('mine')+ })+})++describe('generated plugins, module shapes (executed)', () => {+ let posts: Array<Record<string, unknown>>++ beforeEach(() => {+ posts = []+ vi.stubGlobal('fetch', (_url: string, init: { body: string }) => {+ posts.push(JSON.parse(new URLSearchParams(init.body).get('payload') ?? '{}'))+ return Promise.resolve(new Response())+ })+ vi.stubEnv('NODETERM_NODE_ID', 'node-1')+ vi.stubEnv('NODETERM_HOOK_PORT', '43210')+ vi.stubEnv('NODETERM_HOOK_TOKEN', 'tok')+ vi.stubEnv('NODETERM_HOOK_ENDPOINT', '')+ vi.stubEnv('NODETERM_HOOK_SOCK', '')+ })+ afterEach(() => {+ vi.unstubAllEnvs()+ vi.unstubAllGlobals()+ })++ type V1Hooks = Record<string, (input: unknown) => Promise<void>>+ type V2Def = { id: string; setup: (ctx: unknown) => Promise<(() => void) | void> }++ async function load(body: string): Promise<Record<string, unknown>> {+ const file = path.join(tmp, `plugin-${Math.random().toString(36).slice(2)}.mjs`)+ fs.writeFileSync(file, body)+ return import(/* @vite-ignore */ `file://${file}`)+ }+ const loadV1 = async (): Promise<{ NodetermStatus: () => Promise<V1Hooks> }> =>+ (await load(buildOpencodePlugin())) as unknown as { NodetermStatus: () => Promise<V1Hooks> }+ const loadV2 = async (): Promise<V2Def> => (await load(buildOpencodeV2Plugin())).default as V2Def++ /** A 2.x context: an event stream we push into, and a tool-hook registry. */+ function v2Context(): {+ ctx: unknown+ push: (type: string, data: Record<string, unknown>) => void+ end: () => void+ toolHooks: Array<{ name: string; cb: (input: unknown) => unknown }>+ subscribed: () => number+ signal: () => AbortSignal | undefined+ } {+ const queue: unknown[] = []+ let wake: (() => void) | null = null+ let done = false+ let subs = 0+ let sig: AbortSignal | undefined+ const toolHooks: Array<{ name: string; cb: (input: unknown) => unknown }> = []+ const ctx = {+ event: {+ subscribe: (options?: { signal?: AbortSignal }) => {+ subs+++ sig = options?.signal+ return {+ async *[Symbol.asyncIterator]() {+ for (;;) {+ if (queue.length) {+ yield queue.shift()+ continue+ }+ if (done || sig?.aborted) return+ await new Promise<void>((r) => (wake = r))+ }+ }+ }+ }+ },+ tool: {+ hook: async (name: string, cb: (input: unknown) => unknown) => {+ toolHooks.push({ name, cb })+ return { dispose: () => {} }+ }+ }+ }+ return {+ ctx,+ push: (type, data) => {+ queue.push({ id: 'evt_' + queue.length, created: 1, type, location: { directory: '/p' }, data })+ wake?.()+ },+ end: () => {+ done = true+ wake?.()+ },+ toolHooks,+ subscribed: () => subs,+ signal: () => sig+ }+ }+ const flush = (): Promise<void> => new Promise((r) => setTimeout(r, 0))++ it('1.x file: ONLY the named function export — a default would crash opencode <= 1.2.10', async () => {+ const mod = await load(buildOpencodePlugin())+ // opencode <= 1.2.10 does `for (const [, fn] of Object.entries(mod)) await fn(input)`.+ expect(Object.keys(mod)).toEqual(['NodetermStatus'])+ for (const v of Object.values(mod)) expect(typeof v).toBe('function')+ })++ it('2.x directory plugin: a default OBJECT with an id and a setup function, nothing else exported', async () => {+ const mod = await load(buildOpencodeV2Plugin())+ expect(Object.keys(mod)).toEqual(['default'])+ const def = mod.default as V2Def+ expect(typeof def).toBe('object')+ expect(def.id).toBe('nodeterm-status')+ expect(typeof def.setup).toBe('function')+ })++ it('2.x: translates the event stream to the 1.x wire names normalizeOpencode reads', async () => {+ const def = await loadV2()+ const v2 = v2Context()+ await def.setup(v2.ctx)+ expect(v2.subscribed()).toBe(1)+ v2.push('session.created', { sessionID: 'ses_1', projectID: 'p', slug: 's', version: '2.0.30' })+ v2.push('session.inbox.enqueued', { sessionID: 'ses_1' })+ v2.push('session.execution.started', { sessionID: 'ses_1' })+ v2.push('session.text.delta', { sessionID: 'ses_1', delta: 'hi' })+ v2.push('permission.asked', { id: 'per_1', sessionID: 'ses_1', action: 'shell' })+ v2.push('permission.replied', { sessionID: 'ses_1', requestID: 'per_1', reply: 'once' })+ v2.push('form.created', { form: { id: 'frm_1', sessionID: 'ses_1', title: 'Questions' } })+ v2.push('form.replied', { id: 'frm_1', sessionID: 'ses_1', answer: { q0: 'Red' } })+ v2.push('form.created', { form: { id: 'frm_2', sessionID: 'ses_1' } })+ v2.push('form.cancelled', { id: 'frm_2', sessionID: 'ses_1' })+ v2.push('session.execution.succeeded', { sessionID: 'ses_1' })+ v2.push('session.execution.started', { sessionID: 'ses_1' })+ v2.push('session.execution.interrupted', { sessionID: 'ses_1' })+ v2.push('session.execution.started', { sessionID: 'ses_1' })+ v2.push('session.execution.failed', { sessionID: 'ses_1', error: {} })+ await flush()+ expect(posts).toEqual([+ { event: 'session.created', sessionID: 'ses_1' },+ { event: 'message.updated', sessionID: 'ses_1', role: 'user' },+ { event: 'permission.asked', sessionID: 'ses_1' },+ { event: 'permission.replied', sessionID: 'ses_1' },+ { event: 'question.asked', sessionID: 'ses_1' },+ { event: 'question.replied', sessionID: 'ses_1' },+ { event: 'question.asked', sessionID: 'ses_1' },+ { event: 'question.rejected', sessionID: 'ses_1' },+ { event: 'session.idle', sessionID: 'ses_1' },+ { event: 'message.updated', sessionID: 'ses_1', role: 'user' },+ { event: 'session.idle', sessionID: 'ses_1' },+ { event: 'message.updated', sessionID: 'ses_1', role: 'user' },+ { event: 'session.error', sessionID: 'ses_1' }+ ])+ v2.end()+ })++ it('2.x: a real 2.0.30 TUI turn (as captured) normalizes to the same states as a 1.x turn', async () => {+ // The order a measured `opencode --standalone` turn produced: a shell call behind a+ // permission prompt, then a question form, then the end of the turn.+ const def = await loadV2()+ const v2 = v2Context()+ await def.setup(v2.ctx)+ const hook = v2.toolHooks[0].cb+ v2.push('session.created', { sessionID: 'ses_1' })+ v2.push('session.execution.started', { sessionID: 'ses_1' })+ await flush()+ hook({ tool: 'shell', sessionID: 'ses_1' })+ v2.push('permission.asked', { id: 'per_1', sessionID: 'ses_1' })+ v2.push('permission.replied', { sessionID: 'ses_1', requestID: 'per_1', reply: 'once' })+ await flush()+ hook({ tool: 'question', sessionID: 'ses_1' })+ v2.push('form.created', { form: { id: 'frm_1', sessionID: 'ses_1' } })+ v2.push('form.replied', { id: 'frm_1', sessionID: 'ses_1', answer: { q0: 'Red' } })+ v2.push('session.execution.succeeded', { sessionID: 'ses_1' })+ await flush()+ const states = posts.map((payload) => {+ const n = normalizeOpencode({ nodeId: 'node-1', agentId: 'opencode', payload })+ return n && (n.kind === 'state' ? n.state + (n.newTurn ? '+newTurn' : '') : n.kind)+ })+ expect(states).toEqual([+ 'session',+ 'working+newTurn',+ 'working',+ 'blocked',+ 'working',+ 'working',+ 'blocked',+ 'working',+ 'done'+ ])+ v2.end()+ })++ it('2.x: the tool hook posts tool.execute.before and never throws into the tool call', async () => {+ const def = await loadV2()+ const v2 = v2Context()+ await def.setup(v2.ctx)+ expect(v2.toolHooks.map((h) => h.name)).toEqual(['execute.before'])+ expect(() => v2.toolHooks[0].cb({ tool: 'shell', sessionID: 'ses_1', id: 'call_1' })).not.toThrow()+ expect(() => v2.toolHooks[0].cb(undefined)).not.toThrow()+ expect(posts[0]).toEqual({ event: 'tool.execute.before', sessionID: 'ses_1' })+ v2.end()+ })++ it('2.x: a subagent child session does not move the node, but its blocking prompts do (under the root id)', async () => {+ const def = await loadV2()+ const v2 = v2Context()+ await def.setup(v2.ctx)+ v2.push('session.created', { sessionID: 'ses_c', parentID: 'ses_1' })+ v2.push('session.created', { sessionID: 'ses_g', parentID: 'ses_c' })+ v2.push('session.execution.started', { sessionID: 'ses_c' })+ v2.push('permission.asked', { id: 'per_1', sessionID: 'ses_g' })+ v2.push('form.created', { form: { id: 'frm_1', sessionID: 'ses_c' } })+ v2.push('form.replied', { id: 'frm_1', sessionID: 'ses_c' })+ v2.push('session.execution.succeeded', { sessionID: 'ses_c' })+ await flush()+ v2.toolHooks[0].cb({ tool: 'read', sessionID: 'ses_c' })+ expect(posts).toEqual([+ { event: 'permission.asked', sessionID: 'ses_1' },+ { event: 'question.asked', sessionID: 'ses_1' },+ { event: 'question.replied', sessionID: 'ses_1' }+ ])+ v2.end()+ })++ it('2.x: stays inert inside the shared background server (`serve --service`) — its env names another pane', async () => {+ const def = await loadV2()+ const v2 = v2Context()+ const argv = process.argv+ process.argv = ['bun', '/$bunfs/root/opencode', 'serve', '--service']+ try {+ await def.setup(v2.ctx)+ } finally {+ process.argv = argv+ }+ expect(v2.subscribed()).toBe(0)+ expect(v2.toolHooks).toEqual([])+ expect(g[LATCH]).toBeUndefined()+ })++ it('2.x: no NODETERM_NODE_ID (outside nodeterm) → no subscription, no hook', async () => {+ vi.stubEnv('NODETERM_NODE_ID', '')+ const def = await loadV2()+ const v2 = v2Context()+ await def.setup(v2.ctx)+ expect(v2.subscribed()).toBe(0)+ expect(v2.toolHooks).toEqual([])+ })++ it('2.x: a context without an event stream (a 1.x compatibility pass) is a no-op', async () => {+ const def = await loadV2()+ await def.setup({ options: {}, agent: {}, catalog: {} })+ await def.setup(undefined)+ expect(g[LATCH]).toBeUndefined()+ })++ it('both plugins in ONE process: 1.x armed first keeps 2.x inert (no double posts)', async () => {+ const v1 = await loadV1()+ const hooks = await v1.NodetermStatus()+ const def = await loadV2()+ const v2 = v2Context()+ await def.setup(v2.ctx)+ expect(v2.subscribed()).toBe(0)+ await hooks.event({ event: { type: 'session.idle', properties: { sessionID: 'ses_1' } } })+ expect(posts).toEqual([{ event: 'session.idle', sessionID: 'ses_1' }])+ })++ it('both plugins in ONE process: 2.x armed first keeps the 1.x hooks empty', async () => {+ const def = await loadV2()+ const v2 = v2Context()+ await def.setup(v2.ctx)+ const v1 = await loadV1()+ expect(await v1.NodetermStatus()).toEqual({})+ v2.end()+ })++ it('the latch is per API, not per call: a second plugin instance of the SAME API still arms', async () => {+ const v1 = await loadV1()+ expect(typeof (await v1.NodetermStatus()).event).toBe('function')+ expect(typeof (await v1.NodetermStatus()).event).toBe('function')+ const def = await loadV2()+ delete g[LATCH]+ const a = v2Context()+ const b = v2Context()+ await def.setup(a.ctx)+ await def.setup(b.ctx)+ expect(a.subscribed()).toBe(1)+ expect(b.subscribed()).toBe(1)+ a.end()+ b.end()+ })++ it('2.x: the cleanup setup returns aborts the subscription', async () => {+ const def = await loadV2()+ const v2 = v2Context()+ const cleanup = await def.setup(v2.ctx)+ expect(typeof cleanup).toBe('function')+ expect(v2.signal()?.aborted).toBe(false)+ ;(cleanup as () => void)()+ expect(v2.signal()?.aborted).toBe(true)+ v2.end()+ })+})diff --git a/src/core/agents/hooks/opencode.ts b/src/core/agents/hooks/opencode.tsindex faabd7c84..4b85faad6 100644--- a/src/core/agents/hooks/opencode.ts+++ b/src/core/agents/hooks/opencode.ts@@ -1,9 +1,20 @@// opencode hook service. Unlike claude/gemini (JSON settings merge) and codex (hooks.json +-// trust hash), opencode's hook seam is its PLUGIN system: a JS module in-// ~/.config/opencode/plugins/ whose exported hooks fire on session/tool/permission events.-// nodeterm owns one whole plugin file (marker-gated — a user's own file is never touched).-// opencode loads plugins on EVERY CLI command, so the plugin is env-gated: without the-// NODETERM_* env of a nodeterm-spawned session it returns {} and does nothing.+// trust hash), opencode's hook seam is its PLUGIN system: JS modules in+// ~/.config/opencode/plugins/ whose hooks fire on session/tool/permission events.+// nodeterm owns its plugin files outright (marker-gated — a user's own file is never touched).+// opencode loads plugins on EVERY CLI command, so the plugins are env-gated: without the+// NODETERM_* env of a nodeterm-spawned session they do nothing.+//+// TWO plugin APIs exist, and one file cannot serve both (issue #1136). MEASURED, 2026-10-16:+// - OpenCode 2.x (@opencode/cli 2.0.30) loads `plugins/*.js` AND plugin directories+// (`plugins/<name>/index.js`) and requires a DEFAULT export object `{ id, setup }`; a module+// without one is skipped with a WARN ("Plugin must export a default definition…"). A function+// default is refused too ("Expected object at [\"default\"]").+// - OpenCode 1.x loads only `{plugin,plugins}/*.{ts,js}` FILES, and up to 1.2.10 it calls EVERY+// export as a function: an object default throws `fn is not a function` and kills every opencode+// command on the machine, inside nodeterm or not (bisected: 1.2.10 crashes, 1.2.11 does not).+// So the V1 plugin stays a file with only the named export (V2 merely WARNs about it), and the V2+// plugin is a DIRECTORY, which no 1.x glob matches.import fs from 'fs'import os from 'os'import path from 'path'@@ -20,37 +31,41 @@ export function opencodeConfigDir(): string {: path.join(os.homedir(), '.config', 'opencode')}+/** The OpenCode 1.x plugin file. */export function pluginPath(): string {return path.join(opencodeConfigDir(), 'plugins', 'nodeterm-status.js')}-/** The managed plugin body. Mirrors the managed POSIX script's wire contract exactly- * (see managed-script.ts + hook-server.ts):- * - gate on NODETERM_NODE_ID (absent outside nodeterm-spawned sessions → no-op `{}`);+/** The OpenCode 2.x plugin DIRECTORY (see the header: a directory is invisible to every 1.x). */+export function v2PluginDir(): string {+ return path.join(opencodeConfigDir(), 'plugins', 'nodeterm-status-v2')+}++export function v2PluginPath(): string {+ return path.join(v2PluginDir(), 'index.js')+}++/** Which API armed in this process. Both plugins can end up loaded by one process (V2 loads the+ * V1 file too and only skips it because it has no default export; a future build with a V1+ * compatibility layer might run it). The first API to arm owns the process and the other stays+ * inert, so no build posts every event twice. Keyed by API, not by call: one process may arm the+ * same API more than once (one plugin instance per project directory). */+const LATCH = "Symbol.for('nodeterm.opencode.status.api')"++/** The shared poster, embedded verbatim in both plugins. Mirrors the managed POSIX script's wire+ * contract exactly (see managed-script.ts + hook-server.ts):+ * - gate on NODETERM_NODE_ID (absent outside nodeterm-spawned sessions → no poster);* - per POST, re-read the NODETERM_HOOK_ENDPOINT FILE (KEY=VALUE lines) for the LIVE* port/token — tmux sessions outlive the app, so env-baked coords go stale after a* restart (the restart handoff); fall back to the env vars;* - POST application/x-www-form-urlencoded `nodeId` + `version` + `payload` (JSON) with* the x-nodeterm-hook-token header to http://127.0.0.1:<port>/hook/opencode.- * Bus events (session.created/idle/error, message.updated, permission.updated/replied)- * reach a plugin ONLY through the `event` catch-all hook as { event: { type, properties } }- * — opencode never calls a hook keyed by the event name itself, so per-event-name exports- * are dead code (the bug that made every status silently missing). `tool.execute.before`- * is the exception: it IS a real named plugin hook. The event NAME posted is the contract- * with normalizeOpencode (permission.updated is posted as `permission.asked`);- * sessionID/role are extracted defensively per the SDK payload shapes. message.updated- * forwards ONLY user messages (turn start) so assistant token streaming never floods the- * hook server — and only ONCE per messageID: measured on 1.18.3 (TUI), the user message- * record is updated again after session.idle (title/bookkeeping), and re-forwarding that- * as a turn start resurrected `working` right after `done` (newTurn bypasses the- * done-holdoff by design), pinning the node on RUNNING forever.* Transport: an SSH host advertises a UNIX SOCKET (NODETERM_HOOK_SOCK, no PORT line in the* endpoint file) — the socket wins over TCP, like the POSIX script's `curl --unix-socket`* branch. opencode runs on Bun, whose fetch takes a `unix` option; the node:http* socketPath fallback covers any non-Bun runtime (and is what the tests exercise). */-export function buildOpencodePlugin(): string {- return `${PLUGIN_MARKER}-import fs from 'node:fs'+function sharedPrelude(): string {+ return `import fs from 'node:fs'import http from 'node:http'// The SAME quote-aware parser every TS consumer of the endpoint file uses, embedded verbatim@@ -59,9 +74,18 @@ import http from 'node:http'// which the hook server's constant-time bearer check rejects on every POST.const parseEndpointEnv = ${parseEndpointEnv.toString()}-export const NodetermStatus = async () => {+const LATCH = ${LATCH}+// true when this API may arm: nothing armed yet, or this same API armed first.+const claim = (api) => {+ const owner = globalThis[LATCH]+ if (owner && owner !== api) return false+ globalThis[LATCH] = api+ return true+}++const makePoster = () => {const nodeId = process.env.NODETERM_NODE_ID- if (!nodeId) return {}+ if (!nodeId) return nullconst live = () => {const conf = {port: process.env.NODETERM_HOOK_PORT,@@ -96,7 +120,7 @@ export const NodetermStatus = async () => {return ''}}- const post = (event, extra) => {+ return (event, extra) => {try {const { port, sock, token, version, tokenDir } = live()if (!token || (!sock && !port)) return@@ -124,6 +148,33 @@ export const NodetermStatus = async () => {}} catch {}}+}+`+}++/** The OpenCode 1.x plugin: ONLY the named export — never a default (see the header).+ * Bus events (session.created/idle/error, message.updated, permission.updated/replied)+ * reach a plugin ONLY through the `event` catch-all hook as { event: { type, properties } }+ * — opencode never calls a hook keyed by the event name itself, so per-event-name exports+ * are dead code (the bug that made every status silently missing). `tool.execute.before`+ * is the exception: it IS a real named plugin hook. The event NAME posted is the contract+ * with normalizeOpencode (permission.updated is posted as `permission.asked`);+ * sessionID/role are extracted defensively per the SDK payload shapes. message.updated+ * forwards ONLY user messages (turn start) so assistant token streaming never floods the+ * hook server — and only ONCE per messageID: measured on 1.18.3 (TUI), the user message+ * record is updated again after session.idle (title/bookkeeping), and re-forwarding that+ * as a turn start resurrected `working` right after `done` (newTurn bypasses the+ * done-holdoff by design), pinning the node on RUNNING forever. */+export function buildOpencodePlugin(): string {+ return `${PLUGIN_MARKER}+// OpenCode 1.x plugin. OpenCode 2.x logs "failed to load plugin … must export a default+// definition" for this file at every start: expected and harmless — 2.x is served by the+// nodeterm-status-v2/ directory beside it. A default export here would crash opencode <= 1.2.10.+${sharedPrelude()}+export const NodetermStatus = async () => {+ const post = makePoster()+ if (!post) return {}+ if (!claim('v1')) return {}const seenUserMsgs = new Set()return {event: async (input) => {@@ -167,23 +218,145 @@ export const NodetermStatus = async () => {`}-export function installOpencodeHooks(): void {- const p = pluginPath()+/** The OpenCode 2.x plugin: a default `{ id, setup }` (the only shape 2.x accepts). MEASURED on+ * @opencode/cli 2.0.30 (TUI and `run`, both `--standalone`):+ * - `setup(ctx)` runs in the SERVER process; `ctx.event.subscribe()` is an async iterable of+ * `{ id, created, type, location, data }`; `ctx.tool.hook('execute.before', cb)` hands cb+ * `{ tool, sessionID, … }` and fires BEFORE that call's permission.asked;+ * - a turn is `session.execution.started` … `session.execution.succeeded | failed | interrupted`+ * (Esc) — there is no `session.idle` any more; questions are forms (`form.created` carries the+ * session under `data.form`, `form.replied|cancelled` under `data`);+ * - `session.created` carries `parentID` for a subagent's child session.+ * Every event is translated to the 1.x wire names above, so normalizeOpencode has one dialect:+ * execution.started → message.updated (user), succeeded|interrupted → session.idle, failed →+ * session.error, form.* → question.*.+ * THE SHARED SERVER: by default every 2.x CLI talks to ONE background server (`serve --service`)+ * that keeps the environment of whichever pane started it and outlives it (MEASURED: a second+ * pane's events ran under the first pane's NODETERM_NODE_ID). Posting from there would paint one+ * node's status on another, so the plugin refuses to run in it. Only a `--standalone` server (the+ * pane's own child, `serve --stdio`, which inherits the pane's env) reports. */+export function buildOpencodeV2Plugin(): string {+ return `${PLUGIN_MARKER}+// OpenCode 2.x plugin (a directory, so that no OpenCode 1.x ever loads it).+${sharedPrelude()}+// A subagent runs in a CHILD session (session.created carries parentID). Its turn boundaries are+// not the node's — a child's execution.started would re-key the node to the child's session and+// its succeeded would read as the node going idle mid-turn — but a child's permission or form+// DOES block the node's work, so those are forwarded under the root session id.+const translate = (post, children) => {+ const root = (id) => {+ let cur = id+ for (let i = 0; i < 16 && cur && children.has(cur); i++) cur = children.get(cur)+ return cur+ }+ return (ev) => {+ if (!ev || typeof ev.type !== 'string') return+ const d = ev.data || {}+ const sid = typeof d.sessionID === 'string' ? d.sessionID : undefined+ switch (ev.type) {+ case 'session.created':+ if (sid && typeof d.parentID === 'string' && d.parentID) {+ children.set(sid, d.parentID)+ if (children.size > 500) {+ for (const first of children.keys()) { children.delete(first); break }+ }+ return+ }+ return post('session.created', { sessionID: sid })+ case 'session.execution.started':+ if (sid && children.has(sid)) return+ return post('message.updated', { sessionID: sid, role: 'user' })+ case 'session.execution.succeeded':+ case 'session.execution.interrupted':+ if (sid && children.has(sid)) return+ return post('session.idle', { sessionID: sid })+ case 'session.execution.failed':+ if (sid && children.has(sid)) return+ return post('session.error', { sessionID: sid })+ case 'permission.asked':+ case 'permission.replied':+ return post(ev.type, { sessionID: root(sid) })+ case 'form.created': {+ const f = d.form || {}+ return post('question.asked', { sessionID: root(typeof f.sessionID === 'string' ? f.sessionID : sid) })+ }+ case 'form.replied':+ return post('question.replied', { sessionID: root(sid) })+ case 'form.cancelled':+ return post('question.rejected', { sessionID: root(sid) })+ }+ }+}++export default {+ id: 'nodeterm-status',+ async setup(ctx) {+ if (!ctx || !ctx.event || typeof ctx.event.subscribe !== 'function') return+ // The shared background server's env belongs to whichever pane started it (see above).+ const argv = (typeof process !== 'undefined' && process.argv) || []+ if (argv.includes('--service')) return+ const post = makePoster()+ if (!post) return+ if (!claim('v2')) return+ const children = new Map()+ const onEvent = translate(post, children)+ const controller = new AbortController()+ ;(async () => {+ for await (const ev of ctx.event.subscribe({ signal: controller.signal })) {+ try { onEvent(ev) } catch {}+ }+ })().catch(() => {})+ try {+ if (ctx.tool && typeof ctx.tool.hook === 'function') {+ // A throw here would FAIL the tool call (execute.before may reject one) — never throw.+ await ctx.tool.hook('execute.before', (input) => {+ try {+ const sid = input && input.sessionID+ if (sid && children.has(sid)) return+ post('tool.execute.before', { sessionID: sid })+ } catch {}+ })+ }+ } catch {}+ return () => controller.abort()+ }+}+`+}++/** Write `body` to `file` unless a file WITHOUT our marker is there (a user's own — never touched). */+function plantManaged(file: string, body: string): void {try {- const existing = fs.readFileSync(p, 'utf8')- if (!existing.startsWith(PLUGIN_MARKER)) return // a user's own file — never touch it+ const existing = fs.readFileSync(file, 'utf8')+ if (!existing.startsWith(PLUGIN_MARKER)) return+ if (existing === body) return} catch {/* absent — plant it */}- fs.mkdirSync(path.dirname(p), { recursive: true })- fs.writeFileSync(p, buildOpencodePlugin(), 'utf8')+ fs.mkdirSync(path.dirname(file), { recursive: true })+ fs.writeFileSync(file, body, 'utf8')}-export function removeOpencodeHooks(): void {- const p = pluginPath()+export function installOpencodeHooks(): void {+ plantManaged(pluginPath(), buildOpencodePlugin())+ plantManaged(v2PluginPath(), buildOpencodeV2Plugin())+}++function removeManaged(file: string): void {try {- if (fs.readFileSync(p, 'utf8').startsWith(PLUGIN_MARKER)) fs.rmSync(p, { force: true })+ if (fs.readFileSync(file, 'utf8').startsWith(PLUGIN_MARKER)) fs.rmSync(file, { force: true })} catch {/* absent — nothing to remove */}}++export function removeOpencodeHooks(): void {+ removeManaged(pluginPath())+ removeManaged(v2PluginPath())+ // The directory is ours by name; drop it only when nothing of anyone else's is left in it.+ try {+ fs.rmdirSync(v2PluginDir())+ } catch {+ /* absent, or not empty — leave it */+ }+}