elsemeet-bridge 0.1.3 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,7 +3,7 @@
3
3
  // bridge/bridge.ts
4
4
  import { spawn, spawnSync } from "node:child_process";
5
5
  import { createHash, randomBytes } from "node:crypto";
6
- import { copyFileSync, createWriteStream, existsSync, mkdirSync, openSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
6
+ import { closeSync, copyFileSync, createWriteStream, existsSync, mkdirSync, openSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
7
7
  import { createServer } from "node:http";
8
8
  import { homedir } from "node:os";
9
9
  import { basename, dirname, join, resolve } from "node:path";
@@ -136,18 +136,45 @@ async function tokenRequest(s, params) {
136
136
  });
137
137
  if (!res.ok) throw new Error(`Sign-in failed (${res.status}): ${await res.text()}`);
138
138
  const t = await res.json();
139
- return { access_token: t.access_token, refresh_token: t.refresh_token };
139
+ return { access_token: t.access_token, refresh_token: t.refresh_token, expires_at: Date.now() + (t.expires_in ?? 3600) * 1e3 };
140
140
  }
141
+ async function withRefreshLock(fn) {
142
+ mkdirSync(HOME, { recursive: true });
143
+ const lock = file("refresh.lock");
144
+ const until = Date.now() + 2e4;
145
+ for (; ; ) {
146
+ try {
147
+ closeSync(openSync(lock, "wx"));
148
+ break;
149
+ } catch {
150
+ try {
151
+ if (Date.now() - statSync(lock).mtimeMs > 3e4) rmSync(lock, { force: true });
152
+ } catch {
153
+ }
154
+ if (Date.now() > until) throw new Error("Another Elsemeet Bridge process holds the sign-in; try again.");
155
+ await new Promise((r) => setTimeout(r, 200));
156
+ }
157
+ }
158
+ try {
159
+ return await fn();
160
+ } finally {
161
+ rmSync(lock, { force: true });
162
+ }
163
+ }
164
+ var lasts = (s, ms) => !!s.access_token && !!s.expires_at && s.expires_at - Date.now() > ms;
141
165
  var refreshing = null;
142
- function freshToken(stale) {
166
+ function freshToken(stale, need = 5 * 6e4) {
143
167
  refreshing ??= (async () => {
144
168
  try {
145
- const s = load();
146
- if (stale && s.access_token && s.access_token !== stale) return s.access_token;
147
- if (!s.refresh_token) return null;
148
- Object.assign(s, await tokenRequest(s, { grant_type: "refresh_token", refresh_token: s.refresh_token }));
149
- save(s);
150
- return s.access_token ?? null;
169
+ return await withRefreshLock(async () => {
170
+ const s = load();
171
+ if (stale && s.access_token && s.access_token !== stale) return s.access_token;
172
+ if (!stale && lasts(s, need)) return s.access_token ?? null;
173
+ if (!s.refresh_token) return null;
174
+ Object.assign(s, await tokenRequest(s, { grant_type: "refresh_token", refresh_token: s.refresh_token }));
175
+ save(s);
176
+ return s.access_token ?? null;
177
+ });
151
178
  } catch {
152
179
  return null;
153
180
  } finally {
@@ -178,6 +205,29 @@ async function api(path, query = {}, timeoutMs = 3e4) {
178
205
  return await res.json();
179
206
  }
180
207
  }
208
+ async function apiPost(path, body) {
209
+ const s = load();
210
+ let token = s.access_token ?? "";
211
+ for (let attempt = 0; ; attempt++) {
212
+ const res = await fetch(`${s.server}${path}`, {
213
+ method: "POST",
214
+ headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
215
+ body: JSON.stringify(body),
216
+ signal: AbortSignal.timeout(3e4)
217
+ });
218
+ if (res.status === 401 && attempt === 0) {
219
+ const t = await freshToken(token);
220
+ if (t) {
221
+ token = t;
222
+ continue;
223
+ }
224
+ }
225
+ if (res.status === 401) throw new SignedOut(SIGNED_OUT);
226
+ const out = await res.json().catch(() => ({}));
227
+ if (!res.ok) throw new Error(out.message ?? `${res.status}`);
228
+ return out;
229
+ }
230
+ }
181
231
  function normalizeRepo(u) {
182
232
  return u.trim().toLowerCase().replace(/^git\+/, "").replace(/^[a-z]+:\/\//, "").replace(/^[^@/]+@/, "").replace(/^([^/:]+):(?!\d)/, "$1/").replace(/\.git$/, "").replace(/\/+$/, "");
183
233
  }
@@ -241,7 +291,7 @@ async function startAgent(productId, p, pushYes) {
241
291
  if (!PROJECT_ID.test(productId)) throw new Error(`Not a project id: ${productId}`);
242
292
  const how = resolveAgent(p.agent);
243
293
  if (!how) throw new Error(`${AGENTS[p.agent].command} is not installed here any more: install Claude Code again.`);
244
- const token = await freshToken();
294
+ const token = await freshToken(void 0, 55 * 6e4);
245
295
  if (!token) throw new SignedOut(SIGNED_OUT);
246
296
  mkdirSync(file("run"), { recursive: true });
247
297
  const mcpFile = file(`run/${productId}.mcp.json`);
@@ -303,6 +353,21 @@ async function watch(productId, stop) {
303
353
  if (!p) return log(`${productId}: no longer connected here; stopped watching it.`);
304
354
  const name = p.name ?? productId;
305
355
  try {
356
+ if (p.set_up) {
357
+ let capped2 = false;
358
+ updateProject(productId, (x) => {
359
+ delete x.set_up;
360
+ capped2 = !mayStart(x);
361
+ if (!capped2) x.starts.push(Date.now());
362
+ });
363
+ if (!capped2) {
364
+ log(`${name}: a new project \u2014 starting your AI to set it up from the code.`);
365
+ const code2 = await startAgent(productId, p, false);
366
+ ended = Date.now() + offset;
367
+ log(`${name}: the setup run finished (exit ${code2}).`);
368
+ }
369
+ continue;
370
+ }
306
371
  const q = { product_id: productId, seconds: String(WAIT_SECONDS) };
307
372
  if (p.since) q.since = p.since;
308
373
  if (ended) q.ended = String(ended);
@@ -411,7 +476,7 @@ function selfCommand(script = resolve(process.argv[1] ?? "")) {
411
476
  return { node: process.execPath, args: [...process.execArgv, script, "--home", HOME] };
412
477
  }
413
478
  function startBackground(script) {
414
- refreshAutostartCopy();
479
+ keepAppCopy();
415
480
  const old = runningPid();
416
481
  if (old) killTree(old);
417
482
  rmSync(file("run"), { recursive: true, force: true });
@@ -430,17 +495,6 @@ function autostartOn() {
430
495
  if (process.platform !== "win32") return false;
431
496
  return spawnSync("reg", ["query", RUN_KEY, "/v", RUN_VALUE], { windowsHide: true }).status === 0;
432
497
  }
433
- function refreshAutostartCopy() {
434
- const me = resolve(process.argv[1] ?? "");
435
- const app = file("app/elsemeet-bridge.mjs");
436
- if (!me.endsWith(".mjs") || resolve(app) === me || !autostartOn()) return;
437
- try {
438
- mkdirSync(file("app"), { recursive: true });
439
- copyFileSync(me, app);
440
- } catch (e) {
441
- log(`Could not update the copy that starts with Windows: ${e.message}`);
442
- }
443
- }
444
498
  function setAutostart(on) {
445
499
  if (process.platform !== "win32") throw new Error("Starting with the computer is only for Windows for now; run npx elsemeet-bridge start after a restart.");
446
500
  if (!on) {
@@ -462,6 +516,97 @@ function setAutostart(on) {
462
516
  if (r.status !== 0) throw new Error(`Could not set it to start with Windows: ${r.stderr}`);
463
517
  console.log("The Bridge now starts when you sign in to Windows. Turn it off with: npx elsemeet-bridge autostart off");
464
518
  }
519
+ var APP_COPY = () => file("app/elsemeet-bridge.mjs");
520
+ function keepAppCopy(force = false) {
521
+ const me = resolve(process.argv[1] ?? "");
522
+ if (!me.endsWith(".mjs")) return false;
523
+ if (resolve(APP_COPY()) === me) return true;
524
+ if (!force && !autostartOn() && !load().wired) return true;
525
+ try {
526
+ mkdirSync(file("app"), { recursive: true });
527
+ copyFileSync(me, APP_COPY());
528
+ return true;
529
+ } catch (e) {
530
+ log(`Could not update the Bridge's own copy: ${e.message}`);
531
+ return false;
532
+ }
533
+ }
534
+ function tokenCommand(node, args) {
535
+ return [node, ...args, "token"].map((a) => `"${a.replace(/\\/g, "/")}"`).join(" ");
536
+ }
537
+ function claudeEntry(server, helper) {
538
+ return JSON.stringify({ type: "http", url: `${server}/mcp`, headersHelper: helper });
539
+ }
540
+ var ALLOW_RULE = "mcp__elsemeet";
541
+ function withAllowRule(settings) {
542
+ let j;
543
+ try {
544
+ j = settings.trim() ? JSON.parse(settings) : {};
545
+ } catch {
546
+ return null;
547
+ }
548
+ if (!j || typeof j !== "object" || Array.isArray(j)) return null;
549
+ const o = j;
550
+ const perms = o.permissions && typeof o.permissions === "object" ? o.permissions : {};
551
+ const allow = Array.isArray(perms.allow) ? perms.allow : [];
552
+ if (allow.includes(ALLOW_RULE) || allow.includes(`${ALLOW_RULE}__*`)) return settings;
553
+ return JSON.stringify({ ...o, permissions: { ...perms, allow: [...allow, ALLOW_RULE] } }, null, 2) + "\n";
554
+ }
555
+ async function printToken() {
556
+ const s = load();
557
+ const token = lasts(s, 2 * 6e4) ? s.access_token : await freshToken();
558
+ if (!token) {
559
+ console.error(SIGNED_OUT);
560
+ process.exitCode = 1;
561
+ return;
562
+ }
563
+ process.stdout.write(JSON.stringify({ Authorization: `Bearer ${token}` }));
564
+ }
565
+ function claude(args) {
566
+ const how = resolveAgent("claude");
567
+ if (!how) return { status: null, out: "" };
568
+ const r = spawnSync(how.cmd, [...how.pre, ...args], { encoding: "utf8", windowsHide: true });
569
+ return { status: r.status, out: `${r.stdout ?? ""}${r.stderr ?? ""}`.trim() };
570
+ }
571
+ function hasElsemeet(status2, out) {
572
+ const others = /Configured servers:\s*(.*)$/im.exec(out)?.[1];
573
+ if (others !== void 0) return others.split(",").some((n) => /elsemeet/i.test(n));
574
+ return status2 === 0 && !/No MCP server named/i.test(out);
575
+ }
576
+ async function connectOwnClaude(server, yes) {
577
+ const got = claude(["mcp", "get", MCP_NAME]);
578
+ if (hasElsemeet(got.status, got.out)) return console.log("\nYour Claude Code is connected to Elsemeet already.");
579
+ const say = "Also connect your own Claude Code to Elsemeet, in every folder \u2014 so when you talk to it, it knows your project? It adds Elsemeet to your Claude Code settings, signed in through this Bridge.";
580
+ const on = yes ?? (process.stdin.isTTY ? /^y/i.test(await ask(`
581
+ ${say} [y/N] `)) : false);
582
+ if (!on) return console.log("\nYour own Claude Code is not connected. To do it later: npx elsemeet-bridge connect-claude");
583
+ const me = resolve(process.argv[1] ?? "");
584
+ if (me.endsWith(".mjs") && !keepAppCopy(true)) throw new Error("Could not keep a copy of the Bridge for Claude Code to sign in with.");
585
+ const { node, args } = selfCommand(me.endsWith(".mjs") ? APP_COPY() : me);
586
+ const added = claude(["mcp", "add-json", "--scope", "user", MCP_NAME, claudeEntry(server, tokenCommand(node, args))]);
587
+ if (added.status !== 0) throw new Error(`Could not add Elsemeet to Claude Code: ${added.out}`);
588
+ const s = load();
589
+ s.wired = true;
590
+ save(s);
591
+ const settingsFile = join(homedir(), ".claude", "settings.json");
592
+ const before = existsSync(settingsFile) ? readFileSync(settingsFile, "utf8") : "";
593
+ const after = withAllowRule(before);
594
+ if (after === null) console.log(`Could not read ${settingsFile}: add ${ALLOW_RULE} to permissions.allow there yourself, so /work is not stopped at every step.`);
595
+ else if (after !== before) {
596
+ mkdirSync(dirname(settingsFile), { recursive: true });
597
+ writeFileSync(settingsFile, after);
598
+ }
599
+ console.log(`
600
+ Your Claude Code is connected to Elsemeet (in its user settings), and may use Elsemeet's tools without asking each time (${ALLOW_RULE}). Restart any Claude Code that is open.`);
601
+ }
602
+ function disconnectOwnClaude() {
603
+ const s = load();
604
+ if (!s.wired) return;
605
+ if (claude(["mcp", "get", MCP_NAME]).out.includes("elsemeet-bridge")) claude(["mcp", "remove", "--scope", "user", MCP_NAME]);
606
+ s.wired = false;
607
+ save(s);
608
+ console.log("Your Claude Code is no longer connected to Elsemeet through the Bridge.");
609
+ }
465
610
  async function ask(question) {
466
611
  const rl = createInterface({ input: process.stdin, output: process.stdout });
467
612
  try {
@@ -470,6 +615,10 @@ async function ask(question) {
470
615
  rl.close();
471
616
  }
472
617
  }
618
+ function repoOf(remotes, folderName) {
619
+ const r = remotes.find((x) => x.name === "origin") ?? remotes[0];
620
+ return r ? r.url.replace(/^([a-z][a-z0-9+.-]*:\/\/)[^@/]+@/i, "$1") : folderName;
621
+ }
473
622
  async function setup(o) {
474
623
  const agent = "claude";
475
624
  const how = resolveAgent(agent);
@@ -490,30 +639,52 @@ async function setup(o) {
490
639
  await login(server, o.open, agent);
491
640
  projects = (await api("/bridge/projects")).projects;
492
641
  }
493
- if (!projects.length) throw new Error(`You have no project on Elsemeet yet: start one at ${server}, then run this again.`);
642
+ const remoteList = git(dir, ["remote", "-v"]).split("\n").map((l) => l.split(/\s+/)).filter((x) => x[0] && x[1]).map(([name2, url]) => ({ name: name2, url }));
643
+ const remotes = remoteList.map((r) => r.url);
644
+ const name = basename(dir);
645
+ const createProject = async () => {
646
+ const { project } = await apiPost("/bridge/projects", { name, repo: repoOf(remoteList, name) });
647
+ console.log(`
648
+ New project on Elsemeet: ${project.name}.`);
649
+ return project;
650
+ };
494
651
  let chosen;
652
+ let created = false;
495
653
  if (o.project) {
496
654
  chosen = projects.find((p) => p.id === o.project);
497
655
  if (!chosen) throw new Error(`No project ${o.project} in your account.`);
498
656
  } else {
499
- const remotes = git(dir, ["remote", "-v"]).split("\n").map((l) => l.split(/\s+/)[1]).filter(Boolean);
500
- const found = matchProjects(projects, remotes, basename(dir));
657
+ const found = matchProjects(projects, remotes, name);
501
658
  if (found.length === 1) chosen = found[0];
502
- else {
659
+ else if (o.newProject) {
660
+ chosen = await createProject();
661
+ created = true;
662
+ } else if (!found.length && !projects.length) {
663
+ if (process.stdin.isTTY && !/^n/i.test(await ask(`This folder is not on Elsemeet yet. Set it up as a new project, "${name}"? [Y/n] `))) {
664
+ chosen = await createProject();
665
+ created = true;
666
+ } else if (!process.stdin.isTTY) throw new Error("This folder is not on Elsemeet yet. Run it again with --new to set it up as a new project.");
667
+ else throw new Error("Cancelled: nothing connected.");
668
+ } else {
503
669
  const list = found.length ? found : projects;
504
- if (!process.stdin.isTTY) throw new Error(`Could not tell which project this folder is. Run it again with --project <id>:
670
+ if (!process.stdin.isTTY)
671
+ throw new Error(`Could not tell which project this folder is. Run it again with --project <id>, or --new to set it up as a new one:
505
672
  ${list.map((p) => ` ${p.id} ${p.name}`).join("\n")}`);
506
- console.log(found.length ? "This folder could be more than one project:" : "Which of your projects is this folder?");
673
+ console.log(found.length ? "This folder could be more than one project:" : "This folder is not on Elsemeet yet. Is it one of your projects, or a new one?");
507
674
  list.forEach((p, i) => console.log(` ${i + 1}. ${p.name}${p.repo ? ` (${p.repo})` : ""}`));
675
+ console.log(` ${list.length + 1}. A new project: ${name}`);
508
676
  const n = Number(await ask("Number (Enter to cancel): "));
509
- chosen = list[n - 1];
677
+ if (n === list.length + 1) {
678
+ chosen = await createProject();
679
+ created = true;
680
+ } else chosen = list[n - 1];
510
681
  if (!chosen) throw new Error("Cancelled: nothing connected.");
511
682
  }
512
683
  }
513
684
  s = load();
514
685
  const elsewhere = Object.entries(s.projects).find(([id, p]) => p.folder === dir && id !== chosen.id);
515
686
  if (elsewhere) delete s.projects[elsewhere[0]];
516
- s.projects[chosen.id] = { ...s.projects[chosen.id], folder: dir, name: chosen.name, agent };
687
+ s.projects[chosen.id] = { ...s.projects[chosen.id], folder: dir, name: chosen.name, agent, ...created ? { set_up: true } : {} };
517
688
  save(s);
518
689
  if (git(dir, ["status", "--porcelain"]))
519
690
  console.log(`
@@ -532,7 +703,9 @@ Connected: ${chosen.name} \u2192 ${dir}`);
532
703
  ].join("\n")
533
704
  );
534
705
  console.log("Your Claude Code now starts here on its own when you mark a piece or propose something on the Work board, or Talk does it for you. A teammate\u2019s idea goes on the board, but does not start it.");
706
+ if (created) console.log(`It starts now, once, to set the project up from the code: what the product is, its competitors, what to build next. Watch it on the Work board: ${server}/me/work?project=${chosen.id}`);
535
707
  console.log(`Running in the background (pid ${pid}); you can close this terminal.`);
708
+ await connectOwnClaude(server, o.claude);
536
709
  if (process.platform === "win32" && !autostartOn()) {
537
710
  const on = o.autostart ?? (process.stdin.isTTY ? /^y/i.test(await ask("Start the Bridge when you sign in to Windows? [y/N] ")) : false);
538
711
  if (on) setAutostart(true);
@@ -576,8 +749,17 @@ async function main(argv) {
576
749
  const open = !has("--no-open");
577
750
  const [cmd, arg] = rest;
578
751
  switch (cmd ?? "setup") {
579
- case "setup":
580
- return setup({ server, project, open, autostart: has("--autostart") || void 0 });
752
+ case "setup": {
753
+ const newProject = has("--new") || void 0;
754
+ const own = has("--connect-claude") ? true : has("--no-connect-claude") ? false : void 0;
755
+ return setup({ server, project, open, autostart: has("--autostart") || void 0, newProject, claude: own });
756
+ }
757
+ case "token":
758
+ return printToken();
759
+ case "connect-claude": {
760
+ if (!load().access_token) throw new Error("Not connected yet: run npx elsemeet-bridge in a project folder.");
761
+ return connectOwnClaude(load().server, true);
762
+ }
581
763
  case "run":
582
764
  return run();
583
765
  case "start": {
@@ -612,6 +794,7 @@ async function main(argv) {
612
794
  }
613
795
  case "logout": {
614
796
  await main(["--home", HOME, "stop"]);
797
+ disconnectOwnClaude();
615
798
  if (autostartOn()) setAutostart(false);
616
799
  const s = load();
617
800
  if (s.refresh_token && s.client_id)
@@ -626,7 +809,7 @@ async function main(argv) {
626
809
  return console.log("Signed out; nothing is connected.");
627
810
  }
628
811
  default:
629
- console.log(`Unknown command: ${cmd}. Commands: (none) \xB7 status \xB7 start \xB7 stop \xB7 autostart on|off \xB7 remove \xB7 logout`);
812
+ console.log(`Unknown command: ${cmd}. Commands: (none) \xB7 status \xB7 start \xB7 stop \xB7 autostart on|off \xB7 connect-claude \xB7 remove \xB7 logout`);
630
813
  }
631
814
  }
632
815
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "elsemeet-bridge",
3
- "version": "0.1.3",
3
+ "version": "0.1.4",
4
4
  "description": "Starts your Claude Code on /work when your Elsemeet project has something for it — connect once, in your project folder: npx elsemeet-bridge",
5
5
  "type": "module",
6
6
  "bin": { "elsemeet-bridge": "dist/elsemeet-bridge.mjs" },