@networkbase/cli 2.1.5 → 2.1.6
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/bin/nb.mjs +2 -1
- package/lib/commands/complete.mjs +2 -1
- package/lib/commands/learn.mjs +79 -0
- package/lib/commands/link.mjs +25 -0
- package/lib/commands/mcp.mjs +2 -1
- package/lib/commands/messages.mjs +75 -0
- package/lib/commands/misc.mjs +6 -0
- package/lib/commands/table.mjs +12 -0
- package/lib/commands/ui.mjs +178 -0
- package/lib/context.mjs +2 -3
- package/lib/error-fixes.mjs +1 -0
- package/lib/mcp/tools.mjs +13 -0
- package/lib/self.mjs +7 -0
- package/package.json +1 -1
package/bin/nb.mjs
CHANGED
|
@@ -22,7 +22,8 @@ const argv = process.argv.slice(2);
|
|
|
22
22
|
const add = networkEnv(userConfig, process.env, process.versions.node);
|
|
23
23
|
if (add) {
|
|
24
24
|
const { spawnSync } = await import("node:child_process");
|
|
25
|
-
const
|
|
25
|
+
const { self } = await import("../lib/self.mjs");
|
|
26
|
+
const again = spawnSync(...self(argv), { stdio: "inherit", env: { ...process.env, ...add } });
|
|
26
27
|
process.exit(again.status ?? 1);
|
|
27
28
|
}
|
|
28
29
|
}
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
// small cache per workspace that a background `nb complete --refresh` keeps no older than 10 minutes. Completing
|
|
3
3
|
// never waits on the network: it answers from the cache, even an old one, and refreshes behind.
|
|
4
4
|
import { spawn } from "node:child_process";
|
|
5
|
+
import { self } from "../self.mjs";
|
|
5
6
|
import fs from "node:fs";
|
|
6
7
|
import path from "node:path";
|
|
7
8
|
|
|
@@ -59,7 +60,7 @@ export async function complete(ctx) {
|
|
|
59
60
|
try { cache = readJson(cacheFile(ctx, workspaceId)); } catch { cache = null; }
|
|
60
61
|
if (!cache || Date.now() - cache.at > FRESH_MS) {
|
|
61
62
|
// Behind the shell's back, so the Tab press doesn't wait.
|
|
62
|
-
spawn(
|
|
63
|
+
spawn(...self(["complete", "--refresh"]), { cwd: ctx.cwd, detached: true, stdio: "ignore", env: ctx.env }).unref();
|
|
63
64
|
}
|
|
64
65
|
if (!cache) return 0;
|
|
65
66
|
const [kind, prefix = ""] = ctx.positionals;
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
// nb learn (report C1, M4d): five minutes of guided practice in a workspace made for it. Each step shows the real
|
|
2
|
+
// command, waits for Enter in a terminal, then runs it in a practice folder. Nothing touches real workspaces, and the
|
|
3
|
+
// practice workspace is deleted at the end (--keep leaves it for 24 hours).
|
|
4
|
+
import { spawnSync } from "node:child_process";
|
|
5
|
+
import { self } from "../self.mjs";
|
|
6
|
+
import fs from "node:fs";
|
|
7
|
+
import os from "node:os";
|
|
8
|
+
import path from "node:path";
|
|
9
|
+
import readline from "node:readline";
|
|
10
|
+
|
|
11
|
+
import { CliError } from "../errors.mjs";
|
|
12
|
+
import { safe } from "../print/style.mjs";
|
|
13
|
+
|
|
14
|
+
/** @typedef {import("../context.mjs").Context} Context */
|
|
15
|
+
|
|
16
|
+
/** Waits for Enter; q stops (Ctrl+C too, cleaning up). In scripts and with --yes it never waits. @param {Context} ctx */
|
|
17
|
+
async function next(ctx) {
|
|
18
|
+
if (!ctx.out.interactive || ctx.flags.yes) return true;
|
|
19
|
+
ctx.out.stderr.write(ctx.out.c.muted(" Enter to run it, q to stop "));
|
|
20
|
+
const rl = readline.createInterface({ input: process.stdin, terminal: false });
|
|
21
|
+
const answer = await new Promise((resolve) => { rl.once("line", resolve); rl.once("close", () => resolve("q")); });
|
|
22
|
+
rl.close();
|
|
23
|
+
return !/^\s*(q|quit|exit)\s*$/i.test(String(answer));
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** @param {Context} ctx */
|
|
27
|
+
export async function learn(ctx) {
|
|
28
|
+
const { c, sym } = ctx.out;
|
|
29
|
+
const started = /** @type {any} */ (await ctx.api.post("/api/v1/sandbox", {})).sandbox;
|
|
30
|
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "nb-learn-"));
|
|
31
|
+
// The steps run the same nb, signed in the same way.
|
|
32
|
+
const pass = /** @type {const} */ (["profile", "api-url"]).flatMap((f) => (ctx.flags[f] ? [`--${f}`, String(ctx.flags[f])] : []));
|
|
33
|
+
/** @param {string[]} args @param {{ json?: boolean }} [o] */
|
|
34
|
+
const nb = (args, o = {}) => {
|
|
35
|
+
// With --json the steps' own output goes to stderr, so stdout stays one JSON result.
|
|
36
|
+
const shown = ctx.flags.json ? 2 : "inherit";
|
|
37
|
+
const r = spawnSync(...self([...args, ...pass, ...(o.json ? ["--json"] : [])]), { cwd: dir, env: { ...ctx.env, NB_NO_UPDATE_CHECK: "1" }, encoding: "utf8", stdio: o.json ? ["ignore", "pipe", "pipe"] : ["ignore", shown, shown] });
|
|
38
|
+
if (r.status !== 0 && !o.json) throw new CliError("LEARN_STEP_FAILED", `nb ${args.join(" ")} didn't work`, { hint: "Run nb learn again to start over" });
|
|
39
|
+
return o.json ? JSON.parse(r.stdout || "{}") : null;
|
|
40
|
+
};
|
|
41
|
+
let number = 0;
|
|
42
|
+
/** @type {Array<{ title: string, say: string, show: string, run: () => void }>} */
|
|
43
|
+
const steps = [
|
|
44
|
+
{ title: "Link a folder", say: "A folder on your computer is linked to one workspace. This practice folder is linked to your practice workspace.", show: `nb init ${started.slug}`, run: () => nb(["init", started.slug]) },
|
|
45
|
+
{ title: "See what changed", say: "Make a file, then nb status lists what's new here and what's waiting.", show: "nb status", run: () => { fs.writeFileSync(path.join(dir, "notes.md"), "# My first NetworkBase file\n\nWritten during nb learn.\n"); nb(["status"]); } },
|
|
46
|
+
{ title: "Push it", say: "nb push uploads changes. Pushing the same path again makes a new version; nothing is overwritten.", show: "nb push notes.md", run: () => nb(["push", "notes.md"]) },
|
|
47
|
+
{ title: "Make a task and start it", say: "Tasks are the work. nb task start makes one this folder's task, so pushes attach to it.", show: 'nb task add "Try NetworkBase" && nb task start 1', run: () => { number = Number(nb(["task", "add", "Try NetworkBase"], { json: true })?.data?.number ?? 1); nb(["task", "start", String(number)]); } },
|
|
48
|
+
{ title: "Finish it", say: "nb done finishes the current task (or sends it for review where that's the rule).", show: 'nb done -m "practised"', run: () => nb(["task", "done", String(number), "-m", "practised", "--yes"]) },
|
|
49
|
+
];
|
|
50
|
+
ctx.out.note(`${c.bold("nb learn")}: ${steps.length} steps, about five minutes, in a practice workspace that's deleted at the end.`);
|
|
51
|
+
let finished = false;
|
|
52
|
+
// Only the practice workspace this run made goes at the end: one kept with --keep, or another terminal's, stays.
|
|
53
|
+
const ours = Boolean(started.created) && !ctx.flags.keep;
|
|
54
|
+
let cleaned = false;
|
|
55
|
+
const cleanup = async () => {
|
|
56
|
+
if (cleaned) return;
|
|
57
|
+
cleaned = true;
|
|
58
|
+
if (ours) await ctx.api.request("DELETE", `/api/v1/sandbox/${encodeURIComponent(started.id)}`).catch(() => {});
|
|
59
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
60
|
+
};
|
|
61
|
+
// Ctrl+C (or q) still cleans up: the CLI's own handler would exit before the finally below runs.
|
|
62
|
+
process.removeAllListeners("SIGINT");
|
|
63
|
+
process.once("SIGINT", () => { void cleanup().finally(() => process.exit(130)); });
|
|
64
|
+
try {
|
|
65
|
+
for (const [i, step] of steps.entries()) {
|
|
66
|
+
ctx.out.stderr.write(`\n${c.accent(sym.active)} ${c.bold(`Step ${i + 1} of ${steps.length}: ${step.title}`)}\n ${safe(step.say)}\n ${c.brand("$")} ${step.show}\n`);
|
|
67
|
+
if (!(await next(ctx))) return ctx.out.result("nb.learn/1", { finished: false, steps: i, kept: false }, () => "Stopped. Run nb learn again any time.");
|
|
68
|
+
step.run();
|
|
69
|
+
}
|
|
70
|
+
finished = true;
|
|
71
|
+
} finally {
|
|
72
|
+
await cleanup();
|
|
73
|
+
}
|
|
74
|
+
ctx.out.result("nb.learn/1", { finished, steps: steps.length, kept: !ours }, () => [
|
|
75
|
+
`\n${c.success(sym.done)} Done: link, status, push, task start, done. That's the everyday loop.`,
|
|
76
|
+
ours ? c.muted(" The practice workspace is deleted.") : c.muted(` The practice workspace stays for 24 hours: ${started.slug}`),
|
|
77
|
+
" Next: nb init in a real project folder, or nb help for everything else.",
|
|
78
|
+
]);
|
|
79
|
+
}
|
package/lib/commands/link.mjs
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// Linking a folder to a workspace, and unlinking it (report A1.1, A1.20).
|
|
2
2
|
import { execFileSync } from "node:child_process";
|
|
3
|
+
import { self } from "../self.mjs";
|
|
3
4
|
import fs from "node:fs";
|
|
4
5
|
import os from "node:os";
|
|
5
6
|
import path from "node:path";
|
|
@@ -115,3 +116,27 @@ export async function unlink(ctx) {
|
|
|
115
116
|
if (ctx.flags["purge-local"]) fs.rmSync(path.join(root, ".tasks"), { recursive: true, force: true });
|
|
116
117
|
ctx.out.result("nb.unlink/1", { root, purgedTasks: Boolean(ctx.flags["purge-local"]) }, () => `${ctx.out.c.success(ctx.out.sym.done)} Unlinked ${root}`);
|
|
117
118
|
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* nb start (report C7): from nothing to working in one command, `npx @networkbase/cli start`. Signs in if needed,
|
|
122
|
+
* links this folder (suggesting the workspace named like it) if needed, then pulls. It stops only to ask what it
|
|
123
|
+
* can't guess, through the same commands, so every question and answer flag works as they do.
|
|
124
|
+
* @param {Context} ctx
|
|
125
|
+
*/
|
|
126
|
+
export async function start(ctx) {
|
|
127
|
+
const { spawnSync } = await import("node:child_process");
|
|
128
|
+
const pass = /** @type {const} */ (["profile", "api-url", "yes"]).flatMap((f) => (ctx.flags[f] === true ? [`--${f}`] : ctx.flags[f] ? [`--${f}`, String(ctx.flags[f])] : []));
|
|
129
|
+
const answers = [ctx.flags.answer ?? []].flat().flatMap((a) => ["--answer", String(a)]);
|
|
130
|
+
/** @param {string[]} args */
|
|
131
|
+
const nb = (args) => {
|
|
132
|
+
// With --json the steps' output goes to stderr, so stdout stays one JSON result.
|
|
133
|
+
const r = spawnSync(...self([...args, ...pass, ...answers]), { cwd: ctx.cwd, env: ctx.env, stdio: ["inherit", ctx.flags.json ? 2 : "inherit", "inherit"] });
|
|
134
|
+
if (r.status !== 0) process.exit(r.status ?? 1);
|
|
135
|
+
};
|
|
136
|
+
const steps = [];
|
|
137
|
+
if (!ctx.profile.token) { nb(["login"]); steps.push("signed in"); }
|
|
138
|
+
if (!findRoot(path.resolve(ctx.cwd))) { nb(["init", ...ctx.positionals.slice(0, 1)]); steps.push("linked this folder"); }
|
|
139
|
+
nb(["pull"]);
|
|
140
|
+
steps.push("pulled the files");
|
|
141
|
+
ctx.out.result("nb.start/1", { steps }, (d) => [`${ctx.out.c.success(ctx.out.sym.done)} Ready: ${d.steps.join(", ")}.`, " Next: nb next for what to work on, nb status for what changed here."]);
|
|
142
|
+
}
|
package/lib/commands/mcp.mjs
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
// JSON-RPC messages, one per line (finding 5); everything else goes to stderr. Answers ping and unknown methods
|
|
3
3
|
// (finding 6), negotiates the protocol version (finding 122), and reports tool failures as results (finding 123).
|
|
4
4
|
import { spawn } from "node:child_process";
|
|
5
|
+
import { self } from "../self.mjs";
|
|
5
6
|
import crypto from "node:crypto";
|
|
6
7
|
import readline from "node:readline";
|
|
7
8
|
|
|
@@ -185,7 +186,7 @@ export async function serve(ctx, io = {}) {
|
|
|
185
186
|
if (!finishing) {
|
|
186
187
|
finishing = true;
|
|
187
188
|
const pass = /** @type {const} */ (["profile", "api-url"]).flatMap((f) => (ctx.flags[f] ? [`--${f}`, String(ctx.flags[f])] : []));
|
|
188
|
-
spawn(
|
|
189
|
+
spawn(...self(["mcp", "finish", ...pass, ...(pinged.size ? ["--tasks", [...pinged.keys()].join(",")] : [])]), { cwd: where.cwd, env: where.env, detached: true, stdio: "ignore" }).unref();
|
|
189
190
|
}
|
|
190
191
|
process.exit(0);
|
|
191
192
|
});
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
// nb message (report C4, M4d): your channels and direct messages from the terminal. The person's own sign-in only:
|
|
2
|
+
// the server refuses agents, and tokens need message:read / message:write.
|
|
3
|
+
import { CliError, usage } from "../errors.mjs";
|
|
4
|
+
import { safe } from "../print/style.mjs";
|
|
5
|
+
import { ask } from "../tui/ask.mjs";
|
|
6
|
+
import { formatWhen } from "./tasks.mjs";
|
|
7
|
+
|
|
8
|
+
/** @typedef {import("../context.mjs").Context} Context */
|
|
9
|
+
|
|
10
|
+
/** @param {Context} ctx @returns {Promise<any[]>} */
|
|
11
|
+
async function conversations(ctx) {
|
|
12
|
+
return /** @type {any} */ (await ctx.api.get("/api/v1/chat/conversations")).conversations ?? [];
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* "#design", "@sam", a group's name or a number from `nb message list`. A channel name in several workspaces asks
|
|
17
|
+
* which (--workspace picks; scripts get the choices). @param {Context} ctx @param {string | undefined} ref
|
|
18
|
+
*/
|
|
19
|
+
async function pick(ctx, ref) {
|
|
20
|
+
if (!ref) throw usage("Which conversation?", "nb message read #design, @sam, or a number from nb message list");
|
|
21
|
+
const all = await conversations(ctx);
|
|
22
|
+
if (/^\d+$/.test(ref)) {
|
|
23
|
+
const hit = all[Number(ref) - 1];
|
|
24
|
+
if (!hit) throw new CliError("NOT_FOUND", `No conversation ${ref}`, { hint: "nb message list" });
|
|
25
|
+
return hit;
|
|
26
|
+
}
|
|
27
|
+
const want = ref.toLowerCase();
|
|
28
|
+
const ws = ctx.flags.workspace ? String(ctx.flags.workspace).toLowerCase() : null;
|
|
29
|
+
const named = all.filter((c) => c.label.toLowerCase() === want || (!/^[#@]/.test(want) && c.label.toLowerCase() === `#${want}`));
|
|
30
|
+
const hits = ws ? named.filter((c) => String(c.workspace ?? "").toLowerCase() === ws || String(c.workspaceId ?? "").toLowerCase() === ws) : named;
|
|
31
|
+
if (hits.length === 1) return hits[0];
|
|
32
|
+
if (!hits.length) {
|
|
33
|
+
const near = all.filter((c) => c.label.toLowerCase().includes(want.replace(/^[#@]/, ""))).slice(0, 5).map((c) => (c.workspace ? `${c.label} (${c.workspace})` : c.label));
|
|
34
|
+
throw new CliError("NOT_FOUND", `No conversation ${ref}`, { hint: near.length ? `Did you mean ${near.join(", ")}?` : "nb message list" });
|
|
35
|
+
}
|
|
36
|
+
const id = await ask(ctx, { key: "conversation", header: "Which", question: `${ref} is in ${hits.length} workspaces. Which one?`, options: hits.slice(0, 4).map((c) => ({ value: c.id, label: `${safe(c.label)} in ${safe(c.workspace ?? "no workspace")}` })) });
|
|
37
|
+
return hits.find((c) => c.id === id) ?? hits[0];
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** nb message list. @param {Context} ctx */
|
|
41
|
+
export async function list(ctx) {
|
|
42
|
+
const all = (await conversations(ctx)).filter((c) => !ctx.flags.unread || c.unread > 0);
|
|
43
|
+
const { c } = ctx.out;
|
|
44
|
+
ctx.out.result("nb.message.list/1", { conversations: all }, (d) => d.conversations.length ? [
|
|
45
|
+
...d.conversations.map((/** @type {any} */ m, /** @type {number} */ n) => `${String(n + 1).padStart(3)} ${m.unread ? c.brand(ctx.out.sym.brand) : " "} ${safe(m.label).padEnd(22)} ${c.muted(safe(m.workspace ?? "").padEnd(16))} ${m.unread ? c.bold(`${m.unread} new`.padEnd(7)) : "".padEnd(7)} ${c.muted(m.lastAt ? formatWhen(m.lastAt) : "")} ${safe(m.lastPreview ?? "").replace(/\n/g, " ").slice(0, 60)}`),
|
|
46
|
+
c.muted(" nb message read <#channel|@person|n> · nb message send <#channel|@person> \"text\""),
|
|
47
|
+
] : ctx.flags.unread ? "Nothing unread" : "No conversations yet. Start one in the app: Messages", { page: true });
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** nb message read #design: the latest messages, oldest first, then marks them read. @param {Context} ctx */
|
|
51
|
+
export async function read(ctx) {
|
|
52
|
+
const conv = await pick(ctx, ctx.positionals[0]);
|
|
53
|
+
const res = /** @type {any} */ (await ctx.api.get(`/api/v1/chat/conversations/${encodeURIComponent(conv.id)}/messages`, { query: ctx.flags.before ? { before: Number(ctx.flags.before) } : {} }));
|
|
54
|
+
/** @type {any[]} */
|
|
55
|
+
const messages = res.messages ?? [];
|
|
56
|
+
const last = messages.at(-1);
|
|
57
|
+
if (last && !ctx.flags["keep-unread"] && !ctx.flags.before) await ctx.api.post(`/api/v1/chat/conversations/${encodeURIComponent(conv.id)}/read`, { seq: last.seq }).catch(() => {});
|
|
58
|
+
const { c } = ctx.out;
|
|
59
|
+
ctx.out.result("nb.message.read/1", { conversation: { id: conv.id, label: conv.label, workspace: conv.workspace }, messages }, (d) => d.messages.length ? [
|
|
60
|
+
c.bold(safe(d.conversation.label)) + (d.conversation.workspace ? c.muted(` · ${safe(d.conversation.workspace)}`) : ""),
|
|
61
|
+
...d.messages.map((/** @type {any} */ m) => `${c.muted(String(m.seq).padStart(5))} ${c.bold(safe(m.author))} ${c.muted(formatWhen(m.at))}${m.edited ? c.muted(" (edited)") : ""}\n ${safe(m.text).replace(/\n/g, "\n ")}${m.files.length ? c.muted(`\n ${m.files.length} file${m.files.length === 1 ? "" : "s"}: ${m.files.map(safe).join(", ")}`) : ""}${m.replies ? c.muted(`\n ${m.replies} repl${m.replies === 1 ? "y" : "ies"} (open in the app)`) : ""}`),
|
|
62
|
+
c.muted(` Older: nb message read ${d.conversation.label} --before ${d.messages[0].seq} · Reply: nb message send ${d.conversation.label} "text"`),
|
|
63
|
+
] : "No messages here yet", { page: true });
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** nb message send #design "text" [--reply <seq>]. @param {Context} ctx */
|
|
67
|
+
export async function send(ctx) {
|
|
68
|
+
const [ref, ...words] = ctx.positionals;
|
|
69
|
+
const text = String(ctx.flags.message ?? words.join(" ")).trim();
|
|
70
|
+
if (!ref || !text) throw usage('nb message send <#channel|@person> "text"');
|
|
71
|
+
const conv = await pick(ctx, ref);
|
|
72
|
+
if (!conv.canReply) throw new CliError("FORBIDDEN", `You can't reply in ${conv.label}`, { hint: "nb message list" });
|
|
73
|
+
const res = /** @type {any} */ (await ctx.api.post(`/api/v1/chat/conversations/${encodeURIComponent(conv.id)}/messages`, { text, ...(ctx.flags.reply ? { replyTo: Number(ctx.flags.reply) } : {}) }));
|
|
74
|
+
ctx.out.result("nb.message.send/1", { conversation: conv.label, seq: res.seq }, (d) => `${ctx.out.c.success(ctx.out.sym.done)} Sent to ${safe(d.conversation)}`);
|
|
75
|
+
}
|
package/lib/commands/misc.mjs
CHANGED
|
@@ -95,6 +95,12 @@ export function installMethod(script) {
|
|
|
95
95
|
|
|
96
96
|
/** `nb upgrade` (C5): updates the CLI the way it was installed; npx needs nothing. Asks first. @param {Context} ctx */
|
|
97
97
|
export async function upgrade(ctx) {
|
|
98
|
+
// The single-file nb (C7) updates through the package manager it came from.
|
|
99
|
+
const { SINGLE_FILE } = await import("../self.mjs");
|
|
100
|
+
if (SINGLE_FILE) {
|
|
101
|
+
const command = process.platform === "win32" ? "scoop update nb" : "brew upgrade nb";
|
|
102
|
+
return ctx.out.result("nb.upgrade/1", { how: "single-file", command }, (d) => [`This is the single-file nb. Update it with: ${d.command}`, " Or download the latest from https://networkbase.in/docs/cli#install"]);
|
|
103
|
+
}
|
|
98
104
|
const how = installMethod(fs.realpathSync(process.argv[1] ?? ""));
|
|
99
105
|
const command = "npm i -g @networkbase/cli@latest";
|
|
100
106
|
if (how === "npx") return ctx.out.result("nb.upgrade/1", { how, command: null }, () => "npx runs the latest nb each time: nothing to update");
|
package/lib/commands/table.mjs
CHANGED
|
@@ -73,6 +73,12 @@ export const COMMANDS = [
|
|
|
73
73
|
examples: ["nb init design-lab", "nb init design-lab --task 4"] },
|
|
74
74
|
{ group: "Account and setup", name: "unlink", summary: "Remove the link, keep your files", usage: "nb unlink [--purge-local]", module: "link", fn: "unlink",
|
|
75
75
|
flags: { "purge-local": { type: "boolean", describe: "Also remove .tasks/ copies" } } },
|
|
76
|
+
{ group: "Account and setup", name: "start", summary: "Start from nothing: sign in, link this folder, pull", usage: "nb start [workspace]", module: "link", fn: "start",
|
|
77
|
+
examples: ["npx @networkbase/cli start", "nb start design-lab"] },
|
|
78
|
+
{ group: "Account and setup", name: "learn", summary: "Five minutes of guided practice in a workspace made for it", usage: "nb learn [--keep]", module: "learn", fn: "learn",
|
|
79
|
+
flags: { keep: { type: "boolean", describe: "Keep the practice workspace for 24 hours" } } },
|
|
80
|
+
{ group: "Account and setup", name: "ui", summary: "A full-screen view: tasks, inbox and changed files", usage: "nb ui", module: "ui", fn: "ui",
|
|
81
|
+
examples: ["nb ui", "nb ui --plain (the same as nb status)"] },
|
|
76
82
|
{ group: "Account and setup", name: "status", summary: "What changed here, the started task, conflicts", usage: "nb status", module: "files", fn: "status", exit: [0, 3, 4, 8] },
|
|
77
83
|
{ group: "Account and setup", name: "doctor", summary: "Check sign-in, server, link, Node and this folder", usage: "nb doctor [--repair]", module: "misc", fn: "doctor",
|
|
78
84
|
flags: { repair: { type: "boolean", describe: "Fix what can be fixed (lock, temp files)" } } },
|
|
@@ -270,6 +276,12 @@ export const COMMANDS = [
|
|
|
270
276
|
{ group: "Docs and workspaces", name: "update view", summary: "One update and its comments", usage: "nb update view <n>", module: "browse", fn: "updateView" },
|
|
271
277
|
{ group: "Docs and workspaces", name: "update like", summary: "Like an update (again to unlike)", usage: "nb update like <n>", module: "browse", fn: "updateLike" },
|
|
272
278
|
{ group: "Docs and workspaces", name: "update comment", summary: "Comment on an update", usage: "nb update comment <n> -m text", module: "browse", fn: "updateComment", flags: { ...MESSAGE } },
|
|
279
|
+
{ group: "Docs and workspaces", name: "message list", summary: "Your channels and direct messages, with what's new", usage: "nb message list [--unread]", module: "messages", fn: "list",
|
|
280
|
+
flags: { unread: { type: "boolean", describe: "Only conversations with new messages" } } },
|
|
281
|
+
{ group: "Docs and workspaces", name: "message read", summary: "Read a conversation (marks it read)", usage: "nb message read <#channel|@person|n> [--before <seq>]", module: "messages", fn: "read",
|
|
282
|
+
flags: { before: { type: "string", describe: "Older messages, before this one", valueName: "seq" }, "keep-unread": { type: "boolean", describe: "Don't mark it read" } }, examples: ["nb message read #design", "nb message read @sam"] },
|
|
283
|
+
{ group: "Docs and workspaces", name: "message send", summary: "Send a message as you", usage: "nb message send <#channel|@person> \"text\" [--reply <seq>]", module: "messages", fn: "send",
|
|
284
|
+
flags: { ...MESSAGE, reply: { type: "string", describe: "Reply in the thread of this message", valueName: "seq" } }, examples: ["nb message send #design \"logo is up\"", "nb message send @sam \"thanks!\""] },
|
|
273
285
|
{ group: "Docs and workspaces", name: "member list", summary: "People in the workspace", usage: "nb member list [name]", module: "docs", fn: "memberList" },
|
|
274
286
|
{ group: "Docs and workspaces", name: "search", summary: "Find tasks, files, comments, docs and people", usage: "nb search \"<text>\" [--in tasks,files,comments,docs,people]", module: "docs", fn: "search",
|
|
275
287
|
flags: { in: { type: "string", describe: "Only these: tasks, files, comments, docs, people", valueName: "kinds" } }, examples: ['nb search "login"', 'nb search "login" --in tasks,comments'] },
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
// nb ui (report C9, M4d): a full-screen, keyboard-driven view with three panes: tasks, inbox and changed files.
|
|
2
|
+
// Enter opens, d marks done, p pushes, / filters, r refreshes, ? lists the keys, q quits. --plain, a script or a
|
|
3
|
+
// pipe get nb status instead. Data comes from the same commands' --json; actions run the real command in the normal
|
|
4
|
+
// screen, so their questions and yes prompts work as usual.
|
|
5
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
6
|
+
import { self } from "../self.mjs";
|
|
7
|
+
import readline from "node:readline";
|
|
8
|
+
|
|
9
|
+
import { safe } from "../print/style.mjs";
|
|
10
|
+
|
|
11
|
+
/** @typedef {import("../context.mjs").Context} Context */
|
|
12
|
+
/** @typedef {{ label: string, hint?: string, open?: string[], done?: string[] }} Row */
|
|
13
|
+
/** @typedef {{ pane: number, sel: number[], filter: string, typing: boolean, help: boolean, note: string, head: string, panes: Array<{ title: string, rows: Row[], empty: string }> }} UiState */
|
|
14
|
+
|
|
15
|
+
export const KEYS = [
|
|
16
|
+
["↑ ↓ j k", "move"],
|
|
17
|
+
["Tab ← →", "switch pane"],
|
|
18
|
+
["Enter", "open: task details, the inbox item in the app, a file's diff"],
|
|
19
|
+
["d", "done: finish the task, mark the inbox item read"],
|
|
20
|
+
["p", "push the changed files"],
|
|
21
|
+
["/", "filter the rows"],
|
|
22
|
+
["r", "refresh"],
|
|
23
|
+
["?", "these keys"],
|
|
24
|
+
["q", "quit"],
|
|
25
|
+
];
|
|
26
|
+
|
|
27
|
+
const fit = (/** @type {string} */ s, /** @type {number} */ w) => ([...s].length > w ? `${[...s].slice(0, Math.max(0, w - 1)).join("")}…` : s);
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* The screen as lines, at most `cols` wide and `rows` tall: a header, the three panes stacked (so 80 columns
|
|
31
|
+
* works), and the keys. Pure, so tests read it. @param {UiState} s @param {number} cols @param {number} rows
|
|
32
|
+
* @param {{ bold: (t: string) => string, muted: (t: string) => string, brand: (t: string) => string, accent: (t: string) => string }} c
|
|
33
|
+
*/
|
|
34
|
+
export function render(s, cols, rows, c) {
|
|
35
|
+
const lines = [c.bold(fit(s.head, cols)), ""];
|
|
36
|
+
if (s.help) {
|
|
37
|
+
lines.push(c.bold("Keys"), ...KEYS.map(([k, what]) => fit(` ${k.padEnd(10)} ${what}`, cols)), "", c.muted("Any key to go back"));
|
|
38
|
+
return lines.slice(0, rows);
|
|
39
|
+
}
|
|
40
|
+
const body = Math.max(3, rows - 5);
|
|
41
|
+
const per = Math.max(1, Math.floor(body / 3) - 1);
|
|
42
|
+
s.panes.forEach((pane, i) => {
|
|
43
|
+
const shown = pane.rows.filter((r) => !s.filter || r.label.toLowerCase().includes(s.filter.toLowerCase()));
|
|
44
|
+
const focus = i === s.pane;
|
|
45
|
+
lines.push((focus ? c.accent : c.muted)(fit(`${focus ? "▸" : " "} ${pane.title} (${shown.length})`, cols)));
|
|
46
|
+
if (!shown.length) lines.push(c.muted(fit(` ${s.filter ? "Nothing matches" : pane.empty}`, cols)));
|
|
47
|
+
const sel = Math.min(s.sel[i] ?? 0, Math.max(0, shown.length - 1));
|
|
48
|
+
const from = Math.max(0, Math.min(sel - per + 1, shown.length - per));
|
|
49
|
+
for (const [n, row] of shown.slice(from, from + per).entries()) {
|
|
50
|
+
const on = focus && from + n === sel;
|
|
51
|
+
const text = fit(` ${on ? "›" : " "} ${row.label}${row.hint ? ` ${row.hint}` : ""}`, cols);
|
|
52
|
+
lines.push(on ? c.bold(text) : text);
|
|
53
|
+
}
|
|
54
|
+
});
|
|
55
|
+
lines.push("", s.typing ? fit(`/${s.filter}▏`, cols) : c.muted(fit(s.note || "Enter open · d done · p push · / filter · r refresh · ? keys · q quit", cols)));
|
|
56
|
+
return lines.slice(0, rows);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** One command's --json, as the same nb with the same sign-in. @param {Context} ctx @param {string[]} args */
|
|
60
|
+
function json(ctx, args) {
|
|
61
|
+
return new Promise((resolve) => {
|
|
62
|
+
const child = spawn(...self([...args, "--json", ...pass(ctx)]), { cwd: ctx.cwd, env: { ...ctx.env, NB_NO_UPDATE_CHECK: "1" }, stdio: ["ignore", "pipe", "ignore"] });
|
|
63
|
+
let out = "";
|
|
64
|
+
child.stdout.on("data", (d) => { out += d; });
|
|
65
|
+
child.on("close", () => { try { resolve(JSON.parse(out).data ?? null); } catch { resolve(null); } });
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
const pass = (/** @type {Context} */ ctx) => /** @type {const} */ (["profile", "api-url", "workspace"]).flatMap((f) => (ctx.flags[f] ? [`--${f}`, String(ctx.flags[f])] : []));
|
|
69
|
+
|
|
70
|
+
/** @param {Context} ctx @returns {Promise<Pick<UiState, "head" | "panes">>} */
|
|
71
|
+
async function load(ctx) {
|
|
72
|
+
const [next, inbox, status] = /** @type {any[]} */ (await Promise.all([json(ctx, ["next", "--limit", "30"]), json(ctx, ["inbox"]), json(ctx, ["status"])]));
|
|
73
|
+
const tasks = (next?.items ?? []).map((/** @type {any} */ t) => /** @type {Row} */ ({
|
|
74
|
+
label: `#${t.number} ${safe(t.title)}`, hint: safe(t.why ?? ""),
|
|
75
|
+
open: t.kind === "assignment" ? ["assignment", "view", String(t.number)] : ["task", "view", String(t.number)],
|
|
76
|
+
done: t.kind === "task" ? ["task", "done", String(t.number)] : undefined,
|
|
77
|
+
}));
|
|
78
|
+
const items = (inbox?.items ?? []).map((/** @type {any} */ i, /** @type {number} */ n) => /** @type {Row} */ ({
|
|
79
|
+
label: `${i.readAt ? " " : "•"} ${safe(i.title)}`, hint: i.body ? safe(String(i.body)).replace(/\n/g, " ").slice(0, 40) : "",
|
|
80
|
+
// By id, not position: a notification arriving after the screen loaded doesn't shift which one a key acts on.
|
|
81
|
+
open: ["inbox", "open", String(i.id ?? n + 1)], done: i.readAt ? undefined : ["inbox", "read", String(i.id ?? n + 1)],
|
|
82
|
+
}));
|
|
83
|
+
const files = (status?.files ?? []).map((/** @type {any} */ f) => /** @type {Row} */ ({ label: safe(f.path), hint: safe(f.state), open: ["diff", "--", f.path] }));
|
|
84
|
+
const ws = status?.workspace?.slug ?? "";
|
|
85
|
+
const task = status?.startedTask ? ` · #${status.startedTask.number} ${safe(status.startedTask.title ?? "")}` : "";
|
|
86
|
+
const unread = inbox?.unread ?? 0;
|
|
87
|
+
return {
|
|
88
|
+
head: `NetworkBase · ${ws || "not linked"}${task}${unread ? ` · ${unread} unread` : ""}${status?.offline ? " · offline" : ""}`,
|
|
89
|
+
panes: [
|
|
90
|
+
{ title: "Tasks", rows: tasks, empty: "Nothing open is yours" },
|
|
91
|
+
{ title: "Inbox", rows: items, empty: "Nothing in your inbox" },
|
|
92
|
+
{ title: "Changed here", rows: files, empty: ws ? "Up to date" : "This folder isn't linked: nb init" },
|
|
93
|
+
],
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** @param {Context} ctx */
|
|
98
|
+
export async function ui(ctx) {
|
|
99
|
+
// Not a full-screen terminal: the same overview as nb status (C9).
|
|
100
|
+
if (!ctx.out.interactive || ctx.flags.plain || !process.stdin.isTTY) {
|
|
101
|
+
const { status } = await import("./files.mjs");
|
|
102
|
+
return status(ctx);
|
|
103
|
+
}
|
|
104
|
+
const out = process.stdout;
|
|
105
|
+
/** @type {UiState} */
|
|
106
|
+
const s = { pane: 0, sel: [0, 0, 0], filter: "", typing: false, help: false, note: "Loading…", head: "NetworkBase", panes: [{ title: "Tasks", rows: [], empty: "" }, { title: "Inbox", rows: [], empty: "" }, { title: "Changed here", rows: [], empty: "" }] };
|
|
107
|
+
const { c } = ctx.out;
|
|
108
|
+
const draw = () => out.write(`\x1b[H\x1b[2J${render(s, out.columns || 80, out.rows || 24, c).join("\n")}`);
|
|
109
|
+
const enter = () => { out.write("\x1b[?1049h\x1b[?25l"); process.stdin.setRawMode(true); };
|
|
110
|
+
const leave = () => { process.stdin.setRawMode(false); out.write("\x1b[?25h\x1b[?1049l"); };
|
|
111
|
+
const refresh = async () => { Object.assign(s, await load(ctx), { note: "" }); draw(); };
|
|
112
|
+
/** Runs a real command in the normal screen, then comes back. @param {string[]} args */
|
|
113
|
+
const run = async (args) => {
|
|
114
|
+
leave();
|
|
115
|
+
out.write(`\n$ nb ${args.join(" ")}\n`);
|
|
116
|
+
process.stdin.pause();
|
|
117
|
+
spawnSync(...self([...args, ...pass(ctx)]), { cwd: ctx.cwd, env: ctx.env, stdio: "inherit" });
|
|
118
|
+
out.write("\nPress Enter to go back to nb ui ");
|
|
119
|
+
await new Promise((resolve) => { process.stdin.resume(); process.stdin.once("data", resolve); });
|
|
120
|
+
enter();
|
|
121
|
+
s.note = "Refreshing…";
|
|
122
|
+
draw();
|
|
123
|
+
await refresh();
|
|
124
|
+
};
|
|
125
|
+
const shown = () => s.panes[s.pane]?.rows.filter((r) => !s.filter || r.label.toLowerCase().includes(s.filter.toLowerCase())) ?? [];
|
|
126
|
+
const current = () => shown()[Math.min(s.sel[s.pane] ?? 0, Math.max(0, shown().length - 1))];
|
|
127
|
+
|
|
128
|
+
readline.emitKeypressEvents(process.stdin);
|
|
129
|
+
enter();
|
|
130
|
+
draw();
|
|
131
|
+
const loaded = refresh();
|
|
132
|
+
out.on("resize", draw);
|
|
133
|
+
let busy = false;
|
|
134
|
+
/** @type {Row | null | undefined} the task row d was pressed on once */
|
|
135
|
+
let armed = null;
|
|
136
|
+
await new Promise((resolve) => {
|
|
137
|
+
/** @param {string} str @param {{ name?: string, ctrl?: boolean }} key */
|
|
138
|
+
const onKey = async (str, key = {}) => {
|
|
139
|
+
if (busy) return;
|
|
140
|
+
if (str !== "d") armed = null;
|
|
141
|
+
if (key.ctrl && key.name === "c") { process.stdin.off("keypress", onKey); return resolve(null); }
|
|
142
|
+
if (s.help) { s.help = false; return draw(); }
|
|
143
|
+
if (s.typing) {
|
|
144
|
+
if (key.name === "return" || key.name === "escape") s.typing = false;
|
|
145
|
+
else if (key.name === "backspace") s.filter = s.filter.slice(0, -1);
|
|
146
|
+
else if (str && str.length === 1 && str >= " ") s.filter += str;
|
|
147
|
+
return draw();
|
|
148
|
+
}
|
|
149
|
+
const n = shown().length;
|
|
150
|
+
if (str === "q" || key.name === "escape") { process.stdin.off("keypress", onKey); return resolve(null); }
|
|
151
|
+
if (key.name === "down" || str === "j") s.sel[s.pane] = Math.min((s.sel[s.pane] ?? 0) + 1, Math.max(0, n - 1));
|
|
152
|
+
else if (key.name === "up" || str === "k") s.sel[s.pane] = Math.max((s.sel[s.pane] ?? 0) - 1, 0);
|
|
153
|
+
else if (key.name === "tab" || key.name === "right") s.pane = (s.pane + 1) % 3;
|
|
154
|
+
else if (key.name === "left") s.pane = (s.pane + 2) % 3;
|
|
155
|
+
else if (str === "?") s.help = true;
|
|
156
|
+
else if (str === "/") { s.typing = true; s.filter = ""; }
|
|
157
|
+
else if (str === "r") { s.note = "Refreshing…"; draw(); await loaded; return refresh(); }
|
|
158
|
+
else if (key.name === "return" || str === "d" || str === "p") {
|
|
159
|
+
await loaded;
|
|
160
|
+
const row = current();
|
|
161
|
+
const args = str === "p" ? ["push"] : str === "d" ? row?.done : row?.open;
|
|
162
|
+
if (!args) { s.note = str === "d" ? "Nothing to mark done here" : "Nothing to open"; return draw(); }
|
|
163
|
+
// Finishing a task is one key too easy to hit by mistake: d twice.
|
|
164
|
+
if (str === "d" && s.pane === 0 && armed !== row) { armed = row; s.note = `Press d again to finish ${row?.label ?? "it"}`; return draw(); }
|
|
165
|
+
armed = null;
|
|
166
|
+
busy = true;
|
|
167
|
+
try { await run(args); } finally { busy = false; }
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
draw();
|
|
171
|
+
};
|
|
172
|
+
process.stdin.on("keypress", onKey);
|
|
173
|
+
});
|
|
174
|
+
out.off("resize", draw);
|
|
175
|
+
leave();
|
|
176
|
+
process.stdin.pause();
|
|
177
|
+
ctx.out.result("nb.ui/1", { closed: true }, () => []);
|
|
178
|
+
}
|
package/lib/context.mjs
CHANGED
|
@@ -10,9 +10,8 @@ import { createOutput } from "./print/out.mjs";
|
|
|
10
10
|
import { appendUndo } from "./undo-log.mjs";
|
|
11
11
|
|
|
12
12
|
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
export const VERSION = JSON.parse(fs.readFileSync(PACKAGE_JSON, "utf8")).version;
|
|
13
|
+
/** The version comes from package.json only, so it can't drift (finding 92); the single-file build bakes it in (C7). */
|
|
14
|
+
export const VERSION = /** @type {any} */ (globalThis).__NB_VERSION__ ?? JSON.parse(fs.readFileSync(path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "package.json"), "utf8")).version;
|
|
16
15
|
|
|
17
16
|
/**
|
|
18
17
|
* @param {{ flags: Record<string, any>, positionals: string[], cwd?: string, env?: NodeJS.ProcessEnv, fetchImpl?: typeof fetch, io?: Parameters<typeof createOutput>[1] & { onUndo?: (u: { token: string }) => void } }} input
|
package/lib/error-fixes.mjs
CHANGED
|
@@ -33,6 +33,7 @@ export const FIXES = /** @type {Record<string, string>} */ ({
|
|
|
33
33
|
"NOT_SIGNED_IN": "nb login",
|
|
34
34
|
"NOT_LINKED": "nb init <workspace>, or pass --workspace",
|
|
35
35
|
"WORKSPACE_NOT_FOUND": "nb workspace list",
|
|
36
|
+
"LEARN_STEP_FAILED": "Run nb learn again; it picks up the same practice workspace",
|
|
36
37
|
"TASK_NOT_FOUND": "nb task list --all",
|
|
37
38
|
"DOC_NOT_FOUND": "nb doc list",
|
|
38
39
|
"NOT_A_TASK": "nb inbox open <n>",
|
package/lib/mcp/tools.mjs
CHANGED
|
@@ -338,6 +338,19 @@ TOOLS.push(
|
|
|
338
338
|
description: "Answer a question an agent asked the user in NetworkBase. Answers in their name, so it needs a yes.",
|
|
339
339
|
needsYes: (a) => `Answer question ${a.id}: "${String(a.answer).slice(0, 200)}"`,
|
|
340
340
|
run: (nb, a) => nb("ask answer", [String(a.id), String(a.answer)]) },
|
|
341
|
+
{ name: "networkbase_message_list", title: "Messages", tier: "yes", pack: "people", props: { unread: { type: "boolean" } },
|
|
342
|
+
description: `The user's channels and direct messages with unread counts. Private, so it needs a yes (their own sign-in only; agent sign-ins can't read messages). ${DATA}`,
|
|
343
|
+
needsYes: () => "Let the agent see your list of conversations and their latest messages",
|
|
344
|
+
fields: { conversations: ["label", "workspace", "unread", "lastAt", "lastPreview"] },
|
|
345
|
+
run: (nb, a) => nb("message list", [], a.unread ? { unread: true } : {}) },
|
|
346
|
+
{ name: "networkbase_message_read", title: "Read a conversation", tier: "yes", pack: "people", props: { conversation: { type: "string", description: "#channel, @person or a number from networkbase_message_list" } }, required: ["conversation"],
|
|
347
|
+
description: `The latest messages in a conversation, oldest first. Other people's words, so it needs a yes; it leaves them unread. ${DATA}`,
|
|
348
|
+
needsYes: (a) => `Let the agent read ${String(a.conversation).slice(0, 60)}`,
|
|
349
|
+
run: (nb, a) => nb("message read", [String(a.conversation)], { "keep-unread": true }) },
|
|
350
|
+
{ name: "networkbase_message_send", title: "Send a message", tier: "yes", pack: "people", props: { conversation: { type: "string" }, text: { type: "string" } }, required: ["conversation", "text"],
|
|
351
|
+
description: "Send a message as the user. It goes to other people, so it always needs a yes.",
|
|
352
|
+
needsYes: (a) => `Send to ${String(a.conversation).slice(0, 60)} as you: "${String(a.text).slice(0, 200)}"`,
|
|
353
|
+
run: (nb, a) => nb("message send", [String(a.conversation), String(a.text)]) },
|
|
341
354
|
{ name: "networkbase_update_list", title: "Updates", tier: "read", pack: "people", props: { workspace: workspaceProp },
|
|
342
355
|
description: `The workspace's updates feed, numbered. ${DATA}`,
|
|
343
356
|
run: (nb, a) => nb("update list", [], ws(a)) },
|
package/lib/self.mjs
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
// How nb runs itself again (nb learn, nb start, nb ui, completions, the MCP finish step). From npm it's
|
|
2
|
+
// `node <path to nb.mjs> …`; the single-file build (report C7) is one program, so it's just `nb …`.
|
|
3
|
+
/** @type {boolean} set by scripts/single-file.mjs */
|
|
4
|
+
export const SINGLE_FILE = Boolean(/** @type {any} */ (globalThis).__NB_SINGLE_FILE__);
|
|
5
|
+
|
|
6
|
+
/** The program and the first arguments that start nb again. @param {string[]} args @returns {[string, string[]]} */
|
|
7
|
+
export const self = (args) => [process.execPath, SINGLE_FILE ? args : [process.argv[1] ?? "", ...args]];
|