openmsg 0.4.3 → 0.4.5

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
@@ -22,7 +22,8 @@ Each vendor has its own way to accept a message while it runs. openmsg uses that
22
22
  native way, and gives all of them one command:
23
23
 
24
24
  ```
25
- openmsg list # the agents that run now, all vendors
25
+ openmsg list # the agents that run now, and the work of each
26
+ openmsg note "<text>" # tell the other agents what this one does
26
27
  openmsg send <agent> "<text>" # deliver a message now
27
28
  openmsg inbox # the messages for this agent
28
29
  openmsg whoami # how other agents address this one
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "openmsg",
3
- "version": "0.4.3",
3
+ "version": "0.4.5",
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": {
package/src/cli.mjs CHANGED
@@ -22,13 +22,17 @@ import * as outbox from "./outbox.mjs";
22
22
  import * as limits from "./limits.mjs";
23
23
  import * as device from "./device.mjs";
24
24
  import * as dirsync from "./dirsync.mjs";
25
+ import * as notes from "./notes.mjs";
25
26
  import { fileURLToPath } from "node:url";
26
27
  import fs from "node:fs";
27
28
  import path from "node:path";
29
+ import os from "node:os";
28
30
 
29
31
  const USAGE = `openmsg — messages between AI coding agents
30
32
 
31
- openmsg list show the agents that run now
33
+ openmsg list [--all] [--json] show the agents that run now, and their work
34
+ openmsg note "<text>" tell the other agents what this session does
35
+ [--clear] remove the note
32
36
  openmsg send <agent> <text> send a message to an agent
33
37
  [--reply-to <message-id>] keep the conversation of that message
34
38
  openmsg send project:<dir> <text> the next session in that directory takes it
@@ -83,18 +87,66 @@ A message to another person goes to "claude:api-worker@alice".
83
87
  Addresses look like "claude:api-worker" or "opencode:ses_123".
84
88
  `;
85
89
 
86
- async function cmdList() {
87
- const agents = await allAgents();
90
+ // "5m", "3h", "2d": the time since a moment, in the largest whole unit.
91
+ function ago(ms) {
92
+ if (!ms) return null;
93
+ const s = Math.max(0, Math.round((Date.now() - ms) / 1000));
94
+ if (s < 60) return `${s}s`;
95
+ if (s < 3600) return `${Math.floor(s / 60)}m`;
96
+ if (s < 86400) return `${Math.floor(s / 3600)}h`;
97
+ return `${Math.floor(s / 86400)}d`;
98
+ }
99
+
100
+ // Two records name one session when the vendor and the session id agree.
101
+ function sameSession(a, b) {
102
+ return Boolean(a && b && a.vendor === b.vendor && a.id === b.id);
103
+ }
104
+
105
+ async function cmdList(args = []) {
106
+ // Several sessions can run in one directory with names that look alike. The
107
+ // mark "(you)" shows the agent which row is its own, so that it does not send
108
+ // to itself. A command outside a session has no row, and it gets no mark.
109
+ const [all, me] = await Promise.all([
110
+ allAgents().then((a) => notes.attach(a)),
111
+ self().catch(() => null),
112
+ ]);
113
+ const agents = args.includes("--all") ? all : all.filter((a) => !a.background);
114
+ const hidden = all.length - agents.length;
88
115
  if (agents.length === 0) {
89
- console.log("no running agents found");
116
+ console.log(hidden ? `no running agents found. ${hidden} background sessions: openmsg list --all` : "no running agents found");
117
+ return;
118
+ }
119
+ if (args.includes("--json")) {
120
+ console.log(JSON.stringify(agents.map(({ transport, ...a }) => ({ ...a, you: sameSession(a, me) })), null, 1));
90
121
  return;
91
122
  }
92
123
  const width = Math.max(...agents.map((a) => address(a).length));
124
+ const tilde = (p) => (p && p.startsWith(os.homedir()) ? `~${p.slice(os.homedir().length)}` : p);
93
125
  for (const a of agents) {
94
- const where = a.cwd ? ` · ${a.cwd}` : "";
95
- const note = a.note ? ` · ${a.note}` : "";
96
- console.log(`${address(a).padEnd(width)} ${a.status}${where}${note}`);
126
+ const times = [a.startedAt && `started ${ago(a.startedAt)} ago`, a.updatedAt && `active ${ago(a.updatedAt)} ago`];
127
+ const you = sameSession(a, me) ? "(you)" : "";
128
+ const head = [address(a).padEnd(width), a.status.padEnd(7), times.filter(Boolean).join(", "), you];
129
+ console.log(head.join(" ").trimEnd());
130
+ // The note of the agent comes first, because the agent wrote it about the
131
+ // work of now. The title of the vendor comes next.
132
+ const about = a.note ? `note: ${a.note}` : a.title ?? "(no title)";
133
+ console.log(` ${[about, tilde(a.cwd)].filter(Boolean).join(" · ")}`);
134
+ }
135
+ if (hidden) console.log(`\n${hidden} background sessions not shown. See them: openmsg list --all`);
136
+ }
137
+
138
+ async function cmdNote(args) {
139
+ const me = await self();
140
+ if (me.vendor === "shell" || me.unresolved) {
141
+ throw new Error("only an agent session has a note. Run this command from inside the agent.");
142
+ }
143
+ const text = args.includes("--clear") ? "" : args.filter((a) => a !== "--clear").join(" ");
144
+ if (!text && !args.includes("--clear")) {
145
+ console.log(notes.get(me) ?? "no note. Write one: openmsg note \"<what you work on>\"");
146
+ return;
97
147
  }
148
+ const note = notes.set(me, text);
149
+ console.log(note ? `${address(me)}: ${note}` : `${address(me)}: note removed`);
98
150
  }
99
151
 
100
152
  async function cmdSend(target, text, replyTo = null, args = []) {
@@ -123,6 +175,12 @@ async function cmdSend(target, text, replyTo = null, args = []) {
123
175
  `Its name was ${address(answered.openmsg.from)}. Send a new message instead of a reply.`,
124
176
  );
125
177
  }
178
+ if (sameSession(to, from)) {
179
+ throw new Error(
180
+ `${address(to)} is this session. An agent does not send a message to itself. ` +
181
+ "Leave it out of the recipients.",
182
+ );
183
+ }
126
184
  if (pinned && to.id !== pinned) {
127
185
  throw new Error(
128
186
  `the session that sent ${replyTo} is gone. Its name now belongs to ${address(to)}. ` +
@@ -180,8 +238,9 @@ async function cmdSendProject(target, text, replyTo, args) {
180
238
 
181
239
  // Only the records of Claude Code, because they are files. The discovery of
182
240
  // Codex and OpenCode runs lsof, and that costs seconds.
241
+ // A session that sends to its own directory does not get its own message.
183
242
  const live = claudeAgents()
184
- .filter((a) => projectbox.sessionIsIn(a.cwd, dir))
243
+ .filter((a) => projectbox.sessionIsIn(a.cwd, dir) && !sameSession(a, from))
185
244
  .sort((a, b) => b.updatedAt - a.updatedAt);
186
245
  for (const agent of live) {
187
246
  const got = projectbox.takeMessage(dir, message);
@@ -897,7 +956,8 @@ function commandName() {
897
956
 
898
957
  const [cmd, ...args] = process.argv.slice(2);
899
958
  try {
900
- if (cmd === "list") await cmdList();
959
+ if (cmd === "list") await cmdList(args);
960
+ else if (cmd === "note") await cmdNote(args);
901
961
  else if (cmd === "send") {
902
962
  const rest = positional(args, ["reply-to", "project", "key"]);
903
963
  await cmdSend(rest[0], rest.slice(1).join(" "), flag(args, "reply-to"), args);
package/src/install.mjs CHANGED
@@ -31,7 +31,8 @@ export function block(cliPath) {
31
31
 
32
32
  Other AI agents on this machine can send you a message. It starts with a
33
33
  \`From:\` line and an \`Id:\` line, and two lines of dashes hold its text.
34
- To see who runs now: \`${cliPath} list\`.
34
+ To see who runs now, and what each one works on: \`${cliPath} list\`.
35
+ To tell the others what you work on: \`${cliPath} note "<text>"\`.
35
36
  To answer, or to write first: \`${cliPath} send <agent> "<text>"\`.
36
37
 
37
38
  1. You can answer a message from another agent without a new instruction from your user.
package/src/notes.mjs ADDED
@@ -0,0 +1,50 @@
1
+ // The note that an agent writes about its own work. The vendor gives a title
2
+ // too, but a title can be old or wrong. The agent knows what it does now.
3
+ import fs from "node:fs";
4
+ import path from "node:path";
5
+ import os from "node:os";
6
+
7
+ function file() {
8
+ return path.join(process.env.OPENMSG_HOME ?? path.join(os.homedir(), ".openmsg"), "notes.json");
9
+ }
10
+
11
+ function key(agent) {
12
+ return `${agent.vendor}:${agent.id}`;
13
+ }
14
+
15
+ function readAll() {
16
+ try {
17
+ return JSON.parse(fs.readFileSync(file(), "utf8"));
18
+ } catch {
19
+ return {};
20
+ }
21
+ }
22
+
23
+ function writeAll(all) {
24
+ fs.mkdirSync(path.dirname(file()), { recursive: true });
25
+ const tmp = `${file()}.${process.pid}.tmp`;
26
+ fs.writeFileSync(tmp, JSON.stringify(all, null, 1));
27
+ fs.renameSync(tmp, file());
28
+ }
29
+
30
+ export const MAX_LENGTH = 120;
31
+
32
+ export function set(agent, text) {
33
+ const note = String(text).replace(/\s+/g, " ").trim().slice(0, MAX_LENGTH);
34
+ const all = readAll();
35
+ if (note) all[key(agent)] = { text: note, at: Date.now() };
36
+ else delete all[key(agent)];
37
+ writeAll(all);
38
+ return note || null;
39
+ }
40
+
41
+ export function get(agent) {
42
+ return readAll()[key(agent)]?.text ?? null;
43
+ }
44
+
45
+ // Add the note of each agent. A note of a session that stopped stays on disk,
46
+ // because discovery cannot always tell a stopped session from a quiet one.
47
+ export function attach(agents) {
48
+ const all = readAll();
49
+ return agents.map((a) => ({ ...a, note: all[key(a)]?.text ?? null }));
50
+ }
package/src/registry.mjs CHANGED
@@ -44,6 +44,11 @@ export function claudeAgents() {
44
44
  pid: rec.pid,
45
45
  cwd: rec.cwd,
46
46
  status: rec.status ?? "unknown",
47
+ title: claudeTitle(rec.cwd, rec.sessionId),
48
+ // A program that uses the SDK, such as a memory observer, starts a
49
+ // session too. It is not a session that a person talks to.
50
+ background: rec.entrypoint === "sdk-cli",
51
+ startedAt: rec.startedAt ?? null,
47
52
  updatedAt: rec.updatedAt ?? rec.startedAt ?? 0,
48
53
  transport: { kind: "uds", path: rec.messagingSocketPath },
49
54
  });
@@ -51,6 +56,104 @@ export function claudeAgents() {
51
56
  return out;
52
57
  }
53
58
 
59
+ // Claude Code keeps the transcript of a session in a directory that the
60
+ // working directory names, with each character that is not a letter or a digit
61
+ // changed to "-".
62
+ function claudeTranscript(cwd, sessionId) {
63
+ const root = path.join(HOME, ".claude", "projects");
64
+ const file = `${sessionId}.jsonl`;
65
+ if (cwd) {
66
+ const direct = path.join(root, cwd.replace(/[^A-Za-z0-9]/g, "-"), file);
67
+ if (fs.existsSync(direct)) return direct;
68
+ }
69
+ try {
70
+ for (const d of fs.readdirSync(root)) {
71
+ const candidate = path.join(root, d, file);
72
+ if (fs.existsSync(candidate)) return candidate;
73
+ }
74
+ } catch {
75
+ // No transcripts on this machine.
76
+ }
77
+ return null;
78
+ }
79
+
80
+ function claudeTitle(cwd, sessionId) {
81
+ if (!sessionId) return null;
82
+ const file = claudeTranscript(cwd, sessionId);
83
+ return file ? lastClaudeTitle(file) : null;
84
+ }
85
+
86
+ // Claude Code writes a short title of the conversation into the transcript,
87
+ // and it writes it again as the work goes on. A transcript can hold many
88
+ // megabytes, so this reads only the end of the file.
89
+ export function lastClaudeTitle(file, maxBytes = 1024 * 1024) {
90
+ let fd;
91
+ try {
92
+ fd = fs.openSync(file, "r");
93
+ const size = fs.fstatSync(fd).size;
94
+ const length = Math.min(size, maxBytes);
95
+ const buf = Buffer.alloc(length);
96
+ fs.readSync(fd, buf, 0, length, size - length);
97
+ const lines = buf.toString("utf8").split("\n");
98
+ for (let i = lines.length - 1; i >= 0; i--) {
99
+ if (!lines[i].includes('"ai-title"')) continue;
100
+ try {
101
+ const rec = JSON.parse(lines[i]);
102
+ if (rec.type === "ai-title" && rec.aiTitle) return String(rec.aiTitle).trim();
103
+ } catch {
104
+ // The first line of the window can be a part of a line.
105
+ }
106
+ }
107
+ } catch {
108
+ // The transcript is not there yet, or this command cannot read it.
109
+ } finally {
110
+ if (fd !== undefined) fs.closeSync(fd);
111
+ }
112
+ return null;
113
+ }
114
+
115
+ // Codex keeps the name of each thread in one index file. A later line for the
116
+ // same thread replaces an earlier one.
117
+ export function codexTitles(file = path.join(HOME, ".codex", "session_index.jsonl")) {
118
+ const titles = new Map();
119
+ let text = "";
120
+ try {
121
+ text = fs.readFileSync(file, "utf8");
122
+ } catch {
123
+ return titles;
124
+ }
125
+ for (const line of text.split("\n")) {
126
+ if (!line) continue;
127
+ try {
128
+ const rec = JSON.parse(line);
129
+ if (rec.id && rec.thread_name) titles.set(rec.id, String(rec.thread_name).trim());
130
+ } catch {
131
+ // A line that Codex writes now can be incomplete.
132
+ }
133
+ }
134
+ return titles;
135
+ }
136
+
137
+ // The first line of a rollout file tells where and when the thread started.
138
+ function codexMeta(file) {
139
+ try {
140
+ const payload = JSON.parse(fs.readFileSync(file, "utf8").split("\n", 1)[0])?.payload ?? {};
141
+ const started = Date.parse(payload.timestamp ?? "");
142
+ return { cwd: payload.cwd ?? null, startedAt: Number.isNaN(started) ? null : started };
143
+ } catch {
144
+ // The file can be empty while Codex starts.
145
+ return { cwd: null, startedAt: null };
146
+ }
147
+ }
148
+
149
+ function mtime(file) {
150
+ try {
151
+ return fs.statSync(file).mtimeMs;
152
+ } catch {
153
+ return null;
154
+ }
155
+ }
156
+
54
157
  // The pids of the programs with this exact name. On macOS, pgrep leaves out
55
158
  // the parents of its own process, so an agent that runs this command does not
56
159
  // find itself. `-a` puts them back. Linux pgrep leaves out only itself, and
@@ -111,6 +214,8 @@ export async function opencodeAgents({ maxAgeMs = 24 * 3600 * 1000 } = {}) {
111
214
  pid: Number(pid),
112
215
  cwd: s.directory ?? null,
113
216
  status: "unknown",
217
+ title: title && !title.startsWith("New session") ? title : null,
218
+ startedAt: s.time?.created ?? null,
114
219
  updatedAt: updated,
115
220
  transport: { kind: "http", base },
116
221
  });
@@ -124,6 +229,8 @@ export async function opencodeAgents({ maxAgeMs = 24 * 3600 * 1000 } = {}) {
124
229
  // that runs the session holds that file open. openmsg lists the open rollout
125
230
  // files of every Codex process, and reads the thread id from each one.
126
231
  export async function codexAgents() {
232
+ let index = null;
233
+ const titles = () => (index ??= codexTitles());
127
234
  let pids = [];
128
235
  try {
129
236
  pids = await pgrep("codex");
@@ -144,23 +251,18 @@ export async function codexAgents() {
144
251
  for (const file of paths) {
145
252
  const id = file.match(/rollout-[\dT-]+-([0-9a-f-]{36})\.jsonl$/)?.[1];
146
253
  if (!id || found.has(id)) continue;
147
- let cwd = null;
148
- let name = id.slice(-8);
149
- try {
150
- const first = fs.readFileSync(file, "utf8").split("\n", 1)[0];
151
- const meta = JSON.parse(first);
152
- cwd = meta?.payload?.cwd ?? null;
153
- if (cwd) name = `${path.basename(cwd)}-${id.slice(-4)}`;
154
- } catch {
155
- // The file can be empty while Codex starts. The thread id still works.
156
- }
254
+ // The file can be empty while Codex starts. The thread id still works.
255
+ const { cwd, startedAt } = codexMeta(file);
157
256
  found.set(id, {
158
257
  vendor: "codex",
159
258
  id,
160
- name,
259
+ name: cwd ? `${path.basename(cwd)}-${id.slice(-4)}` : id.slice(-8),
161
260
  pid: Number(pid),
162
261
  cwd,
163
262
  status: "unknown",
263
+ title: titles().get(id) ?? null,
264
+ startedAt,
265
+ updatedAt: mtime(file),
164
266
  transport: { kind: "codex-queue" },
165
267
  });
166
268
  }
@@ -173,6 +275,8 @@ export async function codexAgents() {
173
275
  // changed a moment ago belongs to a session that runs now.
174
276
  export function codexAgentsFromFiles({ maxAgeMs = 12 * 3600 * 1000 } = {}) {
175
277
  const root = path.join(HOME, ".codex", "sessions");
278
+ let index = null;
279
+ const titles = () => (index ??= codexTitles());
176
280
  const out = [];
177
281
  const walk = (dir, depth) => {
178
282
  let entries = [];
@@ -194,12 +298,8 @@ export function codexAgentsFromFiles({ maxAgeMs = 12 * 3600 * 1000 } = {}) {
194
298
  if (Date.now() - stat.mtimeMs > maxAgeMs) continue;
195
299
  const id = e.name.match(/rollout-[\dT-]+-([0-9a-f-]{36})\.jsonl$/)?.[1];
196
300
  if (!id) continue;
197
- let cwd = null;
198
- try {
199
- cwd = JSON.parse(fs.readFileSync(full, "utf8").split("\n", 1)[0])?.payload?.cwd ?? null;
200
- } catch {
201
- // An empty file belongs to a session that just started.
202
- }
301
+ // An empty file belongs to a session that just started.
302
+ const { cwd, startedAt } = codexMeta(full);
203
303
  out.push({
204
304
  vendor: "codex",
205
305
  id,
@@ -207,6 +307,9 @@ export function codexAgentsFromFiles({ maxAgeMs = 12 * 3600 * 1000 } = {}) {
207
307
  pid: null,
208
308
  cwd,
209
309
  status: "unknown",
310
+ title: titles().get(id) ?? null,
311
+ startedAt,
312
+ updatedAt: stat.mtimeMs,
210
313
  transport: { kind: "codex-queue" },
211
314
  mtimeMs: stat.mtimeMs,
212
315
  });
@@ -48,6 +48,7 @@ export function registered({ maxAgeMs = STALE_MS } = {}) {
48
48
  pid: null,
49
49
  cwd: rec.cwd,
50
50
  status: "unknown",
51
+ updatedAt: rec.lastSeen ?? null,
51
52
  transport: { kind: "mailbox" },
52
53
  });
53
54
  }