@networkbase/cli 1.0.4 → 2.0.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/README.md +60 -37
- package/bin/nb.mjs +69 -5390
- package/lib/api.mjs +163 -0
- package/lib/args.mjs +140 -0
- package/lib/commands/account.mjs +293 -0
- package/lib/commands/agent.mjs +169 -0
- package/lib/commands/ask.mjs +84 -0
- package/lib/commands/assignments.mjs +199 -0
- package/lib/commands/browse.mjs +140 -0
- package/lib/commands/docs.mjs +178 -0
- package/lib/commands/extras.mjs +114 -0
- package/lib/commands/files.mjs +425 -0
- package/lib/commands/inbox.mjs +98 -0
- package/lib/commands/link.mjs +85 -0
- package/lib/commands/mcp.mjs +149 -0
- package/lib/commands/misc.mjs +263 -0
- package/lib/commands/resolve.mjs +95 -0
- package/lib/commands/table.mjs +225 -0
- package/lib/commands/tasks.mjs +362 -0
- package/lib/commands/undo.mjs +52 -0
- package/lib/commands/watch.mjs +113 -0
- package/lib/commands/work.mjs +190 -0
- package/lib/config.mjs +203 -0
- package/lib/context.mjs +72 -0
- package/lib/errors.mjs +72 -0
- package/lib/keychain.mjs +59 -0
- package/lib/mcp/tools.mjs +336 -0
- package/lib/print/notices.mjs +48 -0
- package/lib/print/out.mjs +151 -0
- package/lib/print/remind.mjs +25 -0
- package/lib/print/style.mjs +110 -0
- package/lib/sync/diff.mjs +41 -0
- package/lib/sync/ignore.mjs +86 -0
- package/lib/sync/local.mjs +68 -0
- package/lib/sync/plan.mjs +94 -0
- package/lib/sync/queue.mjs +31 -0
- package/lib/sync/state.mjs +136 -0
- package/lib/sync/transfer.mjs +172 -0
- package/lib/tui/ask.mjs +124 -0
- package/lib/undo-log.mjs +34 -0
- package/package.json +13 -11
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
// What was last synced (the base for three-way decisions, report A1.2), the process lock (A1.10) and base
|
|
2
|
+
// copies for offline diff (A1.12).
|
|
3
|
+
import crypto from "node:crypto";
|
|
4
|
+
import fs from "node:fs";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
|
|
7
|
+
import { DIR_NAME, readJson, renameRetry, writeAtomic } from "../config.mjs";
|
|
8
|
+
import { CliError } from "../errors.mjs";
|
|
9
|
+
|
|
10
|
+
export const STATE_VERSION = 1;
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* @typedef {{ nodeId: string, baseVersion: number, baseHash: string, size: number, mtimeMs: number }} BaseEntry
|
|
14
|
+
* @typedef {{ schemaVersion: number, workspaceId: string, files: Record<string, BaseEntry>, conflicts: Record<string, { remoteVersion: number, copy: string }> }} SyncState
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
/** @param {string} root @param {string} workspaceId @returns {SyncState} */
|
|
18
|
+
export function readState(root, workspaceId) {
|
|
19
|
+
const raw = readJson(path.join(root, DIR_NAME, "state.json"));
|
|
20
|
+
if (raw) {
|
|
21
|
+
if (raw.schemaVersion > STATE_VERSION) throw new CliError("CLIENT_TOO_OLD", "This folder was synced by a newer nb", { hint: "Update: npm i -g @networkbase/cli" });
|
|
22
|
+
if (raw.workspaceId === workspaceId) return { conflicts: {}, ...raw };
|
|
23
|
+
return { schemaVersion: STATE_VERSION, workspaceId, files: {}, conflicts: {} };
|
|
24
|
+
}
|
|
25
|
+
// 1.x kept versions in manifest.json; they become the base so nothing is re-downloaded (A1.20).
|
|
26
|
+
const legacy = readJson(path.join(root, DIR_NAME, "manifest.json"));
|
|
27
|
+
/** @type {Record<string, BaseEntry>} */
|
|
28
|
+
const files = {};
|
|
29
|
+
if (legacy?.projectId === workspaceId) {
|
|
30
|
+
for (const [p, entry] of Object.entries(/** @type {Record<string, any>} */ (legacy.files ?? {}))) {
|
|
31
|
+
if (entry?.nodeId && entry?.contentHash) files[p] = { nodeId: entry.nodeId, baseVersion: entry.version ?? 1, baseHash: String(entry.contentHash).toLowerCase(), size: entry.size ?? 0, mtimeMs: 0 };
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
return { schemaVersion: STATE_VERSION, workspaceId, files, conflicts: {} };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** @param {string} root @param {SyncState} state */
|
|
38
|
+
export function writeState(root, state) {
|
|
39
|
+
writeAtomic(path.join(root, DIR_NAME, "state.json"), `${JSON.stringify(state)}\n`);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Process start time, so a PID reused after a reboot isn't mistaken for a running nb (finding 26). @param {number} pid */
|
|
43
|
+
function processStart(pid) {
|
|
44
|
+
try {
|
|
45
|
+
if (process.platform === "linux") return fs.readFileSync(`/proc/${pid}/stat`, "utf8").split(" ")[21] ?? null;
|
|
46
|
+
process.kill(pid, 0);
|
|
47
|
+
return "alive";
|
|
48
|
+
} catch {
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* One nb at a time writes a folder (A1.10). Waits up to `waitMs`, takes over a lock whose process is gone.
|
|
55
|
+
* @param {string} root @param {string} command @param {number} [waitMs]
|
|
56
|
+
* @returns {Promise<() => void>} release
|
|
57
|
+
*/
|
|
58
|
+
export async function acquireLock(root, command, waitMs = 10_000) {
|
|
59
|
+
const file = path.join(root, DIR_NAME, "lock");
|
|
60
|
+
const mine = JSON.stringify({ pid: process.pid, start: processStart(process.pid), command, at: new Date().toISOString() });
|
|
61
|
+
const deadline = Date.now() + waitMs;
|
|
62
|
+
for (;;) {
|
|
63
|
+
try {
|
|
64
|
+
fs.writeFileSync(file, mine, { flag: "wx", mode: 0o600 });
|
|
65
|
+
let released = false;
|
|
66
|
+
const release = () => {
|
|
67
|
+
if (released) return;
|
|
68
|
+
released = true;
|
|
69
|
+
try { if (fs.readFileSync(file, "utf8") === mine) fs.rmSync(file); } catch { /* already gone */ }
|
|
70
|
+
};
|
|
71
|
+
process.once("exit", release);
|
|
72
|
+
return release;
|
|
73
|
+
} catch (error) {
|
|
74
|
+
if (/** @type {NodeJS.ErrnoException} */ (error).code !== "EEXIST") throw error;
|
|
75
|
+
}
|
|
76
|
+
const holder = (() => { try { return JSON.parse(fs.readFileSync(file, "utf8")); } catch { return null; } })();
|
|
77
|
+
const alive = holder?.pid && processStart(holder.pid) !== null && (holder.start === "alive" || processStart(holder.pid) === holder.start);
|
|
78
|
+
if (!alive) {
|
|
79
|
+
fs.rmSync(file, { force: true });
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
if (Date.now() > deadline) throw new CliError("LOCKED", `Another nb is working in this folder (${holder.command}, pid ${holder.pid})`, { hint: "Wait for it to finish, or stop it" });
|
|
83
|
+
await new Promise((r) => setTimeout(r, 200));
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const BASE_MAX_BYTES = 1024 * 1024;
|
|
88
|
+
|
|
89
|
+
/** Keeps a text base ≤ 1 MB for offline diff (A1.12, D26). @param {string} root @param {string} hash @param {Buffer} content */
|
|
90
|
+
export function saveBaseCopy(root, hash, content) {
|
|
91
|
+
if (content.length > BASE_MAX_BYTES || content.includes(0)) return;
|
|
92
|
+
const file = path.join(root, DIR_NAME, "base", hash);
|
|
93
|
+
if (fs.existsSync(file)) return;
|
|
94
|
+
// A cache for nb diff only, so no fsync (it blocked parallel pulls); the rename keeps it whole.
|
|
95
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
96
|
+
const tmp = `${file}.nbtmp-${crypto.randomBytes(4).toString("hex")}`;
|
|
97
|
+
fs.writeFileSync(tmp, content, { mode: 0o600 });
|
|
98
|
+
renameRetry(tmp, file);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** @param {string} root @param {string} hash */
|
|
102
|
+
export function readBaseCopy(root, hash) {
|
|
103
|
+
try {
|
|
104
|
+
return fs.readFileSync(path.join(root, DIR_NAME, "base", hash));
|
|
105
|
+
} catch {
|
|
106
|
+
return null;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Drops base copies no file points to, then trims oldest past the cap. @param {string} root @param {SyncState} state @param {number} capBytes */
|
|
111
|
+
export function pruneBaseCopies(root, state, capBytes = 200 * 1024 * 1024) {
|
|
112
|
+
const dir = path.join(root, DIR_NAME, "base");
|
|
113
|
+
if (!fs.existsSync(dir)) return;
|
|
114
|
+
const live = new Set(Object.values(state.files).map((f) => f.baseHash));
|
|
115
|
+
const kept = [];
|
|
116
|
+
for (const name of fs.readdirSync(dir)) {
|
|
117
|
+
const file = path.join(dir, name);
|
|
118
|
+
if (!live.has(name)) { fs.rmSync(file, { force: true }); continue; }
|
|
119
|
+
const st = fs.statSync(file);
|
|
120
|
+
kept.push({ file, size: st.size, at: st.mtimeMs });
|
|
121
|
+
}
|
|
122
|
+
let total = kept.reduce((sum, f) => sum + f.size, 0);
|
|
123
|
+
for (const f of kept.sort((a, b) => a.at - b.at)) {
|
|
124
|
+
if (total <= capBytes) break;
|
|
125
|
+
fs.rmSync(f.file, { force: true });
|
|
126
|
+
total -= f.size;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** Streaming SHA-256 (no whole-file buffers, A12.7). @param {string} file */
|
|
131
|
+
export function hashFile(file) {
|
|
132
|
+
return new Promise((resolve, reject) => {
|
|
133
|
+
const hash = crypto.createHash("sha256");
|
|
134
|
+
fs.createReadStream(file).on("data", (d) => hash.update(d)).on("error", reject).on("end", () => resolve(hash.digest("hex")));
|
|
135
|
+
});
|
|
136
|
+
}
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
// Moving bytes (report A1.7, A1.9, A12.7, A12.10, A12.11): manifest pages, streamed downloads written
|
|
2
|
+
// atomically and hash-checked, uploads through files/place with base versions, conflict copies.
|
|
3
|
+
import crypto from "node:crypto";
|
|
4
|
+
import fs from "node:fs";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { Readable } from "node:stream";
|
|
7
|
+
import { pipeline } from "node:stream/promises";
|
|
8
|
+
|
|
9
|
+
import { CliError } from "../errors.mjs";
|
|
10
|
+
import { renameRetry } from "../config.mjs";
|
|
11
|
+
import { hashFile } from "./state.mjs";
|
|
12
|
+
|
|
13
|
+
export { renameRetry };
|
|
14
|
+
|
|
15
|
+
/** @typedef {import("../api.mjs").Api} Api */
|
|
16
|
+
|
|
17
|
+
/** Every visible file with version and hash (A2.5 manifest, pages of 5,000). @param {Api} api @param {string} workspaceId */
|
|
18
|
+
export async function fetchManifest(api, workspaceId) {
|
|
19
|
+
/** @type {Map<string, import("./plan.mjs").RemoteFile & { path: string }>} */
|
|
20
|
+
const files = new Map();
|
|
21
|
+
let cursor = null;
|
|
22
|
+
/** @type {any} */
|
|
23
|
+
let page;
|
|
24
|
+
do {
|
|
25
|
+
page = await api.get(`/api/v1/workspaces/${encodeURIComponent(workspaceId)}/manifest`, { query: { cursor } });
|
|
26
|
+
for (const f of page.files) files.set(f.path, { path: f.path, nodeId: f.nodeId, version: f.version, hash: f.contentHash ? String(f.contentHash).toLowerCase() : null, size: f.size ?? 0, updatedAt: f.updatedAt ?? null });
|
|
27
|
+
cursor = page.nextCursor;
|
|
28
|
+
} while (cursor);
|
|
29
|
+
return { files, canWrite: Boolean(page.canWrite), largestFileBytes: page.limits?.largestFileBytes ?? 10 * 1024 * 1024 };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Rejects paths that would land outside the folder (report A3.12, finding 34). @param {string} root @param {string} rel */
|
|
33
|
+
export function safeJoin(root, rel) {
|
|
34
|
+
if (!rel || rel.includes("\0") || path.isAbsolute(rel) || /^[a-zA-Z]:/.test(rel)) throw new CliError("UNSAFE_PATH", `Refusing an unsafe path from the server: ${JSON.stringify(rel)}`);
|
|
35
|
+
const target = path.resolve(root, ...rel.split("/"));
|
|
36
|
+
const inside = path.relative(root, target);
|
|
37
|
+
if (!inside || inside.startsWith("..") || path.isAbsolute(inside)) throw new CliError("UNSAFE_PATH", `Refusing a path outside this folder: ${JSON.stringify(rel)}`);
|
|
38
|
+
if (process.platform === "win32" && inside.split(path.sep).some((part) => /^(con|prn|aux|nul|com\d|lpt\d)(\.|$)/i.test(part))) {
|
|
39
|
+
throw new CliError("RESERVED_NAME", `Windows can't hold a file named ${JSON.stringify(rel)}`);
|
|
40
|
+
}
|
|
41
|
+
return target;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Streams a file to `dest` via a temp file in the same folder, checks its hash, then renames (A1.9, A12.10).
|
|
46
|
+
* @param {Api} api @param {string} workspaceId @param {string} remotePath @param {string} dest @param {string | null} expectedHash
|
|
47
|
+
* @returns {Promise<{ hash: string, size: number, content: Buffer | null }>} content only for small text-like files (base copies)
|
|
48
|
+
*/
|
|
49
|
+
export async function downloadTo(api, workspaceId, remotePath, dest, expectedHash) {
|
|
50
|
+
fs.mkdirSync(path.dirname(dest), { recursive: true });
|
|
51
|
+
const tmp = `${dest}.nbtmp-${crypto.randomBytes(4).toString("hex")}`;
|
|
52
|
+
try {
|
|
53
|
+
const response = await api.download("/api/v1/extension/file", { projectId: workspaceId, path: remotePath, transfer: "raw" }).catch(async (error) => {
|
|
54
|
+
// Files the storage check hasn't verified are served inline instead.
|
|
55
|
+
if (!(error instanceof CliError) || error.status !== 404) throw error;
|
|
56
|
+
return null;
|
|
57
|
+
});
|
|
58
|
+
if (response?.body) {
|
|
59
|
+
await pipeline(Readable.fromWeb(/** @type {any} */ (response.body)), fs.createWriteStream(tmp, { mode: 0o644 }));
|
|
60
|
+
} else {
|
|
61
|
+
const inline = /** @type {any} */ (await api.get("/api/v1/extension/file", { query: { projectId: workspaceId, path: remotePath, transfer: "inline" } }));
|
|
62
|
+
fs.writeFileSync(tmp, Buffer.from(inline.content ?? "", inline.encoding === "base64" ? "base64" : "utf8"), { mode: 0o644 });
|
|
63
|
+
}
|
|
64
|
+
const hash = /** @type {string} */ (await hashFile(tmp));
|
|
65
|
+
if (expectedHash && hash !== expectedHash) throw new CliError("CORRUPT_DOWNLOAD", `${remotePath} didn't arrive intact`, { hint: "Run the command again" });
|
|
66
|
+
const size = fs.statSync(tmp).size;
|
|
67
|
+
const content = size <= 1024 * 1024 ? fs.readFileSync(tmp) : null;
|
|
68
|
+
renameRetry(tmp, dest);
|
|
69
|
+
return { hash, size, content };
|
|
70
|
+
} finally {
|
|
71
|
+
fs.rmSync(tmp, { force: true });
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** `report.md` → `report.remote-v5.md`, next to it so it opens in the same app (A1.7, D18). @param {string} abs @param {number} version */
|
|
76
|
+
export function conflictCopyPath(abs, version) {
|
|
77
|
+
const ext = path.extname(abs);
|
|
78
|
+
return `${abs.slice(0, abs.length - ext.length)}.remote-v${version}${ext}`;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const MIME = /** @type {Record<string, string>} */ ({
|
|
82
|
+
".md": "text/markdown", ".txt": "text/plain", ".json": "application/json", ".csv": "text/csv", ".html": "text/html", ".css": "text/css",
|
|
83
|
+
".js": "text/javascript", ".mjs": "text/javascript", ".ts": "text/plain", ".tsx": "text/plain", ".jsx": "text/plain", ".py": "text/x-python",
|
|
84
|
+
".svg": "image/svg+xml", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".gif": "image/gif", ".webp": "image/webp",
|
|
85
|
+
".pdf": "application/pdf", ".zip": "application/zip", ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
|
86
|
+
".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", ".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
|
|
87
|
+
});
|
|
88
|
+
/** @param {string} p */
|
|
89
|
+
export const mimeFor = (p) => MIME[path.extname(p).toLowerCase()] ?? "application/octet-stream";
|
|
90
|
+
|
|
91
|
+
const INLINE_BATCH_BYTES = 3 * 1024 * 1024;
|
|
92
|
+
const BATCH_FILES = 50;
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Uploads through files/place in batches (≤ 50 files, ≤ 3 MiB inline); bigger files use signed upload slots.
|
|
96
|
+
* @param {Api} api
|
|
97
|
+
* @param {{ workspaceId: string, items: Array<{ path: string, abs: string, size: number, hash: string, baseVersion?: number | null }>, taskId?: string | null, as?: string | null, message?: string | null, keepBoth?: boolean, folder?: string | null, confirmSecrets?: boolean, keyBase?: string }} input
|
|
98
|
+
* @param {(done: number, total: number) => void} [progress]
|
|
99
|
+
*/
|
|
100
|
+
export async function uploadFiles(api, input, progress) {
|
|
101
|
+
/** @type {any[]} */
|
|
102
|
+
const results = [];
|
|
103
|
+
/** @type {any} */
|
|
104
|
+
let lastTransition = null;
|
|
105
|
+
const small = input.items.filter((i) => i.size <= INLINE_BATCH_BYTES);
|
|
106
|
+
const large = input.items.filter((i) => i.size > INLINE_BATCH_BYTES);
|
|
107
|
+
let done = 0;
|
|
108
|
+
for (let i = 0; i < small.length;) {
|
|
109
|
+
const batch = [];
|
|
110
|
+
let bytes = 0;
|
|
111
|
+
while (i < small.length && batch.length < BATCH_FILES && (batch.length === 0 || bytes + (small[i]?.size ?? 0) <= INLINE_BATCH_BYTES)) {
|
|
112
|
+
const item = /** @type {typeof small[number]} */ (small[i++]);
|
|
113
|
+
bytes += item.size;
|
|
114
|
+
batch.push(item);
|
|
115
|
+
}
|
|
116
|
+
const body = {
|
|
117
|
+
projectId: input.workspaceId,
|
|
118
|
+
...(input.taskId ? { taskId: input.taskId } : {}),
|
|
119
|
+
...(input.as ? { role: input.as } : {}),
|
|
120
|
+
...(input.message ? { message: input.message } : {}),
|
|
121
|
+
...(input.keepBoth ? { onSameName: "keep-both" } : {}),
|
|
122
|
+
...(input.folder ? { folder: input.folder } : {}),
|
|
123
|
+
...(input.confirmSecrets ? { confirmSecrets: true } : {}),
|
|
124
|
+
files: batch.map((item) => {
|
|
125
|
+
const content = fs.readFileSync(item.abs);
|
|
126
|
+
return { path: item.path, contentHash: item.hash, size: content.length, mimeType: mimeFor(item.path), contentBase64: content.toString("base64"), ...(item.baseVersion ? { baseVersion: item.baseVersion } : {}) };
|
|
127
|
+
}),
|
|
128
|
+
};
|
|
129
|
+
// Same files and bases → same key, so a push replayed from the offline queue can't land twice (A12.4).
|
|
130
|
+
const key = input.keyBase ? crypto.createHash("sha256").update(`${input.keyBase}:${JSON.stringify(body.files.map((f) => [f.path, f.contentHash, f.baseVersion ?? null]))}`).digest("hex") : undefined;
|
|
131
|
+
const res = /** @type {any} */ (await api.post("/api/v1/files/place", body, { key }));
|
|
132
|
+
results.push(...res.files);
|
|
133
|
+
if (res.transition) lastTransition = res.transition;
|
|
134
|
+
done += batch.length;
|
|
135
|
+
progress?.(done, input.items.length);
|
|
136
|
+
}
|
|
137
|
+
if (large.length) {
|
|
138
|
+
results.push(...(await uploadLarge(api, input.workspaceId, large, input.message ?? null)));
|
|
139
|
+
progress?.(input.items.length, input.items.length);
|
|
140
|
+
}
|
|
141
|
+
return { files: results, transition: lastTransition };
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* Files over 3 MiB: signed upload slots, PUT, then finalize (the 1.x bulk path). The base-version check happened
|
|
146
|
+
* just before through a fresh manifest; the bulk routes don't take one (noted in the phase notes).
|
|
147
|
+
* @param {Api} api @param {string} workspaceId @param {Array<{ path: string, abs: string, size: number, hash: string }>} items @param {string | null} message
|
|
148
|
+
*/
|
|
149
|
+
async function uploadLarge(api, workspaceId, items, message) {
|
|
150
|
+
/** @type {any[]} */
|
|
151
|
+
const out = [];
|
|
152
|
+
for (let i = 0; i < items.length; i += BATCH_FILES) {
|
|
153
|
+
const batch = items.slice(i, i + BATCH_FILES);
|
|
154
|
+
const intent = /** @type {any} */ (await api.post("/api/v1/extension/bulk-intent", {
|
|
155
|
+
projectId: workspaceId,
|
|
156
|
+
files: batch.map((f) => ({ path: f.path, size: f.size, mimeType: mimeFor(f.path), contentHash: f.hash, ...(message ? { comment: message } : {}) })),
|
|
157
|
+
}));
|
|
158
|
+
for (const slot of intent.files) {
|
|
159
|
+
const item = batch.find((f) => f.path === slot.path);
|
|
160
|
+
if (!item) continue;
|
|
161
|
+
const put = await fetch(slot.uploadUrl, /** @type {RequestInit} */ ({ method: "PUT", headers: { "content-type": mimeFor(item.path), "content-length": String(item.size) }, body: /** @type {any} */ (fs.createReadStream(item.abs)), duplex: "half", signal: AbortSignal.timeout(10 * 60_000) }));
|
|
162
|
+
if (!put.ok) throw new CliError("UPLOAD_FAILED", `Uploading ${item.path} failed (HTTP ${put.status})`, { hint: "Run the command again" });
|
|
163
|
+
}
|
|
164
|
+
const finalized = /** @type {any} */ (await api.post("/api/v1/extension/bulk-finalize", {
|
|
165
|
+
projectId: workspaceId,
|
|
166
|
+
uploadSessionId: intent.uploadSessionId,
|
|
167
|
+
files: intent.files.map((/** @type {any} */ slot) => ({ path: slot.path, uploadIntentId: slot.uploadIntentId, checksum: batch.find((f) => f.path === slot.path)?.hash, ...(message ? { comment: message } : {}) })),
|
|
168
|
+
}));
|
|
169
|
+
out.push(...finalized.files);
|
|
170
|
+
}
|
|
171
|
+
return out;
|
|
172
|
+
}
|
package/lib/tui/ask.mjs
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
// Questions when something is unclear (report §20.1, §20.3, A4.4, A4.11). Interactive: numbered options on
|
|
2
|
+
// stderr, recommended first, ↑/↓ or 1–4, Enter, Esc cancels. Not interactive: --answer key=value, --yes takes
|
|
3
|
+
// the recommended option, otherwise exit 6 with the question as JSON so an agent can ask the person.
|
|
4
|
+
import readline from "node:readline";
|
|
5
|
+
|
|
6
|
+
import { CliError } from "../errors.mjs";
|
|
7
|
+
import { safe } from "../print/style.mjs";
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* @typedef {{ value: string, label: string, description?: string, recommended?: boolean }} Option
|
|
11
|
+
* @typedef {{ key: string, header: string, question: string, options: Option[], preview?: string }} Question
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
/** @param {import("../context.mjs").Context} ctx @param {string} key */
|
|
15
|
+
function answered(ctx, key) {
|
|
16
|
+
for (const entry of /** @type {string[]} */ (ctx.flags.answer ?? [])) {
|
|
17
|
+
const eq = entry.indexOf("=");
|
|
18
|
+
if (eq > 0 && entry.slice(0, eq) === key) return entry.slice(eq + 1);
|
|
19
|
+
}
|
|
20
|
+
return null;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* @param {import("../context.mjs").Context} ctx
|
|
25
|
+
* @param {Question} q
|
|
26
|
+
* @returns {Promise<string>} the chosen option's value
|
|
27
|
+
*/
|
|
28
|
+
export async function ask(ctx, q) {
|
|
29
|
+
const given = answered(ctx, q.key);
|
|
30
|
+
if (given !== null) {
|
|
31
|
+
if (!q.options.some((o) => o.value === given)) throw new CliError("USAGE", `--answer ${q.key}=${given}: choose ${q.options.map((o) => o.value).join(", ")}`);
|
|
32
|
+
return given;
|
|
33
|
+
}
|
|
34
|
+
const recommended = q.options.find((o) => o.recommended) ?? q.options[0];
|
|
35
|
+
if (ctx.flags.yes && recommended) return recommended.value;
|
|
36
|
+
if (!ctx.out.interactive) {
|
|
37
|
+
throw new CliError("NEEDS_INPUT", q.question, {
|
|
38
|
+
hint: `Answer with --answer ${q.key}=<${q.options.map((o) => o.value).join("|")}>${recommended ? `, or --yes for ${recommended.value}` : ""}`,
|
|
39
|
+
details: { schema: "nb.question/1", questions: [{ key: q.key, header: q.header, question: q.question, options: q.options, ...(q.preview ? { preview: q.preview } : {}) }] },
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
return interactiveChoice(ctx, q);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** A yes/no that defaults to the safe answer (A4.11). @param {import("../context.mjs").Context} ctx @param {{ key: string, question: string, yesLabel?: string, noLabel?: string, preview?: string, defaultYes?: boolean }} c */
|
|
46
|
+
export async function confirm(ctx, c) {
|
|
47
|
+
// --yes means yes, even where the safe default is No (delete, unlink); --answer key=no still says no.
|
|
48
|
+
if (ctx.flags.yes && answered(ctx, c.key) === null) return true;
|
|
49
|
+
try {
|
|
50
|
+
const value = await ask(ctx, {
|
|
51
|
+
key: c.key,
|
|
52
|
+
header: "Confirm",
|
|
53
|
+
question: c.question,
|
|
54
|
+
...(c.preview ? { preview: c.preview } : {}),
|
|
55
|
+
options: c.defaultYes
|
|
56
|
+
? [{ value: "yes", label: c.yesLabel ?? "Yes", recommended: true }, { value: "no", label: c.noLabel ?? "No" }]
|
|
57
|
+
: [{ value: "no", label: c.noLabel ?? "No", recommended: true }, { value: "yes", label: c.yesLabel ?? "Yes" }],
|
|
58
|
+
});
|
|
59
|
+
return value === "yes";
|
|
60
|
+
} catch (error) {
|
|
61
|
+
// A missing yes is "needs confirmation" (exit 7), not "needs input".
|
|
62
|
+
if (error instanceof CliError && error.code === "NEEDS_INPUT") throw new CliError("NEEDS_CONFIRMATION", c.question, { hint: `Run again with --yes (or --answer ${c.key}=yes)`, details: error.details });
|
|
63
|
+
throw error;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** @param {import("../context.mjs").Context} ctx @param {Question} q */
|
|
68
|
+
function interactiveChoice(ctx, q) {
|
|
69
|
+
const { out } = ctx;
|
|
70
|
+
const err = out.stderr;
|
|
71
|
+
const stdin = process.stdin;
|
|
72
|
+
let cursor = Math.max(0, q.options.findIndex((o) => o.recommended));
|
|
73
|
+
let drawn = 0;
|
|
74
|
+
|
|
75
|
+
const render = () => {
|
|
76
|
+
if (drawn) err.write(`\x1b[${drawn}A\x1b[J`);
|
|
77
|
+
const lines = [`${out.c.accent(out.sym.active)} ${out.c.bold(safe(q.header))} ${safe(q.question)}`];
|
|
78
|
+
if (q.preview) for (const l of safe(q.preview).split("\n").slice(0, 12)) lines.push(`${out.c.muted(out.sym.rail)} ${l}`);
|
|
79
|
+
q.options.forEach((o, i) => {
|
|
80
|
+
const pointer = i === cursor ? out.c.accent(out.sym.cursor) : " ";
|
|
81
|
+
const label = i === cursor ? out.c.bold(safe(o.label)) : safe(o.label);
|
|
82
|
+
lines.push(`${out.c.muted(out.sym.rail)} ${pointer} ${i + 1} ${label}${o.description ? ` ${out.c.muted(safe(o.description))}` : ""}${o.recommended ? ` ${out.c.accent("Recommended")}` : ""}`);
|
|
83
|
+
});
|
|
84
|
+
lines.push(`${out.c.muted(out.sym.end)} ${out.c.muted(`1–${q.options.length} or ↑/↓ · Enter choose · Esc cancel`)}`);
|
|
85
|
+
err.write(`${lines.join("\n")}\n`);
|
|
86
|
+
drawn = lines.length;
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
return new Promise((resolve, reject) => {
|
|
90
|
+
readline.emitKeypressEvents(stdin);
|
|
91
|
+
const wasRaw = stdin.isRaw;
|
|
92
|
+
stdin.setRawMode(true);
|
|
93
|
+
stdin.resume();
|
|
94
|
+
err.write("\x1b[?25l");
|
|
95
|
+
render();
|
|
96
|
+
const cleanup = () => {
|
|
97
|
+
stdin.off("keypress", onKey);
|
|
98
|
+
stdin.setRawMode(Boolean(wasRaw));
|
|
99
|
+
stdin.pause();
|
|
100
|
+
err.write("\x1b[?25h");
|
|
101
|
+
};
|
|
102
|
+
const finish = (/** @type {number} */ index) => {
|
|
103
|
+
cleanup();
|
|
104
|
+
const chosen = /** @type {Option} */ (q.options[index]);
|
|
105
|
+
err.write(`\x1b[${drawn}A\x1b[J${out.c.success(out.sym.done)} ${safe(q.header)} ${out.c.muted(safe(chosen.label))}\n`);
|
|
106
|
+
resolve(chosen.value);
|
|
107
|
+
};
|
|
108
|
+
/** @param {string} str @param {readline.Key} key */
|
|
109
|
+
function onKey(str, key) {
|
|
110
|
+
if ((key.ctrl && key.name === "c") || key.name === "escape") {
|
|
111
|
+
cleanup();
|
|
112
|
+
err.write(`\x1b[${drawn}A\x1b[J`);
|
|
113
|
+
reject(new CliError("CANCELLED", "Cancelled"));
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
if (key.name === "up") { cursor = (cursor - 1 + q.options.length) % q.options.length; render(); return; }
|
|
117
|
+
if (key.name === "down") { cursor = (cursor + 1) % q.options.length; render(); return; }
|
|
118
|
+
if (key.name === "return" || key.name === "enter") { finish(cursor); return; }
|
|
119
|
+
const n = Number(str);
|
|
120
|
+
if (Number.isInteger(n) && n >= 1 && n <= q.options.length) finish(n - 1);
|
|
121
|
+
}
|
|
122
|
+
stdin.on("keypress", onKey);
|
|
123
|
+
});
|
|
124
|
+
}
|
package/lib/undo-log.mjs
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
// Undo tokens the server returned for this machine's changes, newest last (report A2.9). Kept 24 hours, like the
|
|
2
|
+
// server keeps them; `nb undo` uses the newest unless told which.
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
|
|
5
|
+
import { globalDir, readJson, writeAtomic } from "./config.mjs";
|
|
6
|
+
|
|
7
|
+
const DAY = 24 * 60 * 60 * 1000;
|
|
8
|
+
|
|
9
|
+
/** @typedef {{ token: string, at: number, method: string, path: string, origin: string, session?: string | null }} UndoEntry */
|
|
10
|
+
|
|
11
|
+
/** @param {NodeJS.ProcessEnv} env */
|
|
12
|
+
const file = (env) => path.join(globalDir(env), "undo.json");
|
|
13
|
+
|
|
14
|
+
/** @param {NodeJS.ProcessEnv} env @param {string} origin @returns {UndoEntry[]} */
|
|
15
|
+
export function readUndoLog(env, origin) {
|
|
16
|
+
let entries = [];
|
|
17
|
+
try { entries = readJson(file(env))?.entries ?? []; } catch { entries = []; }
|
|
18
|
+
return entries.filter((/** @type {UndoEntry} */ e) => e.origin === origin && Date.now() - e.at < DAY);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** @param {NodeJS.ProcessEnv} env @param {UndoEntry} entry */
|
|
22
|
+
export function appendUndo(env, entry) {
|
|
23
|
+
let entries = [];
|
|
24
|
+
try { entries = readJson(file(env))?.entries ?? []; } catch { entries = []; }
|
|
25
|
+
const kept = entries.filter((/** @type {UndoEntry} */ e) => Date.now() - e.at < DAY).slice(-49);
|
|
26
|
+
try { writeAtomic(file(env), JSON.stringify({ entries: [...kept, entry] })); } catch { /* read-only home: undo by token still works */ }
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** @param {NodeJS.ProcessEnv} env @param {string} token */
|
|
30
|
+
export function dropUndo(env, token) {
|
|
31
|
+
let entries = [];
|
|
32
|
+
try { entries = readJson(file(env))?.entries ?? []; } catch { return; }
|
|
33
|
+
try { writeAtomic(file(env), JSON.stringify({ entries: entries.filter((/** @type {UndoEntry} */ e) => e.token !== token) })); } catch { /* fine */ }
|
|
34
|
+
}
|
package/package.json
CHANGED
|
@@ -1,25 +1,28 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@networkbase/cli",
|
|
3
|
-
"version": "
|
|
4
|
-
"description": "NetworkBase
|
|
3
|
+
"version": "2.0.0",
|
|
4
|
+
"description": "NetworkBase in your terminal: sync files, work on tasks, edit docs",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"homepage": "https://networkbase.in",
|
|
7
7
|
"repository": {
|
|
8
8
|
"type": "git",
|
|
9
|
-
"url": "https://github.com/rama730/NetworkBase.in.git",
|
|
9
|
+
"url": "git+https://github.com/rama730/NetworkBase.in.git",
|
|
10
10
|
"directory": "packages/nb-cli"
|
|
11
11
|
},
|
|
12
12
|
"bin": {
|
|
13
|
-
"nb": "
|
|
14
|
-
"networkbase": "
|
|
15
|
-
|
|
13
|
+
"nb": "bin/nb.mjs",
|
|
14
|
+
"networkbase": "bin/nb.mjs"
|
|
15
|
+
},
|
|
16
|
+
"scripts": {
|
|
17
|
+
"test": "node test/run.mjs"
|
|
16
18
|
},
|
|
17
19
|
"files": [
|
|
18
|
-
"bin/",
|
|
20
|
+
"bin/nb.mjs",
|
|
21
|
+
"lib/",
|
|
19
22
|
"README.md"
|
|
20
23
|
],
|
|
21
24
|
"engines": {
|
|
22
|
-
"node": ">=
|
|
25
|
+
"node": ">=20"
|
|
23
26
|
},
|
|
24
27
|
"publishConfig": {
|
|
25
28
|
"access": "public"
|
|
@@ -27,9 +30,8 @@
|
|
|
27
30
|
"keywords": [
|
|
28
31
|
"networkbase",
|
|
29
32
|
"cli",
|
|
30
|
-
"
|
|
31
|
-
"
|
|
32
|
-
"ai",
|
|
33
|
+
"sync",
|
|
34
|
+
"tasks",
|
|
33
35
|
"developer-tools"
|
|
34
36
|
],
|
|
35
37
|
"license": "Apache-2.0"
|