@droconnell/agent-inbox-cli 0.0.0-stage → 1.5.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 +42 -2
  2. package/agent-inbox.mjs +389 -0
  3. package/package.json +24 -4
package/README.md CHANGED
@@ -1,3 +1,43 @@
1
- # Temporary Holding Version
1
+ # @droconnell/agent-inbox-cli
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The command-line tool for **Next**, the customer-support console. It keeps a workspace's setup in a file you can keep in git, shows what a changed file would do, proposes the changes for an admin to apply, and runs console terminal commands from your own computer. It never changes the workspace by itself: changes wait in **Decisions** until an admin applies them.
4
+
5
+ Needs Node 18 or later. No other dependencies.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ npm i -g @droconnell/agent-inbox-cli
11
+ ```
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 ...`.
14
+
15
+ ## Sign in
16
+
17
+ ```bash
18
+ agent-inbox login https://your-next-address
19
+ ```
20
+
21
+ Your browser opens on Next and asks you to approve the CLI. The address and the sign-in are kept on your computer, so every other command uses them.
22
+
23
+ In CI, set `AGENT_INBOX_URL` and `AGENT_INBOX_TOKEN` (a token from Settings, Terminal, AI tools) instead of signing in.
24
+
25
+ ## Use it
26
+
27
+ ```bash
28
+ agent-inbox export agent-inbox.yaml # the setup as YAML
29
+ agent-inbox diff agent-inbox.yaml # what the file would change; changes nothing
30
+ agent-inbox propose agent-inbox.yaml # send the changes to Decisions
31
+ agent-inbox ls unassigned # any console terminal command
32
+ agent-inbox help # every command
33
+ ```
34
+
35
+ ## Update
36
+
37
+ ```bash
38
+ agent-inbox update
39
+ ```
40
+
41
+ It says how to update for how you installed it: `npm i -g @droconnell/agent-inbox-cli@latest` for npm. A downloaded file replaces itself with the newest one from your Next address. Once a day, the CLI also says when your Next address offers a newer version.
42
+
43
+ The full guide is in your Next help center, under "Use the Next CLI".
@@ -0,0 +1,389 @@
1
+ #!/usr/bin/env node
2
+ // Next CLI: your workspace's setup as a file you keep in git.
3
+ // Needs Node 18 or later and nothing else. Install it with npm (npm i -g @droconnell/agent-inbox-cli) or Homebrew, or get this one
4
+ // file from your workspace: curl -fsSLO <console>/cli/agent-inbox.mjs and run it as node agent-inbox.mjs.
5
+ // The npm package (cli/ in the repository) is a copy of this file made at release: this file is the only source.
6
+ //
7
+ // agent-inbox login <console address> sign in from the browser (or set AGENT_INBOX_URL and AGENT_INBOX_TOKEN)
8
+ // agent-inbox export [file] the setup as YAML (to the file, or printed)
9
+ // agent-inbox diff <file|folder> what the file would change; changes nothing (exit 0 none, 2 some, 1 problems)
10
+ // agent-inbox propose <file|folder> send those changes to Decisions, where an admin applies or discards them
11
+ // (a folder: its Markdown, text and HTML documents, as knowledge articles)
12
+ // agent-inbox <terminal command> any console terminal command, such as agent-inbox ls unassigned
13
+ // agent-inbox run "<command>" the same, in quotes, such as "ls unassigned" or "route test 'refund?'"
14
+ // agent-inbox help <command> one terminal command with an example; agent-inbox commands lists them all
15
+ // agent-inbox script <file> [--propose] a file of terminal commands, one per line, as one plan; --propose sends
16
+ // it to Decisions (exit 0 nothing to change, 2 a plan, 1 problems)
17
+ // agent-inbox logout forget the sign-in on this computer
18
+ // agent-inbox update how to update, for how it was installed (a downloaded file updates itself)
19
+ //
20
+ // Nothing the CLI does changes the workspace by itself: changes wait in Decisions for an admin's click.
21
+ import { createHash, randomBytes } from "node:crypto";
22
+ import { createServer } from "node:http";
23
+ import { mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync, existsSync } from "node:fs";
24
+ import { homedir } from "node:os";
25
+ import { basename, dirname, isAbsolute, join, relative, sep } from "node:path";
26
+ import { spawn } from "node:child_process";
27
+ import { fileURLToPath } from "node:url";
28
+
29
+ export const VERSION = "1.5.0";
30
+ /** The npm package; its command is agent-inbox. (The name agent-inbox itself belongs to someone else on npm.) */
31
+ export const PACKAGE = "@droconnell/agent-inbox-cli";
32
+ const DIR = join(process.env.XDG_CONFIG_HOME || join(homedir(), ".config"), "agent-inbox");
33
+ const SAVED = join(DIR, "sign-in.json");
34
+ const CHECKED = join(DIR, "update-check.json");
35
+ const SELF = fileURLToPath(import.meta.url);
36
+ const real = (p) => { try { return realpathSync(p); } catch { return p; } };
37
+
38
+ /** Whether version a is newer than version b ("1.10.0" is newer than "1.9.2"). Anything unreadable is not newer. */
39
+ export function newer(a, b) {
40
+ const parts = (v) => (/^v?(\d+)\.(\d+)\.(\d+)$/.exec(String(v ?? "").trim()) ?? []).slice(1).map(Number);
41
+ const x = parts(a), y = parts(b);
42
+ if (x.length !== 3 || y.length !== 3) return false;
43
+ for (let i = 0; i < 3; i++) if (x[i] !== y[i]) return x[i] > y[i];
44
+ return false;
45
+ }
46
+
47
+ /** How the person ran it, for the help and the hints: agent-inbox when installed, node <file> when downloaded. */
48
+ export function invokedAs(script = process.argv[1] ?? "", cwd = process.cwd()) {
49
+ if (!/\.m?js$/i.test(basename(script)) || /[\\/]node_modules[\\/]/.test(script)) return "agent-inbox";
50
+ const rel = relative(cwd, script);
51
+ const shown = rel && !rel.startsWith("..") && !isAbsolute(rel) ? rel : script;
52
+ return `node ${/\s/.test(shown) ? JSON.stringify(shown) : shown}`;
53
+ }
54
+
55
+ /** How it was installed, from where this file really lives: Homebrew (its Cellar), npm (node_modules) or a download. */
56
+ export function installedBy(path) {
57
+ if (/[\\/]Cellar[\\/]/.test(path)) return "brew";
58
+ if (/[\\/]node_modules[\\/]/.test(path)) return "npm";
59
+ return "file";
60
+ }
61
+
62
+ const ME = invokedAs();
63
+ const args = process.argv.slice(2);
64
+ const flag = (n) => { const i = args.indexOf(n); return i >= 0 ? (args.splice(i, 1), true) : false; };
65
+ const markdown = flag("--markdown");
66
+ const proposing = flag("--propose");
67
+ const [cmd, ...rest] = args;
68
+
69
+ const say = (s) => process.stdout.write(s.endsWith("\n") ? s : s + "\n");
70
+ const stop = (s, code = 1) => { process.stderr.write(`agent-inbox: ${s}\n`); process.exit(code); };
71
+ const clean = (u) => { try { const x = new URL(u.includes("://") ? u : `https://${u}`); return x.origin; } catch { stop(`${u} is not a web address.`); } };
72
+ const load = () => { try { return JSON.parse(readFileSync(SAVED, "utf8")); } catch { return null; } };
73
+ const keep = (s) => { mkdirSync(DIR, { recursive: true, mode: 0o700 }); writeFileSync(SAVED, JSON.stringify(s, null, 2), { mode: 0o600 }); };
74
+
75
+ async function form(url, body) {
76
+ const r = await fetch(url, { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" }, body: new URLSearchParams(body) });
77
+ const j = await r.json().catch(() => ({}));
78
+ if (!r.ok) throw new Error(j.error_description || j.error || `the server answered ${r.status}`);
79
+ return j;
80
+ }
81
+
82
+ /** Where to work and with what: the environment (CI) first, then this computer's sign-in, renewed when it runs out. */
83
+ async function access() {
84
+ if (process.env.AGENT_INBOX_TOKEN) {
85
+ if (!process.env.AGENT_INBOX_URL) stop("AGENT_INBOX_TOKEN is set, so set AGENT_INBOX_URL to your console's address too.");
86
+ return { url: clean(process.env.AGENT_INBOX_URL), token: process.env.AGENT_INBOX_TOKEN };
87
+ }
88
+ const s = load();
89
+ if (!s) stop(`Not signed in. Run ${ME} login <your console's address>, or set AGENT_INBOX_URL and AGENT_INBOX_TOKEN.`);
90
+ if (Date.now() > s.expiresAt - 60_000) {
91
+ try {
92
+ const t = await form(`${s.url}/api/oauth/token`, { grant_type: "refresh_token", refresh_token: s.refresh, client_id: s.clientId });
93
+ Object.assign(s, { access: t.access_token, refresh: t.refresh_token, expiresAt: Date.now() + t.expires_in * 1000 });
94
+ keep(s);
95
+ } catch { stop(`Your sign-in has ended or was disconnected. Run ${ME} login again.`); }
96
+ }
97
+ notice(s.url);
98
+ return { url: s.url, token: s.access };
99
+ }
100
+
101
+ /** One MCP tool call; the server is the same one claude.ai and Cursor use. */
102
+ async function tool(name, args = {}) {
103
+ const { url, token } = await access();
104
+ let r;
105
+ try {
106
+ r = await fetch(`${url}/api/mcp`, {
107
+ method: "POST",
108
+ headers: { authorization: `Bearer ${token}`, "content-type": "application/json", accept: "application/json, text/event-stream", "user-agent": `agent-inbox-cli/${VERSION}` },
109
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } }),
110
+ });
111
+ } catch { stop(`Could not reach ${url}. Check the address and your connection.`); }
112
+ 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.`);
113
+ if (r.status === 403) stop("Only an admin of the workspace can use this.");
114
+ if (r.status === 429) stop("Too many requests just now. Wait a minute and try again.");
115
+ const raw = await r.text();
116
+ let j; try { j = JSON.parse(raw.startsWith("{") ? raw : raw.split("data: ")[1]); } catch { stop(`The server answered ${r.status}. Try again.`); }
117
+ if (j.error) stop(j.error.message);
118
+ const text = (j.result.content || []).map((c) => c.text).join("\n");
119
+ return { text, isError: !!j.result.isError, data: j.result.structuredContent };
120
+ }
121
+
122
+ // ---- Knowledge from this computer ----------------------------------------------------------------------------------
123
+ const DOCS = [".md", ".markdown", ".txt", ".html", ".htm"];
124
+ const posix = (p) => p.split(sep).join("/");
125
+ /** The same patterns the server reads: * is any name, ** any folders, a plain folder is everything in it. */
126
+ function globTest(pattern) {
127
+ const p = pattern.replace(/^\.\//, "").replace(/\/+$/, "");
128
+ const re = new RegExp(`^${p.split(/(\*\*\/?|\*|\?)/).map((x) => (x === "**/" ? "(?:.*/)?" : x === "**" ? ".*" : x === "*" ? "[^/]*" : x === "?" ? "[^/]" : x.replace(/[.+^${}()|[\]\\]/g, "\\$&"))).join("")}${/[*?]/.test(p) ? "" : "(?:/.*)?"}$`);
129
+ return (path) => re.test(path.replace(/^\.\//, ""));
130
+ }
131
+ function walk(dir, out = []) {
132
+ for (const e of readdirSync(dir, { withFileTypes: true })) {
133
+ if (e.name.startsWith(".") || e.name === "node_modules") continue;
134
+ const p = join(dir, e.name);
135
+ if (e.isDirectory()) walk(p, out); else if (DOCS.some((x) => e.name.toLowerCase().endsWith(x))) out.push(p);
136
+ }
137
+ return out;
138
+ }
139
+ /** The documents a file's knowledge section names (file: and files:), read relative to the file, by path. */
140
+ function documents(text, base) {
141
+ const files = {};
142
+ for (const m of text.matchAll(/^[\s-]*(file|files):\s*["']?([^"'#\n]+?)["']?\s*(?:#.*)?$/gm)) {
143
+ const [, kind, pattern] = m;
144
+ if (kind === "file") { const p = join(base, pattern); if (existsSync(p)) files[posix(pattern.replace(/^\.\//, ""))] = readFileSync(p, "utf8"); continue; }
145
+ const start = join(base, pattern.replace(/^\.\//, "").split(/[*?]/)[0].replace(/[^/]*$/, "") || ".");
146
+ if (!existsSync(start)) continue;
147
+ const test = globTest(pattern);
148
+ for (const p of statSync(start).isDirectory() ? walk(start) : [start]) { const rel = posix(relative(base, p)); if (test(rel)) files[rel] = readFileSync(p, "utf8"); }
149
+ }
150
+ const size = Object.values(files).reduce((n, v) => n + v.length, 0) + text.length;
151
+ if (size > 1_950_000) stop("The file and its documents come to more than 2 MB. Send the knowledge in parts (several smaller folders).");
152
+ return files;
153
+ }
154
+ /** What to send: a YAML file (with any documents it names), or a folder of documents as knowledge. */
155
+ const read = (path) => {
156
+ if (!path) stop(`Name the file or folder, for example ${ME} diff agent-inbox.yaml, or ${ME} diff ./docs`);
157
+ if (!existsSync(path)) stop(`There is nothing called ${path}.`);
158
+ if (statSync(path).isDirectory()) {
159
+ const folder = posix(relative(".", path)) || ".";
160
+ const yaml = JSON.stringify({ knowledge: [{ files: folder === "." ? "**" : folder }] });
161
+ const files = documents(`files: ${folder === "." ? "**" : folder}`, ".");
162
+ if (!Object.keys(files).length) stop(`There are no Markdown, text or HTML documents in ${path}.`);
163
+ return { yaml, files };
164
+ }
165
+ const yaml = readFileSync(path, "utf8");
166
+ const files = documents(yaml, dirname(path));
167
+ return { yaml, files }; // sent even when empty: the server then knows the CLI looked, and says what matched nothing
168
+ };
169
+ const fence = (s) => (markdown ? "```\n" + s.replace(/```/g, "'''") + "\n```" : s);
170
+
171
+ async function login(address) {
172
+ if (!address) stop(`Give your console's address, for example ${ME} login https://inbox.example.com`);
173
+ const url = clean(address);
174
+ const server = createServer();
175
+ await new Promise((ok) => server.listen(0, "127.0.0.1", ok));
176
+ const redirect = `http://127.0.0.1:${server.address().port}/callback`;
177
+ let client;
178
+ 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(); }
179
+ catch { stop(`Could not reach ${url}. Check the address.`); }
180
+ if (!client.client_id) stop(client.error_description || "That address did not accept the sign-in. Is it your Next console?");
181
+ const verifier = randomBytes(32).toString("base64url"), state = randomBytes(12).toString("base64url");
182
+ const go = new URL(`${url}/oauth/authorize`);
183
+ 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);
184
+ say(`Opening your browser to sign in and approve the CLI. If it does not open, go to:\n${go}`);
185
+ const opener = process.platform === "darwin" ? "open" : process.platform === "win32" ? "explorer" : "xdg-open";
186
+ try { spawn(opener, [go.toString()], { stdio: "ignore", detached: true }).on("error", () => {}).unref(); } catch {}
187
+ const back = await new Promise((ok) => {
188
+ const timer = setTimeout(() => ok(null), 5 * 60_000);
189
+ server.on("request", (req, res) => {
190
+ const u = new URL(req.url, redirect);
191
+ if (u.pathname !== "/callback") { res.writeHead(404).end(); return; }
192
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8" }).end(`<p style="font:16px system-ui;margin:40px">${u.searchParams.get("code") ? "Signed in. You can close this tab and go back to the terminal." : "Not connected. You can close this tab."}</p>`);
193
+ clearTimeout(timer); ok(u.searchParams);
194
+ });
195
+ });
196
+ server.close();
197
+ if (!back) stop(`Nobody approved it within 5 minutes. Run ${ME} login again.`);
198
+ if (back.get("state") !== state) stop(`The answer did not match this sign-in. Run ${ME} login again.`);
199
+ 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.");
200
+ 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));
201
+ keep({ url, clientId: client.client_id, access: t.access_token, refresh: t.refresh_token, expiresAt: Date.now() + t.expires_in * 1000, scope: t.scope });
202
+ say(`Signed in to ${url}${t.scope === "read" ? " to look only" : ""}. It shows in Settings, Terminal, AI tools, where you can disconnect it.`);
203
+ }
204
+
205
+ const USAGE = [
206
+ ["login <console address>", "sign in from the browser"],
207
+ ["export [file]", "the setup as YAML"],
208
+ ["diff <file|folder>", "what the file would change (exit 0 nothing, 2 changes, 1 problems)"],
209
+ ["propose <file|folder>", "send the changes to Decisions for an admin to apply"],
210
+ ["", "a folder's Markdown, text and HTML documents become knowledge articles;"],
211
+ ["", "in a file, knowledge entries can name file: docs/a.md or files: docs/**/*.md"],
212
+ ["<terminal command>", "any console terminal command, such as ME ls unassigned"],
213
+ ['run "<command>"', 'the same, in quotes, such as "ls unassigned --inbox Billing"'],
214
+ ["script <file> [--propose]", "commands, one per line, as one plan; --propose sends it to Decisions"],
215
+ ["test", "run the agents' tests and wait (exit 0 all pass, 1 some fail)"],
216
+ ["rehearse <file>", "rehearse the agents the file adds or changes on past conversations and wait"],
217
+ ["", "(both cost money, and need Tests and rehearsals from CI turned on)"],
218
+ ["logout", "forget this computer's sign-in"],
219
+ ["update", "how to get the newest version (a downloaded file updates itself)"],
220
+ ["help <command>", "one terminal command with an example; ME commands lists them all"],
221
+ ];
222
+ /** The usage, naming the command the way it was run, so each line can be copied as it is. */
223
+ export function usage(me = ME) {
224
+ const width = Math.max(...USAGE.map(([u]) => (u ? `${me} ${u}` : "").length)) + 3;
225
+ const lines = USAGE.map(([u, d]) => ` ${(u ? `${me} ${u}` : "").padEnd(width)}${d.replaceAll("ME ", `${me} `)}`);
226
+ return `Next CLI ${VERSION}: your workspace's setup as a file you keep in git.
227
+
228
+ ${lines.join("\n")}
229
+
230
+ In CI, set AGENT_INBOX_URL and AGENT_INBOX_TOKEN (a token from Settings, Terminal, AI tools) instead of logging in.
231
+ Add --markdown to diff for a GitHub job summary. Nothing changes until an admin applies it in Decisions.`;
232
+ }
233
+
234
+ // ---- Updates -------------------------------------------------------------------------------------------------------
235
+ /** The CLI version the server offers (GET /api/cli, no sign-in needed), or null when it cannot say. */
236
+ async function offered(url, ms = 5000) {
237
+ try {
238
+ const r = await fetch(`${url}/api/cli`, { signal: AbortSignal.timeout(ms), headers: { "user-agent": `agent-inbox-cli/${VERSION}` } });
239
+ if (!r.ok) return null;
240
+ const v = (await r.json())?.version;
241
+ return typeof v === "string" ? v : null;
242
+ } catch { return null; }
243
+ }
244
+
245
+ /** At most once a day, ask the server whether it has a newer CLI, and say so in one line as the command ends. */
246
+ function notice(url) {
247
+ if (!process.stderr.isTTY || process.env.CI || markdown || cmd === "update") return;
248
+ let last = 0;
249
+ try { last = JSON.parse(readFileSync(CHECKED, "utf8")).at ?? 0; } catch {}
250
+ if (Date.now() - last < 24 * 3600_000) return;
251
+ try { mkdirSync(DIR, { recursive: true, mode: 0o700 }); writeFileSync(CHECKED, JSON.stringify({ at: Date.now() }), { mode: 0o600 }); } catch { return; }
252
+ offered(url, 2000).then((v) => {
253
+ if (v && newer(v, VERSION)) process.once("exit", () => process.stderr.write(`agent-inbox: version ${v} is out (you have ${VERSION}). Run ${ME} update to get it.\n`));
254
+ });
255
+ }
256
+
257
+ /** What to do to update, for how this copy was installed; a downloaded file is replaced by the server's newest. */
258
+ export function updateAdvice(how, url) {
259
+ if (how === "brew") return "Installed with Homebrew. To update, run: brew upgrade agent-inbox";
260
+ if (how === "npm") return `Installed with npm. To update, run: npm i -g ${PACKAGE}@latest`;
261
+ return `Downloaded from your Next address. To update, download it again: curl -fsSLO ${url || "<your Next address>"}/cli/agent-inbox.mjs`;
262
+ }
263
+
264
+ async function update() {
265
+ const how = installedBy(real(SELF));
266
+ const url = process.env.AGENT_INBOX_URL ? clean(process.env.AGENT_INBOX_URL) : load()?.url;
267
+ const latest = url ? await offered(url) : null;
268
+ if (latest) say(newer(latest, VERSION) ? `Version ${latest} is out; you have ${VERSION}.` : `You have ${VERSION}, the newest version ${url} offers.`);
269
+ if (how !== "file") { say(updateAdvice(how, url)); return; }
270
+ if (!url) stop(`Sign in first with ${ME} login <your console's address>, so the CLI knows where to get the newest version. ${updateAdvice(how, url)}`);
271
+ if (!latest) stop(`Could not ask ${url} for the newest version. Check your connection and try again. ${updateAdvice(how, url)}`);
272
+ if (!newer(latest, VERSION)) return;
273
+ // Replace this file with the server's copy: written beside it first, checked, then moved over it in one step.
274
+ let body;
275
+ try {
276
+ const r = await fetch(`${url}/cli/agent-inbox.mjs`, { signal: AbortSignal.timeout(30_000) });
277
+ body = r.ok ? await r.text() : "";
278
+ } catch { body = ""; }
279
+ if (!body.startsWith("#!/usr/bin/env node") || !body.includes(`const VERSION = "${latest}"`)) stop(`The download from ${url} did not look right, so nothing was changed. ${updateAdvice(how, url)}`);
280
+ const next = `${SELF}.download`;
281
+ try { writeFileSync(next, body, { mode: 0o755 }); renameSync(next, SELF); }
282
+ catch { rmSync(next, { force: true }); stop(`Could not replace ${SELF}: it may belong to another user. ${updateAdvice(how, url)}`); }
283
+ say(`Updated ${relative(process.cwd(), SELF) || SELF} to ${latest}.`);
284
+ }
285
+
286
+ async function main() {
287
+ switch (cmd) {
288
+ case "login": await login(rest[0]); break;
289
+ case "update": await update(); break;
290
+ case "logout": rmSync(SAVED, { force: true }); say("Signed out on this computer. To disconnect it everywhere, revoke it in Settings, Terminal, AI tools."); break;
291
+ case "export": {
292
+ const { text, isError } = await tool("export_workspace");
293
+ if (isError) stop(text);
294
+ if (rest[0]) { writeFileSync(rest[0], text); say(`Wrote ${rest[0]}.`); } else process.stdout.write(text);
295
+ break;
296
+ }
297
+ case "diff": {
298
+ const { text, data } = await tool("import_workspace", read(rest[0]));
299
+ const body = text.replace(/^Plan \w+: /, "").replace(/\n*(Nothing has changed|This token can only look)[\s\S]*$/, "").trim();
300
+ if (!data?.ok) { say(markdown ? `### The workspace file has problems\n\n${fence(body)}` : body); process.exit(1); }
301
+ if (!data.changes) { say(markdown ? "### No changes\n\nThe workspace already matches the file." : "Nothing would change: the workspace already matches the file."); process.exit(0); }
302
+ 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 Decisions.` : body);
303
+ process.exit(2);
304
+ }
305
+ case "propose": {
306
+ const { text, data } = await tool("import_workspace", read(rest[0]));
307
+ if (!data?.ok) { say(text); process.exit(1); }
308
+ if (!data.changes) { say("Nothing to propose: the workspace already matches the file."); break; }
309
+ const sent = await tool("submit_plan", { plan: data.plan });
310
+ if (sent.isError) stop(sent.text);
311
+ say(markdown ? `### Proposed ${data.changes === 1 ? "1 change" : `${data.changes} changes`}\n\n${sent.text}` : sent.text);
312
+ break;
313
+ }
314
+ case "run": {
315
+ if (!rest.length) stop(`Give a command in quotes, for example ${ME} run "ls unassigned"`);
316
+ const { text, isError } = await tool("terminal", { command: rest.join(" ") });
317
+ say(text); if (isError) process.exit(1);
318
+ break;
319
+ }
320
+ case "script": {
321
+ if (!rest[0]) stop(`Give a file of terminal commands, one per line, for example ${ME} script onboarding.txt`);
322
+ let body; try { body = readFileSync(rest[0], "utf8"); } catch { stop(`Could not read ${rest[0]}.`); }
323
+ const got = await tool("run_script", { script: body });
324
+ const isError = got.isError;
325
+ // The server's note to AI tools about submit_plan; the CLI says it in its own words.
326
+ const text = got.text.replace(/\n*Nothing has changed\. An AI tool cannot apply[^\n]*/, "");
327
+ if (isError) { say(text); process.exit(1); }
328
+ const planRef = (/Plan ([0-9a-f]{8})/.exec(text) ?? [])[1];
329
+ if (!planRef) { say(text); break; }
330
+ if (!proposing) { say(markdown ? fence(text) : text); say("Nothing has changed. Run it again with --propose to send this plan to Decisions."); process.exit(2); }
331
+ const sent = await tool("submit_plan", { plan: planRef });
332
+ if (sent.isError) stop(sent.text);
333
+ say(markdown ? `### Proposed\n\n${fence(text)}\n\n${sent.text}` : `${text}\n\n${sent.text}`);
334
+ process.exit(2);
335
+ }
336
+ case "--version": case "-v": say(VERSION); break;
337
+ case "test": case "rehearse": {
338
+ // Start the run, then ask how it stands every few seconds until it is done (asking also moves it along).
339
+ let started;
340
+ if (cmd === "test") started = await tool("run_tests");
341
+ else {
342
+ if (!rest[0]) stop(`Name the workspace file, for example ${ME} rehearse agent-inbox.yaml`);
343
+ started = await tool("rehearse_file", { yaml: read(rest[0]).yaml });
344
+ }
345
+ if (started.isError) stop(started.text);
346
+ const jobs = started.data?.jobs ?? [];
347
+ if (!jobs.length) { say(started.text); break; }
348
+ const lines = [];
349
+ let ok = true;
350
+ for (const { job, agent } of jobs) {
351
+ const until = Date.now() + 15 * 60_000;
352
+ let s;
353
+ for (;;) {
354
+ s = await tool("check_status", { job });
355
+ if (s.data?.state !== "running") break;
356
+ if (Date.now() > until) stop(`Still running after 15 minutes: ${agent}. See Jobs in the console.`);
357
+ if (!markdown && process.stderr.isTTY) process.stderr.write(`\r${agent}: ${s.text}`.padEnd(80).slice(0, 80));
358
+ await new Promise((r) => setTimeout(r, 5000));
359
+ }
360
+ if (!markdown && process.stderr.isTTY) process.stderr.write("\r".padEnd(81) + "\r");
361
+ if (s.data?.passed === false) ok = false;
362
+ lines.push(`${agent}: ${s.text}`);
363
+ }
364
+ say(markdown ? `### ${cmd === "test" ? "Agent tests" : "Rehearsal"}: ${ok ? "pass" : "needs a look"}\n\n${lines.map((l) => `- ${l}`).join("\n")}` : lines.join("\n"));
365
+ process.exit(ok ? 0 : 1);
366
+ }
367
+ case "commands": {
368
+ // The terminal's own list: the same commands, and the same help, as the console terminal and AI tools.
369
+ const { text, isError } = await tool("terminal", { command: "help" });
370
+ say(text); if (isError) process.exit(1);
371
+ break;
372
+ }
373
+ case undefined: case "--help": case "-h": say(usage()); break;
374
+ case "help": {
375
+ if (!rest.length) { say(usage()); break; }
376
+ const { text, isError } = await tool("terminal", { command: `help ${rest.join(" ")}` });
377
+ say(text); if (isError) process.exit(1);
378
+ break;
379
+ }
380
+ default: {
381
+ // Anything else is a terminal command, as typed in the console: agent-inbox ls unassigned, agent-inbox agents.
382
+ const { text, isError } = await tool("terminal", { command: [cmd, ...rest].join(" ") });
383
+ say(text); if (isError) process.exit(1);
384
+ }
385
+ }
386
+ }
387
+
388
+ // Run when started as a command; a test can import the helpers above without running anything.
389
+ if (process.argv[1] && real(process.argv[1]) === real(SELF)) await main();
package/package.json CHANGED
@@ -1,6 +1,26 @@
1
1
  {
2
2
  "name": "@droconnell/agent-inbox-cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.5.0",
4
+ "description": "The Next CLI: a support workspace's setup as a file in git, and the console terminal from your own computer.",
5
+ "type": "module",
6
+ "bin": {
7
+ "agent-inbox": "agent-inbox.mjs"
8
+ },
9
+ "files": [
10
+ "agent-inbox.mjs",
11
+ "README.md"
12
+ ],
13
+ "engines": {
14
+ "node": ">=18"
15
+ },
16
+ "scripts": {
17
+ "prepack": "node ../scripts/cli-pack.mjs"
18
+ },
19
+ "keywords": [
20
+ "cli",
21
+ "customer support",
22
+ "setup as code",
23
+ "agent-inbox"
24
+ ],
25
+ "license": "MIT"
26
+ }