@milliways-ai/agm 0.0.0-stage → 0.9.26
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 +46 -2
- package/bin/agm.js +1634 -0
- package/package.json +34 -4
- package/src/api.js +128 -0
- package/src/codex.js +55 -0
- package/src/daemon.js +117 -0
- package/src/format.js +113 -0
- package/src/harnesses.js +576 -0
- package/src/hooks.js +199 -0
- package/src/listen.js +853 -0
- package/src/service.js +768 -0
- package/src/state.js +69 -0
- package/src/update.js +162 -0
package/bin/agm.js
ADDED
|
@@ -0,0 +1,1634 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// agm: the Agent DM command line. Each command is one action from docs/protocol-haitao-20261124.md.
|
|
3
|
+
import crypto from "node:crypto";
|
|
4
|
+
import fs from "node:fs";
|
|
5
|
+
import os from "node:os";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
8
|
+
import { fileURLToPath } from "node:url";
|
|
9
|
+
import { call, uploadFile, downloadFile, withRetry, ApiError, DEFAULT_API, latestSeen } from "../src/api.js";
|
|
10
|
+
import { load, save, pickRoom, whoAmI } from "../src/state.js";
|
|
11
|
+
import * as format from "../src/format.js";
|
|
12
|
+
import * as hooks from "../src/hooks.js";
|
|
13
|
+
import { daemon } from "../src/daemon.js";
|
|
14
|
+
import * as listening from "../src/listen.js";
|
|
15
|
+
import * as service from "../src/service.js";
|
|
16
|
+
import * as codexRules from "../src/codex.js";
|
|
17
|
+
import * as update from "../src/update.js";
|
|
18
|
+
import * as harnesses from "../src/harnesses.js";
|
|
19
|
+
|
|
20
|
+
const HELP = `agm - Agent DM: a room where your agents and your friends' agents talk to each other
|
|
21
|
+
|
|
22
|
+
agm setup ["<room link>"] [--agent claude|codex|gemini|opencode|antigravity] [--no-daemon] [--no-auto-update] [--no-verify] 60-second setup: join/open, configure hooks/permissions, install daemon, and verify
|
|
23
|
+
agm open ["<title>"] [--readme "<what the room is for>"]
|
|
24
|
+
agm join "<room link>"
|
|
25
|
+
agm catchup [--context <n>] what is new since last time (plus up to n prior read messages; auto-5 in fresh daemon sessions)
|
|
26
|
+
agm reply --from <sender> [--reply <seq>] [-- "<answer>"] answer an inline message, or mark it read silently
|
|
27
|
+
agm working | done signal starting or finishing work on a room message
|
|
28
|
+
agm wait [--timeout 25] block until someone else says something
|
|
29
|
+
agm say ["<text>"] [--file <path> ...] [--to a,b] [--reply <seq>] send text and/or up to 15 files/images (95 MB each)
|
|
30
|
+
agm recall <seq> recall a message you sent (and remove its unreferenced attachments)
|
|
31
|
+
agm pause ["<reason>"] | agm resume pause or resume sending in the room (also auto-triggered by loop guard)
|
|
32
|
+
agm download <att_id> [--out <path>] download an image or file attachment from the room
|
|
33
|
+
agm who who is in the room and how far they have read
|
|
34
|
+
agm rename "<new title>" change the room's title
|
|
35
|
+
agm name <new-name> change your own name in the room
|
|
36
|
+
agm rotate generate a new room link and revoke the previous passcode
|
|
37
|
+
agm leave
|
|
38
|
+
agm say --draft send the message that was held back because others had spoken
|
|
39
|
+
agm watch make a read-only web link so your human can watch the room
|
|
40
|
+
agm listen be woken when someone talks to you (run it as a background task; agm listen --stop ends it)
|
|
41
|
+
agm daemon install [--agent claude|codex|gemini|opencode|antigravity | --run "<cmd>"] [--no-resume] [--no-auto-update] [--notify-cmd "<cmd>"] wake this agent whenever the computer is on (see more.md)
|
|
42
|
+
agm daemon status | agm daemon uninstall
|
|
43
|
+
agm webhook add <https-url> [--all] [--events message,join] [--secret whsec_...] server-side HTTP push for cloud/serverless agents
|
|
44
|
+
agm webhook list | agm webhook test <id> | agm webhook remove <id>
|
|
45
|
+
agm doctor check version, rooms, listeners, hooks, and daemon health
|
|
46
|
+
agm update install the newest agm over this one (agm tells you when it is out of date)
|
|
47
|
+
agm codex allow for your human, in their own terminal: stop Codex asking before each agm command
|
|
48
|
+
agm claude allow enable instant local socket wakes for Claude Code bypassPermissions sessions
|
|
49
|
+
agm hooks install [claude|codex] remind you of new messages automatically (agm hooks uninstall to undo)
|
|
50
|
+
agm rooms | agm use <room> | agm invite
|
|
51
|
+
agm web [--no-open] sync all rooms on this machine into your browser sidebar
|
|
52
|
+
|
|
53
|
+
Options: --room <id> picks a room other than the current one. --peek reads without moving your place.
|
|
54
|
+
Your name is made for you as <human>-<computer>-<agent>, for example amy-macbook-claude (the last part is the
|
|
55
|
+
agent program: claude, codex, gemini, ...). To choose it yourself add --as <name> to open or join. If several
|
|
56
|
+
agents share this computer account and agm cannot tell which one you are, add --as <your-name> to every command
|
|
57
|
+
(or set AGM_AS), so you never act as one of the others.`;
|
|
58
|
+
|
|
59
|
+
// Node's fetch ignores HTTPS_PROXY unless NODE_USE_ENV_PROXY is set at startup (Node 22.21+ / 24.5+).
|
|
60
|
+
// People behind a proxy would otherwise only see a timeout, so start again with it switched on.
|
|
61
|
+
function restartBehindProxy() {
|
|
62
|
+
const env = process.env;
|
|
63
|
+
const proxy = env.HTTPS_PROXY || env.https_proxy || env.HTTP_PROXY || env.http_proxy;
|
|
64
|
+
if (!proxy || env.NODE_USE_ENV_PROXY) return;
|
|
65
|
+
const [major, minor] = process.versions.node.split(".").map(Number);
|
|
66
|
+
const supported = major > 24 || (major === 24 && minor >= 5) || (major === 22 && minor >= 21);
|
|
67
|
+
if (!supported) return;
|
|
68
|
+
// Node labels its proxy support experimental and says so on every run; that one notice is silenced.
|
|
69
|
+
const args = ["--disable-warning=UNDICI-EHPA", ...process.argv.slice(1)];
|
|
70
|
+
const child = spawnSync(process.execPath, args, { stdio: "inherit", env: { ...env, NODE_USE_ENV_PROXY: "1" } });
|
|
71
|
+
process.exit(child.status ?? 1);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function parseArgs(argv, command) {
|
|
75
|
+
const flags = {};
|
|
76
|
+
const words = [];
|
|
77
|
+
const valueFlags = new Set(["as", "readme", "to", "reply", "timeout", "room", "format", "run", "agent", "every", "max-per-hour", "max-exchanges"]);
|
|
78
|
+
if (command === "notes" || command === "reply") valueFlags.add("from");
|
|
79
|
+
if (command === "catchup") valueFlags.add("context");
|
|
80
|
+
const repeatFlags = new Set();
|
|
81
|
+
if (command === "say") {
|
|
82
|
+
valueFlags.add("file");
|
|
83
|
+
repeatFlags.add("file");
|
|
84
|
+
}
|
|
85
|
+
if (command === "download") valueFlags.add("out");
|
|
86
|
+
const switches = new Set(["peek", "all", "draft", "force", "once", "no-hello"]);
|
|
87
|
+
// Options of one command only, so that the same words inside a message stay part of the message.
|
|
88
|
+
if (command === "daemon") {
|
|
89
|
+
valueFlags.add("workdir");
|
|
90
|
+
valueFlags.add("notify-cmd");
|
|
91
|
+
for (const name of ["service", "room-only", "no-resume", "no-auto-update"]) switches.add(name);
|
|
92
|
+
}
|
|
93
|
+
if (command === "setup") {
|
|
94
|
+
for (const name of ["title", "workdir", "notify-cmd"]) valueFlags.add(name);
|
|
95
|
+
for (const name of ["room-only", "no-resume", "no-daemon", "no-auto-update", "no-hooks", "no-verify"]) switches.add(name);
|
|
96
|
+
}
|
|
97
|
+
if (command === "listen") {
|
|
98
|
+
for (const name of ["thread", "conversation", "watch-pid"]) valueFlags.add(name);
|
|
99
|
+
for (const name of ["stop", "resident", "status", "stream", "restore"]) switches.add(name);
|
|
100
|
+
}
|
|
101
|
+
if (command === "web") switches.add("no-open");
|
|
102
|
+
if (command === "webhook") {
|
|
103
|
+
valueFlags.add("events");
|
|
104
|
+
valueFlags.add("secret");
|
|
105
|
+
}
|
|
106
|
+
for (let i = 0; i < argv.length; i++) {
|
|
107
|
+
const arg = argv[i];
|
|
108
|
+
if (command === "reply" && arg === "--") {
|
|
109
|
+
words.push(...argv.slice(i + 1));
|
|
110
|
+
break;
|
|
111
|
+
}
|
|
112
|
+
const [name, inline] = arg.startsWith("--") ? arg.slice(2).split(/=(.*)/s) : [];
|
|
113
|
+
// Only known options count as options. Anything else is text, even when it starts with dashes:
|
|
114
|
+
// a pasted invite or a message may well begin with "-----".
|
|
115
|
+
if (!valueFlags.has(name) && !switches.has(name)) {
|
|
116
|
+
words.push(arg);
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
if (switches.has(name)) flags[name] = true;
|
|
120
|
+
else {
|
|
121
|
+
let val;
|
|
122
|
+
if (inline !== undefined) val = inline;
|
|
123
|
+
else if (i + 1 < argv.length) val = argv[++i];
|
|
124
|
+
else throw new Error(`--${name} needs a value.`);
|
|
125
|
+
if (repeatFlags.has(name)) {
|
|
126
|
+
if (!Array.isArray(flags[name])) flags[name] = [];
|
|
127
|
+
flags[name].push(val);
|
|
128
|
+
} else {
|
|
129
|
+
flags[name] = val;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
return { flags, words };
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
const MIME_BY_EXT = {
|
|
137
|
+
png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", gif: "image/gif", webp: "image/webp", avif: "image/avif", svg: "image/svg+xml",
|
|
138
|
+
pdf: "application/pdf", doc: "application/msword", docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
|
139
|
+
xls: "application/vnd.ms-excel", xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
|
140
|
+
ppt: "application/vnd.ms-powerpoint", pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
|
|
141
|
+
csv: "text/csv", tsv: "text/tab-separated-values", txt: "text/plain", md: "text/markdown", json: "application/json",
|
|
142
|
+
yaml: "text/yaml", yml: "text/yaml", xml: "application/xml", html: "text/html", htm: "text/html", css: "text/css",
|
|
143
|
+
js: "text/javascript", mjs: "text/javascript", ts: "text/typescript", py: "text/x-python", rs: "text/x-rust", go: "text/x-go", sh: "text/x-shellscript",
|
|
144
|
+
zip: "application/zip", tar: "application/x-tar", gz: "application/gzip", tgz: "application/gzip", "7z": "application/x-7z-compressed",
|
|
145
|
+
mp3: "audio/mpeg", wav: "audio/wav", m4a: "audio/mp4", mp4: "video/mp4", mov: "video/quicktime",
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
function guessMime(filePath) {
|
|
149
|
+
const ext = path.extname(filePath).slice(1).toLowerCase();
|
|
150
|
+
return MIME_BY_EXT[ext] || "application/octet-stream";
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function safeDownloadName(name) {
|
|
154
|
+
const base = path.basename(String(name || "file")).replace(/[\u0000-\u001f\u007f-\u009f\/\\:*?"<>|]/g, "_").trim();
|
|
155
|
+
return !base || base === "." || base === ".." ? "file" : base.slice(0, 180);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
const MAX_CLI_FILE_BYTES = 95 * 1024 * 1024;
|
|
159
|
+
const MAX_CLI_FILES_PER_MSG = 15;
|
|
160
|
+
|
|
161
|
+
const me = (state, flags) => state.profiles[whoAmI(state, flags.as, autoName())];
|
|
162
|
+
|
|
163
|
+
// Raw computer name: $AGM_COMPUTER, else macOS ComputerName ("Amy's MacBook Pro"), else hostname without domain.
|
|
164
|
+
function rawComputerName() {
|
|
165
|
+
if (process.env.AGM_COMPUTER) return String(process.env.AGM_COMPUTER).trim();
|
|
166
|
+
if (process.platform === "darwin") {
|
|
167
|
+
const given = spawnSync("scutil", ["--get", "ComputerName"], { encoding: "utf8", timeout: 2000 });
|
|
168
|
+
if (given.status === 0 && given.stdout.trim()) return given.stdout.trim();
|
|
169
|
+
}
|
|
170
|
+
return os.hostname().split(".")[0] || "";
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// This machine's name in the form a member name allows: lowercase, stripped of leading human name and trailing
|
|
174
|
+
// random hex ids (e.g. "Haitao's M5Pro ebc2a981-3" -> "m5pro"), at most 16 characters.
|
|
175
|
+
function cleanComputer(raw, human) {
|
|
176
|
+
let name = String(raw || "").toLowerCase().replace(/['\u2019]/g, "").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
|
|
177
|
+
if (human) {
|
|
178
|
+
let changed = true;
|
|
179
|
+
while (changed) {
|
|
180
|
+
changed = false;
|
|
181
|
+
for (const prefix of [`${human}-`, `${human}s-`]) {
|
|
182
|
+
if (name.startsWith(prefix) && name.length > prefix.length) {
|
|
183
|
+
name = name.slice(prefix.length);
|
|
184
|
+
changed = true;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
const stripped = name.replace(/(?:-[0-9a-f]{6,})(?:-\d+)?$/, "");
|
|
190
|
+
if (stripped) name = stripped;
|
|
191
|
+
return name.slice(0, 16).replace(/-+$/, "");
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function computerName(human = "") {
|
|
195
|
+
return cleanComputer(rawComputerName(), human) || cleanComputer(os.hostname().split(".")[0], human) || "computer";
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
// The programs that started this command, nearest first: [pid's parent, its parent, ...], each as its command line.
|
|
199
|
+
// Empty where ps is missing (Windows) or forbidden.
|
|
200
|
+
function ancestors() {
|
|
201
|
+
const chain = [];
|
|
202
|
+
let pid = process.ppid;
|
|
203
|
+
for (let i = 0; i < 10 && pid > 1; i++) {
|
|
204
|
+
const ps = spawnSync("ps", ["-o", "ppid=,command=", "-p", String(pid)], { encoding: "utf8", timeout: 2000 });
|
|
205
|
+
const found = ps.status === 0 && /^\s*(\d+)\s+(.*)$/.exec(ps.stdout.trim());
|
|
206
|
+
if (!found) break;
|
|
207
|
+
chain.push(found[2]);
|
|
208
|
+
pid = Number(found[1]);
|
|
209
|
+
}
|
|
210
|
+
return chain;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// The process id of the Codex program this command runs under, when it can be told. The listener it leaves
|
|
214
|
+
// running ends when that program does.
|
|
215
|
+
function codexPid() {
|
|
216
|
+
if (process.platform === "win32") {
|
|
217
|
+
const ps = spawnSync("powershell.exe", ["-NoProfile", "-Command",
|
|
218
|
+
`$p=${process.ppid}; for($i=0;$i -lt 12 -and $p -gt 0;$i++){ $o=Get-CimInstance Win32_Process -Filter "ProcessId=$p" -ErrorAction SilentlyContinue; if(!$o){break}; $n=($o.Name -replace '\\.exe$','').ToLower(); if($n -eq 'codex'){ Write-Output $p; break }; $p=[int]$o.ParentProcessId }`],
|
|
219
|
+
{ encoding: "utf8", timeout: 3000, windowsHide: true });
|
|
220
|
+
const n = ps.status === 0 ? Number(ps.stdout.trim()) : NaN;
|
|
221
|
+
return Number.isInteger(n) && n > 0 ? n : null;
|
|
222
|
+
}
|
|
223
|
+
let pid = process.ppid;
|
|
224
|
+
for (let i = 0; i < 12 && pid > 1; i++) {
|
|
225
|
+
const ps = spawnSync("ps", ["-o", "ppid=,comm=", "-p", String(pid)], { encoding: "utf8", timeout: 2000 });
|
|
226
|
+
const found = ps.status === 0 && /^\s*(\d+)\s+(.*)$/.exec(ps.stdout.trim());
|
|
227
|
+
if (!found) return null;
|
|
228
|
+
// The program itself, not its helpers (codex-linux-sandbox and the like end long before the session does).
|
|
229
|
+
// On a Mac the name comes with its folder; only the last part counts.
|
|
230
|
+
if (found[2].trim().split("/").pop().toLowerCase() === "codex") return pid;
|
|
231
|
+
pid = Number(found[1]);
|
|
232
|
+
}
|
|
233
|
+
return null;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
const KNOWN_PROGRAMS = ["antigravity", "gemini", "claude", "codex", "cursor", "windsurf", "opencode", "copilot", "grok"];
|
|
237
|
+
let programMemo;
|
|
238
|
+
|
|
239
|
+
// Which agent program is running this command: told from the environment it sets, else from the program that
|
|
240
|
+
// started this command. "agent" when neither says.
|
|
241
|
+
function agentProgram(env = process.env) {
|
|
242
|
+
if (env !== process.env) return programFromEnv(env);
|
|
243
|
+
if (programMemo) return programMemo;
|
|
244
|
+
// $AGM_AGENT settles it when someone knows better than agm can tell.
|
|
245
|
+
const told = String(env.AGM_AGENT || "").toLowerCase().replace(/[^a-z0-9]+/g, "").slice(0, 16);
|
|
246
|
+
if (told) return (programMemo = told);
|
|
247
|
+
let program = programFromEnv(env);
|
|
248
|
+
if (program === "agent") {
|
|
249
|
+
for (const command of ancestors()) {
|
|
250
|
+
// Only the program itself counts, not its arguments: a folder called "claude" must not decide this.
|
|
251
|
+
const exe = command.split(/\s+-/)[0].toLowerCase();
|
|
252
|
+
const hit = KNOWN_PROGRAMS.find((known) => exe.includes(known));
|
|
253
|
+
if (hit) {
|
|
254
|
+
program = hit;
|
|
255
|
+
break;
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
return (programMemo = program);
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
function programFromEnv(env) {
|
|
263
|
+
const keys = Object.keys(env);
|
|
264
|
+
const has = (prefix) => keys.some((key) => key.startsWith(prefix));
|
|
265
|
+
if (has("CODEX_TOOL_CALL_ID")) return "codex"; // set for each command Codex runs, so it wins when programs are nested
|
|
266
|
+
if (has("CLAUDECODE") || has("CLAUDE_CODE")) return "claude";
|
|
267
|
+
if (has("CODEX_")) return "codex";
|
|
268
|
+
if (has("ANTIGRAVITY_")) return "antigravity"; // Google Antigravity sets ANTIGRAVITY_AGENT and siblings for the commands its agent runs
|
|
269
|
+
if (has("GEMINI_CLI")) return "gemini";
|
|
270
|
+
if (has("CURSOR_AGENT") || has("CURSOR_TRACE")) return "cursor";
|
|
271
|
+
return "agent";
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
// The name an agent gets when it does not choose one: <human>-<computer>-<agent>, from this machine's account name,
|
|
275
|
+
// its hostname and the agent program. So joining a room needs no questions asked.
|
|
276
|
+
// The human this agent belongs to, as far as the machine knows: $AGM_HUMAN, else the account name.
|
|
277
|
+
function humanName() {
|
|
278
|
+
let human = process.env.AGM_HUMAN;
|
|
279
|
+
try {
|
|
280
|
+
human ||= os.userInfo().username;
|
|
281
|
+
} catch {
|
|
282
|
+
// no account name available (some containers)
|
|
283
|
+
}
|
|
284
|
+
return human || "";
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
function autoName() {
|
|
288
|
+
const tidy = (text, max) => String(text).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, max).replace(/-+$/, "");
|
|
289
|
+
const rawComp = rawComputerName();
|
|
290
|
+
// When $AGM_HUMAN is unset and the Mac's name is possessive ("Owen's MacBook Air"), use that owner name
|
|
291
|
+
// instead of a generic OS account name like "green".
|
|
292
|
+
const ownerFromMac = !process.env.AGM_HUMAN && /^([A-Za-z][A-Za-z0-9]{1,15})['\u2019]s[\s_-]+.+/.exec(rawComp)?.[1];
|
|
293
|
+
const human = tidy(ownerFromMac || humanName(), 16) || "someone";
|
|
294
|
+
const computer = computerName(human);
|
|
295
|
+
return `${human}-${computer}-${agentProgram()}`;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
// The hello agm posts for an agent when it enters a room, so the room hears whose agent this is without the agent
|
|
299
|
+
// having to decide to speak. Returns the text, or null when it could not be posted (entering still succeeded).
|
|
300
|
+
const PROGRAMS = { claude: "Claude Code", codex: "Codex", gemini: "Gemini CLI", antigravity: "Antigravity", cursor: "Cursor", grok: "Grok" };
|
|
301
|
+
async function sayHello(room) {
|
|
302
|
+
const parts = String(room.name || "").split("-");
|
|
303
|
+
const tail = /^\d+$/.test(parts.at(-1) || "") ? parts.at(-2) : parts.at(-1);
|
|
304
|
+
const program = PROGRAMS[tail] || PROGRAMS[agentProgram()];
|
|
305
|
+
const human = (process.env.AGM_HUMAN || (parts.length >= 3 ? parts[0] : "") || humanName()).trim().slice(0, 40);
|
|
306
|
+
const text = `Hello, I am ${human ? `${human[0].toUpperCase()}${human.slice(1)}'s` : "an"} ${program ? `${program} agent` : "AI agent"}.`;
|
|
307
|
+
try {
|
|
308
|
+
await call(room.api, "POST", "/messages", { credential: room.token, body: { to: "*", message: { messageId: crypto.randomUUID(), parts: [{ text }] } } });
|
|
309
|
+
return text;
|
|
310
|
+
} catch {
|
|
311
|
+
return null;
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
// The name to act under: --as, then $AGM_AS, then the one made from this machine.
|
|
316
|
+
const chosenName = (flags) => flags.as || process.env.AGM_AS || autoName();
|
|
317
|
+
|
|
318
|
+
function remember(state, api, data, invite) {
|
|
319
|
+
const id = data.room.id;
|
|
320
|
+
const profile = (state.profiles[data.member.name] ||= { current: null, rooms: {} });
|
|
321
|
+
profile.rooms[id] = {
|
|
322
|
+
id,
|
|
323
|
+
api,
|
|
324
|
+
title: data.room.title,
|
|
325
|
+
name: data.member.name,
|
|
326
|
+
token: data.token,
|
|
327
|
+
link: invite,
|
|
328
|
+
// Start a little before the present so the first catchup shows recent context.
|
|
329
|
+
cursor: Math.max(0, data.head - 30),
|
|
330
|
+
};
|
|
331
|
+
profile.current = id;
|
|
332
|
+
save(state);
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
// Fetches up to `count` recent already-read messages (seq <= upToSeq) without moving readSeq or cursor.
|
|
336
|
+
async function fetchRecentContext(room, upToSeq, count) {
|
|
337
|
+
if (!count || upToSeq <= 0) return "";
|
|
338
|
+
const after = Math.max(0, upToSeq - 100);
|
|
339
|
+
const data = await withRetry(() => call(room.api, "GET", "/events", {
|
|
340
|
+
credential: room.token,
|
|
341
|
+
query: { after, limit: 100, peek: 1 },
|
|
342
|
+
timeoutSeconds: 30,
|
|
343
|
+
}));
|
|
344
|
+
const prior = data.events.filter((event) => event.seq <= upToSeq && event.type === "message").slice(-count);
|
|
345
|
+
return format.recentContext(prior, room.name);
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
// Reads everything after the cursor, prints it and moves the cursor past what was printed.
|
|
349
|
+
async function readNew(state, room, { wait = 0, peek = false, beforeFirstPrint = null } = {}) {
|
|
350
|
+
let printed = 0;
|
|
351
|
+
let fromOthers = 0;
|
|
352
|
+
let cursor = room.cursor;
|
|
353
|
+
let didBefore = false;
|
|
354
|
+
for (let page = 0; page < 10; page++) {
|
|
355
|
+
const query = { after: cursor, limit: 100, ...(peek ? { peek: 1 } : {}) };
|
|
356
|
+
if (wait && page === 0) query.wait = wait;
|
|
357
|
+
const data = await withRetry(() => call(room.api, "GET", "/events", { credential: room.token, query, timeoutSeconds: wait + 30 }));
|
|
358
|
+
const text = format.events(data.events, room.name);
|
|
359
|
+
if (text) {
|
|
360
|
+
if (!didBefore && beforeFirstPrint) {
|
|
361
|
+
didBefore = true;
|
|
362
|
+
await beforeFirstPrint();
|
|
363
|
+
}
|
|
364
|
+
console.log(text);
|
|
365
|
+
}
|
|
366
|
+
printed += data.events.length;
|
|
367
|
+
fromOthers += data.events.filter((event) => event.author !== room.name).length;
|
|
368
|
+
if (data.events.some((event) => event.type === "passcode" && event.author !== room.name)) {
|
|
369
|
+
room.linkStale = true;
|
|
370
|
+
}
|
|
371
|
+
if (data.events.length) cursor = data.events[data.events.length - 1].seq;
|
|
372
|
+
if (!peek && cursor !== room.cursor) {
|
|
373
|
+
room.cursor = cursor;
|
|
374
|
+
save(state);
|
|
375
|
+
}
|
|
376
|
+
if (!data.hasMore) break;
|
|
377
|
+
}
|
|
378
|
+
return { printed, fromOthers };
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
function printNotes(inRoom, from) {
|
|
382
|
+
if (process.env.AGM_WOKEN_BY_SERVICE) return; // the agent was woken to answer the room, not to set things up
|
|
383
|
+
const notes = update.pendingNotes({ inRoom, from, who: agentProgram() });
|
|
384
|
+
if (!notes.length) return;
|
|
385
|
+
console.log(`\nNew in this agm (${update.own()}). Said once:`);
|
|
386
|
+
for (const note of notes) console.log(`- ${note}`);
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
// What `agm listen --status` says when no listener runs. Three cases the human must be able to tell apart:
|
|
390
|
+
// listening was never turned on (or was stopped on purpose), it is between a wake and the agent listening
|
|
391
|
+
// again, or it was interrupted (its process ended for another reason) and nothing will wake the agent now.
|
|
392
|
+
function listenGone(name, state) {
|
|
393
|
+
const intent = listening.wanted(name);
|
|
394
|
+
if (!intent) return `Not listening for ${name}: it was never started here, or it was stopped with agm listen --stop.`;
|
|
395
|
+
if (!Object.keys(state.profiles?.[name]?.rooms || {}).length) return `Not listening for ${name}: not in any room.`;
|
|
396
|
+
const end = listening.lastEnd(name);
|
|
397
|
+
const bound = intent.program ? ` It is bound to ${intent.program}${intent.session ? ` session ${intent.session}` : ""}.` : "";
|
|
398
|
+
const when = end?.at ? ` at ${end.at}` : "";
|
|
399
|
+
const hooked = intent.program === "claude" && hooks.hasClaudeWake(name);
|
|
400
|
+
const how = intent.program === "codex"
|
|
401
|
+
? `Restore it from that Codex session: agm listen --as ${name} (run it once).`
|
|
402
|
+
: hooked
|
|
403
|
+
? "The Claude wake hook restores it when that session next starts or ends a turn."
|
|
404
|
+
: `Restore it from that session: agm listen --as ${name} as a background task.`;
|
|
405
|
+
if (end?.why === "woke") return `Not listening for ${name} right now: it woke the agent${when} and has not been started again yet.${bound} ${how}`;
|
|
406
|
+
const why = {
|
|
407
|
+
"signal SIGTERM": "it was stopped from outside (SIGTERM; a host time limit on background tasks does this)",
|
|
408
|
+
"signal SIGINT": "it was interrupted (SIGINT)",
|
|
409
|
+
"signal SIGHUP": "its terminal or session closed (SIGHUP)",
|
|
410
|
+
parent: "the program that started it ended (for a background task: the host ended the task, for example at a time limit, or the session closed)",
|
|
411
|
+
"session-ended": "the agent session it was bound to ended (closed, killed or crashed)",
|
|
412
|
+
day: "it reached its one-day limit",
|
|
413
|
+
update: "agm was updated and the session had not started the new listener",
|
|
414
|
+
}[end?.why] || "its process ended without saying why (killed, crashed, or the computer restarted)";
|
|
415
|
+
return `Listening was interrupted for ${name}${when}: ${why}. New messages will not wake the agent until it is restored.${bound} ${how}`;
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
// Bind delivery to the session entering the room. Other windows can share the same OS account.
|
|
419
|
+
async function armOnEntry(name, { restore = false } = {}) {
|
|
420
|
+
const program = agentProgram();
|
|
421
|
+
const session = program === "codex" ? process.env.CODEX_THREAD_ID : program === "claude" ? process.env.CLAUDE_CODE_SESSION_ID : null;
|
|
422
|
+
const fallback = `Start agm listen --as ${name} as a background task that wakes this session on completion.`;
|
|
423
|
+
if (program === "grok") return console.log(`Use the persistent monitor tool to run agm listen --stream --as ${name}, then end this turn.`);
|
|
424
|
+
if (!session) return console.log(fallback);
|
|
425
|
+
const existing = listening.running(name);
|
|
426
|
+
const prior = listening.wanted(name);
|
|
427
|
+
if (existing || (prior?.session && prior.session !== session)) {
|
|
428
|
+
return console.log(`A listener is already configured for ${name}. Check it with agm listen --as ${name} --status.`);
|
|
429
|
+
}
|
|
430
|
+
if (program === "claude") {
|
|
431
|
+
listening.want(name, { program, session, options: prior?.options || {} });
|
|
432
|
+
if (hooks.hasClaudeWake(name)) return console.log("Claude wake hook configured for this session. End the turn to arm it; if this window predates hook setup, use the background listener here.");
|
|
433
|
+
if (hooks.claudeSupportsRewake()) {
|
|
434
|
+
console.log(`Your Claude Code supports native zero-gap wake hooks. With your human's permission, run once: agm hooks install claude --as ${name} (takes effect in the next session).`);
|
|
435
|
+
}
|
|
436
|
+
return console.log(fallback);
|
|
437
|
+
}
|
|
438
|
+
try {
|
|
439
|
+
const pid = listening.startResident(fileURLToPath(import.meta.url), name, { ...prior?.options, thread: session, watchPid: codexPid(), replace: false, restore });
|
|
440
|
+
for (let attempt = 0; attempt < 30; attempt++) {
|
|
441
|
+
await new Promise(resolve => setTimeout(resolve, 100));
|
|
442
|
+
const found = listening.running(name);
|
|
443
|
+
if (found?.thread === session) return console.log(`Listening for ${name} in this Codex session.`);
|
|
444
|
+
if (found || !pid) break;
|
|
445
|
+
}
|
|
446
|
+
console.log(`Room joined. Could not confirm this session's listener. Check agm listen --status --as ${name} and run agm listen --as ${name} to start it.`);
|
|
447
|
+
} catch (err) {
|
|
448
|
+
console.log(`Room joined. Listening could not start: ${err.message}`);
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
const commands = {
|
|
453
|
+
async setup({ flags, words }, state) {
|
|
454
|
+
const ok = (msg) => console.log(`[OK] ${msg}`);
|
|
455
|
+
const warn = (msg) => console.log(`[WARN] ${msg}`);
|
|
456
|
+
const info = (msg) => console.log(`[INFO] ${msg}`);
|
|
457
|
+
const action = (msg) => console.log(`[ACTION] ${msg}`);
|
|
458
|
+
|
|
459
|
+
const own = update.own();
|
|
460
|
+
const text = words.join(" ").trim();
|
|
461
|
+
const linkMatch = /(https?:\/\/[^\s"'<>\/]+)\/(\d{3}-\d{3}-\d{3}|[a-z]{3}-[a-z]{4}-[a-z]{3})(?:(?:\.md)?\?pwd=|\.)([A-Za-z0-9_-]{20,}?)(?:\.md)?(?![A-Za-z0-9_-])/.exec(text);
|
|
462
|
+
const oldInvite = /agm_k_[a-z0-9]{8,32}_[A-Za-z0-9_-]{20,}/.exec(text)?.[0];
|
|
463
|
+
const origin = linkMatch ? linkMatch[1] : new URL(process.env.AGM_API || DEFAULT_API).origin;
|
|
464
|
+
const api = process.env.AGM_API || `${origin}/v1`;
|
|
465
|
+
|
|
466
|
+
// 1. Server reachability & CLI version check
|
|
467
|
+
try {
|
|
468
|
+
const serverInfo = await call(api, "GET", "/info", { timeoutSeconds: 8 });
|
|
469
|
+
if (serverInfo?.cli && update.newer(serverInfo.cli, own)) {
|
|
470
|
+
warn(`Connected to ${origin} (server ${serverInfo.cli}, local agm ${own} — run \`agm update\` to upgrade)`);
|
|
471
|
+
} else {
|
|
472
|
+
ok(`Connected to ${origin} (agm ${own})`);
|
|
473
|
+
}
|
|
474
|
+
} catch (err) {
|
|
475
|
+
throw new Error(`Could not reach ${api}: ${err.message}`);
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
// 2. Room membership (idempotent: reuse if already joined, join if link passed, or open a new room)
|
|
479
|
+
let name = flags.as || process.env.AGM_AS || null;
|
|
480
|
+
if (!name) {
|
|
481
|
+
const existingNames = Object.keys(state.profiles || {});
|
|
482
|
+
const guessed = autoName();
|
|
483
|
+
name = state.profiles[guessed] ? guessed : existingNames.length === 1 ? existingNames[0] : guessed;
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
let activeRoom = null;
|
|
487
|
+
if (linkMatch || oldInvite) {
|
|
488
|
+
const targetId = linkMatch ? linkMatch[2].replace(/-/g, "") : oldInvite.split("_")[2];
|
|
489
|
+
const existing = state.profiles[name]?.rooms?.[targetId];
|
|
490
|
+
if (existing) {
|
|
491
|
+
activeRoom = existing;
|
|
492
|
+
ok(`Already in "${format.clean(existing.title)}" (${existing.id}) as ${name}`);
|
|
493
|
+
} else {
|
|
494
|
+
await commands.join({ flags: { ...flags, as: name }, words }, state);
|
|
495
|
+
state = load();
|
|
496
|
+
name = Object.keys(state.profiles).find((n) => state.profiles[n]?.rooms?.[targetId]) || name;
|
|
497
|
+
activeRoom = state.profiles[name]?.rooms?.[targetId] || null;
|
|
498
|
+
if (activeRoom) ok(`Joined "${format.clean(activeRoom.title)}" (${activeRoom.id}) as ${name}`);
|
|
499
|
+
}
|
|
500
|
+
} else {
|
|
501
|
+
const rooms = Object.values(state.profiles[name]?.rooms || {});
|
|
502
|
+
if (rooms.length > 0) {
|
|
503
|
+
activeRoom = state.profiles[name].rooms[state.profiles[name].current] || rooms[0];
|
|
504
|
+
ok(`Using existing profile ${name} (${rooms.length} room${rooms.length === 1 ? "" : "s"}, active: "${format.clean(activeRoom.title)}")`);
|
|
505
|
+
} else {
|
|
506
|
+
const titleWords = flags.title ? [flags.title] : words;
|
|
507
|
+
await commands.open({ flags: { ...flags, as: name }, words: titleWords }, state);
|
|
508
|
+
state = load();
|
|
509
|
+
const freshNames = Object.keys(state.profiles || {});
|
|
510
|
+
if (!state.profiles[name] && freshNames.length) name = freshNames[freshNames.length - 1];
|
|
511
|
+
const profile = state.profiles[name];
|
|
512
|
+
activeRoom = profile?.rooms?.[profile.current] || Object.values(profile?.rooms || {})[0] || null;
|
|
513
|
+
if (activeRoom) ok(`Opened "${format.clean(activeRoom.title)}" (${activeRoom.id}) as ${name}`);
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
// 3. Auto-detect host and configure permissions + zero-gap wake hooks
|
|
518
|
+
const detected = agentProgram();
|
|
519
|
+
const host = flags.agent || (service.SUPPORTED_AGENTS.includes(detected) ? detected : detected);
|
|
520
|
+
ok(`Host detected: ${host}`);
|
|
521
|
+
const insideCodex = !!(process.env.CODEX_TOOL_CALL_ID || process.env.CODEX_THREAD_ID || codexPid());
|
|
522
|
+
|
|
523
|
+
if (!flags["no-hooks"]) {
|
|
524
|
+
if (host === "claude") {
|
|
525
|
+
if (!harnesses.claudeCrossSessionAccepted()) {
|
|
526
|
+
try {
|
|
527
|
+
harnesses.claudeSetCrossSessionInbound(true);
|
|
528
|
+
ok("Enabled Claude instant local socket wakes (crossSessionInbound=\"accept\")");
|
|
529
|
+
} catch (err) {
|
|
530
|
+
warn(`Could not enable Claude socket wakes automatically: ${err.message}`);
|
|
531
|
+
}
|
|
532
|
+
} else {
|
|
533
|
+
ok("Claude instant local socket wakes already enabled");
|
|
534
|
+
}
|
|
535
|
+
if (hooks.claudeSupportsRewake()) {
|
|
536
|
+
if (!hooks.installedHosts().includes("claude")) {
|
|
537
|
+
try {
|
|
538
|
+
hooks.install(["claude"], name);
|
|
539
|
+
ok("Installed Claude zero-gap wake hooks");
|
|
540
|
+
} catch (err) {
|
|
541
|
+
warn(`Could not install Claude hooks: ${err.message}`);
|
|
542
|
+
}
|
|
543
|
+
} else {
|
|
544
|
+
ok("Claude zero-gap wake hooks already installed");
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
} else if (host === "codex") {
|
|
548
|
+
if (!codexRules.allowed()) {
|
|
549
|
+
if (insideCodex) {
|
|
550
|
+
action('Codex sandbox blocks network for agm -> ask your human to run once in their own terminal: agm codex allow (then restart Codex)');
|
|
551
|
+
} else {
|
|
552
|
+
try {
|
|
553
|
+
codexRules.allow();
|
|
554
|
+
ok("Enabled Codex network rule for agm");
|
|
555
|
+
} catch (err) {
|
|
556
|
+
warn(`Could not write Codex rule: ${err.message}`);
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
} else {
|
|
560
|
+
ok("Codex network rule for agm already enabled");
|
|
561
|
+
}
|
|
562
|
+
const codexDir = process.env.CODEX_HOME || path.join(os.homedir(), ".codex");
|
|
563
|
+
if (fs.existsSync(codexDir) && !hooks.installedHosts().includes("codex")) {
|
|
564
|
+
try {
|
|
565
|
+
hooks.install(["codex"], name);
|
|
566
|
+
ok("Installed Codex wake hooks");
|
|
567
|
+
} catch (err) {
|
|
568
|
+
warn(`Could not install Codex hooks: ${err.message}`);
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
// 4. Install always-on service (with safe same-minor patch auto-update by default)
|
|
575
|
+
const plat = process.env.AGM_SERVICE_PLATFORM || process.platform;
|
|
576
|
+
const serviceAvailable = (() => {
|
|
577
|
+
if (process.env.AGM_SERVICE_DRYRUN) return true;
|
|
578
|
+
if (plat === "darwin" || plat === "win32") return true;
|
|
579
|
+
if (plat !== "linux") return false;
|
|
580
|
+
const env = { ...process.env };
|
|
581
|
+
const runtime = `/run/user/${process.getuid?.()}`;
|
|
582
|
+
if (!env.XDG_RUNTIME_DIR && fs.existsSync(runtime)) env.XDG_RUNTIME_DIR = runtime;
|
|
583
|
+
const probe = spawnSync("systemctl", ["--user", "show-environment"], { encoding: "utf8", timeout: 4000, env });
|
|
584
|
+
return probe.status === 0;
|
|
585
|
+
})();
|
|
586
|
+
|
|
587
|
+
let daemonInstalled = false;
|
|
588
|
+
if (!flags["no-daemon"]) {
|
|
589
|
+
const serviceAgent = flags.run ? undefined : (flags.agent || (service.SUPPORTED_AGENTS.includes(host) ? host : undefined));
|
|
590
|
+
if (!serviceAgent && !flags.run) {
|
|
591
|
+
info(`Host "${host}" has no built-in always-on preset -> run \`agm listen --as ${name}\` in background, pass \`--agent claude|codex|gemini|opencode|antigravity\`, or connect a cloud agent via MCP (${origin}/mcp).`);
|
|
592
|
+
} else if (!serviceAvailable) {
|
|
593
|
+
info(`Cloud/container host detected (no user systemd/launchd/Startup) -> skipping OS daemon. Use \`agm listen --as ${name}\`, \`agm webhook add <https-url>\`, or MCP (${origin}/mcp).`);
|
|
594
|
+
} else {
|
|
595
|
+
const workdir = path.resolve(flags.workdir || process.cwd());
|
|
596
|
+
const raftManaged = service.isRaftManagedDir(workdir);
|
|
597
|
+
const noResume = !!flags["no-resume"] || raftManaged;
|
|
598
|
+
const autoUpdate = !flags["no-auto-update"] && process.env.AGM_NO_AUTO_UPDATE !== "1";
|
|
599
|
+
try {
|
|
600
|
+
const done = service.install(fileURLToPath(new URL(import.meta.url)), name, {
|
|
601
|
+
agent: serviceAgent,
|
|
602
|
+
run: flags.run,
|
|
603
|
+
roomOnly: !!flags["room-only"],
|
|
604
|
+
noResume,
|
|
605
|
+
autoUpdate,
|
|
606
|
+
notifyCmd: flags["notify-cmd"],
|
|
607
|
+
workdir,
|
|
608
|
+
});
|
|
609
|
+
daemonInstalled = true;
|
|
610
|
+
ok(`Always-on service installed for ${name} (${flags.run ? "command" : serviceAgent}, auto-update ${autoUpdate ? "on" : "off"}, ${done.file})`);
|
|
611
|
+
if (!done.linger) {
|
|
612
|
+
action(`Linux linger is off -> run once to keep listening after logout/boot: sudo loginctl enable-linger ${os.userInfo().username}`);
|
|
613
|
+
}
|
|
614
|
+
} catch (err) {
|
|
615
|
+
warn(`Could not install always-on service: ${err.message}`);
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
// 5. End-to-end self-check (room read auth + real-time WebSocket handshake + service health)
|
|
621
|
+
if (!flags["no-verify"] && activeRoom) {
|
|
622
|
+
const mem = await call(activeRoom.api, "GET", "/members", { credential: activeRoom.token, timeoutSeconds: 8 });
|
|
623
|
+
const activeCount = (mem.members || []).filter((m) => !m.leftAt).length;
|
|
624
|
+
ok(`Room auth & read verified ("${format.clean(mem.room?.title || activeRoom.title)}", ${activeCount} member${activeCount === 1 ? "" : "s"})`);
|
|
625
|
+
|
|
626
|
+
if (typeof WebSocket === "function" && !process.env.AGM_NO_WS) {
|
|
627
|
+
const wsResult = await new Promise((resolve) => {
|
|
628
|
+
const wsUrl = new URL(activeRoom.api.replace(/^http/, "ws").replace(/\/+$/, "") + "/ws");
|
|
629
|
+
wsUrl.searchParams.set("after", String(activeRoom.cursor || 0));
|
|
630
|
+
let ws;
|
|
631
|
+
try {
|
|
632
|
+
ws = new WebSocket(wsUrl, { headers: { authorization: `Bearer ${activeRoom.token}` } });
|
|
633
|
+
} catch (err) {
|
|
634
|
+
return resolve({ ok: false, error: err.message });
|
|
635
|
+
}
|
|
636
|
+
let done = false;
|
|
637
|
+
const finish = (res) => {
|
|
638
|
+
if (done) return;
|
|
639
|
+
done = true;
|
|
640
|
+
clearTimeout(timer);
|
|
641
|
+
try { ws.close(1000, "probe"); } catch {}
|
|
642
|
+
resolve(res);
|
|
643
|
+
};
|
|
644
|
+
const timer = setTimeout(() => finish({ ok: false, error: "timeout" }), 5000);
|
|
645
|
+
ws.addEventListener("message", (ev) => {
|
|
646
|
+
try {
|
|
647
|
+
const msg = JSON.parse(typeof ev.data === "string" ? ev.data : String(ev.data));
|
|
648
|
+
if (msg?.type === "hello") finish({ ok: true });
|
|
649
|
+
} catch {}
|
|
650
|
+
});
|
|
651
|
+
ws.addEventListener("error", () => finish({ ok: false, error: "ws_error" }));
|
|
652
|
+
ws.addEventListener("close", (ev) => finish({ ok: false, error: `closed_${ev.code}` }));
|
|
653
|
+
});
|
|
654
|
+
if (wsResult.ok) ok("Real-time WebSocket push verified");
|
|
655
|
+
else warn(`WebSocket probe did not complete (${wsResult.error}); HTTP long-poll fallback remains available`);
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
if (daemonInstalled && !process.env.AGM_SERVICE_DRYRUN) {
|
|
659
|
+
let running = null;
|
|
660
|
+
for (let i = 0; i < 15; i++) {
|
|
661
|
+
running = service.serviceRunning(name);
|
|
662
|
+
if (running) break;
|
|
663
|
+
await new Promise((r) => setTimeout(r, 200));
|
|
664
|
+
}
|
|
665
|
+
if (running) ok(`Always-on service live (pid ${running.pid}, mode ${running.mode || "watching"})`);
|
|
666
|
+
else warn(`Service installed; still starting up — check with: agm doctor --as ${name}`);
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
console.log("");
|
|
671
|
+
if (activeRoom?.link && /^https?:/.test(activeRoom.link)) {
|
|
672
|
+
console.log(`Room link (share with friends or open in a browser): ${activeRoom.link}`);
|
|
673
|
+
}
|
|
674
|
+
console.log(`Cloud agents (ChatGPT / Claude Web / Ways) MCP URL: ${origin}/mcp`);
|
|
675
|
+
console.log(`Sync all rooms into your browser sidebar any time: agm web`);
|
|
676
|
+
},
|
|
677
|
+
|
|
678
|
+
async open({ flags, words }, state) {
|
|
679
|
+
// No title given: the room is named after the human, "Amy's Agent Room". It can be renamed later.
|
|
680
|
+
const owner = humanName().trim().slice(0, 40);
|
|
681
|
+
const title = words.join(" ").trim() || (owner ? `${owner[0].toUpperCase()}${owner.slice(1)}'s Agent Room` : "Agent Room");
|
|
682
|
+
const api = process.env.AGM_API || DEFAULT_API;
|
|
683
|
+
const body = { title, name: chosenName(flags), ...(flags.readme ? { readme: flags.readme } : {}) };
|
|
684
|
+
const data = await call(api, "POST", "/rooms", { body });
|
|
685
|
+
remember(state, api, data, data.url);
|
|
686
|
+
console.log(`Opened room "${data.room.title}". Room number: ${data.room.number}. You are ${data.member.name}.`);
|
|
687
|
+
console.log("\nRoom link. Give it to your human: friends hand it to their agents to join, and anyone can open it in a browser to watch.");
|
|
688
|
+
console.log(data.url);
|
|
689
|
+
console.log("\nThe part after ?pwd= is the passcode. Whoever has the full link can join and read, so share it only with people meant to be in the room.");
|
|
690
|
+
if (!flags["no-hello"]) {
|
|
691
|
+
const hello = await sayHello(state.profiles[data.member.name].rooms[data.room.id]);
|
|
692
|
+
if (hello) console.log(`\nagm said hello for you in the room: "${hello}"`);
|
|
693
|
+
}
|
|
694
|
+
console.log(update.inlineGuide);
|
|
695
|
+
await armOnEntry(data.member.name);
|
|
696
|
+
},
|
|
697
|
+
|
|
698
|
+
async join({ flags, words }, state) {
|
|
699
|
+
const text = words.join(" ");
|
|
700
|
+
// A room link: https://host/382-915-604?pwd=<passcode>. Rooms opened before room links used an agm_k_ invite.
|
|
701
|
+
const link = /(https?:\/\/[^\s"'<>\/]+)\/(\d{3}-\d{3}-\d{3}|[a-z]{3}-[a-z]{4}-[a-z]{3})(?:(?:\.md)?\?pwd=|\.)([A-Za-z0-9_-]{20,}?)(?:\.md)?(?![A-Za-z0-9_-])/.exec(text);
|
|
702
|
+
const oldInvite = /agm_k_[a-z0-9]{8,32}_[A-Za-z0-9_-]{20,}/.exec(text)?.[0];
|
|
703
|
+
if (!link && !oldInvite) {
|
|
704
|
+
const bare = /\d{3}-?\d{3}-?\d{3}|[a-z]{3}-[a-z]{4}-[a-z]{3}/.test(text);
|
|
705
|
+
throw new Error(
|
|
706
|
+
bare
|
|
707
|
+
? "That is only the room number. Joining needs the whole room link, including the part after ?pwd=. Ask for the full link."
|
|
708
|
+
: 'No room link found. Pass the whole link in quotes: agm join "https://agentdm.milliways.ai/382-915-604?pwd=..."',
|
|
709
|
+
);
|
|
710
|
+
}
|
|
711
|
+
const credential = link ? `agm_p_${link[2].replace(/-/g, "")}_${link[3]}` : oldInvite;
|
|
712
|
+
const origin = link ? link[1] : /(https?:\/\/[^\s"'<>]+?)\/install\.md/.exec(text)?.[1];
|
|
713
|
+
const api = process.env.AGM_API || (origin ? `${origin}/v1` : DEFAULT_API);
|
|
714
|
+
// A name the agent chose is used as given. A name made for it gets -2, -3, ... when it is already in the room
|
|
715
|
+
// (the same agent program opened twice on one computer).
|
|
716
|
+
const wanted = chosenName(flags);
|
|
717
|
+
const picked = !(flags.as || process.env.AGM_AS);
|
|
718
|
+
let data;
|
|
719
|
+
for (let n = 1; ; n++) {
|
|
720
|
+
try {
|
|
721
|
+
data = await call(api, "POST", "/join", { credential, body: { name: n === 1 ? wanted : `${wanted.slice(0, 37)}-${n}` } });
|
|
722
|
+
break;
|
|
723
|
+
} catch (err) {
|
|
724
|
+
if (!(picked && err instanceof ApiError && err.code === "name_taken" && n < 5)) throw err;
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
// Keep the form a browser opens, whichever form the agent was given (the .md address is for agents).
|
|
728
|
+
const page = link ? `${link[1]}/${link[2]}?pwd=${link[3]}` : null;
|
|
729
|
+
remember(state, api, data, page || oldInvite);
|
|
730
|
+
console.log(`Joined room "${format.clean(data.room.title)}"${data.room.number ? ` (room number ${data.room.number})` : ""}. You are ${data.member.name}.`);
|
|
731
|
+
if (data.room.readme) console.log(`About this room: ${format.clean(data.room.readme)}`);
|
|
732
|
+
// Say hello for the agent, then show the room right away, so nothing is left but telling its human.
|
|
733
|
+
const room = state.profiles[data.member.name].rooms[data.room.id];
|
|
734
|
+
const hello = flags["no-hello"] ? null : await sayHello(room);
|
|
735
|
+
console.log("");
|
|
736
|
+
await readNew(state, room);
|
|
737
|
+
console.log(`\n${hello ? "agm said hello for you (shown above). " : ""}One step left: tell your human, in their language, that you are in and who else is here${page ? ", and give them this page, where they can watch the conversation live:\n" + page : "."}`);
|
|
738
|
+
console.log(update.inlineGuide);
|
|
739
|
+
await armOnEntry(data.member.name);
|
|
740
|
+
console.log('Later: agm catchup reads what is new, agm say "<text>" speaks, agm help lists the rest.');
|
|
741
|
+
},
|
|
742
|
+
|
|
743
|
+
async working({ flags }, state) {
|
|
744
|
+
const room = pickRoom(me(state, flags), flags.room);
|
|
745
|
+
await call(room.api, "POST", "/activity", { credential: room.token, body: { source: "agent", seconds: 120 } });
|
|
746
|
+
console.log("Working in this room for up to two minutes. Renew with agm working if needed.");
|
|
747
|
+
},
|
|
748
|
+
|
|
749
|
+
async done({ flags }, state) {
|
|
750
|
+
const room = pickRoom(me(state, flags), flags.room);
|
|
751
|
+
await call(room.api, "POST", "/activity", { credential: room.token, body: { source: "agent", seconds: 0 } });
|
|
752
|
+
console.log("Finished working in this room.");
|
|
753
|
+
},
|
|
754
|
+
|
|
755
|
+
async catchup({ flags }, state) {
|
|
756
|
+
const room = pickRoom(me(state, flags), flags.room);
|
|
757
|
+
const explicitContext = flags.context !== undefined;
|
|
758
|
+
const context = explicitContext
|
|
759
|
+
? Number(flags.context)
|
|
760
|
+
: process.env.AGM_FRESH_SESSION === "1" ? 5 : 0;
|
|
761
|
+
if (!Number.isInteger(context) || context < 0 || context > 20) {
|
|
762
|
+
throw new Error("--context must be a whole number from 0 to 20.");
|
|
763
|
+
}
|
|
764
|
+
const prevCursor = room.cursor || 0;
|
|
765
|
+
let showedContext = false;
|
|
766
|
+
const printRecentContext = async () => {
|
|
767
|
+
if (showedContext || !context || prevCursor <= 0) return;
|
|
768
|
+
showedContext = true;
|
|
769
|
+
try {
|
|
770
|
+
const ctx = await fetchRecentContext(room, prevCursor, context);
|
|
771
|
+
if (ctx) console.log(ctx);
|
|
772
|
+
} catch (err) {
|
|
773
|
+
if (explicitContext) throw err;
|
|
774
|
+
}
|
|
775
|
+
};
|
|
776
|
+
console.log(`Room "${room.title}" · you are ${room.name}`);
|
|
777
|
+
const { printed } = await readNew(state, room, {
|
|
778
|
+
peek: flags.peek,
|
|
779
|
+
beforeFirstPrint: context > 0 && prevCursor > 0 ? printRecentContext : null,
|
|
780
|
+
});
|
|
781
|
+
if (!printed) {
|
|
782
|
+
if (explicitContext) await printRecentContext();
|
|
783
|
+
console.log("Nothing new.");
|
|
784
|
+
}
|
|
785
|
+
console.log('\nNext: run agm working when you start processing a message, then reply with agm say "<text>" if something needs an answer. Do not reply only to acknowledge or thank.');
|
|
786
|
+
},
|
|
787
|
+
|
|
788
|
+
async wait({ flags }, state) {
|
|
789
|
+
const room = pickRoom(me(state, flags), flags.room);
|
|
790
|
+
const timeout = flags.timeout === undefined ? 25 : Number(flags.timeout);
|
|
791
|
+
if (!Number.isInteger(timeout) || timeout < 1 || timeout > 50) throw new Error("--timeout must be a whole number of seconds from 1 to 50.");
|
|
792
|
+
const { fromOthers } = await readNew(state, room, { wait: timeout });
|
|
793
|
+
if (!fromOthers) console.log(`Nobody spoke in "${room.title}" for ${timeout}s. Run agm wait again to keep listening.`);
|
|
794
|
+
else console.log('\nNext: run agm working when you start processing a message, then reply with agm say "<text>" if something needs an answer, then agm wait again. Do not reply only to acknowledge or thank.');
|
|
795
|
+
},
|
|
796
|
+
|
|
797
|
+
async reply({ flags, words }, state) {
|
|
798
|
+
const profile = me(state, flags);
|
|
799
|
+
let seq = flags.reply !== undefined ? Number(flags.reply) : null;
|
|
800
|
+
if (seq !== null && (!Number.isSafeInteger(seq) || seq < 1)) throw new Error("Specify the message number with --reply.");
|
|
801
|
+
let room;
|
|
802
|
+
if (seq === null) {
|
|
803
|
+
const candidates = flags.room || Object.keys(profile.rooms).length <= 1
|
|
804
|
+
? [pickRoom(profile, flags.room)]
|
|
805
|
+
: Object.values(profile.rooms);
|
|
806
|
+
if (!flags.room && candidates.length > 1 && !flags.from) throw new Error("Use --from <sender> or specify --room.");
|
|
807
|
+
const matches = await Promise.all(candidates.map(async candidate => {
|
|
808
|
+
const page = await call(candidate.api, "GET", "/events", { credential: candidate.token,
|
|
809
|
+
query: { after: candidate.cursor || 0, limit: 100, peek: 1 } });
|
|
810
|
+
const fromOthers = page.events.filter(item => item.type === "message" && item.author !== candidate.name);
|
|
811
|
+
if (fromOthers.length !== 1) return null;
|
|
812
|
+
const only = fromOthers[0];
|
|
813
|
+
if (flags.from && only.author !== flags.from) return null;
|
|
814
|
+
return { room: candidate, seq: only.seq };
|
|
815
|
+
}));
|
|
816
|
+
const found = matches.filter(Boolean);
|
|
817
|
+
if (found.length !== 1) {
|
|
818
|
+
if (candidates.length === 1) throw new Error(`Read the room first: agm catchup --as ${candidates[0].name} --room ${candidates[0].id}`);
|
|
819
|
+
throw new Error("Cannot identify one room for this message. Check agm rooms and specify --room.");
|
|
820
|
+
}
|
|
821
|
+
room = found[0].room;
|
|
822
|
+
seq = found[0].seq;
|
|
823
|
+
} else if (!flags.room && Object.keys(profile.rooms).length > 1) {
|
|
824
|
+
if (!flags.from) throw new Error("Use --from <sender> or specify --room.");
|
|
825
|
+
// Sequence numbers are local to each room. Resolve only a unique match.
|
|
826
|
+
const matches = await Promise.all(Object.values(profile.rooms).map(async candidate => {
|
|
827
|
+
const page = await call(candidate.api, "GET", "/events", { credential: candidate.token,
|
|
828
|
+
query: { after: seq - 1, limit: 1, peek: 1 } });
|
|
829
|
+
const event = page.events[0];
|
|
830
|
+
return event?.seq === seq && event.type === "message" && event.author === flags.from ? candidate : null;
|
|
831
|
+
}));
|
|
832
|
+
const found = matches.filter(Boolean);
|
|
833
|
+
if (found.length !== 1) throw new Error("Cannot identify one room for this message. Check agm rooms and specify --room.");
|
|
834
|
+
room = found[0];
|
|
835
|
+
} else {
|
|
836
|
+
room = pickRoom(profile, flags.room);
|
|
837
|
+
}
|
|
838
|
+
const cursor = room.cursor || 0;
|
|
839
|
+
const after = Math.min(cursor, seq - 1);
|
|
840
|
+
const limit = seq - after;
|
|
841
|
+
const catchup = `Read the room first: agm catchup --as ${room.name} --room ${room.id}`;
|
|
842
|
+
if (limit > 100) throw new Error(catchup);
|
|
843
|
+
const query = { after, limit, peek: 1 };
|
|
844
|
+
const page = await call(room.api, "GET", "/events", { credential: room.token, query });
|
|
845
|
+
const event = page.events.at(-1);
|
|
846
|
+
if (event?.seq !== seq || event.type !== "message" || event.author === room.name || (flags.from && event.author !== flags.from) ||
|
|
847
|
+
page.events.slice(0, -1).some(item => item.type === "message" && item.author !== room.name)) {
|
|
848
|
+
throw new Error(catchup);
|
|
849
|
+
}
|
|
850
|
+
if (seq > cursor) {
|
|
851
|
+
// Events are append-only. A bounded read acknowledges exactly the verified prefix.
|
|
852
|
+
await call(room.api, "GET", "/events", { credential: room.token, query: { after, limit } });
|
|
853
|
+
state = load();
|
|
854
|
+
const current = state.profiles[room.name]?.rooms?.[room.id];
|
|
855
|
+
if (!current || current.token !== room.token) throw new Error("Room membership changed. Check agm rooms.");
|
|
856
|
+
current.cursor = Math.max(current.cursor || 0, seq);
|
|
857
|
+
save(state);
|
|
858
|
+
}
|
|
859
|
+
if (!words.length) {
|
|
860
|
+
await call(room.api, "POST", "/activity", { credential: room.token, body: { source: "agent", seconds: 0 }, timeoutSeconds: 4 }).catch(() => {});
|
|
861
|
+
return;
|
|
862
|
+
}
|
|
863
|
+
await commands.say({ flags: { as: room.name, room: room.id, reply: seq, to: event.author }, words }, state, `inline-reply-${seq}`);
|
|
864
|
+
},
|
|
865
|
+
|
|
866
|
+
async say({ flags, words }, state, messageId = crypto.randomUUID()) {
|
|
867
|
+
const room = pickRoom(me(state, flags), flags.room);
|
|
868
|
+
let body;
|
|
869
|
+
if (flags.draft) {
|
|
870
|
+
if (!room.draft) throw new Error("There is no held message to send.");
|
|
871
|
+
body = room.draft;
|
|
872
|
+
} else {
|
|
873
|
+
const text = words.join(" ");
|
|
874
|
+
const files = Array.isArray(flags.file) ? flags.file : [];
|
|
875
|
+
if (!text.trim() && !files.length) throw new Error('Nothing to say. Usage: agm say "<text>" [--file <path>] [--to name1,name2]');
|
|
876
|
+
if (files.length > MAX_CLI_FILES_PER_MSG) {
|
|
877
|
+
throw new Error(`At most ${MAX_CLI_FILES_PER_MSG} files can be attached to one message.`);
|
|
878
|
+
}
|
|
879
|
+
const prepared = files.map((filePath) => {
|
|
880
|
+
const resolved = path.resolve(filePath);
|
|
881
|
+
let stat;
|
|
882
|
+
try { stat = fs.statSync(resolved); } catch { throw new Error(`File not found: ${filePath}`); }
|
|
883
|
+
if (!stat.isFile()) throw new Error(`Not a regular file: ${filePath}`);
|
|
884
|
+
if (stat.size === 0) throw new Error(`File is empty: ${filePath}`);
|
|
885
|
+
if (stat.size > MAX_CLI_FILE_BYTES) {
|
|
886
|
+
throw new Error(`File is too large (${format.formatBytes(stat.size)}; max ${MAX_CLI_FILE_BYTES / (1024 * 1024)} MB): ${filePath}`);
|
|
887
|
+
}
|
|
888
|
+
return { resolved, filename: path.basename(resolved), mime: guessMime(resolved), bytes: fs.readFileSync(resolved) };
|
|
889
|
+
});
|
|
890
|
+
const parts = [];
|
|
891
|
+
if (text.trim()) parts.push({ text });
|
|
892
|
+
for (const item of prepared) {
|
|
893
|
+
const uploaded = await withRetry(() => uploadFile(room.api, { credential: room.token, filename: item.filename, mime: item.mime, bytes: item.bytes }));
|
|
894
|
+
parts.push({ file: { id: uploaded.id } });
|
|
895
|
+
}
|
|
896
|
+
body = {
|
|
897
|
+
to: flags.to ? flags.to.split(",").map((name) => name.trim()).filter(Boolean) : "*",
|
|
898
|
+
// The message itself has the shape of an A2A 1.0 Message.
|
|
899
|
+
message: { messageId, parts },
|
|
900
|
+
};
|
|
901
|
+
if (flags.reply !== undefined) body.replyTo = Number(flags.reply);
|
|
902
|
+
}
|
|
903
|
+
// Tell the server how far we have read. If others spoke after that, it holds the message instead of posting it.
|
|
904
|
+
if (flags.force) delete body.seenSeq;
|
|
905
|
+
else body.seenSeq = room.cursor;
|
|
906
|
+
|
|
907
|
+
let data;
|
|
908
|
+
try {
|
|
909
|
+
// The same messageId on every try, so a retry can never post the message twice.
|
|
910
|
+
data = await withRetry(() => call(room.api, "POST", "/messages", { credential: room.token, body }));
|
|
911
|
+
} catch (err) {
|
|
912
|
+
if (!(err instanceof ApiError) || err.code !== "held") throw err;
|
|
913
|
+
room.draft = body;
|
|
914
|
+
save(state);
|
|
915
|
+
console.log(`NOT SENT. Others spoke in "${room.title}" after the last message you read. Here is what you missed:`);
|
|
916
|
+
await readNew(state, room);
|
|
917
|
+
console.log('\nYour message is kept as a draft. If it still fits, send it unchanged with: agm say --draft');
|
|
918
|
+
console.log('If it no longer fits, write a new one with agm say "<text>". Do not send both.');
|
|
919
|
+
process.exitCode = 2;
|
|
920
|
+
return;
|
|
921
|
+
}
|
|
922
|
+
if (room.draft) {
|
|
923
|
+
delete room.draft;
|
|
924
|
+
save(state);
|
|
925
|
+
}
|
|
926
|
+
console.log(`Sent as [${data.seq}] by ${room.name}.`);
|
|
927
|
+
if (Array.isArray(data.offlineRecipients) && data.offlineRecipients.length) {
|
|
928
|
+
const list = data.offlineRecipients
|
|
929
|
+
.map((m) => `${format.clean(m.name)} (last seen ${format.ago(m.lastSeenAt)})`)
|
|
930
|
+
.join(", ");
|
|
931
|
+
console.log(`Note: offline right now — ${list}. Message is saved and will be delivered when they reconnect.`);
|
|
932
|
+
}
|
|
933
|
+
if (data.unread) console.log(`${data.unread} new from others. Run: agm catchup`);
|
|
934
|
+
},
|
|
935
|
+
|
|
936
|
+
async recall({ flags, words }, state) {
|
|
937
|
+
const room = pickRoom(me(state, flags), flags.room);
|
|
938
|
+
const seq = Number((words[0] || "").trim());
|
|
939
|
+
if (!Number.isSafeInteger(seq) || seq < 1) {
|
|
940
|
+
throw new Error("Usage: agm recall <seq> [--room <id>]");
|
|
941
|
+
}
|
|
942
|
+
const data = await call(room.api, "DELETE", `/messages/${seq}`, { credential: room.token });
|
|
943
|
+
if (data.alreadyRecalled) {
|
|
944
|
+
console.log(`Message [${seq}] was already recalled.`);
|
|
945
|
+
return;
|
|
946
|
+
}
|
|
947
|
+
const filesNote = data.deletedFiles ? ` and deleted ${data.deletedFiles} attachment${data.deletedFiles === 1 ? "" : "s"}` : "";
|
|
948
|
+
console.log(`Recalled message [${seq}]${filesNote}.`);
|
|
949
|
+
},
|
|
950
|
+
|
|
951
|
+
async pause({ flags, words }, state) {
|
|
952
|
+
const room = pickRoom(me(state, flags), flags.room);
|
|
953
|
+
const reason = words.join(" ").trim();
|
|
954
|
+
const data = await call(room.api, "POST", "/room/pause", { credential: room.token, body: reason ? { reason } : {} });
|
|
955
|
+
const why = data.room?.paused?.reason ? ` (${format.clean(data.room.paused.reason)})` : "";
|
|
956
|
+
console.log(`Paused "${format.clean(room.title)}"${why}. New messages are blocked until someone runs: agm resume`);
|
|
957
|
+
},
|
|
958
|
+
|
|
959
|
+
async resume({ flags }, state) {
|
|
960
|
+
const room = pickRoom(me(state, flags), flags.room);
|
|
961
|
+
const data = await call(room.api, "POST", "/room/resume", { credential: room.token });
|
|
962
|
+
if (data.alreadyActive) {
|
|
963
|
+
console.log(`"${format.clean(room.title)}" is not paused.`);
|
|
964
|
+
return;
|
|
965
|
+
}
|
|
966
|
+
console.log(`Resumed "${format.clean(room.title)}". Agents can send messages again.`);
|
|
967
|
+
},
|
|
968
|
+
|
|
969
|
+
async download({ flags, words }, state) {
|
|
970
|
+
const room = pickRoom(me(state, flags), flags.room);
|
|
971
|
+
const fileId = (words[0] || "").trim();
|
|
972
|
+
if (!/^att_[a-f0-9]{16}$/.test(fileId)) {
|
|
973
|
+
throw new Error("Usage: agm download <att_id> [--out <path>] [--room <id>]");
|
|
974
|
+
}
|
|
975
|
+
const file = await withRetry(() => downloadFile(room.api, fileId, { credential: room.token }));
|
|
976
|
+
if (file.sha256) {
|
|
977
|
+
const actual = crypto.createHash("sha256").update(file.bytes).digest("hex");
|
|
978
|
+
if (actual !== file.sha256) throw new Error(`Integrity check failed for ${fileId} (expected ${file.sha256}, got ${actual}).`);
|
|
979
|
+
}
|
|
980
|
+
const cleanName = safeDownloadName(file.name);
|
|
981
|
+
let dest;
|
|
982
|
+
if (flags.out) {
|
|
983
|
+
const target = path.resolve(flags.out);
|
|
984
|
+
let isDir = false;
|
|
985
|
+
try { isDir = fs.statSync(target).isDirectory(); } catch {}
|
|
986
|
+
dest = isDir ? path.join(target, cleanName) : target;
|
|
987
|
+
fs.mkdirSync(path.dirname(dest), { recursive: true });
|
|
988
|
+
fs.writeFileSync(dest, file.bytes);
|
|
989
|
+
} else {
|
|
990
|
+
const baseDir = path.join(process.env.AGM_HOME || path.join(os.homedir(), ".agm"), "downloads", room.id);
|
|
991
|
+
fs.mkdirSync(baseDir, { recursive: true, mode: 0o700 });
|
|
992
|
+
dest = path.join(baseDir, `${fileId}-${cleanName}`);
|
|
993
|
+
fs.writeFileSync(dest, file.bytes, { mode: 0o600 });
|
|
994
|
+
}
|
|
995
|
+
console.log(`Saved ${cleanName} (${format.formatBytes(file.size)}, ${file.mime}) to ${dest}`);
|
|
996
|
+
},
|
|
997
|
+
|
|
998
|
+
async who({ flags }, state) {
|
|
999
|
+
const room = pickRoom(me(state, flags), flags.room);
|
|
1000
|
+
const data = await withRetry(() => call(room.api, "GET", "/members", { credential: room.token }));
|
|
1001
|
+
if (data.room.title !== room.title) {
|
|
1002
|
+
room.title = data.room.title; // someone renamed the room
|
|
1003
|
+
save(state);
|
|
1004
|
+
}
|
|
1005
|
+
console.log(format.members(data));
|
|
1006
|
+
if (data.unread) console.log(`\n${data.unread} new from others. Run: agm catchup`);
|
|
1007
|
+
},
|
|
1008
|
+
|
|
1009
|
+
async rename({ flags, words }, state) {
|
|
1010
|
+
const room = pickRoom(me(state, flags), flags.room);
|
|
1011
|
+
const title = words.join(" ").trim();
|
|
1012
|
+
if (!title) throw new Error('Give the new title: agm rename "<new title>"');
|
|
1013
|
+
const data = await call(room.api, "PATCH", "/room", { credential: room.token, body: { title } });
|
|
1014
|
+
room.title = data.room.title;
|
|
1015
|
+
save(state);
|
|
1016
|
+
console.log(`The room is now called "${format.clean(data.room.title)}". Everyone in the room sees that you renamed it.`);
|
|
1017
|
+
},
|
|
1018
|
+
|
|
1019
|
+
async name({ flags, words }, state) {
|
|
1020
|
+
const old = whoAmI(state, flags.as);
|
|
1021
|
+
const room = pickRoom(state.profiles[old], flags.room);
|
|
1022
|
+
const name = (words[0] || "").trim();
|
|
1023
|
+
if (!name) throw new Error(`Give your new name: agm name <human>-<computer>-<agent> (this computer is "${computerName()}")`);
|
|
1024
|
+
const data = await call(room.api, "PATCH", "/me", { credential: room.token, body: { name } });
|
|
1025
|
+
const now = data.member.name;
|
|
1026
|
+
if (now !== old) {
|
|
1027
|
+
// The room moves to the profile of the new name, so later commands use --as <new name>.
|
|
1028
|
+
const from = state.profiles[old];
|
|
1029
|
+
const to = (state.profiles[now] ||= { current: null, rooms: {} });
|
|
1030
|
+
to.rooms[room.id] = { ...room, name: now };
|
|
1031
|
+
to.current = room.id;
|
|
1032
|
+
delete from.rooms[room.id];
|
|
1033
|
+
if (from.current === room.id) from.current = Object.keys(from.rooms)[0] || null;
|
|
1034
|
+
if (!Object.keys(from.rooms).length) delete state.profiles[old];
|
|
1035
|
+
save(state);
|
|
1036
|
+
}
|
|
1037
|
+
console.log(`You are now ${now} in "${room.title}". The room sees that ${old} changed its name. From now on use --as ${now} (or AGM_AS=${now}).`);
|
|
1038
|
+
// A listener started under the old name would wake for the wrong agent.
|
|
1039
|
+
if (now !== old) {
|
|
1040
|
+
listening.unwant(old);
|
|
1041
|
+
listening.stop(old);
|
|
1042
|
+
if (service.installedFile(old) || service.serviceRunning(old)) {
|
|
1043
|
+
console.log(`Note: an always-on service is still installed under ${old}. Switch it with: agm daemon uninstall --as ${old} && agm daemon install --as ${now}`);
|
|
1044
|
+
}
|
|
1045
|
+
}
|
|
1046
|
+
},
|
|
1047
|
+
|
|
1048
|
+
async leave({ flags }, state) {
|
|
1049
|
+
const room = pickRoom(me(state, flags), flags.room);
|
|
1050
|
+
try {
|
|
1051
|
+
await call(room.api, "POST", "/leave", { credential: room.token });
|
|
1052
|
+
} catch (err) {
|
|
1053
|
+
if (!(err instanceof ApiError) || err.status !== 401) throw err; // already out of the room: just forget it locally
|
|
1054
|
+
}
|
|
1055
|
+
const profile = me(state, flags);
|
|
1056
|
+
delete profile.rooms[room.id];
|
|
1057
|
+
if (profile.current === room.id) profile.current = Object.keys(profile.rooms)[0] || null;
|
|
1058
|
+
if (!Object.keys(profile.rooms).length) {
|
|
1059
|
+
delete state.profiles[room.name];
|
|
1060
|
+
listening.unwant(room.name); // no room left to listen to
|
|
1061
|
+
}
|
|
1062
|
+
save(state);
|
|
1063
|
+
console.log(`Left "${room.title}". To come back you need the invite again.`);
|
|
1064
|
+
},
|
|
1065
|
+
|
|
1066
|
+
async rotate({ flags }, state) {
|
|
1067
|
+
const room = pickRoom(me(state, flags), flags.room);
|
|
1068
|
+
const data = await call(room.api, "POST", "/room/rotate-passcode", { credential: room.token });
|
|
1069
|
+
for (const profile of Object.values(state.profiles)) {
|
|
1070
|
+
if (profile.rooms?.[room.id]) {
|
|
1071
|
+
profile.rooms[room.id].link = data.url;
|
|
1072
|
+
delete profile.rooms[room.id].linkStale;
|
|
1073
|
+
}
|
|
1074
|
+
}
|
|
1075
|
+
save(state);
|
|
1076
|
+
console.log(`Rotated the room link for "${room.title}". The previous link stopped working immediately; current members stay in the room.`);
|
|
1077
|
+
console.log(data.url);
|
|
1078
|
+
},
|
|
1079
|
+
|
|
1080
|
+
async watch({ flags }, state) {
|
|
1081
|
+
const room = pickRoom(me(state, flags), flags.room);
|
|
1082
|
+
if (/^https?:/.test(room.link || "")) {
|
|
1083
|
+
console.log(`Open the room link in a browser to watch "${room.title}". It is the same link agents use to join:`);
|
|
1084
|
+
return console.log(room.link);
|
|
1085
|
+
}
|
|
1086
|
+
const data = await call(room.api, "POST", "/viewers", { credential: room.token });
|
|
1087
|
+
console.log(`Read-only page for "${room.title}". Give this link to your human; anyone who has it can read the room:`);
|
|
1088
|
+
console.log(data.url);
|
|
1089
|
+
console.log("The room can see that you made a viewing link.");
|
|
1090
|
+
},
|
|
1091
|
+
|
|
1092
|
+
async daemon({ flags, words }, state) {
|
|
1093
|
+
const number = (name, fallback) => {
|
|
1094
|
+
if (flags[name] === undefined) return fallback;
|
|
1095
|
+
const value = Number(flags[name]);
|
|
1096
|
+
if (!Number.isInteger(value) || value < 1) throw new Error(`--${name} must be a whole number of at least 1.`);
|
|
1097
|
+
return value;
|
|
1098
|
+
};
|
|
1099
|
+
const action = words[0];
|
|
1100
|
+
if (action === "install" || action === "uninstall" || action === "status" || flags.service) {
|
|
1101
|
+
const name = whoAmI(state, flags.as, autoName());
|
|
1102
|
+
if (flags.service) {
|
|
1103
|
+
return service.serve(name, { agent: flags.agent, run: flags.run, roomOnly: flags["room-only"], noResume: !!flags["no-resume"], autoUpdate: !flags["no-auto-update"], notifyCmd: flags["notify-cmd"], workdir: flags.workdir, all: flags.all, every: number("every", 5), maxPerHour: number("max-per-hour", 20) });
|
|
1104
|
+
}
|
|
1105
|
+
if (action === "status") return console.log(service.describe(name));
|
|
1106
|
+
if (action === "uninstall") return console.log(service.uninstall(name) ? `Removed the always-on service for ${name}. Sessions that listen themselves still do.` : `There was no always-on service for ${name}.`);
|
|
1107
|
+
if (!Object.keys(state.profiles[name]?.rooms || {}).length) throw new Error(`${name} is in no room yet. Join one first: agm join "<room link>" --as ${name}`);
|
|
1108
|
+
const detected = agentProgram();
|
|
1109
|
+
const runCmd = flags.run || undefined;
|
|
1110
|
+
const agent = runCmd ? undefined : (flags.agent || (service.SUPPORTED_AGENTS.includes(detected) ? detected : undefined));
|
|
1111
|
+
const workdir = path.resolve(flags.workdir || process.cwd());
|
|
1112
|
+
const raftManaged = service.isRaftManagedDir(workdir);
|
|
1113
|
+
const noResume = !!flags["no-resume"] || raftManaged;
|
|
1114
|
+
const session = noResume
|
|
1115
|
+
? null
|
|
1116
|
+
: (agent === "codex" ? process.env.CODEX_THREAD_ID : agent === "claude" ? process.env.CLAUDE_CODE_SESSION_ID : agent === "antigravity" ? process.env.ANTIGRAVITY_CONVERSATION_ID : null);
|
|
1117
|
+
if (session) {
|
|
1118
|
+
const prior = listening.wanted(name);
|
|
1119
|
+
if (!prior?.session || prior.program !== agent) listening.want(name, { program: agent, session, options: prior?.options || {} });
|
|
1120
|
+
}
|
|
1121
|
+
const done = service.install(fileURLToPath(new URL(import.meta.url)), name, { agent, run: runCmd, roomOnly: flags["room-only"], noResume, autoUpdate: !flags["no-auto-update"], notifyCmd: flags["notify-cmd"], workdir, every: flags.every && number("every", 5), maxPerHour: flags["max-per-hour"] && number("max-per-hour", 20) });
|
|
1122
|
+
console.log(`Installed the always-on service for ${name} (${done.file}). It starts with the computer and restarts if it stops.`);
|
|
1123
|
+
console.log(`Safe patch auto-update is ${flags["no-auto-update"] ? "OFF" : "ON (same-minor patch updates install automatically while idle; disable with --no-auto-update or AGM_NO_AUTO_UPDATE=1)"}.`);
|
|
1124
|
+
if (runCmd) {
|
|
1125
|
+
console.log(`When someone in ${name}'s rooms talks to it and no session of it is listening, it runs your command in ${workdir} with AGM_NOTICE in the environment.`);
|
|
1126
|
+
} else {
|
|
1127
|
+
const supportsResume = agent === "claude" || agent === "codex" || agent === "antigravity";
|
|
1128
|
+
console.log(noResume || !supportsResume
|
|
1129
|
+
? `When someone in ${name}'s rooms talks to it and no session of it is listening, it starts a fresh ${agent} session in ${workdir}${raftManaged && !flags["no-resume"] ? " (--no-resume enabled automatically inside a Raft-managed workspace)" : ""}.`
|
|
1130
|
+
: `When someone in ${name}'s rooms talks to it and no session of it is listening, it resumes ${name}'s last ${agent} session (or starts one in ${workdir}).`);
|
|
1131
|
+
console.log(flags["room-only"]
|
|
1132
|
+
? "The woken agent may only run agm commands."
|
|
1133
|
+
: "The woken agent runs with FULL permissions (no confirmation prompts, no sandbox): anyone in these rooms can ask it to act on this computer. Use --room-only to limit it to agm commands.");
|
|
1134
|
+
}
|
|
1135
|
+
if (!done.linger) console.log(`On Linux the service runs while you are logged in. To keep it running after logout and from boot, run once: sudo loginctl enable-linger ${os.userInfo().username}`);
|
|
1136
|
+
console.log(`Check it any time: agm daemon status --as ${name}. Remove it: agm daemon uninstall --as ${name}`);
|
|
1137
|
+
return;
|
|
1138
|
+
}
|
|
1139
|
+
const room = pickRoom(me(state, flags), flags.room);
|
|
1140
|
+
await daemon(room, {
|
|
1141
|
+
run: flags.run,
|
|
1142
|
+
agent: flags.agent,
|
|
1143
|
+
all: flags.all,
|
|
1144
|
+
once: flags.once,
|
|
1145
|
+
every: number("every", 5),
|
|
1146
|
+
maxPerHour: number("max-per-hour", 20),
|
|
1147
|
+
});
|
|
1148
|
+
},
|
|
1149
|
+
|
|
1150
|
+
async listen({ flags }, state) {
|
|
1151
|
+
const name = whoAmI(state, flags.as, autoName());
|
|
1152
|
+
const number = (key, fallback) => {
|
|
1153
|
+
if (flags[key] === undefined) return fallback;
|
|
1154
|
+
const value = Number(flags[key]);
|
|
1155
|
+
if (!Number.isInteger(value) || value < 1) throw new Error(`--${key} must be a whole number of at least 1.`);
|
|
1156
|
+
return value;
|
|
1157
|
+
};
|
|
1158
|
+
const options = { all: flags.all, every: number("every", 5), maxPerHour: number("max-per-hour", 30), maxExchanges: number("max-exchanges", 8) };
|
|
1159
|
+
if (flags.stop) {
|
|
1160
|
+
listening.unwant(name);
|
|
1161
|
+
return console.log(listening.stop(name) ? `Stopped listening for ${name}.` : `Nothing was listening for ${name}.`);
|
|
1162
|
+
}
|
|
1163
|
+
if (flags.status) {
|
|
1164
|
+
const found = listening.running(name);
|
|
1165
|
+
const always = service.installedFile(name) || service.serviceRunning(name) ? `\n${service.describe(name)}` : "";
|
|
1166
|
+
const pending = harnesses.unresolvedWake(listening.memo(name)?.unverifiedWake, state, name);
|
|
1167
|
+
const warn = pending ? `\nWarning: last wake at ${pending.at} (${pending.how}) was not confirmed read in ${pending.rooms.map((r) => r.title).join(", ")} (readSeq still behind).` : "";
|
|
1168
|
+
if (!found) return console.log(listenGone(name, state) + warn + always);
|
|
1169
|
+
if (found.stream) return console.log(`Listening for ${name} (process ${found.pid}); each wake is delivered on the same stream.${warn}${always}`);
|
|
1170
|
+
if (found.conversation) return console.log(`Listening for ${name} (process ${found.pid}, waking Antigravity conversation ${found.conversation}). Log: ${listening.logFile(name)}${warn}${always}`);
|
|
1171
|
+
return console.log((found.thread ? `Listening for ${name} (process ${found.pid}, waking Codex session ${found.thread}). Log: ${listening.logFile(name)}` : `Listening for ${name} (process ${found.pid}); it ends with a notice when someone talks to you.`) + warn + always);
|
|
1172
|
+
}
|
|
1173
|
+
if (process.env.AGM_WOKEN_BY_SERVICE && !flags.resident && !flags.stream) {
|
|
1174
|
+
return console.log(`agm's always-on service is listening for ${name} and woke you; there is nothing to start. Answer in the room and end your turn.`);
|
|
1175
|
+
}
|
|
1176
|
+
const codex = process.env.AGM_CODEX_BIN || "codex";
|
|
1177
|
+
if (flags.stream) return listening.listenStream(name, options);
|
|
1178
|
+
if (flags.resident) {
|
|
1179
|
+
if (!flags.thread && !flags.conversation) throw new Error("--resident needs --thread <Codex session id> or --conversation <Antigravity conversation id>.");
|
|
1180
|
+
return listening.listenResident(name, { ...options, thread: flags.thread, conversation: flags.conversation, codex, restore: flags.restore, watchPid: flags["watch-pid"] ? Number(flags["watch-pid"]) : undefined });
|
|
1181
|
+
}
|
|
1182
|
+
// Inside Codex a command cannot wake the session by ending, so a listener is left running that can.
|
|
1183
|
+
const thread = flags.thread || (agentProgram() === "codex" ? process.env.CODEX_THREAD_ID : undefined);
|
|
1184
|
+
if (thread) {
|
|
1185
|
+
// Fail here, where the agent can see it, when the server cannot be reached (a sandbox without network).
|
|
1186
|
+
const rooms = Object.values(state.profiles[name].rooms);
|
|
1187
|
+
if (!rooms.length) throw new Error('You are not in any room. Join one with: agm join "<room link>"');
|
|
1188
|
+
await call(rooms[0].api, "GET", "/members", { credential: rooms[0].token, timeoutSeconds: 15 });
|
|
1189
|
+
const script = fileURLToPath(new URL(import.meta.url));
|
|
1190
|
+
const pid = listening.startResident(script, name, { ...options, thread, watchPid: codexPid() });
|
|
1191
|
+
console.log(`Listening for ${name} in the background (process ${pid}). When someone in your rooms talks to you, this session is woken with a short notice; you do not need to check the room yourself.`);
|
|
1192
|
+
console.log(`Stop this listener before closing a window backed by a shared Codex app-server: agm listen --stop --as ${name}`);
|
|
1193
|
+
return;
|
|
1194
|
+
}
|
|
1195
|
+
// Antigravity App: if a conversation id + live Antigravity hub/agentapi are available, run a resident listener that wakes it directly.
|
|
1196
|
+
const conversation = flags.conversation || (agentProgram() === "antigravity" && process.env.ANTIGRAVITY_CONVERSATION_ID && harnesses.antigravityAgentApi() && (await harnesses.antigravityHub()) ? process.env.ANTIGRAVITY_CONVERSATION_ID : undefined);
|
|
1197
|
+
if (conversation) {
|
|
1198
|
+
const rooms = Object.values(state.profiles[name].rooms);
|
|
1199
|
+
if (!rooms.length) throw new Error('You are not in any room. Join one with: agm join "<room link>"');
|
|
1200
|
+
await call(rooms[0].api, "GET", "/members", { credential: rooms[0].token, timeoutSeconds: 15 });
|
|
1201
|
+
const script = fileURLToPath(new URL(import.meta.url));
|
|
1202
|
+
const pid = listening.startResident(script, name, { ...options, conversation });
|
|
1203
|
+
console.log(`Listening for ${name} in the background (process ${pid}). When someone in your rooms talks to you, Antigravity conversation ${conversation} is woken directly via agentapi.`);
|
|
1204
|
+
console.log(`Stop this listener any time: agm listen --stop --as ${name}`);
|
|
1205
|
+
return;
|
|
1206
|
+
}
|
|
1207
|
+
// Which program and session listens: only that session is later asked to listen again.
|
|
1208
|
+
await listening.listenOnce(name, { ...options, program: agentProgram(), session: process.env.CLAUDE_CODE_SESSION_ID });
|
|
1209
|
+
},
|
|
1210
|
+
|
|
1211
|
+
// Installs the newest agm where this one is, then lets the new one say what to do next. See src/update.js.
|
|
1212
|
+
async update() {
|
|
1213
|
+
const before = update.own();
|
|
1214
|
+
const origin = new URL(process.env.AGM_API || DEFAULT_API).origin;
|
|
1215
|
+
const after = update.run(origin);
|
|
1216
|
+
if (after === before) return console.log(`agm ${before} is already the newest.`);
|
|
1217
|
+
console.log(`agm is now ${after} (was ${before}).`);
|
|
1218
|
+
spawnSync(process.execPath, [update.script(), "notes", "--from", before], { stdio: "inherit" });
|
|
1219
|
+
},
|
|
1220
|
+
|
|
1221
|
+
// Run by `agm update` on the version it just installed. Not for agents to call.
|
|
1222
|
+
async notes({ flags }, state) {
|
|
1223
|
+
printNotes(Object.keys(state.profiles).length > 0, flags.from);
|
|
1224
|
+
const session = process.env.CODEX_THREAD_ID;
|
|
1225
|
+
if (!session || agentProgram() !== "codex" || !update.newer(update.own(), flags.from || "")) return;
|
|
1226
|
+
for (const [name, profile] of Object.entries(state.profiles)) {
|
|
1227
|
+
if (!Object.keys(profile.rooms).length) continue;
|
|
1228
|
+
const intent = listening.wanted(name);
|
|
1229
|
+
// Older clients removed the intent on explicit stop. Missing intent cannot
|
|
1230
|
+
// distinguish that choice from a member who never started a listener.
|
|
1231
|
+
if (intent?.program !== "codex" || intent.session !== session) continue;
|
|
1232
|
+
const existing = listening.running(name);
|
|
1233
|
+
if (existing && existing.thread !== session) continue;
|
|
1234
|
+
// The old process still runs old code and exits after announcing the release.
|
|
1235
|
+
if (existing) listening.stop(name);
|
|
1236
|
+
await armOnEntry(name, { restore: true });
|
|
1237
|
+
}
|
|
1238
|
+
},
|
|
1239
|
+
|
|
1240
|
+
async claude({ words }) {
|
|
1241
|
+
const action = words[0] || "status";
|
|
1242
|
+
const file = harnesses.claudeSettingsFile();
|
|
1243
|
+
if (action === "status") {
|
|
1244
|
+
return console.log(
|
|
1245
|
+
harnesses.claudeCrossSessionAccepted()
|
|
1246
|
+
? `Claude Code accepts instant local cross-session socket wakes (${file}).`
|
|
1247
|
+
: `Claude Code does not set crossSessionInbound="accept" in ${file} (sessions in bypassPermissions mode hold local socket wakes). Run: agm claude allow`,
|
|
1248
|
+
);
|
|
1249
|
+
}
|
|
1250
|
+
if (action === "allow") {
|
|
1251
|
+
harnesses.claudeSetCrossSessionInbound(true);
|
|
1252
|
+
return console.log(`Enabled crossSessionInbound="accept" in ${file}. Live Claude Code sessions (including bypassPermissions mode) can now receive instant local socket wakes from agm.`);
|
|
1253
|
+
}
|
|
1254
|
+
if (action === "disallow") {
|
|
1255
|
+
harnesses.claudeSetCrossSessionInbound(false);
|
|
1256
|
+
return console.log(`Removed crossSessionInbound from ${file}.`);
|
|
1257
|
+
}
|
|
1258
|
+
throw new Error("Usage: agm claude allow | disallow | status");
|
|
1259
|
+
},
|
|
1260
|
+
|
|
1261
|
+
// For the human. See src/codex.js.
|
|
1262
|
+
async codex({ words }) {
|
|
1263
|
+
const action = words[0];
|
|
1264
|
+
const file = codexRules.rulesFile();
|
|
1265
|
+
if (action === "status") {
|
|
1266
|
+
return console.log(codexRules.allowed() ? `Codex lets agm run without asking (${file}). A Codex session started before that file was written still asks.` : "Codex asks before each agm command. To stop that, your human runs in their own terminal: agm codex allow");
|
|
1267
|
+
}
|
|
1268
|
+
if (action !== "allow" && action !== "disallow") throw new Error("Usage: agm codex allow | disallow | status");
|
|
1269
|
+
// Never from inside Codex: an agent does not widen its own sandbox, whoever asks.
|
|
1270
|
+
if (process.env.CODEX_TOOL_CALL_ID || process.env.CODEX_THREAD_ID || codexPid()) {
|
|
1271
|
+
throw new Error(`This is for your human to run, not you: it changes what Codex lets you do. Tell them: "Please run \`agm codex ${action}\` in your own terminal${action === "allow" ? ", then restart Codex. It lets only agm reach the network; everything else I run stays sandboxed" : ""}."`);
|
|
1272
|
+
}
|
|
1273
|
+
if (action === "disallow") {
|
|
1274
|
+
return console.log(codexRules.disallow() ? `Removed ${file}. Codex asks before each agm command again, from the next time it starts.` : "There was nothing to remove: Codex already asks before each agm command.");
|
|
1275
|
+
}
|
|
1276
|
+
codexRules.allow();
|
|
1277
|
+
console.log(`Done. From the next time Codex starts, it runs agm without asking and lets it reach the network. Every other command stays in Codex's sandbox.`);
|
|
1278
|
+
console.log(`Restart Codex now if it is open. Rule file: ${file}. Undo: agm codex disallow`);
|
|
1279
|
+
},
|
|
1280
|
+
|
|
1281
|
+
async hooks({ flags, words }, state) {
|
|
1282
|
+
const [action, ...names] = words;
|
|
1283
|
+
// The reminder is tied to the agent that installs it, so it never reports another agent's rooms.
|
|
1284
|
+
if (action === "install") hooks.install(names, flags.as || (Object.keys(state.profiles).length ? whoAmI(state) : undefined));
|
|
1285
|
+
else if (action === "uninstall") hooks.uninstall(names);
|
|
1286
|
+
else throw new Error("Usage: agm hooks install [claude|codex] or agm hooks uninstall [claude|codex]");
|
|
1287
|
+
},
|
|
1288
|
+
|
|
1289
|
+
// Called by Claude Code and Codex themselves, not by you. See src/hooks.js.
|
|
1290
|
+
async hook(args, state) {
|
|
1291
|
+
// Codex's listener is a program of its own, so the hook can start it again without the agent.
|
|
1292
|
+
const restart = (name, thread, options = {}) => listening.startResident(fileURLToPath(new URL(import.meta.url)), name, { ...options, thread, watchPid: codexPid() });
|
|
1293
|
+
await hooks.run(state, args.flags.as, { format: args.flags.format, rewake: args.words.includes("rewake"), restart });
|
|
1294
|
+
},
|
|
1295
|
+
|
|
1296
|
+
// Lists every agent set up on this machine, so it also works when it is unclear who you are.
|
|
1297
|
+
// What agm can tell about where it runs, for when a name comes out wrong. Prints names of settings, never values.
|
|
1298
|
+
async doctor() {
|
|
1299
|
+
const { default: pkg } = await import("../package.json", { with: { type: "json" } });
|
|
1300
|
+
let latest = "unknown (server not reached)";
|
|
1301
|
+
try {
|
|
1302
|
+
latest = (await call(process.env.AGM_API || DEFAULT_API, "GET", "/info")).cli || "unknown";
|
|
1303
|
+
} catch {
|
|
1304
|
+
// keep "unknown"
|
|
1305
|
+
}
|
|
1306
|
+
console.log(`agm ${pkg.version} (latest ${latest}) · node ${process.versions.node} · ${process.platform}`);
|
|
1307
|
+
console.log(`name agm would give you: ${autoName()}`);
|
|
1308
|
+
console.log(` human: ${humanName() || "(none)"}${process.env.AGM_HUMAN ? " (from AGM_HUMAN)" : ""} · computer: ${computerName()} · hostname: ${os.hostname()}`);
|
|
1309
|
+
console.log(` agent program from settings: ${programFromEnv(process.env)} · used: ${agentProgram()}`);
|
|
1310
|
+
const hints = Object.keys(process.env).filter((key) => /ANTIGRAVITY|GEMINI|CLAUDE|CODEX|CURSOR|WINDSURF|OPENCODE|COPILOT|AGENT|TERM_PROGRAM|VSCODE/i.test(key)).sort();
|
|
1311
|
+
console.log(` settings that hint at the program (names only): ${hints.join(", ") || "(none)"}`);
|
|
1312
|
+
console.log(" started by (nearest first):");
|
|
1313
|
+
for (const command of ancestors()) console.log(` ${command.split(/\s+-/)[0].slice(0, 120)}`);
|
|
1314
|
+
},
|
|
1315
|
+
|
|
1316
|
+
async rooms(_, state) {
|
|
1317
|
+
const names = Object.keys(state.profiles);
|
|
1318
|
+
if (!names.length) return console.log('Nobody on this machine is in a room. Join one with: agm join "<room link>" --as <name>');
|
|
1319
|
+
for (const name of names) {
|
|
1320
|
+
const profile = state.profiles[name];
|
|
1321
|
+
for (const room of Object.values(profile.rooms)) console.log(`${room.id === profile.current ? "*" : " "} ${room.id} "${room.title}" as ${name}`);
|
|
1322
|
+
}
|
|
1323
|
+
},
|
|
1324
|
+
|
|
1325
|
+
async use({ flags, words }, state) {
|
|
1326
|
+
const profile = me(state, flags);
|
|
1327
|
+
const room = pickRoom(profile, words[0] || "");
|
|
1328
|
+
profile.current = room.id;
|
|
1329
|
+
save(state);
|
|
1330
|
+
console.log(`Now using "${room.title}" as ${room.name}.`);
|
|
1331
|
+
},
|
|
1332
|
+
|
|
1333
|
+
async invite({ flags }, state) {
|
|
1334
|
+
const room = pickRoom(me(state, flags), flags.room);
|
|
1335
|
+
if (/^https?:/.test(room.link || "")) {
|
|
1336
|
+
if (room.linkStale) {
|
|
1337
|
+
console.log(`Warning: the room link for "${room.title}" was rotated by someone else after you joined, so this cached link no longer works. Ask for the current link, or run: agm rotate --as ${room.name} --room ${room.id}`);
|
|
1338
|
+
} else {
|
|
1339
|
+
console.log(`Room link for "${room.title}". Agents join with it; humans open it in a browser to watch:`);
|
|
1340
|
+
}
|
|
1341
|
+
return console.log(room.link);
|
|
1342
|
+
}
|
|
1343
|
+
const origin = new URL(room.api).origin;
|
|
1344
|
+
console.log(`You are invited to the Agent DM room "${room.title}".`);
|
|
1345
|
+
console.log("Give this whole message to your AI agent (Claude Code, Codex, ...).\n");
|
|
1346
|
+
console.log(`Agent: read ${origin}/install.md and follow it, then join with this invite:\n${room.link || room.invite}`);
|
|
1347
|
+
},
|
|
1348
|
+
|
|
1349
|
+
async web({ flags }, state) {
|
|
1350
|
+
const profileNames = flags.as || process.env.AGM_AS ? [whoAmI(state, flags.as, autoName())] : Object.keys(state.profiles);
|
|
1351
|
+
const byOrigin = new Map();
|
|
1352
|
+
const seen = new Set();
|
|
1353
|
+
const addRoom = (room, isCurrent) => {
|
|
1354
|
+
const m = /^(https?:\/\/[^\s"'<>\/]+)\/(\d{3}-\d{3}-\d{3}|[a-z]{3}-[a-z]{4}-[a-z]{3})\?pwd=([A-Za-z0-9_-]{20,})/.exec(room.link || "");
|
|
1355
|
+
if (!m) return;
|
|
1356
|
+
const origin = m[1].replace(/\/+$/, "");
|
|
1357
|
+
const key = `${origin.toLowerCase()}:${room.id}`;
|
|
1358
|
+
if (seen.has(key)) return;
|
|
1359
|
+
seen.add(key);
|
|
1360
|
+
if (!byOrigin.has(origin)) byOrigin.set(origin, []);
|
|
1361
|
+
const entry = { id: room.id, number: m[2], pwd: m[3], title: room.title || m[2] };
|
|
1362
|
+
if (isCurrent) byOrigin.get(origin).unshift(entry);
|
|
1363
|
+
else byOrigin.get(origin).push(entry);
|
|
1364
|
+
};
|
|
1365
|
+
for (const name of profileNames) {
|
|
1366
|
+
const profile = state.profiles[name];
|
|
1367
|
+
if (!profile) continue;
|
|
1368
|
+
for (const room of Object.values(profile.rooms || {})) {
|
|
1369
|
+
addRoom(room, room.id === profile.current);
|
|
1370
|
+
}
|
|
1371
|
+
}
|
|
1372
|
+
if (!byOrigin.size) {
|
|
1373
|
+
throw new Error('No rooms with web links found on this machine. Open or join a room first: agm join "<room link>"');
|
|
1374
|
+
}
|
|
1375
|
+
const openBrowser = (url) => {
|
|
1376
|
+
if (flags["no-open"] || process.env.AGM_NO_BROWSER) return false;
|
|
1377
|
+
try {
|
|
1378
|
+
if (process.platform === "darwin") {
|
|
1379
|
+
spawn("open", [url], { detached: true, stdio: "ignore" }).unref();
|
|
1380
|
+
return true;
|
|
1381
|
+
}
|
|
1382
|
+
if (process.platform === "win32") {
|
|
1383
|
+
spawn("cmd", ["/c", "start", "", url], { detached: true, windowsHide: true, stdio: "ignore" }).unref();
|
|
1384
|
+
return true;
|
|
1385
|
+
}
|
|
1386
|
+
if (process.platform === "linux" && (process.env.DISPLAY || process.env.WAYLAND_DISPLAY)) {
|
|
1387
|
+
spawn("xdg-open", [url], { detached: true, stdio: "ignore" }).unref();
|
|
1388
|
+
return true;
|
|
1389
|
+
}
|
|
1390
|
+
} catch {
|
|
1391
|
+
// fallback to printing URL
|
|
1392
|
+
}
|
|
1393
|
+
return false;
|
|
1394
|
+
};
|
|
1395
|
+
for (const [origin, list] of byOrigin) {
|
|
1396
|
+
const payload = list.map((r) => `${r.number}?pwd=${r.pwd}`).join("\n");
|
|
1397
|
+
const url = `${origin}/room#sync=${Buffer.from(payload, "utf8").toString("base64url")}`;
|
|
1398
|
+
const opened = openBrowser(url);
|
|
1399
|
+
console.log(`${opened ? "Opened" : "Sync"} ${list.length} room${list.length === 1 ? "" : "s"} in your browser (${list.map((r) => r.number).join(", ")}).`);
|
|
1400
|
+
console.log("The #sync=... fragment stays local to your browser and is cleared immediately after import:");
|
|
1401
|
+
console.log(url);
|
|
1402
|
+
}
|
|
1403
|
+
},
|
|
1404
|
+
|
|
1405
|
+
async webhook({ flags, words }, state) {
|
|
1406
|
+
const room = pickRoom(me(state, flags), flags.room);
|
|
1407
|
+
const sub = words[0] || "list";
|
|
1408
|
+
if (sub === "list" || sub === "ls") {
|
|
1409
|
+
const data = await call(room.api, "GET", "/webhooks", { credential: room.token });
|
|
1410
|
+
const list = data.webhooks || [];
|
|
1411
|
+
if (!list.length) {
|
|
1412
|
+
console.log(`No webhooks configured for ${room.name} in "${format.clean(room.title)}".`);
|
|
1413
|
+
console.log(`Add one with: agm webhook add https://your-host.example/agentdm`);
|
|
1414
|
+
return;
|
|
1415
|
+
}
|
|
1416
|
+
console.log(`Webhooks for ${room.name} in "${format.clean(room.title)}":`);
|
|
1417
|
+
for (const h of list) {
|
|
1418
|
+
const status = h.disabledAt ? `disabled (${h.consecutiveFailures} failures)` : `active`;
|
|
1419
|
+
const scope = h.all ? "all messages" : "addressed/pair";
|
|
1420
|
+
const last = h.lastStatus ? `, last HTTP ${h.lastStatus} at #${h.lastDeliveredSeq || 0}` : "";
|
|
1421
|
+
console.log(` ${h.id} ${status} [${(h.events || []).join(",")}; ${scope}] ${h.url}${last}`);
|
|
1422
|
+
}
|
|
1423
|
+
return;
|
|
1424
|
+
}
|
|
1425
|
+
if (sub === "add" || sub === "set") {
|
|
1426
|
+
const url = (words[1] || "").trim();
|
|
1427
|
+
if (!url) throw new Error("Give the webhook URL: agm webhook add <https-url> [--all] [--events message,join] [--secret whsec_...]");
|
|
1428
|
+
const body = { url, all: !!flags.all };
|
|
1429
|
+
if (flags.events) body.events = flags.events.split(",").map((e) => e.trim()).filter(Boolean);
|
|
1430
|
+
if (flags.secret) body.secret = flags.secret;
|
|
1431
|
+
const data = await call(room.api, "POST", "/webhooks", { credential: room.token, body });
|
|
1432
|
+
const h = data.webhook;
|
|
1433
|
+
console.log(`Webhook ${h.id} saved for ${room.name} in "${format.clean(room.title)}".`);
|
|
1434
|
+
console.log(`URL: ${h.url}`);
|
|
1435
|
+
console.log(`Events: ${(h.events || []).join(", ")} (${h.all ? "all room messages" : "messages addressed to you or 2-person rooms"})`);
|
|
1436
|
+
console.log(`Secret: ${data.secret}`);
|
|
1437
|
+
console.log("Save this secret now (shown only once). Requests are signed with Standard Webhooks headers: webhook-id, webhook-timestamp, webhook-signature (HMAC-SHA256).");
|
|
1438
|
+
console.log(`Verify delivery with: agm webhook test ${h.id}`);
|
|
1439
|
+
return;
|
|
1440
|
+
}
|
|
1441
|
+
if (sub === "test") {
|
|
1442
|
+
const id = (words[1] || "").trim();
|
|
1443
|
+
if (!id) throw new Error("Give the webhook id: agm webhook test <id>");
|
|
1444
|
+
const data = await call(room.api, "POST", `/webhooks/${encodeURIComponent(id)}/test`, { credential: room.token });
|
|
1445
|
+
if (data.ok) {
|
|
1446
|
+
console.log(`Webhook ${id} test succeeded (HTTP ${data.status}).`);
|
|
1447
|
+
} else {
|
|
1448
|
+
console.log(`Webhook ${id} test failed (${data.error || `HTTP ${data.status || 0}`}).`);
|
|
1449
|
+
process.exitCode = 1;
|
|
1450
|
+
}
|
|
1451
|
+
return;
|
|
1452
|
+
}
|
|
1453
|
+
if (sub === "remove" || sub === "rm" || sub === "delete") {
|
|
1454
|
+
const id = (words[1] || "").trim();
|
|
1455
|
+
if (!id) throw new Error("Give the webhook id: agm webhook remove <id>");
|
|
1456
|
+
await call(room.api, "DELETE", `/webhooks/${encodeURIComponent(id)}`, { credential: room.token });
|
|
1457
|
+
console.log(`Webhook ${id} removed.`);
|
|
1458
|
+
return;
|
|
1459
|
+
}
|
|
1460
|
+
throw new Error('Unknown webhook subcommand. Use: agm webhook add <url> | list | test <id> | remove <id>');
|
|
1461
|
+
},
|
|
1462
|
+
|
|
1463
|
+
async doctor({ flags }, state) {
|
|
1464
|
+
let fails = 0;
|
|
1465
|
+
let warns = 0;
|
|
1466
|
+
const ok = (msg) => console.log(`[OK] ${msg}`);
|
|
1467
|
+
const warn = (msg) => { warns++; console.log(`[WARN] ${msg}`); };
|
|
1468
|
+
const fail = (msg) => { fails++; console.log(`[FAIL] ${msg}`); };
|
|
1469
|
+
|
|
1470
|
+
const own = update.own();
|
|
1471
|
+
const api = process.env.AGM_API || DEFAULT_API;
|
|
1472
|
+
try {
|
|
1473
|
+
const info = await call(api, "GET", "/info", { timeoutSeconds: 8 });
|
|
1474
|
+
if (info?.cli && update.newer(info.cli, own)) warn(`CLI agm ${own} is out of date (${info.cli} is available) -> run: agm update`);
|
|
1475
|
+
else ok(`CLI agm ${own} (server ${new URL(api).origin} reports ${info?.cli || "ok"})`);
|
|
1476
|
+
} catch (err) {
|
|
1477
|
+
fail(`Server ${api} unreachable: ${err.message}`);
|
|
1478
|
+
}
|
|
1479
|
+
|
|
1480
|
+
const host = agentProgram();
|
|
1481
|
+
const installedHooks = hooks.installedHosts();
|
|
1482
|
+
const wsMode = typeof WebSocket === "function" && !process.env.AGM_NO_WS ? "WebSocket push (with HTTP fallback)" : "HTTP long-poll";
|
|
1483
|
+
ok(`Host environment: ${host}, transport: ${wsMode}${installedHooks.length ? `, hooks: ${installedHooks.join(", ")}` : ", no hooks installed"}`);
|
|
1484
|
+
if (host === "codex" && !codexRules.allowed()) warn(`Codex sandbox blocks network for agm -> human should run: agm codex allow`);
|
|
1485
|
+
if (host === "claude" && hooks.claudeSupportsRewake() && !installedHooks.includes("claude")) {
|
|
1486
|
+
warn("Claude Code >= 2.1.296 supports native zero-gap wake hooks -> run: agm hooks install claude");
|
|
1487
|
+
}
|
|
1488
|
+
if (host === "claude") {
|
|
1489
|
+
const inbox = harnesses.claudeLiveInbox(process.env.CLAUDE_CODE_SESSION_ID);
|
|
1490
|
+
if (inbox && !inbox.held) ok(`Claude live inbox socket available (pid ${inbox.pid})`);
|
|
1491
|
+
else if (inbox?.held) warn('Claude live session is in bypassPermissions without crossSessionInbound="accept" -> run: agm claude allow');
|
|
1492
|
+
}
|
|
1493
|
+
if (host === "antigravity") {
|
|
1494
|
+
const hub = await harnesses.antigravityHub();
|
|
1495
|
+
const apiExe = harnesses.antigravityAgentApi();
|
|
1496
|
+
if (hub && apiExe) ok(`Antigravity App hub reachable (${hub.address}, agentapi ready)`);
|
|
1497
|
+
else warn("Antigravity App hub or agentapi not found -> open Antigravity App to enable direct conversation wakes");
|
|
1498
|
+
}
|
|
1499
|
+
|
|
1500
|
+
const names = flags.as || process.env.AGM_AS
|
|
1501
|
+
? [whoAmI(state, flags.as, autoName())]
|
|
1502
|
+
: Object.keys(state.profiles || {});
|
|
1503
|
+
if (!names.length) {
|
|
1504
|
+
warn('No agent profiles configured yet -> run: agm join "<room link>"');
|
|
1505
|
+
return;
|
|
1506
|
+
}
|
|
1507
|
+
|
|
1508
|
+
for (const name of names) {
|
|
1509
|
+
const rooms = Object.values(state.profiles[name]?.rooms || {});
|
|
1510
|
+
const sessionRun = listening.running(name);
|
|
1511
|
+
const daemonRun = service.serviceRunning(name);
|
|
1512
|
+
const daemonFile = service.installedFile(name);
|
|
1513
|
+
if (sessionRun) {
|
|
1514
|
+
const detail = sessionRun.thread
|
|
1515
|
+
? `, Codex ${sessionRun.thread}`
|
|
1516
|
+
: sessionRun.conversation
|
|
1517
|
+
? `, Antigravity ${sessionRun.conversation}`
|
|
1518
|
+
: sessionRun.stream
|
|
1519
|
+
? ", stream"
|
|
1520
|
+
: "";
|
|
1521
|
+
ok(`${name}: session listener running (pid ${sessionRun.pid}${detail})`);
|
|
1522
|
+
}
|
|
1523
|
+
if (daemonRun) {
|
|
1524
|
+
ok(`${name}: always-on service running (pid ${daemonRun.pid}, mode ${daemonRun.mode || "watching"}, ${daemonRun.agent}, auto-update ${daemonRun.autoUpdate === false ? "off" : "on"})`);
|
|
1525
|
+
} else if (daemonFile) {
|
|
1526
|
+
fail(`${name}: always-on service installed (${daemonFile}) but NOT running -> check ${service.serviceLog(name)}`);
|
|
1527
|
+
}
|
|
1528
|
+
const unverified = harnesses.unresolvedWake(service.readStatus(name)?.unverifiedWake, state, name)
|
|
1529
|
+
|| harnesses.unresolvedWake(listening.memo(name)?.unverifiedWake, state, name);
|
|
1530
|
+
if (unverified) {
|
|
1531
|
+
warn(`${name}: unconfirmed wake at ${unverified.at} (${unverified.how}) in ${unverified.rooms.map((r) => r.title).join(", ")} (readSeq still behind) -> run: agm catchup --as ${name}`);
|
|
1532
|
+
}
|
|
1533
|
+
if (!rooms.length) {
|
|
1534
|
+
if (!sessionRun && !daemonRun) {
|
|
1535
|
+
warn(`${name}: no active listener or always-on service -> run: agm listen --as ${name} (or agm daemon install --as ${name})`);
|
|
1536
|
+
}
|
|
1537
|
+
warn(`${name}: not in any rooms`);
|
|
1538
|
+
continue;
|
|
1539
|
+
}
|
|
1540
|
+
let webhookRooms = 0;
|
|
1541
|
+
const roomLines = [];
|
|
1542
|
+
for (const room of rooms) {
|
|
1543
|
+
try {
|
|
1544
|
+
const data = await call(room.api, "GET", "/members", { credential: room.token, timeoutSeconds: 8 });
|
|
1545
|
+
const self = data.members.find((m) => m.name === room.name);
|
|
1546
|
+
let activeHooks = 0;
|
|
1547
|
+
try {
|
|
1548
|
+
const wh = await call(room.api, "GET", "/webhooks", { credential: room.token, timeoutSeconds: 5 });
|
|
1549
|
+
activeHooks = (wh.webhooks || []).filter((h) => !h.disabledAt).length;
|
|
1550
|
+
} catch {
|
|
1551
|
+
// older server without /v1/webhooks
|
|
1552
|
+
}
|
|
1553
|
+
if (activeHooks > 0) webhookRooms++;
|
|
1554
|
+
const status = self?.working ? "working" : self?.listening ? "listening" : "not listening";
|
|
1555
|
+
const hookNote = activeHooks > 0 ? `, ${activeHooks} webhook${activeHooks === 1 ? "" : "s"}` : "";
|
|
1556
|
+
roomLines.push(() => ok(`${name} in "${format.clean(data.room.title)}" (${data.room.number || room.id}): ${status}${hookNote}, ${data.unread} unread`));
|
|
1557
|
+
} catch (err) {
|
|
1558
|
+
if (err instanceof ApiError && err.status === 401) roomLines.push(() => fail(`${name} in "${format.clean(room.title || room.id)}" (${room.id}): unauthorized (401 — left or revoked)`));
|
|
1559
|
+
else roomLines.push(() => fail(`${name} in "${format.clean(room.title || room.id)}" (${room.id}): ${err.message}`));
|
|
1560
|
+
}
|
|
1561
|
+
}
|
|
1562
|
+
if (!sessionRun && !daemonRun) {
|
|
1563
|
+
if (webhookRooms === rooms.length) {
|
|
1564
|
+
ok(`${name}: server-side webhook push active on all ${webhookRooms} room(s)`);
|
|
1565
|
+
} else {
|
|
1566
|
+
warn(`${name}: no active listener or always-on service -> run: agm listen --as ${name} (or agm daemon install --as ${name}, or agm webhook add <https-url>)`);
|
|
1567
|
+
}
|
|
1568
|
+
}
|
|
1569
|
+
for (const line of roomLines) line();
|
|
1570
|
+
}
|
|
1571
|
+
if (fails) {
|
|
1572
|
+
console.log(`\nDoctor found ${fails} failure(s) and ${warns} warning(s).`);
|
|
1573
|
+
process.exitCode = 1;
|
|
1574
|
+
} else if (warns) {
|
|
1575
|
+
console.log(`\nDoctor found 0 failures and ${warns} warning(s).`);
|
|
1576
|
+
} else {
|
|
1577
|
+
console.log("\nAll checks passed.");
|
|
1578
|
+
}
|
|
1579
|
+
},
|
|
1580
|
+
};
|
|
1581
|
+
|
|
1582
|
+
commands["rotate-passcode"] = commands.rotate;
|
|
1583
|
+
|
|
1584
|
+
async function main() {
|
|
1585
|
+
const [name, ...rest] = process.argv.slice(2);
|
|
1586
|
+
if (!name || name === "help" || rest.includes("--help") || rest.includes("-h") || name === "--help" || name === "-h") return console.log(HELP);
|
|
1587
|
+
if (name === "--version" || name === "-v") {
|
|
1588
|
+
const { default: pkg } = await import("../package.json", { with: { type: "json" } });
|
|
1589
|
+
return console.log(pkg.version);
|
|
1590
|
+
}
|
|
1591
|
+
const command = commands[name];
|
|
1592
|
+
if (!command) throw new Error(`Unknown command "${name}". Run agm help.`);
|
|
1593
|
+
// After its work, agm says once what changed since the version this machine last ran, and when it is behind
|
|
1594
|
+
// it says so, with the one command that updates it.
|
|
1595
|
+
if (!["hook", "daemon", "doctor", "listen", "update", "notes"].includes(name)) {
|
|
1596
|
+
// Already in a room before this command: an agent that was using agm, not one installing it now.
|
|
1597
|
+
let wasInRoom = false;
|
|
1598
|
+
try {
|
|
1599
|
+
wasInRoom = Object.keys(load().profiles).length > 0;
|
|
1600
|
+
} catch {}
|
|
1601
|
+
process.on("exit", () => {
|
|
1602
|
+
try {
|
|
1603
|
+
printNotes(wasInRoom);
|
|
1604
|
+
const own = update.own();
|
|
1605
|
+
if (latestSeen && update.newer(latestSeen, own)) {
|
|
1606
|
+
const how = update.plan("x") ? "agm update" : `npm install -g --allow-remote=root ${new URL(process.env.AGM_API || DEFAULT_API).origin}/agm.tgz`;
|
|
1607
|
+
console.log(`\nThis agm (${own}) is out of date; ${latestSeen} is out. Update it now, before you go on: ${how}`);
|
|
1608
|
+
}
|
|
1609
|
+
} catch {
|
|
1610
|
+
// never let this note break a command
|
|
1611
|
+
}
|
|
1612
|
+
});
|
|
1613
|
+
}
|
|
1614
|
+
if (name === "hook") {
|
|
1615
|
+
// Never let a reminder break a session: whatever goes wrong, stay silent and succeed.
|
|
1616
|
+
try {
|
|
1617
|
+
restartBehindProxy();
|
|
1618
|
+
await command(parseArgs(rest, name), load());
|
|
1619
|
+
} catch {}
|
|
1620
|
+
return;
|
|
1621
|
+
}
|
|
1622
|
+
restartBehindProxy();
|
|
1623
|
+
await command(parseArgs(rest, name), load());
|
|
1624
|
+
}
|
|
1625
|
+
|
|
1626
|
+
main().catch((err) => {
|
|
1627
|
+
const code = err instanceof ApiError && err.code ? ` (${err.code})` : "";
|
|
1628
|
+
console.error(`agm: ${err.message}${code}`);
|
|
1629
|
+
// Inside Codex a network failure is nearly always the sandbox; say what gets past it.
|
|
1630
|
+
if (err instanceof ApiError && err.code === "network" && agentProgram() === "codex") {
|
|
1631
|
+
console.error(codexRules.allowed() ? "Codex's sandbox blocked this. agm is already allowed, but this Codex session started before that: ask to run this command outside the sandbox, and tell your human that restarting Codex ends the asking." : `Codex's sandbox blocked this. ${codexRules.ASK}`);
|
|
1632
|
+
}
|
|
1633
|
+
process.exit(1);
|
|
1634
|
+
});
|