openmsg 0.4.5 → 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.5",
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
@@ -19,9 +19,41 @@ function alive(pid) {
19
19
  }
20
20
  }
21
21
 
22
+ // Claude Code keeps its state in ~/.claude, or in the directory that
23
+ // CLAUDE_CONFIG_DIR names. A person can run sessions with more than one such
24
+ // directory, for example ~/.claude-work for a second account. Each session of
25
+ // each directory must be found, so openmsg reads all of them.
26
+ export function claudeConfigDirs() {
27
+ const dirs = [path.join(HOME, ".claude")];
28
+ if (process.env.CLAUDE_CONFIG_DIR) dirs.push(path.resolve(process.env.CLAUDE_CONFIG_DIR));
29
+ try {
30
+ for (const d of fs.readdirSync(HOME)) {
31
+ if (!d.startsWith(".claude-")) continue;
32
+ const full = path.join(HOME, d);
33
+ if (fs.existsSync(path.join(full, "sessions"))) dirs.push(full);
34
+ }
35
+ } catch {
36
+ // The home directory cannot be read.
37
+ }
38
+ return [...new Set(dirs)];
39
+ }
40
+
22
41
  // Claude Code writes one file for each session, with the path of its inbox socket.
23
42
  export function claudeAgents() {
24
- const dir = path.join(HOME, ".claude", "sessions");
43
+ const out = [];
44
+ const seen = new Set();
45
+ for (const config of claudeConfigDirs()) {
46
+ for (const agent of claudeAgentsIn(config)) {
47
+ if (seen.has(agent.id)) continue;
48
+ seen.add(agent.id);
49
+ out.push(agent);
50
+ }
51
+ }
52
+ return out;
53
+ }
54
+
55
+ function claudeAgentsIn(config) {
56
+ const dir = path.join(config, "sessions");
25
57
  let files = [];
26
58
  try {
27
59
  files = fs.readdirSync(dir).filter((f) => f.endsWith(".json"));
@@ -44,7 +76,7 @@ export function claudeAgents() {
44
76
  pid: rec.pid,
45
77
  cwd: rec.cwd,
46
78
  status: rec.status ?? "unknown",
47
- title: claudeTitle(rec.cwd, rec.sessionId),
79
+ title: claudeTitle(config, rec.cwd, rec.sessionId),
48
80
  // A program that uses the SDK, such as a memory observer, starts a
49
81
  // session too. It is not a session that a person talks to.
50
82
  background: rec.entrypoint === "sdk-cli",
@@ -59,8 +91,8 @@ export function claudeAgents() {
59
91
  // Claude Code keeps the transcript of a session in a directory that the
60
92
  // working directory names, with each character that is not a letter or a digit
61
93
  // changed to "-".
62
- function claudeTranscript(cwd, sessionId) {
63
- const root = path.join(HOME, ".claude", "projects");
94
+ function claudeTranscript(config, cwd, sessionId) {
95
+ const root = path.join(config, "projects");
64
96
  const file = `${sessionId}.jsonl`;
65
97
  if (cwd) {
66
98
  const direct = path.join(root, cwd.replace(/[^A-Za-z0-9]/g, "-"), file);
@@ -77,9 +109,9 @@ function claudeTranscript(cwd, sessionId) {
77
109
  return null;
78
110
  }
79
111
 
80
- function claudeTitle(cwd, sessionId) {
112
+ function claudeTitle(config, cwd, sessionId) {
81
113
  if (!sessionId) return null;
82
- const file = claudeTranscript(cwd, sessionId);
114
+ const file = claudeTranscript(config, cwd, sessionId);
83
115
  return file ? lastClaudeTitle(file) : null;
84
116
  }
85
117
 
@@ -164,9 +196,82 @@ async function pgrep(name) {
164
196
  return stdout.trim().split("\n").filter(Boolean);
165
197
  }
166
198
 
167
- // OpenCode runs an HTTP server for each user interface. The port is in the
168
- // listening sockets of the process.
169
- 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 }) {
170
275
  let pids = [];
171
276
  try {
172
277
  // `-x` matches the name of the program. `-f` matches the whole command
@@ -179,9 +284,12 @@ export async function opencodeAgents({ maxAgeMs = 24 * 3600 * 1000 } = {}) {
179
284
  const found = new Map();
180
285
  const out = [];
181
286
  for (const pid of pids) {
287
+ if (Number(pid) === skipPid) continue;
182
288
  let ports = [];
183
289
  try {
184
- 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"]);
185
293
  ports = [...stdout.matchAll(/n\S*:(\d+)/g)].map((m) => Number(m[1]));
186
294
  } catch {
187
295
  continue;
@@ -436,8 +544,33 @@ export async function self() {
436
544
  return known ?? { vendor: "codex", id, name: id.slice(-8), transport: { kind: "codex-queue" } };
437
545
  }
438
546
  if (process.env.CLAUDE_CODE_MESSAGING_SOCKET) {
439
- const me = claudeAgents().find((a) => a.transport.path === process.env.CLAUDE_CODE_MESSAGING_SOCKET);
547
+ const socket = process.env.CLAUDE_CODE_MESSAGING_SOCKET;
548
+ const me = claudeAgents().find((a) => a.transport.path === socket);
440
549
  if (me && (await runsUnder(me.pid))) return me;
550
+ // A Claude session started this command, but no session record holds its
551
+ // socket. A shell name here is false: nobody can send to it, and an agent
552
+ // gives it to other agents as its own address.
553
+ if (!me && !process.env.OPENCODE_SESSION_ID) {
554
+ throw new Error(
555
+ `this command runs in a Claude Code session, but openmsg cannot find the record of that session ` +
556
+ `(socket ${socket}). openmsg reads ${claudeConfigDirs().map((d) => `${d}/sessions`).join(", ")}. ` +
557
+ `If the session uses another CLAUDE_CONFIG_DIR, run openmsg from inside it, or set OPENMSG_SELF.`,
558
+ );
559
+ }
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
+ };
441
574
  }
442
575
  const line = await ancestors(process.ppid);
443
576
  let [codex, opencode] = await Promise.all([codexAgents(), opencodeAgents()]);
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
  }