@networkbase/cli 2.0.3 → 2.0.4

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/api.mjs CHANGED
@@ -15,7 +15,9 @@ const sleep = (/** @type {number} */ ms) => new Promise((resolve) => setTimeout(
15
15
  const HINTS = /** @type {Record<string, string>} */ ({
16
16
  NEEDS_CONFIRMATION: "Show this to the person; if they agree, run the same command again with --confirm <token> (in --json: error.details.confirmToken)",
17
17
  UNAUTHORIZED: "Run nb login",
18
- SCOPE_MISSING: "This token can't do that; sign in again with nb login, or make a token with more access in Settings → Integrations",
18
+ SCOPE_MISSING: "Allow it in Settings → Integrations: Change access for an agent, or a token with more access",
19
+ ACCESS_REQUESTED: "The person answers in NetworkBase (their inbox, or Settings → Integrations); run the same command again once they have",
20
+ ACCESS_DENIED_BY_PERSON: "The person said no for 24 hours: leave this one to them",
19
21
  FORBIDDEN: "Check you're a member of this workspace with nb whoami",
20
22
  RATE_LIMITED: "Wait a minute and try again",
21
23
  VERSION_CONFLICT: "Run nb pull, then push again — or nb resolve <path>",
@@ -28,20 +28,57 @@ export async function saveToken(ctx, profileName, token) {
28
28
  return me;
29
29
  }
30
30
 
31
+ /** The access line (report A4): "Claude Code connected · all workspaces · asks before big changes · until 11 Dec". @param {any} access */
32
+ export function accessLine(access) {
33
+ const where = access.allWorkspaces ? "all workspaces" : `only ${access.workspaceTitle ?? "one workspace"}`;
34
+ const what = { full: "asks before big changes", small: "small changes only", read: "read only", custom: "custom access" }[/** @type {string} */ (access.preset)] ?? access.preset;
35
+ const until = new Date(access.expiresAt).toLocaleDateString("en-GB", { day: "numeric", month: "short" });
36
+ return `${access.agentName} connected · ${where} · ${what} · until ${until}`;
37
+ }
38
+
39
+ /** What to show once an agent is approved: the access line and something to try. @param {Context} ctx @param {any} access */
40
+ export function connectedLines(ctx, access) {
41
+ return [`${ctx.out.c.success(ctx.out.sym.done)} ${safe(accessLine(access))}`, ctx.out.c.muted(` Try it: open ${safe(access.agentName)} and ask "what should I do today?"`)];
42
+ }
43
+
31
44
  /** @param {Context} ctx @param {string} token @param {string} method */
32
45
  async function finish(ctx, token, method) {
33
46
  const me = await whoIs(ctx, token);
34
47
  saveProfile(ctx.profile.name, { origin: ctx.profile.origin, token, user: { id: me.user.id, username: me.user.username, email: me.user.email } }, ctx.env);
35
- ctx.out.result("nb.login/1", { method, origin: ctx.profile.origin, profile: ctx.profile.name, user: me.user, scopes: me.credential.scopes }, (d) =>
36
- `${ctx.out.c.success(ctx.out.sym.done)} Signed in as ${safe(d.user.username ? `@${d.user.username}` : d.user.email ?? d.user.id)} on ${new URL(d.origin).host}${d.profile !== "default" ? ` (profile ${d.profile})` : ""}`);
48
+ ctx.out.result("nb.login/1", { method, origin: ctx.profile.origin, profile: ctx.profile.name, user: me.user, scopes: me.credential.scopes, access: me.access ?? null }, (d) =>
49
+ d.access ? connectedLines(ctx, d.access) : `${ctx.out.c.success(ctx.out.sym.done)} Signed in as ${safe(d.user.username ? `@${d.user.username}` : d.user.email ?? d.user.id)} on ${new URL(d.origin).host}${d.profile !== "default" ? ` (profile ${d.profile})` : ""}`);
37
50
  }
38
51
 
39
52
  /** Over SSH, or on Linux without a display, a browser can't open here, so the code flow is used (A3.1). @param {NodeJS.ProcessEnv} env */
40
53
  const noBrowserHere = (env) => Boolean(env.SSH_CONNECTION || env.SSH_TTY || (process.platform === "linux" && !env.DISPLAY && !env.WAYLAND_DISPLAY));
54
+ const UUID_SHAPE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
55
+
56
+ /**
57
+ * What the sign-in asks for (report A5): --access full|small|read, --workspace <slug|id>, --all-workspaces. The
58
+ * approval page pre-fills it; the person can change it. A workspace that can't be looked up before signing in is
59
+ * left for the page, never an error (a signed-out login must not stop on --workspace).
60
+ * @param {Context} ctx
61
+ */
62
+ async function signInWishes(ctx) {
63
+ const access = ctx.flags.access;
64
+ if (access !== undefined && !["full", "small", "read"].includes(String(access))) throw usage("--access takes full, small or read");
65
+ /** @type {string | null} */
66
+ let workspace = null;
67
+ const given = typeof ctx.flags.workspace === "string" ? ctx.flags.workspace.trim() : "";
68
+ if (ctx.flags["all-workspaces"]) workspace = "all";
69
+ else if (given && UUID_SHAPE.test(given)) workspace = given;
70
+ else if (given) {
71
+ const p = ctx.project;
72
+ if (p?.workspaceId && [p.slug, p.title].some((v) => v && v.toLowerCase() === given.toLowerCase())) workspace = p.workspaceId;
73
+ else if (ctx.profile.token) workspace = await ctx.resolveWorkspace().then(() => (UUID_SHAPE.test(String(ctx.flags.workspace)) ? String(ctx.flags.workspace) : null), () => null);
74
+ if (!workspace) ctx.out.note(ctx.out.c.muted(`Choose ${safe(given)} on the approval page.`));
75
+ }
76
+ return { ...(access ? { requestedAccess: String(access) } : {}), ...(workspace ? { requestedWorkspace: workspace } : {}) };
77
+ }
41
78
 
42
79
  /**
43
- * Sign-in with a code (report A3.1): the server gives a code, the person approves it at /device on any device
44
- * where they're signed in, and this terminal polls until then (10 minutes at most).
80
+ * Sign-in with a code (report A3.1, A4): the server gives a code; the browser opens at the approval page by itself
81
+ * where it can, a QR code covers a phone, and this terminal polls until the person answers (10 minutes at most).
45
82
  * @param {Context} ctx
46
83
  * @returns {Promise<string>}
47
84
  */
@@ -54,26 +91,49 @@ export async function deviceLogin(ctx, agentName = /** @type {string | null} */
54
91
  clientVersion: ctx.version,
55
92
  platform: `${process.platform} ${process.arch}`,
56
93
  type: agent ? "agent" : "device",
57
- ...(agent ? { agentName: agent } : {}),
94
+ ...(agent ? { agentName: agent, ...(await signInWishes(ctx)) } : {}),
58
95
  }, { auth: false }));
59
96
  const { c } = ctx.out;
97
+ const tty = Boolean(ctx.out.stderr.isTTY) && !ctx.out.json;
98
+ ctx.out.note("");
99
+ ctx.out.note(` ${c.bold(String(start.userCode).split("").join(" "))}`);
100
+ ctx.out.note("");
101
+ // A QR code of the link for a phone, when it fits and the terminal can draw it (never in --json or --plain).
102
+ if (tty && !ctx.out.plain) {
103
+ const { qrLines } = await import("../print/qr.mjs");
104
+ const lines = qrLines(start.verificationUriComplete);
105
+ if ((lines[0]?.length ?? 0) + 4 <= ctx.out.columns()) for (const line of lines) ctx.out.note(` ${line}`);
106
+ }
60
107
  ctx.out.note(`Open ${c.bold(start.verificationUri)} and enter ${c.bold(start.userCode)}`);
61
108
  ctx.out.note(c.muted(` or go straight to ${start.verificationUriComplete}`));
62
- ctx.out.note(c.muted(`Waiting for you to approve… (code works for ${Math.round(start.expiresIn / 60)} minutes; Ctrl+C to cancel)`));
109
+ const opened = tty && !noBrowserHere(ctx.env) && !ctx.env.NB_NO_BROWSER ? await openInBrowser(start.verificationUriComplete) : false;
110
+ if (opened) ctx.out.note(c.muted("Opened your browser. Approve only if it shows the same code."));
63
111
  let interval = Number(start.interval ?? 5);
64
112
  const until = Date.now() + Number(start.expiresIn ?? 600) * 1000;
65
- while (Date.now() < until) {
66
- await new Promise((resolve) => setTimeout(resolve, interval * 1000));
67
- const res = /** @type {any} */ (await api.post("/api/v1/device/token", { deviceCode: start.deviceCode }, { auth: false }).catch((/** @type {unknown} */ error) => {
68
- if (error instanceof CliError && error.status === 403) throw new CliError("CANCELLED", "Sign-in was denied in the browser");
69
- if (error instanceof CliError && error.status === 410) throw new CliError("TIMEOUT", "The sign-in code expired before it was approved", { hint: "Run nb login --device again" });
70
- throw error;
71
- }));
72
- if (res.status === "approved") {
73
- if (res.tokenType === "agent") ctx.out.note(c.muted("Signed in as an agent: this token only reaches the workspace you picked."));
74
- return String(res.token);
113
+ const waiting = () => {
114
+ const left = Math.max(0, Math.round((until - Date.now()) / 1000));
115
+ return `Waiting for you to approve in the browser… ${start.userCode} (expires ${String(Math.floor(left / 60)).padStart(2, "0")}:${String(left % 60).padStart(2, "0")})`;
116
+ };
117
+ // On a terminal the countdown updates in place; elsewhere it's printed once.
118
+ const ticker = tty ? setInterval(() => ctx.out.stderr.write(`\r\x1b[2K${c.muted(waiting())}`), 1000) : null;
119
+ if (tty) ctx.out.stderr.write(c.muted(waiting()));
120
+ else ctx.out.note(c.muted(`${waiting()}; Ctrl+C to cancel`));
121
+ try {
122
+ while (Date.now() < until) {
123
+ await new Promise((resolve) => setTimeout(resolve, interval * 1000));
124
+ const res = /** @type {any} */ (await api.post("/api/v1/device/token", { deviceCode: start.deviceCode }, { auth: false }).catch((/** @type {unknown} */ error) => {
125
+ if (error instanceof CliError && error.status === 403) throw new CliError("CANCELLED", "Sign-in was denied in the browser");
126
+ if (error instanceof CliError && error.status === 410) throw new CliError("TIMEOUT", "The sign-in code expired before it was approved", { hint: "Run nb login --device again" });
127
+ throw error;
128
+ }));
129
+ if (res.status === "approved") return String(res.token);
130
+ if (res.status === "slow_down") interval += 5;
131
+ }
132
+ } finally {
133
+ if (ticker) {
134
+ clearInterval(ticker);
135
+ ctx.out.stderr.write("\r\x1b[2K");
75
136
  }
76
- if (res.status === "slow_down") interval += 5;
77
137
  }
78
138
  throw new CliError("TIMEOUT", "The sign-in code expired before it was approved", { hint: "Run nb login --device again" });
79
139
  }
@@ -223,7 +283,9 @@ export async function whoami(ctx) {
223
283
  ctx.out.result("nb.whoami/1", data, (d) => [
224
284
  `${ctx.out.c.brand(ctx.out.sym.brand)} ${safe(d.user.username ? `@${d.user.username}` : d.user.email ?? d.user.id)}${d.user.fullName ? ` · ${safe(d.user.fullName)}` : ""}`,
225
285
  ` server ${new URL(d.origin).host}${d.profile !== "default" ? ` (profile ${d.profile})` : ""}`,
226
- ` token ${d.credential.type ? `${d.credential.type === "agent" ? "agent" : d.credential.type === "pat" ? "personal access" : "device"} · ` : ""}${d.tokenSource === "env" ? "from NETWORKBASE_TOKEN" : `kept in ${storageWords(d.storage)}`} · ${d.credential.scopes.length} permissions${d.credential.workspaceId ? " · one workspace only" : ""}`,
286
+ ` token ${d.credential.type ? `${d.credential.type === "agent" ? "agent" : d.credential.type === "pat" ? "personal access" : "device"} · ` : ""}${d.tokenSource === "env" ? "from NETWORKBASE_TOKEN" : `kept in ${storageWords(d.storage)}`} · ${d.access ? (d.access.allWorkspaces ? "all your workspaces" : `only ${safe(d.access.workspaceTitle ?? "one workspace")}`) : d.credential.workspaceId ? "one workspace only" : `${d.credential.scopes.length} permissions`}`,
287
+ // An agent's access in the approval page's words (report A4, A10 "nb whoami and Settings show the same sentence").
288
+ ...(d.access ? [` access ${safe(d.access.sentence)}`] : []),
227
289
  ` files up to ${Math.round(d.limits.largestFileBytes / 1024 / 1024)} MB each`,
228
290
  ...(ctx.flags.verbose ? [` can ${d.credential.scopes.join(", ")}`] : []),
229
291
  ]);
@@ -29,6 +29,7 @@ const instructions = (w) => [
29
29
  "- Do what the user asks with the tools; don't ask first. Small changes (tasks, subtasks, comments, moving a task, draft pushes) run at once and networkbase_undo reverses them.",
30
30
  "- Push work as drafts unless the user says final. Finishing a task, final files, doc edits and deleting are held by NetworkBase: call the tool, and when it returns needs_confirmation, show the summary and wait for the user's yes.",
31
31
  "- When a tool returns needs_input, ask the user those questions.",
32
+ "- The networkbase server's instructions start with an access card: who you work for, where you may work, what needs their yes, and when access ends. If a tool answers access_requested, tell the person what you asked for; they answer in NetworkBase.",
32
33
  END,
33
34
  ].join("\n");
34
35
 
@@ -78,9 +79,9 @@ function pickAgent(ctx) {
78
79
  export async function setup(ctx) {
79
80
  const { project, agent, key } = pickAgent(ctx);
80
81
  const mode = ctx.flags.token ?? "agent";
81
- if (!["agent", "mine"].includes(mode)) throw usage("--token is agent (its own token, one workspace) or mine (your sign-in)");
82
+ if (!["agent", "mine"].includes(mode)) throw usage("--token is agent (its own sign-in, which you approve) or mine (your sign-in)");
82
83
  const configText = read(agent.config);
83
- // The agent gets its own token, tied to this workspace (report A3.3, A7.8), in a profile of its own.
84
+ // The agent gets its own sign-in (report A3.3, A7.8, A5), in a profile of its own; the person chooses its access.
84
85
  const profile = mode === "agent" ? `agent-${key}` : null;
85
86
  /** @type {Array<{ file: string, write: string, change: string }>} */
86
87
  const changes = [];
@@ -106,10 +107,11 @@ export async function setup(ctx) {
106
107
  const { currentProfile } = await import("../config.mjs");
107
108
  const existing = currentProfile({ flags: { profile, "api-url": ctx.profile.origin }, env: { ...ctx.env, NB_TOKEN: "", NETWORKBASE_TOKEN: "" } });
108
109
  if (!existing.token) {
109
- ctx.out.note(`${agent.name} gets its own sign-in, limited to ${safe(project.title ?? project.slug ?? "this workspace")}. Approve it in your browser:`);
110
- const { deviceLogin, saveToken } = await import("./account.mjs");
110
+ ctx.out.note(`${agent.name} gets its own sign-in. Approve it in your browser; you choose where it works and what it may do.`);
111
+ const { connectedLines, deviceLogin, saveToken } = await import("./account.mjs");
111
112
  const token = await deviceLogin(ctx, AGENT_NAMES[key] ?? agent.name);
112
- await saveToken(ctx, profile, token);
113
+ const me = await saveToken(ctx, profile, token);
114
+ if (me.access) for (const line of connectedLines(ctx, me.access)) ctx.out.note(line);
113
115
  }
114
116
  }
115
117
  for (const c of changes) {
@@ -126,15 +128,58 @@ export async function setup(ctx) {
126
128
  /** Which agents are connected in this folder. @param {string} root @param {NodeJS.ProcessEnv} env */
127
129
  export const agentRows = (root, env) => Object.entries(AGENTS(root, env)).map(([key, a]) => ({ agent: key, name: a.name, server: hasServer(a.kind, read(a.config)), instructions: Boolean(notesRange(read(a.notes))) }));
128
130
 
131
+ /** The person's agent sign-ins with their sentences (report A4 "Afterwards"); empty when signed out. @param {Context} ctx */
132
+ async function agentSignIns(ctx) {
133
+ if (!ctx.profile.token) return [];
134
+ const { tokens } = /** @type {any} */ (await ctx.api.get("/api/v1/tokens").catch(() => ({ tokens: [] })));
135
+ return tokens.filter((/** @type {any} */ t) => t.type === "agent").map((/** @type {any} */ t) => ({ id: t.id, agentName: t.agentName, device: t.name, access: t.access ?? null, lastUsedAt: t.lastUsedAt }));
136
+ }
137
+
129
138
  /** @param {Context} ctx */
130
139
  export async function status(ctx) {
131
140
  const { root } = ctx.requireRoot();
132
141
  const rows = agentRows(root, ctx.env);
133
- ctx.out.result("nb.agent.status/1", { agents: rows }, (d) => ctx.out.table([
134
- { title: "Agent", value: (r) => r.name },
135
- { title: "MCP server", value: (r) => (r.server ? ctx.out.c.success("connected") : ctx.out.c.muted("—")) },
136
- { title: "Instructions", value: (r) => (r.instructions ? "added" : ctx.out.c.muted("—")) },
137
- ], d.agents));
142
+ const signIns = await agentSignIns(ctx);
143
+ ctx.out.result("nb.agent.status/1", { agents: rows, signIns }, (d) => [
144
+ ctx.out.table([
145
+ { title: "Agent", value: (r) => r.name },
146
+ { title: "MCP server", value: (r) => (r.server ? ctx.out.c.success("connected") : ctx.out.c.muted("—")) },
147
+ { title: "Instructions", value: (r) => (r.instructions ? "added" : ctx.out.c.muted("—")) },
148
+ ], d.agents),
149
+ ...(d.signIns.length ? ["", "Signed-in agents:", ...d.signIns.flatMap((/** @type {any} */ s) => [` ${safe(s.agentName ?? "Agent")} on ${safe(s.device)}`, ctx.out.c.muted(` ${safe(s.access ?? "")}`)])] : []),
150
+ ]);
151
+ }
152
+
153
+ const PRESET_FLAGS = /** @type {const} */ ([["full", "full"], ["small", "small"], ["read-only", "read"]]);
154
+
155
+ /**
156
+ * `nb agent access claude --read-only | --small | --full | --workspace <ws> | --all-workspaces` (report A4, A10):
157
+ * opens the agent's Settings page pre-filled. Changing access needs "Verify it's you", which only the browser has.
158
+ * @param {Context} ctx
159
+ */
160
+ export async function access(ctx) {
161
+ const which = ctx.positionals[0];
162
+ const name = AGENT_NAMES[String(which)] ?? which;
163
+ if (!name) throw usage("Which agent? nb agent access claude|codex|cursor [--full|--small|--read-only] [--workspace <ws>|--all-workspaces]");
164
+ const presets = PRESET_FLAGS.filter(([flag]) => ctx.flags[flag]);
165
+ if (presets.length > 1) throw usage("Choose one of --full, --small or --read-only");
166
+ if (ctx.flags.workspace && ctx.flags["all-workspaces"]) throw usage("Choose --workspace or --all-workspaces, not both");
167
+ const signIns = (await agentSignIns(ctx)).filter((/** @type {any} */ s) => String(s.agentName).toLowerCase() === String(name).toLowerCase());
168
+ if (!signIns.length) throw new CliError("NOT_FOUND", `No ${name} sign-in yet`, { hint: `Run nb agent setup ${which}` });
169
+ if (ctx.flags.workspace) await ctx.resolveWorkspace();
170
+ const target = signIns[0];
171
+ const query = new URLSearchParams({
172
+ ...(presets[0] ? { access: presets[0][1] } : {}),
173
+ ...(ctx.flags["all-workspaces"] ? { workspace: "all" } : ctx.flags.workspace ? { workspace: String(ctx.flags.workspace) } : {}),
174
+ }).toString();
175
+ const url = `${ctx.profile.origin}/settings/agents/${target.id}${query ? `?${query}` : ""}`;
176
+ const { openInBrowser } = await import("./misc.mjs");
177
+ const opened = ctx.out.stderr.isTTY && !ctx.out.json && !ctx.env.NB_NO_BROWSER ? await openInBrowser(url) : false;
178
+ ctx.out.result("nb.agent.access/1", { id: target.id, agent: name, url, opened, now: target.access }, (d) => [
179
+ `${d.opened ? "Opened" : "Open"} ${d.url}`,
180
+ ctx.out.c.muted(` Now: ${safe(d.now ?? "")}`),
181
+ ctx.out.c.muted(" Check the choice there and save; it asks you to confirm it's you."),
182
+ ]);
138
183
  }
139
184
 
140
185
  /** @param {Context} ctx */
@@ -4,7 +4,7 @@
4
4
  import crypto from "node:crypto";
5
5
  import readline from "node:readline";
6
6
 
7
- import { HOSTED_EXCLUDED, callTool as runTool, toolList as listTools } from "../mcp/tools.mjs";
7
+ import { HOSTED_EXCLUDED, accessCard, callTool as runTool, readAccess, toolList as listTools } from "../mcp/tools.mjs";
8
8
 
9
9
  /** @typedef {import("../context.mjs").Context} Context */
10
10
 
@@ -37,12 +37,17 @@ const RESOURCES = [
37
37
  /**
38
38
  * One MCP message handler for both servers (report A7.1): `nb mcp` over stdio, and the hosted one over HTTP
39
39
  * (src/app/api/mcp, P6.1). `hosted` leaves out tools that need a local folder and the local undo log.
40
- * @param {{ where: { cwd: string, env: NodeJS.ProcessEnv }, send: (message: any) => void, version: string, hosted?: boolean }} options
40
+ * `access` is who the server works for and what it may do (report A6): the hosted server passes it from its own
41
+ * database; `nb mcp` reads it from /api/v1/me once, on first use.
42
+ * @param {{ where: { cwd: string, env: NodeJS.ProcessEnv }, send: (message: any) => void, version: string, hosted?: boolean, access?: () => Promise<any> }} options
41
43
  */
42
- export function createMcpHandler({ where, send, version, hosted = false }) {
44
+ export function createMcpHandler({ where, send, version, hosted = false, access }) {
43
45
  const cancelled = new Set();
44
46
  const ctx = { version };
45
- const toolList = () => listTools(hosted);
47
+ /** @type {Promise<any> | null} */
48
+ let accessRead = null;
49
+ const getAccess = () => (accessRead ??= (access ? access() : readAccess(where)).catch(() => null));
50
+ const toolList = async () => listTools(hosted, await getAccess());
46
51
  const callTool = (/** @type {string} */ name, /** @type {any} */ args, /** @type {any} */ w) =>
47
52
  hosted && HOSTED_EXCLUDED.has(name)
48
53
  ? Promise.resolve({ isError: true, content: [{ type: "text", text: `${name} needs NetworkBase on your computer (nb mcp); the hosted server can't use local files` }] })
@@ -63,14 +68,14 @@ export function createMcpHandler({ where, send, version, hosted = false }) {
63
68
  protocolVersion: PROTOCOL_VERSIONS.includes(asked) ? asked : PROTOCOL_VERSIONS[0],
64
69
  capabilities: { tools: { listChanged: false }, resources: { listChanged: false }, prompts: { listChanged: false }, logging: {} },
65
70
  serverInfo: { name: "networkbase", title: "NetworkBase", version: ctx.version },
66
- instructions: INSTRUCTIONS,
71
+ instructions: [accessCard(await getAccess()), INSTRUCTIONS].filter(Boolean).join("\n\n"),
67
72
  });
68
73
  }
69
74
  case "ping":
70
75
  case "logging/setLevel":
71
76
  return reply({});
72
77
  case "tools/list":
73
- return reply({ tools: toolList() });
78
+ return reply({ tools: await toolList() });
74
79
  case "tools/call": {
75
80
  if (typeof params?.name !== "string") return fail(-32602, "tools/call needs a tool name");
76
81
  const progressToken = params?._meta?.progressToken;
@@ -47,10 +47,12 @@ const DRY = { "dry-run": { type: "boolean", describe: "Show what would happen, c
47
47
  /** @type {CommandSpec[]} */
48
48
  export const COMMANDS = [
49
49
  // Account and setup
50
- { group: "Account and setup", name: "login", summary: "Sign in (browser, a code, or a token from stdin)", usage: "nb login [--device] [--agent name] [--with-token]", module: "account", fn: "login",
50
+ { group: "Account and setup", name: "login", summary: "Sign in (browser, a code, or a token from stdin)", usage: "nb login [--device] [--agent name [--access full|small|read] [--workspace ws|--all-workspaces]] [--with-token]", module: "account", fn: "login",
51
51
  flags: { "with-token": { type: "boolean", describe: "Read a token from stdin (CI, scripts)" }, device: { type: "boolean", describe: "Sign in with a code you approve on another device (automatic over SSH)" },
52
- agent: { type: "string", describe: "Sign in an AI agent; you pick the one workspace it may use", valueName: "name" } },
53
- examples: ["nb login", "nb login --device", "nb login --device --agent \"Claude Code\"", "echo $NB_TOKEN | nb login --with-token"], exit: [0, 3, 130] },
52
+ agent: { type: "string", describe: "Sign in an AI agent; you approve where it works and what it may do", valueName: "name" },
53
+ access: { type: "string", describe: "What the agent asks for: full, small or read (the page starts there)", valueName: "level" },
54
+ "all-workspaces": { type: "boolean", describe: "The agent asks for all your workspaces" } },
55
+ examples: ["nb login", "nb login --device", "nb login --device --agent \"Claude Code\"", "nb login --device --agent \"Claude Code\" --access read --all-workspaces", "echo $NB_TOKEN | nb login --with-token"], exit: [0, 3, 130] },
54
56
  { group: "Account and setup", name: "logout", summary: "Revoke this device's token and sign out", usage: "nb logout [--all]", module: "account", fn: "logout",
55
57
  flags: { all: { type: "boolean", describe: "Sign out every device and agent (opens Settings to confirm it's you)" } } },
56
58
  { group: "Account and setup", name: "token list", summary: "Your signed-in devices, agents and personal tokens", usage: "nb token list", module: "account", fn: "tokenList" },
@@ -174,9 +176,13 @@ export const COMMANDS = [
174
176
  { group: "Agents", name: "ask list", summary: "Questions agents asked you", usage: "nb ask list", module: "ask", fn: "askList" },
175
177
  { group: "Agents", name: "ask answer", summary: "Answer a question an agent asked you", usage: "nb ask answer <id> <option number or text>", module: "ask", fn: "askAnswer" },
176
178
  { group: "Agents", name: "agent setup", summary: "Connect Claude Code, Codex or Cursor to this workspace (asks first)", usage: "nb agent setup claude|codex|cursor [--token agent|mine]", module: "agent", fn: "setup",
177
- flags: { token: { type: "string", describe: "agent (default): its own sign-in for this workspace only; mine: use yours", valueName: "kind" } },
179
+ flags: { token: { type: "string", describe: "agent (default): its own sign-in, which you approve; mine: use yours", valueName: "kind" } },
178
180
  examples: ["nb agent setup claude", "nb agent setup codex"] },
179
- { group: "Agents", name: "agent status", summary: "Which agents are connected here", usage: "nb agent status", module: "agent", fn: "status" },
181
+ { group: "Agents", name: "agent status", summary: "Which agents are connected here, and what each may do", usage: "nb agent status", module: "agent", fn: "status" },
182
+ { group: "Agents", name: "agent access", summary: "Change what an agent may do (opens its Settings page)", usage: "nb agent access claude|codex|cursor [--full|--small|--read-only] [--workspace ws|--all-workspaces]", module: "agent", fn: "access",
183
+ flags: { full: { type: "boolean", describe: "Full help: asks before big changes" }, small: { type: "boolean", describe: "Small changes only" }, "read-only": { type: "boolean", describe: "Read only" },
184
+ "all-workspaces": { type: "boolean", describe: "All your workspaces" } },
185
+ examples: ["nb agent access claude --read-only", "nb agent access claude --workspace design-lab --small"] },
180
186
  { group: "Agents", name: "agent remove", summary: "Disconnect an agent and remove its NetworkBase notes", usage: "nb agent remove claude|codex|cursor", module: "agent", fn: "remove" },
181
187
  { group: "Agents", name: "mcp", summary: "MCP server for Claude Code, Codex and Cursor (stdio)", usage: "nb mcp", module: "mcp", fn: "serve",
182
188
  examples: ["claude mcp add networkbase -- npx -y @networkbase/cli@2 mcp"] },
package/lib/errors.mjs CHANGED
@@ -22,6 +22,8 @@ const EXIT_BY_CODE = {
22
22
  NOT_SIGNED_IN: EXIT.auth,
23
23
  FORBIDDEN: EXIT.auth,
24
24
  SCOPE_MISSING: EXIT.auth,
25
+ ACCESS_REQUESTED: EXIT.needsInput,
26
+ ACCESS_DENIED_BY_PERSON: EXIT.auth,
25
27
  WORKSPACE_NOT_ALLOWED: EXIT.auth,
26
28
  AGENTS_PAUSED: EXIT.auth,
27
29
  AGENT_NOT_ALLOWED: EXIT.auth,
package/lib/mcp/tools.mjs CHANGED
@@ -300,10 +300,58 @@ export async function callTool(name, args = {}, where) {
300
300
  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
301
  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
302
  }
303
+ // A missing permission was asked for, or refused, by the person (report A5 "Asking for more", A6 #3).
304
+ if (error instanceof CliError && (error.code === "ACCESS_REQUESTED" || error.code === "ACCESS_DENIED_BY_PERSON")) {
305
+ const details = /** @type {any} */ (error.details) ?? {};
306
+ const what = SCOPE_WORDS[details.scope] ?? details.scope ?? "do that";
307
+ if (error.code === "ACCESS_REQUESTED") {
308
+ return {
309
+ 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.` }],
310
+ structuredContent: { status: "access_requested", scope: details.scope ?? null, requestId: details.requestId ?? null },
311
+ };
312
+ }
313
+ return {
314
+ isError: true,
315
+ 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.` }],
316
+ structuredContent: { status: "access_denied", scope: details.scope ?? null, retryAfter: details.retryAfter ?? null },
317
+ };
318
+ }
303
319
  return errorResult(error);
304
320
  }
305
321
  }
306
322
 
323
+ /** Permissions in the words the approval page uses (report A2). */
324
+ const SCOPE_WORDS = /** @type {Record<string, string>} */ ({ "task:complete": "finish tasks", "file:final": "change final files", "doc:write": "edit docs", "task:review": "approve or return reviews" });
325
+ /** Tools whose main job needs a permission an agent preset may leave out. */
326
+ const NEEDS_SCOPE = /** @type {Record<string, string>} */ ({ networkbase_task_done: "task:complete", networkbase_doc_update: "doc:write" });
327
+
328
+ /**
329
+ * Who this MCP server works for and what it may do (report A6 #1), read from /api/v1/me via nb whoami. Null when
330
+ * that can't be read (offline, signed out): the server still starts, with no card.
331
+ * @param {{ cwd: string, env: NodeJS.ProcessEnv }} where
332
+ */
333
+ export async function readAccess(where) {
334
+ try {
335
+ const r = await executor(where, {})("whoami");
336
+ return { user: r.data.user, access: r.data.access ?? null, scopes: r.data.credential?.scopes ?? [] };
337
+ } catch {
338
+ return null;
339
+ }
340
+ }
341
+
342
+ /** The access card at the top of the server's instructions (report A6 #1). @param {any} a */
343
+ export function accessCard(a) {
344
+ if (!a?.user) return "";
345
+ const who = `${a.user.fullName ?? a.user.username ?? a.user.email ?? "the person"}${a.user.username ? ` (@${a.user.username})` : ""}`;
346
+ 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.`;
347
+ return [
348
+ `You are working for ${who} on NetworkBase.`,
349
+ `What they approved: "${a.access.sentence}"`,
350
+ "Whatever the access, finishing tasks, final files, doc edits and deleting wait for their yes (needs_confirmation).",
351
+ "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.",
352
+ ].join("\n");
353
+ }
354
+
307
355
  /** @param {string} name @param {any} args @param {string} summary @param {string | undefined} preview */
308
356
  function confirmationResult(name, args, summary, preview) {
309
357
  const confirmToken = issueConfirmation(name, args);
@@ -322,13 +370,17 @@ function errorResult(error) {
322
370
  /** Tools that read or write files in a linked folder, or the local undo log: only `nb mcp` on your computer has them. */
323
371
  export const HOSTED_EXCLUDED = new Set(["networkbase_status", "networkbase_file_push", "networkbase_file_pull", "networkbase_undo"]);
324
372
 
325
- /** tools/list entries, with tier hints for clients (A7.3). @param {boolean} [hosted] */
373
+ /**
374
+ * tools/list entries, with tier hints for clients (A7.3). With an agent's access (A6 #2), Read only lists only the
375
+ * tools that read, and tools that need the person first say so at the start of their description.
376
+ * @param {boolean} [hosted] @param {any} [access] from readAccess
377
+ */
326
378
  // Every tool that writes takes confirmToken: the server can hold any write for a yes (someone else's task, a file as
327
379
  // 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) => ({
380
+ 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
381
  name: t.name,
330
382
  title: t.title,
331
- description: t.description,
383
+ description: describeFor(t, access),
332
384
  inputSchema: {
333
385
  type: "object",
334
386
  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 +388,10 @@ export const toolList = (hosted = false) => TOOLS.filter((t) => !hosted || !HOST
336
388
  },
337
389
  annotations: { title: t.title, readOnlyHint: t.tier === "read", destructiveHint: t.tier === "yes", openWorldHint: false },
338
390
  }));
391
+
392
+ /** @param {Tool} t @param {any} access */
393
+ function describeFor(t, access) {
394
+ const scope = NEEDS_SCOPE[t.name];
395
+ 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}`;
396
+ return t.tier === "yes" && access?.access ? `Needs the person's yes: ${t.description}` : t.description;
397
+ }
@@ -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
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@networkbase/cli",
3
- "version": "2.0.3",
3
+ "version": "2.0.4",
4
4
  "description": "NetworkBase in your terminal: sync files, work on tasks, edit docs",
5
5
  "type": "module",
6
6
  "homepage": "https://networkbase.in",