@droconnell/agent-inbox-cli 1.5.0 → 1.10.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 +5 -2
- package/agent-inbox.mjs +356 -32
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @droconnell/agent-inbox-cli
|
|
2
2
|
|
|
3
|
-
The command-line tool for **Next**, the customer-support console. It keeps a workspace's setup in a
|
|
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
4
|
|
|
5
5
|
Needs Node 18 or later. No other dependencies.
|
|
6
6
|
|
|
@@ -25,7 +25,10 @@ In CI, set `AGENT_INBOX_URL` and `AGENT_INBOX_TOKEN` (a token from Settings, Ter
|
|
|
25
25
|
## Use it
|
|
26
26
|
|
|
27
27
|
```bash
|
|
28
|
-
agent-inbox
|
|
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
|
|
29
32
|
agent-inbox diff agent-inbox.yaml # what the file would change; changes nothing
|
|
30
33
|
agent-inbox propose agent-inbox.yaml # send the changes to Decisions
|
|
31
34
|
agent-inbox ls unassigned # any console terminal command
|
package/agent-inbox.mjs
CHANGED
|
@@ -6,6 +6,14 @@
|
|
|
6
6
|
//
|
|
7
7
|
// agent-inbox login <console address> sign in from the browser (or set AGENT_INBOX_URL and AGENT_INBOX_TOKEN)
|
|
8
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
|
|
9
17
|
// agent-inbox diff <file|folder> what the file would change; changes nothing (exit 0 none, 2 some, 1 problems)
|
|
10
18
|
// agent-inbox propose <file|folder> send those changes to Decisions, where an admin applies or discards them
|
|
11
19
|
// (a folder: its Markdown, text and HTML documents, as knowledge articles)
|
|
@@ -26,7 +34,7 @@ import { basename, dirname, isAbsolute, join, relative, sep } from "node:path";
|
|
|
26
34
|
import { spawn } from "node:child_process";
|
|
27
35
|
import { fileURLToPath } from "node:url";
|
|
28
36
|
|
|
29
|
-
export const VERSION = "1.
|
|
37
|
+
export const VERSION = "1.10.0";
|
|
30
38
|
/** The npm package; its command is agent-inbox. (The name agent-inbox itself belongs to someone else on npm.) */
|
|
31
39
|
export const PACKAGE = "@droconnell/agent-inbox-cli";
|
|
32
40
|
const DIR = join(process.env.XDG_CONFIG_HOME || join(homedir(), ".config"), "agent-inbox");
|
|
@@ -64,6 +72,8 @@ const args = process.argv.slice(2);
|
|
|
64
72
|
const flag = (n) => { const i = args.indexOf(n); return i >= 0 ? (args.splice(i, 1), true) : false; };
|
|
65
73
|
const markdown = flag("--markdown");
|
|
66
74
|
const proposing = flag("--propose");
|
|
75
|
+
const pruning = flag("--prune");
|
|
76
|
+
const forcing = flag("--force");
|
|
67
77
|
const [cmd, ...rest] = args;
|
|
68
78
|
|
|
69
79
|
const say = (s) => process.stdout.write(s.endsWith("\n") ? s : s + "\n");
|
|
@@ -98,8 +108,11 @@ async function access() {
|
|
|
98
108
|
return { url: s.url, token: s.access };
|
|
99
109
|
}
|
|
100
110
|
|
|
101
|
-
/**
|
|
102
|
-
|
|
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 } = {}) {
|
|
103
116
|
const { url, token } = await access();
|
|
104
117
|
let r;
|
|
105
118
|
try {
|
|
@@ -108,7 +121,8 @@ async function tool(name, args = {}) {
|
|
|
108
121
|
headers: { authorization: `Bearer ${token}`, "content-type": "application/json", accept: "application/json, text/event-stream", "user-agent": `agent-inbox-cli/${VERSION}` },
|
|
109
122
|
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } }),
|
|
110
123
|
});
|
|
111
|
-
} catch { stop(`Could not reach ${url}. Check the address and your connection.`); }
|
|
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");
|
|
112
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.`);
|
|
113
127
|
if (r.status === 403) stop("Only an admin of the workspace can use this.");
|
|
114
128
|
if (r.status === 429) stop("Too many requests just now. Wait a minute and try again.");
|
|
@@ -119,6 +133,128 @@ async function tool(name, args = {}) {
|
|
|
119
133
|
return { text, isError: !!j.result.isError, data: j.result.structuredContent };
|
|
120
134
|
}
|
|
121
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
|
+
|
|
122
258
|
// ---- Knowledge from this computer ----------------------------------------------------------------------------------
|
|
123
259
|
const DOCS = [".md", ".markdown", ".txt", ".html", ".htm"];
|
|
124
260
|
const posix = (p) => p.split(sep).join("/");
|
|
@@ -168,6 +304,99 @@ const read = (path) => {
|
|
|
168
304
|
};
|
|
169
305
|
const fence = (s) => (markdown ? "```\n" + s.replace(/```/g, "'''") + "\n```" : s);
|
|
170
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
|
+
/** The apps whose code or manifest changed since the pull (apps/<name>/app.html, manifest.yaml), by folder name. */
|
|
328
|
+
export function changedApps(files, state) {
|
|
329
|
+
const changed = edits(files, state);
|
|
330
|
+
const names = new Set();
|
|
331
|
+
for (const p of changed ?? []) { const m = /^apps\/([^/]+)\/(app\.html|manifest\.ya?ml)$/.exec(p); if (m) names.add(m[1]); }
|
|
332
|
+
return [...names].filter((n) => files[`apps/${n}/app.html`] !== undefined && (files[`apps/${n}/manifest.yaml`] ?? files[`apps/${n}/manifest.yml`]) !== undefined);
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/** Send each changed app as a draft (propose_app), then remember them as sent, so pushing again does not send them twice. */
|
|
336
|
+
async function pushApps(dir, files) {
|
|
337
|
+
const state = readState(dir);
|
|
338
|
+
const names = changedApps(files, state);
|
|
339
|
+
for (const n of names) {
|
|
340
|
+
const manifestPath = files[`apps/${n}/manifest.yaml`] !== undefined ? `apps/${n}/manifest.yaml` : `apps/${n}/manifest.yml`;
|
|
341
|
+
const sent = await tool("propose_app", { source: files[`apps/${n}/app.html`], manifest: files[manifestPath], note: "Changed in the folder" });
|
|
342
|
+
if (sent.isError) { say(`apps/${n}: ${sent.text}`); process.exitCode = 1; continue; }
|
|
343
|
+
say(sent.text);
|
|
344
|
+
if (state?.files) { state.files[`apps/${n}/app.html`] = hash(files[`apps/${n}/app.html`]); state.files[manifestPath] = hash(files[manifestPath]); }
|
|
345
|
+
}
|
|
346
|
+
if (names.length && state?.files) writeFileSync(join(dir, STATE), JSON.stringify(state, null, 2) + "\n");
|
|
347
|
+
return names.length;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/** Which files differ from the pull: changed or new. Without a record of the pull, it cannot say (null). */
|
|
351
|
+
export function edits(files, state) {
|
|
352
|
+
if (!state?.files) return null;
|
|
353
|
+
return Object.keys(files).filter((p) => state.files[p] !== hash(files[p]));
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
async function pull(dir) {
|
|
357
|
+
const { url } = await access();
|
|
358
|
+
const before = readState(dir);
|
|
359
|
+
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`);
|
|
360
|
+
if (before?.url && before.url !== url) stop(`${dir} was pulled from ${before.url}, not ${url}. Pull into a new folder.`);
|
|
361
|
+
// Every part, then check nothing here would be lost before writing anything.
|
|
362
|
+
const files = [];
|
|
363
|
+
for (let from = 0; from !== null;) {
|
|
364
|
+
const { data, isError, text } = await tool("export_files", { from });
|
|
365
|
+
if (isError || !data) stop(text || "The server did not send the files. Try again.");
|
|
366
|
+
files.push(...data.files); from = data.next;
|
|
367
|
+
}
|
|
368
|
+
const here = existsSync(dir) ? folderFiles(dir) : {};
|
|
369
|
+
const mine = edits(here, before) ?? [];
|
|
370
|
+
const wanted = new Map(files.map((f) => [f.path, f.text]));
|
|
371
|
+
const clash = mine.filter((p) => wanted.has(p) ? wanted.get(p) !== here[p] : true);
|
|
372
|
+
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.`);
|
|
373
|
+
let wrote = 0, removed = 0;
|
|
374
|
+
for (const [p, text] of wanted) {
|
|
375
|
+
const at = join(dir, ...p.split("/"));
|
|
376
|
+
if (here[p] === text) continue;
|
|
377
|
+
mkdirSync(dirname(at), { recursive: true }); writeFileSync(at, text); wrote++;
|
|
378
|
+
}
|
|
379
|
+
// Files the last pull wrote that the workspace no longer has (an article removed in the console) go too.
|
|
380
|
+
for (const p of Object.keys(before?.files ?? {})) if (!wanted.has(p) && existsSync(join(dir, ...p.split("/")))) { rmSync(join(dir, ...p.split("/"))); removed++; }
|
|
381
|
+
// The state file changes only when the files do, so a pull that finds nothing new leaves git clean (ci init's nightly job).
|
|
382
|
+
const hashes = Object.fromEntries([...wanted].map(([p, t]) => [p, hash(t)]));
|
|
383
|
+
if (wrote || removed || !before || JSON.stringify(before.files) !== JSON.stringify(hashes)) {
|
|
384
|
+
writeFileSync(join(dir, STATE), JSON.stringify({ url, pulled: new Date().toISOString(), files: hashes }, null, 2) + "\n");
|
|
385
|
+
}
|
|
386
|
+
const count = (n, one, many) => `${n} ${n === 1 ? one : many}`;
|
|
387
|
+
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/.`);
|
|
388
|
+
if (!before) say(`Change any of them, then ${ME} plan ${dir} shows what would change and ${ME} push ${dir} sends it to Decisions.`);
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/** Plan a pulled folder, as the server reads it; the same answer import_workspace gives for one file. */
|
|
392
|
+
async function planFolder(dir) {
|
|
393
|
+
const files = folderFiles(dir);
|
|
394
|
+
const state = readState(dir);
|
|
395
|
+
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}.`); }
|
|
396
|
+
const changed = edits(files, state);
|
|
397
|
+
return tool("import_folder", { files, ...(changed ? { changed } : {}), ...(pruning ? { prune: true } : {}) });
|
|
398
|
+
}
|
|
399
|
+
|
|
171
400
|
async function login(address) {
|
|
172
401
|
if (!address) stop(`Give your console's address, for example ${ME} login https://inbox.example.com`);
|
|
173
402
|
const url = clean(address);
|
|
@@ -182,8 +411,10 @@ async function login(address) {
|
|
|
182
411
|
const go = new URL(`${url}/oauth/authorize`);
|
|
183
412
|
for (const [k, v] of Object.entries({ response_type: "code", client_id: client.client_id, redirect_uri: redirect, code_challenge: createHash("sha256").update(verifier).digest("base64url"), code_challenge_method: "S256", state, scope: "propose" })) go.searchParams.set(k, v);
|
|
184
413
|
say(`Opening your browser to sign in and approve the CLI. If it does not open, go to:\n${go}`);
|
|
185
|
-
|
|
186
|
-
|
|
414
|
+
// On Windows, explorer drops long addresses like this one; rundll32's URL handler opens the default browser with
|
|
415
|
+
// the whole address, & and all, without a shell in between.
|
|
416
|
+
const [opener, ...how] = process.platform === "darwin" ? ["open"] : process.platform === "win32" ? ["rundll32", "url.dll,FileProtocolHandler"] : ["xdg-open"];
|
|
417
|
+
try { spawn(opener, [...how, go.toString()], { stdio: "ignore", detached: true, windowsHide: true }).on("error", () => {}).unref(); } catch {}
|
|
187
418
|
const back = await new Promise((ok) => {
|
|
188
419
|
const timer = setTimeout(() => ok(null), 5 * 60_000);
|
|
189
420
|
server.on("request", (req, res) => {
|
|
@@ -205,15 +436,23 @@ async function login(address) {
|
|
|
205
436
|
const USAGE = [
|
|
206
437
|
["login <console address>", "sign in from the browser"],
|
|
207
438
|
["export [file]", "the setup as YAML"],
|
|
439
|
+
["pull [folder]", "the setup as a folder of files (agents/, knowledge/, rules/, tests/, apps/)"],
|
|
440
|
+
["plan [folder]", "what the changed folder would change (exit 0 nothing, 2 changes, 1 problems)"],
|
|
441
|
+
["push [folder] [--prune]", "send the folder's changes to Decisions; --prune removes deleted articles and tests"],
|
|
208
442
|
["diff <file|folder>", "what the file would change (exit 0 nothing, 2 changes, 1 problems)"],
|
|
209
443
|
["propose <file|folder>", "send the changes to Decisions for an admin to apply"],
|
|
210
444
|
["", "a folder's Markdown, text and HTML documents become knowledge articles;"],
|
|
211
445
|
["", "in a file, knowledge entries can name file: docs/a.md or files: docs/**/*.md"],
|
|
212
446
|
["<terminal command>", "any console terminal command, such as ME ls unassigned"],
|
|
213
447
|
['run "<command>"', 'the same, in quotes, such as "ls unassigned --inbox Billing"'],
|
|
448
|
+
["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)"],
|
|
449
|
+
["ci init [folder] [--force]", "write a GitHub workflow: check pull requests, propose on merge, and open a pull request when the console changed"],
|
|
450
|
+
["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)"],
|
|
214
451
|
["script <file> [--propose]", "commands, one per line, as one plan; --propose sends it to Decisions"],
|
|
452
|
+
["submit <plan>", "send a plan a change printed to Decisions, for an admin to apply (the CLI never applies)"],
|
|
215
453
|
["test", "run the agents' tests and wait (exit 0 all pass, 1 some fail)"],
|
|
216
454
|
["rehearse <file>", "rehearse the agents the file adds or changes on past conversations and wait"],
|
|
455
|
+
["rehearse [plan] [--on 20] [--topic refund]", "show me before it goes live: past conversations and the tests, with a plan and without"],
|
|
217
456
|
["", "(both cost money, and need Tests and rehearsals from CI turned on)"],
|
|
218
457
|
["logout", "forget this computer's sign-in"],
|
|
219
458
|
["update", "how to get the newest version (a downloaded file updates itself)"],
|
|
@@ -294,21 +533,38 @@ switch (cmd) {
|
|
|
294
533
|
if (rest[0]) { writeFileSync(rest[0], text); say(`Wrote ${rest[0]}.`); } else process.stdout.write(text);
|
|
295
534
|
break;
|
|
296
535
|
}
|
|
297
|
-
case "
|
|
298
|
-
|
|
536
|
+
case "pull": await pull(rest[0] || "."); break;
|
|
537
|
+
case "plan": case "diff": {
|
|
538
|
+
const dir = cmd === "plan" ? rest[0] || "." : rest[0];
|
|
539
|
+
const folder = dir && existsSync(dir) && statSync(dir).isDirectory() && isPulled(dir);
|
|
540
|
+
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.`);
|
|
541
|
+
const { text, data } = folder ? await planFolder(dir) : await tool("import_workspace", read(rest[0]));
|
|
299
542
|
const body = text.replace(/^Plan \w+: /, "").replace(/\n*(Nothing has changed|This token can only look)[\s\S]*$/, "").trim();
|
|
300
543
|
if (!data?.ok) { say(markdown ? `### The workspace file has problems\n\n${fence(body)}` : body); process.exit(1); }
|
|
301
|
-
|
|
544
|
+
const what = folder ? "folder" : "file";
|
|
545
|
+
// Changed apps are not in the plan: push sends each as a draft.
|
|
546
|
+
const apps = folder ? changedApps(folderFiles(dir), readState(dir)) : [];
|
|
547
|
+
if (apps.length) say(`${apps.length === 1 ? "1 app" : `${apps.length} apps`} changed (${apps.map((n) => `apps/${n}`).join(", ")}): ${ME} push sends ${apps.length === 1 ? "it" : "each"} as a draft for an admin to publish.`);
|
|
548
|
+
// A folder's notes (articles from a website, files with no match) are worth seeing even when nothing changes.
|
|
549
|
+
const notes = folder ? text.split("\n").filter((l) => l.trim() && !/^Nothing would change/.test(l)).join("\n") : "";
|
|
550
|
+
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); }
|
|
302
551
|
say(markdown ? `### ${data.changes === 1 ? "1 change" : `${data.changes} changes`} to the workspace\n\n${fence(body)}\n\nMerging proposes these; an admin applies them in Decisions.` : body);
|
|
303
552
|
process.exit(2);
|
|
304
553
|
}
|
|
305
|
-
case "propose": {
|
|
306
|
-
const
|
|
554
|
+
case "push": case "propose": {
|
|
555
|
+
const dir = cmd === "push" ? rest[0] || "." : rest[0];
|
|
556
|
+
const folder = dir && existsSync(dir) && statSync(dir).isDirectory() && isPulled(dir);
|
|
557
|
+
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.`);
|
|
558
|
+
// Apps whose code or manifest changed go first, each as a draft for an admin to publish.
|
|
559
|
+
const appsSent = folder ? await pushApps(dir, folderFiles(dir)) : 0;
|
|
560
|
+
const { text, data } = folder ? await planFolder(dir) : await tool("import_workspace", read(rest[0]));
|
|
307
561
|
if (!data?.ok) { say(text); process.exit(1); }
|
|
308
|
-
if (!data.changes
|
|
562
|
+
if (!data.changes && appsSent) break;
|
|
563
|
+
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; }
|
|
309
564
|
const sent = await tool("submit_plan", { plan: data.plan });
|
|
310
565
|
if (sent.isError) stop(sent.text);
|
|
311
|
-
say(markdown ? `### Proposed ${data.changes === 1 ? "1 change" : `${data.changes} changes`}\n\n${sent.text}` : sent.text);
|
|
566
|
+
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}`);
|
|
567
|
+
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).`);
|
|
312
568
|
break;
|
|
313
569
|
}
|
|
314
570
|
case "run": {
|
|
@@ -317,6 +573,32 @@ switch (cmd) {
|
|
|
317
573
|
say(text); if (isError) process.exit(1);
|
|
318
574
|
break;
|
|
319
575
|
}
|
|
576
|
+
case "tail": {
|
|
577
|
+
// The first page: the last 15 minutes (or --since). In CI or into a file, that page and the line that continues it.
|
|
578
|
+
const first = await tool("terminal", { command: [cmd, ...rest].join(" ") });
|
|
579
|
+
if (first.isError) { say(first.text); process.exit(1); }
|
|
580
|
+
let { body, next } = splitNext(first.text);
|
|
581
|
+
say(body);
|
|
582
|
+
if (!next) process.exit(1);
|
|
583
|
+
if (!process.stdout.isTTY || process.env.CI) { say(`\nTo continue: ${ME} ${next}`); break; }
|
|
584
|
+
if (process.stderr.isTTY) process.stderr.write("Following. Ctrl+C stops.\n");
|
|
585
|
+
let failed = 0;
|
|
586
|
+
for (;;) {
|
|
587
|
+
await new Promise((r) => setTimeout(r, 5000));
|
|
588
|
+
try {
|
|
589
|
+
const page = await tool("terminal", { command: next }, { soft: true });
|
|
590
|
+
if (page.isError) { say(page.text); process.exit(1); }
|
|
591
|
+
failed = 0;
|
|
592
|
+
const got = splitNext(page.text);
|
|
593
|
+
if (got.body && got.body !== "Done.") say(got.body);
|
|
594
|
+
if (!got.next) process.exit(1);
|
|
595
|
+
next = got.next;
|
|
596
|
+
} catch {
|
|
597
|
+
failed += 1;
|
|
598
|
+
if (failed >= 6) stop("Could not reach Next for half a minute, so following stopped. Run tail again to pick up.");
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
}
|
|
320
602
|
case "script": {
|
|
321
603
|
if (!rest[0]) stop(`Give a file of terminal commands, one per line, for example ${ME} script onboarding.txt`);
|
|
322
604
|
let body; try { body = readFileSync(rest[0], "utf8"); } catch { stop(`Could not read ${rest[0]}.`); }
|
|
@@ -334,33 +616,65 @@ switch (cmd) {
|
|
|
334
616
|
process.exit(2);
|
|
335
617
|
}
|
|
336
618
|
case "--version": case "-v": say(VERSION); break;
|
|
619
|
+
case "check": {
|
|
620
|
+
// A support folder's pull request: what it would change, and a rehearsal of the change.
|
|
621
|
+
const opt = (name) => { const i = rest.indexOf(`--${name}`); return i >= 0 ? rest[i + 1] : undefined; };
|
|
622
|
+
const dir = rest.find((a, i) => !a.startsWith("--") && !(i > 0 && rest[i - 1].startsWith("--"))) || ".";
|
|
623
|
+
if (!existsSync(dir) || !statSync(dir).isDirectory() || !isPulled(dir)) stop(`${dir} is not a folder from ${ME} pull (it has no workspace.yaml).`);
|
|
624
|
+
const { text, data } = await planFolder(dir);
|
|
625
|
+
const plan = text.replace(/\n*(Nothing has changed|This token can only look)[\s\S]*$/, "").replace(/\n+Before +rehearse [^\n]*/g, "").trim();
|
|
626
|
+
if (!data?.ok) { say(`${CHECK_MARK}\n\n## Next: the folder has problems\n\n` + "```\n" + plan + "\n```\n"); process.exit(1); }
|
|
627
|
+
// The rehearsal replays past conversations and runs the saved tests, before and after, in one job.
|
|
628
|
+
let rehearsal = null, skipped = null, blocked = null;
|
|
629
|
+
if (data.changes) {
|
|
630
|
+
const on = Number(opt("on") ?? 20);
|
|
631
|
+
const r = await tool("rehearse", { plan: data.plan, conversations: Number.isInteger(on) && on > 0 ? Math.min(on, 30) : 20 });
|
|
632
|
+
if (r.isError && /are off|look-only/i.test(r.text)) skipped = `Not rehearsed: ${r.text}`;
|
|
633
|
+
else if (r.isError) blocked = r.text;
|
|
634
|
+
else rehearsal = r.data?.job ? await waitJobs([{ job: r.data.job, agent: "This change" }]) : { ok: true, lines: [r.text] };
|
|
635
|
+
}
|
|
636
|
+
const report = checkReport({ plan, changes: data.changes, rehearsal, skipped, blocked });
|
|
637
|
+
say(report.text);
|
|
638
|
+
process.exit(report.failed ? 1 : 0);
|
|
639
|
+
}
|
|
640
|
+
case "ci": {
|
|
641
|
+
// ci init [folder]: write the GitHub workflow for a repository of support files.
|
|
642
|
+
if (rest[0] !== "init") stop(`Use ${ME} ci init [folder], in the repository that holds the folder from ${ME} pull.`);
|
|
643
|
+
const dir = rest[1] || ".";
|
|
644
|
+
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.`);
|
|
645
|
+
const { url } = await access();
|
|
646
|
+
const file = join(".github", "workflows", "next-support.yml");
|
|
647
|
+
if (existsSync(file) && !forcing) stop(`${file} is already there. Add --force to write it again.`);
|
|
648
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
649
|
+
writeFileSync(file, ciWorkflow(url, dir));
|
|
650
|
+
say(`Wrote ${file}.
|
|
651
|
+
|
|
652
|
+
Then:
|
|
653
|
+
1. In Next, an admin makes a personal access token set to Look and propose changes (Settings, Terminal, Plain English and AI tools).
|
|
654
|
+
2. In GitHub, add it as the repository secret AGENT_INBOX_TOKEN.
|
|
655
|
+
3. Commit and push the workflow. Each pull request that changes ${dir === "." ? "the folder" : dir} gets a comment with what it would do.
|
|
656
|
+
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.`);
|
|
657
|
+
break;
|
|
658
|
+
}
|
|
337
659
|
case "test": case "rehearse": {
|
|
338
660
|
// Start the run, then ask how it stands every few seconds until it is done (asking also moves it along).
|
|
339
661
|
let started;
|
|
340
662
|
if (cmd === "test") started = await tool("run_tests");
|
|
341
|
-
else {
|
|
342
|
-
|
|
663
|
+
else if (!rest[0] || rest[0].startsWith("--") || (/^[0-9a-f]{4,36}$/i.test(rest[0]) && !existsSync(rest[0]))) {
|
|
664
|
+
// A plan, not a file: rehearse 1a2b3c4d [--on 20] [--topic refund], or your latest plan.
|
|
665
|
+
const plan = rest[0] && !rest[0].startsWith("--") ? rest[0] : undefined;
|
|
666
|
+
const flag = (name) => { const i = rest.indexOf(`--${name}`); return i >= 0 ? rest[i + 1] : undefined; };
|
|
667
|
+
const on = flag("on"), topic = flag("topic") ?? (/^topic=(.+)$/i.exec(on ?? "") ?? [])[1];
|
|
668
|
+
started = await tool("rehearse", { ...(plan ? { plan } : {}), ...(/^\d+$/.test(on ?? "") ? { conversations: Number(on) } : {}), ...(topic ? { topic } : {}) });
|
|
669
|
+
if (!started.isError && started.data?.job) started = { ...started, data: { jobs: [{ job: started.data.job, agent: `plan ${plan ?? "(latest)"}` }] } };
|
|
670
|
+
if (!started.isError) say(started.text);
|
|
671
|
+
} else {
|
|
343
672
|
started = await tool("rehearse_file", { yaml: read(rest[0]).yaml });
|
|
344
673
|
}
|
|
345
674
|
if (started.isError) stop(started.text);
|
|
346
675
|
const jobs = started.data?.jobs ?? [];
|
|
347
676
|
if (!jobs.length) { say(started.text); break; }
|
|
348
|
-
const lines =
|
|
349
|
-
let ok = true;
|
|
350
|
-
for (const { job, agent } of jobs) {
|
|
351
|
-
const until = Date.now() + 15 * 60_000;
|
|
352
|
-
let s;
|
|
353
|
-
for (;;) {
|
|
354
|
-
s = await tool("check_status", { job });
|
|
355
|
-
if (s.data?.state !== "running") break;
|
|
356
|
-
if (Date.now() > until) stop(`Still running after 15 minutes: ${agent}. See Jobs in the console.`);
|
|
357
|
-
if (!markdown && process.stderr.isTTY) process.stderr.write(`\r${agent}: ${s.text}`.padEnd(80).slice(0, 80));
|
|
358
|
-
await new Promise((r) => setTimeout(r, 5000));
|
|
359
|
-
}
|
|
360
|
-
if (!markdown && process.stderr.isTTY) process.stderr.write("\r".padEnd(81) + "\r");
|
|
361
|
-
if (s.data?.passed === false) ok = false;
|
|
362
|
-
lines.push(`${agent}: ${s.text}`);
|
|
363
|
-
}
|
|
677
|
+
const { ok, lines } = await waitJobs(jobs);
|
|
364
678
|
say(markdown ? `### ${cmd === "test" ? "Agent tests" : "Rehearsal"}: ${ok ? "pass" : "needs a look"}\n\n${lines.map((l) => `- ${l}`).join("\n")}` : lines.join("\n"));
|
|
365
679
|
process.exit(ok ? 0 : 1);
|
|
366
680
|
}
|
|
@@ -377,10 +691,20 @@ switch (cmd) {
|
|
|
377
691
|
say(text); if (isError) process.exit(1);
|
|
378
692
|
break;
|
|
379
693
|
}
|
|
694
|
+
case "submit": {
|
|
695
|
+
// A plan a change made here, sent to Decisions for an admin to apply.
|
|
696
|
+
if (!rest[0]) stop(`Give the plan to send, for example ${ME} submit 1a2b3c4d (the reference a change printed).`);
|
|
697
|
+
const sent = await tool("submit_plan", { plan: rest[0] });
|
|
698
|
+
say(sent.text); if (sent.isError) process.exit(1);
|
|
699
|
+
break;
|
|
700
|
+
}
|
|
380
701
|
default: {
|
|
381
702
|
// Anything else is a terminal command, as typed in the console: agent-inbox ls unassigned, agent-inbox agents.
|
|
382
703
|
const { text, isError } = await tool("terminal", { command: [cmd, ...rest].join(" ") });
|
|
383
|
-
|
|
704
|
+
// A change is only a plan from here. The server's note is written for AI tools; the CLI says what a person can do.
|
|
705
|
+
const plan = (/Plan ([0-9a-f]{8})/.exec(text) ?? [])[1];
|
|
706
|
+
say(plan ? text.replace(/Nothing has changed\. An AI tool cannot apply a change:[^\n]*/, `Nothing has changed. Apply it in the console's terminal (Ctrl+\` on any page, then apply ${plan}), or send it to Decisions for an admin with ${ME} submit ${plan}.`) : text);
|
|
707
|
+
if (isError) process.exit(1);
|
|
384
708
|
}
|
|
385
709
|
}
|
|
386
710
|
}
|
package/package.json
CHANGED