@networkbase/cli 2.1.5 → 2.1.7
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/browse.mjs +25 -14
- package/lib/commands/complete.mjs +2 -1
- package/lib/commands/files.mjs +8 -2
- 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 +83 -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 +2 -0
- package/lib/mcp/tools.mjs +13 -0
- package/lib/print/out.mjs +2 -1
- 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
|
}
|
package/lib/commands/browse.mjs
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
// workspace view, activity, sprint list|view, update post, file history|move|rename|delete|attach|detach
|
|
2
2
|
// (report §17.4, A2.5, A8.7, D25).
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
|
|
3
5
|
import { CliError, EXIT, usage } from "../errors.mjs";
|
|
6
|
+
import { toRemote } from "../sync/local.mjs";
|
|
4
7
|
import { commentText, safe } from "../print/style.mjs";
|
|
5
8
|
import { confirm } from "../tui/ask.mjs";
|
|
6
9
|
import { formatDate, formatWhen, resolveTask, taskRef } from "./tasks.mjs";
|
|
@@ -86,13 +89,21 @@ export async function updatePost(ctx) {
|
|
|
86
89
|
ctx.out.result("nb.update.post/1", { posted: true }, () => `${ctx.out.c.success(ctx.out.sym.done)} Posted the update`);
|
|
87
90
|
}
|
|
88
91
|
|
|
89
|
-
/**
|
|
90
|
-
|
|
92
|
+
/**
|
|
93
|
+
* A path argument as a workspace path. With a leading / it is one; otherwise it's relative to where you are in the
|
|
94
|
+
* linked folder, so in a folder linked to /design, nb file history logo.svg means /design/logo.svg (found in the
|
|
95
|
+
* 2.1.6 live check: these commands looked at the workspace root). @param {Context} ctx @param {string} p
|
|
96
|
+
*/
|
|
97
|
+
const remote = (ctx, p) => {
|
|
98
|
+
if (p.startsWith("/") || !ctx.project || !ctx.root) return `/${p.replace(/^\/+/, "")}`;
|
|
99
|
+
const rel = path.relative(ctx.root, path.resolve(ctx.cwd, p));
|
|
100
|
+
return rel.startsWith("..") || path.isAbsolute(rel) ? `/${p.replace(/^\/+/, "")}` : toRemote(ctx.project.remoteRoot ?? "/", rel);
|
|
101
|
+
};
|
|
91
102
|
|
|
92
103
|
/** @param {Context} ctx @param {string} p */
|
|
93
104
|
export async function nodeOf(ctx, p) {
|
|
94
|
-
return /** @type {any} */ (await ctx.api.get("/api/v1/extension/file", { query: { projectId: ctx.requireWorkspace(), path: remote(p), transfer: "metadata" } }).catch((error) => {
|
|
95
|
-
if (error instanceof CliError && error.status === 404) throw new CliError("NOT_FOUND", `No file ${remote(p)} in this workspace`);
|
|
105
|
+
return /** @type {any} */ (await ctx.api.get("/api/v1/extension/file", { query: { projectId: ctx.requireWorkspace(), path: remote(ctx, p), transfer: "metadata" } }).catch((error) => {
|
|
106
|
+
if (error instanceof CliError && error.status === 404) throw new CliError("NOT_FOUND", `No file ${remote(ctx, p)} in this workspace`);
|
|
96
107
|
throw error;
|
|
97
108
|
}));
|
|
98
109
|
}
|
|
@@ -105,7 +116,7 @@ export async function fileHistory(ctx) {
|
|
|
105
116
|
const res = /** @type {any} */ (await ctx.api.get("/api/v1/extension/file-history", { query: { projectId: ctx.requireWorkspace(), nodeId: node.nodeId ?? node.id } }));
|
|
106
117
|
const { c } = ctx.out;
|
|
107
118
|
// Which version is active and what each was based on (C3), so "going back" reads plainly.
|
|
108
|
-
ctx.out.result("nb.file.history/1", { path: remote(p), activeVersion: res.activeVersion ?? null, versions: res.versions }, (d) => [
|
|
119
|
+
ctx.out.result("nb.file.history/1", { path: remote(ctx, p), activeVersion: res.activeVersion ?? null, versions: res.versions }, (d) => [
|
|
109
120
|
...d.versions.map((/** @type {any} */ v) => `${v.version === d.activeVersion ? c.brand(ctx.out.sym.cursor) : " "} v${v.version} ${c.muted(String(v.uploadedAt).slice(0, 16).replace("T", " "))} ${v.uploadedByUsername ? `@${safe(v.uploadedByUsername)}` : safe(v.uploadedByName ?? "someone")}${v.via ? c.muted(` via ${v.via === "agent" ? safe(v.agentName ?? "an agent") : "CLI"}`) : ""}${v.basedOnVersion && v.basedOnVersion !== v.version - 1 ? c.muted(` based on v${v.basedOnVersion}`) : ""}${v.version === d.activeVersion ? ` ${c.success("active")}` : ""}${v.comment ? ` ${safe(v.comment)}` : ""}`),
|
|
110
121
|
...(d.versions.length > 1 ? ["", c.muted(` Go back: nb file use ${safe(d.path.slice(1))} v<n>`)] : []),
|
|
111
122
|
]);
|
|
@@ -118,7 +129,7 @@ export async function fileUse(ctx) {
|
|
|
118
129
|
if (!p || !Number.isInteger(version) || version < 1) throw usage("nb file use <path> v<n>", "See the versions: nb file history <path>");
|
|
119
130
|
const node = await nodeOf(ctx, p);
|
|
120
131
|
const res = /** @type {any} */ (await ctx.api.post("/api/v1/extension/file-history", { projectId: ctx.requireWorkspace(), nodeId: node.nodeId ?? node.id, version }));
|
|
121
|
-
ctx.out.result("nb.file.use/1", { path: remote(p), activeVersion: res.activeVersion, previousVersion: res.previousVersion }, (d) => [
|
|
132
|
+
ctx.out.result("nb.file.use/1", { path: remote(ctx, p), activeVersion: res.activeVersion, previousVersion: res.previousVersion }, (d) => [
|
|
122
133
|
d.previousVersion === d.activeVersion ? `v${d.activeVersion} of ${safe(d.path)} was already active` : `${ctx.out.c.success(ctx.out.sym.done)} v${d.activeVersion} of ${safe(d.path)} is active (was v${d.previousVersion}); the next save is based on it`,
|
|
123
134
|
ctx.out.c.muted(` nb pull gets it here · nb undo puts v${d.previousVersion} back`),
|
|
124
135
|
]);
|
|
@@ -129,15 +140,15 @@ async function fileOperation(ctx, kind) {
|
|
|
129
140
|
const [p, target] = ctx.positionals;
|
|
130
141
|
if (!p || (kind !== "trash" && !target)) throw usage(kind === "move" ? "nb file move <path> <folder>" : kind === "rename" ? "nb file rename <path> <new name>" : "nb file delete <path>");
|
|
131
142
|
const node = await nodeOf(ctx, p);
|
|
132
|
-
const question = kind === "trash" ? `Move ${remote(p)} to the workspace Trash?` : kind === "move" ? `Move ${remote(p)} to ${remote(String(target))}?` : `Rename ${remote(p)} to ${target}?`;
|
|
143
|
+
const question = kind === "trash" ? `Move ${remote(ctx, p)} to the workspace Trash?` : kind === "move" ? `Move ${remote(ctx, p)} to ${remote(ctx, String(target))}?` : `Rename ${remote(ctx, p)} to ${target}?`;
|
|
133
144
|
if (!(await confirm(ctx, { key: kind, heldByServer: true, question, yesLabel: kind === "trash" ? "Move to Trash" : "Yes", defaultYes: kind !== "trash" }))) return EXIT.cancelled;
|
|
134
145
|
let parentId = null;
|
|
135
|
-
if (kind === "move" && remote(String(target)) !== "/") parentId = (await nodeOf(ctx, String(target).replace(/\/+$/, ""))).nodeId ?? null;
|
|
146
|
+
if (kind === "move" && remote(ctx, String(target)) !== "/") parentId = (await nodeOf(ctx, String(target).replace(/\/+$/, ""))).nodeId ?? null;
|
|
136
147
|
await ctx.api.post("/api/v1/extension/file-operation", {
|
|
137
148
|
kind, projectId: ctx.requireWorkspace(), nodeId: node.nodeId ?? node.id, expectedUpdatedAt: new Date(node.updatedAt).toISOString(),
|
|
138
149
|
...(kind === "move" ? { parentId } : kind === "rename" ? { name: String(target) } : {}),
|
|
139
150
|
});
|
|
140
|
-
ctx.out.result(`nb.file.${kind}/1`, { path: remote(p) }, (d) => `${ctx.out.c.success(ctx.out.sym.done)} ${kind === "trash" ? "Moved to Trash" : kind === "move" ? "Moved" : "Renamed"} ${safe(d.path)}`);
|
|
151
|
+
ctx.out.result(`nb.file.${kind}/1`, { path: remote(ctx, p) }, (d) => `${ctx.out.c.success(ctx.out.sym.done)} ${kind === "trash" ? "Moved to Trash" : kind === "move" ? "Moved" : "Renamed"} ${safe(d.path)}`);
|
|
141
152
|
}
|
|
142
153
|
/** @param {Context} ctx */
|
|
143
154
|
export const fileMove = (ctx) => fileOperation(ctx, "move");
|
|
@@ -153,8 +164,8 @@ async function attach(ctx, detach) {
|
|
|
153
164
|
const as = ctx.flags.as ?? "draft";
|
|
154
165
|
if (!["reference", "draft", "final"].includes(as)) throw usage("--as must be reference, draft or final");
|
|
155
166
|
const task = await resolveTask(ctx, taskRef(ctx, undefined));
|
|
156
|
-
await ctx.api.post(`/api/v1/tasks/${task.id}/files`, { projectId: ctx.requireWorkspace(), path: remote(p), as, ...(detach ? { detach: true } : {}) });
|
|
157
|
-
ctx.out.result(detach ? "nb.file.detach/1" : "nb.file.attach/1", { path: remote(p), number: task.taskNumber, as }, (d) => `${ctx.out.c.success(ctx.out.sym.done)} ${detach ? `Took ${safe(d.path)} off #${d.number}` : `Attached ${safe(d.path)} to #${d.number} as ${d.as}`}`);
|
|
167
|
+
await ctx.api.post(`/api/v1/tasks/${task.id}/files`, { projectId: ctx.requireWorkspace(), path: remote(ctx, p), as, ...(detach ? { detach: true } : {}) });
|
|
168
|
+
ctx.out.result(detach ? "nb.file.detach/1" : "nb.file.attach/1", { path: remote(ctx, p), number: task.taskNumber, as }, (d) => `${ctx.out.c.success(ctx.out.sym.done)} ${detach ? `Took ${safe(d.path)} off #${d.number}` : `Attached ${safe(d.path)} to #${d.number} as ${d.as}`}`);
|
|
158
169
|
}
|
|
159
170
|
/** @param {Context} ctx */
|
|
160
171
|
export const fileAttach = (ctx) => attach(ctx, false);
|
|
@@ -191,7 +202,7 @@ export async function fileRestore(ctx) {
|
|
|
191
202
|
export async function fileMkdir(ctx) {
|
|
192
203
|
const p = ctx.positionals[0];
|
|
193
204
|
if (!p) throw usage("nb file mkdir <folder>");
|
|
194
|
-
const clean = remote(p.replace(/\/+$/, ""));
|
|
205
|
+
const clean = remote(ctx, p.replace(/\/+$/, ""));
|
|
195
206
|
const parentPath = clean.slice(0, clean.lastIndexOf("/")) || "/";
|
|
196
207
|
const parentId = parentPath === "/" ? null : (await nodeOf(ctx, parentPath)).nodeId ?? null;
|
|
197
208
|
const { folder } = /** @type {any} */ (await ctx.api.post("/api/v1/extension/file-operation", { kind: "mkdir", projectId: ctx.requireWorkspace(), parentId, name: clean.slice(clean.lastIndexOf("/") + 1) }));
|
|
@@ -203,8 +214,8 @@ export async function fileCopy(ctx) {
|
|
|
203
214
|
const [from, to] = ctx.positionals;
|
|
204
215
|
if (!from || !to) throw usage("nb file copy <file> <to>", "Like nb file copy report.md drafts/report-v2.md");
|
|
205
216
|
const projectId = ctx.requireWorkspace();
|
|
206
|
-
const source = remote(from);
|
|
207
|
-
const target = to.endsWith("/") ? `${remote(to).replace(/\/+$/, "")}/${source.split("/").pop()}` : remote(to);
|
|
217
|
+
const source = remote(ctx, from);
|
|
218
|
+
const target = to.endsWith("/") ? `${remote(ctx, to).replace(/\/+$/, "")}/${source.split("/").pop()}` : remote(ctx, to);
|
|
208
219
|
const res = await ctx.api.download("/api/v1/extension/file", { projectId, path: source, transfer: "raw" });
|
|
209
220
|
const bytes = Buffer.from(await res.arrayBuffer());
|
|
210
221
|
const crypto = await import("node:crypto");
|
|
@@ -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;
|
package/lib/commands/files.mjs
CHANGED
|
@@ -200,7 +200,12 @@ export async function pull(ctx, options = {}) {
|
|
|
200
200
|
results.push({ path: item.path, did: "conflict", version: r.version, copy: path.relative(root, copy) });
|
|
201
201
|
return;
|
|
202
202
|
}
|
|
203
|
-
const got = await downloadTo(ctx.api, project.workspaceId, item.path, abs, r.hash)
|
|
203
|
+
const got = await downloadTo(ctx.api, project.workspaceId, item.path, abs, r.hash).catch((error) => {
|
|
204
|
+
// A file whose content isn't on the server yet (an unfinished import) is skipped, not the end of the pull.
|
|
205
|
+
if (error instanceof CliError && error.code === "CONTENT_NOT_READY") { skipped.push({ path: item.path, reason: "its content isn't on the server yet" }); return null; }
|
|
206
|
+
throw error;
|
|
207
|
+
});
|
|
208
|
+
if (!got) return;
|
|
204
209
|
if (got.content) saveBaseCopy(root, got.hash, got.content);
|
|
205
210
|
recordBase(state, item.path, { nodeId: r.nodeId, version: r.version, hash: got.hash, abs });
|
|
206
211
|
results.push({ path: item.path, did: item.action === "restore" ? "restored" : item.base ? "updated" : "new", version: r.version });
|
|
@@ -210,7 +215,8 @@ export async function pull(ctx, options = {}) {
|
|
|
210
215
|
// 8 downloads at a time, 4 on Windows (A12.6).
|
|
211
216
|
let next = 0;
|
|
212
217
|
const worker = async () => { while (next < todo.length) await apply(/** @type {PlanItem} */ (todo[next++])); };
|
|
213
|
-
|
|
218
|
+
// What did arrive is recorded even when a later file stops the pull, so it isn't a conflict next time.
|
|
219
|
+
await Promise.all(Array.from({ length: Math.min(process.platform === "win32" ? 4 : 8, todo.length) }, worker)).catch((error) => { writeState(root, state); throw error; });
|
|
214
220
|
results.sort((a, b) => a.path.localeCompare(b.path));
|
|
215
221
|
writeState(root, state);
|
|
216
222
|
pruneBaseCopies(root, state, Number(readUserConfig(ctx.env)["base-cache-mb"] ?? 200) * 1024 * 1024);
|
|
@@ -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,83 @@
|
|
|
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
|
+
/** Fits a column: long names end in … so the rows stay aligned. @param {string} s @param {number} n */
|
|
11
|
+
const cut = (s, n) => ([...s].length > n ? `${[...s].slice(0, n - 1).join("")}…` : s);
|
|
12
|
+
|
|
13
|
+
/** @param {Context} ctx @returns {Promise<any[]>} */
|
|
14
|
+
async function conversations(ctx) {
|
|
15
|
+
return /** @type {any} */ (await ctx.api.get("/api/v1/chat/conversations")).conversations ?? [];
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* "#design", "@sam", a group's name or a number from `nb message list`. A channel name in several workspaces asks
|
|
20
|
+
* which (--workspace picks; scripts get the choices). @param {Context} ctx @param {string | undefined} ref
|
|
21
|
+
*/
|
|
22
|
+
async function pick(ctx, ref) {
|
|
23
|
+
// In bash and zsh an unquoted #design is a comment, so nb gets nothing: say so (found in the 2.1.6 live check).
|
|
24
|
+
if (!ref) throw usage("Which conversation?", "nb message read design (a channel without #, or '#design' in quotes), @sam, or a number from nb message list");
|
|
25
|
+
const all = await conversations(ctx);
|
|
26
|
+
if (/^\d+$/.test(ref)) {
|
|
27
|
+
const hit = all[Number(ref) - 1];
|
|
28
|
+
if (!hit) throw new CliError("NOT_FOUND", `No conversation ${ref}`, { hint: "nb message list" });
|
|
29
|
+
return hit;
|
|
30
|
+
}
|
|
31
|
+
const want = ref.toLowerCase();
|
|
32
|
+
const ws = ctx.flags.workspace ? String(ctx.flags.workspace).toLowerCase() : null;
|
|
33
|
+
const named = all.filter((c) => c.label.toLowerCase() === want || (!/^[#@]/.test(want) && c.label.toLowerCase() === `#${want}`));
|
|
34
|
+
const hits = ws ? named.filter((c) => String(c.workspace ?? "").toLowerCase() === ws || String(c.workspaceId ?? "").toLowerCase() === ws) : named;
|
|
35
|
+
if (hits.length === 1) return hits[0];
|
|
36
|
+
if (!hits.length) {
|
|
37
|
+
const near = all.filter((c) => c.label.toLowerCase().includes(want.replace(/^[#@]/, ""))).slice(0, 5).map((c) => (c.workspace ? `${c.label} (${c.workspace})` : c.label));
|
|
38
|
+
throw new CliError("NOT_FOUND", `No conversation ${ref}`, { hint: near.length ? `Did you mean ${near.join(", ")}?` : "nb message list" });
|
|
39
|
+
}
|
|
40
|
+
// Choices by workspace (--answer conversation=deepscope-ai, or -w deepscope-ai), never raw ids.
|
|
41
|
+
const ws2 = await ask(ctx, { key: "conversation", header: "Which", question: `${ref} is in ${hits.length} workspaces. Which one?`, options: hits.slice(0, 4).map((c) => ({ value: String(c.workspace ?? c.id), label: `${safe(c.label)} in ${safe(c.workspace ?? "no workspace")}` })) });
|
|
42
|
+
// Exactly the one chosen, never a guess: a message must not go to the wrong conversation (security review).
|
|
43
|
+
const chosen = hits.find((c) => String(c.workspace ?? c.id) === ws2);
|
|
44
|
+
if (!chosen) throw new CliError("NOT_FOUND", `${ref} isn't in ${ws2}`, { hint: `Use a number from nb message list, or -w ${hits.map((c) => c.workspace).filter(Boolean).join(" or -w ")}` });
|
|
45
|
+
return chosen;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** nb message list. @param {Context} ctx */
|
|
49
|
+
export async function list(ctx) {
|
|
50
|
+
const all = (await conversations(ctx)).filter((c) => !ctx.flags.unread || c.unread > 0);
|
|
51
|
+
const { c } = ctx.out;
|
|
52
|
+
ctx.out.result("nb.message.list/1", { conversations: all }, (d) => d.conversations.length ? [
|
|
53
|
+
...d.conversations.map((/** @type {any} */ m, /** @type {number} */ n) => `${String(n + 1).padStart(3)} ${m.unread ? c.brand(ctx.out.sym.brand) : " "} ${cut(safe(m.label), 22).padEnd(22)} ${c.muted(cut(safe(m.workspace ?? ""), 18).padEnd(18))} ${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)}`),
|
|
54
|
+
c.muted(" nb message read <#channel|@person|n> · nb message send <#channel|@person> \"text\""),
|
|
55
|
+
] : ctx.flags.unread ? "Nothing unread" : "No conversations yet. Start one in the app: Messages", { page: true });
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** nb message read #design: the latest messages, oldest first, then marks them read. @param {Context} ctx */
|
|
59
|
+
export async function read(ctx) {
|
|
60
|
+
const conv = await pick(ctx, ctx.positionals[0]);
|
|
61
|
+
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) } : {} }));
|
|
62
|
+
/** @type {any[]} */
|
|
63
|
+
const messages = res.messages ?? [];
|
|
64
|
+
const last = messages.at(-1);
|
|
65
|
+
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(() => {});
|
|
66
|
+
const { c } = ctx.out;
|
|
67
|
+
ctx.out.result("nb.message.read/1", { conversation: { id: conv.id, label: conv.label, workspace: conv.workspace }, messages }, (d) => d.messages.length ? [
|
|
68
|
+
c.bold(safe(d.conversation.label)) + (d.conversation.workspace ? c.muted(` · ${safe(d.conversation.workspace)}`) : ""),
|
|
69
|
+
...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)`) : ""}`),
|
|
70
|
+
c.muted(` Older: nb message read ${d.conversation.label} --before ${d.messages[0].seq} · Reply: nb message send ${d.conversation.label} "text"`),
|
|
71
|
+
] : "No messages here yet", { page: true });
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** nb message send #design "text" [--reply <seq>]. @param {Context} ctx */
|
|
75
|
+
export async function send(ctx) {
|
|
76
|
+
const [ref, ...words] = ctx.positionals;
|
|
77
|
+
const text = String(ctx.flags.message ?? words.join(" ")).trim();
|
|
78
|
+
if (!ref || !text) throw usage('nb message send <#channel|@person> "text"');
|
|
79
|
+
const conv = await pick(ctx, ref);
|
|
80
|
+
if (!conv.canReply) throw new CliError("FORBIDDEN", `You can't reply in ${conv.label}`, { hint: "nb message list" });
|
|
81
|
+
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) } : {}) }));
|
|
82
|
+
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)}`);
|
|
83
|
+
}
|
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 '#design' -w design-lab", "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
|
@@ -22,6 +22,7 @@ export const FIXES = /** @type {Record<string, string>} */ ({
|
|
|
22
22
|
"NEEDS_CONFIRMATION": "Show the summary; on a yes, send the same request with the confirm token (--confirm)",
|
|
23
23
|
"SECRET_DETECTED": "Remove it, or push with --confirm-secrets if it's safe (agents can't)",
|
|
24
24
|
"CONTENT_MISMATCH": "Run the command again",
|
|
25
|
+
"CONTENT_NOT_READY": "Pull again later; nb pull skips it meanwhile",
|
|
25
26
|
"CONTENT_HASH_MISMATCH": "Run the command again",
|
|
26
27
|
"RATE_LIMITED": "Wait for the time in Retry-After",
|
|
27
28
|
"NOT_SUPPORTED": "Use the app for now",
|
|
@@ -33,6 +34,7 @@ export const FIXES = /** @type {Record<string, string>} */ ({
|
|
|
33
34
|
"NOT_SIGNED_IN": "nb login",
|
|
34
35
|
"NOT_LINKED": "nb init <workspace>, or pass --workspace",
|
|
35
36
|
"WORKSPACE_NOT_FOUND": "nb workspace list",
|
|
37
|
+
"LEARN_STEP_FAILED": "Run nb learn again; it picks up the same practice workspace",
|
|
36
38
|
"TASK_NOT_FOUND": "nb task list --all",
|
|
37
39
|
"DOC_NOT_FOUND": "nb doc list",
|
|
38
40
|
"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/print/out.mjs
CHANGED
|
@@ -121,7 +121,8 @@ export function createOutput(mode, io = {}) {
|
|
|
121
121
|
table(allCols, rows) {
|
|
122
122
|
if (format) {
|
|
123
123
|
// Plain text without colour or truncation: a cell is what the column's value says.
|
|
124
|
-
|
|
124
|
+
// The terminal's markers (the started task's ❯) mean nothing pasted into chat or a sheet (2.1.6 live check).
|
|
125
|
+
const plainCell = (/** @type {string} */ s) => stripForJson(String(s ?? "")).replace(new RegExp(`^\\s*[${sym.cursor}${sym.brand}]\\s+`), "").trim();
|
|
125
126
|
const csv = (/** @type {string} */ s) => (/[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s);
|
|
126
127
|
const md = (/** @type {string} */ s) => s.replace(/\|/g, "\\|").replace(/\n/g, " ");
|
|
127
128
|
const head = allCols.map((col) => col.title || " ");
|
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]];
|