labs-claude 0.1.2 → 0.1.4

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "labs-claude",
3
- "version": "0.1.2",
3
+ "version": "0.1.4",
4
4
  "description": "Run the real Claude Code CLI on ElevenLabs models (GPT-6 Astra, Opus 5.5, Gemini, GLM...) with your own ElevenLabs key — like Ollama, but for ElevenLabs.",
5
5
  "bin": { "labs": "bin/labs.js" },
6
6
  "files": ["bin", "src", "README.md"],
@@ -26,6 +26,18 @@ function contentToText(content) {
26
26
  }).filter(Boolean).join('\n\n');
27
27
  }
28
28
 
29
+ // Base64 images and PDFs in the user turn, including those nested in tool results (screenshots, Read of a .png).
30
+ function collectImages(blocks) {
31
+ const found = [];
32
+ for (const block of blocks || []) {
33
+ if ((block.type === 'image' || block.type === 'document') && block.source?.type === 'base64') {
34
+ found.push({ mediaType: block.source.media_type, data: block.source.data });
35
+ }
36
+ if (block.type === 'tool_result' && Array.isArray(block.content)) found.push(...collectImages(block.content));
37
+ }
38
+ return found;
39
+ }
40
+
29
41
  function extractLatestUserContent(messages) {
30
42
  for (let index = messages.length - 1; index >= 0; index -= 1) {
31
43
  const message = messages[index];
@@ -48,11 +60,12 @@ function extractLatestUserContent(messages) {
48
60
 
49
61
  return {
50
62
  text: text.trim(),
51
- toolResults
63
+ toolResults,
64
+ images: collectImages(blocks)
52
65
  };
53
66
  }
54
67
 
55
- return { text: '', toolResults: [] };
68
+ return { text: '', toolResults: [], images: [] };
56
69
  }
57
70
 
58
71
  function createAnthropicMessage({ model, text = '', toolCalls = [], inputTokens = 0 }) {
package/src/proxy.js CHANGED
@@ -1,474 +1,517 @@
1
- const express = require('express');
2
- const axios = require('axios');
3
- const bodyParser = require('body-parser');
4
- const fs = require('fs');
5
- const path = require('path');
6
- const { createHash } = require('crypto');
7
- const { execFileSync } = require('child_process');
8
- const WebSocket = require('ws');
9
- const {
10
- createAnthropicEvents,
11
- createAnthropicMessage,
12
- createThreadId,
13
- extractLatestUserContent,
14
- formatConversationHistory,
15
- isValidSessionId,
16
- resolveLlm,
17
- writeAnthropicEvents
18
- } = require('./anthropic-protocol');
19
- const { ToolRegistry } = require('./elevenlabs-tools');
20
- const { API_BASE, LABS_DIR, loadConfig, loadLlmList, saveLlmList } = require('./config');
21
- const { version: VERSION } = require('../package.json');
22
-
23
- console.log(`=== labs-claude proxy ${VERSION} ===`);
24
-
25
- const SETTLE_MS = 800;
26
- const REQUEST_TIMEOUT_MS = 600000;
27
- const MAX_REPLAY_CHARS = 120000;
28
- const CONVERSATIONS_DIR = path.join(LABS_DIR, 'conversations');
29
-
30
- const config = loadConfig();
31
- if (!config?.apiKey || !config.bridgeAgent) {
32
- console.error('❌ Not set up. Run: labs setup');
33
- process.exit(1);
34
- }
35
- const PORT = config.port;
36
- const HEADERS = { 'xi-api-key': config.apiKey };
37
- const aliases = config.models;
38
- let llmList = loadLlmList();
39
- let llmIds = new Set(llmList.map(item => item.llm));
40
- const EFFORT_ORDER = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'];
41
-
42
- // Every tool definition is re-read at the start of each ElevenLabs conversation, and ElevenLabs drops a reply whose
43
- // first token takes over 15 s, so only Claude Code's coding tools and MCP tools are forwarded.
44
- const FORWARDED_BUILTINS = new Set([
45
- 'Agent', 'Task', 'Bash', 'PowerShell', 'Read', 'Write', 'Edit', 'MultiEdit', 'Glob', 'Grep',
46
- 'WebFetch', 'WebSearch', 'Skill', 'ToolSearch', 'TodoWrite', 'NotebookEdit'
47
- ]);
48
-
49
- function isForwardedTool(tool) {
50
- return FORWARDED_BUILTINS.has(tool.name) || tool.name.startsWith('mcp__');
51
- }
52
-
53
- // ElevenLabs cuts any single reply after about 50 s (thinking plus writing, measured), so one Write of a whole file
54
- // fails; the model is asked to build files in small steps instead.
55
- const BRIDGE_NOTE = [
56
- '',
57
- '',
58
- '# Output limits of this connection',
59
- 'Every reply (your thinking plus your output) must finish within about 40 seconds or it is cut off.',
60
- 'Never put more than about 80 lines of code in one Write or Edit call.',
61
- 'Build longer files in steps: Write the first part, then add the rest with further Edit calls, one part per reply.'
62
- ].join('\n');
63
-
64
- const toolRegistry = new ToolRegistry({
65
- http: axios,
66
- apiBase: API_BASE,
67
- headers: HEADERS,
68
- file: path.join(LABS_DIR, `tool-registry-${config.bridgeAgent}.json`),
69
- agentId: config.bridgeAgent
70
- });
71
-
72
- async function refreshLlmList() {
73
- try {
74
- const response = await axios.get(`${API_BASE}/llm/list`, { headers: HEADERS });
75
- saveLlmList(response.data.llms);
76
- llmList = response.data.llms;
77
- llmIds = new Set(llmList.map(item => item.llm));
78
- console.log(`📋 ${llmIds.size} ElevenLabs LLMs available`);
79
- } catch (error) {
80
- console.error(`⚠️ Could not refresh LLM list, using cached copy: ${error.message}`);
81
- }
82
- }
83
-
84
- // Effort and reply length are agent-level settings on ElevenLabs (not per-conversation overrides), so the bridge
85
- // agent is re-pointed before each new conversation; the queue keeps concurrent opens from racing each other.
86
- // ElevenLabs drops a turn whose first token takes longer than 15 s (cascade_timeout_seconds), which very high
87
- // effort can exceed; the highest effort that answered in time is remembered per LLM for the proxy's lifetime.
88
- const effortCaps = new Map();
89
-
90
- function lowerEffortCap(llm, failedEffort) {
91
- const efforts = (llmList.find(item => item.llm === llm)?.available_reasoning_efforts || [])
92
- .filter(option => EFFORT_ORDER.indexOf(option) < EFFORT_ORDER.indexOf(failedEffort));
93
- if (!efforts.length) return false;
94
- effortCaps.set(llm, efforts.reduce((best, option) => EFFORT_ORDER.indexOf(option) > EFFORT_ORDER.indexOf(best) ? option : best));
95
- return true;
96
- }
97
-
98
- function agentSettingsFor(llm, requestedEffort, requestedMaxTokens) {
99
- const info = llmList.find(item => item.llm === llm) || {};
100
- const efforts = info.available_reasoning_efforts || [];
101
- const cap = effortCaps.get(llm);
102
- const capped = cap && EFFORT_ORDER.indexOf(requestedEffort) > EFFORT_ORDER.indexOf(cap) ? cap : requestedEffort;
103
- const wanted = EFFORT_ORDER.indexOf(capped);
104
- const effort = efforts.length
105
- ? efforts.reduce((best, option) => Math.abs(EFFORT_ORDER.indexOf(option) - wanted) < Math.abs(EFFORT_ORDER.indexOf(best) - wanted) ? option : best)
106
- : null;
107
- // Always the model's full reply length: Claude Code's own max_tokens is sized for Anthropic models.
108
- return { llm, reasoning_effort: effort, max_tokens: info.max_tokens_limit || requestedMaxTokens || 4096 };
109
- }
110
-
111
- let settingsQueue = Promise.resolve();
112
- let appliedSettings = '';
113
-
114
- function withAgentSettings(settings, openFn) {
115
- const run = async () => {
116
- const key = JSON.stringify(settings);
117
- if (key !== appliedSettings) {
118
- // An explicit null is required: an effort left over from the previous LLM makes ElevenLabs reject the switch.
119
- const prompt = {
120
- llm: settings.llm,
121
- max_tokens: settings.max_tokens,
122
- reasoning_effort: settings.reasoning_effort,
123
- // Voice defaults: 4 s to first token, then silently fall back to another LLM. 15 s is ElevenLabs' maximum.
124
- cascade_timeout_seconds: 15,
125
- // Streaming a reasoning summary counts as the first output, so long thinking no longer trips the 15 s
126
- // first-token cancel (measured: Opus at max effort answered at 27.8 s with it, was cancelled without).
127
- enable_reasoning_summary: Boolean(settings.reasoning_effort),
128
- backup_llm_config: { preference: 'disabled' }
129
- };
130
- // Conversations default to 600 s on new agents; 7200 s is the API maximum.
131
- await axios.patch(`${API_BASE}/agents/${config.bridgeAgent}`,
132
- { conversation_config: { agent: { prompt }, conversation: { max_duration_seconds: 7200 } } }, { headers: HEADERS });
133
- appliedSettings = key;
134
- console.log(`🎚️ Bridge set to ${settings.llm} effort=${settings.reasoning_effort || 'n/a'} max_tokens=${settings.max_tokens}`);
135
- }
136
- const conn = openFn();
137
- await conn.ready;
138
- return conn;
139
- };
140
- const next = settingsQueue.then(run, run);
141
- settingsQueue = next.catch(() => {});
142
- return next;
143
- }
144
-
145
- // ============================================
146
- // WEBSOCKET CONVERSATIONS: one per (LLM, Claude Code thread, tool set)
147
- // ============================================
148
-
149
- const connections = new Map();
150
-
151
- function systemText(system) {
152
- if (typeof system === 'string') return system;
153
- return Array.isArray(system) ? system.map(block => block.text || '').join('\n\n') : '';
154
- }
155
-
156
- function openConversation(key, { llm, prompt, toolIds }) {
157
- const existing = connections.get(key);
158
- // A socket still CONNECTING must be awaited, not replaced: replacing it routed the old socket's events into the new one.
159
- if (existing && [WebSocket.OPEN, WebSocket.CONNECTING].includes(existing.ws.readyState)) return existing;
160
-
161
- console.log(`🔌 Opening ${llm} conversation (${toolIds.length} tools) for ${key}`);
162
- const ws = new WebSocket(`wss://api.elevenlabs.io/v1/convai/conversation?agent_id=${config.bridgeAgent}`, { headers: HEADERS });
163
- const conn = {
164
- ws,
165
- llm,
166
- pending: null,
167
- messageId: 0,
168
- conversationId: null,
169
- contextTokens: 0,
170
- openToolCallIds: new Set(),
171
- closeReason: ''
172
- };
173
- connections.set(key, conn);
174
-
175
- conn.ready = new Promise((resolve, reject) => {
176
- ws.on('open', () => {
177
- ws.send(JSON.stringify({
178
- type: 'conversation_initiation_client_data',
179
- conversation_config_override: {
180
- conversation: { text_only: true },
181
- agent: { first_message: '', prompt: { prompt, llm, tool_ids: toolIds } }
182
- }
183
- }));
184
- conn.markReady = resolve;
185
- });
186
- ws.on('error', error => {
187
- console.error(`🚨 WS error for ${key}: ${error.message}`);
188
- reject(error);
189
- });
190
- ws.on('close', (code, reason) => {
191
- conn.closeReason = `code ${code}${reason?.length ? `: ${reason}` : ''}`;
192
- console.log(`🔌 Conversation closed for ${key} (${conn.closeReason})`);
193
- reject(new Error(`ElevenLabs closed the conversation (${conn.closeReason})`));
194
- if (conn.pending) settle(conn, { error: new Error(`ElevenLabs closed the conversation (${conn.closeReason})`) });
195
- connections.delete(key);
196
- });
197
- });
198
- conn.ready.catch(() => {});
199
-
200
- ws.on('message', data => {
201
- try {
202
- handleEvent(conn, JSON.parse(data.toString()));
203
- } catch (error) {
204
- console.error(`⚠️ WS event error: ${error.message}`);
205
- }
206
- });
207
- return conn;
208
- }
209
-
210
- function handleEvent(conn, msg) {
211
- switch (msg.type) {
212
- case 'conversation_initiation_metadata':
213
- conn.conversationId = msg.conversation_initiation_metadata_event?.conversation_id;
214
- console.log(`📋 Conversation ${conn.conversationId} on ${conn.llm}`);
215
- conn.markReady?.(conn);
216
- break;
217
- case 'ping':
218
- // The server expects the ping's event_id echoed back; a bare pong lets the connection die.
219
- conn.ws.send(JSON.stringify({ type: 'pong', event_id: msg.ping_event?.event_id }));
220
- break;
221
- case 'agent_response': {
222
- if (!conn.pending) break;
223
- const text = msg.agent_response_event?.agent_response || '';
224
- conn.pending.text = conn.pending.text ? `${conn.pending.text}\n\n${text}` : text;
225
- settleSoon(conn);
226
- break;
227
- }
228
- case 'client_tool_call':
229
- handleToolCall(conn, msg.client_tool_call);
230
- break;
231
- case 'context_usage':
232
- conn.contextTokens = msg.context_usage_event?.context_tokens || conn.contextTokens;
233
- break;
234
- case 'client_error':
235
- console.error(`🚨 ElevenLabs client_error: ${JSON.stringify(msg.error_event)}`);
236
- break;
237
- default:
238
- break;
239
- }
240
- }
241
-
242
- function handleToolCall(conn, call) {
243
- if (!call?.tool_name || !call.tool_call_id) return;
244
- if (!conn.pending) {
245
- // Arrived after the turn was already returned; answering keeps the agent from waiting forever.
246
- conn.ws.send(JSON.stringify({
247
- type: 'client_tool_result', tool_call_id: call.tool_call_id, is_error: true,
248
- result: 'This tool call arrived after the turn ended. Request it again in your next turn.'
249
- }));
250
- return;
251
- }
252
- const name = toolRegistry.claudeNameFor(call.tool_name);
253
- if (call.parameters) call.parameters = withWindowsPaths(call.parameters);
254
- console.log(`🔧 ${name} ${JSON.stringify(call.parameters || {}).slice(0, 160)}`);
255
- conn.pending.toolCalls.push({ id: call.tool_call_id, name, input: call.parameters || {} });
256
- conn.openToolCallIds.add(call.tool_call_id);
257
- settleSoon(conn);
258
- }
259
-
260
- // On Windows, models copy Git Bash paths (/tmp/..., /c/Users/...) from `pwd` into file tools; Claude Code reads those
261
- // as outside the project and asks for permission. Git's own cygpath gives the exact Windows equivalent.
262
- const PATH_KEYS = ['file_path', 'path', 'notebook_path'];
263
- const windowsPathCache = new Map();
264
-
265
- function toWindowsPath(value) {
266
- if (process.platform !== 'win32' || typeof value !== 'string' || !value.startsWith('/')) return value;
267
- if (!windowsPathCache.has(value)) {
268
- let converted = value.replace(/^\/([a-zA-Z])(\/|$)/, (match, drive) => `${drive.toUpperCase()}:\\`).replace(/\//g, '\\');
269
- try {
270
- converted = execFileSync('cygpath', ['-w', value], { encoding: 'utf8', windowsHide: true }).trim() || converted;
271
- } catch {
272
- // cygpath missing: the drive-letter rewrite above is the best available guess.
273
- }
274
- windowsPathCache.set(value, converted);
275
- }
276
- return windowsPathCache.get(value);
277
- }
278
-
279
- function withWindowsPaths(input) {
280
- const output = { ...input };
281
- for (const key of PATH_KEYS) output[key] = toWindowsPath(output[key]);
282
- for (const key of PATH_KEYS) if (output[key] === undefined) delete output[key];
283
- return output;
284
- }
285
-
286
- // The agent can emit text and several tool calls for one turn as separate events, so settle after a short quiet gap.
287
- function settleSoon(conn) {
288
- clearTimeout(conn.pending.settleTimer);
289
- conn.pending.settleTimer = setTimeout(() => settle(conn, null), SETTLE_MS);
290
- }
291
-
292
- function settle(conn, failure) {
293
- const pending = conn.pending;
294
- if (!pending) return;
295
- conn.pending = null;
296
- clearTimeout(pending.settleTimer);
297
- clearTimeout(pending.timeout);
298
- if (failure?.error) pending.reject(failure.error);
299
- else pending.resolve({ text: pending.text, toolCalls: pending.toolCalls });
300
- }
301
-
302
- function sendTurn(conn, { text, toolResults, history }) {
303
- if (conn.pending) throw new Error('A request is already active for this conversation');
304
- const requestId = String(++conn.messageId);
305
-
306
- return new Promise((resolve, reject) => {
307
- conn.pending = { resolve, reject, text: '', toolCalls: [], settleTimer: null };
308
- conn.pending.timeout = setTimeout(
309
- () => settle(conn, { error: new Error(`No reply from ${conn.llm} within ${REQUEST_TIMEOUT_MS / 1000}s`) }),
310
- REQUEST_TIMEOUT_MS
311
- );
312
-
313
- // Claude Code resends the whole thread every turn, so a fresh conversation (reconnect, /model switch,
314
- // --resume, compaction) is seeded from what Claude Code sent.
315
- if (conn.messageId === 1 && history.length) {
316
- conn.ws.send(JSON.stringify({
317
- type: 'contextual_update',
318
- text: `Conversation so far:\n${formatConversationHistory(history).slice(-MAX_REPLAY_CHARS)}`
319
- }));
320
- }
321
-
322
- const known = toolResults.filter(result => conn.openToolCallIds.has(result.toolUseId));
323
- if (toolResults.length && known.length === toolResults.length) {
324
- for (const result of toolResults) {
325
- conn.openToolCallIds.delete(result.toolUseId);
326
- conn.ws.send(JSON.stringify({
327
- type: 'client_tool_result',
328
- tool_call_id: result.toolUseId,
329
- result: result.content,
330
- is_error: result.isError
331
- }));
332
- }
333
- if (text) conn.ws.send(JSON.stringify({ type: 'contextual_update', text }));
334
- return;
335
- }
336
-
337
- // Results for calls this conversation never made (it was reopened) go in as text, otherwise the agent
338
- // waits on tool_call_ids it does not know and never answers.
339
- const resultText = toolResults
340
- .map(result => `${result.isError ? 'Tool error' : 'Tool result'} (${result.toolUseId}):\n${result.content}`)
341
- .join('\n\n');
342
- conn.ws.send(JSON.stringify({
343
- type: 'user_message',
344
- id: requestId,
345
- text: [resultText, text, resultText ? 'Continue the task from here.' : ''].filter(Boolean).join('\n\n')
346
- }));
347
- });
348
- }
349
-
350
- function saveConversation(threadId, llm, conversationId, messages) {
351
- if (!fs.existsSync(CONVERSATIONS_DIR)) fs.mkdirSync(CONVERSATIONS_DIR, { recursive: true });
352
- fs.writeFileSync(path.join(CONVERSATIONS_DIR, `${threadId}.json`),
353
- JSON.stringify({ llm, conversationId, history: messages, updatedAt: Date.now() }, null, 1));
354
- }
355
-
356
- function anthropicError(res, status, type, message) {
357
- return res.status(status).json({ type: 'error', error: { type, message } });
358
- }
359
-
360
- // ============================================
361
- // HTTP: Anthropic Messages API
362
- // ============================================
363
-
364
- const app = express();
365
- app.use(bodyParser.json({ limit: '50mb' }));
366
-
367
- app.post('/v1/messages', async (req, res) => {
368
- const { model, messages = [], system, stream, metadata, tools = [], max_tokens: maxTokens, output_config: outputConfig } = req.body;
369
- const launchModel = req.get('x-labs-model');
370
- // Claude Code answers repeated errors by falling back opus -> sonnet -> haiku on its own; on the main thread
371
- // (tools present) a Claude id therefore means "fallback", so stay on the model the user launched with.
372
- const isClaudeFallback = /^claude-/.test(model || '') && (req.body.tools || []).length > 0 && Boolean(launchModel);
373
- const llm = resolveLlm(isClaudeFallback ? launchModel : model, launchModel, aliases, llmIds);
374
- console.log(`\n🤖 ${model} -> ${llm || 'UNKNOWN'} | ${messages.length} messages | ${tools.length} tools`);
375
- if (!llm) return anthropicError(res, 400, 'invalid_request_error', `Unknown model "${model}". Run "labs models" to list models.`);
376
-
377
- try {
378
- const latest = extractLatestUserContent(messages);
379
- if (!latest.text && latest.toolResults.length === 0) {
380
- return anthropicError(res, 400, 'invalid_request_error', 'No text or tool result in the latest user message');
381
- }
382
-
383
- // Claude Code's side calls (titles, summaries) carry no tools; keep them out of the coding conversation.
384
- const isSideRequest = tools.length === 0;
385
- const sessionId = req.get('x-labs-session-id') || metadata?.session_id || `side_${Date.now()}`;
386
- const threadId = isValidSessionId(sessionId) ? createThreadId(sessionId, messages) : createThreadId('anon', messages);
387
- const toolIds = isSideRequest ? [] : await toolRegistry.ensure(tools.filter(isForwardedTool));
388
- const toolSetHash = createHash('sha1').update(toolIds.join(',')).digest('hex').slice(0, 8);
389
- let conn;
390
- let result;
391
- for (;;) {
392
- const settings = agentSettingsFor(llm, outputConfig?.effort || 'high', maxTokens);
393
- const key = isSideRequest
394
- ? `side_${Date.now()}_${Math.random().toString(36).slice(2)}`
395
- : `${llm}:${settings.reasoning_effort}:${threadId}:${toolSetHash}`;
396
- const existing = connections.get(key);
397
- conn = existing && existing.ws.readyState === WebSocket.OPEN
398
- ? existing
399
- : await withAgentSettings(settings, () => openConversation(key, { llm, prompt: `${systemText(system) || 'You are a helpful assistant.'}${BRIDGE_NOTE}`, toolIds }));
400
- try {
401
- result = await sendTurn(conn, { text: latest.text, toolResults: latest.toolResults, history: messages.slice(0, -1) });
402
- break;
403
- } catch (error) {
404
- if (!/Cascade Error: TimeoutError|took too long/.test(error.message) || !lowerEffortCap(llm, settings.reasoning_effort)) throw error;
405
- console.log(`🎚️ ${llm} too slow at effort=${settings.reasoning_effort}; retrying at ${effortCaps.get(llm)}`);
406
- }
407
- }
408
-
409
- // Claude Code decides when to auto-compact from input_tokens, so report the whole request, not just the last turn.
410
- // Base64 images and documents are thousands of characters but roughly 1.5k tokens each to a model; counting
411
- // their raw length made Claude Code believe the window was full and compact after every prompt.
412
- const IMAGE_TOKENS_AS_CHARS = 6000;
413
- const withoutBinary = JSON.stringify(messages, (field, value) =>
414
- field === 'data' && typeof value === 'string' && value.length > IMAGE_TOKENS_AS_CHARS ? 'x'.repeat(IMAGE_TOKENS_AS_CHARS) : value);
415
- const requestChars = JSON.stringify(system || '').length + withoutBinary.length + JSON.stringify(tools.filter(isForwardedTool)).length;
416
- const message = createAnthropicMessage({
417
- model,
418
- text: result.text || '',
419
- toolCalls: result.toolCalls || [],
420
- inputTokens: conn.contextTokens || Math.ceil(requestChars / 4)
421
- });
422
-
423
- if (isSideRequest) conn.ws.close();
424
- else saveConversation(threadId, llm, conn.conversationId, [...messages, { role: 'assistant', content: message.content }]);
425
-
426
- return stream ? writeAnthropicEvents(res, createAnthropicEvents(message)) : res.json(message);
427
- } catch (error) {
428
- console.error(`🚨 ${llm}: ${error.message}`);
429
- // 500, not 529: Claude Code retries a 500 on the same model, but answers repeated 529s by switching models.
430
- if (!res.headersSent) return anthropicError(res, 500, 'api_error', `ElevenLabs ${llm}: ${error.message}`);
431
- }
432
- });
433
-
434
- app.get('/health', (req, res) => res.json({ name: 'labs-claude', version: VERSION }));
435
-
436
- app.post('/shutdown', (req, res) => {
437
- res.json({ ok: true });
438
- setTimeout(() => process.exit(0), 100);
439
- });
440
-
441
- app.get('/v1/models', (req, res) => {
442
- res.json({ data: Object.entries(aliases).map(([id, llm]) => ({ id, type: 'model', display_name: `${id} (${llm})` })) });
443
- });
444
-
445
- app.get('/v1/sessions', (req, res) => {
446
- if (!fs.existsSync(CONVERSATIONS_DIR)) return res.json({ sessions: [] });
447
- const sessions = fs.readdirSync(CONVERSATIONS_DIR).filter(file => file.endsWith('.json')).map(file => {
448
- const data = JSON.parse(fs.readFileSync(path.join(CONVERSATIONS_DIR, file), 'utf8'));
449
- return { id: file.replace('.json', ''), llm: data.llm || data.agentId, messageCount: (data.history || []).length, updatedAt: data.updatedAt };
450
- });
451
- res.json({ sessions: sessions.sort((a, b) => b.updatedAt - a.updatedAt) });
452
- });
453
-
454
- app.delete('/v1/sessions/:sessionId', (req, res) => {
455
- const { sessionId } = req.params;
456
- if (!isValidSessionId(sessionId)) return res.status(400).json({ error: 'Invalid session ID' });
457
- const filePath = path.join(CONVERSATIONS_DIR, `${sessionId}.json`);
458
- if (!fs.existsSync(filePath)) return res.status(404).json({ error: 'Session not found' });
459
- fs.unlinkSync(filePath);
460
- res.json({ success: true });
461
- });
462
-
463
- process.on('uncaughtException', error => console.error(`💥 Uncaught: ${error.stack}`));
464
- process.on('unhandledRejection', error => console.error(`💥 Unhandled rejection: ${error?.stack || error}`));
465
-
466
- process.on('SIGINT', () => {
467
- connections.forEach(conn => conn.ws.close());
468
- process.exit(0);
469
- });
470
-
471
- app.listen(PORT, '127.0.0.1', () => {
472
- console.log(`✅ Proxy LIVE at http://localhost:${PORT} | bridge agent ${config.bridgeAgent}`);
473
- refreshLlmList();
474
- });
1
+ const express = require('express');
2
+ const axios = require('axios');
3
+ const bodyParser = require('body-parser');
4
+ const fs = require('fs');
5
+ const path = require('path');
6
+ const { createHash } = require('crypto');
7
+ const { execFileSync } = require('child_process');
8
+ const WebSocket = require('ws');
9
+ const {
10
+ createAnthropicEvents,
11
+ createAnthropicMessage,
12
+ createThreadId,
13
+ extractLatestUserContent,
14
+ formatConversationHistory,
15
+ isValidSessionId,
16
+ resolveLlm,
17
+ writeAnthropicEvents
18
+ } = require('./anthropic-protocol');
19
+ const { ToolRegistry } = require('./elevenlabs-tools');
20
+ const { API_BASE, LABS_DIR, loadConfig, loadLlmList, saveLlmList } = require('./config');
21
+ const { version: VERSION } = require('../package.json');
22
+
23
+ console.log(`=== labs-claude proxy ${VERSION} ===`);
24
+
25
+ const SETTLE_MS = 800;
26
+ const REQUEST_TIMEOUT_MS = 600000;
27
+ const MAX_REPLAY_CHARS = 120000;
28
+ const CONVERSATIONS_DIR = path.join(LABS_DIR, 'conversations');
29
+
30
+ const config = loadConfig();
31
+ if (!config?.apiKey || !config.bridgeAgent) {
32
+ console.error('❌ Not set up. Run: labs setup');
33
+ process.exit(1);
34
+ }
35
+ const PORT = config.port;
36
+ const HEADERS = { 'xi-api-key': config.apiKey };
37
+ const aliases = config.models;
38
+ let llmList = loadLlmList();
39
+ let llmIds = new Set(llmList.map(item => item.llm));
40
+ const EFFORT_ORDER = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'];
41
+
42
+ // Every tool definition is re-read at the start of each ElevenLabs conversation, and ElevenLabs drops a reply whose
43
+ // first token takes over 15 s, so only Claude Code's coding tools and MCP tools are forwarded.
44
+ const FORWARDED_BUILTINS = new Set([
45
+ 'Agent', 'Task', 'Bash', 'PowerShell', 'Read', 'Write', 'Edit', 'MultiEdit', 'Glob', 'Grep',
46
+ 'WebFetch', 'WebSearch', 'Skill', 'ToolSearch', 'TodoWrite', 'NotebookEdit'
47
+ ]);
48
+
49
+ function isForwardedTool(tool) {
50
+ return FORWARDED_BUILTINS.has(tool.name) || tool.name.startsWith('mcp__');
51
+ }
52
+
53
+ // ElevenLabs cuts any single reply after about 50 s (thinking plus writing, measured), so one Write of a whole file
54
+ // fails; the model is asked to build files in small steps instead.
55
+ const BRIDGE_NOTE = [
56
+ '',
57
+ '',
58
+ '# Output limits of this connection',
59
+ 'Every reply (your thinking plus your output) must finish within about 40 seconds or it is cut off.',
60
+ 'Never put more than about 80 lines of code in one Write or Edit call.',
61
+ 'Build longer files in steps: Write the first part, then add the rest with further Edit calls, one part per reply.'
62
+ ].join('\n');
63
+
64
+ const toolRegistry = new ToolRegistry({
65
+ http: axios,
66
+ apiBase: API_BASE,
67
+ headers: HEADERS,
68
+ file: path.join(LABS_DIR, `tool-registry-${config.bridgeAgent}.json`),
69
+ agentId: config.bridgeAgent
70
+ });
71
+
72
+ async function refreshLlmList() {
73
+ try {
74
+ const response = await axios.get(`${API_BASE}/llm/list`, { headers: HEADERS });
75
+ saveLlmList(response.data.llms);
76
+ llmList = response.data.llms;
77
+ llmIds = new Set(llmList.map(item => item.llm));
78
+ console.log(`📋 ${llmIds.size} ElevenLabs LLMs available`);
79
+ } catch (error) {
80
+ console.error(`⚠️ Could not refresh LLM list, using cached copy: ${error.message}`);
81
+ }
82
+ }
83
+
84
+ // Effort and reply length are agent-level settings on ElevenLabs (not per-conversation overrides), so the bridge
85
+ // agent is re-pointed before each new conversation; the queue keeps concurrent opens from racing each other.
86
+ // ElevenLabs drops a turn whose first token takes longer than 15 s (cascade_timeout_seconds), which very high
87
+ // effort can exceed; the highest effort that answered in time is remembered per LLM for the proxy's lifetime.
88
+ const effortCaps = new Map();
89
+
90
+ function lowerEffortCap(llm, failedEffort) {
91
+ const efforts = (llmList.find(item => item.llm === llm)?.available_reasoning_efforts || [])
92
+ .filter(option => EFFORT_ORDER.indexOf(option) < EFFORT_ORDER.indexOf(failedEffort));
93
+ if (!efforts.length) return false;
94
+ effortCaps.set(llm, efforts.reduce((best, option) => EFFORT_ORDER.indexOf(option) > EFFORT_ORDER.indexOf(best) ? option : best));
95
+ return true;
96
+ }
97
+
98
+ function agentSettingsFor(llm, requestedEffort, requestedMaxTokens) {
99
+ const info = llmList.find(item => item.llm === llm) || {};
100
+ const efforts = info.available_reasoning_efforts || [];
101
+ const cap = effortCaps.get(llm);
102
+ const capped = cap && EFFORT_ORDER.indexOf(requestedEffort) > EFFORT_ORDER.indexOf(cap) ? cap : requestedEffort;
103
+ const wanted = EFFORT_ORDER.indexOf(capped);
104
+ const effort = efforts.length
105
+ ? efforts.reduce((best, option) => Math.abs(EFFORT_ORDER.indexOf(option) - wanted) < Math.abs(EFFORT_ORDER.indexOf(best) - wanted) ? option : best)
106
+ : null;
107
+ // Always the model's full reply length: Claude Code's own max_tokens is sized for Anthropic models.
108
+ return { llm, reasoning_effort: effort, max_tokens: info.max_tokens_limit || requestedMaxTokens || 4096 };
109
+ }
110
+
111
+ let settingsQueue = Promise.resolve();
112
+ let appliedSettings = '';
113
+
114
+ function withAgentSettings(settings, openFn) {
115
+ const run = async () => {
116
+ const key = JSON.stringify(settings);
117
+ if (key !== appliedSettings) {
118
+ // An explicit null is required: an effort left over from the previous LLM makes ElevenLabs reject the switch.
119
+ const prompt = {
120
+ llm: settings.llm,
121
+ max_tokens: settings.max_tokens,
122
+ reasoning_effort: settings.reasoning_effort,
123
+ // Voice defaults: 4 s to first token, then silently fall back to another LLM. 15 s is ElevenLabs' maximum.
124
+ cascade_timeout_seconds: 15,
125
+ // Streaming a reasoning summary counts as the first output, so long thinking no longer trips the 15 s
126
+ // first-token cancel (measured: Opus at max effort answered at 27.8 s with it, was cancelled without).
127
+ enable_reasoning_summary: Boolean(settings.reasoning_effort),
128
+ backup_llm_config: { preference: 'disabled' }
129
+ };
130
+ // Conversations default to 600 s on new agents; 7200 s is the API maximum.
131
+ await axios.patch(`${API_BASE}/agents/${config.bridgeAgent}`,
132
+ { conversation_config: { agent: { prompt }, conversation: { max_duration_seconds: 7200, file_input: { enabled: true } } } }, { headers: HEADERS });
133
+ appliedSettings = key;
134
+ console.log(`🎚️ Bridge set to ${settings.llm} effort=${settings.reasoning_effort || 'n/a'} max_tokens=${settings.max_tokens}`);
135
+ }
136
+ const conn = openFn();
137
+ await conn.ready;
138
+ return conn;
139
+ };
140
+ const next = settingsQueue.then(run, run);
141
+ settingsQueue = next.catch(() => {});
142
+ return next;
143
+ }
144
+
145
+ // ============================================
146
+ // WEBSOCKET CONVERSATIONS: one per (LLM, Claude Code thread, tool set)
147
+ // ============================================
148
+
149
+ const connections = new Map();
150
+
151
+ function systemText(system) {
152
+ if (typeof system === 'string') return system;
153
+ return Array.isArray(system) ? system.map(block => block.text || '').join('\n\n') : '';
154
+ }
155
+
156
+ function openConversation(key, { llm, prompt, toolIds }) {
157
+ const existing = connections.get(key);
158
+ // A socket still CONNECTING must be awaited, not replaced: replacing it routed the old socket's events into the new one.
159
+ if (existing && [WebSocket.OPEN, WebSocket.CONNECTING].includes(existing.ws.readyState)) return existing;
160
+
161
+ console.log(`🔌 Opening ${llm} conversation (${toolIds.length} tools) for ${key}`);
162
+ const ws = new WebSocket(`wss://api.elevenlabs.io/v1/convai/conversation?agent_id=${config.bridgeAgent}`, { headers: HEADERS });
163
+ const conn = {
164
+ ws,
165
+ llm,
166
+ pending: null,
167
+ messageId: 0,
168
+ conversationId: null,
169
+ contextTokens: 0,
170
+ openToolCallIds: new Set(),
171
+ closeReason: ''
172
+ };
173
+ connections.set(key, conn);
174
+
175
+ conn.ready = new Promise((resolve, reject) => {
176
+ ws.on('open', () => {
177
+ ws.send(JSON.stringify({
178
+ type: 'conversation_initiation_client_data',
179
+ conversation_config_override: {
180
+ conversation: { text_only: true },
181
+ agent: { first_message: '', prompt: { prompt, llm, tool_ids: toolIds } }
182
+ }
183
+ }));
184
+ conn.markReady = resolve;
185
+ });
186
+ ws.on('error', error => {
187
+ console.error(`🚨 WS error for ${key}: ${error.message}`);
188
+ reject(error);
189
+ });
190
+ ws.on('close', (code, reason) => {
191
+ conn.closeReason = `code ${code}${reason?.length ? `: ${reason}` : ''}`;
192
+ console.log(`🔌 Conversation closed for ${key} (${conn.closeReason})`);
193
+ reject(new Error(`ElevenLabs closed the conversation (${conn.closeReason})`));
194
+ if (conn.pending) settle(conn, { error: new Error(`ElevenLabs closed the conversation (${conn.closeReason})`) });
195
+ connections.delete(key);
196
+ });
197
+ });
198
+ conn.ready.catch(() => {});
199
+
200
+ ws.on('message', data => {
201
+ try {
202
+ handleEvent(conn, JSON.parse(data.toString()));
203
+ } catch (error) {
204
+ console.error(`⚠️ WS event error: ${error.message}`);
205
+ }
206
+ });
207
+ return conn;
208
+ }
209
+
210
+ function handleEvent(conn, msg) {
211
+ switch (msg.type) {
212
+ case 'conversation_initiation_metadata':
213
+ conn.conversationId = msg.conversation_initiation_metadata_event?.conversation_id;
214
+ console.log(`📋 Conversation ${conn.conversationId} on ${conn.llm}`);
215
+ conn.markReady?.(conn);
216
+ break;
217
+ case 'ping':
218
+ // The server expects the ping's event_id echoed back; a bare pong lets the connection die.
219
+ conn.ws.send(JSON.stringify({ type: 'pong', event_id: msg.ping_event?.event_id }));
220
+ break;
221
+ case 'agent_response': {
222
+ if (!conn.pending) break;
223
+ const text = msg.agent_response_event?.agent_response || '';
224
+ conn.pending.text = conn.pending.text ? `${conn.pending.text}\n\n${text}` : text;
225
+ settleSoon(conn);
226
+ break;
227
+ }
228
+ case 'client_tool_call':
229
+ handleToolCall(conn, msg.client_tool_call);
230
+ break;
231
+ case 'context_usage':
232
+ conn.contextTokens = msg.context_usage_event?.context_tokens || conn.contextTokens;
233
+ break;
234
+ case 'client_error':
235
+ console.error(`🚨 ElevenLabs client_error: ${JSON.stringify(msg.error_event)}`);
236
+ break;
237
+ default:
238
+ break;
239
+ }
240
+ }
241
+
242
+ function handleToolCall(conn, call) {
243
+ if (!call?.tool_name || !call.tool_call_id) return;
244
+ if (!conn.pending) {
245
+ // Arrived after the turn was already returned; answering keeps the agent from waiting forever.
246
+ conn.ws.send(JSON.stringify({
247
+ type: 'client_tool_result', tool_call_id: call.tool_call_id, is_error: true,
248
+ result: 'This tool call arrived after the turn ended. Request it again in your next turn.'
249
+ }));
250
+ return;
251
+ }
252
+ const name = toolRegistry.claudeNameFor(call.tool_name);
253
+ if (call.parameters) call.parameters = withWindowsPaths(call.parameters);
254
+ console.log(`🔧 ${name} ${JSON.stringify(call.parameters || {}).slice(0, 160)}`);
255
+ conn.pending.toolCalls.push({ id: call.tool_call_id, name, input: call.parameters || {} });
256
+ conn.openToolCallIds.add(call.tool_call_id);
257
+ settleSoon(conn);
258
+ }
259
+
260
+ // On Windows, models copy Git Bash paths (/tmp/..., /c/Users/...) from `pwd` into file tools; Claude Code reads those
261
+ // as outside the project and asks for permission. Git's own cygpath gives the exact Windows equivalent.
262
+ const PATH_KEYS = ['file_path', 'path', 'notebook_path'];
263
+ const windowsPathCache = new Map();
264
+
265
+ function toWindowsPath(value) {
266
+ if (process.platform !== 'win32' || typeof value !== 'string' || !value.startsWith('/')) return value;
267
+ if (!windowsPathCache.has(value)) {
268
+ let converted = value.replace(/^\/([a-zA-Z])(\/|$)/, (match, drive) => `${drive.toUpperCase()}:\\`).replace(/\//g, '\\');
269
+ try {
270
+ converted = execFileSync('cygpath', ['-w', value], { encoding: 'utf8', windowsHide: true }).trim() || converted;
271
+ } catch {
272
+ // cygpath missing: the drive-letter rewrite above is the best available guess.
273
+ }
274
+ windowsPathCache.set(value, converted);
275
+ }
276
+ return windowsPathCache.get(value);
277
+ }
278
+
279
+ function withWindowsPaths(input) {
280
+ const output = { ...input };
281
+ for (const key of PATH_KEYS) output[key] = toWindowsPath(output[key]);
282
+ for (const key of PATH_KEYS) if (output[key] === undefined) delete output[key];
283
+ return output;
284
+ }
285
+
286
+ // The agent can emit text and several tool calls for one turn as separate events, so settle after a short quiet gap.
287
+ // ElevenLabs sends no end-of-turn event, and a model may send its "Now adding X" sentence long before the tool call
288
+ // that writes X. Settling 0.8 s after text alone ended turns early and the late tool call was thrown away.
289
+ const TEXT_SETTLE_MS = 6000;
290
+ const ANNOUNCEMENT_SETTLE_MS = 40000;
291
+ const ANNOUNCES_WORK = /(\bnow\b|\bnext\b|\bnext:|i'll|i will|let me|adding|writing|building|creating|updating|starting|:\s*$|…\s*$|\.\.\.\s*$)/i;
292
+
293
+ function settleSoon(conn) {
294
+ const pending = conn.pending;
295
+ clearTimeout(pending.settleTimer);
296
+ const lastLine = (pending.text || '').trim().split('\n').pop() || '';
297
+ // Announcements are short; a long text reply that merely mentions "next steps" is a finished answer.
298
+ const announces = (pending.text || '').length < 400 && ANNOUNCES_WORK.test(lastLine);
299
+ const wait = pending.toolCalls.length ? SETTLE_MS : announces ? ANNOUNCEMENT_SETTLE_MS : TEXT_SETTLE_MS;
300
+ pending.settleTimer = setTimeout(() => settle(conn, null), wait);
301
+ }
302
+
303
+ function settle(conn, failure) {
304
+ const pending = conn.pending;
305
+ if (!pending) return;
306
+ conn.pending = null;
307
+ clearTimeout(pending.settleTimer);
308
+ clearTimeout(pending.timeout);
309
+ if (failure?.error) pending.reject(failure.error);
310
+ else pending.resolve({ text: pending.text, toolCalls: pending.toolCalls });
311
+ }
312
+
313
+ // Images reach ElevenLabs only as files uploaded to the conversation and referenced from a multimodal_message.
314
+ const MAX_FILES_PER_MESSAGE = 5;
315
+
316
+ async function uploadImages(conn, images) {
317
+ const fileIds = [];
318
+ for (const [index, image] of images.entries()) {
319
+ const extension = (image.mediaType.split('/')[1] || 'png').replace('jpeg', 'jpg');
320
+ const form = new FormData();
321
+ form.append('file', new Blob([Buffer.from(image.data, 'base64')], { type: image.mediaType }), `image-${index + 1}.${extension}`);
322
+ const response = await fetch(`${API_BASE}/conversations/${conn.conversationId}/files`, { method: 'POST', headers: HEADERS, body: form });
323
+ if (!response.ok) throw new Error(`Image upload failed (${response.status}): ${(await response.text()).slice(0, 200)}`);
324
+ fileIds.push((await response.json()).file_id);
325
+ }
326
+ return fileIds;
327
+ }
328
+
329
+ function sendMultimodal(conn, text, fileIds) {
330
+ for (let start = 0; start < fileIds.length; start += MAX_FILES_PER_MESSAGE) {
331
+ conn.ws.send(JSON.stringify({
332
+ type: 'multimodal_message',
333
+ text: { type: 'user_message', text: start === 0 ? text : 'More images:', source_medium: 'image' },
334
+ files: fileIds.slice(start, start + MAX_FILES_PER_MESSAGE).map(fileId => ({ type: 'file_input', file_id: fileId }))
335
+ }));
336
+ }
337
+ }
338
+
339
+ function sendTurn(conn, { text, toolResults, history, images = [] }) {
340
+ if (conn.pending) throw new Error('A request is already active for this conversation');
341
+ const requestId = String(++conn.messageId);
342
+
343
+ return new Promise(async (resolve, reject) => {
344
+ conn.pending = { resolve, reject, text: '', toolCalls: [], settleTimer: null };
345
+ let fileIds = [];
346
+ try {
347
+ fileIds = images.length ? await uploadImages(conn, images) : [];
348
+ } catch (error) {
349
+ settle(conn, { error });
350
+ return;
351
+ }
352
+ conn.pending.timeout = setTimeout(
353
+ () => settle(conn, { error: new Error(`No reply from ${conn.llm} within ${REQUEST_TIMEOUT_MS / 1000}s`) }),
354
+ REQUEST_TIMEOUT_MS
355
+ );
356
+
357
+ // Claude Code resends the whole thread every turn, so a fresh conversation (reconnect, /model switch,
358
+ // --resume, compaction) is seeded from what Claude Code sent.
359
+ if (conn.messageId === 1 && history.length) {
360
+ conn.ws.send(JSON.stringify({
361
+ type: 'contextual_update',
362
+ text: `Conversation so far:\n${formatConversationHistory(history).slice(-MAX_REPLAY_CHARS)}`
363
+ }));
364
+ }
365
+
366
+ const known = toolResults.filter(result => conn.openToolCallIds.has(result.toolUseId));
367
+ if (toolResults.length && known.length === toolResults.length) {
368
+ for (const result of toolResults) {
369
+ conn.openToolCallIds.delete(result.toolUseId);
370
+ conn.ws.send(JSON.stringify({
371
+ type: 'client_tool_result',
372
+ tool_call_id: result.toolUseId,
373
+ result: fileIds.length ? `${result.content}\n[The image output of this tool follows in the next message.]` : result.content,
374
+ is_error: result.isError
375
+ }));
376
+ }
377
+ if (text) conn.ws.send(JSON.stringify({ type: 'contextual_update', text }));
378
+ if (fileIds.length) sendMultimodal(conn, 'Image output of the tool call above.', fileIds);
379
+ return;
380
+ }
381
+
382
+ // Results for calls this conversation never made (it was reopened) go in as text, otherwise the agent
383
+ // waits on tool_call_ids it does not know and never answers.
384
+ const resultText = toolResults
385
+ .map(result => `${result.isError ? 'Tool error' : 'Tool result'} (${result.toolUseId}):\n${result.content}`)
386
+ .join('\n\n');
387
+ const turnText = [resultText, text, resultText ? 'Continue the task from here.' : ''].filter(Boolean).join('\n\n');
388
+ if (fileIds.length) sendMultimodal(conn, turnText || 'See the attached image.', fileIds);
389
+ else conn.ws.send(JSON.stringify({ type: 'user_message', id: requestId, text: turnText }));
390
+ });
391
+ }
392
+
393
+ function saveConversation(threadId, llm, conversationId, messages) {
394
+ if (!fs.existsSync(CONVERSATIONS_DIR)) fs.mkdirSync(CONVERSATIONS_DIR, { recursive: true });
395
+ fs.writeFileSync(path.join(CONVERSATIONS_DIR, `${threadId}.json`),
396
+ JSON.stringify({ llm, conversationId, history: messages, updatedAt: Date.now() }, null, 1));
397
+ }
398
+
399
+ function anthropicError(res, status, type, message) {
400
+ return res.status(status).json({ type: 'error', error: { type, message } });
401
+ }
402
+
403
+ // ============================================
404
+ // HTTP: Anthropic Messages API
405
+ // ============================================
406
+
407
+ const app = express();
408
+ app.use(bodyParser.json({ limit: '50mb' }));
409
+
410
+ app.post('/v1/messages', async (req, res) => {
411
+ const { model, messages = [], system, stream, metadata, tools = [], max_tokens: maxTokens, output_config: outputConfig } = req.body;
412
+ const launchModel = req.get('x-labs-model');
413
+ // Claude Code answers repeated errors by falling back opus -> sonnet -> haiku on its own; on the main thread
414
+ // (tools present) a Claude id therefore means "fallback", so stay on the model the user launched with.
415
+ const isClaudeFallback = /^claude-/.test(model || '') && (req.body.tools || []).length > 0 && Boolean(launchModel);
416
+ const llm = resolveLlm(isClaudeFallback ? launchModel : model, launchModel, aliases, llmIds);
417
+ console.log(`\n🤖 ${model} -> ${llm || 'UNKNOWN'} | ${messages.length} messages | ${tools.length} tools`);
418
+ if (!llm) return anthropicError(res, 400, 'invalid_request_error', `Unknown model "${model}". Run "labs models" to list models.`);
419
+
420
+ try {
421
+ const latest = extractLatestUserContent(messages);
422
+ if (!latest.text && latest.toolResults.length === 0 && latest.images.length === 0) {
423
+ return anthropicError(res, 400, 'invalid_request_error', 'No text or tool result in the latest user message');
424
+ }
425
+
426
+ // Claude Code's side calls (titles, summaries) carry no tools; keep them out of the coding conversation.
427
+ const isSideRequest = tools.length === 0;
428
+ const sessionId = req.get('x-labs-session-id') || metadata?.session_id || `side_${Date.now()}`;
429
+ const threadId = isValidSessionId(sessionId) ? createThreadId(sessionId, messages) : createThreadId('anon', messages);
430
+ const toolIds = isSideRequest ? [] : await toolRegistry.ensure(tools.filter(isForwardedTool));
431
+ const toolSetHash = createHash('sha1').update(toolIds.join(',')).digest('hex').slice(0, 8);
432
+ let conn;
433
+ let result;
434
+ for (;;) {
435
+ const settings = agentSettingsFor(llm, outputConfig?.effort || 'high', maxTokens);
436
+ const key = isSideRequest
437
+ ? `side_${Date.now()}_${Math.random().toString(36).slice(2)}`
438
+ : `${llm}:${settings.reasoning_effort}:${threadId}:${toolSetHash}`;
439
+ const existing = connections.get(key);
440
+ conn = existing && existing.ws.readyState === WebSocket.OPEN
441
+ ? existing
442
+ : await withAgentSettings(settings, () => openConversation(key, { llm, prompt: `${systemText(system) || 'You are a helpful assistant.'}${BRIDGE_NOTE}`, toolIds }));
443
+ try {
444
+ result = await sendTurn(conn, { text: latest.text, toolResults: latest.toolResults, images: latest.images, history: messages.slice(0, -1) });
445
+ break;
446
+ } catch (error) {
447
+ if (!/Cascade Error: TimeoutError|took too long/.test(error.message) || !lowerEffortCap(llm, settings.reasoning_effort)) throw error;
448
+ console.log(`🎚️ ${llm} too slow at effort=${settings.reasoning_effort}; retrying at ${effortCaps.get(llm)}`);
449
+ }
450
+ }
451
+
452
+ // Claude Code decides when to auto-compact from input_tokens, so report the whole request, not just the last turn.
453
+ // Base64 images and documents are thousands of characters but roughly 1.5k tokens each to a model; counting
454
+ // their raw length made Claude Code believe the window was full and compact after every prompt.
455
+ const IMAGE_TOKENS_AS_CHARS = 6000;
456
+ const withoutBinary = JSON.stringify(messages, (field, value) =>
457
+ field === 'data' && typeof value === 'string' && value.length > IMAGE_TOKENS_AS_CHARS ? 'x'.repeat(IMAGE_TOKENS_AS_CHARS) : value);
458
+ const requestChars = JSON.stringify(system || '').length + withoutBinary.length + JSON.stringify(tools.filter(isForwardedTool)).length;
459
+ const message = createAnthropicMessage({
460
+ model,
461
+ text: result.text || '',
462
+ toolCalls: result.toolCalls || [],
463
+ inputTokens: conn.contextTokens || Math.ceil(requestChars / 4)
464
+ });
465
+
466
+ if (isSideRequest) conn.ws.close();
467
+ else saveConversation(threadId, llm, conn.conversationId, [...messages, { role: 'assistant', content: message.content }]);
468
+
469
+ return stream ? writeAnthropicEvents(res, createAnthropicEvents(message)) : res.json(message);
470
+ } catch (error) {
471
+ console.error(`🚨 ${llm}: ${error.message}`);
472
+ // 500, not 529: Claude Code retries a 500 on the same model, but answers repeated 529s by switching models.
473
+ if (!res.headersSent) return anthropicError(res, 500, 'api_error', `ElevenLabs ${llm}: ${error.message}`);
474
+ }
475
+ });
476
+
477
+ app.get('/health', (req, res) => res.json({ name: 'labs-claude', version: VERSION }));
478
+
479
+ app.post('/shutdown', (req, res) => {
480
+ res.json({ ok: true });
481
+ setTimeout(() => process.exit(0), 100);
482
+ });
483
+
484
+ app.get('/v1/models', (req, res) => {
485
+ res.json({ data: Object.entries(aliases).map(([id, llm]) => ({ id, type: 'model', display_name: `${id} (${llm})` })) });
486
+ });
487
+
488
+ app.get('/v1/sessions', (req, res) => {
489
+ if (!fs.existsSync(CONVERSATIONS_DIR)) return res.json({ sessions: [] });
490
+ const sessions = fs.readdirSync(CONVERSATIONS_DIR).filter(file => file.endsWith('.json')).map(file => {
491
+ const data = JSON.parse(fs.readFileSync(path.join(CONVERSATIONS_DIR, file), 'utf8'));
492
+ return { id: file.replace('.json', ''), llm: data.llm || data.agentId, messageCount: (data.history || []).length, updatedAt: data.updatedAt };
493
+ });
494
+ res.json({ sessions: sessions.sort((a, b) => b.updatedAt - a.updatedAt) });
495
+ });
496
+
497
+ app.delete('/v1/sessions/:sessionId', (req, res) => {
498
+ const { sessionId } = req.params;
499
+ if (!isValidSessionId(sessionId)) return res.status(400).json({ error: 'Invalid session ID' });
500
+ const filePath = path.join(CONVERSATIONS_DIR, `${sessionId}.json`);
501
+ if (!fs.existsSync(filePath)) return res.status(404).json({ error: 'Session not found' });
502
+ fs.unlinkSync(filePath);
503
+ res.json({ success: true });
504
+ });
505
+
506
+ process.on('uncaughtException', error => console.error(`💥 Uncaught: ${error.stack}`));
507
+ process.on('unhandledRejection', error => console.error(`💥 Unhandled rejection: ${error?.stack || error}`));
508
+
509
+ process.on('SIGINT', () => {
510
+ connections.forEach(conn => conn.ws.close());
511
+ process.exit(0);
512
+ });
513
+
514
+ app.listen(PORT, '127.0.0.1', () => {
515
+ console.log(`✅ Proxy LIVE at http://localhost:${PORT} | bridge agent ${config.bridgeAgent}`);
516
+ refreshLlmList();
517
+ });
package/src/setup.js CHANGED
@@ -46,7 +46,7 @@ async function createBridgeAgent(headers) {
46
46
  backup_llm_config: { preference: 'disabled' }
47
47
  }
48
48
  },
49
- conversation: { text_only: true, max_duration_seconds: 7200 }
49
+ conversation: { text_only: true, max_duration_seconds: 7200, file_input: { enabled: true } }
50
50
  },
51
51
  platform_settings: {
52
52
  // Post-conversation analysis adds nothing for a coding bridge.