@networkbase/cli 2.0.3 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/mcp/tools.mjs CHANGED
@@ -2,8 +2,10 @@
2
2
  // in-process, so agents get the same checks, conflicts and errors as people. Questions come back as needs_input;
3
3
  // anything that needs a person's yes comes back as needs_confirmation with a one-time token.
4
4
  import crypto from "node:crypto";
5
+ import path from "node:path";
5
6
 
6
7
  import { COMMANDS } from "../commands/table.mjs";
8
+ import { currentProfile, globalDir, readJson, writeAtomic } from "../config.mjs";
7
9
  import { createContext } from "../context.mjs";
8
10
  import { CliError } from "../errors.mjs";
9
11
 
@@ -67,7 +69,7 @@ export const TOOLS = [
67
69
  return pick(rank(r.data.workspaces, a.query, (w) => [w.slug, w.id], (w) => w.title), "workspace", (w) => `${w.title} (${w.slug})`, (w) => w.slug);
68
70
  } },
69
71
  { name: "networkbase_task_count", title: "Count my tasks", tier: "read", props: {},
70
- description: `Count the user's open NetworkBase tasks by status across workspaces. Use for "how many tasks do I have".`,
72
+ description: `Count the user's open NetworkBase tasks across all their workspaces, by status and per workspace. Use for "how many tasks do I have". The totals are for every workspace, not only this folder's: say which workspace each overdue task is in (data.workspaces).`,
71
73
  run: (nb) => nb("task count") },
72
74
  { name: "networkbase_task_list", title: "List tasks", tier: "read",
73
75
  props: { workspace: workspaceProp, all: { type: "boolean", description: "Include tasks assigned to others" }, status: { type: "string", description: "Comma list of todo, in_progress, blocked, review, done" }, limit: { type: "number", description: "At most this many (default 50)" } },
@@ -222,28 +224,45 @@ export const TOOLS = [
222
224
  ];
223
225
 
224
226
  /**
225
- * In-process confirmation tokens: single use, 10 minutes, bound to the tool and its exact arguments, so a "yes"
226
- * can't be reused for something else. ponytail: local only; server-side tiers and tokens come with P3.4.
227
+ * Local yes tokens (report D24): signed like the server's (HMAC, 10 minutes, bound to the tool and its exact
228
+ * arguments, used once), with a key made from this computer's sign-in. Any nb process signed in the same way can
229
+ * check one, so a headless agent (`claude -p --continue`, CI) that starts a new MCP server each turn can still
230
+ * confirm. No "." in them: a dotted token is the server's and goes to the server.
227
231
  */
228
- const confirmations = new Map();
229
232
  /** @param {string} name @param {any} args */
230
233
  const fingerprint = (name, args) => {
231
234
  const { confirmToken: _t, answers: _a, ...rest } = args ?? {};
232
235
  return crypto.createHash("sha256").update(`${name}\n${JSON.stringify(rest, Object.keys(rest).sort())}`).digest("hex");
233
236
  };
234
- /** @param {string} name @param {any} args */
235
- function issueConfirmation(name, args) {
236
- const token = crypto.randomBytes(16).toString("hex");
237
- confirmations.set(token, { print: fingerprint(name, args), expires: Date.now() + 10 * 60_000 });
238
- return token;
237
+ /** Without a saved sign-in there is nothing to share, so the key stays in this process. */
238
+ const processKey = crypto.randomBytes(32).toString("hex");
239
+ /** @param {NodeJS.ProcessEnv} env */
240
+ const yesKey = (env) => crypto.createHash("sha256").update(`nb-local-yes\n${currentProfile({ flags: {}, env, project: null }).token ?? processKey}`).digest();
241
+ /** @param {NodeJS.ProcessEnv} env @param {string} print @param {string} expires @param {string} nonce */
242
+ const yesMac = (env, print, expires, nonce) => crypto.createHmac("sha256", yesKey(env)).update(`${print}|${expires}|${nonce}`).digest("hex").slice(0, 32);
243
+ /** @param {string} name @param {any} args @param {NodeJS.ProcessEnv} env */
244
+ function issueConfirmation(name, args, env) {
245
+ const expires = (Date.now() + 10 * 60_000).toString(36);
246
+ const nonce = crypto.randomBytes(9).toString("hex");
247
+ return `y_${expires}_${nonce}_${yesMac(env, fingerprint(name, args), expires, nonce)}`;
239
248
  }
240
- /** @param {string} name @param {any} args */
241
- function takeConfirmation(name, args) {
249
+ /** @param {string} name @param {any} args @param {NodeJS.ProcessEnv} env */
250
+ function takeConfirmation(name, args, env) {
242
251
  const token = args?.confirmToken;
243
252
  if (!token) return false;
244
- const entry = confirmations.get(token);
245
- confirmations.delete(token);
246
- if (!entry || entry.expires < Date.now() || entry.print !== fingerprint(name, args)) throw new CliError("CONFIRMATION_INVALID", "That confirmToken doesn't match this call or has expired", { hint: "Call again without confirmToken to get a new one, and show it to the user" });
253
+ const invalid = () => new CliError("CONFIRMATION_INVALID", "That confirmToken doesn't match this call or has expired", { hint: "Call again without confirmToken to get a new one, and show it to the user" });
254
+ const [, expires = "", nonce = "", mac = ""] = /^y_([0-9a-z]+)_([0-9a-f]{18})_([0-9a-f]{32})$/.exec(String(token)) ?? [];
255
+ if (!mac || parseInt(expires, 36) < Date.now()) throw invalid();
256
+ const want = yesMac(env, fingerprint(name, args), expires, nonce);
257
+ if (!crypto.timingSafeEqual(Buffer.from(want), Buffer.from(mac))) throw invalid();
258
+ // Once only, across processes: used nonces are kept until they'd have expired anyway.
259
+ const file = path.join(globalDir(env), "used-yes.json");
260
+ /** @type {Record<string, number>} */
261
+ let used = {};
262
+ try { used = readJson(file) ?? {}; } catch { used = {}; }
263
+ if (used[nonce]) throw invalid();
264
+ const now = Date.now();
265
+ try { writeAtomic(file, JSON.stringify(Object.fromEntries([...Object.entries(used).filter(([, until]) => until > now), [nonce, parseInt(expires, 36)]]))); } catch { /* read-only home: once per process at least */ }
247
266
  return true;
248
267
  }
249
268
 
@@ -276,11 +295,11 @@ export async function callTool(name, args = {}, where) {
276
295
  try {
277
296
  // A server-issued yes (signed, contains a dot) goes to the server as X-NB-Confirm; it decides.
278
297
  const serverYes = typeof args.confirmToken === "string" && args.confirmToken.includes(".") ? args.confirmToken : null;
279
- const confirmed = serverYes ? false : takeConfirmation(name, args);
298
+ const confirmed = serverYes ? false : takeConfirmation(name, args, where.env);
280
299
  // With an agent token the server holds big changes itself (report §26.6), so asking here too would ask twice.
281
300
  const agentToken = String(createContext({ flags: {}, positionals: [], cwd: where.cwd, env: where.env, io: { stdout: /** @type {any} */ ({ write: () => true }), stderr: process.stderr } }).profile.token ?? "").startsWith("nb_agt_");
282
301
  const summary = !confirmed && !serverYes && !agentToken && tool.needsYes ? tool.needsYes(args) : null;
283
- if (summary) return confirmationResult(name, args, summary, undefined);
302
+ if (summary) return confirmationResult(name, args, summary, undefined, where.env);
284
303
  const answers = Object.entries(args.answers ?? {}).map(([k, v]) => `${k}=${v}`);
285
304
  const nb = executor(where, { ...(confirmed || serverYes ? { yes: true } : {}), ...(serverYes ? { confirm: serverYes } : {}), ...(answers.length ? { answer: answers } : {}) });
286
305
  const r = await tool.run(nb, args);
@@ -294,19 +313,67 @@ export async function callTool(name, args = {}, where) {
294
313
  structuredContent: { status: "needs_confirmation", summary: held.summary ?? "this change needs a yes", ...(held.preview ? { preview: held.preview } : {}), confirmToken: held.confirmToken, by: "server" },
295
314
  };
296
315
  }
297
- if (error instanceof CliError && error.code === "NEEDS_CONFIRMATION") return confirmationResult(name, args, error.message, /** @type {any} */ (error.details)?.questions?.[0]?.preview);
316
+ if (error instanceof CliError && error.code === "NEEDS_CONFIRMATION") return confirmationResult(name, args, error.message, /** @type {any} */ (error.details)?.questions?.[0]?.preview, where.env);
298
317
  if (error instanceof CliError && error.code === "NEEDS_INPUT") {
299
318
  const questions = /** @type {any} */ (error.details)?.questions ?? [];
300
319
  const lines = questions.map((/** @type {any} */ q) => `${q.question} (answers.${q.key}: ${q.options.map((/** @type {any} */ o) => `${o.value}${o.recommended ? " [recommended]" : ""}`).join(" | ")})`);
301
320
  return { content: [{ type: "text", text: `needs_input: ask the user, then call again with answers.\n${lines.join("\n") || error.message}` }], structuredContent: { status: "needs_input", questions } };
302
321
  }
322
+ // A missing permission was asked for, or refused, by the person (report A5 "Asking for more", A6 #3).
323
+ if (error instanceof CliError && (error.code === "ACCESS_REQUESTED" || error.code === "ACCESS_DENIED_BY_PERSON")) {
324
+ const details = /** @type {any} */ (error.details) ?? {};
325
+ const what = SCOPE_WORDS[details.scope] ?? details.scope ?? "do that";
326
+ if (error.code === "ACCESS_REQUESTED") {
327
+ return {
328
+ content: [{ type: "text", text: `access_requested: this needs permission to ${what}, which you weren't given, so NetworkBase asked the person in NetworkBase. Tell them what you asked for and why. Once they answer Allow once or Always, call ${name} again with the same arguments. Don't look for another way to do it.` }],
329
+ structuredContent: { status: "access_requested", scope: details.scope ?? null, requestId: details.requestId ?? null },
330
+ };
331
+ }
332
+ return {
333
+ isError: true,
334
+ content: [{ type: "text", text: `access_denied: the person said no to letting you ${what} (for 24 hours). Don't try another way; tell them it's theirs to do, and carry on with what you can do.` }],
335
+ structuredContent: { status: "access_denied", scope: details.scope ?? null, retryAfter: details.retryAfter ?? null },
336
+ };
337
+ }
303
338
  return errorResult(error);
304
339
  }
305
340
  }
306
341
 
307
- /** @param {string} name @param {any} args @param {string} summary @param {string | undefined} preview */
308
- function confirmationResult(name, args, summary, preview) {
309
- const confirmToken = issueConfirmation(name, args);
342
+ /** Permissions in the words the approval page uses (report A2). */
343
+ const SCOPE_WORDS = /** @type {Record<string, string>} */ ({ "task:complete": "finish tasks", "file:final": "change final files", "doc:write": "edit docs", "task:write": "change tasks", "file:write": "save files", "task:review": "approve or return reviews" });
344
+ /** Tools whose main job needs a permission an agent preset may leave out. */
345
+ const NEEDS_SCOPE = /** @type {Record<string, string>} */ ({ networkbase_task_done: "task:complete", networkbase_doc_update: "doc:write" });
346
+
347
+ /**
348
+ * Who this MCP server works for and what it may do (report A6 #1), read from /api/v1/me via nb whoami. Null when
349
+ * that can't be read (offline, signed out): the server still starts, with no card.
350
+ * @param {{ cwd: string, env: NodeJS.ProcessEnv }} where
351
+ */
352
+ export async function readAccess(where) {
353
+ try {
354
+ const r = await executor(where, {})("whoami");
355
+ return { user: r.data.user, access: r.data.access ?? null, scopes: r.data.credential?.scopes ?? [] };
356
+ } catch {
357
+ return null;
358
+ }
359
+ }
360
+
361
+ /** The access card at the top of the server's instructions (report A6 #1). @param {any} a */
362
+ export function accessCard(a) {
363
+ if (!a?.user) return "";
364
+ const who = `${a.user.fullName ?? a.user.username ?? a.user.email ?? "the person"}${a.user.username ? ` (@${a.user.username})` : ""}`;
365
+ if (!a.access) return `Signed in as ${who} with their own sign-in: you can do what they can, and big changes still go to them first.`;
366
+ return [
367
+ `You are working for ${who} on NetworkBase.`,
368
+ `What they approved: "${a.access.sentence}"`,
369
+ "Whatever the access, finishing tasks, final files, doc edits and deleting wait for their yes (needs_confirmation).",
370
+ "If a tool answers access_requested, NetworkBase has asked them for that permission: tell them, and try again after they answer. Never look for another way round.",
371
+ ].join("\n");
372
+ }
373
+
374
+ /** @param {string} name @param {any} args @param {string} summary @param {string | undefined} preview @param {NodeJS.ProcessEnv} env */
375
+ function confirmationResult(name, args, summary, preview, env) {
376
+ const confirmToken = issueConfirmation(name, args, env);
310
377
  return {
311
378
  content: [{ type: "text", text: `needs_confirmation: ${summary}${preview ? `\n\n${preview}` : ""}\n\nShow this to the user. Only if they agree, call ${name} again with the same arguments and confirmToken "${confirmToken}".` }],
312
379
  structuredContent: { status: "needs_confirmation", summary, ...(preview ? { preview } : {}), confirmToken },
@@ -322,13 +389,17 @@ function errorResult(error) {
322
389
  /** Tools that read or write files in a linked folder, or the local undo log: only `nb mcp` on your computer has them. */
323
390
  export const HOSTED_EXCLUDED = new Set(["networkbase_status", "networkbase_file_push", "networkbase_file_pull", "networkbase_undo"]);
324
391
 
325
- /** tools/list entries, with tier hints for clients (A7.3). @param {boolean} [hosted] */
392
+ /**
393
+ * tools/list entries, with tier hints for clients (A7.3). With an agent's access (A6 #2), Read only lists only the
394
+ * tools that read, and tools that need the person first say so at the start of their description.
395
+ * @param {boolean} [hosted] @param {any} [access] from readAccess
396
+ */
326
397
  // Every tool that writes takes confirmToken: the server can hold any write for a yes (someone else's task, a file as
327
398
  // final, "Ask for everything"), and a client only sends what the schema lists.
328
- export const toolList = (hosted = false) => TOOLS.filter((t) => !hosted || !HOSTED_EXCLUDED.has(t.name)).map((t) => ({
399
+ export const toolList = (hosted = false, access = null) => TOOLS.filter((t) => (!hosted || !HOSTED_EXCLUDED.has(t.name)) && (access?.access?.preset !== "read" || t.tier === "read")).map((t) => ({
329
400
  name: t.name,
330
401
  title: t.title,
331
- description: t.description,
402
+ description: describeFor(t, access),
332
403
  inputSchema: {
333
404
  type: "object",
334
405
  properties: { ...t.props, ...(t.tier !== "read" ? { answers: { type: "object", description: "Answers to a needs_input question: { key: value }" } } : {}), ...(t.tier !== "read" ? { confirmToken: { type: "string", description: "From a needs_confirmation result, after the user agreed" } } : {}) },
@@ -336,3 +407,10 @@ export const toolList = (hosted = false) => TOOLS.filter((t) => !hosted || !HOST
336
407
  },
337
408
  annotations: { title: t.title, readOnlyHint: t.tier === "read", destructiveHint: t.tier === "yes", openWorldHint: false },
338
409
  }));
410
+
411
+ /** @param {Tool} t @param {any} access */
412
+ function describeFor(t, access) {
413
+ const scope = NEEDS_SCOPE[t.name];
414
+ if (access?.access && scope && !access.scopes.includes(scope)) return `Asks the person first: you weren't given permission to ${SCOPE_WORDS[scope]}, so calling this asks them in NetworkBase. ${t.description}`;
415
+ return t.tier === "yes" && access?.access ? `Needs the person's yes: ${t.description}` : t.description;
416
+ }
@@ -22,6 +22,12 @@ export function newer(a, b) {
22
22
 
23
23
  /** @param {import("../context.mjs").Context} ctx */
24
24
  export async function afterCommand(ctx) {
25
+ // 7 days before this computer's sign-in ends, once a day (C6); nb login renews the same sign-in.
26
+ const ends = ctx.profile.profile?.source === "file" ? Date.parse(ctx.profile.profile.expiresAt ?? "") : NaN;
27
+ if (ends > Date.now() && ends - Date.now() < 7 * DAY) {
28
+ const { remindOnce } = await import("./remind.mjs");
29
+ remindOnce(ctx, "sign-in-ends", `Your sign-in on this computer ends ${new Date(ends).toLocaleDateString("en-GB", { day: "numeric", month: "short" })}: nb login renews it`);
30
+ }
25
31
  if (ctx.out.json || ctx.flags.quiet || ctx.env.CI || ctx.env.NB_NO_UPDATE_CHECK || !process.stderr.isTTY) return;
26
32
  const file = path.join(globalDir(ctx.env), "update.json");
27
33
  /** @type {{ lastRun?: string, checkedAt?: number, latest?: string }} */
package/lib/print/out.mjs CHANGED
@@ -1,5 +1,6 @@
1
1
  // The only place the CLI writes to the terminal (report A4.5, A4.7, A4.8, A13.1). stdout carries results
2
2
  // (text or one JSON envelope); stderr carries progress, hints, warnings and prompts.
3
+ import { FIXES } from "../error-fixes.mjs";
3
4
  import { spawnSync } from "node:child_process";
4
5
 
5
6
  import { colorLevel, palette, pad, safe, symbols, truncateEnd, truncateMiddle, asciiOnly, width, hyperlinks } from "./style.mjs";
@@ -92,8 +93,9 @@ export function createOutput(mode, io = {}) {
92
93
  },
93
94
  /** @param {import("../errors.mjs").CliError} error */
94
95
  error(error) {
95
- // Server errors link to their entry on /docs/cli (report A2.6).
96
- const docs = error.status && /^[A-Z_]+$/.test(error.code) ? `https://networkbase.in/docs/cli#error-${error.code}` : null;
96
+ // Every catalogued code links to its entry on /docs/cli (report A2.6, C5), and ends with a next step.
97
+ const docs = FIXES[error.code] && error.code !== "CANCELLED" ? `https://networkbase.in/docs/cli#error-${error.code}` : null;
98
+ if (!error.hint && FIXES[error.code] && error.code !== "CANCELLED") error.hint = FIXES[error.code];
97
99
  if (json) {
98
100
  const body = { ok: false, error: { code: error.code, message: error.message, ...(error.hint ? { hint: error.hint } : {}), ...(error.details !== undefined ? { details: error.details } : {}), ...(docs ? { docs } : {}) } };
99
101
  stdout.write(`${JSON.stringify(body)}\n`);
@@ -0,0 +1,251 @@
1
+ // A QR code for the approval link (report A4), so a server or SSH session can be approved from a phone. Byte mode,
2
+ // error correction level L, versions 1–10 (up to 271 bytes): enough for any approval URL. No dependency (G25.1).
3
+ // The steps follow ISO/IEC 18004: data bits → Reed–Solomon blocks → function patterns → zigzag placement → the
4
+ // mask with the lowest penalty → format and version bits. tests/qr.test.mjs checks a matrix that macOS decoded.
5
+
6
+ // Level L, versions 1–10: error-correction codewords per block, and blocks.
7
+ const ECC_PER_BLOCK = [0, 7, 10, 15, 20, 26, 18, 20, 24, 30, 18];
8
+ const BLOCKS = [0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 4];
9
+
10
+ /** Codewords for data and error correction together. @param {number} ver */
11
+ function rawCodewords(ver) {
12
+ let modules = (16 * ver + 128) * ver + 64;
13
+ if (ver >= 2) {
14
+ const align = Math.floor(ver / 7) + 2;
15
+ modules -= (25 * align - 10) * align - 55;
16
+ if (ver >= 7) modules -= 36;
17
+ }
18
+ return Math.floor(modules / 8);
19
+ }
20
+ const dataCodewords = (/** @type {number} */ ver) => rawCodewords(ver) - ECC_PER_BLOCK[ver] * BLOCKS[ver];
21
+
22
+ // GF(256) with the QR polynomial x^8 + x^4 + x^3 + x^2 + 1.
23
+ const EXP = new Uint8Array(512);
24
+ const LOG = new Uint8Array(256);
25
+ for (let i = 0, x = 1; i < 255; i++) {
26
+ EXP[i] = x;
27
+ LOG[x] = i;
28
+ x = (x << 1) ^ (x & 0x80 ? 0x11d : 0);
29
+ }
30
+ for (let i = 255; i < 512; i++) EXP[i] = EXP[i - 255];
31
+ const mul = (/** @type {number} */ a, /** @type {number} */ b) => (a && b ? EXP[LOG[a] + LOG[b]] : 0);
32
+
33
+ /** The Reed–Solomon remainder of `data` for `degree` check bytes. @param {number[]} data @param {number} degree */
34
+ function reedSolomon(data, degree) {
35
+ // Generator: (x - α^0)(x - α^1)…(x - α^(degree-1)), highest power first and its leading 1 left out.
36
+ let gen = [1];
37
+ for (let i = 0; i < degree; i++) {
38
+ const next = new Array(gen.length + 1).fill(0);
39
+ for (let j = 0; j < gen.length; j++) {
40
+ next[j] ^= gen[j];
41
+ next[j + 1] ^= mul(gen[j], EXP[i]);
42
+ }
43
+ gen = next;
44
+ }
45
+ gen = gen.slice(1);
46
+ const rem = new Array(degree).fill(0);
47
+ for (const b of data) {
48
+ const factor = b ^ /** @type {number} */ (rem.shift());
49
+ rem.push(0);
50
+ for (let j = 0; j < degree; j++) rem[j] ^= mul(gen[j], factor);
51
+ }
52
+ return rem;
53
+ }
54
+
55
+ /** The codewords to place: data split into blocks, each with its check bytes, interleaved. @param {Uint8Array} bytes @param {number} ver */
56
+ function codewords(bytes, ver) {
57
+ const capacity = dataCodewords(ver);
58
+ /** @type {number[]} */
59
+ const bits = [];
60
+ const put = (/** @type {number} */ value, /** @type {number} */ length) => { for (let i = length - 1; i >= 0; i--) bits.push((value >>> i) & 1); };
61
+ put(0b0100, 4);
62
+ put(bytes.length, ver <= 9 ? 8 : 16);
63
+ for (const b of bytes) put(b, 8);
64
+ put(0, Math.min(4, capacity * 8 - bits.length));
65
+ put(0, (8 - (bits.length % 8)) % 8);
66
+ const data = [];
67
+ for (let i = 0; i < bits.length; i += 8) data.push(bits.slice(i, i + 8).reduce((a, b) => (a << 1) | b, 0));
68
+ for (let pad = 0xec; data.length < capacity; pad ^= 0xec ^ 0x11) data.push(pad);
69
+
70
+ const blocks = BLOCKS[ver];
71
+ const ecc = ECC_PER_BLOCK[ver];
72
+ const total = rawCodewords(ver);
73
+ const shortBlocks = blocks - (total % blocks);
74
+ const shortData = Math.floor(total / blocks) - ecc;
75
+ const parts = [];
76
+ for (let i = 0, at = 0; i < blocks; i++) {
77
+ const length = shortData + (i < shortBlocks ? 0 : 1);
78
+ const chunk = data.slice(at, at + length);
79
+ at += length;
80
+ parts.push({ data: chunk, ecc: reedSolomon(chunk, ecc) });
81
+ }
82
+ const out = [];
83
+ for (let i = 0; i <= shortData; i++) for (const p of parts) if (i < p.data.length) out.push(p.data[i]);
84
+ for (let i = 0; i < ecc; i++) for (const p of parts) out.push(p.ecc[i]);
85
+ return out;
86
+ }
87
+
88
+ const MASKS = [
89
+ (/** @type {number} */ x, /** @type {number} */ y) => (x + y) % 2 === 0,
90
+ (/** @type {number} */ _x, /** @type {number} */ y) => y % 2 === 0,
91
+ (/** @type {number} */ x) => x % 3 === 0,
92
+ (/** @type {number} */ x, /** @type {number} */ y) => (x + y) % 3 === 0,
93
+ (/** @type {number} */ x, /** @type {number} */ y) => (Math.floor(x / 3) + Math.floor(y / 2)) % 2 === 0,
94
+ (/** @type {number} */ x, /** @type {number} */ y) => ((x * y) % 2) + ((x * y) % 3) === 0,
95
+ (/** @type {number} */ x, /** @type {number} */ y) => (((x * y) % 2) + ((x * y) % 3)) % 2 === 0,
96
+ (/** @type {number} */ x, /** @type {number} */ y) => (((x + y) % 2) + ((x * y) % 3)) % 2 === 0,
97
+ ];
98
+
99
+ /** Lower is easier to scan (ISO/IEC 18004 §7.8.3). @param {boolean[][]} m */
100
+ function penalty(m) {
101
+ const size = m.length;
102
+ let score = 0;
103
+ const line = (/** @type {(i: number) => boolean} */ at) => {
104
+ let run = 1;
105
+ for (let i = 1; i <= size; i++) {
106
+ if (i < size && at(i) === at(i - 1)) run++;
107
+ else { if (run >= 5) score += 3 + (run - 5); run = 1; }
108
+ }
109
+ // Finder-like 1:1:3:1:1 with four light modules on one side.
110
+ for (let i = 0; i + 11 <= size; i++) {
111
+ const s = Array.from({ length: 11 }, (_, k) => (at(i + k) ? 1 : 0)).join("");
112
+ if (s === "10111010000" || s === "00001011101") score += 40;
113
+ }
114
+ };
115
+ for (let y = 0; y < size; y++) line((x) => m[y][x]);
116
+ for (let x = 0; x < size; x++) line((y) => m[y][x]);
117
+ let dark = 0;
118
+ for (let y = 0; y < size; y++) {
119
+ for (let x = 0; x < size; x++) {
120
+ if (m[y][x]) dark++;
121
+ if (x < size - 1 && y < size - 1 && m[y][x] === m[y][x + 1] && m[y][x] === m[y + 1][x] && m[y][x] === m[y + 1][x + 1]) score += 3;
122
+ }
123
+ }
124
+ const total = size * size;
125
+ return score + (Math.ceil(Math.abs(dark * 20 - total * 10) / total) - 1) * 10;
126
+ }
127
+
128
+ /**
129
+ * The module matrix for `text` (true = dark), smallest version that fits. Throws when it needs more than version 10.
130
+ * @param {string} text
131
+ * @returns {boolean[][]}
132
+ */
133
+ export function qrMatrix(text) {
134
+ const bytes = new TextEncoder().encode(text);
135
+ let ver = 1;
136
+ while (ver <= 10 && 4 + (ver <= 9 ? 8 : 16) + bytes.length * 8 > dataCodewords(ver) * 8) ver++;
137
+ if (ver > 10) throw new Error("Too long for a QR code here");
138
+ const size = ver * 4 + 17;
139
+ const m = Array.from({ length: size }, () => new Array(size).fill(false));
140
+ const fixed = Array.from({ length: size }, () => new Array(size).fill(false));
141
+ const set = (/** @type {number} */ x, /** @type {number} */ y, /** @type {boolean} */ dark) => { m[y][x] = dark; fixed[y][x] = true; };
142
+
143
+ for (let i = 0; i < size; i++) { set(6, i, i % 2 === 0); set(i, 6, i % 2 === 0); }
144
+ for (const [cx, cy] of [[3, 3], [size - 4, 3], [3, size - 4]]) {
145
+ for (let dy = -4; dy <= 4; dy++) {
146
+ for (let dx = -4; dx <= 4; dx++) {
147
+ const x = cx + dx;
148
+ const y = cy + dy;
149
+ const d = Math.max(Math.abs(dx), Math.abs(dy));
150
+ if (x >= 0 && x < size && y >= 0 && y < size) set(x, y, d !== 2 && d !== 4);
151
+ }
152
+ }
153
+ }
154
+ if (ver >= 2) {
155
+ const count = Math.floor(ver / 7) + 2;
156
+ const step = Math.ceil((ver * 4 + 4) / (count * 2 - 2)) * 2;
157
+ const pos = [6];
158
+ for (let p = size - 7; pos.length < count; p -= step) pos.splice(1, 0, p);
159
+ for (let i = 0; i < count; i++) {
160
+ for (let j = 0; j < count; j++) {
161
+ if ((i === 0 && j === 0) || (i === 0 && j === count - 1) || (i === count - 1 && j === 0)) continue;
162
+ for (let dy = -2; dy <= 2; dy++) for (let dx = -2; dx <= 2; dx++) set(pos[i] + dx, pos[j] + dy, Math.max(Math.abs(dx), Math.abs(dy)) !== 1);
163
+ }
164
+ }
165
+ }
166
+ // Reserve the format areas (filled per mask below), the dark module, and the version bits.
167
+ const format = (/** @type {number} */ mask) => {
168
+ let rem = (0b01 << 3) | mask;
169
+ const data = rem;
170
+ for (let i = 0; i < 10; i++) rem = (rem << 1) ^ ((rem >>> 9) * 0x537);
171
+ const bits = ((data << 10) | rem) ^ 0x5412;
172
+ const bit = (/** @type {number} */ i) => ((bits >>> i) & 1) === 1;
173
+ for (let i = 0; i <= 5; i++) set(8, i, bit(i));
174
+ set(8, 7, bit(6));
175
+ set(8, 8, bit(7));
176
+ set(7, 8, bit(8));
177
+ for (let i = 9; i < 15; i++) set(14 - i, 8, bit(i));
178
+ for (let i = 0; i < 8; i++) set(size - 1 - i, 8, bit(i));
179
+ for (let i = 8; i < 15; i++) set(8, size - 15 + i, bit(i));
180
+ set(8, size - 8, true);
181
+ };
182
+ format(0);
183
+ if (ver >= 7) {
184
+ let rem = ver;
185
+ for (let i = 0; i < 12; i++) rem = (rem << 1) ^ ((rem >>> 11) * 0x1f25);
186
+ const bits = (ver << 12) | rem;
187
+ for (let i = 0; i < 18; i++) {
188
+ const dark = ((bits >>> i) & 1) === 1;
189
+ const a = size - 11 + (i % 3);
190
+ const b = Math.floor(i / 3);
191
+ set(a, b, dark);
192
+ set(b, a, dark);
193
+ }
194
+ }
195
+
196
+ const words = codewords(bytes, ver);
197
+ let i = 0;
198
+ for (let right = size - 1; right >= 1; right -= 2) {
199
+ if (right === 6) right = 5;
200
+ for (let vert = 0; vert < size; vert++) {
201
+ for (let j = 0; j < 2; j++) {
202
+ const x = right - j;
203
+ const y = ((right + 1) & 2) === 0 ? size - 1 - vert : vert;
204
+ if (!fixed[y][x] && i < words.length * 8) {
205
+ m[y][x] = ((words[i >>> 3] >>> (7 - (i & 7))) & 1) === 1;
206
+ i++;
207
+ }
208
+ }
209
+ }
210
+ }
211
+
212
+ let best = /** @type {boolean[][] | null} */ (null);
213
+ let bestScore = Infinity;
214
+ for (let mask = 0; mask < 8; mask++) {
215
+ const masked = m.map((row, y) => row.map((dark, x) => (fixed[y][x] ? dark : dark !== MASKS[mask](x, y))));
216
+ const keep = m.map((row) => [...row]);
217
+ for (let y = 0; y < size; y++) for (let x = 0; x < size; x++) m[y][x] = masked[y][x];
218
+ format(mask);
219
+ const score = penalty(m);
220
+ if (score < bestScore) { bestScore = score; best = m.map((row) => [...row]); }
221
+ for (let y = 0; y < size; y++) for (let x = 0; x < size; x++) m[y][x] = keep[y][x];
222
+ }
223
+ return /** @type {boolean[][]} */ (best);
224
+ }
225
+
226
+ /**
227
+ * Two module rows per text line with half blocks, light modules drawn: on a dark terminal the code reads as dark on
228
+ * light, and phone cameras read the inverse too. A two-module quiet zone keeps it narrow.
229
+ * @param {string} text
230
+ */
231
+ export function qrLines(text) {
232
+ const m = qrMatrix(text);
233
+ const quiet = 2;
234
+ const size = m.length + quiet * 2;
235
+ const light = (/** @type {number} */ x, /** @type {number} */ y) => {
236
+ const mx = x - quiet;
237
+ const my = y - quiet;
238
+ return !(mx >= 0 && my >= 0 && mx < m.length && my < m.length && m[my][mx]);
239
+ };
240
+ const lines = [];
241
+ for (let y = 0; y < size; y += 2) {
242
+ let row = "";
243
+ for (let x = 0; x < size; x++) {
244
+ const top = light(x, y);
245
+ const bottom = y + 1 < size ? light(x, y + 1) : false;
246
+ row += top && bottom ? "█" : top ? "▀" : bottom ? "▄" : " ";
247
+ }
248
+ lines.push(row);
249
+ }
250
+ return lines;
251
+ }
@@ -7,7 +7,7 @@ import { DIR_NAME, readJson, writeAtomic } from "../config.mjs";
7
7
 
8
8
  export const QUEUE_TTL_MS = 7 * 24 * 60 * 60 * 1000;
9
9
 
10
- /** @typedef {{ id: string, op: "push", paths: string[], flags: Record<string, any>, queuedAt: string }} QueueEntry */
10
+ /** @typedef {{ id: string, op: "push", paths: string[], flags: Record<string, any>, queuedAt: string, reason?: string }} QueueEntry */
11
11
 
12
12
  /** @param {string} root */
13
13
  const file = (root) => path.join(root, DIR_NAME, "queue.json");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@networkbase/cli",
3
- "version": "2.0.3",
3
+ "version": "2.1.0",
4
4
  "description": "NetworkBase in your terminal: sync files, work on tasks, edit docs",
5
5
  "type": "module",
6
6
  "homepage": "https://networkbase.in",