@yanzc/claude-pro 0.9.0 → 0.9.2

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 (57) hide show
  1. package/README.md +342 -320
  2. package/package.json +1 -2
  3. package/src/agent.js +240 -62
  4. package/src/agents.js +3 -2
  5. package/src/api.js +83 -41
  6. package/src/browser/broker.js +367 -0
  7. package/src/browser/cdp.js +114 -0
  8. package/src/browser/render.js +242 -0
  9. package/src/browser/session.js +948 -0
  10. package/src/browser/snapshot.js +212 -0
  11. package/src/cache.js +1 -1
  12. package/src/checkpoints.js +1 -0
  13. package/src/commands.js +177 -71
  14. package/src/compaction.js +75 -0
  15. package/src/config.js +153 -153
  16. package/src/context.js +45 -18
  17. package/src/filestate.js +2 -1
  18. package/src/gateway.js +208 -164
  19. package/src/hooks.js +2 -2
  20. package/src/keepalive.js +1 -1
  21. package/src/main.js +52 -40
  22. package/src/mcp.js +2 -2
  23. package/src/peers.js +1 -10
  24. package/src/print.js +9 -3
  25. package/src/prompt-profiles.js +0 -6
  26. package/src/prompts.js +6 -62
  27. package/src/ratelimit.js +3 -5
  28. package/src/remote.js +26 -10
  29. package/src/restart.js +3 -0
  30. package/src/runtime.js +33 -10
  31. package/src/selfcheck.js +3 -3
  32. package/src/session.js +93 -3
  33. package/src/supervisor.js +10 -1
  34. package/src/tools/bash.js +19 -18
  35. package/src/tools/browser.js +365 -0
  36. package/src/tools/code.js +430 -0
  37. package/src/tools/effort.js +3 -4
  38. package/src/tools/files.js +92 -19
  39. package/src/tools/index.js +6 -0
  40. package/src/tools/notebook.js +11 -4
  41. package/src/tools/processes.js +274 -0
  42. package/src/tools/search.js +104 -21
  43. package/src/tools/web.js +316 -46
  44. package/src/trace.js +0 -4
  45. package/src/ui/ansi.js +92 -13
  46. package/src/ui/dialogs.js +16 -54
  47. package/src/ui/editor.js +231 -34
  48. package/src/ui/markdown.js +1 -2
  49. package/src/ui/render.js +1 -2
  50. package/src/ui/repl.js +246 -119
  51. package/src/ui/screen.js +139 -31
  52. package/src/updater.js +135 -165
  53. package/src/utils/clipboard.js +5 -3
  54. package/src/utils/paths.js +15 -17
  55. package/src/utils/shell.js +75 -21
  56. package/.env.example +0 -29
  57. package/src/verify.js +0 -57
package/src/api.js CHANGED
@@ -1,10 +1,11 @@
1
1
  // Thin layer over the Anthropic SDK: builds request params from config and turns the
2
2
  // raw SSE stream into a fully assembled assistant message while reporting progress.
3
3
 
4
- import Anthropic from '@anthropic-ai/sdk';
5
- import { humanDuration, parseRateLimit, parseRetryAfter, planRetry, sleepUntil, timing } from './ratelimit.js';
4
+ // The SDK is loaded with the first request: importing it took about 70 ms of every start, restarts included.
5
+ let Anthropic = null;
6
+ import { parseRateLimit, parseRetryAfter, planRetry, sleepUntil, timing } from './ratelimit.js';
6
7
  import { cacheControl, cachePlanOf, fingerprint } from './cache.js';
7
- import { gatewayLogin, fetchGatewayModels, cachedGatewayModel, gatewayEffort, gatewayDefaultEffort } from './gateway.js';
8
+ import { gatewayLogin, loadGatewayModels, cachedGatewayModel, gatewayEffort, gatewayDefaultEffort, nearestEffort } from './gateway.js';
8
9
  import { fitImagesIn } from './utils/images.js';
9
10
  import { costOf } from './pricing.js';
10
11
 
@@ -13,13 +14,13 @@ const SIGNATURE_PREFIX = 'cgw1:';
13
14
 
14
15
  // The gateway provider's key, from /login. Without one the request fails the way a refused key does.
15
16
  function gatewayKey(config) {
16
- const login = gatewayLogin(config.gatewayUrl, config.env.CLAUDE_PRO_GATEWAY_API_KEY);
17
- const key = login?.apiKey || config.env.CLAUDE_PRO_GATEWAY_API_KEY;
17
+ const key = gatewayLogin(config.gatewayUrl)?.apiKey;
18
18
  if (!key) throw new APIError(`Not logged in to the gateway ${config.gatewayUrl}. Run /login and choose the gateway.`, { status: 401, retryable: false });
19
19
  return key;
20
20
  }
21
21
 
22
- export function getClient(config) {
22
+ export async function getClient(config) {
23
+ Anthropic ??= (await import('@anthropic-ai/sdk')).default;
23
24
  const authToken = gatewayKey(config);
24
25
  const key = `${config.gatewayUrl}|${authToken}|${config.apiTimeout}`;
25
26
  if (cached?.key === key && cached.fetch === globalThis.fetch) return cached.client;
@@ -108,14 +109,7 @@ const thinkingStaysOn = new Set();
108
109
 
109
110
  // The effort a model uses when none is sent (docs.claude.com, "Effort"): medium on Opus 5.5 and Haiku 5.5, high on
110
111
  // the other models that take one; null for a model that takes none or is not known.
111
- const gatewayModelInfo = (config, id) => cachedGatewayModel(gatewayLogin(config.gatewayUrl, config.env.CLAUDE_PRO_GATEWAY_API_KEY), id);
112
- const EFFORT_ORDER = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra'];
113
- const nearestEffort = (effort, supported) => {
114
- if (!effort || !supported.length || supported.includes(effort)) return effort;
115
- const want = EFFORT_ORDER.indexOf(effort);
116
- return supported.reduce((best, item) => Math.abs(EFFORT_ORDER.indexOf(item) - want) < Math.abs(EFFORT_ORDER.indexOf(best) - want) ? item : best, supported[0]);
117
- };
118
-
112
+ const gatewayModelInfo = (config, id) => cachedGatewayModel(gatewayLogin(config.gatewayUrl), id);
119
113
  export function defaultEffort(modelId, config = null) {
120
114
  const id = String(modelId || '');
121
115
  if (!effortSupported(id)) return null;
@@ -181,7 +175,7 @@ function withoutCodexThinking(messages) {
181
175
  export function buildParams(config, { model, system, messages, tools, maxTokens, effort, cacheBucket = 'main', cacheMessages = true }) {
182
176
  const wanted = maxTokens || config.maxOutputTokens;
183
177
  const refused = cacheRefused.get(cacheKey(config, model.id));
184
- const caching = !config.promptCachingDisabled(model.id);
178
+ const caching = !config.promptCachingDisabled();
185
179
  const ttl = refused?.has('ttl') ? '5m' : config.cacheTtl(cacheBucket);
186
180
  const mark = (place) => (caching && !refused?.has(place) ? { ...cacheControl(ttl) } : null);
187
181
  const systemMark = mark('system');
@@ -192,7 +186,9 @@ export function buildParams(config, { model, system, messages, tools, maxTokens,
192
186
  const params = {
193
187
  model: model.id,
194
188
  max_tokens: outputCaps.has(model.id) ? Math.min(wanted, outputCaps.get(model.id)) : wanted,
195
- system: [{ type: 'text', text: system, ...(systemMark ? { cache_control: systemMark } : {}) }],
189
+ // An empty system prompt (an empty profile chosen with /prompts) is left out: Anthropic refuses an empty text
190
+ // block ("cache_control cannot be set for empty text blocks"), and DeepSeek and the others take none as well.
191
+ ...(typeof system === 'string' && system.trim() ? { system: [{ type: 'text', text: system, ...(systemMark ? { cache_control: systemMark } : {}) }] } : {}),
196
192
  messages: withCacheControl(messages, cacheMessages ? mark('messages') : null),
197
193
  stream: true,
198
194
  };
@@ -211,11 +207,14 @@ export function buildParams(config, { model, system, messages, tools, maxTokens,
211
207
  }
212
208
 
213
209
  export class APIError extends Error {
214
- constructor(message, { status, retryable, promptTooLong, retryAfterMs = null, rateLimit = null, overloaded = false } = {}) {
210
+ constructor(message, { status, retryable, promptTooLong, promptTokens = 0, promptLimit = 0, retryAfterMs = null, rateLimit = null, overloaded = false } = {}) {
215
211
  super(message);
216
212
  this.status = status;
217
213
  this.retryable = retryable;
218
214
  this.promptTooLong = promptTooLong;
215
+ // Anthropic says how long it was and what fits ("prompt is too long: 1003873 tokens > 1000000 maximum"); 0: not said
216
+ this.promptTokens = promptTokens;
217
+ this.promptLimit = promptLimit;
219
218
  this.overloaded = overloaded; // 529 / overloaded_error: waited out with its own backoff (see planRetry)
220
219
  this.retryAfterMs = retryAfterMs; // what the server's Retry-After header asked for
221
220
  this.rateLimit = rateLimit; // what the rate limit headers say (see ratelimit.js)
@@ -223,23 +222,27 @@ export class APIError extends Error {
223
222
  }
224
223
 
225
224
  function describeError(err, config) {
226
- if (err?.name === 'AbortError' || err instanceof Anthropic.APIUserAbortError) return err;
225
+ if (err?.name === 'AbortError' || (Anthropic && err instanceof Anthropic.APIUserAbortError)) return err;
227
226
  const status = err?.status;
228
227
  let msg = err?.error?.error?.message || err?.error?.message || err?.message || String(err);
229
- const promptTooLong = /prompt is too long|context length|maximum context|too many tokens|context_length_exceeded/i.test(msg);
228
+ const promptTooLong = /prompt is too long|context length|maximum context|too many tokens|context_length_exceeded|exceeds the context window/i.test(msg);
230
229
  if (err instanceof APIError) return err;
231
230
  if (status === 401) msg = `The gateway refused the login (401). Run /login to log in again. ${msg}`;
232
231
  if (status === 402) msg = `The gateway account's balance is too low for this request. Top up at ${config.gatewayUrl}/user (or run /login to check the balance). ${msg}`;
233
- const retryable = !status || status === 408 || status === 409 || status === 429 || status >= 500;
232
+ // A prompt over the window fails the same way every time, so it is not retried: the agent compacts at once. Through
233
+ // the gateway a GPT overflow comes in the stream, without a 4xx: "Your input exceeds the context window of this
234
+ // model. ... (context_length_exceeded)", and was sent 6 more times, with the waits in between, before compacting.
235
+ const retryable = !promptTooLong && (!status || status === 408 || status === 409 || status === 429 || status >= 500);
234
236
  const header = typeof err?.headers?.get === 'function' ? err.headers.get('retry-after') : err?.headers?.['retry-after'];
235
237
  const overloaded = status === 529 || (err?.error?.error?.type || err?.error?.type) === 'overloaded_error';
236
- return new APIError(msg, { status, retryable, promptTooLong, retryAfterMs: parseRetryAfter(header), rateLimit: parseRateLimit(err?.headers, timing.now()), overloaded });
238
+ const sizes = promptTooLong ? /(\d+) tokens > (\d+) maximum/.exec(msg) : null;
239
+ return new APIError(msg, { status, retryable, promptTooLong, promptTokens: Number(sizes?.[1]) || 0, promptLimit: Number(sizes?.[2]) || 0, retryAfterMs: parseRetryAfter(header), rateLimit: parseRateLimit(err?.headers, timing.now()), overloaded });
237
240
  }
238
241
 
239
242
  // Our own aborts are named AbortError and the SDK's is an APIUserAbortError. The message test only
240
243
  // accepts the bare "aborted" wording: a server error that merely mentions "aborted" is not the user.
241
244
  export function isAbort(err) {
242
- return err?.name === 'AbortError' || err instanceof Anthropic.APIUserAbortError || /^(?:request was )?aborted\.?$/i.test(err?.message || '');
245
+ return err?.name === 'AbortError' || (Anthropic !== null && err instanceof Anthropic.APIUserAbortError) || /^(?:request was )?aborted\.?$/i.test(err?.message || '');
243
246
  }
244
247
 
245
248
  // USD for a request at the list prices (see pricing.js), by the model that answered, else the one asked for;
@@ -262,28 +265,30 @@ function charge(config, requested, served, usage) {
262
265
  // {type:'rate_limit_resume', waitedMs} the repeated request was accepted: the pause is over
263
266
  // {type:'reset'} partial output from a failed attempt must be discarded
264
267
  // `waitForRateLimit: false` reports a rate limit as an error instead of waiting for it (side queries
265
- // where nobody wants to sit through a pause). Returns {message, usage, stopReason, model, cost, cache}.
268
+ // where nobody wants to sit through a pause). `afterPause({woken})` is called when a pause for a rate limit (or an
269
+ // overloaded API) is over, before the request is repeated: it may return the request to go on with instead (the
270
+ // conversation made smaller once its prompt cache has run out, or another model), or null for the same one.
271
+ // `pauseControl`: an object that gets a wake() function while such a pause lasts; calling it ends the pause at
272
+ // once (the user chose another model to go on with), and afterPause is told so.
273
+ // Returns {message, usage, stopReason, model, cost, cache}.
266
274
  // What each request costs (an interrupted one too) goes to config.onCost, the conversation's running total.
267
- export async function streamMessage(config, request, { signal, onEvent = () => {}, waitForRateLimit = true } = {}) {
275
+ export async function streamMessage(config, request, { signal, onEvent = () => {}, waitForRateLimit = true, afterPause = null, pauseControl = null } = {}) {
268
276
  if (signal?.aborted) throw Object.assign(new Error('aborted'), { name: 'AbortError', partial: [] });
269
277
  // Load gateway model metadata before the synchronous parameter builder; the cache is keyed by gateway and key,
270
- // so changing accounts or gateway URLs cannot leak a model's effort levels into another context.
271
- if (/^gpt-/i.test(request.model?.id)) {
272
- const login = gatewayLogin(config.gatewayUrl, config.env.CLAUDE_PRO_GATEWAY_API_KEY);
273
- if (login) {
274
- // A gateway that does not answer costs at most a few seconds once (see fetchGatewayModels), not the request.
275
- try { await fetchGatewayModels(login, { signal }); } catch { if (signal?.aborted) throw Object.assign(new Error('aborted'), { name: 'AbortError', partial: [] }); }
276
- }
277
- }
278
- const client = getClient(config);
279
- const params = buildParams(config, request);
278
+ // so changing accounts or gateway URLs cannot leak a model's effort levels into another context. A gateway that
279
+ // does not answer costs at most a few seconds once (see fetchGatewayModels), not the request.
280
+ await loadGatewayModels(config, signal);
281
+ if (signal?.aborted) throw Object.assign(new Error('aborted'), { name: 'AbortError', partial: [] });
282
+ const client = await getClient(config);
283
+ let params = buildParams(config, request);
280
284
  // The gateway keeps a conversation on the upstream account that served it, where its prompt cache is; the
281
285
  // session id names the conversation, in the header Claude Code sends it in.
282
- const options = { signal, ...(config.usesGateway && config.sessionId ? { headers: { 'X-Claude-Code-Session-Id': config.sessionId } } : {}) };
286
+ const options = { signal, ...(config.sessionId ? { headers: { 'X-Claude-Code-Session-Id': config.sessionId } } : {}) };
283
287
  let imagesFitted = false;
284
288
  const refused = new Set(); // what the endpoint refused for this request: remembered once a request got through
285
289
  const retryState = { attempt: 0, rateLimitHits: 0, waitedMs: 0, overloaded: 0, overloadedWaitMs: 0 };
286
290
  let paused = null; // the plan of the pause in progress (see planRetry)
291
+ let woken = false; // the pause was ended by pauseControl.wake()
287
292
  for (;;) {
288
293
  let emitted = false;
289
294
  const startedAt = Date.now(); // the cache TTL counts from the start of the request, not from the end of the reply
@@ -296,7 +301,7 @@ export async function streamMessage(config, request, { signal, onEvent = () => {
296
301
  if (paused) {
297
302
  const overloaded = paused.overloaded;
298
303
  paused = null;
299
- onEvent({ type: 'rate_limit_resume', waitedMs: overloaded ? retryState.overloadedWaitMs : retryState.waitedMs, ...(overloaded ? { overloaded } : {}) });
304
+ onEvent({ type: 'rate_limit_resume', waitedMs: overloaded ? retryState.overloadedWaitMs : retryState.waitedMs, ...(overloaded ? { overloaded } : {}), ...(woken ? { woken } : {}) });
300
305
  }
301
306
  let stopReason = null;
302
307
  let stopped = false;
@@ -311,7 +316,8 @@ export async function streamMessage(config, request, { signal, onEvent = () => {
311
316
  break;
312
317
  case 'content_block_start': {
313
318
  const b = { ...ev.content_block };
314
- if (b.type === 'tool_use') { b.input = {}; jsonBufs[ev.index] = ''; }
319
+ // (server_tool_use: a search the model ran on the server, in WebSearch's request; its input is the query)
320
+ if (b.type === 'tool_use' || b.type === 'server_tool_use') { b.input = {}; jsonBufs[ev.index] = ''; }
315
321
  if (b.type === 'text') b.text = b.text || '';
316
322
  if (b.type === 'thinking') { b.thinking = b.thinking || ''; b.signature = b.signature || ''; }
317
323
  blocks[ev.index] = b;
@@ -326,6 +332,8 @@ export async function streamMessage(config, request, { signal, onEvent = () => {
326
332
  if (d.type === 'text_delta') { b.text += d.text; onEvent({ type: 'text', index: ev.index, text: d.text }); }
327
333
  else if (d.type === 'thinking_delta') { b.thinking += d.thinking; onEvent({ type: 'thinking', index: ev.index, text: d.thinking }); }
328
334
  else if (d.type === 'signature_delta') b.signature = (b.signature || '') + d.signature;
335
+ // where a text block's statement comes from, in a web search answer: kept (see WebSearch)
336
+ else if (d.type === 'citations_delta') (b.citations ||= []).push(d.citation);
329
337
  else if (d.type === 'input_json_delta') {
330
338
  jsonBufs[ev.index] += d.partial_json;
331
339
  onEvent({ type: 'tool_input', index: ev.index, partial: jsonBufs[ev.index], block: b });
@@ -334,7 +342,7 @@ export async function streamMessage(config, request, { signal, onEvent = () => {
334
342
  }
335
343
  case 'content_block_stop': {
336
344
  const b = blocks[ev.index];
337
- if (b?.type === 'tool_use') {
345
+ if (b?.type === 'tool_use' || b?.type === 'server_tool_use') {
338
346
  const raw = jsonBufs[ev.index];
339
347
  try { b.input = raw ? JSON.parse(raw) : {}; } catch { b.input = { __invalid_json: raw }; }
340
348
  }
@@ -365,12 +373,19 @@ export async function streamMessage(config, request, { signal, onEvent = () => {
365
373
  const cost = charge(config, params.model, model, usage);
366
374
  return { message: { role: 'assistant', content }, usage, stopReason, model, cost, cache: { ...cachePlanOf(params), fingerprint: fingerprint(params), at: startedAt } };
367
375
  } catch (raw) {
368
- if (signal?.aborted || isAbort(raw)) {
369
- // An interrupted reply is billed for what it had read and written: the output so far is estimated.
376
+ // A reply cut off (interrupted, or failed on the way: a stream error, a stream that ended early) is billed for
377
+ // what it had read and written once it started: the output so far is estimated. A failure before it started
378
+ // (an error status) costs nothing.
379
+ const chargeCut = () => {
380
+ if (usage.input_tokens == null) return;
370
381
  const written = blocks.reduce((n, b) => n + (b?.text?.length || 0) + (b?.thinking?.length || 0), 0) + jsonBufs.join('').length;
371
382
  charge(config, params.model, model, { ...usage, output_tokens: Math.max(usage.output_tokens || 0, Math.ceil(written / 4)) });
383
+ };
384
+ if (signal?.aborted || isAbort(raw)) {
385
+ chargeCut();
372
386
  throw Object.assign(new Error('aborted'), { name: 'AbortError', partial: raw?.partial || [] });
373
387
  }
388
+ chargeCut();
374
389
  const err = describeError(raw, config);
375
390
  // Not every model takes an effort level. Leave it out for this one, and for the rest of the session.
376
391
  if (err.status === 400 && params.output_config && /does not support the effort parameter/i.test(err.message)) {
@@ -426,8 +441,15 @@ export async function streamMessage(config, request, { signal, onEvent = () => {
426
441
  ? { overloaded: true, waitedMs: retryState.overloadedWaitMs, maxWaitMs: config.overloadedMaxWait }
427
442
  : { waitedMs: retryState.waitedMs, maxWaitMs: config.rateLimitMaxWait }),
428
443
  });
429
- await sleepUntil(plan.resumeAt, signal);
444
+ woken = await sleepThroughPause(plan.resumeAt, signal, pauseControl);
445
+ if (woken) { // what was not waited does not count against the time the session may wait
446
+ const left = Math.max(0, plan.resumeAt - timing.now());
447
+ if (plan.overloaded) retryState.overloadedWaitMs = Math.max(0, retryState.overloadedWaitMs - left);
448
+ else retryState.waitedMs = Math.max(0, retryState.waitedMs - left);
449
+ }
430
450
  retryState.attempt = 0; // the pause is a fresh start: quick retries made before it do not count after it
451
+ const next = afterPause?.({ woken });
452
+ if (next) params = buildParams(config, next);
431
453
  } else {
432
454
  onEvent({ type: 'retry', attempt: plan.attempt, error: err, delayMs: plan.delayMs, maxRetries: plan.maxRetries });
433
455
  await sleepUntil(plan.resumeAt, signal);
@@ -436,6 +458,26 @@ export async function streamMessage(config, request, { signal, onEvent = () => {
436
458
  }
437
459
  }
438
460
 
461
+ // Sleep until `deadline`, or until control.wake() is called (true then). The user's interrupt still throws.
462
+ async function sleepThroughPause(deadline, signal, control) {
463
+ if (!control) { await sleepUntil(deadline, signal); return false; }
464
+ const ac = new AbortController();
465
+ const onAbort = () => ac.abort();
466
+ if (signal?.aborted) ac.abort();
467
+ signal?.addEventListener('abort', onAbort, { once: true });
468
+ let woken = false;
469
+ control.wake = () => { woken = true; ac.abort(); };
470
+ try {
471
+ await sleepUntil(deadline, ac.signal);
472
+ } catch (err) {
473
+ if (!woken || signal?.aborted) throw err;
474
+ } finally {
475
+ control.wake = null;
476
+ signal?.removeEventListener('abort', onAbort);
477
+ }
478
+ return woken;
479
+ }
480
+
439
481
  // One-shot, non-streaming helper for small side queries (summaries, titles, web page extraction).
440
482
  // Nothing here can tell the user that it is paused, so a rate limit is reported as an error by default
441
483
  // instead of being waited for out of sight; waitForRateLimit: true is for a caller that accepts that.
@@ -0,0 +1,367 @@
1
+ // The connections to the user's own browsers, held by one process for every claude-pro session of this user.
2
+ //
3
+ // A browser whose remote debugging was turned on in its settings (edge://inspect, chrome://inspect) asks the user to
4
+ // allow every new connection, and has no "always allow". With a connection per claude-pro process, every restart
5
+ // (one after every change to claude-pro's own source, in every open session) and every other session asked again:
6
+ // the user had to click Allow over and over. The broker keeps one connection per browser instance and lends it to
7
+ // the sessions over a local pipe, passing the DevTools messages through: their ids renumbered, the events of an
8
+ // attached tab sent to the session that attached it, the browser's own events to all. It closes a connection ten
9
+ // minutes after the last session let go of it (a restart takes seconds), and exits when it has none.
10
+ //
11
+ // It runs as `node broker.js --serve`, started by the first session that needs it (connectShared); a session that
12
+ // cannot reach it connects on its own, as before. Only browsers on this computer are connected to, and a session
13
+ // must show the token the broker wrote into the config directory.
14
+
15
+ import net from 'node:net';
16
+ import fs from 'node:fs';
17
+ import path from 'node:path';
18
+ import crypto from 'node:crypto';
19
+ import { spawn } from 'node:child_process';
20
+ import { fileURLToPath } from 'node:url';
21
+ import { Cdp, CdpError, abortError } from './cdp.js';
22
+ import { CONFIG_DIR } from '../config.js';
23
+
24
+ export const brokerLimits = {
25
+ keepMs: 10 * 60_000, // a connection no session uses any more stays this long
26
+ exitMs: 30_000, // the broker exits after this long with no connection and no session
27
+ openMs: 120_000, // the user may take a while to click Allow
28
+ startMs: 5_000, // for a new broker to start listening
29
+ };
30
+ const PROTOCOL = 1;
31
+
32
+ const pipePath = (dir) => (process.platform === 'win32'
33
+ ? `\\\\.\\pipe\\claude-pro-browser-${crypto.createHash('sha1').update(path.resolve(dir).toLowerCase()).digest('hex').slice(0, 12)}`
34
+ : path.join(dir, 'browser-broker.sock'));
35
+ const stateFile = (dir) => path.join(dir, 'browser-broker.json');
36
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
37
+
38
+ const onThisComputer = (url) => {
39
+ try {
40
+ const u = new URL(url);
41
+ return /^wss?:$/.test(u.protocol) && ['127.0.0.1', 'localhost', '[::1]'].includes(u.hostname);
42
+ } catch { return false; }
43
+ };
44
+
45
+ // Newline-separated JSON on a socket: `onLine(text)` for each line.
46
+ function lines(sock, onLine) {
47
+ let buf = '';
48
+ sock.setEncoding('utf8');
49
+ sock.on('data', (d) => {
50
+ buf += d;
51
+ for (let i = buf.indexOf('\n'); i >= 0; i = buf.indexOf('\n')) {
52
+ const line = buf.slice(0, i);
53
+ buf = buf.slice(i + 1);
54
+ if (line) onLine(line);
55
+ }
56
+ });
57
+ }
58
+
59
+ // ---- The broker
60
+
61
+ // One browser connection, shared by the sessions (`clients`) that use it.
62
+ class Upstream {
63
+ constructor(url, onGone) {
64
+ this.url = url;
65
+ this.onGone = onGone;
66
+ this.ws = null;
67
+ this.connecting = null;
68
+ this.clients = new Set();
69
+ this.pending = new Map(); // id sent to the browser -> {client, id: the client's own, method}
70
+ this.owners = new Map(); // sessionId of an attached tab -> the client that attached it
71
+ this.nextId = 1;
72
+ this.opens = 0; // connections made (each one the user had to allow)
73
+ this.keep = null;
74
+ }
75
+
76
+ get open() { return this.ws?.readyState === 1; }
77
+
78
+ connect() {
79
+ if (this.open) return Promise.resolve();
80
+ this.connecting ??= new Promise((resolve, reject) => {
81
+ const ws = new WebSocket(this.url);
82
+ let settled = false;
83
+ const fail = (err) => {
84
+ if (settled) return;
85
+ settled = true;
86
+ clearTimeout(timer);
87
+ this.connecting = null;
88
+ try { ws.close(); } catch { /* not open */ }
89
+ reject(err);
90
+ };
91
+ const timer = setTimeout(() => fail(new Error(`the browser did not accept the connection within ${brokerLimits.openMs / 1000} s (nobody allowed remote debugging?)`)), brokerLimits.openMs);
92
+ ws.onopen = () => {
93
+ if (settled) { try { ws.close(); } catch { /* gone */ } return; }
94
+ settled = true;
95
+ clearTimeout(timer);
96
+ this.connecting = null;
97
+ this.ws = ws;
98
+ this.opens++;
99
+ ws.onmessage = (m) => this.receive(m.data);
100
+ ws.onclose = () => this.lost('the browser closed the connection');
101
+ ws.onerror = () => {};
102
+ resolve();
103
+ };
104
+ ws.onerror = (e) => fail(new Error(`cannot connect to the browser: ${e?.message || e?.error?.message || 'connection refused or declined'}`));
105
+ ws.onclose = (e) => fail(new Error(`the browser refused the connection${e?.code && e.code !== 1006 ? ` (${e.code}${e.reason ? ` ${e.reason}` : ''})` : ''}: remote debugging was declined or turned off`));
106
+ });
107
+ return this.connecting;
108
+ }
109
+
110
+ add(client) {
111
+ this.clients.add(client);
112
+ clearTimeout(this.keep);
113
+ this.keep = null;
114
+ }
115
+
116
+ // A session let go: its tabs are detached, and the connection is kept a while for the next one.
117
+ remove(client) {
118
+ if (!this.clients.delete(client)) return;
119
+ for (const [sessionId, owner] of this.owners) {
120
+ if (owner !== client) continue;
121
+ this.owners.delete(sessionId);
122
+ if (this.open) this.ws.send(JSON.stringify({ id: this.nextId++, method: 'Target.detachFromTarget', params: { sessionId } }));
123
+ }
124
+ for (const [id, p] of this.pending) if (p.client === client) this.pending.delete(id);
125
+ if (!this.clients.size) {
126
+ clearTimeout(this.keep);
127
+ this.keep = setTimeout(() => this.close(), brokerLimits.keepMs);
128
+ }
129
+ }
130
+
131
+ send(client, msg) {
132
+ if (!this.open) {
133
+ if (msg.id !== undefined) client.write({ id: msg.id, error: { code: -32000, message: 'the browser connection is closed' } });
134
+ return;
135
+ }
136
+ const id = this.nextId++;
137
+ this.pending.set(id, { client, id: msg.id, method: msg.method });
138
+ this.ws.send(JSON.stringify({ ...msg, id }));
139
+ }
140
+
141
+ receive(data) {
142
+ let msg;
143
+ try { msg = JSON.parse(typeof data === 'string' ? data : Buffer.from(data).toString('utf8')); } catch { return; }
144
+ if (msg.id !== undefined) {
145
+ const p = this.pending.get(msg.id);
146
+ if (!p) return; // a detach of the broker's own
147
+ this.pending.delete(msg.id);
148
+ if (p.method === 'Target.attachToTarget' && msg.result?.sessionId) this.owners.set(msg.result.sessionId, p.client);
149
+ p.client.write({ ...msg, id: p.id });
150
+ return;
151
+ }
152
+ if (msg.sessionId) { this.owners.get(msg.sessionId)?.write(msg); return; }
153
+ if (msg.method === 'Target.detachedFromTarget') this.owners.delete(msg.params?.sessionId);
154
+ for (const c of this.clients) c.write(msg);
155
+ }
156
+
157
+ lost(reason) {
158
+ this.ws = null;
159
+ for (const c of [...this.clients]) c.end(reason);
160
+ this.clients.clear();
161
+ this.gone();
162
+ }
163
+
164
+ close() {
165
+ const ws = this.ws;
166
+ this.ws = null;
167
+ if (ws) {
168
+ ws.onclose = null;
169
+ try { ws.close(); } catch { /* gone */ }
170
+ }
171
+ this.gone();
172
+ }
173
+
174
+ gone() {
175
+ clearTimeout(this.keep);
176
+ this.keep = null;
177
+ this.onGone(this);
178
+ }
179
+ }
180
+
181
+ export function serve(dir = CONFIG_DIR) {
182
+ const token = crypto.randomBytes(24).toString('hex');
183
+ const upstreams = new Map(); // url -> Upstream
184
+ let sessions = 0;
185
+ let exitTimer = null;
186
+ const maybeExit = () => {
187
+ clearTimeout(exitTimer);
188
+ if (!sessions && !upstreams.size) exitTimer = setTimeout(() => process.exit(0), brokerLimits.exitMs);
189
+ };
190
+ const server = net.createServer((sock) => {
191
+ sessions++;
192
+ clearTimeout(exitTimer);
193
+ let upstream = null;
194
+ let greeted = false;
195
+ const client = {
196
+ write: (msg) => { if (!sock.destroyed) sock.write(`${JSON.stringify(msg)}\n`); },
197
+ end: (reason) => { client.write({ t: 'closed', reason }); sock.end(); },
198
+ };
199
+ const refuse = (message, extra = {}) => { client.write({ t: 'error', message, ...extra }); sock.end(); };
200
+ const hello = async (msg) => {
201
+ if (msg.token !== token) return refuse('not allowed');
202
+ if (msg.protocol !== PROTOCOL) return refuse(`the broker speaks protocol ${PROTOCOL}`, { protocol: PROTOCOL });
203
+ if (msg.t === 'status') {
204
+ client.write({ t: 'status', pid: process.pid, upstreams: [...upstreams.values()].map((u) => ({ url: u.url, sessions: u.clients.size, opens: u.opens, open: u.open })) });
205
+ return sock.end();
206
+ }
207
+ if (!onThisComputer(msg.url)) return refuse('only a browser on this computer');
208
+ let u = upstreams.get(msg.url);
209
+ if (!u) {
210
+ u = new Upstream(msg.url, (gone) => { if (upstreams.get(gone.url) === gone) upstreams.delete(gone.url); maybeExit(); });
211
+ upstreams.set(msg.url, u);
212
+ }
213
+ upstream = u;
214
+ u.add(client);
215
+ const waiting = setTimeout(() => client.write({ t: 'waiting' }), 1500);
216
+ try {
217
+ await u.connect();
218
+ clearTimeout(waiting);
219
+ client.write({ t: 'open' });
220
+ } catch (e) {
221
+ clearTimeout(waiting);
222
+ u.remove(client);
223
+ if (!u.clients.size && !u.open) u.gone();
224
+ refuse(e.message);
225
+ }
226
+ };
227
+ lines(sock, (line) => {
228
+ let msg;
229
+ try { msg = JSON.parse(line); } catch { return; }
230
+ if (!greeted) { greeted = true; hello(msg); return; }
231
+ if (upstream?.open) upstream.send(client, msg);
232
+ });
233
+ sock.on('close', () => {
234
+ sessions--;
235
+ upstream?.remove(client);
236
+ maybeExit();
237
+ });
238
+ sock.on('error', () => {});
239
+ });
240
+ server.on('error', () => process.exit(0)); // another broker has the pipe: it serves
241
+ server.listen(pipePath(dir), () => {
242
+ try { fs.writeFileSync(stateFile(dir), JSON.stringify({ pid: process.pid, pipe: pipePath(dir), token, protocol: PROTOCOL }), { mode: 0o600 }); } catch { process.exit(1); }
243
+ maybeExit();
244
+ });
245
+ return server;
246
+ }
247
+
248
+ // ---- A session's side
249
+
250
+ function readState(dir) {
251
+ try { return JSON.parse(fs.readFileSync(stateFile(dir), 'utf8')); } catch { return null; }
252
+ }
253
+
254
+ function dial(pipe) {
255
+ return new Promise((resolve, reject) => {
256
+ const sock = net.connect(pipe);
257
+ sock.once('connect', () => { sock.removeListener('error', reject); resolve(sock); });
258
+ sock.once('error', reject);
259
+ });
260
+ }
261
+
262
+ function startBroker() {
263
+ const child = spawn(process.execPath, [fileURLToPath(import.meta.url), '--serve'], { detached: true, stdio: 'ignore', windowsHide: true, env: process.env });
264
+ child.on('error', () => {});
265
+ child.unref();
266
+ }
267
+
268
+ // A socket to the broker, and the token to show it: the running one, else one started now.
269
+ async function reach(dir) {
270
+ let state = readState(dir);
271
+ if (state?.pipe) {
272
+ try { return { sock: await dial(state.pipe), state }; } catch { /* gone */ }
273
+ }
274
+ startBroker();
275
+ for (const until = Date.now() + brokerLimits.startMs; Date.now() < until;) {
276
+ await sleep(100);
277
+ state = readState(dir);
278
+ if (!state?.pipe) continue;
279
+ try { return { sock: await dial(state.pipe), state }; } catch { /* not listening yet, or the old one's file */ }
280
+ }
281
+ throw new Error('the browser broker did not start');
282
+ }
283
+
284
+ // The broker's connection to the browser at `url`, in the shape Cdp takes (send, close, onmessage, onclose). Rejects
285
+ // with a CdpError when the browser refuses or nobody allows it (as Cdp.connect), with another error when the broker
286
+ // cannot be had.
287
+ export async function brokerSocket(url, { signal, timeoutMs = brokerLimits.openMs, onWaiting, dir = CONFIG_DIR } = {}) {
288
+ if (signal?.aborted) throw abortError();
289
+ const { sock, state } = await reach(dir);
290
+ return new Promise((resolve, reject) => {
291
+ let settled = false;
292
+ let handler = null;
293
+ const queue = []; // what comes before Cdp takes over
294
+ const socket = {
295
+ onclose: null,
296
+ onerror: null,
297
+ get onmessage() { return handler; },
298
+ set onmessage(h) { handler = h; while (handler && queue.length) handler({ data: queue.shift() }); },
299
+ send: (text) => { if (!sock.destroyed) sock.write(`${text}\n`); },
300
+ close: () => sock.end(),
301
+ };
302
+ const fail = (err) => {
303
+ if (settled) return;
304
+ settled = true;
305
+ clearTimeout(timer);
306
+ signal?.removeEventListener('abort', onAbort);
307
+ sock.destroy();
308
+ reject(err);
309
+ };
310
+ const timer = setTimeout(() => fail(new CdpError(`the browser did not accept the connection within ${timeoutMs / 1000} s (nobody allowed remote debugging?)`)), timeoutMs);
311
+ const onAbort = () => fail(abortError());
312
+ signal?.addEventListener('abort', onAbort, { once: true });
313
+ lines(sock, (line) => {
314
+ if (!settled) {
315
+ let msg;
316
+ try { msg = JSON.parse(line); } catch { return; }
317
+ if (msg.t === 'waiting') { onWaiting?.(); return; }
318
+ if (msg.t === 'open') {
319
+ settled = true;
320
+ clearTimeout(timer);
321
+ signal?.removeEventListener('abort', onAbort);
322
+ resolve(socket);
323
+ return;
324
+ }
325
+ if (msg.t === 'error') {
326
+ // the browser's answer is the browser's; the broker's own trouble (another protocol) is not
327
+ fail(msg.protocol ? new Error(msg.message) : new CdpError(msg.message));
328
+ return;
329
+ }
330
+ return;
331
+ }
332
+ if (line.startsWith('{"t":"closed"')) { sock.end(); return; }
333
+ if (handler) handler({ data: line }); else queue.push(line);
334
+ });
335
+ sock.on('close', () => { if (settled) socket.onclose?.({}); else fail(new Error('the browser broker went away')); });
336
+ sock.on('error', () => {});
337
+ sock.write(`${JSON.stringify({ t: 'hello', token: state.token, protocol: PROTOCOL, url })}\n`);
338
+ });
339
+ }
340
+
341
+ // A Cdp to the browser at `url` through the broker, so that the user allows it once for all sessions and restarts;
342
+ // one of this process's own when the broker cannot be had.
343
+ export async function connectShared(url, opts = {}) {
344
+ let socket;
345
+ try {
346
+ socket = await brokerSocket(url, opts);
347
+ } catch (e) {
348
+ if (e?.name === 'AbortError' || e instanceof CdpError) throw e;
349
+ return Cdp.connect(url, opts);
350
+ }
351
+ return new Cdp(socket);
352
+ }
353
+
354
+ // What the broker holds (for tests and diagnosis): {pid, upstreams: [{url, sessions, opens, open}]}, or null.
355
+ export async function brokerStatus(dir = CONFIG_DIR) {
356
+ const state = readState(dir);
357
+ if (!state?.pipe) return null;
358
+ let sock;
359
+ try { sock = await dial(state.pipe); } catch { return null; }
360
+ return new Promise((resolve) => {
361
+ lines(sock, (line) => { try { resolve(JSON.parse(line)); } catch { resolve(null); } sock.end(); });
362
+ sock.on('close', () => resolve(null));
363
+ sock.write(`${JSON.stringify({ t: 'status', token: state.token, protocol: PROTOCOL })}\n`);
364
+ });
365
+ }
366
+
367
+ if (process.argv.includes('--serve') && process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) serve();