@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/bin/nb.mjs +6 -1
- package/lib/api.mjs +3 -1
- package/lib/args.mjs +37 -17
- package/lib/commands/account.mjs +93 -20
- package/lib/commands/agent.mjs +55 -10
- package/lib/commands/browse.mjs +19 -2
- package/lib/commands/extras.mjs +1 -1
- package/lib/commands/files.mjs +73 -5
- package/lib/commands/inbox.mjs +33 -1
- package/lib/commands/link.mjs +33 -1
- package/lib/commands/mcp.mjs +11 -6
- package/lib/commands/misc.mjs +72 -13
- package/lib/commands/table.mjs +47 -14
- package/lib/commands/tasks.mjs +162 -20
- package/lib/commands/undo.mjs +1 -1
- package/lib/commands/work.mjs +53 -16
- package/lib/config.mjs +1 -1
- package/lib/context.mjs +7 -0
- package/lib/dates.mjs +47 -0
- package/lib/error-fixes.mjs +60 -0
- package/lib/errors.mjs +2 -0
- package/lib/mcp/tools.mjs +101 -23
- package/lib/print/notices.mjs +6 -0
- package/lib/print/out.mjs +4 -2
- package/lib/print/qr.mjs +251 -0
- package/lib/sync/queue.mjs +1 -1
- package/package.json +1 -1
package/bin/nb.mjs
CHANGED
|
@@ -21,6 +21,8 @@ const restoreCursor = () => { if (process.stderr.isTTY) process.stderr.write("\x
|
|
|
21
21
|
process.on("exit", restoreCursor);
|
|
22
22
|
for (const signal of /** @type {const} */ (["SIGINT", "SIGTERM"])) process.on(signal, () => { restoreCursor(); process.exit(EXIT.cancelled); });
|
|
23
23
|
|
|
24
|
+
/** The command being run, so a usage error can point at its help (C5). @type {string | null} */
|
|
25
|
+
let commandName = null;
|
|
24
26
|
try {
|
|
25
27
|
if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
|
|
26
28
|
const { VERSION } = await import("../lib/context.mjs");
|
|
@@ -28,6 +30,7 @@ try {
|
|
|
28
30
|
process.exit(EXIT.ok);
|
|
29
31
|
}
|
|
30
32
|
const { spec, rest, alias } = resolveCommand(argv);
|
|
33
|
+
commandName = spec?.name ?? null;
|
|
31
34
|
if (!spec) {
|
|
32
35
|
if (argv.includes("--json")) {
|
|
33
36
|
const { helpData } = await import("../lib/args.mjs");
|
|
@@ -45,7 +48,7 @@ try {
|
|
|
45
48
|
const ctx = createContext({ flags: spec.name === "prompt" ? { ...flags, quiet: true } : flags, positionals });
|
|
46
49
|
if (alias) {
|
|
47
50
|
const { remindOnce } = await import("../lib/print/remind.mjs");
|
|
48
|
-
remindOnce(ctx, `alias:${alias.from}`, `nb ${alias.from} is now nb ${alias.to} (the old name works until 3.0)`);
|
|
51
|
+
remindOnce(ctx, `alias:${alias.from}`, alias.shortcut ? `nb ${alias.from} is short for nb ${alias.to}` : `nb ${alias.from} is now nb ${alias.to} (the old name works until 3.0)`);
|
|
49
52
|
}
|
|
50
53
|
// login is what signs you in, so it can't look a workspace up first; an agent's workspace is picked on the approval page.
|
|
51
54
|
if (spec.name !== "login") await ctx.resolveWorkspace();
|
|
@@ -67,6 +70,8 @@ try {
|
|
|
67
70
|
await (await import("../lib/print/notices.mjs")).afterCommand(ctx);
|
|
68
71
|
} catch (error) {
|
|
69
72
|
const cliError = toCliError(error);
|
|
73
|
+
// A usage error's next step is the command's own help (C5).
|
|
74
|
+
if (!cliError.hint && cliError.exitCode === EXIT.usage && commandName) cliError.hint = `See nb ${commandName} --help`;
|
|
70
75
|
early.error(cliError);
|
|
71
76
|
if (cliError.code === "INTERNAL" && process.env.NB_DEBUG === "1" && error instanceof Error) process.stderr.write(`${error.stack}\n`);
|
|
72
77
|
process.exitCode = cliError.exitCode;
|
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: "
|
|
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>",
|
package/lib/args.mjs
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// flags and commands are errors with a "did you mean", never silently ignored (finding 81).
|
|
3
3
|
import { parseArgs } from "node:util";
|
|
4
4
|
|
|
5
|
-
import { ALIASES, COMMANDS, GLOBAL_FLAGS, REMOVED } from "./commands/table.mjs";
|
|
5
|
+
import { ALIASES, COMMANDS, GLOBAL_FLAGS, REMOVED, SHORTCUTS } from "./commands/table.mjs";
|
|
6
6
|
import { CliError, usage } from "./errors.mjs";
|
|
7
7
|
|
|
8
8
|
/** @typedef {import("./commands/table.mjs").CommandSpec} CommandSpec */
|
|
@@ -33,23 +33,30 @@ const TASK_REF = /^(#?\d+|T-\d+|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-
|
|
|
33
33
|
/**
|
|
34
34
|
* Finds the command in argv. `nb task 4` is a shortcut for `nb task view 4`.
|
|
35
35
|
* @param {string[]} argv
|
|
36
|
-
* @returns {{ spec: CommandSpec | null, rest: string[], alias: { from: string, to: string } | null }}
|
|
36
|
+
* @returns {{ spec: CommandSpec | null, rest: string[], alias: { from: string, to: string, shortcut?: boolean } | null }}
|
|
37
37
|
*/
|
|
38
38
|
export function resolveCommand(argv) {
|
|
39
|
+
// Help groups these under "Classes", so nb class … is nb assignment … (C16 #10).
|
|
40
|
+
if (argv[0] === "class") argv = ["assignment", ...argv.slice(1)];
|
|
39
41
|
/** @type {string[]} */
|
|
40
42
|
const words = [];
|
|
41
43
|
for (const token of argv) {
|
|
42
44
|
if (token.startsWith("-")) break;
|
|
43
45
|
words.push(token);
|
|
44
46
|
}
|
|
47
|
+
// `nb` on its own is the home screen (C1); `nb --help` stays the help page.
|
|
48
|
+
if (argv.length === 0) return { spec: /** @type {CommandSpec} */ (COMMANDS.find((c) => c.name === "home")), rest: [], alias: null };
|
|
45
49
|
if (words.length === 0) return { spec: null, rest: argv, alias: null };
|
|
46
50
|
for (let n = Math.min(3, words.length); n >= 1; n--) {
|
|
47
51
|
const name = words.slice(0, n).join(" ");
|
|
48
52
|
if (name in REMOVED) throw new CliError("USAGE", /** @type {Record<string, string>} */ (REMOVED)[name]);
|
|
49
|
-
const
|
|
53
|
+
const short = /** @type {Record<string, string>} */ (SHORTCUTS);
|
|
54
|
+
const target = short[short[name] ?? ""] ?? short[name] ?? /** @type {Record<string, string>} */ (ALIASES)[name] ?? name;
|
|
50
55
|
const spec = COMMANDS.find((c) => c.name === target);
|
|
51
|
-
if (spec) return { spec, rest: argv.slice(n), alias: target !== name ? { from: name, to: target } : null };
|
|
56
|
+
if (spec) return { spec, rest: argv.slice(n), alias: target !== name ? { from: name, to: target, ...(short[name] ? { shortcut: true } : {}) } : null };
|
|
52
57
|
}
|
|
58
|
+
// `nb comment "looks good"` comments on the current task (C8).
|
|
59
|
+
if (words[0] === "comment" && words[1]) return { spec: /** @type {CommandSpec} */ (COMMANDS.find((c) => c.name === "comment add")), rest: argv.slice(1), alias: null };
|
|
53
60
|
if (words[0] === "task" && words[1] && TASK_REF.test(words[1])) {
|
|
54
61
|
return { spec: /** @type {CommandSpec} */ (COMMANDS.find((c) => c.name === "task view")), rest: argv.slice(1), alias: null };
|
|
55
62
|
}
|
|
@@ -115,24 +122,37 @@ const wrap = (text, width) => text.split(" ").reduce((/** @type {string[]} */ ou
|
|
|
115
122
|
}, []);
|
|
116
123
|
|
|
117
124
|
/** Overview help: every command by group, summaries wrapped to the terminal. @param {number} [columns] */
|
|
125
|
+
/** The commands most people use, shown first in nb help (C1). */
|
|
126
|
+
const MOST_USED = ["init", "status", "pull", "push", "next", "task list", "task start", "task done", "task create", "inbox"];
|
|
127
|
+
|
|
128
|
+
/** A short help page (C1): the 10 most-used commands, then the rest by area, names only. */
|
|
118
129
|
export function overviewHelp(columns = 80) {
|
|
130
|
+
const width = columns || 80;
|
|
131
|
+
const top = MOST_USED.map((name) => /** @type {CommandSpec} */ (COMMANDS.find((c) => c.name === name)));
|
|
132
|
+
const w = Math.max(...top.map((c) => c.name.length));
|
|
133
|
+
const lines = ["NetworkBase CLI", "", "Usage", " nb <command> [flags]", "", "Most used"];
|
|
134
|
+
for (const c of top) {
|
|
135
|
+
const [first = "", ...rest] = wrap(c.summary, Math.max(16, width - w - 4));
|
|
136
|
+
lines.push(` ${c.name.padEnd(w)} ${first}`, ...rest.map((l) => ` ${" ".repeat(w)} ${l}`));
|
|
137
|
+
}
|
|
138
|
+
lines.push("", "More");
|
|
119
139
|
const groups = new Map();
|
|
120
140
|
for (const c of COMMANDS) {
|
|
121
|
-
if (c.hidden) continue;
|
|
141
|
+
if (c.hidden || MOST_USED.includes(c.name)) continue;
|
|
122
142
|
if (!groups.has(c.group)) groups.set(c.group, []);
|
|
123
|
-
groups.get(c.group).push(c);
|
|
143
|
+
groups.get(c.group).push(c.name);
|
|
124
144
|
}
|
|
125
|
-
const
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
}
|
|
133
|
-
lines.push("");
|
|
145
|
+
for (const [group, names] of groups) {
|
|
146
|
+
// Wrapped between names, never inside one ("inbox / open").
|
|
147
|
+
const rows = names.reduce((/** @type {string[]} */ out, /** @type {string} */ name) => {
|
|
148
|
+
const last = out.at(-1);
|
|
149
|
+
if (last !== undefined && last.length + name.length + 2 <= Math.max(16, width - 5)) out[out.length - 1] = `${last}, ${name}`;
|
|
150
|
+
else out.push(name);
|
|
151
|
+
return out;
|
|
152
|
+
}, []);
|
|
153
|
+
lines.push(` ${group}`, ...rows.map((r, i) => ` ${r}${i < rows.length - 1 ? "," : ""}`));
|
|
134
154
|
}
|
|
135
|
-
lines.push(...wrap("Every command takes --json, --quiet, --plain and --help.",
|
|
155
|
+
lines.push("", ...wrap("nb help <command> explains one. Every command takes --json, --quiet, --plain and --help.", width), "Docs: https://networkbase.in/docs/cli");
|
|
136
156
|
return lines.join("\n");
|
|
137
157
|
}
|
|
138
158
|
|
|
@@ -141,6 +161,6 @@ export function helpData() {
|
|
|
141
161
|
return {
|
|
142
162
|
commands: COMMANDS.filter((c) => !c.hidden).map((c) => ({ name: c.name, summary: c.summary, usage: c.usage, flags: Object.fromEntries(Object.entries(c.flags ?? {}).filter(([, f]) => !f.hidden)), examples: c.examples ?? [], exitCodes: c.exit ?? [0, 1] })),
|
|
143
163
|
globalFlags: GLOBAL_FLAGS,
|
|
144
|
-
aliases: ALIASES,
|
|
164
|
+
aliases: { ...ALIASES, ...SHORTCUTS },
|
|
145
165
|
};
|
|
146
166
|
}
|
package/lib/commands/account.mjs
CHANGED
|
@@ -15,6 +15,14 @@ import { openInBrowser } from "./misc.mjs";
|
|
|
15
15
|
const TOKEN_SHAPE = /^nb_(dev|pat|agt)_[A-Za-z0-9_-]{16,}$/;
|
|
16
16
|
const LOGIN_TIMEOUT_MS = 5 * 60 * 1000;
|
|
17
17
|
|
|
18
|
+
/** @param {Context} ctx @param {string} token */
|
|
19
|
+
/**
|
|
20
|
+
* This computer's own sign-in, sent with a new sign-in so the server closes it (C6): one entry per computer.
|
|
21
|
+
* Only a saved device token; never an agent's, an environment token, or a personal token.
|
|
22
|
+
* @param {Context} ctx
|
|
23
|
+
*/
|
|
24
|
+
const renewing = (ctx) => (!ctx.flags.agent && ctx.profile.profile?.source === "file" && String(ctx.profile.token ?? "").startsWith("nb_dev_") ? { renew: String(ctx.profile.token) } : {});
|
|
25
|
+
|
|
18
26
|
/** @param {Context} ctx @param {string} token */
|
|
19
27
|
async function whoIs(ctx, token) {
|
|
20
28
|
const api = createApi({ origin: ctx.profile.origin, token, version: ctx.version });
|
|
@@ -28,20 +36,58 @@ export async function saveToken(ctx, profileName, token) {
|
|
|
28
36
|
return me;
|
|
29
37
|
}
|
|
30
38
|
|
|
39
|
+
/** The access line (report A4): "Claude Code connected · all workspaces · asks before big changes · until 11 Dec". @param {any} access */
|
|
40
|
+
export function accessLine(access) {
|
|
41
|
+
const where = access.allWorkspaces ? "all workspaces" : `only ${access.workspaceTitle ?? "one workspace"}`;
|
|
42
|
+
const what = { full: "asks before big changes", small: "small changes only", read: "read only", custom: "custom access" }[/** @type {string} */ (access.preset)] ?? access.preset;
|
|
43
|
+
const until = new Date(access.expiresAt).toLocaleDateString("en-GB", { day: "numeric", month: "short" });
|
|
44
|
+
return `${access.agentName} connected · ${where} · ${what} · until ${until}`;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** What to show once an agent is approved: the access line and something to try. @param {Context} ctx @param {any} access */
|
|
48
|
+
export function connectedLines(ctx, access) {
|
|
49
|
+
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?"`)];
|
|
50
|
+
}
|
|
51
|
+
|
|
31
52
|
/** @param {Context} ctx @param {string} token @param {string} method */
|
|
32
53
|
async function finish(ctx, token, method) {
|
|
33
54
|
const me = await whoIs(ctx, token);
|
|
34
|
-
|
|
35
|
-
ctx.
|
|
36
|
-
|
|
55
|
+
// The end date is kept so nb can warn 7 days before (C6).
|
|
56
|
+
saveProfile(ctx.profile.name, { origin: ctx.profile.origin, token, user: { id: me.user.id, username: me.user.username, email: me.user.email }, ...(me.credential?.expiresAt ? { expiresAt: me.credential.expiresAt } : {}) }, ctx.env);
|
|
57
|
+
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) =>
|
|
58
|
+
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
59
|
}
|
|
38
60
|
|
|
39
61
|
/** 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
62
|
const noBrowserHere = (env) => Boolean(env.SSH_CONNECTION || env.SSH_TTY || (process.platform === "linux" && !env.DISPLAY && !env.WAYLAND_DISPLAY));
|
|
63
|
+
const UUID_SHAPE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
41
64
|
|
|
42
65
|
/**
|
|
43
|
-
*
|
|
44
|
-
*
|
|
66
|
+
* What the sign-in asks for (report A5): --access full|small|read, --workspace <slug|id>, --all-workspaces. The
|
|
67
|
+
* approval page pre-fills it; the person can change it. A workspace that can't be looked up before signing in is
|
|
68
|
+
* left for the page, never an error (a signed-out login must not stop on --workspace).
|
|
69
|
+
* @param {Context} ctx
|
|
70
|
+
*/
|
|
71
|
+
async function signInWishes(ctx) {
|
|
72
|
+
const access = ctx.flags.access;
|
|
73
|
+
if (access !== undefined && !["full", "small", "read"].includes(String(access))) throw usage("--access takes full, small or read");
|
|
74
|
+
/** @type {string | null} */
|
|
75
|
+
let workspace = null;
|
|
76
|
+
const given = typeof ctx.flags.workspace === "string" ? ctx.flags.workspace.trim() : "";
|
|
77
|
+
if (ctx.flags["all-workspaces"]) workspace = "all";
|
|
78
|
+
else if (given && UUID_SHAPE.test(given)) workspace = given;
|
|
79
|
+
else if (given) {
|
|
80
|
+
const p = ctx.project;
|
|
81
|
+
if (p?.workspaceId && [p.slug, p.title].some((v) => v && v.toLowerCase() === given.toLowerCase())) workspace = p.workspaceId;
|
|
82
|
+
else if (ctx.profile.token) workspace = await ctx.resolveWorkspace().then(() => (UUID_SHAPE.test(String(ctx.flags.workspace)) ? String(ctx.flags.workspace) : null), () => null);
|
|
83
|
+
if (!workspace) ctx.out.note(ctx.out.c.muted(`Choose ${safe(given)} on the approval page.`));
|
|
84
|
+
}
|
|
85
|
+
return { ...(access ? { requestedAccess: String(access) } : {}), ...(workspace ? { requestedWorkspace: workspace } : {}) };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Sign-in with a code (report A3.1, A4): the server gives a code; the browser opens at the approval page by itself
|
|
90
|
+
* where it can, a QR code covers a phone, and this terminal polls until the person answers (10 minutes at most).
|
|
45
91
|
* @param {Context} ctx
|
|
46
92
|
* @returns {Promise<string>}
|
|
47
93
|
*/
|
|
@@ -54,26 +100,49 @@ export async function deviceLogin(ctx, agentName = /** @type {string | null} */
|
|
|
54
100
|
clientVersion: ctx.version,
|
|
55
101
|
platform: `${process.platform} ${process.arch}`,
|
|
56
102
|
type: agent ? "agent" : "device",
|
|
57
|
-
...(agent ? { agentName: agent } : {}),
|
|
103
|
+
...(agent ? { agentName: agent, ...(await signInWishes(ctx)) } : {}),
|
|
58
104
|
}, { auth: false }));
|
|
59
105
|
const { c } = ctx.out;
|
|
106
|
+
const tty = Boolean(ctx.out.stderr.isTTY) && !ctx.out.json;
|
|
107
|
+
ctx.out.note("");
|
|
108
|
+
ctx.out.note(` ${c.bold(String(start.userCode).split("").join(" "))}`);
|
|
109
|
+
ctx.out.note("");
|
|
110
|
+
// A QR code of the link for a phone, when it fits and the terminal can draw it (never in --json or --plain).
|
|
111
|
+
if (tty && !ctx.out.plain) {
|
|
112
|
+
const { qrLines } = await import("../print/qr.mjs");
|
|
113
|
+
const lines = qrLines(start.verificationUriComplete);
|
|
114
|
+
if ((lines[0]?.length ?? 0) + 4 <= ctx.out.columns()) for (const line of lines) ctx.out.note(` ${line}`);
|
|
115
|
+
}
|
|
60
116
|
ctx.out.note(`Open ${c.bold(start.verificationUri)} and enter ${c.bold(start.userCode)}`);
|
|
61
117
|
ctx.out.note(c.muted(` or go straight to ${start.verificationUriComplete}`));
|
|
62
|
-
|
|
118
|
+
const opened = tty && !noBrowserHere(ctx.env) && !ctx.env.NB_NO_BROWSER ? await openInBrowser(start.verificationUriComplete) : false;
|
|
119
|
+
if (opened) ctx.out.note(c.muted("Opened your browser. Approve only if it shows the same code."));
|
|
63
120
|
let interval = Number(start.interval ?? 5);
|
|
64
121
|
const until = Date.now() + Number(start.expiresIn ?? 600) * 1000;
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
122
|
+
const waiting = () => {
|
|
123
|
+
const left = Math.max(0, Math.round((until - Date.now()) / 1000));
|
|
124
|
+
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")})`;
|
|
125
|
+
};
|
|
126
|
+
// On a terminal the countdown updates in place; elsewhere it's printed once.
|
|
127
|
+
const ticker = tty ? setInterval(() => ctx.out.stderr.write(`\r\x1b[2K${c.muted(waiting())}`), 1000) : null;
|
|
128
|
+
if (tty) ctx.out.stderr.write(c.muted(waiting()));
|
|
129
|
+
else ctx.out.note(c.muted(`${waiting()}; Ctrl+C to cancel`));
|
|
130
|
+
try {
|
|
131
|
+
while (Date.now() < until) {
|
|
132
|
+
await new Promise((resolve) => setTimeout(resolve, interval * 1000));
|
|
133
|
+
const res = /** @type {any} */ (await api.post("/api/v1/device/token", { deviceCode: start.deviceCode, ...renewing(ctx) }, { auth: false }).catch((/** @type {unknown} */ error) => {
|
|
134
|
+
if (error instanceof CliError && error.status === 403) throw new CliError("CANCELLED", "Sign-in was denied in the browser");
|
|
135
|
+
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" });
|
|
136
|
+
throw error;
|
|
137
|
+
}));
|
|
138
|
+
if (res.status === "approved") return String(res.token);
|
|
139
|
+
if (res.status === "slow_down") interval += 5;
|
|
140
|
+
}
|
|
141
|
+
} finally {
|
|
142
|
+
if (ticker) {
|
|
143
|
+
clearInterval(ticker);
|
|
144
|
+
ctx.out.stderr.write("\r\x1b[2K");
|
|
75
145
|
}
|
|
76
|
-
if (res.status === "slow_down") interval += 5;
|
|
77
146
|
}
|
|
78
147
|
throw new CliError("TIMEOUT", "The sign-in code expired before it was approved", { hint: "Run nb login --device again" });
|
|
79
148
|
}
|
|
@@ -145,7 +214,7 @@ function browserLogin(ctx) {
|
|
|
145
214
|
if (!code || url.searchParams.get("state") !== state) return reply(400, "Not this sign-in", "This window doesn't match the sign-in your terminal started.");
|
|
146
215
|
try {
|
|
147
216
|
const api = createApi({ origin, token: null, version: ctx.version });
|
|
148
|
-
const exchanged = /** @type {any} */ (await api.post("/api/v1/extension/auth-code", { code, state, codeVerifier: verifier }, { auth: false }));
|
|
217
|
+
const exchanged = /** @type {any} */ (await api.post("/api/v1/extension/auth-code", { code, state, codeVerifier: verifier, ...renewing(ctx) }, { auth: false }));
|
|
149
218
|
reply(200, "Signed in", "Your terminal is signed in. You can close this window.");
|
|
150
219
|
done(null, exchanged.token);
|
|
151
220
|
} catch (error) {
|
|
@@ -223,7 +292,11 @@ export async function whoami(ctx) {
|
|
|
223
292
|
ctx.out.result("nb.whoami/1", data, (d) => [
|
|
224
293
|
`${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
294
|
` 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.
|
|
295
|
+
` 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.type === "device" ? "all your workspaces" : `${d.credential.scopes.length} permissions`}`,
|
|
296
|
+
// An agent's access in the approval page's words (report A4, A10 "nb whoami and Settings show the same sentence").
|
|
297
|
+
...(d.access ? [` access ${safe(d.access.sentence)}`] : []),
|
|
298
|
+
// Your own sign-in in a sentence too (report C16 #7).
|
|
299
|
+
...(!d.access && d.credential.type === "device" ? [` access Your own sign-in: does what you can, in all your workspaces${d.credential.expiresAt ? `, until ${new Date(d.credential.expiresAt).toLocaleDateString("en-GB", { day: "numeric", month: "short", year: "numeric" })}` : ""}.`] : []),
|
|
227
300
|
` files up to ${Math.round(d.limits.largestFileBytes / 1024 / 1024)} MB each`,
|
|
228
301
|
...(ctx.flags.verbose ? [` can ${d.credential.scopes.join(", ")}`] : []),
|
|
229
302
|
]);
|
package/lib/commands/agent.mjs
CHANGED
|
@@ -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
|
|
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
|
|
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
|
|
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
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
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 */
|
package/lib/commands/browse.mjs
CHANGED
|
@@ -98,8 +98,25 @@ export async function fileHistory(ctx) {
|
|
|
98
98
|
if (!p) throw usage("nb file history <path>");
|
|
99
99
|
const node = await nodeOf(ctx, p);
|
|
100
100
|
const res = /** @type {any} */ (await ctx.api.get("/api/v1/extension/file-history", { query: { projectId: ctx.requireWorkspace(), nodeId: node.nodeId ?? node.id } }));
|
|
101
|
-
|
|
102
|
-
|
|
101
|
+
const { c } = ctx.out;
|
|
102
|
+
// Which version is active and what each was based on (C3), so "going back" reads plainly.
|
|
103
|
+
ctx.out.result("nb.file.history/1", { path: remote(p), activeVersion: res.activeVersion ?? null, versions: res.versions }, (d) => [
|
|
104
|
+
...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)}` : ""}`),
|
|
105
|
+
...(d.versions.length > 1 ? ["", c.muted(` Go back: nb file use ${safe(d.path.slice(1))} v<n>`)] : []),
|
|
106
|
+
]);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** `nb file use <file> v1` (C3): the app's "Use this version"; the next save is based on it. @param {Context} ctx */
|
|
110
|
+
export async function fileUse(ctx) {
|
|
111
|
+
const [p, raw] = ctx.positionals;
|
|
112
|
+
const version = Number(String(raw ?? "").replace(/^v/i, ""));
|
|
113
|
+
if (!p || !Number.isInteger(version) || version < 1) throw usage("nb file use <path> v<n>", "See the versions: nb file history <path>");
|
|
114
|
+
const node = await nodeOf(ctx, p);
|
|
115
|
+
const res = /** @type {any} */ (await ctx.api.post("/api/v1/extension/file-history", { projectId: ctx.requireWorkspace(), nodeId: node.nodeId ?? node.id, version }));
|
|
116
|
+
ctx.out.result("nb.file.use/1", { path: remote(p), activeVersion: res.activeVersion, previousVersion: res.previousVersion }, (d) => [
|
|
117
|
+
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`,
|
|
118
|
+
ctx.out.c.muted(` nb pull gets it here · nb undo puts v${d.previousVersion} back`),
|
|
119
|
+
]);
|
|
103
120
|
}
|
|
104
121
|
|
|
105
122
|
/** @param {Context} ctx @param {"move" | "rename" | "trash"} kind */
|
package/lib/commands/extras.mjs
CHANGED
|
@@ -49,7 +49,7 @@ export async function filesFromLastCommit(cwd) {
|
|
|
49
49
|
|
|
50
50
|
// ───────────────────────────────── saved filters (finding 148)
|
|
51
51
|
|
|
52
|
-
const FILTER_KEYS = ["mine", "all", "status", "limit"];
|
|
52
|
+
const FILTER_KEYS = ["mine", "all", "status", "limit", "due", "to", "sprint", "priority", "sort"];
|
|
53
53
|
|
|
54
54
|
/** `--save <name>` stores the list flags; `@name` brings them back. @param {Context} ctx */
|
|
55
55
|
export function applySavedFilter(ctx) {
|
package/lib/commands/files.mjs
CHANGED
|
@@ -12,7 +12,7 @@ import { enqueue, QUEUE_TTL_MS, readQueue, writeQueue } from "../sync/queue.mjs"
|
|
|
12
12
|
import { acquireLock, pruneBaseCopies, readState, saveBaseCopy, writeState } from "../sync/state.mjs";
|
|
13
13
|
import { conflictCopyPath, downloadTo, fetchManifest, renameRetry, safeJoin, uploadFiles } from "../sync/transfer.mjs";
|
|
14
14
|
import { confirm } from "../tui/ask.mjs";
|
|
15
|
-
import { resolveTask } from "./tasks.mjs";
|
|
15
|
+
import { branchTask, resolveTask } from "./tasks.mjs";
|
|
16
16
|
|
|
17
17
|
/** @typedef {import("../context.mjs").Context} Context */
|
|
18
18
|
/** @typedef {import("../sync/plan.mjs").PlanItem} PlanItem */
|
|
@@ -76,15 +76,20 @@ export function recordBase(state, p, f) {
|
|
|
76
76
|
|
|
77
77
|
/** @param {Context} ctx */
|
|
78
78
|
export async function status(ctx) {
|
|
79
|
+
// The day's counts ride along (C2 "a home screen in nb status"); offline or refused, status still works.
|
|
80
|
+
const todayP = ctx.api.get("/api/v1/home").then((/** @type {any} */ h) => ({ dueThisWeek: h.tasks.dueThisWeek, overdue: h.tasks.overdue, unread: h.unread }), () => null);
|
|
79
81
|
const { root, project, items, skipped, offline, manifest } = await buildPlan(ctx);
|
|
82
|
+
const today = await todayP;
|
|
80
83
|
const changed = items.filter((i) => i.state !== "unchanged");
|
|
81
84
|
const conflicts = changed.filter((i) => i.state === "conflict");
|
|
82
85
|
const data = {
|
|
83
86
|
workspace: { id: project.workspaceId, slug: project.slug, title: project.title },
|
|
84
|
-
|
|
87
|
+
// The current task (C8): the started one, or the one the nb/<n>- git branch names.
|
|
88
|
+
startedTask: project.startedTask ?? ((n) => (n ? { number: Number(n), title: "(from the git branch)" } : null))(branchTask(root)),
|
|
85
89
|
offline,
|
|
86
90
|
readOnly: !manifest.canWrite,
|
|
87
91
|
queued: readQueue(root).length,
|
|
92
|
+
today,
|
|
88
93
|
files: changed.map((i) => ({ path: i.path, state: i.state, action: i.action, ...(i.note ? { note: i.note } : {}), ...(i.remote ? { remoteVersion: i.remote.version } : {}) })),
|
|
89
94
|
skipped,
|
|
90
95
|
};
|
|
@@ -92,8 +97,21 @@ export async function status(ctx) {
|
|
|
92
97
|
ctx.out.result("nb.status/1", data, (d) => {
|
|
93
98
|
const task = d.startedTask ? ` · #${d.startedTask.number ?? ""} ${safe(d.startedTask.title ?? "")}` : "";
|
|
94
99
|
const head = `${c.brand(sym.brand)} ${safe(project.slug ?? project.workspaceId)}${task}${d.readOnly ? ` · ${c.warning("read only")}` : ""}${d.offline ? ` · ${c.warning("offline: server side not checked")}` : ""}`;
|
|
95
|
-
const queued = d.queued ? [` ${c.warning(`${d.queued} push(es) queued while offline: nb
|
|
100
|
+
const queued = d.queued ? [` ${c.warning(`${d.queued} push(es) queued while offline: nb queue`)}`] : [];
|
|
101
|
+
const t = d.today;
|
|
102
|
+
const here = d.files.filter((f) => f.action === "push" || f.state === "conflict").length;
|
|
103
|
+
const day = t ? [t.dueThisWeek && `${t.dueThisWeek} due this week`, t.overdue && c.warning(`${t.overdue} overdue`), t.unread && `${t.unread} unread`, here && `${here} ${here === 1 ? "file" : "files"} changed here`].filter(Boolean) : [];
|
|
104
|
+
if (day.length) queued.unshift(` ${day.join(" · ")}`);
|
|
96
105
|
if (!d.files.length) return [head, ...queued, ` ${c.muted(`Up to date · ${root}`)}`, ...skippedLines(d.skipped)];
|
|
106
|
+
// A freshly linked folder: hundreds of server files are one line, not a table (C16 #5).
|
|
107
|
+
const waiting = d.files.filter((f) => f.state === "remote-added");
|
|
108
|
+
if (waiting.length > 20) {
|
|
109
|
+
const rest = d.files.filter((f) => f.state !== "remote-added");
|
|
110
|
+
const line = ` ${waiting.length} files on the server · ${c.muted("nb pull to get them")}`;
|
|
111
|
+
if (!rest.length) return [head, ...queued, line, ...skippedLines(d.skipped)];
|
|
112
|
+
d = { ...d, files: rest };
|
|
113
|
+
queued.push(line);
|
|
114
|
+
}
|
|
97
115
|
const color = (/** @type {string} */ s) => (s === "conflict" ? c.danger : s === "modified" || s === "added" ? c.accent : s.startsWith("remote") ? c.info : c.muted);
|
|
98
116
|
const counts = Object.entries(d.files.reduce((/** @type {Record<string, number>} */ acc, f) => ({ ...acc, [f.state]: (acc[f.state] ?? 0) + 1 }), {})).map(([s, n]) => `${n} ${s}`).join(" · ");
|
|
99
117
|
const rows = ctx.out.table([
|
|
@@ -236,7 +254,7 @@ export async function push(ctx) {
|
|
|
236
254
|
const queueOffline = () => {
|
|
237
255
|
if (ctx.flags["dry-run"]) return new CliError("OFFLINE", "Can't reach the server", { hint: "Try again when you're online" });
|
|
238
256
|
const flags = Object.fromEntries(["task", "as", "message", "keep-both", "folder", "all"].filter((k) => ctx.flags[k] !== undefined).map((k) => [k, ctx.flags[k]]));
|
|
239
|
-
const n = enqueue(root, { id: keyBase, op: "push", paths: only, flags, queuedAt: new Date().toISOString() });
|
|
257
|
+
const n = enqueue(root, { id: keyBase, op: "push", paths: only, flags, queuedAt: new Date().toISOString(), reason: "the server couldn't be reached" });
|
|
240
258
|
return new CliError("OFFLINE", `Offline: queued this push${n > 1 ? ` (${n} waiting)` : ""}`, { hint: "It sends with your next nb sync; your files are unchanged" });
|
|
241
259
|
};
|
|
242
260
|
const release = ctx.flags["dry-run"] ? () => {} : await acquireLock(root, "nb push");
|
|
@@ -244,6 +262,17 @@ export async function push(ctx) {
|
|
|
244
262
|
const plan = await buildPlan(ctx, { only });
|
|
245
263
|
if (plan.offline) throw queueOffline();
|
|
246
264
|
const { project, state } = plan;
|
|
265
|
+
// A file you named that can't go up is an error that says why, never "Nothing changed" (C16 #2).
|
|
266
|
+
const named = new Set(only.map((p) => p.split(path.sep).join("/").replace(/^\/+/, "")));
|
|
267
|
+
const refused = plan.skipped.find((s) => named.has(s.path.replace(/^\/+/, "")));
|
|
268
|
+
if (refused) {
|
|
269
|
+
const limit = plan.manifest.largestFileBytes;
|
|
270
|
+
const bytes = (() => { try { return fs.statSync(path.join(root, refused.path)).size; } catch { return 0; } })();
|
|
271
|
+
const mb = (/** @type {number} */ n) => Math.ceil(n / 1024 / 1024);
|
|
272
|
+
throw /^over the/.test(refused.reason) && limit
|
|
273
|
+
? new CliError("PLAN_LIMIT_FILE_SIZE", `${safe(refused.path)} is ${mb(bytes)} MB; files can be up to ${mb(limit)} MB`, { hint: "Make it smaller, or share it as a link" })
|
|
274
|
+
: new CliError("USAGE", `${safe(refused.path)} can't be pushed: ${refused.reason}`);
|
|
275
|
+
}
|
|
247
276
|
if (!plan.manifest.canWrite) throw new CliError("READ_ONLY", "You can read this workspace but not change it", { hint: "Ask an owner for member access" });
|
|
248
277
|
// With no paths, only files NetworkBase already tracks; new files are pushed by naming them (A1.6, §17.4).
|
|
249
278
|
let items = plan.items.filter((i) => i.action === "push" && (only.length || i.base));
|
|
@@ -285,7 +314,10 @@ export async function push(ctx) {
|
|
|
285
314
|
}
|
|
286
315
|
}
|
|
287
316
|
moves = moves.filter((m) => state.files[m.path]);
|
|
288
|
-
|
|
317
|
+
// The started task gets the files unless told otherwise (C16 #1, C8): nb task start promises it.
|
|
318
|
+
// The current task (C8): --task, the started one, or the nb/<n>- git branch; --no-task opts out.
|
|
319
|
+
const taskRef = ctx.flags.task ?? (ctx.flags["no-task"] ? null : ctx.project?.startedTask?.id ?? branchTask(root));
|
|
320
|
+
const task = taskRef ? await resolveTask(ctx, String(taskRef)) : null;
|
|
289
321
|
const uploaded = items.length
|
|
290
322
|
? await uploadFiles(ctx.api, {
|
|
291
323
|
workspaceId: project.workspaceId,
|
|
@@ -398,6 +430,42 @@ export async function sync(ctx) {
|
|
|
398
430
|
return push(ctx2);
|
|
399
431
|
}
|
|
400
432
|
|
|
433
|
+
// ───────────────────────────────── queue (C6)
|
|
434
|
+
|
|
435
|
+
/** What's waiting to send, since when and why (C6). @param {Context} ctx */
|
|
436
|
+
export async function queue(ctx) {
|
|
437
|
+
const { root } = ctx.requireRoot();
|
|
438
|
+
const entries = readQueue(root).map((e, i) => ({ n: i + 1, id: e.id, paths: e.paths, task: e.flags?.task ?? null, queuedAt: e.queuedAt, reason: e.reason ?? "the server couldn't be reached", dropsAt: new Date(Date.parse(e.queuedAt) + QUEUE_TTL_MS).toISOString() }));
|
|
439
|
+
const { c } = ctx.out;
|
|
440
|
+
ctx.out.result("nb.queue/1", { entries }, (d) => (d.entries.length ? [
|
|
441
|
+
`${d.entries.length} ${d.entries.length === 1 ? "push is" : "pushes are"} waiting to send`,
|
|
442
|
+
...d.entries.map((e) => ` ${e.n}. ${e.paths.length ? e.paths.map((p) => safe(p)).slice(0, 3).join(", ") + (e.paths.length > 3 ? ` and ${e.paths.length - 3} more` : "") : "every changed file"}${e.task ? ` · task ${safe(String(e.task))}` : ""} ${c.muted(`queued ${e.queuedAt.slice(0, 16).replace("T", " ")}: ${e.reason}`)}`),
|
|
443
|
+
c.muted(" nb queue retry sends them · nb queue drop <n> forgets one (your files stay as they are)"),
|
|
444
|
+
] : "Nothing waiting: every push has gone up"));
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
/** Send the queue now (C6). @param {Context} ctx */
|
|
448
|
+
export async function queueRetry(ctx) {
|
|
449
|
+
const { root } = ctx.requireRoot();
|
|
450
|
+
const before = readQueue(root).length;
|
|
451
|
+
await replayQueue(ctx);
|
|
452
|
+
ctx.out.result("nb.queue.retry/1", { sent: before }, (d) => (d.sent ? `${ctx.out.c.success(ctx.out.sym.done)} Sent ${d.sent} queued ${d.sent === 1 ? "push" : "pushes"}` : "Nothing waiting"));
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
/** Forget queued pushes; the files themselves don't change (C6). @param {Context} ctx */
|
|
456
|
+
export async function queueDrop(ctx) {
|
|
457
|
+
const { root } = ctx.requireRoot();
|
|
458
|
+
const entries = readQueue(root);
|
|
459
|
+
if (!ctx.flags.all && !ctx.positionals.length) throw usage("Which ones?", "nb queue drop 1, or nb queue drop --all");
|
|
460
|
+
const drop = ctx.flags.all ? entries : ctx.positionals.map((r) => {
|
|
461
|
+
const hit = /^\d+$/.test(r) ? entries[Number(r) - 1] : entries.find((e) => e.id.startsWith(r));
|
|
462
|
+
if (!hit) throw new CliError("NOT_FOUND", `Nothing queued as ${r}`, { hint: "nb queue" });
|
|
463
|
+
return hit;
|
|
464
|
+
});
|
|
465
|
+
writeQueue(root, entries.filter((e) => !drop.includes(e)));
|
|
466
|
+
ctx.out.result("nb.queue.drop/1", { dropped: drop.length }, (d) => `${ctx.out.c.success(ctx.out.sym.done)} Dropped ${d.dropped} queued ${d.dropped === 1 ? "push" : "pushes"}; your files are unchanged (nb status shows them)`);
|
|
467
|
+
}
|
|
468
|
+
|
|
401
469
|
/**
|
|
402
470
|
* Sends pushes queued while offline, oldest first. A conflict stops the queue there (later pushes may depend on
|
|
403
471
|
* it); still offline keeps it; expired entries are dropped with a note (A12.4).
|