labs-claude 0.1.7 → 0.2.6

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.
@@ -0,0 +1,149 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const { spawn } = require('child_process');
4
+ const { randomBytes, timingSafeEqual } = require('crypto');
5
+
6
+ // Cookies on 127.0.0.1 are shared across ports, so other local servers would receive this cookie: it holds a random
7
+ // session token kept only in this process's memory, never the proxy key itself.
8
+ const COOKIE = 'labs_chat_session';
9
+ const SESSION_MS = 30 * 24 * 60 * 60 * 1000;
10
+ const sessions = new Map();
11
+ // One-time login codes: `labs chat` asks for one with the proxy key and opens it, so the key is never pasted.
12
+ const loginCodes = new Map();
13
+ const CODE_MS = 60 * 1000;
14
+ const ID_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;
15
+ const LABS_BIN = path.join(__dirname, '..', 'bin', 'labs.js');
16
+ const PAGE = path.join(__dirname, 'chat', 'index.html');
17
+
18
+ function chatCookie(req) {
19
+ const match = String(req.get('cookie') || '').match(new RegExp(`(?:^|;\\s*)${COOKIE}=([^;]+)`));
20
+ return match ? decodeURIComponent(match[1]) : null;
21
+ }
22
+
23
+ // A chat request counts as the owner only with a live session cookie AND the X-Labs-Chat header, which a cross-site
24
+ // form or image cannot send.
25
+ function hasChatSession(req) {
26
+ const token = chatCookie(req);
27
+ const expires = token && sessions.get(token);
28
+ if (!expires) return false;
29
+ if (expires < Date.now()) {
30
+ sessions.delete(token);
31
+ return false;
32
+ }
33
+ return req.get('x-labs-chat') === '1';
34
+ }
35
+
36
+ function sameKey(given, key) {
37
+ const a = Buffer.from(String(given || ''));
38
+ const b = Buffer.from(key);
39
+ return a.length === b.length && timingSafeEqual(a, b);
40
+ }
41
+
42
+ // The page is static and holds no data; every /chat/api call and /v1/messages need the proxy key, which the browser
43
+ // carries as an HttpOnly, SameSite=Strict cookie after one login, so other sites cannot use it.
44
+ function mountChat(app, { labsDir, proxyKey }) {
45
+ const chatDir = path.join(labsDir, 'chat');
46
+ const fileFor = id => path.join(chatDir, `${id}.json`);
47
+
48
+ // Both live under dot folders (~/.npm-global, ~/.labs), which Express refuses to send by default.
49
+ const SEND_OPTIONS = { dotfiles: 'allow' };
50
+
51
+ app.get(['/chat', '/chat/'], (req, res) => res.sendFile(PAGE, SEND_OPTIONS));
52
+
53
+ const startSession = res => {
54
+ const token = randomBytes(32).toString('hex');
55
+ sessions.set(token, Date.now() + SESSION_MS);
56
+ res.set('Set-Cookie', `${COOKIE}=${token}; HttpOnly; SameSite=Strict; Path=/; Max-Age=${SESSION_MS / 1000}`);
57
+ };
58
+
59
+ app.post('/chat/login', (req, res) => {
60
+ if (!sameKey(req.body?.key, proxyKey)) return res.status(401).json({ error: 'Wrong key' });
61
+ startSession(res);
62
+ res.json({ ok: true });
63
+ });
64
+
65
+ // Behind the proxy-key check like every /chat/api route.
66
+ app.post('/chat/api/login-link', (req, res) => {
67
+ const code = randomBytes(32).toString('hex');
68
+ loginCodes.set(code, Date.now() + CODE_MS);
69
+ res.json({ path: `/chat/open?code=${code}` });
70
+ });
71
+
72
+ app.get('/chat/open', (req, res) => {
73
+ const code = String(req.query.code || '');
74
+ const expires = loginCodes.get(code);
75
+ loginCodes.delete(code);
76
+ if (expires && expires > Date.now()) startSession(res);
77
+ res.redirect(302, '/chat');
78
+ });
79
+
80
+ app.get('/chat/api/me', (req, res) => res.json({ ok: true }));
81
+
82
+ app.get('/chat/api/conversations', (req, res) => {
83
+ if (!fs.existsSync(chatDir)) return res.json({ conversations: [] });
84
+ const conversations = fs.readdirSync(chatDir).filter(file => file.endsWith('.json')).map(file => {
85
+ const { id, title, updatedAt, mode } = JSON.parse(fs.readFileSync(path.join(chatDir, file), 'utf8'));
86
+ return { id, title, updatedAt, mode };
87
+ });
88
+ res.json({ conversations: conversations.sort((a, b) => b.updatedAt - a.updatedAt) });
89
+ });
90
+
91
+ app.get('/chat/api/conversations/:id', (req, res) => {
92
+ const { id } = req.params;
93
+ if (!ID_PATTERN.test(id) || !fs.existsSync(fileFor(id))) return res.status(404).json({ error: 'Not found' });
94
+ res.sendFile(fileFor(id), SEND_OPTIONS);
95
+ });
96
+
97
+ app.put('/chat/api/conversations/:id', (req, res) => {
98
+ const { id } = req.params;
99
+ if (!ID_PATTERN.test(id)) return res.status(400).json({ error: 'Bad id' });
100
+ fs.mkdirSync(chatDir, { recursive: true });
101
+ const { title, mode, messages, events, usage, folder, sessionId } = req.body || {};
102
+ fs.writeFileSync(fileFor(id), JSON.stringify({ id, title, mode, messages, events, usage, folder, sessionId, updatedAt: Date.now() }));
103
+ res.json({ ok: true });
104
+ });
105
+
106
+ app.delete('/chat/api/conversations/:id', (req, res) => {
107
+ const { id } = req.params;
108
+ if (ID_PATTERN.test(id) && fs.existsSync(fileFor(id))) fs.unlinkSync(fileFor(id));
109
+ res.json({ ok: true });
110
+ });
111
+
112
+ // Agent mode = the real Claude Code on the chosen model, run headless in the chosen folder; its stream-json lines
113
+ // are passed to the page as server-sent events.
114
+ app.post('/chat/api/agent', (req, res) => {
115
+ const { folder, prompt, model = 'glm', sessionId, access = 'edits' } = req.body || {};
116
+ if (!folder || !path.isAbsolute(folder) || !fs.existsSync(folder) || !fs.statSync(folder).isDirectory()) {
117
+ return res.status(400).json({ error: `Folder not found: ${folder}` });
118
+ }
119
+ if (!prompt || typeof prompt !== 'string') return res.status(400).json({ error: 'Empty prompt' });
120
+ if (sessionId && !/^[0-9a-f-]{36}$/i.test(sessionId)) return res.status(400).json({ error: 'Bad session id' });
121
+
122
+ const args = [LABS_BIN, '--model', model, '-p', prompt, '--output-format', 'stream-json', '--verbose',
123
+ '--permission-mode', access === 'full' ? 'bypassPermissions' : 'acceptEdits'];
124
+ if (sessionId) args.push('--resume', sessionId);
125
+ // stdin closed: with -p, Claude Code otherwise waits 3 s for piped input on every run.
126
+ const child = spawn(process.execPath, args, { cwd: folder, env: process.env, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
127
+
128
+ res.status(200).set({ 'Content-Type': 'text/event-stream; charset=utf-8', 'Cache-Control': 'no-cache', Connection: 'keep-alive' });
129
+ const send = data => res.write(`data: ${JSON.stringify(data)}\n\n`);
130
+ let buffer = '';
131
+ child.stdout.on('data', chunk => {
132
+ buffer += chunk;
133
+ const lines = buffer.split('\n');
134
+ buffer = lines.pop();
135
+ for (const line of lines) {
136
+ if (!line.trim()) continue;
137
+ try { send(JSON.parse(line)); } catch { send({ type: 'log', text: line }); }
138
+ }
139
+ });
140
+ child.stderr.on('data', chunk => send({ type: 'log', text: String(chunk) }));
141
+ child.on('close', code => {
142
+ send({ type: 'exit', code });
143
+ res.end();
144
+ });
145
+ res.on('close', () => { if (child.exitCode === null) child.kill(); });
146
+ });
147
+ }
148
+
149
+ module.exports = { hasChatSession, mountChat };
package/src/config.js CHANGED
@@ -19,7 +19,9 @@ const DEFAULT_MODELS = {
19
19
  haiku: 'claude-haiku-4-5',
20
20
  gemini: 'gemini-3.8-flash',
21
21
  'gemini-pro': 'gemini-3.1-pro-preview',
22
- glm: 'glm-52',
22
+ // GLM 5.3 runs on Amazon Bedrock with the user's own AWS key (labs bedrock), not on ElevenLabs.
23
+ glm: 'bedrock:us.zai.glm-5.3',
24
+ glm52: 'glm-52',
23
25
  qwen: 'qwen35-397b-a17b',
24
26
  deepseek: 'deepseek-v41-flash'
25
27
  };
@@ -30,6 +32,14 @@ function loadConfig() {
30
32
  return {
31
33
  port: DEFAULT_PORT,
32
34
  defaultModel: 'astra',
35
+ // ElevenLabs caches only the system prompt, so every token of history is paid at full price on every turn
36
+ // (measured 2026-10-08: 8 Opus turns at ~324k context cost $11.98). Claude Code compacts at this size.
37
+ contextLimit: 300000,
38
+ // Titles, summaries and compaction (requests without tools) ran on Opus/Sonnet; a cheap 1M model does them.
39
+ sideModel: 'gemini-3.8-flash',
40
+ bedrockRegion: 'us-east-1',
41
+ // Bedrock bills every input token on every turn; 200k keeps one GLM 5.3 turn under ~$0.35.
42
+ bedrockContextLimit: 200000,
33
43
  ...stored,
34
44
  models: { ...DEFAULT_MODELS, ...(stored.models || {}) },
35
45
  apiKey: process.env.ELEVENLABS_API_KEY || stored.apiKey
@@ -4,6 +4,8 @@ const fs = require('fs');
4
4
  const MAX_DESCRIPTION = 1200;
5
5
  const MAX_NAME = 64;
6
6
  const MAX_TIMEOUT_SECS = 120;
7
+ // ElevenLabs refuses an agent with more than 200 tool documents (2026-10-08); 190 leaves room for a few others.
8
+ const MAX_ATTACHED_TOOLS = 190;
7
9
 
8
10
  // ElevenLabs client-tool parameters accept a plain JSON-Schema subset; Claude Code tools use the full dialect.
9
11
  function toElevenLabsSchema(schema, fallbackDescription) {
@@ -90,7 +92,9 @@ class ToolRegistry {
90
92
  async ensureNow(tools) {
91
93
  const usable = tools.filter(tool => tool.name && tool.input_schema);
92
94
  let changed = false;
95
+ const now = Date.now();
93
96
  for (const tool of usable) {
97
+ if (this.entries[tool.name]) this.entries[tool.name].usedAt = now;
94
98
  const fingerprint = toolFingerprint(tool);
95
99
  const entry = this.entries[tool.name];
96
100
  if (entry?.fingerprint === fingerprint) continue;
@@ -100,7 +104,7 @@ class ToolRegistry {
100
104
  entry.fingerprint = fingerprint;
101
105
  } else {
102
106
  const response = await this.http.post(`${this.apiBase}/tools`, { tool_config: toToolConfig(tool) }, { headers: this.headers });
103
- this.entries[tool.name] = { name: tool.name, alias: toElevenLabsName(tool.name), id: response.data.id, fingerprint };
107
+ this.entries[tool.name] = { name: tool.name, alias: toElevenLabsName(tool.name), id: response.data.id, fingerprint, usedAt: now };
104
108
  console.log(`🧩 Mirrored tool ${tool.name} -> ${response.data.id}`);
105
109
  }
106
110
  changed = true;
@@ -108,11 +112,30 @@ class ToolRegistry {
108
112
  console.error(`⚠️ Could not mirror tool ${tool.name}: ${JSON.stringify(error.response?.data || error.message).slice(0, 300)}`);
109
113
  }
110
114
  }
111
- if (changed) {
112
- await this.attachAll();
115
+ const ids = usable.map(tool => this.entries[tool.name]?.id).filter(Boolean);
116
+ if (changed || !this.attached || ids.slice(0, MAX_ATTACHED_TOOLS).some(id => !this.attached.has(id))) {
117
+ await this.attachRecent(ids);
113
118
  fs.writeFileSync(this.file, JSON.stringify(this.entries, null, 1));
114
119
  }
115
- return usable.map(tool => this.entries[tool.name]?.id).filter(Boolean);
120
+ // A conversation may only name attached tools: one unattached id closes it with 1008 "Tool IDs not attached
121
+ // to this agent". Claude Code lists its built-in tools first, so the cap drops the last MCP tools.
122
+ const usableIds = ids.filter(id => this.attached.has(id));
123
+ if (usableIds.length < ids.length) console.log(`🧩 ${ids.length} tools requested, ${usableIds.length} offered (ElevenLabs agent limit)`);
124
+ return usableIds;
125
+ }
126
+
127
+ isAttached(id) {
128
+ return Boolean(this.attached?.has(id));
129
+ }
130
+
131
+ // Newest first, so they are also among the tools attachRecent keeps attached to the agent.
132
+ recentIds(withinMs, max) {
133
+ const since = Date.now() - withinMs;
134
+ return Object.values(this.entries)
135
+ .filter(entry => entry.id && (entry.usedAt || 0) >= since)
136
+ .sort((a, b) => b.usedAt - a.usedAt)
137
+ .slice(0, max)
138
+ .map(entry => entry.id);
116
139
  }
117
140
 
118
141
  claudeNameFor(alias) {
@@ -120,12 +143,19 @@ class ToolRegistry {
120
143
  return entry ? entry.name : alias;
121
144
  }
122
145
 
123
- // Per-conversation tool_ids overrides may only name tools already attached to the agent.
124
- async attachAll() {
125
- const ids = [...new Set(Object.values(this.entries).map(entry => entry.id).filter(Boolean))];
146
+ // Per-conversation tool_ids overrides may only name tools already attached to the agent. Attaching every tool ever
147
+ // mirrored grew past ElevenLabs' 200-document limit (2026-10-08), after which the agent could not even be read and
148
+ // every request failed with 400; only the current request's tools plus the most recently used ones stay attached.
149
+ async attachRecent(currentIds) {
150
+ const recent = Object.values(this.entries)
151
+ .filter(entry => entry.id)
152
+ .sort((a, b) => (b.usedAt || 0) - (a.usedAt || 0))
153
+ .map(entry => entry.id);
154
+ const ids = [...new Set([...currentIds, ...recent])].slice(0, MAX_ATTACHED_TOOLS);
126
155
  await this.http.patch(`${this.apiBase}/agents/${this.agentId}`,
127
156
  { conversation_config: { agent: { prompt: { tool_ids: ids } } } },
128
157
  { headers: this.headers });
158
+ this.attached = new Set(ids);
129
159
  }
130
160
  }
131
161
 
@@ -1,35 +1,44 @@
1
- // Splits `labs` arguments into the Labs model choice and everything that goes to Claude Code untouched.
2
- function parseLaunchArgs(args, { aliases, llmIds, defaultModel }) {
3
- const aliasNames = Object.keys(aliases);
4
- let modelName = defaultModel;
5
- const claudeArgs = [];
6
-
7
- for (let index = 0; index < args.length; index += 1) {
8
- const arg = args[index];
9
- const inline = arg.startsWith('--model=') ? arg.slice('--model='.length) : null;
10
- if (arg !== '--model' && inline === null) {
11
- claudeArgs.push(arg);
12
- continue;
13
- }
14
- const value = inline ?? args[++index];
15
- if (!value) throw new Error('--model requires a value');
16
- modelName = /^\d+$/.test(value) && aliasNames[Number(value) - 1] ? aliasNames[Number(value) - 1] : value;
17
- }
18
-
19
- if (!aliases[modelName] && !llmIds.has(modelName)) {
20
- throw new Error(`Unknown model "${modelName}". Run "labs models --all" to list models.`);
21
- }
22
- return { modelName, claudeArgs: [...claudeArgs, '--model', modelName] };
23
- }
24
-
25
- function withLabsHeaders(headers, sessionId, modelName) {
26
- const lines = String(headers || '')
27
- .split(/\r?\n/)
28
- .filter(line => line.trim()
29
- && !/^\s*x-labs-session-id\s*:/i.test(line)
30
- && !/^\s*x-labs-model\s*:/i.test(line));
31
- lines.push(`X-Labs-Session-Id: ${sessionId}`, `X-Labs-Model: ${modelName}`);
32
- return lines.join('\n');
33
- }
34
-
35
- module.exports = { parseLaunchArgs, withLabsHeaders };
1
+ // Splits `labs` arguments into the Labs model choice and everything that goes to Claude Code untouched.
2
+ function parseLaunchArgs(args, { aliases, llmIds, defaultModel }) {
3
+ const aliasNames = Object.keys(aliases);
4
+ let modelName = defaultModel;
5
+ const claudeArgs = [];
6
+
7
+ for (let index = 0; index < args.length; index += 1) {
8
+ const arg = args[index];
9
+ const inline = arg.startsWith('--model=') ? arg.slice('--model='.length) : null;
10
+ if (arg !== '--model' && inline === null) {
11
+ claudeArgs.push(arg);
12
+ continue;
13
+ }
14
+ const value = inline ?? args[++index];
15
+ if (!value) throw new Error('--model requires a value');
16
+ modelName = /^\d+$/.test(value) && aliasNames[Number(value) - 1] ? aliasNames[Number(value) - 1] : value;
17
+ }
18
+
19
+ if (!aliases[modelName] && !llmIds.has(modelName)) {
20
+ throw new Error(`Unknown model "${modelName}". Run "labs models --all" to list models.`);
21
+ }
22
+ return { modelName, claudeArgs: [...claudeArgs, '--model', modelName] };
23
+ }
24
+
25
+ function withLabsHeaders(headers, sessionId, modelName) {
26
+ const lines = String(headers || '')
27
+ .split(/\r?\n/)
28
+ .filter(line => line.trim()
29
+ && !/^\s*x-labs-session-id\s*:/i.test(line)
30
+ && !/^\s*x-labs-model\s*:/i.test(line));
31
+ lines.push(`X-Labs-Session-Id: ${sessionId}`, `X-Labs-Model: ${modelName}`);
32
+ return lines.join('\n');
33
+ }
34
+
35
+ function chromeCompatibilityWarning(args) {
36
+ const flag = args.filter(arg => arg === '--chrome' || arg === '--no-chrome').at(-1);
37
+ if (flag !== '--chrome') return null;
38
+ return 'Claude in Chrome requires a direct Claude account signed in with /login. '
39
+ + 'Labs uses custom API authentication, which current Claude Code does not support for this integration. '
40
+ + 'Use claude --chrome outside Labs with a supported account, or configure a separate browser MCP server. '
41
+ + 'See https://code.claude.com/docs/en/chrome';
42
+ }
43
+
44
+ module.exports = { parseLaunchArgs, withLabsHeaders, chromeCompatibilityWarning };
@@ -0,0 +1,33 @@
1
+ const { randomBytes, timingSafeEqual } = require('crypto');
2
+ const fs = require('fs');
3
+ const path = require('path');
4
+
5
+ // Any local program, or a web page that rebinds a domain to 127.0.0.1, could otherwise spend the user's ElevenLabs
6
+ // credits through the proxy and read saved conversations. Claude Code sends the key as its ANTHROPIC_AUTH_TOKEN.
7
+ function loadProxyKey(labsDir) {
8
+ const file = path.join(labsDir, 'proxy-key');
9
+ if (!fs.existsSync(file)) {
10
+ fs.mkdirSync(labsDir, { recursive: true });
11
+ fs.writeFileSync(file, randomBytes(32).toString('hex'), { mode: 0o600 });
12
+ }
13
+ return fs.readFileSync(file, 'utf8').trim();
14
+ }
15
+
16
+ function sameKey(given, key) {
17
+ const a = Buffer.from(String(given || ''));
18
+ const b = Buffer.from(key);
19
+ return a.length === b.length && timingSafeEqual(a, b);
20
+ }
21
+
22
+ // Returns null for an allowed request, otherwise the Anthropic-style error to answer with.
23
+ function rejectLocalRequest({ host, path: route, authorization, apiKey }, { port, key }) {
24
+ if (![`127.0.0.1:${port}`, `localhost:${port}`].includes(host)) {
25
+ return { status: 403, type: 'permission_error', message: `Host "${host}" is not the local labs proxy` };
26
+ }
27
+ // The chat page itself is static (no data) and its login checks the key on its own.
28
+ if (['/health', '/chat', '/chat/', '/chat/login', '/chat/open'].includes(route)) return null;
29
+ const given = apiKey || String(authorization || '').replace(/^Bearer\s+/i, '');
30
+ return sameKey(given, key) ? null : { status: 401, type: 'authentication_error', message: 'labs proxy key required (start Claude Code with the labs command)' };
31
+ }
32
+
33
+ module.exports = { loadProxyKey, rejectLocalRequest };
@@ -1,45 +1,82 @@
1
- const axios = require('axios');
2
- const fs = require('fs');
3
- const path = require('path');
4
- const { spawn } = require('child_process');
5
- const { LABS_DIR } = require('./config');
6
- const { version: VERSION } = require('../package.json');
7
-
8
- async function health(port) {
9
- try {
10
- return (await axios.get(`http://127.0.0.1:${port}/health`, { timeout: 1000 })).data;
11
- } catch {
12
- return null;
13
- }
14
- }
15
-
16
- // Reuses a running proxy of the same version; an older version (after `npm update -g`) is stopped and replaced.
17
- async function ensureProxy(port) {
18
- const running = await health(port);
19
- if (running?.name === 'labs-claude' && running.version === VERSION) return true;
20
- if (running?.name === 'labs-claude') {
21
- await axios.post(`http://127.0.0.1:${port}/shutdown`).catch(() => {});
22
- await new Promise(resolve => setTimeout(resolve, 500));
23
- }
24
-
25
- fs.mkdirSync(LABS_DIR, { recursive: true });
26
- const log = fs.openSync(path.join(LABS_DIR, 'proxy.log'), 'a');
27
- const child = spawn(process.execPath, [path.join(__dirname, 'proxy.js')], {
28
- detached: true,
29
- stdio: ['ignore', log, log],
30
- windowsHide: true
31
- });
32
- child.unref();
33
-
34
- for (let attempt = 0; attempt < 120; attempt += 1) {
35
- if ((await health(port))?.version === VERSION) return true;
36
- await new Promise(resolve => setTimeout(resolve, 250));
37
- }
38
- return false;
39
- }
40
-
41
- async function stopProxy(port) {
42
- return axios.post(`http://127.0.0.1:${port}/shutdown`).then(() => true, () => false);
43
- }
44
-
45
- module.exports = { ensureProxy, stopProxy };
1
+ const axios = require('axios');
2
+ const fs = require('fs');
3
+ const path = require('path');
4
+ const { spawn } = require('child_process');
5
+ const { LABS_DIR } = require('./config');
6
+ const { loadProxyKey } = require('./local-auth');
7
+ const { version: VERSION } = require('../package.json');
8
+
9
+ async function health(port) {
10
+ try {
11
+ return (await axios.get(`http://127.0.0.1:${port}/health`, { timeout: 1000 })).data;
12
+ } catch {
13
+ return null;
14
+ }
15
+ }
16
+
17
+ // Reuses a running proxy of the same version; an older version (after `npm update -g`) is stopped and replaced.
18
+ async function ensureProxy(port) {
19
+ const running = await health(port);
20
+ if (running?.name === 'labs-claude' && running.version === VERSION) return true;
21
+ if (running?.name === 'labs-claude') {
22
+ await stopProxy(port);
23
+ await new Promise(resolve => setTimeout(resolve, 500));
24
+ }
25
+
26
+ fs.mkdirSync(LABS_DIR, { recursive: true });
27
+ const log = fs.openSync(path.join(LABS_DIR, 'proxy.log'), 'a');
28
+ const child = spawn(process.execPath, [path.join(__dirname, 'proxy.js')], {
29
+ detached: true,
30
+ stdio: ['ignore', log, log],
31
+ windowsHide: true
32
+ });
33
+ child.unref();
34
+
35
+ for (let attempt = 0; attempt < 120; attempt += 1) {
36
+ if ((await health(port))?.version === VERSION) return true;
37
+ await new Promise(resolve => setTimeout(resolve, 250));
38
+ }
39
+ return false;
40
+ }
41
+
42
+ // Claude Code only reaches the proxy, so a proxy that died (crash, `labs stop`, an upgrade) left every open window
43
+ // retrying ECONNREFUSED until it gave up. While Claude Code runs, the launcher restarts a dead proxy within seconds.
44
+ // It never replaces a running proxy of another version: windows of different versions would fight over the port.
45
+ const WATCHDOG_MS = 5000;
46
+ const BUSY_PROXY_TIMEOUT_MS = 3000;
47
+
48
+ // Only a refused connection means no proxy. A slow /health is a busy proxy: treating it as dead spawned duplicates.
49
+ async function isProxyDown(port) {
50
+ try {
51
+ await axios.get(`http://127.0.0.1:${port}/health`, { timeout: BUSY_PROXY_TIMEOUT_MS });
52
+ return false;
53
+ } catch (error) {
54
+ return error.code === 'ECONNREFUSED';
55
+ }
56
+ }
57
+
58
+ function keepProxyAlive(port) {
59
+ let restarting = false;
60
+ let misses = 0;
61
+ const timer = setInterval(async () => {
62
+ if (restarting) return;
63
+ // Two misses in a row: a newer labs replacing the proxy leaves the port free for a moment, and restarting
64
+ // this window's older version in that gap would take the port from the upgrade.
65
+ misses = await isProxyDown(port) ? misses + 1 : 0;
66
+ if (misses < 2) return;
67
+ restarting = true;
68
+ // Never print here: this runs inside Claude Code's terminal, and a line written there lands in Boss's input box.
69
+ fs.appendFileSync(path.join(LABS_DIR, 'proxy.log'), `⚠️ ${new Date().toISOString()} watchdog: labs proxy was down; restarting it\n`);
70
+ await ensureProxy(port).catch(() => {});
71
+ restarting = false;
72
+ }, WATCHDOG_MS);
73
+ timer.unref();
74
+ return timer;
75
+ }
76
+
77
+ async function stopProxy(port) {
78
+ return axios.post(`http://127.0.0.1:${port}/shutdown`, null, { headers: { 'x-api-key': loadProxyKey(LABS_DIR) } })
79
+ .then(() => true, () => false);
80
+ }
81
+
82
+ module.exports = { ensureProxy, keepProxyAlive, stopProxy };