openmsg 0.1.0
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/LICENSE +21 -0
- package/README.md +86 -0
- package/docs/spec/openmsg-0.1.md +281 -0
- package/docs/spec/openmsg-0.2-draft.md +259 -0
- package/package.json +43 -0
- package/src/adapters/claude.mjs +35 -0
- package/src/adapters/codex.mjs +41 -0
- package/src/adapters/opencode.mjs +17 -0
- package/src/cli.mjs +199 -0
- package/src/envelope.mjs +49 -0
- package/src/hook.mjs +83 -0
- package/src/hookinstall.mjs +83 -0
- package/src/install.mjs +94 -0
- package/src/mailbox.mjs +70 -0
- package/src/registry.mjs +321 -0
- package/src/selfregistry.mjs +49 -0
package/src/registry.mjs
ADDED
|
@@ -0,0 +1,321 @@
|
|
|
1
|
+
// Discovery: find the agent sessions that run now, for each vendor.
|
|
2
|
+
// Each vendor keeps its own record, so openmsg reads each one and returns one list.
|
|
3
|
+
import fs from "node:fs";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import os from "node:os";
|
|
6
|
+
import { execFile } from "node:child_process";
|
|
7
|
+
import { registered } from "./selfregistry.mjs";
|
|
8
|
+
import { promisify } from "node:util";
|
|
9
|
+
|
|
10
|
+
const run = promisify(execFile);
|
|
11
|
+
const HOME = os.homedir();
|
|
12
|
+
|
|
13
|
+
function alive(pid) {
|
|
14
|
+
try {
|
|
15
|
+
process.kill(pid, 0);
|
|
16
|
+
return true;
|
|
17
|
+
} catch {
|
|
18
|
+
return false;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// Claude Code writes one file for each session, with the path of its inbox socket.
|
|
23
|
+
export function claudeAgents() {
|
|
24
|
+
const dir = path.join(HOME, ".claude", "sessions");
|
|
25
|
+
let files = [];
|
|
26
|
+
try {
|
|
27
|
+
files = fs.readdirSync(dir).filter((f) => f.endsWith(".json"));
|
|
28
|
+
} catch {
|
|
29
|
+
return [];
|
|
30
|
+
}
|
|
31
|
+
const out = [];
|
|
32
|
+
for (const f of files) {
|
|
33
|
+
let rec;
|
|
34
|
+
try {
|
|
35
|
+
rec = JSON.parse(fs.readFileSync(path.join(dir, f), "utf8"));
|
|
36
|
+
} catch {
|
|
37
|
+
continue;
|
|
38
|
+
}
|
|
39
|
+
if (!rec.messagingSocketPath || !rec.pid || !alive(rec.pid)) continue;
|
|
40
|
+
out.push({
|
|
41
|
+
vendor: "claude",
|
|
42
|
+
id: rec.sessionId,
|
|
43
|
+
name: rec.name ?? `claude-${rec.pid}`,
|
|
44
|
+
pid: rec.pid,
|
|
45
|
+
cwd: rec.cwd,
|
|
46
|
+
status: rec.status ?? "unknown",
|
|
47
|
+
transport: { kind: "uds", path: rec.messagingSocketPath },
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
return out;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// OpenCode runs an HTTP server for each user interface. The port is in the
|
|
54
|
+
// listening sockets of the process.
|
|
55
|
+
export async function opencodeAgents({ maxAgeMs = 24 * 3600 * 1000 } = {}) {
|
|
56
|
+
let pids = [];
|
|
57
|
+
try {
|
|
58
|
+
// `-x` matches the name of the program. `-f` matches the whole command
|
|
59
|
+
// line, and that also matches a program that only holds the word in its
|
|
60
|
+
// environment.
|
|
61
|
+
const { stdout } = await run("pgrep", ["-x", "opencode"]);
|
|
62
|
+
pids = stdout.trim().split("\n").filter(Boolean);
|
|
63
|
+
} catch {
|
|
64
|
+
return [];
|
|
65
|
+
}
|
|
66
|
+
const found = new Map();
|
|
67
|
+
const out = [];
|
|
68
|
+
for (const pid of pids) {
|
|
69
|
+
let ports = [];
|
|
70
|
+
try {
|
|
71
|
+
const { stdout } = await run("lsof", ["-nP", "-p", pid, "-iTCP", "-sTCP:LISTEN", "-Fn"]);
|
|
72
|
+
ports = [...stdout.matchAll(/n\S*:(\d+)/g)].map((m) => Number(m[1]));
|
|
73
|
+
} catch {
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
for (const port of new Set(ports)) {
|
|
77
|
+
const base = `http://127.0.0.1:${port}`;
|
|
78
|
+
let sessions;
|
|
79
|
+
try {
|
|
80
|
+
const res = await fetch(`${base}/session`, { signal: AbortSignal.timeout(1500) });
|
|
81
|
+
if (!res.ok) continue;
|
|
82
|
+
sessions = await res.json();
|
|
83
|
+
} catch {
|
|
84
|
+
continue;
|
|
85
|
+
}
|
|
86
|
+
// A session of OpenCode stays on disk after it ends. Only a session that
|
|
87
|
+
// changed a short time ago belongs to the work of now.
|
|
88
|
+
for (const s of sessions) {
|
|
89
|
+
const updated = s.time?.updated ?? 0;
|
|
90
|
+
if (Date.now() - updated > maxAgeMs) continue;
|
|
91
|
+
if (found.has(s.id)) continue;
|
|
92
|
+
found.set(s.id, true);
|
|
93
|
+
const title = (s.title ?? "").trim();
|
|
94
|
+
const short = title && !title.startsWith("New session")
|
|
95
|
+
? title.slice(0, 32).replace(/\s+/g, "-")
|
|
96
|
+
: s.id.slice(-4);
|
|
97
|
+
out.push({
|
|
98
|
+
vendor: "opencode",
|
|
99
|
+
id: s.id,
|
|
100
|
+
name: `${short}-${s.id.slice(-4)}`,
|
|
101
|
+
pid: Number(pid),
|
|
102
|
+
cwd: s.directory ?? null,
|
|
103
|
+
status: "unknown",
|
|
104
|
+
updatedAt: updated,
|
|
105
|
+
transport: { kind: "http", base },
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
return out;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// Codex keeps the record of a live session in a rollout file, and the process
|
|
114
|
+
// that runs the session holds that file open. openmsg lists the open rollout
|
|
115
|
+
// files of every Codex process, and reads the thread id from each one.
|
|
116
|
+
export async function codexAgents() {
|
|
117
|
+
let pids = [];
|
|
118
|
+
try {
|
|
119
|
+
const { stdout } = await run("pgrep", ["-x", "codex"]);
|
|
120
|
+
pids = stdout.trim().split("\n").filter(Boolean);
|
|
121
|
+
} catch {
|
|
122
|
+
return [];
|
|
123
|
+
}
|
|
124
|
+
const found = new Map();
|
|
125
|
+
for (const pid of pids) {
|
|
126
|
+
// A command that an agent runs can be sandboxed. Then `lsof` gives nothing,
|
|
127
|
+
// and the caller falls back to codexAgentsFromFiles().
|
|
128
|
+
let paths = [];
|
|
129
|
+
try {
|
|
130
|
+
const { stdout } = await run("lsof", ["-p", pid, "-Fn"]);
|
|
131
|
+
paths = [...stdout.matchAll(/\/[^\s]*\/\.codex\/sessions\/[^\s]*rollout-[^\s]*\.jsonl/g)].map((m) => m[0]);
|
|
132
|
+
} catch {
|
|
133
|
+
continue;
|
|
134
|
+
}
|
|
135
|
+
for (const file of paths) {
|
|
136
|
+
const id = file.match(/rollout-[\dT-]+-([0-9a-f-]{36})\.jsonl$/)?.[1];
|
|
137
|
+
if (!id || found.has(id)) continue;
|
|
138
|
+
let cwd = null;
|
|
139
|
+
let name = id.slice(-8);
|
|
140
|
+
try {
|
|
141
|
+
const first = fs.readFileSync(file, "utf8").split("\n", 1)[0];
|
|
142
|
+
const meta = JSON.parse(first);
|
|
143
|
+
cwd = meta?.payload?.cwd ?? null;
|
|
144
|
+
if (cwd) name = `${path.basename(cwd)}-${id.slice(-4)}`;
|
|
145
|
+
} catch {
|
|
146
|
+
// The file can be empty while Codex starts. The thread id still works.
|
|
147
|
+
}
|
|
148
|
+
found.set(id, {
|
|
149
|
+
vendor: "codex",
|
|
150
|
+
id,
|
|
151
|
+
name,
|
|
152
|
+
pid: Number(pid),
|
|
153
|
+
cwd,
|
|
154
|
+
status: "unknown",
|
|
155
|
+
transport: { kind: "codex-queue" },
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
return [...found.values()];
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// Fallback for Codex when the command runs in a sandbox that blocks `lsof`.
|
|
163
|
+
// It reads the rollout files that Codex changed in the last hours. A file that
|
|
164
|
+
// changed a moment ago belongs to a session that runs now.
|
|
165
|
+
export function codexAgentsFromFiles({ maxAgeMs = 12 * 3600 * 1000 } = {}) {
|
|
166
|
+
const root = path.join(HOME, ".codex", "sessions");
|
|
167
|
+
const out = [];
|
|
168
|
+
const walk = (dir, depth) => {
|
|
169
|
+
let entries = [];
|
|
170
|
+
try {
|
|
171
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
172
|
+
} catch {
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
175
|
+
for (const e of entries) {
|
|
176
|
+
const full = path.join(dir, e.name);
|
|
177
|
+
if (e.isDirectory() && depth < 4) walk(full, depth + 1);
|
|
178
|
+
else if (e.isFile() && e.name.startsWith("rollout-") && e.name.endsWith(".jsonl")) {
|
|
179
|
+
let stat;
|
|
180
|
+
try {
|
|
181
|
+
stat = fs.statSync(full);
|
|
182
|
+
} catch {
|
|
183
|
+
continue;
|
|
184
|
+
}
|
|
185
|
+
if (Date.now() - stat.mtimeMs > maxAgeMs) continue;
|
|
186
|
+
const id = e.name.match(/rollout-[\dT-]+-([0-9a-f-]{36})\.jsonl$/)?.[1];
|
|
187
|
+
if (!id) continue;
|
|
188
|
+
let cwd = null;
|
|
189
|
+
try {
|
|
190
|
+
cwd = JSON.parse(fs.readFileSync(full, "utf8").split("\n", 1)[0])?.payload?.cwd ?? null;
|
|
191
|
+
} catch {
|
|
192
|
+
// An empty file belongs to a session that just started.
|
|
193
|
+
}
|
|
194
|
+
out.push({
|
|
195
|
+
vendor: "codex",
|
|
196
|
+
id,
|
|
197
|
+
name: cwd ? `${path.basename(cwd)}-${id.slice(-4)}` : id.slice(-8),
|
|
198
|
+
pid: null,
|
|
199
|
+
cwd,
|
|
200
|
+
status: "unknown",
|
|
201
|
+
transport: { kind: "codex-queue" },
|
|
202
|
+
mtimeMs: stat.mtimeMs,
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
};
|
|
207
|
+
walk(root, 0);
|
|
208
|
+
return out.sort((a, b) => b.mtimeMs - a.mtimeMs);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
export async function allAgents() {
|
|
212
|
+
const [claude, opencode, codex] = await Promise.all([
|
|
213
|
+
Promise.resolve(claudeAgents()),
|
|
214
|
+
opencodeAgents(),
|
|
215
|
+
codexAgents(),
|
|
216
|
+
]);
|
|
217
|
+
// An agent with no push entry point reports itself from its hook.
|
|
218
|
+
return [...claude, ...opencode, ...codex, ...registered()];
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
export async function findAgent(query) {
|
|
222
|
+
const agents = await allAgents();
|
|
223
|
+
const [vendor, name] = query.includes(":") ? [query.split(":")[0], query.split(":").slice(1).join(":")] : [null, query];
|
|
224
|
+
const matches = agents.filter(
|
|
225
|
+
(a) => (!vendor || a.vendor === vendor) && (a.name === name || a.id === name || a.id?.startsWith(name)),
|
|
226
|
+
);
|
|
227
|
+
if (matches.length === 0) throw new Error(`no agent matches "${query}". Run: openmsg list`);
|
|
228
|
+
if (matches.length > 1) {
|
|
229
|
+
const names = matches.map((m) => `${m.vendor}:${m.name}`).join(", ");
|
|
230
|
+
throw new Error(`"${query}" matches more than one agent: ${names}`);
|
|
231
|
+
}
|
|
232
|
+
return matches[0];
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
// The agents that run a shell command do not all say who they are. openmsg finds
|
|
236
|
+
// the sender in three steps: the environment of Claude Code, then the process
|
|
237
|
+
// that started this command, then the OPENMSG_SELF variable.
|
|
238
|
+
async function ancestors(pid, depth = 8) {
|
|
239
|
+
const out = [];
|
|
240
|
+
let current = pid;
|
|
241
|
+
for (let i = 0; i < depth && current > 1; i++) {
|
|
242
|
+
out.push(current);
|
|
243
|
+
try {
|
|
244
|
+
const { stdout } = await run("ps", ["-o", "ppid=", "-p", String(current)]);
|
|
245
|
+
current = Number(stdout.trim());
|
|
246
|
+
} catch {
|
|
247
|
+
break;
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
return out;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
export async function self() {
|
|
254
|
+
// OPENMSG_SELF can hold an alias, such as "codex:openmsg-33ce". An alias is
|
|
255
|
+
// not a session id, so openmsg looks the session up. Without this step, a
|
|
256
|
+
// reply that pins the session id of the sender fails.
|
|
257
|
+
if (process.env.OPENMSG_SELF) {
|
|
258
|
+
const value = process.env.OPENMSG_SELF;
|
|
259
|
+
try {
|
|
260
|
+
return await findAgent(value);
|
|
261
|
+
} catch {
|
|
262
|
+
const [vendor, ...rest] = value.split(":");
|
|
263
|
+
const name = rest.join(":");
|
|
264
|
+
return { vendor, id: name, name, unresolved: true };
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
// Codex gives the thread id to every command that it runs. This is the exact
|
|
268
|
+
// answer, so openmsg uses it before any guess from the process tree.
|
|
269
|
+
if (process.env.CODEX_THREAD_ID) {
|
|
270
|
+
const id = process.env.CODEX_THREAD_ID;
|
|
271
|
+
const known = codexAgentsFromFiles({ maxAgeMs: 24 * 3600 * 1000 }).find((a) => a.id === id);
|
|
272
|
+
return known ?? { vendor: "codex", id, name: id.slice(-8), transport: { kind: "codex-queue" } };
|
|
273
|
+
}
|
|
274
|
+
if (process.env.CLAUDE_CODE_MESSAGING_SOCKET) {
|
|
275
|
+
const me = claudeAgents().find((a) => a.transport.path === process.env.CLAUDE_CODE_MESSAGING_SOCKET);
|
|
276
|
+
if (me) return me;
|
|
277
|
+
}
|
|
278
|
+
const line = await ancestors(process.ppid);
|
|
279
|
+
let [codex, opencode] = await Promise.all([codexAgents(), opencodeAgents()]);
|
|
280
|
+
if (codex.length === 0) codex = codexAgentsFromFiles({ maxAgeMs: 6 * 3600 * 1000 });
|
|
281
|
+
|
|
282
|
+
// Direct match: an agent process is one of the parents of this command.
|
|
283
|
+
for (const pid of line) {
|
|
284
|
+
const byPid = [...codex, ...opencode].filter((a) => a.pid === pid);
|
|
285
|
+
if (byPid.length === 1) return byPid[0];
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
// Codex runs a command in a separate process, and the session record stays
|
|
289
|
+
// with the daemon. A Codex process in the parent line still shows the vendor,
|
|
290
|
+
// and the working directory shows the session.
|
|
291
|
+
const names = await Promise.all(
|
|
292
|
+
line.map(async (pid) => {
|
|
293
|
+
try {
|
|
294
|
+
const { stdout } = await run("ps", ["-o", "comm=", "-p", String(pid)]);
|
|
295
|
+
return path.basename(stdout.trim());
|
|
296
|
+
} catch {
|
|
297
|
+
return "";
|
|
298
|
+
}
|
|
299
|
+
}),
|
|
300
|
+
);
|
|
301
|
+
const here = process.cwd();
|
|
302
|
+
// In a sandbox, `ps` can also give nothing. Then the working directory is the
|
|
303
|
+
// only evidence left, so openmsg uses it alone.
|
|
304
|
+
const vendorUnknown = names.every((n) => n === "");
|
|
305
|
+
if (names.includes("codex") || vendorUnknown) {
|
|
306
|
+
const sameDir = codex.filter((a) => a.cwd === here);
|
|
307
|
+
if (sameDir.length === 1) return sameDir[0];
|
|
308
|
+
if (sameDir.length > 1) {
|
|
309
|
+
throw new Error(
|
|
310
|
+
`${sameDir.length} Codex sessions run in this directory, so openmsg cannot tell which one sends. ` +
|
|
311
|
+
`Set OPENMSG_SELF, for example: OPENMSG_SELF=codex:${sameDir[0].name}`,
|
|
312
|
+
);
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
if (names.includes("opencode")) {
|
|
316
|
+
const sameDir = opencode.filter((a) => a.cwd === here);
|
|
317
|
+
if (sameDir.length === 1) return sameDir[0];
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
return { vendor: "shell", id: String(process.ppid), name: `shell-${process.ppid}` };
|
|
321
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
// Some agents keep no record of a session that another program can read.
|
|
2
|
+
// Cursor CLI and Gemini CLI are two of them. For those, a hook writes the
|
|
3
|
+
// record here each time it runs, and discovery reads this directory.
|
|
4
|
+
import fs from "node:fs";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import os from "node:os";
|
|
7
|
+
|
|
8
|
+
const ROOT = process.env.OPENMSG_HOME ?? path.join(os.homedir(), ".openmsg");
|
|
9
|
+
const DIR = path.join(ROOT, "agents");
|
|
10
|
+
|
|
11
|
+
// A session that no hook reported for this long is gone from the list.
|
|
12
|
+
export const STALE_MS = 6 * 3600 * 1000;
|
|
13
|
+
|
|
14
|
+
export function register({ vendor, id, name, cwd }) {
|
|
15
|
+
fs.mkdirSync(DIR, { recursive: true });
|
|
16
|
+
const file = path.join(DIR, `${vendor}-${id}.json`.replace(/[^A-Za-z0-9._-]/g, "_"));
|
|
17
|
+
const record = { vendor, id, name, cwd: cwd ?? null, lastSeen: Date.now() };
|
|
18
|
+
fs.writeFileSync(file, JSON.stringify(record, null, 1));
|
|
19
|
+
return record;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function registered({ maxAgeMs = STALE_MS } = {}) {
|
|
23
|
+
let files = [];
|
|
24
|
+
try {
|
|
25
|
+
files = fs.readdirSync(DIR).filter((f) => f.endsWith(".json"));
|
|
26
|
+
} catch {
|
|
27
|
+
return [];
|
|
28
|
+
}
|
|
29
|
+
const out = [];
|
|
30
|
+
for (const f of files) {
|
|
31
|
+
let rec;
|
|
32
|
+
try {
|
|
33
|
+
rec = JSON.parse(fs.readFileSync(path.join(DIR, f), "utf8"));
|
|
34
|
+
} catch {
|
|
35
|
+
continue;
|
|
36
|
+
}
|
|
37
|
+
if (Date.now() - (rec.lastSeen ?? 0) > maxAgeMs) continue;
|
|
38
|
+
out.push({
|
|
39
|
+
vendor: rec.vendor,
|
|
40
|
+
id: rec.id,
|
|
41
|
+
name: rec.name ?? rec.id.slice(-8),
|
|
42
|
+
pid: null,
|
|
43
|
+
cwd: rec.cwd,
|
|
44
|
+
status: "unknown",
|
|
45
|
+
transport: { kind: "mailbox" },
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
return out;
|
|
49
|
+
}
|