elsemeet-bridge 0.0.0-stage → 0.1.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.
package/README.md CHANGED
@@ -1,3 +1,21 @@
1
- # Temporary Holding Version
1
+ # Elsemeet Bridge
2
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.
3
+ Your Claude Code starts on its own when your Elsemeet project has something for it — you mark a piece or propose something on the Work board, or Talk does it for you — so you never open a terminal to type `/work`.
4
+
5
+ Connect once, in your project's folder (a git repository, with Claude Code installed):
6
+
7
+ ```
8
+ npx elsemeet-bridge
9
+ ```
10
+
11
+ It opens your browser to sign in, finds which of your projects this folder is (by its git remote), connects it and keeps running in the background. Optionally it starts when you sign in to Windows.
12
+
13
+ ```
14
+ npx elsemeet-bridge status what it watches, whether it runs
15
+ npx elsemeet-bridge stop | start
16
+ npx elsemeet-bridge autostart on|off
17
+ npx elsemeet-bridge remove stop watching this folder's project
18
+ npx elsemeet-bridge logout
19
+ ```
20
+
21
+ What it lets your AI do: only what you or Talk (for you) put on the board starts it — a teammate's idea does not. It works and reads only inside this folder, and never pushes, deploys or publishes unless you said yes to a push on the board.
@@ -0,0 +1,602 @@
1
+ #!/usr/bin/env node
2
+
3
+ // bridge/bridge.ts
4
+ import { spawn, spawnSync } from "node:child_process";
5
+ import { createHash, randomBytes } from "node:crypto";
6
+ import { copyFileSync, createWriteStream, existsSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
7
+ import { createServer } from "node:http";
8
+ import { homedir } from "node:os";
9
+ import { basename, dirname, join, resolve } from "node:path";
10
+ import { createInterface } from "node:readline/promises";
11
+ var AGENTS = {
12
+ claude: {
13
+ /** The app name it signs in with: the AI it becomes is the person's own "Claude Code" (the part in brackets is dropped). */
14
+ app: "Claude Code (Elsemeet Bridge)",
15
+ command: "claude",
16
+ /** Installed with npm, it is a script node runs (on Windows behind a .cmd that cannot be started without a shell). */
17
+ npm_script: ["node_modules/@anthropic-ai/claude-code/cli.js", "node_modules/@anthropic-ai/claude-code/cli.mjs"]
18
+ }
19
+ };
20
+ function resolveAgent(kind, platform = process.platform, where = whereCommand) {
21
+ const a = AGENTS[kind];
22
+ if (platform !== "win32") return { cmd: a.command, pre: [] };
23
+ for (const found of where(a.command)) {
24
+ if (/\.exe$/i.test(found)) return { cmd: found, pre: [] };
25
+ for (const script of a.npm_script) {
26
+ const js = join(dirname(found), script);
27
+ if (existsSync(js)) return { cmd: process.execPath, pre: [js] };
28
+ }
29
+ }
30
+ return null;
31
+ }
32
+ function whereCommand(name) {
33
+ const r = spawnSync("where", [name], { encoding: "utf8", windowsHide: true });
34
+ return r.status === 0 ? (r.stdout ?? "").split(/\r?\n/).filter(Boolean) : [];
35
+ }
36
+ var HOME = resolve(process.env.ELSEMEET_BRIDGE_HOME ?? join(homedir(), ".elsemeet-bridge"));
37
+ var file = (name) => join(HOME, name);
38
+ var DEFAULT_SERVER = "https://www.elsemeet.com";
39
+ var MCP_NAME = "elsemeet";
40
+ var MAX_STARTS_PER_HOUR = 6;
41
+ var WAIT_SECONDS = 50;
42
+ var NO_SHIP = ["git push", "vercel", "npm publish", "gh"].flatMap((c) => [`Bash(${c}:*)`, `PowerShell(${c}:*)`]);
43
+ var RUN_SETTINGS = JSON.stringify({ permissions: { blockReadsOutsideWorkingDirectories: true } });
44
+ var RUN_WAIT_MINUTES = 45;
45
+ function runNote(pushYes, startedAt = /* @__PURE__ */ new Date()) {
46
+ const until = new Date(startedAt.getTime() + RUN_WAIT_MINUTES * 6e4).toISOString();
47
+ return [
48
+ "This /work was started by Elsemeet Bridge on the user\u2019s computer; nobody is watching this terminal.",
49
+ `Step 6 applies as it says \u2014 wait at wait_for_work while they are on Talk or the Work page \u2014 with one limit: this run started at ${startedAt.toISOString()} and its sign-in lasts an hour, so once it is past ${until}, do not wait again: end, saying in a line what you did (check the time with the shell). The Bridge starts you again when something new comes. When wait_for_work says away or enough, end.`,
50
+ pushYes ? "The project\u2019s Owner said yes to a push on the board: this run may push what that yes covers, as Work says." : "This run cannot push, deploy or publish (the Bridge blocks it). Leave any push mark open \u2014 do not answer it \u2014 and when a wait brings a push mark, end at once: the Bridge then starts a run that can push."
51
+ ].join(" ");
52
+ }
53
+ function noPushEnv(env) {
54
+ const n = Number(env.GIT_CONFIG_COUNT) || 0;
55
+ return { ...env, GIT_CONFIG_COUNT: String(n + 1), [`GIT_CONFIG_KEY_${n}`]: "url.elsemeet-bridge-no-push://.pushInsteadOf", [`GIT_CONFIG_VALUE_${n}`]: "" };
56
+ }
57
+ function load() {
58
+ if (!existsSync(file("state.json"))) return { server: DEFAULT_SERVER, projects: {} };
59
+ return JSON.parse(readFileSync(file("state.json"), "utf8"));
60
+ }
61
+ function save(s) {
62
+ mkdirSync(HOME, { recursive: true });
63
+ const tmp = file("state.json.tmp");
64
+ writeFileSync(tmp, JSON.stringify(s, null, 2), { mode: 384 });
65
+ renameSync(tmp, file("state.json"));
66
+ }
67
+ var log = (msg) => console.log(`[${(/* @__PURE__ */ new Date()).toLocaleString()}] ${msg}`);
68
+ function openBrowser(url) {
69
+ if (process.platform === "win32") spawn("rundll32", ["url.dll,FileProtocolHandler", url], { detached: true, stdio: "ignore" }).unref();
70
+ else spawn(process.platform === "darwin" ? "open" : "xdg-open", [url], { detached: true, stdio: "ignore" }).unref();
71
+ }
72
+ async function login(server, open, agent = "claude") {
73
+ const s = load();
74
+ s.server = server.replace(/\/$/, "");
75
+ const verifier = randomBytes(32).toString("base64url");
76
+ const challenge = createHash("sha256").update(verifier).digest("base64url");
77
+ const state = randomBytes(16).toString("base64url");
78
+ const code = await new Promise((ok, fail) => {
79
+ let redirect = "";
80
+ const http = createServer((req, res) => {
81
+ const u = new URL(req.url ?? "/", "http://127.0.0.1");
82
+ if (u.pathname !== "/callback") return void res.writeHead(404).end();
83
+ const done = (msg) => res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" }).end(msg);
84
+ if (u.searchParams.get("state") !== state) return done("This sign-in is not the one the Bridge started. Close this tab.");
85
+ const c = u.searchParams.get("code");
86
+ http.close();
87
+ if (!c) {
88
+ done("Sign-in was cancelled. You can close this tab.");
89
+ return fail(new Error(u.searchParams.get("error_description") ?? "Sign-in was cancelled."));
90
+ }
91
+ done("Elsemeet Bridge is connected. You can close this tab and go back to the terminal.");
92
+ ok({ code: c, redirect });
93
+ });
94
+ http.listen(0, "127.0.0.1", async () => {
95
+ redirect = `http://127.0.0.1:${http.address().port}/callback`;
96
+ try {
97
+ const reg = await fetch(`${s.server}/oauth/register`, {
98
+ method: "POST",
99
+ headers: { "Content-Type": "application/json" },
100
+ body: JSON.stringify({ client_name: AGENTS[agent].app, redirect_uris: [redirect], token_endpoint_auth_method: "none" })
101
+ });
102
+ if (!reg.ok) throw new Error(`Could not reach ${s.server} to sign in: ${reg.status} ${await reg.text()}`);
103
+ s.client_id = (await reg.json()).client_id;
104
+ const url = new URL(`${s.server}/oauth/authorize`);
105
+ for (const [k, v] of Object.entries({ response_type: "code", client_id: s.client_id, redirect_uri: redirect, code_challenge: challenge, code_challenge_method: "S256", state, resource: `${s.server}/mcp` }))
106
+ url.searchParams.set(k, v);
107
+ console.log(open ? `Opening your browser to sign in to Elsemeet. If it does not open, go to:
108
+ ${url}
109
+ ` : `Sign in to Elsemeet at:
110
+ ${url}
111
+ `);
112
+ if (open) openBrowser(url.toString());
113
+ } catch (e) {
114
+ http.close();
115
+ fail(e);
116
+ }
117
+ });
118
+ setTimeout(() => {
119
+ http.close();
120
+ fail(new Error("Sign-in took longer than 5 minutes; run it again."));
121
+ }, 5 * 6e4).unref();
122
+ });
123
+ Object.assign(s, await tokenRequest(s, { grant_type: "authorization_code", code: code.code, redirect_uri: code.redirect, code_verifier: verifier }));
124
+ save(s);
125
+ console.log("Signed in.");
126
+ }
127
+ async function tokenRequest(s, params) {
128
+ const res = await fetch(`${s.server}/oauth/token`, {
129
+ method: "POST",
130
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
131
+ body: new URLSearchParams({ ...params, client_id: s.client_id ?? "", resource: `${s.server}/mcp` })
132
+ });
133
+ if (!res.ok) throw new Error(`Sign-in failed (${res.status}): ${await res.text()}`);
134
+ const t = await res.json();
135
+ return { access_token: t.access_token, refresh_token: t.refresh_token };
136
+ }
137
+ var refreshing = null;
138
+ function freshToken(stale) {
139
+ refreshing ??= (async () => {
140
+ try {
141
+ const s = load();
142
+ if (stale && s.access_token && s.access_token !== stale) return s.access_token;
143
+ if (!s.refresh_token) return null;
144
+ Object.assign(s, await tokenRequest(s, { grant_type: "refresh_token", refresh_token: s.refresh_token }));
145
+ save(s);
146
+ return s.access_token ?? null;
147
+ } catch {
148
+ return null;
149
+ } finally {
150
+ setTimeout(() => refreshing = null, 0);
151
+ }
152
+ })();
153
+ return refreshing;
154
+ }
155
+ var SignedOut = class extends Error {
156
+ };
157
+ var SIGNED_OUT = "The sign-in is no longer valid: run npx elsemeet-bridge in the project folder to sign in again.";
158
+ async function api(path, query = {}, timeoutMs = 3e4) {
159
+ const s = load();
160
+ const url = new URL(`${s.server}${path}`);
161
+ for (const [k, v] of Object.entries(query)) url.searchParams.set(k, v);
162
+ let token = s.access_token ?? "";
163
+ for (let attempt = 0; ; attempt++) {
164
+ const res = await fetch(url, { headers: { Authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(timeoutMs) });
165
+ if (res.status === 401 && attempt === 0) {
166
+ const t = await freshToken(token);
167
+ if (t) {
168
+ token = t;
169
+ continue;
170
+ }
171
+ }
172
+ if (res.status === 401) throw new SignedOut(SIGNED_OUT);
173
+ if (!res.ok) throw new Error(`${res.status}: ${(await res.text()).slice(0, 300)}`);
174
+ return await res.json();
175
+ }
176
+ }
177
+ function normalizeRepo(u) {
178
+ return u.trim().toLowerCase().replace(/^git\+/, "").replace(/^[a-z]+:\/\//, "").replace(/^[^@/]+@/, "").replace(/^([^/:]+):(?!\d)/, "$1/").replace(/\.git$/, "").replace(/\/+$/, "");
179
+ }
180
+ function matchProjects(projects, remotes, folderName) {
181
+ const mine = new Set(remotes.map(normalizeRepo));
182
+ return projects.filter((p) => {
183
+ if (!p.repo) return false;
184
+ const repo = normalizeRepo(p.repo);
185
+ return mine.has(repo) || !repo.includes("/") && repo === folderName.toLowerCase();
186
+ });
187
+ }
188
+ function git(cwd, args) {
189
+ const r = spawnSync("git", args, { cwd, encoding: "utf8", windowsHide: true });
190
+ return r.status === 0 ? (r.stdout ?? "").trim() : "";
191
+ }
192
+ function agentCommand(p, mcpConfig, pushYes = false, startedAt = /* @__PURE__ */ new Date()) {
193
+ const agent = AGENTS[p.agent];
194
+ if (!agent) throw new Error(`Unknown agent: ${p.agent}`);
195
+ return {
196
+ cmd: agent.command,
197
+ args: [
198
+ "-p",
199
+ `/mcp__${MCP_NAME}__work`,
200
+ "--mcp-config",
201
+ mcpConfig,
202
+ "--strict-mcp-config",
203
+ // A classifier reviews each action; in -p what it would ask about is denied and the run goes on.
204
+ "--permission-mode",
205
+ "auto",
206
+ "--settings",
207
+ RUN_SETTINGS,
208
+ "--append-system-prompt",
209
+ runNote(pushYes, startedAt),
210
+ ...pushYes ? [] : ["--disallowedTools", ...NO_SHIP],
211
+ "--output-format",
212
+ "stream-json",
213
+ "--verbose",
214
+ ...p.extra_args ?? []
215
+ ]
216
+ };
217
+ }
218
+ function mcpConfigFor(server, token) {
219
+ return JSON.stringify({ mcpServers: { [MCP_NAME]: { type: "http", url: `${server}/mcp`, headers: { Authorization: `Bearer ${token}` } } } });
220
+ }
221
+ function mayStart(p, now = Date.now()) {
222
+ p.starts = (p.starts ?? []).filter((t) => now - t < 36e5);
223
+ return p.starts.length < MAX_STARTS_PER_HOUR;
224
+ }
225
+ function killTree(pid) {
226
+ if (process.platform === "win32") spawnSync("taskkill", ["/pid", String(pid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
227
+ else
228
+ try {
229
+ process.kill(pid, "SIGTERM");
230
+ } catch {
231
+ }
232
+ }
233
+ var running = /* @__PURE__ */ new Map();
234
+ var RUN_LIMIT_MS = 60 * 6e4;
235
+ var PROJECT_ID = /^prd_[a-z0-9]{4,40}$/i;
236
+ async function startAgent(productId, p, pushYes) {
237
+ if (!PROJECT_ID.test(productId)) throw new Error(`Not a project id: ${productId}`);
238
+ const how = resolveAgent(p.agent);
239
+ if (!how) throw new Error(`${AGENTS[p.agent].command} is not installed here any more: install Claude Code again.`);
240
+ const token = await freshToken();
241
+ if (!token) throw new SignedOut(SIGNED_OUT);
242
+ mkdirSync(file("run"), { recursive: true });
243
+ const mcpFile = file(`run/${productId}.mcp.json`);
244
+ writeFileSync(mcpFile, mcpConfigFor(load().server, token), { mode: 384 });
245
+ const { cmd: name, args: agentArgs } = agentCommand(p, mcpFile, pushYes);
246
+ mkdirSync(file("logs"), { recursive: true });
247
+ const logFile = file(`logs/${productId}-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.jsonl`);
248
+ const out = createWriteStream(logFile);
249
+ log(`${p.name ?? productId}: starting ${name} /work in ${p.folder}${pushYes ? " \u2014 the Owner said yes to a push: this run may push" : ""} (log: ${logFile})`);
250
+ const env = pushYes ? process.env : noPushEnv(process.env);
251
+ const child = spawn(how.cmd, [...how.pre, ...agentArgs], { cwd: p.folder, env, stdio: ["ignore", "pipe", "pipe"], shell: false, windowsHide: true });
252
+ running.set(productId, child);
253
+ child.stdout?.pipe(out, { end: false });
254
+ child.stderr?.pipe(out, { end: false });
255
+ const limit = setTimeout(() => {
256
+ log(`${p.name ?? productId}: the run took over ${RUN_LIMIT_MS / 6e4} minutes; stopping it.`);
257
+ if (child.pid) killTree(child.pid);
258
+ }, RUN_LIMIT_MS);
259
+ return new Promise((ok) => {
260
+ let done = false;
261
+ const finish = (code) => {
262
+ if (done) return;
263
+ done = true;
264
+ clearTimeout(limit);
265
+ running.delete(productId);
266
+ out.end();
267
+ rmSync(mcpFile, { force: true });
268
+ ok(code);
269
+ };
270
+ child.on("error", (e) => {
271
+ log(`${p.name ?? productId}: could not start ${name}: ${e.message}`);
272
+ finish(null);
273
+ });
274
+ child.on("exit", (code) => finish(code));
275
+ });
276
+ }
277
+ function updateProject(productId, change) {
278
+ const s = load();
279
+ const p = s.projects[productId];
280
+ if (!p) return;
281
+ change(p);
282
+ save(s);
283
+ }
284
+ async function watch(productId, stop) {
285
+ let backoff = 0;
286
+ let ended;
287
+ let offset = 0;
288
+ while (!stop.now) {
289
+ const p = load().projects[productId];
290
+ if (!p) return log(`${productId}: no longer connected here; stopped watching it.`);
291
+ const name = p.name ?? productId;
292
+ try {
293
+ const q = { product_id: productId, seconds: String(WAIT_SECONDS) };
294
+ if (p.since) q.since = p.since;
295
+ if (ended) q.ended = String(ended);
296
+ const w = await api("/bridge/wait", q, (WAIT_SECONDS + 30) * 1e3);
297
+ if (w.now && Number.isFinite(Number(w.now))) offset = Number(w.now) - Date.now();
298
+ backoff = 0;
299
+ if (w.status === "nothing_yet") continue;
300
+ if (w.status === "busy") {
301
+ log(`${name}: ${w.marks} mark(s), ${w.ideas} idea(s) \u2014 an AI is at work there; looking again in 30s.`);
302
+ await sleep(3e4, stop);
303
+ continue;
304
+ }
305
+ let capped = false;
306
+ updateProject(productId, (x) => {
307
+ capped = !mayStart(x);
308
+ if (!capped) x.starts.push(Date.now());
309
+ });
310
+ if (capped) {
311
+ log(`${name}: news, but the agent started ${MAX_STARTS_PER_HOUR} times this hour already; waiting.`);
312
+ await sleep(5 * 6e4, stop);
313
+ continue;
314
+ }
315
+ log(`${name}: ${w.marks} mark(s), ${w.ideas} idea(s) for your AI \u2014 starting it.`);
316
+ const code = await startAgent(productId, p, w.push_yes === true);
317
+ ended = Date.now() + offset;
318
+ log(`${name}: the agent finished (exit ${code}).`);
319
+ if (code === 0) updateProject(productId, (x) => x.since = w.since);
320
+ else await sleep(6e4, stop);
321
+ } catch (e) {
322
+ if (e instanceof SignedOut) {
323
+ log(e.message);
324
+ stop.now = true;
325
+ return;
326
+ }
327
+ backoff = Math.min(backoff ? backoff * 2 : 5e3, 5 * 6e4);
328
+ log(`${name}: ${e.message} \u2014 trying again in ${Math.round(backoff / 1e3)}s.`);
329
+ await sleep(backoff, stop);
330
+ }
331
+ }
332
+ }
333
+ function sleep(ms, stop) {
334
+ const end = Date.now() + ms;
335
+ return new Promise((ok) => {
336
+ const t = setInterval(() => {
337
+ if (stop.now || Date.now() >= end) {
338
+ clearInterval(t);
339
+ ok();
340
+ }
341
+ }, 500);
342
+ });
343
+ }
344
+ function commandLine(pid) {
345
+ if (process.platform === "win32") {
346
+ const query = `(Get-CimInstance Win32_Process -Filter "ProcessId=${Number(pid)}").CommandLine`;
347
+ const r2 = spawnSync("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", query], { encoding: "utf8", windowsHide: true });
348
+ return (r2.stdout ?? "").trim();
349
+ }
350
+ const r = spawnSync("ps", ["-o", "command=", "-p", String(Number(pid))], { encoding: "utf8" });
351
+ return r.status === 0 ? (r.stdout ?? "").trim() : "";
352
+ }
353
+ function isBridgeCommand(cmdline, home) {
354
+ const c = cmdline.replace(/["']/g, "").replace(/\\/g, "/").toLowerCase();
355
+ return c.includes(`--home ${home.replace(/\\/g, "/").toLowerCase()}`) && /\srun\s*$/.test(c);
356
+ }
357
+ function runningPid() {
358
+ try {
359
+ const pid = Number(readFileSync(file("bridge.pid"), "utf8"));
360
+ if (!pid) return null;
361
+ process.kill(pid, 0);
362
+ if (pid === process.pid) return pid;
363
+ return isBridgeCommand(commandLine(pid), HOME) ? pid : null;
364
+ } catch {
365
+ return null;
366
+ }
367
+ }
368
+ async function run() {
369
+ const s = load();
370
+ if (!s.access_token) throw new Error("Not signed in: run npx elsemeet-bridge in a project folder.");
371
+ const ids = Object.keys(s.projects).filter((id) => PROJECT_ID.test(id));
372
+ if (!ids.length) throw new Error("No project connected yet: run npx elsemeet-bridge in a project folder.");
373
+ const other = runningPid();
374
+ if (other && other !== process.pid) throw new Error(`The Bridge is already running (pid ${other}).`);
375
+ mkdirSync(HOME, { recursive: true });
376
+ writeFileSync(file("bridge.pid"), String(process.pid));
377
+ rmSync(file("run"), { recursive: true, force: true });
378
+ const stop = { now: false };
379
+ let closed = false;
380
+ const shutdown = () => {
381
+ if (closed) return;
382
+ closed = true;
383
+ stop.now = true;
384
+ for (const c of running.values()) if (c.pid) killTree(c.pid);
385
+ try {
386
+ if (readFileSync(file("bridge.pid"), "utf8") === String(process.pid)) rmSync(file("bridge.pid"), { force: true });
387
+ } catch {
388
+ }
389
+ setTimeout(() => process.exit(0), 500).unref();
390
+ };
391
+ process.on("SIGINT", shutdown);
392
+ process.on("SIGTERM", shutdown);
393
+ log(`Elsemeet Bridge on ${s.server}, watching: ${ids.map((id) => s.projects[id].name ?? id).join(", ")}.`);
394
+ await Promise.all(ids.map((id) => watch(id, stop)));
395
+ shutdown();
396
+ }
397
+ function selfCommand(script = resolve(process.argv[1] ?? "")) {
398
+ return { node: process.execPath, args: [...process.execArgv, script, "--home", HOME] };
399
+ }
400
+ function startBackground(script) {
401
+ const old = runningPid();
402
+ if (old) killTree(old);
403
+ rmSync(file("run"), { recursive: true, force: true });
404
+ mkdirSync(HOME, { recursive: true });
405
+ const logPath = file("bridge.log");
406
+ if (existsSync(logPath) && statSync(logPath).size > 5e6) renameSync(logPath, `${logPath}.old`);
407
+ const fd = openSync(logPath, "a");
408
+ const { node, args } = selfCommand(script);
409
+ const child = spawn(node, [...args, "run"], { detached: true, stdio: ["ignore", fd, fd], windowsHide: true, env: process.env });
410
+ child.unref();
411
+ return child.pid ?? 0;
412
+ }
413
+ var RUN_KEY = "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run";
414
+ var RUN_VALUE = "ElsemeetBridge";
415
+ function autostartOn() {
416
+ if (process.platform !== "win32") return false;
417
+ return spawnSync("reg", ["query", RUN_KEY, "/v", RUN_VALUE], { windowsHide: true }).status === 0;
418
+ }
419
+ function setAutostart(on) {
420
+ 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.");
421
+ if (!on) {
422
+ spawnSync("reg", ["delete", RUN_KEY, "/v", RUN_VALUE, "/f"], { stdio: "ignore", windowsHide: true });
423
+ rmSync(file("start-hidden.vbs"), { force: true });
424
+ console.log("The Bridge no longer starts with Windows.");
425
+ return;
426
+ }
427
+ const me = resolve(process.argv[1] ?? "");
428
+ if (!me.endsWith(".mjs")) throw new Error("Starting with Windows needs the installed Bridge (npx elsemeet-bridge), not the development copy.");
429
+ mkdirSync(file("app"), { recursive: true });
430
+ const app = file("app/elsemeet-bridge.mjs");
431
+ if (resolve(app) !== me) copyFileSync(me, app);
432
+ const { node, args } = selfCommand(app);
433
+ const command = [node, ...args, "start"].map((a) => `""${a}""`).join(" ");
434
+ writeFileSync(file("start-hidden.vbs"), `CreateObject("WScript.Shell").Run "${command}", 0, False\r
435
+ `);
436
+ const r = spawnSync("reg", ["add", RUN_KEY, "/v", RUN_VALUE, "/t", "REG_SZ", "/d", `wscript.exe "${file("start-hidden.vbs")}"`, "/f"], { windowsHide: true, encoding: "utf8" });
437
+ if (r.status !== 0) throw new Error(`Could not set it to start with Windows: ${r.stderr}`);
438
+ console.log("The Bridge now starts when you sign in to Windows. Turn it off with: npx elsemeet-bridge autostart off");
439
+ }
440
+ async function ask(question) {
441
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
442
+ try {
443
+ return (await rl.question(question)).trim();
444
+ } finally {
445
+ rl.close();
446
+ }
447
+ }
448
+ async function setup(o) {
449
+ const agent = "claude";
450
+ const how = resolveAgent(agent);
451
+ if (!how || spawnSync(how.cmd, [...how.pre, "--version"], { encoding: "utf8", windowsHide: true }).status !== 0)
452
+ throw new Error("Claude Code is not installed here (the claude command): install it first \u2014 https://claude.com/claude-code");
453
+ const folder = git(process.cwd(), ["rev-parse", "--show-toplevel"]);
454
+ if (!folder) throw new Error("Run this in your project\u2019s folder: it must be a git repository, so every change the AI makes can be seen and undone.");
455
+ const dir = resolve(folder);
456
+ let s = load();
457
+ const server = (o.server ?? (s.access_token ? s.server : DEFAULT_SERVER)).replace(/\/$/, "");
458
+ if (!s.access_token || s.server !== server) await login(server, o.open, agent);
459
+ s = load();
460
+ let projects;
461
+ try {
462
+ projects = (await api("/bridge/projects")).projects;
463
+ } catch (e) {
464
+ if (!(e instanceof SignedOut)) throw e;
465
+ await login(server, o.open, agent);
466
+ projects = (await api("/bridge/projects")).projects;
467
+ }
468
+ if (!projects.length) throw new Error(`You have no project on Elsemeet yet: start one at ${server}, then run this again.`);
469
+ let chosen;
470
+ if (o.project) {
471
+ chosen = projects.find((p) => p.id === o.project);
472
+ if (!chosen) throw new Error(`No project ${o.project} in your account.`);
473
+ } else {
474
+ const remotes = git(dir, ["remote", "-v"]).split("\n").map((l) => l.split(/\s+/)[1]).filter(Boolean);
475
+ const found = matchProjects(projects, remotes, basename(dir));
476
+ if (found.length === 1) chosen = found[0];
477
+ else {
478
+ const list = found.length ? found : projects;
479
+ if (!process.stdin.isTTY) throw new Error(`Could not tell which project this folder is. Run it again with --project <id>:
480
+ ${list.map((p) => ` ${p.id} ${p.name}`).join("\n")}`);
481
+ console.log(found.length ? "This folder could be more than one project:" : "Which of your projects is this folder?");
482
+ list.forEach((p, i) => console.log(` ${i + 1}. ${p.name}${p.repo ? ` (${p.repo})` : ""}`));
483
+ const n = Number(await ask("Number (Enter to cancel): "));
484
+ chosen = list[n - 1];
485
+ if (!chosen) throw new Error("Cancelled: nothing connected.");
486
+ }
487
+ }
488
+ s = load();
489
+ const elsewhere = Object.entries(s.projects).find(([id, p]) => p.folder === dir && id !== chosen.id);
490
+ if (elsewhere) delete s.projects[elsewhere[0]];
491
+ s.projects[chosen.id] = { ...s.projects[chosen.id], folder: dir, name: chosen.name, agent };
492
+ save(s);
493
+ if (git(dir, ["status", "--porcelain"]))
494
+ console.log(`
495
+ Note: ${dir} has uncommitted changes. Your AI will work in this folder on its own \u2014 a separate git worktree for it (git worktree add) keeps your changes apart.`);
496
+ const pid = startBackground();
497
+ console.log(`
498
+ Connected: ${chosen.name} \u2192 ${dir}`);
499
+ 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.");
500
+ console.log(`Running in the background (pid ${pid}); you can close this terminal.`);
501
+ if (process.platform === "win32" && !autostartOn()) {
502
+ const on = o.autostart ?? (process.stdin.isTTY ? /^y/i.test(await ask("Start the Bridge when you sign in to Windows? [y/N] ")) : false);
503
+ if (on) setAutostart(true);
504
+ }
505
+ console.log("\nnpx elsemeet-bridge status \u2014 see what it does \xB7 stop \u2014 stop it");
506
+ }
507
+ function status() {
508
+ const s = load();
509
+ const pid = runningPid();
510
+ console.log(`Elsemeet Bridge \xB7 ${s.server} \xB7 ${s.access_token ? "signed in" : "not signed in"}`);
511
+ console.log(pid ? `Running in the background (pid ${pid}).` : "Not running. Start it with: npx elsemeet-bridge start");
512
+ if (process.platform === "win32") console.log(autostartOn() ? "Starts when you sign in to Windows." : "Does not start with Windows (npx elsemeet-bridge autostart on).");
513
+ const ids = Object.keys(s.projects);
514
+ console.log(ids.length ? "Connected:" : "No project connected: run npx elsemeet-bridge in a project folder.");
515
+ for (const id of ids) console.log(` ${s.projects[id].name ?? id} \u2192 ${s.projects[id].folder}`);
516
+ if (existsSync(file("bridge.log"))) {
517
+ const last = readFileSync(file("bridge.log"), "utf8").trim().split("\n").slice(-5);
518
+ if (last.length) console.log(`
519
+ Lately:
520
+ ${last.map((l) => ` ${l}`).join("\n")}`);
521
+ }
522
+ }
523
+ async function main(argv) {
524
+ const rest = [...argv];
525
+ const flag = (name) => {
526
+ const i = rest.indexOf(name);
527
+ if (i < 0) return void 0;
528
+ const v = rest[i + 1];
529
+ rest.splice(i, 2);
530
+ return v;
531
+ };
532
+ const has = (name) => {
533
+ const i = rest.indexOf(name);
534
+ if (i >= 0) rest.splice(i, 1);
535
+ return i >= 0;
536
+ };
537
+ const home = flag("--home");
538
+ if (home) HOME = resolve(home);
539
+ const server = flag("--server");
540
+ const project = flag("--project");
541
+ const open = !has("--no-open");
542
+ const [cmd, arg] = rest;
543
+ switch (cmd ?? "setup") {
544
+ case "setup":
545
+ return setup({ server, project, open, autostart: has("--autostart") || void 0 });
546
+ case "run":
547
+ return run();
548
+ case "start": {
549
+ if (!load().access_token) throw new Error("Not connected yet: run npx elsemeet-bridge in a project folder.");
550
+ const pid = startBackground();
551
+ return console.log(`Running in the background (pid ${pid}).`);
552
+ }
553
+ case "stop": {
554
+ const pid = runningPid();
555
+ if (pid) killTree(pid);
556
+ rmSync(file("bridge.pid"), { force: true });
557
+ rmSync(file("run"), { recursive: true, force: true });
558
+ return console.log(pid ? "Stopped." : "It was not running.");
559
+ }
560
+ case "status":
561
+ return status();
562
+ case "autostart":
563
+ if (arg !== "on" && arg !== "off") throw new Error("autostart on, or autostart off");
564
+ return setAutostart(arg === "on");
565
+ case "remove": {
566
+ const s = load();
567
+ const dir = resolve(git(process.cwd(), ["rev-parse", "--show-toplevel"]) || process.cwd());
568
+ const id = project ?? Object.keys(s.projects).find((k) => s.projects[k].folder === dir);
569
+ if (!id || !s.projects[id]) throw new Error("No project is connected in this folder (or pass --project <id>).");
570
+ delete s.projects[id];
571
+ save(s);
572
+ if (runningPid()) {
573
+ if (Object.keys(s.projects).length) startBackground();
574
+ else await main(["--home", HOME, "stop"]);
575
+ }
576
+ return console.log("Removed: your AI no longer starts in this folder.");
577
+ }
578
+ case "logout": {
579
+ await main(["--home", HOME, "stop"]);
580
+ if (autostartOn()) setAutostart(false);
581
+ const s = load();
582
+ if (s.refresh_token && s.client_id)
583
+ await fetch(`${s.server}/oauth/revoke`, {
584
+ method: "POST",
585
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
586
+ body: new URLSearchParams({ token: s.refresh_token, client_id: s.client_id }),
587
+ signal: AbortSignal.timeout(15e3)
588
+ }).catch(() => {
589
+ });
590
+ save({ server: s.server, projects: {} });
591
+ return console.log("Signed out; nothing is connected.");
592
+ }
593
+ default:
594
+ console.log(`Unknown command: ${cmd}. Commands: (none) \xB7 status \xB7 start \xB7 stop \xB7 autostart on|off \xB7 remove \xB7 logout`);
595
+ }
596
+ }
597
+
598
+ // bridge/cli.ts
599
+ main(process.argv.slice(2)).catch((e) => {
600
+ console.error(e.message);
601
+ process.exit(1);
602
+ });
package/package.json CHANGED
@@ -1,6 +1,11 @@
1
1
  {
2
2
  "name": "elsemeet-bridge",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
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
+ }