labs-claude 0.1.5 → 0.1.7

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,12 +1,28 @@
1
1
  {
2
2
  "name": "labs-claude",
3
- "version": "0.1.5",
3
+ "version": "0.1.7",
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
- "bin": { "labs": "bin/labs.js" },
6
- "files": ["bin", "src", "README.md"],
7
- "scripts": { "test": "node --test" },
8
- "engines": { "node": ">=18" },
9
- "keywords": ["claude-code", "elevenlabs", "proxy", "anthropic", "cli"],
5
+ "bin": {
6
+ "labs": "bin/labs.js"
7
+ },
8
+ "files": [
9
+ "bin",
10
+ "src",
11
+ "README.md"
12
+ ],
13
+ "scripts": {
14
+ "test": "node --test"
15
+ },
16
+ "engines": {
17
+ "node": ">=18"
18
+ },
19
+ "keywords": [
20
+ "claude-code",
21
+ "elevenlabs",
22
+ "proxy",
23
+ "anthropic",
24
+ "cli"
25
+ ],
10
26
  "license": "MIT",
11
27
  "dependencies": {
12
28
  "axios": "^1.20.0",
@@ -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
@@ -11,6 +11,7 @@ const {
11
11
  createAnthropicMessage,
12
12
  createThreadId,
13
13
  extractLatestUserContent,
14
+ replySignature,
14
15
  formatConversationHistory,
15
16
  isValidSessionId,
16
17
  resolveLlm,
@@ -187,13 +188,16 @@ function openConversation(key, { llm, prompt, toolIds }) {
187
188
  ws.on('error', error => {
188
189
  console.error(`🚨 WS error for ${key}: ${error.message}`);
189
190
  reject(error);
191
+ if (conn.pending) settle(conn, { error });
192
+ if (connections.get(key) === conn) connections.delete(key);
193
+ ws.terminate();
190
194
  });
191
195
  ws.on('close', (code, reason) => {
192
196
  conn.closeReason = `code ${code}${reason?.length ? `: ${reason}` : ''}`;
193
197
  console.log(`🔌 Conversation closed for ${key} (${conn.closeReason})`);
194
198
  reject(new Error(`ElevenLabs closed the conversation (${conn.closeReason})`));
195
199
  if (conn.pending) settle(conn, { error: new Error(`ElevenLabs closed the conversation (${conn.closeReason})`) });
196
- connections.delete(key);
200
+ if (connections.get(key) === conn) connections.delete(key);
197
201
  });
198
202
  });
199
203
  conn.ready.catch(() => {});
@@ -368,56 +372,78 @@ function sendTurn(conn, { text, toolResults, history, images = [] }) {
368
372
  if (conn.pending) throw new Error('A request is already active for this conversation');
369
373
  const requestId = String(++conn.messageId);
370
374
 
371
- return new Promise(async (resolve, reject) => {
372
- conn.pending = { resolve, reject, text: '', toolCalls: [], settleTimer: null };
373
- let fileIds = [];
374
- try {
375
- fileIds = images.length ? await uploadImages(conn, images) : [];
376
- } catch (error) {
377
- settle(conn, { error });
378
- return;
379
- }
380
- conn.pending.timeout = setTimeout(
381
- () => settle(conn, { error: new Error(`No reply from ${conn.llm} within ${REQUEST_TIMEOUT_MS / 1000}s`) }),
382
- REQUEST_TIMEOUT_MS
383
- );
384
-
385
- // Claude Code resends the whole thread every turn, so a fresh conversation (reconnect, /model switch,
386
- // --resume, compaction) is seeded from what Claude Code sent.
387
- if (conn.messageId === 1 && history.length) {
388
- conn.ws.send(JSON.stringify({
389
- type: 'contextual_update',
390
- text: `Conversation so far:\n${formatConversationHistory(history).slice(-MAX_REPLAY_CHARS)}`
391
- }));
392
- }
393
-
394
- const known = toolResults.filter(result => conn.openToolCallIds.has(result.toolUseId));
395
- if (toolResults.length && known.length === toolResults.length) {
396
- for (const result of toolResults) {
397
- conn.openToolCallIds.delete(result.toolUseId);
375
+ return new Promise((resolve, reject) => {
376
+ const pending = { resolve, reject, text: '', toolCalls: [], settleTimer: null };
377
+ conn.pending = pending;
378
+ pending.timeout = setTimeout(() => {
379
+ if (conn.pending !== pending) return;
380
+ settle(conn, { error: new Error(`No reply from ${conn.llm} within ${REQUEST_TIMEOUT_MS / 1000}s`) });
381
+ conn.ws.terminate();
382
+ }, REQUEST_TIMEOUT_MS);
383
+ const send = async () => {
384
+ if (conn.ws.readyState !== WebSocket.OPEN) throw new Error('Conversation socket is not open');
385
+ const fileIds = images.length ? await uploadImages(conn, images) : [];
386
+ // A close or timeout can settle this turn while the upload is in flight.
387
+ if (conn.pending !== pending) return;
388
+ if (conn.ws.readyState !== WebSocket.OPEN) throw new Error('Conversation socket is not open');
389
+
390
+ // Claude Code resends the whole thread every turn, so a fresh conversation (reconnect, /model switch,
391
+ // --resume, compaction) is seeded from what Claude Code sent.
392
+ if (conn.messageId === 1 && history.length) {
398
393
  conn.ws.send(JSON.stringify({
399
- type: 'client_tool_result',
400
- tool_call_id: result.toolUseId,
401
- result: fileIds.length ? `${result.content}\n[The image output of this tool follows in the next message.]` : result.content,
402
- is_error: result.isError
394
+ type: 'contextual_update',
395
+ text: `Conversation so far:\n${formatConversationHistory(history).slice(-MAX_REPLAY_CHARS)}`
403
396
  }));
404
397
  }
405
- if (text) conn.ws.send(JSON.stringify({ type: 'contextual_update', text }));
406
- if (fileIds.length) sendMultimodal(conn, 'Image output of the tool call above.', fileIds);
407
- return;
408
- }
409
398
 
410
- // Results for calls this conversation never made (it was reopened) go in as text, otherwise the agent
411
- // waits on tool_call_ids it does not know and never answers.
412
- const resultText = toolResults
413
- .map(result => `${result.isError ? 'Tool error' : 'Tool result'} (${result.toolUseId}):\n${result.content}`)
414
- .join('\n\n');
415
- const turnText = [resultText, text, resultText ? 'Continue the task from here.' : ''].filter(Boolean).join('\n\n');
416
- if (fileIds.length) sendMultimodal(conn, turnText || 'See the attached image.', fileIds);
417
- else conn.ws.send(JSON.stringify({ type: 'user_message', id: requestId, text: turnText }));
399
+ const known = toolResults.filter(result => conn.openToolCallIds.has(result.toolUseId));
400
+ if (toolResults.length && known.length === toolResults.length) {
401
+ for (const result of toolResults) {
402
+ conn.openToolCallIds.delete(result.toolUseId);
403
+ conn.ws.send(JSON.stringify({
404
+ type: 'client_tool_result',
405
+ tool_call_id: result.toolUseId,
406
+ result: fileIds.length ? `${result.content}\n[The image output of this tool follows in the next message.]` : result.content,
407
+ is_error: result.isError
408
+ }));
409
+ }
410
+ if (text) conn.ws.send(JSON.stringify({ type: 'contextual_update', text }));
411
+ if (fileIds.length) sendMultimodal(conn, 'Image output of the tool call above.', fileIds);
412
+ return;
413
+ }
414
+
415
+ // Results for calls this conversation never made (it was reopened) go in as text, otherwise the agent
416
+ // waits on tool_call_ids it does not know and never answers.
417
+ const resultText = toolResults
418
+ .map(result => `${result.isError ? 'Tool error' : 'Tool result'} (${result.toolUseId}):\n${result.content}`)
419
+ .join('\n\n');
420
+ const turnText = [resultText, text, resultText ? 'Continue the task from here.' : ''].filter(Boolean).join('\n\n');
421
+ if (fileIds.length) sendMultimodal(conn, turnText || 'See the attached image.', fileIds);
422
+ else conn.ws.send(JSON.stringify({ type: 'user_message', id: requestId, text: turnText }));
423
+ };
424
+ send().catch(error => {
425
+ if (conn.pending === pending) settle(conn, { error });
426
+ });
418
427
  });
419
428
  }
420
429
 
430
+ // Forks and parallel subagents share the main thread's history, so a key built from that history put them all on one
431
+ // ElevenLabs conversation ("A request is already active"). A request now continues only the free conversation whose
432
+ // last reply is the one the request ends with; anything else gets its own conversation, seeded from its history.
433
+ let conversationCounter = 0;
434
+
435
+ function claimContinuingConversation(prefix, priorReply) {
436
+ if (!priorReply) return null;
437
+ for (const [key, candidate] of connections) {
438
+ if (key.startsWith(prefix) && candidate.lastReply === priorReply && !candidate.claimed && !candidate.pending
439
+ && candidate.ws.readyState === WebSocket.OPEN) {
440
+ candidate.claimed = true;
441
+ return candidate;
442
+ }
443
+ }
444
+ return null;
445
+ }
446
+
421
447
  function saveConversation(threadId, llm, conversationId, messages) {
422
448
  if (!fs.existsSync(CONVERSATIONS_DIR)) fs.mkdirSync(CONVERSATIONS_DIR, { recursive: true });
423
449
  fs.writeFileSync(path.join(CONVERSATIONS_DIR, `${threadId}.json`),
@@ -457,17 +483,21 @@ app.post('/v1/messages', async (req, res) => {
457
483
  const threadId = isValidSessionId(sessionId) ? createThreadId(sessionId, messages) : createThreadId('anon', messages);
458
484
  const toolIds = isSideRequest ? [] : await toolRegistry.ensure(tools.filter(isForwardedTool));
459
485
  const toolSetHash = createHash('sha1').update(toolIds.join(',')).digest('hex').slice(0, 8);
486
+ const prior = messages[messages.length - 2];
487
+ const priorReply = prior?.role === 'assistant' ? replySignature(prior.content) : null;
460
488
  let conn;
461
489
  let result;
462
490
  for (;;) {
463
491
  const settings = agentSettingsFor(llm, outputConfig?.effort || 'high', maxTokens);
464
- const key = isSideRequest
465
- ? `side_${Date.now()}_${Math.random().toString(36).slice(2)}`
466
- : `${llm}:${settings.reasoning_effort}:${threadId}:${toolSetHash}`;
467
- const existing = connections.get(key);
468
- conn = existing && existing.ws.readyState === WebSocket.OPEN
469
- ? existing
470
- : await withAgentSettings(settings, () => openConversation(key, { llm, prompt: `${systemText(system) || 'You are a helpful assistant.'}${BRIDGE_NOTE}`, toolIds }));
492
+ const prefix = `${llm}:${settings.reasoning_effort}:${toolSetHash}:`;
493
+ conn = isSideRequest ? null : claimContinuingConversation(prefix, priorReply);
494
+ if (!conn) {
495
+ const key = isSideRequest
496
+ ? `side_${Date.now()}_${Math.random().toString(36).slice(2)}`
497
+ : `${prefix}${threadId}:${++conversationCounter}`;
498
+ conn = await withAgentSettings(settings, () => openConversation(key, { llm, prompt: `${systemText(system) || 'You are a helpful assistant.'}${BRIDGE_NOTE}`, toolIds }));
499
+ conn.claimed = true;
500
+ }
471
501
  // Past the 10-file limit the main conversation stays put: a side conversation looks at the new images and
472
502
  // its description enters the same chat as text, so no context is lost to a fresh conversation.
473
503
  if (latest.images.length && conn.filesUploaded + latest.images.length > MAX_FILES_PER_CONVERSATION) {
@@ -477,8 +507,10 @@ app.post('/v1/messages', async (req, res) => {
477
507
  }
478
508
  try {
479
509
  result = await sendTurn(conn, { text: latest.text, toolResults: latest.toolResults, images: latest.images, history: messages.slice(0, -1) });
510
+ conn.claimed = false;
480
511
  break;
481
512
  } catch (error) {
513
+ conn.claimed = false;
482
514
  if (!/Cascade Error: TimeoutError|took too long/.test(error.message) || !lowerEffortCap(llm, settings.reasoning_effort)) throw error;
483
515
  console.log(`🎚️ ${llm} too slow at effort=${settings.reasoning_effort}; retrying at ${effortCaps.get(llm)}`);
484
516
  }
@@ -498,6 +530,7 @@ app.post('/v1/messages', async (req, res) => {
498
530
  inputTokens: conn.contextTokens || Math.ceil(requestChars / 4)
499
531
  });
500
532
 
533
+ conn.lastReply = replySignature(message.content);
501
534
  if (isSideRequest) conn.ws.close();
502
535
  else saveConversation(threadId, llm, conn.conversationId, [...messages, { role: 'assistant', content: message.content }]);
503
536