@droconnell/agent-inbox-cli 1.10.0 → 2.0.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.
Files changed (3) hide show
  1. package/README.md +15 -1
  2. package/agent-inbox.mjs +453 -46
  3. package/package.json +2 -2
package/README.md CHANGED
@@ -20,7 +20,21 @@ agent-inbox login https://your-next-address
20
20
 
21
21
  Your browser opens on Next and asks you to approve the CLI. The address and the sign-in are kept on your computer, so every other command uses them.
22
22
 
23
- In CI, set `AGENT_INBOX_URL` and `AGENT_INBOX_TOKEN` (a token from Settings, Terminal, AI tools) instead of signing in.
23
+ In CI, set `AGENT_INBOX_URL` and `AGENT_INBOX_TOKEN` (a token from Settings, Terminal, AI tools) instead of signing in. Where there is no browser, `agent-inbox login https://your-next-address --token` takes a pasted or piped token. `agent-inbox whoami` says who you are signed in as.
24
+
25
+ ## For AI agents
26
+
27
+ ```bash
28
+ agent-inbox claude # add Next to Claude Code as an MCP server
29
+ agent-inbox mcp # Next as an MCP server for any AI tool
30
+ agent-inbox ls unassigned --json # any command as JSON; --fields customer,status keeps those columns
31
+ echo 'today' | agent-inbox run - # commands from a pipe
32
+ agent-inbox events --json # each change as it happens, one JSON line each
33
+ agent-inbox app why Refunds # why an app fails; app logs, app try, app fix
34
+ agent-inbox listen --forward http://localhost:3001/hook # webhooks to your computer, signed
35
+ ```
36
+
37
+ Exit codes: 0 worked, 1 failed, 2 `plan`, `diff` or `script` found changes.
24
38
 
25
39
  ## Use it
26
40
 
package/agent-inbox.mjs CHANGED
@@ -34,7 +34,7 @@ import { basename, dirname, isAbsolute, join, relative, sep } from "node:path";
34
34
  import { spawn } from "node:child_process";
35
35
  import { fileURLToPath } from "node:url";
36
36
 
37
- export const VERSION = "1.10.0";
37
+ export const VERSION = "2.0.0";
38
38
  /** The npm package; its command is agent-inbox. (The name agent-inbox itself belongs to someone else on npm.) */
39
39
  export const PACKAGE = "@droconnell/agent-inbox-cli";
40
40
  const DIR = join(process.env.XDG_CONFIG_HOME || join(homedir(), ".config"), "agent-inbox");
@@ -69,13 +69,52 @@ export function installedBy(path) {
69
69
 
70
70
  const ME = invokedAs();
71
71
  const args = process.argv.slice(2);
72
- const flag = (n) => { const i = args.indexOf(n); return i >= 0 ? (args.splice(i, 1), true) : false; };
72
+ /** Take an option out of the arguments: a flag (true when there), or with a value (the word after it). */
73
+ const take = (n, withValue = false) => {
74
+ const i = args.indexOf(n);
75
+ if (i < 0) return withValue ? undefined : false;
76
+ const v = withValue ? args[i + 1] : true;
77
+ args.splice(i, withValue && args[i + 1] !== undefined && !String(args[i + 1]).startsWith("--") ? 2 : 1);
78
+ return withValue && typeof v === "string" && v.startsWith("--") ? undefined : v;
79
+ };
80
+ // Options for every command, anywhere on the line: --json (data for scripts and agents, see outputJson on the server),
81
+ // --fields a,b (only those columns of a table), --url and --token (sign in for this one run).
82
+ const tokenGiven = args.includes("--token");
83
+ export const asJson = take("--json");
84
+ const fieldsArg = take("--fields", true);
85
+ const urlArg = take("--url", true);
86
+ const tokenArg = take("--token", true);
87
+ /** The CLI's own commands. Anything else is a terminal command, sent as typed. */
88
+ export const OWN = new Set(["login", "logout", "update", "export", "pull", "plan", "diff", "push", "propose", "run", "tail", "script", "check", "ci", "test", "rehearse", "commands", "help", "submit",
89
+ "whoami", "mcp", "claude", "app", "events", "listen", "completion", "__complete", "--version", "-v", "--help", "-h"]);
90
+ const first = args[0];
91
+ // plan, diff and run are also terminal commands: the CLI's own only for a folder or file that is there (plan, diff) or
92
+ // a quoted command (run "ls unassigned"); otherwise they go to the terminal as typed (diff 40 42, run onboarding).
93
+ const isPath = (p) => Boolean(p) && !String(p).startsWith("--") && existsSync(p);
94
+ const terminalOwn = (first === "diff" && !isPath(args[1])) || (first === "plan" && args[1] !== undefined && !isPath(args[1]) && !args[1].startsWith("--"))
95
+ || (first === "run" && args.length > 1 && !(args.length === 2 && (/\s/.test(args[1]) || args[1] === "-")));
96
+ const own = OWN.has(first) && !terminalOwn;
97
+ // A command's own flags are read only for the CLI's commands, so a terminal command keeps its words.
98
+ const flag = (n) => (own ? take(n) : false);
73
99
  const markdown = flag("--markdown");
74
100
  const proposing = flag("--propose");
75
101
  const pruning = flag("--prune");
76
102
  const forcing = flag("--force");
77
- const [cmd, ...rest] = args;
103
+ const readLogin = flag("--read");
104
+ const [cmd, ...rest] = own || !args.length ? args : ["", ...args];
105
+
106
+ /** One word of a terminal command, quoted when it has spaces or quotes, so it arrives as typed. */
107
+ export function quoteWord(w) {
108
+ const s = String(w);
109
+ if (/^[^\s"']+$/.test(s)) return s;
110
+ if (!s.includes("'")) return `'${s}'`;
111
+ if (!s.includes('"')) return `"${s}"`;
112
+ return `"${s.replaceAll('"', "'")}"`;
113
+ }
114
+ export const commandLine = (words) => words.map(quoteWord).join(" ");
78
115
 
116
+ // Output cut short (piped into head, an agent that stopped reading) ends the run quietly, as other tools do.
117
+ process.stdout.on("error", (e) => { if (e.code === "EPIPE") process.exit(0); throw e; });
79
118
  const say = (s) => process.stdout.write(s.endsWith("\n") ? s : s + "\n");
80
119
  const stop = (s, code = 1) => { process.stderr.write(`agent-inbox: ${s}\n`); process.exit(code); };
81
120
  const clean = (u) => { try { const x = new URL(u.includes("://") ? u : `https://${u}`); return x.origin; } catch { stop(`${u} is not a web address.`); } };
@@ -89,20 +128,50 @@ async function form(url, body) {
89
128
  return j;
90
129
  }
91
130
 
92
- /** Where to work and with what: the environment (CI) first, then this computer's sign-in, renewed when it runs out. */
131
+ /**
132
+ * Hold the sign-in file while renewing it: refresh tokens change on every use, so two runs at once (tail and another
133
+ * command, or an agent running several) must not both renew it. Waits up to 15 seconds for the other run.
134
+ */
135
+ async function withLock(fn) {
136
+ const lock = `${SAVED}.lock`;
137
+ mkdirSync(DIR, { recursive: true, mode: 0o700 });
138
+ for (let i = 0; i < 150; i++) {
139
+ try { writeFileSync(lock, String(process.pid), { flag: "wx", mode: 0o600 }); break; }
140
+ catch {
141
+ // A lock left by a run that died is taken over after 30 seconds.
142
+ try { if (Date.now() - statSync(lock).mtimeMs > 30_000) rmSync(lock, { force: true }); } catch {}
143
+ await new Promise((r) => setTimeout(r, 100));
144
+ }
145
+ }
146
+ try { return await fn(); } finally { rmSync(lock, { force: true }); }
147
+ }
148
+
149
+ /**
150
+ * Where to work and with what: --url and --token for this run, then the environment (CI), then this computer's
151
+ * sign-in (a token saved with login --token, or the browser sign-in, renewed when it runs out).
152
+ */
93
153
  async function access() {
94
- if (process.env.AGENT_INBOX_TOKEN) {
95
- if (!process.env.AGENT_INBOX_URL) stop("AGENT_INBOX_TOKEN is set, so set AGENT_INBOX_URL to your console's address too.");
96
- return { url: clean(process.env.AGENT_INBOX_URL), token: process.env.AGENT_INBOX_TOKEN };
154
+ const envToken = tokenArg || process.env.AGENT_INBOX_TOKEN;
155
+ if (envToken) {
156
+ const u = urlArg || process.env.AGENT_INBOX_URL || load()?.url;
157
+ if (!u) stop("A token was given, so give your console's address too: --url or AGENT_INBOX_URL.");
158
+ return { url: clean(u), token: envToken };
97
159
  }
98
- const s = load();
160
+ let s = load();
99
161
  if (!s) stop(`Not signed in. Run ${ME} login <your console's address>, or set AGENT_INBOX_URL and AGENT_INBOX_TOKEN.`);
162
+ if (s.kind === "token") { notice(s.url); return { url: s.url, token: s.token }; }
100
163
  if (Date.now() > s.expiresAt - 60_000) {
101
- try {
102
- const t = await form(`${s.url}/api/oauth/token`, { grant_type: "refresh_token", refresh_token: s.refresh, client_id: s.clientId });
103
- Object.assign(s, { access: t.access_token, refresh: t.refresh_token, expiresAt: Date.now() + t.expires_in * 1000 });
104
- keep(s);
105
- } catch { stop(`Your sign-in has ended or was disconnected. Run ${ME} login again.`); }
164
+ s = await withLock(async () => {
165
+ // Another run may have renewed it while this one waited.
166
+ const now = load() ?? s;
167
+ if (Date.now() <= now.expiresAt - 60_000) return now;
168
+ try {
169
+ const t = await form(`${now.url}/api/oauth/token`, { grant_type: "refresh_token", refresh_token: now.refresh, client_id: now.clientId });
170
+ Object.assign(now, { access: t.access_token, refresh: t.refresh_token, expiresAt: Date.now() + t.expires_in * 1000 });
171
+ keep(now);
172
+ return now;
173
+ } catch { stop(`Your sign-in has ended or was disconnected. Run ${ME} login again.`); }
174
+ });
106
175
  }
107
176
  notice(s.url);
108
177
  return { url: s.url, token: s.access };
@@ -112,6 +181,7 @@ async function access() {
112
181
  * One MCP tool call; the server is the same one claude.ai and Cursor use. With `soft`, a network blip throws instead of
113
182
  * ending the command, so a long-running one (tail) can try again.
114
183
  */
184
+ let calls = 0;
115
185
  async function tool(name, args = {}, { soft = false } = {}) {
116
186
  const { url, token } = await access();
117
187
  let r;
@@ -119,15 +189,18 @@ async function tool(name, args = {}, { soft = false } = {}) {
119
189
  r = await fetch(`${url}/api/mcp`, {
120
190
  method: "POST",
121
191
  headers: { authorization: `Bearer ${token}`, "content-type": "application/json", accept: "application/json, text/event-stream", "user-agent": `agent-inbox-cli/${VERSION}` },
122
- body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } }),
192
+ body: JSON.stringify({ jsonrpc: "2.0", id: ++calls, method: "tools/call", params: { name, arguments: args } }),
123
193
  });
124
194
  } catch { if (soft) throw new Error("unreachable"); stop(`Could not reach ${url}. Check the address and your connection.`); }
125
195
  if (soft && r.status >= 500) throw new Error("unavailable");
126
- if (r.status === 401) stop(process.env.AGENT_INBOX_TOKEN ? "The token was refused: it has expired or been revoked. Make a new one in Settings, Terminal, AI tools." : `Your sign-in was refused. Run ${ME} login again.`);
127
- if (r.status === 403) stop("Only an admin of the workspace can use this.");
128
- if (r.status === 429) stop("Too many requests just now. Wait a minute and try again.");
129
196
  const raw = await r.text();
130
- let j; try { j = JSON.parse(raw.startsWith("{") ? raw : raw.split("data: ")[1]); } catch { stop(`The server answered ${r.status}. Try again.`); }
197
+ // The server's own words, when it gave them.
198
+ const said = (() => { try { return JSON.parse(raw)?.error?.message ?? null; } catch { return null; } })();
199
+ if (r.status === 401) stop(tokenArg || process.env.AGENT_INBOX_TOKEN || load()?.kind === "token" ? "The token was refused: it has expired or been revoked. Make a new one in Settings, Terminal, AI tools." : `Your sign-in was refused. Run ${ME} login again.`);
200
+ if (r.status === 403) stop(said ?? "This token cannot do that.");
201
+ if (r.status === 429) stop(said ?? "Too many requests just now. Wait a minute and try again.");
202
+ // A plain JSON answer, or an event stream: its data lines, together.
203
+ let j; try { j = JSON.parse(raw.startsWith("{") ? raw : raw.split("\n").filter((l) => l.startsWith("data: ")).map((l) => l.slice(6)).join("")); } catch { stop(`The server answered ${r.status}. Try again.`); }
131
204
  if (j.error) stop(j.error.message);
132
205
  const text = (j.result.content || []).map((c) => c.text).join("\n");
133
206
  return { text, isError: !!j.result.isError, data: j.result.structuredContent };
@@ -397,19 +470,49 @@ async function planFolder(dir) {
397
470
  return tool("import_folder", { files, ...(changed ? { changed } : {}), ...(pruning ? { prune: true } : {}) });
398
471
  }
399
472
 
473
+ /** A line typed at the terminal (a token pasted at login --token). */
474
+ async function ask(question) {
475
+ process.stderr.write(question);
476
+ for await (const line of (await import("node:readline")).createInterface({ input: process.stdin })) return line.trim();
477
+ return "";
478
+ }
479
+
400
480
  async function login(address) {
401
481
  if (!address) stop(`Give your console's address, for example ${ME} login https://inbox.example.com`);
402
482
  const url = clean(address);
483
+ // Without a browser (a server, CI, an agent's sandbox): a personal access token, given or pasted, checked, and kept.
484
+ if (tokenGiven) {
485
+ const token = tokenArg || (process.stdin.isTTY ? await ask("Paste a personal access token from Settings, Terminal, AI tools: ") : (await stdinText()).trim());
486
+ if (!token) stop("No token was given.");
487
+ const r = await fetch(`${url}/api/mcp`, { method: "POST", headers: { authorization: `Bearer ${token}`, "content-type": "application/json", accept: "application/json" },
488
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "whoami", arguments: {} } }) }).catch(() => null);
489
+ if (!r) stop(`Could not reach ${url}. Check the address.`);
490
+ if (r.status === 401) stop("That token was refused: it is wrong, expired or revoked.");
491
+ const me = (await r.json().catch(() => null))?.result?.structuredContent;
492
+ if (!me) stop("That address did not answer as Next does. Is it your Next console?");
493
+ keep({ url, kind: "token", token });
494
+ report(`Signed in to ${me.workspace} as ${me.user}, with a ${me.scope} token. It is kept in ${SAVED}; ${ME} logout forgets it.`, { signedIn: true, ...me });
495
+ return;
496
+ }
403
497
  const server = createServer();
404
- await new Promise((ok) => server.listen(0, "127.0.0.1", ok));
405
- const redirect = `http://127.0.0.1:${server.address().port}/callback`;
406
- let client;
407
- try { client = await (await fetch(`${url}/api/oauth/register`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ client_name: "Next CLI", redirect_uris: [redirect], token_endpoint_auth_method: "none" }) })).json(); }
408
- catch { stop(`Could not reach ${url}. Check the address.`); }
498
+ // The same port and client as last time when it can, so signing in again does not pile up clients in Next.
499
+ const before = load();
500
+ const reuse = before?.url === url && before.clientId && before.port ? before : null;
501
+ await new Promise((ok) => {
502
+ server.once("error", () => server.listen(0, "127.0.0.1", ok));
503
+ server.listen(reuse ? reuse.port : 0, "127.0.0.1", ok);
504
+ });
505
+ const port = server.address().port;
506
+ const redirect = `http://127.0.0.1:${port}/callback`;
507
+ let client = reuse && reuse.port === port ? { client_id: reuse.clientId } : null;
508
+ if (!client) {
509
+ try { client = await (await fetch(`${url}/api/oauth/register`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ client_name: "Next CLI", redirect_uris: [redirect], token_endpoint_auth_method: "none" }) })).json(); }
510
+ catch { stop(`Could not reach ${url}. Check the address.`); }
511
+ }
409
512
  if (!client.client_id) stop(client.error_description || "That address did not accept the sign-in. Is it your Next console?");
410
513
  const verifier = randomBytes(32).toString("base64url"), state = randomBytes(12).toString("base64url");
411
514
  const go = new URL(`${url}/oauth/authorize`);
412
- for (const [k, v] of Object.entries({ response_type: "code", client_id: client.client_id, redirect_uri: redirect, code_challenge: createHash("sha256").update(verifier).digest("base64url"), code_challenge_method: "S256", state, scope: "propose" })) go.searchParams.set(k, v);
515
+ for (const [k, v] of Object.entries({ response_type: "code", client_id: client.client_id, redirect_uri: redirect, code_challenge: createHash("sha256").update(verifier).digest("base64url"), code_challenge_method: "S256", state, scope: readLogin ? "read" : "propose" })) go.searchParams.set(k, v);
413
516
  say(`Opening your browser to sign in and approve the CLI. If it does not open, go to:\n${go}`);
414
517
  // On Windows, explorer drops long addresses like this one; rundll32's URL handler opens the default browser with
415
518
  // the whole address, & and all, without a shell in between.
@@ -429,7 +532,7 @@ async function login(address) {
429
532
  if (back.get("state") !== state) stop(`The answer did not match this sign-in. Run ${ME} login again.`);
430
533
  if (!back.get("code")) stop(back.get("error") === "access_denied" ? "Cancelled: the CLI was not connected." : back.get("error_description") || "The sign-in did not work.");
431
534
  const t = await form(`${url}/api/oauth/token`, { grant_type: "authorization_code", code: back.get("code"), code_verifier: verifier, client_id: client.client_id, redirect_uri: redirect }).catch((e) => stop(e.message));
432
- keep({ url, clientId: client.client_id, access: t.access_token, refresh: t.refresh_token, expiresAt: Date.now() + t.expires_in * 1000, scope: t.scope });
535
+ keep({ url, clientId: client.client_id, port, access: t.access_token, refresh: t.refresh_token, expiresAt: Date.now() + t.expires_in * 1000, scope: t.scope });
433
536
  say(`Signed in to ${url}${t.scope === "read" ? " to look only" : ""}. It shows in Settings, Terminal, AI tools, where you can disconnect it.`);
434
537
  }
435
538
 
@@ -454,7 +557,19 @@ const USAGE = [
454
557
  ["rehearse <file>", "rehearse the agents the file adds or changes on past conversations and wait"],
455
558
  ["rehearse [plan] [--on 20] [--topic refund]", "show me before it goes live: past conversations and the tests, with a plan and without"],
456
559
  ["", "(both cost money, and need Tests and rehearsals from CI turned on)"],
457
- ["logout", "forget this computer's sign-in"],
560
+ ["login <address> --token", "sign in without a browser: paste a personal access token (or pipe it in, or --token <value>)"],
561
+ ["login <address> --read", "sign in to look only"],
562
+ ["whoami", "the workspace, person and token this runs as"],
563
+ ["events [--only conversation,apps]", "changes as they happen, one per line (--json: one JSON object per line), until Ctrl+C"],
564
+ ["listen --forward <address> [--events a,b]", "Next's webhooks, signed as usual, sent to a server on this computer while it runs"],
565
+ ["mcp", "an MCP server over stdio for any AI tool, using this computer's sign-in"],
566
+ ["claude [--project]", "add Next to Claude Code (or write .mcp.json for this project)"],
567
+ ["app ls | why <app> | logs <app> [--follow]", "apps: their health, and their runs as they happen"],
568
+ ["app try <app> <tool> [--input JSON]", "run an app's tool that only reads, on its latest version"],
569
+ ["app fix <app> [--claude]", "its recent failures as a request to fix (--claude hands it to Claude Code here)"],
570
+ ["app dev [folder] <app>", "each save of apps/<app>/ becomes a draft version to preview in Next"],
571
+ ["completion bash|zsh|fish", "Tab completion of commands and real names for your shell"],
572
+ ["logout", "forget this computer's sign-in (and revoke a browser sign-in in Next)"],
458
573
  ["update", "how to get the newest version (a downloaded file updates itself)"],
459
574
  ["help <command>", "one terminal command with an example; ME commands lists them all"],
460
575
  ];
@@ -466,8 +581,10 @@ export function usage(me = ME) {
466
581
 
467
582
  ${lines.join("\n")}
468
583
 
469
- In CI, set AGENT_INBOX_URL and AGENT_INBOX_TOKEN (a token from Settings, Terminal, AI tools) instead of logging in.
470
- Add --markdown to diff for a GitHub job summary. Nothing changes until an admin applies it in Decisions.`;
584
+ Every command takes --json (data, not words: for scripts and agents) and --fields a,b (only those columns).
585
+ Pipe commands in with run - or script -. Exit codes: 0 done, 1 failed or refused, 2 a plan or changes to apply.
586
+ In CI, set AGENT_INBOX_URL and AGENT_INBOX_TOKEN (or --url and --token) instead of logging in.
587
+ --markdown gives plan, push, test and rehearse as a GitHub summary. Nothing changes until an admin applies it in Decisions.`;
471
588
  }
472
589
 
473
590
  // ---- Updates -------------------------------------------------------------------------------------------------------
@@ -522,11 +639,295 @@ async function update() {
522
639
  say(`Updated ${relative(process.cwd(), SELF) || SELF} to ${latest}.`);
523
640
  }
524
641
 
642
+ // ---- For agents: an MCP server on this computer, and Claude Code -----------------------------------------------------
643
+ /**
644
+ * agent-inbox mcp: an MCP server over stdio for any AI tool (Claude Desktop, Cursor, Claude Code), using this computer's
645
+ * sign-in. Each JSON-RPC message read on stdin goes to Next's MCP server; its answer comes back on stdout, one per line.
646
+ */
647
+ async function mcpServer() {
648
+ const rl = (await import("node:readline")).createInterface({ input: process.stdin });
649
+ const out = (o) => process.stdout.write(JSON.stringify(o) + "\n");
650
+ for await (const line of rl) {
651
+ if (!line.trim()) continue;
652
+ let msg; try { msg = JSON.parse(line); } catch { out({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "That is not JSON." } }); continue; }
653
+ const list = Array.isArray(msg) ? msg : [msg];
654
+ const asks = list.filter((m) => m && m.id !== undefined && m.id !== null);
655
+ if (!asks.length) continue; // notifications need no answer
656
+ try {
657
+ const { url, token } = await access();
658
+ const r = await fetch(`${url}/api/mcp`, { method: "POST", headers: { authorization: `Bearer ${token}`, "content-type": "application/json", accept: "application/json, text/event-stream", "user-agent": `agent-inbox-cli/${VERSION} mcp` }, body: JSON.stringify(Array.isArray(msg) ? asks : asks[0]) });
659
+ const raw = await r.text();
660
+ const got = JSON.parse(raw.startsWith("{") || raw.startsWith("[") ? raw : raw.split("\n").filter((l) => l.startsWith("data: ")).map((l) => l.slice(6)).join(""));
661
+ for (const a of Array.isArray(got) ? got : [got]) out(a);
662
+ } catch (err) {
663
+ for (const a of asks) out({ jsonrpc: "2.0", id: a.id, error: { code: -32603, message: `Could not reach Next: ${err?.message ?? "no answer"}` } });
664
+ }
665
+ }
666
+ }
667
+
668
+ /** How an AI tool should start this CLI's MCP server: the installed command, or node and this file. */
669
+ function selfCommand() { return ME === "agent-inbox" ? { command: "agent-inbox", args: ["mcp"] } : { command: process.execPath, args: [SELF, "mcp"] }; }
670
+
671
+ /** agent-inbox claude: add Next to Claude Code (claude mcp add), or write .mcp.json for this project with --project. */
672
+ async function claudeSetup(project) {
673
+ const c = selfCommand();
674
+ if (project) {
675
+ const file = ".mcp.json";
676
+ let cfg = {}; try { cfg = JSON.parse(readFileSync(file, "utf8")); } catch {}
677
+ cfg.mcpServers = { ...(cfg.mcpServers ?? {}), next: { command: c.command, args: c.args } };
678
+ writeFileSync(file, JSON.stringify(cfg, null, 2) + "\n");
679
+ report(`Wrote ${file}: Claude Code and other tools that read it start Next's MCP server with ${c.command} ${c.args.join(" ")}. Commit it so the team gets it too; each person signs in with ${ME} login.`, { wrote: file, server: c });
680
+ return;
681
+ }
682
+ const { spawnSync } = await import("node:child_process");
683
+ const has = spawnSync("claude", ["--version"], { stdio: "ignore" }).status === 0;
684
+ if (!has) stop(`Claude Code is not installed here (no claude command). Install it, or run ${ME} claude --project to write .mcp.json for this folder.`);
685
+ const r = spawnSync("claude", ["mcp", "add", "--scope", "user", "next", "--", c.command, ...c.args], { stdio: asJson ? "ignore" : "inherit" });
686
+ if (r.status !== 0) stop("claude mcp add did not work. Run it yourself: claude mcp add next -- " + [c.command, ...c.args].join(" "));
687
+ report(`Claude Code now has Next's tools in every project (as "next"), signed in as this computer is. Ask it, for example: "what needs a person in Next right now?"`, { added: "next", server: c });
688
+ }
689
+
690
+ // ---- Live: events, and webhooks to this computer -------------------------------------------------------------------
691
+ /** Read a server-sent event stream, calling `on(event, data)` for each; resolves when the stream ends. */
692
+ async function readStream(res, on) {
693
+ const reader = res.body.getReader();
694
+ const decoder = new TextDecoder();
695
+ let buffer = "";
696
+ for (;;) {
697
+ const { value, done } = await reader.read();
698
+ if (done) return;
699
+ buffer += decoder.decode(value, { stream: true });
700
+ let end;
701
+ while ((end = buffer.indexOf("\n\n")) >= 0) {
702
+ const chunk = buffer.slice(0, end); buffer = buffer.slice(end + 2);
703
+ const event = /^event: (\w+)/m.exec(chunk)?.[1] ?? "message";
704
+ const data = chunk.split("\n").filter((l) => l.startsWith("data: ")).map((l) => l.slice(6)).join("");
705
+ let parsed = null; try { parsed = data ? JSON.parse(data) : null; } catch {}
706
+ on(event, parsed);
707
+ }
708
+ }
709
+ }
710
+
711
+ /**
712
+ * agent-inbox events: what changes in the workspace, as it happens (conversations, team chat, alerts, apps, agents),
713
+ * one line each, or one JSON object per line with --json, for an agent or a script to react to. Reconnects by itself.
714
+ */
715
+ async function events(only) {
716
+ let failures = 0;
717
+ for (;;) {
718
+ const { url, token } = await access();
719
+ let res;
720
+ try { res = await fetch(`${url}/api/mcp/events`, { headers: { authorization: `Bearer ${token}`, accept: "text/event-stream", "user-agent": `agent-inbox-cli/${VERSION}` } }); }
721
+ catch { res = null; }
722
+ if (res?.status === 401) stop("The sign-in was refused. Run login again.");
723
+ if (res?.status === 503) stop("Live updates are off on this Next server (Settings, Health says why), so there are no events to follow.");
724
+ if (res?.ok) {
725
+ failures = 0;
726
+ if (!asJson && process.stderr.isTTY) process.stderr.write("Listening for changes. Ctrl+C stops.\n");
727
+ await readStream(res, (event, data) => {
728
+ if (event !== "change" || !data || (only && !only.includes(data.type))) return;
729
+ if (asJson) say(JSON.stringify(data));
730
+ else say(`${new Date(data.at).toLocaleTimeString()} ${data.type}${data.id ? ` ${data.id}` : ""}${data.message ? ` ${data.message.role}: ${String(data.message.content).replace(/\s+/g, " ").slice(0, 100)}` : ""}`);
731
+ }).catch(() => {});
732
+ } else failures += 1;
733
+ if (failures >= 6) stop("Could not reach Next for a while, so following stopped. Run events again to pick up.");
734
+ await new Promise((r) => setTimeout(r, failures ? Math.min(30_000, 1000 * 2 ** failures) : 200));
735
+ }
736
+ }
737
+
738
+ /**
739
+ * agent-inbox listen --forward <address>: Next's webhooks, signed as in production, delivered to a server on this
740
+ * computer while it runs (as stripe listen). Prints the signing secret to check them with. Ctrl+C stops it.
741
+ */
742
+ async function listen(forward, eventsWanted) {
743
+ if (!forward) stop(`Say where to send them, for example ${ME} listen --forward http://localhost:3000/webhooks/next`);
744
+ let target; try { target = new URL(forward); } catch { stop(`${forward} is not a web address.`); }
745
+ const started = await tool("webhook_listen", { action: "start", ...(eventsWanted ? { events: eventsWanted } : {}) });
746
+ if (started.isError) stop(started.text);
747
+ const { id, secret, events: on } = started.data;
748
+ report(`Listening for ${on.join(", ")}, forwarding to ${target}.\nSigning secret for this session: ${secret}\nCtrl+C stops.`, { listening: true, events: on, secret, forward: String(target) });
749
+ let stopping = false;
750
+ const end = async () => { if (stopping) return; stopping = true; await tool("webhook_listen", { action: "stop", listener: id }).catch(() => {}); process.exit(0); };
751
+ process.on("SIGINT", end); process.on("SIGTERM", end);
752
+ for (;;) {
753
+ const got = await tool("webhook_listen", { action: "next", listener: id }, { soft: true }).catch(() => null);
754
+ if (got?.isError) stop(got.text);
755
+ for (const d of got?.data?.deliveries ?? []) {
756
+ let status = 0, problem = "";
757
+ try { const r = await fetch(target, { method: "POST", headers: d.headers, body: d.body, signal: AbortSignal.timeout(10_000) }); status = r.status; await r.body?.cancel().catch(() => {}); }
758
+ catch (err) { problem = err?.name === "TimeoutError" ? "no answer in 10 seconds" : "could not reach it"; }
759
+ if (asJson) say(JSON.stringify({ delivery: d.id, event: d.event, status, ...(problem ? { problem } : {}) }));
760
+ else say(`${new Date().toLocaleTimeString()} ${d.event} -> ${status || problem}`);
761
+ }
762
+ await new Promise((r) => setTimeout(r, 1000));
763
+ }
764
+ }
765
+
766
+ // ---- Apps from the terminal ----------------------------------------------------------------------------------------
767
+ /** The value after a flag in a list of words (--input '{}'), or undefined. */
768
+ const valueOf = (words, name) => { const i = words.indexOf(name); return i >= 0 ? words[i + 1] : undefined; };
769
+ const positional = (words) => words.filter((w, i) => !w.startsWith("--") && !(i > 0 && words[i - 1].startsWith("--") && !["--failed", "--follow", "--claude"].includes(words[i - 1])));
770
+
771
+ async function appCommand(words) {
772
+ const [sub, ...more] = words;
773
+ const pos = positional(more);
774
+ switch (sub) {
775
+ case undefined: case "ls": emit(await tool("app_health")); return;
776
+ case "why": case "health": if (!pos[0]) stop(`Name the app, for example ${ME} app why Refunds`); emit(await tool("app_health", { app: pos.join(" ") })); return;
777
+ case "logs": {
778
+ if (!pos[0]) stop(`Name the app, for example ${ME} app logs Refunds --follow`);
779
+ const failed = more.includes("--failed");
780
+ const first = await tool("app_runs", { app: pos.join(" "), failed });
781
+ if (first.isError) stop(first.text);
782
+ const print = (runs) => { for (const r of [...runs].reverse()) say(asJson ? JSON.stringify(r) : `${new Date(r.at).toLocaleTimeString()} v${r.version} ${r.kind} ${r.name} ${r.ok ? "ok" : `failed: ${r.error ?? ""}`} (${r.ms} ms, ${r.startedBy})`); };
783
+ print(first.data?.runs ?? []);
784
+ if (!first.data?.runs?.length && !asJson) process.stderr.write(failed ? "Nothing has failed in it lately.\n" : "It has not run yet.\n");
785
+ if (!more.includes("--follow")) return;
786
+ let after = first.data?.runs?.[0]?.id;
787
+ if (process.stderr.isTTY && !asJson) process.stderr.write("Following its runs. Ctrl+C stops.\n");
788
+ for (;;) {
789
+ await new Promise((r) => setTimeout(r, 3000));
790
+ const page = await tool("app_runs", { app: pos.join(" "), failed, ...(after ? { after } : {}) }, { soft: true }).catch(() => null);
791
+ if (page?.data?.runs?.length) { print(page.data.runs); after = page.data.runs[0].id; }
792
+ }
793
+ }
794
+ case "fix": {
795
+ if (!pos[0]) stop(`Name the app, for example ${ME} app fix Refunds --claude`);
796
+ const r = await tool("app_fix_request", { app: pos.join(" ") });
797
+ if (r.isError) stop(r.text);
798
+ if (!more.includes("--claude")) { emit(r); return; }
799
+ // Hand it to Claude Code in this folder (the one from agent-inbox pull), to change the app's files.
800
+ const { spawnSync } = await import("node:child_process");
801
+ const run = spawnSync("claude", [r.data.request], { stdio: "inherit" });
802
+ if (run.error) stop(`Claude Code is not installed here. The request is:\n\n${r.data.request}`);
803
+ process.exit(run.status ?? 0);
804
+ }
805
+ case "try": {
806
+ const [name, toolName] = pos;
807
+ if (!name || !toolName) stop(`Name the app and the tool, for example ${ME} app try Refunds look_up --input '{"order":"4411"}' --conversation 1234`);
808
+ let input = {};
809
+ const raw = valueOf(more, "--input");
810
+ if (raw) { try { input = JSON.parse(raw); } catch { stop("--input takes JSON, for example '{\"order\":\"4411\"}'."); } }
811
+ const v = valueOf(more, "--version");
812
+ emit(await tool("app_try", { app: name, tool: toolName, input, ...(valueOf(more, "--conversation") ? { conversation: valueOf(more, "--conversation") } : {}), ...(v ? { version: Number(v) } : {}) }));
813
+ return;
814
+ }
815
+ case "dev": {
816
+ // app dev [folder] <app>: send a draft version each time its files are saved, to preview in Next straight away.
817
+ const dir = pos.length > 1 ? pos[0] : ".";
818
+ const slug = pos.length > 1 ? pos[1] : pos[0];
819
+ if (!slug) stop(`Name the app's folder, for example ${ME} app dev support refunds (for support/apps/refunds).`);
820
+ const appDir = join(dir, "apps", slug);
821
+ if (!existsSync(join(appDir, "app.html"))) stop(`${appDir} has no app.html. Run ${ME} pull first, or name a folder under apps/.`);
822
+ const { watch } = await import("node:fs");
823
+ let timer = null, last = "";
824
+ const sendDraft = async () => {
825
+ const html = readFileSync(join(appDir, "app.html"), "utf8");
826
+ const manifestFile = existsSync(join(appDir, "manifest.yaml")) ? "manifest.yaml" : "manifest.yml";
827
+ const manifest = readFileSync(join(appDir, manifestFile), "utf8");
828
+ if (html + manifest === last) return;
829
+ last = html + manifest;
830
+ const sent = await tool("propose_app", { source: html, manifest, note: "Saved in app dev" }, { soft: true }).catch(() => null);
831
+ if (!sent) { say("Could not reach Next; it tries again on the next save."); return; }
832
+ if (asJson) say(JSON.stringify({ at: new Date().toISOString(), ok: !sent.isError, text: sent.text }));
833
+ else say(`${new Date().toLocaleTimeString()} ${sent.isError ? "Not sent: " : ""}${sent.text}`);
834
+ };
835
+ await sendDraft();
836
+ if (!asJson && process.stderr.isTTY) process.stderr.write(`Watching ${appDir}: each save is a new draft version to preview in Next (Apps). Ctrl+C stops.\n`);
837
+ watch(appDir, () => { clearTimeout(timer); timer = setTimeout(() => void sendDraft(), 400); });
838
+ await new Promise(() => {});
839
+ return;
840
+ }
841
+ default: stop(`${ME} app ls | why <app> | logs <app> [--follow] [--failed] | try <app> <tool> [--input JSON] [--conversation n] | fix <app> [--claude] | dev [folder] <app>`);
842
+ }
843
+ }
844
+
845
+ // ---- Shell completion ----------------------------------------------------------------------------------------------
846
+ export function completionScript(shell, me = "agent-inbox") {
847
+ if (shell === "bash") return `# ${me} completion for bash: add to ~/.bashrc: eval "$(${me} completion bash)"
848
+ _agent_inbox() { local IFS=$'\\n'; COMPREPLY=($(compgen -W "$(${me} __complete "\${COMP_WORDS[@]:1:COMP_CWORD-1}" 2>/dev/null)" -- "\${COMP_WORDS[COMP_CWORD]}")); }
849
+ complete -o default -F _agent_inbox ${me}`;
850
+ if (shell === "zsh") return `# ${me} completion for zsh: add to ~/.zshrc: eval "$(${me} completion zsh)"
851
+ _agent_inbox() { local -a c; c=("\${(@f)$(${me} __complete "\${(@)words[2,CURRENT-1]}" 2>/dev/null)}"); compadd -a c; }
852
+ compdef _agent_inbox ${me}`;
853
+ if (shell === "fish") return `# ${me} completion for fish: ${me} completion fish > ~/.config/fish/completions/${me}.fish
854
+ complete -c ${me} -f -a "(${me} __complete (commandline -opc)[2..-1] 2>/dev/null)"`;
855
+ return null;
856
+ }
857
+ /** The words that may come next, from the words so far: commands, then real names after the flags that take them. */
858
+ async function completeWords(words) {
859
+ const cache = join(DIR, "complete.json");
860
+ let known = null;
861
+ try { const c = JSON.parse(readFileSync(cache, "utf8")); if (Date.now() - c.at < 10 * 60_000) known = c; } catch {}
862
+ if (!known) {
863
+ const [names, help, apps] = await Promise.all([tool("names", {}, { soft: true }).catch(() => null), tool("terminal", { command: "help" }, { soft: true }).catch(() => null), tool("app_health", {}, { soft: true }).catch(() => null)]);
864
+ const commands = [...new Set((help?.data?.tables?.[0]?.rows ?? []).map((r) => String(r.usage ?? "").split(/\s+/)[0]).filter(Boolean))];
865
+ known = { at: Date.now(), names: names?.data ?? {}, commands, apps: (apps?.data?.apps ?? []).map((a) => a.name) };
866
+ try { mkdirSync(DIR, { recursive: true, mode: 0o700 }); writeFileSync(cache, JSON.stringify(known), { mode: 0o600 }); } catch {}
867
+ }
868
+ const prev = words.at(-1);
869
+ const n = known.names ?? {};
870
+ if (!words.length) return [...OWN].filter((c) => !c.startsWith("-") && c !== "__complete").concat(known.commands ?? []);
871
+ if (prev === "--inbox") return n.inboxes ?? [];
872
+ if (prev === "--tag" || prev === "tag") return n.tags ?? [];
873
+ if (prev === "assign") return n.people ?? [];
874
+ if (["pause", "resume", "limit"].includes(prev)) return n.agents ?? [];
875
+ if (prev === "brief") return n.accounts ?? [];
876
+ if (words[0] === "app" && words.length === 1) return ["ls", "why", "logs", "try", "fix", "dev"];
877
+ if (words[0] === "app" && words.length === 2) return known.apps ?? [];
878
+ if (words[0] === "completion") return ["bash", "zsh", "fish"];
879
+ return [];
880
+ }
881
+
882
+ // ---- Output for scripts and agents ----------------------------------------------------------------------------------
883
+ /** Only the chosen columns of each table in a terminal answer's data (--fields name,status). */
884
+ export function pickFields(data, fields) {
885
+ if (!data || !fields) return data;
886
+ const keep = String(fields).split(",").map((f) => f.trim().toLowerCase()).filter(Boolean);
887
+ if (!keep.length || !Array.isArray(data.tables)) return data;
888
+ return { ...data, tables: data.tables.map((t) => ({ columns: t.columns.filter((c) => keep.includes(c)), rows: t.rows.map((r) => Object.fromEntries(Object.entries(r).filter(([k]) => keep.includes(k)))) })) };
889
+ }
890
+ /** Print a terminal answer: its text, or its data with --json. A failure exits 1, so a script or an agent knows. */
891
+ function emit(result, extra = {}) {
892
+ if (asJson) say(JSON.stringify({ ...(result.data ? pickFields(result.data, fieldsArg) : { text: result.text, failed: result.isError }), ...extra }, null, 2));
893
+ else say(result.text);
894
+ if (result.isError) process.exit(1);
895
+ }
896
+ /** Print the CLI's own result: words for a person, or the object with --json. */
897
+ function report(textForPeople, data) { if (asJson) say(JSON.stringify(data, null, 2)); else if (textForPeople) say(textForPeople); }
898
+ /** Everything piped in (agent-inbox run -, script -). */
899
+ async function stdinText() {
900
+ if (process.stdin.isTTY) stop("Nothing was piped in. Pipe commands in, one per line, for example: echo 'ls unassigned' | agent-inbox run -");
901
+ const chunks = [];
902
+ for await (const c of process.stdin) chunks.push(c);
903
+ return Buffer.concat(chunks).toString("utf8");
904
+ }
905
+
525
906
  async function main() {
526
907
  switch (cmd) {
527
908
  case "login": await login(rest[0]); break;
528
909
  case "update": await update(); break;
529
- case "logout": rmSync(SAVED, { force: true }); say("Signed out on this computer. To disconnect it everywhere, revoke it in Settings, Terminal, AI tools."); break;
910
+ case "logout": {
911
+ // The browser sign-in is revoked in Next too; a pasted token stays usable elsewhere until revoked in Settings.
912
+ const s = load();
913
+ if (s?.refresh) await fetch(`${s.url}/api/oauth/revoke`, { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ token: s.refresh, client_id: s.clientId ?? "" }) }).catch(() => {});
914
+ rmSync(SAVED, { force: true });
915
+ report(s?.refresh ? "Signed out, and the sign-in is revoked in Next." : s?.kind === "token" ? "Signed out on this computer. The token itself still works until it is revoked in Settings, Terminal, AI tools." : "Not signed in.", { signedOut: true });
916
+ break;
917
+ }
918
+ case "mcp": await mcpServer(); break;
919
+ case "claude": await claudeSetup(rest.includes("--project")); break;
920
+ case "app": await appCommand(rest); break;
921
+ case "events": { const only = (valueOf(rest, "--only") ?? "").split(",").filter(Boolean); await events(only.length ? only : null); break; }
922
+ case "listen": await listen(valueOf(rest, "--forward"), valueOf(rest, "--events")?.split(",").filter(Boolean)); break;
923
+ case "completion": { const sc = completionScript(rest[0], ME === "agent-inbox" ? "agent-inbox" : "agent-inbox"); if (!sc) stop(`Say which shell: ${ME} completion bash, zsh or fish.`); say(sc); break; }
924
+ case "__complete": { const w = await completeWords(rest.filter(Boolean)).catch(() => []); say(w.join("\n")); break; }
925
+ case "whoami": {
926
+ const me = await tool("whoami");
927
+ if (me.isError) stop(me.text);
928
+ emit(me);
929
+ break;
930
+ }
530
931
  case "export": {
531
932
  const { text, isError } = await tool("export_workspace");
532
933
  if (isError) stop(text);
@@ -540,6 +941,11 @@ switch (cmd) {
540
941
  if (cmd === "plan" && !folder) stop(`${dir} is not a folder from ${ME} pull (it has no workspace.yaml). Run ${ME} pull ${dir === "." ? "support" : dir} first, or ${ME} diff <file> for one workspace file.`);
541
942
  const { text, data } = folder ? await planFolder(dir) : await tool("import_workspace", read(rest[0]));
542
943
  const body = text.replace(/^Plan \w+: /, "").replace(/\n*(Nothing has changed|This token can only look)[\s\S]*$/, "").trim();
944
+ if (asJson) {
945
+ const apps = folder && data?.ok ? changedApps(folderFiles(dir), readState(dir)) : [];
946
+ report("", { ok: Boolean(data?.ok), changes: data?.changes ?? 0, plan: data?.plan ?? null, apps: apps.map((n) => `apps/${n}`), text: body });
947
+ process.exit(!data?.ok ? 1 : data.changes ? 2 : 0);
948
+ }
543
949
  if (!data?.ok) { say(markdown ? `### The workspace file has problems\n\n${fence(body)}` : body); process.exit(1); }
544
950
  const what = folder ? "folder" : "file";
545
951
  // Changed apps are not in the plan: push sends each as a draft.
@@ -563,14 +969,16 @@ switch (cmd) {
563
969
  if (!data.changes) { say(folder ? "Nothing to push: the workspace already matches the folder." : "Nothing to propose: the workspace already matches the file."); if (folder) say(text.split("\n").filter((l) => !/^Nothing would change/.test(l) && l.trim()).join("\n")); break; }
564
970
  const sent = await tool("submit_plan", { plan: data.plan });
565
971
  if (sent.isError) stop(sent.text);
972
+ if (asJson) { report("", { proposed: true, changes: data.changes, plan: data.plan, apps: appsSent, text: sent.text }); break; }
566
973
  say(markdown ? `### Proposed ${data.changes === 1 ? "1 change" : `${data.changes} changes`}\n\n${sent.text}` : `${folder ? `${text.replace(/\n*Nothing has changed\. An AI tool cannot apply[^\n]*/, "").trim()}\n\n` : ""}${sent.text}`);
567
974
  if (folder) say(`Once it is applied, ${ME} pull ${dir} brings the folder up to date. Undo it in the console (Decisions, or undo in the terminal).`);
568
975
  break;
569
976
  }
570
977
  case "run": {
571
- if (!rest.length) stop(`Give a command in quotes, for example ${ME} run "ls unassigned"`);
572
- const { text, isError } = await tool("terminal", { command: rest.join(" ") });
573
- say(text); if (isError) process.exit(1);
978
+ if (!rest.length) stop(`Give a command in quotes, for example ${ME} run "ls unassigned", or pipe commands in with ${ME} run -`);
979
+ // run -: commands piped in, one per line, as one script (one plan for every change).
980
+ if (rest[0] === "-") { const got = await tool("run_script", { script: await stdinText() }); emit(got); break; }
981
+ emit(await tool("terminal", { command: rest[0] }));
574
982
  break;
575
983
  }
576
984
  case "tail": {
@@ -579,7 +987,7 @@ switch (cmd) {
579
987
  if (first.isError) { say(first.text); process.exit(1); }
580
988
  let { body, next } = splitNext(first.text);
581
989
  say(body);
582
- if (!next) process.exit(1);
990
+ if (!next) break;
583
991
  if (!process.stdout.isTTY || process.env.CI) { say(`\nTo continue: ${ME} ${next}`); break; }
584
992
  if (process.stderr.isTTY) process.stderr.write("Following. Ctrl+C stops.\n");
585
993
  let failed = 0;
@@ -591,7 +999,7 @@ switch (cmd) {
591
999
  failed = 0;
592
1000
  const got = splitNext(page.text);
593
1001
  if (got.body && got.body !== "Done.") say(got.body);
594
- if (!got.next) process.exit(1);
1002
+ if (!got.next) process.exit(0);
595
1003
  next = got.next;
596
1004
  } catch {
597
1005
  failed += 1;
@@ -600,10 +1008,11 @@ switch (cmd) {
600
1008
  }
601
1009
  }
602
1010
  case "script": {
603
- if (!rest[0]) stop(`Give a file of terminal commands, one per line, for example ${ME} script onboarding.txt`);
604
- let body; try { body = readFileSync(rest[0], "utf8"); } catch { stop(`Could not read ${rest[0]}.`); }
1011
+ if (!rest[0]) stop(`Give a file of terminal commands, one per line, for example ${ME} script onboarding.txt (or - to read them piped in)`);
1012
+ let body; try { body = rest[0] === "-" ? await stdinText() : readFileSync(rest[0], "utf8"); } catch { stop(`Could not read ${rest[0]}.`); }
605
1013
  const got = await tool("run_script", { script: body });
606
1014
  const isError = got.isError;
1015
+ if (asJson && (isError || !proposing)) { emit(got); process.exit((got.data?.plan ?? null) ? 2 : 0); }
607
1016
  // The server's note to AI tools about submit_plan; the CLI says it in its own words.
608
1017
  const text = got.text.replace(/\n*Nothing has changed\. An AI tool cannot apply[^\n]*/, "");
609
1018
  if (isError) { say(text); process.exit(1); }
@@ -675,36 +1084,34 @@ Then:
675
1084
  const jobs = started.data?.jobs ?? [];
676
1085
  if (!jobs.length) { say(started.text); break; }
677
1086
  const { ok, lines } = await waitJobs(jobs);
1087
+ if (asJson) { report("", { ok, results: lines }); process.exit(ok ? 0 : 1); }
678
1088
  say(markdown ? `### ${cmd === "test" ? "Agent tests" : "Rehearsal"}: ${ok ? "pass" : "needs a look"}\n\n${lines.map((l) => `- ${l}`).join("\n")}` : lines.join("\n"));
679
1089
  process.exit(ok ? 0 : 1);
680
1090
  }
681
1091
  case "commands": {
682
1092
  // The terminal's own list: the same commands, and the same help, as the console terminal and AI tools.
683
- const { text, isError } = await tool("terminal", { command: "help" });
684
- say(text); if (isError) process.exit(1);
1093
+ emit(await tool("terminal", { command: "help" }));
685
1094
  break;
686
1095
  }
687
1096
  case undefined: case "--help": case "-h": say(usage()); break;
688
1097
  case "help": {
689
1098
  if (!rest.length) { say(usage()); break; }
690
- const { text, isError } = await tool("terminal", { command: `help ${rest.join(" ")}` });
691
- say(text); if (isError) process.exit(1);
1099
+ emit(await tool("terminal", { command: `help ${commandLine(rest)}` }));
692
1100
  break;
693
1101
  }
694
1102
  case "submit": {
695
1103
  // A plan a change made here, sent to Decisions for an admin to apply.
696
1104
  if (!rest[0]) stop(`Give the plan to send, for example ${ME} submit 1a2b3c4d (the reference a change printed).`);
697
- const sent = await tool("submit_plan", { plan: rest[0] });
698
- say(sent.text); if (sent.isError) process.exit(1);
1105
+ emit(await tool("submit_plan", { plan: rest[0] }));
699
1106
  break;
700
1107
  }
701
1108
  default: {
702
1109
  // Anything else is a terminal command, as typed in the console: agent-inbox ls unassigned, agent-inbox agents.
703
- const { text, isError } = await tool("terminal", { command: [cmd, ...rest].join(" ") });
1110
+ // Each word keeps its quoting: agent-inbox route test "where is my refund?" arrives as one phrase.
1111
+ const got = await tool("terminal", { command: commandLine(cmd ? [cmd, ...rest] : rest) });
704
1112
  // A change is only a plan from here. The server's note is written for AI tools; the CLI says what a person can do.
705
- const plan = (/Plan ([0-9a-f]{8})/.exec(text) ?? [])[1];
706
- say(plan ? text.replace(/Nothing has changed\. An AI tool cannot apply a change:[^\n]*/, `Nothing has changed. Apply it in the console's terminal (Ctrl+\` on any page, then apply ${plan}), or send it to Decisions for an admin with ${ME} submit ${plan}.`) : text);
707
- if (isError) process.exit(1);
1113
+ const plan = (/Plan ([0-9a-f]{8})/.exec(got.text) ?? [])[1];
1114
+ emit(plan ? { ...got, text: got.text.replace(/Nothing has changed\. An AI tool cannot apply a change:[^\n]*/, `Nothing has changed. Apply it in the console's terminal (Ctrl+\` on any page, then apply ${plan}), or send it to Decisions for an admin with ${ME} submit ${plan}.`) } : got);
708
1115
  }
709
1116
  }
710
1117
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@droconnell/agent-inbox-cli",
3
- "version": "1.10.0",
4
- "description": "The Next CLI: a support workspace's setup as a file in git, and the console terminal from your own computer.",
3
+ "version": "2.0.0",
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": {
7
7
  "agent-inbox": "agent-inbox.mjs"