@droconnell/agent-inbox-cli 0.0.0-stage → 1.9.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 +45 -2
- package/agent-inbox.mjs +671 -0
- package/package.json +24 -4
package/README.md
CHANGED
|
@@ -1,3 +1,46 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @droconnell/agent-inbox-cli
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The command-line tool for **Next**, the customer-support console. It keeps a workspace's setup in a folder of files 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 pull support # the setup as a folder: agents/, knowledge/, rules/, tests/, apps/
|
|
29
|
+
agent-inbox plan support # what the changed folder would change; changes nothing
|
|
30
|
+
agent-inbox push support # send the folder's changes to Decisions (--prune removes deleted ones)
|
|
31
|
+
agent-inbox export agent-inbox.yaml # the setup as one YAML file
|
|
32
|
+
agent-inbox diff agent-inbox.yaml # what the file would change; changes nothing
|
|
33
|
+
agent-inbox propose agent-inbox.yaml # send the changes to Decisions
|
|
34
|
+
agent-inbox ls unassigned # any console terminal command
|
|
35
|
+
agent-inbox help # every command
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
## Update
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
agent-inbox update
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
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.
|
|
45
|
+
|
|
46
|
+
The full guide is in your Next help center, under "Use the Next CLI".
|
package/agent-inbox.mjs
ADDED
|
@@ -0,0 +1,671 @@
|
|
|
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 pull [folder] the setup as a folder of files: workspace.yaml, agents/, knowledge/, rules/,
|
|
10
|
+
// tests/ and apps/ (the same files Settings, Your support as files shows)
|
|
11
|
+
// 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 Decisions; --prune also removes articles and tests
|
|
13
|
+
// whose files you deleted
|
|
14
|
+
// agent-inbox check [folder] for a pull request: the plan and a rehearsal of it, as markdown (exit 1 needs a look)
|
|
15
|
+
// agent-inbox ci init [folder] write the GitHub workflow that checks pull requests, proposes on merge, and
|
|
16
|
+
// opens a pull request when someone changed the setup in the console
|
|
17
|
+
// 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 Decisions, where an admin applies or discards them
|
|
19
|
+
// (a folder: its Markdown, text and HTML documents, as knowledge articles)
|
|
20
|
+
// agent-inbox <terminal command> any console terminal command, such as agent-inbox ls unassigned
|
|
21
|
+
// agent-inbox run "<command>" the same, in quotes, such as "ls unassigned" or "route test 'refund?'"
|
|
22
|
+
// agent-inbox help <command> one terminal command with an example; agent-inbox commands lists them all
|
|
23
|
+
// agent-inbox script <file> [--propose] a file of terminal commands, one per line, as one plan; --propose sends
|
|
24
|
+
// it to Decisions (exit 0 nothing to change, 2 a plan, 1 problems)
|
|
25
|
+
// agent-inbox logout forget the sign-in on this computer
|
|
26
|
+
// agent-inbox update how to update, for how it was installed (a downloaded file updates itself)
|
|
27
|
+
//
|
|
28
|
+
// Nothing the CLI does changes the workspace by itself: changes wait in Decisions for an admin's click.
|
|
29
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
30
|
+
import { createServer } from "node:http";
|
|
31
|
+
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";
|
|
35
|
+
import { fileURLToPath } from "node:url";
|
|
36
|
+
|
|
37
|
+
export const VERSION = "1.9.0";
|
|
38
|
+
/** The npm package; its command is agent-inbox. (The name agent-inbox itself belongs to someone else on npm.) */
|
|
39
|
+
export const PACKAGE = "@droconnell/agent-inbox-cli";
|
|
40
|
+
const DIR = join(process.env.XDG_CONFIG_HOME || join(homedir(), ".config"), "agent-inbox");
|
|
41
|
+
const SAVED = join(DIR, "sign-in.json");
|
|
42
|
+
const CHECKED = join(DIR, "update-check.json");
|
|
43
|
+
const SELF = fileURLToPath(import.meta.url);
|
|
44
|
+
const real = (p) => { try { return realpathSync(p); } catch { return p; } };
|
|
45
|
+
|
|
46
|
+
/** Whether version a is newer than version b ("1.10.0" is newer than "1.9.2"). Anything unreadable is not newer. */
|
|
47
|
+
export function newer(a, b) {
|
|
48
|
+
const parts = (v) => (/^v?(\d+)\.(\d+)\.(\d+)$/.exec(String(v ?? "").trim()) ?? []).slice(1).map(Number);
|
|
49
|
+
const x = parts(a), y = parts(b);
|
|
50
|
+
if (x.length !== 3 || y.length !== 3) return false;
|
|
51
|
+
for (let i = 0; i < 3; i++) if (x[i] !== y[i]) return x[i] > y[i];
|
|
52
|
+
return false;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** How the person ran it, for the help and the hints: agent-inbox when installed, node <file> when downloaded. */
|
|
56
|
+
export function invokedAs(script = process.argv[1] ?? "", cwd = process.cwd()) {
|
|
57
|
+
if (!/\.m?js$/i.test(basename(script)) || /[\\/]node_modules[\\/]/.test(script)) return "agent-inbox";
|
|
58
|
+
const rel = relative(cwd, script);
|
|
59
|
+
const shown = rel && !rel.startsWith("..") && !isAbsolute(rel) ? rel : script;
|
|
60
|
+
return `node ${/\s/.test(shown) ? JSON.stringify(shown) : shown}`;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** How it was installed, from where this file really lives: Homebrew (its Cellar), npm (node_modules) or a download. */
|
|
64
|
+
export function installedBy(path) {
|
|
65
|
+
if (/[\\/]Cellar[\\/]/.test(path)) return "brew";
|
|
66
|
+
if (/[\\/]node_modules[\\/]/.test(path)) return "npm";
|
|
67
|
+
return "file";
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const ME = invokedAs();
|
|
71
|
+
const args = process.argv.slice(2);
|
|
72
|
+
const flag = (n) => { const i = args.indexOf(n); return i >= 0 ? (args.splice(i, 1), true) : false; };
|
|
73
|
+
const markdown = flag("--markdown");
|
|
74
|
+
const proposing = flag("--propose");
|
|
75
|
+
const pruning = flag("--prune");
|
|
76
|
+
const forcing = flag("--force");
|
|
77
|
+
const [cmd, ...rest] = args;
|
|
78
|
+
|
|
79
|
+
const say = (s) => process.stdout.write(s.endsWith("\n") ? s : s + "\n");
|
|
80
|
+
const stop = (s, code = 1) => { process.stderr.write(`agent-inbox: ${s}\n`); process.exit(code); };
|
|
81
|
+
const clean = (u) => { try { const x = new URL(u.includes("://") ? u : `https://${u}`); return x.origin; } catch { stop(`${u} is not a web address.`); } };
|
|
82
|
+
const load = () => { try { return JSON.parse(readFileSync(SAVED, "utf8")); } catch { return null; } };
|
|
83
|
+
const keep = (s) => { mkdirSync(DIR, { recursive: true, mode: 0o700 }); writeFileSync(SAVED, JSON.stringify(s, null, 2), { mode: 0o600 }); };
|
|
84
|
+
|
|
85
|
+
async function form(url, body) {
|
|
86
|
+
const r = await fetch(url, { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" }, body: new URLSearchParams(body) });
|
|
87
|
+
const j = await r.json().catch(() => ({}));
|
|
88
|
+
if (!r.ok) throw new Error(j.error_description || j.error || `the server answered ${r.status}`);
|
|
89
|
+
return j;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Where to work and with what: the environment (CI) first, then this computer's sign-in, renewed when it runs out. */
|
|
93
|
+
async function access() {
|
|
94
|
+
if (process.env.AGENT_INBOX_TOKEN) {
|
|
95
|
+
if (!process.env.AGENT_INBOX_URL) stop("AGENT_INBOX_TOKEN is set, so set AGENT_INBOX_URL to your console's address too.");
|
|
96
|
+
return { url: clean(process.env.AGENT_INBOX_URL), token: process.env.AGENT_INBOX_TOKEN };
|
|
97
|
+
}
|
|
98
|
+
const s = load();
|
|
99
|
+
if (!s) stop(`Not signed in. Run ${ME} login <your console's address>, or set AGENT_INBOX_URL and AGENT_INBOX_TOKEN.`);
|
|
100
|
+
if (Date.now() > s.expiresAt - 60_000) {
|
|
101
|
+
try {
|
|
102
|
+
const t = await form(`${s.url}/api/oauth/token`, { grant_type: "refresh_token", refresh_token: s.refresh, client_id: s.clientId });
|
|
103
|
+
Object.assign(s, { access: t.access_token, refresh: t.refresh_token, expiresAt: Date.now() + t.expires_in * 1000 });
|
|
104
|
+
keep(s);
|
|
105
|
+
} catch { stop(`Your sign-in has ended or was disconnected. Run ${ME} login again.`); }
|
|
106
|
+
}
|
|
107
|
+
notice(s.url);
|
|
108
|
+
return { url: s.url, token: s.access };
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* One MCP tool call; the server is the same one claude.ai and Cursor use. With `soft`, a network blip throws instead of
|
|
113
|
+
* ending the command, so a long-running one (tail) can try again.
|
|
114
|
+
*/
|
|
115
|
+
async function tool(name, args = {}, { soft = false } = {}) {
|
|
116
|
+
const { url, token } = await access();
|
|
117
|
+
let r;
|
|
118
|
+
try {
|
|
119
|
+
r = await fetch(`${url}/api/mcp`, {
|
|
120
|
+
method: "POST",
|
|
121
|
+
headers: { authorization: `Bearer ${token}`, "content-type": "application/json", accept: "application/json, text/event-stream", "user-agent": `agent-inbox-cli/${VERSION}` },
|
|
122
|
+
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } }),
|
|
123
|
+
});
|
|
124
|
+
} catch { if (soft) throw new Error("unreachable"); stop(`Could not reach ${url}. Check the address and your connection.`); }
|
|
125
|
+
if (soft && r.status >= 500) throw new Error("unavailable");
|
|
126
|
+
if (r.status === 401) stop(process.env.AGENT_INBOX_TOKEN ? "The token was refused: it has expired or been revoked. Make a new one in Settings, Terminal, AI tools." : `Your sign-in was refused. Run ${ME} login again.`);
|
|
127
|
+
if (r.status === 403) stop("Only an admin of the workspace can use this.");
|
|
128
|
+
if (r.status === 429) stop("Too many requests just now. Wait a minute and try again.");
|
|
129
|
+
const raw = await r.text();
|
|
130
|
+
let j; try { j = JSON.parse(raw.startsWith("{") ? raw : raw.split("data: ")[1]); } catch { stop(`The server answered ${r.status}. Try again.`); }
|
|
131
|
+
if (j.error) stop(j.error.message);
|
|
132
|
+
const text = (j.result.content || []).map((c) => c.text).join("\n");
|
|
133
|
+
return { text, isError: !!j.result.isError, data: j.result.structuredContent };
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** A tail page's text without its last line, "(next: tail … --after e12m34)", and that line's command. */
|
|
137
|
+
export function splitNext(text) {
|
|
138
|
+
const m = /\n*\(next: (tail [^\n)]*)\)\s*$/.exec(text);
|
|
139
|
+
return m ? { body: text.slice(0, m.index).trim(), next: m[1] } : { body: text.trim(), next: null };
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** Wait for test or rehearsal jobs, asking how each stands every few seconds (asking also moves it along). */
|
|
143
|
+
async function waitJobs(jobs) {
|
|
144
|
+
const lines = [];
|
|
145
|
+
let ok = true;
|
|
146
|
+
for (const { job, agent } of jobs) {
|
|
147
|
+
const until = Date.now() + 15 * 60_000;
|
|
148
|
+
let s;
|
|
149
|
+
for (;;) {
|
|
150
|
+
s = await tool("check_status", { job });
|
|
151
|
+
if (s.data?.state !== "running") break;
|
|
152
|
+
if (Date.now() > until) stop(`Still running after 15 minutes: ${agent}. See Jobs in the console.`);
|
|
153
|
+
if (!markdown && process.stderr.isTTY) process.stderr.write(`\r${agent}: ${s.text}`.padEnd(80).slice(0, 80));
|
|
154
|
+
await new Promise((r) => setTimeout(r, 5000));
|
|
155
|
+
}
|
|
156
|
+
if (!markdown && process.stderr.isTTY) process.stderr.write("\r".padEnd(81) + "\r");
|
|
157
|
+
if (s.data?.passed === false) ok = false;
|
|
158
|
+
lines.push(`${agent}: ${s.text}`);
|
|
159
|
+
}
|
|
160
|
+
return { ok, lines };
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// ---- CI for a repository of support files --------------------------------------------------------------------------
|
|
164
|
+
/** The marker a check's pull request comment starts with, so the workflow edits one comment instead of adding more. */
|
|
165
|
+
export const CHECK_MARK = "<!-- next-support-check -->";
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* The report `check` writes for a pull request: what the folder would change, and a rehearsal of the change on past
|
|
169
|
+
* conversations and the saved tests. Pure, so it can be tested. `failed` is true when something needs a look.
|
|
170
|
+
*/
|
|
171
|
+
export function checkReport({ plan, changes, rehearsal = null, skipped = null, blocked = null }) {
|
|
172
|
+
const fenced = (s) => "```\n" + s.replace(/```/g, "'''") + "\n```";
|
|
173
|
+
const list = (r) => r.lines.map((l) => `- ${l}`).join("\n");
|
|
174
|
+
const parts = [CHECK_MARK, "## Next: what this pull request would do"];
|
|
175
|
+
parts.push(changes ? `### ${changes === 1 ? "1 change" : `${changes} changes`}\n\n${fenced(plan)}` : "### No changes\n\nThe workspace already matches the folder.");
|
|
176
|
+
if (rehearsal) parts.push(`### Rehearsal: ${rehearsal.ok ? "nothing got worse" : "something got worse"}\n\nPast conversations and the saved tests, answered with this change and without it.\n\n${list(rehearsal)}`);
|
|
177
|
+
if (skipped) parts.push(`> ${skipped}`);
|
|
178
|
+
if (blocked) parts.push(`### Could not rehearse\n\n${blocked}`);
|
|
179
|
+
const failed = Boolean(blocked || (rehearsal && !rehearsal.ok));
|
|
180
|
+
if (failed) parts.push("**Needs a look before merging.**");
|
|
181
|
+
else if (changes) parts.push("Merging proposes these changes in Next's **Decisions**, where an admin applies them.");
|
|
182
|
+
return { text: parts.join("\n\n") + "\n", failed };
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** The GitHub workflow `ci init` writes for a support folder: check pull requests, propose on merge, catch drift nightly. */
|
|
186
|
+
export function ciWorkflow(url, folder) {
|
|
187
|
+
const dir = folder.replace(/^\.\//, "").replace(/\/+$/, "") || ".";
|
|
188
|
+
const paths = dir === "." ? "**" : `${dir}/**`;
|
|
189
|
+
const cli = 'curl -fsSL "$AGENT_INBOX_URL/cli/agent-inbox.mjs" -o agent-inbox.mjs';
|
|
190
|
+
const setup = ` - uses: actions/checkout@v4
|
|
191
|
+
- uses: actions/setup-node@v4
|
|
192
|
+
with: { node-version: 22 }
|
|
193
|
+
- run: ${cli}`;
|
|
194
|
+
const pr = "${{ github.event.pull_request.number }}";
|
|
195
|
+
return `# Next support, written by agent-inbox ci init. The support setup lives in ${dir === "." ? "this repository" : `${dir}/`} (agent-inbox pull).
|
|
196
|
+
# Pull requests: what the change would do, and a rehearsal on past conversations and the saved tests, as one comment.
|
|
197
|
+
# Merges to main: the changes are proposed in Next's Decisions, for an admin to apply.
|
|
198
|
+
# Nightly: changes someone made in Next's console come back as a pull request, so the two never drift apart.
|
|
199
|
+
# Needs the repository secret AGENT_INBOX_TOKEN: a Next personal access token set to Look and propose changes.
|
|
200
|
+
name: Next support
|
|
201
|
+
on:
|
|
202
|
+
pull_request:
|
|
203
|
+
paths: ["${paths}"]
|
|
204
|
+
push:
|
|
205
|
+
branches: [main]
|
|
206
|
+
paths: ["${paths}"]
|
|
207
|
+
schedule:
|
|
208
|
+
- cron: "17 6 * * *"
|
|
209
|
+
workflow_dispatch:
|
|
210
|
+
permissions:
|
|
211
|
+
contents: write
|
|
212
|
+
pull-requests: write
|
|
213
|
+
env:
|
|
214
|
+
AGENT_INBOX_URL: ${url}
|
|
215
|
+
AGENT_INBOX_TOKEN: \${{ secrets.AGENT_INBOX_TOKEN }}
|
|
216
|
+
jobs:
|
|
217
|
+
check:
|
|
218
|
+
if: github.event_name == 'pull_request'
|
|
219
|
+
runs-on: ubuntu-latest
|
|
220
|
+
steps:
|
|
221
|
+
${setup}
|
|
222
|
+
- name: Check the change
|
|
223
|
+
id: check
|
|
224
|
+
run: |
|
|
225
|
+
set +e
|
|
226
|
+
node agent-inbox.mjs check ${dir} > report.md
|
|
227
|
+
echo "code=$?" >> "$GITHUB_OUTPUT"
|
|
228
|
+
cat report.md >> "$GITHUB_STEP_SUMMARY"
|
|
229
|
+
- name: Comment on the pull request
|
|
230
|
+
env: { GH_TOKEN: "\${{ github.token }}" }
|
|
231
|
+
run: gh pr comment ${pr} --body-file report.md --edit-last || gh pr comment ${pr} --body-file report.md
|
|
232
|
+
- name: Pass or fail
|
|
233
|
+
run: exit \${{ steps.check.outputs.code }}
|
|
234
|
+
propose:
|
|
235
|
+
if: github.event_name == 'push'
|
|
236
|
+
runs-on: ubuntu-latest
|
|
237
|
+
steps:
|
|
238
|
+
${setup}
|
|
239
|
+
- run: node agent-inbox.mjs push ${dir} --markdown >> "$GITHUB_STEP_SUMMARY"
|
|
240
|
+
drift:
|
|
241
|
+
if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch'
|
|
242
|
+
runs-on: ubuntu-latest
|
|
243
|
+
steps:
|
|
244
|
+
${setup}
|
|
245
|
+
- run: node agent-inbox.mjs pull ${dir}
|
|
246
|
+
- name: Open a pull request with what changed in Next
|
|
247
|
+
env: { GH_TOKEN: "\${{ github.token }}" }
|
|
248
|
+
run: |
|
|
249
|
+
rm -f agent-inbox.mjs
|
|
250
|
+
if [ -z "$(git status --porcelain)" ]; then echo "The folder already matches Next."; exit 0; fi
|
|
251
|
+
branch="next-changes-$(date +%Y-%m-%d)"
|
|
252
|
+
git config user.name "Next" && git config user.email "next@users.noreply.github.com"
|
|
253
|
+
git checkout -b "$branch" && git add -A && git commit -m "Changes made in Next" && git push -u origin "$branch"
|
|
254
|
+
gh pr create --title "Changes made in Next" --body "Someone changed the support setup in Next's console. Merging brings this folder up to date; nothing in Next changes."
|
|
255
|
+
`;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
// ---- Knowledge from this computer ----------------------------------------------------------------------------------
|
|
259
|
+
const DOCS = [".md", ".markdown", ".txt", ".html", ".htm"];
|
|
260
|
+
const posix = (p) => p.split(sep).join("/");
|
|
261
|
+
/** The same patterns the server reads: * is any name, ** any folders, a plain folder is everything in it. */
|
|
262
|
+
function globTest(pattern) {
|
|
263
|
+
const p = pattern.replace(/^\.\//, "").replace(/\/+$/, "");
|
|
264
|
+
const re = new RegExp(`^${p.split(/(\*\*\/?|\*|\?)/).map((x) => (x === "**/" ? "(?:.*/)?" : x === "**" ? ".*" : x === "*" ? "[^/]*" : x === "?" ? "[^/]" : x.replace(/[.+^${}()|[\]\\]/g, "\\$&"))).join("")}${/[*?]/.test(p) ? "" : "(?:/.*)?"}$`);
|
|
265
|
+
return (path) => re.test(path.replace(/^\.\//, ""));
|
|
266
|
+
}
|
|
267
|
+
function walk(dir, out = []) {
|
|
268
|
+
for (const e of readdirSync(dir, { withFileTypes: true })) {
|
|
269
|
+
if (e.name.startsWith(".") || e.name === "node_modules") continue;
|
|
270
|
+
const p = join(dir, e.name);
|
|
271
|
+
if (e.isDirectory()) walk(p, out); else if (DOCS.some((x) => e.name.toLowerCase().endsWith(x))) out.push(p);
|
|
272
|
+
}
|
|
273
|
+
return out;
|
|
274
|
+
}
|
|
275
|
+
/** The documents a file's knowledge section names (file: and files:), read relative to the file, by path. */
|
|
276
|
+
function documents(text, base) {
|
|
277
|
+
const files = {};
|
|
278
|
+
for (const m of text.matchAll(/^[\s-]*(file|files):\s*["']?([^"'#\n]+?)["']?\s*(?:#.*)?$/gm)) {
|
|
279
|
+
const [, kind, pattern] = m;
|
|
280
|
+
if (kind === "file") { const p = join(base, pattern); if (existsSync(p)) files[posix(pattern.replace(/^\.\//, ""))] = readFileSync(p, "utf8"); continue; }
|
|
281
|
+
const start = join(base, pattern.replace(/^\.\//, "").split(/[*?]/)[0].replace(/[^/]*$/, "") || ".");
|
|
282
|
+
if (!existsSync(start)) continue;
|
|
283
|
+
const test = globTest(pattern);
|
|
284
|
+
for (const p of statSync(start).isDirectory() ? walk(start) : [start]) { const rel = posix(relative(base, p)); if (test(rel)) files[rel] = readFileSync(p, "utf8"); }
|
|
285
|
+
}
|
|
286
|
+
const size = Object.values(files).reduce((n, v) => n + v.length, 0) + text.length;
|
|
287
|
+
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).");
|
|
288
|
+
return files;
|
|
289
|
+
}
|
|
290
|
+
/** What to send: a YAML file (with any documents it names), or a folder of documents as knowledge. */
|
|
291
|
+
const read = (path) => {
|
|
292
|
+
if (!path) stop(`Name the file or folder, for example ${ME} diff agent-inbox.yaml, or ${ME} diff ./docs`);
|
|
293
|
+
if (!existsSync(path)) stop(`There is nothing called ${path}.`);
|
|
294
|
+
if (statSync(path).isDirectory()) {
|
|
295
|
+
const folder = posix(relative(".", path)) || ".";
|
|
296
|
+
const yaml = JSON.stringify({ knowledge: [{ files: folder === "." ? "**" : folder }] });
|
|
297
|
+
const files = documents(`files: ${folder === "." ? "**" : folder}`, ".");
|
|
298
|
+
if (!Object.keys(files).length) stop(`There are no Markdown, text or HTML documents in ${path}.`);
|
|
299
|
+
return { yaml, files };
|
|
300
|
+
}
|
|
301
|
+
const yaml = readFileSync(path, "utf8");
|
|
302
|
+
const files = documents(yaml, dirname(path));
|
|
303
|
+
return { yaml, files }; // sent even when empty: the server then knows the CLI looked, and says what matched nothing
|
|
304
|
+
};
|
|
305
|
+
const fence = (s) => (markdown ? "```\n" + s.replace(/```/g, "'''") + "\n```" : s);
|
|
306
|
+
|
|
307
|
+
// ---- The setup as a folder (pull, plan, push) ------------------------------------------------------------------------
|
|
308
|
+
/** In a pulled folder: where it came from and each file as it was pulled, to tell edits apart. Never a secret. */
|
|
309
|
+
export const STATE = ".agent-inbox.json";
|
|
310
|
+
const hash = (s) => createHash("sha256").update(s).digest("hex").slice(0, 16);
|
|
311
|
+
const readState = (dir) => { try { return JSON.parse(readFileSync(join(dir, STATE), "utf8")); } catch { return null; } };
|
|
312
|
+
/** A folder pull made, or one laid out like one: workspace.yaml at the top. */
|
|
313
|
+
export const isPulled = (dir) => existsSync(join(dir, STATE)) || existsSync(join(dir, "workspace.yaml"));
|
|
314
|
+
/** Every file in the folder, by path relative to it, skipping hidden ones (.git, the state file) and node_modules. */
|
|
315
|
+
export function folderFiles(dir) {
|
|
316
|
+
const out = {};
|
|
317
|
+
const go = (d) => {
|
|
318
|
+
for (const e of readdirSync(d, { withFileTypes: true })) {
|
|
319
|
+
if (e.name.startsWith(".") || e.name === "node_modules") continue;
|
|
320
|
+
const p = join(d, e.name);
|
|
321
|
+
if (e.isDirectory()) go(p); else if (statSync(p).size <= 1_000_000) out[posix(relative(dir, p))] = readFileSync(p, "utf8");
|
|
322
|
+
}
|
|
323
|
+
};
|
|
324
|
+
go(dir);
|
|
325
|
+
return out;
|
|
326
|
+
}
|
|
327
|
+
/** Which files differ from the pull: changed or new. Without a record of the pull, it cannot say (null). */
|
|
328
|
+
export function edits(files, state) {
|
|
329
|
+
if (!state?.files) return null;
|
|
330
|
+
return Object.keys(files).filter((p) => state.files[p] !== hash(files[p]));
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
async function pull(dir) {
|
|
334
|
+
const { url } = await access();
|
|
335
|
+
const before = readState(dir);
|
|
336
|
+
if (existsSync(dir) && !before && readdirSync(dir).filter((n) => !n.startsWith(".")).length) stop(`${dir} already has files that did not come from ${ME} pull. Name a new folder, for example ${ME} pull support`);
|
|
337
|
+
if (before?.url && before.url !== url) stop(`${dir} was pulled from ${before.url}, not ${url}. Pull into a new folder.`);
|
|
338
|
+
// Every part, then check nothing here would be lost before writing anything.
|
|
339
|
+
const files = [];
|
|
340
|
+
for (let from = 0; from !== null;) {
|
|
341
|
+
const { data, isError, text } = await tool("export_files", { from });
|
|
342
|
+
if (isError || !data) stop(text || "The server did not send the files. Try again.");
|
|
343
|
+
files.push(...data.files); from = data.next;
|
|
344
|
+
}
|
|
345
|
+
const here = existsSync(dir) ? folderFiles(dir) : {};
|
|
346
|
+
const mine = edits(here, before) ?? [];
|
|
347
|
+
const wanted = new Map(files.map((f) => [f.path, f.text]));
|
|
348
|
+
const clash = mine.filter((p) => wanted.has(p) ? wanted.get(p) !== here[p] : true);
|
|
349
|
+
if (clash.length && !forcing) stop(`These changed here since the last pull: ${clash.slice(0, 8).join(", ")}${clash.length > 8 ? ` and ${clash.length - 8} more` : ""}.\nPush them first (${ME} push ${dir}), or run ${ME} pull ${dir} --force to replace them with the workspace's.`);
|
|
350
|
+
let wrote = 0, removed = 0;
|
|
351
|
+
for (const [p, text] of wanted) {
|
|
352
|
+
const at = join(dir, ...p.split("/"));
|
|
353
|
+
if (here[p] === text) continue;
|
|
354
|
+
mkdirSync(dirname(at), { recursive: true }); writeFileSync(at, text); wrote++;
|
|
355
|
+
}
|
|
356
|
+
// Files the last pull wrote that the workspace no longer has (an article removed in the console) go too.
|
|
357
|
+
for (const p of Object.keys(before?.files ?? {})) if (!wanted.has(p) && existsSync(join(dir, ...p.split("/")))) { rmSync(join(dir, ...p.split("/"))); removed++; }
|
|
358
|
+
// The state file changes only when the files do, so a pull that finds nothing new leaves git clean (ci init's nightly job).
|
|
359
|
+
const hashes = Object.fromEntries([...wanted].map(([p, t]) => [p, hash(t)]));
|
|
360
|
+
if (wrote || removed || !before || JSON.stringify(before.files) !== JSON.stringify(hashes)) {
|
|
361
|
+
writeFileSync(join(dir, STATE), JSON.stringify({ url, pulled: new Date().toISOString(), files: hashes }, null, 2) + "\n");
|
|
362
|
+
}
|
|
363
|
+
const count = (n, one, many) => `${n} ${n === 1 ? one : many}`;
|
|
364
|
+
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/.`);
|
|
365
|
+
if (!before) say(`Change any of them, then ${ME} plan ${dir} shows what would change and ${ME} push ${dir} sends it to Decisions.`);
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
/** Plan a pulled folder, as the server reads it; the same answer import_workspace gives for one file. */
|
|
369
|
+
async function planFolder(dir) {
|
|
370
|
+
const files = folderFiles(dir);
|
|
371
|
+
const state = readState(dir);
|
|
372
|
+
if (state?.url) { const { url } = await access(); if (state.url !== url) stop(`${dir} was pulled from ${state.url}, but you are signed in to ${url}.`); }
|
|
373
|
+
const changed = edits(files, state);
|
|
374
|
+
return tool("import_folder", { files, ...(changed ? { changed } : {}), ...(pruning ? { prune: true } : {}) });
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
async function login(address) {
|
|
378
|
+
if (!address) stop(`Give your console's address, for example ${ME} login https://inbox.example.com`);
|
|
379
|
+
const url = clean(address);
|
|
380
|
+
const server = createServer();
|
|
381
|
+
await new Promise((ok) => server.listen(0, "127.0.0.1", ok));
|
|
382
|
+
const redirect = `http://127.0.0.1:${server.address().port}/callback`;
|
|
383
|
+
let client;
|
|
384
|
+
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(); }
|
|
385
|
+
catch { stop(`Could not reach ${url}. Check the address.`); }
|
|
386
|
+
if (!client.client_id) stop(client.error_description || "That address did not accept the sign-in. Is it your Next console?");
|
|
387
|
+
const verifier = randomBytes(32).toString("base64url"), state = randomBytes(12).toString("base64url");
|
|
388
|
+
const go = new URL(`${url}/oauth/authorize`);
|
|
389
|
+
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);
|
|
390
|
+
say(`Opening your browser to sign in and approve the CLI. If it does not open, go to:\n${go}`);
|
|
391
|
+
const opener = process.platform === "darwin" ? "open" : process.platform === "win32" ? "explorer" : "xdg-open";
|
|
392
|
+
try { spawn(opener, [go.toString()], { stdio: "ignore", detached: true }).on("error", () => {}).unref(); } catch {}
|
|
393
|
+
const back = await new Promise((ok) => {
|
|
394
|
+
const timer = setTimeout(() => ok(null), 5 * 60_000);
|
|
395
|
+
server.on("request", (req, res) => {
|
|
396
|
+
const u = new URL(req.url, redirect);
|
|
397
|
+
if (u.pathname !== "/callback") { res.writeHead(404).end(); return; }
|
|
398
|
+
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>`);
|
|
399
|
+
clearTimeout(timer); ok(u.searchParams);
|
|
400
|
+
});
|
|
401
|
+
});
|
|
402
|
+
server.close();
|
|
403
|
+
if (!back) stop(`Nobody approved it within 5 minutes. Run ${ME} login again.`);
|
|
404
|
+
if (back.get("state") !== state) stop(`The answer did not match this sign-in. Run ${ME} login again.`);
|
|
405
|
+
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.");
|
|
406
|
+
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));
|
|
407
|
+
keep({ url, clientId: client.client_id, access: t.access_token, refresh: t.refresh_token, expiresAt: Date.now() + t.expires_in * 1000, scope: t.scope });
|
|
408
|
+
say(`Signed in to ${url}${t.scope === "read" ? " to look only" : ""}. It shows in Settings, Terminal, AI tools, where you can disconnect it.`);
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
const USAGE = [
|
|
412
|
+
["login <console address>", "sign in from the browser"],
|
|
413
|
+
["export [file]", "the setup as YAML"],
|
|
414
|
+
["pull [folder]", "the setup as a folder of files (agents/, knowledge/, rules/, tests/, apps/)"],
|
|
415
|
+
["plan [folder]", "what the changed folder would change (exit 0 nothing, 2 changes, 1 problems)"],
|
|
416
|
+
["push [folder] [--prune]", "send the folder's changes to Decisions; --prune removes deleted articles and tests"],
|
|
417
|
+
["diff <file|folder>", "what the file would change (exit 0 nothing, 2 changes, 1 problems)"],
|
|
418
|
+
["propose <file|folder>", "send the changes to Decisions for an admin to apply"],
|
|
419
|
+
["", "a folder's Markdown, text and HTML documents become knowledge articles;"],
|
|
420
|
+
["", "in a file, knowledge entries can name file: docs/a.md or files: docs/**/*.md"],
|
|
421
|
+
["<terminal command>", "any console terminal command, such as ME ls unassigned"],
|
|
422
|
+
['run "<command>"', 'the same, in quotes, such as "ls unassigned --inbox Billing"'],
|
|
423
|
+
["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)"],
|
|
424
|
+
["ci init [folder] [--force]", "write a GitHub workflow: check pull requests, propose on merge, and open a pull request when the console changed"],
|
|
425
|
+
["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)"],
|
|
426
|
+
["script <file> [--propose]", "commands, one per line, as one plan; --propose sends it to Decisions"],
|
|
427
|
+
["test", "run the agents' tests and wait (exit 0 all pass, 1 some fail)"],
|
|
428
|
+
["rehearse <file>", "rehearse the agents the file adds or changes on past conversations and wait"],
|
|
429
|
+
["rehearse [plan] [--on 20] [--topic refund]", "show me before it goes live: past conversations and the tests, with a plan and without"],
|
|
430
|
+
["", "(both cost money, and need Tests and rehearsals from CI turned on)"],
|
|
431
|
+
["logout", "forget this computer's sign-in"],
|
|
432
|
+
["update", "how to get the newest version (a downloaded file updates itself)"],
|
|
433
|
+
["help <command>", "one terminal command with an example; ME commands lists them all"],
|
|
434
|
+
];
|
|
435
|
+
/** The usage, naming the command the way it was run, so each line can be copied as it is. */
|
|
436
|
+
export function usage(me = ME) {
|
|
437
|
+
const width = Math.max(...USAGE.map(([u]) => (u ? `${me} ${u}` : "").length)) + 3;
|
|
438
|
+
const lines = USAGE.map(([u, d]) => ` ${(u ? `${me} ${u}` : "").padEnd(width)}${d.replaceAll("ME ", `${me} `)}`);
|
|
439
|
+
return `Next CLI ${VERSION}: your workspace's setup as a file you keep in git.
|
|
440
|
+
|
|
441
|
+
${lines.join("\n")}
|
|
442
|
+
|
|
443
|
+
In CI, set AGENT_INBOX_URL and AGENT_INBOX_TOKEN (a token from Settings, Terminal, AI tools) instead of logging in.
|
|
444
|
+
Add --markdown to diff for a GitHub job summary. Nothing changes until an admin applies it in Decisions.`;
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
// ---- Updates -------------------------------------------------------------------------------------------------------
|
|
448
|
+
/** The CLI version the server offers (GET /api/cli, no sign-in needed), or null when it cannot say. */
|
|
449
|
+
async function offered(url, ms = 5000) {
|
|
450
|
+
try {
|
|
451
|
+
const r = await fetch(`${url}/api/cli`, { signal: AbortSignal.timeout(ms), headers: { "user-agent": `agent-inbox-cli/${VERSION}` } });
|
|
452
|
+
if (!r.ok) return null;
|
|
453
|
+
const v = (await r.json())?.version;
|
|
454
|
+
return typeof v === "string" ? v : null;
|
|
455
|
+
} catch { return null; }
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
/** At most once a day, ask the server whether it has a newer CLI, and say so in one line as the command ends. */
|
|
459
|
+
function notice(url) {
|
|
460
|
+
if (!process.stderr.isTTY || process.env.CI || markdown || cmd === "update") return;
|
|
461
|
+
let last = 0;
|
|
462
|
+
try { last = JSON.parse(readFileSync(CHECKED, "utf8")).at ?? 0; } catch {}
|
|
463
|
+
if (Date.now() - last < 24 * 3600_000) return;
|
|
464
|
+
try { mkdirSync(DIR, { recursive: true, mode: 0o700 }); writeFileSync(CHECKED, JSON.stringify({ at: Date.now() }), { mode: 0o600 }); } catch { return; }
|
|
465
|
+
offered(url, 2000).then((v) => {
|
|
466
|
+
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`));
|
|
467
|
+
});
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
/** What to do to update, for how this copy was installed; a downloaded file is replaced by the server's newest. */
|
|
471
|
+
export function updateAdvice(how, url) {
|
|
472
|
+
if (how === "brew") return "Installed with Homebrew. To update, run: brew upgrade agent-inbox";
|
|
473
|
+
if (how === "npm") return `Installed with npm. To update, run: npm i -g ${PACKAGE}@latest`;
|
|
474
|
+
return `Downloaded from your Next address. To update, download it again: curl -fsSLO ${url || "<your Next address>"}/cli/agent-inbox.mjs`;
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
async function update() {
|
|
478
|
+
const how = installedBy(real(SELF));
|
|
479
|
+
const url = process.env.AGENT_INBOX_URL ? clean(process.env.AGENT_INBOX_URL) : load()?.url;
|
|
480
|
+
const latest = url ? await offered(url) : null;
|
|
481
|
+
if (latest) say(newer(latest, VERSION) ? `Version ${latest} is out; you have ${VERSION}.` : `You have ${VERSION}, the newest version ${url} offers.`);
|
|
482
|
+
if (how !== "file") { say(updateAdvice(how, url)); return; }
|
|
483
|
+
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)}`);
|
|
484
|
+
if (!latest) stop(`Could not ask ${url} for the newest version. Check your connection and try again. ${updateAdvice(how, url)}`);
|
|
485
|
+
if (!newer(latest, VERSION)) return;
|
|
486
|
+
// Replace this file with the server's copy: written beside it first, checked, then moved over it in one step.
|
|
487
|
+
let body;
|
|
488
|
+
try {
|
|
489
|
+
const r = await fetch(`${url}/cli/agent-inbox.mjs`, { signal: AbortSignal.timeout(30_000) });
|
|
490
|
+
body = r.ok ? await r.text() : "";
|
|
491
|
+
} catch { body = ""; }
|
|
492
|
+
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)}`);
|
|
493
|
+
const next = `${SELF}.download`;
|
|
494
|
+
try { writeFileSync(next, body, { mode: 0o755 }); renameSync(next, SELF); }
|
|
495
|
+
catch { rmSync(next, { force: true }); stop(`Could not replace ${SELF}: it may belong to another user. ${updateAdvice(how, url)}`); }
|
|
496
|
+
say(`Updated ${relative(process.cwd(), SELF) || SELF} to ${latest}.`);
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
async function main() {
|
|
500
|
+
switch (cmd) {
|
|
501
|
+
case "login": await login(rest[0]); break;
|
|
502
|
+
case "update": await update(); break;
|
|
503
|
+
case "logout": rmSync(SAVED, { force: true }); say("Signed out on this computer. To disconnect it everywhere, revoke it in Settings, Terminal, AI tools."); break;
|
|
504
|
+
case "export": {
|
|
505
|
+
const { text, isError } = await tool("export_workspace");
|
|
506
|
+
if (isError) stop(text);
|
|
507
|
+
if (rest[0]) { writeFileSync(rest[0], text); say(`Wrote ${rest[0]}.`); } else process.stdout.write(text);
|
|
508
|
+
break;
|
|
509
|
+
}
|
|
510
|
+
case "pull": await pull(rest[0] || "."); break;
|
|
511
|
+
case "plan": case "diff": {
|
|
512
|
+
const dir = cmd === "plan" ? rest[0] || "." : rest[0];
|
|
513
|
+
const folder = dir && existsSync(dir) && statSync(dir).isDirectory() && isPulled(dir);
|
|
514
|
+
if (cmd === "plan" && !folder) stop(`${dir} is not a folder from ${ME} pull (it has no workspace.yaml). Run ${ME} pull ${dir === "." ? "support" : dir} first, or ${ME} diff <file> for one workspace file.`);
|
|
515
|
+
const { text, data } = folder ? await planFolder(dir) : await tool("import_workspace", read(rest[0]));
|
|
516
|
+
const body = text.replace(/^Plan \w+: /, "").replace(/\n*(Nothing has changed|This token can only look)[\s\S]*$/, "").trim();
|
|
517
|
+
if (!data?.ok) { say(markdown ? `### The workspace file has problems\n\n${fence(body)}` : body); process.exit(1); }
|
|
518
|
+
const what = folder ? "folder" : "file";
|
|
519
|
+
// A folder's notes (articles from a website, files with no match) are worth seeing even when nothing changes.
|
|
520
|
+
const notes = folder ? text.split("\n").filter((l) => l.trim() && !/^Nothing would change/.test(l)).join("\n") : "";
|
|
521
|
+
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); }
|
|
522
|
+
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);
|
|
523
|
+
process.exit(2);
|
|
524
|
+
}
|
|
525
|
+
case "push": case "propose": {
|
|
526
|
+
const dir = cmd === "push" ? rest[0] || "." : rest[0];
|
|
527
|
+
const folder = dir && existsSync(dir) && statSync(dir).isDirectory() && isPulled(dir);
|
|
528
|
+
if (cmd === "push" && !folder) stop(`${dir} is not a folder from ${ME} pull (it has no workspace.yaml). Run ${ME} pull first, or ${ME} propose <file> for one workspace file.`);
|
|
529
|
+
const { text, data } = folder ? await planFolder(dir) : await tool("import_workspace", read(rest[0]));
|
|
530
|
+
if (!data?.ok) { say(text); process.exit(1); }
|
|
531
|
+
if (!data.changes) { say(folder ? "Nothing to push: the workspace already matches the folder." : "Nothing to propose: the workspace already matches the file."); if (folder) say(text.split("\n").filter((l) => !/^Nothing would change/.test(l) && l.trim()).join("\n")); break; }
|
|
532
|
+
const sent = await tool("submit_plan", { plan: data.plan });
|
|
533
|
+
if (sent.isError) stop(sent.text);
|
|
534
|
+
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}`);
|
|
535
|
+
if (folder) say(`Once it is applied, ${ME} pull ${dir} brings the folder up to date. Undo it in the console (Decisions, or undo in the terminal).`);
|
|
536
|
+
break;
|
|
537
|
+
}
|
|
538
|
+
case "run": {
|
|
539
|
+
if (!rest.length) stop(`Give a command in quotes, for example ${ME} run "ls unassigned"`);
|
|
540
|
+
const { text, isError } = await tool("terminal", { command: rest.join(" ") });
|
|
541
|
+
say(text); if (isError) process.exit(1);
|
|
542
|
+
break;
|
|
543
|
+
}
|
|
544
|
+
case "tail": {
|
|
545
|
+
// The first page: the last 15 minutes (or --since). In CI or into a file, that page and the line that continues it.
|
|
546
|
+
const first = await tool("terminal", { command: [cmd, ...rest].join(" ") });
|
|
547
|
+
if (first.isError) { say(first.text); process.exit(1); }
|
|
548
|
+
let { body, next } = splitNext(first.text);
|
|
549
|
+
say(body);
|
|
550
|
+
if (!next) process.exit(1);
|
|
551
|
+
if (!process.stdout.isTTY || process.env.CI) { say(`\nTo continue: ${ME} ${next}`); break; }
|
|
552
|
+
if (process.stderr.isTTY) process.stderr.write("Following. Ctrl+C stops.\n");
|
|
553
|
+
let failed = 0;
|
|
554
|
+
for (;;) {
|
|
555
|
+
await new Promise((r) => setTimeout(r, 5000));
|
|
556
|
+
try {
|
|
557
|
+
const page = await tool("terminal", { command: next }, { soft: true });
|
|
558
|
+
if (page.isError) { say(page.text); process.exit(1); }
|
|
559
|
+
failed = 0;
|
|
560
|
+
const got = splitNext(page.text);
|
|
561
|
+
if (got.body && got.body !== "Done.") say(got.body);
|
|
562
|
+
if (!got.next) process.exit(1);
|
|
563
|
+
next = got.next;
|
|
564
|
+
} catch {
|
|
565
|
+
failed += 1;
|
|
566
|
+
if (failed >= 6) stop("Could not reach Next for half a minute, so following stopped. Run tail again to pick up.");
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
case "script": {
|
|
571
|
+
if (!rest[0]) stop(`Give a file of terminal commands, one per line, for example ${ME} script onboarding.txt`);
|
|
572
|
+
let body; try { body = readFileSync(rest[0], "utf8"); } catch { stop(`Could not read ${rest[0]}.`); }
|
|
573
|
+
const got = await tool("run_script", { script: body });
|
|
574
|
+
const isError = got.isError;
|
|
575
|
+
// The server's note to AI tools about submit_plan; the CLI says it in its own words.
|
|
576
|
+
const text = got.text.replace(/\n*Nothing has changed\. An AI tool cannot apply[^\n]*/, "");
|
|
577
|
+
if (isError) { say(text); process.exit(1); }
|
|
578
|
+
const planRef = (/Plan ([0-9a-f]{8})/.exec(text) ?? [])[1];
|
|
579
|
+
if (!planRef) { say(text); break; }
|
|
580
|
+
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); }
|
|
581
|
+
const sent = await tool("submit_plan", { plan: planRef });
|
|
582
|
+
if (sent.isError) stop(sent.text);
|
|
583
|
+
say(markdown ? `### Proposed\n\n${fence(text)}\n\n${sent.text}` : `${text}\n\n${sent.text}`);
|
|
584
|
+
process.exit(2);
|
|
585
|
+
}
|
|
586
|
+
case "--version": case "-v": say(VERSION); break;
|
|
587
|
+
case "check": {
|
|
588
|
+
// A support folder's pull request: what it would change, and a rehearsal of the change.
|
|
589
|
+
const opt = (name) => { const i = rest.indexOf(`--${name}`); return i >= 0 ? rest[i + 1] : undefined; };
|
|
590
|
+
const dir = rest.find((a, i) => !a.startsWith("--") && !(i > 0 && rest[i - 1].startsWith("--"))) || ".";
|
|
591
|
+
if (!existsSync(dir) || !statSync(dir).isDirectory() || !isPulled(dir)) stop(`${dir} is not a folder from ${ME} pull (it has no workspace.yaml).`);
|
|
592
|
+
const { text, data } = await planFolder(dir);
|
|
593
|
+
const plan = text.replace(/\n*(Nothing has changed|This token can only look)[\s\S]*$/, "").replace(/\n+Before +rehearse [^\n]*/g, "").trim();
|
|
594
|
+
if (!data?.ok) { say(`${CHECK_MARK}\n\n## Next: the folder has problems\n\n` + "```\n" + plan + "\n```\n"); process.exit(1); }
|
|
595
|
+
// The rehearsal replays past conversations and runs the saved tests, before and after, in one job.
|
|
596
|
+
let rehearsal = null, skipped = null, blocked = null;
|
|
597
|
+
if (data.changes) {
|
|
598
|
+
const on = Number(opt("on") ?? 20);
|
|
599
|
+
const r = await tool("rehearse", { plan: data.plan, conversations: Number.isInteger(on) && on > 0 ? Math.min(on, 30) : 20 });
|
|
600
|
+
if (r.isError && /are off|look-only/i.test(r.text)) skipped = `Not rehearsed: ${r.text}`;
|
|
601
|
+
else if (r.isError) blocked = r.text;
|
|
602
|
+
else rehearsal = r.data?.job ? await waitJobs([{ job: r.data.job, agent: "This change" }]) : { ok: true, lines: [r.text] };
|
|
603
|
+
}
|
|
604
|
+
const report = checkReport({ plan, changes: data.changes, rehearsal, skipped, blocked });
|
|
605
|
+
say(report.text);
|
|
606
|
+
process.exit(report.failed ? 1 : 0);
|
|
607
|
+
}
|
|
608
|
+
case "ci": {
|
|
609
|
+
// ci init [folder]: write the GitHub workflow for a repository of support files.
|
|
610
|
+
if (rest[0] !== "init") stop(`Use ${ME} ci init [folder], in the repository that holds the folder from ${ME} pull.`);
|
|
611
|
+
const dir = rest[1] || ".";
|
|
612
|
+
if (!existsSync(dir) || !statSync(dir).isDirectory() || !isPulled(dir)) stop(`${dir} is not a folder from ${ME} pull (it has no workspace.yaml). Run ${ME} pull ${dir} first.`);
|
|
613
|
+
const { url } = await access();
|
|
614
|
+
const file = join(".github", "workflows", "next-support.yml");
|
|
615
|
+
if (existsSync(file) && !forcing) stop(`${file} is already there. Add --force to write it again.`);
|
|
616
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
617
|
+
writeFileSync(file, ciWorkflow(url, dir));
|
|
618
|
+
say(`Wrote ${file}.
|
|
619
|
+
|
|
620
|
+
Then:
|
|
621
|
+
1. In Next, an admin makes a personal access token set to Look and propose changes (Settings, Terminal, Plain English and AI tools).
|
|
622
|
+
2. In GitHub, add it as the repository secret AGENT_INBOX_TOKEN.
|
|
623
|
+
3. Commit and push the workflow. Each pull request that changes ${dir === "." ? "the folder" : dir} gets a comment with what it would do.
|
|
624
|
+
4. For rehearsals on pull requests, an admin turns on Tests and rehearsals from CI and AI tools (Settings, AI features). They are charged as tests.`);
|
|
625
|
+
break;
|
|
626
|
+
}
|
|
627
|
+
case "test": case "rehearse": {
|
|
628
|
+
// Start the run, then ask how it stands every few seconds until it is done (asking also moves it along).
|
|
629
|
+
let started;
|
|
630
|
+
if (cmd === "test") started = await tool("run_tests");
|
|
631
|
+
else if (!rest[0] || rest[0].startsWith("--") || (/^[0-9a-f]{4,36}$/i.test(rest[0]) && !existsSync(rest[0]))) {
|
|
632
|
+
// A plan, not a file: rehearse 1a2b3c4d [--on 20] [--topic refund], or your latest plan.
|
|
633
|
+
const plan = rest[0] && !rest[0].startsWith("--") ? rest[0] : undefined;
|
|
634
|
+
const flag = (name) => { const i = rest.indexOf(`--${name}`); return i >= 0 ? rest[i + 1] : undefined; };
|
|
635
|
+
const on = flag("on"), topic = flag("topic") ?? (/^topic=(.+)$/i.exec(on ?? "") ?? [])[1];
|
|
636
|
+
started = await tool("rehearse", { ...(plan ? { plan } : {}), ...(/^\d+$/.test(on ?? "") ? { conversations: Number(on) } : {}), ...(topic ? { topic } : {}) });
|
|
637
|
+
if (!started.isError && started.data?.job) started = { ...started, data: { jobs: [{ job: started.data.job, agent: `plan ${plan ?? "(latest)"}` }] } };
|
|
638
|
+
if (!started.isError) say(started.text);
|
|
639
|
+
} else {
|
|
640
|
+
started = await tool("rehearse_file", { yaml: read(rest[0]).yaml });
|
|
641
|
+
}
|
|
642
|
+
if (started.isError) stop(started.text);
|
|
643
|
+
const jobs = started.data?.jobs ?? [];
|
|
644
|
+
if (!jobs.length) { say(started.text); break; }
|
|
645
|
+
const { ok, lines } = await waitJobs(jobs);
|
|
646
|
+
say(markdown ? `### ${cmd === "test" ? "Agent tests" : "Rehearsal"}: ${ok ? "pass" : "needs a look"}\n\n${lines.map((l) => `- ${l}`).join("\n")}` : lines.join("\n"));
|
|
647
|
+
process.exit(ok ? 0 : 1);
|
|
648
|
+
}
|
|
649
|
+
case "commands": {
|
|
650
|
+
// The terminal's own list: the same commands, and the same help, as the console terminal and AI tools.
|
|
651
|
+
const { text, isError } = await tool("terminal", { command: "help" });
|
|
652
|
+
say(text); if (isError) process.exit(1);
|
|
653
|
+
break;
|
|
654
|
+
}
|
|
655
|
+
case undefined: case "--help": case "-h": say(usage()); break;
|
|
656
|
+
case "help": {
|
|
657
|
+
if (!rest.length) { say(usage()); break; }
|
|
658
|
+
const { text, isError } = await tool("terminal", { command: `help ${rest.join(" ")}` });
|
|
659
|
+
say(text); if (isError) process.exit(1);
|
|
660
|
+
break;
|
|
661
|
+
}
|
|
662
|
+
default: {
|
|
663
|
+
// Anything else is a terminal command, as typed in the console: agent-inbox ls unassigned, agent-inbox agents.
|
|
664
|
+
const { text, isError } = await tool("terminal", { command: [cmd, ...rest].join(" ") });
|
|
665
|
+
say(text); if (isError) process.exit(1);
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
// Run when started as a command; a test can import the helpers above without running anything.
|
|
671
|
+
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": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.9.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
|
+
}
|