@droconnell/agent-inbox-cli 2.7.0 → 2.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/agent-inbox.mjs +316 -23
- package/package.json +1 -1
package/agent-inbox.mjs
CHANGED
|
@@ -13,6 +13,8 @@
|
|
|
13
13
|
// agent-inbox plan [folder] what the changed folder would change; changes nothing (exit 0 none, 2 some, 1 problems)
|
|
14
14
|
// agent-inbox push [folder] [--prune] send those changes to Approvals; --prune also removes articles and tests
|
|
15
15
|
// whose files you deleted
|
|
16
|
+
// agent-inbox dev [agent] in your support folder: talk to the agent as the folder's unpushed files have
|
|
17
|
+
// it; each save reloads it; --replay <ticket> answers a past conversation again
|
|
16
18
|
// agent-inbox check [folder] for a pull request: the plan and a rehearsal of it, as markdown (exit 1 needs a look)
|
|
17
19
|
// agent-inbox ci init [folder] write the GitHub workflow that checks pull requests, proposes on merge, and
|
|
18
20
|
// opens a pull request when someone changed the setup in the console
|
|
@@ -40,7 +42,7 @@ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "nod
|
|
|
40
42
|
import { spawn, spawnSync } from "node:child_process";
|
|
41
43
|
import { fileURLToPath } from "node:url";
|
|
42
44
|
|
|
43
|
-
export const VERSION = "2.
|
|
45
|
+
export const VERSION = "2.10.0";
|
|
44
46
|
/** The npm package; its command is agent-inbox. (The name agent-inbox itself belongs to someone else on npm.) */
|
|
45
47
|
export const PACKAGE = "@droconnell/agent-inbox-cli";
|
|
46
48
|
const DIR = join(process.env.XDG_CONFIG_HOME || join(homedir(), ".config"), "agent-inbox");
|
|
@@ -93,7 +95,7 @@ const fieldsArg = take("--fields", true);
|
|
|
93
95
|
const urlArg = take("--url", true);
|
|
94
96
|
const tokenArg = take("--token", true);
|
|
95
97
|
/** The CLI's own commands. Anything else is a terminal command, sent as typed. */
|
|
96
|
-
export const OWN = new Set(["login", "logout", "update", "export", "pull", "plan", "diff", "push", "propose", "run", "tail", "script", "check", "ci", "test", "rehearse", "commands", "help", "submit",
|
|
98
|
+
export const OWN = new Set(["login", "logout", "update", "export", "pull", "plan", "diff", "push", "propose", "run", "tail", "script", "check", "ci", "test", "rehearse", "commands", "help", "submit", "dev",
|
|
97
99
|
"whoami", "policy", "audit", "mcp", "claude", "init", "connect", "app", "events", "listen", "completion", "__complete", "--version", "-v", "--help", "-h"]);
|
|
98
100
|
const first = args[0];
|
|
99
101
|
// plan, diff and run are also terminal commands: the CLI's own only for a folder or file that is there (plan, diff) or
|
|
@@ -243,6 +245,252 @@ async function waitJobs(jobs) {
|
|
|
243
245
|
return { ok, lines, data };
|
|
244
246
|
}
|
|
245
247
|
|
|
248
|
+
// ---- Talk to an agent as the folder has it: agent-inbox dev ---------------------------------------------------------
|
|
249
|
+
/**
|
|
250
|
+
* agent-inbox dev [agent] (prd/agent-dev.md): a chat in the terminal with the agent as this folder's unpushed files
|
|
251
|
+
* have it. Each turn sends the folder and the chat to Next (dev_answer), which answers in a throwaway test conversation;
|
|
252
|
+
* a save reloads the draft for the next answer. Each turn is charged as tests.
|
|
253
|
+
*/
|
|
254
|
+
export const DEV_COMMANDS = { reset: "start the chat again (the folder stays as it is)", why: "why the last answer said what it said (free)", "save-test": "keep the last question as a test in tests/ (add what it must do after it)", quit: "stop" };
|
|
255
|
+
|
|
256
|
+
/** A line typed in dev: a command (/why) or a message for the agent. "//" starts a message that begins with a slash. */
|
|
257
|
+
export function parseDevLine(line) {
|
|
258
|
+
const s = String(line ?? "").trim();
|
|
259
|
+
if (!s) return { kind: "empty" };
|
|
260
|
+
if (s.startsWith("//")) return { kind: "say", text: s.slice(1) };
|
|
261
|
+
const m = /^\/([a-z-]+)(?:\s+([\s\S]*))?$/i.exec(s);
|
|
262
|
+
if (!m) return { kind: "say", text: s };
|
|
263
|
+
const word = m[1].toLowerCase();
|
|
264
|
+
const name = word === "exit" || word === "q" ? "quit" : word === "savetest" || word === "save" ? "save-test" : word === "help" || word === "?" ? "help" : word;
|
|
265
|
+
if (name !== "help" && !(name in DEV_COMMANDS)) return { kind: "unknown", word: `/${word}` };
|
|
266
|
+
return { kind: "command", name, arg: (m[2] ?? "").trim() };
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/** The most customer messages one replay answers: each one is a turn. */
|
|
270
|
+
export const REPLAY_MAX = 20;
|
|
271
|
+
|
|
272
|
+
/**
|
|
273
|
+
* A past conversation (read_conversation) as turns to answer again: each customer message, the conversation as it was
|
|
274
|
+
* before it (customer and team lines; notes and system lines left out), and what was said back then, if anything.
|
|
275
|
+
*/
|
|
276
|
+
export function replayPairs(thread) {
|
|
277
|
+
const lines = (thread?.messages ?? []).filter((m) => !m.note && (m.role === "customer" || m.role === "agent" || m.role === "operator") && String(m.text ?? "").trim());
|
|
278
|
+
const pairs = [];
|
|
279
|
+
for (let i = 0; i < lines.length && pairs.length < REPLAY_MAX; i++) {
|
|
280
|
+
if (lines[i].role !== "customer") continue;
|
|
281
|
+
// Two customer messages in a row are answered together, as the agent would have met them.
|
|
282
|
+
let j = i;
|
|
283
|
+
while (lines[j + 1]?.role === "customer") j++;
|
|
284
|
+
const history = lines.slice(0, j + 1).map((m) => ({ role: m.role === "customer" ? "customer" : "agent", text: m.text }));
|
|
285
|
+
const back = lines[j + 1] && lines[j + 1].role !== "customer" ? lines[j + 1] : null;
|
|
286
|
+
// Went to a person: a teammate wrote before the customer's next message, even after the agent's reply.
|
|
287
|
+
let k = j + 1;
|
|
288
|
+
while (lines[k] && lines[k].role !== "customer" && lines[k].role !== "operator") k++;
|
|
289
|
+
const handed = Boolean(lines[k] && lines[k].role === "operator");
|
|
290
|
+
pairs.push({ customer: lines.slice(i, j + 1).map((m) => m.text).join("\n"), history, then: back ? { who: back.author || (back.role === "agent" ? "the agent" : "a teammate"), byAgent: back.role === "agent", handed, text: back.text } : null });
|
|
291
|
+
i = j;
|
|
292
|
+
}
|
|
293
|
+
return pairs;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/** How the new answer differs from the old in kind: the only differences that count, as a rehearsal's. */
|
|
297
|
+
export function replayKind(then, now) {
|
|
298
|
+
if (!then) return "same";
|
|
299
|
+
const before = then.byAgent && !then.handed ? "answered" : "person";
|
|
300
|
+
if (now.handedOff && before === "answered") return "now handed to a person";
|
|
301
|
+
if (!now.handedOff && before === "person") return "now answered";
|
|
302
|
+
return "same";
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/** A test file for the last question, as tests/<question>.yaml in the folder (the format pull writes). */
|
|
306
|
+
export function devTestFile(question, { handedOff = false, must = "" } = {}, exists = () => false) {
|
|
307
|
+
const slug = String(question).normalize("NFKD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60).replace(/-+$/, "") || "untitled";
|
|
308
|
+
let path = `tests/${slug}.yaml`;
|
|
309
|
+
for (let n = 2; exists(path); n++) path = `tests/${slug}-${n}.yaml`;
|
|
310
|
+
// JSON strings are YAML too: quotes, colons and new lines stay exactly as typed.
|
|
311
|
+
const text = `question: ${JSON.stringify(String(question).trim())}\nexpect: ${handedOff ? "escalate" : "answer"}\n${must.trim() ? `must: ${JSON.stringify(must.trim())}\n` : ""}`;
|
|
312
|
+
return { path, text };
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
const usd = (micros) => `$${(micros / 1e6).toFixed(micros < 100_000 ? 3 : 2)}`;
|
|
316
|
+
const SUPPORT = { strong: "strong support", partial: "partly supported", none: "not from the knowledge" };
|
|
317
|
+
|
|
318
|
+
/** The quiet lines under an answer: what it read, followed and would do, and what it cost. */
|
|
319
|
+
export function answerLines(a) {
|
|
320
|
+
const out = [];
|
|
321
|
+
for (const r of a.read ?? []) out.push(`read ${r.title}${r.quote ? `: “${r.quote}”` : ""}`);
|
|
322
|
+
if (!(a.read ?? []).length && (a.alsoSeen ?? []).length) out.push(`saw ${a.alsoSeen.join(", ")} (did not draw on them)`);
|
|
323
|
+
for (const p of a.followed ?? []) out.push(`followed ${p} (procedure)`);
|
|
324
|
+
for (const w of a.wouldDo ?? []) out.push(`would do ${w.replace(/^Would have (done|asked the team to approve): /, (m, k) => (k === "done" ? "" : "ask first: "))} (dry run)`);
|
|
325
|
+
out.push(`cost ${usd(a.micros ?? 0)} · ${a.handedOff ? `handed to a person${a.reason ? `: ${a.reason}` : ""}` : `answered${a.support ? `, ${SUPPORT[a.support] ?? a.support}` : ""}`}`);
|
|
326
|
+
return out;
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/** /why: the last answer explained from what it recorded. No model is asked, so it is free and cannot make a reason up. */
|
|
330
|
+
export function whyText(a, setup) {
|
|
331
|
+
if (!a) return "Nothing to explain yet: ask something first.";
|
|
332
|
+
const lines = [`Why ${a.agent} said that:`];
|
|
333
|
+
if (setup && !setup.unchanged) lines.push(`- It answered with this folder's changes: ${setup.trying.join("; ")}.`);
|
|
334
|
+
else if (setup) lines.push("- The folder changes nothing it says, so it answered as things are in Next.");
|
|
335
|
+
lines.push(a.searches?.length ? `- It searched the knowledge for: ${a.searches.map((q) => `“${q}”`).join(", ")}.` : "- It did not search the knowledge.");
|
|
336
|
+
if (a.read?.length) lines.push(`- The answer rests on ${a.read.map((r) => r.title).join(", ")} (${SUPPORT[a.support] ?? "support unknown"}).`);
|
|
337
|
+
else if (a.support === "none" && !a.handedOff) lines.push("- Nothing it read supports the answer: it came from the instructions, or it is a guess. Add an article if it should know this.");
|
|
338
|
+
if (a.alsoSeen?.length) lines.push(`- It also saw ${a.alsoSeen.join(", ")}, and did not draw on ${a.alsoSeen.length === 1 ? "it" : "them"}.`);
|
|
339
|
+
if (a.followed?.length) lines.push(`- It followed the procedure ${a.followed.join(", ")}.`);
|
|
340
|
+
for (const w of a.wouldDo ?? []) lines.push(`- ${w}. Only recorded, nothing ran.`);
|
|
341
|
+
if (a.handedOff) lines.push(`- It handed the conversation to a person${a.reason ? `: ${a.reason}` : ""}.`);
|
|
342
|
+
if (a.steps?.length) lines.push(`- What it did, in order: ${a.steps.join("; ")}.`);
|
|
343
|
+
return lines.join("\n");
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/** Two texts side by side in columns, each wrapped to its width, for a wide terminal. */
|
|
347
|
+
export function sideBySide(left, right, width = 100) {
|
|
348
|
+
const col = Math.max(20, Math.floor((width - 3) / 2));
|
|
349
|
+
const wrap = (text) => {
|
|
350
|
+
const out = [];
|
|
351
|
+
for (const para of String(text).split("\n")) {
|
|
352
|
+
let line = "";
|
|
353
|
+
for (const word of para.split(/\s+/).filter(Boolean)) {
|
|
354
|
+
const w = word.length > col ? `${word.slice(0, col - 1)}…` : word;
|
|
355
|
+
if (line && line.length + 1 + w.length > col) { out.push(line); line = w; } else line = line ? `${line} ${w}` : w;
|
|
356
|
+
}
|
|
357
|
+
out.push(line);
|
|
358
|
+
}
|
|
359
|
+
return out;
|
|
360
|
+
};
|
|
361
|
+
const a = wrap(left), b = wrap(right);
|
|
362
|
+
return Array.from({ length: Math.max(a.length, b.length) }, (_, i) => `${(a[i] ?? "").padEnd(col)} │ ${b[i] ?? ""}`.trimEnd()).join("\n");
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/**
|
|
366
|
+
* Watch the folder and call `changed` once a burst of saves has settled (editors write a file in several steps).
|
|
367
|
+
* Hidden files (.git, the pull's state file) and node_modules are left out. `watch` is node:fs's, or a stand-in in tests.
|
|
368
|
+
*/
|
|
369
|
+
export function watchFolder(dir, changed, { watch, wait = 400, timers = { setTimeout, clearTimeout } } = {}) {
|
|
370
|
+
let timer = null;
|
|
371
|
+
const seen = new Set();
|
|
372
|
+
const handle = (_event, name) => {
|
|
373
|
+
const file = name ? posix(String(name)) : "";
|
|
374
|
+
if (file && file.split("/").some((p) => p.startsWith(".") || p === "node_modules")) return;
|
|
375
|
+
if (file) seen.add(file);
|
|
376
|
+
timers.clearTimeout(timer);
|
|
377
|
+
timer = timers.setTimeout(() => { const files = [...seen]; seen.clear(); changed(files); }, wait);
|
|
378
|
+
};
|
|
379
|
+
let watcher;
|
|
380
|
+
try { watcher = watch(dir, { recursive: true }, handle); }
|
|
381
|
+
catch { watcher = watch(dir, handle); } // older systems without recursive watching: the top of the folder only
|
|
382
|
+
return { close: () => { timers.clearTimeout(timer); watcher?.close?.(); } };
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
async function devCommand(words) {
|
|
386
|
+
const { createInterface } = await import("node:readline");
|
|
387
|
+
const folder = valueOf(words, "--folder") ?? ".";
|
|
388
|
+
const replayRef = valueOf(words, "--replay");
|
|
389
|
+
const yes = words.includes("--yes");
|
|
390
|
+
// A shell drops an unquoted #1042 as a comment: say so rather than start a chat.
|
|
391
|
+
if (words.includes("--replay") && (!replayRef || replayRef.startsWith("--"))) stop(`Name the conversation to replay: its ticket number (${ME} dev --replay 1042) or the 8 characters ls shows.`);
|
|
392
|
+
const skip = new Set(["--folder", "--replay"]);
|
|
393
|
+
const agent = words.filter((w, i) => !w.startsWith("--") && !skip.has(words[i - 1])).join(" ").trim() || undefined;
|
|
394
|
+
if (!existsSync(folder) || !statSync(folder).isDirectory() || !isPulled(folder)) stop(`${folder === "." ? "This folder" : folder} is not a folder from ${ME} pull (it has no workspace.yaml). Run it in your support folder, or name it with --folder.`);
|
|
395
|
+
const state = readState(folder);
|
|
396
|
+
if (state?.url) { const { url } = await access(); if (state.url !== url) stop(`${folder} was pulled from ${state.url}, but you are signed in to ${url}.`); }
|
|
397
|
+
const color = process.stdout.isTTY && !process.env.NO_COLOR;
|
|
398
|
+
const dim = (s) => (color ? `\x1b[2m${s}\x1b[22m` : s);
|
|
399
|
+
const bold = (s) => (color ? `\x1b[1m${s}\x1b[22m` : s);
|
|
400
|
+
const folderNow = () => { const files = folderFiles(folder); const changed = edits(files, readState(folder)); return { files, ...(changed ? { changed } : {}) }; };
|
|
401
|
+
const ask = (args) => tool("dev_answer", { ...folderNow(), ...(agent ? { agent } : {}), ...args });
|
|
402
|
+
|
|
403
|
+
// Who answers, what it tries and the price of a turn: free, and the switch is checked before anything is charged.
|
|
404
|
+
const first = await ask({});
|
|
405
|
+
if (first.isError) stop(first.text);
|
|
406
|
+
let setup = first.data?.setup;
|
|
407
|
+
if (!setup) stop("Next did not answer as expected. Update the CLI or Next, and try again.");
|
|
408
|
+
const intro = () => `${setup.agent} answers ${setup.unchanged ? "as things are in Next: this folder changes nothing it says" : `as this folder has it, unpushed: ${setup.trying.join("; ")}`}.${setup.notTried.length ? ` Not tried: ${setup.notTried.join("; ")}.` : ""}`;
|
|
409
|
+
if (first.data.off) { say(`${intro()}\n\n${first.data.off}`); process.exit(1); }
|
|
410
|
+
const price = `About $${setup.usd.toFixed(2)} a turn, charged as tests.`;
|
|
411
|
+
|
|
412
|
+
if (replayRef) {
|
|
413
|
+
const got = await tool("read_conversation", { conversation: replayRef.replace(/^ticket\s*/i, "") });
|
|
414
|
+
if (got.isError || !got.data) stop(got.text || `There is no conversation ${replayRef} that you can open.`);
|
|
415
|
+
const pairs = replayPairs(got.data);
|
|
416
|
+
if (!pairs.length) stop(`${replayRef} has no customer messages to answer again.`);
|
|
417
|
+
const name = got.data.number ? `#${got.data.number}` : got.data.ref;
|
|
418
|
+
say(`${intro()}\nReplaying ${name}: ${pairs.length === 1 ? "1 customer message" : `${pairs.length} customer messages`}, about $${(setup.usd * pairs.length).toFixed(2)}, charged as tests.`);
|
|
419
|
+
if (!yes) {
|
|
420
|
+
if (!process.stdin.isTTY) stop("Add --yes to start it.");
|
|
421
|
+
const ok = await new Promise((done) => { const rl = createInterface({ input: process.stdin, output: process.stderr }); rl.question("Go ahead? (y/N) ", (a) => { rl.close(); done(/^y/i.test(a.trim())); }); });
|
|
422
|
+
if (!ok) { say("Not replayed."); return; }
|
|
423
|
+
}
|
|
424
|
+
const width = process.stdout.columns ?? 80;
|
|
425
|
+
const counts = { "now answered": 0, "now handed to a person": 0, same: 0 };
|
|
426
|
+
for (const [n, p] of pairs.entries()) {
|
|
427
|
+
const r = await ask({ messages: p.history });
|
|
428
|
+
if (r.isError) stop(r.text);
|
|
429
|
+
const a = r.data.answer;
|
|
430
|
+
const kind = replayKind(p.then, a);
|
|
431
|
+
counts[kind] = (counts[kind] ?? 0) + 1;
|
|
432
|
+
say(`\n${bold(`customer ${n + 1}/${pairs.length}`)} ${p.customer}`);
|
|
433
|
+
const then = p.then ? `then (${p.then.who}): ${p.then.text}` : "then: nobody answered";
|
|
434
|
+
const now = `now (${a.agent})${kind !== "same" ? `, ${kind}` : ""}: ${a.text || "(no answer)"}`;
|
|
435
|
+
say(width >= 100 ? sideBySide(then, now, Math.min(width, 160)) : `${then}\n\n${now}`);
|
|
436
|
+
say(dim(answerLines(a).map((l) => ` ${l}`).join("\n")));
|
|
437
|
+
}
|
|
438
|
+
say(`\n${pairs.length === 1 ? "1 answer" : `${pairs.length} answers`}: ${counts["now answered"]} now answered, ${counts["now handed to a person"]} now handed to a person, ${counts.same} the same kind as then. Nothing was sent or saved.`);
|
|
439
|
+
return;
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
say(`${intro()}\n${price} Save a file and the next answer uses it. /why /reset /save-test /quit`);
|
|
443
|
+
const chat = [];
|
|
444
|
+
let last = null;
|
|
445
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout, prompt: color ? "\x1b[36myou\x1b[39m " : "you ", terminal: process.stdin.isTTY });
|
|
446
|
+
const { watch } = await import("node:fs");
|
|
447
|
+
const watcher = watchFolder(folder, async (files) => {
|
|
448
|
+
const r = await ask({}).catch(() => null);
|
|
449
|
+
if (!r) return;
|
|
450
|
+
if (r.isError) { process.stdout.write(`\n${r.text}\nThe chat waits for the next save.\n`); return; }
|
|
451
|
+
setup = r.data.setup;
|
|
452
|
+
process.stdout.write(`\n↻ ${files.length ? `${files.slice(0, 3).join(", ")}${files.length > 3 ? ` and ${files.length - 3} more` : ""} saved` : "Saved"}: reloaded. ${intro()}\n`);
|
|
453
|
+
if (process.stdin.isTTY) rl.prompt(true);
|
|
454
|
+
}, { watch });
|
|
455
|
+
let busy = Promise.resolve();
|
|
456
|
+
const end = () => { watcher.close(); rl.close(); process.exit(0); };
|
|
457
|
+
// Ctrl+D, or the end of piped input: finish the turns already asked, then stop.
|
|
458
|
+
rl.on("SIGINT", end);
|
|
459
|
+
rl.on("close", () => { void busy.then(() => { watcher.close(); process.exit(0); }); });
|
|
460
|
+
const prompt = () => { if (process.stdin.isTTY) rl.prompt(); };
|
|
461
|
+
prompt();
|
|
462
|
+
rl.on("line", (line) => { busy = busy.then(() => onLine(line)).catch((e) => say(String(e?.message ?? e))).then(prompt); });
|
|
463
|
+
async function onLine(line) {
|
|
464
|
+
const said = parseDevLine(line);
|
|
465
|
+
if (said.kind === "empty") return;
|
|
466
|
+
if (said.kind === "unknown") { say(`${said.word} is not a command here. ${Object.keys(DEV_COMMANDS).map((c) => `/${c}`).join(" ")}`); return; }
|
|
467
|
+
if (said.kind === "command") {
|
|
468
|
+
if (said.name === "quit") end();
|
|
469
|
+
if (said.name === "help") { say(Object.entries(DEV_COMMANDS).map(([c, d]) => `/${c.padEnd(10)} ${d}`).join("\n") + "\n//text send a message that starts with a slash"); return; }
|
|
470
|
+
if (said.name === "reset") { chat.length = 0; last = null; say("Started again. The folder stays as it is."); return; }
|
|
471
|
+
if (said.name === "why") { say(whyText(last?.answer, setup)); return; }
|
|
472
|
+
if (said.name === "save-test") {
|
|
473
|
+
if (!last) { say("Ask something first: the test is the last thing you asked."); return; }
|
|
474
|
+
const must = said.arg.replace(/^must:?\s+/i, "");
|
|
475
|
+
const t = devTestFile(last.question, { handedOff: last.answer.handedOff, must }, (p) => existsSync(join(folder, ...p.split("/"))));
|
|
476
|
+
mkdirSync(join(folder, "tests"), { recursive: true });
|
|
477
|
+
writeFileSync(join(folder, ...t.path.split("/")), t.text);
|
|
478
|
+
say(`Wrote ${t.path} (expect: ${last.answer.handedOff ? "escalate" : "answer"}${must ? `, must: ${must}` : ""}). ${ME} push sends it with the rest.`);
|
|
479
|
+
return;
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
chat.push({ role: "customer", text: said.text });
|
|
483
|
+
const r = await ask({ messages: chat });
|
|
484
|
+
if (r.isError) { chat.pop(); say(r.text); return; }
|
|
485
|
+
const a = r.data.answer;
|
|
486
|
+
setup = r.data.setup ?? setup;
|
|
487
|
+
chat.push({ role: "agent", text: a.text || "(no answer)" });
|
|
488
|
+
last = { question: said.text, answer: a };
|
|
489
|
+
say(`${bold(a.agent)}${a.handedOff ? dim(" (handed to a person)") : ""}\n${a.text || "(no answer)"}\n${dim(answerLines(a).map((l) => ` ${l}`).join("\n"))}`);
|
|
490
|
+
}
|
|
491
|
+
await new Promise(() => {});
|
|
492
|
+
}
|
|
493
|
+
|
|
246
494
|
// ---- CI for a repository of support files --------------------------------------------------------------------------
|
|
247
495
|
/** The marker a check's pull request comment starts with, so the workflow edits one comment instead of adding more. */
|
|
248
496
|
export const CHECK_MARK = "<!-- next-support-check -->";
|
|
@@ -756,6 +1004,8 @@ const USAGE = [
|
|
|
756
1004
|
["", "in a file, knowledge entries can name file: docs/a.md or files: docs/**/*.md"],
|
|
757
1005
|
["<terminal command>", "any console terminal command, such as ME ls unassigned"],
|
|
758
1006
|
['run "<command>"', 'the same, in quotes, such as "ls unassigned --inbox Billing"'],
|
|
1007
|
+
["dev [agent] [--folder support]", "talk to the agent as this folder's unpushed files have it; each save reloads it (each turn is charged as tests)"],
|
|
1008
|
+
["dev --replay <ticket|conversation> [--yes]", "answer a past conversation's customer messages again with the folder, beside what was said then"],
|
|
759
1009
|
["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)"],
|
|
760
1010
|
["ci init [folder] [--force]", "write a GitHub workflow: check pull requests, propose on merge, and open a pull request when the console changed"],
|
|
761
1011
|
["ci comment [folder] [--on 10] [--pr n] [--print]", "in a pull request's workflow: one comment with what the change does and the answers it changes, before and after (costs money)"],
|
|
@@ -949,6 +1199,12 @@ export function initArgs(words, exists = existsSync) {
|
|
|
949
1199
|
return { address, folder: plain.find((w) => w !== address) ?? "support" };
|
|
950
1200
|
}
|
|
951
1201
|
|
|
1202
|
+
/**
|
|
1203
|
+
* Next as a Claude Code plugin: its tools and skills for a support lead, from the marketplace in this repository
|
|
1204
|
+
* (.claude-plugin/marketplace.json, plugins/next). init prints these two lines; typed in Claude Code, they install it.
|
|
1205
|
+
*/
|
|
1206
|
+
export const PLUGIN_LINES = ["/plugin marketplace add droconnell/agent-inbox", "/plugin install next@agent-inbox"];
|
|
1207
|
+
|
|
952
1208
|
/**
|
|
953
1209
|
* agent-inbox init <address> [folder]: everything the guide walks through, in one go. Each step says what it is doing,
|
|
954
1210
|
* skips what is already done, and never overwrites a file someone changed, so it is safe to run again. It only looks
|
|
@@ -1023,6 +1279,10 @@ async function init(words) {
|
|
|
1023
1279
|
step(6, "Claude Code");
|
|
1024
1280
|
done.claude = Boolean(sh("claude", ["--version"])?.ok);
|
|
1025
1281
|
if (!asJson) say(done.claude ? ` Claude Code is installed. Opened in ${dir}/, it has Next's tools and reads CLAUDE.md.` : " Claude Code is not installed here. Get it at https://claude.com/claude-code; this folder is ready for it.");
|
|
1282
|
+
// Offered, never run: the person types these in Claude Code if they want the skills. The folder's .mcp.json already
|
|
1283
|
+
// gives Claude Code the tools without them.
|
|
1284
|
+
done.plugin = PLUGIN_LINES;
|
|
1285
|
+
if (!asJson) say(` For Next's skills too (why did the agent say this, what broke this week, ship a change), type these in Claude Code:\n${PLUGIN_LINES.map((l) => ` ${l}`).join("\n")}`);
|
|
1026
1286
|
|
|
1027
1287
|
done.next.unshift(done.claude ? `cd ${dir}, run claude, and ask: "What needs a person in Next right now?"` : `Install Claude Code, then cd ${dir}, run claude, and ask: "What needs a person in Next right now?"`);
|
|
1028
1288
|
if (asJson) { report("", done); return; }
|
|
@@ -1259,6 +1519,24 @@ export function runnable(sub, args) {
|
|
|
1259
1519
|
return [...sub.split(" "), ...(path === null ? [] : [path]), ...flags];
|
|
1260
1520
|
}
|
|
1261
1521
|
|
|
1522
|
+
/**
|
|
1523
|
+
* A sequence from Next (Run all 3): two or three commands, each checked by runnable and each one that may run without
|
|
1524
|
+
* asking (only those go together; anything that changes Next or costs money is asked about on its own). The CLI's own
|
|
1525
|
+
* words for each, in order, or null for anything else, which is refused without asking. The same rule as
|
|
1526
|
+
* validSequence in src/lib/computer-commands.ts (src/lib/computer-commands.test.ts checks they agree).
|
|
1527
|
+
*/
|
|
1528
|
+
export const MAX_SEQUENCE = 3;
|
|
1529
|
+
export function runnableSequence(steps) {
|
|
1530
|
+
if (!Array.isArray(steps) || steps.length < 2 || steps.length > MAX_SEQUENCE) return null;
|
|
1531
|
+
const out = [];
|
|
1532
|
+
for (const s of steps) {
|
|
1533
|
+
const argv = s && typeof s === "object" ? runnable(s.sub, s.args) : null;
|
|
1534
|
+
if (!argv || !RUNNABLE[s.sub].always) return null;
|
|
1535
|
+
out.push({ sub: s.sub, argv });
|
|
1536
|
+
}
|
|
1537
|
+
return out;
|
|
1538
|
+
}
|
|
1539
|
+
|
|
1262
1540
|
/** Text from Next shown in this terminal: no control characters, so nothing sent can move the cursor or recolour the screen. */
|
|
1263
1541
|
export const plainText = (s, max = 120) => String(s ?? "").replace(/[\u0000-\u001f\u007f-\u009f\u200b-\u200f\u2028-\u202e]/g, "").slice(0, max);
|
|
1264
1542
|
|
|
@@ -1356,27 +1634,31 @@ async function connect(words) {
|
|
|
1356
1634
|
return false;
|
|
1357
1635
|
};
|
|
1358
1636
|
|
|
1637
|
+
/** The folder or file a command's words name (it comes right after the command's own words, before any option), or "." */
|
|
1638
|
+
const namedPath = (sub, argv) => { const named = argv[sub.split(" ").length]; return named && !named.startsWith("-") ? named : "."; };
|
|
1639
|
+
|
|
1359
1640
|
/** One request: check it, show it, ask, then run this CLI with its words in this folder, and send back what it printed. */
|
|
1360
1641
|
const handle = async (run) => {
|
|
1361
|
-
|
|
1362
|
-
const
|
|
1642
|
+
// Run all 3: two or three commands that may run without asking, shown together and asked about once.
|
|
1643
|
+
const several = Array.isArray(run.steps);
|
|
1644
|
+
const steps = several ? runnableSequence(run.steps) : (() => { const argv = runnable(run.sub, run.args); return argv ? [{ sub: run.sub, argv }] : null; })();
|
|
1645
|
+
const lines = steps ? steps.map((s) => `agent-inbox ${s.argv.join(" ")}`) : [`agent-inbox ${plainText(run.sub, 40)}`];
|
|
1363
1646
|
// A request from before this computer reconnected says how old it is, so an earlier ask is not mistaken for a new one.
|
|
1364
1647
|
const ago = Math.floor((Date.now() - Date.parse(run.askedAt)) / 60_000);
|
|
1365
1648
|
const when = ago >= 1 ? ` ${ago} minute${ago === 1 ? "" : "s"} ago` : "";
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
const path = named && !named.startsWith("-") ? named : ".";
|
|
1370
|
-
if (!argv || !staysInside(folder, path)) {
|
|
1649
|
+
const shownLines = several && steps ? lines.map((l, i) => ` ${i + 1}. ${l}`).join("\n") : ` ${lines[0]}`;
|
|
1650
|
+
say(`\n${clock()} ${plainText(run.from, 40)} wants to run, asked by ${plainText(run.askedBy, 60)}${when}:\n\n${shownLines}\n in ${folder}${several && steps ? ", one after the other" : ""}\n`);
|
|
1651
|
+
if (!steps || !steps.every((s) => staysInside(folder, namedPath(s.sub, s.argv)))) {
|
|
1371
1652
|
say("Not run: this computer only runs agent-inbox commands from its list, in this folder.");
|
|
1372
1653
|
await report(run, { status: "declined", output: "This computer refused it: it only runs agent-inbox commands from its list, in the folder it connected.\n" });
|
|
1373
1654
|
return;
|
|
1374
1655
|
}
|
|
1375
|
-
let approved = always.has(
|
|
1376
|
-
if (approved) say(`Running: you chose Always for ${run.sub} while connected.`);
|
|
1656
|
+
let approved = steps.every((s) => always.has(s.sub)) ? "always" : null;
|
|
1657
|
+
if (approved) say(several ? "Running: you chose Always for each of these while connected." : `Running: you chose Always for ${run.sub} while connected.`);
|
|
1377
1658
|
while (!approved) {
|
|
1378
|
-
|
|
1379
|
-
const
|
|
1659
|
+
// Always is offered for one command that may have it, never for a sequence as a whole.
|
|
1660
|
+
const canAlways = !several && RUNNABLE[run.sub].always;
|
|
1661
|
+
const a = await question(several ? `Run all ${steps.length}? [y] yes [n] no › ` : `Run it? [y] yes ${canAlways ? `[a] always for ${run.sub} ` : ""}[n] no › `);
|
|
1380
1662
|
if (a === "y" || a === "yes") approved = "once";
|
|
1381
1663
|
else if (canAlways && (a === "a" || a === "always")) { approved = "always"; always.add(run.sub); }
|
|
1382
1664
|
else if (a === "n" || a === "no") break;
|
|
@@ -1388,16 +1670,26 @@ async function connect(words) {
|
|
|
1388
1670
|
let pending = "";
|
|
1389
1671
|
const flush = async () => { if (!pending) return; const chunk = pending; pending = ""; await report(run, { status: "running", output: chunk }); };
|
|
1390
1672
|
const timer = setInterval(() => void flush(), 1000);
|
|
1391
|
-
const
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1673
|
+
const take = (s) => { process.stdout.write(s); pending += s; };
|
|
1674
|
+
let code = 0;
|
|
1675
|
+
for (let i = 0; i < steps.length; i++) {
|
|
1676
|
+
// In a sequence, each command's output starts with the command, so Next (and the Assistant) can tell them apart.
|
|
1677
|
+
if (several) take(`$ ${lines[i]}\n`);
|
|
1678
|
+
code = await new Promise((done) => {
|
|
1679
|
+
// This CLI's own code with the checked words, in this folder, without a shell: nothing can be added to the line.
|
|
1680
|
+
child = spawn(process.execPath, [SELF, ...steps[i].argv], { cwd: folder, shell: false, windowsHide: true, stdio: ["ignore", "pipe", "pipe"], env: { ...process.env, NO_COLOR: "1" } });
|
|
1681
|
+
const got = (b) => take(b.toString("utf8"));
|
|
1682
|
+
child.stdout.on("data", got); child.stderr.on("data", got);
|
|
1683
|
+
const limit = setTimeout(() => { take("\nStopped after 20 minutes.\n"); child?.kill(); }, 20 * 60_000);
|
|
1684
|
+
child.on("error", () => { clearTimeout(limit); done(-1); });
|
|
1685
|
+
child.on("close", (c) => { clearTimeout(limit); done(c ?? -1); });
|
|
1686
|
+
});
|
|
1687
|
+
child = null;
|
|
1688
|
+
if (runEnded(code) !== "done") {
|
|
1689
|
+
if (several && i < steps.length - 1) take(`Stopped: ${lines[i]} did not finish, so the rest did not run.\n`);
|
|
1690
|
+
break;
|
|
1691
|
+
}
|
|
1692
|
+
}
|
|
1401
1693
|
clearInterval(timer);
|
|
1402
1694
|
const ended = runEnded(code);
|
|
1403
1695
|
const output = pending; pending = "";
|
|
@@ -1507,6 +1799,7 @@ switch (cmd) {
|
|
|
1507
1799
|
case "claude": await claudeSetup(rest.includes("--project")); break;
|
|
1508
1800
|
case "init": await init(rest); break;
|
|
1509
1801
|
case "connect": await connect(rest); break;
|
|
1802
|
+
case "dev": await devCommand(rest); break;
|
|
1510
1803
|
case "app": await appCommand(rest); break;
|
|
1511
1804
|
case "events": { const only = (valueOf(rest, "--only") ?? "").split(",").filter(Boolean); await events(only.length ? only : null); break; }
|
|
1512
1805
|
case "listen": await listen(valueOf(rest, "--forward"), valueOf(rest, "--events")?.split(",").filter(Boolean)); break;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@droconnell/agent-inbox-cli",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.10.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": {
|