@networkbase/cli 2.1.6 → 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.
@@ -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
- /** @param {string} p */
90
- const remote = (p) => `/${p.replace(/^\/+/, "")}`;
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");
@@ -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
- await Promise.all(Array.from({ length: Math.min(process.platform === "win32" ? 4 : 8, todo.length) }, worker));
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);
@@ -7,6 +7,9 @@ import { formatWhen } from "./tasks.mjs";
7
7
 
8
8
  /** @typedef {import("../context.mjs").Context} Context */
9
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
+
10
13
  /** @param {Context} ctx @returns {Promise<any[]>} */
11
14
  async function conversations(ctx) {
12
15
  return /** @type {any} */ (await ctx.api.get("/api/v1/chat/conversations")).conversations ?? [];
@@ -17,7 +20,8 @@ async function conversations(ctx) {
17
20
  * which (--workspace picks; scripts get the choices). @param {Context} ctx @param {string | undefined} ref
18
21
  */
19
22
  async function pick(ctx, ref) {
20
- if (!ref) throw usage("Which conversation?", "nb message read #design, @sam, or a number from nb message list");
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");
21
25
  const all = await conversations(ctx);
22
26
  if (/^\d+$/.test(ref)) {
23
27
  const hit = all[Number(ref) - 1];
@@ -33,8 +37,12 @@ async function pick(ctx, ref) {
33
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));
34
38
  throw new CliError("NOT_FOUND", `No conversation ${ref}`, { hint: near.length ? `Did you mean ${near.join(", ")}?` : "nb message list" });
35
39
  }
36
- const id = await ask(ctx, { key: "conversation", header: "Which", question: `${ref} is in ${hits.length} workspaces. Which one?`, options: hits.slice(0, 4).map((c) => ({ value: c.id, label: `${safe(c.label)} in ${safe(c.workspace ?? "no workspace")}` })) });
37
- return hits.find((c) => c.id === id) ?? hits[0];
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;
38
46
  }
39
47
 
40
48
  /** nb message list. @param {Context} ctx */
@@ -42,7 +50,7 @@ export async function list(ctx) {
42
50
  const all = (await conversations(ctx)).filter((c) => !ctx.flags.unread || c.unread > 0);
43
51
  const { c } = ctx.out;
44
52
  ctx.out.result("nb.message.list/1", { conversations: all }, (d) => d.conversations.length ? [
45
- ...d.conversations.map((/** @type {any} */ m, /** @type {number} */ n) => `${String(n + 1).padStart(3)} ${m.unread ? c.brand(ctx.out.sym.brand) : " "} ${safe(m.label).padEnd(22)} ${c.muted(safe(m.workspace ?? "").padEnd(16))} ${m.unread ? c.bold(`${m.unread} new`.padEnd(7)) : "".padEnd(7)} ${c.muted(m.lastAt ? formatWhen(m.lastAt) : "")} ${safe(m.lastPreview ?? "").replace(/\n/g, " ").slice(0, 60)}`),
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)}`),
46
54
  c.muted(" nb message read <#channel|@person|n> · nb message send <#channel|@person> \"text\""),
47
55
  ] : ctx.flags.unread ? "Nothing unread" : "No conversations yet. Start one in the app: Messages", { page: true });
48
56
  }
@@ -279,9 +279,9 @@ export const COMMANDS = [
279
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
280
  flags: { unread: { type: "boolean", describe: "Only conversations with new messages" } } },
281
281
  { group: "Docs and workspaces", name: "message read", summary: "Read a conversation (marks it read)", usage: "nb message read <#channel|@person|n> [--before <seq>]", module: "messages", fn: "read",
282
- flags: { before: { type: "string", describe: "Older messages, before this one", valueName: "seq" }, "keep-unread": { type: "boolean", describe: "Don't mark it read" } }, examples: ["nb message read #design", "nb message read @sam"] },
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
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!\""] },
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!\""] },
285
285
  { group: "Docs and workspaces", name: "member list", summary: "People in the workspace", usage: "nb member list [name]", module: "docs", fn: "memberList" },
286
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",
287
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'] },
@@ -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",
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
- const plainCell = (/** @type {string} */ s) => stripForJson(String(s ?? ""));
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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@networkbase/cli",
3
- "version": "2.1.6",
3
+ "version": "2.1.7",
4
4
  "description": "NetworkBase in your terminal: sync files, work on tasks, edit docs",
5
5
  "type": "module",
6
6
  "homepage": "https://networkbase.in",