openmsg 0.7.0 → 0.8.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/src/spawn.mjs ADDED
@@ -0,0 +1,403 @@
1
+ // A session that openmsg opens, and closes. The owner is away from the
2
+ // machine, and a chat of the owner asks for work in a project where no session
3
+ // runs. openmsg starts Claude Code there, inside tmux, and the new session is
4
+ // an agent like any other: `list` shows it, and `send` reaches it.
5
+ //
6
+ // tmux gives the session a terminal, so the session runs when the screen is
7
+ // locked and no window is open. A window of Terminal.app can show it, and the
8
+ // session does not depend on that window.
9
+ import fs from "node:fs";
10
+ import path from "node:path";
11
+ import os from "node:os";
12
+ import { execFileSync, spawn as spawnProcess } from "node:child_process";
13
+ import { randomBytes } from "node:crypto";
14
+ import { claudeAgents, claudeConfigDirs } from "./registry.mjs";
15
+
16
+ const HOME = os.homedir();
17
+
18
+ // How many sessions that openmsg opened can run at one time.
19
+ export const DEFAULT_MAX = 6;
20
+ // A session that openmsg opened, with no turn for this many hours, closes.
21
+ export const DEFAULT_IDLE_HOURS = 12;
22
+
23
+ function openmsgHome() {
24
+ return process.env.OPENMSG_HOME ?? path.join(HOME, ".openmsg");
25
+ }
26
+
27
+ function file() {
28
+ return path.join(openmsgHome(), "spawned.json");
29
+ }
30
+
31
+ function read() {
32
+ try {
33
+ return JSON.parse(fs.readFileSync(file(), "utf8"));
34
+ } catch {
35
+ return {};
36
+ }
37
+ }
38
+
39
+ function save(data) {
40
+ fs.mkdirSync(path.dirname(file()), { recursive: true });
41
+ const tmp = `${file()}.${process.pid}.tmp`;
42
+ fs.writeFileSync(tmp, JSON.stringify(data, null, 1) + "\n");
43
+ fs.renameSync(tmp, file());
44
+ }
45
+
46
+ // A test runs its own tmux server, with its own socket name, so it never
47
+ // touches the sessions of the owner.
48
+ function tmux(args, opts = {}) {
49
+ const socket = process.env.OPENMSG_TMUX_SOCKET;
50
+ return execFileSync("tmux", [...(socket ? ["-L", socket] : []), ...args], {
51
+ encoding: "utf8",
52
+ stdio: ["ignore", "pipe", "pipe"],
53
+ ...opts,
54
+ }).trim();
55
+ }
56
+
57
+ function tmuxAlive(name) {
58
+ try {
59
+ tmux(["has-session", "-t", `=${name}`]);
60
+ return true;
61
+ } catch {
62
+ return false;
63
+ }
64
+ }
65
+
66
+ function pidAlive(pid) {
67
+ try {
68
+ process.kill(pid, 0);
69
+ return true;
70
+ } catch {
71
+ return false;
72
+ }
73
+ }
74
+
75
+ // The accounts of Claude Code on this machine. "default" is ~/.claude, and
76
+ // each other name is a directory ~/.claude-<name> with sessions in it.
77
+ export function accounts() {
78
+ return claudeConfigDirs().map((dir) => ({
79
+ name: dir === path.join(HOME, ".claude") ? "default" : path.basename(dir).replace(/^\.claude-/, ""),
80
+ dir,
81
+ }));
82
+ }
83
+
84
+ export function accountDir(name) {
85
+ const all = accounts();
86
+ const found = all.find((a) => a.name === (name ?? "default"));
87
+ if (!found) {
88
+ throw new Error(`no account "${name}". The accounts on this machine: ${all.map((a) => a.name).join(", ")}`);
89
+ }
90
+ return found;
91
+ }
92
+
93
+ // The account of a folder, when the command names none. The owner keeps the
94
+ // rules in ~/.claude/accounts.conf, one line for each rule: a path prefix and
95
+ // an account name. The longest prefix that matches wins. The shell of the
96
+ // owner reads the same file when the owner types `claude`.
97
+ export function accountFor(dir) {
98
+ const conf = process.env.CLAUDE_ACCOUNTS_CONF ?? path.join(HOME, ".claude", "accounts.conf");
99
+ let best = "default";
100
+ let bestLength = 0;
101
+ let lines = [];
102
+ try {
103
+ lines = fs.readFileSync(conf, "utf8").split("\n");
104
+ } catch {
105
+ return best;
106
+ }
107
+ for (const line of lines) {
108
+ const words = line.replace(/#.*/, "").trim().split(/\s+/);
109
+ if (words.length < 2) continue;
110
+ const prefix = words[0].replace(/^~(?=$|\/)/, HOME).replace(/\/+$/, "");
111
+ if ((dir + "/").startsWith(prefix + "/") && prefix.length > bestLength) {
112
+ bestLength = prefix.length;
113
+ best = words[1] === "personal" ? "default" : words[1];
114
+ }
115
+ }
116
+ return best;
117
+ }
118
+
119
+ // Claude Code asks one time for each folder: "Is this a project you trust?"
120
+ // The answer is in the state file of the account, for that folder or for a
121
+ // folder above it. A session that waits for that answer has no socket yet,
122
+ // and no message reaches it.
123
+ export function folderTrusted(account, dir) {
124
+ const state = account.name === "default"
125
+ ? path.join(HOME, ".claude.json")
126
+ : path.join(account.dir, ".claude.json");
127
+ let projects = {};
128
+ try {
129
+ projects = JSON.parse(fs.readFileSync(state, "utf8")).projects ?? {};
130
+ } catch {
131
+ return false;
132
+ }
133
+ let at = dir;
134
+ for (;;) {
135
+ if (projects[at]?.hasTrustDialogAccepted) return true;
136
+ const up = path.dirname(at);
137
+ if (up === at) return false;
138
+ at = up;
139
+ }
140
+ }
141
+
142
+ // The names that tell a program that it runs inside a session of an agent.
143
+ // The new session is not inside this one, so they do not go to it. The tmux
144
+ // server can hold them in its own environment, from the first program that
145
+ // started it, so the command removes them each time.
146
+ const INHERITED = [
147
+ "CLAUDECODE",
148
+ "CLAUDE_CODE_ENTRYPOINT",
149
+ "CLAUDE_CODE_MESSAGING_SOCKET",
150
+ "CLAUDE_CODE_MESSAGING_TOKEN",
151
+ "CLAUDE_CONFIG_DIR",
152
+ "CODEX_THREAD_ID",
153
+ "OPENCODE_SESSION_ID",
154
+ "OPENMSG_SELF",
155
+ ];
156
+
157
+ // The command that tmux runs. tmux gets each word apart, and no shell reads
158
+ // the prompt. `env` replaces itself with claude, so the process id that tmux
159
+ // gives is the process id of the session.
160
+ export function commandOf({ account, prompt = null, program = "claude" }) {
161
+ const unset = [...new Set([...INHERITED, ...Object.keys(process.env).filter((k) => k.startsWith("CLAUDE_CODE_"))])];
162
+ return [
163
+ "env",
164
+ ...unset.flatMap((k) => ["-u", k]),
165
+ ...(account.name === "default" ? [] : [`CLAUDE_CONFIG_DIR=${account.dir}`]),
166
+ program,
167
+ ...(prompt ? [prompt] : []),
168
+ ];
169
+ }
170
+
171
+ function slug(dir) {
172
+ const base = path.basename(dir).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 24);
173
+ return base || "session";
174
+ }
175
+
176
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
177
+
178
+ function screen(name) {
179
+ try {
180
+ return tmux(["capture-pane", "-p", "-t", `=${name}:`]);
181
+ } catch {
182
+ return "";
183
+ }
184
+ }
185
+
186
+ const TRUST_QUESTION = /trust this folder|Is this a project you created or one you trust/i;
187
+
188
+ // The sessions that openmsg opened and that still run. A row of a session
189
+ // that ended goes away here.
190
+ export function running() {
191
+ const data = read();
192
+ let changed = false;
193
+ for (const [name, row] of Object.entries(data)) {
194
+ if (!tmuxAlive(name) && !(row.pid && pidAlive(row.pid))) {
195
+ delete data[name];
196
+ changed = true;
197
+ }
198
+ }
199
+ if (changed) save(data);
200
+ return Object.entries(data).map(([tmuxName, row]) => ({ tmux: tmuxName, ...row }));
201
+ }
202
+
203
+ export function rowOfPid(pid) {
204
+ return running().find((r) => r.pid === pid) ?? null;
205
+ }
206
+
207
+ // Open one session. It gives the record of the new session when discovery
208
+ // finds it.
209
+ // dir the working directory. It must exist.
210
+ // account a name from accounts(). With null, accounts.conf chooses.
211
+ // prompt the first message of the session, or null.
212
+ // trustFolder true when the owner said yes to the question of Claude Code
213
+ // for a folder that the account does not trust yet.
214
+ // view true opens a window of Terminal.app that shows the session.
215
+ // program the command. A test gives a program that is not Claude.
216
+ // role "operator" for the session that a chat of the owner talks to.
217
+ // The limit and the idle rule do not count it.
218
+ export async function open({
219
+ dir,
220
+ account: accountName = null,
221
+ prompt = null,
222
+ trustFolder = false,
223
+ view = true,
224
+ program = "claude",
225
+ role = null,
226
+ max = Number(process.env.OPENMSG_SPAWN_MAX ?? DEFAULT_MAX),
227
+ waitMs = 30_000,
228
+ find = (pid) => claudeAgents().find((a) => a.pid === pid) ?? null,
229
+ } = {}) {
230
+ if (!dir) throw new Error("give the directory of the new session");
231
+ const where = path.resolve(dir.replace(/^~(?=$|\/)/, HOME));
232
+ if (!fs.existsSync(where) || !fs.statSync(where).isDirectory()) throw new Error(`${where} is not a directory`);
233
+ const real = fs.realpathSync(where);
234
+ const account = accountDir(accountName ?? accountFor(real));
235
+
236
+ // The operator is not one of the sessions of the work, so it takes no place.
237
+ const now = running().filter((r) => r.role !== "operator");
238
+ if (now.length >= max) {
239
+ throw new Error(
240
+ `${now.length} sessions that openmsg opened run now, and the limit is ${max}. ` +
241
+ `Close one first: openmsg close <session>. These run: ${now.map((r) => r.address ?? r.tmux).join(", ")}`,
242
+ );
243
+ }
244
+ const trusted = folderTrusted(account, real);
245
+ if (!trusted && !trustFolder) {
246
+ throw new Error(
247
+ `the account ${account.name} does not trust the folder ${real} yet, and Claude Code asks about it before the session starts. ` +
248
+ "That answer is a permission of your user. Ask your user first. " +
249
+ "After a yes, run the same command again with --trust-folder",
250
+ );
251
+ }
252
+
253
+ const name = `om-${slug(real)}-${randomBytes(2).toString("hex")}`;
254
+ const pid = Number(
255
+ tmux([
256
+ "new-session", "-d", "-s", name, "-x", "200", "-y", "50", "-c", real,
257
+ "-P", "-F", "#{pane_pid}",
258
+ ...commandOf({ account, prompt, program }),
259
+ ]),
260
+ );
261
+ const row = { pid, dir: real, account: account.name, ...(role ? { role } : {}), startedAt: new Date().toISOString(), address: null, session: null };
262
+ const data = read();
263
+ data[name] = row;
264
+ save(data);
265
+
266
+ // The answer to the question of Claude Code about the folder. The second
267
+ // choice is "Yes, I trust this folder".
268
+ let answered = trusted;
269
+ const until = Date.now() + waitMs;
270
+ let agent = null;
271
+ while (Date.now() < until) {
272
+ agent = find(pid);
273
+ if (agent) break;
274
+ if (!tmuxAlive(name)) break;
275
+ if (!answered && TRUST_QUESTION.test(screen(name))) {
276
+ tmux(["send-keys", "-t", `=${name}:`, "Down"]);
277
+ tmux(["send-keys", "-t", `=${name}:`, "Enter"]);
278
+ answered = true;
279
+ }
280
+ await sleep(300);
281
+ }
282
+
283
+ if (agent) {
284
+ row.address = `${agent.vendor}:${agent.name}`;
285
+ row.session = agent.id;
286
+ const again = read();
287
+ if (again[name]) {
288
+ again[name] = row;
289
+ save(again);
290
+ }
291
+ }
292
+ const viewed = view && agent ? showWindow(name) : null;
293
+ return { tmux: name, ...row, agent, viewed, alive: tmuxAlive(name) };
294
+ }
295
+
296
+ // A window of Terminal.app that shows the session. The window is only a view:
297
+ // the session runs in tmux, and it keeps running when the window closes.
298
+ // macOS asks the owner one time to let openmsg control Terminal.app.
299
+ export function showWindow(name) {
300
+ const socket = process.env.OPENMSG_TMUX_SOCKET;
301
+ const attach = `exec tmux ${socket ? `-L ${socket} ` : ""}attach -t '=${name}'`;
302
+ const script = `tell application "Terminal" to do script "${attach.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
303
+ try {
304
+ const child = spawnProcess("osascript", ["-e", script], { stdio: "ignore", detached: true });
305
+ child.unref();
306
+ return true;
307
+ } catch {
308
+ return false;
309
+ }
310
+ }
311
+
312
+ // The windows of Terminal.app that showed a session that ended. A window
313
+ // closes only when its tty is one of `ttys` and no process runs in it, so a
314
+ // window of the owner with other work stays.
315
+ export function closeWindows(ttys) {
316
+ const list = ttys.map((t) => `"${t.replace(/[^/a-z0-9]/gi, "")}"`).join(", ");
317
+ const script = [
318
+ 'tell application "Terminal"',
319
+ " repeat with w in (get every window)",
320
+ ` if ({${list}} contains (tty of tab 1 of w)) and not (busy of tab 1 of w) then close w`,
321
+ " end repeat",
322
+ "end tell",
323
+ ].join("\n");
324
+ try {
325
+ execFileSync("osascript", ["-e", script], { stdio: "ignore", timeout: 5000 });
326
+ return true;
327
+ } catch {
328
+ return false;
329
+ }
330
+ }
331
+
332
+ // Close one session. `agent` is the record of discovery, or null when the
333
+ // session has no record yet. A session that openmsg opened loses its tmux
334
+ // session too. The transcript stays, and `claude --resume <id>` opens it again.
335
+ export async function close({ agent = null, tmuxName = null, waitMs = 5000 } = {}) {
336
+ const rows = running();
337
+ const row = tmuxName
338
+ ? rows.find((r) => r.tmux === tmuxName)
339
+ : rows.find((r) => (agent?.pid && r.pid === agent.pid) || (agent?.id && r.session === agent.id));
340
+ if (tmuxName && !row) throw new Error(`openmsg opened no session ${tmuxName}, or it ended`);
341
+ const pid = agent?.pid ?? row?.pid ?? null;
342
+ if (!pid && !row) throw new Error("that session has no process on this machine");
343
+
344
+ // The terminals that show the session. Their windows close after it.
345
+ let views = [];
346
+ if (row && tmuxAlive(row.tmux)) {
347
+ try {
348
+ views = tmux(["list-clients", "-t", `=${row.tmux}`, "-F", "#{client_tty}"]).split("\n").filter(Boolean);
349
+ } catch {
350
+ // No terminal shows it.
351
+ }
352
+ try {
353
+ tmux(["kill-session", "-t", `=${row.tmux}`]);
354
+ } catch {
355
+ // It ended between the check and the command.
356
+ }
357
+ }
358
+ // tmux gives the process a hangup, and Claude Code takes a moment to stop.
359
+ // A process that still runs after that gets a TERM.
360
+ const until = Date.now() + waitMs;
361
+ while (pid && pidAlive(pid) && Date.now() < until) await sleep(200);
362
+ if (pid && pidAlive(pid)) {
363
+ process.kill(pid, "SIGTERM");
364
+ const later = Date.now() + waitMs;
365
+ while (pidAlive(pid) && Date.now() < later) await sleep(200);
366
+ }
367
+ const stopped = !(pid && pidAlive(pid));
368
+ if (views.length > 0) closeWindows(views);
369
+ if (row && stopped) {
370
+ const data = read();
371
+ delete data[row.tmux];
372
+ save(data);
373
+ }
374
+ return {
375
+ stopped,
376
+ opened: Boolean(row),
377
+ tmux: row?.tmux ?? null,
378
+ dir: row?.dir ?? agent?.cwd ?? null,
379
+ configDir: agent?.configDir ?? (row ? accountDir(row.account).dir : null),
380
+ session: agent?.id ?? row?.session ?? null,
381
+ };
382
+ }
383
+
384
+ // The sessions that openmsg opened and that had no turn for `hours`. A
385
+ // session that the owner opened never closes here.
386
+ export function idle({ hours = DEFAULT_IDLE_HOURS, now = Date.now(), find = (pid) => claudeAgents().find((a) => a.pid === pid) ?? null } = {}) {
387
+ const out = [];
388
+ for (const row of running()) {
389
+ // The operator waits for the owner, and a long wait is its work.
390
+ if (row.role === "operator") continue;
391
+ const agent = find(row.pid);
392
+ const last = agent ? Number(agent.updatedAt) || Date.parse(row.startedAt) : Date.parse(row.startedAt);
393
+ if (now - last >= hours * 3_600_000) out.push({ row, agent });
394
+ }
395
+ return out;
396
+ }
397
+
398
+ // The command that opens a closed session again, in its own account.
399
+ export function resumeCommand({ dir, configDir = null, session }) {
400
+ if (!session) return null;
401
+ const env = configDir && configDir !== path.join(HOME, ".claude") ? `CLAUDE_CONFIG_DIR=${configDir} ` : "";
402
+ return `cd ${JSON.stringify(dir ?? ".")} && ${env}claude --resume ${session}`;
403
+ }
@@ -0,0 +1,42 @@
1
+ // The identities on other machines that belong to the owner of this machine,
2
+ // such as a hosted bot that the owner talks to from a phone. The bot has its
3
+ // own keys, so the directory holds it as another person. The owner can say
4
+ // that a request from it counts as a request of the owner, as for a chat of
5
+ // section 7.2 of the spec of 0.1.
6
+ //
7
+ // Only a command of the owner sets the mark. No message changes this file.
8
+ import fs from "node:fs";
9
+ import path from "node:path";
10
+ import { home } from "./identity.mjs";
11
+
12
+ function file() {
13
+ return path.join(home(), "voice-owners.json");
14
+ }
15
+
16
+ function read() {
17
+ try {
18
+ return JSON.parse(fs.readFileSync(file(), "utf8"));
19
+ } catch {
20
+ return {};
21
+ }
22
+ }
23
+
24
+ function save(data) {
25
+ fs.mkdirSync(path.dirname(file()), { recursive: true });
26
+ fs.writeFileSync(file(), JSON.stringify(data, null, 1) + "\n", { mode: 0o600 });
27
+ }
28
+
29
+ export function set(ownerId, label, on) {
30
+ const data = read();
31
+ if (on) data[ownerId] = { label, at: new Date().toISOString() };
32
+ else delete data[ownerId];
33
+ save(data);
34
+ }
35
+
36
+ export function speaksForOwner(ownerId) {
37
+ return Boolean(ownerId && read()[ownerId]);
38
+ }
39
+
40
+ export function list() {
41
+ return Object.entries(read()).map(([ownerId, row]) => ({ ownerId, ...row }));
42
+ }