@clearlysh/beehaven 0.8.23 → 0.8.25

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.
@@ -421,6 +421,25 @@ export function clearAgentSession(name) {
421
421
  }
422
422
  catch { /* best-effort cleanup */ }
423
423
  }
424
+ /**
425
+ * Forget the ended work session's id, and nothing else (AWO-225 `agent handoff`).
426
+ *
427
+ * ⚠ NOT `clearAgentSession`: that also drops `lastLoginAt`, which `agentForScope` uses to choose
428
+ * between identities bound to one scope. A handoff ends a stretch of work, not the sign-in, so the
429
+ * terminal must keep resolving to this agent.
430
+ */
431
+ export function clearAgentSessionId(name) {
432
+ try {
433
+ const rec = loadAgent(name);
434
+ if (!rec)
435
+ return;
436
+ const raw = { ...rec };
437
+ delete raw.sessionId;
438
+ delete raw.session;
439
+ saveAgent(name, raw);
440
+ }
441
+ catch { /* best-effort cleanup */ }
442
+ }
424
443
  /** The last session id we started for this agent, if any. */
425
444
  export function loadAgentSession(name) {
426
445
  try {
@@ -0,0 +1,283 @@
1
+ /**
2
+ * The ONE browser sign-in: localhost loopback OAuth against `<web origin>/cli/auth`.
3
+ *
4
+ * ⚠⚠ AWO-224 — THERE WERE TWO, AND ONE POINTED AT A ROUTE THAT NO LONGER EXISTS. `beehaven login`
5
+ * carried this flow inline in cli.ts; the daemon's interactive fallback (no token on start, or an
6
+ * expired session) had its own copy in setup-relay.ts that opened `/auth/beehaven?callback=` and
7
+ * waited for a single `token`. The web app removed that route, so the fallback opened a 404 and
8
+ * hung for two minutes before exiting. Both callers now use this module; the daemon fallback
9
+ * cannot drift from the command people actually run.
10
+ *
11
+ * The pattern is firebase-tools / wrangler / gh / vercel / fly / supabase: start an ephemeral
12
+ * HTTP server on a free port, open the browser to `/cli/auth?state=…&redirect=http://127.0.0.1:
13
+ * <port>/callback`. After the user signs in and approves, the page navigates the browser to the
14
+ * loopback with the Firebase tokens. The CLI validates state, stores the tokens and shuts the
15
+ * server down. The web origin and the Worker are NOT in the token-exchange path: tokens go from
16
+ * the browser's authed session straight to localhost, and state (anti-CSRF) stops a malicious site
17
+ * sending tokens to a CLI that did not ask for them.
18
+ *
19
+ * What a caller does AFTER signing in (restart the daemon, install agent skills) stays with the
20
+ * caller: the daemon fallback runs INSIDE the daemon and must not restart itself.
21
+ */
22
+ import http from 'http';
23
+ import net from 'net';
24
+ import { spawn } from 'child_process';
25
+ import crypto from 'crypto';
26
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';
27
+ import { homedir } from 'os';
28
+ import { join } from 'path';
29
+ import { color } from './spinner.js';
30
+ import { resolveRelaySelection } from './relay-presets.js';
31
+ import { withUtm } from './utm.js';
32
+ import { keychain } from './keychain.js';
33
+ const LOGIN_TIMEOUT_MS = 5 * 60 * 1000;
34
+ /**
35
+ * Resolve the web origin from the active env so staging users sign in against staging's Pages
36
+ * alias (or local dev), prod users against prod.
37
+ */
38
+ const ENV_AUTH_ORIGINS = {
39
+ prod: 'https://www.clearly.sh',
40
+ staging: 'https://localhost:3000',
41
+ dev: 'https://localhost:3000',
42
+ };
43
+ const configPath = () => join(homedir(), '.beehaven', 'config.json');
44
+ function readConfig() {
45
+ try {
46
+ const p = configPath();
47
+ return existsSync(p) ? JSON.parse(readFileSync(p, 'utf8')) : {};
48
+ }
49
+ catch {
50
+ return {};
51
+ }
52
+ }
53
+ export function resolveAuthOrigin(cfg = readConfig(), env = process.env) {
54
+ let activeEnv = 'prod';
55
+ try {
56
+ // Derive env from the canonical endpoint, not the cfg.envName alias (a fresh login / Mac-app
57
+ // install may write only `endpoint`).
58
+ const { envName } = resolveRelaySelection(cfg);
59
+ if (ENV_AUTH_ORIGINS[envName])
60
+ activeEnv = envName;
61
+ }
62
+ catch { }
63
+ return { authOrigin: env.BEEHAVEN_AUTH_ORIGIN ?? ENV_AUTH_ORIGINS[activeEnv], activeEnv };
64
+ }
65
+ /** The page the web app serves for this flow: app/(auth)/cli/auth. */
66
+ export function cliAuthUrl(authOrigin, state, callbackUrl) {
67
+ return withUtm(`${authOrigin}/cli/auth?state=${state}&redirect=${encodeURIComponent(callbackUrl)}`);
68
+ }
69
+ /** Pre-warning: a non-prod env requires a local dev server. */
70
+ async function warnIfLocalDevDown() {
71
+ const probe = await new Promise((resolve) => {
72
+ const t = setTimeout(() => resolve(false), 800);
73
+ const sock = net.createConnection(3000, '127.0.0.1');
74
+ sock.once('connect', () => {
75
+ clearTimeout(t);
76
+ sock.destroy();
77
+ resolve(true);
78
+ });
79
+ sock.once('error', () => {
80
+ clearTimeout(t);
81
+ resolve(false);
82
+ });
83
+ }).catch(() => false);
84
+ if (!probe) {
85
+ console.log('');
86
+ console.log(` ${color.yellow('!')} localhost:3000 isn't responding.`);
87
+ console.log(` Run ${color.cyan('npm run dev')} (with --experimental-https) in the clearly monorepo first.`);
88
+ console.log('');
89
+ }
90
+ }
91
+ /**
92
+ * Best-effort browser open. macOS `open` dispatches to the user's default browser; xdg-open on
93
+ * Linux; start on Windows. Failure is SURFACED — silent failure was the bug — so the person can
94
+ * paste the URL themselves.
95
+ */
96
+ function openInBrowser(url) {
97
+ try {
98
+ const opener = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'start' : 'xdg-open';
99
+ const proc = spawn(opener, [url], { stdio: 'ignore', detached: true });
100
+ proc.unref();
101
+ proc.on('error', (err) => {
102
+ console.log(` ${color.yellow('!')} Couldn't auto-open browser: ${err.message}`);
103
+ console.log(` Paste this URL into your browser instead:`);
104
+ console.log(` ${color.cyan(url)}`);
105
+ });
106
+ }
107
+ catch (err) {
108
+ console.log(` ${color.yellow('!')} Couldn't spawn opener: ${err?.message ?? err}`);
109
+ console.log(` Paste this URL into your browser instead:`);
110
+ console.log(` ${color.cyan(url)}`);
111
+ }
112
+ }
113
+ /**
114
+ * Tiny success page the browser sees AFTER it navigates to the loopback. Self-contained — no
115
+ * external assets, works offline. Auto-close after 1.5s on supported browsers (Chrome/Firefox allow
116
+ * window.close on self-opened or scripted-navigated tabs).
117
+ */
118
+ const successHtml = `<!doctype html>
119
+ <html><head><meta charset="utf-8"><title>beehaven CLI signed in</title>
120
+ <style>
121
+ body { font: 15px -apple-system, sans-serif; background: #fafaf9; color: #292524;
122
+ display: grid; place-items: center; min-height: 100vh; margin: 0; }
123
+ .card { background: white; padding: 32px 40px; border-radius: 14px;
124
+ box-shadow: 0 1px 3px rgba(0,0,0,.08), 0 8px 24px rgba(0,0,0,.06);
125
+ max-width: 420px; }
126
+ h1 { font-size: 20px; margin: 0 0 8px; letter-spacing: -0.01em; }
127
+ p { color: #57534e; margin: 8px 0; }
128
+ .ok { color: #16a34a; }
129
+ .eyebrow { font-size: 10px; letter-spacing: .22em; color: #a8a29e;
130
+ text-transform: uppercase; margin-bottom: 8px; }
131
+ </style></head>
132
+ <body><div class="card">
133
+ <p class="eyebrow">01 — beehaven CLI</p>
134
+ <h1><span class="ok">✓</span> Signed in</h1>
135
+ <p>The CLI now has your credentials. You can close this tab and
136
+ return to your terminal.</p>
137
+ </div>
138
+ <script>setTimeout(() => { try { window.close(); } catch (e) {} }, 1500);</script>
139
+ </body></html>`;
140
+ const errorHtml = (msg) => `<!doctype html>
141
+ <html><head><meta charset="utf-8"><title>beehaven CLI error</title>
142
+ <style>body{font:15px -apple-system,sans-serif;padding:40px;color:#292524}
143
+ .err{color:#dc2626}</style></head>
144
+ <body><h1 class="err">✗ Sign-in error</h1><p>${msg}</p>
145
+ <p><small>Run <code>beehaven login</code> again from your terminal.</small></p>
146
+ </body></html>`;
147
+ /**
148
+ * Spin up the loopback server (the OS picks a free port), open the browser and resolve with the
149
+ * tokens the `/cli/auth` page hands back. `open` is injectable so the contract can be exercised
150
+ * without a browser.
151
+ */
152
+ export function captureBrowserLogin(opts) {
153
+ const { authOrigin, timeoutMs = LOGIN_TIMEOUT_MS, open = openInBrowser } = opts;
154
+ const state = crypto.randomBytes(16).toString('hex');
155
+ return new Promise((resolve, reject) => {
156
+ const server = http.createServer((req, res) => {
157
+ if (req.method !== 'GET' || !(req.url ?? '').startsWith('/callback')) {
158
+ res.writeHead(404, { 'Content-Type': 'text/plain' });
159
+ res.end('Not Found');
160
+ return;
161
+ }
162
+ // Tokens arrive as ?state=…&idToken=…&refreshToken=…&userId=… because the web side
163
+ // window.location.assign'd here — fetch() from HTTPS to an HTTP loopback is mixed-content
164
+ // blocked by every browser since 2020, so top-level navigation is the standard pattern.
165
+ const url = new URL(req.url, `http://127.0.0.1`);
166
+ const presentedState = url.searchParams.get('state') ?? '';
167
+ const idToken = url.searchParams.get('idToken') ?? '';
168
+ const refreshToken = url.searchParams.get('refreshToken') ?? '';
169
+ const userId = url.searchParams.get('userId') ?? '';
170
+ const email = url.searchParams.get('email') ?? undefined;
171
+ const displayName = url.searchParams.get('displayName') ?? undefined;
172
+ if (presentedState !== state) {
173
+ res.writeHead(403, { 'Content-Type': 'text/html; charset=utf-8' });
174
+ res.end(errorHtml("State mismatch — the CLI didn't initiate this sign-in."));
175
+ return;
176
+ }
177
+ if (!idToken || !refreshToken || !userId) {
178
+ res.writeHead(400, { 'Content-Type': 'text/html; charset=utf-8' });
179
+ res.end(errorHtml('Missing token fields. Try <code>beehaven login</code> again.'));
180
+ return;
181
+ }
182
+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
183
+ res.end(successHtml);
184
+ // Tear down after the response flushes so the browser can render the success page before
185
+ // the connection drops.
186
+ setTimeout(() => {
187
+ try {
188
+ server.close();
189
+ }
190
+ catch { }
191
+ }, 500);
192
+ resolve({ idToken, refreshToken, userId, email, displayName });
193
+ });
194
+ server.on('error', reject);
195
+ // An upper bound so a forgotten browser tab doesn't hang the terminal forever.
196
+ const timeout = setTimeout(() => {
197
+ try {
198
+ server.close();
199
+ }
200
+ catch { }
201
+ reject(new Error(`Sign-in timed out after ${Math.round(timeoutMs / 60_000)} minutes.`));
202
+ }, timeoutMs);
203
+ server.on('close', () => clearTimeout(timeout));
204
+ server.listen(0, '127.0.0.1', () => {
205
+ const addr = server.address();
206
+ const port = addr && typeof addr === 'object' ? addr.port : 0;
207
+ const callbackUrl = `http://127.0.0.1:${port}/callback`;
208
+ const url = cliAuthUrl(authOrigin, state, callbackUrl);
209
+ console.log('');
210
+ console.log(` ${color.cyan('→')} Opening browser to ${authOrigin}/cli/auth …`);
211
+ console.log(` ${color.dim("If it doesn't open: ")}${color.dim(url)}`);
212
+ console.log(` ${color.dim('Listening on ' + callbackUrl + ` (${Math.round(timeoutMs / 60_000)}-min timeout).`)}`);
213
+ console.log('');
214
+ open(url);
215
+ });
216
+ });
217
+ }
218
+ /**
219
+ * Persist the captured tokens. Mirror the Mac app's installDaemon flow exactly: the keychain stores
220
+ * the **idToken** under service='beehaven', account='daemon-token', because that is what
221
+ * relay.ts:Relay.loadConfig reads on every daemon launch. The refresh token stays in config.json
222
+ * where relay.ts:refreshIdToken reads it.
223
+ *
224
+ * Earlier the refreshToken went into the keychain — the wrong slot. The daemon then authenticated
225
+ * its WebSocket with the refresh token, got 401, refreshed successfully but wrote the new idToken
226
+ * to config.json (not the keychain), and the loop repeated on every restart.
227
+ *
228
+ * Throws when config.json cannot be written; a sign-in that saved nothing has not signed anyone in.
229
+ */
230
+ export function persistBrowserLogin(captured) {
231
+ try {
232
+ keychain.setToken(captured.idToken);
233
+ }
234
+ catch { }
235
+ try {
236
+ const cfgDir = join(homedir(), '.beehaven');
237
+ if (!existsSync(cfgDir))
238
+ mkdirSync(cfgDir, { recursive: true, mode: 0o700 });
239
+ const existing = readConfig();
240
+ /**
241
+ * ⚠⚠ SIGNING IN WRITES A DIAL TARGET. It used to write only credentials and lean on
242
+ * `...existing` to carry `endpoint` forward — which PRESERVES one and can never CREATE one.
243
+ * So on a config that had none (a fresh install before the Mac app's `install()` ran, or any
244
+ * config after `logout`, which deletes `endpoint` by name) login produced valid tokens with
245
+ * nothing to connect to, and the daemon reported "Token refresh failed" while the tray read
246
+ * "agent offline". A login that leaves the user unable to connect has not signed anyone in.
247
+ *
248
+ * ⚠ RESOLVED FROM THE CONFIG, NEVER A HARDCODED CONSTANT — `resolveRelaySelection` keys off
249
+ * whichever key is present and defaults to prod only when neither is. Pinning a literal here is
250
+ * the bug the old setup-relay.ts flow had: it sent every staging login to the prod relay.
251
+ *
252
+ * ⚠ BOTH KEYS, KEPT IN SYNC, exactly as `beehaven env` writes them — `endpoint` is what the
253
+ * relay client dials and `relayUrl` is the alias other surfaces read.
254
+ */
255
+ const { url: dialUrl } = resolveRelaySelection(existing);
256
+ const next = {
257
+ ...existing,
258
+ onboarded: true,
259
+ tier: existing.tier ?? 'connected',
260
+ userId: captured.userId,
261
+ email: captured.email ?? null,
262
+ displayName: captured.displayName ?? null,
263
+ tokenStorage: 'keychain',
264
+ refreshToken: captured.refreshToken,
265
+ token: captured.idToken,
266
+ endpoint: dialUrl,
267
+ relayUrl: dialUrl,
268
+ };
269
+ writeFileSync(configPath(), JSON.stringify(next, null, 2), { mode: 0o600 });
270
+ }
271
+ catch (err) {
272
+ throw new Error(`Failed to write config: ${err?.message ?? err}`);
273
+ }
274
+ }
275
+ /** Resolve the origin, warn about a missing local dev server, capture and persist. */
276
+ export async function browserLogin() {
277
+ const { authOrigin, activeEnv } = resolveAuthOrigin();
278
+ if (activeEnv !== 'prod')
279
+ await warnIfLocalDevDown();
280
+ const captured = await captureBrowserLogin({ authOrigin });
281
+ persistBrowserLogin(captured);
282
+ return captured;
283
+ }
@@ -53,9 +53,9 @@ export const PUBLIC_BUILD = true;
53
53
  * ⚠ REWRITTEN IN `dist/` AT BUILD TIME, like `PUBLIC_BUILD`. `unstamped` is what a source checkout
54
54
  * carries and what `tsx`/`vitest` see, and it is honest: nothing has stamped them.
55
55
  */
56
- export const BUILD_SHA = '8585349e92e9-dirty';
56
+ export const BUILD_SHA = '4f251482a5c6-dirty';
57
57
  /** ISO-8601 minute precision, UTC. Rewritten in `dist/` by `scripts/stamp-build-channel.mjs`. */
58
- export const BUILD_TIME = '2026-10-02T00:47Z';
58
+ export const BUILD_TIME = '2026-10-06T06:45Z';
59
59
  /**
60
60
  * The build identity as one short string, for `--version`.
61
61
  *