@droconnell/agent-inbox-cli 2.5.0 → 2.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -66,6 +66,16 @@ agent-inbox ls unassigned # any console terminal command
66
66
  agent-inbox help # every command
67
67
  ```
68
68
 
69
+ ## Run commands from Next's answers
70
+
71
+ ```bash
72
+ cd support && agent-inbox connect # keep it open; Ctrl+C disconnects
73
+ ```
74
+
75
+ While `connect` runs, a command in the Assistant's answer in Next gets **Run on** your computer beside Copy. Your
76
+ computer shows what will run and asks `Run it? [y] yes [a] always [n] no` before each one; only `agent-inbox` commands
77
+ from a short list run, only in this folder, with no shell. Admins only.
78
+
69
79
  ## Update
70
80
 
71
81
  ```bash
package/agent-inbox.mjs CHANGED
@@ -24,6 +24,8 @@
24
24
  // agent-inbox help <command> one terminal command with an example; agent-inbox commands lists them all
25
25
  // agent-inbox script <file> [--propose] a file of terminal commands, one per line, as one plan; --propose sends
26
26
  // it to Approvals (exit 0 nothing to change, 2 a plan, 1 problems)
27
+ // agent-inbox connect [--name "..."] in your support folder: Next's Assistant may offer to run agent-inbox commands
28
+ // here; each one runs only after you say yes on this computer (Ctrl+C stops it)
27
29
  // agent-inbox logout forget the sign-in on this computer
28
30
  // agent-inbox update how to update, for how it was installed (a downloaded file updates itself)
29
31
  //
@@ -31,12 +33,12 @@
31
33
  import { createHash, randomBytes } from "node:crypto";
32
34
  import { createServer } from "node:http";
33
35
  import { mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync, existsSync } from "node:fs";
34
- import { homedir } from "node:os";
36
+ import { homedir, hostname, platform, userInfo } from "node:os";
35
37
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
36
38
  import { spawn, spawnSync } from "node:child_process";
37
39
  import { fileURLToPath } from "node:url";
38
40
 
39
- export const VERSION = "2.5.0";
41
+ export const VERSION = "2.6.0";
40
42
  /** The npm package; its command is agent-inbox. (The name agent-inbox itself belongs to someone else on npm.) */
41
43
  export const PACKAGE = "@droconnell/agent-inbox-cli";
42
44
  const DIR = join(process.env.XDG_CONFIG_HOME || join(homedir(), ".config"), "agent-inbox");
@@ -90,7 +92,7 @@ const urlArg = take("--url", true);
90
92
  const tokenArg = take("--token", true);
91
93
  /** The CLI's own commands. Anything else is a terminal command, sent as typed. */
92
94
  export const OWN = new Set(["login", "logout", "update", "export", "pull", "plan", "diff", "push", "propose", "run", "tail", "script", "check", "ci", "test", "rehearse", "commands", "help", "submit",
93
- "whoami", "policy", "audit", "mcp", "claude", "init", "app", "events", "listen", "completion", "__complete", "--version", "-v", "--help", "-h"]);
95
+ "whoami", "policy", "audit", "mcp", "claude", "init", "connect", "app", "events", "listen", "completion", "__complete", "--version", "-v", "--help", "-h"]);
94
96
  const first = args[0];
95
97
  // plan, diff and run are also terminal commands: the CLI's own only for a folder or file that is there (plan, diff) or
96
98
  // a quoted command (run "ls unassigned"); otherwise they go to the terminal as typed (diff 40 42, run onboarding).
@@ -589,6 +591,7 @@ const USAGE = [
589
591
  ["listen --forward <address> [--events a,b]", "Next's webhooks, signed as usual, sent to a server on this computer while it runs"],
590
592
  ["mcp", "an MCP server over stdio for any AI tool, using this computer's sign-in"],
591
593
  ["claude [--project]", "add Next to Claude Code (or write .mcp.json for this project)"],
594
+ ["connect [--name \"Maya's MacBook\"]", "in your support folder: the Assistant may offer to run agent-inbox commands here, each after you say yes (Ctrl+C stops)"],
592
595
  ["app ls | why <app> | logs <app> [--follow]", "apps: their health, and their runs as they happen"],
593
596
  ["app try <app> <tool> [--input JSON]", "run an app's tool that only reads, on its latest version"],
594
597
  ["app fix <app> [--claude]", "its recent failures as a request to fix (--claude hands it to Claude Code here)"],
@@ -1010,6 +1013,234 @@ async function appCommand(words) {
1010
1013
  }
1011
1014
  }
1012
1015
 
1016
+ // ---- Run on your computer: agent-inbox connect ----------------------------------------------------------------------
1017
+ /**
1018
+ * The commands Next may ask this computer to run, and whether the person may choose Always for one. The same list as
1019
+ * RUNNABLE in src/lib/computer-commands.ts on the server (src/lib/computer-commands.test.ts checks they agree), kept
1020
+ * here too so this computer checks every request itself: a server that was tricked still cannot widen it. Always is
1021
+ * only for commands that neither change Next nor cost money.
1022
+ */
1023
+ export const RUNNABLE = {
1024
+ pull: { always: true, path: "optional" },
1025
+ plan: { always: true, path: "optional" },
1026
+ "policy check": { always: true, path: "optional" },
1027
+ "policy pull": { always: true, path: "optional" },
1028
+ "policy plan": { always: true, path: "optional" },
1029
+ whoami: { always: true },
1030
+ push: { always: false, path: "optional", flags: { "--prune": "flag" } },
1031
+ propose: { always: false, path: "required" },
1032
+ "policy push": { always: false, path: "optional" },
1033
+ check: { always: false, path: "optional", flags: { "--on": "count" } },
1034
+ test: { always: false },
1035
+ "ci init": { always: false, path: "optional" },
1036
+ };
1037
+
1038
+ /** A folder or file inside the connected folder: `.`, or plain names that do not start with a dot. Never /, ~ or .. */
1039
+ export function insidePath(p) {
1040
+ if (typeof p !== "string" || p.length === 0 || p.length > 200) return false;
1041
+ return /^(\.|[A-Za-z0-9_][A-Za-z0-9._-]*)(\/[A-Za-z0-9_][A-Za-z0-9._-]*)*\/?$/.test(p);
1042
+ }
1043
+
1044
+ /**
1045
+ * The CLI's own words to run for a request from Next (its command's name and words), checked against RUNNABLE: such
1046
+ * as ["pull", "."] or ["policy", "check"]. Null for anything else, which is refused without asking.
1047
+ */
1048
+ export function runnable(sub, args) {
1049
+ if (typeof sub !== "string" || !Object.hasOwn(RUNNABLE, sub) || !Array.isArray(args) || args.length > 4) return null;
1050
+ if (!args.every((a) => typeof a === "string")) return null;
1051
+ const kind = RUNNABLE[sub];
1052
+ let path = null;
1053
+ const flags = [];
1054
+ for (let i = 0; i < args.length; i++) {
1055
+ const a = args[i];
1056
+ if (a.startsWith("-")) {
1057
+ const f = kind.flags?.[a];
1058
+ if (!f || flags.includes(a)) return null;
1059
+ if (f === "count") {
1060
+ const n = args[i + 1];
1061
+ if (!n || !/^[1-9]\d?$/.test(n) || Number(n) > 30) return null;
1062
+ flags.push(a, n); i++;
1063
+ } else flags.push(a);
1064
+ continue;
1065
+ }
1066
+ if (!kind.path || path !== null || !insidePath(a)) return null;
1067
+ path = a;
1068
+ }
1069
+ if (kind.path === "required" && path === null) return null;
1070
+ return [...sub.split(" "), ...(path === null ? [] : [path]), ...flags];
1071
+ }
1072
+
1073
+ /** Text from Next shown in this terminal: no control characters, so nothing sent can move the cursor or recolour the screen. */
1074
+ export const plainText = (s, max = 120) => String(s ?? "").replace(/[\u0000-\u001f\u007f-\u009f\u200b-\u200f\u2028-\u202e]/g, "").slice(0, max);
1075
+
1076
+ /** Whether a path the command names stays inside the folder, following any links on the way (a link out is refused). */
1077
+ export function staysInside(folder, p) {
1078
+ const root = real(folder);
1079
+ let at = resolve(root, p);
1080
+ // The part that exists, with its links followed; what is not there yet can only be made under it.
1081
+ const rest = [];
1082
+ while (!existsSync(at) && dirname(at) !== at) { rest.unshift(basename(at)); at = dirname(at); }
1083
+ const whole = join(real(at), ...rest);
1084
+ const rel = relative(root, whole);
1085
+ return rel === "" || (!rel.startsWith("..") && !isAbsolute(rel));
1086
+ }
1087
+
1088
+ /** What this computer calls itself in Next: Maya's MacBook Pro from Mayas-MacBook-Pro, or Maya's Mac when it has no useful name. */
1089
+ export function computerName(host = hostname(), user = (() => { try { return userInfo().username; } catch { return ""; } })(), os = platform()) {
1090
+ const h = String(host ?? "").replace(/\.(local|lan|home|localdomain)$/i, "").split(".")[0];
1091
+ const kind = os === "darwin" ? "Mac" : os === "win32" ? "PC" : "computer";
1092
+ const owner = user ? user.charAt(0).toUpperCase() + user.slice(1) : "";
1093
+ if (!h || /^(localhost|[0-9a-f]{8,})$/i.test(h)) return owner ? `${owner}'s ${kind}` : `This ${kind}`;
1094
+ const m = /^([A-Za-z]+?)s-(.+)$/.exec(h);
1095
+ if (m && /^(macbook|imac|mac|pc|laptop|desktop|surface|thinkpad)/i.test(m[2])) return `${m[1].charAt(0).toUpperCase() + m[1].slice(1)}'s ${m[2].replace(/-/g, " ")}`;
1096
+ return h.replace(/-/g, " ");
1097
+ }
1098
+
1099
+ /** A command's outcome from how the CLI ended: 0 is done, 2 is done with a plan or changes to show, anything else a problem. */
1100
+ export const runEnded = (code) => (code === 0 || code === 2 ? "done" : "failed");
1101
+
1102
+ /**
1103
+ * agent-inbox connect: keep a line open from this computer to Next, so the Assistant can offer to run agent-inbox
1104
+ * commands in this support folder. Next only ever sends a command's name and words from the list above; this computer
1105
+ * checks them again, shows exactly what will run, where and who asked, and runs it only after you answer here (never in
1106
+ * the browser). It runs this CLI's own code, without a shell, in this folder only. Ctrl+C disconnects.
1107
+ */
1108
+ async function connect(words) {
1109
+ const folder = real(process.cwd());
1110
+ if (!process.stdin.isTTY || !process.stdout.isTTY) stop("connect asks you before every command it runs, so it needs a terminal you can type in.");
1111
+ if (folder === real(homedir()) || dirname(folder) === folder) stop(`Run connect in your support folder (the one ${ME} init or pull made), not in your home folder.`);
1112
+ if (!isPulled(folder)) stop(`This is not a support folder: it has no workspace.yaml. Run connect in the folder ${ME} init or pull made, such as support.`);
1113
+ const me = await tool("whoami");
1114
+ if (me.isError || !me.data) stop(me.text || `The sign-in did not work. Run ${ME} login again.`);
1115
+ const { url } = await access();
1116
+ const name = plainText(valueOf(words, "--name") || computerName(), 80);
1117
+ const shown = folder.startsWith(homedir() + sep) ? `~${folder.slice(homedir().length)}` : folder;
1118
+ const always = new Set();
1119
+
1120
+ /** One call on the line. Network trouble comes back as null, so the loop can wait and try again. */
1121
+ const line = async (method, body, search = "") => {
1122
+ const { url: at, token } = await access();
1123
+ let r;
1124
+ try {
1125
+ r = await fetch(`${at}/api/cli/computer${search}`, { method, headers: { authorization: `Bearer ${token}`, "content-type": "application/json", "user-agent": UA }, ...(body ? { body: JSON.stringify(body) } : {}), signal: AbortSignal.timeout(45_000) });
1126
+ } catch { return null; }
1127
+ if (r.status === 401) stop(`Your sign-in was refused. Run ${ME} login again, then connect.`);
1128
+ if (r.status === 403) stop("Only an admin of the workspace can connect a computer.");
1129
+ if (r.status === 404) stop(`${at} does not have Run on your computer yet. It needs a newer Next.`);
1130
+ if (r.status >= 500) return null;
1131
+ return { status: r.status, data: await r.json().catch(() => ({})) };
1132
+ };
1133
+
1134
+ const hello = await line("POST", { action: "connect", name, folder: shown, version: VERSION, always: [] });
1135
+ if (!hello) stop(`Could not reach ${url}. Check your connection and try again.`);
1136
+ if (hello.status !== 200 || !hello.data?.id) stop(hello.data?.error || "Next did not accept this computer. Try again.");
1137
+ const { id, line: lineId } = hello.data;
1138
+ const clock = () => new Date().toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
1139
+ say(`${clock()} Connected to ${new URL(url).host} as ${plainText(me.data.user)}`);
1140
+ say(`This computer shows in Next as "${name}", for ${folder}.\nWhen ${plainText(me.data.workspace)}'s Assistant offers to run an agent-inbox command, it asks you here first. Ctrl+C disconnects.`);
1141
+
1142
+ const rl = (await import("node:readline")).createInterface({ input: process.stdin, output: process.stdout });
1143
+ let child = null, leaving = false;
1144
+ const leave = async (why) => {
1145
+ if (leaving) return;
1146
+ leaving = true;
1147
+ if (child) child.kill();
1148
+ if (why) say(`\n${why}`);
1149
+ await line("POST", { action: "leave", id, line: lineId }).catch(() => {});
1150
+ rl.close();
1151
+ process.exit(0);
1152
+ };
1153
+ // Ctrl+C typed here reaches readline; a signal from elsewhere (kill, the window closing) reaches the process.
1154
+ rl.on("SIGINT", () => void leave("Disconnected. Next shows this computer as offline."));
1155
+ process.on("SIGINT", () => void leave("Disconnected. Next shows this computer as offline."));
1156
+ process.on("SIGTERM", () => void leave(""));
1157
+ process.on("SIGHUP", () => void leave(""));
1158
+ const question = (q) => new Promise((ok) => rl.question(q, (a) => ok(a.trim().toLowerCase())));
1159
+
1160
+ /** Tell Next how a run stands; tries a few times. False when Next refused it (the run ended there meanwhile). */
1161
+ const report = async (run, body) => {
1162
+ for (let i = 0; i < 5; i++) {
1163
+ const r = await line("POST", { action: "report", id, line: lineId, run: run.id, ...body });
1164
+ if (r) return r.status === 200;
1165
+ await new Promise((ok) => setTimeout(ok, 1000 * (i + 1)));
1166
+ }
1167
+ return false;
1168
+ };
1169
+
1170
+ /** One request: check it, show it, ask, then run this CLI with its words in this folder, and send back what it printed. */
1171
+ const handle = async (run) => {
1172
+ const argv = runnable(run.sub, run.args);
1173
+ const command = `agent-inbox ${argv ? argv.join(" ") : plainText(run.sub, 40)}`;
1174
+ // A request from before this computer reconnected says how old it is, so an earlier ask is not mistaken for a new one.
1175
+ const ago = Math.floor((Date.now() - Date.parse(run.askedAt)) / 60_000);
1176
+ const when = ago >= 1 ? ` ${ago} minute${ago === 1 ? "" : "s"} ago` : "";
1177
+ say(`\n${clock()} ${plainText(run.from, 40)} wants to run, asked by ${plainText(run.askedBy, 60)}${when}:\n\n ${command}\n in ${folder}\n`);
1178
+ // The folder or file it names comes right after the command's own words (runnable puts it there), before any option.
1179
+ const named = argv?.[run.sub.split(" ").length];
1180
+ const path = named && !named.startsWith("-") ? named : ".";
1181
+ if (!argv || !staysInside(folder, path)) {
1182
+ say("Not run: this computer only runs agent-inbox commands from its list, in this folder.");
1183
+ await report(run, { status: "declined", output: "This computer refused it: it only runs agent-inbox commands from its list, in the folder it connected.\n" });
1184
+ return;
1185
+ }
1186
+ let approved = always.has(run.sub) ? "always" : null;
1187
+ if (approved) say(`Running: you chose Always for ${run.sub} while connected.`);
1188
+ while (!approved) {
1189
+ const canAlways = RUNNABLE[run.sub].always;
1190
+ const a = await question(`Run it? [y] yes ${canAlways ? `[a] always for ${run.sub} ` : ""}[n] no › `);
1191
+ if (a === "y" || a === "yes") approved = "once";
1192
+ else if (canAlways && (a === "a" || a === "always")) { approved = "always"; always.add(run.sub); }
1193
+ else if (a === "n" || a === "no") break;
1194
+ else say(canAlways ? "Type y, a or n, then Enter." : "Type y or n, then Enter.");
1195
+ }
1196
+ if (!approved) { say("Not run."); await report(run, { status: "declined" }); return; }
1197
+ if (!(await report(run, { status: "running", approved }))) { say("Not run: the request ended in Next before you answered (after 10 minutes, or it was disconnected). Ask again from Next."); return; }
1198
+ const started = Date.now();
1199
+ let pending = "";
1200
+ const flush = async () => { if (!pending) return; const chunk = pending; pending = ""; await report(run, { status: "running", output: chunk }); };
1201
+ const timer = setInterval(() => void flush(), 1000);
1202
+ const code = await new Promise((done) => {
1203
+ // This CLI's own code with the checked words, in this folder, without a shell: nothing can be added to the line.
1204
+ child = spawn(process.execPath, [SELF, ...argv], { cwd: folder, shell: false, windowsHide: true, stdio: ["ignore", "pipe", "pipe"], env: { ...process.env, NO_COLOR: "1" } });
1205
+ const take = (b) => { const s = b.toString("utf8"); process.stdout.write(s); pending += s; };
1206
+ child.stdout.on("data", take); child.stderr.on("data", take);
1207
+ const limit = setTimeout(() => { pending += "\nStopped after 20 minutes.\n"; child?.kill(); }, 20 * 60_000);
1208
+ child.on("error", () => { clearTimeout(limit); done(-1); });
1209
+ child.on("close", (c) => { clearTimeout(limit); done(c ?? -1); });
1210
+ });
1211
+ child = null;
1212
+ clearInterval(timer);
1213
+ const ended = runEnded(code);
1214
+ const output = pending; pending = "";
1215
+ await report(run, { status: ended, exitCode: code, output });
1216
+ say(`${ended === "done" ? "Done" : "Stopped with a problem"} in ${Math.max(1, Math.round((Date.now() - started) / 1000))} s. Next shows the result.`);
1217
+ };
1218
+
1219
+ // The line: ask for work again and again (each ask waits up to 25 seconds). Requests are handled one at a time.
1220
+ const queue = [];
1221
+ let working = false;
1222
+ const work = async () => {
1223
+ if (working) return;
1224
+ working = true;
1225
+ while (queue.length) await handle(queue.shift()).catch(() => say("That run could not finish. Next shows it as stopped."));
1226
+ working = false;
1227
+ };
1228
+ let lostSince = 0;
1229
+ for (;;) {
1230
+ const got = await line("GET", null, `?id=${id}&line=${lineId}&wait=25000&always=${encodeURIComponent([...always].join(","))}`);
1231
+ if (!got || got.status !== 200) {
1232
+ if (!lostSince) { lostSince = Date.now(); say(`${clock()} Lost the line to Next. Trying again…`); }
1233
+ if (Date.now() - lostSince > 10 * 60_000) await leave("Could not reach Next for 10 minutes, so this computer disconnected. Run connect again.");
1234
+ await new Promise((ok) => setTimeout(ok, 5000));
1235
+ continue;
1236
+ }
1237
+ if (lostSince) { lostSince = 0; say(`${clock()} Back in touch with Next.`); }
1238
+ if (got.data?.gone) await leave("Disconnected in Next (Settings, Terminal). Run connect again to reconnect.");
1239
+ if (got.data?.replaced) { leaving = true; say("\nconnect was started again for this folder, so this one stopped."); rl.close(); process.exit(0); }
1240
+ if (got.data?.run) { queue.push(got.data.run); void work(); }
1241
+ }
1242
+ }
1243
+
1013
1244
  // ---- Shell completion ----------------------------------------------------------------------------------------------
1014
1245
  export function completionScript(shell, me = "agent-inbox") {
1015
1246
  if (shell === "bash") return `# ${me} completion for bash: add to ~/.bashrc: eval "$(${me} completion bash)"
@@ -1086,6 +1317,7 @@ switch (cmd) {
1086
1317
  case "mcp": await mcpServer(); break;
1087
1318
  case "claude": await claudeSetup(rest.includes("--project")); break;
1088
1319
  case "init": await init(rest); break;
1320
+ case "connect": await connect(rest); break;
1089
1321
  case "app": await appCommand(rest); break;
1090
1322
  case "events": { const only = (valueOf(rest, "--only") ?? "").split(",").filter(Boolean); await events(only.length ? only : null); break; }
1091
1323
  case "listen": await listen(valueOf(rest, "--forward"), valueOf(rest, "--events")?.split(",").filter(Boolean)); break;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@droconnell/agent-inbox-cli",
3
- "version": "2.5.0",
3
+ "version": "2.6.0",
4
4
  "description": "The Next CLI, built for agents: JSON on every command, an MCP server for any AI tool, live events, apps and webhooks from the terminal, and a support workspace's setup as files in git.",
5
5
  "type": "module",
6
6
  "bin": {