openmsg 0.4.6 → 0.4.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -35,7 +35,7 @@ An address is `<vendor>:<name>`, for example `claude:api-worker`.
35
35
  |---|---|---|
36
36
  | Claude Code | The inbox socket of the session | Works, tested live |
37
37
  | Codex | `codex queue` on the shared app-server daemon | Works, tested live |
38
- | OpenCode | `POST /session/{id}/prompt_async` on its local server | Delivery tested live. A reply needs a model account |
38
+ | OpenCode | 2.x: `POST /api/session/{id}/prompt` on the shared service, with the password from `~/.local/state/opencode/service.json`. 1.x: `POST /session/{id}/prompt_async` | Works both ways, tested live with 2.2.6 |
39
39
  | Cursor CLI | A hook reads the mailbox at the end of each turn | Written, tested with fixtures. A live test needs `CURSOR_API_KEY` |
40
40
  | Gemini CLI | The same hook, as an AfterAgent deny | Written, tested with fixtures. Gemini CLI is not installed here |
41
41
  | Other agents | `tmux send-keys` | Not started |
@@ -137,6 +137,37 @@ for a message to a directory:
137
137
  openmsg install --hooks
138
138
  ```
139
139
 
140
+ ## Troubleshooting
141
+
142
+ ### `EPERM: operation not permitted` on macOS
143
+
144
+ The symptoms:
145
+
146
+ - `openmsg list` or `openmsg send` stops with `EPERM: operation not permitted, open '.../src/cli.mjs'`.
147
+ - Codex shows `Hook failed: hook exited with code 126`.
148
+
149
+ The cause: macOS protects `~/Desktop`, `~/Documents`, and `~/Downloads`. A
150
+ program in a terminal gets access to these folders through the terminal app.
151
+ When the terminal app loses this access, every agent in that terminal loses it
152
+ too. An update of the terminal app can cause this. On 2026-10-22, an update of
153
+ Cursor caused it on one Mac. The sandbox of the agent is not the cause.
154
+
155
+ To find the process that macOS blocks:
156
+
157
+ ```
158
+ log show --last 10m --predicate 'eventMessage CONTAINS "System Policy"' | grep deny
159
+ ```
160
+
161
+ To correct the fault:
162
+
163
+ 1. Open System Settings > Privacy & Security > Full Disk Access.
164
+ 2. Remove the terminal app (Cursor, VS Code, iTerm, or Terminal), then add it again.
165
+ 3. Quit the terminal app, then open it again. A running app keeps the old state.
166
+
167
+ Until you do this, an agent in that terminal still receives a message, because
168
+ the entry point of each vendor is outside these folders. The agent cannot send
169
+ a message.
170
+
140
171
  ## How each vendor lets a message in
141
172
 
142
173
  [`research/2026-09-19-transport-research.md`](https://github.com/marciob/openmsg/blob/main/research/2026-09-19-transport-research.md)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "openmsg",
3
- "version": "0.4.6",
3
+ "version": "0.4.7",
4
4
  "description": "Messages between AI coding agents of different vendors, on one machine or between two people, sealed end to end.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -12,6 +12,7 @@
12
12
  // Source: packages/opencode/src/cli/cmd/tui/routes/session/index.tsx (v1.1.11),
13
13
  // packages/opencode/src/session/message-v2.ts.
14
14
  import { render, RULE } from "../envelope.mjs";
15
+ import { opencodeService, opencodeServiceFile } from "../registry.mjs";
15
16
 
16
17
  export function partsOf({ head, body, foot }) {
17
18
  const cut = foot.indexOf(RULE) + 1;
@@ -20,7 +21,33 @@ export function partsOf({ head, body, foot }) {
20
21
  return rest.length ? [shown, { type: "text", synthetic: true, text: rest.join("\n") }] : [shown];
21
22
  }
22
23
 
24
+ // OpenCode 2 has no `prompt_async` and no part list. `/api/.../prompt` takes one
25
+ // text. `/api/.../synthetic` exists, but the server runs each item of the inbox
26
+ // as its own turn: a hidden notice after the text arrives one turn late, and it
27
+ // costs a second call to the model. So the whole text goes in one prompt, and
28
+ // the person sees the notice too. `queue` waits for a turn that runs now.
29
+ // Source: GET /openapi.json of `opencode serve --service`, version 2.2.6, and a
30
+ // live test on 2026-11-07.
31
+ async function deliverV2(agent, message, { text, layout }) {
32
+ const service = opencodeService();
33
+ if (!service) throw new Error(`opencode: no running service in ${opencodeServiceFile()}`);
34
+ const body = {
35
+ text: layout ? [...layout.head, layout.body, ...layout.foot].join("\n") : (text ?? render(message)),
36
+ delivery: "queue",
37
+ metadata: { openmsg: message?.messageId ?? true },
38
+ };
39
+ const res = await fetch(`${agent.transport.base}/api/session/${agent.id}/prompt`, {
40
+ method: "POST",
41
+ headers: { "content-type": "application/json", authorization: service.auth },
42
+ body: JSON.stringify(body),
43
+ signal: AbortSignal.timeout(5000),
44
+ });
45
+ if (!res.ok) throw new Error(`opencode ${res.status}: ${(await res.text()).slice(0, 200)}`);
46
+ return { delivered: true, transport: "http" };
47
+ }
48
+
23
49
  export async function deliver(agent, message, { text = null, layout = null } = {}) {
50
+ if (agent.transport?.api === 2) return deliverV2(agent, message, { text, layout });
24
51
  const url = `${agent.transport.base}/session/${agent.id}/prompt_async`;
25
52
  const parts = layout ? partsOf(layout) : [{ type: "text", text: text ?? render(message) }];
26
53
  const res = await fetch(url, {
package/src/cli.mjs CHANGED
@@ -198,7 +198,8 @@ async function cmdSend(target, text, replyTo = null, args = []) {
198
198
  if (message.openmsg.hops.length > MAX_HOPS) {
199
199
  throw new Error(
200
200
  `hop limit reached: this conversation already passed through ${message.openmsg.hops.length - 1} agents. ` +
201
- "Tell your user instead.",
201
+ "Ask your user if they want to continue. If the user says yes, send the text again " +
202
+ "as a new message, without --reply-to. A new message starts a new conversation.",
202
203
  );
203
204
  }
204
205
 
package/src/envelope.mjs CHANGED
@@ -3,8 +3,9 @@
3
3
  import { randomUUID } from "node:crypto";
4
4
 
5
5
  // A chain of replies inside one conversation. It stops a loop between two
6
- // agents that answer each other without end.
7
- export const MAX_HOPS = 8;
6
+ // agents that answer each other without end. At the limit, the agent asks its
7
+ // user, and a new message starts a new chain.
8
+ export const MAX_HOPS = 100;
8
9
 
9
10
  export function createMessage({ from, to, text, contextId, replyTo }) {
10
11
  return {
package/src/registry.mjs CHANGED
@@ -196,9 +196,82 @@ async function pgrep(name) {
196
196
  return stdout.trim().split("\n").filter(Boolean);
197
197
  }
198
198
 
199
- // OpenCode runs an HTTP server for each user interface. The port is in the
200
- // listening sockets of the process.
201
- export async function opencodeAgents({ maxAgeMs = 24 * 3600 * 1000 } = {}) {
199
+ // OpenCode 2 runs one shared server, `opencode serve --service`, and each user
200
+ // interface is a client of it. The server writes its address, its process id,
201
+ // and its password to one file. Every request needs the password, with Basic
202
+ // authentication and the user name "opencode". The API is under /api, and each
203
+ // answer holds its result in `data`.
204
+ // A test sets OPENMSG_OPENCODE_SERVICE to a file of its own.
205
+ export function opencodeServiceFile() {
206
+ return process.env.OPENMSG_OPENCODE_SERVICE || path.join(HOME, ".local", "state", "opencode", "service.json");
207
+ }
208
+
209
+ export function opencodeService(file = opencodeServiceFile()) {
210
+ try {
211
+ const s = JSON.parse(fs.readFileSync(file, "utf8"));
212
+ if (!s.url || !s.password) return null;
213
+ if (s.pid && !alive(s.pid)) return null;
214
+ return { base: s.url.replace(/\/$/, ""), pid: s.pid ?? null, auth: `Basic ${Buffer.from(`opencode:${s.password}`).toString("base64")}` };
215
+ } catch {
216
+ return null;
217
+ }
218
+ }
219
+
220
+ async function opencodeServiceAgents({ maxAgeMs, file } = {}) {
221
+ const service = opencodeService(file);
222
+ if (!service) return [];
223
+ const get = async (p) => {
224
+ const res = await fetch(`${service.base}${p}`, {
225
+ headers: { authorization: service.auth },
226
+ signal: AbortSignal.timeout(1500),
227
+ });
228
+ if (!res.ok) throw new Error(`opencode ${res.status}`);
229
+ return (await res.json()).data;
230
+ };
231
+ let sessions;
232
+ let active = {};
233
+ try {
234
+ sessions = await get("/api/session?parentID=null");
235
+ } catch {
236
+ return [];
237
+ }
238
+ try {
239
+ active = (await get("/api/session/active")) ?? {};
240
+ } catch {
241
+ // Without this list, the state of each session stays unknown.
242
+ }
243
+ const out = [];
244
+ for (const s of sessions ?? []) {
245
+ const updated = s.time?.updated ?? 0;
246
+ if (Date.now() - updated > maxAgeMs) continue;
247
+ const title = (s.title ?? "").trim();
248
+ const short = title && !title.startsWith("New session") ? title.slice(0, 32).replace(/\s+/g, "-") : s.id.slice(-4);
249
+ out.push({
250
+ vendor: "opencode",
251
+ id: s.id,
252
+ name: `${short}-${s.id.slice(-4)}`,
253
+ pid: service.pid,
254
+ cwd: s.location?.directory ?? null,
255
+ status: active[s.id] ? "busy" : "idle",
256
+ title: title && !title.startsWith("New session") ? title : null,
257
+ startedAt: s.time?.created ?? null,
258
+ updatedAt: updated,
259
+ transport: { kind: "http", base: service.base, api: 2 },
260
+ });
261
+ }
262
+ return out;
263
+ }
264
+
265
+ // OpenCode 1 runs an HTTP server for each user interface. The port is in the
266
+ // listening sockets of the process. OpenCode 2 has the shared server above.
267
+ export async function opencodeAgents({ maxAgeMs = 24 * 3600 * 1000, serviceFile } = {}) {
268
+ const service = await opencodeServiceAgents({ maxAgeMs, file: serviceFile });
269
+ const legacy = await opencodeLegacyAgents({ maxAgeMs, skipPid: service[0]?.pid });
270
+ const seen = new Set(service.map((a) => a.id));
271
+ return [...service, ...legacy.filter((a) => !seen.has(a.id))];
272
+ }
273
+
274
+ async function opencodeLegacyAgents({ maxAgeMs, skipPid = null }) {
202
275
  let pids = [];
203
276
  try {
204
277
  // `-x` matches the name of the program. `-f` matches the whole command
@@ -211,9 +284,12 @@ export async function opencodeAgents({ maxAgeMs = 24 * 3600 * 1000 } = {}) {
211
284
  const found = new Map();
212
285
  const out = [];
213
286
  for (const pid of pids) {
287
+ if (Number(pid) === skipPid) continue;
214
288
  let ports = [];
215
289
  try {
216
- const { stdout } = await run("lsof", ["-nP", "-p", pid, "-iTCP", "-sTCP:LISTEN", "-Fn"]);
290
+ // `-a` joins the conditions. Without it, lsof gives the listening ports
291
+ // of every process, and openmsg asks each of them for sessions.
292
+ const { stdout } = await run("lsof", ["-a", "-nP", "-p", pid, "-iTCP", "-sTCP:LISTEN", "-Fn"]);
217
293
  ports = [...stdout.matchAll(/n\S*:(\d+)/g)].map((m) => Number(m[1]));
218
294
  } catch {
219
295
  continue;
@@ -474,7 +550,7 @@ export async function self() {
474
550
  // A Claude session started this command, but no session record holds its
475
551
  // socket. A shell name here is false: nobody can send to it, and an agent
476
552
  // gives it to other agents as its own address.
477
- if (!me) {
553
+ if (!me && !process.env.OPENCODE_SESSION_ID) {
478
554
  throw new Error(
479
555
  `this command runs in a Claude Code session, but openmsg cannot find the record of that session ` +
480
556
  `(socket ${socket}). openmsg reads ${claudeConfigDirs().map((d) => `${d}/sessions`).join(", ")}. ` +
@@ -482,6 +558,20 @@ export async function self() {
482
558
  );
483
559
  }
484
560
  }
561
+ // OpenCode 2 gives the session id to every shell command that it runs.
562
+ if (process.env.OPENCODE_SESSION_ID) {
563
+ const id = process.env.OPENCODE_SESSION_ID;
564
+ const known = (await opencodeAgents()).find((a) => a.id === id);
565
+ if (known) return known;
566
+ const service = opencodeService();
567
+ return {
568
+ vendor: "opencode",
569
+ id,
570
+ name: id.slice(-4),
571
+ cwd: process.cwd(),
572
+ transport: service ? { kind: "http", base: service.base, api: 2 } : { kind: "mailbox" },
573
+ };
574
+ }
485
575
  const line = await ancestors(process.ppid);
486
576
  let [codex, opencode] = await Promise.all([codexAgents(), opencodeAgents()]);
487
577
  if (codex.length === 0) codex = codexAgentsFromFiles({ maxAgeMs: 6 * 3600 * 1000 });
package/src/remote.mjs CHANGED
@@ -82,7 +82,12 @@ export function createRemote({
82
82
  },
83
83
  };
84
84
  if (message.openmsg.hops.length > MAX_HOPS) {
85
- throw fail("hop-limit", `this conversation already passed through ${message.openmsg.hops.length - 1} agents`);
85
+ throw fail(
86
+ "hop-limit",
87
+ `this conversation already passed through ${message.openmsg.hops.length - 1} agents. ` +
88
+ "Ask your user if they want to continue. If the user says yes, send the text again " +
89
+ "as a new message, without --reply-to. A new message starts a new conversation.",
90
+ );
86
91
  }
87
92
  return signedView(message);
88
93
  }