@droconnell/agent-inbox-cli 2.10.0 → 2.11.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 (2) hide show
  1. package/agent-inbox.mjs +243 -4
  2. package/package.json +1 -1
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.0";
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");
@@ -1537,6 +1539,159 @@ export function runnableSequence(steps) {
1537
1539
  return out;
1538
1540
  }
1539
1541
 
1542
+ // ---- Check steps in the product (prd/step-checks.md): a request of its own kind, never a command ---------------------
1543
+ /**
1544
+ * Next may also ask this computer to check its help articles' steps in the product: open each listed page in a real
1545
+ * browser and look for each label the articles name. The same rules as validStepCheck in src/lib/step-checks.ts
1546
+ * (src/lib/step-checks.test.ts checks they agree), checked here again, so only pages on the product's own site are ever
1547
+ * opened, however the request was made.
1548
+ */
1549
+ export const STEP_PAGES = 20;
1550
+ export const STEP_LABELS = 30;
1551
+ const LOCAL_HOST = /^(localhost|127\.0\.0\.1|\[::1\])$/;
1552
+ const cleanText = (s) => String(s).replace(/[\u0000-\u001f\u007f-\u009f\u200b-\u200f\u2028-\u202e]/g, " ").replace(/\s+/g, " ").trim();
1553
+
1554
+ /** The product's address made whole: https (http only on this computer itself), no sign-in in it, no #part. Or null. */
1555
+ export function productAddress(raw) {
1556
+ if (typeof raw !== "string") return null;
1557
+ const text = raw.trim();
1558
+ if (!text || text.length > 300 || /\s/.test(text)) return null;
1559
+ let u;
1560
+ try { u = new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(text) ? text : `https://${text}`); } catch { return null; }
1561
+ if (u.username || u.password || (!u.hostname.includes(".") && !LOCAL_HOST.test(u.hostname))) return null;
1562
+ if (u.protocol !== "https:" && !(u.protocol === "http:" && LOCAL_HOST.test(u.hostname))) return null;
1563
+ u.hash = "";
1564
+ return u.toString();
1565
+ }
1566
+
1567
+ /** 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. */
1568
+ export function onProductSite(url, product) {
1569
+ if (typeof url !== "string" || url.length > 500) return false;
1570
+ let u, p;
1571
+ try { u = new URL(url); p = new URL(product); } catch { return false; }
1572
+ if (u.username || u.password || (u.protocol !== "https:" && u.protocol !== "http:")) return false;
1573
+ if (p.protocol === "https:" && u.protocol !== "https:") return false;
1574
+ if (u.protocol === "http:" && !LOCAL_HOST.test(u.hostname)) return false;
1575
+ const site = p.hostname.toLowerCase().replace(/^www\./, ""), host = u.hostname.toLowerCase().replace(/^www\./, "");
1576
+ return (host === site || host.endsWith(`.${site}`)) && u.port === p.port;
1577
+ }
1578
+
1579
+ /** A step check from Next, as this computer accepts it, or null (refused without asking). */
1580
+ export function stepCheckRequest(x) {
1581
+ if (!x || typeof x !== "object") return null;
1582
+ const { product, pages } = x;
1583
+ const name = typeof product?.name === "string" ? cleanText(product.name).slice(0, 80) : "";
1584
+ const url = productAddress(product?.url);
1585
+ if (!name || !url || url !== product?.url) return null;
1586
+ if (!Array.isArray(pages) || pages.length < 1 || pages.length > STEP_PAGES) return null;
1587
+ const out = [];
1588
+ for (const p of pages) {
1589
+ if (!p || typeof p !== "object" || !onProductSite(p.url, url)) return null;
1590
+ const { labels } = p;
1591
+ if (!Array.isArray(labels) || labels.length < 1 || labels.length > STEP_LABELS) return null;
1592
+ if (!labels.every((l) => typeof l === "string" && l.length >= 2 && l.length <= 60 && cleanText(l) === l)) return null;
1593
+ out.push({ url: p.url, labels: [...labels] });
1594
+ }
1595
+ return { product: { name, url }, pages: out };
1596
+ }
1597
+
1598
+ /** The browser profile the check uses: its own, in this CLI's config folder. It never leaves this computer. */
1599
+ export const BROWSER_PROFILE = join(DIR, "browser");
1600
+ /** The one command that installs what the check needs. */
1601
+ export const PLAYWRIGHT_INSTALL = "npm install -g playwright && npx playwright install chromium";
1602
+
1603
+ /** Where Playwright is on this computer: in the support folder, beside this CLI, or installed globally. Null if nowhere. */
1604
+ export function findPlaywright(folder, globalRoot = npmGlobalRoot) {
1605
+ for (const from of [join(folder, "package.json"), SELF]) {
1606
+ try { return createRequire(from).resolve("playwright"); } catch { /* not there */ }
1607
+ }
1608
+ const root = globalRoot();
1609
+ if (root) { try { return createRequire(join(dirname(root), "package.json")).resolve("playwright"); } catch { /* not there */ } }
1610
+ return null;
1611
+ }
1612
+ function npmGlobalRoot() {
1613
+ const r = spawnSync(platform() === "win32" ? "npm.cmd" : "npm", ["root", "-g"], { encoding: "utf8", timeout: 15_000, shell: false, windowsHide: true });
1614
+ return r.status === 0 ? r.stdout.trim() : "";
1615
+ }
1616
+
1617
+ /** Whether the page shows a label: as a button, link, tab, menu item or field label, or as visible text. */
1618
+ async function pageShows(page, label) {
1619
+ const ways = [
1620
+ page.getByRole("button", { name: label }), page.getByRole("link", { name: label }), page.getByRole("tab", { name: label }),
1621
+ page.getByRole("menuitem", { name: label }), page.getByLabel(label), page.getByText(label),
1622
+ ];
1623
+ for (const way of ways) {
1624
+ try {
1625
+ const n = Math.min(await way.count(), 5);
1626
+ for (let i = 0; i < n; i++) if (await way.nth(i).isVisible()) return true;
1627
+ } catch { /* that way does not apply here */ }
1628
+ }
1629
+ return false;
1630
+ }
1631
+
1632
+ /** The labels a page does show (buttons, links, tabs, field labels, headings): what a fix can use instead. */
1633
+ const NEARBY = () => {
1634
+ const seen = new Set(), out = [];
1635
+ for (const el of document.querySelectorAll("button, a, [role=button], [role=tab], [role=menuitem], label, h1, h2, h3, summary")) {
1636
+ if (!el.getClientRects().length) continue;
1637
+ const text = (el.innerText || el.getAttribute("aria-label") || "").replace(/\s+/g, " ").trim();
1638
+ if (text.length < 2 || text.length > 60 || seen.has(text.toLowerCase())) continue;
1639
+ seen.add(text.toLowerCase());
1640
+ out.push(text);
1641
+ if (out.length >= 80) break;
1642
+ }
1643
+ return out;
1644
+ };
1645
+
1646
+ /**
1647
+ * Visit each page of a step check in a real browser, with its own profile, and look for each label. One page at a
1648
+ * time, a pause between pages, only pages on the product's own site (a page that sends the browser elsewhere, such as
1649
+ * to a sign-in on another site, is reported and not screenshot). `onPage` gets each page's result and a JPEG of what
1650
+ * was on screen. Pages not reached by `until`, or once `stopped()` says so, are reported as stopped.
1651
+ */
1652
+ 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 () => {} } = {}) {
1653
+ const fresh = !existsSync(profile);
1654
+ mkdirSync(profile, { recursive: true, mode: 0o700 });
1655
+ const browser = await chromium.launchPersistentContext(profile, { headless, viewport: { width: 1280, height: 860 } });
1656
+ onBrowser(browser);
1657
+ const results = [];
1658
+ try {
1659
+ const page = browser.pages()[0] ?? await browser.newPage();
1660
+ // The first time, there is no sign-in in this profile yet: open the product and let the person sign in.
1661
+ let go = true;
1662
+ if (fresh) {
1663
+ await page.goto(check.product.url, { waitUntil: "domcontentloaded", timeout: 30_000 }).catch(() => {});
1664
+ go = await signIn();
1665
+ }
1666
+ for (let i = 0; i < check.pages.length; i++) {
1667
+ const want = check.pages[i];
1668
+ if (!go || stopped() || Date.now() > until) { results.push({ url: want.url, found: [], missing: [], problem: "stopped" }); continue; }
1669
+ if (i > 0) await new Promise((ok) => setTimeout(ok, pauseMs));
1670
+ let result, shot = null;
1671
+ try {
1672
+ await page.goto(want.url, { waitUntil: "domcontentloaded", timeout: 30_000 });
1673
+ await page.waitForLoadState("networkidle", { timeout: 5_000 }).catch(() => {});
1674
+ const at = page.url();
1675
+ if (!onProductSite(at, check.product.url)) result = { url: want.url, at, found: [], missing: [], problem: "off_site" };
1676
+ else {
1677
+ const found = [], missing = [];
1678
+ for (const label of want.labels) (await pageShows(page, label) ? found : missing).push(label);
1679
+ const nearby = await page.evaluate(NEARBY).catch(() => []);
1680
+ shot = await page.screenshot({ type: "jpeg", quality: 60 }).catch(() => null);
1681
+ result = { url: want.url, ...(at !== want.url ? { at } : {}), found, missing, nearby };
1682
+ }
1683
+ } catch {
1684
+ result = { url: want.url, found: [], missing: [], problem: "not_loaded" };
1685
+ }
1686
+ results.push(result);
1687
+ await onPage(i, result, shot);
1688
+ }
1689
+ } finally {
1690
+ await browser.close().catch(() => {});
1691
+ }
1692
+ return results;
1693
+ }
1694
+
1540
1695
  /** Text from Next shown in this terminal: no control characters, so nothing sent can move the cursor or recolour the screen. */
1541
1696
  export const plainText = (s, max = 120) => String(s ?? "").replace(/[\u0000-\u001f\u007f-\u009f\u200b-\u200f\u2028-\u202e]/g, "").slice(0, max);
1542
1697
 
@@ -1607,11 +1762,14 @@ async function connect(words) {
1607
1762
  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
1763
 
1609
1764
  const rl = (await import("node:readline")).createInterface({ input: process.stdin, output: process.stdout });
1610
- let child = null, leaving = false;
1765
+ // A step check's browser, and what to tell Next if Ctrl+C stops it part way.
1766
+ let child = null, browser = null, onLeave = null, leaving = false;
1611
1767
  const leave = async (why) => {
1612
1768
  if (leaving) return;
1613
1769
  leaving = true;
1614
1770
  if (child) child.kill();
1771
+ if (onLeave) await onLeave().catch(() => {});
1772
+ if (browser) await browser.close().catch(() => {});
1615
1773
  if (why) say(`\n${why}`);
1616
1774
  await line("POST", { action: "leave", id, line: lineId }).catch(() => {});
1617
1775
  rl.close();
@@ -1637,8 +1795,89 @@ async function connect(words) {
1637
1795
  /** The folder or file a command's words name (it comes right after the command's own words, before any option), or "." */
1638
1796
  const namedPath = (sub, argv) => { const named = argv[sub.split(" ").length]; return named && !named.startsWith("-") ? named : "."; };
1639
1797
 
1798
+ /**
1799
+ * A step check (prd/step-checks.md): not a command. Shows the product, each page and its labels, and asks; then opens
1800
+ * a real browser with its own profile and looks for each label, one page at a time, sending each page's result and
1801
+ * screenshot to Next as it goes. Needs Playwright on this computer, and stops after 10 minutes or at Ctrl+C.
1802
+ */
1803
+ const checkSteps = async (run) => {
1804
+ const check = stepCheckRequest(run.check);
1805
+ const ago = Math.floor((Date.now() - Date.parse(run.askedAt)) / 60_000);
1806
+ const when = ago >= 1 ? ` ${ago} minute${ago === 1 ? "" : "s"} ago` : "";
1807
+ if (!check) {
1808
+ 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}.`);
1809
+ 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` });
1810
+ return;
1811
+ }
1812
+ const product = plainText(check.product.name, 80), host = new URL(check.product.url).host;
1813
+ const short = (u) => plainText(u.replace(/^https?:\/\//, "").replace(/\/$/, ""), 100);
1814
+ const profile = BROWSER_PROFILE.startsWith(homedir() + sep) ? `~${BROWSER_PROFILE.slice(homedir().length)}` : BROWSER_PROFILE;
1815
+ const list = check.pages.map((p, i) => ` ${i + 1}. ${short(p.url)}\n ${p.labels.map((l) => plainText(l, 60)).join(", ")}`).join("\n");
1816
+ const n = check.pages.length, pagesWord = n === 1 ? "page" : "pages";
1817
+ 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` +
1818
+ `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` +
1819
+ `The screenshots go to Next, where only admins see them, and show whatever ${product} shows you, your customers' data too.\n`);
1820
+ let yes = null;
1821
+ while (yes === null) {
1822
+ const a = await question("Check them? [y] yes [n] no › ");
1823
+ if (a === "y" || a === "yes") yes = true;
1824
+ else if (a === "n" || a === "no") yes = false;
1825
+ else say("Type y or n, then Enter.");
1826
+ }
1827
+ if (!yes) { say("Not checked."); await report(run, { status: "declined" }); return; }
1828
+ 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; }
1829
+ const install = `\n ${PLAYWRIGHT_INSTALL}\n\nthen press Check steps in ${product} in Next again.`;
1830
+ const found = findPlaywright(folder);
1831
+ let chromium = null;
1832
+ if (found) { try { const pw = await import(pathToFileURL(found).href); chromium = pw.chromium ?? pw.default?.chromium ?? null; } catch { /* reported below */ } }
1833
+ if (!chromium) {
1834
+ say(`Not checked: Playwright, which opens the browser, is not on this computer. Install it with:\n${install}`);
1835
+ await report(run, { status: "failed", problem: "no_playwright", result: [] });
1836
+ return;
1837
+ }
1838
+ const started = Date.now();
1839
+ const done = [];
1840
+ onLeave = () => report(run, { status: "failed", problem: "stopped", result: [...done, ...check.pages.slice(done.length).map((p) => ({ url: p.url, found: [], missing: [], problem: "stopped" }))] });
1841
+ say(`${clock()} Opening the browser…`);
1842
+ let results;
1843
+ try {
1844
+ results = await checkPages(chromium, check, {
1845
+ headless: process.env.AGENT_INBOX_HEADLESS === "1",
1846
+ until: started + 10 * 60_000,
1847
+ stopped: () => leaving,
1848
+ onBrowser: (b) => { browser = b; },
1849
+ signIn: async () => {
1850
+ 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) › `);
1851
+ return a !== "n" && a !== "no";
1852
+ },
1853
+ onPage: async (i, r, shot) => {
1854
+ done.push(r);
1855
+ 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(", ")}` : ""}`;
1856
+ say(`${i + 1}/${n} ${short(r.url)} ${how}`);
1857
+ if (shot && shot.length <= 2_000_000) await line("POST", { action: "shot", id, line: lineId, run: run.id, page: i, image: shot.toString("base64") });
1858
+ await report(run, { status: "running", result: done });
1859
+ },
1860
+ });
1861
+ } catch {
1862
+ browser = null; onLeave = null;
1863
+ say(`Not checked: the browser did not start. If Playwright's browser is missing, install it with:\n${install}`);
1864
+ await report(run, { status: "failed", problem: "no_browser", result: done });
1865
+ return;
1866
+ }
1867
+ browser = null; onLeave = null;
1868
+ if (leaving) return;
1869
+ const cut = results.some((r) => r.problem === "stopped");
1870
+ const missing = results.reduce((m, r) => m + r.missing.length, 0);
1871
+ await report(run, { status: cut ? "failed" : "done", ...(cut ? { problem: "stopped" } : {}), result: results, exitCode: 0 });
1872
+ const secs = Math.max(1, Math.round((Date.now() - started) / 1000));
1873
+ say(cut
1874
+ ? `Stopped after 10 minutes: checked ${results.filter((r) => r.problem !== "stopped").length} of ${n} ${pagesWord}. Next shows what was checked.`
1875
+ : `Checked ${n} ${pagesWord} in ${secs} s: ${missing === 0 ? "every label was found" : `${missing} label${missing === 1 ? "" : "s"} not found`}. Next shows them on Knowledge.`);
1876
+ };
1877
+
1640
1878
  /** One request: check it, show it, ask, then run this CLI with its words in this folder, and send back what it printed. */
1641
1879
  const handle = async (run) => {
1880
+ if (run.kind === "steps") return checkSteps(run);
1642
1881
  // Run all 3: two or three commands that may run without asking, shown together and asked about once.
1643
1882
  const several = Array.isArray(run.steps);
1644
1883
  const steps = several ? runnableSequence(run.steps) : (() => { const argv = runnable(run.sub, run.args); return argv ? [{ sub: run.sub, argv }] : null; })();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@droconnell/agent-inbox-cli",
3
- "version": "2.10.0",
3
+ "version": "2.11.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": {