vibebook.dev 1.0.1 → 1.2.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.
Files changed (2) hide show
  1. package/cli.mjs +505 -28
  2. package/package.json +1 -1
package/cli.mjs CHANGED
@@ -1,17 +1,18 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // cli/vibebook.ts
4
- import { execSync, spawn } from "node:child_process";
4
+ import { execFileSync, execSync, spawn } from "node:child_process";
5
5
  import { createHash, randomBytes } from "node:crypto";
6
- import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
6
+ import { appendFileSync, chmodSync, closeSync, existsSync, fstatSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
7
7
  import { createServer } from "node:http";
8
8
  import { homedir, tmpdir } from "node:os";
9
9
  import { basename, dirname, join } from "node:path";
10
- var VERSION = "1.0.1";
10
+ var VERSION = "1.2.0";
11
11
  var HOME = process.env.VIBEBOOK_HOME || join(homedir(), ".vibebook");
12
12
  var SESSION = join(HOME, "session.json");
13
13
  var AGENTS = join(HOME, "agents.json");
14
14
  var DEFAULT_ORIGIN = "https://vibebook.dev";
15
+ var HERDR = join(HOME, "herdr.json");
15
16
  var die = (msg, code = 1) => {
16
17
  process.stderr.write(`${msg}
17
18
  `);
@@ -26,8 +27,10 @@ var readJson = (f, fallback) => {
26
27
  };
27
28
  var writePrivate = (f, data) => {
28
29
  mkdirSync(dirname(f), { recursive: true, mode: 448 });
29
- writeFileSync(f, JSON.stringify(data, null, 2), { mode: 384 });
30
- chmodSync(f, 384);
30
+ const tmp = `${f}.${process.pid}.tmp`;
31
+ writeFileSync(tmp, JSON.stringify(data, null, 2), { mode: 384 });
32
+ chmodSync(tmp, 384);
33
+ renameSync(tmp, f);
31
34
  };
32
35
  var argv = process.argv.slice(2);
33
36
  var flags = {};
@@ -55,10 +58,7 @@ function repoRoot() {
55
58
  return process.cwd();
56
59
  }
57
60
  }
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
- }
61
+ var linkedRoom = (root) => readFileSync(join(root, ".vibebook"), "utf8").match(/^room_id=([a-z0-9]+)/m)?.[1];
62
62
  function roomHere(root) {
63
63
  try {
64
64
  const r = linkedRoom(root);
@@ -139,34 +139,128 @@ ${url}
139
139
  const t = await tok.json();
140
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
141
  }
142
+ var fresh = (s) => !!s && Date.now() < s.expires_at - 60000;
142
143
  async function session() {
143
- const s = readJson(SESSION, null);
144
+ let s = readJson(SESSION, null);
144
145
  if (!s)
145
146
  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
+ if (fresh(s))
147
148
  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;
149
+ const lock = `${SESSION}.lock`;
150
+ for (let i = 0;; i++) {
151
+ try {
152
+ mkdirSync(lock);
153
+ break;
154
+ } catch {
155
+ try {
156
+ if (Date.now() - statSync(lock).mtimeMs > 30000)
157
+ rmSync(lock, { recursive: true, force: true });
158
+ } catch {}
159
+ if (i > 100)
160
+ return die("vibebook session is locked by another process; try again in a moment", 75);
161
+ await new Promise((r) => setTimeout(r, 100));
162
+ const again = readJson(SESSION, null);
163
+ if (fresh(again))
164
+ return again;
165
+ }
166
+ }
167
+ const quit = (m, code) => (rmSync(lock, { recursive: true, force: true }), die(m, code));
168
+ try {
169
+ s = readJson(SESSION, null) ?? s;
170
+ if (fresh(s))
171
+ return s;
172
+ if (!s.refresh_token)
173
+ return quit("Session expired. Ask your human to run, in their own terminal: vibebook login");
174
+ const r = await fetch(`${s.origin}/oauth/token`, {
175
+ method: "POST",
176
+ headers: { "content-type": "application/x-www-form-urlencoded" },
177
+ body: new URLSearchParams({ grant_type: "refresh_token", refresh_token: s.refresh_token, client_id: s.client_id })
178
+ });
179
+ if (r.status === 400 || r.status === 401)
180
+ return quit("Could not refresh the session. Ask your human to run, in their own terminal: vibebook login");
181
+ if (!r.ok)
182
+ return quit(`vibebook unreachable (${r.status}); try again in a moment`, 75);
183
+ const t = await r.json();
184
+ 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 };
185
+ writePrivate(SESSION, next);
186
+ return next;
187
+ } finally {
188
+ rmSync(lock, { recursive: true, force: true });
189
+ }
163
190
  }
191
+ var CTX_WINDOW = Number(process.env.VIBEBOOK_CONTEXT_WINDOW) || 1e6;
192
+ function sessionContext(sid) {
193
+ if (!/^[\w-]{8,80}$/.test(sid))
194
+ return;
195
+ try {
196
+ const root = join(homedir(), ".claude", "projects");
197
+ const dir = readdirSync(root).find((d) => existsSync(join(root, d, `${sid}.jsonl`)));
198
+ if (!dir)
199
+ return;
200
+ const fd = openSync(join(root, dir, `${sid}.jsonl`), "r");
201
+ const size = fstatSync(fd).size;
202
+ const n = Math.min(size, 4 << 20);
203
+ const buf = Buffer.alloc(n);
204
+ readSync(fd, buf, 0, n, size - n);
205
+ closeSync(fd);
206
+ const lines = buf.toString("utf8").split(`
207
+ `);
208
+ for (let i = lines.length - 1;i >= 0; i--) {
209
+ if (lines[i].includes('"compact_boundary"'))
210
+ return { tokens: 0, window: CTX_WINDOW };
211
+ if (!lines[i].includes('"usage"'))
212
+ continue;
213
+ try {
214
+ const u = JSON.parse(lines[i])?.message?.usage;
215
+ if (u)
216
+ return { tokens: (u.input_tokens || 0) + (u.cache_read_input_tokens || 0) + (u.cache_creation_input_tokens || 0), window: CTX_WINDOW };
217
+ } catch {}
218
+ }
219
+ } catch {}
220
+ }
221
+ var STATUS = join(HOME, "status");
222
+ function statusline() {
223
+ const input = readFileSync(0);
224
+ try {
225
+ const j = JSON.parse(input.toString());
226
+ if (/^[\w-]{8,80}$/.test(j.session_id ?? "")) {
227
+ const limits = {};
228
+ for (const k of ["five_hour", "seven_day"]) {
229
+ const l = j.rate_limits?.[k];
230
+ if (typeof l?.used_percentage === "number")
231
+ limits[k] = { p: Math.round(l.used_percentage), r: Number(l.resets_at) || 0 };
232
+ }
233
+ mkdirSync(STATUS, { recursive: true });
234
+ writeFileSync(join(STATUS, `${j.session_id}.json`), JSON.stringify({ window: Number(j.context_window?.context_window_size) || undefined, limits, at: Date.now() }));
235
+ }
236
+ } catch {}
237
+ const rest = process.argv.slice(process.argv.indexOf("statusline") + 1).join(" ").trim();
238
+ if (rest)
239
+ process.stdout.write(execSync(rest, { input, stdio: ["pipe", "pipe", "ignore"] }));
240
+ }
241
+ var sessionStatus = (sid) => {
242
+ if (!/^[\w-]{8,80}$/.test(sid))
243
+ return;
244
+ const s = readJson(join(STATUS, `${sid}.json`), null);
245
+ return s && Date.now() - s.at < 6 * 3600000 ? s : undefined;
246
+ };
247
+ var myContext = () => {
248
+ const sid = process.env.CLAUDE_CODE_SESSION_ID;
249
+ const c = sid ? sessionContext(sid) : undefined;
250
+ if (!sid || !c)
251
+ return {};
252
+ const st = sessionStatus(sid);
253
+ const h = { "x-vibebook-context": `${c.tokens}/${st?.window ?? c.window}` };
254
+ if (st?.limits && Object.keys(st.limits).length)
255
+ h["x-vibebook-limits"] = JSON.stringify(st.limits);
256
+ return h;
257
+ };
164
258
  var rpcId = 0;
165
259
  async function rpc(method, params, agent) {
166
260
  const s = await session();
167
261
  const r = await fetch(`${s.origin}/mcp`, {
168
262
  method: "POST",
169
- headers: { "content-type": "application/json", authorization: `Bearer ${s.access_token}`, "mcp-session-id": agent },
263
+ headers: { "content-type": "application/json", authorization: `Bearer ${s.access_token}`, "mcp-session-id": agent, ...myContext() },
170
264
  body: JSON.stringify({ jsonrpc: "2.0", id: ++rpcId, method, params })
171
265
  });
172
266
  if (r.status === 401)
@@ -224,6 +318,334 @@ function readData() {
224
318
  return die(`arguments must be a JSON object, e.g. '{"room_id":"abc"}' (or -d @file.json, -d @-)`);
225
319
  }
226
320
  }
321
+ var COMPACT_AT = Number(process.env.VIBEBOOK_COMPACT_AT) || 0.75;
322
+ var herdr = (...args) => JSON.parse(execFileSync("herdr", args, { stdio: ["ignore", "pipe", "pipe"] }).toString()).result;
323
+ var PROJECTS = join(homedir(), "Projects");
324
+ var LISTEN_PROMPT = 'Ouça a sala do vibebook desta pasta: rode `vibebook listen --model "<seu modelo>"` em background (Bash run_in_background); quando ele sair, `vibebook call read_room`, aja nas mensagens from_your_human e volte a ouvir. (Com o plugin, é o /vibebook:listen.)';
325
+ var slug = (t) => t.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 40) || "sala";
326
+ function roomFolder(room, title) {
327
+ const look = (dir, depth) => {
328
+ let names = [];
329
+ try {
330
+ names = readdirSync(dir);
331
+ } catch {
332
+ return;
333
+ }
334
+ if (names.includes(".vibebook")) {
335
+ try {
336
+ if (linkedRoom(dir) === room)
337
+ return dir;
338
+ } catch {}
339
+ }
340
+ if (depth === 0)
341
+ return;
342
+ for (const n of names)
343
+ if (!n.startsWith(".") && n !== "node_modules" && n !== "_archive") {
344
+ const f = look(join(dir, n), depth - 1);
345
+ if (f)
346
+ return f;
347
+ }
348
+ };
349
+ return look(PROJECTS, 2) ?? join(PROJECTS, slug(title));
350
+ }
351
+ function linkFolder(folder, room) {
352
+ mkdirSync(folder, { recursive: true });
353
+ const f = join(folder, ".vibebook");
354
+ try {
355
+ if (linkedRoom(folder) === room)
356
+ return;
357
+ } catch {}
358
+ writeFileSync(f, `room_id=${room}
359
+ `);
360
+ const exclude = join(folder, ".git", "info", "exclude");
361
+ if (existsSync(exclude) && !readFileSync(exclude, "utf8").split(`
362
+ `).includes(".vibebook"))
363
+ appendFileSync(exclude, `
364
+ .vibebook
365
+ `);
366
+ }
367
+ function terminalApp() {
368
+ try {
369
+ for (const pid of execFileSync("pgrep", ["-x", "herdr"]).toString().split(/\s+/).filter(Boolean)) {
370
+ let p = pid;
371
+ for (let i = 0;i < 10 && p && p !== "1"; i++) {
372
+ const [ppid, ...cmd] = execFileSync("ps", ["-o", "ppid=,comm=", "-p", p]).toString().trim().split(/\s+/);
373
+ const app = cmd.join(" ").match(/^(.*?\.app)\/Contents\/MacOS\//)?.[1];
374
+ if (app)
375
+ return app;
376
+ p = ppid;
377
+ }
378
+ }
379
+ } catch {}
380
+ }
381
+ function herdrServer(appMode = false) {
382
+ const allowed = new Set([readJson(SESSION, null)?.origin ?? DEFAULT_ORIGIN, DEFAULT_ORIGIN]);
383
+ const port = Number(process.env.VIBEBOOK_HERDR_PORT || 47321);
384
+ createServer((req, res) => {
385
+ const origin = req.headers.origin ?? "";
386
+ const send = (code, body) => {
387
+ res.writeHead(code, { "content-type": "application/json", ...allowed.has(origin) ? { "access-control-allow-origin": origin, "access-control-allow-private-network": "true", vary: "origin" } : {} });
388
+ res.end(JSON.stringify(body));
389
+ };
390
+ if (!allowed.has(origin) || req.headers.host !== `127.0.0.1:${port}`)
391
+ return send(403, { error: "origin" });
392
+ if (req.method === "OPTIONS")
393
+ return send(204, null);
394
+ const u = new URL(req.url ?? "/", "http://127.0.0.1");
395
+ const map = readJson(appMode ? HERDR_APP : HERDR, {});
396
+ const target = (r) => appMode ? map[r]?.space : map[r]?.workspace;
397
+ if (u.pathname === "/ping")
398
+ return send(200, { ok: true, rooms: Object.keys(map).filter((r) => target(r)) });
399
+ if (u.pathname === "/where") {
400
+ const room = u.searchParams.get("room") ?? "";
401
+ if (!/^[a-z0-9]{6,40}$/.test(room))
402
+ return send(400, { error: "room" });
403
+ const folder = map[room]?.folder ?? roomFolder(room, (u.searchParams.get("title") ?? "").slice(0, 200));
404
+ const how = map[room]?.folder ? "used" : (() => {
405
+ try {
406
+ return linkedRoom(folder) === room;
407
+ } catch {
408
+ return false;
409
+ }
410
+ })() ? "linked" : existsSync(folder) ? "slug" : "new";
411
+ return send(200, { folder, home: homedir(), how });
412
+ }
413
+ if (u.pathname !== "/focus")
414
+ return send(404, { error: "not found" });
415
+ const ws = target(u.searchParams.get("room") ?? "");
416
+ if (!ws)
417
+ return send(404, { error: "Nenhum Claude aberto pra essa sala no herdr." });
418
+ try {
419
+ if (appMode) {
420
+ happ("do", "space.select", "--id", ws);
421
+ execFileSync("open", ["-a", "Herdr"]);
422
+ return send(200, { ok: true });
423
+ }
424
+ herdr("workspace", "focus", ws);
425
+ const app = terminalApp();
426
+ if (app)
427
+ execFileSync("open", ["-a", app]);
428
+ send(200, { ok: true });
429
+ } catch (e) {
430
+ send(500, { error: String(e.message ?? e) });
431
+ }
432
+ }).on("error", (e) => process.stderr.write(`vibebook herdr: botão "ir pro Claude" desligado (${e.message})
433
+ `)).listen(port, "127.0.0.1");
434
+ }
435
+ async function herdrSync(agent, tools) {
436
+ const res = await callTool("claude_rooms", {}, agent, tools);
437
+ const rooms = JSON.parse(res.content[0]?.text ?? "{}").rooms ?? [];
438
+ const deaf = new Set(rooms.filter((r) => r.on && r.listening === false).map((r) => r.room_id));
439
+ const map = readJson(HERDR, {});
440
+ const live = new Set(herdr("workspace", "list").workspaces.map((w) => w.workspace_id));
441
+ const panes = herdr("pane", "list").panes;
442
+ const on = new Map(rooms.filter((r) => r.on).map((r) => [r.room_id, r.title]));
443
+ const log = (m) => process.stdout.write(`${new Date().toLocaleTimeString()} ${m}
444
+ `);
445
+ for (const [room, title] of on) {
446
+ const e = map[room] ??= {};
447
+ if (e.workspace && live.has(e.workspace)) {
448
+ if (!deaf.has(room))
449
+ delete e.deaf_since;
450
+ else
451
+ e.deaf_since ??= Date.now();
452
+ if (e.listening && e.deaf_since && Date.now() - e.deaf_since > 3 * 60000 && Date.now() - (e.prompted_at ?? 0) > 5 * 60000)
453
+ e.listening = false;
454
+ const cp = panes.find((x) => x.workspace_id === e.workspace && x.agent === "claude");
455
+ const cs = cp?.agent_session?.value;
456
+ const cx0 = cs ? sessionContext(cs) : undefined;
457
+ const cx = cx0 && cs ? { ...cx0, window: sessionStatus(cs)?.window ?? cx0.window } : undefined;
458
+ if (cp && cx && cx.tokens >= cx.window * COMPACT_AT && (cp.agent_status === "idle" || cp.agent_status === "done") && Date.now() - (e.compacted_at ?? 0) > 15 * 60000) {
459
+ try {
460
+ herdr("agent", "prompt", cp.pane_id, "/compact");
461
+ e.compacted_at = Date.now();
462
+ log(`${title}: contexto em ${Math.round(cx.tokens / cx.window * 100)}%, mandei /compact`);
463
+ } catch {}
464
+ continue;
465
+ }
466
+ if (!e.listening) {
467
+ const p = panes.find((x) => x.workspace_id === e.workspace && x.agent === "claude");
468
+ if (p && (p.agent_status === "idle" || p.agent_status === "done"))
469
+ try {
470
+ herdr("agent", "prompt", p.pane_id, LISTEN_PROMPT);
471
+ e.listening = true;
472
+ e.prompted_at = Date.now();
473
+ delete e.deaf_since;
474
+ log(`${title}: o Claude ficou livre, pedi pra ele ouvir a sala`);
475
+ } catch {}
476
+ }
477
+ continue;
478
+ }
479
+ e.listening = false;
480
+ e.folder ??= roomFolder(room, title);
481
+ linkFolder(e.folder, room);
482
+ const there = panes.find((p) => p.agent === "claude" && (p.cwd === e.folder || p.foreground_cwd === e.folder));
483
+ if (there) {
484
+ e.workspace = there.workspace_id;
485
+ try {
486
+ herdr("workspace", "rename", there.workspace_id, title.slice(0, 40));
487
+ } catch {}
488
+ log(`${title}: adotei o Claude que já estava em ${e.folder}`);
489
+ if (there.agent_status === "idle" || there.agent_status === "done")
490
+ try {
491
+ herdr("agent", "prompt", there.pane_id, LISTEN_PROMPT);
492
+ e.listening = true;
493
+ e.prompted_at = Date.now();
494
+ } catch {}
495
+ continue;
496
+ }
497
+ const w = herdr("workspace", "create", "--cwd", e.folder, "--label", title.slice(0, 40), "--no-focus");
498
+ e.workspace = w.workspace.workspace_id;
499
+ const args = ["agent", "start", `vb-${room}`, "--kind", "claude", "--pane", w.root_pane.pane_id, "--timeout", "60000", "--"];
500
+ if (e.session)
501
+ args.push("--resume", e.session);
502
+ e.listening = true;
503
+ e.prompted_at = Date.now();
504
+ writePrivate(HERDR, map);
505
+ try {
506
+ herdr(...args, "/vibebook:listen");
507
+ log(`${title}: abri um Claude em ${e.folder}${e.session ? " (retomando a conversa)" : ""}`);
508
+ } catch (err) {
509
+ log(`${title}: Claude aberto em ${e.folder}, esperando você confirmar no herdr (${String(err.stderr ?? err).match(/"message":"([^"]+)"/)?.[1] ?? "não ficou pronto"})`);
510
+ }
511
+ }
512
+ for (const [room, e] of Object.entries(map)) {
513
+ if (on.has(room) || !e.workspace)
514
+ continue;
515
+ if (live.has(e.workspace)) {
516
+ const p = panes.find((x) => x.workspace_id === e.workspace && x.agent === "claude");
517
+ if (p?.agent_session?.value)
518
+ e.session = p.agent_session.value;
519
+ herdr("workspace", "close", e.workspace);
520
+ log(`${rooms.find((r) => r.room_id === room)?.title ?? room}: Claude desligado, fechei a aba (a conversa fica pra retomar)`);
521
+ }
522
+ delete e.workspace;
523
+ }
524
+ writePrivate(HERDR, map);
525
+ herdrOrder([...on.keys()], map);
526
+ }
527
+ var HERDR_APP = join(HOME, "herdr-app.json");
528
+ var happ = (...args) => {
529
+ const r = JSON.parse(execFileSync("herdr-app", args, { stdio: ["ignore", "pipe", "pipe"] }).toString());
530
+ if (r?.error)
531
+ throw new Error(r.error);
532
+ return r;
533
+ };
534
+ var appClaude = (sp) => sp.tabs.flatMap((t) => t.terminals).find((t) => /claude/i.test(t.app ?? ""));
535
+ async function herdrAppSync(agent, tools) {
536
+ const res = await callTool("claude_rooms", {}, agent, tools);
537
+ const rooms = JSON.parse(res.content[0]?.text ?? "{}").rooms ?? [];
538
+ const deaf = new Set(rooms.filter((r) => r.on && r.listening === false).map((r) => r.room_id));
539
+ const map = readJson(HERDR_APP, {});
540
+ let spaces = happ("ls").spaces;
541
+ const live = new Set(spaces.map((x) => x.id));
542
+ const on = new Map(rooms.filter((r) => r.on).map((r) => [r.room_id, r.title]));
543
+ const log = (m) => process.stdout.write(`${new Date().toLocaleTimeString()} ${m}
544
+ `);
545
+ for (const [room, title] of on) {
546
+ const e = map[room] ??= {};
547
+ if (e.space && live.has(e.space)) {
548
+ if (!deaf.has(room))
549
+ delete e.deaf_since;
550
+ else
551
+ e.deaf_since ??= Date.now();
552
+ const c = appClaude(spaces.find((x) => x.id === e.space));
553
+ if (c && e.deaf_since && Date.now() - e.deaf_since > 3 * 60000 && Date.now() - (e.prompted_at ?? 0) > 5 * 60000 && (c.status === "idle" || c.status === "done"))
554
+ try {
555
+ execFileSync("hc", ["send", c.terminal, LISTEN_PROMPT], { stdio: "ignore" });
556
+ e.prompted_at = Date.now();
557
+ log(`${title}: ninguém ouvindo, pedi pro Claude ouvir a sala de novo`);
558
+ } catch {}
559
+ continue;
560
+ }
561
+ e.folder ??= roomFolder(room, title);
562
+ linkFolder(e.folder, room);
563
+ const there = spaces.find((x) => x.folder === e.folder && appClaude(x));
564
+ if (there) {
565
+ e.space = there.id;
566
+ try {
567
+ happ("do", "space.rename", "--id", there.id, "--name", title.slice(0, 40));
568
+ } catch {}
569
+ const c = appClaude(there);
570
+ if (c && (c.status === "idle" || c.status === "done"))
571
+ try {
572
+ execFileSync("hc", ["send", c.terminal, LISTEN_PROMPT], { stdio: "ignore" });
573
+ e.prompted_at = Date.now();
574
+ } catch {}
575
+ log(`${title}: adotei o Claude que já estava em ${e.folder}`);
576
+ continue;
577
+ }
578
+ const r = happ("do", "space.new", "--name", title.slice(0, 40), "--folder", e.folder, "--argv", JSON.stringify(["claude"]), "--task", "/vibebook:listen");
579
+ e.space = r.space;
580
+ e.prompted_at = Date.now();
581
+ log(`${title}: abri um Claude em ${e.folder}`);
582
+ }
583
+ for (const [room, e] of Object.entries(map)) {
584
+ if (on.has(room) || !e.space)
585
+ continue;
586
+ if (live.has(e.space)) {
587
+ happ("do", "space.close", "--id", e.space, "--confirmed", "true");
588
+ log(`${rooms.find((r) => r.room_id === room)?.title ?? room}: Claude desligado, fechei o space`);
589
+ }
590
+ delete e.space;
591
+ }
592
+ writePrivate(HERDR_APP, map);
593
+ spaces = happ("ls").spaces;
594
+ const want = [...on.keys()].map((r) => map[r]?.space).filter((x) => !!x && spaces.some((s) => s.id === x));
595
+ want.forEach((id, i) => {
596
+ if (spaces[i]?.id === id)
597
+ return;
598
+ happ("do", "space.move", "--id", id, "--index", String(i + 1));
599
+ spaces = happ("ls").spaces;
600
+ });
601
+ }
602
+ function herdrOrder(order, map) {
603
+ const list = herdr("workspace", "list").workspaces;
604
+ const ours = new Map(order.filter((r) => map[r]?.workspace).map((r) => [map[r].workspace, r]));
605
+ const current = list.map((w) => w.workspace_id);
606
+ const desired = [...order.map((r) => map[r]?.workspace).filter((w) => !!w && current.includes(w)), ...current.filter((w) => !ours.has(w))];
607
+ let i = 0;
608
+ while (i < desired.length && current[i] === desired[i])
609
+ i++;
610
+ if (i === desired.length)
611
+ return;
612
+ const focused = list.find((w) => w.focused)?.workspace_id;
613
+ let refocus;
614
+ const tabs = herdr("tab", "list").tabs;
615
+ for (const ws of desired.slice(i)) {
616
+ const room = ours.get(ws);
617
+ const panes = herdr("pane", "list").panes.filter((p) => p.workspace_id === ws);
618
+ let newWs;
619
+ const newTab = new Map;
620
+ for (const p of panes) {
621
+ const tabLabel = tabs.find((t) => t.tab_id === p.tab_id)?.label ?? "1";
622
+ let r;
623
+ if (!newWs)
624
+ r = herdr("pane", "move", p.pane_id, "--new-workspace", "--label", list.find((w) => w.workspace_id === ws)?.label ?? room ?? "1", "--tab-label", tabLabel);
625
+ else if (newTab.has(p.tab_id))
626
+ r = herdr("pane", "move", p.pane_id, "--tab", newTab.get(p.tab_id), "--split", "right", "--no-focus");
627
+ else
628
+ r = herdr("pane", "move", p.pane_id, "--new-tab", "--workspace", newWs, "--label", tabLabel, "--no-focus");
629
+ const moved = r.move_result.pane;
630
+ newWs = moved.workspace_id;
631
+ newTab.set(p.tab_id, moved.tab_id);
632
+ }
633
+ if (newWs) {
634
+ if (room)
635
+ map[room].workspace = newWs;
636
+ if (ws === focused)
637
+ refocus = newWs;
638
+ }
639
+ }
640
+ writePrivate(HERDR, map);
641
+ const back = refocus ?? focused;
642
+ if (back)
643
+ try {
644
+ herdr("workspace", "focus", back);
645
+ } catch {}
646
+ process.stdout.write(`${new Date().toLocaleTimeString()} reordenei ${desired.length - i} workspace(s): salas na ordem do vibebook, depois o resto
647
+ `);
648
+ }
227
649
  var HELP = `vibebook ${VERSION}: your vibebook rooms from the terminal (for you and your Claude).
228
650
 
229
651
  vibebook login connect this machine (opens the browser; once per machine)
@@ -235,11 +657,18 @@ var HELP = `vibebook ${VERSION}: your vibebook rooms from the terminal (for you
235
657
  run a tool; room_id, repo and model are filled in from this folder
236
658
  vibebook listen [--room <id>] wait until the room has messages you haven't read, print them, exit
237
659
  vibebook upload <file> [--message ".."] [--thread <epic>] [--room <id>]
660
+ vibebook herdr [--once] keep one Claude Code per room in herdr: opens it when you switch
661
+ "Meu Claude" on in the app, closes it when you switch it off
662
+ vibebook herdr --app the same in the Herdr desktop app: one space per room (not with the terminal one)
663
+ vibebook statusline [command] as Claude Code's statusLine: keeps the session's context window and plan
664
+ limits for the room, then runs your own statusline command (if any) with the same input
238
665
  vibebook update install the latest version
239
666
 
240
667
  Options: --model "Claude Opus 5.5" (or VIBEBOOK_MODEL) names the agent in the room; --origin for a local server.`;
241
668
  async function main() {
242
669
  const cmd = flags.version ? "version" : pos[0];
670
+ if (cmd === "statusline")
671
+ return statusline();
243
672
  const root = repoRoot();
244
673
  const agent = agentId(root);
245
674
  switch (cmd) {
@@ -291,8 +720,9 @@ async function main() {
291
720
  const res = await callTool("wait_for_messages", { timeout_seconds: 50, ...room ? { room_id: room } : {} }, agent, tools);
292
721
  const out = JSON.parse(res.content[0]?.text ?? "{}");
293
722
  if (out.new?.length) {
723
+ const title = (t) => (t ?? "").replace(/[\p{Cc}"`]/gu, " ").replace(/\s+/g, " ").trim().slice(0, 60);
294
724
  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}` : ""}
725
+ process.stdout.write(`vibebook: ${r.new_messages} nova(s) em "${title(r.title)}" room_id=${r.room_id}
296
726
  `);
297
727
  return;
298
728
  }
@@ -301,6 +731,53 @@ async function main() {
301
731
  }
302
732
  }
303
733
  }
734
+ case "herdr": {
735
+ const appMode = !!flags.app;
736
+ try {
737
+ if (appMode)
738
+ happ("ls");
739
+ else
740
+ execFileSync("herdr", ["status"], { stdio: "ignore" });
741
+ } catch {
742
+ return die(appMode ? "Herdr (the desktop app) isn't open, or herdr-app isn't installed (https://herdr.dev)" : "herdr not found or not running (https://herdr.dev)");
743
+ }
744
+ const lock = join(HOME, "herdr.pid");
745
+ const other = Number(existsSync(lock) ? readFileSync(lock, "utf8") : 0);
746
+ if (other && other !== process.pid) {
747
+ let alive = true;
748
+ try {
749
+ process.kill(other, 0);
750
+ } catch {
751
+ alive = false;
752
+ }
753
+ if (alive)
754
+ return die(`vibebook herdr is already running (pid ${other}); one per machine is enough`);
755
+ }
756
+ writeFileSync(lock, String(process.pid));
757
+ const release = () => {
758
+ try {
759
+ if (Number(readFileSync(lock, "utf8")) === process.pid)
760
+ unlinkSync(lock);
761
+ } catch {}
762
+ };
763
+ process.on("exit", release);
764
+ for (const sig of ["SIGINT", "SIGTERM", "SIGHUP"])
765
+ process.on(sig, () => process.exit(0));
766
+ const tools = await listTools(agent);
767
+ if (!flags.once)
768
+ herdrServer(appMode);
769
+ for (;; ) {
770
+ try {
771
+ await (appMode ? herdrAppSync : herdrSync)(agent, tools);
772
+ } catch (e) {
773
+ process.stderr.write(`vibebook herdr: ${String(e?.message ?? e)}
774
+ `);
775
+ }
776
+ if (flags.once)
777
+ return;
778
+ await new Promise((r) => setTimeout(r, 15000));
779
+ }
780
+ }
304
781
  case "upload": {
305
782
  const file = pos[1];
306
783
  if (!file || !existsSync(file))
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vibebook.dev",
3
- "version": "1.0.1",
3
+ "version": "1.2.0",
4
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
5
  "type": "module",
6
6
  "bin": { "vibebook": "cli.mjs" },