@networkbase/cli 2.1.1 → 2.1.2

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.
@@ -29,7 +29,7 @@ export async function resolveTask(ctx, ref, { brief = false } = {}) {
29
29
  if (error instanceof CliError && (error.status === 404 || error.code === "NOT_FOUND")) throw new CliError("TASK_NOT_FOUND", `No task ${ref} in this workspace`, { hint: "See nb task list" });
30
30
  throw error;
31
31
  }));
32
- return { ...detail.task, subtasks: detail.subtasks ?? [], files: detail.files ?? [], comments: detail.comments ?? [], pushes: detail.pushes ?? [] };
32
+ return { ...detail.task, subtasks: detail.subtasks ?? [], files: detail.files ?? [], comments: detail.comments ?? [], pushes: detail.pushes ?? [], meta: detail.meta ?? null };
33
33
  }
34
34
 
35
35
  /**
@@ -110,11 +110,13 @@ export async function list(ctx) {
110
110
  if (ctx.flags.sprint) query.sprint = await resolveSprint(ctx, String(ctx.flags.sprint));
111
111
  if (ctx.flags.priority) query.priority = String(ctx.flags.priority);
112
112
  if (ctx.flags.sort) query.sort = String(ctx.flags.sort);
113
+ if (ctx.flags.label) query.label = String(ctx.flags.label).toLowerCase();
114
+ if (ctx.flags.starred) { query.starred = "1"; query.scope = "all"; }
113
115
  const { tasks } = /** @type {any} */ (await ctx.api.get("/api/v1/extension/workspace-tasks", { query }));
114
116
  let rows = tasks.filter((/** @type {any} */ t) => (wanted ? wanted.has(t.status) || (wanted.has("review") && t.reviewStatus === "pending") : true));
115
117
  const more = Math.max(0, rows.length - limit);
116
118
  rows = rows.slice(0, limit);
117
- const data = { scope, tasks: rows.map((/** @type {any} */ t) => ({ id: t.id, number: t.taskNumber, title: t.title, status: t.status, reviewStatus: t.reviewStatus ?? null, priority: t.priority ?? null, dueDate: t.dueDate ?? null, assignee: t.assigneeUsername ?? t.assigneeName ?? null, subtasks: t.subtaskSummary ?? null })), more };
119
+ const data = { scope, tasks: rows.map((/** @type {any} */ t) => ({ id: t.id, number: t.taskNumber, title: t.title, status: t.status, reviewStatus: t.reviewStatus ?? null, priority: t.priority ?? null, dueDate: t.dueDate ?? null, assignee: t.assigneeUsername ?? t.assigneeName ?? null, labels: t.labels ?? [], subtasks: t.subtaskSummary ?? null })), more };
118
120
  ctx.out.result("nb.task.list/1", data, (d) => {
119
121
  if (!d.tasks.length) return scope === "mine" ? "No open tasks assigned to you · nb task list --all for everyone's" : "No open tasks";
120
122
  const started = ctx.project?.startedTask?.id;
@@ -122,7 +124,7 @@ export async function list(ctx) {
122
124
  ...ctx.out.table([
123
125
  // The started task gets a marker and a space, so plain output never reads as "-1" (C16 #4).
124
126
  { title: "#", value: (t) => `${t.id === started ? ctx.out.c.brand(ctx.out.sym.cursor) : " "} ${t.number ?? ""}`, align: "right" },
125
- { title: "Task", value: (t) => safe(t.title), flex: true },
127
+ { title: "Task", value: (t) => `${safe(t.title)}${t.labels?.length ? ` ${ctx.out.c.accent(t.labels.map((/** @type {string} */ l) => `[${safe(l)}]`).join(" "))}` : ""}`, flex: true },
126
128
  { title: "Status", value: (t) => statusWord(t) },
127
129
  { title: "Due", value: (t) => (t.dueDate ? formatDate(t.dueDate) : "—"), optional: true },
128
130
  { title: "Assignee", value: (t) => (t.assignee ? `@${safe(t.assignee)}` : "—"), optional: true },
@@ -174,10 +176,21 @@ export function formatDate(iso) {
174
176
  if (days === 0) return "today";
175
177
  if (days === 1) return "tomorrow";
176
178
  if (days === -1) return "yesterday";
177
- if (days > 1 && days < 7) return d.toLocaleDateString(undefined, { weekday: "short" });
179
+ // Relative within a week (C11): "in 3 days", "4 days ago"; exact dates stay in --json.
180
+ if (days > 1 && days < 7) return `in ${days} days`;
181
+ if (days < -1 && days > -7) return `${-days} days ago`;
178
182
  return d.toLocaleDateString(undefined, { day: "numeric", month: "short" });
179
183
  }
180
184
 
185
+ /** When something happened (C11): "just now", "5 min ago", "3 h ago", then as formatDate. @param {string} iso */
186
+ export function formatWhen(iso) {
187
+ const ms = Date.now() - new Date(iso).getTime();
188
+ if (ms >= 0 && ms < 60_000) return "just now";
189
+ if (ms >= 0 && ms < 3_600_000) return `${Math.floor(ms / 60_000)} min ago`;
190
+ if (ms >= 0 && ms < 86_400_000) return `${Math.floor(ms / 3_600_000)} h ago`;
191
+ return formatDate(iso);
192
+ }
193
+
181
194
  /** "How many tasks do I have?" (report §18.2). @param {Context} ctx */
182
195
  export async function count(ctx) {
183
196
  const counts = /** @type {any} */ (await ctx.api.get("/api/v1/tasks/count"));
@@ -202,16 +215,29 @@ export async function view(ctx) {
202
215
  assignee: task.assignee?.username ?? task.assignee?.name ?? null, sprint: task.sprint?.name ?? null, description: task.description ?? "",
203
216
  subtasks: task.subtasks.map((/** @type {any} */ s, /** @type {number} */ i) => ({ n: s.index ?? i + 1, id: s.id, title: s.title, done: Boolean(s.completed) })),
204
217
  files: task.files.map((/** @type {any} */ f) => ({ path: f.path ?? f.name, as: ROLE[f.role] ?? "draft", version: f.currentVersion ?? null })),
218
+ // The one-screen view (C11): labels, what it waits on and what waits on it, links, the latest 3 comments.
219
+ labels: task.meta?.labels ?? task.labels ?? [],
220
+ blockedBy: (task.meta?.blockedBy ?? []).map((/** @type {any} */ t) => ({ number: t.number, title: t.title, status: t.status })),
221
+ blocking: (task.meta?.blocking ?? []).map((/** @type {any} */ t) => ({ number: t.number, title: t.title, status: t.status })),
222
+ links: task.meta?.links ?? [],
223
+ watching: Boolean(task.meta?.watching),
224
+ starred: Boolean(task.meta?.starred),
225
+ comments: task.comments.slice(0, 3).map((/** @type {any} */ cm) => ({ by: cm.authorUsername ?? cm.authorName ?? null, text: cm.content, at: cm.createdAt })),
205
226
  };
206
227
  const { c, sym } = ctx.out;
207
228
  const slug = ctx.project?.slug ?? ctx.flags.workspace;
208
229
  const taskUrl = slug ? `${ctx.profile.origin}/workspaces/${encodeURIComponent(String(slug))}?tab=tasks&task=${data.number}` : null;
209
230
  ctx.out.result("nb.task.view/1", data, (d) => [
210
231
  `${c.brand(sym.brand)} ${taskUrl ? ctx.out.link(`#${d.number}`, taskUrl, ctx.profile.origin) : `#${d.number}`} ${c.bold(safe(d.title))}`,
211
- ` ${statusWord(d)}${d.priority ? ` · ${d.priority}` : ""}${d.assignee ? ` · @${safe(d.assignee)}` : ""}${d.sprint ? ` · ${safe(d.sprint)}` : ""}`,
232
+ ` ${statusWord(d)}${d.priority ? ` · ${d.priority}` : ""}${d.assignee ? ` · @${safe(d.assignee)}` : ""}${d.sprint ? ` · ${safe(d.sprint)}` : ""}${d.starred ? ` · ${c.warning("★")}` : ""}${d.watching ? c.muted(" · watching") : ""}`,
233
+ ...(d.labels.length ? [` ${d.labels.map((/** @type {string} */ l) => c.accent(`[${safe(l)}]`)).join(" ")}`] : []),
234
+ ...(d.blockedBy.length ? [` ${c.warning("Waiting on")} ${d.blockedBy.map((/** @type {any} */ t) => `#${t.number} ${safe(t.title)}${t.status === "done" ? c.muted(" (done)") : ""}`).join(", ")}`] : []),
235
+ ...(d.blocking.length ? [` ${c.muted("Blocks")} ${d.blocking.map((/** @type {any} */ t) => `#${t.number}`).join(", ")}`] : []),
212
236
  ...(d.description.trim() ? ["", ...safe(d.description.trim()).split("\n").map((l) => ` ${l}`)] : []),
213
237
  ...(d.subtasks.length ? ["", ` Subtasks (${d.subtasks.filter((/** @type {any} */ s) => s.done).length}/${d.subtasks.length})`, ...d.subtasks.map((/** @type {any} */ s) => ` ${s.done ? c.success("[x]") : "[ ]"} ${s.n}. ${safe(s.title)}`)] : []),
214
238
  ...(d.files.length ? ["", " Files", ...d.files.map((/** @type {any} */ f) => ` ${safe(f.path)} ${c.muted(`${f.as}${f.version ? ` · v${f.version}` : ""}`)}`)] : []),
239
+ ...(d.links.length ? ["", " Links", ...d.links.map((/** @type {any} */ l) => ` ${l.kind === "pull_request" ? "PR " : l.kind === "issue" ? "Issue " : ""}${l.title ? `${safe(l.title)} ${c.muted(safe(l.url))}` : safe(l.url)}`)] : []),
240
+ ...(d.comments.length ? ["", " Latest comments", ...d.comments.map((/** @type {any} */ cm) => ` ${cm.by ? `@${safe(cm.by)}` : "someone"}: ${commentText(cm.text).replace(/\n/g, " ").slice(0, 160)}`)] : []),
215
241
  ], { page: true });
216
242
  }
217
243
 
@@ -494,11 +520,67 @@ export const subtaskUncheck = (ctx) => setSubtasks(ctx, false);
494
520
 
495
521
  /** @param {Context} ctx */
496
522
  export async function commentAdd(ctx) {
523
+ // A comment on a doc is a comment on its file (C4): nb comment add --doc readme -m "…".
524
+ if (ctx.flags.doc) {
525
+ const { docs } = /** @type {any} */ (await ctx.api.get(`/api/v1/workspaces/${encodeURIComponent(ctx.requireWorkspace())}/docs`));
526
+ const doc = docs.find((/** @type {any} */ d) => d.slug === String(ctx.flags.doc).toLowerCase());
527
+ if (!doc?.nodePath) throw new CliError("DOC_NOT_FOUND", doc ? `${doc.slug} has no file yet` : `No doc called ${ctx.flags.doc}`, { hint: "nb doc list" });
528
+ ctx.flags.file = `${doc.nodePath.replace(/^\//, "")}:1`;
529
+ }
497
530
  if (ctx.flags.file) return (await import("./work.mjs")).commentOnFile(ctx);
498
- const text = String(ctx.flags.message ?? ctx.positionals.join(" ")).trim();
499
- if (!text) throw usage('nb comment add -m "<text>" [--task 4]');
531
+ const raw = String(ctx.flags.message ?? ctx.positionals.join(" ")).trim();
532
+ if (!raw) throw usage('nb comment add -m "<text>" [--task 4] [--reply <id>]');
533
+ const task = await resolveTask(ctx, taskRef(ctx, undefined));
534
+ const text = await withMentions(ctx, raw);
535
+ const replyTo = ctx.flags.reply ? commentIdOf(task, String(ctx.flags.reply)) : null;
536
+ await ctx.api.post("/api/v1/extension/comments", { kind: "task", projectId: ctx.requireWorkspace(), taskId: task.id, text, ...(replyTo ? { replyTo } : {}) });
537
+ ctx.out.result("nb.comment.add/1", { number: task.taskNumber, reply: Boolean(replyTo) }, (d) => `${ctx.out.c.success(ctx.out.sym.done)} ${d.reply ? "Replied" : "Commented"} on #${d.number}`);
538
+ }
539
+
540
+ /**
541
+ * `@sam` in a comment becomes a real mention (C4), so Sam is told, as in the app. A name that isn't a member of the
542
+ * workspace is an error that says so, never a mention that quietly goes nowhere.
543
+ * @param {Context} ctx @param {string} text
544
+ */
545
+ export async function withMentions(ctx, text) {
546
+ const names = [...new Set([...text.matchAll(/(?<![\w@{])@([a-z0-9_.-]{2,40})\b/gi)].map((m) => m[1].toLowerCase()))];
547
+ if (!names.length) return text;
548
+ const { members } = /** @type {any} */ (await ctx.api.get(`/api/v1/workspaces/${encodeURIComponent(ctx.requireWorkspace())}/members`));
549
+ let out = text;
550
+ for (const name of names) {
551
+ const m = members.find((/** @type {any} */ x) => String(x.username ?? "").toLowerCase() === name);
552
+ if (!m) throw new CliError("NOT_FOUND", `@${name} isn't in this workspace, so they wouldn't be told`, { hint: "nb member list" });
553
+ out = out.replace(new RegExp(`(?<![\\w@{])@${name.replace(/[.]/g, "\\.")}\\b`, "gi"), `@{${m.id}|${String(m.fullName ?? m.username).replace(/[|}]/g, "")}}`);
554
+ }
555
+ return out;
556
+ }
557
+
558
+ /** A comment by the id shown in nb comment list (its first characters are enough). @param {any} task @param {string} ref */
559
+ function commentIdOf(task, ref) {
560
+ const hits = task.comments.filter((/** @type {any} */ c) => String(c.id).startsWith(ref.toLowerCase()));
561
+ if (hits.length !== 1) throw new CliError("NOT_FOUND", hits.length ? `${ref} matches more than one comment` : `No comment ${ref} on #${task.taskNumber}`, { hint: `nb comment list --task ${task.taskNumber}` });
562
+ return hits[0].id;
563
+ }
564
+
565
+ /** `nb comment edit <id> -m "…"` and `nb comment delete <id>` (C4): your own task comments. @param {Context} ctx @param {"edit" | "delete"} what */
566
+ async function ownComment(ctx, what) {
567
+ const ref = ctx.positionals[0];
568
+ if (!ref) throw usage(what === "edit" ? 'nb comment edit <id> -m "new text" [--task 4]' : "nb comment delete <id> [--task 4]", "The ids are in nb comment list");
500
569
  const task = await resolveTask(ctx, taskRef(ctx, undefined));
501
- await ctx.api.post("/api/v1/extension/comments", { kind: "task", projectId: ctx.requireWorkspace(), taskId: task.id, text });
502
- ctx.out.result("nb.comment.add/1", { number: task.taskNumber }, (d) => `${ctx.out.c.success(ctx.out.sym.done)} Commented on #${d.number}`);
570
+ const commentId = commentIdOf(task, ref);
571
+ if (what === "edit") {
572
+ const raw = String(ctx.flags.message ?? ctx.positionals.slice(1).join(" ")).trim();
573
+ if (!raw) throw usage('nb comment edit <id> -m "new text"');
574
+ await ctx.api.patch("/api/v1/extension/comments", { projectId: ctx.requireWorkspace(), commentId, text: await withMentions(ctx, raw) });
575
+ } else {
576
+ const { confirm } = await import("../tui/ask.mjs");
577
+ if (!(await confirm(ctx, { key: "delete", question: `Delete your comment ${ref} on #${task.taskNumber}?`, yesLabel: "Delete", defaultYes: false }))) return 130;
578
+ await ctx.api.request("DELETE", "/api/v1/extension/comments", { body: { projectId: ctx.requireWorkspace(), commentId } });
579
+ }
580
+ ctx.out.result(`nb.comment.${what}/1`, { number: task.taskNumber, commentId }, (d) => `${ctx.out.c.success(ctx.out.sym.done)} ${what === "edit" ? "Edited" : "Deleted"} your comment on #${d.number}`);
503
581
  }
582
+ /** @param {Context} ctx */
583
+ export const commentEdit = (ctx) => ownComment(ctx, "edit");
584
+ /** @param {Context} ctx */
585
+ export const commentDelete = (ctx) => ownComment(ctx, "delete");
504
586
 
@@ -15,8 +15,14 @@ const WHAT = /** @type {Record<string, string>} */ ({
15
15
  export async function undo(ctx) {
16
16
  const log = readUndoLog(ctx.env, ctx.profile.origin);
17
17
  if (ctx.flags.list) {
18
- return ctx.out.result("nb.undo.list/1", { changes: log.slice().reverse().map((e) => ({ token: e.token, at: new Date(e.at).toISOString(), what: WHAT[e.path] ?? e.path })) }, (d) =>
19
- d.changes.length ? d.changes.map((c, i) => ` ${i === 0 ? ctx.out.c.brand(ctx.out.sym.brand) : " "} ${c.at.slice(11, 16)} ${c.what} ${ctx.out.c.muted(c.token.slice(0, 8))}`) : "Nothing to undo from the last 24 hours");
18
+ // What each would undo, in the server's words (C10), newest first; nb undo <n> picks one.
19
+ const recent = log.slice().reverse().slice(0, 20);
20
+ const summaries = await Promise.all(recent.map((e) => ctx.api.get(`/api/v1/undo/${encodeURIComponent(e.token)}`).then((/** @type {any} */ r) => String(r.summary), () => null)));
21
+ const changes = recent.map((e, i) => ({ n: i + 1, token: e.token, at: new Date(e.at).toISOString(), what: summaries[i] ?? WHAT[e.path] ?? e.path, available: summaries[i] !== null }));
22
+ return ctx.out.result("nb.undo.list/1", { changes }, (d) =>
23
+ d.changes.length
24
+ ? [...d.changes.map((c) => ` ${String(c.n).padStart(2)}. ${ctx.out.c.muted(c.at.slice(11, 16))} ${safe(c.what)}${c.available ? "" : ctx.out.c.muted(" (can't be undone any more)")}`), ctx.out.c.muted(" nb undo <n> undoes that one")]
25
+ : "Nothing to undo from the last 24 hours");
20
26
  }
21
27
  if (ctx.flags.session) {
22
28
  // Everything this agent session did, newest first (report A7.7): `nb mcp` tags its changes with a session id.
@@ -39,7 +45,9 @@ export async function undo(ctx) {
39
45
  return results.every((r) => r.ok) ? 0 : 4;
40
46
  }
41
47
  const given = ctx.positionals[0];
42
- const entry = given ? log.find((e) => e.token.startsWith(given)) ?? { token: given } : log.at(-1);
48
+ // A number is a line of nb undo --list (newest first); anything else is a token or its start.
49
+ const numbered = given && /^\d{1,2}$/.test(given) ? log.slice().reverse()[Number(given) - 1] : null;
50
+ const entry = numbered ?? (given ? log.find((e) => e.token.startsWith(given)) ?? { token: given } : log.at(-1));
43
51
  if (!entry) throw new CliError("NOT_FOUND", "Nothing to undo from the last 24 hours on this machine", { hint: "nb undo --list" });
44
52
  try {
45
53
  const res = /** @type {any} */ (await ctx.api.post(`/api/v1/undo/${encodeURIComponent(entry.token)}`, {}));
@@ -47,9 +47,12 @@ export async function watch(ctx) {
47
47
  let backoff = 1000;
48
48
  while (!stopping) {
49
49
  try {
50
- const res = /** @type {any} */ (await ctx.api.get("/api/v1/events", { query: { since, workspace: project.workspaceId, inbox: 0 }, timeoutMs: 40_000 }));
50
+ const res = /** @type {any} */ (await ctx.api.get("/api/v1/events", { query: { since, workspace: project.workspaceId, inbox: ctx.flags.inbox ? 1 : 0 }, timeoutMs: 40_000 }));
51
51
  since = res.cursor;
52
52
  backoff = 1000;
53
+ // --inbox (C13): your notifications as they happen, one line each; your settings and quiet hours already apply.
54
+ if (ctx.flags.inbox) for (const n of res.notifications ?? []) ctx.out.note(`${ctx.out.c.brand(ctx.out.sym.brand)} ${safe(n.title ?? "")}${n.body ? ctx.out.c.muted(` · ${safe(String(n.body)).replace(/\s+/g, " ").slice(0, 100)}`) : ""}`);
55
+ if (ctx.flags["no-pull"]) continue;
53
56
  const theirs = [...new Set(res.files.filter((/** @type {any} */ f) => !f.mine).map((/** @type {any} */ f) => toRelative(project.remoteRoot, f.path)).filter(Boolean))];
54
57
  if (!theirs.length || stopping) continue;
55
58
  while (busy) await new Promise((r) => setTimeout(r, 200));
@@ -68,7 +71,7 @@ export async function watch(ctx) {
68
71
  }
69
72
  }
70
73
  };
71
- if (!ctx.flags["no-pull"]) void livePull();
74
+ if (!ctx.flags["no-pull"] || ctx.flags.inbox) void livePull();
72
75
 
73
76
  /** One batch: files whose last change is older than the quiet window. */
74
77
  async function flush() {
@@ -8,7 +8,7 @@ import { CliError, EXIT, usage } from "../errors.mjs";
8
8
  import { commentText, safe } from "../print/style.mjs";
9
9
  import { confirm } from "../tui/ask.mjs";
10
10
  import { parseDate } from "../dates.mjs";
11
- import { bulkChange, resolveTask, taskRef } from "./tasks.mjs";
11
+ import { bulkChange, formatWhen, resolveTask, taskRef } from "./tasks.mjs";
12
12
 
13
13
  /** @typedef {import("../context.mjs").Context} Context */
14
14
 
@@ -32,7 +32,28 @@ export async function taskEdit(ctx) {
32
32
  if (due !== "none" && !date) throw usage(`--due ${due} isn't a date I know`, "Use today, tomorrow, friday, next week, in 3 days, 2026-12-01, or none");
33
33
  changes.push(["dueDate", date]);
34
34
  }
35
- if (!changes.length) throw usage("nb task edit <task…> [--title text] [-m description] [--priority high] [--due friday|none]");
35
+ // Labels, "blocked by" and links (C2, C12, 0087) go to the task's meta route.
36
+ const list = (/** @type {unknown} */ v) => (v === undefined ? [] : /** @type {string[]} */ ([v].flat()).flatMap((x) => String(x).split(",")).map((x) => x.trim()).filter(Boolean));
37
+ const labelAdd = list(ctx.flags.label).map((l) => l.toLowerCase()), labelRemove = list(ctx.flags.unlabel).map((l) => l.toLowerCase()), blockAdd = list(ctx.flags["blocked-by"]), blockRemove = list(ctx.flags["not-blocked-by"]), linkAdd = list(ctx.flags.link);
38
+ const metaWanted = labelAdd.length || labelRemove.length || blockAdd.length || blockRemove.length || linkAdd.length;
39
+ if (!changes.length && !metaWanted) throw usage("nb task edit <task…> [--title text] [-m description] [--priority high] [--due friday|none] [--label bug] [--blocked-by 7] [--link url]");
40
+ if (metaWanted) {
41
+ if (ctx.positionals.length > 1) throw usage("Labels, blocked-by and links change one task at a time");
42
+ const task = await resolveTask(ctx, taskRef(ctx, ctx.positionals[0]), { brief: true });
43
+ const ids = async (/** @type {string[]} */ refs) => Promise.all(refs.map(async (r) => (await resolveTask(ctx, r, { brief: true })).id));
44
+ const meta = /** @type {any} */ (await ctx.api.patch(`/api/v1/tasks/${task.id}/meta`, {
45
+ ...(labelAdd.length || labelRemove.length ? { labels: { ...(labelAdd.length ? { add: labelAdd } : {}), ...(labelRemove.length ? { remove: labelRemove } : {}) } } : {}),
46
+ ...(blockAdd.length || blockRemove.length ? { blockedBy: { ...(blockAdd.length ? { add: await ids(blockAdd) } : {}), ...(blockRemove.length ? { remove: await ids(blockRemove) } : {}) } } : {}),
47
+ ...(linkAdd.length ? { links: { add: linkAdd.map((url) => ({ url })) } } : {}),
48
+ }));
49
+ for (const [field, value] of changes) await update(ctx, { kind: "edit", taskId: task.id, field, value });
50
+ return ctx.out.result("nb.task.edit/1", { number: task.taskNumber, changed: changes.map(([f]) => f), labels: meta.labels, blockedBy: meta.blockedBy.map((/** @type {any} */ t) => t.number), links: meta.links }, (d) => [
51
+ `${ctx.out.c.success(ctx.out.sym.done)} Changed #${d.number}${d.changed.length ? `: ${d.changed.join(", ")}` : ""}`,
52
+ ...(d.labels.length ? [` labels ${d.labels.map((/** @type {string} */ l) => `[${safe(l)}]`).join(" ")}`] : []),
53
+ ...(d.blockedBy.length ? [` waiting on ${d.blockedBy.map((/** @type {number} */ n) => `#${n}`).join(", ")}`] : []),
54
+ ...(d.links.length ? [` links ${d.links.map((/** @type {any} */ l) => safe(l.title ?? l.url)).join(", ")}`] : []),
55
+ ]);
56
+ }
36
57
  if (ctx.positionals.length > 1) {
37
58
  if (changes.some(([f]) => f === "title" || f === "description")) throw usage("Several tasks take --priority and --due; change a title one task at a time");
38
59
  let numbers = [];
@@ -70,6 +91,47 @@ async function pickPerson(ctx) {
70
91
  ] });
71
92
  }
72
93
 
94
+ /** Watching and starring are your own (C2, 0087): `nb task watch 4`, `nb task star 4`, and `--off`. @param {Context} ctx @param {"watch" | "star"} what */
95
+ async function personal(ctx, what) {
96
+ const task = await resolveTask(ctx, taskRef(ctx, ctx.positionals[0]), { brief: true });
97
+ const on = !ctx.flags.off;
98
+ await ctx.api.patch(`/api/v1/tasks/${task.id}/meta`, { [what]: on });
99
+ ctx.out.result(`nb.task.${what}/1`, { number: task.taskNumber, [what === "watch" ? "watching" : "starred"]: on }, () =>
100
+ `${ctx.out.c.success(ctx.out.sym.done)} ${what === "watch" ? (on ? `Watching #${task.taskNumber}: you'll hear when it changes` : `Stopped watching #${task.taskNumber}`) : on ? `Starred #${task.taskNumber} · nb task list --starred` : `Unstarred #${task.taskNumber}`}`);
101
+ }
102
+ /**
103
+ * `nb task remind 4 "tomorrow 9am" [-m note]` (C2, 0088): your own reminder, delivered to your inbox (and push or
104
+ * email as your settings say). `--list` shows yours on the task; `--off` cancels them.
105
+ * @param {Context} ctx
106
+ */
107
+ export async function taskRemind(ctx) {
108
+ const [ref, ...words] = ctx.positionals;
109
+ if (!ref) throw usage('nb task remind <task> "tomorrow 9am" [-m note]', "Or --list to see yours, --off to cancel them");
110
+ const task = await resolveTask(ctx, ref, { brief: true });
111
+ const path = `/api/v1/tasks/${task.id}/reminders`;
112
+ if (ctx.flags.off) {
113
+ const { cancelled } = /** @type {any} */ (await ctx.api.request("DELETE", path));
114
+ return ctx.out.result("nb.task.remind/1", { number: task.taskNumber, cancelled }, (d) => `${ctx.out.c.success(ctx.out.sym.done)} Cancelled ${d.cancelled} reminder${d.cancelled === 1 ? "" : "s"} on #${d.number}`);
115
+ }
116
+ if (ctx.flags.list || !words.length) {
117
+ const { reminders } = /** @type {any} */ (await ctx.api.get(path));
118
+ return ctx.out.result("nb.task.reminders/1", { number: task.taskNumber, reminders }, (d) => (d.reminders.length
119
+ ? d.reminders.map((/** @type {any} */ r) => ` ${new Date(r.remindAt).toLocaleString(undefined, { weekday: "short", day: "numeric", month: "short", hour: "numeric", minute: "2-digit" })}${r.note ? ` ${ctx.out.c.muted(safe(r.note))}` : ""}`)
120
+ : `No reminders on #${d.number} · nb task remind ${d.number} "tomorrow 9am"`));
121
+ }
122
+ const { parseWhen } = await import("../dates.mjs");
123
+ const at = parseWhen(words.join(" "));
124
+ if (!at) throw usage(`"${words.join(" ")}" isn't a time I know`, 'Try: "tomorrow 9am", "friday 14:30", "in 2 hours", "today 5pm"');
125
+ const { reminder } = /** @type {any} */ (await ctx.api.post(path, { at: at.toISOString(), ...(ctx.flags.message ? { note: String(ctx.flags.message) } : {}) }));
126
+ ctx.out.result("nb.task.remind/1", { number: task.taskNumber, at: reminder.remindAt, note: reminder.note }, (d) =>
127
+ `${ctx.out.c.success(ctx.out.sym.done)} I'll remind you about #${d.number} ${new Date(d.at).toLocaleString(undefined, { weekday: "short", day: "numeric", month: "short", hour: "numeric", minute: "2-digit" })}`);
128
+ }
129
+
130
+ /** @param {Context} ctx */
131
+ export const taskWatch = (ctx) => personal(ctx, "watch");
132
+ /** @param {Context} ctx */
133
+ export const taskStar = (ctx) => personal(ctx, "star");
134
+
73
135
  /** @param {Context} ctx */
74
136
  export async function taskAssign(ctx) {
75
137
  // nb task assign 4 @sam, or several: nb task assign 3 4 --to sam (C2). Left out: choose from the members.
@@ -196,7 +258,7 @@ export async function commentList(ctx) {
196
258
  const task = await resolveTask(ctx, taskRef(ctx, undefined));
197
259
  const comments = task.comments.map((/** @type {any} */ c) => ({ id: c.id, by: c.authorUsername ?? c.authorName ?? null, text: c.content, at: c.createdAt }));
198
260
  ctx.out.result("nb.comment.list/1", { number: task.taskNumber, comments, untrusted: true }, (d) =>
199
- d.comments.length ? d.comments.map((/** @type {any} */ c) => ` ${ctx.out.c.muted(String(c.at).slice(0, 16).replace("T", " "))} ${c.by ? `@${safe(c.by)}` : "someone"}: ${commentText(c.text).replace(/\n/g, " ")}`) : `#${d.number} has no comments`);
261
+ d.comments.length ? d.comments.map((/** @type {any} */ c) => ` ${ctx.out.c.muted(formatWhen(String(c.at)))} ${c.by ? `@${safe(c.by)}` : "someone"}: ${commentText(c.text).replace(/\n/g, " ")}${c.id ? ctx.out.c.muted(` ${String(c.id).slice(0, 8)}`) : ""}`) : `#${d.number} has no comments`);
200
262
  }
201
263
 
202
264
  /** A comment on lines of a file (report D10): `nb comment add -m "…" --file src/app.ts:12-18`. @param {Context} ctx */
package/lib/config.mjs CHANGED
@@ -190,6 +190,8 @@ export function readProjectConfig(root, warn) {
190
190
  startedTask: raw.startedTask ?? null,
191
191
  profile: raw.profile ?? null,
192
192
  linkedAt: raw.linkedAt,
193
+ /** Folders this copy keeps in sync (C3 `nb sync --only`); none = everything. */
194
+ only: Array.isArray(raw.only) ? raw.only.filter((/** @type {unknown} */ x) => typeof x === "string") : [],
193
195
  };
194
196
  }
195
197
 
package/lib/context.mjs CHANGED
@@ -18,7 +18,8 @@ export const VERSION = JSON.parse(fs.readFileSync(PACKAGE_JSON, "utf8")).version
18
18
  * @param {{ flags: Record<string, any>, positionals: string[], cwd?: string, env?: NodeJS.ProcessEnv, fetchImpl?: typeof fetch, io?: Parameters<typeof createOutput>[1] }} input
19
19
  */
20
20
  export function createContext({ flags, positionals, cwd = process.cwd(), env = process.env, fetchImpl, io }) {
21
- const out = createOutput({ json: Boolean(flags.json || env.NB_JSON === "1"), quiet: Boolean(flags.quiet), plain: Boolean(flags.plain), verbose: Boolean(flags.verbose), fields: flags.fields ? String(flags.fields).split(",").map((f) => f.trim()).filter(Boolean) : null, pager: !flags["no-pager"] }, io);
21
+ if (flags.format !== undefined && !["table", "json", "csv", "md"].includes(String(flags.format))) throw new CliError("USAGE", `--format ${flags.format}: use table, json, csv or md`);
22
+ const out = createOutput({ json: Boolean(flags.json || env.NB_JSON === "1"), quiet: Boolean(flags.quiet), plain: Boolean(flags.plain), verbose: Boolean(flags.verbose), fields: flags.fields ? String(flags.fields).split(",").map((f) => f.trim()).filter(Boolean) : null, pager: !flags["no-pager"], format: flags.format ? /** @type {any} */ (String(flags.format)) : null }, io);
22
23
  const root = findRoot(cwd);
23
24
  const project = root ? readProjectConfig(root, (m) => out.warn(m)) : null;
24
25
  const profile = currentProfile({ flags, env, project });
@@ -30,6 +31,8 @@ export function createContext({ flags, positionals, cwd = process.cwd(), env = p
30
31
  confirmToken: typeof flags.confirm === "string" ? flags.confirm : null,
31
32
  onUndo: (u) => appendUndo(env, { token: u.token, at: Date.now(), method: u.method, path: u.path, origin: profile.origin, session: env.NB_AGENT_SESSION ?? null }),
32
33
  onRetry: ({ waitMs, reason }) => out.note(out.c.muted(`${reason}; retrying in ${Math.max(1, Math.round(waitMs / 1000))} s`)),
34
+ // Commands with their own --dry-run (push, pull) plan without writing; every other one stops at its first write.
35
+ dryRun: Boolean(flags["dry-run"]) && !flags.ownDryRun,
33
36
  });
34
37
 
35
38
  // The first step comes first (C1): signed out, "link this folder" is the wrong advice.
package/lib/dates.mjs CHANGED
@@ -45,3 +45,27 @@ export function dueRange(word, now = new Date()) {
45
45
  const [y, m, d] = date.split("-").map(Number);
46
46
  return { after: new Date(y, m - 1, d).toISOString(), before: new Date(y, m - 1, d + 1).toISOString() };
47
47
  }
48
+
49
+ /**
50
+ * A moment for reminders (C2): "tomorrow 9am", "friday 14:30", "in 2 hours", "in 30 minutes", "today 5pm", or a
51
+ * date alone (9:00 that day). Read in the person's time zone; null when it isn't one.
52
+ * @param {string} text @param {Date} [now] @returns {Date | null}
53
+ */
54
+ export function parseWhen(text, now = new Date()) {
55
+ const t = String(text ?? "").trim().toLowerCase().replace(/\s+/g, " ");
56
+ const rel = /^in (\d{1,4}) ?(m|min|mins|minute|minutes|h|hr|hrs|hour|hours)$/.exec(t);
57
+ if (rel) return new Date(now.getTime() + Number(rel[1]) * (rel[2].startsWith("h") ? 3_600_000 : 60_000));
58
+ if (!Number.isNaN(Date.parse(t)) && /\d{4}-\d{2}-\d{2}t/.test(t)) return new Date(t.toUpperCase());
59
+ const time = /(?:^|\s)(?:at\s)?(\d{1,2})(?::(\d{2}))?\s?(am|pm)?$/.exec(t);
60
+ const dayPart = time ? t.slice(0, time.index).trim() : t;
61
+ if (time && !time[3] && !time[2] && !dayPart) return null; // a bare number isn't a time
62
+ const day = parseDate(dayPart || "today", now);
63
+ if (!day) return null;
64
+ let hour = time ? Number(time[1]) : 9;
65
+ const minute = time?.[2] ? Number(time[2]) : 0;
66
+ if (time?.[3] === "pm" && hour < 12) hour += 12;
67
+ if (time?.[3] === "am" && hour === 12) hour = 0;
68
+ if (hour > 23 || minute > 59) return null;
69
+ const [y, m, d] = day.split("-").map(Number);
70
+ return new Date(y, m - 1, d, hour, minute);
71
+ }
@@ -38,6 +38,7 @@ export const FIXES = /** @type {Record<string, string>} */ ({
38
38
  "NOT_A_TASK": "nb inbox open <n>",
39
39
  "NOTHING_TO_APPROVE": "nb inbox open <n>",
40
40
  "NEEDS_INPUT": "Answer with --answer key=value, or --yes for the recommended choice",
41
+ "DRY_RUN": "Run the same command without --dry-run to make the change",
41
42
  "CANCELLED": "Run the command again when ready",
42
43
  "OFFLINE": "nb doctor checks the connection; nb sync sends the queue",
43
44
  "TIMEOUT": "Try again; nb doctor checks the connection",
@@ -53,6 +54,7 @@ export const FIXES = /** @type {Record<string, string>} */ ({
53
54
  "CORRUPT_DOWNLOAD": "Run nb pull again",
54
55
  "UPLOAD_FAILED": "Run nb push again; it picks up where it stopped",
55
56
  "CONFIRMATION_INVALID": "Run the command without --confirm to get a new one",
57
+ "UPGRADE_FAILED": "Run npm i -g @networkbase/cli@latest yourself to see why",
56
58
  "GIT_FAILED": "Run the git command yourself to see why",
57
59
  "EDITOR_FAILED": "Set your editor: export EDITOR=nano",
58
60
  "UNKNOWN_TOOL": "Restart the agent so it reads the current tool list",
package/lib/errors.mjs CHANGED
@@ -41,6 +41,7 @@ const EXIT_BY_CODE = {
41
41
  NEEDS_CONFIRMATION: EXIT.needsConfirmation,
42
42
  OFFLINE: EXIT.offline,
43
43
  CANCELLED: EXIT.cancelled,
44
+ DRY_RUN: EXIT.ok,
44
45
  };
45
46
 
46
47
  export class CliError extends Error {
@@ -0,0 +1,47 @@
1
+ // `nb help <topic>` (report C5): how a part of nb fits together, with examples that the tests run through the
2
+ // command table, so an example can never name a command or flag that doesn't exist.
3
+
4
+ export const TOPICS = /** @type {Record<string, { title: string, lines: string[], examples: string[] }>} */ ({
5
+ files: {
6
+ title: "Files: one folder, kept in step with the workspace",
7
+ lines: [
8
+ "nb init links this folder to a workspace. nb pull brings files down; nb push sends your changes up.",
9
+ "Every push of the same path is a new version; nothing is overwritten. nb file history shows them, nb file use goes back.",
10
+ "If a file changed on both sides, you get a conflict copy (name.remote-vN.ext) and nb resolve settles it.",
11
+ ],
12
+ examples: ["nb pull", "nb push report.md -m \"First draft\"", "nb file history report.md", "nb file use report.md v1", "nb sync --only design"],
13
+ },
14
+ agents: {
15
+ title: "Agents: Claude Code, Codex, Cursor and others working with you",
16
+ lines: [
17
+ "nb agent setup connects an agent; you approve it once in the browser and choose what it may do alone.",
18
+ "Big changes (finishing tasks, final files, deleting) wait for your yes. Everything it changes can be undone.",
19
+ ],
20
+ examples: ["nb agent setup claude", "nb agent access claude --small", "nb agent status", "nb undo --session"],
21
+ },
22
+ classes: {
23
+ title: "Classes: assignments, hand-ins and reviews",
24
+ lines: [
25
+ "Students: nb assignment list shows what's due; nb assignment hand-in sends your work with the class's late rules.",
26
+ "Teachers: nb review list shows what's waiting; approve or return several at once.",
27
+ ],
28
+ examples: ["nb assignment list", "nb assignment hand-in 3 essay.pdf -m \"Final\"", "nb review list -w cse-3b", "nb review approve 3 5 8"],
29
+ },
30
+ "sign-in": {
31
+ title: "Signing in",
32
+ lines: [
33
+ "nb login opens your browser; over SSH it shows a code and a QR code instead.",
34
+ "Your sign-in lasts a year; nb warns a week before it ends, and nb login renews the same one.",
35
+ "In CI, use a personal token: echo $TOKEN | nb login --with-token, or set NETWORKBASE_TOKEN.",
36
+ ],
37
+ examples: ["nb login", "nb login --device", "nb whoami", "nb token list"],
38
+ },
39
+ offline: {
40
+ title: "Working offline",
41
+ lines: [
42
+ "Without a connection, pushes wait in a queue and nb status reads from what was last pulled.",
43
+ "nb queue shows what's waiting; nb queue retry sends it when you're back.",
44
+ ],
45
+ examples: ["nb queue", "nb queue retry", "nb queue drop 1", "nb diff"],
46
+ },
47
+ });
@@ -0,0 +1,27 @@
1
+ // A company proxy and its own certificates (report C6). Node's fetch only uses HTTPS_PROXY with NODE_USE_ENV_PROXY=1
2
+ // (Node 22.21+ and 24+), and NODE_EXTRA_CA_CERTS is read at start-up, so when either is needed nb starts itself again
3
+ // once with them set. Nothing changes for anyone who doesn't use a proxy or extra certificates.
4
+
5
+ /** Node versions whose fetch can use HTTPS_PROXY. @param {string} version like "22.22.0" */
6
+ export function proxyCapable(version) {
7
+ const [major = 0, minor = 0] = version.split(".").map(Number);
8
+ return major >= 23 || (major === 22 && minor >= 21);
9
+ }
10
+
11
+ /**
12
+ * What to add to the environment for this run, or null when nothing is needed.
13
+ * @param {Record<string, any>} config the user config (`proxy`, `ca-file`) @param {NodeJS.ProcessEnv} env @param {string} nodeVersion
14
+ * @returns {Record<string, string> | null}
15
+ */
16
+ export function networkEnv(config, env, nodeVersion) {
17
+ if (env.NB_NETWORK_APPLIED) return null;
18
+ /** @type {Record<string, string>} */
19
+ const add = {};
20
+ if (config["ca-file"] && env.NODE_EXTRA_CA_CERTS !== config["ca-file"]) add.NODE_EXTRA_CA_CERTS = String(config["ca-file"]);
21
+ const proxy = config.proxy ?? env.HTTPS_PROXY ?? env.https_proxy ?? null;
22
+ if (proxy && proxyCapable(nodeVersion)) {
23
+ if (config.proxy && env.HTTPS_PROXY !== config.proxy) { add.HTTPS_PROXY = String(config.proxy); add.HTTP_PROXY = String(config.proxy); }
24
+ if (env.NODE_USE_ENV_PROXY !== "1") add.NODE_USE_ENV_PROXY = "1";
25
+ }
26
+ return Object.keys(add).length ? { ...add, NB_NETWORK_APPLIED: "1" } : null;
27
+ }
@@ -38,6 +38,9 @@ export async function afterCommand(ctx) {
38
38
  const minor = (/** @type {string} */ v) => v.split(".").slice(0, 2).join(".");
39
39
  if (seen.lastRun && minor(seen.lastRun) !== minor(ctx.version)) {
40
40
  ctx.out.note(`${c.brand(ctx.out.sym.brand)} Updated to nb ${ctx.version}`);
41
+ // What's new in this minor version (F7), in three lines.
42
+ const { WHATS_NEW } = await import("../whats-new.mjs");
43
+ for (const line of WHATS_NEW[minor(ctx.version)] ?? []) ctx.out.note(c.muted(` · ${line}`));
41
44
  ctx.out.note(c.muted(" What changed: https://www.npmjs.com/package/@networkbase/cli?activeTab=readme · nb help"));
42
45
  }
43
46
  if (Date.now() - (seen.checkedAt ?? 0) > DAY) {
package/lib/print/out.mjs CHANGED
@@ -6,7 +6,7 @@ import { spawnSync } from "node:child_process";
6
6
  import { colorLevel, palette, pad, safe, symbols, truncateEnd, truncateMiddle, asciiOnly, width, hyperlinks } from "./style.mjs";
7
7
 
8
8
  /**
9
- * @typedef {{ json: boolean, quiet: boolean, plain: boolean, verbose: boolean, fields: string[] | null, pager: boolean }} OutputMode
9
+ * @typedef {{ json: boolean, quiet: boolean, plain: boolean, verbose: boolean, fields: string[] | null, pager: boolean, format?: "table" | "json" | "csv" | "md" | null }} OutputMode
10
10
  * @typedef {ReturnType<typeof createOutput>} Output
11
11
  */
12
12
 
@@ -23,7 +23,11 @@ export function createOutput(mode, io = {}) {
23
23
  const level = plain ? 0 : colorLevel(stderr, env);
24
24
  const c = palette(level);
25
25
  const sym = symbols(plain || asciiOnly(env));
26
- const json = Boolean(mode.json);
26
+ // --format (C11): json is --json; csv and md print lists as a spreadsheet or a Markdown table, and nothing else.
27
+ const json = Boolean(mode.json) || mode.format === "json";
28
+ const format = mode.format === "csv" || mode.format === "md" ? mode.format : null;
29
+ /** Lines a table made in csv/md form, so result() prints only those. @type {Set<string>} */
30
+ const tableLines = new Set();
27
31
  const quiet = Boolean(mode.quiet);
28
32
  const columns = () => Math.max(40, stderr.columns || stdout.columns || 80);
29
33
  /** @type {string[]} */
@@ -79,8 +83,9 @@ export function createOutput(mode, io = {}) {
79
83
  stdout.write(`${JSON.stringify(envelope)}\n`);
80
84
  return;
81
85
  }
82
- const lines = human(data);
86
+ let lines = human(data);
83
87
  if (lines === null || lines === undefined) return;
88
+ if (format) lines = (Array.isArray(lines) ? lines : [lines]).filter((l) => tableLines.has(l));
84
89
  const text = Array.isArray(lines) ? lines.join("\n") : lines;
85
90
  if (text === "") return;
86
91
  const out = text.endsWith("\n") ? text : `${text}\n`;
@@ -114,6 +119,19 @@ export function createOutput(mode, io = {}) {
114
119
  * @param {any[]} rows
115
120
  */
116
121
  table(allCols, rows) {
122
+ if (format) {
123
+ // Plain text without colour or truncation: a cell is what the column's value says.
124
+ const plainCell = (/** @type {string} */ s) => stripForJson(String(s ?? ""));
125
+ const csv = (/** @type {string} */ s) => (/[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s);
126
+ const md = (/** @type {string} */ s) => s.replace(/\|/g, "\\|").replace(/\n/g, " ");
127
+ const head = allCols.map((col) => col.title || " ");
128
+ const body = rows.map((row) => allCols.map((col) => plainCell(col.value(row))));
129
+ const out = format === "csv"
130
+ ? [head, ...body].map((r) => r.map(csv).join(","))
131
+ : [`| ${head.map(md).join(" | ")} |`, `|${head.map(() => " --- ").join("|")}|`, ...body.map((r) => `| ${r.map(md).join(" | ")} |`)];
132
+ for (const l of out) tableLines.add(l);
133
+ return out;
134
+ }
117
135
  const natural = (/** @type {typeof allCols[number]} */ col) => Math.max(width(col.title), ...rows.map((r) => width(col.value(r))));
118
136
  const fixedWidth = (/** @type {typeof allCols} */ cs) => cs.reduce((a, col) => a + (col.flex ? 10 : natural(col)), 0) + 2 * cs.length;
119
137
  let cols = allCols;
@@ -94,7 +94,7 @@ const BATCH_FILES = 50;
94
94
  /**
95
95
  * Uploads through files/place in batches (≤ 50 files, ≤ 3 MiB inline); bigger files use signed upload slots.
96
96
  * @param {Api} api
97
- * @param {{ workspaceId: string, items: Array<{ path: string, abs: string, size: number, hash: string, baseVersion?: number | null }>, taskId?: string | null, as?: string | null, message?: string | null, keepBoth?: boolean, folder?: string | null, confirmSecrets?: boolean, keyBase?: string }} input
97
+ * @param {{ workspaceId: string, items: Array<{ path: string, abs: string, size: number, hash: string, baseVersion?: number | null }>, taskId?: string | null, as?: string | null, message?: string | null, keepBoth?: boolean, folder?: string | null, confirmSecrets?: boolean, keyBase?: string, onBytes?: (path: string, sent: number, total: number) => void }} input
98
98
  * @param {(done: number, total: number) => void} [progress]
99
99
  */
100
100
  export async function uploadFiles(api, input, progress) {
@@ -135,7 +135,7 @@ export async function uploadFiles(api, input, progress) {
135
135
  progress?.(done, input.items.length);
136
136
  }
137
137
  if (large.length) {
138
- results.push(...(await uploadLarge(api, input.workspaceId, large, input.message ?? null)));
138
+ results.push(...(await uploadLarge(api, input.workspaceId, large, input.message ?? null, input.onBytes)));
139
139
  progress?.(input.items.length, input.items.length);
140
140
  }
141
141
  return { files: results, transition: lastTransition };
@@ -145,8 +145,9 @@ export async function uploadFiles(api, input, progress) {
145
145
  * Files over 3 MiB: signed upload slots, PUT, then finalize (the 1.x bulk path). The base-version check happened
146
146
  * just before through a fresh manifest; the bulk routes don't take one (noted in the phase notes).
147
147
  * @param {Api} api @param {string} workspaceId @param {Array<{ path: string, abs: string, size: number, hash: string }>} items @param {string | null} message
148
+ * @param {(path: string, sent: number, total: number) => void} [onBytes] progress of each big file (C3)
148
149
  */
149
- async function uploadLarge(api, workspaceId, items, message) {
150
+ async function uploadLarge(api, workspaceId, items, message, onBytes) {
150
151
  /** @type {any[]} */
151
152
  const out = [];
152
153
  for (let i = 0; i < items.length; i += BATCH_FILES) {
@@ -158,7 +159,12 @@ async function uploadLarge(api, workspaceId, items, message) {
158
159
  for (const slot of intent.files) {
159
160
  const item = batch.find((f) => f.path === slot.path);
160
161
  if (!item) continue;
161
- const put = await fetch(slot.uploadUrl, /** @type {RequestInit} */ ({ method: "PUT", headers: { "content-type": mimeFor(item.path), "content-length": String(item.size) }, body: /** @type {any} */ (fs.createReadStream(item.abs)), duplex: "half", signal: AbortSignal.timeout(10 * 60_000) }));
162
+ // ponytail: a file stopped midway (Ctrl+C) goes up whole on the next push, not from where it stopped; files are
163
+ // at most 25 MB. Byte-level resume needs a resumable upload protocol on storage.
164
+ const stream = fs.createReadStream(item.abs);
165
+ let sent = 0;
166
+ stream.on("data", (chunk) => { sent += chunk.length; onBytes?.(item.path, sent, item.size); });
167
+ const put = await fetch(slot.uploadUrl, /** @type {RequestInit} */ ({ method: "PUT", headers: { "content-type": mimeFor(item.path), "content-length": String(item.size) }, body: /** @type {any} */ (stream), duplex: "half", signal: AbortSignal.timeout(10 * 60_000) }));
162
168
  if (!put.ok) throw new CliError("UPLOAD_FAILED", `Uploading ${item.path} failed (HTTP ${put.status})`, { hint: "Run the command again" });
163
169
  }
164
170
  const finalized = /** @type {any} */ (await api.post("/api/v1/extension/bulk-finalize", {
@@ -0,0 +1,8 @@
1
+ // What a new minor version brings (F7 "what's new"), shown once after updating. Newest first.
2
+ export const WHATS_NEW = /** @type {Record<string, string[]>} */ ({
3
+ "2.1": [
4
+ "nb on its own shows where you are; nb next says what to work on",
5
+ "Labels, blocked by, reminders, starred tasks and files; trash, copy and lock files",
6
+ "--dry-run on every command; nb help files|agents|classes|sign-in|offline",
7
+ ],
8
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@networkbase/cli",
3
- "version": "2.1.1",
3
+ "version": "2.1.2",
4
4
  "description": "NetworkBase in your terminal: sync files, work on tasks, edit docs",
5
5
  "type": "module",
6
6
  "homepage": "https://networkbase.in",