From be32435f5c15cfb6c46d0b4762a1f3471e0539d1 Mon Sep 17 00:00:00 2001 From: Gordon Breuer Date: Sat, 24 Oct 2026 15:03:11 +0200 Subject: [PATCH 1/2] Add managed OpenCode lifecycle plugin and native smoke coverage --- .github/workflows/dotnet-ci.yml | 2 + README.md | 3 +- docs/wiki/Agent-Integrations.md | 47 ++++++++++++++++++- scripts/opencode_smoke.mjs | 47 +++++++++++++++++++ scripts/opencode_smoke.py | 42 +++++++++++++++++ src/SidePulse.Cli/Agents.cs | 4 +- src/SidePulse.Cli/Program.cs | 2 +- src/SidePulse.Core/AgentEvents.cs | 19 +++++++- src/SidePulse.Core/HookConfiguration.cs | 3 +- src/SidePulse.Core/HookInstallation.cs | 10 ++-- src/SidePulse.Core/OpenCodePlugin.cs | 61 +++++++++++++++++++++++++ tests/SidePulse.Tests/AgentTests.cs | 47 +++++++++++++++++++ 12 files changed, 275 insertions(+), 12 deletions(-) create mode 100644 scripts/opencode_smoke.mjs create mode 100644 scripts/opencode_smoke.py create mode 100644 src/SidePulse.Core/OpenCodePlugin.cs diff --git a/.github/workflows/dotnet-ci.yml b/.github/workflows/dotnet-ci.yml index acdd635..58a3d0d 100644 --- a/.github/workflows/dotnet-ci.yml +++ b/.github/workflows/dotnet-ci.yml @@ -101,6 +101,8 @@ jobs: if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } python scripts/agent_smoke.py "src/SidePulse.Cli/bin/Release/net10.0/$binary" if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + python scripts/opencode_smoke.py "src/SidePulse.Cli/bin/Release/net10.0/$binary" + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - name: Publish and exercise self-contained previews shell: pwsh run: | diff --git a/README.md b/README.md index b825170..f485ead 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ an agent is working, waiting for input or finished. ## Preview functionality - Cursor menus, script-command review/copy/export, plain/quiet/JSON output. -- Copilot CLI, Codex, Claude Code and Kiro CLI V3 hooks with shared status aggregation. +- Copilot CLI, Codex, Claude Code, Kiro CLI V3 hooks and an OpenCode plugin with shared status aggregation. - Writable USB/SD LED output, iPhone linking and native protected credentials. - Dot/Pro animation simulation, custom editor, upstream patterns and state profiles. - Host lifecycle, bounded logs, diagnostics and phone aliases. @@ -99,6 +99,7 @@ sidepulse-net agents install codex sidepulse-net agents install claude sidepulse-net agents install kiro sidepulse-net agents install copilot +sidepulse-net agents install opencode sidepulse-net host start --phone default sidepulse-net host status sidepulse-net host stop diff --git a/docs/wiki/Agent-Integrations.md b/docs/wiki/Agent-Integrations.md index b5abc7e..091a237 100644 --- a/docs/wiki/Agent-Integrations.md +++ b/docs/wiki/Agent-Integrations.md @@ -1,7 +1,7 @@ # Agent integrations The preview supports Copilot CLI, current local Codex lifecycle hooks, Claude Code -and Kiro CLI V3 standalone hooks. They feed one current-user host and share the +Kiro CLI V3 standalone hooks and OpenCode local plugins. They feed one current-user host and share the same status reducer. Provider IDs namespace sessions, so equal session IDs from different tools cannot collide. `agents list --json` reports supported events and limitations. Unknown providers/events are not guessed from terminal text. @@ -15,6 +15,8 @@ sidepulse-net agents install copilot sidepulse-net agents install codex sidepulse-net agents install claude sidepulse-net agents install kiro +sidepulse-net agents install opencode --dry-run +sidepulse-net agents install opencode sidepulse-net agents status claude --json sidepulse-net agents uninstall claude --dry-run sidepulse-net agents uninstall claude @@ -31,6 +33,7 @@ scope unless duplicate events are intended. | Copilot CLI | `$COPILOT_HOME/hooks/sidepulse-net.json` or `~/.copilot/hooks/sidepulse-net.json` | Dedicated version-1 hook file; Bash and PowerShell wrappers | | Codex | `$CODEX_HOME/hooks.json` or `~/.codex/hooks.json` | Merge lifecycle groups into the hooks object | | Claude Code | `~/.claude/settings.json` | Merge lifecycle groups while preserving unrelated settings | +| OpenCode | `$OPENCODE_CONFIG_DIR/plugins/sidepulse-net.js` or `$XDG_CONFIG_HOME/opencode/plugins/sidepulse-net.js` (default `~/.config/opencode/plugins/sidepulse-net.js`) | Dedicated local JavaScript event plugin; no npm dependency | | Kiro CLI V3 | `~/.kiro/hooks/sidepulse-net.json` | Dedicated version-v1 standalone hook document | Installation is explicit. Dry runs show only the new managed fragment and target, @@ -46,6 +49,9 @@ restore a missing/modified backup. Review and merge those cases manually. A pending installation interrupted before its target write can be removed safely. Backups remain available after removal. Do not delete them before uninstalling. Malformed JSON, unsupported hook shapes and unowned dedicated files are refused. +OpenCode installs a JavaScript file instead of JSON; use +`--config .opencode/plugins/sidepulse-net.js` for project scope. It uses a directly +spawned executable on every platform, without Bash or PowerShell. The installer preserves permission settings and never approves tools, bypasses trust, or edits agent instructions. Restart the agent after installing/removing. Codex requires reviewing the new definitions in `/hooks` before they execute. @@ -79,6 +85,41 @@ use a PowerShell 7 encoded command to avoid parent-shell quoting ambiguities; Copilot includes its native PowerShell field. Unix uses quoted shell commands. These are passive status hooks: their output never contains policy decisions. +## OpenCode + +```shell +sidepulse-net agents install opencode +sidepulse-net host start --phone default +sidepulse-net agents status opencode --json +sidepulse-net agents uninstall opencode --dry-run +``` + +Restart OpenCode after installation. The plugin subscribes to native events: + +| Event | SidePulse state | +|---|---| +| `session.status` busy/retry | Working | +| `permission.asked`, `question.asked` | Waiting | +| Last pending permission/question replied or rejected | Working | +| `session.error` | Error | +| Session created/deleted or status idle | Idle | + +An error remains visible through a following idle event until activity resumes +or the session is deleted. Pending requests are tracked separately per session and request. Busy/retry events +and individual replies cannot clear another pending prompt. Child sessions keep +their own identity and cannot finish a parent. Idle may also follow cancellation, +so this adapter deliberately does not infer Done. A terminated OpenCode process +has no guaranteed shutdown event; use `host reset` to clear abandoned sessions. +Restarting the plugin does not reconstruct pending requests from earlier events. + +The plugin forwards only session identity and status, never prompt text, question +contents, permission rules or tool arguments. Child processes are silent, shell-free +and bounded to 1.5 seconds. A missing host or executable does not interrupt the agent. +It never answers a permission request or changes OpenCode configuration/trust policy. +Local plugin loading and event shapes are based on the official plugin reference +and upstream v1.2.27 session, permission and question schemas. Synthetic native CI +runs exercise the generated plugin; actual OpenCode/version acceptance remains required. + ## Validation and limits Tests cover representative documented payloads, each provider's configuration @@ -100,5 +141,9 @@ Checked 2026-10-23: - [Copilot hook reference](https://docs.github.com/en/copilot/reference/hooks-reference) - [Codex lifecycle hooks](https://developers.openai.com/codex/hooks) - [Claude Code hooks](https://code.claude.com/docs/en/hooks) +- [OpenCode plugins](https://opencode.ai/docs/plugins/) +- [OpenCode session status schema](https://github.com/anomalyco/opencode/blob/v1.2.27/packages/opencode/src/session/status.ts) +- [OpenCode permission events](https://github.com/anomalyco/opencode/blob/v1.2.27/packages/opencode/src/permission/service.ts) +- [OpenCode question events](https://github.com/anomalyco/opencode/blob/v1.2.27/packages/opencode/src/question/service.ts) - [Kiro standalone schema](https://kiro.dev/docs/hooks/) - [Kiro triggers and session identity](https://kiro.dev/docs/hooks/types/) diff --git a/scripts/opencode_smoke.mjs b/scripts/opencode_smoke.mjs new file mode 100644 index 0000000..10c7ff8 --- /dev/null +++ b/scripts/opencode_smoke.mjs @@ -0,0 +1,47 @@ +import { readFile } from 'node:fs/promises'; +import { execFileSync } from 'node:child_process'; +import assert from 'node:assert/strict'; +const [path, exe] = process.argv.slice(2); +const source = await readFile(path, 'utf8'); +const { SidePulsePlugin } = await import('data:text/javascript;base64,' + Buffer.from(source).toString('base64')); +const plugin = await SidePulsePlugin(); +const snapshot = () => JSON.parse(execFileSync(exe, ['host', 'status', '--json'], { encoding: 'utf8' })); +const send = (type, properties = {}) => plugin.event({ event: { type, properties: { sessionID: 'opencode-test', ...properties, prompt: 'DO-NOT-FORWARD' } } }); +async function expect(state) { + for (let i = 0; i < 30; i++) { + if (snapshot().State === state) return; + await new Promise(resolve => setTimeout(resolve, 50)); + } + assert.equal(snapshot().State, state); +} +await plugin.event({ event: { type: 'session.status', properties: { status: { type: 'busy' } } } }); +assert.equal(snapshot().Sessions.length, 0); +await send('session.created', { info: { id: 'opencode-test' } }); +await expect('Idle'); +await send('session.status', { status: { type: 'busy' } }); +await expect('Working'); +await send('permission.asked', { id: 'permission-1' }); +await expect('Waiting'); +await send('question.asked', { id: 'question-1' }); +await send('session.status', { status: { type: 'busy' } }); +await send('permission.replied', { requestID: 'permission-1' }); +await expect('Waiting'); +await send('question.rejected', { requestID: 'question-1' }); +await expect('Working'); +await send('session.error', { error: { message: 'DO-NOT-FORWARD' } }); +await expect('Error'); +await send('session.status', { status: { type: 'idle' } }); +await expect('Error'); +await send('session.status', { status: { type: 'retry' } }); +await expect('Working'); +await send('session.status', { sessionID: 'other-session', status: { type: 'busy' } }); +await send('session.deleted', { info: { id: 'opencode-test' } }); +await expect('Working'); +assert.equal(snapshot().Sessions.length, 2); +await send('session.status', { sessionID: 'other-session', status: { type: 'idle' } }); +await expect('Idle'); +await send('unrecognized', { status: { type: 'busy' } }); +await expect('Idle'); +// Host absence is silent, and does not reject the OpenCode event hook. +execFileSync(exe, ['host', 'stop', '--json']); +await send('session.status', { status: { type: 'busy' } }); diff --git a/scripts/opencode_smoke.py b/scripts/opencode_smoke.py new file mode 100644 index 0000000..8f962f6 --- /dev/null +++ b/scripts/opencode_smoke.py @@ -0,0 +1,42 @@ +"""Execute the generated OpenCode plugin against the real host, without an agent account.""" +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile + + +def main(): + exe = str(Path(sys.argv[1]).resolve()) + with tempfile.TemporaryDirectory(prefix="SidePulse OpenCode ü ") as directory: + root = Path(directory) + env = os.environ.copy() + env['SIDEPULSE_NET_HOME'] = str(root / 'state') + plugin = root / 'sidepulse-net.js' + + def run(*args): + result = subprocess.run([exe, *args], capture_output=True, text=True, env=env, timeout=20) + assert result.returncode == 0, (args, result.stdout, result.stderr) + return result.stdout + + preview = json.loads(run('agents', 'install', 'opencode', '--config', str(plugin), '--dry-run', '--json')) + assert not plugin.exists() + assert 'plugin' in preview['managedHooks'] + run('agents', 'install', 'opencode', '--config', str(plugin)) + assert json.loads(run('agents', 'status', 'opencode', '--config', str(plugin), '--json'))['State'] == 'installed' + run('host', 'start', '--exe', exe, '--dry-run', '--json') + try: + result = subprocess.run(['node', str(Path(__file__).with_name('opencode_smoke.mjs')), str(plugin), exe], + capture_output=True, text=True, env=env, timeout=45) + assert result.returncode == 0, (result.stdout, result.stderr) + assert 'DO-NOT-FORWARD' not in run('host', 'logs', '--tail', '100') + finally: + run('host', 'stop', '--json') + run('agents', 'uninstall', 'opencode', '--config', str(plugin)) + assert not plugin.exists() + print('OpenCode generated plugin, lifecycle, multiple prompts, isolation and removal passed.') + + +if __name__ == '__main__': + main() diff --git a/src/SidePulse.Cli/Agents.cs b/src/SidePulse.Cli/Agents.cs index 7c24192..b0c9c39 100644 --- a/src/SidePulse.Cli/Agents.cs +++ b/src/SidePulse.Cli/Agents.cs @@ -45,7 +45,9 @@ public string Target AgentProvider.Copilot => Path.Combine(Home("COPILOT_HOME", ".copilot"), "hooks", "sidepulse-net.json"), AgentProvider.Codex => Path.Combine(Home("CODEX_HOME", ".codex"), "hooks.json"), AgentProvider.Claude => Path.Combine(user, ".claude", "settings.json"), - _ => Path.Combine(user, ".kiro", "hooks", "sidepulse-net.json") + AgentProvider.Kiro => Path.Combine(user, ".kiro", "hooks", "sidepulse-net.json"), + AgentProvider.OpenCode => Path.Combine(Environment.GetEnvironmentVariable("OPENCODE_CONFIG_DIR") is { Length: > 0 } config ? config : Path.Combine(Home("XDG_CONFIG_HOME", ".config"), "opencode"), "plugins", "sidepulse-net.js"), + _ => throw new ArgumentException("Unknown agent.") }; } } diff --git a/src/SidePulse.Cli/Program.cs b/src/SidePulse.Cli/Program.cs index 8c698cb..30571c6 100644 --- a/src/SidePulse.Cli/Program.cs +++ b/src/SidePulse.Cli/Program.cs @@ -80,7 +80,7 @@ }); config.AddBranch("agents", agents => { - agents.SetDescription("Set up Copilot, Codex, Claude Code and Kiro lifecycle hooks."); + agents.SetDescription("Set up Copilot, Codex, Claude Code, Kiro and OpenCode lifecycle integrations."); agents.AddCommand("list"); agents.AddCommand("install"); agents.AddCommand("status"); diff --git a/src/SidePulse.Core/AgentEvents.cs b/src/SidePulse.Core/AgentEvents.cs index be1a3ba..5c0ab31 100644 --- a/src/SidePulse.Core/AgentEvents.cs +++ b/src/SidePulse.Core/AgentEvents.cs @@ -2,7 +2,7 @@ namespace SidePulse.Core; -public enum AgentProvider { Copilot, Codex, Claude, Kiro } +public enum AgentProvider { Copilot, Codex, Claude, Kiro, OpenCode } public sealed record AgentCapability(AgentProvider Provider, string Target, string[] Events, string Limitations); public static class AgentEvents @@ -12,7 +12,8 @@ public static class AgentEvents new(AgentProvider.Copilot, "Copilot CLI", ["sessionStart", "userPromptSubmitted", "preToolUse", "postToolUse", "agentStop", "errorOccurred", "postToolUseFailure", "sessionEnd", "notification"], "Notification waiting signals; no permission decision hooks."), new(AgentProvider.Codex, "Codex local lifecycle hooks", ["SessionStart", "UserPromptSubmit", "PreToolUse", "PostToolUse", "PermissionRequest", "Stop", "Interrupt", "SessionEnd"], "Review and trust installed hooks in Codex /hooks. Cloud orchestration is not supported."), new(AgentProvider.Claude, "Claude Code", ["SessionStart", "UserPromptSubmit", "PreToolUse", "PostToolUse", "PostToolUseFailure", "Notification", "Stop", "StopFailure", "SessionEnd"], "Notification waiting signals can be delayed. Subagent events are ignored."), - new(AgentProvider.Kiro, "Kiro CLI V3 standalone hooks", ["SessionStart", "UserPromptSubmit", "PreToolUse", "PostToolUse", "Stop", "SessionEnd"], "No documented general permission-wait or error signal. CLI 2.x profiles are not edited.") + new(AgentProvider.Kiro, "Kiro CLI V3 standalone hooks", ["SessionStart", "UserPromptSubmit", "PreToolUse", "PostToolUse", "Stop", "SessionEnd"], "No documented general permission-wait or error signal. CLI 2.x profiles are not edited."), + new(AgentProvider.OpenCode, "OpenCode local event plugin", ["session.status", "session.created", "session.deleted", "session.error", "permission.asked", "permission.replied", "question.asked", "question.replied", "question.rejected"], "Idle includes cancellation and is not reported as successful completion. Restart OpenCode after plugin changes.") ]; public static SessionEvent? Parse(AgentProvider provider, string name, string json, long? receivedAt = null) { @@ -33,6 +34,20 @@ public static class AgentEvents if (!string.IsNullOrEmpty(Get("agent_id"))) return null; if (!Capabilities.Single(c => c.Provider == provider).Events.Contains(name)) return null; if (name == "SessionStart" && Get("source") == "compact") return null; + if (provider == AgentProvider.OpenCode) + { + AgentState? mapped = name switch + { + "session.status" when Get("status") is "busy" or "retry" => AgentState.Working, + "session.status" when Get("status") == "idle" => AgentState.Idle, + "session.created" or "session.deleted" => AgentState.Idle, + "session.error" => AgentState.Error, + "permission.asked" or "question.asked" => AgentState.Waiting, + "permission.replied" or "question.replied" or "question.rejected" => AgentState.Working, + _ => null + }; + return mapped.HasValue ? new(session, mapped.Value, receivedAt ?? DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), provider) : null; + } var tool = Get("tool_name"); AgentState? state = name switch { diff --git a/src/SidePulse.Core/HookConfiguration.cs b/src/SidePulse.Core/HookConfiguration.cs index 0cf87e3..2670689 100644 --- a/src/SidePulse.Core/HookConfiguration.cs +++ b/src/SidePulse.Core/HookConfiguration.cs @@ -23,6 +23,7 @@ public static (string Bash, string PowerShell) Commands(string exe, AgentProvide } public static JsonObject Generate(AgentProvider provider, string exe, bool windows) { + if (provider == AgentProvider.OpenCode) return new JsonObject { ["plugin"] = OpenCodePlugin.Generate(exe) }; var events = AgentEvents.Capabilities.Single(c => c.Provider == provider).Events; var hooks = new JsonObject(); var kiro = new JsonArray(); @@ -61,7 +62,7 @@ public static JsonObject Generate(AgentProvider provider, string exe, bool windo } public static JsonObject Merge(AgentProvider provider, JsonObject? existing, JsonObject generated) { - if (provider is AgentProvider.Copilot or AgentProvider.Kiro) + if (provider is AgentProvider.Copilot or AgentProvider.Kiro or AgentProvider.OpenCode) { if (existing is not null) throw new IOException("The dedicated hook file already exists and is not owned by this installation."); return generated; diff --git a/src/SidePulse.Core/HookInstallation.cs b/src/SidePulse.Core/HookInstallation.cs index bc9d46f..a4becb7 100644 --- a/src/SidePulse.Core/HookInstallation.cs +++ b/src/SidePulse.Core/HookInstallation.cs @@ -40,9 +40,9 @@ public InstallationStatus Install(string path, AgentProvider provider, JsonObjec { var originalBytes = existingManifest.BeforeHash == "absent" ? null : existingManifest.Backup is { } backupPath ? Read(backupPath) : null; if (Hash(originalBytes) != existingManifest.BeforeHash) throw new IOException("The original backup is missing or modified. Review it before reinstalling."); - var originalSettings = originalBytes is null ? null : JsonNode.Parse(originalBytes)!.AsObject(); + var originalSettings = originalBytes is null ? null : provider == AgentProvider.OpenCode ? new JsonObject() : JsonNode.Parse(originalBytes)!.AsObject(); var requested = HookConfiguration.Merge(provider, originalSettings, generated); - if (Hash(Serialize(requested)) != existingManifest.InstalledHash) + if (Hash(Serialize(provider, requested)) != existingManifest.InstalledHash) throw new IOException("The requested hooks differ from the installed hooks. Uninstall before reinstalling with a different executable or configuration; no files were changed."); return status; } @@ -52,12 +52,12 @@ public InstallationStatus Install(string path, AgentProvider provider, JsonObjec JsonObject? original; try { - original = before is null ? null : JsonNode.Parse(before)?.AsObject(); + original = before is null ? null : provider == AgentProvider.OpenCode ? new JsonObject() : JsonNode.Parse(before)?.AsObject(); if (before is not null && original is null) throw new IOException("Existing configuration must be a JSON object."); } catch (Exception ex) when (ex is JsonException or InvalidOperationException) { throw new IOException("Existing configuration must be valid JSON. No files were changed."); } var merged = HookConfiguration.Merge(provider, original, generated); - var after = Serialize(merged); + var after = Serialize(provider, merged); if (dryRun) return new("preview", target, null); Directory.CreateDirectory(Path.GetDirectoryName(target)!); Directory.CreateDirectory(manifestDirectory); @@ -111,7 +111,7 @@ private static FileStream PrivateFile(string path, FileMode mode) if (!OperatingSystem.IsWindows()) options.UnixCreateMode = UnixFileMode.UserRead | UnixFileMode.UserWrite; return new FileStream(path, options); } - private static byte[] Serialize(JsonObject value) => System.Text.Encoding.UTF8.GetBytes(value.ToJsonString(new JsonSerializerOptions { WriteIndented = true }) + "\n"); + private static byte[] Serialize(AgentProvider provider, JsonObject value) => System.Text.Encoding.UTF8.GetBytes(provider == AgentProvider.OpenCode ? value["plugin"]!.GetValue() : value.ToJsonString(new JsonSerializerOptions { WriteIndented = true }) + "\n"); private static void AtomicWrite(string path, byte[] bytes) { var temporary = path + "." + Guid.NewGuid().ToString("N") + ".tmp"; diff --git a/src/SidePulse.Core/OpenCodePlugin.cs b/src/SidePulse.Core/OpenCodePlugin.cs new file mode 100644 index 0000000..13ce2e7 --- /dev/null +++ b/src/SidePulse.Core/OpenCodePlugin.cs @@ -0,0 +1,61 @@ +using System.Text.Json; + +namespace SidePulse.Core; + +public static class OpenCodePlugin +{ + public static string Generate(string executable) => """ + // Managed by SidePulse.NET. Uninstall before editing or moving the executable. + import { spawn } from "node:child_process"; + const executable = + """ + JsonSerializer.Serialize(executable) + ";\n" + """ + export const SidePulsePlugin = async () => { + const pending = new Map(); + const failed = new Set(); + let delivery = Promise.resolve(); + const supported = new Set(["session.status", "session.created", "session.deleted", "session.error", + "permission.asked", "permission.replied", "question.asked", "question.replied", "question.rejected"]); + const handle = async ({ event }) => { + try { + if (!supported.has(event?.type)) return; + const p = event.properties; + const id = p?.sessionID ?? p?.info?.id; + if (typeof id !== "string" || !id.trim() || id.length > 240) return; + const type = event.type; + const key = (type.startsWith("permission.") ? "p:" : "q:") + (p.requestID ?? p.id ?? "unknown"); + const waits = pending.get(id) ?? new Set(); + if (type.endsWith(".asked")) { waits.add(key); pending.set(id, waits); } + if (type.endsWith(".replied") || type === "question.rejected") { + waits.delete(key); + if (waits.size) return; + pending.delete(id); + } + const status = p.status?.type; + if (type === "session.status" && status === "idle" && failed.has(id)) return; + if (type === "session.error") failed.add(id); + if (type === "session.deleted" || (type === "session.status" && (status === "busy" || status === "retry"))) failed.delete(id); + if (type === "session.status" && waits.size && (status === "busy" || status === "retry")) return; + if (type === "session.deleted" || type === "session.error" || (type === "session.status" && status === "idle")) pending.delete(id); + // Forward only identity and status. Never send prompts, questions or tool arguments. + const payload = JSON.stringify({ session_id: id, status }); + await new Promise(resolve => { + let child; + let timer; + const finish = () => { clearTimeout(timer); resolve(); }; + child = spawn(executable, ["hook", type, "--source", "opencode"], + { shell: false, windowsHide: true, stdio: ["pipe", "ignore", "ignore"] }); + timer = setTimeout(() => { child.kill(); finish(); }, 1500); + child.on("error", finish); + child.on("close", finish); + child.stdin.on("error", () => {}); + child.stdin.end(payload); + }); + } catch { /* Passive integration: never interrupt OpenCode. */ } + }; + return { event: input => { + delivery = delivery.then(() => handle(input)).catch(() => {}); + return delivery; + } }; + }; + """ + "\n"; +} diff --git a/tests/SidePulse.Tests/AgentTests.cs b/tests/SidePulse.Tests/AgentTests.cs index 25baef5..d6956d2 100644 --- a/tests/SidePulse.Tests/AgentTests.cs +++ b/tests/SidePulse.Tests/AgentTests.cs @@ -55,6 +55,11 @@ public void GeneratedSchemasContainSilentWrappersAndNoPolicyDecisions() var json = generated.ToJsonString(); Assert.DoesNotContain("permissionDecision", json); Assert.DoesNotContain("dangerously", json); + if (provider == AgentProvider.OpenCode) + { + Assert.Contains("shell: false", generated["plugin"]!.GetValue()); + continue; + } if (provider == AgentProvider.Kiro) { Assert.Equal("v1", generated["version"]!.GetValue()); @@ -153,6 +158,48 @@ public void DedicatedFilesAreRemovedButUnownedFilesAreNeverReplaced() Assert.Throws(() => installer.Install(target, AgentProvider.Kiro, fragment, false)); }); } + [Theory] + [InlineData("session.status", "busy", AgentState.Working)] + [InlineData("session.status", "retry", AgentState.Working)] + [InlineData("session.status", "idle", AgentState.Idle)] + [InlineData("permission.asked", "", AgentState.Waiting)] + [InlineData("question.asked", "", AgentState.Waiting)] + [InlineData("question.rejected", "", AgentState.Working)] + [InlineData("session.error", "", AgentState.Error)] + [InlineData("session.deleted", "", AgentState.Idle)] + public void OpenCodeMapsSanitizedEvents(string name, string status, AgentState state) + { + var payload = new JsonObject { ["session_id"] = "open", ["status"] = status }.ToJsonString(); + var item = AgentEvents.Parse(AgentProvider.OpenCode, name, payload, 42)!; + Assert.Equal(state, item.State); + Assert.Equal(AgentProvider.OpenCode, item.Provider); + Assert.Equal(42, item.Timestamp); + Assert.Null(AgentEvents.Parse(AgentProvider.OpenCode, "session.status", "{\"session_id\":\"open\",\"status\":\"unknown\"}")); + } + [Fact] + public void OpenCodeOwnsOnlyItsPluginAndRefusesModifiedOrUnownedFiles() + { + WithDirectory(directory => + { + var target = Path.Combine(directory, "sidepulse-net.js"); + var installer = new HookInstallation(Path.Combine(directory, "manifests")); + var generated = HookConfiguration.Generate(AgentProvider.OpenCode, "C:\\O'Brien ü\\sidepulse-net.exe", true); + Assert.Equal("preview", installer.Install(target, AgentProvider.OpenCode, generated, true).State); + Assert.False(File.Exists(target)); + installer.Install(target, AgentProvider.OpenCode, generated, false); + Assert.Equal(generated["plugin"]!.GetValue(), File.ReadAllText(target)); + Assert.Equal("installed", installer.Install(target, AgentProvider.OpenCode, generated, false).State); + Assert.Throws(() => installer.Install(target, AgentProvider.OpenCode, HookConfiguration.Generate(AgentProvider.OpenCode, "/new/sidepulse-net", false), false)); + File.AppendAllText(target, "// manual edit"); + Assert.Throws(() => installer.Uninstall(target, false)); + File.WriteAllText(target, generated["plugin"]!.GetValue()); + installer.Uninstall(target, false); + Assert.False(File.Exists(target)); + File.WriteAllText(target, "// user plugin"); + Assert.Throws(() => installer.Install(target, AgentProvider.OpenCode, generated, false)); + Assert.Equal("// user plugin", File.ReadAllText(target)); + }); + } private static void WithDirectory(Action action) { var directory = Path.Combine(Path.GetTempPath(), "sidepulse-agent-test-" + Guid.NewGuid()); From eacfc4282a523b4fbc26f5573bae581cb358c158 Mon Sep 17 00:00:00 2001 From: Gordon Breuer Date: Sat, 24 Oct 2026 15:05:24 +0200 Subject: [PATCH 2/2] Clear OpenCode error latch when user-input activity resumes --- scripts/opencode_smoke.mjs | 12 ++++++++++-- src/SidePulse.Core/OpenCodePlugin.cs | 1 + 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/scripts/opencode_smoke.mjs b/scripts/opencode_smoke.mjs index 10c7ff8..86fe128 100644 --- a/scripts/opencode_smoke.mjs +++ b/scripts/opencode_smoke.mjs @@ -16,7 +16,7 @@ async function expect(state) { } await plugin.event({ event: { type: 'session.status', properties: { status: { type: 'busy' } } } }); assert.equal(snapshot().Sessions.length, 0); -await send('session.created', { info: { id: 'opencode-test' } }); +await plugin.event({ event: { type: 'session.created', properties: { info: { id: 'opencode-test' } } } }); await expect('Idle'); await send('session.status', { status: { type: 'busy' } }); await expect('Working'); @@ -35,11 +35,19 @@ await expect('Error'); await send('session.status', { status: { type: 'retry' } }); await expect('Working'); await send('session.status', { sessionID: 'other-session', status: { type: 'busy' } }); -await send('session.deleted', { info: { id: 'opencode-test' } }); +await plugin.event({ event: { type: 'session.deleted', properties: { info: { id: 'opencode-test' } } } }); await expect('Working'); assert.equal(snapshot().Sessions.length, 2); await send('session.status', { sessionID: 'other-session', status: { type: 'idle' } }); await expect('Idle'); +await send('session.error'); +await expect('Error'); +await send('question.asked', { id: 'recovery-question' }); +await expect('Waiting'); +await send('question.replied', { requestID: 'recovery-question' }); +await expect('Working'); +await send('session.status', { status: { type: 'idle' } }); +await expect('Idle'); await send('unrecognized', { status: { type: 'busy' } }); await expect('Idle'); // Host absence is silent, and does not reject the OpenCode event hook. diff --git a/src/SidePulse.Core/OpenCodePlugin.cs b/src/SidePulse.Core/OpenCodePlugin.cs index 13ce2e7..389d48f 100644 --- a/src/SidePulse.Core/OpenCodePlugin.cs +++ b/src/SidePulse.Core/OpenCodePlugin.cs @@ -24,6 +24,7 @@ public static string Generate(string executable) => """ const type = event.type; const key = (type.startsWith("permission.") ? "p:" : "q:") + (p.requestID ?? p.id ?? "unknown"); const waits = pending.get(id) ?? new Set(); + if (type.endsWith(".asked") || type.endsWith(".replied") || type === "question.rejected") failed.delete(id); if (type.endsWith(".asked")) { waits.add(key); pending.set(id, waits); } if (type.endsWith(".replied") || type === "question.rejected") { waits.delete(key);