@droconnell/agent-inbox-cli 2.10.0 → 2.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -10,14 +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`. On a Mac or Linux, if npm says `EACCES: permission denied`, give npm a folder of your own once, then install again without `sudo`:
13
+ That installs the command `agent-inbox` (`agent-inbox-cli` works too). 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
14
 
15
15
  ```bash
16
16
  mkdir -p ~/.npm-global && npm config set prefix ~/.npm-global
17
17
  echo 'export PATH="$HOME/.npm-global/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc
18
18
  ```
19
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 ...`.
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` (in Windows PowerShell, `curl.exe`), then `node agent-inbox.mjs ...`.
21
21
 
22
22
  ## Set everything up at once
23
23
 
package/agent-inbox.mjs CHANGED
@@ -29,7 +29,8 @@
29
29
  // agent-inbox script <file> [--propose] a file of terminal commands, one per line, as one plan; --propose sends
30
30
  // it to Approvals (exit 0 nothing to change, 2 a plan, 1 problems)
31
31
  // agent-inbox connect [--name "..."] in your support folder: Next's Assistant may offer to run agent-inbox commands
32
- // here; each one runs only after you say yes on this computer (Ctrl+C stops it)
32
+ // here, and Knowledge may ask it to check help steps in your product in a
33
+ // browser; each runs only after you say yes on this computer (Ctrl+C stops it)
33
34
  // agent-inbox logout forget the sign-in on this computer
34
35
  // agent-inbox update how to update, for how it was installed (a downloaded file updates itself)
35
36
  //
@@ -40,9 +41,10 @@ import { mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync,
40
41
  import { homedir, hostname, platform, userInfo } from "node:os";
41
42
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
42
43
  import { spawn, spawnSync } from "node:child_process";
43
- import { fileURLToPath } from "node:url";
44
+ import { fileURLToPath, pathToFileURL } from "node:url";
45
+ import { createRequire } from "node:module";
44
46
 
45
- export const VERSION = "2.10.0";
47
+ export const VERSION = "2.11.1";
46
48
  /** The npm package; its command is agent-inbox. (The name agent-inbox itself belongs to someone else on npm.) */
47
49
  export const PACKAGE = "@droconnell/agent-inbox-cli";
48
50
  const DIR = join(process.env.XDG_CONFIG_HOME || join(homedir(), ".config"), "agent-inbox");
@@ -96,7 +98,7 @@ const urlArg = take("--url", true);
96
98
  const tokenArg = take("--token", true);
97
99
  /** The CLI's own commands. Anything else is a terminal command, sent as typed. */
98
100
  export const OWN = new Set(["login", "logout", "update", "export", "pull", "plan", "diff", "push", "propose", "run", "tail", "script", "check", "ci", "test", "rehearse", "commands", "help", "submit", "dev",
99
- "whoami", "policy", "audit", "mcp", "claude", "init", "connect", "app", "events", "listen", "completion", "__complete", "--version", "-v", "--help", "-h"]);
101
+ "whoami", "policy", "audit", "mcp", "claude", "init", "connect", "app", "events", "listen", "completion", "__complete", "version", "--version", "-v", "--help", "-h"]);
100
102
  const first = args[0];
101
103
  // plan, diff and run are also terminal commands: the CLI's own only for a folder or file that is there (plan, diff) or
102
104
  // a quoted command (run "ls unassigned"); otherwise they go to the terminal as typed (diff 40 42, run onboarding).
@@ -1038,6 +1040,7 @@ const USAGE = [
1038
1040
  ["completion bash|zsh|fish", "Tab completion of commands and real names for your shell"],
1039
1041
  ["logout", "forget this computer's sign-in (and revoke a browser sign-in in Next)"],
1040
1042
  ["update", "how to get the newest version (a downloaded file updates itself)"],
1043
+ ["version", "which version you have (also --version)"],
1041
1044
  ["help <command>", "one terminal command with an example; ME commands lists them all"],
1042
1045
  ];
1043
1046
  /** The usage, naming the command the way it was run, so each line can be copied as it is. */
@@ -1537,6 +1540,159 @@ export function runnableSequence(steps) {
1537
1540
  return out;
1538
1541
  }
1539
1542
 
1543
+ // ---- Check steps in the product (prd/step-checks.md): a request of its own kind, never a command ---------------------
1544
+ /**
1545
+ * Next may also ask this computer to check its help articles' steps in the product: open each listed page in a real
1546
+ * browser and look for each label the articles name. The same rules as validStepCheck in src/lib/step-checks.ts
1547
+ * (src/lib/step-checks.test.ts checks they agree), checked here again, so only pages on the product's own site are ever
1548
+ * opened, however the request was made.
1549
+ */
1550
+ export const STEP_PAGES = 20;
1551
+ export const STEP_LABELS = 30;
1552
+ const LOCAL_HOST = /^(localhost|127\.0\.0\.1|\[::1\])$/;
1553
+ const cleanText = (s) => String(s).replace(/[\u0000-\u001f\u007f-\u009f\u200b-\u200f\u2028-\u202e]/g, " ").replace(/\s+/g, " ").trim();
1554
+
1555
+ /** The product's address made whole: https (http only on this computer itself), no sign-in in it, no #part. Or null. */
1556
+ export function productAddress(raw) {
1557
+ if (typeof raw !== "string") return null;
1558
+ const text = raw.trim();
1559
+ if (!text || text.length > 300 || /\s/.test(text)) return null;
1560
+ let u;
1561
+ try { u = new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(text) ? text : `https://${text}`); } catch { return null; }
1562
+ if (u.username || u.password || (!u.hostname.includes(".") && !LOCAL_HOST.test(u.hostname))) return null;
1563
+ if (u.protocol !== "https:" && !(u.protocol === "http:" && LOCAL_HOST.test(u.hostname))) return null;
1564
+ u.hash = "";
1565
+ return u.toString();
1566
+ }
1567
+
1568
+ /** Whether an address is on the product's own site: the same host or one under it (www. aside), same port, https when it is. */
1569
+ export function onProductSite(url, product) {
1570
+ if (typeof url !== "string" || url.length > 500) return false;
1571
+ let u, p;
1572
+ try { u = new URL(url); p = new URL(product); } catch { return false; }
1573
+ if (u.username || u.password || (u.protocol !== "https:" && u.protocol !== "http:")) return false;
1574
+ if (p.protocol === "https:" && u.protocol !== "https:") return false;
1575
+ if (u.protocol === "http:" && !LOCAL_HOST.test(u.hostname)) return false;
1576
+ const site = p.hostname.toLowerCase().replace(/^www\./, ""), host = u.hostname.toLowerCase().replace(/^www\./, "");
1577
+ return (host === site || host.endsWith(`.${site}`)) && u.port === p.port;
1578
+ }
1579
+
1580
+ /** A step check from Next, as this computer accepts it, or null (refused without asking). */
1581
+ export function stepCheckRequest(x) {
1582
+ if (!x || typeof x !== "object") return null;
1583
+ const { product, pages } = x;
1584
+ const name = typeof product?.name === "string" ? cleanText(product.name).slice(0, 80) : "";
1585
+ const url = productAddress(product?.url);
1586
+ if (!name || !url || url !== product?.url) return null;
1587
+ if (!Array.isArray(pages) || pages.length < 1 || pages.length > STEP_PAGES) return null;
1588
+ const out = [];
1589
+ for (const p of pages) {
1590
+ if (!p || typeof p !== "object" || !onProductSite(p.url, url)) return null;
1591
+ const { labels } = p;
1592
+ if (!Array.isArray(labels) || labels.length < 1 || labels.length > STEP_LABELS) return null;
1593
+ if (!labels.every((l) => typeof l === "string" && l.length >= 2 && l.length <= 60 && cleanText(l) === l)) return null;
1594
+ out.push({ url: p.url, labels: [...labels] });
1595
+ }
1596
+ return { product: { name, url }, pages: out };
1597
+ }
1598
+
1599
+ /** The browser profile the check uses: its own, in this CLI's config folder. It never leaves this computer. */
1600
+ export const BROWSER_PROFILE = join(DIR, "browser");
1601
+ /** The one command that installs what the check needs. */
1602
+ export const PLAYWRIGHT_INSTALL = "npm install -g playwright && npx playwright install chromium";
1603
+
1604
+ /** Where Playwright is on this computer: in the support folder, beside this CLI, or installed globally. Null if nowhere. */
1605
+ export function findPlaywright(folder, globalRoot = npmGlobalRoot) {
1606
+ for (const from of [join(folder, "package.json"), SELF]) {
1607
+ try { return createRequire(from).resolve("playwright"); } catch { /* not there */ }
1608
+ }
1609
+ const root = globalRoot();
1610
+ if (root) { try { return createRequire(join(dirname(root), "package.json")).resolve("playwright"); } catch { /* not there */ } }
1611
+ return null;
1612
+ }
1613
+ function npmGlobalRoot() {
1614
+ const r = spawnSync(platform() === "win32" ? "npm.cmd" : "npm", ["root", "-g"], { encoding: "utf8", timeout: 15_000, shell: false, windowsHide: true });
1615
+ return r.status === 0 ? r.stdout.trim() : "";
1616
+ }
1617
+
1618
+ /** Whether the page shows a label: as a button, link, tab, menu item or field label, or as visible text. */
1619
+ async function pageShows(page, label) {
1620
+ const ways = [
1621
+ page.getByRole("button", { name: label }), page.getByRole("link", { name: label }), page.getByRole("tab", { name: label }),
1622
+ page.getByRole("menuitem", { name: label }), page.getByLabel(label), page.getByText(label),
1623
+ ];
1624
+ for (const way of ways) {
1625
+ try {
1626
+ const n = Math.min(await way.count(), 5);
1627
+ for (let i = 0; i < n; i++) if (await way.nth(i).isVisible()) return true;
1628
+ } catch { /* that way does not apply here */ }
1629
+ }
1630
+ return false;
1631
+ }
1632
+
1633
+ /** The labels a page does show (buttons, links, tabs, field labels, headings): what a fix can use instead. */
1634
+ const NEARBY = () => {
1635
+ const seen = new Set(), out = [];
1636
+ for (const el of document.querySelectorAll("button, a, [role=button], [role=tab], [role=menuitem], label, h1, h2, h3, summary")) {
1637
+ if (!el.getClientRects().length) continue;
1638
+ const text = (el.innerText || el.getAttribute("aria-label") || "").replace(/\s+/g, " ").trim();
1639
+ if (text.length < 2 || text.length > 60 || seen.has(text.toLowerCase())) continue;
1640
+ seen.add(text.toLowerCase());
1641
+ out.push(text);
1642
+ if (out.length >= 80) break;
1643
+ }
1644
+ return out;
1645
+ };
1646
+
1647
+ /**
1648
+ * Visit each page of a step check in a real browser, with its own profile, and look for each label. One page at a
1649
+ * time, a pause between pages, only pages on the product's own site (a page that sends the browser elsewhere, such as
1650
+ * to a sign-in on another site, is reported and not screenshot). `onPage` gets each page's result and a JPEG of what
1651
+ * was on screen. Pages not reached by `until`, or once `stopped()` says so, are reported as stopped.
1652
+ */
1653
+ export async function checkPages(chromium, check, { profile = BROWSER_PROFILE, headless = false, pauseMs = 1500, until = Date.now() + 10 * 60_000, stopped = () => false, onBrowser = () => {}, signIn = async () => true, onPage = async () => {} } = {}) {
1654
+ const fresh = !existsSync(profile);
1655
+ mkdirSync(profile, { recursive: true, mode: 0o700 });
1656
+ const browser = await chromium.launchPersistentContext(profile, { headless, viewport: { width: 1280, height: 860 } });
1657
+ onBrowser(browser);
1658
+ const results = [];
1659
+ try {
1660
+ const page = browser.pages()[0] ?? await browser.newPage();
1661
+ // The first time, there is no sign-in in this profile yet: open the product and let the person sign in.
1662
+ let go = true;
1663
+ if (fresh) {
1664
+ await page.goto(check.product.url, { waitUntil: "domcontentloaded", timeout: 30_000 }).catch(() => {});
1665
+ go = await signIn();
1666
+ }
1667
+ for (let i = 0; i < check.pages.length; i++) {
1668
+ const want = check.pages[i];
1669
+ if (!go || stopped() || Date.now() > until) { results.push({ url: want.url, found: [], missing: [], problem: "stopped" }); continue; }
1670
+ if (i > 0) await new Promise((ok) => setTimeout(ok, pauseMs));
1671
+ let result, shot = null;
1672
+ try {
1673
+ await page.goto(want.url, { waitUntil: "domcontentloaded", timeout: 30_000 });
1674
+ await page.waitForLoadState("networkidle", { timeout: 5_000 }).catch(() => {});
1675
+ const at = page.url();
1676
+ if (!onProductSite(at, check.product.url)) result = { url: want.url, at, found: [], missing: [], problem: "off_site" };
1677
+ else {
1678
+ const found = [], missing = [];
1679
+ for (const label of want.labels) (await pageShows(page, label) ? found : missing).push(label);
1680
+ const nearby = await page.evaluate(NEARBY).catch(() => []);
1681
+ shot = await page.screenshot({ type: "jpeg", quality: 60 }).catch(() => null);
1682
+ result = { url: want.url, ...(at !== want.url ? { at } : {}), found, missing, nearby };
1683
+ }
1684
+ } catch {
1685
+ result = { url: want.url, found: [], missing: [], problem: "not_loaded" };
1686
+ }
1687
+ results.push(result);
1688
+ await onPage(i, result, shot);
1689
+ }
1690
+ } finally {
1691
+ await browser.close().catch(() => {});
1692
+ }
1693
+ return results;
1694
+ }
1695
+
1540
1696
  /** Text from Next shown in this terminal: no control characters, so nothing sent can move the cursor or recolour the screen. */
1541
1697
  export const plainText = (s, max = 120) => String(s ?? "").replace(/[\u0000-\u001f\u007f-\u009f\u200b-\u200f\u2028-\u202e]/g, "").slice(0, max);
1542
1698
 
@@ -1607,11 +1763,14 @@ async function connect(words) {
1607
1763
  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.`);
1608
1764
 
1609
1765
  const rl = (await import("node:readline")).createInterface({ input: process.stdin, output: process.stdout });
1610
- let child = null, leaving = false;
1766
+ // A step check's browser, and what to tell Next if Ctrl+C stops it part way.
1767
+ let child = null, browser = null, onLeave = null, leaving = false;
1611
1768
  const leave = async (why) => {
1612
1769
  if (leaving) return;
1613
1770
  leaving = true;
1614
1771
  if (child) child.kill();
1772
+ if (onLeave) await onLeave().catch(() => {});
1773
+ if (browser) await browser.close().catch(() => {});
1615
1774
  if (why) say(`\n${why}`);
1616
1775
  await line("POST", { action: "leave", id, line: lineId }).catch(() => {});
1617
1776
  rl.close();
@@ -1637,8 +1796,89 @@ async function connect(words) {
1637
1796
  /** The folder or file a command's words name (it comes right after the command's own words, before any option), or "." */
1638
1797
  const namedPath = (sub, argv) => { const named = argv[sub.split(" ").length]; return named && !named.startsWith("-") ? named : "."; };
1639
1798
 
1799
+ /**
1800
+ * A step check (prd/step-checks.md): not a command. Shows the product, each page and its labels, and asks; then opens
1801
+ * a real browser with its own profile and looks for each label, one page at a time, sending each page's result and
1802
+ * screenshot to Next as it goes. Needs Playwright on this computer, and stops after 10 minutes or at Ctrl+C.
1803
+ */
1804
+ const checkSteps = async (run) => {
1805
+ const check = stepCheckRequest(run.check);
1806
+ const ago = Math.floor((Date.now() - Date.parse(run.askedAt)) / 60_000);
1807
+ const when = ago >= 1 ? ` ${ago} minute${ago === 1 ? "" : "s"} ago` : "";
1808
+ if (!check) {
1809
+ say(`\n${clock()} ${plainText(run.from, 40)} sent a step check this computer does not accept. Not checked: it only opens pages on the product's own site, at most ${STEP_PAGES}.`);
1810
+ await report(run, { status: "declined", output: `This computer refused it: it only checks pages on the product's own site, at most ${STEP_PAGES}.\n` });
1811
+ return;
1812
+ }
1813
+ const product = plainText(check.product.name, 80), host = new URL(check.product.url).host;
1814
+ const short = (u) => plainText(u.replace(/^https?:\/\//, "").replace(/\/$/, ""), 100);
1815
+ const profile = BROWSER_PROFILE.startsWith(homedir() + sep) ? `~${BROWSER_PROFILE.slice(homedir().length)}` : BROWSER_PROFILE;
1816
+ const list = check.pages.map((p, i) => ` ${i + 1}. ${short(p.url)}\n ${p.labels.map((l) => plainText(l, 60)).join(", ")}`).join("\n");
1817
+ const n = check.pages.length, pagesWord = n === 1 ? "page" : "pages";
1818
+ say(`\n${clock()} ${plainText(run.from, 40)} wants to check steps in ${product}, asked by ${plainText(run.askedBy, 60)}${when}:\n\n${list}\n\n` +
1819
+ `A browser opens with its own profile (${profile}) and visits only these ${n} ${pagesWord}, on ${host}. It looks for each label and takes a screenshot of each page.\n` +
1820
+ `The screenshots go to Next, where only admins see them, and show whatever ${product} shows you, your customers' data too.\n`);
1821
+ let yes = null;
1822
+ while (yes === null) {
1823
+ const a = await question("Check them? [y] yes [n] no › ");
1824
+ if (a === "y" || a === "yes") yes = true;
1825
+ else if (a === "n" || a === "no") yes = false;
1826
+ else say("Type y or n, then Enter.");
1827
+ }
1828
+ if (!yes) { say("Not checked."); await report(run, { status: "declined" }); return; }
1829
+ if (!(await report(run, { status: "running", approved: "once" }))) { say("Not checked: the request ended in Next before you answered (after 10 minutes, or it was disconnected). Ask again from Next."); return; }
1830
+ const install = `\n ${PLAYWRIGHT_INSTALL}\n\nthen press Check steps in ${product} in Next again.`;
1831
+ const found = findPlaywright(folder);
1832
+ let chromium = null;
1833
+ if (found) { try { const pw = await import(pathToFileURL(found).href); chromium = pw.chromium ?? pw.default?.chromium ?? null; } catch { /* reported below */ } }
1834
+ if (!chromium) {
1835
+ say(`Not checked: Playwright, which opens the browser, is not on this computer. Install it with:\n${install}`);
1836
+ await report(run, { status: "failed", problem: "no_playwright", result: [] });
1837
+ return;
1838
+ }
1839
+ const started = Date.now();
1840
+ const done = [];
1841
+ onLeave = () => report(run, { status: "failed", problem: "stopped", result: [...done, ...check.pages.slice(done.length).map((p) => ({ url: p.url, found: [], missing: [], problem: "stopped" }))] });
1842
+ say(`${clock()} Opening the browser…`);
1843
+ let results;
1844
+ try {
1845
+ results = await checkPages(chromium, check, {
1846
+ headless: process.env.AGENT_INBOX_HEADLESS === "1",
1847
+ until: started + 10 * 60_000,
1848
+ stopped: () => leaving,
1849
+ onBrowser: (b) => { browser = b; },
1850
+ signIn: async () => {
1851
+ const a = await question(`This is the first check on this computer. Sign in to ${product} in the browser that opened, then press Enter here (n stops) › `);
1852
+ return a !== "n" && a !== "no";
1853
+ },
1854
+ onPage: async (i, r, shot) => {
1855
+ done.push(r);
1856
+ const how = r.problem === "off_site" ? `went to ${short(r.at ?? "")} instead (sign in there, then check again)` : r.problem === "not_loaded" ? "did not load" : `${r.found.length} of ${r.found.length + r.missing.length} found${r.missing.length ? `; not found: ${r.missing.map((l) => plainText(l, 60)).join(", ")}` : ""}`;
1857
+ say(`${i + 1}/${n} ${short(r.url)} ${how}`);
1858
+ if (shot && shot.length <= 2_000_000) await line("POST", { action: "shot", id, line: lineId, run: run.id, page: i, image: shot.toString("base64") });
1859
+ await report(run, { status: "running", result: done });
1860
+ },
1861
+ });
1862
+ } catch {
1863
+ browser = null; onLeave = null;
1864
+ say(`Not checked: the browser did not start. If Playwright's browser is missing, install it with:\n${install}`);
1865
+ await report(run, { status: "failed", problem: "no_browser", result: done });
1866
+ return;
1867
+ }
1868
+ browser = null; onLeave = null;
1869
+ if (leaving) return;
1870
+ const cut = results.some((r) => r.problem === "stopped");
1871
+ const missing = results.reduce((m, r) => m + r.missing.length, 0);
1872
+ await report(run, { status: cut ? "failed" : "done", ...(cut ? { problem: "stopped" } : {}), result: results, exitCode: 0 });
1873
+ const secs = Math.max(1, Math.round((Date.now() - started) / 1000));
1874
+ say(cut
1875
+ ? `Stopped after 10 minutes: checked ${results.filter((r) => r.problem !== "stopped").length} of ${n} ${pagesWord}. Next shows what was checked.`
1876
+ : `Checked ${n} ${pagesWord} in ${secs} s: ${missing === 0 ? "every label was found" : `${missing} label${missing === 1 ? "" : "s"} not found`}. Next shows them on Knowledge.`);
1877
+ };
1878
+
1640
1879
  /** One request: check it, show it, ask, then run this CLI with its words in this folder, and send back what it printed. */
1641
1880
  const handle = async (run) => {
1881
+ if (run.kind === "steps") return checkSteps(run);
1642
1882
  // Run all 3: two or three commands that may run without asking, shown together and asked about once.
1643
1883
  const several = Array.isArray(run.steps);
1644
1884
  const steps = several ? runnableSequence(run.steps) : (() => { const argv = runnable(run.sub, run.args); return argv ? [{ sub: run.sub, argv }] : null; })();
@@ -1978,7 +2218,7 @@ switch (cmd) {
1978
2218
  say(markdown ? `### Proposed\n\n${fence(text)}\n\n${sent.text}` : `${text}\n\n${sent.text}`);
1979
2219
  process.exit(2);
1980
2220
  }
1981
- case "--version": case "-v": say(VERSION); break;
2221
+ case "version": case "--version": case "-v": say(VERSION); break;
1982
2222
  case "check": {
1983
2223
  // A support folder's pull request: what it would change, and a rehearsal of the change.
1984
2224
  const opt = (name) => { const i = rest.indexOf(`--${name}`); return i >= 0 ? rest[i + 1] : undefined; };
package/package.json CHANGED
@@ -1,10 +1,11 @@
1
1
  {
2
2
  "name": "@droconnell/agent-inbox-cli",
3
- "version": "2.10.0",
3
+ "version": "2.11.1",
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": {
7
- "agent-inbox": "agent-inbox.mjs"
7
+ "agent-inbox": "agent-inbox.mjs",
8
+ "agent-inbox-cli": "agent-inbox.mjs"
8
9
  },
9
10
  "files": [
10
11
  "agent-inbox.mjs",