Skip to content

Reason Network: your team's coding agents, talking to each other. The engine behind `reason network`.

Load the opencode plugin on opencode 2.x, and deliver each message once

Lars Talian9881169ace95
diff --git a/DESIGN.md b/DESIGN.md
index 4688a51..73b4f8c 100644
--- a/DESIGN.md
+++ b/DESIGN.md
@@ -162,7 +162,7 @@ The hard part. Each session advertises a **delivery tier** so senders know when
|---|---|---|
| Claude Code | push | MCP child posts to the session's own inbox socket (`CLAUDE_CODE_MESSAGING_SOCKET`, `{"type":"user",…}` frame): delivered between tool calls, starts a turn if idle. Fallbacks: `asyncRewake` hook (documented idle wake), channels (`notifications/claude/channel`, needs a dev flag until allowlisted). |
| Codex | push | `codex queue --thread <id>` / app-server `turn/start` (default daemon mode). Mid-turn: `PostToolUse` `additionalContext`. Stop: `decision:block`. Hooks need one-time approval in `/hooks`. |
-| opencode | push | Plugin: `client.session.promptAsync` (V1), `POST /api/session/:id/prompt` via `service.json` (V2). |
+| opencode | push | Plugin (one file for 1.x and 2.x): `client.session.promptAsync` (1.x), `ctx.session.prompt` (2.x, where busy/idle come from `session.execution.*` events). |
| pi | push | Extension (`~/.pi/agent/extensions/reason-network.ts`): registers the MCP server per session (`deferred`, with `REASON_NETWORK_SESSION`), `sendUserMessage` (`deliverAs: "steer"` mid-run, a new turn when idle), busy/idle from `agent_start`/`agent_settled`, the session name as `doing`. |
| Reason | push | Its agent runs in Reason's cloud: the daemon lists live sessions (`reason session list --json`, when `reason = true`) and sends with `reason session send`. Replies go through the CLI: `reason-network send <to> --from <its address>`. |
| Amp | push | Plugin: `thread.appendUserMessage(…, {steer:true})`. |
@@ -195,7 +195,7 @@ Agents never report what they are doing; Reason Network reads it from what they
session's title (Claude Code's `ai-title` transcript entries, Codex's thread names in
`~/.codex/session_index.jsonl`, opencode's session title) and the task in progress on its own todo list
(Claude Code's `~/.claude/tasks/<session>/`, TodoWrite, Codex's `update_plan`, Gemini's `write_todos`,
-Cursor's `todo_write`, opencode's todos). Transcripts come from hooks (`transcript_path`) or, for Claude Code,
+Cursor's `todo_write`, opencode 1.x's todos). Transcripts come from hooks (`transcript_path`) or, for Claude Code,
from its session id; only what was appended since the last look is read. A Claude Code session renamed with
`/rename` keeps that name on Reason Network.
diff --git a/src/daemon/sessions.rs b/src/daemon/sessions.rs
index 1aeea67..ea1d549 100644
--- a/src/daemon/sessions.rs
+++ b/src/daemon/sessions.rs
@@ -4,7 +4,7 @@
use super::{Daemon, Inner, Live, log};
use crate::{agent, git::GitInfo, proto::*, render, store::Remembered, util};
use anyhow::{Result, anyhow, bail};
-use std::{collections::HashSet, sync::Arc};
+use std::{collections::HashSet, sync::Arc, time::Instant};
/// A hook-only session that hasn't fired a hook for this long is considered gone.
const HOOK_TTL_MS: i64 = 6 * 3_600_000;
@@ -209,8 +209,12 @@ impl Daemon {
} else {
Vec::new()
};
- // Not marked read here: the hook confirms with `Delivered` once it has printed them.
+ // Not marked read here: the hook confirms with `Delivered` once it has printed them. Until then they are in
+ // flight, so a hook asking at the same moment (opencode 2.x can run two plugin instances) doesn't get them too.
let ids: Vec<String> = msgs.iter().map(|m| m.id.clone()).collect();
+ for id in &ids {
+ g.in_flight.insert(id.clone(), Instant::now());
+ }
let text = (!msgs.is_empty()).then(|| render::for_agent(&msgs, Some(&agent_kind), false));
Ok(HookReply { address: Some(address), text, ids })
}
diff --git a/src/opencode-plugin.ts b/src/opencode-plugin.ts
index e3b1bde..6d66075 100644
--- a/src/opencode-plugin.ts
+++ b/src/opencode-plugin.ts
@@ -1,6 +1,6 @@
// reason network for opencode: written by `reason network setup`, removed by `reason uninstall`.
// Reports each session's busy/idle state and what it is doing (its title and todo in progress) to reason network, and
-// delivers teammates' messages into idle sessions.
+// delivers teammates' messages into idle sessions, on opencode 1.x and 2.x.
import type { Plugin } from "@opencode-ai/plugin"
import { execFile } from "node:child_process"
@@ -11,66 +11,120 @@ const run = (args: string[], cwd: string) =>
execFile(ENGINE, args, { cwd, timeout: 10_000 }, (err, out) => resolve(err ? "" : String(out).trim())),
)
-export const ReasonNetwork: Plugin = async ({ client, directory }) => {
+// What both plugin formats share; `prompt` puts a teammate's message into a session.
+const network = (prompt: (id: string, text: string) => Promise<unknown>) => {
const idle = new Set<string>()
const subagents = new Set<string>()
const delivering = new Set<string>()
- const last = new Map<string, { agent?: string; model?: { providerID: string; modelID: string } }>()
+ const dirs = new Map<string, string>()
const titles = new Map<string, string>()
const tasks = new Map<string, string>()
const doing = (id: string) => {
const line = [titles.get(id), tasks.get(id)].filter(Boolean).join(" · ")
- void run(["hook", "opencode", "doing", "--session", id, "--doing", line], directory)
+ void run(["hook", "opencode", "doing", "--session", id, "--doing", line], dirs.get(id)!)
}
const deliver = async (id: string) => {
if (delivering.has(id) || subagents.has(id)) return
delivering.add(id)
try {
- const text = await run(["hook", "opencode", "poll", "--session", id], directory)
+ const text = await run(["hook", "opencode", "poll", "--session", id], dirs.get(id)!)
if (!text) return
idle.delete(id)
- await client.session.promptAsync({ path: { id }, body: { ...(last.get(id) ?? {}), parts: [{ type: "text", text }] } })
+ await prompt(id, text)
} finally {
delivering.delete(id)
}
}
const timer = setInterval(() => idle.forEach((id) => void deliver(id)), 5_000)
+ return {
+ subagent: (id: string) => subagents.add(id),
+ title: (id: string, title: string, dir: string) => {
+ // Until opencode names it, a session is "New session - <date>".
+ if (title.startsWith("New session") || titles.get(id) === title || subagents.has(id)) return
+ dirs.set(id, dir)
+ titles.set(id, title)
+ doing(id)
+ },
+ todo: (id: string, now: string, dir: string) => {
+ if (tasks.get(id) === now || subagents.has(id)) return
+ dirs.set(id, dir)
+ tasks.set(id, now)
+ doing(id)
+ },
+ status: async (id: string, state: string, dir: string) => {
+ if (subagents.has(id)) return
+ dirs.set(id, dir)
+ void run(["hook", "opencode", "status", "--session", id, "--state", state], dir)
+ if (state === "idle") {
+ idle.add(id)
+ await deliver(id)
+ } else idle.delete(id)
+ },
+ stop: () => clearInterval(timer),
+ }
+}
+
+const ReasonNetwork: Plugin = async ({ client, directory }) => {
+ const last = new Map<string, { agent?: string; model?: { providerID: string; modelID: string } }>()
+ const net = network((id, text) =>
+ client.session.promptAsync({ path: { id }, body: { ...(last.get(id) ?? {}), parts: [{ type: "text", text }] } }),
+ )
+
return {
event: async ({ event }) => {
const e = event as any
- if (e.type === "session.created" && e.properties?.info?.parentID) subagents.add(e.properties.info.id)
+ if (e.type === "session.created" && e.properties?.info?.parentID) net.subagent(e.properties.info.id)
if (e.type === "message.updated" && e.properties?.info?.role === "user") {
const m = e.properties.info
last.set(m.sessionID, { agent: m.agent, model: m.model })
}
if (e.type === "session.updated") {
const { id, title } = e.properties?.info ?? {}
- // Until opencode names it, a session is "New session - <date>".
- if (id && title && !title.startsWith("New session") && titles.get(id) !== title && !subagents.has(id)) {
- titles.set(id, title)
- doing(id)
- }
+ if (id && title) net.title(id, title, directory)
}
if (e.type === "todo.updated") {
const { sessionID, todos } = e.properties ?? {}
const now = (todos ?? []).find((t: any) => t.status === "in_progress")?.content ?? ""
- if (sessionID && tasks.get(sessionID) !== now && !subagents.has(sessionID)) {
- tasks.set(sessionID, now)
- doing(sessionID)
- }
- }
- if (e.type === "session.status") {
- const { sessionID, status } = e.properties
- if (subagents.has(sessionID)) return
- void run(["hook", "opencode", "status", "--session", sessionID, "--state", status.type], directory)
- if (status.type === "idle") {
- idle.add(sessionID)
- await deliver(sessionID)
- } else idle.delete(sessionID)
+ if (sessionID) net.todo(sessionID, now, directory)
}
+ if (e.type === "session.status") await net.status(e.properties.sessionID, e.properties.status.type, directory)
},
- dispose: async () => clearInterval(timer),
+ dispose: async () => net.stop(),
}
}
+
+// opencode 2.x has no todo events, and a session's busy and idle come as its execution starting and ending (it
+// doesn't send session.status).
+const STATE: Record<string, string> = {
+ "session.execution.started": "busy",
+ "session.execution.succeeded": "idle",
+ "session.execution.failed": "idle",
+ "session.execution.interrupted": "idle",
+}
+
+// opencode 1.x calls `server`, 2.x calls `setup`.
+export default {
+ id: "reason-network",
+ server: ReasonNetwork,
+ setup: (ctx: any) => {
+ // 1.x calls this too, with a context that has no events; it runs `server` instead.
+ if (!ctx.event) return
+ const abort = new AbortController()
+ const net = network((sessionID, text) => ctx.session.prompt({ sessionID, text }))
+ void (async () => {
+ for await (const e of ctx.event.subscribe({ signal: abort.signal })) {
+ const d = e.data ?? {}
+ const dir = e.location?.directory ?? ctx.location.directory
+ if (e.type === "session.created" && d.parentID) net.subagent(d.sessionID)
+ if (e.type === "session.renamed") net.title(d.sessionID, d.title, dir)
+ if (STATE[e.type]) void net.status(d.sessionID, STATE[e.type], dir)
+ }
+ })().catch(() => {})
+ return () => {
+ abort.abort()
+ net.stop()
+ }
+ },
+}