@droconnell/agent-inbox-cli 2.4.0 → 2.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +18 -0
- package/agent-inbox.mjs +411 -28
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -19,6 +19,14 @@ echo 'export PATH="$HOME/.npm-global/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc
|
|
|
19
19
|
|
|
20
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 ...`.
|
|
21
21
|
|
|
22
|
+
## Set everything up at once
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
agent-inbox init https://your-next-address
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
Signs you in, writes your setup to a folder named `support`, adds a starter `CLAUDE.md`, `.mcp.json` (so AI tools opened there get Next's tools) and the GitHub workflow that checks pull requests, makes the folder a git repository, and offers to create a private GitHub repository when `gh` is signed in. It changes nothing in your workspace, and is safe to run again.
|
|
29
|
+
|
|
22
30
|
## Sign in
|
|
23
31
|
|
|
24
32
|
```bash
|
|
@@ -58,6 +66,16 @@ agent-inbox ls unassigned # any console terminal command
|
|
|
58
66
|
agent-inbox help # every command
|
|
59
67
|
```
|
|
60
68
|
|
|
69
|
+
## Run commands from Next's answers
|
|
70
|
+
|
|
71
|
+
```bash
|
|
72
|
+
cd support && agent-inbox connect # keep it open; Ctrl+C disconnects
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
While `connect` runs, a command in the Assistant's answer in Next gets **Run on** your computer beside Copy. Your
|
|
76
|
+
computer shows what will run and asks `Run it? [y] yes [a] always [n] no` before each one; only `agent-inbox` commands
|
|
77
|
+
from a short list run, only in this folder, with no shell. Admins only.
|
|
78
|
+
|
|
61
79
|
## Update
|
|
62
80
|
|
|
63
81
|
```bash
|
package/agent-inbox.mjs
CHANGED
|
@@ -4,43 +4,49 @@
|
|
|
4
4
|
// file from your workspace: curl -fsSLO <console>/cli/agent-inbox.mjs and run it as node agent-inbox.mjs.
|
|
5
5
|
// The npm package (cli/ in the repository) is a copy of this file made at release: this file is the only source.
|
|
6
6
|
//
|
|
7
|
+
// agent-inbox init <console address> everything at once: sign in, the setup as a folder in git, Claude Code and
|
|
8
|
+
// the pull request check, ready to use (run it again any time: it skips what is done)
|
|
7
9
|
// agent-inbox login <console address> sign in from the browser (or set AGENT_INBOX_URL and AGENT_INBOX_TOKEN)
|
|
8
10
|
// agent-inbox export [file] the setup as YAML (to the file, or printed)
|
|
9
11
|
// agent-inbox pull [folder] the setup as a folder of files: workspace.yaml, agents/, knowledge/, rules/,
|
|
10
12
|
// tests/ and apps/ (the same files Settings, Your support as files shows)
|
|
11
13
|
// agent-inbox plan [folder] what the changed folder would change; changes nothing (exit 0 none, 2 some, 1 problems)
|
|
12
|
-
// agent-inbox push [folder] [--prune] send those changes to
|
|
14
|
+
// agent-inbox push [folder] [--prune] send those changes to Approvals; --prune also removes articles and tests
|
|
13
15
|
// whose files you deleted
|
|
14
16
|
// agent-inbox check [folder] for a pull request: the plan and a rehearsal of it, as markdown (exit 1 needs a look)
|
|
15
17
|
// agent-inbox ci init [folder] write the GitHub workflow that checks pull requests, proposes on merge, and
|
|
16
18
|
// opens a pull request when someone changed the setup in the console
|
|
17
19
|
// agent-inbox diff <file|folder> what the file would change; changes nothing (exit 0 none, 2 some, 1 problems)
|
|
18
|
-
// agent-inbox propose <file|folder> send those changes to
|
|
20
|
+
// agent-inbox propose <file|folder> send those changes to Approvals, where an admin applies or discards them
|
|
19
21
|
// (a folder: its Markdown, text and HTML documents, as knowledge articles)
|
|
20
22
|
// agent-inbox <terminal command> any console terminal command, such as agent-inbox ls unassigned
|
|
21
23
|
// agent-inbox run "<command>" the same, in quotes, such as "ls unassigned" or "route test 'refund?'"
|
|
22
24
|
// agent-inbox help <command> one terminal command with an example; agent-inbox commands lists them all
|
|
23
25
|
// agent-inbox script <file> [--propose] a file of terminal commands, one per line, as one plan; --propose sends
|
|
24
|
-
// it to
|
|
26
|
+
// it to Approvals (exit 0 nothing to change, 2 a plan, 1 problems)
|
|
27
|
+
// agent-inbox connect [--name "..."] in your support folder: Next's Assistant may offer to run agent-inbox commands
|
|
28
|
+
// here; each one runs only after you say yes on this computer (Ctrl+C stops it)
|
|
25
29
|
// agent-inbox logout forget the sign-in on this computer
|
|
26
30
|
// agent-inbox update how to update, for how it was installed (a downloaded file updates itself)
|
|
27
31
|
//
|
|
28
|
-
// Nothing the CLI does changes the workspace by itself: changes wait in
|
|
32
|
+
// Nothing the CLI does changes the workspace by itself: changes wait in Approvals for an admin's click.
|
|
29
33
|
import { createHash, randomBytes } from "node:crypto";
|
|
30
34
|
import { createServer } from "node:http";
|
|
31
35
|
import { mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync, existsSync } from "node:fs";
|
|
32
|
-
import { homedir } from "node:os";
|
|
33
|
-
import { basename, dirname, isAbsolute, join, relative, sep } from "node:path";
|
|
34
|
-
import { spawn } from "node:child_process";
|
|
36
|
+
import { homedir, hostname, platform, userInfo } from "node:os";
|
|
37
|
+
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
38
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
35
39
|
import { fileURLToPath } from "node:url";
|
|
36
40
|
|
|
37
|
-
export const VERSION = "2.
|
|
41
|
+
export const VERSION = "2.6.0";
|
|
38
42
|
/** The npm package; its command is agent-inbox. (The name agent-inbox itself belongs to someone else on npm.) */
|
|
39
43
|
export const PACKAGE = "@droconnell/agent-inbox-cli";
|
|
40
44
|
const DIR = join(process.env.XDG_CONFIG_HOME || join(homedir(), ".config"), "agent-inbox");
|
|
41
45
|
const SAVED = join(DIR, "sign-in.json");
|
|
42
46
|
const CHECKED = join(DIR, "update-check.json");
|
|
43
47
|
const SELF = fileURLToPath(import.meta.url);
|
|
48
|
+
/** How the CLI names itself to Next. A run in CI says so, so Next can tell a pull request check from a person typing. */
|
|
49
|
+
const UA = `agent-inbox-cli/${VERSION}${process.env.CI || process.env.GITHUB_ACTIONS ? " ci" : ""}`;
|
|
44
50
|
const real = (p) => { try { return realpathSync(p); } catch { return p; } };
|
|
45
51
|
|
|
46
52
|
/** Whether version a is newer than version b ("1.10.0" is newer than "1.9.2"). Anything unreadable is not newer. */
|
|
@@ -86,7 +92,7 @@ const urlArg = take("--url", true);
|
|
|
86
92
|
const tokenArg = take("--token", true);
|
|
87
93
|
/** The CLI's own commands. Anything else is a terminal command, sent as typed. */
|
|
88
94
|
export const OWN = new Set(["login", "logout", "update", "export", "pull", "plan", "diff", "push", "propose", "run", "tail", "script", "check", "ci", "test", "rehearse", "commands", "help", "submit",
|
|
89
|
-
"whoami", "policy", "audit", "mcp", "claude", "app", "events", "listen", "completion", "__complete", "--version", "-v", "--help", "-h"]);
|
|
95
|
+
"whoami", "policy", "audit", "mcp", "claude", "init", "connect", "app", "events", "listen", "completion", "__complete", "--version", "-v", "--help", "-h"]);
|
|
90
96
|
const first = args[0];
|
|
91
97
|
// plan, diff and run are also terminal commands: the CLI's own only for a folder or file that is there (plan, diff) or
|
|
92
98
|
// a quoted command (run "ls unassigned"); otherwise they go to the terminal as typed (diff 40 42, run onboarding).
|
|
@@ -188,7 +194,7 @@ async function tool(name, args = {}, { soft = false } = {}) {
|
|
|
188
194
|
try {
|
|
189
195
|
r = await fetch(`${url}/api/mcp`, {
|
|
190
196
|
method: "POST",
|
|
191
|
-
headers: { authorization: `Bearer ${token}`, "content-type": "application/json", accept: "application/json, text/event-stream", "user-agent":
|
|
197
|
+
headers: { authorization: `Bearer ${token}`, "content-type": "application/json", accept: "application/json, text/event-stream", "user-agent": UA },
|
|
192
198
|
body: JSON.stringify({ jsonrpc: "2.0", id: ++calls, method: "tools/call", params: { name, arguments: args } }),
|
|
193
199
|
});
|
|
194
200
|
} catch { if (soft) throw new Error("unreachable"); stop(`Could not reach ${url}. Check the address and your connection.`); }
|
|
@@ -252,7 +258,7 @@ export function checkReport({ plan, changes, rehearsal = null, skipped = null, b
|
|
|
252
258
|
if (blocked) parts.push(`### Could not rehearse\n\n${blocked}`);
|
|
253
259
|
const failed = Boolean(blocked || (rehearsal && !rehearsal.ok));
|
|
254
260
|
if (failed) parts.push("**Needs a look before merging.**");
|
|
255
|
-
else if (changes) parts.push("Merging proposes these changes in Next's **
|
|
261
|
+
else if (changes) parts.push("Merging proposes these changes in Next's **Approvals**, where an admin applies them.");
|
|
256
262
|
return { text: parts.join("\n\n") + "\n", failed };
|
|
257
263
|
}
|
|
258
264
|
|
|
@@ -268,7 +274,7 @@ export function ciWorkflow(url, folder) {
|
|
|
268
274
|
const pr = "${{ github.event.pull_request.number }}";
|
|
269
275
|
return `# Next support, written by agent-inbox ci init. The support setup lives in ${dir === "." ? "this repository" : `${dir}/`} (agent-inbox pull).
|
|
270
276
|
# Pull requests: what the change would do, and a rehearsal on past conversations and the saved tests, as one comment.
|
|
271
|
-
# Merges to main: the changes are proposed in Next's
|
|
277
|
+
# Merges to main: the changes are proposed in Next's Approvals, for an admin to apply.
|
|
272
278
|
# Nightly: changes someone made in Next's console come back as a pull request, so the two never drift apart. That
|
|
273
279
|
# includes policy.yaml, what every agent may do: a change to it (an agent now allowed to act alone) is a reviewed line.
|
|
274
280
|
# Needs the repository secret AGENT_INBOX_TOKEN: a Next personal access token set to Look and propose changes.
|
|
@@ -395,12 +401,14 @@ export const isPulled = (dir) => existsSync(join(dir, STATE)) || existsSync(join
|
|
|
395
401
|
* policy.yaml at the top, which policy pull keeps and policy check reads: it records the setup, it does not change it.
|
|
396
402
|
*/
|
|
397
403
|
export const POLICY_FILE = "policy.yaml";
|
|
404
|
+
/** Files at the top of the folder that are for the people and AI tools working in it, never part of the setup. */
|
|
405
|
+
export const HOUSE_FILES = ["CLAUDE.md", "AGENTS.md"];
|
|
398
406
|
export function folderFiles(dir) {
|
|
399
407
|
const out = {};
|
|
400
408
|
const go = (d) => {
|
|
401
409
|
for (const e of readdirSync(d, { withFileTypes: true })) {
|
|
402
410
|
if (e.name.startsWith(".") || e.name === "node_modules") continue;
|
|
403
|
-
if (d === dir && e.name === POLICY_FILE) continue;
|
|
411
|
+
if (d === dir && (e.name === POLICY_FILE || HOUSE_FILES.includes(e.name))) continue;
|
|
404
412
|
const p = join(d, e.name);
|
|
405
413
|
if (e.isDirectory()) go(p); else if (statSync(p).size <= 1_000_000) out[posix(relative(dir, p))] = readFileSync(p, "utf8");
|
|
406
414
|
}
|
|
@@ -469,7 +477,7 @@ async function pull(dir) {
|
|
|
469
477
|
}
|
|
470
478
|
const count = (n, one, many) => `${n} ${n === 1 ? one : many}`;
|
|
471
479
|
say(before ? `Brought ${dir} up to date: ${count(wrote, "file", "files")} written${removed ? `, ${count(removed, "file", "files")} removed` : ""}, ${count(wanted.size, "file", "files")} in all.` : `Wrote ${count(wanted.size, "file", "files")} to ${dir}: workspace.yaml, agents/, knowledge/, rules/, tests/ and apps/.`);
|
|
472
|
-
if (!before) say(`Change any of them, then ${ME} plan ${dir} shows what would change and ${ME} push ${dir} sends it to
|
|
480
|
+
if (!before) say(`Change any of them, then ${ME} plan ${dir} shows what would change and ${ME} push ${dir} sends it to Approvals.`);
|
|
473
481
|
}
|
|
474
482
|
|
|
475
483
|
/** Plan a pulled folder, as the server reads it; the same answer import_workspace gives for one file. */
|
|
@@ -495,7 +503,7 @@ async function login(address) {
|
|
|
495
503
|
if (tokenGiven) {
|
|
496
504
|
const token = tokenArg || (process.stdin.isTTY ? await ask("Paste a personal access token from Settings, Terminal, AI tools: ") : (await stdinText()).trim());
|
|
497
505
|
if (!token) stop("No token was given.");
|
|
498
|
-
const r = await fetch(`${url}/api/mcp`, { method: "POST", headers: { authorization: `Bearer ${token}`, "content-type": "application/json", accept: "application/json" },
|
|
506
|
+
const r = await fetch(`${url}/api/mcp`, { method: "POST", headers: { authorization: `Bearer ${token}`, "content-type": "application/json", accept: "application/json", "user-agent": UA },
|
|
499
507
|
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "whoami", arguments: {} } }) }).catch(() => null);
|
|
500
508
|
if (!r) stop(`Could not reach ${url}. Check the address.`);
|
|
501
509
|
if (r.status === 401) stop("That token was refused: it is wrong, expired or revoked.");
|
|
@@ -548,13 +556,14 @@ async function login(address) {
|
|
|
548
556
|
}
|
|
549
557
|
|
|
550
558
|
const USAGE = [
|
|
559
|
+
["init <console address> [folder]", "set everything up at once: sign in, the setup as a folder in git, Claude Code and the pull request check"],
|
|
551
560
|
["login <console address>", "sign in from the browser"],
|
|
552
561
|
["export [file]", "the setup as YAML"],
|
|
553
562
|
["pull [folder]", "the setup as a folder of files (agents/, knowledge/, rules/, tests/, apps/)"],
|
|
554
563
|
["plan [folder]", "what the changed folder would change (exit 0 nothing, 2 changes, 1 problems)"],
|
|
555
|
-
["push [folder] [--prune]", "send the folder's changes to
|
|
564
|
+
["push [folder] [--prune]", "send the folder's changes to Approvals; --prune removes deleted articles and tests"],
|
|
556
565
|
["diff <file|folder>", "what the file would change (exit 0 nothing, 2 changes, 1 problems)"],
|
|
557
|
-
["propose <file|folder>", "send the changes to
|
|
566
|
+
["propose <file|folder>", "send the changes to Approvals for an admin to apply"],
|
|
558
567
|
["", "a folder's Markdown, text and HTML documents become knowledge articles;"],
|
|
559
568
|
["", "in a file, knowledge entries can name file: docs/a.md or files: docs/**/*.md"],
|
|
560
569
|
["<terminal command>", "any console terminal command, such as ME ls unassigned"],
|
|
@@ -562,8 +571,8 @@ const USAGE = [
|
|
|
562
571
|
["check [folder] [--on 20]", "for a pull request: what the folder would change and a rehearsal of it, as markdown (exit 1 when something needs a look)"],
|
|
563
572
|
["ci init [folder] [--force]", "write a GitHub workflow: check pull requests, propose on merge, and open a pull request when the console changed"],
|
|
564
573
|
["tail [--inbox name] [--tag name] [--since 15m]", "what is happening now, then keeps following until Ctrl+C (in CI: one page, then the line to continue)"],
|
|
565
|
-
["script <file> [--propose]", "commands, one per line, as one plan; --propose sends it to
|
|
566
|
-
["submit <plan>", "send a plan a change printed to
|
|
574
|
+
["script <file> [--propose]", "commands, one per line, as one plan; --propose sends it to Approvals"],
|
|
575
|
+
["submit <plan>", "send a plan a change printed to Approvals, for an admin to apply (the CLI never applies)"],
|
|
567
576
|
["test", "run the agents' tests and wait (exit 0 all pass, 1 some fail)"],
|
|
568
577
|
["rehearse <file>", "rehearse the agents the file adds or changes on past conversations and wait"],
|
|
569
578
|
["rehearse [plan] [--on 20] [--topic refund]", "show me before it goes live: past conversations and the tests, with a plan and without"],
|
|
@@ -575,13 +584,14 @@ const USAGE = [
|
|
|
575
584
|
["policy pull [policy.yaml]", "write what every agent may do (apps, tools, limits, guards) to a file to keep in git"],
|
|
576
585
|
["policy check [policy.yaml]", "fail (exit 1) when the workspace no longer matches the file: for CI"],
|
|
577
586
|
["policy plan [policy.yaml]", "what an edited policy file would change: agents on or off, at_most, model, daily limit, apps, limits, tools, inbox ceilings"],
|
|
578
|
-
["policy push [policy.yaml]", "send those changes to
|
|
587
|
+
["policy push [policy.yaml]", "send those changes to Approvals, where an admin applies them (nothing changes from here)"],
|
|
579
588
|
["policy", "print what every agent may do"],
|
|
580
589
|
["audit [--from 2026-11-01] [--to 2026-11-30] [--area access] [--csv] [--out file]", "the audit log and how much each token was used, for a date range (the last 30 days if none): admins only"],
|
|
581
590
|
["events [--only conversation,apps]", "changes as they happen, one per line (--json: one JSON object per line), until Ctrl+C"],
|
|
582
591
|
["listen --forward <address> [--events a,b]", "Next's webhooks, signed as usual, sent to a server on this computer while it runs"],
|
|
583
592
|
["mcp", "an MCP server over stdio for any AI tool, using this computer's sign-in"],
|
|
584
593
|
["claude [--project]", "add Next to Claude Code (or write .mcp.json for this project)"],
|
|
594
|
+
["connect [--name \"Maya's MacBook\"]", "in your support folder: the Assistant may offer to run agent-inbox commands here, each after you say yes (Ctrl+C stops)"],
|
|
585
595
|
["app ls | why <app> | logs <app> [--follow]", "apps: their health, and their runs as they happen"],
|
|
586
596
|
["app try <app> <tool> [--input JSON]", "run an app's tool that only reads, on its latest version"],
|
|
587
597
|
["app fix <app> [--claude]", "its recent failures as a request to fix (--claude hands it to Claude Code here)"],
|
|
@@ -602,7 +612,7 @@ ${lines.join("\n")}
|
|
|
602
612
|
Every command takes --json (data, not words: for scripts and agents) and --fields a,b (only those columns).
|
|
603
613
|
Pipe commands in with run - or script -. Exit codes: 0 done, 1 failed or refused, 2 a plan or changes to apply.
|
|
604
614
|
In CI, set AGENT_INBOX_URL and AGENT_INBOX_TOKEN (or --url and --token) instead of logging in.
|
|
605
|
-
--markdown gives plan, push, test and rehearse as a GitHub summary. Nothing changes until an admin applies it in
|
|
615
|
+
--markdown gives plan, push, test and rehearse as a GitHub summary. Nothing changes until an admin applies it in Approvals.`;
|
|
606
616
|
}
|
|
607
617
|
|
|
608
618
|
// ---- Updates -------------------------------------------------------------------------------------------------------
|
|
@@ -687,6 +697,149 @@ async function mcpServer() {
|
|
|
687
697
|
function selfCommand() { return ME === "agent-inbox" ? { command: "agent-inbox", args: ["mcp"] } : { command: process.execPath, args: [SELF, "mcp"] }; }
|
|
688
698
|
|
|
689
699
|
/** agent-inbox claude: add Next to Claude Code (claude mcp add), or write .mcp.json for this project with --project. */
|
|
700
|
+
/** Write (or add to) the folder's .mcp.json so AI tools opened there start Next's MCP server. True when it changed. */
|
|
701
|
+
function writeMcpJson(dir = ".") {
|
|
702
|
+
const c = selfCommand();
|
|
703
|
+
const file = join(dir, ".mcp.json");
|
|
704
|
+
let cfg = {}; try { cfg = JSON.parse(readFileSync(file, "utf8")); } catch {}
|
|
705
|
+
const next = { command: c.command, args: c.args };
|
|
706
|
+
if (JSON.stringify(cfg.mcpServers?.next) === JSON.stringify(next)) return false;
|
|
707
|
+
cfg.mcpServers = { ...(cfg.mcpServers ?? {}), next };
|
|
708
|
+
writeFileSync(file, JSON.stringify(cfg, null, 2) + "\n");
|
|
709
|
+
return true;
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
/**
|
|
713
|
+
* The starter CLAUDE.md that init writes at the top of a support folder: what the folder is, how a change travels, and
|
|
714
|
+
* the house rules every AI tool working here should keep. People edit it afterwards; init never overwrites it.
|
|
715
|
+
*/
|
|
716
|
+
export function claudeMd({ workspace, url, agents = [], me = "agent-inbox" }) {
|
|
717
|
+
return `# ${workspace || "Our"} support
|
|
718
|
+
|
|
719
|
+
This folder is the setup of our support in Next (${url}): the agents, what they know, the rules and the tests.
|
|
720
|
+
It was written by \`${me} pull\`. Changing a file here changes nothing in Next until a person applies it.
|
|
721
|
+
|
|
722
|
+
## What is where
|
|
723
|
+
|
|
724
|
+
- \`workspace.yaml\`: inboxes, routing, hours and the other settings.
|
|
725
|
+
- \`agents/\`: one file per agent, with its job and instructions.${agents.length ? ` Ours: ${agents.join(", ")}.` : ""}
|
|
726
|
+
- \`knowledge/\`: one file per article the agents answer from. A new file is a new article.
|
|
727
|
+
- \`rules/\`: the rules every agent follows.
|
|
728
|
+
- \`tests/\`: questions with what a good answer must say. A new file is a new test.
|
|
729
|
+
- \`apps/\`: the small tools beside a conversation.
|
|
730
|
+
|
|
731
|
+
## How a change travels
|
|
732
|
+
|
|
733
|
+
1. Change the files.
|
|
734
|
+
2. \`${me} plan .\` shows what would change. It changes nothing.
|
|
735
|
+
3. \`${me} push .\` (or merging a pull request) sends it to Approvals in Next.
|
|
736
|
+
4. An admin presses Apply there. Nothing here can apply or undo a change.
|
|
737
|
+
|
|
738
|
+
You also have Next's tools (the MCP server named next): look things up with them instead of guessing.
|
|
739
|
+
|
|
740
|
+
## House rules
|
|
741
|
+
|
|
742
|
+
- Always show the plan before proposing anything, and say in one line why the change is worth making.
|
|
743
|
+
- Never propose a change that removes or turns something off without asking first.
|
|
744
|
+
- A change to an agent's instructions comes with a test in \`tests/\` that would have caught the problem.
|
|
745
|
+
- Write knowledge the way the other articles are written: plain words, short, one topic per article, no promises we cannot keep.
|
|
746
|
+
- Start from evidence: \`${me} gaps\` for what customers asked that the agents could not answer, and real conversations for why.
|
|
747
|
+
- Rehearsals and tests cost money. Ask before running one.
|
|
748
|
+
- Never put a customer's name, email or message into a file here.
|
|
749
|
+
`;
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
/** Run a program and wait; null when it is not installed. */
|
|
753
|
+
const sh = (cmd, a, cwd) => { const r = spawnSync(cmd, a, { cwd, encoding: "utf8", windowsHide: true }); return r.error ? null : { ok: r.status === 0, out: `${r.stdout ?? ""}${r.stderr ?? ""}`.trim() }; };
|
|
754
|
+
/** A name GitHub accepts for the repository: the workspace's name, then -support. */
|
|
755
|
+
export const repoName = (workspace) => `${String(workspace || "next").toLowerCase().normalize("NFKD").replace(/\p{M}+/gu, "").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60) || "next"}-support`;
|
|
756
|
+
/** init's words: the console's address (anything that reads as one) and the folder (anything else), in either order. */
|
|
757
|
+
export function initArgs(words, exists = existsSync) {
|
|
758
|
+
const plain = words.filter((w) => !w.startsWith("--"));
|
|
759
|
+
const address = plain.find((w) => /^https?:\/\//i.test(w) || (/^[a-z0-9.-]+\.[a-z]{2,}(:\d+)?$/i.test(w) && !exists(w)) || /^localhost(:\d+)?$/i.test(w));
|
|
760
|
+
return { address, folder: plain.find((w) => w !== address) ?? "support" };
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
/**
|
|
764
|
+
* agent-inbox init <address> [folder]: everything the guide walks through, in one go. Each step says what it is doing,
|
|
765
|
+
* skips what is already done, and never overwrites a file someone changed, so it is safe to run again. It only looks
|
|
766
|
+
* and writes files on this computer: nothing in the workspace changes.
|
|
767
|
+
*/
|
|
768
|
+
async function init(words) {
|
|
769
|
+
const { address, folder: dir } = initArgs(words);
|
|
770
|
+
const total = 6;
|
|
771
|
+
const step = (n, text) => { if (!asJson) say(`\n[${n}/${total}] ${text}`); };
|
|
772
|
+
const done = { signedIn: false, folder: dir, wrote: [], git: "skipped", github: "skipped", claude: false, next: [] };
|
|
773
|
+
|
|
774
|
+
step(1, "Signing in");
|
|
775
|
+
const saved = load();
|
|
776
|
+
const fromEnv = Boolean(process.env.AGENT_INBOX_TOKEN || tokenArg);
|
|
777
|
+
if (!fromEnv && address && saved?.url !== clean(address)) await login(address);
|
|
778
|
+
else if (!fromEnv && !saved) stop(`Give your Next address, for example ${ME} init https://inbox.example.com`);
|
|
779
|
+
const me = await tool("whoami");
|
|
780
|
+
if (me.isError || !me.data) stop(me.text || "The sign-in did not work. Run it again.");
|
|
781
|
+
done.signedIn = true;
|
|
782
|
+
const { url } = await access();
|
|
783
|
+
if (!asJson) say(` Signed in to ${me.data.workspace} as ${me.data.user}.`);
|
|
784
|
+
if (me.data.scope === "read" && !asJson) say(` This sign-in can only look. To propose changes later, run ${ME} login ${url} again.`);
|
|
785
|
+
|
|
786
|
+
step(2, `Your support as files, in ${dir}/`);
|
|
787
|
+
if (readState(dir)) { if (!asJson) say(` ${dir}/ is already here. ${ME} pull ${dir} brings it up to date.`); }
|
|
788
|
+
else await pull(dir);
|
|
789
|
+
|
|
790
|
+
step(3, "Files for Claude Code and for GitHub");
|
|
791
|
+
const wrote = (rel) => { done.wrote.push(rel); if (!asJson) say(` Wrote ${rel}`); };
|
|
792
|
+
const kept = (rel) => { if (!asJson) say(` Kept your ${rel}`); };
|
|
793
|
+
const files = folderFiles(dir);
|
|
794
|
+
const agents = [...new Set(Object.keys(files).filter((p) => p.startsWith("agents/")).map((p) => basename(p).replace(/\.[a-z]+$/i, "")))];
|
|
795
|
+
if (existsSync(join(dir, "CLAUDE.md"))) kept("CLAUDE.md"); else { writeFileSync(join(dir, "CLAUDE.md"), claudeMd({ workspace: me.data.workspace, url, agents, me: ME === "agent-inbox" ? ME : "agent-inbox" })); wrote("CLAUDE.md"); }
|
|
796
|
+
if (writeMcpJson(dir)) wrote(".mcp.json"); else kept(".mcp.json");
|
|
797
|
+
if (ME !== "agent-inbox" && !asJson) say(" (.mcp.json names this computer's copy of the CLI. Installed with npm, it works for teammates too.)");
|
|
798
|
+
const flow = join(dir, ".github", "workflows", "next-support.yml");
|
|
799
|
+
if (existsSync(flow)) kept(".github/workflows/next-support.yml"); else { mkdirSync(dirname(flow), { recursive: true }); writeFileSync(flow, ciWorkflow(url, ".")); wrote(".github/workflows/next-support.yml"); }
|
|
800
|
+
|
|
801
|
+
step(4, "Git");
|
|
802
|
+
const git = sh("git", ["--version"]);
|
|
803
|
+
if (!git?.ok) { done.git = "missing"; done.next.push("Install git (https://git-scm.com), then run this again."); if (!asJson) say(" Git is not installed here, so the folder is not a repository yet."); }
|
|
804
|
+
else if (existsSync(join(dir, ".git"))) { done.git = "there"; if (!asJson) say(" Already a repository. Commit the new files when you are ready."); }
|
|
805
|
+
else if (sh("git", ["rev-parse", "--is-inside-work-tree"], dir)?.ok) { done.git = "inside"; if (!asJson) say(` ${dir}/ is inside another repository, so it was left as it is. For the pull request check, give it a repository of its own.`); }
|
|
806
|
+
else {
|
|
807
|
+
sh("git", ["init", "-q", "-b", "main"], dir);
|
|
808
|
+
sh("git", ["add", "-A"], dir);
|
|
809
|
+
const c = sh("git", ["commit", "-q", "-m", "Our support setup, from Next"], dir);
|
|
810
|
+
done.git = c?.ok ? "committed" : "made";
|
|
811
|
+
if (!asJson) say(c?.ok ? " Made a repository and the first commit." : " Made a repository. Git needs your name before it can commit: git config --global user.name \"Your name\", and the same for user.email.");
|
|
812
|
+
}
|
|
813
|
+
|
|
814
|
+
step(5, "GitHub");
|
|
815
|
+
const hasGit = ["there", "committed", "made"].includes(done.git);
|
|
816
|
+
const remote = hasGit ? sh("git", ["remote", "get-url", "origin"], dir) : null;
|
|
817
|
+
const gh = sh("gh", ["auth", "status"]);
|
|
818
|
+
const secretLine = "gh secret set AGENT_INBOX_TOKEN";
|
|
819
|
+
if (remote?.ok) { done.github = "there"; if (!asJson) say(` Already on ${remote.out}.`); }
|
|
820
|
+
else if (!hasGit) { if (!asJson) say(" Skipped: there is no repository of its own to put there yet."); }
|
|
821
|
+
else if (gh?.ok && done.git === "committed" && process.stdin.isTTY && !asJson && !rest.includes("--no-github")) {
|
|
822
|
+
const name = repoName(me.data.workspace);
|
|
823
|
+
const yes = /^y(es)?$/i.test(await ask(` Create a private repository named ${name} on GitHub and push to it? (y/n) `));
|
|
824
|
+
if (yes) {
|
|
825
|
+
const made = sh("gh", ["repo", "create", name, "--private", "--source", ".", "--remote", "origin", "--push"], dir);
|
|
826
|
+
done.github = made?.ok ? "created" : "failed";
|
|
827
|
+
say(made?.ok ? ` Created ${name}, private, and pushed.` : ` GitHub did not create it: ${made?.out.split("\n").pop() ?? "no answer"}. Create it on github.com and push when you are ready.`);
|
|
828
|
+
} else say(" Left on this computer. Push it to a private repository when you are ready.");
|
|
829
|
+
} else {
|
|
830
|
+
if (!asJson) say(gh ? " Push this folder to a private repository on GitHub when you are ready." : " Push this folder to a private repository on GitHub when you are ready. (With GitHub's own tool, gh, installed and signed in, this step does it for you.)");
|
|
831
|
+
}
|
|
832
|
+
done.next.push(`For the pull request check: in Next, make a token set to Look and propose changes (Settings, Terminal, Plain English and AI tools), then in ${dir}/ run ${secretLine} and paste it${gh ? "" : " (or add it as a repository secret named AGENT_INBOX_TOKEN on github.com)"}. Paste it nowhere else.`);
|
|
833
|
+
|
|
834
|
+
step(6, "Claude Code");
|
|
835
|
+
done.claude = Boolean(sh("claude", ["--version"])?.ok);
|
|
836
|
+
if (!asJson) say(done.claude ? ` Claude Code is installed. Opened in ${dir}/, it has Next's tools and reads CLAUDE.md.` : " Claude Code is not installed here. Get it at https://claude.com/claude-code; this folder is ready for it.");
|
|
837
|
+
|
|
838
|
+
done.next.unshift(done.claude ? `cd ${dir}, run claude, and ask: "What needs a person in Next right now?"` : `Install Claude Code, then cd ${dir}, run claude, and ask: "What needs a person in Next right now?"`);
|
|
839
|
+
if (asJson) { report("", done); return; }
|
|
840
|
+
say(`\nDone. Nothing in ${me.data.workspace} was changed.\n\nNext:\n${done.next.map((n, i) => ` ${i + 1}. ${n}`).join("\n")}\n\n${url}/settings/terminal shows how far along you are.`);
|
|
841
|
+
}
|
|
842
|
+
|
|
690
843
|
async function claudeSetup(project) {
|
|
691
844
|
const c = selfCommand();
|
|
692
845
|
if (project) {
|
|
@@ -860,6 +1013,234 @@ async function appCommand(words) {
|
|
|
860
1013
|
}
|
|
861
1014
|
}
|
|
862
1015
|
|
|
1016
|
+
// ---- Run on your computer: agent-inbox connect ----------------------------------------------------------------------
|
|
1017
|
+
/**
|
|
1018
|
+
* The commands Next may ask this computer to run, and whether the person may choose Always for one. The same list as
|
|
1019
|
+
* RUNNABLE in src/lib/computer-commands.ts on the server (src/lib/computer-commands.test.ts checks they agree), kept
|
|
1020
|
+
* here too so this computer checks every request itself: a server that was tricked still cannot widen it. Always is
|
|
1021
|
+
* only for commands that neither change Next nor cost money.
|
|
1022
|
+
*/
|
|
1023
|
+
export const RUNNABLE = {
|
|
1024
|
+
pull: { always: true, path: "optional" },
|
|
1025
|
+
plan: { always: true, path: "optional" },
|
|
1026
|
+
"policy check": { always: true, path: "optional" },
|
|
1027
|
+
"policy pull": { always: true, path: "optional" },
|
|
1028
|
+
"policy plan": { always: true, path: "optional" },
|
|
1029
|
+
whoami: { always: true },
|
|
1030
|
+
push: { always: false, path: "optional", flags: { "--prune": "flag" } },
|
|
1031
|
+
propose: { always: false, path: "required" },
|
|
1032
|
+
"policy push": { always: false, path: "optional" },
|
|
1033
|
+
check: { always: false, path: "optional", flags: { "--on": "count" } },
|
|
1034
|
+
test: { always: false },
|
|
1035
|
+
"ci init": { always: false, path: "optional" },
|
|
1036
|
+
};
|
|
1037
|
+
|
|
1038
|
+
/** A folder or file inside the connected folder: `.`, or plain names that do not start with a dot. Never /, ~ or .. */
|
|
1039
|
+
export function insidePath(p) {
|
|
1040
|
+
if (typeof p !== "string" || p.length === 0 || p.length > 200) return false;
|
|
1041
|
+
return /^(\.|[A-Za-z0-9_][A-Za-z0-9._-]*)(\/[A-Za-z0-9_][A-Za-z0-9._-]*)*\/?$/.test(p);
|
|
1042
|
+
}
|
|
1043
|
+
|
|
1044
|
+
/**
|
|
1045
|
+
* The CLI's own words to run for a request from Next (its command's name and words), checked against RUNNABLE: such
|
|
1046
|
+
* as ["pull", "."] or ["policy", "check"]. Null for anything else, which is refused without asking.
|
|
1047
|
+
*/
|
|
1048
|
+
export function runnable(sub, args) {
|
|
1049
|
+
if (typeof sub !== "string" || !Object.hasOwn(RUNNABLE, sub) || !Array.isArray(args) || args.length > 4) return null;
|
|
1050
|
+
if (!args.every((a) => typeof a === "string")) return null;
|
|
1051
|
+
const kind = RUNNABLE[sub];
|
|
1052
|
+
let path = null;
|
|
1053
|
+
const flags = [];
|
|
1054
|
+
for (let i = 0; i < args.length; i++) {
|
|
1055
|
+
const a = args[i];
|
|
1056
|
+
if (a.startsWith("-")) {
|
|
1057
|
+
const f = kind.flags?.[a];
|
|
1058
|
+
if (!f || flags.includes(a)) return null;
|
|
1059
|
+
if (f === "count") {
|
|
1060
|
+
const n = args[i + 1];
|
|
1061
|
+
if (!n || !/^[1-9]\d?$/.test(n) || Number(n) > 30) return null;
|
|
1062
|
+
flags.push(a, n); i++;
|
|
1063
|
+
} else flags.push(a);
|
|
1064
|
+
continue;
|
|
1065
|
+
}
|
|
1066
|
+
if (!kind.path || path !== null || !insidePath(a)) return null;
|
|
1067
|
+
path = a;
|
|
1068
|
+
}
|
|
1069
|
+
if (kind.path === "required" && path === null) return null;
|
|
1070
|
+
return [...sub.split(" "), ...(path === null ? [] : [path]), ...flags];
|
|
1071
|
+
}
|
|
1072
|
+
|
|
1073
|
+
/** Text from Next shown in this terminal: no control characters, so nothing sent can move the cursor or recolour the screen. */
|
|
1074
|
+
export const plainText = (s, max = 120) => String(s ?? "").replace(/[\u0000-\u001f\u007f-\u009f\u200b-\u200f\u2028-\u202e]/g, "").slice(0, max);
|
|
1075
|
+
|
|
1076
|
+
/** Whether a path the command names stays inside the folder, following any links on the way (a link out is refused). */
|
|
1077
|
+
export function staysInside(folder, p) {
|
|
1078
|
+
const root = real(folder);
|
|
1079
|
+
let at = resolve(root, p);
|
|
1080
|
+
// The part that exists, with its links followed; what is not there yet can only be made under it.
|
|
1081
|
+
const rest = [];
|
|
1082
|
+
while (!existsSync(at) && dirname(at) !== at) { rest.unshift(basename(at)); at = dirname(at); }
|
|
1083
|
+
const whole = join(real(at), ...rest);
|
|
1084
|
+
const rel = relative(root, whole);
|
|
1085
|
+
return rel === "" || (!rel.startsWith("..") && !isAbsolute(rel));
|
|
1086
|
+
}
|
|
1087
|
+
|
|
1088
|
+
/** What this computer calls itself in Next: Maya's MacBook Pro from Mayas-MacBook-Pro, or Maya's Mac when it has no useful name. */
|
|
1089
|
+
export function computerName(host = hostname(), user = (() => { try { return userInfo().username; } catch { return ""; } })(), os = platform()) {
|
|
1090
|
+
const h = String(host ?? "").replace(/\.(local|lan|home|localdomain)$/i, "").split(".")[0];
|
|
1091
|
+
const kind = os === "darwin" ? "Mac" : os === "win32" ? "PC" : "computer";
|
|
1092
|
+
const owner = user ? user.charAt(0).toUpperCase() + user.slice(1) : "";
|
|
1093
|
+
if (!h || /^(localhost|[0-9a-f]{8,})$/i.test(h)) return owner ? `${owner}'s ${kind}` : `This ${kind}`;
|
|
1094
|
+
const m = /^([A-Za-z]+?)s-(.+)$/.exec(h);
|
|
1095
|
+
if (m && /^(macbook|imac|mac|pc|laptop|desktop|surface|thinkpad)/i.test(m[2])) return `${m[1].charAt(0).toUpperCase() + m[1].slice(1)}'s ${m[2].replace(/-/g, " ")}`;
|
|
1096
|
+
return h.replace(/-/g, " ");
|
|
1097
|
+
}
|
|
1098
|
+
|
|
1099
|
+
/** A command's outcome from how the CLI ended: 0 is done, 2 is done with a plan or changes to show, anything else a problem. */
|
|
1100
|
+
export const runEnded = (code) => (code === 0 || code === 2 ? "done" : "failed");
|
|
1101
|
+
|
|
1102
|
+
/**
|
|
1103
|
+
* agent-inbox connect: keep a line open from this computer to Next, so the Assistant can offer to run agent-inbox
|
|
1104
|
+
* commands in this support folder. Next only ever sends a command's name and words from the list above; this computer
|
|
1105
|
+
* checks them again, shows exactly what will run, where and who asked, and runs it only after you answer here (never in
|
|
1106
|
+
* the browser). It runs this CLI's own code, without a shell, in this folder only. Ctrl+C disconnects.
|
|
1107
|
+
*/
|
|
1108
|
+
async function connect(words) {
|
|
1109
|
+
const folder = real(process.cwd());
|
|
1110
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY) stop("connect asks you before every command it runs, so it needs a terminal you can type in.");
|
|
1111
|
+
if (folder === real(homedir()) || dirname(folder) === folder) stop(`Run connect in your support folder (the one ${ME} init or pull made), not in your home folder.`);
|
|
1112
|
+
if (!isPulled(folder)) stop(`This is not a support folder: it has no workspace.yaml. Run connect in the folder ${ME} init or pull made, such as support.`);
|
|
1113
|
+
const me = await tool("whoami");
|
|
1114
|
+
if (me.isError || !me.data) stop(me.text || `The sign-in did not work. Run ${ME} login again.`);
|
|
1115
|
+
const { url } = await access();
|
|
1116
|
+
const name = plainText(valueOf(words, "--name") || computerName(), 80);
|
|
1117
|
+
const shown = folder.startsWith(homedir() + sep) ? `~${folder.slice(homedir().length)}` : folder;
|
|
1118
|
+
const always = new Set();
|
|
1119
|
+
|
|
1120
|
+
/** One call on the line. Network trouble comes back as null, so the loop can wait and try again. */
|
|
1121
|
+
const line = async (method, body, search = "") => {
|
|
1122
|
+
const { url: at, token } = await access();
|
|
1123
|
+
let r;
|
|
1124
|
+
try {
|
|
1125
|
+
r = await fetch(`${at}/api/cli/computer${search}`, { method, headers: { authorization: `Bearer ${token}`, "content-type": "application/json", "user-agent": UA }, ...(body ? { body: JSON.stringify(body) } : {}), signal: AbortSignal.timeout(45_000) });
|
|
1126
|
+
} catch { return null; }
|
|
1127
|
+
if (r.status === 401) stop(`Your sign-in was refused. Run ${ME} login again, then connect.`);
|
|
1128
|
+
if (r.status === 403) stop("Only an admin of the workspace can connect a computer.");
|
|
1129
|
+
if (r.status === 404) stop(`${at} does not have Run on your computer yet. It needs a newer Next.`);
|
|
1130
|
+
if (r.status >= 500) return null;
|
|
1131
|
+
return { status: r.status, data: await r.json().catch(() => ({})) };
|
|
1132
|
+
};
|
|
1133
|
+
|
|
1134
|
+
const hello = await line("POST", { action: "connect", name, folder: shown, version: VERSION, always: [] });
|
|
1135
|
+
if (!hello) stop(`Could not reach ${url}. Check your connection and try again.`);
|
|
1136
|
+
if (hello.status !== 200 || !hello.data?.id) stop(hello.data?.error || "Next did not accept this computer. Try again.");
|
|
1137
|
+
const { id, line: lineId } = hello.data;
|
|
1138
|
+
const clock = () => new Date().toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
|
|
1139
|
+
say(`${clock()} Connected to ${new URL(url).host} as ${plainText(me.data.user)}`);
|
|
1140
|
+
say(`This computer shows in Next as "${name}", for ${folder}.\nWhen ${plainText(me.data.workspace)}'s Assistant offers to run an agent-inbox command, it asks you here first. Ctrl+C disconnects.`);
|
|
1141
|
+
|
|
1142
|
+
const rl = (await import("node:readline")).createInterface({ input: process.stdin, output: process.stdout });
|
|
1143
|
+
let child = null, leaving = false;
|
|
1144
|
+
const leave = async (why) => {
|
|
1145
|
+
if (leaving) return;
|
|
1146
|
+
leaving = true;
|
|
1147
|
+
if (child) child.kill();
|
|
1148
|
+
if (why) say(`\n${why}`);
|
|
1149
|
+
await line("POST", { action: "leave", id, line: lineId }).catch(() => {});
|
|
1150
|
+
rl.close();
|
|
1151
|
+
process.exit(0);
|
|
1152
|
+
};
|
|
1153
|
+
// Ctrl+C typed here reaches readline; a signal from elsewhere (kill, the window closing) reaches the process.
|
|
1154
|
+
rl.on("SIGINT", () => void leave("Disconnected. Next shows this computer as offline."));
|
|
1155
|
+
process.on("SIGINT", () => void leave("Disconnected. Next shows this computer as offline."));
|
|
1156
|
+
process.on("SIGTERM", () => void leave(""));
|
|
1157
|
+
process.on("SIGHUP", () => void leave(""));
|
|
1158
|
+
const question = (q) => new Promise((ok) => rl.question(q, (a) => ok(a.trim().toLowerCase())));
|
|
1159
|
+
|
|
1160
|
+
/** Tell Next how a run stands; tries a few times. False when Next refused it (the run ended there meanwhile). */
|
|
1161
|
+
const report = async (run, body) => {
|
|
1162
|
+
for (let i = 0; i < 5; i++) {
|
|
1163
|
+
const r = await line("POST", { action: "report", id, line: lineId, run: run.id, ...body });
|
|
1164
|
+
if (r) return r.status === 200;
|
|
1165
|
+
await new Promise((ok) => setTimeout(ok, 1000 * (i + 1)));
|
|
1166
|
+
}
|
|
1167
|
+
return false;
|
|
1168
|
+
};
|
|
1169
|
+
|
|
1170
|
+
/** One request: check it, show it, ask, then run this CLI with its words in this folder, and send back what it printed. */
|
|
1171
|
+
const handle = async (run) => {
|
|
1172
|
+
const argv = runnable(run.sub, run.args);
|
|
1173
|
+
const command = `agent-inbox ${argv ? argv.join(" ") : plainText(run.sub, 40)}`;
|
|
1174
|
+
// A request from before this computer reconnected says how old it is, so an earlier ask is not mistaken for a new one.
|
|
1175
|
+
const ago = Math.floor((Date.now() - Date.parse(run.askedAt)) / 60_000);
|
|
1176
|
+
const when = ago >= 1 ? ` ${ago} minute${ago === 1 ? "" : "s"} ago` : "";
|
|
1177
|
+
say(`\n${clock()} ${plainText(run.from, 40)} wants to run, asked by ${plainText(run.askedBy, 60)}${when}:\n\n ${command}\n in ${folder}\n`);
|
|
1178
|
+
// The folder or file it names comes right after the command's own words (runnable puts it there), before any option.
|
|
1179
|
+
const named = argv?.[run.sub.split(" ").length];
|
|
1180
|
+
const path = named && !named.startsWith("-") ? named : ".";
|
|
1181
|
+
if (!argv || !staysInside(folder, path)) {
|
|
1182
|
+
say("Not run: this computer only runs agent-inbox commands from its list, in this folder.");
|
|
1183
|
+
await report(run, { status: "declined", output: "This computer refused it: it only runs agent-inbox commands from its list, in the folder it connected.\n" });
|
|
1184
|
+
return;
|
|
1185
|
+
}
|
|
1186
|
+
let approved = always.has(run.sub) ? "always" : null;
|
|
1187
|
+
if (approved) say(`Running: you chose Always for ${run.sub} while connected.`);
|
|
1188
|
+
while (!approved) {
|
|
1189
|
+
const canAlways = RUNNABLE[run.sub].always;
|
|
1190
|
+
const a = await question(`Run it? [y] yes ${canAlways ? `[a] always for ${run.sub} ` : ""}[n] no › `);
|
|
1191
|
+
if (a === "y" || a === "yes") approved = "once";
|
|
1192
|
+
else if (canAlways && (a === "a" || a === "always")) { approved = "always"; always.add(run.sub); }
|
|
1193
|
+
else if (a === "n" || a === "no") break;
|
|
1194
|
+
else say(canAlways ? "Type y, a or n, then Enter." : "Type y or n, then Enter.");
|
|
1195
|
+
}
|
|
1196
|
+
if (!approved) { say("Not run."); await report(run, { status: "declined" }); return; }
|
|
1197
|
+
if (!(await report(run, { status: "running", approved }))) { say("Not run: the request ended in Next before you answered (after 10 minutes, or it was disconnected). Ask again from Next."); return; }
|
|
1198
|
+
const started = Date.now();
|
|
1199
|
+
let pending = "";
|
|
1200
|
+
const flush = async () => { if (!pending) return; const chunk = pending; pending = ""; await report(run, { status: "running", output: chunk }); };
|
|
1201
|
+
const timer = setInterval(() => void flush(), 1000);
|
|
1202
|
+
const code = await new Promise((done) => {
|
|
1203
|
+
// This CLI's own code with the checked words, in this folder, without a shell: nothing can be added to the line.
|
|
1204
|
+
child = spawn(process.execPath, [SELF, ...argv], { cwd: folder, shell: false, windowsHide: true, stdio: ["ignore", "pipe", "pipe"], env: { ...process.env, NO_COLOR: "1" } });
|
|
1205
|
+
const take = (b) => { const s = b.toString("utf8"); process.stdout.write(s); pending += s; };
|
|
1206
|
+
child.stdout.on("data", take); child.stderr.on("data", take);
|
|
1207
|
+
const limit = setTimeout(() => { pending += "\nStopped after 20 minutes.\n"; child?.kill(); }, 20 * 60_000);
|
|
1208
|
+
child.on("error", () => { clearTimeout(limit); done(-1); });
|
|
1209
|
+
child.on("close", (c) => { clearTimeout(limit); done(c ?? -1); });
|
|
1210
|
+
});
|
|
1211
|
+
child = null;
|
|
1212
|
+
clearInterval(timer);
|
|
1213
|
+
const ended = runEnded(code);
|
|
1214
|
+
const output = pending; pending = "";
|
|
1215
|
+
await report(run, { status: ended, exitCode: code, output });
|
|
1216
|
+
say(`${ended === "done" ? "Done" : "Stopped with a problem"} in ${Math.max(1, Math.round((Date.now() - started) / 1000))} s. Next shows the result.`);
|
|
1217
|
+
};
|
|
1218
|
+
|
|
1219
|
+
// The line: ask for work again and again (each ask waits up to 25 seconds). Requests are handled one at a time.
|
|
1220
|
+
const queue = [];
|
|
1221
|
+
let working = false;
|
|
1222
|
+
const work = async () => {
|
|
1223
|
+
if (working) return;
|
|
1224
|
+
working = true;
|
|
1225
|
+
while (queue.length) await handle(queue.shift()).catch(() => say("That run could not finish. Next shows it as stopped."));
|
|
1226
|
+
working = false;
|
|
1227
|
+
};
|
|
1228
|
+
let lostSince = 0;
|
|
1229
|
+
for (;;) {
|
|
1230
|
+
const got = await line("GET", null, `?id=${id}&line=${lineId}&wait=25000&always=${encodeURIComponent([...always].join(","))}`);
|
|
1231
|
+
if (!got || got.status !== 200) {
|
|
1232
|
+
if (!lostSince) { lostSince = Date.now(); say(`${clock()} Lost the line to Next. Trying again…`); }
|
|
1233
|
+
if (Date.now() - lostSince > 10 * 60_000) await leave("Could not reach Next for 10 minutes, so this computer disconnected. Run connect again.");
|
|
1234
|
+
await new Promise((ok) => setTimeout(ok, 5000));
|
|
1235
|
+
continue;
|
|
1236
|
+
}
|
|
1237
|
+
if (lostSince) { lostSince = 0; say(`${clock()} Back in touch with Next.`); }
|
|
1238
|
+
if (got.data?.gone) await leave("Disconnected in Next (Settings, Terminal). Run connect again to reconnect.");
|
|
1239
|
+
if (got.data?.replaced) { leaving = true; say("\nconnect was started again for this folder, so this one stopped."); rl.close(); process.exit(0); }
|
|
1240
|
+
if (got.data?.run) { queue.push(got.data.run); void work(); }
|
|
1241
|
+
}
|
|
1242
|
+
}
|
|
1243
|
+
|
|
863
1244
|
// ---- Shell completion ----------------------------------------------------------------------------------------------
|
|
864
1245
|
export function completionScript(shell, me = "agent-inbox") {
|
|
865
1246
|
if (shell === "bash") return `# ${me} completion for bash: add to ~/.bashrc: eval "$(${me} completion bash)"
|
|
@@ -935,6 +1316,8 @@ switch (cmd) {
|
|
|
935
1316
|
}
|
|
936
1317
|
case "mcp": await mcpServer(); break;
|
|
937
1318
|
case "claude": await claudeSetup(rest.includes("--project")); break;
|
|
1319
|
+
case "init": await init(rest); break;
|
|
1320
|
+
case "connect": await connect(rest); break;
|
|
938
1321
|
case "app": await appCommand(rest); break;
|
|
939
1322
|
case "events": { const only = (valueOf(rest, "--only") ?? "").split(",").filter(Boolean); await events(only.length ? only : null); break; }
|
|
940
1323
|
case "listen": await listen(valueOf(rest, "--forward"), valueOf(rest, "--events")?.split(",").filter(Boolean)); break;
|
|
@@ -970,7 +1353,7 @@ switch (cmd) {
|
|
|
970
1353
|
}
|
|
971
1354
|
if (sub === "plan" || sub === "push") {
|
|
972
1355
|
// Edited by hand, the file becomes a plan to make the workspace match it (src/lib/policy.ts, policyToSetup); push
|
|
973
|
-
// sends it to
|
|
1356
|
+
// sends it to Approvals, where an admin applies it. Nothing changes from here.
|
|
974
1357
|
if (!existsSync(file)) stop(`There is no ${file} here. Make it with ${ME} policy pull${file === "policy.yaml" ? "" : ` ${file}`}, change it, then ${ME} policy ${sub}.`);
|
|
975
1358
|
const got = await tool("plan_policy", { file: readFileSync(file, "utf8") });
|
|
976
1359
|
const d = got.data ?? {};
|
|
@@ -980,7 +1363,7 @@ switch (cmd) {
|
|
|
980
1363
|
if (sub === "plan") {
|
|
981
1364
|
const body = got.text.replace(/\n*(Nothing has changed|This token can only look)[\s\S]*?(?=\n\nNot changed by the file|$)/, "").trim();
|
|
982
1365
|
if (asJson) { report("", { ok: true, changes: d.changes, plan: d.plan, notes: d.notes ?? [], text: body }); process.exit(2); }
|
|
983
|
-
say(markdown ? `### ${d.changes === 1 ? "1 change" : `${d.changes} changes`} to what the agents may do\n\n${fence(body)}\n\nMerging proposes these; an admin applies them in
|
|
1366
|
+
say(markdown ? `### ${d.changes === 1 ? "1 change" : `${d.changes} changes`} to what the agents may do\n\n${fence(body)}\n\nMerging proposes these; an admin applies them in Approvals.` : `${body}\n\n${ME} policy push${file === "policy.yaml" ? "" : ` ${file}`} sends this to Approvals, where an admin applies it.`);
|
|
984
1367
|
process.exit(2);
|
|
985
1368
|
}
|
|
986
1369
|
const sent = await tool("submit_plan", { plan: d.plan });
|
|
@@ -1043,7 +1426,7 @@ switch (cmd) {
|
|
|
1043
1426
|
// A folder's notes (articles from a website, files with no match) are worth seeing even when nothing changes.
|
|
1044
1427
|
const notes = folder ? text.split("\n").filter((l) => l.trim() && !/^Nothing would change/.test(l)).join("\n") : "";
|
|
1045
1428
|
if (!data.changes) { say(markdown ? `### No changes\n\nThe workspace already matches the ${what}.${notes ? `\n\n${notes}` : ""}` : `No changes: the workspace already matches the ${what}.${notes ? `\n${notes}` : ""}`); process.exit(0); }
|
|
1046
|
-
say(markdown ? `### ${data.changes === 1 ? "1 change" : `${data.changes} changes`} to the workspace\n\n${fence(body)}\n\nMerging proposes these; an admin applies them in
|
|
1429
|
+
say(markdown ? `### ${data.changes === 1 ? "1 change" : `${data.changes} changes`} to the workspace\n\n${fence(body)}\n\nMerging proposes these; an admin applies them in Approvals.` : body);
|
|
1047
1430
|
process.exit(2);
|
|
1048
1431
|
}
|
|
1049
1432
|
case "push": case "propose": {
|
|
@@ -1060,7 +1443,7 @@ switch (cmd) {
|
|
|
1060
1443
|
if (sent.isError) stop(sent.text);
|
|
1061
1444
|
if (asJson) { report("", { proposed: true, changes: data.changes, plan: data.plan, apps: appsSent, text: sent.text }); break; }
|
|
1062
1445
|
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}`);
|
|
1063
|
-
if (folder) say(`Once it is applied, ${ME} pull ${dir} brings the folder up to date. Undo it in the console (
|
|
1446
|
+
if (folder) say(`Once it is applied, ${ME} pull ${dir} brings the folder up to date. Undo it in the console (Approvals, or undo in the terminal).`);
|
|
1064
1447
|
break;
|
|
1065
1448
|
}
|
|
1066
1449
|
case "run": {
|
|
@@ -1107,7 +1490,7 @@ switch (cmd) {
|
|
|
1107
1490
|
if (isError) { say(text); process.exit(1); }
|
|
1108
1491
|
const planRef = (/Plan ([0-9a-f]{8})/.exec(text) ?? [])[1];
|
|
1109
1492
|
if (!planRef) { say(text); break; }
|
|
1110
|
-
if (!proposing) { say(markdown ? fence(text) : text); say("Nothing has changed. Run it again with --propose to send this plan to
|
|
1493
|
+
if (!proposing) { say(markdown ? fence(text) : text); say("Nothing has changed. Run it again with --propose to send this plan to Approvals."); process.exit(2); }
|
|
1111
1494
|
const sent = await tool("submit_plan", { plan: planRef });
|
|
1112
1495
|
if (sent.isError) stop(sent.text);
|
|
1113
1496
|
say(markdown ? `### Proposed\n\n${fence(text)}\n\n${sent.text}` : `${text}\n\n${sent.text}`);
|
|
@@ -1198,7 +1581,7 @@ Then:
|
|
|
1198
1581
|
break;
|
|
1199
1582
|
}
|
|
1200
1583
|
case "submit": {
|
|
1201
|
-
// A plan a change made here, sent to
|
|
1584
|
+
// A plan a change made here, sent to Approvals for an admin to apply.
|
|
1202
1585
|
if (!rest[0]) stop(`Give the plan to send, for example ${ME} submit 1a2b3c4d (the reference a change printed).`);
|
|
1203
1586
|
emit(await tool("submit_plan", { plan: rest[0] }));
|
|
1204
1587
|
break;
|
|
@@ -1209,7 +1592,7 @@ Then:
|
|
|
1209
1592
|
const got = await tool("terminal", { command: commandLine(cmd ? [cmd, ...rest] : rest) });
|
|
1210
1593
|
// 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.
|
|
1211
1594
|
const plan = (/Plan ([0-9a-f]{8})/.exec(got.text) ?? [])[1];
|
|
1212
|
-
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
|
|
1595
|
+
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 Approvals for an admin with ${ME} submit ${plan}.`) } : got);
|
|
1213
1596
|
}
|
|
1214
1597
|
}
|
|
1215
1598
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@droconnell/agent-inbox-cli",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.6.0",
|
|
4
4
|
"description": "The Next CLI, built for agents: JSON on every command, an MCP server for any AI tool, live events, apps and webhooks from the terminal, and a support workspace's setup as files in git.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|