elsemeet-bridge 0.1.3 → 0.1.5

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/dist/elsemeet-bridge.mjs +229 -34
  2. package/package.json +11 -11
@@ -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 beating(productId, () => 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);
@@ -326,7 +391,7 @@ async function watch(productId, stop) {
326
391
  continue;
327
392
  }
328
393
  log(`${name}: ${w.marks} mark(s), ${w.ideas} idea(s) for your AI \u2014 starting it.`);
329
- const code = await startAgent(productId, p, w.push_yes === true);
394
+ const code = await beating(productId, () => startAgent(productId, p, w.push_yes === true));
330
395
  ended = Date.now() + offset;
331
396
  log(`${name}: the agent finished (exit ${code}).`);
332
397
  if (code === 0) updateProject(productId, (x) => x.since = w.since);
@@ -343,6 +408,18 @@ async function watch(productId, stop) {
343
408
  }
344
409
  }
345
410
  }
411
+ async function beating(productId, run2) {
412
+ const send = (state) => apiPost("/bridge/beat", { product_id: productId, state }).catch(() => {
413
+ });
414
+ void send("working");
415
+ const timer = setInterval(() => void send("working"), 3e4);
416
+ try {
417
+ return await run2();
418
+ } finally {
419
+ clearInterval(timer);
420
+ void send("idle");
421
+ }
422
+ }
346
423
  function sleep(ms, stop) {
347
424
  const end = Date.now() + ms;
348
425
  return new Promise((ok) => {
@@ -411,7 +488,7 @@ function selfCommand(script = resolve(process.argv[1] ?? "")) {
411
488
  return { node: process.execPath, args: [...process.execArgv, script, "--home", HOME] };
412
489
  }
413
490
  function startBackground(script) {
414
- refreshAutostartCopy();
491
+ keepAppCopy();
415
492
  const old = runningPid();
416
493
  if (old) killTree(old);
417
494
  rmSync(file("run"), { recursive: true, force: true });
@@ -430,17 +507,6 @@ function autostartOn() {
430
507
  if (process.platform !== "win32") return false;
431
508
  return spawnSync("reg", ["query", RUN_KEY, "/v", RUN_VALUE], { windowsHide: true }).status === 0;
432
509
  }
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
510
  function setAutostart(on) {
445
511
  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
512
  if (!on) {
@@ -462,6 +528,97 @@ function setAutostart(on) {
462
528
  if (r.status !== 0) throw new Error(`Could not set it to start with Windows: ${r.stderr}`);
463
529
  console.log("The Bridge now starts when you sign in to Windows. Turn it off with: npx elsemeet-bridge autostart off");
464
530
  }
531
+ var APP_COPY = () => file("app/elsemeet-bridge.mjs");
532
+ function keepAppCopy(force = false) {
533
+ const me = resolve(process.argv[1] ?? "");
534
+ if (!me.endsWith(".mjs")) return false;
535
+ if (resolve(APP_COPY()) === me) return true;
536
+ if (!force && !autostartOn() && !load().wired) return true;
537
+ try {
538
+ mkdirSync(file("app"), { recursive: true });
539
+ copyFileSync(me, APP_COPY());
540
+ return true;
541
+ } catch (e) {
542
+ log(`Could not update the Bridge's own copy: ${e.message}`);
543
+ return false;
544
+ }
545
+ }
546
+ function tokenCommand(node, args) {
547
+ return [node, ...args, "token"].map((a) => `"${a.replace(/\\/g, "/")}"`).join(" ");
548
+ }
549
+ function claudeEntry(server, helper) {
550
+ return JSON.stringify({ type: "http", url: `${server}/mcp`, headersHelper: helper });
551
+ }
552
+ var ALLOW_RULE = "mcp__elsemeet";
553
+ function withAllowRule(settings) {
554
+ let j;
555
+ try {
556
+ j = settings.trim() ? JSON.parse(settings) : {};
557
+ } catch {
558
+ return null;
559
+ }
560
+ if (!j || typeof j !== "object" || Array.isArray(j)) return null;
561
+ const o = j;
562
+ const perms = o.permissions && typeof o.permissions === "object" ? o.permissions : {};
563
+ const allow = Array.isArray(perms.allow) ? perms.allow : [];
564
+ if (allow.includes(ALLOW_RULE) || allow.includes(`${ALLOW_RULE}__*`)) return settings;
565
+ return JSON.stringify({ ...o, permissions: { ...perms, allow: [...allow, ALLOW_RULE] } }, null, 2) + "\n";
566
+ }
567
+ async function printToken() {
568
+ const s = load();
569
+ const token = lasts(s, 2 * 6e4) ? s.access_token : await freshToken();
570
+ if (!token) {
571
+ console.error(SIGNED_OUT);
572
+ process.exitCode = 1;
573
+ return;
574
+ }
575
+ process.stdout.write(JSON.stringify({ Authorization: `Bearer ${token}` }));
576
+ }
577
+ function claude(args) {
578
+ const how = resolveAgent("claude");
579
+ if (!how) return { status: null, out: "" };
580
+ const r = spawnSync(how.cmd, [...how.pre, ...args], { encoding: "utf8", windowsHide: true });
581
+ return { status: r.status, out: `${r.stdout ?? ""}${r.stderr ?? ""}`.trim() };
582
+ }
583
+ function hasElsemeet(status2, out) {
584
+ const others = /Configured servers:\s*(.*)$/im.exec(out)?.[1];
585
+ if (others !== void 0) return others.split(",").some((n) => /elsemeet/i.test(n));
586
+ return status2 === 0 && !/No MCP server named/i.test(out);
587
+ }
588
+ async function connectOwnClaude(server, yes) {
589
+ const got = claude(["mcp", "get", MCP_NAME]);
590
+ if (hasElsemeet(got.status, got.out)) return console.log("\nYour Claude Code is connected to Elsemeet already.");
591
+ 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.";
592
+ const on = yes ?? (process.stdin.isTTY ? /^y/i.test(await ask(`
593
+ ${say} [y/N] `)) : false);
594
+ if (!on) return console.log("\nYour own Claude Code is not connected. To do it later: npx elsemeet-bridge connect-claude");
595
+ const me = resolve(process.argv[1] ?? "");
596
+ if (me.endsWith(".mjs") && !keepAppCopy(true)) throw new Error("Could not keep a copy of the Bridge for Claude Code to sign in with.");
597
+ const { node, args } = selfCommand(me.endsWith(".mjs") ? APP_COPY() : me);
598
+ const added = claude(["mcp", "add-json", "--scope", "user", MCP_NAME, claudeEntry(server, tokenCommand(node, args))]);
599
+ if (added.status !== 0) throw new Error(`Could not add Elsemeet to Claude Code: ${added.out}`);
600
+ const s = load();
601
+ s.wired = true;
602
+ save(s);
603
+ const settingsFile = join(homedir(), ".claude", "settings.json");
604
+ const before = existsSync(settingsFile) ? readFileSync(settingsFile, "utf8") : "";
605
+ const after = withAllowRule(before);
606
+ 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.`);
607
+ else if (after !== before) {
608
+ mkdirSync(dirname(settingsFile), { recursive: true });
609
+ writeFileSync(settingsFile, after);
610
+ }
611
+ console.log(`
612
+ 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.`);
613
+ }
614
+ function disconnectOwnClaude() {
615
+ const s = load();
616
+ if (!s.wired) return;
617
+ if (claude(["mcp", "get", MCP_NAME]).out.includes("elsemeet-bridge")) claude(["mcp", "remove", "--scope", "user", MCP_NAME]);
618
+ s.wired = false;
619
+ save(s);
620
+ console.log("Your Claude Code is no longer connected to Elsemeet through the Bridge.");
621
+ }
465
622
  async function ask(question) {
466
623
  const rl = createInterface({ input: process.stdin, output: process.stdout });
467
624
  try {
@@ -470,6 +627,10 @@ async function ask(question) {
470
627
  rl.close();
471
628
  }
472
629
  }
630
+ function repoOf(remotes, folderName) {
631
+ const r = remotes.find((x) => x.name === "origin") ?? remotes[0];
632
+ return r ? r.url.replace(/^([a-z][a-z0-9+.-]*:\/\/)[^@/]+@/i, "$1") : folderName;
633
+ }
473
634
  async function setup(o) {
474
635
  const agent = "claude";
475
636
  const how = resolveAgent(agent);
@@ -490,30 +651,52 @@ async function setup(o) {
490
651
  await login(server, o.open, agent);
491
652
  projects = (await api("/bridge/projects")).projects;
492
653
  }
493
- if (!projects.length) throw new Error(`You have no project on Elsemeet yet: start one at ${server}, then run this again.`);
654
+ 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 }));
655
+ const remotes = remoteList.map((r) => r.url);
656
+ const name = basename(dir);
657
+ const createProject = async () => {
658
+ const { project } = await apiPost("/bridge/projects", { name, repo: repoOf(remoteList, name) });
659
+ console.log(`
660
+ New project on Elsemeet: ${project.name}.`);
661
+ return project;
662
+ };
494
663
  let chosen;
664
+ let created = false;
495
665
  if (o.project) {
496
666
  chosen = projects.find((p) => p.id === o.project);
497
667
  if (!chosen) throw new Error(`No project ${o.project} in your account.`);
498
668
  } 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));
669
+ const found = matchProjects(projects, remotes, name);
501
670
  if (found.length === 1) chosen = found[0];
502
- else {
671
+ else if (o.newProject) {
672
+ chosen = await createProject();
673
+ created = true;
674
+ } else if (!found.length && !projects.length) {
675
+ 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] `))) {
676
+ chosen = await createProject();
677
+ created = true;
678
+ } 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.");
679
+ else throw new Error("Cancelled: nothing connected.");
680
+ } else {
503
681
  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>:
682
+ if (!process.stdin.isTTY)
683
+ 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
684
  ${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?");
685
+ 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
686
  list.forEach((p, i) => console.log(` ${i + 1}. ${p.name}${p.repo ? ` (${p.repo})` : ""}`));
687
+ console.log(` ${list.length + 1}. A new project: ${name}`);
508
688
  const n = Number(await ask("Number (Enter to cancel): "));
509
- chosen = list[n - 1];
689
+ if (n === list.length + 1) {
690
+ chosen = await createProject();
691
+ created = true;
692
+ } else chosen = list[n - 1];
510
693
  if (!chosen) throw new Error("Cancelled: nothing connected.");
511
694
  }
512
695
  }
513
696
  s = load();
514
697
  const elsewhere = Object.entries(s.projects).find(([id, p]) => p.folder === dir && id !== chosen.id);
515
698
  if (elsewhere) delete s.projects[elsewhere[0]];
516
- s.projects[chosen.id] = { ...s.projects[chosen.id], folder: dir, name: chosen.name, agent };
699
+ s.projects[chosen.id] = { ...s.projects[chosen.id], folder: dir, name: chosen.name, agent, ...created ? { set_up: true } : {} };
517
700
  save(s);
518
701
  if (git(dir, ["status", "--porcelain"]))
519
702
  console.log(`
@@ -532,7 +715,9 @@ Connected: ${chosen.name} \u2192 ${dir}`);
532
715
  ].join("\n")
533
716
  );
534
717
  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.");
718
+ 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
719
  console.log(`Running in the background (pid ${pid}); you can close this terminal.`);
720
+ await connectOwnClaude(server, o.claude);
536
721
  if (process.platform === "win32" && !autostartOn()) {
537
722
  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
723
  if (on) setAutostart(true);
@@ -576,8 +761,17 @@ async function main(argv) {
576
761
  const open = !has("--no-open");
577
762
  const [cmd, arg] = rest;
578
763
  switch (cmd ?? "setup") {
579
- case "setup":
580
- return setup({ server, project, open, autostart: has("--autostart") || void 0 });
764
+ case "setup": {
765
+ const newProject = has("--new") || void 0;
766
+ const own = has("--connect-claude") ? true : has("--no-connect-claude") ? false : void 0;
767
+ return setup({ server, project, open, autostart: has("--autostart") || void 0, newProject, claude: own });
768
+ }
769
+ case "token":
770
+ return printToken();
771
+ case "connect-claude": {
772
+ if (!load().access_token) throw new Error("Not connected yet: run npx elsemeet-bridge in a project folder.");
773
+ return connectOwnClaude(load().server, true);
774
+ }
581
775
  case "run":
582
776
  return run();
583
777
  case "start": {
@@ -612,6 +806,7 @@ async function main(argv) {
612
806
  }
613
807
  case "logout": {
614
808
  await main(["--home", HOME, "stop"]);
809
+ disconnectOwnClaude();
615
810
  if (autostartOn()) setAutostart(false);
616
811
  const s = load();
617
812
  if (s.refresh_token && s.client_id)
@@ -626,7 +821,7 @@ async function main(argv) {
626
821
  return console.log("Signed out; nothing is connected.");
627
822
  }
628
823
  default:
629
- console.log(`Unknown command: ${cmd}. Commands: (none) \xB7 status \xB7 start \xB7 stop \xB7 autostart on|off \xB7 remove \xB7 logout`);
824
+ 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
825
  }
631
826
  }
632
827
 
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
- {
2
- "name": "elsemeet-bridge",
3
- "version": "0.1.3",
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
- "type": "module",
6
- "bin": { "elsemeet-bridge": "dist/elsemeet-bridge.mjs" },
7
- "files": ["dist/elsemeet-bridge.mjs", "README.md"],
8
- "engines": { "node": ">=20" },
9
- "license": "ISC",
10
- "homepage": "https://www.elsemeet.com"
11
- }
1
+ {
2
+ "name": "elsemeet-bridge",
3
+ "version": "0.1.5",
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
+ "type": "module",
6
+ "bin": { "elsemeet-bridge": "dist/elsemeet-bridge.mjs" },
7
+ "files": ["dist/elsemeet-bridge.mjs", "README.md"],
8
+ "engines": { "node": ">=20" },
9
+ "license": "ISC",
10
+ "homepage": "https://www.elsemeet.com"
11
+ }