@droconnell/agent-inbox-cli 1.10.0 → 2.1.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 +25 -2
  2. package/agent-inbox.mjs +493 -49
  3. package/package.json +2 -2
package/README.md CHANGED
@@ -10,7 +10,14 @@ Needs Node 18 or later. No other dependencies.
10
10
  npm i -g @droconnell/agent-inbox-cli
11
11
  ```
12
12
 
13
- That installs the command `agent-inbox`. You can also download the single file from your own Next address and run it with Node: `curl -fsSLO https://your-next-address/cli/agent-inbox.mjs`, then `node agent-inbox.mjs ...`.
13
+ That installs the command `agent-inbox`. On a Mac or Linux, if npm says `EACCES: permission denied`, give npm a folder of your own once, then install again without `sudo`:
14
+
15
+ ```bash
16
+ mkdir -p ~/.npm-global && npm config set prefix ~/.npm-global
17
+ echo 'export PATH="$HOME/.npm-global/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc
18
+ ```
19
+
20
+ You can also download the single file from your own Next address and run it with Node: `curl -fsSLO https://your-next-address/cli/agent-inbox.mjs`, then `node agent-inbox.mjs ...`.
14
21
 
15
22
  ## Sign in
16
23
 
@@ -20,7 +27,21 @@ agent-inbox login https://your-next-address
20
27
 
21
28
  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
29
 
23
- In CI, set `AGENT_INBOX_URL` and `AGENT_INBOX_TOKEN` (a token from Settings, Terminal, AI tools) instead of signing in.
30
+ 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.
31
+
32
+ ## For AI agents
33
+
34
+ ```bash
35
+ agent-inbox claude # add Next to Claude Code as an MCP server
36
+ agent-inbox mcp # Next as an MCP server for any AI tool
37
+ agent-inbox ls unassigned --json # any command as JSON; --fields customer,status keeps those columns
38
+ echo 'today' | agent-inbox run - # commands from a pipe
39
+ agent-inbox events --json # each change as it happens, one JSON line each
40
+ agent-inbox app why Refunds # why an app fails; app logs, app try, app fix
41
+ agent-inbox listen --forward http://localhost:3001/hook # webhooks to your computer, signed
42
+ ```
43
+
44
+ Exit codes: 0 worked, 1 failed, 2 `plan`, `diff` or `script` found changes.
24
45
 
25
46
  ## Use it
26
47
 
@@ -31,6 +52,8 @@ agent-inbox push support # send the folder's changes to Decisions
31
52
  agent-inbox export agent-inbox.yaml # the setup as one YAML file
32
53
  agent-inbox diff agent-inbox.yaml # what the file would change; changes nothing
33
54
  agent-inbox propose agent-inbox.yaml # send the changes to Decisions
55
+ agent-inbox policy pull # what every agent may do, to policy.yaml, for git
56
+ agent-inbox policy check # exit 1 when the workspace no longer matches policy.yaml
34
57
  agent-inbox ls unassigned # any console terminal command
35
58
  agent-inbox help # every command
36
59
  ```
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.1.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", "policy", "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 };
@@ -195,7 +268,8 @@ export function ciWorkflow(url, folder) {
195
268
  return `# Next support, written by agent-inbox ci init. The support setup lives in ${dir === "." ? "this repository" : `${dir}/`} (agent-inbox pull).
196
269
  # Pull requests: what the change would do, and a rehearsal on past conversations and the saved tests, as one comment.
197
270
  # Merges to main: the changes are proposed in Next's Decisions, for an admin to apply.
198
- # Nightly: changes someone made in Next's console come back as a pull request, so the two never drift apart.
271
+ # Nightly: changes someone made in Next's console come back as a pull request, so the two never drift apart. That
272
+ # includes policy.yaml, what every agent may do: a change to it (an agent now allowed to act alone) is a reviewed line.
199
273
  # Needs the repository secret AGENT_INBOX_TOKEN: a Next personal access token set to Look and propose changes.
200
274
  name: Next support
201
275
  on:
@@ -243,6 +317,10 @@ ${setup}
243
317
  steps:
244
318
  ${setup}
245
319
  - run: node agent-inbox.mjs pull ${dir}
320
+ - name: What the agents may do
321
+ run: |
322
+ node agent-inbox.mjs policy check ${dir === "." ? "" : `${dir}/`}policy.yaml --markdown >> "$GITHUB_STEP_SUMMARY" || true
323
+ node agent-inbox.mjs policy pull ${dir === "." ? "" : `${dir}/`}policy.yaml
246
324
  - name: Open a pull request with what changed in Next
247
325
  env: { GH_TOKEN: "\${{ github.token }}" }
248
326
  run: |
@@ -251,7 +329,7 @@ ${setup}
251
329
  branch="next-changes-$(date +%Y-%m-%d)"
252
330
  git config user.name "Next" && git config user.email "next@users.noreply.github.com"
253
331
  git checkout -b "$branch" && git add -A && git commit -m "Changes made in Next" && git push -u origin "$branch"
254
- gh pr create --title "Changes made in Next" --body "Someone changed the support setup in Next's console. Merging brings this folder up to date; nothing in Next changes."
332
+ gh pr create --title "Changes made in Next" --body "Someone changed the support setup in Next's console. Merging brings this folder up to date; nothing in Next changes. A change to policy.yaml is a change to what the AI agents may do: check it before merging."
255
333
  `;
256
334
  }
257
335
 
@@ -311,12 +389,17 @@ const hash = (s) => createHash("sha256").update(s).digest("hex").slice(0, 16);
311
389
  const readState = (dir) => { try { return JSON.parse(readFileSync(join(dir, STATE), "utf8")); } catch { return null; } };
312
390
  /** A folder pull made, or one laid out like one: workspace.yaml at the top. */
313
391
  export const isPulled = (dir) => existsSync(join(dir, STATE)) || existsSync(join(dir, "workspace.yaml"));
314
- /** Every file in the folder, by path relative to it, skipping hidden ones (.git, the state file) and node_modules. */
392
+ /**
393
+ * Every file in the folder, by path relative to it, skipping hidden ones (.git, the state file), node_modules, and
394
+ * policy.yaml at the top, which policy pull keeps and policy check reads: it records the setup, it does not change it.
395
+ */
396
+ export const POLICY_FILE = "policy.yaml";
315
397
  export function folderFiles(dir) {
316
398
  const out = {};
317
399
  const go = (d) => {
318
400
  for (const e of readdirSync(d, { withFileTypes: true })) {
319
401
  if (e.name.startsWith(".") || e.name === "node_modules") continue;
402
+ if (d === dir && e.name === POLICY_FILE) continue;
320
403
  const p = join(d, e.name);
321
404
  if (e.isDirectory()) go(p); else if (statSync(p).size <= 1_000_000) out[posix(relative(dir, p))] = readFileSync(p, "utf8");
322
405
  }
@@ -397,19 +480,49 @@ async function planFolder(dir) {
397
480
  return tool("import_folder", { files, ...(changed ? { changed } : {}), ...(pruning ? { prune: true } : {}) });
398
481
  }
399
482
 
483
+ /** A line typed at the terminal (a token pasted at login --token). */
484
+ async function ask(question) {
485
+ process.stderr.write(question);
486
+ for await (const line of (await import("node:readline")).createInterface({ input: process.stdin })) return line.trim();
487
+ return "";
488
+ }
489
+
400
490
  async function login(address) {
401
491
  if (!address) stop(`Give your console's address, for example ${ME} login https://inbox.example.com`);
402
492
  const url = clean(address);
493
+ // Without a browser (a server, CI, an agent's sandbox): a personal access token, given or pasted, checked, and kept.
494
+ if (tokenGiven) {
495
+ const token = tokenArg || (process.stdin.isTTY ? await ask("Paste a personal access token from Settings, Terminal, AI tools: ") : (await stdinText()).trim());
496
+ if (!token) stop("No token was given.");
497
+ const r = await fetch(`${url}/api/mcp`, { method: "POST", headers: { authorization: `Bearer ${token}`, "content-type": "application/json", accept: "application/json" },
498
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "whoami", arguments: {} } }) }).catch(() => null);
499
+ if (!r) stop(`Could not reach ${url}. Check the address.`);
500
+ if (r.status === 401) stop("That token was refused: it is wrong, expired or revoked.");
501
+ const me = (await r.json().catch(() => null))?.result?.structuredContent;
502
+ if (!me) stop("That address did not answer as Next does. Is it your Next console?");
503
+ keep({ url, kind: "token", token });
504
+ 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 });
505
+ return;
506
+ }
403
507
  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.`); }
508
+ // The same port and client as last time when it can, so signing in again does not pile up clients in Next.
509
+ const before = load();
510
+ const reuse = before?.url === url && before.clientId && before.port ? before : null;
511
+ await new Promise((ok) => {
512
+ server.once("error", () => server.listen(0, "127.0.0.1", ok));
513
+ server.listen(reuse ? reuse.port : 0, "127.0.0.1", ok);
514
+ });
515
+ const port = server.address().port;
516
+ const redirect = `http://127.0.0.1:${port}/callback`;
517
+ let client = reuse && reuse.port === port ? { client_id: reuse.clientId } : null;
518
+ if (!client) {
519
+ 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(); }
520
+ catch { stop(`Could not reach ${url}. Check the address.`); }
521
+ }
409
522
  if (!client.client_id) stop(client.error_description || "That address did not accept the sign-in. Is it your Next console?");
410
523
  const verifier = randomBytes(32).toString("base64url"), state = randomBytes(12).toString("base64url");
411
524
  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);
525
+ 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
526
  say(`Opening your browser to sign in and approve the CLI. If it does not open, go to:\n${go}`);
414
527
  // On Windows, explorer drops long addresses like this one; rundll32's URL handler opens the default browser with
415
528
  // the whole address, & and all, without a shell in between.
@@ -429,7 +542,7 @@ async function login(address) {
429
542
  if (back.get("state") !== state) stop(`The answer did not match this sign-in. Run ${ME} login again.`);
430
543
  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
544
  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 });
545
+ 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
546
  say(`Signed in to ${url}${t.scope === "read" ? " to look only" : ""}. It shows in Settings, Terminal, AI tools, where you can disconnect it.`);
434
547
  }
435
548
 
@@ -454,7 +567,22 @@ const USAGE = [
454
567
  ["rehearse <file>", "rehearse the agents the file adds or changes on past conversations and wait"],
455
568
  ["rehearse [plan] [--on 20] [--topic refund]", "show me before it goes live: past conversations and the tests, with a plan and without"],
456
569
  ["", "(both cost money, and need Tests and rehearsals from CI turned on)"],
457
- ["logout", "forget this computer's sign-in"],
570
+ ["login <address> --token", "sign in without a browser: paste a personal access token (or pipe it in, or --token <value>)"],
571
+ ["login <address> --read", "sign in to look only"],
572
+ ["whoami", "the workspace, person and token this runs as"],
573
+ ["policy pull [policy.yaml]", "write what every agent may do (apps, tools, limits, guards) to a file to keep in git"],
574
+ ["policy check [policy.yaml]", "fail (exit 1) when the workspace no longer matches the file: for CI"],
575
+ ["policy", "print what every agent may do"],
576
+ ["events [--only conversation,apps]", "changes as they happen, one per line (--json: one JSON object per line), until Ctrl+C"],
577
+ ["listen --forward <address> [--events a,b]", "Next's webhooks, signed as usual, sent to a server on this computer while it runs"],
578
+ ["mcp", "an MCP server over stdio for any AI tool, using this computer's sign-in"],
579
+ ["claude [--project]", "add Next to Claude Code (or write .mcp.json for this project)"],
580
+ ["app ls | why <app> | logs <app> [--follow]", "apps: their health, and their runs as they happen"],
581
+ ["app try <app> <tool> [--input JSON]", "run an app's tool that only reads, on its latest version"],
582
+ ["app fix <app> [--claude]", "its recent failures as a request to fix (--claude hands it to Claude Code here)"],
583
+ ["app dev [folder] <app>", "each save of apps/<app>/ becomes a draft version to preview in Next"],
584
+ ["completion bash|zsh|fish", "Tab completion of commands and real names for your shell"],
585
+ ["logout", "forget this computer's sign-in (and revoke a browser sign-in in Next)"],
458
586
  ["update", "how to get the newest version (a downloaded file updates itself)"],
459
587
  ["help <command>", "one terminal command with an example; ME commands lists them all"],
460
588
  ];
@@ -466,8 +594,10 @@ export function usage(me = ME) {
466
594
 
467
595
  ${lines.join("\n")}
468
596
 
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.`;
597
+ Every command takes --json (data, not words: for scripts and agents) and --fields a,b (only those columns).
598
+ Pipe commands in with run - or script -. Exit codes: 0 done, 1 failed or refused, 2 a plan or changes to apply.
599
+ In CI, set AGENT_INBOX_URL and AGENT_INBOX_TOKEN (or --url and --token) instead of logging in.
600
+ --markdown gives plan, push, test and rehearse as a GitHub summary. Nothing changes until an admin applies it in Decisions.`;
471
601
  }
472
602
 
473
603
  // ---- Updates -------------------------------------------------------------------------------------------------------
@@ -522,11 +652,319 @@ async function update() {
522
652
  say(`Updated ${relative(process.cwd(), SELF) || SELF} to ${latest}.`);
523
653
  }
524
654
 
655
+ // ---- For agents: an MCP server on this computer, and Claude Code -----------------------------------------------------
656
+ /**
657
+ * agent-inbox mcp: an MCP server over stdio for any AI tool (Claude Desktop, Cursor, Claude Code), using this computer's
658
+ * sign-in. Each JSON-RPC message read on stdin goes to Next's MCP server; its answer comes back on stdout, one per line.
659
+ */
660
+ async function mcpServer() {
661
+ const rl = (await import("node:readline")).createInterface({ input: process.stdin });
662
+ const out = (o) => process.stdout.write(JSON.stringify(o) + "\n");
663
+ for await (const line of rl) {
664
+ if (!line.trim()) continue;
665
+ let msg; try { msg = JSON.parse(line); } catch { out({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "That is not JSON." } }); continue; }
666
+ const list = Array.isArray(msg) ? msg : [msg];
667
+ const asks = list.filter((m) => m && m.id !== undefined && m.id !== null);
668
+ if (!asks.length) continue; // notifications need no answer
669
+ try {
670
+ const { url, token } = await access();
671
+ 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]) });
672
+ const raw = await r.text();
673
+ const got = JSON.parse(raw.startsWith("{") || raw.startsWith("[") ? raw : raw.split("\n").filter((l) => l.startsWith("data: ")).map((l) => l.slice(6)).join(""));
674
+ for (const a of Array.isArray(got) ? got : [got]) out(a);
675
+ } catch (err) {
676
+ for (const a of asks) out({ jsonrpc: "2.0", id: a.id, error: { code: -32603, message: `Could not reach Next: ${err?.message ?? "no answer"}` } });
677
+ }
678
+ }
679
+ }
680
+
681
+ /** How an AI tool should start this CLI's MCP server: the installed command, or node and this file. */
682
+ function selfCommand() { return ME === "agent-inbox" ? { command: "agent-inbox", args: ["mcp"] } : { command: process.execPath, args: [SELF, "mcp"] }; }
683
+
684
+ /** agent-inbox claude: add Next to Claude Code (claude mcp add), or write .mcp.json for this project with --project. */
685
+ async function claudeSetup(project) {
686
+ const c = selfCommand();
687
+ if (project) {
688
+ const file = ".mcp.json";
689
+ let cfg = {}; try { cfg = JSON.parse(readFileSync(file, "utf8")); } catch {}
690
+ cfg.mcpServers = { ...(cfg.mcpServers ?? {}), next: { command: c.command, args: c.args } };
691
+ writeFileSync(file, JSON.stringify(cfg, null, 2) + "\n");
692
+ 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 });
693
+ return;
694
+ }
695
+ const { spawnSync } = await import("node:child_process");
696
+ const has = spawnSync("claude", ["--version"], { stdio: "ignore" }).status === 0;
697
+ 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.`);
698
+ const r = spawnSync("claude", ["mcp", "add", "--scope", "user", "next", "--", c.command, ...c.args], { stdio: asJson ? "ignore" : "inherit" });
699
+ if (r.status !== 0) stop("claude mcp add did not work. Run it yourself: claude mcp add next -- " + [c.command, ...c.args].join(" "));
700
+ 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 });
701
+ }
702
+
703
+ // ---- Live: events, and webhooks to this computer -------------------------------------------------------------------
704
+ /** Read a server-sent event stream, calling `on(event, data)` for each; resolves when the stream ends. */
705
+ async function readStream(res, on) {
706
+ const reader = res.body.getReader();
707
+ const decoder = new TextDecoder();
708
+ let buffer = "";
709
+ for (;;) {
710
+ const { value, done } = await reader.read();
711
+ if (done) return;
712
+ buffer += decoder.decode(value, { stream: true });
713
+ let end;
714
+ while ((end = buffer.indexOf("\n\n")) >= 0) {
715
+ const chunk = buffer.slice(0, end); buffer = buffer.slice(end + 2);
716
+ const event = /^event: (\w+)/m.exec(chunk)?.[1] ?? "message";
717
+ const data = chunk.split("\n").filter((l) => l.startsWith("data: ")).map((l) => l.slice(6)).join("");
718
+ let parsed = null; try { parsed = data ? JSON.parse(data) : null; } catch {}
719
+ on(event, parsed);
720
+ }
721
+ }
722
+ }
723
+
724
+ /**
725
+ * agent-inbox events: what changes in the workspace, as it happens (conversations, team chat, alerts, apps, agents),
726
+ * one line each, or one JSON object per line with --json, for an agent or a script to react to. Reconnects by itself.
727
+ */
728
+ async function events(only) {
729
+ let failures = 0;
730
+ for (;;) {
731
+ const { url, token } = await access();
732
+ let res;
733
+ try { res = await fetch(`${url}/api/mcp/events`, { headers: { authorization: `Bearer ${token}`, accept: "text/event-stream", "user-agent": `agent-inbox-cli/${VERSION}` } }); }
734
+ catch { res = null; }
735
+ if (res?.status === 401) stop("The sign-in was refused. Run login again.");
736
+ if (res?.status === 503) stop("Live updates are off on this Next server (Settings, Health says why), so there are no events to follow.");
737
+ if (res?.ok) {
738
+ failures = 0;
739
+ if (!asJson && process.stderr.isTTY) process.stderr.write("Listening for changes. Ctrl+C stops.\n");
740
+ await readStream(res, (event, data) => {
741
+ if (event !== "change" || !data || (only && !only.includes(data.type))) return;
742
+ if (asJson) say(JSON.stringify(data));
743
+ 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)}` : ""}`);
744
+ }).catch(() => {});
745
+ } else failures += 1;
746
+ if (failures >= 6) stop("Could not reach Next for a while, so following stopped. Run events again to pick up.");
747
+ await new Promise((r) => setTimeout(r, failures ? Math.min(30_000, 1000 * 2 ** failures) : 200));
748
+ }
749
+ }
750
+
751
+ /**
752
+ * agent-inbox listen --forward <address>: Next's webhooks, signed as in production, delivered to a server on this
753
+ * computer while it runs (as stripe listen). Prints the signing secret to check them with. Ctrl+C stops it.
754
+ */
755
+ async function listen(forward, eventsWanted) {
756
+ if (!forward) stop(`Say where to send them, for example ${ME} listen --forward http://localhost:3000/webhooks/next`);
757
+ let target; try { target = new URL(forward); } catch { stop(`${forward} is not a web address.`); }
758
+ const started = await tool("webhook_listen", { action: "start", ...(eventsWanted ? { events: eventsWanted } : {}) });
759
+ if (started.isError) stop(started.text);
760
+ const { id, secret, events: on } = started.data;
761
+ 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) });
762
+ let stopping = false;
763
+ const end = async () => { if (stopping) return; stopping = true; await tool("webhook_listen", { action: "stop", listener: id }).catch(() => {}); process.exit(0); };
764
+ process.on("SIGINT", end); process.on("SIGTERM", end);
765
+ for (;;) {
766
+ const got = await tool("webhook_listen", { action: "next", listener: id }, { soft: true }).catch(() => null);
767
+ if (got?.isError) stop(got.text);
768
+ for (const d of got?.data?.deliveries ?? []) {
769
+ let status = 0, problem = "";
770
+ 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(() => {}); }
771
+ catch (err) { problem = err?.name === "TimeoutError" ? "no answer in 10 seconds" : "could not reach it"; }
772
+ if (asJson) say(JSON.stringify({ delivery: d.id, event: d.event, status, ...(problem ? { problem } : {}) }));
773
+ else say(`${new Date().toLocaleTimeString()} ${d.event} -> ${status || problem}`);
774
+ }
775
+ await new Promise((r) => setTimeout(r, 1000));
776
+ }
777
+ }
778
+
779
+ // ---- Apps from the terminal ----------------------------------------------------------------------------------------
780
+ /** The value after a flag in a list of words (--input '{}'), or undefined. */
781
+ const valueOf = (words, name) => { const i = words.indexOf(name); return i >= 0 ? words[i + 1] : undefined; };
782
+ const positional = (words) => words.filter((w, i) => !w.startsWith("--") && !(i > 0 && words[i - 1].startsWith("--") && !["--failed", "--follow", "--claude"].includes(words[i - 1])));
783
+
784
+ async function appCommand(words) {
785
+ const [sub, ...more] = words;
786
+ const pos = positional(more);
787
+ switch (sub) {
788
+ case undefined: case "ls": emit(await tool("app_health")); return;
789
+ 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;
790
+ case "logs": {
791
+ if (!pos[0]) stop(`Name the app, for example ${ME} app logs Refunds --follow`);
792
+ const failed = more.includes("--failed");
793
+ const first = await tool("app_runs", { app: pos.join(" "), failed });
794
+ if (first.isError) stop(first.text);
795
+ 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})`); };
796
+ print(first.data?.runs ?? []);
797
+ if (!first.data?.runs?.length && !asJson) process.stderr.write(failed ? "Nothing has failed in it lately.\n" : "It has not run yet.\n");
798
+ if (!more.includes("--follow")) return;
799
+ let after = first.data?.runs?.[0]?.id;
800
+ if (process.stderr.isTTY && !asJson) process.stderr.write("Following its runs. Ctrl+C stops.\n");
801
+ for (;;) {
802
+ await new Promise((r) => setTimeout(r, 3000));
803
+ const page = await tool("app_runs", { app: pos.join(" "), failed, ...(after ? { after } : {}) }, { soft: true }).catch(() => null);
804
+ if (page?.data?.runs?.length) { print(page.data.runs); after = page.data.runs[0].id; }
805
+ }
806
+ }
807
+ case "fix": {
808
+ if (!pos[0]) stop(`Name the app, for example ${ME} app fix Refunds --claude`);
809
+ const r = await tool("app_fix_request", { app: pos.join(" ") });
810
+ if (r.isError) stop(r.text);
811
+ if (!more.includes("--claude")) { emit(r); return; }
812
+ // Hand it to Claude Code in this folder (the one from agent-inbox pull), to change the app's files.
813
+ const { spawnSync } = await import("node:child_process");
814
+ const run = spawnSync("claude", [r.data.request], { stdio: "inherit" });
815
+ if (run.error) stop(`Claude Code is not installed here. The request is:\n\n${r.data.request}`);
816
+ process.exit(run.status ?? 0);
817
+ }
818
+ case "try": {
819
+ const [name, toolName] = pos;
820
+ if (!name || !toolName) stop(`Name the app and the tool, for example ${ME} app try Refunds look_up --input '{"order":"4411"}' --conversation 1234`);
821
+ let input = {};
822
+ const raw = valueOf(more, "--input");
823
+ if (raw) { try { input = JSON.parse(raw); } catch { stop("--input takes JSON, for example '{\"order\":\"4411\"}'."); } }
824
+ const v = valueOf(more, "--version");
825
+ emit(await tool("app_try", { app: name, tool: toolName, input, ...(valueOf(more, "--conversation") ? { conversation: valueOf(more, "--conversation") } : {}), ...(v ? { version: Number(v) } : {}) }));
826
+ return;
827
+ }
828
+ case "dev": {
829
+ // app dev [folder] <app>: send a draft version each time its files are saved, to preview in Next straight away.
830
+ const dir = pos.length > 1 ? pos[0] : ".";
831
+ const slug = pos.length > 1 ? pos[1] : pos[0];
832
+ if (!slug) stop(`Name the app's folder, for example ${ME} app dev support refunds (for support/apps/refunds).`);
833
+ const appDir = join(dir, "apps", slug);
834
+ if (!existsSync(join(appDir, "app.html"))) stop(`${appDir} has no app.html. Run ${ME} pull first, or name a folder under apps/.`);
835
+ const { watch } = await import("node:fs");
836
+ let timer = null, last = "";
837
+ const sendDraft = async () => {
838
+ const html = readFileSync(join(appDir, "app.html"), "utf8");
839
+ const manifestFile = existsSync(join(appDir, "manifest.yaml")) ? "manifest.yaml" : "manifest.yml";
840
+ const manifest = readFileSync(join(appDir, manifestFile), "utf8");
841
+ if (html + manifest === last) return;
842
+ last = html + manifest;
843
+ const sent = await tool("propose_app", { source: html, manifest, note: "Saved in app dev" }, { soft: true }).catch(() => null);
844
+ if (!sent) { say("Could not reach Next; it tries again on the next save."); return; }
845
+ if (asJson) say(JSON.stringify({ at: new Date().toISOString(), ok: !sent.isError, text: sent.text }));
846
+ else say(`${new Date().toLocaleTimeString()} ${sent.isError ? "Not sent: " : ""}${sent.text}`);
847
+ };
848
+ await sendDraft();
849
+ 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`);
850
+ watch(appDir, () => { clearTimeout(timer); timer = setTimeout(() => void sendDraft(), 400); });
851
+ await new Promise(() => {});
852
+ return;
853
+ }
854
+ default: stop(`${ME} app ls | why <app> | logs <app> [--follow] [--failed] | try <app> <tool> [--input JSON] [--conversation n] | fix <app> [--claude] | dev [folder] <app>`);
855
+ }
856
+ }
857
+
858
+ // ---- Shell completion ----------------------------------------------------------------------------------------------
859
+ export function completionScript(shell, me = "agent-inbox") {
860
+ if (shell === "bash") return `# ${me} completion for bash: add to ~/.bashrc: eval "$(${me} completion bash)"
861
+ _agent_inbox() { local IFS=$'\\n'; COMPREPLY=($(compgen -W "$(${me} __complete "\${COMP_WORDS[@]:1:COMP_CWORD-1}" 2>/dev/null)" -- "\${COMP_WORDS[COMP_CWORD]}")); }
862
+ complete -o default -F _agent_inbox ${me}`;
863
+ if (shell === "zsh") return `# ${me} completion for zsh: add to ~/.zshrc: eval "$(${me} completion zsh)"
864
+ _agent_inbox() { local -a c; c=("\${(@f)$(${me} __complete "\${(@)words[2,CURRENT-1]}" 2>/dev/null)}"); compadd -a c; }
865
+ compdef _agent_inbox ${me}`;
866
+ if (shell === "fish") return `# ${me} completion for fish: ${me} completion fish > ~/.config/fish/completions/${me}.fish
867
+ complete -c ${me} -f -a "(${me} __complete (commandline -opc)[2..-1] 2>/dev/null)"`;
868
+ return null;
869
+ }
870
+ /** The words that may come next, from the words so far: commands, then real names after the flags that take them. */
871
+ async function completeWords(words) {
872
+ const cache = join(DIR, "complete.json");
873
+ let known = null;
874
+ try { const c = JSON.parse(readFileSync(cache, "utf8")); if (Date.now() - c.at < 10 * 60_000) known = c; } catch {}
875
+ if (!known) {
876
+ 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)]);
877
+ const commands = [...new Set((help?.data?.tables?.[0]?.rows ?? []).map((r) => String(r.usage ?? "").split(/\s+/)[0]).filter(Boolean))];
878
+ known = { at: Date.now(), names: names?.data ?? {}, commands, apps: (apps?.data?.apps ?? []).map((a) => a.name) };
879
+ try { mkdirSync(DIR, { recursive: true, mode: 0o700 }); writeFileSync(cache, JSON.stringify(known), { mode: 0o600 }); } catch {}
880
+ }
881
+ const prev = words.at(-1);
882
+ const n = known.names ?? {};
883
+ if (!words.length) return [...OWN].filter((c) => !c.startsWith("-") && c !== "__complete").concat(known.commands ?? []);
884
+ if (prev === "--inbox") return n.inboxes ?? [];
885
+ if (prev === "--tag" || prev === "tag") return n.tags ?? [];
886
+ if (prev === "assign") return n.people ?? [];
887
+ if (["pause", "resume", "limit"].includes(prev)) return n.agents ?? [];
888
+ if (prev === "brief") return n.accounts ?? [];
889
+ if (words[0] === "app" && words.length === 1) return ["ls", "why", "logs", "try", "fix", "dev"];
890
+ if (words[0] === "app" && words.length === 2) return known.apps ?? [];
891
+ if (words[0] === "completion") return ["bash", "zsh", "fish"];
892
+ return [];
893
+ }
894
+
895
+ // ---- Output for scripts and agents ----------------------------------------------------------------------------------
896
+ /** Only the chosen columns of each table in a terminal answer's data (--fields name,status). */
897
+ export function pickFields(data, fields) {
898
+ if (!data || !fields) return data;
899
+ const keep = String(fields).split(",").map((f) => f.trim().toLowerCase()).filter(Boolean);
900
+ if (!keep.length || !Array.isArray(data.tables)) return data;
901
+ 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)))) })) };
902
+ }
903
+ /** Print a terminal answer: its text, or its data with --json. A failure exits 1, so a script or an agent knows. */
904
+ function emit(result, extra = {}) {
905
+ if (asJson) say(JSON.stringify({ ...(result.data ? pickFields(result.data, fieldsArg) : { text: result.text, failed: result.isError }), ...extra }, null, 2));
906
+ else say(result.text);
907
+ if (result.isError) process.exit(1);
908
+ }
909
+ /** Print the CLI's own result: words for a person, or the object with --json. */
910
+ function report(textForPeople, data) { if (asJson) say(JSON.stringify(data, null, 2)); else if (textForPeople) say(textForPeople); }
911
+ /** Everything piped in (agent-inbox run -, script -). */
912
+ async function stdinText() {
913
+ if (process.stdin.isTTY) stop("Nothing was piped in. Pipe commands in, one per line, for example: echo 'ls unassigned' | agent-inbox run -");
914
+ const chunks = [];
915
+ for await (const c of process.stdin) chunks.push(c);
916
+ return Buffer.concat(chunks).toString("utf8");
917
+ }
918
+
525
919
  async function main() {
526
920
  switch (cmd) {
527
921
  case "login": await login(rest[0]); break;
528
922
  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;
923
+ case "logout": {
924
+ // The browser sign-in is revoked in Next too; a pasted token stays usable elsewhere until revoked in Settings.
925
+ const s = load();
926
+ 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(() => {});
927
+ rmSync(SAVED, { force: true });
928
+ 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 });
929
+ break;
930
+ }
931
+ case "mcp": await mcpServer(); break;
932
+ case "claude": await claudeSetup(rest.includes("--project")); break;
933
+ case "app": await appCommand(rest); break;
934
+ case "events": { const only = (valueOf(rest, "--only") ?? "").split(",").filter(Boolean); await events(only.length ? only : null); break; }
935
+ case "listen": await listen(valueOf(rest, "--forward"), valueOf(rest, "--events")?.split(",").filter(Boolean)); break;
936
+ 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; }
937
+ case "__complete": { const w = await completeWords(rest.filter(Boolean)).catch(() => []); say(w.join("\n")); break; }
938
+ case "whoami": {
939
+ const me = await tool("whoami");
940
+ if (me.isError) stop(me.text);
941
+ emit(me);
942
+ break;
943
+ }
944
+ case "policy": {
945
+ // What every agent may do (src/lib/policy.ts): pull writes it, check fails when the workspace has moved on from it.
946
+ const sub = rest[0] && !rest[0].startsWith("--") ? rest[0] : "show";
947
+ const file = rest[1] && !rest[1].startsWith("--") ? rest[1] : "policy.yaml";
948
+ if (sub === "show" || sub === "pull") {
949
+ const got = await tool("get_policy");
950
+ if (got.isError || !got.data?.yaml) stop(got.text || "The server did not send the policy. Try again.");
951
+ if (sub === "show") { if (asJson) report("", { yaml: got.data.yaml }); else process.stdout.write(got.data.yaml); break; }
952
+ const before = existsSync(file) ? readFileSync(file, "utf8") : null;
953
+ if (before === got.data.yaml) { report(`${file} already matches the workspace.`, { file, changed: false }); break; }
954
+ writeFileSync(file, got.data.yaml);
955
+ report(`${before === null ? "Wrote" : "Updated"} ${file}. Commit it: a pull request shows exactly what changed in what the agents may do.`, { file, changed: true });
956
+ break;
957
+ }
958
+ if (sub === "check") {
959
+ if (!existsSync(file)) stop(`There is no ${file} here. Make it with ${ME} policy pull ${file === "policy.yaml" ? "" : file}`.trim());
960
+ const got = await tool("check_policy", { file: readFileSync(file, "utf8") });
961
+ const ok = Boolean(got.data?.ok);
962
+ if (asJson) { report("", { ok, differences: got.data?.differences ?? [], problems: got.data?.problems ?? [] }); process.exit(ok ? 0 : 1); }
963
+ say(markdown && !ok ? `### What the agents may do has changed\n\n${(got.data?.differences ?? []).map((d) => `- ${d}`).join("\n")}\n\nIf it was meant, run \`${ME} policy pull\` and commit ${file}.` : got.text);
964
+ process.exit(ok ? 0 : 1);
965
+ }
966
+ stop(`Say what to do: ${ME} policy, ${ME} policy pull [file] or ${ME} policy check [file].`);
967
+ }
530
968
  case "export": {
531
969
  const { text, isError } = await tool("export_workspace");
532
970
  if (isError) stop(text);
@@ -540,6 +978,11 @@ switch (cmd) {
540
978
  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
979
  const { text, data } = folder ? await planFolder(dir) : await tool("import_workspace", read(rest[0]));
542
980
  const body = text.replace(/^Plan \w+: /, "").replace(/\n*(Nothing has changed|This token can only look)[\s\S]*$/, "").trim();
981
+ if (asJson) {
982
+ const apps = folder && data?.ok ? changedApps(folderFiles(dir), readState(dir)) : [];
983
+ report("", { ok: Boolean(data?.ok), changes: data?.changes ?? 0, plan: data?.plan ?? null, apps: apps.map((n) => `apps/${n}`), text: body });
984
+ process.exit(!data?.ok ? 1 : data.changes ? 2 : 0);
985
+ }
543
986
  if (!data?.ok) { say(markdown ? `### The workspace file has problems\n\n${fence(body)}` : body); process.exit(1); }
544
987
  const what = folder ? "folder" : "file";
545
988
  // Changed apps are not in the plan: push sends each as a draft.
@@ -563,14 +1006,16 @@ switch (cmd) {
563
1006
  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
1007
  const sent = await tool("submit_plan", { plan: data.plan });
565
1008
  if (sent.isError) stop(sent.text);
1009
+ if (asJson) { report("", { proposed: true, changes: data.changes, plan: data.plan, apps: appsSent, text: sent.text }); break; }
566
1010
  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
1011
  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
1012
  break;
569
1013
  }
570
1014
  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);
1015
+ if (!rest.length) stop(`Give a command in quotes, for example ${ME} run "ls unassigned", or pipe commands in with ${ME} run -`);
1016
+ // run -: commands piped in, one per line, as one script (one plan for every change).
1017
+ if (rest[0] === "-") { const got = await tool("run_script", { script: await stdinText() }); emit(got); break; }
1018
+ emit(await tool("terminal", { command: rest[0] }));
574
1019
  break;
575
1020
  }
576
1021
  case "tail": {
@@ -579,7 +1024,7 @@ switch (cmd) {
579
1024
  if (first.isError) { say(first.text); process.exit(1); }
580
1025
  let { body, next } = splitNext(first.text);
581
1026
  say(body);
582
- if (!next) process.exit(1);
1027
+ if (!next) break;
583
1028
  if (!process.stdout.isTTY || process.env.CI) { say(`\nTo continue: ${ME} ${next}`); break; }
584
1029
  if (process.stderr.isTTY) process.stderr.write("Following. Ctrl+C stops.\n");
585
1030
  let failed = 0;
@@ -591,7 +1036,7 @@ switch (cmd) {
591
1036
  failed = 0;
592
1037
  const got = splitNext(page.text);
593
1038
  if (got.body && got.body !== "Done.") say(got.body);
594
- if (!got.next) process.exit(1);
1039
+ if (!got.next) process.exit(0);
595
1040
  next = got.next;
596
1041
  } catch {
597
1042
  failed += 1;
@@ -600,10 +1045,11 @@ switch (cmd) {
600
1045
  }
601
1046
  }
602
1047
  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]}.`); }
1048
+ 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)`);
1049
+ let body; try { body = rest[0] === "-" ? await stdinText() : readFileSync(rest[0], "utf8"); } catch { stop(`Could not read ${rest[0]}.`); }
605
1050
  const got = await tool("run_script", { script: body });
606
1051
  const isError = got.isError;
1052
+ if (asJson && (isError || !proposing)) { emit(got); process.exit((got.data?.plan ?? null) ? 2 : 0); }
607
1053
  // The server's note to AI tools about submit_plan; the CLI says it in its own words.
608
1054
  const text = got.text.replace(/\n*Nothing has changed\. An AI tool cannot apply[^\n]*/, "");
609
1055
  if (isError) { say(text); process.exit(1); }
@@ -675,36 +1121,34 @@ Then:
675
1121
  const jobs = started.data?.jobs ?? [];
676
1122
  if (!jobs.length) { say(started.text); break; }
677
1123
  const { ok, lines } = await waitJobs(jobs);
1124
+ if (asJson) { report("", { ok, results: lines }); process.exit(ok ? 0 : 1); }
678
1125
  say(markdown ? `### ${cmd === "test" ? "Agent tests" : "Rehearsal"}: ${ok ? "pass" : "needs a look"}\n\n${lines.map((l) => `- ${l}`).join("\n")}` : lines.join("\n"));
679
1126
  process.exit(ok ? 0 : 1);
680
1127
  }
681
1128
  case "commands": {
682
1129
  // 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);
1130
+ emit(await tool("terminal", { command: "help" }));
685
1131
  break;
686
1132
  }
687
1133
  case undefined: case "--help": case "-h": say(usage()); break;
688
1134
  case "help": {
689
1135
  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);
1136
+ emit(await tool("terminal", { command: `help ${commandLine(rest)}` }));
692
1137
  break;
693
1138
  }
694
1139
  case "submit": {
695
1140
  // A plan a change made here, sent to Decisions for an admin to apply.
696
1141
  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);
1142
+ emit(await tool("submit_plan", { plan: rest[0] }));
699
1143
  break;
700
1144
  }
701
1145
  default: {
702
1146
  // 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(" ") });
1147
+ // Each word keeps its quoting: agent-inbox route test "where is my refund?" arrives as one phrase.
1148
+ const got = await tool("terminal", { command: commandLine(cmd ? [cmd, ...rest] : rest) });
704
1149
  // 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);
1150
+ const plan = (/Plan ([0-9a-f]{8})/.exec(got.text) ?? [])[1];
1151
+ 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
1152
  }
709
1153
  }
710
1154
  }
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.1.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"