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