labs-claude 0.1.16 ā 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.
- package/README.md +122 -68
- package/bin/labs.js +65 -6
- package/package.json +2 -1
- package/src/anthropic-protocol.js +2 -1
- package/src/autostart.js +43 -0
- package/src/bedrock.js +162 -0
- package/src/chat/index.html +534 -0
- package/src/chat-routes.js +149 -0
- package/src/config.js +6 -1
- package/src/local-auth.js +2 -1
- package/src/proxy-manager.js +14 -2
- package/src/proxy.js +110 -19
- package/src/setup.js +23 -4
|
@@ -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
|
-
|
|
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
|
};
|
|
@@ -35,6 +37,9 @@ function loadConfig() {
|
|
|
35
37
|
contextLimit: 300000,
|
|
36
38
|
// Titles, summaries and compaction (requests without tools) ran on Opus/Sonnet; a cheap 1M model does them.
|
|
37
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,
|
|
38
43
|
...stored,
|
|
39
44
|
models: { ...DEFAULT_MODELS, ...(stored.models || {}) },
|
|
40
45
|
apiKey: process.env.ELEVENLABS_API_KEY || stored.apiKey
|
package/src/local-auth.js
CHANGED
|
@@ -24,7 +24,8 @@ function rejectLocalRequest({ host, path: route, authorization, apiKey }, { port
|
|
|
24
24
|
if (![`127.0.0.1:${port}`, `localhost:${port}`].includes(host)) {
|
|
25
25
|
return { status: 403, type: 'permission_error', message: `Host "${host}" is not the local labs proxy` };
|
|
26
26
|
}
|
|
27
|
-
|
|
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;
|
|
28
29
|
const given = apiKey || String(authorization || '').replace(/^Bearer\s+/i, '');
|
|
29
30
|
return sameKey(given, key) ? null : { status: 401, type: 'authentication_error', message: 'labs proxy key required (start Claude Code with the labs command)' };
|
|
30
31
|
}
|
package/src/proxy-manager.js
CHANGED
|
@@ -43,6 +43,17 @@ async function ensureProxy(port) {
|
|
|
43
43
|
// retrying ECONNREFUSED until it gave up. While Claude Code runs, the launcher restarts a dead proxy within seconds.
|
|
44
44
|
// It never replaces a running proxy of another version: windows of different versions would fight over the port.
|
|
45
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
|
+
}
|
|
46
57
|
|
|
47
58
|
function keepProxyAlive(port) {
|
|
48
59
|
let restarting = false;
|
|
@@ -51,10 +62,11 @@ function keepProxyAlive(port) {
|
|
|
51
62
|
if (restarting) return;
|
|
52
63
|
// Two misses in a row: a newer labs replacing the proxy leaves the port free for a moment, and restarting
|
|
53
64
|
// this window's older version in that gap would take the port from the upgrade.
|
|
54
|
-
misses = await
|
|
65
|
+
misses = await isProxyDown(port) ? misses + 1 : 0;
|
|
55
66
|
if (misses < 2) return;
|
|
56
67
|
restarting = true;
|
|
57
|
-
|
|
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`);
|
|
58
70
|
await ensureProxy(port).catch(() => {});
|
|
59
71
|
restarting = false;
|
|
60
72
|
}, WATCHDOG_MS);
|
package/src/proxy.js
CHANGED
|
@@ -3,7 +3,7 @@ const axios = require('axios');
|
|
|
3
3
|
const bodyParser = require('body-parser');
|
|
4
4
|
const fs = require('fs');
|
|
5
5
|
const path = require('path');
|
|
6
|
-
const {
|
|
6
|
+
const { execFile } = require('child_process');
|
|
7
7
|
const WebSocket = require('ws');
|
|
8
8
|
const {
|
|
9
9
|
createAnthropicMessage,
|
|
@@ -19,6 +19,8 @@ const {
|
|
|
19
19
|
const { ToolRegistry } = require('./elevenlabs-tools');
|
|
20
20
|
const { oversizedWholeFileReads, shuntNote, WORKER_PROMPT } = require('./read-shunt');
|
|
21
21
|
const { loadProxyKey, rejectLocalRequest } = require('./local-auth');
|
|
22
|
+
const { bedrockModelId, createBedrockClient, readBedrockKey, streamConverse } = require('./bedrock');
|
|
23
|
+
const { hasChatSession, mountChat } = require('./chat-routes');
|
|
22
24
|
const { API_BASE, LABS_DIR, loadConfig, loadLlmList, saveLlmList } = require('./config');
|
|
23
25
|
const { version: VERSION } = require('../package.json');
|
|
24
26
|
|
|
@@ -100,6 +102,7 @@ async function refreshLlmList() {
|
|
|
100
102
|
// effort can exceed; the highest effort that answered in time is remembered per LLM for the proxy's lifetime.
|
|
101
103
|
const effortCaps = new Map();
|
|
102
104
|
const MAX_SLOW_RETRIES = 3;
|
|
105
|
+
const SHARED_MAX_TOKENS = 65536;
|
|
103
106
|
|
|
104
107
|
function lowerEffortCap(llm, failedEffort) {
|
|
105
108
|
const efforts = (llmList.find(item => item.llm === llm)?.available_reasoning_efforts || [])
|
|
@@ -118,8 +121,11 @@ function agentSettingsFor(llm, requestedEffort, requestedMaxTokens) {
|
|
|
118
121
|
const effort = efforts.length
|
|
119
122
|
? efforts.reduce((best, option) => Math.abs(EFFORT_ORDER.indexOf(option) - wanted) < Math.abs(EFFORT_ORDER.indexOf(best) - wanted) ? option : best)
|
|
120
123
|
: null;
|
|
121
|
-
//
|
|
122
|
-
|
|
124
|
+
// The model's full reply length (Claude Code's own max_tokens is sized for Anthropic models), but never above the
|
|
125
|
+
// largest every Gemini 3.x accepts: reply length is agent-wide, so an Opus window opening mid side call handed
|
|
126
|
+
// gemini-3.8-flash Opus's 128000 and Google refused it (15 failed side calls, 2026-10-30).
|
|
127
|
+
const limit = info.max_tokens_limit || requestedMaxTokens || 4096;
|
|
128
|
+
return { llm, reasoning_effort: effort, max_tokens: Math.min(limit, SHARED_MAX_TOKENS) };
|
|
123
129
|
}
|
|
124
130
|
|
|
125
131
|
// New agents do not send context_usage or agent_response_complete unless asked; both are verified on gpt-6-astra.
|
|
@@ -154,9 +160,11 @@ function withAgentSettings(settings, openFn) {
|
|
|
154
160
|
enable_reasoning_summary: Boolean(settings.reasoning_effort),
|
|
155
161
|
backup_llm_config: { preference: 'disabled' }
|
|
156
162
|
};
|
|
157
|
-
// Conversations default to 600 s on new agents; 7200 s is the API maximum.
|
|
163
|
+
// Conversations default to 600 s on new agents; 7200 s is the API maximum. Unset, the idle limit closed every
|
|
164
|
+
// chat 15 min after the last reply (145 of 300, measured 2026-10-30), and the cold reopen of a ~190k-token
|
|
165
|
+
// history missed the 15 s first-token limit: all 7 "All LLMs have failed". 7200 s is its maximum too.
|
|
158
166
|
await axios.patch(`${API_BASE}/agents/${config.bridgeAgent}`,
|
|
159
|
-
{ conversation_config: { agent: { prompt }, conversation: { max_duration_seconds: 7200, file_input: { enabled: true }, client_events: CLIENT_EVENTS, compaction: compactionFor(settings.llm) } } }, { headers: HEADERS });
|
|
167
|
+
{ conversation_config: { agent: { prompt }, conversation: { max_duration_seconds: 7200, max_duration_seconds_after_last_agent_message: 7200, file_input: { enabled: true }, client_events: CLIENT_EVENTS, compaction: compactionFor(settings.llm) } } }, { headers: HEADERS });
|
|
160
168
|
appliedSettings = key;
|
|
161
169
|
console.log(`šļø Bridge set to ${settings.llm} effort=${settings.reasoning_effort || 'n/a'} max_tokens=${settings.max_tokens}`);
|
|
162
170
|
}
|
|
@@ -198,6 +206,8 @@ function openConversation(key, { llm, prompt, toolIds }) {
|
|
|
198
206
|
timedOutToolCalls: new Set(),
|
|
199
207
|
toolIds: new Set(toolIds),
|
|
200
208
|
filesUploaded: 0,
|
|
209
|
+
promptChars: prompt.length,
|
|
210
|
+
replayChars: 0,
|
|
201
211
|
closeReason: ''
|
|
202
212
|
};
|
|
203
213
|
connections.set(key, conn);
|
|
@@ -324,20 +334,24 @@ function handleToolCall(conn, call) {
|
|
|
324
334
|
// On Windows, models copy Git Bash paths (/tmp/..., /c/Users/...) from `pwd` into file tools; Claude Code reads those
|
|
325
335
|
// as outside the project and asks for permission. Git's own cygpath gives the exact Windows equivalent.
|
|
326
336
|
const PATH_KEYS = ['file_path', 'path', 'notebook_path'];
|
|
327
|
-
|
|
337
|
+
// A cygpath call per new path froze the whole proxy for 0.2-1.9 s (measured 2026-10-29), so every window stalled and
|
|
338
|
+
// the watchdog called it dead. Its answer only depends on Git Bash's mounts: ask once at start, convert in memory.
|
|
339
|
+
const gitBashMounts = [];
|
|
340
|
+
if (process.platform === 'win32') {
|
|
341
|
+
execFile('cygpath', ['-w', '/tmp', '/'], { encoding: 'utf8', windowsHide: true }, (error, stdout) => {
|
|
342
|
+
if (error) return; // cygpath missing: drive letters still convert below.
|
|
343
|
+
const [tmp, root] = stdout.trim().split(/\r?\n/);
|
|
344
|
+
if (tmp) gitBashMounts.push(['/tmp', tmp.replace(/\\$/, '')]);
|
|
345
|
+
if (root) gitBashMounts.push(['', root.replace(/\\$/, '')]);
|
|
346
|
+
});
|
|
347
|
+
}
|
|
328
348
|
|
|
329
349
|
function toWindowsPath(value) {
|
|
330
350
|
if (process.platform !== 'win32' || typeof value !== 'string' || !value.startsWith('/')) return value;
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
} catch {
|
|
336
|
-
// cygpath missing: the drive-letter rewrite above is the best available guess.
|
|
337
|
-
}
|
|
338
|
-
windowsPathCache.set(value, converted);
|
|
339
|
-
}
|
|
340
|
-
return windowsPathCache.get(value);
|
|
351
|
+
const drive = value.match(/^\/([a-zA-Z])(\/.*)?$/);
|
|
352
|
+
if (drive) return `${drive[1].toUpperCase()}:\\${(drive[2] || '').slice(1).replace(/\//g, '\\')}`;
|
|
353
|
+
const mount = gitBashMounts.find(([prefix]) => value === prefix || value.startsWith(`${prefix}/`));
|
|
354
|
+
return mount ? `${mount[1]}${value.slice(mount[0].length).replace(/\//g, '\\')}` : value.replace(/\//g, '\\');
|
|
341
355
|
}
|
|
342
356
|
|
|
343
357
|
function withWindowsPaths(input) {
|
|
@@ -475,6 +489,7 @@ function sendTurn(conn, { text, toolResults, history, images = [], replayChars =
|
|
|
475
489
|
// --resume, compaction) is seeded from what Claude Code sent.
|
|
476
490
|
if (conn.messageId === 1 && history.length) {
|
|
477
491
|
const replay = formatConversationHistory(history, replayChars);
|
|
492
|
+
conn.replayChars = replay.length;
|
|
478
493
|
console.log(`š¼ Replaying ${history.length} messages (${replay.length} chars) into ${conn.conversationId}`);
|
|
479
494
|
conn.ws.send(JSON.stringify({ type: 'contextual_update', text: `Conversation so far:\n${replay}` }));
|
|
480
495
|
}
|
|
@@ -502,6 +517,10 @@ function sendTurn(conn, { text, toolResults, history, images = [], replayChars =
|
|
|
502
517
|
.join('\n\n');
|
|
503
518
|
for (const result of toolResults) conn.timedOutToolCalls.delete(result.toolUseId);
|
|
504
519
|
const turnText = [resultText, text, resultText ? 'Continue the task from here.' : ''].filter(Boolean).join('\n\n');
|
|
520
|
+
// Failed Opus opens received ~115k more tokens than prompt + replay + tools explain (2026-10-30); this pins the part.
|
|
521
|
+
if (conn.messageId === 1) {
|
|
522
|
+
console.log(`š first turn parts (chars): prompt ${conn.promptChars} | replay ${conn.replayChars} | turn ${turnText.length} | images ${fileIds.length} | tools ${conn.toolIds?.size ?? 0}`);
|
|
523
|
+
}
|
|
505
524
|
if (fileIds.length) sendMultimodal(conn, turnText || 'See the attached image.', fileIds);
|
|
506
525
|
else conn.ws.send(JSON.stringify({ type: 'user_message', id: requestId, text: turnText }));
|
|
507
526
|
};
|
|
@@ -543,6 +562,69 @@ function anthropicError(res, status, type, message) {
|
|
|
543
562
|
return res.status(status).json({ type: 'error', error: { type, message } });
|
|
544
563
|
}
|
|
545
564
|
|
|
565
|
+
// ============================================
|
|
566
|
+
// Amazon Bedrock: a direct API, so none of the ElevenLabs bridge limits (conversation setup, 50 s replies, 200 tools)
|
|
567
|
+
// ============================================
|
|
568
|
+
|
|
569
|
+
const BEDROCK_USAGE_FILE = path.join(LABS_DIR, 'bedrock-usage.jsonl');
|
|
570
|
+
let bedrockClient = null;
|
|
571
|
+
let bedrockClientKey = null;
|
|
572
|
+
|
|
573
|
+
function getBedrockClient() {
|
|
574
|
+
const apiKey = readBedrockKey(LABS_DIR);
|
|
575
|
+
if (!apiKey) return null;
|
|
576
|
+
if (apiKey !== bedrockClientKey) {
|
|
577
|
+
bedrockClient = createBedrockClient({ region: config.bedrockRegion, apiKey });
|
|
578
|
+
bedrockClientKey = apiKey;
|
|
579
|
+
}
|
|
580
|
+
return bedrockClient;
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
// A session launched on a Bedrock model keeps Claude Code's own side calls (claude-haiku titles, compaction) there too.
|
|
584
|
+
function bedrockRoute(model, launchModel) {
|
|
585
|
+
const direct = bedrockModelId(aliases[String(model || '').replace(/\[1m\]$/i, '')]);
|
|
586
|
+
if (direct) return direct;
|
|
587
|
+
const launched = bedrockModelId(aliases[launchModel]);
|
|
588
|
+
return launched && (!model || /^claude-/.test(model)) ? launched : null;
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
async function handleBedrock(req, res, modelId) {
|
|
592
|
+
const { model, stream, tools = [], messages = [] } = req.body;
|
|
593
|
+
const client = getBedrockClient();
|
|
594
|
+
if (!client) return anthropicError(res, 401, 'authentication_error', 'No Amazon Bedrock key on this machine. Run: labs bedrock');
|
|
595
|
+
const estimate = Math.ceil(JSON.stringify(req.body).length / 4);
|
|
596
|
+
console.log(`\nš§ ${model} -> bedrock ${modelId} | ${messages.length} messages | ${tools.length} tools`);
|
|
597
|
+
const live = stream ? createLiveStream(res, { model, inputTokens: estimate }) : null;
|
|
598
|
+
const abort = new AbortController();
|
|
599
|
+
res.on('close', () => { if (!res.writableEnded) abort.abort(); });
|
|
600
|
+
const started = Date.now();
|
|
601
|
+
try {
|
|
602
|
+
const result = await streamConverse({ client, body: req.body, modelId, signal: abort.signal, onText: live && (delta => live.text(delta)) });
|
|
603
|
+
const message = createAnthropicMessage({
|
|
604
|
+
model,
|
|
605
|
+
text: live?.started ? live.streamedText : result.text,
|
|
606
|
+
toolCalls: result.toolCalls,
|
|
607
|
+
inputTokens: result.usage.inputTokens || estimate
|
|
608
|
+
});
|
|
609
|
+
if (result.usage.outputTokens) message.usage.output_tokens = result.usage.outputTokens;
|
|
610
|
+
if (result.stopReason === 'max_tokens') message.stop_reason = 'max_tokens';
|
|
611
|
+
const seconds = ((Date.now() - started) / 1000).toFixed(1);
|
|
612
|
+
console.log(`š§ ${seconds}s | in ${result.usage.inputTokens} out ${result.usage.outputTokens} tokens | ${result.toolCalls.length} tool calls`);
|
|
613
|
+
fs.appendFileSync(BEDROCK_USAGE_FILE, `${JSON.stringify({ at: new Date().toISOString(), modelId, input: result.usage.inputTokens, output: result.usage.outputTokens, seconds: Number(seconds) })}\n`);
|
|
614
|
+
return live ? live.finish(message) : res.json(message);
|
|
615
|
+
} catch (error) {
|
|
616
|
+
const status = error.$metadata?.httpStatusCode;
|
|
617
|
+
const detail = `${error.name || 'Error'}${status ? ` ${status}` : ''}: ${error.message}`;
|
|
618
|
+
console.error(`šØ bedrock ${modelId}: ${detail}`);
|
|
619
|
+
if (live?.started) return live.fail(new Error(`Bedrock ${modelId}: ${detail}`));
|
|
620
|
+
if (res.headersSent) return;
|
|
621
|
+
// 403 (access, verification) will not fix itself; anything else gets 500 so Claude Code retries the same model.
|
|
622
|
+
return status === 403
|
|
623
|
+
? anthropicError(res, 403, 'permission_error', `Bedrock ${modelId}: ${detail}`)
|
|
624
|
+
: anthropicError(res, 500, 'api_error', `Bedrock ${modelId}: ${detail}`);
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
|
|
546
628
|
// ============================================
|
|
547
629
|
// HTTP: Anthropic Messages API
|
|
548
630
|
// ============================================
|
|
@@ -551,15 +633,18 @@ const app = express();
|
|
|
551
633
|
const PROXY_KEY = loadProxyKey(LABS_DIR);
|
|
552
634
|
app.use((req, res, next) => {
|
|
553
635
|
const refusal = rejectLocalRequest(
|
|
554
|
-
{ host: req.get('host'), path: req.path, authorization: req.get('authorization'), apiKey: req.get('x-api-key') },
|
|
636
|
+
{ host: req.get('host'), path: req.path, authorization: req.get('authorization'), apiKey: hasChatSession(req) ? PROXY_KEY : req.get('x-api-key') },
|
|
555
637
|
{ port: PORT, key: PROXY_KEY });
|
|
556
638
|
return refusal ? anthropicError(res, refusal.status, refusal.type, refusal.message) : next();
|
|
557
639
|
});
|
|
558
640
|
app.use(bodyParser.json({ limit: '50mb' }));
|
|
641
|
+
mountChat(app, { labsDir: LABS_DIR, proxyKey: PROXY_KEY });
|
|
559
642
|
|
|
560
643
|
app.post('/v1/messages', async (req, res) => {
|
|
561
644
|
const { model, messages = [], system, stream, metadata, tools = [], max_tokens: maxTokens, output_config: outputConfig } = req.body;
|
|
562
645
|
const launchModel = req.get('x-labs-model');
|
|
646
|
+
const bedrockId = bedrockRoute(model, launchModel);
|
|
647
|
+
if (bedrockId) return handleBedrock(req, res, bedrockId);
|
|
563
648
|
// Claude Code answers repeated errors by falling back opus -> sonnet -> haiku on its own; on the main thread
|
|
564
649
|
// (tools present) a Claude id therefore means "fallback", so stay on the model the user launched with.
|
|
565
650
|
const isClaudeFallback = /^claude-/.test(model || '') && (req.body.tools || []).length > 0 && Boolean(launchModel);
|
|
@@ -704,7 +789,13 @@ process.on('SIGINT', () => {
|
|
|
704
789
|
process.exit(0);
|
|
705
790
|
});
|
|
706
791
|
|
|
707
|
-
|
|
708
|
-
|
|
792
|
+
// Express 5 hands a failed listen to this callback; ignoring it logged "LIVE" for every duplicate (319 in one log),
|
|
793
|
+
// which hid the one proxy that really serves. The port is the single-instance lock.
|
|
794
|
+
app.listen(PORT, '127.0.0.1', error => {
|
|
795
|
+
if (error) {
|
|
796
|
+
console.log(`š° ${new Date().toISOString()} another labs proxy already holds port ${PORT}; this copy exits (${error.code})`);
|
|
797
|
+
process.exit(0);
|
|
798
|
+
}
|
|
799
|
+
console.log(`ā
${new Date().toISOString()} Proxy LIVE at http://localhost:${PORT} | bridge agent ${config.bridgeAgent}`);
|
|
709
800
|
refreshLlmList();
|
|
710
801
|
});
|
package/src/setup.js
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
const axios = require('axios');
|
|
2
2
|
const readline = require('readline');
|
|
3
3
|
const { execFileSync } = require('child_process');
|
|
4
|
-
const
|
|
4
|
+
const path = require('path');
|
|
5
|
+
const { API_BASE, CONFIG_PATH, LABS_DIR, loadConfig, saveConfig, saveLlmList } = require('./config');
|
|
6
|
+
const { saveBedrockKey } = require('./bedrock');
|
|
5
7
|
const { EXTENSION_URL, installBrowserServer } = require('./browser-setup');
|
|
6
8
|
|
|
7
9
|
const BRIDGE_AGENT_NAME = 'Labs Claude Code Bridge';
|
|
@@ -47,7 +49,7 @@ async function createBridgeAgent(headers) {
|
|
|
47
49
|
backup_llm_config: { preference: 'disabled' }
|
|
48
50
|
}
|
|
49
51
|
},
|
|
50
|
-
conversation: { text_only: true, max_duration_seconds: 7200, file_input: { enabled: true } }
|
|
52
|
+
conversation: { text_only: true, max_duration_seconds: 7200, max_duration_seconds_after_last_agent_message: 7200, file_input: { enabled: true } }
|
|
51
53
|
},
|
|
52
54
|
platform_settings: {
|
|
53
55
|
// Post-conversation analysis adds nothing for a coding bridge.
|
|
@@ -88,6 +90,10 @@ async function runSetup() {
|
|
|
88
90
|
} else {
|
|
89
91
|
console.log('š Paste your ElevenLabs API key (elevenlabs.io ā Developers ā API Keys; it needs ElevenAgents access).');
|
|
90
92
|
apiKey = await askHidden(' API key: ');
|
|
93
|
+
if (!apiKey) {
|
|
94
|
+
console.log('ā Nothing was pasted. Your terminal may block pasting into a hidden prompt. Run this instead:\n $env:ELEVENLABS_API_KEY = "sk_..."; labs setup');
|
|
95
|
+
process.exit(1);
|
|
96
|
+
}
|
|
91
97
|
}
|
|
92
98
|
const headers = { 'xi-api-key': apiKey };
|
|
93
99
|
|
|
@@ -95,7 +101,9 @@ async function runSetup() {
|
|
|
95
101
|
try {
|
|
96
102
|
llms = (await axios.get(`${API_BASE}/llm/list`, { headers })).data.llms;
|
|
97
103
|
} catch (error) {
|
|
98
|
-
|
|
104
|
+
const reason = error.response?.data?.detail?.message || error.response?.data?.detail?.status || error.message;
|
|
105
|
+
console.log(`ā ElevenLabs rejected the key (${error.response?.status || 'no response'}): ${reason}`);
|
|
106
|
+
console.log(` The key you gave is ${apiKey.length} characters long${apiKey.startsWith('sk_') ? '' : ' and does not start with sk_'}. Check it has ElevenAgents permission.`);
|
|
99
107
|
process.exit(1);
|
|
100
108
|
}
|
|
101
109
|
saveLlmList(llms);
|
|
@@ -145,4 +153,15 @@ function ask(question) {
|
|
|
145
153
|
});
|
|
146
154
|
}
|
|
147
155
|
|
|
148
|
-
|
|
156
|
+
// The key is typed hidden and goes straight to ~/.labs/bedrock-key (mode 600); it is never printed or logged.
|
|
157
|
+
async function setupBedrock() {
|
|
158
|
+
console.log('\nš§ Amazon Bedrock key for GLM 5.3 (labs --model glm)');
|
|
159
|
+
console.log(' Create one in the AWS console: Amazon Bedrock > API keys > Generate long-term API key.\n');
|
|
160
|
+
const key = await askHidden('Paste the Bedrock API key (hidden): ');
|
|
161
|
+
if (!key) return console.log('Nothing saved.');
|
|
162
|
+
if (!/^ABSK/.test(key)) console.log('ā ļø Bedrock API keys usually start with ABSK; saving it anyway.');
|
|
163
|
+
saveBedrockKey(LABS_DIR, key);
|
|
164
|
+
console.log(`ā
Saved to ${path.join(LABS_DIR, 'bedrock-key')}. Start with: labs --model glm`);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
module.exports = { runSetup, setupBedrock };
|