vibebook.dev 0.0.0-stage → 1.0.1

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.
Files changed (3) hide show
  1. package/cli.mjs +358 -0
  2. package/package.json +11 -4
  3. package/README.md +0 -3
package/cli.mjs ADDED
@@ -0,0 +1,358 @@
1
+ #!/usr/bin/env node
2
+
3
+ // cli/vibebook.ts
4
+ import { execSync, spawn } from "node:child_process";
5
+ import { createHash, randomBytes } from "node:crypto";
6
+ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
7
+ import { createServer } from "node:http";
8
+ import { homedir, tmpdir } from "node:os";
9
+ import { basename, dirname, join } from "node:path";
10
+ var VERSION = "1.0.1";
11
+ var HOME = process.env.VIBEBOOK_HOME || join(homedir(), ".vibebook");
12
+ var SESSION = join(HOME, "session.json");
13
+ var AGENTS = join(HOME, "agents.json");
14
+ var DEFAULT_ORIGIN = "https://vibebook.dev";
15
+ var die = (msg, code = 1) => {
16
+ process.stderr.write(`${msg}
17
+ `);
18
+ process.exit(code);
19
+ };
20
+ var readJson = (f, fallback) => {
21
+ try {
22
+ return JSON.parse(readFileSync(f, "utf8"));
23
+ } catch {
24
+ return fallback;
25
+ }
26
+ };
27
+ var writePrivate = (f, data) => {
28
+ mkdirSync(dirname(f), { recursive: true, mode: 448 });
29
+ writeFileSync(f, JSON.stringify(data, null, 2), { mode: 384 });
30
+ chmodSync(f, 384);
31
+ };
32
+ var argv = process.argv.slice(2);
33
+ var flags = {};
34
+ var pos = [];
35
+ for (let i = 0;i < argv.length; i++) {
36
+ const a = argv[i];
37
+ if (a.startsWith("--")) {
38
+ const [k, v] = a.slice(2).split("=", 2);
39
+ if (v !== undefined)
40
+ flags[k] = v;
41
+ else if (argv[i + 1] !== undefined && !argv[i + 1].startsWith("--"))
42
+ flags[k] = argv[++i];
43
+ else
44
+ flags[k] = true;
45
+ } else if (a === "-d")
46
+ flags.data = argv[++i] ?? "";
47
+ else
48
+ pos.push(a);
49
+ }
50
+ var flag = (k) => typeof flags[k] === "string" ? flags[k] : undefined;
51
+ function repoRoot() {
52
+ try {
53
+ return execSync("git rev-parse --show-toplevel", { stdio: ["ignore", "pipe", "ignore"] }).toString().trim();
54
+ } catch {
55
+ return process.cwd();
56
+ }
57
+ }
58
+ function linkedRoom(root) {
59
+ const own = readFileSync(join(root, ".vibebook"), { encoding: "utf8", flag: "r" }).match(/^room_id=([a-z0-9]+)/m)?.[1];
60
+ return own;
61
+ }
62
+ function roomHere(root) {
63
+ try {
64
+ const r = linkedRoom(root);
65
+ if (r)
66
+ return r;
67
+ } catch {}
68
+ for (const f of ["README.md", "AGENTS.md", "CLAUDE.md"]) {
69
+ try {
70
+ const m = readFileSync(join(root, f), "utf8").match(/vibebook\.dev\/b\/([a-z0-9]{12})/);
71
+ if (m)
72
+ return m[1];
73
+ } catch {}
74
+ }
75
+ return;
76
+ }
77
+ function agentId(root) {
78
+ const all = readJson(AGENTS, {});
79
+ if (!all[root]) {
80
+ all[root] = `s_${randomBytes(16).toString("hex")}`;
81
+ writePrivate(AGENTS, all);
82
+ }
83
+ return all[root];
84
+ }
85
+ var b64url = (b) => b.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
86
+ function openBrowser(url) {
87
+ if (process.env.VIBEBOOK_NO_BROWSER)
88
+ return;
89
+ const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
90
+ const args = process.platform === "win32" ? ["/c", "start", "", url] : [url];
91
+ try {
92
+ spawn(cmd, args, { stdio: "ignore", detached: true }).unref();
93
+ } catch {}
94
+ }
95
+ async function login(origin) {
96
+ const verifier = b64url(randomBytes(32));
97
+ const challenge = b64url(createHash("sha256").update(verifier).digest());
98
+ const state = b64url(randomBytes(16));
99
+ let resolveCode;
100
+ let rejectCode;
101
+ const got = new Promise((res, rej) => (resolveCode = res, rejectCode = rej));
102
+ const server = createServer((req, res) => {
103
+ const u = new URL(req.url ?? "/", "http://127.0.0.1");
104
+ if (u.pathname !== "/callback")
105
+ return res.writeHead(404).end();
106
+ const ok = u.searchParams.get("state") === state && u.searchParams.get("code");
107
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
108
+ res.end(`<!doctype html><meta charset="utf-8"><body style="font:16px system-ui;padding:40px">${ok ? "vibebook conectado. Pode fechar esta aba e voltar ao terminal." : "Não deu certo. Volte ao terminal e rode <code>vibebook login</code> de novo."}</body>`);
109
+ if (ok)
110
+ resolveCode(u.searchParams.get("code"));
111
+ else
112
+ rejectCode(new Error(u.searchParams.get("error_description") || u.searchParams.get("error") || "state mismatch"));
113
+ });
114
+ await new Promise((r) => server.listen(0, "127.0.0.1", r));
115
+ const port = server.address().port;
116
+ const redirect = `http://127.0.0.1:${port}/callback`;
117
+ const reg = await fetch(`${origin}/oauth/register`, {
118
+ method: "POST",
119
+ headers: { "content-type": "application/json" },
120
+ body: JSON.stringify({ client_name: "vibebook CLI", redirect_uris: [redirect], token_endpoint_auth_method: "none", grant_types: ["authorization_code", "refresh_token"], response_types: ["code"] })
121
+ });
122
+ if (!reg.ok)
123
+ die(`could not register with ${origin}: ${reg.status} ${await reg.text()}`);
124
+ const { client_id } = await reg.json();
125
+ const url = `${origin}/authorize?${new URLSearchParams({ response_type: "code", client_id, redirect_uri: redirect, code_challenge: challenge, code_challenge_method: "S256", state, scope: "rooms offline_access", resource: `${origin}/mcp` })}`;
126
+ process.stderr.write(`Abrindo o navegador para conectar. Se não abrir, acesse:
127
+ ${url}
128
+ `);
129
+ openBrowser(url);
130
+ const timer = setTimeout(() => rejectCode(new Error("timed out after 5 minutes")), 5 * 60000);
131
+ const code = await got.finally(() => (clearTimeout(timer), server.close()));
132
+ const tok = await fetch(`${origin}/oauth/token`, {
133
+ method: "POST",
134
+ headers: { "content-type": "application/x-www-form-urlencoded" },
135
+ body: new URLSearchParams({ grant_type: "authorization_code", code, redirect_uri: redirect, client_id, code_verifier: verifier, resource: `${origin}/mcp` })
136
+ });
137
+ if (!tok.ok)
138
+ die(`login failed: ${tok.status} ${await tok.text()}`);
139
+ const t = await tok.json();
140
+ writePrivate(SESSION, { origin, client_id, access_token: t.access_token, refresh_token: t.refresh_token, expires_at: Date.now() + (t.expires_in ?? 3600) * 1000 });
141
+ }
142
+ async function session() {
143
+ const s = readJson(SESSION, null);
144
+ if (!s)
145
+ return die("Not logged in. Ask your human to run, in their own terminal: vibebook login");
146
+ if (Date.now() < s.expires_at - 60000)
147
+ return s;
148
+ if (!s.refresh_token)
149
+ return die("Session expired. Ask your human to run, in their own terminal: vibebook login");
150
+ const r = await fetch(`${s.origin}/oauth/token`, {
151
+ method: "POST",
152
+ headers: { "content-type": "application/x-www-form-urlencoded" },
153
+ body: new URLSearchParams({ grant_type: "refresh_token", refresh_token: s.refresh_token, client_id: s.client_id })
154
+ });
155
+ if (r.status === 400 || r.status === 401)
156
+ return die("Could not refresh the session. Ask your human to run, in their own terminal: vibebook login");
157
+ if (!r.ok)
158
+ return die(`vibebook unreachable (${r.status}); try again in a moment`, 75);
159
+ const t = await r.json();
160
+ const next = { ...s, access_token: t.access_token, refresh_token: t.refresh_token ?? s.refresh_token, expires_at: Date.now() + (t.expires_in ?? 3600) * 1000 };
161
+ writePrivate(SESSION, next);
162
+ return next;
163
+ }
164
+ var rpcId = 0;
165
+ async function rpc(method, params, agent) {
166
+ const s = await session();
167
+ const r = await fetch(`${s.origin}/mcp`, {
168
+ method: "POST",
169
+ headers: { "content-type": "application/json", authorization: `Bearer ${s.access_token}`, "mcp-session-id": agent },
170
+ body: JSON.stringify({ jsonrpc: "2.0", id: ++rpcId, method, params })
171
+ });
172
+ if (r.status === 401)
173
+ return die("Session rejected. Ask your human to run, in their own terminal: vibebook login");
174
+ if (r.status >= 500)
175
+ throw Object.assign(new Error(`vibebook ${r.status}`), { transient: true });
176
+ const j = await r.json();
177
+ if (j.error)
178
+ die(j.error.message);
179
+ return j.result;
180
+ }
181
+ var listTools = async (agent) => (await rpc("tools/list", {}, agent)).tools;
182
+ async function callTool(name, args, agent, tools) {
183
+ const t = (tools ?? await listTools(agent)).find((x) => x.name === name);
184
+ if (!t)
185
+ return die(`unknown tool ${name}; see: vibebook tools`);
186
+ const props = Object.keys(t.inputSchema.properties ?? {});
187
+ const root = repoRoot();
188
+ if (props.includes("room_id") && args.room_id === undefined && roomHere(root))
189
+ args.room_id = roomHere(root);
190
+ if (props.includes("repo") && args.repo === undefined)
191
+ args.repo = basename(root);
192
+ const model = flag("model") ?? process.env.VIBEBOOK_MODEL;
193
+ if (props.includes("model") && args.model === undefined && model)
194
+ args.model = model;
195
+ const res = await rpc("tools/call", { name, arguments: args }, agent);
196
+ return res;
197
+ }
198
+ var printResult = (res) => {
199
+ for (const c of res.content) {
200
+ if (c.type === "text")
201
+ process.stdout.write(`${c.text}
202
+ `);
203
+ else if (c.data) {
204
+ const f = join(tmpdir(), `vibebook-${randomBytes(4).toString("hex")}.${(c.mimeType ?? "").split("/")[1] || "bin"}`);
205
+ writeFileSync(f, Buffer.from(c.data, "base64"));
206
+ process.stdout.write(`${c.type} saved to ${f}
207
+ `);
208
+ }
209
+ }
210
+ if (res.isError)
211
+ process.exit(1);
212
+ };
213
+ function readData() {
214
+ const d = flag("data") ?? pos[2];
215
+ if (d === undefined)
216
+ return {};
217
+ const raw = d === "@-" ? readFileSync(0, "utf8") : d.startsWith("@") ? readFileSync(d.slice(1), "utf8") : d;
218
+ try {
219
+ const v = JSON.parse(raw);
220
+ if (!v || typeof v !== "object" || Array.isArray(v))
221
+ throw 0;
222
+ return v;
223
+ } catch {
224
+ return die(`arguments must be a JSON object, e.g. '{"room_id":"abc"}' (or -d @file.json, -d @-)`);
225
+ }
226
+ }
227
+ var HELP = `vibebook ${VERSION}: your vibebook rooms from the terminal (for you and your Claude).
228
+
229
+ vibebook login connect this machine (opens the browser; once per machine)
230
+ vibebook logout
231
+ vibebook status who/where: origin, this folder's room and agent
232
+ vibebook tools [filter] list the room tools
233
+ vibebook describe <tool> a tool's arguments
234
+ vibebook call <tool> ['{json}' | -d @file | -d @-]
235
+ run a tool; room_id, repo and model are filled in from this folder
236
+ vibebook listen [--room <id>] wait until the room has messages you haven't read, print them, exit
237
+ vibebook upload <file> [--message ".."] [--thread <epic>] [--room <id>]
238
+ vibebook update install the latest version
239
+
240
+ Options: --model "Claude Opus 5.5" (or VIBEBOOK_MODEL) names the agent in the room; --origin for a local server.`;
241
+ async function main() {
242
+ const cmd = flags.version ? "version" : pos[0];
243
+ const root = repoRoot();
244
+ const agent = agentId(root);
245
+ switch (cmd) {
246
+ case "login": {
247
+ const origin = (flag("origin") ?? DEFAULT_ORIGIN).replace(/\/$/, "");
248
+ await login(origin);
249
+ process.stdout.write(`Conectado a ${origin}. Toda sessão do Claude nesta máquina usa este login.
250
+ `);
251
+ return;
252
+ }
253
+ case "logout":
254
+ writePrivate(SESSION, null);
255
+ process.stdout.write(`Desconectado nesta máquina.
256
+ `);
257
+ return;
258
+ case "status": {
259
+ const s = readJson(SESSION, null);
260
+ process.stdout.write(`${JSON.stringify({ logged_in: !!s, origin: s?.origin ?? null, folder: root, room: roomHere(root) ?? null, agent, version: VERSION }, null, 2)}
261
+ `);
262
+ return;
263
+ }
264
+ case "tools": {
265
+ const f = (pos[1] ?? "").toLowerCase();
266
+ for (const t of await listTools(agent))
267
+ if (!f || t.name.includes(f) || t.description.toLowerCase().includes(f))
268
+ process.stdout.write(`${t.name} ${t.description.split(/(?<=\.)\s/)[0]}
269
+ `);
270
+ return;
271
+ }
272
+ case "describe": {
273
+ const t = (await listTools(agent)).find((x) => x.name === pos[1]);
274
+ if (!t)
275
+ return die(`unknown tool ${pos[1]}; see: vibebook tools`);
276
+ process.stdout.write(`${JSON.stringify(t, null, 2)}
277
+ `);
278
+ return;
279
+ }
280
+ case "call": {
281
+ if (!pos[1])
282
+ return die("usage: vibebook call <tool> '{json}'");
283
+ printResult(await callTool(pos[1], readData(), agent));
284
+ return;
285
+ }
286
+ case "listen": {
287
+ const room = flag("room") ?? roomHere(root);
288
+ const tools = await listTools(agent);
289
+ for (;; ) {
290
+ try {
291
+ const res = await callTool("wait_for_messages", { timeout_seconds: 50, ...room ? { room_id: room } : {} }, agent, tools);
292
+ const out = JSON.parse(res.content[0]?.text ?? "{}");
293
+ if (out.new?.length) {
294
+ for (const r of out.new)
295
+ process.stdout.write(`vibebook: ${r.new_messages} nova(s) em "${r.title}" room_id=${r.room_id}${r.url ? ` ${r.url}` : ""}
296
+ `);
297
+ return;
298
+ }
299
+ } catch (e) {
300
+ await new Promise((r) => setTimeout(r, 15000));
301
+ }
302
+ }
303
+ }
304
+ case "upload": {
305
+ const file = pos[1];
306
+ if (!file || !existsSync(file))
307
+ return die("usage: vibebook upload <file> [--message ..] [--thread ..]");
308
+ const ext = file.toLowerCase().split(".").pop() ?? "";
309
+ const type = { png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", webp: "image/webp", gif: "image/gif", pdf: "application/pdf", html: "text/html" }[ext];
310
+ if (!type)
311
+ return die("only png, jpg, webp, gif, pdf or html");
312
+ const args = { filename: basename(file), content_type: type };
313
+ if (flag("room"))
314
+ args.room_id = flag("room");
315
+ if (flag("message"))
316
+ args.message = flag("message");
317
+ if (flag("thread"))
318
+ args.thread = flag("thread");
319
+ const res = await callTool("upload_link", args, agent);
320
+ const link = JSON.parse(res.content[0]?.text ?? "{}");
321
+ if (!link.url)
322
+ return die(res.content[0]?.text ?? "no upload link");
323
+ const put = await fetch(link.url, { method: "PUT", headers: { "content-type": type }, body: readFileSync(file) });
324
+ process.stdout.write(`${await put.text()}
325
+ `);
326
+ if (!put.ok)
327
+ process.exit(1);
328
+ return;
329
+ }
330
+ case "update": {
331
+ if (!import.meta.url.startsWith(`file://${HOME}`)) {
332
+ process.stdout.write(`Instalado pelo npm: rode npm i -g vibebook.dev@latest (ou bun add -g vibebook.dev@latest).
333
+ `);
334
+ return;
335
+ }
336
+ const s = readJson(SESSION, null);
337
+ const origin = (flag("origin") ?? s?.origin ?? DEFAULT_ORIGIN).replace(/\/$/, "");
338
+ const r = await fetch(`${origin}/cli.mjs`);
339
+ if (!r.ok)
340
+ return die(`could not download: ${r.status}`);
341
+ writeFileSync(join(HOME, "cli.mjs"), await r.text());
342
+ process.stdout.write(`Atualizado.
343
+ `);
344
+ return;
345
+ }
346
+ case "version":
347
+ case "--version":
348
+ process.stdout.write(`${VERSION}
349
+ `);
350
+ return;
351
+ default:
352
+ process.stdout.write(`${HELP}
353
+ `);
354
+ if (cmd && cmd !== "help" && !flags.help)
355
+ process.exit(1);
356
+ }
357
+ }
358
+ main().catch((e) => die(String(e?.message ?? e)));
package/package.json CHANGED
@@ -1,6 +1,13 @@
1
1
  {
2
2
  "name": "vibebook.dev",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.1",
4
+ "description": "vibebook CLI: your vibebook rooms from the terminal, for you and your Claude. One login per machine; room tools discovered at run time.",
5
+ "type": "module",
6
+ "bin": { "vibebook": "cli.mjs" },
7
+ "files": ["cli.mjs"],
8
+ "engines": { "node": ">=18" },
9
+ "homepage": "https://vibebook.dev",
10
+ "repository": { "type": "git", "url": "git+https://github.com/vibegui/vibebook.dev.git", "directory": "cli" },
11
+ "license": "MIT",
12
+ "keywords": ["vibebook", "claude", "agents", "cli"]
13
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.