@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/src/service.js
ADDED
|
@@ -0,0 +1,768 @@
|
|
|
1
|
+
// agm daemon install: an always-on service that wakes this agent whenever someone in its rooms talks to it,
|
|
2
|
+
// for as long as the computer is on.
|
|
3
|
+
//
|
|
4
|
+
// Listening used to hang on a session (a background task, a hook, a Codex window). Sessions close, crash, hit
|
|
5
|
+
// time limits and do not survive a restart, so listening kept lapsing. Here the waiting hangs on the computer
|
|
6
|
+
// instead: the system (systemd on Linux, launchd on a Mac) starts this program at boot and again whenever it
|
|
7
|
+
// stops. A session is only where a wake goes:
|
|
8
|
+
// - a session that listens itself (the Claude wake hook, the Codex listener) is left to do so: the service
|
|
9
|
+
// steps aside, so a message never wakes two copies of the agent;
|
|
10
|
+
// - otherwise the service resumes the agent's own last session (`claude -p --resume`, `codex exec resume`)
|
|
11
|
+
// in that session's folder, so the agent that answers remembers what it was doing;
|
|
12
|
+
// - with no session to resume, it starts a new one in the folder chosen at install.
|
|
13
|
+
// By default the woken agent may do what it can do when its human is there (Haitao's decision 2026-12-04:
|
|
14
|
+
// foundation first, safety later). --room-only limits it to agm commands.
|
|
15
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
16
|
+
import fs from "node:fs";
|
|
17
|
+
import os from "node:os";
|
|
18
|
+
import path from "node:path";
|
|
19
|
+
import { call, DEFAULT_API } from "./api.js";
|
|
20
|
+
import { load } from "./state.js";
|
|
21
|
+
import * as listening from "./listen.js";
|
|
22
|
+
import * as harnesses from "./harnesses.js";
|
|
23
|
+
import * as update from "./update.js";
|
|
24
|
+
|
|
25
|
+
const dir = () => process.env.AGM_HOME || path.join(os.homedir(), ".agm");
|
|
26
|
+
const safe = (name) => name.replace(/[^a-z0-9._-]/gi, "_").replace(/^\.+/, "_");
|
|
27
|
+
const statusFile = (name) => path.join(dir(), `service-${safe(name)}.json`);
|
|
28
|
+
const envFile = (name) => path.join(dir(), `service-${safe(name)}.env.json`);
|
|
29
|
+
export const serviceLog = (name) => path.join(dir(), `service-${safe(name)}.log`);
|
|
30
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
31
|
+
const log = (text) => console.log(`${new Date().toISOString()} ${text}`);
|
|
32
|
+
// A session that was just woken is answering and will listen again when its turn ends. Leave it this long
|
|
33
|
+
// while its host process is alive and it has not finished catching up.
|
|
34
|
+
const BUSY_MS = 15 * 60 * 1000;
|
|
35
|
+
const CAUGHT_UP_GRACE_MS = 30 * 1000;
|
|
36
|
+
const RUN_LIMIT_MS = 30 * 60 * 1000;
|
|
37
|
+
|
|
38
|
+
function alive(pid) {
|
|
39
|
+
try {
|
|
40
|
+
process.kill(pid, 0);
|
|
41
|
+
return true;
|
|
42
|
+
} catch (err) {
|
|
43
|
+
return err.code === "EPERM";
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function readStatus(name) {
|
|
48
|
+
try {
|
|
49
|
+
return JSON.parse(fs.readFileSync(statusFile(name), "utf8"));
|
|
50
|
+
} catch {
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
function writeStatus(name, update) {
|
|
55
|
+
fs.mkdirSync(dir(), { recursive: true, mode: 0o700 });
|
|
56
|
+
const next = { ...readStatus(name), ...update };
|
|
57
|
+
const tmp = `${statusFile(name)}.${process.pid}.tmp`;
|
|
58
|
+
fs.writeFileSync(tmp, JSON.stringify(next) + "\n", { mode: 0o600 });
|
|
59
|
+
fs.renameSync(tmp, statusFile(name));
|
|
60
|
+
}
|
|
61
|
+
// The service process for this name, if it is running.
|
|
62
|
+
export function serviceRunning(name) {
|
|
63
|
+
const found = readStatus(name);
|
|
64
|
+
return found && Number.isInteger(found.pid) && alive(found.pid) ? found : null;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// ---- where the agent's own session lives ----
|
|
68
|
+
|
|
69
|
+
function firstCwd(file, pick) {
|
|
70
|
+
// Session files can be large; the folder is near the start.
|
|
71
|
+
const fd = fs.openSync(file, "r");
|
|
72
|
+
try {
|
|
73
|
+
const buf = Buffer.alloc(256 * 1024);
|
|
74
|
+
const text = buf.subarray(0, fs.readSync(fd, buf, 0, buf.length, 0)).toString("utf8");
|
|
75
|
+
for (const line of text.split("\n")) {
|
|
76
|
+
try {
|
|
77
|
+
const cwd = pick(JSON.parse(line));
|
|
78
|
+
if (typeof cwd === "string" && cwd) return cwd;
|
|
79
|
+
} catch {
|
|
80
|
+
// a partial last line
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
} finally {
|
|
84
|
+
fs.closeSync(fd);
|
|
85
|
+
}
|
|
86
|
+
return null;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function findClaude(session) {
|
|
90
|
+
const root = path.join(process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), ".claude"), "projects");
|
|
91
|
+
let projects = [];
|
|
92
|
+
try {
|
|
93
|
+
projects = fs.readdirSync(root);
|
|
94
|
+
} catch {
|
|
95
|
+
return null;
|
|
96
|
+
}
|
|
97
|
+
for (const project of projects) {
|
|
98
|
+
const file = path.join(root, project, `${session}.jsonl`);
|
|
99
|
+
if (fs.existsSync(file)) return firstCwd(file, (entry) => entry.cwd);
|
|
100
|
+
}
|
|
101
|
+
return null;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function findCodex(session) {
|
|
105
|
+
const root = path.join(process.env.CODEX_HOME || path.join(os.homedir(), ".codex"), "sessions");
|
|
106
|
+
const walk = (folder, depth) => {
|
|
107
|
+
let entries = [];
|
|
108
|
+
try {
|
|
109
|
+
entries = fs.readdirSync(folder, { withFileTypes: true });
|
|
110
|
+
} catch {
|
|
111
|
+
return null;
|
|
112
|
+
}
|
|
113
|
+
for (const entry of entries) {
|
|
114
|
+
const full = path.join(folder, entry.name);
|
|
115
|
+
if (entry.isDirectory() && depth < 4) {
|
|
116
|
+
const found = walk(full, depth + 1);
|
|
117
|
+
if (found) return found;
|
|
118
|
+
} else if (entry.isFile() && entry.name.endsWith(`${session}.jsonl`)) {
|
|
119
|
+
return firstCwd(full, (line) => line.payload?.cwd || line.cwd);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
return null;
|
|
123
|
+
};
|
|
124
|
+
return walk(root, 0);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// The session this agent last listened from, when it belongs to the agent program the service runs and can
|
|
128
|
+
// still be found on this computer: { session, cwd }.
|
|
129
|
+
export function isRaftManagedDir(cwd) {
|
|
130
|
+
return /[\\/]\.slock[\\/]agents[\\/]/i.test(String(cwd || ""));
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export function ownSession(name, agent) {
|
|
134
|
+
const intent = listening.wanted(name);
|
|
135
|
+
if (!intent?.session || intent.program !== agent || !/^[A-Za-z0-9-]{8,80}$/.test(intent.session)) return null;
|
|
136
|
+
if (agent === "antigravity") return { session: intent.session, cwd: null };
|
|
137
|
+
const cwd = agent === "claude" ? findClaude(intent.session) : agent === "codex" ? findCodex(intent.session) : null;
|
|
138
|
+
if (!cwd || !fs.existsSync(cwd) || isRaftManagedDir(cwd)) return null;
|
|
139
|
+
return { session: intent.session, cwd };
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
export const SUPPORTED_AGENTS = ["claude", "codex", "gemini", "opencode", "antigravity"];
|
|
143
|
+
|
|
144
|
+
// What to run for one wake: { command, args, cwd, how }.
|
|
145
|
+
export function wakeCommand({ agent, run, roomOnly, workdir, stateDir }, own) {
|
|
146
|
+
if (run) return { command: run, args: [], shell: true, cwd: workdir, how: "command" };
|
|
147
|
+
const cwd = own?.cwd || workdir;
|
|
148
|
+
if (agent === "claude") {
|
|
149
|
+
const power = roomOnly ? ["--allowedTools", "Bash(agm:*)"] : ["--dangerously-skip-permissions"];
|
|
150
|
+
const resume = own ? ["--resume", own.session] : [];
|
|
151
|
+
// `--` ends variadic options like --allowedTools so the prompt is never swallowed as another tool name.
|
|
152
|
+
return { command: process.env.AGM_CLAUDE_BIN || "claude", agent: "claude", args: ["-p", ...resume, ...power, "--"], notice: "last", cwd, how: own ? `resume ${own.session}` : "new session" };
|
|
153
|
+
}
|
|
154
|
+
if (agent === "codex") {
|
|
155
|
+
const power = roomOnly
|
|
156
|
+
? ["-c", 'sandbox_mode="workspace-write"', "-c", "sandbox_workspace_write.network_access=true", "-c", `sandbox_workspace_write.writable_roots=[${JSON.stringify(stateDir)}]`]
|
|
157
|
+
: ["--dangerously-bypass-approvals-and-sandbox"];
|
|
158
|
+
const args = own ? ["exec", "resume", "--skip-git-repo-check", ...power, own.session] : ["exec", "--skip-git-repo-check", ...power, "-C", cwd];
|
|
159
|
+
return { command: process.env.AGM_CODEX_BIN || "codex", agent: "codex", args, notice: "last", cwd, how: own ? `resume ${own.session}` : "new session" };
|
|
160
|
+
}
|
|
161
|
+
if (agent === "gemini") {
|
|
162
|
+
const power = roomOnly ? [] : ["--yolo"];
|
|
163
|
+
return { command: process.env.AGM_GEMINI_BIN || "gemini", agent: "gemini", args: [...power, "-p"], notice: "last", cwd, how: "new session" };
|
|
164
|
+
}
|
|
165
|
+
if (agent === "opencode") {
|
|
166
|
+
return { command: process.env.AGM_OPENCODE_BIN || "opencode", agent: "opencode", args: ["run"], notice: "last", cwd, how: "new session" };
|
|
167
|
+
}
|
|
168
|
+
if (agent === "antigravity") {
|
|
169
|
+
return { agent: "antigravity", direct: true, session: own?.session || null, cwd, how: own ? `antigravity ${own.session}` : "antigravity" };
|
|
170
|
+
}
|
|
171
|
+
throw new Error(`Say which agent the service wakes: --agent ${SUPPORTED_AGENTS.join("|")} (or --run '<command>').`);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
export function quoteWinShellArg(arg) {
|
|
175
|
+
const s = String(arg);
|
|
176
|
+
if (s && /^[A-Za-z0-9_@%+=:,./\\-]+$/.test(s)) return s;
|
|
177
|
+
return `"${s.replace(/"/g, '""')}"`;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function runOnce(spec, notice, env, logStream) {
|
|
181
|
+
return new Promise((resolve) => {
|
|
182
|
+
const useStdin = platformName() === "win32" && spec.notice === "last";
|
|
183
|
+
let args;
|
|
184
|
+
if (useStdin) {
|
|
185
|
+
if (spec.agent === "claude") args = spec.args.at(-1) === "--" ? spec.args.slice(0, -1) : [...spec.args];
|
|
186
|
+
else if (spec.agent === "codex") args = [...spec.args, "-"];
|
|
187
|
+
else args = [...spec.args];
|
|
188
|
+
} else {
|
|
189
|
+
args = spec.notice === "last" ? [...spec.args, notice] : spec.args;
|
|
190
|
+
}
|
|
191
|
+
// On Windows, npm installs claude/codex as .cmd shims, which require shell: true to spawn.
|
|
192
|
+
const useWinShell = !spec.shell && process.platform === "win32";
|
|
193
|
+
const command = useWinShell ? quoteWinShellArg(spec.command) : spec.command;
|
|
194
|
+
const spawnArgs = useWinShell ? args.map(quoteWinShellArg) : args;
|
|
195
|
+
const child = spawn(command, spawnArgs, {
|
|
196
|
+
shell: !!spec.shell || useWinShell,
|
|
197
|
+
cwd: spec.cwd,
|
|
198
|
+
windowsHide: true,
|
|
199
|
+
stdio: [useStdin ? "pipe" : "ignore", "pipe", "pipe"],
|
|
200
|
+
env: { ...process.env, ...env, AGM_NOTICE: notice },
|
|
201
|
+
});
|
|
202
|
+
if (useStdin && child.stdin) {
|
|
203
|
+
child.stdin.on("error", () => {});
|
|
204
|
+
child.stdin.end(notice);
|
|
205
|
+
}
|
|
206
|
+
const keep = (chunk) => logStream?.(chunk.toString());
|
|
207
|
+
child.stdout.on("data", keep);
|
|
208
|
+
child.stderr.on("data", keep);
|
|
209
|
+
const timer = setTimeout(() => child.kill("SIGTERM"), RUN_LIMIT_MS);
|
|
210
|
+
child.on("exit", (code, signal) => {
|
|
211
|
+
clearTimeout(timer);
|
|
212
|
+
resolve(code ?? (signal ? 128 : 1));
|
|
213
|
+
});
|
|
214
|
+
child.on("error", (err) => {
|
|
215
|
+
clearTimeout(timer);
|
|
216
|
+
keep(`could not start ${spec.command}: ${err.message}\n`);
|
|
217
|
+
resolve(-1);
|
|
218
|
+
});
|
|
219
|
+
});
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// Is a session of this agent listening, or busy answering a wake it will listen again after?
|
|
223
|
+
export function sessionHasIt(name) {
|
|
224
|
+
if (listening.running(name)) return true;
|
|
225
|
+
const intent = listening.wanted(name);
|
|
226
|
+
const end = listening.lastEnd(name);
|
|
227
|
+
if (end?.why !== "woke" || !intent) return false;
|
|
228
|
+
const elapsed = Date.now() - Date.parse(end.at);
|
|
229
|
+
if (!(elapsed < BUSY_MS)) return false;
|
|
230
|
+
// If the host process that owned the session already exited, take over immediately instead of waiting 15m.
|
|
231
|
+
if (Number.isInteger(intent.hostPid) && !listening.alive(intent.hostPid)) return false;
|
|
232
|
+
// Once the agent has already read everything it was woken for, wait at most 30s for it to re-arm.
|
|
233
|
+
const rooms = load().profiles?.[name]?.rooms || {};
|
|
234
|
+
const memo = listening.memo(name);
|
|
235
|
+
const toldEntries = Object.entries(memo.told || {}).filter(([id]) => rooms[id]);
|
|
236
|
+
const caughtUp = toldEntries.length > 0 && toldEntries.every(([id, seq]) => (rooms[id].cursor || 0) >= seq);
|
|
237
|
+
if (caughtUp && elapsed >= CAUGHT_UP_GRACE_MS) return false;
|
|
238
|
+
return true;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
function runNotify(notifyCmd, workdir, env) {
|
|
242
|
+
if (!notifyCmd) return;
|
|
243
|
+
try {
|
|
244
|
+
const child = spawn(notifyCmd, {
|
|
245
|
+
shell: true,
|
|
246
|
+
cwd: workdir,
|
|
247
|
+
windowsHide: true,
|
|
248
|
+
stdio: "ignore",
|
|
249
|
+
env: { ...process.env, ...env },
|
|
250
|
+
});
|
|
251
|
+
const timer = setTimeout(() => { try { child.kill("SIGTERM"); } catch {} }, 10000);
|
|
252
|
+
timer.unref?.();
|
|
253
|
+
child.on("exit", () => clearTimeout(timer));
|
|
254
|
+
child.on("error", () => clearTimeout(timer));
|
|
255
|
+
child.unref?.();
|
|
256
|
+
} catch {
|
|
257
|
+
// best effort: notification failure must never disrupt watching
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
// The service itself. Runs until the system stops it.
|
|
262
|
+
export async function serve(name, { agent, run, roomOnly = false, noResume = false, autoUpdate = true, notifyCmd, workdir, all = false, every = 5, maxPerHour = 20, maxExchanges = 8 }) {
|
|
263
|
+
workdir ||= os.homedir();
|
|
264
|
+
const stateDir = dir();
|
|
265
|
+
const autoUpdateEnabled = autoUpdate && process.env.AGM_NO_AUTO_UPDATE !== "1";
|
|
266
|
+
const autoUpdateFailed = new Map(); // version -> timestamp of last failed attempt
|
|
267
|
+
const AUTO_UPDATE_BACKOFF_MS = 30 * 60 * 1000;
|
|
268
|
+
wakeCommand({ agent, run, roomOnly, workdir, stateDir }, null); // fail early on a bad --agent
|
|
269
|
+
writeStatus(name, { pid: process.pid, since: new Date().toISOString(), agent: run ? "command" : agent, roomOnly, noResume, autoUpdate: autoUpdateEnabled, ...(notifyCmd ? { notifyCmd } : {}), workdir });
|
|
270
|
+
const quit = () => {
|
|
271
|
+
writeStatus(name, { pid: null, stopped: new Date().toISOString() });
|
|
272
|
+
process.exit(0);
|
|
273
|
+
};
|
|
274
|
+
for (const signal of ["SIGTERM", "SIGINT", "SIGHUP"]) process.on(signal, quit);
|
|
275
|
+
// Behind a proxy agm runs itself again as a child (see agm.js); end with the process the system watches.
|
|
276
|
+
const parent = process.ppid;
|
|
277
|
+
setInterval(() => process.ppid !== parent && quit(), 3000).unref();
|
|
278
|
+
log(`agm service for ${name}: waking ${run ? "a command" : agent}${roomOnly ? " (room only)" : " with full permissions"}${noResume ? " (fresh sessions)" : ""} (auto-update: ${autoUpdateEnabled ? "on" : "off"}) when someone talks to it.`);
|
|
279
|
+
|
|
280
|
+
let stepped = null;
|
|
281
|
+
let failures = 0;
|
|
282
|
+
for (;;) {
|
|
283
|
+
if (!Object.keys(load().profiles?.[name]?.rooms || {}).length) {
|
|
284
|
+
if (stepped !== "no-room") log(`${name} is in no room. Waiting for it to join one.`);
|
|
285
|
+
stepped = "no-room";
|
|
286
|
+
await sleep(5000);
|
|
287
|
+
continue;
|
|
288
|
+
}
|
|
289
|
+
if (sessionHasIt(name)) {
|
|
290
|
+
if (stepped !== "session") log("A session of this agent is listening (or answering). Leaving the wake to it.");
|
|
291
|
+
stepped = "session";
|
|
292
|
+
writeStatus(name, { mode: "session" });
|
|
293
|
+
await sleep(5000);
|
|
294
|
+
continue;
|
|
295
|
+
}
|
|
296
|
+
if (stepped !== "watching") log("No session is listening. Watching the rooms.");
|
|
297
|
+
stepped = "watching";
|
|
298
|
+
writeStatus(name, { mode: "watching" });
|
|
299
|
+
|
|
300
|
+
const hits = await listening.nextWake(name, { all, every, maxPerHour, maxExchanges, log, outstanding: new Map(), yieldTo: () => sessionHasIt(name) });
|
|
301
|
+
if (!hits || hits.yielded) continue;
|
|
302
|
+
|
|
303
|
+
// Safe idle self-update: apply same-minor patch releases directly via npm without waking the LLM agent.
|
|
304
|
+
if (hits.update) {
|
|
305
|
+
const target = hits.update;
|
|
306
|
+
const runningVer = update.BOOT_VERSION;
|
|
307
|
+
let onDisk;
|
|
308
|
+
try { onDisk = update.own(); } catch { onDisk = null; }
|
|
309
|
+
if (onDisk && !update.newer(target, onDisk)) {
|
|
310
|
+
if (update.newer(onDisk, runningVer)) {
|
|
311
|
+
log(`agm on disk is already ${onDisk} (running ${runningVer}); restarting service to load the new version.`);
|
|
312
|
+
writeStatus(name, { mode: "watching", lastAutoUpdate: { at: new Date().toISOString(), from: runningVer, to: onDisk } });
|
|
313
|
+
quit();
|
|
314
|
+
}
|
|
315
|
+
continue;
|
|
316
|
+
}
|
|
317
|
+
const roomsNow = Object.values(load().profiles?.[name]?.rooms || {});
|
|
318
|
+
const origin = new URL(roomsNow[0]?.api || process.env.AGM_API || DEFAULT_API).origin;
|
|
319
|
+
const canSelfUpdate = autoUpdateEnabled && onDisk && update.autoUpdateAllowed(onDisk, target) && !!update.plan(origin);
|
|
320
|
+
if (canSelfUpdate) {
|
|
321
|
+
const prevFail = autoUpdateFailed.get(target) || 0;
|
|
322
|
+
if (Date.now() - prevFail < AUTO_UPDATE_BACKOFF_MS) {
|
|
323
|
+
log(`Auto-update to ${target} is in backoff after a recent failure; skipping for now.`);
|
|
324
|
+
continue;
|
|
325
|
+
}
|
|
326
|
+
writeStatus(name, { mode: "updating" });
|
|
327
|
+
log(`Auto-updating agm ${onDisk} -> ${target} (same-minor patch release, idle daemon)...`);
|
|
328
|
+
const locked = await update.withUpdateLock(async () => {
|
|
329
|
+
const freshDisk = update.own();
|
|
330
|
+
if (!update.newer(target, freshDisk)) return { alreadyUpdated: true, before: runningVer, after: freshDisk };
|
|
331
|
+
return update.runQuiet(origin);
|
|
332
|
+
});
|
|
333
|
+
if (!locked.acquired) {
|
|
334
|
+
log("Another agm service on this machine is updating right now; waiting 15s and checking again.");
|
|
335
|
+
await sleep(15000);
|
|
336
|
+
let afterWait;
|
|
337
|
+
try { afterWait = update.own(); } catch { afterWait = null; }
|
|
338
|
+
if (afterWait && update.newer(afterWait, runningVer)) {
|
|
339
|
+
log(`agm was updated to ${afterWait} by sibling service (running ${runningVer}); restarting.`);
|
|
340
|
+
writeStatus(name, { mode: "watching", lastAutoUpdate: { at: new Date().toISOString(), from: runningVer, to: afterWait } });
|
|
341
|
+
quit();
|
|
342
|
+
}
|
|
343
|
+
// Allow next check if sibling failed
|
|
344
|
+
const prev = listening.memo(name);
|
|
345
|
+
listening.commit(name, { ...prev, updateTold: undefined });
|
|
346
|
+
continue;
|
|
347
|
+
}
|
|
348
|
+
const res = locked.value;
|
|
349
|
+
if (res?.alreadyUpdated || (res?.ok && update.newer(res.after, runningVer))) {
|
|
350
|
+
const toVer = res.after;
|
|
351
|
+
log(`Auto-updated agm ${runningVer} -> ${toVer}; restarting service so the new version runs.`);
|
|
352
|
+
writeStatus(name, { mode: "watching", lastAutoUpdate: { at: new Date().toISOString(), from: runningVer, to: toVer } });
|
|
353
|
+
quit();
|
|
354
|
+
}
|
|
355
|
+
autoUpdateFailed.set(target, Date.now());
|
|
356
|
+
log(`Auto-update to ${target} failed (${res?.error || "unknown"}). Will retry after 30m. Continuing to watch rooms.`);
|
|
357
|
+
writeStatus(name, { mode: "watching", lastAutoUpdateError: { at: new Date().toISOString(), target, error: res?.error || "unknown" } });
|
|
358
|
+
continue;
|
|
359
|
+
}
|
|
360
|
+
log(`agm ${target} is out (running ${runningVer}, disk ${onDisk || "unknown"}); ${!autoUpdateEnabled ? "auto-update is disabled" : !update.sameMinor(onDisk || "", target) ? "minor/major version jump requires manual agm update" : "not an npm install"}. Run \`agm update\` when ready.`);
|
|
361
|
+
continue;
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
const own = run || noResume || failures > 0 ? null : ownSession(name, agent);
|
|
365
|
+
const spec = wakeCommand({ agent, run, roomOnly, workdir, stateDir }, own);
|
|
366
|
+
const text = hits.update ? listening.updateNotice(name, hits.update).replace(/\n3\. Start listening again[^\n]*/, "") : listening.notice(name, hits, { again: false, inline: false, away: run ? undefined : roomOnly ? "room" : "full" });
|
|
367
|
+
const rooms = hits.update ? [] : hits.map((hit) => hit.room);
|
|
368
|
+
log(hits.update ? `agm ${hits.update} is out: waking the agent to update (${spec.how}).` : `Waking for ${hits.length} room(s) (${spec.how}, in ${spec.cwd}).`);
|
|
369
|
+
writeStatus(name, { mode: "waking", lastWake: { at: new Date().toISOString(), how: spec.how } });
|
|
370
|
+
|
|
371
|
+
// Signal yellow "working" lamp immediately on every wake path (both blocking CLI and live-session handoffs).
|
|
372
|
+
// For async live-session handoffs we use source "agent" (auto-cleared when the agent runs agm say/reply/done/wait);
|
|
373
|
+
// for blocking CLI runs we use source "daemon" (renewed every 30s and explicitly cleared in finally).
|
|
374
|
+
const report = (seconds, source = "daemon") => Promise.all(rooms.map((room) => call(room.api, "POST", "/activity", { credential: room.token, body: { source, seconds }, timeoutSeconds: 4 }).catch(() => {})));
|
|
375
|
+
const targets = hits.update ? [] : hits.map((hit) => ({ room: hit.room, targetSeq: hit.events.at(-1).seq }));
|
|
376
|
+
let code;
|
|
377
|
+
let tail = "";
|
|
378
|
+
let deliveryHow = spec.how;
|
|
379
|
+
let verified = true;
|
|
380
|
+
let unconfirmed = [];
|
|
381
|
+
{
|
|
382
|
+
// 1) Antigravity App: deliver directly to the conversation via local agentapi, then confirm readSeq moved.
|
|
383
|
+
if (!run && agent === "antigravity") {
|
|
384
|
+
if (!own?.session) {
|
|
385
|
+
log("No Antigravity conversation recorded for this agent; cannot deliver wake.");
|
|
386
|
+
code = 1;
|
|
387
|
+
} else {
|
|
388
|
+
const res = await harnesses.antigravitySend(own.session, text);
|
|
389
|
+
if (res.ok) {
|
|
390
|
+
deliveryHow = `antigravity ${own.session}`;
|
|
391
|
+
log(`Delivered wake to Antigravity conversation ${own.session}; verifying readSeq.`);
|
|
392
|
+
const check = await harnesses.verifyDelivery(name, targets);
|
|
393
|
+
verified = check.verified;
|
|
394
|
+
unconfirmed = check.unconfirmed;
|
|
395
|
+
if (verified) {
|
|
396
|
+
await report(60, "agent");
|
|
397
|
+
} else {
|
|
398
|
+
log(`Warning: Antigravity wake was not confirmed read (${unconfirmed.map((u) => u.title).join(", ")}).`);
|
|
399
|
+
}
|
|
400
|
+
code = 0;
|
|
401
|
+
} else {
|
|
402
|
+
log(`Could not wake Antigravity conversation ${own.session}: ${res.error || "unknown error"}.`);
|
|
403
|
+
code = 1;
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
// 2) Claude Code: if the target session is ALREADY live with a Unix inbox socket (and not held by bypassPermissions),
|
|
408
|
+
// inject the content-free wake notice straight into the live session and confirm readSeq advances.
|
|
409
|
+
// If unconfirmed after the window, automatically fall back to CLI resume so messages are never silently dropped.
|
|
410
|
+
if (code === undefined && !run && agent === "claude" && !noResume && own?.session) {
|
|
411
|
+
const inbox = harnesses.claudeLiveInbox(own.session);
|
|
412
|
+
if (inbox && !inbox.held) {
|
|
413
|
+
const res = await harnesses.claudeSocketSend(inbox, text);
|
|
414
|
+
if (res.ok) {
|
|
415
|
+
log(`Injected wake into live Claude session ${own.session} via Unix socket (pid ${inbox.pid}); verifying readSeq.`);
|
|
416
|
+
const check = await harnesses.verifyDelivery(name, targets);
|
|
417
|
+
if (check.verified) {
|
|
418
|
+
await report(60, "agent");
|
|
419
|
+
deliveryHow = `claude-socket ${own.session}`;
|
|
420
|
+
verified = true;
|
|
421
|
+
code = 0;
|
|
422
|
+
} else {
|
|
423
|
+
log(`Claude socket wake was not confirmed read within window (${check.unconfirmed.map((u) => u.title).join(", ")}); falling back to CLI resume.`);
|
|
424
|
+
deliveryHow = `claude-socket->${spec.how}`;
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
} else if (inbox?.held) {
|
|
428
|
+
log(`Live Claude session ${own.session} is in bypassPermissions without crossSessionInbound="accept"; falling back to CLI resume.`);
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
// 3) Codex: probe ~/.codex/thread-writer-locks/<id>.lock before spawning `codex exec resume`.
|
|
432
|
+
// If another Codex process currently holds this thread open, queue safely and confirm readSeq advances.
|
|
433
|
+
// If unconfirmed and the window has since closed, automatically fall back to CLI resume.
|
|
434
|
+
if (code === undefined && !run && agent === "codex" && !noResume && own?.session) {
|
|
435
|
+
if (harnesses.codexThreadOpen(own.session) === true) {
|
|
436
|
+
const codexBin = process.env.AGM_CODEX_BIN || "codex";
|
|
437
|
+
let queuedVia = null;
|
|
438
|
+
const q = spawnSync(codexBin, ["queue", "--thread", own.session, "--message", text], { encoding: "utf8", timeout: 30000, windowsHide: true, shell: process.platform === "win32" });
|
|
439
|
+
if (q.status === 0) {
|
|
440
|
+
queuedVia = "codex-queue";
|
|
441
|
+
} else {
|
|
442
|
+
const rpc = await harnesses.codexQueueAdd(own.session, text, undefined, { codexBin });
|
|
443
|
+
if (rpc.ok) queuedVia = "codex-rpc";
|
|
444
|
+
else {
|
|
445
|
+
log(`Codex thread ${own.session} is open in another process and queueing failed (${rpc.error || "unknown"}); skipping resume to avoid write collision.`);
|
|
446
|
+
code = 1;
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
if (queuedVia) {
|
|
450
|
+
log(`Codex thread ${own.session} is open in another process; queued wake safely (${queuedVia}), verifying readSeq.`);
|
|
451
|
+
const check = await harnesses.verifyDelivery(name, targets);
|
|
452
|
+
if (check.verified) {
|
|
453
|
+
await report(60, "agent");
|
|
454
|
+
deliveryHow = `${queuedVia} ${own.session}`;
|
|
455
|
+
verified = true;
|
|
456
|
+
code = 0;
|
|
457
|
+
} else if (harnesses.codexThreadOpen(own.session) === false) {
|
|
458
|
+
log(`Codex thread ${own.session} closed before reading queued wake; falling back to CLI resume.`);
|
|
459
|
+
deliveryHow = `${queuedVia}->${spec.how}`;
|
|
460
|
+
} else {
|
|
461
|
+
deliveryHow = `${queuedVia} ${own.session}`;
|
|
462
|
+
verified = false;
|
|
463
|
+
unconfirmed = check.unconfirmed;
|
|
464
|
+
log(`Warning: Codex thread ${own.session} is still open but did not confirm reading wake (${unconfirmed.map((u) => u.title).join(", ")}); skipping CLI resume to avoid write collision.`);
|
|
465
|
+
code = 0;
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
if (code === undefined) {
|
|
471
|
+
await report(60);
|
|
472
|
+
const timer = setInterval(() => report(60), 30000);
|
|
473
|
+
try {
|
|
474
|
+
const auth = Object.fromEntries(Object.entries(loadAuthEnv(name)).filter(([key]) => !process.env[key]));
|
|
475
|
+
code = await runOnce(spec, text, {
|
|
476
|
+
...auth,
|
|
477
|
+
AGM_AS: name,
|
|
478
|
+
AGM_WOKEN_BY_SERVICE: run ? "command" : roomOnly ? "room" : "full",
|
|
479
|
+
...(own ? {} : { AGM_FRESH_SESSION: "1" }),
|
|
480
|
+
}, (chunk) => {
|
|
481
|
+
process.stdout.write(chunk);
|
|
482
|
+
tail = (tail + chunk).slice(-800);
|
|
483
|
+
});
|
|
484
|
+
} finally {
|
|
485
|
+
clearInterval(timer);
|
|
486
|
+
await report(0);
|
|
487
|
+
}
|
|
488
|
+
if (code === 0 && targets.length) {
|
|
489
|
+
const check = await harnesses.verifyDelivery(name, targets, { timeoutMs: 0 });
|
|
490
|
+
verified = check.verified;
|
|
491
|
+
unconfirmed = check.unconfirmed;
|
|
492
|
+
if (!verified) {
|
|
493
|
+
log(`Warning: agent exited 0 without advancing readSeq in ${unconfirmed.map((u) => u.title).join(", ")}.`);
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
const nowIso = new Date().toISOString();
|
|
499
|
+
log(`The agent finished (exit code ${code}, ${verified ? "confirmed read" : "unconfirmed"}).`);
|
|
500
|
+
const unverifiedWake = code === 0 && !verified && unconfirmed.length
|
|
501
|
+
? { at: nowIso, how: deliveryHow, rooms: unconfirmed }
|
|
502
|
+
: null;
|
|
503
|
+
writeStatus(name, {
|
|
504
|
+
mode: "watching",
|
|
505
|
+
lastWake: { at: nowIso, how: deliveryHow, code, verified },
|
|
506
|
+
unverifiedWake,
|
|
507
|
+
});
|
|
508
|
+
if (code === 0) {
|
|
509
|
+
failures = 0;
|
|
510
|
+
// Told only once the agent has had the notice: a failed run is tried again.
|
|
511
|
+
if (hits.memo) listening.commit(name, hits.memo);
|
|
512
|
+
if (hits.update) {
|
|
513
|
+
log("Restarting so the updated agm runs.");
|
|
514
|
+
quit();
|
|
515
|
+
}
|
|
516
|
+
if (notifyCmd) {
|
|
517
|
+
runNotify(notifyCmd, workdir, {
|
|
518
|
+
AGM_AS: name,
|
|
519
|
+
AGM_WAKE_ROOMS: rooms.map((r) => r.id).join(","),
|
|
520
|
+
AGM_WAKE_EXIT: String(code),
|
|
521
|
+
AGM_WAKE_HOW: deliveryHow,
|
|
522
|
+
AGM_WAKE_VERIFIED: verified ? "1" : "0",
|
|
523
|
+
AGM_WAKE_SUMMARY: tail.trim().slice(-500),
|
|
524
|
+
});
|
|
525
|
+
}
|
|
526
|
+
} else {
|
|
527
|
+
failures++;
|
|
528
|
+
const prev = listening.memo(name);
|
|
529
|
+
if (hits.update) listening.commit(name, { ...prev, updateTold: undefined });
|
|
530
|
+
else if (hits.memo) listening.commit(name, { ...prev, wakes: hits.memo.wakes });
|
|
531
|
+
await sleep(Math.min(15 * 60 * 1000, 60000 * 2 ** (failures - 1)));
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
// ---- installing it with the system ----
|
|
537
|
+
|
|
538
|
+
const platformName = () => process.env.AGM_SERVICE_PLATFORM || process.platform;
|
|
539
|
+
const label = (name) => `ai.milliways.agm.${safe(name)}`;
|
|
540
|
+
const unitName = (name) => `agm-${safe(name)}.service`;
|
|
541
|
+
const unitFile = (name) => path.join(process.env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config"), "systemd", "user", unitName(name));
|
|
542
|
+
const plistFile = (name) => path.join(os.homedir(), "Library", "LaunchAgents", `${label(name)}.plist`);
|
|
543
|
+
const winStartupDir = () => path.join(process.env.APPDATA || path.join(os.homedir(), "AppData", "Roaming"), "Microsoft", "Windows", "Start Menu", "Programs", "Startup");
|
|
544
|
+
const winVbsFile = (name) => path.join(winStartupDir(), `agm-${safe(name)}.vbs`);
|
|
545
|
+
const winCmdFile = (name) => path.join(dir(), `service-${safe(name)}.cmd`);
|
|
546
|
+
const winGenFile = (name) => path.join(dir(), `service-${safe(name)}.gen`);
|
|
547
|
+
const dry = () => !!process.env.AGM_SERVICE_DRYRUN;
|
|
548
|
+
|
|
549
|
+
// Only what the service needs to find the agent program and reach the server. No keys or tokens are copied into
|
|
550
|
+
// the system service file; agent auth variables (when present in the shell) live separately in ~/.agm (0600).
|
|
551
|
+
const AUTH_ENV = ["CLAUDE_CODE_OAUTH_TOKEN", "ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_BASE_URL", "OPENAI_API_KEY", "OPENAI_BASE_URL", "GEMINI_API_KEY", "GOOGLE_API_KEY", "OPENCODE_API_KEY"];
|
|
552
|
+
function serviceEnv() {
|
|
553
|
+
const keep = ["PATH", "HOME", "LANG", "AGM_HOME", "AGM_API", "CLAUDE_CONFIG_DIR", "AGM_CLAUDE_HOME", "CODEX_HOME", "ANTIGRAVITY_APP_DATA_DIR", "AGM_ANTIGRAVITY_HOME", "AGM_ANTIGRAVITY_AGENTAPI", "AGM_DELIVERY_TIMEOUT_MS", "AGM_DELIVERY_POLL_MS", "AGM_NO_AUTO_UPDATE", "AGM_UPDATE_SOURCE", "AGM_NPM_BIN", "HTTPS_PROXY", "HTTP_PROXY", "NO_PROXY", "https_proxy", "http_proxy", "no_proxy", "ALL_PROXY", "all_proxy", "AGM_CLAUDE_BIN", "AGM_CODEX_BIN", "AGM_GEMINI_BIN", "AGM_OPENCODE_BIN"];
|
|
554
|
+
return Object.fromEntries(keep.filter((key) => process.env[key]).map((key) => [key, process.env[key]]));
|
|
555
|
+
}
|
|
556
|
+
function saveAuthEnv(name) {
|
|
557
|
+
const found = Object.fromEntries(AUTH_ENV.filter((key) => process.env[key]).map((key) => [key, process.env[key]]));
|
|
558
|
+
if (!Object.keys(found).length) return fs.rmSync(envFile(name), { force: true });
|
|
559
|
+
const tmp = `${envFile(name)}.${process.pid}.tmp`;
|
|
560
|
+
fs.writeFileSync(tmp, JSON.stringify(found) + "\n", { mode: 0o600 });
|
|
561
|
+
fs.renameSync(tmp, envFile(name));
|
|
562
|
+
}
|
|
563
|
+
function loadAuthEnv(name) {
|
|
564
|
+
try {
|
|
565
|
+
const parsed = JSON.parse(fs.readFileSync(envFile(name), "utf8"));
|
|
566
|
+
return parsed && typeof parsed === "object" ? parsed : {};
|
|
567
|
+
} catch {
|
|
568
|
+
return {};
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
function sh(command, args) {
|
|
573
|
+
if (dry()) return { status: 0, stdout: "", stderr: "" };
|
|
574
|
+
// From ssh or a service, the user's systemd can only be reached once told where its runtime folder is.
|
|
575
|
+
const env = { ...process.env };
|
|
576
|
+
const runtime = `/run/user/${process.getuid?.()}`;
|
|
577
|
+
if (command === "systemctl" && !env.XDG_RUNTIME_DIR && fs.existsSync(runtime)) env.XDG_RUNTIME_DIR = runtime;
|
|
578
|
+
return spawnSync(command, args, { encoding: "utf8", timeout: 20000, env });
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
const xml = (text) => String(text).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
582
|
+
const quoteUnit = (arg) => (/^[A-Za-z0-9_@%+=:,./-]+$/.test(arg) ? arg : `"${arg.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/%/g, "%%")}"`);
|
|
583
|
+
const escapeCmd = (text) => String(text).replace(/%/g, "%%").replace(/"/g, '""');
|
|
584
|
+
const quoteCmd = (arg) => `"${escapeCmd(arg)}"`;
|
|
585
|
+
const escapeVbs = (text) => String(text).replace(/"/g, '""');
|
|
586
|
+
|
|
587
|
+
export function install(script, name, { agent, run, roomOnly, noResume, autoUpdate = true, notifyCmd, workdir, every, maxPerHour }) {
|
|
588
|
+
if (!run && !SUPPORTED_AGENTS.includes(agent)) {
|
|
589
|
+
throw new Error(`Say which agent the service wakes: agm daemon install --agent ${SUPPORTED_AGENTS.join("|")} (or --run '<command>').`);
|
|
590
|
+
}
|
|
591
|
+
workdir = path.resolve(workdir || process.cwd());
|
|
592
|
+
const args = [process.execPath, script, "daemon", "--service", "--as", name, ...(run ? ["--run", run] : ["--agent", agent]), "--workdir", workdir];
|
|
593
|
+
if (roomOnly) args.push("--room-only");
|
|
594
|
+
if (noResume) args.push("--no-resume");
|
|
595
|
+
if (autoUpdate === false) args.push("--no-auto-update");
|
|
596
|
+
if (notifyCmd) args.push("--notify-cmd", notifyCmd);
|
|
597
|
+
if (every) args.push("--every", String(every));
|
|
598
|
+
if (maxPerHour) args.push("--max-per-hour", String(maxPerHour));
|
|
599
|
+
const env = serviceEnv();
|
|
600
|
+
fs.mkdirSync(dir(), { recursive: true, mode: 0o700 });
|
|
601
|
+
saveAuthEnv(name);
|
|
602
|
+
const logPath = serviceLog(name);
|
|
603
|
+
const plat = platformName();
|
|
604
|
+
if (plat === "linux") {
|
|
605
|
+
const file = unitFile(name);
|
|
606
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
607
|
+
fs.writeFileSync(file, [
|
|
608
|
+
"[Unit]",
|
|
609
|
+
`Description=Agent DM: wake ${name} when someone in its rooms talks to it`,
|
|
610
|
+
"After=network-online.target",
|
|
611
|
+
"Wants=network-online.target",
|
|
612
|
+
"",
|
|
613
|
+
"[Service]",
|
|
614
|
+
`ExecStart=${args.map(quoteUnit).join(" ")}`,
|
|
615
|
+
...Object.entries(env).map(([key, value]) => `Environment=${quoteUnit(`${key}=${value}`)}`),
|
|
616
|
+
`WorkingDirectory=${quoteUnit(workdir)}`,
|
|
617
|
+
"Restart=always",
|
|
618
|
+
"RestartSec=10",
|
|
619
|
+
`StandardOutput=append:${logPath}`,
|
|
620
|
+
`StandardError=append:${logPath}`,
|
|
621
|
+
"",
|
|
622
|
+
"[Install]",
|
|
623
|
+
"WantedBy=default.target",
|
|
624
|
+
"",
|
|
625
|
+
].join("\n"), { mode: 0o600 });
|
|
626
|
+
for (const step of [["daemon-reload"], ["enable", unitName(name)], ["restart", unitName(name)]]) {
|
|
627
|
+
const done = sh("systemctl", ["--user", ...step]);
|
|
628
|
+
if (done.status !== 0) throw new Error(`systemctl --user ${step.join(" ")} failed: ${(done.stderr || done.error?.message || "").trim()}. The unit file is at ${file}.`);
|
|
629
|
+
}
|
|
630
|
+
const linger = sh("loginctl", ["show-user", os.userInfo().username, "-p", "Linger"]);
|
|
631
|
+
return { file, linger: dry() || /Linger=yes/.test(linger.stdout || "") };
|
|
632
|
+
}
|
|
633
|
+
if (plat === "darwin") {
|
|
634
|
+
const file = plistFile(name);
|
|
635
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
636
|
+
const strings = (list) => list.map((item) => ` <string>${xml(item)}</string>`).join("\n");
|
|
637
|
+
fs.writeFileSync(file, `<?xml version="1.0" encoding="UTF-8"?>
|
|
638
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
639
|
+
<plist version="1.0">
|
|
640
|
+
<dict>
|
|
641
|
+
<key>Label</key><string>${xml(label(name))}</string>
|
|
642
|
+
<key>ProgramArguments</key>
|
|
643
|
+
<array>
|
|
644
|
+
${strings(args)}
|
|
645
|
+
</array>
|
|
646
|
+
<key>EnvironmentVariables</key>
|
|
647
|
+
<dict>
|
|
648
|
+
${Object.entries(env).map(([key, value]) => ` <key>${xml(key)}</key><string>${xml(value)}</string>`).join("\n")}
|
|
649
|
+
</dict>
|
|
650
|
+
<key>WorkingDirectory</key><string>${xml(workdir)}</string>
|
|
651
|
+
<key>RunAtLoad</key><true/>
|
|
652
|
+
<key>KeepAlive</key><true/>
|
|
653
|
+
<key>ThrottleInterval</key><integer>10</integer>
|
|
654
|
+
<key>StandardOutPath</key><string>${xml(logPath)}</string>
|
|
655
|
+
<key>StandardErrorPath</key><string>${xml(logPath)}</string>
|
|
656
|
+
</dict>
|
|
657
|
+
</plist>
|
|
658
|
+
`, { mode: 0o600 });
|
|
659
|
+
const domain = `gui/${process.getuid()}`;
|
|
660
|
+
sh("launchctl", ["bootout", `${domain}/${label(name)}`]);
|
|
661
|
+
const done = sh("launchctl", ["bootstrap", domain, file]);
|
|
662
|
+
if (done.status !== 0) throw new Error(`launchctl bootstrap failed: ${(done.stderr || "").trim()}. The file is at ${file}.`);
|
|
663
|
+
return { file, linger: true };
|
|
664
|
+
}
|
|
665
|
+
if (plat === "win32") {
|
|
666
|
+
const vbs = winVbsFile(name);
|
|
667
|
+
const cmd = winCmdFile(name);
|
|
668
|
+
const genFile = winGenFile(name);
|
|
669
|
+
const gen = `${Date.now()}-${process.pid}`;
|
|
670
|
+
fs.mkdirSync(path.dirname(vbs), { recursive: true });
|
|
671
|
+
fs.writeFileSync(genFile, `${gen}\n`, { mode: 0o600 });
|
|
672
|
+
const envLines = Object.entries(env).map(([key, value]) => `set "${key}=${escapeCmd(value)}"`);
|
|
673
|
+
fs.writeFileSync(cmd, [
|
|
674
|
+
"@echo off",
|
|
675
|
+
"setlocal",
|
|
676
|
+
`cd /d ${quoteCmd(workdir)}`,
|
|
677
|
+
...envLines,
|
|
678
|
+
":loop",
|
|
679
|
+
`if not exist ${quoteCmd(cmd)} exit /b 0`,
|
|
680
|
+
"set \"AGM_GEN=\"",
|
|
681
|
+
`set /p AGM_GEN=<${quoteCmd(genFile)} 2>nul`,
|
|
682
|
+
`if not "%AGM_GEN%"=="${gen}" exit /b 0`,
|
|
683
|
+
`${args.map(quoteCmd).join(" ")} >> ${quoteCmd(logPath)} 2>&1`,
|
|
684
|
+
`if not exist ${quoteCmd(cmd)} exit /b 0`,
|
|
685
|
+
"set \"AGM_GEN=\"",
|
|
686
|
+
`set /p AGM_GEN=<${quoteCmd(genFile)} 2>nul`,
|
|
687
|
+
`if not "%AGM_GEN%"=="${gen}" exit /b 0`,
|
|
688
|
+
"timeout /t 10 /nobreak >nul",
|
|
689
|
+
"goto loop",
|
|
690
|
+
"",
|
|
691
|
+
].join("\r\n"), { mode: 0o600 });
|
|
692
|
+
fs.writeFileSync(vbs, [
|
|
693
|
+
'Set sh = CreateObject("WScript.Shell")',
|
|
694
|
+
`sh.Run """" & "${escapeVbs(cmd)}" & """", 0, False`,
|
|
695
|
+
"",
|
|
696
|
+
].join("\r\n"), { mode: 0o600 });
|
|
697
|
+
const existing = serviceRunning(name);
|
|
698
|
+
if (existing && !dry()) {
|
|
699
|
+
try {
|
|
700
|
+
process.kill(existing.pid, "SIGTERM");
|
|
701
|
+
} catch {
|
|
702
|
+
// already gone
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
const done = sh("wscript.exe", [vbs]);
|
|
706
|
+
if (done.status !== 0) throw new Error(`wscript.exe failed: ${(done.stderr || done.error?.message || "").trim()}. The launcher is at ${vbs}.`);
|
|
707
|
+
return { file: vbs, cmdFile: cmd, linger: true };
|
|
708
|
+
}
|
|
709
|
+
throw new Error("agm daemon install works on Linux (systemd), macOS (launchd), and Windows (Startup).");
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
export function uninstall(name) {
|
|
713
|
+
let removed = false;
|
|
714
|
+
const plat = platformName();
|
|
715
|
+
if (plat === "linux") {
|
|
716
|
+
const file = unitFile(name);
|
|
717
|
+
if (fs.existsSync(file)) {
|
|
718
|
+
sh("systemctl", ["--user", "disable", "--now", unitName(name)]);
|
|
719
|
+
fs.rmSync(file, { force: true });
|
|
720
|
+
sh("systemctl", ["--user", "daemon-reload"]);
|
|
721
|
+
removed = true;
|
|
722
|
+
}
|
|
723
|
+
} else if (plat === "darwin") {
|
|
724
|
+
const file = plistFile(name);
|
|
725
|
+
if (fs.existsSync(file)) {
|
|
726
|
+
sh("launchctl", ["bootout", `gui/${process.getuid()}/${label(name)}`]);
|
|
727
|
+
fs.rmSync(file, { force: true });
|
|
728
|
+
removed = true;
|
|
729
|
+
}
|
|
730
|
+
} else if (plat === "win32") {
|
|
731
|
+
for (const file of [winVbsFile(name), winCmdFile(name), winGenFile(name)]) {
|
|
732
|
+
if (fs.existsSync(file)) {
|
|
733
|
+
fs.rmSync(file, { force: true });
|
|
734
|
+
removed = true;
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
fs.rmSync(envFile(name), { force: true });
|
|
739
|
+
const found = serviceRunning(name);
|
|
740
|
+
if (found && !dry()) {
|
|
741
|
+
try {
|
|
742
|
+
process.kill(found.pid, "SIGTERM");
|
|
743
|
+
} catch {
|
|
744
|
+
// already gone
|
|
745
|
+
}
|
|
746
|
+
}
|
|
747
|
+
return removed || !!found;
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
export function installedFile(name) {
|
|
751
|
+
const plat = platformName();
|
|
752
|
+
const file = plat === "darwin" ? plistFile(name) : plat === "linux" ? unitFile(name) : plat === "win32" ? winVbsFile(name) : null;
|
|
753
|
+
return file && fs.existsSync(file) ? file : null;
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
// One paragraph for `agm daemon status` and `agm listen --status`.
|
|
757
|
+
export function describe(name) {
|
|
758
|
+
const file = installedFile(name);
|
|
759
|
+
const found = serviceRunning(name);
|
|
760
|
+
if (!file && !found) return `No always-on service for ${name}. To be woken whenever this computer is on: agm daemon install --agent claude (or codex) --as ${name}`;
|
|
761
|
+
if (!found) return `The always-on service for ${name} is installed (${file}) but not running. The system restarts it within seconds; if this stays, see ${serviceLog(name)}.`;
|
|
762
|
+
const last = found.lastWake ? ` Last wake ${found.lastWake.at} (${found.lastWake.how}${found.lastWake.code === undefined ? ", running" : `, exit ${found.lastWake.code}${found.lastWake.verified === false ? ", unconfirmed" : ""}`}).` : "";
|
|
763
|
+
const pending = harnesses.unresolvedWake(found.unverifiedWake, load(), name);
|
|
764
|
+
const warn = pending ? ` Warning: wake at ${pending.at} (${pending.how}) was not confirmed read in ${pending.rooms.map((r) => r.title).join(", ")} (readSeq still behind).` : "";
|
|
765
|
+
const mode = found.mode === "session" ? "a session of the agent is listening, so the service is leaving wakes to it" : found.mode === "waking" ? "it is waking the agent now" : found.mode === "updating" ? "it is auto-updating agm" : "it is watching the rooms and will wake the agent";
|
|
766
|
+
const autoNote = found.autoUpdate === false ? ", auto-update off" : ", auto-update on";
|
|
767
|
+
return `Always-on service for ${name} is running (process ${found.pid}, since ${found.since}): ${mode}. It wakes ${found.agent}${found.roomOnly ? " limited to agm commands" : " with full permissions"}${found.noResume ? ", always starting fresh sessions" : ""}${autoNote}.${last}${warn} Log: ${serviceLog(name)}`;
|
|
768
|
+
}
|